diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000000..c68a6f2a6ab --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "third_party/jaffarCommon"] + path = third_party/jaffarCommon + url = https://github.com/SergioMartin86/jaffarCommon.git diff --git a/config.h b/config.h new file mode 100644 index 00000000000..68f396241e9 --- /dev/null +++ b/config.h @@ -0,0 +1,386 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + + +/* + * Copyright (C) 2002-2021 The DOSBox Team + * + * 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 2 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 Library 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. + */ + + +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ + +/* Compiling on BSD */ +/* #undef BSD */ + +/* Determines if the compilers supports always_inline attribute. */ +/* #undef C_ATTRIBUTE_ALWAYS_INLINE */ + +/* Determines if the compilers supports fastcall attribute. */ +/* #undef C_ATTRIBUTE_FASTCALL */ + +/* Define to 1 to use FFMPEG libavcodec for video capture */ +/* #undef C_AVCODEC */ + +/* Define to 1 to use Direct3D shaders */ +/* #undef C_D3DSHADERS */ + +/* Define to 1 to enable internal debugger, requires libcurses */ +/* #undef C_DEBUG */ + +/* Define to 1 to enable Direct3D 9 display output support */ +/* #undef C_DIRECT3D */ + +/* Define to 1 if you want parallel pass-through support (Win32, Linux and + BSD). */ +#define C_DIRECTLPT 1 + +/* Define to 1 if you want serial pass-through support (Win32, Posix and + OS/2). */ +#define C_DIRECTSERIAL 1 + +/* Define to 1 to use x86/x64 dynamic cpu core */ +#define C_DYNAMIC_X86 1 + +/* Define to 1 to use recompiling cpu core */ +#define C_DYNREC 1 + +/* Targeting Emscripten */ +/* #undef C_EMSCRIPTEN */ + +/* Define to 1 to enable libfluidsynth MIDI synthesis */ +#define C_FLUIDSYNTH 0 + +/* Force SDL drawn menus */ +/* #undef C_FORCE_MENU_SDLDRAW */ + +/* Define to 1 to enable floating point emulation */ +#define C_FPU 1 + +/* Define to 1 to use a x86/x64 assembly fpu core */ +#define C_FPU_X86 1 + +/* Define to 1 to enable freetype support */ +/* #undef C_FREETYPE */ + +/* Define to 1 to enable game link headless mode */ +#define C_GAMELINK 1 + +/* Determines if the compilers supports attributes for structures. */ +#define C_HAS_ATTRIBUTE 1 + +/* Determines if the compilers supports __builtin_expect for branch + prediction. */ +/* #undef C_HAS_BUILTIN_EXPECT */ + +/* Define to 1 if you have linux/kvm.h and KVM virtualization */ +#define C_HAVE_LINUX_KVM 1 + +/* Define to 1 if you have the mach_vm_remap function */ +/* #undef C_HAVE_MACH_VM_REMAP */ + +/* Define to 1 if you have the memfd_create function */ +#define C_HAVE_MEMFD_CREATE 1 + +/* Define to 1 if you have the mmap function */ +#define C_HAVE_MMAP 1 + +/* Define to 1 if you have the mprotect function */ +#define C_HAVE_MPROTECT 1 + +/* Define to 1 if you have the posix_memalign function */ +/* #undef C_HAVE_POSIX_MEMALIGN */ + +/* Define to 1 to enable heavy debugging, also have to enable C_DEBUG */ +/* #undef C_HEAVY_DEBUG */ + +/* Targeting HX DOS extender */ +/* #undef C_HX_DOS */ + +/* Define to 1 to use iconv */ +#define C_ICONV 1 + +/* Define to 1 to use Win32 functions in iconv backend */ +/* #undef C_ICONV_WIN32 */ + +/* Define to 1 to enable IPX over Internet networking, requires SDL_net */ +/* #undef C_IPX */ + +/* Define to 1 if you have libpng */ +/* #undef C_LIBPNG */ + +/* Define to 1 if you have libz */ +/* #undef C_LIBZ */ + +/* Define to 1 to enable internal modem support, requires SDL_net */ +/* #undef C_MODEM */ + +/* Define to 1 to enable MT32 emulation */ +#define C_MT32 1 + +/* Define to 1 to use opengl display output support */ +/* #undef C_OPENGL */ + +/* Define to 1 to enable ethernet pass-through, requires libpcap */ +/* #undef C_PCAP */ + +/* Define to 1 to enable printer emulation */ +/* #undef C_PRINTER */ + +/* Define to 1 to alter the simpler render scalers to operate only on the full + scanline instead of detecting differences. This is a performance adjustment + for slow or embedded systems */ +/* #undef C_SCALER_FULL_LINE */ + +/* Set to 1 to enable SDL 1.x support */ +/* #undef C_SDL1 */ + +/* Set to 1 to enable SDL 2.x support */ +#define C_SDL2 1 + +/* Indicate whether SDL_net is present */ +/* #undef C_SDL_NET */ + +/* Define to 1 if you have setpriority support */ +/* #undef C_SET_PRIORITY */ + +/* Define to 1 to enable userspace TCP/IP emulation, requires libslirp */ +/* #undef C_SLIRP */ + +/* Define to 1 to enable screenshots, requires libpng */ +/* #undef C_SSHOT */ + +/* The type of cpu this target has */ +#define C_TARGETCPU X86_64 + +/* Define to 1 to use a unaligned memory access */ +#define C_UNALIGNED_MEMORY 1 + +/* define to 1 to enable X11 support */ +/* #define C_X11 */ + +/* define to 1 if XKBrules.h is present */ +/* #undef C_X11_EXT_XKBRULES */ + +/* define to 1 if you have XKBlib.h and X11 lib */ +/* #undef C_X11_XKB */ + +/* define to 1 if XKBfile.h is present */ +/* #undef C_X11_XKBFILE */ + +/* define to 1 if you have XRandr.h and X11 lib */ +/* #undef C_X11_XRANDR */ + +/* Define to 1 to enable XBRZ scaler */ +/* #undef C_XBRZ */ + +/* Determines if the function clock_gettime is available. */ +#define DB_HAVE_CLOCK_GETTIME 1 + +/* libm does not include powf */ +/* #undef DB_HAVE_NO_POWF */ + +/* struct dirent has d_type */ +#define DIRENT_HAS_D_TYPE 1 + +/* environ can be included */ +/* #undef ENVIRON_INCLUDED */ + +/* environ can be linked */ +#define ENVIRON_LINKED 1 + +/* Compiling on Haiku */ +/* #undef HAIKU */ + +/* Define to 1 to use ALSA for MIDI */ +/* #undef HAVE_ALSA */ + +/* Define to 1 to use Direct3D 9 display output support */ +/* #undef HAVE_D3D9_H */ + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `asound' library (-lasound). */ +#define HAVE_LIBASOUND 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_NETINET_IN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_PWD_H 1 + +/* Define to 1 if you have the `realpath' function. */ +#define HAVE_REALPATH 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDIO_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SOCKET_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Whether iconv uses const char** */ +/* #undef ICONV_CONST_CHAR */ + +/* Compiling on GNU/Linux */ +#define LINUX 1 + +/* Compiling on Mac OS X */ +/* #undef MACOSX */ + +/* Compiling on OS/2 EMX */ +/* #undef OS2 */ + +/* Name of package */ +#define PACKAGE "dosbox-x" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "https://github.com/joncampbell123/dosbox-x/issues" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "dosbox-x" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "dosbox-x 2025.02.01" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "dosbox-x" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "https://dosbox-x.com" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "2025.02.01" + +/* Compiling on RISC OS */ +/* #undef RISCOS */ + +/* Define to 1 if all of the C90 standard headers exist (not just the ones + required in a freestanding environment). This macro is provided for + backward compatibility; new code need not use it. */ +#define STDC_HEADERS 1 + +/* Define to 1 if your declares `struct tm'. */ +/* #undef TM_IN_SYS_TIME */ + +/* Version number of package */ +#define VERSION "2025.02.01" + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +/* # undef WORDS_BIGENDIAN */ +# endif +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +/* #undef _FILE_OFFSET_BITS */ + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to `__inline__' or `__inline' if that's what the C compiler + calls it, or to nothing if 'inline' is not supported under any name. */ +#ifndef __cplusplus +/* #undef inline */ +#endif + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ + +#if C_ATTRIBUTE_ALWAYS_INLINE +#define INLINE inline __attribute__((always_inline)) +#else +#define INLINE inline +#endif + +#if C_ATTRIBUTE_FASTCALL +#define DB_FASTCALL __attribute__((fastcall)) +#else +#define DB_FASTCALL +#endif + +#if C_HAS_ATTRIBUTE +#define GCC_ATTRIBUTE(x) __attribute__ ((x)) +#else +#define GCC_ATTRIBUTE(x) /* attribute not supported */ +#endif + +#if C_HAS_BUILTIN_EXPECT +#define GCC_UNLIKELY(x) __builtin_expect((x),0) +#define GCC_LIKELY(x) __builtin_expect((x),1) +#else +#define GCC_UNLIKELY(x) (x) +#define GCC_LIKELY(x) (x) +#endif + + +#if !defined(FLUIDINC) +#include + +typedef uintptr_t Bitu; +typedef intptr_t Bits; +#endif + + +/* + Define HAS_CDIRECTLPT as 1 if C_DIRECTLPT is defined (as 1) *and* parallel + pass-through is available on the current platform. It is only available on + x86{_64} with Windows or BSD, and on Linux. + We cannot override the value of C_DIRECTLPT, because configure will replace + "#undef C_DIRECTLPT" or "#define C_DIRECTLPT 0" with "#define C_DIRECTLPT 1". +*/ +#ifdef C_DIRECTLPT +#if ((defined __i386__ || defined __x86_64__ || defined _M_IX86 || defined _M_X64) && \ + (defined WIN32 || defined BSD || defined __CYGWIN__)) || \ + /* WIN32 is not defined by default on Cygwin */ \ + defined LINUX /* Linux, including non-x86 (e.g. Raspberry Pi) */ +#define HAS_CDIRECTLPT 1 +#endif +#endif // C_DIRECTLPT +#ifndef HAS_CDIRECTLPT +#define HAS_CDIRECTLPT 0 +#endif diff --git a/include/bios_disk.h b/include/bios_disk.h index d5cf260507f..8b28caacacc 100644 --- a/include/bios_disk.h +++ b/include/bios_disk.h @@ -22,6 +22,7 @@ #include "dos_inc.h" #include "logging.h" #include "../src/dos/cdrom.h" +#include "memfile.h" /* The Section handling Bios Disk Access */ #define BIOS_MAX_DISK 10 @@ -99,8 +100,10 @@ class imageDisk { imageDisk(class DOS_Drive *useDrive, unsigned int letter, uint32_t freeMB, int timeout); imageDisk(FILE *imgFile, const char *imgName, uint32_t imgSizeK, bool isHardDisk); imageDisk(FILE* diskimg, const char* diskName, uint32_t cylinders, uint32_t heads, uint32_t sectors, uint32_t sector_size, bool hardDrive); + + imageDisk() = default; virtual ~imageDisk(); - void Set_GeometryForHardDisk(); + virtual void Set_GeometryForHardDisk(); struct fatFromDOSDrive* ffdd = NULL; unsigned int drvnum = DOS_DRIVES; @@ -113,13 +116,13 @@ class imageDisk { uint32_t sectors = 0; bool hardDrive = false; uint64_t diskSizeK = 0; - FILE* diskimg = NULL; bool diskChangeFlag = false; /* this is intended only for when the disk can change out from under us while mounted */ virtual bool detectDiskChange(void) { const bool r = diskChangeFlag; diskChangeFlag = false; return r; } protected: + FILE* diskimg = NULL; imageDisk(IMAGE_TYPE class_id); uint8_t floppytype = 0; @@ -127,7 +130,7 @@ class imageDisk { uint64_t image_base = 0; uint64_t image_length = 0; - private: + protected: volatile int refcount = 0; std::vector partition_in_use; /* used by FAT driver to prevent mounting a partition twice */ uint64_t current_fpos = 0; @@ -165,6 +168,16 @@ class imageDisk { } }; +class imageDisk_Mem : public imageDisk { + public: + uint8_t Read_AbsoluteSector(uint32_t sectnum, void * data) override; + uint8_t Write_AbsoluteSector(uint32_t sectnum, const void * data) override; + imageDisk_Mem(jaffarCommon::file::MemoryFile* memfile, const char *imgName, uint32_t imgSizeK, bool isHardDisk) ; + ~imageDisk_Mem(); + void Set_GeometryForHardDisk() override; + jaffarCommon::file::MemoryFile* _memfile; +}; + class imageDiskEmptyDrive : public imageDisk { public: uint8_t Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size=0) override; @@ -299,7 +312,7 @@ class imageDiskMemory : public imageDisk { imageDiskMemory(imageDisk* underlyingImage); virtual ~imageDiskMemory(); -private: +protected: void init(diskGeo diskParams, bool isHardDrive, imageDisk* underlyingImage); bool CalculateFAT(uint32_t partitionStartingSector, uint32_t partitionLength, bool isHardDrive, uint32_t rootEntries, uint32_t* rootSectors, uint32_t* sectorsPerCluster, bool* isFat16, uint32_t* fatSectors, uint32_t* reservedSectors); @@ -399,7 +412,7 @@ class imageDiskVHD : public imageDisk { static void mk_uuid(uint8_t* buf); virtual ~imageDiskVHD(); -private: +protected: struct ParentLocatorEntry { uint32_t platformCode; uint32_t platformDataSpace; @@ -627,4 +640,6 @@ class imageDiskINT13Drive : public imageDisk { bool busy = false; }; + + #endif diff --git a/include/dosbox.h b/include/dosbox.h index 1b129988dd5..7dae1ddfab5 100644 --- a/include/dosbox.h +++ b/include/dosbox.h @@ -399,12 +399,12 @@ class SerializeGlobalPOD : public SaveState::Component protected: void getBytes(std::ostream& stream) override { - std::for_each(podRef.begin(), podRef.end(), std::bind1st(WriteGlobalPOD(), &stream)); + // std::for_each(podRef.begin(), podRef.end(), std::bind(WriteGlobalPOD(), &stream)); } void setBytes(std::istream& stream) override { - std::for_each(podRef.begin(), podRef.end(), std::bind1st(ReadGlobalPOD(), &stream)); + // std::for_each(podRef.begin(), podRef.end(), std::bind(ReadGlobalPOD(), &stream)); } private: @@ -416,21 +416,21 @@ class SerializeGlobalPOD : public SaveState::Component size_t size; }; - struct WriteGlobalPOD : public std::binary_function - { - void operator()(std::ostream* stream, const POD& data) const - { - stream->write(static_cast(data.address), data.size); - } - }; - - struct ReadGlobalPOD : public std::binary_function - { - void operator()(std::istream* stream, const POD& data) const - { - stream->read(static_cast(data.address), data.size); - } - }; + // struct WriteGlobalPOD : public std::__binary_function + // { + // void operator()(std::ostream* stream, const POD& data) const + // { + // stream->write(static_cast(data.address), data.size); + // } + // }; + + // struct ReadGlobalPOD : public std::__binary_function + // { + // void operator()(std::istream* stream, const POD& data) const + // { + // stream->read(static_cast(data.address), data.size); + // } + // }; std::vector podRef; }; diff --git a/include/ioapi.h b/include/ioapi.h index 0bc6904ffd1..a743301728b 100644 --- a/include/ioapi.h +++ b/include/ioapi.h @@ -42,7 +42,7 @@ #include #include -#include "zlib.h" +// #include "zlib.h" #if defined(__APPLE__) || defined(USE_FILE32API) #define fopen64 fopen diff --git a/include/joystick.h b/include/joystick.h index e39ca42c2f0..ed6fcdaec2e 100644 --- a/include/joystick.h +++ b/include/joystick.h @@ -16,34 +16,45 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -#ifndef DOSBOX_JOYSTICK_H -#define DOSBOX_JOYSTICK_H -void JOYSTICK_Enable(Bitu which,bool enabled); - -void JOYSTICK_Button(Bitu which,Bitu num,bool pressed); - -void JOYSTICK_Move_X(Bitu which,float x); - -void JOYSTICK_Move_Y(Bitu which,float y); - -bool JOYSTICK_IsEnabled(Bitu which); - -bool JOYSTICK_GetButton(Bitu which, Bitu num); - -float JOYSTICK_GetMove_X(Bitu which); - -float JOYSTICK_GetMove_Y(Bitu which); - -enum JoystickType { - JOY_NONE, - JOY_AUTO, - JOY_2AXIS, - JOY_4AXIS, - JOY_4AXIS_2, - JOY_FCS, - JOY_CH -}; - -extern JoystickType joytype; -extern bool button_wrapping_enabled; -#endif + #ifndef DOSBOX_JOYSTICK_H + #define DOSBOX_JOYSTICK_H + void JOYSTICK_Enable(Bitu which,bool enabled); + + void JOYSTICK_Button(Bitu which,Bitu num,bool pressed); + + void JOYSTICK_Move_X(Bitu which,float x); + + void JOYSTICK_Move_Y(Bitu which,float y); + + bool JOYSTICK_IsEnabled(Bitu which); + + bool JOYSTICK_GetButton(Bitu which, Bitu num); + + float JOYSTICK_GetMove_X(Bitu which); + + float JOYSTICK_GetMove_Y(Bitu which); + + enum JoystickType { + JOY_NONE, + JOY_AUTO, + JOY_2AXIS, + JOY_4AXIS, + JOY_4AXIS_2, + JOY_FCS, + JOY_CH + }; + + extern JoystickType joytype; + extern bool button_wrapping_enabled; + + struct JoyStick { + bool enabled; + float xpos,ypos; + double xtick,ytick; + Bitu xcount,ycount; + bool button[2]; + }; + extern JoyStick stick[2]; + + #endif + \ No newline at end of file diff --git a/include/memfile.h b/include/memfile.h new file mode 100644 index 00000000000..be948bb281b --- /dev/null +++ b/include/memfile.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern jaffarCommon::file::MemoryFileDirectory _memFileDirectory; diff --git a/include/mixer.h b/include/mixer.h index 70c9ca3cb3d..a142a473860 100644 --- a/include/mixer.h +++ b/include/mixer.h @@ -17,135 +17,163 @@ */ -#ifndef DOSBOX_MIXER_H -#define DOSBOX_MIXER_H - -/* -#ifdef C_SDL2 -#define SDL_LockAudio __DO_NOT_USE__1 -#define SDL_UnlockAudio __DO_NOT_USE__2 -#define SDL_PauseAudio __DO_NOT_USE__3 -#define SDL_CloseAudio __DO_NOT_USE__4 -#define SDL_OpenAudio __DO_NOT_USE__5 -#endif -*/ - -typedef void (*MIXER_MixHandler)(uint8_t * sampdate,uint32_t len); -typedef void (*MIXER_Handler)(Bitu len); - -template T clamp(const T& n, const T& lower, const T& upper) { - return std::max(lower, std::min(n, upper)); -} - -#define MIXER_BUFSIZE (16*1024) -#define MIXER_BUFMASK (MIXER_BUFSIZE-1) -extern uint8_t MixTemp[MIXER_BUFSIZE]; - -#define MAX_AUDIO ((1<<(16-1))-1) -#define MIN_AUDIO -(1<<(16-1)) - -#define LOWPASS_ORDER 8 - -class MixerChannel { -public: - void SetVolume(float _left,float _right); - void SetScale( float f ); - void SetScale(float _left, float _right); - void UpdateVolume(void); - void SetLowpassFreq(Bitu _freq,unsigned int order=2); // _freq / 1 Hz. call with _freq == 0 to disable - void SetSlewFreq(Bitu _freq); // denominator provided by call to SetFreq. call with _freq == 0 to disable - void SetFreq(Bitu _freq,Bitu _den=1U); - void Mix(Bitu whole,Bitu frac); - void AddSilence(void); //Fill up until needed - void EndFrame(Bitu samples); - - void lowpassUpdate(); - int32_t lowpassStep(int32_t in,const unsigned int iteration,const unsigned int channel); - void lowpassProc(int32_t ch[2]); - - template - void loadCurrentSample(Bitu &len, const Type* &data); - - template - void AddSamples(Bitu len, const Type* data); - double timeSinceLastSample(void); - - bool runSampleInterpolation(const Bitu upto); - - void updateSlew(void); - void padFillSampleInterpolation(const Bitu upto); - void finishSampleInterpolation(const Bitu upto); - void AddSamples_m8(Bitu len, const uint8_t * data); - void AddSamples_s8(Bitu len, const uint8_t * data); - void AddSamples_m8s(Bitu len, const int8_t * data); - void AddSamples_s8s(Bitu len, const int8_t * data); - void AddSamples_m16(Bitu len, const int16_t * data); - void AddSamples_s16(Bitu len, const int16_t * data); - void AddSamples_m16u(Bitu len, const uint16_t * data); - void AddSamples_s16u(Bitu len, const uint16_t * data); - void AddSamples_m32(Bitu len, const int32_t * data); - void AddSamples_s32(Bitu len, const int32_t * data); - void AddSamples_m16_nonnative(Bitu len, const int16_t * data); - void AddSamples_s16_nonnative(Bitu len, const int16_t * data); - void AddSamples_m16u_nonnative(Bitu len, const uint16_t * data); - void AddSamples_s16u_nonnative(Bitu len, const uint16_t * data); - void AddSamples_m32_nonnative(Bitu len, const int32_t * data); - void AddSamples_s32_nonnative(Bitu len, const int32_t * data); - - void FillUp(void); - void Enable(bool _yesno); - void SaveState( std::ostream& stream ); - void LoadState( std::istream& stream ); - - MIXER_Handler handler; - float volmain[2]; - float scale[2]; - int32_t volmul[2]; - int32_t lowpass[LOWPASS_ORDER][2]; // lowpass filter - int32_t lowpass_alpha; // "alpha" multiplier for lowpass (16.16 fixed point) - Bitu lowpass_freq; - unsigned int lowpass_order; - bool lowpass_on_load; // apply lowpass on sample load (if source rate > mixer rate) - bool lowpass_on_out; // apply lowpass on rendered output (if source rate <= mixer rate) - unsigned int freq_f,freq_fslew; - unsigned int freq_nslew,freq_nslew_want; - unsigned int rendering_to_n,rendering_to_d; - unsigned int rend_n,rend_d; - unsigned int freq_n,freq_d,freq_d_orig; - bool current_loaded; - int32_t current[2],last[2],delta[2],max_change; - int32_t msbuffer[2048][2]; // more than enough for 1ms of audio, at mixer sample rate - Bits last_sample_write; - Bitu msbuffer_o; - Bitu msbuffer_i; - const char * name; - bool enabled; - MixerChannel * next; -}; - -void MIXER_SetMaster(float vol0,float vol1); - -MixerChannel * MIXER_AddChannel(MIXER_Handler handler,Bitu freq,const char * name); -MixerChannel * MIXER_FindChannel(const char * name); -/* Find the device you want to delete with findchannel "delchan gets deleted" */ -void MIXER_DelChannel(MixerChannel* delchan); - -/* Object to maintain a mixerchannel; As all objects it registers itself with create - * and removes itself when destroyed. */ -class MixerObject{ -private: - bool installed = false; - char m_name[32] = {}; -public: - MixerObject() {}; - MixerChannel* Install(MIXER_Handler handler,Bitu freq,const char * name); - ~MixerObject(); -}; - - -/* PC Speakers functions, tightly related to the timer functions */ -void PCSPEAKER_SetCounter(Bitu cntr,Bitu mode); -void PCSPEAKER_SetType(bool pit_clock_gate_enabled, bool pit_output_enabled); -void PCSPEAKER_SetPITControl(Bitu mode); - -#endif + #ifndef DOSBOX_MIXER_H + #define DOSBOX_MIXER_H + + /* + #ifdef C_SDL2 + #define SDL_LockAudio __DO_NOT_USE__1 + #define SDL_UnlockAudio __DO_NOT_USE__2 + #define SDL_PauseAudio __DO_NOT_USE__3 + #define SDL_CloseAudio __DO_NOT_USE__4 + #define SDL_OpenAudio __DO_NOT_USE__5 + #endif + */ + + typedef void (*MIXER_MixHandler)(uint8_t * sampdate,uint32_t len); + typedef void (*MIXER_Handler)(Bitu len); + + template T clamp(const T& n, const T& lower, const T& upper) { + return std::max(lower, std::min(n, upper)); + } + + #define MIXER_BUFSIZE (16*1024) + #define MIXER_BUFMASK (MIXER_BUFSIZE-1) + extern uint8_t MixTemp[MIXER_BUFSIZE]; + + #define MAX_AUDIO ((1<<(16-1))-1) + #define MIN_AUDIO -(1<<(16-1)) + + #define LOWPASS_ORDER 8 + + class MixerChannel { + public: + void SetVolume(float _left,float _right); + void SetScale( float f ); + void SetScale(float _left, float _right); + void UpdateVolume(void); + void SetLowpassFreq(Bitu _freq,unsigned int order=2); // _freq / 1 Hz. call with _freq == 0 to disable + void SetSlewFreq(Bitu _freq); // denominator provided by call to SetFreq. call with _freq == 0 to disable + void SetFreq(Bitu _freq,Bitu _den=1U); + void Mix(Bitu whole,Bitu frac); + void AddSilence(void); //Fill up until needed + void EndFrame(Bitu samples); + + void lowpassUpdate(); + int32_t lowpassStep(int32_t in,const unsigned int iteration,const unsigned int channel); + void lowpassProc(int32_t ch[2]); + + template + void loadCurrentSample(Bitu &len, const Type* &data); + + template + void AddSamples(Bitu len, const Type* data); + double timeSinceLastSample(void); + + bool runSampleInterpolation(const Bitu upto); + + void updateSlew(void); + void padFillSampleInterpolation(const Bitu upto); + void finishSampleInterpolation(const Bitu upto); + void AddSamples_m8(Bitu len, const uint8_t * data); + void AddSamples_s8(Bitu len, const uint8_t * data); + void AddSamples_m8s(Bitu len, const int8_t * data); + void AddSamples_s8s(Bitu len, const int8_t * data); + void AddSamples_m16(Bitu len, const int16_t * data); + void AddSamples_s16(Bitu len, const int16_t * data); + void AddSamples_m16u(Bitu len, const uint16_t * data); + void AddSamples_s16u(Bitu len, const uint16_t * data); + void AddSamples_m32(Bitu len, const int32_t * data); + void AddSamples_s32(Bitu len, const int32_t * data); + void AddSamples_m16_nonnative(Bitu len, const int16_t * data); + void AddSamples_s16_nonnative(Bitu len, const int16_t * data); + void AddSamples_m16u_nonnative(Bitu len, const uint16_t * data); + void AddSamples_s16u_nonnative(Bitu len, const uint16_t * data); + void AddSamples_m32_nonnative(Bitu len, const int32_t * data); + void AddSamples_s32_nonnative(Bitu len, const int32_t * data); + + void FillUp(void); + void Enable(bool _yesno); + void SaveState( std::ostream& stream ); + void LoadState( std::istream& stream ); + + MIXER_Handler handler; + float volmain[2]; + float scale[2]; + int32_t volmul[2]; + int32_t lowpass[LOWPASS_ORDER][2]; // lowpass filter + int32_t lowpass_alpha; // "alpha" multiplier for lowpass (16.16 fixed point) + Bitu lowpass_freq; + unsigned int lowpass_order; + bool lowpass_on_load; // apply lowpass on sample load (if source rate > mixer rate) + bool lowpass_on_out; // apply lowpass on rendered output (if source rate <= mixer rate) + unsigned int freq_f,freq_fslew; + unsigned int freq_nslew,freq_nslew_want; + unsigned int rendering_to_n,rendering_to_d; + unsigned int rend_n,rend_d; + unsigned int freq_n,freq_d,freq_d_orig; + bool current_loaded; + int32_t current[2],last[2],delta[2],max_change; + int32_t msbuffer[2048][2]; // more than enough for 1ms of audio, at mixer sample rate + Bits last_sample_write; + Bitu msbuffer_o; + Bitu msbuffer_i; + const char * name; + bool enabled; + MixerChannel * next; + }; + + void MIXER_SetMaster(float vol0,float vol1); + + MixerChannel * MIXER_AddChannel(MIXER_Handler handler,Bitu freq,const char * name); + MixerChannel * MIXER_FindChannel(const char * name); + /* Find the device you want to delete with findchannel "delchan gets deleted" */ + void MIXER_DelChannel(MixerChannel* delchan); + + /* Object to maintain a mixerchannel; As all objects it registers itself with create + * and removes itself when destroyed. */ + class MixerObject{ + private: + bool installed = false; + char m_name[32] = {}; + public: + MixerObject() {}; + MixerChannel* Install(MIXER_Handler handler,Bitu freq,const char * name); + ~MixerObject(); + }; + + + /* PC Speakers functions, tightly related to the timer functions */ + void PCSPEAKER_SetCounter(Bitu cntr,Bitu mode); + void PCSPEAKER_SetType(bool pit_clock_gate_enabled, bool pit_output_enabled); + void PCSPEAKER_SetPITControl(Bitu mode); + + struct mixedFraction { + unsigned int w; + unsigned int fn,fd; + }; + + struct mixer_t { + int32_t work[MIXER_BUFSIZE][2]; + Bitu work_in,work_out,work_wrap; + Bitu pos,done; + float mastervol[2]; + float recordvol[2]; + MixerChannel* channels; + uint32_t freq; + uint32_t blocksize; + struct mixedFraction samples_per_ms; + struct mixedFraction samples_this_ms; + struct mixedFraction samples_rendered_ms; + bool nosound; + bool swapstereo; + bool sampleaccurate; + bool prebuffer_wait; + Bitu prebuffer_samples; + bool mute; + }; + + extern mixer_t mixer; + + #endif + \ No newline at end of file diff --git a/include/mouse.h b/include/mouse.h index 1c6a964f787..89590a71c56 100644 --- a/include/mouse.h +++ b/include/mouse.h @@ -21,6 +21,8 @@ #ifndef DOSBOX_MOUSE_H #define DOSBOX_MOUSE_H +#include + enum MOUSE_EMULATION { MOUSE_EMULATION_NEVER, @@ -33,7 +35,6 @@ bool Mouse_SetPS2State(bool use); void Mouse_ChangePS2Callback(uint16_t pseg, uint16_t pofs); - void Mouse_CursorMoved(float xrel,float yrel,float x,float y,bool emulate); const char* Mouse_GetSelected(int x1, int y1, int x2, int y2, int w, int h, uint16_t *textlen); #if defined(WIN32) || defined(MACOSX) || defined(C_SDL2) @@ -51,4 +52,90 @@ void Mouse_AfterNewVideoMode(bool setmode); void UpdateMouseReportRate(void); void ChangeMouseReportRate(unsigned int new_rate); +#define MOUSE_BUTTONS 3 +#define QUEUE_SIZE 32 +#define CURSORX 16 +#define CURSORY 16 +#define MOUSE_HAS_MOVED 1 +#define MOUSE_LEFT_PRESSED 2 +#define MOUSE_LEFT_RELEASED 4 +#define MOUSE_RIGHT_PRESSED 8 +#define MOUSE_RIGHT_RELEASED 16 +#define MOUSE_MIDDLE_PRESSED 32 +#define MOUSE_MIDDLE_RELEASED 64 +#define MOUSE_WHEEL_MOVED 128 +#define MOUSE_ABSOLUTE 256 + +struct button_event { + uint8_t type; + uint8_t buttons; +}; + +struct mouse_t { + uint8_t buttons; + int16_t wheel; + uint16_t times_pressed[MOUSE_BUTTONS]; + uint16_t times_released[MOUSE_BUTTONS]; + uint16_t last_released_x[MOUSE_BUTTONS]; + uint16_t last_released_y[MOUSE_BUTTONS]; + uint16_t last_pressed_x[MOUSE_BUTTONS]; + uint16_t last_pressed_y[MOUSE_BUTTONS]; + pic_tickindex_t hidden_at; + uint16_t last_scrolled_x; + uint16_t last_scrolled_y; + uint16_t hidden; + float add_x,add_y; + int16_t min_x,max_x,min_y,max_y; + int16_t max_screen_x,max_screen_y; + int32_t mickey_x,mickey_y; + float mickey_accum_x, mickey_accum_y; + float x,y; + float ps2x,ps2y; + button_event event_queue[QUEUE_SIZE]; + uint8_t events;//Increase if QUEUE_SIZE >255 (currently 32) + uint16_t sub_seg,sub_ofs; + uint16_t sub_mask; + + bool background; + int16_t backposx, backposy; + uint8_t backData[CURSORX*CURSORY]; + uint16_t* screenMask; + uint16_t* cursorMask; + int16_t clipx,clipy; + int16_t hotx,hoty; + uint16_t textAndMask, textXorMask; + + float mickeysPerPixel_x; + float mickeysPerPixel_y; + float pixelPerMickey_x; + float pixelPerMickey_y; + uint16_t senv_x_val; + uint16_t senv_y_val; + uint16_t dspeed_val; + float senv_x; + float senv_y; + int16_t updateRegion_x[2]; + int16_t updateRegion_y[2]; + uint16_t doubleSpeedThreshold; + uint16_t language; + uint16_t cursorType; + uint16_t oldhidden; + uint8_t page; + bool enabled; + bool inhibit_draw; + bool timer_in_progress; + bool first_range_setx; + bool first_range_sety; + bool in_UIR; + uint8_t mode; + int16_t gran_x,gran_y; + int scrollwheel; + uint8_t ps2_type; + uint8_t ps2_rate; // sampling rate is not really emulated, but needed for switching between protocols + uint8_t ps2_packet_size; + uint8_t ps2_unlock_idx; +}; + +extern mouse_t mouse; +extern void Mouse_AddEvent(uint8_t type); #endif diff --git a/include/opus.h b/include/opus.h deleted file mode 100644 index 2fc97b17868..00000000000 --- a/include/opus.h +++ /dev/null @@ -1,981 +0,0 @@ -/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited - Written by Jean-Marc Valin and Koen Vos */ -/* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * @file opus.h - * @brief Opus reference implementation API - */ - -#ifndef OPUS_H -#define OPUS_H - -#include "opus_types.h" -#include "opus_defines.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @mainpage Opus - * - * The Opus codec is designed for interactive speech and audio transmission over the Internet. - * It is designed by the IETF Codec Working Group and incorporates technology from - * Skype's SILK codec and Xiph.Org's CELT codec. - * - * The Opus codec is designed to handle a wide range of interactive audio applications, - * including Voice over IP, videoconferencing, in-game chat, and even remote live music - * performances. It can scale from low bit-rate narrowband speech to very high quality - * stereo music. Its main features are: - - * @li Sampling rates from 8 to 48 kHz - * @li Bit-rates from 6 kb/s to 510 kb/s - * @li Support for both constant bit-rate (CBR) and variable bit-rate (VBR) - * @li Audio bandwidth from narrowband to full-band - * @li Support for speech and music - * @li Support for mono and stereo - * @li Support for multichannel (up to 255 channels) - * @li Frame sizes from 2.5 ms to 60 ms - * @li Good loss robustness and packet loss concealment (PLC) - * @li Floating point and fixed-point implementation - * - * Documentation sections: - * @li @ref opus_encoder - * @li @ref opus_decoder - * @li @ref opus_repacketizer - * @li @ref opus_multistream - * @li @ref opus_libinfo - * @li @ref opus_custom - */ - -/** @defgroup opus_encoder Opus Encoder - * @{ - * - * @brief This page describes the process and functions used to encode Opus. - * - * Since Opus is a stateful codec, the encoding process starts with creating an encoder - * state. This can be done with: - * - * @code - * int error; - * OpusEncoder *enc; - * enc = opus_encoder_create(Fs, channels, application, &error); - * @endcode - * - * From this point, @c enc can be used for encoding an audio stream. An encoder state - * @b must @b not be used for more than one stream at the same time. Similarly, the encoder - * state @b must @b not be re-initialized for each frame. - * - * While opus_encoder_create() allocates memory for the state, it's also possible - * to initialize pre-allocated memory: - * - * @code - * int size; - * int error; - * OpusEncoder *enc; - * size = opus_encoder_get_size(channels); - * enc = malloc(size); - * error = opus_encoder_init(enc, Fs, channels, application); - * @endcode - * - * where opus_encoder_get_size() returns the required size for the encoder state. Note that - * future versions of this code may change the size, so no assumptions should be made about it. - * - * The encoder state is always continuous in memory and only a shallow copy is sufficient - * to copy it (e.g. memcpy()) - * - * It is possible to change some of the encoder's settings using the opus_encoder_ctl() - * interface. All these settings already default to the recommended value, so they should - * only be changed when necessary. The most common settings one may want to change are: - * - * @code - * opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate)); - * opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity)); - * opus_encoder_ctl(enc, OPUS_SET_SIGNAL(signal_type)); - * @endcode - * - * where - * - * @arg bitrate is in bits per second (b/s) - * @arg complexity is a value from 1 to 10, where 1 is the lowest complexity and 10 is the highest - * @arg signal_type is either OPUS_AUTO (default), OPUS_SIGNAL_VOICE, or OPUS_SIGNAL_MUSIC - * - * See @ref opus_encoderctls and @ref opus_genericctls for a complete list of parameters that can be set or queried. Most parameters can be set or changed at any time during a stream. - * - * To encode a frame, opus_encode() or opus_encode_float() must be called with exactly one frame (2.5, 5, 10, 20, 40 or 60 ms) of audio data: - * @code - * len = opus_encode(enc, audio_frame, frame_size, packet, max_packet); - * @endcode - * - * where - *
    - *
  • audio_frame is the audio data in opus_int16 (or float for opus_encode_float())
  • - *
  • frame_size is the duration of the frame in samples (per channel)
  • - *
  • packet is the byte array to which the compressed data is written
  • - *
  • max_packet is the maximum number of bytes that can be written in the packet (4000 bytes is recommended). - * Do not use max_packet to control VBR target bitrate, instead use the #OPUS_SET_BITRATE CTL.
  • - *
- * - * opus_encode() and opus_encode_float() return the number of bytes actually written to the packet. - * The return value can be negative, which indicates that an error has occurred. If the return value - * is 2 bytes or less, then the packet does not need to be transmitted (DTX). - * - * Once the encoder state if no longer needed, it can be destroyed with - * - * @code - * opus_encoder_destroy(enc); - * @endcode - * - * If the encoder was created with opus_encoder_init() rather than opus_encoder_create(), - * then no action is required aside from potentially freeing the memory that was manually - * allocated for it (calling free(enc) for the example above) - * - */ - -/** Opus encoder state. - * This contains the complete state of an Opus encoder. - * It is position independent and can be freely copied. - * @see opus_encoder_create,opus_encoder_init - */ -typedef struct OpusEncoder OpusEncoder; - -/** Gets the size of an OpusEncoder structure. - * @param[in] channels int: Number of channels. - * This must be 1 or 2. - * @returns The size in bytes. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_encoder_get_size(int channels); - -/** - */ - -/** Allocates and initializes an encoder state. - * There are three coding modes: - * - * @ref OPUS_APPLICATION_VOIP gives best quality at a given bitrate for voice - * signals. It enhances the input signal by high-pass filtering and - * emphasizing formants and harmonics. Optionally it includes in-band - * forward error correction to protect against packet loss. Use this - * mode for typical VoIP applications. Because of the enhancement, - * even at high bitrates the output may sound different from the input. - * - * @ref OPUS_APPLICATION_AUDIO gives best quality at a given bitrate for most - * non-voice signals like music. Use this mode for music and mixed - * (music/voice) content, broadcast, and applications requiring less - * than 15 ms of coding delay. - * - * @ref OPUS_APPLICATION_RESTRICTED_LOWDELAY configures low-delay mode that - * disables the speech-optimized mode in exchange for slightly reduced delay. - * This mode can only be set on an newly initialized or freshly reset encoder - * because it changes the codec delay. - * - * This is useful when the caller knows that the speech-optimized modes will not be needed (use with caution). - * @param [in] Fs opus_int32: Sampling rate of input signal (Hz) - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param [in] channels int: Number of channels (1 or 2) in input signal - * @param [in] application int: Coding mode (@ref OPUS_APPLICATION_VOIP/@ref OPUS_APPLICATION_AUDIO/@ref OPUS_APPLICATION_RESTRICTED_LOWDELAY) - * @param [out] error int*: @ref opus_errorcodes - * @note Regardless of the sampling rate and number channels selected, the Opus encoder - * can switch to a lower audio bandwidth or number of channels if the bitrate - * selected is too low. This also means that it is safe to always use 48 kHz stereo input - * and let the encoder optimize the encoding. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusEncoder *opus_encoder_create( - opus_int32 Fs, - int channels, - int application, - int *error -); - -/** Initializes a previously allocated encoder state - * The memory pointed to by st must be at least the size returned by opus_encoder_get_size(). - * This is intended for applications which use their own allocator instead of malloc. - * @see opus_encoder_create(),opus_encoder_get_size() - * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. - * @param [in] st OpusEncoder*: Encoder state - * @param [in] Fs opus_int32: Sampling rate of input signal (Hz) - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param [in] channels int: Number of channels (1 or 2) in input signal - * @param [in] application int: Coding mode (OPUS_APPLICATION_VOIP/OPUS_APPLICATION_AUDIO/OPUS_APPLICATION_RESTRICTED_LOWDELAY) - * @retval #OPUS_OK Success or @ref opus_errorcodes - */ -OPUS_EXPORT int opus_encoder_init( - OpusEncoder *st, - opus_int32 Fs, - int channels, - int application -) OPUS_ARG_NONNULL(1); - -/** Encodes an Opus frame. - * @param [in] st OpusEncoder*: Encoder state - * @param [in] pcm opus_int16*: Input signal (interleaved if 2 channels). length is frame_size*channels*sizeof(opus_int16) - * @param [in] frame_size int: Number of samples per channel in the - * input signal. - * This must be an Opus frame size for - * the encoder's sampling rate. - * For example, at 48 kHz the permitted - * values are 120, 240, 480, 960, 1920, - * and 2880. - * Passing in a duration of less than - * 10 ms (480 samples at 48 kHz) will - * prevent the encoder from using the LPC - * or hybrid modes. - * @param [out] data unsigned char*: Output payload. - * This must contain storage for at - * least \a max_data_bytes. - * @param [in] max_data_bytes opus_int32: Size of the allocated - * memory for the output - * payload. This may be - * used to impose an upper limit on - * the instant bitrate, but should - * not be used as the only bitrate - * control. Use #OPUS_SET_BITRATE to - * control the bitrate. - * @returns The length of the encoded packet (in bytes) on success or a - * negative error code (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_encode( - OpusEncoder *st, - const opus_int16 *pcm, - int frame_size, - unsigned char *data, - opus_int32 max_data_bytes -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); - -/** Encodes an Opus frame from floating point input. - * @param [in] st OpusEncoder*: Encoder state - * @param [in] pcm float*: Input in float format (interleaved if 2 channels), with a normal range of +/-1.0. - * Samples with a range beyond +/-1.0 are supported but will - * be clipped by decoders using the integer API and should - * only be used if it is known that the far end supports - * extended dynamic range. - * length is frame_size*channels*sizeof(float) - * @param [in] frame_size int: Number of samples per channel in the - * input signal. - * This must be an Opus frame size for - * the encoder's sampling rate. - * For example, at 48 kHz the permitted - * values are 120, 240, 480, 960, 1920, - * and 2880. - * Passing in a duration of less than - * 10 ms (480 samples at 48 kHz) will - * prevent the encoder from using the LPC - * or hybrid modes. - * @param [out] data unsigned char*: Output payload. - * This must contain storage for at - * least \a max_data_bytes. - * @param [in] max_data_bytes opus_int32: Size of the allocated - * memory for the output - * payload. This may be - * used to impose an upper limit on - * the instant bitrate, but should - * not be used as the only bitrate - * control. Use #OPUS_SET_BITRATE to - * control the bitrate. - * @returns The length of the encoded packet (in bytes) on success or a - * negative error code (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_encode_float( - OpusEncoder *st, - const float *pcm, - int frame_size, - unsigned char *data, - opus_int32 max_data_bytes -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); - -/** Frees an OpusEncoder allocated by opus_encoder_create(). - * @param[in] st OpusEncoder*: State to be freed. - */ -OPUS_EXPORT void opus_encoder_destroy(OpusEncoder *st); - -/** Perform a CTL function on an Opus encoder. - * - * Generally the request and subsequent arguments are generated - * by a convenience macro. - * @param st OpusEncoder*: Encoder state. - * @param request This and all remaining parameters should be replaced by one - * of the convenience macros in @ref opus_genericctls or - * @ref opus_encoderctls. - * @see opus_genericctls - * @see opus_encoderctls - */ -OPUS_EXPORT int opus_encoder_ctl(OpusEncoder *st, int request, ...) OPUS_ARG_NONNULL(1); -/**@}*/ - -/** @defgroup opus_decoder Opus Decoder - * @{ - * - * @brief This page describes the process and functions used to decode Opus. - * - * The decoding process also starts with creating a decoder - * state. This can be done with: - * @code - * int error; - * OpusDecoder *dec; - * dec = opus_decoder_create(Fs, channels, &error); - * @endcode - * where - * @li Fs is the sampling rate and must be 8000, 12000, 16000, 24000, or 48000 - * @li channels is the number of channels (1 or 2) - * @li error will hold the error code in case of failure (or #OPUS_OK on success) - * @li the return value is a newly created decoder state to be used for decoding - * - * While opus_decoder_create() allocates memory for the state, it's also possible - * to initialize pre-allocated memory: - * @code - * int size; - * int error; - * OpusDecoder *dec; - * size = opus_decoder_get_size(channels); - * dec = malloc(size); - * error = opus_decoder_init(dec, Fs, channels); - * @endcode - * where opus_decoder_get_size() returns the required size for the decoder state. Note that - * future versions of this code may change the size, so no assumptions should be made about it. - * - * The decoder state is always continuous in memory and only a shallow copy is sufficient - * to copy it (e.g. memcpy()) - * - * To decode a frame, opus_decode() or opus_decode_float() must be called with a packet of compressed audio data: - * @code - * frame_size = opus_decode(dec, packet, len, decoded, max_size, 0); - * @endcode - * where - * - * @li packet is the byte array containing the compressed data - * @li len is the exact number of bytes contained in the packet - * @li decoded is the decoded audio data in opus_int16 (or float for opus_decode_float()) - * @li max_size is the max duration of the frame in samples (per channel) that can fit into the decoded_frame array - * - * opus_decode() and opus_decode_float() return the number of samples (per channel) decoded from the packet. - * If that value is negative, then an error has occurred. This can occur if the packet is corrupted or if the audio - * buffer is too small to hold the decoded audio. - * - * Opus is a stateful codec with overlapping blocks and as a result Opus - * packets are not coded independently of each other. Packets must be - * passed into the decoder serially and in the correct order for a correct - * decode. Lost packets can be replaced with loss concealment by calling - * the decoder with a null pointer and zero length for the missing packet. - * - * A single codec state may only be accessed from a single thread at - * a time and any required locking must be performed by the caller. Separate - * streams must be decoded with separate decoder states and can be decoded - * in parallel unless the library was compiled with NONTHREADSAFE_PSEUDOSTACK - * defined. - * - */ - -/** Opus decoder state. - * This contains the complete state of an Opus decoder. - * It is position independent and can be freely copied. - * @see opus_decoder_create,opus_decoder_init - */ -typedef struct OpusDecoder OpusDecoder; - -/** Gets the size of an OpusDecoder structure. - * @param [in] channels int: Number of channels. - * This must be 1 or 2. - * @returns The size in bytes. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decoder_get_size(int channels); - -/** Allocates and initializes a decoder state. - * @param [in] Fs opus_int32: Sample rate to decode at (Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param [in] channels int: Number of channels (1 or 2) to decode - * @param [out] error int*: #OPUS_OK Success or @ref opus_errorcodes - * - * Internally Opus stores data at 48000 Hz, so that should be the default - * value for Fs. However, the decoder can efficiently decode to buffers - * at 8, 12, 16, and 24 kHz so if for some reason the caller cannot use - * data at the full sample rate, or knows the compressed data doesn't - * use the full frequency range, it can request decoding at a reduced - * rate. Likewise, the decoder is capable of filling in either mono or - * interleaved stereo pcm buffers, at the caller's request. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusDecoder *opus_decoder_create( - opus_int32 Fs, - int channels, - int *error -); - -/** Initializes a previously allocated decoder state. - * The state must be at least the size returned by opus_decoder_get_size(). - * This is intended for applications which use their own allocator instead of malloc. @see opus_decoder_create,opus_decoder_get_size - * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. - * @param [in] st OpusDecoder*: Decoder state. - * @param [in] Fs opus_int32: Sampling rate to decode to (Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param [in] channels int: Number of channels (1 or 2) to decode - * @retval #OPUS_OK Success or @ref opus_errorcodes - */ -OPUS_EXPORT int opus_decoder_init( - OpusDecoder *st, - opus_int32 Fs, - int channels -) OPUS_ARG_NONNULL(1); - -/** Decode an Opus packet. - * @param [in] st OpusDecoder*: Decoder state - * @param [in] data char*: Input payload. Use a NULL pointer to indicate packet loss - * @param [in] len opus_int32: Number of bytes in payload* - * @param [out] pcm opus_int16*: Output signal (interleaved if 2 channels). length - * is frame_size*channels*sizeof(opus_int16) - * @param [in] frame_size Number of samples per channel of available space in \a pcm. - * If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will - * not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1), - * then frame_size needs to be exactly the duration of audio that is missing, otherwise the - * decoder will not be in the optimal state to decode the next incoming packet. For the PLC and - * FEC cases, frame_size must be a multiple of 2.5 ms. - * @param [in] decode_fec int: Flag (0 or 1) to request that any in-band forward error correction data be - * decoded. If no such data is available, the frame is decoded as if it were lost. - * @returns Number of decoded samples or @ref opus_errorcodes - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decode( - OpusDecoder *st, - const unsigned char *data, - opus_int32 len, - opus_int16 *pcm, - int frame_size, - int decode_fec -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - -/** Decode an Opus packet with floating point output. - * @param [in] st OpusDecoder*: Decoder state - * @param [in] data char*: Input payload. Use a NULL pointer to indicate packet loss - * @param [in] len opus_int32: Number of bytes in payload - * @param [out] pcm float*: Output signal (interleaved if 2 channels). length - * is frame_size*channels*sizeof(float) - * @param [in] frame_size Number of samples per channel of available space in \a pcm. - * If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will - * not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1), - * then frame_size needs to be exactly the duration of audio that is missing, otherwise the - * decoder will not be in the optimal state to decode the next incoming packet. For the PLC and - * FEC cases, frame_size must be a multiple of 2.5 ms. - * @param [in] decode_fec int: Flag (0 or 1) to request that any in-band forward error correction data be - * decoded. If no such data is available the frame is decoded as if it were lost. - * @returns Number of decoded samples or @ref opus_errorcodes - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decode_float( - OpusDecoder *st, - const unsigned char *data, - opus_int32 len, - float *pcm, - int frame_size, - int decode_fec -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - -/** Perform a CTL function on an Opus decoder. - * - * Generally the request and subsequent arguments are generated - * by a convenience macro. - * @param st OpusDecoder*: Decoder state. - * @param request This and all remaining parameters should be replaced by one - * of the convenience macros in @ref opus_genericctls or - * @ref opus_decoderctls. - * @see opus_genericctls - * @see opus_decoderctls - */ -OPUS_EXPORT int opus_decoder_ctl(OpusDecoder *st, int request, ...) OPUS_ARG_NONNULL(1); - -/** Frees an OpusDecoder allocated by opus_decoder_create(). - * @param[in] st OpusDecoder*: State to be freed. - */ -OPUS_EXPORT void opus_decoder_destroy(OpusDecoder *st); - -/** Parse an opus packet into one or more frames. - * Opus_decode will perform this operation internally so most applications do - * not need to use this function. - * This function does not copy the frames, the returned pointers are pointers into - * the input packet. - * @param [in] data char*: Opus packet to be parsed - * @param [in] len opus_int32: size of data - * @param [out] out_toc char*: TOC pointer - * @param [out] frames char*[48] encapsulated frames - * @param [out] size opus_int16[48] sizes of the encapsulated frames - * @param [out] payload_offset int*: returns the position of the payload within the packet (in bytes) - * @returns number of frames - */ -OPUS_EXPORT int opus_packet_parse( - const unsigned char *data, - opus_int32 len, - unsigned char *out_toc, - const unsigned char *frames[48], - opus_int16 size[48], - int *payload_offset -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(5); - -/** Gets the bandwidth of an Opus packet. - * @param [in] data char*: Opus packet - * @retval OPUS_BANDWIDTH_NARROWBAND Narrowband (4kHz bandpass) - * @retval OPUS_BANDWIDTH_MEDIUMBAND Mediumband (6kHz bandpass) - * @retval OPUS_BANDWIDTH_WIDEBAND Wideband (8kHz bandpass) - * @retval OPUS_BANDWIDTH_SUPERWIDEBAND Superwideband (12kHz bandpass) - * @retval OPUS_BANDWIDTH_FULLBAND Fullband (20kHz bandpass) - * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_bandwidth(const unsigned char *data) OPUS_ARG_NONNULL(1); - -/** Gets the number of samples per frame from an Opus packet. - * @param [in] data char*: Opus packet. - * This must contain at least one byte of - * data. - * @param [in] Fs opus_int32: Sampling rate in Hz. - * This must be a multiple of 400, or - * inaccurate results will be returned. - * @returns Number of samples per frame. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_samples_per_frame(const unsigned char *data, opus_int32 Fs) OPUS_ARG_NONNULL(1); - -/** Gets the number of channels from an Opus packet. - * @param [in] data char*: Opus packet - * @returns Number of channels - * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_channels(const unsigned char *data) OPUS_ARG_NONNULL(1); - -/** Gets the number of frames in an Opus packet. - * @param [in] packet char*: Opus packet - * @param [in] len opus_int32: Length of packet - * @returns Number of frames - * @retval OPUS_BAD_ARG Insufficient data was passed to the function - * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_frames(const unsigned char packet[], opus_int32 len) OPUS_ARG_NONNULL(1); - -/** Gets the number of samples of an Opus packet. - * @param [in] packet char*: Opus packet - * @param [in] len opus_int32: Length of packet - * @param [in] Fs opus_int32: Sampling rate in Hz. - * This must be a multiple of 400, or - * inaccurate results will be returned. - * @returns Number of samples - * @retval OPUS_BAD_ARG Insufficient data was passed to the function - * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_samples(const unsigned char packet[], opus_int32 len, opus_int32 Fs) OPUS_ARG_NONNULL(1); - -/** Gets the number of samples of an Opus packet. - * @param [in] dec OpusDecoder*: Decoder state - * @param [in] packet char*: Opus packet - * @param [in] len opus_int32: Length of packet - * @returns Number of samples - * @retval OPUS_BAD_ARG Insufficient data was passed to the function - * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decoder_get_nb_samples(const OpusDecoder *dec, const unsigned char packet[], opus_int32 len) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2); - -/** Applies soft-clipping to bring a float signal within the [-1,1] range. If - * the signal is already in that range, nothing is done. If there are values - * outside of [-1,1], then the signal is clipped as smoothly as possible to - * both fit in the range and avoid creating excessive distortion in the - * process. - * @param [in,out] pcm float*: Input PCM and modified PCM - * @param [in] frame_size int Number of samples per channel to process - * @param [in] channels int: Number of channels - * @param [in,out] softclip_mem float*: State memory for the soft clipping process (one float per channel, initialized to zero) - */ -OPUS_EXPORT void opus_pcm_soft_clip(float *pcm, int frame_size, int channels, float *softclip_mem); - - -/**@}*/ - -/** @defgroup opus_repacketizer Repacketizer - * @{ - * - * The repacketizer can be used to merge multiple Opus packets into a single - * packet or alternatively to split Opus packets that have previously been - * merged. Splitting valid Opus packets is always guaranteed to succeed, - * whereas merging valid packets only succeeds if all frames have the same - * mode, bandwidth, and frame size, and when the total duration of the merged - * packet is no more than 120 ms. The 120 ms limit comes from the - * specification and limits decoder memory requirements at a point where - * framing overhead becomes negligible. - * - * The repacketizer currently only operates on elementary Opus - * streams. It will not manipulate multistream packets successfully, except in - * the degenerate case where they consist of data from a single stream. - * - * The repacketizing process starts with creating a repacketizer state, either - * by calling opus_repacketizer_create() or by allocating the memory yourself, - * e.g., - * @code - * OpusRepacketizer *rp; - * rp = (OpusRepacketizer*)malloc(opus_repacketizer_get_size()); - * if (rp != NULL) - * opus_repacketizer_init(rp); - * @endcode - * - * Then the application should submit packets with opus_repacketizer_cat(), - * extract new packets with opus_repacketizer_out() or - * opus_repacketizer_out_range(), and then reset the state for the next set of - * input packets via opus_repacketizer_init(). - * - * For example, to split a sequence of packets into individual frames: - * @code - * unsigned char *data; - * int len; - * while (get_next_packet(&data, &len)) - * { - * unsigned char out[1276]; - * opus_int32 out_len; - * int nb_frames; - * int err; - * int i; - * err = opus_repacketizer_cat(rp, data, len); - * if (err != OPUS_OK) - * { - * release_packet(data); - * return err; - * } - * nb_frames = opus_repacketizer_get_nb_frames(rp); - * for (i = 0; i < nb_frames; i++) - * { - * out_len = opus_repacketizer_out_range(rp, i, i+1, out, sizeof(out)); - * if (out_len < 0) - * { - * release_packet(data); - * return (int)out_len; - * } - * output_next_packet(out, out_len); - * } - * opus_repacketizer_init(rp); - * release_packet(data); - * } - * @endcode - * - * Alternatively, to combine a sequence of frames into packets that each - * contain up to TARGET_DURATION_MS milliseconds of data: - * @code - * // The maximum number of packets with duration TARGET_DURATION_MS occurs - * // when the frame size is 2.5 ms, for a total of (TARGET_DURATION_MS*2/5) - * // packets. - * unsigned char *data[(TARGET_DURATION_MS*2/5)+1]; - * opus_int32 len[(TARGET_DURATION_MS*2/5)+1]; - * int nb_packets; - * unsigned char out[1277*(TARGET_DURATION_MS*2/2)]; - * opus_int32 out_len; - * int prev_toc; - * nb_packets = 0; - * while (get_next_packet(data+nb_packets, len+nb_packets)) - * { - * int nb_frames; - * int err; - * nb_frames = opus_packet_get_nb_frames(data[nb_packets], len[nb_packets]); - * if (nb_frames < 1) - * { - * release_packets(data, nb_packets+1); - * return nb_frames; - * } - * nb_frames += opus_repacketizer_get_nb_frames(rp); - * // If adding the next packet would exceed our target, or it has an - * // incompatible TOC sequence, output the packets we already have before - * // submitting it. - * // N.B., The nb_packets > 0 check ensures we've submitted at least one - * // packet since the last call to opus_repacketizer_init(). Otherwise a - * // single packet longer than TARGET_DURATION_MS would cause us to try to - * // output an (invalid) empty packet. It also ensures that prev_toc has - * // been set to a valid value. Additionally, len[nb_packets] > 0 is - * // guaranteed by the call to opus_packet_get_nb_frames() above, so the - * // reference to data[nb_packets][0] should be valid. - * if (nb_packets > 0 && ( - * ((prev_toc & 0xFC) != (data[nb_packets][0] & 0xFC)) || - * opus_packet_get_samples_per_frame(data[nb_packets], 48000)*nb_frames > - * TARGET_DURATION_MS*48)) - * { - * out_len = opus_repacketizer_out(rp, out, sizeof(out)); - * if (out_len < 0) - * { - * release_packets(data, nb_packets+1); - * return (int)out_len; - * } - * output_next_packet(out, out_len); - * opus_repacketizer_init(rp); - * release_packets(data, nb_packets); - * data[0] = data[nb_packets]; - * len[0] = len[nb_packets]; - * nb_packets = 0; - * } - * err = opus_repacketizer_cat(rp, data[nb_packets], len[nb_packets]); - * if (err != OPUS_OK) - * { - * release_packets(data, nb_packets+1); - * return err; - * } - * prev_toc = data[nb_packets][0]; - * nb_packets++; - * } - * // Output the final, partial packet. - * if (nb_packets > 0) - * { - * out_len = opus_repacketizer_out(rp, out, sizeof(out)); - * release_packets(data, nb_packets); - * if (out_len < 0) - * return (int)out_len; - * output_next_packet(out, out_len); - * } - * @endcode - * - * An alternate way of merging packets is to simply call opus_repacketizer_cat() - * unconditionally until it fails. At that point, the merged packet can be - * obtained with opus_repacketizer_out() and the input packet for which - * opus_repacketizer_cat() needs to be re-added to a newly reinitialized - * repacketizer state. - */ - -typedef struct OpusRepacketizer OpusRepacketizer; - -/** Gets the size of an OpusRepacketizer structure. - * @returns The size in bytes. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_repacketizer_get_size(void); - -/** (Re)initializes a previously allocated repacketizer state. - * The state must be at least the size returned by opus_repacketizer_get_size(). - * This can be used for applications which use their own allocator instead of - * malloc(). - * It must also be called to reset the queue of packets waiting to be - * repacketized, which is necessary if the maximum packet duration of 120 ms - * is reached or if you wish to submit packets with a different Opus - * configuration (coding mode, audio bandwidth, frame size, or channel count). - * Failure to do so will prevent a new packet from being added with - * opus_repacketizer_cat(). - * @see opus_repacketizer_create - * @see opus_repacketizer_get_size - * @see opus_repacketizer_cat - * @param rp OpusRepacketizer*: The repacketizer state to - * (re)initialize. - * @returns A pointer to the same repacketizer state that was passed in. - */ -OPUS_EXPORT OpusRepacketizer *opus_repacketizer_init(OpusRepacketizer *rp) OPUS_ARG_NONNULL(1); - -/** Allocates memory and initializes the new repacketizer with - * opus_repacketizer_init(). - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusRepacketizer *opus_repacketizer_create(void); - -/** Frees an OpusRepacketizer allocated by - * opus_repacketizer_create(). - * @param[in] rp OpusRepacketizer*: State to be freed. - */ -OPUS_EXPORT void opus_repacketizer_destroy(OpusRepacketizer *rp); - -/** Add a packet to the current repacketizer state. - * This packet must match the configuration of any packets already submitted - * for repacketization since the last call to opus_repacketizer_init(). - * This means that it must have the same coding mode, audio bandwidth, frame - * size, and channel count. - * This can be checked in advance by examining the top 6 bits of the first - * byte of the packet, and ensuring they match the top 6 bits of the first - * byte of any previously submitted packet. - * The total duration of audio in the repacketizer state also must not exceed - * 120 ms, the maximum duration of a single packet, after adding this packet. - * - * The contents of the current repacketizer state can be extracted into new - * packets using opus_repacketizer_out() or opus_repacketizer_out_range(). - * - * In order to add a packet with a different configuration or to add more - * audio beyond 120 ms, you must clear the repacketizer state by calling - * opus_repacketizer_init(). - * If a packet is too large to add to the current repacketizer state, no part - * of it is added, even if it contains multiple frames, some of which might - * fit. - * If you wish to be able to add parts of such packets, you should first use - * another repacketizer to split the packet into pieces and add them - * individually. - * @see opus_repacketizer_out_range - * @see opus_repacketizer_out - * @see opus_repacketizer_init - * @param rp OpusRepacketizer*: The repacketizer state to which to - * add the packet. - * @param[in] data const unsigned char*: The packet data. - * The application must ensure - * this pointer remains valid - * until the next call to - * opus_repacketizer_init() or - * opus_repacketizer_destroy(). - * @param len opus_int32: The number of bytes in the packet data. - * @returns An error code indicating whether or not the operation succeeded. - * @retval #OPUS_OK The packet's contents have been added to the repacketizer - * state. - * @retval #OPUS_INVALID_PACKET The packet did not have a valid TOC sequence, - * the packet's TOC sequence was not compatible - * with previously submitted packets (because - * the coding mode, audio bandwidth, frame size, - * or channel count did not match), or adding - * this packet would increase the total amount of - * audio stored in the repacketizer state to more - * than 120 ms. - */ -OPUS_EXPORT int opus_repacketizer_cat(OpusRepacketizer *rp, const unsigned char *data, opus_int32 len) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2); - - -/** Construct a new packet from data previously submitted to the repacketizer - * state via opus_repacketizer_cat(). - * @param rp OpusRepacketizer*: The repacketizer state from which to - * construct the new packet. - * @param begin int: The index of the first frame in the current - * repacketizer state to include in the output. - * @param end int: One past the index of the last frame in the - * current repacketizer state to include in the - * output. - * @param[out] data const unsigned char*: The buffer in which to - * store the output packet. - * @param maxlen opus_int32: The maximum number of bytes to store in - * the output buffer. In order to guarantee - * success, this should be at least - * 1276 for a single frame, - * or for multiple frames, - * 1277*(end-begin). - * However, 1*(end-begin) plus - * the size of all packet data submitted to - * the repacketizer since the last call to - * opus_repacketizer_init() or - * opus_repacketizer_create() is also - * sufficient, and possibly much smaller. - * @returns The total size of the output packet on success, or an error code - * on failure. - * @retval #OPUS_BAD_ARG [begin,end) was an invalid range of - * frames (begin < 0, begin >= end, or end > - * opus_repacketizer_get_nb_frames()). - * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the - * complete output packet. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_repacketizer_out_range(OpusRepacketizer *rp, int begin, int end, unsigned char *data, opus_int32 maxlen) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - -/** Return the total number of frames contained in packet data submitted to - * the repacketizer state so far via opus_repacketizer_cat() since the last - * call to opus_repacketizer_init() or opus_repacketizer_create(). - * This defines the valid range of packets that can be extracted with - * opus_repacketizer_out_range() or opus_repacketizer_out(). - * @param rp OpusRepacketizer*: The repacketizer state containing the - * frames. - * @returns The total number of frames contained in the packet data submitted - * to the repacketizer state. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_repacketizer_get_nb_frames(OpusRepacketizer *rp) OPUS_ARG_NONNULL(1); - -/** Construct a new packet from data previously submitted to the repacketizer - * state via opus_repacketizer_cat(). - * This is a convenience routine that returns all the data submitted so far - * in a single packet. - * It is equivalent to calling - * @code - * opus_repacketizer_out_range(rp, 0, opus_repacketizer_get_nb_frames(rp), - * data, maxlen) - * @endcode - * @param rp OpusRepacketizer*: The repacketizer state from which to - * construct the new packet. - * @param[out] data const unsigned char*: The buffer in which to - * store the output packet. - * @param maxlen opus_int32: The maximum number of bytes to store in - * the output buffer. In order to guarantee - * success, this should be at least - * 1277*opus_repacketizer_get_nb_frames(rp). - * However, - * 1*opus_repacketizer_get_nb_frames(rp) - * plus the size of all packet data - * submitted to the repacketizer since the - * last call to opus_repacketizer_init() or - * opus_repacketizer_create() is also - * sufficient, and possibly much smaller. - * @returns The total size of the output packet on success, or an error code - * on failure. - * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the - * complete output packet. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_repacketizer_out(OpusRepacketizer *rp, unsigned char *data, opus_int32 maxlen) OPUS_ARG_NONNULL(1); - -/** Pads a given Opus packet to a larger size (possibly changing the TOC sequence). - * @param[in,out] data const unsigned char*: The buffer containing the - * packet to pad. - * @param len opus_int32: The size of the packet. - * This must be at least 1. - * @param new_len opus_int32: The desired size of the packet after padding. - * This must be at least as large as len. - * @returns an error code - * @retval #OPUS_OK \a on success. - * @retval #OPUS_BAD_ARG \a len was less than 1 or new_len was less than len. - * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet. - */ -OPUS_EXPORT int opus_packet_pad(unsigned char *data, opus_int32 len, opus_int32 new_len); - -/** Remove all padding from a given Opus packet and rewrite the TOC sequence to - * minimize space usage. - * @param[in,out] data const unsigned char*: The buffer containing the - * packet to strip. - * @param len opus_int32: The size of the packet. - * This must be at least 1. - * @returns The new size of the output packet on success, or an error code - * on failure. - * @retval #OPUS_BAD_ARG \a len was less than 1. - * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_packet_unpad(unsigned char *data, opus_int32 len); - -/** Pads a given Opus multi-stream packet to a larger size (possibly changing the TOC sequence). - * @param[in,out] data const unsigned char*: The buffer containing the - * packet to pad. - * @param len opus_int32: The size of the packet. - * This must be at least 1. - * @param new_len opus_int32: The desired size of the packet after padding. - * This must be at least 1. - * @param nb_streams opus_int32: The number of streams (not channels) in the packet. - * This must be at least as large as len. - * @returns an error code - * @retval #OPUS_OK \a on success. - * @retval #OPUS_BAD_ARG \a len was less than 1. - * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet. - */ -OPUS_EXPORT int opus_multistream_packet_pad(unsigned char *data, opus_int32 len, opus_int32 new_len, int nb_streams); - -/** Remove all padding from a given Opus multi-stream packet and rewrite the TOC sequence to - * minimize space usage. - * @param[in,out] data const unsigned char*: The buffer containing the - * packet to strip. - * @param len opus_int32: The size of the packet. - * This must be at least 1. - * @param nb_streams opus_int32: The number of streams (not channels) in the packet. - * This must be at least 1. - * @returns The new size of the output packet on success, or an error code - * on failure. - * @retval #OPUS_BAD_ARG \a len was less than 1 or new_len was less than len. - * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_packet_unpad(unsigned char *data, opus_int32 len, int nb_streams); - -/**@}*/ - -#ifdef __cplusplus -} -#endif - -#endif /* OPUS_H */ diff --git a/include/opus_custom.h b/include/opus_custom.h deleted file mode 100644 index 427abecbe5b..00000000000 --- a/include/opus_custom.h +++ /dev/null @@ -1,342 +0,0 @@ -/* Copyright (c) 2007-2008 CSIRO - Copyright (c) 2007-2009 Xiph.Org Foundation - Copyright (c) 2008-2012 Gregory Maxwell - Written by Jean-Marc Valin and Gregory Maxwell */ -/* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - @file opus_custom.h - @brief Opus-Custom reference implementation API - */ - -#ifndef OPUS_CUSTOM_H -#define OPUS_CUSTOM_H - -#include "opus_defines.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef CUSTOM_MODES -# define OPUS_CUSTOM_EXPORT OPUS_EXPORT -# define OPUS_CUSTOM_EXPORT_STATIC OPUS_EXPORT -#else -# define OPUS_CUSTOM_EXPORT -# ifdef OPUS_BUILD -# define OPUS_CUSTOM_EXPORT_STATIC static OPUS_INLINE -# else -# define OPUS_CUSTOM_EXPORT_STATIC -# endif -#endif - -/** @defgroup opus_custom Opus Custom - * @{ - * Opus Custom is an optional part of the Opus specification and - * reference implementation which uses a distinct API from the regular - * API and supports frame sizes that are not normally supported.\ Use - * of Opus Custom is discouraged for all but very special applications - * for which a frame size different from 2.5, 5, 10, or 20 ms is needed - * (for either complexity or latency reasons) and where interoperability - * is less important. - * - * In addition to the interoperability limitations the use of Opus custom - * disables a substantial chunk of the codec and generally lowers the - * quality available at a given bitrate. Normally when an application needs - * a different frame size from the codec it should buffer to match the - * sizes but this adds a small amount of delay which may be important - * in some very low latency applications. Some transports (especially - * constant rate RF transports) may also work best with frames of - * particular durations. - * - * Libopus only supports custom modes if they are enabled at compile time. - * - * The Opus Custom API is similar to the regular API but the - * @ref opus_encoder_create and @ref opus_decoder_create calls take - * an additional mode parameter which is a structure produced by - * a call to @ref opus_custom_mode_create. Both the encoder and decoder - * must create a mode using the same sample rate (fs) and frame size - * (frame size) so these parameters must either be signaled out of band - * or fixed in a particular implementation. - * - * Similar to regular Opus the custom modes support on the fly frame size - * switching, but the sizes available depend on the particular frame size in - * use. For some initial frame sizes on a single on the fly size is available. - */ - -/** Contains the state of an encoder. One encoder state is needed - for each stream. It is initialized once at the beginning of the - stream. Do *not* re-initialize the state for every frame. - @brief Encoder state - */ -typedef struct OpusCustomEncoder OpusCustomEncoder; - -/** State of the decoder. One decoder state is needed for each stream. - It is initialized once at the beginning of the stream. Do *not* - re-initialize the state for every frame. - @brief Decoder state - */ -typedef struct OpusCustomDecoder OpusCustomDecoder; - -/** The mode contains all the information necessary to create an - encoder. Both the encoder and decoder need to be initialized - with exactly the same mode, otherwise the output will be - corrupted. - @brief Mode configuration - */ -typedef struct OpusCustomMode OpusCustomMode; - -/** Creates a new mode struct. This will be passed to an encoder or - * decoder. The mode MUST NOT BE DESTROYED until the encoders and - * decoders that use it are destroyed as well. - * @param [in] Fs int: Sampling rate (8000 to 96000 Hz) - * @param [in] frame_size int: Number of samples (per channel) to encode in each - * packet (64 - 1024, prime factorization must contain zero or more 2s, 3s, or 5s and no other primes) - * @param [out] error int*: Returned error code (if NULL, no error will be returned) - * @return A newly created mode - */ -OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomMode *opus_custom_mode_create(opus_int32 Fs, int frame_size, int *error); - -/** Destroys a mode struct. Only call this after all encoders and - * decoders using this mode are destroyed as well. - * @param [in] mode OpusCustomMode*: Mode to be freed. - */ -OPUS_CUSTOM_EXPORT void opus_custom_mode_destroy(OpusCustomMode *mode); - - -#if !defined(OPUS_BUILD) || defined(CELT_ENCODER_C) - -/* Encoder */ -/** Gets the size of an OpusCustomEncoder structure. - * @param [in] mode OpusCustomMode *: Mode configuration - * @param [in] channels int: Number of channels - * @returns size - */ -OPUS_CUSTOM_EXPORT_STATIC OPUS_WARN_UNUSED_RESULT int opus_custom_encoder_get_size( - const OpusCustomMode *mode, - int channels -) OPUS_ARG_NONNULL(1); - -# ifdef CUSTOM_MODES -/** Initializes a previously allocated encoder state - * The memory pointed to by st must be the size returned by opus_custom_encoder_get_size. - * This is intended for applications which use their own allocator instead of malloc. - * @see opus_custom_encoder_create(),opus_custom_encoder_get_size() - * To reset a previously initialized state use the OPUS_RESET_STATE CTL. - * @param [in] st OpusCustomEncoder*: Encoder state - * @param [in] mode OpusCustomMode *: Contains all the information about the characteristics of - * the stream (must be the same characteristics as used for the - * decoder) - * @param [in] channels int: Number of channels - * @return OPUS_OK Success or @ref opus_errorcodes - */ -OPUS_CUSTOM_EXPORT int opus_custom_encoder_init( - OpusCustomEncoder *st, - const OpusCustomMode *mode, - int channels -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2); -# endif -#endif - - -/** Creates a new encoder state. Each stream needs its own encoder - * state (can't be shared across simultaneous streams). - * @param [in] mode OpusCustomMode*: Contains all the information about the characteristics of - * the stream (must be the same characteristics as used for the - * decoder) - * @param [in] channels int: Number of channels - * @param [out] error int*: Returns an error code - * @return Newly created encoder state. -*/ -OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomEncoder *opus_custom_encoder_create( - const OpusCustomMode *mode, - int channels, - int *error -) OPUS_ARG_NONNULL(1); - - -/** Destroys an encoder state. - * @param[in] st OpusCustomEncoder*: State to be freed. - */ -OPUS_CUSTOM_EXPORT void opus_custom_encoder_destroy(OpusCustomEncoder *st); - -/** Encodes a frame of audio. - * @param [in] st OpusCustomEncoder*: Encoder state - * @param [in] pcm float*: PCM audio in float format, with a normal range of +/-1.0. - * Samples with a range beyond +/-1.0 are supported but will - * be clipped by decoders using the integer API and should - * only be used if it is known that the far end supports - * extended dynamic range. There must be exactly - * frame_size samples per channel. - * @param [in] frame_size int: Number of samples per frame of input signal - * @param [out] compressed char *: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long. - * @param [in] maxCompressedBytes int: Maximum number of bytes to use for compressing the frame - * (can change from one frame to another) - * @return Number of bytes written to "compressed". - * If negative, an error has occurred (see error codes). It is IMPORTANT that - * the length returned be somehow transmitted to the decoder. Otherwise, no - * decoding is possible. - */ -OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_encode_float( - OpusCustomEncoder *st, - const float *pcm, - int frame_size, - unsigned char *compressed, - int maxCompressedBytes -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); - -/** Encodes a frame of audio. - * @param [in] st OpusCustomEncoder*: Encoder state - * @param [in] pcm opus_int16*: PCM audio in signed 16-bit format (native endian). - * There must be exactly frame_size samples per channel. - * @param [in] frame_size int: Number of samples per frame of input signal - * @param [out] compressed char *: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long. - * @param [in] maxCompressedBytes int: Maximum number of bytes to use for compressing the frame - * (can change from one frame to another) - * @return Number of bytes written to "compressed". - * If negative, an error has occurred (see error codes). It is IMPORTANT that - * the length returned be somehow transmitted to the decoder. Otherwise, no - * decoding is possible. - */ -OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_encode( - OpusCustomEncoder *st, - const opus_int16 *pcm, - int frame_size, - unsigned char *compressed, - int maxCompressedBytes -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); - -/** Perform a CTL function on an Opus custom encoder. - * - * Generally the request and subsequent arguments are generated - * by a convenience macro. - * @see opus_encoderctls - */ -OPUS_CUSTOM_EXPORT int opus_custom_encoder_ctl(OpusCustomEncoder * OPUS_RESTRICT st, int request, ...) OPUS_ARG_NONNULL(1); - - -#if !defined(OPUS_BUILD) || defined(CELT_DECODER_C) -/* Decoder */ - -/** Gets the size of an OpusCustomDecoder structure. - * @param [in] mode OpusCustomMode *: Mode configuration - * @param [in] channels int: Number of channels - * @returns size - */ -OPUS_CUSTOM_EXPORT_STATIC OPUS_WARN_UNUSED_RESULT int opus_custom_decoder_get_size( - const OpusCustomMode *mode, - int channels -) OPUS_ARG_NONNULL(1); - -/** Initializes a previously allocated decoder state - * The memory pointed to by st must be the size returned by opus_custom_decoder_get_size. - * This is intended for applications which use their own allocator instead of malloc. - * @see opus_custom_decoder_create(),opus_custom_decoder_get_size() - * To reset a previously initialized state use the OPUS_RESET_STATE CTL. - * @param [in] st OpusCustomDecoder*: Decoder state - * @param [in] mode OpusCustomMode *: Contains all the information about the characteristics of - * the stream (must be the same characteristics as used for the - * encoder) - * @param [in] channels int: Number of channels - * @return OPUS_OK Success or @ref opus_errorcodes - */ -OPUS_CUSTOM_EXPORT_STATIC int opus_custom_decoder_init( - OpusCustomDecoder *st, - const OpusCustomMode *mode, - int channels -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2); - -#endif - - -/** Creates a new decoder state. Each stream needs its own decoder state (can't - * be shared across simultaneous streams). - * @param [in] mode OpusCustomMode: Contains all the information about the characteristics of the - * stream (must be the same characteristics as used for the encoder) - * @param [in] channels int: Number of channels - * @param [out] error int*: Returns an error code - * @return Newly created decoder state. - */ -OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomDecoder *opus_custom_decoder_create( - const OpusCustomMode *mode, - int channels, - int *error -) OPUS_ARG_NONNULL(1); - -/** Destroys an decoder state. - * @param[in] st OpusCustomDecoder*: State to be freed. - */ -OPUS_CUSTOM_EXPORT void opus_custom_decoder_destroy(OpusCustomDecoder *st); - -/** Decode an opus custom frame with floating point output - * @param [in] st OpusCustomDecoder*: Decoder state - * @param [in] data char*: Input payload. Use a NULL pointer to indicate packet loss - * @param [in] len int: Number of bytes in payload - * @param [out] pcm float*: Output signal (interleaved if 2 channels). length - * is frame_size*channels*sizeof(float) - * @param [in] frame_size Number of samples per channel of available space in *pcm. - * @returns Number of decoded samples or @ref opus_errorcodes - */ -OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_decode_float( - OpusCustomDecoder *st, - const unsigned char *data, - int len, - float *pcm, - int frame_size -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - -/** Decode an opus custom frame - * @param [in] st OpusCustomDecoder*: Decoder state - * @param [in] data char*: Input payload. Use a NULL pointer to indicate packet loss - * @param [in] len int: Number of bytes in payload - * @param [out] pcm opus_int16*: Output signal (interleaved if 2 channels). length - * is frame_size*channels*sizeof(opus_int16) - * @param [in] frame_size Number of samples per channel of available space in *pcm. - * @returns Number of decoded samples or @ref opus_errorcodes - */ -OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_decode( - OpusCustomDecoder *st, - const unsigned char *data, - int len, - opus_int16 *pcm, - int frame_size -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - -/** Perform a CTL function on an Opus custom decoder. - * - * Generally the request and subsequent arguments are generated - * by a convenience macro. - * @see opus_genericctls - */ -OPUS_CUSTOM_EXPORT int opus_custom_decoder_ctl(OpusCustomDecoder * OPUS_RESTRICT st, int request, ...) OPUS_ARG_NONNULL(1); - -/**@}*/ - -#ifdef __cplusplus -} -#endif - -#endif /* OPUS_CUSTOM_H */ diff --git a/include/opus_defines.h b/include/opus_defines.h deleted file mode 100644 index 0e05cb54daf..00000000000 --- a/include/opus_defines.h +++ /dev/null @@ -1,799 +0,0 @@ -/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited - Written by Jean-Marc Valin and Koen Vos */ -/* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * @file opus_defines.h - * @brief Opus reference implementation constants - */ - -#ifndef OPUS_DEFINES_H -#define OPUS_DEFINES_H - -#include "opus_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** @defgroup opus_errorcodes Error codes - * @{ - */ -/** No error @hideinitializer*/ -#define OPUS_OK 0 -/** One or more invalid/out of range arguments @hideinitializer*/ -#define OPUS_BAD_ARG -1 -/** Not enough bytes allocated in the buffer @hideinitializer*/ -#define OPUS_BUFFER_TOO_SMALL -2 -/** An internal error was detected @hideinitializer*/ -#define OPUS_INTERNAL_ERROR -3 -/** The compressed data passed is corrupted @hideinitializer*/ -#define OPUS_INVALID_PACKET -4 -/** Invalid/unsupported request number @hideinitializer*/ -#define OPUS_UNIMPLEMENTED -5 -/** An encoder or decoder structure is invalid or already freed @hideinitializer*/ -#define OPUS_INVALID_STATE -6 -/** Memory allocation has failed @hideinitializer*/ -#define OPUS_ALLOC_FAIL -7 -/**@}*/ - -/** @cond OPUS_INTERNAL_DOC */ -/**Export control for opus functions */ - -#ifndef OPUS_EXPORT -# if defined(WIN32) -# if defined(OPUS_BUILD) && defined(DLL_EXPORT) -# define OPUS_EXPORT __declspec(dllexport) -# else -# define OPUS_EXPORT -# endif -# elif defined(__GNUC__) && defined(OPUS_BUILD) -# define OPUS_EXPORT __attribute__ ((visibility ("default"))) -# else -# define OPUS_EXPORT -# endif -#endif - -# if !defined(OPUS_GNUC_PREREQ) -# if defined(__GNUC__)&&defined(__GNUC_MINOR__) -# define OPUS_GNUC_PREREQ(_maj,_min) \ - ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min)) -# else -# define OPUS_GNUC_PREREQ(_maj,_min) 0 -# endif -# endif - -#if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) -# if OPUS_GNUC_PREREQ(3,0) -# define OPUS_RESTRICT __restrict__ -# elif (defined(_MSC_VER) && _MSC_VER >= 1400) -# define OPUS_RESTRICT __restrict -# else -# define OPUS_RESTRICT -# endif -#else -# define OPUS_RESTRICT restrict -#endif - -#if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) ) -# if OPUS_GNUC_PREREQ(2,7) -# define OPUS_INLINE __inline__ -# elif (defined(_MSC_VER)) -# define OPUS_INLINE __inline -# else -# define OPUS_INLINE -# endif -#else -# define OPUS_INLINE inline -#endif - -/**Warning attributes for opus functions - * NONNULL is not used in OPUS_BUILD to avoid the compiler optimizing out - * some paranoid null checks. */ -#if defined(__GNUC__) && OPUS_GNUC_PREREQ(3, 4) -# define OPUS_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__)) -#else -# define OPUS_WARN_UNUSED_RESULT -#endif -#if !defined(OPUS_BUILD) && defined(__GNUC__) && OPUS_GNUC_PREREQ(3, 4) -# define OPUS_ARG_NONNULL(_x) __attribute__ ((__nonnull__(_x))) -#else -# define OPUS_ARG_NONNULL(_x) -#endif - -/** These are the actual Encoder CTL ID numbers. - * They should not be used directly by applications. - * In general, SETs should be even and GETs should be odd.*/ -#define OPUS_SET_APPLICATION_REQUEST 4000 -#define OPUS_GET_APPLICATION_REQUEST 4001 -#define OPUS_SET_BITRATE_REQUEST 4002 -#define OPUS_GET_BITRATE_REQUEST 4003 -#define OPUS_SET_MAX_BANDWIDTH_REQUEST 4004 -#define OPUS_GET_MAX_BANDWIDTH_REQUEST 4005 -#define OPUS_SET_VBR_REQUEST 4006 -#define OPUS_GET_VBR_REQUEST 4007 -#define OPUS_SET_BANDWIDTH_REQUEST 4008 -#define OPUS_GET_BANDWIDTH_REQUEST 4009 -#define OPUS_SET_COMPLEXITY_REQUEST 4010 -#define OPUS_GET_COMPLEXITY_REQUEST 4011 -#define OPUS_SET_INBAND_FEC_REQUEST 4012 -#define OPUS_GET_INBAND_FEC_REQUEST 4013 -#define OPUS_SET_PACKET_LOSS_PERC_REQUEST 4014 -#define OPUS_GET_PACKET_LOSS_PERC_REQUEST 4015 -#define OPUS_SET_DTX_REQUEST 4016 -#define OPUS_GET_DTX_REQUEST 4017 -#define OPUS_SET_VBR_CONSTRAINT_REQUEST 4020 -#define OPUS_GET_VBR_CONSTRAINT_REQUEST 4021 -#define OPUS_SET_FORCE_CHANNELS_REQUEST 4022 -#define OPUS_GET_FORCE_CHANNELS_REQUEST 4023 -#define OPUS_SET_SIGNAL_REQUEST 4024 -#define OPUS_GET_SIGNAL_REQUEST 4025 -#define OPUS_GET_LOOKAHEAD_REQUEST 4027 -/* #define OPUS_RESET_STATE 4028 */ -#define OPUS_GET_SAMPLE_RATE_REQUEST 4029 -#define OPUS_GET_FINAL_RANGE_REQUEST 4031 -#define OPUS_GET_PITCH_REQUEST 4033 -#define OPUS_SET_GAIN_REQUEST 4034 -#define OPUS_GET_GAIN_REQUEST 4045 /* Should have been 4035 */ -#define OPUS_SET_LSB_DEPTH_REQUEST 4036 -#define OPUS_GET_LSB_DEPTH_REQUEST 4037 -#define OPUS_GET_LAST_PACKET_DURATION_REQUEST 4039 -#define OPUS_SET_EXPERT_FRAME_DURATION_REQUEST 4040 -#define OPUS_GET_EXPERT_FRAME_DURATION_REQUEST 4041 -#define OPUS_SET_PREDICTION_DISABLED_REQUEST 4042 -#define OPUS_GET_PREDICTION_DISABLED_REQUEST 4043 -/* Don't use 4045, it's already taken by OPUS_GET_GAIN_REQUEST */ -#define OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST 4046 -#define OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST 4047 -#define OPUS_GET_IN_DTX_REQUEST 4049 - -/** Defines for the presence of extended APIs. */ -#define OPUS_HAVE_OPUS_PROJECTION_H - -/* Macros to trigger compilation errors when the wrong types are provided to a CTL */ -#define __opus_check_int(x) (((void)((x) == (opus_int32)0)), (opus_int32)(x)) -#define __opus_check_int_ptr(ptr) ((ptr) + ((ptr) - (opus_int32*)(ptr))) -#define __opus_check_uint_ptr(ptr) ((ptr) + ((ptr) - (opus_uint32*)(ptr))) -#define __opus_check_val16_ptr(ptr) ((ptr) + ((ptr) - (opus_val16*)(ptr))) -/** @endcond */ - -/** @defgroup opus_ctlvalues Pre-defined values for CTL interface - * @see opus_genericctls, opus_encoderctls - * @{ - */ -/* Values for the various encoder CTLs */ -#define OPUS_AUTO -1000 /**opus_int32: Allowed values: 0-10, inclusive. - * - * @hideinitializer */ -#define OPUS_SET_COMPLEXITY(x) OPUS_SET_COMPLEXITY_REQUEST, __opus_check_int(x) -/** Gets the encoder's complexity configuration. - * @see OPUS_SET_COMPLEXITY - * @param[out] x opus_int32 *: Returns a value in the range 0-10, - * inclusive. - * @hideinitializer */ -#define OPUS_GET_COMPLEXITY(x) OPUS_GET_COMPLEXITY_REQUEST, __opus_check_int_ptr(x) - -/** Configures the bitrate in the encoder. - * Rates from 500 to 512000 bits per second are meaningful, as well as the - * special values #OPUS_AUTO and #OPUS_BITRATE_MAX. - * The value #OPUS_BITRATE_MAX can be used to cause the codec to use as much - * rate as it can, which is useful for controlling the rate by adjusting the - * output buffer size. - * @see OPUS_GET_BITRATE - * @param[in] x opus_int32: Bitrate in bits per second. The default - * is determined based on the number of - * channels and the input sampling rate. - * @hideinitializer */ -#define OPUS_SET_BITRATE(x) OPUS_SET_BITRATE_REQUEST, __opus_check_int(x) -/** Gets the encoder's bitrate configuration. - * @see OPUS_SET_BITRATE - * @param[out] x opus_int32 *: Returns the bitrate in bits per second. - * The default is determined based on the - * number of channels and the input - * sampling rate. - * @hideinitializer */ -#define OPUS_GET_BITRATE(x) OPUS_GET_BITRATE_REQUEST, __opus_check_int_ptr(x) - -/** Enables or disables variable bitrate (VBR) in the encoder. - * The configured bitrate may not be met exactly because frames must - * be an integer number of bytes in length. - * @see OPUS_GET_VBR - * @see OPUS_SET_VBR_CONSTRAINT - * @param[in] x opus_int32: Allowed values: - *
- *
0
Hard CBR. For LPC/hybrid modes at very low bit-rate, this can - * cause noticeable quality degradation.
- *
1
VBR (default). The exact type of VBR is controlled by - * #OPUS_SET_VBR_CONSTRAINT.
- *
- * @hideinitializer */ -#define OPUS_SET_VBR(x) OPUS_SET_VBR_REQUEST, __opus_check_int(x) -/** Determine if variable bitrate (VBR) is enabled in the encoder. - * @see OPUS_SET_VBR - * @see OPUS_GET_VBR_CONSTRAINT - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
0
Hard CBR.
- *
1
VBR (default). The exact type of VBR may be retrieved via - * #OPUS_GET_VBR_CONSTRAINT.
- *
- * @hideinitializer */ -#define OPUS_GET_VBR(x) OPUS_GET_VBR_REQUEST, __opus_check_int_ptr(x) - -/** Enables or disables constrained VBR in the encoder. - * This setting is ignored when the encoder is in CBR mode. - * @warning Only the MDCT mode of Opus currently heeds the constraint. - * Speech mode ignores it completely, hybrid mode may fail to obey it - * if the LPC layer uses more bitrate than the constraint would have - * permitted. - * @see OPUS_GET_VBR_CONSTRAINT - * @see OPUS_SET_VBR - * @param[in] x opus_int32: Allowed values: - *
- *
0
Unconstrained VBR.
- *
1
Constrained VBR (default). This creates a maximum of one - * frame of buffering delay assuming a transport with a - * serialization speed of the nominal bitrate.
- *
- * @hideinitializer */ -#define OPUS_SET_VBR_CONSTRAINT(x) OPUS_SET_VBR_CONSTRAINT_REQUEST, __opus_check_int(x) -/** Determine if constrained VBR is enabled in the encoder. - * @see OPUS_SET_VBR_CONSTRAINT - * @see OPUS_GET_VBR - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
0
Unconstrained VBR.
- *
1
Constrained VBR (default).
- *
- * @hideinitializer */ -#define OPUS_GET_VBR_CONSTRAINT(x) OPUS_GET_VBR_CONSTRAINT_REQUEST, __opus_check_int_ptr(x) - -/** Configures mono/stereo forcing in the encoder. - * This can force the encoder to produce packets encoded as either mono or - * stereo, regardless of the format of the input audio. This is useful when - * the caller knows that the input signal is currently a mono source embedded - * in a stereo stream. - * @see OPUS_GET_FORCE_CHANNELS - * @param[in] x opus_int32: Allowed values: - *
- *
#OPUS_AUTO
Not forced (default)
- *
1
Forced mono
- *
2
Forced stereo
- *
- * @hideinitializer */ -#define OPUS_SET_FORCE_CHANNELS(x) OPUS_SET_FORCE_CHANNELS_REQUEST, __opus_check_int(x) -/** Gets the encoder's forced channel configuration. - * @see OPUS_SET_FORCE_CHANNELS - * @param[out] x opus_int32 *: - *
- *
#OPUS_AUTO
Not forced (default)
- *
1
Forced mono
- *
2
Forced stereo
- *
- * @hideinitializer */ -#define OPUS_GET_FORCE_CHANNELS(x) OPUS_GET_FORCE_CHANNELS_REQUEST, __opus_check_int_ptr(x) - -/** Configures the maximum bandpass that the encoder will select automatically. - * Applications should normally use this instead of #OPUS_SET_BANDWIDTH - * (leaving that set to the default, #OPUS_AUTO). This allows the - * application to set an upper bound based on the type of input it is - * providing, but still gives the encoder the freedom to reduce the bandpass - * when the bitrate becomes too low, for better overall quality. - * @see OPUS_GET_MAX_BANDWIDTH - * @param[in] x opus_int32: Allowed values: - *
- *
OPUS_BANDWIDTH_NARROWBAND
4 kHz passband
- *
OPUS_BANDWIDTH_MEDIUMBAND
6 kHz passband
- *
OPUS_BANDWIDTH_WIDEBAND
8 kHz passband
- *
OPUS_BANDWIDTH_SUPERWIDEBAND
12 kHz passband
- *
OPUS_BANDWIDTH_FULLBAND
20 kHz passband (default)
- *
- * @hideinitializer */ -#define OPUS_SET_MAX_BANDWIDTH(x) OPUS_SET_MAX_BANDWIDTH_REQUEST, __opus_check_int(x) - -/** Gets the encoder's configured maximum allowed bandpass. - * @see OPUS_SET_MAX_BANDWIDTH - * @param[out] x opus_int32 *: Allowed values: - *
- *
#OPUS_BANDWIDTH_NARROWBAND
4 kHz passband
- *
#OPUS_BANDWIDTH_MEDIUMBAND
6 kHz passband
- *
#OPUS_BANDWIDTH_WIDEBAND
8 kHz passband
- *
#OPUS_BANDWIDTH_SUPERWIDEBAND
12 kHz passband
- *
#OPUS_BANDWIDTH_FULLBAND
20 kHz passband (default)
- *
- * @hideinitializer */ -#define OPUS_GET_MAX_BANDWIDTH(x) OPUS_GET_MAX_BANDWIDTH_REQUEST, __opus_check_int_ptr(x) - -/** Sets the encoder's bandpass to a specific value. - * This prevents the encoder from automatically selecting the bandpass based - * on the available bitrate. If an application knows the bandpass of the input - * audio it is providing, it should normally use #OPUS_SET_MAX_BANDWIDTH - * instead, which still gives the encoder the freedom to reduce the bandpass - * when the bitrate becomes too low, for better overall quality. - * @see OPUS_GET_BANDWIDTH - * @param[in] x opus_int32: Allowed values: - *
- *
#OPUS_AUTO
(default)
- *
#OPUS_BANDWIDTH_NARROWBAND
4 kHz passband
- *
#OPUS_BANDWIDTH_MEDIUMBAND
6 kHz passband
- *
#OPUS_BANDWIDTH_WIDEBAND
8 kHz passband
- *
#OPUS_BANDWIDTH_SUPERWIDEBAND
12 kHz passband
- *
#OPUS_BANDWIDTH_FULLBAND
20 kHz passband
- *
- * @hideinitializer */ -#define OPUS_SET_BANDWIDTH(x) OPUS_SET_BANDWIDTH_REQUEST, __opus_check_int(x) - -/** Configures the type of signal being encoded. - * This is a hint which helps the encoder's mode selection. - * @see OPUS_GET_SIGNAL - * @param[in] x opus_int32: Allowed values: - *
- *
#OPUS_AUTO
(default)
- *
#OPUS_SIGNAL_VOICE
Bias thresholds towards choosing LPC or Hybrid modes.
- *
#OPUS_SIGNAL_MUSIC
Bias thresholds towards choosing MDCT modes.
- *
- * @hideinitializer */ -#define OPUS_SET_SIGNAL(x) OPUS_SET_SIGNAL_REQUEST, __opus_check_int(x) -/** Gets the encoder's configured signal type. - * @see OPUS_SET_SIGNAL - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
#OPUS_AUTO
(default)
- *
#OPUS_SIGNAL_VOICE
Bias thresholds towards choosing LPC or Hybrid modes.
- *
#OPUS_SIGNAL_MUSIC
Bias thresholds towards choosing MDCT modes.
- *
- * @hideinitializer */ -#define OPUS_GET_SIGNAL(x) OPUS_GET_SIGNAL_REQUEST, __opus_check_int_ptr(x) - - -/** Configures the encoder's intended application. - * The initial value is a mandatory argument to the encoder_create function. - * @see OPUS_GET_APPLICATION - * @param[in] x opus_int32: Returns one of the following values: - *
- *
#OPUS_APPLICATION_VOIP
- *
Process signal for improved speech intelligibility.
- *
#OPUS_APPLICATION_AUDIO
- *
Favor faithfulness to the original input.
- *
#OPUS_APPLICATION_RESTRICTED_LOWDELAY
- *
Configure the minimum possible coding delay by disabling certain modes - * of operation.
- *
- * @hideinitializer */ -#define OPUS_SET_APPLICATION(x) OPUS_SET_APPLICATION_REQUEST, __opus_check_int(x) -/** Gets the encoder's configured application. - * @see OPUS_SET_APPLICATION - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
#OPUS_APPLICATION_VOIP
- *
Process signal for improved speech intelligibility.
- *
#OPUS_APPLICATION_AUDIO
- *
Favor faithfulness to the original input.
- *
#OPUS_APPLICATION_RESTRICTED_LOWDELAY
- *
Configure the minimum possible coding delay by disabling certain modes - * of operation.
- *
- * @hideinitializer */ -#define OPUS_GET_APPLICATION(x) OPUS_GET_APPLICATION_REQUEST, __opus_check_int_ptr(x) - -/** Gets the total samples of delay added by the entire codec. - * This can be queried by the encoder and then the provided number of samples can be - * skipped on from the start of the decoder's output to provide time aligned input - * and output. From the perspective of a decoding application the real data begins this many - * samples late. - * - * The decoder contribution to this delay is identical for all decoders, but the - * encoder portion of the delay may vary from implementation to implementation, - * version to version, or even depend on the encoder's initial configuration. - * Applications needing delay compensation should call this CTL rather than - * hard-coding a value. - * @param[out] x opus_int32 *: Number of lookahead samples - * @hideinitializer */ -#define OPUS_GET_LOOKAHEAD(x) OPUS_GET_LOOKAHEAD_REQUEST, __opus_check_int_ptr(x) - -/** Configures the encoder's use of inband forward error correction (FEC). - * @note This is only applicable to the LPC layer - * @see OPUS_GET_INBAND_FEC - * @param[in] x opus_int32: Allowed values: - *
- *
0
Disable inband FEC (default).
- *
1
Enable inband FEC.
- *
- * @hideinitializer */ -#define OPUS_SET_INBAND_FEC(x) OPUS_SET_INBAND_FEC_REQUEST, __opus_check_int(x) -/** Gets encoder's configured use of inband forward error correction. - * @see OPUS_SET_INBAND_FEC - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
0
Inband FEC disabled (default).
- *
1
Inband FEC enabled.
- *
- * @hideinitializer */ -#define OPUS_GET_INBAND_FEC(x) OPUS_GET_INBAND_FEC_REQUEST, __opus_check_int_ptr(x) - -/** Configures the encoder's expected packet loss percentage. - * Higher values trigger progressively more loss resistant behavior in the encoder - * at the expense of quality at a given bitrate in the absence of packet loss, but - * greater quality under loss. - * @see OPUS_GET_PACKET_LOSS_PERC - * @param[in] x opus_int32: Loss percentage in the range 0-100, inclusive (default: 0). - * @hideinitializer */ -#define OPUS_SET_PACKET_LOSS_PERC(x) OPUS_SET_PACKET_LOSS_PERC_REQUEST, __opus_check_int(x) -/** Gets the encoder's configured packet loss percentage. - * @see OPUS_SET_PACKET_LOSS_PERC - * @param[out] x opus_int32 *: Returns the configured loss percentage - * in the range 0-100, inclusive (default: 0). - * @hideinitializer */ -#define OPUS_GET_PACKET_LOSS_PERC(x) OPUS_GET_PACKET_LOSS_PERC_REQUEST, __opus_check_int_ptr(x) - -/** Configures the encoder's use of discontinuous transmission (DTX). - * @note This is only applicable to the LPC layer - * @see OPUS_GET_DTX - * @param[in] x opus_int32: Allowed values: - *
- *
0
Disable DTX (default).
- *
1
Enabled DTX.
- *
- * @hideinitializer */ -#define OPUS_SET_DTX(x) OPUS_SET_DTX_REQUEST, __opus_check_int(x) -/** Gets encoder's configured use of discontinuous transmission. - * @see OPUS_SET_DTX - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
0
DTX disabled (default).
- *
1
DTX enabled.
- *
- * @hideinitializer */ -#define OPUS_GET_DTX(x) OPUS_GET_DTX_REQUEST, __opus_check_int_ptr(x) -/** Configures the depth of signal being encoded. - * - * This is a hint which helps the encoder identify silence and near-silence. - * It represents the number of significant bits of linear intensity below - * which the signal contains ignorable quantization or other noise. - * - * For example, OPUS_SET_LSB_DEPTH(14) would be an appropriate setting - * for G.711 u-law input. OPUS_SET_LSB_DEPTH(16) would be appropriate - * for 16-bit linear pcm input with opus_encode_float(). - * - * When using opus_encode() instead of opus_encode_float(), or when libopus - * is compiled for fixed-point, the encoder uses the minimum of the value - * set here and the value 16. - * - * @see OPUS_GET_LSB_DEPTH - * @param[in] x opus_int32: Input precision in bits, between 8 and 24 - * (default: 24). - * @hideinitializer */ -#define OPUS_SET_LSB_DEPTH(x) OPUS_SET_LSB_DEPTH_REQUEST, __opus_check_int(x) -/** Gets the encoder's configured signal depth. - * @see OPUS_SET_LSB_DEPTH - * @param[out] x opus_int32 *: Input precision in bits, between 8 and - * 24 (default: 24). - * @hideinitializer */ -#define OPUS_GET_LSB_DEPTH(x) OPUS_GET_LSB_DEPTH_REQUEST, __opus_check_int_ptr(x) - -/** Configures the encoder's use of variable duration frames. - * When variable duration is enabled, the encoder is free to use a shorter frame - * size than the one requested in the opus_encode*() call. - * It is then the user's responsibility - * to verify how much audio was encoded by checking the ToC byte of the encoded - * packet. The part of the audio that was not encoded needs to be resent to the - * encoder for the next call. Do not use this option unless you really - * know what you are doing. - * @see OPUS_GET_EXPERT_FRAME_DURATION - * @param[in] x opus_int32: Allowed values: - *
- *
OPUS_FRAMESIZE_ARG
Select frame size from the argument (default).
- *
OPUS_FRAMESIZE_2_5_MS
Use 2.5 ms frames.
- *
OPUS_FRAMESIZE_5_MS
Use 5 ms frames.
- *
OPUS_FRAMESIZE_10_MS
Use 10 ms frames.
- *
OPUS_FRAMESIZE_20_MS
Use 20 ms frames.
- *
OPUS_FRAMESIZE_40_MS
Use 40 ms frames.
- *
OPUS_FRAMESIZE_60_MS
Use 60 ms frames.
- *
OPUS_FRAMESIZE_80_MS
Use 80 ms frames.
- *
OPUS_FRAMESIZE_100_MS
Use 100 ms frames.
- *
OPUS_FRAMESIZE_120_MS
Use 120 ms frames.
- *
- * @hideinitializer */ -#define OPUS_SET_EXPERT_FRAME_DURATION(x) OPUS_SET_EXPERT_FRAME_DURATION_REQUEST, __opus_check_int(x) -/** Gets the encoder's configured use of variable duration frames. - * @see OPUS_SET_EXPERT_FRAME_DURATION - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
OPUS_FRAMESIZE_ARG
Select frame size from the argument (default).
- *
OPUS_FRAMESIZE_2_5_MS
Use 2.5 ms frames.
- *
OPUS_FRAMESIZE_5_MS
Use 5 ms frames.
- *
OPUS_FRAMESIZE_10_MS
Use 10 ms frames.
- *
OPUS_FRAMESIZE_20_MS
Use 20 ms frames.
- *
OPUS_FRAMESIZE_40_MS
Use 40 ms frames.
- *
OPUS_FRAMESIZE_60_MS
Use 60 ms frames.
- *
OPUS_FRAMESIZE_80_MS
Use 80 ms frames.
- *
OPUS_FRAMESIZE_100_MS
Use 100 ms frames.
- *
OPUS_FRAMESIZE_120_MS
Use 120 ms frames.
- *
- * @hideinitializer */ -#define OPUS_GET_EXPERT_FRAME_DURATION(x) OPUS_GET_EXPERT_FRAME_DURATION_REQUEST, __opus_check_int_ptr(x) - -/** If set to 1, disables almost all use of prediction, making frames almost - * completely independent. This reduces quality. - * @see OPUS_GET_PREDICTION_DISABLED - * @param[in] x opus_int32: Allowed values: - *
- *
0
Enable prediction (default).
- *
1
Disable prediction.
- *
- * @hideinitializer */ -#define OPUS_SET_PREDICTION_DISABLED(x) OPUS_SET_PREDICTION_DISABLED_REQUEST, __opus_check_int(x) -/** Gets the encoder's configured prediction status. - * @see OPUS_SET_PREDICTION_DISABLED - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
0
Prediction enabled (default).
- *
1
Prediction disabled.
- *
- * @hideinitializer */ -#define OPUS_GET_PREDICTION_DISABLED(x) OPUS_GET_PREDICTION_DISABLED_REQUEST, __opus_check_int_ptr(x) - -/**@}*/ - -/** @defgroup opus_genericctls Generic CTLs - * - * These macros are used with the \c opus_decoder_ctl and - * \c opus_encoder_ctl calls to generate a particular - * request. - * - * When called on an \c OpusDecoder they apply to that - * particular decoder instance. When called on an - * \c OpusEncoder they apply to the corresponding setting - * on that encoder instance, if present. - * - * Some usage examples: - * - * @code - * int ret; - * opus_int32 pitch; - * ret = opus_decoder_ctl(dec_ctx, OPUS_GET_PITCH(&pitch)); - * if (ret == OPUS_OK) return ret; - * - * opus_encoder_ctl(enc_ctx, OPUS_RESET_STATE); - * opus_decoder_ctl(dec_ctx, OPUS_RESET_STATE); - * - * opus_int32 enc_bw, dec_bw; - * opus_encoder_ctl(enc_ctx, OPUS_GET_BANDWIDTH(&enc_bw)); - * opus_decoder_ctl(dec_ctx, OPUS_GET_BANDWIDTH(&dec_bw)); - * if (enc_bw != dec_bw) { - * printf("packet bandwidth mismatch!\n"); - * } - * @endcode - * - * @see opus_encoder, opus_decoder_ctl, opus_encoder_ctl, opus_decoderctls, opus_encoderctls - * @{ - */ - -/** Resets the codec state to be equivalent to a freshly initialized state. - * This should be called when switching streams in order to prevent - * the back to back decoding from giving different results from - * one at a time decoding. - * @hideinitializer */ -#define OPUS_RESET_STATE 4028 - -/** Gets the final state of the codec's entropy coder. - * This is used for testing purposes, - * The encoder and decoder state should be identical after coding a payload - * (assuming no data corruption or software bugs) - * - * @param[out] x opus_uint32 *: Entropy coder state - * - * @hideinitializer */ -#define OPUS_GET_FINAL_RANGE(x) OPUS_GET_FINAL_RANGE_REQUEST, __opus_check_uint_ptr(x) - -/** Gets the encoder's configured bandpass or the decoder's last bandpass. - * @see OPUS_SET_BANDWIDTH - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
#OPUS_AUTO
(default)
- *
#OPUS_BANDWIDTH_NARROWBAND
4 kHz passband
- *
#OPUS_BANDWIDTH_MEDIUMBAND
6 kHz passband
- *
#OPUS_BANDWIDTH_WIDEBAND
8 kHz passband
- *
#OPUS_BANDWIDTH_SUPERWIDEBAND
12 kHz passband
- *
#OPUS_BANDWIDTH_FULLBAND
20 kHz passband
- *
- * @hideinitializer */ -#define OPUS_GET_BANDWIDTH(x) OPUS_GET_BANDWIDTH_REQUEST, __opus_check_int_ptr(x) - -/** Gets the sampling rate the encoder or decoder was initialized with. - * This simply returns the Fs value passed to opus_encoder_init() - * or opus_decoder_init(). - * @param[out] x opus_int32 *: Sampling rate of encoder or decoder. - * @hideinitializer - */ -#define OPUS_GET_SAMPLE_RATE(x) OPUS_GET_SAMPLE_RATE_REQUEST, __opus_check_int_ptr(x) - -/** If set to 1, disables the use of phase inversion for intensity stereo, - * improving the quality of mono downmixes, but slightly reducing normal - * stereo quality. Disabling phase inversion in the decoder does not comply - * with RFC 6716, although it does not cause any interoperability issue and - * is expected to become part of the Opus standard once RFC 6716 is updated - * by draft-ietf-codec-opus-update. - * @see OPUS_GET_PHASE_INVERSION_DISABLED - * @param[in] x opus_int32: Allowed values: - *
- *
0
Enable phase inversion (default).
- *
1
Disable phase inversion.
- *
- * @hideinitializer */ -#define OPUS_SET_PHASE_INVERSION_DISABLED(x) OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST, __opus_check_int(x) -/** Gets the encoder's configured phase inversion status. - * @see OPUS_SET_PHASE_INVERSION_DISABLED - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
0
Stereo phase inversion enabled (default).
- *
1
Stereo phase inversion disabled.
- *
- * @hideinitializer */ -#define OPUS_GET_PHASE_INVERSION_DISABLED(x) OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST, __opus_check_int_ptr(x) -/** Gets the DTX state of the encoder. - * Returns whether the last encoded frame was either a comfort noise update - * during DTX or not encoded because of DTX. - * @param[out] x opus_int32 *: Returns one of the following values: - *
- *
0
The encoder is not in DTX.
- *
1
The encoder is in DTX.
- *
- * @hideinitializer */ -#define OPUS_GET_IN_DTX(x) OPUS_GET_IN_DTX_REQUEST, __opus_check_int_ptr(x) - -/**@}*/ - -/** @defgroup opus_decoderctls Decoder related CTLs - * @see opus_genericctls, opus_encoderctls, opus_decoder - * @{ - */ - -/** Configures decoder gain adjustment. - * Scales the decoded output by a factor specified in Q8 dB units. - * This has a maximum range of -32768 to 32767 inclusive, and returns - * OPUS_BAD_ARG otherwise. The default is zero indicating no adjustment. - * This setting survives decoder reset. - * - * gain = pow(10, x/(20.0*256)) - * - * @param[in] x opus_int32: Amount to scale PCM signal by in Q8 dB units. - * @hideinitializer */ -#define OPUS_SET_GAIN(x) OPUS_SET_GAIN_REQUEST, __opus_check_int(x) -/** Gets the decoder's configured gain adjustment. @see OPUS_SET_GAIN - * - * @param[out] x opus_int32 *: Amount to scale PCM signal by in Q8 dB units. - * @hideinitializer */ -#define OPUS_GET_GAIN(x) OPUS_GET_GAIN_REQUEST, __opus_check_int_ptr(x) - -/** Gets the duration (in samples) of the last packet successfully decoded or concealed. - * @param[out] x opus_int32 *: Number of samples (at current sampling rate). - * @hideinitializer */ -#define OPUS_GET_LAST_PACKET_DURATION(x) OPUS_GET_LAST_PACKET_DURATION_REQUEST, __opus_check_int_ptr(x) - -/** Gets the pitch of the last decoded frame, if available. - * This can be used for any post-processing algorithm requiring the use of pitch, - * e.g. time stretching/shortening. If the last frame was not voiced, or if the - * pitch was not coded in the frame, then zero is returned. - * - * This CTL is only implemented for decoder instances. - * - * @param[out] x opus_int32 *: pitch period at 48 kHz (or 0 if not available) - * - * @hideinitializer */ -#define OPUS_GET_PITCH(x) OPUS_GET_PITCH_REQUEST, __opus_check_int_ptr(x) - -/**@}*/ - -/** @defgroup opus_libinfo Opus library information functions - * @{ - */ - -/** Converts an opus error code into a human readable string. - * - * @param[in] error int: Error number - * @returns Error string - */ -OPUS_EXPORT const char *opus_strerror(int error); - -/** Gets the libopus version string. - * - * Applications may look for the substring "-fixed" in the version string to - * determine whether they have a fixed-point or floating-point build at - * runtime. - * - * @returns Version string - */ -OPUS_EXPORT const char *opus_get_version_string(void); -/**@}*/ - -#ifdef __cplusplus -} -#endif - -#endif /* OPUS_DEFINES_H */ diff --git a/include/opus_multistream.h b/include/opus_multistream.h deleted file mode 100644 index fceab87d7e1..00000000000 --- a/include/opus_multistream.h +++ /dev/null @@ -1,660 +0,0 @@ -/* Copyright (c) 2011 Xiph.Org Foundation - Written by Jean-Marc Valin */ -/* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * @file opus_multistream.h - * @brief Opus reference implementation multistream API - */ - -#ifndef OPUS_MULTISTREAM_H -#define OPUS_MULTISTREAM_H - -#include "opus.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** @cond OPUS_INTERNAL_DOC */ - -/** Macros to trigger compilation errors when the wrong types are provided to a - * CTL. */ -/**@{*/ -#define __opus_check_encstate_ptr(ptr) ((ptr) + ((ptr) - (OpusEncoder**)(ptr))) -#define __opus_check_decstate_ptr(ptr) ((ptr) + ((ptr) - (OpusDecoder**)(ptr))) -/**@}*/ - -/** These are the actual encoder and decoder CTL ID numbers. - * They should not be used directly by applications. - * In general, SETs should be even and GETs should be odd.*/ -/**@{*/ -#define OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST 5120 -#define OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST 5122 -/**@}*/ - -/** @endcond */ - -/** @defgroup opus_multistream_ctls Multistream specific encoder and decoder CTLs - * - * These are convenience macros that are specific to the - * opus_multistream_encoder_ctl() and opus_multistream_decoder_ctl() - * interface. - * The CTLs from @ref opus_genericctls, @ref opus_encoderctls, and - * @ref opus_decoderctls may be applied to a multistream encoder or decoder as - * well. - * In addition, you may retrieve the encoder or decoder state for an specific - * stream via #OPUS_MULTISTREAM_GET_ENCODER_STATE or - * #OPUS_MULTISTREAM_GET_DECODER_STATE and apply CTLs to it individually. - */ -/**@{*/ - -/** Gets the encoder state for an individual stream of a multistream encoder. - * @param[in] x opus_int32: The index of the stream whose encoder you - * wish to retrieve. - * This must be non-negative and less than - * the streams parameter used - * to initialize the encoder. - * @param[out] y OpusEncoder**: Returns a pointer to the given - * encoder state. - * @retval OPUS_BAD_ARG The index of the requested stream was out of range. - * @hideinitializer - */ -#define OPUS_MULTISTREAM_GET_ENCODER_STATE(x,y) OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST, __opus_check_int(x), __opus_check_encstate_ptr(y) - -/** Gets the decoder state for an individual stream of a multistream decoder. - * @param[in] x opus_int32: The index of the stream whose decoder you - * wish to retrieve. - * This must be non-negative and less than - * the streams parameter used - * to initialize the decoder. - * @param[out] y OpusDecoder**: Returns a pointer to the given - * decoder state. - * @retval OPUS_BAD_ARG The index of the requested stream was out of range. - * @hideinitializer - */ -#define OPUS_MULTISTREAM_GET_DECODER_STATE(x,y) OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST, __opus_check_int(x), __opus_check_decstate_ptr(y) - -/**@}*/ - -/** @defgroup opus_multistream Opus Multistream API - * @{ - * - * The multistream API allows individual Opus streams to be combined into a - * single packet, enabling support for up to 255 channels. Unlike an - * elementary Opus stream, the encoder and decoder must negotiate the channel - * configuration before the decoder can successfully interpret the data in the - * packets produced by the encoder. Some basic information, such as packet - * duration, can be computed without any special negotiation. - * - * The format for multistream Opus packets is defined in - * RFC 7845 - * and is based on the self-delimited Opus framing described in Appendix B of - * RFC 6716. - * Normal Opus packets are just a degenerate case of multistream Opus packets, - * and can be encoded or decoded with the multistream API by setting - * streams to 1 when initializing the encoder or - * decoder. - * - * Multistream Opus streams can contain up to 255 elementary Opus streams. - * These may be either "uncoupled" or "coupled", indicating that the decoder - * is configured to decode them to either 1 or 2 channels, respectively. - * The streams are ordered so that all coupled streams appear at the - * beginning. - * - * A mapping table defines which decoded channel i - * should be used for each input/output (I/O) channel j. This table is - * typically provided as an unsigned char array. - * Let i = mapping[j] be the index for I/O channel j. - * If i < 2*coupled_streams, then I/O channel j is - * encoded as the left channel of stream (i/2) if i - * is even, or as the right channel of stream (i/2) if - * i is odd. Otherwise, I/O channel j is encoded as - * mono in stream (i - coupled_streams), unless it has the special - * value 255, in which case it is omitted from the encoding entirely (the - * decoder will reproduce it as silence). Each value i must either - * be the special value 255 or be less than streams + coupled_streams. - * - * The output channels specified by the encoder - * should use the - * Vorbis - * channel ordering. A decoder may wish to apply an additional permutation - * to the mapping the encoder used to achieve a different output channel - * order (e.g. for outputting in WAV order). - * - * Each multistream packet contains an Opus packet for each stream, and all of - * the Opus packets in a single multistream packet must have the same - * duration. Therefore the duration of a multistream packet can be extracted - * from the TOC sequence of the first stream, which is located at the - * beginning of the packet, just like an elementary Opus stream: - * - * @code - * int nb_samples; - * int nb_frames; - * nb_frames = opus_packet_get_nb_frames(data, len); - * if (nb_frames < 1) - * return nb_frames; - * nb_samples = opus_packet_get_samples_per_frame(data, 48000) * nb_frames; - * @endcode - * - * The general encoding and decoding process proceeds exactly the same as in - * the normal @ref opus_encoder and @ref opus_decoder APIs. - * See their documentation for an overview of how to use the corresponding - * multistream functions. - */ - -/** Opus multistream encoder state. - * This contains the complete state of a multistream Opus encoder. - * It is position independent and can be freely copied. - * @see opus_multistream_encoder_create - * @see opus_multistream_encoder_init - */ -typedef struct OpusMSEncoder OpusMSEncoder; - -/** Opus multistream decoder state. - * This contains the complete state of a multistream Opus decoder. - * It is position independent and can be freely copied. - * @see opus_multistream_decoder_create - * @see opus_multistream_decoder_init - */ -typedef struct OpusMSDecoder OpusMSDecoder; - -/**\name Multistream encoder functions */ -/**@{*/ - -/** Gets the size of an OpusMSEncoder structure. - * @param streams int: The total number of streams to encode from the - * input. - * This must be no more than 255. - * @param coupled_streams int: Number of coupled (2 channel) streams - * to encode. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * encoded channels (streams + - * coupled_streams) must be no - * more than 255. - * @returns The size in bytes on success, or a negative error code - * (see @ref opus_errorcodes) on error. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_encoder_get_size( - int streams, - int coupled_streams -); - -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_surround_encoder_get_size( - int channels, - int mapping_family -); - - -/** Allocates and initializes a multistream encoder state. - * Call opus_multistream_encoder_destroy() to release - * this object when finished. - * @param Fs opus_int32: Sampling rate of the input signal (in Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param channels int: Number of channels in the input signal. - * This must be at most 255. - * It may be greater than the number of - * coded channels (streams + - * coupled_streams). - * @param streams int: The total number of streams to encode from the - * input. - * This must be no more than the number of channels. - * @param coupled_streams int: Number of coupled (2 channel) streams - * to encode. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * encoded channels (streams + - * coupled_streams) must be no - * more than the number of input channels. - * @param[in] mapping const unsigned char[channels]: Mapping from - * encoded channels to input channels, as described in - * @ref opus_multistream. As an extra constraint, the - * multistream encoder does not allow encoding coupled - * streams for which one channel is unused since this - * is never a good idea. - * @param application int: The target encoder application. - * This must be one of the following: - *
- *
#OPUS_APPLICATION_VOIP
- *
Process signal for improved speech intelligibility.
- *
#OPUS_APPLICATION_AUDIO
- *
Favor faithfulness to the original input.
- *
#OPUS_APPLICATION_RESTRICTED_LOWDELAY
- *
Configure the minimum possible coding delay by disabling certain modes - * of operation.
- *
- * @param[out] error int *: Returns #OPUS_OK on success, or an error - * code (see @ref opus_errorcodes) on - * failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusMSEncoder *opus_multistream_encoder_create( - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - const unsigned char *mapping, - int application, - int *error -) OPUS_ARG_NONNULL(5); - -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusMSEncoder *opus_multistream_surround_encoder_create( - opus_int32 Fs, - int channels, - int mapping_family, - int *streams, - int *coupled_streams, - unsigned char *mapping, - int application, - int *error -) OPUS_ARG_NONNULL(4) OPUS_ARG_NONNULL(5) OPUS_ARG_NONNULL(6); - -/** Initialize a previously allocated multistream encoder state. - * The memory pointed to by \a st must be at least the size returned by - * opus_multistream_encoder_get_size(). - * This is intended for applications which use their own allocator instead of - * malloc. - * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. - * @see opus_multistream_encoder_create - * @see opus_multistream_encoder_get_size - * @param st OpusMSEncoder*: Multistream encoder state to initialize. - * @param Fs opus_int32: Sampling rate of the input signal (in Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param channels int: Number of channels in the input signal. - * This must be at most 255. - * It may be greater than the number of - * coded channels (streams + - * coupled_streams). - * @param streams int: The total number of streams to encode from the - * input. - * This must be no more than the number of channels. - * @param coupled_streams int: Number of coupled (2 channel) streams - * to encode. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * encoded channels (streams + - * coupled_streams) must be no - * more than the number of input channels. - * @param[in] mapping const unsigned char[channels]: Mapping from - * encoded channels to input channels, as described in - * @ref opus_multistream. As an extra constraint, the - * multistream encoder does not allow encoding coupled - * streams for which one channel is unused since this - * is never a good idea. - * @param application int: The target encoder application. - * This must be one of the following: - *
- *
#OPUS_APPLICATION_VOIP
- *
Process signal for improved speech intelligibility.
- *
#OPUS_APPLICATION_AUDIO
- *
Favor faithfulness to the original input.
- *
#OPUS_APPLICATION_RESTRICTED_LOWDELAY
- *
Configure the minimum possible coding delay by disabling certain modes - * of operation.
- *
- * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes) - * on failure. - */ -OPUS_EXPORT int opus_multistream_encoder_init( - OpusMSEncoder *st, - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - const unsigned char *mapping, - int application -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6); - -OPUS_EXPORT int opus_multistream_surround_encoder_init( - OpusMSEncoder *st, - opus_int32 Fs, - int channels, - int mapping_family, - int *streams, - int *coupled_streams, - unsigned char *mapping, - int application -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(5) OPUS_ARG_NONNULL(6) OPUS_ARG_NONNULL(7); - -/** Encodes a multistream Opus frame. - * @param st OpusMSEncoder*: Multistream encoder state. - * @param[in] pcm const opus_int16*: The input signal as interleaved - * samples. - * This must contain - * frame_size*channels - * samples. - * @param frame_size int: Number of samples per channel in the input - * signal. - * This must be an Opus frame size for the - * encoder's sampling rate. - * For example, at 48 kHz the permitted values - * are 120, 240, 480, 960, 1920, and 2880. - * Passing in a duration of less than 10 ms - * (480 samples at 48 kHz) will prevent the - * encoder from using the LPC or hybrid modes. - * @param[out] data unsigned char*: Output payload. - * This must contain storage for at - * least \a max_data_bytes. - * @param [in] max_data_bytes opus_int32: Size of the allocated - * memory for the output - * payload. This may be - * used to impose an upper limit on - * the instant bitrate, but should - * not be used as the only bitrate - * control. Use #OPUS_SET_BITRATE to - * control the bitrate. - * @returns The length of the encoded packet (in bytes) on success or a - * negative error code (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_multistream_encode( - OpusMSEncoder *st, - const opus_int16 *pcm, - int frame_size, - unsigned char *data, - opus_int32 max_data_bytes -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); - -/** Encodes a multistream Opus frame from floating point input. - * @param st OpusMSEncoder*: Multistream encoder state. - * @param[in] pcm const float*: The input signal as interleaved - * samples with a normal range of - * +/-1.0. - * Samples with a range beyond +/-1.0 - * are supported but will be clipped by - * decoders using the integer API and - * should only be used if it is known - * that the far end supports extended - * dynamic range. - * This must contain - * frame_size*channels - * samples. - * @param frame_size int: Number of samples per channel in the input - * signal. - * This must be an Opus frame size for the - * encoder's sampling rate. - * For example, at 48 kHz the permitted values - * are 120, 240, 480, 960, 1920, and 2880. - * Passing in a duration of less than 10 ms - * (480 samples at 48 kHz) will prevent the - * encoder from using the LPC or hybrid modes. - * @param[out] data unsigned char*: Output payload. - * This must contain storage for at - * least \a max_data_bytes. - * @param [in] max_data_bytes opus_int32: Size of the allocated - * memory for the output - * payload. This may be - * used to impose an upper limit on - * the instant bitrate, but should - * not be used as the only bitrate - * control. Use #OPUS_SET_BITRATE to - * control the bitrate. - * @returns The length of the encoded packet (in bytes) on success or a - * negative error code (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_multistream_encode_float( - OpusMSEncoder *st, - const float *pcm, - int frame_size, - unsigned char *data, - opus_int32 max_data_bytes -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); - -/** Frees an OpusMSEncoder allocated by - * opus_multistream_encoder_create(). - * @param st OpusMSEncoder*: Multistream encoder state to be freed. - */ -OPUS_EXPORT void opus_multistream_encoder_destroy(OpusMSEncoder *st); - -/** Perform a CTL function on a multistream Opus encoder. - * - * Generally the request and subsequent arguments are generated by a - * convenience macro. - * @param st OpusMSEncoder*: Multistream encoder state. - * @param request This and all remaining parameters should be replaced by one - * of the convenience macros in @ref opus_genericctls, - * @ref opus_encoderctls, or @ref opus_multistream_ctls. - * @see opus_genericctls - * @see opus_encoderctls - * @see opus_multistream_ctls - */ -OPUS_EXPORT int opus_multistream_encoder_ctl(OpusMSEncoder *st, int request, ...) OPUS_ARG_NONNULL(1); - -/**@}*/ - -/**\name Multistream decoder functions */ -/**@{*/ - -/** Gets the size of an OpusMSDecoder structure. - * @param streams int: The total number of streams coded in the - * input. - * This must be no more than 255. - * @param coupled_streams int: Number streams to decode as coupled - * (2 channel) streams. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * coded channels (streams + - * coupled_streams) must be no - * more than 255. - * @returns The size in bytes on success, or a negative error code - * (see @ref opus_errorcodes) on error. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_multistream_decoder_get_size( - int streams, - int coupled_streams -); - -/** Allocates and initializes a multistream decoder state. - * Call opus_multistream_decoder_destroy() to release - * this object when finished. - * @param Fs opus_int32: Sampling rate to decode at (in Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param channels int: Number of channels to output. - * This must be at most 255. - * It may be different from the number of coded - * channels (streams + - * coupled_streams). - * @param streams int: The total number of streams coded in the - * input. - * This must be no more than 255. - * @param coupled_streams int: Number of streams to decode as coupled - * (2 channel) streams. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * coded channels (streams + - * coupled_streams) must be no - * more than 255. - * @param[in] mapping const unsigned char[channels]: Mapping from - * coded channels to output channels, as described in - * @ref opus_multistream. - * @param[out] error int *: Returns #OPUS_OK on success, or an error - * code (see @ref opus_errorcodes) on - * failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusMSDecoder *opus_multistream_decoder_create( - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - const unsigned char *mapping, - int *error -) OPUS_ARG_NONNULL(5); - -/** Initialize a previously allocated decoder state object. - * The memory pointed to by \a st must be at least the size returned by - * opus_multistream_encoder_get_size(). - * This is intended for applications which use their own allocator instead of - * malloc. - * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. - * @see opus_multistream_decoder_create - * @see opus_multistream_deocder_get_size - * @param st OpusMSEncoder*: Multistream encoder state to initialize. - * @param Fs opus_int32: Sampling rate to decode at (in Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param channels int: Number of channels to output. - * This must be at most 255. - * It may be different from the number of coded - * channels (streams + - * coupled_streams). - * @param streams int: The total number of streams coded in the - * input. - * This must be no more than 255. - * @param coupled_streams int: Number of streams to decode as coupled - * (2 channel) streams. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * coded channels (streams + - * coupled_streams) must be no - * more than 255. - * @param[in] mapping const unsigned char[channels]: Mapping from - * coded channels to output channels, as described in - * @ref opus_multistream. - * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes) - * on failure. - */ -OPUS_EXPORT int opus_multistream_decoder_init( - OpusMSDecoder *st, - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - const unsigned char *mapping -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6); - -/** Decode a multistream Opus packet. - * @param st OpusMSDecoder*: Multistream decoder state. - * @param[in] data const unsigned char*: Input payload. - * Use a NULL - * pointer to indicate packet - * loss. - * @param len opus_int32: Number of bytes in payload. - * @param[out] pcm opus_int16*: Output signal, with interleaved - * samples. - * This must contain room for - * frame_size*channels - * samples. - * @param frame_size int: The number of samples per channel of - * available space in \a pcm. - * If this is less than the maximum packet duration - * (120 ms; 5760 for 48kHz), this function will not be capable - * of decoding some packets. In the case of PLC (data==NULL) - * or FEC (decode_fec=1), then frame_size needs to be exactly - * the duration of audio that is missing, otherwise the - * decoder will not be in the optimal state to decode the - * next incoming packet. For the PLC and FEC cases, frame_size - * must be a multiple of 2.5 ms. - * @param decode_fec int: Flag (0 or 1) to request that any in-band - * forward error correction data be decoded. - * If no such data is available, the frame is - * decoded as if it were lost. - * @returns Number of samples decoded on success or a negative error code - * (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_multistream_decode( - OpusMSDecoder *st, - const unsigned char *data, - opus_int32 len, - opus_int16 *pcm, - int frame_size, - int decode_fec -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - -/** Decode a multistream Opus packet with floating point output. - * @param st OpusMSDecoder*: Multistream decoder state. - * @param[in] data const unsigned char*: Input payload. - * Use a NULL - * pointer to indicate packet - * loss. - * @param len opus_int32: Number of bytes in payload. - * @param[out] pcm opus_int16*: Output signal, with interleaved - * samples. - * This must contain room for - * frame_size*channels - * samples. - * @param frame_size int: The number of samples per channel of - * available space in \a pcm. - * If this is less than the maximum packet duration - * (120 ms; 5760 for 48kHz), this function will not be capable - * of decoding some packets. In the case of PLC (data==NULL) - * or FEC (decode_fec=1), then frame_size needs to be exactly - * the duration of audio that is missing, otherwise the - * decoder will not be in the optimal state to decode the - * next incoming packet. For the PLC and FEC cases, frame_size - * must be a multiple of 2.5 ms. - * @param decode_fec int: Flag (0 or 1) to request that any in-band - * forward error correction data be decoded. - * If no such data is available, the frame is - * decoded as if it were lost. - * @returns Number of samples decoded on success or a negative error code - * (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_multistream_decode_float( - OpusMSDecoder *st, - const unsigned char *data, - opus_int32 len, - float *pcm, - int frame_size, - int decode_fec -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - -/** Perform a CTL function on a multistream Opus decoder. - * - * Generally the request and subsequent arguments are generated by a - * convenience macro. - * @param st OpusMSDecoder*: Multistream decoder state. - * @param request This and all remaining parameters should be replaced by one - * of the convenience macros in @ref opus_genericctls, - * @ref opus_decoderctls, or @ref opus_multistream_ctls. - * @see opus_genericctls - * @see opus_decoderctls - * @see opus_multistream_ctls - */ -OPUS_EXPORT int opus_multistream_decoder_ctl(OpusMSDecoder *st, int request, ...) OPUS_ARG_NONNULL(1); - -/** Frees an OpusMSDecoder allocated by - * opus_multistream_decoder_create(). - * @param st OpusMSDecoder: Multistream decoder state to be freed. - */ -OPUS_EXPORT void opus_multistream_decoder_destroy(OpusMSDecoder *st); - -/**@}*/ - -/**@}*/ - -#ifdef __cplusplus -} -#endif - -#endif /* OPUS_MULTISTREAM_H */ diff --git a/include/opus_projection.h b/include/opus_projection.h deleted file mode 100644 index cb4a333b561..00000000000 --- a/include/opus_projection.h +++ /dev/null @@ -1,568 +0,0 @@ -/* Copyright (c) 2017 Google Inc. - Written by Andrew Allen */ -/* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/** - * @file opus_projection.h - * @brief Opus projection reference API - */ - -#ifndef OPUS_PROJECTION_H -#define OPUS_PROJECTION_H - -#include "opus_multistream.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** @cond OPUS_INTERNAL_DOC */ - -/** These are the actual encoder and decoder CTL ID numbers. - * They should not be used directly by applications.c - * In general, SETs should be even and GETs should be odd.*/ -/**@{*/ -#define OPUS_PROJECTION_GET_DEMIXING_MATRIX_GAIN_REQUEST 6001 -#define OPUS_PROJECTION_GET_DEMIXING_MATRIX_SIZE_REQUEST 6003 -#define OPUS_PROJECTION_GET_DEMIXING_MATRIX_REQUEST 6005 -/**@}*/ - - -/** @endcond */ - -/** @defgroup opus_projection_ctls Projection specific encoder and decoder CTLs - * - * These are convenience macros that are specific to the - * opus_projection_encoder_ctl() and opus_projection_decoder_ctl() - * interface. - * The CTLs from @ref opus_genericctls, @ref opus_encoderctls, - * @ref opus_decoderctls, and @ref opus_multistream_ctls may be applied to a - * projection encoder or decoder as well. - */ -/**@{*/ - -/** Gets the gain (in dB. S7.8-format) of the demixing matrix from the encoder. - * @param[out] x opus_int32 *: Returns the gain (in dB. S7.8-format) - * of the demixing matrix. - * @hideinitializer - */ -#define OPUS_PROJECTION_GET_DEMIXING_MATRIX_GAIN(x) OPUS_PROJECTION_GET_DEMIXING_MATRIX_GAIN_REQUEST, __opus_check_int_ptr(x) - - -/** Gets the size in bytes of the demixing matrix from the encoder. - * @param[out] x opus_int32 *: Returns the size in bytes of the - * demixing matrix. - * @hideinitializer - */ -#define OPUS_PROJECTION_GET_DEMIXING_MATRIX_SIZE(x) OPUS_PROJECTION_GET_DEMIXING_MATRIX_SIZE_REQUEST, __opus_check_int_ptr(x) - - -/** Copies the demixing matrix to the supplied pointer location. - * @param[out] x unsigned char *: Returns the demixing matrix to the - * supplied pointer location. - * @param y opus_int32: The size in bytes of the reserved memory at the - * pointer location. - * @hideinitializer - */ -#define OPUS_PROJECTION_GET_DEMIXING_MATRIX(x,y) OPUS_PROJECTION_GET_DEMIXING_MATRIX_REQUEST, x, __opus_check_int(y) - - -/**@}*/ - -/** Opus projection encoder state. - * This contains the complete state of a projection Opus encoder. - * It is position independent and can be freely copied. - * @see opus_projection_ambisonics_encoder_create - */ -typedef struct OpusProjectionEncoder OpusProjectionEncoder; - - -/** Opus projection decoder state. - * This contains the complete state of a projection Opus decoder. - * It is position independent and can be freely copied. - * @see opus_projection_decoder_create - * @see opus_projection_decoder_init - */ -typedef struct OpusProjectionDecoder OpusProjectionDecoder; - - -/**\name Projection encoder functions */ -/**@{*/ - -/** Gets the size of an OpusProjectionEncoder structure. - * @param channels int: The total number of input channels to encode. - * This must be no more than 255. - * @param mapping_family int: The mapping family to use for selecting - * the appropriate projection. - * @returns The size in bytes on success, or a negative error code - * (see @ref opus_errorcodes) on error. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_projection_ambisonics_encoder_get_size( - int channels, - int mapping_family -); - - -/** Allocates and initializes a projection encoder state. - * Call opus_projection_encoder_destroy() to release - * this object when finished. - * @param Fs opus_int32: Sampling rate of the input signal (in Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param channels int: Number of channels in the input signal. - * This must be at most 255. - * It may be greater than the number of - * coded channels (streams + - * coupled_streams). - * @param mapping_family int: The mapping family to use for selecting - * the appropriate projection. - * @param[out] streams int *: The total number of streams that will - * be encoded from the input. - * @param[out] coupled_streams int *: Number of coupled (2 channel) - * streams that will be encoded from the input. - * @param application int: The target encoder application. - * This must be one of the following: - *
- *
#OPUS_APPLICATION_VOIP
- *
Process signal for improved speech intelligibility.
- *
#OPUS_APPLICATION_AUDIO
- *
Favor faithfulness to the original input.
- *
#OPUS_APPLICATION_RESTRICTED_LOWDELAY
- *
Configure the minimum possible coding delay by disabling certain modes - * of operation.
- *
- * @param[out] error int *: Returns #OPUS_OK on success, or an error - * code (see @ref opus_errorcodes) on - * failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusProjectionEncoder *opus_projection_ambisonics_encoder_create( - opus_int32 Fs, - int channels, - int mapping_family, - int *streams, - int *coupled_streams, - int application, - int *error -) OPUS_ARG_NONNULL(4) OPUS_ARG_NONNULL(5); - - -/** Initialize a previously allocated projection encoder state. - * The memory pointed to by \a st must be at least the size returned by - * opus_projection_ambisonics_encoder_get_size(). - * This is intended for applications which use their own allocator instead of - * malloc. - * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. - * @see opus_projection_ambisonics_encoder_create - * @see opus_projection_ambisonics_encoder_get_size - * @param st OpusProjectionEncoder*: Projection encoder state to initialize. - * @param Fs opus_int32: Sampling rate of the input signal (in Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param channels int: Number of channels in the input signal. - * This must be at most 255. - * It may be greater than the number of - * coded channels (streams + - * coupled_streams). - * @param streams int: The total number of streams to encode from the - * input. - * This must be no more than the number of channels. - * @param coupled_streams int: Number of coupled (2 channel) streams - * to encode. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * encoded channels (streams + - * coupled_streams) must be no - * more than the number of input channels. - * @param application int: The target encoder application. - * This must be one of the following: - *
- *
#OPUS_APPLICATION_VOIP
- *
Process signal for improved speech intelligibility.
- *
#OPUS_APPLICATION_AUDIO
- *
Favor faithfulness to the original input.
- *
#OPUS_APPLICATION_RESTRICTED_LOWDELAY
- *
Configure the minimum possible coding delay by disabling certain modes - * of operation.
- *
- * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes) - * on failure. - */ -OPUS_EXPORT int opus_projection_ambisonics_encoder_init( - OpusProjectionEncoder *st, - opus_int32 Fs, - int channels, - int mapping_family, - int *streams, - int *coupled_streams, - int application -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(5) OPUS_ARG_NONNULL(6); - - -/** Encodes a projection Opus frame. - * @param st OpusProjectionEncoder*: Projection encoder state. - * @param[in] pcm const opus_int16*: The input signal as interleaved - * samples. - * This must contain - * frame_size*channels - * samples. - * @param frame_size int: Number of samples per channel in the input - * signal. - * This must be an Opus frame size for the - * encoder's sampling rate. - * For example, at 48 kHz the permitted values - * are 120, 240, 480, 960, 1920, and 2880. - * Passing in a duration of less than 10 ms - * (480 samples at 48 kHz) will prevent the - * encoder from using the LPC or hybrid modes. - * @param[out] data unsigned char*: Output payload. - * This must contain storage for at - * least \a max_data_bytes. - * @param [in] max_data_bytes opus_int32: Size of the allocated - * memory for the output - * payload. This may be - * used to impose an upper limit on - * the instant bitrate, but should - * not be used as the only bitrate - * control. Use #OPUS_SET_BITRATE to - * control the bitrate. - * @returns The length of the encoded packet (in bytes) on success or a - * negative error code (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_projection_encode( - OpusProjectionEncoder *st, - const opus_int16 *pcm, - int frame_size, - unsigned char *data, - opus_int32 max_data_bytes -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); - - -/** Encodes a projection Opus frame from floating point input. - * @param st OpusProjectionEncoder*: Projection encoder state. - * @param[in] pcm const float*: The input signal as interleaved - * samples with a normal range of - * +/-1.0. - * Samples with a range beyond +/-1.0 - * are supported but will be clipped by - * decoders using the integer API and - * should only be used if it is known - * that the far end supports extended - * dynamic range. - * This must contain - * frame_size*channels - * samples. - * @param frame_size int: Number of samples per channel in the input - * signal. - * This must be an Opus frame size for the - * encoder's sampling rate. - * For example, at 48 kHz the permitted values - * are 120, 240, 480, 960, 1920, and 2880. - * Passing in a duration of less than 10 ms - * (480 samples at 48 kHz) will prevent the - * encoder from using the LPC or hybrid modes. - * @param[out] data unsigned char*: Output payload. - * This must contain storage for at - * least \a max_data_bytes. - * @param [in] max_data_bytes opus_int32: Size of the allocated - * memory for the output - * payload. This may be - * used to impose an upper limit on - * the instant bitrate, but should - * not be used as the only bitrate - * control. Use #OPUS_SET_BITRATE to - * control the bitrate. - * @returns The length of the encoded packet (in bytes) on success or a - * negative error code (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_projection_encode_float( - OpusProjectionEncoder *st, - const float *pcm, - int frame_size, - unsigned char *data, - opus_int32 max_data_bytes -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4); - - -/** Frees an OpusProjectionEncoder allocated by - * opus_projection_ambisonics_encoder_create(). - * @param st OpusProjectionEncoder*: Projection encoder state to be freed. - */ -OPUS_EXPORT void opus_projection_encoder_destroy(OpusProjectionEncoder *st); - - -/** Perform a CTL function on a projection Opus encoder. - * - * Generally the request and subsequent arguments are generated by a - * convenience macro. - * @param st OpusProjectionEncoder*: Projection encoder state. - * @param request This and all remaining parameters should be replaced by one - * of the convenience macros in @ref opus_genericctls, - * @ref opus_encoderctls, @ref opus_multistream_ctls, or - * @ref opus_projection_ctls - * @see opus_genericctls - * @see opus_encoderctls - * @see opus_multistream_ctls - * @see opus_projection_ctls - */ -OPUS_EXPORT int opus_projection_encoder_ctl(OpusProjectionEncoder *st, int request, ...) OPUS_ARG_NONNULL(1); - - -/**@}*/ - -/**\name Projection decoder functions */ -/**@{*/ - -/** Gets the size of an OpusProjectionDecoder structure. - * @param channels int: The total number of output channels. - * This must be no more than 255. - * @param streams int: The total number of streams coded in the - * input. - * This must be no more than 255. - * @param coupled_streams int: Number streams to decode as coupled - * (2 channel) streams. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * coded channels (streams + - * coupled_streams) must be no - * more than 255. - * @returns The size in bytes on success, or a negative error code - * (see @ref opus_errorcodes) on error. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_projection_decoder_get_size( - int channels, - int streams, - int coupled_streams -); - - -/** Allocates and initializes a projection decoder state. - * Call opus_projection_decoder_destroy() to release - * this object when finished. - * @param Fs opus_int32: Sampling rate to decode at (in Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param channels int: Number of channels to output. - * This must be at most 255. - * It may be different from the number of coded - * channels (streams + - * coupled_streams). - * @param streams int: The total number of streams coded in the - * input. - * This must be no more than 255. - * @param coupled_streams int: Number of streams to decode as coupled - * (2 channel) streams. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * coded channels (streams + - * coupled_streams) must be no - * more than 255. - * @param[in] demixing_matrix const unsigned char[demixing_matrix_size]: Demixing matrix - * that mapping from coded channels to output channels, - * as described in @ref opus_projection and - * @ref opus_projection_ctls. - * @param demixing_matrix_size opus_int32: The size in bytes of the - * demixing matrix, as - * described in @ref - * opus_projection_ctls. - * @param[out] error int *: Returns #OPUS_OK on success, or an error - * code (see @ref opus_errorcodes) on - * failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusProjectionDecoder *opus_projection_decoder_create( - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - unsigned char *demixing_matrix, - opus_int32 demixing_matrix_size, - int *error -) OPUS_ARG_NONNULL(5); - - -/** Initialize a previously allocated projection decoder state object. - * The memory pointed to by \a st must be at least the size returned by - * opus_projection_decoder_get_size(). - * This is intended for applications which use their own allocator instead of - * malloc. - * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL. - * @see opus_projection_decoder_create - * @see opus_projection_deocder_get_size - * @param st OpusProjectionDecoder*: Projection encoder state to initialize. - * @param Fs opus_int32: Sampling rate to decode at (in Hz). - * This must be one of 8000, 12000, 16000, - * 24000, or 48000. - * @param channels int: Number of channels to output. - * This must be at most 255. - * It may be different from the number of coded - * channels (streams + - * coupled_streams). - * @param streams int: The total number of streams coded in the - * input. - * This must be no more than 255. - * @param coupled_streams int: Number of streams to decode as coupled - * (2 channel) streams. - * This must be no larger than the total - * number of streams. - * Additionally, The total number of - * coded channels (streams + - * coupled_streams) must be no - * more than 255. - * @param[in] demixing_matrix const unsigned char[demixing_matrix_size]: Demixing matrix - * that mapping from coded channels to output channels, - * as described in @ref opus_projection and - * @ref opus_projection_ctls. - * @param demixing_matrix_size opus_int32: The size in bytes of the - * demixing matrix, as - * described in @ref - * opus_projection_ctls. - * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes) - * on failure. - */ -OPUS_EXPORT int opus_projection_decoder_init( - OpusProjectionDecoder *st, - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - unsigned char *demixing_matrix, - opus_int32 demixing_matrix_size -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(6); - - -/** Decode a projection Opus packet. - * @param st OpusProjectionDecoder*: Projection decoder state. - * @param[in] data const unsigned char*: Input payload. - * Use a NULL - * pointer to indicate packet - * loss. - * @param len opus_int32: Number of bytes in payload. - * @param[out] pcm opus_int16*: Output signal, with interleaved - * samples. - * This must contain room for - * frame_size*channels - * samples. - * @param frame_size int: The number of samples per channel of - * available space in \a pcm. - * If this is less than the maximum packet duration - * (120 ms; 5760 for 48kHz), this function will not be capable - * of decoding some packets. In the case of PLC (data==NULL) - * or FEC (decode_fec=1), then frame_size needs to be exactly - * the duration of audio that is missing, otherwise the - * decoder will not be in the optimal state to decode the - * next incoming packet. For the PLC and FEC cases, frame_size - * must be a multiple of 2.5 ms. - * @param decode_fec int: Flag (0 or 1) to request that any in-band - * forward error correction data be decoded. - * If no such data is available, the frame is - * decoded as if it were lost. - * @returns Number of samples decoded on success or a negative error code - * (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_projection_decode( - OpusProjectionDecoder *st, - const unsigned char *data, - opus_int32 len, - opus_int16 *pcm, - int frame_size, - int decode_fec -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - - -/** Decode a projection Opus packet with floating point output. - * @param st OpusProjectionDecoder*: Projection decoder state. - * @param[in] data const unsigned char*: Input payload. - * Use a NULL - * pointer to indicate packet - * loss. - * @param len opus_int32: Number of bytes in payload. - * @param[out] pcm opus_int16*: Output signal, with interleaved - * samples. - * This must contain room for - * frame_size*channels - * samples. - * @param frame_size int: The number of samples per channel of - * available space in \a pcm. - * If this is less than the maximum packet duration - * (120 ms; 5760 for 48kHz), this function will not be capable - * of decoding some packets. In the case of PLC (data==NULL) - * or FEC (decode_fec=1), then frame_size needs to be exactly - * the duration of audio that is missing, otherwise the - * decoder will not be in the optimal state to decode the - * next incoming packet. For the PLC and FEC cases, frame_size - * must be a multiple of 2.5 ms. - * @param decode_fec int: Flag (0 or 1) to request that any in-band - * forward error correction data be decoded. - * If no such data is available, the frame is - * decoded as if it were lost. - * @returns Number of samples decoded on success or a negative error code - * (see @ref opus_errorcodes) on failure. - */ -OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_projection_decode_float( - OpusProjectionDecoder *st, - const unsigned char *data, - opus_int32 len, - float *pcm, - int frame_size, - int decode_fec -) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4); - - -/** Perform a CTL function on a projection Opus decoder. - * - * Generally the request and subsequent arguments are generated by a - * convenience macro. - * @param st OpusProjectionDecoder*: Projection decoder state. - * @param request This and all remaining parameters should be replaced by one - * of the convenience macros in @ref opus_genericctls, - * @ref opus_decoderctls, @ref opus_multistream_ctls, or - * @ref opus_projection_ctls. - * @see opus_genericctls - * @see opus_decoderctls - * @see opus_multistream_ctls - * @see opus_projection_ctls - */ -OPUS_EXPORT int opus_projection_decoder_ctl(OpusProjectionDecoder *st, int request, ...) OPUS_ARG_NONNULL(1); - - -/** Frees an OpusProjectionDecoder allocated by - * opus_projection_decoder_create(). - * @param st OpusProjectionDecoder: Projection decoder state to be freed. - */ -OPUS_EXPORT void opus_projection_decoder_destroy(OpusProjectionDecoder *st); - - -/**@}*/ - -/**@}*/ - -#ifdef __cplusplus -} -#endif - -#endif /* OPUS_PROJECTION_H */ diff --git a/include/opus_types.h b/include/opus_types.h deleted file mode 100644 index b4f09a3bc16..00000000000 --- a/include/opus_types.h +++ /dev/null @@ -1,166 +0,0 @@ -/* (C) COPYRIGHT 1994-2002 Xiph.Org Foundation */ -/* Modified by Jean-Marc Valin */ -/* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/* opus_types.h based on ogg_types.h from libogg */ - -/** - @file opus_types.h - @brief Opus reference implementation types -*/ -#ifndef OPUS_TYPES_H -#define OPUS_TYPES_H - -#define opus_int int /* used for counters etc; at least 16 bits */ -#define opus_int64 long long -#define opus_int8 signed char - -#define opus_uint unsigned int /* used for counters etc; at least 16 bits */ -#define opus_uint64 unsigned long long -#define opus_uint8 unsigned char - -/* Use the real stdint.h if it's there (taken from Paul Hsieh's pstdint.h) */ -#if (defined(__STDC__) && __STDC__ && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || (defined(__GNUC__) && (defined(_STDINT_H) || defined(_STDINT_H_)) || defined (HAVE_STDINT_H)) -#include -# undef opus_int64 -# undef opus_int8 -# undef opus_uint64 -# undef opus_uint8 - typedef int8_t opus_int8; - typedef uint8_t opus_uint8; - typedef int16_t opus_int16; - typedef uint16_t opus_uint16; - typedef int32_t opus_int32; - typedef uint32_t opus_uint32; - typedef int64_t opus_int64; - typedef uint64_t opus_uint64; -#elif defined(_WIN32) - -# if defined(__CYGWIN__) -# include <_G_config.h> - typedef _G_int32_t opus_int32; - typedef _G_uint32_t opus_uint32; - typedef _G_int16 opus_int16; - typedef _G_uint16 opus_uint16; -# elif defined(__MINGW32__) - typedef short opus_int16; - typedef unsigned short opus_uint16; - typedef int opus_int32; - typedef unsigned int opus_uint32; -# elif defined(__MWERKS__) - typedef int opus_int32; - typedef unsigned int opus_uint32; - typedef short opus_int16; - typedef unsigned short opus_uint16; -# else - /* MSVC/Borland */ - typedef __int32 opus_int32; - typedef unsigned __int32 opus_uint32; - typedef __int16 opus_int16; - typedef unsigned __int16 opus_uint16; -# endif - -#elif defined(__MACOS__) - -# include - typedef SInt16 opus_int16; - typedef UInt16 opus_uint16; - typedef SInt32 opus_int32; - typedef UInt32 opus_uint32; - -#elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */ - -# include - typedef int16_t opus_int16; - typedef u_int16_t opus_uint16; - typedef int32_t opus_int32; - typedef u_int32_t opus_uint32; - -#elif defined(__BEOS__) - - /* Be */ -# include - typedef int16 opus_int16; - typedef u_int16 opus_uint16; - typedef int32_t opus_int32; - typedef u_int32_t opus_uint32; - -#elif defined (__EMX__) - - /* OS/2 GCC */ - typedef short opus_int16; - typedef unsigned short opus_uint16; - typedef int opus_int32; - typedef unsigned int opus_uint32; - -#elif defined (DJGPP) - - /* DJGPP */ - typedef short opus_int16; - typedef unsigned short opus_uint16; - typedef int opus_int32; - typedef unsigned int opus_uint32; - -#elif defined(R5900) - - /* PS2 EE */ - typedef int opus_int32; - typedef unsigned opus_uint32; - typedef short opus_int16; - typedef unsigned short opus_uint16; - -#elif defined(__SYMBIAN32__) - - /* Symbian GCC */ - typedef signed short opus_int16; - typedef unsigned short opus_uint16; - typedef signed int opus_int32; - typedef unsigned int opus_uint32; - -#elif defined(CONFIG_TI_C54X) || defined (CONFIG_TI_C55X) - - typedef short opus_int16; - typedef unsigned short opus_uint16; - typedef long opus_int32; - typedef unsigned long opus_uint32; - -#elif defined(CONFIG_TI_C6X) - - typedef short opus_int16; - typedef unsigned short opus_uint16; - typedef int opus_int32; - typedef unsigned int opus_uint32; - -#else - - /* Give up, take a reasonable guess */ - typedef short opus_int16; - typedef unsigned short opus_uint16; - typedef int opus_int32; - typedef unsigned int opus_uint32; - -#endif - -#endif /* OPUS_TYPES_H */ diff --git a/include/opusfile.h b/include/opusfile.h deleted file mode 100644 index f5141eef78d..00000000000 --- a/include/opusfile.h +++ /dev/null @@ -1,2164 +0,0 @@ -/******************************************************************** - * * - * THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. * - * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * - * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * - * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * - * * - * THE libopusfile SOURCE CODE IS (C) COPYRIGHT 1994-2012 * - * by the Xiph.Org Foundation and contributors http://www.xiph.org/ * - * * - ******************************************************************** - - function: stdio-based convenience library for opening/seeking/decoding - last mod: $Id: vorbisfile.h 17182 2010-04-29 03:48:32Z xiphmont $ - - ********************************************************************/ -#if !defined(_opusfile_h) -# define _opusfile_h (1) - -/**\mainpage - \section Introduction - - This is the documentation for the libopusfile C API. - - The libopusfile package provides a convenient high-level API for - decoding and basic manipulation of all Ogg Opus audio streams. - libopusfile is implemented as a layer on top of Xiph.Org's - reference - libogg - and - libopus - libraries. - - libopusfile provides several sets of built-in routines for - file/stream access, and may also use custom stream I/O routines provided by - the embedded environment. - There are built-in I/O routines provided for ANSI-compliant - stdio (FILE *), memory buffers, and URLs - (including URLs, plus optionally and URLs). - - \section Organization - - The main API is divided into several sections: - - \ref stream_open_close - - \ref stream_info - - \ref stream_decoding - - \ref stream_seeking - - Several additional sections are not tied to the main API. - - \ref stream_callbacks - - \ref header_info - - \ref error_codes - - \section Overview - - The libopusfile API always decodes files to 48 kHz. - The original sample rate is not preserved by the lossy compression, though - it is stored in the header to allow you to resample to it after decoding - (the libopusfile API does not currently provide a resampler, - but the - the - Speex resampler is a good choice if you need one). - In general, if you are playing back the audio, you should leave it at - 48 kHz, provided your audio hardware supports it. - When decoding to a file, it may be worth resampling back to the original - sample rate, so as not to surprise users who might not expect the sample - rate to change after encoding to Opus and decoding. - - Opus files can contain anywhere from 1 to 255 channels of audio. - The channel mappings for up to 8 channels are the same as the - Vorbis - mappings. - A special stereo API can convert everything to 2 channels, making it simple - to support multichannel files in an application which only has stereo - output. - Although the libopusfile ABI provides support for the theoretical - maximum number of channels, the current implementation does not support - files with more than 8 channels, as they do not have well-defined channel - mappings. - - Like all Ogg files, Opus files may be "chained". - That is, multiple Opus files may be combined into a single, longer file just - by concatenating the original files. - This is commonly done in internet radio streaming, as it allows the title - and artist to be updated each time the song changes, since each link in the - chain includes its own set of metadata. - - libopusfile fully supports chained files. - It will decode the first Opus stream found in each link of a chained file - (ignoring any other streams that might be concurrently multiplexed with it, - such as a video stream). - - The channel count can also change between links. - If your application is not prepared to deal with this, it can use the stereo - API to ensure the audio from all links will always get decoded into a - common format. - Since libopusfile always decodes to 48 kHz, you do not have to - worry about the sample rate changing between links (as was possible with - Vorbis). - This makes application support for chained files with libopusfile - very easy.*/ - -# if defined(__cplusplus) -extern "C" { -# endif - -# include -# include -# include -# include - -/**@cond PRIVATE*/ - -/*Enable special features for gcc and gcc-compatible compilers.*/ -# if !defined(OP_GNUC_PREREQ) -# if defined(__GNUC__)&&defined(__GNUC_MINOR__) -# define OP_GNUC_PREREQ(_maj,_min) \ - ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min)) -# else -# define OP_GNUC_PREREQ(_maj,_min) 0 -# endif -# endif - -# if OP_GNUC_PREREQ(4,0) -# pragma GCC visibility push(default) -# endif - -typedef struct OpusHead OpusHead; -typedef struct OpusTags OpusTags; -typedef struct OpusPictureTag OpusPictureTag; -typedef struct OpusServerInfo OpusServerInfo; -typedef struct OpusFileCallbacks OpusFileCallbacks; -typedef struct OggOpusFile OggOpusFile; - -/*Warning attributes for libopusfile functions.*/ -# if OP_GNUC_PREREQ(3,4) -# define OP_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) -# else -# define OP_WARN_UNUSED_RESULT -# endif -# if OP_GNUC_PREREQ(3,4) -# define OP_ARG_NONNULL(_x) __attribute__((__nonnull__(_x))) -# else -# define OP_ARG_NONNULL(_x) -# endif - -/**@endcond*/ - -/**\defgroup error_codes Error Codes*/ -/*@{*/ -/**\name List of possible error codes - Many of the functions in this library return a negative error code when a - function fails. - This list provides a brief explanation of the common errors. - See each individual function for more details on what a specific error code - means in that context.*/ -/*@{*/ - -/**A request did not succeed.*/ -#define OP_FALSE (-1) -/*Currently not used externally.*/ -#define OP_EOF (-2) -/**There was a hole in the page sequence numbers (e.g., a page was corrupt or - missing).*/ -#define OP_HOLE (-3) -/**An underlying read, seek, or tell operation failed when it should have - succeeded.*/ -#define OP_EREAD (-128) -/**A NULL pointer was passed where one was unexpected, or an - internal memory allocation failed, or an internal library error was - encountered.*/ -#define OP_EFAULT (-129) -/**The stream used a feature that is not implemented, such as an unsupported - channel family.*/ -#define OP_EIMPL (-130) -/**One or more parameters to a function were invalid.*/ -#define OP_EINVAL (-131) -/**A purported Ogg Opus stream did not begin with an Ogg page, a purported - header packet did not start with one of the required strings, "OpusHead" or - "OpusTags", or a link in a chained file was encountered that did not - contain any logical Opus streams.*/ -#define OP_ENOTFORMAT (-132) -/**A required header packet was not properly formatted, contained illegal - values, or was missing altogether.*/ -#define OP_EBADHEADER (-133) -/**The ID header contained an unrecognized version number.*/ -#define OP_EVERSION (-134) -/*Currently not used at all.*/ -#define OP_ENOTAUDIO (-135) -/**An audio packet failed to decode properly. - This is usually caused by a multistream Ogg packet where the durations of - the individual Opus packets contained in it are not all the same.*/ -#define OP_EBADPACKET (-136) -/**We failed to find data we had seen before, or the bitstream structure was - sufficiently malformed that seeking to the target destination was - impossible.*/ -#define OP_EBADLINK (-137) -/**An operation that requires seeking was requested on an unseekable stream.*/ -#define OP_ENOSEEK (-138) -/**The first or last granule position of a link failed basic validity checks.*/ -#define OP_EBADTIMESTAMP (-139) - -/*@}*/ -/*@}*/ - -/**\defgroup header_info Header Information*/ -/*@{*/ - -/**The maximum number of channels in an Ogg Opus stream.*/ -#define OPUS_CHANNEL_COUNT_MAX (255) - -/**Ogg Opus bitstream information. - This contains the basic playback parameters for a stream, and corresponds to - the initial ID header packet of an Ogg Opus stream.*/ -struct OpusHead{ - /**The Ogg Opus format version, in the range 0...255. - The top 4 bits represent a "major" version, and the bottom four bits - represent backwards-compatible "minor" revisions. - The current specification describes version 1. - This library will recognize versions up through 15 as backwards compatible - with the current specification. - An earlier draft of the specification described a version 0, but the only - difference between version 1 and version 0 is that version 0 did - not specify the semantics for handling the version field.*/ - int version; - /**The number of channels, in the range 1...255.*/ - int channel_count; - /**The number of samples that should be discarded from the beginning of the - stream.*/ - unsigned pre_skip; - /**The sampling rate of the original input. - All Opus audio is coded at 48 kHz, and should also be decoded at 48 kHz - for playback (unless the target hardware does not support this sampling - rate). - However, this field may be used to resample the audio back to the original - sampling rate, for example, when saving the output to a file.*/ - opus_uint32 input_sample_rate; - /**The gain to apply to the decoded output, in dB, as a Q8 value in the range - -32768...32767. - The libopusfile API will automatically apply this gain to the - decoded output before returning it, scaling it by - pow(10,output_gain/(20.0*256)). - You can adjust this behavior with op_set_gain_offset().*/ - int output_gain; - /**The channel mapping family, in the range 0...255. - Channel mapping family 0 covers mono or stereo in a single stream. - Channel mapping family 1 covers 1 to 8 channels in one or more streams, - using the Vorbis speaker assignments. - Channel mapping family 255 covers 1 to 255 channels in one or more - streams, but without any defined speaker assignment.*/ - int mapping_family; - /**The number of Opus streams in each Ogg packet, in the range 1...255.*/ - int stream_count; - /**The number of coupled Opus streams in each Ogg packet, in the range - 0...127. - This must satisfy 0 <= coupled_count <= stream_count and - coupled_count + stream_count <= 255. - The coupled streams appear first, before all uncoupled streams, in an Ogg - Opus packet.*/ - int coupled_count; - /**The mapping from coded stream channels to output channels. - Let index=mapping[k] be the value for channel k. - If index<2*coupled_count, then it refers to the left channel - from stream (index/2) if even, and the right channel from - stream (index/2) if odd. - Otherwise, it refers to the output of the uncoupled stream - (index-coupled_count).*/ - unsigned char mapping[OPUS_CHANNEL_COUNT_MAX]; -}; - -/**The metadata from an Ogg Opus stream. - - This structure holds the in-stream metadata corresponding to the 'comment' - header packet of an Ogg Opus stream. - The comment header is meant to be used much like someone jotting a quick - note on the label of a CD. - It should be a short, to the point text note that can be more than a couple - words, but not more than a short paragraph. - - The metadata is stored as a series of (tag, value) pairs, in length-encoded - string vectors, using the same format as Vorbis (without the final "framing - bit"), Theora, and Speex, except for the packet header. - The first occurrence of the '=' character delimits the tag and value. - A particular tag may occur more than once, and order is significant. - The character set encoding for the strings is always UTF-8, but the tag - names are limited to ASCII, and treated as case-insensitive. - See the Vorbis - comment header specification for details. - - In filling in this structure, libopusfile will null-terminate the - #user_comments strings for safety. - However, the bitstream format itself treats them as 8-bit clean vectors, - possibly containing NUL characters, so the #comment_lengths array should be - treated as their authoritative length. - - This structure is binary and source-compatible with a - vorbis_comment, and pointers to it may be freely cast to - vorbis_comment pointers, and vice versa. - It is provided as a separate type to avoid introducing a compile-time - dependency on the libvorbis headers.*/ -struct OpusTags{ - /**The array of comment string vectors.*/ - char **user_comments; - /**An array of the corresponding length of each vector, in bytes.*/ - int *comment_lengths; - /**The total number of comment streams.*/ - int comments; - /**The null-terminated vendor string. - This identifies the software used to encode the stream.*/ - char *vendor; -}; - -/**\name Picture tag image formats*/ -/*@{*/ - -/**The MIME type was not recognized, or the image data did not match the - declared MIME type.*/ -#define OP_PIC_FORMAT_UNKNOWN (-1) -/**The MIME type indicates the image data is really a URL.*/ -#define OP_PIC_FORMAT_URL (0) -/**The image is a JPEG.*/ -#define OP_PIC_FORMAT_JPEG (1) -/**The image is a PNG.*/ -#define OP_PIC_FORMAT_PNG (2) -/**The image is a GIF.*/ -#define OP_PIC_FORMAT_GIF (3) - -/*@}*/ - -/**The contents of a METADATA_BLOCK_PICTURE tag.*/ -struct OpusPictureTag{ - /**The picture type according to the ID3v2 APIC frame: -
    -
  1. Other
  2. -
  3. 32x32 pixels 'file icon' (PNG only)
  4. -
  5. Other file icon
  6. -
  7. Cover (front)
  8. -
  9. Cover (back)
  10. -
  11. Leaflet page
  12. -
  13. Media (e.g. label side of CD)
  14. -
  15. Lead artist/lead performer/soloist
  16. -
  17. Artist/performer
  18. -
  19. Conductor
  20. -
  21. Band/Orchestra
  22. -
  23. Composer
  24. -
  25. Lyricist/text writer
  26. -
  27. Recording Location
  28. -
  29. During recording
  30. -
  31. During performance
  32. -
  33. Movie/video screen capture
  34. -
  35. A bright colored fish
  36. -
  37. Illustration
  38. -
  39. Band/artist logotype
  40. -
  41. Publisher/Studio logotype
  42. -
- Others are reserved and should not be used. - There may only be one each of picture type 1 and 2 in a file.*/ - opus_int32 type; - /**The MIME type of the picture, in printable ASCII characters 0x20-0x7E. - The MIME type may also be "-->" to signify that the data part - is a URL pointing to the picture instead of the picture data itself. - In this case, a terminating NUL is appended to the URL string in #data, - but #data_length is set to the length of the string excluding that - terminating NUL.*/ - char *mime_type; - /**The description of the picture, in UTF-8.*/ - char *description; - /**The width of the picture in pixels.*/ - opus_uint32 width; - /**The height of the picture in pixels.*/ - opus_uint32 height; - /**The color depth of the picture in bits-per-pixel (not - bits-per-channel).*/ - opus_uint32 depth; - /**For indexed-color pictures (e.g., GIF), the number of colors used, or 0 - for non-indexed pictures.*/ - opus_uint32 colors; - /**The length of the picture data in bytes.*/ - opus_uint32 data_length; - /**The binary picture data.*/ - unsigned char *data; - /**The format of the picture data, if known. - One of -
    -
  • #OP_PIC_FORMAT_UNKNOWN,
  • -
  • #OP_PIC_FORMAT_URL,
  • -
  • #OP_PIC_FORMAT_JPEG,
  • -
  • #OP_PIC_FORMAT_PNG, or
  • -
  • #OP_PIC_FORMAT_GIF.
  • -
*/ - int format; -}; - -/**\name Functions for manipulating header data - - These functions manipulate the #OpusHead and #OpusTags structures, - which describe the audio parameters and tag-value metadata, respectively. - These can be used to query the headers returned by libopusfile, or - to parse Opus headers from sources other than an Ogg Opus stream, provided - they use the same format.*/ -/*@{*/ - -/**Parses the contents of the ID header packet of an Ogg Opus stream. - \param[out] _head Returns the contents of the parsed packet. - The contents of this structure are untouched on error. - This may be NULL to merely test the header - for validity. - \param[in] _data The contents of the ID header packet. - \param _len The number of bytes of data in the ID header packet. - \return 0 on success or a negative value on error. - \retval #OP_ENOTFORMAT If the data does not start with the "OpusHead" - string. - \retval #OP_EVERSION If the version field signaled a version this library - does not know how to parse. - \retval #OP_EIMPL If the channel mapping family was 255, which general - purpose players should not attempt to play. - \retval #OP_EBADHEADER If the contents of the packet otherwise violate the - Ogg Opus specification: -
    -
  • Insufficient data,
  • -
  • Too much data for the known minor versions,
  • -
  • An unrecognized channel mapping family,
  • -
  • Zero channels or too many channels,
  • -
  • Zero coded streams,
  • -
  • Too many coupled streams, or
  • -
  • An invalid channel mapping index.
  • -
*/ -OP_WARN_UNUSED_RESULT int opus_head_parse(OpusHead *_head, - const unsigned char *_data,size_t _len) OP_ARG_NONNULL(2); - -/**Converts a granule position to a sample offset for a given Ogg Opus stream. - The sample offset is simply _gp-_head->pre_skip. - Granule position values smaller than OpusHead#pre_skip correspond to audio - that should never be played, and thus have no associated sample offset. - This function returns -1 for such values. - This function also correctly handles extremely large granule positions, - which may have wrapped around to a negative number when stored in a signed - ogg_int64_t value. - \param _head The #OpusHead information from the ID header of the stream. - \param _gp The granule position to convert. - \return The sample offset associated with the given granule position - (counting at a 48 kHz sampling rate), or the special value -1 on - error (i.e., the granule position was smaller than the pre-skip - amount).*/ -ogg_int64_t opus_granule_sample(const OpusHead *_head,ogg_int64_t _gp) - OP_ARG_NONNULL(1); - -/**Parses the contents of the 'comment' header packet of an Ogg Opus stream. - \param[out] _tags An uninitialized #OpusTags structure. - This returns the contents of the parsed packet. - The contents of this structure are untouched on error. - This may be NULL to merely test the header - for validity. - \param[in] _data The contents of the 'comment' header packet. - \param _len The number of bytes of data in the 'info' header packet. - \retval 0 Success. - \retval #OP_ENOTFORMAT If the data does not start with the "OpusTags" - string. - \retval #OP_EBADHEADER If the contents of the packet otherwise violate the - Ogg Opus specification. - \retval #OP_EFAULT If there wasn't enough memory to store the tags.*/ -OP_WARN_UNUSED_RESULT int opus_tags_parse(OpusTags *_tags, - const unsigned char *_data,size_t _len) OP_ARG_NONNULL(2); - -/**Performs a deep copy of an #OpusTags structure. - \param _dst The #OpusTags structure to copy into. - If this function fails, the contents of this structure remain - untouched. - \param _src The #OpusTags structure to copy from. - \retval 0 Success. - \retval #OP_EFAULT If there wasn't enough memory to copy the tags.*/ -int opus_tags_copy(OpusTags *_dst,const OpusTags *_src) OP_ARG_NONNULL(1); - -/**Initializes an #OpusTags structure. - This should be called on a freshly allocated #OpusTags structure before - attempting to use it. - \param _tags The #OpusTags structure to initialize.*/ -void opus_tags_init(OpusTags *_tags) OP_ARG_NONNULL(1); - -/**Add a (tag, value) pair to an initialized #OpusTags structure. - \note Neither opus_tags_add() nor opus_tags_add_comment() support values - containing embedded NULs, although the bitstream format does support them. - To add such tags, you will need to manipulate the #OpusTags structure - directly. - \param _tags The #OpusTags structure to add the (tag, value) pair to. - \param _tag A NUL-terminated, case-insensitive, ASCII string containing - the tag to add (without an '=' character). - \param _value A NUL-terminated UTF-8 containing the corresponding value. - \return 0 on success, or a negative value on failure. - \retval #OP_EFAULT An internal memory allocation failed.*/ -int opus_tags_add(OpusTags *_tags,const char *_tag,const char *_value) - OP_ARG_NONNULL(1) OP_ARG_NONNULL(2) OP_ARG_NONNULL(3); - -/**Add a comment to an initialized #OpusTags structure. - \note Neither opus_tags_add_comment() nor opus_tags_add() support comments - containing embedded NULs, although the bitstream format does support them. - To add such tags, you will need to manipulate the #OpusTags structure - directly. - \param _tags The #OpusTags structure to add the comment to. - \param _comment A NUL-terminated UTF-8 string containing the comment in - "TAG=value" form. - \return 0 on success, or a negative value on failure. - \retval #OP_EFAULT An internal memory allocation failed.*/ -int opus_tags_add_comment(OpusTags *_tags,const char *_comment) - OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/**Replace the binary suffix data at the end of the packet (if any). - \param _tags An initialized #OpusTags structure. - \param _data A buffer of binary data to append after the encoded user - comments. - The least significant bit of the first byte of this data must - be set (to ensure the data is preserved by other editors). - \param _len The number of bytes of binary data to append. - This may be zero to remove any existing binary suffix data. - \return 0 on success, or a negative value on error. - \retval #OP_EINVAL \a _len was negative, or \a _len was positive but - \a _data was NULL or the least significant - bit of the first byte was not set. - \retval #OP_EFAULT An internal memory allocation failed.*/ -int opus_tags_set_binary_suffix(OpusTags *_tags, - const unsigned char *_data,int _len) OP_ARG_NONNULL(1); - -/**Look up a comment value by its tag. - \param _tags An initialized #OpusTags structure. - \param _tag The tag to look up. - \param _count The instance of the tag. - The same tag can appear multiple times, each with a distinct - value, so an index is required to retrieve them all. - The order in which these values appear is significant and - should be preserved. - Use opus_tags_query_count() to get the legal range for the - \a _count parameter. - \return A pointer to the queried tag's value. - This points directly to data in the #OpusTags structure. - It should not be modified or freed by the application, and - modifications to the structure may invalidate the pointer. - \retval NULL If no matching tag is found.*/ -const char *opus_tags_query(const OpusTags *_tags,const char *_tag,int _count) - OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/**Look up the number of instances of a tag. - Call this first when querying for a specific tag and then iterate over the - number of instances with separate calls to opus_tags_query() to retrieve - all the values for that tag in order. - \param _tags An initialized #OpusTags structure. - \param _tag The tag to look up. - \return The number of instances of this particular tag.*/ -int opus_tags_query_count(const OpusTags *_tags,const char *_tag) - OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/**Retrieve the binary suffix data at the end of the packet (if any). - \param _tags An initialized #OpusTags structure. - \param[out] _len Returns the number of bytes of binary suffix data returned. - \return A pointer to the binary suffix data, or NULL if none - was present.*/ -const unsigned char *opus_tags_get_binary_suffix(const OpusTags *_tags, - int *_len) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/**Get the album gain from an R128_ALBUM_GAIN tag, if one was specified. - This searches for the first R128_ALBUM_GAIN tag with a valid signed, - 16-bit decimal integer value and returns the value. - This routine is exposed merely for convenience for applications which wish - to do something special with the album gain (i.e., display it). - If you simply wish to apply the album gain instead of the header gain, you - can use op_set_gain_offset() with an #OP_ALBUM_GAIN type and no offset. - \param _tags An initialized #OpusTags structure. - \param[out] _gain_q8 The album gain, in 1/256ths of a dB. - This will lie in the range [-32768,32767], and should - be applied in addition to the header gain. - On error, no value is returned, and the previous - contents remain unchanged. - \return 0 on success, or a negative value on error. - \retval #OP_FALSE There was no album gain available in the given tags.*/ -int opus_tags_get_album_gain(const OpusTags *_tags,int *_gain_q8) - OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/**Get the track gain from an R128_TRACK_GAIN tag, if one was specified. - This searches for the first R128_TRACK_GAIN tag with a valid signed, - 16-bit decimal integer value and returns the value. - This routine is exposed merely for convenience for applications which wish - to do something special with the track gain (i.e., display it). - If you simply wish to apply the track gain instead of the header gain, you - can use op_set_gain_offset() with an #OP_TRACK_GAIN type and no offset. - \param _tags An initialized #OpusTags structure. - \param[out] _gain_q8 The track gain, in 1/256ths of a dB. - This will lie in the range [-32768,32767], and should - be applied in addition to the header gain. - On error, no value is returned, and the previous - contents remain unchanged. - \return 0 on success, or a negative value on error. - \retval #OP_FALSE There was no track gain available in the given tags.*/ -int opus_tags_get_track_gain(const OpusTags *_tags,int *_gain_q8) - OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/**Clears the #OpusTags structure. - This should be called on an #OpusTags structure after it is no longer - needed. - It will free all memory used by the structure members. - \param _tags The #OpusTags structure to clear.*/ -void opus_tags_clear(OpusTags *_tags) OP_ARG_NONNULL(1); - -/**Check if \a _comment is an instance of a \a _tag_name tag. - \see opus_tagncompare - \param _tag_name A NUL-terminated, case-insensitive, ASCII string containing - the name of the tag to check for (without the terminating - '=' character). - \param _comment The comment string to check. - \return An integer less than, equal to, or greater than zero if \a _comment - is found respectively, to be less than, to match, or be greater - than a "tag=value" string whose tag matches \a _tag_name.*/ -int opus_tagcompare(const char *_tag_name,const char *_comment); - -/**Check if \a _comment is an instance of a \a _tag_name tag. - This version is slightly more efficient than opus_tagcompare() if the length - of the tag name is already known (e.g., because it is a constant). - \see opus_tagcompare - \param _tag_name A case-insensitive ASCII string containing the name of the - tag to check for (without the terminating '=' character). - \param _tag_len The number of characters in the tag name. - This must be non-negative. - \param _comment The comment string to check. - \return An integer less than, equal to, or greater than zero if \a _comment - is found respectively, to be less than, to match, or be greater - than a "tag=value" string whose tag matches the first \a _tag_len - characters of \a _tag_name.*/ -int opus_tagncompare(const char *_tag_name,int _tag_len,const char *_comment); - -/**Parse a single METADATA_BLOCK_PICTURE tag. - This decodes the BASE64-encoded content of the tag and returns a structure - with the MIME type, description, image parameters (if known), and the - compressed image data. - If the MIME type indicates the presence of an image format we recognize - (JPEG, PNG, or GIF) and the actual image data contains the magic signature - associated with that format, then the OpusPictureTag::format field will be - set to the corresponding format. - This is provided as a convenience to avoid requiring applications to parse - the MIME type and/or do their own format detection for the commonly used - formats. - In this case, we also attempt to extract the image parameters directly from - the image data (overriding any that were present in the tag, which the - specification says applications are not meant to rely on). - The application must still provide its own support for actually decoding the - image data and, if applicable, retrieving that data from URLs. - \param[out] _pic Returns the parsed picture data. - No sanitation is done on the type, MIME type, or - description fields, so these might return invalid values. - The contents of this structure are left unmodified on - failure. - \param _tag The METADATA_BLOCK_PICTURE tag contents. - The leading "METADATA_BLOCK_PICTURE=" portion is optional, - to allow the function to be used on either directly on the - values in OpusTags::user_comments or on the return value - of opus_tags_query(). - \return 0 on success or a negative value on error. - \retval #OP_ENOTFORMAT The METADATA_BLOCK_PICTURE contents were not valid. - \retval #OP_EFAULT There was not enough memory to store the picture tag - contents.*/ -OP_WARN_UNUSED_RESULT int opus_picture_tag_parse(OpusPictureTag *_pic, - const char *_tag) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/**Initializes an #OpusPictureTag structure. - This should be called on a freshly allocated #OpusPictureTag structure - before attempting to use it. - \param _pic The #OpusPictureTag structure to initialize.*/ -void opus_picture_tag_init(OpusPictureTag *_pic) OP_ARG_NONNULL(1); - -/**Clears the #OpusPictureTag structure. - This should be called on an #OpusPictureTag structure after it is no longer - needed. - It will free all memory used by the structure members. - \param _pic The #OpusPictureTag structure to clear.*/ -void opus_picture_tag_clear(OpusPictureTag *_pic) OP_ARG_NONNULL(1); - -/*@}*/ - -/*@}*/ - -/**\defgroup url_options URL Reading Options*/ -/*@{*/ -/**\name URL reading options - Options for op_url_stream_create() and associated functions. - These allow you to provide proxy configuration parameters, skip SSL - certificate checks, etc. - Options are processed in order, and if the same option is passed multiple - times, only the value specified by the last occurrence has an effect - (unless otherwise specified). - They may be expanded in the future.*/ -/*@{*/ - -/**@cond PRIVATE*/ - -/*These are the raw numbers used to define the request codes. - They should not be used directly.*/ -#define OP_SSL_SKIP_CERTIFICATE_CHECK_REQUEST (6464) -#define OP_HTTP_PROXY_HOST_REQUEST (6528) -#define OP_HTTP_PROXY_PORT_REQUEST (6592) -#define OP_HTTP_PROXY_USER_REQUEST (6656) -#define OP_HTTP_PROXY_PASS_REQUEST (6720) -#define OP_GET_SERVER_INFO_REQUEST (6784) - -#define OP_URL_OPT(_request) ((_request)+(char *)0) - -/*These macros trigger compilation errors or warnings if the wrong types are - provided to one of the URL options.*/ -#define OP_CHECK_INT(_x) ((void)((_x)==(opus_int32)0),(opus_int32)(_x)) -#define OP_CHECK_CONST_CHAR_PTR(_x) ((_x)+((_x)-(const char *)(_x))) -#define OP_CHECK_SERVER_INFO_PTR(_x) ((_x)+((_x)-(OpusServerInfo *)(_x))) - -/**@endcond*/ - -/**HTTP/Shoutcast/Icecast server information associated with a URL.*/ -struct OpusServerInfo{ - /**The name of the server (icy-name/ice-name). - This is NULL if there was no icy-name or - ice-name header.*/ - char *name; - /**A short description of the server (icy-description/ice-description). - This is NULL if there was no icy-description or - ice-description header.*/ - char *description; - /**The genre the server falls under (icy-genre/ice-genre). - This is NULL if there was no icy-genre or - ice-genre header.*/ - char *genre; - /**The homepage for the server (icy-url/ice-url). - This is NULL if there was no icy-url or - ice-url header.*/ - char *url; - /**The software used by the origin server (Server). - This is NULL if there was no Server header.*/ - char *server; - /**The media type of the entity sent to the recipient (Content-Type). - This is NULL if there was no Content-Type - header.*/ - char *content_type; - /**The nominal stream bitrate in kbps (icy-br/ice-bitrate). - This is -1 if there was no icy-br or - ice-bitrate header.*/ - opus_int32 bitrate_kbps; - /**Flag indicating whether the server is public (1) or not - (0) (icy-pub/ice-public). - This is -1 if there was no icy-pub or - ice-public header.*/ - int is_public; - /**Flag indicating whether the server is using HTTPS instead of HTTP. - This is 0 unless HTTPS is being used. - This may not match the protocol used in the original URL if there were - redirections.*/ - int is_ssl; -}; - -/**Initializes an #OpusServerInfo structure. - All fields are set as if the corresponding header was not available. - \param _info The #OpusServerInfo structure to initialize. - \note If you use this function, you must link against libopusurl.*/ -void opus_server_info_init(OpusServerInfo *_info) OP_ARG_NONNULL(1); - -/**Clears the #OpusServerInfo structure. - This should be called on an #OpusServerInfo structure after it is no longer - needed. - It will free all memory used by the structure members. - \param _info The #OpusServerInfo structure to clear. - \note If you use this function, you must link against libopusurl.*/ -void opus_server_info_clear(OpusServerInfo *_info) OP_ARG_NONNULL(1); - -/**Skip the certificate check when connecting via TLS/SSL (https). - \param _b opus_int32: Whether or not to skip the certificate - check. - The check will be skipped if \a _b is non-zero, and will not be - skipped if \a _b is zero. - \hideinitializer*/ -#define OP_SSL_SKIP_CERTIFICATE_CHECK(_b) \ - OP_URL_OPT(OP_SSL_SKIP_CERTIFICATE_CHECK_REQUEST),OP_CHECK_INT(_b) - -/**Proxy connections through the given host. - If no port is specified via #OP_HTTP_PROXY_PORT, the port number defaults - to 8080 (http-alt). - All proxy parameters are ignored for non-http and non-https URLs. - \param _host const char *: The proxy server hostname. - This may be NULL to disable the use of a proxy - server. - \hideinitializer*/ -#define OP_HTTP_PROXY_HOST(_host) \ - OP_URL_OPT(OP_HTTP_PROXY_HOST_REQUEST),OP_CHECK_CONST_CHAR_PTR(_host) - -/**Use the given port when proxying connections. - This option only has an effect if #OP_HTTP_PROXY_HOST is specified with a - non-NULL \a _host. - If this option is not provided, the proxy port number defaults to 8080 - (http-alt). - All proxy parameters are ignored for non-http and non-https URLs. - \param _port opus_int32: The proxy server port. - This must be in the range 0...65535 (inclusive), or the - URL function this is passed to will fail. - \hideinitializer*/ -#define OP_HTTP_PROXY_PORT(_port) \ - OP_URL_OPT(OP_HTTP_PROXY_PORT_REQUEST),OP_CHECK_INT(_port) - -/**Use the given user name for authentication when proxying connections. - All proxy parameters are ignored for non-http and non-https URLs. - \param _user const char *: The proxy server user name. - This may be NULL to disable proxy - authentication. - A non-NULL value only has an effect - if #OP_HTTP_PROXY_HOST and #OP_HTTP_PROXY_PASS - are also specified with non-NULL - arguments. - \hideinitializer*/ -#define OP_HTTP_PROXY_USER(_user) \ - OP_URL_OPT(OP_HTTP_PROXY_USER_REQUEST),OP_CHECK_CONST_CHAR_PTR(_user) - -/**Use the given password for authentication when proxying connections. - All proxy parameters are ignored for non-http and non-https URLs. - \param _pass const char *: The proxy server password. - This may be NULL to disable proxy - authentication. - A non-NULL value only has an effect - if #OP_HTTP_PROXY_HOST and #OP_HTTP_PROXY_USER - are also specified with non-NULL - arguments. - \hideinitializer*/ -#define OP_HTTP_PROXY_PASS(_pass) \ - OP_URL_OPT(OP_HTTP_PROXY_PASS_REQUEST),OP_CHECK_CONST_CHAR_PTR(_pass) - -/**Parse information about the streaming server (if any) and return it. - Very little validation is done. - In particular, OpusServerInfo::url may not be a valid URL, - OpusServerInfo::bitrate_kbps may not really be in kbps, and - OpusServerInfo::content_type may not be a valid MIME type. - The character set of the string fields is not specified anywhere, and should - not be assumed to be valid UTF-8. - \param _info OpusServerInfo *: Returns information about the server. - If there is any error opening the stream, the - contents of this structure remain - unmodified. - On success, fills in the structure with the - server information that was available, if - any. - After a successful return, the contents of - this structure should be freed by calling - opus_server_info_clear(). - \hideinitializer*/ -#define OP_GET_SERVER_INFO(_info) \ - OP_URL_OPT(OP_GET_SERVER_INFO_REQUEST),OP_CHECK_SERVER_INFO_PTR(_info) - -/*@}*/ -/*@}*/ - -/**\defgroup stream_callbacks Abstract Stream Reading Interface*/ -/*@{*/ -/**\name Functions for reading from streams - These functions define the interface used to read from and seek in a stream - of data. - A stream does not need to implement seeking, but the decoder will not be - able to seek if it does not do so. - These functions also include some convenience routines for working with - standard FILE pointers, complete streams stored in a single - block of memory, or URLs.*/ -/*@{*/ - -/**Reads up to \a _nbytes bytes of data from \a _stream. - \param _stream The stream to read from. - \param[out] _ptr The buffer to store the data in. - \param _nbytes The maximum number of bytes to read. - This function may return fewer, though it will not - return zero unless it reaches end-of-file. - \return The number of bytes successfully read, or a negative value on - error.*/ -typedef int (*op_read_func)(void *_stream,unsigned char *_ptr,int _nbytes); - -/**Sets the position indicator for \a _stream. - The new position, measured in bytes, is obtained by adding \a _offset - bytes to the position specified by \a _whence. - If \a _whence is set to SEEK_SET, SEEK_CUR, or - SEEK_END, the offset is relative to the start of the stream, - the current position indicator, or end-of-file, respectively. - \retval 0 Success. - \retval -1 Seeking is not supported or an error occurred. - errno need not be set.*/ -typedef int (*op_seek_func)(void *_stream,opus_int64 _offset,int _whence); - -/**Obtains the current value of the position indicator for \a _stream. - \return The current position indicator.*/ -typedef opus_int64 (*op_tell_func)(void *_stream); - -/**Closes the underlying stream. - \retval 0 Success. - \retval EOF An error occurred. - errno need not be set.*/ -typedef int (*op_close_func)(void *_stream); - -/**The callbacks used to access non-FILE stream resources. - The function prototypes are basically the same as for the stdio functions - fread(), fseek(), ftell(), and - fclose(). - The differences are that the FILE * arguments have been - replaced with a void *, which is to be used as a pointer to - whatever internal data these functions might need, that #seek and #tell - take and return 64-bit offsets, and that #seek must return -1 if - the stream is unseekable.*/ -struct OpusFileCallbacks{ - /**Used to read data from the stream. - This must not be NULL.*/ - op_read_func read; - /**Used to seek in the stream. - This may be NULL if seeking is not implemented.*/ - op_seek_func seek; - /**Used to return the current read position in the stream. - This may be NULL if seeking is not implemented.*/ - op_tell_func tell; - /**Used to close the stream when the decoder is freed. - This may be NULL to leave the stream open.*/ - op_close_func close; -}; - -/**Opens a stream with fopen() and fills in a set of callbacks - that can be used to access it. - This is useful to avoid writing your own portable 64-bit seeking wrappers, - and also avoids cross-module linking issues on Windows, where a - FILE * must be accessed by routines defined in the same module - that opened it. - \param[out] _cb The callbacks to use for this file. - If there is an error opening the file, nothing will be - filled in here. - \param _path The path to the file to open. - On Windows, this string must be UTF-8 (to allow access to - files whose names cannot be represented in the current - MBCS code page). - All other systems use the native character encoding. - \param _mode The mode to open the file in. - \return A stream handle to use with the callbacks, or NULL on - error.*/ -OP_WARN_UNUSED_RESULT void *op_fopen(OpusFileCallbacks *_cb, - const char *_path,const char *_mode) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2) - OP_ARG_NONNULL(3); - -/**Opens a stream with fdopen() and fills in a set of callbacks - that can be used to access it. - This is useful to avoid writing your own portable 64-bit seeking wrappers, - and also avoids cross-module linking issues on Windows, where a - FILE * must be accessed by routines defined in the same module - that opened it. - \param[out] _cb The callbacks to use for this file. - If there is an error opening the file, nothing will be - filled in here. - \param _fd The file descriptor to open. - \param _mode The mode to open the file in. - \return A stream handle to use with the callbacks, or NULL on - error.*/ -OP_WARN_UNUSED_RESULT void *op_fdopen(OpusFileCallbacks *_cb, - int _fd,const char *_mode) OP_ARG_NONNULL(1) OP_ARG_NONNULL(3); - -/**Opens a stream with freopen() and fills in a set of callbacks - that can be used to access it. - This is useful to avoid writing your own portable 64-bit seeking wrappers, - and also avoids cross-module linking issues on Windows, where a - FILE * must be accessed by routines defined in the same module - that opened it. - \param[out] _cb The callbacks to use for this file. - If there is an error opening the file, nothing will be - filled in here. - \param _path The path to the file to open. - On Windows, this string must be UTF-8 (to allow access - to files whose names cannot be represented in the - current MBCS code page). - All other systems use the native character encoding. - \param _mode The mode to open the file in. - \param _stream A stream previously returned by op_fopen(), op_fdopen(), - or op_freopen(). - \return A stream handle to use with the callbacks, or NULL on - error.*/ -OP_WARN_UNUSED_RESULT void *op_freopen(OpusFileCallbacks *_cb, - const char *_path,const char *_mode,void *_stream) OP_ARG_NONNULL(1) - OP_ARG_NONNULL(2) OP_ARG_NONNULL(3) OP_ARG_NONNULL(4); - -/**Creates a stream that reads from the given block of memory. - This block of memory must contain the complete stream to decode. - This is useful for caching small streams (e.g., sound effects) in RAM. - \param[out] _cb The callbacks to use for this stream. - If there is an error creating the stream, nothing will be - filled in here. - \param _data The block of memory to read from. - \param _size The size of the block of memory. - \return A stream handle to use with the callbacks, or NULL on - error.*/ -OP_WARN_UNUSED_RESULT void *op_mem_stream_create(OpusFileCallbacks *_cb, - const unsigned char *_data,size_t _size) OP_ARG_NONNULL(1); - -/**Creates a stream that reads from the given URL. - This function behaves identically to op_url_stream_create(), except that it - takes a va_list instead of a variable number of arguments. - It does not call the va_end macro, and because it invokes the - va_arg macro, the value of \a _ap is undefined after the call. - \note If you use this function, you must link against libopusurl. - \param[out] _cb The callbacks to use for this stream. - If there is an error creating the stream, nothing will - be filled in here. - \param _url The URL to read from. - Currently only the , , and - schemes are supported. - Both and may be disabled at compile - time, in which case opening such URLs will always fail. - Currently this only supports URIs. - IRIs should be converted to UTF-8 and URL-escaped, with - internationalized domain names encoded in punycode, - before passing them to this function. - \param[in,out] _ap A list of the \ref url_options "optional flags" to use. - This is a variable-length list of options terminated - with NULL. - \return A stream handle to use with the callbacks, or NULL on - error.*/ -OP_WARN_UNUSED_RESULT void *op_url_stream_vcreate(OpusFileCallbacks *_cb, - const char *_url,va_list _ap) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/**Creates a stream that reads from the given URL. - \note If you use this function, you must link against libopusurl. - \param[out] _cb The callbacks to use for this stream. - If there is an error creating the stream, nothing will be - filled in here. - \param _url The URL to read from. - Currently only the , , and schemes - are supported. - Both and may be disabled at compile time, - in which case opening such URLs will always fail. - Currently this only supports URIs. - IRIs should be converted to UTF-8 and URL-escaped, with - internationalized domain names encoded in punycode, before - passing them to this function. - \param ... The \ref url_options "optional flags" to use. - This is a variable-length list of options terminated with - NULL. - \return A stream handle to use with the callbacks, or NULL on - error.*/ -OP_WARN_UNUSED_RESULT void *op_url_stream_create(OpusFileCallbacks *_cb, - const char *_url,...) OP_ARG_NONNULL(1) OP_ARG_NONNULL(2); - -/*@}*/ -/*@}*/ - -/**\defgroup stream_open_close Opening and Closing*/ -/*@{*/ -/**\name Functions for opening and closing streams - - These functions allow you to test a stream to see if it is Opus, open it, - and close it. - Several flavors are provided for each of the built-in stream types, plus a - more general version which takes a set of application-provided callbacks.*/ -/*@{*/ - -/**Test to see if this is an Opus stream. - For good results, you will need at least 57 bytes (for a pure Opus-only - stream). - Something like 512 bytes will give more reliable results for multiplexed - streams. - This function is meant to be a quick-rejection filter. - Its purpose is not to guarantee that a stream is a valid Opus stream, but to - ensure that it looks enough like Opus that it isn't going to be recognized - as some other format (except possibly an Opus stream that is also - multiplexed with other codecs, such as video). - \param[out] _head The parsed ID header contents. - You may pass NULL if you do not need - this information. - If the function fails, the contents of this structure - remain untouched. - \param _initial_data An initial buffer of data from the start of the - stream. - \param _initial_bytes The number of bytes in \a _initial_data. - \return 0 if the data appears to be Opus, or a negative value on error. - \retval #OP_FALSE There was not enough data to tell if this was an Opus - stream or not. - \retval #OP_EFAULT An internal memory allocation failed. - \retval #OP_EIMPL The stream used a feature that is not implemented, - such as an unsupported channel family. - \retval #OP_ENOTFORMAT If the data did not contain a recognizable ID - header for an Opus stream. - \retval #OP_EVERSION If the version field signaled a version this library - does not know how to parse. - \retval #OP_EBADHEADER The ID header was not properly formatted or contained - illegal values.*/ -int op_test(OpusHead *_head, - const unsigned char *_initial_data,size_t _initial_bytes); - -/**Open a stream from the given file path. - \param _path The path to the file to open. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want the - failure code. - The failure code will be #OP_EFAULT if the file could not - be opened, or one of the other failure codes from - op_open_callbacks() otherwise. - \return A freshly opened \c OggOpusFile, or NULL on error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_open_file(const char *_path,int *_error) - OP_ARG_NONNULL(1); - -/**Open a stream from a memory buffer. - \param _data The memory buffer to open. - \param _size The number of bytes in the buffer. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want the - failure code. - See op_open_callbacks() for a full list of failure codes. - \return A freshly opened \c OggOpusFile, or NULL on error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_open_memory(const unsigned char *_data, - size_t _size,int *_error); - -/**Open a stream from a URL. - This function behaves identically to op_open_url(), except that it - takes a va_list instead of a variable number of arguments. - It does not call the va_end macro, and because it invokes the - va_arg macro, the value of \a _ap is undefined after the call. - \note If you use this function, you must link against libopusurl. - \param _url The URL to open. - Currently only the , , and - schemes are supported. - Both and may be disabled at compile - time, in which case opening such URLs will always - fail. - Currently this only supports URIs. - IRIs should be converted to UTF-8 and URL-escaped, - with internationalized domain names encoded in - punycode, before passing them to this function. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want - the failure code. - See op_open_callbacks() for a full list of failure - codes. - \param[in,out] _ap A list of the \ref url_options "optional flags" to - use. - This is a variable-length list of options terminated - with NULL. - \return A freshly opened \c OggOpusFile, or NULL on error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_vopen_url(const char *_url, - int *_error,va_list _ap) OP_ARG_NONNULL(1); - -/**Open a stream from a URL. - \note If you use this function, you must link against libopusurl. - \param _url The URL to open. - Currently only the , , and schemes - are supported. - Both and may be disabled at compile - time, in which case opening such URLs will always fail. - Currently this only supports URIs. - IRIs should be converted to UTF-8 and URL-escaped, with - internationalized domain names encoded in punycode, - before passing them to this function. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want the - failure code. - See op_open_callbacks() for a full list of failure codes. - \param ... The \ref url_options "optional flags" to use. - This is a variable-length list of options terminated with - NULL. - \return A freshly opened \c OggOpusFile, or NULL on error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_open_url(const char *_url, - int *_error,...) OP_ARG_NONNULL(1); - -/**Open a stream using the given set of callbacks to access it. - \param _stream The stream to read from (e.g., a FILE *). - This value will be passed verbatim as the first - argument to all of the callbacks. - \param _cb The callbacks with which to access the stream. - read() must - be implemented. - seek() and - tell() may - be NULL, or may always return -1 to - indicate a stream is unseekable, but if - seek() is - implemented and succeeds on a particular stream, then - tell() must - also. - close() may - be NULL, but if it is not, it will be - called when the \c OggOpusFile is destroyed by - op_free(). - It will not be called if op_open_callbacks() fails - with an error. - \param _initial_data An initial buffer of data from the start of the - stream. - Applications can read some number of bytes from the - start of the stream to help identify this as an Opus - stream, and then provide them here to allow the - stream to be opened, even if it is unseekable. - \param _initial_bytes The number of bytes in \a _initial_data. - If the stream is seekable, its current position (as - reported by - tell() - at the start of this function) must be equal to - \a _initial_bytes. - Otherwise, seeking to absolute positions will - generate inconsistent results. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want - the failure code. - The failure code will be one of -
-
#OP_EREAD
-
An underlying read, seek, or tell operation - failed when it should have succeeded, or we failed - to find data in the stream we had seen before.
-
#OP_EFAULT
-
There was a memory allocation failure, or an - internal library error.
-
#OP_EIMPL
-
The stream used a feature that is not - implemented, such as an unsupported channel - family.
-
#OP_EINVAL
-
seek() - was implemented and succeeded on this source, but - tell() - did not, or the starting position indicator was - not equal to \a _initial_bytes.
-
#OP_ENOTFORMAT
-
The stream contained a link that did not have - any logical Opus streams in it.
-
#OP_EBADHEADER
-
A required header packet was not properly - formatted, contained illegal values, or was missing - altogether.
-
#OP_EVERSION
-
An ID header contained an unrecognized version - number.
-
#OP_EBADLINK
-
We failed to find data we had seen before after - seeking.
-
#OP_EBADTIMESTAMP
-
The first or last timestamp in a link failed - basic validity checks.
-
- \return A freshly opened \c OggOpusFile, or NULL on error. - libopusfile does not take ownership of the stream - if the call fails. - The calling application is responsible for closing the stream if - this call returns an error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_open_callbacks(void *_stream, - const OpusFileCallbacks *_cb,const unsigned char *_initial_data, - size_t _initial_bytes,int *_error) OP_ARG_NONNULL(2); - -/**Partially open a stream from the given file path. - \see op_test_callbacks - \param _path The path to the file to open. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want the - failure code. - The failure code will be #OP_EFAULT if the file could not - be opened, or one of the other failure codes from - op_open_callbacks() otherwise. - \return A partially opened \c OggOpusFile, or NULL on error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_test_file(const char *_path,int *_error) - OP_ARG_NONNULL(1); - -/**Partially open a stream from a memory buffer. - \see op_test_callbacks - \param _data The memory buffer to open. - \param _size The number of bytes in the buffer. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want the - failure code. - See op_open_callbacks() for a full list of failure codes. - \return A partially opened \c OggOpusFile, or NULL on error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_test_memory(const unsigned char *_data, - size_t _size,int *_error); - -/**Partially open a stream from a URL. - This function behaves identically to op_test_url(), except that it - takes a va_list instead of a variable number of arguments. - It does not call the va_end macro, and because it invokes the - va_arg macro, the value of \a _ap is undefined after the call. - \note If you use this function, you must link against libopusurl. - \see op_test_url - \see op_test_callbacks - \param _url The URL to open. - Currently only the , , and - schemes are supported. - Both and may be disabled at compile - time, in which case opening such URLs will always - fail. - Currently this only supports URIs. - IRIs should be converted to UTF-8 and URL-escaped, - with internationalized domain names encoded in - punycode, before passing them to this function. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want - the failure code. - See op_open_callbacks() for a full list of failure - codes. - \param[in,out] _ap A list of the \ref url_options "optional flags" to - use. - This is a variable-length list of options terminated - with NULL. - \return A partially opened \c OggOpusFile, or NULL on error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_vtest_url(const char *_url, - int *_error,va_list _ap) OP_ARG_NONNULL(1); - -/**Partially open a stream from a URL. - \note If you use this function, you must link against libopusurl. - \see op_test_callbacks - \param _url The URL to open. - Currently only the , , and - schemes are supported. - Both and may be disabled at compile - time, in which case opening such URLs will always fail. - Currently this only supports URIs. - IRIs should be converted to UTF-8 and URL-escaped, with - internationalized domain names encoded in punycode, - before passing them to this function. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want the - failure code. - See op_open_callbacks() for a full list of failure - codes. - \param ... The \ref url_options "optional flags" to use. - This is a variable-length list of options terminated - with NULL. - \return A partially opened \c OggOpusFile, or NULL on error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_test_url(const char *_url, - int *_error,...) OP_ARG_NONNULL(1); - -/**Partially open a stream using the given set of callbacks to access it. - This tests for Opusness and loads the headers for the first link. - It does not seek (although it tests for seekability). - You can query a partially open stream for the few pieces of basic - information returned by op_serialno(), op_channel_count(), op_head(), and - op_tags() (but only for the first link). - You may also determine if it is seekable via a call to op_seekable(). - You cannot read audio from the stream, seek, get the size or duration, - get information from links other than the first one, or even get the total - number of links until you finish opening the stream with op_test_open(). - If you do not need to do any of these things, you can dispose of it with - op_free() instead. - - This function is provided mostly to simplify porting existing code that used - libvorbisfile. - For new code, you are likely better off using op_test() instead, which - is less resource-intensive, requires less data to succeed, and imposes a - hard limit on the amount of data it examines (important for unseekable - streams, where all such data must be buffered until you are sure of the - stream type). - \param _stream The stream to read from (e.g., a FILE *). - This value will be passed verbatim as the first - argument to all of the callbacks. - \param _cb The callbacks with which to access the stream. - read() must - be implemented. - seek() and - tell() may - be NULL, or may always return -1 to - indicate a stream is unseekable, but if - seek() is - implemented and succeeds on a particular stream, then - tell() must - also. - close() may - be NULL, but if it is not, it will be - called when the \c OggOpusFile is destroyed by - op_free(). - It will not be called if op_open_callbacks() fails - with an error. - \param _initial_data An initial buffer of data from the start of the - stream. - Applications can read some number of bytes from the - start of the stream to help identify this as an Opus - stream, and then provide them here to allow the - stream to be tested more thoroughly, even if it is - unseekable. - \param _initial_bytes The number of bytes in \a _initial_data. - If the stream is seekable, its current position (as - reported by - tell() - at the start of this function) must be equal to - \a _initial_bytes. - Otherwise, seeking to absolute positions will - generate inconsistent results. - \param[out] _error Returns 0 on success, or a failure code on error. - You may pass in NULL if you don't want - the failure code. - See op_open_callbacks() for a full list of failure - codes. - \return A partially opened \c OggOpusFile, or NULL on error. - libopusfile does not take ownership of the stream - if the call fails. - The calling application is responsible for closing the stream if - this call returns an error.*/ -OP_WARN_UNUSED_RESULT OggOpusFile *op_test_callbacks(void *_stream, - const OpusFileCallbacks *_cb,const unsigned char *_initial_data, - size_t _initial_bytes,int *_error) OP_ARG_NONNULL(2); - -/**Finish opening a stream partially opened with op_test_callbacks() or one of - the associated convenience functions. - If this function fails, you are still responsible for freeing the - \c OggOpusFile with op_free(). - \param _of The \c OggOpusFile to finish opening. - \return 0 on success, or a negative value on error. - \retval #OP_EREAD An underlying read, seek, or tell operation failed - when it should have succeeded. - \retval #OP_EFAULT There was a memory allocation failure, or an - internal library error. - \retval #OP_EIMPL The stream used a feature that is not implemented, - such as an unsupported channel family. - \retval #OP_EINVAL The stream was not partially opened with - op_test_callbacks() or one of the associated - convenience functions. - \retval #OP_ENOTFORMAT The stream contained a link that did not have any - logical Opus streams in it. - \retval #OP_EBADHEADER A required header packet was not properly - formatted, contained illegal values, or was - missing altogether. - \retval #OP_EVERSION An ID header contained an unrecognized version - number. - \retval #OP_EBADLINK We failed to find data we had seen before after - seeking. - \retval #OP_EBADTIMESTAMP The first or last timestamp in a link failed basic - validity checks.*/ -int op_test_open(OggOpusFile *_of) OP_ARG_NONNULL(1); - -/**Release all memory used by an \c OggOpusFile. - \param _of The \c OggOpusFile to free.*/ -void op_free(OggOpusFile *_of); - -/*@}*/ -/*@}*/ - -/**\defgroup stream_info Stream Information*/ -/*@{*/ -/**\name Functions for obtaining information about streams - - These functions allow you to get basic information about a stream, including - seekability, the number of links (for chained streams), plus the size, - duration, bitrate, header parameters, and meta information for each link - (or, where available, the stream as a whole). - Some of these (size, duration) are only available for seekable streams. - You can also query the current stream position, link, and playback time, - and instantaneous bitrate during playback. - - Some of these functions may be used successfully on the partially open - streams returned by op_test_callbacks() or one of the associated - convenience functions. - Their documentation will indicate so explicitly.*/ -/*@{*/ - -/**Returns whether or not the stream being read is seekable. - This is true if -
    -
  1. The seek() and - tell() callbacks are both - non-NULL,
  2. -
  3. The seek() callback was - successfully executed at least once, and
  4. -
  5. The tell() callback was - successfully able to report the position indicator afterwards.
  6. -
- This function may be called on partially-opened streams. - \param _of The \c OggOpusFile whose seekable status is to be returned. - \return A non-zero value if seekable, and 0 if unseekable.*/ -int op_seekable(const OggOpusFile *_of) OP_ARG_NONNULL(1); - -/**Returns the number of links in this chained stream. - This function may be called on partially-opened streams, but it will always - return 1. - The actual number of links is not known until the stream is fully opened. - \param _of The \c OggOpusFile from which to retrieve the link count. - \return For fully-open seekable streams, this returns the total number of - links in the whole stream, which will be at least 1. - For partially-open or unseekable streams, this always returns 1.*/ -int op_link_count(const OggOpusFile *_of) OP_ARG_NONNULL(1); - -/**Get the serial number of the given link in a (possibly-chained) Ogg Opus - stream. - This function may be called on partially-opened streams, but it will always - return the serial number of the Opus stream in the first link. - \param _of The \c OggOpusFile from which to retrieve the serial number. - \param _li The index of the link whose serial number should be retrieved. - Use a negative number to get the serial number of the current - link. - \return The serial number of the given link. - If \a _li is greater than the total number of links, this returns - the serial number of the last link. - If the stream is not seekable, this always returns the serial number - of the current link.*/ -opus_uint32 op_serialno(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); - -/**Get the channel count of the given link in a (possibly-chained) Ogg Opus - stream. - This is equivalent to op_head(_of,_li)->channel_count, but - is provided for convenience. - This function may be called on partially-opened streams, but it will always - return the channel count of the Opus stream in the first link. - \param _of The \c OggOpusFile from which to retrieve the channel count. - \param _li The index of the link whose channel count should be retrieved. - Use a negative number to get the channel count of the current - link. - \return The channel count of the given link. - If \a _li is greater than the total number of links, this returns - the channel count of the last link. - If the stream is not seekable, this always returns the channel count - of the current link.*/ -int op_channel_count(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); - -/**Get the total (compressed) size of the stream, or of an individual link in - a (possibly-chained) Ogg Opus stream, including all headers and Ogg muxing - overhead. - \warning If the Opus stream (or link) is concurrently multiplexed with other - logical streams (e.g., video), this returns the size of the entire stream - (or link), not just the number of bytes in the first logical Opus stream. - Returning the latter would require scanning the entire file. - \param _of The \c OggOpusFile from which to retrieve the compressed size. - \param _li The index of the link whose compressed size should be computed. - Use a negative number to get the compressed size of the entire - stream. - \return The compressed size of the entire stream if \a _li is negative, the - compressed size of link \a _li if it is non-negative, or a negative - value on error. - The compressed size of the entire stream may be smaller than that - of the underlying stream if trailing garbage was detected in the - file. - \retval #OP_EINVAL The stream is not seekable (so we can't know the length), - \a _li wasn't less than the total number of links in - the stream, or the stream was only partially open.*/ -opus_int64 op_raw_total(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); - -/**Get the total PCM length (number of samples at 48 kHz) of the stream, or of - an individual link in a (possibly-chained) Ogg Opus stream. - Users looking for op_time_total() should use op_pcm_total() - instead. - Because timestamps in Opus are fixed at 48 kHz, there is no need for a - separate function to convert this to seconds (and leaving it out avoids - introducing floating point to the API, for those that wish to avoid it). - \param _of The \c OggOpusFile from which to retrieve the PCM offset. - \param _li The index of the link whose PCM length should be computed. - Use a negative number to get the PCM length of the entire stream. - \return The PCM length of the entire stream if \a _li is negative, the PCM - length of link \a _li if it is non-negative, or a negative value on - error. - \retval #OP_EINVAL The stream is not seekable (so we can't know the length), - \a _li wasn't less than the total number of links in - the stream, or the stream was only partially open.*/ -ogg_int64_t op_pcm_total(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); - -/**Get the ID header information for the given link in a (possibly chained) Ogg - Opus stream. - This function may be called on partially-opened streams, but it will always - return the ID header information of the Opus stream in the first link. - \param _of The \c OggOpusFile from which to retrieve the ID header - information. - \param _li The index of the link whose ID header information should be - retrieved. - Use a negative number to get the ID header information of the - current link. - For an unseekable stream, \a _li is ignored, and the ID header - information for the current link is always returned, if - available. - \return The contents of the ID header for the given link.*/ -const OpusHead *op_head(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); - -/**Get the comment header information for the given link in a (possibly - chained) Ogg Opus stream. - This function may be called on partially-opened streams, but it will always - return the tags from the Opus stream in the first link. - \param _of The \c OggOpusFile from which to retrieve the comment header - information. - \param _li The index of the link whose comment header information should be - retrieved. - Use a negative number to get the comment header information of - the current link. - For an unseekable stream, \a _li is ignored, and the comment - header information for the current link is always returned, if - available. - \return The contents of the comment header for the given link, or - NULL if this is an unseekable stream that encountered - an invalid link.*/ -const OpusTags *op_tags(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); - -/**Retrieve the index of the current link. - This is the link that produced the data most recently read by - op_read_float() or its associated functions, or, after a seek, the link - that the seek target landed in. - Reading more data may advance the link index (even on the first read after a - seek). - \param _of The \c OggOpusFile from which to retrieve the current link index. - \return The index of the current link on success, or a negative value on - failure. - For seekable streams, this is a number between 0 (inclusive) and the - value returned by op_link_count() (exclusive). - For unseekable streams, this value starts at 0 and increments by one - each time a new link is encountered (even though op_link_count() - always returns 1). - \retval #OP_EINVAL The stream was only partially open.*/ -int op_current_link(const OggOpusFile *_of) OP_ARG_NONNULL(1); - -/**Computes the bitrate of the stream, or of an individual link in a - (possibly-chained) Ogg Opus stream. - The stream must be seekable to compute the bitrate. - For unseekable streams, use op_bitrate_instant() to get periodic estimates. - \warning If the Opus stream (or link) is concurrently multiplexed with other - logical streams (e.g., video), this uses the size of the entire stream (or - link) to compute the bitrate, not just the number of bytes in the first - logical Opus stream. - Returning the latter requires scanning the entire file, but this may be done - by decoding the whole file and calling op_bitrate_instant() once at the - end. - Install a trivial decoding callback with op_set_decode_callback() if you - wish to skip actual decoding during this process. - \param _of The \c OggOpusFile from which to retrieve the bitrate. - \param _li The index of the link whose bitrate should be computed. - Use a negative number to get the bitrate of the whole stream. - \return The bitrate on success, or a negative value on error. - \retval #OP_EINVAL The stream was only partially open, the stream was not - seekable, or \a _li was larger than the number of - links.*/ -opus_int32 op_bitrate(const OggOpusFile *_of,int _li) OP_ARG_NONNULL(1); - -/**Compute the instantaneous bitrate, measured as the ratio of bits to playable - samples decoded since a) the last call to op_bitrate_instant(), b) the last - seek, or c) the start of playback, whichever was most recent. - This will spike somewhat after a seek or at the start/end of a chain - boundary, as pre-skip, pre-roll, and end-trimming causes samples to be - decoded but not played. - \param _of The \c OggOpusFile from which to retrieve the bitrate. - \return The bitrate, in bits per second, or a negative value on error. - \retval #OP_FALSE No data has been decoded since any of the events - described above. - \retval #OP_EINVAL The stream was only partially open.*/ -opus_int32 op_bitrate_instant(OggOpusFile *_of) OP_ARG_NONNULL(1); - -/**Obtain the current value of the position indicator for \a _of. - \param _of The \c OggOpusFile from which to retrieve the position indicator. - \return The byte position that is currently being read from. - \retval #OP_EINVAL The stream was only partially open.*/ -opus_int64 op_raw_tell(const OggOpusFile *_of) OP_ARG_NONNULL(1); - -/**Obtain the PCM offset of the next sample to be read. - If the stream is not properly timestamped, this might not increment by the - proper amount between reads, or even return monotonically increasing - values. - \param _of The \c OggOpusFile from which to retrieve the PCM offset. - \return The PCM offset of the next sample to be read. - \retval #OP_EINVAL The stream was only partially open.*/ -ogg_int64_t op_pcm_tell(const OggOpusFile *_of) OP_ARG_NONNULL(1); - -/*@}*/ -/*@}*/ - -/**\defgroup stream_seeking Seeking*/ -/*@{*/ -/**\name Functions for seeking in Opus streams - - These functions let you seek in Opus streams, if the underlying stream - support it. - Seeking is implemented for all built-in stream I/O routines, though some - individual streams may not be seekable (pipes, live HTTP streams, or HTTP - streams from a server that does not support Range requests). - - op_raw_seek() is the fastest: it is guaranteed to perform at most one - physical seek, but, since the target is a byte position, makes no guarantee - how close to a given time it will come. - op_pcm_seek() provides sample-accurate seeking. - The number of physical seeks it requires is still quite small (often 1 or - 2, even in highly variable bitrate streams). - - Seeking in Opus requires decoding some pre-roll amount before playback to - allow the internal state to converge (as if recovering from packet loss). - This is handled internally by libopusfile, but means there is - little extra overhead for decoding up to the exact position requested - (since it must decode some amount of audio anyway). - It also means that decoding after seeking may not return exactly the same - values as would be obtained by decoding the stream straight through. - However, such differences are expected to be smaller than the loss - introduced by Opus's lossy compression.*/ -/*@{*/ - -/**Seek to a byte offset relative to the compressed data. - This also scans packets to update the PCM cursor. - It will cross a logical bitstream boundary, but only if it can't get any - packets out of the tail of the link to which it seeks. - \param _of The \c OggOpusFile in which to seek. - \param _byte_offset The byte position to seek to. - This must be between 0 and #op_raw_total(\a _of,\c -1) - (inclusive). - \return 0 on success, or a negative error code on failure. - \retval #OP_EREAD The underlying seek operation failed. - \retval #OP_EINVAL The stream was only partially open, or the target was - outside the valid range for the stream. - \retval #OP_ENOSEEK This stream is not seekable. - \retval #OP_EBADLINK Failed to initialize a decoder for a stream for an - unknown reason.*/ -int op_raw_seek(OggOpusFile *_of,opus_int64 _byte_offset) OP_ARG_NONNULL(1); - -/**Seek to the specified PCM offset, such that decoding will begin at exactly - the requested position. - \param _of The \c OggOpusFile in which to seek. - \param _pcm_offset The PCM offset to seek to. - This is in samples at 48 kHz relative to the start of the - stream. - \return 0 on success, or a negative value on error. - \retval #OP_EREAD An underlying read or seek operation failed. - \retval #OP_EINVAL The stream was only partially open, or the target was - outside the valid range for the stream. - \retval #OP_ENOSEEK This stream is not seekable. - \retval #OP_EBADLINK We failed to find data we had seen before, or the - bitstream structure was sufficiently malformed that - seeking to the target destination was impossible.*/ -int op_pcm_seek(OggOpusFile *_of,ogg_int64_t _pcm_offset) OP_ARG_NONNULL(1); - -/*@}*/ -/*@}*/ - -/**\defgroup stream_decoding Decoding*/ -/*@{*/ -/**\name Functions for decoding audio data - - These functions retrieve actual decoded audio data from the stream. - The general functions, op_read() and op_read_float() return 16-bit or - floating-point output, both using native endian ordering. - The number of channels returned can change from link to link in a chained - stream. - There are special functions, op_read_stereo() and op_read_float_stereo(), - which always output two channels, to simplify applications which do not - wish to handle multichannel audio. - These downmix multichannel files to two channels, so they can always return - samples in the same format for every link in a chained file. - - If the rest of your audio processing chain can handle floating point, the - floating-point routines should be preferred, as they prevent clipping and - other issues which might be avoided entirely if, e.g., you scale down the - volume at some other stage. - However, if you intend to consume 16-bit samples directly, the conversion in - libopusfile provides noise-shaping dithering and, if compiled - against libopus 1.1 or later, soft-clipping prevention. - - libopusfile can also be configured at compile time to use the - fixed-point libopus API. - If so, libopusfile's floating-point API may also be disabled. - In that configuration, nothing in libopusfile will use any - floating-point operations, to simplify support on devices without an - adequate FPU. - - \warning HTTPS streams may be vulnerable to truncation attacks if you do - not check the error return code from op_read_float() or its associated - functions. - If the remote peer does not close the connection gracefully (with a TLS - "close notify" message), these functions will return #OP_EREAD instead of 0 - when they reach the end of the file. - If you are reading from an URL (particularly if seeking is not - supported), you should make sure to check for this error and warn the user - appropriately.*/ -/*@{*/ - -/**Indicates that the decoding callback should produce signed 16-bit - native-endian output samples.*/ -#define OP_DEC_FORMAT_SHORT (7008) -/**Indicates that the decoding callback should produce 32-bit native-endian - float samples.*/ -#define OP_DEC_FORMAT_FLOAT (7040) - -/**Indicates that the decoding callback did not decode anything, and that - libopusfile should decode normally instead.*/ -#define OP_DEC_USE_DEFAULT (6720) - -/**Called to decode an Opus packet. - This should invoke the functional equivalent of opus_multistream_decode() or - opus_multistream_decode_float(), except that it returns 0 on success - instead of the number of decoded samples (which is known a priori). - \param _ctx The application-provided callback context. - \param _decoder The decoder to use to decode the packet. - \param[out] _pcm The buffer to decode into. - This will always have enough room for \a _nchannels of - \a _nsamples samples, which should be placed into this - buffer interleaved. - \param _op The packet to decode. - This will always have its granule position set to a valid - value. - \param _nsamples The number of samples expected from the packet. - \param _nchannels The number of channels expected from the packet. - \param _format The desired sample output format. - This is either #OP_DEC_FORMAT_SHORT or - #OP_DEC_FORMAT_FLOAT. - \param _li The index of the link from which this packet was decoded. - \return A non-negative value on success, or a negative value on error. - Any error codes should be the same as those returned by - opus_multistream_decode() or opus_multistream_decode_float(). - Success codes are as follows: - \retval 0 Decoding was successful. - The application has filled the buffer with - exactly \a _nsamples*\a - _nchannels samples in the requested - format. - \retval #OP_DEC_USE_DEFAULT No decoding was done. - libopusfile should do the decoding - by itself instead.*/ -typedef int (*op_decode_cb_func)(void *_ctx,OpusMSDecoder *_decoder,void *_pcm, - const ogg_packet *_op,int _nsamples,int _nchannels,int _format,int _li); - -/**Sets the packet decode callback function. - If set, this is called once for each packet that needs to be decoded. - This can be used by advanced applications to do additional processing on the - compressed or uncompressed data. - For example, an application might save the final entropy coder state for - debugging and testing purposes, or it might apply additional filters - before the downmixing, dithering, or soft-clipping performed by - libopusfile, so long as these filters do not introduce any - latency. - - A call to this function is no guarantee that the audio will eventually be - delivered to the application. - libopusfile may discard some or all of the decoded audio data - (i.e., at the beginning or end of a link, or after a seek), however the - callback is still required to provide all of it. - \param _of The \c OggOpusFile on which to set the decode callback. - \param _decode_cb The callback function to call. - This may be NULL to disable calling the - callback. - \param _ctx The application-provided context pointer to pass to the - callback on each call.*/ -void op_set_decode_callback(OggOpusFile *_of, - op_decode_cb_func _decode_cb,void *_ctx) OP_ARG_NONNULL(1); - -/**Gain offset type that indicates that the provided offset is relative to the - header gain. - This is the default.*/ -#define OP_HEADER_GAIN (0) - -/**Gain offset type that indicates that the provided offset is relative to the - R128_ALBUM_GAIN value (if any), in addition to the header gain.*/ -#define OP_ALBUM_GAIN (3007) - -/**Gain offset type that indicates that the provided offset is relative to the - R128_TRACK_GAIN value (if any), in addition to the header gain.*/ -#define OP_TRACK_GAIN (3008) - -/**Gain offset type that indicates that the provided offset should be used as - the gain directly, without applying any the header or track gains.*/ -#define OP_ABSOLUTE_GAIN (3009) - -/**Sets the gain to be used for decoded output. - By default, the gain in the header is applied with no additional offset. - The total gain (including header gain and/or track gain, if applicable, and - this offset), will be clamped to [-32768,32767]/256 dB. - This is more than enough to saturate or underflow 16-bit PCM. - \note The new gain will not be applied to any already buffered, decoded - output. - This means you cannot change it sample-by-sample, as at best it will be - updated packet-by-packet. - It is meant for setting a target volume level, rather than applying smooth - fades, etc. - \param _of The \c OggOpusFile on which to set the gain offset. - \param _gain_type One of #OP_HEADER_GAIN, #OP_ALBUM_GAIN, - #OP_TRACK_GAIN, or #OP_ABSOLUTE_GAIN. - \param _gain_offset_q8 The gain offset to apply, in 1/256ths of a dB. - \return 0 on success or a negative value on error. - \retval #OP_EINVAL The \a _gain_type was unrecognized.*/ -int op_set_gain_offset(OggOpusFile *_of, - int _gain_type,opus_int32 _gain_offset_q8) OP_ARG_NONNULL(1); - -/**Sets whether or not dithering is enabled for 16-bit decoding. - By default, when libopusfile is compiled to use floating-point - internally, calling op_read() or op_read_stereo() will first decode to - float, and then convert to fixed-point using noise-shaping dithering. - This flag can be used to disable that dithering. - When the application uses op_read_float() or op_read_float_stereo(), or when - the library has been compiled to decode directly to fixed point, this flag - has no effect. - \param _of The \c OggOpusFile on which to enable or disable dithering. - \param _enabled A non-zero value to enable dithering, or 0 to disable it.*/ -void op_set_dither_enabled(OggOpusFile *_of,int _enabled) OP_ARG_NONNULL(1); - -/**Reads more samples from the stream. - \note Although \a _buf_size must indicate the total number of values that - can be stored in \a _pcm, the return value is the number of samples - per channel. - This is done because -
    -
  1. The channel count cannot be known a priori (reading more samples might - advance us into the next link, with a different channel count), so - \a _buf_size cannot also be in units of samples per channel,
  2. -
  3. Returning the samples per channel matches the libopus API - as closely as we're able,
  4. -
  5. Returning the total number of values instead of samples per channel - would mean the caller would need a division to compute the samples per - channel, and might worry about the possibility of getting back samples - for some channels and not others, and
  6. -
  7. This approach is relatively fool-proof: if an application passes too - small a value to \a _buf_size, they will simply get fewer samples back, - and if they assume the return value is the total number of values, then - they will simply read too few (rather than reading too many and going - off the end of the buffer).
  8. -
- \param _of The \c OggOpusFile from which to read. - \param[out] _pcm A buffer in which to store the output PCM samples, as - signed native-endian 16-bit values at 48 kHz - with a nominal range of [-32768,32767). - Multiple channels are interleaved using the - Vorbis - channel ordering. - This must have room for at least \a _buf_size values. - \param _buf_size The number of values that can be stored in \a _pcm. - It is recommended that this be large enough for at - least 120 ms of data at 48 kHz per channel (5760 - values per channel). - Smaller buffers will simply return less data, possibly - consuming more memory to buffer the data internally. - libopusfile may return less data than - requested. - If so, there is no guarantee that the remaining data - in \a _pcm will be unmodified. - \param[out] _li The index of the link this data was decoded from. - You may pass NULL if you do not need this - information. - If this function fails (returning a negative value), - this parameter is left unset. - \return The number of samples read per channel on success, or a negative - value on failure. - The channel count can be retrieved on success by calling - op_head(_of,*_li). - The number of samples returned may be 0 if the buffer was too small - to store even a single sample for all channels, or if end-of-file - was reached. - The list of possible failure codes follows. - Most of them can only be returned by unseekable, chained streams - that encounter a new link. - \retval #OP_HOLE There was a hole in the data, and some samples - may have been skipped. - Call this function again to continue decoding - past the hole. - \retval #OP_EREAD An underlying read operation failed. - This may signal a truncation attack from an - source. - \retval #OP_EFAULT An internal memory allocation failed. - \retval #OP_EIMPL An unseekable stream encountered a new link that - used a feature that is not implemented, such as - an unsupported channel family. - \retval #OP_EINVAL The stream was only partially open. - \retval #OP_ENOTFORMAT An unseekable stream encountered a new link that - did not have any logical Opus streams in it. - \retval #OP_EBADHEADER An unseekable stream encountered a new link with a - required header packet that was not properly - formatted, contained illegal values, or was - missing altogether. - \retval #OP_EVERSION An unseekable stream encountered a new link with - an ID header that contained an unrecognized - version number. - \retval #OP_EBADPACKET Failed to properly decode the next packet. - \retval #OP_EBADLINK We failed to find data we had seen before. - \retval #OP_EBADTIMESTAMP An unseekable stream encountered a new link with - a starting timestamp that failed basic validity - checks.*/ -OP_WARN_UNUSED_RESULT int op_read(OggOpusFile *_of, - opus_int16 *_pcm,int _buf_size,int *_li) OP_ARG_NONNULL(1); - -/**Reads more samples from the stream. - \note Although \a _buf_size must indicate the total number of values that - can be stored in \a _pcm, the return value is the number of samples - per channel. -
    -
  1. The channel count cannot be known a priori (reading more samples might - advance us into the next link, with a different channel count), so - \a _buf_size cannot also be in units of samples per channel,
  2. -
  3. Returning the samples per channel matches the libopus API - as closely as we're able,
  4. -
  5. Returning the total number of values instead of samples per channel - would mean the caller would need a division to compute the samples per - channel, and might worry about the possibility of getting back samples - for some channels and not others, and
  6. -
  7. This approach is relatively fool-proof: if an application passes too - small a value to \a _buf_size, they will simply get fewer samples back, - and if they assume the return value is the total number of values, then - they will simply read too few (rather than reading too many and going - off the end of the buffer).
  8. -
- \param _of The \c OggOpusFile from which to read. - \param[out] _pcm A buffer in which to store the output PCM samples as - signed floats at 48 kHz with a nominal range of - [-1.0,1.0]. - Multiple channels are interleaved using the - Vorbis - channel ordering. - This must have room for at least \a _buf_size floats. - \param _buf_size The number of floats that can be stored in \a _pcm. - It is recommended that this be large enough for at - least 120 ms of data at 48 kHz per channel (5760 - samples per channel). - Smaller buffers will simply return less data, possibly - consuming more memory to buffer the data internally. - If less than \a _buf_size values are returned, - libopusfile makes no guarantee that the - remaining data in \a _pcm will be unmodified. - \param[out] _li The index of the link this data was decoded from. - You may pass NULL if you do not need this - information. - If this function fails (returning a negative value), - this parameter is left unset. - \return The number of samples read per channel on success, or a negative - value on failure. - The channel count can be retrieved on success by calling - op_head(_of,*_li). - The number of samples returned may be 0 if the buffer was too small - to store even a single sample for all channels, or if end-of-file - was reached. - The list of possible failure codes follows. - Most of them can only be returned by unseekable, chained streams - that encounter a new link. - \retval #OP_HOLE There was a hole in the data, and some samples - may have been skipped. - Call this function again to continue decoding - past the hole. - \retval #OP_EREAD An underlying read operation failed. - This may signal a truncation attack from an - source. - \retval #OP_EFAULT An internal memory allocation failed. - \retval #OP_EIMPL An unseekable stream encountered a new link that - used a feature that is not implemented, such as - an unsupported channel family. - \retval #OP_EINVAL The stream was only partially open. - \retval #OP_ENOTFORMAT An unseekable stream encountered a new link that - did not have any logical Opus streams in it. - \retval #OP_EBADHEADER An unseekable stream encountered a new link with a - required header packet that was not properly - formatted, contained illegal values, or was - missing altogether. - \retval #OP_EVERSION An unseekable stream encountered a new link with - an ID header that contained an unrecognized - version number. - \retval #OP_EBADPACKET Failed to properly decode the next packet. - \retval #OP_EBADLINK We failed to find data we had seen before. - \retval #OP_EBADTIMESTAMP An unseekable stream encountered a new link with - a starting timestamp that failed basic validity - checks.*/ -OP_WARN_UNUSED_RESULT int op_read_float(OggOpusFile *_of, - float *_pcm,int _buf_size,int *_li) OP_ARG_NONNULL(1); - -/**Reads more samples from the stream and downmixes to stereo, if necessary. - This function is intended for simple players that want a uniform output - format, even if the channel count changes between links in a chained - stream. - \note \a _buf_size indicates the total number of values that can be stored - in \a _pcm, while the return value is the number of samples per - channel, even though the channel count is known, for consistency with - op_read(). - \param _of The \c OggOpusFile from which to read. - \param[out] _pcm A buffer in which to store the output PCM samples, as - signed native-endian 16-bit values at 48 kHz - with a nominal range of [-32768,32767). - The left and right channels are interleaved in the - buffer. - This must have room for at least \a _buf_size values. - \param _buf_size The number of values that can be stored in \a _pcm. - It is recommended that this be large enough for at - least 120 ms of data at 48 kHz per channel (11520 - values total). - Smaller buffers will simply return less data, possibly - consuming more memory to buffer the data internally. - If less than \a _buf_size values are returned, - libopusfile makes no guarantee that the - remaining data in \a _pcm will be unmodified. - \return The number of samples read per channel on success, or a negative - value on failure. - The number of samples returned may be 0 if the buffer was too small - to store even a single sample for both channels, or if end-of-file - was reached. - The list of possible failure codes follows. - Most of them can only be returned by unseekable, chained streams - that encounter a new link. - \retval #OP_HOLE There was a hole in the data, and some samples - may have been skipped. - Call this function again to continue decoding - past the hole. - \retval #OP_EREAD An underlying read operation failed. - This may signal a truncation attack from an - source. - \retval #OP_EFAULT An internal memory allocation failed. - \retval #OP_EIMPL An unseekable stream encountered a new link that - used a feature that is not implemented, such as - an unsupported channel family. - \retval #OP_EINVAL The stream was only partially open. - \retval #OP_ENOTFORMAT An unseekable stream encountered a new link that - did not have any logical Opus streams in it. - \retval #OP_EBADHEADER An unseekable stream encountered a new link with a - required header packet that was not properly - formatted, contained illegal values, or was - missing altogether. - \retval #OP_EVERSION An unseekable stream encountered a new link with - an ID header that contained an unrecognized - version number. - \retval #OP_EBADPACKET Failed to properly decode the next packet. - \retval #OP_EBADLINK We failed to find data we had seen before. - \retval #OP_EBADTIMESTAMP An unseekable stream encountered a new link with - a starting timestamp that failed basic validity - checks.*/ -OP_WARN_UNUSED_RESULT int op_read_stereo(OggOpusFile *_of, - opus_int16 *_pcm,int _buf_size) OP_ARG_NONNULL(1); - -/**Reads more samples from the stream and downmixes to stereo, if necessary. - This function is intended for simple players that want a uniform output - format, even if the channel count changes between links in a chained - stream. - \note \a _buf_size indicates the total number of values that can be stored - in \a _pcm, while the return value is the number of samples per - channel, even though the channel count is known, for consistency with - op_read_float(). - \param _of The \c OggOpusFile from which to read. - \param[out] _pcm A buffer in which to store the output PCM samples, as - signed floats at 48 kHz with a nominal range of - [-1.0,1.0]. - The left and right channels are interleaved in the - buffer. - This must have room for at least \a _buf_size values. - \param _buf_size The number of values that can be stored in \a _pcm. - It is recommended that this be large enough for at - least 120 ms of data at 48 kHz per channel (11520 - values total). - Smaller buffers will simply return less data, possibly - consuming more memory to buffer the data internally. - If less than \a _buf_size values are returned, - libopusfile makes no guarantee that the - remaining data in \a _pcm will be unmodified. - \return The number of samples read per channel on success, or a negative - value on failure. - The number of samples returned may be 0 if the buffer was too small - to store even a single sample for both channels, or if end-of-file - was reached. - The list of possible failure codes follows. - Most of them can only be returned by unseekable, chained streams - that encounter a new link. - \retval #OP_HOLE There was a hole in the data, and some samples - may have been skipped. - Call this function again to continue decoding - past the hole. - \retval #OP_EREAD An underlying read operation failed. - This may signal a truncation attack from an - source. - \retval #OP_EFAULT An internal memory allocation failed. - \retval #OP_EIMPL An unseekable stream encountered a new link that - used a feature that is not implemented, such as - an unsupported channel family. - \retval #OP_EINVAL The stream was only partially open. - \retval #OP_ENOTFORMAT An unseekable stream encountered a new link that - that did not have any logical Opus streams in it. - \retval #OP_EBADHEADER An unseekable stream encountered a new link with a - required header packet that was not properly - formatted, contained illegal values, or was - missing altogether. - \retval #OP_EVERSION An unseekable stream encountered a new link with - an ID header that contained an unrecognized - version number. - \retval #OP_EBADPACKET Failed to properly decode the next packet. - \retval #OP_EBADLINK We failed to find data we had seen before. - \retval #OP_EBADTIMESTAMP An unseekable stream encountered a new link with - a starting timestamp that failed basic validity - checks.*/ -OP_WARN_UNUSED_RESULT int op_read_float_stereo(OggOpusFile *_of, - float *_pcm,int _buf_size) OP_ARG_NONNULL(1); - -/*@}*/ -/*@}*/ - -# if OP_GNUC_PREREQ(4,0) -# pragma GCC visibility pop -# endif - -# if defined(__cplusplus) -} -# endif - -#endif diff --git a/include/timer.h b/include/timer.h index bd729ceb586..478be4b6f78 100644 --- a/include/timer.h +++ b/include/timer.h @@ -30,7 +30,8 @@ extern unsigned long PIT_TICK_RATE; -#define GetTicks() SDL_GetTicks() +extern uint32_t _GetTicks(); +#define GetTicks() _GetTicks() typedef void (*TIMER_TickHandler)(void); diff --git a/include/zip.h b/include/zip.h index f23d2220e8f..e9cec3e4e67 100644 --- a/include/zip.h +++ b/include/zip.h @@ -46,7 +46,7 @@ extern "C" { //#define HAVE_BZIP2 -#include "zlib.h" +// #include "zlib.h" #include "ioapi.h" #ifdef HAVE_BZIP2 diff --git a/src/builtin/xcopy/xcopy.c b/src/builtin/xcopy/xcopy.c index 113ae2c9eaa..58027bfec3e 100644 --- a/src/builtin/xcopy/xcopy.c +++ b/src/builtin/xcopy/xcopy.c @@ -306,7 +306,8 @@ int main(int argc, const char **argv) { /* filename/-pattern */ if (fileargc < 2) { /* no destination path specified -> use current */ - getcwd(dest_pathname, MAXPATH); + // getcwd(dest_pathname, MAXPATH); + strcpy(dest_pathname, "."); strmcpy(dest_filename, "*.*", sizeof(dest_filename)); } else { @@ -526,7 +527,7 @@ int make_dir(char *path) { if (tmp_path1[i] == '\\') { tmp_path2[i] = '\0'; if (!dir_exists(tmp_path2)) { - mkdir_error = mkdir(tmp_path2); + mkdir_error = 1; //mkdir(tmp_path2); if (mkdir_error) { path[i] = '\0'; return mkdir_error; diff --git a/src/debug/debug.cpp b/src/debug/debug.cpp index 2c362bf7a69..fe1f39f9935 100644 --- a/src/debug/debug.cpp +++ b/src/debug/debug.cpp @@ -51,6 +51,8 @@ using namespace std; #include "keyboard.h" #include "control.h" +extern void _Delay(uint32_t ticks); + bool Clear_SYSENTER_Debug(); bool Toggle_BreakSYSEnter(); bool Toggle_BreakSYSExit(); @@ -4451,7 +4453,7 @@ Bitu DEBUG_Loop(void) { uint16_t oldCS = SegValue(cs); uint32_t oldEIP = reg_eip; PIC_runIRQs(); - SDL_Delay(1); + _Delay(1); #if (C_DYNAMIC_X86) if (GetDynamicType() > 0) { diff --git a/src/debug/debug_gui.cpp b/src/debug/debug_gui.cpp index 94a5290e07c..a5e44a7b693 100644 --- a/src/debug/debug_gui.cpp +++ b/src/debug/debug_gui.cpp @@ -841,6 +841,7 @@ void LOG::operator() (char const* format, ...){ if (d_type>=LOG_MAX) return; if (d_severity < loggrp[d_type].min_severity) return; + printf("%10u%s %s:%s\n",static_cast(cycle_count),s_severity,loggrp[d_type].front,buf); DEBUG_ShowMsg("%10u%s %s:%s\n",static_cast(cycle_count),s_severity,loggrp[d_type].front,buf); } diff --git a/src/dos/cdrom.cpp b/src/dos/cdrom.cpp index 1a4ec924f92..5d2d57e0322 100644 --- a/src/dos/cdrom.cpp +++ b/src/dos/cdrom.cpp @@ -30,6 +30,8 @@ #include "drives.h" #include "cdrom.h" +#define SDL_CDROM_DUMMY +#include "../../vs/sdl/src/cdrom/dummy/SDL_syscdrom.c" #if defined(C_SDL2) #include "../../vs/sdl/src/cdrom/SDL_cdrom.c" #if defined(WIN32) @@ -37,7 +39,6 @@ #include "../../vs/sdl/src/cdrom/win32/SDL_syscdrom.c" #elif defined(LINUX) #define SDL_CDROM_LINUX -#include "../../vs/sdl/src/cdrom/linux/SDL_syscdrom.c" #elif defined(MACOSX) #define SDL_CDROM_MACOSX #include "../../vs/sdl/src/cdrom/macosx/SDL_syscdrom.c" diff --git a/src/dos/cdrom.h b/src/dos/cdrom.h index 7a096b3ef72..d71b4389e3b 100644 --- a/src/dos/cdrom.h +++ b/src/dos/cdrom.h @@ -64,6 +64,29 @@ // frames is described by the equation: // Sector = Minute * 60 * 75 + Second * 75 + Frame - 150 +struct CDTrack_t +{ + int offset; + int start; + int end; + int mode; + int loopEnabled; + int loopOffset; +}; + +#define MAX_CD_COUNT 10 +#define CD_MAX_TRACKS 100 + +struct CDData_t +{ + int numSectors; + int numTracks; + CDTrack_t tracks[CD_MAX_TRACKS]; +}; + +extern CDData_t _cdData[MAX_CD_COUNT]; + + enum { CDROM_USE_SDL, CDROM_USE_ASPI, CDROM_USE_IOCTL_DIO, CDROM_USE_IOCTL_DX, CDROM_USE_IOCTL_MCI }; //! \brief CD-ROM time stamp @@ -231,6 +254,8 @@ class CDROM_Interface_Fake : public CDROM_Interface class CDROM_Interface_Image : public CDROM_Interface { private: + std::string cdRomName; + // Nested Class Definitions class TrackFile { protected: @@ -410,6 +435,7 @@ class CDROM_Interface_Image : public CDROM_Interface static void CDAudioCallBack (Bitu len); // Private functions for cue sheet processing + bool LoadBizhawkCD(const char* cdName); bool LoadCueSheet(char *cuefile); bool LoadChdFile(char* chdfile); bool LoadCloneCDSheet(char *cuefile); diff --git a/src/dos/cdrom_image.cpp b/src/dos/cdrom_image.cpp index 8daa4ebc816..0fb9234e6b7 100644 --- a/src/dos/cdrom_image.cpp +++ b/src/dos/cdrom_image.cpp @@ -46,32 +46,6 @@ #include "logging.h" #include "support.h" #include "setup.h" -#include "src/libs/decoders/audio_convert.c" -#include "src/libs/decoders/SDL_sound.c" -#include "src/libs/decoders/vorbis.c" -#include "src/libs/decoders/flac.c" -#include "src/libs/decoders/opus.c" -#include "src/libs/decoders/wav.c" -#include "src/libs/decoders/mp3_seek_table.cpp" -#include "src/libs/decoders/mp3.cpp" -#include "src/libs/decoders/dr_flac.h" -#include "src/libs/libchdr/chd.h" -#include "src/libs/libchdr/libchdr_chd.c" -#include "src/libs/libchdr/libchdr_cdrom.c" -#include "src/libs/libchdr/libchdr_flac.c" -#include "src/libs/libchdr/libchdr_huffman.c" -#include "src/libs/libchdr/libchdr_bitstream.c" -#include "src/libs/libchdr/lzma/LzmaDec.c" -#include "src/libs/libchdr/lzma/LzmaEnc.c" -#include "src/libs/libchdr/lzma/LzFind.c" -#include "src/libs/libchdr/zstd/common/entropy_common.c" -#include "src/libs/libchdr/zstd/common/error_private.c" -#include "src/libs/libchdr/zstd/common/fse_decompress.c" -#include "src/libs/libchdr/zstd/common/zstd_common.c" -#include "src/libs/libchdr/zstd/decompress/huf_decompress.c" -#include "src/libs/libchdr/zstd/decompress/zstd_decompress_block.c" -#include "src/libs/libchdr/zstd/decompress/zstd_decompress.c" -#include "src/libs/libchdr/zstd/decompress/zstd_ddict.c" using namespace std; @@ -79,6 +53,8 @@ using namespace std; #define MAX_LINE_LENGTH 512 #define MAX_FILENAME_LENGTH 256 +extern bool _driveUsed; + std::string get_basename(const std::string& filename) { // Guard against corner cases: '', '/', '\', 'a' if (filename.length() <= 1) @@ -134,6 +110,7 @@ CDROM_Interface_Image::BinaryFile::~BinaryFile() bool CDROM_Interface_Image::BinaryFile::read(uint8_t *buffer,int64_t offset, int count) { + _driveUsed = true; if (!seek(offset)) return false; file->seekg((streampos)offset, ios::beg); file->read((char*)buffer, count); @@ -160,6 +137,8 @@ uint16_t CDROM_Interface_Image::BinaryFile::getEndian() bool CDROM_Interface_Image::BinaryFile::seek(int64_t offset) { + _driveUsed = true; + const auto pos = static_cast(offset); if (file->tellg() == pos) return true; @@ -177,6 +156,8 @@ bool CDROM_Interface_Image::BinaryFile::seek(int64_t offset) uint16_t CDROM_Interface_Image::BinaryFile::decode(uint8_t *buffer) { + _driveUsed = true; + if (static_cast(file->tellg()) != audio_pos) if (!seek(audio_pos)) return 0; @@ -189,6 +170,8 @@ uint16_t CDROM_Interface_Image::BinaryFile::decode(uint8_t *buffer) CDROM_Interface_Image::AudioFile::AudioFile(const char *filename, bool &error) : TrackFile(4096) { + _driveUsed = true; + // Use the audio file's actual sample rate and number of channels as opposed to overriding Sound_AudioInfo desired = {AUDIO_S16, 0, 0}; sample = Sound_NewSampleFromFile(filename, &desired, chunkSize); @@ -225,6 +208,8 @@ CDROM_Interface_Image::AudioFile::~AudioFile() */ bool CDROM_Interface_Image::AudioFile::seek(int64_t offset) { + _driveUsed = true; + #ifdef DEBUG const auto begin = std::chrono::steady_clock::now(); #endif @@ -250,6 +235,8 @@ bool CDROM_Interface_Image::AudioFile::seek(int64_t offset) uint16_t CDROM_Interface_Image::AudioFile::decode(uint8_t *buffer) { + _driveUsed = true; + const uint16_t bytes = Sound_Decode(sample); audio_pos += bytes; memcpy(buffer, sample->buffer, bytes); @@ -341,6 +328,8 @@ void hunk_thread_func(chd_file* chd, int hunk_index, uint8_t* buffer, bool* erro bool CDROM_Interface_Image::CHDFile::read(uint8_t* buffer,int64_t offset, int count) { + _driveUsed = true; + // we can not read more than a single sector currently if (count > RAW_SECTOR_SIZE) { return false; @@ -417,6 +406,8 @@ uint16_t CDROM_Interface_Image::CHDFile::getEndian() bool CDROM_Interface_Image::CHDFile::seek(int64_t offset) { + _driveUsed = true; + // only checks if seek range is valid ? only used for audio ? // only used by PlayAudioSector ? if ((uint32_t)((uint64_t)offset / this->header->hunkbytes) < this->header->hunkcount) { @@ -442,6 +433,8 @@ static void Endian_A16_Swap(void* src, uint32_t nelements) uint16_t CDROM_Interface_Image::CHDFile::decode(uint8_t* buffer) { + _driveUsed = true; + // reads one sector of CD audio ? assert(this->audio_pos % 2448 == 0); @@ -498,7 +491,7 @@ extern bool qmount; bool CDROM_Interface_Image::SetDevice(char* path, int forceCD) { (void)forceCD;//UNUSED - const bool result = LoadCueSheet(path) || LoadCloneCDSheet(path) || LoadIsoFile(path) || LoadChdFile(path); + const bool result = LoadBizhawkCD(path) || LoadCueSheet(path) || LoadCloneCDSheet(path) || LoadIsoFile(path) || LoadChdFile(path); if (!result && !qmount) { // print error message on dosbox-x console char buf[MAX_LINE_LENGTH]; @@ -531,6 +524,8 @@ bool CDROM_Interface_Image::GetUPC(unsigned char& attr, char* upc) bool CDROM_Interface_Image::GetAudioTracks(int& stTrack, int& end, TMSF& leadOut) { + _driveUsed = true; + stTrack = 1; end = (int)(tracks.size() - 1); FRAMES_TO_MSF(tracks[tracks.size() - 1].start + 150, &leadOut.min, &leadOut.sec, &leadOut.fr); @@ -572,6 +567,8 @@ extern const char* RunningProgram; bool CDROM_Interface_Image::GetAudioSub(unsigned char& attr, unsigned char& track, unsigned char& index, TMSF& relPos, TMSF& absPos) { + _driveUsed = true; + int cur_track = GetTrack(player.currFrame); if (cur_track < 1) return false; track = (unsigned char)cur_track; @@ -635,6 +632,8 @@ bool CDROM_Interface_Image::GetMediaTrayStatus(bool& mediaPresent, bool& mediaCh bool CDROM_Interface_Image::PlayAudioSector(unsigned long start, unsigned long len) { + _driveUsed = true; + bool is_playable(false); int track = GetTrack(start) - 1; int end = (int)(tracks.size() - 1); @@ -737,6 +736,8 @@ bool CDROM_Interface_Image::PlayAudioSector(unsigned long start, unsigned long l bool CDROM_Interface_Image::PauseAudio(bool resume) { + _driveUsed = true; + player.isPaused = !resume; if (player.channel) player.channel->Enable(resume); @@ -745,6 +746,8 @@ bool CDROM_Interface_Image::PauseAudio(bool resume) bool CDROM_Interface_Image::StopAudio(void) { + _driveUsed = true; + player.isPlaying = false; player.isPaused = false; if (player.channel) @@ -768,6 +771,8 @@ void CDROM_Interface_Image::ChannelControl(TCtrl ctrl) bool CDROM_Interface_Image::ReadSectors(PhysPt buffer, bool raw, unsigned long sector, unsigned long num) { + _driveUsed = true; + int sectorSize = raw ? RAW_SECTOR_SIZE : COOKED_SECTOR_SIZE; Bitu buflen = num * sectorSize; uint8_t* buf = new uint8_t[buflen]; @@ -785,6 +790,8 @@ bool CDROM_Interface_Image::ReadSectors(PhysPt buffer, bool raw, unsigned long s bool CDROM_Interface_Image::ReadSectorsHost(void *buffer, bool raw, unsigned long sector, unsigned long num) { + _driveUsed = true; + Bitu sectorSize = raw ? RAW_SECTOR_SIZE : COOKED_SECTOR_SIZE; uint8_t* buf = (uint8_t*)buffer; bool success = true; //Gobliiins reads 0 sectors @@ -804,13 +811,16 @@ bool CDROM_Interface_Image::ReadSectorsHost(void *buffer, bool raw, unsigned lon bool CDROM_Interface_Image::LoadUnloadMedia(bool unload) { + _driveUsed = true; (void)unload; // unused by part of the API return true; } int CDROM_Interface_Image::GetTrack(unsigned long sector) { -/* vector::iterator i = tracks.begin(); + _driveUsed = true; + + vector::iterator i = tracks.begin(); vector::iterator end = tracks.end() - 1; while(i != end) { @@ -819,21 +829,27 @@ int CDROM_Interface_Image::GetTrack(unsigned long sector) if (curr.start <= sector && sector < next.start) return curr.number; i++; } -*/ - int end = tracks.size() - 1; - int i = 0; - while(i < end) { - if((tracks[i].pregap ? tracks[i].pregap : tracks[i].start) <= sector && sector < (tracks[i + 1].pregap ? tracks[i+1].pregap : tracks[i+1].start)) { - //LOG_MSG("CDROM: GetTrack sector=%d start %d next %d number %d", sector, tracks[i].pregap, tracks[i+1].pregap, tracks[i].number); - return tracks[i].number; - } - i++; - } - return -1; + + return tracks.size()-1; + + // int end = tracks.size() - 1; + // int i = 0; + // while(i < end) { + // if((tracks[i].pregap ? tracks[i].pregap : tracks[i].start) <= sector && sector < (tracks[i + 1].pregap ? tracks[i+1].pregap : tracks[i+1].start)) { + // //LOG_MSG("CDROM: GetTrack sector=%d start %d next %d number %d", sector, tracks[i].pregap, tracks[i+1].pregap, tracks[i].number); + // return tracks[i].number; + // } + // i++; + // } + // return -1; } +extern void (*cd_read_callback)(const char* cdRomName, int32_t lba, void * dest, int sectorSize); + bool CDROM_Interface_Image::ReadSector(uint8_t *buffer, bool raw, unsigned long sector) { + _driveUsed = true; + const int track = GetTrack(sector)-1; // LOG_MSG("CDROM: Readsector sector=%d, track=%d", sector, track); if (track < 0) return false; @@ -843,12 +859,25 @@ bool CDROM_Interface_Image::ReadSector(uint8_t *buffer, bool raw, unsigned long if ((tracks[track].sectorSize == RAW_SECTOR_SIZE || tracks[track].sectorSize == 2448) && !tracks[track].mode2 && !raw) seek += 16; if (tracks[track].mode2 && !raw) seek += 24; - // LOG_MSG("CDROM: ReadSector track=%d, desired raw=%s, sector=%ld, length=%d", track, raw ? "true":"false", sector, length); - return tracks[track].file->read(buffer, seek, length); + // printf("CDROM: ReadSector track=%d, desired raw=%s, sector=%ld, length=%d", track, raw ? "true":"false", sector, length); + // bool result = tracks[track].file->read(buffer, seek, length); + size_t oldChecksum = 0; + // for (size_t i = 0; i < length; i++) oldChecksum += buffer[i]; + + // uint8_t* newBuf = (uint8_t*)malloc(length); + cd_read_callback(cdRomName.c_str(), sector, buffer, length); + size_t newChecksum = 0; + for (size_t i = 0; i < length; i++) newChecksum += buffer[i]; + + // printf("CDROM: ReadSector track=%d, desired raw=%s, sector=%ld, length=%d, old checksum=0x%lX, new checksum=0x%lX\n", track, raw ? "true":"false", sector, length, oldChecksum, newChecksum); + + return true; } void CDROM_Interface_Image::CDAudioCallBack(Bitu len) { + _driveUsed = true; + // Our member object "playbackRemaining" holds the // exact number of stream-bytes we need to play before meeting the // DOS program's desired playback duration in sectors. We simply @@ -976,6 +1005,8 @@ void CDROM_Interface_Image::CDAudioCallBack(Bitu len) bool CDROM_Interface_Image::LoadIsoFile(char* filename) { + _driveUsed = true; + tracks.clear(); // data track Track track = {0, 0, 0, 0, 0, 0, 0, false, NULL}; @@ -1297,6 +1328,9 @@ bool CDROM_Interface_Image::LoadCloneCDSheet(char *cuefile) { bool CDROM_Interface_Image::LoadCueSheet(char *cuefile) { + _driveUsed = true; + + // printf("Processing CUE Sheet\n"); // reject any file which are not a CUE sheet, GOG is so smart that they set several different extensions so that we can't assume .cue only. // Known extensions at the moment are: .cue, .ins, .dat, .inst (not sure it is an exhaustive list) { @@ -1469,6 +1503,8 @@ std::vector split_string_to_list(const std::string& str, const std::stri bool CDROM_Interface_Image::LoadChdFile(char* chdfile) { + _driveUsed = true; + /* ToDo: - check if this is a CD and not an HDD CHD @@ -1595,19 +1631,86 @@ bool CDROM_Interface_Image::LoadChdFile(char* chdfile) } } +bool CDROM_Interface_Image::LoadBizhawkCD(const char* path) +{ + _driveUsed = true; + + cdRomName = path; + printf("Processing Bizhawk CD Info for: %s\n", cdRomName.c_str()); + int cdIdx = 0; + + Track track = {0, 0, 0, 0, 0, 0, 0, false, NULL}; + tracks.clear(); + + int prestart = -1; + int shift = 0; + int currPregap = 0; + int totalPregap = 0; + track.file = NULL; + + for (size_t trackIdx = 0; trackIdx < _cdData[cdIdx].numTracks; trackIdx++) + { + if (_cdData[cdIdx].tracks[trackIdx].mode == 1) // Data + { + track.sectorSize = COOKED_SECTOR_SIZE; + track.attr = 0x40; + track.mode2 = false; + } + + if (_cdData[cdIdx].tracks[trackIdx].mode == 0) // Audio + { + track.sectorSize = RAW_SECTOR_SIZE; + track.attr = 0; + track.mode2 = false; + } + + if (_cdData[cdIdx].tracks[trackIdx].mode == 2) // Mode 2 + { + track.sectorSize = 2336; + track.attr = 0x40; + track.mode2 = true; + } + + track.number++; + track.start = _cdData[cdIdx].tracks[trackIdx].start; + track.length = _cdData[cdIdx].tracks[trackIdx].end - _cdData[cdIdx].tracks[trackIdx].start; + tracks.push_back(track); + } + + // add leadout track + track.number++; + track.attr = 0; // sync with load iso + track.start = 0; + track.length = 0; + tracks.push_back(track); + + return true; +} + + bool CDROM_Interface_Image::AddTrack(Track &curr, int &shift, int prestart, int &totalPregap, int currPregap) { + // printf("CDROM: AddTrack number=%d, attr=%d, start=%d, length=%.1fmin.\n", curr.number, curr.attr, curr.start, curr.file ? curr.file->getLength() * (1 / 10584000.0) : curr.length); + // frames between index 0(prestart) and 1(curr.start) must be skipped int skip; if (prestart >= 0) { - if ((unsigned int)prestart > curr.start) return false; + if ((unsigned int)prestart > curr.start) + { + fprintf(stderr, "Bad pre-start\n"); + return false; + } skip = curr.start - prestart; //LOG_MSG("CDROM Addtrack skip=%d prestart=%d curr.start=%d", skip, prestart, curr.start); } else skip = 0; // first track (track number must be 1) if (tracks.empty()) { - if(curr.number != 1) return false; + if(curr.number != 1) + { + fprintf(stderr, "Bad track number\n"); + return false; + } curr.pregap = 0; // first track starts from sector zero, right? curr.skip = skip * curr.sectorSize; // curr.start += currPregap; @@ -1643,6 +1746,8 @@ bool CDROM_Interface_Image::AddTrack(Track &curr, int &shift, int prestart, int totalPregap = currPregap; } + // printf("CDROM: AddTrack number=%d, attr=%d, start=%d, length=%.1fmin.\n", curr.number, curr.attr, curr.start, curr.file ? curr.file->getLength() * (1 / 10584000.0) : -1); + #ifdef DEBUG LOG_MSG("CDROM: AddTrack number=%d, attr=%d, start=%d, length=%.1fmin.", curr.number, curr.attr, curr.start, curr.file ? curr.file->getLength() * (1 / 10584000.0) : -1); @@ -1652,10 +1757,10 @@ bool CDROM_Interface_Image::AddTrack(Track &curr, int &shift, int prestart, int #endif // error checks - if (curr.number <= 1) return false; - if (prev.number + 1 != curr.number) return false; - if (curr.start < prev.start + prev.length) return false; - if (curr.length < 0) return false; + if (curr.number <= 1) { fprintf(stderr, "Bad track number (b)\n"); return false; } + if (prev.number + 1 != curr.number) { fprintf(stderr, "Bad track number (c) %d + 1 != %d\n", prev.number, curr.number); return false; } + if (curr.start < prev.start + prev.length) { fprintf(stderr, "Bad track start %d < %d + %d\n", curr.start , prev.start + prev.length); return false; } + if (curr.length < 0) { fprintf(stderr, "Bad length %d < 0\n", curr.length); return false; } return false; tracks.push_back(curr); return true; @@ -1796,10 +1901,10 @@ void CDROM_Interface_Image::ClearTracks() } void CDROM_Image_ShutDown(Section* /*sec*/) { - Sound_Quit(); + // Sound_Quit(); } void CDROM_Image_Init() { - Sound_Init(); + // Sound_Init(); AddExitFunction(AddExitFunctionFuncPair(CDROM_Image_ShutDown)); } diff --git a/src/dos/dos_files.cpp b/src/dos/dos_files.cpp index e7880148e2f..1ea49d4aeb6 100644 --- a/src/dos/dos_files.cpp +++ b/src/dos/dos_files.cpp @@ -17,2657 +17,2662 @@ */ -#include -#include -#include -#include -#if defined(WIN32) && defined(__MINGW32__) -# include -#endif - -#include "dosbox.h" -#include "bios.h" -#include "logging.h" -#include "mem.h" -#include "regs.h" -#include "dos_inc.h" -#include "drives.h" -#include "cross.h" -#include "control.h" -#include "support.h" -#include "menu.h" -#include "cdrom.h" -#include "ide.h" -#include "bios_disk.h" - -#define DOS_FILESTART 4 - -#define FCB_SUCCESS 0 -#define FCB_READ_NODATA 1 -#define FCB_READ_PARTIAL 3 -#define FCB_ERR_NODATA 1 -#define FCB_ERR_EOF 3 -#define FCB_ERR_WRITE 1 - -extern bool log_int21; -extern bool log_fileio; -extern bool enable_share_exe, enable_dbcs_tables; -extern int dos_clipboard_device_access; -extern const char *dos_clipboard_device_name; - -Bitu DOS_FILES = 127; -DOS_File ** Files = NULL; -DOS_Drive * Drives[DOS_DRIVES] = {NULL}; -bool force_sfn = false; -int sdrive = 0; - -/* This is the LFN filefind handle that is currently being used, with normal values between - * 0 and 254 for LFN calls. The value LFN_FILEFIND_INTERNAL and LFN_FILEFIND_IMG are used - * internally by LFN and image handling functions. For non-LFN calls the value is fixed to - * be LFN_FILEFIND_NONE as defined in drives.h. */ -int lfn_filefind_handle = LFN_FILEFIND_NONE; -bool isDBCSCP(), isKanji1(uint8_t chr), shiftjis_lead_byte(int c); - -bool DOS_GetFileAttrEx(char const* const name, struct stat *status, uint8_t hdrive) -{ - char fullname[DOS_PATHLENGTH]; - uint8_t drive; - bool usehdrive=/*hdrive>=0&&(always true)*/hdriveGetFileAttrEx(fullname, status); -} - -#include "dos_network2.h" - -uint8_t DOS_GetDefaultDrive(void) { -// return DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).GetDrive(); - uint8_t d = DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).GetDrive(); - if( d != dos.current_drive ) LOG(LOG_DOSMISC,LOG_ERROR)("SDA drive %d not the same as dos.current_drive %d",d,dos.current_drive); - return dos.current_drive; -} - -void DOS_SetDefaultDrive(uint8_t drive) { -// if (drive<=DOS_DRIVES && ((drive<2) || Drives[drive])) DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).SetDrive(drive); - if (drive=DOS_DRIVES || !Drives[*drive]) { - DOS_SetError(DOSERR_PATH_NOT_FOUND); - return false; - } - - if(isVolume) // Don't process any further - { - strcpy(fullname, name_int); - return true; - } - - r=0;w=0; - while (r='a') && (c<='z')) c-=32; - else if (c==' ') continue; /* should be separator */ - } - upname[w++]=(char)c; - if (((IS_PC98_ARCH && shiftjis_lead_byte(c)) || (isDBCSCP() && isKanji1(c))) && r0 && name_int[r-1]==' ') r--; - if (r>=DOS_PATHLENGTH) { DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; } - upname[w]=0; - - /* Now parse the new file name to make the final filename */ - if (upname[0]!='\\') strcpy(fullname,Drives[*drive]->curdir); - else fullname[0]=0; - uint32_t lastdir=0;uint32_t t=0; - bool lead = false; - while (fullname[t]!=0) { - if (lead) lead = false; - else if ((IS_PC98_ARCH && shiftjis_lead_byte(fullname[t])) || (isDBCSCP() && isKanji1(fullname[t]))) lead = true; - else if ((fullname[t]=='\\') && (fullname[t+1]!=0)) lastdir=t; - t++; - } - r=0;w=0; - tempdir[0]=0; - lead=false; - bool stop=false; - while (!stop) { - if (lead) lead=false; - else if ((IS_PC98_ARCH && shiftjis_lead_byte(upname[r])) || (isDBCSCP() && isKanji1(upname[r]))) lead=true; - else if ((upname[r]=='\\') || (upname[r]==0)){ - if (upname[r]==0) stop=true; - tempdir[w]=0; - if (tempdir[0]==0) { w=0;r++;continue;} - if (strcmp(tempdir,".")==0) { - tempdir[0]=0; - w=0;r++; - continue; - } - - int32_t iDown; - bool dots = true; - int32_t templen=(int32_t)strlen(tempdir); - for(iDown=0;(iDown < templen) && dots;iDown++) - if(tempdir[iDown] != '.') - dots = false; - - // only dots? - if (dots && (templen > 1)) { - int32_t cDots = templen - 1; - for(iDown=(int32_t)strlen(fullname)-1;iDown>=0;iDown--) { - if(fullname[iDown]=='\\' || iDown==0) { - if (iDown > 0 && (IS_PC98_ARCH || isDBCSCP())) { - char c = fullname[iDown+1]; - fullname[iDown+1] = 0; - char *p = strrchr_dbcs(fullname, '\\'); - fullname[iDown+1] = c; - if (p==NULL || p-fullnamefile not found - //Or path not found depending on whether - //we are still in dir check stage or file stage - if(stop) - DOS_SetError(DOSERR_FILE_NOT_FOUND); - else - DOS_SetError(DOSERR_PATH_NOT_FOUND); - return false; - } - - ext[4] = 0; - if((strlen(tempdir) - strlen(ext)) > 8) memmove(tempdir + 8, ext, 5); - } else { - tempdir[8] = 0; - } - } - - if (strlen(fullname)+strlen(tempdir)>=DOS_PATHLENGTH) { - DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; - } - - strcat(fullname,tempdir); - tempdir[0]=0; - w=0;r++; - continue; - } - tempdir[w++]=upname[r++]; - } - return true; -} - -bool checkwat=false; -bool DOS_GetSFNPath(char const * const path,char * SFNPath,bool LFN) { - char pdir[LFN_NAMELENGTH+4], *p; - uint8_t drive;char fulldir[DOS_PATHLENGTH],LFNPath[CROSS_LEN]; - char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH]; - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; - if (!DOS_MakeName(path,fulldir,&drive)) return false; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(fulldir)) { - strcpy(SFNPath,fulldir); - return true; - } -#endif - sprintf(SFNPath,"%c:\\",drive+'A'); - strcpy(LFNPath,SFNPath); - p = fulldir; - if (*p==0) return true; - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - int fbak=lfn_filefind_handle; - for (char *s = strchr_dbcs(p,'\\'); s != NULL; s = strchr_dbcs(p,'\\')) { - *s = 0; - if (check_last_split_char(SFNPath, strlen(SFNPath), '\\')) - sprintf(pdir,"\"%s%s\"",SFNPath,p); - else - sprintf(pdir,"\"%s\\%s\"",SFNPath,p); - if (!strrchr(p,'*') && !strrchr(p,'?')) { - *s = '\\'; - p = s + 1; - lfn_filefind_handle=LFN_FILEFIND_INTERNAL; - if (DOS_FindFirst(pdir,0xffff & DOS_ATTR_DIRECTORY & ~DOS_ATTR_VOLUME,false)) { - lfn_filefind_handle=fbak; - dta.GetResult(name,lname,size,hsize,date,time,attr); - strcat(SFNPath,name); - strcat(LFNPath,lname); - strcat(SFNPath,"\\"); - strcat(LFNPath,"\\"); - } - else { - lfn_filefind_handle=fbak; - dos.dta(save_dta); - return false; - } - } else { - strcat(SFNPath,p); - strcat(LFNPath,p); - strcat(SFNPath,"\\"); - strcat(LFNPath,"\\"); - *s = '\\'; - p = s + 1; - break; - } - } - if (p) { - sprintf(pdir,"\"%s%s\"",SFNPath,p); - lfn_filefind_handle=LFN_FILEFIND_INTERNAL; - if (!strrchr(p,'*')&&!strrchr(p,'?')&&DOS_FindFirst(pdir,0xffff & ~DOS_ATTR_VOLUME,false)) { - dta.GetResult(name,lname,size,hsize,date,time,attr); - strcat(SFNPath,name); - strcat(LFNPath,lname); - } else if (checkwat) { - lfn_filefind_handle=fbak; - dos.dta(save_dta); - return false; - } else { - strcat(SFNPath,p); - strcat(LFNPath,p); - } - lfn_filefind_handle=fbak; - } - dos.dta(save_dta); - if (LFN) strcpy(SFNPath,LFNPath); - return true; -} - -bool DOS_GetCurrentDir(uint8_t drive,char * const buffer, bool LFN) { - if (drive==0) drive=DOS_GetDefaultDrive(); - else drive--; - - if ((drive>=DOS_DRIVES) || (!Drives[drive])) { - DOS_SetError(DOSERR_INVALID_DRIVE); - return false; - } - - if (LFN && uselfn) { - char cdir[DOS_PATHLENGTH+8],ldir[DOS_PATHLENGTH]; - - if (strchr(Drives[drive]->curdir,' ')) - sprintf(cdir,"\"%c:\\%s\"",drive+'A',Drives[drive]->curdir); - else - sprintf(cdir,"%c:\\%s",drive+'A',Drives[drive]->curdir); - - if (!DOS_GetSFNPath(cdir,ldir,true)) - return false; - - strcpy(buffer,ldir+3); - if (DOS_GetSFNPath(cdir,ldir,false)) - strcpy(Drives[drive]->curdir,ldir+3); - } else { - strcpy(buffer,Drives[drive]->curdir); - } - - return true; -} - -bool DOS_ChangeDir(char const * const dir) { - uint8_t drive;char fulldir[DOS_PATHLENGTH]; - const char * testdir=dir; - if (strlen(testdir) && testdir[1]==':') testdir+=2; - size_t len=strlen(testdir); - if (!len) { - DOS_SetError(DOSERR_PATH_NOT_FOUND); - return false; - } - if (!DOS_MakeName(dir,fulldir,&drive)) return false; - if (strlen(fulldir) && check_last_split_char(testdir, len, '\\')) { - DOS_SetError(DOSERR_PATH_NOT_FOUND); - return false; - } - - if (Drives[drive]->TestDir(fulldir)) { - strcpy(Drives[drive]->curdir,fulldir); - return true; - } else { - DOS_SetError(DOSERR_PATH_NOT_FOUND); - } - return false; -} - -bool DOS_MakeDir(char const * const dir) { - uint8_t drive;char fulldir[DOS_PATHLENGTH]; - size_t len = strlen(dir); - if(!len || check_last_split_char(dir, len, '\\')) { - DOS_SetError(DOSERR_PATH_NOT_FOUND); - return false; - } - if (!DOS_MakeName(dir,fulldir,&drive)) return false; - while (strlen(fulldir)&&(*(fulldir+strlen(fulldir)-1)=='.'||*(fulldir+strlen(fulldir)-1)==' ')) *(fulldir+strlen(fulldir)-1)=0; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(dir)) return Network_MakeDir(dir); -#endif - if(Drives[drive]->MakeDir(fulldir)) return true; - - /* Determine reason for failing */ - if(Drives[drive]->TestDir(fulldir)) - DOS_SetError(DOSERR_ACCESS_DENIED); - else - DOS_SetError(DOSERR_PATH_NOT_FOUND); - return false; -} - -bool DOS_RemoveDir(char const * const dir) { -/* We need to do the test before the removal as can not rely on - * the host to forbid removal of the current directory. - * We never change directory. Everything happens in the drives. - */ - uint8_t drive;char fulldir[DOS_PATHLENGTH]; - if (!DOS_MakeName(dir,fulldir,&drive)) return false; - /* Check if exists */ -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(dir)) return Network_RemoveDir(dir); -#endif - if(!Drives[drive]->TestDir(fulldir)) { - DOS_SetError(DOSERR_PATH_NOT_FOUND); - return false; - } - /* See if it's current directory */ - char currdir[DOS_PATHLENGTH]= { 0 }, lcurrdir[DOS_PATHLENGTH]= { 0 }; - DOS_GetCurrentDir(drive + 1 ,currdir, false); - DOS_GetCurrentDir(drive + 1 ,lcurrdir, true); - if(strcasecmp(currdir,fulldir) == 0 || (uselfn && strcasecmp(lcurrdir,fulldir) == 0)) { - DOS_SetError(DOSERR_REMOVE_CURRENT_DIRECTORY); - return false; - } - - if(Drives[drive]->RemoveDir(fulldir)) return true; - - /* Failed. We know it exists and it's not the current dir */ - /* Assume non empty */ - DOS_SetError(DOSERR_ACCESS_DENIED); - return false; -} - -static bool PathExists(char const * const name) { - const char* leading = strrchr_dbcs((char *)name,'\\'); - if(!leading) return true; - char temp[CROSS_LEN]; - strcpy(temp,name); - char * lead = strrchr_dbcs(temp,'\\'); - if (lead == temp) return true; - *lead = 0; - uint8_t drive;char fulldir[DOS_PATHLENGTH]; - if (!DOS_MakeName(temp,fulldir,&drive)) return false; - if(!Drives[drive]->TestDir(fulldir)) return false; - return true; -} - -bool DOS_Rename(char const * const oldname,char const * const newname) { - uint8_t driveold;char fullold[DOS_PATHLENGTH]; - uint8_t drivenew;char fullnew[DOS_PATHLENGTH]; - if (!DOS_MakeName(oldname,fullold,&driveold)) return false; - if (!DOS_MakeName(newname,fullnew,&drivenew)) return false; - while (strlen(fullnew)&&(*(fullnew+strlen(fullnew)-1)=='.'||*(fullnew+strlen(fullnew)-1)==' ')) *(fullnew+strlen(fullnew)-1)=0; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(oldname)) return Network_Rename(oldname,newname); -#endif - - /* No tricks with devices */ - bool clip=false; - if ( (DOS_FindDevice(oldname) != DOS_DEVICES) || - (DOS_FindDevice(newname) != DOS_DEVICES) ) { - if (!control->SecureMode()&&(dos_clipboard_device_access==3||dos_clipboard_device_access==4)) { - if (DOS_FindDevice(oldname) == DOS_DEVICES) { - const char* find_last; - find_last=strrchr_dbcs(fullnew,'\\'); - if (find_last==NULL) find_last=fullnew; - else find_last++; - if (!strcasecmp(find_last, *dos_clipboard_device_name?dos_clipboard_device_name:"CLIP$")) - clip=true; - } - } - if (!clip) { - DOS_SetError(DOSERR_FILE_NOT_FOUND); - return false; - } - } - /* Must be on the same drive */ - if(driveold != drivenew) { - DOS_SetError(DOSERR_NOT_SAME_DEVICE); - return false; - } - uint16_t attr; - /* Source must exist */ - if (!Drives[driveold]->GetFileAttr( fullold, &attr ) ) { - if (!PathExists(oldname)) DOS_SetError(DOSERR_PATH_NOT_FOUND); - else DOS_SetError(DOSERR_FILE_NOT_FOUND); - return false; - } - /*Test if target exists => no access */ - if(Drives[drivenew]->GetFileAttr(fullnew,&attr)&&!(uselfn&&!force_sfn&&strcmp(fullold, fullnew)&&!strcasecmp(fullold, fullnew))) { - DOS_SetError(DOSERR_ACCESS_DENIED); - return false; - } - -#if defined (WIN32) - if (clip) { - uint16_t sourceHandle, targetHandle, toread = 0x8000; - static uint8_t buffer[0x8000]; - bool failed = false; - if (DOS_OpenFile(oldname,OPEN_READ,&sourceHandle) && DOS_OpenFile(newname,OPEN_WRITE,&targetHandle)) { - do { - if (!DOS_ReadFile(sourceHandle,buffer,&toread) || !DOS_WriteFile(targetHandle,buffer,&toread)) failed=true; - } while (toread == 0x8000); - if (!DOS_CloseFile(sourceHandle)||!DOS_CloseFile(targetHandle)) failed=true; - } else failed=true; - if (!failed&&Drives[drivenew]->FileUnlink(fullold)) return true; - } else -#endif - - if (Drives[drivenew]->Rename(fullold,fullnew)) return true; - /* Rename failed despite checks => no access */ - DOS_SetError(DOSERR_ACCESS_DENIED); - return false; -} - -bool forcelfn = false; -bool DOS_FindFirst(const char * search,uint16_t attr,bool fcb_findfirst) { - LOG(LOG_FILES,LOG_NORMAL)("file search attributes %X name %s",attr,search); - DOS_DTA dta(dos.dta()); - uint8_t drive;char fullsearch[DOS_PATHLENGTH]; - char dir[DOS_PATHLENGTH];char pattern[DOS_PATHLENGTH]; - size_t len = strlen(search); - if(len && check_last_split_char(search, len, '\\') && !( (len > 2) && (search[len - 2] == ':') && (attr == DOS_ATTR_VOLUME) )) { - //Dark Forces installer, but c:\ is alright for volume labels(exclusively set) - DOS_SetError(DOSERR_NO_MORE_FILES); - return false; - } - if (!DOS_MakeName(search,fullsearch,&drive,attr == DOS_ATTR_VOLUME)) return false; - //Check for devices. FindDevice checks for leading subdir as well - bool device = false; - //if (attr & DOS_ATTR_DEVICE) /* FIX_ME: This line deleted to fix launching Blocek editor (Issue #4385), revert this if this induces other errors */ - device = DOS_FindDevice(search) != DOS_DEVICES; - - /* Split the search in dir and pattern */ - forcelfn = false; - char *find_last = NULL; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - bool net = Network_IsNetworkResource(search); - if (net) forcelfn = true; - char *p = net ? strchr_dbcs(fullsearch+(fullsearch[0]=='"'?3:2), '\\') : NULL; - find_last = strrchr_dbcs(p != NULL ? p + 1 : fullsearch, '\\'); -#else - find_last = strrchr_dbcs(fullsearch,'\\'); -#endif - if (!find_last) { /*No dir */ - strcpy(pattern,fullsearch); - dir[0]=0; - } else { - *find_last=0; - strcpy(pattern,find_last+1); - strcpy(dir,fullsearch); - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (!strlen(dir)&&Network_IsNetworkResource(pattern)) {forcelfn=false;return false;} -#endif - - // Silence CHKDSK "Invalid sub-directory entry" - if (fcb_findfirst && !strcmp(search+1, ":????????.???") && attr==30) { - char psp_name[9]; - DOS_MCB psp_mcb(dos.psp()-1); - psp_mcb.GetFileName(psp_name); - if (!strcmp(psp_name, "CHKDSK")) attr&=~DOS_ATTR_DIRECTORY; - } - - sdrive=drive; - dta.SetupSearch(drive,(uint8_t)attr,pattern); - forcelfn = false; - - if(device) { - find_last = strrchr(pattern,'.'); - if(find_last) *find_last = 0; - //TODO use current date and time - dta.SetResult(pattern,pattern,0,0,0,0,DOS_ATTR_DEVICE); - LOG(LOG_DOSMISC,LOG_WARN)("finding device %s",pattern); - return true; - } - -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (net) return Network_FindFirst(dir,dta); -#endif - if (Drives[drive]->FindFirst(dir,dta,fcb_findfirst)) return true; - return false; -} - -bool DOS_FindNext(void) { - DOS_DTA dta(dos.dta()); - uint8_t i = dta.GetSearchDrive(); - if(uselfn && (i >= DOS_DRIVES || !Drives[i])) i=sdrive; - if(i >= DOS_DRIVES || !Drives[i]) { - /* Corrupt search. */ - LOG(LOG_FILES,LOG_ERROR)("Corrupt search!!!!"); - DOS_SetError(DOSERR_NO_MORE_FILES); - return false; - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - unsigned int pos = lfn_filefind_handle>=LFN_FILEFIND_MAX?dta.GetDirID():lfn_id[lfn_filefind_handle]; - if (pos==65534) return Network_FindNext(dta); -#endif - if (Drives[i]->FindNext(dta)) return true; - return false; -} - - -bool DOS_ReadFile(uint16_t entry,uint8_t * data,uint16_t * amount,bool fcb) { - uint32_t handle = fcb?entry:RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsActiveResource(entry)) - return Network_ReadFile(entry,data,amount); -#endif - if (!Files[handle] || !Files[handle]->IsOpen()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - - if (log_fileio) { - LOG(LOG_FILES, LOG_DEBUG)("Reading %d bytes from %s ", *amount, Files[handle]->name); - } -/* - if ((Files[handle]->flags & 0x0f) == OPEN_WRITE)) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -*/ - uint16_t toread=*amount; - bool ret=Files[handle]->Read(data,&toread); - *amount=toread; - return ret; -} - -bool DOS_WriteFile(uint16_t entry,const uint8_t * data,uint16_t * amount,bool fcb) { - uint32_t handle = fcb?entry:RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsActiveResource(entry)) - return Network_WriteFile(entry,data,amount); -#endif - if (!Files[handle] || !Files[handle]->IsOpen()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - - if (log_fileio) { - LOG(LOG_FILES, LOG_DEBUG)("Writing %d bytes to %s", *amount, Files[handle]->name); - } -/* - if ((Files[handle]->flags & 0x0f) == OPEN_READ)) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -*/ - uint16_t towrite=*amount; - bool ret=Files[handle]->Write(data,&towrite); - *amount=towrite; - return ret; -} - -bool DOS_SeekFile(uint16_t entry,uint32_t * pos,uint32_t type,bool fcb) { - uint32_t handle = fcb?entry:RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsActiveResource(entry)) - return Network_SeekFile(entry,pos,type); -#endif - if (!Files[handle] || !Files[handle]->IsOpen()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - - if (log_fileio) { - LOG(LOG_FILES, LOG_DEBUG)("Seeking to %d bytes from position type (%d) in %s ", *pos, type, Files[handle]->name); - } - - return Files[handle]->Seek(pos,type); -} - -/* ert, 20100711: Locking extensions */ -bool DOS_LockFile(uint16_t entry,uint8_t mode,uint32_t pos,uint32_t size) { - uint32_t handle=RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - if (!Files[handle] || !Files[handle]->IsOpen()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - return Files[handle]->LockFile(mode,pos,size); -} - -bool DOS_CloseFile(uint16_t entry, bool fcb, uint8_t * refcnt) { - uint32_t handle = fcb?entry:RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsActiveResource(entry)) - return Network_CloseFile(entry); -#endif - if (!Files[handle]) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - if (Files[handle]->IsOpen()) { - if (log_fileio) { - LOG(LOG_FILES, LOG_NORMAL)("Closing file %s", Files[handle]->name); - } - Files[handle]->Close(); - } - - DOS_PSP psp(dos.psp()); - if (!fcb) psp.SetFileHandle(entry,0xff); - - Bits refs=Files[handle]->RemoveRef(); - if (refs<=0) { - delete Files[handle]; - Files[handle]=nullptr; - } - if (refcnt!=NULL) *refcnt=static_cast(refs+1); - return true; -} - -bool DOS_FlushFile(uint16_t entry) { - uint32_t handle=RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsActiveResource(entry)) - return Network_FlushFile(entry); -#endif - if (!Files[handle] || !Files[handle]->IsOpen()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - - LOG(LOG_DOSMISC,LOG_DEBUG)("FFlush used."); - - Files[handle]->Flush(); - return true; -} - - -bool DOS_CreateFile(char const * name,uint16_t attributes,uint16_t * entry,bool fcb) { - // Creation of a device is the same as opening it - // Tc201 installer - if (DOS_FindDevice(name) != DOS_DEVICES) - return DOS_OpenFile(name, OPEN_READ, entry, fcb); - - LOG(LOG_FILES,LOG_NORMAL)("file create attributes %X file %s",attributes,name); - char fullname[DOS_PATHLENGTH];uint8_t drive; - DOS_PSP psp(dos.psp()); - if (!DOS_MakeName(name,fullname,&drive)) return false; - while (strlen(fullname)&&(*(fullname+strlen(fullname)-1)=='.'||*(fullname+strlen(fullname)-1)==' ')) *(fullname+strlen(fullname)-1)=0; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsNetworkResource(name)) - return Network_CreateFile(name,attributes,entry); -#endif - - /* Check for a free file handle */ - uint8_t handle=(uint8_t)DOS_FILES;uint8_t i; - for (i=0;iFileCreate(&Files[handle],fullname,attributes); - if (foundit) { - if (Files[handle]) { - Files[handle]->SetDrive(drive); - Files[handle]->AddRef(); - Files[handle]->drive = drive; - } - if (!fcb) psp.SetFileHandle(*entry,handle); - if (Files[handle]) Drives[drive]->EmptyCache(); - return true; - } else { - if(dos.errorcode==DOSERR_ACCESS_DENIED||dos.errorcode==DOSERR_WRITE_PROTECTED) return false; - if(!PathExists(name)) DOS_SetError(DOSERR_PATH_NOT_FOUND); - else DOS_SetError(DOSERR_FILE_NOT_FOUND); - return false; - } -} - -bool DOS_OpenFile(char const * name,uint8_t flags,uint16_t * entry,bool fcb) { - /* First check for devices */ - if (flags>2) LOG(LOG_FILES,LOG_NORMAL)("Special file open command %X file %s",flags,name); // FIXME: Why? Is there something about special opens DOSBox doesn't handle properly? - else LOG(LOG_FILES,LOG_NORMAL)("file open command %X file %s",flags,name); - - DOS_PSP psp(dos.psp()); - uint16_t attr = 0; - uint8_t devnum = DOS_FindDevice(name); - bool device = (devnum != DOS_DEVICES); - if(!device && DOS_GetFileAttr(name,&attr)) { - //DON'T ALLOW directories to be opened. (skip test if file is device). - if((attr & DOS_ATTR_DIRECTORY) || (attr & DOS_ATTR_VOLUME)){ - DOS_SetError(DOSERR_ACCESS_DENIED); - return false; - } - } - - char fullname[DOS_PATHLENGTH];uint8_t drive;uint8_t i; - /* First check if the name is correct */ - if (!DOS_MakeName(name,fullname,&drive)) return false; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsNetworkResource(name)) - return Network_OpenFile(name,flags,entry); -#endif - uint8_t handle=255; - /* Check for a free file handle */ - for (i=0;iGetInformation() & EXT_DEVICE_BIT) - Files[handle] = new DOS_ExtDevice(*(DOS_ExtDevice*)Devices[devnum]); - else - Files[handle]=new DOS_Device(*Devices[devnum]); - } else { - uint16_t olderror=dos.errorcode; - dos.errorcode=0; - exists=Drives[drive]->FileOpen(&Files[handle],fullname,flags) || Drives[drive]->FileOpen(&Files[handle],upcase(fullname),flags); - if (exists) Files[handle]->SetDrive(drive); - else if (dos.errorcode==DOSERR_ACCESS_CODE_INVALID) return false; - dos.errorcode=olderror; - } - if (exists || device ) { - Files[handle]->AddRef(); - psp.SetFileHandle(*entry,handle); - Files[handle]->drive = drive; - return true; - } else { - //Test if file exists, but opened in read-write mode (and writeprotected) - if((((flags&3) != OPEN_READ) || (enable_share_exe && !strncmp(Drives[drive]->GetInfo(),"local directory ",16))) && Drives[drive]->FileExists(fullname)) - DOS_SetError(DOSERR_ACCESS_DENIED); - else { - if(!PathExists(name)) DOS_SetError(DOSERR_PATH_NOT_FOUND); - else DOS_SetError(DOSERR_FILE_NOT_FOUND); - } - return false; - } -} - -bool DOS_OpenFileExtended(char const * name, uint16_t flags, uint16_t createAttr, uint16_t action, uint16_t *entry, uint16_t* status) { -// FIXME: Not yet supported : Bit 13 of flags (int 0x24 on critical error) - uint16_t result = 0; - if (action==0) { - // always fail setting - DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); - return false; - } else { - if (((action & 0x0f)>2) || ((action & 0xf0)>0x10)) { - // invalid action parameter - DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); - return false; - } - } - if (DOS_OpenFile(name, (uint8_t)(flags&0xff), entry)) { - // File already exists - switch (action & 0x0f) { - case 0x00: // failed - DOS_SetError(DOSERR_FILE_ALREADY_EXISTS); - return false; - case 0x01: // file open (already done) - result = 1; - break; - case 0x02: // replace - DOS_CloseFile(*entry); - if (!DOS_CreateFile(name, createAttr, entry)) return false; - result = 3; - break; - default: - DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); - E_Exit("DOS: OpenFileExtended: Unknown action."); - break; - } - } else { - // File doesn't exist - if ((action & 0xf0)==0) { - // uses error code from failed open - return false; - } - // Create File - if (!DOS_CreateFile(name, createAttr, entry)) { - // uses error code from failed create - return false; - } - result = 2; - } - // success - *status = result; - return true; -} - -bool DOS_UnlinkFile(char const * const name) { - char fullname[DOS_PATHLENGTH];uint8_t drive; - // An existing device returns an access denied error - if (log_fileio) { - LOG(LOG_FILES, LOG_NORMAL)("Deleting file %s", name); - } - if (DOS_FindDevice(name) != DOS_DEVICES) { - DOS_SetError(DOSERR_ACCESS_DENIED); - return false; - } - if (!DOS_MakeName(name,fullname,&drive)) return false; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(name)) return Network_UnlinkFile(name); -#endif - if(Drives[drive]->FileUnlink(fullname)){ - return true; - } else if(uselfn&&!force_sfn&&(strchr(fullname, '*')||strchr(fullname, '?'))) { // Wildcard delete as used by MS-DOS 7+ "DEL *.*" in LFN mode - char dir[DOS_PATHLENGTH], temp[DOS_PATHLENGTH], fname[DOS_PATHLENGTH], spath[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH]; - if (!DOS_Canonicalize(name,fullname)||!strlen(fullname)) { - DOS_SetError(DOSERR_PATH_NOT_FOUND); - return false; - } - if (!strchr(name,'\"')||!DOS_GetSFNPath(("\""+std::string(fullname)+"\"").c_str(), fname, false)) - strcpy(fname, fullname); - char * find_last=strrchr_dbcs(fname,'\\'); - if (!find_last) { - dir[0]=0; - strcpy(pattern, fname); - } else { - *find_last=0; - strcpy(dir,fname); - strcpy(pattern, find_last+1); - } - int k=0; - for (int i=0;i<(int)strlen(pattern);i++) - if (pattern[i]!='\"') - pattern[k++]=pattern[i]; - pattern[k]=0; - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - std::vector cdirs; - cdirs.clear(); - strcpy(spath, dir); - if (!DOS_GetSFNPath(dir, spath, false)) strcpy(spath, dir); - if (!strlen(spath)||spath[strlen(spath)-1]!='\\') strcat(spath, "\\"); - std::string pfull=std::string(spath)+std::string(pattern); - int fbak=lfn_filefind_handle; - lfn_filefind_handle=LFN_FILEFIND_INTERNAL; - bool ret=DOS_FindFirst(((pfull.length()&&pfull[0]=='"'?"":"\"")+pfull+(pfull.length()&&pfull[pfull.length()-1]=='"'?"":"\"")).c_str(),0xffu & ~DOS_ATTR_VOLUME & ~DOS_ATTR_DIRECTORY); - if (ret) do { - char find_name[DOS_NAMELENGTH_ASCII],lfind_name[LFN_NAMELENGTH]; - uint16_t find_date,find_time;uint32_t find_size,find_hsize;uint8_t find_attr; - dta.GetResult(find_name,lfind_name,find_size,find_hsize,find_date,find_time,find_attr); - if (!(find_attr & DOS_ATTR_DIRECTORY)&&strlen(find_name)&&!strchr(find_name, '*')&&!strchr(find_name, '?')) { - strcpy(temp, dir); - if (strlen(temp)&&temp[strlen(temp)-1]!='\\') strcat(temp, "\\"); - strcat(temp, find_name); - cdirs.emplace_back(std::string(temp)); - } - } while ((ret=DOS_FindNext())==true); - lfn_filefind_handle=fbak; - bool removed=false; - while (!cdirs.empty()) { - if (DOS_UnlinkFile(cdirs.begin()->c_str())) - removed=true; - cdirs.erase(cdirs.begin()); - } - dos.dta(save_dta); - if (removed) - return true; - else { - if (dos.errorcode!=DOSERR_ACCESS_DENIED&&dos.errorcode!=DOSERR_WRITE_PROTECTED) DOS_SetError(DOSERR_FILE_NOT_FOUND); - return false; - } - } else { - if (dos.errorcode!=DOSERR_ACCESS_DENIED&&dos.errorcode!=DOSERR_WRITE_PROTECTED) DOS_SetError(DOSERR_FILE_NOT_FOUND); - return false; - } -} - -bool DOS_GetFileAttr(char const * const name,uint16_t * attr) { - char fullname[DOS_PATHLENGTH];uint8_t drive; - if (!DOS_MakeName(name,fullname,&drive)) return false; -#if defined (WIN32) - if (!control->SecureMode()&&dos_clipboard_device_access) { - const char* find_last; - find_last=strrchr_dbcs(fullname,'\\'); - if (find_last==NULL) find_last=fullname; - else find_last++; - if (!strcasecmp(find_last, *dos_clipboard_device_name?dos_clipboard_device_name:"CLIP$")) - return true; - } -#if !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(name)) { - if (Network_GetFileAttr(name, attr)) { - return true; - } else { - DOS_SetError(DOSERR_FILE_NOT_FOUND); - return false; - } - } -#endif -#endif - - if (Drives[drive]->GetFileAttr(fullname,attr)) { - return true; - } else { - DOS_SetError(DOSERR_FILE_NOT_FOUND); - return false; - } -} - -unsigned long DOS_GetCompressedFileSize(char const* const name) -{ - char fullname[DOS_PATHLENGTH]; - uint8_t drive; - if (!DOS_MakeName(name, fullname, &drive)) - return false; - return Drives[drive]->GetCompressedSize(fullname); -} - -#if defined (WIN32) -HANDLE DOS_CreateOpenFile(char const* const name) -{ - char fullname[DOS_PATHLENGTH]; - uint8_t drive; - if (!DOS_MakeName(name, fullname, &drive)) - return INVALID_HANDLE_VALUE; - return Drives[drive]->CreateOpenFile(fullname); -} -#endif - -bool DOS_SetFileAttr(char const * const name,uint16_t attr) -// returns false when using on cdrom (stonekeep) -{ - char fullname[DOS_PATHLENGTH];uint8_t drive; - if (!DOS_MakeName(name,fullname,&drive)) return false; - if (strncmp(Drives[drive]->GetInfo(),"CDRom ",6)==0 || strncmp(Drives[drive]->GetInfo(),"isoDrive ",9)==0) { - DOS_SetError(DOSERR_ACCESS_DENIED); - return false; - } - - /* This function must prevent changing a file into a directory, volume label into a file, etc. - * Also Windows 95 setup likes to create WINBOOT.INI as a file and then chattr it into a directory for some stupid reason. */ - uint16_t old_attr; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if ((Network_IsNetworkResource(name)&&!Network_GetFileAttr(name,&old_attr))||(!Network_IsNetworkResource(name)&&!Drives[drive]->GetFileAttr(fullname,&old_attr))) -#else - if (!Drives[drive]->GetFileAttr(fullname,&old_attr)) -#endif - { - DOS_SetError(DOSERR_FILE_NOT_FOUND); - return false; - } - - if ((old_attr ^ attr) & DOS_ATTR_VOLUME) { /* change in volume label attribute */ - LOG(LOG_DOSMISC,LOG_WARN)("Attempted to change volume label attribute of '%s' with SetFileAttr",name); - return false; - } - - if ((old_attr ^ attr) & DOS_ATTR_DIRECTORY) /* change in directory attribute (ex: Windows 95 SETUP.EXE vs WINBOOT.INI) */ - LOG(LOG_DOSMISC,LOG_WARN)("Attempted to change directory attribute of '%s' with SetFileAttr",name); - - /* define what cannot be changed */ - const uint16_t attr_mask = (DOS_ATTR_VOLUME|DOS_ATTR_DIRECTORY); - - attr = (attr & ~attr_mask) | (old_attr & attr_mask); - -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(name)) return Network_SetFileAttr(name,attr); -#endif - return Drives[drive]->SetFileAttr(fullname,attr); -} - -bool DOS_Canonicalize(char const * const name,char * const big) { -//TODO Add Better support for devices and shit but will it be needed i doubt it :) - uint8_t drive; - char fullname[DOS_PATHLENGTH]; - if (!DOS_MakeName(name,fullname,&drive)) return false; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(name)) { - strcpy(&big[0], name); - return true; - } -#endif - big[0]=drive+'A'; - big[1]=':'; - big[2]='\\'; - strcpy(&big[3],fullname); - return true; -} - -#ifdef _MSC_VER -# define MIN(a,b) ((a) < (b) ? (a) : (b)) -# define MAX(a,b) ((a) > (b) ? (a) : (b)) -#else -# define MIN(a,b) std::min(a,b) -# define MAX(a,b) std::max(a,b) -#endif - -/* Common routine to take larger allocation information (such as FAT32) and convert it to values - * that are suitable for use with older DOS programs that pre-date FAT32 and partitions 2GB or larger. - * This is what Windows 95 OSR2 and higher do with FAT32 partitions anyway, as documented by Microsoft. */ -bool DOS_CommonFAT32FAT16DiskSpaceConv( - uint16_t * bytes,uint8_t * sectors,uint16_t * clusters,uint16_t * free, - const uint32_t bytes32,const uint32_t sectors32,const uint32_t clusters32,const uint32_t free32) { - uint32_t cdiv = 1; - - if (sectors32 > 128 || bytes32 > 0x8000) - return false; - - /* This function is for the old API. It is necessary to adjust the values so that they never overflow - * 16-bit unsigned integers and never multiply out to a number greater than just under 2GB. Because - * old DOS programs use 32-bit signed integers for disk total/free and FAT12/FAT16 filesystem limitations. */ - /* NTS: Make sure (bytes per sector * sectors per cluster) is less than 0x10000, or else FORMAT.COM will - * crash with divide by zero or produce incorrect results when run with "FORMAT /S" */ - while ((clusters32 > 0xFFFFu || free32 > 0xFFFFu) && (sectors32 * cdiv) <= 64u && (bytes32 * sectors32 * cdiv) < 0x8000/*Needed for FORMAT.COM*/) - cdiv *= 2u; - - /* The old API must never report more than just under 2GB for total and free */ - const uint32_t clust2gb = (uint32_t)0x7FFF8000ul / (uint32_t)bytes32 / (sectors32 * cdiv); - - *bytes = bytes32; - *sectors = sectors32 * cdiv; - *clusters = (uint16_t)MIN(MIN(clusters32 / cdiv,clust2gb),0xFFFFu); - *free = (uint16_t)MIN(MIN(free32 / cdiv,clust2gb),0xFFFFu); - return true; -} - -bool DOS_GetFreeDiskSpace(uint8_t drive,uint16_t * bytes,uint8_t * sectors,uint16_t * clusters,uint16_t * free) { - if (drive==0) drive=DOS_GetDefaultDrive(); - else drive--; - if ((drive>=DOS_DRIVES) || (!Drives[drive])) { - DOS_SetError(DOSERR_INVALID_DRIVE); - return false; - } - - { - uint32_t bytes32,sectors32,clusters32,free32; - if ((dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10)) && - Drives[drive]->AllocationInfo32(&bytes32,§ors32,&clusters32,&free32) && - DOS_CommonFAT32FAT16DiskSpaceConv(bytes,sectors,clusters,free,bytes32,sectors32,clusters32,free32)) - return true; - } - - if (Drives[drive]->AllocationInfo(bytes,sectors,clusters,free)) - return true; - - return false; -} - -bool DOS_GetFreeDiskSpace32(uint8_t drive,uint32_t * bytes,uint32_t * sectors,uint32_t * clusters,uint32_t * free) { - if (drive==0) drive=DOS_GetDefaultDrive(); - else drive--; - if ((drive>=DOS_DRIVES) || (!Drives[drive])) { - DOS_SetError(DOSERR_INVALID_DRIVE); - return false; - } - - if ((dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10)) && Drives[drive]->AllocationInfo32(bytes,sectors,clusters,free)) - return true; - - { - uint8_t sectors8; - uint16_t bytes16,clusters16,free16; - if (Drives[drive]->AllocationInfo(&bytes16,§ors8,&clusters16,&free16)) { - *free = free16; - *bytes = bytes16; - *sectors = sectors8; - *clusters = clusters16; - return true; - } - } - - return false; -} - -bool DOS_DuplicateEntry(uint16_t entry,uint16_t * newentry) { - // Don't duplicate console handles -/* if (entry<=STDPRN) { - *newentry = entry; - return true; - }; -*/ - uint8_t handle=RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - if (!Files[handle] || !Files[handle]->IsOpen()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - DOS_PSP psp(dos.psp()); - *newentry = psp.FindFreeFileEntry(); - if (*newentry==0xff) { - DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); - return false; - } - Files[handle]->AddRef(); - psp.SetFileHandle(*newentry,handle); - return true; -} - -bool DOS_ForceDuplicateEntry(uint16_t entry,uint16_t newentry) { - if(entry == newentry) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - uint8_t orig = RealHandle(entry); - if (orig >= DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - if (!Files[orig] || !Files[orig]->IsOpen()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - uint8_t newone = RealHandle(newentry); - if (newone < DOS_FILES && Files[newone]) { - DOS_CloseFile(newentry); - } - DOS_PSP psp(dos.psp()); - Files[orig]->AddRef(); - psp.SetFileHandle(newentry,orig); - return true; -} - -void initRand() { -#ifdef WIN32 - srand(GetTickCount()); -#else - struct timespec ts; - unsigned theTick = 0U; - clock_gettime( CLOCK_REALTIME, &ts ); - theTick = ts.tv_nsec / 1000000; - theTick += ts.tv_sec * 1000; - srand(theTick); -#endif -} - -bool DOS_CreateTempFile(char * const name,uint16_t * entry) { - size_t namelen=strlen(name); - char * tempname=name+namelen; - if (namelen==0) { - // temp file created in root directory - tempname[0]='\\'; - tempname++; - } else { - if (!check_last_split_char(name, namelen, '\\') && (name[namelen-1]!='/')) { - tempname[0]='\\'; - tempname++; - } - } - uint16_t olderror=dos.errorcode; - dos.errorcode=0; - /* add random crap to the end of the name and try to open */ - initRand(); - bool cont; - do { - cont=false; - uint32_t i; - for (i=0;i<8;i++) { - tempname[i]=(rand()%26)+'A'; - } - tempname[8]=0; - //if (DOS_FileExists(name)) {cont=true;continue;} // FIXME: Check name uniqueness - } while (cont || DOS_FileExists(name)); - DOS_CreateFile(name,0,entry); - if (dos.errorcode) return false; - dos.errorcode=olderror; - return true; -} - -char DOS_ToUpper(char c) { - unsigned char uc = *reinterpret_cast(&c); - if (uc > 0x60 && uc < 0x7B) uc -= 0x20; - else if (uc > 0x7F && uc < 0xA5) { - const unsigned char t[0x25] = { - 0x00, 0x9a, 0x45, 0x41, 0x8E, 0x41, 0x8F, 0x80, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x00, 0x00, - 0x00, 0x92, 0x00, 0x4F, 0x99, 0x4F, 0x55, 0x55, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x41, 0x49, 0x4F, 0x55, 0xA5}; - if (t[uc - 0x80]) uc = t[uc-0x80]; - } - char sc = *reinterpret_cast(&uc); - return sc; -} - -#define FCB_SEP ":;,=+" -#define ILLEGAL ":.;,=+ \t/\"[]<>|" - -static bool isvalid(const char in){ - const char ill[]=ILLEGAL; - return (uint8_t(in)>0x1F) && (!strchr(ill,in)); -} - -#define PARSE_SEP_STOP 0x01 -#define PARSE_DFLT_DRIVE 0x02 -#define PARSE_BLNK_FNAME 0x04 -#define PARSE_BLNK_FEXT 0x08 - -#define PARSE_RET_NOWILD 0 -#define PARSE_RET_WILD 1 -#define PARSE_RET_BADDRIVE 0xff - -uint8_t FCB_Parsename(uint16_t seg,uint16_t offset,uint8_t parser ,char *string, uint8_t *change) { - const char* string_begin = string; - uint8_t ret=0; - if (!(parser & PARSE_DFLT_DRIVE)) { - // default drive forced, this intentionally invalidates an extended FCB - mem_writeb(PhysMake(seg,offset),0); - } - DOS_FCB fcb(seg,offset,false); // always a non-extended FCB - bool hasdrive,hasname,hasext,finished; - hasdrive=hasname=hasext=finished=false; - Bitu index=0; - uint8_t fill=' '; -/* First get the old data from the fcb */ -#ifdef _MSC_VER -#pragma pack (1) -#endif - union { - struct { - char drive[2]; - char name[9]; - char ext[4]; - } GCC_ATTRIBUTE (packed) part; - char full[DOS_FCBNAME]; - } fcb_name; -#ifdef _MSC_VER -#pragma pack() -#endif - /* Get the old information from the previous fcb */ - fcb.GetName(fcb_name.full); - fcb_name.part.drive[0]-='A'-1;fcb_name.part.drive[1]=0; - fcb_name.part.name[8]=0;fcb_name.part.ext[3]=0; - /* strip leading spaces */ - while((*string==' ')||(*string=='\t')) string++; - - /* Strip of the leading separator */ - if((parser & PARSE_SEP_STOP) && *string) { - char sep[] = FCB_SEP;char a[2]; - a[0] = *string;a[1] = '\0'; - if (strcspn(a,sep) == 0) string++; - } - - /* Skip following spaces as well */ - while((*string==' ')||(*string=='\t')) string++; - - /* Check for a drive */ - if (string[1]==':') { - unsigned char d = *reinterpret_cast(&string[0]); - if (!isvalid(ascii_toupper(d))) {string += 2; goto savefcb;} //TODO check (for ret value) - fcb_name.part.drive[0]=0; - hasdrive=true; - if (isalpha(d) && Drives[ascii_toupper(d)-'A']) { //Floppies under dos always exist, but don't bother with that at this level - ; //THIS* was here - } else ret=0xff; - fcb_name.part.drive[0]=DOS_ToUpper(string[0])-'A'+1; //Always do THIS* and continue parsing, just return the right code - string+=2; - } - - /* Check for extension only file names */ - if (string[0] == '.') {string++;goto checkext;} - - /* do nothing if not a valid name */ - if(!isvalid(string[0])) goto savefcb; - - hasname=true;finished=false;fill=' ';index=0; - /* Copy the name */ - while (true) { - unsigned char nc = *reinterpret_cast(&string[0]); - if ((IS_PC98_ARCH && shiftjis_lead_byte(nc)) || (isDBCSCP() && isKanji1(nc))) { - /* Shift-JIS is NOT ASCII and SHOULD NOT be converted to uppercase like ASCII */ - fcb_name.part.name[index]=(char)nc; - string++; - index++; - if (index >= 8) break; - - /* should be trailing byte of Shift-JIS */ - if (nc < 32 || nc >= 127) continue; - - fcb_name.part.name[index]=(char)nc; - } - else - { - char ncs = (char)ascii_toupper(nc); //Should use DOS_ToUpper, but then more calls need to be changed. - if (ncs == '*') { //Handle * - fill = '?'; - ncs = '?'; - } - if (ncs == '?' && !ret && index < 8) ret = 1; //Don't override bad drive - if (!isvalid(ncs)) { //Fill up the name. - while(index < 8) - fcb_name.part.name[index++] = (char)fill; - break; - } - if (index < 8) { - fcb_name.part.name[index++] = (char)((fill == '?')?fill:ncs); - } - } - string++; - } - if (!(string[0]=='.')) goto savefcb; - string++; -checkext: - /* Copy the extension */ - hasext=true;finished=false;fill=' ';index=0; - while (true) { - unsigned char nc = *reinterpret_cast(&string[0]); - if ((IS_PC98_ARCH && shiftjis_lead_byte(nc)) || (isDBCSCP() && isKanji1(nc))) { - /* DBCS is NOT ASCII and SHOULD NOT be converted to uppercase like ASCII */ - fcb_name.part.ext[index]=(char)nc; - string++; - index++; - if (index >= 3) break; - - /* should be trailing byte of DBCS character */ - if (nc < 32u || nc >= 127u) continue; - - fcb_name.part.ext[index]=(char)nc; - } - else - { - char ncs = (char)ascii_toupper(nc); - if (ncs == '*') { //Handle * - fill = '?'; - ncs = '?'; - } - if (ncs == '?' && !ret && index < 3) ret = 1; - if (!isvalid(ncs)) { //Fill up the name. - while(index < 3) - fcb_name.part.ext[index++] = (char)fill; - break; - } - if (index < 3) { - fcb_name.part.ext[index++] = (char)((fill=='?')?fill:ncs); - } - } - string++; - } -savefcb: - if (!hasdrive && !(parser & PARSE_DFLT_DRIVE)) fcb_name.part.drive[0] = 0; - if (!hasname && !(parser & PARSE_BLNK_FNAME)) strcpy(fcb_name.part.name," "); - if (!hasext && !(parser & PARSE_BLNK_FEXT)) strcpy(fcb_name.part.ext," "); - fcb.SetName((unsigned char)fcb_name.part.drive[0],fcb_name.part.name,fcb_name.part.ext); - fcb.ClearBlockRecsize(); //Undocumented bonus work. - *change=(uint8_t)(string-string_begin); - return ret; -} - -static void DTAExtendNameVolumeLabel(const char* const name, char* const filename, char* const ext) { - size_t i,s; - - i=0; - s=0; - while (i < 8 && name[s] != 0) filename[i++] = name[s++]; - while (i < 8) filename[i++] = ' '; - - i=0; - while (i < 3 && name[s] != 0) ext[i++] = name[s++]; - while (i < 3) ext[i++] = ' '; -} - -void DTAExtendName(char * const name,char * const filename,char * const ext) { - char * find=strchr(name,'.'); - if (find && find!=name) { - strcpy(ext,find+1); - *find=0; - } else ext[0]=0; - strcpy(filename,name); - size_t i; - for (i=strlen(name);i<8;i++) filename[i]=' '; - filename[8]=0; - for (i=strlen(ext);i<3;i++) ext[i]=' '; - ext[3]=0; -} - -static void SaveFindResult(DOS_FCB & find_fcb) { - DOS_DTA find_dta(dos.tables.tempdta); - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr;uint8_t drive; - char file_name[9];char ext[4]; - find_dta.GetResult(name,lname,size,hsize,date,time,attr); - drive=find_fcb.GetDrive()+1; - uint8_t find_attr = DOS_ATTR_ARCHIVE; - find_fcb.GetAttr(find_attr); /* Gets search attributes if extended */ - /* Create a correct file and extension */ - if (attr & DOS_ATTR_VOLUME) - DTAExtendNameVolumeLabel(name,file_name,ext); - else - DTAExtendName(name,file_name,ext); - - DOS_FCB fcb(RealSeg(dos.dta()),RealOff(dos.dta()));//TODO - fcb.Create(find_fcb.Extended()); - fcb.SetName(drive,file_name,ext); - fcb.SetAttr(find_attr); /* Only adds attribute if fcb is extended */ - fcb.SetResult(size,date,time,attr); -} - -bool DOS_FCBCreate(uint16_t seg,uint16_t offset) { - DOS_FCB fcb(seg,offset); - char shortname[DOS_FCBNAME];uint16_t handle; - uint8_t attr = DOS_ATTR_ARCHIVE; - fcb.GetAttr(attr); - if (!attr) attr = DOS_ATTR_ARCHIVE; //Better safe than sorry - - if (attr & DOS_ATTR_VOLUME) { - fcb.GetVolumeName(shortname); - return Drives[fcb.GetDrive()]->FileCreate(NULL,shortname,attr); - } - - fcb.GetName(shortname); - if (!DOS_CreateFile(shortname,attr,&handle,true)) return false; - fcb.FileOpen((uint8_t)handle); - return true; -} - -bool DOS_FCBOpen(uint16_t seg,uint16_t offset) { - DOS_FCB fcb(seg,offset); - char shortname[DOS_FCBNAME];uint16_t handle; - fcb.GetName(shortname); - - /* Search for file if name has wildcards */ - if (strpbrk(shortname,"*?")) { - LOG(LOG_FCB,LOG_WARN)("Wildcards in filename"); - if (!DOS_FCBFindFirst(seg,offset)) return false; - DOS_DTA find_dta(dos.tables.tempdta); - DOS_FCB find_fcb(RealSeg(dos.tables.tempdta),RealOff(dos.tables.tempdta)); - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH],file_name[9],ext[4]; - uint32_t size,hsize;uint16_t date,time;uint8_t attr; - find_dta.GetResult(name,lname,size,hsize,date,time,attr); - DTAExtendName(name,file_name,ext); - find_fcb.SetName(fcb.GetDrive()+1,file_name,ext); - find_fcb.GetName(shortname); - } - - /* First check if the name is correct */ - uint8_t drive; - char fullname[DOS_PATHLENGTH]; - if (!DOS_MakeName(shortname,fullname,&drive)) return false; - - /* Check, if file is already opened */ - for (uint8_t i = 0;i < DOS_FILES;i++) { - if (Files[i] && Files[i]->IsOpen() && Files[i]->IsName(fullname)) { - Files[i]->AddRef(); - fcb.FileOpen(i); - return true; - } - } - - if (!DOS_OpenFile(shortname,OPEN_READWRITE,&handle,true)) return false; - fcb.FileOpen((uint8_t)handle); - return true; -} - -bool DOS_FCBClose(uint16_t seg,uint16_t offset) { - DOS_FCB fcb(seg,offset); - if(!fcb.Valid()) return false; - uint8_t fhandle; - fcb.FileClose(fhandle); - DOS_CloseFile(fhandle,true); - return true; -} - -bool DOS_FCBFindFirst(uint16_t seg,uint16_t offset) { - DOS_FCB fcb(seg,offset); - RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta); - char name[DOS_FCBNAME];fcb.GetName(name); - uint8_t attr = DOS_ATTR_ARCHIVE; - fcb.GetAttr(attr); /* Gets search attributes if extended */ - bool ret=DOS_FindFirst(name,attr,true); - dos.dta(old_dta); - if (ret) SaveFindResult(fcb); - return ret; -} - -bool DOS_FCBFindNext(uint16_t seg,uint16_t offset) { - DOS_FCB fcb(seg,offset); - RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta); - bool ret=DOS_FindNext(); - dos.dta(old_dta); - if (ret) SaveFindResult(fcb); - return ret; -} - -uint8_t DOS_FCBRead(uint16_t seg,uint16_t offset,uint16_t recno) { - DOS_FCB fcb(seg,offset); - uint8_t fhandle,cur_rec;uint16_t cur_block,rec_size; - fcb.GetSeqData(fhandle,rec_size); - if (fhandle==0xff && rec_size!=0) { - if (!DOS_FCBOpen(seg,offset)) return FCB_READ_NODATA; - LOG(LOG_FCB,LOG_WARN)("Reopened closed FCB"); - fcb.GetSeqData(fhandle,rec_size); - } - if (rec_size == 0) { - rec_size = 128; - fcb.SetSeqData(fhandle,rec_size); - } - fcb.GetRecord(cur_block,cur_rec); - uint32_t pos=((cur_block*128u)+cur_rec)*rec_size; - if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_READ_NODATA; - uint16_t toread=rec_size; - if (!DOS_ReadFile(fhandle,dos_copybuf,&toread,true)) return FCB_READ_NODATA; - if (toread==0) return FCB_READ_NODATA; - if (toread < rec_size) { //Zero pad copybuffer to rec_size - Bitu i = toread; - while(i < rec_size) dos_copybuf[i++] = 0; - } - MEM_BlockWrite(Real2Phys(dos.dta())+(PhysPt)(recno*rec_size),dos_copybuf,rec_size); - if (++cur_rec>127u) { cur_block++;cur_rec=0; } - fcb.SetRecord(cur_block,cur_rec); - if (toread==rec_size) return FCB_SUCCESS; - return FCB_READ_PARTIAL; -} - -uint8_t DOS_FCBWrite(uint16_t seg,uint16_t offset,uint16_t recno) { - DOS_FCB fcb(seg,offset); - uint8_t fhandle,cur_rec;uint16_t cur_block,rec_size; - fcb.GetSeqData(fhandle,rec_size); - if (fhandle==0xffu && rec_size!=0u) { - if (!DOS_FCBOpen(seg,offset)) return FCB_READ_NODATA; - LOG(LOG_FCB,LOG_WARN)("Reopened closed FCB"); - fcb.GetSeqData(fhandle,rec_size); - } - if (rec_size == 0) { - rec_size = 128; - fcb.SetSeqData(fhandle,rec_size); - } - fcb.GetRecord(cur_block,cur_rec); - uint32_t pos=((cur_block*128u)+cur_rec)*rec_size; - if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_ERR_WRITE; - MEM_BlockRead(Real2Phys(dos.dta())+(PhysPt)(recno*rec_size),dos_copybuf,rec_size); - uint16_t towrite=rec_size; - if (!DOS_WriteFile(fhandle,dos_copybuf,&towrite,true)) return FCB_ERR_WRITE; - uint32_t size;uint16_t date,time; - fcb.GetSizeDateTime(size,date,time); - if (pos+towrite>size) size=pos+towrite; - //time doesn't keep track of endofday - date = DOS_PackDate(dos.date.year,dos.date.month,dos.date.day); - uint32_t ticks = mem_readd(BIOS_TIMER); - uint32_t seconds = (ticks*10u)/182u; - uint16_t hour = (uint16_t)(seconds/3600u); - uint16_t min = (uint16_t)((seconds % 3600u)/60u); - uint16_t sec = (uint16_t)(seconds % 60u); - time = DOS_PackTime(hour,min,sec); - Files[fhandle]->time = time; - Files[fhandle]->date = date; - fcb.SetSizeDateTime(size,date,time); - if (++cur_rec>127u) { cur_block++;cur_rec=0; } - fcb.SetRecord(cur_block,cur_rec); - return FCB_SUCCESS; -} - -uint8_t DOS_FCBIncreaseSize(uint16_t seg,uint16_t offset) { - DOS_FCB fcb(seg,offset); - uint8_t fhandle,cur_rec;uint16_t cur_block,rec_size; - fcb.GetSeqData(fhandle,rec_size); - fcb.GetRecord(cur_block,cur_rec); - uint32_t pos=((cur_block*128u)+cur_rec)*rec_size; - if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_ERR_WRITE; - uint16_t towrite=0; - if (!DOS_WriteFile(fhandle,dos_copybuf,&towrite,true)) return FCB_ERR_WRITE; - uint32_t size;uint16_t date,time; - fcb.GetSizeDateTime(size,date,time); - if (pos+towrite>size) size=pos+towrite; - //time doesn't keep track of endofday - date = DOS_PackDate(dos.date.year,dos.date.month,dos.date.day); - uint32_t ticks = mem_readd(BIOS_TIMER); - uint32_t seconds = (ticks*10u)/182u; - uint16_t hour = (uint16_t)(seconds/3600u); - uint16_t min = (uint16_t)((seconds % 3600u)/60u); - uint16_t sec = (uint16_t)(seconds % 60u); - time = DOS_PackTime(hour,min,sec); - Files[fhandle]->time = time; - Files[fhandle]->date = date; - fcb.SetSizeDateTime(size,date,time); - fcb.SetRecord(cur_block,cur_rec); - return FCB_SUCCESS; -} - -uint8_t DOS_FCBRandomRead(uint16_t seg,uint16_t offset,uint16_t * numRec,bool restore) { -/* if restore is true :random read else random block read. - * random read updates old block and old record to reflect the random data - * before the read!!!!!!!!! and the random data is not updated! (user must do this) - * Random block read updates these fields to reflect the state after the read! + #include + #include + #include + #include + #if defined(WIN32) && defined(__MINGW32__) + # include + #endif + + #include "dosbox.h" + #include "bios.h" + #include "logging.h" + #include "mem.h" + #include "regs.h" + #include "dos_inc.h" + #include "drives.h" + #include "cross.h" + #include "control.h" + #include "support.h" + #include "menu.h" + #include "cdrom.h" + #include "ide.h" + #include "bios_disk.h" + + #define DOS_FILESTART 4 + + #define FCB_SUCCESS 0 + #define FCB_READ_NODATA 1 + #define FCB_READ_PARTIAL 3 + #define FCB_ERR_NODATA 1 + #define FCB_ERR_EOF 3 + #define FCB_ERR_WRITE 1 + + extern bool log_int21; + extern bool log_fileio; + extern bool enable_share_exe, enable_dbcs_tables; + extern int dos_clipboard_device_access; + extern const char *dos_clipboard_device_name; + + Bitu DOS_FILES = 127; + DOS_File ** Files = NULL; + DOS_Drive * Drives[DOS_DRIVES] = {NULL}; + bool force_sfn = false; + int sdrive = 0; + + /* This is the LFN filefind handle that is currently being used, with normal values between + * 0 and 254 for LFN calls. The value LFN_FILEFIND_INTERNAL and LFN_FILEFIND_IMG are used + * internally by LFN and image handling functions. For non-LFN calls the value is fixed to + * be LFN_FILEFIND_NONE as defined in drives.h. */ + int lfn_filefind_handle = LFN_FILEFIND_NONE; + bool isDBCSCP(), isKanji1(uint8_t chr), shiftjis_lead_byte(int c); + + bool DOS_GetFileAttrEx(char const* const name, struct stat *status, uint8_t hdrive) + { + char fullname[DOS_PATHLENGTH]; + uint8_t drive; + bool usehdrive=/*hdrive>=0&&(always true)*/hdriveGetFileAttrEx(fullname, status); + } + + #include "dos_network2.h" + + uint8_t DOS_GetDefaultDrive(void) { + // return DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).GetDrive(); + uint8_t d = DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).GetDrive(); + if( d != dos.current_drive ) LOG(LOG_DOSMISC,LOG_ERROR)("SDA drive %d not the same as dos.current_drive %d",d,dos.current_drive); + return dos.current_drive; + } + + void DOS_SetDefaultDrive(uint8_t drive) { + // if (drive<=DOS_DRIVES && ((drive<2) || Drives[drive])) DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).SetDrive(drive); + if (drive=DOS_DRIVES || !Drives[*drive]) { + DOS_SetError(DOSERR_PATH_NOT_FOUND); + return false; + } + + if(isVolume) // Don't process any further + { + strcpy(fullname, name_int); + return true; + } + + r=0;w=0; + while (r='a') && (c<='z')) c-=32; + else if (c==' ') continue; /* should be separator */ + } + upname[w++]=(char)c; + if (((IS_PC98_ARCH && shiftjis_lead_byte(c)) || (isDBCSCP() && isKanji1(c))) && r0 && name_int[r-1]==' ') r--; + if (r>=DOS_PATHLENGTH) { DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; } + upname[w]=0; + + /* Now parse the new file name to make the final filename */ + if (upname[0]!='\\') strcpy(fullname,Drives[*drive]->curdir); + else fullname[0]=0; + uint32_t lastdir=0;uint32_t t=0; + bool lead = false; + while (fullname[t]!=0) { + if (lead) lead = false; + else if ((IS_PC98_ARCH && shiftjis_lead_byte(fullname[t])) || (isDBCSCP() && isKanji1(fullname[t]))) lead = true; + else if ((fullname[t]=='\\') && (fullname[t+1]!=0)) lastdir=t; + t++; + } + r=0;w=0; + tempdir[0]=0; + lead=false; + bool stop=false; + while (!stop) { + if (lead) lead=false; + else if ((IS_PC98_ARCH && shiftjis_lead_byte(upname[r])) || (isDBCSCP() && isKanji1(upname[r]))) lead=true; + else if ((upname[r]=='\\') || (upname[r]==0)){ + if (upname[r]==0) stop=true; + tempdir[w]=0; + if (tempdir[0]==0) { w=0;r++;continue;} + if (strcmp(tempdir,".")==0) { + tempdir[0]=0; + w=0;r++; + continue; + } + + int32_t iDown; + bool dots = true; + int32_t templen=(int32_t)strlen(tempdir); + for(iDown=0;(iDown < templen) && dots;iDown++) + if(tempdir[iDown] != '.') + dots = false; + + // only dots? + if (dots && (templen > 1)) { + int32_t cDots = templen - 1; + for(iDown=(int32_t)strlen(fullname)-1;iDown>=0;iDown--) { + if(fullname[iDown]=='\\' || iDown==0) { + if (iDown > 0 && (IS_PC98_ARCH || isDBCSCP())) { + char c = fullname[iDown+1]; + fullname[iDown+1] = 0; + char *p = strrchr_dbcs(fullname, '\\'); + fullname[iDown+1] = c; + if (p==NULL || p-fullnamefile not found + //Or path not found depending on whether + //we are still in dir check stage or file stage + if(stop) + DOS_SetError(DOSERR_FILE_NOT_FOUND); + else + DOS_SetError(DOSERR_PATH_NOT_FOUND); + return false; + } + + ext[4] = 0; + if((strlen(tempdir) - strlen(ext)) > 8) memmove(tempdir + 8, ext, 5); + } else { + tempdir[8] = 0; + } + } + + if (strlen(fullname)+strlen(tempdir)>=DOS_PATHLENGTH) { + DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; + } + + strcat(fullname,tempdir); + tempdir[0]=0; + w=0;r++; + continue; + } + tempdir[w++]=upname[r++]; + } + return true; + } + + bool checkwat=false; + bool DOS_GetSFNPath(char const * const path,char * SFNPath,bool LFN) { + char pdir[LFN_NAMELENGTH+4], *p; + uint8_t drive;char fulldir[DOS_PATHLENGTH],LFNPath[CROSS_LEN]; + char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH]; + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; + if (!DOS_MakeName(path,fulldir,&drive)) return false; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(fulldir)) { + strcpy(SFNPath,fulldir); + return true; + } + #endif + sprintf(SFNPath,"%c:\\",drive+'A'); + strcpy(LFNPath,SFNPath); + p = fulldir; + if (*p==0) return true; + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + int fbak=lfn_filefind_handle; + for (char *s = strchr_dbcs(p,'\\'); s != NULL; s = strchr_dbcs(p,'\\')) { + *s = 0; + if (check_last_split_char(SFNPath, strlen(SFNPath), '\\')) + sprintf(pdir,"\"%s%s\"",SFNPath,p); + else + sprintf(pdir,"\"%s\\%s\"",SFNPath,p); + if (!strrchr(p,'*') && !strrchr(p,'?')) { + *s = '\\'; + p = s + 1; + lfn_filefind_handle=LFN_FILEFIND_INTERNAL; + if (DOS_FindFirst(pdir,0xffff & DOS_ATTR_DIRECTORY & ~DOS_ATTR_VOLUME,false)) { + lfn_filefind_handle=fbak; + dta.GetResult(name,lname,size,hsize,date,time,attr); + strcat(SFNPath,name); + strcat(LFNPath,lname); + strcat(SFNPath,"\\"); + strcat(LFNPath,"\\"); + } + else { + lfn_filefind_handle=fbak; + dos.dta(save_dta); + return false; + } + } else { + strcat(SFNPath,p); + strcat(LFNPath,p); + strcat(SFNPath,"\\"); + strcat(LFNPath,"\\"); + *s = '\\'; + p = s + 1; + break; + } + } + if (p) { + sprintf(pdir,"\"%s%s\"",SFNPath,p); + lfn_filefind_handle=LFN_FILEFIND_INTERNAL; + if (!strrchr(p,'*')&&!strrchr(p,'?')&&DOS_FindFirst(pdir,0xffff & ~DOS_ATTR_VOLUME,false)) { + dta.GetResult(name,lname,size,hsize,date,time,attr); + strcat(SFNPath,name); + strcat(LFNPath,lname); + } else if (checkwat) { + lfn_filefind_handle=fbak; + dos.dta(save_dta); + return false; + } else { + strcat(SFNPath,p); + strcat(LFNPath,p); + } + lfn_filefind_handle=fbak; + } + dos.dta(save_dta); + if (LFN) strcpy(SFNPath,LFNPath); + return true; + } + + bool DOS_GetCurrentDir(uint8_t drive,char * const buffer, bool LFN) { + if (drive==0) drive=DOS_GetDefaultDrive(); + else drive--; + + if ((drive>=DOS_DRIVES) || (!Drives[drive])) { + DOS_SetError(DOSERR_INVALID_DRIVE); + return false; + } + + if (LFN && uselfn) { + char cdir[DOS_PATHLENGTH+8],ldir[DOS_PATHLENGTH]; + + if (strchr(Drives[drive]->curdir,' ')) + sprintf(cdir,"\"%c:\\%s\"",drive+'A',Drives[drive]->curdir); + else + sprintf(cdir,"%c:\\%s",drive+'A',Drives[drive]->curdir); + + if (!DOS_GetSFNPath(cdir,ldir,true)) + return false; + + strcpy(buffer,ldir+3); + if (DOS_GetSFNPath(cdir,ldir,false)) + strcpy(Drives[drive]->curdir,ldir+3); + } else { + strcpy(buffer,Drives[drive]->curdir); + } + + return true; + } + + bool DOS_ChangeDir(char const * const dir) { + uint8_t drive;char fulldir[DOS_PATHLENGTH]; + const char * testdir=dir; + if (strlen(testdir) && testdir[1]==':') testdir+=2; + size_t len=strlen(testdir); + if (!len) { + DOS_SetError(DOSERR_PATH_NOT_FOUND); + return false; + } + if (!DOS_MakeName(dir,fulldir,&drive)) return false; + if (strlen(fulldir) && check_last_split_char(testdir, len, '\\')) { + DOS_SetError(DOSERR_PATH_NOT_FOUND); + return false; + } + + if (Drives[drive]->TestDir(fulldir)) { + strcpy(Drives[drive]->curdir,fulldir); + return true; + } else { + DOS_SetError(DOSERR_PATH_NOT_FOUND); + } + return false; + } + + bool DOS_MakeDir(char const * const dir) { + uint8_t drive;char fulldir[DOS_PATHLENGTH]; + size_t len = strlen(dir); + if(!len || check_last_split_char(dir, len, '\\')) { + DOS_SetError(DOSERR_PATH_NOT_FOUND); + return false; + } + if (!DOS_MakeName(dir,fulldir,&drive)) return false; + while (strlen(fulldir)&&(*(fulldir+strlen(fulldir)-1)=='.'||*(fulldir+strlen(fulldir)-1)==' ')) *(fulldir+strlen(fulldir)-1)=0; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(dir)) return Network_MakeDir(dir); + #endif + if(Drives[drive]->MakeDir(fulldir)) return true; + + /* Determine reason for failing */ + if(Drives[drive]->TestDir(fulldir)) + DOS_SetError(DOSERR_ACCESS_DENIED); + else + DOS_SetError(DOSERR_PATH_NOT_FOUND); + return false; + } + + bool DOS_RemoveDir(char const * const dir) { + /* We need to do the test before the removal as can not rely on + * the host to forbid removal of the current directory. + * We never change directory. Everything happens in the drives. + */ + uint8_t drive;char fulldir[DOS_PATHLENGTH]; + if (!DOS_MakeName(dir,fulldir,&drive)) return false; + /* Check if exists */ + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(dir)) return Network_RemoveDir(dir); + #endif + if(!Drives[drive]->TestDir(fulldir)) { + DOS_SetError(DOSERR_PATH_NOT_FOUND); + return false; + } + /* See if it's current directory */ + char currdir[DOS_PATHLENGTH]= { 0 }, lcurrdir[DOS_PATHLENGTH]= { 0 }; + DOS_GetCurrentDir(drive + 1 ,currdir, false); + DOS_GetCurrentDir(drive + 1 ,lcurrdir, true); + if(strcasecmp(currdir,fulldir) == 0 || (uselfn && strcasecmp(lcurrdir,fulldir) == 0)) { + DOS_SetError(DOSERR_REMOVE_CURRENT_DIRECTORY); + return false; + } + + if(Drives[drive]->RemoveDir(fulldir)) return true; + + /* Failed. We know it exists and it's not the current dir */ + /* Assume non empty */ + DOS_SetError(DOSERR_ACCESS_DENIED); + return false; + } + + static bool PathExists(char const * const name) { + const char* leading = strrchr_dbcs((char *)name,'\\'); + if(!leading) return true; + char temp[CROSS_LEN]; + strcpy(temp,name); + char * lead = strrchr_dbcs(temp,'\\'); + if (lead == temp) return true; + *lead = 0; + uint8_t drive;char fulldir[DOS_PATHLENGTH]; + if (!DOS_MakeName(temp,fulldir,&drive)) return false; + if(!Drives[drive]->TestDir(fulldir)) return false; + return true; + } + + bool DOS_Rename(char const * const oldname,char const * const newname) { + uint8_t driveold;char fullold[DOS_PATHLENGTH]; + uint8_t drivenew;char fullnew[DOS_PATHLENGTH]; + if (!DOS_MakeName(oldname,fullold,&driveold)) return false; + if (!DOS_MakeName(newname,fullnew,&drivenew)) return false; + while (strlen(fullnew)&&(*(fullnew+strlen(fullnew)-1)=='.'||*(fullnew+strlen(fullnew)-1)==' ')) *(fullnew+strlen(fullnew)-1)=0; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(oldname)) return Network_Rename(oldname,newname); + #endif + + /* No tricks with devices */ + bool clip=false; + if ( (DOS_FindDevice(oldname) != DOS_DEVICES) || + (DOS_FindDevice(newname) != DOS_DEVICES) ) { + if (!control->SecureMode()&&(dos_clipboard_device_access==3||dos_clipboard_device_access==4)) { + if (DOS_FindDevice(oldname) == DOS_DEVICES) { + const char* find_last; + find_last=strrchr_dbcs(fullnew,'\\'); + if (find_last==NULL) find_last=fullnew; + else find_last++; + if (!strcasecmp(find_last, *dos_clipboard_device_name?dos_clipboard_device_name:"CLIP$")) + clip=true; + } + } + if (!clip) { + DOS_SetError(DOSERR_FILE_NOT_FOUND); + return false; + } + } + /* Must be on the same drive */ + if(driveold != drivenew) { + DOS_SetError(DOSERR_NOT_SAME_DEVICE); + return false; + } + uint16_t attr; + /* Source must exist */ + if (!Drives[driveold]->GetFileAttr( fullold, &attr ) ) { + if (!PathExists(oldname)) DOS_SetError(DOSERR_PATH_NOT_FOUND); + else DOS_SetError(DOSERR_FILE_NOT_FOUND); + return false; + } + /*Test if target exists => no access */ + if(Drives[drivenew]->GetFileAttr(fullnew,&attr)&&!(uselfn&&!force_sfn&&strcmp(fullold, fullnew)&&!strcasecmp(fullold, fullnew))) { + DOS_SetError(DOSERR_ACCESS_DENIED); + return false; + } + + #if defined (WIN32) + if (clip) { + uint16_t sourceHandle, targetHandle, toread = 0x8000; + static uint8_t buffer[0x8000]; + bool failed = false; + if (DOS_OpenFile(oldname,OPEN_READ,&sourceHandle) && DOS_OpenFile(newname,OPEN_WRITE,&targetHandle)) { + do { + if (!DOS_ReadFile(sourceHandle,buffer,&toread) || !DOS_WriteFile(targetHandle,buffer,&toread)) failed=true; + } while (toread == 0x8000); + if (!DOS_CloseFile(sourceHandle)||!DOS_CloseFile(targetHandle)) failed=true; + } else failed=true; + if (!failed&&Drives[drivenew]->FileUnlink(fullold)) return true; + } else + #endif + + if (Drives[drivenew]->Rename(fullold,fullnew)) return true; + /* Rename failed despite checks => no access */ + DOS_SetError(DOSERR_ACCESS_DENIED); + return false; + } + + bool forcelfn = false; + bool DOS_FindFirst(const char * search,uint16_t attr,bool fcb_findfirst) { + LOG(LOG_FILES,LOG_NORMAL)("file search attributes %X name %s",attr,search); + DOS_DTA dta(dos.dta()); + uint8_t drive;char fullsearch[DOS_PATHLENGTH]; + char dir[DOS_PATHLENGTH];char pattern[DOS_PATHLENGTH]; + size_t len = strlen(search); + if(len && check_last_split_char(search, len, '\\') && !( (len > 2) && (search[len - 2] == ':') && (attr == DOS_ATTR_VOLUME) )) { + //Dark Forces installer, but c:\ is alright for volume labels(exclusively set) + DOS_SetError(DOSERR_NO_MORE_FILES); + return false; + } + if (!DOS_MakeName(search,fullsearch,&drive,attr == DOS_ATTR_VOLUME)) return false; + //Check for devices. FindDevice checks for leading subdir as well + bool device = false; + //if (attr & DOS_ATTR_DEVICE) /* FIX_ME: This line deleted to fix launching Blocek editor (Issue #4385), revert this if this induces other errors */ + device = DOS_FindDevice(search) != DOS_DEVICES; + + /* Split the search in dir and pattern */ + forcelfn = false; + char *find_last = NULL; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + bool net = Network_IsNetworkResource(search); + if (net) forcelfn = true; + char *p = net ? strchr_dbcs(fullsearch+(fullsearch[0]=='"'?3:2), '\\') : NULL; + find_last = strrchr_dbcs(p != NULL ? p + 1 : fullsearch, '\\'); + #else + find_last = strrchr_dbcs(fullsearch,'\\'); + #endif + if (!find_last) { /*No dir */ + strcpy(pattern,fullsearch); + dir[0]=0; + } else { + *find_last=0; + strcpy(pattern,find_last+1); + strcpy(dir,fullsearch); + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (!strlen(dir)&&Network_IsNetworkResource(pattern)) {forcelfn=false;return false;} + #endif + + // Silence CHKDSK "Invalid sub-directory entry" + if (fcb_findfirst && !strcmp(search+1, ":????????.???") && attr==30) { + char psp_name[9]; + DOS_MCB psp_mcb(dos.psp()-1); + psp_mcb.GetFileName(psp_name); + if (!strcmp(psp_name, "CHKDSK")) attr&=~DOS_ATTR_DIRECTORY; + } + + sdrive=drive; + dta.SetupSearch(drive,(uint8_t)attr,pattern); + forcelfn = false; + + if(device) { + find_last = strrchr(pattern,'.'); + if(find_last) *find_last = 0; + //TODO use current date and time + dta.SetResult(pattern,pattern,0,0,0,0,DOS_ATTR_DEVICE); + LOG(LOG_DOSMISC,LOG_WARN)("finding device %s",pattern); + return true; + } + + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (net) return Network_FindFirst(dir,dta); + #endif + if (Drives[drive]->FindFirst(dir,dta,fcb_findfirst)) return true; + return false; + } + + bool DOS_FindNext(void) { + DOS_DTA dta(dos.dta()); + uint8_t i = dta.GetSearchDrive(); + if(uselfn && (i >= DOS_DRIVES || !Drives[i])) i=sdrive; + if(i >= DOS_DRIVES || !Drives[i]) { + /* Corrupt search. */ + LOG(LOG_FILES,LOG_ERROR)("Corrupt search!!!!"); + DOS_SetError(DOSERR_NO_MORE_FILES); + return false; + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + unsigned int pos = lfn_filefind_handle>=LFN_FILEFIND_MAX?dta.GetDirID():lfn_id[lfn_filefind_handle]; + if (pos==65534) return Network_FindNext(dta); + #endif + if (Drives[i]->FindNext(dta)) return true; + return false; + } + + + bool DOS_ReadFile(uint16_t entry,uint8_t * data,uint16_t * amount,bool fcb) { + uint32_t handle = fcb?entry:RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsActiveResource(entry)) + return Network_ReadFile(entry,data,amount); + #endif + if (!Files[handle] || !Files[handle]->IsOpen()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + + if (log_fileio) { + LOG(LOG_FILES, LOG_DEBUG)("Reading %d bytes from %s ", *amount, Files[handle]->name); + } + /* + if ((Files[handle]->flags & 0x0f) == OPEN_WRITE)) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } */ - DOS_FCB fcb(seg,offset); - uint32_t random; - uint16_t old_block=0; - uint8_t old_rec=0; - uint8_t error=0; - uint16_t count; - - /* Set the correct record from the random data */ - fcb.GetRandom(random); - fcb.SetRecord((uint16_t)(random / 128u),(uint8_t)(random & 127u)); - if (restore) fcb.GetRecord(old_block,old_rec);//store this for after the read. - // Read records - for (count=0; count<*numRec; count++) { - error = DOS_FCBRead(seg,offset,count); - if (error!=FCB_SUCCESS) break; - } - if (error==FCB_READ_PARTIAL) count++; //partial read counts - *numRec=count; - uint16_t new_block;uint8_t new_rec; - fcb.GetRecord(new_block,new_rec); - if (restore) fcb.SetRecord(old_block,old_rec); - /* Update the random record pointer with new position only when restore is false*/ - if(!restore) fcb.SetRandom(new_block*128u+new_rec); - return error; -} - -uint8_t DOS_FCBRandomWrite(uint16_t seg,uint16_t offset,uint16_t * numRec,bool restore) { -/* see FCB_RandomRead */ - DOS_FCB fcb(seg,offset); - uint32_t random; - uint16_t old_block=0; - uint8_t old_rec=0; - uint8_t error=0; - - /* Set the correct record from the random data */ - fcb.GetRandom(random); - fcb.SetRecord((uint16_t)(random / 128u),(uint8_t)(random & 127u)); - if (restore) fcb.GetRecord(old_block,old_rec); - if (*numRec > 0) { - uint16_t count; - /* Write records */ - for (count=0; count<*numRec; count++) { - error = DOS_FCBWrite(seg,offset,count);// dos_fcbwrite return 0 false when true... - if (error!=FCB_SUCCESS) break; - } - *numRec=count; - } else { - DOS_FCBIncreaseSize(seg,offset); - } - uint16_t new_block;uint8_t new_rec; - fcb.GetRecord(new_block,new_rec); - if (restore) fcb.SetRecord(old_block,old_rec); - /* Update the random record pointer with new position only when restore is false */ - if (!restore) fcb.SetRandom(new_block*128u+new_rec); - return error; -} - -bool DOS_FCBGetFileSize(uint16_t seg,uint16_t offset) { - char shortname[DOS_PATHLENGTH];uint16_t entry; - DOS_FCB fcb(seg,offset); - fcb.GetName(shortname); - if (!DOS_OpenFile(shortname,OPEN_READ,&entry,true)) return false; - uint32_t size = 0; - Files[entry]->Seek(&size,DOS_SEEK_END); - DOS_CloseFile(entry,true); - - uint8_t handle; uint16_t rec_size; - fcb.GetSeqData(handle,rec_size); - if (rec_size == 0) rec_size = 128; //Use default if missing. - - uint32_t random=(size/rec_size); - if (size % rec_size) random++; - fcb.SetRandom(random); - return true; -} - -bool DOS_FCBDeleteFile(uint16_t seg,uint16_t offset){ -/* Special case: ????????.??? and DOS_ATTR_VOLUME */ - { - DOS_FCB fcb(seg,offset); - uint8_t attr = 0; - fcb.GetAttr(attr); - uint8_t drive = fcb.GetDrive(); - std::string label = Drives[drive]->GetLabel(); - - if (attr & DOS_ATTR_VOLUME) { - char shortname[DOS_FCBNAME]; - fcb.GetVolumeName(shortname); - - if (!strcmp(shortname,"???????????")) { - if (!label.empty()) { - Drives[drive]->SetLabel("",false,true); - LOG(LOG_DOSMISC,LOG_NORMAL)("FCB delete volume label"); - return true; - } - } - else { - /* MS-DOS 6.22 LABEL.EXE will explicitly request to delete the volume label by the volume label not ????????.???? */ - if (!label.empty()) { - while (label.length() < 11) label += ' '; - if (!memcmp(label.c_str(),shortname,11)) { - Drives[drive]->SetLabel("",false,true); - LOG(LOG_DOSMISC,LOG_NORMAL)("FCB delete volume label deleted"); - return true; - } - } - } - - LOG(LOG_DOSMISC,LOG_NORMAL)("FCB delete volume label not found (current='%s' asking='%s')",label.c_str(),shortname); - DOS_SetError(DOSERR_FILE_NOT_FOUND); // right? - return false; - } - } - -/* FCB DELETE honours wildcards. it will return true if one or more - * files get deleted. - * To get this: the dta is set to temporary dta in which found files are - * stored. This can not be the tempdta as that one is used by fcbfindfirst + uint16_t toread=*amount; + bool ret=Files[handle]->Read(data,&toread); + *amount=toread; + return ret; + } + + bool DOS_WriteFile(uint16_t entry,const uint8_t * data,uint16_t * amount,bool fcb) { + uint32_t handle = fcb?entry:RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsActiveResource(entry)) + return Network_WriteFile(entry,data,amount); + #endif + if (!Files[handle] || !Files[handle]->IsOpen()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + + if (log_fileio) { + LOG(LOG_FILES, LOG_DEBUG)("Writing %d bytes to %s", *amount, Files[handle]->name); + } + /* + if ((Files[handle]->flags & 0x0f) == OPEN_READ)) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } */ - RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta_fcbdelete); - RealPt new_dta=dos.dta(); - bool nextfile = false; - bool return_value = false; - nextfile = DOS_FCBFindFirst(seg,offset); - DOS_FCB fcb(RealSeg(new_dta),RealOff(new_dta)); - while(nextfile) { - char shortname[DOS_FCBNAME] = { 0 }; - fcb.GetName(shortname); - bool res=DOS_UnlinkFile(shortname); - if(!return_value && res) return_value = true; //at least one file deleted - nextfile = DOS_FCBFindNext(seg,offset); - } - dos.dta(old_dta); /*Restore dta */ - return return_value; -} - -char* trimString(char* str); - -bool DOS_FCBRenameFile(uint16_t seg, uint16_t offset){ - DOS_FCB fcbold(seg,offset); - DOS_FCB fcbnew(seg,offset); - fcbnew.SetPtPhys(fcbnew.GetPtPhys()+0x10u);//HACK: FCB NEW memory offset is affected by whether FCB OLD is extended - if(!fcbold.Valid()) return false; - char oldname[DOS_FCBNAME]; - char newname[DOS_FCBNAME]; - fcbold.GetName(oldname);fcbnew.GetName(newname); - - { - uint8_t drive = fcbold.GetDrive(); - std::string label = Drives[drive]->GetLabel(); - uint8_t attr = 0; - - fcbold.GetAttr(attr); - /* According to RBIL and confirmed with SETLABEL.ASM in DOSLIB2, you can rename a volume label dirent as well with this function */ - if (attr & DOS_ATTR_VOLUME) { - fcbold.GetVolumeName(oldname); - fcbnew.GetVolumeName(newname); - - for (unsigned int i=0;i < 11;i++) - oldname[i] = toupper(oldname[i]); - - trimString(oldname); - trimString(newname); - - if (!label.empty()) { - if (!strcmp(oldname,"???????????") || label == oldname) { - Drives[drive]->SetLabel(newname,false,true); - LOG(LOG_DOSMISC,LOG_NORMAL)("FCB rename volume label to '%s' from '%s'",newname,oldname); - return true; - } - else { - LOG(LOG_DOSMISC,LOG_NORMAL)("FCB rename volume label rejected, does not match current label '%s' from '%s'",newname,oldname); - DOS_SetError(DOSERR_FILE_NOT_FOUND); // right? - return false; - } - } - else { - LOG(LOG_DOSMISC,LOG_NORMAL)("FCB rename volume label rejected, no label set"); - DOS_SetError(DOSERR_FILE_NOT_FOUND); // right? - return false; - } - } - } - - /* Check, if sourcefile is still open. This was possible in DOS, but modern oses don't like this */ - uint8_t drive; char fullname[DOS_PATHLENGTH]; - if (!DOS_MakeName(oldname,fullname,&drive)) return false; - - DOS_PSP psp(dos.psp()); - for (uint8_t i=0;iIsOpen() && Files[i]->IsName(fullname)) { - uint16_t handle = psp.FindEntryByHandle(i); - //(more than once maybe) - if (handle == 0xFFu) { - DOS_CloseFile(i,true); - } else { - DOS_CloseFile(handle); - } - } - } - - /* Rename the file */ - return DOS_Rename(oldname,newname); -} - -void DOS_FCBSetRandomRecord(uint16_t seg, uint16_t offset) { - DOS_FCB fcb(seg,offset); - uint16_t block;uint8_t rec; - fcb.GetRecord(block,rec); - fcb.SetRandom(block*128u+rec); -} - - -bool DOS_FileExists(char const * const name) { - char fullname[DOS_PATHLENGTH];uint8_t drive; - if (!DOS_MakeName(name,fullname,&drive)) return false; -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(name)) return Network_FileExists(fullname); -#endif - return Drives[drive]->FileExists(fullname); -} - -bool DOS_GetAllocationInfo(uint8_t drive,uint16_t * _bytes_sector,uint8_t * _sectors_cluster,uint16_t * _total_clusters) { - if (!drive) drive = DOS_GetDefaultDrive(); - else drive--; - if (drive >= DOS_DRIVES || !Drives[drive]) { - DOS_SetError(DOSERR_INVALID_DRIVE); - return false; - } - uint16_t _free_clusters; - Drives[drive]->AllocationInfo(_bytes_sector,_sectors_cluster,_total_clusters,&_free_clusters); - SegSet16(ds,RealSeg(dos.tables.mediaid)); - reg_bx=RealOff(dos.tables.mediaid+drive*dos.tables.dpb_size); - return true; -} - -bool DOS_SetDrive(uint8_t drive) { - if (Drives[drive]) { - DOS_SetDefaultDrive(drive); - return true; - } else { - return false; - } -} - -bool DOS_GetFileDate(uint16_t entry, uint16_t* otime, uint16_t* odate) { - uint32_t handle=RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsActiveResource(entry)) - return Network_GetFileDate(entry, otime, odate); -#endif - if (!Files[handle] || !Files[handle]->IsOpen()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - if (!Files[handle]->UpdateDateTimeFromHost()) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - *otime = Files[handle]->time; - *odate = Files[handle]->date; - return true; -} - -bool DOS_SetFileDate(uint16_t entry, uint16_t ntime, uint16_t ndate) -{ - uint32_t handle=RealHandle(entry); - if (handle>=DOS_FILES) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if(Network_IsActiveResource(entry)) - return Network_SetFileDate(entry, ntime, ndate); -#endif - if (!Files[handle]) { - DOS_SetError(DOSERR_INVALID_HANDLE); - return false; - } - Files[handle]->time = ntime; - Files[handle]->date = ndate; - Files[handle]->newtime = true; - - return true; -} - -extern int swapInDisksSpecificDrive; -void DOS_SetupFiles (void) { - /* Setup the File Handles */ - Files = new DOS_File * [DOS_FILES]; - uint32_t i; - for (i=0;iRelease(); - diskSwap[si] = NULL; - } - } - swapInDisksSpecificDrive = -1; - } - Drives[25]=new Virtual_Drive(); -} - -// save state support -void DOS_File::SaveState( std::ostream& stream ) -{ - uint32_t file_namelen, seek_pos; - - - file_namelen = (uint32_t)strlen( name ); - seek_pos = GetSeekPos(); - - //****************************************** - //****************************************** - //****************************************** - - // - pure data - WRITE_POD( &file_namelen, file_namelen ); - WRITE_POD_SIZE( name, file_namelen ); - - WRITE_POD( &flags, flags ); - WRITE_POD( &open, open ); - - WRITE_POD( &attr, attr ); - WRITE_POD( &time, time ); - WRITE_POD( &date, date ); - WRITE_POD( &refCtr, refCtr ); - WRITE_POD( &hdrive, hdrive ); - - //****************************************** - //****************************************** - //****************************************** - - // - reloc ptr - WRITE_POD( &seek_pos, seek_pos ); -} - - -void DOS_File::LoadState( std::istream& stream, bool pop ) -{ - uint32_t file_namelen, seek_pos; - char *file_name; - - //****************************************** - //****************************************** - //****************************************** - - // - pure data - READ_POD( &file_namelen, file_namelen ); - file_name = (char*)alloca( file_namelen * sizeof(char) ); - READ_POD_SIZE( file_name, file_namelen ); - - READ_POD( &flags, flags ); - READ_POD( &open, open ); - - READ_POD( &attr, attr ); - READ_POD( &time, time ); - READ_POD( &date, date ); - READ_POD( &refCtr, refCtr ); - READ_POD( &hdrive, hdrive ); - - //****************************************** - //****************************************** - //****************************************** - - // - reloc ptr - READ_POD( &seek_pos, seek_pos ); - - if (pop) - return; - - if( open ) Seek( &seek_pos, DOS_SEEK_SET ); - else Close(); -} - -extern bool dos_kernel_disabled; -extern uint8_t ZDRIVE_NUM; -struct Alloc { - uint16_t bytes_sector; - uint8_t sectors_cluster; - uint16_t total_clusters; - uint16_t free_clusters; - uint8_t mediaid; -}; -Alloc lalloc, oalloc; -struct Opts { - uint32_t bytesector; - uint32_t cylsector; - uint32_t headscyl; - uint32_t cylinders; - int mounttype; - uint8_t mediaid; - unsigned char CDROM_drive; - unsigned long cdrom_sector_offset; - unsigned char floppy_emu_type; -}; -Opts opts; -char overlaydir[CROSS_LEN]; -void MSCDEX_SetCDInterface(int intNr, int forceCD); -void POD_Save_DOS_Files( std::ostream& stream ) -{ - char dinfo[256]; - WRITE_POD( &ZDRIVE_NUM, ZDRIVE_NUM); - if (!dos_kernel_disabled) { - // 1. Do drives first (directories -> files) - // 2. Then files next - - for( int i=2; iGetInfo()); - WRITE_POD( &dinfo, dinfo); - *overlaydir=0; - if (!strncmp(dinfo,"local directory ",16) || !strncmp(dinfo,"CDRom ",6) || !strncmp(dinfo,"PhysFS directory ",17) || !strncmp(dinfo,"PhysFS CDRom ",13) ) { - localDrive *ldp = dynamic_cast(Drives[lcv]); - if (!ldp) ldp = dynamic_cast(Drives[lcv]); - if (!ldp) ldp = dynamic_cast(Drives[lcv]); - if (ldp) { - lalloc.bytes_sector=ldp->allocation.bytes_sector; - lalloc.sectors_cluster=ldp->allocation.sectors_cluster; - lalloc.total_clusters=ldp->allocation.total_clusters; - lalloc.free_clusters=ldp->allocation.free_clusters; - lalloc.mediaid=ldp->allocation.mediaid; - } - Overlay_Drive *odp = dynamic_cast(Drives[lcv]); - if (odp) { - strcpy(overlaydir,odp->getOverlaydir()); - oalloc.bytes_sector=odp->allocation.bytes_sector; - oalloc.sectors_cluster=odp->allocation.sectors_cluster; - oalloc.total_clusters=odp->allocation.total_clusters; - oalloc.free_clusters=odp->allocation.free_clusters; - oalloc.mediaid=odp->allocation.mediaid; - } else { - physfsDrive *pdp = dynamic_cast(Drives[lcv]); - if (pdp && pdp->getOverlaydir()) - strcpy(overlaydir,pdp->getOverlaydir()); - } - } else if (!strncmp(dinfo,"fatDrive ",9)) { - fatDrive *fdp = dynamic_cast(Drives[lcv]); - if (fdp) { - opts.bytesector=fdp->loadedDisk?fdp->loadedDisk->sector_size:fdp->opts.bytesector; - opts.cylsector=fdp->loadedDisk?fdp->loadedDisk->sectors:fdp->opts.cylsector; - opts.headscyl=fdp->loadedDisk?fdp->loadedDisk->heads:fdp->opts.headscyl; - opts.cylinders=fdp->loadedDisk?fdp->loadedDisk->cylinders:fdp->opts.cylinders; - opts.mounttype=fdp->opts.mounttype; - opts.mediaid=fdp->GetMediaByte(); - opts.CDROM_drive=fdp->el.CDROM_drive; - opts.cdrom_sector_offset=fdp->el.cdrom_sector_offset; - opts.floppy_emu_type=fdp->el.floppy_emu_type; - } - } - - WRITE_POD( &overlaydir, overlaydir); - WRITE_POD( &lalloc, lalloc); - WRITE_POD( &oalloc, oalloc); - WRITE_POD( &opts, opts); - Drives[lcv]->SaveState(stream); - } - - for( unsigned int lcv=0; lcvGetName() == NULL ) file_valid = 0xff; - else { - if( strcmp( Files[lcv]->GetName(), "NUL" ) == 0 ) file_valid = 0xfe;//earth 2140 needs this - if( strcmp( Files[lcv]->GetName(), "CON" ) == 0 ) file_valid = 0xfe; - if( strcmp( Files[lcv]->GetName(), "LPT1" ) == 0 ) file_valid = 0xfe; - if( strcmp( Files[lcv]->GetName(), "PRN" ) == 0 ) file_valid = 0xfe; - if( strcmp( Files[lcv]->GetName(), "AUX" ) == 0 ) file_valid = 0xfe; - if( strcmp( Files[lcv]->GetName(), "EMMXXXX0" ) == 0 ) file_valid = 0xfe;//raiden needs this - } - - // - reloc ptr - WRITE_POD( &file_valid, file_valid ); - // system files - if( file_valid == 0xff ) continue; - if( file_valid == 0xfe ) { - WRITE_POD( &Files[lcv]->refCtr, Files[lcv]->refCtr ); - continue; - } - - //********************************************** - //********************************************** - //********************************************** - - file_namelen = (uint8_t)strlen( Files[lcv]->name ); - file_name = (char *) alloca( file_namelen ); - strcpy( file_name, Files[lcv]->name ); - - file_drive = Files[lcv]->GetDrive(); - file_flags = Files[lcv]->flags; - - // - Drives->FileOpen vars (repeat copy) - WRITE_POD( &file_namelen, file_namelen ); - WRITE_POD_SIZE( file_name, file_namelen ); - - WRITE_POD( &file_drive, file_drive ); - WRITE_POD( &file_flags, file_flags ); - - Files[lcv]->SaveState(stream); - } - } else { - for( int i=2; iGetInfo()); - WRITE_POD( &dinfo, dinfo); - } - } - - for (int i=2; i(imageDiskList[d]); - strcpy(diskname, image!=NULL?"El Torito floppy drive":imageDiskList[d]->diskname.c_str()); - WRITE_POD( &diskname, diskname ); - if (image!=NULL) { - opts.CDROM_drive=image->CDROM_drive; - opts.cdrom_sector_offset=image->cdrom_sector_offset; - opts.floppy_emu_type=image->floppy_type; - opts.mounttype=1; - } else { - imageDiskMemory* idmem = dynamic_cast(imageDiskList[d]); - imageDiskVHD* idvhd = dynamic_cast(imageDiskList[d]); - if (idmem!=NULL) - opts.mounttype=2; - else if (idvhd!=NULL) - opts.mounttype=3; - else { - opts.bytesector=imageDiskList[d]->sector_size; - opts.cylsector=imageDiskList[d]->sectors; - opts.headscyl=imageDiskList[d]->heads; - opts.cylinders=imageDiskList[d]->cylinders; - opts.mounttype=0; - } - } - WRITE_POD( &opts, opts); - } -} - -void DOS_EnableDriveMenu(char drv); -void IDE_Auto(signed char &index,bool &slave); -bool AttachToBiosByLetter(imageDisk* image, const char drive); -bool AttachToBiosAndIdeByLetter(imageDisk* image, const char drive, const unsigned char ide_index, const bool ide_slave); -imageDiskMemory* CreateRamDrive(Bitu sizes[], const int reserved_cylinders, const bool forceFloppy, Program* obj); - -void unmount(int lcv) { - if (!Drives[lcv] || lcv>=DOS_DRIVES-1) return; - const isoDrive* cdrom = dynamic_cast(Drives[lcv]); - if (DriveManager::UnmountDrive(lcv) == 0) { - if (cdrom) IDE_CDROM_Detach(lcv); - Drives[lcv]=nullptr; - DOS_EnableDriveMenu('A'+lcv); - mem_writeb(Real2Phys(dos.tables.mediaid)+lcv*dos.tables.dpb_size,0); - } -} - -void POD_Load_DOS_Files( std::istream& stream ) -{ - char dinfo[256]; - std::vector clist; - clist.clear(); - uint8_t ZDRIVE_CUR = ZDRIVE_NUM; - READ_POD( &ZDRIVE_NUM, ZDRIVE_NUM); - if (!dos_kernel_disabled) { - if (ZDRIVE_CUR != ZDRIVE_NUM) { - Drives[ZDRIVE_NUM] = Drives[ZDRIVE_CUR]; - Drives[ZDRIVE_CUR] = nullptr; - } - // 1. Do drives first (directories -> files) - // 2. Then files next - - for( int i=2; iinfo, dinfo) && (!strncmp(dinfo,"local directory ",16) || !strncmp(dinfo,"CDRom ",6) || !strncmp(dinfo,"PhysFS directory ",17) || !strncmp(dinfo,"PhysFS CDRom ",13) || (!strncmp(dinfo,"isoDrive ",9) || !strncmp(dinfo,"fatDrive ",9)))) - unmount(lcv); - if( !Drives[lcv] ) { - std::vector options; - if (!strncmp(dinfo,"local directory ",16)) { - Drives[lcv]=new localDrive(dinfo+16,lalloc.bytes_sector,lalloc.sectors_cluster,lalloc.total_clusters,lalloc.free_clusters,lalloc.mediaid,options); - if (Drives[lcv]) { - DOS_EnableDriveMenu('A'+lcv); - mem_writeb(Real2Phys(dos.tables.mediaid)+lcv*dos.tables.dpb_size,lalloc.mediaid); - if (strlen(overlaydir)) { - uint8_t error = 0; - Drives[lcv]=new Overlay_Drive(dynamic_cast(Drives[lcv])->getBasedir(),overlaydir,oalloc.bytes_sector,oalloc.sectors_cluster,oalloc.total_clusters,oalloc.free_clusters,oalloc.mediaid,error,options); - } - } else - LOG_MSG("Error: Cannot restore drive from directory %s\n", dinfo+16); - } else if (!strncmp(dinfo,"CDRom ",6) || !strncmp(dinfo,"PhysFS CDRom ",13)) { - int num = -1; - int error = 0; - int id, major, minor; - DOSBox_CheckOS(id, major, minor); - if ((id==VER_PLATFORM_WIN32_NT) && (major>5)) - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); - else - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); - if (!strncmp(dinfo,"PhysFS CDRom ",13)) { - std::string str=std::string(dinfo+13); - std::size_t found=str.find(", "); - if (found!=std::string::npos) - str=str.substr(0,found); - Drives[lcv] = new physfscdromDrive('A'+lcv,(":"+str+"\\").c_str(),lalloc.bytes_sector,lalloc.sectors_cluster,lalloc.total_clusters,0,lalloc.mediaid,error,options); - } else - Drives[lcv] = new cdromDrive('A'+lcv,dinfo+6,lalloc.bytes_sector,lalloc.sectors_cluster,lalloc.total_clusters,lalloc.free_clusters,lalloc.mediaid,error,options); - if (Drives[lcv]) { - DOS_EnableDriveMenu('A'+lcv); - mem_writeb(Real2Phys(dos.tables.mediaid)+lcv*dos.tables.dpb_size,lalloc.mediaid); - } else - LOG_MSG("Error: Cannot restore drive from directory %s\n", dinfo+6); - } else if (!strncmp(dinfo,"PhysFS directory ",17)) { - int error = 0; - std::string str=std::string(dinfo+17); - std::size_t found=str.find(", "); - if (found!=std::string::npos) - str=str.substr(0,found); - Drives[lcv]=new physfsDrive('A'+lcv,(":"+str+"\\").c_str(),lalloc.bytes_sector,lalloc.sectors_cluster,lalloc.total_clusters,lalloc.free_clusters,lalloc.mediaid,error,options); - if (Drives[lcv]) { - if (strlen(overlaydir)) dynamic_cast(Drives[lcv])->setOverlaydir(overlaydir); - DOS_EnableDriveMenu('A'+lcv); - mem_writeb(Real2Phys(dos.tables.mediaid)+lcv*dos.tables.dpb_size,lalloc.mediaid); - } else - LOG_MSG("Error: Cannot restore drive from directory %s\n", dinfo+16); - } else if (!strncmp(dinfo,"isoDrive ",9) && *(dinfo+9)) { - MSCDEX_SetCDInterface(CDROM_USE_SDL, -1); - uint8_t mediaid = 0xF8; - int error = -1; - isoDrive* newDrive = new isoDrive('A'+lcv, dinfo+9, mediaid, error, options); - if (!error) { - Drives[lcv] = newDrive; - DriveManager::AppendDisk(lcv, newDrive); - DriveManager::InitializeDrive(lcv); - DOS_EnableDriveMenu('A'+lcv); - mem_writeb(Real2Phys(dos.tables.mediaid) + lcv*dos.tables.dpb_size, mediaid); - clist.push_back(lcv); - } - } else if (!strncmp(dinfo,"fatDrive ",9)) { - fatDrive* newDrive = NULL; - Bitu sizes[4] = { 0,0,0,0 }; - if (opts.mounttype==1) { - imageDisk * newImage = new imageDiskElToritoFloppy((unsigned char)opts.CDROM_drive, opts.cdrom_sector_offset, opts.floppy_emu_type); - if (newImage != NULL) { - newImage->Addref(); - newDrive = new fatDrive(newImage, options); - newImage->Release(); - } else - LOG_MSG("Error: Cannot restore drive from El Torito floppy image.\n"); - - } else if (opts.mounttype==2) { - imageDiskMemory* image = CreateRamDrive(sizes, 0, lcv < 2 && sizes[0] == 0, NULL); - if (image != NULL && image->Format() == 0x00) { - image->Addref(); - newDrive = new fatDrive(image, options); - image->Release(); - } - } else if (opts.mounttype==3 && *(dinfo+9)) { - imageDisk* vhdImage = NULL; - if (imageDiskVHD::Open(dinfo+9, false, &vhdImage)==imageDiskVHD::OPEN_SUCCESS) - newDrive = new fatDrive(vhdImage, options); - vhdImage = NULL; - } else if (!opts.mounttype && *(dinfo+9)) - newDrive = new fatDrive(dinfo+9, opts.bytesector, opts.cylsector, opts.headscyl, opts.cylinders, options); - if (newDrive && newDrive->created_successfully) { - Drives[lcv] = newDrive; - DriveManager::AppendDisk(lcv, newDrive); - DriveManager::InitializeDrive(lcv); - DOS_EnableDriveMenu('A'+lcv); - mem_writeb(Real2Phys(dos.tables.mediaid) + lcv*dos.tables.dpb_size, opts.mediaid); - } else if ((!opts.mounttype || opts.mounttype==3) && *(dinfo+9)) - LOG_MSG("Error: Cannot restore drive from image file %s\n", dinfo+9); - } - } - if( Drives[lcv] ) Drives[lcv]->LoadState(stream); - } - - //Alien Carnage - game creates and unlinks temp files - //Here are two situations - //1. Game already unlinked temp file, but information about file is still in Files[] and we saved it. In this case we must only pop old data from stream by loading. This is fixed. - //2. Game still did not unlink file, We saved this information. Then was game restarted and temp files were removed. Then we try load save state, but we don't have temp file. This is not fixed - DOS_File *dummy = NULL; - - for( unsigned int lcv=0; lcvrefCtr, Files[lcv]->refCtr ); - continue; - } - - // shutdown old file - if( Files[lcv] && Files[lcv]->GetName() != NULL ) { - // invalid file state - abort - if( strcmp( Files[lcv]->GetName(), "NUL" ) == 0 ) break; - if( strcmp( Files[lcv]->GetName(), "CON" ) == 0 ) break; - if( strcmp( Files[lcv]->GetName(), "LPT1" ) == 0 ) break; - if( strcmp( Files[lcv]->GetName(), "PRN" ) == 0 ) break; - if( strcmp( Files[lcv]->GetName(), "AUX" ) == 0 ) break; - if( strcmp( Files[lcv]->GetName(), "EMMXXXX0" ) == 0 ) break;//raiden needs this - - - if( Files[lcv]->IsOpen() ) Files[lcv]->Close(); - if (Files[lcv]->RemoveRef()<=0) { - delete Files[lcv]; - } - Files[lcv]=nullptr; - } - - // ignore NULL file - if( file_valid == 0xff ) continue; - - //********************************************** - //********************************************** - //********************************************** - - // - Drives->FileOpen vars (repeat copy) - - READ_POD( &file_namelen, file_namelen ); - file_name = (char *) alloca( file_namelen ); - READ_POD_SIZE( file_name, file_namelen ); - - READ_POD( &file_drive, file_drive ); - READ_POD( &file_flags, file_flags ); - - - // NOTE: Must open regardless to get 'new' DOS_File class - Drives[file_drive]->FileOpen( &Files[lcv], file_name, file_flags ); - - if( Files[lcv] ) { - Files[lcv]->LoadState(stream, false); - } else { - //Alien carnage ->pop data for invalid file from stream - if (dummy == NULL) { - dummy = new LocalFile(); - } - dummy->LoadState(stream, true); - }; - } - - if (dummy != NULL) { - delete dummy; - } - } else { - for( int i=2; iinfo, dinfo)) - unmount(lcv); - if (!Drives[lcv] && !strncmp(dinfo,"isoDrive ",9)) { - std::vector options; - MSCDEX_SetCDInterface(CDROM_USE_SDL, -1); - uint8_t mediaid = 0xF8; - int error = -1; - isoDrive* newDrive = new isoDrive('A'+lcv, dinfo+9, mediaid, error, options); - if (!error) { - Drives[lcv] = newDrive; - DriveManager::AppendDisk(lcv, newDrive); - DriveManager::InitializeDrive(lcv); - mem_writeb(Real2Phys(dos.tables.mediaid) + lcv*dos.tables.dpb_size, mediaid); - clist.push_back(lcv); - } - } - } - } - - for (int i=2; i 1) IDE_Hard_Disk_Detach(d); - imageDiskList[d]->Release(); - imageDiskList[d] = NULL; - imageDiskChange[d] = true; - } - if (i==MAX_DISK_IMAGES-1) - for (auto &it : clist) { - ide_slave = false; - ide_index = -1; - IDE_Auto(ide_index,ide_slave); - if (ide_index >= 0) IDE_CDROM_Attach(ide_index, ide_slave, it); - } - continue; - } - char diskname[256]; - READ_POD( &diskname, diskname ); - READ_POD( &opts, opts); - Bitu sizes[4] = { 0,0,0,0 }; - ide_slave = false; - ide_index = -1; - IDE_Auto(ide_index,ide_slave); - if( imageDiskList[d] && ((opts.mounttype==1 && dynamic_cast(imageDiskList[d])==NULL) || (opts.mounttype!=1 && strcasecmp(imageDiskList[d]->diskname.c_str(), diskname )))) { - if (d > 1) IDE_Hard_Disk_Detach(d); - imageDiskList[d]->Release(); - imageDiskList[d] = NULL; - imageDiskChange[d] = true; - } - if (imageDiskList[d]) - ; - else if (opts.mounttype==1) { - imageDisk * image = new imageDiskElToritoFloppy((unsigned char)opts.CDROM_drive, opts.cdrom_sector_offset, opts.floppy_emu_type); - if (image) AttachToBiosByLetter(image, 'A'+d); - else LOG_MSG("Warning: Cannot restore drive number from El Torito floppy image.\n"); - } else if (opts.mounttype==2) { - imageDiskMemory* image = CreateRamDrive(sizes, 0, d < 2 && sizes[0] == 0, NULL); - if (image != NULL && image->Format() == 0x00) AttachToBiosAndIdeByLetter(image, d, (unsigned char)ide_index, ide_slave); - } else if (opts.mounttype==3 && *diskname) { - imageDisk* image = NULL; - if (imageDiskVHD::Open(diskname, false, &image)==imageDiskVHD::OPEN_SUCCESS) - AttachToBiosAndIdeByLetter(image, 'A'+d, (unsigned char)ide_index, ide_slave); - else - LOG_MSG("Warning: Cannot restore drive number from image file %s\n", diskname); - image = NULL; - } else if (!opts.mounttype && *diskname) { - std::vector options; - fatDrive* newDrive = new fatDrive(diskname, opts.bytesector, opts.cylsector, opts.headscyl, opts.cylinders, options); - if (newDrive->created_successfully) { - imageDisk* image = newDrive->loadedDisk; - AttachToBiosAndIdeByLetter(image, 'A'+d, (unsigned char)ide_index, ide_slave); - } else - LOG_MSG("Warning: Cannot restore drive number from image file %s\n", diskname); - if (newDrive) delete newDrive; - } - if (i==MAX_DISK_IMAGES-1) - for (auto &it : clist) { - ide_slave = false; - ide_index = -1; - IDE_Auto(ide_index,ide_slave); - if (ide_index >= 0) IDE_CDROM_Attach(ide_index, ide_slave, it); - } - } -} + uint16_t towrite=*amount; + bool ret=Files[handle]->Write(data,&towrite); + *amount=towrite; + return ret; + } + + bool DOS_SeekFile(uint16_t entry,uint32_t * pos,uint32_t type,bool fcb) { + uint32_t handle = fcb?entry:RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsActiveResource(entry)) + return Network_SeekFile(entry,pos,type); + #endif + if (!Files[handle] || !Files[handle]->IsOpen()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + + if (log_fileio) { + LOG(LOG_FILES, LOG_DEBUG)("Seeking to %d bytes from position type (%d) in %s ", *pos, type, Files[handle]->name); + } + + return Files[handle]->Seek(pos,type); + } + + /* ert, 20100711: Locking extensions */ + bool DOS_LockFile(uint16_t entry,uint8_t mode,uint32_t pos,uint32_t size) { + uint32_t handle=RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + if (!Files[handle] || !Files[handle]->IsOpen()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + return Files[handle]->LockFile(mode,pos,size); + } + + bool DOS_CloseFile(uint16_t entry, bool fcb, uint8_t * refcnt) { + uint32_t handle = fcb?entry:RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsActiveResource(entry)) + return Network_CloseFile(entry); + #endif + if (!Files[handle]) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + if (Files[handle]->IsOpen()) { + if (log_fileio) { + LOG(LOG_FILES, LOG_NORMAL)("Closing file %s", Files[handle]->name); + } + Files[handle]->Close(); + } + + DOS_PSP psp(dos.psp()); + if (!fcb) psp.SetFileHandle(entry,0xff); + + Bits refs=Files[handle]->RemoveRef(); + if (refs<=0) { + delete Files[handle]; + Files[handle]=nullptr; + } + if (refcnt!=NULL) *refcnt=static_cast(refs+1); + return true; + } + + bool DOS_FlushFile(uint16_t entry) { + uint32_t handle=RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsActiveResource(entry)) + return Network_FlushFile(entry); + #endif + if (!Files[handle] || !Files[handle]->IsOpen()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + + LOG(LOG_DOSMISC,LOG_DEBUG)("FFlush used."); + + Files[handle]->Flush(); + return true; + } + + + bool DOS_CreateFile(char const * name,uint16_t attributes,uint16_t * entry,bool fcb) { + // Creation of a device is the same as opening it + // Tc201 installer + if (DOS_FindDevice(name) != DOS_DEVICES) + return DOS_OpenFile(name, OPEN_READ, entry, fcb); + + LOG(LOG_FILES,LOG_NORMAL)("file create attributes %X file %s",attributes,name); + char fullname[DOS_PATHLENGTH];uint8_t drive; + DOS_PSP psp(dos.psp()); + if (!DOS_MakeName(name,fullname,&drive)) return false; + while (strlen(fullname)&&(*(fullname+strlen(fullname)-1)=='.'||*(fullname+strlen(fullname)-1)==' ')) *(fullname+strlen(fullname)-1)=0; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsNetworkResource(name)) + return Network_CreateFile(name,attributes,entry); + #endif + + /* Check for a free file handle */ + uint8_t handle=(uint8_t)DOS_FILES;uint8_t i; + for (i=0;iFileCreate(&Files[handle],fullname,attributes); + if (foundit) { + if (Files[handle]) { + Files[handle]->SetDrive(drive); + Files[handle]->AddRef(); + Files[handle]->drive = drive; + } + if (!fcb) psp.SetFileHandle(*entry,handle); + if (Files[handle]) Drives[drive]->EmptyCache(); + return true; + } else { + if(dos.errorcode==DOSERR_ACCESS_DENIED||dos.errorcode==DOSERR_WRITE_PROTECTED) return false; + if(!PathExists(name)) DOS_SetError(DOSERR_PATH_NOT_FOUND); + else DOS_SetError(DOSERR_FILE_NOT_FOUND); + return false; + } + } + + bool DOS_OpenFile(char const * name,uint8_t flags,uint16_t * entry,bool fcb) { + /* First check for devices */ + if (flags>2) LOG(LOG_FILES,LOG_NORMAL)("Special file open command %X file %s",flags,name); // FIXME: Why? Is there something about special opens DOSBox doesn't handle properly? + else LOG(LOG_FILES,LOG_NORMAL)("file open command %X file %s",flags,name); + + DOS_PSP psp(dos.psp()); + uint16_t attr = 0; + uint8_t devnum = DOS_FindDevice(name); + bool device = (devnum != DOS_DEVICES); + if(!device && DOS_GetFileAttr(name,&attr)) { + //DON'T ALLOW directories to be opened. (skip test if file is device). + if((attr & DOS_ATTR_DIRECTORY) || (attr & DOS_ATTR_VOLUME)){ + DOS_SetError(DOSERR_ACCESS_DENIED); + return false; + } + } + + char fullname[DOS_PATHLENGTH];uint8_t drive;uint8_t i; + /* First check if the name is correct */ + if (!DOS_MakeName(name,fullname,&drive)) return false; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsNetworkResource(name)) + return Network_OpenFile(name,flags,entry); + #endif + uint8_t handle=255; + /* Check for a free file handle */ + for (i=0;iGetInformation() & EXT_DEVICE_BIT) + Files[handle] = new DOS_ExtDevice(*(DOS_ExtDevice*)Devices[devnum]); + else + Files[handle]=new DOS_Device(*Devices[devnum]); + } else { + uint16_t olderror=dos.errorcode; + dos.errorcode=0; + exists=Drives[drive]->FileOpen(&Files[handle],fullname,flags) || Drives[drive]->FileOpen(&Files[handle],upcase(fullname),flags); + if (exists) Files[handle]->SetDrive(drive); + else if (dos.errorcode==DOSERR_ACCESS_CODE_INVALID) return false; + dos.errorcode=olderror; + } + if (exists || device ) { + Files[handle]->AddRef(); + psp.SetFileHandle(*entry,handle); + Files[handle]->drive = drive; + return true; + } else { + //Test if file exists, but opened in read-write mode (and writeprotected) + if((((flags&3) != OPEN_READ) || (enable_share_exe && !strncmp(Drives[drive]->GetInfo(),"local directory ",16))) && Drives[drive]->FileExists(fullname)) + DOS_SetError(DOSERR_ACCESS_DENIED); + else { + if(!PathExists(name)) DOS_SetError(DOSERR_PATH_NOT_FOUND); + else DOS_SetError(DOSERR_FILE_NOT_FOUND); + } + return false; + } + } + + bool DOS_OpenFileExtended(char const * name, uint16_t flags, uint16_t createAttr, uint16_t action, uint16_t *entry, uint16_t* status) { + // FIXME: Not yet supported : Bit 13 of flags (int 0x24 on critical error) + uint16_t result = 0; + if (action==0) { + // always fail setting + DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); + return false; + } else { + if (((action & 0x0f)>2) || ((action & 0xf0)>0x10)) { + // invalid action parameter + DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); + return false; + } + } + if (DOS_OpenFile(name, (uint8_t)(flags&0xff), entry)) { + // File already exists + switch (action & 0x0f) { + case 0x00: // failed + DOS_SetError(DOSERR_FILE_ALREADY_EXISTS); + return false; + case 0x01: // file open (already done) + result = 1; + break; + case 0x02: // replace + DOS_CloseFile(*entry); + if (!DOS_CreateFile(name, createAttr, entry)) return false; + result = 3; + break; + default: + DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); + E_Exit("DOS: OpenFileExtended: Unknown action."); + break; + } + } else { + // File doesn't exist + if ((action & 0xf0)==0) { + // uses error code from failed open + return false; + } + // Create File + if (!DOS_CreateFile(name, createAttr, entry)) { + // uses error code from failed create + return false; + } + result = 2; + } + // success + *status = result; + return true; + } + + bool DOS_UnlinkFile(char const * const name) { + char fullname[DOS_PATHLENGTH];uint8_t drive; + // An existing device returns an access denied error + if (log_fileio) { + LOG(LOG_FILES, LOG_NORMAL)("Deleting file %s", name); + } + if (DOS_FindDevice(name) != DOS_DEVICES) { + DOS_SetError(DOSERR_ACCESS_DENIED); + return false; + } + if (!DOS_MakeName(name,fullname,&drive)) return false; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(name)) return Network_UnlinkFile(name); + #endif + if(Drives[drive]->FileUnlink(fullname)){ + return true; + } else if(uselfn&&!force_sfn&&(strchr(fullname, '*')||strchr(fullname, '?'))) { // Wildcard delete as used by MS-DOS 7+ "DEL *.*" in LFN mode + char dir[DOS_PATHLENGTH], temp[DOS_PATHLENGTH], fname[DOS_PATHLENGTH], spath[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH]; + if (!DOS_Canonicalize(name,fullname)||!strlen(fullname)) { + DOS_SetError(DOSERR_PATH_NOT_FOUND); + return false; + } + if (!strchr(name,'\"')||!DOS_GetSFNPath(("\""+std::string(fullname)+"\"").c_str(), fname, false)) + strcpy(fname, fullname); + char * find_last=strrchr_dbcs(fname,'\\'); + if (!find_last) { + dir[0]=0; + strcpy(pattern, fname); + } else { + *find_last=0; + strcpy(dir,fname); + strcpy(pattern, find_last+1); + } + int k=0; + for (int i=0;i<(int)strlen(pattern);i++) + if (pattern[i]!='\"') + pattern[k++]=pattern[i]; + pattern[k]=0; + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + std::vector cdirs; + cdirs.clear(); + strcpy(spath, dir); + if (!DOS_GetSFNPath(dir, spath, false)) strcpy(spath, dir); + if (!strlen(spath)||spath[strlen(spath)-1]!='\\') strcat(spath, "\\"); + std::string pfull=std::string(spath)+std::string(pattern); + int fbak=lfn_filefind_handle; + lfn_filefind_handle=LFN_FILEFIND_INTERNAL; + bool ret=DOS_FindFirst(((pfull.length()&&pfull[0]=='"'?"":"\"")+pfull+(pfull.length()&&pfull[pfull.length()-1]=='"'?"":"\"")).c_str(),0xffu & ~DOS_ATTR_VOLUME & ~DOS_ATTR_DIRECTORY); + if (ret) do { + char find_name[DOS_NAMELENGTH_ASCII],lfind_name[LFN_NAMELENGTH]; + uint16_t find_date,find_time;uint32_t find_size,find_hsize;uint8_t find_attr; + dta.GetResult(find_name,lfind_name,find_size,find_hsize,find_date,find_time,find_attr); + if (!(find_attr & DOS_ATTR_DIRECTORY)&&strlen(find_name)&&!strchr(find_name, '*')&&!strchr(find_name, '?')) { + strcpy(temp, dir); + if (strlen(temp)&&temp[strlen(temp)-1]!='\\') strcat(temp, "\\"); + strcat(temp, find_name); + cdirs.emplace_back(std::string(temp)); + } + } while ((ret=DOS_FindNext())==true); + lfn_filefind_handle=fbak; + bool removed=false; + while (!cdirs.empty()) { + if (DOS_UnlinkFile(cdirs.begin()->c_str())) + removed=true; + cdirs.erase(cdirs.begin()); + } + dos.dta(save_dta); + if (removed) + return true; + else { + if (dos.errorcode!=DOSERR_ACCESS_DENIED&&dos.errorcode!=DOSERR_WRITE_PROTECTED) DOS_SetError(DOSERR_FILE_NOT_FOUND); + return false; + } + } else { + if (dos.errorcode!=DOSERR_ACCESS_DENIED&&dos.errorcode!=DOSERR_WRITE_PROTECTED) DOS_SetError(DOSERR_FILE_NOT_FOUND); + return false; + } + } + + bool DOS_GetFileAttr(char const * const name,uint16_t * attr) { + char fullname[DOS_PATHLENGTH];uint8_t drive; + if (!DOS_MakeName(name,fullname,&drive)) return false; + #if defined (WIN32) + if (!control->SecureMode()&&dos_clipboard_device_access) { + const char* find_last; + find_last=strrchr_dbcs(fullname,'\\'); + if (find_last==NULL) find_last=fullname; + else find_last++; + if (!strcasecmp(find_last, *dos_clipboard_device_name?dos_clipboard_device_name:"CLIP$")) + return true; + } + #if !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(name)) { + if (Network_GetFileAttr(name, attr)) { + return true; + } else { + DOS_SetError(DOSERR_FILE_NOT_FOUND); + return false; + } + } + #endif + #endif + + if (Drives[drive]->GetFileAttr(fullname,attr)) { + return true; + } else { + DOS_SetError(DOSERR_FILE_NOT_FOUND); + return false; + } + } + + unsigned long DOS_GetCompressedFileSize(char const* const name) + { + char fullname[DOS_PATHLENGTH]; + uint8_t drive; + if (!DOS_MakeName(name, fullname, &drive)) + return false; + return Drives[drive]->GetCompressedSize(fullname); + } + + #if defined (WIN32) + HANDLE DOS_CreateOpenFile(char const* const name) + { + char fullname[DOS_PATHLENGTH]; + uint8_t drive; + if (!DOS_MakeName(name, fullname, &drive)) + return INVALID_HANDLE_VALUE; + return Drives[drive]->CreateOpenFile(fullname); + } + #endif + + bool DOS_SetFileAttr(char const * const name,uint16_t attr) + // returns false when using on cdrom (stonekeep) + { + char fullname[DOS_PATHLENGTH];uint8_t drive; + if (!DOS_MakeName(name,fullname,&drive)) return false; + if (strncmp(Drives[drive]->GetInfo(),"CDRom ",6)==0 || strncmp(Drives[drive]->GetInfo(),"isoDrive ",9)==0) { + DOS_SetError(DOSERR_ACCESS_DENIED); + return false; + } + + /* This function must prevent changing a file into a directory, volume label into a file, etc. + * Also Windows 95 setup likes to create WINBOOT.INI as a file and then chattr it into a directory for some stupid reason. */ + uint16_t old_attr; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if ((Network_IsNetworkResource(name)&&!Network_GetFileAttr(name,&old_attr))||(!Network_IsNetworkResource(name)&&!Drives[drive]->GetFileAttr(fullname,&old_attr))) + #else + if (!Drives[drive]->GetFileAttr(fullname,&old_attr)) + #endif + { + DOS_SetError(DOSERR_FILE_NOT_FOUND); + return false; + } + + if ((old_attr ^ attr) & DOS_ATTR_VOLUME) { /* change in volume label attribute */ + LOG(LOG_DOSMISC,LOG_WARN)("Attempted to change volume label attribute of '%s' with SetFileAttr",name); + return false; + } + + if ((old_attr ^ attr) & DOS_ATTR_DIRECTORY) /* change in directory attribute (ex: Windows 95 SETUP.EXE vs WINBOOT.INI) */ + LOG(LOG_DOSMISC,LOG_WARN)("Attempted to change directory attribute of '%s' with SetFileAttr",name); + + /* define what cannot be changed */ + const uint16_t attr_mask = (DOS_ATTR_VOLUME|DOS_ATTR_DIRECTORY); + + attr = (attr & ~attr_mask) | (old_attr & attr_mask); + + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(name)) return Network_SetFileAttr(name,attr); + #endif + return Drives[drive]->SetFileAttr(fullname,attr); + } + + bool DOS_Canonicalize(char const * const name,char * const big) { + //TODO Add Better support for devices and shit but will it be needed i doubt it :) + uint8_t drive; + char fullname[DOS_PATHLENGTH]; + if (!DOS_MakeName(name,fullname,&drive)) return false; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(name)) { + strcpy(&big[0], name); + return true; + } + #endif + big[0]=drive+'A'; + big[1]=':'; + big[2]='\\'; + strcpy(&big[3],fullname); + return true; + } + + #ifdef _MSC_VER + # define MIN(a,b) ((a) < (b) ? (a) : (b)) + # define MAX(a,b) ((a) > (b) ? (a) : (b)) + #else + # define MIN(a,b) std::min(a,b) + # define MAX(a,b) std::max(a,b) + #endif + + /* Common routine to take larger allocation information (such as FAT32) and convert it to values + * that are suitable for use with older DOS programs that pre-date FAT32 and partitions 2GB or larger. + * This is what Windows 95 OSR2 and higher do with FAT32 partitions anyway, as documented by Microsoft. */ + bool DOS_CommonFAT32FAT16DiskSpaceConv( + uint16_t * bytes,uint8_t * sectors,uint16_t * clusters,uint16_t * free, + const uint32_t bytes32,const uint32_t sectors32,const uint32_t clusters32,const uint32_t free32) { + uint32_t cdiv = 1; + + if (sectors32 > 128 || bytes32 > 0x8000) + return false; + + /* This function is for the old API. It is necessary to adjust the values so that they never overflow + * 16-bit unsigned integers and never multiply out to a number greater than just under 2GB. Because + * old DOS programs use 32-bit signed integers for disk total/free and FAT12/FAT16 filesystem limitations. */ + /* NTS: Make sure (bytes per sector * sectors per cluster) is less than 0x10000, or else FORMAT.COM will + * crash with divide by zero or produce incorrect results when run with "FORMAT /S" */ + while ((clusters32 > 0xFFFFu || free32 > 0xFFFFu) && (sectors32 * cdiv) <= 64u && (bytes32 * sectors32 * cdiv) < 0x8000/*Needed for FORMAT.COM*/) + cdiv *= 2u; + + /* The old API must never report more than just under 2GB for total and free */ + const uint32_t clust2gb = (uint32_t)0x7FFF8000ul / (uint32_t)bytes32 / (sectors32 * cdiv); + + *bytes = bytes32; + *sectors = sectors32 * cdiv; + *clusters = (uint16_t)MIN(MIN(clusters32 / cdiv,clust2gb),0xFFFFu); + *free = (uint16_t)MIN(MIN(free32 / cdiv,clust2gb),0xFFFFu); + return true; + } + + bool DOS_GetFreeDiskSpace(uint8_t drive,uint16_t * bytes,uint8_t * sectors,uint16_t * clusters,uint16_t * free) { + if (drive==0) drive=DOS_GetDefaultDrive(); + else drive--; + if ((drive>=DOS_DRIVES) || (!Drives[drive])) { + DOS_SetError(DOSERR_INVALID_DRIVE); + return false; + } + + { + uint32_t bytes32,sectors32,clusters32,free32; + if ((dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10)) && + Drives[drive]->AllocationInfo32(&bytes32,§ors32,&clusters32,&free32) && + DOS_CommonFAT32FAT16DiskSpaceConv(bytes,sectors,clusters,free,bytes32,sectors32,clusters32,free32)) + return true; + } + + if (Drives[drive]->AllocationInfo(bytes,sectors,clusters,free)) + return true; + + return false; + } + + bool DOS_GetFreeDiskSpace32(uint8_t drive,uint32_t * bytes,uint32_t * sectors,uint32_t * clusters,uint32_t * free) { + if (drive==0) drive=DOS_GetDefaultDrive(); + else drive--; + if ((drive>=DOS_DRIVES) || (!Drives[drive])) { + DOS_SetError(DOSERR_INVALID_DRIVE); + return false; + } + + if ((dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10)) && Drives[drive]->AllocationInfo32(bytes,sectors,clusters,free)) + return true; + + { + uint8_t sectors8; + uint16_t bytes16,clusters16,free16; + if (Drives[drive]->AllocationInfo(&bytes16,§ors8,&clusters16,&free16)) { + *free = free16; + *bytes = bytes16; + *sectors = sectors8; + *clusters = clusters16; + return true; + } + } + + return false; + } + + bool DOS_DuplicateEntry(uint16_t entry,uint16_t * newentry) { + // Don't duplicate console handles + /* if (entry<=STDPRN) { + *newentry = entry; + return true; + }; + */ + uint8_t handle=RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + if (!Files[handle] || !Files[handle]->IsOpen()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + DOS_PSP psp(dos.psp()); + *newentry = psp.FindFreeFileEntry(); + if (*newentry==0xff) { + DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); + return false; + } + Files[handle]->AddRef(); + psp.SetFileHandle(*newentry,handle); + return true; + } + + bool DOS_ForceDuplicateEntry(uint16_t entry,uint16_t newentry) { + if(entry == newentry) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + uint8_t orig = RealHandle(entry); + if (orig >= DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + if (!Files[orig] || !Files[orig]->IsOpen()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + uint8_t newone = RealHandle(newentry); + if (newone < DOS_FILES && Files[newone]) { + DOS_CloseFile(newentry); + } + DOS_PSP psp(dos.psp()); + Files[orig]->AddRef(); + psp.SetFileHandle(newentry,orig); + return true; + } + + void initRand() { + #ifdef WIN32 + srand(GetTickCount()); + #else + struct timespec ts; + unsigned theTick = 0U; + clock_gettime( CLOCK_REALTIME, &ts ); + theTick = ts.tv_nsec / 1000000; + theTick += ts.tv_sec * 1000; + srand(theTick); + #endif + } + + bool DOS_CreateTempFile(char * const name,uint16_t * entry) { + size_t namelen=strlen(name); + char * tempname=name+namelen; + if (namelen==0) { + // temp file created in root directory + tempname[0]='\\'; + tempname++; + } else { + if (!check_last_split_char(name, namelen, '\\') && (name[namelen-1]!='/')) { + tempname[0]='\\'; + tempname++; + } + } + uint16_t olderror=dos.errorcode; + dos.errorcode=0; + /* add random crap to the end of the name and try to open */ + initRand(); + bool cont; + do { + cont=false; + uint32_t i; + for (i=0;i<8;i++) { + tempname[i]=(rand()%26)+'A'; + } + tempname[8]=0; + //if (DOS_FileExists(name)) {cont=true;continue;} // FIXME: Check name uniqueness + } while (cont || DOS_FileExists(name)); + DOS_CreateFile(name,0,entry); + if (dos.errorcode) return false; + dos.errorcode=olderror; + return true; + } + + char DOS_ToUpper(char c) { + unsigned char uc = *reinterpret_cast(&c); + if (uc > 0x60 && uc < 0x7B) uc -= 0x20; + else if (uc > 0x7F && uc < 0xA5) { + const unsigned char t[0x25] = { + 0x00, 0x9a, 0x45, 0x41, 0x8E, 0x41, 0x8F, 0x80, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x00, 0x00, + 0x00, 0x92, 0x00, 0x4F, 0x99, 0x4F, 0x55, 0x55, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x41, 0x49, 0x4F, 0x55, 0xA5}; + if (t[uc - 0x80]) uc = t[uc-0x80]; + } + char sc = *reinterpret_cast(&uc); + return sc; + } + + #define FCB_SEP ":;,=+" + #define ILLEGAL ":.;,=+ \t/\"[]<>|" + + static bool isvalid(const char in){ + const char ill[]=ILLEGAL; + return (uint8_t(in)>0x1F) && (!strchr(ill,in)); + } + + #define PARSE_SEP_STOP 0x01 + #define PARSE_DFLT_DRIVE 0x02 + #define PARSE_BLNK_FNAME 0x04 + #define PARSE_BLNK_FEXT 0x08 + + #define PARSE_RET_NOWILD 0 + #define PARSE_RET_WILD 1 + #define PARSE_RET_BADDRIVE 0xff + + uint8_t FCB_Parsename(uint16_t seg,uint16_t offset,uint8_t parser ,char *string, uint8_t *change) { + const char* string_begin = string; + uint8_t ret=0; + if (!(parser & PARSE_DFLT_DRIVE)) { + // default drive forced, this intentionally invalidates an extended FCB + mem_writeb(PhysMake(seg,offset),0); + } + DOS_FCB fcb(seg,offset,false); // always a non-extended FCB + bool hasdrive,hasname,hasext,finished; + hasdrive=hasname=hasext=finished=false; + Bitu index=0; + uint8_t fill=' '; + /* First get the old data from the fcb */ + #ifdef _MSC_VER + #pragma pack (1) + #endif + union { + struct { + char drive[2]; + char name[9]; + char ext[4]; + } GCC_ATTRIBUTE (packed) part; + char full[DOS_FCBNAME]; + } fcb_name; + #ifdef _MSC_VER + #pragma pack() + #endif + /* Get the old information from the previous fcb */ + fcb.GetName(fcb_name.full); + fcb_name.part.drive[0]-='A'-1;fcb_name.part.drive[1]=0; + fcb_name.part.name[8]=0;fcb_name.part.ext[3]=0; + /* strip leading spaces */ + while((*string==' ')||(*string=='\t')) string++; + + /* Strip of the leading separator */ + if((parser & PARSE_SEP_STOP) && *string) { + char sep[] = FCB_SEP;char a[2]; + a[0] = *string;a[1] = '\0'; + if (strcspn(a,sep) == 0) string++; + } + + /* Skip following spaces as well */ + while((*string==' ')||(*string=='\t')) string++; + + /* Check for a drive */ + if (string[1]==':') { + unsigned char d = *reinterpret_cast(&string[0]); + if (!isvalid(ascii_toupper(d))) {string += 2; goto savefcb;} //TODO check (for ret value) + fcb_name.part.drive[0]=0; + hasdrive=true; + if (isalpha(d) && Drives[ascii_toupper(d)-'A']) { //Floppies under dos always exist, but don't bother with that at this level + ; //THIS* was here + } else ret=0xff; + fcb_name.part.drive[0]=DOS_ToUpper(string[0])-'A'+1; //Always do THIS* and continue parsing, just return the right code + string+=2; + } + + /* Check for extension only file names */ + if (string[0] == '.') {string++;goto checkext;} + + /* do nothing if not a valid name */ + if(!isvalid(string[0])) goto savefcb; + + hasname=true;finished=false;fill=' ';index=0; + /* Copy the name */ + while (true) { + unsigned char nc = *reinterpret_cast(&string[0]); + if ((IS_PC98_ARCH && shiftjis_lead_byte(nc)) || (isDBCSCP() && isKanji1(nc))) { + /* Shift-JIS is NOT ASCII and SHOULD NOT be converted to uppercase like ASCII */ + fcb_name.part.name[index]=(char)nc; + string++; + index++; + if (index >= 8) break; + + /* should be trailing byte of Shift-JIS */ + if (nc < 32 || nc >= 127) continue; + + fcb_name.part.name[index]=(char)nc; + } + else + { + char ncs = (char)ascii_toupper(nc); //Should use DOS_ToUpper, but then more calls need to be changed. + if (ncs == '*') { //Handle * + fill = '?'; + ncs = '?'; + } + if (ncs == '?' && !ret && index < 8) ret = 1; //Don't override bad drive + if (!isvalid(ncs)) { //Fill up the name. + while(index < 8) + fcb_name.part.name[index++] = (char)fill; + break; + } + if (index < 8) { + fcb_name.part.name[index++] = (char)((fill == '?')?fill:ncs); + } + } + string++; + } + if (!(string[0]=='.')) goto savefcb; + string++; + checkext: + /* Copy the extension */ + hasext=true;finished=false;fill=' ';index=0; + while (true) { + unsigned char nc = *reinterpret_cast(&string[0]); + if ((IS_PC98_ARCH && shiftjis_lead_byte(nc)) || (isDBCSCP() && isKanji1(nc))) { + /* DBCS is NOT ASCII and SHOULD NOT be converted to uppercase like ASCII */ + fcb_name.part.ext[index]=(char)nc; + string++; + index++; + if (index >= 3) break; + + /* should be trailing byte of DBCS character */ + if (nc < 32u || nc >= 127u) continue; + + fcb_name.part.ext[index]=(char)nc; + } + else + { + char ncs = (char)ascii_toupper(nc); + if (ncs == '*') { //Handle * + fill = '?'; + ncs = '?'; + } + if (ncs == '?' && !ret && index < 3) ret = 1; + if (!isvalid(ncs)) { //Fill up the name. + while(index < 3) + fcb_name.part.ext[index++] = (char)fill; + break; + } + if (index < 3) { + fcb_name.part.ext[index++] = (char)((fill=='?')?fill:ncs); + } + } + string++; + } + savefcb: + if (!hasdrive && !(parser & PARSE_DFLT_DRIVE)) fcb_name.part.drive[0] = 0; + if (!hasname && !(parser & PARSE_BLNK_FNAME)) strcpy(fcb_name.part.name," "); + if (!hasext && !(parser & PARSE_BLNK_FEXT)) strcpy(fcb_name.part.ext," "); + fcb.SetName((unsigned char)fcb_name.part.drive[0],fcb_name.part.name,fcb_name.part.ext); + fcb.ClearBlockRecsize(); //Undocumented bonus work. + *change=(uint8_t)(string-string_begin); + return ret; + } + + static void DTAExtendNameVolumeLabel(const char* const name, char* const filename, char* const ext) { + size_t i,s; + + i=0; + s=0; + while (i < 8 && name[s] != 0) filename[i++] = name[s++]; + while (i < 8) filename[i++] = ' '; + + i=0; + while (i < 3 && name[s] != 0) ext[i++] = name[s++]; + while (i < 3) ext[i++] = ' '; + } + + void DTAExtendName(char * const name,char * const filename,char * const ext) { + char * find=strchr(name,'.'); + if (find && find!=name) { + strcpy(ext,find+1); + *find=0; + } else ext[0]=0; + strcpy(filename,name); + size_t i; + for (i=strlen(name);i<8;i++) filename[i]=' '; + filename[8]=0; + for (i=strlen(ext);i<3;i++) ext[i]=' '; + ext[3]=0; + } + + static void SaveFindResult(DOS_FCB & find_fcb) { + DOS_DTA find_dta(dos.tables.tempdta); + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr;uint8_t drive; + char file_name[9];char ext[4]; + find_dta.GetResult(name,lname,size,hsize,date,time,attr); + drive=find_fcb.GetDrive()+1; + uint8_t find_attr = DOS_ATTR_ARCHIVE; + find_fcb.GetAttr(find_attr); /* Gets search attributes if extended */ + /* Create a correct file and extension */ + if (attr & DOS_ATTR_VOLUME) + DTAExtendNameVolumeLabel(name,file_name,ext); + else + DTAExtendName(name,file_name,ext); + + DOS_FCB fcb(RealSeg(dos.dta()),RealOff(dos.dta()));//TODO + fcb.Create(find_fcb.Extended()); + fcb.SetName(drive,file_name,ext); + fcb.SetAttr(find_attr); /* Only adds attribute if fcb is extended */ + fcb.SetResult(size,date,time,attr); + } + + bool DOS_FCBCreate(uint16_t seg,uint16_t offset) { + DOS_FCB fcb(seg,offset); + char shortname[DOS_FCBNAME];uint16_t handle; + uint8_t attr = DOS_ATTR_ARCHIVE; + fcb.GetAttr(attr); + if (!attr) attr = DOS_ATTR_ARCHIVE; //Better safe than sorry + + if (attr & DOS_ATTR_VOLUME) { + fcb.GetVolumeName(shortname); + return Drives[fcb.GetDrive()]->FileCreate(NULL,shortname,attr); + } + + fcb.GetName(shortname); + if (!DOS_CreateFile(shortname,attr,&handle,true)) return false; + fcb.FileOpen((uint8_t)handle); + return true; + } + + bool DOS_FCBOpen(uint16_t seg,uint16_t offset) { + DOS_FCB fcb(seg,offset); + char shortname[DOS_FCBNAME];uint16_t handle; + fcb.GetName(shortname); + + /* Search for file if name has wildcards */ + if (strpbrk(shortname,"*?")) { + LOG(LOG_FCB,LOG_WARN)("Wildcards in filename"); + if (!DOS_FCBFindFirst(seg,offset)) return false; + DOS_DTA find_dta(dos.tables.tempdta); + DOS_FCB find_fcb(RealSeg(dos.tables.tempdta),RealOff(dos.tables.tempdta)); + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH],file_name[9],ext[4]; + uint32_t size,hsize;uint16_t date,time;uint8_t attr; + find_dta.GetResult(name,lname,size,hsize,date,time,attr); + DTAExtendName(name,file_name,ext); + find_fcb.SetName(fcb.GetDrive()+1,file_name,ext); + find_fcb.GetName(shortname); + } + + /* First check if the name is correct */ + uint8_t drive; + char fullname[DOS_PATHLENGTH]; + if (!DOS_MakeName(shortname,fullname,&drive)) return false; + + /* Check, if file is already opened */ + for (uint8_t i = 0;i < DOS_FILES;i++) { + if (Files[i] && Files[i]->IsOpen() && Files[i]->IsName(fullname)) { + Files[i]->AddRef(); + fcb.FileOpen(i); + return true; + } + } + + if (!DOS_OpenFile(shortname,OPEN_READWRITE,&handle,true)) return false; + fcb.FileOpen((uint8_t)handle); + return true; + } + + bool DOS_FCBClose(uint16_t seg,uint16_t offset) { + DOS_FCB fcb(seg,offset); + if(!fcb.Valid()) return false; + uint8_t fhandle; + fcb.FileClose(fhandle); + DOS_CloseFile(fhandle,true); + return true; + } + + bool DOS_FCBFindFirst(uint16_t seg,uint16_t offset) { + DOS_FCB fcb(seg,offset); + RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta); + char name[DOS_FCBNAME];fcb.GetName(name); + uint8_t attr = DOS_ATTR_ARCHIVE; + fcb.GetAttr(attr); /* Gets search attributes if extended */ + bool ret=DOS_FindFirst(name,attr,true); + dos.dta(old_dta); + if (ret) SaveFindResult(fcb); + return ret; + } + + bool DOS_FCBFindNext(uint16_t seg,uint16_t offset) { + DOS_FCB fcb(seg,offset); + RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta); + bool ret=DOS_FindNext(); + dos.dta(old_dta); + if (ret) SaveFindResult(fcb); + return ret; + } + + uint8_t DOS_FCBRead(uint16_t seg,uint16_t offset,uint16_t recno) { + DOS_FCB fcb(seg,offset); + uint8_t fhandle,cur_rec;uint16_t cur_block,rec_size; + fcb.GetSeqData(fhandle,rec_size); + if (fhandle==0xff && rec_size!=0) { + if (!DOS_FCBOpen(seg,offset)) return FCB_READ_NODATA; + LOG(LOG_FCB,LOG_WARN)("Reopened closed FCB"); + fcb.GetSeqData(fhandle,rec_size); + } + if (rec_size == 0) { + rec_size = 128; + fcb.SetSeqData(fhandle,rec_size); + } + fcb.GetRecord(cur_block,cur_rec); + uint32_t pos=((cur_block*128u)+cur_rec)*rec_size; + if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_READ_NODATA; + uint16_t toread=rec_size; + if (!DOS_ReadFile(fhandle,dos_copybuf,&toread,true)) return FCB_READ_NODATA; + if (toread==0) return FCB_READ_NODATA; + if (toread < rec_size) { //Zero pad copybuffer to rec_size + Bitu i = toread; + while(i < rec_size) dos_copybuf[i++] = 0; + } + MEM_BlockWrite(Real2Phys(dos.dta())+(PhysPt)(recno*rec_size),dos_copybuf,rec_size); + if (++cur_rec>127u) { cur_block++;cur_rec=0; } + fcb.SetRecord(cur_block,cur_rec); + if (toread==rec_size) return FCB_SUCCESS; + return FCB_READ_PARTIAL; + } + + uint8_t DOS_FCBWrite(uint16_t seg,uint16_t offset,uint16_t recno) { + DOS_FCB fcb(seg,offset); + uint8_t fhandle,cur_rec;uint16_t cur_block,rec_size; + fcb.GetSeqData(fhandle,rec_size); + if (fhandle==0xffu && rec_size!=0u) { + if (!DOS_FCBOpen(seg,offset)) return FCB_READ_NODATA; + LOG(LOG_FCB,LOG_WARN)("Reopened closed FCB"); + fcb.GetSeqData(fhandle,rec_size); + } + if (rec_size == 0) { + rec_size = 128; + fcb.SetSeqData(fhandle,rec_size); + } + fcb.GetRecord(cur_block,cur_rec); + uint32_t pos=((cur_block*128u)+cur_rec)*rec_size; + if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_ERR_WRITE; + MEM_BlockRead(Real2Phys(dos.dta())+(PhysPt)(recno*rec_size),dos_copybuf,rec_size); + uint16_t towrite=rec_size; + if (!DOS_WriteFile(fhandle,dos_copybuf,&towrite,true)) return FCB_ERR_WRITE; + uint32_t size;uint16_t date,time; + fcb.GetSizeDateTime(size,date,time); + if (pos+towrite>size) size=pos+towrite; + //time doesn't keep track of endofday + date = DOS_PackDate(dos.date.year,dos.date.month,dos.date.day); + uint32_t ticks = mem_readd(BIOS_TIMER); + uint32_t seconds = (ticks*10u)/182u; + uint16_t hour = (uint16_t)(seconds/3600u); + uint16_t min = (uint16_t)((seconds % 3600u)/60u); + uint16_t sec = (uint16_t)(seconds % 60u); + time = DOS_PackTime(hour,min,sec); + Files[fhandle]->time = time; + Files[fhandle]->date = date; + fcb.SetSizeDateTime(size,date,time); + if (++cur_rec>127u) { cur_block++;cur_rec=0; } + fcb.SetRecord(cur_block,cur_rec); + return FCB_SUCCESS; + } + + uint8_t DOS_FCBIncreaseSize(uint16_t seg,uint16_t offset) { + DOS_FCB fcb(seg,offset); + uint8_t fhandle,cur_rec;uint16_t cur_block,rec_size; + fcb.GetSeqData(fhandle,rec_size); + fcb.GetRecord(cur_block,cur_rec); + uint32_t pos=((cur_block*128u)+cur_rec)*rec_size; + if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET,true)) return FCB_ERR_WRITE; + uint16_t towrite=0; + if (!DOS_WriteFile(fhandle,dos_copybuf,&towrite,true)) return FCB_ERR_WRITE; + uint32_t size;uint16_t date,time; + fcb.GetSizeDateTime(size,date,time); + if (pos+towrite>size) size=pos+towrite; + //time doesn't keep track of endofday + date = DOS_PackDate(dos.date.year,dos.date.month,dos.date.day); + uint32_t ticks = mem_readd(BIOS_TIMER); + uint32_t seconds = (ticks*10u)/182u; + uint16_t hour = (uint16_t)(seconds/3600u); + uint16_t min = (uint16_t)((seconds % 3600u)/60u); + uint16_t sec = (uint16_t)(seconds % 60u); + time = DOS_PackTime(hour,min,sec); + Files[fhandle]->time = time; + Files[fhandle]->date = date; + fcb.SetSizeDateTime(size,date,time); + fcb.SetRecord(cur_block,cur_rec); + return FCB_SUCCESS; + } + + uint8_t DOS_FCBRandomRead(uint16_t seg,uint16_t offset,uint16_t * numRec,bool restore) { + /* if restore is true :random read else random block read. + * random read updates old block and old record to reflect the random data + * before the read!!!!!!!!! and the random data is not updated! (user must do this) + * Random block read updates these fields to reflect the state after the read! + */ + DOS_FCB fcb(seg,offset); + uint32_t random; + uint16_t old_block=0; + uint8_t old_rec=0; + uint8_t error=0; + uint16_t count; + + /* Set the correct record from the random data */ + fcb.GetRandom(random); + fcb.SetRecord((uint16_t)(random / 128u),(uint8_t)(random & 127u)); + if (restore) fcb.GetRecord(old_block,old_rec);//store this for after the read. + // Read records + for (count=0; count<*numRec; count++) { + error = DOS_FCBRead(seg,offset,count); + if (error!=FCB_SUCCESS) break; + } + if (error==FCB_READ_PARTIAL) count++; //partial read counts + *numRec=count; + uint16_t new_block;uint8_t new_rec; + fcb.GetRecord(new_block,new_rec); + if (restore) fcb.SetRecord(old_block,old_rec); + /* Update the random record pointer with new position only when restore is false*/ + if(!restore) fcb.SetRandom(new_block*128u+new_rec); + return error; + } + + uint8_t DOS_FCBRandomWrite(uint16_t seg,uint16_t offset,uint16_t * numRec,bool restore) { + /* see FCB_RandomRead */ + DOS_FCB fcb(seg,offset); + uint32_t random; + uint16_t old_block=0; + uint8_t old_rec=0; + uint8_t error=0; + + /* Set the correct record from the random data */ + fcb.GetRandom(random); + fcb.SetRecord((uint16_t)(random / 128u),(uint8_t)(random & 127u)); + if (restore) fcb.GetRecord(old_block,old_rec); + if (*numRec > 0) { + uint16_t count; + /* Write records */ + for (count=0; count<*numRec; count++) { + error = DOS_FCBWrite(seg,offset,count);// dos_fcbwrite return 0 false when true... + if (error!=FCB_SUCCESS) break; + } + *numRec=count; + } else { + DOS_FCBIncreaseSize(seg,offset); + } + uint16_t new_block;uint8_t new_rec; + fcb.GetRecord(new_block,new_rec); + if (restore) fcb.SetRecord(old_block,old_rec); + /* Update the random record pointer with new position only when restore is false */ + if (!restore) fcb.SetRandom(new_block*128u+new_rec); + return error; + } + + bool DOS_FCBGetFileSize(uint16_t seg,uint16_t offset) { + char shortname[DOS_PATHLENGTH];uint16_t entry; + DOS_FCB fcb(seg,offset); + fcb.GetName(shortname); + if (!DOS_OpenFile(shortname,OPEN_READ,&entry,true)) return false; + uint32_t size = 0; + Files[entry]->Seek(&size,DOS_SEEK_END); + DOS_CloseFile(entry,true); + + uint8_t handle; uint16_t rec_size; + fcb.GetSeqData(handle,rec_size); + if (rec_size == 0) rec_size = 128; //Use default if missing. + + uint32_t random=(size/rec_size); + if (size % rec_size) random++; + fcb.SetRandom(random); + return true; + } + + bool DOS_FCBDeleteFile(uint16_t seg,uint16_t offset){ + /* Special case: ????????.??? and DOS_ATTR_VOLUME */ + { + DOS_FCB fcb(seg,offset); + uint8_t attr = 0; + fcb.GetAttr(attr); + uint8_t drive = fcb.GetDrive(); + std::string label = Drives[drive]->GetLabel(); + + if (attr & DOS_ATTR_VOLUME) { + char shortname[DOS_FCBNAME]; + fcb.GetVolumeName(shortname); + + if (!strcmp(shortname,"???????????")) { + if (!label.empty()) { + Drives[drive]->SetLabel("",false,true); + LOG(LOG_DOSMISC,LOG_NORMAL)("FCB delete volume label"); + return true; + } + } + else { + /* MS-DOS 6.22 LABEL.EXE will explicitly request to delete the volume label by the volume label not ????????.???? */ + if (!label.empty()) { + while (label.length() < 11) label += ' '; + if (!memcmp(label.c_str(),shortname,11)) { + Drives[drive]->SetLabel("",false,true); + LOG(LOG_DOSMISC,LOG_NORMAL)("FCB delete volume label deleted"); + return true; + } + } + } + + LOG(LOG_DOSMISC,LOG_NORMAL)("FCB delete volume label not found (current='%s' asking='%s')",label.c_str(),shortname); + DOS_SetError(DOSERR_FILE_NOT_FOUND); // right? + return false; + } + } + + /* FCB DELETE honours wildcards. it will return true if one or more + * files get deleted. + * To get this: the dta is set to temporary dta in which found files are + * stored. This can not be the tempdta as that one is used by fcbfindfirst + */ + RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta_fcbdelete); + RealPt new_dta=dos.dta(); + bool nextfile = false; + bool return_value = false; + nextfile = DOS_FCBFindFirst(seg,offset); + DOS_FCB fcb(RealSeg(new_dta),RealOff(new_dta)); + while(nextfile) { + char shortname[DOS_FCBNAME] = { 0 }; + fcb.GetName(shortname); + bool res=DOS_UnlinkFile(shortname); + if(!return_value && res) return_value = true; //at least one file deleted + nextfile = DOS_FCBFindNext(seg,offset); + } + dos.dta(old_dta); /*Restore dta */ + return return_value; + } + + char* trimString(char* str); + + bool DOS_FCBRenameFile(uint16_t seg, uint16_t offset){ + DOS_FCB fcbold(seg,offset); + DOS_FCB fcbnew(seg,offset); + fcbnew.SetPtPhys(fcbnew.GetPtPhys()+0x10u);//HACK: FCB NEW memory offset is affected by whether FCB OLD is extended + if(!fcbold.Valid()) return false; + char oldname[DOS_FCBNAME]; + char newname[DOS_FCBNAME]; + fcbold.GetName(oldname);fcbnew.GetName(newname); + + { + uint8_t drive = fcbold.GetDrive(); + std::string label = Drives[drive]->GetLabel(); + uint8_t attr = 0; + + fcbold.GetAttr(attr); + /* According to RBIL and confirmed with SETLABEL.ASM in DOSLIB2, you can rename a volume label dirent as well with this function */ + if (attr & DOS_ATTR_VOLUME) { + fcbold.GetVolumeName(oldname); + fcbnew.GetVolumeName(newname); + + for (unsigned int i=0;i < 11;i++) + oldname[i] = toupper(oldname[i]); + + trimString(oldname); + trimString(newname); + + if (!label.empty()) { + if (!strcmp(oldname,"???????????") || label == oldname) { + Drives[drive]->SetLabel(newname,false,true); + LOG(LOG_DOSMISC,LOG_NORMAL)("FCB rename volume label to '%s' from '%s'",newname,oldname); + return true; + } + else { + LOG(LOG_DOSMISC,LOG_NORMAL)("FCB rename volume label rejected, does not match current label '%s' from '%s'",newname,oldname); + DOS_SetError(DOSERR_FILE_NOT_FOUND); // right? + return false; + } + } + else { + LOG(LOG_DOSMISC,LOG_NORMAL)("FCB rename volume label rejected, no label set"); + DOS_SetError(DOSERR_FILE_NOT_FOUND); // right? + return false; + } + } + } + + /* Check, if sourcefile is still open. This was possible in DOS, but modern oses don't like this */ + uint8_t drive; char fullname[DOS_PATHLENGTH]; + if (!DOS_MakeName(oldname,fullname,&drive)) return false; + + DOS_PSP psp(dos.psp()); + for (uint8_t i=0;iIsOpen() && Files[i]->IsName(fullname)) { + uint16_t handle = psp.FindEntryByHandle(i); + //(more than once maybe) + if (handle == 0xFFu) { + DOS_CloseFile(i,true); + } else { + DOS_CloseFile(handle); + } + } + } + + /* Rename the file */ + return DOS_Rename(oldname,newname); + } + + void DOS_FCBSetRandomRecord(uint16_t seg, uint16_t offset) { + DOS_FCB fcb(seg,offset); + uint16_t block;uint8_t rec; + fcb.GetRecord(block,rec); + fcb.SetRandom(block*128u+rec); + } + + + bool DOS_FileExists(char const * const name) { + char fullname[DOS_PATHLENGTH];uint8_t drive; + if (!DOS_MakeName(name,fullname,&drive)) return false; + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(name)) return Network_FileExists(fullname); + #endif + return Drives[drive]->FileExists(fullname); + } + + bool DOS_GetAllocationInfo(uint8_t drive,uint16_t * _bytes_sector,uint8_t * _sectors_cluster,uint16_t * _total_clusters) { + if (!drive) drive = DOS_GetDefaultDrive(); + else drive--; + if (drive >= DOS_DRIVES || !Drives[drive]) { + DOS_SetError(DOSERR_INVALID_DRIVE); + return false; + } + uint16_t _free_clusters; + Drives[drive]->AllocationInfo(_bytes_sector,_sectors_cluster,_total_clusters,&_free_clusters); + SegSet16(ds,RealSeg(dos.tables.mediaid)); + reg_bx=RealOff(dos.tables.mediaid+drive*dos.tables.dpb_size); + return true; + } + + bool DOS_SetDrive(uint8_t drive) { + if (Drives[drive]) { + DOS_SetDefaultDrive(drive); + return true; + } else { + return false; + } + } + + bool DOS_GetFileDate(uint16_t entry, uint16_t* otime, uint16_t* odate) { + uint32_t handle=RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsActiveResource(entry)) + return Network_GetFileDate(entry, otime, odate); + #endif + if (!Files[handle] || !Files[handle]->IsOpen()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + if (!Files[handle]->UpdateDateTimeFromHost()) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + *otime = Files[handle]->time; + *odate = Files[handle]->date; + return true; + } + + bool DOS_SetFileDate(uint16_t entry, uint16_t ntime, uint16_t ndate) + { + uint32_t handle=RealHandle(entry); + if (handle>=DOS_FILES) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if(Network_IsActiveResource(entry)) + return Network_SetFileDate(entry, ntime, ndate); + #endif + if (!Files[handle]) { + DOS_SetError(DOSERR_INVALID_HANDLE); + return false; + } + Files[handle]->time = ntime; + Files[handle]->date = ndate; + Files[handle]->newtime = true; + + return true; + } + + extern int swapInDisksSpecificDrive; + void DOS_SetupFiles (void) { + /* Setup the File Handles */ + Files = new DOS_File * [DOS_FILES]; + uint32_t i; + for (i=0;iRelease(); + diskSwap[si] = NULL; + } + } + swapInDisksSpecificDrive = -1; + } + Drives[25]=new Virtual_Drive(); + } + + // save state support + void DOS_File::SaveState( std::ostream& stream ) + { + uint32_t file_namelen, seek_pos; + + + file_namelen = (uint32_t)strlen( name ); + seek_pos = GetSeekPos(); + + //****************************************** + //****************************************** + //****************************************** + + // - pure data + WRITE_POD( &file_namelen, file_namelen ); + WRITE_POD_SIZE( name, file_namelen ); + + WRITE_POD( &flags, flags ); + WRITE_POD( &open, open ); + + WRITE_POD( &attr, attr ); + WRITE_POD( &time, time ); + WRITE_POD( &date, date ); + WRITE_POD( &refCtr, refCtr ); + WRITE_POD( &hdrive, hdrive ); + + //****************************************** + //****************************************** + //****************************************** + + // - reloc ptr + WRITE_POD( &seek_pos, seek_pos ); + } + + + void DOS_File::LoadState( std::istream& stream, bool pop ) + { + uint32_t file_namelen, seek_pos; + char *file_name; + + //****************************************** + //****************************************** + //****************************************** + + // - pure data + READ_POD( &file_namelen, file_namelen ); + file_name = (char*)alloca( file_namelen * sizeof(char) ); + READ_POD_SIZE( file_name, file_namelen ); + + READ_POD( &flags, flags ); + READ_POD( &open, open ); + + READ_POD( &attr, attr ); + READ_POD( &time, time ); + READ_POD( &date, date ); + READ_POD( &refCtr, refCtr ); + READ_POD( &hdrive, hdrive ); + + //****************************************** + //****************************************** + //****************************************** + + // - reloc ptr + READ_POD( &seek_pos, seek_pos ); + + if (pop) + return; + + if( open ) Seek( &seek_pos, DOS_SEEK_SET ); + else Close(); + } + + extern bool dos_kernel_disabled; + extern uint8_t ZDRIVE_NUM; + struct Alloc { + uint16_t bytes_sector; + uint8_t sectors_cluster; + uint16_t total_clusters; + uint16_t free_clusters; + uint8_t mediaid; + }; + Alloc lalloc, oalloc; + struct Opts { + uint32_t bytesector; + uint32_t cylsector; + uint32_t headscyl; + uint32_t cylinders; + int mounttype; + uint8_t mediaid; + unsigned char CDROM_drive; + unsigned long cdrom_sector_offset; + unsigned char floppy_emu_type; + }; + Opts opts; + char overlaydir[CROSS_LEN]; + void MSCDEX_SetCDInterface(int intNr, int forceCD); + void POD_Save_DOS_Files( std::ostream& stream ) + { + char dinfo[256]; + WRITE_POD( &ZDRIVE_NUM, ZDRIVE_NUM); + if (!dos_kernel_disabled) { + // 1. Do drives first (directories -> files) + // 2. Then files next + + for( int i=2; iGetInfo()); + WRITE_POD( &dinfo, dinfo); + *overlaydir=0; + if (!strncmp(dinfo,"local directory ",16) || !strncmp(dinfo,"CDRom ",6) || !strncmp(dinfo,"PhysFS directory ",17) || !strncmp(dinfo,"PhysFS CDRom ",13) ) { + localDrive *ldp = dynamic_cast(Drives[lcv]); + if (!ldp) ldp = dynamic_cast(Drives[lcv]); + if (!ldp) ldp = dynamic_cast(Drives[lcv]); + if (ldp) { + lalloc.bytes_sector=ldp->allocation.bytes_sector; + lalloc.sectors_cluster=ldp->allocation.sectors_cluster; + lalloc.total_clusters=ldp->allocation.total_clusters; + lalloc.free_clusters=ldp->allocation.free_clusters; + lalloc.mediaid=ldp->allocation.mediaid; + } + Overlay_Drive *odp = dynamic_cast(Drives[lcv]); + if (odp) { + strcpy(overlaydir,odp->getOverlaydir()); + oalloc.bytes_sector=odp->allocation.bytes_sector; + oalloc.sectors_cluster=odp->allocation.sectors_cluster; + oalloc.total_clusters=odp->allocation.total_clusters; + oalloc.free_clusters=odp->allocation.free_clusters; + oalloc.mediaid=odp->allocation.mediaid; + } else { + physfsDrive *pdp = dynamic_cast(Drives[lcv]); + if (pdp && pdp->getOverlaydir()) + strcpy(overlaydir,pdp->getOverlaydir()); + } + } else if (!strncmp(dinfo,"fatDrive ",9)) { + fatDrive *fdp = dynamic_cast(Drives[lcv]); + if (fdp) { + opts.bytesector=fdp->loadedDisk?fdp->loadedDisk->sector_size:fdp->opts.bytesector; + opts.cylsector=fdp->loadedDisk?fdp->loadedDisk->sectors:fdp->opts.cylsector; + opts.headscyl=fdp->loadedDisk?fdp->loadedDisk->heads:fdp->opts.headscyl; + opts.cylinders=fdp->loadedDisk?fdp->loadedDisk->cylinders:fdp->opts.cylinders; + opts.mounttype=fdp->opts.mounttype; + opts.mediaid=fdp->GetMediaByte(); + opts.CDROM_drive=fdp->el.CDROM_drive; + opts.cdrom_sector_offset=fdp->el.cdrom_sector_offset; + opts.floppy_emu_type=fdp->el.floppy_emu_type; + } + } + + WRITE_POD( &overlaydir, overlaydir); + WRITE_POD( &lalloc, lalloc); + WRITE_POD( &oalloc, oalloc); + WRITE_POD( &opts, opts); + Drives[lcv]->SaveState(stream); + } + + for( unsigned int lcv=0; lcvGetName() == NULL ) file_valid = 0xff; + else { + if( strcmp( Files[lcv]->GetName(), "NUL" ) == 0 ) file_valid = 0xfe;//earth 2140 needs this + if( strcmp( Files[lcv]->GetName(), "CON" ) == 0 ) file_valid = 0xfe; + if( strcmp( Files[lcv]->GetName(), "LPT1" ) == 0 ) file_valid = 0xfe; + if( strcmp( Files[lcv]->GetName(), "PRN" ) == 0 ) file_valid = 0xfe; + if( strcmp( Files[lcv]->GetName(), "AUX" ) == 0 ) file_valid = 0xfe; + if( strcmp( Files[lcv]->GetName(), "EMMXXXX0" ) == 0 ) file_valid = 0xfe;//raiden needs this + } + + // - reloc ptr + WRITE_POD( &file_valid, file_valid ); + // system files + if( file_valid == 0xff ) continue; + if( file_valid == 0xfe ) { + WRITE_POD( &Files[lcv]->refCtr, Files[lcv]->refCtr ); + continue; + } + + //********************************************** + //********************************************** + //********************************************** + + file_namelen = (uint8_t)strlen( Files[lcv]->name ); + file_name = (char *) alloca( file_namelen ); + strcpy( file_name, Files[lcv]->name ); + + file_drive = Files[lcv]->GetDrive(); + file_flags = Files[lcv]->flags; + + // - Drives->FileOpen vars (repeat copy) + WRITE_POD( &file_namelen, file_namelen ); + WRITE_POD_SIZE( file_name, file_namelen ); + + WRITE_POD( &file_drive, file_drive ); + WRITE_POD( &file_flags, file_flags ); + + Files[lcv]->SaveState(stream); + } + } else { + for( int i=2; iGetInfo()); + WRITE_POD( &dinfo, dinfo); + } + } + + for (int i=2; i(imageDiskList[d]); + strcpy(diskname, image!=NULL?"El Torito floppy drive":imageDiskList[d]->diskname.c_str()); + WRITE_POD( &diskname, diskname ); + if (image!=NULL) { + opts.CDROM_drive=image->CDROM_drive; + opts.cdrom_sector_offset=image->cdrom_sector_offset; + opts.floppy_emu_type=image->floppy_type; + opts.mounttype=1; + } else { + imageDiskMemory* idmem = dynamic_cast(imageDiskList[d]); + imageDiskVHD* idvhd = dynamic_cast(imageDiskList[d]); + if (idmem!=NULL) + opts.mounttype=2; + else if (idvhd!=NULL) + opts.mounttype=3; + else { + opts.bytesector=imageDiskList[d]->sector_size; + opts.cylsector=imageDiskList[d]->sectors; + opts.headscyl=imageDiskList[d]->heads; + opts.cylinders=imageDiskList[d]->cylinders; + opts.mounttype=0; + } + } + WRITE_POD( &opts, opts); + } + } + + void DOS_EnableDriveMenu(char drv); + void IDE_Auto(signed char &index,bool &slave); + bool AttachToBiosByLetter(imageDisk* image, const char drive); + bool AttachToBiosAndIdeByLetter(imageDisk* image, const char drive, const unsigned char ide_index, const bool ide_slave); + imageDiskMemory* CreateRamDrive(Bitu sizes[], const int reserved_cylinders, const bool forceFloppy, Program* obj); + + void unmount(int lcv) { + if (!Drives[lcv] || lcv>=DOS_DRIVES-1) return; + const isoDrive* cdrom = dynamic_cast(Drives[lcv]); + if (DriveManager::UnmountDrive(lcv) == 0) { + if (cdrom) IDE_CDROM_Detach(lcv); + Drives[lcv]=nullptr; + DOS_EnableDriveMenu('A'+lcv); + mem_writeb(Real2Phys(dos.tables.mediaid)+lcv*dos.tables.dpb_size,0); + } + } + + void POD_Load_DOS_Files( std::istream& stream ) + { + char dinfo[256]; + std::vector clist; + clist.clear(); + uint8_t ZDRIVE_CUR = ZDRIVE_NUM; + READ_POD( &ZDRIVE_NUM, ZDRIVE_NUM); + if (!dos_kernel_disabled) { + if (ZDRIVE_CUR != ZDRIVE_NUM) { + Drives[ZDRIVE_NUM] = Drives[ZDRIVE_CUR]; + Drives[ZDRIVE_CUR] = nullptr; + } + // 1. Do drives first (directories -> files) + // 2. Then files next + + for( int i=2; iinfo, dinfo) && (!strncmp(dinfo,"local directory ",16) || !strncmp(dinfo,"CDRom ",6) || !strncmp(dinfo,"PhysFS directory ",17) || !strncmp(dinfo,"PhysFS CDRom ",13) || (!strncmp(dinfo,"isoDrive ",9) || !strncmp(dinfo,"fatDrive ",9)))) + unmount(lcv); + if( !Drives[lcv] ) { + std::vector options; + if (!strncmp(dinfo,"local directory ",16)) { + Drives[lcv]=new localDrive(dinfo+16,lalloc.bytes_sector,lalloc.sectors_cluster,lalloc.total_clusters,lalloc.free_clusters,lalloc.mediaid,options); + if (Drives[lcv]) { + DOS_EnableDriveMenu('A'+lcv); + mem_writeb(Real2Phys(dos.tables.mediaid)+lcv*dos.tables.dpb_size,lalloc.mediaid); + if (strlen(overlaydir)) { + uint8_t error = 0; + Drives[lcv]=new Overlay_Drive(dynamic_cast(Drives[lcv])->getBasedir(),overlaydir,oalloc.bytes_sector,oalloc.sectors_cluster,oalloc.total_clusters,oalloc.free_clusters,oalloc.mediaid,error,options); + } + } else + LOG_MSG("Error: Cannot restore drive from directory %s\n", dinfo+16); + } else if (!strncmp(dinfo,"CDRom ",6) || !strncmp(dinfo,"PhysFS CDRom ",13)) { + int num = -1; + int error = 0; + int id, major, minor; + DOSBox_CheckOS(id, major, minor); + if ((id==VER_PLATFORM_WIN32_NT) && (major>5)) + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); + else + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); + if (!strncmp(dinfo,"PhysFS CDRom ",13)) { + std::string str=std::string(dinfo+13); + std::size_t found=str.find(", "); + if (found!=std::string::npos) + str=str.substr(0,found); + Drives[lcv] = new physfscdromDrive('A'+lcv,(":"+str+"\\").c_str(),lalloc.bytes_sector,lalloc.sectors_cluster,lalloc.total_clusters,0,lalloc.mediaid,error,options); + } else + Drives[lcv] = new cdromDrive('A'+lcv,dinfo+6,lalloc.bytes_sector,lalloc.sectors_cluster,lalloc.total_clusters,lalloc.free_clusters,lalloc.mediaid,error,options); + if (Drives[lcv]) { + DOS_EnableDriveMenu('A'+lcv); + mem_writeb(Real2Phys(dos.tables.mediaid)+lcv*dos.tables.dpb_size,lalloc.mediaid); + } else + LOG_MSG("Error: Cannot restore drive from directory %s\n", dinfo+6); + } else if (!strncmp(dinfo,"PhysFS directory ",17)) { + int error = 0; + std::string str=std::string(dinfo+17); + std::size_t found=str.find(", "); + if (found!=std::string::npos) + str=str.substr(0,found); + Drives[lcv]=new physfsDrive('A'+lcv,(":"+str+"\\").c_str(),lalloc.bytes_sector,lalloc.sectors_cluster,lalloc.total_clusters,lalloc.free_clusters,lalloc.mediaid,error,options); + if (Drives[lcv]) { + if (strlen(overlaydir)) dynamic_cast(Drives[lcv])->setOverlaydir(overlaydir); + DOS_EnableDriveMenu('A'+lcv); + mem_writeb(Real2Phys(dos.tables.mediaid)+lcv*dos.tables.dpb_size,lalloc.mediaid); + } else + LOG_MSG("Error: Cannot restore drive from directory %s\n", dinfo+16); + } else if (!strncmp(dinfo,"isoDrive ",9) && *(dinfo+9)) { + MSCDEX_SetCDInterface(CDROM_USE_SDL, -1); + uint8_t mediaid = 0xF8; + int error = -1; + isoDrive* newDrive = new isoDrive('A'+lcv, dinfo+9, mediaid, error, options); + if (!error) { + Drives[lcv] = newDrive; + DriveManager::AppendDisk(lcv, newDrive); + DriveManager::InitializeDrive(lcv); + DOS_EnableDriveMenu('A'+lcv); + mem_writeb(Real2Phys(dos.tables.mediaid) + lcv*dos.tables.dpb_size, mediaid); + clist.push_back(lcv); + } + } else if (!strncmp(dinfo,"fatDrive ",9)) { + fatDrive* newDrive = NULL; + Bitu sizes[4] = { 0,0,0,0 }; + if (opts.mounttype==1) { + imageDisk * newImage = new imageDiskElToritoFloppy((unsigned char)opts.CDROM_drive, opts.cdrom_sector_offset, opts.floppy_emu_type); + if (newImage != NULL) { + newImage->Addref(); + newDrive = new fatDrive(newImage, options); + newImage->Release(); + } else + LOG_MSG("Error: Cannot restore drive from El Torito floppy image.\n"); + + } else if (opts.mounttype==2) { + imageDiskMemory* image = CreateRamDrive(sizes, 0, lcv < 2 && sizes[0] == 0, NULL); + if (image != NULL && image->Format() == 0x00) { + image->Addref(); + newDrive = new fatDrive(image, options); + image->Release(); + } + } else if (opts.mounttype==3 && *(dinfo+9)) { + imageDisk* vhdImage = NULL; + if (imageDiskVHD::Open(dinfo+9, false, &vhdImage)==imageDiskVHD::OPEN_SUCCESS) + newDrive = new fatDrive(vhdImage, options); + vhdImage = NULL; + } else if (!opts.mounttype && *(dinfo+9)) + newDrive = new fatDrive(dinfo+9, opts.bytesector, opts.cylsector, opts.headscyl, opts.cylinders, options); + if (newDrive && newDrive->created_successfully) { + Drives[lcv] = newDrive; + DriveManager::AppendDisk(lcv, newDrive); + DriveManager::InitializeDrive(lcv); + DOS_EnableDriveMenu('A'+lcv); + mem_writeb(Real2Phys(dos.tables.mediaid) + lcv*dos.tables.dpb_size, opts.mediaid); + } else if ((!opts.mounttype || opts.mounttype==3) && *(dinfo+9)) + LOG_MSG("Error: Cannot restore drive from image file %s\n", dinfo+9); + } + } + if( Drives[lcv] ) Drives[lcv]->LoadState(stream); + } + + //Alien Carnage - game creates and unlinks temp files + //Here are two situations + //1. Game already unlinked temp file, but information about file is still in Files[] and we saved it. In this case we must only pop old data from stream by loading. This is fixed. + //2. Game still did not unlink file, We saved this information. Then was game restarted and temp files were removed. Then we try load save state, but we don't have temp file. This is not fixed + DOS_File *dummy = NULL; + + for( unsigned int lcv=0; lcvrefCtr, Files[lcv]->refCtr ); + continue; + } + + // shutdown old file + if( Files[lcv] && Files[lcv]->GetName() != NULL ) { + // invalid file state - abort + if( strcmp( Files[lcv]->GetName(), "NUL" ) == 0 ) break; + if( strcmp( Files[lcv]->GetName(), "CON" ) == 0 ) break; + if( strcmp( Files[lcv]->GetName(), "LPT1" ) == 0 ) break; + if( strcmp( Files[lcv]->GetName(), "PRN" ) == 0 ) break; + if( strcmp( Files[lcv]->GetName(), "AUX" ) == 0 ) break; + if( strcmp( Files[lcv]->GetName(), "EMMXXXX0" ) == 0 ) break;//raiden needs this + + + if( Files[lcv]->IsOpen() ) Files[lcv]->Close(); + if (Files[lcv]->RemoveRef()<=0) { + delete Files[lcv]; + } + Files[lcv]=nullptr; + } + + // ignore NULL file + if( file_valid == 0xff ) continue; + + //********************************************** + //********************************************** + //********************************************** + + // - Drives->FileOpen vars (repeat copy) + + READ_POD( &file_namelen, file_namelen ); + file_name = (char *) alloca( file_namelen ); + READ_POD_SIZE( file_name, file_namelen ); + + READ_POD( &file_drive, file_drive ); + READ_POD( &file_flags, file_flags ); + + + // NOTE: Must open regardless to get 'new' DOS_File class + Drives[file_drive]->FileOpen( &Files[lcv], file_name, file_flags ); + + if( Files[lcv] ) { + Files[lcv]->LoadState(stream, false); + } else { + //Alien carnage ->pop data for invalid file from stream + if (dummy == NULL) { + dummy = new LocalFile(); + } + dummy->LoadState(stream, true); + }; + } + + if (dummy != NULL) { + delete dummy; + } + } else { + for( int i=2; iinfo, dinfo)) + unmount(lcv); + if (!Drives[lcv] && !strncmp(dinfo,"isoDrive ",9)) { + std::vector options; + MSCDEX_SetCDInterface(CDROM_USE_SDL, -1); + uint8_t mediaid = 0xF8; + int error = -1; + isoDrive* newDrive = new isoDrive('A'+lcv, dinfo+9, mediaid, error, options); + if (!error) { + Drives[lcv] = newDrive; + DriveManager::AppendDisk(lcv, newDrive); + DriveManager::InitializeDrive(lcv); + mem_writeb(Real2Phys(dos.tables.mediaid) + lcv*dos.tables.dpb_size, mediaid); + clist.push_back(lcv); + } + } + } + } + + for (int i=2; i 1) IDE_Hard_Disk_Detach(d); + imageDiskList[d]->Release(); + imageDiskList[d] = NULL; + imageDiskChange[d] = true; + } + if (i==MAX_DISK_IMAGES-1) + for (auto &it : clist) { + ide_slave = false; + ide_index = -1; + IDE_Auto(ide_index,ide_slave); + if (ide_index >= 0) IDE_CDROM_Attach(ide_index, ide_slave, it); + } + continue; + } + char diskname[256]; + READ_POD( &diskname, diskname ); + READ_POD( &opts, opts); + Bitu sizes[4] = { 0,0,0,0 }; + ide_slave = false; + ide_index = -1; + IDE_Auto(ide_index,ide_slave); + if( imageDiskList[d] && ((opts.mounttype==1 && dynamic_cast(imageDiskList[d])==NULL) || (opts.mounttype!=1 && strcasecmp(imageDiskList[d]->diskname.c_str(), diskname )))) { + if (d > 1) IDE_Hard_Disk_Detach(d); + imageDiskList[d]->Release(); + imageDiskList[d] = NULL; + imageDiskChange[d] = true; + } + if (imageDiskList[d]) + ; + else if (opts.mounttype==1) { + imageDisk * image = new imageDiskElToritoFloppy((unsigned char)opts.CDROM_drive, opts.cdrom_sector_offset, opts.floppy_emu_type); + if (image) AttachToBiosByLetter(image, 'A'+d); + else LOG_MSG("Warning: Cannot restore drive number from El Torito floppy image.\n"); + } else if (opts.mounttype==2) { + imageDiskMemory* image = CreateRamDrive(sizes, 0, d < 2 && sizes[0] == 0, NULL); + if (image != NULL && image->Format() == 0x00) AttachToBiosAndIdeByLetter(image, d, (unsigned char)ide_index, ide_slave); + } else if (opts.mounttype==3 && *diskname) { + imageDisk* image = NULL; + if (imageDiskVHD::Open(diskname, false, &image)==imageDiskVHD::OPEN_SUCCESS) + AttachToBiosAndIdeByLetter(image, 'A'+d, (unsigned char)ide_index, ide_slave); + else + LOG_MSG("Warning: Cannot restore drive number from image file %s\n", diskname); + image = NULL; + } else if (!opts.mounttype && *diskname) { + std::vector options; + fatDrive* newDrive = new fatDrive(diskname, opts.bytesector, opts.cylsector, opts.headscyl, opts.cylinders, options); + // if (newDrive->created_successfully) { + // imageDisk* image = newDrive->loadedDisk; + // AttachToBiosAndIdeByLetter(image, 'A'+d, (unsigned char)ide_index, ide_slave); + // } else + LOG_MSG("Warning: Cannot restore drive number from image file %s\n", diskname); + if (newDrive) delete newDrive; + } + if (i==MAX_DISK_IMAGES-1) + for (auto &it : clist) { + ide_slave = false; + ide_index = -1; + IDE_Auto(ide_index,ide_slave); + if (ide_index >= 0) IDE_CDROM_Attach(ide_index, ide_slave, it); + } + } + } + \ No newline at end of file diff --git a/src/dos/dos_mscdex.cpp b/src/dos/dos_mscdex.cpp index 140c7120bd6..103f0570777 100644 --- a/src/dos/dos_mscdex.cpp +++ b/src/dos/dos_mscdex.cpp @@ -253,78 +253,78 @@ int CMscdex::AddDrive(uint16_t _drive, char* physicalPath, uint8_t& subUnit) // Set return type to ok int result = 0; // Get Mounttype and init needed cdrom interface - switch (CDROM_GetMountType(physicalPath,forceCD)) { - case 0x00: { - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: Mounting physical cdrom: %s" ,physicalPath); -#if defined (WIN32) - // Check OS - OSVERSIONINFO osi; - osi.dwOSVersionInfoSize = sizeof(osi); - GetVersionEx(&osi); - if ((osi.dwPlatformId==VER_PLATFORM_WIN32_NT) && (osi.dwMajorVersion>4)) { - // only WIN NT/200/XP - if (useCdromInterface==CDROM_USE_IOCTL_DIO) { - cdrom[numDrives] = new CDROM_Interface_Ioctl(CDROM_Interface_Ioctl::CDIOCTL_CDA_DIO); - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: IOCTL Interface."); - break; - } - if (useCdromInterface==CDROM_USE_IOCTL_DX) { - cdrom[numDrives] = new CDROM_Interface_Ioctl(CDROM_Interface_Ioctl::CDIOCTL_CDA_DX); - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: IOCTL Interface (digital audio extraction)."); - break; - } - if (useCdromInterface==CDROM_USE_IOCTL_MCI) { - cdrom[numDrives] = new CDROM_Interface_Ioctl(CDROM_Interface_Ioctl::CDIOCTL_CDA_MCI); - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: IOCTL Interface (media control interface)."); - break; - } - } - if (useCdromInterface==CDROM_USE_ASPI) { - // all Wins - ASPI - cdrom[numDrives] = new CDROM_Interface_Aspi(); - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: ASPI Interface."); - break; - } -#endif -#if defined (LINUX) || defined(OS2) - // Always use IOCTL in Linux or OS/2 - cdrom[numDrives] = new CDROM_Interface_Ioctl(); - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: IOCTL Interface."); -#else - // Default case windows and other oses - cdrom[numDrives] = new CDROM_Interface_SDL(); - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: SDL Interface."); -#endif - } break; - case 0x01: // iso cdrom interface - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: Mounting iso file as cdrom: %s", physicalPath); - cdrom[numDrives] = new CDROM_Interface_Image((uint8_t)numDrives); - break; - case 0x02: // fake cdrom interface (directories) - { - CDROM_Interface_Fake *fake = new CDROM_Interface_Fake; - cdrom[numDrives] = fake; - assert(fake->class_id == CDROM_Interface::INTERFACE_TYPE::ID_FAKE); - if (!strcmp(physicalPath,"empty")) { - fake->isEmpty = true; - } - else { - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: Mounting directory as cdrom: %s",physicalPath); - LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: You won't have full MSCDEX support !"); - result = 5; - } - } - break; - default : // weird result - return 6; - } +// switch (CDROM_GetMountType(physicalPath,forceCD)) { +// case 0x00: { +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: Mounting physical cdrom: %s" ,physicalPath); +// #if defined (WIN32) +// // Check OS +// OSVERSIONINFO osi; +// osi.dwOSVersionInfoSize = sizeof(osi); +// GetVersionEx(&osi); +// if ((osi.dwPlatformId==VER_PLATFORM_WIN32_NT) && (osi.dwMajorVersion>4)) { +// // only WIN NT/200/XP +// if (useCdromInterface==CDROM_USE_IOCTL_DIO) { +// cdrom[numDrives] = new CDROM_Interface_Ioctl(CDROM_Interface_Ioctl::CDIOCTL_CDA_DIO); +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: IOCTL Interface."); +// break; +// } +// if (useCdromInterface==CDROM_USE_IOCTL_DX) { +// cdrom[numDrives] = new CDROM_Interface_Ioctl(CDROM_Interface_Ioctl::CDIOCTL_CDA_DX); +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: IOCTL Interface (digital audio extraction)."); +// break; +// } +// if (useCdromInterface==CDROM_USE_IOCTL_MCI) { +// cdrom[numDrives] = new CDROM_Interface_Ioctl(CDROM_Interface_Ioctl::CDIOCTL_CDA_MCI); +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: IOCTL Interface (media control interface)."); +// break; +// } +// } +// if (useCdromInterface==CDROM_USE_ASPI) { +// // all Wins - ASPI +// cdrom[numDrives] = new CDROM_Interface_Aspi(); +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: ASPI Interface."); +// break; +// } +// #endif +// #if defined (LINUX) || defined(OS2) +// // // Always use IOCTL in Linux or OS/2 +// // cdrom[numDrives] = new CDROM_Interface_Ioctl(); +// // LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: IOCTL Interface."); +// // #else +// // Default case windows and other oses +// cdrom[numDrives] = new CDROM_Interface_SDL(); +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: SDL Interface."); +// #endif +// } break; +// case 0x01: // iso cdrom interface +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: Mounting iso file as cdrom: %s", physicalPath); +// cdrom[numDrives] = new CDROM_Interface_Image((uint8_t)numDrives); +// break; +// case 0x02: // fake cdrom interface (directories) +// { +// CDROM_Interface_Fake *fake = new CDROM_Interface_Fake; +// cdrom[numDrives] = fake; +// assert(fake->class_id == CDROM_Interface::INTERFACE_TYPE::ID_FAKE); +// if (!strcmp(physicalPath,"empty")) { +// fake->isEmpty = true; +// } +// else { +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: Mounting directory as cdrom: %s",physicalPath); +// LOG(LOG_MISC,LOG_NORMAL)("MSCDEX: You won't have full MSCDEX support !"); +// result = 5; +// } +// } +// break; +// default : // weird result +// return 6; +// } + cdrom[numDrives] = new CDROM_Interface_Image((uint8_t)numDrives); if (!cdrom[numDrives]->SetDevice(physicalPath,forceCD)) { // delete cdrom[numDrives] ; mount seems to delete it return 3; } - if (rootDriverHeaderSeg==0) { uint16_t driverSize = sizeof(DOS_DeviceHeader::sDeviceHeader) + 10; // 10 = Bytes for 3 callbacks @@ -406,6 +406,7 @@ int CMscdex::AddDrive(uint16_t _drive, char* physicalPath, uint8_t& subUnit) dinfo[numDrives].physDrive = (uint8_t)toupper(physicalPath[0]); subUnit = (uint8_t)numDrives; } + numDrives++; // init channel control for (uint8_t chan=0;chan<4;chan++) { diff --git a/src/dos/dos_programs.cpp b/src/dos/dos_programs.cpp index 3aa9c6509c6..288d28b8167 100644 --- a/src/dos/dos_programs.cpp +++ b/src/dos/dos_programs.cpp @@ -22,10156 +22,10275 @@ * SERIAL command Copyright sduensin and Wengier */ -#include "dosbox.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "menudef.h" -#include "programs.h" -#include "support.h" -#include "drives.h" -#include "cross.h" -#include "regs.h" -#include "ide.h" -#include "cpu.h" -#include "callback.h" -#include "cdrom.h" -#include "builtin.h" -#include "bios_disk.h" -#include "dos_system.h" -#include "dos_inc.h" -#include "bios.h" -#include "bitop.h" -#include "inout.h" -#include "dma.h" -#include "bios_disk.h" -#include "qcow2_disk.h" -#include "shell.h" -#include "setup.h" -#include "control.h" -#include -#include "menu.h" -#include "render.h" -#include "mouse.h" -#include "eltorito.h" -#include "../ints/int10.h" -#include "../output/output_opengl.h" -#include "paging.h" -#if !defined(HX_DOS) -#include "../libs/tinyfiledialogs/tinyfiledialogs.c" -#endif -#if defined(WIN32) -#ifndef C_ICONV -# define C_ICONV -# include "../misc/winiconv.c" -#endif -typedef wchar_t host_cnv_char_t; -host_cnv_char_t *CodePageGuestToHost(const char *s); -#if !defined(S_ISREG) -# define S_ISREG(x) ((x & S_IFREG) == S_IFREG) -#endif -#include -#else -#include -#endif -#ifdef C_ICONV -#include "iconvpp.hpp" -typedef char16_t test_char_t; -typedef std::basic_string test_string; -typedef std::basic_string test_char; -#endif -int freesizecap = 1; -int result_errorcode = 0; -char lastmount = 0; -bool Mouse_Drv=true; -bool Mouse_Vertical = false; -bool force_nocachedir = false; -bool lockmount = true; -bool wpcolon = true; -bool convertimg = true; -bool startcmd = false; -bool startwait = true; -bool startquiet = false; -bool starttranspath = false; -bool mountwarning = true; -bool qmount = false; -bool nowarn = false; -bool CodePageHostToGuestUTF8(char *d/*CROSS_LEN*/,const char *s/*CROSS_LEN*/), CodePageHostToGuestUTF16(char *d/*CROSS_LEN*/,const uint16_t *s/*CROSS_LEN*/); -inline bool CodePageHostToGuestUTF16(char *d/*CROSS_LEN*/,const char16_t *s/*CROSS_LEN*/) { - return CodePageHostToGuestUTF16(d, reinterpret_cast(s)); -} -extern bool systemmessagebox(char const * aTitle, char const * aMessage, char const * aDialogType, char const * aIconType, int aDefaultButton); -extern bool addovl, addipx, addne2k, prepared, inshell, usecon, uao, loadlang, morelen, mountfro[26], mountiro[26], resetcolor, staycolors, printfont, notrycp, internal_program; -extern bool clear_screen(), OpenGL_using(void), DOS_SetAnsiAttr(uint8_t attr), isDBCSCP(); -extern int lastcp, lastmsgcp, tryconvertcp, FileDirExistCP(const char *name), FileDirExistUTF8(std::string &localname, const char *name); -extern uint8_t DOS_GetAnsiAttr(void); -extern int toSetCodePage(DOS_Shell *shell, int newCP, int opt); -void MSG_Init(), JFONT_Init(), InitFontHandle(), ShutFontHandle(), DOSBox_SetSysMenu(), Load_Language(std::string name); -void DOS_EnableDriveMenu(char drv), GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused), UpdateSDLDrawTexture(); -void runBoot(const char *str), runMount(const char *str), runImgmount(const char *str), runRescan(const char *str), show_prompt(), ttf_reset(void); -void getdrivezpath(std::string &path, std::string const& dirname), drivezRegister(std::string const& path, std::string const& dir, bool usecp), UpdateDefaultPrinterFont(void); -std::string GetDOSBoxXPath(bool withexe=false); -FILE *testLoadLangFile(const char *fname); -bool CheckDBCSCP(int32_t codepage); - -#define MAXU32 0xffffffff -#include "zip.h" -#include "unzip.h" -#include "ioapi.h" -#include "zipcppstdbuf.h" - -#if defined(OS2) -#define INCL DOSFILEMGR -#define INCL_DOSERRORS -#include "os2.h" -#endif - -#if defined(WIN32) -#ifndef S_ISDIR -#define S_ISDIR(m) (((m)&S_IFMT)==S_IFDIR) -#endif -#endif - -#if defined(RISCOS) -#include -#include -#endif - -#if C_DEBUG -Bitu DEBUG_EnableDebugger(void); -#endif - -/* Microsoft likes to make POSIX library functions less convenient and your code - * less portable by nagging you to add a leading underscore to those functions. */ -#if !defined(_MSC_VER) -#define _access access -#define _strdup strdup -#endif - -class MOUSE : public Program { -public: - void Run(void) override; -}; - -void MOUSE::Run(void) { - if (cmd->FindExist("/?",false) || cmd->FindExist("/h",false)) { - WriteOut(MSG_Get("PROGRAM_MOUSE_HELP")); - return; - } - if (!Mouse_Drv) { - if (cmd->FindExist("/u",false)) - WriteOut(MSG_Get("PROGRAM_MOUSE_NOINSTALLED")); - else { - Mouse_Drv = true; - mainMenu.get_item("dos_mouse_enable_int33").check(Mouse_Drv).refresh_item(mainMenu); - WriteOut(MSG_Get("PROGRAM_MOUSE_INSTALL")); - if (cmd->FindExist("/v",false)) { - Mouse_Vertical = true; - WriteOut(MSG_Get("PROGRAM_MOUSE_VERTICAL")); - } else { - Mouse_Vertical = false; - } - mainMenu.get_item("dos_mouse_y_axis_reverse").check(Mouse_Vertical).refresh_item(mainMenu); - } - } - else { - if (cmd->FindExist("/u",false)) { - Mouse_Drv = false; - mainMenu.get_item("dos_mouse_enable_int33").check(Mouse_Drv).refresh_item(mainMenu); - WriteOut(MSG_Get("PROGRAM_MOUSE_UNINSTALL")); - } else - if (cmd->FindExist("/v",false)) { - if(!Mouse_Vertical) { - Mouse_Vertical = true; - WriteOut(MSG_Get("PROGRAM_MOUSE_VERTICAL")); - } else { - Mouse_Vertical = false; - WriteOut(MSG_Get("PROGRAM_MOUSE_VERTICAL_BACK")); - } - mainMenu.get_item("dos_mouse_y_axis_reverse").check(Mouse_Vertical).refresh_item(mainMenu); - } else - WriteOut(MSG_Get("PROGRAM_MOUSE_ERROR")); - } -} - -static void MOUSE_ProgramStart(Program * * make) { - *make=new MOUSE; -} - -void DetachFromBios(imageDisk* image) { - if (image) { - for (int index = 0; index < MAX_DISK_IMAGES; index++) { - if (imageDiskList[index] == image) { - if (index > 1) IDE_Hard_Disk_Detach(index); - imageDiskList[index]->Release(); - imageDiskChange[index] = true; - imageDiskList[index] = NULL; - } - } - } -} - -bool SwitchLanguage(int oldcp, int newcp, bool confirm) { - auto iterold = langcp_map.find(lastmsgcp), iternew = langcp_map.find(newcp); - std::string langold = iterold != langcp_map.end() ? iterold->second : "", langnew = iternew != langcp_map.end() ? iternew->second : ""; - if (loadlang && langnew.size() && strcasecmp(langold.c_str(), langnew.c_str())) { - FILE *file = testLoadLangFile(langnew.c_str()); - if (file) { - fclose(file); - std::string msg = "You have changed the active code page to " + std::to_string(newcp) + ". Do you want to load language file " + langnew + " for this code page?"; - if (!confirm || (CheckDBCSCP(oldcp) && !CheckDBCSCP(newcp)) || systemmessagebox("DOSBox-X language file", msg.c_str(), "yesno","question", 2)) { - SetVal("dosbox", "language", langnew); - Load_Language(langnew); - lastmsgcp = newcp; - return true; // Will load language file for the active codepage - } - } - } - return false; -} - -extern std::string hidefiles, dosbox_title; -extern int swapInDisksSpecificDrive; -extern bool dos_kernel_disabled, clearline; -void MSCDEX_SetCDInterface(int intNr, int forceCD); -bool FDC_UnassignINT13Disk(unsigned char drv); -bool bootguest=false, use_quick_reboot=false; -int bootdrive=-1; -uint8_t ZDRIVE_NUM = 25; -std::string msgget; -static const char* UnmountHelper(char umount) { - int i_drive; - if (umount < '0' || umount > 3+'0') - i_drive = toupper(umount) - 'A'; - else - i_drive = umount - '0'; - - if (i_drive >= DOS_DRIVES || i_drive < 0) - return MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"); - - if (i_drive < MAX_DISK_IMAGES && Drives[i_drive] == NULL && imageDiskList[i_drive] == NULL) - return MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"); - - if (i_drive >= MAX_DISK_IMAGES && Drives[i_drive] == NULL) - return MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"); - - if (i_drive <= 1) - FDC_UnassignINT13Disk(i_drive); - - msgget=MSG_Get("PROGRAM_MOUNT_UMOUNT_SUCCESS"); - if (Drives[i_drive]) { - const bool partitionMount = Drives[i_drive]->partitionMount; - const fatDrive* drive = dynamic_cast(Drives[i_drive]); - imageDisk* image = drive ? drive->loadedDisk : NULL; - const isoDrive* cdrom = dynamic_cast(Drives[i_drive]); - switch (DriveManager::UnmountDrive(i_drive)) { - case 1: return MSG_Get("PROGRAM_MOUNT_UMOUNT_NO_VIRTUAL"); - case 2: return MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS"); - } - if (image && !partitionMount) DetachFromBios(image); - if (cdrom) IDE_CDROM_Detach(i_drive); - Drives[i_drive] = nullptr; - DOS_EnableDriveMenu(i_drive+'A'); - mem_writeb(Real2Phys(dos.tables.mediaid)+(unsigned int)i_drive*dos.tables.dpb_size,0); - if (i_drive == DOS_GetDefaultDrive()) - DOS_SetDrive(ZDRIVE_NUM); - if (cdrom) - for (int drv=0; drv<2; drv++) - if (Drives[drv]) { - fatDrive *fdp = dynamic_cast(Drives[drv]); - if (fdp&&fdp->opts.mounttype==1&&toupper(umount)==fdp->el.CDROM_drive) { - msgget+=UnmountHelper('A'+drv); - size_t found=msgget.rfind("%c"); - if (found!=std::string::npos) - msgget.replace(found, 2, std::string(1, 'A'+drv)); - } - } - } - - if (i_drive < MAX_DISK_IMAGES && imageDiskList[i_drive]) { - imageDiskList[i_drive]->Release(); - imageDiskList[i_drive] = NULL; - } - if (swapInDisksSpecificDrive == i_drive) { - for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { - if (diskSwap[si] != NULL) { - diskSwap[si]->Release(); - diskSwap[si] = NULL; - } - } - swapInDisksSpecificDrive = -1; - } - - return msgget.c_str(); -} - -void MountHelper(char drive, const char drive2[DOS_PATHLENGTH], std::string const& drive_type) { - std::vector options; - DOS_Drive * newdrive; - std::string temp_line; - std::string str_size; - uint16_t sizes[4]; - uint8_t mediaid=0; - - if(drive_type=="CDROM") { - mediaid=0xF8; /* Hard Disk */ - str_size="2048,1,65535,0"; - } else { - if(drive_type=="FLOPPY") { - mediaid=0xF0; /* Floppy 1.44 media */ - str_size="512,1,2880,2880"; /* All space free */ - } else if(drive_type=="LOCAL") { - mediaid=0xF8; - str_size="512,32,0,0"; - } - } - - char number[20]; const char * scan=str_size.c_str(); - Bitu index=0; Bitu count=0; - while (*scan) { - if (*scan==',') { - number[index]=0;sizes[count++]=atoi(number); - index=0; - } else number[index++]=*scan; - scan++; - } - number[index]=0; sizes[count++]=atoi(number); - - temp_line = drive2; - if(temp_line.size() > 3 && temp_line[temp_line.size()-1]=='\\') temp_line.erase(temp_line.size()-1,1); - if (temp_line[temp_line.size()-1]!=CROSS_FILESPLIT) temp_line+=CROSS_FILESPLIT; - uint8_t bit8size=(uint8_t) sizes[1]; - - if(drive_type=="CDROM") { - int num = -1; - int error; - - int id, major, minor; - DOSBox_CheckOS(id, major, minor); - if ((id==VER_PLATFORM_WIN32_NT) && (major>5)) { - // Vista/above - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); - } else { - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); - } - newdrive = new cdromDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],0,mediaid,error,options); - std::string errmsg; - switch (error) { - case 0 : errmsg=MSG_Get("MSCDEX_SUCCESS"); break; - case 1 : errmsg=MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS"); break; - case 2 : errmsg=MSG_Get("MSCDEX_ERROR_NOT_SUPPORTED"); break; - case 3 : errmsg=MSG_Get("MSCDEX_ERROR_PATH"); break; - case 4 : errmsg=MSG_Get("MSCDEX_TOO_MANY_DRIVES"); break; - case 5 : errmsg=MSG_Get("MSCDEX_LIMITED_SUPPORT"); break; - default : errmsg=MSG_Get("MSCDEX_UNKNOWN_ERROR"); break; - } - if (error) { - systemmessagebox(error==5?"Warning":"Error",errmsg.c_str(),"ok","error", 1); - if (error!=5) { - delete newdrive; - return; - } - } - } else { - newdrive=new localDrive(temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,options); - newdrive->readonly = mountfro[drive-'A']; - } - - if (!newdrive) E_Exit("DOS:Can't create drive"); - Drives[drive-'A']=newdrive; - DOS_EnableDriveMenu(drive); - mem_writeb(Real2Phys(dos.tables.mediaid)+(drive-'A')*dos.tables.dpb_size,mediaid); - if(drive_type=="CDROM") - LOG_MSG("GUI: Drive %c is mounted as CD-ROM",drive); - else - LOG_MSG("GUI: Drive %c is mounted as local directory",drive); - if(drive == drive2[0] && strlen(drive2) == 3) { - // automatic mount - } else { - if(drive_type=="CDROM") return; - std::string label; - label = drive; - if(drive_type=="LOCAL") - label += "_DRIVE"; - else - label += "_FLOPPY"; - newdrive->SetLabel(label.c_str(),false,true); - } -} - -#if defined(WIN32) -void MenuMountDrive(char drive, const char drive2[DOS_PATHLENGTH]) { - std::vector options; - std::string str(1, drive); - std::string drive_warn; - if (Drives[drive-'A']) { - drive_warn="Drive "+str+": is already mounted. Unmount it first, and then try again."; - systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); - return; - } - if(control->SecureMode()) { - systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); - return; - } - DOS_Drive * newdrive; - std::string temp_line; - std::string str_size; - uint16_t sizes[4]; - uint8_t mediaid; - drive_warn="Do you really want to give DOSBox-X access to"; - int type=GetDriveType(drive2); - if(type==DRIVE_NO_ROOT_DIR) { - systemmessagebox("Error",("Drive "+str+": does not exist in the system.").c_str(),"ok","error", 1); - return; - } else if(type==DRIVE_CDROM) - drive_warn += " your real CD-ROM drive "; - else if(type==DRIVE_REMOVABLE) - drive_warn += drive=='A'||drive=='B'?" your real floppy drive ":" your real removable drive "; - else if(type==DRIVE_REMOTE) - drive_warn += " your real network drive "; - else - drive_warn += " your real hard drive "; - - if (mountwarning && !systemmessagebox("Warning",(drive_warn+str+"?").c_str(),"yesno","warning",1)) return; - - if(type==DRIVE_CDROM) { - mediaid=0xF8; /* Hard Disk */ - str_size="2048,1,65535,0"; - } else if(type==DRIVE_REMOVABLE && (drive=='A'||drive=='B')) { - mediaid=0xF0; /* Floppy 1.44 media */ - str_size="512,1,2880,2880"; /* All space free */ - } else { - mediaid=0xF8; - str_size="512,32,0,0"; - } - - char number[20]; const char * scan=str_size.c_str(); - Bitu index=0; Bitu count=0; - while (*scan) { - if (*scan==',') { - number[index]=0;sizes[count++]=atoi(number); - index=0; - } else number[index++]=*scan; - scan++; - } - number[index]=0; sizes[count++]=atoi(number); - uint8_t bit8size=(uint8_t) sizes[1]; - - temp_line = drive2; - int error = 0, num = -1; - if(type==DRIVE_CDROM) { - int id, major, minor; - DOSBox_CheckOS(id, major, minor); - if ((id==VER_PLATFORM_WIN32_NT) && (major>5)) { - // Vista/above - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); - } else { - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); - } - newdrive = new cdromDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],0,mediaid,error,options); - std::string errmsg; - switch (error) { - case 0 : errmsg=MSG_Get("MSCDEX_SUCCESS"); break; - case 1 : errmsg=MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS"); break; - case 2 : errmsg=MSG_Get("MSCDEX_ERROR_NOT_SUPPORTED"); break; - case 3 : errmsg=MSG_Get("MSCDEX_ERROR_PATH"); break; - case 4 : errmsg=MSG_Get("MSCDEX_TOO_MANY_DRIVES"); break; - case 5 : errmsg=MSG_Get("MSCDEX_LIMITED_SUPPORT"); break; - default : errmsg=MSG_Get("MSCDEX_UNKNOWN_ERROR"); break; - } - if (error) { - systemmessagebox(error==5?"Warning":"Error",errmsg.c_str(),"ok",error==5?"warning":"error", 1); - if (error!=5) { - delete newdrive; - return; - } - } - } else { - newdrive=new localDrive(temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,options); - newdrive->readonly = mountfro[drive-'A']; - } - - if (!newdrive) E_Exit("DOS:Can't create drive"); - if(error && (type==DRIVE_CDROM)) return; - Drives[drive-'A']=newdrive; - DOS_EnableDriveMenu(drive); - mem_writeb(Real2Phys(dos.tables.mediaid)+(drive-'A')*dos.tables.dpb_size,mediaid); - if(type == DRIVE_CDROM) LOG_MSG("GUI: Drive %c is mounted as CD-ROM %c:\\", drive, drive); - else LOG_MSG("GUI: Drive %c is mounted as local directory %c:\\", drive, drive); - if(drive == drive2[0] && strlen(drive2) == 3) { - // automatic mount - } else { - if(type == DRIVE_CDROM) return; - std::string label; - label = drive; - if(type==DRIVE_REMOVABLE && (drive=='A'||drive=='B')) - label += "_FLOPPY"; - else - label += "_DRIVE"; - newdrive->SetLabel(label.c_str(),false,true); - } -} -#endif - -std::string newstr=""; -std::string GetNewStr(const char *str) { - newstr = str?std::string(str):""; -#if defined(WIN32) - int flags = 0; -#ifdef WC_NO_BEST_FIT_CHARS - flags |= WC_NO_BEST_FIT_CHARS; -#endif - if (str&&dos.loaded_codepage!=437) { - char *temp = NULL; - wchar_t* wstr = NULL; - int reqsize = MultiByteToWideChar(CP_UTF8, 0, str, (int)(strlen(str)+1), NULL, 0); - if (reqsize>0 && (wstr = new wchar_t[reqsize]) && MultiByteToWideChar(CP_UTF8, 0, str, (int)(strlen(str)+1), wstr, reqsize)==reqsize) { - reqsize = WideCharToMultiByte(dos.loaded_codepage==808?866:(dos.loaded_codepage==859?858:(dos.loaded_codepage==872?855:(dos.loaded_codepage==951?950:dos.loaded_codepage))), flags, wstr, -1, NULL, 0, "\x07", NULL); - if (reqsize > 1 && (temp = new char[reqsize]) && WideCharToMultiByte(dos.loaded_codepage==808?866:(dos.loaded_codepage==859?858:(dos.loaded_codepage==872?855:(dos.loaded_codepage==951?950:dos.loaded_codepage))), flags, wstr, -1, (LPSTR)temp, reqsize, "\x07", NULL) == reqsize) - newstr = std::string(temp); - } - } -#endif - return newstr; -} - -void MenuBrowseCDImage(char drive, int num) { - if(control->SecureMode()) { - systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); - return; - } - - if (Drives[drive-'A']&&!strncmp(Drives[drive-'A']->GetInfo(), "isoDrive ", 9)) { -#if !defined(HX_DOS) - std::string drive_warn = "CD drive "+(dos_kernel_disabled?std::to_string(num):std::string(1, drive)+":")+" is currently mounted with the image:\n\n"+std::string(Drives[drive-'A']->GetInfo()+9)+"\n\nDo you want to change the CD image now?"; - if (!systemmessagebox("Change CD image",drive_warn.c_str(),"yesno","question", 1)) return; -#endif - } else - return; -#if !defined(HX_DOS) - char CurrentDir[512]; - std::vector options; - char * Temp_CurrentDir = CurrentDir; - getcwd(Temp_CurrentDir, 512); - char const * lTheOpenFileName; - std::string files="", fname=""; - const char *lFilterPatterns[] = {"*.iso","*.cue","*.bin","*.chd","*.mdf","*.gog","*.ins","*.inst","*.ISO","*.CUE","*.BIN","*.CHD","*.MDF","*.GOG","*.INS","*.INST" }; - const char *lFilterDescription = "CD image files (*.iso, *.cue, *.bin, *.chd, *.mdf, *.gog, *.ins, *.inst)"; - lTheOpenFileName = tinyfd_openFileDialog("Select a CD image file","", sizeof(lFilterPatterns) / sizeof(lFilterPatterns[0]),lFilterPatterns,lFilterDescription,0); - bool isempty = std::string(Drives[drive - 'A']->GetInfo() + 9) == "empty"; - if (lTheOpenFileName) { - isoDrive *cdrom = dynamic_cast(Drives[drive-'A']); - DOS_Drive *newDrive = NULL; - int error = -1; - uint8_t mediaid = 0xF8; - if (cdrom && dos_kernel_disabled) { - cdrom->setFileName(lTheOpenFileName); - if(isempty) { - newDrive = new isoDrive(drive, lTheOpenFileName, mediaid, error, options); - if(error) { - delete newDrive; - systemmessagebox("Error", "Could not mount the selected CD image.", "ok", "error", 1); - chdir(Temp_CurrentDir); - return; - } - delete cdrom; - cdrom = dynamic_cast(newDrive); - Drives[drive - 'A'] = cdrom; - } - } else { - newDrive = new isoDrive(drive, lTheOpenFileName, mediaid, error, options); - if (error) { - delete newDrive; - systemmessagebox("Error","Could not mount the selected CD image.","ok","error", 1); - chdir( Temp_CurrentDir ); - return; - } - cdrom = dynamic_cast(newDrive); - Drives[drive - 'A'] = cdrom; - } - if ((!isempty || !dos_kernel_disabled) && cdrom) DriveManager::ChangeDisk(drive-'A', cdrom); - } - chdir( Temp_CurrentDir ); -#endif -} - -void MenuBrowseFDImage(char drive, int num, int type) { - if(control->SecureMode()) { - systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); - return; - } - - if (type==-1 || (Drives[drive-'A'] && !strncmp(Drives[drive-'A']->GetInfo(), "fatDrive ", 9))) { -#if !defined(HX_DOS) - std::string image = type==1||(type==-1&&dynamic_cast(imageDiskList[drive-'A'])!=NULL)?"El Torito floppy image":(type==2||(type==-1&&dynamic_cast(imageDiskList[drive-'A'])!=NULL)?"RAM floppy image":(type==-1?imageDiskList[drive-'A']->diskname.c_str():Drives[drive-'A']->GetInfo()+9)); - std::string drive_warn = "Floppy drive "+(type==-1?std::string(1, drive-'A'+'0'):(dos_kernel_disabled?std::to_string(num):std::string(1, drive)+":"))+" is currently mounted with the image:\n\n"+image+"\n\nDo you want to change the floppy disk image now?"; - if (!systemmessagebox("Change floppy disk image",drive_warn.c_str(),"yesno","question", 1)) return; -#endif - } else - return; -#if !defined(HX_DOS) - char CurrentDir[512]; - char * Temp_CurrentDir = CurrentDir; - getcwd(Temp_CurrentDir, 512); - char const * lTheOpenFileName; - std::string files="", fname=""; - const char *lFilterPatterns[] = {"*.ima","*.img","*.xdf","*.fdi","*.hdm","*.nfd","*.d88","*.IMA","*.IMG","*.XDF","*.FDI","*.HDM","*.NFD","*.D88"}; - const char *lFilterDescription = "Floppy image files (*.ima, *.img, *.xdf, *.fdi, *.hdm, *.nfd, *.d88)"; - lTheOpenFileName = tinyfd_openFileDialog("Select a floppy image file","",sizeof(lFilterPatterns)/sizeof(lFilterPatterns[0]), lFilterPatterns, lFilterDescription, 0); - - if (lTheOpenFileName) { - //uint8_t mediaid = 0xF0; UNUSED - std::vector options; - if (mountiro[drive-'A']) options.emplace_back("readonly"); - fatDrive *newDrive = new fatDrive(lTheOpenFileName, 0, 0, 0, 0, options); - if (!newDrive->created_successfully) { - systemmessagebox("Error","Could not mount the selected floppy disk image.","ok","error", 1); - chdir( Temp_CurrentDir ); - return; - } - if (newDrive) { - if (type>-1) - DriveManager::ChangeDisk(drive-'A', newDrive); - else if (newDrive->loadedDisk) { - if (imageDiskList[drive-'A']) { - imageDiskList[drive-'A']->Release(); - imageDiskList[drive-'A'] = newDrive->loadedDisk; - //imageDiskList[drive-'A']->Addref(); - imageDiskChange[drive-'A'] = true; - } - if (swapInDisksSpecificDrive == drive-'A' && diskSwap[swapPosition]) { - diskSwap[swapPosition]->Release(); - diskSwap[swapPosition] = newDrive->loadedDisk; - diskSwap[swapPosition]->Addref(); - } - } - } - } - chdir( Temp_CurrentDir ); -#endif -} - -void MenuBrowseImageFile(char drive, bool arc, bool boot, bool multiple) { - std::string str(1, drive); - std::string drive_warn; - if (Drives[drive-'A']&&!boot) { - drive_warn="Drive "+str+": is already mounted. Unmount it first, and then try again."; - systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); - return; - } - if(control->SecureMode()) { - systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); - return; - } - if (dos_kernel_disabled) - return; -#if !defined(HX_DOS) - char CurrentDir[512]; - char * Temp_CurrentDir = CurrentDir; - getcwd(Temp_CurrentDir, 512); - char const * lTheOpenFileName; - std::string files="", fname=""; - if (arc) { - const char *lFilterPatterns[] = {"*.zip","*.7z","*.ZIP","*.7Z"}; - const char *lFilterDescription = "Archive files (*.zip, *.7z)"; - lTheOpenFileName = tinyfd_openFileDialog(("Select an archive file for Drive "+str+":").c_str(),"", sizeof(lFilterPatterns) / sizeof(lFilterPatterns[0]),lFilterPatterns,lFilterDescription,0); - if (lTheOpenFileName) fname = GetNewStr(lTheOpenFileName); - } else { - const char *lFilterPatterns[] = {"*.ima","*.img","*.vhd","*.fdi","*.hdi","*.nfd","*.nhd","*.d88","*.hdm","*.xdf","*.iso","*.cue","*.bin","*.chd","*.mdf","*.gog","*.ins","*.ccd","*.inst","*.IMA","*.IMG","*.VHD","*.FDI","*.HDI","*.NFD","*.NHD","*.D88","*.HDM","*.XDF","*.ISO","*.CUE","*.BIN","*.CHD","*.MDF","*.GOG","*.INS","*.CCD","*.INST"}; - const char *lFilterDescription = "Disk/CD image files"; - lTheOpenFileName = tinyfd_openFileDialog(((multiple?"Select image file(s) for Drive ":"Select an image file for Drive ")+str+":").c_str(),"", sizeof(lFilterPatterns) / sizeof(lFilterPatterns[0]),lFilterPatterns,lFilterDescription,multiple?1:0); - if (lTheOpenFileName) fname = "\"" + GetNewStr(lTheOpenFileName) + "\""; - if (multiple&&fname.size()) { - files = std::regex_replace(fname, std::regex("\\|"), "\" \""); - } - while (multiple&&lTheOpenFileName&&systemmessagebox("Mount image files","Do you want to mount more image file(s)?","yesno", "question", 1)) { - lTheOpenFileName = tinyfd_openFileDialog(("Select image file(s) for Drive "+str+":").c_str(),"", sizeof(lFilterPatterns) / sizeof(lFilterPatterns[0]),lFilterPatterns,lFilterDescription,multiple?1:0); - if (lTheOpenFileName) { - fname = "\"" + GetNewStr(lTheOpenFileName) + "\""; - files = files + " " + std::regex_replace(fname, std::regex("\\|"), "\" \""); - } - } - } - - if (fname.size()||files.size()) { - char type[15]; - if (!arc&&!files.size()) { - char ext[5] = ""; - if (fname.size()>4) - strcpy(ext, fname.substr(fname.size()-4).c_str()); - if(!strcasecmp(ext,".ima")) - strcpy(type,"-t floppy "); - else if((!strcasecmp(ext,".iso")) || (!strcasecmp(ext,".cue")) || (!strcasecmp(ext,".bin")) || (!strcasecmp(ext,".chd")) || (!strcasecmp(ext,".mdf")) || (!strcasecmp(ext,".gog")) || (!strcasecmp(ext,".ins")) || (!strcasecmp(ext, ".inst"))) - strcpy(type,"-t iso "); - else - strcpy(type,""); - } else - *type=0; - char mountstring[CROSS_LEN*4+20]; - if (files.size()>CROSS_LEN*4) { - systemmessagebox("Error","The path for the file(s) to mount is too long.","ok","error", 1); - return; - } - strcpy(mountstring,type); - char temp_str[3] = { 0,0,0 }; - temp_str[0]=drive; - temp_str[1]=' '; - strcat(mountstring,temp_str); - //if (!multiple) strcat(mountstring,"\""); - strcat(mountstring,files.size()?files.c_str():fname.c_str()); - //if(!multiple) strcat(mountstring, "\""); - if(mountiro[drive - 'A']) strcat(mountstring, " -ro"); - if(boot) { - strcat(mountstring, " -u"); - mountstring[0] = drive - 'A' + '0'; - runImgmount(mountstring); // mount by drive number - std::string bootstr = "-Q "; - bootstr += drive; - bootstr += ':'; - runBoot(bootstr.c_str()); - std::string drive_warn = "Drive " + std::string(1, drive) + ": failed to boot."; - systemmessagebox("Error", drive_warn.c_str(), "ok", "error", 1); - bootstr = "-u "; - bootstr += drive - 'A' + '0'; - runImgmount(bootstr.c_str()); // unmount if boot failed - return; - } - if(arc) { - strcat(mountstring," -q"); - runMount(mountstring); - } else { - qmount=true; - runImgmount(mountstring); - qmount=false; - } - chdir( Temp_CurrentDir ); - if (!Drives[drive - 'A']) { - drive_warn="Drive "+str+": failed to mount."; - systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); - return; - } else if (multiple) { - systemmessagebox("Information",("Mounted disk images to Drive "+std::string(1,drive)+(dos.loaded_codepage==437?":\n"+files:".")+(mountiro[drive-'A']?"\n(Read-only mode)":"")).c_str(),"ok","info", 1); - } else if (lTheOpenFileName) { - systemmessagebox("Information",(std::string(arc?"Mounted archive":"Mounted disk image")+" to Drive "+std::string(1,drive)+":\n"+std::string(lTheOpenFileName)+(arc||mountiro[drive-'A']?"\n(Read-only mode)":"")).c_str(),"ok","info", 1); - } - } - chdir( Temp_CurrentDir ); -#endif -} - -void MenuBrowseFolder(char drive, std::string const& drive_type) { - std::string str(1, drive); - if (Drives[drive-'A']) { - std::string drive_warn="Drive "+str+": is already mounted. Unmount it first, and then try again."; - systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); - return; - } - if(control->SecureMode()) { - systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); - return; - } -#if !defined(HX_DOS) - std::string title = "Select a drive/directory to mount for Drive "+str+":"; - if(drive_type=="CDROM") - title += " CD-ROM\nMounting a directory as CD-ROM gives an limited support"; - else if(drive_type=="FLOPPY") - title += " as Floppy"; - else if(drive_type=="LOCAL") - title += " as Local"; - char const * lTheSelectFolderName = tinyfd_selectFolderDialog(title.c_str(), NULL); - if (lTheSelectFolderName) { - MountHelper(drive,GetNewStr(lTheSelectFolderName).c_str(),drive_type); - if (Drives[drive-'A']) systemmessagebox("Information",("Drive "+std::string(1,drive)+" is now mounted to:\n"+std::string(lTheSelectFolderName)).c_str(),"ok","info", 1); - } -#endif -} - -void MenuUnmountDrive(char drive) { - if (!Drives[drive-'A']) { - std::string drive_warn="Drive "+std::string(1, drive)+": is not yet mounted."; - systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); - return; - } - UnmountHelper(drive); -} - -void MenuBootDrive(char drive) { - if(control->SecureMode()) { - systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); - return; - } - char str[] = "-Q A:"; - str[3]=drive; - runBoot(str); - std::string drive_warn="Drive "+std::string(1, drive)+": failed to boot."; - systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); -} - -void MenuBrowseProgramFile() { - if(control->SecureMode()) { - systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); - return; - } - if (dos_kernel_disabled) - return; - std::string drive_warn; - DOS_MCB mcb(dos.psp()-1); - static char psp_name[9]; - mcb.GetFileName(psp_name); - if(strlen(psp_name)&&strcmp(psp_name, "COMMAND")) { - drive_warn=strcmp(psp_name, "4DOS")?"Another program is already running.":"Another shell is currently running."; - systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); - return; - } - -#if !defined(HX_DOS) - char drv=' '; - for (int i=2; i options; - void Move_Z(char new_z) { - char newz_drive = (char)toupper(new_z); - int i_newz = (int)newz_drive - (int)'A'; - if (i_newz >= 0 && i_newz < DOS_DRIVES) { - if(Drives[i_newz]) { - WriteOut("Drive %c is already in use\n", new_z); - return; - } - /* remap drives */ - Drives[i_newz] = Drives[ZDRIVE_NUM]; - Drives[ZDRIVE_NUM] = nullptr; - DOS_EnableDriveMenu(i_newz + 'A'); - DOS_EnableDriveMenu(ZDRIVE_NUM + 'A'); - if (!first_shell) return; //Should not be possible - /* Update environment */ - std::string line = ""; - char ppp[2] = { newz_drive,0 }; - std::string tempenv = ppp; tempenv += ":\\"; - std::string tempenvZ = std::string(1, 'A'+ZDRIVE_NUM); tempenvZ += ":\\"; - std::string tempenvz = std::string(1, 'a'+ZDRIVE_NUM); tempenvz += ":\\"; - if (first_shell->GetEnvStr("PATH", line)) { - std::string::size_type idx = line.find('='); - std::string value = line.substr(idx + 1, std::string::npos); - while ((idx = value.find(tempenvZ)) != std::string::npos || - (idx = value.find(tempenvz)) != std::string::npos) - value.replace(idx, 3, tempenv); - line = value; - } - if (!line.size()) line = tempenv; - first_shell->SetEnv("PATH", line.c_str()); - tempenv += "COMMAND.COM"; - first_shell->SetEnv("COMSPEC", tempenv.c_str()); - - /* Update batch file if running from Z: (very likely: autoexec) */ - if (first_shell->bf) { - std::string& name = first_shell->bf->filename; - if (name.length() > 2 && name[0] == 'A'+ZDRIVE_NUM && name[1] == ':') name[0] = newz_drive; - } - /* Change the active drive */ - if (DOS_GetDefaultDrive() == ZDRIVE_NUM) DOS_SetDrive(i_newz); - ZDRIVE_NUM = i_newz; - } - else - WriteOut("Drive %c is not a valid drive\n", new_z); - } - void ListMounts(bool quiet, bool local) { - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; - /* Command uses dta so set it to our internal dta */ - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - - if (!quiet) { - WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_1")); - WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_FORMAT"),MSG_Get("DRIVE"),MSG_Get("TYPE"),MSG_Get("LABEL")); - } - int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - if (!cols) cols=80; - if (!quiet) { - for(int p = 1;p < cols;p++) WriteOut("-"); - WriteOut("\n"); - } - bool none=true; - for (int d = 0;d < DOS_DRIVES;d++) { - if (!Drives[d]) continue; - if (local && strncasecmp("local ", Drives[d]->GetInfo(), 6)) continue; - if (quiet) { - WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"), 'A'+d, Drives[d]->GetInfo()+(local && !strncasecmp("local ", Drives[d]->GetInfo(), 6)?16:0)); - continue; - } - char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; - bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); - if (ret) { - dta.GetResult(name,lname,size,hsize,date,time,attr); - DOS_FindNext(); //Mark entry as invalid - } else name[0] = 0; - - /* Change 8.3 to 11.0 */ - const char* dot = strchr(name, '.'); - if(dot && (dot - name == 8) ) { - name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; - } - - root[1] = 0; //This way, the format string can be reused. - WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name); - none=false; - } - if (none&&!quiet) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); - dos.dta(save_dta); - } - - void Run(void) override { - DOS_Drive *newdrive = NULL; - std::string label; - std::string umount; - std::string newz; - bool quiet=false; - char drive; - - //Hack To allow long commandlines - ChangeToLongCmd(); - /* Parse the command line */ - /* if the command line is empty show current mounts */ - if (!cmd->GetCount()) { - ListMounts(false, false); - return; - } - - /* In secure mode don't allow people to change mount points. - * Neither mount nor unmount */ - if(control->SecureMode()) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); - return; - } - if (cmd->FindExist("/examples")||cmd->FindExist("-examples")) { - resetcolor = true; -#if defined (WIN32) || defined(OS2) - WriteOut(MSG_Get("PROGRAM_MOUNT_EXAMPLE"),"d:\\dosprogs","d:\\dosprogs","\"d:\\dos games\"","\"d:\\dos games\"","d:\\dosprogs","d:\\dosprogs","d:\\dosprogs","d:\\dosprogs","d:\\dosprogs","d:\\dosprogs","d:\\overlaydir"); -#else - WriteOut(MSG_Get("PROGRAM_MOUNT_EXAMPLE"),"~/dosprogs","~/dosprogs","\"~/dos games\"","\"~/dos games\"","~/dosprogs","~/dosprogs","~/dosprogs","~/dosprogs","~/dosprogs","~/dosprogs","~/overlaydir"); -#endif - return; - } - - //look for -o options - bool local = false; - { - std::string s; - while (cmd->FindString("-o", s, true)) { - if (!strcasecmp(s.c_str(), "local")) local = true; - options.push_back(s); - } - if (local && !cmd->GetCount()) { - ListMounts(false, true); - return; - } - } - - if (cmd->FindExist("-q",true)) { - quiet = true; - if (!cmd->GetCount()) { - ListMounts(true, local); - return; - } - } - - bool path_relative_to_last_config = false; - if (cmd->FindExist("-pr",true)) path_relative_to_last_config = true; - - /* Check for unmounting */ - if (cmd->FindString("-u",umount,false)) { - const char *msg=UnmountHelper(umount[0]); - if (!quiet) WriteOut(msg, toupper(umount[0])); - return; - } - - /* Check for moving Z: */ - /* Only allowing moving it once. It is merely a convenience added for the wine team */ - if (cmd->FindString("-z", newz,false)) { - if (ZDRIVE_NUM != newz[0]-'A') Move_Z(newz[0]); - return; - } - /* Show list of cdroms */ - if (cmd->FindExist("-cd",false)) { - int num = SDL_CDNumDrives(); - if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_CDROMS_FOUND"),num); - for (int i=0; iFindExist("-nocachedir",true)) - nocachedir = true; - - if (cmd->FindExist("-nl",true)) - nextdrive = true; - - bool readonly = false; - if (cmd->FindExist("-ro",true)) - readonly = true; - if (cmd->FindExist("-rw",true)) - readonly = false; - - std::string type="dir"; - cmd->FindString("-t",type,true); - std::transform(type.begin(), type.end(), type.begin(), ::tolower); - bool iscdrom = (type =="cdrom"); //Used for mscdex bug cdrom label name emulation - bool exist = false, removed = false; - if (type=="floppy" || type=="dir" || type=="cdrom" || type =="overlay") { - uint16_t sizes[4] = { 0 }; - uint8_t mediaid; - std::string str_size = ""; - if (type=="floppy") { - str_size="512,1,2880,2880"; - mediaid=0xF0; /* Floppy 1.44 media */ - } else if (type=="dir" || type == "overlay") { - // 512*32*32765==~500MB total size - // 512*32*16000==~250MB total free size - str_size="512,32,0,0"; - mediaid=0xF8; /* Hard Disk */ - } else if (type=="cdrom") { - str_size="2048,1,65535,0"; - mediaid=0xF8; /* Hard Disk */ - } else { - if (!quiet) WriteOut(MSG_Get("PROGAM_MOUNT_ILL_TYPE"),type.c_str()); - return; - } - /* Parse the free space in mb's (kb's for floppies) */ - std::string mb_size; - if(cmd->FindString("-freesize",mb_size,true)) { - char teststr[1024]; - uint16_t freesize = static_cast(atoi(mb_size.c_str())); - if (type=="floppy") { - // freesize in kb - sprintf(teststr,"512,1,2880,%d",freesize*1024/(512*1)>2880?2880:freesize*1024/(512*1)); - } else { - //if (freesize>1919) freesize=1919; - uint16_t numc=type=="cdrom"?1:32; - uint32_t total_size_cyl=32765; - uint32_t tmp=(uint32_t)freesize*1024*1024/(type=="cdrom"?2048*1:512*32); - if(tmp > 65534) numc = type == "cdrom" ? (tmp + 65535) / 65536 : 64; - uint32_t free_size_cyl=(uint32_t)freesize*1024*1024/(numc*(type=="cdrom"?2048:512)); - if (free_size_cyl>65534) free_size_cyl=65534; - if (total_size_cyl65534) total_size_cyl=65534; - sprintf(teststr,type=="cdrom"?"2048,%u,%u,%u":"512,%u,%u,%u",numc,total_size_cyl,free_size_cyl); - } - str_size=teststr; - } - - cmd->FindString("-size",str_size,true); - char number[21] = { 0 }; const char* scan = str_size.c_str(); - Bitu index = 0; Bitu count = 0; - /* Parse the str_size string */ - while (*scan && index < 20 && count < 4) { - if (*scan==',') { - number[index] = 0; - sizes[count++] = atoi(number); - index = 0; - } else number[index++] = *scan; - scan++; - } - if (count < 4) { - number[index] = 0; //always goes correct as index is max 20 at this point. - sizes[count] = atoi(number); - } - - // get the drive letter - cmd->FindCommand(1,temp_line); - if ((temp_line.size() > 2) || ((temp_line.size()>1) && (temp_line[1]!=':'))) goto showusage; - int i_drive = toupper(temp_line[0]); - if (!isalpha(i_drive)) goto showusage; - if ((i_drive - 'A') >= DOS_DRIVES || (i_drive - 'A') < 0) goto showusage; - if (!cmd->FindCommand(2,temp_line)) { - if (Drives[i_drive - 'A']) { - const char *info = Drives[i_drive - 'A']->GetInfo(); - if (!quiet) - WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"), i_drive, info+(local&&!strncasecmp("local ", info, 6)?16:0)); - else if (local&&!strncasecmp("local ", info, 6)) - WriteOut("%s\n", info+16); - else if (!local) - WriteOut("%s\n", info); - } else if (!quiet) - WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"), i_drive); - return; - } - if (!temp_line.size()) goto showusage; - if (cmd->FindExist("-u",true)) { - bool curdrv = toupper(i_drive)-'A' == DOS_GetDefaultDrive(); - const char *msg=UnmountHelper(i_drive); - if(!quiet) WriteOut(msg, toupper(i_drive)); - if(!cmd->FindCommand(2, temp_line) || !temp_line.size()) return; - if(curdrv && toupper(i_drive) - 'A' != DOS_GetDefaultDrive()) removed = true; - } - drive = static_cast(i_drive); - if (type == "overlay") { - //Ensure that the base drive exists: - if (!Drives[drive-'A']) { - if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_NO_BASE")); - return; - } - } else if (Drives[drive-'A']) { - bool found = false; - if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_ALREADY_MOUNTED"),drive,Drives[drive-'A']->GetInfo()); - if (nextdrive) - for (int i=drive-'A'+1; iconfigfiles.size() && !Cross::IsPathAbsolute(temp_line)) { - std::string lastconfigdir(control->configfiles[control->configfiles.size()-1]); - std::string::size_type pos = lastconfigdir.rfind(CROSS_FILESPLIT); - if(pos == std::string::npos) pos = 0; //No directory then erase string - lastconfigdir.erase(pos); - if (lastconfigdir.length()) temp_line = lastconfigdir + CROSS_FILESPLIT + temp_line; - } - bool is_physfs = temp_line.find(':',((temp_line[0]|0x20) >= 'a' && (temp_line[0]|0x20) <= 'z')?2:0) != std::string::npos; - struct stat test; - //Win32 : strip tailing backslashes - //os2: some special drive check - //rest: substitute ~ for home - bool failed = false; - - (void)failed;// MAY BE UNUSED - -#if defined (RISCOS) - // If the user provided a RISC OS style path, convert it to a Unix style path - // TODO: Disable UnixLib's automatic path conversion and use RISC OS style paths internally? - if (temp_line.find('$',0) != std::string::npos) { - char fname[PATH_MAX]; - is_physfs = false; - __unixify_std(temp_line.c_str(), fname, sizeof(fname), 0); - temp_line = fname; - } -#endif - -#if defined (WIN32) || defined(OS2) - // Windows: Workaround for LaunchBox - if (is_physfs && temp_line.size()>4 && temp_line[0]=='\'' && toupper(temp_line[1])>='A' && toupper(temp_line[1])<='Z' && temp_line[2]==':' && (temp_line[3]=='/' || temp_line[3]=='\\') && temp_line.back()=='\'') { - temp_line = temp_line.substr(1, temp_line.size()-2); - is_physfs = temp_line.find(':',((temp_line[0]|0x20) >= 'a' && (temp_line[0]|0x20) <= 'z')?2:0) != std::string::npos; - } else if (is_physfs && temp_line.size()>3 && temp_line[0]=='\'' && toupper(temp_line[1])>='A' && toupper(temp_line[1])<='Z' && temp_line[2]==':' && (temp_line[3]=='/' || temp_line[3]=='\\')) { - std::string line=trim((char *)cmd->GetRawCmdline().c_str()); - std::size_t space=line.find(' '); - if (space!=std::string::npos) { - line=trim((char *)line.substr(space).c_str()); - std::size_t found=line.back()=='\''?line.find_last_of('\''):line.rfind("' "); - if (found!=std::string::npos&&found>2) { - temp_line=line.substr(1, found-1); - is_physfs = temp_line.find(':',((temp_line[0]|0x20) >= 'a' && (temp_line[0]|0x20) <= 'z')?2:0) != std::string::npos; - } - } - } -#else - // Linux: Convert backslash to forward slash - if (!is_physfs && temp_line.size() > 0) { - for (size_t i=0;i < temp_line.size();i++) { - if (temp_line[i] == '\\') - temp_line[i] = '/'; - } - } -#endif - - bool useh = false; -#if defined (WIN32) - ht_stat_t htest; -#else - struct stat htest; -#endif -#if defined (WIN32) || defined(OS2) - /* Removing trailing backslash if not root dir so stat will succeed */ - if(temp_line.size() > 3 && temp_line[temp_line.size()-1]=='\\') temp_line.erase(temp_line.size()-1,1); - if(temp_line.size() == 2 && toupper(temp_line[0])>='A' && toupper(temp_line[0])<='Z' && temp_line[1]==':') temp_line.append("\\"); - if(temp_line.size() > 4 && temp_line[0] == '\\' && temp_line[1] == '\\' && temp_line[2] != '\\' && std::count(temp_line.begin() + 3, temp_line.end(), '\\') == 1) temp_line.append("\\"); - notrycp = true; - const host_cnv_char_t* host_name = CodePageGuestToHost(temp_line.c_str()); - notrycp = false; - if (!is_physfs && stat(temp_line.c_str(),&test)) { -#endif -#if defined(WIN32) - if (host_name == NULL || ht_stat(host_name, &htest)) failed = true; - useh = true; - } else if (!is_physfs && tryconvertcp && _waccess(host_name,0) && dos.loaded_codepage == 437) { - uint16_t cp = GetACP(), cpbak = dos.loaded_codepage; -#if defined(USE_TTF) - if ((ttf.inUse&&(cp<1250||cp>1259)&&cp!=437&&isSupportedCP(cp))||(!ttf.inUse&&(cp==932||cp==936||cp==949||cp==950||cp==951))) -#else - if (cp==932||cp==936||cp==949||cp==950||cp==951) -#endif - { - cpbak = dos.loaded_codepage; - dos.loaded_codepage = cp; - host_name = CodePageGuestToHost(temp_line.c_str()); - char str[150]; - - sprintf(str, "Drive %c: may require code page %d to be properly accessed.\n\nDo you want to change the current code page to %d now?\n", drive, cp, cp); - if (!host_name || ht_stat(host_name, &htest) || _waccess(host_name,0) || !systemmessagebox("Changing code page",str,"yesno","question",1)) - dos.loaded_codepage = cpbak; -#if defined(USE_TTF) - else if (ttf.inUse) { - dos.loaded_codepage = cpbak; - toSetCodePage(NULL, cp, -1); - } -#endif - else { - MSG_Init(); - DOSBox_SetSysMenu(); - if (isDBCSCP()) { - ShutFontHandle(); - InitFontHandle(); - JFONT_Init(); - } - SetupDBCSTable(); - runRescan("-A -Q"); -#if C_OPENGL && DOSBOXMENU_TYPE == DOSBOXMENU_SDLDRAW - if (OpenGL_using() && control->opt_lang.size() && lastcp && lastcp != dos.loaded_codepage) - UpdateSDLDrawTexture(); -#endif - } - SwitchLanguage(cpbak, cp, false); - } - } -#elif defined (OS2) - if (temp_line.size() <= 2) // Seems to be a drive. - { - failed = true; - HFILE cdrom_fd = 0; - ULONG ulAction = 0; - - APIRET rc = DosOpen((unsigned char*)temp_line.c_str(), &cdrom_fd, &ulAction, 0L, FILE_NORMAL, OPEN_ACTION_OPEN_IF_EXISTS, - OPEN_FLAGS_DASD | OPEN_SHARE_DENYNONE | OPEN_ACCESS_READONLY, 0L); - DosClose(cdrom_fd); - if (rc != NO_ERROR && rc != ERROR_NOT_READY) - { - failed = true; - } else { - failed = false; - } - } - } -#else - if (!is_physfs && stat(temp_line.c_str(),&test)) { - failed = true; - Cross::ResolveHomedir(temp_line); - //Try again after resolving ~ - if(!stat(temp_line.c_str(),&test)) failed = false; - } -#endif - if(failed) { - if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_ERROR_1"),temp_line.c_str()); - return; - } - /* Not a switch so a normal directory/file */ - if (!is_physfs && !S_ISDIR(useh?htest.st_mode:test.st_mode)) { -#ifdef OS2 - HFILE cdrom_fd = 0; - ULONG ulAction = 0; - - APIRET rc = DosOpen((unsigned char*)temp_line.c_str(), &cdrom_fd, &ulAction, 0L, FILE_NORMAL, OPEN_ACTION_OPEN_IF_EXISTS, - OPEN_FLAGS_DASD | OPEN_SHARE_DENYNONE | OPEN_ACCESS_READONLY, 0L); - DosClose(cdrom_fd); - if (rc != NO_ERROR && rc != ERROR_NOT_READY) -#endif - { - is_physfs = true; - temp_line.insert(0, 1, ':'); - /*if (!quiet) { - WriteOut(MSG_Get("PROGRAM_MOUNT_ERROR_2"),temp_line.c_str()); - if (temp_line.length()>4) { - char ext[5]; - strncpy(ext, temp_line.substr(temp_line.length()-4).c_str(), 4); - ext[4]=0; - if (!strcasecmp(ext, ".iso")||!strcasecmp(ext, ".cue")||!strcasecmp(ext, ".bin")||!strcasecmp(ext, ".chd")||!strcasecmp(ext, ".mdf")||!strcasecmp(ext, ".ima")||!strcasecmp(ext, ".img")||!strcasecmp(ext, ".vhd")||!strcasecmp(ext, ".hdi")) - WriteOut(MSG_Get("PROGRAM_MOUNT_IMGMOUNT"),temp_line.c_str()); - } - } - return;*/ - } - } - - if (temp_line[temp_line.size()-1]!=CROSS_FILESPLIT) temp_line+=CROSS_FILESPLIT; - uint8_t bit8size=(uint8_t) sizes[1]; - exist = drive - 'A' < DOS_DRIVES && drive - 'A' >= 0 && Drives[drive - 'A']; - if (type=="cdrom") { - int num = -1; - cmd->FindInt("-usecd",num,true); - int error = 0; - if (cmd->FindExist("-aspi",false)) { - MSCDEX_SetCDInterface(CDROM_USE_ASPI, num); - } else if (cmd->FindExist("-ioctl_dio",false)) { - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); - } else if (cmd->FindExist("-ioctl_dx",false)) { - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); -#if defined (WIN32) - } else if (cmd->FindExist("-ioctl_mci",false)) { - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_MCI, num); -#endif - } else if (cmd->FindExist("-noioctl",false)) { - MSCDEX_SetCDInterface(CDROM_USE_SDL, num); - } else { -#if defined (WIN32) - int id, major, minor; - DOSBox_CheckOS(id, major, minor); - if ((id==VER_PLATFORM_WIN32_NT) && (major>5)) { - // Vista/above - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); - } else { - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); - } -#else - MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); -#endif - } - if (is_physfs) - newdrive = new physfscdromDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],0,mediaid,error,options); - else - newdrive = new cdromDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,error,options); - // Check Mscdex, if it worked out... - if(!quiet) - switch(error) { - case 0: WriteOut(MSG_Get("MSCDEX_SUCCESS")); break; - case 1: WriteOut(MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS")); break; - case 2: WriteOut(MSG_Get("MSCDEX_ERROR_NOT_SUPPORTED")); break; - case 3: WriteOut(MSG_Get("MSCDEX_ERROR_PATH")); break; - case 4: WriteOut(MSG_Get("MSCDEX_TOO_MANY_DRIVES")); break; - case 5: WriteOut(MSG_Get("MSCDEX_LIMITED_SUPPORT")); break; - case 10: WriteOut(MSG_Get("PROGRAM_MOUNT_PHYSFS_ERROR")); WriteOut(MSG_Get("PROGRAM_MOUNT_IMGMOUNT")); break; - default: WriteOut(MSG_Get("MSCDEX_UNKNOWN_ERROR")); break; - } - if (error && error!=5) { - delete newdrive; - return; - } - } else { - /* Give a warning when mount c:\ or the / */ - if (mountwarning && !quiet && !nowarn) { -#if defined (WIN32) || defined(OS2) - if( (temp_line == "c:\\") || (temp_line == "C:\\") || - (temp_line == "c:/") || (temp_line == "C:/") ) - WriteOut(MSG_Get("PROGRAM_MOUNT_WARNING_WIN")); -#else - if(temp_line == "/") WriteOut(MSG_Get("PROGRAM_MOUNT_WARNING_OTHER")); -#endif - } - if (is_physfs) { - int error = 0; - newdrive=new physfsDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,error,options); - if (error) { - if (!quiet) {WriteOut(MSG_Get("PROGRAM_MOUNT_PHYSFS_ERROR"));WriteOut(MSG_Get("PROGRAM_MOUNT_IMGMOUNT"));} - delete newdrive; - return; - } - } else if(type == "overlay") { - physfsDrive* pdp = dynamic_cast(Drives[drive-'A']); - physfscdromDrive* pcdp = dynamic_cast(Drives[drive-'A']); - if (pdp && !pcdp) { - if (pdp->setOverlaydir(temp_line.c_str())) - WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_STATUS"),(temp_line+(temp_line.size()&&temp_line.back()!=CROSS_FILESPLIT?std::string(1, CROSS_FILESPLIT):"")+std::string(1, drive)+"_DRIVE").c_str(),drive); - else - WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_ERROR")); - return; - } - localDrive* ldp = dynamic_cast(Drives[drive-'A']); - cdromDrive* cdp = dynamic_cast(Drives[drive-'A']); - if(!ldp || cdp || pcdp) { - if(!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_INCOMPAT_BASE")); - return; - } - std::string base = ldp->getBasedir(); - uint8_t o_error = 0; - newdrive = new Overlay_Drive(base.c_str(),temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,o_error,options); - //Erase old drive on success - if (newdrive) { - if (o_error) { - if (quiet) {delete newdrive;return;} - if (o_error == 1) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_MIXED_BASE")); - else if (o_error == 2) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_SAME_AS_BASE")); - else WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_ERROR")); - delete newdrive; - return; - } else { - Overlay_Drive* odrive=dynamic_cast(newdrive); - if (odrive!=NULL) { - odrive->ovlnocachedir = nocachedir; - odrive->ovlreadonly = readonly; - } - } - - //Copy current directory if not marked as deleted. - if (newdrive->TestDir(ldp->curdir)) { - strcpy(newdrive->curdir,ldp->curdir); - } - - if (Drives[drive-'A'] != NULL) { - if (dynamic_cast(Drives[drive-'A']) != NULL) { /* Yeah, this relies on RTTI but it's probably worth it */ - /* Let the user know in case experience with other OSes or emulators leads them to think - * that they can "stack" overlays by mounting multiple times. */ - WriteOut("Existing overlay has been replaced with new overlay.\n"); - } - delete Drives[drive-'A']; - Drives[drive-'A'] = nullptr; - } - } else { - if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_ERROR")); - return; - } - } else { - newdrive=new localDrive(temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,options); - newdrive->nocachedir = nocachedir; - newdrive->readonly = readonly; - } - } - } else { - if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_ILL_TYPE"),type.c_str()); - return; - } - if (!newdrive) E_Exit("DOS:Can't create drive"); - Drives[drive-'A']=newdrive; - if (removed && !exist) DOS_SetDefaultDrive(drive-'A'); - DOS_EnableDriveMenu(drive); - /* Set the correct media byte in the table */ - mem_writeb(Real2Phys(dos.tables.mediaid)+((unsigned int)drive-'A')*dos.tables.dpb_size,newdrive->GetMediaByte()); - lastmount = drive; - if (!quiet) { - if (type != "overlay") WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"),drive,newdrive->GetInfo()); - else WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_STATUS"),temp_line.c_str(),drive); - } - /* check if volume label is given and don't allow it to updated in the future */ - if (cmd->FindString("-label",label,true)) newdrive->SetLabel(label.c_str(),iscdrom,false); - /* For hard drives set the label to DRIVELETTER_Drive. - * For floppy drives set the label to DRIVELETTER_Floppy. - * This way every drive except cdroms should get a label.*/ - else if(type == "dir" || type == "overlay") { -#if defined (WIN32) || defined(OS2) - if(temp_line.size()==3 && toupper(drive) == toupper(temp_line[0])) { - // automatic mount - } else { - label = drive; label += "_DRIVE"; - newdrive->SetLabel(label.c_str(),iscdrom,false); - } -#endif - } else if(type == "floppy") { -#if defined (WIN32) || defined(OS2) - if(temp_line.size()==3 && toupper(drive) == toupper(temp_line[0])) { - // automatic mount - } else { - label = drive; label += "_FLOPPY"; - newdrive->SetLabel(label.c_str(),iscdrom,true); - } -#endif - } - if(type == "floppy") incrementFDD(); - return; -showusage: - resetcolor = true; - WriteOut(MSG_Get("PROGRAM_MOUNT_USAGE")); - return; - } -}; - -static void MOUNT_ProgramStart(Program * * make) { - *make=new MOUNT; -} - -void runMount(const char *str) { - MOUNT mount; - mount.cmd=new CommandLine("MOUNT", str); - mount.Run(); -} - -void GUI_Run(bool pressed); - -class CFGTOOL : public Program { -public: - void Run(void) override { - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Starts DOSBox-X's graphical configuration tool.\n\nCFGTOOL\n\nNote: You can also use CONFIG command for command-line configurations.\n"); - return; - } - GUI_Run(false); /* So that I don't have to run the keymapper on every setup of mine just to get the GUI --J.C */ - } -}; - -static void CFGTOOL_ProgramStart(Program * * make) { - *make=new CFGTOOL; -} - -extern bool custom_bios; -extern size_t custom_bios_image_size; -extern Bitu custom_bios_image_offset; -extern unsigned char *custom_bios_image; -extern uint32_t floppytype; -extern bool boot_debug_break; -extern Bitu BIOS_bootfail_code_offset; - -void DisableINT33(); -void EMS_DoShutDown(); -void XMS_DoShutDown(); -void DOS_DoShutDown(); -void GUS_DOS_Shutdown(); -void SBLASTER_DOS_Shutdown(); - -unsigned char PC98_ITF_ROM[0x8000]; -bool PC98_ITF_ROM_init = false; -unsigned char PC98_BANK_Select = 0x12; - -class PC98ITFPageHandler : public PageHandler { -public: - PC98ITFPageHandler() : PageHandler(PFLAG_READABLE|PFLAG_HASROM) {} - PC98ITFPageHandler(Bitu flags) : PageHandler(flags) {} - HostPt GetHostReadPt(PageNum phys_page) override { - return PC98_ITF_ROM+(phys_page&0x7)*MEM_PAGESIZE; - } - HostPt GetHostWritePt(PageNum phys_page) override { - return PC98_ITF_ROM+(phys_page&0x7)*MEM_PAGESIZE; - } - void writeb(PhysPt addr,uint8_t val) override { - LOG(LOG_CPU,LOG_ERROR)("Write %x to rom at %x",(int)val,(int)addr); - } - void writew(PhysPt addr,uint16_t val) override { - LOG(LOG_CPU,LOG_ERROR)("Write %x to rom at %x",(int)val,(int)addr); - } - void writed(PhysPt addr,uint32_t val) override { - LOG(LOG_CPU,LOG_ERROR)("Write %x to rom at %x",(int)val,(int)addr); - } -}; - -PC98ITFPageHandler mem_itf_rom; - -bool FDC_AssignINT13Disk(unsigned char drv); -void MEM_RegisterHandler(Bitu phys_page,PageHandler * handler,Bitu page_range); -void MEM_ResetPageHandler_Unmapped(Bitu phys_page, Bitu pages); -bool MEM_map_ROM_physmem(Bitu start,Bitu end); -PageHandler &Get_ROM_page_handler(void); - -// Normal BIOS is in the BIOS memory area -// ITF is in its own buffer, served by mem_itf_rom -void PC98_BIOS_Bank_Switch(void) { - if (PC98_BANK_Select == 0x00) { - MEM_RegisterHandler(0xF8,&mem_itf_rom,0x8); - } - else { - MEM_RegisterHandler(0xF8,&Get_ROM_page_handler(),0x8); - } - - PAGING_ClearTLB(); -} - -// BIOS behavior suggests a reset signal puts the BIOS back -void PC98_BIOS_Bank_Switch_Reset(void) { - LOG_MSG("PC-98 43Dh mapping BIOS back into top of RAM"); - PC98_BANK_Select = 0x12; - PC98_BIOS_Bank_Switch(); -#if 0 - Bitu DEBUG_EnableDebugger(void); - DEBUG_EnableDebugger(); -#endif -} - -void pc98_43d_write(Bitu port,Bitu val,Bitu iolen) { - (void)port; - (void)iolen; - - LOG_MSG("PC-98 43Dh BIOS bank switching write: 0x%02x",(unsigned int)val); - - switch (val) { - case 0x00: // ITF - case 0x10: - case 0x18: - PC98_BANK_Select = 0x00; - PC98_BIOS_Bank_Switch(); - break; - case 0x12: // BIOS - PC98_BANK_Select = 0x12; - PC98_BIOS_Bank_Switch(); - break; - default: - LOG_MSG("PC-98 43Dh BIOS bank switching write: 0x%02x unknown value",(unsigned int)val); - break; - } -} - -int IDE_MatchCDROMDrive(char drv); - -#if defined(WIN32) -#include -#else -#if defined(MACOSX) -#define _DARWIN_C_SOURCE -#endif -#include -#endif -FILE *retfile = NULL; -FILE * fopen_lock(const char * fname, const char * mode, bool &readonly) { - std::string fmode = mode; - if (lockmount && fmode.size()>1 && fmode.back()=='+') { -#if defined(WIN32) - HANDLE hFile = CreateFile(fname, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) { - const host_cnv_char_t* host_name = CodePageGuestToHost(fname); - if (host_name != NULL) hFile = CreateFileW(host_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - } - if (hFile == INVALID_HANDLE_VALUE) {fmode.pop_back();readonly=true;goto next;} - int nHandle = _open_osfhandle((intptr_t)hFile, _O_RDONLY); - if (nHandle == -1) {CloseHandle(hFile);return NULL;} - retfile = _fdopen(nHandle, fmode.c_str()); - if(!retfile) {CloseHandle(hFile);return NULL;} - LockFile(hFile, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF); -#else - retfile = fopen64(fname, fmode.c_str()); - if (retfile == NULL) {fmode.pop_back();readonly=true;goto next;} /* did you know fopen returns NULL if it cannot open the file? */ - int lock = flock(fileno(retfile), LOCK_EX | LOCK_NB); /* did you know fileno() assumes retfile != NULL and you will segfault if that is wrong? */ - if (lock < 0) { - fclose(retfile); /* don't leak file handles on failure to flock() */ - return NULL; - } -#endif - } else { -next: - retfile = fopen64(fname, fmode.c_str()); -#if defined(WIN32) - if (retfile == NULL) { - const host_cnv_char_t* host_name = CodePageGuestToHost(fname); - if (host_name != NULL) { - const size_t size = fmode.size()+1; - wchar_t* wmode = new wchar_t[size]; - mbstowcs (wmode, fmode.c_str(), size); - retfile = _wfopen(host_name, wmode); - } - } -#endif - } - return retfile; -} - -/*! \brief BOOT.COM utility to boot a floppy or hard disk device. - * - * \description Users will use this command to boot a guest operating system from - * a disk image. Options are provided to specify the device to boot - * from (if the image is already assigned) or a floppy disk image - * specified on the command line. - */ -class BOOT : public Program { -public: - BOOT() { - for (size_t i=0;i < MAX_SWAPPABLE_DISKS;i++) newDiskSwap[i] = NULL; - } - virtual ~BOOT() { - for (size_t i=0;i < MAX_SWAPPABLE_DISKS;i++) { - if (newDiskSwap[i] != NULL) { - newDiskSwap[i]->Release(); - newDiskSwap[i] = NULL; - } - } - } - /*! \brief Array of disk images to add to floppy swaplist - */ - imageDisk* newDiskSwap[MAX_SWAPPABLE_DISKS] = {}; - -private: - - /*! \brief Open a file as a disk image and return FILE* handle and size - */ - FILE *getFSFile_mounted(char const* filename, uint32_t *ksize, uint32_t *bsize, uint8_t *error) { - //if return NULL then put in error the errormessage code if an error was requested - bool tryload = (*error)?true:false; - *error = 0; - uint8_t drive; - char fullname[DOS_PATHLENGTH]; - - localDrive* ldp=nullptr; - bool readonly=wpcolon&&strlen(filename)>1&&filename[0]==':'; - if (!DOS_MakeName(readonly?filename+1:filename,fullname,&drive)) return NULL; - - try { - ldp=dynamic_cast(Drives[drive]); - if(!ldp) return NULL; - - FILE *tmpfile = ldp->GetSystemFilePtr(fullname, "rb"); - if(tmpfile == NULL) { - if (!tryload) *error=1; - return NULL; - } - - // get file size - fseek(tmpfile,0L, SEEK_END); - *ksize = uint32_t(ftell(tmpfile) / 1024); - *bsize = uint32_t(ftell(tmpfile)); - fclose(tmpfile); - - if (!readonly) - tmpfile = ldp->GetSystemFilePtr(fullname, "rb+"); - if(readonly || tmpfile == NULL) { -// if (!tryload) *error=2; -// return NULL; - WriteOut(MSG_Get("PROGRAM_BOOT_WRITE_PROTECTED")); - tmpfile = ldp->GetSystemFilePtr(fullname, "rb"); - if(tmpfile == NULL) { - if (!tryload) *error=1; - return NULL; - } - } - - return tmpfile; - } - catch(...) { - return NULL; - } - } - - /*! \brief Open a file as a disk image and return FILE* handle and size - */ - FILE *getFSFile(char const * filename, uint32_t *ksize, uint32_t *bsize,bool tryload=false) { - uint8_t error = tryload?1:0; - FILE* tmpfile = getFSFile_mounted(filename,ksize,bsize,&error); - if(tmpfile) return tmpfile; - //File not found on mounted filesystem. Try regular filesystem - std::string filename_s(filename); - Cross::ResolveHomedir(filename_s); - bool readonly=wpcolon&&filename_s.length()>1&&filename_s[0]==':'; - if (!readonly) - tmpfile = fopen_lock(filename_s.c_str(),"rb+",readonly); - if(readonly || !tmpfile) { - if( (tmpfile = fopen(readonly?filename_s.c_str()+1:filename_s.c_str(),"rb")) ) { - //File exists; So can't be opened in correct mode => error 2 -// fclose(tmpfile); -// if(tryload) error = 2; - WriteOut(MSG_Get("PROGRAM_BOOT_WRITE_PROTECTED")); - fseek(tmpfile,0L, SEEK_END); - *ksize = uint32_t(ftell(tmpfile) / 1024); - *bsize = uint32_t(ftell(tmpfile)); - return tmpfile; - } - // Give the delayed errormessages from the mounted variant (or from above) - if(error == 1) WriteOut(MSG_Get("PROGRAM_BOOT_NOT_EXIST")); - if(error == 2) WriteOut(MSG_Get("PROGRAM_BOOT_NOT_OPEN")); - return NULL; - } - fseek(tmpfile,0L, SEEK_END); - *ksize = uint32_t(ftell(tmpfile) / 1024); - *bsize = uint32_t(ftell(tmpfile)); - return tmpfile; - } - - /*! \brief Utility function to print generic boot error - */ - void printError(void) { - resetcolor = true; - WriteOut(MSG_Get("PROGRAM_BOOT_PRINT_ERROR")); - } - -public: - - /*! \brief Program entry point, when the command is run - */ - void Run(void) override { - std::string tmp; - std::string bios; - std::string boothax_str; - std::string el_torito_mode="noemu"; - std::string el_torito; - bool pc98_640x200 = true; - bool pc98_show_graphics = false; - bool bios_boot = false; - bool swaponedrive = false; - bool convertro = false; - bool force = false; - int loadseg_user = -1; - int convimg = -1; - int quiet = 0; - - //Hack To allow long commandlines - ChangeToLongCmd(); - - boot_debug_break = false; - if (cmd->FindExist("-debug",true)) - boot_debug_break = true; - - if (cmd->FindExist("-swap-one-drive",true)) - swaponedrive = true; - - //look for -el-torito parameter and remove it from the command line. - //This is copy-pasta to be consistent with the IMGMOUNT command which accepts this as either -el-torito or -bootcd. - //But with one important difference: Unlike IMGMOUNT which only supports bootable floppy emulation, this version lets - //you specify any other mode, though at this time, only "no emulation" mode is supported. You specify it as a =suffix - //i.e. -el-torito d:=noemu. No emulation mode is default, the IMGMOUNT --el-torito is still recommended for booting - //floppy emulation at this time. - cmd->FindString("-el-torito",el_torito,true); - if(el_torito == "") cmd->FindString("-bootcd", el_torito, true); - - if (!el_torito.empty()) { - size_t o = el_torito.find_last_of('='); - if (o != std::string::npos && (o+1) < el_torito.length()) { - el_torito_mode = el_torito.substr(o+1); - el_torito = el_torito.substr(0,o); - } - } - - // debugging options - if (cmd->FindExist("-pc98-640x200",true)) - pc98_640x200 = true; - if (cmd->FindExist("-pc98-640x400",true)) - pc98_640x200 = false; - if (cmd->FindExist("-pc98-graphics",true)) - pc98_show_graphics = true; - - if (cmd->FindExist("-q",true)) - quiet = 1; - if (cmd->FindExist("-qq",true)) - quiet = 2; - - if (cmd->FindExist("-force",true)) - force = true; - - if (cmd->FindExist("-convertfatro",true)) { - convimg = 1; - convertro = true; - } - - if (cmd->FindExist("-convertfat",true)) - convimg = 1; - - if (cmd->FindExist("-noconvertfat",true)) - convimg = 0; - - if (cmd->FindString("-bios",bios,true)) - bios_boot = true; - - cmd->FindString("-load-seg",tmp,true); - if (!tmp.empty()) - loadseg_user = strtoul(tmp.c_str(),NULL,0); - - cmd->FindString("-boothax",boothax_str,true); - - if (boothax_str == "msdos") // WARNING: For MS-DOS only, including MS-DOS 7/8 included in Windows 95/98/ME. - boothax = BOOTHAX_MSDOS; // do NOT use while in the graphical interface of Windows 95/98/ME especially a DOS VM. - else if (boothax_str == "") - boothax = BOOTHAX_NONE; - else { - if (!quiet) WriteOut("Unknown boothax mode"); - return; - } - - /* In secure mode don't allow people to boot stuff. - * They might try to corrupt the data on it */ - if(control->SecureMode()) { - if (!quiet) WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); - return; - } - - if (bios_boot) { - uint32_t isz1,isz2; - - if (bios.empty()) { - if (!quiet) WriteOut("Must specify BIOS image to boot\n"); - return; - } - - // NOTES: - // - // Regarding PC-98 mode, you should use an older BIOS image. - // The PC-9821 ROM image(s) I have appear to rely on bank - // switching parts of itself to boot up and operate. - // - // Update: I found some PC-9801 ROM BIOS images online, which - // ALSO seem to have a BIOS.ROM, ITF.ROM, etc... - // - // So, this command will not be able to run those - // images until port 43Dh (the I/O port used for - // bank switching) is implemented in DOSBox-X. - // - // In IBM PC/AT mode, this should hopefully allow using old - // 386/486 BIOSes in DOSBox-X. - - /* load it */ - FILE *romfp = getFSFile(bios.c_str(), &isz1, &isz2); - if (romfp == NULL) { - if (!quiet) WriteOut("Unable to open BIOS image\n"); - return; - } - Bitu loadsz = (isz2 + 0xFU) & (~0xFU); - if (loadsz == 0) loadsz = 0x10; - if (loadsz > (IS_PC98_ARCH ? 0x18000u : 0x20000u)) loadsz = (IS_PC98_ARCH ? 0x18000u : 0x20000u); - Bitu segbase = 0x100000 - loadsz; - LOG_MSG("Loading BIOS image %s to 0x%lx, 0x%lx bytes",bios.c_str(),(unsigned long)segbase,(unsigned long)loadsz); - fseek(romfp, 0, SEEK_SET); - - // To avoid crashes should any interrupt be called on the way to running the BIOS, - // don't actually map it in until it's good and ready to go. - if (custom_bios_image != NULL) delete[] custom_bios_image; - custom_bios_image_size = loadsz; - custom_bios_image_offset = segbase; - custom_bios_image = new unsigned char[custom_bios_image_size]; - - size_t readResult = fread(custom_bios_image,loadsz,1,romfp); - fclose(romfp); - if (readResult != 1) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); - return; - } - - if (IS_PC98_ARCH) { - // The PC-98 BIOS has a bank switching system where at least the last 32KB - // can be switched to an Initial Firmware Test BIOS, which initializes the - // system then switches back to the full 96KB visible during runtime. - // - // We can emulate the same if a file named ITF.ROM exists in the same directory - // as the BIOS image we were given. - // - // To enable multiple ITFs per ROM image, we first try .itf.rom - // before trying itf.rom, for the user's convenience. - FILE *itffp; - - itffp = getFSFile((bios + ".itf.rom").c_str(), &isz1, &isz2); - if (itffp == NULL) itffp = getFSFile((bios + ".ITF.ROM").c_str(), &isz1, &isz2); - if (itffp == NULL) itffp = getFSFile("itf.rom", &isz1, &isz2); - if (itffp == NULL) itffp = getFSFile("ITF.ROM", &isz1, &isz2); - - if (itffp != NULL && isz2 <= 0x8000ul) { - LOG_MSG("Found ITF (initial firmware test) BIOS image (0x%lx bytes)",(unsigned long)isz2); - - memset(PC98_ITF_ROM,0xFF,sizeof(PC98_ITF_ROM)); - readResult = fread(PC98_ITF_ROM,isz2,1,itffp); - fclose(itffp); - if (readResult != 1) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); - return; - } - PC98_ITF_ROM_init = true; - } - - IO_RegisterWriteHandler(0x43D,pc98_43d_write,IO_MB); - } - - custom_bios = true; - - /* boot it */ - throw int(8); - } - - bool bootbyDrive=false; - FILE *usefile_1=NULL; - FILE *usefile_2=NULL; - Bitu i=0; - uint32_t floppysize=0; - uint32_t rombytesize_1=0; - uint32_t rombytesize_2=0; - uint8_t drive = 'A'; - std::string cart_cmd=""; - Bitu max_seg; - - /* IBM PC: - * CS:IP = 0000:7C00 Load = 07C0:0000 - * SS:SP = ??? - * - * PC-98: - * CS:IP = 1FC0:0000 Load = 1FC0:0000 - * SS:SP = 0030:00D8 - * - * Reportedly PC-98 will load to 1FE0:0000 when booting the 1.44MB format (512 bytes per sector). - * Note that 0x1FC0:0000 leaves enough room for the 1024 bytes per sector format of PC-98. - */ - Bitu stack_seg=IS_PC98_ARCH ? 0x0030 : 0x7000; - Bitu load_seg;//=IS_PC98_ARCH ? 0x1FC0 : 0x07C0; - - if (MEM_TotalPages() > 0x9C) - max_seg = 0x9C00; - else - max_seg = MEM_TotalPages() << (12 - 4); - - if ((stack_seg+0x20) > max_seg) - stack_seg = max_seg - 0x20; - - /* if booting El Torito, the drive specified must be a CD-ROM drive */ - if (!el_torito.empty()) { - //get el-torito floppy from cdrom mounted at drive letter el_torito_cd_drive - char el_torito_cd_drive = toupper(el_torito[0]); - if (el_torito_cd_drive < 'A' || el_torito_cd_drive > 'Z') { - printError(); - return; - } - - if (IS_PC98_ARCH) { - /* PC-98 doesn't have a bootable CD-ROM specification... does it? - * By the time that became common the NEC basically switched to - * making IBM PC-AT compatible Windows 95 systems anyway. */ - printError(); - return; - } - - drive = 0; - if (!cmd->GetCount()) { - drive = 'A' + (dos_kernel_disabled?26:DOS_GetDefaultDrive()); - } - else if (cmd->GetCount() == 1) { - cmd->FindCommand(1, temp_line); - if (temp_line.length()==2&&toupper(temp_line[0])>='A'&&toupper(temp_line[0])<='Z'&&temp_line[1]==':') { - drive = toupper(temp_line[0]); - } - } - else { - printError(); - return; - } - - /* must be valid drive letter, C to Z */ - if (!isalpha(el_torito_cd_drive) || el_torito_cd_drive < 'C') { - WriteOut("El Torito emulation requires a proper CD-ROM drive letter\n"); - return; - } - - /* drive must not exist (as a hard drive) */ - if (imageDiskList[el_torito_cd_drive - 'A'] != NULL) { - WriteOut("El Torito CD-ROM drive specified already exists as a non-CD-ROM device\n"); - return; - } - - bool GetMSCDEXDrive(unsigned char drive_letter, CDROM_Interface **_cdrom); - - /* get the CD-ROM drive */ - CDROM_Interface *src_drive = NULL; - if (!GetMSCDEXDrive(el_torito_cd_drive - 'A', &src_drive)) { - WriteOut("El Torito CD-ROM drive specified is not actually a CD-ROM drive\n"); - return; - } - - /* "No emulation" boot is the only mode supported at this time. - * For floppy emulation boot, use IMGMOUNT and then boot the emulated floppy drive. */ - if (el_torito_mode != "noemu") { - WriteOut("Unsupported boot mode"); - return; - } - - unsigned char entries[2048], *entry, ent_num = 0; - int header_platform = -1, header_count = 0; - bool header_final = false; - int header_more = -1; - - /* Okay. Step #1: Scan the volume descriptors for the Boot Record. */ - unsigned long el_torito_base = 0, boot_record_sector = 0, el_torito_rba = (~0ul), el_torito_load_segment = 0, el_torito_sectors = 0/*VIRTUAL SECTORS*/; - unsigned char el_torito_mediatype = 0; - if (!ElTorito_ScanForBootRecord(src_drive, boot_record_sector, el_torito_base)) { - WriteOut("El Torito CD-ROM boot record not found\n"); - return; - } - - LOG_MSG("El Torito looking for mode '%s'",el_torito_mode.c_str()); - LOG_MSG("El Torito emulation: Found ISO 9660 Boot Record in sector %lu, pointing to sector %lu\n", - boot_record_sector, el_torito_base); - - /* Step #2: Parse the records. Each one is 32 bytes long */ - if (!src_drive->ReadSectorsHost(entries, false, el_torito_base, 1)) { - WriteOut("El Torito entries unreadable\n"); - return; - } - - /* for more information about what this loop is doing, read: - * http://download.intel.com/support/motherboards/desktop/sb/specscdrom.pdf - */ - for (ent_num = 0; ent_num < (2048 / 0x20); ent_num++) { - entry = entries + (ent_num * 0x20); - - if (memcmp(entry, "\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0", 32) == 0) - break; - - if (entry[0] == 0x01/*header*/) { - if (!ElTorito_ChecksumRecord(entry)) { - LOG_MSG("Warning: El Torito checksum error in header(0x01) entry\n"); - continue; - } - - if (header_count != 0) { - LOG_MSG("Warning: El Torito has more than one Header/validation entry\n"); - continue; - } - - if (header_final) { - LOG_MSG("Warning: El Torito has an additional header past the final header\n"); - continue; - } - - header_more = -1; - header_platform = entry[1]; - LOG_MSG("El Torito entry: first header platform=0x%02x\n", header_platform); - header_count++; - } - else if (entry[0] == 0x90/*header, more follows*/ || entry[0] == 0x91/*final header*/) { - if (header_final) { - LOG_MSG("Warning: El Torito has an additional header past the final header\n"); - continue; - } - - header_final = (entry[0] == 0x91); - header_more = (int)(((unsigned int)entry[2]) + (((unsigned int)entry[3]) << 8u)); - header_platform = entry[1]; - LOG_MSG("El Torito entry: first header platform=0x%02x more=%u final=%u\n", header_platform, header_more, header_final); - header_count++; - } - else { - if (header_more == 0) { - LOG_MSG("El Torito entry: Non-header entry count expired, ignoring record 0x%02x\n", entry[0]); - continue; - } - else if (header_more > 0) { - header_more--; - } - - if (entry[0] == 0x44) { - LOG_MSG("El Torito entry: ignoring extension record\n"); - } - else if (entry[0] == 0x00/*non-bootable*/) { - LOG_MSG("El Torito entry: ignoring non-bootable record\n"); - } - else if (entry[0] == 0x88/*bootable*/) { - if (header_platform == 0x00/*x86*/) { - unsigned char mediatype = entry[1] & 0xF; - unsigned short load_segment = ((unsigned int)entry[2]) + (((unsigned int)entry[3]) << 8); - unsigned char system_type = entry[4]; - unsigned short sector_count = ((unsigned int)entry[6]) + (((unsigned int)entry[7]) << 8); - unsigned long load_rba = ((unsigned int)entry[8]) + (((unsigned int)entry[9]) << 8) + - (((unsigned int)entry[10]) << 16) + (((unsigned int)entry[11]) << 24); - - LOG_MSG("El Torito entry: bootable x86 record mediatype=%u load_segment=0x%04x " - "system_type=0x%02x sector_count=%u load_rba=%lu\n", - mediatype, load_segment, system_type, sector_count, load_rba); - - /* already chose one, ignore */ - if (el_torito_rba != ~0UL) - continue; - - if ((mediatype == 0 && el_torito_mode == "noemu")) { - el_torito_rba = load_rba; - el_torito_mediatype = mediatype; - el_torito_load_segment = (load_segment != 0) ? load_segment : 0x7C0; - el_torito_sectors = sector_count; /* VIRTUAL EMULATED sectors not CD-ROM SECTORS */ - } - } - else { - LOG_MSG("El Torito entry: ignoring bootable non-x86 (platform_id=0x%02x) record\n", header_platform); - } - } - else { - LOG_MSG("El Torito entry: ignoring unknown record ID %02x\n", entry[0]); - } - } - } - - if (el_torito_rba == (~0ul) || el_torito_sectors == 0) { - WriteOut("Unable to locate bootable section\n"); - return; - } - - LOG_MSG("Using: rba=%lu virt-sectors=%lu load=0x%lx mediatype=%u", - (unsigned long)el_torito_rba, - (unsigned long)el_torito_sectors, - (unsigned long)el_torito_load_segment, - el_torito_mediatype); - - load_seg = el_torito_load_segment; - - /* round up to CD-ROM sectors and read */ - unsigned int bootcdsect = (el_torito_sectors + 3u) / 4u; /* 4 512-byte sectors per CD-ROM sector */ - if (bootcdsect == 0) bootcdsect = 1; - - for (unsigned int s=0;s < bootcdsect;s++) { - if (!src_drive->ReadSectorsHost(entries, false, el_torito_rba+s, 1)) { - WriteOut("El Torito boot sector unreadable\n"); - return; - } - - for(i=0;i<2048;i++) real_writeb((uint16_t)load_seg, (uint16_t)i+(s*2048), entries[i]); - } - - /* signal INT 13h to emulate a CD-ROM drive El Torito "no emulation" style */ - INT13_ElTorito_IDEInterface = -1; - INT13_ElTorito_NoEmuDriveNumber = 0x90; - INT13_ElTorito_NoEmuCDROMDrive = el_torito_cd_drive; - - /* this is required if INT 13h extensions are to correctly report what IDE controller the drive is connected to and master/slave */ - { - int x = IDE_MatchCDROMDrive(el_torito_cd_drive); - if (x >= 0) INT13_ElTorito_IDEInterface = (char)x; - LOG_MSG("CD-ROM drive IDE interface number %d",INT13_ElTorito_IDEInterface); - } - - SegSet16(cs, load_seg); - SegSet16(ds, 0); - SegSet16(es, 0); - reg_ip = 0; - reg_ebx = 0; - reg_esp = 0x100; - /* set up stack at a safe place */ - SegSet16(ss, (uint16_t)stack_seg); - reg_esi = 0; - reg_ecx = 0; - reg_ebp = 0; - reg_eax = 0; - /* ISOLINUX clearly assumes DL at entry contains the drive number and at no point from entry to INT 13h does it change the contents of DX */ - reg_edx = INT13_ElTorito_NoEmuDriveNumber; -#ifdef __WIN32__ - // let menu know it boots - menu.boot=true; -#endif - bootguest=false; - bootdrive=drive-65; - - /* forcibly exit the shell, the DOS kernel, and anything else by throwing an exception */ - throw int(2); - - return; - } - - if(!cmd->GetCount()) { - uint8_t drv = dos_kernel_disabled?26:DOS_GetDefaultDrive(); - if (drv < 4 && Drives[drv] && !strncmp(Drives[drv]->GetInfo(), "fatDrive ", 9)) { - drive = 'A' + drv; - bootbyDrive = true; - } else { - printError(); - return; - } - } else if (cmd->GetCount()==1) { - cmd->FindCommand(1, temp_line); - if (temp_line.length()==2&&toupper(temp_line[0])>='A'&&toupper(temp_line[0])<='Z'&&temp_line[1]==':') { - drive=toupper(temp_line[0]); - if ((drive != 'A') && (drive != 'C') && (drive != 'D')) { - printError(); - return; - } - bootbyDrive = true; - } - } - - if(!bootbyDrive) - while(i < cmd->GetCount()) { - if(cmd->FindCommand((unsigned int)(i+1), temp_line)) { - if ((temp_line == "/?") || (temp_line == "-?")) { - printError(); - return; - } - if((temp_line == "-l") || (temp_line == "-L")) { - /* Specifying drive... next argument then is the drive */ - bootbyDrive = true; - i++; - if(cmd->FindCommand((unsigned int)(i+1), temp_line)) { - if (temp_line.length()==1&&isdigit(temp_line[0])) - drive='A'+(temp_line[0]-'0'); - else - drive=toupper(temp_line[0]); - if ((drive != 'A') && (drive != 'C') && (drive != 'D')) { - printError(); - return; - } - - } else { - printError(); - return; - } - i++; - continue; - } - - if((temp_line == "-e") || (temp_line == "-E")) { - /* Command mode for PCJr cartridges */ - i++; - if(cmd->FindCommand((unsigned int)(i + 1), temp_line)) { - for(size_t ct = 0;ct < temp_line.size();ct++) temp_line[ct] = toupper(temp_line[ct]); - cart_cmd = temp_line; - } else { - printError(); - return; - } - i++; - continue; - } - - if(imageDiskList[0] != NULL || imageDiskList[1] != NULL) { - WriteOut(MSG_Get("PROGRAM_BOOT_IMAGE_MOUNTED")); - return; - } - - if (i >= MAX_SWAPPABLE_DISKS) { - return; //TODO give a warning. - } - - uint32_t rombytesize=0; - bool readonly=wpcolon&&temp_line.length()>1&&temp_line[0]==':'; - if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_IMAGE_OPEN"), readonly?temp_line.c_str()+1:temp_line.c_str()); - FILE *usefile = getFSFile(temp_line.c_str(), &floppysize, &rombytesize); - if(usefile != NULL) { - char tmp[256]; - - if (newDiskSwap[i] != NULL) { - newDiskSwap[i]->Release(); - newDiskSwap[i] = NULL; - } - - fseeko64(usefile, 0L, SEEK_SET); - size_t readResult = fread(tmp,256,1,usefile); // look for magic signatures - if (readResult != 1) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); - return; - } - - const char *ext = strrchr(temp_line.c_str(),'.'), *fname=readonly?temp_line.c_str()+1:temp_line.c_str(); - - if (ext != NULL && !strcasecmp(ext, ".d88")) { - newDiskSwap[i] = new imageDiskD88(usefile, fname, floppysize, false); - } - else if (!memcmp(tmp,"VFD1.",5)) { /* FDD files */ - newDiskSwap[i] = new imageDiskVFD(usefile, fname, floppysize, false); - } - else if (!memcmp(tmp,"T98FDDIMAGE.R0\0\0",16)) { - newDiskSwap[i] = new imageDiskNFD(usefile, fname, floppysize, false, 0); - } - else if (!memcmp(tmp,"T98FDDIMAGE.R1\0\0",16)) { - newDiskSwap[i] = new imageDiskNFD(usefile, fname, floppysize, false, 1); - } - else { - newDiskSwap[i] = new imageDisk(usefile, fname, floppysize, false); - } - newDiskSwap[i]->Addref(); - if (newDiskSwap[i]->active && !newDiskSwap[i]->hardDrive) incrementFDD(); //moved from imageDisk constructor - - if (usefile_1==NULL) { - usefile_1=usefile; - rombytesize_1=rombytesize; - } else { - usefile_2=usefile; - rombytesize_2=rombytesize; - } - } else { - if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_IMAGE_NOT_OPEN"), readonly?temp_line.c_str()+1:temp_line.c_str()); - return; - } - - } - i++; - } - - if (!bootbyDrive) { - if (i == 0) { - if (!quiet) WriteOut("No images specified"); - return; - } - - if (i > 1) { - /* if more than one image is given, then this drive becomes the focus of the swaplist */ - if (swapInDisksSpecificDrive >= 0 && swapInDisksSpecificDrive != (drive - 65)) { - if (!quiet) WriteOut("Multiple disk images specified and another drive is already connected to the swap list"); - return; - } - else if (swapInDisksSpecificDrive < 0 && swaponedrive) { - swapInDisksSpecificDrive = drive - 65; - } - - /* transfer to the diskSwap array */ - for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { - if (diskSwap[si] != NULL) { - diskSwap[si]->Release(); - diskSwap[si] = NULL; - } - - diskSwap[si] = newDiskSwap[si]; - newDiskSwap[si] = NULL; - } - - swapPosition = 0; - swapInDisks(-1); - } - else { - if (swapInDisksSpecificDrive == (drive - 65)) { - /* if we're replacing the diskSwap drive clear it now */ - for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { - if (diskSwap[si] != NULL) { - diskSwap[si]->Release(); - diskSwap[si] = NULL; - } - } - - swapInDisksSpecificDrive = -1; - } - - /* attach directly without using the swap list */ - if (imageDiskList[drive-65] != NULL) { - imageDiskChange[drive-65] = true; - imageDiskList[drive-65]->Release(); - imageDiskList[drive-65] = NULL; - } - - imageDiskList[drive-65] = newDiskSwap[0]; - newDiskSwap[0] = NULL; - } - } - - if(imageDiskList[drive-65]==NULL) { - if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_UNABLE"), drive); - return; - } - - // .D88 images come from PC-88 which usually means the boot sector is full - // of Z80 executable code, therefore it's very unlikely the boot sector will - // work with our x86 emulation! - // - // If the user is REALLY REALLY SURE they want to try executing Z80 bootsector - // code as x86, they're free to use --force. - // - // However PC-98 games are also distributed as .D88 images and therefore - // we probably CAN boot the image. - // - // It depends on the fd_type field of the image. - if (!force && imageDiskList[drive-65]->class_id == imageDisk::ID_D88) { - if (reinterpret_cast(imageDiskList[drive-65])->fd_type_major == imageDiskD88::DISKTYPE_2D) { - if (!quiet) WriteOut("The D88 image appears to target PC-88 and cannot be booted."); - return; - } - } - - - bootSector bootarea; - - if (imageDiskList[drive-65]->getSectSize() > sizeof(bootarea)) { - if (!quiet) WriteOut("Bytes/sector too large"); - return; - } - - /* clear the disk change flag. - * Most OSes don't expect the disk change error signal when they first boot up */ - imageDiskChange[drive-65] = false; - - bool has_read = false; - bool pc98_sect128 = false; - unsigned int bootsize = imageDiskList[drive-65]->getSectSize(); - - if (!has_read && IS_PC98_ARCH && drive < 'C') { - /* this may be one of those odd FDD images where track 0, head 0 is all 128-byte sectors - * and the rest of the disk is 256-byte sectors. */ - if (imageDiskList[drive - 65]->Read_Sector(0, 0, 1, (uint8_t *)&bootarea, 128) == 0 && - imageDiskList[drive - 65]->Read_Sector(0, 0, 2, (uint8_t *)&bootarea + 128, 128) == 0 && - imageDiskList[drive - 65]->Read_Sector(0, 0, 3, (uint8_t *)&bootarea + 256, 128) == 0 && - imageDiskList[drive - 65]->Read_Sector(0, 0, 4, (uint8_t *)&bootarea + 384, 128) == 0) { - LOG_MSG("First sector is 128 byte/sector. Booting from first four sectors."); - has_read = true; - bootsize = 512; // 128 x 4 - pc98_sect128 = true; - } - } - - if (!has_read && IS_PC98_ARCH && drive < 'C') { - /* another nonstandard one with track 0 having 256 bytes/sector while the rest have 1024 bytes/sector */ - if (imageDiskList[drive - 65]->Read_Sector(0, 0, 1, (uint8_t *)&bootarea, 256) == 0 && - imageDiskList[drive - 65]->Read_Sector(0, 0, 2, (uint8_t *)&bootarea + 256, 256) == 0 && - imageDiskList[drive - 65]->Read_Sector(0, 0, 3, (uint8_t *)&bootarea + 512, 256) == 0 && - imageDiskList[drive - 65]->Read_Sector(0, 0, 4, (uint8_t *)&bootarea + 768, 256) == 0) { - LOG_MSG("First sector is 256 byte/sector. Booting from first two sectors."); - has_read = true; - bootsize = 1024; // 256 x 4 - pc98_sect128 = true; - } - } - - /* NTS: Load address is 128KB - sector size */ - if (loadseg_user > 0) { /* Some PC-98 games have floppy boot code that suggests the boot segment isn't always 0x1FC0 like PC-9821 hardware does? */ - load_seg=(unsigned int)loadseg_user; - } - else { - unsigned int max_seg = std::min((unsigned int)(MEM_TotalPages()*(4096u/16u)/*pages to paragraphs*/),0xC000u); - if (IS_PC98_ARCH) - load_seg=std::min(max_seg,0x2000u/*128KB mark*/) - (bootsize/16U); /* normally 0x1FC0 (1024 byte/sector) or 0x1FE0 (512 byte/sector) */ - else - load_seg=std::min(max_seg,0x800u/*32KB mark*/) - 0x40u/*1KB*/; /* normally 0x07C0 */ - } - - if (!has_read) { - if (imageDiskList[drive - 65]->Read_Sector(0, 0, 1, (uint8_t *)&bootarea) != 0) { - if (!quiet) WriteOut("Error reading drive"); - return; - } - } - - Bitu pcjr_hdr_length = 0; - uint8_t pcjr_hdr_type = 0; // not a PCjr cartridge - if ((bootarea.rawdata[0]==0x50) && (bootarea.rawdata[1]==0x43) && (bootarea.rawdata[2]==0x6a) && (bootarea.rawdata[3]==0x72)) { - pcjr_hdr_type = 1; // JRipCart - pcjr_hdr_length = 0x200; - } else if ((bootarea.rawdata[56]==0x50) && (bootarea.rawdata[57]==0x43) && (bootarea.rawdata[58]==0x4a) && (bootarea.rawdata[59]==0x52)) { - pcjr_hdr_type = 2; // PCJRCart - pcjr_hdr_length = 0x80; - } - - if (pcjr_hdr_type > 0) { - if (machine!=MCH_PCJR&&!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_WO_PCJR")); - else { - uint8_t rombuf[65536]; - Bits cfound_at=-1; - if (cart_cmd!="") { - /* read cartridge data into buffer */ - fseek(usefile_1, (long)pcjr_hdr_length, SEEK_SET); - size_t readResult = fread(rombuf, 1, rombytesize_1-pcjr_hdr_length, usefile_1); - if (readResult != rombytesize_1 - pcjr_hdr_length) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); - return; - } - - char cmdlist[1024]; - cmdlist[0]=0; - Bitu ct=6; - Bits clen=rombuf[ct]; - char buf[257]; - if (cart_cmd=="?") { - while (clen!=0) { - safe_strncpy(buf,(char*)&rombuf[ct+1],clen); - buf[clen]=0; - upcase(buf); - strcat(cmdlist," "); - strcat(cmdlist,buf); - ct+=1u+(Bitu)clen+3u; - if (ct>sizeof(cmdlist)) break; - clen=rombuf[ct]; - } - if (ct>6) { - if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_LIST_CMDS"),cmdlist); - } else { - if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_NO_CMDS")); - } - for(Bitu dct=0;dctRelease(); - diskSwap[dct]=NULL; - } - } - //fclose(usefile_1); //delete diskSwap closes the file - return; - } else { - while (clen!=0) { - safe_strncpy(buf,(char*)&rombuf[ct+1],clen); - buf[clen]=0; - upcase(buf); - strcat(cmdlist," "); - strcat(cmdlist,buf); - ct+=1u+(Bitu)clen; - - if (cart_cmd==buf) { - cfound_at=(Bits)ct; - break; - } - - ct+=3; - if (ct>sizeof(cmdlist)) break; - clen=rombuf[ct]; - } - if (cfound_at<=0) { - if (ct>6) { - if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_LIST_CMDS"),cmdlist); - } else { - if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_NO_CMDS")); - } - for(Bitu dct=0;dctRelease(); - diskSwap[dct]=NULL; - } - } - //fclose(usefile_1); //Delete diskSwap closes the file - return; - } - } - } - - void PreparePCJRCartRom(void); - PreparePCJRCartRom(); - - if (usefile_1==NULL) return; - - uint32_t sz1,sz2; - FILE *tfile = getFSFile("system.rom", &sz1, &sz2, true); - if (tfile!=NULL) { - fseek(tfile, 0x3000L, SEEK_SET); - uint32_t drd=(uint32_t)fread(rombuf, 1, 0xb000, tfile); - if (drd==0xb000) { - for(i=0;i<0xb000;i++) phys_writeb((PhysPt)(0xf3000+i),rombuf[i]); - } - fclose(tfile); - } - - if (usefile_2!=NULL) { - unsigned int romseg_pt=0; - - fseek(usefile_2, 0x0L, SEEK_SET); - size_t readResult = fread(rombuf, 1, pcjr_hdr_length, usefile_2); - if (readResult != pcjr_hdr_length) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); - return; - } - - if (pcjr_hdr_type == 1) { - romseg_pt=host_readw(&rombuf[0x1ce]); - } else { - fseek(usefile_2, 0x61L, SEEK_SET); - int scanResult = fscanf(usefile_2, "%4x", &romseg_pt); - if (scanResult == 0) { - LOG(LOG_IO, LOG_ERROR) ("Scanning error in Run\n"); - return; - } - } - /* read cartridge data into buffer */ - fseek(usefile_2, (long)pcjr_hdr_length, SEEK_SET); - readResult = fread(rombuf, 1, rombytesize_2-pcjr_hdr_length, usefile_2); - if (readResult != rombytesize_2 - pcjr_hdr_length) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); - return; - } - //fclose(usefile_2); //usefile_2 is in diskSwap structure which should be deleted to close the file - - /* write cartridge data into ROM */ - for(i=0;iRelease(); - diskSwap[dct]=NULL; - } - } - - - if (cart_cmd=="") { - uint32_t old_int18=mem_readd(0x60); - /* run cartridge setup */ - SegSet16(ds,romseg); - SegSet16(es,romseg); - SegSet16(ss,0x8000); - reg_esp=0xfffe; - CALLBACK_RunRealFar(romseg,0x0003); - - uint32_t new_int18=mem_readd(0x60); - if (old_int18!=new_int18) { - /* boot cartridge (int18) */ - SegSet16(cs,RealSeg(new_int18)); - reg_ip = RealOff(new_int18); - } - } else { - if (cfound_at>0) { - /* run cartridge setup */ - SegSet16(ds,dos.psp()); - SegSet16(es,dos.psp()); - CALLBACK_RunRealFar((uint16_t)romseg,(uint16_t)cfound_at); - } - } - } - } else { - extern const char* RunningProgram; - - if (max_seg < (IS_PC98_ARCH?0x2000:0x0800)) LOG(LOG_MISC,LOG_WARN)("Booting a guest OS with too small amount of RAM may not work correctly"); - - /* Other versions of MS-DOS/PC-DOS have their own requirements about memory: - * - IBM PC-DOS 1.0/1.1: not too picky, will boot with as little as 32KB even though - * it was intended for the average model with 64KB of RAM. - * - * - IBM PC-DOS 2.1: requires at least 44KB of RAM. will crash on boot otherwise. - * - * - MS-DOS 3.2: requires at least 64KB to boot without crashing, 80KB to make it - * to the command line without halting at "configuration too big for - * memory"*/ - - /* TODO: Need a configuration option or a BOOT command option where the user can - * dictate where we put the stack: if we put it at 0x7000 or top of memory - * (default) or just below the boot sector, or... */ - - if((bootarea.rawdata[0]==0) && (bootarea.rawdata[1]==0)) { - if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_UNABLE"), drive); - return; - } - - char msg[512] = {0}; - const uint8_t page=real_readb(BIOSMEM_SEG,BIOSMEM_CURRENT_PAGE); - if (!dos_kernel_disabled && (convimg == 1 || (convertimg && convimg == -1))) { - unsigned int drv = 2, nextdrv = 2; - Section_prop *sec = static_cast(control->GetSection("dosbox")); - int freeMB = sec->Get_int("convert fat free space"), timeout = sec->Get_int("convert fat timeout"); - for (unsigned int d=2;dGetInfo(), "fatDrive ", 9) && strncmp(Drives[drv]->GetInfo(), "isoDrive ", 9)) { - if (drv==ZDRIVE_NUM && !static_cast(control->GetSection("dos"))->Get_bool("drive z convert fat")) continue; - while (imageDiskList[nextdrv]) nextdrv++; - if (nextdrv>=MAX_DISK_IMAGES) break; - if (quiet<2) { - size_t len = strlen(msg); - if (!len) { - strcat(msg, CURSOR_POS_COL(page)>0?"\r\n":""); - len = strlen(msg); - } - strcat(msg, "Converting drive "); - strcat(msg, std::string(1, 'A'+drv).c_str()); - strcat(msg, ": to FAT..."); - LOG_MSG("%s", msg+len); - strcat(msg, "\r\n"); - if (!quiet) { - uint16_t s = (uint16_t)strlen(msg); - DOS_WriteFile(STDERR,(uint8_t*)msg,&s); - *msg = 0; - } - } - Overlay_Drive *od = dynamic_cast(Drives[drv]); - imageDisk *imagedrv = new imageDisk(Drives[drv], drv, (convertro || Drives[drv]->readonly || (od && od->ovlreadonly)) ? 0 : freeMB, timeout); - if (imagedrv && imagedrv->ffdd) { - imageDiskList[nextdrv] = imagedrv; - imagedrv->Addref(); - bool ide_slave = false; - signed char ide_index = -1; - IDE_Auto(ide_index,ide_slave); - IDE_Hard_Disk_Attach((signed char)ide_index, ide_slave, nextdrv); - } else if (imagedrv) - delete imagedrv; - } - } - } - - if (quiet<2) { - if (!strlen(msg)) strcat(msg, CURSOR_POS_COL(page)>0?"\r\n":""); - strcat(msg, MSG_Get("PROGRAM_BOOT_BOOTING")); - strcat(msg, std::string(1, drive).c_str()); - strcat(msg, "...\r\n"); - uint16_t s = (uint16_t)strlen(msg); - DOS_WriteFile(STDERR,(uint8_t*)msg,&s); - } - if (IS_DOSV) { - uint8_t mode = real_readb(BIOSMEM_SEG, BIOSMEM_CURRENT_MODE); - if (mode == 3 || mode == 0x70 || mode == 0x72 || mode == 0x78) { - uint16_t oldax=reg_ax; - reg_ax = 0x12; - CALLBACK_RunRealInt(0x10); - reg_ax = oldax; - } - } - - for(i=0;itcount=true; - GetDMAChannel(3)->tcount=true; - } - else { - if (!IS_TANDY_ARCH && floppysize!=0) GetDMAChannel(2)->tcount=true; - } - - /* standard method */ - if (IS_PC98_ARCH) { - /* Based on a CPU register dump at boot time on a real PC-9821: - * - * DUMP: - * - * SP: 00D8 SS: 0030 ES: 1FE0 DS: 0000 CS: 1FE0 FL: 0246 BP: 0000 - * DI: 055C SI: 1FE0 DX: 0001 CX: 0200 BX: 0200 AX: 0030 IP: 0000 - * - * So: - * - * Stack at 0030:00D8 - * - * CS:IP at load_seg:0000 - * - * load_seg at 0x1FE0 which on the original 128KB PC-98 puts it at the top of memory - * - */ - SegSet16(cs, (uint16_t)load_seg); - SegSet16(ds, 0x0000); - SegSet16(es, (uint16_t)load_seg); - reg_ip = 0; - reg_ebx = 0x200; - reg_esp = 0xD8; - /* set up stack at a safe place */ - SegSet16(ss, (uint16_t)stack_seg); - reg_esi = (uint32_t)load_seg; - reg_ecx = 0x200; - reg_ebp = 0; - reg_eax = 0x30; - reg_edx = 0x1; - - /* It seems 640x200 8-color digital mode is the state of the graphics hardware when the - * BIOS boots the OS, and some games like Ys II assume the hardware is in this state. - * - * If I am wrong, you can pass --pc98-640x400 as a command line option to disable this. */ - if (pc98_640x200) { - reg_eax = 0x4200; // setup 640x200 graphics - reg_ecx = 0x8000; // lower - CALLBACK_RunRealInt(0x18); - } - else { - reg_eax = 0x4200; // setup 640x400 graphics - reg_ecx = 0xC000; // full - CALLBACK_RunRealInt(0x18); - } - - /* Some HDI images of Orange House games need this option because it assumes NEC MOUSE.COM - * behavior where mouse driver init and reset show the graphics layer. Unfortunately the HDI - * image uses QMOUSE which does not show the graphics layer. Use this option with those - * HDI images to make them playable anyway. */ - if (pc98_show_graphics) { - reg_eax = 0x4000; // show graphics - CALLBACK_RunRealInt(0x18); - } - else { - reg_eax = 0x4100; // hide graphics (normal state of graphics layer on startup). INT 33h emulation might have enabled it. - CALLBACK_RunRealInt(0x18); - } - - /* PC-98 MS-DOS boot sector behavior suggests that the BIOS does a CALL FAR - * to the boot sector, and the boot sector can RETF back to the BIOS on failure. */ - CPU_Push16((uint16_t)(BIOS_bootfail_code_offset >> 4)); /* segment */ - CPU_Push16(BIOS_bootfail_code_offset & 0xF); /* offset */ - - /* clear the text layer */ - for (i=0;i < (80*25*2);i += 2) { - mem_writew((PhysPt)(0xA0000+i),0x0000); - mem_writew((PhysPt)(0xA2000+i),0x00E1); - } - - /* hide the cursor */ - void PC98_show_cursor(bool show); - PC98_show_cursor(false); - - /* There is a byte at 0x584 that describes the boot drive + type. - * This is confirmed in Neko Project II source and by the behavior - * of an MS-DOS boot disk formatted by a PC-98 system. - * - * There are three values for three different floppy formats, and - * one for hard drives */ - uint32_t heads,cyls,sects,ssize; - - imageDiskList[drive-65]->Get_Geometry(&heads,&cyls,§s,&ssize); - - uint8_t RDISK_EQUIP = 0; /* 488h (ref. PC-9800 Series Technical Data Book - BIOS 1992 page 233 */ - /* bits [7:4] = 640KB FD drives 3:0 - * bits [3:0] = 1MB FD drives 3:0 */ - uint8_t F2HD_MODE = 0; /* 493h (ref. PC-9800 Series Technical Data Book - BIOS 1992 page 233 */ - /* bits [7:4] = 640KB FD drives 3:0 ?? - * bits [3:0] = 1MB FD drives 3:0 ?? */ - uint8_t F2DD_MODE = 0; /* 5CAh (ref. PC-9800 Series Technical Data Book - BIOS 1992 page 233 */ - /* bits [7:4] = 640KB FD drives 3:0 ?? - * bits [3:0] = 1MB FD drives 3:0 ?? */ - uint16_t disk_equip = 0, disk_equip_144 = 0; - uint8_t scsi_equip = 0; - - /* FIXME: MS-DOS appears to be able to see disk image B: but only - * if the disk format is the same, for some reason. - * - * So, apparently you cannot put a 1.44MB image in drive A: - * and a 1.2MB image in drive B: */ - - for (i=0;i < 2;i++) { - if (imageDiskList[i] != NULL) { - disk_equip |= (0x0111u << i); /* 320KB[15:12] 1MB[11:8] 640KB[7:4] unit[1:0] */ - disk_equip_144 |= (1u << i); - F2HD_MODE |= (0x11u << i); - } - } - - for (i=0;i < 2;i++) { - if (imageDiskList[i+2] != NULL) { - scsi_equip |= (1u << i); - - uint16_t m = 0x460u + ((uint16_t)i * 4u); - - mem_writeb(m+0u,sects); - mem_writeb(m+1u,heads); - mem_writew(m+2u,(cyls & 0xFFFu) + (ssize == 512u ? 0x1000u : 0u) + (ssize == 1024u ? 0x2000u : 0) + 0x8000u/*NP2:hwsec*/); - } - } - - mem_writew(0x55C,disk_equip); /* disk equipment (drive 0 is present) */ - mem_writew(0x5AE,disk_equip_144); /* disk equipment (drive 0 is present, 1.44MB) */ - mem_writeb(0x482,scsi_equip); - mem_writeb(0x488,RDISK_EQUIP); /* RAM disk equip */ - mem_writeb(0x493,F2HD_MODE); - mem_writeb(0x5CA,F2DD_MODE); - - if (drive >= 'C') { - /* hard drive */ - mem_writeb(0x584,0xA0/*type*/ + (drive - 'C')/*drive*/); - } - else if ((ssize == 1024 && heads == 2 && cyls == 77 && sects == 8) || pc98_sect128) { - mem_writeb(0x584,0x90/*type*/ + (drive - 65)/*drive*/); /* 1.2MB 3-mode */ - } - else if (ssize == 512 && heads == 2 && cyls == 80 && sects == 18) { - mem_writeb(0x584,0x30/*type*/ + (drive - 65)/*drive*/); /* 1.44MB */ - } - else { - // FIXME - LOG_MSG("PC-98 boot: Unable to determine boot drive type for ssize=%u heads=%u cyls=%u sects=%u. Guessing.", - ssize,heads,cyls,sects); - - mem_writeb(0x584,(ssize < 1024 ? 0x30 : 0x90)/*type*/ + (drive - 65)/*drive*/); - } - } - else { - // Toshiba DOS bootloader checks the floppy disk drives running in the BIOS working area. - if(IS_J3100) { - mem_writeb(BIOS_DRIVE_RUNNING, 0x01); - mem_writeb(BIOS_DISK_MOTOR_TIMEOUT, 10); - } - SegSet16(cs, 0); - SegSet16(ds, 0); - SegSet16(es, 0); - reg_ip = (uint16_t)(load_seg<<4); - reg_ebx = (uint32_t)(load_seg<<4); //Real code probably uses bx to load the image - reg_esp = 0x100; - /* set up stack at a safe place */ - SegSet16(ss, (uint16_t)stack_seg); - reg_esi = 0; - reg_ecx = 1; - reg_ebp = 0; - reg_eax = 0; - reg_edx = 0; //Head 0 - if (drive >= 'A' && drive <= 'B') - reg_edx += (unsigned int)(drive-'A'); - else if (drive >= 'C' && drive <= 'Z') - reg_edx += 0x80u+(unsigned int)(drive-'C'); - } -#ifdef __WIN32__ - // let menu know it boots - menu.boot=true; -#endif - bootguest=false; - bootdrive=drive-65; - - /* forcibly exit the shell, the DOS kernel, and anything else by throwing an exception */ - throw int(2); - } - } -}; - -static void BOOT_ProgramStart(Program * * make) { - *make=new BOOT; -} - -void runBoot(const char *str) { - BOOT boot; - boot.cmd=new CommandLine("BOOT", str); - boot.Run(); -} - -class LOADROM : public Program { -public: - void Run(void) override { - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut(MSG_Get("PROGRAM_LOADROM_HELP")); - return; - } - - if (!(cmd->FindCommand(1, temp_line))) { - WriteOut(MSG_Get("PROGRAM_LOADROM_SPECIFY_FILE")); - return; - } - - uint8_t drive; - char fullname[DOS_PATHLENGTH]; - localDrive* ldp=nullptr; - if (!DOS_MakeName(temp_line.c_str(),fullname,&drive)) return; - - try { - /* try to read ROM file into buffer */ - ldp=dynamic_cast(Drives[drive]); - if(!ldp) return; - - FILE *tmpfile = ldp->GetSystemFilePtr(fullname, "rb"); - if(tmpfile == NULL) { - WriteOut(MSG_Get("PROGRAM_LOADROM_CANT_OPEN")); - return; - } - fseek(tmpfile, 0L, SEEK_END); - if (ftell(tmpfile)>0x8000) { - WriteOut(MSG_Get("PROGRAM_LOADROM_TOO_LARGE")); - fclose(tmpfile); - return; - } - fseek(tmpfile, 0L, SEEK_SET); - uint8_t rom_buffer[0x8000]; - Bitu data_read = fread(rom_buffer, 1, 0x8000, tmpfile); - fclose(tmpfile); - - /* try to identify ROM type */ - PhysPt rom_base = 0; - if (data_read >= 0x4000 && rom_buffer[0] == 0x55 && rom_buffer[1] == 0xaa && - (rom_buffer[3] & 0xfc) == 0xe8 && strncmp((char*)(&rom_buffer[0x1e]), "IBM", 3) == 0) { - - if (!IS_EGAVGA_ARCH) { - WriteOut(MSG_Get("PROGRAM_LOADROM_INCOMPATIBLE")); - return; - } - rom_base = PhysMake(0xc000, 0); // video BIOS - } - else if (data_read == 0x8000 && rom_buffer[0] == 0xe9 && rom_buffer[1] == 0x8f && - rom_buffer[2] == 0x7e && strncmp((char*)(&rom_buffer[0x4cd4]), "IBM", 3) == 0) { - - rom_base = PhysMake(0xf600, 0); // BASIC - } - - if (rom_base) { - /* write buffer into ROM */ - for (Bitu i=0; iFindCommand(1, temp_line))) { - WriteOut("Must specify BIOS file to load.\n"); - return; - } - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut(MSG_Get("PROGRAM_BIOSTEST_HELP")); - return; - } - - uint8_t drive; - char fullname[DOS_PATHLENGTH]; - localDrive* ldp = nullptr; - if (!DOS_MakeName(temp_line.c_str(), fullname, &drive)) return; - - try { - /* try to read ROM file into buffer */ - ldp = dynamic_cast(Drives[drive]); - if (!ldp) return; - - FILE* tmpfile = ldp->GetSystemFilePtr(fullname, "rb"); - if (tmpfile == NULL) { - WriteOut("Can't open a file"); - return; - } - fseek(tmpfile, 0L, SEEK_END); - if (ftell(tmpfile) > 64 * 1024) { - WriteOut("BIOS File too large"); - fclose(tmpfile); - return; - } - fseek(tmpfile, 0L, SEEK_SET); - uint8_t buffer[64 * 1024]; - Bitu data_read = fread(buffer, 1, sizeof(buffer), tmpfile); - fclose(tmpfile); - - uint32_t rom_base = PhysMake(0xf000, 0); // override regular dosbox bios - /* write buffer into ROM */ - for (Bitu i = 0; i < data_read; i++) phys_writeb((PhysPt)(rom_base + i), buffer[i]); - - //Start executing this bios - memset(&cpu_regs, 0, sizeof(cpu_regs)); - memset(&Segs, 0, sizeof(Segs)); - - SegSet16(cs, 0xf000); - reg_eip = 0xfff0; - } - catch (...) { - return; - } - } -}; - -static void BIOSTEST_ProgramStart(Program** make) { - *make = new BIOSTEST; -} -#endif - -/* non-bootable MS-DOS floppy disk boot sector. - * will be modified as appropriate. */ -unsigned char this_is_not_a_bootable_partition[512] = { - 0xeb, 0x3c, 0x90, 0x6d, 0x6b, 0x64, 0x6f, 0x73, 0x66, 0x73, 0x00, 0x00, 0x02, 0x01, 0x01, 0x00, - 0x02, 0xe0, 0x00, 0x40, 0x0b, 0xf0, 0x09, 0x00, 0x12, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0xce, 0xf2, 0x4e, 0xda, 0x20, 0x20, 0x20, 0x20, 0x20, - 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x46, 0x41, 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x0e, 0x1f, - 0xbe, 0x5b, 0x7c, 0xac, 0x22, 0xc0, 0x74, 0x0b, 0x56, 0xb4, 0x0e, 0xbb, 0x07, 0x00, 0xcd, 0x10, - 0x5e, 0xeb, 0xf0, 0x32, 0xe4, 0xcd, 0x16, 0xcd, 0x19, 0xeb, 0xfe, 0x54, 0x68, 0x69, 0x73, 0x20, - 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x74, 0x61, 0x62, 0x6c, - 0x65, 0x20, 0x64, 0x69, 0x73, 0x6b, 0x2e, 0x20, 0x20, 0x50, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x20, - 0x69, 0x6e, 0x73, 0x65, 0x72, 0x74, 0x20, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x74, 0x61, 0x62, 0x6c, - 0x65, 0x20, 0x66, 0x6c, 0x6f, 0x70, 0x70, 0x79, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x70, 0x72, - 0x65, 0x73, 0x73, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x74, 0x6f, 0x20, 0x74, - 0x72, 0x79, 0x20, 0x61, 0x67, 0x61, 0x69, 0x6e, 0x20, 0x2e, 0x2e, 0x2e, 0x20, 0x0d, 0x0a, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa -}; - -const uint8_t freedos_mbr[] = { - 0xFA,0xFC,0x31,0xC0,0x8E,0xD0,0x8E,0xD8,0xBD,0x00,0x7C,0x8D,0x66,0xE0,0xFB,0xB8, - 0xE0,0x1F,0x8E,0xC0,0x89,0xEE,0x89,0xEF,0xB9,0x00,0x01,0xF3,0xA5,0xEA,0x22,0x7C, // 10h - 0xE0,0x1F,0x8E,0xD8,0x8E,0xD0,0x31,0xC0,0x8E,0xC0,0x8D,0xBE,0xBE,0x01,0xF6,0x05, // 20h - 0x80,0x75,0x6D,0x83,0xC7,0x10,0x81,0xFF,0xFE,0x7D,0x72,0xF2,0xE8,0xC4,0x00,0x6E, - 0x6F,0x20,0x61,0x63,0x74,0x69,0x76,0x65,0x20,0x70,0x61,0x72,0x74,0x69,0x74,0x69, // 40h - 0x6F,0x6E,0x20,0x66,0x6F,0x75,0x6E,0x64,0x00,0xEB,0xFE,0xE8,0xA5,0x00,0x72,0x65, - 0x61,0x64,0x20,0x65,0x72,0x72,0x6F,0x72,0x20,0x77,0x68,0x69,0x6C,0x65,0x20,0x72, - 0x65,0x61,0x64,0x69,0x6E,0x67,0x20,0x64,0x72,0x69,0x76,0x65,0x00,0xEB,0xDA,0xE8, - 0x81,0x00,0x70,0x61,0x72,0x74,0x69,0x74,0x69,0x6F,0x6E,0x20,0x73,0x69,0x67,0x6E, // 80h - 0x61,0x74,0x75,0x72,0x65,0x20,0x21,0x3D,0x20,0x35,0x35,0x41,0x41,0x00,0xEB,0xB9, - 0xE8,0x10,0x00,0x72,0xB6,0x26,0x81,0x3E,0xFE,0x7D,0x55,0xAA,0x75,0xD1,0xEA,0x00, - 0x7C,0x00,0x00,0xBB,0xAA,0x55,0xB4,0x41,0xCD,0x13,0x72,0x32,0x81,0xFB,0x55,0xAA, - 0x75,0x2C,0xF6,0xC1,0x01,0x74,0x27,0xEB,0x10,0x10,0x00,0x04,0x00,0x00,0x7C,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x8B,0x45,0x08,0xA3,0xD1,0x7C,0x8B, - 0x45,0x0A,0xA3,0xD3,0x7C,0xB8,0x00,0x42,0xBE,0xC9,0x7C,0xCD,0x13,0xC3,0xB8,0x04, - 0x02,0xBB,0x00,0x7C,0x8B,0x4D,0x02,0x8A,0x75,0x01,0xCD,0x13,0xC3,0x31,0xDB,0xB4, - 0x0E,0xCD,0x10,0x5E,0xAC,0x56,0x3C,0x00,0x75,0xF3,0xC3,0x00,0x00,0x00,0x00,0x00, //100h - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //110h - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //120h - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //140h - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //180h - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x73,0x73,0x65,0xE3,0x3F,0xBF,0x00,0x00, //1B0h - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x55,0xAA -}; -#ifdef WIN32 -#include -#endif - -static void lba2chs3(unsigned char *b3,uint32_t lba,const unsigned int gc,const unsigned int gh,const unsigned int gs) { - const unsigned int s = (unsigned int)(lba % (uint32_t)gs) + 1u; lba /= (uint32_t)gs; - const unsigned int h = (unsigned int)(lba % (uint32_t)gh); lba /= (uint32_t)gh; - const unsigned int c = (unsigned int) lba; - - (void)gc; - - b3[0] = h; - b3[1] = s | ((c >> 8u) << 6u); /* [7:6] cylinder bits 8-9 [5:0] sector */ - b3[2] = c; -} - -class IMGMAKE : public Program { -public: -#ifdef WIN32 - bool OpenDisk(HANDLE* f, OVERLAPPED* o, uint8_t* name) const { - o->hEvent = INVALID_HANDLE_VALUE; - *f = CreateFile( (LPCSTR)name, GENERIC_READ | GENERIC_WRITE, - 0, // exclusive access - NULL, // default security attributes - OPEN_EXISTING, - FILE_FLAG_OVERLAPPED, - NULL ); - - if (*f == INVALID_HANDLE_VALUE) return false; - - // init OVERLAPPED - o->Internal = 0; - o->InternalHigh = 0; - o->Offset = 0; - o->OffsetHigh = 0; - o->hEvent = CreateEvent( - NULL, // default security attributes - TRUE, // manual-reset event - FALSE, // not signaled - NULL // no name - ); - return true; - } - - void CloseDisk(HANDLE f, OVERLAPPED* o) const { - if(f != INVALID_HANDLE_VALUE) CloseHandle(f); - if(o->hEvent != INVALID_HANDLE_VALUE) CloseHandle(o->hEvent); - } - - bool StartReadDisk(HANDLE f, OVERLAPPED* o, uint8_t* buffer, Bitu offset, Bitu size) const { - o->Offset = (DWORD)offset; - if (!ReadFile(f, buffer, (DWORD)size, NULL, o) && - (GetLastError()==ERROR_IO_PENDING)) return true; - return false; - } - - // 0=still waiting, 1=catastrophic failure, 2=success, 3=sector not found, 4=crc error - Bitu CheckDiskReadComplete(HANDLE f, OVERLAPPED* o) const { - DWORD numret; - BOOL b = GetOverlappedResult( f, o, &numret,false); - if(b) return 2; - else { - int error = GetLastError(); - if(error==ERROR_IO_INCOMPLETE) return 0; - if(error==ERROR_FLOPPY_UNKNOWN_ERROR) return 5; - if(error==ERROR_CRC) return 4; - if(error==ERROR_SECTOR_NOT_FOUND) return 3; - return 1; - } - } - - Bitu ReadDisk(FILE* f, uint8_t driveletter, Bitu retries_max) { - unsigned char data[36*2*512]; - HANDLE hFloppy; - DWORD numret; - OVERLAPPED o; - DISK_GEOMETRY geom; - - uint8_t drivestring[] = "\\\\.\\x:"; drivestring[4]=driveletter; - if(!OpenDisk(&hFloppy, &o, drivestring)) return false; - - // get drive geom - DeviceIoControl( hFloppy, IOCTL_DISK_GET_DRIVE_GEOMETRY,NULL,0, - &geom,sizeof(DISK_GEOMETRY),&numret,NULL); - - switch(geom.MediaType) { - case F5_1Pt2_512: case F3_1Pt44_512: case F3_2Pt88_512: case F3_720_512: - case F5_360_512: case F5_320_512: case F5_180_512: case F5_160_512: - break; - default: - CloseDisk(hFloppy,&o); - return false; - } - Bitu total_sect_per_cyl = geom.SectorsPerTrack * geom.TracksPerCylinder; - Bitu cyln_size = 512 * total_sect_per_cyl; - - WriteOut(MSG_Get("PROGRAM_IMGMAKE_FLREAD"), - geom.Cylinders.LowPart,geom.TracksPerCylinder, - geom.SectorsPerTrack,(cyln_size*geom.Cylinders.LowPart)/1024); - WriteOut(MSG_Get("PROGRAM_IMGMAKE_FLREAD2"), "\xdb", "\xb1"); - - for(Bitu i = 0; i < geom.Cylinders.LowPart; i++) { - Bitu result; - // for each cylinder - WriteOut("%2u",i); - - if(!StartReadDisk(hFloppy, &o, &data[0], cyln_size*i, cyln_size)){ - CloseDisk(hFloppy,&o); - return false; - } - do { - result = CheckDiskReadComplete(hFloppy, &o); - CALLBACK_Idle(); - } - while (result==0); - - switch(result) { - case 1: - CloseDisk(hFloppy,&o); - return false; - case 2: // success - for(Bitu m=0; m < cyln_size/512; m++) WriteOut("\xdb"); - break; - case 3: - case 4: // data errors - case 5: - for(Bitu k=0; k < total_sect_per_cyl; k++) { - Bitu retries=retries_max; -restart_int: - StartReadDisk(hFloppy, &o, &data[512*k], cyln_size*i + 512*k, 512); - do { - result = CheckDiskReadComplete(hFloppy, &o); - CALLBACK_Idle(); - } - while (result==0); - - switch(result) { - case 1: // bad error - CloseDisk(hFloppy,&o); - return false; - case 2: // success - if(retries==retries_max) WriteOut("\xdb"); - else WriteOut("\b\b\b\xb1"); - break; - case 3: - case 4: // read errors - case 5: - if(retries!=retries_max) WriteOut("\b\b\b"); - retries--; - switch(result) { - case 3: WriteOut("x"); - case 4: WriteOut("!"); - case 5: WriteOut("?"); - } - WriteOut("%2d",retries); - - if(retries) goto restart_int; - const uint8_t badfood[]="IMGMAKE BAD FLOPPY SECTOR \xBA\xAD\xF0\x0D"; - for(uint8_t z = 0; z < 512/32; z++) - memcpy(&data[512*k+z*32],badfood,31); - WriteOut("\b\b"); - break; - } - } - break; - } - fwrite(data, 512, total_sect_per_cyl, f); - WriteOut("%2x%2x\n", data[0], data[1]); - } - // seek to 0 - StartReadDisk(hFloppy, &o, &data[0], 0, 512); - CloseDisk(hFloppy,&o); - return true; - } -#endif - - void Run(void) override { - std::string disktype; - std::string label; - std::string src; - std::string filename; - std::string dpath; - std::string tmp; - - int lbamode = -1; - uint32_t c, h, s; - uint64_t size = 0, sectors; - uint16_t alignment = 0; // if nonzero, try to align structures to this multiple of K (i.e. 4K sector alignment) - - if(control->SecureMode()) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); - return; - } - if(cmd->FindExist("-?")) { - printHelp(); - return; - } - if (cmd->FindExist("/examples")||cmd->FindExist("-examples")) { - resetcolor = true; - WriteOut(MSG_Get("PROGRAM_IMGMAKE_EXAMPLE")); - return; - } - -/* - this stuff is too frustrating - - // when only a filename is passed try to create the file on the current DOS path - // if directory+filename are passed first see if directory is a host path, if not - // maybe it is a DOSBox path. - - // split filename and path - std::string path = ""; - Bitu spos = temp_line.rfind('\\'); - if(spos==std::string::npos) { - temp_line.rfind('/'); - } - - if(spos==std::string::npos) { - // no path separator - filename=temp_line; - } else { - path=temp_line.substr(0,spos); - filename=temp_line.substr(spos+1,std::string::npos); - } - if(filename=="") - - char tbuffer[DOS_PATHLENGTH]= { 0 }; - if(path=="") { - if(!DOS_GetCurrentDir(DOS_GetDefaultDrive()+1,tbuffer)){ - printHelp(); - return; - } - dpath=(std::string)tbuffer; - } - WriteOut("path %s, filename %s, dpath %s", - path.c_str(),filename.c_str(),dpath.c_str()); - return; -*/ - - bool ForceOverwrite = false; - if (cmd->FindExist("-force",true)) - ForceOverwrite = true; -#ifdef WIN32 - // read from real floppy? - if(cmd->FindString("-source",src,true)) { - int retries = 10; - cmd->FindInt("-retries",retries,true); - if((retries < 1)||(retries > 99)) { - printHelp(); - return; - } - if((src.length()!=1) || !isalpha(src.c_str()[0])) { - // only one letter allowed - printHelp(); - return; - } - - /* temp_line is the given filename */ - if (!(cmd->FindCommand(1, temp_line))) - temp_line = "IMGMAKE.IMG"; - - bool setdir=false; - char dirCur[512], dirNew[512]; - if (!dos_kernel_disabled&&getcwd(dirCur, 512)!=NULL&&(!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"local ",6)||!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"CDRom ",6))) { - Overlay_Drive *ddp = dynamic_cast(Drives[DOS_GetDefaultDrive()]); - strcpy(dirNew, ddp!=NULL?ddp->getOverlaydir():Drives[DOS_GetDefaultDrive()]->GetBaseDir()); - strcat(dirNew, Drives[DOS_GetDefaultDrive()]->curdir); - if (chdir(dirNew)==0) setdir=true; - } - - FILE* f = fopen(temp_line.c_str(),"r"); - if (f){ - fclose(f); - if (!ForceOverwrite) { - WriteOut(MSG_Get("PROGRAM_IMGMAKE_FILE_EXISTS"),temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - } - f = fopen(temp_line.c_str(),"wb+"); - if (!f) { - WriteOut(MSG_Get("PROGRAM_IMGMAKE_CANNOT_WRITE"),temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - if (setdir) chdir(dirCur); - // maybe delete f if it failed? - if(!ReadDisk(f, src.c_str()[0],retries)) - WriteOut(MSG_Get("PROGRAM_IMGMAKE_CANT_READ_FLOPPY")); - fclose(f); - if (setdir) runRescan("-Q"); - return; - } -#endif - // disk type - if (!(cmd->FindString("-t",disktype,true))) { - printHelp(); - return; - } - std::transform(disktype.begin(), disktype.end(), disktype.begin(), ::tolower); - - // filesystem label - cmd->FindString("-label",label,true); - - // alignment - if (cmd->FindString("-align",tmp,true)) { - const char *s = tmp.c_str(); - alignment = (uint32_t)strtoul(s,(char**)(&s),0); - /* if 'K' follows, convert K to sectors */ - if (*s == 'K' || *s == 'k') alignment *= (uint32_t)2u; - - if (alignment == (uint32_t)0 || alignment > (uint32_t)2048/*1MB*/) { - WriteOut("Invalid alignment"); - return; - } - } - - uint8_t mediadesc = 0xF8; // media descriptor byte; also used to differ fd and hd - uint16_t root_ent = 512; // FAT root directory entries: 512 is for harddisks - uint16_t disksize = 0; // disk size of floppy images - uint32_t sect_per_fat = 0; // allowable range: FAT12 1-12, FAT16 16-256, FAT32 512-2,097,152 sectors - uint16_t sectors_per_cluster = 0; // max limit: 128 - bool is_fd = false; - if(disktype=="fd_160") { - c = 40; h = 1; s = 8; mediadesc = 0xFE; root_ent = 64; sect_per_fat = 1; sectors_per_cluster = 1; - disksize = 160; is_fd = true; - } else if(disktype=="fd_180") { - c = 40; h = 1; s = 9; mediadesc = 0xFC; root_ent = 64; sect_per_fat = 2; sectors_per_cluster = 1; - disksize = 180; is_fd = true; - } else if(disktype=="fd_200") { - c = 40; h = 1; s = 10; mediadesc = 0xFC; root_ent = 64; sect_per_fat = 2; sectors_per_cluster = 2;// root_ent? - disksize = 200; is_fd = true; - } else if(disktype=="fd_320") { - c = 40; h = 2; s = 8; mediadesc = 0xFF; root_ent = 112; sect_per_fat = 1; sectors_per_cluster = 2; - disksize = 320; is_fd = true; - } else if(disktype=="fd_360") { - c = 40; h = 2; s = 9; mediadesc = 0xFD; root_ent = 112; sect_per_fat = 2; sectors_per_cluster = 2; - disksize = 360; is_fd = true; - } else if(disktype=="fd_400") { - c = 40; h = 2; s = 10; mediadesc = 0xFD; root_ent = 112; sect_per_fat = 2; sectors_per_cluster = 2; - disksize = 400; is_fd = true; - } else if(disktype=="fd_720") { - c = 80; h = 2; s = 9; mediadesc = 0xF9; root_ent = 112; sect_per_fat = 3; sectors_per_cluster = 2; - disksize = 720; is_fd = true; - } else if(disktype=="fd_1200") { - c = 80; h = 2; s = 15; mediadesc = 0xF9; root_ent = 224; sect_per_fat = 7; sectors_per_cluster = 1; - disksize = 1200; is_fd = true; - } else if(disktype=="fd_1440"||disktype=="fd"||disktype=="floppy") { - c = 80; h = 2; s = 18; mediadesc = 0xF0; root_ent = 224; sect_per_fat = 9; sectors_per_cluster = 1; - disksize = 1440; is_fd = true; - } else if(disktype=="fd_2880") { - c = 80; h = 2; s = 36; mediadesc = 0xF0; root_ent = 240; sect_per_fat = 9; sectors_per_cluster = 2; - disksize = 2880; is_fd = true; - } else if(disktype=="hd_250") { - c = 489; h = 16; s = 63; - } else if(disktype=="hd_520") { - c = 1023; h = 16; s = 63; - } else if(disktype=="hd_1gig") { - c = 1023; h = 32; s = 63; - } else if(disktype=="hd_2gig") { - c = 1023; h = 64; s = 63; - } else if(disktype=="hd_4gig") { // fseek only supports 2gb - c = 1023; h = 130; s = 63; - } else if(disktype=="hd_8gig") { // fseek only supports 2gb - c = 1023; h = 255; s = 63; - } else if(disktype=="hd_st251") { // old 40mb drive - c = 820; h = 6; s = 17; - } else if(disktype=="hd_st225") { // even older 20mb drive - c = 615; h = 4; s = 17; - } else if(disktype=="hd" || disktype=="vhd") { - // get size from parameter - std::string isize; - if (!(cmd->FindString("-size",isize,true))) { - // maybe -chs? - if (!(cmd->FindString("-chs",isize,true))){ - // user forgot -size and -chs - printHelp(); - return; - } - else { - // got chs data: -chs 1023,16,63 - if(sscanf(isize.c_str(),"%u,%u,%u",&c,&h,&s) != 3) { - WriteOut(MSG_Get("PROGRAM_IMGMAKE_BADSIZE")); - return; - } - // sanity-check chs values - if((h>255)||(c>1023)||(s>63)) { - printHelp(); - return; - } - size = (uint64_t)c * (uint64_t)h * (uint64_t)s * 512ULL; - if((size < 3*1024*1024ull) || (size > 0x1FFFFFFFFull)/*8GB*/) { - // user picked geometry resulting in wrong size - WriteOut(MSG_Get("PROGRAM_IMGMAKE_BADSIZE")); - return; - } - } - } else { - // got -size - std::istringstream stream(isize); - stream >> size; - size *= 1024*1024LL; // size in megabytes - // low limit: 3 megs, high limit: 2 terabytes - // Int13 limit would be 8 gigs - if((size < 3*1024*1024ull) || (size > 0x1FFFFFFFFFFull)/*2TB*/) { - // wrong size - WriteOut(MSG_Get("PROGRAM_IMGMAKE_BADSIZE")); - return; - } - if(disktype == "vhd" && size > 2040*1024*1024*1024ull) {/*2040GB*/ - // wrong size - WriteOut(MSG_Get("PROGRAM_IMGMAKE_BADSIZE")); - return; - } - sectors = size / 512; - - if (alignment != 0u) { - sectors += (uint64_t)(alignment - 1u); - sectors -= sectors % (uint64_t)alignment; - } - - // Now that we finally have the proper size, figure out good CHS values - if (size > 0xFFFFFFFFull/*4GB*/) { - /* beyond that point it's easier to just map like LBA and be done with it */ - h=255; - s=63; - c=sectors/(h*s); - } - else { - h=2; - while(h*1023*63 < sectors) h <<= 1; - if(h>255) h=255; - s=8; - while(h*s*1023 < sectors) s *= 2; - if(s>63) s=63; - c=sectors/(h*s); - if(c>1023) c=1023; - } - } - } else { - // user passed a wrong -t argument - printHelp(); - return; - } - - std::string t2 = ""; - if(cmd->FindExist("-bat",true)) { - t2 = "-bat"; - } - - size = (uint64_t)c * (uint64_t)h * (uint64_t)s * 512ULL; - int64_t bootsect_pos = 0; // offset of the boot sector in clusters - if(cmd->FindExist("-nofs",true)) { - bootsect_pos = -1; - } - - if (cmd->FindExist("-chs",true)) - lbamode = 0; - else if (cmd->FindExist("-lba",true)) - lbamode = 1; - else - lbamode = size > (2048ULL << 20ULL); /* automatically choose LBA for 2GB or larger images */ - - /* beyond this point clamp c */ - if (c > 1023) c = 1023; - - /* temp_line is the given filename */ - if (!(cmd->FindCommand(1, temp_line))) - temp_line = "IMGMAKE.IMG"; - - bool setdir=false; - char dirCur[512], dirNew[512]; - if (!dos_kernel_disabled&&getcwd(dirCur, 512)!=NULL&&!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"local directory", 15)) { - Overlay_Drive *ddp = dynamic_cast(Drives[DOS_GetDefaultDrive()]); - strcpy(dirNew, ddp!=NULL?ddp->getOverlaydir():Drives[DOS_GetDefaultDrive()]->GetBaseDir()); - strcat(dirNew, Drives[DOS_GetDefaultDrive()]->curdir); - if (chdir(dirNew)==0) setdir=true; - } - -#if !defined(WIN32) && !defined(OS2) - if (setdir&&temp_line[0]!='/'&&!(temp_line[0]=='~'&&temp_line[1]=='/')) - std::replace(temp_line.begin(), temp_line.end(), '\\', '/'); - pref_struct_stat test; - std::string homedir(temp_line); - Cross::ResolveHomedir(homedir); - std::string homepath=homedir; - if (!pref_stat(dirname((char *)homepath.c_str()), &test) && test.st_mode & S_IFDIR) - temp_line = homedir; -#endif - FILE* f; - imageDiskVHD* vhd; - f = fopen(temp_line.c_str(), "r"); - if(f) { - fclose(f); - if(!ForceOverwrite) { - if(!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_FILE_EXISTS"), temp_line.c_str()); - if(setdir) chdir(dirCur); - return; - } - } - char extension[6] = {}; // care extensions longer than 3 letters such as '.vhdd' - if(temp_line.find_last_of('.') != std::string::npos) { - for(unsigned int i = 0; i < sizeof(extension) - 1; i++) { - if(temp_line.find_last_of('.') + i > temp_line.length() - 1) break; - extension[i] = temp_line[temp_line.find_last_of('.') + i]; - } - extension[sizeof(extension) - 1] = '\0'; // Terminate string just in case - } - if (!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_PRINT_CHS"),temp_line.c_str(),c,h,s); - LOG_MSG(MSG_Get("PROGRAM_IMGMAKE_PRINT_CHS"),temp_line.c_str(),c,h,s); - - // do it again for fixed chs values - sectors = size / 512; - - // create the image file - if(disktype == "vhd") { - uint32_t ret = imageDiskVHD::CreateDynamic(temp_line.c_str(), size); - switch(ret) { - case imageDiskVHD::ERROR_OPENING: - WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), temp_line.c_str()); - return; - case imageDiskVHD::ERROR_WRITING: - WriteOut(MSG_Get("PROGRAM_VHDMAKE_WRITERR"), temp_line.c_str()); - return; - } - if(imageDiskVHD::Open(temp_line.c_str(), false, (imageDisk**)&vhd) != imageDiskVHD::OPEN_SUCCESS) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), temp_line.c_str()); - return; - } - } - else { - f = fopen64(temp_line.c_str(), "wb+"); - if(!f) { - if(!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_CANNOT_WRITE"), temp_line.c_str()); - if(setdir) chdir(dirCur); - return; - } - -#if (defined (_MSC_VER) && (_MSC_VER >= 1400)) || defined(__MINGW32__) - if(fseeko64(f, (__int64)(size - 1ull), SEEK_SET)) { -#else - if(fseeko64(f, static_cast(size - 1ull), SEEK_SET)) { -#endif - if(!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_NOT_ENOUGH_SPACE"), size); - fclose(f); - unlink(temp_line.c_str()); - if(setdir) chdir(dirCur); - return; - } - uint8_t bufferbyte = 0; - if(fwrite(&bufferbyte, 1, 1, f) != 1) { - if(!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_NOT_ENOUGH_SPACE"), size); - fclose(f); - unlink(temp_line.c_str()); - if(setdir) chdir(dirCur); - return; - } - } - // Format the image if not unrequested (and image size<2GB) - if(bootsect_pos > -1) { - uint32_t reserved_sectors = 1; /* 1 for the boot sector + BPB. FAT32 will require more */ - uint64_t vol_sectors = 0; - uint8_t fat_copies = 2; /* number of copies of the FAT */ - uint32_t partsector = 0; - uint32_t fatlimitmin; - uint32_t fatlimit; - int8_t FAT = -1; - bool spc_changed = false; - bool rootent_changed = false; - - /* Partition sector override */ - if (cmd->FindString("-partofs",tmp,true)) { - partsector = atoi(tmp.c_str()); - if (partsector == 0) { - WriteOut("Invalid -partofs\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - } - - /* FAT filesystem, user choice */ - if (cmd->FindString("-fat",tmp,true)) { - FAT = atoi(tmp.c_str()); - if (!(FAT == 12 || FAT == 16 || FAT == 32)) { - WriteOut("Invalid -fat option. Must be 12, 16, or 32\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - } - - /* FAT copies, user choice */ - if (cmd->FindString("-fatcopies",tmp,true)) { - fat_copies = atoi(tmp.c_str()); - if (fat_copies < 1u || fat_copies > 4u) { - WriteOut("Invalid -fatcopies option\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - } - - /* Sectors per cluster, user choice */ - if (cmd->FindString("-spc",tmp,true)) { - sectors_per_cluster = atoi(tmp.c_str()); - if (sectors_per_cluster < 1u || sectors_per_cluster > 128u) { - WriteOut("Invalid -spc option, out of range\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - if ((sectors_per_cluster & (sectors_per_cluster - 1u)) != 0u) { - WriteOut("Invalid -spc option, must be a power of 2\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - spc_changed = true; - } - - /* Root directory count, user choice. - * Does not apply to FAT32, which makes the root directory an allocation chain like any other directory/file. */ - if (cmd->FindString("-rootdir",tmp,true)) { - root_ent = atoi(tmp.c_str()); - if (root_ent < 1u || root_ent > 4096u) { - WriteOut("Invalid -rootdir option\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - rootent_changed = true; - } - - /* decide partition placement */ - if (mediadesc == 0xF8) { - if (partsector > (uint32_t)0) - bootsect_pos = (int64_t)partsector; - else - bootsect_pos = (int64_t)s; - } - else { - bootsect_pos = 0; - } - - if (alignment != 0u) { - bootsect_pos += alignment - 1u; - bootsect_pos -= bootsect_pos % (int64_t)alignment; - } - - if (sectors <= (uint64_t)bootsect_pos) { - WriteOut("Invalid bootsector position\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - vol_sectors = sectors - (uint64_t)bootsect_pos; - - if (alignment != 0u) { - if ((vol_sectors % alignment) != 0u) { - WriteOut("Sanity check failed: Volume size not aligned\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - } - - /* auto-decide FAT system */ - if (is_fd) FAT = 12; - else if (FAT < 0) { - bool dosver_fat32 = (dos.version.major >= 8) || (dos.version.major == 7 && dos.version.minor >= 10); - - if (vol_sectors >= 2*1024*1024*1024ull/512ull && !dosver_fat32) /* 2GB or larger */ - FAT = 32; - else if (vol_sectors >= 512*1024*1024ull/512ull && dosver_fat32) /* 512MB or larger */ - FAT = 32; - else if (vol_sectors >= 12*1024*1024ull/512ull) /* 12MB or larger */ - FAT = 16; - else - FAT = 12; - } - - /* highest cluster number + 1 */ - switch (FAT) { - case 32: - fatlimit = 0x0FFFFFF6u; - fatlimitmin = 0xFFF6u; - break; - case 16: - fatlimit = 0xFFF6u; - fatlimitmin = 0xFF6u; - break; - case 12: - fatlimit = 0xFF6u; - fatlimitmin = 0u; - break; - default: - abort(); - } - - /* FAT32 increases reserved area to at least 7. Microsoft likes to use 32 */ - if (FAT >= 32) - reserved_sectors = 32; - - if (alignment != 0u) { - reserved_sectors += alignment - 1u; - reserved_sectors -= reserved_sectors % alignment; - } - - uint8_t sbuf[512]; - if(mediadesc == 0xF8) { - // is a harddisk: write MBR - memcpy(sbuf,freedos_mbr,512); - // active partition - sbuf[0x1be]=0x80; - // start head - head 0 has the partition table, head 1 first partition - // start sector with bits 8-9 of start cylinder in bits 6-7 - // start cylinder bits 0-7 - lba2chs3(sbuf+0x1bf,bootsect_pos,c,h,s); - // OS indicator - if (FAT < 32 && (bootsect_pos+vol_sectors) < 65536) { /* 32MB or smaller */ - if (FAT >= 16) - sbuf[0x1c2]=0x04; /* FAT16 within the first 32MB */ - else - sbuf[0x1c2]=0x01; /* FAT12 within the first 32MB */ - } - else if (!lbamode) { /* 4GB or smaller */ - if (FAT >= 32) - sbuf[0x1c2]=0x0B; /* FAT32 C/H/S */ - else - sbuf[0x1c2]=0x06; /* FAT12/FAT16 C/H/S */ - } - else { - if (FAT >= 32) - sbuf[0x1c2]=0x0C; /* FAT32 LBA */ - else - sbuf[0x1c2]=0x0E; /* FAT12/FAT16 LBA */ - } - // end head (0-based) - // end sector with bits 8-9 of end cylinder (0-based) in bits 6-7 - // end cylinder (0-based) bits 0-7 - lba2chs3(sbuf+0x1c3,bootsect_pos+vol_sectors-1ul,c,h,s); - // sectors preceding partition1 (one head) - host_writed(&sbuf[0x1c6],(uint32_t)bootsect_pos); - // length of partition1, align to chs value - host_writed(&sbuf[0x1ca],vol_sectors); - - // write partition table - if(disktype != "vhd") { - fseeko64(f, 0, SEEK_SET); - fwrite(&sbuf, 512, 1, f); - } - else { - vhd->Write_AbsoluteSector(0, sbuf); - } - } - - // set boot sector values - memset(sbuf,0,512); - // TODO boot code jump - if (FAT >= 32) { - sbuf[0]=0xEB; sbuf[1]=0x58; sbuf[2]=0x90; // Windows 98 values - } - else { - sbuf[0]=0xEB; sbuf[1]=0x3c; sbuf[2]=0x90; - } - // OEM - if (FAT >= 32) { - sprintf((char*)&sbuf[0x03],"MSWIN4.1"); - } else { - sprintf((char*)&sbuf[0x03],"MSDOS5.0"); - } - // bytes per sector: always 512 - host_writew(&sbuf[BytsPerSec],512); - // sectors per cluster: 1,2,4,8,16,... - // NOTES: SCANDISK.EXE will hang if you ask it to check a FAT12 filesystem with 128 sectors/cluster. - if (sectors_per_cluster == 0) { - sectors_per_cluster = 1; - /* one sector per cluster on anything larger than 200KB is a bit wasteful (large FAT tables). - * Improve capacity by starting from a larger value.*/ - if (vol_sectors >= 400) { - unsigned int tmp_fatlimit; - - /* Windows 98 likes multiples of 4KB, which is actually reasonable considering - * that it keeps FAT32 efficient. Also, Windows 98 SETUP will crash if sectors/cluster - * is too small. Ref: [https://github.com/joncampbell123/dosbox-x/issues/1553#issuecomment-651880604] - * and [http://www.helpwithwindows.com/windows98/fat32.html] */ - if (FAT >= 32) { - if (vol_sectors >= 67108864/*32GB*/) - sectors_per_cluster = 64; /* 32KB (64*512) */ - else if (vol_sectors >= 33554432/*16GB*/) - sectors_per_cluster = 32; /* 16KB (32*512) */ - else if (vol_sectors >= 16777216/*8GB*/) - sectors_per_cluster = 16; /* 8KB (16*512) */ - else - sectors_per_cluster = 8; /* 4KB (8*512) */ - } - else { - /* 1 sector per cluster is very inefficient */ - if (vol_sectors >= 6144000/*3000MB*/) - sectors_per_cluster = 8; - else if (vol_sectors >= 1048576/*512MB*/) - sectors_per_cluster = 4; - else if (vol_sectors >= 131072/*64MB*/) - sectors_per_cluster = 2; - } - - /* no more than 5% of the disk */ - switch (FAT) { - case 12: tmp_fatlimit = ((((vol_sectors / 20u) * (512u / fat_copies)) / 3u) * 2u) + 2u; break; - case 16: tmp_fatlimit = (((vol_sectors / 20u) * (512u / fat_copies)) / 2u) + 2u; break; - case 32: tmp_fatlimit = (((vol_sectors / 20u) * (512u / fat_copies)) / 4u) + 2u; break; - default: abort(); - } - - while ((vol_sectors/sectors_per_cluster) >= (tmp_fatlimit - 2u) && sectors_per_cluster < 0x80u) sectors_per_cluster <<= 1; - } - } - - /* if alignment is a power of 2, align sectors per cluster to it */ - if (bitop::ispowerof2(alignment)) { - while (sectors_per_cluster < 0x80u && sectors_per_cluster < alignment) sectors_per_cluster <<= 1; - } - - /* FAT12/FAT16 size the root directory so that it is aligned, which then aligns the data area following it */ - if (alignment != 0u && FAT < 32) { - const uint32_t t_alignment = alignment * (512u / 32u); /* 512 bytes/sector, 32 bytes per dirent = number of root dirents per sector */ - root_ent += t_alignment - 1; - root_ent -= root_ent % t_alignment; - } - - while (!is_fd && (vol_sectors/sectors_per_cluster) >= (fatlimit - 2u) && sectors_per_cluster < 0x80u) sectors_per_cluster <<= 1; - sbuf[SecPerClus]=(uint8_t)sectors_per_cluster; - // reserved sectors - host_writew(&sbuf[RsvdSecCnt],reserved_sectors); - // Number of FATs - sbuf[NumFATs] = fat_copies; - // Root entries if not FAT32 - if (FAT < 32) host_writew(&sbuf[RootEntCnt],root_ent); - // sectors (under 32MB) if not FAT32 and less than 65536 - if (FAT < 32 && vol_sectors < 65536ul) host_writew(&sbuf[TotSec16],vol_sectors); - // sectors (32MB or larger or FAT32) - if (FAT >= 32 || vol_sectors >= 65536ul) host_writed(&sbuf[TotSec32],vol_sectors); - else host_writed(&sbuf[TotSec32],0); - // media descriptor - sbuf[Media]=mediadesc; - // needed entries: (sectors per cluster) - uint64_t clusters = vol_sectors / sectors_per_cluster; // initial estimate - - // sectors per FAT - if (FAT >= 32) sect_per_fat = ((clusters*4u)+511u)/512u; - else if (FAT >= 16) sect_per_fat = ((clusters*2u)+511u)/512u; - // Use standard sect_per_fat values for standard floppy images, otherwise it may required to be adjusted - else if (!is_fd || sect_per_fat == 0 || (is_fd && (rootent_changed || (fat_copies != 2)))) sect_per_fat = ((((clusters+1u)/2u)*3u)+511u)/512u; - - if (alignment != 0u) { - if (alignment % fat_copies) { - sect_per_fat += alignment - 1u; - sect_per_fat -= sect_per_fat % alignment; - } - else { - const uint32_t t_alignment = alignment / fat_copies; /* we could align sect_per_fat based on ALL copies of the FAT table */ - sect_per_fat += t_alignment - 1u; - sect_per_fat -= sect_per_fat % t_alignment; - } - } - - if (alignment != 0u) { - if ((((uint64_t)sect_per_fat * (uint64_t)fat_copies) % (uint64_t)alignment) != 0u) { - WriteOut("Sanity check failed: FAT tables not aligned\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - } - - if (FAT < 32 && sect_per_fat > 256u) { - WriteOut("Error: Generated filesystem has more than 256 sectors per FAT and is not FAT32\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - - uint32_t root_ent_sec = 0; - uint64_t data_area = vol_sectors - reserved_sectors - (sect_per_fat * fat_copies); - if (FAT < 32) { - root_ent_sec = ((root_ent * 32u) + 511u) / 512u; - data_area -= root_ent_sec; - } - clusters = data_area / sectors_per_cluster; - if (FAT < 32) host_writew(&sbuf[FATSz16],(uint16_t)sect_per_fat); - - if (alignment != 0u) { - if ((root_ent_sec % alignment) != 0u) { - WriteOut("Sanity check failed: Volume size not aligned\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - } - - /* Too many or to few clusters can foul up FAT12/FAT16/FAT32 detection and cause corruption! */ - if ((clusters+2u) < fatlimitmin) { - WriteOut("Error: Generated filesystem has too few clusters given the parameters\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - if ((clusters+2u) > fatlimit) { - clusters = fatlimit-2u; - WriteOut("Warning: Cluster count is too high given the volume size. Reporting a\n"); - WriteOut(" smaller sector count.\n"); - /* Well, if the user wants an oversized partition, hack the total sectors fields to make it work */ - uint32_t adj_vol_sectors = - (uint32_t)(reserved_sectors + (sect_per_fat * fat_copies) + - (((root_ent * 32u) + 511u) / 512u) + (clusters * sectors_per_cluster)); - - // sectors (under 32MB) if not FAT32 and less than 65536 - if (adj_vol_sectors < 65536ul) host_writew(&sbuf[TotSec16],(uint16_t)adj_vol_sectors); - // sectors (32MB or larger or FAT32) - if (adj_vol_sectors >= 65536ul) host_writed(&sbuf[TotSec32],adj_vol_sectors); - else host_writed(&sbuf[TotSec32],0); - } - - const unsigned long long first_cluster = - (unsigned long long)bootsect_pos + reserved_sectors + - ((unsigned long long)sect_per_fat * (unsigned long long)fat_copies) + - (unsigned long long)root_ent_sec; - - /* do not validate alignment of data area, because some of the fd and hd presets might - * violate it, but certainly make sure that the first cluster is aligned */ - if (alignment != 0u) { - if ((first_cluster % (unsigned long long)alignment) != 0ull) { - WriteOut("Sanity check failed: First cluster not aligned\n"); - fclose(f); - unlink(temp_line.c_str()); - if (setdir) chdir(dirCur); - return; - } - } - - // sectors per track - host_writew(&sbuf[SecPerTrk],s); - // heads - host_writew(&sbuf[NumHeads],h); - // hidden sectors - host_writed(&sbuf[HiddSec],(uint32_t)bootsect_pos); - /* after 0x24, FAT12/FAT16 and FAT32 diverge in structure */ - if (FAT >= 32) { - host_writed(&sbuf[FATSz32],sect_per_fat); - sbuf[0x28] = 0x00; // FAT is mirrored at runtime because that is what DOSBox-X's FAT driver does - host_writew(&sbuf[0x2A],0x0000); // FAT32 version 0.0 - host_writed(&sbuf[0x2C],2); // root directory starting cluster - host_writew(&sbuf[0x30],1); // sector number in reserved area of FSINFO structure - host_writew(&sbuf[0x32],6); // sector number in reserved area of backup boot sector - // BIOS drive - sbuf[DrvNum32] = (mediadesc == 0xF8) ? 0x80 : 0x00; - // ext. boot signature - sbuf[BootSig32] = 0x29; - // Volume label - sprintf((char*)&sbuf[VolLab32], "NO NAME "); - // volume serial number - // let's use the BIOS time (cheap, huh?) - host_writed(&sbuf[VolID32], mem_readd(BIOS_TIMER)); - // file system type - sprintf((char*)&sbuf[FilSysType32],"FAT32 "); - } - else { /* FAT12/FAT16 */ - // BIOS drive - sbuf[BootSig] = 0x29; - // Volume label - sprintf((char*)&sbuf[VolLab], "NO NAME "); - // volume serial number - // let's use the BIOS time (cheap, huh?) - host_writed(&sbuf[VolID], mem_readd(BIOS_TIMER)); - if(is_fd) { - uint8_t index = 0; - while(DiskGeometryList[index].cylcount != 0) { - if(DiskGeometryList[index].ksize == disksize) { - sbuf[Media] = DiskGeometryList[index].mediaid; - mediadesc = DiskGeometryList[index].mediaid; - host_writew(&sbuf[SecPerTrk],DiskGeometryList[index].secttrack); - host_writew(&sbuf[NumHeads], DiskGeometryList[index].headscyl); - host_writew(&sbuf[BytsPerSec], DiskGeometryList[index].bytespersect); - sbuf[SecPerClus] = spc_changed ? sectors_per_cluster : DiskGeometryList[index].sectcluster; - host_writew(&sbuf[RootEntCnt], rootent_changed ? root_ent : DiskGeometryList[index].rootentries); - host_writew(&sbuf[FATSz16],sect_per_fat); - break; - } - index++; - } - } - // BIOS drive - sbuf[DrvNum] = (mediadesc == 0xF8) ? 0x80 : 0x00; - // file system type - if (FAT >= 16) sprintf((char*)&sbuf[FilSysType],"FAT16 "); - else sprintf((char*)&sbuf[FilSysType],"FAT12 "); - } - // boot sector signature - host_writew(&sbuf[BootSign],0xAA55); - - // if anything should try to boot this partition, add code to print an error message instead of - // letting the CPU run wild through not executable code. - if (FAT >= 32) { - // the code expects to load a string from a fixed address. - // we're relocating it to make room for FAT32 structures so some patching is required. - memcpy(sbuf+BootCode32,this_is_not_a_bootable_partition+0x3E,BootSign - BootCode32); - host_writew(sbuf+0x5D,0x7C77); // 0x7C5D: MOV SI, we are patching the - } - else { - memcpy(sbuf+BootCode,this_is_not_a_bootable_partition+0x3E,BootSign - BootCode); - } - - // write label - if (!label.empty()) { - const char *s = label.c_str(); - unsigned int i; - char *d; - - if (FAT >= 32) d = (char*)sbuf + VolLab32; - else d = (char*)sbuf + VolLab; - - for (i=0;i < 11 && *s;i++) *d++ = *s++; - for ( ;i < 11; i++) *d++ = ' '; - } - - // write the boot sector - if(disktype == "vhd") { - vhd->Write_AbsoluteSector(bootsect_pos, sbuf); - } - else { - fseeko64(f, bootsect_pos * 512, SEEK_SET); - fwrite(&sbuf, 512, 1, f); - } - // FAT32: Write backup copy too. - // The BPB we wrote says sector 6 from start of volume - if(FAT >= 32) { - if(disktype != "vhd") { - fseeko64(f, (bootsect_pos + 6u) * 512, SEEK_SET); - fwrite(&sbuf, 512, 1, f); - } - else { - vhd->Write_AbsoluteSector((bootsect_pos + 6u), sbuf); - } - } - // FAT32: Write FSInfo sector too at sector 1 from start of volume. - // Windows 98 behavior shows that the FSInfo is duplicated - // along with the boot sector. - if (FAT >= 32) { - memset(sbuf,0,512); - host_writed(&sbuf[0x000],0x41615252); /* "RRaA" */ - host_writed(&sbuf[0x1e4],0x61417272); /* "rrAa" */ - host_writed(&sbuf[0x1e8],(uint32_t)(clusters-1)); /* Last known free cluster count */ - host_writed(&sbuf[0x1ec],3); /* Next free cluster. We used 2 for the root dir, so 3 is next */ - host_writed(&sbuf[0x1fc],0xAA550000); /* signature */ - if(disktype != "vhd") { - fseeko64(f, (bootsect_pos + 1u) * 512, SEEK_SET); - fwrite(&sbuf, 512, 1, f); - fseeko64(f, (bootsect_pos + 6u + 1u) * 512, SEEK_SET); - fwrite(&sbuf, 512, 1, f); - } - else { - vhd->Write_AbsoluteSector((bootsect_pos + 1u), sbuf); - vhd->Write_AbsoluteSector((bootsect_pos + 6u +1u), sbuf); - } - } - - // write FATs - memset(sbuf,0,512); - if (FAT >= 32) { - host_writed(&sbuf[0],0x0FFFFF00 | mediadesc); - host_writed(&sbuf[4],0x0FFFFFFF); - - /* The code above marks cluster 2 as the start of the root directory. */ - host_writed(&sbuf[8],0x0FFFFFFF); - } - else if (FAT >= 16) - host_writed(&sbuf[0],0xFFFFFF00 | mediadesc); - else - host_writed(&sbuf[0],0xFFFF00 | mediadesc); - - for (unsigned int fat=0;fat < fat_copies;fat++) { - if(disktype != "vhd") { - fseeko64(f, (off_t)(((unsigned long long)bootsect_pos + reserved_sectors + (unsigned long long)sect_per_fat * (unsigned long long)fat) * 512ull), SEEK_SET); - fwrite(&sbuf, 512, 1, f); - } - else { - vhd->Write_AbsoluteSector((unsigned long long)bootsect_pos + reserved_sectors + (unsigned long long)sect_per_fat * (unsigned long long)fat, sbuf); - } - } - - // write label in root directory, as first entry - if (!label.empty()) { - const char *s = label.c_str(); - unsigned int i; - char *d; - - unsigned long long sec; - - /* FAT12/FAT16: This points at the root directory area. - * FAT32: This points at the root directory only because this code constructed the root directory allocation chain - * starting at cluster 2, which is the first cluster of the data area. */ - sec = (unsigned long long)bootsect_pos + reserved_sectors + - ((unsigned long long)sect_per_fat * (unsigned long long)fat_copies); - - memset(sbuf,0,512); - - d = (char*)sbuf; - for (i=0;i < 11 && *s;i++) *d++ = *s++; - for ( ;i < 11; i++) *d++ = ' '; - sbuf[11] = 0x08; /* volume label */ - - if(disktype != "vhd") { - fseeko64(f, (off_t)(sec * 512ull), SEEK_SET); - fwrite(&sbuf, 512, 1, f); - } - else { - vhd->Write_AbsoluteSector(sec, sbuf); - } - } - - // warning - if ((sectors_per_cluster*512ul) >= 65536ul) - WriteOut("WARNING: Cluster sizes >= 64KB are not compatible with MS-DOS and SCANDISK\n"); - } - // write VHD footer if requested - if((mediadesc == 0xF8) && disktype != "vhd" && !strcasecmp(extension, ".vhd")) { - imageDiskVHD::VHDFooter footer; - footer.SetDefaults(); - footer.dataOffset = 0xFFFFFFFFFFFFFFFF; - footer.originalSize = footer.currentSize = size; - footer.geometry.cylinders = c; - footer.geometry.heads = h; - footer.geometry.sectors = s; - footer.diskType = imageDiskVHD::VHD_TYPE_FIXED; - imageDiskVHD::mk_uuid((uint8_t*)footer.uniqueId); - footer.checksum = footer.CalculateChecksum(); - footer.SwapByteOrder(); - // write footer - fseeko64(f, 0L, SEEK_END); - fwrite(&footer,512,1,f); - } - if(disktype != "vhd") { - fclose(f); - } - else { - delete vhd; - } - // create the batch file - if(t2 == "-bat") { - if(temp_line.length() > 3) { - t2 = temp_line.substr(0,temp_line.length()-4) + ".bat"; - } else { - t2 = temp_line + ".bat"; - } - WriteOut("%s\n",t2.c_str()); - f = fopen(t2.c_str(),"wb+"); - if (!f) { - WriteOut(MSG_Get("PROGRAM_IMGMAKE_CANNOT_WRITE"),t2.c_str()); - if (setdir) { - chdir(dirCur); - runRescan("-Q"); - } - return; - } - - if (bootsect_pos < 0) /* -nofs */ - fprintf(f,"imgmount 2 %s -size 512,%u,%u,%u\r\n",temp_line.c_str(),s,h,c); - else - fprintf(f,"imgmount c %s -size 512,%u,%u,%u\r\n",temp_line.c_str(),s,h,c); - - fclose(f); - } - if (setdir) { - chdir(dirCur); - runRescan("-Q"); - } - return; - } - void printHelp() { // maybe hint parameter? - resetcolor = true; - WriteOut(MSG_Get("PROGRAM_IMGMAKE_SYNTAX")); - } -}; - -static void IMGMAKE_ProgramStart(Program * * make) { - *make=new IMGMAKE; -} - -void runImgmake(const char *str) { - IMGMAKE imgmake; - imgmake.cmd=new CommandLine("IMGMAKE", str); - imgmake.Run(); -} - -void swapInDrive(int drive, unsigned int position=0); -class IMGSWAP : public Program -{ -public: - void ListImgSwaps(void) { - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; - /* Command uses dta so set it to our internal dta */ - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - WriteOut(MSG_Get("PROGRAM_IMGSWAP_STATUS")); - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),MSG_Get("DRIVE"),MSG_Get("TYPE"),MSG_Get("LABEL"),MSG_Get("SWAP_SLOT")); - int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - if (!cols) cols=80; - for(int p = 1;p < cols;p++) WriteOut("-"); - WriteOut("\n"); - bool none=true; - for (int d = 0;d < DOS_DRIVES;d++) { - if (!Drives[d] || (strncmp(Drives[d]->GetInfo(), "fatDrive ", 9) && strncmp(Drives[d]->GetInfo(), "isoDrive ", 9))||(int)DriveManager::GetDisksSize(d)<2) continue; - char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; - bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); - if (ret) { - dta.GetResult(name,lname,size,hsize,date,time,attr); - DOS_FindNext(); //Mark entry as invalid - } else name[0] = 0; - - /* Change 8.3 to 11.0 */ - const char* dot = strchr(name, '.'); - if(dot && (dot - name == 8) ) { - name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; - } - - root[1] = 0; //This way, the format string can be reused. - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name,DriveManager::GetDrivePosition(d)); - none=false; - } - if (none) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); - dos.dta(save_dta); - } - void Run() override - { - //Hack To allow long commandlines - ChangeToLongCmd(); - - if(cmd->FindExist("/?", true) || cmd->FindExist("-?", true) || cmd->FindExist("?", true)) { - resetcolor = true; - WriteOut("Swaps floppy, hard drive and optical disc images.\n\n" - "\033[32;1mIMGSWAP\033[0m \033[37;1mdrive\033[0m \033[36;1m[position]\033[0m\n" - " \033[37;1mdrive\033[0m Drive letter to swap the image.\n" - " \033[36;1m[position]\033[0m Disk position to swap to.\n"); - return; - } - if (!cmd->GetCount()) { - ListImgSwaps(); - return; - } - if (!cmd->FindCommand(1,temp_line) || (temp_line.size() > 2) || ((temp_line.size()>1) && (temp_line[1]!=':')) || (!(temp_line[0] >= 'A' && temp_line[0] <= 'Z') && !(temp_line[0] >= 'a' && temp_line[0] <= 'z'))) { - WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); - return; - } - int d=temp_line[0] - (temp_line[0] >= 'a' && temp_line[0] <= 'z' ? 'a' : 'A'); - if (!Drives[d] || (strncmp(Drives[d]->GetInfo(), "fatDrive ", 9) && strncmp(Drives[d]->GetInfo(), "isoDrive ", 9)) || (int)DriveManager::GetDisksSize(d)<2) { - ListImgSwaps(); - return; - } - if (cmd->FindCommand(2,temp_line)) { - int swap=atoi(temp_line.c_str()); - if (swap<1||swap>DriveManager::GetDisksSize(d)) { - WriteOut(MSG_Get("PROGRAM_IMGSWAP_ERROR"), DriveManager::GetDisksSize(d)); - return; - } - swapInDrive(d,swap); - } else - swapInDrive(d); - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; - /* Command uses dta so set it to our internal dta */ - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),MSG_Get("DRIVE"),MSG_Get("TYPE"),MSG_Get("LABEL"),MSG_Get("SWAP_SLOT")); - int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - if (!cols) cols=80; - for(int p = 1;p < cols;p++) WriteOut("-"); - WriteOut("\n"); - char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; - bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); - if (ret) { - dta.GetResult(name,lname,size,hsize,date,time,attr); - DOS_FindNext(); //Mark entry as invalid - } else name[0] = 0; - - /* Change 8.3 to 11.0 */ - const char* dot = strchr(name, '.'); - if(dot && (dot - name == 8) ) { - name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; - } - - root[1] = 0; //This way, the format string can be reused. - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name,DriveManager::GetDrivePosition(d)); - dos.dta(save_dta); - } -}; - -void IMGSWAP_ProgramStart(Program** make) -{ - *make = new IMGSWAP; -} - -// LOADFIX - -class LOADFIX : public Program { -public: - void Run(void) override; -}; - -bool XMS_Active(void); -Bitu XMS_AllocateMemory(Bitu size, uint16_t& handle); -Bitu XMS_FreeMemory(Bitu handle); -uint8_t EMM_AllocateMemory(uint16_t pages,uint16_t & dhandle,bool can_allocate_zpages); -uint8_t EMM_ReleaseMemory(uint16_t handle); -bool EMS_Active(void); - -/* HIMEM.SYS does not store who owns what block, so for -D or -F to work, - * we need to keep track of handles ourself */ -std::vector LOADFIX_xms_handles; -std::vector LOADFIX_ems_handles; - -void LOADFIX_OnDOSShutdown(void) { - LOADFIX_xms_handles.clear(); - LOADFIX_ems_handles.clear(); -} - -void LOADFIX::Run(void) -{ - uint16_t commandNr = 1; - Bitu kb = 64; - bool xms = false; - bool ems = false; - bool opta = false; - - if (cmd->FindExist("-xms",true) || cmd->FindExist("/xms",true)) { - xms = true; - kb = 1024; - } - - if (cmd->FindExist("-ems",true) || cmd->FindExist("/ems",true)) { - ems = true; - kb = 1024; - } - - if (cmd->FindExist("-a",true) || cmd->FindExist("/a",true)) - opta = true; - - if (cmd->GetCount()==1 && (cmd->FindExist("-?", false) || cmd->FindExist("/?", false))) { - resetcolor = true; - WriteOut(MSG_Get("PROGRAM_LOADFIX_HELP")); - return; - } - - if (cmd->FindCommand(commandNr,temp_line)) { - if (temp_line[0]=='-' || (temp_line[0]=='/')) { - char ch = temp_line[1]; - if ((*upcase(&ch)=='D') || (*upcase(&ch)=='F')) { - // Deallocate all - if (ems) { - for (auto i=LOADFIX_ems_handles.begin();i!=LOADFIX_ems_handles.end();i++) { - if (EMM_ReleaseMemory(*i)) - WriteOut("XMS handle %u: unable to free",*i); - } - LOADFIX_ems_handles.clear(); - WriteOut(MSG_Get("PROGRAM_LOADFIX_DEALLOCALL"),kb); - } - else if (xms) { - for (auto i=LOADFIX_xms_handles.begin();i!=LOADFIX_xms_handles.end();i++) { - if (XMS_FreeMemory(*i)) - WriteOut("XMS handle %u: unable to free",*i); - } - LOADFIX_xms_handles.clear(); - WriteOut(MSG_Get("PROGRAM_LOADFIX_DEALLOCALL"),kb); - } - else { - DOS_FreeProcessMemory(0x40); - WriteOut(MSG_Get("PROGRAM_LOADFIX_DEALLOCALL"),kb); - } - return; - } else { - // Set mem amount to allocate - kb = (Bitu)atoi(temp_line.c_str()+1); - if (kb==0) kb=xms?1024:64; - commandNr++; - } - } - } - - // Allocate Memory - if (ems) { - if (EMS_Active()) { - uint16_t handle; - Bitu err; - - /* EMS allocates in 16kb increments */ - kb = (kb + 15u) & (~15u); - - err = EMM_AllocateMemory((uint16_t)(kb/16u)/*16KB pages*/,/*&*/handle,false); - if (err == 0) { - WriteOut("EMS block allocated (%uKB)\n",kb); - LOADFIX_ems_handles.push_back(handle); - } - else { - WriteOut("Unable to allocate EMS block\n"); - } - } - else { - WriteOut("EMS not active\n"); - } - } - else if (xms) { - if (XMS_Active()) { - uint16_t handle; - Bitu err; - - err = XMS_AllocateMemory(kb,/*&*/handle); - if (err == 0) { - WriteOut("XMS block allocated (%uKB)\n",kb); - LOADFIX_xms_handles.push_back(handle); - } - else { - WriteOut("Unable to allocate XMS block\n"); - } - } - else { - WriteOut("XMS not active\n"); - } - } - else { - uint16_t segment; - uint16_t blocks = (uint16_t)(kb*1024/16); - if (DOS_AllocateMemory(&segment,&blocks)) { - DOS_MCB mcb((uint16_t)(segment-1)); - if (opta) { - if (segment < 0x1000) { - uint16_t needed = 0x1000 - segment; - if (DOS_ResizeMemory(segment,&needed)) - kb=needed*16/1024; - } - else { - DOS_FreeMemory(segment); - WriteOut("Lowest MCB is above 64KB, nothing allocated\n"); - return; - } - } - mcb.SetPSPSeg(0x40); // use fake segment - WriteOut(MSG_Get("PROGRAM_LOADFIX_ALLOC"),kb); - // Prepare commandline... - if (cmd->FindCommand(commandNr++,temp_line)) { - // get Filename - char filename[128]; - safe_strncpy(filename,temp_line.c_str(),128); - // Setup commandline - char args[256 + 1]; - args[0] = 0; - bool found = cmd->FindCommand(commandNr++, temp_line); - while (found) { - if (strlen(args) + temp_line.length() + 1 > 256) break; - strcat(args, temp_line.c_str()); - found = cmd->FindCommand(commandNr++, temp_line); - if (found) strcat(args, " "); - } - // Use shell to start program - DOS_Shell shell; - shell.Execute(filename,args); - DOS_FreeMemory(segment); - WriteOut(MSG_Get("PROGRAM_LOADFIX_DEALLOC"),kb); - } - } else { - WriteOut(MSG_Get("PROGRAM_LOADFIX_ERROR"),kb); - } - } -} - -static void LOADFIX_ProgramStart(Program * * make) { - *make=new LOADFIX; -} - -// RESCAN - -class RESCAN : public Program { -public: - void Run(void) override; -}; - -void RESCAN::Run(void) -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Rescans for changes on mounted drives made on the host by clearing caches.\n\nRESCAN [/A] [/Q]\nRESCAN [drive:] [/Q]\n\n [/A]\t\tRescan all drives\n [/Q]\t\tEnable quiet mode\n [drive:]\tThe drive to rescan\n\nType RESCAN with no parameters to rescan the current drive.\n"); - return; - } - bool all = false, quiet = false; - if (cmd->FindExist("-q",true) || cmd->FindExist("/q",true)) - quiet = true; - - uint8_t drive = DOS_GetDefaultDrive(); - if(cmd->FindCommand(1,temp_line)) { - //-A -All /A /All - if(temp_line.size() >= 2 && (temp_line[0] == '-' ||temp_line[0] =='/')&& (temp_line[1] == 'a' || temp_line[1] =='A') ) all = true; - else if(temp_line.size() == 2 && temp_line[1] == ':') { - lowcase(temp_line); - drive = temp_line[0] - 'a'; - } - } - // Get current drive - if (all) { - for(Bitu i =0; iEmptyCache(); - } - if (!quiet) WriteOut(MSG_Get("PROGRAM_RESCAN_SUCCESS")); - } else { - if (drive < DOS_DRIVES && Drives[drive]) { - Drives[drive]->EmptyCache(); - if (!quiet) WriteOut(MSG_Get("PROGRAM_RESCAN_SUCCESS")); - } else - if (!quiet) WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_NOT_FOUND"), 'A'+drive); - } -} - -static void RESCAN_ProgramStart(Program * * make) { - *make=new RESCAN; -} - -void runRescan(const char *str) { - RESCAN rescan; - rescan.cmd=new CommandLine("RESCAN", str); - rescan.Run(); -} - -/* TODO: This menu code sucks. Write a better one. */ -class INTRO : public Program { -public: - void DisplayMount(void) { - /* Basic mounting has a version for each operating system. - * This is done this way so both messages appear in the language file*/ - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_START")); - if (machine == MCH_PC98) { -#if (WIN32) - WriteOut("\033[44;1m\x86\x52\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x56\n" - "\033[44;1m\x86\x46\033[0m "); - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXST_WINDOWS")); - WriteOut(" \033[44;1m\x86\x46\033[0m\n\033[44;1m\x86\x46\033[0m \033[44;1m\x86\x46\033[0m\n\033[44;1m\x86\x46\033[0m "); - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXEN_WINDOWS")); - WriteOut(" \033[37m \033[44;1m\x86\x46\033[44;1m\n" - "\033[44;1m\x86\x5A\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x5E\033[0m\n" - ); -#else - WriteOut("\033[44;1m\x86\x52\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x56\n" - "\x86\x46 "); - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXST_OTHER")); - WriteOut(" \x86\x46\n\x86\x46 \x86\x46\n\x86\x46 "); - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXEN_OTHER")); - WriteOut(" \033[37m \x86\x46\n" - "\x86\x5A\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" - "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x5E\033[0m\n" - ); -#endif - } else { -#if (WIN32) - WriteOut("\033[44;1m\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\n" - "\xBA "); - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXST_WINDOWS")); - WriteOut("\xBA\n\xBA \xBA\n\xBA "); - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXEN_WINDOWS")); - WriteOut("\xBA\n" - "\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\033[0m\n"); -#else - WriteOut("\033[44;1m\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\n" - "\xBA "); - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXST_OTHER")); - WriteOut("\xBA\n\xBA \xBA\n\xBA "); - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXEN_OTHER")); - WriteOut("\xBA\n" - "\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" - "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\033[0m\n"); -#endif - } - WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_END")); - } - void DisplayUsage(void) { - uint8_t c;uint16_t n=1; - WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_TOP")); - WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_1")); - DOS_ReadFile (STDIN,&c,&n); - WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_TOP")); - WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_2")); - DOS_ReadFile (STDIN,&c,&n); - WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_TOP")); - WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_3")); - DOS_ReadFile (STDIN,&c,&n); - } - void DisplayIntro(void) { - WriteOut(MSG_Get("PROGRAM_INTRO")); - WriteOut("\033[44m\033[K\033[0m\n\033[44m\033[K\033[1m\033[1m\t\t\t\t\t\t\t "); - WriteOut(MSG_Get("PROGRAM_INTRO_MENU_UP")); - if (machine == MCH_PC98) - WriteOut("\033[0m\n" - "\033[44m\033[K\033[1m\033[1m \x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\033[0m\n" - "\033[44m\033[K\033[0m\n" - ); - else - WriteOut(" \033[0m\n" - "\033[44m\033[K\033[1m\033[1m \xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\033[0m\n" - "\033[44m\033[K\033[0m\n" - ); - } - void DisplayMenuBefore(void) { WriteOut("\033[44m\033[K\033[33m\033[1m \033[0m "); } - void DisplayMenuCursorStart(void) { - if (machine == MCH_PC98) { - WriteOut("\033[44m\033[K\033[1m\033[33;44m \x1C\033[0m\033[5;37;44m "); - } else { - WriteOut("\033[44m\033[K\033[1m\033[33;44m \x10\033[0m\033[5;37;44m "); - } - } - void DisplayMenuCursorEnd(void) { WriteOut("\033[0m\n"); } - void DisplayMenuNone(void) { WriteOut("\033[44m\033[K\033[0m\n"); } - - bool CON_IN(uint8_t * data) const { - uint8_t c; - uint16_t n=1; - - /* handle arrow keys vs normal input, - * with special conditions for PC-98 and IBM PC */ - if (!DOS_ReadFile(STDIN,&c,&n) || n == 0) return false; - - if (IS_PC98_ARCH) { - /* translate PC-98 arrow keys to IBM PC escape for the caller */ - if (c == 0x0B) - *data = 0x48 | 0x80; /* IBM extended code up arrow */ - else if (c == 0x0A) - *data = 0x50 | 0x80; /* IBM extended code down arrow */ - else - *data = c; - } - else { - if (c == 0) { - if (!DOS_ReadFile(STDIN,&c,&n) || n == 0) return false; - *data = c | 0x80; /* extended code */ - } - else { - *data = c; - } - } - - return true; - } - - void Run(void) override { - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("A full-screen introduction to DOSBox-X.\n\nINTRO [/RUN] [CDROM|MOUNT|USAGE|WELCOME]\n"); - return; - } - uint8_t attr = DOS_GetAnsiAttr(); - std::string menuname = "BASIC"; // default - /* Only run if called from the first shell (Xcom TFTD runs any intro file in the path) */ - if (!cmd->FindExist("-run", true)&&!cmd->FindExist("/run", true)&&DOS_PSP(dos.psp()).GetParent() != DOS_PSP(DOS_PSP(dos.psp()).GetParent()).GetParent()) return; - if(cmd->FindExist("welcome",false)) { - void showWelcome(Program *shell); - showWelcome(this); - return; - } - if(cmd->FindExist("cdrom",false)) { - WriteOut(MSG_Get("PROGRAM_INTRO_CDROM")); - if (attr) DOS_SetAnsiAttr(attr); - return; - } - if(cmd->FindExist("mount",false)) { - WriteOut("\033[2J");//Clear screen before printing - DisplayMount(); - if (attr) DOS_SetAnsiAttr(attr); - return; - } - - if(cmd->FindExist("usage", false)) { - DisplayUsage(); - if(attr) DOS_SetAnsiAttr(attr); - return; - } - uint8_t c;uint16_t n=1; - -#define CURSOR(option) \ - if (menuname==option) DisplayMenuCursorStart(); \ - else DisplayMenuBefore(); \ - WriteOut(MSG_Get("PROGRAM_INTRO_MENU_" option "")); \ - if (menuname==option) DisplayMenuCursorEnd(); \ - else WriteOut("\n"); - - /* Intro */ - -menufirst: - DisplayIntro(); - CURSOR("BASIC") - CURSOR("CDROM") - CURSOR("USAGE") - DisplayMenuNone(); // None - CURSOR("INFO") - CURSOR("QUIT") - DisplayMenuNone(); // None - - if (menuname=="BASIC") goto basic; - else if (menuname=="CDROM") goto cdrom; - else if (menuname=="USAGE") goto usage; - else if (menuname=="INFO") goto info; - else if (menuname=="QUIT") goto quit; - else if (menuname=="GOTO_EXIT") goto goto_exit; - -goto_exit: - WriteOut("\n"); // Give a line - if (attr) DOS_SetAnsiAttr(attr); - return; - -basic: - menuname="BASIC"; - WriteOut(MSG_Get("PROGRAM_INTRO_MENU_BASIC_HELP")); - CON_IN(&c); - do switch (c) { - case 0x48|0x80: menuname="QUIT"; goto menufirst; // Up - case 0x50|0x80: menuname="CDROM"; goto menufirst; // Down - case 0x1B: menuname="QUIT"; goto menufirst; - case 0xD: // Run - WriteOut("\033[2J"); - WriteOut(MSG_Get("PROGRAM_INTRO")); - WriteOut("\n"); - DisplayMount(); - DOS_ReadFile (STDIN,&c,&n); - goto menufirst; - } while (CON_IN(&c)); - -cdrom: - menuname="CDROM"; - WriteOut(MSG_Get("PROGRAM_INTRO_MENU_CDROM_HELP")); - CON_IN(&c); - do switch (c) { - case 0x48|0x80: menuname="BASIC"; goto menufirst; // Up - case 0x50|0x80: menuname="USAGE"; goto menufirst; // Down - case 0x1B: menuname="QUIT"; goto menufirst; - case 0xD: // Run - WriteOut(MSG_Get("PROGRAM_INTRO_CDROM")); - DOS_ReadFile (STDIN,&c,&n); - goto menufirst; - } while (CON_IN(&c)); - -usage: - menuname="USAGE"; - WriteOut(MSG_Get("PROGRAM_INTRO_MENU_USAGE_HELP")); - CON_IN(&c); - do switch (c) { - case 0x48|0x80: menuname="CDROM"; goto menufirst; // Down - case 0x50|0x80: menuname="INFO"; goto menufirst; // Down - case 0x1B: menuname="QUIT"; goto menufirst; - case 0xD: // Run - DisplayUsage(); - goto menufirst; - } while (CON_IN(&c)); - -info: - menuname="INFO"; - WriteOut(MSG_Get("PROGRAM_INTRO_MENU_INFO_HELP")); - CON_IN(&c); - do switch (c) { - case 0x48|0x80: menuname="USAGE"; goto menufirst; // Up - case 0x50|0x80: menuname="QUIT"; goto menufirst; // Down - case 0x1B: menuname="QUIT"; goto menufirst; - case 0xD: // Run - WriteOut("\033[2J"); - WriteOut(MSG_Get("PROGRAM_INTRO")); - WriteOut("\n"); - WriteOut(MSG_Get("PROGRAM_INTRO_INFO")); - DOS_ReadFile (STDIN,&c,&n); - goto menufirst; - } while (CON_IN(&c)); - -quit: - menuname="QUIT"; - WriteOut(MSG_Get("PROGRAM_INTRO_MENU_QUIT_HELP")); - CON_IN(&c); - do switch (c) { - case 0x48|0x80: menuname="INFO"; goto menufirst; // Up - case 0x50|0x80: menuname="BASIC"; goto menufirst; // Down - case 0xD: // Run - menuname="GOTO_EXIT"; - goto menufirst; - } while (CON_IN(&c)); - if (attr) DOS_SetAnsiAttr(attr); - } -}; - -static void INTRO_ProgramStart(Program * * make) { - *make=new INTRO; -} - -imageDiskMemory* CreateRamDrive(Bitu sizes[], const int reserved_cylinders, const bool forceFloppy, Program* obj) { - imageDiskMemory* dsk = NULL; - //if chs not specified - if (sizes[1] == 0) { - uint32_t imgSizeK = (uint32_t)sizes[0]; - //default to 1.44mb floppy - if (forceFloppy && imgSizeK == 0) imgSizeK = 1440; - //search for floppy geometry that matches specified size in KB - int index = 0; - while (DiskGeometryList[index].cylcount != 0) { - if (DiskGeometryList[index].ksize == imgSizeK) { - //create floppy - dsk = new imageDiskMemory(DiskGeometryList[index]); - break; - } - index++; - } - if (dsk == NULL) { - //create hard drive - if (forceFloppy) { - if (obj!=NULL) obj->WriteOut("Floppy size not recognized\n"); - return NULL; - } - - // The fatDrive class is hard-coded to assume that disks 2880KB or smaller are floppies, - // whether or not they are attached to a floppy controller. So, let's enforce a minimum - // size of 4096kb for hard drives. Use the other constructor for floppy drives. - // Note that a size of 0 means to auto-select a size - if (imgSizeK < 4096) imgSizeK = 4096; - - dsk = new imageDiskMemory(imgSizeK); - } - } - else { - //search for floppy geometry that matches specified geometry - int index = 0; - while (DiskGeometryList[index].cylcount != 0) { - if (DiskGeometryList[index].cylcount == sizes[3] && - DiskGeometryList[index].headscyl == sizes[2] && - DiskGeometryList[index].secttrack == sizes[1] && - DiskGeometryList[index].bytespersect == sizes[0]) { - //create floppy - dsk = new imageDiskMemory(DiskGeometryList[index]); - break; - } - index++; - } - if (dsk == NULL) { - //create hard drive - if (forceFloppy) { - if (obj!=NULL) obj->WriteOut("Floppy size not recognized\n"); - return NULL; - } - dsk = new imageDiskMemory((uint16_t)sizes[3], (uint16_t)sizes[2], (uint16_t)sizes[1], (uint16_t)sizes[0]); - } - } - if (!dsk->active) { - if (obj!=NULL) obj->WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); - delete dsk; - return NULL; - } - dsk->Set_Reserved_Cylinders((Bitu)reserved_cylinders); - return dsk; -} - -bool AttachToBiosByIndex(imageDisk* image, const unsigned char bios_drive_index) { - if (bios_drive_index >= MAX_DISK_IMAGES) return false; - if (imageDiskList[bios_drive_index] != NULL) { - /* Notify IDE ATA emulation if a drive is already there */ - if (bios_drive_index >= 2) IDE_Hard_Disk_Detach(bios_drive_index); - imageDiskList[bios_drive_index]->Release(); - } - imageDiskList[bios_drive_index] = image; - imageDiskChange[bios_drive_index] = true; - image->Addref(); - - // let FDC know if we mounted a floppy - if (bios_drive_index <= 1) { - FDC_AssignINT13Disk(bios_drive_index); - incrementFDD(); - } - - return true; -} - -bool AttachToBiosAndIdeByIndex(imageDisk* image, const unsigned char bios_drive_index, const unsigned char ide_index, const bool ide_slave) { - if (!AttachToBiosByIndex(image, bios_drive_index)) return false; - //if hard drive image, and if ide controller is specified - if (bios_drive_index >= 2 && bios_drive_index < MAX_DISK_IMAGES) { - IDE_Hard_Disk_Attach((signed char)ide_index, ide_slave, bios_drive_index); - updateDPT(); - } - return true; -} - -bool AttachToBiosByLetter(imageDisk* image, const char drive) { - if (image->hardDrive) { - //for hard drives, mount hard drives at first available index - for (int index = 2; index < MAX_DISK_IMAGES; index++) { - if (imageDiskList[index] == NULL) { - return AttachToBiosByIndex(image, index); - } - } - LOG_MSG("BIOS: Warning: Four hard drives (Disk no. 2-5) attached to BIOS already. Drive %c not attached", drive); - } -#if 0 - else if (IS_PC98_ARCH) { - // FIX_ME: This code is not correct. PC-98 boots from Drive 2 only if Drive 1 is empty. - // Currently disable this code since DOSBox-X supports only Drive A (Drive 1) as floppy boot drive anyway. - - //for pc-98 machines, mount floppies at first available index - for (int index = 0; index < 2; index++) { - if (imageDiskList[index] == NULL) { - return AttachToBiosByIndex(image, index); - } - } - } -#endif - else if ((drive - 'A') < 2) { - //for PCs, mount floppies only if A: or B: is specified, and then if so, at specified index - return AttachToBiosByIndex(image, drive - 'A'); - } - return false; -} - -bool AttachToBiosAndIdeByLetter(imageDisk* image, const char drive, const unsigned char ide_index, const bool ide_slave) { - if (image->hardDrive) { - //for hard drives, mount hard drives at first available index - for (int index = 2; index < MAX_DISK_IMAGES; index++) { - if (imageDiskList[index] == NULL) { - return AttachToBiosAndIdeByIndex(image, index, ide_index, ide_slave); - } - } - LOG_MSG("BIOS: Warning: Four hard drives (Disk no. 2-5) attached to BIOS already. Drive %c not attached", drive); - } -#if 0 - else if (IS_PC98_ARCH) { - // FIX_ME: This code is not correct. PC-98 boots from Drive 2 only if Drive 1 is empty. - // Currently disable this code since DOSBox-X supports only Drive A (Drive 1) as floppy boot drive anyway. - - //for pc-98 machines, mount floppies at first available index - for (int index = 0; index < 2; index++) { - if (imageDiskList[index] == NULL) { - return AttachToBiosByIndex(image, index); - } - } - } -#endif - else if ((drive - 'A') < 2) { - //for PCs, mount floppies only if A: or B: is specified, and then if so, at specified index - return AttachToBiosByIndex(image, drive - 'A'); - } - return false; -} - -std::string GetIDEPosition(unsigned char bios_disk_index); -class IMGMOUNT : public Program { - public: - std::vector options; - void ListImgMounts(void) { - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; - /* Command uses dta so set it to our internal dta */ - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_1")); - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),MSG_Get("DRIVE"),MSG_Get("TYPE"),MSG_Get("LABEL"),MSG_Get("SWAP_SLOT")); - int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - if (!cols) cols=80; - for(int p = 1;p < cols;p++) WriteOut("-"); - WriteOut("\n"); - char swapstr[50]; - bool none=true; - for (int d = 0;d < DOS_DRIVES;d++) { - if (!Drives[d] || (strncmp(Drives[d]->GetInfo(), "fatDrive ", 9) && strncmp(Drives[d]->GetInfo(), "isoDrive ", 9))) continue; - char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; - bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); - if (ret) { - dta.GetResult(name,lname,size,hsize,date,time,attr); - DOS_FindNext(); //Mark entry as invalid - } else name[0] = 0; - - /* Change 8.3 to 11.0 */ - const char* dot = strchr(name, '.'); - if(dot && (dot - name == 8) ) { - name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; - } - - root[1] = 0; //This way, the format string can be reused. - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name,DriveManager::GetDrivePosition(d)); - none=false; - } - if (none) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); - WriteOut("\n"); - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_2")); - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NUMBER_FORMAT"),MSG_Get("DRIVE_NUMBER"),MSG_Get("DISK_NAME"),MSG_Get("IDE_POSITION"),MSG_Get("SWAP_SLOT")); - for(int p = 1;p < cols;p++) WriteOut("-"); - WriteOut("\n"); - none=true; - for (int index = 0; index < MAX_DISK_IMAGES; index++) { - if (imageDiskList[index]) { - int swaps=0; - if (swapInDisksSpecificDrive == index) { - for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) - if (diskSwap[si] != NULL) - swaps++; - } - if (!swaps) swaps=1; - sprintf(swapstr, "%d / %d", swaps==1?1:swapPosition+1, swaps); - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NUMBER_FORMAT"), std::to_string(index).c_str(), dynamic_cast(imageDiskList[index])!=NULL?"El Torito floppy drive":imageDiskList[index]->diskname.c_str(), GetIDEPosition(index).c_str(), swapstr); - none=false; - } - } - if (none) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); - dos.dta(save_dta); - } - void Run(void) override { - //Hack To allow long commandlines - ChangeToLongCmd(); - /* In secure mode don't allow people to change imgmount points. - * Neither mount nor unmount */ - if(control->SecureMode()) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); - return; - } - imageDisk * newImage; - char drive; - std::vector paths; - if (!cmd->GetCount()) { - ListImgMounts(); - return; - } - //show help if /? or -? - if (cmd->FindExist("/?", true) || cmd->FindExist("-?", true) || cmd->FindExist("?", true) || cmd->FindExist("-help", true)) { - resetcolor = true; - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_HELP")); - return; - } - if (cmd->FindExist("/examples")||cmd->FindExist("-examples")) { - resetcolor = true; - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_EXAMPLE")); - return; - } - /* Check for unmounting */ - std::string umount; - if (cmd->FindString("-u",umount,false)) { - Unmount(umount[0]); - return; - } - - bool roflag = false; - if (cmd->FindExist("-ro",true)) - roflag = true; - - //initialize more variables - unsigned long el_torito_floppy_base=~0UL; - unsigned char el_torito_floppy_type=0xFF; - bool ide_slave = false; - signed char ide_index = -1; - char el_torito_cd_drive = 0; - std::string el_torito; - std::string ideattach="auto"; - std::string type="hdd"; - uint8_t tdr = 0; - std::string bdisk; - int bdisk_number=-1; - - //this code simply sets default type to "floppy" if mounting at A: or B: --- nothing else - // get first parameter - which is probably the drive letter to mount at (A-Z or A:-Z:) - and check it if is A or B or A: or B: - // default to floppy for drive letters A and B and numbers 0 and 1 - if (!cmd->FindCommand(1,temp_line) || (temp_line.size() > 2) || - ((temp_line.size()>1) && (temp_line[1]!=':'))) { - // drive not valid - } else { - tdr = toupper(temp_line[0]); - if(tdr=='A'||tdr=='B'||tdr=='0'||tdr=='1') type="floppy"; - } - - if (temp_line.size() == 1 && isdigit(temp_line[0]) && temp_line[0]>='0' && temp_line[0]FindExist("-u",true)) { - Unmount(temp_line[0]); - std::string templine; - if (!cmd->FindCommand(2,templine)||!templine.size()) return; - } - - //get the type - bool rtype=cmd->FindString("-t", type, true); - std::transform(type.begin(), type.end(), type.begin(), ::tolower); - - if (type == "cdrom") type = "iso"; //Tiny hack for people who like to type -t cdrom - if (!(type == "floppy" || type == "hdd" || type == "iso" || type == "ram")) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_TYPE_UNSUPPORTED"), type.c_str()); - return; - } - - //look for -o options - { - std::string s; - - while (cmd->FindString("-o", s, true)) - options.push_back(s); - } - - //look for -el-torito parameter and remove it from the command line - cmd->FindString("-el-torito",el_torito,true); - if(el_torito == "") cmd->FindString("-bootcd", el_torito, true); - if (el_torito != "") { - //get el-torito floppy from cdrom mounted at drive letter el_torito_cd_drive - el_torito_cd_drive = toupper(el_torito[0]); - //validate the el_torito loading (look for boot image on the cdrom, etc), and - // find the el_torito_floppy_base and el_torito_floppy_type values - if (!PrepElTorito(type, el_torito_cd_drive, el_torito_floppy_base, el_torito_floppy_type)) return; - } - - //the user can use -bd to mount partitions from an INT 13h BIOS disk mounted image, - //meaning a disk image attached to INT 13h using IMGMOUNT -fs none. This way, - //it is possible to mount multiple partitions from one HDD image. - cmd->FindString("-bd",bdisk,true); - if (bdisk != "") { - bdisk_number = atoi(bdisk.c_str()); - if (bdisk_number < 0 || bdisk_number >= MAX_DISK_IMAGES) return; - if (imageDiskList[bdisk_number] == NULL) { - WriteOut("BIOS disk index does not have an image assigned"); - return; - } - } - - //default fstype is fat - std::string fstype="fat"; - bool rfstype=cmd->FindString("-fs",fstype,true); - std::transform(fstype.begin(), fstype.end(), fstype.begin(), ::tolower); - - Bitu sizes[4] = { 0,0,0,0 }; - int reserved_cylinders=0; - std::string reservecyl; - - /* DOSBox-X: to please certain 32-bit drivers like Windows 3.1 WDCTRL, or to emulate older h/w configurations, - * we allow the user or script to specify the number of reserved cylinders. older BIOSes were known - * to subtract 1 or 2 additional cylinders from the total in the fixed disk param table. the -reservecyl - * option allows the number we subtract from the total in INT 13H to be set */ - cmd->FindString("-reservecyl",reservecyl,true); - if (reservecyl != "") reserved_cylinders = atoi(reservecyl.c_str()); - - /* DOSBox-X: we allow "-ide" to allow controlling which IDE controller and slot to attach the hard disk/CD-ROM to */ - cmd->FindString("-ide",ideattach,true); - std::transform(ideattach.begin(), ideattach.end(), ideattach.begin(), ::tolower); - - if(isdigit(tdr) && tdr - '0' >= 2) { //Allocate to respective slots if drive number is specified - ide_index = (tdr - '2') / 2; // Drive number 2 = 1m (index=0, slave=false), 3 = 1s (index=0, slave=true), ... - ide_slave = (tdr - '2') & 1 ? true : false; - } else if(ideattach == "auto") { - //LOG_MSG("IDE: attach=auto type=%s", type); - if(type != "floppy") { - if(type == "iso") { - if(!IDE_controller_occupied(1, false)) { // CD-ROMS default to secondary master if not occupied - ide_index = 1; - ide_slave = false; - } - } - if (ide_index < 0) IDE_Auto(ide_index, ide_slave); - } - } - else if (ideattach != "none" && isdigit(ideattach[0]) && ideattach[0] > '0') { /* takes the form [controller] such as: 1m for primary master */ - ide_index = ideattach[0] - '1'; - if (ideattach.length() >= 2) ide_slave = (ideattach[1] == 's'); - } - - //if floppy, don't attach to ide controller - //if cdrom, file system is iso - if (type=="floppy") { - ideattach="none"; - } else if (type=="iso") { - //str_size=="2048,1,60000,0"; // ignored, see drive_iso.cpp (AllocationInfo) - fstype = "iso"; - } - - //load the size parameter - //auto detect hard drives if not specified - std::string str_size; - std::string str_chs; - cmd->FindString("-size", str_size, true); - cmd->FindString("-chs", str_chs, true); - if (!ReadSizeParameter(str_size, str_chs, type, sizes)) return; - - if (!rfstype&&isdigit(temp_line[0])) fstype="none"; - - //for floppies, hard drives, and cdroms, require a drive letter - //for -fs none, require a number indicating where to mount at - if(fstype=="fat" || fstype=="iso") { - // get the drive letter - if (!cmd->FindCommand(1,temp_line) || (temp_line.size() > 2) || ((temp_line.size()>1) && (temp_line[1]!=':'))) { - WriteOut_NoParsing(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY_DRIVE")); - return; - } - - /* if fs type if "fat" and we're asked to mount *: then check for that here */ - if (temp_line[0] == '*' && temp_line[1] == ':') { - /* What drives are available? */ - int i_drive = IS_PC98_ARCH ? 'A' : 'C'; - while (i_drive <= 'Z' && Drives[i_drive-'A'] != NULL && (i_drive-'A') < DOS_DRIVES) i_drive++; - - if (i_drive > 'Z') { - WriteOut_NoParsing("No drive letters available"); - return; - } - - drive = static_cast(i_drive); - } - else { - int i_drive = toupper(temp_line[0]); - if (!isalpha(i_drive) || (i_drive - 'A') >= DOS_DRIVES || (i_drive - 'A') < 0) { - WriteOut_NoParsing(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY_DRIVE")); - return; - } - drive = static_cast(i_drive); - } - } else if (fstype=="none") { - cmd->FindCommand(1,temp_line); - if ((temp_line.size() > 1) || (!isdigit(temp_line[0]))) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY2"), MAX_DISK_IMAGES-1); - return; - } - drive=temp_line[0]; - if ((drive<'0') || (drive>=MAX_DISK_IMAGES+'0')) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY2"), MAX_DISK_IMAGES-1); - return; - } - int index = drive - '0'; - if (imageDiskList[index]) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED_NUMBER"),index); - return; - } - } else { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_FORMAT_UNSUPPORTED"),fstype.c_str()); - return; - } - - // find all file parameters, assuming that all option parameters have been removed - bool removed=ParseFiles(temp_line, paths, el_torito != "" || type == "ram" || bdisk != ""); - - // some generic checks - if (el_torito != "") { - if (paths.size() != 0) { - WriteOut("Do not specify files when mounting floppy drives from El Torito bootable CDs\n"); - return; - } - } - else if (bdisk != "") { - } - else if (type == "ram") { - if (paths.size() != 0) { - WriteOut("Do not specify files when mounting RAM drives\n"); - return; - } - } - else { - if (paths.size() == 0) { - if (strcasecmp(temp_line.c_str(), "-u")&&!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY_FILE")); - return; - } - if (!rtype&&!rfstype&&fstype!="none"&&paths[0].length()>4) { - const char *ext = strrchr(paths[0].c_str(), '.'); - if (ext != NULL) { - if (!strcasecmp(ext, ".iso")||!strcasecmp(ext, ".cue")||!strcasecmp(ext, ".bin")||!strcasecmp(ext, ".chd")||!strcasecmp(ext, ".mdf")||!strcasecmp(ext, ".gog")||!strcasecmp(ext, ".ins")||!strcasecmp(ext, ".ccd")||!strcasecmp(ext, ".inst")) { - type="iso"; - fstype="iso"; - if(ide_index < 0 || ideattach == "auto") { - if(!IDE_controller_occupied(1, false)) { // check if secondary master is already occupied - ide_index = 1; - ide_slave = false; - } - else IDE_Auto(ide_index, ide_slave); - } - } else if (!strcasecmp(ext, ".ima")) { - type="floppy"; - ideattach="none"; - } - } - } - } - - int i_drive = drive - 'A'; - bool exist = i_drive < DOS_DRIVES && i_drive >= 0 && Drives[i_drive]; - //====== call the proper subroutine ====== - if(fstype=="fat") { - //mount floppy or hard drive - if (bdisk != "") { - if (!MountPartitionFat(drive, bdisk_number)) return; - } - else if (el_torito != "") { - if (!MountElToritoFat(drive, sizes, el_torito_cd_drive, el_torito_floppy_base, el_torito_floppy_type)) return; - } - else if (type == "ram") { - if (!MountRam(sizes, drive, ide_index, ide_slave, roflag)) return; - } - else { - //supports multiple files - if (!MountFat(sizes, drive, type == "hdd", str_size, paths, ide_index, ide_slave, reserved_cylinders, roflag)) return; - } - if (removed && !exist && i_drive < DOS_DRIVES && i_drive >= 0 && Drives[i_drive]) DOS_SetDefaultDrive(i_drive); - } else if (fstype=="iso") { - if (bdisk != "") { - // TODO - return; - } - if (el_torito != "") { - WriteOut("El Torito bootable CD: -fs iso mounting not supported\n"); /* <- NTS: Will never implement, either */ - return; - } - //supports multiple files - if (!MountIso(drive, paths, ide_index, ide_slave)) return; - if (removed && !exist && i_drive < DOS_DRIVES && i_drive >= 0 && Drives[i_drive]) DOS_SetDefaultDrive(i_drive); - } else if (fstype=="none") { - unsigned char driveIndex = drive - '0'; - - if (paths.size() > 1) { - if (driveIndex <= 1) { - if (swapInDisksSpecificDrive >= 0 && swapInDisksSpecificDrive <= 1 && - swapInDisksSpecificDrive != driveIndex) { - WriteOut("Multiple images given and another drive already uses multiple images\n"); - return; - } - } - else { - WriteOut("Multiple disk images not supported for that drive\n"); - return; - } - } - - if (el_torito != "") { - newImage = new imageDiskElToritoFloppy((unsigned char)el_torito_cd_drive, el_torito_floppy_base, el_torito_floppy_type); - } - else if (type == "ram") { - newImage = MountImageNoneRam(sizes, reserved_cylinders, driveIndex < 2); - } - else { - newImage = MountImageNone(paths[0].c_str(), NULL, sizes, reserved_cylinders, roflag); - } - if (newImage == NULL) return; - newImage->Addref(); - if (newImage->hardDrive && (driveIndex < 2)) { - WriteOut("Cannot mount hard drive in floppy position.\n"); - } - else if (!newImage->hardDrive && (driveIndex >= 2)) { - WriteOut("Cannot mount floppy in hard drive position.\n"); - } - else { - if (AttachToBiosAndIdeByIndex(newImage, (unsigned char)driveIndex, (unsigned char)ide_index, ide_slave)) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_MOUNT_NUMBER"), drive - '0', (!paths.empty()) ? (wpcolon&&paths[0].length()>1&&paths[0].c_str()[0]==':'?paths[0].c_str()+1:paths[0].c_str()) : (el_torito != ""?"El Torito floppy drive":(type == "ram"?"RAM drive":"-"))); - const char *ext = strrchr(paths[0].c_str(), '.'); - if (ext != NULL) { - if ((!IS_PC98_ARCH && strcasecmp(ext,".img") && strcasecmp(ext,".ima") && strcasecmp(ext,".vhd") && strcasecmp(ext,".qcow2")) || - (IS_PC98_ARCH && strcasecmp(ext,".hdi") && strcasecmp(ext,".nhd") && strcasecmp(ext,".img") && strcasecmp(ext,".ima"))){ - WriteOut(MSG_Get("PROGRAM_MOUNT_UNSUPPORTED_EXT"), ext); - } - } - if (swapInDisksSpecificDrive == driveIndex || swapInDisksSpecificDrive == -1) { - for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { - if (diskSwap[si] != NULL) { - diskSwap[si]->Release(); - diskSwap[si] = NULL; - } - } - swapInDisksSpecificDrive = -1; - if (paths.size() > 1) { - /* slot 0 is the image we already assigned */ - diskSwap[0] = newImage; - diskSwap[0]->Addref(); - swapPosition = 0; - swapInDisksSpecificDrive = driveIndex; - - for (size_t si=1;si < MAX_SWAPPABLE_DISKS && si < paths.size();si++) { - imageDisk *img = MountImageNone(paths[si].c_str(), NULL, sizes, reserved_cylinders, roflag); - - if (img != NULL) { - diskSwap[si] = img; - diskSwap[si]->Addref(); - } - } - } - } - } - else { - WriteOut("Invalid mount number\n"); - } - } - newImage->Release(); - return; - } - else { - WriteOut("Invalid fstype\n"); - return; - } - - return; - } - - private: - bool ReadSizeParameter(const std::string &str_size, const std::string &str_chs, const std::string &type, Bitu sizes[]) { - bool isCHS = false; - const char * scan; - if (str_chs.size() != 0) { - if (str_size.size() != 0) { - WriteOut("Size and chs parameter cannot both be specified\n"); - return false; - } - isCHS = true; - scan = str_chs.c_str(); - } - else if (str_size.size() != 0) { - scan = str_size.c_str(); - } - else { - //nothing specified, so automatic size detection - return true; - } - char number[20]; - Bitu index = 0; - Bitu count = 0; - int val; - - //scan through input string - while (*scan) { - //separate string by ',' - if (*scan == ',') { - number[index] = 0; //add null char - val = atoi(number); - if (val <= 0) { - //out of range - WriteOut("Invalid size parameter\n"); - return false; - } - sizes[count++] = (unsigned int)val; - index = 0; - if (count == 4) { - //too many commas - WriteOut("Invalid size parameter\n"); - return false; - } - } - else if (index >= 19) { - //number too large (too many characters, anyway) - WriteOut("Invalid size parameter\n"); - return false; - } - else { - number[index++] = *scan; - } - scan++; - } - number[index] = 0; - val = atoi(number); - if (val <= 0) { - //out of range - WriteOut("Invalid size parameter\n"); - return false; - } - sizes[count++] = (unsigned int)val; - if (isCHS) { - if (count == 3) sizes[count++] = 512; //set sector size automatically - if (count != 4) { - WriteOut("Invalid chs parameter\n"); - return false; - } - Bitu temp = sizes[3]; //hold on to sector size temporarily - sizes[3] = sizes[0]; //put cylinders in the right spot - sizes[0] = temp; //put sector size in the right spot - temp = sizes[2]; //hold on to sectors temporarily - sizes[2] = sizes[1]; //put heads in the right spot - sizes[1] = temp; //put sectors in the right spot - } - if (!((type == "ram" && count == 1) || count == 4)) { - //ram drives require 1 or 4 numbers - //other drives require 4 numbers - WriteOut("Invalid size parameter\n"); - return false; - } - return true; - } - bool ParseFiles(std::string &commandLine, std::vector &paths, bool nodef) { - char drive=commandLine[0]; - bool nocont=false; - int num = 0; - while (!nocont&&cmd->FindCommand((unsigned int)(paths.size() + 1 - num), commandLine)) { - bool usedef=false; - if (!cmd->FindCommand((unsigned int)(paths.size() + 2 - num), commandLine) || !commandLine.size()) { - if (!nodef && !paths.size()) { - commandLine="IMGMAKE.IMG"; - usedef=true; - } - else break; - } - if (commandLine == "empty") { - /* special name */ - paths.push_back(commandLine); - continue; - } -#if defined (WIN32) || defined(OS2) - // Windows: Workaround for LaunchBox - if (commandLine.size()>4 && commandLine[0]=='\'' && toupper(commandLine[1])>='A' && toupper(commandLine[1])<='Z' && commandLine[2]==':' && (commandLine[3]=='/' || commandLine[3]=='\\') && commandLine.back()=='\'') - commandLine = commandLine.substr(1, commandLine.size()-2); - else if (!paths.size() && commandLine.size()>3 && commandLine[0]=='\'' && toupper(commandLine[1])>='A' && toupper(commandLine[1])<='Z' && commandLine[2]==':' && (commandLine[3]=='/' || commandLine[3]=='\\')) { - std::string line=cmd->GetRawCmdline(); - trim(line); - std::size_t space=line.find(' '); - if (space!=std::string::npos) { - line=line.substr(space); - trim(line); - std::size_t found=line.back()=='\''?line.find_last_of('\''):line.rfind("' "); - if (found!=std::string::npos&&found>2) { - commandLine=line.substr(1, found-1); - nocont=true; - if (line.size()>3 && !strcasecmp(line.substr(line.size()-3).c_str(), " -u")) Unmount(drive); - } - } - } -#else - // Linux: Convert backslash to forward slash - if (commandLine.size() > 0) { - for (size_t i = 0; i < commandLine.size(); i++) { - if (commandLine[i] == '\\') - commandLine[i] = '/'; - } - } -#endif - - if (!strcasecmp(commandLine.c_str(), "-u")) { - bool exist = toupper(drive) - 'A' == DOS_GetDefaultDrive(); - Unmount(drive); - return exist && drive - 'A' != DOS_GetDefaultDrive(); - } - - char fullname[CROSS_LEN]; - char tmp[CROSS_LEN]; - bool useh = false, readonly = wpcolon&&commandLine.length()>1&&commandLine[0]==':'; - safe_strncpy(tmp, readonly?commandLine.c_str()+1:commandLine.c_str(), CROSS_LEN); - pref_struct_stat test; -#if defined(WIN32) - ht_stat_t htest; - const host_cnv_char_t* host_name = CodePageGuestToHost(tmp); - if (pref_stat(tmp, &test) && (host_name == NULL || ht_stat(host_name, &htest))) { - if (pref_stat(tmp, &test) && host_name != NULL) useh = true; -#else - pref_struct_stat htest; - if (pref_stat(tmp, &test)) { -#endif - //See if it works if the ~ are written out - std::string homedir(commandLine); - Cross::ResolveHomedir(homedir); - if (!pref_stat(homedir.c_str(), &test)) { - commandLine = homedir; - } - else { - // convert dosbox-x filename to system filename - uint8_t dummy; - temp_line = tmp; - int res = get_expanded_files(temp_line, paths, readonly); - if (res) { - num += res - 1; - temp_line = paths[0]; - continue; - } else if ((!DOS_MakeName(tmp, fullname, &dummy) || strncmp(Drives[dummy]->GetInfo(), "local directory", 15)) && !qmount) { - WriteOut(MSG_Get(usedef?"PROGRAM_IMGMOUNT_DEFAULT_NOT_FOUND":"PROGRAM_IMGMOUNT_NON_LOCAL_DRIVE")); - return false; - } - - localDrive *ldp = dynamic_cast(Drives[dummy]); - if (ldp == NULL) { - if (!qmount) WriteOut(MSG_Get(usedef?"PROGRAM_IMGMOUNT_DEFAULT_NOT_FOUND":"PROGRAM_IMGMOUNT_FILE_NOT_FOUND")); - return false; - } - ldp->GetSystemFilename(readonly?tmp+1:tmp, fullname); - if (readonly) tmp[0]=':'; - commandLine = tmp; - - if (pref_stat(readonly?tmp+1:tmp, &test)) { - temp_line = readonly?tmp+1:tmp; - int res = get_expanded_files(temp_line, paths, readonly); - if (res) { - num += res - 1; - temp_line = paths[0]; - continue; - } else if (!qmount) - WriteOut(MSG_Get(usedef?"PROGRAM_IMGMOUNT_DEFAULT_NOT_FOUND":"PROGRAM_IMGMOUNT_FILE_NOT_FOUND")); - return false; - } - } - } - if (S_ISDIR(useh?htest.st_mode:test.st_mode)&&!usedef) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_MOUNT")); - return false; - } - paths.push_back(commandLine); - } - return false; - } - - bool Unmount(char &letter) { - letter = toupper(letter); - if (isalpha(letter)) { /* if it's a drive letter, then traditional usage applies */ - int i_drive = letter - 'A'; - if (i_drive < DOS_DRIVES && i_drive >= 0 && Drives[i_drive]) { - //if drive A: or B: - if (i_drive <= 1) - FDC_UnassignINT13Disk(i_drive); - - //get reference to image and cdrom before they are possibly destroyed - const bool partitionMount = Drives[i_drive]->partitionMount; - const fatDrive* drive = dynamic_cast(Drives[i_drive]); - imageDisk* image = drive ? drive->loadedDisk : NULL; - const isoDrive* cdrom = dynamic_cast(Drives[i_drive]); - - switch (DriveManager::UnmountDrive(i_drive)) { - case 0: //success - { - //detach hard drive or floppy drive from bios and ide controller - if (image && !partitionMount) DetachFromBios(image); - /* If the drive letter is also a CD-ROM drive attached to IDE, then let the IDE code know */ - if (cdrom) IDE_CDROM_Detach(i_drive); - Drives[i_drive] = NULL; - DOS_EnableDriveMenu(i_drive+'A'); - if (i_drive == DOS_GetDefaultDrive()) - DOS_SetDrive(toupper('Z') - 'A'); - if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_SUCCESS"), letter); - if (cdrom) - for (int drv=0; drv<2; drv++) - if (Drives[drv]) { - fatDrive *fdp = dynamic_cast(Drives[drv]); - if (fdp&&fdp->opts.mounttype==1&&letter==fdp->el.CDROM_drive) { - char drive='A'+drv; - Unmount(drive); - } - } - if (i_drive < MAX_DISK_IMAGES && imageDiskList[i_drive]) { - delete imageDiskList[i_drive]; - imageDiskList[i_drive] = NULL; - } - if (swapInDisksSpecificDrive == i_drive) { - for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { - if (diskSwap[si] != NULL) { - diskSwap[si]->Release(); - diskSwap[si] = NULL; - } - } - swapInDisksSpecificDrive = -1; - } - return true; - } - case 1: - if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_NO_VIRTUAL")); - return false; - case 2: - if (!qmount) WriteOut(MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS")); - return false; - default: - return false; - } - } - else { - if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"), letter); - return false; - } - } - else if (isdigit(letter)) { /* DOSBox-X: drives mounted by number (INT 13h) can be unmounted this way */ - int index = letter - '0'; - - //detach hard drive or floppy drive from bios and ide controller - if (index < MAX_DISK_IMAGES && imageDiskList[index]) { - if (index > 1) IDE_Hard_Disk_Detach(index); - imageDiskList[index]->Release(); - imageDiskList[index] = NULL; - imageDiskChange[index] = true; - if (swapInDisksSpecificDrive == index) { - for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { - if (diskSwap[si] != NULL) { - diskSwap[si]->Release(); - diskSwap[si] = NULL; - } - } - swapInDisksSpecificDrive = -1; - } - WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_NUMBER_SUCCESS"), letter); - return true; - } - WriteOut("Drive number %d is not mounted.\n", index); - return false; - } - else { - WriteOut("Incorrect IMGMOUNT unmount usage.\n"); - return false; - } - } - - bool PrepElTorito(const std::string& type, const char &el_torito_cd_drive, unsigned long &el_torito_floppy_base, unsigned char &el_torito_floppy_type) { - el_torito_floppy_base = ~0UL; - el_torito_floppy_type = 0xFF; - - unsigned char entries[2048], *entry, ent_num = 0; - int header_platform = -1, header_count = 0; - bool header_final = false; - int header_more = -1; - - /* must be valid drive letter, C to Z */ - if (!isalpha(el_torito_cd_drive) || el_torito_cd_drive < 'C') { - WriteOut("El Torito emulation requires a proper CD-ROM drive letter\n"); - return false; - } - - /* drive must not exist (as a hard drive) */ - if (imageDiskList[el_torito_cd_drive - 'A'] != NULL) { - WriteOut("El Torito CD-ROM drive specified already exists as a non-CD-ROM device\n"); - return false; - } - - bool GetMSCDEXDrive(unsigned char drive_letter, CDROM_Interface **_cdrom); - - /* get the CD-ROM drive */ - CDROM_Interface *src_drive = NULL; - if (!GetMSCDEXDrive(el_torito_cd_drive - 'A', &src_drive)) { - WriteOut("El Torito CD-ROM drive specified is not actually a CD-ROM drive\n"); - return false; - } - - /* FIXME: We only support the floppy emulation mode at this time. - * "Superfloppy" or hard disk emulation modes are not yet implemented. - * This mode will never support "no emulation" boot. */ - if (type != "floppy") { - WriteOut("El Torito emulation must be used with -t floppy at this time\n"); - return false; - } - - /* Okay. Step #1: Scan the volume descriptors for the Boot Record. */ - unsigned long el_torito_base = 0, boot_record_sector = 0; - if (!ElTorito_ScanForBootRecord(src_drive, boot_record_sector, el_torito_base)) { - WriteOut("El Torito CD-ROM boot record not found\n"); - return false; - } - - LOG_MSG("El Torito emulation: Found ISO 9660 Boot Record in sector %lu, pointing to sector %lu\n", - boot_record_sector, el_torito_base); - - /* Step #2: Parse the records. Each one is 32 bytes long */ - if (!src_drive->ReadSectorsHost(entries, false, el_torito_base, 1)) { - WriteOut("El Torito entries unreadable\n"); - return false; - } - - /* for more information about what this loop is doing, read: - * http://download.intel.com/support/motherboards/desktop/sb/specscdrom.pdf - */ - /* FIXME: Somebody find me an example of a CD-ROM with bootable code for both x86, PowerPC, and Macintosh. - * I need an example of such a CD since El Torito allows multiple "headers" */ - /* TODO: Is it possible for this record list to span multiple sectors? */ - for (ent_num = 0; ent_num < (2048 / 0x20); ent_num++) { - entry = entries + (ent_num * 0x20); - - if (memcmp(entry, "\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0", 32) == 0) - break; - - if (entry[0] == 0x01/*header*/) { - if (!ElTorito_ChecksumRecord(entry)) { - LOG_MSG("Warning: El Torito checksum error in header(0x01) entry\n"); - continue; - } - - if (header_count != 0) { - LOG_MSG("Warning: El Torito has more than one Header/validation entry\n"); - continue; - } - - if (header_final) { - LOG_MSG("Warning: El Torito has an additional header past the final header\n"); - continue; - } - - header_more = -1; - header_platform = entry[1]; - LOG_MSG("El Torito entry: first header platform=0x%02x\n", header_platform); - header_count++; - } - else if (entry[0] == 0x90/*header, more follows*/ || entry[0] == 0x91/*final header*/) { - if (header_final) { - LOG_MSG("Warning: El Torito has an additional header past the final header\n"); - continue; - } - - header_final = (entry[0] == 0x91); - header_more = (int)(((unsigned int)entry[2]) + (((unsigned int)entry[3]) << 8u)); - header_platform = entry[1]; - LOG_MSG("El Torito entry: first header platform=0x%02x more=%u final=%u\n", header_platform, header_more, header_final); - header_count++; - } - else { - if (header_more == 0) { - LOG_MSG("El Torito entry: Non-header entry count expired, ignoring record 0x%02x\n", entry[0]); - continue; - } - else if (header_more > 0) { - header_more--; - } - - if (entry[0] == 0x44) { - LOG_MSG("El Torito entry: ignoring extension record\n"); - } - else if (entry[0] == 0x00/*non-bootable*/) { - LOG_MSG("El Torito entry: ignoring non-bootable record\n"); - } - else if (entry[0] == 0x88/*bootable*/) { - if (header_platform == 0x00/*x86*/) { - unsigned char mediatype = entry[1] & 0xF; - unsigned short load_segment = ((unsigned int)entry[2]) + (((unsigned int)entry[3]) << 8); - unsigned char system_type = entry[4]; - unsigned short sector_count = ((unsigned int)entry[6]) + (((unsigned int)entry[7]) << 8); - unsigned long load_rba = ((unsigned int)entry[8]) + (((unsigned int)entry[9]) << 8) + - (((unsigned int)entry[10]) << 16) + (((unsigned int)entry[11]) << 24); - - LOG_MSG("El Torito entry: bootable x86 record mediatype=%u load_segment=0x%04x " - "system_type=0x%02x sector_count=%u load_rba=%lu\n", - mediatype, load_segment, system_type, sector_count, load_rba); - - /* already chose one, ignore */ - if (el_torito_floppy_base != ~0UL) - continue; - - if (load_segment != 0 && load_segment != 0x7C0) - LOG_MSG("El Torito boot warning: load segments other than 0x7C0 not supported yet\n"); - if (sector_count != 1) - LOG_MSG("El Torito boot warning: sector counts other than 1 are not supported yet\n"); - - if (mediatype < 1 || mediatype > 3) { - LOG_MSG("El Torito boot entry: media types other than floppy emulation not supported yet\n"); - continue; - } - - el_torito_floppy_base = load_rba; - el_torito_floppy_type = mediatype; - } - else { - LOG_MSG("El Torito entry: ignoring bootable non-x86 (platform_id=0x%02x) record\n", header_platform); - } - } - else { - LOG_MSG("El Torito entry: ignoring unknown record ID %02x\n", entry[0]); - } - } - } - - if (el_torito_floppy_type == 0xFF || el_torito_floppy_base == ~0UL) { - WriteOut("El Torito bootable floppy not found\n"); - return false; - } - - return true; - } - - bool MountPartitionFat(const char drive, const int src_bios_disk) { - unsigned char driveIndex = drive - 'A'; - - /* NTS: IBM PC systems: Hard disk partitions must start at C: or higher. - * PC-98 systems: Any drive letter is valid, A: can be a hard drive. */ - if ((!IS_PC98_ARCH && driveIndex < 2) || driveIndex >= 26) { - WriteOut("Invalid drive letter"); - return false; - } - - if (Drives[driveIndex]) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); - return false; - } - - if (src_bios_disk < 2/*no, don't allow partitions on floppies!*/ || src_bios_disk >= MAX_DISK_IMAGES || imageDiskList[src_bios_disk] == NULL) { - WriteOut("BIOS disk index does not have an image assigned"); - return false; - } - - /* FIXME: IMGMOUNT and MOUNT -u are so hard-coded around C: and BIOS device indexes that some confusion may happen - * if a partition is C: mounted from, say, BIOS device 0x81 and the wrong thing may get unmounted and detached. - * So for sanity reasons, do not allow mounting to a drive letter if a BIOS disk image WOULD normally be - * associated with it. This is a mess inherited from back when this code forked from DOSBox SVN, because - * DOSBox SVN makes these hardcoded assumptions. */ - if (driveIndex < MAX_DISK_IMAGES && imageDiskList[driveIndex] != NULL) { - WriteOut("Partitions cannot be mounted in conflict with the standard INT 13h hard disk\nallotment. Choose a different drive letter to mount to."); - return false; - } - - DOS_Drive* newDrive = new fatDrive(imageDiskList[src_bios_disk], options); - if (!(dynamic_cast(newDrive))->created_successfully) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); - return false; - } - - newDrive->partitionMount = true; - AddToDriveManager(drive, newDrive, 0xF0); - DOS_EnableDriveMenu(drive); - - lastmount = drive; - return true; - } - - bool MountElToritoFat(const char drive, const Bitu sizes[], const char el_torito_cd_drive, const unsigned long el_torito_floppy_base, const unsigned char el_torito_floppy_type) { - unsigned char driveIndex = drive - 'A'; - - (void)sizes;//UNUSED - - if (driveIndex > 1) { - WriteOut("Invalid drive letter"); - return false; - } - - if (Drives[driveIndex]) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); - return false; - } - - imageDisk * newImage = new imageDiskElToritoFloppy((unsigned char)el_torito_cd_drive, el_torito_floppy_base, el_torito_floppy_type); - newImage->Addref(); - - DOS_Drive* newDrive = new fatDrive(newImage, options); - newImage->Release(); //fatDrive calls Addref, and this will release newImage if fatDrive doesn't use it - if (!(dynamic_cast(newDrive))->created_successfully) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); - return false; - } - - AddToDriveManager(drive, newDrive, 0xF0); - AttachToBiosByLetter(newImage, drive); - DOS_EnableDriveMenu(drive); - - lastmount = drive; - if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_ELTORITO"), drive); - - return true; - } - - bool unformatted = false; - bool unsupported_ext = false; - int path_no; - bool MountFat(Bitu sizes[], const char drive, const bool isHardDrive, const std::string &str_size, const std::vector &paths, const signed char ide_index, const bool ide_slave, const int reserved_cylinders, bool roflag) { - (void)reserved_cylinders; - if (Drives[drive - 'A']) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); - return false; - } - - for (auto i=options.begin();i!=options.end();i++) { - if ((*i) == "int13") { - char buf[32]; - - if (drive >= 'C') - sprintf(buf,"=%u",drive+0x80-'C'); - else - sprintf(buf,"=%u",drive-'A'); - - (*i) += buf; - } - } - - bool imgsizedetect = isHardDrive && sizes[0] == 0; - int mediaid = -1; - - std::vector imgDisks; - std::vector::size_type i; - std::vector::size_type ct; - - for (i = 0; i < paths.size(); i++) { - const char* errorMessage = NULL; - imageDisk* vhdImage = NULL; - imageDisk* newImage = NULL; - bool ro=false; - - //detect hard drive geometry - if (paths[i] == "empty") { - errorMessage = "empty file not supported for drive letter mount\n"; - } - else if (imgsizedetect) { - bool skipDetectGeometry = false; - sizes[0] = 0; - sizes[1] = 0; - sizes[2] = 0; - sizes[3] = 0; - - /* .HDI images contain the geometry explicitly in the header. */ - if (str_size.size() == 0) { - const char *ext = strrchr(paths[i].c_str(), '.'); - if (ext != NULL) { - if (!strcasecmp(ext, ".hdi")) { - skipDetectGeometry = true; - } - else if (!strcasecmp(ext, ".nhd")) { - skipDetectGeometry = true; - } - else if (!strcasecmp(ext, ".nfd")) { - skipDetectGeometry = true; - } - //for all vhd files where the system will autodetect the chs values, - else if (!strcasecmp(ext, ".vhd")) { - ro=wpcolon&&paths[i].length()>1&&paths[i].c_str()[0]==':'; - //load the file with imageDiskVHD, which supports fixed/dynamic/differential disks - imageDiskVHD::ErrorCodes ret = imageDiskVHD::Open(ro?paths[i].c_str()+1:paths[i].c_str(), ro||roflag, &vhdImage); - switch (ret) { - case imageDiskVHD::UNSUPPORTED_WRITE: - options.emplace_back("readonly"); - case imageDiskVHD::OPEN_SUCCESS: { - skipDetectGeometry = true; - const imageDiskVHD* vhdDisk = dynamic_cast(vhdImage); - if (vhdDisk != NULL) { - LOG_MSG("VHD image detected SS,S,H,C: %u,%u,%u,%u", - (uint32_t)vhdDisk->sector_size, (uint32_t)vhdDisk->sectors, (uint32_t)vhdDisk->heads, (uint32_t)vhdDisk->cylinders); - if (vhdDisk->cylinders>1023) LOG_MSG("WARNING: cylinders>1023, INT13 will not work unless extensions are used"); - if(vhdDisk->GetVHDType() == imageDiskVHD::VHD_TYPE_FIXED) LOG_MSG("VHD is a fixed image"); - if(vhdDisk->GetVHDType() == imageDiskVHD::VHD_TYPE_DYNAMIC) LOG_MSG("VHD is a dynamic image"); - if(vhdDisk->GetVHDType() == imageDiskVHD::VHD_TYPE_DIFFERENCING) LOG_MSG("VHD is a differencing image"); - } - break; - } - case imageDiskVHD::ERROR_OPENING: - errorMessage = MSG_Get("VHD_ERROR_OPENING"); break; - case imageDiskVHD::INVALID_DATA: - errorMessage = MSG_Get("VHD_INVALID_DATA"); break; - case imageDiskVHD::UNSUPPORTED_TYPE: - errorMessage = MSG_Get("VHD_UNSUPPORTED_TYPE"); break; - case imageDiskVHD::ERROR_OPENING_PARENT: - errorMessage = MSG_Get("VHD_ERROR_OPENING_PARENT"); break; - case imageDiskVHD::PARENT_INVALID_DATA: - errorMessage = MSG_Get("VHD_PARENT_INVALID_DATA"); break; - case imageDiskVHD::PARENT_UNSUPPORTED_TYPE: - errorMessage = MSG_Get("VHD_PARENT_UNSUPPORTED_TYPE"); break; - case imageDiskVHD::PARENT_INVALID_MATCH: - errorMessage = MSG_Get("VHD_PARENT_INVALID_MATCH"); break; - case imageDiskVHD::PARENT_INVALID_DATE: - errorMessage = MSG_Get("VHD_PARENT_INVALID_DATE"); break; - default: break; - } - } - else if(!strcasecmp(ext, ".qcow2")) { - ro = wpcolon && paths[i].length() > 1 && paths[i].c_str()[0] == ':'; - const char* fname = ro ? paths[i].c_str() + 1 : paths[i].c_str(); - FILE* newDisk = fopen_lock(fname, ro ? "rb" : "rb+", ro); - if(!newDisk) { - if(!qmount) WriteOut("Unable to open '%s'\n", fname); - return false; - } - QCow2Image::QCow2Header qcow2_header = QCow2Image::read_header(newDisk); - // uint64_t sectors; /* unused */ - uint32_t imagesize; - sizes[0] = 512; // default sector size - if(qcow2_header.magic == QCow2Image::magic && (qcow2_header.version == 2 || qcow2_header.version == 3)) { - uint32_t cluster_size = 1u << qcow2_header.cluster_bits; - if((sizes[0] < 512) || ((cluster_size % sizes[0]) != 0)) { - WriteOut("Sector size must be larger than 512 bytes and evenly divide the image cluster size of %lu bytes.\n", cluster_size); - return false; - } - // sectors = (uint64_t)qcow2_header.size / (uint64_t)sizes[0]; /* unused */ - imagesize = (uint32_t)(qcow2_header.size / 1024L); - sizes[1] = 63; // sectors - sizes[2] = 16; // heads - sizes[3] = (uint64_t)qcow2_header.size / sizes[0] / sizes[1] / sizes[2]; // cylinders - setbuf(newDisk, NULL); - newImage = new QCow2Disk(qcow2_header, newDisk, fname, imagesize, (uint32_t)sizes[0], (imagesize > 2880)); - skipDetectGeometry = true; - newImage->sector_size = sizes[0]; // sector size - newImage->sectors = sizes[1]; // sectors - newImage->heads = sizes[2]; // heads - newImage->cylinders = sizes[3]; // cylinders - } - else { - WriteOut("qcow2 image '%s' is not supported\n", fname); - fclose(newDisk); - newImage = NULL; - } - } - else if (!strcasecmp(ext,".img") || !strcasecmp(ext,".ima")){ // Raw MFM image format is typically .img or .ima - unsupported_ext = false; - } - else { - LOG_MSG("IMGMOUNT: Perhaps unsupported extension %s", ext); - unsupported_ext = true; - path_no = i; - } - } - } - if (!skipDetectGeometry && !DetectGeometry(NULL, paths[i].c_str(), sizes)) { - errorMessage = "Unable to detect geometry\n"; - } - } - - if (!errorMessage) { - DOS_Drive* newDrive = NULL; - if (vhdImage) { - newDrive = new fatDrive(vhdImage, options); - strcpy(newDrive->info, "fatDrive "); - strcat(newDrive->info, ro?paths[i].c_str()+1:paths[i].c_str()); - vhdImage = NULL; - } - else if(newImage) { - newDrive = new fatDrive(newImage, options); - strcpy(newDrive->info, "fatDrive "); - strcat(newDrive->info, ro ? paths[i].c_str() + 1 : paths[i].c_str()); - LOG_MSG("IMGMOUNT: qcow2 image mounted (experimental)"); - LOG_MSG("IMGMOUNT: qcow2 SS,S,H,C: %u,%u,%u,%u", - (uint32_t)newImage->sector_size, (uint32_t)newImage->sectors, (uint32_t)newImage->heads, (uint32_t)newImage->cylinders); - newImage = NULL; - } - else { - if (roflag) options.emplace_back("readonly"); - newDrive = new fatDrive(paths[i].c_str(), (uint32_t)sizes[0], (uint32_t)sizes[1], (uint32_t)sizes[2], (uint32_t)sizes[3], options); - } - imgDisks.push_back(newDrive); - fatDrive* fdrive=dynamic_cast(newDrive); - if (!fdrive->created_successfully) { - errorMessage = MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE"); - if (fdrive->req_ver_major>0) { - static char ver_msg[150]; - sprintf(ver_msg, "Mounting this image file requires a reported DOS version of %u.%u or higher.\n%s", fdrive->req_ver_major, fdrive->req_ver_minor, errorMessage); - errorMessage = ver_msg; - } - } else { - if (imgDisks.size() == 1) mediaid = (int)((unsigned char)fdrive->GetMediaByte()); - if ((vhdImage&&ro)||roflag) fdrive->readonly=true; - } - unformatted = fdrive->unformatted; - } - if (errorMessage) { - if (!qmount) WriteOut(errorMessage); - for (ct = 0; ct < imgDisks.size(); ct++) { - delete imgDisks[ct]; - } - return false; - } - } - - AddToDriveManager(drive, imgDisks, (mediaid >= 0xF0) ? mediaid : (isHardDrive ? 0xF8 : 0xF0)); - DOS_EnableDriveMenu(drive); - - std::string tmp(wpcolon&&paths[0].length()>1&&paths[0].c_str()[0]==':'?paths[0].substr(1):paths[0]); - for (i = 1; i < paths.size(); i++) { - tmp += "; " + (wpcolon&&paths[i].length()>1&&paths[i].c_str()[0]==':'?paths[i].substr(1):paths[i]); - } - lastmount = drive; - if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"), drive, tmp.c_str()); - if (unformatted) { - if(!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_NOT_FORMATTED")); - LOG_MSG("IMGMOUNT: Drive %c not formatted", drive); - } - if (unsupported_ext) { - const char *ext = strrchr(paths[path_no].c_str(), '.'); - if (ext != NULL) { - if(!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_UNSUPPORTED_EXT"), ext); - LOG_MSG("Unsupported extension %s: Mounted as raw IMG image.", ext); - } - } - unsigned char driveIndex = drive-'A'; - if (imgDisks.size() == 1 || (imgDisks.size() > 1 && driveIndex < 2 && (swapInDisksSpecificDrive == driveIndex || swapInDisksSpecificDrive == -1))) { - imageDisk* image = ((fatDrive*)imgDisks[0])->loadedDisk; - if (AttachToBiosAndIdeByLetter(image, drive, (unsigned char)ide_index, ide_slave)) { - if (swapInDisksSpecificDrive == driveIndex || swapInDisksSpecificDrive == -1) { - for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { - if (diskSwap[si] != NULL) { - diskSwap[si]->Release(); - diskSwap[si] = NULL; - } - } - swapInDisksSpecificDrive = -1; - if (paths.size() > 1) { - /* slot 0 is the image we already assigned */ - diskSwap[0] = image; - diskSwap[0]->Addref(); - swapPosition = 0; - swapInDisksSpecificDrive = driveIndex; - - for (size_t si=1;si < MAX_SWAPPABLE_DISKS && si < paths.size();si++) { - imageDisk *img = ((fatDrive*)imgDisks[si])->loadedDisk; - diskSwap[si] = img; - diskSwap[si]->Addref(); - } - } - } - } - - /* now that the image is attached to INT 13h the INT 13 image can use it now */ - if (image->class_id == imageDisk::ID_INT13) { - imageDiskINT13Drive *x = (imageDiskINT13Drive*)image; - x->enable_int13 = true; - LOG(LOG_MISC,LOG_DEBUG)("INT 13 image enabling calling"); - } - } - return true; - } - - imageDisk* MountImageNoneRam(Bitu sizes[], const int reserved_cylinders, const bool forceFloppy) { - imageDiskMemory* dsk = CreateRamDrive(sizes, reserved_cylinders, forceFloppy, this); - if (dsk == NULL) return NULL; - //formatting might fail; just log the failure and continue - uint8_t ret = dsk->Format(); - if (ret != 0x00) { - LOG_MSG("Warning: could not format RAM drive - error code %u\n", (unsigned int)ret); - } - return dsk; - } - - bool MountRam(Bitu sizes[], const char drive, const signed char ide_index, const bool ide_slave, bool roflag) { - if (Drives[drive - 'A']) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); - return false; - } - - //by default, make a floppy disk if A: or B: is specified (still makes a hard drive if not a recognized size) - imageDiskMemory* dsk = CreateRamDrive(sizes, 0, (drive - 'A') < 2 && sizes[0] == 0, this); - if (dsk == NULL) return false; - if (dsk->Format() != 0x00) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); - delete dsk; - return false; - } - dsk->Addref(); - DOS_Drive* newDrive = new fatDrive(dsk, options); - if (roflag) newDrive->readonly=true; - dsk->Release(); - if (!(dynamic_cast(newDrive))->created_successfully) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); - delete newDrive; //this executes dsk.Release() which executes delete dsk - return false; - } - - AddToDriveManager(drive, newDrive, dsk->hardDrive ? 0xF8 : 0xF0); - DOS_EnableDriveMenu(drive); - - lastmount = drive; - if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_RAMDRIVE"), drive); - - AttachToBiosAndIdeByLetter(dsk, drive, (unsigned char)ide_index, ide_slave); - - return true; - } - - void AddToDriveManager(const char drive, DOS_Drive* imgDisk, const uint8_t mediaid) const { - std::vector imgDisks = { imgDisk }; - AddToDriveManager(drive, imgDisks, mediaid); - } - - void AddToDriveManager(const char drive, const std::vector &imgDisks, const uint8_t mediaid) const { - std::vector::size_type ct; - - // Update DriveManager - for (ct = 0; ct < imgDisks.size(); ct++) { - DriveManager::AppendDisk(drive - 'A', imgDisks[ct]); - } - DriveManager::InitializeDrive(drive - 'A'); - - // Set the correct media byte in the table - mem_writeb(Real2Phys(dos.tables.mediaid) + ((unsigned int)drive - 'A') * dos.tables.dpb_size, mediaid); - - /* Command uses dta so set it to our internal dta */ - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - - for (ct = 0; ct < imgDisks.size(); ct++) { - DriveManager::CycleDisks(drive - 'A', (ct == (imgDisks.size() - 1))); - - char root[7] = { drive, ':', '\\', '*', '.', '*', 0 }; - DOS_FindFirst(root, DOS_ATTR_VOLUME); // force obtaining the label and saving it in dirCache - } - dos.dta(save_dta); - - } - - bool DetectGeometry(FILE * file, const char* fileName, Bitu sizes[]) { - bool yet_detected = false, readonly = wpcolon&&strlen(fileName)>1&&fileName[0]==':'; - FILE * diskfile = file==NULL?fopen64(readonly?fileName+1:fileName, "rb"):file; -#if defined(WIN32) - if (!diskfile && file==NULL) { - const host_cnv_char_t* host_name = CodePageGuestToHost(readonly?fileName+1:fileName); - if (host_name != NULL) diskfile = _wfopen(host_name, L"rb"); - } -#endif - if (!diskfile) { - if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_IMAGE")); - return false; - } - fseeko64(diskfile, 0L, SEEK_END); - uint32_t fcsize = (uint32_t)(ftello64(diskfile) / 512L); - uint8_t buf[512]; -#if 0 // VHD pseudo geometry should be avoided always! - // New VHD driver is capable of MBR/BPB analysis. - - // check for vhd signature - fseeko64(diskfile, -512, SEEK_CUR); - if (fread(buf, sizeof(uint8_t), 512, diskfile)<512) { - fclose(diskfile); - if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_IMAGE")); - return false; - } - if (!strcmp((const char*)buf, "conectix")) { - fcsize--; // skip footer (512 bytes) - sizes[0] = 512; // sector size - sizes[1] = buf[0x3b]; // sectors - sizes[2] = buf[0x3a]; // heads - sizes[3] = SDL_SwapBE16((uint16_t)(*(int16_t*)(buf + 0x38))); // cylinders - - // Do translation (?) - while ((sizes[2] < 128u) && (sizes[3] > 1023u)) { - sizes[2] <<= 1u; - sizes[3] >>= 1u; - } - - if (sizes[3]>1023) { - // Set x/255/63 - sizes[2] = 255; - sizes[3] = fcsize / sizes[2] / sizes[1]; - } - - LOG_MSG("VHD image detected: %u,%u,%u,%u", - (unsigned int)sizes[0], (unsigned int)sizes[1], (unsigned int)sizes[2], (unsigned int)sizes[3]); - if (sizes[3]>1023) LOG_MSG("WARNING: cylinders>1023, INT13 will not work unless extensions are used"); - yet_detected = true; - } -#endif - fseeko64(diskfile, 0L, SEEK_SET); - if (fread(buf, sizeof(uint8_t), 512, diskfile)<512) { - fclose(diskfile); - if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_IMAGE")); - return false; - } - if (file==NULL) fclose(diskfile); - // check MBR signature for unknown images - if (!yet_detected && ((buf[510] != 0x55) || (buf[511] != 0xaa))) { - if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_GEOMETRY")); - return false; - } - // check MBR partition entry 1 - if (!yet_detected) - yet_detected = DetectMFMsectorPartition(buf, fcsize, sizes); - - // Try bximage disk geometry - // bximage flat images should already be detected by - // DetectMFMSectorPartition(), not sure what this adds... - if (!yet_detected) { - yet_detected = DetectBximagePartition(fcsize, sizes); - } - - uint8_t ptype = buf[0x1c2]; // Location of DOS 3.3+ partition type - bool assume_lba = false; - - /* If the first partition is a Windows 95 FAT32 (LBA) type partition, and we failed to detect, - * then assume LBA and make up a geometry */ - if (!yet_detected && (ptype == 0x0C/*FAT32+LBA*/ || ptype == 0x0E/*FAT16+LBA*/)) { - yet_detected = 1; - assume_lba = true; - LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on first partition type (FAT with LBA)"); - } - - /* If the MBR has only a partition table, but the part that normally contains executable - * code is all zeros. To avoid false negatives, check only the first 0x20 bytes since - * at boot time executable code must reside there to do something, and many of these - * disk images while they ARE mostly zeros, do have some extra nonzero bytes immediately - * before the partition table at 0x1BE. - * - * Modern FAT32 generator tools and older digital cameras will format FAT32 like this. - * These tools are unlikely to support non-LBA disks. - * - * To avoid false positives, the partition type has to be something related to FAT */ - if (!yet_detected && (ptype == 0x01 || ptype == 0x04 || ptype == 0x06 || ptype == 0x0B || ptype == 0x0C || ptype == 0x0E)) { - /* buf[] still contains MBR */ - unsigned int i=0; - while (i < 0x20 && buf[i] == 0) i++; - if (i == 0x20) { - yet_detected = 1; - assume_lba = true; - LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on first partition type (FAT-related) and lack of executable code in the MBR"); - } - } - - /* If we failed to detect, but the disk image is 4GB or larger, make up a geometry because - * IDE drives by that point were pure LBA anyway and supported C/H/S for the sake of - * backward compatibility anyway. fcsize is in 512-byte sectors. */ - if (!yet_detected && fcsize >= ((4ull*1024ull*1024ull*1024ull)/512ull)) { - yet_detected = 1; - assume_lba = true; - LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on size"); - } - - if (yet_detected && assume_lba) { - sizes[0] = 512; - sizes[1] = 63; - sizes[2] = 255; - { - const Bitu d = sizes[1]*sizes[2]; - sizes[3] = (fcsize + d - 1) / d; /* round up */ - } - } - - if (yet_detected) { - //"Image geometry auto detection: -size %u,%u,%u,%u\r\n", - //sizes[0],sizes[1],sizes[2],sizes[3]); - if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_AUTODET_VALUES"), sizes[0], sizes[1], sizes[2], sizes[3]); - return true; - } - else { - if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_GEOMETRY")); - return false; - } - } - - bool DetectMFMsectorPartition(uint8_t buf[], uint32_t fcsize, Bitu sizes[]) const { - // This is used for plain MFM sector format as created by IMGMAKE - // It tries to find the first partition. Addressing is in CHS format. - /* Offset | Length | Description - * +0 | 1 byte | 80 hex = active, 00 = inactive - * +1 | 3 bytes | CHS of first sector in partition - * +4 | 1 byte | partition type - * +5 | 3 bytes | CHS of last sector in partition - * +8 | 4 bytes | LBA of first sector in partition - * +C | 4 bytes | Number of sectors in partition. 0 may mean, use LBA - */ - uint8_t starthead = 0; // start head of partition - uint8_t startsect = 0; // start sector of partition - uint16_t startcyl = 0; // start cylinder of partition - //uint8_t ptype = 0; // Partition Type - uint16_t endcyl = 0; // end cylinder of partition - uint8_t heads = 0; // heads in partition - uint8_t sectors = 0; // sectors per track in partition - uint32_t pe1_size = host_readd(&buf[0x1ca]); - if ((uint32_t)host_readd(&buf[0x1fa]) != 0) { // DOS 2.0-3.21 partition table - pe1_size = host_readd(&buf[0x1fa]); - starthead = buf[0x1ef]; - startsect = (buf[0x1f0] & 0x3fu) - 1u; - startcyl = (unsigned char)buf[0x1f1] | (unsigned int)((buf[0x1f0] & 0xc0) << 2u); - endcyl = (unsigned char)buf[0x1f5] | (unsigned int)((buf[0x1f4] & 0xc0) << 2u); - //ptype = buf[0x1f2]; - heads = buf[0x1f3] + 1u; - sectors = buf[0x1f4] & 0x3fu; - } else if (pe1_size != 0) { // DOS 3.3+ partition table, starting at 0x1BE - starthead = buf[0x1bf]; - startsect = (buf[0x1c0] & 0x3fu) - 1u; - startcyl = (unsigned char)buf[0x1c1] | (unsigned int)((buf[0x1c0] & 0xc0) << 2u); - endcyl = (unsigned char)buf[0x1c5] | (unsigned int)((buf[0x1c4] & 0xc0) << 2u); - //ptype = buf[0x1c2]; - heads = buf[0x1c3] + 1u; - sectors = buf[0x1c4] & 0x3fu; - } - if (pe1_size != 0) { - uint32_t part_start = startsect + sectors * starthead + - startcyl * sectors * heads; - uint32_t part_end = heads * sectors * endcyl; - uint32_t part_len = part_end - part_start; - // partition start/end sanity check - // partition length should not exceed file length - // real partition size can be a few cylinders less than pe1_size - // if more than 1023 cylinders see if first partition fits - // into 1023, else bail. - if (/*(part_len<0) always false because unsigned || */(part_len > pe1_size) || (pe1_size > fcsize) || - ((pe1_size - part_len) / (sectors*heads)>2u) || - ((pe1_size / (heads*sectors))>1023u)) { - //LOG_MSG("start(c,h,s) %u,%u,%u",startcyl,starthead,startsect); - //LOG_MSG("endcyl %u heads %u sectors %u",endcyl,heads,sectors); - //LOG_MSG("psize %u start %u end %u",pe1_size,part_start,part_end); - } else { - sizes[0] = 512; sizes[1] = sectors; - sizes[2] = heads; sizes[3] = (uint16_t)(fcsize / (heads*sectors)); - if (sizes[3]>1023) sizes[3] = 1023; - return true; - } - } - return false; - } - - bool DetectBximagePartition(uint32_t fcsize, Bitu sizes[]) const { - // Try bximage disk geometry - uint32_t cylinders = fcsize / (16 * 63); - // Int13 only supports up to 1023 cylinders - // For mounting unknown images we could go up with the heads to 255 - if ((cylinders * 16 * 63 == fcsize) && (cylinders<1024)) { - sizes[0] = 512; sizes[1] = 63; sizes[2] = 16; sizes[3] = cylinders; - return true; - } - return false; - } - - bool MountIso(const char drive, const std::vector &paths, const signed char ide_index, const bool ide_slave) { - //mount cdrom - if (Drives[drive - 'A']) { - WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); - return false; - } - uint8_t mediaid = 0xF8; - MSCDEX_SetCDInterface(CDROM_USE_SDL, -1); - // create new drives for all images - std::vector isoDisks; - std::vector::size_type i; - std::vector::size_type ct; - for (i = 0; i < paths.size(); i++) { - int error = -1; - DOS_Drive* newDrive = new isoDrive(drive, wpcolon&&paths[i].length()>1&&paths[i].c_str()[0]==':'?paths[i].c_str()+1:paths[i].c_str(), mediaid, error, options); - isoDisks.push_back(newDrive); - if(!qmount) - switch(error) { - case 0: break; - case 1: WriteOut(MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS")); break; - case 2: WriteOut(MSG_Get("MSCDEX_ERROR_NOT_SUPPORTED")); break; - case 3: WriteOut(MSG_Get("MSCDEX_ERROR_OPEN")); break; - case 4: WriteOut(MSG_Get("MSCDEX_TOO_MANY_DRIVES")); break; - case 5: WriteOut(MSG_Get("MSCDEX_LIMITED_SUPPORT")); break; - case 6: WriteOut(MSG_Get("MSCDEX_INVALID_FILEFORMAT")); break; - default: WriteOut(MSG_Get("MSCDEX_UNKNOWN_ERROR")); break; - } - // error: clean up and leave - if (error) { - for (ct = 0; ct < isoDisks.size(); ct++) { - delete isoDisks[ct]; - } - return false; - } - } - // Update DriveManager - for (ct = 0; ct < isoDisks.size(); ct++) { - DriveManager::AppendDisk(drive - 'A', isoDisks[ct]); - } - DriveManager::InitializeDrive(drive - 'A'); - DOS_EnableDriveMenu(drive); - - // Set the correct media byte in the table - mem_writeb(Real2Phys(dos.tables.mediaid) + ((unsigned int)drive - 'A') * dos.tables.dpb_size, mediaid); - - // If instructed, attach to IDE controller as ATAPI CD-ROM device - if (ide_index >= 0) IDE_CDROM_Attach(ide_index, ide_slave, drive - 'A'); - - // Print status message (success) - if (!qmount) WriteOut(MSG_Get("MSCDEX_SUCCESS")); - if (!paths.empty()) { - std::string tmp(wpcolon&&paths[0].length()>1&&paths[0].c_str()[0]==':'?paths[0].substr(1):paths[0]); - for (i = 1; i < paths.size(); i++) { - tmp += "; " + (wpcolon&&paths[i].length()>1&&paths[i].c_str()[0]==':'?paths[i].substr(1):paths[i]); - } - lastmount = drive; - if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"), drive, tmp.c_str()); - } - else { - lastmount = drive; - } - return true; - } - - imageDisk* MountImageNone(const char* fileName, FILE* file, const Bitu sizesOriginal[], const int reserved_cylinders, bool roflag) { - bool assumeHardDisk = false; - imageDisk* newImage = nullptr; - Bitu sizes[4]; - sizes[0] = sizesOriginal[0]; - sizes[1] = sizesOriginal[1]; - sizes[2] = sizesOriginal[2]; - sizes[3] = sizesOriginal[3]; - - if (!strcmp(fileName,"empty")) { - imageDiskEmptyDrive *emd = new imageDiskEmptyDrive(); - if (sizes[0] != 0 && sizes[1] != 0 && sizes[2] != 0 && sizes[3] != 0) { - emd->sector_size = sizes[0]; - emd->sectors = sizes[1]; - emd->heads = sizes[2]; - emd->cylinders = sizes[3]; - emd->diskSizeK = ((sizes[0]*sizes[1]*sizes[2]*sizes[3])+512)/1024; - emd->UpdateFloppyType(); - } - LOG_MSG("Mounted empty C/H/S/sz %u/%u/%u/%u %uKB", - (unsigned int)emd->cylinders, - (unsigned int)emd->heads, - (unsigned int)emd->sectors, - (unsigned int)emd->sector_size, - (unsigned int)emd->diskSizeK); - return emd; - } - - //check for VHD files - if (sizes[0] == 0 /* auto detect size */) { - const char *ext = strrchr(fileName, '.'); - if (ext != NULL) { - if (!strcasecmp(ext, ".vhd")) { - bool ro=wpcolon&&strlen(fileName)>1&&fileName[0]==':'; - imageDiskVHD::ErrorCodes ret = imageDiskVHD::Open(ro?fileName+1:fileName, ro||roflag, &newImage); - switch (ret) { - case imageDiskVHD::ERROR_OPENING: WriteOut(MSG_Get("VHD_ERROR_OPENING")); break; - case imageDiskVHD::INVALID_DATA: WriteOut(MSG_Get("VHD_INVALID_DATA")); break; - case imageDiskVHD::UNSUPPORTED_TYPE: WriteOut(MSG_Get("VHD_UNSUPPORTED_TYPE")); break; - case imageDiskVHD::ERROR_OPENING_PARENT: WriteOut(MSG_Get("VHD_ERROR_OPENING_PARENT")); break; - case imageDiskVHD::PARENT_INVALID_DATA: WriteOut(MSG_Get("VHD_PARENT_INVALID_DATA")); break; - case imageDiskVHD::PARENT_UNSUPPORTED_TYPE: WriteOut(MSG_Get("VHD_PARENT_UNSUPPORTED_TYPE")); break; - case imageDiskVHD::PARENT_INVALID_MATCH: WriteOut(MSG_Get("VHD_PARENT_INVALID_MATCH")); break; - case imageDiskVHD::PARENT_INVALID_DATE: WriteOut(MSG_Get("VHD_PARENT_INVALID_DATE")); break; - case imageDiskVHD::UNSUPPORTED_WRITE: roflag=true; break; - default: break; - } - return newImage; - } - else if (!strcasecmp(ext, ".hdi")) { - assumeHardDisk = true; /* bugfix for HDI images smaller than 2.88MB so that the .hdi file is not mistaken for a floppy disk image */ - } - } - } - - uint32_t imagesize; - /* auto-fill: sector size */ - if (sizes[0] == 0) sizes[0] = 512; - - bool readonly = wpcolon&&strlen(fileName)>1&&fileName[0]==':'; - const char* fname=readonly?fileName+1:fileName; - FILE *newDisk = file==NULL?fopen_lock(fname, readonly||roflag?"rb":"rb+", roflag):file; - if (!newDisk) { - if (!qmount) WriteOut("Unable to open '%s'\n", fname); - return NULL; - } - - QCow2Image::QCow2Header qcow2_header = QCow2Image::read_header(newDisk); - - uint64_t sectors; - if (qcow2_header.magic == QCow2Image::magic && (qcow2_header.version == 2 || qcow2_header.version == 3)) { - uint32_t cluster_size = 1u << qcow2_header.cluster_bits; - if ((sizes[0] < 512) || ((cluster_size % sizes[0]) != 0)) { - WriteOut("Sector size must be larger than 512 bytes and evenly divide the image cluster size of %lu bytes.\n", cluster_size); - return nullptr; - } - sectors = (uint64_t)qcow2_header.size / (uint64_t)sizes[0]; - imagesize = (uint32_t)(qcow2_header.size / 1024L); - setbuf(newDisk, NULL); - newImage = new QCow2Disk(qcow2_header, newDisk, fname, imagesize, (uint32_t)sizes[0], (imagesize > 2880)); - } - else { - char tmp[256]; - - fseeko64(newDisk, 0L, SEEK_SET); - size_t readResult = fread(tmp, 256, 1, newDisk); // look for magic signatures - if (readResult != 1) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in MountImageNone\n"); - return NULL; - } - - const char *ext = strrchr(fname,'.'); - - if (ext != NULL && !strcasecmp(ext, ".d88")) { - fseeko64(newDisk, 0L, SEEK_END); - sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; - imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ - setbuf(newDisk, NULL); - newImage = new imageDiskD88(newDisk, fname, imagesize, false/*this is a FLOPPY image format*/); - } - else if (!memcmp(tmp, "VFD1.", 5)) { /* FDD files */ - fseeko64(newDisk, 0L, SEEK_END); - sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; - imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ - setbuf(newDisk, NULL); - newImage = new imageDiskVFD(newDisk, fname, imagesize, false/*this is a FLOPPY image format*/); - } - else if (!memcmp(tmp,"T98FDDIMAGE.R0\0\0",16)) { - fseeko64(newDisk, 0L, SEEK_END); - sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; - imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ - setbuf(newDisk, NULL); - newImage = new imageDiskNFD(newDisk, fname, imagesize, false/*this is a FLOPPY image format*/, 0); - } - else if (!memcmp(tmp,"T98FDDIMAGE.R1\0\0",16)) { - fseeko64(newDisk, 0L, SEEK_END); - sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; - imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ - setbuf(newDisk, NULL); - newImage = new imageDiskNFD(newDisk, fname, imagesize, false/*this is a FLOPPY image format*/, 1); - } - else { - fseeko64(newDisk, 0L, SEEK_END); - sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; - imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ - setbuf(newDisk, NULL); - newImage = new imageDisk(newDisk, fname, imagesize, (imagesize > 2880) || assumeHardDisk); - } - } - - /* sometimes imageDisk is able to determine geometry automatically (HDI images) */ - if (newImage) { - if (newImage->sectors != 0 && newImage->heads != 0 && newImage->cylinders != 0 && newImage->sector_size != 0) { - /* prevent the code below from changing the geometry */ - sizes[0] = newImage->sector_size; - sizes[1] = newImage->sectors; - sizes[2] = newImage->heads; - sizes[3] = newImage->cylinders; - } - } - - /* try auto-detect */ - if (sizes[3] == 0 && sizes[2] == 0) { - DetectGeometry(newDisk, fname, sizes); - } - - /* auto-fill: sector/track count */ - if (sizes[1] == 0) sizes[1] = 63; - /* auto-fill: head/cylinder count */ - if (sizes[3]/*cylinders*/ == 0 && sizes[2]/*heads*/ == 0) { - sizes[2] = 16; /* typical hard drive, unless a very old drive */ - sizes[3]/*cylinders*/ = - (Bitu)(((uint64_t)sectors + ((uint64_t)sizes[2]/*heads*/ * (uint64_t)sizes[1]/*sectors/track*/) - (uint64_t)1u) / - ((uint64_t)sizes[2]/*heads*/ * (uint64_t)sizes[1]/*sectors/track*/)); - - if (IS_PC98_ARCH) { - /* TODO: PC-98 has its own issues with a 4096-cylinder limit */ - } - else { - /* INT 13h mapping, deal with 1024-cyl limit */ - while (sizes[3] > 1024) { - if (sizes[2] >= 255) break; /* nothing more we can do */ - - /* try to generate head count 16, 32, 64, 128, 255 */ - sizes[2]/*heads*/ *= 2; - if (sizes[2] >= 256) sizes[2] = 255; - - /* and recompute cylinders */ - sizes[3]/*cylinders*/ = - (Bitu)(((uint64_t)sectors + ((uint64_t)sizes[2]/*heads*/ * (uint64_t)sizes[1]/*sectors/track*/) - (uint64_t)1u) / - ((uint64_t)sizes[2]/*heads*/ * (uint64_t)sizes[1]/*sectors/track*/)); - } - } - } - - LOG(LOG_DOSMISC, LOG_NORMAL)("Mounting image as C/H/S %u/%u/%u with %u bytes/sector", - (unsigned int)sizes[3], (unsigned int)sizes[2], (unsigned int)sizes[1], (unsigned int)sizes[0]); - - if (imagesize > 2880) newImage->Set_Geometry((uint32_t)sizes[2], (uint32_t)sizes[3], (uint32_t)sizes[1], (uint32_t)sizes[0]); - if (reserved_cylinders > 0) newImage->Set_Reserved_Cylinders((Bitu)reserved_cylinders); - - return newImage; - } -}; - -void IMGMOUNT_ProgramStart(Program * * make) { - *make=new IMGMOUNT; -} - -void runImgmount(const char *str) { - IMGMOUNT imgmount; - imgmount.cmd=new CommandLine("IMGMOUNT", str); - imgmount.Run(); -} - -Bitu DOS_SwitchKeyboardLayout(const char* new_layout, int32_t& tried_cp); -Bitu DOS_LoadKeyboardLayout(const char * layoutname, int32_t codepage, const char * codepagefile); -Bitu DOS_ChangeKeyboardLayout(const char* layoutname, int32_t codepage); -Bitu DOS_ChangeCodepage(int32_t codepage, const char* codepagefile); -const char* DOS_GetLoadedLayout(void); - -class KEYB : public Program { -public: - void Run(void) override; -}; - -void KEYB::Run(void) { - if (cmd->FindCommand(1,temp_line)) { /* first parameter is layout ID */ - if (cmd->FindString("?",temp_line,false)) { - resetcolor = true; - WriteOut(MSG_Get("PROGRAM_KEYB_SHOWHELP")); - } else { - Bitu keyb_error=0; /* Return code of switching keyboard layouts */ - std::string cp_string=""; - const char* layout_id = temp_line.c_str(); - cmd->FindCommand(2,cp_string); /* second parameter is codepage number */ - int32_t cp = cp_string.size() ? atoi(cp_string.c_str()) : 0;; - int32_t tocp = !strcasecmp(layout_id, "jp") ? 932 : (!strcasecmp(layout_id, "ko") ? 949 : (!strcasecmp(layout_id, "tw") || !strcasecmp(layout_id, "hk") || !strcasecmp(layout_id, "zht") || (!strcasecmp(layout_id, "zh") && ((cp == 950 || cp == 951) || (!cp_string.size() && (dos.loaded_codepage == 950 || dos.loaded_codepage == 951)))) ? (cp == 951 || (!cp_string.size() && dos.loaded_codepage == 951) ? 951 : 950) : (!strcasecmp(layout_id, "cn") || !strcasecmp(layout_id, "zhs") || !strcasecmp(layout_id, "zh") ? 936 : 0))); - int32_t cpbak = dos.loaded_codepage; - const char* layout_name = DOS_GetLoadedLayout(); - if(tocp && !IS_PC98_ARCH) { - dos.loaded_codepage = tocp; -#if defined(USE_TTF) - if(ttf.inUse) { - dos.loaded_codepage = cpbak; - toSetCodePage(NULL, tocp, -1); - } - else -#endif - { - MSG_Init(); - DOSBox_SetSysMenu(); - if(isDBCSCP()) { - ShutFontHandle(); - InitFontHandle(); - JFONT_Init(); - } - SetupDBCSTable(); - runRescan("-A -Q"); -#if C_OPENGL && DOSBOXMENU_TYPE == DOSBOXMENU_SDLDRAW - if(OpenGL_using() && control->opt_lang.size() && lastcp && lastcp != dos.loaded_codepage) - UpdateSDLDrawTexture(); -#endif - } - if(!strcasecmp(layout_id, "jp")) { - keyb_error = DOS_LoadKeyboardLayout("jp", tocp, "auto"); /* Load a default layout if not loaded at all */ - if(cp) keyb_error = DOS_ChangeCodepage(cp , "auto"); - if(keyb_error == KEYB_NOERROR) DOS_ChangeKeyboardLayout("jp", cp ? cp : tocp); - } - else { - keyb_error = DOS_SwitchKeyboardLayout("us", tocp); /* set Korean and Chinese keyboard layout to be "us" */ - /* FIX_ME: Chinese keyboards are identical to US keyboards, but some fixes may be needed for Korean unique keys */ - } - } - else if (cp) { - char cp_file_name[256]; - if (cmd->FindCommand(3,cp_string)) { - /* third parameter is codepage file */ - strcpy(cp_file_name, cp_string.c_str()); - } else { - /* no codepage file specified, use automatic selection */ - strcpy(cp_file_name, "auto"); - } - keyb_error = DOS_LoadKeyboardLayout(layout_id, cp, cp_file_name); - } - else { - if(!strcasecmp(layout_id, "us")) { - keyb_error = DOS_LoadKeyboardLayout("us", 437, "auto"); /* set 437 as default codepage for US layout */ - dos.loaded_codepage = 437; - } - else { - if(layout_name == NULL) { - keyb_error = DOS_LoadKeyboardLayout("us", 437, "auto"); /* Load a default layout if not loaded at all */ - } - keyb_error = DOS_SwitchKeyboardLayout(layout_id, cp); - } - } - switch (keyb_error) { - case KEYB_NOERROR: - { - SwitchLanguage(cpbak, cp ? cp : tocp, true); - WriteOut(MSG_Get("PROGRAM_KEYB_NOERROR"),layout_id, dos.loaded_codepage); - runRescan("-A -Q"); -#if C_OPENGL && DOSBOXMENU_TYPE == DOSBOXMENU_SDLDRAW - if (OpenGL_using() && control->opt_lang.size() && lastcp && lastcp != dos.loaded_codepage) - UpdateSDLDrawTexture(); -#endif - break; + #include "dosbox.h" + #include + #include + #include + #include + #include + #include + #include + #include + #include + + #include "menudef.h" + #include "programs.h" + #include "support.h" + #include "drives.h" + #include "cross.h" + #include "regs.h" + #include "ide.h" + #include "cpu.h" + #include "callback.h" + #include "cdrom.h" + #include "builtin.h" + #include "bios_disk.h" + #include "dos_system.h" + #include "dos_inc.h" + #include "bios.h" + #include "bitop.h" + #include "inout.h" + #include "dma.h" + #include "bios_disk.h" + #include "qcow2_disk.h" + #include "shell.h" + #include "setup.h" + #include "control.h" + #include + #include "menu.h" + #include "render.h" + #include "mouse.h" + #include "eltorito.h" + #include "../ints/int10.h" + #include "../output/output_opengl.h" + #include "paging.h" + #if !defined(HX_DOS) + #include "../libs/tinyfiledialogs/tinyfiledialogs.c" + #endif + #if defined(WIN32) + #ifndef C_ICONV + # define C_ICONV + # include "../misc/winiconv.c" + #endif + typedef wchar_t host_cnv_char_t; + host_cnv_char_t *CodePageGuestToHost(const char *s); + #if !defined(S_ISREG) + # define S_ISREG(x) ((x & S_IFREG) == S_IFREG) + #endif + #include + #else + #include + #endif + #ifdef C_ICONV + #include "iconvpp.hpp" + typedef char16_t test_char_t; + typedef std::basic_string test_string; + typedef std::basic_string test_char; + #endif + int freesizecap = 1; + int result_errorcode = 0; + char lastmount = 0; + bool Mouse_Drv=true; + bool Mouse_Vertical = false; + bool force_nocachedir = false; + bool lockmount = true; + bool wpcolon = true; + bool convertimg = true; + bool startcmd = false; + bool startwait = true; + bool startquiet = false; + bool starttranspath = false; + bool mountwarning = true; + bool qmount = false; + bool nowarn = false; + bool CodePageHostToGuestUTF8(char *d/*CROSS_LEN*/,const char *s/*CROSS_LEN*/), CodePageHostToGuestUTF16(char *d/*CROSS_LEN*/,const uint16_t *s/*CROSS_LEN*/); + inline bool CodePageHostToGuestUTF16(char *d/*CROSS_LEN*/,const char16_t *s/*CROSS_LEN*/) { + return CodePageHostToGuestUTF16(d, reinterpret_cast(s)); + } + extern bool systemmessagebox(char const * aTitle, char const * aMessage, char const * aDialogType, char const * aIconType, int aDefaultButton); + extern bool addovl, addipx, addne2k, prepared, inshell, usecon, uao, loadlang, morelen, mountfro[26], mountiro[26], resetcolor, staycolors, printfont, notrycp, internal_program; + extern bool clear_screen(), OpenGL_using(void), DOS_SetAnsiAttr(uint8_t attr), isDBCSCP(); + extern int lastcp, lastmsgcp, tryconvertcp, FileDirExistCP(const char *name), FileDirExistUTF8(std::string &localname, const char *name); + extern uint8_t DOS_GetAnsiAttr(void); + extern int toSetCodePage(DOS_Shell *shell, int newCP, int opt); + void MSG_Init(), JFONT_Init(), InitFontHandle(), ShutFontHandle(), DOSBox_SetSysMenu(), Load_Language(std::string name); + void DOS_EnableDriveMenu(char drv), GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused), UpdateSDLDrawTexture(); + void runBoot(const char *str), runMount(const char *str), runImgmount(const char *str), runRescan(const char *str), show_prompt(), ttf_reset(void); + void getdrivezpath(std::string &path, std::string const& dirname), drivezRegister(std::string const& path, std::string const& dir, bool usecp), UpdateDefaultPrinterFont(void); + std::string GetDOSBoxXPath(bool withexe=false); + FILE *testLoadLangFile(const char *fname); + bool CheckDBCSCP(int32_t codepage); + + #define MAXU32 0xffffffff + // #include "zip.h" + // #include "unzip.h" + // #include "ioapi.h" + // #include "zipcppstdbuf.h" + + #if defined(OS2) + #define INCL DOSFILEMGR + #define INCL_DOSERRORS + #include "os2.h" + #endif + + #if defined(WIN32) + #ifndef S_ISDIR + #define S_ISDIR(m) (((m)&S_IFMT)==S_IFDIR) + #endif + #endif + + #if defined(RISCOS) + #include + #include + #endif + + #if C_DEBUG + Bitu DEBUG_EnableDebugger(void); + #endif + + /* Microsoft likes to make POSIX library functions less convenient and your code + * less portable by nagging you to add a leading underscore to those functions. */ + #if !defined(_MSC_VER) + #define _access access + #define _strdup strdup + #endif + + class MOUSE : public Program { + public: + void Run(void) override; + }; + + void MOUSE::Run(void) { + if (cmd->FindExist("/?",false) || cmd->FindExist("/h",false)) { + WriteOut(MSG_Get("PROGRAM_MOUSE_HELP")); + return; + } + if (!Mouse_Drv) { + if (cmd->FindExist("/u",false)) + WriteOut(MSG_Get("PROGRAM_MOUSE_NOINSTALLED")); + else { + Mouse_Drv = true; + mainMenu.get_item("dos_mouse_enable_int33").check(Mouse_Drv).refresh_item(mainMenu); + WriteOut(MSG_Get("PROGRAM_MOUSE_INSTALL")); + if (cmd->FindExist("/v",false)) { + Mouse_Vertical = true; + WriteOut(MSG_Get("PROGRAM_MOUSE_VERTICAL")); + } else { + Mouse_Vertical = false; + } + mainMenu.get_item("dos_mouse_y_axis_reverse").check(Mouse_Vertical).refresh_item(mainMenu); + } + } + else { + if (cmd->FindExist("/u",false)) { + Mouse_Drv = false; + mainMenu.get_item("dos_mouse_enable_int33").check(Mouse_Drv).refresh_item(mainMenu); + WriteOut(MSG_Get("PROGRAM_MOUSE_UNINSTALL")); + } else + if (cmd->FindExist("/v",false)) { + if(!Mouse_Vertical) { + Mouse_Vertical = true; + WriteOut(MSG_Get("PROGRAM_MOUSE_VERTICAL")); + } else { + Mouse_Vertical = false; + WriteOut(MSG_Get("PROGRAM_MOUSE_VERTICAL_BACK")); + } + mainMenu.get_item("dos_mouse_y_axis_reverse").check(Mouse_Vertical).refresh_item(mainMenu); + } else + WriteOut(MSG_Get("PROGRAM_MOUSE_ERROR")); + } + } + + static void MOUSE_ProgramStart(Program * * make) { + *make=new MOUSE; + } + + void DetachFromBios(imageDisk* image) { + if (image) { + for (int index = 0; index < MAX_DISK_IMAGES; index++) { + if (imageDiskList[index] == image) { + if (index > 1) IDE_Hard_Disk_Detach(index); + imageDiskList[index]->Release(); + imageDiskChange[index] = true; + imageDiskList[index] = NULL; + } + } + } + } + + bool SwitchLanguage(int oldcp, int newcp, bool confirm) { + auto iterold = langcp_map.find(lastmsgcp), iternew = langcp_map.find(newcp); + std::string langold = iterold != langcp_map.end() ? iterold->second : "", langnew = iternew != langcp_map.end() ? iternew->second : ""; + if (loadlang && langnew.size() && strcasecmp(langold.c_str(), langnew.c_str())) { + FILE *file = testLoadLangFile(langnew.c_str()); + if (file) { + fclose(file); + std::string msg = "You have changed the active code page to " + std::to_string(newcp) + ". Do you want to load language file " + langnew + " for this code page?"; + if (!confirm || (CheckDBCSCP(oldcp) && !CheckDBCSCP(newcp)) || systemmessagebox("DOSBox-X language file", msg.c_str(), "yesno","question", 2)) { + SetVal("dosbox", "language", langnew); + Load_Language(langnew); + lastmsgcp = newcp; + return true; // Will load language file for the active codepage + } + } + } + return false; + } + + extern std::string hidefiles, dosbox_title; + extern int swapInDisksSpecificDrive; + extern bool dos_kernel_disabled, clearline; + void MSCDEX_SetCDInterface(int intNr, int forceCD); + bool FDC_UnassignINT13Disk(unsigned char drv); + bool bootguest=false, use_quick_reboot=false; + int bootdrive=-1; + uint8_t ZDRIVE_NUM = 25; + std::string msgget; + static const char* UnmountHelper(char umount) { + int i_drive; + if (umount < '0' || umount > 3+'0') + i_drive = toupper(umount) - 'A'; + else + i_drive = umount - '0'; + + if (i_drive >= DOS_DRIVES || i_drive < 0) + return MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"); + + if (i_drive < MAX_DISK_IMAGES && Drives[i_drive] == NULL && imageDiskList[i_drive] == NULL) + return MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"); + + if (i_drive >= MAX_DISK_IMAGES && Drives[i_drive] == NULL) + return MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"); + + if (i_drive <= 1) + FDC_UnassignINT13Disk(i_drive); + + msgget=MSG_Get("PROGRAM_MOUNT_UMOUNT_SUCCESS"); + if (Drives[i_drive]) { + const bool partitionMount = Drives[i_drive]->partitionMount; + const fatDrive* drive = dynamic_cast(Drives[i_drive]); + imageDisk* image = drive ? drive->loadedDisk : NULL; + const isoDrive* cdrom = dynamic_cast(Drives[i_drive]); + switch (DriveManager::UnmountDrive(i_drive)) { + case 1: return MSG_Get("PROGRAM_MOUNT_UMOUNT_NO_VIRTUAL"); + case 2: return MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS"); + } + if (image && !partitionMount) DetachFromBios(image); + if (cdrom) IDE_CDROM_Detach(i_drive); + Drives[i_drive] = nullptr; + DOS_EnableDriveMenu(i_drive+'A'); + mem_writeb(Real2Phys(dos.tables.mediaid)+(unsigned int)i_drive*dos.tables.dpb_size,0); + if (i_drive == DOS_GetDefaultDrive()) + DOS_SetDrive(ZDRIVE_NUM); + if (cdrom) + for (int drv=0; drv<2; drv++) + if (Drives[drv]) { + fatDrive *fdp = dynamic_cast(Drives[drv]); + if (fdp&&fdp->opts.mounttype==1&&toupper(umount)==fdp->el.CDROM_drive) { + msgget+=UnmountHelper('A'+drv); + size_t found=msgget.rfind("%c"); + if (found!=std::string::npos) + msgget.replace(found, 2, std::string(1, 'A'+drv)); + } + } + } + + if (i_drive < MAX_DISK_IMAGES && imageDiskList[i_drive]) { + imageDiskList[i_drive]->Release(); + imageDiskList[i_drive] = NULL; + } + if (swapInDisksSpecificDrive == i_drive) { + for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { + if (diskSwap[si] != NULL) { + diskSwap[si]->Release(); + diskSwap[si] = NULL; + } + } + swapInDisksSpecificDrive = -1; + } + + return msgget.c_str(); + } + + void MountHelper(char drive, const char drive2[DOS_PATHLENGTH], std::string const& drive_type) { + std::vector options; + DOS_Drive * newdrive; + std::string temp_line; + std::string str_size; + uint16_t sizes[4]; + uint8_t mediaid=0; + + if(drive_type=="CDROM") { + mediaid=0xF8; /* Hard Disk */ + str_size="2048,1,65535,0"; + } else { + if(drive_type=="FLOPPY") { + mediaid=0xF0; /* Floppy 1.44 media */ + str_size="512,1,2880,2880"; /* All space free */ + } else if(drive_type=="LOCAL") { + mediaid=0xF8; + str_size="512,32,0,0"; + } + } + + char number[20]; const char * scan=str_size.c_str(); + Bitu index=0; Bitu count=0; + while (*scan) { + if (*scan==',') { + number[index]=0;sizes[count++]=atoi(number); + index=0; + } else number[index++]=*scan; + scan++; + } + number[index]=0; sizes[count++]=atoi(number); + + temp_line = drive2; + if(temp_line.size() > 3 && temp_line[temp_line.size()-1]=='\\') temp_line.erase(temp_line.size()-1,1); + if (temp_line[temp_line.size()-1]!=CROSS_FILESPLIT) temp_line+=CROSS_FILESPLIT; + uint8_t bit8size=(uint8_t) sizes[1]; + + if(drive_type=="CDROM") { + int num = -1; + int error; + + int id, major, minor; + DOSBox_CheckOS(id, major, minor); + if ((id==VER_PLATFORM_WIN32_NT) && (major>5)) { + // Vista/above + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); + } else { + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); + } + newdrive = new cdromDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],0,mediaid,error,options); + std::string errmsg; + switch (error) { + case 0 : errmsg=MSG_Get("MSCDEX_SUCCESS"); break; + case 1 : errmsg=MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS"); break; + case 2 : errmsg=MSG_Get("MSCDEX_ERROR_NOT_SUPPORTED"); break; + case 3 : errmsg=MSG_Get("MSCDEX_ERROR_PATH"); break; + case 4 : errmsg=MSG_Get("MSCDEX_TOO_MANY_DRIVES"); break; + case 5 : errmsg=MSG_Get("MSCDEX_LIMITED_SUPPORT"); break; + default : errmsg=MSG_Get("MSCDEX_UNKNOWN_ERROR"); break; + } + if (error) { + systemmessagebox(error==5?"Warning":"Error",errmsg.c_str(),"ok","error", 1); + if (error!=5) { + delete newdrive; + return; + } + } + } else { + newdrive=new localDrive(temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,options); + newdrive->readonly = mountfro[drive-'A']; + } + + if (!newdrive) E_Exit("DOS:Can't create drive"); + Drives[drive-'A']=newdrive; + DOS_EnableDriveMenu(drive); + mem_writeb(Real2Phys(dos.tables.mediaid)+(drive-'A')*dos.tables.dpb_size,mediaid); + if(drive_type=="CDROM") + LOG_MSG("GUI: Drive %c is mounted as CD-ROM",drive); + else + LOG_MSG("GUI: Drive %c is mounted as local directory",drive); + if(drive == drive2[0] && strlen(drive2) == 3) { + // automatic mount + } else { + if(drive_type=="CDROM") return; + std::string label; + label = drive; + if(drive_type=="LOCAL") + label += "_DRIVE"; + else + label += "_FLOPPY"; + newdrive->SetLabel(label.c_str(),false,true); + } + } + + #if defined(WIN32) + void MenuMountDrive(char drive, const char drive2[DOS_PATHLENGTH]) { + std::vector options; + std::string str(1, drive); + std::string drive_warn; + if (Drives[drive-'A']) { + drive_warn="Drive "+str+": is already mounted. Unmount it first, and then try again."; + systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); + return; + } + if(control->SecureMode()) { + systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); + return; + } + DOS_Drive * newdrive; + std::string temp_line; + std::string str_size; + uint16_t sizes[4]; + uint8_t mediaid; + drive_warn="Do you really want to give DOSBox-X access to"; + int type=GetDriveType(drive2); + if(type==DRIVE_NO_ROOT_DIR) { + systemmessagebox("Error",("Drive "+str+": does not exist in the system.").c_str(),"ok","error", 1); + return; + } else if(type==DRIVE_CDROM) + drive_warn += " your real CD-ROM drive "; + else if(type==DRIVE_REMOVABLE) + drive_warn += drive=='A'||drive=='B'?" your real floppy drive ":" your real removable drive "; + else if(type==DRIVE_REMOTE) + drive_warn += " your real network drive "; + else + drive_warn += " your real hard drive "; + + if (mountwarning && !systemmessagebox("Warning",(drive_warn+str+"?").c_str(),"yesno","warning",1)) return; + + if(type==DRIVE_CDROM) { + mediaid=0xF8; /* Hard Disk */ + str_size="2048,1,65535,0"; + } else if(type==DRIVE_REMOVABLE && (drive=='A'||drive=='B')) { + mediaid=0xF0; /* Floppy 1.44 media */ + str_size="512,1,2880,2880"; /* All space free */ + } else { + mediaid=0xF8; + str_size="512,32,0,0"; + } + + char number[20]; const char * scan=str_size.c_str(); + Bitu index=0; Bitu count=0; + while (*scan) { + if (*scan==',') { + number[index]=0;sizes[count++]=atoi(number); + index=0; + } else number[index++]=*scan; + scan++; + } + number[index]=0; sizes[count++]=atoi(number); + uint8_t bit8size=(uint8_t) sizes[1]; + + temp_line = drive2; + int error = 0, num = -1; + if(type==DRIVE_CDROM) { + int id, major, minor; + DOSBox_CheckOS(id, major, minor); + if ((id==VER_PLATFORM_WIN32_NT) && (major>5)) { + // Vista/above + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); + } else { + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); + } + newdrive = new cdromDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],0,mediaid,error,options); + std::string errmsg; + switch (error) { + case 0 : errmsg=MSG_Get("MSCDEX_SUCCESS"); break; + case 1 : errmsg=MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS"); break; + case 2 : errmsg=MSG_Get("MSCDEX_ERROR_NOT_SUPPORTED"); break; + case 3 : errmsg=MSG_Get("MSCDEX_ERROR_PATH"); break; + case 4 : errmsg=MSG_Get("MSCDEX_TOO_MANY_DRIVES"); break; + case 5 : errmsg=MSG_Get("MSCDEX_LIMITED_SUPPORT"); break; + default : errmsg=MSG_Get("MSCDEX_UNKNOWN_ERROR"); break; + } + if (error) { + systemmessagebox(error==5?"Warning":"Error",errmsg.c_str(),"ok",error==5?"warning":"error", 1); + if (error!=5) { + delete newdrive; + return; + } + } + } else { + newdrive=new localDrive(temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,options); + newdrive->readonly = mountfro[drive-'A']; + } + + if (!newdrive) E_Exit("DOS:Can't create drive"); + if(error && (type==DRIVE_CDROM)) return; + Drives[drive-'A']=newdrive; + DOS_EnableDriveMenu(drive); + mem_writeb(Real2Phys(dos.tables.mediaid)+(drive-'A')*dos.tables.dpb_size,mediaid); + if(type == DRIVE_CDROM) LOG_MSG("GUI: Drive %c is mounted as CD-ROM %c:\\", drive, drive); + else LOG_MSG("GUI: Drive %c is mounted as local directory %c:\\", drive, drive); + if(drive == drive2[0] && strlen(drive2) == 3) { + // automatic mount + } else { + if(type == DRIVE_CDROM) return; + std::string label; + label = drive; + if(type==DRIVE_REMOVABLE && (drive=='A'||drive=='B')) + label += "_FLOPPY"; + else + label += "_DRIVE"; + newdrive->SetLabel(label.c_str(),false,true); + } + } + #endif + + std::string newstr=""; + std::string GetNewStr(const char *str) { + newstr = str?std::string(str):""; + #if defined(WIN32) + int flags = 0; + #ifdef WC_NO_BEST_FIT_CHARS + flags |= WC_NO_BEST_FIT_CHARS; + #endif + if (str&&dos.loaded_codepage!=437) { + char *temp = NULL; + wchar_t* wstr = NULL; + int reqsize = MultiByteToWideChar(CP_UTF8, 0, str, (int)(strlen(str)+1), NULL, 0); + if (reqsize>0 && (wstr = new wchar_t[reqsize]) && MultiByteToWideChar(CP_UTF8, 0, str, (int)(strlen(str)+1), wstr, reqsize)==reqsize) { + reqsize = WideCharToMultiByte(dos.loaded_codepage==808?866:(dos.loaded_codepage==859?858:(dos.loaded_codepage==872?855:(dos.loaded_codepage==951?950:dos.loaded_codepage))), flags, wstr, -1, NULL, 0, "\x07", NULL); + if (reqsize > 1 && (temp = new char[reqsize]) && WideCharToMultiByte(dos.loaded_codepage==808?866:(dos.loaded_codepage==859?858:(dos.loaded_codepage==872?855:(dos.loaded_codepage==951?950:dos.loaded_codepage))), flags, wstr, -1, (LPSTR)temp, reqsize, "\x07", NULL) == reqsize) + newstr = std::string(temp); + } + } + #endif + return newstr; + } + + void MenuBrowseCDImage(char drive, int num) { + if(control->SecureMode()) { + systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); + return; + } + + if (Drives[drive-'A']&&!strncmp(Drives[drive-'A']->GetInfo(), "isoDrive ", 9)) { + #if !defined(HX_DOS) + std::string drive_warn = "CD drive "+(dos_kernel_disabled?std::to_string(num):std::string(1, drive)+":")+" is currently mounted with the image:\n\n"+std::string(Drives[drive-'A']->GetInfo()+9)+"\n\nDo you want to change the CD image now?"; + if (!systemmessagebox("Change CD image",drive_warn.c_str(),"yesno","question", 1)) return; + #endif + } else + return; + #if !defined(HX_DOS) + char CurrentDir[512] = "."; + std::vector options; + char * Temp_CurrentDir = CurrentDir; + // getcwd(Temp_CurrentDir, 512); + char const * lTheOpenFileName; + std::string files="", fname=""; + const char *lFilterPatterns[] = {"*.cdrom", "*.iso","*.cue","*.bin","*.chd","*.mdf","*.gog","*.ins","*.inst","*.CDROM", "*.ISO","*.CUE","*.BIN","*.CHD","*.MDF","*.GOG","*.INS","*.INST" }; + const char *lFilterDescription = "CD image files (*.cdrom, *.iso, *.cue, *.bin, *.chd, *.mdf, *.gog, *.ins, *.inst)"; + lTheOpenFileName = tinyfd_openFileDialog("Select a CD image file","", sizeof(lFilterPatterns) / sizeof(lFilterPatterns[0]),lFilterPatterns,lFilterDescription,0); + bool isempty = std::string(Drives[drive - 'A']->GetInfo() + 9) == "empty"; + if (lTheOpenFileName) { + isoDrive *cdrom = dynamic_cast(Drives[drive-'A']); + DOS_Drive *newDrive = NULL; + int error = -1; + uint8_t mediaid = 0xF8; + if (cdrom && dos_kernel_disabled) { + cdrom->setFileName(lTheOpenFileName); + if(isempty) { + newDrive = new isoDrive(drive, lTheOpenFileName, mediaid, error, options); + if(error) { + delete newDrive; + systemmessagebox("Error", "Could not mount the selected CD image.", "ok", "error", 1); + chdir(Temp_CurrentDir); + return; + } + delete cdrom; + cdrom = dynamic_cast(newDrive); + Drives[drive - 'A'] = cdrom; + } + } else { + newDrive = new isoDrive(drive, lTheOpenFileName, mediaid, error, options); + if (error) { + delete newDrive; + systemmessagebox("Error","Could not mount the selected CD image.","ok","error", 1); + chdir( Temp_CurrentDir ); + return; + } + cdrom = dynamic_cast(newDrive); + Drives[drive - 'A'] = cdrom; + } + if ((!isempty || !dos_kernel_disabled) && cdrom) DriveManager::ChangeDisk(drive-'A', cdrom); + } + chdir( Temp_CurrentDir ); + #endif + } + + void MenuBrowseFDImage(char drive, int num, int type) { + if(control->SecureMode()) { + systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); + return; + } + + if (type==-1 || (Drives[drive-'A'] && !strncmp(Drives[drive-'A']->GetInfo(), "fatDrive ", 9))) { + #if !defined(HX_DOS) + std::string image = type==1||(type==-1&&dynamic_cast(imageDiskList[drive-'A'])!=NULL)?"El Torito floppy image":(type==2||(type==-1&&dynamic_cast(imageDiskList[drive-'A'])!=NULL)?"RAM floppy image":(type==-1?imageDiskList[drive-'A']->diskname.c_str():Drives[drive-'A']->GetInfo()+9)); + std::string drive_warn = "Floppy drive "+(type==-1?std::string(1, drive-'A'+'0'):(dos_kernel_disabled?std::to_string(num):std::string(1, drive)+":"))+" is currently mounted with the image:\n\n"+image+"\n\nDo you want to change the floppy disk image now?"; + if (!systemmessagebox("Change floppy disk image",drive_warn.c_str(),"yesno","question", 1)) return; + #endif + } else + return; + #if !defined(HX_DOS) + char CurrentDir[512] = "."; + char * Temp_CurrentDir = CurrentDir; + // getcwd(Temp_CurrentDir, 512); + char const * lTheOpenFileName; + std::string files="", fname=""; + const char *lFilterPatterns[] = {"*.ima","*.img","*.xdf","*.fdi","*.hdm","*.nfd","*.d88","*.IMA","*.IMG","*.XDF","*.FDI","*.HDM","*.NFD","*.D88"}; + const char *lFilterDescription = "Floppy image files (*.ima, *.img, *.xdf, *.fdi, *.hdm, *.nfd, *.d88)"; + lTheOpenFileName = tinyfd_openFileDialog("Select a floppy image file","",sizeof(lFilterPatterns)/sizeof(lFilterPatterns[0]), lFilterPatterns, lFilterDescription, 0); + + if (lTheOpenFileName) { + //uint8_t mediaid = 0xF0; UNUSED + std::vector options; + if (mountiro[drive-'A']) options.emplace_back("readonly"); + fatDrive *newDrive = new fatDrive(lTheOpenFileName, 0, 0, 0, 0, options); + if (!newDrive->created_successfully) { + systemmessagebox("Error","Could not mount the selected floppy disk image.","ok","error", 1); + chdir( Temp_CurrentDir ); + return; + } + if (newDrive) { + if (type>-1) + DriveManager::ChangeDisk(drive-'A', newDrive); + else if (newDrive->loadedDisk) { + if (imageDiskList[drive-'A']) { + imageDiskList[drive-'A']->Release(); + imageDiskList[drive-'A'] = newDrive->loadedDisk; + //imageDiskList[drive-'A']->Addref(); + imageDiskChange[drive-'A'] = true; + } + if (swapInDisksSpecificDrive == drive-'A' && diskSwap[swapPosition]) { + diskSwap[swapPosition]->Release(); + diskSwap[swapPosition] = newDrive->loadedDisk; + diskSwap[swapPosition]->Addref(); + } + } + } + } + chdir( Temp_CurrentDir ); + #endif + } + + void MenuBrowseImageFile(char drive, bool arc, bool boot, bool multiple) { + std::string str(1, drive); + std::string drive_warn; + if (Drives[drive-'A']&&!boot) { + drive_warn="Drive "+str+": is already mounted. Unmount it first, and then try again."; + systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); + return; + } + if(control->SecureMode()) { + systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); + return; + } + if (dos_kernel_disabled) + return; + #if !defined(HX_DOS) + char CurrentDir[512] = "."; + char * Temp_CurrentDir = CurrentDir; + // getcwd(Temp_CurrentDir, 512); + char const * lTheOpenFileName; + std::string files="", fname=""; + if (arc) { + const char *lFilterPatterns[] = {"*.zip","*.7z","*.ZIP","*.7Z"}; + const char *lFilterDescription = "Archive files (*.zip, *.7z)"; + lTheOpenFileName = tinyfd_openFileDialog(("Select an archive file for Drive "+str+":").c_str(),"", sizeof(lFilterPatterns) / sizeof(lFilterPatterns[0]),lFilterPatterns,lFilterDescription,0); + if (lTheOpenFileName) fname = GetNewStr(lTheOpenFileName); + } else { + const char *lFilterPatterns[] = {"*.ima","*.img","*.vhd","*.fdi","*.hdi","*.nfd","*.nhd","*.d88","*.hdm","*.xdf","*.cdrom", "*.iso","*.cue","*.bin","*.chd","*.mdf","*.gog","*.ins","*.ccd","*.inst","*.IMA","*.IMG","*.VHD","*.FDI","*.HDI","*.NFD","*.NHD","*.D88","*.HDM","*.XDF",".CDROM", "*.ISO","*.CUE","*.BIN","*.CHD","*.MDF","*.GOG","*.INS","*.CCD","*.INST"}; + const char *lFilterDescription = "Disk/CD image files"; + lTheOpenFileName = tinyfd_openFileDialog(((multiple?"Select image file(s) for Drive ":"Select an image file for Drive ")+str+":").c_str(),"", sizeof(lFilterPatterns) / sizeof(lFilterPatterns[0]),lFilterPatterns,lFilterDescription,multiple?1:0); + if (lTheOpenFileName) fname = "\"" + GetNewStr(lTheOpenFileName) + "\""; + if (multiple&&fname.size()) { + files = std::regex_replace(fname, std::regex("\\|"), "\" \""); + } + while (multiple&&lTheOpenFileName&&systemmessagebox("Mount image files","Do you want to mount more image file(s)?","yesno", "question", 1)) { + lTheOpenFileName = tinyfd_openFileDialog(("Select image file(s) for Drive "+str+":").c_str(),"", sizeof(lFilterPatterns) / sizeof(lFilterPatterns[0]),lFilterPatterns,lFilterDescription,multiple?1:0); + if (lTheOpenFileName) { + fname = "\"" + GetNewStr(lTheOpenFileName) + "\""; + files = files + " " + std::regex_replace(fname, std::regex("\\|"), "\" \""); + } + } + } + + if (fname.size()||files.size()) { + char type[15]; + if (!arc&&!files.size()) { + char ext[5] = ""; + if (fname.size()>4) + strcpy(ext, fname.substr(fname.size()-4).c_str()); + if(!strcasecmp(ext,".ima")) + strcpy(type,"-t floppy "); + else if((!strcasecmp(ext,".iso")) || (!strcasecmp(ext,".cue")) || (!strcasecmp(ext,".bin")) || (!strcasecmp(ext,".chd")) || (!strcasecmp(ext,".mdf")) || (!strcasecmp(ext,".gog")) || (!strcasecmp(ext,".ins")) || (!strcasecmp(ext, ".inst"))) + strcpy(type,"-t iso "); + else + strcpy(type,""); + } else + *type=0; + char mountstring[CROSS_LEN*4+20]; + if (files.size()>CROSS_LEN*4) { + systemmessagebox("Error","The path for the file(s) to mount is too long.","ok","error", 1); + return; + } + strcpy(mountstring,type); + char temp_str[3] = { 0,0,0 }; + temp_str[0]=drive; + temp_str[1]=' '; + strcat(mountstring,temp_str); + //if (!multiple) strcat(mountstring,"\""); + strcat(mountstring,files.size()?files.c_str():fname.c_str()); + //if(!multiple) strcat(mountstring, "\""); + if(mountiro[drive - 'A']) strcat(mountstring, " -ro"); + if(boot) { + strcat(mountstring, " -u"); + mountstring[0] = drive - 'A' + '0'; + runImgmount(mountstring); // mount by drive number + std::string bootstr = "-Q "; + bootstr += drive; + bootstr += ':'; + runBoot(bootstr.c_str()); + std::string drive_warn = "Drive " + std::string(1, drive) + ": failed to boot."; + systemmessagebox("Error", drive_warn.c_str(), "ok", "error", 1); + bootstr = "-u "; + bootstr += drive - 'A' + '0'; + runImgmount(bootstr.c_str()); // unmount if boot failed + return; + } + if(arc) { + strcat(mountstring," -q"); + runMount(mountstring); + } else { + qmount=true; + runImgmount(mountstring); + qmount=false; + } + chdir( Temp_CurrentDir ); + if (!Drives[drive - 'A']) { + drive_warn="Drive "+str+": failed to mount."; + systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); + return; + } else if (multiple) { + systemmessagebox("Information",("Mounted disk images to Drive "+std::string(1,drive)+(dos.loaded_codepage==437?":\n"+files:".")+(mountiro[drive-'A']?"\n(Read-only mode)":"")).c_str(),"ok","info", 1); + } else if (lTheOpenFileName) { + systemmessagebox("Information",(std::string(arc?"Mounted archive":"Mounted disk image")+" to Drive "+std::string(1,drive)+":\n"+std::string(lTheOpenFileName)+(arc||mountiro[drive-'A']?"\n(Read-only mode)":"")).c_str(),"ok","info", 1); + } + } + chdir( Temp_CurrentDir ); + #endif + } + + void MenuBrowseFolder(char drive, std::string const& drive_type) { + std::string str(1, drive); + if (Drives[drive-'A']) { + std::string drive_warn="Drive "+str+": is already mounted. Unmount it first, and then try again."; + systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); + return; + } + if(control->SecureMode()) { + systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); + return; + } + #if !defined(HX_DOS) + std::string title = "Select a drive/directory to mount for Drive "+str+":"; + if(drive_type=="CDROM") + title += " CD-ROM\nMounting a directory as CD-ROM gives an limited support"; + else if(drive_type=="FLOPPY") + title += " as Floppy"; + else if(drive_type=="LOCAL") + title += " as Local"; + char const * lTheSelectFolderName = tinyfd_selectFolderDialog(title.c_str(), NULL); + if (lTheSelectFolderName) { + MountHelper(drive,GetNewStr(lTheSelectFolderName).c_str(),drive_type); + if (Drives[drive-'A']) systemmessagebox("Information",("Drive "+std::string(1,drive)+" is now mounted to:\n"+std::string(lTheSelectFolderName)).c_str(),"ok","info", 1); + } + #endif + } + + void MenuUnmountDrive(char drive) { + if (!Drives[drive-'A']) { + std::string drive_warn="Drive "+std::string(1, drive)+": is not yet mounted."; + systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); + return; + } + UnmountHelper(drive); + } + + void MenuBootDrive(char drive) { + if(control->SecureMode()) { + systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); + return; + } + char str[] = "-Q A:"; + str[3]=drive; + runBoot(str); + std::string drive_warn="Drive "+std::string(1, drive)+": failed to boot."; + systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); + } + + void MenuBrowseProgramFile() { + if(control->SecureMode()) { + systemmessagebox("Error",MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW"),"ok","error", 1); + return; + } + if (dos_kernel_disabled) + return; + std::string drive_warn; + DOS_MCB mcb(dos.psp()-1); + static char psp_name[9]; + mcb.GetFileName(psp_name); + if(strlen(psp_name)&&strcmp(psp_name, "COMMAND")) { + drive_warn=strcmp(psp_name, "4DOS")?"Another program is already running.":"Another shell is currently running."; + systemmessagebox("Error",drive_warn.c_str(),"ok","error", 1); + return; + } + + #if !defined(HX_DOS) + char drv=' '; + for (int i=2; i options; + void Move_Z(char new_z) { + char newz_drive = (char)toupper(new_z); + int i_newz = (int)newz_drive - (int)'A'; + if (i_newz >= 0 && i_newz < DOS_DRIVES) { + if(Drives[i_newz]) { + WriteOut("Drive %c is already in use\n", new_z); + return; + } + /* remap drives */ + Drives[i_newz] = Drives[ZDRIVE_NUM]; + Drives[ZDRIVE_NUM] = nullptr; + DOS_EnableDriveMenu(i_newz + 'A'); + DOS_EnableDriveMenu(ZDRIVE_NUM + 'A'); + if (!first_shell) return; //Should not be possible + /* Update environment */ + std::string line = ""; + char ppp[2] = { newz_drive,0 }; + std::string tempenv = ppp; tempenv += ":\\"; + std::string tempenvZ = std::string(1, 'A'+ZDRIVE_NUM); tempenvZ += ":\\"; + std::string tempenvz = std::string(1, 'a'+ZDRIVE_NUM); tempenvz += ":\\"; + if (first_shell->GetEnvStr("PATH", line)) { + std::string::size_type idx = line.find('='); + std::string value = line.substr(idx + 1, std::string::npos); + while ((idx = value.find(tempenvZ)) != std::string::npos || + (idx = value.find(tempenvz)) != std::string::npos) + value.replace(idx, 3, tempenv); + line = value; + } + if (!line.size()) line = tempenv; + first_shell->SetEnv("PATH", line.c_str()); + tempenv += "COMMAND.COM"; + first_shell->SetEnv("COMSPEC", tempenv.c_str()); + + /* Update batch file if running from Z: (very likely: autoexec) */ + if (first_shell->bf) { + std::string& name = first_shell->bf->filename; + if (name.length() > 2 && name[0] == 'A'+ZDRIVE_NUM && name[1] == ':') name[0] = newz_drive; + } + /* Change the active drive */ + if (DOS_GetDefaultDrive() == ZDRIVE_NUM) DOS_SetDrive(i_newz); + ZDRIVE_NUM = i_newz; + } + else + WriteOut("Drive %c is not a valid drive\n", new_z); + } + void ListMounts(bool quiet, bool local) { + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; + /* Command uses dta so set it to our internal dta */ + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + + if (!quiet) { + WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_1")); + WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_FORMAT"),MSG_Get("DRIVE"),MSG_Get("TYPE"),MSG_Get("LABEL")); + } + int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + if (!cols) cols=80; + if (!quiet) { + for(int p = 1;p < cols;p++) WriteOut("-"); + WriteOut("\n"); + } + bool none=true; + for (int d = 0;d < DOS_DRIVES;d++) { + if (!Drives[d]) continue; + if (local && strncasecmp("local ", Drives[d]->GetInfo(), 6)) continue; + if (quiet) { + WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"), 'A'+d, Drives[d]->GetInfo()+(local && !strncasecmp("local ", Drives[d]->GetInfo(), 6)?16:0)); + continue; + } + char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; + bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); + if (ret) { + dta.GetResult(name,lname,size,hsize,date,time,attr); + DOS_FindNext(); //Mark entry as invalid + } else name[0] = 0; + + /* Change 8.3 to 11.0 */ + const char* dot = strchr(name, '.'); + if(dot && (dot - name == 8) ) { + name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; + } + + root[1] = 0; //This way, the format string can be reused. + WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name); + none=false; + } + if (none&&!quiet) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); + dos.dta(save_dta); + } + + void Run(void) override { + DOS_Drive *newdrive = NULL; + std::string label; + std::string umount; + std::string newz; + bool quiet=false; + char drive; + + //Hack To allow long commandlines + ChangeToLongCmd(); + /* Parse the command line */ + /* if the command line is empty show current mounts */ + if (!cmd->GetCount()) { + ListMounts(false, false); + return; + } + + /* In secure mode don't allow people to change mount points. + * Neither mount nor unmount */ + if(control->SecureMode()) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); + return; + } + if (cmd->FindExist("/examples")||cmd->FindExist("-examples")) { + resetcolor = true; + #if defined (WIN32) || defined(OS2) + WriteOut(MSG_Get("PROGRAM_MOUNT_EXAMPLE"),"d:\\dosprogs","d:\\dosprogs","\"d:\\dos games\"","\"d:\\dos games\"","d:\\dosprogs","d:\\dosprogs","d:\\dosprogs","d:\\dosprogs","d:\\dosprogs","d:\\dosprogs","d:\\overlaydir"); + #else + WriteOut(MSG_Get("PROGRAM_MOUNT_EXAMPLE"),"~/dosprogs","~/dosprogs","\"~/dos games\"","\"~/dos games\"","~/dosprogs","~/dosprogs","~/dosprogs","~/dosprogs","~/dosprogs","~/dosprogs","~/overlaydir"); + #endif + return; + } + + //look for -o options + bool local = false; + { + std::string s; + while (cmd->FindString("-o", s, true)) { + if (!strcasecmp(s.c_str(), "local")) local = true; + options.push_back(s); + } + if (local && !cmd->GetCount()) { + ListMounts(false, true); + return; + } + } + + if (cmd->FindExist("-q",true)) { + quiet = true; + if (!cmd->GetCount()) { + ListMounts(true, local); + return; + } + } + + bool path_relative_to_last_config = false; + if (cmd->FindExist("-pr",true)) path_relative_to_last_config = true; + + /* Check for unmounting */ + if (cmd->FindString("-u",umount,false)) { + const char *msg=UnmountHelper(umount[0]); + if (!quiet) WriteOut(msg, toupper(umount[0])); + return; + } + + /* Check for moving Z: */ + /* Only allowing moving it once. It is merely a convenience added for the wine team */ + if (cmd->FindString("-z", newz,false)) { + if (ZDRIVE_NUM != newz[0]-'A') Move_Z(newz[0]); + return; + } + /* Show list of cdroms */ + if (cmd->FindExist("-cd",false)) { + int num = SDL_CDNumDrives(); + if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_CDROMS_FOUND"),num); + for (int i=0; iFindExist("-nocachedir",true)) + nocachedir = true; + + if (cmd->FindExist("-nl",true)) + nextdrive = true; + + bool readonly = false; + if (cmd->FindExist("-ro",true)) + readonly = true; + if (cmd->FindExist("-rw",true)) + readonly = false; + + std::string type="dir"; + cmd->FindString("-t",type,true); + std::transform(type.begin(), type.end(), type.begin(), ::tolower); + bool iscdrom = (type =="cdrom"); //Used for mscdex bug cdrom label name emulation + bool exist = false, removed = false; + if (type=="floppy" || type=="dir" || type=="cdrom" || type =="overlay") { + uint16_t sizes[4] = { 0 }; + uint8_t mediaid; + std::string str_size = ""; + if (type=="floppy") { + str_size="512,1,2880,2880"; + mediaid=0xF0; /* Floppy 1.44 media */ + } else if (type=="dir" || type == "overlay") { + // 512*32*32765==~500MB total size + // 512*32*16000==~250MB total free size + str_size="512,32,0,0"; + mediaid=0xF8; /* Hard Disk */ + } else if (type=="cdrom") { + str_size="2048,1,65535,0"; + mediaid=0xF8; /* Hard Disk */ + } else { + if (!quiet) WriteOut(MSG_Get("PROGAM_MOUNT_ILL_TYPE"),type.c_str()); + return; + } + /* Parse the free space in mb's (kb's for floppies) */ + std::string mb_size; + if(cmd->FindString("-freesize",mb_size,true)) { + char teststr[1024]; + uint16_t freesize = static_cast(atoi(mb_size.c_str())); + if (type=="floppy") { + // freesize in kb + sprintf(teststr,"512,1,2880,%d",freesize*1024/(512*1)>2880?2880:freesize*1024/(512*1)); + } else { + //if (freesize>1919) freesize=1919; + uint16_t numc=type=="cdrom"?1:32; + uint32_t total_size_cyl=32765; + uint32_t tmp=(uint32_t)freesize*1024*1024/(type=="cdrom"?2048*1:512*32); + if(tmp > 65534) numc = type == "cdrom" ? (tmp + 65535) / 65536 : 64; + uint32_t free_size_cyl=(uint32_t)freesize*1024*1024/(numc*(type=="cdrom"?2048:512)); + if (free_size_cyl>65534) free_size_cyl=65534; + if (total_size_cyl65534) total_size_cyl=65534; + sprintf(teststr,type=="cdrom"?"2048,%u,%u,%u":"512,%u,%u,%u",numc,total_size_cyl,free_size_cyl); + } + str_size=teststr; + } + + cmd->FindString("-size",str_size,true); + char number[21] = { 0 }; const char* scan = str_size.c_str(); + Bitu index = 0; Bitu count = 0; + /* Parse the str_size string */ + while (*scan && index < 20 && count < 4) { + if (*scan==',') { + number[index] = 0; + sizes[count++] = atoi(number); + index = 0; + } else number[index++] = *scan; + scan++; + } + if (count < 4) { + number[index] = 0; //always goes correct as index is max 20 at this point. + sizes[count] = atoi(number); + } + + // get the drive letter + cmd->FindCommand(1,temp_line); + if ((temp_line.size() > 2) || ((temp_line.size()>1) && (temp_line[1]!=':'))) goto showusage; + int i_drive = toupper(temp_line[0]); + if (!isalpha(i_drive)) goto showusage; + if ((i_drive - 'A') >= DOS_DRIVES || (i_drive - 'A') < 0) goto showusage; + if (!cmd->FindCommand(2,temp_line)) { + if (Drives[i_drive - 'A']) { + const char *info = Drives[i_drive - 'A']->GetInfo(); + if (!quiet) + WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"), i_drive, info+(local&&!strncasecmp("local ", info, 6)?16:0)); + else if (local&&!strncasecmp("local ", info, 6)) + WriteOut("%s\n", info+16); + else if (!local) + WriteOut("%s\n", info); + } else if (!quiet) + WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"), i_drive); + return; + } + if (!temp_line.size()) goto showusage; + if (cmd->FindExist("-u",true)) { + bool curdrv = toupper(i_drive)-'A' == DOS_GetDefaultDrive(); + const char *msg=UnmountHelper(i_drive); + if(!quiet) WriteOut(msg, toupper(i_drive)); + if(!cmd->FindCommand(2, temp_line) || !temp_line.size()) return; + if(curdrv && toupper(i_drive) - 'A' != DOS_GetDefaultDrive()) removed = true; + } + drive = static_cast(i_drive); + if (type == "overlay") { + //Ensure that the base drive exists: + if (!Drives[drive-'A']) { + if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_NO_BASE")); + return; + } + } else if (Drives[drive-'A']) { + bool found = false; + if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_ALREADY_MOUNTED"),drive,Drives[drive-'A']->GetInfo()); + if (nextdrive) + for (int i=drive-'A'+1; iconfigfiles.size() && !Cross::IsPathAbsolute(temp_line)) { + std::string lastconfigdir(control->configfiles[control->configfiles.size()-1]); + std::string::size_type pos = lastconfigdir.rfind(CROSS_FILESPLIT); + if(pos == std::string::npos) pos = 0; //No directory then erase string + lastconfigdir.erase(pos); + if (lastconfigdir.length()) temp_line = lastconfigdir + CROSS_FILESPLIT + temp_line; + } + bool is_physfs = temp_line.find(':',((temp_line[0]|0x20) >= 'a' && (temp_line[0]|0x20) <= 'z')?2:0) != std::string::npos; + struct stat test; + //Win32 : strip tailing backslashes + //os2: some special drive check + //rest: substitute ~ for home + bool failed = false; + + (void)failed;// MAY BE UNUSED + + #if defined (RISCOS) + // If the user provided a RISC OS style path, convert it to a Unix style path + // TODO: Disable UnixLib's automatic path conversion and use RISC OS style paths internally? + if (temp_line.find('$',0) != std::string::npos) { + char fname[PATH_MAX]; + is_physfs = false; + __unixify_std(temp_line.c_str(), fname, sizeof(fname), 0); + temp_line = fname; + } + #endif + + #if defined (WIN32) || defined(OS2) + // Windows: Workaround for LaunchBox + if (is_physfs && temp_line.size()>4 && temp_line[0]=='\'' && toupper(temp_line[1])>='A' && toupper(temp_line[1])<='Z' && temp_line[2]==':' && (temp_line[3]=='/' || temp_line[3]=='\\') && temp_line.back()=='\'') { + temp_line = temp_line.substr(1, temp_line.size()-2); + is_physfs = temp_line.find(':',((temp_line[0]|0x20) >= 'a' && (temp_line[0]|0x20) <= 'z')?2:0) != std::string::npos; + } else if (is_physfs && temp_line.size()>3 && temp_line[0]=='\'' && toupper(temp_line[1])>='A' && toupper(temp_line[1])<='Z' && temp_line[2]==':' && (temp_line[3]=='/' || temp_line[3]=='\\')) { + std::string line=trim((char *)cmd->GetRawCmdline().c_str()); + std::size_t space=line.find(' '); + if (space!=std::string::npos) { + line=trim((char *)line.substr(space).c_str()); + std::size_t found=line.back()=='\''?line.find_last_of('\''):line.rfind("' "); + if (found!=std::string::npos&&found>2) { + temp_line=line.substr(1, found-1); + is_physfs = temp_line.find(':',((temp_line[0]|0x20) >= 'a' && (temp_line[0]|0x20) <= 'z')?2:0) != std::string::npos; + } + } + } + #else + // Linux: Convert backslash to forward slash + if (!is_physfs && temp_line.size() > 0) { + for (size_t i=0;i < temp_line.size();i++) { + if (temp_line[i] == '\\') + temp_line[i] = '/'; + } + } + #endif + + bool useh = false; + #if defined (WIN32) + ht_stat_t htest; + #else + struct stat htest; + #endif + #if defined (WIN32) || defined(OS2) + /* Removing trailing backslash if not root dir so stat will succeed */ + if(temp_line.size() > 3 && temp_line[temp_line.size()-1]=='\\') temp_line.erase(temp_line.size()-1,1); + if(temp_line.size() == 2 && toupper(temp_line[0])>='A' && toupper(temp_line[0])<='Z' && temp_line[1]==':') temp_line.append("\\"); + if(temp_line.size() > 4 && temp_line[0] == '\\' && temp_line[1] == '\\' && temp_line[2] != '\\' && std::count(temp_line.begin() + 3, temp_line.end(), '\\') == 1) temp_line.append("\\"); + notrycp = true; + const host_cnv_char_t* host_name = CodePageGuestToHost(temp_line.c_str()); + notrycp = false; + if (!is_physfs && stat(temp_line.c_str(),&test)) { + #endif + #if defined(WIN32) + if (host_name == NULL || ht_stat(host_name, &htest)) failed = true; + useh = true; + } else if (!is_physfs && tryconvertcp && _waccess(host_name,0) && dos.loaded_codepage == 437) { + uint16_t cp = GetACP(), cpbak = dos.loaded_codepage; + #if defined(USE_TTF) + if ((ttf.inUse&&(cp<1250||cp>1259)&&cp!=437&&isSupportedCP(cp))||(!ttf.inUse&&(cp==932||cp==936||cp==949||cp==950||cp==951))) + #else + if (cp==932||cp==936||cp==949||cp==950||cp==951) + #endif + { + cpbak = dos.loaded_codepage; + dos.loaded_codepage = cp; + host_name = CodePageGuestToHost(temp_line.c_str()); + char str[150]; + + sprintf(str, "Drive %c: may require code page %d to be properly accessed.\n\nDo you want to change the current code page to %d now?\n", drive, cp, cp); + if (!host_name || ht_stat(host_name, &htest) || _waccess(host_name,0) || !systemmessagebox("Changing code page",str,"yesno","question",1)) + dos.loaded_codepage = cpbak; + #if defined(USE_TTF) + else if (ttf.inUse) { + dos.loaded_codepage = cpbak; + toSetCodePage(NULL, cp, -1); + } + #endif + else { + MSG_Init(); + DOSBox_SetSysMenu(); + if (isDBCSCP()) { + ShutFontHandle(); + InitFontHandle(); + JFONT_Init(); + } + SetupDBCSTable(); + runRescan("-A -Q"); + #if C_OPENGL && DOSBOXMENU_TYPE == DOSBOXMENU_SDLDRAW + if (OpenGL_using() && control->opt_lang.size() && lastcp && lastcp != dos.loaded_codepage) + UpdateSDLDrawTexture(); + #endif + } + SwitchLanguage(cpbak, cp, false); + } + } + #elif defined (OS2) + if (temp_line.size() <= 2) // Seems to be a drive. + { + failed = true; + HFILE cdrom_fd = 0; + ULONG ulAction = 0; + + APIRET rc = DosOpen((unsigned char*)temp_line.c_str(), &cdrom_fd, &ulAction, 0L, FILE_NORMAL, OPEN_ACTION_OPEN_IF_EXISTS, + OPEN_FLAGS_DASD | OPEN_SHARE_DENYNONE | OPEN_ACCESS_READONLY, 0L); + DosClose(cdrom_fd); + if (rc != NO_ERROR && rc != ERROR_NOT_READY) + { + failed = true; + } else { + failed = false; + } + } + } + #else + if (!is_physfs && stat(temp_line.c_str(),&test)) { + failed = true; + Cross::ResolveHomedir(temp_line); + //Try again after resolving ~ + if(!stat(temp_line.c_str(),&test)) failed = false; + } + #endif + if(failed) { + if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_ERROR_1"),temp_line.c_str()); + return; + } + /* Not a switch so a normal directory/file */ + if (!is_physfs && !S_ISDIR(useh?htest.st_mode:test.st_mode)) { + #ifdef OS2 + HFILE cdrom_fd = 0; + ULONG ulAction = 0; + + APIRET rc = DosOpen((unsigned char*)temp_line.c_str(), &cdrom_fd, &ulAction, 0L, FILE_NORMAL, OPEN_ACTION_OPEN_IF_EXISTS, + OPEN_FLAGS_DASD | OPEN_SHARE_DENYNONE | OPEN_ACCESS_READONLY, 0L); + DosClose(cdrom_fd); + if (rc != NO_ERROR && rc != ERROR_NOT_READY) + #endif + { + is_physfs = true; + temp_line.insert(0, 1, ':'); + /*if (!quiet) { + WriteOut(MSG_Get("PROGRAM_MOUNT_ERROR_2"),temp_line.c_str()); + if (temp_line.length()>4) { + char ext[5]; + strncpy(ext, temp_line.substr(temp_line.length()-4).c_str(), 4); + ext[4]=0; + if (!strcasecmp(ext, ".iso")||!strcasecmp(ext, ".cue")||!strcasecmp(ext, ".bin")||!strcasecmp(ext, ".chd")||!strcasecmp(ext, ".mdf")||!strcasecmp(ext, ".ima")||!strcasecmp(ext, ".img")||!strcasecmp(ext, ".vhd")||!strcasecmp(ext, ".hdi")) + WriteOut(MSG_Get("PROGRAM_MOUNT_IMGMOUNT"),temp_line.c_str()); + } + } + return;*/ + } + } + + if (temp_line[temp_line.size()-1]!=CROSS_FILESPLIT) temp_line+=CROSS_FILESPLIT; + uint8_t bit8size=(uint8_t) sizes[1]; + exist = drive - 'A' < DOS_DRIVES && drive - 'A' >= 0 && Drives[drive - 'A']; + if (type=="cdrom") { + int num = -1; + cmd->FindInt("-usecd",num,true); + int error = 0; + if (cmd->FindExist("-aspi",false)) { + MSCDEX_SetCDInterface(CDROM_USE_ASPI, num); + } else if (cmd->FindExist("-ioctl_dio",false)) { + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); + } else if (cmd->FindExist("-ioctl_dx",false)) { + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); + #if defined (WIN32) + } else if (cmd->FindExist("-ioctl_mci",false)) { + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_MCI, num); + #endif + } else if (cmd->FindExist("-noioctl",false)) { + MSCDEX_SetCDInterface(CDROM_USE_SDL, num); + } else { + #if defined (WIN32) + int id, major, minor; + DOSBox_CheckOS(id, major, minor); + if ((id==VER_PLATFORM_WIN32_NT) && (major>5)) { + // Vista/above + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DX, num); + } else { + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); + } + #else + MSCDEX_SetCDInterface(CDROM_USE_IOCTL_DIO, num); + #endif + } + if (is_physfs) + newdrive = new physfscdromDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],0,mediaid,error,options); + else + newdrive = new cdromDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,error,options); + // Check Mscdex, if it worked out... + if(!quiet) + switch(error) { + case 0: WriteOut(MSG_Get("MSCDEX_SUCCESS")); break; + case 1: WriteOut(MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS")); break; + case 2: WriteOut(MSG_Get("MSCDEX_ERROR_NOT_SUPPORTED")); break; + case 3: WriteOut(MSG_Get("MSCDEX_ERROR_PATH")); break; + case 4: WriteOut(MSG_Get("MSCDEX_TOO_MANY_DRIVES")); break; + case 5: WriteOut(MSG_Get("MSCDEX_LIMITED_SUPPORT")); break; + case 10: WriteOut(MSG_Get("PROGRAM_MOUNT_PHYSFS_ERROR")); WriteOut(MSG_Get("PROGRAM_MOUNT_IMGMOUNT")); break; + default: WriteOut(MSG_Get("MSCDEX_UNKNOWN_ERROR")); break; + } + if (error && error!=5) { + delete newdrive; + return; + } + } else { + /* Give a warning when mount c:\ or the / */ + if (mountwarning && !quiet && !nowarn) { + #if defined (WIN32) || defined(OS2) + if( (temp_line == "c:\\") || (temp_line == "C:\\") || + (temp_line == "c:/") || (temp_line == "C:/") ) + WriteOut(MSG_Get("PROGRAM_MOUNT_WARNING_WIN")); + #else + if(temp_line == "/") WriteOut(MSG_Get("PROGRAM_MOUNT_WARNING_OTHER")); + #endif + } + if (is_physfs) { + int error = 0; + newdrive=new physfsDrive(drive,temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,error,options); + if (error) { + if (!quiet) {WriteOut(MSG_Get("PROGRAM_MOUNT_PHYSFS_ERROR"));WriteOut(MSG_Get("PROGRAM_MOUNT_IMGMOUNT"));} + delete newdrive; + return; + } + } else if(type == "overlay") { + physfsDrive* pdp = dynamic_cast(Drives[drive-'A']); + physfscdromDrive* pcdp = dynamic_cast(Drives[drive-'A']); + if (pdp && !pcdp) { + if (pdp->setOverlaydir(temp_line.c_str())) + WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_STATUS"),(temp_line+(temp_line.size()&&temp_line.back()!=CROSS_FILESPLIT?std::string(1, CROSS_FILESPLIT):"")+std::string(1, drive)+"_DRIVE").c_str(),drive); + else + WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_ERROR")); + return; + } + localDrive* ldp = dynamic_cast(Drives[drive-'A']); + cdromDrive* cdp = dynamic_cast(Drives[drive-'A']); + if(!ldp || cdp || pcdp) { + if(!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_INCOMPAT_BASE")); + return; + } + std::string base = ldp->getBasedir(); + uint8_t o_error = 0; + newdrive = new Overlay_Drive(base.c_str(),temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,o_error,options); + //Erase old drive on success + if (newdrive) { + if (o_error) { + if (quiet) {delete newdrive;return;} + if (o_error == 1) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_MIXED_BASE")); + else if (o_error == 2) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_SAME_AS_BASE")); + else WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_ERROR")); + delete newdrive; + return; + } else { + Overlay_Drive* odrive=dynamic_cast(newdrive); + if (odrive!=NULL) { + odrive->ovlnocachedir = nocachedir; + odrive->ovlreadonly = readonly; + } + } + + //Copy current directory if not marked as deleted. + if (newdrive->TestDir(ldp->curdir)) { + strcpy(newdrive->curdir,ldp->curdir); + } + + if (Drives[drive-'A'] != NULL) { + if (dynamic_cast(Drives[drive-'A']) != NULL) { /* Yeah, this relies on RTTI but it's probably worth it */ + /* Let the user know in case experience with other OSes or emulators leads them to think + * that they can "stack" overlays by mounting multiple times. */ + WriteOut("Existing overlay has been replaced with new overlay.\n"); + } + delete Drives[drive-'A']; + Drives[drive-'A'] = nullptr; + } + } else { + if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_ERROR")); + return; + } + } else { + newdrive=new localDrive(temp_line.c_str(),sizes[0],bit8size,sizes[2],sizes[3],mediaid,options); + newdrive->nocachedir = nocachedir; + newdrive->readonly = readonly; + } + } + } else { + if (!quiet) WriteOut(MSG_Get("PROGRAM_MOUNT_ILL_TYPE"),type.c_str()); + return; + } + if (!newdrive) E_Exit("DOS:Can't create drive"); + Drives[drive-'A']=newdrive; + if (removed && !exist) DOS_SetDefaultDrive(drive-'A'); + DOS_EnableDriveMenu(drive); + /* Set the correct media byte in the table */ + mem_writeb(Real2Phys(dos.tables.mediaid)+((unsigned int)drive-'A')*dos.tables.dpb_size,newdrive->GetMediaByte()); + lastmount = drive; + if (!quiet) { + if (type != "overlay") WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"),drive,newdrive->GetInfo()); + else WriteOut(MSG_Get("PROGRAM_MOUNT_OVERLAY_STATUS"),temp_line.c_str(),drive); + } + /* check if volume label is given and don't allow it to updated in the future */ + if (cmd->FindString("-label",label,true)) newdrive->SetLabel(label.c_str(),iscdrom,false); + /* For hard drives set the label to DRIVELETTER_Drive. + * For floppy drives set the label to DRIVELETTER_Floppy. + * This way every drive except cdroms should get a label.*/ + else if(type == "dir" || type == "overlay") { + #if defined (WIN32) || defined(OS2) + if(temp_line.size()==3 && toupper(drive) == toupper(temp_line[0])) { + // automatic mount + } else { + label = drive; label += "_DRIVE"; + newdrive->SetLabel(label.c_str(),iscdrom,false); + } + #endif + } else if(type == "floppy") { + #if defined (WIN32) || defined(OS2) + if(temp_line.size()==3 && toupper(drive) == toupper(temp_line[0])) { + // automatic mount + } else { + label = drive; label += "_FLOPPY"; + newdrive->SetLabel(label.c_str(),iscdrom,true); + } + #endif + } + if(type == "floppy") incrementFDD(); + return; + showusage: + resetcolor = true; + WriteOut(MSG_Get("PROGRAM_MOUNT_USAGE")); + return; + } + }; + + static void MOUNT_ProgramStart(Program * * make) { + *make=new MOUNT; + } + + void runMount(const char *str) { + MOUNT mount; + mount.cmd=new CommandLine("MOUNT", str); + mount.Run(); + } + + void GUI_Run(bool pressed); + + class CFGTOOL : public Program { + public: + void Run(void) override { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Starts DOSBox-X's graphical configuration tool.\n\nCFGTOOL\n\nNote: You can also use CONFIG command for command-line configurations.\n"); + return; + } + GUI_Run(false); /* So that I don't have to run the keymapper on every setup of mine just to get the GUI --J.C */ + } + }; + + static void CFGTOOL_ProgramStart(Program * * make) { + *make=new CFGTOOL; + } + + extern bool custom_bios; + extern size_t custom_bios_image_size; + extern Bitu custom_bios_image_offset; + extern unsigned char *custom_bios_image; + extern uint32_t floppytype; + extern bool boot_debug_break; + extern Bitu BIOS_bootfail_code_offset; + + void DisableINT33(); + void EMS_DoShutDown(); + void XMS_DoShutDown(); + void DOS_DoShutDown(); + void GUS_DOS_Shutdown(); + void SBLASTER_DOS_Shutdown(); + + unsigned char PC98_ITF_ROM[0x8000]; + bool PC98_ITF_ROM_init = false; + unsigned char PC98_BANK_Select = 0x12; + + class PC98ITFPageHandler : public PageHandler { + public: + PC98ITFPageHandler() : PageHandler(PFLAG_READABLE|PFLAG_HASROM) {} + PC98ITFPageHandler(Bitu flags) : PageHandler(flags) {} + HostPt GetHostReadPt(PageNum phys_page) override { + return PC98_ITF_ROM+(phys_page&0x7)*MEM_PAGESIZE; + } + HostPt GetHostWritePt(PageNum phys_page) override { + return PC98_ITF_ROM+(phys_page&0x7)*MEM_PAGESIZE; + } + void writeb(PhysPt addr,uint8_t val) override { + LOG(LOG_CPU,LOG_ERROR)("Write %x to rom at %x",(int)val,(int)addr); + } + void writew(PhysPt addr,uint16_t val) override { + LOG(LOG_CPU,LOG_ERROR)("Write %x to rom at %x",(int)val,(int)addr); + } + void writed(PhysPt addr,uint32_t val) override { + LOG(LOG_CPU,LOG_ERROR)("Write %x to rom at %x",(int)val,(int)addr); + } + }; + + PC98ITFPageHandler mem_itf_rom; + + bool FDC_AssignINT13Disk(unsigned char drv); + void MEM_RegisterHandler(Bitu phys_page,PageHandler * handler,Bitu page_range); + void MEM_ResetPageHandler_Unmapped(Bitu phys_page, Bitu pages); + bool MEM_map_ROM_physmem(Bitu start,Bitu end); + PageHandler &Get_ROM_page_handler(void); + + // Normal BIOS is in the BIOS memory area + // ITF is in its own buffer, served by mem_itf_rom + void PC98_BIOS_Bank_Switch(void) { + if (PC98_BANK_Select == 0x00) { + MEM_RegisterHandler(0xF8,&mem_itf_rom,0x8); + } + else { + MEM_RegisterHandler(0xF8,&Get_ROM_page_handler(),0x8); + } + + PAGING_ClearTLB(); + } + + // BIOS behavior suggests a reset signal puts the BIOS back + void PC98_BIOS_Bank_Switch_Reset(void) { + LOG_MSG("PC-98 43Dh mapping BIOS back into top of RAM"); + PC98_BANK_Select = 0x12; + PC98_BIOS_Bank_Switch(); + #if 0 + Bitu DEBUG_EnableDebugger(void); + DEBUG_EnableDebugger(); + #endif + } + + void pc98_43d_write(Bitu port,Bitu val,Bitu iolen) { + (void)port; + (void)iolen; + + LOG_MSG("PC-98 43Dh BIOS bank switching write: 0x%02x",(unsigned int)val); + + switch (val) { + case 0x00: // ITF + case 0x10: + case 0x18: + PC98_BANK_Select = 0x00; + PC98_BIOS_Bank_Switch(); + break; + case 0x12: // BIOS + PC98_BANK_Select = 0x12; + PC98_BIOS_Bank_Switch(); + break; + default: + LOG_MSG("PC-98 43Dh BIOS bank switching write: 0x%02x unknown value",(unsigned int)val); + break; + } + } + + int IDE_MatchCDROMDrive(char drv); + + #if defined(WIN32) + #include + #else + #if defined(MACOSX) + #define _DARWIN_C_SOURCE + #endif + #include + #endif + FILE *retfile = NULL; + FILE * fopen_lock(const char * fname, const char * mode, bool &readonly) { + std::string fmode = mode; + if (lockmount && fmode.size()>1 && fmode.back()=='+') { + #if defined(WIN32) + HANDLE hFile = CreateFile(fname, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) { + const host_cnv_char_t* host_name = CodePageGuestToHost(fname); + if (host_name != NULL) hFile = CreateFileW(host_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + } + if (hFile == INVALID_HANDLE_VALUE) {fmode.pop_back();readonly=true;goto next;} + int nHandle = _open_osfhandle((intptr_t)hFile, _O_RDONLY); + if (nHandle == -1) {CloseHandle(hFile);return NULL;} + retfile = _fdopen(nHandle, fmode.c_str()); + if(!retfile) {CloseHandle(hFile);return NULL;} + LockFile(hFile, 0, 0, 0xFFFFFFFF, 0xFFFFFFFF); + #else + retfile = fopen64(fname, fmode.c_str()); + if (retfile == NULL) {fmode.pop_back();readonly=true;goto next;} /* did you know fopen returns NULL if it cannot open the file? */ + int lock = flock(fileno(retfile), LOCK_EX | LOCK_NB); /* did you know fileno() assumes retfile != NULL and you will segfault if that is wrong? */ + if (lock < 0) { + fclose(retfile); /* don't leak file handles on failure to flock() */ + return NULL; + } + #endif + } else { + next: + retfile = fopen64(fname, fmode.c_str()); + #if defined(WIN32) + if (retfile == NULL) { + const host_cnv_char_t* host_name = CodePageGuestToHost(fname); + if (host_name != NULL) { + const size_t size = fmode.size()+1; + wchar_t* wmode = new wchar_t[size]; + mbstowcs (wmode, fmode.c_str(), size); + retfile = _wfopen(host_name, wmode); + } + } + #endif + } + return retfile; + } + + /*! \brief BOOT.COM utility to boot a floppy or hard disk device. + * + * \description Users will use this command to boot a guest operating system from + * a disk image. Options are provided to specify the device to boot + * from (if the image is already assigned) or a floppy disk image + * specified on the command line. + */ + class BOOT : public Program { + public: + BOOT() { + for (size_t i=0;i < MAX_SWAPPABLE_DISKS;i++) newDiskSwap[i] = NULL; + } + virtual ~BOOT() { + for (size_t i=0;i < MAX_SWAPPABLE_DISKS;i++) { + if (newDiskSwap[i] != NULL) { + newDiskSwap[i]->Release(); + newDiskSwap[i] = NULL; + } + } + } + /*! \brief Array of disk images to add to floppy swaplist + */ + imageDisk* newDiskSwap[MAX_SWAPPABLE_DISKS] = {}; + + private: + + /*! \brief Open a file as a disk image and return FILE* handle and size + */ + FILE *getFSFile_mounted(char const* filename, uint32_t *ksize, uint32_t *bsize, uint8_t *error) { + //if return NULL then put in error the errormessage code if an error was requested + bool tryload = (*error)?true:false; + *error = 0; + uint8_t drive; + char fullname[DOS_PATHLENGTH]; + + localDrive* ldp=nullptr; + bool readonly=wpcolon&&strlen(filename)>1&&filename[0]==':'; + if (!DOS_MakeName(readonly?filename+1:filename,fullname,&drive)) return NULL; + + try { + ldp=dynamic_cast(Drives[drive]); + if(!ldp) return NULL; + + FILE *tmpfile = ldp->GetSystemFilePtr(fullname, "rb"); + if(tmpfile == NULL) { + if (!tryload) *error=1; + return NULL; + } + + // get file size + fseek(tmpfile,0L, SEEK_END); + *ksize = uint32_t(ftell(tmpfile) / 1024); + *bsize = uint32_t(ftell(tmpfile)); + fclose(tmpfile); + + if (!readonly) + tmpfile = ldp->GetSystemFilePtr(fullname, "rb+"); + if(readonly || tmpfile == NULL) { + // if (!tryload) *error=2; + // return NULL; + WriteOut(MSG_Get("PROGRAM_BOOT_WRITE_PROTECTED")); + tmpfile = ldp->GetSystemFilePtr(fullname, "rb"); + if(tmpfile == NULL) { + if (!tryload) *error=1; + return NULL; + } + } + + return tmpfile; + } + catch(...) { + return NULL; + } + } + + /*! \brief Open a file as a disk image and return FILE* handle and size + */ + FILE *getFSFile(char const * filename, uint32_t *ksize, uint32_t *bsize,bool tryload=false) { + uint8_t error = tryload?1:0; + FILE* tmpfile = getFSFile_mounted(filename,ksize,bsize,&error); + if(tmpfile) return tmpfile; + //File not found on mounted filesystem. Try regular filesystem + std::string filename_s(filename); + Cross::ResolveHomedir(filename_s); + bool readonly=wpcolon&&filename_s.length()>1&&filename_s[0]==':'; + if (!readonly) + tmpfile = fopen_lock(filename_s.c_str(),"rb+",readonly); + if(readonly || !tmpfile) { + if( (tmpfile = fopen(readonly?filename_s.c_str()+1:filename_s.c_str(),"rb")) ) { + //File exists; So can't be opened in correct mode => error 2 + // fclose(tmpfile); + // if(tryload) error = 2; + WriteOut(MSG_Get("PROGRAM_BOOT_WRITE_PROTECTED")); + fseek(tmpfile,0L, SEEK_END); + *ksize = uint32_t(ftell(tmpfile) / 1024); + *bsize = uint32_t(ftell(tmpfile)); + return tmpfile; + } + // Give the delayed errormessages from the mounted variant (or from above) + if(error == 1) WriteOut(MSG_Get("PROGRAM_BOOT_NOT_EXIST")); + if(error == 2) WriteOut(MSG_Get("PROGRAM_BOOT_NOT_OPEN")); + return NULL; + } + fseek(tmpfile,0L, SEEK_END); + *ksize = uint32_t(ftell(tmpfile) / 1024); + *bsize = uint32_t(ftell(tmpfile)); + return tmpfile; + } + + /*! \brief Utility function to print generic boot error + */ + void printError(void) { + resetcolor = true; + WriteOut(MSG_Get("PROGRAM_BOOT_PRINT_ERROR")); + } + + public: + + /*! \brief Program entry point, when the command is run + */ + void Run(void) override { + std::string tmp; + std::string bios; + std::string boothax_str; + std::string el_torito_mode="noemu"; + std::string el_torito; + bool pc98_640x200 = true; + bool pc98_show_graphics = false; + bool bios_boot = false; + bool swaponedrive = false; + bool convertro = false; + bool force = false; + int loadseg_user = -1; + int convimg = -1; + int quiet = 0; + + //Hack To allow long commandlines + ChangeToLongCmd(); + + boot_debug_break = false; + if (cmd->FindExist("-debug",true)) + boot_debug_break = true; + + if (cmd->FindExist("-swap-one-drive",true)) + swaponedrive = true; + + //look for -el-torito parameter and remove it from the command line. + //This is copy-pasta to be consistent with the IMGMOUNT command which accepts this as either -el-torito or -bootcd. + //But with one important difference: Unlike IMGMOUNT which only supports bootable floppy emulation, this version lets + //you specify any other mode, though at this time, only "no emulation" mode is supported. You specify it as a =suffix + //i.e. -el-torito d:=noemu. No emulation mode is default, the IMGMOUNT --el-torito is still recommended for booting + //floppy emulation at this time. + cmd->FindString("-el-torito",el_torito,true); + if(el_torito == "") cmd->FindString("-bootcd", el_torito, true); + + if (!el_torito.empty()) { + size_t o = el_torito.find_last_of('='); + if (o != std::string::npos && (o+1) < el_torito.length()) { + el_torito_mode = el_torito.substr(o+1); + el_torito = el_torito.substr(0,o); + } + } + + // debugging options + if (cmd->FindExist("-pc98-640x200",true)) + pc98_640x200 = true; + if (cmd->FindExist("-pc98-640x400",true)) + pc98_640x200 = false; + if (cmd->FindExist("-pc98-graphics",true)) + pc98_show_graphics = true; + + if (cmd->FindExist("-q",true)) + quiet = 1; + if (cmd->FindExist("-qq",true)) + quiet = 2; + + if (cmd->FindExist("-force",true)) + force = true; + + if (cmd->FindExist("-convertfatro",true)) { + convimg = 1; + convertro = true; + } + + if (cmd->FindExist("-convertfat",true)) + convimg = 1; + + if (cmd->FindExist("-noconvertfat",true)) + convimg = 0; + + if (cmd->FindString("-bios",bios,true)) + bios_boot = true; + + cmd->FindString("-load-seg",tmp,true); + if (!tmp.empty()) + loadseg_user = strtoul(tmp.c_str(),NULL,0); + + cmd->FindString("-boothax",boothax_str,true); + + if (boothax_str == "msdos") // WARNING: For MS-DOS only, including MS-DOS 7/8 included in Windows 95/98/ME. + boothax = BOOTHAX_MSDOS; // do NOT use while in the graphical interface of Windows 95/98/ME especially a DOS VM. + else if (boothax_str == "") + boothax = BOOTHAX_NONE; + else { + if (!quiet) WriteOut("Unknown boothax mode"); + return; + } + + /* In secure mode don't allow people to boot stuff. + * They might try to corrupt the data on it */ + if(control->SecureMode()) { + if (!quiet) WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); + return; + } + + if (bios_boot) { + uint32_t isz1,isz2; + + if (bios.empty()) { + if (!quiet) WriteOut("Must specify BIOS image to boot\n"); + return; + } + + // NOTES: + // + // Regarding PC-98 mode, you should use an older BIOS image. + // The PC-9821 ROM image(s) I have appear to rely on bank + // switching parts of itself to boot up and operate. + // + // Update: I found some PC-9801 ROM BIOS images online, which + // ALSO seem to have a BIOS.ROM, ITF.ROM, etc... + // + // So, this command will not be able to run those + // images until port 43Dh (the I/O port used for + // bank switching) is implemented in DOSBox-X. + // + // In IBM PC/AT mode, this should hopefully allow using old + // 386/486 BIOSes in DOSBox-X. + + /* load it */ + FILE *romfp = getFSFile(bios.c_str(), &isz1, &isz2); + if (romfp == NULL) { + if (!quiet) WriteOut("Unable to open BIOS image\n"); + return; + } + Bitu loadsz = (isz2 + 0xFU) & (~0xFU); + if (loadsz == 0) loadsz = 0x10; + if (loadsz > (IS_PC98_ARCH ? 0x18000u : 0x20000u)) loadsz = (IS_PC98_ARCH ? 0x18000u : 0x20000u); + Bitu segbase = 0x100000 - loadsz; + LOG_MSG("Loading BIOS image %s to 0x%lx, 0x%lx bytes",bios.c_str(),(unsigned long)segbase,(unsigned long)loadsz); + fseek(romfp, 0, SEEK_SET); + + // To avoid crashes should any interrupt be called on the way to running the BIOS, + // don't actually map it in until it's good and ready to go. + if (custom_bios_image != NULL) delete[] custom_bios_image; + custom_bios_image_size = loadsz; + custom_bios_image_offset = segbase; + custom_bios_image = new unsigned char[custom_bios_image_size]; + + size_t readResult = fread(custom_bios_image,loadsz,1,romfp); + fclose(romfp); + if (readResult != 1) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); + return; + } + + if (IS_PC98_ARCH) { + // The PC-98 BIOS has a bank switching system where at least the last 32KB + // can be switched to an Initial Firmware Test BIOS, which initializes the + // system then switches back to the full 96KB visible during runtime. + // + // We can emulate the same if a file named ITF.ROM exists in the same directory + // as the BIOS image we were given. + // + // To enable multiple ITFs per ROM image, we first try .itf.rom + // before trying itf.rom, for the user's convenience. + FILE *itffp; + + itffp = getFSFile((bios + ".itf.rom").c_str(), &isz1, &isz2); + if (itffp == NULL) itffp = getFSFile((bios + ".ITF.ROM").c_str(), &isz1, &isz2); + if (itffp == NULL) itffp = getFSFile("itf.rom", &isz1, &isz2); + if (itffp == NULL) itffp = getFSFile("ITF.ROM", &isz1, &isz2); + + if (itffp != NULL && isz2 <= 0x8000ul) { + LOG_MSG("Found ITF (initial firmware test) BIOS image (0x%lx bytes)",(unsigned long)isz2); + + memset(PC98_ITF_ROM,0xFF,sizeof(PC98_ITF_ROM)); + readResult = fread(PC98_ITF_ROM,isz2,1,itffp); + fclose(itffp); + if (readResult != 1) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); + return; + } + PC98_ITF_ROM_init = true; + } + + IO_RegisterWriteHandler(0x43D,pc98_43d_write,IO_MB); + } + + custom_bios = true; + + /* boot it */ + throw int(8); + } + + bool bootbyDrive=false; + FILE *usefile_1=NULL; + FILE *usefile_2=NULL; + Bitu i=0; + uint32_t floppysize=0; + uint32_t rombytesize_1=0; + uint32_t rombytesize_2=0; + uint8_t drive = 'A'; + std::string cart_cmd=""; + Bitu max_seg; + + /* IBM PC: + * CS:IP = 0000:7C00 Load = 07C0:0000 + * SS:SP = ??? + * + * PC-98: + * CS:IP = 1FC0:0000 Load = 1FC0:0000 + * SS:SP = 0030:00D8 + * + * Reportedly PC-98 will load to 1FE0:0000 when booting the 1.44MB format (512 bytes per sector). + * Note that 0x1FC0:0000 leaves enough room for the 1024 bytes per sector format of PC-98. + */ + Bitu stack_seg=IS_PC98_ARCH ? 0x0030 : 0x7000; + Bitu load_seg;//=IS_PC98_ARCH ? 0x1FC0 : 0x07C0; + + if (MEM_TotalPages() > 0x9C) + max_seg = 0x9C00; + else + max_seg = MEM_TotalPages() << (12 - 4); + + if ((stack_seg+0x20) > max_seg) + stack_seg = max_seg - 0x20; + + /* if booting El Torito, the drive specified must be a CD-ROM drive */ + if (!el_torito.empty()) { + //get el-torito floppy from cdrom mounted at drive letter el_torito_cd_drive + char el_torito_cd_drive = toupper(el_torito[0]); + if (el_torito_cd_drive < 'A' || el_torito_cd_drive > 'Z') { + printError(); + return; + } + + if (IS_PC98_ARCH) { + /* PC-98 doesn't have a bootable CD-ROM specification... does it? + * By the time that became common the NEC basically switched to + * making IBM PC-AT compatible Windows 95 systems anyway. */ + printError(); + return; + } + + drive = 0; + if (!cmd->GetCount()) { + drive = 'A' + (dos_kernel_disabled?26:DOS_GetDefaultDrive()); + } + else if (cmd->GetCount() == 1) { + cmd->FindCommand(1, temp_line); + if (temp_line.length()==2&&toupper(temp_line[0])>='A'&&toupper(temp_line[0])<='Z'&&temp_line[1]==':') { + drive = toupper(temp_line[0]); } - case KEYB_FILENOTFOUND: - if (temp_line!="/?"&&temp_line!="-?") WriteOut(MSG_Get("PROGRAM_KEYB_FILENOTFOUND"),layout_id); - WriteOut(MSG_Get("PROGRAM_KEYB_SHOWHELP")); - break; - case KEYB_INVALIDFILE: - WriteOut(MSG_Get("PROGRAM_KEYB_INVALIDFILE"),layout_id); - break; - case KEYB_LAYOUTNOTFOUND: - WriteOut(MSG_Get("PROGRAM_KEYB_LAYOUTNOTFOUND"),layout_id, cp ? cp : tocp); - break; - case KEYB_INVALIDCPFILE: - WriteOut(MSG_Get("PROGRAM_KEYB_INVCPFILE"),layout_id); - WriteOut(MSG_Get("PROGRAM_KEYB_SHOWHELP")); - break; - default: - LOG(LOG_DOSMISC,LOG_ERROR)("KEYB:Invalid returncode %x",(int)keyb_error); - break; - } - } - } else { - /* no parameter in the command line, just output codepage info and possibly loaded layout ID */ - const char* layout_name = DOS_GetLoadedLayout(); - if (layout_name==NULL) { - WriteOut(MSG_Get("PROGRAM_KEYB_INFO"),dos.loaded_codepage); - } else { - WriteOut(MSG_Get("PROGRAM_KEYB_INFO_LAYOUT"),dos.loaded_codepage,layout_name); - } - } -} - -static void KEYB_ProgramStart(Program * * make) { - *make=new KEYB; -} - -// MODE - -class MODE : public Program { -public: - void Run(void) override; -private: - void PrintStatus() { - WriteOut("Status for device CON:\n----------------------\nColumns=%d\nLines=%d\n", COLS, LINES); -#if defined(USE_TTF) - if(!ttf.inUse) -#endif - WriteOut("\nCode page operation not supported on this device\n"); - } - int LINES = 25, COLS = 80; -}; - -bool setlines(const char *mname); -void MODE::Run(void) { - uint16_t rate=0,delay=0,cols=0,lines=0,mode; - LINES=(IS_EGAVGA_ARCH?real_readb(BIOSMEM_SEG,BIOSMEM_NB_ROWS):24)+1; - COLS=real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - if (!cmd->FindCommand(1,temp_line)) { - PrintStatus(); - return; - } - if (temp_line=="-?" || temp_line=="/?") { - WriteOut(MSG_Get("PROGRAM_MODE_USAGE")); - return; - } - else if (strcasecmp(temp_line.c_str(),"con")==0 || strcasecmp(temp_line.c_str(),"con:")==0) { - if (IS_PC98_ARCH) return; - if (cmd->GetCount()<2) { - PrintStatus(); - return; - } - if (cmd->FindStringBegin("rate=", temp_line,false)) rate=atoi(temp_line.c_str()); - if (cmd->FindStringBegin("delay=", temp_line,false)) delay=atoi(temp_line.c_str()); - if (cmd->FindStringBegin("cols=", temp_line,false)) cols=atoi(temp_line.c_str()); else cols=COLS; - if (cmd->FindStringBegin("lines=",temp_line,false)) lines=atoi(temp_line.c_str()); else lines=LINES; - bool optr=cmd->FindStringBegin("rate=", temp_line,true), optd=cmd->FindStringBegin("delay=",temp_line,true), optc=cmd->FindStringBegin("cols=", temp_line,true), optl=cmd->FindStringBegin("lines=",temp_line,true); - if ((optr&&!optd)||(optd&&!optr)) { - WriteOut("Rate and delay must be specified together\n"); - return; - } - if (cmd->GetCount()>1) goto modeparam; - if (optr&&optd) { - if (rate<1 || rate>32 || delay<1 || delay>4) goto modeparam; - IO_Write(0x60,0xf3); IO_Write(0x60,(uint8_t)(((delay-1)<<5)|(32-rate))); - } - if ((optc||optl)&&(cols!=COLS||lines!=LINES)) { - std::string cmd="line_"+std::to_string((int)cols)+"x"+std::to_string((int)lines); - if (!setlines(cmd.c_str())) goto modeparam; - } - return; - } - else if (cmd->GetCount()>1) goto modeparam; - else if (strcasecmp(temp_line.c_str(),"mono")==0) mode=7; - else if (machine==MCH_HERC || machine==MCH_MDA) goto modeparam; - else if (strcasecmp(temp_line.c_str(),"co80")==0) mode=3; - else if (strcasecmp(temp_line.c_str(),"bw80")==0) mode=2; - else if (strcasecmp(temp_line.c_str(),"co40")==0) mode=1; - else if (strcasecmp(temp_line.c_str(),"bw40")==0) mode=0; - else goto modeparam; - mem_writeb(BIOS_CONFIGURATION,(mem_readb(BIOS_CONFIGURATION)&0xcf)|((mode==7)?0x30:0x20)); - reg_ax=mode; - CALLBACK_RunRealInt(0x10); - return; -modeparam: - WriteOut(MSG_Get("PROGRAM_MODE_INVALID_PARAMETERS")); - return; -} - -static void MODE_ProgramStart(Program * * make) { - *make=new MODE; -} -/* -// MORE -class MORE : public Program { -public: - void Run(void); -}; - -void MORE::Run(void) { - if (cmd->GetCount()) { - WriteOut(MSG_Get("PROGRAM_MORE_USAGE")); - return; - } - uint16_t ncols=mem_readw(BIOS_SCREEN_COLUMNS); - uint16_t nrows=(uint16_t)mem_readb(BIOS_ROWS_ON_SCREEN_MINUS_1); - uint16_t col=1,row=1; - uint8_t c;uint16_t n=1; - WriteOut("\n"); - while (n) { - DOS_ReadFile(STDIN,&c,&n); - if (n==0 || c==0x1a) break; // stop at EOF - switch (c) { - case 0x07: break; - case 0x08: if (col>1) col--; break; - case 0x09: col=((col+7)&~7)+1; break; - case 0x0a: row++; break; - case 0x0d: col=1; break; - default: col++; break; - } - if (col>ncols) {col=1;row++;} - DOS_WriteFile(STDOUT,&c,&n); - if (row>=nrows) { - WriteOut(MSG_Get("PROGRAM_MORE_MORE")); - DOS_ReadFile(STDERR,&c,&n); - if (c==0) DOS_ReadFile(STDERR,&c,&n); // read extended key - WriteOut("\n\n"); - col=row=1; - } - } -} - -static void MORE_ProgramStart(Program * * make) { - *make=new MORE; -} -*/ - -void MIXER_ProgramStart(Program * * make); -void REDOS_ProgramStart(Program * * make); -void SHELL_ProgramStart(Program * * make); -void SERIAL_ProgramStart(Program * * make); -void CONFIG_ProgramStart(Program * * make); -void IPXNET_ProgramStart(Program * * make); -void A20GATE_ProgramStart(Program * * make); -void CGASNOW_ProgramStart(Program * * make); -void PARALLEL_ProgramStart(Program * * make); -void PC98UTIL_ProgramStart(Program * * make); -void VESAMOED_ProgramStart(Program * * make); -void VFRCRATE_ProgramStart(Program * * make); - -#if defined C_DEBUG -class NMITEST : public Program { -public: - void Run(void) override { - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Generates a non-maskable interrupt (NMI).\n\nNMITEST\n\nNote: This is a debugging tool to test if the interrupt handler works properly.\n"); - return; - } - WriteOut("Generating a non-maskable interrupt (NMI)...\n"); - CPU_Raise_NMI(); - } -}; - -static void NMITEST_ProgramStart(Program * * make) { - *make=new NMITEST; -} -#endif - -class CAPMOUSE : public Program -{ -public: - void Run() override - { - auto val = 0; - auto tmp = std::string(""); - - if(cmd->GetCount() == 0) - val = -1; - else if(cmd->FindExist("/?", true)) - val = 0; - else if(cmd->FindExist("/C", false)) - val = 1; - else if(cmd->FindExist("/R", false)) - val = 2; - - auto cap = false; - switch(val) - { - case -1: - case 2: - break; - case 1: - cap = true; - break; - case 0: - default: - WriteOut("Captures or releases the mouse inside DOSBox-X.\n\n"); - WriteOut("CAPMOUSE [/C|/R]\n"); - WriteOut(" /C Capture the mouse\n"); - WriteOut(" /R Release the mouse\n"); - return; - } - - if (val>-1) { - CaptureMouseNotify(!cap); - GFX_CaptureMouse(cap); - } - std::string msg; - msg.append("Mouse "); - if (val==-1) msg.append("is currently "); - msg.append(Mouse_IsLocked() ? "captured" : "released"); - msg.append(".\n"); - WriteOut(msg.c_str()); - } -}; - -void CAPMOUSE_ProgramStart(Program** make) -{ - *make = new CAPMOUSE; -} - -class LABEL : public Program -{ - public: - void Help() { - WriteOut(MSG_Get("PROGRAM_LABEL_HELP")); - } - void Run() override - { - /* MS-DOS behavior: If no label provided at the command line, prompt for one. - * - * LABEL [drive:] [label] - * - * No options are supported in MS-DOS, and the label can have spaces in it. - * This is valid, apparently: - * - * LABEL H E L L O - * - * Will set the volume label to "H E L L O" - * - * Label /? will print help. - */ - std::string label; - uint8_t drive = DOS_GetDefaultDrive(); - const char *raw = cmd->GetRawCmdline().c_str(); - - /* skip space */ - while (*raw == ' ') raw++; - - /* options */ - if (raw[0] == '/') { - raw++; - if (raw[0] == '?') { - Help(); - return; - } - } - - /* is the next part a drive letter? */ - if (raw[0] != 0 && raw[1] != 0) { - if (isalpha(raw[0]) && raw[1] == ':') { - drive = tolower(raw[0]) - 'a'; - raw += 2; - while (*raw == ' ') raw++; - } - } - - /* then the label. MS-DOS behavior is to treat the rest of the command line, spaces and all, as the label */ - if (*raw != 0) { - label = raw; - } - - /* if the label is longer than 11 chars or contains a dot, MS-DOS will reject it and then prompt for another label */ - if (label.length() > 11) { - WriteOut(MSG_Get("PROGRAM_LABEL_TOOLONG")); - label.clear(); - } - else if (label.find_first_of(".:/\\") != std::string::npos) { - WriteOut(MSG_Get("PROGRAM_LABEL_BADCHARS")); - label.clear(); - } - - /* if no label provided, MS-DOS will display the current label and serial number and prompt the user to type in a new label. */ - if (label.empty()) { - std::string clabel = Drives[drive]->GetLabel(); - - if (!clabel.empty()) - WriteOut(MSG_Get("PROGRAM_LABEL_VOLUMEIS"),drive+'A',clabel.c_str()); - else - WriteOut(MSG_Get("PROGRAM_LABEL_NOLABEL"),drive+'A'); - } - - /* If no label is provided, MS-DOS will prompt the user whether to delete the label. */ - if (label.empty()) { - uint8_t c,ans=0; - uint16_t s; - - /* It does not make sense to say drive C: has no label, then prompt to delete it */ - if ((*Drives[drive]->GetLabel()) == 0) return; - - inshell = true; - do { - WriteOut(MSG_Get("PROGRAM_LABEL_DELETE")); - s = 1; - DOS_ReadFile(STDIN,&c,&s); - WriteOut("\n"); - if (s != 1 || c == 3) {inshell=false;return;} - ans = uint8_t(tolower(char(c))); - } while (!(ans == MSG_Get("INT21_6523_YESNO_CHARS")[0] || ans == MSG_Get("INT21_6523_YESNO_CHARS")[1])); - inshell = false; - - if (ans != MSG_Get("INT21_6523_YESNO_CHARS")[0]) return; - } - - /* delete then create the label */ - Drives[drive]->SetLabel("",false,true); - Drives[drive]->SetLabel(label.c_str(),false,true); - } -}; - -void LABEL_ProgramStart(Program** make) -{ - *make = new LABEL; -} - -std::vector MAPPER_GetEventNames(const std::string &prefix); -void MAPPER_AutoType(std::vector &sequence, const uint32_t wait_ms, const uint32_t pacing_ms, bool choice); - -class AUTOTYPE : public Program { -public: - void Run() override; - -private: - void PrintUsage(); - void PrintKeys(); - bool ReadDoubleArg(const std::string &name, - const char *flag, - const double &def_value, - const double &min_value, - const double &max_value, - double &value); -}; - -void AUTOTYPE_ProgramStart(Program **make); - -void AUTOTYPE::PrintUsage() -{ - constexpr const char *msg = - "Performs scripted keyboard entry into a running DOS program.\n\n" - "AUTOTYPE [-list] [-w WAIT] [-p PACE] button_1 [button_2 [...]]\n\n" - "Where:\n" - " -list: prints all available button names.\n" - " -w WAIT: seconds before typing begins. Two second default; max of 30.\n" - " -p PACE: seconds between each keystroke. Half-second default; max of 10.\n\n" - " The sequence is comprised of one or more space-separated buttons.\n" - " Autotyping begins after WAIT seconds, and each button is entered\n" - " every PACE seconds. The , character inserts an extra PACE delay.\n\n" - "Some examples:\n" - " \033[32;1mAUTOTYPE -w 1 -p 0.3 up enter , right enter\033[0m\n" - " \033[32;1mAUTOTYPE -p 0.2 f1 kp_8 , , enter\033[0m\n" - " \033[32;1mAUTOTYPE -w 1.3 esc enter , p l a y e r enter\033[0m\n"; - resetcolor = true; - WriteOut(msg); -} - -// Prints the key-names for the mapper's currently-bound events. -void AUTOTYPE::PrintKeys() -{ - const std::vector names = MAPPER_GetEventNames("key_"); - - // Keep track of the longest key name - size_t max_length = 0; - for (const auto &name : names) - max_length = (std::max)(name.length(), max_length); - - // Sanity check to avoid dividing by 0 - if (!max_length) { - WriteOut_NoParsing( - "AUTOTYPE: The mapper has no key bindings\n"); - return; - } - - // Setup our rows and columns - const size_t wrap_width = 72; // comfortable columns not pushed to the edge - const size_t columns = wrap_width / max_length; - const size_t rows = ceil_udivide(names.size(), columns); - - // Build the string output by rows and columns - auto name = names.begin(); - for (size_t row = 0; row < rows; ++row) { - for (size_t i = row; i < names.size(); i += rows) - WriteOut(" %-*s", static_cast(max_length), (name[i].size()==1&&name[i][0]>='a'&&name[i][0]<='z'?name[i]+" ("+std::string(1, toupper(name[i][0]))+")":name[i]).c_str()); - WriteOut_NoParsing("\n"); - } -} - -/* - * Converts a string to a finite number (such as float or double). - * Returns the number or quiet_NaN, if it could not be parsed. - * This function does not attempt to capture exceptions that may - * be thrown from std::stod(...) + } + else { + printError(); + return; + } + + /* must be valid drive letter, C to Z */ + if (!isalpha(el_torito_cd_drive) || el_torito_cd_drive < 'C') { + WriteOut("El Torito emulation requires a proper CD-ROM drive letter\n"); + return; + } + + /* drive must not exist (as a hard drive) */ + if (imageDiskList[el_torito_cd_drive - 'A'] != NULL) { + WriteOut("El Torito CD-ROM drive specified already exists as a non-CD-ROM device\n"); + return; + } + + bool GetMSCDEXDrive(unsigned char drive_letter, CDROM_Interface **_cdrom); + + /* get the CD-ROM drive */ + CDROM_Interface *src_drive = NULL; + if (!GetMSCDEXDrive(el_torito_cd_drive - 'A', &src_drive)) { + WriteOut("El Torito CD-ROM drive specified is not actually a CD-ROM drive\n"); + return; + } + + /* "No emulation" boot is the only mode supported at this time. + * For floppy emulation boot, use IMGMOUNT and then boot the emulated floppy drive. */ + if (el_torito_mode != "noemu") { + WriteOut("Unsupported boot mode"); + return; + } + + unsigned char entries[2048], *entry, ent_num = 0; + int header_platform = -1, header_count = 0; + bool header_final = false; + int header_more = -1; + + /* Okay. Step #1: Scan the volume descriptors for the Boot Record. */ + unsigned long el_torito_base = 0, boot_record_sector = 0, el_torito_rba = (~0ul), el_torito_load_segment = 0, el_torito_sectors = 0/*VIRTUAL SECTORS*/; + unsigned char el_torito_mediatype = 0; + if (!ElTorito_ScanForBootRecord(src_drive, boot_record_sector, el_torito_base)) { + WriteOut("El Torito CD-ROM boot record not found\n"); + return; + } + + LOG_MSG("El Torito looking for mode '%s'",el_torito_mode.c_str()); + LOG_MSG("El Torito emulation: Found ISO 9660 Boot Record in sector %lu, pointing to sector %lu\n", + boot_record_sector, el_torito_base); + + /* Step #2: Parse the records. Each one is 32 bytes long */ + if (!src_drive->ReadSectorsHost(entries, false, el_torito_base, 1)) { + WriteOut("El Torito entries unreadable\n"); + return; + } + + /* for more information about what this loop is doing, read: + * http://download.intel.com/support/motherboards/desktop/sb/specscdrom.pdf + */ + for (ent_num = 0; ent_num < (2048 / 0x20); ent_num++) { + entry = entries + (ent_num * 0x20); + + if (memcmp(entry, "\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0", 32) == 0) + break; + + if (entry[0] == 0x01/*header*/) { + if (!ElTorito_ChecksumRecord(entry)) { + LOG_MSG("Warning: El Torito checksum error in header(0x01) entry\n"); + continue; + } + + if (header_count != 0) { + LOG_MSG("Warning: El Torito has more than one Header/validation entry\n"); + continue; + } + + if (header_final) { + LOG_MSG("Warning: El Torito has an additional header past the final header\n"); + continue; + } + + header_more = -1; + header_platform = entry[1]; + LOG_MSG("El Torito entry: first header platform=0x%02x\n", header_platform); + header_count++; + } + else if (entry[0] == 0x90/*header, more follows*/ || entry[0] == 0x91/*final header*/) { + if (header_final) { + LOG_MSG("Warning: El Torito has an additional header past the final header\n"); + continue; + } + + header_final = (entry[0] == 0x91); + header_more = (int)(((unsigned int)entry[2]) + (((unsigned int)entry[3]) << 8u)); + header_platform = entry[1]; + LOG_MSG("El Torito entry: first header platform=0x%02x more=%u final=%u\n", header_platform, header_more, header_final); + header_count++; + } + else { + if (header_more == 0) { + LOG_MSG("El Torito entry: Non-header entry count expired, ignoring record 0x%02x\n", entry[0]); + continue; + } + else if (header_more > 0) { + header_more--; + } + + if (entry[0] == 0x44) { + LOG_MSG("El Torito entry: ignoring extension record\n"); + } + else if (entry[0] == 0x00/*non-bootable*/) { + LOG_MSG("El Torito entry: ignoring non-bootable record\n"); + } + else if (entry[0] == 0x88/*bootable*/) { + if (header_platform == 0x00/*x86*/) { + unsigned char mediatype = entry[1] & 0xF; + unsigned short load_segment = ((unsigned int)entry[2]) + (((unsigned int)entry[3]) << 8); + unsigned char system_type = entry[4]; + unsigned short sector_count = ((unsigned int)entry[6]) + (((unsigned int)entry[7]) << 8); + unsigned long load_rba = ((unsigned int)entry[8]) + (((unsigned int)entry[9]) << 8) + + (((unsigned int)entry[10]) << 16) + (((unsigned int)entry[11]) << 24); + + LOG_MSG("El Torito entry: bootable x86 record mediatype=%u load_segment=0x%04x " + "system_type=0x%02x sector_count=%u load_rba=%lu\n", + mediatype, load_segment, system_type, sector_count, load_rba); + + /* already chose one, ignore */ + if (el_torito_rba != ~0UL) + continue; + + if ((mediatype == 0 && el_torito_mode == "noemu")) { + el_torito_rba = load_rba; + el_torito_mediatype = mediatype; + el_torito_load_segment = (load_segment != 0) ? load_segment : 0x7C0; + el_torito_sectors = sector_count; /* VIRTUAL EMULATED sectors not CD-ROM SECTORS */ + } + } + else { + LOG_MSG("El Torito entry: ignoring bootable non-x86 (platform_id=0x%02x) record\n", header_platform); + } + } + else { + LOG_MSG("El Torito entry: ignoring unknown record ID %02x\n", entry[0]); + } + } + } + + if (el_torito_rba == (~0ul) || el_torito_sectors == 0) { + WriteOut("Unable to locate bootable section\n"); + return; + } + + LOG_MSG("Using: rba=%lu virt-sectors=%lu load=0x%lx mediatype=%u", + (unsigned long)el_torito_rba, + (unsigned long)el_torito_sectors, + (unsigned long)el_torito_load_segment, + el_torito_mediatype); + + load_seg = el_torito_load_segment; + + /* round up to CD-ROM sectors and read */ + unsigned int bootcdsect = (el_torito_sectors + 3u) / 4u; /* 4 512-byte sectors per CD-ROM sector */ + if (bootcdsect == 0) bootcdsect = 1; + + for (unsigned int s=0;s < bootcdsect;s++) { + if (!src_drive->ReadSectorsHost(entries, false, el_torito_rba+s, 1)) { + WriteOut("El Torito boot sector unreadable\n"); + return; + } + + for(i=0;i<2048;i++) real_writeb((uint16_t)load_seg, (uint16_t)i+(s*2048), entries[i]); + } + + /* signal INT 13h to emulate a CD-ROM drive El Torito "no emulation" style */ + INT13_ElTorito_IDEInterface = -1; + INT13_ElTorito_NoEmuDriveNumber = 0x90; + INT13_ElTorito_NoEmuCDROMDrive = el_torito_cd_drive; + + /* this is required if INT 13h extensions are to correctly report what IDE controller the drive is connected to and master/slave */ + { + int x = IDE_MatchCDROMDrive(el_torito_cd_drive); + if (x >= 0) INT13_ElTorito_IDEInterface = (char)x; + LOG_MSG("CD-ROM drive IDE interface number %d",INT13_ElTorito_IDEInterface); + } + + SegSet16(cs, load_seg); + SegSet16(ds, 0); + SegSet16(es, 0); + reg_ip = 0; + reg_ebx = 0; + reg_esp = 0x100; + /* set up stack at a safe place */ + SegSet16(ss, (uint16_t)stack_seg); + reg_esi = 0; + reg_ecx = 0; + reg_ebp = 0; + reg_eax = 0; + /* ISOLINUX clearly assumes DL at entry contains the drive number and at no point from entry to INT 13h does it change the contents of DX */ + reg_edx = INT13_ElTorito_NoEmuDriveNumber; + #ifdef __WIN32__ + // let menu know it boots + menu.boot=true; + #endif + bootguest=false; + bootdrive=drive-65; + + /* forcibly exit the shell, the DOS kernel, and anything else by throwing an exception */ + throw int(2); + + return; + } + + if(!cmd->GetCount()) { + uint8_t drv = dos_kernel_disabled?26:DOS_GetDefaultDrive(); + if (drv < 4 && Drives[drv] && !strncmp(Drives[drv]->GetInfo(), "fatDrive ", 9)) { + drive = 'A' + drv; + bootbyDrive = true; + } else { + printError(); + return; + } + } else if (cmd->GetCount()==1) { + cmd->FindCommand(1, temp_line); + if (temp_line.length()==2&&toupper(temp_line[0])>='A'&&toupper(temp_line[0])<='Z'&&temp_line[1]==':') { + drive=toupper(temp_line[0]); + if ((drive != 'A') && (drive != 'C') && (drive != 'D')) { + printError(); + return; + } + bootbyDrive = true; + } + } + + if(!bootbyDrive) + while(i < cmd->GetCount()) { + if(cmd->FindCommand((unsigned int)(i+1), temp_line)) { + if ((temp_line == "/?") || (temp_line == "-?")) { + printError(); + return; + } + if((temp_line == "-l") || (temp_line == "-L")) { + /* Specifying drive... next argument then is the drive */ + bootbyDrive = true; + i++; + if(cmd->FindCommand((unsigned int)(i+1), temp_line)) { + if (temp_line.length()==1&&isdigit(temp_line[0])) + drive='A'+(temp_line[0]-'0'); + else + drive=toupper(temp_line[0]); + if ((drive != 'A') && (drive != 'C') && (drive != 'D')) { + printError(); + return; + } + + } else { + printError(); + return; + } + i++; + continue; + } + + if((temp_line == "-e") || (temp_line == "-E")) { + /* Command mode for PCJr cartridges */ + i++; + if(cmd->FindCommand((unsigned int)(i + 1), temp_line)) { + for(size_t ct = 0;ct < temp_line.size();ct++) temp_line[ct] = toupper(temp_line[ct]); + cart_cmd = temp_line; + } else { + printError(); + return; + } + i++; + continue; + } + + if(imageDiskList[0] != NULL || imageDiskList[1] != NULL) { + WriteOut(MSG_Get("PROGRAM_BOOT_IMAGE_MOUNTED")); + return; + } + + if (i >= MAX_SWAPPABLE_DISKS) { + return; //TODO give a warning. + } + + uint32_t rombytesize=0; + bool readonly=wpcolon&&temp_line.length()>1&&temp_line[0]==':'; + if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_IMAGE_OPEN"), readonly?temp_line.c_str()+1:temp_line.c_str()); + FILE *usefile = getFSFile(temp_line.c_str(), &floppysize, &rombytesize); + if(usefile != NULL) { + char tmp[256]; + + if (newDiskSwap[i] != NULL) { + newDiskSwap[i]->Release(); + newDiskSwap[i] = NULL; + } + + fseeko64(usefile, 0L, SEEK_SET); + size_t readResult = fread(tmp,256,1,usefile); // look for magic signatures + if (readResult != 1) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); + return; + } + + const char *ext = strrchr(temp_line.c_str(),'.'), *fname=readonly?temp_line.c_str()+1:temp_line.c_str(); + + if (ext != NULL && !strcasecmp(ext, ".d88")) { + newDiskSwap[i] = new imageDiskD88(usefile, fname, floppysize, false); + } + else if (!memcmp(tmp,"VFD1.",5)) { /* FDD files */ + newDiskSwap[i] = new imageDiskVFD(usefile, fname, floppysize, false); + } + else if (!memcmp(tmp,"T98FDDIMAGE.R0\0\0",16)) { + newDiskSwap[i] = new imageDiskNFD(usefile, fname, floppysize, false, 0); + } + else if (!memcmp(tmp,"T98FDDIMAGE.R1\0\0",16)) { + newDiskSwap[i] = new imageDiskNFD(usefile, fname, floppysize, false, 1); + } + else { + newDiskSwap[i] = new imageDisk(usefile, fname, floppysize, false); + } + newDiskSwap[i]->Addref(); + if (newDiskSwap[i]->active && !newDiskSwap[i]->hardDrive) incrementFDD(); //moved from imageDisk constructor + + if (usefile_1==NULL) { + usefile_1=usefile; + rombytesize_1=rombytesize; + } else { + usefile_2=usefile; + rombytesize_2=rombytesize; + } + } else { + if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_IMAGE_NOT_OPEN"), readonly?temp_line.c_str()+1:temp_line.c_str()); + return; + } + + } + i++; + } + + if (!bootbyDrive) { + if (i == 0) { + if (!quiet) WriteOut("No images specified"); + return; + } + + if (i > 1) { + /* if more than one image is given, then this drive becomes the focus of the swaplist */ + if (swapInDisksSpecificDrive >= 0 && swapInDisksSpecificDrive != (drive - 65)) { + if (!quiet) WriteOut("Multiple disk images specified and another drive is already connected to the swap list"); + return; + } + else if (swapInDisksSpecificDrive < 0 && swaponedrive) { + swapInDisksSpecificDrive = drive - 65; + } + + /* transfer to the diskSwap array */ + for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { + if (diskSwap[si] != NULL) { + diskSwap[si]->Release(); + diskSwap[si] = NULL; + } + + diskSwap[si] = newDiskSwap[si]; + newDiskSwap[si] = NULL; + } + + swapPosition = 0; + swapInDisks(-1); + } + else { + if (swapInDisksSpecificDrive == (drive - 65)) { + /* if we're replacing the diskSwap drive clear it now */ + for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { + if (diskSwap[si] != NULL) { + diskSwap[si]->Release(); + diskSwap[si] = NULL; + } + } + + swapInDisksSpecificDrive = -1; + } + + /* attach directly without using the swap list */ + if (imageDiskList[drive-65] != NULL) { + imageDiskChange[drive-65] = true; + imageDiskList[drive-65]->Release(); + imageDiskList[drive-65] = NULL; + } + + imageDiskList[drive-65] = newDiskSwap[0]; + newDiskSwap[0] = NULL; + } + } + + if(imageDiskList[drive-65]==NULL) { + if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_UNABLE"), drive); + return; + } + + // .D88 images come from PC-88 which usually means the boot sector is full + // of Z80 executable code, therefore it's very unlikely the boot sector will + // work with our x86 emulation! + // + // If the user is REALLY REALLY SURE they want to try executing Z80 bootsector + // code as x86, they're free to use --force. + // + // However PC-98 games are also distributed as .D88 images and therefore + // we probably CAN boot the image. + // + // It depends on the fd_type field of the image. + if (!force && imageDiskList[drive-65]->class_id == imageDisk::ID_D88) { + if (reinterpret_cast(imageDiskList[drive-65])->fd_type_major == imageDiskD88::DISKTYPE_2D) { + if (!quiet) WriteOut("The D88 image appears to target PC-88 and cannot be booted."); + return; + } + } + + + bootSector bootarea; + + if (imageDiskList[drive-65]->getSectSize() > sizeof(bootarea)) { + if (!quiet) WriteOut("Bytes/sector too large"); + return; + } + + /* clear the disk change flag. + * Most OSes don't expect the disk change error signal when they first boot up */ + imageDiskChange[drive-65] = false; + + bool has_read = false; + bool pc98_sect128 = false; + unsigned int bootsize = imageDiskList[drive-65]->getSectSize(); + + if (!has_read && IS_PC98_ARCH && drive < 'C') { + /* this may be one of those odd FDD images where track 0, head 0 is all 128-byte sectors + * and the rest of the disk is 256-byte sectors. */ + if (imageDiskList[drive - 65]->Read_Sector(0, 0, 1, (uint8_t *)&bootarea, 128) == 0 && + imageDiskList[drive - 65]->Read_Sector(0, 0, 2, (uint8_t *)&bootarea + 128, 128) == 0 && + imageDiskList[drive - 65]->Read_Sector(0, 0, 3, (uint8_t *)&bootarea + 256, 128) == 0 && + imageDiskList[drive - 65]->Read_Sector(0, 0, 4, (uint8_t *)&bootarea + 384, 128) == 0) { + LOG_MSG("First sector is 128 byte/sector. Booting from first four sectors."); + has_read = true; + bootsize = 512; // 128 x 4 + pc98_sect128 = true; + } + } + + if (!has_read && IS_PC98_ARCH && drive < 'C') { + /* another nonstandard one with track 0 having 256 bytes/sector while the rest have 1024 bytes/sector */ + if (imageDiskList[drive - 65]->Read_Sector(0, 0, 1, (uint8_t *)&bootarea, 256) == 0 && + imageDiskList[drive - 65]->Read_Sector(0, 0, 2, (uint8_t *)&bootarea + 256, 256) == 0 && + imageDiskList[drive - 65]->Read_Sector(0, 0, 3, (uint8_t *)&bootarea + 512, 256) == 0 && + imageDiskList[drive - 65]->Read_Sector(0, 0, 4, (uint8_t *)&bootarea + 768, 256) == 0) { + LOG_MSG("First sector is 256 byte/sector. Booting from first two sectors."); + has_read = true; + bootsize = 1024; // 256 x 4 + pc98_sect128 = true; + } + } + + /* NTS: Load address is 128KB - sector size */ + if (loadseg_user > 0) { /* Some PC-98 games have floppy boot code that suggests the boot segment isn't always 0x1FC0 like PC-9821 hardware does? */ + load_seg=(unsigned int)loadseg_user; + } + else { + unsigned int max_seg = std::min((unsigned int)(MEM_TotalPages()*(4096u/16u)/*pages to paragraphs*/),0xC000u); + if (IS_PC98_ARCH) + load_seg=std::min(max_seg,0x2000u/*128KB mark*/) - (bootsize/16U); /* normally 0x1FC0 (1024 byte/sector) or 0x1FE0 (512 byte/sector) */ + else + load_seg=std::min(max_seg,0x800u/*32KB mark*/) - 0x40u/*1KB*/; /* normally 0x07C0 */ + } + + if (!has_read) { + if (imageDiskList[drive - 65]->Read_Sector(0, 0, 1, (uint8_t *)&bootarea) != 0) { + if (!quiet) WriteOut("Error reading drive"); + return; + } + } + + Bitu pcjr_hdr_length = 0; + uint8_t pcjr_hdr_type = 0; // not a PCjr cartridge + if ((bootarea.rawdata[0]==0x50) && (bootarea.rawdata[1]==0x43) && (bootarea.rawdata[2]==0x6a) && (bootarea.rawdata[3]==0x72)) { + pcjr_hdr_type = 1; // JRipCart + pcjr_hdr_length = 0x200; + } else if ((bootarea.rawdata[56]==0x50) && (bootarea.rawdata[57]==0x43) && (bootarea.rawdata[58]==0x4a) && (bootarea.rawdata[59]==0x52)) { + pcjr_hdr_type = 2; // PCJRCart + pcjr_hdr_length = 0x80; + } + + if (pcjr_hdr_type > 0) { + if (machine!=MCH_PCJR&&!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_WO_PCJR")); + else { + uint8_t rombuf[65536]; + Bits cfound_at=-1; + if (cart_cmd!="") { + /* read cartridge data into buffer */ + fseek(usefile_1, (long)pcjr_hdr_length, SEEK_SET); + size_t readResult = fread(rombuf, 1, rombytesize_1-pcjr_hdr_length, usefile_1); + if (readResult != rombytesize_1 - pcjr_hdr_length) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); + return; + } + + char cmdlist[1024]; + cmdlist[0]=0; + Bitu ct=6; + Bits clen=rombuf[ct]; + char buf[257]; + if (cart_cmd=="?") { + while (clen!=0) { + safe_strncpy(buf,(char*)&rombuf[ct+1],clen); + buf[clen]=0; + upcase(buf); + strcat(cmdlist," "); + strcat(cmdlist,buf); + ct+=1u+(Bitu)clen+3u; + if (ct>sizeof(cmdlist)) break; + clen=rombuf[ct]; + } + if (ct>6) { + if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_LIST_CMDS"),cmdlist); + } else { + if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_NO_CMDS")); + } + for(Bitu dct=0;dctRelease(); + diskSwap[dct]=NULL; + } + } + //fclose(usefile_1); //delete diskSwap closes the file + return; + } else { + while (clen!=0) { + safe_strncpy(buf,(char*)&rombuf[ct+1],clen); + buf[clen]=0; + upcase(buf); + strcat(cmdlist," "); + strcat(cmdlist,buf); + ct+=1u+(Bitu)clen; + + if (cart_cmd==buf) { + cfound_at=(Bits)ct; + break; + } + + ct+=3; + if (ct>sizeof(cmdlist)) break; + clen=rombuf[ct]; + } + if (cfound_at<=0) { + if (ct>6) { + if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_LIST_CMDS"),cmdlist); + } else { + if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_CART_NO_CMDS")); + } + for(Bitu dct=0;dctRelease(); + diskSwap[dct]=NULL; + } + } + //fclose(usefile_1); //Delete diskSwap closes the file + return; + } + } + } + + void PreparePCJRCartRom(void); + PreparePCJRCartRom(); + + if (usefile_1==NULL) return; + + uint32_t sz1,sz2; + FILE *tfile = getFSFile("system.rom", &sz1, &sz2, true); + if (tfile!=NULL) { + fseek(tfile, 0x3000L, SEEK_SET); + uint32_t drd=(uint32_t)fread(rombuf, 1, 0xb000, tfile); + if (drd==0xb000) { + for(i=0;i<0xb000;i++) phys_writeb((PhysPt)(0xf3000+i),rombuf[i]); + } + fclose(tfile); + } + + if (usefile_2!=NULL) { + unsigned int romseg_pt=0; + + fseek(usefile_2, 0x0L, SEEK_SET); + size_t readResult = fread(rombuf, 1, pcjr_hdr_length, usefile_2); + if (readResult != pcjr_hdr_length) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); + return; + } + + if (pcjr_hdr_type == 1) { + romseg_pt=host_readw(&rombuf[0x1ce]); + } else { + fseek(usefile_2, 0x61L, SEEK_SET); + int scanResult = fscanf(usefile_2, "%4x", &romseg_pt); + if (scanResult == 0) { + LOG(LOG_IO, LOG_ERROR) ("Scanning error in Run\n"); + return; + } + } + /* read cartridge data into buffer */ + fseek(usefile_2, (long)pcjr_hdr_length, SEEK_SET); + readResult = fread(rombuf, 1, rombytesize_2-pcjr_hdr_length, usefile_2); + if (readResult != rombytesize_2 - pcjr_hdr_length) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in Run\n"); + return; + } + //fclose(usefile_2); //usefile_2 is in diskSwap structure which should be deleted to close the file + + /* write cartridge data into ROM */ + for(i=0;iRelease(); + diskSwap[dct]=NULL; + } + } + + + if (cart_cmd=="") { + uint32_t old_int18=mem_readd(0x60); + /* run cartridge setup */ + SegSet16(ds,romseg); + SegSet16(es,romseg); + SegSet16(ss,0x8000); + reg_esp=0xfffe; + CALLBACK_RunRealFar(romseg,0x0003); + + uint32_t new_int18=mem_readd(0x60); + if (old_int18!=new_int18) { + /* boot cartridge (int18) */ + SegSet16(cs,RealSeg(new_int18)); + reg_ip = RealOff(new_int18); + } + } else { + if (cfound_at>0) { + /* run cartridge setup */ + SegSet16(ds,dos.psp()); + SegSet16(es,dos.psp()); + CALLBACK_RunRealFar((uint16_t)romseg,(uint16_t)cfound_at); + } + } + } + } else { + extern const char* RunningProgram; + + if (max_seg < (IS_PC98_ARCH?0x2000:0x0800)) LOG(LOG_MISC,LOG_WARN)("Booting a guest OS with too small amount of RAM may not work correctly"); + + /* Other versions of MS-DOS/PC-DOS have their own requirements about memory: + * - IBM PC-DOS 1.0/1.1: not too picky, will boot with as little as 32KB even though + * it was intended for the average model with 64KB of RAM. + * + * - IBM PC-DOS 2.1: requires at least 44KB of RAM. will crash on boot otherwise. + * + * - MS-DOS 3.2: requires at least 64KB to boot without crashing, 80KB to make it + * to the command line without halting at "configuration too big for + * memory"*/ + + /* TODO: Need a configuration option or a BOOT command option where the user can + * dictate where we put the stack: if we put it at 0x7000 or top of memory + * (default) or just below the boot sector, or... */ + + if((bootarea.rawdata[0]==0) && (bootarea.rawdata[1]==0)) { + if (!quiet) WriteOut(MSG_Get("PROGRAM_BOOT_UNABLE"), drive); + return; + } + + char msg[512] = {0}; + const uint8_t page=real_readb(BIOSMEM_SEG,BIOSMEM_CURRENT_PAGE); + if (!dos_kernel_disabled && (convimg == 1 || (convertimg && convimg == -1))) { + unsigned int drv = 2, nextdrv = 2; + Section_prop *sec = static_cast(control->GetSection("dosbox")); + int freeMB = sec->Get_int("convert fat free space"), timeout = sec->Get_int("convert fat timeout"); + for (unsigned int d=2;dGetInfo(), "fatDrive ", 9) && strncmp(Drives[drv]->GetInfo(), "isoDrive ", 9)) { + if (drv==ZDRIVE_NUM && !static_cast(control->GetSection("dos"))->Get_bool("drive z convert fat")) continue; + while (imageDiskList[nextdrv]) nextdrv++; + if (nextdrv>=MAX_DISK_IMAGES) break; + if (quiet<2) { + size_t len = strlen(msg); + if (!len) { + strcat(msg, CURSOR_POS_COL(page)>0?"\r\n":""); + len = strlen(msg); + } + strcat(msg, "Converting drive "); + strcat(msg, std::string(1, 'A'+drv).c_str()); + strcat(msg, ": to FAT..."); + LOG_MSG("%s", msg+len); + strcat(msg, "\r\n"); + if (!quiet) { + uint16_t s = (uint16_t)strlen(msg); + DOS_WriteFile(STDERR,(uint8_t*)msg,&s); + *msg = 0; + } + } + Overlay_Drive *od = dynamic_cast(Drives[drv]); + imageDisk *imagedrv = new imageDisk(Drives[drv], drv, (convertro || Drives[drv]->readonly || (od && od->ovlreadonly)) ? 0 : freeMB, timeout); + if (imagedrv && imagedrv->ffdd) { + imageDiskList[nextdrv] = imagedrv; + imagedrv->Addref(); + bool ide_slave = false; + signed char ide_index = -1; + IDE_Auto(ide_index,ide_slave); + IDE_Hard_Disk_Attach((signed char)ide_index, ide_slave, nextdrv); + } else if (imagedrv) + delete imagedrv; + } + } + } + + if (quiet<2) { + if (!strlen(msg)) strcat(msg, CURSOR_POS_COL(page)>0?"\r\n":""); + strcat(msg, MSG_Get("PROGRAM_BOOT_BOOTING")); + strcat(msg, std::string(1, drive).c_str()); + strcat(msg, "...\r\n"); + uint16_t s = (uint16_t)strlen(msg); + DOS_WriteFile(STDERR,(uint8_t*)msg,&s); + } + if (IS_DOSV) { + uint8_t mode = real_readb(BIOSMEM_SEG, BIOSMEM_CURRENT_MODE); + if (mode == 3 || mode == 0x70 || mode == 0x72 || mode == 0x78) { + uint16_t oldax=reg_ax; + reg_ax = 0x12; + CALLBACK_RunRealInt(0x10); + reg_ax = oldax; + } + } + + for(i=0;itcount=true; + GetDMAChannel(3)->tcount=true; + } + else { + if (!IS_TANDY_ARCH && floppysize!=0) GetDMAChannel(2)->tcount=true; + } + + /* standard method */ + if (IS_PC98_ARCH) { + /* Based on a CPU register dump at boot time on a real PC-9821: + * + * DUMP: + * + * SP: 00D8 SS: 0030 ES: 1FE0 DS: 0000 CS: 1FE0 FL: 0246 BP: 0000 + * DI: 055C SI: 1FE0 DX: 0001 CX: 0200 BX: 0200 AX: 0030 IP: 0000 + * + * So: + * + * Stack at 0030:00D8 + * + * CS:IP at load_seg:0000 + * + * load_seg at 0x1FE0 which on the original 128KB PC-98 puts it at the top of memory + * + */ + SegSet16(cs, (uint16_t)load_seg); + SegSet16(ds, 0x0000); + SegSet16(es, (uint16_t)load_seg); + reg_ip = 0; + reg_ebx = 0x200; + reg_esp = 0xD8; + /* set up stack at a safe place */ + SegSet16(ss, (uint16_t)stack_seg); + reg_esi = (uint32_t)load_seg; + reg_ecx = 0x200; + reg_ebp = 0; + reg_eax = 0x30; + reg_edx = 0x1; + + /* It seems 640x200 8-color digital mode is the state of the graphics hardware when the + * BIOS boots the OS, and some games like Ys II assume the hardware is in this state. + * + * If I am wrong, you can pass --pc98-640x400 as a command line option to disable this. */ + if (pc98_640x200) { + reg_eax = 0x4200; // setup 640x200 graphics + reg_ecx = 0x8000; // lower + CALLBACK_RunRealInt(0x18); + } + else { + reg_eax = 0x4200; // setup 640x400 graphics + reg_ecx = 0xC000; // full + CALLBACK_RunRealInt(0x18); + } + + /* Some HDI images of Orange House games need this option because it assumes NEC MOUSE.COM + * behavior where mouse driver init and reset show the graphics layer. Unfortunately the HDI + * image uses QMOUSE which does not show the graphics layer. Use this option with those + * HDI images to make them playable anyway. */ + if (pc98_show_graphics) { + reg_eax = 0x4000; // show graphics + CALLBACK_RunRealInt(0x18); + } + else { + reg_eax = 0x4100; // hide graphics (normal state of graphics layer on startup). INT 33h emulation might have enabled it. + CALLBACK_RunRealInt(0x18); + } + + /* PC-98 MS-DOS boot sector behavior suggests that the BIOS does a CALL FAR + * to the boot sector, and the boot sector can RETF back to the BIOS on failure. */ + CPU_Push16((uint16_t)(BIOS_bootfail_code_offset >> 4)); /* segment */ + CPU_Push16(BIOS_bootfail_code_offset & 0xF); /* offset */ + + /* clear the text layer */ + for (i=0;i < (80*25*2);i += 2) { + mem_writew((PhysPt)(0xA0000+i),0x0000); + mem_writew((PhysPt)(0xA2000+i),0x00E1); + } + + /* hide the cursor */ + void PC98_show_cursor(bool show); + PC98_show_cursor(false); + + /* There is a byte at 0x584 that describes the boot drive + type. + * This is confirmed in Neko Project II source and by the behavior + * of an MS-DOS boot disk formatted by a PC-98 system. + * + * There are three values for three different floppy formats, and + * one for hard drives */ + uint32_t heads,cyls,sects,ssize; + + imageDiskList[drive-65]->Get_Geometry(&heads,&cyls,§s,&ssize); + + uint8_t RDISK_EQUIP = 0; /* 488h (ref. PC-9800 Series Technical Data Book - BIOS 1992 page 233 */ + /* bits [7:4] = 640KB FD drives 3:0 + * bits [3:0] = 1MB FD drives 3:0 */ + uint8_t F2HD_MODE = 0; /* 493h (ref. PC-9800 Series Technical Data Book - BIOS 1992 page 233 */ + /* bits [7:4] = 640KB FD drives 3:0 ?? + * bits [3:0] = 1MB FD drives 3:0 ?? */ + uint8_t F2DD_MODE = 0; /* 5CAh (ref. PC-9800 Series Technical Data Book - BIOS 1992 page 233 */ + /* bits [7:4] = 640KB FD drives 3:0 ?? + * bits [3:0] = 1MB FD drives 3:0 ?? */ + uint16_t disk_equip = 0, disk_equip_144 = 0; + uint8_t scsi_equip = 0; + + /* FIXME: MS-DOS appears to be able to see disk image B: but only + * if the disk format is the same, for some reason. + * + * So, apparently you cannot put a 1.44MB image in drive A: + * and a 1.2MB image in drive B: */ + + for (i=0;i < 2;i++) { + if (imageDiskList[i] != NULL) { + disk_equip |= (0x0111u << i); /* 320KB[15:12] 1MB[11:8] 640KB[7:4] unit[1:0] */ + disk_equip_144 |= (1u << i); + F2HD_MODE |= (0x11u << i); + } + } + + for (i=0;i < 2;i++) { + if (imageDiskList[i+2] != NULL) { + scsi_equip |= (1u << i); + + uint16_t m = 0x460u + ((uint16_t)i * 4u); + + mem_writeb(m+0u,sects); + mem_writeb(m+1u,heads); + mem_writew(m+2u,(cyls & 0xFFFu) + (ssize == 512u ? 0x1000u : 0u) + (ssize == 1024u ? 0x2000u : 0) + 0x8000u/*NP2:hwsec*/); + } + } + + mem_writew(0x55C,disk_equip); /* disk equipment (drive 0 is present) */ + mem_writew(0x5AE,disk_equip_144); /* disk equipment (drive 0 is present, 1.44MB) */ + mem_writeb(0x482,scsi_equip); + mem_writeb(0x488,RDISK_EQUIP); /* RAM disk equip */ + mem_writeb(0x493,F2HD_MODE); + mem_writeb(0x5CA,F2DD_MODE); + + if (drive >= 'C') { + /* hard drive */ + mem_writeb(0x584,0xA0/*type*/ + (drive - 'C')/*drive*/); + } + else if ((ssize == 1024 && heads == 2 && cyls == 77 && sects == 8) || pc98_sect128) { + mem_writeb(0x584,0x90/*type*/ + (drive - 65)/*drive*/); /* 1.2MB 3-mode */ + } + else if (ssize == 512 && heads == 2 && cyls == 80 && sects == 18) { + mem_writeb(0x584,0x30/*type*/ + (drive - 65)/*drive*/); /* 1.44MB */ + } + else { + // FIXME + LOG_MSG("PC-98 boot: Unable to determine boot drive type for ssize=%u heads=%u cyls=%u sects=%u. Guessing.", + ssize,heads,cyls,sects); + + mem_writeb(0x584,(ssize < 1024 ? 0x30 : 0x90)/*type*/ + (drive - 65)/*drive*/); + } + } + else { + // Toshiba DOS bootloader checks the floppy disk drives running in the BIOS working area. + if(IS_J3100) { + mem_writeb(BIOS_DRIVE_RUNNING, 0x01); + mem_writeb(BIOS_DISK_MOTOR_TIMEOUT, 10); + } + SegSet16(cs, 0); + SegSet16(ds, 0); + SegSet16(es, 0); + reg_ip = (uint16_t)(load_seg<<4); + reg_ebx = (uint32_t)(load_seg<<4); //Real code probably uses bx to load the image + reg_esp = 0x100; + /* set up stack at a safe place */ + SegSet16(ss, (uint16_t)stack_seg); + reg_esi = 0; + reg_ecx = 1; + reg_ebp = 0; + reg_eax = 0; + reg_edx = 0; //Head 0 + if (drive >= 'A' && drive <= 'B') + reg_edx += (unsigned int)(drive-'A'); + else if (drive >= 'C' && drive <= 'Z') + reg_edx += 0x80u+(unsigned int)(drive-'C'); + } + #ifdef __WIN32__ + // let menu know it boots + menu.boot=true; + #endif + bootguest=false; + bootdrive=drive-65; + + /* forcibly exit the shell, the DOS kernel, and anything else by throwing an exception */ + throw int(2); + } + } + }; + + static void BOOT_ProgramStart(Program * * make) { + *make=new BOOT; + } + + void runBoot(const char *str) { + BOOT boot; + boot.cmd=new CommandLine("BOOT", str); + boot.Run(); + } + + class LOADROM : public Program { + public: + void Run(void) override { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut(MSG_Get("PROGRAM_LOADROM_HELP")); + return; + } + + if (!(cmd->FindCommand(1, temp_line))) { + WriteOut(MSG_Get("PROGRAM_LOADROM_SPECIFY_FILE")); + return; + } + + uint8_t drive; + char fullname[DOS_PATHLENGTH]; + localDrive* ldp=nullptr; + if (!DOS_MakeName(temp_line.c_str(),fullname,&drive)) return; + + try { + /* try to read ROM file into buffer */ + ldp=dynamic_cast(Drives[drive]); + if(!ldp) return; + + FILE *tmpfile = ldp->GetSystemFilePtr(fullname, "rb"); + if(tmpfile == NULL) { + WriteOut(MSG_Get("PROGRAM_LOADROM_CANT_OPEN")); + return; + } + fseek(tmpfile, 0L, SEEK_END); + if (ftell(tmpfile)>0x8000) { + WriteOut(MSG_Get("PROGRAM_LOADROM_TOO_LARGE")); + fclose(tmpfile); + return; + } + fseek(tmpfile, 0L, SEEK_SET); + uint8_t rom_buffer[0x8000]; + Bitu data_read = fread(rom_buffer, 1, 0x8000, tmpfile); + fclose(tmpfile); + + /* try to identify ROM type */ + PhysPt rom_base = 0; + if (data_read >= 0x4000 && rom_buffer[0] == 0x55 && rom_buffer[1] == 0xaa && + (rom_buffer[3] & 0xfc) == 0xe8 && strncmp((char*)(&rom_buffer[0x1e]), "IBM", 3) == 0) { + + if (!IS_EGAVGA_ARCH) { + WriteOut(MSG_Get("PROGRAM_LOADROM_INCOMPATIBLE")); + return; + } + rom_base = PhysMake(0xc000, 0); // video BIOS + } + else if (data_read == 0x8000 && rom_buffer[0] == 0xe9 && rom_buffer[1] == 0x8f && + rom_buffer[2] == 0x7e && strncmp((char*)(&rom_buffer[0x4cd4]), "IBM", 3) == 0) { + + rom_base = PhysMake(0xf600, 0); // BASIC + } + + if (rom_base) { + /* write buffer into ROM */ + for (Bitu i=0; iFindCommand(1, temp_line))) { + WriteOut("Must specify BIOS file to load.\n"); + return; + } + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut(MSG_Get("PROGRAM_BIOSTEST_HELP")); + return; + } + + uint8_t drive; + char fullname[DOS_PATHLENGTH]; + localDrive* ldp = nullptr; + if (!DOS_MakeName(temp_line.c_str(), fullname, &drive)) return; + + try { + /* try to read ROM file into buffer */ + ldp = dynamic_cast(Drives[drive]); + if (!ldp) return; + + FILE* tmpfile = ldp->GetSystemFilePtr(fullname, "rb"); + if (tmpfile == NULL) { + WriteOut("Can't open a file"); + return; + } + fseek(tmpfile, 0L, SEEK_END); + if (ftell(tmpfile) > 64 * 1024) { + WriteOut("BIOS File too large"); + fclose(tmpfile); + return; + } + fseek(tmpfile, 0L, SEEK_SET); + uint8_t buffer[64 * 1024]; + Bitu data_read = fread(buffer, 1, sizeof(buffer), tmpfile); + fclose(tmpfile); + + uint32_t rom_base = PhysMake(0xf000, 0); // override regular dosbox bios + /* write buffer into ROM */ + for (Bitu i = 0; i < data_read; i++) phys_writeb((PhysPt)(rom_base + i), buffer[i]); + + //Start executing this bios + memset(&cpu_regs, 0, sizeof(cpu_regs)); + memset(&Segs, 0, sizeof(Segs)); + + SegSet16(cs, 0xf000); + reg_eip = 0xfff0; + } + catch (...) { + return; + } + } + }; + + static void BIOSTEST_ProgramStart(Program** make) { + *make = new BIOSTEST; + } + #endif + + /* non-bootable MS-DOS floppy disk boot sector. + * will be modified as appropriate. */ + unsigned char this_is_not_a_bootable_partition[512] = { + 0xeb, 0x3c, 0x90, 0x6d, 0x6b, 0x64, 0x6f, 0x73, 0x66, 0x73, 0x00, 0x00, 0x02, 0x01, 0x01, 0x00, + 0x02, 0xe0, 0x00, 0x40, 0x0b, 0xf0, 0x09, 0x00, 0x12, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0xce, 0xf2, 0x4e, 0xda, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x46, 0x41, 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x0e, 0x1f, + 0xbe, 0x5b, 0x7c, 0xac, 0x22, 0xc0, 0x74, 0x0b, 0x56, 0xb4, 0x0e, 0xbb, 0x07, 0x00, 0xcd, 0x10, + 0x5e, 0xeb, 0xf0, 0x32, 0xe4, 0xcd, 0x16, 0xcd, 0x19, 0xeb, 0xfe, 0x54, 0x68, 0x69, 0x73, 0x20, + 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x74, 0x61, 0x62, 0x6c, + 0x65, 0x20, 0x64, 0x69, 0x73, 0x6b, 0x2e, 0x20, 0x20, 0x50, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x20, + 0x69, 0x6e, 0x73, 0x65, 0x72, 0x74, 0x20, 0x61, 0x20, 0x62, 0x6f, 0x6f, 0x74, 0x61, 0x62, 0x6c, + 0x65, 0x20, 0x66, 0x6c, 0x6f, 0x70, 0x70, 0x79, 0x20, 0x61, 0x6e, 0x64, 0x0d, 0x0a, 0x70, 0x72, + 0x65, 0x73, 0x73, 0x20, 0x61, 0x6e, 0x79, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x74, 0x6f, 0x20, 0x74, + 0x72, 0x79, 0x20, 0x61, 0x67, 0x61, 0x69, 0x6e, 0x20, 0x2e, 0x2e, 0x2e, 0x20, 0x0d, 0x0a, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa + }; + + const uint8_t freedos_mbr[] = { + 0xFA,0xFC,0x31,0xC0,0x8E,0xD0,0x8E,0xD8,0xBD,0x00,0x7C,0x8D,0x66,0xE0,0xFB,0xB8, + 0xE0,0x1F,0x8E,0xC0,0x89,0xEE,0x89,0xEF,0xB9,0x00,0x01,0xF3,0xA5,0xEA,0x22,0x7C, // 10h + 0xE0,0x1F,0x8E,0xD8,0x8E,0xD0,0x31,0xC0,0x8E,0xC0,0x8D,0xBE,0xBE,0x01,0xF6,0x05, // 20h + 0x80,0x75,0x6D,0x83,0xC7,0x10,0x81,0xFF,0xFE,0x7D,0x72,0xF2,0xE8,0xC4,0x00,0x6E, + 0x6F,0x20,0x61,0x63,0x74,0x69,0x76,0x65,0x20,0x70,0x61,0x72,0x74,0x69,0x74,0x69, // 40h + 0x6F,0x6E,0x20,0x66,0x6F,0x75,0x6E,0x64,0x00,0xEB,0xFE,0xE8,0xA5,0x00,0x72,0x65, + 0x61,0x64,0x20,0x65,0x72,0x72,0x6F,0x72,0x20,0x77,0x68,0x69,0x6C,0x65,0x20,0x72, + 0x65,0x61,0x64,0x69,0x6E,0x67,0x20,0x64,0x72,0x69,0x76,0x65,0x00,0xEB,0xDA,0xE8, + 0x81,0x00,0x70,0x61,0x72,0x74,0x69,0x74,0x69,0x6F,0x6E,0x20,0x73,0x69,0x67,0x6E, // 80h + 0x61,0x74,0x75,0x72,0x65,0x20,0x21,0x3D,0x20,0x35,0x35,0x41,0x41,0x00,0xEB,0xB9, + 0xE8,0x10,0x00,0x72,0xB6,0x26,0x81,0x3E,0xFE,0x7D,0x55,0xAA,0x75,0xD1,0xEA,0x00, + 0x7C,0x00,0x00,0xBB,0xAA,0x55,0xB4,0x41,0xCD,0x13,0x72,0x32,0x81,0xFB,0x55,0xAA, + 0x75,0x2C,0xF6,0xC1,0x01,0x74,0x27,0xEB,0x10,0x10,0x00,0x04,0x00,0x00,0x7C,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x8B,0x45,0x08,0xA3,0xD1,0x7C,0x8B, + 0x45,0x0A,0xA3,0xD3,0x7C,0xB8,0x00,0x42,0xBE,0xC9,0x7C,0xCD,0x13,0xC3,0xB8,0x04, + 0x02,0xBB,0x00,0x7C,0x8B,0x4D,0x02,0x8A,0x75,0x01,0xCD,0x13,0xC3,0x31,0xDB,0xB4, + 0x0E,0xCD,0x10,0x5E,0xAC,0x56,0x3C,0x00,0x75,0xF3,0xC3,0x00,0x00,0x00,0x00,0x00, //100h + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //110h + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //120h + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //140h + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, //180h + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x73,0x73,0x65,0xE3,0x3F,0xBF,0x00,0x00, //1B0h + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x55,0xAA + }; + #ifdef WIN32 + #include + #endif + + static void lba2chs3(unsigned char *b3,uint32_t lba,const unsigned int gc,const unsigned int gh,const unsigned int gs) { + const unsigned int s = (unsigned int)(lba % (uint32_t)gs) + 1u; lba /= (uint32_t)gs; + const unsigned int h = (unsigned int)(lba % (uint32_t)gh); lba /= (uint32_t)gh; + const unsigned int c = (unsigned int) lba; + + (void)gc; + + b3[0] = h; + b3[1] = s | ((c >> 8u) << 6u); /* [7:6] cylinder bits 8-9 [5:0] sector */ + b3[2] = c; + } + + class IMGMAKE : public Program { + public: + #ifdef WIN32 + bool OpenDisk(HANDLE* f, OVERLAPPED* o, uint8_t* name) const { + o->hEvent = INVALID_HANDLE_VALUE; + *f = CreateFile( (LPCSTR)name, GENERIC_READ | GENERIC_WRITE, + 0, // exclusive access + NULL, // default security attributes + OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, + NULL ); + + if (*f == INVALID_HANDLE_VALUE) return false; + + // init OVERLAPPED + o->Internal = 0; + o->InternalHigh = 0; + o->Offset = 0; + o->OffsetHigh = 0; + o->hEvent = CreateEvent( + NULL, // default security attributes + TRUE, // manual-reset event + FALSE, // not signaled + NULL // no name + ); + return true; + } + + void CloseDisk(HANDLE f, OVERLAPPED* o) const { + if(f != INVALID_HANDLE_VALUE) CloseHandle(f); + if(o->hEvent != INVALID_HANDLE_VALUE) CloseHandle(o->hEvent); + } + + bool StartReadDisk(HANDLE f, OVERLAPPED* o, uint8_t* buffer, Bitu offset, Bitu size) const { + o->Offset = (DWORD)offset; + if (!ReadFile(f, buffer, (DWORD)size, NULL, o) && + (GetLastError()==ERROR_IO_PENDING)) return true; + return false; + } + + // 0=still waiting, 1=catastrophic failure, 2=success, 3=sector not found, 4=crc error + Bitu CheckDiskReadComplete(HANDLE f, OVERLAPPED* o) const { + DWORD numret; + BOOL b = GetOverlappedResult( f, o, &numret,false); + if(b) return 2; + else { + int error = GetLastError(); + if(error==ERROR_IO_INCOMPLETE) return 0; + if(error==ERROR_FLOPPY_UNKNOWN_ERROR) return 5; + if(error==ERROR_CRC) return 4; + if(error==ERROR_SECTOR_NOT_FOUND) return 3; + return 1; + } + } + + Bitu ReadDisk(FILE* f, uint8_t driveletter, Bitu retries_max) { + unsigned char data[36*2*512]; + HANDLE hFloppy; + DWORD numret; + OVERLAPPED o; + DISK_GEOMETRY geom; + + uint8_t drivestring[] = "\\\\.\\x:"; drivestring[4]=driveletter; + if(!OpenDisk(&hFloppy, &o, drivestring)) return false; + + // get drive geom + DeviceIoControl( hFloppy, IOCTL_DISK_GET_DRIVE_GEOMETRY,NULL,0, + &geom,sizeof(DISK_GEOMETRY),&numret,NULL); + + switch(geom.MediaType) { + case F5_1Pt2_512: case F3_1Pt44_512: case F3_2Pt88_512: case F3_720_512: + case F5_360_512: case F5_320_512: case F5_180_512: case F5_160_512: + break; + default: + CloseDisk(hFloppy,&o); + return false; + } + Bitu total_sect_per_cyl = geom.SectorsPerTrack * geom.TracksPerCylinder; + Bitu cyln_size = 512 * total_sect_per_cyl; + + WriteOut(MSG_Get("PROGRAM_IMGMAKE_FLREAD"), + geom.Cylinders.LowPart,geom.TracksPerCylinder, + geom.SectorsPerTrack,(cyln_size*geom.Cylinders.LowPart)/1024); + WriteOut(MSG_Get("PROGRAM_IMGMAKE_FLREAD2"), "\xdb", "\xb1"); + + for(Bitu i = 0; i < geom.Cylinders.LowPart; i++) { + Bitu result; + // for each cylinder + WriteOut("%2u",i); + + if(!StartReadDisk(hFloppy, &o, &data[0], cyln_size*i, cyln_size)){ + CloseDisk(hFloppy,&o); + return false; + } + do { + result = CheckDiskReadComplete(hFloppy, &o); + CALLBACK_Idle(); + } + while (result==0); + + switch(result) { + case 1: + CloseDisk(hFloppy,&o); + return false; + case 2: // success + for(Bitu m=0; m < cyln_size/512; m++) WriteOut("\xdb"); + break; + case 3: + case 4: // data errors + case 5: + for(Bitu k=0; k < total_sect_per_cyl; k++) { + Bitu retries=retries_max; + restart_int: + StartReadDisk(hFloppy, &o, &data[512*k], cyln_size*i + 512*k, 512); + do { + result = CheckDiskReadComplete(hFloppy, &o); + CALLBACK_Idle(); + } + while (result==0); + + switch(result) { + case 1: // bad error + CloseDisk(hFloppy,&o); + return false; + case 2: // success + if(retries==retries_max) WriteOut("\xdb"); + else WriteOut("\b\b\b\xb1"); + break; + case 3: + case 4: // read errors + case 5: + if(retries!=retries_max) WriteOut("\b\b\b"); + retries--; + switch(result) { + case 3: WriteOut("x"); + case 4: WriteOut("!"); + case 5: WriteOut("?"); + } + WriteOut("%2d",retries); + + if(retries) goto restart_int; + const uint8_t badfood[]="IMGMAKE BAD FLOPPY SECTOR \xBA\xAD\xF0\x0D"; + for(uint8_t z = 0; z < 512/32; z++) + memcpy(&data[512*k+z*32],badfood,31); + WriteOut("\b\b"); + break; + } + } + break; + } + fwrite(data, 512, total_sect_per_cyl, f); + WriteOut("%2x%2x\n", data[0], data[1]); + } + // seek to 0 + StartReadDisk(hFloppy, &o, &data[0], 0, 512); + CloseDisk(hFloppy,&o); + return true; + } + #endif + + void Run(void) override { + std::string disktype; + std::string label; + std::string src; + std::string filename; + std::string dpath; + std::string tmp; + + int lbamode = -1; + uint32_t c, h, s; + uint64_t size = 0, sectors; + uint16_t alignment = 0; // if nonzero, try to align structures to this multiple of K (i.e. 4K sector alignment) + + if(control->SecureMode()) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); + return; + } + if(cmd->FindExist("-?")) { + printHelp(); + return; + } + if (cmd->FindExist("/examples")||cmd->FindExist("-examples")) { + resetcolor = true; + WriteOut(MSG_Get("PROGRAM_IMGMAKE_EXAMPLE")); + return; + } + + /* + this stuff is too frustrating + + // when only a filename is passed try to create the file on the current DOS path + // if directory+filename are passed first see if directory is a host path, if not + // maybe it is a DOSBox path. + + // split filename and path + std::string path = ""; + Bitu spos = temp_line.rfind('\\'); + if(spos==std::string::npos) { + temp_line.rfind('/'); + } + + if(spos==std::string::npos) { + // no path separator + filename=temp_line; + } else { + path=temp_line.substr(0,spos); + filename=temp_line.substr(spos+1,std::string::npos); + } + if(filename=="") + + char tbuffer[DOS_PATHLENGTH]= { 0 }; + if(path=="") { + if(!DOS_GetCurrentDir(DOS_GetDefaultDrive()+1,tbuffer)){ + printHelp(); + return; + } + dpath=(std::string)tbuffer; + } + WriteOut("path %s, filename %s, dpath %s", + path.c_str(),filename.c_str(),dpath.c_str()); + return; */ -template -T to_finite(const std::string& input) { - // Defensively set NaN from the get-go - T result = std::numeric_limits::quiet_NaN(); - size_t bytes_read = 0; - try { - const double interim = std::stod(input, &bytes_read); - if (!input.empty() && bytes_read == input.size()) - result = static_cast(interim); - } - // Capture expected exceptions stod may throw - catch (std::invalid_argument& e) { (void)e; } - catch (std::out_of_range& e) { (void)e; } - return result; -} - -/* - * Reads a floating point argument from command line, where: - * - name is a human description for the flag, ie: DELAY - * - flag is the command-line flag, ie: -d or -delay - * - default is the default value if the flag doesn't exist - * - value will be populated with the default or provided value - * - * Returns: - * true if 'value' is set to the default or read from the arg. - * false if the argument was used but could not be parsed. + + bool ForceOverwrite = false; + if (cmd->FindExist("-force",true)) + ForceOverwrite = true; + #ifdef WIN32 + // read from real floppy? + if(cmd->FindString("-source",src,true)) { + int retries = 10; + cmd->FindInt("-retries",retries,true); + if((retries < 1)||(retries > 99)) { + printHelp(); + return; + } + if((src.length()!=1) || !isalpha(src.c_str()[0])) { + // only one letter allowed + printHelp(); + return; + } + + /* temp_line is the given filename */ + if (!(cmd->FindCommand(1, temp_line))) + temp_line = "IMGMAKE.IMG"; + + bool setdir=false; + char dirCur[512] = ".", dirNew[512] = "."; + // if (!dos_kernel_disabled&&getcwd(dirCur, 512)!=NULL&&(!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"local ",6)||!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"CDRom ",6))) { + // Overlay_Drive *ddp = dynamic_cast(Drives[DOS_GetDefaultDrive()]); + // strcpy(dirNew, ddp!=NULL?ddp->getOverlaydir():Drives[DOS_GetDefaultDrive()]->GetBaseDir()); + // strcat(dirNew, Drives[DOS_GetDefaultDrive()]->curdir); + // if (chdir(dirNew)==0) setdir=true; + // } + + FILE* f = fopen(temp_line.c_str(),"r"); + if (f){ + fclose(f); + if (!ForceOverwrite) { + WriteOut(MSG_Get("PROGRAM_IMGMAKE_FILE_EXISTS"),temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + } + f = fopen(temp_line.c_str(),"wb+"); + if (!f) { + WriteOut(MSG_Get("PROGRAM_IMGMAKE_CANNOT_WRITE"),temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + if (setdir) chdir(dirCur); + // maybe delete f if it failed? + if(!ReadDisk(f, src.c_str()[0],retries)) + WriteOut(MSG_Get("PROGRAM_IMGMAKE_CANT_READ_FLOPPY")); + fclose(f); + if (setdir) runRescan("-Q"); + return; + } + #endif + // disk type + if (!(cmd->FindString("-t",disktype,true))) { + printHelp(); + return; + } + std::transform(disktype.begin(), disktype.end(), disktype.begin(), ::tolower); + + // filesystem label + cmd->FindString("-label",label,true); + + // alignment + if (cmd->FindString("-align",tmp,true)) { + const char *s = tmp.c_str(); + alignment = (uint32_t)strtoul(s,(char**)(&s),0); + /* if 'K' follows, convert K to sectors */ + if (*s == 'K' || *s == 'k') alignment *= (uint32_t)2u; + + if (alignment == (uint32_t)0 || alignment > (uint32_t)2048/*1MB*/) { + WriteOut("Invalid alignment"); + return; + } + } + + uint8_t mediadesc = 0xF8; // media descriptor byte; also used to differ fd and hd + uint16_t root_ent = 512; // FAT root directory entries: 512 is for harddisks + uint16_t disksize = 0; // disk size of floppy images + uint32_t sect_per_fat = 0; // allowable range: FAT12 1-12, FAT16 16-256, FAT32 512-2,097,152 sectors + uint16_t sectors_per_cluster = 0; // max limit: 128 + bool is_fd = false; + if(disktype=="fd_160") { + c = 40; h = 1; s = 8; mediadesc = 0xFE; root_ent = 64; sect_per_fat = 1; sectors_per_cluster = 1; + disksize = 160; is_fd = true; + } else if(disktype=="fd_180") { + c = 40; h = 1; s = 9; mediadesc = 0xFC; root_ent = 64; sect_per_fat = 2; sectors_per_cluster = 1; + disksize = 180; is_fd = true; + } else if(disktype=="fd_200") { + c = 40; h = 1; s = 10; mediadesc = 0xFC; root_ent = 64; sect_per_fat = 2; sectors_per_cluster = 2;// root_ent? + disksize = 200; is_fd = true; + } else if(disktype=="fd_320") { + c = 40; h = 2; s = 8; mediadesc = 0xFF; root_ent = 112; sect_per_fat = 1; sectors_per_cluster = 2; + disksize = 320; is_fd = true; + } else if(disktype=="fd_360") { + c = 40; h = 2; s = 9; mediadesc = 0xFD; root_ent = 112; sect_per_fat = 2; sectors_per_cluster = 2; + disksize = 360; is_fd = true; + } else if(disktype=="fd_400") { + c = 40; h = 2; s = 10; mediadesc = 0xFD; root_ent = 112; sect_per_fat = 2; sectors_per_cluster = 2; + disksize = 400; is_fd = true; + } else if(disktype=="fd_720") { + c = 80; h = 2; s = 9; mediadesc = 0xF9; root_ent = 112; sect_per_fat = 3; sectors_per_cluster = 2; + disksize = 720; is_fd = true; + } else if(disktype=="fd_1200") { + c = 80; h = 2; s = 15; mediadesc = 0xF9; root_ent = 224; sect_per_fat = 7; sectors_per_cluster = 1; + disksize = 1200; is_fd = true; + } else if(disktype=="fd_1440"||disktype=="fd"||disktype=="floppy") { + c = 80; h = 2; s = 18; mediadesc = 0xF0; root_ent = 224; sect_per_fat = 9; sectors_per_cluster = 1; + disksize = 1440; is_fd = true; + } else if(disktype=="fd_2880") { + c = 80; h = 2; s = 36; mediadesc = 0xF0; root_ent = 240; sect_per_fat = 9; sectors_per_cluster = 2; + disksize = 2880; is_fd = true; + } else if(disktype=="hd_250") { + c = 489; h = 16; s = 63; + } else if(disktype=="hd_520") { + c = 1023; h = 16; s = 63; + } else if(disktype=="hd_1gig") { + c = 1023; h = 32; s = 63; + } else if(disktype=="hd_2gig") { + c = 1023; h = 64; s = 63; + } else if(disktype=="hd_4gig") { // fseek only supports 2gb + c = 1023; h = 130; s = 63; + } else if(disktype=="hd_8gig") { // fseek only supports 2gb + c = 1023; h = 255; s = 63; + } else if(disktype=="hd_st251") { // old 40mb drive + c = 820; h = 6; s = 17; + } else if(disktype=="hd_st225") { // even older 20mb drive + c = 615; h = 4; s = 17; + } else if(disktype=="hd" || disktype=="vhd") { + // get size from parameter + std::string isize; + if (!(cmd->FindString("-size",isize,true))) { + // maybe -chs? + if (!(cmd->FindString("-chs",isize,true))){ + // user forgot -size and -chs + printHelp(); + return; + } + else { + // got chs data: -chs 1023,16,63 + if(sscanf(isize.c_str(),"%u,%u,%u",&c,&h,&s) != 3) { + WriteOut(MSG_Get("PROGRAM_IMGMAKE_BADSIZE")); + return; + } + // sanity-check chs values + if((h>255)||(c>1023)||(s>63)) { + printHelp(); + return; + } + size = (uint64_t)c * (uint64_t)h * (uint64_t)s * 512ULL; + if((size < 3*1024*1024ull) || (size > 0x1FFFFFFFFull)/*8GB*/) { + // user picked geometry resulting in wrong size + WriteOut(MSG_Get("PROGRAM_IMGMAKE_BADSIZE")); + return; + } + } + } else { + // got -size + std::istringstream stream(isize); + stream >> size; + size *= 1024*1024LL; // size in megabytes + // low limit: 3 megs, high limit: 2 terabytes + // Int13 limit would be 8 gigs + if((size < 3*1024*1024ull) || (size > 0x1FFFFFFFFFFull)/*2TB*/) { + // wrong size + WriteOut(MSG_Get("PROGRAM_IMGMAKE_BADSIZE")); + return; + } + if(disktype == "vhd" && size > 2040*1024*1024*1024ull) {/*2040GB*/ + // wrong size + WriteOut(MSG_Get("PROGRAM_IMGMAKE_BADSIZE")); + return; + } + sectors = size / 512; + + if (alignment != 0u) { + sectors += (uint64_t)(alignment - 1u); + sectors -= sectors % (uint64_t)alignment; + } + + // Now that we finally have the proper size, figure out good CHS values + if (size > 0xFFFFFFFFull/*4GB*/) { + /* beyond that point it's easier to just map like LBA and be done with it */ + h=255; + s=63; + c=sectors/(h*s); + } + else { + h=2; + while(h*1023*63 < sectors) h <<= 1; + if(h>255) h=255; + s=8; + while(h*s*1023 < sectors) s *= 2; + if(s>63) s=63; + c=sectors/(h*s); + if(c>1023) c=1023; + } + } + } else { + // user passed a wrong -t argument + printHelp(); + return; + } + + std::string t2 = ""; + if(cmd->FindExist("-bat",true)) { + t2 = "-bat"; + } + + size = (uint64_t)c * (uint64_t)h * (uint64_t)s * 512ULL; + int64_t bootsect_pos = 0; // offset of the boot sector in clusters + if(cmd->FindExist("-nofs",true)) { + bootsect_pos = -1; + } + + if (cmd->FindExist("-chs",true)) + lbamode = 0; + else if (cmd->FindExist("-lba",true)) + lbamode = 1; + else + lbamode = size > (2048ULL << 20ULL); /* automatically choose LBA for 2GB or larger images */ + + /* beyond this point clamp c */ + if (c > 1023) c = 1023; + + /* temp_line is the given filename */ + if (!(cmd->FindCommand(1, temp_line))) + temp_line = "IMGMAKE.IMG"; + + bool setdir=false; + char dirCur[512] = ".", dirNew[512] = "."; + // if (!dos_kernel_disabled&&getcwd(dirCur, 512)!=NULL&&!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"local directory", 15)) { + // Overlay_Drive *ddp = dynamic_cast(Drives[DOS_GetDefaultDrive()]); + // strcpy(dirNew, ddp!=NULL?ddp->getOverlaydir():Drives[DOS_GetDefaultDrive()]->GetBaseDir()); + // strcat(dirNew, Drives[DOS_GetDefaultDrive()]->curdir); + // if (chdir(dirNew)==0) setdir=true; + // } + + #if !defined(WIN32) && !defined(OS2) + if (setdir&&temp_line[0]!='/'&&!(temp_line[0]=='~'&&temp_line[1]=='/')) + std::replace(temp_line.begin(), temp_line.end(), '\\', '/'); + pref_struct_stat test; + std::string homedir(temp_line); + Cross::ResolveHomedir(homedir); + std::string homepath=homedir; + if (!pref_stat(dirname((char *)homepath.c_str()), &test) && test.st_mode & S_IFDIR) + temp_line = homedir; + #endif + FILE* f; + imageDiskVHD* vhd; + f = fopen(temp_line.c_str(), "r"); + if(f) { + fclose(f); + if(!ForceOverwrite) { + if(!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_FILE_EXISTS"), temp_line.c_str()); + if(setdir) chdir(dirCur); + return; + } + } + char extension[6] = {}; // care extensions longer than 3 letters such as '.vhdd' + if(temp_line.find_last_of('.') != std::string::npos) { + for(unsigned int i = 0; i < sizeof(extension) - 1; i++) { + if(temp_line.find_last_of('.') + i > temp_line.length() - 1) break; + extension[i] = temp_line[temp_line.find_last_of('.') + i]; + } + extension[sizeof(extension) - 1] = '\0'; // Terminate string just in case + } + if (!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_PRINT_CHS"),temp_line.c_str(),c,h,s); + LOG_MSG(MSG_Get("PROGRAM_IMGMAKE_PRINT_CHS"),temp_line.c_str(),c,h,s); + + // do it again for fixed chs values + sectors = size / 512; + + // create the image file + if(disktype == "vhd") { + uint32_t ret = imageDiskVHD::CreateDynamic(temp_line.c_str(), size); + switch(ret) { + case imageDiskVHD::ERROR_OPENING: + WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), temp_line.c_str()); + return; + case imageDiskVHD::ERROR_WRITING: + WriteOut(MSG_Get("PROGRAM_VHDMAKE_WRITERR"), temp_line.c_str()); + return; + } + if(imageDiskVHD::Open(temp_line.c_str(), false, (imageDisk**)&vhd) != imageDiskVHD::OPEN_SUCCESS) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), temp_line.c_str()); + return; + } + } + else { + f = fopen64(temp_line.c_str(), "wb+"); + if(!f) { + if(!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_CANNOT_WRITE"), temp_line.c_str()); + if(setdir) chdir(dirCur); + return; + } + + #if (defined (_MSC_VER) && (_MSC_VER >= 1400)) || defined(__MINGW32__) + if(fseeko64(f, (__int64)(size - 1ull), SEEK_SET)) { + #else + if(fseeko64(f, static_cast(size - 1ull), SEEK_SET)) { + #endif + if(!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_NOT_ENOUGH_SPACE"), size); + fclose(f); + unlink(temp_line.c_str()); + if(setdir) chdir(dirCur); + return; + } + uint8_t bufferbyte = 0; + if(fwrite(&bufferbyte, 1, 1, f) != 1) { + if(!dos_kernel_disabled) WriteOut(MSG_Get("PROGRAM_IMGMAKE_NOT_ENOUGH_SPACE"), size); + fclose(f); + unlink(temp_line.c_str()); + if(setdir) chdir(dirCur); + return; + } + } + // Format the image if not unrequested (and image size<2GB) + if(bootsect_pos > -1) { + uint32_t reserved_sectors = 1; /* 1 for the boot sector + BPB. FAT32 will require more */ + uint64_t vol_sectors = 0; + uint8_t fat_copies = 2; /* number of copies of the FAT */ + uint32_t partsector = 0; + uint32_t fatlimitmin; + uint32_t fatlimit; + int8_t FAT = -1; + bool spc_changed = false; + bool rootent_changed = false; + + /* Partition sector override */ + if (cmd->FindString("-partofs",tmp,true)) { + partsector = atoi(tmp.c_str()); + if (partsector == 0) { + WriteOut("Invalid -partofs\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + } + + /* FAT filesystem, user choice */ + if (cmd->FindString("-fat",tmp,true)) { + FAT = atoi(tmp.c_str()); + if (!(FAT == 12 || FAT == 16 || FAT == 32)) { + WriteOut("Invalid -fat option. Must be 12, 16, or 32\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + } + + /* FAT copies, user choice */ + if (cmd->FindString("-fatcopies",tmp,true)) { + fat_copies = atoi(tmp.c_str()); + if (fat_copies < 1u || fat_copies > 4u) { + WriteOut("Invalid -fatcopies option\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + } + + /* Sectors per cluster, user choice */ + if (cmd->FindString("-spc",tmp,true)) { + sectors_per_cluster = atoi(tmp.c_str()); + if (sectors_per_cluster < 1u || sectors_per_cluster > 128u) { + WriteOut("Invalid -spc option, out of range\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + if ((sectors_per_cluster & (sectors_per_cluster - 1u)) != 0u) { + WriteOut("Invalid -spc option, must be a power of 2\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + spc_changed = true; + } + + /* Root directory count, user choice. + * Does not apply to FAT32, which makes the root directory an allocation chain like any other directory/file. */ + if (cmd->FindString("-rootdir",tmp,true)) { + root_ent = atoi(tmp.c_str()); + if (root_ent < 1u || root_ent > 4096u) { + WriteOut("Invalid -rootdir option\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + rootent_changed = true; + } + + /* decide partition placement */ + if (mediadesc == 0xF8) { + if (partsector > (uint32_t)0) + bootsect_pos = (int64_t)partsector; + else + bootsect_pos = (int64_t)s; + } + else { + bootsect_pos = 0; + } + + if (alignment != 0u) { + bootsect_pos += alignment - 1u; + bootsect_pos -= bootsect_pos % (int64_t)alignment; + } + + if (sectors <= (uint64_t)bootsect_pos) { + WriteOut("Invalid bootsector position\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + vol_sectors = sectors - (uint64_t)bootsect_pos; + + if (alignment != 0u) { + if ((vol_sectors % alignment) != 0u) { + WriteOut("Sanity check failed: Volume size not aligned\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + } + + /* auto-decide FAT system */ + if (is_fd) FAT = 12; + else if (FAT < 0) { + bool dosver_fat32 = (dos.version.major >= 8) || (dos.version.major == 7 && dos.version.minor >= 10); + + if (vol_sectors >= 2*1024*1024*1024ull/512ull && !dosver_fat32) /* 2GB or larger */ + FAT = 32; + else if (vol_sectors >= 512*1024*1024ull/512ull && dosver_fat32) /* 512MB or larger */ + FAT = 32; + else if (vol_sectors >= 12*1024*1024ull/512ull) /* 12MB or larger */ + FAT = 16; + else + FAT = 12; + } + + /* highest cluster number + 1 */ + switch (FAT) { + case 32: + fatlimit = 0x0FFFFFF6u; + fatlimitmin = 0xFFF6u; + break; + case 16: + fatlimit = 0xFFF6u; + fatlimitmin = 0xFF6u; + break; + case 12: + fatlimit = 0xFF6u; + fatlimitmin = 0u; + break; + default: + abort(); + } + + /* FAT32 increases reserved area to at least 7. Microsoft likes to use 32 */ + if (FAT >= 32) + reserved_sectors = 32; + + if (alignment != 0u) { + reserved_sectors += alignment - 1u; + reserved_sectors -= reserved_sectors % alignment; + } + + uint8_t sbuf[512]; + if(mediadesc == 0xF8) { + // is a harddisk: write MBR + memcpy(sbuf,freedos_mbr,512); + // active partition + sbuf[0x1be]=0x80; + // start head - head 0 has the partition table, head 1 first partition + // start sector with bits 8-9 of start cylinder in bits 6-7 + // start cylinder bits 0-7 + lba2chs3(sbuf+0x1bf,bootsect_pos,c,h,s); + // OS indicator + if (FAT < 32 && (bootsect_pos+vol_sectors) < 65536) { /* 32MB or smaller */ + if (FAT >= 16) + sbuf[0x1c2]=0x04; /* FAT16 within the first 32MB */ + else + sbuf[0x1c2]=0x01; /* FAT12 within the first 32MB */ + } + else if (!lbamode) { /* 4GB or smaller */ + if (FAT >= 32) + sbuf[0x1c2]=0x0B; /* FAT32 C/H/S */ + else + sbuf[0x1c2]=0x06; /* FAT12/FAT16 C/H/S */ + } + else { + if (FAT >= 32) + sbuf[0x1c2]=0x0C; /* FAT32 LBA */ + else + sbuf[0x1c2]=0x0E; /* FAT12/FAT16 LBA */ + } + // end head (0-based) + // end sector with bits 8-9 of end cylinder (0-based) in bits 6-7 + // end cylinder (0-based) bits 0-7 + lba2chs3(sbuf+0x1c3,bootsect_pos+vol_sectors-1ul,c,h,s); + // sectors preceding partition1 (one head) + host_writed(&sbuf[0x1c6],(uint32_t)bootsect_pos); + // length of partition1, align to chs value + host_writed(&sbuf[0x1ca],vol_sectors); + + // write partition table + if(disktype != "vhd") { + fseeko64(f, 0, SEEK_SET); + fwrite(&sbuf, 512, 1, f); + } + else { + vhd->Write_AbsoluteSector(0, sbuf); + } + } + + // set boot sector values + memset(sbuf,0,512); + // TODO boot code jump + if (FAT >= 32) { + sbuf[0]=0xEB; sbuf[1]=0x58; sbuf[2]=0x90; // Windows 98 values + } + else { + sbuf[0]=0xEB; sbuf[1]=0x3c; sbuf[2]=0x90; + } + // OEM + if (FAT >= 32) { + sprintf((char*)&sbuf[0x03],"MSWIN4.1"); + } else { + sprintf((char*)&sbuf[0x03],"MSDOS5.0"); + } + // bytes per sector: always 512 + host_writew(&sbuf[BytsPerSec],512); + // sectors per cluster: 1,2,4,8,16,... + // NOTES: SCANDISK.EXE will hang if you ask it to check a FAT12 filesystem with 128 sectors/cluster. + if (sectors_per_cluster == 0) { + sectors_per_cluster = 1; + /* one sector per cluster on anything larger than 200KB is a bit wasteful (large FAT tables). + * Improve capacity by starting from a larger value.*/ + if (vol_sectors >= 400) { + unsigned int tmp_fatlimit; + + /* Windows 98 likes multiples of 4KB, which is actually reasonable considering + * that it keeps FAT32 efficient. Also, Windows 98 SETUP will crash if sectors/cluster + * is too small. Ref: [https://github.com/joncampbell123/dosbox-x/issues/1553#issuecomment-651880604] + * and [http://www.helpwithwindows.com/windows98/fat32.html] */ + if (FAT >= 32) { + if (vol_sectors >= 67108864/*32GB*/) + sectors_per_cluster = 64; /* 32KB (64*512) */ + else if (vol_sectors >= 33554432/*16GB*/) + sectors_per_cluster = 32; /* 16KB (32*512) */ + else if (vol_sectors >= 16777216/*8GB*/) + sectors_per_cluster = 16; /* 8KB (16*512) */ + else + sectors_per_cluster = 8; /* 4KB (8*512) */ + } + else { + /* 1 sector per cluster is very inefficient */ + if (vol_sectors >= 6144000/*3000MB*/) + sectors_per_cluster = 8; + else if (vol_sectors >= 1048576/*512MB*/) + sectors_per_cluster = 4; + else if (vol_sectors >= 131072/*64MB*/) + sectors_per_cluster = 2; + } + + /* no more than 5% of the disk */ + switch (FAT) { + case 12: tmp_fatlimit = ((((vol_sectors / 20u) * (512u / fat_copies)) / 3u) * 2u) + 2u; break; + case 16: tmp_fatlimit = (((vol_sectors / 20u) * (512u / fat_copies)) / 2u) + 2u; break; + case 32: tmp_fatlimit = (((vol_sectors / 20u) * (512u / fat_copies)) / 4u) + 2u; break; + default: abort(); + } + + while ((vol_sectors/sectors_per_cluster) >= (tmp_fatlimit - 2u) && sectors_per_cluster < 0x80u) sectors_per_cluster <<= 1; + } + } + + /* if alignment is a power of 2, align sectors per cluster to it */ + if (bitop::ispowerof2(alignment)) { + while (sectors_per_cluster < 0x80u && sectors_per_cluster < alignment) sectors_per_cluster <<= 1; + } + + /* FAT12/FAT16 size the root directory so that it is aligned, which then aligns the data area following it */ + if (alignment != 0u && FAT < 32) { + const uint32_t t_alignment = alignment * (512u / 32u); /* 512 bytes/sector, 32 bytes per dirent = number of root dirents per sector */ + root_ent += t_alignment - 1; + root_ent -= root_ent % t_alignment; + } + + while (!is_fd && (vol_sectors/sectors_per_cluster) >= (fatlimit - 2u) && sectors_per_cluster < 0x80u) sectors_per_cluster <<= 1; + sbuf[SecPerClus]=(uint8_t)sectors_per_cluster; + // reserved sectors + host_writew(&sbuf[RsvdSecCnt],reserved_sectors); + // Number of FATs + sbuf[NumFATs] = fat_copies; + // Root entries if not FAT32 + if (FAT < 32) host_writew(&sbuf[RootEntCnt],root_ent); + // sectors (under 32MB) if not FAT32 and less than 65536 + if (FAT < 32 && vol_sectors < 65536ul) host_writew(&sbuf[TotSec16],vol_sectors); + // sectors (32MB or larger or FAT32) + if (FAT >= 32 || vol_sectors >= 65536ul) host_writed(&sbuf[TotSec32],vol_sectors); + else host_writed(&sbuf[TotSec32],0); + // media descriptor + sbuf[Media]=mediadesc; + // needed entries: (sectors per cluster) + uint64_t clusters = vol_sectors / sectors_per_cluster; // initial estimate + + // sectors per FAT + if (FAT >= 32) sect_per_fat = ((clusters*4u)+511u)/512u; + else if (FAT >= 16) sect_per_fat = ((clusters*2u)+511u)/512u; + // Use standard sect_per_fat values for standard floppy images, otherwise it may required to be adjusted + else if (!is_fd || sect_per_fat == 0 || (is_fd && (rootent_changed || (fat_copies != 2)))) sect_per_fat = ((((clusters+1u)/2u)*3u)+511u)/512u; + + if (alignment != 0u) { + if (alignment % fat_copies) { + sect_per_fat += alignment - 1u; + sect_per_fat -= sect_per_fat % alignment; + } + else { + const uint32_t t_alignment = alignment / fat_copies; /* we could align sect_per_fat based on ALL copies of the FAT table */ + sect_per_fat += t_alignment - 1u; + sect_per_fat -= sect_per_fat % t_alignment; + } + } + + if (alignment != 0u) { + if ((((uint64_t)sect_per_fat * (uint64_t)fat_copies) % (uint64_t)alignment) != 0u) { + WriteOut("Sanity check failed: FAT tables not aligned\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + } + + if (FAT < 32 && sect_per_fat > 256u) { + WriteOut("Error: Generated filesystem has more than 256 sectors per FAT and is not FAT32\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + + uint32_t root_ent_sec = 0; + uint64_t data_area = vol_sectors - reserved_sectors - (sect_per_fat * fat_copies); + if (FAT < 32) { + root_ent_sec = ((root_ent * 32u) + 511u) / 512u; + data_area -= root_ent_sec; + } + clusters = data_area / sectors_per_cluster; + if (FAT < 32) host_writew(&sbuf[FATSz16],(uint16_t)sect_per_fat); + + if (alignment != 0u) { + if ((root_ent_sec % alignment) != 0u) { + WriteOut("Sanity check failed: Volume size not aligned\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + } + + /* Too many or to few clusters can foul up FAT12/FAT16/FAT32 detection and cause corruption! */ + if ((clusters+2u) < fatlimitmin) { + WriteOut("Error: Generated filesystem has too few clusters given the parameters\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + if ((clusters+2u) > fatlimit) { + clusters = fatlimit-2u; + WriteOut("Warning: Cluster count is too high given the volume size. Reporting a\n"); + WriteOut(" smaller sector count.\n"); + /* Well, if the user wants an oversized partition, hack the total sectors fields to make it work */ + uint32_t adj_vol_sectors = + (uint32_t)(reserved_sectors + (sect_per_fat * fat_copies) + + (((root_ent * 32u) + 511u) / 512u) + (clusters * sectors_per_cluster)); + + // sectors (under 32MB) if not FAT32 and less than 65536 + if (adj_vol_sectors < 65536ul) host_writew(&sbuf[TotSec16],(uint16_t)adj_vol_sectors); + // sectors (32MB or larger or FAT32) + if (adj_vol_sectors >= 65536ul) host_writed(&sbuf[TotSec32],adj_vol_sectors); + else host_writed(&sbuf[TotSec32],0); + } + + const unsigned long long first_cluster = + (unsigned long long)bootsect_pos + reserved_sectors + + ((unsigned long long)sect_per_fat * (unsigned long long)fat_copies) + + (unsigned long long)root_ent_sec; + + /* do not validate alignment of data area, because some of the fd and hd presets might + * violate it, but certainly make sure that the first cluster is aligned */ + if (alignment != 0u) { + if ((first_cluster % (unsigned long long)alignment) != 0ull) { + WriteOut("Sanity check failed: First cluster not aligned\n"); + fclose(f); + unlink(temp_line.c_str()); + if (setdir) chdir(dirCur); + return; + } + } + + // sectors per track + host_writew(&sbuf[SecPerTrk],s); + // heads + host_writew(&sbuf[NumHeads],h); + // hidden sectors + host_writed(&sbuf[HiddSec],(uint32_t)bootsect_pos); + /* after 0x24, FAT12/FAT16 and FAT32 diverge in structure */ + if (FAT >= 32) { + host_writed(&sbuf[FATSz32],sect_per_fat); + sbuf[0x28] = 0x00; // FAT is mirrored at runtime because that is what DOSBox-X's FAT driver does + host_writew(&sbuf[0x2A],0x0000); // FAT32 version 0.0 + host_writed(&sbuf[0x2C],2); // root directory starting cluster + host_writew(&sbuf[0x30],1); // sector number in reserved area of FSINFO structure + host_writew(&sbuf[0x32],6); // sector number in reserved area of backup boot sector + // BIOS drive + sbuf[DrvNum32] = (mediadesc == 0xF8) ? 0x80 : 0x00; + // ext. boot signature + sbuf[BootSig32] = 0x29; + // Volume label + sprintf((char*)&sbuf[VolLab32], "NO NAME "); + // volume serial number + // let's use the BIOS time (cheap, huh?) + host_writed(&sbuf[VolID32], mem_readd(BIOS_TIMER)); + // file system type + sprintf((char*)&sbuf[FilSysType32],"FAT32 "); + } + else { /* FAT12/FAT16 */ + // BIOS drive + sbuf[BootSig] = 0x29; + // Volume label + sprintf((char*)&sbuf[VolLab], "NO NAME "); + // volume serial number + // let's use the BIOS time (cheap, huh?) + host_writed(&sbuf[VolID], mem_readd(BIOS_TIMER)); + if(is_fd) { + uint8_t index = 0; + while(DiskGeometryList[index].cylcount != 0) { + if(DiskGeometryList[index].ksize == disksize) { + sbuf[Media] = DiskGeometryList[index].mediaid; + mediadesc = DiskGeometryList[index].mediaid; + host_writew(&sbuf[SecPerTrk],DiskGeometryList[index].secttrack); + host_writew(&sbuf[NumHeads], DiskGeometryList[index].headscyl); + host_writew(&sbuf[BytsPerSec], DiskGeometryList[index].bytespersect); + sbuf[SecPerClus] = spc_changed ? sectors_per_cluster : DiskGeometryList[index].sectcluster; + host_writew(&sbuf[RootEntCnt], rootent_changed ? root_ent : DiskGeometryList[index].rootentries); + host_writew(&sbuf[FATSz16],sect_per_fat); + break; + } + index++; + } + } + // BIOS drive + sbuf[DrvNum] = (mediadesc == 0xF8) ? 0x80 : 0x00; + // file system type + if (FAT >= 16) sprintf((char*)&sbuf[FilSysType],"FAT16 "); + else sprintf((char*)&sbuf[FilSysType],"FAT12 "); + } + // boot sector signature + host_writew(&sbuf[BootSign],0xAA55); + + // if anything should try to boot this partition, add code to print an error message instead of + // letting the CPU run wild through not executable code. + if (FAT >= 32) { + // the code expects to load a string from a fixed address. + // we're relocating it to make room for FAT32 structures so some patching is required. + memcpy(sbuf+BootCode32,this_is_not_a_bootable_partition+0x3E,BootSign - BootCode32); + host_writew(sbuf+0x5D,0x7C77); // 0x7C5D: MOV SI, we are patching the + } + else { + memcpy(sbuf+BootCode,this_is_not_a_bootable_partition+0x3E,BootSign - BootCode); + } + + // write label + if (!label.empty()) { + const char *s = label.c_str(); + unsigned int i; + char *d; + + if (FAT >= 32) d = (char*)sbuf + VolLab32; + else d = (char*)sbuf + VolLab; + + for (i=0;i < 11 && *s;i++) *d++ = *s++; + for ( ;i < 11; i++) *d++ = ' '; + } + + // write the boot sector + if(disktype == "vhd") { + vhd->Write_AbsoluteSector(bootsect_pos, sbuf); + } + else { + fseeko64(f, bootsect_pos * 512, SEEK_SET); + fwrite(&sbuf, 512, 1, f); + } + // FAT32: Write backup copy too. + // The BPB we wrote says sector 6 from start of volume + if(FAT >= 32) { + if(disktype != "vhd") { + fseeko64(f, (bootsect_pos + 6u) * 512, SEEK_SET); + fwrite(&sbuf, 512, 1, f); + } + else { + vhd->Write_AbsoluteSector((bootsect_pos + 6u), sbuf); + } + } + // FAT32: Write FSInfo sector too at sector 1 from start of volume. + // Windows 98 behavior shows that the FSInfo is duplicated + // along with the boot sector. + if (FAT >= 32) { + memset(sbuf,0,512); + host_writed(&sbuf[0x000],0x41615252); /* "RRaA" */ + host_writed(&sbuf[0x1e4],0x61417272); /* "rrAa" */ + host_writed(&sbuf[0x1e8],(uint32_t)(clusters-1)); /* Last known free cluster count */ + host_writed(&sbuf[0x1ec],3); /* Next free cluster. We used 2 for the root dir, so 3 is next */ + host_writed(&sbuf[0x1fc],0xAA550000); /* signature */ + if(disktype != "vhd") { + fseeko64(f, (bootsect_pos + 1u) * 512, SEEK_SET); + fwrite(&sbuf, 512, 1, f); + fseeko64(f, (bootsect_pos + 6u + 1u) * 512, SEEK_SET); + fwrite(&sbuf, 512, 1, f); + } + else { + vhd->Write_AbsoluteSector((bootsect_pos + 1u), sbuf); + vhd->Write_AbsoluteSector((bootsect_pos + 6u +1u), sbuf); + } + } + + // write FATs + memset(sbuf,0,512); + if (FAT >= 32) { + host_writed(&sbuf[0],0x0FFFFF00 | mediadesc); + host_writed(&sbuf[4],0x0FFFFFFF); + + /* The code above marks cluster 2 as the start of the root directory. */ + host_writed(&sbuf[8],0x0FFFFFFF); + } + else if (FAT >= 16) + host_writed(&sbuf[0],0xFFFFFF00 | mediadesc); + else + host_writed(&sbuf[0],0xFFFF00 | mediadesc); + + for (unsigned int fat=0;fat < fat_copies;fat++) { + if(disktype != "vhd") { + fseeko64(f, (off_t)(((unsigned long long)bootsect_pos + reserved_sectors + (unsigned long long)sect_per_fat * (unsigned long long)fat) * 512ull), SEEK_SET); + fwrite(&sbuf, 512, 1, f); + } + else { + vhd->Write_AbsoluteSector((unsigned long long)bootsect_pos + reserved_sectors + (unsigned long long)sect_per_fat * (unsigned long long)fat, sbuf); + } + } + + // write label in root directory, as first entry + if (!label.empty()) { + const char *s = label.c_str(); + unsigned int i; + char *d; + + unsigned long long sec; + + /* FAT12/FAT16: This points at the root directory area. + * FAT32: This points at the root directory only because this code constructed the root directory allocation chain + * starting at cluster 2, which is the first cluster of the data area. */ + sec = (unsigned long long)bootsect_pos + reserved_sectors + + ((unsigned long long)sect_per_fat * (unsigned long long)fat_copies); + + memset(sbuf,0,512); + + d = (char*)sbuf; + for (i=0;i < 11 && *s;i++) *d++ = *s++; + for ( ;i < 11; i++) *d++ = ' '; + sbuf[11] = 0x08; /* volume label */ + + if(disktype != "vhd") { + fseeko64(f, (off_t)(sec * 512ull), SEEK_SET); + fwrite(&sbuf, 512, 1, f); + } + else { + vhd->Write_AbsoluteSector(sec, sbuf); + } + } + + // warning + if ((sectors_per_cluster*512ul) >= 65536ul) + WriteOut("WARNING: Cluster sizes >= 64KB are not compatible with MS-DOS and SCANDISK\n"); + } + // write VHD footer if requested + if((mediadesc == 0xF8) && disktype != "vhd" && !strcasecmp(extension, ".vhd")) { + imageDiskVHD::VHDFooter footer; + footer.SetDefaults(); + footer.dataOffset = 0xFFFFFFFFFFFFFFFF; + footer.originalSize = footer.currentSize = size; + footer.geometry.cylinders = c; + footer.geometry.heads = h; + footer.geometry.sectors = s; + footer.diskType = imageDiskVHD::VHD_TYPE_FIXED; + imageDiskVHD::mk_uuid((uint8_t*)footer.uniqueId); + footer.checksum = footer.CalculateChecksum(); + footer.SwapByteOrder(); + // write footer + fseeko64(f, 0L, SEEK_END); + fwrite(&footer,512,1,f); + } + if(disktype != "vhd") { + fclose(f); + } + else { + delete vhd; + } + // create the batch file + if(t2 == "-bat") { + if(temp_line.length() > 3) { + t2 = temp_line.substr(0,temp_line.length()-4) + ".bat"; + } else { + t2 = temp_line + ".bat"; + } + WriteOut("%s\n",t2.c_str()); + f = fopen(t2.c_str(),"wb+"); + if (!f) { + WriteOut(MSG_Get("PROGRAM_IMGMAKE_CANNOT_WRITE"),t2.c_str()); + if (setdir) { + chdir(dirCur); + runRescan("-Q"); + } + return; + } + + if (bootsect_pos < 0) /* -nofs */ + fprintf(f,"imgmount 2 %s -size 512,%u,%u,%u\r\n",temp_line.c_str(),s,h,c); + else + fprintf(f,"imgmount c %s -size 512,%u,%u,%u\r\n",temp_line.c_str(),s,h,c); + + fclose(f); + } + if (setdir) { + chdir(dirCur); + runRescan("-Q"); + } + return; + } + void printHelp() { // maybe hint parameter? + resetcolor = true; + WriteOut(MSG_Get("PROGRAM_IMGMAKE_SYNTAX")); + } + }; + + static void IMGMAKE_ProgramStart(Program * * make) { + *make=new IMGMAKE; + } + + void runImgmake(const char *str) { + IMGMAKE imgmake; + imgmake.cmd=new CommandLine("IMGMAKE", str); + imgmake.Run(); + } + + void swapInDrive(int drive, unsigned int position=0); + class IMGSWAP : public Program + { + public: + void ListImgSwaps(void) { + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; + /* Command uses dta so set it to our internal dta */ + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + WriteOut(MSG_Get("PROGRAM_IMGSWAP_STATUS")); + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),MSG_Get("DRIVE"),MSG_Get("TYPE"),MSG_Get("LABEL"),MSG_Get("SWAP_SLOT")); + int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + if (!cols) cols=80; + for(int p = 1;p < cols;p++) WriteOut("-"); + WriteOut("\n"); + bool none=true; + for (int d = 0;d < DOS_DRIVES;d++) { + if (!Drives[d] || (strncmp(Drives[d]->GetInfo(), "fatDrive ", 9) && strncmp(Drives[d]->GetInfo(), "isoDrive ", 9))||(int)DriveManager::GetDisksSize(d)<2) continue; + char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; + bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); + if (ret) { + dta.GetResult(name,lname,size,hsize,date,time,attr); + DOS_FindNext(); //Mark entry as invalid + } else name[0] = 0; + + /* Change 8.3 to 11.0 */ + const char* dot = strchr(name, '.'); + if(dot && (dot - name == 8) ) { + name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; + } + + root[1] = 0; //This way, the format string can be reused. + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name,DriveManager::GetDrivePosition(d)); + none=false; + } + if (none) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); + dos.dta(save_dta); + } + void Run() override + { + //Hack To allow long commandlines + ChangeToLongCmd(); + + if(cmd->FindExist("/?", true) || cmd->FindExist("-?", true) || cmd->FindExist("?", true)) { + resetcolor = true; + WriteOut("Swaps floppy, hard drive and optical disc images.\n\n" + "\033[32;1mIMGSWAP\033[0m \033[37;1mdrive\033[0m \033[36;1m[position]\033[0m\n" + " \033[37;1mdrive\033[0m Drive letter to swap the image.\n" + " \033[36;1m[position]\033[0m Disk position to swap to.\n"); + return; + } + if (!cmd->GetCount()) { + ListImgSwaps(); + return; + } + if (!cmd->FindCommand(1,temp_line) || (temp_line.size() > 2) || ((temp_line.size()>1) && (temp_line[1]!=':')) || (!(temp_line[0] >= 'A' && temp_line[0] <= 'Z') && !(temp_line[0] >= 'a' && temp_line[0] <= 'z'))) { + WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); + return; + } + int d=temp_line[0] - (temp_line[0] >= 'a' && temp_line[0] <= 'z' ? 'a' : 'A'); + if (!Drives[d] || (strncmp(Drives[d]->GetInfo(), "fatDrive ", 9) && strncmp(Drives[d]->GetInfo(), "isoDrive ", 9)) || (int)DriveManager::GetDisksSize(d)<2) { + ListImgSwaps(); + return; + } + if (cmd->FindCommand(2,temp_line)) { + int swap=atoi(temp_line.c_str()); + if (swap<1||swap>DriveManager::GetDisksSize(d)) { + WriteOut(MSG_Get("PROGRAM_IMGSWAP_ERROR"), DriveManager::GetDisksSize(d)); + return; + } + swapInDrive(d,swap); + } else + swapInDrive(d); + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; + /* Command uses dta so set it to our internal dta */ + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),MSG_Get("DRIVE"),MSG_Get("TYPE"),MSG_Get("LABEL"),MSG_Get("SWAP_SLOT")); + int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + if (!cols) cols=80; + for(int p = 1;p < cols;p++) WriteOut("-"); + WriteOut("\n"); + char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; + bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); + if (ret) { + dta.GetResult(name,lname,size,hsize,date,time,attr); + DOS_FindNext(); //Mark entry as invalid + } else name[0] = 0; + + /* Change 8.3 to 11.0 */ + const char* dot = strchr(name, '.'); + if(dot && (dot - name == 8) ) { + name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; + } + + root[1] = 0; //This way, the format string can be reused. + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name,DriveManager::GetDrivePosition(d)); + dos.dta(save_dta); + } + }; + + void IMGSWAP_ProgramStart(Program** make) + { + *make = new IMGSWAP; + } + + // LOADFIX + + class LOADFIX : public Program { + public: + void Run(void) override; + }; + + bool XMS_Active(void); + Bitu XMS_AllocateMemory(Bitu size, uint16_t& handle); + Bitu XMS_FreeMemory(Bitu handle); + uint8_t EMM_AllocateMemory(uint16_t pages,uint16_t & dhandle,bool can_allocate_zpages); + uint8_t EMM_ReleaseMemory(uint16_t handle); + bool EMS_Active(void); + + /* HIMEM.SYS does not store who owns what block, so for -D or -F to work, + * we need to keep track of handles ourself */ + std::vector LOADFIX_xms_handles; + std::vector LOADFIX_ems_handles; + + void LOADFIX_OnDOSShutdown(void) { + LOADFIX_xms_handles.clear(); + LOADFIX_ems_handles.clear(); + } + + void LOADFIX::Run(void) + { + uint16_t commandNr = 1; + Bitu kb = 64; + bool xms = false; + bool ems = false; + bool opta = false; + + if (cmd->FindExist("-xms",true) || cmd->FindExist("/xms",true)) { + xms = true; + kb = 1024; + } + + if (cmd->FindExist("-ems",true) || cmd->FindExist("/ems",true)) { + ems = true; + kb = 1024; + } + + if (cmd->FindExist("-a",true) || cmd->FindExist("/a",true)) + opta = true; + + if (cmd->GetCount()==1 && (cmd->FindExist("-?", false) || cmd->FindExist("/?", false))) { + resetcolor = true; + WriteOut(MSG_Get("PROGRAM_LOADFIX_HELP")); + return; + } + + if (cmd->FindCommand(commandNr,temp_line)) { + if (temp_line[0]=='-' || (temp_line[0]=='/')) { + char ch = temp_line[1]; + if ((*upcase(&ch)=='D') || (*upcase(&ch)=='F')) { + // Deallocate all + if (ems) { + for (auto i=LOADFIX_ems_handles.begin();i!=LOADFIX_ems_handles.end();i++) { + if (EMM_ReleaseMemory(*i)) + WriteOut("XMS handle %u: unable to free",*i); + } + LOADFIX_ems_handles.clear(); + WriteOut(MSG_Get("PROGRAM_LOADFIX_DEALLOCALL"),kb); + } + else if (xms) { + for (auto i=LOADFIX_xms_handles.begin();i!=LOADFIX_xms_handles.end();i++) { + if (XMS_FreeMemory(*i)) + WriteOut("XMS handle %u: unable to free",*i); + } + LOADFIX_xms_handles.clear(); + WriteOut(MSG_Get("PROGRAM_LOADFIX_DEALLOCALL"),kb); + } + else { + DOS_FreeProcessMemory(0x40); + WriteOut(MSG_Get("PROGRAM_LOADFIX_DEALLOCALL"),kb); + } + return; + } else { + // Set mem amount to allocate + kb = (Bitu)atoi(temp_line.c_str()+1); + if (kb==0) kb=xms?1024:64; + commandNr++; + } + } + } + + // Allocate Memory + if (ems) { + if (EMS_Active()) { + uint16_t handle; + Bitu err; + + /* EMS allocates in 16kb increments */ + kb = (kb + 15u) & (~15u); + + err = EMM_AllocateMemory((uint16_t)(kb/16u)/*16KB pages*/,/*&*/handle,false); + if (err == 0) { + WriteOut("EMS block allocated (%uKB)\n",kb); + LOADFIX_ems_handles.push_back(handle); + } + else { + WriteOut("Unable to allocate EMS block\n"); + } + } + else { + WriteOut("EMS not active\n"); + } + } + else if (xms) { + if (XMS_Active()) { + uint16_t handle; + Bitu err; + + err = XMS_AllocateMemory(kb,/*&*/handle); + if (err == 0) { + WriteOut("XMS block allocated (%uKB)\n",kb); + LOADFIX_xms_handles.push_back(handle); + } + else { + WriteOut("Unable to allocate XMS block\n"); + } + } + else { + WriteOut("XMS not active\n"); + } + } + else { + uint16_t segment; + uint16_t blocks = (uint16_t)(kb*1024/16); + if (DOS_AllocateMemory(&segment,&blocks)) { + DOS_MCB mcb((uint16_t)(segment-1)); + if (opta) { + if (segment < 0x1000) { + uint16_t needed = 0x1000 - segment; + if (DOS_ResizeMemory(segment,&needed)) + kb=needed*16/1024; + } + else { + DOS_FreeMemory(segment); + WriteOut("Lowest MCB is above 64KB, nothing allocated\n"); + return; + } + } + mcb.SetPSPSeg(0x40); // use fake segment + WriteOut(MSG_Get("PROGRAM_LOADFIX_ALLOC"),kb); + // Prepare commandline... + if (cmd->FindCommand(commandNr++,temp_line)) { + // get Filename + char filename[128]; + safe_strncpy(filename,temp_line.c_str(),128); + // Setup commandline + char args[256 + 1]; + args[0] = 0; + bool found = cmd->FindCommand(commandNr++, temp_line); + while (found) { + if (strlen(args) + temp_line.length() + 1 > 256) break; + strcat(args, temp_line.c_str()); + found = cmd->FindCommand(commandNr++, temp_line); + if (found) strcat(args, " "); + } + // Use shell to start program + DOS_Shell shell; + shell.Execute(filename,args); + DOS_FreeMemory(segment); + WriteOut(MSG_Get("PROGRAM_LOADFIX_DEALLOC"),kb); + } + } else { + WriteOut(MSG_Get("PROGRAM_LOADFIX_ERROR"),kb); + } + } + } + + static void LOADFIX_ProgramStart(Program * * make) { + *make=new LOADFIX; + } + + // RESCAN + + class RESCAN : public Program { + public: + void Run(void) override; + }; + + void RESCAN::Run(void) + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Rescans for changes on mounted drives made on the host by clearing caches.\n\nRESCAN [/A] [/Q]\nRESCAN [drive:] [/Q]\n\n [/A]\t\tRescan all drives\n [/Q]\t\tEnable quiet mode\n [drive:]\tThe drive to rescan\n\nType RESCAN with no parameters to rescan the current drive.\n"); + return; + } + bool all = false, quiet = false; + if (cmd->FindExist("-q",true) || cmd->FindExist("/q",true)) + quiet = true; + + uint8_t drive = DOS_GetDefaultDrive(); + if(cmd->FindCommand(1,temp_line)) { + //-A -All /A /All + if(temp_line.size() >= 2 && (temp_line[0] == '-' ||temp_line[0] =='/')&& (temp_line[1] == 'a' || temp_line[1] =='A') ) all = true; + else if(temp_line.size() == 2 && temp_line[1] == ':') { + lowcase(temp_line); + drive = temp_line[0] - 'a'; + } + } + // Get current drive + if (all) { + for(Bitu i =0; iEmptyCache(); + } + if (!quiet) WriteOut(MSG_Get("PROGRAM_RESCAN_SUCCESS")); + } else { + if (drive < DOS_DRIVES && Drives[drive]) { + Drives[drive]->EmptyCache(); + if (!quiet) WriteOut(MSG_Get("PROGRAM_RESCAN_SUCCESS")); + } else + if (!quiet) WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_NOT_FOUND"), 'A'+drive); + } + } + + static void RESCAN_ProgramStart(Program * * make) { + *make=new RESCAN; + } + + void runRescan(const char *str) { + RESCAN rescan; + rescan.cmd=new CommandLine("RESCAN", str); + rescan.Run(); + } + + /* TODO: This menu code sucks. Write a better one. */ + class INTRO : public Program { + public: + void DisplayMount(void) { + /* Basic mounting has a version for each operating system. + * This is done this way so both messages appear in the language file*/ + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_START")); + if (machine == MCH_PC98) { + #if (WIN32) + WriteOut("\033[44;1m\x86\x52\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x56\n" + "\033[44;1m\x86\x46\033[0m "); + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXST_WINDOWS")); + WriteOut(" \033[44;1m\x86\x46\033[0m\n\033[44;1m\x86\x46\033[0m \033[44;1m\x86\x46\033[0m\n\033[44;1m\x86\x46\033[0m "); + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXEN_WINDOWS")); + WriteOut(" \033[37m \033[44;1m\x86\x46\033[44;1m\n" + "\033[44;1m\x86\x5A\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x5E\033[0m\n" + ); + #else + WriteOut("\033[44;1m\x86\x52\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x56\n" + "\x86\x46 "); + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXST_OTHER")); + WriteOut(" \x86\x46\n\x86\x46 \x86\x46\n\x86\x46 "); + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXEN_OTHER")); + WriteOut(" \033[37m \x86\x46\n" + "\x86\x5A\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44" + "\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x5E\033[0m\n" + ); + #endif + } else { + #if (WIN32) + WriteOut("\033[44;1m\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\n" + "\xBA "); + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXST_WINDOWS")); + WriteOut("\xBA\n\xBA \xBA\n\xBA "); + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXEN_WINDOWS")); + WriteOut("\xBA\n" + "\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\033[0m\n"); + #else + WriteOut("\033[44;1m\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\n" + "\xBA "); + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXST_OTHER")); + WriteOut("\xBA\n\xBA \xBA\n\xBA "); + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_EXEN_OTHER")); + WriteOut("\xBA\n" + "\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\033[0m\n"); + #endif + } + WriteOut(MSG_Get("PROGRAM_INTRO_MOUNT_END")); + } + void DisplayUsage(void) { + uint8_t c;uint16_t n=1; + WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_TOP")); + WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_1")); + DOS_ReadFile (STDIN,&c,&n); + WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_TOP")); + WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_2")); + DOS_ReadFile (STDIN,&c,&n); + WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_TOP")); + WriteOut(MSG_Get("PROGRAM_INTRO_USAGE_3")); + DOS_ReadFile (STDIN,&c,&n); + } + void DisplayIntro(void) { + WriteOut(MSG_Get("PROGRAM_INTRO")); + WriteOut("\033[44m\033[K\033[0m\n\033[44m\033[K\033[1m\033[1m\t\t\t\t\t\t\t "); + WriteOut(MSG_Get("PROGRAM_INTRO_MENU_UP")); + if (machine == MCH_PC98) + WriteOut("\033[0m\n" + "\033[44m\033[K\033[1m\033[1m \x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\x86\x43\033[0m\n" + "\033[44m\033[K\033[0m\n" + ); + else + WriteOut(" \033[0m\n" + "\033[44m\033[K\033[1m\033[1m \xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\033[0m\n" + "\033[44m\033[K\033[0m\n" + ); + } + void DisplayMenuBefore(void) { WriteOut("\033[44m\033[K\033[33m\033[1m \033[0m "); } + void DisplayMenuCursorStart(void) { + if (machine == MCH_PC98) { + WriteOut("\033[44m\033[K\033[1m\033[33;44m \x1C\033[0m\033[5;37;44m "); + } else { + WriteOut("\033[44m\033[K\033[1m\033[33;44m \x10\033[0m\033[5;37;44m "); + } + } + void DisplayMenuCursorEnd(void) { WriteOut("\033[0m\n"); } + void DisplayMenuNone(void) { WriteOut("\033[44m\033[K\033[0m\n"); } + + bool CON_IN(uint8_t * data) const { + uint8_t c; + uint16_t n=1; + + /* handle arrow keys vs normal input, + * with special conditions for PC-98 and IBM PC */ + if (!DOS_ReadFile(STDIN,&c,&n) || n == 0) return false; + + if (IS_PC98_ARCH) { + /* translate PC-98 arrow keys to IBM PC escape for the caller */ + if (c == 0x0B) + *data = 0x48 | 0x80; /* IBM extended code up arrow */ + else if (c == 0x0A) + *data = 0x50 | 0x80; /* IBM extended code down arrow */ + else + *data = c; + } + else { + if (c == 0) { + if (!DOS_ReadFile(STDIN,&c,&n) || n == 0) return false; + *data = c | 0x80; /* extended code */ + } + else { + *data = c; + } + } + + return true; + } + + void Run(void) override { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("A full-screen introduction to DOSBox-X.\n\nINTRO [/RUN] [CDROM|MOUNT|USAGE|WELCOME]\n"); + return; + } + uint8_t attr = DOS_GetAnsiAttr(); + std::string menuname = "BASIC"; // default + /* Only run if called from the first shell (Xcom TFTD runs any intro file in the path) */ + if (!cmd->FindExist("-run", true)&&!cmd->FindExist("/run", true)&&DOS_PSP(dos.psp()).GetParent() != DOS_PSP(DOS_PSP(dos.psp()).GetParent()).GetParent()) return; + if(cmd->FindExist("welcome",false)) { + void showWelcome(Program *shell); + showWelcome(this); + return; + } + if(cmd->FindExist("cdrom",false)) { + WriteOut(MSG_Get("PROGRAM_INTRO_CDROM")); + if (attr) DOS_SetAnsiAttr(attr); + return; + } + if(cmd->FindExist("mount",false)) { + WriteOut("\033[2J");//Clear screen before printing + DisplayMount(); + if (attr) DOS_SetAnsiAttr(attr); + return; + } + + if(cmd->FindExist("usage", false)) { + DisplayUsage(); + if(attr) DOS_SetAnsiAttr(attr); + return; + } + uint8_t c;uint16_t n=1; + + #define CURSOR(option) \ + if (menuname==option) DisplayMenuCursorStart(); \ + else DisplayMenuBefore(); \ + WriteOut(MSG_Get("PROGRAM_INTRO_MENU_" option "")); \ + if (menuname==option) DisplayMenuCursorEnd(); \ + else WriteOut("\n"); + + /* Intro */ + + menufirst: + DisplayIntro(); + CURSOR("BASIC") + CURSOR("CDROM") + CURSOR("USAGE") + DisplayMenuNone(); // None + CURSOR("INFO") + CURSOR("QUIT") + DisplayMenuNone(); // None + + if (menuname=="BASIC") goto basic; + else if (menuname=="CDROM") goto cdrom; + else if (menuname=="USAGE") goto usage; + else if (menuname=="INFO") goto info; + else if (menuname=="QUIT") goto quit; + else if (menuname=="GOTO_EXIT") goto goto_exit; + + goto_exit: + WriteOut("\n"); // Give a line + if (attr) DOS_SetAnsiAttr(attr); + return; + + basic: + menuname="BASIC"; + WriteOut(MSG_Get("PROGRAM_INTRO_MENU_BASIC_HELP")); + CON_IN(&c); + do switch (c) { + case 0x48|0x80: menuname="QUIT"; goto menufirst; // Up + case 0x50|0x80: menuname="CDROM"; goto menufirst; // Down + case 0x1B: menuname="QUIT"; goto menufirst; + case 0xD: // Run + WriteOut("\033[2J"); + WriteOut(MSG_Get("PROGRAM_INTRO")); + WriteOut("\n"); + DisplayMount(); + DOS_ReadFile (STDIN,&c,&n); + goto menufirst; + } while (CON_IN(&c)); + + cdrom: + menuname="CDROM"; + WriteOut(MSG_Get("PROGRAM_INTRO_MENU_CDROM_HELP")); + CON_IN(&c); + do switch (c) { + case 0x48|0x80: menuname="BASIC"; goto menufirst; // Up + case 0x50|0x80: menuname="USAGE"; goto menufirst; // Down + case 0x1B: menuname="QUIT"; goto menufirst; + case 0xD: // Run + WriteOut(MSG_Get("PROGRAM_INTRO_CDROM")); + DOS_ReadFile (STDIN,&c,&n); + goto menufirst; + } while (CON_IN(&c)); + + usage: + menuname="USAGE"; + WriteOut(MSG_Get("PROGRAM_INTRO_MENU_USAGE_HELP")); + CON_IN(&c); + do switch (c) { + case 0x48|0x80: menuname="CDROM"; goto menufirst; // Down + case 0x50|0x80: menuname="INFO"; goto menufirst; // Down + case 0x1B: menuname="QUIT"; goto menufirst; + case 0xD: // Run + DisplayUsage(); + goto menufirst; + } while (CON_IN(&c)); + + info: + menuname="INFO"; + WriteOut(MSG_Get("PROGRAM_INTRO_MENU_INFO_HELP")); + CON_IN(&c); + do switch (c) { + case 0x48|0x80: menuname="USAGE"; goto menufirst; // Up + case 0x50|0x80: menuname="QUIT"; goto menufirst; // Down + case 0x1B: menuname="QUIT"; goto menufirst; + case 0xD: // Run + WriteOut("\033[2J"); + WriteOut(MSG_Get("PROGRAM_INTRO")); + WriteOut("\n"); + WriteOut(MSG_Get("PROGRAM_INTRO_INFO")); + DOS_ReadFile (STDIN,&c,&n); + goto menufirst; + } while (CON_IN(&c)); + + quit: + menuname="QUIT"; + WriteOut(MSG_Get("PROGRAM_INTRO_MENU_QUIT_HELP")); + CON_IN(&c); + do switch (c) { + case 0x48|0x80: menuname="INFO"; goto menufirst; // Up + case 0x50|0x80: menuname="BASIC"; goto menufirst; // Down + case 0xD: // Run + menuname="GOTO_EXIT"; + goto menufirst; + } while (CON_IN(&c)); + if (attr) DOS_SetAnsiAttr(attr); + } + }; + + static void INTRO_ProgramStart(Program * * make) { + *make=new INTRO; + } + + imageDiskMemory* CreateRamDrive(Bitu sizes[], const int reserved_cylinders, const bool forceFloppy, Program* obj) { + imageDiskMemory* dsk = NULL; + //if chs not specified + if (sizes[1] == 0) { + uint32_t imgSizeK = (uint32_t)sizes[0]; + //default to 1.44mb floppy + if (forceFloppy && imgSizeK == 0) imgSizeK = 1440; + //search for floppy geometry that matches specified size in KB + int index = 0; + while (DiskGeometryList[index].cylcount != 0) { + if (DiskGeometryList[index].ksize == imgSizeK) { + //create floppy + dsk = new imageDiskMemory(DiskGeometryList[index]); + break; + } + index++; + } + if (dsk == NULL) { + //create hard drive + if (forceFloppy) { + if (obj!=NULL) obj->WriteOut("Floppy size not recognized\n"); + return NULL; + } + + // The fatDrive class is hard-coded to assume that disks 2880KB or smaller are floppies, + // whether or not they are attached to a floppy controller. So, let's enforce a minimum + // size of 4096kb for hard drives. Use the other constructor for floppy drives. + // Note that a size of 0 means to auto-select a size + if (imgSizeK < 4096) imgSizeK = 4096; + + dsk = new imageDiskMemory(imgSizeK); + } + } + else { + //search for floppy geometry that matches specified geometry + int index = 0; + while (DiskGeometryList[index].cylcount != 0) { + if (DiskGeometryList[index].cylcount == sizes[3] && + DiskGeometryList[index].headscyl == sizes[2] && + DiskGeometryList[index].secttrack == sizes[1] && + DiskGeometryList[index].bytespersect == sizes[0]) { + //create floppy + dsk = new imageDiskMemory(DiskGeometryList[index]); + break; + } + index++; + } + if (dsk == NULL) { + //create hard drive + if (forceFloppy) { + if (obj!=NULL) obj->WriteOut("Floppy size not recognized\n"); + return NULL; + } + dsk = new imageDiskMemory((uint16_t)sizes[3], (uint16_t)sizes[2], (uint16_t)sizes[1], (uint16_t)sizes[0]); + } + } + if (!dsk->active) { + if (obj!=NULL) obj->WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); + delete dsk; + return NULL; + } + dsk->Set_Reserved_Cylinders((Bitu)reserved_cylinders); + return dsk; + } + + bool AttachToBiosByIndex(imageDisk* image, const unsigned char bios_drive_index) { + if (bios_drive_index >= MAX_DISK_IMAGES) return false; + if (imageDiskList[bios_drive_index] != NULL) { + /* Notify IDE ATA emulation if a drive is already there */ + if (bios_drive_index >= 2) IDE_Hard_Disk_Detach(bios_drive_index); + imageDiskList[bios_drive_index]->Release(); + } + imageDiskList[bios_drive_index] = image; + imageDiskChange[bios_drive_index] = true; + image->Addref(); + + // let FDC know if we mounted a floppy + if (bios_drive_index <= 1) { + FDC_AssignINT13Disk(bios_drive_index); + incrementFDD(); + } + + return true; + } + + bool AttachToBiosAndIdeByIndex(imageDisk* image, const unsigned char bios_drive_index, const unsigned char ide_index, const bool ide_slave) { + if (!AttachToBiosByIndex(image, bios_drive_index)) return false; + //if hard drive image, and if ide controller is specified + if (bios_drive_index >= 2 && bios_drive_index < MAX_DISK_IMAGES) { + IDE_Hard_Disk_Attach((signed char)ide_index, ide_slave, bios_drive_index); + updateDPT(); + } + return true; + } + + bool AttachToBiosByLetter(imageDisk* image, const char drive) { + if (image->hardDrive) { + //for hard drives, mount hard drives at first available index + for (int index = 2; index < MAX_DISK_IMAGES; index++) { + if (imageDiskList[index] == NULL) { + return AttachToBiosByIndex(image, index); + } + } + LOG_MSG("BIOS: Warning: Four hard drives (Disk no. 2-5) attached to BIOS already. Drive %c not attached", drive); + } + #if 0 + else if (IS_PC98_ARCH) { + // FIX_ME: This code is not correct. PC-98 boots from Drive 2 only if Drive 1 is empty. + // Currently disable this code since DOSBox-X supports only Drive A (Drive 1) as floppy boot drive anyway. + + //for pc-98 machines, mount floppies at first available index + for (int index = 0; index < 2; index++) { + if (imageDiskList[index] == NULL) { + return AttachToBiosByIndex(image, index); + } + } + } + #endif + else if ((drive - 'A') < 2) { + //for PCs, mount floppies only if A: or B: is specified, and then if so, at specified index + return AttachToBiosByIndex(image, drive - 'A'); + } + return false; + } + + bool AttachToBiosAndIdeByLetter(imageDisk* image, const char drive, const unsigned char ide_index, const bool ide_slave) { + if (image->hardDrive) { + //for hard drives, mount hard drives at first available index + for (int index = 2; index < MAX_DISK_IMAGES; index++) { + if (imageDiskList[index] == NULL) { + return AttachToBiosAndIdeByIndex(image, index, ide_index, ide_slave); + } + } + LOG_MSG("BIOS: Warning: Four hard drives (Disk no. 2-5) attached to BIOS already. Drive %c not attached", drive); + } + #if 0 + else if (IS_PC98_ARCH) { + // FIX_ME: This code is not correct. PC-98 boots from Drive 2 only if Drive 1 is empty. + // Currently disable this code since DOSBox-X supports only Drive A (Drive 1) as floppy boot drive anyway. + + //for pc-98 machines, mount floppies at first available index + for (int index = 0; index < 2; index++) { + if (imageDiskList[index] == NULL) { + return AttachToBiosByIndex(image, index); + } + } + } + #endif + else if ((drive - 'A') < 2) { + //for PCs, mount floppies only if A: or B: is specified, and then if so, at specified index + return AttachToBiosByIndex(image, drive - 'A'); + } + return false; + } + + std::string GetIDEPosition(unsigned char bios_disk_index); + class IMGMOUNT : public Program { + public: + std::vector options; + void ListImgMounts(void) { + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; + /* Command uses dta so set it to our internal dta */ + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_1")); + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),MSG_Get("DRIVE"),MSG_Get("TYPE"),MSG_Get("LABEL"),MSG_Get("SWAP_SLOT")); + int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + if (!cols) cols=80; + for(int p = 1;p < cols;p++) WriteOut("-"); + WriteOut("\n"); + char swapstr[50]; + bool none=true; + for (int d = 0;d < DOS_DRIVES;d++) { + if (!Drives[d] || (strncmp(Drives[d]->GetInfo(), "fatDrive ", 9) && strncmp(Drives[d]->GetInfo(), "isoDrive ", 9))) continue; + char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; + bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); + if (ret) { + dta.GetResult(name,lname,size,hsize,date,time,attr); + DOS_FindNext(); //Mark entry as invalid + } else name[0] = 0; + + /* Change 8.3 to 11.0 */ + const char* dot = strchr(name, '.'); + if(dot && (dot - name == 8) ) { + name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; + } + + root[1] = 0; //This way, the format string can be reused. + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name,DriveManager::GetDrivePosition(d)); + none=false; + } + if (none) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); + WriteOut("\n"); + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_2")); + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NUMBER_FORMAT"),MSG_Get("DRIVE_NUMBER"),MSG_Get("DISK_NAME"),MSG_Get("IDE_POSITION"),MSG_Get("SWAP_SLOT")); + for(int p = 1;p < cols;p++) WriteOut("-"); + WriteOut("\n"); + none=true; + for (int index = 0; index < MAX_DISK_IMAGES; index++) { + if (imageDiskList[index]) { + int swaps=0; + if (swapInDisksSpecificDrive == index) { + for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) + if (diskSwap[si] != NULL) + swaps++; + } + if (!swaps) swaps=1; + sprintf(swapstr, "%d / %d", swaps==1?1:swapPosition+1, swaps); + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NUMBER_FORMAT"), std::to_string(index).c_str(), dynamic_cast(imageDiskList[index])!=NULL?"El Torito floppy drive":imageDiskList[index]->diskname.c_str(), GetIDEPosition(index).c_str(), swapstr); + none=false; + } + } + if (none) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); + dos.dta(save_dta); + } + void Run(void) override { + //Hack To allow long commandlines + ChangeToLongCmd(); + /* In secure mode don't allow people to change imgmount points. + * Neither mount nor unmount */ + if(control->SecureMode()) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); + return; + } + imageDisk * newImage; + char drive; + std::vector paths; + if (!cmd->GetCount()) { + ListImgMounts(); + return; + } + //show help if /? or -? + if (cmd->FindExist("/?", true) || cmd->FindExist("-?", true) || cmd->FindExist("?", true) || cmd->FindExist("-help", true)) { + resetcolor = true; + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_HELP")); + return; + } + if (cmd->FindExist("/examples")||cmd->FindExist("-examples")) { + resetcolor = true; + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_EXAMPLE")); + return; + } + /* Check for unmounting */ + std::string umount; + if (cmd->FindString("-u",umount,false)) { + Unmount(umount[0]); + return; + } + + bool roflag = false; + if (cmd->FindExist("-ro",true)) + roflag = true; + + //initialize more variables + unsigned long el_torito_floppy_base=~0UL; + unsigned char el_torito_floppy_type=0xFF; + bool ide_slave = false; + signed char ide_index = -1; + char el_torito_cd_drive = 0; + std::string el_torito; + std::string ideattach="auto"; + std::string type="hdd"; + uint8_t tdr = 0; + std::string bdisk; + int bdisk_number=-1; + + //this code simply sets default type to "floppy" if mounting at A: or B: --- nothing else + // get first parameter - which is probably the drive letter to mount at (A-Z or A:-Z:) - and check it if is A or B or A: or B: + // default to floppy for drive letters A and B and numbers 0 and 1 + if (!cmd->FindCommand(1,temp_line) || (temp_line.size() > 2) || + ((temp_line.size()>1) && (temp_line[1]!=':'))) { + // drive not valid + } else { + tdr = toupper(temp_line[0]); + if(tdr=='A'||tdr=='B'||tdr=='0'||tdr=='1') type="floppy"; + } + + if (temp_line.size() == 1 && isdigit(temp_line[0]) && temp_line[0]>='0' && temp_line[0]FindExist("-u",true)) { + Unmount(temp_line[0]); + std::string templine; + if (!cmd->FindCommand(2,templine)||!templine.size()) return; + } + + //get the type + bool rtype=cmd->FindString("-t", type, true); + std::transform(type.begin(), type.end(), type.begin(), ::tolower); + + if (type == "cdrom") type = "iso"; //Tiny hack for people who like to type -t cdrom + if (!(type == "floppy" || type == "hdd" || type == "iso" || type == "ram")) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_TYPE_UNSUPPORTED"), type.c_str()); + return; + } + + //look for -o options + { + std::string s; + + while (cmd->FindString("-o", s, true)) + options.push_back(s); + } + + //look for -el-torito parameter and remove it from the command line + cmd->FindString("-el-torito",el_torito,true); + if(el_torito == "") cmd->FindString("-bootcd", el_torito, true); + if (el_torito != "") { + //get el-torito floppy from cdrom mounted at drive letter el_torito_cd_drive + el_torito_cd_drive = toupper(el_torito[0]); + //validate the el_torito loading (look for boot image on the cdrom, etc), and + // find the el_torito_floppy_base and el_torito_floppy_type values + if (!PrepElTorito(type, el_torito_cd_drive, el_torito_floppy_base, el_torito_floppy_type)) return; + } + + //the user can use -bd to mount partitions from an INT 13h BIOS disk mounted image, + //meaning a disk image attached to INT 13h using IMGMOUNT -fs none. This way, + //it is possible to mount multiple partitions from one HDD image. + cmd->FindString("-bd",bdisk,true); + if (bdisk != "") { + bdisk_number = atoi(bdisk.c_str()); + if (bdisk_number < 0 || bdisk_number >= MAX_DISK_IMAGES) return; + if (imageDiskList[bdisk_number] == NULL) { + WriteOut("BIOS disk index does not have an image assigned"); + return; + } + } + + //default fstype is fat + std::string fstype="fat"; + bool rfstype=cmd->FindString("-fs",fstype,true); + std::transform(fstype.begin(), fstype.end(), fstype.begin(), ::tolower); + + Bitu sizes[4] = { 0,0,0,0 }; + int reserved_cylinders=0; + std::string reservecyl; + + /* DOSBox-X: to please certain 32-bit drivers like Windows 3.1 WDCTRL, or to emulate older h/w configurations, + * we allow the user or script to specify the number of reserved cylinders. older BIOSes were known + * to subtract 1 or 2 additional cylinders from the total in the fixed disk param table. the -reservecyl + * option allows the number we subtract from the total in INT 13H to be set */ + cmd->FindString("-reservecyl",reservecyl,true); + if (reservecyl != "") reserved_cylinders = atoi(reservecyl.c_str()); + + /* DOSBox-X: we allow "-ide" to allow controlling which IDE controller and slot to attach the hard disk/CD-ROM to */ + cmd->FindString("-ide",ideattach,true); + std::transform(ideattach.begin(), ideattach.end(), ideattach.begin(), ::tolower); + + if(isdigit(tdr) && tdr - '0' >= 2) { //Allocate to respective slots if drive number is specified + ide_index = (tdr - '2') / 2; // Drive number 2 = 1m (index=0, slave=false), 3 = 1s (index=0, slave=true), ... + ide_slave = (tdr - '2') & 1 ? true : false; + } else if(ideattach == "auto") { + //LOG_MSG("IDE: attach=auto type=%s", type); + if(type != "floppy") { + if(type == "iso") { + if(!IDE_controller_occupied(1, false)) { // CD-ROMS default to secondary master if not occupied + ide_index = 1; + ide_slave = false; + } + } + if (ide_index < 0) IDE_Auto(ide_index, ide_slave); + } + } + else if (ideattach != "none" && isdigit(ideattach[0]) && ideattach[0] > '0') { /* takes the form [controller] such as: 1m for primary master */ + ide_index = ideattach[0] - '1'; + if (ideattach.length() >= 2) ide_slave = (ideattach[1] == 's'); + } + + //if floppy, don't attach to ide controller + //if cdrom, file system is iso + if (type=="floppy") { + ideattach="none"; + } else if (type=="iso") { + //str_size=="2048,1,60000,0"; // ignored, see drive_iso.cpp (AllocationInfo) + fstype = "iso"; + } + + //load the size parameter + //auto detect hard drives if not specified + std::string str_size; + std::string str_chs; + cmd->FindString("-size", str_size, true); + cmd->FindString("-chs", str_chs, true); + if (!ReadSizeParameter(str_size, str_chs, type, sizes)) return; + + if (!rfstype&&isdigit(temp_line[0])) fstype="none"; + + //for floppies, hard drives, and cdroms, require a drive letter + //for -fs none, require a number indicating where to mount at + if(fstype=="fat" || fstype=="iso") { + // get the drive letter + if (!cmd->FindCommand(1,temp_line) || (temp_line.size() > 2) || ((temp_line.size()>1) && (temp_line[1]!=':'))) { + WriteOut_NoParsing(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY_DRIVE")); + return; + } + + /* if fs type if "fat" and we're asked to mount *: then check for that here */ + if (temp_line[0] == '*' && temp_line[1] == ':') { + /* What drives are available? */ + int i_drive = IS_PC98_ARCH ? 'A' : 'C'; + while (i_drive <= 'Z' && Drives[i_drive-'A'] != NULL && (i_drive-'A') < DOS_DRIVES) i_drive++; + + if (i_drive > 'Z') { + WriteOut_NoParsing("No drive letters available"); + return; + } + + drive = static_cast(i_drive); + } + else { + int i_drive = toupper(temp_line[0]); + if (!isalpha(i_drive) || (i_drive - 'A') >= DOS_DRIVES || (i_drive - 'A') < 0) { + WriteOut_NoParsing(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY_DRIVE")); + return; + } + drive = static_cast(i_drive); + } + } else if (fstype=="none") { + cmd->FindCommand(1,temp_line); + if ((temp_line.size() > 1) || (!isdigit(temp_line[0]))) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY2"), MAX_DISK_IMAGES-1); + return; + } + drive=temp_line[0]; + if ((drive<'0') || (drive>=MAX_DISK_IMAGES+'0')) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY2"), MAX_DISK_IMAGES-1); + return; + } + int index = drive - '0'; + if (imageDiskList[index]) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED_NUMBER"),index); + return; + } + } else { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_FORMAT_UNSUPPORTED"),fstype.c_str()); + return; + } + + // find all file parameters, assuming that all option parameters have been removed + bool removed=ParseFiles(temp_line, paths, el_torito != "" || type == "ram" || bdisk != ""); + + // some generic checks + if (el_torito != "") { + if (paths.size() != 0) { + WriteOut("Do not specify files when mounting floppy drives from El Torito bootable CDs\n"); + return; + } + } + else if (bdisk != "") { + } + else if (type == "ram") { + if (paths.size() != 0) { + WriteOut("Do not specify files when mounting RAM drives\n"); + return; + } + } + else { + if (paths.size() == 0) { + if (strcasecmp(temp_line.c_str(), "-u")&&!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_SPECIFY_FILE")); + return; + } + if (!rtype&&!rfstype&&fstype!="none"&&paths[0].length()>4) { + const char *ext = strrchr(paths[0].c_str(), '.'); + if (ext != NULL) { + if (!strcasecmp(ext, ".cdrom")||!strcasecmp(ext, ".iso")||!strcasecmp(ext, ".cue")||!strcasecmp(ext, ".bin")||!strcasecmp(ext, ".chd")||!strcasecmp(ext, ".mdf")||!strcasecmp(ext, ".gog")||!strcasecmp(ext, ".ins")||!strcasecmp(ext, ".ccd")||!strcasecmp(ext, ".inst")) { + type="iso"; + fstype="iso"; + if(ide_index < 0 || ideattach == "auto") { + if(!IDE_controller_occupied(1, false)) { // check if secondary master is already occupied + ide_index = 1; + ide_slave = false; + } + else IDE_Auto(ide_index, ide_slave); + } + } else if (!strcasecmp(ext, ".ima")) { + type="floppy"; + ideattach="none"; + } + } + } + } + + int i_drive = drive - 'A'; + bool exist = i_drive < DOS_DRIVES && i_drive >= 0 && Drives[i_drive]; + //====== call the proper subroutine ====== + if(fstype=="fat") { + //mount floppy or hard drive + if (bdisk != "") { + if (!MountPartitionFat(drive, bdisk_number)) return; + } + else if (el_torito != "") { + if (!MountElToritoFat(drive, sizes, el_torito_cd_drive, el_torito_floppy_base, el_torito_floppy_type)) return; + } + else if (type == "ram") { + if (!MountRam(sizes, drive, ide_index, ide_slave, roflag)) return; + } + else { + //supports multiple files + if (!MountFat(sizes, drive, type == "hdd", str_size, paths, ide_index, ide_slave, reserved_cylinders, roflag)) return; + } + if (removed && !exist && i_drive < DOS_DRIVES && i_drive >= 0 && Drives[i_drive]) DOS_SetDefaultDrive(i_drive); + } else if (fstype=="iso") { + if (bdisk != "") { + // TODO + return; + } + if (el_torito != "") { + WriteOut("El Torito bootable CD: -fs iso mounting not supported\n"); /* <- NTS: Will never implement, either */ + return; + } + //supports multiple files + if (!MountIso(drive, paths, ide_index, ide_slave)) return; + if (removed && !exist && i_drive < DOS_DRIVES && i_drive >= 0 && Drives[i_drive]) DOS_SetDefaultDrive(i_drive); + } else if (fstype=="none") { + unsigned char driveIndex = drive - '0'; + + if (paths.size() > 1) { + if (driveIndex <= 1) { + if (swapInDisksSpecificDrive >= 0 && swapInDisksSpecificDrive <= 1 && + swapInDisksSpecificDrive != driveIndex) { + WriteOut("Multiple images given and another drive already uses multiple images\n"); + return; + } + } + else { + WriteOut("Multiple disk images not supported for that drive\n"); + return; + } + } + + if (el_torito != "") { + newImage = new imageDiskElToritoFloppy((unsigned char)el_torito_cd_drive, el_torito_floppy_base, el_torito_floppy_type); + } + else if (type == "ram") { + newImage = MountImageNoneRam(sizes, reserved_cylinders, driveIndex < 2); + } + else { + newImage = MountImageNone(paths[0].c_str(), NULL, sizes, reserved_cylinders, roflag); + } + if (newImage == NULL) return; + newImage->Addref(); + if (newImage->hardDrive && (driveIndex < 2)) { + WriteOut("Cannot mount hard drive in floppy position.\n"); + } + else if (!newImage->hardDrive && (driveIndex >= 2)) { + WriteOut("Cannot mount floppy in hard drive position.\n"); + } + else { + if (AttachToBiosAndIdeByIndex(newImage, (unsigned char)driveIndex, (unsigned char)ide_index, ide_slave)) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_MOUNT_NUMBER"), drive - '0', (!paths.empty()) ? (wpcolon&&paths[0].length()>1&&paths[0].c_str()[0]==':'?paths[0].c_str()+1:paths[0].c_str()) : (el_torito != ""?"El Torito floppy drive":(type == "ram"?"RAM drive":"-"))); + const char *ext = strrchr(paths[0].c_str(), '.'); + if (ext != NULL) { + if ((!IS_PC98_ARCH && strcasecmp(ext,".img") && strcasecmp(ext,".ima") && strcasecmp(ext,".vhd") && strcasecmp(ext,".qcow2")) || + (IS_PC98_ARCH && strcasecmp(ext,".hdi") && strcasecmp(ext,".nhd") && strcasecmp(ext,".img") && strcasecmp(ext,".ima"))){ + WriteOut(MSG_Get("PROGRAM_MOUNT_UNSUPPORTED_EXT"), ext); + } + } + if (swapInDisksSpecificDrive == driveIndex || swapInDisksSpecificDrive == -1) { + for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { + if (diskSwap[si] != NULL) { + diskSwap[si]->Release(); + diskSwap[si] = NULL; + } + } + swapInDisksSpecificDrive = -1; + if (paths.size() > 1) { + /* slot 0 is the image we already assigned */ + diskSwap[0] = newImage; + diskSwap[0]->Addref(); + swapPosition = 0; + swapInDisksSpecificDrive = driveIndex; + + for (size_t si=1;si < MAX_SWAPPABLE_DISKS && si < paths.size();si++) { + imageDisk *img = MountImageNone(paths[si].c_str(), NULL, sizes, reserved_cylinders, roflag); + + if (img != NULL) { + diskSwap[si] = img; + diskSwap[si]->Addref(); + } + } + } + } + } + else { + WriteOut("Invalid mount number\n"); + } + } + newImage->Release(); + return; + } + else { + WriteOut("Invalid fstype\n"); + return; + } + + return; + } + + private: + bool ReadSizeParameter(const std::string &str_size, const std::string &str_chs, const std::string &type, Bitu sizes[]) { + bool isCHS = false; + const char * scan; + if (str_chs.size() != 0) { + if (str_size.size() != 0) { + WriteOut("Size and chs parameter cannot both be specified\n"); + return false; + } + isCHS = true; + scan = str_chs.c_str(); + } + else if (str_size.size() != 0) { + scan = str_size.c_str(); + } + else { + //nothing specified, so automatic size detection + return true; + } + char number[20]; + Bitu index = 0; + Bitu count = 0; + int val; + + //scan through input string + while (*scan) { + //separate string by ',' + if (*scan == ',') { + number[index] = 0; //add null char + val = atoi(number); + if (val <= 0) { + //out of range + WriteOut("Invalid size parameter\n"); + return false; + } + sizes[count++] = (unsigned int)val; + index = 0; + if (count == 4) { + //too many commas + WriteOut("Invalid size parameter\n"); + return false; + } + } + else if (index >= 19) { + //number too large (too many characters, anyway) + WriteOut("Invalid size parameter\n"); + return false; + } + else { + number[index++] = *scan; + } + scan++; + } + number[index] = 0; + val = atoi(number); + if (val <= 0) { + //out of range + WriteOut("Invalid size parameter\n"); + return false; + } + sizes[count++] = (unsigned int)val; + if (isCHS) { + if (count == 3) sizes[count++] = 512; //set sector size automatically + if (count != 4) { + WriteOut("Invalid chs parameter\n"); + return false; + } + Bitu temp = sizes[3]; //hold on to sector size temporarily + sizes[3] = sizes[0]; //put cylinders in the right spot + sizes[0] = temp; //put sector size in the right spot + temp = sizes[2]; //hold on to sectors temporarily + sizes[2] = sizes[1]; //put heads in the right spot + sizes[1] = temp; //put sectors in the right spot + } + if (!((type == "ram" && count == 1) || count == 4)) { + //ram drives require 1 or 4 numbers + //other drives require 4 numbers + WriteOut("Invalid size parameter\n"); + return false; + } + return true; + } + bool ParseFiles(std::string &commandLine, std::vector &paths, bool nodef) { + char drive=commandLine[0]; + bool nocont=false; + int num = 0; + while (!nocont&&cmd->FindCommand((unsigned int)(paths.size() + 1 - num), commandLine)) { + bool usedef=false; + if (!cmd->FindCommand((unsigned int)(paths.size() + 2 - num), commandLine) || !commandLine.size()) { + if (!nodef && !paths.size()) { + commandLine="IMGMAKE.IMG"; + usedef=true; + } + else break; + } + if (commandLine == "empty") { + /* special name */ + paths.push_back(commandLine); + continue; + } + #if defined (WIN32) || defined(OS2) + // Windows: Workaround for LaunchBox + if (commandLine.size()>4 && commandLine[0]=='\'' && toupper(commandLine[1])>='A' && toupper(commandLine[1])<='Z' && commandLine[2]==':' && (commandLine[3]=='/' || commandLine[3]=='\\') && commandLine.back()=='\'') + commandLine = commandLine.substr(1, commandLine.size()-2); + else if (!paths.size() && commandLine.size()>3 && commandLine[0]=='\'' && toupper(commandLine[1])>='A' && toupper(commandLine[1])<='Z' && commandLine[2]==':' && (commandLine[3]=='/' || commandLine[3]=='\\')) { + std::string line=cmd->GetRawCmdline(); + trim(line); + std::size_t space=line.find(' '); + if (space!=std::string::npos) { + line=line.substr(space); + trim(line); + std::size_t found=line.back()=='\''?line.find_last_of('\''):line.rfind("' "); + if (found!=std::string::npos&&found>2) { + commandLine=line.substr(1, found-1); + nocont=true; + if (line.size()>3 && !strcasecmp(line.substr(line.size()-3).c_str(), " -u")) Unmount(drive); + } + } + } + #else + // Linux: Convert backslash to forward slash + if (commandLine.size() > 0) { + for (size_t i = 0; i < commandLine.size(); i++) { + if (commandLine[i] == '\\') + commandLine[i] = '/'; + } + } + #endif + + if (!strcasecmp(commandLine.c_str(), "-u")) { + bool exist = toupper(drive) - 'A' == DOS_GetDefaultDrive(); + Unmount(drive); + return exist && drive - 'A' != DOS_GetDefaultDrive(); + } + + char fullname[CROSS_LEN]; + char tmp[CROSS_LEN]; + bool useh = false, readonly = wpcolon&&commandLine.length()>1&&commandLine[0]==':'; + safe_strncpy(tmp, readonly?commandLine.c_str()+1:commandLine.c_str(), CROSS_LEN); + pref_struct_stat test; + #if defined(WIN32) + ht_stat_t htest; + const host_cnv_char_t* host_name = CodePageGuestToHost(tmp); + if (pref_stat(tmp, &test) && (host_name == NULL || ht_stat(host_name, &htest))) { + if (pref_stat(tmp, &test) && host_name != NULL) useh = true; + #else + pref_struct_stat htest; + if (pref_stat(tmp, &test)) { + #endif + //See if it works if the ~ are written out + std::string homedir(commandLine); + Cross::ResolveHomedir(homedir); + if (!pref_stat(homedir.c_str(), &test)) { + commandLine = homedir; + } + else { + // convert dosbox-x filename to system filename + uint8_t dummy; + temp_line = tmp; + int res = get_expanded_files(temp_line, paths, readonly); + if (res) { + num += res - 1; + temp_line = paths[0]; + continue; + } else if ((!DOS_MakeName(tmp, fullname, &dummy) || strncmp(Drives[dummy]->GetInfo(), "local directory", 15)) && !qmount) { + if (_memFileDirectory.contains(tmp) || std::string(tmp).find(".cdrom") != std::string::npos) { paths.push_back(tmp); continue; } + else WriteOut(MSG_Get(usedef?"PROGRAM_IMGMOUNT_DEFAULT_NOT_FOUND":"PROGRAM_IMGMOUNT_NON_LOCAL_DRIVE")); + return true; + } + + localDrive *ldp = dynamic_cast(Drives[dummy]); + if (ldp == NULL) { + if (!qmount) WriteOut(MSG_Get(usedef?"PROGRAM_IMGMOUNT_DEFAULT_NOT_FOUND":"PROGRAM_IMGMOUNT_FILE_NOT_FOUND")); + return false; + } + ldp->GetSystemFilename(readonly?tmp+1:tmp, fullname); + if (readonly) tmp[0]=':'; + commandLine = tmp; + + if (pref_stat(readonly?tmp+1:tmp, &test)) { + temp_line = readonly?tmp+1:tmp; + int res = get_expanded_files(temp_line, paths, readonly); + if (res) { + num += res - 1; + temp_line = paths[0]; + continue; + } else if (!qmount) + WriteOut(MSG_Get(usedef?"PROGRAM_IMGMOUNT_DEFAULT_NOT_FOUND":"PROGRAM_IMGMOUNT_FILE_NOT_FOUND")); + return false; + } + } + } + if (S_ISDIR(useh?htest.st_mode:test.st_mode)&&!usedef) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_MOUNT")); + return false; + } + paths.push_back(commandLine); + } + + if (paths.size() > 0) return true; + return false; + } + + bool Unmount(char &letter) { + letter = toupper(letter); + if (isalpha(letter)) { /* if it's a drive letter, then traditional usage applies */ + int i_drive = letter - 'A'; + if (i_drive < DOS_DRIVES && i_drive >= 0 && Drives[i_drive]) { + //if drive A: or B: + if (i_drive <= 1) + FDC_UnassignINT13Disk(i_drive); + + //get reference to image and cdrom before they are possibly destroyed + const bool partitionMount = Drives[i_drive]->partitionMount; + const fatDrive* drive = dynamic_cast(Drives[i_drive]); + imageDisk* image = drive ? drive->loadedDisk : NULL; + const isoDrive* cdrom = dynamic_cast(Drives[i_drive]); + + switch (DriveManager::UnmountDrive(i_drive)) { + case 0: //success + { + //detach hard drive or floppy drive from bios and ide controller + if (image && !partitionMount) DetachFromBios(image); + /* If the drive letter is also a CD-ROM drive attached to IDE, then let the IDE code know */ + if (cdrom) IDE_CDROM_Detach(i_drive); + Drives[i_drive] = NULL; + DOS_EnableDriveMenu(i_drive+'A'); + if (i_drive == DOS_GetDefaultDrive()) + DOS_SetDrive(toupper('Z') - 'A'); + if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_SUCCESS"), letter); + if (cdrom) + for (int drv=0; drv<2; drv++) + if (Drives[drv]) { + fatDrive *fdp = dynamic_cast(Drives[drv]); + if (fdp&&fdp->opts.mounttype==1&&letter==fdp->el.CDROM_drive) { + char drive='A'+drv; + Unmount(drive); + } + } + if (i_drive < MAX_DISK_IMAGES && imageDiskList[i_drive]) { + delete imageDiskList[i_drive]; + imageDiskList[i_drive] = NULL; + } + if (swapInDisksSpecificDrive == i_drive) { + for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { + if (diskSwap[si] != NULL) { + diskSwap[si]->Release(); + diskSwap[si] = NULL; + } + } + swapInDisksSpecificDrive = -1; + } + return true; + } + case 1: + if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_NO_VIRTUAL")); + return false; + case 2: + if (!qmount) WriteOut(MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS")); + return false; + default: + return false; + } + } + else { + if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED"), letter); + return false; + } + } + else if (isdigit(letter)) { /* DOSBox-X: drives mounted by number (INT 13h) can be unmounted this way */ + int index = letter - '0'; + + //detach hard drive or floppy drive from bios and ide controller + if (index < MAX_DISK_IMAGES && imageDiskList[index]) { + if (index > 1) IDE_Hard_Disk_Detach(index); + imageDiskList[index]->Release(); + imageDiskList[index] = NULL; + imageDiskChange[index] = true; + if (swapInDisksSpecificDrive == index) { + for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { + if (diskSwap[si] != NULL) { + diskSwap[si]->Release(); + diskSwap[si] = NULL; + } + } + swapInDisksSpecificDrive = -1; + } + WriteOut(MSG_Get("PROGRAM_MOUNT_UMOUNT_NUMBER_SUCCESS"), letter); + return true; + } + WriteOut("Drive number %d is not mounted.\n", index); + return false; + } + else { + WriteOut("Incorrect IMGMOUNT unmount usage.\n"); + return false; + } + } + + bool PrepElTorito(const std::string& type, const char &el_torito_cd_drive, unsigned long &el_torito_floppy_base, unsigned char &el_torito_floppy_type) { + el_torito_floppy_base = ~0UL; + el_torito_floppy_type = 0xFF; + + unsigned char entries[2048], *entry, ent_num = 0; + int header_platform = -1, header_count = 0; + bool header_final = false; + int header_more = -1; + + /* must be valid drive letter, C to Z */ + if (!isalpha(el_torito_cd_drive) || el_torito_cd_drive < 'C') { + WriteOut("El Torito emulation requires a proper CD-ROM drive letter\n"); + return false; + } + + /* drive must not exist (as a hard drive) */ + if (imageDiskList[el_torito_cd_drive - 'A'] != NULL) { + WriteOut("El Torito CD-ROM drive specified already exists as a non-CD-ROM device\n"); + return false; + } + + bool GetMSCDEXDrive(unsigned char drive_letter, CDROM_Interface **_cdrom); + + /* get the CD-ROM drive */ + CDROM_Interface *src_drive = NULL; + if (!GetMSCDEXDrive(el_torito_cd_drive - 'A', &src_drive)) { + WriteOut("El Torito CD-ROM drive specified is not actually a CD-ROM drive\n"); + return false; + } + + /* FIXME: We only support the floppy emulation mode at this time. + * "Superfloppy" or hard disk emulation modes are not yet implemented. + * This mode will never support "no emulation" boot. */ + if (type != "floppy") { + WriteOut("El Torito emulation must be used with -t floppy at this time\n"); + return false; + } + + /* Okay. Step #1: Scan the volume descriptors for the Boot Record. */ + unsigned long el_torito_base = 0, boot_record_sector = 0; + if (!ElTorito_ScanForBootRecord(src_drive, boot_record_sector, el_torito_base)) { + WriteOut("El Torito CD-ROM boot record not found\n"); + return false; + } + + LOG_MSG("El Torito emulation: Found ISO 9660 Boot Record in sector %lu, pointing to sector %lu\n", + boot_record_sector, el_torito_base); + + /* Step #2: Parse the records. Each one is 32 bytes long */ + if (!src_drive->ReadSectorsHost(entries, false, el_torito_base, 1)) { + WriteOut("El Torito entries unreadable\n"); + return false; + } + + /* for more information about what this loop is doing, read: + * http://download.intel.com/support/motherboards/desktop/sb/specscdrom.pdf + */ + /* FIXME: Somebody find me an example of a CD-ROM with bootable code for both x86, PowerPC, and Macintosh. + * I need an example of such a CD since El Torito allows multiple "headers" */ + /* TODO: Is it possible for this record list to span multiple sectors? */ + for (ent_num = 0; ent_num < (2048 / 0x20); ent_num++) { + entry = entries + (ent_num * 0x20); + + if (memcmp(entry, "\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0""\0\0\0\0", 32) == 0) + break; + + if (entry[0] == 0x01/*header*/) { + if (!ElTorito_ChecksumRecord(entry)) { + LOG_MSG("Warning: El Torito checksum error in header(0x01) entry\n"); + continue; + } + + if (header_count != 0) { + LOG_MSG("Warning: El Torito has more than one Header/validation entry\n"); + continue; + } + + if (header_final) { + LOG_MSG("Warning: El Torito has an additional header past the final header\n"); + continue; + } + + header_more = -1; + header_platform = entry[1]; + LOG_MSG("El Torito entry: first header platform=0x%02x\n", header_platform); + header_count++; + } + else if (entry[0] == 0x90/*header, more follows*/ || entry[0] == 0x91/*final header*/) { + if (header_final) { + LOG_MSG("Warning: El Torito has an additional header past the final header\n"); + continue; + } + + header_final = (entry[0] == 0x91); + header_more = (int)(((unsigned int)entry[2]) + (((unsigned int)entry[3]) << 8u)); + header_platform = entry[1]; + LOG_MSG("El Torito entry: first header platform=0x%02x more=%u final=%u\n", header_platform, header_more, header_final); + header_count++; + } + else { + if (header_more == 0) { + LOG_MSG("El Torito entry: Non-header entry count expired, ignoring record 0x%02x\n", entry[0]); + continue; + } + else if (header_more > 0) { + header_more--; + } + + if (entry[0] == 0x44) { + LOG_MSG("El Torito entry: ignoring extension record\n"); + } + else if (entry[0] == 0x00/*non-bootable*/) { + LOG_MSG("El Torito entry: ignoring non-bootable record\n"); + } + else if (entry[0] == 0x88/*bootable*/) { + if (header_platform == 0x00/*x86*/) { + unsigned char mediatype = entry[1] & 0xF; + unsigned short load_segment = ((unsigned int)entry[2]) + (((unsigned int)entry[3]) << 8); + unsigned char system_type = entry[4]; + unsigned short sector_count = ((unsigned int)entry[6]) + (((unsigned int)entry[7]) << 8); + unsigned long load_rba = ((unsigned int)entry[8]) + (((unsigned int)entry[9]) << 8) + + (((unsigned int)entry[10]) << 16) + (((unsigned int)entry[11]) << 24); + + LOG_MSG("El Torito entry: bootable x86 record mediatype=%u load_segment=0x%04x " + "system_type=0x%02x sector_count=%u load_rba=%lu\n", + mediatype, load_segment, system_type, sector_count, load_rba); + + /* already chose one, ignore */ + if (el_torito_floppy_base != ~0UL) + continue; + + if (load_segment != 0 && load_segment != 0x7C0) + LOG_MSG("El Torito boot warning: load segments other than 0x7C0 not supported yet\n"); + if (sector_count != 1) + LOG_MSG("El Torito boot warning: sector counts other than 1 are not supported yet\n"); + + if (mediatype < 1 || mediatype > 3) { + LOG_MSG("El Torito boot entry: media types other than floppy emulation not supported yet\n"); + continue; + } + + el_torito_floppy_base = load_rba; + el_torito_floppy_type = mediatype; + } + else { + LOG_MSG("El Torito entry: ignoring bootable non-x86 (platform_id=0x%02x) record\n", header_platform); + } + } + else { + LOG_MSG("El Torito entry: ignoring unknown record ID %02x\n", entry[0]); + } + } + } + + if (el_torito_floppy_type == 0xFF || el_torito_floppy_base == ~0UL) { + WriteOut("El Torito bootable floppy not found\n"); + return false; + } + + return true; + } + + bool MountPartitionFat(const char drive, const int src_bios_disk) { + unsigned char driveIndex = drive - 'A'; + + /* NTS: IBM PC systems: Hard disk partitions must start at C: or higher. + * PC-98 systems: Any drive letter is valid, A: can be a hard drive. */ + if ((!IS_PC98_ARCH && driveIndex < 2) || driveIndex >= 26) { + WriteOut("Invalid drive letter"); + return false; + } + + if (Drives[driveIndex]) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); + return false; + } + + if (src_bios_disk < 2/*no, don't allow partitions on floppies!*/ || src_bios_disk >= MAX_DISK_IMAGES || imageDiskList[src_bios_disk] == NULL) { + WriteOut("BIOS disk index does not have an image assigned"); + return false; + } + + /* FIXME: IMGMOUNT and MOUNT -u are so hard-coded around C: and BIOS device indexes that some confusion may happen + * if a partition is C: mounted from, say, BIOS device 0x81 and the wrong thing may get unmounted and detached. + * So for sanity reasons, do not allow mounting to a drive letter if a BIOS disk image WOULD normally be + * associated with it. This is a mess inherited from back when this code forked from DOSBox SVN, because + * DOSBox SVN makes these hardcoded assumptions. */ + if (driveIndex < MAX_DISK_IMAGES && imageDiskList[driveIndex] != NULL) { + WriteOut("Partitions cannot be mounted in conflict with the standard INT 13h hard disk\nallotment. Choose a different drive letter to mount to."); + return false; + } + + DOS_Drive* newDrive = new fatDrive(imageDiskList[src_bios_disk], options); + if (!(dynamic_cast(newDrive))->created_successfully) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); + return false; + } + + newDrive->partitionMount = true; + AddToDriveManager(drive, newDrive, 0xF0); + DOS_EnableDriveMenu(drive); + + lastmount = drive; + return true; + } + + bool MountElToritoFat(const char drive, const Bitu sizes[], const char el_torito_cd_drive, const unsigned long el_torito_floppy_base, const unsigned char el_torito_floppy_type) { + unsigned char driveIndex = drive - 'A'; + + (void)sizes;//UNUSED + + if (driveIndex > 1) { + WriteOut("Invalid drive letter"); + return false; + } + + if (Drives[driveIndex]) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); + return false; + } + + imageDisk * newImage = new imageDiskElToritoFloppy((unsigned char)el_torito_cd_drive, el_torito_floppy_base, el_torito_floppy_type); + newImage->Addref(); + + DOS_Drive* newDrive = new fatDrive(newImage, options); + newImage->Release(); //fatDrive calls Addref, and this will release newImage if fatDrive doesn't use it + if (!(dynamic_cast(newDrive))->created_successfully) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); + return false; + } + + AddToDriveManager(drive, newDrive, 0xF0); + AttachToBiosByLetter(newImage, drive); + DOS_EnableDriveMenu(drive); + + lastmount = drive; + if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_ELTORITO"), drive); + + return true; + } + + bool unformatted = false; + bool unsupported_ext = false; + int path_no; + bool MountFat(Bitu sizes[], const char drive, const bool isHardDrive, const std::string &str_size, const std::vector &paths, const signed char ide_index, const bool ide_slave, const int reserved_cylinders, bool roflag) { + // printf("Trying path: %s\n", paths[i].c_str()); + (void)reserved_cylinders; + if (Drives[drive - 'A']) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); + return false; + } + + for (auto i=options.begin();i!=options.end();i++) { + if ((*i) == "int13") { + char buf[32]; + + if (drive >= 'C') + sprintf(buf,"=%u",drive+0x80-'C'); + else + sprintf(buf,"=%u",drive-'A'); + + (*i) += buf; + } + } + + bool imgsizedetect = isHardDrive && sizes[0] == 0; + int mediaid = -1; + + std::vector imgDisks; + std::vector::size_type i; + std::vector::size_type ct; + + for (i = 0; i < paths.size(); i++) { + const char* errorMessage = NULL; + imageDisk* vhdImage = NULL; + imageDisk* newImage = NULL; + bool ro=false; + + //detect hard drive geometry + if (paths[i] == "empty") { + errorMessage = "empty file not supported for drive letter mount\n"; + } + else if (imgsizedetect) { + bool skipDetectGeometry = false; + sizes[0] = 0; + sizes[1] = 0; + sizes[2] = 0; + sizes[3] = 0; + + /* .HDI images contain the geometry explicitly in the header. */ + if (str_size.size() == 0) { + const char *ext = strrchr(paths[i].c_str(), '.'); + if (ext != NULL) { + if (!strcasecmp(ext, ".hdi")) { + skipDetectGeometry = true; + } + else if (!strcasecmp(ext, ".nhd")) { + skipDetectGeometry = true; + } + else if (!strcasecmp(ext, ".nfd")) { + skipDetectGeometry = true; + } + //for all vhd files where the system will autodetect the chs values, + else if (!strcasecmp(ext, ".vhd")) { + ro=wpcolon&&paths[i].length()>1&&paths[i].c_str()[0]==':'; + //load the file with imageDiskVHD, which supports fixed/dynamic/differential disks + imageDiskVHD::ErrorCodes ret = imageDiskVHD::Open(ro?paths[i].c_str()+1:paths[i].c_str(), ro||roflag, &vhdImage); + switch (ret) { + case imageDiskVHD::UNSUPPORTED_WRITE: + options.emplace_back("readonly"); + case imageDiskVHD::OPEN_SUCCESS: { + skipDetectGeometry = true; + const imageDiskVHD* vhdDisk = dynamic_cast(vhdImage); + if (vhdDisk != NULL) { + LOG_MSG("VHD image detected SS,S,H,C: %u,%u,%u,%u", + (uint32_t)vhdDisk->sector_size, (uint32_t)vhdDisk->sectors, (uint32_t)vhdDisk->heads, (uint32_t)vhdDisk->cylinders); + if (vhdDisk->cylinders>1023) LOG_MSG("WARNING: cylinders>1023, INT13 will not work unless extensions are used"); + if(vhdDisk->GetVHDType() == imageDiskVHD::VHD_TYPE_FIXED) LOG_MSG("VHD is a fixed image"); + if(vhdDisk->GetVHDType() == imageDiskVHD::VHD_TYPE_DYNAMIC) LOG_MSG("VHD is a dynamic image"); + if(vhdDisk->GetVHDType() == imageDiskVHD::VHD_TYPE_DIFFERENCING) LOG_MSG("VHD is a differencing image"); + } + break; + } + case imageDiskVHD::ERROR_OPENING: + errorMessage = MSG_Get("VHD_ERROR_OPENING"); break; + case imageDiskVHD::INVALID_DATA: + errorMessage = MSG_Get("VHD_INVALID_DATA"); break; + case imageDiskVHD::UNSUPPORTED_TYPE: + errorMessage = MSG_Get("VHD_UNSUPPORTED_TYPE"); break; + case imageDiskVHD::ERROR_OPENING_PARENT: + errorMessage = MSG_Get("VHD_ERROR_OPENING_PARENT"); break; + case imageDiskVHD::PARENT_INVALID_DATA: + errorMessage = MSG_Get("VHD_PARENT_INVALID_DATA"); break; + case imageDiskVHD::PARENT_UNSUPPORTED_TYPE: + errorMessage = MSG_Get("VHD_PARENT_UNSUPPORTED_TYPE"); break; + case imageDiskVHD::PARENT_INVALID_MATCH: + errorMessage = MSG_Get("VHD_PARENT_INVALID_MATCH"); break; + case imageDiskVHD::PARENT_INVALID_DATE: + errorMessage = MSG_Get("VHD_PARENT_INVALID_DATE"); break; + default: break; + } + } + else if(!strcasecmp(ext, ".qcow2")) { + ro = wpcolon && paths[i].length() > 1 && paths[i].c_str()[0] == ':'; + const char* fname = ro ? paths[i].c_str() + 1 : paths[i].c_str(); + FILE* newDisk = fopen_lock(fname, ro ? "rb" : "rb+", ro); + if(!newDisk) { + if(!qmount) WriteOut("Unable to open '%s'\n", fname); + return false; + } + QCow2Image::QCow2Header qcow2_header = QCow2Image::read_header(newDisk); + // uint64_t sectors; /* unused */ + uint32_t imagesize; + sizes[0] = 512; // default sector size + if(qcow2_header.magic == QCow2Image::magic && (qcow2_header.version == 2 || qcow2_header.version == 3)) { + uint32_t cluster_size = 1u << qcow2_header.cluster_bits; + if((sizes[0] < 512) || ((cluster_size % sizes[0]) != 0)) { + WriteOut("Sector size must be larger than 512 bytes and evenly divide the image cluster size of %lu bytes.\n", cluster_size); + return false; + } + // sectors = (uint64_t)qcow2_header.size / (uint64_t)sizes[0]; /* unused */ + imagesize = (uint32_t)(qcow2_header.size / 1024L); + sizes[1] = 63; // sectors + sizes[2] = 16; // heads + sizes[3] = (uint64_t)qcow2_header.size / sizes[0] / sizes[1] / sizes[2]; // cylinders + // setbuf(newDisk, NULL); + newImage = new QCow2Disk(qcow2_header, newDisk, fname, imagesize, (uint32_t)sizes[0], (imagesize > 2880)); + skipDetectGeometry = true; + newImage->sector_size = sizes[0]; // sector size + newImage->sectors = sizes[1]; // sectors + newImage->heads = sizes[2]; // heads + newImage->cylinders = sizes[3]; // cylinders + } + else { + WriteOut("qcow2 image '%s' is not supported\n", fname); + fclose(newDisk); + newImage = NULL; + } + } + else if (!strcasecmp(ext,".img") || !strcasecmp(ext,".ima")){ // Raw MFM image format is typically .img or .ima + unsupported_ext = false; + } + else { + LOG_MSG("IMGMOUNT: Perhaps unsupported extension %s", ext); + unsupported_ext = true; + path_no = i; + } + } + } + if (!skipDetectGeometry && !DetectGeometry(NULL, paths[i].c_str(), sizes)) { + errorMessage = "Unable to detect geometry\n"; + } + } + + if (!errorMessage) { + DOS_Drive* newDrive = NULL; + if (vhdImage) { + newDrive = new fatDrive(vhdImage, options); + strcpy(newDrive->info, "fatDrive "); + strcat(newDrive->info, ro?paths[i].c_str()+1:paths[i].c_str()); + vhdImage = NULL; + } + else if(newImage) { + newDrive = new fatDrive(newImage, options); + strcpy(newDrive->info, "fatDrive "); + strcat(newDrive->info, ro ? paths[i].c_str() + 1 : paths[i].c_str()); + LOG_MSG("IMGMOUNT: qcow2 image mounted (experimental)"); + LOG_MSG("IMGMOUNT: qcow2 SS,S,H,C: %u,%u,%u,%u", + (uint32_t)newImage->sector_size, (uint32_t)newImage->sectors, (uint32_t)newImage->heads, (uint32_t)newImage->cylinders); + newImage = NULL; + } + else { + if (roflag) options.emplace_back("readonly"); + newDrive = new fatDrive(paths[i].c_str(), (uint32_t)sizes[0], (uint32_t)sizes[1], (uint32_t)sizes[2], (uint32_t)sizes[3], options); + } + imgDisks.push_back(newDrive); + fatDrive* fdrive=dynamic_cast(newDrive); + if (!fdrive->created_successfully) { + errorMessage = MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE"); + if (fdrive->req_ver_major>0) { + static char ver_msg[150]; + sprintf(ver_msg, "Mounting this image file requires a reported DOS version of %u.%u or higher.\n%s", fdrive->req_ver_major, fdrive->req_ver_minor, errorMessage); + errorMessage = ver_msg; + } + } else { + if (imgDisks.size() == 1) mediaid = (int)((unsigned char)fdrive->GetMediaByte()); + if ((vhdImage&&ro)||roflag) fdrive->readonly=true; + } + unformatted = fdrive->unformatted; + } + if (errorMessage) { + if (!qmount) WriteOut(errorMessage); + for (ct = 0; ct < imgDisks.size(); ct++) { + delete imgDisks[ct]; + } + return false; + } + } + + AddToDriveManager(drive, imgDisks, (mediaid >= 0xF0) ? mediaid : (isHardDrive ? 0xF8 : 0xF0)); + DOS_EnableDriveMenu(drive); + + std::string tmp(wpcolon&&paths[0].length()>1&&paths[0].c_str()[0]==':'?paths[0].substr(1):paths[0]); + for (i = 1; i < paths.size(); i++) { + tmp += "; " + (wpcolon&&paths[i].length()>1&&paths[i].c_str()[0]==':'?paths[i].substr(1):paths[i]); + } + lastmount = drive; + if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"), drive, tmp.c_str()); + if (unformatted) { + if(!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_NOT_FORMATTED")); + LOG_MSG("IMGMOUNT: Drive %c not formatted", drive); + } + if (unsupported_ext) { + const char *ext = strrchr(paths[path_no].c_str(), '.'); + if (ext != NULL) { + if(!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_UNSUPPORTED_EXT"), ext); + LOG_MSG("Unsupported extension %s: Mounted as raw IMG image.", ext); + } + } + unsigned char driveIndex = drive-'A'; + if (imgDisks.size() == 1 || (imgDisks.size() > 1 && driveIndex < 2 && (swapInDisksSpecificDrive == driveIndex || swapInDisksSpecificDrive == -1))) { + imageDisk* image = ((fatDrive*)imgDisks[0])->loadedDisk; + if (AttachToBiosAndIdeByLetter(image, drive, (unsigned char)ide_index, ide_slave)) { + if (swapInDisksSpecificDrive == driveIndex || swapInDisksSpecificDrive == -1) { + for (size_t si=0;si < MAX_SWAPPABLE_DISKS;si++) { + if (diskSwap[si] != NULL) { + diskSwap[si]->Release(); + diskSwap[si] = NULL; + } + } + swapInDisksSpecificDrive = -1; + if (paths.size() > 1) { + /* slot 0 is the image we already assigned */ + diskSwap[0] = image; + diskSwap[0]->Addref(); + swapPosition = 0; + swapInDisksSpecificDrive = driveIndex; + + for (size_t si=1;si < MAX_SWAPPABLE_DISKS && si < paths.size();si++) { + imageDisk *img = ((fatDrive*)imgDisks[si])->loadedDisk; + diskSwap[si] = img; + diskSwap[si]->Addref(); + } + } + } + } + + /* now that the image is attached to INT 13h the INT 13 image can use it now */ + if (image->class_id == imageDisk::ID_INT13) { + imageDiskINT13Drive *x = (imageDiskINT13Drive*)image; + x->enable_int13 = true; + LOG(LOG_MISC,LOG_DEBUG)("INT 13 image enabling calling"); + } + } + return true; + } + + imageDisk* MountImageNoneRam(Bitu sizes[], const int reserved_cylinders, const bool forceFloppy) { + imageDiskMemory* dsk = CreateRamDrive(sizes, reserved_cylinders, forceFloppy, this); + if (dsk == NULL) return NULL; + //formatting might fail; just log the failure and continue + uint8_t ret = dsk->Format(); + if (ret != 0x00) { + LOG_MSG("Warning: could not format RAM drive - error code %u\n", (unsigned int)ret); + } + return dsk; + } + + bool MountRam(Bitu sizes[], const char drive, const signed char ide_index, const bool ide_slave, bool roflag) { + if (Drives[drive - 'A']) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); + return false; + } + + //by default, make a floppy disk if A: or B: is specified (still makes a hard drive if not a recognized size) + imageDiskMemory* dsk = CreateRamDrive(sizes, 0, (drive - 'A') < 2 && sizes[0] == 0, this); + if (dsk == NULL) return false; + if (dsk->Format() != 0x00) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); + delete dsk; + return false; + } + dsk->Addref(); + DOS_Drive* newDrive = new fatDrive(dsk, options); + if (roflag) newDrive->readonly=true; + dsk->Release(); + if (!(dynamic_cast(newDrive))->created_successfully) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_CANT_CREATE")); + delete newDrive; //this executes dsk.Release() which executes delete dsk + return false; + } + + AddToDriveManager(drive, newDrive, dsk->hardDrive ? 0xF8 : 0xF0); + DOS_EnableDriveMenu(drive); + + lastmount = drive; + if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_RAMDRIVE"), drive); + + AttachToBiosAndIdeByLetter(dsk, drive, (unsigned char)ide_index, ide_slave); + + return true; + } + + void AddToDriveManager(const char drive, DOS_Drive* imgDisk, const uint8_t mediaid) const { + std::vector imgDisks = { imgDisk }; + AddToDriveManager(drive, imgDisks, mediaid); + } + + void AddToDriveManager(const char drive, const std::vector &imgDisks, const uint8_t mediaid) const { + std::vector::size_type ct; + + // Update DriveManager + for (ct = 0; ct < imgDisks.size(); ct++) { + DriveManager::AppendDisk(drive - 'A', imgDisks[ct]); + } + DriveManager::InitializeDrive(drive - 'A'); + + // Set the correct media byte in the table + mem_writeb(Real2Phys(dos.tables.mediaid) + ((unsigned int)drive - 'A') * dos.tables.dpb_size, mediaid); + + /* Command uses dta so set it to our internal dta */ + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + + for (ct = 0; ct < imgDisks.size(); ct++) { + DriveManager::CycleDisks(drive - 'A', (ct == (imgDisks.size() - 1))); + + char root[7] = { drive, ':', '\\', '*', '.', '*', 0 }; + DOS_FindFirst(root, DOS_ATTR_VOLUME); // force obtaining the label and saving it in dirCache + } + dos.dta(save_dta); + + } + + bool DetectGeometry_Mem(const char* fileName, Bitu sizes[]) { + bool yet_detected = false, readonly = wpcolon&&strlen(fileName)>1&&fileName[0]==':'; + jaffarCommon::file::MemoryFile * diskfile = _memFileDirectory.fopen(readonly?fileName+1:fileName, "rb"); + + if (!diskfile) { + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_IMAGE")); + return false; + } + jaffarCommon::file::MemoryFile::fseeko64(diskfile, 0L, SEEK_END); + uint32_t fcsize = (uint32_t)(jaffarCommon::file::MemoryFile::ftello64(diskfile) / 512L); + uint8_t buf[512]; + jaffarCommon::file::MemoryFile::fseeko64(diskfile, 0L, SEEK_SET); + if (jaffarCommon::file::MemoryFile::fread(buf, sizeof(uint8_t), 512, diskfile)<512) { + _memFileDirectory.fclose(diskfile); + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_IMAGE")); + return false; + } + _memFileDirectory.fclose(diskfile); + + + // check MBR signature for unknown images + if (!yet_detected && ((buf[510] != 0x55) || (buf[511] != 0xaa))) { + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_GEOMETRY")); + return false; + } + // check MBR partition entry 1 + if (!yet_detected) + yet_detected = DetectMFMsectorPartition(buf, fcsize, sizes); + + // Try bximage disk geometry + // bximage flat images should already be detected by + // DetectMFMSectorPartition(), not sure what this adds... + if (!yet_detected) { + yet_detected = DetectBximagePartition(fcsize, sizes); + } + + uint8_t ptype = buf[0x1c2]; // Location of DOS 3.3+ partition type + bool assume_lba = false; + + /* If the first partition is a Windows 95 FAT32 (LBA) type partition, and we failed to detect, + * then assume LBA and make up a geometry */ + if (!yet_detected && (ptype == 0x0C/*FAT32+LBA*/ || ptype == 0x0E/*FAT16+LBA*/)) { + yet_detected = 1; + assume_lba = true; + LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on first partition type (FAT with LBA)"); + } + + /* If the MBR has only a partition table, but the part that normally contains executable + * code is all zeros. To avoid false negatives, check only the first 0x20 bytes since + * at boot time executable code must reside there to do something, and many of these + * disk images while they ARE mostly zeros, do have some extra nonzero bytes immediately + * before the partition table at 0x1BE. + * + * Modern FAT32 generator tools and older digital cameras will format FAT32 like this. + * These tools are unlikely to support non-LBA disks. + * + * To avoid false positives, the partition type has to be something related to FAT */ + if (!yet_detected && (ptype == 0x01 || ptype == 0x04 || ptype == 0x06 || ptype == 0x0B || ptype == 0x0C || ptype == 0x0E)) { + /* buf[] still contains MBR */ + unsigned int i=0; + while (i < 0x20 && buf[i] == 0) i++; + if (i == 0x20) { + yet_detected = 1; + assume_lba = true; + LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on first partition type (FAT-related) and lack of executable code in the MBR"); + } + } + + /* If we failed to detect, but the disk image is 4GB or larger, make up a geometry because + * IDE drives by that point were pure LBA anyway and supported C/H/S for the sake of + * backward compatibility anyway. fcsize is in 512-byte sectors. */ + if (!yet_detected && fcsize >= ((4ull*1024ull*1024ull*1024ull)/512ull)) { + yet_detected = 1; + assume_lba = true; + LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on size"); + } + + if (yet_detected && assume_lba) { + sizes[0] = 512; + sizes[1] = 63; + sizes[2] = 255; + { + const Bitu d = sizes[1]*sizes[2]; + sizes[3] = (fcsize + d - 1) / d; /* round up */ + } + } + + if (yet_detected) { + //"Image geometry auto detection: -size %u,%u,%u,%u\r\n", + //sizes[0],sizes[1],sizes[2],sizes[3]); + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_AUTODET_VALUES"), sizes[0], sizes[1], sizes[2], sizes[3]); + return true; + } + else { + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_GEOMETRY")); + return false; + } + } + + bool DetectGeometry(FILE * file, const char* fileName, Bitu sizes[]) { + bool yet_detected = false, readonly = wpcolon&&strlen(fileName)>1&&fileName[0]==':'; + FILE * diskfile = file==NULL?fopen64(readonly?fileName+1:fileName, "rb"):file; + #if defined(WIN32) + if (!diskfile && file==NULL) { + const host_cnv_char_t* host_name = CodePageGuestToHost(readonly?fileName+1:fileName); + if (host_name != NULL) diskfile = _wfopen(host_name, L"rb"); + } + #endif + if (!diskfile) { + return DetectGeometry_Mem(fileName, sizes); + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_IMAGE")); + return false; + } + fseeko64(diskfile, 0L, SEEK_END); + uint32_t fcsize = (uint32_t)(ftello64(diskfile) / 512L); + uint8_t buf[512]; + #if 0 // VHD pseudo geometry should be avoided always! + // New VHD driver is capable of MBR/BPB analysis. + + // check for vhd signature + fseeko64(diskfile, -512, SEEK_CUR); + if (fread(buf, sizeof(uint8_t), 512, diskfile)<512) { + fclose(diskfile); + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_IMAGE")); + return false; + } + if (!strcmp((const char*)buf, "conectix")) { + fcsize--; // skip footer (512 bytes) + sizes[0] = 512; // sector size + sizes[1] = buf[0x3b]; // sectors + sizes[2] = buf[0x3a]; // heads + sizes[3] = SDL_SwapBE16((uint16_t)(*(int16_t*)(buf + 0x38))); // cylinders + + // Do translation (?) + while ((sizes[2] < 128u) && (sizes[3] > 1023u)) { + sizes[2] <<= 1u; + sizes[3] >>= 1u; + } + + if (sizes[3]>1023) { + // Set x/255/63 + sizes[2] = 255; + sizes[3] = fcsize / sizes[2] / sizes[1]; + } + + LOG_MSG("VHD image detected: %u,%u,%u,%u", + (unsigned int)sizes[0], (unsigned int)sizes[1], (unsigned int)sizes[2], (unsigned int)sizes[3]); + if (sizes[3]>1023) LOG_MSG("WARNING: cylinders>1023, INT13 will not work unless extensions are used"); + yet_detected = true; + } + #endif + fseeko64(diskfile, 0L, SEEK_SET); + if (fread(buf, sizeof(uint8_t), 512, diskfile)<512) { + fclose(diskfile); + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_IMAGE")); + return false; + } + if (file==NULL) fclose(diskfile); + // check MBR signature for unknown images + if (!yet_detected && ((buf[510] != 0x55) || (buf[511] != 0xaa))) { + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_GEOMETRY")); + return false; + } + // check MBR partition entry 1 + if (!yet_detected) + yet_detected = DetectMFMsectorPartition(buf, fcsize, sizes); + + // Try bximage disk geometry + // bximage flat images should already be detected by + // DetectMFMSectorPartition(), not sure what this adds... + if (!yet_detected) { + yet_detected = DetectBximagePartition(fcsize, sizes); + } + + uint8_t ptype = buf[0x1c2]; // Location of DOS 3.3+ partition type + bool assume_lba = false; + + /* If the first partition is a Windows 95 FAT32 (LBA) type partition, and we failed to detect, + * then assume LBA and make up a geometry */ + if (!yet_detected && (ptype == 0x0C/*FAT32+LBA*/ || ptype == 0x0E/*FAT16+LBA*/)) { + yet_detected = 1; + assume_lba = true; + LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on first partition type (FAT with LBA)"); + } + + /* If the MBR has only a partition table, but the part that normally contains executable + * code is all zeros. To avoid false negatives, check only the first 0x20 bytes since + * at boot time executable code must reside there to do something, and many of these + * disk images while they ARE mostly zeros, do have some extra nonzero bytes immediately + * before the partition table at 0x1BE. + * + * Modern FAT32 generator tools and older digital cameras will format FAT32 like this. + * These tools are unlikely to support non-LBA disks. + * + * To avoid false positives, the partition type has to be something related to FAT */ + if (!yet_detected && (ptype == 0x01 || ptype == 0x04 || ptype == 0x06 || ptype == 0x0B || ptype == 0x0C || ptype == 0x0E)) { + /* buf[] still contains MBR */ + unsigned int i=0; + while (i < 0x20 && buf[i] == 0) i++; + if (i == 0x20) { + yet_detected = 1; + assume_lba = true; + LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on first partition type (FAT-related) and lack of executable code in the MBR"); + } + } + + /* If we failed to detect, but the disk image is 4GB or larger, make up a geometry because + * IDE drives by that point were pure LBA anyway and supported C/H/S for the sake of + * backward compatibility anyway. fcsize is in 512-byte sectors. */ + if (!yet_detected && fcsize >= ((4ull*1024ull*1024ull*1024ull)/512ull)) { + yet_detected = 1; + assume_lba = true; + LOG_MSG("Failed to autodetect geometry, assuming LBA approximation based on size"); + } + + if (yet_detected && assume_lba) { + sizes[0] = 512; + sizes[1] = 63; + sizes[2] = 255; + { + const Bitu d = sizes[1]*sizes[2]; + sizes[3] = (fcsize + d - 1) / d; /* round up */ + } + } + + if (yet_detected) { + //"Image geometry auto detection: -size %u,%u,%u,%u\r\n", + //sizes[0],sizes[1],sizes[2],sizes[3]); + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_AUTODET_VALUES"), sizes[0], sizes[1], sizes[2], sizes[3]); + return true; + } + else { + if (!qmount) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_INVALID_GEOMETRY")); + return false; + } + } + + + + bool DetectMFMsectorPartition(uint8_t buf[], uint32_t fcsize, Bitu sizes[]) const { + // This is used for plain MFM sector format as created by IMGMAKE + // It tries to find the first partition. Addressing is in CHS format. + /* Offset | Length | Description + * +0 | 1 byte | 80 hex = active, 00 = inactive + * +1 | 3 bytes | CHS of first sector in partition + * +4 | 1 byte | partition type + * +5 | 3 bytes | CHS of last sector in partition + * +8 | 4 bytes | LBA of first sector in partition + * +C | 4 bytes | Number of sectors in partition. 0 may mean, use LBA + */ + uint8_t starthead = 0; // start head of partition + uint8_t startsect = 0; // start sector of partition + uint16_t startcyl = 0; // start cylinder of partition + //uint8_t ptype = 0; // Partition Type + uint16_t endcyl = 0; // end cylinder of partition + uint8_t heads = 0; // heads in partition + uint8_t sectors = 0; // sectors per track in partition + uint32_t pe1_size = host_readd(&buf[0x1ca]); + if ((uint32_t)host_readd(&buf[0x1fa]) != 0) { // DOS 2.0-3.21 partition table + pe1_size = host_readd(&buf[0x1fa]); + starthead = buf[0x1ef]; + startsect = (buf[0x1f0] & 0x3fu) - 1u; + startcyl = (unsigned char)buf[0x1f1] | (unsigned int)((buf[0x1f0] & 0xc0) << 2u); + endcyl = (unsigned char)buf[0x1f5] | (unsigned int)((buf[0x1f4] & 0xc0) << 2u); + //ptype = buf[0x1f2]; + heads = buf[0x1f3] + 1u; + sectors = buf[0x1f4] & 0x3fu; + } else if (pe1_size != 0) { // DOS 3.3+ partition table, starting at 0x1BE + starthead = buf[0x1bf]; + startsect = (buf[0x1c0] & 0x3fu) - 1u; + startcyl = (unsigned char)buf[0x1c1] | (unsigned int)((buf[0x1c0] & 0xc0) << 2u); + endcyl = (unsigned char)buf[0x1c5] | (unsigned int)((buf[0x1c4] & 0xc0) << 2u); + //ptype = buf[0x1c2]; + heads = buf[0x1c3] + 1u; + sectors = buf[0x1c4] & 0x3fu; + } + if (pe1_size != 0) { + uint32_t part_start = startsect + sectors * starthead + + startcyl * sectors * heads; + uint32_t part_end = heads * sectors * endcyl; + uint32_t part_len = part_end - part_start; + // partition start/end sanity check + // partition length should not exceed file length + // real partition size can be a few cylinders less than pe1_size + // if more than 1023 cylinders see if first partition fits + // into 1023, else bail. + if (/*(part_len<0) always false because unsigned || */(part_len > pe1_size) || (pe1_size > fcsize) || + ((pe1_size - part_len) / (sectors*heads)>2u) || + ((pe1_size / (heads*sectors))>1023u)) { + //LOG_MSG("start(c,h,s) %u,%u,%u",startcyl,starthead,startsect); + //LOG_MSG("endcyl %u heads %u sectors %u",endcyl,heads,sectors); + //LOG_MSG("psize %u start %u end %u",pe1_size,part_start,part_end); + } else { + sizes[0] = 512; sizes[1] = sectors; + sizes[2] = heads; sizes[3] = (uint16_t)(fcsize / (heads*sectors)); + if (sizes[3]>1023) sizes[3] = 1023; + return true; + } + } + return false; + } + + bool DetectBximagePartition(uint32_t fcsize, Bitu sizes[]) const { + // Try bximage disk geometry + uint32_t cylinders = fcsize / (16 * 63); + // Int13 only supports up to 1023 cylinders + // For mounting unknown images we could go up with the heads to 255 + if ((cylinders * 16 * 63 == fcsize) && (cylinders<1024)) { + sizes[0] = 512; sizes[1] = 63; sizes[2] = 16; sizes[3] = cylinders; + return true; + } + return false; + } + + bool MountIso(const char drive, const std::vector &paths, const signed char ide_index, const bool ide_slave) { + //mount cdrom + if (Drives[drive - 'A']) { + WriteOut(MSG_Get("PROGRAM_IMGMOUNT_ALREADY_MOUNTED")); + return false; + } + uint8_t mediaid = 0xF8; + MSCDEX_SetCDInterface(CDROM_USE_SDL, -1); + // create new drives for all images + std::vector isoDisks; + std::vector::size_type i; + std::vector::size_type ct; + for (i = 0; i < paths.size(); i++) { + int error = -1; + DOS_Drive* newDrive = new isoDrive(drive, wpcolon&&paths[i].length()>1&&paths[i].c_str()[0]==':'?paths[i].c_str()+1:paths[i].c_str(), mediaid, error, options); + isoDisks.push_back(newDrive); + if(!qmount) + switch(error) { + case 0: break; + case 1: WriteOut(MSG_Get("MSCDEX_ERROR_MULTIPLE_CDROMS")); break; + case 2: WriteOut(MSG_Get("MSCDEX_ERROR_NOT_SUPPORTED")); break; + case 3: WriteOut(MSG_Get("MSCDEX_ERROR_OPEN")); break; + case 4: WriteOut(MSG_Get("MSCDEX_TOO_MANY_DRIVES")); break; + case 5: WriteOut(MSG_Get("MSCDEX_LIMITED_SUPPORT")); break; + case 6: WriteOut(MSG_Get("MSCDEX_INVALID_FILEFORMAT")); break; + default: WriteOut(MSG_Get("MSCDEX_UNKNOWN_ERROR")); break; + } + // error: clean up and leave + if (error) { + for (ct = 0; ct < isoDisks.size(); ct++) { + delete isoDisks[ct]; + } + return false; + } + } + // Update DriveManager + for (ct = 0; ct < isoDisks.size(); ct++) { + DriveManager::AppendDisk(drive - 'A', isoDisks[ct]); + } + DriveManager::InitializeDrive(drive - 'A'); + DOS_EnableDriveMenu(drive); + + // Set the correct media byte in the table + mem_writeb(Real2Phys(dos.tables.mediaid) + ((unsigned int)drive - 'A') * dos.tables.dpb_size, mediaid); + + // If instructed, attach to IDE controller as ATAPI CD-ROM device + if (ide_index >= 0) IDE_CDROM_Attach(ide_index, ide_slave, drive - 'A'); + + // Print status message (success) + if (!qmount) WriteOut(MSG_Get("MSCDEX_SUCCESS")); + if (!paths.empty()) { + std::string tmp(wpcolon&&paths[0].length()>1&&paths[0].c_str()[0]==':'?paths[0].substr(1):paths[0]); + for (i = 1; i < paths.size(); i++) { + tmp += "; " + (wpcolon&&paths[i].length()>1&&paths[i].c_str()[0]==':'?paths[i].substr(1):paths[i]); + } + lastmount = drive; + if (!qmount) WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_2"), drive, tmp.c_str()); + } + else { + lastmount = drive; + } + return true; + } + + imageDisk* MountImageNone(const char* fileName, FILE* file, const Bitu sizesOriginal[], const int reserved_cylinders, bool roflag) { + bool assumeHardDisk = false; + imageDisk* newImage = nullptr; + Bitu sizes[4]; + sizes[0] = sizesOriginal[0]; + sizes[1] = sizesOriginal[1]; + sizes[2] = sizesOriginal[2]; + sizes[3] = sizesOriginal[3]; + + if (!strcmp(fileName,"empty")) { + imageDiskEmptyDrive *emd = new imageDiskEmptyDrive(); + if (sizes[0] != 0 && sizes[1] != 0 && sizes[2] != 0 && sizes[3] != 0) { + emd->sector_size = sizes[0]; + emd->sectors = sizes[1]; + emd->heads = sizes[2]; + emd->cylinders = sizes[3]; + emd->diskSizeK = ((sizes[0]*sizes[1]*sizes[2]*sizes[3])+512)/1024; + emd->UpdateFloppyType(); + } + LOG_MSG("Mounted empty C/H/S/sz %u/%u/%u/%u %uKB", + (unsigned int)emd->cylinders, + (unsigned int)emd->heads, + (unsigned int)emd->sectors, + (unsigned int)emd->sector_size, + (unsigned int)emd->diskSizeK); + return emd; + } + + //check for VHD files + if (sizes[0] == 0 /* auto detect size */) { + const char *ext = strrchr(fileName, '.'); + if (ext != NULL) { + if (!strcasecmp(ext, ".vhd")) { + bool ro=wpcolon&&strlen(fileName)>1&&fileName[0]==':'; + imageDiskVHD::ErrorCodes ret = imageDiskVHD::Open(ro?fileName+1:fileName, ro||roflag, &newImage); + switch (ret) { + case imageDiskVHD::ERROR_OPENING: WriteOut(MSG_Get("VHD_ERROR_OPENING")); break; + case imageDiskVHD::INVALID_DATA: WriteOut(MSG_Get("VHD_INVALID_DATA")); break; + case imageDiskVHD::UNSUPPORTED_TYPE: WriteOut(MSG_Get("VHD_UNSUPPORTED_TYPE")); break; + case imageDiskVHD::ERROR_OPENING_PARENT: WriteOut(MSG_Get("VHD_ERROR_OPENING_PARENT")); break; + case imageDiskVHD::PARENT_INVALID_DATA: WriteOut(MSG_Get("VHD_PARENT_INVALID_DATA")); break; + case imageDiskVHD::PARENT_UNSUPPORTED_TYPE: WriteOut(MSG_Get("VHD_PARENT_UNSUPPORTED_TYPE")); break; + case imageDiskVHD::PARENT_INVALID_MATCH: WriteOut(MSG_Get("VHD_PARENT_INVALID_MATCH")); break; + case imageDiskVHD::PARENT_INVALID_DATE: WriteOut(MSG_Get("VHD_PARENT_INVALID_DATE")); break; + case imageDiskVHD::UNSUPPORTED_WRITE: roflag=true; break; + default: break; + } + return newImage; + } + else if (!strcasecmp(ext, ".hdi")) { + assumeHardDisk = true; /* bugfix for HDI images smaller than 2.88MB so that the .hdi file is not mistaken for a floppy disk image */ + } + } + } + + uint32_t imagesize; + /* auto-fill: sector size */ + if (sizes[0] == 0) sizes[0] = 512; + + bool readonly = wpcolon&&strlen(fileName)>1&&fileName[0]==':'; + const char* fname=readonly?fileName+1:fileName; + FILE *newDisk = file==NULL?fopen_lock(fname, readonly||roflag?"rb":"rb+", roflag):file; + if (!newDisk) { + if (!qmount) WriteOut("Unable to open '%s'\n", fname); + return NULL; + } + + QCow2Image::QCow2Header qcow2_header = QCow2Image::read_header(newDisk); + + uint64_t sectors; + if (qcow2_header.magic == QCow2Image::magic && (qcow2_header.version == 2 || qcow2_header.version == 3)) { + uint32_t cluster_size = 1u << qcow2_header.cluster_bits; + if ((sizes[0] < 512) || ((cluster_size % sizes[0]) != 0)) { + WriteOut("Sector size must be larger than 512 bytes and evenly divide the image cluster size of %lu bytes.\n", cluster_size); + return nullptr; + } + sectors = (uint64_t)qcow2_header.size / (uint64_t)sizes[0]; + imagesize = (uint32_t)(qcow2_header.size / 1024L); + // setbuf(newDisk, NULL); + newImage = new QCow2Disk(qcow2_header, newDisk, fname, imagesize, (uint32_t)sizes[0], (imagesize > 2880)); + } + else { + char tmp[256]; + + fseeko64(newDisk, 0L, SEEK_SET); + size_t readResult = fread(tmp, 256, 1, newDisk); // look for magic signatures + if (readResult != 1) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in MountImageNone\n"); + return NULL; + } + + const char *ext = strrchr(fname,'.'); + + if (ext != NULL && !strcasecmp(ext, ".d88")) { + fseeko64(newDisk, 0L, SEEK_END); + sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; + imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ + // setbuf(newDisk, NULL); + newImage = new imageDiskD88(newDisk, fname, imagesize, false/*this is a FLOPPY image format*/); + } + else if (!memcmp(tmp, "VFD1.", 5)) { /* FDD files */ + fseeko64(newDisk, 0L, SEEK_END); + sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; + imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ + // setbuf(newDisk, NULL); + newImage = new imageDiskVFD(newDisk, fname, imagesize, false/*this is a FLOPPY image format*/); + } + else if (!memcmp(tmp,"T98FDDIMAGE.R0\0\0",16)) { + fseeko64(newDisk, 0L, SEEK_END); + sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; + imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ + // setbuf(newDisk, NULL); + newImage = new imageDiskNFD(newDisk, fname, imagesize, false/*this is a FLOPPY image format*/, 0); + } + else if (!memcmp(tmp,"T98FDDIMAGE.R1\0\0",16)) { + fseeko64(newDisk, 0L, SEEK_END); + sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; + imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ + // setbuf(newDisk, NULL); + newImage = new imageDiskNFD(newDisk, fname, imagesize, false/*this is a FLOPPY image format*/, 1); + } + else { + fseeko64(newDisk, 0L, SEEK_END); + sectors = (uint64_t)ftello64(newDisk) / (uint64_t)sizes[0]; + imagesize = (uint32_t)(sectors / 2); /* orig. code wants it in KBs */ + // setbuf(newDisk, NULL); + newImage = new imageDisk(newDisk, fname, imagesize, (imagesize > 2880) || assumeHardDisk); + } + } + + /* sometimes imageDisk is able to determine geometry automatically (HDI images) */ + if (newImage) { + if (newImage->sectors != 0 && newImage->heads != 0 && newImage->cylinders != 0 && newImage->sector_size != 0) { + /* prevent the code below from changing the geometry */ + sizes[0] = newImage->sector_size; + sizes[1] = newImage->sectors; + sizes[2] = newImage->heads; + sizes[3] = newImage->cylinders; + } + } + + /* try auto-detect */ + if (sizes[3] == 0 && sizes[2] == 0) { + DetectGeometry(newDisk, fname, sizes); + } + + /* auto-fill: sector/track count */ + if (sizes[1] == 0) sizes[1] = 63; + /* auto-fill: head/cylinder count */ + if (sizes[3]/*cylinders*/ == 0 && sizes[2]/*heads*/ == 0) { + sizes[2] = 16; /* typical hard drive, unless a very old drive */ + sizes[3]/*cylinders*/ = + (Bitu)(((uint64_t)sectors + ((uint64_t)sizes[2]/*heads*/ * (uint64_t)sizes[1]/*sectors/track*/) - (uint64_t)1u) / + ((uint64_t)sizes[2]/*heads*/ * (uint64_t)sizes[1]/*sectors/track*/)); + + if (IS_PC98_ARCH) { + /* TODO: PC-98 has its own issues with a 4096-cylinder limit */ + } + else { + /* INT 13h mapping, deal with 1024-cyl limit */ + while (sizes[3] > 1024) { + if (sizes[2] >= 255) break; /* nothing more we can do */ + + /* try to generate head count 16, 32, 64, 128, 255 */ + sizes[2]/*heads*/ *= 2; + if (sizes[2] >= 256) sizes[2] = 255; + + /* and recompute cylinders */ + sizes[3]/*cylinders*/ = + (Bitu)(((uint64_t)sectors + ((uint64_t)sizes[2]/*heads*/ * (uint64_t)sizes[1]/*sectors/track*/) - (uint64_t)1u) / + ((uint64_t)sizes[2]/*heads*/ * (uint64_t)sizes[1]/*sectors/track*/)); + } + } + } + + LOG(LOG_DOSMISC, LOG_NORMAL)("Mounting image as C/H/S %u/%u/%u with %u bytes/sector", + (unsigned int)sizes[3], (unsigned int)sizes[2], (unsigned int)sizes[1], (unsigned int)sizes[0]); + + if (imagesize > 2880) newImage->Set_Geometry((uint32_t)sizes[2], (uint32_t)sizes[3], (uint32_t)sizes[1], (uint32_t)sizes[0]); + if (reserved_cylinders > 0) newImage->Set_Reserved_Cylinders((Bitu)reserved_cylinders); + + return newImage; + } + }; + + void IMGMOUNT_ProgramStart(Program * * make) { + *make=new IMGMOUNT; + } + + void runImgmount(const char *str) { + IMGMOUNT imgmount; + imgmount.cmd=new CommandLine("IMGMOUNT", str); + imgmount.Run(); + } + + Bitu DOS_SwitchKeyboardLayout(const char* new_layout, int32_t& tried_cp); + Bitu DOS_LoadKeyboardLayout(const char * layoutname, int32_t codepage, const char * codepagefile); + Bitu DOS_ChangeKeyboardLayout(const char* layoutname, int32_t codepage); + Bitu DOS_ChangeCodepage(int32_t codepage, const char* codepagefile); + const char* DOS_GetLoadedLayout(void); + + class KEYB : public Program { + public: + void Run(void) override; + }; + + void KEYB::Run(void) { + if (cmd->FindCommand(1,temp_line)) { /* first parameter is layout ID */ + if (cmd->FindString("?",temp_line,false)) { + resetcolor = true; + WriteOut(MSG_Get("PROGRAM_KEYB_SHOWHELP")); + } else { + Bitu keyb_error=0; /* Return code of switching keyboard layouts */ + std::string cp_string=""; + const char* layout_id = temp_line.c_str(); + cmd->FindCommand(2,cp_string); /* second parameter is codepage number */ + int32_t cp = cp_string.size() ? atoi(cp_string.c_str()) : 0;; + int32_t tocp = !strcasecmp(layout_id, "jp") ? 932 : (!strcasecmp(layout_id, "ko") ? 949 : (!strcasecmp(layout_id, "tw") || !strcasecmp(layout_id, "hk") || !strcasecmp(layout_id, "zht") || (!strcasecmp(layout_id, "zh") && ((cp == 950 || cp == 951) || (!cp_string.size() && (dos.loaded_codepage == 950 || dos.loaded_codepage == 951)))) ? (cp == 951 || (!cp_string.size() && dos.loaded_codepage == 951) ? 951 : 950) : (!strcasecmp(layout_id, "cn") || !strcasecmp(layout_id, "zhs") || !strcasecmp(layout_id, "zh") ? 936 : 0))); + int32_t cpbak = dos.loaded_codepage; + const char* layout_name = DOS_GetLoadedLayout(); + if(tocp && !IS_PC98_ARCH) { + dos.loaded_codepage = tocp; + #if defined(USE_TTF) + if(ttf.inUse) { + dos.loaded_codepage = cpbak; + toSetCodePage(NULL, tocp, -1); + } + else + #endif + { + MSG_Init(); + DOSBox_SetSysMenu(); + if(isDBCSCP()) { + ShutFontHandle(); + InitFontHandle(); + JFONT_Init(); + } + SetupDBCSTable(); + runRescan("-A -Q"); + #if C_OPENGL && DOSBOXMENU_TYPE == DOSBOXMENU_SDLDRAW + if(OpenGL_using() && control->opt_lang.size() && lastcp && lastcp != dos.loaded_codepage) + UpdateSDLDrawTexture(); + #endif + } + if(!strcasecmp(layout_id, "jp")) { + keyb_error = DOS_LoadKeyboardLayout("jp", tocp, "auto"); /* Load a default layout if not loaded at all */ + if(cp) keyb_error = DOS_ChangeCodepage(cp , "auto"); + if(keyb_error == KEYB_NOERROR) DOS_ChangeKeyboardLayout("jp", cp ? cp : tocp); + } + else { + keyb_error = DOS_SwitchKeyboardLayout("us", tocp); /* set Korean and Chinese keyboard layout to be "us" */ + /* FIX_ME: Chinese keyboards are identical to US keyboards, but some fixes may be needed for Korean unique keys */ + } + } + else if (cp) { + char cp_file_name[256]; + if (cmd->FindCommand(3,cp_string)) { + /* third parameter is codepage file */ + strcpy(cp_file_name, cp_string.c_str()); + } else { + /* no codepage file specified, use automatic selection */ + strcpy(cp_file_name, "auto"); + } + keyb_error = DOS_LoadKeyboardLayout(layout_id, cp, cp_file_name); + } + else { + if(!strcasecmp(layout_id, "us")) { + keyb_error = DOS_LoadKeyboardLayout("us", 437, "auto"); /* set 437 as default codepage for US layout */ + dos.loaded_codepage = 437; + } + else { + if(layout_name == NULL) { + keyb_error = DOS_LoadKeyboardLayout("us", 437, "auto"); /* Load a default layout if not loaded at all */ + } + keyb_error = DOS_SwitchKeyboardLayout(layout_id, cp); + } + } + switch (keyb_error) { + case KEYB_NOERROR: + { + SwitchLanguage(cpbak, cp ? cp : tocp, true); + WriteOut(MSG_Get("PROGRAM_KEYB_NOERROR"),layout_id, dos.loaded_codepage); + runRescan("-A -Q"); + #if C_OPENGL && DOSBOXMENU_TYPE == DOSBOXMENU_SDLDRAW + if (OpenGL_using() && control->opt_lang.size() && lastcp && lastcp != dos.loaded_codepage) + UpdateSDLDrawTexture(); + #endif + break; + } + case KEYB_FILENOTFOUND: + if (temp_line!="/?"&&temp_line!="-?") WriteOut(MSG_Get("PROGRAM_KEYB_FILENOTFOUND"),layout_id); + WriteOut(MSG_Get("PROGRAM_KEYB_SHOWHELP")); + break; + case KEYB_INVALIDFILE: + WriteOut(MSG_Get("PROGRAM_KEYB_INVALIDFILE"),layout_id); + break; + case KEYB_LAYOUTNOTFOUND: + WriteOut(MSG_Get("PROGRAM_KEYB_LAYOUTNOTFOUND"),layout_id, cp ? cp : tocp); + break; + case KEYB_INVALIDCPFILE: + WriteOut(MSG_Get("PROGRAM_KEYB_INVCPFILE"),layout_id); + WriteOut(MSG_Get("PROGRAM_KEYB_SHOWHELP")); + break; + default: + LOG(LOG_DOSMISC,LOG_ERROR)("KEYB:Invalid returncode %x",(int)keyb_error); + break; + } + } + } else { + /* no parameter in the command line, just output codepage info and possibly loaded layout ID */ + const char* layout_name = DOS_GetLoadedLayout(); + if (layout_name==NULL) { + WriteOut(MSG_Get("PROGRAM_KEYB_INFO"),dos.loaded_codepage); + } else { + WriteOut(MSG_Get("PROGRAM_KEYB_INFO_LAYOUT"),dos.loaded_codepage,layout_name); + } + } + } + + static void KEYB_ProgramStart(Program * * make) { + *make=new KEYB; + } + + // MODE + + class MODE : public Program { + public: + void Run(void) override; + private: + void PrintStatus() { + WriteOut("Status for device CON:\n----------------------\nColumns=%d\nLines=%d\n", COLS, LINES); + #if defined(USE_TTF) + if(!ttf.inUse) + #endif + WriteOut("\nCode page operation not supported on this device\n"); + } + int LINES = 25, COLS = 80; + }; + + bool setlines(const char *mname); + void MODE::Run(void) { + uint16_t rate=0,delay=0,cols=0,lines=0,mode; + LINES=(IS_EGAVGA_ARCH?real_readb(BIOSMEM_SEG,BIOSMEM_NB_ROWS):24)+1; + COLS=real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + if (!cmd->FindCommand(1,temp_line)) { + PrintStatus(); + return; + } + if (temp_line=="-?" || temp_line=="/?") { + WriteOut(MSG_Get("PROGRAM_MODE_USAGE")); + return; + } + else if (strcasecmp(temp_line.c_str(),"con")==0 || strcasecmp(temp_line.c_str(),"con:")==0) { + if (IS_PC98_ARCH) return; + if (cmd->GetCount()<2) { + PrintStatus(); + return; + } + if (cmd->FindStringBegin("rate=", temp_line,false)) rate=atoi(temp_line.c_str()); + if (cmd->FindStringBegin("delay=", temp_line,false)) delay=atoi(temp_line.c_str()); + if (cmd->FindStringBegin("cols=", temp_line,false)) cols=atoi(temp_line.c_str()); else cols=COLS; + if (cmd->FindStringBegin("lines=",temp_line,false)) lines=atoi(temp_line.c_str()); else lines=LINES; + bool optr=cmd->FindStringBegin("rate=", temp_line,true), optd=cmd->FindStringBegin("delay=",temp_line,true), optc=cmd->FindStringBegin("cols=", temp_line,true), optl=cmd->FindStringBegin("lines=",temp_line,true); + if ((optr&&!optd)||(optd&&!optr)) { + WriteOut("Rate and delay must be specified together\n"); + return; + } + if (cmd->GetCount()>1) goto modeparam; + if (optr&&optd) { + if (rate<1 || rate>32 || delay<1 || delay>4) goto modeparam; + IO_Write(0x60,0xf3); IO_Write(0x60,(uint8_t)(((delay-1)<<5)|(32-rate))); + } + if ((optc||optl)&&(cols!=COLS||lines!=LINES)) { + std::string cmd="line_"+std::to_string((int)cols)+"x"+std::to_string((int)lines); + if (!setlines(cmd.c_str())) goto modeparam; + } + return; + } + else if (cmd->GetCount()>1) goto modeparam; + else if (strcasecmp(temp_line.c_str(),"mono")==0) mode=7; + else if (machine==MCH_HERC || machine==MCH_MDA) goto modeparam; + else if (strcasecmp(temp_line.c_str(),"co80")==0) mode=3; + else if (strcasecmp(temp_line.c_str(),"bw80")==0) mode=2; + else if (strcasecmp(temp_line.c_str(),"co40")==0) mode=1; + else if (strcasecmp(temp_line.c_str(),"bw40")==0) mode=0; + else goto modeparam; + mem_writeb(BIOS_CONFIGURATION,(mem_readb(BIOS_CONFIGURATION)&0xcf)|((mode==7)?0x30:0x20)); + reg_ax=mode; + CALLBACK_RunRealInt(0x10); + return; + modeparam: + WriteOut(MSG_Get("PROGRAM_MODE_INVALID_PARAMETERS")); + return; + } + + static void MODE_ProgramStart(Program * * make) { + *make=new MODE; + } + /* + // MORE + class MORE : public Program { + public: + void Run(void); + }; + + void MORE::Run(void) { + if (cmd->GetCount()) { + WriteOut(MSG_Get("PROGRAM_MORE_USAGE")); + return; + } + uint16_t ncols=mem_readw(BIOS_SCREEN_COLUMNS); + uint16_t nrows=(uint16_t)mem_readb(BIOS_ROWS_ON_SCREEN_MINUS_1); + uint16_t col=1,row=1; + uint8_t c;uint16_t n=1; + WriteOut("\n"); + while (n) { + DOS_ReadFile(STDIN,&c,&n); + if (n==0 || c==0x1a) break; // stop at EOF + switch (c) { + case 0x07: break; + case 0x08: if (col>1) col--; break; + case 0x09: col=((col+7)&~7)+1; break; + case 0x0a: row++; break; + case 0x0d: col=1; break; + default: col++; break; + } + if (col>ncols) {col=1;row++;} + DOS_WriteFile(STDOUT,&c,&n); + if (row>=nrows) { + WriteOut(MSG_Get("PROGRAM_MORE_MORE")); + DOS_ReadFile(STDERR,&c,&n); + if (c==0) DOS_ReadFile(STDERR,&c,&n); // read extended key + WriteOut("\n\n"); + col=row=1; + } + } + } + + static void MORE_ProgramStart(Program * * make) { + *make=new MORE; + } */ -bool AUTOTYPE::ReadDoubleArg(const std::string &name, - const char *flag, - const double &def_value, - const double &min_value, - const double &max_value, - double &value) -{ - bool result = false; - std::string str_value; - - // Is the user trying to set this flag? - if (cmd->FindString(flag, str_value, true)) { - // Can the user's value be parsed? - const double user_value = to_finite(str_value); - if (isfinite(user_value)) { - result = true; - - // Clamp the user's value if needed - value = clamp(user_value, min_value, max_value); - - // Inform them if we had to clamp their value - if (fabs(user_value - value) > - std::numeric_limits::epsilon()) - WriteOut("AUTOTYPE: bounding %s value of %.2f " - "to %.2f\n", - name.c_str(), user_value, value); - - } else { // Otherwise we couldn't parse their value - WriteOut("AUTOTYPE: %s value '%s' is not a valid " - "floating point number\n", - name.c_str(), str_value.c_str()); - } - } else { // Otherwise they haven't passed this flag - value = def_value; - result = true; - } - return result; -} - -void AUTOTYPE::Run() -{ - // Hack To allow long commandlines - ChangeToLongCmd(); - - // Usage - if (!cmd->GetCount()||(cmd->GetCount()==1 && (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)))) { - PrintUsage(); - return; - } - - // Print available keys - if (cmd->FindExist("-list", false) || cmd->FindExist("/list", false)) { - PrintKeys(); - return; - } - - // Get the wait delay in milliseconds - double wait_s; - constexpr double def_wait_s = 2.0; - constexpr double min_wait_s = 0.0; - constexpr double max_wait_s = 30.0; - if (!ReadDoubleArg("WAIT", "-w", def_wait_s, min_wait_s, max_wait_s, wait_s)) - return; - const auto wait_ms = static_cast(wait_s * 1000); - - // Get the inter-key pacing in milliseconds - double pace_s; - constexpr double def_pace_s = 0.5; - constexpr double min_pace_s = 0.0; - constexpr double max_pace_s = 10.0; - if (!ReadDoubleArg("PACE", "-p", def_pace_s, min_pace_s, max_pace_s, pace_s)) - return; - const auto pace_ms = static_cast(pace_s * 1000); - - // Get the button sequence - std::vector sequence; - cmd->FillVector(sequence); - if (sequence.empty()) { - WriteOut_NoParsing("AUTOTYPE: button sequence is empty\n"); - return; - } - MAPPER_AutoType(sequence, wait_ms, pace_ms, false); -} - -void AUTOTYPE_ProgramStart(Program **make) -{ - *make = new AUTOTYPE; -} - -class ADDKEY : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Generates artificial keypresses.\n\nADDKEY [pmsec] [key]\n\n" - "For example, the command below types \"dir\" followed by ENTER after 1 second:\n\nADDKEY p1000 d i r enter\n\n" - "You could also try AUTOTYPE command instead of this command to perform\nscripted keyboard entry into a running DOS program.\n"; - WriteOut(msg); - } -}; - -void ADDKEY::Run() -{ - // Hack To allow long commandlines - ChangeToLongCmd(); - - // Usage - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - char *args=(char *)cmd->GetRawCmdline().c_str(); - args=trim(args); - DOS_Shell temp; - temp.CMD_ADDKEY(args); -} - -static void ADDKEY_ProgramStart(Program * * make) { - *make=new ADDKEY; -} - -class LS : public Program { -public: - void Run(void) override; -}; - -void LS::Run() -{ - std::string tmp = ""; - cmd->GetStringRemain(tmp); - char args[CMD_MAXLINE]; - strcpy(args, tmp.c_str()); - DOS_Shell temp; - temp.CMD_LS(args); -} - -static void LS_ProgramStart(Program * * make) { - *make=new LS; -} - -class CHOICE : public Program { -public: - void Run(void) override; -}; - -void CHOICE::Run() -{ - std::string tmp = ""; - cmd->GetStringRemain(tmp); - char args[CMD_MAXLINE]; - strcpy(args, tmp.c_str()); - DOS_Shell temp; - temp.CMD_CHOICE(args); - result_errorcode = dos.return_code; -} - -void CHOICE_ProgramStart(Program **make) -{ - *make = new CHOICE; -} - -class COUNTRY : public Program { -public: - void Run(void) override; -}; - -void COUNTRY::Run() -{ - char *args=(char *)cmd->GetRawCmdline().c_str(); - args=trim(args); - DOS_Shell temp; - temp.CMD_COUNTRY(args); -} - -static void COUNTRY_ProgramStart(Program * * make) { - *make=new COUNTRY; -} - -#ifdef C_ICONV -class UTF8 : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Converts UTF-8 text to view in the current code page.\n\n" - "UTF8 < [drive:][path]filename\ncommand-name | UTF8\n"; - WriteOut(msg); - } -}; - -void UTF8::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - if (usecon) { - WriteOut("No input text found.\n"); - return; - } - // int cp=dos.loaded_codepage; /* unused */ - char target[11] = "CP437"; - if (dos.loaded_codepage==808) strcpy(target, "CP866"); - else if (dos.loaded_codepage==859) strcpy(target, "CP858"); - else if (dos.loaded_codepage==867) strcpy(target, "CP862"); - else if (dos.loaded_codepage==872) strcpy(target, "CP855"); - else if (dos.loaded_codepage==951 && !uao) strcpy(target, "BIG5HKSCS"); - else if (dos.loaded_codepage==951) strcpy(target, "CP950"); - else if (!(customcp && dos.loaded_codepage==customcp) && !(altcp && dos.loaded_codepage==altcp)) sprintf(target, "CP%d", dos.loaded_codepage); - _Iconv *x = _Iconv::create("UTF-8"); - _Iconv *fx = _Iconv::create(target); - if (x == NULL || fx == NULL) { - WriteOut("Invalid code page for text conversion.\n"); - return; - } - test_string dst; - std::string text=""; - char temp[4096]; - morelen=true; - bool first=true; - uint8_t c;uint16_t m=1; - while (true) { - DOS_ReadFile (STDIN,&c,&m); - if (m) text+=std::string(1, c); - if (m && first && text.size() == 2 && (((uint8_t)text[0] == 0xFE && (uint8_t)text[1] == 0xFF) || ((uint8_t)text[0] == 0xFF && (uint8_t)text[1] == 0xFE))) { - WriteOut("The input text is UTF-16.\n"); - break; - } - if (m && first && text.size() == 3 && (uint8_t)text[0] == 0xEF && (uint8_t)text[1] == 0xBB && (uint8_t)text[2] == 0xBF) { - first=false; - text=""; - } else if (!m || c==0x1A || c==0xA || (text.size()>1 && (uint8_t)text[text.size()-2] == 0xD)) { - if (c!=0xA && text.size()>1 && (uint8_t)text[text.size()-2] == 0xD) text[text.size()-1] = 0xA; - if (CodePageHostToGuestUTF8(temp,text.c_str())) { - WriteOut_NoParsing(temp, true); - } else { - x->set_src(text.c_str()); - if ((customcp && dos.loaded_codepage==customcp) || (altcp && dos.loaded_codepage==altcp) || x->string_convert_dest(dst) < 0 || (text.size() && !fx->string_convert(dst).size())) { - WriteOut("An error occurred during text conversion.\n"); - morelen=false; - return; - } else - WriteOut_NoParsing(fx->string_convert(dst).c_str(), true); - } - first=false; - text=""; - if (!m||c==0x1A) break; - else if (c!=0xA) text+=std::string(1, c); - } - } - x->finish(); - morelen=false; -} - -static void UTF8_ProgramStart(Program * * make) { - *make=new UTF8; -} - -class UTF16 : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Converts UTF-16 text to view in the current code page.\n\n" - "UTF16 [/BE|/LE] < [drive:][path]filename\ncommand-name | UTF16 [/BE|/LE]\n\n" - " /BE Use UTF-16 Big Endian\n /LE Use UTF-16 Little Endian\n"; - WriteOut(msg); - } -}; - -void UTF16::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - if (usecon) { - WriteOut("No input text found.\n"); - return; - } - char target[11] = "CP437"; - if (dos.loaded_codepage==808) strcpy(target, "CP866"); - else if (dos.loaded_codepage==859) strcpy(target, "CP858"); - else if (dos.loaded_codepage==867) strcpy(target, "CP862"); - else if (dos.loaded_codepage==872) strcpy(target, "CP855"); - else if (dos.loaded_codepage==951 && !uao) strcpy(target, "BIG5HKSCS"); - else if (dos.loaded_codepage==951) strcpy(target, "CP950"); - else if (!(customcp && dos.loaded_codepage==customcp) && !(altcp && dos.loaded_codepage==altcp)) sprintf(target, "CP%d", dos.loaded_codepage); - uint8_t buf[3];uint16_t m=2; - DOS_ReadFile (STDIN,buf,&m); - if (m<2) { - if (m==1) WriteOut("An error occurred during text conversion.\n"); - return; - } - bool le=true; - if (cmd->FindExist("-BE", false) || cmd->FindExist("/BE", false)) - le=false; - else if (cmd->FindExist("-LE", false) || cmd->FindExist("/LE", false)) - le=true; - else if (buf[0] == 0xFE && buf[1]== 0xFF) - le=false; - else if (buf[0] == 0xFF && buf[1]== 0xFE) - le=true; -#if defined(MACOSX) - else - le=false; -#endif - _Iconv *x = _Iconv::create(target); - if (x == NULL) { - WriteOut("Invalid code page for text conversion.\n"); - return; - } - test_char dst; - test_char_t *wch; - test_char_t ch = 0; - std::wstring text=L""; - char temp[4096]; - unsigned int c=0; - morelen=true; - bool first=true; - while (true) { - if (!first || (buf[0] == 0xFE && buf[1]== 0xFF) || (buf[0] == 0xFF && buf[1]== 0xFE)) DOS_ReadFile (STDIN,buf,&m); - first=false; - if (m==1) { - WriteOut("An error occurred during text conversion.\n"); - break; - } else if (m==2) { - ch=buf[le?1:0]*0x100+buf[le?0:1]; - text+=ch; - c++; - } - if (!m || ch==0x1A || ch==0xA || (c>1 && text[c-2] == 0xD)) { - if (ch!=0xA && c>1 && text[c-2] == 0xD) {text[c-1] = 0xA;} - wch=new test_char_t[c+1]; - for (unsigned int i=0; iset_src(wch); - if ((customcp && dos.loaded_codepage==customcp) || (altcp && dos.loaded_codepage==altcp) || x->string_convert_dest(dst) < 0 || (c && !dst.size())) { - WriteOut("An error occurred during text conversion.\n"); - delete[] wch; - morelen=false; - return; - } else - WriteOut_NoParsing(dst.c_str(), true); - } - delete[] wch; - text=L""; - c=0; - if (!m||ch==0x1A) break; - else if (ch!=0xA) {text+=ch;c++;} - } - } - x->finish(); - morelen=false; -} - -static void UTF16_ProgramStart(Program * * make) { - *make=new UTF16; -} -#endif - -class VTEXT : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Changes V-text mode for the DOS/V emulation.\n\nVTEXT [mode]\n\n[mode] can be 0, 1, 2, for no V-text, V-text 1, and V-text 2 respectively.\n\nType VTEXT without a parameter to show the current V-text mode status.\n"; - WriteOut(msg); - } -}; - -void VTEXT::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - std::string tmp = ""; - cmd->GetStringRemain(tmp); - char args[CMD_MAXLINE]; - strcpy(args, tmp.c_str()); - DOS_Shell temp; - temp.CMD_VTEXT(args); -} - -static void VTEXT_ProgramStart(Program * * make) { - *make=new VTEXT; -} - -class DCGA : public Program { -public: - void Run(void) override; -}; - -void DCGA::Run() -{ - uint16_t oldax=reg_ax; - reg_ax = 0x74; - CALLBACK_RunRealInt(0x10); - reg_ax = oldax; -} - -static void DCGA_ProgramStart(Program * * make) { - *make=new DCGA; -} - -class TEXT80X25 : public Program { -public: - void Run(void) override; -}; - -void TEXT80X25::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Changes to 80x25 text mode.\n"); - return; - } - clear_screen(); - setlines("line_80x25"); - show_prompt(); -} - -static void TEXT80X25_ProgramStart(Program * * make) { - *make=new TEXT80X25; -} - -class TEXT80X43 : public Program { -public: - void Run(void) override; -}; - -void TEXT80X43::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Changes to 80x43 text mode.\n"); - return; - } - clear_screen(); - setlines("line_80x43"); - show_prompt(); -} - -static void TEXT80X43_ProgramStart(Program * * make) { - *make=new TEXT80X43; -} - -class TEXT80X50 : public Program { -public: - void Run(void) override; -}; - -void TEXT80X50::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Changes to 80x50 text mode.\n"); - return; - } - clear_screen(); - setlines("line_80x50"); - show_prompt(); -} - -static void TEXT80X50_ProgramStart(Program * * make) { - *make=new TEXT80X50; -} - -class TEXT80X60 : public Program { -public: - void Run(void) override; -}; - -void TEXT80X60::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Changes to 80x60 text mode.\n"); - return; - } - clear_screen(); - setlines("line_80x60"); - show_prompt(); -} - -static void TEXT80X60_ProgramStart(Program * * make) { - *make=new TEXT80X60; -} - -class TEXT132X25 : public Program { -public: - void Run(void) override; -}; - -void TEXT132X25::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Changes to 132x25 text mode.\n"); - return; - } - clear_screen(); - setlines("line_132x25"); - show_prompt(); -} - -static void TEXT132X25_ProgramStart(Program * * make) { - *make=new TEXT132X25; -} - -class TEXT132X43 : public Program { -public: - void Run(void) override; -}; - -void TEXT132X43::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Changes to 132x43 text mode.\n"); - return; - } - clear_screen(); - setlines("line_132x43"); - show_prompt(); -} - -static void TEXT132X43_ProgramStart(Program * * make) { - *make=new TEXT132X43; -} - -class TEXT132X50 : public Program { -public: - void Run(void) override; -}; - -void TEXT132X50::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Changes to 132x50 text mode.\n"); - return; - } - clear_screen(); - setlines("line_132x50"); - show_prompt(); -} - -static void TEXT132X50_ProgramStart(Program * * make) { - *make=new TEXT132X50; -} - -class TEXT132X60 : public Program { -public: - void Run(void) override; -}; - -void TEXT132X60::Run() -{ - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - WriteOut("Changes to 132x60 text mode.\n"); - return; - } - clear_screen(); - setlines("line_132x60"); - show_prompt(); -} - -static void TEXT132X60_ProgramStart(Program * * make) { - *make=new TEXT132X60; -} - -class HELP : public Program { -public: - void Run(void) override; -}; - -void HELP::Run() -{ - std::string tmp = ""; - cmd->GetStringRemain(tmp); - char args[CMD_MAXLINE]; - strcpy(args, tmp.c_str()); - DOS_Shell temp; - temp.CMD_HELP(args); -} - -static void HELP_ProgramStart(Program * * make) { - *make=new HELP; -} - -class DELTREE : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Deletes a directory and all the subdirectories and files in it.\n\n" - "To delete one or more files and directories:\n" - "DELTREE [/Y] [drive:]path [[drive:]path[...]]\n\n" - " /Y Suppresses prompting to confirm you want to delete\n" - " the subdirectory.\n" - " [drive:]path Specifies the name of the directory you want to delete.\n\n" - "Note: Use DELTREE cautiously. Every file and subdirectory within the\n" - "specified directory will be deleted.\n"; - WriteOut(msg); - } -}; - -void DELTREE::Run() -{ - // Hack To allow long commandlines - ChangeToLongCmd(); - - // Usage - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - char *args=(char *)cmd->GetRawCmdline().c_str(); - args=trim(args); - DOS_Shell temp; - temp.CMD_DELTREE(args); -} - -static void DELTREE_ProgramStart(Program * * make) { - *make=new DELTREE; -} - -class TREE : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Graphically displays the directory structure of a drive or path.\n\n" - "TREE [drive:][path] [/F] [/A]\n\n" - " /F Displays the names of the files in each directory.\n" - " /A Uses ASCII instead of extended characters.\n"; - WriteOut(msg); - } -}; - -void TREE::Run() -{ - // Hack To allow long commandlines - ChangeToLongCmd(); - - // Usage - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - char *args=(char *)cmd->GetRawCmdline().c_str(); - args=trim(args); - DOS_Shell temp; - temp.CMD_TREE(args); -} - -static void TREE_ProgramStart(Program * * make) { - *make=new TREE; -} - -class TITLE : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Sets the window title for the DOSBox-X window.\n\n" - "TITLE [string]\n\n" - " string Specifies the title for the DOSBox-X window.\n"; - WriteOut(msg); - } -}; - -bool CodePageGuestToHostUTF8(char *d/*CROSS_LEN*/,const char *s/*CROSS_LEN*/); - -void TITLE::Run() -{ - // Hack To allow long commandlines - ChangeToLongCmd(); - - // Usage - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - char *args=trim((char *)cmd->GetRawCmdline().c_str()); - char title[4096]; - if(CodePageGuestToHostUTF8(title, args)) { - dosbox_title=title; - } else { - dosbox_title=args; - } - SetVal("dosbox", "title", dosbox_title); - GFX_SetTitle(-1,-1,-1,false); -} - -static void TITLE_ProgramStart(Program * * make) { - *make=new TITLE; -} - -class VHDMAKE : public Program { -public: - void Run(void) override; -private: - const char* vhdTypes[5] = { "", "", "Fixed", "Dynamic", "Differencing" }; - uint64_t ssizetou64(const char* s_size); - void PrintUsage() { - const char* msg = MSG_Get("PROGRAM_VHDMAKE_HELP"); - WriteOut(msg); - } -}; - -// Converts a string disk size with unit into a 64-bit unsigned integer -uint64_t VHDMAKE::ssizetou64(const char* s_size) { - const char* sizes = "BKMGT"; - char* sd_size = _strdup(s_size); - char* last = sd_size + strlen(s_size) - 1; - char* c; - uint64_t size; - - if((c = strchr((char*)sizes, toupper(*last)))) { - *last = 0; - size = atoll(sd_size); - size <<= ((c - sizes) * 10); - } - else { - size = atoll(sd_size); - } - free(sd_size); - return size; -} - -void VHDMAKE::Run() -{ - bool bOverwrite = false; - // bool bExists = false; /* unused */ - uint32_t ret; - char basename[256], filename[256]; - - // Hack To allow long commandlines - ChangeToLongCmd(); - - // Usage - if(cmd->FindExist("-?", false) || cmd->FindExist("/?", false) || cmd->GetCount() < 2) { - PrintUsage(); - return; - } - - if(cmd->FindExist("-f", true) || cmd->FindExist("-force", true)) - bOverwrite = true; - - if(cmd->FindExist("-i", true) || cmd->FindExist("-info", true)) { - if(cmd->GetCount() > 1) { - PrintUsage(); - return; - } - cmd->FindCommand(1, temp_line); - safe_strcpy(filename, temp_line.c_str()); // image to query - - imageDiskVHD::VHDInfo* info = NULL; - if(imageDiskVHD::GetInfo(filename, &info)) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_NOINFO"), filename); - return; - } - WriteOut(MSG_Get("PROGRAM_VHDMAKE_INFO"), filename, vhdTypes[(int)info->vhdType], info->vhdSizeMB); - if(info->vhdType != imageDiskVHD::VHD_TYPE_FIXED) - WriteOut(MSG_Get("PROGRAM_VHDMAKE_BLOCKSTATS"), info->allocatedBlocks, info->totalBlocks); - else - WriteOut(".\n"); - if(info->parentInfo != NULL) { - uint32_t index = 0; - imageDiskVHD::VHDInfo* p = info->parentInfo; - while(p != NULL) { - index++; - for(uint32_t i = 0; i < index; i++) WriteOut(" "); - WriteOut("child of \"%s\" (%s)", p->diskname.c_str(), vhdTypes[(int)p->vhdType]); - if (p->vhdType != imageDiskVHD::VHD_TYPE_FIXED) - WriteOut(MSG_Get("PROGRAM_VHDMAKE_BLOCKSTATS"), p->allocatedBlocks, p->totalBlocks); - else - WriteOut(".\n"); - p = p->parentInfo; - } - } - delete info; - return; - } - - if(cmd->FindExist("-m", true) || cmd->FindExist("-merge", true)) { - if(cmd->GetCount() > 1) { - PrintUsage(); - return; - } - cmd->FindCommand(1, temp_line); - safe_strcpy(basename, temp_line.c_str()); - imageDiskVHD* vhd; - if(imageDiskVHD::Open(basename, true, (imageDisk**)&vhd) != imageDiskVHD::OPEN_SUCCESS) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), basename); - return; - } - if(vhd->vhdType != imageDiskVHD::VHD_TYPE_DIFFERENCING) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_CANTMERGE"), basename); - delete vhd; - return; - } - imageDiskVHD::VHDInfo* info = new imageDiskVHD::VHDInfo; - if(vhd->GetInfo(info)) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_NOINFO"), basename); - return; - } - uint32_t totalSectorsMerged, totalBlocksUpdated; - std::string parentName = info->parentInfo->diskname; - if(vhd->MergeSnapshot(&totalSectorsMerged, &totalBlocksUpdated)) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGEREPORT"), totalSectorsMerged, totalBlocksUpdated, basename, parentName.c_str()); - delete vhd; - if(remove(basename)) - WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGENODELETE"), basename); - else - WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGEOKDELETE")); - } - else { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGEFAILED")); - if(totalSectorsMerged) - WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGEWARNCORRUPTION"), parentName.c_str()); - else - WriteOut("\n"); - } - delete info; - return; - } - - if(cmd->FindExist("-c", true) || cmd->FindExist("-convert", true)) { - if(cmd->GetCount() != 2) { - PrintUsage(); - return; - } - cmd->FindCommand(1, temp_line); - safe_strcpy(filename, temp_line.c_str()); // image to convert - FILE* f; - if(!(f = fopen(filename, "r"))) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), filename); - return; - } - fclose(f); - cmd->FindCommand(2, temp_line); - safe_strcpy(basename, temp_line.c_str()); // resulting VHD (after renaming) - if(_access(basename, 0) == 0) { - if(!bOverwrite) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_FNEEDED")); - return; - } - if(remove(basename)) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_REMOVEERR"), basename); - } - } - ret = imageDiskVHD::ConvertFixed(filename); - if(ret == imageDiskVHD::OPEN_SUCCESS) { - if (rename(filename, basename)) - WriteOut(MSG_Get("PROGRAM_VHDMAKE_RENAME")); - } - } - else if(cmd->FindExist("-l", true) || cmd->FindExist("-link", true)) { - if(cmd->GetCount() > 2) { - PrintUsage(); - return; - } - cmd->FindCommand(1, temp_line); - safe_strcpy(basename, temp_line.c_str()); - cmd->FindCommand(2, temp_line); - safe_strcpy(filename, temp_line.c_str()); - if(basename[1] == ':' || basename[0] == '/') - WriteOut(MSG_Get("PROGRAM_VHDMAKE_ABSPATH")); - if(! bOverwrite && _access(filename, 0) == 0) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_FNEEDED")); - return; - } - ret = imageDiskVHD::CreateDifferencing(filename, basename); - } - else { - if(cmd->GetCount() > 2) { - PrintUsage(); - return; - } - char size[16]; - cmd->FindCommand(1, temp_line); - safe_strcpy(filename, temp_line.c_str()); - cmd->FindCommand(2, temp_line); - safe_strcpy(size, temp_line.c_str()); - uint64_t vhd_size = ssizetou64(size); - if(!vhd_size || vhd_size < 3145728 || vhd_size > 2190433320960) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_BADSIZE")); - return; - } - if(!bOverwrite && _access(filename, 0) == 0) { - WriteOut(MSG_Get("PROGRAM_VHDMAKE_FNEEDED")); - return; - } - ret = imageDiskVHD::CreateDynamic(filename, vhd_size); - } - - switch(ret) { - case imageDiskVHD::UNSUPPORTED_SIZE: - WriteOut(MSG_Get("PROGRAM_VHDMAKE_BADSIZE")); - break; - case imageDiskVHD::ERROR_OPENING: - WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), filename); - break; - case imageDiskVHD::ERROR_OPENING_PARENT: - WriteOut(MSG_Get("PROGRAM_VHDMAKE_BADPARENT"), filename); - break; - case imageDiskVHD::ERROR_WRITING: - WriteOut(MSG_Get("PROGRAM_VHDMAKE_WRITERR"), filename); - break; - case imageDiskVHD::OPEN_SUCCESS: - WriteOut(MSG_Get("PROGRAM_VHDMAKE_SUCCESS")); - break; - } -} - - -static void VHDMAKE_ProgramStart(Program * * make) { - *make=new VHDMAKE; -} - -class COLOR : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Sets the default console foreground and background colors.\n\n" - "COLOR [attr]\n\n" - " attr Specifies color attribute of console output\n\n" - "Color attributes are specified by TWO hex digits -- the first\n" - "corresponds to the background; the second to the foreground.\n" - "Each digit can be any of the following values:\n\n" - " 0 = Black 8 = Gray\n" - " 1 = Blue 9 = Light Blue\n" - " 2 = Green A = Light Green\n" - " 3 = Aqua B = Light Aqua\n" - " 4 = Red C = Light Red\n" - " 5 = Purple D = Light Purple\n" - " 6 = Yellow E = Light Yellow\n" - " 7 = White F = Bright White\n\n" - "If no argument is given, this command restores the original color.\n\n" - "Example: \"COLOR fc\" produces light red on bright white\n"; - WriteOut(msg); - } -}; - -void COLOR::Run() -{ - // Hack To allow long commandlines - ChangeToLongCmd(); - - // Usage - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - bool back=false; - char fg, bg; - int fgc=0, bgc=0; - char *args=(char *)cmd->GetRawCmdline().c_str(); - args=trim(args); - if (strlen(args)==2) { - bg=args[0]; - fg=args[1]; - if (fg=='0'||fg=='8') - fgc=30; - else if (fg=='1'||fg=='9') - fgc=34; - else if (fg=='2'||tolower(fg)=='a') - fgc=32; - else if (fg=='3'||tolower(fg)=='b') - fgc=36; - else if (fg=='4'||tolower(fg)=='c') - fgc=31; - else if (fg=='5'||tolower(fg)=='d') - fgc=35; - else if (fg=='6'||tolower(fg)=='e') - fgc=32; - else if (fg=='7'||tolower(fg)=='f') - fgc=37; - else - back=true; - if (bg=='0'||bg=='8') - bgc=40; - else if (bg=='1'||bg=='9') - bgc=44; - else if (bg=='2'||tolower(bg)=='a') - bgc=42; - else if (bg=='3'||tolower(bg)=='b') - bgc=46; - else if (bg=='4'||tolower(bg)=='c') - bgc=41; - else if (bg=='5'||tolower(bg)=='d') - bgc=45; - else if (bg=='6'||tolower(bg)=='e') - bgc=42; - else if (bg=='7'||tolower(bg)=='f') - bgc=47; - else - back=true; - } else - back=true; - if (back) - WriteOut("\033[0m"); - else { - bool fgl=fg>='0'&&fg<='7', bgl=bg>='0'&&bg<='7'; - WriteOut(("\033["+std::string(fgl||bgl?"0;":"")+std::string(fgl?"":"1;")+std::string(bgl?"":"5;")+std::to_string(fgc)+";"+std::to_string(bgc)+"m").c_str()); - } -} - -static void COLOR_ProgramStart(Program * * make) { - *make=new COLOR; -} - -alt_rgb altBGR[16], altBGR0[16], *rgbcolors = (alt_rgb*)render.pal.rgb; -bool init_altBGR = false,init_altBGR0 = false; - -bool setVGAColor(const char *colorArray, int j) { - if (!IS_VGA_ARCH||!CurMode) return false; - const char * nextRGB = colorArray; - int32_t rgbVal[4] = {-1,-1,-1,-1}; - if (sscanf(nextRGB, " ( %d , %d , %d)", &rgbVal[0], &rgbVal[1], &rgbVal[2]) == 3) { - for (int i = 0; i< 3; i++) { - if (rgbVal[i] < 0 || rgbVal[i] > 255) - return false; - } - } else if (sscanf(nextRGB, " #%6x", (unsigned int*)(&rgbVal[3])) == 1) { - if (rgbVal[3] < 0 || rgbVal[3] > 0xFFFFFF) - return false; - for (int i = 2; i >= 0; i--) { - rgbVal[i] = rgbVal[3]&255; - rgbVal[3] >>= 8; - } - } else - return false; - IO_ReadB(mem_readw(BIOS_VIDEO_PORT)+6); - IO_WriteB(VGAREG_ACTL_ADDRESS, j+32); - uint8_t imap=IO_ReadB(VGAREG_ACTL_READ_DATA); - IO_WriteB(VGAREG_DAC_WRITE_ADDRESS, imap); - IO_WriteB(VGAREG_DAC_DATA, rgbVal[0] >> 2); - IO_WriteB(VGAREG_DAC_DATA, rgbVal[1] >> 2); - IO_WriteB(VGAREG_DAC_DATA, rgbVal[2] >> 2); - rgbcolors[j].red = rgbVal[0] & 0xFF; - rgbcolors[j].green = rgbVal[1] & 0xFF; - rgbcolors[j].blue = rgbVal[2] & 0xFF; - altBGR0[j].red = rgbVal[0]; - altBGR0[j].green = rgbVal[1]; - altBGR0[j].blue = rgbVal[2]; - return true; -} - -#if defined(USE_TTF) -extern alt_rgb altBGR1[16]; -extern bool colorChanged; -bool setColors(const char *colorArray, int n); -void resetFontSize(); -#endif - -bool get_pal = false; -class SETCOLOR : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Views or changes the text-mode color scheme settings.\n\nSETCOLOR [color# [value]]\n\nFor example:\n\n SETCOLOR 0 (50,50,50)\n\nChange Color #0 to the specified color value\n\n SETCOLOR 7 -\n\nReturn Color #7 to the default color value\n\n SETCOLOR 3 +\n\nReturn Color #3 to the preset color value\n\n SETCOLOR MONO\n\nDisplay current MONO mode status\n\nTo change the current background and foreground colors, use COLOR command.\n"; - WriteOut(msg); - } -}; - -void SETCOLOR::Run() -{ - // Hack To allow long commandlines - ChangeToLongCmd(); - - if (!get_pal){ - for (uint8_t i=0; i<16; i++){ - altBGR0[i].red = rgbcolors[i].red; - altBGR0[i].green = rgbcolors[i].green; - altBGR0[i].blue = rgbcolors[i].blue; -#ifdef USE_TTF - altBGR1[i].red = rgbcolors[i].red; - altBGR1[i].green = rgbcolors[i].green; - altBGR1[i].blue = rgbcolors[i].blue; -#endif - get_pal = true; - } - } - - // Usage - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - char *args=(char *)cmd->GetRawCmdline().c_str(); - if (*args) { - args=trim(args); - char *p = strchr(args, ' '); - if (p!=NULL) - *p=0; - int i=atoi(args); - if (!strcasecmp(args,"MONO")) { - if (p==NULL) - WriteOut("MONO mode status: %s (video mode %d)\n",CurMode->mode==7?"active":CurMode->mode==3?"inactive":"unavailable",CurMode->mode); - else if (!strcmp(trim(p+1),"+")) { - if (CurMode->mode!=7) INT10_SetVideoMode(7); - WriteOut(CurMode->mode==7?"MONO mode status => active (video mode 7)\n":"Failed to change MONO mode\n"); - } else if (!strcmp(trim(p+1),"-")) { - if (CurMode->mode!=3) INT10_SetVideoMode(3); - WriteOut(CurMode->mode==3?"MONO mode status => inactive (video mode 3)\n":"Failed to change MONO mode\n"); - } else - WriteOut("Must be + or - for MONO: %s\n",trim(p+1)); - } else if (!strcmp(args,"0")||!strcmp(args,"00")||!strcmp(args,"+0")||!strcmp(args,"-0")||(i>0&&i<16)) { - if (p==NULL) { -#if defined(USE_TTF) - bool colornul = staycolors || (IS_VGA_ARCH && (altBGR1[i].red > 4 || altBGR1[i].green > 4 || altBGR1[i].blue > 4) && rgbcolors[i].red < 5 && rgbcolors[i].green < 5 && rgbcolors[i].blue < 5); - altBGR[i].red = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].red:rgbcolors[i].red; - altBGR[i].green = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].green:rgbcolors[i].green; - altBGR[i].blue = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].blue:rgbcolors[i].blue; - WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,altBGR0[i].red,altBGR0[i].green,altBGR0[i].blue,altBGR0[i].red,altBGR0[i].green,altBGR0[i].blue); -#else - WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue); -#endif - } - } else { - WriteOut("Invalid color number - %s\n", trim(args)); - DOS_SetError(DOSERR_DATA_INVALID); - return; - } if (p!=NULL&&strcasecmp(args,"MONO")) { - char value[128]; - if (!strcmp(trim(p+1),"-")) { - strcpy(value,i==0?"#000000":i==1?"#0000aa":i==2?"#00aa00":i==3?"#00aaaa":i==4?"#aa0000":i==5?"#aa00aa":i==6?"#aa5500":i==7?"#aaaaaa":i==8?"#555555":i==9?"#5555ff":i==10?"#55ff55":i==11?"#55ffff":i==12?"#ff5555":i==13?"#ff55ff":i==14?"#ffff55":"#ffffff"); - } else if (!strcmp(trim(p+1),"+")) { - Section_prop * ttf_section=static_cast(control->GetSection("ttf")); - const char * colors = ttf_section->Get_string("colors"); - const char * nextRGB = *colors ? (colors + (*colors == '+'?1:0)) : "#000000 #0000aa #00aa00 #00aaaa #aa0000 #aa00aa #aa5500 #aaaaaa #555555 #5555ff #55ff55 #55ffff #ff5555 #ff55ff #ffff55 #ffffff"; - int rgbVal[3] = {-1,-1,-1}; - for (int colNo = 0; colNo <= i; colNo++) { - if (sscanf(nextRGB, " ( %d , %d , %d)", &rgbVal[0], &rgbVal[1], &rgbVal[2]) == 3) { - sprintf(value,"(%d,%d,%d)",rgbVal[0],rgbVal[1],rgbVal[2]); - while (*nextRGB != ')') - nextRGB++; - nextRGB++; - } else if (sscanf(nextRGB, " #%6x", (unsigned int*)(&rgbVal[0])) == 1) { - sprintf(value,"#%6x",rgbVal[0]); - nextRGB = strchr(nextRGB, '#') + 7; - } else { - WriteOut("Invalid color value - %s\n",nextRGB); - return; - } - } - } else { - strncpy(value,trim(p+1),127); - value[127]=0; - } -#if defined(USE_TTF) - if (!ttf.inUse) { -#endif - if (!IS_VGA_ARCH) - WriteOut("Changing color scheme is not supported for the current video mode.\n"); - else if (setVGAColor(value, i)) - //WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue); - WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,altBGR0[i].red,altBGR0[i].green,altBGR0[i].blue,altBGR0[i].red,altBGR0[i].green,altBGR0[i].blue); - else - WriteOut("Invalid color value - %s\n",value); -#if defined(USE_TTF) - } else if (setColors(value,i)) { - bool colornul = staycolors || (IS_VGA_ARCH && (altBGR1[i].red > 4 || altBGR1[i].green > 4 || altBGR1[i].blue > 4) && rgbcolors[i].red < 5 && rgbcolors[i].green < 5 && rgbcolors[i].blue < 5); - altBGR[i].red = (colornul||(colorChanged&&!IS_VGA_ARCH))?altBGR1[i].red:rgbcolors[i].red; - altBGR[i].green = (colornul||(colorChanged&&!IS_VGA_ARCH))?altBGR1[i].green:rgbcolors[i].green; - altBGR[i].blue = (colornul||(colorChanged&&!IS_VGA_ARCH))?altBGR1[i].blue:rgbcolors[i].blue; - WriteOut("Color %d => (%d,%d,%d) or #%02x%02x%02x\n",i,altBGR[i].red,altBGR[i].green,altBGR[i].blue,altBGR[i].red,altBGR[i].green,altBGR[i].blue); - resetFontSize(); - } else - WriteOut("Invalid color value - %s\n",value); -#endif - } - } else { - WriteOut("MONO mode status: %s (video mode %d)\n",CurMode->mode==7?"active":CurMode->mode==3?"inactive":"unavailable",CurMode->mode); - for (int i = 0; i < 16; i++) { -#if defined(USE_TTF) - bool colornul = staycolors || (IS_VGA_ARCH && (altBGR1[i].red > 4 || altBGR1[i].green > 4 || altBGR1[i].blue > 4) && rgbcolors[i].red < 5 && rgbcolors[i].green < 5 && rgbcolors[i].blue < 5); - altBGR[i].red = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].red:rgbcolors[i].red; - altBGR[i].green = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].green:rgbcolors[i].green; - altBGR[i].blue = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].blue:rgbcolors[i].blue; - WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,altBGR[i].red,altBGR[i].green,altBGR[i].blue,altBGR[i].red,altBGR[i].green,altBGR[i].blue); -#else - WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue); -#endif - } - } -} - -static void SETCOLOR_ProgramStart(Program * * make) { - *make=new SETCOLOR; -} - -#if C_DEBUG -extern Bitu int2fdbg_hook_callback; -class INT2FDBG : public Program { -public: - void Run(void) override; -private: - void PrintUsage() { - constexpr const char *msg = - "Hooks INT 2Fh for debugging purposes.\n\nINT2FDBG [option]\n /I Installs hook\n\nIt will hook INT 2Fh at the top of the call chain for debugging information.\n\nType INT2FDBG without a parameter to show the current hook status.\n"; - WriteOut(msg); - } -}; - -void INT2FDBG::Run() -{ - // Hack To allow long commandlines - ChangeToLongCmd(); - - if (!cmd->GetCount()) { - if (int2fdbg_hook_callback == 0) - WriteOut("INT 2Fh hook has not been set.\n"); - else - WriteOut("INT 2Fh hook has already been set.\n"); - return; - } - - // Usage - if (!cmd->GetCount() || cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - PrintUsage(); - return; - } - char *args=(char *)cmd->GetRawCmdline().c_str(); - args=trim(args); - DOS_Shell temp; - temp.CMD_INT2FDBG(args); -} - -static void INT2FDBG_ProgramStart(Program * * make) { - *make=new INT2FDBG; -} -#endif - -#if defined (WIN32) -extern bool ctrlbrk; -extern std::string startincon; -#endif -#if defined (WIN32) && !defined(HX_DOS) -#include -#include -SHELLEXECUTEINFO lpExecInfo; - -void EndStartProcess() { - if(lpExecInfo.hProcess!=NULL) { - DWORD exitCode; - GetExitCodeProcess(lpExecInfo.hProcess, &exitCode); - if (exitCode==STILL_ACTIVE) - TerminateProcess(lpExecInfo.hProcess, 0); - } - ctrlbrk=false; -} -#endif - -void zipSetCurrentTime(zip_fileinfo &zi); -int zipOutOpenFile(zipFile zf,const char *zfname,zip_fileinfo &zi,const bool compress); - -const char * TranslateHostPath(const char * arg, bool next = false); -class START : public Program { -public: - void Run() override { - if(control->SecureMode()) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); - return; - } - - // Hack To allow long commandlines - ChangeToLongCmd(); - - // Usage - if (!cmd->GetCount()||(cmd->GetCount()==1 && (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)))) { - PrintUsage(); - return; - } - char *args=(char *)cmd->GetRawCmdline().c_str(); - args=trim(args); - char *cmd = strlen(args)?args:NULL; - if (cmd!=NULL&&strlen(cmd)>1&&cmd[0]=='"'&&cmd[1]==' ') { - cmd++; - while (cmd[0]==' ') cmd++; - cmd--; - cmd[0]='"'; - } -#if defined(WIN32) && !defined(HX_DOS) - char *cmdstr = cmd==NULL?NULL:(char *)strstr(cmd, cmd[0]=='"'?"\" ":" "); - char buf[CROSS_LEN], dir[CROSS_LEN+15], str[CROSS_LEN*2]; - int k=0; - if (cmdstr!=NULL) { - if (*cmdstr=='\"') cmdstr++; - while (*cmdstr==' ') {k++;*cmdstr++=0;} - } - int state = cmd==NULL?0:!strcmp(cmd,"-")||!strcasecmp(cmd,"/min")||!strcasecmp(cmd,"-min")?1:!strcmp(cmd,"+")||!strcasecmp(cmd,"/max")||!strcasecmp(cmd,"-max")?2:!strcasecmp(cmd,"_")||!strcasecmp(cmd,"/hid")||!strcasecmp(cmd,"-hid")?3:0; - if (state > 0) { - k=0; - cmd = cmdstr; - if (cmd!=NULL&&strlen(cmd)>1&&cmd[0]=='"'&&cmd[1]==' ') { - cmd++; - while (cmd[0]==' ') cmd++; - cmd--; - cmd[0]='"'; - } - if ((cmdstr = cmd==NULL?NULL:(char *)strstr(cmd, cmd[0]=='"'?"\" ":" "))!=NULL) { - if (*cmdstr=='\"') cmdstr++; - while (*cmdstr==' ') {k++;*cmdstr++=0;} - } - } - if (cmd!=NULL) { - char *ret, *ret0, *ret1, *ret2, *ret3, *ret4; - ret0 = strchr(cmd, '/'); - ret1 = strchr(cmd, '|'); - ret2 = strchr(cmd, '<'); - ret3 = strchr(cmd, '>'); - ret4 = strchr(cmd, ' '); - ret = ret0>cmd?ret0:NULL; - if (ret1!=NULL && (ret == NULL || ret1cmd&&*(ret-1)==':')) { - strcpy(buf, cmdstr==NULL?"":cmdstr); - strcpy(str, ret); - if (k<1) k=1; - for (int i=0; i0&&cmdstr[strlen(cmdstr)-2]=='"') { - cmd++; - cmdstr[strlen(cmdstr)-2]='\0'; - } - } - } - if (cmd==NULL || !strlen(cmd) || !strcmp(cmd,"?") || !strcmp(cmd,"/") || !strcmp(cmd,"/?") || !strcmp(cmd,"-?")) { - PrintUsage(); - DOS_SetError(0); - return; - } - int sw = state==0?SW_SHOW:state==1?SW_MINIMIZE:state==2?SW_MAXIMIZE:SW_HIDE; - bool match=false; - std::istringstream in(startincon); - if (in) for (std::string command; in >> command; ) { - if (!strcasecmp(cmd,command.c_str())||!strcasecmp(cmd,("\""+command+"\"").c_str())) { - match=true; - break; - } - } - lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); - lpExecInfo.fMask=SEE_MASK_DOENVSUBST|SEE_MASK_NOCLOSEPROCESS; - lpExecInfo.hwnd = NULL; - lpExecInfo.lpVerb = "open"; - lpExecInfo.lpDirectory = NULL; - lpExecInfo.nShow = sw; - lpExecInfo.hInstApp = (HINSTANCE) SE_ERR_DDEFAIL; - if (match) { - strcpy(dir, strcasecmp(cmd,"for")?"/C \"":"/C \"("); - strcat(dir, cmd); - strcat(dir, " "); - if (cmdstr!=NULL) strcat(dir, TranslateHostPath(cmdstr)); - if (!strcasecmp(cmd,"for")) strcat(dir, ")"); - strcat(dir, " & echo( & echo The command execution is completed. & pause\""); - lpExecInfo.lpFile = "CMD.EXE"; - lpExecInfo.lpParameters = dir; - } else { - lpExecInfo.lpFile = cmd==NULL?NULL:TranslateHostPath(cmd); - lpExecInfo.lpParameters = cmdstr==NULL?NULL:TranslateHostPath(cmdstr, true); - } - bool setdir=false; - char winDirCur[512], winDirNew[512]; - if (GetCurrentDirectory(512, winDirCur)&&(!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"local ",6)||!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"CDRom ",6))) { - Overlay_Drive *ddp = dynamic_cast(Drives[DOS_GetDefaultDrive()]); - strcpy(winDirNew, ddp!=NULL?ddp->getOverlaydir():Drives[DOS_GetDefaultDrive()]->GetBaseDir()); - strcat(winDirNew, Drives[DOS_GetDefaultDrive()]->curdir); - if (SetCurrentDirectory(winDirNew)) setdir=true; - } - if (!startquiet) WriteOut("Starting %s...\n", cmd); - ShellExecuteEx(&lpExecInfo); - int ErrorCode = GetLastError(); - if (setdir) SetCurrentDirectory(winDirCur); - if (startwait && lpExecInfo.hProcess!=NULL) { - DWORD exitCode; - BOOL ret; - int count=0; - ctrlbrk=false; - inshell=true; - do { - ret=GetExitCodeProcess(lpExecInfo.hProcess, &exitCode); - CALLBACK_Idle(); - if (ctrlbrk) { - uint8_t c;uint16_t n=1; - DOS_ReadFile (STDIN,&c,&n); - if (c == 3) WriteOut("^C\r\n"); - EndStartProcess(); - exitCode=0; - break; - } - if (++count==20000&&ret&&exitCode==STILL_ACTIVE&&!startquiet) WriteOut("(Press Ctrl+C to exit immediately)\n"); - } while (ret!=0&&exitCode==STILL_ACTIVE); - ErrorCode = GetLastError(); - CloseHandle(lpExecInfo.hProcess); - inshell=false; - } - DOS_SetError(ErrorCode); -#else - if (cmd==NULL || !strlen(cmd) || !strcmp(cmd,"?") || !strcmp(cmd,"/") || !strcmp(cmd,"/?") || !strcmp(cmd,"-?") || !strcasecmp(cmd,"/open") || !strcasecmp(cmd,"-open")) { - PrintUsage(); - DOS_SetError(0); - return; - } - if (!startquiet) WriteOut("Starting %s...\n", cmd); - bool open=false; - if (!strncasecmp(cmd, "/open ", 5) || !strncasecmp(cmd, "-open ", 6)) { - open=true; - cmd+=5; - } - cmd=trim((char *)TranslateHostPath(cmd)); - int ret=0; -#if defined(LINUX) || defined(MACOSX) - ret=system(((open? -#if defined(LINUX) - "xdg-open " -#else - "open " -#endif - :"")+std::string(cmd)+(startwait||(strlen(cmd)>2&&!strcmp(cmd+strlen(cmd)-2," &"))?"":" &")).c_str()); -#else - WriteOut("Error: START cannot launch application to run on your current host system.\n"); - return; -#endif - if (ret==-1) { - WriteOut("Error: START could not launch application.\n"); - return; - } - DOS_SetError(ret); -#endif - } - -private: - void PrintUsage() { - constexpr const char *msg = - "Starts a separate window to run a specified program or command.\n\n" -#if defined(WIN32) - "START [+|-|_] command [arguments]\n\n" - " [+|-|_]: To maximize/minimize/hide the program.\n" - " The options /MAX, /MIN, /HID are also accepted.\n" - " command: The command, program or file to start.\n" - " arguments: Arguments to pass to the application.\n\n" - "START opens the Windows command prompt automatically to run these commands\n" - "and wait for a key press before exiting (specified by \"startincon\" option):\n%s\n\n" -#else - "START /OPEN file\nSTART command [arguments]\n\n" - " /OPEN: To open a file or URL with the associated program.\n" - " file: The file or URL to open with the associated program.\n" - " command: The command or program to start or run.\n" - " arguments: Arguments to pass to the application.\n\n" -#endif - "Note: The path specified in this command is the path on the host system.\n"; - WriteOut(msg -#if defined(WIN32) - ,startincon.c_str() -#endif - ); - } -}; - -void START_ProgramStart(Program **make) -{ - *make = new START; -} - -#define MAX_FLAGS 512 -char *g_flagged_files[MAX_FLAGS]; //global array to hold flagged files -int flagged_backup(char *zip) -{ - unsigned char buffer[4096]; - char zipfile[CROSS_LEN]; - int ret = 0; - int i; - - bool compresssaveparts = static_cast(control->GetSection("dosbox"))->Get_bool("compresssaveparts"); - - strcpy(zipfile, zip); - if (strstr(zipfile, ".sav")) - strcpy(strstr(zipfile, ".sav"), ".dat"); - - i=0; - while (i < MAX_FLAGS && g_flagged_files[i] == NULL) i++; - if (i < MAX_FLAGS) { - zipFile zf; - { - const char *global_comment = "DOSBox-X flagged file save state"; - zlib_filefunc64_def ffunc; -#ifdef USEWIN32IOAPI - fill_win32_filefunc64A(&ffunc); -#else - fill_fopen64_filefunc(&ffunc); -#endif - remove(zipfile); - zf = zipOpen2_64(zipfile,APPEND_STATUS_CREATE,&global_comment,&ffunc); - } - if (zf != NULL) { - while (i < MAX_FLAGS) { - if (g_flagged_files[i] != NULL) { - uint16_t handle = 0; - if (DOS_FindDevice(("\""+std::string(g_flagged_files[i])+"\"").c_str()) != DOS_DEVICES || !DOS_OpenFile(("\""+std::string(g_flagged_files[i])+"\"").c_str(),0,&handle)) { - LOG_MSG(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),g_flagged_files[i]); - continue; - } - - zip_fileinfo zi; zipSetCurrentTime(zi); - if (zipOutOpenFile(zf,g_flagged_files[i],zi,compresssaveparts) == ZIP_OK) { - zip_ostreambuf zos(zf); - - do { - uint16_t n = sizeof(buffer); - DOS_ReadFile(handle,buffer,&n); - if (n == 0) break; - if (zos.xsputn((zip_ostreambuf::char_type*)buffer,n) < n) break; - } while(1); - - zos.close(); - } - - DOS_CloseFile(handle); - } - - i++; - } - zipClose(zf,NULL); - } - } - - return ret; -} - -int flagged_restore(char* zip) -{ - unsigned char buffer[4096]; - unz_file_info64 file_info; - char zipfile[MAX_FLAGS]; - int ret = 0; - int i; - - strcpy(zipfile, zip); - if (strstr(zipfile, ".sav")) - strcpy(strstr(zipfile, ".sav"), ".dat"); - i=0; - while (i < MAX_FLAGS && g_flagged_files[i] == NULL) i++; - if (i < MAX_FLAGS) { - unzFile zf; - { - zlib_filefunc64_def ffunc; -#ifdef USEWIN32IOAPI - fill_win32_filefunc64A(&ffunc); -#else - fill_fopen64_filefunc(&ffunc); -#endif - zf = unzOpen2_64(zipfile,&ffunc); - } - if (zf != NULL) { - while (i < MAX_FLAGS) { - if (g_flagged_files[i] != NULL) { - if (DOS_FindDevice(("\""+std::string(g_flagged_files[i])+"\"").c_str()) != DOS_DEVICES) { - LOG_MSG(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),g_flagged_files[i]); - continue; - } - - if (unzLocateFile(zf,g_flagged_files[i],2/*case insensitive*/) == UNZ_OK && - unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0) == UNZ_OK) { - if (unzOpenCurrentFile(zf) == UNZ_OK) { - zip_istreambuf zis(zf); - - uint16_t handle=0; - if (DOS_CreateFile(("\""+std::string(g_flagged_files[i])+"\"").c_str(),0,&handle)) { - do { - uint16_t n = zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)); - if (n == 0) break; - DOS_WriteFile(handle,(uint8_t*)buffer,&n); - if (n == 0) break; - } while (1); - DOS_CloseFile(handle); - } - - zis.close(); - } - } - } - - i++; - } - unzClose(zf); - } - } - - return ret; -} - -class FLAGSAVE : public Program -{ -public: - - void Run(void) override - { - std::string file_to_flag; - int i, lf; - bool force=false, remove=false; - - if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { - printHelp(); - return; - } - if (cmd->FindExist("/f", true)) - force=true; - if (cmd->FindExist("/r", true)) - remove=true; - if (cmd->FindExist("/u", true)) - { - for (i = 0; i < MAX_FLAGS; i++) - { - if (g_flagged_files[i] != NULL) - g_flagged_files[i] = NULL; - } - WriteOut("All files unflagged for saving.\n"); - return; - } - else if (cmd->GetCount()) - { - for (unsigned int i=1; i<=cmd->GetCount(); i++) { - cmd->FindCommand(i,temp_line); - uint8_t drive; - char fullname[DOS_PATHLENGTH], flagfile[CROSS_LEN]; - - strcpy(flagfile, temp_line.c_str()); - if (*flagfile&&DOS_MakeName(((flagfile[0]!='\"'?"\"":"")+std::string(flagfile)+(flagfile[strlen(flagfile)-1]!='\"'?"\"":"")).c_str(), fullname, &drive)) - { - sprintf(flagfile, "%c:\\%s", drive+'A', fullname); - if (remove) { - for (lf = 0; lf < MAX_FLAGS; lf++) - { - if (g_flagged_files[lf] != NULL && !strcasecmp(g_flagged_files[lf], flagfile)) - { - WriteOut("File %s unflagged for saving.\n", g_flagged_files[lf]); - free(g_flagged_files[lf]); - g_flagged_files[lf] = NULL; - break; - } - } - continue; - } - if (!force && !DOS_FileExists(("\""+std::string(flagfile)+"\"").c_str())) { - WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"), flagfile); - continue; - } - bool found=false; - for (lf = 0; lf < MAX_FLAGS; lf++) - { - if (g_flagged_files[lf] == NULL) - continue; - if (!strcasecmp(g_flagged_files[lf], flagfile)) - { - WriteOut("File already flagged for saving - %s\n", flagfile); - found=true; - } - } - if (found) continue; - for (lf = 0; lf < MAX_FLAGS; lf++) - { - if (g_flagged_files[lf] == NULL) - break; - } - if (lf == MAX_FLAGS) - { - WriteOut("Too many files to flag for saving.\n"); - return; - } - g_flagged_files[lf] = (char*)malloc(strlen(flagfile) + 1); - strcpy(g_flagged_files[lf], flagfile); - WriteOut("File %s flagged for saving\n", g_flagged_files[lf]); - } else - WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"), flagfile); - } - return; - } - else - { - WriteOut("Files flagged for saving:\n"); - for (i = 0; i < MAX_FLAGS; i++) - { - if (g_flagged_files[i]) - WriteOut("%s\n", g_flagged_files[i]); - } - return; - } - } - void printHelp() - { - WriteOut( "Marks or flags files to be saved for the save state feature.\n\n" - "FLAGSAVE [file(s) [/F] [/R]] [/U]\n\n" - " file(s) Specifies one or more files to be flagged for saving.\n" - " /F Forces to flag the file(s) even if they are not found.\n" - " /R Removes flags from the specified file(s).\n" - " /U Removes flags from all flagged files.\n\n" - "Type FLAGSAVE without a parameter to list flagged files.\n"); - } -}; - -static void FLAGSAVE_ProgramStart(Program** make) -{ - *make = new FLAGSAVE; -} - -void Add_VFiles(bool usecp) { - VFILE_Register("TEXTUTIL", nullptr, 0, "/"); - VFILE_Register("SYSTEM", nullptr, 0, "/"); - VFILE_Register("DEBUG", nullptr, 0, "/"); - VFILE_Register("DOS", nullptr, 0, "/"); - VFILE_Register("CPI", nullptr, 0, "/"); - VFILE_Register("BIN", nullptr, 0, "/"); - VFILE_Register("4DOS", nullptr, 0, "/"); - - std::string dirname="drivez"; - std::string path = "."; - path += CROSS_FILESPLIT; - path += dirname; - getdrivezpath(path, dirname); - drivezRegister(path, "/", usecp); - - PROGRAMS_MakeFile("HELP.COM",HELP_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("INTRO.COM",INTRO_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("IMGMOUNT.COM", IMGMOUNT_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("IMGMAKE.COM", IMGMAKE_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("IMGSWAP.COM", IMGSWAP_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("MOUNT.COM",MOUNT_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("BOOT.COM",BOOT_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("CONFIG.COM",CONFIG_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("COUNTRY.COM",COUNTRY_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("COMMAND.COM",SHELL_ProgramStart); - internal_program = true; - if (usecp && prepared) VFILE_Register("AUTOEXEC.BAT",(uint8_t *)autoexec_data,(uint32_t)strlen(autoexec_data)); - if (prepared) VFILE_Register("CONFIG.SYS",(uint8_t *)config_data,(uint32_t)strlen(config_data)); - internal_program = false; - PROGRAMS_MakeFile("RE-DOS.COM",REDOS_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("RESCAN.COM",RESCAN_ProgramStart,"/SYSTEM/"); -#if defined(WIN32) && !defined(HX_DOS) || defined(LINUX) || defined(MACOSX) - if (startcmd) PROGRAMS_MakeFile("START.COM", START_ProgramStart,"/SYSTEM/"); -#endif - - if (machine == MCH_CGA) PROGRAMS_MakeFile("CGASNOW.COM",CGASNOW_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("VFRCRATE.COM",VFRCRATE_ProgramStart,"/DEBUG/"); - - if (IS_VGA_ARCH && svgaCard != SVGA_None) - PROGRAMS_MakeFile("VESAMOED.COM",VESAMOED_ProgramStart,"/DEBUG/"); - - if (!IS_PC98_ARCH) { - PROGRAMS_MakeFile("LOADROM.COM", LOADROM_ProgramStart,"/DEBUG/"); - PROGRAMS_MakeFile("KEYB.COM", KEYB_ProgramStart,"/DOS/"); - PROGRAMS_MakeFile("MODE.COM", MODE_ProgramStart,"/DOS/"); - PROGRAMS_MakeFile("MOUSE.COM", MOUSE_ProgramStart,"/DOS/"); - PROGRAMS_MakeFile("SETCOLOR.COM", SETCOLOR_ProgramStart,"/BIN/"); - } - - if (IS_VGA_ARCH) { - PROGRAMS_MakeFile("80X60.COM", TEXT80X60_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("80X50.COM", TEXT80X50_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("80X43.COM", TEXT80X43_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("80X25.COM", TEXT80X25_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("132X60.COM", TEXT132X60_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("132X50.COM", TEXT132X50_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("132X43.COM", TEXT132X43_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("132X25.COM", TEXT132X25_ProgramStart,"/TEXTUTIL/"); - PROGRAMS_MakeFile("DCGA.COM", DCGA_ProgramStart,"/TEXTUTIL/"); - } - - PROGRAMS_MakeFile("COLOR.COM",COLOR_ProgramStart,"/BIN/"); - PROGRAMS_MakeFile("TITLE.COM",TITLE_ProgramStart,"/BIN/"); - PROGRAMS_MakeFile("VHDMAKE.COM",VHDMAKE_ProgramStart,"/BIN/"); - PROGRAMS_MakeFile("LS.COM",LS_ProgramStart,"/BIN/"); - PROGRAMS_MakeFile("ADDKEY.COM",ADDKEY_ProgramStart,"/BIN/"); - PROGRAMS_MakeFile("CFGTOOL.COM",CFGTOOL_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("FLAGSAVE.COM", FLAGSAVE_ProgramStart,"/SYSTEM/"); -#if defined C_DEBUG - PROGRAMS_MakeFile("NMITEST.COM",NMITEST_ProgramStart,"/DEBUG/"); - PROGRAMS_MakeFile("INT2FDBG.COM",INT2FDBG_ProgramStart,"/DEBUG/"); - PROGRAMS_MakeFile("BIOSTEST.COM", BIOSTEST_ProgramStart,"/DEBUG/"); -#endif - PROGRAMS_MakeFile("A20GATE.COM",A20GATE_ProgramStart,"/DEBUG/"); - - if (IS_PC98_ARCH) - PROGRAMS_MakeFile("PC98UTIL.COM",PC98UTIL_ProgramStart,"/BIN/"); - - PROGRAMS_MakeFile("CAPMOUSE.COM", CAPMOUSE_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("LOADFIX.COM",LOADFIX_ProgramStart,"/DOS/"); - PROGRAMS_MakeFile("LABEL.COM", LABEL_ProgramStart,"/DOS/"); - PROGRAMS_MakeFile("TREE.COM", TREE_ProgramStart,"/DOS/"); - PROGRAMS_MakeFile("DELTREE.EXE",DELTREE_ProgramStart,"/DOS/"); - PROGRAMS_MakeFile("CHOICE.COM", CHOICE_ProgramStart,"/DOS/"); - PROGRAMS_MakeFile("AUTOTYPE.COM", AUTOTYPE_ProgramStart,"/BIN/"); -#ifdef C_ICONV - PROGRAMS_MakeFile("UTF8.COM", UTF8_ProgramStart,"/BIN/"); - PROGRAMS_MakeFile("UTF16.COM", UTF16_ProgramStart,"/BIN/"); -#endif - PROGRAMS_MakeFile("MIXER.COM",MIXER_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("SERIAL.COM", SERIAL_ProgramStart,"/SYSTEM/"); - PROGRAMS_MakeFile("PARALLEL.COM", PARALLEL_ProgramStart,"/SYSTEM/"); - if (IS_DOSV) - PROGRAMS_MakeFile("VTEXT.COM", VTEXT_ProgramStart,"/TEXTUTIL/"); - - VFILE_RegisterBuiltinFileBlob(bfb_EDLIN_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_DEBUG_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_MOVE_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_FIND_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_FCBS_COM, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_FILES_COM, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_LASTDRIV_COM, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_REPLACE_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_SORT_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_XCOPY_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_APPEND_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_DEVICE_COM, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_BUFFERS_COM, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_CHKDSK_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_COMP_COM, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_FC_EXE, "/DOS/"); -#if C_IPX - if (addipx) PROGRAMS_MakeFile("IPXNET.COM",IPXNET_ProgramStart,"/SYSTEM/"); -#endif - if (addne2k) VFILE_RegisterBuiltinFileBlob(bfb_NE2000_COM, "/SYSTEM/"); - if (addovl) VFILE_RegisterBuiltinFileBlob(bfb_GLIDE2X_OVL, "/SYSTEM/"); - - /* These are IBM PC/XT/AT ONLY. They will not work in PC-98 mode. */ - if (!IS_PC98_ARCH) { - VFILE_RegisterBuiltinFileBlob(bfb_SYS_COM, "/DOS/"); /* may rely on INT 13h or IBM PC specific functions and layout */ - VFILE_RegisterBuiltinFileBlob(bfb_FORMAT_EXE, "/DOS/"); /* does not work in PC-98 mode */ - VFILE_RegisterBuiltinFileBlob(bfb_DEFRAG_EXE, "/DOS/"); /* relies on IBM PC CGA/EGA/VGA alphanumeric display memory */ - VFILE_RegisterBuiltinFileBlob(bfb_FDISK_EXE, "/BIN/"); /* relies on IBM PC INT 13h */ - VFILE_RegisterBuiltinFileBlob(bfb_HEXMEM16_EXE, "/DEBUG/"); - VFILE_RegisterBuiltinFileBlob(bfb_HEXMEM32_EXE, "/DEBUG/"); - VFILE_RegisterBuiltinFileBlob(bfb_DOSIDLE_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_DOS32A_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_DOS4GW_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_CDPLAY_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_CDPLAY_TXT, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_CDPLAY_ZIP, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_DOSMID_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_MPXPLAY_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_ZIP_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_UNZIP_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_EMSMAGIC_COM, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_DISKCOPY_EXE, "/DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_CWSDPMI_EXE, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_PRINT_COM, "/DOS/"); - - /* It appears the latest EDIT.COM requires a 386, and it does not bother - * to detect if the CPU is a 386. If you run this program for 286 and lower - * you get a crash. */ - if (CPU_ArchitectureType >= CPU_ARCHTYPE_386) - VFILE_RegisterBuiltinFileBlob(bfb_EDIT_COM, "/DOS/"); - - VFILE_RegisterBuiltinFileBlob(bfb_LICENSE_TXT, "/4DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_EXAMPLES_BTM, "/4DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_BATCOMP_EXE, "/4DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_OPTION_EXE, "/4DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_4HELP_EXE, "/4DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_4DOS_HLP, "/4DOS/"); - VFILE_RegisterBuiltinFileBlob(bfb_4DOS_COM, "/4DOS/"); - } - if (prepared) VFILE_Register("4DOS.INI",(uint8_t *)i4dos_data,(uint32_t)strlen(i4dos_data), "/4DOS/"); - - if (IS_VGA_ARCH) { - VFILE_RegisterBuiltinFileBlob(bfb_VGA_COM, "/TEXTUTIL/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA_COM, "/TEXTUTIL/"); - VFILE_RegisterBuiltinFileBlob(bfb_CLR_COM, "/TEXTUTIL/"); - VFILE_RegisterBuiltinFileBlob(bfb_CGA_COM, "/TEXTUTIL/"); - VFILE_RegisterBuiltinFileBlob(bfb_50_COM, "/TEXTUTIL/"); - VFILE_RegisterBuiltinFileBlob(bfb_28_COM, "/TEXTUTIL/"); - } else if (IS_EGA_ARCH) - VFILE_RegisterBuiltinFileBlob(bfb_28_COM_ega, "/TEXTUTIL/"); - - if (IS_VGA_ARCH) - VFILE_RegisterBuiltinFileBlob(bfb_25_COM, "/TEXTUTIL/"); - else if (IS_EGA_ARCH) - VFILE_RegisterBuiltinFileBlob(bfb_25_COM_ega, "/TEXTUTIL/"); - else if (!IS_PC98_ARCH) - VFILE_RegisterBuiltinFileBlob(bfb_25_COM_other, "/TEXTUTIL/"); - - /* MEM.COM is not compatible with PC-98 and/or 8086 emulation */ - if(!IS_PC98_ARCH && CPU_ArchitectureType >= CPU_ARCHTYPE_80186) - VFILE_RegisterBuiltinFileBlob(bfb_MEM_EXE, "/DOS/"); - else if(IS_PC98_ARCH || CPU_ArchitectureType < CPU_ARCHTYPE_80186) - VFILE_RegisterBuiltinFileBlob(bfb_MEM_EXE_PC98, "/DOS/"); - - /* DSXMENU.EXE */ - if(IS_PC98_ARCH) { - VFILE_RegisterBuiltinFileBlob(bfb_DSXMENU_EXE_PC98, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_CWSDPMI_PC98_EXE, "/BIN/"); - } - else { - VFILE_RegisterBuiltinFileBlob(bfb_DSXMENU_EXE_PC, "/BIN/"); - VFILE_RegisterBuiltinFileBlob(bfb_SHUTDOWN_COM, "/BIN/"); - } - - VFILE_RegisterBuiltinFileBlob(bfb_EVAL_EXE, "/BIN/"); - if(!IS_PC98_ARCH) - VFILE_RegisterBuiltinFileBlob(bfb_EVAL_HLP, "/BIN/"); - - VFILE_RegisterBuiltinFileBlob(bfb_EGA18_CPI, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA17_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA16_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA15_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA14_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA13_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA12_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA11_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA10_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA9_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA8_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA7_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA6_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA5_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA4_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA3_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA2_CPX, "/CPI/"); - VFILE_RegisterBuiltinFileBlob(bfb_EGA_CPX, "/CPI/"); -} - -#if WIN32 -void Add_Existing_Drive_Directories() -{ - for(auto drive = 'C'; drive < 'Y'; drive++) - { - auto name = std::string("drive"); - auto path = std::string("."); - - name += drive; - path += CROSS_FILESPLIT; - path += name; - - getdrivezpath(path, name); - - if (path.empty()) - continue; - - LOG_MSG("Mounting directory 'drive%c' found in DOSBox-X directory as drive %c.\n", static_cast(drive + 32), drive); - - MountHelper(drive, path.c_str(), "LOCAL"); - } -} -#endif - -void DOS_SetupPrograms(void) { - /*Add Messages */ - - MSG_Add("PROGRAM_MOUSE_INSTALL","Installed at PS/2 port.\n"); - MSG_Add("PROGRAM_MOUSE_VERTICAL","Reverse Y-axis enabled.\n"); - MSG_Add("PROGRAM_MOUSE_VERTICAL_BACK","Reverse Y-axis disabled.\n"); - MSG_Add("PROGRAM_MOUSE_UNINSTALL","Driver successfully unloaded...\n"); - MSG_Add("PROGRAM_MOUSE_ERROR","Already installed at PS/2 port.\n"); - MSG_Add("PROGRAM_MOUSE_NOINSTALLED","Driver is not installed.\n"); - MSG_Add("PROGRAM_MOUSE_HELP","Turns on/off mouse.\n\nMOUSE [/?] [/U] [/V]\n /U: Uninstall\n /V: Reverse Y-axis\n"); - MSG_Add("PROGRAM_MOUNT_CDROMS_FOUND","CDROMs found: %d\n"); - MSG_Add("PROGRAM_MOUNT_STATUS_FORMAT","%-5s %-58s %-12s\n"); - MSG_Add("PROGRAM_MOUNT_STATUS_ELTORITO", "Drive %c is mounted as El Torito floppy drive\n"); - MSG_Add("PROGRAM_MOUNT_STATUS_RAMDRIVE", "Drive %c is mounted as RAM drive\n"); - MSG_Add("PROGRAM_MOUNT_STATUS_2","Drive %c is mounted as %s\n"); - MSG_Add("PROGRAM_MOUNT_STATUS_1","The currently mounted drives are:\n"); - MSG_Add("PROGRAM_MOUNT_NOT_FORMATTED","Drive not formatted. Format it before accessing the drive.\n"); - MSG_Add("PROGRAM_MOUNT_UNSUPPORTED_EXT","Unsupported extension %s: Mounted as raw IMG image.\n"); - MSG_Add("PROGRAM_IMGMOUNT_STATUS_FORMAT","%-5s %-47s %-12s %s\n"); - MSG_Add("PROGRAM_IMGMOUNT_STATUS_NUMBER_FORMAT","%-12s %-40s %-12s %s\n"); - MSG_Add("PROGRAM_IMGMOUNT_STATUS_2","The currently mounted drive numbers are:\n"); - MSG_Add("PROGRAM_IMGMOUNT_STATUS_1","The currently mounted FAT/ISO drives are:\n"); - MSG_Add("PROGRAM_IMGMOUNT_STATUS_NONE","No drive available\n"); - MSG_Add("PROGRAM_IMGSWAP_STATUS","Drives currently available for swapping are:\n"); - MSG_Add("PROGRAM_IMGSWAP_ERROR","Position must be between 1 and %d for this drive.\n"); - MSG_Add("PROGRAM_MOUNT_ERROR_1","Directory %s does not exist.\n"); - MSG_Add("PROGRAM_MOUNT_ERROR_2","%s is not a directory\n"); - MSG_Add("PROGRAM_MOUNT_IMGMOUNT","To mount image files, use the \033[34;1mIMGMOUNT\033[0m command, not the \033[34;1mMOUNT\033[0m command.\n"); - MSG_Add("PROGRAM_MOUNT_ILL_TYPE","Illegal type %s\n"); - MSG_Add("PROGRAM_MOUNT_ALREADY_MOUNTED","Drive %c already mounted with %s\n"); - MSG_Add("PROGRAM_MOUNT_USAGE", - "Mounts directories or drives in the host system as DOSBox-X drives.\n" - "Usage: \033[34;1m\033[32;1mMOUNT\033[0m \033[37;1mdrive\033[0m \033[36;1mlocal_directory\033[0m [option]\033[0m\n" - " \033[37;1mdrive\033[0m Drive letter where the directory or drive will be mounted.\n" - " \033[36;1mlocal_directory\033[0m Local directory or drive in the host system to be mounted.\n" - " [option] Option(s) for mounting. The following options are accepted:\n" - " -t Specify the drive type the mounted drive to behave as.\n" - " Supported drive type: dir, floppy, cdrom, overlay\n" - " (Note that 'overlay' redirects writes for mounted drive to another directory)\n" - " -label [name] Set the volume label name of the drive (all upper case).\n" - " -nl Use next available drive letter if the drive is mounted.\n" - " -ro Mount the drive in read-only mode.\n" - " -pr Specify the path is relative to the config file location.\n" - " -cd Generate a list of local CD drive's \"drive #\" values.\n" - " -usecd [drive #] For direct hardware emulation such as audio playback.\n" - " -ioctl Use lowest level hardware access (following -usecd option).\n" - " -aspi Use the installed ASPI layer (following -usecd option).\n" - " -freesize [size] Specify the free disk space of drive in MB (KB for floppies).\n" - " -nocachedir Enable real-time update and do not cache the drive.\n" - " -z drive Move virtual drive Z: to a different letter.\n" - " -o Report the drive as: local, remote.\n" - " -q Quiet mode (no message output).\n" - " -u Unmount the drive.\n" - " \033[32;1m-examples Show some usage examples.\033[0m\n" - "Type MOUNT with no parameters to display a list of mounted drives."); - MSG_Add("PROGRAM_MOUNT_EXAMPLE", - "A basic example of MOUNT command:\n\n" - "\033[32;1mMOUNT c %s\033[0m\n\n" - "This makes the directory %s act as the C: drive inside DOSBox-X.\n" - "The directory has to exist in the host system. If the directory contains\n" - "space(s), be sure to properly quote the directory with double quotes,\n" - "e.g. %s\n\n" - "Some other usage examples of MOUNT:\n\n" -#if defined (WIN32) || defined(OS2) - "\033[32;1mMOUNT\033[0m - list all mounted drives\n" - "\033[32;1mMOUNT -cd\033[0m - list all local CD drives\n" -#else - "\033[32;1mMOUNT\033[0m - list all mounted drives\n" - "\033[32;1mMOUNT -cd\033[0m - list all local CD drives\n" -#endif - "\033[32;1mMOUNT d %s\033[0m - mount the D: drive to the directory\n" - "\033[32;1mMOUNT c %s -t cdrom\033[0m - mount the C: drive as a CD-ROM drive\n" - "\033[32;1mMOUNT c %s -ro\033[0m - mount the C: drive in read-only mode\n" - "\033[32;1mMOUNT c %s -label TEST\033[0m - mount the C: drive with the label TEST\n" - "\033[32;1mMOUNT c %s -nocachedir \033[0m - mount C: without caching the drive\n" - "\033[32;1mMOUNT c %s -freesize 128\033[0m - mount C: with 128MB free disk space\n" - "\033[32;1mMOUNT c %s -u\033[0m - force mount C: drive even if it's mounted\n" - "\033[32;1mMOUNT c %s -t overlay\033[0m - mount C: with overlay directory on top\n" -#if defined (WIN32) || defined(OS2) - "\033[32;1mMOUNT c -u\033[0m - unmount the C: drive\n" -#else - "\033[32;1mMOUNT c -u\033[0m - unmount the C: drive\n" -#endif - ); - MSG_Add("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED","Drive %c is not mounted.\n"); - MSG_Add("PROGRAM_MOUNT_UMOUNT_SUCCESS","Drive %c has successfully been removed.\n"); - MSG_Add("PROGRAM_MOUNT_UMOUNT_NUMBER_SUCCESS","Drive number %c has successfully been removed.\n"); - MSG_Add("PROGRAM_MOUNT_UMOUNT_NO_VIRTUAL","Virtual Drives can not be unMOUNTed.\n"); - MSG_Add("PROGRAM_MOUNT_WARNING_WIN","Warning: Mounting C:\\ is not recommended.\n"); - MSG_Add("PROGRAM_MOUNT_WARNING_OTHER","Warning: Mounting / is not recommended.\n"); - MSG_Add("PROGRAM_MOUNT_PHYSFS_ERROR","Failed to mount the PhysFS drive with the archive file.\n"); - MSG_Add("PROGRAM_MOUNT_OVERLAY_NO_BASE","Please MOUNT a normal directory first before adding an overlay on top.\n"); - MSG_Add("PROGRAM_MOUNT_OVERLAY_INCOMPAT_BASE","The overlay is NOT compatible with the drive that is specified.\n"); - MSG_Add("PROGRAM_MOUNT_OVERLAY_MIXED_BASE","The overlay needs to be specified using the same addressing as the underlying drive. No mixing of relative and absolute paths."); - MSG_Add("PROGRAM_MOUNT_OVERLAY_SAME_AS_BASE","The overlay directory can not be the same as underlying drive.\n"); - MSG_Add("PROGRAM_MOUNT_OVERLAY_ERROR","An error occurred when trying to create an overlay drive.\n"); - MSG_Add("PROGRAM_MOUNT_OVERLAY_STATUS","Overlay %s on drive %c mounted.\n"); - - MSG_Add("PROGRAM_LOADFIX_ALLOC","%d kb allocated.\n"); - MSG_Add("PROGRAM_LOADFIX_DEALLOC","%d kb freed.\n"); - MSG_Add("PROGRAM_LOADFIX_DEALLOCALL","Used memory freed.\n"); - MSG_Add("PROGRAM_LOADFIX_ERROR","Memory allocation error.\n"); - MSG_Add("PROGRAM_LOADFIX_HELP", - "Loads a program above the first 64 KB memory by reducing the available memory.\n\n" - "LOADFIX [-xms] [-ems] [-{ram}] [{program}] [{options}]\n" - "LOADFIX -f [-xms] [-ems]\n\n" - " -xms Allocates memory from XMS rather than conventional memory\n" - " -ems Allocates memory from EMS rather than conventional memory\n" - " -{ram} Specifies the amount of memory to allocate in KB\n" - " Defaults to 64KB for conventional memory; 1MB for XMS/EMS memory\n" - " -a Auto allocates enough memory to fill the lowest 64KB memory\n" - " -f (or -d) Frees previously allocated memory\n" - " {program} Runs the specified program\n" - " {options} Program options (if any)\n\n" - "Examples:\n" - " \033[32;1mLOADFIX game.exe\033[0m Allocates 64KB of conventional memory and runs game.exe\n" - " \033[32;1mLOADFIX -a\033[0m Auto-allocates enough memory conventional memory\n" - " \033[32;1mLOADFIX -128\033[0m Allocates 128KB of conventional memory\n" - " \033[32;1mLOADFIX -xms\033[0m Allocates 1MB of XMS memory\n" - " \033[32;1mLOADFIX -f\033[0m Frees allocated conventional memory\n"); - - MSG_Add("MSCDEX_SUCCESS","MSCDEX installed.\n"); - MSG_Add("MSCDEX_ERROR_MULTIPLE_CDROMS","MSCDEX: Failure: Drive-letters of multiple CD-ROM drives have to be continuous.\n"); - MSG_Add("MSCDEX_ERROR_NOT_SUPPORTED","MSCDEX: Failure: Not yet supported.\n"); - MSG_Add("MSCDEX_ERROR_PATH","MSCDEX: Specified location is not a CD-ROM drive.\n"); - MSG_Add("MSCDEX_ERROR_OPEN","MSCDEX: Failure: Invalid file or unable to open.\n"); - MSG_Add("MSCDEX_TOO_MANY_DRIVES","MSCDEX: Failure: Too many CD-ROM drives (max: 5). MSCDEX Installation failed.\n"); - MSG_Add("MSCDEX_LIMITED_SUPPORT","MSCDEX: Mounted subdirectory: limited support.\n"); - MSG_Add("MSCDEX_INVALID_FILEFORMAT","MSCDEX: Failure: File is either no ISO/CUE image or contains errors.\n"); - MSG_Add("MSCDEX_UNKNOWN_ERROR","MSCDEX: Failure: Unknown error.\n"); - - MSG_Add("PROGRAM_RESCAN_SUCCESS","Drive cache cleared.\n"); - - MSG_Add("PROGRAM_INTRO", - "\033[2J\033[32;1mWelcome to DOSBox-X\033[0m, an open-source x86 emulator with sound and graphics.\n" - "DOSBox-X creates a shell for you which looks just like the plain DOS.\n" - "\n" - "\033[31;1mDOSBox-X will stop/exit without a warning if an error occurred!\033[0m\n" - "\n" - "\n" ); - MSG_Add("PROGRAM_INTRO_MENU_UP", "DOSBox-X Introduction"); - MSG_Add("PROGRAM_INTRO_MENU_BASIC","Basic mount"); - MSG_Add("PROGRAM_INTRO_MENU_CDROM","CD-ROM support"); - MSG_Add("PROGRAM_INTRO_MENU_USAGE","Usage"); - MSG_Add("PROGRAM_INTRO_MENU_INFO","Information"); - MSG_Add("PROGRAM_INTRO_MENU_QUIT","Quit"); - MSG_Add("PROGRAM_INTRO_MENU_BASIC_HELP","\n\033[1m \033[1m\033[KMOUNT allows you to connect real hardware to DOSBox-X's emulated PC.\033[0m\n"); - MSG_Add("PROGRAM_INTRO_MENU_CDROM_HELP","\n\033[1m \033[1m\033[KTo mount your CD-ROM in DOSBox-X, you need to specify additional options\n when mounting the CD-ROM.\033[0m\n"); - MSG_Add("PROGRAM_INTRO_MENU_USAGE_HELP","\n\033[1m \033[1m\033[KAn overview of the command line options you can give to DOSBox-X.\033[0m\n"); - MSG_Add("PROGRAM_INTRO_MENU_INFO_HELP","\n\033[1m \033[1m\033[KHow to get more information about DOSBox-X.\033[0m\n"); - MSG_Add("PROGRAM_INTRO_MENU_QUIT_HELP","\n\033[1m \033[1m\033[KExit from Intro.\033[0m\n"); - MSG_Add("PROGRAM_INTRO_USAGE_TOP", - "\033[2J\033[32;1mAn overview of the command line options you can give to DOSBox-X.\033[0m\n" - "Windows users must open cmd.exe or edit the shortcut to DOSBox-X.exe for this.\n\n" - "dosbox-x [name] [-exit] [-version] [-fastlaunch] [-fullscreen]\n" - " [-conf congfigfile] [-lang languagefile] [-machine machinetype]\n" - " [-startmapper] [-noautoexec] [-scaler scaler | -forcescaler scaler]\n" - " [-o options] [-c command] [-set
]\n\n" - ); - MSG_Add("PROGRAM_INTRO_USAGE_1", - "\033[33;1m name\033[0m\n" - "\tIf name is a directory it will mount that as the C: drive.\n" - "\tIf name is an executable it will mount the directory of name\n" - "\tas the C: drive and execute name.\n\n" - "\033[33;1m -exit\033[0m\n" - "\tDOSBox-X will close itself when the DOS application name ends.\n\n" - "\033[33;1m -version\033[0m\n" - "\tOutputs version information and exit. Useful for frontends.\n\n" - "\033[33;1m -fastlaunch\033[0m\n" - "\tEnables fast launch mode (skip BIOS logo and welcome banner).\n\n" - "\033[33;1m -fullscreen\033[0m\n" - "\tStarts DOSBox-X in fullscreen mode.\n" - ); - MSG_Add("PROGRAM_INTRO_USAGE_2", - "\033[33;1m -conf\033[0m configfile\n" - "\tStart DOSBox-X with the options specified in configfile.\n" - "\tSee the documentation for more details.\n\n" - "\033[33;1m -lang\033[0m languagefile\n" - "\tStart DOSBox-X using the language specified in languagefile.\n\n" - "\033[33;1m -startmapper\033[0m\n" - "\tEnter the keymapper directly on startup. Useful for people with\n" - "\tkeyboard problems.\n\n" - "\033[33;1m -machine\033[0m machinetype\n" - "\tSetup DOSBox-X to emulate a specific type of machine. Valid choices:\n" - "\thercules, cga, cga_mono, mcga, mda, pcjr, tandy, ega, vga, vgaonly,\n" - "\tpc98, vesa_nolfb, vesa_oldvbe, svga_paradise, svga_s3 (default).\n" - "\tThe machinetype affects both the video card and available sound cards.\n" - ); - MSG_Add("PROGRAM_INTRO_USAGE_3", - "\033[33;1m -noautoexec\033[0m\n" - "\tSkips the [autoexec] section of the loaded configuration file.\n\n" - "\033[33;1m -o\033[0m options\n" - "\tProvides command-line option(s) for \"name\" if an executable name is\n" - "\tspecified. Multiple -o can be used for multiple executable names.\n\n" - "\033[33;1m -c\033[0m command\n" - "\tRuns the specified command before running name. Multiple commands\n" - "\tcan be specified. Each command should start with -c, though.\n" - "\tA command can be: an Internal Program, a DOS command or an executable\n" - "\ton a mounted drive.\n\n" - "\033[33;1m -set\033[0m
\n" - "\tSets the config option (overriding the config file). Multiple options\n" - "\tcan be specified. Each option should start with -set, though.\n" - ); - MSG_Add("PROGRAM_INTRO_INFO", - "\033[32;1mInformation:\033[0m\n\n" - "For information about basic mount, type \033[34;1mintro mount\033[0m\n" - "For information about CD-ROM support, type \033[34;1mintro cdrom\033[0m\n" - "For information about usage, type \033[34;1mintro usage\033[0m\n\n" - "For the latest version of DOSBox-X, go to its homepage:\033[34;1m\n" - "\n" - "\033[34;1mhttps://dosbox-x.com/\033[0m or \033[34;1mhttp://dosbox-x.software\033[0m\n" - "\n" - "For more information about DOSBox-X, please take a look at its Wiki:\n" - "\n" - "\033[34;1mhttps://dosbox-x.com/wiki\033[0m\n" - ); - MSG_Add("PROGRAM_INTRO_MOUNT_START", - "\033[32;1mHere are some commands to get you started:\033[0m\n" - "Before you can use the files located on your own filesystem,\n" - "you have to mount the directory containing the files.\n" - "\n" - ); - MSG_Add("PROGRAM_INTRO_MOUNT_EXST_WINDOWS", "\033[32mmount c c:\\dosgames\\\033[37m will create a C drive with c:\\dosgames as contents."); - MSG_Add("PROGRAM_INTRO_MOUNT_EXEN_WINDOWS", "c:\\dosgames\\\033[37m is an example. Replace it with your own games directory. \033[37m "); - MSG_Add("PROGRAM_INTRO_MOUNT_EXST_OTHER", "\033[32mmount c ~/dosgames\033[37m will create a C drive with ~/dosgames as contents."); - MSG_Add("PROGRAM_INTRO_MOUNT_EXEN_OTHER", "\033[32m~/dosgames\033[37m is an example. Replace it with your own games directory.\033[37m "); - MSG_Add("PROGRAM_INTRO_MOUNT_END", - "When the mount has successfully completed you can type \033[34;1mc:\033[0m to go to your freshly\n" - "mounted C: drive. Typing \033[34;1mdir\033[0m there will show its contents." - " \033[34;1mcd\033[0m will allow you to\n" - "enter a directory (recognised by the \033[33;1m[]\033[0m in a directory listing).\n" - "You can run programs/files which end with \033[31m.exe .bat\033[0m and \033[31m.com\033[0m.\n" - ); - MSG_Add("PROGRAM_INTRO_CDROM", - "\033[2J\033[32;1mHow to mount a Real/Virtual CD-ROM Drive in DOSBox-X:\033[0m\n" - "DOSBox-X provides CD-ROM emulation on several levels.\n" - "\n" - "The \033[33mbasic\033[0m level works on all CD-ROM drives and normal directories.\n" - "It installs MSCDEX and marks the files read-only.\n" - "Usually this is enough for most games:\n" - "\033[34;1mmount d \033[0;31mD:\\\033[34;1m -t cdrom\033[0m or \033[34;1mmount d C:\\example -t cdrom\033[0m\n" - "If it doesn't work you might have to tell DOSBox-X the label of the CD-ROM:\n" - "\033[34;1mmount d C:\\example -t cdrom -label CDLABEL\033[0m\n" - "\n" - "The \033[33mnext\033[0m level adds some low-level support.\n" - "Therefore only works on CD-ROM drives:\n" - "\033[34;1mmount d \033[0;31mD:\\\033[34;1m -t cdrom -usecd \033[33m0\033[0m\n" - "\n" - "The \033[33mlast\033[0m level of support depends on your Operating System:\n" - "For \033[1mWindows 2000\033[0m, \033[1mWindows XP\033[0m and \033[1mLinux\033[0m:\n" - "\033[34;1mmount d \033[0;31mD:\\\033[34;1m -t cdrom -usecd \033[33m0 \033[34m-ioctl\033[0m\n" - "For \033[1mWindows 9x\033[0m with a ASPI layer installed:\n" - "\033[34;1mmount d \033[0;31mD:\\\033[34;1m -t cdrom -usecd \033[33m0 \033[34m-aspi\033[0m\n" - "\n" - "Replace \033[0;31mD:\\\033[0m with the location of your CD-ROM.\n" - "Replace the \033[33;1m0\033[0m in \033[34;1m-usecd \033[33m0\033[0m with the number reported for your CD-ROM if you type:\n" - "\033[34;1mmount -cd\033[0m\n" - ); - MSG_Add("PROGRAM_BOOT_NOT_EXIST","Bootdisk file does not exist. Failing.\n"); - MSG_Add("PROGRAM_BOOT_NOT_OPEN","Cannot open bootdisk file. Failing.\n"); - MSG_Add("PROGRAM_BOOT_WRITE_PROTECTED","Image file is read-only! Boot in write-protected mode.\n"); - MSG_Add("PROGRAM_BOOT_PRINT_ERROR","This command boots DOSBox-X from either a floppy or hard disk image.\n\n" - "For this command, one can specify a succession of floppy disks swappable\n" - "by the menu command, and drive: specifies the mounted drive to boot from.\n" - "If no drive letter is specified, this defaults to boot from the A drive.\n" - "If no parameter is specified, it will try to boot from the current drive.\n" - "The only bootable drive letters are A, C, and D. For booting from a hard\n" - "drive (C or D), ensure the image is already mounted by \033[34;1mIMGMOUNT\033[0m command.\n\n" - "The syntax of this command is one of the following:\n\n" - "\033[34;1mBOOT [driveletter:] [-convertfat|-convertfatro|-noconvertfat]\033[0m\n\n" - "\033[34;1mBOOT diskimg1.img [diskimg2.img ...] [-L driveletter]\033[0m\n\n" - "Note: An image file with a leading colon (:) will be booted in write-protected\n" - "mode if the \"leading colon write protect image\" option is enabled.\n\n" - "Examples:\n\n" - "\033[32;1mBOOT A:\033[0m - boot from drive A: if it is mounted and bootable.\n" - "\033[32;1mBOOT :DOS.IMG\033[0m - boot from floppy image DOS.IMG in write-protected mode.\n" - ); - MSG_Add("PROGRAM_BOOT_UNABLE","Unable to boot off of drive %c.\n"); - MSG_Add("PROGRAM_BOOT_IMAGE_MOUNTED", "Floppy image(s) already mounted.\n"); - MSG_Add("PROGRAM_BOOT_IMAGE_OPEN","Opening image file: %s\n"); - MSG_Add("PROGRAM_BOOT_IMAGE_NOT_OPEN","Cannot open %s\n"); - MSG_Add("PROGRAM_BOOT_CART_WO_PCJR","PCjr cartridge found, but machine is not PCjr"); - MSG_Add("PROGRAM_BOOT_CART_LIST_CMDS","Available PCjr cartridge commandos:%s"); - MSG_Add("PROGRAM_BOOT_CART_NO_CMDS", "No PCjr cartridge commandos found"); - MSG_Add("PROGRAM_BOOT_BOOTING", "Booting from drive "); - - MSG_Add("PROGRAM_LOADROM_HELP","Loads the specified ROM image file for video BIOS or IBM BASIC.\n\nLOADROM ROM_file\n"); - MSG_Add("PROGRAM_LOADROM_HELP","Must specify ROM file to load.\n"); - MSG_Add("PROGRAM_LOADROM_SPECIFY_FILE","Must specify ROM file to load.\n"); - MSG_Add("PROGRAM_LOADROM_CANT_OPEN","ROM file not accessible.\n"); - MSG_Add("PROGRAM_LOADROM_TOO_LARGE","ROM file too large.\n"); - MSG_Add("PROGRAM_LOADROM_INCOMPATIBLE","Video BIOS not supported by machine type.\n"); - MSG_Add("PROGRAM_LOADROM_UNRECOGNIZED","ROM file not recognized.\n"); - MSG_Add("PROGRAM_LOADROM_BASIC_LOADED","BASIC ROM loaded.\n"); - MSG_Add("PROGRAM_BIOSTEST_HELP","Boots into a BIOS image for running CPU tester BIOS.\n\nBIOSTEST image_file\n"); - - MSG_Add("VHD_ERROR_OPENING", "Could not open the specified VHD file.\n"); - MSG_Add("VHD_INVALID_DATA", "The specified VHD file is corrupt and cannot be opened.\n"); - MSG_Add("VHD_UNSUPPORTED_TYPE", "The specified VHD file is of an unsupported type.\n"); - MSG_Add("VHD_ERROR_OPENING_PARENT", "The parent of the specified VHD file could not be found.\n"); - MSG_Add("VHD_PARENT_INVALID_DATA", "The parent of the specified VHD file is corrupt and cannot be opened.\n"); - MSG_Add("VHD_PARENT_UNSUPPORTED_TYPE", "The parent of the specified VHD file is of an unsupported type.\n"); - MSG_Add("VHD_PARENT_INVALID_MATCH", "The parent of the specified VHD file does not contain the expected identifier.\n"); - MSG_Add("VHD_PARENT_INVALID_DATE", "The parent of the specified VHD file has been changed and cannot be loaded.\n"); - - MSG_Add("PROGRAM_IMGMOUNT_SPECIFY_DRIVE","Must specify drive letter to mount image at.\n"); - MSG_Add("PROGRAM_IMGMOUNT_SPECIFY2","Must specify drive number (0 to %d) to mount image at (0,1=fda,fdb;2,3=hda,hdb).\n"); - /*MSG_Add("PROGRAM_IMGMOUNT_SPECIFY_GEOMETRY", - "For \033[33mCD-ROM\033[0m images: \033[34;1mIMGMOUNT drive-letter location-of-image -t iso\033[0m\n" - "\n" - "For \033[33mhardrive\033[0m images: Must specify drive geometry for hard drives:\n" - "bytes_per_sector, sectors_per_cylinder, heads_per_cylinder, cylinder_count.\n" - "\033[34;1mIMGMOUNT drive-letter location-of-image -size bps,spc,hpc,cyl\033[0m\n");*/ - MSG_Add("PROGRAM_IMGMOUNT_INVALID_IMAGE","Could not load image file.\n" - "Check that the path is correct and the image is accessible.\n"); - MSG_Add("PROGRAM_IMGMOUNT_INVALID_GEOMETRY","Could not extract drive geometry from image.\n" - "Use parameter -size bps,spc,hpc,cyl to specify the geometry.\n"); - MSG_Add("PROGRAM_IMGMOUNT_AUTODET_VALUES","Image geometry auto detection: -size %u,%u,%u,%u\n"); - MSG_Add("PROGRAM_IMGMOUNT_TYPE_UNSUPPORTED","Type \"%s\" is unsupported. Specify \"hdd\" or \"floppy\" or \"iso\".\n"); - MSG_Add("PROGRAM_IMGMOUNT_FORMAT_UNSUPPORTED","Format \"%s\" is unsupported. Specify \"fat\" or \"iso\" or \"none\".\n"); - MSG_Add("PROGRAM_IMGMOUNT_SPECIFY_FILE","Must specify image file(s) to mount.\n"); - MSG_Add("PROGRAM_IMGMOUNT_FILE_NOT_FOUND","Image file not found.\n"); - MSG_Add("PROGRAM_IMGMOUNT_DEFAULT_NOT_FOUND","Image file not found: IMGMAKE.IMG.\n"); - MSG_Add("PROGRAM_IMGMOUNT_MOUNT","To mount directories, use the \033[34;1mMOUNT\033[0m command, not the \033[34;1mIMGMOUNT\033[0m command.\n"); - MSG_Add("PROGRAM_IMGMOUNT_ALREADY_MOUNTED","Drive already mounted at that letter.\n"); - MSG_Add("PROGRAM_IMGMOUNT_ALREADY_MOUNTED_NUMBER","Drive number %d already mounted.\n"); - MSG_Add("PROGRAM_IMGMOUNT_CANT_CREATE","Cannot create drive from file.\n"); - MSG_Add("PROGRAM_IMGMOUNT_CANT_CREATE_PHYSFS","Cannot create PhysFS drive.\n"); - MSG_Add("PROGRAM_IMGMOUNT_MOUNT_NUMBER","Drive number %d mounted as %s\n"); - MSG_Add("PROGRAM_IMGMOUNT_NON_LOCAL_DRIVE", "The image must be on a host, local or network drive.\n"); - MSG_Add("PROGRAM_IMGMOUNT_MULTIPLE_NON_CUEISO_FILES", "Using multiple files is only supported for cue/iso images.\n"); - - MSG_Add("PROGRAM_IMGMOUNT_HELP", - "Mounts floppy, hard drive and optical disc images.\n" - "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m \033[36;1mfile\033[0m [-ro] [-t floppy] [-fs fat] [-size ss,s,h,c]\n" - "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m \033[36;1mfile\033[0m [-ro] [-t hdd] [-fs fat] [-size ss,s,h,c] [-ide controller]\n" - "\033[32;1mIMGMOUNT\033[0m \033[37;1mdriveNum\033[0m \033[36;1mfile\033[0m [-ro] [-fs none] [-size ss,s,h,c] [-reservecyl #]\n" - "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m \033[36;1mfile\033[0m [-t iso] [-fs iso]\n" - "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m [-t floppy] -bootcd cdDrive (or -el-torito cdDrive)\n" - "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m -t ram -size size\n" - "\033[32;1mIMGMOUNT\033[0m -u \033[37;1mdrive|driveNum\033[0m (or \033[32;1mIMGMOUNT\033[0m \033[37;1mdrive|driveNum\033[0m \033[36;1mfile\033[0m [options] -u)\n" - " \033[37;1mdrive\033[0m Drive letter to mount the image at.\n" - " \033[37;1mdriveNum\033[0m Drive number to mount, where 0-1 are FDDs, 2-5 are HDDs.\n" - " \033[36;1mfile\033[0m Image filename(s), or \033[33;1mIMGMAKE.IMG\033[0m if not specified.\n" - " -t iso Image type is optical disc iso or cue / bin image.\n" - " -t hdd|floppy|ram Image type is hard disk (inc. VHD/HDI)|floppy|RAM drive.\n" - " -fs iso Filesystem is ISO 9660 (auto-assumed for .iso/.cue files).\n" - " -fs fat Filesystem is FAT - FAT12, FAT16 and FAT32 are supported.\n" - " -fs none Do not detect filesystem (auto-assumed for drive numbers).\n" - " -reservecyl # Report # number of cylinders less than actual in BIOS.\n" - " -ide controller Specify IDE controller (1m, 1s, 2m, 2s) to mount drive.\n" - " -size size|ss,s,h,c Specify the size in KB, or sector size and CHS geometry.\n" - " -bootcd cdDrive Specify the CD drive to load the bootable floppy from.\n" - " -o partidx=# Specify a hard disk partition number to mount as drive.\n" - " -ro Mount image(s) read-only (or leading ':' for read-only).\n" - " -u Unmount the drive or drive number.\n" - " \033[32;1m-examples Show some usage examples.\033[0m" - ); - MSG_Add("PROGRAM_IMGMOUNT_EXAMPLE", - "Some usage examples of IMGMOUNT:\n\n" - " \033[32;1mIMGMOUNT\033[0m - list mounted FAT/ISO drives & drive numbers\n" - " \033[32;1mIMGMOUNT C\033[0m - mount hard disk image \033[33;1mIMGMAKE.IMG\033[0m as C:\n" -#ifdef WIN32 - " \033[32;1mIMGMOUNT C c:\\image.img\033[0m - mount hard disk image c:\\image.img as C:\n" - " \033[32;1mIMGMOUNT D c:\\files\\game.iso\033[0m - mount CD image c:\\files\\game.iso as D:\n" -#else - " \033[32;1mIMGMOUNT C ~/image.img\033[0m - mount hard disk image ~/image.img as C:\n" - " \033[32;1mIMGMOUNT D ~/files/game.iso\033[0m - mount CD image ~/files/game.iso as D:\n" -#endif - " \033[32;1mIMGMOUNT D cdaudio.cue\033[0m - mount cue file of a cue/bin pair as CD drive\n" - " \033[32;1mIMGMOUNT 0 dos.ima\033[0m - mount floppy image dos.ima as drive number 0\n" - " (\033[33;1mBOOT A:\033[0m will boot from drive if bootable)\n" - " \033[32;1mIMGMOUNT A -ro dos.ima\033[0m - mount floppy image dos.ima as A: read-only\n" - " \033[32;1mIMGMOUNT A :dsk1.img dsk2.img\033[0m - mount floppy images dsk1.img and dsk2.img as\n" - " A:, swappable via menu item \"Swap floppy\",\n" - " with dsk1.img read-only (but not dsk2.img)\n" - " \033[32;1mIMGMOUNT A -bootcd D\033[0m - mount bootable floppy A: from CD drive D:\n" - " \033[32;1mIMGMOUNT C -t ram -size 10000\033[0m - mount hard drive C: as a 10MB RAM drive\n" - " \033[32;1mIMGMOUNT D d.img -o partidx=4\033[0m - mount 1st logical partition of d.img as D:\n" - " \033[32;1mIMGMOUNT C disk.img -u\033[0m - force mount hard disk image disk.img as C:,\n" - " auto-unmount drive beforehand if necessary\n" - " \033[32;1mIMGMOUNT A -u\033[0m - unmount previously-mounted drive A:\n" - ); - MSG_Add("PROGRAM_IMGMAKE_SYNTAX", - "Creates floppy or hard disk images.\n" - "Usage: \033[34;1mIMGMAKE [file] [-t type] [[-size size] | [-chs geometry]] [-spc] [-nofs]\033[0m\n" - " \033[34;1m[-bat] [-fat] [-fatcopies] [-rootdir] [-force]" -#ifdef WIN32 - " [-source source] [-retries #]" -#endif - "\033[0m\n" - " file: Image file to create (or \033[33;1mIMGMAKE.IMG\033[0m if not set) - \033[31;1mpath on the host\033[0m\n" - " -t: Type of image.\n" - " \033[33;1mFloppy disk templates\033[0m (names resolve to floppy sizes in KB or fd=fd_1440):\n" - " fd_160 fd_180 fd_200 fd_320 fd_360 fd_400 fd_720 fd_1200 fd_1440 fd_2880\n" - " \033[33;1mHard disk templates:\033[0m\n" - " hd_250: 250MB, hd_520: 520MB, hd_1gig: 1GB, hd_2gig: 2GB, hd_4gig: 4GB,\n" - " hd_8gig: 8GB, hd_st251: 40MB, hd_st225: 20MB (geometry from old drives)\n" - " \033[33;1mCustom hard disks:\033[0m hd vhd (requires -size or -chs)\n" - " -size: Size of a custom hard disk image in MB (vhd: up to 2088960).\n" - " -chs: Disk geometry in cylinders(1-1023),heads(1-255),sectors(1-63).\n" - " -nofs: Add this parameter if a blank image should be created.\n" - " -force: Overwrite existing image file. -chs / -lba: Choose C/H/S or LBA.\n" - " -bat: Create a .bat file with the IMGMOUNT command required for this image.\n" - " -fat: Type (12, 16, or 32). -fatcopies: FAT table copies.\n" - " -spc: Sectors per cluster (must be power of 2). -label Drive label.\n" - " -rootdir: Root directory entries. -partofs: Start of hd partition.\n" - " -align: Align filesystem structures. In sectors, or add 'K' suffix for KB.\n" -#ifdef WIN32 - " -source: drive letter - if specified the image is read from a floppy disk.\n" - " -retries: how often to retry when attempting to read a bad floppy disk(1-99).\n" -#endif - " \033[32;1m-examples: Show some usage examples.\033[0m" - ); - MSG_Add("PROGRAM_IMGMAKE_EXAMPLE", - "Some usage examples of IMGMAKE:\n\n" - " \033[32;1mIMGMAKE -t fd\033[0m - create a 1.44MB floppy image \033[33;1mIMGMAKE.IMG\033[0m\n" - " \033[32;1mIMGMAKE -t fd_1440 -force\033[0m - force to create a floppy image \033[33;1mIMGMAKE.IMG\033[0m\n" - " \033[32;1mIMGMAKE dos.img -t fd_2880\033[0m - create a 2.88MB floppy image named dos.img\n" - " \033[32;1mIMGMAKE new.vhd -t vhd -size 520\033[0m- create a 520MB Dynamic VHD named new.vhd\n" -#ifdef WIN32 - " \033[32;1mIMGMAKE c:\\disk.img -t hd -size 50\033[0m - create a 50MB HDD image c:\\disk.img\n" - " \033[32;1mIMGMAKE c:\\disk.img -t hd_520 -nofs\033[0m - create a 520MB blank HDD image\n" - " \033[32;1mIMGMAKE c:\\disk.img -t hd_2gig -fat 32\033[0m - create a 2GB FAT32 HDD image\n" - " \033[32;1mIMGMAKE c:\\disk.img -t hd -chs 130,2,17\033[0m - create a HDD image of specified CHS\n" - " \033[32;1mIMGMAKE c:\\disk.img -source a\033[0m - read image from physical drive A:\n" -#else - " \033[32;1mIMGMAKE ~/disk.img -t hd -size 50\033[0m - create a 50MB HDD image ~/disk.img\n" - " \033[32;1mIMGMAKE ~/disk.img -t hd_520 -nofs\033[0m - create a 520MB blank HDD image\n" - " \033[32;1mIMGMAKE ~/disk.img -t hd_2gig -fat 32\033[0m - create a 2GB FAT32 HDD image\n" - " \033[32;1mIMGMAKE ~/disk.img -t hd -chs 130,2,17\033[0m - create a HDD image of specified CHS\n" -#endif - ); - -#ifdef WIN32 - MSG_Add("PROGRAM_IMGMAKE_FLREAD", - "Disk geometry: %d Cylinders, %d Heads, %d Sectors, %d Kilobytes\n\n"); - MSG_Add("PROGRAM_IMGMAKE_FLREAD2", - "%s =good, %s =good after retries, ! =CRC error, x =sector not found, ? =unknown\n\n"); -#endif - MSG_Add("PROGRAM_IMGMAKE_FILE_EXISTS","The file \"%s\" already exists. You can specify \"-force\" to overwrite.\n"); - MSG_Add("PROGRAM_IMGMAKE_CANNOT_WRITE","The file \"%s\" cannot be opened for writing.\n"); - MSG_Add("PROGRAM_IMGMAKE_NOT_ENOUGH_SPACE","Not enough space available for the image file. Need %llu bytes.\n"); - MSG_Add("PROGRAM_IMGMAKE_PRINT_CHS","Creating image file \"%s\" with %u cylinders, %u heads and %u sectors\n"); - MSG_Add("PROGRAM_IMGMAKE_CANT_READ_FLOPPY","\n\nUnable to read floppy."); - MSG_Add("PROGRAM_IMGMAKE_BADSIZE","Wrong -size or -chs arguments.\n"); - - MSG_Add("PROGRAM_KEYB_INFO","Codepage %i has been loaded\n"); - MSG_Add("PROGRAM_KEYB_INFO_LAYOUT","Codepage %i has been loaded for layout %s\n"); - MSG_Add("PROGRAM_KEYB_SHOWHELP","Configures a keyboard for a specific language.\n\n" - "Usage: \033[32;1mKEYB\033[0m [keyboard layout ID [codepage number [codepage file]]]\n" - " layout ID Name of layout or keyboard file (.kl) to load\n" - " codepage number Number of codepage to load\n" - " codepage file .cpi/.cpx file including specified codepage information\n" - " (.kl, .cpi/.cpx files shall be placed under the directory where dosbox-x\n" - " executable exists.)\n\n" - "Some examples:\n" - " \033[32;1mKEYB\033[0m Display currently loaded codepage.\n" - " \033[32;1mKEYB sp\033[0m Load the Spanish (SP) layout, use an appropriate codepage.\n" - " \033[32;1mKEYB sp 850\033[0m Load the Spanish (SP) layout, use codepage 850.\n" - " \033[32;1mKEYB sp 850 mycp.cpi\033[0m Same as above, but use file mycp.cpi.\n" - " \033[32;1mKEYB sp_mod 850\033[0m Load keyboard layout from sp_mod.kl, use codepage 850.\n"); - MSG_Add("PROGRAM_KEYB_NOERROR","Keyboard layout %s loaded for codepage %i\n"); - MSG_Add("PROGRAM_KEYB_FILENOTFOUND","Keyboard file %s not found (or not a valid ID)\n\n"); - MSG_Add("PROGRAM_KEYB_INVALIDFILE","Keyboard file %s invalid\n"); - MSG_Add("PROGRAM_KEYB_LAYOUTNOTFOUND","No layout in %s for codepage %i\n"); - MSG_Add("PROGRAM_KEYB_INVCPFILE","None or invalid codepage file for layout %s\n\n"); - MSG_Add("INT21_6523_YESNO_CHARS", "yn"); - MSG_Add("PROGRAM_LABEL_HELP", "Creates, changes, or deletes the volume label of a drive.\n\nLABEL [drive:][label]\n\n [drive:]\tSpecifies the drive letter\n [label]\tSpecifies the volume label\n"); - MSG_Add("PROGRAM_LABEL_DELETE", "Delete the volume label (Y/N)? "); - MSG_Add("PROGRAM_LABEL_TOOLONG", "Label is too long (more than 11 characters).\n"); - MSG_Add("PROGRAM_LABEL_BADCHARS", "Label has invalid characters.\n"); - MSG_Add("PROGRAM_LABEL_VOLUMEIS", "Volume in drive %c is %s\n"); - MSG_Add("PROGRAM_LABEL_NOLABEL", "Volume in drive %c has no label\n"); - MSG_Add("PROGRAM_MODE_USAGE","Configures system devices.\n\n" - "\033[34;1mMODE\033[0m display-type :display-type codes are " - "\033[1mCO80\033[0m, \033[1mBW80\033[0m, \033[1mCO40\033[0m, \033[1mBW40\033[0m, or \033[1mMONO\033[0m\n" - "\033[34;1mMODE CON COLS=\033[0mc \033[34;1mLINES=\033[0mn :columns and lines, c=80 or 132, n=25, 43, 50, or 60\n" - "\033[34;1mMODE CON RATE=\033[0mr \033[34;1mDELAY=\033[0md :typematic rates, r=1-32 (32=fastest), d=1-4 (1=lowest)\n"); - MSG_Add("PROGRAM_MODE_INVALID_PARAMETERS","Invalid parameter(s).\n"); - MSG_Add("PROGRAM_PORT_INVALID_NUMBER","Must specify a port number between 1 and 9.\n"); - MSG_Add("PROGRAM_VHDMAKE_WRITERR", "Could not write to new VHD image \"%s\", aborting.\n"); - MSG_Add("PROGRAM_VHDMAKE_REMOVEERR", "Could not erase file \"%s\"\n"); - MSG_Add("PROGRAM_VHDMAKE_RENAME", "You'll have to manually rename the newly created VHD image.\n"); - MSG_Add("PROGRAM_VHDMAKE_SUCCESS", "New VHD image successfully created. You can mount it with \033[34;1mIMGMOUNT\033[0m.\n"); - MSG_Add("PROGRAM_VHDMAKE_ERROPEN", "Error, could not open image file \"%s\".\n"); - MSG_Add("PROGRAM_VHDMAKE_BADSIZE", "Bad VHD size specified, aborting!\n"); - MSG_Add("PROGRAM_VHDMAKE_FNEEDED", "A pre-existing VHD image can't be silently overwritten without -f option!\n"); - MSG_Add("PROGRAM_VHDMAKE_BADPARENT", "The parent VHD image \"%s\" can't be opened for linking, aborting!\n"); - MSG_Add("PROGRAM_VHDMAKE_NOINFO", "Couldn't query info for \"%s\".\n"); - MSG_Add("PROGRAM_VHDMAKE_BLOCKSTATS", " with %d/%d blocks allocated.\n"); - MSG_Add("PROGRAM_VHDMAKE_INFO", "VHD \"%s\" type is %s.\nIts virtual size is %.02f MB"); - MSG_Add("PROGRAM_VHDMAKE_CANTMERGE", "%s is not a Differencing disk, can't merge!\n"); - MSG_Add("PROGRAM_VHDMAKE_MERGEREPORT", "%d sectors in %d blocks from \"%s\" merged into \"%s\".\n"); - MSG_Add("PROGRAM_VHDMAKE_MERGENODELETE", "Couldn't remove snapshot \"%s\", you'll have to do it yourself!"); - MSG_Add("PROGRAM_VHDMAKE_MERGEOKDELETE", "Snapshot VHD merged and deleted.\n"); - MSG_Add("PROGRAM_VHDMAKE_MERGEFAILED", "Failure while merging, aborted!\n"); - MSG_Add("PROGRAM_VHDMAKE_MERGEWARNCORRUPTION", " Parent \"%s\" contents could be corrupted!\n"); - MSG_Add("PROGRAM_VHDMAKE_ABSPATH", "Warning: an absolute path to parent prevents portability.\nPlease prefer a path relative to the differencing image file!\n"); - MSG_Add("PROGRAM_VHDMAKE_HELP", - "Creates Dynamic or Differencing VHD images, converts raw images into Fixed VHD,\n" - "shows information about VHD images and merges them.\n" - "\033[32;1mVHDMAKE\033[0m [-f] new.vhd size[BKMGT]\n" - "\033[32;1mVHDMAKE\033[0m \033[34;1m-convert\033[0m raw.hdd new.vhd\n" - "\033[32;1mVHDMAKE\033[0m [-f] \033[34;1m-link\033[0m parent.vhd new.vhd\n" - "\033[32;1mVHDMAKE\033[0m \033[34;1m-merge\033[0m delta.vhd\n" - "\033[32;1mVHDMAKE\033[0m \033[34;1m-info\033[0m a.vhd\n" - " -c | -convert convert a raw hd image to Fixed VHD, renaming it to new.vhd\n" - " -l | -link create a new Differencing VHD new.vhd and link it to the\n" - " pre-existing parent image parent.vhd\n" - " -f | -force force overwriting a pre-existing image file\n" - " -i | -info show useful information about a.vhd image\n" - " -m | -merge merge differencing delta.vhd to its parent\n" - " new.vhd name of the new Dynamic VHD image to create\n" - " size disk size (eventually with size unit, Bytes is implicit)\n" - "When converting a raw disk image to Fixed VHD, it has to be partitioned with\n" - "MBR scheme and formatted with FAT format.\n" - "When creating a Dynamic VHD, its size must range from 3 MB to 2040 GB.\n" - "The Dynamic VHD created is not partitioned nor formatted: to directly mount to\n" - "a drive letter with \033[34;1mIMGMOUNT\033[0m, please consider using \033[34;1mIMGMAKE\033[0m instead.\n" - "A merged snapshot VHD is automatically deleted if merge is successful.\n"); - - const Section_prop * dos_section=static_cast(control->GetSection("dos")); - hidefiles = dos_section->Get_string("drive z hide files"); - - /*regular setup*/ - Add_VFiles(false); - -#if WIN32 - if (dos_section->Get_bool("automount drive directories")) { - Add_Existing_Drive_Directories(); - } -#endif -} + + void MIXER_ProgramStart(Program * * make); + void REDOS_ProgramStart(Program * * make); + void SHELL_ProgramStart(Program * * make); + void SERIAL_ProgramStart(Program * * make); + void CONFIG_ProgramStart(Program * * make); + void IPXNET_ProgramStart(Program * * make); + void A20GATE_ProgramStart(Program * * make); + void CGASNOW_ProgramStart(Program * * make); + void PARALLEL_ProgramStart(Program * * make); + void PC98UTIL_ProgramStart(Program * * make); + void VESAMOED_ProgramStart(Program * * make); + void VFRCRATE_ProgramStart(Program * * make); + + #if defined C_DEBUG + class NMITEST : public Program { + public: + void Run(void) override { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Generates a non-maskable interrupt (NMI).\n\nNMITEST\n\nNote: This is a debugging tool to test if the interrupt handler works properly.\n"); + return; + } + WriteOut("Generating a non-maskable interrupt (NMI)...\n"); + CPU_Raise_NMI(); + } + }; + + static void NMITEST_ProgramStart(Program * * make) { + *make=new NMITEST; + } + #endif + + class CAPMOUSE : public Program + { + public: + void Run() override + { + auto val = 0; + auto tmp = std::string(""); + + if(cmd->GetCount() == 0) + val = -1; + else if(cmd->FindExist("/?", true)) + val = 0; + else if(cmd->FindExist("/C", false)) + val = 1; + else if(cmd->FindExist("/R", false)) + val = 2; + + auto cap = false; + switch(val) + { + case -1: + case 2: + break; + case 1: + cap = true; + break; + case 0: + default: + WriteOut("Captures or releases the mouse inside DOSBox-X.\n\n"); + WriteOut("CAPMOUSE [/C|/R]\n"); + WriteOut(" /C Capture the mouse\n"); + WriteOut(" /R Release the mouse\n"); + return; + } + + if (val>-1) { + CaptureMouseNotify(!cap); + GFX_CaptureMouse(cap); + } + std::string msg; + msg.append("Mouse "); + if (val==-1) msg.append("is currently "); + msg.append(Mouse_IsLocked() ? "captured" : "released"); + msg.append(".\n"); + WriteOut(msg.c_str()); + } + }; + + void CAPMOUSE_ProgramStart(Program** make) + { + *make = new CAPMOUSE; + } + + class LABEL : public Program + { + public: + void Help() { + WriteOut(MSG_Get("PROGRAM_LABEL_HELP")); + } + void Run() override + { + /* MS-DOS behavior: If no label provided at the command line, prompt for one. + * + * LABEL [drive:] [label] + * + * No options are supported in MS-DOS, and the label can have spaces in it. + * This is valid, apparently: + * + * LABEL H E L L O + * + * Will set the volume label to "H E L L O" + * + * Label /? will print help. + */ + std::string label; + uint8_t drive = DOS_GetDefaultDrive(); + const char *raw = cmd->GetRawCmdline().c_str(); + + /* skip space */ + while (*raw == ' ') raw++; + + /* options */ + if (raw[0] == '/') { + raw++; + if (raw[0] == '?') { + Help(); + return; + } + } + + /* is the next part a drive letter? */ + if (raw[0] != 0 && raw[1] != 0) { + if (isalpha(raw[0]) && raw[1] == ':') { + drive = tolower(raw[0]) - 'a'; + raw += 2; + while (*raw == ' ') raw++; + } + } + + /* then the label. MS-DOS behavior is to treat the rest of the command line, spaces and all, as the label */ + if (*raw != 0) { + label = raw; + } + + /* if the label is longer than 11 chars or contains a dot, MS-DOS will reject it and then prompt for another label */ + if (label.length() > 11) { + WriteOut(MSG_Get("PROGRAM_LABEL_TOOLONG")); + label.clear(); + } + else if (label.find_first_of(".:/\\") != std::string::npos) { + WriteOut(MSG_Get("PROGRAM_LABEL_BADCHARS")); + label.clear(); + } + + /* if no label provided, MS-DOS will display the current label and serial number and prompt the user to type in a new label. */ + if (label.empty()) { + std::string clabel = Drives[drive]->GetLabel(); + + if (!clabel.empty()) + { + printf("Volume is: %s\n", clabel.c_str()); + WriteOut(MSG_Get("PROGRAM_LABEL_VOLUMEIS"),drive+'A',clabel.c_str()); + } + else + WriteOut(MSG_Get("PROGRAM_LABEL_NOLABEL"),drive+'A'); + } + + /* If no label is provided, MS-DOS will prompt the user whether to delete the label. */ + if (label.empty()) { + uint8_t c,ans=0; + uint16_t s; + + /* It does not make sense to say drive C: has no label, then prompt to delete it */ + if ((*Drives[drive]->GetLabel()) == 0) return; + + inshell = true; + do { + WriteOut(MSG_Get("PROGRAM_LABEL_DELETE")); + s = 1; + DOS_ReadFile(STDIN,&c,&s); + WriteOut("\n"); + if (s != 1 || c == 3) {inshell=false;return;} + ans = uint8_t(tolower(char(c))); + } while (!(ans == MSG_Get("INT21_6523_YESNO_CHARS")[0] || ans == MSG_Get("INT21_6523_YESNO_CHARS")[1])); + inshell = false; + + if (ans != MSG_Get("INT21_6523_YESNO_CHARS")[0]) return; + } + + /* delete then create the label */ + Drives[drive]->SetLabel("",false,true); + Drives[drive]->SetLabel(label.c_str(),false,true); + } + }; + + void LABEL_ProgramStart(Program** make) + { + *make = new LABEL; + } + + std::vector MAPPER_GetEventNames(const std::string &prefix); + void MAPPER_AutoType(std::vector &sequence, const uint32_t wait_ms, const uint32_t pacing_ms, bool choice); + + class AUTOTYPE : public Program { + public: + void Run() override; + + private: + void PrintUsage(); + void PrintKeys(); + bool ReadDoubleArg(const std::string &name, + const char *flag, + const double &def_value, + const double &min_value, + const double &max_value, + double &value); + }; + + void AUTOTYPE_ProgramStart(Program **make); + + void AUTOTYPE::PrintUsage() + { + constexpr const char *msg = + "Performs scripted keyboard entry into a running DOS program.\n\n" + "AUTOTYPE [-list] [-w WAIT] [-p PACE] button_1 [button_2 [...]]\n\n" + "Where:\n" + " -list: prints all available button names.\n" + " -w WAIT: seconds before typing begins. Two second default; max of 30.\n" + " -p PACE: seconds between each keystroke. Half-second default; max of 10.\n\n" + " The sequence is comprised of one or more space-separated buttons.\n" + " Autotyping begins after WAIT seconds, and each button is entered\n" + " every PACE seconds. The , character inserts an extra PACE delay.\n\n" + "Some examples:\n" + " \033[32;1mAUTOTYPE -w 1 -p 0.3 up enter , right enter\033[0m\n" + " \033[32;1mAUTOTYPE -p 0.2 f1 kp_8 , , enter\033[0m\n" + " \033[32;1mAUTOTYPE -w 1.3 esc enter , p l a y e r enter\033[0m\n"; + resetcolor = true; + WriteOut(msg); + } + + // Prints the key-names for the mapper's currently-bound events. + void AUTOTYPE::PrintKeys() + { + const std::vector names = MAPPER_GetEventNames("key_"); + + // Keep track of the longest key name + size_t max_length = 0; + for (const auto &name : names) + max_length = (std::max)(name.length(), max_length); + + // Sanity check to avoid dividing by 0 + if (!max_length) { + WriteOut_NoParsing( + "AUTOTYPE: The mapper has no key bindings\n"); + return; + } + + // Setup our rows and columns + const size_t wrap_width = 72; // comfortable columns not pushed to the edge + const size_t columns = wrap_width / max_length; + const size_t rows = ceil_udivide(names.size(), columns); + + // Build the string output by rows and columns + auto name = names.begin(); + for (size_t row = 0; row < rows; ++row) { + for (size_t i = row; i < names.size(); i += rows) + WriteOut(" %-*s", static_cast(max_length), (name[i].size()==1&&name[i][0]>='a'&&name[i][0]<='z'?name[i]+" ("+std::string(1, toupper(name[i][0]))+")":name[i]).c_str()); + WriteOut_NoParsing("\n"); + } + } + + /* + * Converts a string to a finite number (such as float or double). + * Returns the number or quiet_NaN, if it could not be parsed. + * This function does not attempt to capture exceptions that may + * be thrown from std::stod(...) + */ + template + T to_finite(const std::string& input) { + // Defensively set NaN from the get-go + T result = std::numeric_limits::quiet_NaN(); + size_t bytes_read = 0; + try { + const double interim = std::stod(input, &bytes_read); + if (!input.empty() && bytes_read == input.size()) + result = static_cast(interim); + } + // Capture expected exceptions stod may throw + catch (std::invalid_argument& e) { (void)e; } + catch (std::out_of_range& e) { (void)e; } + return result; + } + + /* + * Reads a floating point argument from command line, where: + * - name is a human description for the flag, ie: DELAY + * - flag is the command-line flag, ie: -d or -delay + * - default is the default value if the flag doesn't exist + * - value will be populated with the default or provided value + * + * Returns: + * true if 'value' is set to the default or read from the arg. + * false if the argument was used but could not be parsed. + */ + bool AUTOTYPE::ReadDoubleArg(const std::string &name, + const char *flag, + const double &def_value, + const double &min_value, + const double &max_value, + double &value) + { + bool result = false; + std::string str_value; + + // Is the user trying to set this flag? + if (cmd->FindString(flag, str_value, true)) { + // Can the user's value be parsed? + const double user_value = to_finite(str_value); + if (isfinite(user_value)) { + result = true; + + // Clamp the user's value if needed + value = clamp(user_value, min_value, max_value); + + // Inform them if we had to clamp their value + if (fabs(user_value - value) > + std::numeric_limits::epsilon()) + WriteOut("AUTOTYPE: bounding %s value of %.2f " + "to %.2f\n", + name.c_str(), user_value, value); + + } else { // Otherwise we couldn't parse their value + WriteOut("AUTOTYPE: %s value '%s' is not a valid " + "floating point number\n", + name.c_str(), str_value.c_str()); + } + } else { // Otherwise they haven't passed this flag + value = def_value; + result = true; + } + return result; + } + + void AUTOTYPE::Run() + { + // Hack To allow long commandlines + ChangeToLongCmd(); + + // Usage + if (!cmd->GetCount()||(cmd->GetCount()==1 && (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)))) { + PrintUsage(); + return; + } + + // Print available keys + if (cmd->FindExist("-list", false) || cmd->FindExist("/list", false)) { + PrintKeys(); + return; + } + + // Get the wait delay in milliseconds + double wait_s; + constexpr double def_wait_s = 2.0; + constexpr double min_wait_s = 0.0; + constexpr double max_wait_s = 30.0; + if (!ReadDoubleArg("WAIT", "-w", def_wait_s, min_wait_s, max_wait_s, wait_s)) + return; + const auto wait_ms = static_cast(wait_s * 1000); + + // Get the inter-key pacing in milliseconds + double pace_s; + constexpr double def_pace_s = 0.5; + constexpr double min_pace_s = 0.0; + constexpr double max_pace_s = 10.0; + if (!ReadDoubleArg("PACE", "-p", def_pace_s, min_pace_s, max_pace_s, pace_s)) + return; + const auto pace_ms = static_cast(pace_s * 1000); + + // Get the button sequence + std::vector sequence; + cmd->FillVector(sequence); + if (sequence.empty()) { + WriteOut_NoParsing("AUTOTYPE: button sequence is empty\n"); + return; + } + MAPPER_AutoType(sequence, wait_ms, pace_ms, false); + } + + void AUTOTYPE_ProgramStart(Program **make) + { + *make = new AUTOTYPE; + } + + class ADDKEY : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Generates artificial keypresses.\n\nADDKEY [pmsec] [key]\n\n" + "For example, the command below types \"dir\" followed by ENTER after 1 second:\n\nADDKEY p1000 d i r enter\n\n" + "You could also try AUTOTYPE command instead of this command to perform\nscripted keyboard entry into a running DOS program.\n"; + WriteOut(msg); + } + }; + + void ADDKEY::Run() + { + // Hack To allow long commandlines + ChangeToLongCmd(); + + // Usage + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + char *args=(char *)cmd->GetRawCmdline().c_str(); + args=trim(args); + DOS_Shell temp; + temp.CMD_ADDKEY(args); + } + + static void ADDKEY_ProgramStart(Program * * make) { + *make=new ADDKEY; + } + + class LS : public Program { + public: + void Run(void) override; + }; + + void LS::Run() + { + std::string tmp = ""; + cmd->GetStringRemain(tmp); + char args[CMD_MAXLINE]; + strcpy(args, tmp.c_str()); + DOS_Shell temp; + temp.CMD_LS(args); + } + + static void LS_ProgramStart(Program * * make) { + *make=new LS; + } + + class CHOICE : public Program { + public: + void Run(void) override; + }; + + void CHOICE::Run() + { + std::string tmp = ""; + cmd->GetStringRemain(tmp); + char args[CMD_MAXLINE]; + strcpy(args, tmp.c_str()); + DOS_Shell temp; + temp.CMD_CHOICE(args); + result_errorcode = dos.return_code; + } + + void CHOICE_ProgramStart(Program **make) + { + *make = new CHOICE; + } + + class COUNTRY : public Program { + public: + void Run(void) override; + }; + + void COUNTRY::Run() + { + char *args=(char *)cmd->GetRawCmdline().c_str(); + args=trim(args); + DOS_Shell temp; + temp.CMD_COUNTRY(args); + } + + static void COUNTRY_ProgramStart(Program * * make) { + *make=new COUNTRY; + } + + #ifdef C_ICONV + class UTF8 : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Converts UTF-8 text to view in the current code page.\n\n" + "UTF8 < [drive:][path]filename\ncommand-name | UTF8\n"; + WriteOut(msg); + } + }; + + void UTF8::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + if (usecon) { + WriteOut("No input text found.\n"); + return; + } + // int cp=dos.loaded_codepage; /* unused */ + char target[11] = "CP437"; + if (dos.loaded_codepage==808) strcpy(target, "CP866"); + else if (dos.loaded_codepage==859) strcpy(target, "CP858"); + else if (dos.loaded_codepage==867) strcpy(target, "CP862"); + else if (dos.loaded_codepage==872) strcpy(target, "CP855"); + else if (dos.loaded_codepage==951 && !uao) strcpy(target, "BIG5HKSCS"); + else if (dos.loaded_codepage==951) strcpy(target, "CP950"); + else if (!(customcp && dos.loaded_codepage==customcp) && !(altcp && dos.loaded_codepage==altcp)) sprintf(target, "CP%d", dos.loaded_codepage); + _Iconv *x = _Iconv::create("UTF-8"); + _Iconv *fx = _Iconv::create(target); + if (x == NULL || fx == NULL) { + WriteOut("Invalid code page for text conversion.\n"); + return; + } + test_string dst; + std::string text=""; + char temp[4096]; + morelen=true; + bool first=true; + uint8_t c;uint16_t m=1; + while (true) { + DOS_ReadFile (STDIN,&c,&m); + if (m) text+=std::string(1, c); + if (m && first && text.size() == 2 && (((uint8_t)text[0] == 0xFE && (uint8_t)text[1] == 0xFF) || ((uint8_t)text[0] == 0xFF && (uint8_t)text[1] == 0xFE))) { + WriteOut("The input text is UTF-16.\n"); + break; + } + if (m && first && text.size() == 3 && (uint8_t)text[0] == 0xEF && (uint8_t)text[1] == 0xBB && (uint8_t)text[2] == 0xBF) { + first=false; + text=""; + } else if (!m || c==0x1A || c==0xA || (text.size()>1 && (uint8_t)text[text.size()-2] == 0xD)) { + if (c!=0xA && text.size()>1 && (uint8_t)text[text.size()-2] == 0xD) text[text.size()-1] = 0xA; + if (CodePageHostToGuestUTF8(temp,text.c_str())) { + WriteOut_NoParsing(temp, true); + } else { + x->set_src(text.c_str()); + if ((customcp && dos.loaded_codepage==customcp) || (altcp && dos.loaded_codepage==altcp) || x->string_convert_dest(dst) < 0 || (text.size() && !fx->string_convert(dst).size())) { + WriteOut("An error occurred during text conversion.\n"); + morelen=false; + return; + } else + WriteOut_NoParsing(fx->string_convert(dst).c_str(), true); + } + first=false; + text=""; + if (!m||c==0x1A) break; + else if (c!=0xA) text+=std::string(1, c); + } + } + x->finish(); + morelen=false; + } + + static void UTF8_ProgramStart(Program * * make) { + *make=new UTF8; + } + + class UTF16 : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Converts UTF-16 text to view in the current code page.\n\n" + "UTF16 [/BE|/LE] < [drive:][path]filename\ncommand-name | UTF16 [/BE|/LE]\n\n" + " /BE Use UTF-16 Big Endian\n /LE Use UTF-16 Little Endian\n"; + WriteOut(msg); + } + }; + + void UTF16::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + if (usecon) { + WriteOut("No input text found.\n"); + return; + } + char target[11] = "CP437"; + if (dos.loaded_codepage==808) strcpy(target, "CP866"); + else if (dos.loaded_codepage==859) strcpy(target, "CP858"); + else if (dos.loaded_codepage==867) strcpy(target, "CP862"); + else if (dos.loaded_codepage==872) strcpy(target, "CP855"); + else if (dos.loaded_codepage==951 && !uao) strcpy(target, "BIG5HKSCS"); + else if (dos.loaded_codepage==951) strcpy(target, "CP950"); + else if (!(customcp && dos.loaded_codepage==customcp) && !(altcp && dos.loaded_codepage==altcp)) sprintf(target, "CP%d", dos.loaded_codepage); + uint8_t buf[3];uint16_t m=2; + DOS_ReadFile (STDIN,buf,&m); + if (m<2) { + if (m==1) WriteOut("An error occurred during text conversion.\n"); + return; + } + bool le=true; + if (cmd->FindExist("-BE", false) || cmd->FindExist("/BE", false)) + le=false; + else if (cmd->FindExist("-LE", false) || cmd->FindExist("/LE", false)) + le=true; + else if (buf[0] == 0xFE && buf[1]== 0xFF) + le=false; + else if (buf[0] == 0xFF && buf[1]== 0xFE) + le=true; + #if defined(MACOSX) + else + le=false; + #endif + _Iconv *x = _Iconv::create(target); + if (x == NULL) { + WriteOut("Invalid code page for text conversion.\n"); + return; + } + test_char dst; + test_char_t *wch; + test_char_t ch = 0; + std::wstring text=L""; + char temp[4096]; + unsigned int c=0; + morelen=true; + bool first=true; + while (true) { + if (!first || (buf[0] == 0xFE && buf[1]== 0xFF) || (buf[0] == 0xFF && buf[1]== 0xFE)) DOS_ReadFile (STDIN,buf,&m); + first=false; + if (m==1) { + WriteOut("An error occurred during text conversion.\n"); + break; + } else if (m==2) { + ch=buf[le?1:0]*0x100+buf[le?0:1]; + text+=ch; + c++; + } + if (!m || ch==0x1A || ch==0xA || (c>1 && text[c-2] == 0xD)) { + if (ch!=0xA && c>1 && text[c-2] == 0xD) {text[c-1] = 0xA;} + wch=new test_char_t[c+1]; + for (unsigned int i=0; iset_src(wch); + if ((customcp && dos.loaded_codepage==customcp) || (altcp && dos.loaded_codepage==altcp) || x->string_convert_dest(dst) < 0 || (c && !dst.size())) { + WriteOut("An error occurred during text conversion.\n"); + delete[] wch; + morelen=false; + return; + } else + WriteOut_NoParsing(dst.c_str(), true); + } + delete[] wch; + text=L""; + c=0; + if (!m||ch==0x1A) break; + else if (ch!=0xA) {text+=ch;c++;} + } + } + x->finish(); + morelen=false; + } + + static void UTF16_ProgramStart(Program * * make) { + *make=new UTF16; + } + #endif + + class VTEXT : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Changes V-text mode for the DOS/V emulation.\n\nVTEXT [mode]\n\n[mode] can be 0, 1, 2, for no V-text, V-text 1, and V-text 2 respectively.\n\nType VTEXT without a parameter to show the current V-text mode status.\n"; + WriteOut(msg); + } + }; + + void VTEXT::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + std::string tmp = ""; + cmd->GetStringRemain(tmp); + char args[CMD_MAXLINE]; + strcpy(args, tmp.c_str()); + DOS_Shell temp; + temp.CMD_VTEXT(args); + } + + static void VTEXT_ProgramStart(Program * * make) { + *make=new VTEXT; + } + + class DCGA : public Program { + public: + void Run(void) override; + }; + + void DCGA::Run() + { + uint16_t oldax=reg_ax; + reg_ax = 0x74; + CALLBACK_RunRealInt(0x10); + reg_ax = oldax; + } + + static void DCGA_ProgramStart(Program * * make) { + *make=new DCGA; + } + + class TEXT80X25 : public Program { + public: + void Run(void) override; + }; + + void TEXT80X25::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Changes to 80x25 text mode.\n"); + return; + } + clear_screen(); + setlines("line_80x25"); + show_prompt(); + } + + static void TEXT80X25_ProgramStart(Program * * make) { + *make=new TEXT80X25; + } + + class TEXT80X43 : public Program { + public: + void Run(void) override; + }; + + void TEXT80X43::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Changes to 80x43 text mode.\n"); + return; + } + clear_screen(); + setlines("line_80x43"); + show_prompt(); + } + + static void TEXT80X43_ProgramStart(Program * * make) { + *make=new TEXT80X43; + } + + class TEXT80X50 : public Program { + public: + void Run(void) override; + }; + + void TEXT80X50::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Changes to 80x50 text mode.\n"); + return; + } + clear_screen(); + setlines("line_80x50"); + show_prompt(); + } + + static void TEXT80X50_ProgramStart(Program * * make) { + *make=new TEXT80X50; + } + + class TEXT80X60 : public Program { + public: + void Run(void) override; + }; + + void TEXT80X60::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Changes to 80x60 text mode.\n"); + return; + } + clear_screen(); + setlines("line_80x60"); + show_prompt(); + } + + static void TEXT80X60_ProgramStart(Program * * make) { + *make=new TEXT80X60; + } + + class TEXT132X25 : public Program { + public: + void Run(void) override; + }; + + void TEXT132X25::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Changes to 132x25 text mode.\n"); + return; + } + clear_screen(); + setlines("line_132x25"); + show_prompt(); + } + + static void TEXT132X25_ProgramStart(Program * * make) { + *make=new TEXT132X25; + } + + class TEXT132X43 : public Program { + public: + void Run(void) override; + }; + + void TEXT132X43::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Changes to 132x43 text mode.\n"); + return; + } + clear_screen(); + setlines("line_132x43"); + show_prompt(); + } + + static void TEXT132X43_ProgramStart(Program * * make) { + *make=new TEXT132X43; + } + + class TEXT132X50 : public Program { + public: + void Run(void) override; + }; + + void TEXT132X50::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Changes to 132x50 text mode.\n"); + return; + } + clear_screen(); + setlines("line_132x50"); + show_prompt(); + } + + static void TEXT132X50_ProgramStart(Program * * make) { + *make=new TEXT132X50; + } + + class TEXT132X60 : public Program { + public: + void Run(void) override; + }; + + void TEXT132X60::Run() + { + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + WriteOut("Changes to 132x60 text mode.\n"); + return; + } + clear_screen(); + setlines("line_132x60"); + show_prompt(); + } + + static void TEXT132X60_ProgramStart(Program * * make) { + *make=new TEXT132X60; + } + + class HELP : public Program { + public: + void Run(void) override; + }; + + void HELP::Run() + { + std::string tmp = ""; + cmd->GetStringRemain(tmp); + char args[CMD_MAXLINE]; + strcpy(args, tmp.c_str()); + DOS_Shell temp; + temp.CMD_HELP(args); + } + + static void HELP_ProgramStart(Program * * make) { + *make=new HELP; + } + + class DELTREE : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Deletes a directory and all the subdirectories and files in it.\n\n" + "To delete one or more files and directories:\n" + "DELTREE [/Y] [drive:]path [[drive:]path[...]]\n\n" + " /Y Suppresses prompting to confirm you want to delete\n" + " the subdirectory.\n" + " [drive:]path Specifies the name of the directory you want to delete.\n\n" + "Note: Use DELTREE cautiously. Every file and subdirectory within the\n" + "specified directory will be deleted.\n"; + WriteOut(msg); + } + }; + + void DELTREE::Run() + { + // Hack To allow long commandlines + ChangeToLongCmd(); + + // Usage + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + char *args=(char *)cmd->GetRawCmdline().c_str(); + args=trim(args); + DOS_Shell temp; + temp.CMD_DELTREE(args); + } + + static void DELTREE_ProgramStart(Program * * make) { + *make=new DELTREE; + } + + class TREE : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Graphically displays the directory structure of a drive or path.\n\n" + "TREE [drive:][path] [/F] [/A]\n\n" + " /F Displays the names of the files in each directory.\n" + " /A Uses ASCII instead of extended characters.\n"; + WriteOut(msg); + } + }; + + void TREE::Run() + { + // Hack To allow long commandlines + ChangeToLongCmd(); + + // Usage + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + char *args=(char *)cmd->GetRawCmdline().c_str(); + args=trim(args); + DOS_Shell temp; + temp.CMD_TREE(args); + } + + static void TREE_ProgramStart(Program * * make) { + *make=new TREE; + } + + class TITLE : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Sets the window title for the DOSBox-X window.\n\n" + "TITLE [string]\n\n" + " string Specifies the title for the DOSBox-X window.\n"; + WriteOut(msg); + } + }; + + bool CodePageGuestToHostUTF8(char *d/*CROSS_LEN*/,const char *s/*CROSS_LEN*/); + + void TITLE::Run() + { + // Hack To allow long commandlines + ChangeToLongCmd(); + + // Usage + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + char *args=trim((char *)cmd->GetRawCmdline().c_str()); + char title[4096]; + if(CodePageGuestToHostUTF8(title, args)) { + dosbox_title=title; + } else { + dosbox_title=args; + } + SetVal("dosbox", "title", dosbox_title); + GFX_SetTitle(-1,-1,-1,false); + } + + static void TITLE_ProgramStart(Program * * make) { + *make=new TITLE; + } + + class VHDMAKE : public Program { + public: + void Run(void) override; + private: + const char* vhdTypes[5] = { "", "", "Fixed", "Dynamic", "Differencing" }; + uint64_t ssizetou64(const char* s_size); + void PrintUsage() { + const char* msg = MSG_Get("PROGRAM_VHDMAKE_HELP"); + WriteOut(msg); + } + }; + + // Converts a string disk size with unit into a 64-bit unsigned integer + uint64_t VHDMAKE::ssizetou64(const char* s_size) { + const char* sizes = "BKMGT"; + char* sd_size = _strdup(s_size); + char* last = sd_size + strlen(s_size) - 1; + char* c; + uint64_t size; + + if((c = strchr((char*)sizes, toupper(*last)))) { + *last = 0; + size = atoll(sd_size); + size <<= ((c - sizes) * 10); + } + else { + size = atoll(sd_size); + } + free(sd_size); + return size; + } + + void VHDMAKE::Run() + { + bool bOverwrite = false; + // bool bExists = false; /* unused */ + uint32_t ret; + char basename[256], filename[256]; + + // Hack To allow long commandlines + ChangeToLongCmd(); + + // Usage + if(cmd->FindExist("-?", false) || cmd->FindExist("/?", false) || cmd->GetCount() < 2) { + PrintUsage(); + return; + } + + if(cmd->FindExist("-f", true) || cmd->FindExist("-force", true)) + bOverwrite = true; + + if(cmd->FindExist("-i", true) || cmd->FindExist("-info", true)) { + if(cmd->GetCount() > 1) { + PrintUsage(); + return; + } + cmd->FindCommand(1, temp_line); + safe_strcpy(filename, temp_line.c_str()); // image to query + + imageDiskVHD::VHDInfo* info = NULL; + if(imageDiskVHD::GetInfo(filename, &info)) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_NOINFO"), filename); + return; + } + WriteOut(MSG_Get("PROGRAM_VHDMAKE_INFO"), filename, vhdTypes[(int)info->vhdType], info->vhdSizeMB); + if(info->vhdType != imageDiskVHD::VHD_TYPE_FIXED) + WriteOut(MSG_Get("PROGRAM_VHDMAKE_BLOCKSTATS"), info->allocatedBlocks, info->totalBlocks); + else + WriteOut(".\n"); + if(info->parentInfo != NULL) { + uint32_t index = 0; + imageDiskVHD::VHDInfo* p = info->parentInfo; + while(p != NULL) { + index++; + for(uint32_t i = 0; i < index; i++) WriteOut(" "); + WriteOut("child of \"%s\" (%s)", p->diskname.c_str(), vhdTypes[(int)p->vhdType]); + if (p->vhdType != imageDiskVHD::VHD_TYPE_FIXED) + WriteOut(MSG_Get("PROGRAM_VHDMAKE_BLOCKSTATS"), p->allocatedBlocks, p->totalBlocks); + else + WriteOut(".\n"); + p = p->parentInfo; + } + } + delete info; + return; + } + + if(cmd->FindExist("-m", true) || cmd->FindExist("-merge", true)) { + if(cmd->GetCount() > 1) { + PrintUsage(); + return; + } + cmd->FindCommand(1, temp_line); + safe_strcpy(basename, temp_line.c_str()); + imageDiskVHD* vhd; + if(imageDiskVHD::Open(basename, true, (imageDisk**)&vhd) != imageDiskVHD::OPEN_SUCCESS) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), basename); + return; + } + if(vhd->vhdType != imageDiskVHD::VHD_TYPE_DIFFERENCING) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_CANTMERGE"), basename); + delete vhd; + return; + } + imageDiskVHD::VHDInfo* info = new imageDiskVHD::VHDInfo; + if(vhd->GetInfo(info)) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_NOINFO"), basename); + return; + } + uint32_t totalSectorsMerged, totalBlocksUpdated; + std::string parentName = info->parentInfo->diskname; + if(vhd->MergeSnapshot(&totalSectorsMerged, &totalBlocksUpdated)) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGEREPORT"), totalSectorsMerged, totalBlocksUpdated, basename, parentName.c_str()); + delete vhd; + if(remove(basename)) + WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGENODELETE"), basename); + else + WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGEOKDELETE")); + } + else { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGEFAILED")); + if(totalSectorsMerged) + WriteOut(MSG_Get("PROGRAM_VHDMAKE_MERGEWARNCORRUPTION"), parentName.c_str()); + else + WriteOut("\n"); + } + delete info; + return; + } + + if(cmd->FindExist("-c", true) || cmd->FindExist("-convert", true)) { + if(cmd->GetCount() != 2) { + PrintUsage(); + return; + } + cmd->FindCommand(1, temp_line); + safe_strcpy(filename, temp_line.c_str()); // image to convert + FILE* f; + if(!(f = fopen(filename, "r"))) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), filename); + return; + } + fclose(f); + cmd->FindCommand(2, temp_line); + safe_strcpy(basename, temp_line.c_str()); // resulting VHD (after renaming) + if(_access(basename, 0) == 0) { + if(!bOverwrite) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_FNEEDED")); + return; + } + if(remove(basename)) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_REMOVEERR"), basename); + } + } + ret = imageDiskVHD::ConvertFixed(filename); + if(ret == imageDiskVHD::OPEN_SUCCESS) { + if (rename(filename, basename)) + WriteOut(MSG_Get("PROGRAM_VHDMAKE_RENAME")); + } + } + else if(cmd->FindExist("-l", true) || cmd->FindExist("-link", true)) { + if(cmd->GetCount() > 2) { + PrintUsage(); + return; + } + cmd->FindCommand(1, temp_line); + safe_strcpy(basename, temp_line.c_str()); + cmd->FindCommand(2, temp_line); + safe_strcpy(filename, temp_line.c_str()); + if(basename[1] == ':' || basename[0] == '/') + WriteOut(MSG_Get("PROGRAM_VHDMAKE_ABSPATH")); + if(! bOverwrite && _access(filename, 0) == 0) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_FNEEDED")); + return; + } + ret = imageDiskVHD::CreateDifferencing(filename, basename); + } + else { + if(cmd->GetCount() > 2) { + PrintUsage(); + return; + } + char size[16]; + cmd->FindCommand(1, temp_line); + safe_strcpy(filename, temp_line.c_str()); + cmd->FindCommand(2, temp_line); + safe_strcpy(size, temp_line.c_str()); + uint64_t vhd_size = ssizetou64(size); + if(!vhd_size || vhd_size < 3145728 || vhd_size > 2190433320960) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_BADSIZE")); + return; + } + if(!bOverwrite && _access(filename, 0) == 0) { + WriteOut(MSG_Get("PROGRAM_VHDMAKE_FNEEDED")); + return; + } + ret = imageDiskVHD::CreateDynamic(filename, vhd_size); + } + + switch(ret) { + case imageDiskVHD::UNSUPPORTED_SIZE: + WriteOut(MSG_Get("PROGRAM_VHDMAKE_BADSIZE")); + break; + case imageDiskVHD::ERROR_OPENING: + WriteOut(MSG_Get("PROGRAM_VHDMAKE_ERROPEN"), filename); + break; + case imageDiskVHD::ERROR_OPENING_PARENT: + WriteOut(MSG_Get("PROGRAM_VHDMAKE_BADPARENT"), filename); + break; + case imageDiskVHD::ERROR_WRITING: + WriteOut(MSG_Get("PROGRAM_VHDMAKE_WRITERR"), filename); + break; + case imageDiskVHD::OPEN_SUCCESS: + WriteOut(MSG_Get("PROGRAM_VHDMAKE_SUCCESS")); + break; + } + } + + + static void VHDMAKE_ProgramStart(Program * * make) { + *make=new VHDMAKE; + } + + class COLOR : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Sets the default console foreground and background colors.\n\n" + "COLOR [attr]\n\n" + " attr Specifies color attribute of console output\n\n" + "Color attributes are specified by TWO hex digits -- the first\n" + "corresponds to the background; the second to the foreground.\n" + "Each digit can be any of the following values:\n\n" + " 0 = Black 8 = Gray\n" + " 1 = Blue 9 = Light Blue\n" + " 2 = Green A = Light Green\n" + " 3 = Aqua B = Light Aqua\n" + " 4 = Red C = Light Red\n" + " 5 = Purple D = Light Purple\n" + " 6 = Yellow E = Light Yellow\n" + " 7 = White F = Bright White\n\n" + "If no argument is given, this command restores the original color.\n\n" + "Example: \"COLOR fc\" produces light red on bright white\n"; + WriteOut(msg); + } + }; + + void COLOR::Run() + { + // Hack To allow long commandlines + ChangeToLongCmd(); + + // Usage + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + bool back=false; + char fg, bg; + int fgc=0, bgc=0; + char *args=(char *)cmd->GetRawCmdline().c_str(); + args=trim(args); + if (strlen(args)==2) { + bg=args[0]; + fg=args[1]; + if (fg=='0'||fg=='8') + fgc=30; + else if (fg=='1'||fg=='9') + fgc=34; + else if (fg=='2'||tolower(fg)=='a') + fgc=32; + else if (fg=='3'||tolower(fg)=='b') + fgc=36; + else if (fg=='4'||tolower(fg)=='c') + fgc=31; + else if (fg=='5'||tolower(fg)=='d') + fgc=35; + else if (fg=='6'||tolower(fg)=='e') + fgc=32; + else if (fg=='7'||tolower(fg)=='f') + fgc=37; + else + back=true; + if (bg=='0'||bg=='8') + bgc=40; + else if (bg=='1'||bg=='9') + bgc=44; + else if (bg=='2'||tolower(bg)=='a') + bgc=42; + else if (bg=='3'||tolower(bg)=='b') + bgc=46; + else if (bg=='4'||tolower(bg)=='c') + bgc=41; + else if (bg=='5'||tolower(bg)=='d') + bgc=45; + else if (bg=='6'||tolower(bg)=='e') + bgc=42; + else if (bg=='7'||tolower(bg)=='f') + bgc=47; + else + back=true; + } else + back=true; + if (back) + WriteOut("\033[0m"); + else { + bool fgl=fg>='0'&&fg<='7', bgl=bg>='0'&&bg<='7'; + WriteOut(("\033["+std::string(fgl||bgl?"0;":"")+std::string(fgl?"":"1;")+std::string(bgl?"":"5;")+std::to_string(fgc)+";"+std::to_string(bgc)+"m").c_str()); + } + } + + static void COLOR_ProgramStart(Program * * make) { + *make=new COLOR; + } + + alt_rgb altBGR[16], altBGR0[16], *rgbcolors = (alt_rgb*)render.pal.rgb; + bool init_altBGR = false,init_altBGR0 = false; + + bool setVGAColor(const char *colorArray, int j) { + if (!IS_VGA_ARCH||!CurMode) return false; + const char * nextRGB = colorArray; + int32_t rgbVal[4] = {-1,-1,-1,-1}; + if (sscanf(nextRGB, " ( %d , %d , %d)", &rgbVal[0], &rgbVal[1], &rgbVal[2]) == 3) { + for (int i = 0; i< 3; i++) { + if (rgbVal[i] < 0 || rgbVal[i] > 255) + return false; + } + } else if (sscanf(nextRGB, " #%6x", (unsigned int*)(&rgbVal[3])) == 1) { + if (rgbVal[3] < 0 || rgbVal[3] > 0xFFFFFF) + return false; + for (int i = 2; i >= 0; i--) { + rgbVal[i] = rgbVal[3]&255; + rgbVal[3] >>= 8; + } + } else + return false; + IO_ReadB(mem_readw(BIOS_VIDEO_PORT)+6); + IO_WriteB(VGAREG_ACTL_ADDRESS, j+32); + uint8_t imap=IO_ReadB(VGAREG_ACTL_READ_DATA); + IO_WriteB(VGAREG_DAC_WRITE_ADDRESS, imap); + IO_WriteB(VGAREG_DAC_DATA, rgbVal[0] >> 2); + IO_WriteB(VGAREG_DAC_DATA, rgbVal[1] >> 2); + IO_WriteB(VGAREG_DAC_DATA, rgbVal[2] >> 2); + rgbcolors[j].red = rgbVal[0] & 0xFF; + rgbcolors[j].green = rgbVal[1] & 0xFF; + rgbcolors[j].blue = rgbVal[2] & 0xFF; + altBGR0[j].red = rgbVal[0]; + altBGR0[j].green = rgbVal[1]; + altBGR0[j].blue = rgbVal[2]; + return true; + } + + #if defined(USE_TTF) + extern alt_rgb altBGR1[16]; + extern bool colorChanged; + bool setColors(const char *colorArray, int n); + void resetFontSize(); + #endif + + bool get_pal = false; + class SETCOLOR : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Views or changes the text-mode color scheme settings.\n\nSETCOLOR [color# [value]]\n\nFor example:\n\n SETCOLOR 0 (50,50,50)\n\nChange Color #0 to the specified color value\n\n SETCOLOR 7 -\n\nReturn Color #7 to the default color value\n\n SETCOLOR 3 +\n\nReturn Color #3 to the preset color value\n\n SETCOLOR MONO\n\nDisplay current MONO mode status\n\nTo change the current background and foreground colors, use COLOR command.\n"; + WriteOut(msg); + } + }; + + void SETCOLOR::Run() + { + // Hack To allow long commandlines + ChangeToLongCmd(); + + if (!get_pal){ + for (uint8_t i=0; i<16; i++){ + altBGR0[i].red = rgbcolors[i].red; + altBGR0[i].green = rgbcolors[i].green; + altBGR0[i].blue = rgbcolors[i].blue; + #ifdef USE_TTF + altBGR1[i].red = rgbcolors[i].red; + altBGR1[i].green = rgbcolors[i].green; + altBGR1[i].blue = rgbcolors[i].blue; + #endif + get_pal = true; + } + } + + // Usage + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + char *args=(char *)cmd->GetRawCmdline().c_str(); + if (*args) { + args=trim(args); + char *p = strchr(args, ' '); + if (p!=NULL) + *p=0; + int i=atoi(args); + if (!strcasecmp(args,"MONO")) { + if (p==NULL) + WriteOut("MONO mode status: %s (video mode %d)\n",CurMode->mode==7?"active":CurMode->mode==3?"inactive":"unavailable",CurMode->mode); + else if (!strcmp(trim(p+1),"+")) { + if (CurMode->mode!=7) INT10_SetVideoMode(7); + WriteOut(CurMode->mode==7?"MONO mode status => active (video mode 7)\n":"Failed to change MONO mode\n"); + } else if (!strcmp(trim(p+1),"-")) { + if (CurMode->mode!=3) INT10_SetVideoMode(3); + WriteOut(CurMode->mode==3?"MONO mode status => inactive (video mode 3)\n":"Failed to change MONO mode\n"); + } else + WriteOut("Must be + or - for MONO: %s\n",trim(p+1)); + } else if (!strcmp(args,"0")||!strcmp(args,"00")||!strcmp(args,"+0")||!strcmp(args,"-0")||(i>0&&i<16)) { + if (p==NULL) { + #if defined(USE_TTF) + bool colornul = staycolors || (IS_VGA_ARCH && (altBGR1[i].red > 4 || altBGR1[i].green > 4 || altBGR1[i].blue > 4) && rgbcolors[i].red < 5 && rgbcolors[i].green < 5 && rgbcolors[i].blue < 5); + altBGR[i].red = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].red:rgbcolors[i].red; + altBGR[i].green = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].green:rgbcolors[i].green; + altBGR[i].blue = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].blue:rgbcolors[i].blue; + WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,altBGR0[i].red,altBGR0[i].green,altBGR0[i].blue,altBGR0[i].red,altBGR0[i].green,altBGR0[i].blue); + #else + WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue); + #endif + } + } else { + WriteOut("Invalid color number - %s\n", trim(args)); + DOS_SetError(DOSERR_DATA_INVALID); + return; + } if (p!=NULL&&strcasecmp(args,"MONO")) { + char value[128]; + if (!strcmp(trim(p+1),"-")) { + strcpy(value,i==0?"#000000":i==1?"#0000aa":i==2?"#00aa00":i==3?"#00aaaa":i==4?"#aa0000":i==5?"#aa00aa":i==6?"#aa5500":i==7?"#aaaaaa":i==8?"#555555":i==9?"#5555ff":i==10?"#55ff55":i==11?"#55ffff":i==12?"#ff5555":i==13?"#ff55ff":i==14?"#ffff55":"#ffffff"); + } else if (!strcmp(trim(p+1),"+")) { + Section_prop * ttf_section=static_cast(control->GetSection("ttf")); + const char * colors = ttf_section->Get_string("colors"); + const char * nextRGB = *colors ? (colors + (*colors == '+'?1:0)) : "#000000 #0000aa #00aa00 #00aaaa #aa0000 #aa00aa #aa5500 #aaaaaa #555555 #5555ff #55ff55 #55ffff #ff5555 #ff55ff #ffff55 #ffffff"; + int rgbVal[3] = {-1,-1,-1}; + for (int colNo = 0; colNo <= i; colNo++) { + if (sscanf(nextRGB, " ( %d , %d , %d)", &rgbVal[0], &rgbVal[1], &rgbVal[2]) == 3) { + sprintf(value,"(%d,%d,%d)",rgbVal[0],rgbVal[1],rgbVal[2]); + while (*nextRGB != ')') + nextRGB++; + nextRGB++; + } else if (sscanf(nextRGB, " #%6x", (unsigned int*)(&rgbVal[0])) == 1) { + sprintf(value,"#%6x",rgbVal[0]); + nextRGB = strchr(nextRGB, '#') + 7; + } else { + WriteOut("Invalid color value - %s\n",nextRGB); + return; + } + } + } else { + strncpy(value,trim(p+1),127); + value[127]=0; + } + #if defined(USE_TTF) + if (!ttf.inUse) { + #endif + if (!IS_VGA_ARCH) + WriteOut("Changing color scheme is not supported for the current video mode.\n"); + else if (setVGAColor(value, i)) + //WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue); + WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,altBGR0[i].red,altBGR0[i].green,altBGR0[i].blue,altBGR0[i].red,altBGR0[i].green,altBGR0[i].blue); + else + WriteOut("Invalid color value - %s\n",value); + #if defined(USE_TTF) + } else if (setColors(value,i)) { + bool colornul = staycolors || (IS_VGA_ARCH && (altBGR1[i].red > 4 || altBGR1[i].green > 4 || altBGR1[i].blue > 4) && rgbcolors[i].red < 5 && rgbcolors[i].green < 5 && rgbcolors[i].blue < 5); + altBGR[i].red = (colornul||(colorChanged&&!IS_VGA_ARCH))?altBGR1[i].red:rgbcolors[i].red; + altBGR[i].green = (colornul||(colorChanged&&!IS_VGA_ARCH))?altBGR1[i].green:rgbcolors[i].green; + altBGR[i].blue = (colornul||(colorChanged&&!IS_VGA_ARCH))?altBGR1[i].blue:rgbcolors[i].blue; + WriteOut("Color %d => (%d,%d,%d) or #%02x%02x%02x\n",i,altBGR[i].red,altBGR[i].green,altBGR[i].blue,altBGR[i].red,altBGR[i].green,altBGR[i].blue); + resetFontSize(); + } else + WriteOut("Invalid color value - %s\n",value); + #endif + } + } else { + WriteOut("MONO mode status: %s (video mode %d)\n",CurMode->mode==7?"active":CurMode->mode==3?"inactive":"unavailable",CurMode->mode); + for (int i = 0; i < 16; i++) { + #if defined(USE_TTF) + bool colornul = staycolors || (IS_VGA_ARCH && (altBGR1[i].red > 4 || altBGR1[i].green > 4 || altBGR1[i].blue > 4) && rgbcolors[i].red < 5 && rgbcolors[i].green < 5 && rgbcolors[i].blue < 5); + altBGR[i].red = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].red:rgbcolors[i].red; + altBGR[i].green = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].green:rgbcolors[i].green; + altBGR[i].blue = colornul||(colorChanged&&!IS_VGA_ARCH)?altBGR1[i].blue:rgbcolors[i].blue; + WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,altBGR[i].red,altBGR[i].green,altBGR[i].blue,altBGR[i].red,altBGR[i].green,altBGR[i].blue); + #else + WriteOut("Color %d: (%d,%d,%d) or #%02x%02x%02x\n",i,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue,rgbcolors[i].red,rgbcolors[i].green,rgbcolors[i].blue); + #endif + } + } + } + + static void SETCOLOR_ProgramStart(Program * * make) { + *make=new SETCOLOR; + } + + #if C_DEBUG + extern Bitu int2fdbg_hook_callback; + class INT2FDBG : public Program { + public: + void Run(void) override; + private: + void PrintUsage() { + constexpr const char *msg = + "Hooks INT 2Fh for debugging purposes.\n\nINT2FDBG [option]\n /I Installs hook\n\nIt will hook INT 2Fh at the top of the call chain for debugging information.\n\nType INT2FDBG without a parameter to show the current hook status.\n"; + WriteOut(msg); + } + }; + + void INT2FDBG::Run() + { + // Hack To allow long commandlines + ChangeToLongCmd(); + + if (!cmd->GetCount()) { + if (int2fdbg_hook_callback == 0) + WriteOut("INT 2Fh hook has not been set.\n"); + else + WriteOut("INT 2Fh hook has already been set.\n"); + return; + } + + // Usage + if (!cmd->GetCount() || cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + PrintUsage(); + return; + } + char *args=(char *)cmd->GetRawCmdline().c_str(); + args=trim(args); + DOS_Shell temp; + temp.CMD_INT2FDBG(args); + } + + static void INT2FDBG_ProgramStart(Program * * make) { + *make=new INT2FDBG; + } + #endif + + #if defined (WIN32) + extern bool ctrlbrk; + extern std::string startincon; + #endif + #if defined (WIN32) && !defined(HX_DOS) + #include + #include + SHELLEXECUTEINFO lpExecInfo; + + void EndStartProcess() { + if(lpExecInfo.hProcess!=NULL) { + DWORD exitCode; + GetExitCodeProcess(lpExecInfo.hProcess, &exitCode); + if (exitCode==STILL_ACTIVE) + TerminateProcess(lpExecInfo.hProcess, 0); + } + ctrlbrk=false; + } + #endif + + // void zipSetCurrentTime(zip_fileinfo &zi); + // int zipOutOpenFile(zipFile zf,const char *zfname,zip_fileinfo &zi,const bool compress); + + const char * TranslateHostPath(const char * arg, bool next = false); + class START : public Program { + public: + void Run() override { + if(control->SecureMode()) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); + return; + } + + // Hack To allow long commandlines + ChangeToLongCmd(); + + // Usage + if (!cmd->GetCount()||(cmd->GetCount()==1 && (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)))) { + PrintUsage(); + return; + } + char *args=(char *)cmd->GetRawCmdline().c_str(); + args=trim(args); + char *cmd = strlen(args)?args:NULL; + if (cmd!=NULL&&strlen(cmd)>1&&cmd[0]=='"'&&cmd[1]==' ') { + cmd++; + while (cmd[0]==' ') cmd++; + cmd--; + cmd[0]='"'; + } + #if defined(WIN32) && !defined(HX_DOS) + char *cmdstr = cmd==NULL?NULL:(char *)strstr(cmd, cmd[0]=='"'?"\" ":" "); + char buf[CROSS_LEN], dir[CROSS_LEN+15], str[CROSS_LEN*2]; + int k=0; + if (cmdstr!=NULL) { + if (*cmdstr=='\"') cmdstr++; + while (*cmdstr==' ') {k++;*cmdstr++=0;} + } + int state = cmd==NULL?0:!strcmp(cmd,"-")||!strcasecmp(cmd,"/min")||!strcasecmp(cmd,"-min")?1:!strcmp(cmd,"+")||!strcasecmp(cmd,"/max")||!strcasecmp(cmd,"-max")?2:!strcasecmp(cmd,"_")||!strcasecmp(cmd,"/hid")||!strcasecmp(cmd,"-hid")?3:0; + if (state > 0) { + k=0; + cmd = cmdstr; + if (cmd!=NULL&&strlen(cmd)>1&&cmd[0]=='"'&&cmd[1]==' ') { + cmd++; + while (cmd[0]==' ') cmd++; + cmd--; + cmd[0]='"'; + } + if ((cmdstr = cmd==NULL?NULL:(char *)strstr(cmd, cmd[0]=='"'?"\" ":" "))!=NULL) { + if (*cmdstr=='\"') cmdstr++; + while (*cmdstr==' ') {k++;*cmdstr++=0;} + } + } + if (cmd!=NULL) { + char *ret, *ret0, *ret1, *ret2, *ret3, *ret4; + ret0 = strchr(cmd, '/'); + ret1 = strchr(cmd, '|'); + ret2 = strchr(cmd, '<'); + ret3 = strchr(cmd, '>'); + ret4 = strchr(cmd, ' '); + ret = ret0>cmd?ret0:NULL; + if (ret1!=NULL && (ret == NULL || ret1cmd&&*(ret-1)==':')) { + strcpy(buf, cmdstr==NULL?"":cmdstr); + strcpy(str, ret); + if (k<1) k=1; + for (int i=0; i0&&cmdstr[strlen(cmdstr)-2]=='"') { + cmd++; + cmdstr[strlen(cmdstr)-2]='\0'; + } + } + } + if (cmd==NULL || !strlen(cmd) || !strcmp(cmd,"?") || !strcmp(cmd,"/") || !strcmp(cmd,"/?") || !strcmp(cmd,"-?")) { + PrintUsage(); + DOS_SetError(0); + return; + } + int sw = state==0?SW_SHOW:state==1?SW_MINIMIZE:state==2?SW_MAXIMIZE:SW_HIDE; + bool match=false; + std::istringstream in(startincon); + if (in) for (std::string command; in >> command; ) { + if (!strcasecmp(cmd,command.c_str())||!strcasecmp(cmd,("\""+command+"\"").c_str())) { + match=true; + break; + } + } + lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); + lpExecInfo.fMask=SEE_MASK_DOENVSUBST|SEE_MASK_NOCLOSEPROCESS; + lpExecInfo.hwnd = NULL; + lpExecInfo.lpVerb = "open"; + lpExecInfo.lpDirectory = NULL; + lpExecInfo.nShow = sw; + lpExecInfo.hInstApp = (HINSTANCE) SE_ERR_DDEFAIL; + if (match) { + strcpy(dir, strcasecmp(cmd,"for")?"/C \"":"/C \"("); + strcat(dir, cmd); + strcat(dir, " "); + if (cmdstr!=NULL) strcat(dir, TranslateHostPath(cmdstr)); + if (!strcasecmp(cmd,"for")) strcat(dir, ")"); + strcat(dir, " & echo( & echo The command execution is completed. & pause\""); + lpExecInfo.lpFile = "CMD.EXE"; + lpExecInfo.lpParameters = dir; + } else { + lpExecInfo.lpFile = cmd==NULL?NULL:TranslateHostPath(cmd); + lpExecInfo.lpParameters = cmdstr==NULL?NULL:TranslateHostPath(cmdstr, true); + } + bool setdir=false; + char winDirCur[512], winDirNew[512]; + if (GetCurrentDirectory(512, winDirCur)&&(!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"local ",6)||!strncmp(Drives[DOS_GetDefaultDrive()]->GetInfo(),"CDRom ",6))) { + Overlay_Drive *ddp = dynamic_cast(Drives[DOS_GetDefaultDrive()]); + strcpy(winDirNew, ddp!=NULL?ddp->getOverlaydir():Drives[DOS_GetDefaultDrive()]->GetBaseDir()); + strcat(winDirNew, Drives[DOS_GetDefaultDrive()]->curdir); + if (SetCurrentDirectory(winDirNew)) setdir=true; + } + if (!startquiet) WriteOut("Starting %s...\n", cmd); + ShellExecuteEx(&lpExecInfo); + int ErrorCode = GetLastError(); + if (setdir) SetCurrentDirectory(winDirCur); + if (startwait && lpExecInfo.hProcess!=NULL) { + DWORD exitCode; + BOOL ret; + int count=0; + ctrlbrk=false; + inshell=true; + do { + ret=GetExitCodeProcess(lpExecInfo.hProcess, &exitCode); + CALLBACK_Idle(); + if (ctrlbrk) { + uint8_t c;uint16_t n=1; + DOS_ReadFile (STDIN,&c,&n); + if (c == 3) WriteOut("^C\r\n"); + EndStartProcess(); + exitCode=0; + break; + } + if (++count==20000&&ret&&exitCode==STILL_ACTIVE&&!startquiet) WriteOut("(Press Ctrl+C to exit immediately)\n"); + } while (ret!=0&&exitCode==STILL_ACTIVE); + ErrorCode = GetLastError(); + CloseHandle(lpExecInfo.hProcess); + inshell=false; + } + DOS_SetError(ErrorCode); + #else + if (cmd==NULL || !strlen(cmd) || !strcmp(cmd,"?") || !strcmp(cmd,"/") || !strcmp(cmd,"/?") || !strcmp(cmd,"-?") || !strcasecmp(cmd,"/open") || !strcasecmp(cmd,"-open")) { + PrintUsage(); + DOS_SetError(0); + return; + } + if (!startquiet) WriteOut("Starting %s...\n", cmd); + bool open=false; + if (!strncasecmp(cmd, "/open ", 5) || !strncasecmp(cmd, "-open ", 6)) { + open=true; + cmd+=5; + } + cmd=trim((char *)TranslateHostPath(cmd)); + int ret=0; + #if defined(LINUX) || defined(MACOSX) + ret=system(((open? + #if defined(LINUX) + "xdg-open " + #else + "open " + #endif + :"")+std::string(cmd)+(startwait||(strlen(cmd)>2&&!strcmp(cmd+strlen(cmd)-2," &"))?"":" &")).c_str()); + #else + WriteOut("Error: START cannot launch application to run on your current host system.\n"); + return; + #endif + if (ret==-1) { + WriteOut("Error: START could not launch application.\n"); + return; + } + DOS_SetError(ret); + #endif + } + + private: + void PrintUsage() { + constexpr const char *msg = + "Starts a separate window to run a specified program or command.\n\n" + #if defined(WIN32) + "START [+|-|_] command [arguments]\n\n" + " [+|-|_]: To maximize/minimize/hide the program.\n" + " The options /MAX, /MIN, /HID are also accepted.\n" + " command: The command, program or file to start.\n" + " arguments: Arguments to pass to the application.\n\n" + "START opens the Windows command prompt automatically to run these commands\n" + "and wait for a key press before exiting (specified by \"startincon\" option):\n%s\n\n" + #else + "START /OPEN file\nSTART command [arguments]\n\n" + " /OPEN: To open a file or URL with the associated program.\n" + " file: The file or URL to open with the associated program.\n" + " command: The command or program to start or run.\n" + " arguments: Arguments to pass to the application.\n\n" + #endif + "Note: The path specified in this command is the path on the host system.\n"; + WriteOut(msg + #if defined(WIN32) + ,startincon.c_str() + #endif + ); + } + }; + + void START_ProgramStart(Program **make) + { + *make = new START; + } + + #define MAX_FLAGS 512 + char *g_flagged_files[MAX_FLAGS]; //global array to hold flagged files + int flagged_backup(char *zip) + { + + unsigned char buffer[4096]; + char zipfile[CROSS_LEN]; + int ret = 0; + int i; + + #ifdef C_LIBZ + + bool compresssaveparts = static_cast(control->GetSection("dosbox"))->Get_bool("compresssaveparts"); + + strcpy(zipfile, zip); + if (strstr(zipfile, ".sav")) + strcpy(strstr(zipfile, ".sav"), ".dat"); + + i=0; + while (i < MAX_FLAGS && g_flagged_files[i] == NULL) i++; + if (i < MAX_FLAGS) { + zipFile zf; + { + const char *global_comment = "DOSBox-X flagged file save state"; + zlib_filefunc64_def ffunc; + #ifdef USEWIN32IOAPI + fill_win32_filefunc64A(&ffunc); + #else + fill_fopen64_filefunc(&ffunc); + #endif + remove(zipfile); + zf = zipOpen2_64(zipfile,APPEND_STATUS_CREATE,&global_comment,&ffunc); + } + if (zf != NULL) { + while (i < MAX_FLAGS) { + if (g_flagged_files[i] != NULL) { + uint16_t handle = 0; + if (DOS_FindDevice(("\""+std::string(g_flagged_files[i])+"\"").c_str()) != DOS_DEVICES || !DOS_OpenFile(("\""+std::string(g_flagged_files[i])+"\"").c_str(),0,&handle)) { + LOG_MSG(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),g_flagged_files[i]); + continue; + } + + zip_fileinfo zi; zipSetCurrentTime(zi); + if (zipOutOpenFile(zf,g_flagged_files[i],zi,compresssaveparts) == ZIP_OK) { + zip_ostreambuf zos(zf); + + do { + uint16_t n = sizeof(buffer); + DOS_ReadFile(handle,buffer,&n); + if (n == 0) break; + if (zos.xsputn((zip_ostreambuf::char_type*)buffer,n) < n) break; + } while(1); + + zos.close(); + } + + DOS_CloseFile(handle); + } + + i++; + } + zipClose(zf,NULL); + } + } + + #endif + + return ret; + } + + // int flagged_restore(char* zip) + // { + // unsigned char buffer[4096]; + // unz_file_info64 file_info; + // char zipfile[MAX_FLAGS]; + // int ret = 0; + // int i; + + // #ifdef C_LIBZ + + // strcpy(zipfile, zip); + // if (strstr(zipfile, ".sav")) + // strcpy(strstr(zipfile, ".sav"), ".dat"); + // i=0; + // while (i < MAX_FLAGS && g_flagged_files[i] == NULL) i++; + // if (i < MAX_FLAGS) { + // unzFile zf; + // { + // zlib_filefunc64_def ffunc; + // #ifdef USEWIN32IOAPI + // fill_win32_filefunc64A(&ffunc); + // #else + // fill_fopen64_filefunc(&ffunc); + // #endif + // zf = unzOpen2_64(zipfile,&ffunc); + // } + // if (zf != NULL) { + // while (i < MAX_FLAGS) { + // if (g_flagged_files[i] != NULL) { + // if (DOS_FindDevice(("\""+std::string(g_flagged_files[i])+"\"").c_str()) != DOS_DEVICES) { + // LOG_MSG(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),g_flagged_files[i]); + // continue; + // } + + // if (unzLocateFile(zf,g_flagged_files[i],2/*case insensitive*/) == UNZ_OK && + // unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0) == UNZ_OK) { + // if (unzOpenCurrentFile(zf) == UNZ_OK) { + // zip_istreambuf zis(zf); + + // uint16_t handle=0; + // if (DOS_CreateFile(("\""+std::string(g_flagged_files[i])+"\"").c_str(),0,&handle)) { + // do { + // uint16_t n = zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)); + // if (n == 0) break; + // DOS_WriteFile(handle,(uint8_t*)buffer,&n); + // if (n == 0) break; + // } while (1); + // DOS_CloseFile(handle); + // } + + // zis.close(); + // } + // } + // } + + // i++; + // } + // unzClose(zf); + // } + // } + + // #endif + + // return ret; + // } + + class FLAGSAVE : public Program + { + public: + + void Run(void) override + { + std::string file_to_flag; + int i, lf; + bool force=false, remove=false; + + if (cmd->FindExist("-?", false) || cmd->FindExist("/?", false)) { + printHelp(); + return; + } + if (cmd->FindExist("/f", true)) + force=true; + if (cmd->FindExist("/r", true)) + remove=true; + if (cmd->FindExist("/u", true)) + { + for (i = 0; i < MAX_FLAGS; i++) + { + if (g_flagged_files[i] != NULL) + g_flagged_files[i] = NULL; + } + WriteOut("All files unflagged for saving.\n"); + return; + } + else if (cmd->GetCount()) + { + for (unsigned int i=1; i<=cmd->GetCount(); i++) { + cmd->FindCommand(i,temp_line); + uint8_t drive; + char fullname[DOS_PATHLENGTH], flagfile[CROSS_LEN]; + + strcpy(flagfile, temp_line.c_str()); + if (*flagfile&&DOS_MakeName(((flagfile[0]!='\"'?"\"":"")+std::string(flagfile)+(flagfile[strlen(flagfile)-1]!='\"'?"\"":"")).c_str(), fullname, &drive)) + { + sprintf(flagfile, "%c:\\%s", drive+'A', fullname); + if (remove) { + for (lf = 0; lf < MAX_FLAGS; lf++) + { + if (g_flagged_files[lf] != NULL && !strcasecmp(g_flagged_files[lf], flagfile)) + { + WriteOut("File %s unflagged for saving.\n", g_flagged_files[lf]); + free(g_flagged_files[lf]); + g_flagged_files[lf] = NULL; + break; + } + } + continue; + } + if (!force && !DOS_FileExists(("\""+std::string(flagfile)+"\"").c_str())) { + WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"), flagfile); + continue; + } + bool found=false; + for (lf = 0; lf < MAX_FLAGS; lf++) + { + if (g_flagged_files[lf] == NULL) + continue; + if (!strcasecmp(g_flagged_files[lf], flagfile)) + { + WriteOut("File already flagged for saving - %s\n", flagfile); + found=true; + } + } + if (found) continue; + for (lf = 0; lf < MAX_FLAGS; lf++) + { + if (g_flagged_files[lf] == NULL) + break; + } + if (lf == MAX_FLAGS) + { + WriteOut("Too many files to flag for saving.\n"); + return; + } + g_flagged_files[lf] = (char*)malloc(strlen(flagfile) + 1); + strcpy(g_flagged_files[lf], flagfile); + WriteOut("File %s flagged for saving\n", g_flagged_files[lf]); + } else + WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"), flagfile); + } + return; + } + else + { + WriteOut("Files flagged for saving:\n"); + for (i = 0; i < MAX_FLAGS; i++) + { + if (g_flagged_files[i]) + WriteOut("%s\n", g_flagged_files[i]); + } + return; + } + } + void printHelp() + { + WriteOut( "Marks or flags files to be saved for the save state feature.\n\n" + "FLAGSAVE [file(s) [/F] [/R]] [/U]\n\n" + " file(s) Specifies one or more files to be flagged for saving.\n" + " /F Forces to flag the file(s) even if they are not found.\n" + " /R Removes flags from the specified file(s).\n" + " /U Removes flags from all flagged files.\n\n" + "Type FLAGSAVE without a parameter to list flagged files.\n"); + } + }; + + static void FLAGSAVE_ProgramStart(Program** make) + { + *make = new FLAGSAVE; + } + + void Add_VFiles(bool usecp) { + VFILE_Register("TEXTUTIL", nullptr, 0, "/"); + VFILE_Register("SYSTEM", nullptr, 0, "/"); + VFILE_Register("DEBUG", nullptr, 0, "/"); + VFILE_Register("DOS", nullptr, 0, "/"); + VFILE_Register("CPI", nullptr, 0, "/"); + VFILE_Register("BIN", nullptr, 0, "/"); + VFILE_Register("4DOS", nullptr, 0, "/"); + + std::string dirname="drivez"; + std::string path = "."; + path += CROSS_FILESPLIT; + path += dirname; + getdrivezpath(path, dirname); + drivezRegister(path, "/", usecp); + + PROGRAMS_MakeFile("HELP.COM",HELP_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("INTRO.COM",INTRO_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("IMGMOUNT.COM", IMGMOUNT_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("IMGMAKE.COM", IMGMAKE_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("IMGSWAP.COM", IMGSWAP_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("MOUNT.COM",MOUNT_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("BOOT.COM",BOOT_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("CONFIG.COM",CONFIG_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("COUNTRY.COM",COUNTRY_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("COMMAND.COM",SHELL_ProgramStart); + internal_program = true; + if (usecp && prepared) VFILE_Register("AUTOEXEC.BAT",(uint8_t *)autoexec_data,(uint32_t)strlen(autoexec_data)); + if (prepared) VFILE_Register("CONFIG.SYS",(uint8_t *)config_data,(uint32_t)strlen(config_data)); + internal_program = false; + PROGRAMS_MakeFile("RE-DOS.COM",REDOS_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("RESCAN.COM",RESCAN_ProgramStart,"/SYSTEM/"); + #if defined(WIN32) && !defined(HX_DOS) || defined(LINUX) || defined(MACOSX) + if (startcmd) PROGRAMS_MakeFile("START.COM", START_ProgramStart,"/SYSTEM/"); + #endif + + if (machine == MCH_CGA) PROGRAMS_MakeFile("CGASNOW.COM",CGASNOW_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("VFRCRATE.COM",VFRCRATE_ProgramStart,"/DEBUG/"); + + if (IS_VGA_ARCH && svgaCard != SVGA_None) + PROGRAMS_MakeFile("VESAMOED.COM",VESAMOED_ProgramStart,"/DEBUG/"); + + if (!IS_PC98_ARCH) { + PROGRAMS_MakeFile("LOADROM.COM", LOADROM_ProgramStart,"/DEBUG/"); + PROGRAMS_MakeFile("KEYB.COM", KEYB_ProgramStart,"/DOS/"); + PROGRAMS_MakeFile("MODE.COM", MODE_ProgramStart,"/DOS/"); + PROGRAMS_MakeFile("MOUSE.COM", MOUSE_ProgramStart,"/DOS/"); + PROGRAMS_MakeFile("SETCOLOR.COM", SETCOLOR_ProgramStart,"/BIN/"); + } + + if (IS_VGA_ARCH) { + PROGRAMS_MakeFile("80X60.COM", TEXT80X60_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("80X50.COM", TEXT80X50_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("80X43.COM", TEXT80X43_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("80X25.COM", TEXT80X25_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("132X60.COM", TEXT132X60_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("132X50.COM", TEXT132X50_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("132X43.COM", TEXT132X43_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("132X25.COM", TEXT132X25_ProgramStart,"/TEXTUTIL/"); + PROGRAMS_MakeFile("DCGA.COM", DCGA_ProgramStart,"/TEXTUTIL/"); + } + + PROGRAMS_MakeFile("COLOR.COM",COLOR_ProgramStart,"/BIN/"); + PROGRAMS_MakeFile("TITLE.COM",TITLE_ProgramStart,"/BIN/"); + PROGRAMS_MakeFile("VHDMAKE.COM",VHDMAKE_ProgramStart,"/BIN/"); + PROGRAMS_MakeFile("LS.COM",LS_ProgramStart,"/BIN/"); + PROGRAMS_MakeFile("ADDKEY.COM",ADDKEY_ProgramStart,"/BIN/"); + PROGRAMS_MakeFile("CFGTOOL.COM",CFGTOOL_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("FLAGSAVE.COM", FLAGSAVE_ProgramStart,"/SYSTEM/"); + #if defined C_DEBUG + PROGRAMS_MakeFile("NMITEST.COM",NMITEST_ProgramStart,"/DEBUG/"); + PROGRAMS_MakeFile("INT2FDBG.COM",INT2FDBG_ProgramStart,"/DEBUG/"); + PROGRAMS_MakeFile("BIOSTEST.COM", BIOSTEST_ProgramStart,"/DEBUG/"); + #endif + PROGRAMS_MakeFile("A20GATE.COM",A20GATE_ProgramStart,"/DEBUG/"); + + if (IS_PC98_ARCH) + PROGRAMS_MakeFile("PC98UTIL.COM",PC98UTIL_ProgramStart,"/BIN/"); + + PROGRAMS_MakeFile("CAPMOUSE.COM", CAPMOUSE_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("LOADFIX.COM",LOADFIX_ProgramStart,"/DOS/"); + PROGRAMS_MakeFile("LABEL.COM", LABEL_ProgramStart,"/DOS/"); + PROGRAMS_MakeFile("TREE.COM", TREE_ProgramStart,"/DOS/"); + PROGRAMS_MakeFile("DELTREE.EXE",DELTREE_ProgramStart,"/DOS/"); + PROGRAMS_MakeFile("CHOICE.COM", CHOICE_ProgramStart,"/DOS/"); + PROGRAMS_MakeFile("AUTOTYPE.COM", AUTOTYPE_ProgramStart,"/BIN/"); + #ifdef C_ICONV + PROGRAMS_MakeFile("UTF8.COM", UTF8_ProgramStart,"/BIN/"); + PROGRAMS_MakeFile("UTF16.COM", UTF16_ProgramStart,"/BIN/"); + #endif + PROGRAMS_MakeFile("MIXER.COM",MIXER_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("SERIAL.COM", SERIAL_ProgramStart,"/SYSTEM/"); + PROGRAMS_MakeFile("PARALLEL.COM", PARALLEL_ProgramStart,"/SYSTEM/"); + if (IS_DOSV) + PROGRAMS_MakeFile("VTEXT.COM", VTEXT_ProgramStart,"/TEXTUTIL/"); + + VFILE_RegisterBuiltinFileBlob(bfb_EDLIN_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_DEBUG_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_MOVE_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_FIND_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_FCBS_COM, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_FILES_COM, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_LASTDRIV_COM, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_REPLACE_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_SORT_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_XCOPY_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_APPEND_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_DEVICE_COM, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_BUFFERS_COM, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_CHKDSK_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_COMP_COM, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_FC_EXE, "/DOS/"); + #if C_IPX + if (addipx) PROGRAMS_MakeFile("IPXNET.COM",IPXNET_ProgramStart,"/SYSTEM/"); + #endif + if (addne2k) VFILE_RegisterBuiltinFileBlob(bfb_NE2000_COM, "/SYSTEM/"); + if (addovl) VFILE_RegisterBuiltinFileBlob(bfb_GLIDE2X_OVL, "/SYSTEM/"); + + /* These are IBM PC/XT/AT ONLY. They will not work in PC-98 mode. */ + if (!IS_PC98_ARCH) { + VFILE_RegisterBuiltinFileBlob(bfb_SYS_COM, "/DOS/"); /* may rely on INT 13h or IBM PC specific functions and layout */ + VFILE_RegisterBuiltinFileBlob(bfb_FORMAT_EXE, "/DOS/"); /* does not work in PC-98 mode */ + VFILE_RegisterBuiltinFileBlob(bfb_DEFRAG_EXE, "/DOS/"); /* relies on IBM PC CGA/EGA/VGA alphanumeric display memory */ + VFILE_RegisterBuiltinFileBlob(bfb_FDISK_EXE, "/BIN/"); /* relies on IBM PC INT 13h */ + VFILE_RegisterBuiltinFileBlob(bfb_HEXMEM16_EXE, "/DEBUG/"); + VFILE_RegisterBuiltinFileBlob(bfb_HEXMEM32_EXE, "/DEBUG/"); + VFILE_RegisterBuiltinFileBlob(bfb_DOSIDLE_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_DOS32A_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_DOS4GW_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_CDPLAY_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_CDPLAY_TXT, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_CDPLAY_ZIP, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_DOSMID_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_MPXPLAY_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_ZIP_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_UNZIP_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_EMSMAGIC_COM, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_DISKCOPY_EXE, "/DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_CWSDPMI_EXE, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_PRINT_COM, "/DOS/"); + + /* It appears the latest EDIT.COM requires a 386, and it does not bother + * to detect if the CPU is a 386. If you run this program for 286 and lower + * you get a crash. */ + if (CPU_ArchitectureType >= CPU_ARCHTYPE_386) + VFILE_RegisterBuiltinFileBlob(bfb_EDIT_COM, "/DOS/"); + + VFILE_RegisterBuiltinFileBlob(bfb_LICENSE_TXT, "/4DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_EXAMPLES_BTM, "/4DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_BATCOMP_EXE, "/4DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_OPTION_EXE, "/4DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_4HELP_EXE, "/4DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_4DOS_HLP, "/4DOS/"); + VFILE_RegisterBuiltinFileBlob(bfb_4DOS_COM, "/4DOS/"); + } + if (prepared) VFILE_Register("4DOS.INI",(uint8_t *)i4dos_data,(uint32_t)strlen(i4dos_data), "/4DOS/"); + + if (IS_VGA_ARCH) { + VFILE_RegisterBuiltinFileBlob(bfb_VGA_COM, "/TEXTUTIL/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA_COM, "/TEXTUTIL/"); + VFILE_RegisterBuiltinFileBlob(bfb_CLR_COM, "/TEXTUTIL/"); + VFILE_RegisterBuiltinFileBlob(bfb_CGA_COM, "/TEXTUTIL/"); + VFILE_RegisterBuiltinFileBlob(bfb_50_COM, "/TEXTUTIL/"); + VFILE_RegisterBuiltinFileBlob(bfb_28_COM, "/TEXTUTIL/"); + } else if (IS_EGA_ARCH) + VFILE_RegisterBuiltinFileBlob(bfb_28_COM_ega, "/TEXTUTIL/"); + + if (IS_VGA_ARCH) + VFILE_RegisterBuiltinFileBlob(bfb_25_COM, "/TEXTUTIL/"); + else if (IS_EGA_ARCH) + VFILE_RegisterBuiltinFileBlob(bfb_25_COM_ega, "/TEXTUTIL/"); + else if (!IS_PC98_ARCH) + VFILE_RegisterBuiltinFileBlob(bfb_25_COM_other, "/TEXTUTIL/"); + + /* MEM.COM is not compatible with PC-98 and/or 8086 emulation */ + if(!IS_PC98_ARCH && CPU_ArchitectureType >= CPU_ARCHTYPE_80186) + VFILE_RegisterBuiltinFileBlob(bfb_MEM_EXE, "/DOS/"); + else if(IS_PC98_ARCH || CPU_ArchitectureType < CPU_ARCHTYPE_80186) + VFILE_RegisterBuiltinFileBlob(bfb_MEM_EXE_PC98, "/DOS/"); + + /* DSXMENU.EXE */ + if(IS_PC98_ARCH) { + VFILE_RegisterBuiltinFileBlob(bfb_DSXMENU_EXE_PC98, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_CWSDPMI_PC98_EXE, "/BIN/"); + } + else { + VFILE_RegisterBuiltinFileBlob(bfb_DSXMENU_EXE_PC, "/BIN/"); + VFILE_RegisterBuiltinFileBlob(bfb_SHUTDOWN_COM, "/BIN/"); + } + + VFILE_RegisterBuiltinFileBlob(bfb_EVAL_EXE, "/BIN/"); + if(!IS_PC98_ARCH) + VFILE_RegisterBuiltinFileBlob(bfb_EVAL_HLP, "/BIN/"); + + VFILE_RegisterBuiltinFileBlob(bfb_EGA18_CPI, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA17_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA16_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA15_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA14_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA13_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA12_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA11_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA10_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA9_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA8_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA7_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA6_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA5_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA4_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA3_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA2_CPX, "/CPI/"); + VFILE_RegisterBuiltinFileBlob(bfb_EGA_CPX, "/CPI/"); + } + + #if WIN32 + void Add_Existing_Drive_Directories() + { + for(auto drive = 'C'; drive < 'Y'; drive++) + { + auto name = std::string("drive"); + auto path = std::string("."); + + name += drive; + path += CROSS_FILESPLIT; + path += name; + + getdrivezpath(path, name); + + if (path.empty()) + continue; + + LOG_MSG("Mounting directory 'drive%c' found in DOSBox-X directory as drive %c.\n", static_cast(drive + 32), drive); + + MountHelper(drive, path.c_str(), "LOCAL"); + } + } + #endif + + void DOS_SetupPrograms(void) { + /*Add Messages */ + + MSG_Add("PROGRAM_MOUSE_INSTALL","Installed at PS/2 port.\n"); + MSG_Add("PROGRAM_MOUSE_VERTICAL","Reverse Y-axis enabled.\n"); + MSG_Add("PROGRAM_MOUSE_VERTICAL_BACK","Reverse Y-axis disabled.\n"); + MSG_Add("PROGRAM_MOUSE_UNINSTALL","Driver successfully unloaded...\n"); + MSG_Add("PROGRAM_MOUSE_ERROR","Already installed at PS/2 port.\n"); + MSG_Add("PROGRAM_MOUSE_NOINSTALLED","Driver is not installed.\n"); + MSG_Add("PROGRAM_MOUSE_HELP","Turns on/off mouse.\n\nMOUSE [/?] [/U] [/V]\n /U: Uninstall\n /V: Reverse Y-axis\n"); + MSG_Add("PROGRAM_MOUNT_CDROMS_FOUND","CDROMs found: %d\n"); + MSG_Add("PROGRAM_MOUNT_STATUS_FORMAT","%-5s %-58s %-12s\n"); + MSG_Add("PROGRAM_MOUNT_STATUS_ELTORITO", "Drive %c is mounted as El Torito floppy drive\n"); + MSG_Add("PROGRAM_MOUNT_STATUS_RAMDRIVE", "Drive %c is mounted as RAM drive\n"); + MSG_Add("PROGRAM_MOUNT_STATUS_2","Drive %c is mounted as %s\n"); + MSG_Add("PROGRAM_MOUNT_STATUS_1","The currently mounted drives are:\n"); + MSG_Add("PROGRAM_MOUNT_NOT_FORMATTED","Drive not formatted. Format it before accessing the drive.\n"); + MSG_Add("PROGRAM_MOUNT_UNSUPPORTED_EXT","Unsupported extension %s: Mounted as raw IMG image.\n"); + MSG_Add("PROGRAM_IMGMOUNT_STATUS_FORMAT","%-5s %-47s %-12s %s\n"); + MSG_Add("PROGRAM_IMGMOUNT_STATUS_NUMBER_FORMAT","%-12s %-40s %-12s %s\n"); + MSG_Add("PROGRAM_IMGMOUNT_STATUS_2","The currently mounted drive numbers are:\n"); + MSG_Add("PROGRAM_IMGMOUNT_STATUS_1","The currently mounted FAT/ISO drives are:\n"); + MSG_Add("PROGRAM_IMGMOUNT_STATUS_NONE","No drive available\n"); + MSG_Add("PROGRAM_IMGSWAP_STATUS","Drives currently available for swapping are:\n"); + MSG_Add("PROGRAM_IMGSWAP_ERROR","Position must be between 1 and %d for this drive.\n"); + MSG_Add("PROGRAM_MOUNT_ERROR_1","Directory %s does not exist.\n"); + MSG_Add("PROGRAM_MOUNT_ERROR_2","%s is not a directory\n"); + MSG_Add("PROGRAM_MOUNT_IMGMOUNT","To mount image files, use the \033[34;1mIMGMOUNT\033[0m command, not the \033[34;1mMOUNT\033[0m command.\n"); + MSG_Add("PROGRAM_MOUNT_ILL_TYPE","Illegal type %s\n"); + MSG_Add("PROGRAM_MOUNT_ALREADY_MOUNTED","Drive %c already mounted with %s\n"); + MSG_Add("PROGRAM_MOUNT_USAGE", + "Mounts directories or drives in the host system as DOSBox-X drives.\n" + "Usage: \033[34;1m\033[32;1mMOUNT\033[0m \033[37;1mdrive\033[0m \033[36;1mlocal_directory\033[0m [option]\033[0m\n" + " \033[37;1mdrive\033[0m Drive letter where the directory or drive will be mounted.\n" + " \033[36;1mlocal_directory\033[0m Local directory or drive in the host system to be mounted.\n" + " [option] Option(s) for mounting. The following options are accepted:\n" + " -t Specify the drive type the mounted drive to behave as.\n" + " Supported drive type: dir, floppy, cdrom, overlay\n" + " (Note that 'overlay' redirects writes for mounted drive to another directory)\n" + " -label [name] Set the volume label name of the drive (all upper case).\n" + " -nl Use next available drive letter if the drive is mounted.\n" + " -ro Mount the drive in read-only mode.\n" + " -pr Specify the path is relative to the config file location.\n" + " -cd Generate a list of local CD drive's \"drive #\" values.\n" + " -usecd [drive #] For direct hardware emulation such as audio playback.\n" + " -ioctl Use lowest level hardware access (following -usecd option).\n" + " -aspi Use the installed ASPI layer (following -usecd option).\n" + " -freesize [size] Specify the free disk space of drive in MB (KB for floppies).\n" + " -nocachedir Enable real-time update and do not cache the drive.\n" + " -z drive Move virtual drive Z: to a different letter.\n" + " -o Report the drive as: local, remote.\n" + " -q Quiet mode (no message output).\n" + " -u Unmount the drive.\n" + " \033[32;1m-examples Show some usage examples.\033[0m\n" + "Type MOUNT with no parameters to display a list of mounted drives."); + MSG_Add("PROGRAM_MOUNT_EXAMPLE", + "A basic example of MOUNT command:\n\n" + "\033[32;1mMOUNT c %s\033[0m\n\n" + "This makes the directory %s act as the C: drive inside DOSBox-X.\n" + "The directory has to exist in the host system. If the directory contains\n" + "space(s), be sure to properly quote the directory with double quotes,\n" + "e.g. %s\n\n" + "Some other usage examples of MOUNT:\n\n" + #if defined (WIN32) || defined(OS2) + "\033[32;1mMOUNT\033[0m - list all mounted drives\n" + "\033[32;1mMOUNT -cd\033[0m - list all local CD drives\n" + #else + "\033[32;1mMOUNT\033[0m - list all mounted drives\n" + "\033[32;1mMOUNT -cd\033[0m - list all local CD drives\n" + #endif + "\033[32;1mMOUNT d %s\033[0m - mount the D: drive to the directory\n" + "\033[32;1mMOUNT c %s -t cdrom\033[0m - mount the C: drive as a CD-ROM drive\n" + "\033[32;1mMOUNT c %s -ro\033[0m - mount the C: drive in read-only mode\n" + "\033[32;1mMOUNT c %s -label TEST\033[0m - mount the C: drive with the label TEST\n" + "\033[32;1mMOUNT c %s -nocachedir \033[0m - mount C: without caching the drive\n" + "\033[32;1mMOUNT c %s -freesize 128\033[0m - mount C: with 128MB free disk space\n" + "\033[32;1mMOUNT c %s -u\033[0m - force mount C: drive even if it's mounted\n" + "\033[32;1mMOUNT c %s -t overlay\033[0m - mount C: with overlay directory on top\n" + #if defined (WIN32) || defined(OS2) + "\033[32;1mMOUNT c -u\033[0m - unmount the C: drive\n" + #else + "\033[32;1mMOUNT c -u\033[0m - unmount the C: drive\n" + #endif + ); + MSG_Add("PROGRAM_MOUNT_UMOUNT_NOT_MOUNTED","Drive %c is not mounted.\n"); + MSG_Add("PROGRAM_MOUNT_UMOUNT_SUCCESS","Drive %c has successfully been removed.\n"); + MSG_Add("PROGRAM_MOUNT_UMOUNT_NUMBER_SUCCESS","Drive number %c has successfully been removed.\n"); + MSG_Add("PROGRAM_MOUNT_UMOUNT_NO_VIRTUAL","Virtual Drives can not be unMOUNTed.\n"); + MSG_Add("PROGRAM_MOUNT_WARNING_WIN","Warning: Mounting C:\\ is not recommended.\n"); + MSG_Add("PROGRAM_MOUNT_WARNING_OTHER","Warning: Mounting / is not recommended.\n"); + MSG_Add("PROGRAM_MOUNT_PHYSFS_ERROR","Failed to mount the PhysFS drive with the archive file.\n"); + MSG_Add("PROGRAM_MOUNT_OVERLAY_NO_BASE","Please MOUNT a normal directory first before adding an overlay on top.\n"); + MSG_Add("PROGRAM_MOUNT_OVERLAY_INCOMPAT_BASE","The overlay is NOT compatible with the drive that is specified.\n"); + MSG_Add("PROGRAM_MOUNT_OVERLAY_MIXED_BASE","The overlay needs to be specified using the same addressing as the underlying drive. No mixing of relative and absolute paths."); + MSG_Add("PROGRAM_MOUNT_OVERLAY_SAME_AS_BASE","The overlay directory can not be the same as underlying drive.\n"); + MSG_Add("PROGRAM_MOUNT_OVERLAY_ERROR","An error occurred when trying to create an overlay drive.\n"); + MSG_Add("PROGRAM_MOUNT_OVERLAY_STATUS","Overlay %s on drive %c mounted.\n"); + + MSG_Add("PROGRAM_LOADFIX_ALLOC","%d kb allocated.\n"); + MSG_Add("PROGRAM_LOADFIX_DEALLOC","%d kb freed.\n"); + MSG_Add("PROGRAM_LOADFIX_DEALLOCALL","Used memory freed.\n"); + MSG_Add("PROGRAM_LOADFIX_ERROR","Memory allocation error.\n"); + MSG_Add("PROGRAM_LOADFIX_HELP", + "Loads a program above the first 64 KB memory by reducing the available memory.\n\n" + "LOADFIX [-xms] [-ems] [-{ram}] [{program}] [{options}]\n" + "LOADFIX -f [-xms] [-ems]\n\n" + " -xms Allocates memory from XMS rather than conventional memory\n" + " -ems Allocates memory from EMS rather than conventional memory\n" + " -{ram} Specifies the amount of memory to allocate in KB\n" + " Defaults to 64KB for conventional memory; 1MB for XMS/EMS memory\n" + " -a Auto allocates enough memory to fill the lowest 64KB memory\n" + " -f (or -d) Frees previously allocated memory\n" + " {program} Runs the specified program\n" + " {options} Program options (if any)\n\n" + "Examples:\n" + " \033[32;1mLOADFIX game.exe\033[0m Allocates 64KB of conventional memory and runs game.exe\n" + " \033[32;1mLOADFIX -a\033[0m Auto-allocates enough memory conventional memory\n" + " \033[32;1mLOADFIX -128\033[0m Allocates 128KB of conventional memory\n" + " \033[32;1mLOADFIX -xms\033[0m Allocates 1MB of XMS memory\n" + " \033[32;1mLOADFIX -f\033[0m Frees allocated conventional memory\n"); + + MSG_Add("MSCDEX_SUCCESS","MSCDEX installed.\n"); + MSG_Add("MSCDEX_ERROR_MULTIPLE_CDROMS","MSCDEX: Failure: Drive-letters of multiple CD-ROM drives have to be continuous.\n"); + MSG_Add("MSCDEX_ERROR_NOT_SUPPORTED","MSCDEX: Failure: Not yet supported.\n"); + MSG_Add("MSCDEX_ERROR_PATH","MSCDEX: Specified location is not a CD-ROM drive.\n"); + MSG_Add("MSCDEX_ERROR_OPEN","MSCDEX: Failure: Invalid file or unable to open.\n"); + MSG_Add("MSCDEX_TOO_MANY_DRIVES","MSCDEX: Failure: Too many CD-ROM drives (max: 5). MSCDEX Installation failed.\n"); + MSG_Add("MSCDEX_LIMITED_SUPPORT","MSCDEX: Mounted subdirectory: limited support.\n"); + MSG_Add("MSCDEX_INVALID_FILEFORMAT","MSCDEX: Failure: File is either no ISO/CUE image or contains errors.\n"); + MSG_Add("MSCDEX_UNKNOWN_ERROR","MSCDEX: Failure: Unknown error.\n"); + + MSG_Add("PROGRAM_RESCAN_SUCCESS","Drive cache cleared.\n"); + + MSG_Add("PROGRAM_INTRO", + "\033[2J\033[32;1mWelcome to DOSBox-X\033[0m, an open-source x86 emulator with sound and graphics.\n" + "DOSBox-X creates a shell for you which looks just like the plain DOS.\n" + "\n" + "\033[31;1mDOSBox-X will stop/exit without a warning if an error occurred!\033[0m\n" + "\n" + "\n" ); + MSG_Add("PROGRAM_INTRO_MENU_UP", "DOSBox-X Introduction"); + MSG_Add("PROGRAM_INTRO_MENU_BASIC","Basic mount"); + MSG_Add("PROGRAM_INTRO_MENU_CDROM","CD-ROM support"); + MSG_Add("PROGRAM_INTRO_MENU_USAGE","Usage"); + MSG_Add("PROGRAM_INTRO_MENU_INFO","Information"); + MSG_Add("PROGRAM_INTRO_MENU_QUIT","Quit"); + MSG_Add("PROGRAM_INTRO_MENU_BASIC_HELP","\n\033[1m \033[1m\033[KMOUNT allows you to connect real hardware to DOSBox-X's emulated PC.\033[0m\n"); + MSG_Add("PROGRAM_INTRO_MENU_CDROM_HELP","\n\033[1m \033[1m\033[KTo mount your CD-ROM in DOSBox-X, you need to specify additional options\n when mounting the CD-ROM.\033[0m\n"); + MSG_Add("PROGRAM_INTRO_MENU_USAGE_HELP","\n\033[1m \033[1m\033[KAn overview of the command line options you can give to DOSBox-X.\033[0m\n"); + MSG_Add("PROGRAM_INTRO_MENU_INFO_HELP","\n\033[1m \033[1m\033[KHow to get more information about DOSBox-X.\033[0m\n"); + MSG_Add("PROGRAM_INTRO_MENU_QUIT_HELP","\n\033[1m \033[1m\033[KExit from Intro.\033[0m\n"); + MSG_Add("PROGRAM_INTRO_USAGE_TOP", + "\033[2J\033[32;1mAn overview of the command line options you can give to DOSBox-X.\033[0m\n" + "Windows users must open cmd.exe or edit the shortcut to DOSBox-X.exe for this.\n\n" + "dosbox-x [name] [-exit] [-version] [-fastlaunch] [-fullscreen]\n" + " [-conf congfigfile] [-lang languagefile] [-machine machinetype]\n" + " [-startmapper] [-noautoexec] [-scaler scaler | -forcescaler scaler]\n" + " [-o options] [-c command] [-set
]\n\n" + ); + MSG_Add("PROGRAM_INTRO_USAGE_1", + "\033[33;1m name\033[0m\n" + "\tIf name is a directory it will mount that as the C: drive.\n" + "\tIf name is an executable it will mount the directory of name\n" + "\tas the C: drive and execute name.\n\n" + "\033[33;1m -exit\033[0m\n" + "\tDOSBox-X will close itself when the DOS application name ends.\n\n" + "\033[33;1m -version\033[0m\n" + "\tOutputs version information and exit. Useful for frontends.\n\n" + "\033[33;1m -fastlaunch\033[0m\n" + "\tEnables fast launch mode (skip BIOS logo and welcome banner).\n\n" + "\033[33;1m -fullscreen\033[0m\n" + "\tStarts DOSBox-X in fullscreen mode.\n" + ); + MSG_Add("PROGRAM_INTRO_USAGE_2", + "\033[33;1m -conf\033[0m configfile\n" + "\tStart DOSBox-X with the options specified in configfile.\n" + "\tSee the documentation for more details.\n\n" + "\033[33;1m -lang\033[0m languagefile\n" + "\tStart DOSBox-X using the language specified in languagefile.\n\n" + "\033[33;1m -startmapper\033[0m\n" + "\tEnter the keymapper directly on startup. Useful for people with\n" + "\tkeyboard problems.\n\n" + "\033[33;1m -machine\033[0m machinetype\n" + "\tSetup DOSBox-X to emulate a specific type of machine. Valid choices:\n" + "\thercules, cga, cga_mono, mcga, mda, pcjr, tandy, ega, vga, vgaonly,\n" + "\tpc98, vesa_nolfb, vesa_oldvbe, svga_paradise, svga_s3 (default).\n" + "\tThe machinetype affects both the video card and available sound cards.\n" + ); + MSG_Add("PROGRAM_INTRO_USAGE_3", + "\033[33;1m -noautoexec\033[0m\n" + "\tSkips the [autoexec] section of the loaded configuration file.\n\n" + "\033[33;1m -o\033[0m options\n" + "\tProvides command-line option(s) for \"name\" if an executable name is\n" + "\tspecified. Multiple -o can be used for multiple executable names.\n\n" + "\033[33;1m -c\033[0m command\n" + "\tRuns the specified command before running name. Multiple commands\n" + "\tcan be specified. Each command should start with -c, though.\n" + "\tA command can be: an Internal Program, a DOS command or an executable\n" + "\ton a mounted drive.\n\n" + "\033[33;1m -set\033[0m
\n" + "\tSets the config option (overriding the config file). Multiple options\n" + "\tcan be specified. Each option should start with -set, though.\n" + ); + MSG_Add("PROGRAM_INTRO_INFO", + "\033[32;1mInformation:\033[0m\n\n" + "For information about basic mount, type \033[34;1mintro mount\033[0m\n" + "For information about CD-ROM support, type \033[34;1mintro cdrom\033[0m\n" + "For information about usage, type \033[34;1mintro usage\033[0m\n\n" + "For the latest version of DOSBox-X, go to its homepage:\033[34;1m\n" + "\n" + "\033[34;1mhttps://dosbox-x.com/\033[0m or \033[34;1mhttp://dosbox-x.software\033[0m\n" + "\n" + "For more information about DOSBox-X, please take a look at its Wiki:\n" + "\n" + "\033[34;1mhttps://dosbox-x.com/wiki\033[0m\n" + ); + MSG_Add("PROGRAM_INTRO_MOUNT_START", + "\033[32;1mHere are some commands to get you started:\033[0m\n" + "Before you can use the files located on your own filesystem,\n" + "you have to mount the directory containing the files.\n" + "\n" + ); + MSG_Add("PROGRAM_INTRO_MOUNT_EXST_WINDOWS", "\033[32mmount c c:\\dosgames\\\033[37m will create a C drive with c:\\dosgames as contents."); + MSG_Add("PROGRAM_INTRO_MOUNT_EXEN_WINDOWS", "c:\\dosgames\\\033[37m is an example. Replace it with your own games directory. \033[37m "); + MSG_Add("PROGRAM_INTRO_MOUNT_EXST_OTHER", "\033[32mmount c ~/dosgames\033[37m will create a C drive with ~/dosgames as contents."); + MSG_Add("PROGRAM_INTRO_MOUNT_EXEN_OTHER", "\033[32m~/dosgames\033[37m is an example. Replace it with your own games directory.\033[37m "); + MSG_Add("PROGRAM_INTRO_MOUNT_END", + "When the mount has successfully completed you can type \033[34;1mc:\033[0m to go to your freshly\n" + "mounted C: drive. Typing \033[34;1mdir\033[0m there will show its contents." + " \033[34;1mcd\033[0m will allow you to\n" + "enter a directory (recognised by the \033[33;1m[]\033[0m in a directory listing).\n" + "You can run programs/files which end with \033[31m.exe .bat\033[0m and \033[31m.com\033[0m.\n" + ); + MSG_Add("PROGRAM_INTRO_CDROM", + "\033[2J\033[32;1mHow to mount a Real/Virtual CD-ROM Drive in DOSBox-X:\033[0m\n" + "DOSBox-X provides CD-ROM emulation on several levels.\n" + "\n" + "The \033[33mbasic\033[0m level works on all CD-ROM drives and normal directories.\n" + "It installs MSCDEX and marks the files read-only.\n" + "Usually this is enough for most games:\n" + "\033[34;1mmount d \033[0;31mD:\\\033[34;1m -t cdrom\033[0m or \033[34;1mmount d C:\\example -t cdrom\033[0m\n" + "If it doesn't work you might have to tell DOSBox-X the label of the CD-ROM:\n" + "\033[34;1mmount d C:\\example -t cdrom -label CDLABEL\033[0m\n" + "\n" + "The \033[33mnext\033[0m level adds some low-level support.\n" + "Therefore only works on CD-ROM drives:\n" + "\033[34;1mmount d \033[0;31mD:\\\033[34;1m -t cdrom -usecd \033[33m0\033[0m\n" + "\n" + "The \033[33mlast\033[0m level of support depends on your Operating System:\n" + "For \033[1mWindows 2000\033[0m, \033[1mWindows XP\033[0m and \033[1mLinux\033[0m:\n" + "\033[34;1mmount d \033[0;31mD:\\\033[34;1m -t cdrom -usecd \033[33m0 \033[34m-ioctl\033[0m\n" + "For \033[1mWindows 9x\033[0m with a ASPI layer installed:\n" + "\033[34;1mmount d \033[0;31mD:\\\033[34;1m -t cdrom -usecd \033[33m0 \033[34m-aspi\033[0m\n" + "\n" + "Replace \033[0;31mD:\\\033[0m with the location of your CD-ROM.\n" + "Replace the \033[33;1m0\033[0m in \033[34;1m-usecd \033[33m0\033[0m with the number reported for your CD-ROM if you type:\n" + "\033[34;1mmount -cd\033[0m\n" + ); + MSG_Add("PROGRAM_BOOT_NOT_EXIST","Bootdisk file does not exist. Failing.\n"); + MSG_Add("PROGRAM_BOOT_NOT_OPEN","Cannot open bootdisk file. Failing.\n"); + MSG_Add("PROGRAM_BOOT_WRITE_PROTECTED","Image file is read-only! Boot in write-protected mode.\n"); + MSG_Add("PROGRAM_BOOT_PRINT_ERROR","This command boots DOSBox-X from either a floppy or hard disk image.\n\n" + "For this command, one can specify a succession of floppy disks swappable\n" + "by the menu command, and drive: specifies the mounted drive to boot from.\n" + "If no drive letter is specified, this defaults to boot from the A drive.\n" + "If no parameter is specified, it will try to boot from the current drive.\n" + "The only bootable drive letters are A, C, and D. For booting from a hard\n" + "drive (C or D), ensure the image is already mounted by \033[34;1mIMGMOUNT\033[0m command.\n\n" + "The syntax of this command is one of the following:\n\n" + "\033[34;1mBOOT [driveletter:] [-convertfat|-convertfatro|-noconvertfat]\033[0m\n\n" + "\033[34;1mBOOT diskimg1.img [diskimg2.img ...] [-L driveletter]\033[0m\n\n" + "Note: An image file with a leading colon (:) will be booted in write-protected\n" + "mode if the \"leading colon write protect image\" option is enabled.\n\n" + "Examples:\n\n" + "\033[32;1mBOOT A:\033[0m - boot from drive A: if it is mounted and bootable.\n" + "\033[32;1mBOOT :DOS.IMG\033[0m - boot from floppy image DOS.IMG in write-protected mode.\n" + ); + MSG_Add("PROGRAM_BOOT_UNABLE","Unable to boot off of drive %c.\n"); + MSG_Add("PROGRAM_BOOT_IMAGE_MOUNTED", "Floppy image(s) already mounted.\n"); + MSG_Add("PROGRAM_BOOT_IMAGE_OPEN","Opening image file: %s\n"); + MSG_Add("PROGRAM_BOOT_IMAGE_NOT_OPEN","Cannot open %s\n"); + MSG_Add("PROGRAM_BOOT_CART_WO_PCJR","PCjr cartridge found, but machine is not PCjr"); + MSG_Add("PROGRAM_BOOT_CART_LIST_CMDS","Available PCjr cartridge commandos:%s"); + MSG_Add("PROGRAM_BOOT_CART_NO_CMDS", "No PCjr cartridge commandos found"); + MSG_Add("PROGRAM_BOOT_BOOTING", "Booting from drive "); + + MSG_Add("PROGRAM_LOADROM_HELP","Loads the specified ROM image file for video BIOS or IBM BASIC.\n\nLOADROM ROM_file\n"); + MSG_Add("PROGRAM_LOADROM_HELP","Must specify ROM file to load.\n"); + MSG_Add("PROGRAM_LOADROM_SPECIFY_FILE","Must specify ROM file to load.\n"); + MSG_Add("PROGRAM_LOADROM_CANT_OPEN","ROM file not accessible.\n"); + MSG_Add("PROGRAM_LOADROM_TOO_LARGE","ROM file too large.\n"); + MSG_Add("PROGRAM_LOADROM_INCOMPATIBLE","Video BIOS not supported by machine type.\n"); + MSG_Add("PROGRAM_LOADROM_UNRECOGNIZED","ROM file not recognized.\n"); + MSG_Add("PROGRAM_LOADROM_BASIC_LOADED","BASIC ROM loaded.\n"); + MSG_Add("PROGRAM_BIOSTEST_HELP","Boots into a BIOS image for running CPU tester BIOS.\n\nBIOSTEST image_file\n"); + + MSG_Add("VHD_ERROR_OPENING", "Could not open the specified VHD file.\n"); + MSG_Add("VHD_INVALID_DATA", "The specified VHD file is corrupt and cannot be opened.\n"); + MSG_Add("VHD_UNSUPPORTED_TYPE", "The specified VHD file is of an unsupported type.\n"); + MSG_Add("VHD_ERROR_OPENING_PARENT", "The parent of the specified VHD file could not be found.\n"); + MSG_Add("VHD_PARENT_INVALID_DATA", "The parent of the specified VHD file is corrupt and cannot be opened.\n"); + MSG_Add("VHD_PARENT_UNSUPPORTED_TYPE", "The parent of the specified VHD file is of an unsupported type.\n"); + MSG_Add("VHD_PARENT_INVALID_MATCH", "The parent of the specified VHD file does not contain the expected identifier.\n"); + MSG_Add("VHD_PARENT_INVALID_DATE", "The parent of the specified VHD file has been changed and cannot be loaded.\n"); + + MSG_Add("PROGRAM_IMGMOUNT_SPECIFY_DRIVE","Must specify drive letter to mount image at.\n"); + MSG_Add("PROGRAM_IMGMOUNT_SPECIFY2","Must specify drive number (0 to %d) to mount image at (0,1=fda,fdb;2,3=hda,hdb).\n"); + /*MSG_Add("PROGRAM_IMGMOUNT_SPECIFY_GEOMETRY", + "For \033[33mCD-ROM\033[0m images: \033[34;1mIMGMOUNT drive-letter location-of-image -t iso\033[0m\n" + "\n" + "For \033[33mhardrive\033[0m images: Must specify drive geometry for hard drives:\n" + "bytes_per_sector, sectors_per_cylinder, heads_per_cylinder, cylinder_count.\n" + "\033[34;1mIMGMOUNT drive-letter location-of-image -size bps,spc,hpc,cyl\033[0m\n");*/ + MSG_Add("PROGRAM_IMGMOUNT_INVALID_IMAGE","Could not load image file.\n" + "Check that the path is correct and the image is accessible.\n"); + MSG_Add("PROGRAM_IMGMOUNT_INVALID_GEOMETRY","Could not extract drive geometry from image.\n" + "Use parameter -size bps,spc,hpc,cyl to specify the geometry.\n"); + MSG_Add("PROGRAM_IMGMOUNT_AUTODET_VALUES","Image geometry auto detection: -size %u,%u,%u,%u\n"); + MSG_Add("PROGRAM_IMGMOUNT_TYPE_UNSUPPORTED","Type \"%s\" is unsupported. Specify \"hdd\" or \"floppy\" or \"iso\".\n"); + MSG_Add("PROGRAM_IMGMOUNT_FORMAT_UNSUPPORTED","Format \"%s\" is unsupported. Specify \"fat\" or \"iso\" or \"none\".\n"); + MSG_Add("PROGRAM_IMGMOUNT_SPECIFY_FILE","Must specify image file(s) to mount.\n"); + MSG_Add("PROGRAM_IMGMOUNT_FILE_NOT_FOUND","Image file not found.\n"); + MSG_Add("PROGRAM_IMGMOUNT_DEFAULT_NOT_FOUND","Image file not found: IMGMAKE.IMG.\n"); + MSG_Add("PROGRAM_IMGMOUNT_MOUNT","To mount directories, use the \033[34;1mMOUNT\033[0m command, not the \033[34;1mIMGMOUNT\033[0m command.\n"); + MSG_Add("PROGRAM_IMGMOUNT_ALREADY_MOUNTED","Drive already mounted at that letter.\n"); + MSG_Add("PROGRAM_IMGMOUNT_ALREADY_MOUNTED_NUMBER","Drive number %d already mounted.\n"); + MSG_Add("PROGRAM_IMGMOUNT_CANT_CREATE","Cannot create drive from file.\n"); + MSG_Add("PROGRAM_IMGMOUNT_CANT_CREATE_PHYSFS","Cannot create PhysFS drive.\n"); + MSG_Add("PROGRAM_IMGMOUNT_MOUNT_NUMBER","Drive number %d mounted as %s\n"); + MSG_Add("PROGRAM_IMGMOUNT_NON_LOCAL_DRIVE", "The image must be on a host, local or network drive.\n"); + MSG_Add("PROGRAM_IMGMOUNT_MULTIPLE_NON_CUEISO_FILES", "Using multiple files is only supported for cue/iso images.\n"); + + MSG_Add("PROGRAM_IMGMOUNT_HELP", + "Mounts floppy, hard drive and optical disc images.\n" + "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m \033[36;1mfile\033[0m [-ro] [-t floppy] [-fs fat] [-size ss,s,h,c]\n" + "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m \033[36;1mfile\033[0m [-ro] [-t hdd] [-fs fat] [-size ss,s,h,c] [-ide controller]\n" + "\033[32;1mIMGMOUNT\033[0m \033[37;1mdriveNum\033[0m \033[36;1mfile\033[0m [-ro] [-fs none] [-size ss,s,h,c] [-reservecyl #]\n" + "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m \033[36;1mfile\033[0m [-t iso] [-fs iso]\n" + "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m [-t floppy] -bootcd cdDrive (or -el-torito cdDrive)\n" + "\033[32;1mIMGMOUNT\033[0m \033[37;1mdrive\033[0m -t ram -size size\n" + "\033[32;1mIMGMOUNT\033[0m -u \033[37;1mdrive|driveNum\033[0m (or \033[32;1mIMGMOUNT\033[0m \033[37;1mdrive|driveNum\033[0m \033[36;1mfile\033[0m [options] -u)\n" + " \033[37;1mdrive\033[0m Drive letter to mount the image at.\n" + " \033[37;1mdriveNum\033[0m Drive number to mount, where 0-1 are FDDs, 2-5 are HDDs.\n" + " \033[36;1mfile\033[0m Image filename(s), or \033[33;1mIMGMAKE.IMG\033[0m if not specified.\n" + " -t iso Image type is optical disc iso or cue / bin image.\n" + " -t hdd|floppy|ram Image type is hard disk (inc. VHD/HDI)|floppy|RAM drive.\n" + " -fs iso Filesystem is ISO 9660 (auto-assumed for .iso/.cue files).\n" + " -fs fat Filesystem is FAT - FAT12, FAT16 and FAT32 are supported.\n" + " -fs none Do not detect filesystem (auto-assumed for drive numbers).\n" + " -reservecyl # Report # number of cylinders less than actual in BIOS.\n" + " -ide controller Specify IDE controller (1m, 1s, 2m, 2s) to mount drive.\n" + " -size size|ss,s,h,c Specify the size in KB, or sector size and CHS geometry.\n" + " -bootcd cdDrive Specify the CD drive to load the bootable floppy from.\n" + " -o partidx=# Specify a hard disk partition number to mount as drive.\n" + " -ro Mount image(s) read-only (or leading ':' for read-only).\n" + " -u Unmount the drive or drive number.\n" + " \033[32;1m-examples Show some usage examples.\033[0m" + ); + MSG_Add("PROGRAM_IMGMOUNT_EXAMPLE", + "Some usage examples of IMGMOUNT:\n\n" + " \033[32;1mIMGMOUNT\033[0m - list mounted FAT/ISO drives & drive numbers\n" + " \033[32;1mIMGMOUNT C\033[0m - mount hard disk image \033[33;1mIMGMAKE.IMG\033[0m as C:\n" + #ifdef WIN32 + " \033[32;1mIMGMOUNT C c:\\image.img\033[0m - mount hard disk image c:\\image.img as C:\n" + " \033[32;1mIMGMOUNT D c:\\files\\game.iso\033[0m - mount CD image c:\\files\\game.iso as D:\n" + #else + " \033[32;1mIMGMOUNT C ~/image.img\033[0m - mount hard disk image ~/image.img as C:\n" + " \033[32;1mIMGMOUNT D ~/files/game.iso\033[0m - mount CD image ~/files/game.iso as D:\n" + #endif + " \033[32;1mIMGMOUNT D cdaudio.cue\033[0m - mount cue file of a cue/bin pair as CD drive\n" + " \033[32;1mIMGMOUNT 0 dos.ima\033[0m - mount floppy image dos.ima as drive number 0\n" + " (\033[33;1mBOOT A:\033[0m will boot from drive if bootable)\n" + " \033[32;1mIMGMOUNT A -ro dos.ima\033[0m - mount floppy image dos.ima as A: read-only\n" + " \033[32;1mIMGMOUNT A :dsk1.img dsk2.img\033[0m - mount floppy images dsk1.img and dsk2.img as\n" + " A:, swappable via menu item \"Swap floppy\",\n" + " with dsk1.img read-only (but not dsk2.img)\n" + " \033[32;1mIMGMOUNT A -bootcd D\033[0m - mount bootable floppy A: from CD drive D:\n" + " \033[32;1mIMGMOUNT C -t ram -size 10000\033[0m - mount hard drive C: as a 10MB RAM drive\n" + " \033[32;1mIMGMOUNT D d.img -o partidx=4\033[0m - mount 1st logical partition of d.img as D:\n" + " \033[32;1mIMGMOUNT C disk.img -u\033[0m - force mount hard disk image disk.img as C:,\n" + " auto-unmount drive beforehand if necessary\n" + " \033[32;1mIMGMOUNT A -u\033[0m - unmount previously-mounted drive A:\n" + ); + MSG_Add("PROGRAM_IMGMAKE_SYNTAX", + "Creates floppy or hard disk images.\n" + "Usage: \033[34;1mIMGMAKE [file] [-t type] [[-size size] | [-chs geometry]] [-spc] [-nofs]\033[0m\n" + " \033[34;1m[-bat] [-fat] [-fatcopies] [-rootdir] [-force]" + #ifdef WIN32 + " [-source source] [-retries #]" + #endif + "\033[0m\n" + " file: Image file to create (or \033[33;1mIMGMAKE.IMG\033[0m if not set) - \033[31;1mpath on the host\033[0m\n" + " -t: Type of image.\n" + " \033[33;1mFloppy disk templates\033[0m (names resolve to floppy sizes in KB or fd=fd_1440):\n" + " fd_160 fd_180 fd_200 fd_320 fd_360 fd_400 fd_720 fd_1200 fd_1440 fd_2880\n" + " \033[33;1mHard disk templates:\033[0m\n" + " hd_250: 250MB, hd_520: 520MB, hd_1gig: 1GB, hd_2gig: 2GB, hd_4gig: 4GB,\n" + " hd_8gig: 8GB, hd_st251: 40MB, hd_st225: 20MB (geometry from old drives)\n" + " \033[33;1mCustom hard disks:\033[0m hd vhd (requires -size or -chs)\n" + " -size: Size of a custom hard disk image in MB (vhd: up to 2088960).\n" + " -chs: Disk geometry in cylinders(1-1023),heads(1-255),sectors(1-63).\n" + " -nofs: Add this parameter if a blank image should be created.\n" + " -force: Overwrite existing image file. -chs / -lba: Choose C/H/S or LBA.\n" + " -bat: Create a .bat file with the IMGMOUNT command required for this image.\n" + " -fat: Type (12, 16, or 32). -fatcopies: FAT table copies.\n" + " -spc: Sectors per cluster (must be power of 2). -label Drive label.\n" + " -rootdir: Root directory entries. -partofs: Start of hd partition.\n" + " -align: Align filesystem structures. In sectors, or add 'K' suffix for KB.\n" + #ifdef WIN32 + " -source: drive letter - if specified the image is read from a floppy disk.\n" + " -retries: how often to retry when attempting to read a bad floppy disk(1-99).\n" + #endif + " \033[32;1m-examples: Show some usage examples.\033[0m" + ); + MSG_Add("PROGRAM_IMGMAKE_EXAMPLE", + "Some usage examples of IMGMAKE:\n\n" + " \033[32;1mIMGMAKE -t fd\033[0m - create a 1.44MB floppy image \033[33;1mIMGMAKE.IMG\033[0m\n" + " \033[32;1mIMGMAKE -t fd_1440 -force\033[0m - force to create a floppy image \033[33;1mIMGMAKE.IMG\033[0m\n" + " \033[32;1mIMGMAKE dos.img -t fd_2880\033[0m - create a 2.88MB floppy image named dos.img\n" + " \033[32;1mIMGMAKE new.vhd -t vhd -size 520\033[0m- create a 520MB Dynamic VHD named new.vhd\n" + #ifdef WIN32 + " \033[32;1mIMGMAKE c:\\disk.img -t hd -size 50\033[0m - create a 50MB HDD image c:\\disk.img\n" + " \033[32;1mIMGMAKE c:\\disk.img -t hd_520 -nofs\033[0m - create a 520MB blank HDD image\n" + " \033[32;1mIMGMAKE c:\\disk.img -t hd_2gig -fat 32\033[0m - create a 2GB FAT32 HDD image\n" + " \033[32;1mIMGMAKE c:\\disk.img -t hd -chs 130,2,17\033[0m - create a HDD image of specified CHS\n" + " \033[32;1mIMGMAKE c:\\disk.img -source a\033[0m - read image from physical drive A:\n" + #else + " \033[32;1mIMGMAKE ~/disk.img -t hd -size 50\033[0m - create a 50MB HDD image ~/disk.img\n" + " \033[32;1mIMGMAKE ~/disk.img -t hd_520 -nofs\033[0m - create a 520MB blank HDD image\n" + " \033[32;1mIMGMAKE ~/disk.img -t hd_2gig -fat 32\033[0m - create a 2GB FAT32 HDD image\n" + " \033[32;1mIMGMAKE ~/disk.img -t hd -chs 130,2,17\033[0m - create a HDD image of specified CHS\n" + #endif + ); + + #ifdef WIN32 + MSG_Add("PROGRAM_IMGMAKE_FLREAD", + "Disk geometry: %d Cylinders, %d Heads, %d Sectors, %d Kilobytes\n\n"); + MSG_Add("PROGRAM_IMGMAKE_FLREAD2", + "%s =good, %s =good after retries, ! =CRC error, x =sector not found, ? =unknown\n\n"); + #endif + MSG_Add("PROGRAM_IMGMAKE_FILE_EXISTS","The file \"%s\" already exists. You can specify \"-force\" to overwrite.\n"); + MSG_Add("PROGRAM_IMGMAKE_CANNOT_WRITE","The file \"%s\" cannot be opened for writing.\n"); + MSG_Add("PROGRAM_IMGMAKE_NOT_ENOUGH_SPACE","Not enough space available for the image file. Need %llu bytes.\n"); + MSG_Add("PROGRAM_IMGMAKE_PRINT_CHS","Creating image file \"%s\" with %u cylinders, %u heads and %u sectors\n"); + MSG_Add("PROGRAM_IMGMAKE_CANT_READ_FLOPPY","\n\nUnable to read floppy."); + MSG_Add("PROGRAM_IMGMAKE_BADSIZE","Wrong -size or -chs arguments.\n"); + + MSG_Add("PROGRAM_KEYB_INFO","Codepage %i has been loaded\n"); + MSG_Add("PROGRAM_KEYB_INFO_LAYOUT","Codepage %i has been loaded for layout %s\n"); + MSG_Add("PROGRAM_KEYB_SHOWHELP","Configures a keyboard for a specific language.\n\n" + "Usage: \033[32;1mKEYB\033[0m [keyboard layout ID [codepage number [codepage file]]]\n" + " layout ID Name of layout or keyboard file (.kl) to load\n" + " codepage number Number of codepage to load\n" + " codepage file .cpi/.cpx file including specified codepage information\n" + " (.kl, .cpi/.cpx files shall be placed under the directory where dosbox-x\n" + " executable exists.)\n\n" + "Some examples:\n" + " \033[32;1mKEYB\033[0m Display currently loaded codepage.\n" + " \033[32;1mKEYB sp\033[0m Load the Spanish (SP) layout, use an appropriate codepage.\n" + " \033[32;1mKEYB sp 850\033[0m Load the Spanish (SP) layout, use codepage 850.\n" + " \033[32;1mKEYB sp 850 mycp.cpi\033[0m Same as above, but use file mycp.cpi.\n" + " \033[32;1mKEYB sp_mod 850\033[0m Load keyboard layout from sp_mod.kl, use codepage 850.\n"); + MSG_Add("PROGRAM_KEYB_NOERROR","Keyboard layout %s loaded for codepage %i\n"); + MSG_Add("PROGRAM_KEYB_FILENOTFOUND","Keyboard file %s not found (or not a valid ID)\n\n"); + MSG_Add("PROGRAM_KEYB_INVALIDFILE","Keyboard file %s invalid\n"); + MSG_Add("PROGRAM_KEYB_LAYOUTNOTFOUND","No layout in %s for codepage %i\n"); + MSG_Add("PROGRAM_KEYB_INVCPFILE","None or invalid codepage file for layout %s\n\n"); + MSG_Add("INT21_6523_YESNO_CHARS", "yn"); + MSG_Add("PROGRAM_LABEL_HELP", "Creates, changes, or deletes the volume label of a drive.\n\nLABEL [drive:][label]\n\n [drive:]\tSpecifies the drive letter\n [label]\tSpecifies the volume label\n"); + MSG_Add("PROGRAM_LABEL_DELETE", "Delete the volume label (Y/N)? "); + MSG_Add("PROGRAM_LABEL_TOOLONG", "Label is too long (more than 11 characters).\n"); + MSG_Add("PROGRAM_LABEL_BADCHARS", "Label has invalid characters.\n"); + MSG_Add("PROGRAM_LABEL_VOLUMEIS", "Volume in drive %c is %s\n"); + MSG_Add("PROGRAM_LABEL_NOLABEL", "Volume in drive %c has no label\n"); + MSG_Add("PROGRAM_MODE_USAGE","Configures system devices.\n\n" + "\033[34;1mMODE\033[0m display-type :display-type codes are " + "\033[1mCO80\033[0m, \033[1mBW80\033[0m, \033[1mCO40\033[0m, \033[1mBW40\033[0m, or \033[1mMONO\033[0m\n" + "\033[34;1mMODE CON COLS=\033[0mc \033[34;1mLINES=\033[0mn :columns and lines, c=80 or 132, n=25, 43, 50, or 60\n" + "\033[34;1mMODE CON RATE=\033[0mr \033[34;1mDELAY=\033[0md :typematic rates, r=1-32 (32=fastest), d=1-4 (1=lowest)\n"); + MSG_Add("PROGRAM_MODE_INVALID_PARAMETERS","Invalid parameter(s).\n"); + MSG_Add("PROGRAM_PORT_INVALID_NUMBER","Must specify a port number between 1 and 9.\n"); + MSG_Add("PROGRAM_VHDMAKE_WRITERR", "Could not write to new VHD image \"%s\", aborting.\n"); + MSG_Add("PROGRAM_VHDMAKE_REMOVEERR", "Could not erase file \"%s\"\n"); + MSG_Add("PROGRAM_VHDMAKE_RENAME", "You'll have to manually rename the newly created VHD image.\n"); + MSG_Add("PROGRAM_VHDMAKE_SUCCESS", "New VHD image successfully created. You can mount it with \033[34;1mIMGMOUNT\033[0m.\n"); + MSG_Add("PROGRAM_VHDMAKE_ERROPEN", "Error, could not open image file \"%s\".\n"); + MSG_Add("PROGRAM_VHDMAKE_BADSIZE", "Bad VHD size specified, aborting!\n"); + MSG_Add("PROGRAM_VHDMAKE_FNEEDED", "A pre-existing VHD image can't be silently overwritten without -f option!\n"); + MSG_Add("PROGRAM_VHDMAKE_BADPARENT", "The parent VHD image \"%s\" can't be opened for linking, aborting!\n"); + MSG_Add("PROGRAM_VHDMAKE_NOINFO", "Couldn't query info for \"%s\".\n"); + MSG_Add("PROGRAM_VHDMAKE_BLOCKSTATS", " with %d/%d blocks allocated.\n"); + MSG_Add("PROGRAM_VHDMAKE_INFO", "VHD \"%s\" type is %s.\nIts virtual size is %.02f MB"); + MSG_Add("PROGRAM_VHDMAKE_CANTMERGE", "%s is not a Differencing disk, can't merge!\n"); + MSG_Add("PROGRAM_VHDMAKE_MERGEREPORT", "%d sectors in %d blocks from \"%s\" merged into \"%s\".\n"); + MSG_Add("PROGRAM_VHDMAKE_MERGENODELETE", "Couldn't remove snapshot \"%s\", you'll have to do it yourself!"); + MSG_Add("PROGRAM_VHDMAKE_MERGEOKDELETE", "Snapshot VHD merged and deleted.\n"); + MSG_Add("PROGRAM_VHDMAKE_MERGEFAILED", "Failure while merging, aborted!\n"); + MSG_Add("PROGRAM_VHDMAKE_MERGEWARNCORRUPTION", " Parent \"%s\" contents could be corrupted!\n"); + MSG_Add("PROGRAM_VHDMAKE_ABSPATH", "Warning: an absolute path to parent prevents portability.\nPlease prefer a path relative to the differencing image file!\n"); + MSG_Add("PROGRAM_VHDMAKE_HELP", + "Creates Dynamic or Differencing VHD images, converts raw images into Fixed VHD,\n" + "shows information about VHD images and merges them.\n" + "\033[32;1mVHDMAKE\033[0m [-f] new.vhd size[BKMGT]\n" + "\033[32;1mVHDMAKE\033[0m \033[34;1m-convert\033[0m raw.hdd new.vhd\n" + "\033[32;1mVHDMAKE\033[0m [-f] \033[34;1m-link\033[0m parent.vhd new.vhd\n" + "\033[32;1mVHDMAKE\033[0m \033[34;1m-merge\033[0m delta.vhd\n" + "\033[32;1mVHDMAKE\033[0m \033[34;1m-info\033[0m a.vhd\n" + " -c | -convert convert a raw hd image to Fixed VHD, renaming it to new.vhd\n" + " -l | -link create a new Differencing VHD new.vhd and link it to the\n" + " pre-existing parent image parent.vhd\n" + " -f | -force force overwriting a pre-existing image file\n" + " -i | -info show useful information about a.vhd image\n" + " -m | -merge merge differencing delta.vhd to its parent\n" + " new.vhd name of the new Dynamic VHD image to create\n" + " size disk size (eventually with size unit, Bytes is implicit)\n" + "When converting a raw disk image to Fixed VHD, it has to be partitioned with\n" + "MBR scheme and formatted with FAT format.\n" + "When creating a Dynamic VHD, its size must range from 3 MB to 2040 GB.\n" + "The Dynamic VHD created is not partitioned nor formatted: to directly mount to\n" + "a drive letter with \033[34;1mIMGMOUNT\033[0m, please consider using \033[34;1mIMGMAKE\033[0m instead.\n" + "A merged snapshot VHD is automatically deleted if merge is successful.\n"); + + const Section_prop * dos_section=static_cast(control->GetSection("dos")); + hidefiles = dos_section->Get_string("drive z hide files"); + + /*regular setup*/ + Add_VFiles(false); + + #if WIN32 + if (dos_section->Get_bool("automount drive directories")) { + Add_Existing_Drive_Directories(); + } + #endif + } + \ No newline at end of file diff --git a/src/dos/drive_fat.cpp b/src/dos/drive_fat.cpp index be7e2c9c0e5..69f12875b32 100644 --- a/src/dos/drive_fat.cpp +++ b/src/dos/drive_fat.cpp @@ -47,6 +47,8 @@ #define FAT16 1 #define FAT32 2 +extern bool _driveUsed; + static uint16_t dpos[256]; static uint32_t dnum[256]; extern bool wpcolon, force_sfn; @@ -353,6 +355,7 @@ void fatFile::Flush(void) { } bool fatFile::Read(uint8_t * data, uint16_t *size) { + _driveUsed = true; if ((this->flags & 0xf) == OPEN_WRITE) { // check if file opened in write-only mode DOS_SetError(DOSERR_ACCESS_DENIED); return false; @@ -406,6 +409,7 @@ bool fatFile::Read(uint8_t * data, uint16_t *size) { } bool fatFile::Write(const uint8_t * data, uint16_t *size) { + _driveUsed = true; if ((this->flags & 0xf) == OPEN_READ) { // check if file opened in read-only mode DOS_SetError(DOSERR_ACCESS_DENIED); return false; @@ -531,6 +535,7 @@ bool fatFile::Write(const uint8_t * data, uint16_t *size) { } bool fatFile::Seek(uint32_t *pos, uint32_t type) { + _driveUsed = true; int32_t seekto=0; switch(type) { @@ -563,6 +568,7 @@ bool fatFile::Seek(uint32_t *pos, uint32_t type) { } bool fatFile::Close() { + _driveUsed = true; /* Flush buffer */ if (loadedSector) myDrive->writeSector(currentSector, sectorBuffer); @@ -808,6 +814,7 @@ void fatDrive::UpdateBootVolumeLabel(const char *label) { } void fatDrive::SetLabel(const char *label, bool /*iscdrom*/, bool /*updatable*/) { + _driveUsed = true; if (unformatted) return; direntry sectbuf[MAX_DIRENTS_PER_SECTOR]; /* 16 directory entries per 512 byte sector */ @@ -1054,6 +1061,7 @@ bool fatDrive::getDirClustNum(const char *dir, uint32_t *clustNum, bool parDir) (instead of fatDrive's, which can differ), VHD access works fine, and RAW images keep working. 2023.05.11 - maxpat78 */ uint8_t fatDrive::readSector(uint32_t sectnum, void * data) { + _driveUsed = true; if (absolute) return Read_AbsoluteSector(sectnum, data); assert(!IS_PC98_ARCH); #ifdef OLD_CHS_CONVERSION @@ -1073,6 +1081,7 @@ uint8_t fatDrive::readSector(uint32_t sectnum, void * data) { } uint8_t fatDrive::writeSector(uint32_t sectnum, void * data) { + _driveUsed = true; if (absolute) return Write_AbsoluteSector(sectnum, data); assert(!IS_PC98_ARCH); #ifdef OLD_CHS_CONVERSION @@ -1353,9 +1362,41 @@ fatDrive::fatDrive(const char* sysFilename, uint32_t bytesector, uint32_t cylsec std::vector::iterator it = std::find(options.begin(), options.end(), "readonly"); bool roflag = it!=options.end(); readonly = wpcolon&&strlen(sysFilename)>1&&sysFilename[0]==':'; + const char *fname=readonly?sysFilename+1:sysFilename; diskfile = fopen_lock(fname, readonly||roflag?"rb":"rb+", readonly); - if (!diskfile) {created_successfully = false;return;} + + const char *ext = strrchr(sysFilename,'.'); + bool is_hdd = false; + if((ext != NULL) && (!strcasecmp(ext, ".hdi") || !strcasecmp(ext, ".nhd"))) is_hdd = true; + + if (!diskfile) + { + // Try with memfiles -- These are always opened as rw + readonly = false; + jaffarCommon::file::MemoryFile *memfile = _memFileDirectory.fopen(fname, "rb+"); + + if (memfile == NULL) + { + created_successfully = false; + return; + } + + jaffarCommon::file::MemoryFile::fseeko64(memfile, 0L, SEEK_SET); + size_t readResult = jaffarCommon::file::MemoryFile::fread(bootcode,256,1,memfile); // look for magic signatures + if (readResult != 1) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in fatDrive constructor\n"); + return; + } + + jaffarCommon::file::MemoryFile::fseeko64(memfile, 0L, SEEK_END); + filesize = (uint32_t)(jaffarCommon::file::MemoryFile::ftello64(memfile) / 1024L); + loadedDisk = new imageDisk_Mem(memfile, fname, filesize, (is_hdd | (filesize > 2880))); + fatDriveInit(sysFilename, bytesector, cylsector, headscyl, cylinders, filesize, options); + + return; + } + opts.bytesector = bytesector; opts.cylsector = cylsector; opts.headscyl = headscyl; @@ -1387,11 +1428,6 @@ fatDrive::fatDrive(const char* sysFilename, uint32_t bytesector, uint32_t cylsec LOG(LOG_IO, LOG_ERROR) ("Reading error in fatDrive constructor\n"); return; } - - const char *ext = strrchr(sysFilename,'.'); - bool is_hdd = false; - if((ext != NULL) && (!strcasecmp(ext, ".hdi") || !strcasecmp(ext, ".nhd"))) is_hdd = true; - if (ext != NULL && !strcasecmp(ext, ".d88")) { fseeko64(diskfile, 0L, SEEK_END); filesize = (uint32_t)(ftello64(diskfile) / 1024L); @@ -1458,6 +1494,7 @@ fatDrive::fatDrive(imageDisk *sourceLoadedDisk, std::vector &option } uint8_t fatDrive::Read_AbsoluteSector(uint32_t sectnum, void * data) { + _driveUsed = true; if (loadedDisk != NULL) { /* this will only work if the logical sector size is larger than the disk sector size */ const unsigned int lsz = loadedDisk->getSectSize(); @@ -1481,6 +1518,7 @@ uint8_t fatDrive::Read_AbsoluteSector(uint32_t sectnum, void * data) { } uint8_t fatDrive::Write_AbsoluteSector(uint32_t sectnum, void * data) { + _driveUsed = true; if (loadedDisk != NULL) { /* this will only work if the logical sector size is larger than the disk sector size */ const unsigned int lsz = loadedDisk->getSectSize(); @@ -2533,7 +2571,6 @@ bool fatDrive::FileCreate(DOS_File **file, const char *name, uint16_t attributes DOS_SetError(DOSERR_ACCESS_DENIED); return false; } - /* Check if file already exists */ if(getFileDirEntry(name, &fileEntry, &dirClust, &subEntry, true/*dirOk*/)) { /* You can't create/truncate a directory! */ @@ -2547,6 +2584,7 @@ bool fatDrive::FileCreate(DOS_File **file, const char *name, uint16_t attributes const uint32_t chk = BPB.is_fat32() ? fileEntry.Cluster32() : fileEntry.loFirstClust; if(chk != 0) deleteClustChain(chk, 0); } + /* Update directory entry */ fileEntry.entrysize=0; fileEntry.SetCluster32(0); @@ -2588,7 +2626,8 @@ bool fatDrive::FileCreate(DOS_File **file, const char *name, uint16_t attributes fileEntry.modDate = cd; } fileEntry.attrib = (uint8_t)(attributes & 0xff); - addDirectoryEntry(dirClust, fileEntry, lfn); + if (addDirectoryEntry(dirClust, fileEntry, lfn) == false) return false; + /* Check if file exists now */ if(!getFileDirEntry(name, &fileEntry, &dirClust, &subEntry)) return false; diff --git a/src/dos/drive_iso.cpp b/src/dos/drive_iso.cpp index 888a43c6bc0..b9167cc9096 100644 --- a/src/dos/drive_iso.cpp +++ b/src/dos/drive_iso.cpp @@ -34,6 +34,7 @@ #define FLAGS1 ((iso) ? de.fileFlags : de.timeZone) #define FLAGS2 ((iso) ? de->fileFlags : de->timeZone) +extern bool _driveUsed; char fullname[LFN_NAMELENGTH]; static uint16_t sdid[256]; extern int lfn_filefind_handle; @@ -1737,6 +1738,7 @@ bool isoDrive::ReadCachedSector(uint8_t** buffer, const uint32_t sector) { } inline bool isoDrive :: readSector(uint8_t *buffer, uint32_t sector) const { + _driveUsed = true; if(CDROM_Interface_Image::images[subUnit] == nullptr) return false; return CDROM_Interface_Image::images[subUnit]->ReadSector(buffer, false, sector); } @@ -2095,7 +2097,7 @@ bool isoDrive :: loadImage() { unsigned int choose_iso9660 = 0; unsigned int choose_joliet = 0; unsigned int sector = 16; - + is_rock_ridge = false; is_udf = false; dataCD = false; @@ -2117,6 +2119,7 @@ bool isoDrive :: loadImage() { while (sector < 256) { pvd[0] = 0xFF; readSector(pvd,sector); + // printf("CD Signature: %u %u %u %u %u %u %u\n", pvd[0], pvd[1], pvd[2], pvd[3], pvd[4], pvd[5], pvd[6]); if (pvd[0] == 1) { // primary volume if (!strncmp((char*)(&pvd[1]), "CD001", 5) && pvd[6] == 1) { diff --git a/src/dos/drive_local.cpp b/src/dos/drive_local.cpp index ff5cb8ccfec..0f8d7052547 100644 --- a/src/dos/drive_local.cpp +++ b/src/dos/drive_local.cpp @@ -38,6 +38,7 @@ #include #endif #include +#include #include "dosbox.h" #include "dos_inc.h" diff --git a/src/dosbox.cpp b/src/dosbox.cpp index 4bb6011f124..eb9df3aaa4f 100644 --- a/src/dosbox.cpp +++ b/src/dosbox.cpp @@ -79,6 +79,11 @@ #include "parport.h" #include "keyboard.h" #include "clockdomain.h" +#include "libco.h" + +extern cothread_t _driverCoroutine; + +extern void _Delay(uint32_t ticks); #if C_EMSCRIPTEN # include @@ -410,7 +415,7 @@ extern bool DOSBox_Paused(), isDBCSCP(), InitCodePage(); //#define DEBUG_CYCLE_OVERRUN_CALLBACK //For trying other delays -#define wrap_delay(a) SDL_Delay(a) +#define wrap_delay(a) _Delay(a) static Uint32 SDL_ticks_last = 0,SDL_ticks_next = 0; @@ -498,11 +503,13 @@ static Bitu Normal_Loop(void) { #endif } else { GFX_Events(); + if (DOSBox_Paused() == false && ticksRemain > 0) { TIMER_AddTick(); ticksRemain--; } else { increaseticks(); + co_switch(_driverCoroutine); return 0; } } @@ -545,6 +552,7 @@ static Bitu Normal_Loop(void) { throw; } } + return 0; } @@ -562,6 +570,7 @@ void increaseticks() { //Make it return ticksRemain and set it in the function a return; } uint32_t ticksNew = GetTicks(); + // printf("TicksNew: %d, TicksLast: %d\n", ticksNew, ticksLast); ticksScheduled += ticksAdded; if (ticksNew <= ticksLast) { //lower should not be possible, only equal. diff --git a/src/gui/menu_callback.cpp b/src/gui/menu_callback.cpp index 4f9a62781d7..73c9fce0a69 100644 --- a/src/gui/menu_callback.cpp +++ b/src/gui/menu_callback.cpp @@ -472,12 +472,12 @@ bool drive_saveimg_menu_callback(DOSBoxMenu * const menu,DOSBoxMenu::item * cons } #if !defined(HX_DOS) - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - if(getcwd(Temp_CurrentDir, 512) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("drive_saveimg_menu_callback failed to get the current working directory."); - return false; - } + // if(getcwd(Temp_CurrentDir, 512) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("drive_saveimg_menu_callback failed to get the current working directory."); + // return false; + // } std::string cwd = std::string(Temp_CurrentDir)+CROSS_FILESPLIT; const char *lFilterPatterns[] = {IS_PC98_ARCH?"*.hdi":"*.img",IS_PC98_ARCH?"*.HDI":"*.hdi"}; const char *lFilterDescription = IS_PC98_ARCH ? "Disk image (*.hdi)" : "Disk image (*.img)"; @@ -1473,12 +1473,12 @@ bool vid_select_glsl_shader_menu_callback(DOSBoxMenu* const menu, DOSBoxMenu::it //Prop_path *sh = section->Get_path("glshader"); #if !defined(HX_DOS) - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - if(getcwd(Temp_CurrentDir, 512) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("vid_select_glsl_shader_menu_callback failed to get the current working directory."); - return false; - } + // if(getcwd(Temp_CurrentDir, 512) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("vid_select_glsl_shader_menu_callback failed to get the current working directory."); + // return false; + // } struct stat st; std::string cwd = std::string(Temp_CurrentDir)+CROSS_FILESPLIT+"glshaders"+CROSS_FILESPLIT; # if defined(MACOSX) @@ -1567,12 +1567,12 @@ bool vid_select_ttf_font_menu_callback(DOSBoxMenu* const menu, DOSBoxMenu::item* (void)menuitem;//UNUSED #if !defined(HX_DOS) - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - if(getcwd(Temp_CurrentDir, 512) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("vid_select_ttf_font_menu_callback failed to get the current working directory."); - return false; - } + // if(getcwd(Temp_CurrentDir, 512) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("vid_select_ttf_font_menu_callback failed to get the current working directory."); + // return false; + // } std::string cwd = std::string(Temp_CurrentDir)+CROSS_FILESPLIT; const char *lFilterPatterns[] = {"*.ttf","*.TTF","*.ttc","*.TTC","*.otf","*.OTF","*.fon","*.FON"}; const char *lFilterDescription = "TrueType font files (*.ttf, *.ttc, *.otf, *.fon)"; @@ -1754,12 +1754,12 @@ void Load_mapper_file() { assert(section != NULL); #if !defined(HX_DOS) - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - if(getcwd(Temp_CurrentDir, 512) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("Load_mapper_file failed to get the current working directory."); - return; - } + // if(getcwd(Temp_CurrentDir, 512) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("Load_mapper_file failed to get the current working directory."); + // return; + // } std::string cwd = std::string(Temp_CurrentDir)+CROSS_FILESPLIT; const char *lFilterPatterns[] = {"*.map","*.MAP"}; const char *lFilterDescription = "Mapper files (*.map)"; @@ -1807,12 +1807,12 @@ void Load_mapper_file() { void Restart_config_file() { #if !defined(HX_DOS) - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - if(getcwd(Temp_CurrentDir, 512) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("Restart_config_file failed to get the current working directory."); - return; - } + // if(getcwd(Temp_CurrentDir, 512) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("Restart_config_file failed to get the current working directory."); + // return; + // } std::string cwd = std::string(Temp_CurrentDir)+CROSS_FILESPLIT; const char *lFilterPatterns[] = {"*.conf","*.CONF","*.cfg","*.CFG"}; const char *lFilterDescription = "DOSBox-X config files (*.conf, *.cfg)"; @@ -1848,12 +1848,12 @@ void Restart_config_file() { void Load_language_file() { #if !defined(HX_DOS) - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - if(getcwd(Temp_CurrentDir, 512) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("Load_language_file failed to get the current working directory."); - return; - } + // if(getcwd(Temp_CurrentDir, 512) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("Load_language_file failed to get the current working directory."); + // return; + // } struct stat st; std::string res_path, exepath = GetDOSBoxXPath(); std::string cwd = std::string(Temp_CurrentDir)+CROSS_FILESPLIT+"languages"+CROSS_FILESPLIT; @@ -2412,12 +2412,12 @@ bool save_logas_menu_callback(DOSBoxMenu * const menu,DOSBoxMenu::item * const m (void)menu;//UNUSED (void)menuitem;//UNUSED #if !defined(HX_DOS) - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - if(getcwd(Temp_CurrentDir, 512) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("save_logas_menu_callback failed to get the current working directory."); - return false; - } + // if(getcwd(Temp_CurrentDir, 512) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("save_logas_menu_callback failed to get the current working directory."); + // return false; + // } std::string cwd = std::string(Temp_CurrentDir)+CROSS_FILESPLIT; const char *lFilterPatterns[] = {"*.log","*.LOG"}; const char *lFilterDescription = "Log files (*.log)"; @@ -2692,12 +2692,12 @@ bool browse_save_file_menu_callback(DOSBoxMenu * const menu, DOSBoxMenu::item * if (!strcmp(mname, "browsesavefile")&&!use_save_file) return false; #if !defined(HX_DOS) - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - if(getcwd(Temp_CurrentDir, 512) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("browse_save_file_menu_callback failed to get the current working directory."); - return false; - } + // if(getcwd(Temp_CurrentDir, 512) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("browse_save_file_menu_callback failed to get the current working directory."); + // return false; + // } const char *lFilterPatterns[] = {"*.sav","*.SAV"}; const char *lFilterDescription = "Save files (*.sav)"; char const * lTheSaveFileName = tinyfd_saveFileDialog("Select a save file","",2,lFilterPatterns,lFilterDescription); diff --git a/src/gui/midi.cpp b/src/gui/midi.cpp index 16a02c803ba..118028b69d1 100644 --- a/src/gui/midi.cpp +++ b/src/gui/midi.cpp @@ -128,6 +128,8 @@ static struct { #endif +extern void _Delay(uint32_t ticks); + //#define WIN32_MIDI_STATE_DEBUG @@ -512,7 +514,7 @@ void MIDI_State_LoadMessage() void MIDI_RawOutByte(uint8_t data) { if (midi.sysex.start) { uint32_t passed_ticks = GetTicks() - midi.sysex.start; - if (passed_ticks < midi.sysex.delay) SDL_Delay((Uint32)(midi.sysex.delay - passed_ticks)); + if (passed_ticks < midi.sysex.delay) _Delay((Uint32)(midi.sysex.delay - passed_ticks)); } /* Test for a realtime MIDI message */ diff --git a/src/gui/midi_timidity.h b/src/gui/midi_timidity.h index e854a7cea2d..e2b4b74fddd 100644 --- a/src/gui/midi_timidity.h +++ b/src/gui/midi_timidity.h @@ -33,6 +33,8 @@ #define BUF_HIGH_SYNC 0.8 #endif +extern void _Delay(uint32_t ticks); + /* default host & port */ #define DEFAULT_TIMIDITY_HOST "127.0.0.1" #define DEFAULT_TIMIDITY_PORT 7777 @@ -312,7 +314,7 @@ int MidiHandler_timidity::timidity_sync(int centsec) { sleep_usec = (unsigned long)(atof(res + 4) * 1000000); if (sleep_usec > 0) - SDL_Delay (sleep_usec / 1000); + _Delay (sleep_usec / 1000); return 0; } diff --git a/src/gui/render.cpp b/src/gui/render.cpp index 4c0c5e8c276..0f1bc2b9174 100644 --- a/src/gui/render.cpp +++ b/src/gui/render.cpp @@ -390,6 +390,8 @@ void AspectRatio_mapper_shortcut(bool pressed) { void VGA_DebugOverlay(); + +extern void doRenderUpdateCallback(); void RENDER_EndUpdate( bool abort ) { if (GCC_UNLIKELY(!render.updating)) return; @@ -420,6 +422,7 @@ void RENDER_EndUpdate( bool abort ) { flags, fps, (uint8_t *)&scalerSourceCache, (uint8_t*)&render.pal.rgb ); } if ( render.scale.outWrite ) { + doRenderUpdateCallback(); GFX_EndUpdate( abort? NULL : Scaler_ChangedLines ); render.frameskip.hadSkip[render.frameskip.index] = 0; } else { @@ -432,7 +435,11 @@ void RENDER_EndUpdate( bool abort ) { #endif // Force output to update the screen even if nothing changed... // works only with Direct3D output (GFX_StartUpdate() was probably not even called) - if (RENDER_GetForceUpdate()) GFX_EndUpdate(nullptr); + if (RENDER_GetForceUpdate()) + { + doRenderUpdateCallback(); + GFX_EndUpdate(nullptr); + } } render.frameskip.index = (render.frameskip.index + 1) & (RENDER_SKIP_CACHE - 1); render.updating=false; diff --git a/src/gui/sdl_gui.cpp b/src/gui/sdl_gui.cpp index 61fb1893438..ecf184a37b8 100644 --- a/src/gui/sdl_gui.cpp +++ b/src/gui/sdl_gui.cpp @@ -77,6 +77,8 @@ static DOSBoxMenu guiMenu, nullMenu; #endif +extern void _Delay(uint32_t ticks); + /* helper class for command execution */ class VirtualBatch : public BatchFile { public: @@ -250,7 +252,7 @@ static GUI::ScreenSDL *UI_Startup(GUI::ScreenSDL *screen) { KEYBOARD_ClrBuffer();//Clear buffer } GFX_LosingFocus();//Release any keys pressed (buffer gets filled again). (could be in above if, but clearing the mapper input when exiting the mapper is sensible as well - SDL_Delay(20); + _Delay(20); unsigned int cpbak = dos.loaded_codepage; if (dos_kernel_disabled&&maincp) dos.loaded_codepage = maincp; @@ -414,7 +416,7 @@ static GUI::ScreenSDL *UI_Startup(GUI::ScreenSDL *screen) { SDL_Window* GFX_GetSDLWindow(void); SDL_UpdateWindowSurface(GFX_GetSDLWindow()); while (SDL_PollEvent(&event)); - SDL_Delay(40); + _Delay(40); } SDL_SetSurfaceBlendMode(screenshot, SDL_BLENDMODE_NONE); } @@ -432,7 +434,7 @@ static GUI::ScreenSDL *UI_Startup(GUI::ScreenSDL *screen) { SDL_BlitSurface(screenshot, NULL, sdlscreen, NULL); SDL_UpdateRect(sdlscreen, 0, 0, 0, 0); while (SDL_PollEvent(&event)); - SDL_Delay(40); + _Delay(40); } } #endif @@ -553,7 +555,7 @@ static void UI_Shutdown(GUI::ScreenSDL *screen) { SDL_Window* GFX_GetSDLWindow(void); SDL_UpdateWindowSurface(GFX_GetSDLWindow()); while (SDL_PollEvent(&event)); - SDL_Delay(40); + _Delay(40); } SDL_SetSurfaceBlendMode(screenshot, SDL_BLENDMODE_NONE); } @@ -571,7 +573,7 @@ static void UI_Shutdown(GUI::ScreenSDL *screen) { SDL_BlitSurface(screenshot, NULL, sdlscreen, NULL); SDL_UpdateRect(sdlscreen, 0, 0, 0, 0); while (SDL_PollEvent(&event)) {} - SDL_Delay(40); + _Delay(40); } } #endif @@ -1039,7 +1041,7 @@ class PropertyEditorHex : public PropertyEditor { bool prepare(std::string &buffer) override { int val; convert(input->getText(), val, false, std::hex); - if ((Hex)val == prop->GetValue()) return false; + if ((Value)val == prop->GetValue()) return false; buffer.append(stringify(val, std::hex)); return true; } @@ -3004,9 +3006,9 @@ class MakeDiskImage : public GUI::ToplevelWindow { #if defined(HX_DOS) char const * lTheSaveFileName = "IMGMAKE.IMG"; #else - char CurrentDir[512]; + char CurrentDir[512] = "."; char * Temp_CurrentDir = CurrentDir; - getcwd(Temp_CurrentDir, 512); + // getcwd(Temp_CurrentDir, 512); const char *lFilterPatterns[] = {"*.img","*.IMG"}; const char *lFilterDescription = "Disk image files (*.img)"; char const * lTheSaveFileName = tinyfd_saveFileDialog("Select a disk image file","IMGMAKE.IMG",2,lFilterPatterns,lFilterDescription); @@ -3021,7 +3023,7 @@ class MakeDiskImage : public GUI::ToplevelWindow { } } #if !defined(HX_DOS) - chdir( Temp_CurrentDir ); + // chdir( Temp_CurrentDir ); #endif } if (shortcut) running = false; @@ -3566,7 +3568,7 @@ static void UI_Execute(GUI::ScreenSDL *screen) { SDL_UpdateRect(sdlscreen, 0, 0, 0, 0); #endif - SDL_Delay(40); + _Delay(40); } } @@ -3827,7 +3829,7 @@ static void UI_Select(GUI::ScreenSDL *screen, int select) { #else SDL_UpdateRect(sdlscreen, 0, 0, 0, 0); #endif - SDL_Delay(20); + _Delay(20); } } diff --git a/src/gui/sdl_mapper.cpp b/src/gui/sdl_mapper.cpp index 52cb83beeff..83bce71199e 100644 --- a/src/gui/sdl_mapper.cpp +++ b/src/gui/sdl_mapper.cpp @@ -71,6 +71,8 @@ #include #endif +extern void _Delay(uint32_t ticks); + #define BMOD_Mod1 0x0001 #define BMOD_Mod2 0x0002 #define BMOD_Mod3 0x0004 @@ -5410,7 +5412,7 @@ void MAPPER_RunInternal() { #endif } BIND_MappingEvents(); - SDL_Delay(1); + _Delay(1); } #if defined(C_SDL2) SDL_FreeSurface(mapper.draw_surface); diff --git a/src/gui/sdlmain.cpp b/src/gui/sdlmain.cpp index 1ca1163feed..d08c1784e80 100644 --- a/src/gui/sdlmain.cpp +++ b/src/gui/sdlmain.cpp @@ -89,6 +89,8 @@ bool kana_input = false; // true if a half-width kana was typed #define GL_SILENCE_DEPRECATION #endif +#include +#include #include #include #include @@ -249,6 +251,12 @@ extern "C" void sdl1_hax_macosx_highdpi_set_enable(const bool enable); #include "build_timestamp.h" #include "version_string.h" +#include "libco.h" + +extern void _Delay(uint32_t ticks); + +extern cothread_t _driverCoroutine; + #if C_OPENGL namespace gl2 { extern PFNGLATTACHSHADERPROC glAttachShader; @@ -1413,7 +1421,7 @@ void PauseDOSBoxLoop(Bitu /*unused*/) { SDL_PollEvent(&event); #elif C_GAMELINK // Keep GameLink ticking over. - SDL_Delay(100); + _Delay(100); OUTPUT_GAMELINK_Transfer(); SDL_PollEvent(&event); #else @@ -5434,6 +5442,230 @@ bool gfx_in_mapper = false; #define DB_POLLSKIP 1 #endif +#ifndef C_SDL2 +#define C_SDL2 +#endif + +std::set _pressedKeys; +std::set _releasedKeys; + +SDL_Keycode getSDLKeycodeFromDosboxKeyCode(KBD_KEYS code) +{ + switch(code) + { + case KBD_NONE: return SDLK_UNKNOWN; + case KBD_1: return SDLK_1; + case KBD_2: return SDLK_2; + case KBD_3: return SDLK_3; + case KBD_4: return SDLK_4; + case KBD_5: return SDLK_5; + case KBD_6: return SDLK_6; + case KBD_7: return SDLK_7; + case KBD_8: return SDLK_8; + case KBD_9: return SDLK_9; + case KBD_0: return SDLK_0; + case KBD_q: return SDLK_q; + case KBD_w: return SDLK_w; + case KBD_e: return SDLK_e; + case KBD_r: return SDLK_r; + case KBD_t: return SDLK_t; + case KBD_y: return SDLK_y; + case KBD_u: return SDLK_u; + case KBD_i: return SDLK_i; + case KBD_o: return SDLK_o; + case KBD_p: return SDLK_p; + case KBD_a: return SDLK_a; + case KBD_s: return SDLK_s; + case KBD_d: return SDLK_d; + case KBD_f: return SDLK_f; + case KBD_g: return SDLK_g; + case KBD_h: return SDLK_h; + case KBD_j: return SDLK_j; + case KBD_k: return SDLK_k; + case KBD_l: return SDLK_l; + case KBD_z: return SDLK_z; + case KBD_x: return SDLK_x; + case KBD_c: return SDLK_c; + case KBD_v: return SDLK_v; + case KBD_b: return SDLK_b; + case KBD_n: return SDLK_n; + case KBD_m: return SDLK_m; + case KBD_f1: return SDLK_F1; + case KBD_f2: return SDLK_F2; + case KBD_f3: return SDLK_F3; + case KBD_f4: return SDLK_F4; + case KBD_f5: return SDLK_F5; + case KBD_f6: return SDLK_F6; + case KBD_f7: return SDLK_F7; + case KBD_f8: return SDLK_F8; + case KBD_f9: return SDLK_F9; + case KBD_f10: return SDLK_F10; + case KBD_f11: return SDLK_F11; + case KBD_f12: return SDLK_F12; + case KBD_esc: return SDLK_ESCAPE; + case KBD_tab: return SDLK_TAB; + case KBD_backspace: return SDLK_BACKSPACE; + case KBD_enter: return SDLK_RETURN; + case KBD_space: return SDLK_SPACE; + case KBD_capslock: return SDLK_CAPSLOCK; + case KBD_scrolllock: return SDLK_SCROLLLOCK; + case KBD_grave: return SDLK_BACKQUOTE; + case KBD_minus: return SDLK_MINUS; + case KBD_equals: return SDLK_EQUALS; + case KBD_backslash: return SDLK_BACKSLASH; + case KBD_leftbracket: return SDLK_LEFTBRACKET; + case KBD_rightbracket: return SDLK_RIGHTBRACKET; + case KBD_semicolon: return SDLK_SEMICOLON; + case KBD_quote: return SDLK_QUOTE; + case KBD_period: return SDLK_PERIOD; + case KBD_comma: return SDLK_COMMA; + case KBD_slash: return SDLK_SLASH; + case KBD_extra_lt_gt: return SDLK_LESS; + case KBD_printscreen: return SDLK_PRINTSCREEN; + case KBD_pause: return SDLK_PAUSE; + case KBD_insert: return SDLK_INSERT; + case KBD_home: return SDLK_HOME; + case KBD_pageup: return SDLK_PAGEUP; + case KBD_delete: return SDLK_DELETE; + case KBD_end: return SDLK_END; + case KBD_pagedown: return SDLK_PAGEDOWN; + case KBD_left: return SDLK_LEFT; + case KBD_up: return SDLK_UP; + case KBD_down: return SDLK_DOWN; + case KBD_right: return SDLK_RIGHT; + case KBD_kp1: return SDLK_KP_1; + case KBD_kp2: return SDLK_KP_2; + case KBD_kp3: return SDLK_KP_3; + case KBD_kp4: return SDLK_KP_4; + case KBD_kp5: return SDLK_KP_5; + case KBD_kp6: return SDLK_KP_6; + case KBD_kp7: return SDLK_KP_7; + case KBD_kp8: return SDLK_KP_8; + case KBD_kp9: return SDLK_KP_9; + case KBD_kp0: return SDLK_KP_0; + case KBD_kpdivide: return SDLK_KP_DIVIDE; + case KBD_kpmultiply: return SDLK_KP_MULTIPLY; + case KBD_kpminus: return SDLK_KP_MINUS; + case KBD_kpplus: return SDLK_KP_PLUS; + case KBD_kpenter: return SDLK_KP_ENTER; + case KBD_kpperiod: return SDLK_KP_PERIOD; + default: return SDLK_UNKNOWN; + } +} + +SDL_Scancode getSDLScancodeFromDosboxKeyCode(KBD_KEYS code) +{ + switch(code) + { + case KBD_NONE: return SDL_SCANCODE_UNKNOWN; + case KBD_1: return SDL_SCANCODE_1; + case KBD_2: return SDL_SCANCODE_2; + case KBD_3: return SDL_SCANCODE_3; + case KBD_4: return SDL_SCANCODE_4; + case KBD_5: return SDL_SCANCODE_5; + case KBD_6: return SDL_SCANCODE_6; + case KBD_7: return SDL_SCANCODE_7; + case KBD_8: return SDL_SCANCODE_8; + case KBD_9: return SDL_SCANCODE_9; + case KBD_0: return SDL_SCANCODE_0; + case KBD_q: return SDL_SCANCODE_Q; + case KBD_w: return SDL_SCANCODE_W; + case KBD_e: return SDL_SCANCODE_E; + case KBD_r: return SDL_SCANCODE_R; + case KBD_t: return SDL_SCANCODE_T; + case KBD_y: return SDL_SCANCODE_Y; + case KBD_u: return SDL_SCANCODE_U; + case KBD_i: return SDL_SCANCODE_I; + case KBD_o: return SDL_SCANCODE_O; + case KBD_p: return SDL_SCANCODE_P; + case KBD_a: return SDL_SCANCODE_A; + case KBD_s: return SDL_SCANCODE_S; + case KBD_d: return SDL_SCANCODE_D; + case KBD_f: return SDL_SCANCODE_F; + case KBD_g: return SDL_SCANCODE_G; + case KBD_h: return SDL_SCANCODE_H; + case KBD_j: return SDL_SCANCODE_J; + case KBD_k: return SDL_SCANCODE_K; + case KBD_l: return SDL_SCANCODE_L; + case KBD_z: return SDL_SCANCODE_Z; + case KBD_x: return SDL_SCANCODE_X; + case KBD_c: return SDL_SCANCODE_C; + case KBD_v: return SDL_SCANCODE_V; + case KBD_b: return SDL_SCANCODE_B; + case KBD_n: return SDL_SCANCODE_N; + case KBD_m: return SDL_SCANCODE_M; + case KBD_f1: return SDL_SCANCODE_F1; + case KBD_f2: return SDL_SCANCODE_F2; + case KBD_f3: return SDL_SCANCODE_F3; + case KBD_f4: return SDL_SCANCODE_F4; + case KBD_f5: return SDL_SCANCODE_F5; + case KBD_f6: return SDL_SCANCODE_F6; + case KBD_f7: return SDL_SCANCODE_F7; + case KBD_f8: return SDL_SCANCODE_F8; + case KBD_f9: return SDL_SCANCODE_F9; + case KBD_f10: return SDL_SCANCODE_F10; + case KBD_f11: return SDL_SCANCODE_F11; + case KBD_f12: return SDL_SCANCODE_F12; + case KBD_esc: return SDL_SCANCODE_ESCAPE; + case KBD_tab: return SDL_SCANCODE_TAB; + case KBD_backspace: return SDL_SCANCODE_BACKSPACE; + case KBD_enter: return SDL_SCANCODE_RETURN; + case KBD_space: return SDL_SCANCODE_SPACE; + case KBD_leftalt: return SDL_SCANCODE_LALT; + case KBD_rightalt: return SDL_SCANCODE_RALT; + case KBD_leftctrl: return SDL_SCANCODE_LCTRL; + case KBD_rightctrl: return SDL_SCANCODE_RCTRL; + case KBD_leftshift: return SDL_SCANCODE_LSHIFT; + case KBD_rightshift: return SDL_SCANCODE_RSHIFT; + case KBD_numlock: return SDL_SCANCODE_NUMLOCKCLEAR; + case KBD_capslock: return SDL_SCANCODE_CAPSLOCK; + case KBD_scrolllock: return SDL_SCANCODE_SCROLLLOCK; + case KBD_grave: return SDL_SCANCODE_GRAVE; + case KBD_minus: return SDL_SCANCODE_MINUS; + case KBD_equals: return SDL_SCANCODE_EQUALS; + case KBD_backslash: return SDL_SCANCODE_BACKSLASH; + case KBD_leftbracket: return SDL_SCANCODE_LEFTBRACKET; + case KBD_rightbracket: return SDL_SCANCODE_RIGHTBRACKET; + case KBD_semicolon: return SDL_SCANCODE_SEMICOLON; + case KBD_quote: return SDL_SCANCODE_APOSTROPHE; + case KBD_period: return SDL_SCANCODE_PERIOD; + case KBD_comma: return SDL_SCANCODE_COMMA; + case KBD_slash: return SDL_SCANCODE_SLASH; + case KBD_extra_lt_gt: return SDL_SCANCODE_GRAVE; + case KBD_printscreen: return SDL_SCANCODE_PRINTSCREEN; + case KBD_pause: return SDL_SCANCODE_PAUSE; + case KBD_insert: return SDL_SCANCODE_INSERT; + case KBD_home: return SDL_SCANCODE_HOME; + case KBD_pageup: return SDL_SCANCODE_PAGEUP; + case KBD_delete: return SDL_SCANCODE_DELETE; + case KBD_end: return SDL_SCANCODE_END; + case KBD_pagedown: return SDL_SCANCODE_PAGEDOWN; + case KBD_left: return SDL_SCANCODE_LEFT; + case KBD_up: return SDL_SCANCODE_UP; + case KBD_down: return SDL_SCANCODE_DOWN; + case KBD_right: return SDL_SCANCODE_RIGHT; + case KBD_kp1: return SDL_SCANCODE_KP_1; + case KBD_kp2: return SDL_SCANCODE_KP_2; + case KBD_kp3: return SDL_SCANCODE_KP_3; + case KBD_kp4: return SDL_SCANCODE_KP_4; + case KBD_kp5: return SDL_SCANCODE_KP_5; + case KBD_kp6: return SDL_SCANCODE_KP_6; + case KBD_kp7: return SDL_SCANCODE_KP_7; + case KBD_kp8: return SDL_SCANCODE_KP_8; + case KBD_kp9: return SDL_SCANCODE_KP_9; + case KBD_kp0: return SDL_SCANCODE_KP_0; + case KBD_kpdivide: return SDL_SCANCODE_KP_DIVIDE; + case KBD_kpmultiply: return SDL_SCANCODE_KP_MULTIPLY; + case KBD_kpminus: return SDL_SCANCODE_KP_MINUS; + case KBD_kpplus: return SDL_SCANCODE_KP_PLUS; + case KBD_kpenter: return SDL_SCANCODE_KP_ENTER; + case KBD_kpperiod: return SDL_SCANCODE_KP_PERIOD; + default: return SDL_SCANCODE_UNKNOWN; + } +} + + + void GFX_Events() { CheckMapperKeyboardLayout(); #if defined(C_SDL2) /* SDL 2.x---------------------------------- */ @@ -5483,7 +5715,31 @@ void GFX_Events() { emscripten_sleep(0); #endif - while (SDL_PollEvent(&event)) { + std::queue pendingEvents; + + // Artificially adding pressend and released keys + for (const auto key : _releasedKeys) + { + SDL_Event newEvent; + newEvent.type = SDL_KEYUP; + newEvent.key.keysym.sym = getSDLKeycodeFromDosboxKeyCode(key); + newEvent.key.keysym.scancode = getSDLScancodeFromDosboxKeyCode(key); + pendingEvents.push(newEvent); + } + for (const auto key : _pressedKeys) + { + SDL_Event newEvent; + newEvent.type = SDL_KEYDOWN; + newEvent.key.keysym.sym = getSDLKeycodeFromDosboxKeyCode(key); + newEvent.key.keysym.scancode = getSDLScancodeFromDosboxKeyCode(key); + pendingEvents.push(newEvent); + } + _releasedKeys.clear(); + + // while (SDL_PollEvent(&event)) { + while (pendingEvents.empty() == false) + { + SDL_Event event = pendingEvents.front(); pendingEvents.pop(); #if defined(C_SDL2) /* SDL2 hack: There seems to be a problem where calling the SetWindowSize function, even for the same size, still causes a resize event, and sometimes for no apparent @@ -5495,7 +5751,6 @@ void GFX_Events() { eatRestoredWindow = false; } #endif - switch (event.type) { #if defined(WIN32) && !defined(HX_DOS) case SDL_SYSWMEVENT: @@ -5641,7 +5896,7 @@ void GFX_Events() { GFX_SetTitle(-1,-1,-1,true); KEYBOARD_ClrBuffer(); -// SDL_Delay(500); +// _Delay(500); // while (SDL_PollEvent(&ev)) { // flush event queue. // } @@ -5824,6 +6079,8 @@ void GFX_Events() { #endif case SDL_KEYDOWN: case SDL_KEYUP: + // if (event.type == SDL_KEYDOWN )printf("Processing Key Down event\n"); + // if (event.type == SDL_KEYUP ) printf("Processing Key Up event\n"); if (sdl.desktop.type == SCREEN_GAMELINK) break; #if defined (WIN32) || defined(MACOSX) || defined(C_SDL2) if (event.key.keysym.sym==SDLK_LALT) sdl.laltstate = event.key.type; @@ -5876,6 +6133,7 @@ void GFX_Events() { if (sdl.desktop.type == SCREEN_GAMELINK) break; gfx_in_mapper = true; if (ticksLocked && event.type == SDL_KEYDOWN && static_cast(control->GetSection("cpu"))->Get_bool("stop turbo on key")) DOSBOX_UnlockSpeed2(true); + // printf("Mapper Check Event\n"); MAPPER_CheckEvent(&event); gfx_in_mapper = false; } @@ -6088,7 +6346,7 @@ void GFX_Events() { GFX_SetTitle(-1,-1,-1,true); KEYBOARD_ClrBuffer(); -// SDL_Delay(500); +// _Delay(500); // while (SDL_PollEvent(&ev)) { // flush event queue. // } @@ -6638,7 +6896,7 @@ static void show_warning(char const * const message) { #else SDL_Flip(sdl.surface); #endif - SDL_Delay(12000); + _Delay(12000); ApplyPreventCap(); } @@ -7337,7 +7595,7 @@ void SERIAL_Init(); #if C_PRINTER void PRINTER_Init(); #endif -void PARALLEL_Init(); +// void PARALLEL_Init(); void DONGLE_Init(); void DOS_Init(); void XMS_Init(); @@ -7728,7 +7986,7 @@ void CPU_OnReset(Section* sec); void DISP2_Init(uint8_t color), DISP2_Shut(); //extern void UI_Init(void); void grGlideShutdown(void); -int main(int argc, char* argv[]) SDL_MAIN_NOEXCEPT { +int _main(int argc, char* argv[]) SDL_MAIN_NOEXCEPT { #if (defined __i386__ || defined __x86_64__) && (defined BSD || defined LINUX) dropPrivilegesTemp(); #endif @@ -7995,10 +8253,10 @@ int main(int argc, char* argv[]) SDL_MAIN_NOEXCEPT { std::string workdirsaveas = ""; #if defined(MACOSX) || defined(LINUX) || (defined(WIN32) && !defined(HX_DOS)) { - char cwd[512] = {0}; - if(getcwd(cwd, sizeof(cwd) - 1) == NULL) { - LOG(LOG_GUI, LOG_ERROR)("sdlmain.cpp main() failed to get the current working directory."); - } + char cwd[512] = "."; + // if(getcwd(cwd, sizeof(cwd) - 1) == NULL) { + // LOG(LOG_GUI, LOG_ERROR)("sdlmain.cpp main() failed to get the current working directory."); + // } if(control->opt_promptfolder < 0) { #if !defined(MACOSX) @@ -8583,11 +8841,11 @@ int main(int argc, char* argv[]) SDL_MAIN_NOEXCEPT { } } - char cwd[512] = {0}; - if(getcwd(cwd, sizeof(cwd) - 1)) - LOG_MSG("DOSBox-X's working directory: %s\n", cwd); - else - LOG(LOG_GUI, LOG_ERROR)("sdlmain.cpp main() failed to get the current working directory."); + char cwd[512] = "."; + // if(getcwd(cwd, sizeof(cwd) - 1)) + // LOG_MSG("DOSBox-X's working directory: %s\n", cwd); + // else + // LOG(LOG_GUI, LOG_ERROR)("sdlmain.cpp main() failed to get the current working directory."); const char *imestr = section->Get_string("ime"); enableime = !strcasecmp(imestr, "true") || !strcasecmp(imestr, "1"); @@ -8800,7 +9058,7 @@ int main(int argc, char* argv[]) SDL_MAIN_NOEXCEPT { LOG_MSG("Prevent capture: %u",preventcap); /* -- SDL init */ - if (SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_NOPARACHUTE) >= 0) + if (SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO) >= 0) sdl.inited = true; else E_Exit("Can't init SDL %s",SDL_GetError()); @@ -9028,7 +9286,7 @@ int main(int argc, char* argv[]) SDL_MAIN_NOEXCEPT { #if C_PRINTER PRINTER_Init(); #endif - PARALLEL_Init(); + // PARALLEL_Init(); NE2K_Init(); #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU @@ -9406,6 +9664,9 @@ int main(int argc, char* argv[]) SDL_MAIN_NOEXCEPT { if (control->opt_test) ::testing::InitGoogleTest(&argc, argv); #endif + // Returning after initializing + co_switch(_driverCoroutine); + /* NTS: CPU reset handler, and BIOS init, has the instruction pointer poised to run through BIOS initialization, * which will then "boot" into the DOSBox-X kernel, and then the shell, by calling VM_Boot_DOSBox_Kernel() */ /* FIXME: throwing int() is a stupid and nondescriptive way to signal shutdown/reset. */ @@ -9940,7 +10201,7 @@ void GUI_ResetResize(bool pressed) { bool MOUSE_IsLocked() { - return sdl.mouse.locked; + return true; } #if defined(C_SDL2) && defined(C_OPENGL)/*HACK*/ diff --git a/src/gui/whereami.c b/src/gui/whereami.c index f725da84e41..2c85ec1600c 100644 --- a/src/gui/whereami.c +++ b/src/gui/whereami.c @@ -181,8 +181,8 @@ int WAI_PREFIX(getModulePath)(char* out, int capacity, int* dirname_length) #include #include #if defined(__linux__) -#include -#else +// #include +// #else #include #endif #ifndef __STDC_FORMAT_MACROS diff --git a/src/hardware/adlib.cpp b/src/hardware/adlib.cpp index 1385f041848..be05f27f035 100644 --- a/src/hardware/adlib.cpp +++ b/src/hardware/adlib.cpp @@ -38,8 +38,9 @@ #include "opl3duoboard/opl3duoboard.h" #include "esfmu/esfm.h" -#define RETROWAVE_USE_BUFFER -#include "RetroWaveLib/RetroWave_DOSBoX.hpp" +#undef RETROWAVE_USE_BUFFER +// #define RETROWAVE_USE_BUFFER +// #include "RetroWaveLib/RetroWave_DOSBoX.hpp" #define OPL2_INTERNAL_FREQ 3600000 // The OPL2 operates at 3.6MHz #define OPL3_INTERNAL_FREQ 14400000 // The OPL3 operates at 14.4MHz @@ -523,71 +524,71 @@ namespace OPL3DUOBOARD { }; } -namespace Retrowave_OPL3 { - struct Handler : public Adlib::Handler { - void WriteReg(uint32_t reg, uint8_t val) override { -// printf("writereg: 0x%08x 0x%02x\n", reg, val); - - uint16_t port = reg & 0x100; - uint8_t real_reg = reg & 0xff; - uint8_t real_val = val; - - if (real_reg == 1) - // Prevent writes to the test registers. - return; - - if (port) { -#ifdef RETROWAVE_USE_BUFFER - retrowave_opl3_queue_port1(&retrowave_global_context, real_reg, real_val); -#else - retrowave_opl3_emit_port1(&retrowave_global_context, real_reg, real_val); -#endif - } else { -#ifdef RETROWAVE_USE_BUFFER - retrowave_opl3_queue_port0(&retrowave_global_context, real_reg, real_val); -#else - retrowave_opl3_emit_port0(&retrowave_global_context, real_reg, real_val); -#endif - } - } - - uint32_t WriteAddr(uint32_t port, uint8_t val) override { -// printf("writeaddr: 0x%08x 0x%02x\n", port, val); - - switch (port & 3) { - case 0: - return val; - case 2: - return 0x100 | val; - } - - return 0; - } - - void Generate(MixerChannel* chan, Bitu samples) override { - (void)samples;//UNUSED -#ifdef RETROWAVE_USE_BUFFER - retrowave_flush(&retrowave_global_context); -#endif - const int16_t buf = 0; - chan->AddSamples_m16(1, &buf); - } - - void Init(Bitu rate) override { - (void)rate;//UNUSED - retrowave_opl3_reset(&retrowave_global_context); - } - - Handler(const std::string& bus, const std::string& path, const std::string& spi_cs) { - retrowave_init_dosbox(bus, path, spi_cs); - LOG_MSG("RetroWave: OPL3 class init"); - } - - ~Handler() { - retrowave_opl3_reset(&retrowave_global_context); - } - }; -} +// namespace Retrowave_OPL3 { +// struct Handler : public Adlib::Handler { +// void WriteReg(uint32_t reg, uint8_t val) override { +// // printf("writereg: 0x%08x 0x%02x\n", reg, val); + +// uint16_t port = reg & 0x100; +// uint8_t real_reg = reg & 0xff; +// uint8_t real_val = val; + +// if (real_reg == 1) +// // Prevent writes to the test registers. +// return; + +// if (port) { +// #ifdef RETROWAVE_USE_BUFFER +// retrowave_opl3_queue_port1(&retrowave_global_context, real_reg, real_val); +// #else +// retrowave_opl3_emit_port1(&retrowave_global_context, real_reg, real_val); +// #endif +// } else { +// #ifdef RETROWAVE_USE_BUFFER +// retrowave_opl3_queue_port0(&retrowave_global_context, real_reg, real_val); +// #else +// retrowave_opl3_emit_port0(&retrowave_global_context, real_reg, real_val); +// #endif +// } +// } + +// uint32_t WriteAddr(uint32_t port, uint8_t val) override { +// // printf("writeaddr: 0x%08x 0x%02x\n", port, val); + +// switch (port & 3) { +// case 0: +// return val; +// case 2: +// return 0x100 | val; +// } + +// return 0; +// } + +// void Generate(MixerChannel* chan, Bitu samples) override { +// (void)samples;//UNUSED +// #ifdef RETROWAVE_USE_BUFFER +// retrowave_flush(&retrowave_global_context); +// #endif +// const int16_t buf = 0; +// chan->AddSamples_m16(1, &buf); +// } + +// void Init(Bitu rate) override { +// (void)rate;//UNUSED +// retrowave_opl3_reset(&retrowave_global_context); +// } + +// Handler(const std::string& bus, const std::string& path, const std::string& spi_cs) { +// retrowave_init_dosbox(bus, path, spi_cs); +// LOG_MSG("RetroWave: OPL3 class init"); +// } + +// ~Handler() { +// retrowave_opl3_reset(&retrowave_global_context); +// } +// }; +// } #define RAW_SIZE 1024 @@ -1433,7 +1434,7 @@ Module::Module( Section* configuration ) : Module_base(configuration) { handler = new OPL3DUOBOARD::Handler(oplport.c_str()); } else if (oplemu == "retrowave_opl3") { - handler = new Retrowave_OPL3::Handler(retrowave_bus, retrowave_port, retrowave_spi_cs); + // handler = new Retrowave_OPL3::Handler(retrowave_bus, retrowave_port, retrowave_spi_cs); } else if (oplemu == "mame") { if (oplmode == OPL_opl2) { diff --git a/src/hardware/esfmu/esfm.c b/src/hardware/esfmu/esfm.c index 5e0433ede98..5d1f9540db3 100644 --- a/src/hardware/esfmu/esfm.c +++ b/src/hardware/esfmu/esfm.c @@ -1777,7 +1777,10 @@ ESFM_process_feedback(esfm_chip *chip) phase_acc = (uint32_t)(slot->in.phase_acc - phase_offset * 28); eg_output = slot->in.eg_output; - // ASM optimizaions! + // ASM optimizaions + #ifdef NDEBUG + #undef __x86_64__ + #endif #if defined(__GNUC__) && defined(__x86_64__) asm ( "movzbq %[wave], %%r8 \n\t" diff --git a/src/hardware/imfc.cpp b/src/hardware/imfc.cpp index 17bfcf194dd..afd87658c68 100644 --- a/src/hardware/imfc.cpp +++ b/src/hardware/imfc.cpp @@ -93,6 +93,8 @@ uint8_t IMFC_IRQ = 3; SDL_mutex* m_loggerMutex; +extern void _Delay(uint32_t ticks); + template void IMF_LOG(std::string format, Args const&... args) { @@ -5488,7 +5490,7 @@ class MusicFeatureCard : public Module_base { // reenable MUSIC_MODE_LOOP_read_System_And_Dispatch(); logSuccess(); - SDL_Delay(1); + _Delay(1); } } diff --git a/src/hardware/joystick.cpp b/src/hardware/joystick.cpp index c88fcc35f0f..507bde4473b 100644 --- a/src/hardware/joystick.cpp +++ b/src/hardware/joystick.cpp @@ -17,294 +17,287 @@ */ -#include -#include "dosbox.h" -#include "inout.h" -#include "logging.h" -#include "setup.h" -#include "joystick.h" -#include "pic.h" -#include "support.h" -#include "control.h" - -#define RANGE 64 -#define TIMEOUT 10 - -#define OHMS 120000/2 -#define JOY_S_CONSTANT 0.0000242 -#define S_PER_OHM 0.000000011 - -struct JoyStick { - bool enabled; - float xpos,ypos; - double xtick,ytick; - Bitu xcount,ycount; - bool button[2]; -}; - -JoystickType joytype; -static JoyStick stick[2]; - -static uint32_t last_write = 0; -static bool write_active = false; -static bool swap34 = false; -bool button_wrapping_enabled = true; - -extern bool autofire; //sdl_mapper.cpp -extern int joy1axes[]; //sdl_mapper.cpp -extern int joy2axes[]; //sdl_mapper.cpp - -static Bitu read_p201(Bitu port,Bitu iolen) { - (void)iolen;//UNUSED - (void)port;//UNUSED - /* Reset Joystick to 0 after TIMEOUT ms */ - if(write_active && ((PIC_Ticks - last_write) > TIMEOUT)) { - write_active = false; - stick[0].xcount = 0; - stick[1].xcount = 0; - stick[0].ycount = 0; - stick[1].ycount = 0; -// LOG_MSG("reset by time %d %d",PIC_Ticks,last_write); - } - - /** Format of the byte to be returned: - ** | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | - ** +-------------------------------+ - ** | | | | | | | | - ** Joystick B, Button 2 ---+ | | | | | | +--- Joystick A, X Axis - ** Joystick B, Button 1 -------+ | | | | +------- Joystick A, Y Axis - ** Joystick A, Button 2 -----------+ | | +----------- Joystick B, X Axis - ** Joystick A, Button 1 ---------------+ +--------------- Joystick B, Y Axis - **/ - uint8_t ret=0xff; - if (stick[0].enabled) { - if (stick[0].xcount) stick[0].xcount--; else ret&=~1; - if (stick[0].ycount) stick[0].ycount--; else ret&=~2; - if (stick[0].button[0]) ret&=~16; - if (stick[0].button[1]) ret&=~32; - } - if (stick[1].enabled) { - if (stick[1].xcount) stick[1].xcount--; else ret&=~4; - if (stick[1].ycount) stick[1].ycount--; else ret&=~8; - if (stick[1].button[0]) ret&=~64; - if (stick[1].button[1]) ret&=~128; - } - return ret; -} - -static Bitu read_p201_timed(Bitu port,Bitu iolen) { - (void)port;//UNUSED - (void)iolen;//UNUSED - uint8_t ret=0xff; - double currentTick = PIC_FullIndex(); - if( stick[0].enabled ){ - if( stick[0].xtick < currentTick ) ret &=~1; - if( stick[0].ytick < currentTick ) ret &=~2; - } - if( stick[1].enabled ){ - if( stick[1].xtick < currentTick ) ret &=~4; - if( stick[1].ytick < currentTick ) ret &=~8; - } - - if (stick[0].enabled) { - if (stick[0].button[0]) ret&=~16; - if (stick[0].button[1]) ret&=~32; - } - if (stick[1].enabled) { - if (stick[1].button[0]) ret&=~64; - if (stick[1].button[1]) ret&=~128; - } - return ret; -} - -static void write_p201(Bitu port,Bitu val,Bitu iolen) { - (void)val;//UNUSED - (void)port;//UNUSED - (void)iolen;//UNUSED - /* Store writetime index */ - write_active = true; - last_write = (uint32_t)PIC_Ticks; - if (stick[0].enabled) { - stick[0].xcount=(Bitu)((stick[0].xpos*RANGE)+RANGE); - stick[0].ycount=(Bitu)((stick[0].ypos*RANGE)+RANGE); - } - if (stick[1].enabled) { - stick[1].xcount=(Bitu)(((swap34? stick[1].ypos : stick[1].xpos)*RANGE)+RANGE); - stick[1].ycount=(Bitu)(((swap34? stick[1].xpos : stick[1].ypos)*RANGE)+RANGE); - } - -} -static void write_p201_timed(Bitu port,Bitu val,Bitu iolen) { - (void)val;//UNUSED - (void)port;//UNUSED - (void)iolen;//UNUSED - // Store writetime index - // Axes take time = 24.2 microseconds + ( 0.011 microseconds/ohm * resistance ) - // to reset to 0 - // Precalculate the time at which each axis hits 0 here - double currentTick = PIC_FullIndex(); - if (stick[0].enabled) { - stick[0].xtick = currentTick + 1000.0*( JOY_S_CONSTANT + S_PER_OHM * - (double)((stick[0].xpos+1.0)* OHMS) ); - stick[0].ytick = currentTick + 1000.0*( JOY_S_CONSTANT + S_PER_OHM * - (double)((stick[0].ypos+1.0)* OHMS) ); - } - if (stick[1].enabled) { - stick[1].xtick = currentTick + 1000.0*( JOY_S_CONSTANT + S_PER_OHM * - (double)((swap34? stick[1].ypos : stick[1].xpos)+1.0) * OHMS); - stick[1].ytick = currentTick + 1000.0*( JOY_S_CONSTANT + S_PER_OHM * - (double)((swap34? stick[1].xpos : stick[1].ypos)+1.0) * OHMS); - } -} - -void JOYSTICK_Enable(Bitu which,bool enabled) { - LOG(LOG_MISC,LOG_DEBUG)("JOYSTICK: Stick %u enable=%u",(int)which,enabled?1:0); - if (which<2) stick[which].enabled=enabled; -} - -void JOYSTICK_Button(Bitu which,Bitu num,bool pressed) { - if ((which<2) && (num<2)) stick[which].button[num]=pressed; -} - -void JOYSTICK_Move_X(Bitu which,float x) { - if (which<2) { - stick[which].xpos=x; - } -} - -void JOYSTICK_Move_Y(Bitu which,float y) { - if (which<2) { - stick[which].ypos=y; - } -} - -bool JOYSTICK_IsEnabled(Bitu which) { - if (which<2) return stick[which].enabled; - return false; -} - -bool JOYSTICK_GetButton(Bitu which, Bitu num) { - if ((which<2) && (num<2)) return stick[which].button[num]; - return false; -} - -float JOYSTICK_GetMove_X(Bitu which) { - if (which<2) return stick[which].xpos; - return 0.0f; -} - -float JOYSTICK_GetMove_Y(Bitu which) { - if (which<2) return stick[which].ypos; - return 0.0f; -} - -class JOYSTICK:public Module_base{ -private: - IO_ReadHandleObject ReadHandler; - IO_WriteHandleObject WriteHandler; -public: - JOYSTICK(Section* configuration):Module_base(configuration){ - Section_prop * section=static_cast(configuration); - - bool timed = section->Get_bool("timed"); - if(timed) { - ReadHandler.Install(0x201,read_p201_timed,IO_MB); - WriteHandler.Install(0x201,write_p201_timed,IO_MB); - } else { - ReadHandler.Install(0x201,read_p201,IO_MB); - WriteHandler.Install(0x201,write_p201,IO_MB); - } - } -}; - -static JOYSTICK* test = NULL; - -void JOYSTICK_Destroy(Section* sec) { - (void)sec;//UNUSED - if (test != NULL) { - delete test; - test = NULL; - } -} - -void JOYSTICK_OnPowerOn(Section* sec) { - (void)sec;//UNUSED - if (test == NULL) { - LOG(LOG_MISC,LOG_DEBUG)("Allocating joystick emulation"); - test = new JOYSTICK(control->GetSection("joystick")); - } -} - -void JOYSTICK_Init() { - LOG(LOG_MISC,LOG_DEBUG)("Initializing joystick emulation"); - - /* NTS: Joystick emulation does not work if we init joystick type AFTER mapper init. - * We cannot wait for poweron/reset signal for determination of joystick type. - * But, I/O port setup can happen later. */ - { - Section_prop * section=static_cast(control->GetSection("joystick")); - - const char * type=section->Get_string("joysticktype"); - if (!strcasecmp(type,"none")) joytype = JOY_NONE; - else if (!strcasecmp(type,"false")) joytype = JOY_NONE; - else if (!strcasecmp(type,"auto")) joytype = JOY_AUTO; - else if (!strcasecmp(type,"2axis")) joytype = JOY_2AXIS; - else if (!strcasecmp(type,"4axis")) joytype = JOY_4AXIS; - else if (!strcasecmp(type,"4axis_2")) joytype = JOY_4AXIS_2; - else if (!strcasecmp(type,"fcs")) joytype = JOY_FCS; - else if (!strcasecmp(type,"ch")) joytype = JOY_CH; - else joytype = JOY_AUTO; - - autofire = section->Get_bool("autofire"); - swap34 = section->Get_bool("swap34"); - button_wrapping_enabled = section->Get_bool("buttonwrap"); - stick[0].enabled = false; - stick[1].enabled = false; - stick[0].xtick = stick[0].ytick = stick[1].xtick = - stick[1].ytick = PIC_FullIndex(); - - // retrieves axes mapping - auto joysticks = 2; - auto axes = 8; - for (auto i = 0; i < joysticks; i++) - { - for (auto j = 0; j < axes; j++) - { - auto propname = "joy" + std::to_string(i + 1) + "axis" + std::to_string(j); - auto axis = section->Get_int(propname); - if (i == 0) - { - joy1axes[j] = axis; - } - else - { - joy2axes[j] = axis; - } - } - } - } - - AddExitFunction(AddExitFunctionFuncPair(JOYSTICK_Destroy),true); - - if (!IS_PC98_ARCH) - AddVMEventFunction(VM_EVENT_POWERON,AddVMEventFunctionFuncPair(JOYSTICK_OnPowerOn)); -} - -//save state support -namespace -{ -class SerializeStick : public SerializeGlobalPOD -{ -public: - SerializeStick() : SerializeGlobalPOD("Joystick") - { - registerPOD(joytype); - registerPOD(stick); - registerPOD(last_write); - registerPOD(write_active); - registerPOD(swap34); - registerPOD(button_wrapping_enabled); - registerPOD(autofire); - } -} dummy; -} + #include + #include "dosbox.h" + #include "inout.h" + #include "logging.h" + #include "setup.h" + #include "joystick.h" + #include "pic.h" + #include "support.h" + #include "control.h" + + #define RANGE 64 + #define TIMEOUT 10 + + #define OHMS 120000/2 + #define JOY_S_CONSTANT 0.0000242 + #define S_PER_OHM 0.000000011 + + JoystickType joytype; + JoyStick stick[2]; + + static uint32_t last_write = 0; + static bool write_active = false; + static bool swap34 = false; + bool button_wrapping_enabled = true; + + extern bool autofire; //sdl_mapper.cpp + extern int joy1axes[]; //sdl_mapper.cpp + extern int joy2axes[]; //sdl_mapper.cpp + + static Bitu read_p201(Bitu port,Bitu iolen) { + (void)iolen;//UNUSED + (void)port;//UNUSED + /* Reset Joystick to 0 after TIMEOUT ms */ + if(write_active && ((PIC_Ticks - last_write) > TIMEOUT)) { + write_active = false; + stick[0].xcount = 0; + stick[1].xcount = 0; + stick[0].ycount = 0; + stick[1].ycount = 0; + // LOG_MSG("reset by time %d %d",PIC_Ticks,last_write); + } + + /** Format of the byte to be returned: + ** | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + ** +-------------------------------+ + ** | | | | | | | | + ** Joystick B, Button 2 ---+ | | | | | | +--- Joystick A, X Axis + ** Joystick B, Button 1 -------+ | | | | +------- Joystick A, Y Axis + ** Joystick A, Button 2 -----------+ | | +----------- Joystick B, X Axis + ** Joystick A, Button 1 ---------------+ +--------------- Joystick B, Y Axis + **/ + uint8_t ret=0xff; + if (stick[0].enabled) { + if (stick[0].xcount) stick[0].xcount--; else ret&=~1; + if (stick[0].ycount) stick[0].ycount--; else ret&=~2; + if (stick[0].button[0]) ret&=~16; + if (stick[0].button[1]) ret&=~32; + } + if (stick[1].enabled) { + if (stick[1].xcount) stick[1].xcount--; else ret&=~4; + if (stick[1].ycount) stick[1].ycount--; else ret&=~8; + if (stick[1].button[0]) ret&=~64; + if (stick[1].button[1]) ret&=~128; + } + return ret; + } + + static Bitu read_p201_timed(Bitu port,Bitu iolen) { + (void)port;//UNUSED + (void)iolen;//UNUSED + uint8_t ret=0xff; + double currentTick = PIC_FullIndex(); + if( stick[0].enabled ){ + if( stick[0].xtick < currentTick ) ret &=~1; + if( stick[0].ytick < currentTick ) ret &=~2; + } + if( stick[1].enabled ){ + if( stick[1].xtick < currentTick ) ret &=~4; + if( stick[1].ytick < currentTick ) ret &=~8; + } + + if (stick[0].enabled) { + if (stick[0].button[0]) ret&=~16; + if (stick[0].button[1]) ret&=~32; + } + if (stick[1].enabled) { + if (stick[1].button[0]) ret&=~64; + if (stick[1].button[1]) ret&=~128; + } + return ret; + } + + static void write_p201(Bitu port,Bitu val,Bitu iolen) { + (void)val;//UNUSED + (void)port;//UNUSED + (void)iolen;//UNUSED + /* Store writetime index */ + write_active = true; + last_write = (uint32_t)PIC_Ticks; + if (stick[0].enabled) { + stick[0].xcount=(Bitu)((stick[0].xpos*RANGE)+RANGE); + stick[0].ycount=(Bitu)((stick[0].ypos*RANGE)+RANGE); + } + if (stick[1].enabled) { + stick[1].xcount=(Bitu)(((swap34? stick[1].ypos : stick[1].xpos)*RANGE)+RANGE); + stick[1].ycount=(Bitu)(((swap34? stick[1].xpos : stick[1].ypos)*RANGE)+RANGE); + } + + } + static void write_p201_timed(Bitu port,Bitu val,Bitu iolen) { + (void)val;//UNUSED + (void)port;//UNUSED + (void)iolen;//UNUSED + // Store writetime index + // Axes take time = 24.2 microseconds + ( 0.011 microseconds/ohm * resistance ) + // to reset to 0 + // Precalculate the time at which each axis hits 0 here + double currentTick = PIC_FullIndex(); + if (stick[0].enabled) { + stick[0].xtick = currentTick + 1000.0*( JOY_S_CONSTANT + S_PER_OHM * + (double)((stick[0].xpos+1.0)* OHMS) ); + stick[0].ytick = currentTick + 1000.0*( JOY_S_CONSTANT + S_PER_OHM * + (double)((stick[0].ypos+1.0)* OHMS) ); + } + if (stick[1].enabled) { + stick[1].xtick = currentTick + 1000.0*( JOY_S_CONSTANT + S_PER_OHM * + (double)((swap34? stick[1].ypos : stick[1].xpos)+1.0) * OHMS); + stick[1].ytick = currentTick + 1000.0*( JOY_S_CONSTANT + S_PER_OHM * + (double)((swap34? stick[1].xpos : stick[1].ypos)+1.0) * OHMS); + } + } + + void JOYSTICK_Enable(Bitu which,bool enabled) { + LOG(LOG_MISC,LOG_DEBUG)("JOYSTICK: Stick %u enable=%u",(int)which,enabled?1:0); + if (which<2) stick[which].enabled=enabled; + } + + void JOYSTICK_Button(Bitu which,Bitu num,bool pressed) { + if ((which<2) && (num<2)) stick[which].button[num]=pressed; + } + + void JOYSTICK_Move_X(Bitu which,float x) { + if (which<2) { + stick[which].xpos=x; + } + } + + void JOYSTICK_Move_Y(Bitu which,float y) { + if (which<2) { + stick[which].ypos=y; + } + } + + bool JOYSTICK_IsEnabled(Bitu which) { + if (which<2) return stick[which].enabled; + return false; + } + + bool JOYSTICK_GetButton(Bitu which, Bitu num) { + if ((which<2) && (num<2)) return stick[which].button[num]; + return false; + } + + float JOYSTICK_GetMove_X(Bitu which) { + if (which<2) return stick[which].xpos; + return 0.0f; + } + + float JOYSTICK_GetMove_Y(Bitu which) { + if (which<2) return stick[which].ypos; + return 0.0f; + } + + class JOYSTICK:public Module_base{ + private: + IO_ReadHandleObject ReadHandler; + IO_WriteHandleObject WriteHandler; + public: + JOYSTICK(Section* configuration):Module_base(configuration){ + Section_prop * section=static_cast(configuration); + + bool timed = section->Get_bool("timed"); + if(timed) { + ReadHandler.Install(0x201,read_p201_timed,IO_MB); + WriteHandler.Install(0x201,write_p201_timed,IO_MB); + } else { + ReadHandler.Install(0x201,read_p201,IO_MB); + WriteHandler.Install(0x201,write_p201,IO_MB); + } + } + }; + + static JOYSTICK* test = NULL; + + void JOYSTICK_Destroy(Section* sec) { + (void)sec;//UNUSED + if (test != NULL) { + delete test; + test = NULL; + } + } + + void JOYSTICK_OnPowerOn(Section* sec) { + (void)sec;//UNUSED + if (test == NULL) { + LOG(LOG_MISC,LOG_DEBUG)("Allocating joystick emulation"); + test = new JOYSTICK(control->GetSection("joystick")); + } + } + + void JOYSTICK_Init() { + LOG(LOG_MISC,LOG_DEBUG)("Initializing joystick emulation"); + + /* NTS: Joystick emulation does not work if we init joystick type AFTER mapper init. + * We cannot wait for poweron/reset signal for determination of joystick type. + * But, I/O port setup can happen later. */ + { + Section_prop * section=static_cast(control->GetSection("joystick")); + + const char * type=section->Get_string("joysticktype"); + if (!strcasecmp(type,"none")) joytype = JOY_NONE; + else if (!strcasecmp(type,"false")) joytype = JOY_NONE; + else if (!strcasecmp(type,"auto")) joytype = JOY_AUTO; + else if (!strcasecmp(type,"2axis")) joytype = JOY_2AXIS; + else if (!strcasecmp(type,"4axis")) joytype = JOY_4AXIS; + else if (!strcasecmp(type,"4axis_2")) joytype = JOY_4AXIS_2; + else if (!strcasecmp(type,"fcs")) joytype = JOY_FCS; + else if (!strcasecmp(type,"ch")) joytype = JOY_CH; + else joytype = JOY_AUTO; + + autofire = section->Get_bool("autofire"); + swap34 = section->Get_bool("swap34"); + button_wrapping_enabled = section->Get_bool("buttonwrap"); + stick[0].enabled = false; + stick[1].enabled = false; + stick[0].xtick = stick[0].ytick = stick[1].xtick = + stick[1].ytick = PIC_FullIndex(); + + // retrieves axes mapping + auto joysticks = 2; + auto axes = 8; + for (auto i = 0; i < joysticks; i++) + { + for (auto j = 0; j < axes; j++) + { + auto propname = "joy" + std::to_string(i + 1) + "axis" + std::to_string(j); + auto axis = section->Get_int(propname); + if (i == 0) + { + joy1axes[j] = axis; + } + else + { + joy2axes[j] = axis; + } + } + } + } + + AddExitFunction(AddExitFunctionFuncPair(JOYSTICK_Destroy),true); + + if (!IS_PC98_ARCH) + AddVMEventFunction(VM_EVENT_POWERON,AddVMEventFunctionFuncPair(JOYSTICK_OnPowerOn)); + } + + //save state support + namespace + { + class SerializeStick : public SerializeGlobalPOD + { + public: + SerializeStick() : SerializeGlobalPOD("Joystick") + { + registerPOD(joytype); + registerPOD(stick); + registerPOD(last_write); + registerPOD(write_active); + registerPOD(swap34); + registerPOD(button_wrapping_enabled); + registerPOD(autofire); + } + } dummy; + } + \ No newline at end of file diff --git a/src/hardware/keyboard.cpp b/src/hardware/keyboard.cpp index 2d40a28e708..03f5d977ada 100644 --- a/src/hardware/keyboard.cpp +++ b/src/hardware/keyboard.cpp @@ -36,6 +36,7 @@ #include "jfont.h" #include "keymap.h" #include "control.h" +#include #if defined(_MSC_VER) # pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ @@ -1884,7 +1885,7 @@ static void KEYBOARD_TickHandler(void) { if (keyb.active && keyb.scanning) { if (keyb.pending_key >= 0) { - KEYBOARD_AddKey((KBD_KEYS)keyb.pending_key,keyb.pending_key_state); + // KEYBOARD_AddKey((KBD_KEYS)keyb.pending_key,keyb.pending_key_state); keyb.pending_key = -1; } else if (keyb.repeat.wait) { diff --git a/src/hardware/mixer.cpp b/src/hardware/mixer.cpp index b5bb11a15b8..7705bd17670 100644 --- a/src/hardware/mixer.cpp +++ b/src/hardware/mixer.cpp @@ -68,6 +68,8 @@ SDL_AudioDeviceID SDL2_AudioDevice = 0; /* valid IDs are 2 or higher, 1 for compat, 0 is never a valid ID */ #endif +extern std::vector _audioSamples; + static INLINE int16_t MIXER_CLIP(Bits SAMP) { if (SAMP < MAX_AUDIO) { if (SAMP > MIN_AUDIO) @@ -79,30 +81,8 @@ static INLINE int16_t MIXER_CLIP(Bits SAMP) { } } -struct mixedFraction { - unsigned int w; - unsigned int fn,fd; -}; -static struct { - int32_t work[MIXER_BUFSIZE][2]; - Bitu work_in,work_out,work_wrap; - Bitu pos,done; - float mastervol[2]; - float recordvol[2]; - MixerChannel* channels; - uint32_t freq; - uint32_t blocksize; - struct mixedFraction samples_per_ms; - struct mixedFraction samples_this_ms; - struct mixedFraction samples_rendered_ms; - bool nosound; - bool swapstereo; - bool sampleaccurate; - bool prebuffer_wait; - Bitu prebuffer_samples; - bool mute; -} mixer; +mixer_t mixer; uint32_t Mixer_MIXQ(void) { return ((uint32_t)mixer.freq) | @@ -647,6 +627,7 @@ inline bool MixerChannel::runSampleInterpolation(const Bitu upto) { current[0] = last[0] + delta[0]; current[1] = last[1] + delta[1]; while (freq_f < freq_d) { + msbuffer[msbuffer_o][0] = current[0] * volmul[0]; msbuffer[msbuffer_o][1] = current[1] * volmul[1]; @@ -661,7 +642,6 @@ inline bool MixerChannel::runSampleInterpolation(const Bitu upto) { template inline void MixerChannel::AddSamples(Bitu len, const Type* data) { last_sample_write = (Bits)mixer.samples_rendered_ms.w; - if (msbuffer_o >= 2048) { fprintf(stderr,"WARNING: addSample overrun (immediate)\n"); return; @@ -790,7 +770,7 @@ static void MIXER_MixData(Bitu fracs/*render up to*/) { chan=chan->next; } - if (CaptureState & (CAPTURE_WAVE|CAPTURE_VIDEO)) { + // if (CaptureState & (CAPTURE_WAVE|CAPTURE_VIDEO)) { int32_t volscale1 = (int32_t)(mixer.recordvol[0] * (1 << MIXER_VOLSHIFT)); int32_t volscale2 = (int32_t)(mixer.recordvol[1] * (1 << MIXER_VOLSHIFT)); int16_t convert[1024][2]; @@ -799,12 +779,14 @@ static void MIXER_MixData(Bitu fracs/*render up to*/) { Bitu readpos = mixer.work_in + prev_rendered; for (Bitu i=0;i> (MIXER_VOLSHIFT + MIXER_VOLSHIFT)); + _audioSamples.push_back(convert[i][0]); convert[i][1]=MIXER_CLIP(((int64_t)mixer.work[readpos][1] * (int64_t)volscale2) >> (MIXER_VOLSHIFT + MIXER_VOLSHIFT)); + _audioSamples.push_back(convert[i][1]); readpos++; } assert(readpos <= MIXER_BUFSIZE); - CAPTURE_AddWave( mixer.freq, added, (int16_t*)convert ); - } + // CAPTURE_AddWave( mixer.freq, added, (int16_t*)convert ); + // } if (Mixer_MIXC_Active() && prev_rendered < whole) { Bitu readpos = mixer.work_in + prev_rendered; @@ -936,8 +918,10 @@ static void SDLCALL MIXER_CallBack(void * userdata, Uint8 *stream, int len) { int32_t *in = &mixer.work[mixer.work_out][0]; while (need > 0) { if (mixer.work_out == mixer.work_in) break; + *output++ = MIXER_CLIP((((int64_t)(*in++)) * (int64_t)volscale1) >> (MIXER_VOLSHIFT + MIXER_VOLSHIFT)); *output++ = MIXER_CLIP((((int64_t)(*in++)) * (int64_t)volscale2) >> (MIXER_VOLSHIFT + MIXER_VOLSHIFT)); + mixer.work_out++; if (mixer.work_out >= mixer.work_wrap) { mixer.work_out = 0; @@ -1258,8 +1242,10 @@ void MIXER_Init() { #endif } else { if(((Bitu)mixer.freq != (Bitu)obtained.freq) || ((Bitu)mixer.blocksize != (Bitu)obtained.samples)) + { LOG(LOG_MISC,LOG_DEBUG)("MIXER:Got different values from SDL: freq %d, blocksize %d",(int)obtained.freq,(int)obtained.samples); - + } + mixer.freq=(unsigned int)obtained.freq; mixer.blocksize=obtained.samples; TIMER_AddTickHandler(MIXER_Mix); diff --git a/src/hardware/parport/parport.cpp b/src/hardware/parport/parport.cpp index ae8b3f534cf..16c12cfc09d 100644 --- a/src/hardware/parport/parport.cpp +++ b/src/hardware/parport/parport.cpp @@ -397,18 +397,18 @@ class PARPORTS:public Module_base { } } else #endif - if(!str.compare("file")) { - CFileLPT* cflpt= new CFileLPT(i, defaultirq[i], &cmd, squote); - if(cflpt->InstallationSuccessful) { - parallelPortObjects[i]=cflpt; - parallelPortObjects[i]->parallelType = PARALLEL_TYPE_FILE; - cmd.Shift(1); - cmd.GetStringRemain(parallelPortObjects[i]->commandLineString); - } else { - delete cflpt; - parallelPortObjects[i] = nullptr; - } - } else + // if(!str.compare("file")) { + // CFileLPT* cflpt= new CFileLPT(i, defaultirq[i], &cmd, squote); + // if(cflpt->InstallationSuccessful) { + // parallelPortObjects[i]=cflpt; + // parallelPortObjects[i]->parallelType = PARALLEL_TYPE_FILE; + // cmd.Shift(1); + // cmd.GetStringRemain(parallelPortObjects[i]->commandLineString); + // } else { + // delete cflpt; + // parallelPortObjects[i] = nullptr; + // } + // } else #if C_PRINTER // allow printer redirection on a single port if (str == "printer" && !printer_used) @@ -632,12 +632,12 @@ void PARALLEL::Run() break; } #endif - case PARALLEL_TYPE_FILE: - { - CFileLPT* cflpt= new CFileLPT(port-1, defaultirq[port-1], &cmd, squote); - if(cflpt->InstallationSuccessful) parallelPortObjects[port-1]=cflpt; - break; - } + // case PARALLEL_TYPE_FILE: + // { + // CFileLPT* cflpt= new CFileLPT(port-1, defaultirq[port-1], &cmd, squote); + // if(cflpt->InstallationSuccessful) parallelPortObjects[port-1]=cflpt; + // break; + // } #if C_PRINTER case PARALLEL_TYPE_PRINTER: if (!testParallelPortsBaseclass->printer_used) { diff --git a/src/hardware/pic.cpp b/src/hardware/pic.cpp index 3540aca523e..ca95139c796 100644 --- a/src/hardware/pic.cpp +++ b/src/hardware/pic.cpp @@ -726,7 +726,6 @@ bool PIC_RunQueue(void) { if (!PIC_IRQCheck && !PIC_IRQCheckPending && ((master.irr&master.imrr) != 0 || (slave.irr&slave.imrr) != 0)) LOG_MSG("PIC_IRQCheck not set and interrupts pending"); #endif - if (CPU_CycleLeft > 0) { if (PIC_IRQCheck) PIC_runIRQs(); diff --git a/src/hardware/snd_pc98/x11/dosio.c b/src/hardware/snd_pc98/x11/dosio.c index 08f6bec580e..dbc23f5278e 100644 --- a/src/hardware/snd_pc98/x11/dosio.c +++ b/src/hardware/snd_pc98/x11/dosio.c @@ -6,6 +6,7 @@ //#include "codecnv.h" #include "dosio.h" +#include //static OEMCHAR curpath[MAX_PATH]; diff --git a/src/hardware/vga_draw.cpp b/src/hardware/vga_draw.cpp index 8bcf21a88c7..d7376ff2ec4 100644 --- a/src/hardware/vga_draw.cpp +++ b/src/hardware/vga_draw.cpp @@ -6681,6 +6681,9 @@ void ChooseRenderOnDemand(void) { LOG(LOG_VGAMISC,LOG_DEBUG)("Render On Demand mode is %s for RodU %d",vga_render_on_demand?"on":"off",vga_render_on_demand_user); } +extern int _refreshRateNumerator; +extern int _refreshRateDenominator; + void VGA_SetupDrawing(Bitu /*val*/) { if (vga.mode==M_ERROR) { PIC_RemoveEvents(VGA_VerticalTimer); @@ -7016,6 +7019,8 @@ void VGA_SetupDrawing(Bitu /*val*/) { } else { // The screen refresh frequency + _refreshRateNumerator = clock; + _refreshRateDenominator = vtotal*htotal; fps=(double)clock/(vtotal*htotal); LOG(LOG_VGA,LOG_NORMAL)("VGA refresh rate is now, %.3f",fps); } diff --git a/src/ints/bios.cpp b/src/ints/bios.cpp index 29697dccd15..d2cbc65979a 100644 --- a/src/ints/bios.cpp +++ b/src/ints/bios.cpp @@ -1,12076 +1,12078 @@ -/* - * Copyright (C) 2002-2021 The DOSBox Team - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include -#include "control.h" -#include "dosbox.h" -#include "mem.h" -#include "cpu.h" -#include "bios.h" -#include "regs.h" -#include "timer.h" -#include "cpu.h" -#include "bitop.h" -#include "callback.h" -#include "inout.h" -#include "pic.h" -#include "hardware.h" -#include "pci_bus.h" -#include "joystick.h" -#include "mouse.h" -#include "callback.h" -#include "setup.h" -#include "bios_disk.h" -#include "serialport.h" -#include "mapper.h" -#include "vga.h" -#include "jfont.h" -#include "shiftjis.h" -#include "pc98_gdc.h" -#include "pc98_gdc_const.h" -#include "regionalloctracking.h" -#include "build_timestamp.h" -extern bool PS1AudioCard; -#include "parport.h" -#include "dma.h" -#include "shell.h" -#include "render.h" -#include "sdlmain.h" -#include -#include -#include "version_string.h" - -#if C_LIBPNG -#include -#endif - -#if defined(DB_HAVE_CLOCK_GETTIME) && ! defined(WIN32) -//time.h is already included -#else -#include -#endif - -#if C_EMSCRIPTEN -# include -#endif - -#include - -#if defined(_MSC_VER) -# pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ -# pragma warning(disable:4305) /* truncation from double to float */ -#endif - -#if defined(WIN32) && !defined(S_ISREG) -# define S_ISREG(x) ((x & S_IFREG) == S_IFREG) -#endif - -struct BIOS_E280_entry { - uint64_t base = 0; - uint64_t length = 0; - uint32_t type = 0; - uint32_t acpi_ext_addr = 0; -}; - -#define MAX_E280 16 -static BIOS_E280_entry E280_table[MAX_E280]; -static unsigned int E280_table_entries = 0; - -bool VGA_InitBiosLogo(unsigned int w,unsigned int h,unsigned int x,unsigned int y); -void VGA_WriteBiosLogoBMP(unsigned int y,unsigned char *scanline,unsigned int w); -void VGA_WriteBiosLogoPalette(unsigned int start,unsigned int count,unsigned char *rgb); -void VGA_FreeBiosLogo(void); +/* + * Copyright (C) 2002-2021 The DOSBox Team + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include +#include "control.h" +#include "dosbox.h" +#include "mem.h" +#include "cpu.h" +#include "bios.h" +#include "regs.h" +#include "timer.h" +#include "cpu.h" +#include "bitop.h" +#include "callback.h" +#include "inout.h" +#include "pic.h" +#include "hardware.h" +#include "pci_bus.h" +#include "joystick.h" +#include "mouse.h" +#include "callback.h" +#include "setup.h" +#include "bios_disk.h" +#include "serialport.h" +#include "mapper.h" +#include "vga.h" +#include "jfont.h" +#include "shiftjis.h" +#include "pc98_gdc.h" +#include "pc98_gdc_const.h" +#include "regionalloctracking.h" +#include "build_timestamp.h" +extern bool PS1AudioCard; +#include "parport.h" +#include "dma.h" +#include "shell.h" +#include "render.h" +#include "sdlmain.h" +#include +#include +#include "version_string.h" + +#if C_LIBPNG +#include +#endif + +#if defined(DB_HAVE_CLOCK_GETTIME) && ! defined(WIN32) +//time.h is already included +#else +#include +#endif + +#if C_EMSCRIPTEN +# include +#endif + +#include + +#if defined(_MSC_VER) +# pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ +# pragma warning(disable:4305) /* truncation from double to float */ +#endif + +#if defined(WIN32) && !defined(S_ISREG) +# define S_ISREG(x) ((x & S_IFREG) == S_IFREG) +#endif + +struct BIOS_E280_entry { + uint64_t base = 0; + uint64_t length = 0; + uint32_t type = 0; + uint32_t acpi_ext_addr = 0; +}; + +#define MAX_E280 16 +static BIOS_E280_entry E280_table[MAX_E280]; +static unsigned int E280_table_entries = 0; + +bool VGA_InitBiosLogo(unsigned int w,unsigned int h,unsigned int x,unsigned int y); +void VGA_WriteBiosLogoBMP(unsigned int y,unsigned char *scanline,unsigned int w); +void VGA_WriteBiosLogoPalette(unsigned int start,unsigned int count,unsigned char *rgb); +void VGA_FreeBiosLogo(void); void VGA_ShowBIOSLogo(void); - -extern bool ega200; - -unsigned char ACPI_ENABLE_CMD = 0xA1; -unsigned char ACPI_DISABLE_CMD = 0xA0; -unsigned int ACPI_IO_BASE = 0x820; -unsigned int ACPI_PM1A_EVT_BLK = 0x820; -unsigned int ACPI_PM1A_CNT_BLK = 0x824; -unsigned int ACPI_PM_TMR_BLK = 0x830; -/* debug region 0x840-0x84F */ -unsigned int ACPI_DEBUG_IO = 0x840; - -std::string ibm_rom_basic; -size_t ibm_rom_basic_size = 0; -uint32_t ibm_rom_basic_base = 0; - -/* NTS: The "Epson check" code in Windows 2.1 only compares up to the end of "NEC Corporation" */ -const std::string pc98_copyright_str = "Copyright (C) 1983 by NEC Corporation / Microsoft Corp.\x0D\x0A"; - -/* more strange data involved in the "Epson check" */ -const unsigned char pc98_epson_check_2[0x27] = { - 0x26,0x8A,0x05,0xA8,0x10,0x75,0x11,0xC6,0x06,0xD6,0x09,0x1B,0xC6,0x06,0xD7,0x09, - 0x4B,0xC6,0x06,0xD8,0x09,0x48,0xEB,0x0F,0xC6,0x06,0xD6,0x09,0x1A,0xC6,0x06,0xD7 , - 0x09,0x70,0xC6,0x06,0xD8,0x09,0x71 -}; - -bool enable_pc98_copyright_string = false; - -/* mouse.cpp */ -extern bool pc98_40col_text; -extern bool en_bios_ps2mouse; -extern bool rom_bios_8x8_cga_font; -extern bool pcibus_enable; -extern bool enable_fpu; - -bool pc98_timestamp5c = true; // port 5ch and 5eh "time stamp/hardware wait" - -uint32_t Keyb_ig_status(); -bool VM_Boot_DOSBox_Kernel(); -Bitu bios_post_parport_count(); -Bitu bios_post_comport_count(); -void pc98_update_cpu_page_ptr(void); -bool KEYBOARD_Report_BIOS_PS2Mouse(); -bool gdc_5mhz_according_to_bios(void); -void pc98_update_display_page_ptr(void); -void pc98_update_palette(void); -bool MEM_map_ROM_alias_physmem(Bitu start,Bitu end); -void MOUSE_Startup(Section *sec); -void Mouse_PS2SetSamplingRate(uint8_t rate); -bool Mouse_PS2SetPacketSize(uint8_t packet_size); -void change_output(int output); -void runBoot(const char *str); -void SetIMPosition(void); -bool isDBCSCP(); -Bitu INT60_Handler(void); -Bitu INT6F_Handler(void); -#if defined(USE_TTF) -void ttf_switch_on(bool ss), ttf_switch_off(bool ss), ttf_setlines(int cols, int lins); -#endif - -/* Rate limit log entries regarding APM AH=05h CPU IDLE because Windows 98's APM driver likes to call it way too much per second */ -pic_tickindex_t APM_log_cpu_idle_next_report = 0; -unsigned long APM_log_cpu_idle = 0; - -unsigned long APM_WakeupKeys = 0; - -/* APM events (eventually ACPI as well) */ -unsigned long PowerButtonClicks = 0; -bool APM_ResumeNotificationFromSuspend = false; -bool APM_ResumeNotificationFromStandby = false; -bool APM_PowerButtonSendsSuspend = true; - - -bool bochs_port_e9 = false; -bool isa_memory_hole_512kb = false; -bool isa_memory_hole_15mb = false; -bool int15_wait_force_unmask_irq = false; - -int unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; - -unsigned int reset_post_delay = 0; - -Bitu call_irq_default = 0; -uint16_t biosConfigSeg=0; - -static constexpr unsigned int ACPI_PMTIMER_CLOCK_RATE = 3579545; /* 3.579545MHz */ - -pic_tickindex_t ACPI_PMTIMER_BASE_TIME = 0; -uint32_t ACPI_PMTIMER_BASE_COUNT = 0; -uint32_t ACPI_PMTIMER_MASK = 0xFFFFFFu; /* 24-bit mode */ - -uint32_t ACPI_PMTIMER(void) { - pic_tickindex_t pt = PIC_FullIndex() - ACPI_PMTIMER_BASE_TIME; - uint32_t ct = (uint32_t)((pt * ACPI_PMTIMER_CLOCK_RATE) / 1000.0); - return ct; -} - -void ACPI_PMTIMER_Event(Bitu /*val*/); -void ACPI_PMTIMER_ScheduleNext(void) { - const uint32_t now_ct = ACPI_PMTIMER() & ACPI_PMTIMER_MASK; - const uint32_t next_delay_ct = (ACPI_PMTIMER_MASK + 1u) - now_ct; - const pic_tickindex_t delay = (1000.0 * next_delay_ct) / (pic_tickindex_t)ACPI_PMTIMER_CLOCK_RATE; - - LOG(LOG_MISC,LOG_DEBUG)("ACPI PM TIMER SCHEDULE: now=0x%x next=0x%x delay=%.3f",now_ct,next_delay_ct,(double)delay); - PIC_AddEvent(ACPI_PMTIMER_Event,delay); -} - -void ACPI_PMTIMER_CHECK(void) { /* please don't call this often */ - PIC_RemoveEvents(ACPI_PMTIMER_Event); - LOG(LOG_MISC,LOG_DEBUG)("ACPI PM TIMER CHECK"); - ACPI_PMTIMER_ScheduleNext(); -} - -Bitu BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION = ~0u; -Bitu BIOS_DEFAULT_IRQ0_LOCATION = ~0u; // (RealMake(0xf000,0xfea5)) -Bitu BIOS_DEFAULT_IRQ1_LOCATION = ~0u; // (RealMake(0xf000,0xe987)) -Bitu BIOS_DEFAULT_IRQ07_DEF_LOCATION = ~0u; // (RealMake(0xf000,0xff55)) -Bitu BIOS_DEFAULT_IRQ815_DEF_LOCATION = ~0u; // (RealMake(0xf000,0xe880)) - -Bitu BIOS_DEFAULT_HANDLER_LOCATION = ~0u; // (RealMake(0xf000,0xff53)) -Bitu BIOS_DEFAULT_INT5_LOCATION = ~0u; // (RealMake(0xf000,0xff54)) - -Bitu BIOS_VIDEO_TABLE_LOCATION = ~0u; // RealMake(0xf000,0xf0a4) -Bitu BIOS_VIDEO_TABLE_SIZE = 0u; - -Bitu BIOS_DEFAULT_RESET_LOCATION = ~0u; // RealMake(0xf000,0xe05b) -Bitu BIOS_DEFAULT_RESET_CODE_LOCATION = ~0u; - -bool allow_more_than_640kb = false; - -unsigned int APM_BIOS_connected_minor_version = 0;// what version the OS connected to us with. default to 1.0 -unsigned int APM_BIOS_minor_version = 2; // what version to emulate e.g to emulate 1.2 set this to 2 - -static bool apm_realmode_connected = false; - -/* default bios type/version/date strings */ -const char* const bios_type_string = "IBM COMPATIBLE BIOS for DOSBox-X"; -const char* const bios_version_string = "DOSBox-X BIOS v1.0"; -const char* const bios_date_string = "01/01/92"; - -bool APM_inactivity_timer = true; - -RegionAllocTracking rombios_alloc; - -Bitu rombios_minimum_location = 0xF0000; /* minimum segment allowed */ -Bitu rombios_minimum_size = 0x10000; - -static bool ACPI_SCI_EN = false; -static bool ACPI_BM_RLD = false; - -static IO_Callout_t acpi_iocallout = IO_Callout_t_none; - -static unsigned int ACPI_PM1_Enable = 0; -static unsigned int ACPI_PM1_Status = 0; -static constexpr unsigned int ACPI_PM1_Enable_TMR_EN = (1u << 0u); -static constexpr unsigned int ACPI_PM1_Enable_GBL_EN = (1u << 5u); -static constexpr unsigned int ACPI_PM1_Enable_PWRBTN_EN = (1u << 8u); -static constexpr unsigned int ACPI_PM1_Enable_SLPBTN_EN = (1u << 9u); -static constexpr unsigned int ACPI_PM1_Enable_RTC_EN = (1u << 10u); - -unsigned int ACPI_buffer_global_lock = 0; - -unsigned long ACPI_FACS_GlobalLockValue(void) { - if (ACPI_buffer && ACPI_buffer_global_lock != 0) - return host_readd(ACPI_buffer+ACPI_buffer_global_lock); - - return 0; -} - -/* Triggered by GBL_RLS bit */ -static void ACPI_OnGuestGlobalRelease(void) { - LOG(LOG_MISC,LOG_DEBUG)("ACPI GBL_RLS event. Global lock = %lx",ACPI_FACS_GlobalLockValue()); -} - -bool ACPI_GuestEnabled(void) { - return ACPI_SCI_EN; -} - -static void ACPI_SCI_Check(void) { - if (ACPI_SCI_EN) { - if (ACPI_PM1_Status & ACPI_PM1_Enable) { - LOG(LOG_MISC,LOG_DEBUG)("ACPI SCI interrupt"); - PIC_ActivateIRQ(ACPI_IRQ); - } - } -} - -void ACPI_PowerButtonEvent(void) { - if (ACPI_SCI_EN) { - if (!(ACPI_PM1_Status & ACPI_PM1_Enable_PWRBTN_EN)) { - ACPI_PM1_Status |= ACPI_PM1_Enable_PWRBTN_EN; - ACPI_SCI_Check(); - } - } -} - -void ACPI_PMTIMER_Event(Bitu /*val*/) { - if (!(ACPI_PM1_Status & ACPI_PM1_Enable_TMR_EN)) { - ACPI_PM1_Status |= ACPI_PM1_Enable_TMR_EN; - ACPI_SCI_Check(); - } - - ACPI_PMTIMER_ScheduleNext(); -} - -/* you can't very well write strings with this, but you could write codes */ -static void acpi_cb_port_debug_w(Bitu /*port*/,Bitu val,Bitu /*iolen*/) { - LOG(LOG_MISC,LOG_DEBUG)("ACPI debug: 0x%x\n",(unsigned int)val); -} - -static void acpi_cb_port_smi_cmd_w(Bitu /*port*/,Bitu val,Bitu /*iolen*/) { - /* 8-bit SMI_CMD port */ - LOG(LOG_MISC,LOG_DEBUG)("ACPI SMI_CMD %x",(unsigned int)val); - - if (val == ACPI_ENABLE_CMD) { - if (!ACPI_SCI_EN) { - LOG(LOG_MISC,LOG_DEBUG)("Guest enabled ACPI"); - ACPI_SCI_EN = true; - ACPI_PMTIMER_CHECK(); - ACPI_SCI_Check(); - } - } - else if (val == ACPI_DISABLE_CMD) { - if (ACPI_SCI_EN) { - LOG(LOG_MISC,LOG_DEBUG)("Guest disabled ACPI"); - ACPI_PMTIMER_CHECK(); - ACPI_SCI_EN = false; - } - } -} - -static Bitu acpi_cb_port_cnt_blk_r(Bitu port,Bitu /*iolen*/) { - /* 16-bit register (PM1_CNT_LEN == 2) */ - Bitu ret = 0; - if (ACPI_SCI_EN) ret |= (1u << 0u); - if (ACPI_BM_RLD) ret |= (1u << 1u); - /* GBL_RLS is write only */ - /* TODO: bits 3-8 are "reserved by the ACPI driver"? So are they writeable then? */ - /* TODO: SLP_TYPx */ - /* SLP_EN is write-only */ - - LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_CNT_BLK read port %x ret %x",(unsigned int)port,(unsigned int)ret); - return ret; -} - -static void acpi_cb_port_cnt_blk_w(Bitu port,Bitu val,Bitu iolen) { - /* 16-bit register (PM1_CNT_LEN == 2) */ - LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_CNT_BLK write port %x val %x iolen %x",(unsigned int)port,(unsigned int)val,(unsigned int)iolen); - - /* BIOS controls SCI_EN and therefore guest cannot change it */ - ACPI_BM_RLD = !!(val & (1u << 1u)); - /* GLB_RLS is write only and triggers an SMI interrupt to pass execution to the BIOS, usually to indicate a release of the global lock and set of pending bit */ - if (val & (1u << 2u)/*GBL_RLS*/) ACPI_OnGuestGlobalRelease(); - /* TODO: bits 3-8 are "reserved by the ACPI driver"? So are they writeable then? */ - /* TODO: SLP_TYPx */ - /* SLP_EN is write-only */ -} - -static Bitu acpi_cb_port_evtst_blk_r(Bitu port,Bitu /*iolen*/) { - /* 16-bit register (PM1_EVT_LEN/2 == 2) */ - Bitu ret = ACPI_PM1_Status; - LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_EVT_BLK(status) read port %x ret %x",(unsigned int)port,(unsigned int)ret); - return ret; -} - -static void acpi_cb_port_evtst_blk_w(Bitu port,Bitu val,Bitu iolen) { - /* 16-bit register (PM1_EVT_LEN/2 == 2) */ - LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_EVT_BLK(status) write port %x val %x iolen %x",(unsigned int)port,(unsigned int)val,(unsigned int)iolen); - ACPI_PM1_Status &= (~val); - ACPI_SCI_Check(); -} - -static Bitu acpi_cb_port_evten_blk_r(Bitu port,Bitu /*iolen*/) { - /* 16-bit register (PM1_EVT_LEN/2 == 2) */ - Bitu ret = ACPI_PM1_Enable; - LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_EVT_BLK(enable) read port %x ret %x",(unsigned int)port,(unsigned int)ret); - return ret; -} - -static Bitu acpi_cb_port_tmr_r(Bitu port,Bitu /*iolen*/) { - /* 24 or 32-bit TMR_VAL (depends on the mask value and whether our ACPI structures tell the OS it's 32-bit wide) */ - Bitu ret = (Bitu)ACPI_PMTIMER(); - LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM_TMR read port %x ret %x",(unsigned int)port,(unsigned int)ret); - return ret; -} - -static void acpi_cb_port_evten_blk_w(Bitu port,Bitu val,Bitu iolen) { - /* 16-bit register (PM1_EVT_LEN/2 == 2) */ - LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_EVT_BLK(enable) write port %x val %x iolen %x",(unsigned int)port,(unsigned int)val,(unsigned int)iolen); - ACPI_PM1_Enable = val; - ACPI_SCI_Check(); -} - -static IO_ReadHandler* acpi_cb_port_r(IO_CalloutObject &co,Bitu port,Bitu iolen) { - (void)co; - (void)iolen; - - if ((port & (~1u)) == (ACPI_PM1A_EVT_BLK+0) && iolen >= 2) - return acpi_cb_port_evtst_blk_r; - else if ((port & (~1u)) == (ACPI_PM1A_EVT_BLK+2) && iolen >= 2) - return acpi_cb_port_evten_blk_r; - else if ((port & (~1u)) == ACPI_PM1A_CNT_BLK && iolen >= 2) - return acpi_cb_port_cnt_blk_r; - /* The ACPI specification says nothing about reading SMI_CMD so assume that means write only */ - else if ((port & (~3u)) == ACPI_PM_TMR_BLK && iolen >= 4) - return acpi_cb_port_tmr_r; - - return NULL; -} - -static IO_WriteHandler* acpi_cb_port_w(IO_CalloutObject &co,Bitu port,Bitu iolen) { - (void)co; - (void)iolen; - - if ((port & (~1u)) == (ACPI_PM1A_EVT_BLK+0) && iolen >= 2) - return acpi_cb_port_evtst_blk_w; - else if ((port & (~1u)) == (ACPI_PM1A_EVT_BLK+2) && iolen >= 2) - return acpi_cb_port_evten_blk_w; - else if ((port & (~1u)) == ACPI_PM1A_CNT_BLK && iolen >= 2) - return acpi_cb_port_cnt_blk_w; - else if ((port & (~3u)) == ACPI_SMI_CMD) - return acpi_cb_port_smi_cmd_w; - else if (port == ACPI_DEBUG_IO && iolen >= 4) - return acpi_cb_port_debug_w; - else if ((port & (~3u)) == ACPI_PM_TMR_BLK) { - LOG(LOG_MISC,LOG_DEBUG)("write ACPI_PM_TMR_BLK port=0x%x iolen=%u",(unsigned int)port,(unsigned int)iolen); - } - - return NULL; -} - -bool MEM_map_ROM_physmem(Bitu start,Bitu end); -bool MEM_unmap_physmem(Bitu start,Bitu end); - -static std::string bochs_port_e9_line; - -static void bochs_port_e9_flush() { - if (!bochs_port_e9_line.empty()) { - LOG_MSG("Bochs port E9h: %s",bochs_port_e9_line.c_str()); - bochs_port_e9_line.clear(); - } -} - -void bochs_port_e9_write(Bitu port,Bitu val,Bitu /*iolen*/) { - (void)port;//UNUSED - if (val == '\n' || val == '\r') { - bochs_port_e9_flush(); - } - else { - bochs_port_e9_line += (char)val; - if (bochs_port_e9_line.length() >= 256) - bochs_port_e9_flush(); - } -} - -LoopHandler *DOSBOX_GetLoop(void); - -static Bitu APM_SuspendedLoopFunc(void); - -static RealPt APM_SuspendedLoopRptr=0; - -/* "wakeup" keys were pressed and released */ -void APM_Suspend_Wakeup_Key(void) { - APM_WakeupKeys++; -} - -void APM_SuspendedLoopLeaveState() { - APM_WakeupKeys = 0; - PowerButtonClicks = 0; - - /* Turn on the VGA display, assuming it was on when suspended */ - if (IS_VGA_ARCH) { - Bitu crtc; - Bitu tmp; - - IO_Write(0x3C4,0x01); // clocking mode - tmp = IO_Read(0x3C5); - IO_Write(0x3C5,tmp & (~0x20)); // turn on screen - - // NTS: vga_crtc.cpp/vga_draw.cpp does not emulate blanking the display upon disabling sync signals - crtc = (IO_Read(0x3CC) & 1) ? 0x3D4 : 0x3B4; - IO_Write(crtc,0x17); // mode control - tmp = IO_Read(crtc+1); - IO_Write(crtc+1,tmp | 0x80); // enable sync - } -} - -/* callback for APM suspended loop routine in BIOS */ -static Bitu APM_SuspendedLoopFunc(void) { - if (APM_WakeupKeys != 0 || PowerButtonClicks != 0) { - APM_SuspendedLoopLeaveState(); - LOG_MSG("APM: leaving suspended state"); - reg_eip += 3; /* skip over HLT+JMP to get to RET */ - return CBRET_NONE; - } - - return CBRET_NONE; -} - -bool PowerManagementEnabledButton() { - if (IS_PC98_ARCH) /* power management not yet known or implemented */ - return false; - - if (ACPI_GuestEnabled()) - ACPI_PowerButtonEvent(); - - if (apm_realmode_connected) /* guest has connected to the APM BIOS */ - return true; - - return false; -} - -void APM_BeginSuspendedMode(void) { - /* Enable interrupts, dumbass. We use HLT here. */ - CPU_STI(); - - /* WARNING: This assumes, like all callbacks, that they reside in the same segment. - * The APM BIOS entry point can be called from real mode, 16-bit or 32-bit protected mode, - * therefore this code cannot assume any particular segment value and can only safely - * change reg_(e)ip to direct CPU execution. The most likely scenario is that the - * return address pushed here will point at the IRET in the INT 15 handler. */ - if (cpu.stack.big) CPU_Push32(reg_eip); - else CPU_Push16(reg_ip); - - reg_ip = APM_SuspendedLoopRptr & 0xFFFF; /* offset only */ - - /* reset counters */ - PowerButtonClicks = 0; - APM_WakeupKeys = 0; - - /* Turn off the VGA display */ - if (IS_VGA_ARCH) { - Bitu crtc; - Bitu tmp; - - IO_Write(0x3C4,0x01); // clocking mode - tmp = IO_Read(0x3C5); - IO_Write(0x3C5,tmp | 0x20); // turn off screen - - // NTS: vga_crtc.cpp/vga_draw.cpp does not emulate blanking the display upon disabling sync signals - crtc = (IO_Read(0x3CC) & 1) ? 0x3D4 : 0x3B4; - IO_Write(crtc,0x17); // mode control - tmp = IO_Read(crtc+1); - IO_Write(crtc+1,tmp & (~0x80)); // disable sync - } - - LOG_MSG("System is now in APM suspend mode"); -} - - -void ROMBIOS_DumpMemory() { - rombios_alloc.logDump(); -} - -void ROMBIOS_SanityCheck() { - rombios_alloc.sanityCheck(); -} - -Bitu ROMBIOS_MinAllocatedLoc() { - Bitu r = rombios_alloc.getMinAddress(); - - if (r > (0x100000u - rombios_minimum_size)) - r = (0x100000u - rombios_minimum_size); - - return r & ~0xFFFu; -} - -void ROMBIOS_FreeUnusedMinToLoc(Bitu phys) { - Bitu new_phys; - - if (rombios_minimum_location & 0xFFF) E_Exit("ROMBIOS: FreeUnusedMinToLoc minimum location not page aligned"); - - phys &= ~0xFFFUL; - new_phys = rombios_alloc.freeUnusedMinToLoc(phys) & (~0xFFFUL); - assert(new_phys >= phys); - if (phys < new_phys) MEM_unmap_physmem(phys,new_phys-1); - rombios_minimum_location = new_phys; - ROMBIOS_SanityCheck(); - ROMBIOS_DumpMemory(); -} - -bool ROMBIOS_FreeMemory(Bitu phys) { - return rombios_alloc.freeMemory(phys); -} - -Bitu ROMBIOS_GetMemory(Bitu bytes,const char *who,Bitu alignment,Bitu must_be_at) { - return rombios_alloc.getMemory(bytes,who,alignment,must_be_at); -} - -void ROMBIOS_InitForCustomBIOS(void) { - rombios_alloc.initSetRange(0xD8000,0xE0000); -} - -static IO_Callout_t dosbox_int_iocallout = IO_Callout_t_none; - -static unsigned char dosbox_int_register_shf = 0; -static uint32_t dosbox_int_register = 0; -static unsigned char dosbox_int_regsel_shf = 0; -static uint32_t dosbox_int_regsel = 0; -static bool dosbox_int_error = false; -static bool dosbox_int_busy = false; - -#define STRINGIZE_HELPER(A) #A -#define STRINGIZE(A) STRINGIZE_HELPER(A) -#define PPCAT_HELPER(A, B, C) A ## . ## B ## . ## C -#define PPCAT(A, B, C) PPCAT_HELPER(A, B, C) - -#define INTDEV_VERSION_BUMP 2 -#define INTDEV_VERSION_MAJOR 1 -#define INTDEV_VERSION_MINOR 0 -#define INTDEV_VERSION_SUB 1 - -static const char *dosbox_int_version = "DOSBox-X integration device v" STRINGIZE(PPCAT(INTDEV_VERSION_MAJOR, INTDEV_VERSION_MINOR, INTDEV_VERSION_SUB)); -static const char *dosbox_int_ver_read = NULL; - -struct dosbox_int_saved_state { - unsigned char dosbox_int_register_shf; - uint32_t dosbox_int_register; - unsigned char dosbox_int_regsel_shf; - uint32_t dosbox_int_regsel; - bool dosbox_int_error; - bool dosbox_int_busy; -}; - -#define DOSBOX_INT_SAVED_STATE_MAX 4 - -struct dosbox_int_saved_state dosbox_int_saved[DOSBOX_INT_SAVED_STATE_MAX]; -int dosbox_int_saved_sp = -1; - -/* for use with interrupt handlers in DOS/Windows that need to save IG state - * to ensure that IG state is restored on return in order to not interfere - * with anything userspace is doing (as an alternative to wrapping all access - * in CLI/STI or PUSHF/CLI/POPF) */ -bool dosbox_int_push_save_state(void) { - - if (dosbox_int_saved_sp >= (DOSBOX_INT_SAVED_STATE_MAX-1)) - return false; - - struct dosbox_int_saved_state *ss = &dosbox_int_saved[++dosbox_int_saved_sp]; - - ss->dosbox_int_register_shf = dosbox_int_register_shf; - ss->dosbox_int_register = dosbox_int_register; - ss->dosbox_int_regsel_shf = dosbox_int_regsel_shf; - ss->dosbox_int_regsel = dosbox_int_regsel; - ss->dosbox_int_error = dosbox_int_error; - ss->dosbox_int_busy = dosbox_int_busy; - return true; -} - -bool dosbox_int_pop_save_state(void) { - if (dosbox_int_saved_sp < 0) - return false; - - struct dosbox_int_saved_state *ss = &dosbox_int_saved[dosbox_int_saved_sp--]; - - dosbox_int_register_shf = ss->dosbox_int_register_shf; - dosbox_int_register = ss->dosbox_int_register; - dosbox_int_regsel_shf = ss->dosbox_int_regsel_shf; - dosbox_int_regsel = ss->dosbox_int_regsel; - dosbox_int_error = ss->dosbox_int_error; - dosbox_int_busy = ss->dosbox_int_busy; - return true; -} - -bool dosbox_int_discard_save_state(void) { - if (dosbox_int_saved_sp < 0) - return false; - - dosbox_int_saved_sp--; - return true; -} - -extern bool user_cursor_locked; -extern int user_cursor_x,user_cursor_y; -extern int user_cursor_sw,user_cursor_sh; -extern int master_cascade_irq,bootdrive; -extern bool enable_slave_pic; -extern bool bootguest, use_quick_reboot; -extern uint16_t countryNo; -bool bootvm = false, bootfast = false; -static std::string dosbox_int_debug_out; - -uint32_t VGA_QuerySizeIG(void); - -uint32_t Mixer_MIXQ(void); -uint32_t Mixer_MIXC(void); -void Mixer_MIXC_Write(uint32_t v); -PhysPt Mixer_MIXWritePos(void); -void Mixer_MIXWritePos_Write(PhysPt np); -void Mixer_MIXWriteBegin_Write(PhysPt np); -void Mixer_MIXWriteEnd_Write(PhysPt np); - -/* read triggered, update the regsel */ -void dosbox_integration_trigger_read() { - dosbox_int_error = false; - - switch (dosbox_int_regsel) { - case 0: /* Identification */ - dosbox_int_register = 0xD05B0740; - break; - case 1: /* test */ - break; - case 2: /* version string */ - if (dosbox_int_ver_read == NULL) - dosbox_int_ver_read = dosbox_int_version; - - dosbox_int_register = 0; - for (Bitu i=0;i < 4;i++) { - if (*dosbox_int_ver_read == 0) { - dosbox_int_ver_read = dosbox_int_version; - break; - } - - dosbox_int_register += ((uint32_t)((unsigned char)(*dosbox_int_ver_read++))) << (uint32_t)(i * 8); - } - break; - case 3: /* version number */ - dosbox_int_register = INTDEV_VERSION_MAJOR + (INTDEV_VERSION_MINOR << 8U) + (INTDEV_VERSION_SUB << 16U) + (INTDEV_VERSION_BUMP << 24U); - break; - case 4: /* current emulator time as 16.16 fixed point */ - dosbox_int_register = (uint32_t)(PIC_FullIndex() * 0x10000); - break; - case 5: // DOSBox-X version number major (e.g. 2022) - { - const char * ver = strchr(VERSION, '.'); - dosbox_int_register = ver == NULL ? 0 : atoi(std::string(VERSION).substr(0, strlen(ver) - strlen(VERSION)).c_str()); - break; - } - case 6: // DOSBox-X version number minor (e.g. 8) - { - const char * ver = strchr(VERSION, '.'); - dosbox_int_register = ver == NULL ? 0 : atoi(ver + 1); - break; - } - case 7: // DOSBox-X version number sub (e.g. 0) - { - const char * ver = strchr(VERSION, '.'); - ver = strchr(ver + 1, '.'); - dosbox_int_register = ver == NULL ? 0 : atoi(ver + 1); - break; - } - case 8: // DOSBox-X platform type - dosbox_int_register = 0; -#if defined(HX_DOS) - dosbox_int_register = 4; -#elif defined(WIN32) - dosbox_int_register = 1; -#elif defined(LINUX) - dosbox_int_register = 2; -#elif defined(MACOSX) - dosbox_int_register = 3; -#elif defined(OS2) - dosbox_int_register = 5; -#else - dosbox_int_register = 0; -#endif - if (control->opt_securemode || control->SecureMode()) dosbox_int_register = 0; -#if OS_BIT_INT == 64 - dosbox_int_register += 0x20; // 64-bit -#else - dosbox_int_register += 0x10; // 32-bit -#endif -#if defined(C_SDL2) - dosbox_int_register += 0x200; // SDL2 -#elif defined(SDL_DOSBOX_X_SPECIAL) - dosbox_int_register += 0x100; // SDL1 (modified) -#endif - break; - case 9: // DOSBox-X machine type - dosbox_int_register = machine; - break; - - case 0x4B6F4400: // DOS kernel status - dosbox_int_register = dos_kernel_disabled ? 0: 1; - break; - case 0x4B6F4401: // DOS codepage number - dosbox_int_register = dos_kernel_disabled ? 0: dos.loaded_codepage; - break; - case 0x4B6F4402: // DOS country number - dosbox_int_register = dos_kernel_disabled ? 0: countryNo; - break; - case 0x4B6F4403: // DOS version major - dosbox_int_register = dos_kernel_disabled ? 0: dos.version.major; - break; - case 0x4B6F4404: // DOS version minor - dosbox_int_register = dos_kernel_disabled ? 0: dos.version.minor; - break; - case 0x4B6F4405: // DOS error code - dosbox_int_register = dos_kernel_disabled ? 0 : dos.errorcode; - break; - case 0x4B6F4406: // DOS boot drive - dosbox_int_register = bootdrive; - break; - case 0x4B6F4407: // DOS current drive - dosbox_int_register = dos_kernel_disabled ? 0 : DOS_GetDefaultDrive(); - break; - case 0x4B6F4408: // DOS LFN status - dosbox_int_register = dos_kernel_disabled || !uselfn ? 0: 1; - break; - - case 0x5158494D: /* query mixer output 'MIXQ' */ - /* bits [19:0] = sample rate in Hz or 0 if mixer is not mixing AT ALL - * bits [23:20] = number of channels (at this time, always 2 aka stereo) - * bits [29:29] = 1=swap stereo 0=normal - * bits [30:30] = 1=muted 0=not muted - * bits [31:31] = 1=sound 0=nosound */ - dosbox_int_register = Mixer_MIXQ(); - break; - - case 0x4358494D: /* query mixer output 'MIXC' */ - dosbox_int_register = Mixer_MIXC(); - break; - - case 0x5058494D: /* query mixer output 'MIXP' */ - dosbox_int_register = Mixer_MIXWritePos(); - break; - - case 0x4258494D: /* query mixer output 'MIXB' */ - break; - - case 0x4558494D: /* query mixer output 'MIXE' */ - break; - - case 0x6845C0: /* query VGA display size */ - dosbox_int_register = VGA_QuerySizeIG(); - break; - - case 0x825901: /* PIC configuration */ - /* bits [7:0] = cascade interrupt or 0xFF if none - * bit [8:8] = primary PIC present - * bit [9:9] = secondary PIC present */ - if (master_cascade_irq >= 0) - dosbox_int_register = ((unsigned int)master_cascade_irq & 0xFFu); - else - dosbox_int_register = 0xFFu; - - dosbox_int_register |= 0x100; // primary always present - if (enable_slave_pic) dosbox_int_register |= 0x200; - break; - - case 0x823780: /* ISA DMA injection, single byte/word (read from memory) */ - break; - -// case 0x804200: /* keyboard input injection -- not supposed to read */ -// break; - - case 0x804201: /* keyboard status */ - dosbox_int_register = Keyb_ig_status(); - break; - - case 0x434D54: /* read user mouse status */ - dosbox_int_register = - (user_cursor_locked ? (1UL << 0UL) : 0UL); /* bit 0 = mouse capture lock */ - break; - - case 0x434D55: /* read user mouse cursor position */ - dosbox_int_register = (uint32_t((uint16_t)user_cursor_y & 0xFFFFUL) << 16UL) | uint32_t((uint16_t)user_cursor_x & 0xFFFFUL); - break; - - case 0x434D56: { /* read user mouse cursor position (normalized for Windows 3.x) */ - signed long long x = ((signed long long)user_cursor_x << 16LL) / (signed long long)(user_cursor_sw-1); - signed long long y = ((signed long long)user_cursor_y << 16LL) / (signed long long)(user_cursor_sh-1); - if (x < 0x0000LL) x = 0x0000LL; - if (x > 0xFFFFLL) x = 0xFFFFLL; - if (y < 0x0000LL) y = 0x0000LL; - if (y > 0xFFFFLL) y = 0xFFFFLL; - dosbox_int_register = ((unsigned int)y << 16UL) | (unsigned int)x; - } break; - - case 0xC54010: /* Screenshot/capture trigger */ - /* TODO: This should also be hidden behind an enable switch, so that rogue DOS development - * can't retaliate if the user wants to capture video or screenshots. */ -#if (C_SSHOT) - dosbox_int_register = 0x00000000; // available - if (CaptureState & CAPTURE_IMAGE) - dosbox_int_register |= 1 << 0; // Image capture is in progress - if (CaptureState & CAPTURE_VIDEO) - dosbox_int_register |= 1 << 1; // Video capture is in progress - if (CaptureState & CAPTURE_WAVE) - dosbox_int_register |= 1 << 2; // WAVE capture is in progress -#else - dosbox_int_register = 0xC0000000; // not available (bit 31 set), not enabled (bit 30 set) -#endif - break; - - case 0xAA55BB66UL: /* interface reset result */ - break; - - default: - dosbox_int_register = 0xAA55AA55; - dosbox_int_error = true; - break; - } - - LOG(LOG_MISC,LOG_DEBUG)("DOSBox-X integration read 0x%08lx got 0x%08lx (err=%u)\n", - (unsigned long)dosbox_int_regsel, - (unsigned long)dosbox_int_register, - dosbox_int_error?1:0); -} - -bool watchdog_set = false; - -void Watchdog_Timeout_Event(Bitu /*val*/) { - LOG_MSG("Watchdog timeout occurred"); - CPU_Raise_NMI(); -} - -void Watchdog_Timer_Clear(void) { - if (watchdog_set) { - PIC_RemoveEvents(Watchdog_Timeout_Event); - watchdog_set = false; - } -} - -void Watchdog_Timer_Set(uint32_t timeout_ms) { - Watchdog_Timer_Clear(); - - if (timeout_ms != 0) { - watchdog_set = true; - PIC_AddEvent(Watchdog_Timeout_Event,(double)timeout_ms); - } -} - -unsigned int mouse_notify_mode = 0; -// 0 = off -// 1 = trigger as PS/2 mouse interrupt - -/* write triggered */ -void dosbox_integration_trigger_write() { - dosbox_int_error = false; - - LOG(LOG_MISC,LOG_DEBUG)("DOSBox-X integration write 0x%08lx val 0x%08lx\n", - (unsigned long)dosbox_int_regsel, - (unsigned long)dosbox_int_register); - - switch (dosbox_int_regsel) { - case 1: /* test */ - break; - - case 2: /* version string */ - dosbox_int_ver_read = NULL; - break; - - case 0xDEB0: /* debug output (to log) */ - for (unsigned int b=0;b < 4;b++) { - unsigned char c = (unsigned char)(dosbox_int_register >> (b * 8U)); - if (c == '\n' || dosbox_int_debug_out.length() >= 200) { - LOG_MSG("Client debug message: %s\n",dosbox_int_debug_out.c_str()); - dosbox_int_debug_out.clear(); - } - else if (c != 0) { - dosbox_int_debug_out += ((char)c); - } - else { - break; - } - } - dosbox_int_register = 0; - break; - - case 0xDEB1: /* debug output clear */ - dosbox_int_debug_out.clear(); - break; - - case 0x52434D: /* release mouse capture 'MCR' */ - void GFX_ReleaseMouse(void); - GFX_ReleaseMouse(); - break; - - case 0x5158494D: /* query mixer output 'MIXQ' */ - break; - - case 0x4358494D: /* query mixer output 'MIXC' */ - Mixer_MIXC_Write(dosbox_int_register); - break; - - case 0x5058494D: /* query mixer output 'MIXP' */ - Mixer_MIXWritePos_Write(dosbox_int_register); - break; - - case 0x4258494D: /* query mixer output 'MIXB' */ - Mixer_MIXWriteBegin_Write(dosbox_int_register); - break; - - case 0x4558494D: /* query mixer output 'MIXE' */ - Mixer_MIXWriteEnd_Write(dosbox_int_register); - break; - - case 0x57415444: /* Set/clear watchdog timer 'WATD' */ - Watchdog_Timer_Set(dosbox_int_register); - break; - - case 0x808602: /* NMI (INT 02h) interrupt injection */ - { - dosbox_int_register_shf = 0; - dosbox_int_regsel_shf = 0; - CPU_Raise_NMI(); - } - break; - - case 0x825900: /* PIC interrupt injection */ - { - dosbox_int_register_shf = 0; - dosbox_int_regsel_shf = 0; - /* bits [7:0] = IRQ to signal (must be 0-15) - * bit [8:8] = 1=raise 0=lower IRQ */ - uint8_t IRQ = dosbox_int_register&0xFFu; - bool raise = (dosbox_int_register>>8u)&1u; - - if (IRQ < 16) { - if (raise) - PIC_ActivateIRQ(IRQ); - else - PIC_DeActivateIRQ(IRQ); - } - } - break; - - case 0x823700: /* ISA DMA injection, single byte/word (write to memory) */ - { - dosbox_int_register_shf = 0; - dosbox_int_regsel_shf = 0; - /* bits [7:0] = data byte if 8-bit DNA - * bits [15:0] = data word if 16-bit DMA - * bits [18:16] = DMA channel to send to */ - DmaChannel *ch = GetDMAChannel((dosbox_int_register>>16u)&7u); - if (ch != NULL) { - unsigned char tmp[2]; - - tmp[0] = (unsigned char)( dosbox_int_register & 0xFFu); - tmp[1] = (unsigned char)((dosbox_int_register >> 8u) & 0xFFu); - - /* NTS: DMA channel write will write tmp[0] if 8-bit, tmp[0]/tmp[1] if 16-bit */ - if (ch->Write(1/*one unit of transfer*/,tmp) == 1) { - dosbox_int_register = 0; - dosbox_int_error = false; - } - else { - dosbox_int_register = 0x823700; - dosbox_int_error = true; - } - } - else { - dosbox_int_register = 0x8237FF; - dosbox_int_error = true; - } - } - break; - - case 0x823780: /* ISA DMA injection, single byte/word (read from memory) */ - { - dosbox_int_register_shf = 0; - dosbox_int_regsel_shf = 0; - /* bits [18:16] = DMA channel to send to */ - DmaChannel *ch = GetDMAChannel((dosbox_int_register>>16u)&7u); - if (ch != NULL) { - unsigned char tmp[2]; - - /* NTS: DMA channel write will write tmp[0] if 8-bit, tmp[0]/tmp[1] if 16-bit */ - tmp[0] = tmp[1] = 0; - if (ch->Read(1/*one unit of transfer*/,tmp) == 1) { - dosbox_int_register = ((unsigned int)tmp[1] << 8u) + (unsigned int)tmp[0]; - dosbox_int_error = false; - } - else { - dosbox_int_register = 0x823700; - dosbox_int_error = true; - } - } - else { - dosbox_int_register = 0x8237FF; - dosbox_int_error = true; - } - } - break; - - case 0x804200: /* keyboard input injection */ - void Mouse_ButtonPressed(uint8_t button); - void Mouse_ButtonReleased(uint8_t button); - void pc98_keyboard_send(const unsigned char b); - void Mouse_CursorMoved(float xrel,float yrel,float x,float y,bool emulate); - void KEYBOARD_AUX_Event(float x,float y,Bitu buttons,int scrollwheel); - void KEYBOARD_AddBuffer(uint16_t data); - - switch ((dosbox_int_register>>8)&0xFF) { - case 0x00: // keyboard - if (IS_PC98_ARCH) - pc98_keyboard_send(dosbox_int_register&0xFF); - else - KEYBOARD_AddBuffer(dosbox_int_register&0xFF); - break; - case 0x01: // AUX - if (!IS_PC98_ARCH) - KEYBOARD_AddBuffer((dosbox_int_register&0xFF)|0x100/*AUX*/); - else // no such interface in PC-98 mode - dosbox_int_error = true; - break; - case 0x08: // mouse button injection - if (dosbox_int_register&0x80) Mouse_ButtonPressed(dosbox_int_register&0x7F); - else Mouse_ButtonReleased(dosbox_int_register&0x7F); - break; - case 0x09: // mouse movement injection (X) - Mouse_CursorMoved(((dosbox_int_register>>16UL) / 256.0f) - 1.0f,0,0,0,true); - break; - case 0x0A: // mouse movement injection (Y) - Mouse_CursorMoved(0,((dosbox_int_register>>16UL) / 256.0f) - 1.0f,0,0,true); - break; - case 0x0B: // mouse scrollwheel injection - // TODO - break; - default: - dosbox_int_error = true; - break; - } - break; - -// case 0x804201: /* keyboard status do not write */ -// break; - - /* this command is used to enable notification of mouse movement over the windows even if the mouse isn't captured */ - case 0x434D55: /* read user mouse cursor position */ - case 0x434D56: /* read user mouse cursor position (normalized for Windows 3.x) */ - mouse_notify_mode = dosbox_int_register & 0xFF; - LOG(LOG_MISC,LOG_DEBUG)("Mouse notify mode=%u",mouse_notify_mode); - break; - - case 0xC54010: /* Screenshot/capture trigger */ -#if (C_SSHOT) - void CAPTURE_ScreenShotEvent(bool pressed); - void CAPTURE_VideoEvent(bool pressed); -#endif - void CAPTURE_WaveEvent(bool pressed); - - /* TODO: It would be wise to grant/deny access to this register through another dosbox-x.conf option - * so that rogue DOS development cannot shit-spam the capture folder */ -#if (C_SSHOT) - if (dosbox_int_register & 1) - CAPTURE_ScreenShotEvent(true); - if (dosbox_int_register & 2) - CAPTURE_VideoEvent(true); -#endif - if (dosbox_int_register & 4) - CAPTURE_WaveEvent(true); - break; - - default: - dosbox_int_register = 0x55AA55AA; - dosbox_int_error = true; - break; - } -} - -/* PORT 0x28: Index - * 0x29: Data - * 0x2A: Status(R) or Command(W) - * 0x2B: Not yet assigned - * - * Registers are 32-bit wide. I/O to index and data rotate through the - * bytes of the register depending on I/O length, meaning that one 32-bit - * I/O read will read the entire register, while four 8-bit reads will - * read one byte out of 4. */ - -static Bitu dosbox_integration_port00_index_r(Bitu port,Bitu iolen) { - (void)port;//UNUSED - Bitu retb = 0; - Bitu ret = 0; - - while (iolen > 0) { - ret += ((dosbox_int_regsel >> (dosbox_int_regsel_shf * 8)) & 0xFFU) << (retb * 8); - if ((++dosbox_int_regsel_shf) >= 4) dosbox_int_regsel_shf = 0; - iolen--; - retb++; - } - - return ret; -} - -static void dosbox_integration_port00_index_w(Bitu port,Bitu val,Bitu iolen) { - (void)port;//UNUSED - - while (iolen > 0) { - uint32_t msk = 0xFFU << (dosbox_int_regsel_shf * 8); - dosbox_int_regsel = (dosbox_int_regsel & ~msk) + ((val & 0xFF) << (dosbox_int_regsel_shf * 8)); - if ((++dosbox_int_regsel_shf) >= 4) dosbox_int_regsel_shf = 0; - val >>= 8U; - iolen--; - } -} - -static Bitu dosbox_integration_port01_data_r(Bitu port,Bitu iolen) { - (void)port;//UNUSED - Bitu retb = 0; - Bitu ret = 0; - - while (iolen > 0) { - if (dosbox_int_register_shf == 0) dosbox_integration_trigger_read(); - ret += ((dosbox_int_register >> (dosbox_int_register_shf * 8)) & 0xFFU) << (retb * 8); - if ((++dosbox_int_register_shf) >= 4) dosbox_int_register_shf = 0; - iolen--; - retb++; - } - - return ret; -} - -static void dosbox_integration_port01_data_w(Bitu port,Bitu val,Bitu iolen) { - (void)port;//UNUSED - - while (iolen > 0) { - uint32_t msk = 0xFFU << (dosbox_int_register_shf * 8); - dosbox_int_register = (dosbox_int_register & ~msk) + ((val & 0xFF) << (dosbox_int_register_shf * 8)); - if ((++dosbox_int_register_shf) >= 4) dosbox_int_register_shf = 0; - if (dosbox_int_register_shf == 0) dosbox_integration_trigger_write(); - val >>= 8U; - iolen--; - } -} - -static Bitu dosbox_integration_port02_status_r(Bitu port,Bitu iolen) { - (void)iolen;//UNUSED - (void)port;//UNUSED - /* status */ - /* 7:6 = regsel byte index - * 5:4 = register byte index - * 3:2 = reserved - * 1 = error - * 0 = busy */ - return - ((unsigned int)dosbox_int_regsel_shf << 6u) + ((unsigned int)dosbox_int_register_shf << 4u) + - (dosbox_int_error ? 2u : 0u) + (dosbox_int_busy ? 1u : 0u); -} - -static void dosbox_integration_port02_command_w(Bitu port,Bitu val,Bitu iolen) { - (void)port; - (void)iolen; - switch (val) { - case 0x00: /* reset latch */ - dosbox_int_register_shf = 0; - dosbox_int_regsel_shf = 0; - break; - case 0x01: /* flush write */ - if (dosbox_int_register_shf != 0) { - dosbox_integration_trigger_write(); - dosbox_int_register_shf = 0; - } - break; - case 0x20: /* push state */ - if (dosbox_int_push_save_state()) { - dosbox_int_register_shf = 0; - dosbox_int_regsel_shf = 0; - dosbox_int_error = false; - dosbox_int_busy = false; - dosbox_int_regsel = 0xAA55BB66; - dosbox_int_register = 0xD05B0C5; - LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state saved"); - } - else { - LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to push state, stack overflow"); - dosbox_int_error = true; - } - break; - case 0x21: /* pop state */ - if (dosbox_int_pop_save_state()) { - LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state restored"); - } - else { - LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to pop state, stack underflow"); - dosbox_int_error = true; - } - break; - case 0x22: /* discard state */ - if (dosbox_int_discard_save_state()) { - LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state discarded"); - } - else { - LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to discard state, stack underflow"); - dosbox_int_error = true; - } - break; - case 0x23: /* discard all state */ - while (dosbox_int_discard_save_state()); - break; - case 0xFE: /* clear error */ - dosbox_int_error = false; - break; - case 0xFF: /* reset interface */ - dosbox_int_busy = false; - dosbox_int_error = false; - dosbox_int_regsel = 0xAA55BB66; - dosbox_int_register = 0xD05B0C5; - break; - default: - dosbox_int_error = true; - break; - } -} - -static IO_ReadHandler* const dosbox_integration_cb_ports_r[4] = { - dosbox_integration_port00_index_r, - dosbox_integration_port01_data_r, - dosbox_integration_port02_status_r, - NULL -}; - -static IO_ReadHandler* dosbox_integration_cb_port_r(IO_CalloutObject &co,Bitu port,Bitu iolen) { - (void)co; - (void)iolen; - return dosbox_integration_cb_ports_r[port&3]; -} - -static IO_WriteHandler* const dosbox_integration_cb_ports_w[4] = { - dosbox_integration_port00_index_w, - dosbox_integration_port01_data_w, - dosbox_integration_port02_command_w, - NULL -}; - -static IO_WriteHandler* dosbox_integration_cb_port_w(IO_CalloutObject &co,Bitu port,Bitu iolen) { - (void)co; - (void)iolen; - return dosbox_integration_cb_ports_w[port&3]; -} - -/* if mem_systems 0 then size_extended is reported as the real size else - * zero is reported. ems and xms can increase or decrease the other_memsystems - * counter using the BIOS_ZeroExtendedSize call */ -static uint16_t size_extended; -static unsigned int ISA_PNP_WPORT = 0x20B; -static unsigned int ISA_PNP_WPORT_BIOS = 0; -static IO_ReadHandleObject *ISAPNP_PNP_READ_PORT = NULL; /* 0x200-0x3FF range */ -static IO_WriteHandleObject *ISAPNP_PNP_ADDRESS_PORT = NULL; /* 0x279 */ -static IO_WriteHandleObject *ISAPNP_PNP_DATA_PORT = NULL; /* 0xA79 */ -static IO_WriteHandleObject *BOCHS_PORT_E9 = NULL; -//static unsigned char ISA_PNP_CUR_CSN = 0; -static unsigned char ISA_PNP_CUR_ADDR = 0; -static unsigned char ISA_PNP_CUR_STATE = 0; -enum { - ISA_PNP_WAIT_FOR_KEY=0, - ISA_PNP_SLEEP, - ISA_PNP_ISOLATE, - ISA_PNP_CONFIG -}; - -const unsigned char isa_pnp_init_keystring[32] = { - 0x6A,0xB5,0xDA,0xED,0xF6,0xFB,0x7D,0xBE, - 0xDF,0x6F,0x37,0x1B,0x0D,0x86,0xC3,0x61, - 0xB0,0x58,0x2C,0x16,0x8B,0x45,0xA2,0xD1, - 0xE8,0x74,0x3A,0x9D,0xCE,0xE7,0x73,0x39 -}; - -static RealPt INT15_apm_pmentry=0; -static unsigned char ISA_PNP_KEYMATCH=0; -static Bits other_memsystems=0; -void CMOS_SetRegister(Bitu regNr, uint8_t val); //For setting equipment word -bool enable_integration_device_pnp=false; -bool enable_integration_device=false; -bool ISAPNPBIOS=false; -bool ISAPNPPORT=false; -bool APMBIOS=false; -bool APMBIOS_pnp=false; -bool APMBIOS_allow_realmode=false; -bool APMBIOS_allow_prot16=false; -bool APMBIOS_allow_prot32=false; -int APMBIOS_connect_mode=0; - -enum { - APMBIOS_CONNECT_REAL=0, - APMBIOS_CONNECT_PROT16, - APMBIOS_CONNECT_PROT32 -}; - -unsigned int APMBIOS_connected_already_err() { - switch (APMBIOS_connect_mode) { - case APMBIOS_CONNECT_REAL: return 0x02; - case APMBIOS_CONNECT_PROT16: return 0x05; - case APMBIOS_CONNECT_PROT32: return 0x07; - } - - return 0x00; -} - -ISAPnPDevice::ISAPnPDevice() { - memset(ident,0,sizeof(ident)); -} - -bool ISAPnPDevice::alloc(size_t sz) { - if (sz == alloc_sz) - return true; - - if (alloc_res == resource_data) { - resource_data_len = 0; - resource_data_pos = 0; - resource_data = NULL; - } - if (alloc_res != NULL) - delete[] alloc_res; - - alloc_res = NULL; - alloc_write = 0; - alloc_sz = 0; - - if (sz == 0) - return true; - if (sz > 65536) - return false; - - alloc_res = new unsigned char[sz]; - if (alloc_res == NULL) return false; - memset(alloc_res,0xFF,sz); - alloc_sz = sz; - return true; -} - -ISAPnPDevice::~ISAPnPDevice() { - ISAPnPDevice::alloc(0); -} - -void ISAPnPDevice::begin_write_res() { - if (alloc_res == NULL) return; - - resource_data_pos = 0; - resource_data_len = 0; - resource_data = NULL; - alloc_write = 0; -} - -void ISAPnPDevice::write_byte(const unsigned char c) { - if (alloc_res == NULL || alloc_write >= alloc_sz) return; - alloc_res[alloc_write++] = c; -} - -void ISAPnPDevice::write_begin_SMALLTAG(const ISAPnPDevice::SmallTags stag,unsigned char len) { - if (len >= 8 || (unsigned int)stag >= 0x10) return; - write_byte(((unsigned char)stag << 3) + len); -} - -void ISAPnPDevice::write_begin_LARGETAG(const ISAPnPDevice::LargeTags stag,unsigned int len) { - if (len >= 4096) return; - write_byte(0x80 + ((unsigned char)stag)); - write_byte(len & 0xFF); - write_byte(len >> 8); -} - -void ISAPnPDevice::write_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { - write_byte((((unsigned char)c1 & 0x1FU) << 2) + (((unsigned char)c2 & 0x18U) >> 3)); - write_byte((((unsigned char)c2 & 0x07U) << 5) + ((unsigned char)c3 & 0x1FU)); - write_byte((((unsigned char)c4 & 0x0FU) << 4) + ((unsigned char)c5 & 0x0FU)); - write_byte((((unsigned char)c6 & 0x0FU) << 4) + ((unsigned char)c7 & 0x0FU)); -} - -void ISAPnPDevice::write_Logical_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { - write_begin_SMALLTAG(SmallTags::LogicalDeviceID,5); - write_Device_ID(c1,c2,c3,c4,c5,c6,c7); - write_byte(0x00); -} - -void ISAPnPDevice::write_Compatible_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { - write_begin_SMALLTAG(SmallTags::CompatibleDeviceID,4); - write_Device_ID(c1,c2,c3,c4,c5,c6,c7); -} - -void ISAPnPDevice::write_IRQ_Format(const uint16_t IRQ_mask,const unsigned char IRQ_signal_type) { - bool write_irq_info = (IRQ_signal_type != 0); - - write_begin_SMALLTAG(SmallTags::IRQFormat,write_irq_info?3:2); - write_byte(IRQ_mask & 0xFF); - write_byte(IRQ_mask >> 8); - if (write_irq_info) write_byte(IRQ_signal_type & 0x0F); -} - -void ISAPnPDevice::write_DMA_Format(const uint8_t DMA_mask,const unsigned char transfer_type_preference,const bool is_bus_master,const bool byte_mode,const bool word_mode,const unsigned char speed_supported) { - write_begin_SMALLTAG(SmallTags::DMAFormat,2); - write_byte(DMA_mask); - write_byte( - (transfer_type_preference & 0x03) | - (is_bus_master ? 0x04 : 0x00) | - (byte_mode ? 0x08 : 0x00) | - (word_mode ? 0x10 : 0x00) | - ((speed_supported & 3) << 5)); -} - -void ISAPnPDevice::write_IO_Port(const uint16_t min_port,const uint16_t max_port,const uint8_t count,const uint8_t alignment,const bool full16bitdecode) { - write_begin_SMALLTAG(SmallTags::IOPortDescriptor,7); - write_byte((full16bitdecode ? 0x01 : 0x00)); - write_byte(min_port & 0xFF); - write_byte(min_port >> 8); - write_byte(max_port & 0xFF); - write_byte(max_port >> 8); - write_byte(alignment); - write_byte(count); -} - -void ISAPnPDevice::write_Dependent_Function_Start(const ISAPnPDevice::DependentFunctionConfig cfg,const bool force) { - bool write_cfg_byte = force || (cfg != ISAPnPDevice::DependentFunctionConfig::AcceptableDependentConfiguration); - - write_begin_SMALLTAG(SmallTags::StartDependentFunctions,write_cfg_byte ? 1 : 0); - if (write_cfg_byte) write_byte((unsigned char)cfg); -} - -void ISAPnPDevice::write_End_Dependent_Functions() { - write_begin_SMALLTAG(SmallTags::EndDependentFunctions,0); -} - -void ISAPnPDevice::write_nstring(const char *str,const size_t l) { - (void)l; - - if (alloc_res == NULL || alloc_write >= alloc_sz) return; - - while (*str != 0 && alloc_write < alloc_sz) - alloc_res[alloc_write++] = (unsigned char)(*str++); -} - -void ISAPnPDevice::write_Identifier_String(const char *str) { - const size_t l = strlen(str); - if (l > 4096) return; - - write_begin_LARGETAG(LargeTags::IdentifierStringANSI,(unsigned int)l); - if (l != 0) write_nstring(str,l); -} - -void ISAPnPDevice::write_ISAPnP_version(unsigned char major,unsigned char minor,unsigned char vendor) { - write_begin_SMALLTAG(SmallTags::PlugAndPlayVersionNumber,2); - write_byte((major << 4) + minor); - write_byte(vendor); -} - -void ISAPnPDevice::write_END() { - unsigned char sum = 0; - size_t i; - - write_begin_SMALLTAG(SmallTags::EndTag,/*length*/1); - - for (i=0;i < alloc_write;i++) sum += alloc_res[i]; - write_byte((0x100 - sum) & 0xFF); -} - -void ISAPnPDevice::end_write_res() { - if (alloc_res == NULL) return; - - write_END(); - - if (alloc_write >= alloc_sz) LOG(LOG_MISC,LOG_WARN)("ISA PNP generation overflow"); - - resource_data_pos = 0; - resource_data_len = alloc_sz; // the device usually has a reason for allocating the fixed size it does - resource_data = alloc_res; - alloc_write = 0; -} - -void ISAPnPDevice::config(Bitu val) { - (void)val; -} - -void ISAPnPDevice::wakecsn(Bitu val) { - (void)val; - ident_bp = 0; - ident_2nd = 0; - resource_data_pos = 0; - resource_ident = 0; -} - -void ISAPnPDevice::select_logical_device(Bitu val) { - (void)val; -} - -void ISAPnPDevice::checksum_ident() { - unsigned char checksum = 0x6a,bit; - - for (int i=0;i < 8;i++) { - for (int j=0;j < 8;j++) { - bit = (ident[i] >> j) & 1; - checksum = ((((checksum ^ (checksum >> 1)) & 1) ^ bit) << 7) | (checksum >> 1); - } - } - - ident[8] = checksum; -} - -void ISAPnPDevice::on_pnp_key() { - resource_ident = 0; -} - -uint8_t ISAPnPDevice::read(Bitu addr) { - (void)addr; - return 0x00; -} - -void ISAPnPDevice::write(Bitu addr,Bitu val) { - (void)addr; - (void)val; -} - -#define MAX_ISA_PNP_DEVICES 64 -#define MAX_ISA_PNP_SYSDEVNODES 256 - -static ISAPnPDevice *ISA_PNP_selected = NULL; -static ISAPnPDevice *ISA_PNP_devs[MAX_ISA_PNP_DEVICES] = {NULL}; /* FIXME: free objects on shutdown */ -static Bitu ISA_PNP_devnext = 0; - -static const unsigned char ISAPnPIntegrationDevice_sysdev[] = { - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x28,0x28, /* min-max range I/O port */ - 0x04,0x04), /* align=4 length=4 */ - ISAPNP_END -}; - -class ISAPnPIntegrationDevice : public ISAPnPDevice { - public: - ISAPnPIntegrationDevice() : ISAPnPDevice() { - resource_ident = 0; - resource_data = (unsigned char*)ISAPnPIntegrationDevice_sysdev; - resource_data_len = sizeof(ISAPnPIntegrationDevice_sysdev); - host_writed(ident+0,ISAPNP_ID('D','O','S',0x1,0x2,0x3,0x4)); /* DOS1234 test device */ - host_writed(ident+4,0xFFFFFFFFUL); - checksum_ident(); - } -}; - -ISAPnPIntegrationDevice *isapnpigdevice = NULL; - -class ISAPNP_SysDevNode { -public: - ISAPNP_SysDevNode(const unsigned char *ir,size_t len,bool already_alloc=false) { - if (already_alloc) { - raw = (unsigned char*)ir; - raw_len = len; - own = false; - } - else { - if (len > 65535) E_Exit("ISAPNP_SysDevNode data too long"); - raw = new unsigned char[len+1u]; - if (ir == NULL) - E_Exit("ISAPNP_SysDevNode cannot allocate buffer"); - else - memcpy(raw, ir, len); - raw_len = len; - raw[len] = 0; - own = true; - } - } - virtual ~ISAPNP_SysDevNode() { - if (own) delete[] raw; - } - - unsigned char* raw; - size_t raw_len; - bool own; -}; - -static ISAPNP_SysDevNode* ISAPNP_SysDevNodes[MAX_ISA_PNP_SYSDEVNODES] = {NULL}; -static Bitu ISAPNP_SysDevNodeLargest=0; -static Bitu ISAPNP_SysDevNodeCount=0; - -void ISA_PNP_FreeAllSysNodeDevs() { - for (Bitu i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) { - if (ISAPNP_SysDevNodes[i] != NULL) delete ISAPNP_SysDevNodes[i]; - ISAPNP_SysDevNodes[i] = NULL; - } - - ISAPNP_SysDevNodeLargest=0; - ISAPNP_SysDevNodeCount=0; -} - -void ISA_PNP_FreeAllDevs() { - Bitu i; - - for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { - if (ISA_PNP_devs[i] != NULL) { - delete ISA_PNP_devs[i]; - ISA_PNP_devs[i] = NULL; - } - } - for (i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) { - if (ISAPNP_SysDevNodes[i] != NULL) delete ISAPNP_SysDevNodes[i]; - ISAPNP_SysDevNodes[i] = NULL; - } - - ISAPNP_SysDevNodeLargest=0; - ISAPNP_SysDevNodeCount=0; -} - -void ISA_PNP_devreg(ISAPnPDevice *x) { - if (ISA_PNP_devnext < MAX_ISA_PNP_DEVICES) { - if (ISA_PNP_WPORT_BIOS == 0 && ISAPNPPORT) ISA_PNP_WPORT_BIOS = ISA_PNP_WPORT; - ISA_PNP_devs[ISA_PNP_devnext++] = x; - x->CSN = ISA_PNP_devnext; - } -} - -static Bitu isapnp_read_port(Bitu port,Bitu /*iolen*/) { - (void)port;//UNUSED - Bitu ret=0xff; - - switch (ISA_PNP_CUR_ADDR) { - case 0x01: /* serial isolation */ - if (ISA_PNP_selected && ISA_PNP_selected->CSN == 0) { - if (ISA_PNP_selected->ident_bp < 72) { - if (ISA_PNP_selected->ident[ISA_PNP_selected->ident_bp>>3] & (1 << (ISA_PNP_selected->ident_bp&7))) - ret = ISA_PNP_selected->ident_2nd ? 0xAA : 0x55; - else - ret = 0xFF; - - if (++ISA_PNP_selected->ident_2nd >= 2) { - ISA_PNP_selected->ident_2nd = 0; - ISA_PNP_selected->ident_bp++; - } - } - } - else { - ret = 0xFF; - } - break; - case 0x04: /* read resource data */ - if (ISA_PNP_selected) { - if (ISA_PNP_selected->resource_ident < 9) - ret = ISA_PNP_selected->ident[ISA_PNP_selected->resource_ident++]; - else { - /* real-world hardware testing shows that devices act as if there was some fixed block of ROM, - * that repeats every 128, 256, 512, or 1024 bytes if you just blindly read from this port. */ - if (ISA_PNP_selected->resource_data_pos < ISA_PNP_selected->resource_data_len) - ret = ISA_PNP_selected->resource_data[ISA_PNP_selected->resource_data_pos++]; - - /* that means that if you read enough bytes the ROM loops back to returning the ident */ - if (ISA_PNP_selected->resource_data_pos >= ISA_PNP_selected->resource_data_len) { - ISA_PNP_selected->resource_data_pos = 0; - ISA_PNP_selected->resource_ident = 0; - } - } - } - break; - case 0x05: /* read resource status */ - if (ISA_PNP_selected) { - /* real-world hardware testing shows that devices act as if there was some fixed block of ROM, - * that repeats every 128, 256, 512, or 1024 bytes if you just blindly read from this port. - * therefore, there's always a byte to return. */ - ret = 0x01; /* TODO: simulate hardware slowness */ - } - break; - case 0x06: /* card select number */ - if (ISA_PNP_selected) ret = ISA_PNP_selected->CSN; - break; - case 0x07: /* logical device number */ - if (ISA_PNP_selected) ret = ISA_PNP_selected->logical_device; - break; - default: /* pass the rest down to the class */ - if (ISA_PNP_selected) ret = ISA_PNP_selected->read(ISA_PNP_CUR_ADDR); - break; - } - -// if (1) LOG_MSG("PnP read(%02X) = %02X\n",ISA_PNP_CUR_ADDR,ret); - return ret; -} - -void isapnp_write_port(Bitu port,Bitu val,Bitu /*iolen*/) { - Bitu i; - - if (port == 0x279) { -// if (1) LOG_MSG("PnP addr(%02X)\n",val); - if (val == isa_pnp_init_keystring[ISA_PNP_KEYMATCH]) { - if (++ISA_PNP_KEYMATCH == 32) { -// LOG_MSG("ISA PnP key -> going to sleep\n"); - ISA_PNP_CUR_STATE = ISA_PNP_SLEEP; - ISA_PNP_KEYMATCH = 0; - for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { - if (ISA_PNP_devs[i] != NULL) { - ISA_PNP_devs[i]->on_pnp_key(); - } - } - } - } - else { - ISA_PNP_KEYMATCH = 0; - } - - ISA_PNP_CUR_ADDR = val; - } - else if (port == 0xA79) { -// if (1) LOG_MSG("PnP write(%02X) = %02X\n",ISA_PNP_CUR_ADDR,val); - switch (ISA_PNP_CUR_ADDR) { - case 0x00: { /* RD_DATA */ - unsigned int np = ((val & 0xFF) << 2) | 3; - if (np != ISA_PNP_WPORT) { - if (ISAPNP_PNP_READ_PORT != NULL) { - ISAPNP_PNP_READ_PORT = NULL; - delete ISAPNP_PNP_READ_PORT; - } - - if (np >= 0x200 && np <= 0x3FF) { /* allowable port I/O range according to spec */ - LOG_MSG("PNP OS changed I/O read port to 0x%03X (from 0x%03X)\n",np,ISA_PNP_WPORT); - - ISA_PNP_WPORT = np; - ISAPNP_PNP_READ_PORT = new IO_ReadHandleObject; - ISAPNP_PNP_READ_PORT->Install(ISA_PNP_WPORT,isapnp_read_port,IO_MB); - } - else { - LOG_MSG("PNP OS I/O read port disabled\n"); - - ISA_PNP_WPORT = 0; - } - - if (ISA_PNP_selected != NULL) { - ISA_PNP_selected->ident_bp = 0; - ISA_PNP_selected->ident_2nd = 0; - ISA_PNP_selected->resource_data_pos = 0; - } - } - } break; - case 0x02: /* config control */ - if (val & 4) { - /* ALL CARDS RESET CSN to 0 */ - for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { - if (ISA_PNP_devs[i] != NULL) { - ISA_PNP_devs[i]->CSN = 0; - } - } - } - if (val & 2) ISA_PNP_CUR_STATE = ISA_PNP_WAIT_FOR_KEY; - if ((val & 1) && ISA_PNP_selected) ISA_PNP_selected->config(val); - for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { - if (ISA_PNP_devs[i] != NULL) { - ISA_PNP_devs[i]->ident_bp = 0; - ISA_PNP_devs[i]->ident_2nd = 0; - ISA_PNP_devs[i]->resource_data_pos = 0; - } - } - break; - case 0x03: { /* wake[CSN] */ - ISA_PNP_selected = NULL; - for (i=0;ISA_PNP_selected == NULL && i < MAX_ISA_PNP_DEVICES;i++) { - if (ISA_PNP_devs[i] == NULL) - continue; - if (ISA_PNP_devs[i]->CSN == val) { - ISA_PNP_selected = ISA_PNP_devs[i]; - ISA_PNP_selected->wakecsn(val); - } - } - if (val == 0) - ISA_PNP_CUR_STATE = ISA_PNP_ISOLATE; - else - ISA_PNP_CUR_STATE = ISA_PNP_CONFIG; - } break; - case 0x06: /* card select number */ - if (ISA_PNP_selected) ISA_PNP_selected->CSN = val; - break; - case 0x07: /* logical device number */ - if (ISA_PNP_selected) ISA_PNP_selected->select_logical_device(val); - break; - default: /* pass the rest down to the class */ - if (ISA_PNP_selected) ISA_PNP_selected->write(ISA_PNP_CUR_ADDR,val); - break; - } - } -} - -// IBM PC/AT CTRL+BREAK interrupt, called by IRQ1 handler. -// Not applicable to PC-98 mode, of course. -Bitu INT1B_Break_Handler(void) { - // BIOS DATA AREA 40:71 bit 7 is set when Break key is pressed. - // This is already implemented by IRQ1 handler in src/ints/bios_keyboard.cpp. - // Ref: [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/Computers/IBM/PS%e2%88%952/IBM%20Personal%20System%e2%88%952%20and%20Personal%20Computer%20BIOS%20Interface%20Technical%20Reference%20%281991%2d09%29%20First%20Edition%2c%20part%203%2epdf] - return CBRET_NONE; -} - - -static Bitu INT15_Handler(void); - -// FIXME: This initializes both APM BIOS and ISA PNP emulation! -// Need to separate APM BIOS init from ISA PNP init from ISA PNP BIOS init! -// It might also be appropriate to move this into the BIOS init sequence. -void ISAPNP_Cfg_Reset(Section *sec) { - (void)sec;//UNUSED - const Section_prop* section = static_cast(control->GetSection("cpu")); - - LOG(LOG_MISC,LOG_DEBUG)("Initializing ISA PnP emulation"); - - enable_integration_device = section->Get_bool("integration device"); - enable_integration_device_pnp = section->Get_bool("integration device pnp"); - ISAPNPBIOS = section->Get_bool("isapnpbios"); - { - /* ISAPNPPORT = off|auto|on */ - const char *s = section->Get_string("isapnpport"); - - if (!strcmp(s,"true") || !strcmp(s,"1")) - ISAPNPPORT = true; - else if (!strcmp(s,"false") || !strcmp(s,"0")) - ISAPNPPORT = false; - else /* auto */ - ISAPNPPORT = ISAPNPBIOS; /* if the PnP BIOS is enabled, then so is the port */ - } - APMBIOS = section->Get_bool("apmbios"); - APMBIOS_pnp = section->Get_bool("apmbios pnp"); - APMBIOS_allow_realmode = section->Get_bool("apmbios allow realmode"); - APMBIOS_allow_prot16 = section->Get_bool("apmbios allow 16-bit protected mode"); - APMBIOS_allow_prot32 = section->Get_bool("apmbios allow 32-bit protected mode"); - - std::string apmbiosver = section->Get_string("apmbios version"); - - /* PC-98 does not have the IBM PC/AT APM BIOS interface */ - if (IS_PC98_ARCH) { - APMBIOS = false; - APMBIOS_pnp = false; - } - - if (apmbiosver == "1.0") - APM_BIOS_minor_version = 0; - else if (apmbiosver == "1.1") - APM_BIOS_minor_version = 1; - else if (apmbiosver == "1.2") - APM_BIOS_minor_version = 2; - else//auto - APM_BIOS_minor_version = 2; - - /* PC-98 does not have APM. - * I *think* it has Plug & Play, but probably different from ISA PnP and specific to the C-Bus interface, - * which I have no information on at this time --J.C. */ - if (IS_PC98_ARCH) - return; - - LOG(LOG_MISC,LOG_DEBUG)("APM BIOS allow: real=%u pm16=%u pm32=%u version=1.%u", - APMBIOS_allow_realmode, - APMBIOS_allow_prot16, - APMBIOS_allow_prot32, - APM_BIOS_minor_version); - - std::string apmbiospwrbtn = section->Get_string("apm power button event"); - if (apmbiospwrbtn == "standby") - APM_PowerButtonSendsSuspend = false; - else - APM_PowerButtonSendsSuspend = true; - - - if (APMBIOS && (APMBIOS_allow_prot16 || APMBIOS_allow_prot32) && INT15_apm_pmentry == 0) { - Bitu cb,base; - - /* NTS: This is... kind of a terrible hack. It basically tricks Windows into executing our - * INT 15h handler as if the APM entry point. Except that instead of an actual INT 15h - * triggering the callback, a FAR CALL triggers the callback instead (CB_RETF not CB_IRET). */ - /* TODO: We should really consider moving the APM BIOS code in INT15_Handler() out into its - * own function, then having the INT15_Handler() call it as well as directing this callback - * directly to it. If you think about it, this hack also lets the "APM entry point" invoke - * other arbitrary INT 15h calls which is not valid. */ - - cb = CALLBACK_Allocate(); - INT15_apm_pmentry = CALLBACK_RealPointer(cb); - LOG_MSG("Allocated APM BIOS pm entry point at %04x:%04x\n",INT15_apm_pmentry>>16,INT15_apm_pmentry&0xFFFF); - CALLBACK_Setup(cb,INT15_Handler,CB_RETF,"APM BIOS protected mode entry point"); - - /* NTS: Actually INT15_Handler is written to act like an interrupt (IRETF) type callback. - * Prior versions hacked this into something that responds by CB_RETF, however some - * poking around reveals that CALLBACK_SCF and friends still assume an interrupt - * stack, thus, the cause of random crashes in Windows was simply that we were - * flipping flag bits in the middle of the return address on the stack. The other - * source of random crashes is that the CF/ZF manipulation in INT 15h wasn't making - * its way back to Windows, meaning that when APM BIOS emulation intended to return - * an error (by setting CF), Windows didn't get the memo (CF wasn't set on return) - * and acted as if the call succeeded, or worse, CF happened to be set on entry and - * was never cleared by APM BIOS emulation. - * - * So what we need is: - * - * PUSHF ; put flags in right place - * PUSH BP ; dummy FAR pointer - * PUSH BP ; again - * - * POP BP ; drop it - * POP BP ; drop it - * POPF - * RETF - * - * Then CALLBACK_SCF can work normally this way. - * - * NTS: We *still* need to separate APM BIOS calls from the general INT 15H emulation though... */ - base = Real2Phys(INT15_apm_pmentry); - LOG_MSG("Writing code to %05x\n",(unsigned int)base); - - phys_writeb(base+0x00,0x9C); /* pushf */ - phys_writeb(base+0x01,0x55); /* push (e)bp */ - phys_writeb(base+0x02,0x55); /* push (e)bp */ - - phys_writeb(base+0x03,(uint8_t)0xFE); //GRP 4 - phys_writeb(base+0x04,(uint8_t)0x38); //Extra Callback instruction - phys_writew(base+0x05,(uint16_t)cb); //The immediate word - - phys_writeb(base+0x07,0x5D); /* pop (e)bp */ - phys_writeb(base+0x08,0x5D); /* pop (e)bp */ - phys_writeb(base+0x09,0x9D); /* popf */ - phys_writeb(base+0x0A,0xCB); /* retf */ - - /* APM suspended mode execution loop */ - cb = CALLBACK_Allocate(); - APM_SuspendedLoopRptr = CALLBACK_RealPointer(cb); - CALLBACK_Setup(cb,APM_SuspendedLoopFunc,CB_RETF,"APM BIOS suspend/standby loop"); - - base = Real2Phys(APM_SuspendedLoopRptr); - LOG_MSG("Writing code to %05x\n",(unsigned int)base); - phys_writeb(base+0x04,0xF4); /* hlt */ - phys_writew(base+0x05,0xF9EB); /* jmp $-5 (EB xx) */ - phys_writeb(base+0x07,0xC3); /* ret */ - } -} - -void ISAPNP_Cfg_Init() { - AddVMEventFunction(VM_EVENT_RESET,AddVMEventFunctionFuncPair(ISAPNP_Cfg_Reset)); -} - -/* the PnP callback registered two entry points. One for real, one for protected mode. */ -static Bitu PNPentry_real,PNPentry_prot; - -static bool ISAPNP_Verify_BiosSelector(Bitu seg) { - if (!cpu.pmode || (reg_flags & FLAG_VM)) { - return (seg == 0xF000); - } else if (seg == 0) - return 0; - else { -#if 1 - /* FIXME: Always return true. But figure out how to ask DOSBox the linear->phys - mapping to determine whether the segment's base address maps to 0xF0000. - In the meantime disabling this check makes PnP BIOS emulation work with - Windows 95 OSR2 which appears to give us a segment mapped to a virtual - address rather than linearly mapped to 0xF0000 as Windows 95 original - did. */ - return true; -#else - Descriptor desc; - cpu.gdt.GetDescriptor(seg,desc); - - /* TODO: Check desc.Type() to make sure it's a writeable data segment */ - return (desc.GetBase() == 0xF0000); -#endif - } -} - -static bool ISAPNP_CPU_ProtMode() { - if (!cpu.pmode || (reg_flags & FLAG_VM)) - return 0; - - return 1; -} - -static Bitu ISAPNP_xlate_address(Bitu far_ptr) { - if (!cpu.pmode || (reg_flags & FLAG_VM)) - return Real2Phys(far_ptr); - else { - Descriptor desc; - cpu.gdt.GetDescriptor(far_ptr >> 16,desc); - - /* TODO: Check desc.Type() to make sure it's a writeable data segment */ - return (desc.GetBase() + (far_ptr & 0xFFFF)); - } -} - -static const unsigned char ISAPNP_sysdev_Keyboard[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0x3,0x0,0x3), /* PNP0303 IBM Enhanced 101/102 key with PS/2 */ - ISAPNP_TYPE(0x09,0x00,0x00), /* type: input, keyboard */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x60,0x60, /* min-max range I/O port */ - 0x01,0x01), /* align=1 length=1 */ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x64,0x64, /* min-max range I/O port */ - 0x01,0x01), /* align=1 length=1 */ - ISAPNP_IRQ_SINGLE( - 1, /* IRQ 1 */ - 0x09), /* HTE=1 LTL=1 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -static const unsigned char ISAPNP_sysdev_Mouse[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xF,0x0,0xE), /* PNP0F0E Microsoft compatible PS/2 */ - ISAPNP_TYPE(0x09,0x02,0x00), /* type: input, keyboard */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IRQ_SINGLE( - 12, /* IRQ 12 */ - 0x09), /* HTE=1 LTL=1 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -static const unsigned char ISAPNP_sysdev_DMA_Controller[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0x2,0x0,0x0), /* PNP0200 AT DMA controller */ - ISAPNP_TYPE(0x08,0x01,0x00), /* type: input, keyboard */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x00,0x00, /* min-max range I/O port (DMA channels 0-3) */ - 0x10,0x10), /* align=16 length=16 */ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x81,0x81, /* min-max range I/O port (DMA page registers) */ - 0x01,0x0F), /* align=1 length=15 */ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0xC0,0xC0, /* min-max range I/O port (AT DMA channels 4-7) */ - 0x20,0x20), /* align=32 length=32 */ - ISAPNP_DMA_SINGLE( - 4, /* DMA 4 */ - 0x01), /* 8/16-bit transfers, compatible speed */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -static const unsigned char ISAPNP_sysdev_PIC[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0x0,0x0,0x0), /* PNP0000 Interrupt controller */ - ISAPNP_TYPE(0x08,0x00,0x01), /* type: ISA interrupt controller */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x20,0x20, /* min-max range I/O port */ - 0x01,0x02), /* align=1 length=2 */ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0xA0,0xA0, /* min-max range I/O port */ - 0x01,0x02), /* align=1 length=2 */ - ISAPNP_IRQ_SINGLE( - 2, /* IRQ 2 */ - 0x09), /* HTE=1 LTL=1 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -static const unsigned char ISAPNP_sysdev_Timer[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0x1,0x0,0x0), /* PNP0100 Timer */ - ISAPNP_TYPE(0x08,0x02,0x01), /* type: ISA timer */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x40,0x40, /* min-max range I/O port */ - 0x04,0x04), /* align=4 length=4 */ - ISAPNP_IRQ_SINGLE( - 0, /* IRQ 0 */ - 0x09), /* HTE=1 LTL=1 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -static const unsigned char ISAPNP_sysdev_RTC[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xB,0x0,0x0), /* PNP0B00 Real-time clock */ - ISAPNP_TYPE(0x08,0x03,0x01), /* type: ISA real-time clock */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x70,0x70, /* min-max range I/O port */ - 0x01,0x02), /* align=1 length=2 */ - ISAPNP_IRQ_SINGLE( - 8, /* IRQ 8 */ - 0x09), /* HTE=1 LTL=1 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -static const unsigned char ISAPNP_sysdev_PC_Speaker[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0x8,0x0,0x0), /* PNP0800 PC speaker */ - ISAPNP_TYPE(0x04,0x01,0x00), /* type: PC speaker */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x61,0x61, /* min-max range I/O port */ - 0x01,0x01), /* align=1 length=1 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -static const unsigned char ISAPNP_sysdev_Numeric_Coprocessor[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x4), /* PNP0C04 Numeric Coprocessor */ - ISAPNP_TYPE(0x0B,0x80,0x00), /* type: FPU */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0xF0,0xF0, /* min-max range I/O port */ - 0x10,0x10), /* align=16 length=16 */ - ISAPNP_IRQ_SINGLE( - 13, /* IRQ 13 */ - 0x09), /* HTE=1 LTL=1 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -static const unsigned char ISAPNP_sysdev_System_Board[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x1), /* PNP0C01 System board */ - ISAPNP_TYPE(0x08,0x80,0x00), /* type: System peripheral, Other */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x24,0x24, /* min-max range I/O port */ - 0x04,0x04), /* align=4 length=4 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -/* NTS: If some of my late 1990's laptops are any indication, this resource list can be used - * as a hint that the motherboard supports Intel EISA/PCI controller DMA registers that - * allow ISA DMA to extend to 32-bit addresses instead of being limited to 24-bit */ -static const unsigned char ISAPNP_sysdev_General_ISAPNP[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x2), /* PNP0C02 General ID for reserving resources */ - ISAPNP_TYPE(0x08,0x80,0x00), /* type: System peripheral, Other */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_IO_RANGE( - 0x01, /* decodes 16-bit ISA addr */ - 0x208,0x208, /* min-max range I/O port */ - 0x04,0x04), /* align=4 length=4 */ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -/* PnP system entry to tell Windows 95 the obvious: That there's an ISA bus present */ -/* NTS: Examination of some old laptops of mine shows that these devices do not list any resources, - * or at least, an old Toshiba of mine lists the PCI registers 0xCF8-0xCFF as motherboard resources - * and defines no resources for the PCI Bus PnP device. */ -static const unsigned char ISAPNP_sysdev_ISA_BUS[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xA,0x0,0x0), /* PNP0A00 ISA Bus */ - ISAPNP_TYPE(0x06,0x04,0x00), /* type: System device, peripheral bus */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -/* PnP system entry to tell Windows 95 the obvious: That there's a PCI bus present */ -static const unsigned char ISAPNP_sysdev_PCI_BUS[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xA,0x0,0x3), /* PNP0A03 PCI Bus */ - ISAPNP_TYPE(0x06,0x04,0x00), /* type: System device, peripheral bus */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -/* to help convince Windows 95 that the APM BIOS is present */ -static const unsigned char ISAPNP_sysdev_APM_BIOS[] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x5), /* PNP0C05 APM BIOS */ - ISAPNP_TYPE(0x08,0x80,0x00), /* type: FIXME is this right?? I can't find any examples or documentation */ - 0x0001 | 0x0002), /* can't disable, can't configure */ - /*----------allocated--------*/ - ISAPNP_END, - /*----------possible--------*/ - ISAPNP_END, - /*----------compatible--------*/ - ISAPNP_END -}; - -bool ISAPNP_RegisterSysDev(const unsigned char *raw,Bitu len,bool already) { - if (ISAPNP_SysDevNodeCount >= MAX_ISA_PNP_SYSDEVNODES) - return false; - - ISAPNP_SysDevNodes[ISAPNP_SysDevNodeCount] = new ISAPNP_SysDevNode(raw,len,already); - if (ISAPNP_SysDevNodes[ISAPNP_SysDevNodeCount] == NULL) - return false; - - ISAPNP_SysDevNodeCount++; - if (ISAPNP_SysDevNodeLargest < (len+3)) - ISAPNP_SysDevNodeLargest = len+3; - - return true; -} - -/* ISA PnP function calls have their parameters stored on the stack "C" __cdecl style. Parameters - * are either int, long, or FAR pointers. Like __cdecl an assembly language implementation pushes - * the function arguments on the stack BACKWARDS */ -static Bitu ISAPNP_Handler(bool protmode /* called from protected mode interface == true */) { - Bitu arg; - Bitu func,BiosSelector; - - /* I like how the ISA PnP spec says that the 16-bit entry points (real and protected) are given 16-bit data segments - * which implies that all segments involved might as well be 16-bit. - * - * Right? - * - * Well, guess what Windows 95 gives us when calling this entry point: - * - * Segment SS = DS = 0x30 base=0 limit=0xFFFFFFFF - * SS:SP = 0x30:0xC138BADF or something like that from within BIOS.VXD - * - * Yeah... for a 16-bit code segment call. Right. Typical Microsoft. >:( - * - * This might also explain why my early experiments with Bochs always had the perpetual - * APM BIOS that never worked but was always detected. - * - * ------------------------------------------------------------------------ - * Windows 95 OSR2: - * - * Windows 95 OSR2 however uses a 16-bit stack (where the stack segment is based somewhere - * around 0xC1xxxxxx), all we have to do to correctly access it is work through the page tables. - * This is within spec, but now Microsoft sends us a data segment that is based at virtual address - * 0xC2xxxxxx, which is why I had to disable the "verify selector" routine */ - arg = SegPhys(ss) + (reg_esp&cpu.stack.mask) + (2*2); /* entry point (real and protected) is 16-bit, expected to RETF (skip CS:IP) */ - - if (protmode != ISAPNP_CPU_ProtMode()) { - //LOG_MSG("ISA PnP %s entry point called from %s. On real BIOSes this would CRASH\n",protmode ? "Protected mode" : "Real mode", - // ISAPNP_CPU_ProtMode() ? "Protected mode" : "Real mode"); - reg_ax = 0x84;/* BAD_PARAMETER */ - return 0; - } - - func = mem_readw(arg); -// LOG_MSG("PnP prot=%u DS=%04x (base=0x%08lx) SS:ESP=%04x:%04x (base=0x%08lx phys=0x%08lx) function=0x%04x\n", -// (unsigned int)protmode,(unsigned int)SegValue(ds),(unsigned long)SegPhys(ds), -// (unsigned int)SegValue(ss),(unsigned int)reg_esp,(unsigned long)SegPhys(ss), -// (unsigned long)arg,(unsigned int)func); - - /* every function takes the form - * - * int __cdecl FAR (*entrypoint)(int Function...); - * - * so the first argument on the stack is an int that we read to determine what the caller is asking - * - * Don't forget in the real-mode world: - * sizeof(int) == 16 bits - * sizeof(long) == 32 bits - */ - switch (func) { - case 0: { /* Get Number of System Nodes */ - /* int __cdecl FAR (*entrypoint)(int Function,unsigned char FAR *NumNodes,unsigned int FAR *NodeSize,unsigned int BiosSelector); - * ^ +0 ^ +2 ^ +6 ^ +10 = 12 */ - Bitu NumNodes_ptr = mem_readd(arg+2); - Bitu NodeSize_ptr = mem_readd(arg+6); - BiosSelector = mem_readw(arg+10); - - if (!ISAPNP_Verify_BiosSelector(BiosSelector)) - goto badBiosSelector; - - if (NumNodes_ptr != 0) mem_writeb(ISAPNP_xlate_address(NumNodes_ptr),ISAPNP_SysDevNodeCount); - if (NodeSize_ptr != 0) mem_writew(ISAPNP_xlate_address(NodeSize_ptr),ISAPNP_SysDevNodeLargest); - - reg_ax = 0x00;/* SUCCESS */ - } break; - case 1: { /* Get System Device Node */ - /* int __cdecl FAR (*entrypoint)(int Function,unsigned char FAR *Node,struct DEV_NODE FAR *devNodeBuffer,unsigned int Control,unsigned int BiosSelector); - * ^ +0 ^ +2 ^ +6 ^ +10 ^ +12 = 14 */ - Bitu Node_ptr = mem_readd(arg+2); - Bitu devNodeBuffer_ptr = mem_readd(arg+6); - Bitu Control = mem_readw(arg+10); - BiosSelector = mem_readw(arg+12); - unsigned char Node; - Bitu i=0; - - if (!ISAPNP_Verify_BiosSelector(BiosSelector)) - goto badBiosSelector; - - /* control bits 0-1 must be '01' or '10' but not '00' or '11' */ - if (Control == 0 || (Control&3) == 3) { - LOG_MSG("ISAPNP Get System Device Node: Invalid Control value 0x%04x\n",(int)Control); - reg_ax = 0x84;/* BAD_PARAMETER */ - break; - } - - devNodeBuffer_ptr = ISAPNP_xlate_address(devNodeBuffer_ptr); - Node_ptr = ISAPNP_xlate_address(Node_ptr); - Node = mem_readb(Node_ptr); - if (Node >= ISAPNP_SysDevNodeCount) { - LOG_MSG("ISAPNP Get System Device Node: Invalid Node 0x%02x (max 0x%04x)\n",(int)Node,(int)ISAPNP_SysDevNodeCount); - reg_ax = 0x84;/* BAD_PARAMETER */ - break; - } - - const ISAPNP_SysDevNode *nd = ISAPNP_SysDevNodes[Node]; - - mem_writew(devNodeBuffer_ptr+0,(uint16_t)(nd->raw_len+3)); /* Length */ - mem_writeb(devNodeBuffer_ptr+2,Node); /* on most PnP BIOS implementations I've seen "handle" is set to the same value as Node */ - for (i=0;i < (Bitu)nd->raw_len;i++) - mem_writeb(devNodeBuffer_ptr+i+3,nd->raw[i]); - -// LOG_MSG("ISAPNP OS asked for Node 0x%02x\n",Node); - - if (++Node >= ISAPNP_SysDevNodeCount) Node = 0xFF; /* no more nodes */ - mem_writeb(Node_ptr,Node); - - reg_ax = 0x00;/* SUCCESS */ - } break; - case 4: { /* Send Message */ - /* int __cdecl FAR (*entrypoint)(int Function,unsigned int Message,unsigned int BiosSelector); - * ^ +0 ^ +2 ^ +4 = 6 */ - Bitu Message = mem_readw(arg+2); - BiosSelector = mem_readw(arg+4); - - if (!ISAPNP_Verify_BiosSelector(BiosSelector)) - goto badBiosSelector; - - switch (Message) { - case 0x41: /* POWER_OFF */ - LOG_MSG("Plug & Play OS requested power off.\n"); - reg_ax = 0; - throw 1; /* NTS: Based on the Reboot handler code, causes DOSBox-X to cleanly shutdown and exit */ - break; - case 0x42: /* PNP_OS_ACTIVE */ - LOG_MSG("Plug & Play OS reports itself active\n"); - reg_ax = 0; - break; - case 0x43: /* PNP_OS_INACTIVE */ - LOG_MSG("Plug & Play OS reports itself inactive\n"); - reg_ax = 0; - break; - default: - LOG_MSG("Unknown ISA PnP message 0x%04x\n",(int)Message); - reg_ax = 0x82;/* FUNCTION_NOT_SUPPORTED */ - break; - } - } break; - case 0x40: { /* Get PnP ISA configuration */ - /* int __cdecl FAR (*entrypoint)(int Function,unsigned char far *struct,unsigned int BiosSelector); - * ^ +0 ^ +2 ^ +6 = 8 */ - Bitu struct_ptr = mem_readd(arg+2); - BiosSelector = mem_readw(arg+6); - - if (!ISAPNP_Verify_BiosSelector(BiosSelector)) - goto badBiosSelector; - - /* struct isapnp_pnp_isa_cfg { - uint8_t revision; - uint8_t total_csn; - uint16_t isa_pnp_port; - uint16_t reserved; - }; */ - - if (struct_ptr != 0) { - Bitu ph = ISAPNP_xlate_address(struct_ptr); - mem_writeb(ph+0,0x01); /* ->revision = 0x01 */ - mem_writeb(ph+1,ISA_PNP_devnext); /* ->total_csn */ - mem_writew(ph+2,ISA_PNP_WPORT_BIOS); /* ->isa_pnp_port */ - mem_writew(ph+4,0); /* ->reserved */ - } - - reg_ax = 0x00;/* SUCCESS */ - } break; - default: - //LOG_MSG("Unsupported ISA PnP function 0x%04x\n",func); - reg_ax = 0x82;/* FUNCTION_NOT_SUPPORTED */ - break; - } - - return 0; -badBiosSelector: - /* return an error. remind the user (possible developer) how lucky he is, a real - * BIOS implementation would CRASH when misused like this */ - LOG_MSG("ISA PnP function 0x%04x called with incorrect BiosSelector parameter 0x%04x\n",(int)func,(int)BiosSelector); - LOG_MSG(" > STACK %04X %04X %04X %04X %04X %04X %04X %04X\n", - mem_readw(arg), mem_readw(arg+2), mem_readw(arg+4), mem_readw(arg+6), - mem_readw(arg+8), mem_readw(arg+10), mem_readw(arg+12), mem_readw(arg+14)); - - reg_ax = 0x84;/* BAD_PARAMETER */ - return 0; -} - -static Bitu ISAPNP_Handler_PM(void) { - return ISAPNP_Handler(true); -} - -static Bitu ISAPNP_Handler_RM(void) { - return ISAPNP_Handler(false); -} - -static Bitu INT70_Handler(void) { - /* Acknowledge irq with cmos */ - IO_Write(0x70,0xc); - IO_Read(0x71); - if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { - uint32_t count=mem_readd(BIOS_WAIT_FLAG_COUNT); - if (count>997) { - mem_writed(BIOS_WAIT_FLAG_COUNT,count-997); - } else { - mem_writed(BIOS_WAIT_FLAG_COUNT,0); - PhysPt where=Real2Phys(mem_readd(BIOS_WAIT_FLAG_POINTER)); - mem_writeb(where,mem_readb(where)|0x80); - mem_writeb(BIOS_WAIT_FLAG_ACTIVE,0); - mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(0,BIOS_WAIT_FLAG_TEMP)); - IO_Write(0x70,0xb); - IO_Write(0x71,IO_Read(0x71)&~0x40); - } - } - /* Signal EOI to both pics */ - IO_Write(0xa0,0x20); - IO_Write(0x20,0x20); - return 0; -} - -CALLBACK_HandlerObject* tandy_DAC_callback[2]; -static struct { - uint16_t port; - uint8_t irq; - uint8_t dma; -} tandy_sb; -static struct { - uint16_t port; - uint8_t irq; - uint8_t dma; -} tandy_dac; - -static bool Tandy_InitializeSB() { - /* see if soundblaster module available and at what port/IRQ/DMA */ - Bitu sbport, sbirq, sbdma; - if (SB_Get_Address(sbport, sbirq, sbdma)) { - tandy_sb.port=(uint16_t)(sbport&0xffff); - tandy_sb.irq =(uint8_t)(sbirq&0xff); - tandy_sb.dma =(uint8_t)(sbdma&0xff); - return true; - } else { - /* no soundblaster accessible, disable Tandy DAC */ - tandy_sb.port=0; - return false; - } -} - -static bool Tandy_InitializeTS() { - /* see if Tandy DAC module available and at what port/IRQ/DMA */ - Bitu tsport, tsirq, tsdma; - if (TS_Get_Address(tsport, tsirq, tsdma)) { - tandy_dac.port=(uint16_t)(tsport&0xffff); - tandy_dac.irq =(uint8_t)(tsirq&0xff); - tandy_dac.dma =(uint8_t)(tsdma&0xff); - return true; - } else { - /* no Tandy DAC accessible */ - tandy_dac.port=0; - return false; - } -} - -/* check if Tandy DAC is still playing */ -static bool Tandy_TransferInProgress(void) { - if (real_readw(0x40,0xd0)) return true; /* not yet done */ - if (real_readb(0x40,0xd4)==0xff) return false; /* still in init-state */ - - uint8_t tandy_dma = 1; - if (tandy_sb.port) tandy_dma = tandy_sb.dma; - else if (tandy_dac.port) tandy_dma = tandy_dac.dma; - - IO_Write(0x0c,0x00); - uint16_t datalen = (IO_ReadB(tandy_dma * 2 + 1)) + (IO_ReadB(tandy_dma * 2 + 1) << 8); - if (datalen==0xffff) return false; /* no DMA transfer */ - else if ((datalen<0x10) && (real_readb(0x40,0xd4)==0x0f) && (real_readw(0x40,0xd2)==0x1c)) { - /* stop already requested */ - return false; - } - return true; -} - -static void Tandy_SetupTransfer(PhysPt bufpt,bool isplayback) { - Bitu length=real_readw(0x40,0xd0); - if (length==0) return; /* nothing to do... */ - - if ((tandy_sb.port==0) && (tandy_dac.port==0)) return; - - uint8_t tandy_irq = 7; - if (tandy_sb.port) tandy_irq = tandy_sb.irq; - else if (tandy_dac.port) tandy_irq = tandy_dac.irq; - uint8_t tandy_irq_vector = tandy_irq; - if (tandy_irq_vector<8) tandy_irq_vector += 8; - else tandy_irq_vector += (0x70-8); - - /* revector IRQ-handler if necessary */ - RealPt current_irq=RealGetVec(tandy_irq_vector); - if (current_irq!=tandy_DAC_callback[0]->Get_RealPointer()) { - real_writed(0x40,0xd6,current_irq); - RealSetVec(tandy_irq_vector,tandy_DAC_callback[0]->Get_RealPointer()); - } - - uint8_t tandy_dma = 1; - if (tandy_sb.port) tandy_dma = tandy_sb.dma; - else if (tandy_dac.port) tandy_dma = tandy_dac.dma; - - if (tandy_sb.port) { - IO_Write(tandy_sb.port+0xcu,0xd0); /* stop DMA transfer */ - IO_Write(0x21,IO_Read(0x21)&(~(1u<>16u)&0xff); - IO_Write(tandy_dma*2u,(uint8_t)(bufpt&0xff)); - IO_Write(tandy_dma*2u,(uint8_t)((bufpt>>8u)&0xff)); - switch (tandy_dma) { - case 0: IO_Write(0x87,bufpage); break; - case 1: IO_Write(0x83,bufpage); break; - case 2: IO_Write(0x81,bufpage); break; - case 3: IO_Write(0x82,bufpage); break; - } - real_writeb(0x40,0xd4,bufpage); - - /* calculate transfer size (respects segment boundaries) */ - uint32_t tlength=length; - if (tlength+(bufpt&0xffff)>0x10000) tlength=0x10000-(bufpt&0xffff); - real_writew(0x40,0xd0,(uint16_t)(length-tlength)); /* remaining buffer length */ - tlength--; - - /* set transfer size */ - IO_Write(tandy_dma*2u+1u,(uint8_t)(tlength&0xffu)); - IO_Write(tandy_dma*2u+1u,(uint8_t)((tlength>>8u)&0xffu)); - - uint16_t delay=(uint16_t)(real_readw(0x40,0xd2)&0xfff); - uint8_t amplitude=(uint8_t)(((unsigned int)real_readw(0x40,0xd2)>>13u)&0x7u); - if (tandy_sb.port) { - IO_Write(0x0a,tandy_dma); /* enable DMA channel */ - /* set frequency */ - IO_Write(tandy_sb.port+0xcu,0x40); - IO_Write(tandy_sb.port+0xcu,256u - delay*100u/358u); - /* set playback type to 8bit */ - if (isplayback) IO_Write(tandy_sb.port+0xcu,0x14u); - else IO_Write(tandy_sb.port+0xcu,0x24u); - /* set transfer size */ - IO_Write(tandy_sb.port+0xcu,(uint8_t)(tlength&0xffu)); - IO_Write(tandy_sb.port+0xcu,(uint8_t)((tlength>>8)&0xffu)); - } else { - if (isplayback) IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x03u); - else IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x02u); - IO_Write(tandy_dac.port+2u,(uint8_t)(delay&0xffu)); - IO_Write(tandy_dac.port+3u,(uint8_t)((((unsigned int)delay>>8u)&0xfu) | ((unsigned int)amplitude<<5u))); - if (isplayback) IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x1fu); - else IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7c) | 0x1e); - IO_Write(0x0a,tandy_dma); /* enable DMA channel */ - } - - if (!isplayback) { - /* mark transfer as recording operation */ - real_writew(0x40,0xd2,(uint16_t)(delay|0x1000)); - } -} - -static Bitu IRQ_TandyDAC(void) { - if (tandy_dac.port) { - IO_Read(tandy_dac.port); - } - if (real_readw(0x40,0xd0)) { /* play/record next buffer */ - /* acknowledge IRQ */ - IO_Write(0x20,0x20); - if (tandy_sb.port) { - IO_Read(tandy_sb.port+0xeu); - } - - /* buffer starts at the next page */ - uint8_t npage=real_readb(0x40,0xd4)+1u; - real_writeb(0x40,0xd4,npage); - - Bitu rb=real_readb(0x40,0xd3); - if (rb&0x10) { - /* start recording */ - real_writeb(0x40,0xd3,rb&0xefu); - Tandy_SetupTransfer((unsigned int)npage<<16u,false); - } else { - /* start playback */ - Tandy_SetupTransfer((unsigned int)npage<<16u,true); - } - } else { /* playing/recording is finished */ - uint8_t tandy_irq = 7u; - if (tandy_sb.port) tandy_irq = tandy_sb.irq; - else if (tandy_dac.port) tandy_irq = tandy_dac.irq; - uint8_t tandy_irq_vector = tandy_irq; - if (tandy_irq_vector<8u) tandy_irq_vector += 8u; - else tandy_irq_vector += (0x70u-8u); - - RealSetVec(tandy_irq_vector,real_readd(0x40,0xd6)); - - /* turn off speaker and acknowledge soundblaster IRQ */ - if (tandy_sb.port) { - IO_Write(tandy_sb.port+0xcu,0xd3u); - IO_Read(tandy_sb.port+0xeu); - } - - /* issue BIOS tandy sound device busy callout */ - SegSet16(cs, RealSeg(tandy_DAC_callback[1]->Get_RealPointer())); - reg_ip = RealOff(tandy_DAC_callback[1]->Get_RealPointer()); - } - return CBRET_NONE; -} - -static void TandyDAC_Handler(uint8_t tfunction) { - if ((!tandy_sb.port) && (!tandy_dac.port)) return; - switch (tfunction) { - case 0x81: /* Tandy sound system check */ - if (tandy_dac.port) { - reg_ax=tandy_dac.port; - } else { - reg_ax=0xc4; - } - CALLBACK_SCF(Tandy_TransferInProgress()); - break; - case 0x82: /* Tandy sound system start recording */ - case 0x83: /* Tandy sound system start playback */ - if (Tandy_TransferInProgress()) { - /* cannot play yet as the last transfer isn't finished yet */ - reg_ah=0x00; - CALLBACK_SCF(true); - break; - } - /* store buffer length */ - real_writew(0x40,0xd0,reg_cx); - /* store delay and volume */ - real_writew(0x40,0xd2,(reg_dx&0xfff)|((reg_al&7)<<13)); - Tandy_SetupTransfer(PhysMake(SegValue(es),reg_bx),reg_ah==0x83); - reg_ah=0x00; - CALLBACK_SCF(false); - break; - case 0x84: /* Tandy sound system stop playing */ - reg_ah=0x00; - - /* setup for a small buffer with silence */ - real_writew(0x40,0xd0,0x0a); - real_writew(0x40,0xd2,0x1c); - Tandy_SetupTransfer(PhysMake(0xf000,0xa084),true); - CALLBACK_SCF(false); - break; - case 0x85: /* Tandy sound system reset */ - if (tandy_dac.port) { - IO_Write(tandy_dac.port,(uint8_t)(IO_Read(tandy_dac.port)&0xe0)); - } - reg_ah=0x00; - CALLBACK_SCF(false); - break; - } -} - -extern bool date_host_forced; -static uint8_t ReadCmosByte (Bitu index) { - IO_Write(0x70, index); - return IO_Read(0x71); -} - -static void WriteCmosByte (Bitu index, Bitu val) { - IO_Write(0x70, index); - IO_Write(0x71, val); -} - -static bool RtcUpdateDone () { - while ((ReadCmosByte(0x0a) & 0x80) != 0) CALLBACK_Idle(); - return true; // cannot fail in DOSbox -} - -static void InitRtc () { - // Change the RTC to return BCD and set the 24h bit. Clear the SET bit. - // That's it. Do not change any other bits. - // - // Some games ("The Tales of Peter Rabbit") use the RTC clock periodic - // interrupt for timing and music at rates other than 1024Hz and we must - // not change that rate nor clear any interrupt enable bits. Do not clear - // pending interrupts, either! The periodic interrupt does not affect reading - // the RTC clock. The point of this function and INT 15h code calling this - // function is to read the clock. - WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x7du/*clear=SET[7]|DM[2]*/) | 0x03u/*set=24/12[1]|DSE[0]*/); -} - -static Bitu INT1A_Handler(void) { - CALLBACK_SIF(true); - switch (reg_ah) { - case 0x00: /* Get System time */ - { - uint32_t ticks=mem_readd(BIOS_TIMER); - reg_al=mem_readb(BIOS_24_HOURS_FLAG); - mem_writeb(BIOS_24_HOURS_FLAG,0); // reset the "flag" - reg_cx=(uint16_t)(ticks >> 16u); - reg_dx=(uint16_t)(ticks & 0xffff); - break; - } - case 0x01: /* Set System time */ - mem_writed(BIOS_TIMER,((unsigned int)reg_cx<<16u)|reg_dx); - break; - case 0x02: /* GET REAL-TIME CLOCK TIME (AT,XT286,PS) */ - InitRtc(); // make sure BCD and no am/pm - if (RtcUpdateDone()) { // make sure it's safe to read - reg_ch = ReadCmosByte(0x04); // hours - reg_cl = ReadCmosByte(0x02); // minutes - reg_dh = ReadCmosByte(0x00); // seconds - reg_dl = ReadCmosByte(0x0b) & 0x01; // daylight saving time - /* 2023/10/06 - Let interrupts and CPU cycles catch up and the RTC clock a chance to tick. This is needed for - * "Pizza Tycoon" which appears to start by running in a loop reading time from the BIOS and writing - * time to INT 21h in a loop until the second value changes. */ - for (unsigned int c=0;c < 4;c++) CALLBACK_Idle(); - } - CALLBACK_SCF(false); - break; - case 0x03: // set RTC time - InitRtc(); // make sure BCD and no am/pm - if (RtcUpdateDone()) { // make sure it's safe to read - WriteCmosByte(0x0b, ReadCmosByte(0x0b) | 0x80u); // prohibit updates - WriteCmosByte(0x04, reg_ch); // hours - WriteCmosByte(0x02, reg_cl); // minutes - WriteCmosByte(0x00, reg_dh); // seconds - WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x7eu) | (reg_dh & 0x01u)); // dst + implicitly allow updates - /* 2023/10/06 - Let interrupts and CPU cycles catch up and the RTC clock a chance to tick. This is needed for - * "Pizza Tycoon" which appears to start by running in a loop reading time from the BIOS and writing - * time to INT 21h in a loop until the second value changes. */ - for (unsigned int c=0;c < 4;c++) CALLBACK_Idle(); - } - break; - case 0x04: /* GET REAL-TIME ClOCK DATE (AT,XT286,PS) */ - InitRtc(); // make sure BCD and no am/pm - if (RtcUpdateDone()) { // make sure it's safe to read - reg_ch = ReadCmosByte(0x32); // century - reg_cl = ReadCmosByte(0x09); // year - reg_dh = ReadCmosByte(0x08); // month - reg_dl = ReadCmosByte(0x07); // day - /* 2023/10/06 - Let interrupts and CPU cycles catch up and the RTC clock a chance to tick. This is needed for - * "Pizza Tycoon" which appears to start by running in a loop reading time from the BIOS and writing - * time to INT 21h in a loop until the second value changes. */ - for (unsigned int c=0;c < 4;c++) CALLBACK_Idle(); - } - CALLBACK_SCF(false); - break; - case 0x05: // set RTC date - InitRtc(); // make sure BCD and no am/pm - if (RtcUpdateDone()) { // make sure it's safe to read - WriteCmosByte(0x0b, ReadCmosByte(0x0b) | 0x80); // prohibit updates - WriteCmosByte(0x32, reg_ch); // century - WriteCmosByte(0x09, reg_cl); // year - WriteCmosByte(0x08, reg_dh); // month - WriteCmosByte(0x07, reg_dl); // day - WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x7f)); // allow updates - /* 2023/10/06 - Let interrupts and CPU cycles catch up and the RTC clock a chance to tick. This is needed for - * "Pizza Tycoon" which appears to start by running in a loop reading time from the BIOS and writing - * time to INT 21h in a loop until the second value changes. */ - for (unsigned int c=0;c < 4;c++) CALLBACK_Idle(); - } - break; - case 0x80: /* Pcjr Setup Sound Multiplexer */ - LOG(LOG_BIOS,LOG_ERROR)("INT1A:80:Setup tandy sound multiplexer to %d",reg_al); - break; - case 0x81: /* Tandy sound system check */ - case 0x82: /* Tandy sound system start recording */ - case 0x83: /* Tandy sound system start playback */ - case 0x84: /* Tandy sound system stop playing */ - case 0x85: /* Tandy sound system reset */ - TandyDAC_Handler(reg_ah); - break; - case 0xb1: /* PCI Bios Calls */ - if (pcibus_enable) { - LOG(LOG_BIOS,LOG_WARN)("INT1A:PCI bios call %2X",reg_al); - switch (reg_al) { - case 0x01: // installation check - if (PCI_IsInitialized()) { - reg_ah=0x00; - reg_al=0x01; // cfg space mechanism 1 supported - reg_bx=0x0210; // ver 2.10 - reg_cx=0x0000; // only one PCI bus - reg_edx=0x20494350; - reg_edi=PCI_GetPModeInterface(); - CALLBACK_SCF(false); - } else { - CALLBACK_SCF(true); - } - break; - case 0x02: { // find device - Bitu devnr=0u; - Bitu count=0x100u; - uint32_t devicetag=((unsigned int)reg_cx<<16u)|reg_dx; - Bits found=-1; - for (Bitu i=0; i<=count; i++) { - IO_WriteD(0xcf8,0x80000000u|(i<<8u)); // query unique device/subdevice entries - if (IO_ReadD(0xcfc)==devicetag) { - if (devnr==reg_si) { - found=(Bits)i; - break; - } else { - // device found, but not the SIth device - devnr++; - } - } - } - if (found>=0) { - reg_ah=0x00; - reg_bh=0x00; // bus 0 - reg_bl=(uint8_t)(found&0xff); - CALLBACK_SCF(false); - } else { - reg_ah=0x86; // device not found - CALLBACK_SCF(true); - } - } - break; - case 0x03: { // find device by class code - Bitu devnr=0; - Bitu count=0x100u; - uint32_t classtag=reg_ecx&0xffffffu; - Bits found=-1; - for (Bitu i=0; i<=count; i++) { - IO_WriteD(0xcf8,0x80000000u|(i<<8u)); // query unique device/subdevice entries - if (IO_ReadD(0xcfc)!=0xffffffffu) { - IO_WriteD(0xcf8,0x80000000u|(i<<8u)|0x08u); - if ((IO_ReadD(0xcfc)>>8u)==classtag) { - if (devnr==reg_si) { - found=(Bits)i; - break; - } else { - // device found, but not the SIth device - devnr++; - } - } - } - } - if (found>=0) { - reg_ah=0x00; - reg_bh=0x00; // bus 0 - reg_bl=(uint8_t)found & 0xffu; - CALLBACK_SCF(false); - } else { - reg_ah=0x86; // device not found - CALLBACK_SCF(true); - } - } - break; - case 0x08: // read configuration byte - IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); - reg_cl=IO_ReadB(0xcfc+(reg_di&3u)); - CALLBACK_SCF(false); - reg_ah=0x00; - break; - case 0x09: // read configuration word - IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); - reg_cx=IO_ReadW(0xcfc+(reg_di&2u)); - CALLBACK_SCF(false); - reg_ah=0x00; - break; - case 0x0a: // read configuration dword - IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); - reg_ecx=IO_ReadD(0xcfc+(reg_di&3u)); - CALLBACK_SCF(false); - reg_ah=0x00; - break; - case 0x0b: // write configuration byte - IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); - IO_WriteB(0xcfc+(reg_di&3u),reg_cl); - CALLBACK_SCF(false); - reg_ah=0x00; - break; - case 0x0c: // write configuration word - IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); - IO_WriteW(0xcfc+(reg_di&2u),reg_cx); - CALLBACK_SCF(false); - reg_ah=0x00; - break; - case 0x0d: // write configuration dword - IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); - IO_WriteD(0xcfc+((unsigned int)reg_di&3u),reg_ecx); - CALLBACK_SCF(false); - reg_ah=0x00; - break; - default: - LOG(LOG_BIOS,LOG_ERROR)("INT1A:PCI BIOS: unknown function %x (%x %x %x)", - reg_ax,reg_bx,reg_cx,reg_dx); - CALLBACK_SCF(true); - break; - } - } - else { - CALLBACK_SCF(true); - } - break; - default: - LOG(LOG_BIOS,LOG_ERROR)("INT1A:Undefined call %2X",reg_ah); - } - return CBRET_NONE; -} - -bool INT16_get_key(uint16_t &code); -bool INT16_peek_key(uint16_t &code); - -extern uint8_t GDC_display_plane; -extern uint8_t GDC_display_plane_pending; -extern bool GDC_vsync_interrupt; - -unsigned char prev_pc98_mode42 = 0; - -unsigned char pc98_function_row_mode = 0; - -const char *pc98_func_key_default[10] = { - " C1 ", - " CU ", - " CA ", - " S1 ", - " SU ", - - "VOID ", - "NWL ", - "INS ", - "REP ", - " ^Z " -}; - -const char pc98_func_key_escapes_default[10][3] = { - {0x1B,0x53,0}, // F1 - {0x1B,0x54,0}, // F2 - {0x1B,0x55,0}, // F3 - {0x1B,0x56,0}, // F4 - {0x1B,0x57,0}, // F5 - {0x1B,0x45,0}, // F6 - {0x1B,0x4A,0}, // F7 - {0x1B,0x50,0}, // F8 - {0x1B,0x51,0}, // F9 - {0x1B,0x5A,0} // F10 -}; - -const char pc98_editor_key_escapes_default[11][3] = { - {0}, // ROLL UP 0x36 - {0}, // ROLL DOWN 0x37 - {0x1B,0x50,0}, // INS 0x38 - {0x1B,0x44,0}, // DEL 0x39 - {0x0B,0}, // UP ARROW 0x3A - {0x08,0}, // LEFT ARROW 0x3B - {0x0C,0}, // RIGHT ARROW 0x3C - {0x0A,0}, // DOWN ARROW 0x3D - {0}, // HOME/CLR 0x3E - {0}, // HELP 0x3F - {0} // KEYPAD - 0x40 -}; - -// shortcuts offered by SHIFT F1-F10. You can bring this onscreen using CTRL+F7. This row shows '*' in col 2. -// The text displayed onscreen is obviously just the first 6 chars of the shortcut text. -const char *pc98_shcut_key_defaults[10] = { - "dir a:\x0D", - "dir b:\x0D", - "copy ", - "del ", - "ren ", - - "chkdsk a:\x0D", - "chkdsk b:\x0D", - "type ", - "date\x0D", - "time\x0D" -}; - -#pragma pack(push,1) -struct pc98_func_key_shortcut_def { - unsigned char length; /* +0x00 length of text */ - unsigned char shortcut[0x0F]; /* +0x01 Shortcut text to insert into CON device */ - - std::string getShortcutText(void) const { - std::string ret; - unsigned int i; - - /* Whether a shortcut or escape (0xFE or not) the first 6 chars are displayed always */ - /* TODO: Strings for display are expected to display as Shift-JIS, convert to UTF-8 for display on host */ - for (i=0;i < 0x0F;i++) { - if (shortcut[i] == 0u) - break; - else if (shortcut[i] == 0x1B) { - ret += ""; - } - else if (shortcut[i] > 0x7Fu || shortcut[i] < 32u) /* 0xFE is invisible on real hardware */ - ret += ' '; - else - ret += (char)shortcut[i]; - } - - return ret; - } - - std::string getDisplayText(void) const { - unsigned int i; - char tmp[8]; - - /* Whether a shortcut or escape (0xFE or not) the first 6 chars are displayed always */ - /* TODO: Strings for display are expected to display as Shift-JIS, convert to UTF-8 for display on host */ - for (i=0;i < 6;i++) { - if (shortcut[i] == 0u) - break; - else if (shortcut[i] > 0x7Fu || shortcut[i] < 32u) /* 0xFE is invisible on real hardware */ - tmp[i] = ' '; - else - tmp[i] = (char)shortcut[i]; - } - tmp[i] = 0; - - return tmp; - } - - std::string debugToString(void) const { - std::string ret; - char tmp[512]; - - if (length == 0) - return "(none)"; - - if (shortcut[0] == 0xFE) { - sprintf(tmp,"disp=\"%s\" ",getDisplayText().c_str()); - ret += tmp; - - ret += "dispraw={ "; - for (unsigned int i=0;i < 6;i++) { - sprintf(tmp,"%02x ",shortcut[i]); - ret += tmp; - } - ret += "} "; - - ret += "esc={ "; - for (unsigned int i=6;i < length;i++) { - sprintf(tmp,"%02x ",shortcut[i]); - ret += tmp; - } - ret += "}"; - } - else { - sprintf(tmp,"text=\"%s\" ",getShortcutText().c_str()); - ret += tmp; - - ret += "esc={ "; - for (unsigned int i=0;i < length;i++) { - sprintf(tmp,"%02x ",shortcut[i]); - ret += tmp; - } - ret += "}"; - } - - return ret; - } - - // set shortcut. - // usually a direct string to insert. - void set_shortcut(const char *str) { - unsigned int i=0; - char c; - - while (i < 0x0F && (c = *str++) != 0) shortcut[i++] = (unsigned char)c; - length = i; - - while (i < 0x0F) shortcut[i++] = 0; - } - - // set text and escape code. text does NOT include the leading 0xFE char. - void set_text_and_escape(const char *text,const char *escape) { - unsigned int i=1; - char c; - - // this is based on observed MS-DOS behavior on PC-98. - // the length byte covers both the display text and escape code (sum of the two). - // the first byte of the shortcut is 0xFE which apparently means the next 5 chars - // are text to display. The 0xFE is copied as-is to the display when rendered. - // 0xFE in the CG ROM is a blank space. - shortcut[0] = 0xFE; - while (i < 6 && (c = *text++) != 0) shortcut[i++] = (unsigned char)c; - while (i < 6) shortcut[i++] = ' '; - - while (i < 0x0F && (c = *escape++) != 0) shortcut[i++] = (unsigned char)c; - length = i; - while (i < 0x0F) shortcut[i++] = 0; - } -}; /* =0x10 */ -#pragma pack(pop) - -struct pc98_func_key_shortcut_def pc98_func_key[10]; /* F1-F10 */ -struct pc98_func_key_shortcut_def pc98_vfunc_key[5]; /* VF1-VF5 */ -struct pc98_func_key_shortcut_def pc98_func_key_shortcut[10]; /* Shift+F1 - Shift-F10 */ -struct pc98_func_key_shortcut_def pc98_vfunc_key_shortcut[5]; /* Shift+VF1 - Shift-VF5 */ -struct pc98_func_key_shortcut_def pc98_func_key_ctrl[10]; /* Control+F1 - Control-F10 */ -struct pc98_func_key_shortcut_def pc98_vfunc_key_ctrl[5]; /* Control+VF1 - Control-VF5 */ -struct pc98_func_key_shortcut_def pc98_editor_key_escapes[11]; /* Editor keys */ - -// FIXME: This is STUPID. Cleanup is needed in order to properly use std::min without causing grief. -#ifdef _MSC_VER -# define MIN(a,b) ((a) < (b) ? (a) : (b)) -# define MAX(a,b) ((a) > (b) ? (a) : (b)) -#else -# define MIN(a,b) std::min(a,b) -# define MAX(a,b) std::max(a,b) -#endif - -void PC98_GetFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i,const struct pc98_func_key_shortcut_def *keylist) { - if (i >= 1 && i <= 10) { - const pc98_func_key_shortcut_def &def = keylist[i-1u]; - unsigned int j=0,o=0; - - /* if the shortcut starts with 0xFE then the next 5 chars are intended for display only - * and the shortcut starts after that. Else the entire string is stuffed into the CON - * device. */ - if (def.shortcut[0] == 0xFE) - j = 6; - - while (j < MIN(0x0Fu,(unsigned int)def.length)) - buf[o++] = def.shortcut[j++]; - - len = (size_t)o; - buf[o] = 0; - } - else { - len = 0; - buf[0] = 0; - } -} - -void PC98_GetEditorKeyEscape(size_t &len,unsigned char buf[16],const unsigned int scan) { - if (scan >= 0x36 && scan <= 0x40) { - const pc98_func_key_shortcut_def &def = pc98_editor_key_escapes[scan-0x36]; - unsigned int j=0,o=0; - - while (j < MIN(0x05u,(unsigned int)def.length)) - buf[o++] = def.shortcut[j++]; - - len = (size_t)o; - buf[o] = 0; - } - else { - len = 0; - buf[0] = 0; - } -} - -void PC98_GetVFKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i,const struct pc98_func_key_shortcut_def *keylist) { - if (i >= 1 && i <= 5) { - const pc98_func_key_shortcut_def &def = keylist[i-1]; - unsigned int j=0,o=0; - - /* if the shortcut starts with 0xFE then the next 5 chars are intended for display only - * and the shortcut starts after that. Else the entire string is stuffed into the CON - * device. */ - if (def.shortcut[0] == 0xFE) - j = 6; - - while (j < MIN(0x0Fu,(unsigned int)def.length)) - buf[o++] = def.shortcut[j++]; - - len = (size_t)o; - buf[o] = 0; - } - else { - len = 0; - buf[0] = 0; - } -} - -void PC98_GetFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { - PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key); -} - -void PC98_GetShiftFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { - PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key_shortcut); -} - -void PC98_GetCtrlFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { - PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key_ctrl); -} - -void PC98_GetVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { - PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key); -} - -void PC98_GetShiftVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { - PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key_shortcut); -} - -void PC98_GetCtrlVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { - PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key_ctrl); -} - -void PC98_InitDefFuncRow(void) { - for (unsigned int i=0;i < 10;i++) { - pc98_func_key_shortcut_def &def = pc98_func_key[i]; - - def.set_text_and_escape(pc98_func_key_default[i],pc98_func_key_escapes_default[i]); - } - for (unsigned int i=0;i < 10;i++) { - pc98_func_key_shortcut_def &def = pc98_func_key_shortcut[i]; - - def.set_shortcut(pc98_shcut_key_defaults[i]); - } - for (unsigned int i=0;i < 11;i++) { - pc98_func_key_shortcut_def &def = pc98_editor_key_escapes[i]; - - def.set_shortcut(pc98_editor_key_escapes_default[i]); - } - for (unsigned int i=0;i < 10;i++) { - pc98_func_key_shortcut_def &def = pc98_func_key_ctrl[i]; - - def.set_shortcut(""); - } - /* MS-DOS by default does not assign the VFn keys anything */ - for (unsigned int i=0;i < 5;i++) { - pc98_func_key_shortcut_def &def = pc98_vfunc_key[i]; - - def.set_shortcut(""); - } - for (unsigned int i=0;i < 5;i++) { - pc98_func_key_shortcut_def &def = pc98_vfunc_key_shortcut[i]; - - def.set_shortcut(""); - } - for (unsigned int i=0;i < 5;i++) { - pc98_func_key_shortcut_def &def = pc98_vfunc_key_ctrl[i]; - - def.set_shortcut(""); - } -} - -#include "int10.h" - -void draw_pc98_function_row_elem(unsigned int o, unsigned int co, const struct pc98_func_key_shortcut_def& key) { - const unsigned char *str = key.shortcut; - unsigned int j = 0,i = 0; - - // NTS: Some shortcut strings start with 0xFE, which is rendered as an invisible space anyway. - - // NTS: Apparently the strings are Shift-JIS and expected to render to the function key row - // the same way the console normally does it. - ShiftJISDecoder sjis; - - while (j < 6u && str[i] != 0) { - if (sjis.take(str[i++])) { - if (sjis.doublewide) { - /* JIS conversion to WORD value appropriate for text RAM */ - if (sjis.b2 != 0) sjis.b1 -= 0x20; - - uint16_t w = (sjis.b2 << 8) + sjis.b1; - mem_writew(0xA0000+((o+co+j)*2u),w); - mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible - j++; - mem_writew(0xA0000+((o+co+j)*2u),w); - mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible - j++; - } - else { - mem_writew(0xA0000+((o+co+j)*2u),str[j]); - mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible - j++; - } - } - } - - while (j < 6u) { - mem_writew(0xA0000+((o+co+j)*2u),(unsigned char)(' ')); - mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible - j++; - } -} - -void draw_pc98_function_row(unsigned int o, const struct pc98_func_key_shortcut_def* keylist) { - mem_writew(0xA0000+((o+1)*2),real_readb(0x60,0x8B)); - mem_writeb(0xA2000+((o+1)*2),0xE1); - for (unsigned int i=0u;i < 5u;i++) - draw_pc98_function_row_elem(o,4u + (i * 7u),keylist[i]); - for (unsigned int i=5u;i < 10u;i++) - draw_pc98_function_row_elem(o,42u + ((i - 5u) * 7u),keylist[i]); -} - -unsigned int pc98_DOS_console_rows(void) { - uint8_t b = real_readb(0x60,0x113); - - return (b & 0x01) ? 25 : 20; -} - -void update_pc98_function_row(unsigned char setting,bool force_redraw) { - if (!force_redraw && pc98_function_row_mode == setting) return; - pc98_function_row_mode = setting; - - unsigned int total_rows = pc98_DOS_console_rows(); - unsigned char c = real_readb(0x60,0x11C); - unsigned char r = real_readb(0x60,0x110); - unsigned int o = 80 * (total_rows - 1); - - if (pc98_function_row_mode != 0) { - if (r > (total_rows - 2)) { - r = (total_rows - 2); - void INTDC_CL10h_AH04h(void); - INTDC_CL10h_AH04h(); - } - } - - /* update mode 2 indicator */ - real_writeb(0x60,0x8C,(pc98_function_row_mode == 2) ? '*' : ' '); - - real_writeb(0x60,0x112,total_rows - 1 - ((pc98_function_row_mode != 0) ? 1 : 0)); - - if (pc98_function_row_mode == 2) { - /* draw the function row. - * based on real hardware: - * - * The function key is 72 chars wide. 4 blank chars on each side of the screen. - * It is divided into two halves, 36 chars each. - * Within each half, aligned to its side, is 5 x 7 regions. - * 6 of the 7 are inverted. centered in the white block is the function key. */ - for (unsigned int i=0;i < 40;) { - mem_writew(0xA0000+((o+i)*2),0x0000); - mem_writeb(0xA2000+((o+i)*2),0xE1); - - mem_writew(0xA0000+((o+(79-i))*2),0x0000); - mem_writeb(0xA2000+((o+(79-i))*2),0xE1); - - if (i >= 3 && i < 38) - i += 7; - else - i++; - } - - mem_writew(0xA0000+((o+2)*2),real_readb(0x60,0x8C)); - mem_writeb(0xA2000+((o+2)*2),0xE1); - - draw_pc98_function_row(o,pc98_func_key_shortcut); - } - else if (pc98_function_row_mode == 1) { - /* draw the function row. - * based on real hardware: - * - * The function key is 72 chars wide. 4 blank chars on each side of the screen. - * It is divided into two halves, 36 chars each. - * Within each half, aligned to its side, is 5 x 7 regions. - * 6 of the 7 are inverted. centered in the white block is the function key. */ - for (unsigned int i=0;i < 40;) { - mem_writew(0xA0000+((o+i)*2),0x0000); - mem_writeb(0xA2000+((o+i)*2),0xE1); - - mem_writew(0xA0000+((o+(79-i))*2),0x0000); - mem_writeb(0xA2000+((o+(79-i))*2),0xE1); - - if (i >= 3 && i < 38) - i += 7; - else - i++; - } - - draw_pc98_function_row(o,pc98_func_key); - } - else { - /* erase the function row */ - for (unsigned int i=0;i < 80;i++) { - mem_writew(0xA0000+((o+i)*2),0x0000); - mem_writeb(0xA2000+((o+i)*2),0xE1); - } - } - - real_writeb(0x60,0x11C,c); - real_writeb(0x60,0x110,r); - - real_writeb(0x60,0x111,(pc98_function_row_mode != 0) ? 0x01 : 0x00);/* function key row display status */ - - void vga_pc98_direct_cursor_pos(uint16_t address); - vga_pc98_direct_cursor_pos((r*80)+c); -} - -void pc98_function_row_user_toggle(void) { - if (pc98_function_row_mode >= 2) - update_pc98_function_row(0,true); - else - update_pc98_function_row(pc98_function_row_mode+1,true); -} - -void pc98_set_char_mode(bool mode) { - real_writeb(0x60,0x8A,mode); - real_writeb(0x60,0x8B,(mode == true) ? ' ' : 'g'); - update_pc98_function_row(pc98_function_row_mode,true); -} - -void pc98_toggle_char_mode(void) { - pc98_set_char_mode(!real_readb(0x60,0x8A)); -} - -void pc98_set_digpal_entry(unsigned char ent,unsigned char grb); -void PC98_show_cursor(bool show); - -extern bool gdc_5mhz_mode; -extern bool enable_pc98_egc; -extern bool enable_pc98_grcg; -extern bool enable_pc98_16color; -extern bool enable_pc98_256color; -extern bool enable_pc98_188usermod; -extern bool pc98_31khz_mode; -extern bool pc98_attr4_graphic; - -extern unsigned char pc98_text_first_row_scanline_start; /* port 70h */ -extern unsigned char pc98_text_first_row_scanline_end; /* port 72h */ -extern unsigned char pc98_text_row_scanline_blank_at; /* port 74h */ -extern unsigned char pc98_text_row_scroll_lines; /* port 76h */ -extern unsigned char pc98_text_row_scroll_count_start; /* port 78h */ -extern unsigned char pc98_text_row_scroll_num_lines; /* port 7Ah */ - -void pc98_update_text_layer_lineheight_from_bda(void) { -// unsigned char c = mem_readb(0x53C); - unsigned char lineheight = mem_readb(0x53B) + 1; - - pc98_gdc[GDC_MASTER].force_fifo_complete(); - pc98_gdc[GDC_MASTER].row_height = lineheight; - - if (lineheight > 20) { // usually 24 - pc98_text_first_row_scanline_start = 0x1C; - pc98_text_first_row_scanline_end = lineheight - 5; - pc98_text_row_scanline_blank_at = 16; - } - else if (lineheight > 16) { // usually 20 - pc98_text_first_row_scanline_start = 0x1E; - pc98_text_first_row_scanline_end = lineheight - 3; - pc98_text_row_scanline_blank_at = 16; - } - else { - pc98_text_first_row_scanline_start = 0; - pc98_text_first_row_scanline_end = lineheight - 1; - pc98_text_row_scanline_blank_at = lineheight; - } - - pc98_text_row_scroll_lines = 0; - pc98_text_row_scroll_count_start = 0; - pc98_text_row_scroll_num_lines = 0; - - vga.crtc.cursor_start = 0; - vga.draw.cursor.sline = 0; - - vga.crtc.cursor_end = lineheight - 1; - vga.draw.cursor.eline = lineheight - 1; -} - -void pc98_update_text_lineheight_from_bda(void) { - unsigned char b597 = mem_readb(0x597); - unsigned char c = mem_readb(0x53C); - unsigned char lineheight; - - if ((b597 & 0x3) == 0x3) {//WARNING: This could be wrong - if (c & 0x10)/*30-line mode (30x16 = 640x480)*/ - lineheight = 16; - else if (c & 0x01)/*20-line mode (20x24 = 640x480)*/ - lineheight = 24; - else/*25-line mode (25x19 = 640x480)*/ - lineheight = 19; - } - else { - if (c & 0x10)/*30-line mode (30x13 = 640x400)*/ - lineheight = 13;//?? - else if (c & 0x01)/*20-line mode (20x20 = 640x400)*/ - lineheight = 20; - else/*25-line mode (25x16 = 640x400)*/ - lineheight = 16; - } - - mem_writeb(0x53B,lineheight - 1); -} - -static const uint8_t pc98_katakana6x8_font[] = { - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x50,0x20,0x00, - 0x70,0x40,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x1c,0x00, - 0x00,0x00,0x00,0x00,0x40,0x20,0x10,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00, - 0x7c,0x04,0x7c,0x04,0x04,0x08,0x30,0x00,0x00,0x00,0x7c,0x14,0x18,0x10,0x20,0x00, - 0x00,0x00,0x04,0x08,0x18,0x28,0x08,0x00,0x00,0x00,0x10,0x7c,0x44,0x04,0x18,0x00, - 0x00,0x00,0x00,0x38,0x10,0x10,0x7c,0x00,0x00,0x00,0x08,0x7c,0x18,0x28,0x48,0x00, - 0x00,0x00,0x20,0x7c,0x24,0x28,0x20,0x00,0x00,0x00,0x00,0x38,0x08,0x08,0x7c,0x00, - 0x00,0x00,0x3c,0x04,0x3c,0x04,0x3c,0x00,0x00,0x00,0x00,0x54,0x54,0x04,0x18,0x00, - 0x00,0x00,0x00,0x7c,0x00,0x00,0x00,0x00,0x7c,0x04,0x14,0x18,0x10,0x20,0x40,0x00, - 0x04,0x08,0x10,0x30,0x50,0x10,0x10,0x00,0x10,0x7c,0x44,0x44,0x04,0x08,0x10,0x00, - 0x00,0x7c,0x10,0x10,0x10,0x10,0x7c,0x00,0x08,0x7c,0x18,0x28,0x48,0x08,0x08,0x00, - 0x20,0x7c,0x24,0x24,0x24,0x44,0x08,0x00,0x10,0x7c,0x10,0x7c,0x10,0x10,0x10,0x00, - 0x3c,0x24,0x44,0x04,0x04,0x08,0x30,0x00,0x20,0x3c,0x28,0x48,0x08,0x08,0x30,0x00, - 0x00,0x7c,0x04,0x04,0x04,0x04,0x7c,0x00,0x28,0x28,0x7c,0x28,0x08,0x10,0x20,0x00, - 0x60,0x00,0x64,0x04,0x04,0x08,0x70,0x00,0x7c,0x04,0x04,0x08,0x10,0x28,0x44,0x00, - 0x20,0x7c,0x24,0x28,0x20,0x20,0x18,0x00,0x44,0x44,0x24,0x04,0x04,0x08,0x30,0x00, - 0x3c,0x24,0x34,0x4c,0x04,0x08,0x30,0x00,0x08,0x70,0x10,0x7c,0x10,0x10,0x20,0x00, - 0x54,0x54,0x54,0x04,0x08,0x08,0x30,0x00,0x38,0x00,0x7c,0x10,0x10,0x10,0x20,0x00, - 0x20,0x20,0x20,0x38,0x24,0x20,0x20,0x00,0x10,0x10,0x7c,0x10,0x10,0x20,0x40,0x00, - 0x00,0x38,0x00,0x00,0x00,0x00,0x7c,0x00,0x7c,0x04,0x04,0x28,0x10,0x28,0x40,0x00, - 0x10,0x7c,0x08,0x10,0x38,0x54,0x10,0x00,0x04,0x04,0x04,0x04,0x08,0x10,0x20,0x00, - 0x10,0x08,0x04,0x44,0x44,0x44,0x44,0x00,0x40,0x4c,0x70,0x40,0x40,0x40,0x3c,0x00, - 0x7c,0x04,0x04,0x04,0x04,0x08,0x30,0x00,0x00,0x20,0x50,0x08,0x04,0x04,0x00,0x00, - 0x10,0x7c,0x10,0x10,0x54,0x54,0x10,0x00,0x00,0x7c,0x04,0x04,0x28,0x10,0x08,0x00, - 0x00,0x38,0x00,0x38,0x00,0x38,0x04,0x00,0x10,0x10,0x20,0x40,0x44,0x7c,0x04,0x00, - 0x04,0x04,0x28,0x10,0x28,0x40,0x00,0x00,0x7c,0x10,0x7c,0x10,0x10,0x10,0x0c,0x00, - 0x20,0x7c,0x24,0x24,0x28,0x20,0x20,0x00,0x00,0x38,0x08,0x08,0x08,0x08,0x7c,0x00, - 0x7c,0x04,0x04,0x7c,0x04,0x04,0x7c,0x00,0x38,0x00,0x7c,0x04,0x04,0x08,0x30,0x00, - 0x24,0x24,0x24,0x04,0x04,0x08,0x10,0x00,0x10,0x50,0x50,0x50,0x54,0x58,0x10,0x00, - 0x20,0x20,0x20,0x24,0x24,0x28,0x30,0x00,0x7c,0x44,0x44,0x44,0x44,0x44,0x7c,0x00, - 0x7c,0x44,0x44,0x04,0x04,0x08,0x10,0x00,0x60,0x00,0x04,0x04,0x08,0x10,0x60,0x00, - 0x20,0x10,0x40,0x20,0x00,0x00,0x00,0x00,0x00,0x20,0x50,0x20,0x00,0x00,0x00,0x00 -}; - -unsigned char byte_reverse(unsigned char c); - -static void PC98_INT18_DrawShape(void) -{ - PhysPt ucw; - uint8_t type, dir; - uint16_t x1, y1; - uint16_t ead, dad; - uint16_t dc, d, d2, dm; - - ucw = SegPhys(ds) + reg_bx; - type = mem_readb(ucw + 0x28); - dir = mem_readb(ucw + 0x03); - x1 = mem_readw(ucw + 0x08); - y1 = mem_readw(ucw + 0x0a); - if((reg_ch & 0xc0) == 0x40) { - y1 += 200; - } - ead = (y1 * 40) + (x1 >> 4); - dad = x1 % 16; - // line pattern - pc98_gdc[GDC_SLAVE].set_textw(((uint16_t)byte_reverse(mem_readb(ucw + 0x20)) << 8) | byte_reverse(mem_readb(ucw + 0x21))); - if(type == 0x04) { - // arc - dc = mem_readw(ucw + 0x0c); - d = mem_readw(ucw + 0x1c) - 1; - d2 = d >> 1; - dm = mem_readw(ucw + 0x1a); - if((reg_ch & 0x30) == 0x30) { - uint8_t plane = mem_readb(ucw + 0x00); - uint32_t offset = 0x4000; - for(uint8_t bit = 1 ; bit <= 4 ; bit <<= 1) { - pc98_gdc[GDC_SLAVE].set_mode((plane & bit) ? 0x03 : 0x02); - pc98_gdc[GDC_SLAVE].set_vectw(0x20, dir, dc, d, d2, 0x3fff, dm); - pc98_gdc[GDC_SLAVE].set_csrw(offset + ead, dad); - pc98_gdc[GDC_SLAVE].exec(0x6c); - offset += 0x4000; - } - } else { - pc98_gdc[GDC_SLAVE].set_mode(mem_readb(ucw + 0x02)); - pc98_gdc[GDC_SLAVE].set_vectw(0x20, dir, dc, d, d2, 0x3fff, dm); - pc98_gdc[GDC_SLAVE].set_csrw(0x4000 + ((reg_ch & 0x30) << 10) + ead, dad); - pc98_gdc[GDC_SLAVE].exec(0x6c); - } - } else { - uint16_t x2, y2, temp; - x2 = mem_readw(ucw + 0x16); - y2 = mem_readw(ucw + 0x18); - if(type == 0x01) { - // line - if((reg_ch & 0x30) == 0x30) { - uint8_t plane = mem_readb(ucw + 0x00); - uint32_t offset = 0x4000; - for(uint8_t bit = 1 ; bit <= 4 ; bit <<= 1) { - pc98_gdc[GDC_SLAVE].set_mode((plane & bit) ? 0x03 : 0x02); - pc98_gdc[GDC_SLAVE].set_vectl(x1, y1, x2, y2); - pc98_gdc[GDC_SLAVE].set_csrw(offset + ead, dad); - pc98_gdc[GDC_SLAVE].exec(0x6c); - offset += 0x4000; - } - } else { - pc98_gdc[GDC_SLAVE].set_mode(mem_readb(ucw + 0x02)); - pc98_gdc[GDC_SLAVE].set_vectl(x1, y1, x2, y2); - pc98_gdc[GDC_SLAVE].set_csrw(0x4000 + ((reg_ch & 0x30) << 10) + ead, dad); - pc98_gdc[GDC_SLAVE].exec(0x6c); - } - } else if(type == 0x02) { - // box - uint16_t dx, dy; - if(x1 > x2) { - temp = x2; x2 = x1; x1 = temp; - } - if(y1 > y2) { - temp = y2; y2 = y1; y1 = temp; - } - dx = x2 - x1; - dy = y2 - y1; - switch(dir & 3) { - case 0: - d = dy; - d2 = dx; - break; - case 1: - d2 = dx + dy; - d2 >>= 1; - d = dx - dy; - d = (d >> 1) & 0x3fff; - break; - case 2: - d = dx; - d2 = dy; - break; - case 3: - d2 = dx + dy; - d2 >>= 1; - d = dy - dx; - d = (d >> 1) & 0x3fff; - break; - } - if((reg_ch & 0x30) == 0x30) { - uint8_t plane = mem_readb(ucw + 0x00); - uint32_t offset = 0x4000; - for(uint8_t bit = 1 ; bit <= 4 ; bit <<= 1) { - pc98_gdc[GDC_SLAVE].set_mode((plane & bit) ? 0x03 : 0x02); - pc98_gdc[GDC_SLAVE].set_vectw(0x40, dir, 3, d, d2, 0xffff, d); - pc98_gdc[GDC_SLAVE].set_csrw(offset + ead, dad); - pc98_gdc[GDC_SLAVE].exec(0x6c); - offset += 0x4000; - } - } else { - pc98_gdc[GDC_SLAVE].set_mode(mem_readb(ucw + 0x02)); - pc98_gdc[GDC_SLAVE].set_vectw(0x40, dir, 3, d, d2, 0xffff, d); - pc98_gdc[GDC_SLAVE].set_csrw(0x4000 + ((reg_ch & 0x30) << 10) + ead, dad); - pc98_gdc[GDC_SLAVE].exec(0x6c); - } - } - } -} - -static void PC98_INT18_DrawText(void) -{ - PhysPt ucw; - uint8_t dir; - uint8_t tile[8]; - uint16_t len; - uint16_t x1, y1; - uint16_t ead, dad; - uint16_t dc, d; - - ucw = SegPhys(ds) + reg_bx; - for(uint8_t i = 0 ; i < 8 ; i++) { - tile[i] = byte_reverse(mem_readb(ucw + 0x20 + i)); - } - pc98_gdc[GDC_SLAVE].set_textw(tile, 8); - len = mem_readw(ucw + 0x0c); - if(len > 0) { - d = len; - dc = (mem_readw(ucw + 0x1e) - 1) & 0x3fff; - } else { - d = 8; - dc = 7; - } - dir = mem_readb(ucw + 0x03); - x1 = mem_readw(ucw + 0x08); - y1 = mem_readw(ucw + 0x0a); - if((reg_ch & 0xc0) == 0x40) { - y1 += 200; - } - ead = (y1 * 40) + (x1 >> 4); - dad = x1 % 16; - if((reg_ch & 0x30) == 0x30) { - uint8_t plane = mem_readb(ucw + 0x00); - uint32_t offset = 0x4000; - for(uint8_t bit = 1 ; bit <= 4 ; bit <<= 1) { - pc98_gdc[GDC_SLAVE].set_mode((plane & bit) ? 0x03 : 0x02); - pc98_gdc[GDC_SLAVE].set_vectw(0x10, dir, dc, d, 0, 0, 0); - pc98_gdc[GDC_SLAVE].set_csrw(offset + ead, dad); - pc98_gdc[GDC_SLAVE].exec(0x68); - offset += 0x4000; - } - } else { - pc98_gdc[GDC_SLAVE].set_mode(mem_readb(ucw + 0x02)); - pc98_gdc[GDC_SLAVE].set_vectw(0x10, dir, dc, d, 0, 0, 0); - pc98_gdc[GDC_SLAVE].set_csrw(0x4000 + ((reg_ch & 0x30) << 10) + ead, dad); - pc98_gdc[GDC_SLAVE].exec(0x68); - } -} - -/* TODO: The text and graphics code that talks to the GDC will need to be converted - * to CPU I/O read and write calls. I think the reason Windows 3.1's 16-color - * driver is causing screen distortion when going fullscreen with COMMAND.COM, - * and the reason COMMAND.COM windowed doesn't show anything, has to do with - * the fact that Windows 3.1 expects this BIOS call to use I/O so it can trap - * and virtualize the GDC and display state. - * - * Obviously for the same reason VGA INT 10h emulation in IBM PC mode needs to - * do the same to prevent display and virtualization problems with the IBM PC - * version of Windows 3.1. - * - * See also: [https://github.com/joncampbell123/dosbox-x/issues/1066] */ -static Bitu INT18_PC98_Handler(void) { - uint16_t temp16; - -#if 0 - if (reg_ah >= 0x0A) { - LOG_MSG("PC-98 INT 18h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - } -#endif - - /* NTS: Based on information gleaned from Neko Project II source code including comments which - * I've run through GNU iconv to convert from SHIFT-JIS to UTF-8 here in case Google Translate - * got anything wrong. */ - switch (reg_ah) { - case 0x00: /* Reading of key data (キー・データの読みだし) */ - /* FIXME: We use the IBM PC/AT keyboard buffer to fake this call. - * This will be replaced with PROPER emulation once the PC-98 keyboard handler has been - * updated to write the buffer the way PC-98 BIOSes do it. - * - * IBM PC/AT keyboard buffer at 40:1E-40:3D - * - * PC-98 keyboard buffer at 50:02-50:21 */ - /* This call blocks until keyboard input */ - if (INT16_get_key(temp16)) { - reg_ax = temp16; - } - else { - /* Keyboard checks. - * If the interrupt got masked, unmask it. - * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler - * handled the keyboard interrupt and never read the keyboard (Quarth). - * - * TODO: Is this what real PC-98 BIOSes do? */ - void check_keyboard_fire_IRQ1(void); - check_keyboard_fire_IRQ1(); - IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 - - reg_ip += 1; /* step over IRET, to NOPs which then JMP back to callback */ - } - break; - case 0x01: /* Sense of key buffer state (キー・バッファ状態のセンス) */ - /* This call returns whether or not there is input waiting. - * The waiting data is read, but NOT discarded from the buffer. */ - if (INT16_peek_key(temp16)) { - reg_ax = temp16; - reg_bh = 1; - } - else { - /* Keyboard checks. - * If the interrupt got masked, unmask it. - * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler - * handled the keyboard interrupt and never read the keyboard (Quarth). - * - * TODO: Is this what real PC-98 BIOSes do? */ - void check_keyboard_fire_IRQ1(void); - check_keyboard_fire_IRQ1(); - IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 - - reg_bh = 0; - } - break; - case 0x02: /* Sense of shift key state (シフト・キー状態のセンス) */ - reg_al = mem_readb(0x53A); - break; - case 0x03: /* Initialization of keyboard interface (キーボード・インタフェイスの初期化) */ - /* TODO */ - IO_WriteB(0x43, 0x3a); - IO_WriteB(0x43, 0x32); - IO_WriteB(0x43, 0x16); - for (int i=0; i<0x20; i++) mem_writeb(0x502+i, 0); - for (int i=0; i<0x13; i++) mem_writeb(0x528+i, 0); - mem_writew(0x522,(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800)); - mem_writew(0x524, 0x0502); - mem_writew(0x526, 0x0502); - mem_writew(0x5C6,(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800)); - mem_writew(0x5C8,0xFD80); - break; - case 0x04: /* Sense of key input state (キー入力状態のセンス) */ - reg_ah = mem_readb(0x52A + (unsigned int)(reg_al & 0x0Fu)); - /* Hack for "Shangrlia" by Elf: The game's regulation of animation speed seems to depend on - * INT 18h AH=0x04 taking some amount of time. If we do not do this, animation will run way - * too fast and everyone will be talking/moving at a million miles a second. - * - * This is based on comparing animation speed vs the same game on real Pentium-class PC-98 - * hardware. - * - * Looking at the software loop involved during opening cutscenes, the game is constantly - * polling INT 18h AH=04h (keyboard state) and INT 33h AH=03h (mouse button/position state) - * while animating the characters on the screen. Without this delay, animation runs way too - * fast. - * - * This guess is also loosely based on a report by the Touhou Community Reliant Automatic Patcher - * that Touhou Project directly reads this byte but delays by 0.6ms to handle the fact that - * the bit in question may toggle while the key is held down due to the scan codes returned by - * the keyboard. - * - * This is a guess, but it seems to help animation speed match that of real hardware regardless - * of cycle count in DOSBox-X. */ - CPU_Cycles -= (cpu_cycles_count_t)(CPU_CycleMax * 0.006); - break; - case 0x05: /* Key input sense (キー入力センス) */ - /* This appears to return a key from the buffer (and remove from - * buffer) or return BH == 0 to signal no key was pending. */ - if (INT16_get_key(temp16)) { - reg_ax = temp16; - reg_bh = 1; - } - else { - /* Keyboard checks. - * If the interrupt got masked, unmask it. - * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler - * handled the keyboard interrupt and never read the keyboard (Quarth). - * - * TODO: Is this what real PC-98 BIOSes do? */ - void check_keyboard_fire_IRQ1(void); - check_keyboard_fire_IRQ1(); - IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 - - reg_bh = 0; - } - break; - case 0x0A: /* set CRT mode */ - /* bit off on - 0 25lines 20lines - 1 80cols 40cols - 2 v.lines simp.graphics - 3 K-CG access mode(not used in PC-98) */ - - //TODO: set 25/20 lines mode and 80/40 columns mode. - //Attribute bit (bit 2) - pc98_attr4_graphic = !!(reg_al & 0x04); - pc98_40col_text = !!(reg_al & 0x02); -#if defined(USE_TTF) - if (!(reg_al & 0xc) && pc98_gdc[GDC_MASTER].display_enable) ttf_switch_on(false); -#endif - - mem_writeb(0x53C,(mem_readb(0x53C) & 0xF0u) | (reg_al & 0x0Fu)); - - if (reg_al & 8) - LOG_MSG("INT 18H AH=0Ah warning: K-CG dot access mode not supported"); - - pc98_update_text_lineheight_from_bda(); - pc98_update_text_layer_lineheight_from_bda(); - - /* Apparently, this BIOS call also hides the cursor */ - PC98_show_cursor(0); - break; - case 0x0B: /* get CRT mode */ - /* bit off on - 0 25lines 20lines - 1 80cols 40cols - 2 v.lines simp.graphics - 3 K-CG access mode(not used in PC-98) - 7 std CRT hi-res CRT */ - /* NTS: I assume that real hardware doesn't offer a way to read back the state of these bits, - * so the BIOS's only option is to read the mode byte back from the data area. - * Neko Project II agrees. */ - reg_al = mem_readb(0x53C); - break; - // TODO: "Edge" is using INT 18h AH=06h, what is that? - // (Something to do with the buffer [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf]) - // Neko Project is also unaware of such a call. - case 0x0C: /* text layer enable */ - /* PROBLEM: Okay, so it's unclear when text layer is or is not allowed. - * I was unable to turn on the text layer with this BIOS call on real PC-9821 hardware, so I believed that it did not allow it. - * - * But PC-9821 CD-ROM game "Shamat, The Holy Circlet" expects to turn on the text layer in 640x400 256-color PEGC mode, - * because it displays graphics in the background while scrolling Japanese text up over it, and if sound hardware is available, - * plays a voice reading the text synchronized to it. - * - * Perhaps in my case it was 640x480 256-color mode, not 640x400 256-color mode, but then, 640x480 also enables a text mode with - * either more rows or a taller character cell which is apparently recognized by the MS-DOS console driver. - * - * So then, what exactly decides whether or not to allow this call to enable the text layer? */ - if (pc98_gdc_vramop & (1u << VOPBIT_VGA) && 0/*DISABLED*/) { - /* NTS: According to tests on real PC-9821 hardware, you can't turn on the text layer in 256-color mode, at least through the BIOS. */ - /* FIXME: Is this a restriction imposed by the BIOS, or the hardware itself? */ - LOG_MSG("INT 18h: Attempt to turn on text layer in 256-color mode"); - } - else { - pc98_gdc[GDC_MASTER].force_fifo_complete(); - pc98_gdc[GDC_MASTER].display_enable = true; -#if defined(USE_TTF) - ttf_switch_on(false); -#endif - } - break; - case 0x0D: /* text layer disable */ -#if defined(USE_TTF) - ttf_switch_off(false); -#endif - pc98_gdc[GDC_MASTER].force_fifo_complete(); - pc98_gdc[GDC_MASTER].display_enable = false; - break; - case 0x0E: /* set text display area (DX=byte offset) */ - pc98_gdc[GDC_MASTER].force_fifo_complete(); - pc98_gdc[GDC_MASTER].param_ram[0] = (reg_dx >> 1) & 0xFF; - pc98_gdc[GDC_MASTER].param_ram[1] = (reg_dx >> 9) & 0xFF; - pc98_gdc[GDC_MASTER].param_ram[2] = (400 << 4) & 0xFF; - pc98_gdc[GDC_MASTER].param_ram[3] = (400 << 4) >> 8; - break; - case 0x11: /* show cursor */ - PC98_show_cursor(true); - break; - case 0x12: /* hide cursor */ - PC98_show_cursor(false); - break; - case 0x13: /* set cursor position (DX=byte position) */ - void vga_pc98_direct_cursor_pos(uint16_t address); - - pc98_gdc[GDC_MASTER].force_fifo_complete(); - vga_pc98_direct_cursor_pos(reg_dx >> 1); - break; - case 0x14: /* read FONT RAM */ - { - unsigned int i,o,r; - - /* DX = code (must be 0x76xx or 0x7700) - * BX:CX = 34-byte region to write to */ - if (reg_dh == 0x80u) { /* 8x16 ascii */ - i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; - mem_writew(i-2u,0x0102u); - for (r=0;r < 16u;r++) { - o = (reg_dl*16u)+r; - - assert((o+2u) <= sizeof(vga.draw.font)); - - mem_writeb(i+r,vga.draw.font[o]); - } - } - else if ((reg_dh & 0xFC) == 0x28) { /* 8x16 kanji */ - i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; - mem_writew(i-2u,0x0102u); - for (r=0;r < 16u;r++) { - o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; - - assert((o+2u) <= sizeof(vga.draw.font)); - - mem_writeb(i+r+0u,vga.draw.font[o+0u]); - } - } - else if (reg_dh != 0) { /* 16x16 kanji */ - i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; - mem_writew(i-2u,0x0202u); - for (r=0;r < 16u;r++) { - o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; - - assert((o+2u) <= sizeof(vga.draw.font)); - - mem_writeb(i+(r*2u)+0u,vga.draw.font[o+0u]); - mem_writeb(i+(r*2u)+1u,vga.draw.font[o+1u]); - } - } - else if(reg_dl < 0x80) { /* 6x8 ascii .. Substitute 8x8 */ - i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; - mem_writew(i-2u,0x0101u); - o = reg_dl * 8; - for (r=0;r < 8u;r++) { - mem_writeb(i+r, int10_font_08[o + r]); - } - } - else if(reg_dl >= 0xa0 && reg_dl <= 0xdf) { /* 6x8 kana */ - i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; - mem_writew(i - 2u, 0x0101u); - o = (reg_dl - 0xa0) * 8; - for(r = 0; r < 8u; r++) { - mem_writeb(i + r, pc98_katakana6x8_font[o + r]); - } - } - else { - LOG_MSG("PC-98 INT 18h AH=14h font RAM read ignored, code 0x%04x not supported",reg_dx); - } - } - break; - case 0x16: /* fill screen with chr + attr */ - { - /* DL = character - * DH = attribute */ - unsigned int i; - - for (i=0;i < 0x2000;i += 2) { - vga.mem.linear[i+0] = reg_dl; - vga.mem.linear[i+1] = 0x00; - } - for ( ;i < 0x3FE0;i += 2) { - vga.mem.linear[i+0] = reg_dh; - vga.mem.linear[i+1] = 0x00; - } - } - break; - case 0x17: /* BELL ON */ - IO_WriteB(0x37,0x06); - break; - case 0x18: /* BELL OFF */ - IO_WriteB(0x37,0x07); - break; - case 0x1A: /* load FONT RAM */ - { - /* DX = code (must be 0x76xx or 0x7700) - * BX:CX = 34-byte region to read from */ - if ((reg_dh & 0x7Eu) == 0x76u) { - unsigned int i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; - for (unsigned int r=0;r < 16u;r++) { - unsigned int o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; - - assert((o+2u) <= sizeof(vga.draw.font)); - - vga.draw.font[o+0u] = mem_readb(i+(r*2u)+0u); - vga.draw.font[o+1u] = mem_readb(i+(r*2u)+1u); - } - } - else { - LOG_MSG("PC-98 INT 18h AH=1Ah font RAM load ignored, code 0x%04x out of range",reg_dx); - } - } - break; - case 0x30: /* Set display mode */ - /* FIXME: There is still a lot that is inaccurate about this call */ - if (enable_pc98_egc) { - unsigned char b597 = mem_readb(0x597); - unsigned char tstat = mem_readb(0x53C); - unsigned char b54C = mem_readb(0x54C); - unsigned char ret = 0x05; // according to NP2 - - // assume the same as AH=42h - while (!(IO_ReadB(0x60) & 0x20/*vertical retrace*/)) { - void CALLBACK_Idle(void); - CALLBACK_Idle(); - } - - LOG_MSG("PC-98 INT 18 AH=30h AL=%02Xh BH=%02Xh",reg_al,reg_bh); - - if ((reg_bh & 0x30) == 0x30) { // 640x480 - if ((reg_al & 0xC) == 0x0C) { // 31KHz sync - void PC98_Set31KHz_480line(void); - pc98_31khz_mode = true; - PC98_Set31KHz_480line(); - - void pc98_port6A_command_write(unsigned char b); - pc98_port6A_command_write(0x69); // disable 128KB wrap - - b54C = (b54C & (~0x20)) + ((reg_al & 0x04) ? 0x20 : 0x00); - -#if defined(USE_TTF) - ttf_switch_off(false); -#endif - pc98_gdc[GDC_MASTER].force_fifo_complete(); - pc98_gdc[GDC_SLAVE].force_fifo_complete(); - - // according to real hardware, this also hides the text layer for some reason - pc98_gdc[GDC_MASTER].display_enable = false; - - /* clear PRAM, graphics */ - for (unsigned int i=0;i < 16;i++) - pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; - - /* reset scroll area of graphics */ - pc98_gdc[GDC_SLAVE].param_ram[0] = 0; - pc98_gdc[GDC_SLAVE].param_ram[1] = 0; - - pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; - pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); - pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; - - pc98_gdc[GDC_SLAVE].doublescan = false; - pc98_gdc[GDC_SLAVE].row_height = 1; - - b597 = (b597 & ~3u) + ((uint8_t)(reg_bh >> 4u) & 3u); - - pc98_gdc_vramop &= ~(1 << VOPBIT_ACCESS); - pc98_update_cpu_page_ptr(); - - GDC_display_plane = GDC_display_plane_pending = 0; - pc98_update_display_page_ptr(); - - /* based on real hardware behavior, this ALSO sets 256-color mode */ - void pc98_port6A_command_write(unsigned char b); - pc98_port6A_command_write(0x07); // enable EGC - pc98_port6A_command_write(0x01); // enable 16-color - pc98_port6A_command_write(0x21); // enable 256-color - } - else { - // according to Neko Project II, this case is ignored. - // this is confirmed on real hardware as well. - LOG_MSG("PC-98 INT 18h AH=30h attempt to set 640x480 mode with 24KHz hsync which is not supported by the platform"); - ret = 0; - } - } - else { // 640x400 or 640x200 - // TODO: A PC9821Lt2 laptop's BIOS refuses to allow 31khz except for 640x480 mode. - // Perhaps it's just a technical restriction of the LCD display. - // - // Check on other PC-98 hardware to see what the policy is for 31khz in all modes. - // That restriction would make no sense on another system I have that has a VGA - // port and a default setting of 70Hz / 31KHz 640x400. - if ((reg_al & 0x0C) < 0x08) { /* bits [3:2] == 0x */ - LOG_MSG("PC-98 INT 18h AH=30h attempt to set 15KHz hsync which is not yet supported"); - ret = 0; - } - else { - if ((reg_al ^ (((b54C & 0x20) ? 3 : 2) << 2)) & 0x0C) { /* change in bits [3:2] */ - LOG_MSG("PC-98 change in hsync frequency to %uHz",(reg_al & 0x04) ? 31 : 24); - - if (reg_al & 4) { - void PC98_Set31KHz(void); - pc98_31khz_mode = true; - PC98_Set31KHz(); - } - else { - void PC98_Set24KHz(void); - pc98_31khz_mode = false; - PC98_Set24KHz(); - } - - b54C = (b54C & (~0x20)) + ((reg_al & 0x04) ? 0x20 : 0x00); - } - } - - void pc98_port6A_command_write(unsigned char b); - pc98_port6A_command_write(0x68); // restore 128KB wrap - -#if defined(USE_TTF) - ttf_switch_off(false); -#endif - pc98_gdc[GDC_MASTER].force_fifo_complete(); - pc98_gdc[GDC_SLAVE].force_fifo_complete(); - - // 640x480 forces 256-color mode. - // the 400 line modes (this case) do not clear 256-color mode. - - // according to real hardware, this also hides the text layer for some reason - pc98_gdc[GDC_MASTER].display_enable = false; - - /* clear PRAM, graphics */ - for (unsigned int i=0;i < 16;i++) - pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; - - /* reset scroll area of graphics */ - if ((reg_bh & 0x30) == 0x10) { /* 640x200 upper half bits [5:4] == 1 */ - pc98_gdc[GDC_SLAVE].param_ram[0] = (200*40) & 0xFF; - pc98_gdc[GDC_SLAVE].param_ram[1] = (200*40) >> 8; - } - else { - pc98_gdc[GDC_SLAVE].param_ram[0] = 0; - pc98_gdc[GDC_SLAVE].param_ram[1] = 0; - } - - pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; - pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); - pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; - - if ((reg_bh & 0x20) == 0x00) { /* 640x200 */ - pc98_gdc[GDC_SLAVE].doublescan = true; - pc98_gdc[GDC_SLAVE].row_height = pc98_gdc[GDC_SLAVE].doublescan ? 2 : 1; - } - else { - pc98_gdc[GDC_SLAVE].doublescan = false; - pc98_gdc[GDC_SLAVE].row_height = 1; - } - - b597 = (b597 & ~3u) + ((uint8_t)(reg_bh >> 4u) & 3u); - - pc98_gdc_vramop &= ~(1 << VOPBIT_ACCESS); - pc98_update_cpu_page_ptr(); - - GDC_display_plane = GDC_display_plane_pending = 0; - pc98_update_display_page_ptr(); - } - - tstat &= ~(0x10 | 0x01); - if (reg_bh & 2) - tstat |= 0x10; - else if ((reg_bh & 1) == 0) - tstat |= 0x01; - - mem_writeb(0x597,b597); - mem_writeb(0x53C,tstat); - mem_writeb(0x54C,b54C); - - pc98_update_text_lineheight_from_bda(); - pc98_update_text_layer_lineheight_from_bda(); - - // according to real hardware (PC-9821Lt2), AH=5 on success (same as NP2) - // or AH is unchanged on failure and AL=1 and BH=1 (NOT the same as NP2) - if (ret == 0x05) reg_ah = ret; - reg_al = (ret == 0x05) ? 0x00 : 0x01; // according to NP2 - reg_bh = (ret == 0x05) ? 0x00 : 0x01; // according to NP2 - } - break; - case 0x31: /* Return display mode and status */ - /* NTS: According to NP II this call shouldn't even work unless you first call AH=30h to set 640x480 mode. - * It seems that is wrong. Real hardware will still return the current mode regardless. */ - if (enable_pc98_egc) { /* FIXME: INT 18h AH=31/30h availability is tied to EGC enable */ - unsigned char b597 = mem_readb(0x597); - unsigned char tstat = mem_readb(0x53C); - unsigned char b54C = mem_readb(0x54C); - - /* 54Ch: - * bit[5:5] = Horizontal sync rate 1=31.47KHz 0=24.83KHz */ - - /* Return values: - * - * AL = - * bit [7:7] = ? - * bit [6:6] = ? - * bit [5:5] = ? - * bit [4:4] = ? - * bit [3:2] = horizontal sync - * 00 = 15.98KHz - * 01 = ? - * 10 = 24.83KHz - * 11 = 31.47KHz - * bit [1:1] = ? - * bit [0:0] = interlaced (1=yes 0=no) - * BH = - * bit [7:7] = ? - * bit [6:6] = ? - * bit [5:4] = graphics video mode - * 00 = 640x200 (upper half) - * 01 = 640x200 (lower half) - * 10 = 640x400 - * 11 = 640x480 - * bit [3:3] = ? - * bit [2:2] = ? - * bit [1:0] = number of text rows - * 00 = 20 rows - * 01 = 25 rows - * 10 = 30 rows - * 11 = ? - */ - reg_al = - (((b54C & 0x20) ? 3 : 2) << 2)/*hsync*/; - reg_bh = - ((b597 & 3) << 4)/*graphics video mode*/; - if (tstat & 0x10) - reg_bh |= 2;/*30 rows*/ - else if ((tstat & 0x01) == 0) - reg_bh |= 1;/*25 rows*/ - } - break; - /* From this point on the INT 18h call list appears to wander off from the keyboard into CRT/GDC/display management. */ - case 0x40: /* Start displaying the graphics screen (グラフィック画面の表示開始) */ - pc98_gdc[GDC_SLAVE].force_fifo_complete(); - pc98_gdc[GDC_SLAVE].display_enable = true; -#if defined(USE_TTF) - if (!pc98_gdc[GDC_MASTER].display_enable) ttf_switch_off(false); -#endif - - { - unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); - mem_writeb(0x54C/*MEMB_PRXCRT*/,b | 0x80); - } - break; - case 0x41: /* Stop displaying the graphics screen (グラフィック画面の表示終了) */ - pc98_gdc[GDC_SLAVE].force_fifo_complete(); - pc98_gdc[GDC_SLAVE].display_enable = false; -#if defined(USE_TTF) - if (pc98_gdc[GDC_MASTER].display_enable) ttf_switch_on(false); -#endif - - { - unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); - mem_writeb(0x54C/*MEMB_PRXCRT*/,b & (~0x80)); - } - break; - case 0x42: /* Display area setup (表示領域の設定) */ - // HACK for Quarth: If the game has triggered vsync interrupt, wait for it. - // Quarth's vsync interrupt will reprogram the display partitions back to what - // it would have set for gameplay after this modeset and cause display problems - // with the main menu. Waiting one vertical retrace period before mode setting - // gives Quarth one last frame to reprogram partitions before realizing that - // it's time to stop it. - // - // If the BIOS on real hardware has any check like this, it's probably a loop - // to wait for vsync. - // - // The interrupt does NOT cancel the vertical retrace interrupt. Some games - // (Rusty) will not work properly if this call cancels the vertical retrace - // interrupt. - while (!(IO_ReadB(0x60) & 0x20/*vertical retrace*/)) { - void CALLBACK_Idle(void); - CALLBACK_Idle(); - } - - pc98_gdc[GDC_MASTER].force_fifo_complete(); - pc98_gdc[GDC_SLAVE].force_fifo_complete(); - - /* clear PRAM, graphics */ - for (unsigned int i=0;i < 16;i++) - pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; - - /* reset scroll area of graphics */ - if ((reg_ch & 0xC0) == 0x40) { /* 640x200 G-RAM upper half */ - pc98_gdc[GDC_SLAVE].param_ram[0] = (200*40) & 0xFF; - pc98_gdc[GDC_SLAVE].param_ram[1] = (200*40) >> 8; - } - else { - pc98_gdc[GDC_SLAVE].param_ram[0] = 0; - pc98_gdc[GDC_SLAVE].param_ram[1] = 0; - } - - pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; - pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); - pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; - - // CH - // [7:6] = G-RAM setup - // 00 = no graphics (?) - // 01 = 640x200 upper half - // 10 = 640x200 lower half - // 11 = 640x400 - // [5:5] = CRT - // 0 = color - // 1 = monochrome - // [4:4] = Display bank - - // Color or monochrome mode - IO_WriteB(0x68, (reg_ch & 0x20) ? 0x03 : 0x02); - - // FIXME: This is a guess. I have no idea as to actual behavior, yet. - // This seems to help with clearing the text layer when games start the graphics. - // This is ALSO how we will detect games that switch on the 200-line double-scan mode vs 400-line mode. - if ((reg_ch & 0xC0) != 0) { - pc98_gdc[GDC_SLAVE].doublescan = ((reg_ch & 0xC0) == 0x40) || ((reg_ch & 0xC0) == 0x80); - pc98_gdc[GDC_SLAVE].row_height = pc98_gdc[GDC_SLAVE].doublescan ? 2 : 1; - - /* update graphics mode bits */ - { - unsigned char b = mem_readb(0x597); - - b &= ~3; - b |= ((reg_ch >> 6) - 1) & 3; - - mem_writeb(0x597,b); - } - } - else { - pc98_gdc[GDC_SLAVE].doublescan = false; - pc98_gdc[GDC_SLAVE].row_height = 1; - } - - { - unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); - - // Real hardware behavior: graphics selection updated by BIOS to reflect MEMB_PRXCRT state - pc98_gdc[GDC_SLAVE].display_enable = !!(b & 0x80); -#if defined(USE_TTF) - if (pc98_gdc[GDC_SLAVE].display_enable) - ttf_switch_off(false); - else if (pc98_gdc[GDC_MASTER].display_enable) - ttf_switch_on(false); -#endif - } - - GDC_display_plane = GDC_display_plane_pending = (reg_ch & 0x10) ? 1 : 0; - pc98_update_display_page_ptr(); - - prev_pc98_mode42 = reg_ch; - - LOG_MSG("PC-98 INT 18 AH=42h CH=0x%02X",reg_ch); - break; - case 0x43: // Palette register settings? Only works in digital mode? --leonier - // - // This is said to fix Thexder's GAME ARTS logo. --Jonathan C. - // - // TODO: Validate this against real PC-98 hardware and BIOS - { - unsigned int gbcpc = SegValue(ds)*0x10u + reg_bx; - for(unsigned int i=0;i<4;i++) - { - unsigned char p=mem_readb(gbcpc+4u+i); - pc98_set_digpal_entry(7u-2u*i, p&0xFu); - pc98_set_digpal_entry(6u-2u*i, p>>4u); - } - LOG_MSG("PC-98 INT 18 AH=43h CX=0x%04X DS=0x%04X", reg_cx, SegValue(ds)); - break; - } - case 0x47: // Line, Box - case 0x48: // Arc - PC98_INT18_DrawShape(); - break; - case 0x49: // Text - PC98_INT18_DrawText(); - break; - case 0x4D: // 256-color enable - if (reg_ch == 1) { - void pc98_port6A_command_write(unsigned char b); - pc98_port6A_command_write(0x07); // enable EGC - pc98_port6A_command_write(0x01); // enable 16-color - pc98_port6A_command_write(0x21); // enable 256-color - PC98_show_cursor(false); // apparently hides the cursor? - mem_writeb(0x54D, mem_readb(0x54D) | 0x80); - } - else if (reg_ch == 0) { - void pc98_port6A_command_write(unsigned char b); - pc98_port6A_command_write(0x20); // disable 256-color - PC98_show_cursor(false); // apparently hides the cursor? - mem_writeb(0x54D, mem_readb(0x54D) & ~0x80); - } - else { - LOG_MSG("PC-98 INT 18h AH=4Dh unknown CH=%02xh",reg_ch); - } - break; - default: - LOG_MSG("PC-98 INT 18h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - break; - } - - /* FIXME: What do actual BIOSes do when faced with an unknown INT 18h call? */ - return CBRET_NONE; -} - -#define PC98_FLOPPY_HIGHDENSITY 0x01 -#define PC98_FLOPPY_2HEAD 0x02 -#define PC98_FLOPPY_RPM_3MODE 0x04 -#define PC98_FLOPPY_RPM_IBMPC 0x08 - -unsigned char PC98_BIOS_FLOPPY_BUFFER[32768]; /* 128 << 8 */ - -static unsigned int PC98_FDC_SZ_TO_BYTES(unsigned int sz) { - return 128U << sz; -} - -int PC98_BIOS_SCSI_POS(imageDisk *floppy,uint32_t §or) { - if (reg_al & 0x80) { - uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; - - floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); - - /* DL = sector - * DH = head - * CX = track */ - if (reg_dl >= img_sect || - reg_dh >= img_heads || - reg_cx >= img_cyl) { - return (reg_ah=0x60); - } - - sector = reg_cx; - sector *= img_heads; - sector += reg_dh; - sector *= img_sect; - sector += reg_dl; - -// LOG_MSG("Sector CHS %u/%u/%u -> %u (geo %u/%u/%u)",reg_cx,reg_dh,reg_dl,sector,img_cyl,img_heads,img_sect); - } - else { - /* Linear LBA addressing */ - sector = ((unsigned int)reg_dl << 16UL) + reg_cx; - /* TODO: SASI caps at 0x1FFFFF according to NP2 */ - } - - return 0; -} - -void PC98_BIOS_SCSI_CALL(void) { - uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; - uint32_t memaddr,size,ssize; - imageDisk *floppy; - unsigned int i; - uint32_t sector; - int idx; - -#if 0 - LOG_MSG("PC-98 INT 1Bh SCSI BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); -#endif - - idx = (reg_al & 0xF) + 2; - if (idx < 0 || idx >= MAX_DISK_IMAGES) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - floppy = imageDiskList[idx]; - if (floppy == NULL) { - CALLBACK_SCF(true); - reg_ah = 0x60; - return; - } - - /* FIXME: According to NPKai, command is reg_ah & 0x1F not reg_ah & 0x0F. Right? */ - - /* what to do is in the lower 4 bits of AH */ - switch (reg_ah & 0x0F) { - case 0x05: /* write */ - if (PC98_BIOS_SCSI_POS(floppy,/*&*/sector) == 0) { - floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); - assert(img_ssz != 0); - - size = reg_bx; - if (size == 0) size = 0x10000U; - memaddr = ((unsigned int)SegValue(es) << 4u) + reg_bp; - - reg_ah = 0; - CALLBACK_SCF(false); - -// LOG_MSG("WRITE memaddr=0x%lx size=0x%x sector=0x%lx ES:BP=%04x:%04X", -// (unsigned long)memaddr,(unsigned int)size,(unsigned long)sector,SegValue(es),reg_bp); - - while (size != 0) { - ssize = size; - if (ssize > img_ssz) ssize = img_ssz; - -// LOG_MSG(" ... memaddr=0x%lx ssize=0x%x sector=0x%lx", -// (unsigned long)memaddr,(unsigned int)ssize,(unsigned long)sector); - - for (i=0;i < ssize;i++) PC98_BIOS_FLOPPY_BUFFER[i] = mem_readb(memaddr+i); - - if (floppy->Write_AbsoluteSector(sector,PC98_BIOS_FLOPPY_BUFFER) != 0) { - reg_ah = 0xD0; - CALLBACK_SCF(true); - break; - } - - sector++; - size -= ssize; - memaddr += ssize; - } - } - else { - CALLBACK_SCF(true); - } - break; - case 0x06: /* read */ - if (PC98_BIOS_SCSI_POS(floppy,/*&*/sector) == 0) { - floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); - assert(img_ssz != 0); - - size = reg_bx; - if (size == 0) size = 0x10000U; - memaddr = ((unsigned int)SegValue(es) << 4u) + reg_bp; - - reg_ah = 0; - CALLBACK_SCF(false); - -// LOG_MSG("READ memaddr=0x%lx size=0x%x sector=0x%lx ES:BP=%04x:%04X", -// (unsigned long)memaddr,(unsigned int)size,(unsigned long)sector,SegValue(es),reg_bp); - - while (size != 0) { - ssize = size; - if (ssize > img_ssz) ssize = img_ssz; - -// LOG_MSG(" ... memaddr=0x%lx ssize=0x%x sector=0x%lx", -// (unsigned long)memaddr,(unsigned int)ssize,(unsigned long)sector); - - if (floppy->Read_AbsoluteSector(sector,PC98_BIOS_FLOPPY_BUFFER) == 0) { - for (i=0;i < ssize;i++) mem_writeb(memaddr+i,PC98_BIOS_FLOPPY_BUFFER[i]); - } - else { - reg_ah = 0xD0; - CALLBACK_SCF(true); - break; - } - - sector++; - size -= ssize; - memaddr += ssize; - } - } - else { - CALLBACK_SCF(true); - } - break; - case 0x03: /* according to NPKai source code: "negate ack" (cbus/scsicmd.c line 211, and 61) */ - reg_ah = 0x35; /* according to scsicmd_negate() line 61, as translated by stat2ret[] by code line 228 */ - CALLBACK_SCF(false); - // NTS: This is needed for an HDI image to boot that apparently contains FreeDOS98 - break; - case 0x07: /* unknown, always succeeds */ - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x0E: /* unknown, always fails */ - reg_ah = 0x40; - CALLBACK_SCF(true); - break; - case 0x04: /* drive status */ - if (reg_ah == 0x84) { - floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); - - reg_dl = img_sect; - reg_dh = img_heads; /* Max 16 */ - reg_cx = img_cyl; /* Max 4096 */ - reg_bx = img_ssz; - - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - } - else if (reg_ah == 0x04 || reg_ah == 0x14) { - reg_ah = 0x00; - CALLBACK_SCF(false); - } - else { - goto default_goto; - } - default: - default_goto: - LOG_MSG("PC-98 INT 1Bh unknown SCSI BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - CALLBACK_SCF(true); - break; - } -} - -void PC98_BIOS_FDC_CALL_GEO_UNPACK(unsigned int &fdc_cyl,unsigned int &fdc_head,unsigned int &fdc_sect,unsigned int &fdc_sz) { - fdc_cyl = reg_cl; - fdc_head = reg_dh; - fdc_sect = reg_dl; - fdc_sz = reg_ch; - if (fdc_sz > 8) fdc_sz = 8; -} - -/* NTS: FDC calls reset IRQ 0 timer to a specific fixed interval, - * because the real BIOS likely does the same in the act of - * controlling the floppy drive. - * - * Resetting the interval is required to prevent Ys II from - * crashing after disk swap (divide by zero/overflow) because - * Ys II reads the timer after INT 1Bh for whatever reason - * and the upper half of the timer byte later affects a divide - * by 3 in the code. */ - -void PC98_Interval_Timer_Continue(void); - -bool enable_fdc_timer_hack = false; - -void FDC_WAIT_TIMER_HACK(void) { - unsigned int v; - unsigned int c=0; - - // Explanation: - // - // Originally the FDC code here changed the timer interval back to the stock 100hz - // normally used in PC-98, to fix Ys II. However that seems to break other booter - // games that hook IRQ 0 directly and set the timer ONCE, then access the disk. - // - // For example, "Angelus" ran WAY too slow with the timer hack because it programs - // the timer to a 600hz interval and expects it to stay that way. - // - // So the new method to satisfy both games is to loop here until the timer - // count is below the maximum that would occur if the 100hz tick count were - // still in effect, even if the timer interval was reprogrammed. - // - // NTS: Writing port 0x77 to relatch the timer also seems to break games - // - // TODO: As a safety against getting stuck, perhaps PIC_FullIndex() should be used - // to break out of the loop if this runs for more than 1 second, since that - // is a sign the timer is in an odd state that will never terminate this loop. - - v = ~0U; - c = 10; - do { - void CALLBACK_Idle(void); - CALLBACK_Idle(); - - unsigned int pv = v; - - v = (unsigned int)IO_ReadB(0x71); - v |= (unsigned int)IO_ReadB(0x71) << 8u; - - if (v > pv) { - /* if the timer rolled around, we might have missed the narrow window we're watching for */ - if (--c == 0) break; - } - } while (v >= 0x60); -} - -void PC98_BIOS_FDC_CALL(unsigned int flags) { - static unsigned int fdc_cyl[2]={0,0},fdc_head[2]={0,0},fdc_sect[2]={0,0},fdc_sz[2]={0,0}; // FIXME: Rename and move out. Making "static" is a hack here. - uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; - unsigned int drive; - unsigned int status; - unsigned int size,accsize,unitsize; - unsigned long memaddr; - imageDisk *floppy; - - /* AL bits[1:0] = which floppy drive */ - if ((reg_al & 3) >= 2) { - /* This emulation only supports up to 2 floppy drives */ - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - floppy = GetINT13FloppyDrive(drive=(reg_al & 3)); - - /* what to do is in the lower 4 bits of AH */ - switch (reg_ah & 0x0F) { - /* TODO: 0x00 = seek to track (in CL) */ - /* TODO: 0x01 = test read? */ - /* TODO: 0x03 = equipment flags? */ - /* TODO: 0x04 = format detect? */ - /* TODO: 0x05 = write disk */ - /* TODO: 0x07 = recalibrate (seek to track 0) */ - /* TODO: 0x0A = Read ID */ - /* TODO: 0x0D = Format track */ - /* TODO: 0x0E = ?? */ - case 0x03: /* equipment flags update (?) */ - // TODO: Update the disk equipment flags in BDA. - // For now, make Alantia happy by returning success. - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x00: /* seek */ - /* CL = track */ - if (floppy == NULL) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - if (enable_fdc_timer_hack) { - // Hack for Ys II - FDC_WAIT_TIMER_HACK(); - } - - fdc_cyl[drive] = reg_cl; - - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x01: /* test read */ - /* AH bits[4:4] = If set, seek to track specified */ - /* CL = cylinder (track) */ - /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ - /* DL = sector number (1-based) */ - /* DH = head */ - /* BX = size (in bytes) of data to read */ - /* ES:BP = buffer to read data into */ - if (floppy == NULL) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); - - if (enable_fdc_timer_hack) { - // Hack for Ys II - FDC_WAIT_TIMER_HACK(); - } - - /* Prevent reading 1.44MB floppies using 1.2MB read commands and vice versa. - * FIXME: It seems MS-DOS 5.0 booted from a HDI image has trouble understanding - * when Drive A: (the first floppy) is a 1.44MB drive or not and fails - * because it only attempts it using 1.2MB format read commands. */ - if (flags & PC98_FLOPPY_RPM_IBMPC) { - if (img_ssz == 1024) { /* reject 1.2MB 3-mode format */ - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - } - else { - if (img_ssz == 512) { /* reject IBM PC 1.44MB format */ - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - } - - PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); - unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); - if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - size = reg_bx; - while (size > 0) { - accsize = size > unitsize ? unitsize : size; - - if (floppy->Read_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - size -= accsize; - - if (size == 0) break; - - if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { - fdc_sect[drive] = 1; - if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { - fdc_head[drive] = 0; - fdc_cyl[drive]++; - } - } - } - - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x02: /* read sectors */ - case 0x06: /* read sectors (what's the difference from 0x02?) */ - /* AH bits[4:4] = If set, seek to track specified */ - /* CL = cylinder (track) */ - /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ - /* DL = sector number (1-based) */ - /* DH = head */ - /* BX = size (in bytes) of data to read */ - /* ES:BP = buffer to read data into */ - if (floppy == NULL) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); - - if (enable_fdc_timer_hack) { - // Hack for Ys II - FDC_WAIT_TIMER_HACK(); - } - - /* Prevent reading 1.44MB floppies using 1.2MB read commands and vice versa. - * FIXME: It seems MS-DOS 5.0 booted from a HDI image has trouble understanding - * when Drive A: (the first floppy) is a 1.44MB drive or not and fails - * because it only attempts it using 1.2MB format read commands. */ - if (flags & PC98_FLOPPY_RPM_IBMPC) { - if (img_ssz == 1024) { /* reject 1.2MB 3-mode format */ - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - } - else { - if (img_ssz == 512) { /* reject IBM PC 1.44MB format */ - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - } - - PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); - unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); - if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - size = reg_bx; - memaddr = ((unsigned int)SegValue(es) << 4U) + reg_bp; - while (size > 0) { - accsize = size > unitsize ? unitsize : size; - - if (floppy->Read_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - for (unsigned int i=0;i < accsize;i++) - mem_writeb(memaddr+i,PC98_BIOS_FLOPPY_BUFFER[i]); - - memaddr += accsize; - size -= accsize; - - if (size == 0) break; - - if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { - fdc_sect[drive] = 1; - if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { - fdc_head[drive] = 0; - fdc_cyl[drive]++; - } - } - } - - /* need to clear DMA terminal count after read as BIOS would, I assume (Arsys Star Cruiser) */ - { - DmaChannel *dma = GetDMAChannel(2); - if (dma) dma->tcount = false; - } - - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x04: /* drive status */ - status = 0; - - /* TODO: bit 4 is set if write protected */ - - if (reg_al & 0x80) { /* high density */ - status |= 0x01; - } - else { /* double density */ - /* TODO: */ - status |= 0x01; - } - - if ((reg_ax & 0x8F40) == 0x8400) { - status |= 8; /* 1MB/640KB format, spindle speed for 3-mode */ - if (reg_ah & 0x40) /* DOSBox-X always supports 1.44MB */ - status |= 4; /* 1.44MB format, spindle speed for IBM PC format */ - } - - if (floppy == NULL) - status |= 0xC0; - - reg_ah = status; - CALLBACK_SCF(false); - break; - /* TODO: 0x00 = seek to track (in CL) */ - /* TODO: 0x01 = test read? */ - /* TODO: 0x03 = equipment flags? */ - /* TODO: 0x04 = format detect? */ - /* TODO: 0x05 = write disk */ - /* TODO: 0x07 = recalibrate (seek to track 0) */ - /* TODO: 0x0A = Read ID */ - /* TODO: 0x0D = Format track */ - /* TODO: 0x0E = ?? */ - case 0x05: /* write sectors */ - /* AH bits[4:4] = If set, seek to track specified */ - /* CL = cylinder (track) */ - /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ - /* DL = sector number (1-based) */ - /* DH = head */ - /* BX = size (in bytes) of data to read */ - /* ES:BP = buffer to write data from */ - if (floppy == NULL) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); - - if (enable_fdc_timer_hack) { - // Hack for Ys II - FDC_WAIT_TIMER_HACK(); - } - - /* TODO: Error if write protected */ - - PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); - unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); - if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - size = reg_bx; - memaddr = ((unsigned int)SegValue(es) << 4U) + reg_bp; - while (size > 0) { - accsize = size > unitsize ? unitsize : size; - - for (unsigned int i=0;i < accsize;i++) - PC98_BIOS_FLOPPY_BUFFER[i] = mem_readb(memaddr+i); - - if (floppy->Write_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - memaddr += accsize; - size -= accsize; - - if (size == 0) break; - - if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { - fdc_sect[drive] = 1; - if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { - fdc_head[drive] = 0; - fdc_cyl[drive]++; - } - } - } - - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x07: /* recalibrate (seek to track 0) */ - if (floppy == NULL) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - if (enable_fdc_timer_hack) { - // Hack for Ys II - FDC_WAIT_TIMER_HACK(); - } - - fdc_cyl[drive] = 0; - - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x0D: /* format track */ - if (floppy == NULL) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); - unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); - - if (enable_fdc_timer_hack) { - // Hack for Ys II - FDC_WAIT_TIMER_HACK(); - } - - LOG_MSG("WARNING: INT 1Bh FDC format track command not implemented. Formatting is faked, for now on C/H/S/sz %u/%u/%u/%u drive %c.", - (unsigned int)fdc_cyl[drive], - (unsigned int)fdc_head[drive], - (unsigned int)fdc_sect[drive], - (unsigned int)unitsize, - drive + 'A'); - - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x0A: /* read ID */ - /* NTS: PC-98 "MEGDOS" used by some games seems to rely heavily on this call to - * verify the floppy head is where it thinks it should be! */ - if (floppy == NULL) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); - - if (enable_fdc_timer_hack) { - // Hack for Ys II - FDC_WAIT_TIMER_HACK(); - } - - if (reg_ah & 0x10) { // seek to track number in CL - if (img_cyl != 0 && reg_cl >= img_cyl) { - CALLBACK_SCF(true); - reg_ah = 0x00; - /* TODO? Error code? */ - return; - } - - fdc_cyl[drive] = reg_cl; - } - - if (fdc_sect[drive] == 0) - fdc_sect[drive] = 1; - - if (img_ssz >= 1024) - fdc_sz[drive] = 3; - else if (img_ssz >= 512) - fdc_sz[drive] = 2; - else if (img_ssz >= 256) - fdc_sz[drive] = 1; - else - fdc_sz[drive] = 0; - - reg_cl = fdc_cyl[drive]; - reg_dh = fdc_head[drive]; - reg_dl = fdc_sect[drive]; - /* ^ FIXME: A more realistic emulation would return a random number from 1 to N - * where N=sectors/track because the floppy motor is running and tracks - * are moving past the head. */ - reg_ch = fdc_sz[drive]; - - /* per read ID call, increment the sector through the range on disk. - * This is REQUIRED or else MEGDOS will not attempt to read this disk. */ - if (img_sect != 0) { - if ((++fdc_sect[drive]) > img_sect) - fdc_sect[drive] = 1; - } - - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - default: - LOG_MSG("PC-98 INT 1Bh unknown FDC BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - CALLBACK_SCF(true); - break; - } -} - -static Bitu INT19_PC98_Handler(void) { - LOG_MSG("PC-98 INT 19h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - - return CBRET_NONE; -} - -static Bitu INT1A_PC98_Handler(void) { - /* HACK: This makes the "test" program in DOSLIB work. - * We'll remove this when we implement INT 1Ah */ - if (reg_ax == 0x1000) { - CALLBACK_SCF(false); - reg_ax = 0; - } - - LOG_MSG("PC-98 INT 1Ah unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - - return CBRET_NONE; -} - -static Bitu INT1B_PC98_Handler(void) { - /* As BIOS interfaces for disk I/O go, this is fairly unusual */ - switch (reg_al & 0xF0) { - /* floppy disk access */ - /* AL bits[1:0] = floppy drive number */ - /* Uses INT42 if high density, INT41 if double density */ - /* AH bits[3:0] = command */ - case 0x90: /* 1.2MB HD */ - PC98_BIOS_FDC_CALL(PC98_FLOPPY_HIGHDENSITY|PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_3MODE); - break; - case 0x30: /* 1.44MB HD (NTS: not supported until the early 1990s) */ - case 0xB0: - PC98_BIOS_FDC_CALL(PC98_FLOPPY_HIGHDENSITY|PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_IBMPC); - break; - case 0x70: /* 720KB DD (??) */ - case 0xF0: - PC98_BIOS_FDC_CALL(PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_3MODE); // FIXME, correct?? - break; - case 0x20: /* SCSI hard disk BIOS */ - case 0xA0: /* SCSI hard disk BIOS */ - case 0x00: /* SASI hard disk BIOS */ - case 0x80: /* SASI hard disk BIOS */ - PC98_BIOS_SCSI_CALL(); - break; - /* TODO: Other disk formats */ - /* TODO: Future SASI/SCSI BIOS emulation for hard disk images */ - default: - LOG_MSG("PC-98 INT 1Bh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - CALLBACK_SCF(true); - break; - } - - return CBRET_NONE; -} - -void PC98_Interval_Timer_Continue(void) { - /* assume: interrupts are disabled */ - IO_WriteB(0x71,0x00); - // TODO: What time interval is this supposed to be? - if (PIT_TICK_RATE == PIT_TICK_RATE_PC98_8MHZ) - IO_WriteB(0x71,0x4E); - else - IO_WriteB(0x71,0x60); - - IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/0u))); // unmask IRQ0 -} - -unsigned char pc98_dec2bcd(unsigned char c) { - return ((c / 10u) << 4u) + (c % 10u); -} - -static Bitu INT1C_PC98_Handler(void) { - if (reg_ah == 0x00) { /* get time and date */ - time_t curtime; - const struct tm *loctime; - curtime = time (NULL); - loctime = localtime (&curtime); - - unsigned char tmp[6]; - - tmp[0] = pc98_dec2bcd((unsigned int)loctime->tm_year % 100u); - tmp[1] = (((unsigned int)loctime->tm_mon + 1u) << 4u) + (unsigned int)loctime->tm_wday; - tmp[2] = pc98_dec2bcd(loctime->tm_mday); - tmp[3] = pc98_dec2bcd(loctime->tm_hour); - tmp[4] = pc98_dec2bcd(loctime->tm_min); - tmp[5] = pc98_dec2bcd(loctime->tm_sec); - - unsigned long mem = ((unsigned int)SegValue(es) << 4u) + reg_bx; - - for (unsigned int i=0;i < 6;i++) - mem_writeb(mem+i,tmp[i]); - } - else if (reg_ah == 0x02) { /* set interval timer (single event) */ - /* es:bx = interrupt handler to execute - * cx = timer interval in ticks (FIXME: what units of time?) */ - mem_writew(0x1C,reg_bx); - mem_writew(0x1E,SegValue(es)); - mem_writew(0x58A,reg_cx); - - IO_WriteB(0x77,0x36); /* mode 3, binary, low-byte high-byte 16-bit counter */ - - PC98_Interval_Timer_Continue(); - } - else if (reg_ah == 0x03) { /* continue interval timer */ - PC98_Interval_Timer_Continue(); - } - /* TODO: According to the PDF at - * - * http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20NEC%20PC%2d98/Collections/PC%2d9801%20Bible%20%e6%9d%b1%e4%ba%ac%e7%90%86%e7%a7%91%e5%a4%a7%e5%ad%a6EIC%20%281994%29%2epdf - * - * There are additional functions - * - * AH = 04h - * ES:BX = ? - * - * --- - * - * AH = 05h - * ES:BX = ? - * - * --- - * - * AH = 06h - * CX = ? (1-FFFFh) - * DX = ? (20h-8000h Hz) - * - * If any PC-98 games or applications rely on this, let me know. Adding a case for them is easy enough if anyone is interested. --J.C. - */ - else { - LOG_MSG("PC-98 INT 1Ch unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - } - - return CBRET_NONE; -} - -// NTS: According to this PDF, chapter 5, INT 1Dh has additional functions on "High Resolution" PC-98 systems. -// [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] -static Bitu INT1D_PC98_Handler(void) { - LOG_MSG("PC-98 INT 1Dh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - - return CBRET_NONE; -} - -static Bitu INT1E_PC98_Handler(void) { - LOG_MSG("PC-98 INT 1Eh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - - return CBRET_NONE; -} - -void PC98_EXTMEMCPY(void) { - bool enabled = MEM_A20_Enabled(); - MEM_A20_Enable(true); - - Bitu bytes = ((reg_cx - 1u) & 0xFFFFu) + 1u; // bytes, except that 0 == 64KB - PhysPt data = SegPhys(es)+reg_bx; - PhysPt source = (mem_readd(data + 0x12u) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data + 0x17u) << 24u) + reg_si; - PhysPt dest = (mem_readd(data + 0x1Au) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data + 0x1Fu) << 24u) + reg_di; - - LOG_MSG("PC-98 memcpy: src=0x%x dst=0x%x data=0x%x count=0x%x", - (unsigned int)source,(unsigned int)dest,(unsigned int)data,(unsigned int)bytes); - - MEM_BlockCopy(dest,source,bytes); - MEM_A20_Enable(enabled); - Segs.limit[cs] = 0xFFFF; - Segs.limit[ds] = 0xFFFF; - Segs.limit[es] = 0xFFFF; - Segs.limit[ss] = 0xFFFF; - - CALLBACK_SCF(false); -} - -static Bitu INT1F_PC98_Handler(void) { - switch (reg_ah) { - case 0x90: - /* Copy extended memory */ - PC98_EXTMEMCPY(); - break; - default: - LOG_MSG("PC-98 INT 1Fh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - CALLBACK_SCF(true); - break; - } - - return CBRET_NONE; -} - -static Bitu INTGEN_PC98_Handler(void) { - LOG_MSG("PC-98 INT stub unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - - return CBRET_NONE; -} - -/* This interrupt should only exist while the DOS kernel is active. - * On actual PC-98 MS-DOS this is a direct interface to MS-DOS's built-in ANSI CON driver. - * - * CL = major function call number - * AH = minor function call number - * DX = data?? */ - -void PC98_INTDC_WriteChar(unsigned char b); - -void INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut_def &def,const Bitu ofs) { - unsigned int i; - - for (i=0;i < 0x0F;i++) - def.shortcut[i] = mem_readb(ofs+0x0+i); - - for (i=0;i < 0x0F && def.shortcut[i] != 0;) i++; - def.length = i; -} - -void INTDC_STORE_FUNCDEC(const Bitu ofs,const pc98_func_key_shortcut_def &def) { - for (unsigned int i=0;i < 0x0F;i++) mem_writeb(ofs+0x0+i,def.shortcut[i]); - mem_writeb(ofs+0xF,0); -} - -void INTDC_LOAD_EDITDEC(pc98_func_key_shortcut_def &def,const Bitu ofs) { - unsigned int i; - - for (i=0;i < 0x05;i++) - def.shortcut[i] = mem_readb(ofs+0x0+i); - - for (i=0;i < 0x05 && def.shortcut[i] != 0;) i++; - def.length = i; -} - -void INTDC_STORE_EDITDEC(const Bitu ofs,const pc98_func_key_shortcut_def &def) { - for (unsigned int i=0;i < 0x05;i++) mem_writeb(ofs+0x0+i,def.shortcut[i]); - mem_writeb(ofs+0x5,0); -} - -bool inhibited_ControlFn(void) { - return real_readb(0x60,0x10C) & 0x01; -} - -static const char *fneditkeys[11] = { - "ROLLUP", - "ROLLDOWN", - "INS", - "DEL", - "UPARROW", - "LEFTARROW", - "RIGHTARROW", - "DOWNARROW", - "HOMECLR", - "HELP", - "KEYPAD-" -}; - -void DEBUG_INTDC_FnKeyMapInfo(void) { - if (!IS_PC98_ARCH) { - DEBUG_ShowMsg("INT DCh has no meaning except in PC-98 mode"); - } - else if (dos_kernel_disabled) { - DEBUG_ShowMsg("INT DCh FnKey mapping has no meaning outside the DOS environment"); - } - else { - DEBUG_ShowMsg("INT DCh FnKey mapping. Ctrl+Fn builtin inhibited=%s",inhibited_ControlFn()?"yes":"no"); - for (unsigned int i=0;i < 10;i++) - DEBUG_ShowMsg(" F%u: %s",i+1,pc98_func_key[i].debugToString().c_str()); - for (unsigned int i=0;i < 5;i++) - DEBUG_ShowMsg(" VF%u: %s",i+1,pc98_vfunc_key[i].debugToString().c_str()); - - for (unsigned int i=0;i < 10;i++) - DEBUG_ShowMsg(" Shift+F%u: %s",i+1,pc98_func_key_shortcut[i].debugToString().c_str()); - for (unsigned int i=0;i < 5;i++) - DEBUG_ShowMsg(" Shift+VF%u: %s",i+1,pc98_vfunc_key_shortcut[i].debugToString().c_str()); - - for (unsigned int i=0;i < 10;i++) - DEBUG_ShowMsg(" Control+F%u: %s",i+1,pc98_func_key_ctrl[i].debugToString().c_str()); - for (unsigned int i=0;i < 5;i++) - DEBUG_ShowMsg(" Control+VF%u: %s",i+1,pc98_vfunc_key_ctrl[i].debugToString().c_str()); - - for (unsigned int i=0;i < 11;i++) - DEBUG_ShowMsg(" %s: %s",fneditkeys[i],pc98_editor_key_escapes[i].debugToString().c_str()); - } -} - -/* PC-98 application notes, that are NOT DOSBox-X bugs because they occur on real MS-DOS as well: - * - * VZ.COM - If the function key row was hidden when VZ.COM is started, VZ.COM will not restore the - * function key row. VZ.COM's function key shortcuts affect Fn and Shift+Fn keys and the - * text they display even if VZ.COM also disables the Ctrl+F7 shortcut that lets you - * toggle the function key row, which makes displaying the Shift+Fn key shortcuts impossible - * unless the function key row was left showing that at startup. - */ - -static Bitu INTDC_PC98_Handler(void) { - if (dos_kernel_disabled) goto unknown; - - switch (reg_cl) { - /* Tracking implementation according to [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20NEC%20PC%2d98/Collections/Undocumented%209801%2c%209821%20Volume%201%20English%20translation/INTDC%2eTXT] */ - case 0x0C: /* CL=0x0C General entry point to read function key state */ -/*=================================================================================================== -Table [List of key specification values and corresponding keys] - ------------------------+--------------------------------------------------- - Key specification value | Corresponding key - ------------------------+--------------------------------------------------- - 0000h | [f・1] to [f・10], [SHIFT] + [f・1] to [SHIFT] + [f・10], - | [ROLL UP], [ROLL DOWN], [INS], [DEL], [↑], [←], [→], [↓], - | [HOME/CLR], [HELP], [SHIFT] + [HOME/CLR] - 0001 to 000Ah | [f・1] to [f・10] - 000B to 0014h | [SHIFT] + [f・1] to [SHIFT] + [f・10] - 0015h | [ROLL UP] - 0016h | [ROLL DOWN] - 0017h | [INS] - 0018h | [DEL] - 0019h | [↑] - 001Ah | [←] - 001Bh | [→] - 001Ch | [↓] - 001Dh | [HOME/CLR](XA keyboard:[CLR]) - 001Eh | [HELP] - 001Fh | [SHIFT]+[HOME/CLR](XA keyboard:[HOME]) - 0020-0024h | [vf・1]-[vf・5] - 0025-0029h | [SHIFT]+[vf・1]-[vf・5] - 002A-0033h | [CTRL]+[f・1]-[f・10] - 0034-0038h | [CTRL]+[vf・1]-[vf・5] - 0039h | [CTRL]+[XFER]/[NFER] (Undocumented) - 003Ah | [CTRL]+[XFER]/[NFER],[CTRL]+[f・1]~[f・10] - | (Undocumented) - 00FFh | [f・1]〜[f・10],[vf・1]〜[vf・5], - | [SHIFT]+[f・1]〜[SHIFT]+[f・10],[SHIFT]+[vf・1]〜[vf・5], - | [ROLL UP],[ROLL DOWN],[INS],[DEL],[↑],[←],[→],[↓], - | [HOME/CLR],[HELP],[SHIFT]+[HOME/CLR], - | [CTRL]+[f・1] to [f・10], [CTRL]+[vf・1] to [vf・5] - ------------------------+--------------------------------------------------- - Table [Supported range of key specification values for each MS-DOS version] - ------------------------+---+---+---+---+---+---+---+---+-----+ - Key specification value | MS-DOS version (PS98-XXX) - |111|121|122|123|125|127|129|011|XA125 - ------------------------+---+---+---+---+---+---+---+---+-----+ - 0000 to 001Fh | ○ | ○ | ○ | ○ | ○ | ○ | ○ | ○ | ○ - 0020 to 0029h | × | × | × | × | × | × | × | ○ | ○ - 002A-0033h | × | × | × | × | ○ | ○ | ○ | ○ | △ - 0034-0038h | × | × | × | × | × | × | × | ○ | △ - 0039h | × | × | × | × | × | ○ | ○ | ○ | × - 003Ah | × | × | × | × | ○ | ○ | ○ | ○ | × - 00FFh | × | × | × | × | × | × | × | ○ | ○ - ------------------------+---+---+---+---+---+---+---+---+-----+ - * PC-98LT/HA is the same as PS98-127. - * MS-DOS 3.3(all), 5.0, 5.0A is the same as PS98-011. - * For the PS98-XA125 triangle mark, the keys are as follows. - Key values 002B to 0033h specify [CTRL]+[f・1] to [f・9]. - Key values 0035 to 0038h specify [CTRL]+[vf・1] to [vf・4]. -=============================================================================================== - * NTS: According to a translation table in the MS-DOS kernel, where - * AX=1h to AX=29h inclusive look up from this 0x29-element table: - * - * Table starts with AX=1h, ends with AX=29h - * - * 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 - * | | | | | | | | | | | | | | | | - * 0ADC:00003DE0 01 02 03 04 05 06 07 08 09 0A 10 11 12 13 14 15 ................ - * 0ADC:00003DF0 16 17 18 19 1F 20 21 22 23 24 25 26 27 28 29 0B ..... !"#$%&'(). - * 0ADC:00003E00 0C 0D 0E 0F 1A 1B 1C 1D 1E| - * - * The table is read, then the byte is decremented by one. - * - * If the result of that is less than 0x1E, it's an index into - * the 16 byte/entry Fn key table. - * - * If the result is 0x1E or larger, then (result - 0x1E) is an - * index into the editor table, 8 bytes/entry. - * - * Meanings: - * - * 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 - * | | | | | | | | | | | | | | | | - * 0ADC:00003DE0 01 02 03 04 05 06 07 08 09 0A 10 11 12 13 14 15 ................ - * | --- Function keys F1-F10 ---| Fn shift F1-F6 - - * 0ADC:00003DF0 16 17 18 19 1F 20 21 22 23 24 25 26 27 28 29 0B ..... !"#$%&'(). - * | Sh F7-F10 | ------- EDITOR KEYS -----------| - - * 0ADC:00003E00 0C 0D 0E 0F 1A 1B 1C 1D 1E| - * | --------- | ------------ | -===============================================================================================*/ - if (reg_ax == 0x00) { /* Read all state, DS:DX = data to store to */ -/*============================================================================================= - DS:DX contains +extern bool ega200; + +unsigned char ACPI_ENABLE_CMD = 0xA1; +unsigned char ACPI_DISABLE_CMD = 0xA0; +unsigned int ACPI_IO_BASE = 0x820; +unsigned int ACPI_PM1A_EVT_BLK = 0x820; +unsigned int ACPI_PM1A_CNT_BLK = 0x824; +unsigned int ACPI_PM_TMR_BLK = 0x830; +/* debug region 0x840-0x84F */ +unsigned int ACPI_DEBUG_IO = 0x840; + +std::string ibm_rom_basic; +size_t ibm_rom_basic_size = 0; +uint32_t ibm_rom_basic_base = 0; + +/* NTS: The "Epson check" code in Windows 2.1 only compares up to the end of "NEC Corporation" */ +const std::string pc98_copyright_str = "Copyright (C) 1983 by NEC Corporation / Microsoft Corp.\x0D\x0A"; + +/* more strange data involved in the "Epson check" */ +const unsigned char pc98_epson_check_2[0x27] = { + 0x26,0x8A,0x05,0xA8,0x10,0x75,0x11,0xC6,0x06,0xD6,0x09,0x1B,0xC6,0x06,0xD7,0x09, + 0x4B,0xC6,0x06,0xD8,0x09,0x48,0xEB,0x0F,0xC6,0x06,0xD6,0x09,0x1A,0xC6,0x06,0xD7 , + 0x09,0x70,0xC6,0x06,0xD8,0x09,0x71 +}; + +bool enable_pc98_copyright_string = false; + +/* mouse.cpp */ +extern bool pc98_40col_text; +extern bool en_bios_ps2mouse; +extern bool rom_bios_8x8_cga_font; +extern bool pcibus_enable; +extern bool enable_fpu; + +bool pc98_timestamp5c = true; // port 5ch and 5eh "time stamp/hardware wait" + +uint32_t Keyb_ig_status(); +bool VM_Boot_DOSBox_Kernel(); +Bitu bios_post_parport_count(); +Bitu bios_post_comport_count(); +void pc98_update_cpu_page_ptr(void); +bool KEYBOARD_Report_BIOS_PS2Mouse(); +bool gdc_5mhz_according_to_bios(void); +void pc98_update_display_page_ptr(void); +void pc98_update_palette(void); +bool MEM_map_ROM_alias_physmem(Bitu start,Bitu end); +void MOUSE_Startup(Section *sec); +void Mouse_PS2SetSamplingRate(uint8_t rate); +bool Mouse_PS2SetPacketSize(uint8_t packet_size); +void change_output(int output); +void runBoot(const char *str); +void SetIMPosition(void); +bool isDBCSCP(); +Bitu INT60_Handler(void); +Bitu INT6F_Handler(void); +#if defined(USE_TTF) +void ttf_switch_on(bool ss), ttf_switch_off(bool ss), ttf_setlines(int cols, int lins); +#endif + +/* Rate limit log entries regarding APM AH=05h CPU IDLE because Windows 98's APM driver likes to call it way too much per second */ +pic_tickindex_t APM_log_cpu_idle_next_report = 0; +unsigned long APM_log_cpu_idle = 0; + +unsigned long APM_WakeupKeys = 0; + +/* APM events (eventually ACPI as well) */ +unsigned long PowerButtonClicks = 0; +bool APM_ResumeNotificationFromSuspend = false; +bool APM_ResumeNotificationFromStandby = false; +bool APM_PowerButtonSendsSuspend = true; + + +bool bochs_port_e9 = false; +bool isa_memory_hole_512kb = false; +bool isa_memory_hole_15mb = false; +bool int15_wait_force_unmask_irq = false; + +int unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; + +unsigned int reset_post_delay = 0; + +Bitu call_irq_default = 0; +uint16_t biosConfigSeg=0; + +static constexpr unsigned int ACPI_PMTIMER_CLOCK_RATE = 3579545; /* 3.579545MHz */ + +pic_tickindex_t ACPI_PMTIMER_BASE_TIME = 0; +uint32_t ACPI_PMTIMER_BASE_COUNT = 0; +uint32_t ACPI_PMTIMER_MASK = 0xFFFFFFu; /* 24-bit mode */ + +uint32_t ACPI_PMTIMER(void) { + pic_tickindex_t pt = PIC_FullIndex() - ACPI_PMTIMER_BASE_TIME; + uint32_t ct = (uint32_t)((pt * ACPI_PMTIMER_CLOCK_RATE) / 1000.0); + return ct; +} + +void ACPI_PMTIMER_Event(Bitu /*val*/); +void ACPI_PMTIMER_ScheduleNext(void) { + const uint32_t now_ct = ACPI_PMTIMER() & ACPI_PMTIMER_MASK; + const uint32_t next_delay_ct = (ACPI_PMTIMER_MASK + 1u) - now_ct; + const pic_tickindex_t delay = (1000.0 * next_delay_ct) / (pic_tickindex_t)ACPI_PMTIMER_CLOCK_RATE; + + LOG(LOG_MISC,LOG_DEBUG)("ACPI PM TIMER SCHEDULE: now=0x%x next=0x%x delay=%.3f",now_ct,next_delay_ct,(double)delay); + PIC_AddEvent(ACPI_PMTIMER_Event,delay); +} + +void ACPI_PMTIMER_CHECK(void) { /* please don't call this often */ + PIC_RemoveEvents(ACPI_PMTIMER_Event); + LOG(LOG_MISC,LOG_DEBUG)("ACPI PM TIMER CHECK"); + ACPI_PMTIMER_ScheduleNext(); +} + +Bitu BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION = ~0u; +Bitu BIOS_DEFAULT_IRQ0_LOCATION = ~0u; // (RealMake(0xf000,0xfea5)) +Bitu BIOS_DEFAULT_IRQ1_LOCATION = ~0u; // (RealMake(0xf000,0xe987)) +Bitu BIOS_DEFAULT_IRQ07_DEF_LOCATION = ~0u; // (RealMake(0xf000,0xff55)) +Bitu BIOS_DEFAULT_IRQ815_DEF_LOCATION = ~0u; // (RealMake(0xf000,0xe880)) + +Bitu BIOS_DEFAULT_HANDLER_LOCATION = ~0u; // (RealMake(0xf000,0xff53)) +Bitu BIOS_DEFAULT_INT5_LOCATION = ~0u; // (RealMake(0xf000,0xff54)) + +Bitu BIOS_VIDEO_TABLE_LOCATION = ~0u; // RealMake(0xf000,0xf0a4) +Bitu BIOS_VIDEO_TABLE_SIZE = 0u; + +Bitu BIOS_DEFAULT_RESET_LOCATION = ~0u; // RealMake(0xf000,0xe05b) +Bitu BIOS_DEFAULT_RESET_CODE_LOCATION = ~0u; + +bool allow_more_than_640kb = false; + +unsigned int APM_BIOS_connected_minor_version = 0;// what version the OS connected to us with. default to 1.0 +unsigned int APM_BIOS_minor_version = 2; // what version to emulate e.g to emulate 1.2 set this to 2 + +static bool apm_realmode_connected = false; + +/* default bios type/version/date strings */ +const char* const bios_type_string = "IBM COMPATIBLE BIOS for DOSBox-X"; +const char* const bios_version_string = "DOSBox-X BIOS v1.0"; +const char* const bios_date_string = "01/01/92"; + +bool APM_inactivity_timer = true; + +RegionAllocTracking rombios_alloc; + +Bitu rombios_minimum_location = 0xF0000; /* minimum segment allowed */ +Bitu rombios_minimum_size = 0x10000; + +static bool ACPI_SCI_EN = false; +static bool ACPI_BM_RLD = false; + +static IO_Callout_t acpi_iocallout = IO_Callout_t_none; + +static unsigned int ACPI_PM1_Enable = 0; +static unsigned int ACPI_PM1_Status = 0; +static constexpr unsigned int ACPI_PM1_Enable_TMR_EN = (1u << 0u); +static constexpr unsigned int ACPI_PM1_Enable_GBL_EN = (1u << 5u); +static constexpr unsigned int ACPI_PM1_Enable_PWRBTN_EN = (1u << 8u); +static constexpr unsigned int ACPI_PM1_Enable_SLPBTN_EN = (1u << 9u); +static constexpr unsigned int ACPI_PM1_Enable_RTC_EN = (1u << 10u); + +unsigned int ACPI_buffer_global_lock = 0; + +unsigned long ACPI_FACS_GlobalLockValue(void) { + if (ACPI_buffer && ACPI_buffer_global_lock != 0) + return host_readd(ACPI_buffer+ACPI_buffer_global_lock); + + return 0; +} + +/* Triggered by GBL_RLS bit */ +static void ACPI_OnGuestGlobalRelease(void) { + LOG(LOG_MISC,LOG_DEBUG)("ACPI GBL_RLS event. Global lock = %lx",ACPI_FACS_GlobalLockValue()); +} + +bool ACPI_GuestEnabled(void) { + return ACPI_SCI_EN; +} + +static void ACPI_SCI_Check(void) { + if (ACPI_SCI_EN) { + if (ACPI_PM1_Status & ACPI_PM1_Enable) { + LOG(LOG_MISC,LOG_DEBUG)("ACPI SCI interrupt"); + PIC_ActivateIRQ(ACPI_IRQ); + } + } +} + +void ACPI_PowerButtonEvent(void) { + if (ACPI_SCI_EN) { + if (!(ACPI_PM1_Status & ACPI_PM1_Enable_PWRBTN_EN)) { + ACPI_PM1_Status |= ACPI_PM1_Enable_PWRBTN_EN; + ACPI_SCI_Check(); + } + } +} + +void ACPI_PMTIMER_Event(Bitu /*val*/) { + if (!(ACPI_PM1_Status & ACPI_PM1_Enable_TMR_EN)) { + ACPI_PM1_Status |= ACPI_PM1_Enable_TMR_EN; + ACPI_SCI_Check(); + } + + ACPI_PMTIMER_ScheduleNext(); +} + +/* you can't very well write strings with this, but you could write codes */ +static void acpi_cb_port_debug_w(Bitu /*port*/,Bitu val,Bitu /*iolen*/) { + LOG(LOG_MISC,LOG_DEBUG)("ACPI debug: 0x%x\n",(unsigned int)val); +} + +static void acpi_cb_port_smi_cmd_w(Bitu /*port*/,Bitu val,Bitu /*iolen*/) { + /* 8-bit SMI_CMD port */ + LOG(LOG_MISC,LOG_DEBUG)("ACPI SMI_CMD %x",(unsigned int)val); + + if (val == ACPI_ENABLE_CMD) { + if (!ACPI_SCI_EN) { + LOG(LOG_MISC,LOG_DEBUG)("Guest enabled ACPI"); + ACPI_SCI_EN = true; + ACPI_PMTIMER_CHECK(); + ACPI_SCI_Check(); + } + } + else if (val == ACPI_DISABLE_CMD) { + if (ACPI_SCI_EN) { + LOG(LOG_MISC,LOG_DEBUG)("Guest disabled ACPI"); + ACPI_PMTIMER_CHECK(); + ACPI_SCI_EN = false; + } + } +} + +static Bitu acpi_cb_port_cnt_blk_r(Bitu port,Bitu /*iolen*/) { + /* 16-bit register (PM1_CNT_LEN == 2) */ + Bitu ret = 0; + if (ACPI_SCI_EN) ret |= (1u << 0u); + if (ACPI_BM_RLD) ret |= (1u << 1u); + /* GBL_RLS is write only */ + /* TODO: bits 3-8 are "reserved by the ACPI driver"? So are they writeable then? */ + /* TODO: SLP_TYPx */ + /* SLP_EN is write-only */ + + LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_CNT_BLK read port %x ret %x",(unsigned int)port,(unsigned int)ret); + return ret; +} + +static void acpi_cb_port_cnt_blk_w(Bitu port,Bitu val,Bitu iolen) { + /* 16-bit register (PM1_CNT_LEN == 2) */ + LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_CNT_BLK write port %x val %x iolen %x",(unsigned int)port,(unsigned int)val,(unsigned int)iolen); + + /* BIOS controls SCI_EN and therefore guest cannot change it */ + ACPI_BM_RLD = !!(val & (1u << 1u)); + /* GLB_RLS is write only and triggers an SMI interrupt to pass execution to the BIOS, usually to indicate a release of the global lock and set of pending bit */ + if (val & (1u << 2u)/*GBL_RLS*/) ACPI_OnGuestGlobalRelease(); + /* TODO: bits 3-8 are "reserved by the ACPI driver"? So are they writeable then? */ + /* TODO: SLP_TYPx */ + /* SLP_EN is write-only */ +} + +static Bitu acpi_cb_port_evtst_blk_r(Bitu port,Bitu /*iolen*/) { + /* 16-bit register (PM1_EVT_LEN/2 == 2) */ + Bitu ret = ACPI_PM1_Status; + LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_EVT_BLK(status) read port %x ret %x",(unsigned int)port,(unsigned int)ret); + return ret; +} + +static void acpi_cb_port_evtst_blk_w(Bitu port,Bitu val,Bitu iolen) { + /* 16-bit register (PM1_EVT_LEN/2 == 2) */ + LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_EVT_BLK(status) write port %x val %x iolen %x",(unsigned int)port,(unsigned int)val,(unsigned int)iolen); + ACPI_PM1_Status &= (~val); + ACPI_SCI_Check(); +} + +static Bitu acpi_cb_port_evten_blk_r(Bitu port,Bitu /*iolen*/) { + /* 16-bit register (PM1_EVT_LEN/2 == 2) */ + Bitu ret = ACPI_PM1_Enable; + LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_EVT_BLK(enable) read port %x ret %x",(unsigned int)port,(unsigned int)ret); + return ret; +} + +static Bitu acpi_cb_port_tmr_r(Bitu port,Bitu /*iolen*/) { + /* 24 or 32-bit TMR_VAL (depends on the mask value and whether our ACPI structures tell the OS it's 32-bit wide) */ + Bitu ret = (Bitu)ACPI_PMTIMER(); + LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM_TMR read port %x ret %x",(unsigned int)port,(unsigned int)ret); + return ret; +} + +static void acpi_cb_port_evten_blk_w(Bitu port,Bitu val,Bitu iolen) { + /* 16-bit register (PM1_EVT_LEN/2 == 2) */ + LOG(LOG_MISC,LOG_DEBUG)("ACPI_PM1_EVT_BLK(enable) write port %x val %x iolen %x",(unsigned int)port,(unsigned int)val,(unsigned int)iolen); + ACPI_PM1_Enable = val; + ACPI_SCI_Check(); +} + +static IO_ReadHandler* acpi_cb_port_r(IO_CalloutObject &co,Bitu port,Bitu iolen) { + (void)co; + (void)iolen; + + if ((port & (~1u)) == (ACPI_PM1A_EVT_BLK+0) && iolen >= 2) + return acpi_cb_port_evtst_blk_r; + else if ((port & (~1u)) == (ACPI_PM1A_EVT_BLK+2) && iolen >= 2) + return acpi_cb_port_evten_blk_r; + else if ((port & (~1u)) == ACPI_PM1A_CNT_BLK && iolen >= 2) + return acpi_cb_port_cnt_blk_r; + /* The ACPI specification says nothing about reading SMI_CMD so assume that means write only */ + else if ((port & (~3u)) == ACPI_PM_TMR_BLK && iolen >= 4) + return acpi_cb_port_tmr_r; + + return NULL; +} + +static IO_WriteHandler* acpi_cb_port_w(IO_CalloutObject &co,Bitu port,Bitu iolen) { + (void)co; + (void)iolen; + + if ((port & (~1u)) == (ACPI_PM1A_EVT_BLK+0) && iolen >= 2) + return acpi_cb_port_evtst_blk_w; + else if ((port & (~1u)) == (ACPI_PM1A_EVT_BLK+2) && iolen >= 2) + return acpi_cb_port_evten_blk_w; + else if ((port & (~1u)) == ACPI_PM1A_CNT_BLK && iolen >= 2) + return acpi_cb_port_cnt_blk_w; + else if ((port & (~3u)) == ACPI_SMI_CMD) + return acpi_cb_port_smi_cmd_w; + else if (port == ACPI_DEBUG_IO && iolen >= 4) + return acpi_cb_port_debug_w; + else if ((port & (~3u)) == ACPI_PM_TMR_BLK) { + LOG(LOG_MISC,LOG_DEBUG)("write ACPI_PM_TMR_BLK port=0x%x iolen=%u",(unsigned int)port,(unsigned int)iolen); + } + + return NULL; +} + +bool MEM_map_ROM_physmem(Bitu start,Bitu end); +bool MEM_unmap_physmem(Bitu start,Bitu end); + +static std::string bochs_port_e9_line; + +static void bochs_port_e9_flush() { + if (!bochs_port_e9_line.empty()) { + LOG_MSG("Bochs port E9h: %s",bochs_port_e9_line.c_str()); + bochs_port_e9_line.clear(); + } +} + +void bochs_port_e9_write(Bitu port,Bitu val,Bitu /*iolen*/) { + (void)port;//UNUSED + if (val == '\n' || val == '\r') { + bochs_port_e9_flush(); + } + else { + bochs_port_e9_line += (char)val; + if (bochs_port_e9_line.length() >= 256) + bochs_port_e9_flush(); + } +} + +LoopHandler *DOSBOX_GetLoop(void); + +static Bitu APM_SuspendedLoopFunc(void); + +static RealPt APM_SuspendedLoopRptr=0; + +/* "wakeup" keys were pressed and released */ +void APM_Suspend_Wakeup_Key(void) { + APM_WakeupKeys++; +} + +void APM_SuspendedLoopLeaveState() { + APM_WakeupKeys = 0; + PowerButtonClicks = 0; + + /* Turn on the VGA display, assuming it was on when suspended */ + if (IS_VGA_ARCH) { + Bitu crtc; + Bitu tmp; + + IO_Write(0x3C4,0x01); // clocking mode + tmp = IO_Read(0x3C5); + IO_Write(0x3C5,tmp & (~0x20)); // turn on screen + + // NTS: vga_crtc.cpp/vga_draw.cpp does not emulate blanking the display upon disabling sync signals + crtc = (IO_Read(0x3CC) & 1) ? 0x3D4 : 0x3B4; + IO_Write(crtc,0x17); // mode control + tmp = IO_Read(crtc+1); + IO_Write(crtc+1,tmp | 0x80); // enable sync + } +} + +/* callback for APM suspended loop routine in BIOS */ +static Bitu APM_SuspendedLoopFunc(void) { + if (APM_WakeupKeys != 0 || PowerButtonClicks != 0) { + APM_SuspendedLoopLeaveState(); + LOG_MSG("APM: leaving suspended state"); + reg_eip += 3; /* skip over HLT+JMP to get to RET */ + return CBRET_NONE; + } + + return CBRET_NONE; +} + +bool PowerManagementEnabledButton() { + if (IS_PC98_ARCH) /* power management not yet known or implemented */ + return false; + + if (ACPI_GuestEnabled()) + ACPI_PowerButtonEvent(); + + if (apm_realmode_connected) /* guest has connected to the APM BIOS */ + return true; + + return false; +} + +void APM_BeginSuspendedMode(void) { + /* Enable interrupts, dumbass. We use HLT here. */ + CPU_STI(); + + /* WARNING: This assumes, like all callbacks, that they reside in the same segment. + * The APM BIOS entry point can be called from real mode, 16-bit or 32-bit protected mode, + * therefore this code cannot assume any particular segment value and can only safely + * change reg_(e)ip to direct CPU execution. The most likely scenario is that the + * return address pushed here will point at the IRET in the INT 15 handler. */ + if (cpu.stack.big) CPU_Push32(reg_eip); + else CPU_Push16(reg_ip); + + reg_ip = APM_SuspendedLoopRptr & 0xFFFF; /* offset only */ + + /* reset counters */ + PowerButtonClicks = 0; + APM_WakeupKeys = 0; + + /* Turn off the VGA display */ + if (IS_VGA_ARCH) { + Bitu crtc; + Bitu tmp; + + IO_Write(0x3C4,0x01); // clocking mode + tmp = IO_Read(0x3C5); + IO_Write(0x3C5,tmp | 0x20); // turn off screen + + // NTS: vga_crtc.cpp/vga_draw.cpp does not emulate blanking the display upon disabling sync signals + crtc = (IO_Read(0x3CC) & 1) ? 0x3D4 : 0x3B4; + IO_Write(crtc,0x17); // mode control + tmp = IO_Read(crtc+1); + IO_Write(crtc+1,tmp & (~0x80)); // disable sync + } + + LOG_MSG("System is now in APM suspend mode"); +} + + +void ROMBIOS_DumpMemory() { + rombios_alloc.logDump(); +} + +void ROMBIOS_SanityCheck() { + rombios_alloc.sanityCheck(); +} + +Bitu ROMBIOS_MinAllocatedLoc() { + Bitu r = rombios_alloc.getMinAddress(); + + if (r > (0x100000u - rombios_minimum_size)) + r = (0x100000u - rombios_minimum_size); + + return r & ~0xFFFu; +} + +void ROMBIOS_FreeUnusedMinToLoc(Bitu phys) { + Bitu new_phys; + + if (rombios_minimum_location & 0xFFF) E_Exit("ROMBIOS: FreeUnusedMinToLoc minimum location not page aligned"); + + phys &= ~0xFFFUL; + new_phys = rombios_alloc.freeUnusedMinToLoc(phys) & (~0xFFFUL); + assert(new_phys >= phys); + if (phys < new_phys) MEM_unmap_physmem(phys,new_phys-1); + rombios_minimum_location = new_phys; + ROMBIOS_SanityCheck(); + ROMBIOS_DumpMemory(); +} + +bool ROMBIOS_FreeMemory(Bitu phys) { + return rombios_alloc.freeMemory(phys); +} + +Bitu ROMBIOS_GetMemory(Bitu bytes,const char *who,Bitu alignment,Bitu must_be_at) { + return rombios_alloc.getMemory(bytes,who,alignment,must_be_at); +} + +void ROMBIOS_InitForCustomBIOS(void) { + rombios_alloc.initSetRange(0xD8000,0xE0000); +} + +static IO_Callout_t dosbox_int_iocallout = IO_Callout_t_none; + +static unsigned char dosbox_int_register_shf = 0; +static uint32_t dosbox_int_register = 0; +static unsigned char dosbox_int_regsel_shf = 0; +static uint32_t dosbox_int_regsel = 0; +static bool dosbox_int_error = false; +static bool dosbox_int_busy = false; + +#define STRINGIZE_HELPER(A) #A +#define STRINGIZE(A) STRINGIZE_HELPER(A) +#define PPCAT_HELPER(A, B, C) A ## . ## B ## . ## C +#define PPCAT(A, B, C) PPCAT_HELPER(A, B, C) + +#define INTDEV_VERSION_BUMP 2 +#define INTDEV_VERSION_MAJOR 1 +#define INTDEV_VERSION_MINOR 0 +#define INTDEV_VERSION_SUB 1 + +static const char *dosbox_int_version = "DOSBox-X integration device v" STRINGIZE(PPCAT(INTDEV_VERSION_MAJOR, INTDEV_VERSION_MINOR, INTDEV_VERSION_SUB)); +static const char *dosbox_int_ver_read = NULL; + +struct dosbox_int_saved_state { + unsigned char dosbox_int_register_shf; + uint32_t dosbox_int_register; + unsigned char dosbox_int_regsel_shf; + uint32_t dosbox_int_regsel; + bool dosbox_int_error; + bool dosbox_int_busy; +}; + +#define DOSBOX_INT_SAVED_STATE_MAX 4 + +struct dosbox_int_saved_state dosbox_int_saved[DOSBOX_INT_SAVED_STATE_MAX]; +int dosbox_int_saved_sp = -1; + +/* for use with interrupt handlers in DOS/Windows that need to save IG state + * to ensure that IG state is restored on return in order to not interfere + * with anything userspace is doing (as an alternative to wrapping all access + * in CLI/STI or PUSHF/CLI/POPF) */ +bool dosbox_int_push_save_state(void) { + + if (dosbox_int_saved_sp >= (DOSBOX_INT_SAVED_STATE_MAX-1)) + return false; + + struct dosbox_int_saved_state *ss = &dosbox_int_saved[++dosbox_int_saved_sp]; + + ss->dosbox_int_register_shf = dosbox_int_register_shf; + ss->dosbox_int_register = dosbox_int_register; + ss->dosbox_int_regsel_shf = dosbox_int_regsel_shf; + ss->dosbox_int_regsel = dosbox_int_regsel; + ss->dosbox_int_error = dosbox_int_error; + ss->dosbox_int_busy = dosbox_int_busy; + return true; +} + +bool dosbox_int_pop_save_state(void) { + if (dosbox_int_saved_sp < 0) + return false; + + struct dosbox_int_saved_state *ss = &dosbox_int_saved[dosbox_int_saved_sp--]; + + dosbox_int_register_shf = ss->dosbox_int_register_shf; + dosbox_int_register = ss->dosbox_int_register; + dosbox_int_regsel_shf = ss->dosbox_int_regsel_shf; + dosbox_int_regsel = ss->dosbox_int_regsel; + dosbox_int_error = ss->dosbox_int_error; + dosbox_int_busy = ss->dosbox_int_busy; + return true; +} + +bool dosbox_int_discard_save_state(void) { + if (dosbox_int_saved_sp < 0) + return false; + + dosbox_int_saved_sp--; + return true; +} + +extern bool user_cursor_locked; +extern int user_cursor_x,user_cursor_y; +extern int user_cursor_sw,user_cursor_sh; +extern int master_cascade_irq,bootdrive; +extern bool enable_slave_pic; +extern bool bootguest, use_quick_reboot; +extern uint16_t countryNo; +bool bootvm = false, bootfast = false; +static std::string dosbox_int_debug_out; + +uint32_t VGA_QuerySizeIG(void); + +uint32_t Mixer_MIXQ(void); +uint32_t Mixer_MIXC(void); +void Mixer_MIXC_Write(uint32_t v); +PhysPt Mixer_MIXWritePos(void); +void Mixer_MIXWritePos_Write(PhysPt np); +void Mixer_MIXWriteBegin_Write(PhysPt np); +void Mixer_MIXWriteEnd_Write(PhysPt np); + +/* read triggered, update the regsel */ +void dosbox_integration_trigger_read() { + dosbox_int_error = false; + + switch (dosbox_int_regsel) { + case 0: /* Identification */ + dosbox_int_register = 0xD05B0740; + break; + case 1: /* test */ + break; + case 2: /* version string */ + if (dosbox_int_ver_read == NULL) + dosbox_int_ver_read = dosbox_int_version; + + dosbox_int_register = 0; + for (Bitu i=0;i < 4;i++) { + if (*dosbox_int_ver_read == 0) { + dosbox_int_ver_read = dosbox_int_version; + break; + } + + dosbox_int_register += ((uint32_t)((unsigned char)(*dosbox_int_ver_read++))) << (uint32_t)(i * 8); + } + break; + case 3: /* version number */ + dosbox_int_register = INTDEV_VERSION_MAJOR + (INTDEV_VERSION_MINOR << 8U) + (INTDEV_VERSION_SUB << 16U) + (INTDEV_VERSION_BUMP << 24U); + break; + case 4: /* current emulator time as 16.16 fixed point */ + dosbox_int_register = (uint32_t)(PIC_FullIndex() * 0x10000); + break; + case 5: // DOSBox-X version number major (e.g. 2022) + { + const char * ver = strchr(VERSION, '.'); + dosbox_int_register = ver == NULL ? 0 : atoi(std::string(VERSION).substr(0, strlen(ver) - strlen(VERSION)).c_str()); + break; + } + case 6: // DOSBox-X version number minor (e.g. 8) + { + const char * ver = strchr(VERSION, '.'); + dosbox_int_register = ver == NULL ? 0 : atoi(ver + 1); + break; + } + case 7: // DOSBox-X version number sub (e.g. 0) + { + const char * ver = strchr(VERSION, '.'); + ver = strchr(ver + 1, '.'); + dosbox_int_register = ver == NULL ? 0 : atoi(ver + 1); + break; + } + case 8: // DOSBox-X platform type + dosbox_int_register = 0; +#if defined(HX_DOS) + dosbox_int_register = 4; +#elif defined(WIN32) + dosbox_int_register = 1; +#elif defined(LINUX) + dosbox_int_register = 2; +#elif defined(MACOSX) + dosbox_int_register = 3; +#elif defined(OS2) + dosbox_int_register = 5; +#else + dosbox_int_register = 0; +#endif + if (control->opt_securemode || control->SecureMode()) dosbox_int_register = 0; +#if OS_BIT_INT == 64 + dosbox_int_register += 0x20; // 64-bit +#else + dosbox_int_register += 0x10; // 32-bit +#endif +#if defined(C_SDL2) + dosbox_int_register += 0x200; // SDL2 +#elif defined(SDL_DOSBOX_X_SPECIAL) + dosbox_int_register += 0x100; // SDL1 (modified) +#endif + break; + case 9: // DOSBox-X machine type + dosbox_int_register = machine; + break; + + case 0x4B6F4400: // DOS kernel status + dosbox_int_register = dos_kernel_disabled ? 0: 1; + break; + case 0x4B6F4401: // DOS codepage number + dosbox_int_register = dos_kernel_disabled ? 0: dos.loaded_codepage; + break; + case 0x4B6F4402: // DOS country number + dosbox_int_register = dos_kernel_disabled ? 0: countryNo; + break; + case 0x4B6F4403: // DOS version major + dosbox_int_register = dos_kernel_disabled ? 0: dos.version.major; + break; + case 0x4B6F4404: // DOS version minor + dosbox_int_register = dos_kernel_disabled ? 0: dos.version.minor; + break; + case 0x4B6F4405: // DOS error code + dosbox_int_register = dos_kernel_disabled ? 0 : dos.errorcode; + break; + case 0x4B6F4406: // DOS boot drive + dosbox_int_register = bootdrive; + break; + case 0x4B6F4407: // DOS current drive + dosbox_int_register = dos_kernel_disabled ? 0 : DOS_GetDefaultDrive(); + break; + case 0x4B6F4408: // DOS LFN status + dosbox_int_register = dos_kernel_disabled || !uselfn ? 0: 1; + break; + + case 0x5158494D: /* query mixer output 'MIXQ' */ + /* bits [19:0] = sample rate in Hz or 0 if mixer is not mixing AT ALL + * bits [23:20] = number of channels (at this time, always 2 aka stereo) + * bits [29:29] = 1=swap stereo 0=normal + * bits [30:30] = 1=muted 0=not muted + * bits [31:31] = 1=sound 0=nosound */ + dosbox_int_register = Mixer_MIXQ(); + break; + + case 0x4358494D: /* query mixer output 'MIXC' */ + dosbox_int_register = Mixer_MIXC(); + break; + + case 0x5058494D: /* query mixer output 'MIXP' */ + dosbox_int_register = Mixer_MIXWritePos(); + break; + + case 0x4258494D: /* query mixer output 'MIXB' */ + break; + + case 0x4558494D: /* query mixer output 'MIXE' */ + break; + + case 0x6845C0: /* query VGA display size */ + dosbox_int_register = VGA_QuerySizeIG(); + break; + + case 0x825901: /* PIC configuration */ + /* bits [7:0] = cascade interrupt or 0xFF if none + * bit [8:8] = primary PIC present + * bit [9:9] = secondary PIC present */ + if (master_cascade_irq >= 0) + dosbox_int_register = ((unsigned int)master_cascade_irq & 0xFFu); + else + dosbox_int_register = 0xFFu; + + dosbox_int_register |= 0x100; // primary always present + if (enable_slave_pic) dosbox_int_register |= 0x200; + break; + + case 0x823780: /* ISA DMA injection, single byte/word (read from memory) */ + break; + +// case 0x804200: /* keyboard input injection -- not supposed to read */ +// break; + + case 0x804201: /* keyboard status */ + dosbox_int_register = Keyb_ig_status(); + break; + + case 0x434D54: /* read user mouse status */ + dosbox_int_register = + (user_cursor_locked ? (1UL << 0UL) : 0UL); /* bit 0 = mouse capture lock */ + break; + + case 0x434D55: /* read user mouse cursor position */ + dosbox_int_register = (uint32_t((uint16_t)user_cursor_y & 0xFFFFUL) << 16UL) | uint32_t((uint16_t)user_cursor_x & 0xFFFFUL); + break; + + case 0x434D56: { /* read user mouse cursor position (normalized for Windows 3.x) */ + signed long long x = ((signed long long)user_cursor_x << 16LL) / (signed long long)(user_cursor_sw-1); + signed long long y = ((signed long long)user_cursor_y << 16LL) / (signed long long)(user_cursor_sh-1); + if (x < 0x0000LL) x = 0x0000LL; + if (x > 0xFFFFLL) x = 0xFFFFLL; + if (y < 0x0000LL) y = 0x0000LL; + if (y > 0xFFFFLL) y = 0xFFFFLL; + dosbox_int_register = ((unsigned int)y << 16UL) | (unsigned int)x; + } break; + + case 0xC54010: /* Screenshot/capture trigger */ + /* TODO: This should also be hidden behind an enable switch, so that rogue DOS development + * can't retaliate if the user wants to capture video or screenshots. */ +#if (C_SSHOT) + dosbox_int_register = 0x00000000; // available + if (CaptureState & CAPTURE_IMAGE) + dosbox_int_register |= 1 << 0; // Image capture is in progress + if (CaptureState & CAPTURE_VIDEO) + dosbox_int_register |= 1 << 1; // Video capture is in progress + if (CaptureState & CAPTURE_WAVE) + dosbox_int_register |= 1 << 2; // WAVE capture is in progress +#else + dosbox_int_register = 0xC0000000; // not available (bit 31 set), not enabled (bit 30 set) +#endif + break; + + case 0xAA55BB66UL: /* interface reset result */ + break; + + default: + dosbox_int_register = 0xAA55AA55; + dosbox_int_error = true; + break; + } + + LOG(LOG_MISC,LOG_DEBUG)("DOSBox-X integration read 0x%08lx got 0x%08lx (err=%u)\n", + (unsigned long)dosbox_int_regsel, + (unsigned long)dosbox_int_register, + dosbox_int_error?1:0); +} + +bool watchdog_set = false; + +void Watchdog_Timeout_Event(Bitu /*val*/) { + LOG_MSG("Watchdog timeout occurred"); + CPU_Raise_NMI(); +} + +void Watchdog_Timer_Clear(void) { + if (watchdog_set) { + PIC_RemoveEvents(Watchdog_Timeout_Event); + watchdog_set = false; + } +} + +void Watchdog_Timer_Set(uint32_t timeout_ms) { + Watchdog_Timer_Clear(); + + if (timeout_ms != 0) { + watchdog_set = true; + PIC_AddEvent(Watchdog_Timeout_Event,(double)timeout_ms); + } +} + +unsigned int mouse_notify_mode = 0; +// 0 = off +// 1 = trigger as PS/2 mouse interrupt + +/* write triggered */ +void dosbox_integration_trigger_write() { + dosbox_int_error = false; + + LOG(LOG_MISC,LOG_DEBUG)("DOSBox-X integration write 0x%08lx val 0x%08lx\n", + (unsigned long)dosbox_int_regsel, + (unsigned long)dosbox_int_register); + + switch (dosbox_int_regsel) { + case 1: /* test */ + break; + + case 2: /* version string */ + dosbox_int_ver_read = NULL; + break; + + case 0xDEB0: /* debug output (to log) */ + for (unsigned int b=0;b < 4;b++) { + unsigned char c = (unsigned char)(dosbox_int_register >> (b * 8U)); + if (c == '\n' || dosbox_int_debug_out.length() >= 200) { + LOG_MSG("Client debug message: %s\n",dosbox_int_debug_out.c_str()); + dosbox_int_debug_out.clear(); + } + else if (c != 0) { + dosbox_int_debug_out += ((char)c); + } + else { + break; + } + } + dosbox_int_register = 0; + break; + + case 0xDEB1: /* debug output clear */ + dosbox_int_debug_out.clear(); + break; + + case 0x52434D: /* release mouse capture 'MCR' */ + void GFX_ReleaseMouse(void); + GFX_ReleaseMouse(); + break; + + case 0x5158494D: /* query mixer output 'MIXQ' */ + break; + + case 0x4358494D: /* query mixer output 'MIXC' */ + Mixer_MIXC_Write(dosbox_int_register); + break; + + case 0x5058494D: /* query mixer output 'MIXP' */ + Mixer_MIXWritePos_Write(dosbox_int_register); + break; + + case 0x4258494D: /* query mixer output 'MIXB' */ + Mixer_MIXWriteBegin_Write(dosbox_int_register); + break; + + case 0x4558494D: /* query mixer output 'MIXE' */ + Mixer_MIXWriteEnd_Write(dosbox_int_register); + break; + + case 0x57415444: /* Set/clear watchdog timer 'WATD' */ + Watchdog_Timer_Set(dosbox_int_register); + break; + + case 0x808602: /* NMI (INT 02h) interrupt injection */ + { + dosbox_int_register_shf = 0; + dosbox_int_regsel_shf = 0; + CPU_Raise_NMI(); + } + break; + + case 0x825900: /* PIC interrupt injection */ + { + dosbox_int_register_shf = 0; + dosbox_int_regsel_shf = 0; + /* bits [7:0] = IRQ to signal (must be 0-15) + * bit [8:8] = 1=raise 0=lower IRQ */ + uint8_t IRQ = dosbox_int_register&0xFFu; + bool raise = (dosbox_int_register>>8u)&1u; + + if (IRQ < 16) { + if (raise) + PIC_ActivateIRQ(IRQ); + else + PIC_DeActivateIRQ(IRQ); + } + } + break; + + case 0x823700: /* ISA DMA injection, single byte/word (write to memory) */ + { + dosbox_int_register_shf = 0; + dosbox_int_regsel_shf = 0; + /* bits [7:0] = data byte if 8-bit DNA + * bits [15:0] = data word if 16-bit DMA + * bits [18:16] = DMA channel to send to */ + DmaChannel *ch = GetDMAChannel((dosbox_int_register>>16u)&7u); + if (ch != NULL) { + unsigned char tmp[2]; + + tmp[0] = (unsigned char)( dosbox_int_register & 0xFFu); + tmp[1] = (unsigned char)((dosbox_int_register >> 8u) & 0xFFu); + + /* NTS: DMA channel write will write tmp[0] if 8-bit, tmp[0]/tmp[1] if 16-bit */ + if (ch->Write(1/*one unit of transfer*/,tmp) == 1) { + dosbox_int_register = 0; + dosbox_int_error = false; + } + else { + dosbox_int_register = 0x823700; + dosbox_int_error = true; + } + } + else { + dosbox_int_register = 0x8237FF; + dosbox_int_error = true; + } + } + break; + + case 0x823780: /* ISA DMA injection, single byte/word (read from memory) */ + { + dosbox_int_register_shf = 0; + dosbox_int_regsel_shf = 0; + /* bits [18:16] = DMA channel to send to */ + DmaChannel *ch = GetDMAChannel((dosbox_int_register>>16u)&7u); + if (ch != NULL) { + unsigned char tmp[2]; + + /* NTS: DMA channel write will write tmp[0] if 8-bit, tmp[0]/tmp[1] if 16-bit */ + tmp[0] = tmp[1] = 0; + if (ch->Read(1/*one unit of transfer*/,tmp) == 1) { + dosbox_int_register = ((unsigned int)tmp[1] << 8u) + (unsigned int)tmp[0]; + dosbox_int_error = false; + } + else { + dosbox_int_register = 0x823700; + dosbox_int_error = true; + } + } + else { + dosbox_int_register = 0x8237FF; + dosbox_int_error = true; + } + } + break; + + case 0x804200: /* keyboard input injection */ + void Mouse_ButtonPressed(uint8_t button); + void Mouse_ButtonReleased(uint8_t button); + void pc98_keyboard_send(const unsigned char b); + void Mouse_CursorMoved(float xrel,float yrel,float x,float y,bool emulate); + void KEYBOARD_AUX_Event(float x,float y,Bitu buttons,int scrollwheel); + void KEYBOARD_AddBuffer(uint16_t data); + + switch ((dosbox_int_register>>8)&0xFF) { + case 0x00: // keyboard + if (IS_PC98_ARCH) + pc98_keyboard_send(dosbox_int_register&0xFF); + else + KEYBOARD_AddBuffer(dosbox_int_register&0xFF); + break; + case 0x01: // AUX + if (!IS_PC98_ARCH) + KEYBOARD_AddBuffer((dosbox_int_register&0xFF)|0x100/*AUX*/); + else // no such interface in PC-98 mode + dosbox_int_error = true; + break; + case 0x08: // mouse button injection + if (dosbox_int_register&0x80) Mouse_ButtonPressed(dosbox_int_register&0x7F); + else Mouse_ButtonReleased(dosbox_int_register&0x7F); + break; + case 0x09: // mouse movement injection (X) + Mouse_CursorMoved(((dosbox_int_register>>16UL) / 256.0f) - 1.0f,0,0,0,true); + break; + case 0x0A: // mouse movement injection (Y) + Mouse_CursorMoved(0,((dosbox_int_register>>16UL) / 256.0f) - 1.0f,0,0,true); + break; + case 0x0B: // mouse scrollwheel injection + // TODO + break; + default: + dosbox_int_error = true; + break; + } + break; + +// case 0x804201: /* keyboard status do not write */ +// break; + + /* this command is used to enable notification of mouse movement over the windows even if the mouse isn't captured */ + case 0x434D55: /* read user mouse cursor position */ + case 0x434D56: /* read user mouse cursor position (normalized for Windows 3.x) */ + mouse_notify_mode = dosbox_int_register & 0xFF; + LOG(LOG_MISC,LOG_DEBUG)("Mouse notify mode=%u",mouse_notify_mode); + break; + + case 0xC54010: /* Screenshot/capture trigger */ +#if (C_SSHOT) + void CAPTURE_ScreenShotEvent(bool pressed); + void CAPTURE_VideoEvent(bool pressed); +#endif + void CAPTURE_WaveEvent(bool pressed); + + /* TODO: It would be wise to grant/deny access to this register through another dosbox-x.conf option + * so that rogue DOS development cannot shit-spam the capture folder */ +#if (C_SSHOT) + if (dosbox_int_register & 1) + CAPTURE_ScreenShotEvent(true); + if (dosbox_int_register & 2) + CAPTURE_VideoEvent(true); +#endif + if (dosbox_int_register & 4) + CAPTURE_WaveEvent(true); + break; + + default: + dosbox_int_register = 0x55AA55AA; + dosbox_int_error = true; + break; + } +} + +/* PORT 0x28: Index + * 0x29: Data + * 0x2A: Status(R) or Command(W) + * 0x2B: Not yet assigned + * + * Registers are 32-bit wide. I/O to index and data rotate through the + * bytes of the register depending on I/O length, meaning that one 32-bit + * I/O read will read the entire register, while four 8-bit reads will + * read one byte out of 4. */ + +static Bitu dosbox_integration_port00_index_r(Bitu port,Bitu iolen) { + (void)port;//UNUSED + Bitu retb = 0; + Bitu ret = 0; + + while (iolen > 0) { + ret += ((dosbox_int_regsel >> (dosbox_int_regsel_shf * 8)) & 0xFFU) << (retb * 8); + if ((++dosbox_int_regsel_shf) >= 4) dosbox_int_regsel_shf = 0; + iolen--; + retb++; + } + + return ret; +} + +static void dosbox_integration_port00_index_w(Bitu port,Bitu val,Bitu iolen) { + (void)port;//UNUSED + + while (iolen > 0) { + uint32_t msk = 0xFFU << (dosbox_int_regsel_shf * 8); + dosbox_int_regsel = (dosbox_int_regsel & ~msk) + ((val & 0xFF) << (dosbox_int_regsel_shf * 8)); + if ((++dosbox_int_regsel_shf) >= 4) dosbox_int_regsel_shf = 0; + val >>= 8U; + iolen--; + } +} + +static Bitu dosbox_integration_port01_data_r(Bitu port,Bitu iolen) { + (void)port;//UNUSED + Bitu retb = 0; + Bitu ret = 0; + + while (iolen > 0) { + if (dosbox_int_register_shf == 0) dosbox_integration_trigger_read(); + ret += ((dosbox_int_register >> (dosbox_int_register_shf * 8)) & 0xFFU) << (retb * 8); + if ((++dosbox_int_register_shf) >= 4) dosbox_int_register_shf = 0; + iolen--; + retb++; + } + + return ret; +} + +static void dosbox_integration_port01_data_w(Bitu port,Bitu val,Bitu iolen) { + (void)port;//UNUSED + + while (iolen > 0) { + uint32_t msk = 0xFFU << (dosbox_int_register_shf * 8); + dosbox_int_register = (dosbox_int_register & ~msk) + ((val & 0xFF) << (dosbox_int_register_shf * 8)); + if ((++dosbox_int_register_shf) >= 4) dosbox_int_register_shf = 0; + if (dosbox_int_register_shf == 0) dosbox_integration_trigger_write(); + val >>= 8U; + iolen--; + } +} + +static Bitu dosbox_integration_port02_status_r(Bitu port,Bitu iolen) { + (void)iolen;//UNUSED + (void)port;//UNUSED + /* status */ + /* 7:6 = regsel byte index + * 5:4 = register byte index + * 3:2 = reserved + * 1 = error + * 0 = busy */ + return + ((unsigned int)dosbox_int_regsel_shf << 6u) + ((unsigned int)dosbox_int_register_shf << 4u) + + (dosbox_int_error ? 2u : 0u) + (dosbox_int_busy ? 1u : 0u); +} + +static void dosbox_integration_port02_command_w(Bitu port,Bitu val,Bitu iolen) { + (void)port; + (void)iolen; + switch (val) { + case 0x00: /* reset latch */ + dosbox_int_register_shf = 0; + dosbox_int_regsel_shf = 0; + break; + case 0x01: /* flush write */ + if (dosbox_int_register_shf != 0) { + dosbox_integration_trigger_write(); + dosbox_int_register_shf = 0; + } + break; + case 0x20: /* push state */ + if (dosbox_int_push_save_state()) { + dosbox_int_register_shf = 0; + dosbox_int_regsel_shf = 0; + dosbox_int_error = false; + dosbox_int_busy = false; + dosbox_int_regsel = 0xAA55BB66; + dosbox_int_register = 0xD05B0C5; + LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state saved"); + } + else { + LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to push state, stack overflow"); + dosbox_int_error = true; + } + break; + case 0x21: /* pop state */ + if (dosbox_int_pop_save_state()) { + LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state restored"); + } + else { + LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to pop state, stack underflow"); + dosbox_int_error = true; + } + break; + case 0x22: /* discard state */ + if (dosbox_int_discard_save_state()) { + LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG state discarded"); + } + else { + LOG(LOG_MISC,LOG_DEBUG)("DOSBOX-X IG unable to discard state, stack underflow"); + dosbox_int_error = true; + } + break; + case 0x23: /* discard all state */ + while (dosbox_int_discard_save_state()); + break; + case 0xFE: /* clear error */ + dosbox_int_error = false; + break; + case 0xFF: /* reset interface */ + dosbox_int_busy = false; + dosbox_int_error = false; + dosbox_int_regsel = 0xAA55BB66; + dosbox_int_register = 0xD05B0C5; + break; + default: + dosbox_int_error = true; + break; + } +} + +static IO_ReadHandler* const dosbox_integration_cb_ports_r[4] = { + dosbox_integration_port00_index_r, + dosbox_integration_port01_data_r, + dosbox_integration_port02_status_r, + NULL +}; + +static IO_ReadHandler* dosbox_integration_cb_port_r(IO_CalloutObject &co,Bitu port,Bitu iolen) { + (void)co; + (void)iolen; + return dosbox_integration_cb_ports_r[port&3]; +} + +static IO_WriteHandler* const dosbox_integration_cb_ports_w[4] = { + dosbox_integration_port00_index_w, + dosbox_integration_port01_data_w, + dosbox_integration_port02_command_w, + NULL +}; + +static IO_WriteHandler* dosbox_integration_cb_port_w(IO_CalloutObject &co,Bitu port,Bitu iolen) { + (void)co; + (void)iolen; + return dosbox_integration_cb_ports_w[port&3]; +} + +/* if mem_systems 0 then size_extended is reported as the real size else + * zero is reported. ems and xms can increase or decrease the other_memsystems + * counter using the BIOS_ZeroExtendedSize call */ +static uint16_t size_extended; +static unsigned int ISA_PNP_WPORT = 0x20B; +static unsigned int ISA_PNP_WPORT_BIOS = 0; +static IO_ReadHandleObject *ISAPNP_PNP_READ_PORT = NULL; /* 0x200-0x3FF range */ +static IO_WriteHandleObject *ISAPNP_PNP_ADDRESS_PORT = NULL; /* 0x279 */ +static IO_WriteHandleObject *ISAPNP_PNP_DATA_PORT = NULL; /* 0xA79 */ +static IO_WriteHandleObject *BOCHS_PORT_E9 = NULL; +//static unsigned char ISA_PNP_CUR_CSN = 0; +static unsigned char ISA_PNP_CUR_ADDR = 0; +static unsigned char ISA_PNP_CUR_STATE = 0; +enum { + ISA_PNP_WAIT_FOR_KEY=0, + ISA_PNP_SLEEP, + ISA_PNP_ISOLATE, + ISA_PNP_CONFIG +}; + +const unsigned char isa_pnp_init_keystring[32] = { + 0x6A,0xB5,0xDA,0xED,0xF6,0xFB,0x7D,0xBE, + 0xDF,0x6F,0x37,0x1B,0x0D,0x86,0xC3,0x61, + 0xB0,0x58,0x2C,0x16,0x8B,0x45,0xA2,0xD1, + 0xE8,0x74,0x3A,0x9D,0xCE,0xE7,0x73,0x39 +}; + +static RealPt INT15_apm_pmentry=0; +static unsigned char ISA_PNP_KEYMATCH=0; +static Bits other_memsystems=0; +void CMOS_SetRegister(Bitu regNr, uint8_t val); //For setting equipment word +bool enable_integration_device_pnp=false; +bool enable_integration_device=false; +bool ISAPNPBIOS=false; +bool ISAPNPPORT=false; +bool APMBIOS=false; +bool APMBIOS_pnp=false; +bool APMBIOS_allow_realmode=false; +bool APMBIOS_allow_prot16=false; +bool APMBIOS_allow_prot32=false; +int APMBIOS_connect_mode=0; + +enum { + APMBIOS_CONNECT_REAL=0, + APMBIOS_CONNECT_PROT16, + APMBIOS_CONNECT_PROT32 +}; + +unsigned int APMBIOS_connected_already_err() { + switch (APMBIOS_connect_mode) { + case APMBIOS_CONNECT_REAL: return 0x02; + case APMBIOS_CONNECT_PROT16: return 0x05; + case APMBIOS_CONNECT_PROT32: return 0x07; + } + + return 0x00; +} + +ISAPnPDevice::ISAPnPDevice() { + memset(ident,0,sizeof(ident)); +} + +bool ISAPnPDevice::alloc(size_t sz) { + if (sz == alloc_sz) + return true; + + if (alloc_res == resource_data) { + resource_data_len = 0; + resource_data_pos = 0; + resource_data = NULL; + } + if (alloc_res != NULL) + delete[] alloc_res; + + alloc_res = NULL; + alloc_write = 0; + alloc_sz = 0; + + if (sz == 0) + return true; + if (sz > 65536) + return false; + + alloc_res = new unsigned char[sz]; + if (alloc_res == NULL) return false; + memset(alloc_res,0xFF,sz); + alloc_sz = sz; + return true; +} + +ISAPnPDevice::~ISAPnPDevice() { + ISAPnPDevice::alloc(0); +} + +void ISAPnPDevice::begin_write_res() { + if (alloc_res == NULL) return; + + resource_data_pos = 0; + resource_data_len = 0; + resource_data = NULL; + alloc_write = 0; +} + +void ISAPnPDevice::write_byte(const unsigned char c) { + if (alloc_res == NULL || alloc_write >= alloc_sz) return; + alloc_res[alloc_write++] = c; +} + +void ISAPnPDevice::write_begin_SMALLTAG(const ISAPnPDevice::SmallTags stag,unsigned char len) { + if (len >= 8 || (unsigned int)stag >= 0x10) return; + write_byte(((unsigned char)stag << 3) + len); +} + +void ISAPnPDevice::write_begin_LARGETAG(const ISAPnPDevice::LargeTags stag,unsigned int len) { + if (len >= 4096) return; + write_byte(0x80 + ((unsigned char)stag)); + write_byte(len & 0xFF); + write_byte(len >> 8); +} + +void ISAPnPDevice::write_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { + write_byte((((unsigned char)c1 & 0x1FU) << 2) + (((unsigned char)c2 & 0x18U) >> 3)); + write_byte((((unsigned char)c2 & 0x07U) << 5) + ((unsigned char)c3 & 0x1FU)); + write_byte((((unsigned char)c4 & 0x0FU) << 4) + ((unsigned char)c5 & 0x0FU)); + write_byte((((unsigned char)c6 & 0x0FU) << 4) + ((unsigned char)c7 & 0x0FU)); +} + +void ISAPnPDevice::write_Logical_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { + write_begin_SMALLTAG(SmallTags::LogicalDeviceID,5); + write_Device_ID(c1,c2,c3,c4,c5,c6,c7); + write_byte(0x00); +} + +void ISAPnPDevice::write_Compatible_Device_ID(const char c1,const char c2,const char c3,const char c4,const char c5,const char c6,const char c7) { + write_begin_SMALLTAG(SmallTags::CompatibleDeviceID,4); + write_Device_ID(c1,c2,c3,c4,c5,c6,c7); +} + +void ISAPnPDevice::write_IRQ_Format(const uint16_t IRQ_mask,const unsigned char IRQ_signal_type) { + bool write_irq_info = (IRQ_signal_type != 0); + + write_begin_SMALLTAG(SmallTags::IRQFormat,write_irq_info?3:2); + write_byte(IRQ_mask & 0xFF); + write_byte(IRQ_mask >> 8); + if (write_irq_info) write_byte(IRQ_signal_type & 0x0F); +} + +void ISAPnPDevice::write_DMA_Format(const uint8_t DMA_mask,const unsigned char transfer_type_preference,const bool is_bus_master,const bool byte_mode,const bool word_mode,const unsigned char speed_supported) { + write_begin_SMALLTAG(SmallTags::DMAFormat,2); + write_byte(DMA_mask); + write_byte( + (transfer_type_preference & 0x03) | + (is_bus_master ? 0x04 : 0x00) | + (byte_mode ? 0x08 : 0x00) | + (word_mode ? 0x10 : 0x00) | + ((speed_supported & 3) << 5)); +} + +void ISAPnPDevice::write_IO_Port(const uint16_t min_port,const uint16_t max_port,const uint8_t count,const uint8_t alignment,const bool full16bitdecode) { + write_begin_SMALLTAG(SmallTags::IOPortDescriptor,7); + write_byte((full16bitdecode ? 0x01 : 0x00)); + write_byte(min_port & 0xFF); + write_byte(min_port >> 8); + write_byte(max_port & 0xFF); + write_byte(max_port >> 8); + write_byte(alignment); + write_byte(count); +} + +void ISAPnPDevice::write_Dependent_Function_Start(const ISAPnPDevice::DependentFunctionConfig cfg,const bool force) { + bool write_cfg_byte = force || (cfg != ISAPnPDevice::DependentFunctionConfig::AcceptableDependentConfiguration); + + write_begin_SMALLTAG(SmallTags::StartDependentFunctions,write_cfg_byte ? 1 : 0); + if (write_cfg_byte) write_byte((unsigned char)cfg); +} + +void ISAPnPDevice::write_End_Dependent_Functions() { + write_begin_SMALLTAG(SmallTags::EndDependentFunctions,0); +} + +void ISAPnPDevice::write_nstring(const char *str,const size_t l) { + (void)l; + + if (alloc_res == NULL || alloc_write >= alloc_sz) return; + + while (*str != 0 && alloc_write < alloc_sz) + alloc_res[alloc_write++] = (unsigned char)(*str++); +} + +void ISAPnPDevice::write_Identifier_String(const char *str) { + const size_t l = strlen(str); + if (l > 4096) return; + + write_begin_LARGETAG(LargeTags::IdentifierStringANSI,(unsigned int)l); + if (l != 0) write_nstring(str,l); +} + +void ISAPnPDevice::write_ISAPnP_version(unsigned char major,unsigned char minor,unsigned char vendor) { + write_begin_SMALLTAG(SmallTags::PlugAndPlayVersionNumber,2); + write_byte((major << 4) + minor); + write_byte(vendor); +} + +void ISAPnPDevice::write_END() { + unsigned char sum = 0; + size_t i; + + write_begin_SMALLTAG(SmallTags::EndTag,/*length*/1); + + for (i=0;i < alloc_write;i++) sum += alloc_res[i]; + write_byte((0x100 - sum) & 0xFF); +} + +void ISAPnPDevice::end_write_res() { + if (alloc_res == NULL) return; + + write_END(); + + if (alloc_write >= alloc_sz) LOG(LOG_MISC,LOG_WARN)("ISA PNP generation overflow"); + + resource_data_pos = 0; + resource_data_len = alloc_sz; // the device usually has a reason for allocating the fixed size it does + resource_data = alloc_res; + alloc_write = 0; +} + +void ISAPnPDevice::config(Bitu val) { + (void)val; +} + +void ISAPnPDevice::wakecsn(Bitu val) { + (void)val; + ident_bp = 0; + ident_2nd = 0; + resource_data_pos = 0; + resource_ident = 0; +} + +void ISAPnPDevice::select_logical_device(Bitu val) { + (void)val; +} + +void ISAPnPDevice::checksum_ident() { + unsigned char checksum = 0x6a,bit; + + for (int i=0;i < 8;i++) { + for (int j=0;j < 8;j++) { + bit = (ident[i] >> j) & 1; + checksum = ((((checksum ^ (checksum >> 1)) & 1) ^ bit) << 7) | (checksum >> 1); + } + } + + ident[8] = checksum; +} + +void ISAPnPDevice::on_pnp_key() { + resource_ident = 0; +} + +uint8_t ISAPnPDevice::read(Bitu addr) { + (void)addr; + return 0x00; +} + +void ISAPnPDevice::write(Bitu addr,Bitu val) { + (void)addr; + (void)val; +} + +#define MAX_ISA_PNP_DEVICES 64 +#define MAX_ISA_PNP_SYSDEVNODES 256 + +static ISAPnPDevice *ISA_PNP_selected = NULL; +static ISAPnPDevice *ISA_PNP_devs[MAX_ISA_PNP_DEVICES] = {NULL}; /* FIXME: free objects on shutdown */ +static Bitu ISA_PNP_devnext = 0; + +static const unsigned char ISAPnPIntegrationDevice_sysdev[] = { + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x28,0x28, /* min-max range I/O port */ + 0x04,0x04), /* align=4 length=4 */ + ISAPNP_END +}; + +class ISAPnPIntegrationDevice : public ISAPnPDevice { + public: + ISAPnPIntegrationDevice() : ISAPnPDevice() { + resource_ident = 0; + resource_data = (unsigned char*)ISAPnPIntegrationDevice_sysdev; + resource_data_len = sizeof(ISAPnPIntegrationDevice_sysdev); + host_writed(ident+0,ISAPNP_ID('D','O','S',0x1,0x2,0x3,0x4)); /* DOS1234 test device */ + host_writed(ident+4,0xFFFFFFFFUL); + checksum_ident(); + } +}; + +ISAPnPIntegrationDevice *isapnpigdevice = NULL; + +class ISAPNP_SysDevNode { +public: + ISAPNP_SysDevNode(const unsigned char *ir,size_t len,bool already_alloc=false) { + if (already_alloc) { + raw = (unsigned char*)ir; + raw_len = len; + own = false; + } + else { + if (len > 65535) E_Exit("ISAPNP_SysDevNode data too long"); + raw = new unsigned char[len+1u]; + if (ir == NULL) + E_Exit("ISAPNP_SysDevNode cannot allocate buffer"); + else + memcpy(raw, ir, len); + raw_len = len; + raw[len] = 0; + own = true; + } + } + virtual ~ISAPNP_SysDevNode() { + if (own) delete[] raw; + } + + unsigned char* raw; + size_t raw_len; + bool own; +}; + +static ISAPNP_SysDevNode* ISAPNP_SysDevNodes[MAX_ISA_PNP_SYSDEVNODES] = {NULL}; +static Bitu ISAPNP_SysDevNodeLargest=0; +static Bitu ISAPNP_SysDevNodeCount=0; + +void ISA_PNP_FreeAllSysNodeDevs() { + for (Bitu i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) { + if (ISAPNP_SysDevNodes[i] != NULL) delete ISAPNP_SysDevNodes[i]; + ISAPNP_SysDevNodes[i] = NULL; + } + + ISAPNP_SysDevNodeLargest=0; + ISAPNP_SysDevNodeCount=0; +} + +void ISA_PNP_FreeAllDevs() { + Bitu i; + + for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { + if (ISA_PNP_devs[i] != NULL) { + delete ISA_PNP_devs[i]; + ISA_PNP_devs[i] = NULL; + } + } + for (i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) { + if (ISAPNP_SysDevNodes[i] != NULL) delete ISAPNP_SysDevNodes[i]; + ISAPNP_SysDevNodes[i] = NULL; + } + + ISAPNP_SysDevNodeLargest=0; + ISAPNP_SysDevNodeCount=0; +} + +void ISA_PNP_devreg(ISAPnPDevice *x) { + if (ISA_PNP_devnext < MAX_ISA_PNP_DEVICES) { + if (ISA_PNP_WPORT_BIOS == 0 && ISAPNPPORT) ISA_PNP_WPORT_BIOS = ISA_PNP_WPORT; + ISA_PNP_devs[ISA_PNP_devnext++] = x; + x->CSN = ISA_PNP_devnext; + } +} + +static Bitu isapnp_read_port(Bitu port,Bitu /*iolen*/) { + (void)port;//UNUSED + Bitu ret=0xff; + + switch (ISA_PNP_CUR_ADDR) { + case 0x01: /* serial isolation */ + if (ISA_PNP_selected && ISA_PNP_selected->CSN == 0) { + if (ISA_PNP_selected->ident_bp < 72) { + if (ISA_PNP_selected->ident[ISA_PNP_selected->ident_bp>>3] & (1 << (ISA_PNP_selected->ident_bp&7))) + ret = ISA_PNP_selected->ident_2nd ? 0xAA : 0x55; + else + ret = 0xFF; + + if (++ISA_PNP_selected->ident_2nd >= 2) { + ISA_PNP_selected->ident_2nd = 0; + ISA_PNP_selected->ident_bp++; + } + } + } + else { + ret = 0xFF; + } + break; + case 0x04: /* read resource data */ + if (ISA_PNP_selected) { + if (ISA_PNP_selected->resource_ident < 9) + ret = ISA_PNP_selected->ident[ISA_PNP_selected->resource_ident++]; + else { + /* real-world hardware testing shows that devices act as if there was some fixed block of ROM, + * that repeats every 128, 256, 512, or 1024 bytes if you just blindly read from this port. */ + if (ISA_PNP_selected->resource_data_pos < ISA_PNP_selected->resource_data_len) + ret = ISA_PNP_selected->resource_data[ISA_PNP_selected->resource_data_pos++]; + + /* that means that if you read enough bytes the ROM loops back to returning the ident */ + if (ISA_PNP_selected->resource_data_pos >= ISA_PNP_selected->resource_data_len) { + ISA_PNP_selected->resource_data_pos = 0; + ISA_PNP_selected->resource_ident = 0; + } + } + } + break; + case 0x05: /* read resource status */ + if (ISA_PNP_selected) { + /* real-world hardware testing shows that devices act as if there was some fixed block of ROM, + * that repeats every 128, 256, 512, or 1024 bytes if you just blindly read from this port. + * therefore, there's always a byte to return. */ + ret = 0x01; /* TODO: simulate hardware slowness */ + } + break; + case 0x06: /* card select number */ + if (ISA_PNP_selected) ret = ISA_PNP_selected->CSN; + break; + case 0x07: /* logical device number */ + if (ISA_PNP_selected) ret = ISA_PNP_selected->logical_device; + break; + default: /* pass the rest down to the class */ + if (ISA_PNP_selected) ret = ISA_PNP_selected->read(ISA_PNP_CUR_ADDR); + break; + } + +// if (1) LOG_MSG("PnP read(%02X) = %02X\n",ISA_PNP_CUR_ADDR,ret); + return ret; +} + +void isapnp_write_port(Bitu port,Bitu val,Bitu /*iolen*/) { + Bitu i; + + if (port == 0x279) { +// if (1) LOG_MSG("PnP addr(%02X)\n",val); + if (val == isa_pnp_init_keystring[ISA_PNP_KEYMATCH]) { + if (++ISA_PNP_KEYMATCH == 32) { +// LOG_MSG("ISA PnP key -> going to sleep\n"); + ISA_PNP_CUR_STATE = ISA_PNP_SLEEP; + ISA_PNP_KEYMATCH = 0; + for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { + if (ISA_PNP_devs[i] != NULL) { + ISA_PNP_devs[i]->on_pnp_key(); + } + } + } + } + else { + ISA_PNP_KEYMATCH = 0; + } + + ISA_PNP_CUR_ADDR = val; + } + else if (port == 0xA79) { +// if (1) LOG_MSG("PnP write(%02X) = %02X\n",ISA_PNP_CUR_ADDR,val); + switch (ISA_PNP_CUR_ADDR) { + case 0x00: { /* RD_DATA */ + unsigned int np = ((val & 0xFF) << 2) | 3; + if (np != ISA_PNP_WPORT) { + if (ISAPNP_PNP_READ_PORT != NULL) { + ISAPNP_PNP_READ_PORT = NULL; + delete ISAPNP_PNP_READ_PORT; + } + + if (np >= 0x200 && np <= 0x3FF) { /* allowable port I/O range according to spec */ + LOG_MSG("PNP OS changed I/O read port to 0x%03X (from 0x%03X)\n",np,ISA_PNP_WPORT); + + ISA_PNP_WPORT = np; + ISAPNP_PNP_READ_PORT = new IO_ReadHandleObject; + ISAPNP_PNP_READ_PORT->Install(ISA_PNP_WPORT,isapnp_read_port,IO_MB); + } + else { + LOG_MSG("PNP OS I/O read port disabled\n"); + + ISA_PNP_WPORT = 0; + } + + if (ISA_PNP_selected != NULL) { + ISA_PNP_selected->ident_bp = 0; + ISA_PNP_selected->ident_2nd = 0; + ISA_PNP_selected->resource_data_pos = 0; + } + } + } break; + case 0x02: /* config control */ + if (val & 4) { + /* ALL CARDS RESET CSN to 0 */ + for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { + if (ISA_PNP_devs[i] != NULL) { + ISA_PNP_devs[i]->CSN = 0; + } + } + } + if (val & 2) ISA_PNP_CUR_STATE = ISA_PNP_WAIT_FOR_KEY; + if ((val & 1) && ISA_PNP_selected) ISA_PNP_selected->config(val); + for (i=0;i < MAX_ISA_PNP_DEVICES;i++) { + if (ISA_PNP_devs[i] != NULL) { + ISA_PNP_devs[i]->ident_bp = 0; + ISA_PNP_devs[i]->ident_2nd = 0; + ISA_PNP_devs[i]->resource_data_pos = 0; + } + } + break; + case 0x03: { /* wake[CSN] */ + ISA_PNP_selected = NULL; + for (i=0;ISA_PNP_selected == NULL && i < MAX_ISA_PNP_DEVICES;i++) { + if (ISA_PNP_devs[i] == NULL) + continue; + if (ISA_PNP_devs[i]->CSN == val) { + ISA_PNP_selected = ISA_PNP_devs[i]; + ISA_PNP_selected->wakecsn(val); + } + } + if (val == 0) + ISA_PNP_CUR_STATE = ISA_PNP_ISOLATE; + else + ISA_PNP_CUR_STATE = ISA_PNP_CONFIG; + } break; + case 0x06: /* card select number */ + if (ISA_PNP_selected) ISA_PNP_selected->CSN = val; + break; + case 0x07: /* logical device number */ + if (ISA_PNP_selected) ISA_PNP_selected->select_logical_device(val); + break; + default: /* pass the rest down to the class */ + if (ISA_PNP_selected) ISA_PNP_selected->write(ISA_PNP_CUR_ADDR,val); + break; + } + } +} + +// IBM PC/AT CTRL+BREAK interrupt, called by IRQ1 handler. +// Not applicable to PC-98 mode, of course. +Bitu INT1B_Break_Handler(void) { + // BIOS DATA AREA 40:71 bit 7 is set when Break key is pressed. + // This is already implemented by IRQ1 handler in src/ints/bios_keyboard.cpp. + // Ref: [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/Computers/IBM/PS%e2%88%952/IBM%20Personal%20System%e2%88%952%20and%20Personal%20Computer%20BIOS%20Interface%20Technical%20Reference%20%281991%2d09%29%20First%20Edition%2c%20part%203%2epdf] + return CBRET_NONE; +} + + +static Bitu INT15_Handler(void); + +// FIXME: This initializes both APM BIOS and ISA PNP emulation! +// Need to separate APM BIOS init from ISA PNP init from ISA PNP BIOS init! +// It might also be appropriate to move this into the BIOS init sequence. +void ISAPNP_Cfg_Reset(Section *sec) { + (void)sec;//UNUSED + const Section_prop* section = static_cast(control->GetSection("cpu")); + + LOG(LOG_MISC,LOG_DEBUG)("Initializing ISA PnP emulation"); + + enable_integration_device = section->Get_bool("integration device"); + enable_integration_device_pnp = section->Get_bool("integration device pnp"); + ISAPNPBIOS = section->Get_bool("isapnpbios"); + { + /* ISAPNPPORT = off|auto|on */ + const char *s = section->Get_string("isapnpport"); + + if (!strcmp(s,"true") || !strcmp(s,"1")) + ISAPNPPORT = true; + else if (!strcmp(s,"false") || !strcmp(s,"0")) + ISAPNPPORT = false; + else /* auto */ + ISAPNPPORT = ISAPNPBIOS; /* if the PnP BIOS is enabled, then so is the port */ + } + APMBIOS = section->Get_bool("apmbios"); + APMBIOS_pnp = section->Get_bool("apmbios pnp"); + APMBIOS_allow_realmode = section->Get_bool("apmbios allow realmode"); + APMBIOS_allow_prot16 = section->Get_bool("apmbios allow 16-bit protected mode"); + APMBIOS_allow_prot32 = section->Get_bool("apmbios allow 32-bit protected mode"); + + std::string apmbiosver = section->Get_string("apmbios version"); + + /* PC-98 does not have the IBM PC/AT APM BIOS interface */ + if (IS_PC98_ARCH) { + APMBIOS = false; + APMBIOS_pnp = false; + } + + if (apmbiosver == "1.0") + APM_BIOS_minor_version = 0; + else if (apmbiosver == "1.1") + APM_BIOS_minor_version = 1; + else if (apmbiosver == "1.2") + APM_BIOS_minor_version = 2; + else//auto + APM_BIOS_minor_version = 2; + + /* PC-98 does not have APM. + * I *think* it has Plug & Play, but probably different from ISA PnP and specific to the C-Bus interface, + * which I have no information on at this time --J.C. */ + if (IS_PC98_ARCH) + return; + + LOG(LOG_MISC,LOG_DEBUG)("APM BIOS allow: real=%u pm16=%u pm32=%u version=1.%u", + APMBIOS_allow_realmode, + APMBIOS_allow_prot16, + APMBIOS_allow_prot32, + APM_BIOS_minor_version); + + std::string apmbiospwrbtn = section->Get_string("apm power button event"); + if (apmbiospwrbtn == "standby") + APM_PowerButtonSendsSuspend = false; + else + APM_PowerButtonSendsSuspend = true; + + + if (APMBIOS && (APMBIOS_allow_prot16 || APMBIOS_allow_prot32) && INT15_apm_pmentry == 0) { + Bitu cb,base; + + /* NTS: This is... kind of a terrible hack. It basically tricks Windows into executing our + * INT 15h handler as if the APM entry point. Except that instead of an actual INT 15h + * triggering the callback, a FAR CALL triggers the callback instead (CB_RETF not CB_IRET). */ + /* TODO: We should really consider moving the APM BIOS code in INT15_Handler() out into its + * own function, then having the INT15_Handler() call it as well as directing this callback + * directly to it. If you think about it, this hack also lets the "APM entry point" invoke + * other arbitrary INT 15h calls which is not valid. */ + + cb = CALLBACK_Allocate(); + INT15_apm_pmentry = CALLBACK_RealPointer(cb); + LOG_MSG("Allocated APM BIOS pm entry point at %04x:%04x\n",INT15_apm_pmentry>>16,INT15_apm_pmentry&0xFFFF); + CALLBACK_Setup(cb,INT15_Handler,CB_RETF,"APM BIOS protected mode entry point"); + + /* NTS: Actually INT15_Handler is written to act like an interrupt (IRETF) type callback. + * Prior versions hacked this into something that responds by CB_RETF, however some + * poking around reveals that CALLBACK_SCF and friends still assume an interrupt + * stack, thus, the cause of random crashes in Windows was simply that we were + * flipping flag bits in the middle of the return address on the stack. The other + * source of random crashes is that the CF/ZF manipulation in INT 15h wasn't making + * its way back to Windows, meaning that when APM BIOS emulation intended to return + * an error (by setting CF), Windows didn't get the memo (CF wasn't set on return) + * and acted as if the call succeeded, or worse, CF happened to be set on entry and + * was never cleared by APM BIOS emulation. + * + * So what we need is: + * + * PUSHF ; put flags in right place + * PUSH BP ; dummy FAR pointer + * PUSH BP ; again + * + * POP BP ; drop it + * POP BP ; drop it + * POPF + * RETF + * + * Then CALLBACK_SCF can work normally this way. + * + * NTS: We *still* need to separate APM BIOS calls from the general INT 15H emulation though... */ + base = Real2Phys(INT15_apm_pmentry); + LOG_MSG("Writing code to %05x\n",(unsigned int)base); + + phys_writeb(base+0x00,0x9C); /* pushf */ + phys_writeb(base+0x01,0x55); /* push (e)bp */ + phys_writeb(base+0x02,0x55); /* push (e)bp */ + + phys_writeb(base+0x03,(uint8_t)0xFE); //GRP 4 + phys_writeb(base+0x04,(uint8_t)0x38); //Extra Callback instruction + phys_writew(base+0x05,(uint16_t)cb); //The immediate word + + phys_writeb(base+0x07,0x5D); /* pop (e)bp */ + phys_writeb(base+0x08,0x5D); /* pop (e)bp */ + phys_writeb(base+0x09,0x9D); /* popf */ + phys_writeb(base+0x0A,0xCB); /* retf */ + + /* APM suspended mode execution loop */ + cb = CALLBACK_Allocate(); + APM_SuspendedLoopRptr = CALLBACK_RealPointer(cb); + CALLBACK_Setup(cb,APM_SuspendedLoopFunc,CB_RETF,"APM BIOS suspend/standby loop"); + + base = Real2Phys(APM_SuspendedLoopRptr); + LOG_MSG("Writing code to %05x\n",(unsigned int)base); + phys_writeb(base+0x04,0xF4); /* hlt */ + phys_writew(base+0x05,0xF9EB); /* jmp $-5 (EB xx) */ + phys_writeb(base+0x07,0xC3); /* ret */ + } +} + +void ISAPNP_Cfg_Init() { + AddVMEventFunction(VM_EVENT_RESET,AddVMEventFunctionFuncPair(ISAPNP_Cfg_Reset)); +} + +/* the PnP callback registered two entry points. One for real, one for protected mode. */ +static Bitu PNPentry_real,PNPentry_prot; + +static bool ISAPNP_Verify_BiosSelector(Bitu seg) { + if (!cpu.pmode || (reg_flags & FLAG_VM)) { + return (seg == 0xF000); + } else if (seg == 0) + return 0; + else { +#if 1 + /* FIXME: Always return true. But figure out how to ask DOSBox the linear->phys + mapping to determine whether the segment's base address maps to 0xF0000. + In the meantime disabling this check makes PnP BIOS emulation work with + Windows 95 OSR2 which appears to give us a segment mapped to a virtual + address rather than linearly mapped to 0xF0000 as Windows 95 original + did. */ + return true; +#else + Descriptor desc; + cpu.gdt.GetDescriptor(seg,desc); + + /* TODO: Check desc.Type() to make sure it's a writeable data segment */ + return (desc.GetBase() == 0xF0000); +#endif + } +} + +static bool ISAPNP_CPU_ProtMode() { + if (!cpu.pmode || (reg_flags & FLAG_VM)) + return 0; + + return 1; +} + +static Bitu ISAPNP_xlate_address(Bitu far_ptr) { + if (!cpu.pmode || (reg_flags & FLAG_VM)) + return Real2Phys(far_ptr); + else { + Descriptor desc; + cpu.gdt.GetDescriptor(far_ptr >> 16,desc); + + /* TODO: Check desc.Type() to make sure it's a writeable data segment */ + return (desc.GetBase() + (far_ptr & 0xFFFF)); + } +} + +static const unsigned char ISAPNP_sysdev_Keyboard[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0x3,0x0,0x3), /* PNP0303 IBM Enhanced 101/102 key with PS/2 */ + ISAPNP_TYPE(0x09,0x00,0x00), /* type: input, keyboard */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x60,0x60, /* min-max range I/O port */ + 0x01,0x01), /* align=1 length=1 */ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x64,0x64, /* min-max range I/O port */ + 0x01,0x01), /* align=1 length=1 */ + ISAPNP_IRQ_SINGLE( + 1, /* IRQ 1 */ + 0x09), /* HTE=1 LTL=1 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +static const unsigned char ISAPNP_sysdev_Mouse[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xF,0x0,0xE), /* PNP0F0E Microsoft compatible PS/2 */ + ISAPNP_TYPE(0x09,0x02,0x00), /* type: input, keyboard */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IRQ_SINGLE( + 12, /* IRQ 12 */ + 0x09), /* HTE=1 LTL=1 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +static const unsigned char ISAPNP_sysdev_DMA_Controller[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0x2,0x0,0x0), /* PNP0200 AT DMA controller */ + ISAPNP_TYPE(0x08,0x01,0x00), /* type: input, keyboard */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x00,0x00, /* min-max range I/O port (DMA channels 0-3) */ + 0x10,0x10), /* align=16 length=16 */ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x81,0x81, /* min-max range I/O port (DMA page registers) */ + 0x01,0x0F), /* align=1 length=15 */ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0xC0,0xC0, /* min-max range I/O port (AT DMA channels 4-7) */ + 0x20,0x20), /* align=32 length=32 */ + ISAPNP_DMA_SINGLE( + 4, /* DMA 4 */ + 0x01), /* 8/16-bit transfers, compatible speed */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +static const unsigned char ISAPNP_sysdev_PIC[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0x0,0x0,0x0), /* PNP0000 Interrupt controller */ + ISAPNP_TYPE(0x08,0x00,0x01), /* type: ISA interrupt controller */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x20,0x20, /* min-max range I/O port */ + 0x01,0x02), /* align=1 length=2 */ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0xA0,0xA0, /* min-max range I/O port */ + 0x01,0x02), /* align=1 length=2 */ + ISAPNP_IRQ_SINGLE( + 2, /* IRQ 2 */ + 0x09), /* HTE=1 LTL=1 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +static const unsigned char ISAPNP_sysdev_Timer[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0x1,0x0,0x0), /* PNP0100 Timer */ + ISAPNP_TYPE(0x08,0x02,0x01), /* type: ISA timer */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x40,0x40, /* min-max range I/O port */ + 0x04,0x04), /* align=4 length=4 */ + ISAPNP_IRQ_SINGLE( + 0, /* IRQ 0 */ + 0x09), /* HTE=1 LTL=1 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +static const unsigned char ISAPNP_sysdev_RTC[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xB,0x0,0x0), /* PNP0B00 Real-time clock */ + ISAPNP_TYPE(0x08,0x03,0x01), /* type: ISA real-time clock */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x70,0x70, /* min-max range I/O port */ + 0x01,0x02), /* align=1 length=2 */ + ISAPNP_IRQ_SINGLE( + 8, /* IRQ 8 */ + 0x09), /* HTE=1 LTL=1 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +static const unsigned char ISAPNP_sysdev_PC_Speaker[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0x8,0x0,0x0), /* PNP0800 PC speaker */ + ISAPNP_TYPE(0x04,0x01,0x00), /* type: PC speaker */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x61,0x61, /* min-max range I/O port */ + 0x01,0x01), /* align=1 length=1 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +static const unsigned char ISAPNP_sysdev_Numeric_Coprocessor[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x4), /* PNP0C04 Numeric Coprocessor */ + ISAPNP_TYPE(0x0B,0x80,0x00), /* type: FPU */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0xF0,0xF0, /* min-max range I/O port */ + 0x10,0x10), /* align=16 length=16 */ + ISAPNP_IRQ_SINGLE( + 13, /* IRQ 13 */ + 0x09), /* HTE=1 LTL=1 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +static const unsigned char ISAPNP_sysdev_System_Board[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x1), /* PNP0C01 System board */ + ISAPNP_TYPE(0x08,0x80,0x00), /* type: System peripheral, Other */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x24,0x24, /* min-max range I/O port */ + 0x04,0x04), /* align=4 length=4 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +/* NTS: If some of my late 1990's laptops are any indication, this resource list can be used + * as a hint that the motherboard supports Intel EISA/PCI controller DMA registers that + * allow ISA DMA to extend to 32-bit addresses instead of being limited to 24-bit */ +static const unsigned char ISAPNP_sysdev_General_ISAPNP[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x2), /* PNP0C02 General ID for reserving resources */ + ISAPNP_TYPE(0x08,0x80,0x00), /* type: System peripheral, Other */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_IO_RANGE( + 0x01, /* decodes 16-bit ISA addr */ + 0x208,0x208, /* min-max range I/O port */ + 0x04,0x04), /* align=4 length=4 */ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +/* PnP system entry to tell Windows 95 the obvious: That there's an ISA bus present */ +/* NTS: Examination of some old laptops of mine shows that these devices do not list any resources, + * or at least, an old Toshiba of mine lists the PCI registers 0xCF8-0xCFF as motherboard resources + * and defines no resources for the PCI Bus PnP device. */ +static const unsigned char ISAPNP_sysdev_ISA_BUS[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xA,0x0,0x0), /* PNP0A00 ISA Bus */ + ISAPNP_TYPE(0x06,0x04,0x00), /* type: System device, peripheral bus */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +/* PnP system entry to tell Windows 95 the obvious: That there's a PCI bus present */ +static const unsigned char ISAPNP_sysdev_PCI_BUS[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xA,0x0,0x3), /* PNP0A03 PCI Bus */ + ISAPNP_TYPE(0x06,0x04,0x00), /* type: System device, peripheral bus */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +/* to help convince Windows 95 that the APM BIOS is present */ +static const unsigned char ISAPNP_sysdev_APM_BIOS[] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x5), /* PNP0C05 APM BIOS */ + ISAPNP_TYPE(0x08,0x80,0x00), /* type: FIXME is this right?? I can't find any examples or documentation */ + 0x0001 | 0x0002), /* can't disable, can't configure */ + /*----------allocated--------*/ + ISAPNP_END, + /*----------possible--------*/ + ISAPNP_END, + /*----------compatible--------*/ + ISAPNP_END +}; + +bool ISAPNP_RegisterSysDev(const unsigned char *raw,Bitu len,bool already) { + if (ISAPNP_SysDevNodeCount >= MAX_ISA_PNP_SYSDEVNODES) + return false; + + ISAPNP_SysDevNodes[ISAPNP_SysDevNodeCount] = new ISAPNP_SysDevNode(raw,len,already); + if (ISAPNP_SysDevNodes[ISAPNP_SysDevNodeCount] == NULL) + return false; + + ISAPNP_SysDevNodeCount++; + if (ISAPNP_SysDevNodeLargest < (len+3)) + ISAPNP_SysDevNodeLargest = len+3; + + return true; +} + +/* ISA PnP function calls have their parameters stored on the stack "C" __cdecl style. Parameters + * are either int, long, or FAR pointers. Like __cdecl an assembly language implementation pushes + * the function arguments on the stack BACKWARDS */ +static Bitu ISAPNP_Handler(bool protmode /* called from protected mode interface == true */) { + Bitu arg; + Bitu func,BiosSelector; + + /* I like how the ISA PnP spec says that the 16-bit entry points (real and protected) are given 16-bit data segments + * which implies that all segments involved might as well be 16-bit. + * + * Right? + * + * Well, guess what Windows 95 gives us when calling this entry point: + * + * Segment SS = DS = 0x30 base=0 limit=0xFFFFFFFF + * SS:SP = 0x30:0xC138BADF or something like that from within BIOS.VXD + * + * Yeah... for a 16-bit code segment call. Right. Typical Microsoft. >:( + * + * This might also explain why my early experiments with Bochs always had the perpetual + * APM BIOS that never worked but was always detected. + * + * ------------------------------------------------------------------------ + * Windows 95 OSR2: + * + * Windows 95 OSR2 however uses a 16-bit stack (where the stack segment is based somewhere + * around 0xC1xxxxxx), all we have to do to correctly access it is work through the page tables. + * This is within spec, but now Microsoft sends us a data segment that is based at virtual address + * 0xC2xxxxxx, which is why I had to disable the "verify selector" routine */ + arg = SegPhys(ss) + (reg_esp&cpu.stack.mask) + (2*2); /* entry point (real and protected) is 16-bit, expected to RETF (skip CS:IP) */ + + if (protmode != ISAPNP_CPU_ProtMode()) { + //LOG_MSG("ISA PnP %s entry point called from %s. On real BIOSes this would CRASH\n",protmode ? "Protected mode" : "Real mode", + // ISAPNP_CPU_ProtMode() ? "Protected mode" : "Real mode"); + reg_ax = 0x84;/* BAD_PARAMETER */ + return 0; + } + + func = mem_readw(arg); +// LOG_MSG("PnP prot=%u DS=%04x (base=0x%08lx) SS:ESP=%04x:%04x (base=0x%08lx phys=0x%08lx) function=0x%04x\n", +// (unsigned int)protmode,(unsigned int)SegValue(ds),(unsigned long)SegPhys(ds), +// (unsigned int)SegValue(ss),(unsigned int)reg_esp,(unsigned long)SegPhys(ss), +// (unsigned long)arg,(unsigned int)func); + + /* every function takes the form + * + * int __cdecl FAR (*entrypoint)(int Function...); + * + * so the first argument on the stack is an int that we read to determine what the caller is asking + * + * Don't forget in the real-mode world: + * sizeof(int) == 16 bits + * sizeof(long) == 32 bits + */ + switch (func) { + case 0: { /* Get Number of System Nodes */ + /* int __cdecl FAR (*entrypoint)(int Function,unsigned char FAR *NumNodes,unsigned int FAR *NodeSize,unsigned int BiosSelector); + * ^ +0 ^ +2 ^ +6 ^ +10 = 12 */ + Bitu NumNodes_ptr = mem_readd(arg+2); + Bitu NodeSize_ptr = mem_readd(arg+6); + BiosSelector = mem_readw(arg+10); + + if (!ISAPNP_Verify_BiosSelector(BiosSelector)) + goto badBiosSelector; + + if (NumNodes_ptr != 0) mem_writeb(ISAPNP_xlate_address(NumNodes_ptr),ISAPNP_SysDevNodeCount); + if (NodeSize_ptr != 0) mem_writew(ISAPNP_xlate_address(NodeSize_ptr),ISAPNP_SysDevNodeLargest); + + reg_ax = 0x00;/* SUCCESS */ + } break; + case 1: { /* Get System Device Node */ + /* int __cdecl FAR (*entrypoint)(int Function,unsigned char FAR *Node,struct DEV_NODE FAR *devNodeBuffer,unsigned int Control,unsigned int BiosSelector); + * ^ +0 ^ +2 ^ +6 ^ +10 ^ +12 = 14 */ + Bitu Node_ptr = mem_readd(arg+2); + Bitu devNodeBuffer_ptr = mem_readd(arg+6); + Bitu Control = mem_readw(arg+10); + BiosSelector = mem_readw(arg+12); + unsigned char Node; + Bitu i=0; + + if (!ISAPNP_Verify_BiosSelector(BiosSelector)) + goto badBiosSelector; + + /* control bits 0-1 must be '01' or '10' but not '00' or '11' */ + if (Control == 0 || (Control&3) == 3) { + LOG_MSG("ISAPNP Get System Device Node: Invalid Control value 0x%04x\n",(int)Control); + reg_ax = 0x84;/* BAD_PARAMETER */ + break; + } + + devNodeBuffer_ptr = ISAPNP_xlate_address(devNodeBuffer_ptr); + Node_ptr = ISAPNP_xlate_address(Node_ptr); + Node = mem_readb(Node_ptr); + if (Node >= ISAPNP_SysDevNodeCount) { + LOG_MSG("ISAPNP Get System Device Node: Invalid Node 0x%02x (max 0x%04x)\n",(int)Node,(int)ISAPNP_SysDevNodeCount); + reg_ax = 0x84;/* BAD_PARAMETER */ + break; + } + + const ISAPNP_SysDevNode *nd = ISAPNP_SysDevNodes[Node]; + + mem_writew(devNodeBuffer_ptr+0,(uint16_t)(nd->raw_len+3)); /* Length */ + mem_writeb(devNodeBuffer_ptr+2,Node); /* on most PnP BIOS implementations I've seen "handle" is set to the same value as Node */ + for (i=0;i < (Bitu)nd->raw_len;i++) + mem_writeb(devNodeBuffer_ptr+i+3,nd->raw[i]); + +// LOG_MSG("ISAPNP OS asked for Node 0x%02x\n",Node); + + if (++Node >= ISAPNP_SysDevNodeCount) Node = 0xFF; /* no more nodes */ + mem_writeb(Node_ptr,Node); + + reg_ax = 0x00;/* SUCCESS */ + } break; + case 4: { /* Send Message */ + /* int __cdecl FAR (*entrypoint)(int Function,unsigned int Message,unsigned int BiosSelector); + * ^ +0 ^ +2 ^ +4 = 6 */ + Bitu Message = mem_readw(arg+2); + BiosSelector = mem_readw(arg+4); + + if (!ISAPNP_Verify_BiosSelector(BiosSelector)) + goto badBiosSelector; + + switch (Message) { + case 0x41: /* POWER_OFF */ + LOG_MSG("Plug & Play OS requested power off.\n"); + reg_ax = 0; + throw 1; /* NTS: Based on the Reboot handler code, causes DOSBox-X to cleanly shutdown and exit */ + break; + case 0x42: /* PNP_OS_ACTIVE */ + LOG_MSG("Plug & Play OS reports itself active\n"); + reg_ax = 0; + break; + case 0x43: /* PNP_OS_INACTIVE */ + LOG_MSG("Plug & Play OS reports itself inactive\n"); + reg_ax = 0; + break; + default: + LOG_MSG("Unknown ISA PnP message 0x%04x\n",(int)Message); + reg_ax = 0x82;/* FUNCTION_NOT_SUPPORTED */ + break; + } + } break; + case 0x40: { /* Get PnP ISA configuration */ + /* int __cdecl FAR (*entrypoint)(int Function,unsigned char far *struct,unsigned int BiosSelector); + * ^ +0 ^ +2 ^ +6 = 8 */ + Bitu struct_ptr = mem_readd(arg+2); + BiosSelector = mem_readw(arg+6); + + if (!ISAPNP_Verify_BiosSelector(BiosSelector)) + goto badBiosSelector; + + /* struct isapnp_pnp_isa_cfg { + uint8_t revision; + uint8_t total_csn; + uint16_t isa_pnp_port; + uint16_t reserved; + }; */ + + if (struct_ptr != 0) { + Bitu ph = ISAPNP_xlate_address(struct_ptr); + mem_writeb(ph+0,0x01); /* ->revision = 0x01 */ + mem_writeb(ph+1,ISA_PNP_devnext); /* ->total_csn */ + mem_writew(ph+2,ISA_PNP_WPORT_BIOS); /* ->isa_pnp_port */ + mem_writew(ph+4,0); /* ->reserved */ + } + + reg_ax = 0x00;/* SUCCESS */ + } break; + default: + //LOG_MSG("Unsupported ISA PnP function 0x%04x\n",func); + reg_ax = 0x82;/* FUNCTION_NOT_SUPPORTED */ + break; + } + + return 0; +badBiosSelector: + /* return an error. remind the user (possible developer) how lucky he is, a real + * BIOS implementation would CRASH when misused like this */ + LOG_MSG("ISA PnP function 0x%04x called with incorrect BiosSelector parameter 0x%04x\n",(int)func,(int)BiosSelector); + LOG_MSG(" > STACK %04X %04X %04X %04X %04X %04X %04X %04X\n", + mem_readw(arg), mem_readw(arg+2), mem_readw(arg+4), mem_readw(arg+6), + mem_readw(arg+8), mem_readw(arg+10), mem_readw(arg+12), mem_readw(arg+14)); + + reg_ax = 0x84;/* BAD_PARAMETER */ + return 0; +} + +static Bitu ISAPNP_Handler_PM(void) { + return ISAPNP_Handler(true); +} + +static Bitu ISAPNP_Handler_RM(void) { + return ISAPNP_Handler(false); +} + +static Bitu INT70_Handler(void) { + /* Acknowledge irq with cmos */ + IO_Write(0x70,0xc); + IO_Read(0x71); + if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { + uint32_t count=mem_readd(BIOS_WAIT_FLAG_COUNT); + if (count>997) { + mem_writed(BIOS_WAIT_FLAG_COUNT,count-997); + } else { + mem_writed(BIOS_WAIT_FLAG_COUNT,0); + PhysPt where=Real2Phys(mem_readd(BIOS_WAIT_FLAG_POINTER)); + mem_writeb(where,mem_readb(where)|0x80); + mem_writeb(BIOS_WAIT_FLAG_ACTIVE,0); + mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(0,BIOS_WAIT_FLAG_TEMP)); + IO_Write(0x70,0xb); + IO_Write(0x71,IO_Read(0x71)&~0x40); + } + } + /* Signal EOI to both pics */ + IO_Write(0xa0,0x20); + IO_Write(0x20,0x20); + return 0; +} + +CALLBACK_HandlerObject* tandy_DAC_callback[2]; +static struct { + uint16_t port; + uint8_t irq; + uint8_t dma; +} tandy_sb; +static struct { + uint16_t port; + uint8_t irq; + uint8_t dma; +} tandy_dac; + +static bool Tandy_InitializeSB() { + /* see if soundblaster module available and at what port/IRQ/DMA */ + Bitu sbport, sbirq, sbdma; + if (SB_Get_Address(sbport, sbirq, sbdma)) { + tandy_sb.port=(uint16_t)(sbport&0xffff); + tandy_sb.irq =(uint8_t)(sbirq&0xff); + tandy_sb.dma =(uint8_t)(sbdma&0xff); + return true; + } else { + /* no soundblaster accessible, disable Tandy DAC */ + tandy_sb.port=0; + return false; + } +} + +static bool Tandy_InitializeTS() { + /* see if Tandy DAC module available and at what port/IRQ/DMA */ + Bitu tsport, tsirq, tsdma; + if (TS_Get_Address(tsport, tsirq, tsdma)) { + tandy_dac.port=(uint16_t)(tsport&0xffff); + tandy_dac.irq =(uint8_t)(tsirq&0xff); + tandy_dac.dma =(uint8_t)(tsdma&0xff); + return true; + } else { + /* no Tandy DAC accessible */ + tandy_dac.port=0; + return false; + } +} + +/* check if Tandy DAC is still playing */ +static bool Tandy_TransferInProgress(void) { + if (real_readw(0x40,0xd0)) return true; /* not yet done */ + if (real_readb(0x40,0xd4)==0xff) return false; /* still in init-state */ + + uint8_t tandy_dma = 1; + if (tandy_sb.port) tandy_dma = tandy_sb.dma; + else if (tandy_dac.port) tandy_dma = tandy_dac.dma; + + IO_Write(0x0c,0x00); + uint16_t datalen = (IO_ReadB(tandy_dma * 2 + 1)) + (IO_ReadB(tandy_dma * 2 + 1) << 8); + if (datalen==0xffff) return false; /* no DMA transfer */ + else if ((datalen<0x10) && (real_readb(0x40,0xd4)==0x0f) && (real_readw(0x40,0xd2)==0x1c)) { + /* stop already requested */ + return false; + } + return true; +} + +static void Tandy_SetupTransfer(PhysPt bufpt,bool isplayback) { + Bitu length=real_readw(0x40,0xd0); + if (length==0) return; /* nothing to do... */ + + if ((tandy_sb.port==0) && (tandy_dac.port==0)) return; + + uint8_t tandy_irq = 7; + if (tandy_sb.port) tandy_irq = tandy_sb.irq; + else if (tandy_dac.port) tandy_irq = tandy_dac.irq; + uint8_t tandy_irq_vector = tandy_irq; + if (tandy_irq_vector<8) tandy_irq_vector += 8; + else tandy_irq_vector += (0x70-8); + + /* revector IRQ-handler if necessary */ + RealPt current_irq=RealGetVec(tandy_irq_vector); + if (current_irq!=tandy_DAC_callback[0]->Get_RealPointer()) { + real_writed(0x40,0xd6,current_irq); + RealSetVec(tandy_irq_vector,tandy_DAC_callback[0]->Get_RealPointer()); + } + + uint8_t tandy_dma = 1; + if (tandy_sb.port) tandy_dma = tandy_sb.dma; + else if (tandy_dac.port) tandy_dma = tandy_dac.dma; + + if (tandy_sb.port) { + IO_Write(tandy_sb.port+0xcu,0xd0); /* stop DMA transfer */ + IO_Write(0x21,IO_Read(0x21)&(~(1u<>16u)&0xff); + IO_Write(tandy_dma*2u,(uint8_t)(bufpt&0xff)); + IO_Write(tandy_dma*2u,(uint8_t)((bufpt>>8u)&0xff)); + switch (tandy_dma) { + case 0: IO_Write(0x87,bufpage); break; + case 1: IO_Write(0x83,bufpage); break; + case 2: IO_Write(0x81,bufpage); break; + case 3: IO_Write(0x82,bufpage); break; + } + real_writeb(0x40,0xd4,bufpage); + + /* calculate transfer size (respects segment boundaries) */ + uint32_t tlength=length; + if (tlength+(bufpt&0xffff)>0x10000) tlength=0x10000-(bufpt&0xffff); + real_writew(0x40,0xd0,(uint16_t)(length-tlength)); /* remaining buffer length */ + tlength--; + + /* set transfer size */ + IO_Write(tandy_dma*2u+1u,(uint8_t)(tlength&0xffu)); + IO_Write(tandy_dma*2u+1u,(uint8_t)((tlength>>8u)&0xffu)); + + uint16_t delay=(uint16_t)(real_readw(0x40,0xd2)&0xfff); + uint8_t amplitude=(uint8_t)(((unsigned int)real_readw(0x40,0xd2)>>13u)&0x7u); + if (tandy_sb.port) { + IO_Write(0x0a,tandy_dma); /* enable DMA channel */ + /* set frequency */ + IO_Write(tandy_sb.port+0xcu,0x40); + IO_Write(tandy_sb.port+0xcu,256u - delay*100u/358u); + /* set playback type to 8bit */ + if (isplayback) IO_Write(tandy_sb.port+0xcu,0x14u); + else IO_Write(tandy_sb.port+0xcu,0x24u); + /* set transfer size */ + IO_Write(tandy_sb.port+0xcu,(uint8_t)(tlength&0xffu)); + IO_Write(tandy_sb.port+0xcu,(uint8_t)((tlength>>8)&0xffu)); + } else { + if (isplayback) IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x03u); + else IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x02u); + IO_Write(tandy_dac.port+2u,(uint8_t)(delay&0xffu)); + IO_Write(tandy_dac.port+3u,(uint8_t)((((unsigned int)delay>>8u)&0xfu) | ((unsigned int)amplitude<<5u))); + if (isplayback) IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7cu) | 0x1fu); + else IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7c) | 0x1e); + IO_Write(0x0a,tandy_dma); /* enable DMA channel */ + } + + if (!isplayback) { + /* mark transfer as recording operation */ + real_writew(0x40,0xd2,(uint16_t)(delay|0x1000)); + } +} + +static Bitu IRQ_TandyDAC(void) { + if (tandy_dac.port) { + IO_Read(tandy_dac.port); + } + if (real_readw(0x40,0xd0)) { /* play/record next buffer */ + /* acknowledge IRQ */ + IO_Write(0x20,0x20); + if (tandy_sb.port) { + IO_Read(tandy_sb.port+0xeu); + } + + /* buffer starts at the next page */ + uint8_t npage=real_readb(0x40,0xd4)+1u; + real_writeb(0x40,0xd4,npage); + + Bitu rb=real_readb(0x40,0xd3); + if (rb&0x10) { + /* start recording */ + real_writeb(0x40,0xd3,rb&0xefu); + Tandy_SetupTransfer((unsigned int)npage<<16u,false); + } else { + /* start playback */ + Tandy_SetupTransfer((unsigned int)npage<<16u,true); + } + } else { /* playing/recording is finished */ + uint8_t tandy_irq = 7u; + if (tandy_sb.port) tandy_irq = tandy_sb.irq; + else if (tandy_dac.port) tandy_irq = tandy_dac.irq; + uint8_t tandy_irq_vector = tandy_irq; + if (tandy_irq_vector<8u) tandy_irq_vector += 8u; + else tandy_irq_vector += (0x70u-8u); + + RealSetVec(tandy_irq_vector,real_readd(0x40,0xd6)); + + /* turn off speaker and acknowledge soundblaster IRQ */ + if (tandy_sb.port) { + IO_Write(tandy_sb.port+0xcu,0xd3u); + IO_Read(tandy_sb.port+0xeu); + } + + /* issue BIOS tandy sound device busy callout */ + SegSet16(cs, RealSeg(tandy_DAC_callback[1]->Get_RealPointer())); + reg_ip = RealOff(tandy_DAC_callback[1]->Get_RealPointer()); + } + return CBRET_NONE; +} + +static void TandyDAC_Handler(uint8_t tfunction) { + if ((!tandy_sb.port) && (!tandy_dac.port)) return; + switch (tfunction) { + case 0x81: /* Tandy sound system check */ + if (tandy_dac.port) { + reg_ax=tandy_dac.port; + } else { + reg_ax=0xc4; + } + CALLBACK_SCF(Tandy_TransferInProgress()); + break; + case 0x82: /* Tandy sound system start recording */ + case 0x83: /* Tandy sound system start playback */ + if (Tandy_TransferInProgress()) { + /* cannot play yet as the last transfer isn't finished yet */ + reg_ah=0x00; + CALLBACK_SCF(true); + break; + } + /* store buffer length */ + real_writew(0x40,0xd0,reg_cx); + /* store delay and volume */ + real_writew(0x40,0xd2,(reg_dx&0xfff)|((reg_al&7)<<13)); + Tandy_SetupTransfer(PhysMake(SegValue(es),reg_bx),reg_ah==0x83); + reg_ah=0x00; + CALLBACK_SCF(false); + break; + case 0x84: /* Tandy sound system stop playing */ + reg_ah=0x00; + + /* setup for a small buffer with silence */ + real_writew(0x40,0xd0,0x0a); + real_writew(0x40,0xd2,0x1c); + Tandy_SetupTransfer(PhysMake(0xf000,0xa084),true); + CALLBACK_SCF(false); + break; + case 0x85: /* Tandy sound system reset */ + if (tandy_dac.port) { + IO_Write(tandy_dac.port,(uint8_t)(IO_Read(tandy_dac.port)&0xe0)); + } + reg_ah=0x00; + CALLBACK_SCF(false); + break; + } +} + +extern bool date_host_forced; +static uint8_t ReadCmosByte (Bitu index) { + IO_Write(0x70, index); + return IO_Read(0x71); +} + +static void WriteCmosByte (Bitu index, Bitu val) { + IO_Write(0x70, index); + IO_Write(0x71, val); +} + +static bool RtcUpdateDone () { + while ((ReadCmosByte(0x0a) & 0x80) != 0) CALLBACK_Idle(); + return true; // cannot fail in DOSbox +} + +static void InitRtc () { + // Change the RTC to return BCD and set the 24h bit. Clear the SET bit. + // That's it. Do not change any other bits. + // + // Some games ("The Tales of Peter Rabbit") use the RTC clock periodic + // interrupt for timing and music at rates other than 1024Hz and we must + // not change that rate nor clear any interrupt enable bits. Do not clear + // pending interrupts, either! The periodic interrupt does not affect reading + // the RTC clock. The point of this function and INT 15h code calling this + // function is to read the clock. + WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x7du/*clear=SET[7]|DM[2]*/) | 0x03u/*set=24/12[1]|DSE[0]*/); +} + +static Bitu INT1A_Handler(void) { + CALLBACK_SIF(true); + switch (reg_ah) { + case 0x00: /* Get System time */ + { + uint32_t ticks=mem_readd(BIOS_TIMER); + reg_al=mem_readb(BIOS_24_HOURS_FLAG); + mem_writeb(BIOS_24_HOURS_FLAG,0); // reset the "flag" + reg_cx=(uint16_t)(ticks >> 16u); + reg_dx=(uint16_t)(ticks & 0xffff); + break; + } + case 0x01: /* Set System time */ + mem_writed(BIOS_TIMER,((unsigned int)reg_cx<<16u)|reg_dx); + break; + case 0x02: /* GET REAL-TIME CLOCK TIME (AT,XT286,PS) */ + InitRtc(); // make sure BCD and no am/pm + if (RtcUpdateDone()) { // make sure it's safe to read + reg_ch = ReadCmosByte(0x04); // hours + reg_cl = ReadCmosByte(0x02); // minutes + reg_dh = ReadCmosByte(0x00); // seconds + reg_dl = ReadCmosByte(0x0b) & 0x01; // daylight saving time + /* 2023/10/06 - Let interrupts and CPU cycles catch up and the RTC clock a chance to tick. This is needed for + * "Pizza Tycoon" which appears to start by running in a loop reading time from the BIOS and writing + * time to INT 21h in a loop until the second value changes. */ + for (unsigned int c=0;c < 4;c++) CALLBACK_Idle(); + } + CALLBACK_SCF(false); + break; + case 0x03: // set RTC time + InitRtc(); // make sure BCD and no am/pm + if (RtcUpdateDone()) { // make sure it's safe to read + WriteCmosByte(0x0b, ReadCmosByte(0x0b) | 0x80u); // prohibit updates + WriteCmosByte(0x04, reg_ch); // hours + WriteCmosByte(0x02, reg_cl); // minutes + WriteCmosByte(0x00, reg_dh); // seconds + WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x7eu) | (reg_dh & 0x01u)); // dst + implicitly allow updates + /* 2023/10/06 - Let interrupts and CPU cycles catch up and the RTC clock a chance to tick. This is needed for + * "Pizza Tycoon" which appears to start by running in a loop reading time from the BIOS and writing + * time to INT 21h in a loop until the second value changes. */ + for (unsigned int c=0;c < 4;c++) CALLBACK_Idle(); + } + break; + case 0x04: /* GET REAL-TIME ClOCK DATE (AT,XT286,PS) */ + InitRtc(); // make sure BCD and no am/pm + if (RtcUpdateDone()) { // make sure it's safe to read + reg_ch = ReadCmosByte(0x32); // century + reg_cl = ReadCmosByte(0x09); // year + reg_dh = ReadCmosByte(0x08); // month + reg_dl = ReadCmosByte(0x07); // day + /* 2023/10/06 - Let interrupts and CPU cycles catch up and the RTC clock a chance to tick. This is needed for + * "Pizza Tycoon" which appears to start by running in a loop reading time from the BIOS and writing + * time to INT 21h in a loop until the second value changes. */ + for (unsigned int c=0;c < 4;c++) CALLBACK_Idle(); + } + CALLBACK_SCF(false); + break; + case 0x05: // set RTC date + InitRtc(); // make sure BCD and no am/pm + if (RtcUpdateDone()) { // make sure it's safe to read + WriteCmosByte(0x0b, ReadCmosByte(0x0b) | 0x80); // prohibit updates + WriteCmosByte(0x32, reg_ch); // century + WriteCmosByte(0x09, reg_cl); // year + WriteCmosByte(0x08, reg_dh); // month + WriteCmosByte(0x07, reg_dl); // day + WriteCmosByte(0x0b, (ReadCmosByte(0x0b) & 0x7f)); // allow updates + /* 2023/10/06 - Let interrupts and CPU cycles catch up and the RTC clock a chance to tick. This is needed for + * "Pizza Tycoon" which appears to start by running in a loop reading time from the BIOS and writing + * time to INT 21h in a loop until the second value changes. */ + for (unsigned int c=0;c < 4;c++) CALLBACK_Idle(); + } + break; + case 0x80: /* Pcjr Setup Sound Multiplexer */ + LOG(LOG_BIOS,LOG_ERROR)("INT1A:80:Setup tandy sound multiplexer to %d",reg_al); + break; + case 0x81: /* Tandy sound system check */ + case 0x82: /* Tandy sound system start recording */ + case 0x83: /* Tandy sound system start playback */ + case 0x84: /* Tandy sound system stop playing */ + case 0x85: /* Tandy sound system reset */ + TandyDAC_Handler(reg_ah); + break; + case 0xb1: /* PCI Bios Calls */ + if (pcibus_enable) { + LOG(LOG_BIOS,LOG_WARN)("INT1A:PCI bios call %2X",reg_al); + switch (reg_al) { + case 0x01: // installation check + if (PCI_IsInitialized()) { + reg_ah=0x00; + reg_al=0x01; // cfg space mechanism 1 supported + reg_bx=0x0210; // ver 2.10 + reg_cx=0x0000; // only one PCI bus + reg_edx=0x20494350; + reg_edi=PCI_GetPModeInterface(); + CALLBACK_SCF(false); + } else { + CALLBACK_SCF(true); + } + break; + case 0x02: { // find device + Bitu devnr=0u; + Bitu count=0x100u; + uint32_t devicetag=((unsigned int)reg_cx<<16u)|reg_dx; + Bits found=-1; + for (Bitu i=0; i<=count; i++) { + IO_WriteD(0xcf8,0x80000000u|(i<<8u)); // query unique device/subdevice entries + if (IO_ReadD(0xcfc)==devicetag) { + if (devnr==reg_si) { + found=(Bits)i; + break; + } else { + // device found, but not the SIth device + devnr++; + } + } + } + if (found>=0) { + reg_ah=0x00; + reg_bh=0x00; // bus 0 + reg_bl=(uint8_t)(found&0xff); + CALLBACK_SCF(false); + } else { + reg_ah=0x86; // device not found + CALLBACK_SCF(true); + } + } + break; + case 0x03: { // find device by class code + Bitu devnr=0; + Bitu count=0x100u; + uint32_t classtag=reg_ecx&0xffffffu; + Bits found=-1; + for (Bitu i=0; i<=count; i++) { + IO_WriteD(0xcf8,0x80000000u|(i<<8u)); // query unique device/subdevice entries + if (IO_ReadD(0xcfc)!=0xffffffffu) { + IO_WriteD(0xcf8,0x80000000u|(i<<8u)|0x08u); + if ((IO_ReadD(0xcfc)>>8u)==classtag) { + if (devnr==reg_si) { + found=(Bits)i; + break; + } else { + // device found, but not the SIth device + devnr++; + } + } + } + } + if (found>=0) { + reg_ah=0x00; + reg_bh=0x00; // bus 0 + reg_bl=(uint8_t)found & 0xffu; + CALLBACK_SCF(false); + } else { + reg_ah=0x86; // device not found + CALLBACK_SCF(true); + } + } + break; + case 0x08: // read configuration byte + IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); + reg_cl=IO_ReadB(0xcfc+(reg_di&3u)); + CALLBACK_SCF(false); + reg_ah=0x00; + break; + case 0x09: // read configuration word + IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); + reg_cx=IO_ReadW(0xcfc+(reg_di&2u)); + CALLBACK_SCF(false); + reg_ah=0x00; + break; + case 0x0a: // read configuration dword + IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); + reg_ecx=IO_ReadD(0xcfc+(reg_di&3u)); + CALLBACK_SCF(false); + reg_ah=0x00; + break; + case 0x0b: // write configuration byte + IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); + IO_WriteB(0xcfc+(reg_di&3u),reg_cl); + CALLBACK_SCF(false); + reg_ah=0x00; + break; + case 0x0c: // write configuration word + IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); + IO_WriteW(0xcfc+(reg_di&2u),reg_cx); + CALLBACK_SCF(false); + reg_ah=0x00; + break; + case 0x0d: // write configuration dword + IO_WriteD(0xcf8,0x80000000u|((unsigned int)reg_bx<<8u)|(reg_di&0xfcu)); + IO_WriteD(0xcfc+((unsigned int)reg_di&3u),reg_ecx); + CALLBACK_SCF(false); + reg_ah=0x00; + break; + default: + LOG(LOG_BIOS,LOG_ERROR)("INT1A:PCI BIOS: unknown function %x (%x %x %x)", + reg_ax,reg_bx,reg_cx,reg_dx); + CALLBACK_SCF(true); + break; + } + } + else { + CALLBACK_SCF(true); + } + break; + default: + LOG(LOG_BIOS,LOG_ERROR)("INT1A:Undefined call %2X",reg_ah); + } + return CBRET_NONE; +} + +bool INT16_get_key(uint16_t &code); +bool INT16_peek_key(uint16_t &code); + +extern uint8_t GDC_display_plane; +extern uint8_t GDC_display_plane_pending; +extern bool GDC_vsync_interrupt; + +unsigned char prev_pc98_mode42 = 0; + +unsigned char pc98_function_row_mode = 0; + +const char *pc98_func_key_default[10] = { + " C1 ", + " CU ", + " CA ", + " S1 ", + " SU ", + + "VOID ", + "NWL ", + "INS ", + "REP ", + " ^Z " +}; + +const char pc98_func_key_escapes_default[10][3] = { + {0x1B,0x53,0}, // F1 + {0x1B,0x54,0}, // F2 + {0x1B,0x55,0}, // F3 + {0x1B,0x56,0}, // F4 + {0x1B,0x57,0}, // F5 + {0x1B,0x45,0}, // F6 + {0x1B,0x4A,0}, // F7 + {0x1B,0x50,0}, // F8 + {0x1B,0x51,0}, // F9 + {0x1B,0x5A,0} // F10 +}; + +const char pc98_editor_key_escapes_default[11][3] = { + {0}, // ROLL UP 0x36 + {0}, // ROLL DOWN 0x37 + {0x1B,0x50,0}, // INS 0x38 + {0x1B,0x44,0}, // DEL 0x39 + {0x0B,0}, // UP ARROW 0x3A + {0x08,0}, // LEFT ARROW 0x3B + {0x0C,0}, // RIGHT ARROW 0x3C + {0x0A,0}, // DOWN ARROW 0x3D + {0}, // HOME/CLR 0x3E + {0}, // HELP 0x3F + {0} // KEYPAD - 0x40 +}; + +// shortcuts offered by SHIFT F1-F10. You can bring this onscreen using CTRL+F7. This row shows '*' in col 2. +// The text displayed onscreen is obviously just the first 6 chars of the shortcut text. +const char *pc98_shcut_key_defaults[10] = { + "dir a:\x0D", + "dir b:\x0D", + "copy ", + "del ", + "ren ", + + "chkdsk a:\x0D", + "chkdsk b:\x0D", + "type ", + "date\x0D", + "time\x0D" +}; + +#pragma pack(push,1) +struct pc98_func_key_shortcut_def { + unsigned char length; /* +0x00 length of text */ + unsigned char shortcut[0x0F]; /* +0x01 Shortcut text to insert into CON device */ + + std::string getShortcutText(void) const { + std::string ret; + unsigned int i; + + /* Whether a shortcut or escape (0xFE or not) the first 6 chars are displayed always */ + /* TODO: Strings for display are expected to display as Shift-JIS, convert to UTF-8 for display on host */ + for (i=0;i < 0x0F;i++) { + if (shortcut[i] == 0u) + break; + else if (shortcut[i] == 0x1B) { + ret += ""; + } + else if (shortcut[i] > 0x7Fu || shortcut[i] < 32u) /* 0xFE is invisible on real hardware */ + ret += ' '; + else + ret += (char)shortcut[i]; + } + + return ret; + } + + std::string getDisplayText(void) const { + unsigned int i; + char tmp[8]; + + /* Whether a shortcut or escape (0xFE or not) the first 6 chars are displayed always */ + /* TODO: Strings for display are expected to display as Shift-JIS, convert to UTF-8 for display on host */ + for (i=0;i < 6;i++) { + if (shortcut[i] == 0u) + break; + else if (shortcut[i] > 0x7Fu || shortcut[i] < 32u) /* 0xFE is invisible on real hardware */ + tmp[i] = ' '; + else + tmp[i] = (char)shortcut[i]; + } + tmp[i] = 0; + + return tmp; + } + + std::string debugToString(void) const { + std::string ret; + char tmp[512]; + + if (length == 0) + return "(none)"; + + if (shortcut[0] == 0xFE) { + sprintf(tmp,"disp=\"%s\" ",getDisplayText().c_str()); + ret += tmp; + + ret += "dispraw={ "; + for (unsigned int i=0;i < 6;i++) { + sprintf(tmp,"%02x ",shortcut[i]); + ret += tmp; + } + ret += "} "; + + ret += "esc={ "; + for (unsigned int i=6;i < length;i++) { + sprintf(tmp,"%02x ",shortcut[i]); + ret += tmp; + } + ret += "}"; + } + else { + sprintf(tmp,"text=\"%s\" ",getShortcutText().c_str()); + ret += tmp; + + ret += "esc={ "; + for (unsigned int i=0;i < length;i++) { + sprintf(tmp,"%02x ",shortcut[i]); + ret += tmp; + } + ret += "}"; + } + + return ret; + } + + // set shortcut. + // usually a direct string to insert. + void set_shortcut(const char *str) { + unsigned int i=0; + char c; + + while (i < 0x0F && (c = *str++) != 0) shortcut[i++] = (unsigned char)c; + length = i; + + while (i < 0x0F) shortcut[i++] = 0; + } + + // set text and escape code. text does NOT include the leading 0xFE char. + void set_text_and_escape(const char *text,const char *escape) { + unsigned int i=1; + char c; + + // this is based on observed MS-DOS behavior on PC-98. + // the length byte covers both the display text and escape code (sum of the two). + // the first byte of the shortcut is 0xFE which apparently means the next 5 chars + // are text to display. The 0xFE is copied as-is to the display when rendered. + // 0xFE in the CG ROM is a blank space. + shortcut[0] = 0xFE; + while (i < 6 && (c = *text++) != 0) shortcut[i++] = (unsigned char)c; + while (i < 6) shortcut[i++] = ' '; + + while (i < 0x0F && (c = *escape++) != 0) shortcut[i++] = (unsigned char)c; + length = i; + while (i < 0x0F) shortcut[i++] = 0; + } +}; /* =0x10 */ +#pragma pack(pop) + +struct pc98_func_key_shortcut_def pc98_func_key[10]; /* F1-F10 */ +struct pc98_func_key_shortcut_def pc98_vfunc_key[5]; /* VF1-VF5 */ +struct pc98_func_key_shortcut_def pc98_func_key_shortcut[10]; /* Shift+F1 - Shift-F10 */ +struct pc98_func_key_shortcut_def pc98_vfunc_key_shortcut[5]; /* Shift+VF1 - Shift-VF5 */ +struct pc98_func_key_shortcut_def pc98_func_key_ctrl[10]; /* Control+F1 - Control-F10 */ +struct pc98_func_key_shortcut_def pc98_vfunc_key_ctrl[5]; /* Control+VF1 - Control-VF5 */ +struct pc98_func_key_shortcut_def pc98_editor_key_escapes[11]; /* Editor keys */ + +// FIXME: This is STUPID. Cleanup is needed in order to properly use std::min without causing grief. +#ifdef _MSC_VER +# define MIN(a,b) ((a) < (b) ? (a) : (b)) +# define MAX(a,b) ((a) > (b) ? (a) : (b)) +#else +# define MIN(a,b) std::min(a,b) +# define MAX(a,b) std::max(a,b) +#endif + +void PC98_GetFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i,const struct pc98_func_key_shortcut_def *keylist) { + if (i >= 1 && i <= 10) { + const pc98_func_key_shortcut_def &def = keylist[i-1u]; + unsigned int j=0,o=0; + + /* if the shortcut starts with 0xFE then the next 5 chars are intended for display only + * and the shortcut starts after that. Else the entire string is stuffed into the CON + * device. */ + if (def.shortcut[0] == 0xFE) + j = 6; + + while (j < MIN(0x0Fu,(unsigned int)def.length)) + buf[o++] = def.shortcut[j++]; + + len = (size_t)o; + buf[o] = 0; + } + else { + len = 0; + buf[0] = 0; + } +} + +void PC98_GetEditorKeyEscape(size_t &len,unsigned char buf[16],const unsigned int scan) { + if (scan >= 0x36 && scan <= 0x40) { + const pc98_func_key_shortcut_def &def = pc98_editor_key_escapes[scan-0x36]; + unsigned int j=0,o=0; + + while (j < MIN(0x05u,(unsigned int)def.length)) + buf[o++] = def.shortcut[j++]; + + len = (size_t)o; + buf[o] = 0; + } + else { + len = 0; + buf[0] = 0; + } +} + +void PC98_GetVFKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i,const struct pc98_func_key_shortcut_def *keylist) { + if (i >= 1 && i <= 5) { + const pc98_func_key_shortcut_def &def = keylist[i-1]; + unsigned int j=0,o=0; + + /* if the shortcut starts with 0xFE then the next 5 chars are intended for display only + * and the shortcut starts after that. Else the entire string is stuffed into the CON + * device. */ + if (def.shortcut[0] == 0xFE) + j = 6; + + while (j < MIN(0x0Fu,(unsigned int)def.length)) + buf[o++] = def.shortcut[j++]; + + len = (size_t)o; + buf[o] = 0; + } + else { + len = 0; + buf[0] = 0; + } +} + +void PC98_GetFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { + PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key); +} + +void PC98_GetShiftFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { + PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key_shortcut); +} + +void PC98_GetCtrlFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { + PC98_GetFuncKeyEscape(len,buf,i,pc98_func_key_ctrl); +} + +void PC98_GetVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { + PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key); +} + +void PC98_GetShiftVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { + PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key_shortcut); +} + +void PC98_GetCtrlVFuncKeyEscape(size_t &len,unsigned char buf[16],const unsigned int i) { + PC98_GetVFKeyEscape(len,buf,i,pc98_vfunc_key_ctrl); +} + +void PC98_InitDefFuncRow(void) { + for (unsigned int i=0;i < 10;i++) { + pc98_func_key_shortcut_def &def = pc98_func_key[i]; + + def.set_text_and_escape(pc98_func_key_default[i],pc98_func_key_escapes_default[i]); + } + for (unsigned int i=0;i < 10;i++) { + pc98_func_key_shortcut_def &def = pc98_func_key_shortcut[i]; + + def.set_shortcut(pc98_shcut_key_defaults[i]); + } + for (unsigned int i=0;i < 11;i++) { + pc98_func_key_shortcut_def &def = pc98_editor_key_escapes[i]; + + def.set_shortcut(pc98_editor_key_escapes_default[i]); + } + for (unsigned int i=0;i < 10;i++) { + pc98_func_key_shortcut_def &def = pc98_func_key_ctrl[i]; + + def.set_shortcut(""); + } + /* MS-DOS by default does not assign the VFn keys anything */ + for (unsigned int i=0;i < 5;i++) { + pc98_func_key_shortcut_def &def = pc98_vfunc_key[i]; + + def.set_shortcut(""); + } + for (unsigned int i=0;i < 5;i++) { + pc98_func_key_shortcut_def &def = pc98_vfunc_key_shortcut[i]; + + def.set_shortcut(""); + } + for (unsigned int i=0;i < 5;i++) { + pc98_func_key_shortcut_def &def = pc98_vfunc_key_ctrl[i]; + + def.set_shortcut(""); + } +} + +#include "int10.h" + +void draw_pc98_function_row_elem(unsigned int o, unsigned int co, const struct pc98_func_key_shortcut_def& key) { + const unsigned char *str = key.shortcut; + unsigned int j = 0,i = 0; + + // NTS: Some shortcut strings start with 0xFE, which is rendered as an invisible space anyway. + + // NTS: Apparently the strings are Shift-JIS and expected to render to the function key row + // the same way the console normally does it. + ShiftJISDecoder sjis; + + while (j < 6u && str[i] != 0) { + if (sjis.take(str[i++])) { + if (sjis.doublewide) { + /* JIS conversion to WORD value appropriate for text RAM */ + if (sjis.b2 != 0) sjis.b1 -= 0x20; + + uint16_t w = (sjis.b2 << 8) + sjis.b1; + mem_writew(0xA0000+((o+co+j)*2u),w); + mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible + j++; + mem_writew(0xA0000+((o+co+j)*2u),w); + mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible + j++; + } + else { + mem_writew(0xA0000+((o+co+j)*2u),str[j]); + mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible + j++; + } + } + } + + while (j < 6u) { + mem_writew(0xA0000+((o+co+j)*2u),(unsigned char)(' ')); + mem_writeb(0xA2000+((o+co+j)*2u),0xE5); // white reverse visible + j++; + } +} + +void draw_pc98_function_row(unsigned int o, const struct pc98_func_key_shortcut_def* keylist) { + mem_writew(0xA0000+((o+1)*2),real_readb(0x60,0x8B)); + mem_writeb(0xA2000+((o+1)*2),0xE1); + for (unsigned int i=0u;i < 5u;i++) + draw_pc98_function_row_elem(o,4u + (i * 7u),keylist[i]); + for (unsigned int i=5u;i < 10u;i++) + draw_pc98_function_row_elem(o,42u + ((i - 5u) * 7u),keylist[i]); +} + +unsigned int pc98_DOS_console_rows(void) { + uint8_t b = real_readb(0x60,0x113); + + return (b & 0x01) ? 25 : 20; +} + +void update_pc98_function_row(unsigned char setting,bool force_redraw) { + if (!force_redraw && pc98_function_row_mode == setting) return; + pc98_function_row_mode = setting; + + unsigned int total_rows = pc98_DOS_console_rows(); + unsigned char c = real_readb(0x60,0x11C); + unsigned char r = real_readb(0x60,0x110); + unsigned int o = 80 * (total_rows - 1); + + if (pc98_function_row_mode != 0) { + if (r > (total_rows - 2)) { + r = (total_rows - 2); + void INTDC_CL10h_AH04h(void); + INTDC_CL10h_AH04h(); + } + } + + /* update mode 2 indicator */ + real_writeb(0x60,0x8C,(pc98_function_row_mode == 2) ? '*' : ' '); + + real_writeb(0x60,0x112,total_rows - 1 - ((pc98_function_row_mode != 0) ? 1 : 0)); + + if (pc98_function_row_mode == 2) { + /* draw the function row. + * based on real hardware: + * + * The function key is 72 chars wide. 4 blank chars on each side of the screen. + * It is divided into two halves, 36 chars each. + * Within each half, aligned to its side, is 5 x 7 regions. + * 6 of the 7 are inverted. centered in the white block is the function key. */ + for (unsigned int i=0;i < 40;) { + mem_writew(0xA0000+((o+i)*2),0x0000); + mem_writeb(0xA2000+((o+i)*2),0xE1); + + mem_writew(0xA0000+((o+(79-i))*2),0x0000); + mem_writeb(0xA2000+((o+(79-i))*2),0xE1); + + if (i >= 3 && i < 38) + i += 7; + else + i++; + } + + mem_writew(0xA0000+((o+2)*2),real_readb(0x60,0x8C)); + mem_writeb(0xA2000+((o+2)*2),0xE1); + + draw_pc98_function_row(o,pc98_func_key_shortcut); + } + else if (pc98_function_row_mode == 1) { + /* draw the function row. + * based on real hardware: + * + * The function key is 72 chars wide. 4 blank chars on each side of the screen. + * It is divided into two halves, 36 chars each. + * Within each half, aligned to its side, is 5 x 7 regions. + * 6 of the 7 are inverted. centered in the white block is the function key. */ + for (unsigned int i=0;i < 40;) { + mem_writew(0xA0000+((o+i)*2),0x0000); + mem_writeb(0xA2000+((o+i)*2),0xE1); + + mem_writew(0xA0000+((o+(79-i))*2),0x0000); + mem_writeb(0xA2000+((o+(79-i))*2),0xE1); + + if (i >= 3 && i < 38) + i += 7; + else + i++; + } + + draw_pc98_function_row(o,pc98_func_key); + } + else { + /* erase the function row */ + for (unsigned int i=0;i < 80;i++) { + mem_writew(0xA0000+((o+i)*2),0x0000); + mem_writeb(0xA2000+((o+i)*2),0xE1); + } + } + + real_writeb(0x60,0x11C,c); + real_writeb(0x60,0x110,r); + + real_writeb(0x60,0x111,(pc98_function_row_mode != 0) ? 0x01 : 0x00);/* function key row display status */ + + void vga_pc98_direct_cursor_pos(uint16_t address); + vga_pc98_direct_cursor_pos((r*80)+c); +} + +void pc98_function_row_user_toggle(void) { + if (pc98_function_row_mode >= 2) + update_pc98_function_row(0,true); + else + update_pc98_function_row(pc98_function_row_mode+1,true); +} + +void pc98_set_char_mode(bool mode) { + real_writeb(0x60,0x8A,mode); + real_writeb(0x60,0x8B,(mode == true) ? ' ' : 'g'); + update_pc98_function_row(pc98_function_row_mode,true); +} + +void pc98_toggle_char_mode(void) { + pc98_set_char_mode(!real_readb(0x60,0x8A)); +} + +void pc98_set_digpal_entry(unsigned char ent,unsigned char grb); +void PC98_show_cursor(bool show); + +extern bool gdc_5mhz_mode; +extern bool enable_pc98_egc; +extern bool enable_pc98_grcg; +extern bool enable_pc98_16color; +extern bool enable_pc98_256color; +extern bool enable_pc98_188usermod; +extern bool pc98_31khz_mode; +extern bool pc98_attr4_graphic; + +extern unsigned char pc98_text_first_row_scanline_start; /* port 70h */ +extern unsigned char pc98_text_first_row_scanline_end; /* port 72h */ +extern unsigned char pc98_text_row_scanline_blank_at; /* port 74h */ +extern unsigned char pc98_text_row_scroll_lines; /* port 76h */ +extern unsigned char pc98_text_row_scroll_count_start; /* port 78h */ +extern unsigned char pc98_text_row_scroll_num_lines; /* port 7Ah */ + +void pc98_update_text_layer_lineheight_from_bda(void) { +// unsigned char c = mem_readb(0x53C); + unsigned char lineheight = mem_readb(0x53B) + 1; + + pc98_gdc[GDC_MASTER].force_fifo_complete(); + pc98_gdc[GDC_MASTER].row_height = lineheight; + + if (lineheight > 20) { // usually 24 + pc98_text_first_row_scanline_start = 0x1C; + pc98_text_first_row_scanline_end = lineheight - 5; + pc98_text_row_scanline_blank_at = 16; + } + else if (lineheight > 16) { // usually 20 + pc98_text_first_row_scanline_start = 0x1E; + pc98_text_first_row_scanline_end = lineheight - 3; + pc98_text_row_scanline_blank_at = 16; + } + else { + pc98_text_first_row_scanline_start = 0; + pc98_text_first_row_scanline_end = lineheight - 1; + pc98_text_row_scanline_blank_at = lineheight; + } + + pc98_text_row_scroll_lines = 0; + pc98_text_row_scroll_count_start = 0; + pc98_text_row_scroll_num_lines = 0; + + vga.crtc.cursor_start = 0; + vga.draw.cursor.sline = 0; + + vga.crtc.cursor_end = lineheight - 1; + vga.draw.cursor.eline = lineheight - 1; +} + +void pc98_update_text_lineheight_from_bda(void) { + unsigned char b597 = mem_readb(0x597); + unsigned char c = mem_readb(0x53C); + unsigned char lineheight; + + if ((b597 & 0x3) == 0x3) {//WARNING: This could be wrong + if (c & 0x10)/*30-line mode (30x16 = 640x480)*/ + lineheight = 16; + else if (c & 0x01)/*20-line mode (20x24 = 640x480)*/ + lineheight = 24; + else/*25-line mode (25x19 = 640x480)*/ + lineheight = 19; + } + else { + if (c & 0x10)/*30-line mode (30x13 = 640x400)*/ + lineheight = 13;//?? + else if (c & 0x01)/*20-line mode (20x20 = 640x400)*/ + lineheight = 20; + else/*25-line mode (25x16 = 640x400)*/ + lineheight = 16; + } + + mem_writeb(0x53B,lineheight - 1); +} + +static const uint8_t pc98_katakana6x8_font[] = { + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x50,0x20,0x00, + 0x70,0x40,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x1c,0x00, + 0x00,0x00,0x00,0x00,0x40,0x20,0x10,0x00,0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x00, + 0x7c,0x04,0x7c,0x04,0x04,0x08,0x30,0x00,0x00,0x00,0x7c,0x14,0x18,0x10,0x20,0x00, + 0x00,0x00,0x04,0x08,0x18,0x28,0x08,0x00,0x00,0x00,0x10,0x7c,0x44,0x04,0x18,0x00, + 0x00,0x00,0x00,0x38,0x10,0x10,0x7c,0x00,0x00,0x00,0x08,0x7c,0x18,0x28,0x48,0x00, + 0x00,0x00,0x20,0x7c,0x24,0x28,0x20,0x00,0x00,0x00,0x00,0x38,0x08,0x08,0x7c,0x00, + 0x00,0x00,0x3c,0x04,0x3c,0x04,0x3c,0x00,0x00,0x00,0x00,0x54,0x54,0x04,0x18,0x00, + 0x00,0x00,0x00,0x7c,0x00,0x00,0x00,0x00,0x7c,0x04,0x14,0x18,0x10,0x20,0x40,0x00, + 0x04,0x08,0x10,0x30,0x50,0x10,0x10,0x00,0x10,0x7c,0x44,0x44,0x04,0x08,0x10,0x00, + 0x00,0x7c,0x10,0x10,0x10,0x10,0x7c,0x00,0x08,0x7c,0x18,0x28,0x48,0x08,0x08,0x00, + 0x20,0x7c,0x24,0x24,0x24,0x44,0x08,0x00,0x10,0x7c,0x10,0x7c,0x10,0x10,0x10,0x00, + 0x3c,0x24,0x44,0x04,0x04,0x08,0x30,0x00,0x20,0x3c,0x28,0x48,0x08,0x08,0x30,0x00, + 0x00,0x7c,0x04,0x04,0x04,0x04,0x7c,0x00,0x28,0x28,0x7c,0x28,0x08,0x10,0x20,0x00, + 0x60,0x00,0x64,0x04,0x04,0x08,0x70,0x00,0x7c,0x04,0x04,0x08,0x10,0x28,0x44,0x00, + 0x20,0x7c,0x24,0x28,0x20,0x20,0x18,0x00,0x44,0x44,0x24,0x04,0x04,0x08,0x30,0x00, + 0x3c,0x24,0x34,0x4c,0x04,0x08,0x30,0x00,0x08,0x70,0x10,0x7c,0x10,0x10,0x20,0x00, + 0x54,0x54,0x54,0x04,0x08,0x08,0x30,0x00,0x38,0x00,0x7c,0x10,0x10,0x10,0x20,0x00, + 0x20,0x20,0x20,0x38,0x24,0x20,0x20,0x00,0x10,0x10,0x7c,0x10,0x10,0x20,0x40,0x00, + 0x00,0x38,0x00,0x00,0x00,0x00,0x7c,0x00,0x7c,0x04,0x04,0x28,0x10,0x28,0x40,0x00, + 0x10,0x7c,0x08,0x10,0x38,0x54,0x10,0x00,0x04,0x04,0x04,0x04,0x08,0x10,0x20,0x00, + 0x10,0x08,0x04,0x44,0x44,0x44,0x44,0x00,0x40,0x4c,0x70,0x40,0x40,0x40,0x3c,0x00, + 0x7c,0x04,0x04,0x04,0x04,0x08,0x30,0x00,0x00,0x20,0x50,0x08,0x04,0x04,0x00,0x00, + 0x10,0x7c,0x10,0x10,0x54,0x54,0x10,0x00,0x00,0x7c,0x04,0x04,0x28,0x10,0x08,0x00, + 0x00,0x38,0x00,0x38,0x00,0x38,0x04,0x00,0x10,0x10,0x20,0x40,0x44,0x7c,0x04,0x00, + 0x04,0x04,0x28,0x10,0x28,0x40,0x00,0x00,0x7c,0x10,0x7c,0x10,0x10,0x10,0x0c,0x00, + 0x20,0x7c,0x24,0x24,0x28,0x20,0x20,0x00,0x00,0x38,0x08,0x08,0x08,0x08,0x7c,0x00, + 0x7c,0x04,0x04,0x7c,0x04,0x04,0x7c,0x00,0x38,0x00,0x7c,0x04,0x04,0x08,0x30,0x00, + 0x24,0x24,0x24,0x04,0x04,0x08,0x10,0x00,0x10,0x50,0x50,0x50,0x54,0x58,0x10,0x00, + 0x20,0x20,0x20,0x24,0x24,0x28,0x30,0x00,0x7c,0x44,0x44,0x44,0x44,0x44,0x7c,0x00, + 0x7c,0x44,0x44,0x04,0x04,0x08,0x10,0x00,0x60,0x00,0x04,0x04,0x08,0x10,0x60,0x00, + 0x20,0x10,0x40,0x20,0x00,0x00,0x00,0x00,0x00,0x20,0x50,0x20,0x00,0x00,0x00,0x00 +}; + +unsigned char byte_reverse(unsigned char c); + +static void PC98_INT18_DrawShape(void) +{ + PhysPt ucw; + uint8_t type, dir; + uint16_t x1, y1; + uint16_t ead, dad; + uint16_t dc, d, d2, dm; + + ucw = SegPhys(ds) + reg_bx; + type = mem_readb(ucw + 0x28); + dir = mem_readb(ucw + 0x03); + x1 = mem_readw(ucw + 0x08); + y1 = mem_readw(ucw + 0x0a); + if((reg_ch & 0xc0) == 0x40) { + y1 += 200; + } + ead = (y1 * 40) + (x1 >> 4); + dad = x1 % 16; + // line pattern + pc98_gdc[GDC_SLAVE].set_textw(((uint16_t)byte_reverse(mem_readb(ucw + 0x20)) << 8) | byte_reverse(mem_readb(ucw + 0x21))); + if(type == 0x04) { + // arc + dc = mem_readw(ucw + 0x0c); + d = mem_readw(ucw + 0x1c) - 1; + d2 = d >> 1; + dm = mem_readw(ucw + 0x1a); + if((reg_ch & 0x30) == 0x30) { + uint8_t plane = mem_readb(ucw + 0x00); + uint32_t offset = 0x4000; + for(uint8_t bit = 1 ; bit <= 4 ; bit <<= 1) { + pc98_gdc[GDC_SLAVE].set_mode((plane & bit) ? 0x03 : 0x02); + pc98_gdc[GDC_SLAVE].set_vectw(0x20, dir, dc, d, d2, 0x3fff, dm); + pc98_gdc[GDC_SLAVE].set_csrw(offset + ead, dad); + pc98_gdc[GDC_SLAVE].exec(0x6c); + offset += 0x4000; + } + } else { + pc98_gdc[GDC_SLAVE].set_mode(mem_readb(ucw + 0x02)); + pc98_gdc[GDC_SLAVE].set_vectw(0x20, dir, dc, d, d2, 0x3fff, dm); + pc98_gdc[GDC_SLAVE].set_csrw(0x4000 + ((reg_ch & 0x30) << 10) + ead, dad); + pc98_gdc[GDC_SLAVE].exec(0x6c); + } + } else { + uint16_t x2, y2, temp; + x2 = mem_readw(ucw + 0x16); + y2 = mem_readw(ucw + 0x18); + if(type == 0x01) { + // line + if((reg_ch & 0x30) == 0x30) { + uint8_t plane = mem_readb(ucw + 0x00); + uint32_t offset = 0x4000; + for(uint8_t bit = 1 ; bit <= 4 ; bit <<= 1) { + pc98_gdc[GDC_SLAVE].set_mode((plane & bit) ? 0x03 : 0x02); + pc98_gdc[GDC_SLAVE].set_vectl(x1, y1, x2, y2); + pc98_gdc[GDC_SLAVE].set_csrw(offset + ead, dad); + pc98_gdc[GDC_SLAVE].exec(0x6c); + offset += 0x4000; + } + } else { + pc98_gdc[GDC_SLAVE].set_mode(mem_readb(ucw + 0x02)); + pc98_gdc[GDC_SLAVE].set_vectl(x1, y1, x2, y2); + pc98_gdc[GDC_SLAVE].set_csrw(0x4000 + ((reg_ch & 0x30) << 10) + ead, dad); + pc98_gdc[GDC_SLAVE].exec(0x6c); + } + } else if(type == 0x02) { + // box + uint16_t dx, dy; + if(x1 > x2) { + temp = x2; x2 = x1; x1 = temp; + } + if(y1 > y2) { + temp = y2; y2 = y1; y1 = temp; + } + dx = x2 - x1; + dy = y2 - y1; + switch(dir & 3) { + case 0: + d = dy; + d2 = dx; + break; + case 1: + d2 = dx + dy; + d2 >>= 1; + d = dx - dy; + d = (d >> 1) & 0x3fff; + break; + case 2: + d = dx; + d2 = dy; + break; + case 3: + d2 = dx + dy; + d2 >>= 1; + d = dy - dx; + d = (d >> 1) & 0x3fff; + break; + } + if((reg_ch & 0x30) == 0x30) { + uint8_t plane = mem_readb(ucw + 0x00); + uint32_t offset = 0x4000; + for(uint8_t bit = 1 ; bit <= 4 ; bit <<= 1) { + pc98_gdc[GDC_SLAVE].set_mode((plane & bit) ? 0x03 : 0x02); + pc98_gdc[GDC_SLAVE].set_vectw(0x40, dir, 3, d, d2, 0xffff, d); + pc98_gdc[GDC_SLAVE].set_csrw(offset + ead, dad); + pc98_gdc[GDC_SLAVE].exec(0x6c); + offset += 0x4000; + } + } else { + pc98_gdc[GDC_SLAVE].set_mode(mem_readb(ucw + 0x02)); + pc98_gdc[GDC_SLAVE].set_vectw(0x40, dir, 3, d, d2, 0xffff, d); + pc98_gdc[GDC_SLAVE].set_csrw(0x4000 + ((reg_ch & 0x30) << 10) + ead, dad); + pc98_gdc[GDC_SLAVE].exec(0x6c); + } + } + } +} + +static void PC98_INT18_DrawText(void) +{ + PhysPt ucw; + uint8_t dir; + uint8_t tile[8]; + uint16_t len; + uint16_t x1, y1; + uint16_t ead, dad; + uint16_t dc, d; + + ucw = SegPhys(ds) + reg_bx; + for(uint8_t i = 0 ; i < 8 ; i++) { + tile[i] = byte_reverse(mem_readb(ucw + 0x20 + i)); + } + pc98_gdc[GDC_SLAVE].set_textw(tile, 8); + len = mem_readw(ucw + 0x0c); + if(len > 0) { + d = len; + dc = (mem_readw(ucw + 0x1e) - 1) & 0x3fff; + } else { + d = 8; + dc = 7; + } + dir = mem_readb(ucw + 0x03); + x1 = mem_readw(ucw + 0x08); + y1 = mem_readw(ucw + 0x0a); + if((reg_ch & 0xc0) == 0x40) { + y1 += 200; + } + ead = (y1 * 40) + (x1 >> 4); + dad = x1 % 16; + if((reg_ch & 0x30) == 0x30) { + uint8_t plane = mem_readb(ucw + 0x00); + uint32_t offset = 0x4000; + for(uint8_t bit = 1 ; bit <= 4 ; bit <<= 1) { + pc98_gdc[GDC_SLAVE].set_mode((plane & bit) ? 0x03 : 0x02); + pc98_gdc[GDC_SLAVE].set_vectw(0x10, dir, dc, d, 0, 0, 0); + pc98_gdc[GDC_SLAVE].set_csrw(offset + ead, dad); + pc98_gdc[GDC_SLAVE].exec(0x68); + offset += 0x4000; + } + } else { + pc98_gdc[GDC_SLAVE].set_mode(mem_readb(ucw + 0x02)); + pc98_gdc[GDC_SLAVE].set_vectw(0x10, dir, dc, d, 0, 0, 0); + pc98_gdc[GDC_SLAVE].set_csrw(0x4000 + ((reg_ch & 0x30) << 10) + ead, dad); + pc98_gdc[GDC_SLAVE].exec(0x68); + } +} + +/* TODO: The text and graphics code that talks to the GDC will need to be converted + * to CPU I/O read and write calls. I think the reason Windows 3.1's 16-color + * driver is causing screen distortion when going fullscreen with COMMAND.COM, + * and the reason COMMAND.COM windowed doesn't show anything, has to do with + * the fact that Windows 3.1 expects this BIOS call to use I/O so it can trap + * and virtualize the GDC and display state. + * + * Obviously for the same reason VGA INT 10h emulation in IBM PC mode needs to + * do the same to prevent display and virtualization problems with the IBM PC + * version of Windows 3.1. + * + * See also: [https://github.com/joncampbell123/dosbox-x/issues/1066] */ +static Bitu INT18_PC98_Handler(void) { + uint16_t temp16; + +#if 0 + if (reg_ah >= 0x0A) { + LOG_MSG("PC-98 INT 18h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + } +#endif + + /* NTS: Based on information gleaned from Neko Project II source code including comments which + * I've run through GNU iconv to convert from SHIFT-JIS to UTF-8 here in case Google Translate + * got anything wrong. */ + switch (reg_ah) { + case 0x00: /* Reading of key data (キー・データの読みだし) */ + /* FIXME: We use the IBM PC/AT keyboard buffer to fake this call. + * This will be replaced with PROPER emulation once the PC-98 keyboard handler has been + * updated to write the buffer the way PC-98 BIOSes do it. + * + * IBM PC/AT keyboard buffer at 40:1E-40:3D + * + * PC-98 keyboard buffer at 50:02-50:21 */ + /* This call blocks until keyboard input */ + if (INT16_get_key(temp16)) { + reg_ax = temp16; + } + else { + /* Keyboard checks. + * If the interrupt got masked, unmask it. + * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler + * handled the keyboard interrupt and never read the keyboard (Quarth). + * + * TODO: Is this what real PC-98 BIOSes do? */ + void check_keyboard_fire_IRQ1(void); + check_keyboard_fire_IRQ1(); + IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 + + reg_ip += 1; /* step over IRET, to NOPs which then JMP back to callback */ + } + break; + case 0x01: /* Sense of key buffer state (キー・バッファ状態のセンス) */ + /* This call returns whether or not there is input waiting. + * The waiting data is read, but NOT discarded from the buffer. */ + if (INT16_peek_key(temp16)) { + reg_ax = temp16; + reg_bh = 1; + } + else { + /* Keyboard checks. + * If the interrupt got masked, unmask it. + * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler + * handled the keyboard interrupt and never read the keyboard (Quarth). + * + * TODO: Is this what real PC-98 BIOSes do? */ + void check_keyboard_fire_IRQ1(void); + check_keyboard_fire_IRQ1(); + IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 + + reg_bh = 0; + } + break; + case 0x02: /* Sense of shift key state (シフト・キー状態のセンス) */ + reg_al = mem_readb(0x53A); + break; + case 0x03: /* Initialization of keyboard interface (キーボード・インタフェイスの初期化) */ + /* TODO */ + IO_WriteB(0x43, 0x3a); + IO_WriteB(0x43, 0x32); + IO_WriteB(0x43, 0x16); + for (int i=0; i<0x20; i++) mem_writeb(0x502+i, 0); + for (int i=0; i<0x13; i++) mem_writeb(0x528+i, 0); + mem_writew(0x522,(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800)); + mem_writew(0x524, 0x0502); + mem_writew(0x526, 0x0502); + mem_writew(0x5C6,(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800)); + mem_writew(0x5C8,0xFD80); + break; + case 0x04: /* Sense of key input state (キー入力状態のセンス) */ + reg_ah = mem_readb(0x52A + (unsigned int)(reg_al & 0x0Fu)); + /* Hack for "Shangrlia" by Elf: The game's regulation of animation speed seems to depend on + * INT 18h AH=0x04 taking some amount of time. If we do not do this, animation will run way + * too fast and everyone will be talking/moving at a million miles a second. + * + * This is based on comparing animation speed vs the same game on real Pentium-class PC-98 + * hardware. + * + * Looking at the software loop involved during opening cutscenes, the game is constantly + * polling INT 18h AH=04h (keyboard state) and INT 33h AH=03h (mouse button/position state) + * while animating the characters on the screen. Without this delay, animation runs way too + * fast. + * + * This guess is also loosely based on a report by the Touhou Community Reliant Automatic Patcher + * that Touhou Project directly reads this byte but delays by 0.6ms to handle the fact that + * the bit in question may toggle while the key is held down due to the scan codes returned by + * the keyboard. + * + * This is a guess, but it seems to help animation speed match that of real hardware regardless + * of cycle count in DOSBox-X. */ + CPU_Cycles -= (cpu_cycles_count_t)(CPU_CycleMax * 0.006); + break; + case 0x05: /* Key input sense (キー入力センス) */ + /* This appears to return a key from the buffer (and remove from + * buffer) or return BH == 0 to signal no key was pending. */ + if (INT16_get_key(temp16)) { + reg_ax = temp16; + reg_bh = 1; + } + else { + /* Keyboard checks. + * If the interrupt got masked, unmask it. + * If the keyboard has data waiting, make sure the interrupt signal is active in case the last interrupt handler + * handled the keyboard interrupt and never read the keyboard (Quarth). + * + * TODO: Is this what real PC-98 BIOSes do? */ + void check_keyboard_fire_IRQ1(void); + check_keyboard_fire_IRQ1(); + IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/1u))); // unmask IRQ1 + + reg_bh = 0; + } + break; + case 0x0A: /* set CRT mode */ + /* bit off on + 0 25lines 20lines + 1 80cols 40cols + 2 v.lines simp.graphics + 3 K-CG access mode(not used in PC-98) */ + + //TODO: set 25/20 lines mode and 80/40 columns mode. + //Attribute bit (bit 2) + pc98_attr4_graphic = !!(reg_al & 0x04); + pc98_40col_text = !!(reg_al & 0x02); +#if defined(USE_TTF) + if (!(reg_al & 0xc) && pc98_gdc[GDC_MASTER].display_enable) ttf_switch_on(false); +#endif + + mem_writeb(0x53C,(mem_readb(0x53C) & 0xF0u) | (reg_al & 0x0Fu)); + + if (reg_al & 8) + LOG_MSG("INT 18H AH=0Ah warning: K-CG dot access mode not supported"); + + pc98_update_text_lineheight_from_bda(); + pc98_update_text_layer_lineheight_from_bda(); + + /* Apparently, this BIOS call also hides the cursor */ + PC98_show_cursor(0); + break; + case 0x0B: /* get CRT mode */ + /* bit off on + 0 25lines 20lines + 1 80cols 40cols + 2 v.lines simp.graphics + 3 K-CG access mode(not used in PC-98) + 7 std CRT hi-res CRT */ + /* NTS: I assume that real hardware doesn't offer a way to read back the state of these bits, + * so the BIOS's only option is to read the mode byte back from the data area. + * Neko Project II agrees. */ + reg_al = mem_readb(0x53C); + break; + // TODO: "Edge" is using INT 18h AH=06h, what is that? + // (Something to do with the buffer [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf]) + // Neko Project is also unaware of such a call. + case 0x0C: /* text layer enable */ + /* PROBLEM: Okay, so it's unclear when text layer is or is not allowed. + * I was unable to turn on the text layer with this BIOS call on real PC-9821 hardware, so I believed that it did not allow it. + * + * But PC-9821 CD-ROM game "Shamat, The Holy Circlet" expects to turn on the text layer in 640x400 256-color PEGC mode, + * because it displays graphics in the background while scrolling Japanese text up over it, and if sound hardware is available, + * plays a voice reading the text synchronized to it. + * + * Perhaps in my case it was 640x480 256-color mode, not 640x400 256-color mode, but then, 640x480 also enables a text mode with + * either more rows or a taller character cell which is apparently recognized by the MS-DOS console driver. + * + * So then, what exactly decides whether or not to allow this call to enable the text layer? */ + if (pc98_gdc_vramop & (1u << VOPBIT_VGA) && 0/*DISABLED*/) { + /* NTS: According to tests on real PC-9821 hardware, you can't turn on the text layer in 256-color mode, at least through the BIOS. */ + /* FIXME: Is this a restriction imposed by the BIOS, or the hardware itself? */ + LOG_MSG("INT 18h: Attempt to turn on text layer in 256-color mode"); + } + else { + pc98_gdc[GDC_MASTER].force_fifo_complete(); + pc98_gdc[GDC_MASTER].display_enable = true; +#if defined(USE_TTF) + ttf_switch_on(false); +#endif + } + break; + case 0x0D: /* text layer disable */ +#if defined(USE_TTF) + ttf_switch_off(false); +#endif + pc98_gdc[GDC_MASTER].force_fifo_complete(); + pc98_gdc[GDC_MASTER].display_enable = false; + break; + case 0x0E: /* set text display area (DX=byte offset) */ + pc98_gdc[GDC_MASTER].force_fifo_complete(); + pc98_gdc[GDC_MASTER].param_ram[0] = (reg_dx >> 1) & 0xFF; + pc98_gdc[GDC_MASTER].param_ram[1] = (reg_dx >> 9) & 0xFF; + pc98_gdc[GDC_MASTER].param_ram[2] = (400 << 4) & 0xFF; + pc98_gdc[GDC_MASTER].param_ram[3] = (400 << 4) >> 8; + break; + case 0x11: /* show cursor */ + PC98_show_cursor(true); + break; + case 0x12: /* hide cursor */ + PC98_show_cursor(false); + break; + case 0x13: /* set cursor position (DX=byte position) */ + void vga_pc98_direct_cursor_pos(uint16_t address); + + pc98_gdc[GDC_MASTER].force_fifo_complete(); + vga_pc98_direct_cursor_pos(reg_dx >> 1); + break; + case 0x14: /* read FONT RAM */ + { + unsigned int i,o,r; + + /* DX = code (must be 0x76xx or 0x7700) + * BX:CX = 34-byte region to write to */ + if (reg_dh == 0x80u) { /* 8x16 ascii */ + i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; + mem_writew(i-2u,0x0102u); + for (r=0;r < 16u;r++) { + o = (reg_dl*16u)+r; + + assert((o+2u) <= sizeof(vga.draw.font)); + + mem_writeb(i+r,vga.draw.font[o]); + } + } + else if ((reg_dh & 0xFC) == 0x28) { /* 8x16 kanji */ + i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; + mem_writew(i-2u,0x0102u); + for (r=0;r < 16u;r++) { + o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; + + assert((o+2u) <= sizeof(vga.draw.font)); + + mem_writeb(i+r+0u,vga.draw.font[o+0u]); + } + } + else if (reg_dh != 0) { /* 16x16 kanji */ + i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; + mem_writew(i-2u,0x0202u); + for (r=0;r < 16u;r++) { + o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; + + assert((o+2u) <= sizeof(vga.draw.font)); + + mem_writeb(i+(r*2u)+0u,vga.draw.font[o+0u]); + mem_writeb(i+(r*2u)+1u,vga.draw.font[o+1u]); + } + } + else if(reg_dl < 0x80) { /* 6x8 ascii .. Substitute 8x8 */ + i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; + mem_writew(i-2u,0x0101u); + o = reg_dl * 8; + for (r=0;r < 8u;r++) { + mem_writeb(i+r, int10_font_08[o + r]); + } + } + else if(reg_dl >= 0xa0 && reg_dl <= 0xdf) { /* 6x8 kana */ + i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; + mem_writew(i - 2u, 0x0101u); + o = (reg_dl - 0xa0) * 8; + for(r = 0; r < 8u; r++) { + mem_writeb(i + r, pc98_katakana6x8_font[o + r]); + } + } + else { + LOG_MSG("PC-98 INT 18h AH=14h font RAM read ignored, code 0x%04x not supported",reg_dx); + } + } + break; + case 0x16: /* fill screen with chr + attr */ + { + /* DL = character + * DH = attribute */ + unsigned int i; + + for (i=0;i < 0x2000;i += 2) { + vga.mem.linear[i+0] = reg_dl; + vga.mem.linear[i+1] = 0x00; + } + for ( ;i < 0x3FE0;i += 2) { + vga.mem.linear[i+0] = reg_dh; + vga.mem.linear[i+1] = 0x00; + } + } + break; + case 0x17: /* BELL ON */ + IO_WriteB(0x37,0x06); + break; + case 0x18: /* BELL OFF */ + IO_WriteB(0x37,0x07); + break; + case 0x1A: /* load FONT RAM */ + { + /* DX = code (must be 0x76xx or 0x7700) + * BX:CX = 34-byte region to read from */ + if ((reg_dh & 0x7Eu) == 0x76u) { + unsigned int i = ((unsigned int)reg_bx << 4u) + reg_cx + 2u; + for (unsigned int r=0;r < 16u;r++) { + unsigned int o = (((((reg_dl & 0x7Fu)*128u)+((reg_dh - 0x20u) & 0x7Fu))*16u)+r)*2u; + + assert((o+2u) <= sizeof(vga.draw.font)); + + vga.draw.font[o+0u] = mem_readb(i+(r*2u)+0u); + vga.draw.font[o+1u] = mem_readb(i+(r*2u)+1u); + } + } + else { + LOG_MSG("PC-98 INT 18h AH=1Ah font RAM load ignored, code 0x%04x out of range",reg_dx); + } + } + break; + case 0x30: /* Set display mode */ + /* FIXME: There is still a lot that is inaccurate about this call */ + if (enable_pc98_egc) { + unsigned char b597 = mem_readb(0x597); + unsigned char tstat = mem_readb(0x53C); + unsigned char b54C = mem_readb(0x54C); + unsigned char ret = 0x05; // according to NP2 + + // assume the same as AH=42h + while (!(IO_ReadB(0x60) & 0x20/*vertical retrace*/)) { + void CALLBACK_Idle(void); + CALLBACK_Idle(); + } + + LOG_MSG("PC-98 INT 18 AH=30h AL=%02Xh BH=%02Xh",reg_al,reg_bh); + + if ((reg_bh & 0x30) == 0x30) { // 640x480 + if ((reg_al & 0xC) == 0x0C) { // 31KHz sync + void PC98_Set31KHz_480line(void); + pc98_31khz_mode = true; + PC98_Set31KHz_480line(); + + void pc98_port6A_command_write(unsigned char b); + pc98_port6A_command_write(0x69); // disable 128KB wrap + + b54C = (b54C & (~0x20)) + ((reg_al & 0x04) ? 0x20 : 0x00); + +#if defined(USE_TTF) + ttf_switch_off(false); +#endif + pc98_gdc[GDC_MASTER].force_fifo_complete(); + pc98_gdc[GDC_SLAVE].force_fifo_complete(); + + // according to real hardware, this also hides the text layer for some reason + pc98_gdc[GDC_MASTER].display_enable = false; + + /* clear PRAM, graphics */ + for (unsigned int i=0;i < 16;i++) + pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; + + /* reset scroll area of graphics */ + pc98_gdc[GDC_SLAVE].param_ram[0] = 0; + pc98_gdc[GDC_SLAVE].param_ram[1] = 0; + + pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; + pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); + pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; + + pc98_gdc[GDC_SLAVE].doublescan = false; + pc98_gdc[GDC_SLAVE].row_height = 1; + + b597 = (b597 & ~3u) + ((uint8_t)(reg_bh >> 4u) & 3u); + + pc98_gdc_vramop &= ~(1 << VOPBIT_ACCESS); + pc98_update_cpu_page_ptr(); + + GDC_display_plane = GDC_display_plane_pending = 0; + pc98_update_display_page_ptr(); + + /* based on real hardware behavior, this ALSO sets 256-color mode */ + void pc98_port6A_command_write(unsigned char b); + pc98_port6A_command_write(0x07); // enable EGC + pc98_port6A_command_write(0x01); // enable 16-color + pc98_port6A_command_write(0x21); // enable 256-color + } + else { + // according to Neko Project II, this case is ignored. + // this is confirmed on real hardware as well. + LOG_MSG("PC-98 INT 18h AH=30h attempt to set 640x480 mode with 24KHz hsync which is not supported by the platform"); + ret = 0; + } + } + else { // 640x400 or 640x200 + // TODO: A PC9821Lt2 laptop's BIOS refuses to allow 31khz except for 640x480 mode. + // Perhaps it's just a technical restriction of the LCD display. + // + // Check on other PC-98 hardware to see what the policy is for 31khz in all modes. + // That restriction would make no sense on another system I have that has a VGA + // port and a default setting of 70Hz / 31KHz 640x400. + if ((reg_al & 0x0C) < 0x08) { /* bits [3:2] == 0x */ + LOG_MSG("PC-98 INT 18h AH=30h attempt to set 15KHz hsync which is not yet supported"); + ret = 0; + } + else { + if ((reg_al ^ (((b54C & 0x20) ? 3 : 2) << 2)) & 0x0C) { /* change in bits [3:2] */ + LOG_MSG("PC-98 change in hsync frequency to %uHz",(reg_al & 0x04) ? 31 : 24); + + if (reg_al & 4) { + void PC98_Set31KHz(void); + pc98_31khz_mode = true; + PC98_Set31KHz(); + } + else { + void PC98_Set24KHz(void); + pc98_31khz_mode = false; + PC98_Set24KHz(); + } + + b54C = (b54C & (~0x20)) + ((reg_al & 0x04) ? 0x20 : 0x00); + } + } + + void pc98_port6A_command_write(unsigned char b); + pc98_port6A_command_write(0x68); // restore 128KB wrap + +#if defined(USE_TTF) + ttf_switch_off(false); +#endif + pc98_gdc[GDC_MASTER].force_fifo_complete(); + pc98_gdc[GDC_SLAVE].force_fifo_complete(); + + // 640x480 forces 256-color mode. + // the 400 line modes (this case) do not clear 256-color mode. + + // according to real hardware, this also hides the text layer for some reason + pc98_gdc[GDC_MASTER].display_enable = false; + + /* clear PRAM, graphics */ + for (unsigned int i=0;i < 16;i++) + pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; + + /* reset scroll area of graphics */ + if ((reg_bh & 0x30) == 0x10) { /* 640x200 upper half bits [5:4] == 1 */ + pc98_gdc[GDC_SLAVE].param_ram[0] = (200*40) & 0xFF; + pc98_gdc[GDC_SLAVE].param_ram[1] = (200*40) >> 8; + } + else { + pc98_gdc[GDC_SLAVE].param_ram[0] = 0; + pc98_gdc[GDC_SLAVE].param_ram[1] = 0; + } + + pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; + pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); + pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; + + if ((reg_bh & 0x20) == 0x00) { /* 640x200 */ + pc98_gdc[GDC_SLAVE].doublescan = true; + pc98_gdc[GDC_SLAVE].row_height = pc98_gdc[GDC_SLAVE].doublescan ? 2 : 1; + } + else { + pc98_gdc[GDC_SLAVE].doublescan = false; + pc98_gdc[GDC_SLAVE].row_height = 1; + } + + b597 = (b597 & ~3u) + ((uint8_t)(reg_bh >> 4u) & 3u); + + pc98_gdc_vramop &= ~(1 << VOPBIT_ACCESS); + pc98_update_cpu_page_ptr(); + + GDC_display_plane = GDC_display_plane_pending = 0; + pc98_update_display_page_ptr(); + } + + tstat &= ~(0x10 | 0x01); + if (reg_bh & 2) + tstat |= 0x10; + else if ((reg_bh & 1) == 0) + tstat |= 0x01; + + mem_writeb(0x597,b597); + mem_writeb(0x53C,tstat); + mem_writeb(0x54C,b54C); + + pc98_update_text_lineheight_from_bda(); + pc98_update_text_layer_lineheight_from_bda(); + + // according to real hardware (PC-9821Lt2), AH=5 on success (same as NP2) + // or AH is unchanged on failure and AL=1 and BH=1 (NOT the same as NP2) + if (ret == 0x05) reg_ah = ret; + reg_al = (ret == 0x05) ? 0x00 : 0x01; // according to NP2 + reg_bh = (ret == 0x05) ? 0x00 : 0x01; // according to NP2 + } + break; + case 0x31: /* Return display mode and status */ + /* NTS: According to NP II this call shouldn't even work unless you first call AH=30h to set 640x480 mode. + * It seems that is wrong. Real hardware will still return the current mode regardless. */ + if (enable_pc98_egc) { /* FIXME: INT 18h AH=31/30h availability is tied to EGC enable */ + unsigned char b597 = mem_readb(0x597); + unsigned char tstat = mem_readb(0x53C); + unsigned char b54C = mem_readb(0x54C); + + /* 54Ch: + * bit[5:5] = Horizontal sync rate 1=31.47KHz 0=24.83KHz */ + + /* Return values: + * + * AL = + * bit [7:7] = ? + * bit [6:6] = ? + * bit [5:5] = ? + * bit [4:4] = ? + * bit [3:2] = horizontal sync + * 00 = 15.98KHz + * 01 = ? + * 10 = 24.83KHz + * 11 = 31.47KHz + * bit [1:1] = ? + * bit [0:0] = interlaced (1=yes 0=no) + * BH = + * bit [7:7] = ? + * bit [6:6] = ? + * bit [5:4] = graphics video mode + * 00 = 640x200 (upper half) + * 01 = 640x200 (lower half) + * 10 = 640x400 + * 11 = 640x480 + * bit [3:3] = ? + * bit [2:2] = ? + * bit [1:0] = number of text rows + * 00 = 20 rows + * 01 = 25 rows + * 10 = 30 rows + * 11 = ? + */ + reg_al = + (((b54C & 0x20) ? 3 : 2) << 2)/*hsync*/; + reg_bh = + ((b597 & 3) << 4)/*graphics video mode*/; + if (tstat & 0x10) + reg_bh |= 2;/*30 rows*/ + else if ((tstat & 0x01) == 0) + reg_bh |= 1;/*25 rows*/ + } + break; + /* From this point on the INT 18h call list appears to wander off from the keyboard into CRT/GDC/display management. */ + case 0x40: /* Start displaying the graphics screen (グラフィック画面の表示開始) */ + pc98_gdc[GDC_SLAVE].force_fifo_complete(); + pc98_gdc[GDC_SLAVE].display_enable = true; +#if defined(USE_TTF) + if (!pc98_gdc[GDC_MASTER].display_enable) ttf_switch_off(false); +#endif + + { + unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); + mem_writeb(0x54C/*MEMB_PRXCRT*/,b | 0x80); + } + break; + case 0x41: /* Stop displaying the graphics screen (グラフィック画面の表示終了) */ + pc98_gdc[GDC_SLAVE].force_fifo_complete(); + pc98_gdc[GDC_SLAVE].display_enable = false; +#if defined(USE_TTF) + if (pc98_gdc[GDC_MASTER].display_enable) ttf_switch_on(false); +#endif + + { + unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); + mem_writeb(0x54C/*MEMB_PRXCRT*/,b & (~0x80)); + } + break; + case 0x42: /* Display area setup (表示領域の設定) */ + // HACK for Quarth: If the game has triggered vsync interrupt, wait for it. + // Quarth's vsync interrupt will reprogram the display partitions back to what + // it would have set for gameplay after this modeset and cause display problems + // with the main menu. Waiting one vertical retrace period before mode setting + // gives Quarth one last frame to reprogram partitions before realizing that + // it's time to stop it. + // + // If the BIOS on real hardware has any check like this, it's probably a loop + // to wait for vsync. + // + // The interrupt does NOT cancel the vertical retrace interrupt. Some games + // (Rusty) will not work properly if this call cancels the vertical retrace + // interrupt. + while (!(IO_ReadB(0x60) & 0x20/*vertical retrace*/)) { + void CALLBACK_Idle(void); + CALLBACK_Idle(); + } + + pc98_gdc[GDC_MASTER].force_fifo_complete(); + pc98_gdc[GDC_SLAVE].force_fifo_complete(); + + /* clear PRAM, graphics */ + for (unsigned int i=0;i < 16;i++) + pc98_gdc[GDC_SLAVE].param_ram[i] = 0x00; + + /* reset scroll area of graphics */ + if ((reg_ch & 0xC0) == 0x40) { /* 640x200 G-RAM upper half */ + pc98_gdc[GDC_SLAVE].param_ram[0] = (200*40) & 0xFF; + pc98_gdc[GDC_SLAVE].param_ram[1] = (200*40) >> 8; + } + else { + pc98_gdc[GDC_SLAVE].param_ram[0] = 0; + pc98_gdc[GDC_SLAVE].param_ram[1] = 0; + } + + pc98_gdc[GDC_SLAVE].param_ram[2] = 0xF0; + pc98_gdc[GDC_SLAVE].param_ram[3] = 0x3F + (gdc_5mhz_according_to_bios()?0x40:0x00/*IM bit*/); + pc98_gdc[GDC_SLAVE].display_pitch = gdc_5mhz_according_to_bios() ? 80u : 40u; + + // CH + // [7:6] = G-RAM setup + // 00 = no graphics (?) + // 01 = 640x200 upper half + // 10 = 640x200 lower half + // 11 = 640x400 + // [5:5] = CRT + // 0 = color + // 1 = monochrome + // [4:4] = Display bank + + // Color or monochrome mode + IO_WriteB(0x68, (reg_ch & 0x20) ? 0x03 : 0x02); + + // FIXME: This is a guess. I have no idea as to actual behavior, yet. + // This seems to help with clearing the text layer when games start the graphics. + // This is ALSO how we will detect games that switch on the 200-line double-scan mode vs 400-line mode. + if ((reg_ch & 0xC0) != 0) { + pc98_gdc[GDC_SLAVE].doublescan = ((reg_ch & 0xC0) == 0x40) || ((reg_ch & 0xC0) == 0x80); + pc98_gdc[GDC_SLAVE].row_height = pc98_gdc[GDC_SLAVE].doublescan ? 2 : 1; + + /* update graphics mode bits */ + { + unsigned char b = mem_readb(0x597); + + b &= ~3; + b |= ((reg_ch >> 6) - 1) & 3; + + mem_writeb(0x597,b); + } + } + else { + pc98_gdc[GDC_SLAVE].doublescan = false; + pc98_gdc[GDC_SLAVE].row_height = 1; + } + + { + unsigned char b = mem_readb(0x54C/*MEMB_PRXCRT*/); + + // Real hardware behavior: graphics selection updated by BIOS to reflect MEMB_PRXCRT state + pc98_gdc[GDC_SLAVE].display_enable = !!(b & 0x80); +#if defined(USE_TTF) + if (pc98_gdc[GDC_SLAVE].display_enable) + ttf_switch_off(false); + else if (pc98_gdc[GDC_MASTER].display_enable) + ttf_switch_on(false); +#endif + } + + GDC_display_plane = GDC_display_plane_pending = (reg_ch & 0x10) ? 1 : 0; + pc98_update_display_page_ptr(); + + prev_pc98_mode42 = reg_ch; + + LOG_MSG("PC-98 INT 18 AH=42h CH=0x%02X",reg_ch); + break; + case 0x43: // Palette register settings? Only works in digital mode? --leonier + // + // This is said to fix Thexder's GAME ARTS logo. --Jonathan C. + // + // TODO: Validate this against real PC-98 hardware and BIOS + { + unsigned int gbcpc = SegValue(ds)*0x10u + reg_bx; + for(unsigned int i=0;i<4;i++) + { + unsigned char p=mem_readb(gbcpc+4u+i); + pc98_set_digpal_entry(7u-2u*i, p&0xFu); + pc98_set_digpal_entry(6u-2u*i, p>>4u); + } + LOG_MSG("PC-98 INT 18 AH=43h CX=0x%04X DS=0x%04X", reg_cx, SegValue(ds)); + break; + } + case 0x47: // Line, Box + case 0x48: // Arc + PC98_INT18_DrawShape(); + break; + case 0x49: // Text + PC98_INT18_DrawText(); + break; + case 0x4D: // 256-color enable + if (reg_ch == 1) { + void pc98_port6A_command_write(unsigned char b); + pc98_port6A_command_write(0x07); // enable EGC + pc98_port6A_command_write(0x01); // enable 16-color + pc98_port6A_command_write(0x21); // enable 256-color + PC98_show_cursor(false); // apparently hides the cursor? + mem_writeb(0x54D, mem_readb(0x54D) | 0x80); + } + else if (reg_ch == 0) { + void pc98_port6A_command_write(unsigned char b); + pc98_port6A_command_write(0x20); // disable 256-color + PC98_show_cursor(false); // apparently hides the cursor? + mem_writeb(0x54D, mem_readb(0x54D) & ~0x80); + } + else { + LOG_MSG("PC-98 INT 18h AH=4Dh unknown CH=%02xh",reg_ch); + } + break; + default: + LOG_MSG("PC-98 INT 18h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + break; + } + + /* FIXME: What do actual BIOSes do when faced with an unknown INT 18h call? */ + return CBRET_NONE; +} + +#define PC98_FLOPPY_HIGHDENSITY 0x01 +#define PC98_FLOPPY_2HEAD 0x02 +#define PC98_FLOPPY_RPM_3MODE 0x04 +#define PC98_FLOPPY_RPM_IBMPC 0x08 + +unsigned char PC98_BIOS_FLOPPY_BUFFER[32768]; /* 128 << 8 */ + +static unsigned int PC98_FDC_SZ_TO_BYTES(unsigned int sz) { + return 128U << sz; +} + +int PC98_BIOS_SCSI_POS(imageDisk *floppy,uint32_t §or) { + if (reg_al & 0x80) { + uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; + + floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); + + /* DL = sector + * DH = head + * CX = track */ + if (reg_dl >= img_sect || + reg_dh >= img_heads || + reg_cx >= img_cyl) { + return (reg_ah=0x60); + } + + sector = reg_cx; + sector *= img_heads; + sector += reg_dh; + sector *= img_sect; + sector += reg_dl; + +// LOG_MSG("Sector CHS %u/%u/%u -> %u (geo %u/%u/%u)",reg_cx,reg_dh,reg_dl,sector,img_cyl,img_heads,img_sect); + } + else { + /* Linear LBA addressing */ + sector = ((unsigned int)reg_dl << 16UL) + reg_cx; + /* TODO: SASI caps at 0x1FFFFF according to NP2 */ + } + + return 0; +} + +void PC98_BIOS_SCSI_CALL(void) { + uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; + uint32_t memaddr,size,ssize; + imageDisk *floppy; + unsigned int i; + uint32_t sector; + int idx; + +#if 0 + LOG_MSG("PC-98 INT 1Bh SCSI BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); +#endif + + idx = (reg_al & 0xF) + 2; + if (idx < 0 || idx >= MAX_DISK_IMAGES) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + floppy = imageDiskList[idx]; + if (floppy == NULL) { + CALLBACK_SCF(true); + reg_ah = 0x60; + return; + } + + /* FIXME: According to NPKai, command is reg_ah & 0x1F not reg_ah & 0x0F. Right? */ + + /* what to do is in the lower 4 bits of AH */ + switch (reg_ah & 0x0F) { + case 0x05: /* write */ + if (PC98_BIOS_SCSI_POS(floppy,/*&*/sector) == 0) { + floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); + assert(img_ssz != 0); + + size = reg_bx; + if (size == 0) size = 0x10000U; + memaddr = ((unsigned int)SegValue(es) << 4u) + reg_bp; + + reg_ah = 0; + CALLBACK_SCF(false); + +// LOG_MSG("WRITE memaddr=0x%lx size=0x%x sector=0x%lx ES:BP=%04x:%04X", +// (unsigned long)memaddr,(unsigned int)size,(unsigned long)sector,SegValue(es),reg_bp); + + while (size != 0) { + ssize = size; + if (ssize > img_ssz) ssize = img_ssz; + +// LOG_MSG(" ... memaddr=0x%lx ssize=0x%x sector=0x%lx", +// (unsigned long)memaddr,(unsigned int)ssize,(unsigned long)sector); + + for (i=0;i < ssize;i++) PC98_BIOS_FLOPPY_BUFFER[i] = mem_readb(memaddr+i); + + if (floppy->Write_AbsoluteSector(sector,PC98_BIOS_FLOPPY_BUFFER) != 0) { + reg_ah = 0xD0; + CALLBACK_SCF(true); + break; + } + + sector++; + size -= ssize; + memaddr += ssize; + } + } + else { + CALLBACK_SCF(true); + } + break; + case 0x06: /* read */ + if (PC98_BIOS_SCSI_POS(floppy,/*&*/sector) == 0) { + floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); + assert(img_ssz != 0); + + size = reg_bx; + if (size == 0) size = 0x10000U; + memaddr = ((unsigned int)SegValue(es) << 4u) + reg_bp; + + reg_ah = 0; + CALLBACK_SCF(false); + +// LOG_MSG("READ memaddr=0x%lx size=0x%x sector=0x%lx ES:BP=%04x:%04X", +// (unsigned long)memaddr,(unsigned int)size,(unsigned long)sector,SegValue(es),reg_bp); + + while (size != 0) { + ssize = size; + if (ssize > img_ssz) ssize = img_ssz; + +// LOG_MSG(" ... memaddr=0x%lx ssize=0x%x sector=0x%lx", +// (unsigned long)memaddr,(unsigned int)ssize,(unsigned long)sector); + + if (floppy->Read_AbsoluteSector(sector,PC98_BIOS_FLOPPY_BUFFER) == 0) { + for (i=0;i < ssize;i++) mem_writeb(memaddr+i,PC98_BIOS_FLOPPY_BUFFER[i]); + } + else { + reg_ah = 0xD0; + CALLBACK_SCF(true); + break; + } + + sector++; + size -= ssize; + memaddr += ssize; + } + } + else { + CALLBACK_SCF(true); + } + break; + case 0x03: /* according to NPKai source code: "negate ack" (cbus/scsicmd.c line 211, and 61) */ + reg_ah = 0x35; /* according to scsicmd_negate() line 61, as translated by stat2ret[] by code line 228 */ + CALLBACK_SCF(false); + // NTS: This is needed for an HDI image to boot that apparently contains FreeDOS98 + break; + case 0x07: /* unknown, always succeeds */ + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x0E: /* unknown, always fails */ + reg_ah = 0x40; + CALLBACK_SCF(true); + break; + case 0x04: /* drive status */ + if (reg_ah == 0x84) { + floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); + + reg_dl = img_sect; + reg_dh = img_heads; /* Max 16 */ + reg_cx = img_cyl; /* Max 4096 */ + reg_bx = img_ssz; + + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + } + else if (reg_ah == 0x04 || reg_ah == 0x14) { + reg_ah = 0x00; + CALLBACK_SCF(false); + } + else { + goto default_goto; + } + default: + default_goto: + LOG_MSG("PC-98 INT 1Bh unknown SCSI BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + CALLBACK_SCF(true); + break; + } +} + +void PC98_BIOS_FDC_CALL_GEO_UNPACK(unsigned int &fdc_cyl,unsigned int &fdc_head,unsigned int &fdc_sect,unsigned int &fdc_sz) { + fdc_cyl = reg_cl; + fdc_head = reg_dh; + fdc_sect = reg_dl; + fdc_sz = reg_ch; + if (fdc_sz > 8) fdc_sz = 8; +} + +/* NTS: FDC calls reset IRQ 0 timer to a specific fixed interval, + * because the real BIOS likely does the same in the act of + * controlling the floppy drive. + * + * Resetting the interval is required to prevent Ys II from + * crashing after disk swap (divide by zero/overflow) because + * Ys II reads the timer after INT 1Bh for whatever reason + * and the upper half of the timer byte later affects a divide + * by 3 in the code. */ + +void PC98_Interval_Timer_Continue(void); + +bool enable_fdc_timer_hack = false; + +void FDC_WAIT_TIMER_HACK(void) { + unsigned int v; + unsigned int c=0; + + // Explanation: + // + // Originally the FDC code here changed the timer interval back to the stock 100hz + // normally used in PC-98, to fix Ys II. However that seems to break other booter + // games that hook IRQ 0 directly and set the timer ONCE, then access the disk. + // + // For example, "Angelus" ran WAY too slow with the timer hack because it programs + // the timer to a 600hz interval and expects it to stay that way. + // + // So the new method to satisfy both games is to loop here until the timer + // count is below the maximum that would occur if the 100hz tick count were + // still in effect, even if the timer interval was reprogrammed. + // + // NTS: Writing port 0x77 to relatch the timer also seems to break games + // + // TODO: As a safety against getting stuck, perhaps PIC_FullIndex() should be used + // to break out of the loop if this runs for more than 1 second, since that + // is a sign the timer is in an odd state that will never terminate this loop. + + v = ~0U; + c = 10; + do { + void CALLBACK_Idle(void); + CALLBACK_Idle(); + + unsigned int pv = v; + + v = (unsigned int)IO_ReadB(0x71); + v |= (unsigned int)IO_ReadB(0x71) << 8u; + + if (v > pv) { + /* if the timer rolled around, we might have missed the narrow window we're watching for */ + if (--c == 0) break; + } + } while (v >= 0x60); +} + +void PC98_BIOS_FDC_CALL(unsigned int flags) { + static unsigned int fdc_cyl[2]={0,0},fdc_head[2]={0,0},fdc_sect[2]={0,0},fdc_sz[2]={0,0}; // FIXME: Rename and move out. Making "static" is a hack here. + uint32_t img_heads=0,img_cyl=0,img_sect=0,img_ssz=0; + unsigned int drive; + unsigned int status; + unsigned int size,accsize,unitsize; + unsigned long memaddr; + imageDisk *floppy; + + /* AL bits[1:0] = which floppy drive */ + if ((reg_al & 3) >= 2) { + /* This emulation only supports up to 2 floppy drives */ + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + floppy = GetINT13FloppyDrive(drive=(reg_al & 3)); + + /* what to do is in the lower 4 bits of AH */ + switch (reg_ah & 0x0F) { + /* TODO: 0x00 = seek to track (in CL) */ + /* TODO: 0x01 = test read? */ + /* TODO: 0x03 = equipment flags? */ + /* TODO: 0x04 = format detect? */ + /* TODO: 0x05 = write disk */ + /* TODO: 0x07 = recalibrate (seek to track 0) */ + /* TODO: 0x0A = Read ID */ + /* TODO: 0x0D = Format track */ + /* TODO: 0x0E = ?? */ + case 0x03: /* equipment flags update (?) */ + // TODO: Update the disk equipment flags in BDA. + // For now, make Alantia happy by returning success. + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x00: /* seek */ + /* CL = track */ + if (floppy == NULL) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + if (enable_fdc_timer_hack) { + // Hack for Ys II + FDC_WAIT_TIMER_HACK(); + } + + fdc_cyl[drive] = reg_cl; + + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x01: /* test read */ + /* AH bits[4:4] = If set, seek to track specified */ + /* CL = cylinder (track) */ + /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ + /* DL = sector number (1-based) */ + /* DH = head */ + /* BX = size (in bytes) of data to read */ + /* ES:BP = buffer to read data into */ + if (floppy == NULL) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); + + if (enable_fdc_timer_hack) { + // Hack for Ys II + FDC_WAIT_TIMER_HACK(); + } + + /* Prevent reading 1.44MB floppies using 1.2MB read commands and vice versa. + * FIXME: It seems MS-DOS 5.0 booted from a HDI image has trouble understanding + * when Drive A: (the first floppy) is a 1.44MB drive or not and fails + * because it only attempts it using 1.2MB format read commands. */ + if (flags & PC98_FLOPPY_RPM_IBMPC) { + if (img_ssz == 1024) { /* reject 1.2MB 3-mode format */ + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + } + else { + if (img_ssz == 512) { /* reject IBM PC 1.44MB format */ + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + } + + PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); + unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); + if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + size = reg_bx; + while (size > 0) { + accsize = size > unitsize ? unitsize : size; + + if (floppy->Read_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + size -= accsize; + + if (size == 0) break; + + if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { + fdc_sect[drive] = 1; + if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { + fdc_head[drive] = 0; + fdc_cyl[drive]++; + } + } + } + + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x02: /* read sectors */ + case 0x06: /* read sectors (what's the difference from 0x02?) */ + /* AH bits[4:4] = If set, seek to track specified */ + /* CL = cylinder (track) */ + /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ + /* DL = sector number (1-based) */ + /* DH = head */ + /* BX = size (in bytes) of data to read */ + /* ES:BP = buffer to read data into */ + if (floppy == NULL) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); + + if (enable_fdc_timer_hack) { + // Hack for Ys II + FDC_WAIT_TIMER_HACK(); + } + + /* Prevent reading 1.44MB floppies using 1.2MB read commands and vice versa. + * FIXME: It seems MS-DOS 5.0 booted from a HDI image has trouble understanding + * when Drive A: (the first floppy) is a 1.44MB drive or not and fails + * because it only attempts it using 1.2MB format read commands. */ + if (flags & PC98_FLOPPY_RPM_IBMPC) { + if (img_ssz == 1024) { /* reject 1.2MB 3-mode format */ + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + } + else { + if (img_ssz == 512) { /* reject IBM PC 1.44MB format */ + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + } + + PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); + unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); + if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + size = reg_bx; + memaddr = ((unsigned int)SegValue(es) << 4U) + reg_bp; + while (size > 0) { + accsize = size > unitsize ? unitsize : size; + + if (floppy->Read_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + for (unsigned int i=0;i < accsize;i++) + mem_writeb(memaddr+i,PC98_BIOS_FLOPPY_BUFFER[i]); + + memaddr += accsize; + size -= accsize; + + if (size == 0) break; + + if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { + fdc_sect[drive] = 1; + if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { + fdc_head[drive] = 0; + fdc_cyl[drive]++; + } + } + } + + /* need to clear DMA terminal count after read as BIOS would, I assume (Arsys Star Cruiser) */ + { + DmaChannel *dma = GetDMAChannel(2); + if (dma) dma->tcount = false; + } + + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x04: /* drive status */ + status = 0; + + /* TODO: bit 4 is set if write protected */ + + if (reg_al & 0x80) { /* high density */ + status |= 0x01; + } + else { /* double density */ + /* TODO: */ + status |= 0x01; + } + + if ((reg_ax & 0x8F40) == 0x8400) { + status |= 8; /* 1MB/640KB format, spindle speed for 3-mode */ + if (reg_ah & 0x40) /* DOSBox-X always supports 1.44MB */ + status |= 4; /* 1.44MB format, spindle speed for IBM PC format */ + } + + if (floppy == NULL) + status |= 0xC0; + + reg_ah = status; + CALLBACK_SCF(false); + break; + /* TODO: 0x00 = seek to track (in CL) */ + /* TODO: 0x01 = test read? */ + /* TODO: 0x03 = equipment flags? */ + /* TODO: 0x04 = format detect? */ + /* TODO: 0x05 = write disk */ + /* TODO: 0x07 = recalibrate (seek to track 0) */ + /* TODO: 0x0A = Read ID */ + /* TODO: 0x0D = Format track */ + /* TODO: 0x0E = ?? */ + case 0x05: /* write sectors */ + /* AH bits[4:4] = If set, seek to track specified */ + /* CL = cylinder (track) */ + /* CH = sector size (0=128 1=256 2=512 3=1024 etc) */ + /* DL = sector number (1-based) */ + /* DH = head */ + /* BX = size (in bytes) of data to read */ + /* ES:BP = buffer to write data from */ + if (floppy == NULL) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); + + if (enable_fdc_timer_hack) { + // Hack for Ys II + FDC_WAIT_TIMER_HACK(); + } + + /* TODO: Error if write protected */ + + PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); + unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); + if (0/*unitsize != img_ssz || img_heads == 0 || img_cyl == 0 || img_sect == 0*/) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + size = reg_bx; + memaddr = ((unsigned int)SegValue(es) << 4U) + reg_bp; + while (size > 0) { + accsize = size > unitsize ? unitsize : size; + + for (unsigned int i=0;i < accsize;i++) + PC98_BIOS_FLOPPY_BUFFER[i] = mem_readb(memaddr+i); + + if (floppy->Write_Sector(fdc_head[drive],fdc_cyl[drive],fdc_sect[drive],PC98_BIOS_FLOPPY_BUFFER,unitsize) != 0) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + memaddr += accsize; + size -= accsize; + + if (size == 0) break; + + if ((++fdc_sect[drive]) > img_sect && img_sect != 0) { + fdc_sect[drive] = 1; + if ((++fdc_head[drive]) >= img_heads && img_heads != 0) { + fdc_head[drive] = 0; + fdc_cyl[drive]++; + } + } + } + + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x07: /* recalibrate (seek to track 0) */ + if (floppy == NULL) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + if (enable_fdc_timer_hack) { + // Hack for Ys II + FDC_WAIT_TIMER_HACK(); + } + + fdc_cyl[drive] = 0; + + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x0D: /* format track */ + if (floppy == NULL) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + PC98_BIOS_FDC_CALL_GEO_UNPACK(/*&*/fdc_cyl[drive],/*&*/fdc_head[drive],/*&*/fdc_sect[drive],/*&*/fdc_sz[drive]); + unitsize = PC98_FDC_SZ_TO_BYTES(fdc_sz[drive]); + + if (enable_fdc_timer_hack) { + // Hack for Ys II + FDC_WAIT_TIMER_HACK(); + } + + LOG_MSG("WARNING: INT 1Bh FDC format track command not implemented. Formatting is faked, for now on C/H/S/sz %u/%u/%u/%u drive %c.", + (unsigned int)fdc_cyl[drive], + (unsigned int)fdc_head[drive], + (unsigned int)fdc_sect[drive], + (unsigned int)unitsize, + drive + 'A'); + + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x0A: /* read ID */ + /* NTS: PC-98 "MEGDOS" used by some games seems to rely heavily on this call to + * verify the floppy head is where it thinks it should be! */ + if (floppy == NULL) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + floppy->Get_Geometry(&img_heads, &img_cyl, &img_sect, &img_ssz); + + if (enable_fdc_timer_hack) { + // Hack for Ys II + FDC_WAIT_TIMER_HACK(); + } + + if (reg_ah & 0x10) { // seek to track number in CL + if (img_cyl != 0 && reg_cl >= img_cyl) { + CALLBACK_SCF(true); + reg_ah = 0x00; + /* TODO? Error code? */ + return; + } + + fdc_cyl[drive] = reg_cl; + } + + if (fdc_sect[drive] == 0) + fdc_sect[drive] = 1; + + if (img_ssz >= 1024) + fdc_sz[drive] = 3; + else if (img_ssz >= 512) + fdc_sz[drive] = 2; + else if (img_ssz >= 256) + fdc_sz[drive] = 1; + else + fdc_sz[drive] = 0; + + reg_cl = fdc_cyl[drive]; + reg_dh = fdc_head[drive]; + reg_dl = fdc_sect[drive]; + /* ^ FIXME: A more realistic emulation would return a random number from 1 to N + * where N=sectors/track because the floppy motor is running and tracks + * are moving past the head. */ + reg_ch = fdc_sz[drive]; + + /* per read ID call, increment the sector through the range on disk. + * This is REQUIRED or else MEGDOS will not attempt to read this disk. */ + if (img_sect != 0) { + if ((++fdc_sect[drive]) > img_sect) + fdc_sect[drive] = 1; + } + + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + default: + LOG_MSG("PC-98 INT 1Bh unknown FDC BIOS call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + CALLBACK_SCF(true); + break; + } +} + +static Bitu INT19_PC98_Handler(void) { + LOG_MSG("PC-98 INT 19h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + + return CBRET_NONE; +} + +static Bitu INT1A_PC98_Handler(void) { + /* HACK: This makes the "test" program in DOSLIB work. + * We'll remove this when we implement INT 1Ah */ + if (reg_ax == 0x1000) { + CALLBACK_SCF(false); + reg_ax = 0; + } + + LOG_MSG("PC-98 INT 1Ah unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + + return CBRET_NONE; +} + +static Bitu INT1B_PC98_Handler(void) { + /* As BIOS interfaces for disk I/O go, this is fairly unusual */ + switch (reg_al & 0xF0) { + /* floppy disk access */ + /* AL bits[1:0] = floppy drive number */ + /* Uses INT42 if high density, INT41 if double density */ + /* AH bits[3:0] = command */ + case 0x90: /* 1.2MB HD */ + PC98_BIOS_FDC_CALL(PC98_FLOPPY_HIGHDENSITY|PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_3MODE); + break; + case 0x30: /* 1.44MB HD (NTS: not supported until the early 1990s) */ + case 0xB0: + PC98_BIOS_FDC_CALL(PC98_FLOPPY_HIGHDENSITY|PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_IBMPC); + break; + case 0x70: /* 720KB DD (??) */ + case 0xF0: + PC98_BIOS_FDC_CALL(PC98_FLOPPY_2HEAD|PC98_FLOPPY_RPM_3MODE); // FIXME, correct?? + break; + case 0x20: /* SCSI hard disk BIOS */ + case 0xA0: /* SCSI hard disk BIOS */ + case 0x00: /* SASI hard disk BIOS */ + case 0x80: /* SASI hard disk BIOS */ + PC98_BIOS_SCSI_CALL(); + break; + /* TODO: Other disk formats */ + /* TODO: Future SASI/SCSI BIOS emulation for hard disk images */ + default: + LOG_MSG("PC-98 INT 1Bh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + CALLBACK_SCF(true); + break; + } + + return CBRET_NONE; +} + +void PC98_Interval_Timer_Continue(void) { + /* assume: interrupts are disabled */ + IO_WriteB(0x71,0x00); + // TODO: What time interval is this supposed to be? + if (PIT_TICK_RATE == PIT_TICK_RATE_PC98_8MHZ) + IO_WriteB(0x71,0x4E); + else + IO_WriteB(0x71,0x60); + + IO_WriteB(0x02,IO_ReadB(0x02) & (~(1u << /*IRQ*/0u))); // unmask IRQ0 +} + +unsigned char pc98_dec2bcd(unsigned char c) { + return ((c / 10u) << 4u) + (c % 10u); +} + +static Bitu INT1C_PC98_Handler(void) { + if (reg_ah == 0x00) { /* get time and date */ + time_t curtime; + const struct tm *loctime; + curtime = time (NULL); + loctime = localtime (&curtime); + + unsigned char tmp[6]; + + tmp[0] = pc98_dec2bcd((unsigned int)loctime->tm_year % 100u); + tmp[1] = (((unsigned int)loctime->tm_mon + 1u) << 4u) + (unsigned int)loctime->tm_wday; + tmp[2] = pc98_dec2bcd(loctime->tm_mday); + tmp[3] = pc98_dec2bcd(loctime->tm_hour); + tmp[4] = pc98_dec2bcd(loctime->tm_min); + tmp[5] = pc98_dec2bcd(loctime->tm_sec); + + unsigned long mem = ((unsigned int)SegValue(es) << 4u) + reg_bx; + + for (unsigned int i=0;i < 6;i++) + mem_writeb(mem+i,tmp[i]); + } + else if (reg_ah == 0x02) { /* set interval timer (single event) */ + /* es:bx = interrupt handler to execute + * cx = timer interval in ticks (FIXME: what units of time?) */ + mem_writew(0x1C,reg_bx); + mem_writew(0x1E,SegValue(es)); + mem_writew(0x58A,reg_cx); + + IO_WriteB(0x77,0x36); /* mode 3, binary, low-byte high-byte 16-bit counter */ + + PC98_Interval_Timer_Continue(); + } + else if (reg_ah == 0x03) { /* continue interval timer */ + PC98_Interval_Timer_Continue(); + } + /* TODO: According to the PDF at + * + * http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20NEC%20PC%2d98/Collections/PC%2d9801%20Bible%20%e6%9d%b1%e4%ba%ac%e7%90%86%e7%a7%91%e5%a4%a7%e5%ad%a6EIC%20%281994%29%2epdf + * + * There are additional functions + * + * AH = 04h + * ES:BX = ? + * + * --- + * + * AH = 05h + * ES:BX = ? + * + * --- + * + * AH = 06h + * CX = ? (1-FFFFh) + * DX = ? (20h-8000h Hz) + * + * If any PC-98 games or applications rely on this, let me know. Adding a case for them is easy enough if anyone is interested. --J.C. + */ + else { + LOG_MSG("PC-98 INT 1Ch unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + } + + return CBRET_NONE; +} + +// NTS: According to this PDF, chapter 5, INT 1Dh has additional functions on "High Resolution" PC-98 systems. +// [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] +static Bitu INT1D_PC98_Handler(void) { + LOG_MSG("PC-98 INT 1Dh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + + return CBRET_NONE; +} + +static Bitu INT1E_PC98_Handler(void) { + LOG_MSG("PC-98 INT 1Eh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + + return CBRET_NONE; +} + +void PC98_EXTMEMCPY(void) { + bool enabled = MEM_A20_Enabled(); + MEM_A20_Enable(true); + + Bitu bytes = ((reg_cx - 1u) & 0xFFFFu) + 1u; // bytes, except that 0 == 64KB + PhysPt data = SegPhys(es)+reg_bx; + PhysPt source = (mem_readd(data + 0x12u) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data + 0x17u) << 24u) + reg_si; + PhysPt dest = (mem_readd(data + 0x1Au) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data + 0x1Fu) << 24u) + reg_di; + + LOG_MSG("PC-98 memcpy: src=0x%x dst=0x%x data=0x%x count=0x%x", + (unsigned int)source,(unsigned int)dest,(unsigned int)data,(unsigned int)bytes); + + MEM_BlockCopy(dest,source,bytes); + MEM_A20_Enable(enabled); + Segs.limit[cs] = 0xFFFF; + Segs.limit[ds] = 0xFFFF; + Segs.limit[es] = 0xFFFF; + Segs.limit[ss] = 0xFFFF; + + CALLBACK_SCF(false); +} + +static Bitu INT1F_PC98_Handler(void) { + switch (reg_ah) { + case 0x90: + /* Copy extended memory */ + PC98_EXTMEMCPY(); + break; + default: + LOG_MSG("PC-98 INT 1Fh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + CALLBACK_SCF(true); + break; + } + + return CBRET_NONE; +} + +static Bitu INTGEN_PC98_Handler(void) { + LOG_MSG("PC-98 INT stub unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + + return CBRET_NONE; +} + +/* This interrupt should only exist while the DOS kernel is active. + * On actual PC-98 MS-DOS this is a direct interface to MS-DOS's built-in ANSI CON driver. + * + * CL = major function call number + * AH = minor function call number + * DX = data?? */ + +void PC98_INTDC_WriteChar(unsigned char b); + +void INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut_def &def,const Bitu ofs) { + unsigned int i; + + for (i=0;i < 0x0F;i++) + def.shortcut[i] = mem_readb(ofs+0x0+i); + + for (i=0;i < 0x0F && def.shortcut[i] != 0;) i++; + def.length = i; +} + +void INTDC_STORE_FUNCDEC(const Bitu ofs,const pc98_func_key_shortcut_def &def) { + for (unsigned int i=0;i < 0x0F;i++) mem_writeb(ofs+0x0+i,def.shortcut[i]); + mem_writeb(ofs+0xF,0); +} + +void INTDC_LOAD_EDITDEC(pc98_func_key_shortcut_def &def,const Bitu ofs) { + unsigned int i; + + for (i=0;i < 0x05;i++) + def.shortcut[i] = mem_readb(ofs+0x0+i); + + for (i=0;i < 0x05 && def.shortcut[i] != 0;) i++; + def.length = i; +} + +void INTDC_STORE_EDITDEC(const Bitu ofs,const pc98_func_key_shortcut_def &def) { + for (unsigned int i=0;i < 0x05;i++) mem_writeb(ofs+0x0+i,def.shortcut[i]); + mem_writeb(ofs+0x5,0); +} + +bool inhibited_ControlFn(void) { + return real_readb(0x60,0x10C) & 0x01; +} + +static const char *fneditkeys[11] = { + "ROLLUP", + "ROLLDOWN", + "INS", + "DEL", + "UPARROW", + "LEFTARROW", + "RIGHTARROW", + "DOWNARROW", + "HOMECLR", + "HELP", + "KEYPAD-" +}; + +void DEBUG_INTDC_FnKeyMapInfo(void) { + if (!IS_PC98_ARCH) { + DEBUG_ShowMsg("INT DCh has no meaning except in PC-98 mode"); + } + else if (dos_kernel_disabled) { + DEBUG_ShowMsg("INT DCh FnKey mapping has no meaning outside the DOS environment"); + } + else { + DEBUG_ShowMsg("INT DCh FnKey mapping. Ctrl+Fn builtin inhibited=%s",inhibited_ControlFn()?"yes":"no"); + for (unsigned int i=0;i < 10;i++) + DEBUG_ShowMsg(" F%u: %s",i+1,pc98_func_key[i].debugToString().c_str()); + for (unsigned int i=0;i < 5;i++) + DEBUG_ShowMsg(" VF%u: %s",i+1,pc98_vfunc_key[i].debugToString().c_str()); + + for (unsigned int i=0;i < 10;i++) + DEBUG_ShowMsg(" Shift+F%u: %s",i+1,pc98_func_key_shortcut[i].debugToString().c_str()); + for (unsigned int i=0;i < 5;i++) + DEBUG_ShowMsg(" Shift+VF%u: %s",i+1,pc98_vfunc_key_shortcut[i].debugToString().c_str()); + + for (unsigned int i=0;i < 10;i++) + DEBUG_ShowMsg(" Control+F%u: %s",i+1,pc98_func_key_ctrl[i].debugToString().c_str()); + for (unsigned int i=0;i < 5;i++) + DEBUG_ShowMsg(" Control+VF%u: %s",i+1,pc98_vfunc_key_ctrl[i].debugToString().c_str()); + + for (unsigned int i=0;i < 11;i++) + DEBUG_ShowMsg(" %s: %s",fneditkeys[i],pc98_editor_key_escapes[i].debugToString().c_str()); + } +} + +/* PC-98 application notes, that are NOT DOSBox-X bugs because they occur on real MS-DOS as well: + * + * VZ.COM - If the function key row was hidden when VZ.COM is started, VZ.COM will not restore the + * function key row. VZ.COM's function key shortcuts affect Fn and Shift+Fn keys and the + * text they display even if VZ.COM also disables the Ctrl+F7 shortcut that lets you + * toggle the function key row, which makes displaying the Shift+Fn key shortcuts impossible + * unless the function key row was left showing that at startup. + */ + +static Bitu INTDC_PC98_Handler(void) { + if (dos_kernel_disabled) goto unknown; + + switch (reg_cl) { + /* Tracking implementation according to [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20NEC%20PC%2d98/Collections/Undocumented%209801%2c%209821%20Volume%201%20English%20translation/INTDC%2eTXT] */ + case 0x0C: /* CL=0x0C General entry point to read function key state */ +/*=================================================================================================== +Table [List of key specification values and corresponding keys] + ------------------------+--------------------------------------------------- + Key specification value | Corresponding key + ------------------------+--------------------------------------------------- + 0000h | [f・1] to [f・10], [SHIFT] + [f・1] to [SHIFT] + [f・10], + | [ROLL UP], [ROLL DOWN], [INS], [DEL], [↑], [←], [→], [↓], + | [HOME/CLR], [HELP], [SHIFT] + [HOME/CLR] + 0001 to 000Ah | [f・1] to [f・10] + 000B to 0014h | [SHIFT] + [f・1] to [SHIFT] + [f・10] + 0015h | [ROLL UP] + 0016h | [ROLL DOWN] + 0017h | [INS] + 0018h | [DEL] + 0019h | [↑] + 001Ah | [←] + 001Bh | [→] + 001Ch | [↓] + 001Dh | [HOME/CLR](XA keyboard:[CLR]) + 001Eh | [HELP] + 001Fh | [SHIFT]+[HOME/CLR](XA keyboard:[HOME]) + 0020-0024h | [vf・1]-[vf・5] + 0025-0029h | [SHIFT]+[vf・1]-[vf・5] + 002A-0033h | [CTRL]+[f・1]-[f・10] + 0034-0038h | [CTRL]+[vf・1]-[vf・5] + 0039h | [CTRL]+[XFER]/[NFER] (Undocumented) + 003Ah | [CTRL]+[XFER]/[NFER],[CTRL]+[f・1]~[f・10] + | (Undocumented) + 00FFh | [f・1]〜[f・10],[vf・1]〜[vf・5], + | [SHIFT]+[f・1]〜[SHIFT]+[f・10],[SHIFT]+[vf・1]〜[vf・5], + | [ROLL UP],[ROLL DOWN],[INS],[DEL],[↑],[←],[→],[↓], + | [HOME/CLR],[HELP],[SHIFT]+[HOME/CLR], + | [CTRL]+[f・1] to [f・10], [CTRL]+[vf・1] to [vf・5] + ------------------------+--------------------------------------------------- + + Table [Supported range of key specification values for each MS-DOS version] + ------------------------+---+---+---+---+---+---+---+---+-----+ + Key specification value | MS-DOS version (PS98-XXX) + |111|121|122|123|125|127|129|011|XA125 + ------------------------+---+---+---+---+---+---+---+---+-----+ + 0000 to 001Fh | ○ | ○ | ○ | ○ | ○ | ○ | ○ | ○ | ○ + 0020 to 0029h | × | × | × | × | × | × | × | ○ | ○ + 002A-0033h | × | × | × | × | ○ | ○ | ○ | ○ | △ + 0034-0038h | × | × | × | × | × | × | × | ○ | △ + 0039h | × | × | × | × | × | ○ | ○ | ○ | × + 003Ah | × | × | × | × | ○ | ○ | ○ | ○ | × + 00FFh | × | × | × | × | × | × | × | ○ | ○ + ------------------------+---+---+---+---+---+---+---+---+-----+ + * PC-98LT/HA is the same as PS98-127. + * MS-DOS 3.3(all), 5.0, 5.0A is the same as PS98-011. + * For the PS98-XA125 triangle mark, the keys are as follows. + Key values 002B to 0033h specify [CTRL]+[f・1] to [f・9]. + Key values 0035 to 0038h specify [CTRL]+[vf・1] to [vf・4]. +=============================================================================================== + * NTS: According to a translation table in the MS-DOS kernel, where + * AX=1h to AX=29h inclusive look up from this 0x29-element table: + * + * Table starts with AX=1h, ends with AX=29h + * + * 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 + * | | | | | | | | | | | | | | | | + * 0ADC:00003DE0 01 02 03 04 05 06 07 08 09 0A 10 11 12 13 14 15 ................ + * 0ADC:00003DF0 16 17 18 19 1F 20 21 22 23 24 25 26 27 28 29 0B ..... !"#$%&'(). + * 0ADC:00003E00 0C 0D 0E 0F 1A 1B 1C 1D 1E| + * + * The table is read, then the byte is decremented by one. + * + * If the result of that is less than 0x1E, it's an index into + * the 16 byte/entry Fn key table. + * + * If the result is 0x1E or larger, then (result - 0x1E) is an + * index into the editor table, 8 bytes/entry. + * + * Meanings: + * + * 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 + * | | | | | | | | | | | | | | | | + * 0ADC:00003DE0 01 02 03 04 05 06 07 08 09 0A 10 11 12 13 14 15 ................ + * | --- Function keys F1-F10 ---| Fn shift F1-F6 - + * 0ADC:00003DF0 16 17 18 19 1F 20 21 22 23 24 25 26 27 28 29 0B ..... !"#$%&'(). + * | Sh F7-F10 | ------- EDITOR KEYS -----------| - + * 0ADC:00003E00 0C 0D 0E 0F 1A 1B 1C 1D 1E| + * | --------- | ------------ | +===============================================================================================*/ + if (reg_ax == 0x00) { /* Read all state, DS:DX = data to store to */ +/*============================================================================================= + DS:DX contains + +Table [Programmable key setting data buffer structure] + (1) Key specification value 0000h + -------+--------------------+-------------------------------------- + Offset | Key type | Size of key setting data + -------+--------------------+-------------------------------------- + +0000h | [f・1] | 16 bytes (15 bytes of key setting data + 00h) + +0010h | [f・2] | 16 bytes (15 bytes of key setting data + 00h) + +0020h | [f・3] | 16 bytes (15 bytes of key setting data + 00h) + +0030h | [f・4] | 16 bytes (15 bytes of key setting data + 00h) + +0040h | [f・5] | 16 bytes (15 bytes of key setting data + 00h) + +0050h | [f・6] | 16 bytes (15 bytes of key setting data + 00h) + +0060h | [f・7] | 16 bytes (15 bytes of key setting data + 00h) + +0070h | [f・8] | 16 bytes (15 bytes of key setting data + 00h) + +0080h | [f・9] | 16 bytes (15 bytes of key setting data + 00h) + +0090h | [f・10] | 16 bytes (15 bytes of key setting data + 00h) + +00A0h | [SHIFT]+[f・1] | 16 bytes (15 bytes of key setting data + 00h) + +00B0h | [SHIFT]+[f・2] | 16 bytes (15 bytes of key setting data + 00h) + +00C0h | [SHIFT]+[f・3] | 16 bytes (15 bytes of key setting data + 00h) + +00D0h | [SHIFT]+[f・4] | 16 bytes (15 bytes of key setting data + 00h) + +00E0h | [SHIFT]+[f・5] | 16 bytes (15 bytes of key setting data + 00h) + +00F0h | [SHIFT]+[f・6] | 16 bytes (15 bytes of key setting data + 00h) + +0100h | [SHIFT]+[f・7] | 16 bytes (15 bytes of key setting data + 00h) + +0110h | [SHIFT]+[f・8] | 16 bytes (15 bytes of key setting data + 00h) + +0120h | [SHIFT]+[f・9] | 16 bytes (15 bytes of key setting data + 00h) + +0130h | [SHIFT]+[f・10] | 16 bytes (15 bytes of key setting data + 00h) + +0140h | [ROLL UP] | 6 bytes (5 bytes of key setting data + 00h) + +0146h | [ROLL DOWN] | 6 bytes (5 bytes of key setting data + 00h) + +014Ch | [INS] | 6 bytes (5 bytes of key setting data + 00h) + +0152h | [DEL] | 6 bytes (5 bytes of key setting data + 00h) + +0158h | [↑] | 6 bytes (5 bytes of key setting data + 00h) + +015Eh | [←] | 6 bytes (5 bytes of key setting data + 00h) + +0164h | [→] | 6 bytes (5 bytes of key setting data + 00h) + +016Ah | [↓] | 6 bytes (5 bytes of key setting data + 00h) + +0170h | [HOME/CLR] | 6 bytes (5 bytes of key setting data + 00h) + +0176h | [HELP] | 6 bytes (5 bytes of key setting data + 00h) + +017Ch | [SHIFT]+[HOME/CLR] | 6 bytes (5 bytes of key setting data + 00h) + -------+--------------------+-------------------------------------- +===============================================================================================*/ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + + /* function keys F1-F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_STORE_FUNCDEC(ofs,pc98_func_key[f]); + /* function keys Shift+F1 - Shift+F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[f]); + /* editor keys */ + for (unsigned int f=0;f < 11;f++,ofs += 6) + INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[f]); + + goto done; + } + else if (reg_ax >= 0x01 && reg_ax <= 0x0A) { /* Read individual function keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_STORE_FUNCDEC(ofs,pc98_func_key[reg_ax - 0x01]); + goto done; + } + else if (reg_ax >= 0x0B && reg_ax <= 0x14) { /* Read individual shift + function keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[reg_ax - 0x0B]); + goto done; + } + else if (reg_ax >= 0x15 && reg_ax <= 0x1F) { /* Read individual editor keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[reg_ax - 0x15]); + goto done; + } + else if (reg_ax >= 0x20 && reg_ax <= 0x24) { /* Read VF1-VF5 keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key[reg_ax - 0x20]); + goto done; + } + else if (reg_ax >= 0x25 && reg_ax <= 0x29) { /* Read shift VF1-VF5 keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_shortcut[reg_ax - 0x25]); + goto done; + } + else if (reg_ax >= 0x2A && reg_ax <= 0x33) { /* Read individual function keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_STORE_FUNCDEC(ofs,pc98_func_key_ctrl[reg_ax - 0x2A]); + goto done; + } + else if (reg_ax >= 0x34 && reg_ax <= 0x38) { /* Read control VF1-VF5 keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_ctrl[reg_ax - 0x34]); + goto done; + } + else if (reg_ax == 0xFF) { /* Extended version of the API when AX == 0, DS:DX = data to store to */ + /* DS:DX contains + * 16*10 bytes, 16 bytes per entry for function keys F1-F10 + * 16*5 bytes, 16 bytes per entry for VF1-VF5 + * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 + * 16*5 bytes, 16 bytes per entry for shift VF1-VF5 + * 6*11 bytes, 6 bytes per entry for editor keys + * 16*10 bytes, 16 bytes per entry for function key shortcuts Control+F1 to Control+F10 + * 16*5 bytes, 16 bytes per entry for control VF1-VF5 + * + * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + + /* function keys F1-F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_STORE_FUNCDEC(ofs,pc98_func_key[f]); + /* VF1-VF5 */ + for (unsigned int f=0;f < 5;f++,ofs += 16) + INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key[f]); + /* function keys Shift+F1 - Shift+F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[f]); + /* VF1-VF5 */ + for (unsigned int f=0;f < 5;f++,ofs += 16) + INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_shortcut[f]); + /* editor keys */ + for (unsigned int f=0;f < 11;f++,ofs += 6) + INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[f]); + /* function keys Control+F1 - Control+F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_STORE_FUNCDEC(ofs,pc98_func_key_ctrl[f]); + /* VF1-VF5 */ + for (unsigned int f=0;f < 5;f++,ofs += 16) + INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_ctrl[f]); + + goto done; + } + goto unknown; + case 0x0D: /* CL=0x0D General entry point to set function key state */ + if (reg_ax == 0xFF) { /* Extended version of the API when AX == 0, DS:DX = data to set */ + /* DS:DX contains + * 16*10 bytes, 16 bytes per entry for function keys F1-F10 + * 16*5 bytes, 16 bytes per entry for VF1-VF5 + * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 + * 16*5 bytes, 16 bytes per entry for shift VF1-VF5 + * 6*11 bytes, 6 bytes per entry for editor keys + * 16*10 bytes, 16 bytes per entry for function key shortcuts Control+F1 to Control+F10 + * 16*5 bytes, 16 bytes per entry for control VF1-VF5 + * + * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + + /* function keys F1-F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_LOAD_FUNCDEC(pc98_func_key[f],ofs); + /* VF1-VF5 */ + for (unsigned int f=0;f < 5;f++,ofs += 16) + INTDC_LOAD_FUNCDEC(pc98_vfunc_key[f],ofs); + /* function keys Shift+F1 - Shift+F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[f],ofs); + /* Shift+VF1 - Shift+VF5 */ + for (unsigned int f=0;f < 5;f++,ofs += 16) + INTDC_LOAD_FUNCDEC(pc98_vfunc_key_shortcut[f],ofs); + /* editor keys */ + for (unsigned int f=0;f < 11;f++,ofs += 6) + INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[f],ofs); + /* function keys Control+F1 - Control+F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_LOAD_FUNCDEC(pc98_func_key_ctrl[f],ofs); + /* Shift+VF1 - Shift+VF5 */ + for (unsigned int f=0;f < 5;f++,ofs += 16) + INTDC_LOAD_FUNCDEC(pc98_vfunc_key_ctrl[f],ofs); + + update_pc98_function_row(pc98_function_row_mode,true); + goto done; + } + else if (reg_ax >= 0x01 && reg_ax <= 0x0A) { /* Read individual function keys, DS:DX = data to set */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_LOAD_FUNCDEC(pc98_func_key[reg_ax - 0x01],ofs); + goto done; + } + else if (reg_ax >= 0x0B && reg_ax <= 0x14) { /* Read individual shift + function keys, DS:DX = data to set */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[reg_ax - 0x0B],ofs); + goto done; + } + else if (reg_ax >= 0x15 && reg_ax <= 0x1F) { /* Read individual editor keys, DS:DX = data to set */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[reg_ax - 0x15],ofs); + goto done; + } + else if (reg_ax >= 0x20 && reg_ax <= 0x24) { /* Read VF1-VF5 keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_LOAD_FUNCDEC(pc98_vfunc_key[reg_ax - 0x20],ofs); + goto done; + } + else if (reg_ax >= 0x25 && reg_ax <= 0x29) { /* Read shift VF1-VF5 keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_LOAD_FUNCDEC(pc98_vfunc_key_shortcut[reg_ax - 0x25],ofs); + goto done; + } + else if (reg_ax >= 0x2A && reg_ax <= 0x33) { /* Read individual function keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_LOAD_FUNCDEC(pc98_func_key_ctrl[reg_ax - 0x2A],ofs); + goto done; + } + else if (reg_ax >= 0x34 && reg_ax <= 0x38) { /* Read control VF1-VF5 keys, DS:DX = data to store to */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + INTDC_LOAD_FUNCDEC(pc98_vfunc_key_ctrl[reg_ax - 0x34],ofs); + goto done; + } + else if (reg_ax == 0x00) { /* Read all state, DS:DX = data to set */ + /* DS:DX contains + * 16*10 bytes, 16 bytes per entry for function keys F1-F10 + * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 + * 6*11 bytes, 6 bytes per entry of editor keys (INS, DEL, etc) that match a specific scan code range + * + * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ + Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; + + /* function keys F1-F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_LOAD_FUNCDEC(pc98_func_key[f],ofs); + /* function keys Shift+F1 - Shift+F10 */ + for (unsigned int f=0;f < 10;f++,ofs += 16) + INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[f],ofs); + /* editor keys */ + for (unsigned int f=0;f < 11;f++,ofs += 6) + INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[f],ofs); + + update_pc98_function_row(pc98_function_row_mode,true); + goto done; + } + goto unknown; + case 0x0F: + if (reg_ax == 0) { /* inhibit Control+Fn shortcuts */ + real_writeb(0x60,0x10C,real_readb(0x60,0x10C) | 0x01); + goto done; + } + else if (reg_ax == 1) { /* enable Control+Fn shortcuts */ + real_writeb(0x60,0x10C,real_readb(0x60,0x10C) & (~0x01)); + goto done; + } + goto unknown; + case 0x10: + if (reg_ah == 0x00) { /* CL=0x10 AH=0x00 DL=char write char to CON */ + PC98_INTDC_WriteChar(reg_dl); + goto done; + } + else if (reg_ah == 0x01) { /* CL=0x10 AH=0x01 DS:DX write string to CON */ + /* According to the example at http://tepe.tec.fukuoka-u.ac.jp/HP98/studfile/grth/gt10.pdf + * the string ends in '$' just like the main DOS string output function. */ + uint16_t ofs = reg_dx; + do { + unsigned char c = real_readb(SegValue(ds),ofs++); + if (c == '$') break; + PC98_INTDC_WriteChar(c); + } while (1); + goto done; + } + else if (reg_ah == 0x02) { /* CL=0x10 AH=0x02 DL=attribute set console output attribute */ + /* Ref: https://nas.jmc/jmcs/docs/browse/Computer/Platform/PC%2c%20NEC%20PC%2d98/Collections/Undocumented%209801%2c%209821%20Volume%202%20%28webtech.co.jp%29%20English%20translation/memdos%2eenglish%2dgoogle%2dtranslate%2etxt + * + * DL is the attribute byte (in the format written directly to video RAM, not the ANSI code) + * + * NTS: Reverse engineering INT DCh shows it sets both 71Dh and 73Ch as below */ + real_writeb(0x60,0x11D,reg_dl); + real_writeb(0x60,0x13C,reg_dx); + goto done; + } + else if (reg_ah == 0x03) { /* CL=0x10 AH=0x03 DL=X-coord DH=Y-coord set cursor position */ + void INTDC_CL10h_AH03h(uint16_t raw); + INTDC_CL10h_AH03h(reg_dx); + goto done; + } + else if (reg_ah == 0x04) { /* CL=0x10 AH=0x04 Move cursor down one line */ + void INTDC_CL10h_AH04h(void); + INTDC_CL10h_AH04h(); + goto done; + } + else if (reg_ah == 0x05) { /* CL=0x10 AH=0x05 Move cursor up one line */ + void INTDC_CL10h_AH05h(void); + INTDC_CL10h_AH05h(); + goto done; + } + else if (reg_ah == 0x06) { /* CL=0x10 AH=0x06 DX=count Move cursor up multiple lines */ + void INTDC_CL10h_AH06h(uint16_t count); + INTDC_CL10h_AH06h(reg_dx); + goto done; + } + else if (reg_ah == 0x07) { /* CL=0x10 AH=0x07 DX=count Move cursor down multiple lines */ + void INTDC_CL10h_AH07h(uint16_t count); + INTDC_CL10h_AH07h(reg_dx); + goto done; + } + else if (reg_ah == 0x08) { /* CL=0x10 AH=0x08 DX=count Move cursor right multiple lines */ + void INTDC_CL10h_AH08h(uint16_t count); + INTDC_CL10h_AH08h(reg_dx); + goto done; + } + else if (reg_ah == 0x09) { /* CL=0x10 AH=0x09 DX=count Move cursor left multiple lines */ + void INTDC_CL10h_AH09h(uint16_t count); + INTDC_CL10h_AH09h(reg_dx); + goto done; + } + else if (reg_ah == 0x0a) { /* CL=0x10 AH=0x0A DL=pattern Erase screen */ + void INTDC_CL10h_AH0Ah(uint16_t pattern); + INTDC_CL10h_AH0Ah(reg_dx); + goto done; + } + else if (reg_ah == 0x0b) { /* CL=0x10 AH=0x0B DL=pattern Erase lines */ + void INTDC_CL10h_AH0Bh(uint16_t pattern); + INTDC_CL10h_AH0Bh(reg_dx); + goto done; + } + else if (reg_ah == 0x0c) { /* CL=0x10 AH=0x0C DL=count Insert lines */ + void INTDC_CL10h_AH0Ch(uint16_t count); + INTDC_CL10h_AH0Ch(reg_dx); + goto done; + } + else if (reg_ah == 0x0d) { /* CL=0x10 AH=0x0D DL=count Erase lines */ + void INTDC_CL10h_AH0Dh(uint16_t count); + INTDC_CL10h_AH0Dh(reg_dx); + goto done; + } + else if (reg_ah == 0x0E) { /* CL=0x10 AH=0x0E DL=mode Change character mode */ + void pc98_set_char_mode(bool mode); + pc98_set_char_mode(reg_dl == 0); + goto done; + } + goto unknown; + default: /* some compilers don't like not having a default case */ + goto unknown; + } + +done: + return CBRET_NONE; + +unknown: + LOG_MSG("PC-98 INT DCh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + + return CBRET_NONE; +} + +static Bitu INTF2_PC98_Handler(void) { + LOG_MSG("PC-98 INT F2h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + + return CBRET_NONE; +} + +extern void lio_read_parameter(); +extern uint8_t PC98_BIOS_LIO_GINIT(); +extern uint8_t PC98_BIOS_LIO_GSCREEN(); +extern uint8_t PC98_BIOS_LIO_GVIEW(); +extern uint8_t PC98_BIOS_LIO_GCOLOR1(); +extern uint8_t PC98_BIOS_LIO_GCOLOR2(); +extern uint8_t PC98_BIOS_LIO_GCLS(); +extern uint8_t PC98_BIOS_LIO_GPSET(); +extern uint8_t PC98_BIOS_LIO_GLINE(); +extern uint8_t PC98_BIOS_LIO_GCIRCLE(); +extern uint8_t PC98_BIOS_LIO_GPAINT1(); +extern uint8_t PC98_BIOS_LIO_GPAINT2(); +extern uint8_t PC98_BIOS_LIO_GGET(); +extern uint8_t PC98_BIOS_LIO_GPUT1(); +extern uint8_t PC98_BIOS_LIO_GPUT2(); +extern uint8_t PC98_BIOS_LIO_GPOINT2(); + +// for more information see [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] +static Bitu PC98_BIOS_LIO(void) { + uint8_t ret = 0; + const char *call_name = "?"; + + lio_read_parameter(); + switch (reg_al) { + case 0xA0: // GINIT + ret = PC98_BIOS_LIO_GINIT(); + break; + case 0xA1: // GSCREEN + ret = PC98_BIOS_LIO_GSCREEN(); + break; + case 0xA2: // GVIEW + ret = PC98_BIOS_LIO_GVIEW(); + break; + case 0xA3: // GCOLOR1 + ret = PC98_BIOS_LIO_GCOLOR1(); + break; + case 0xA4: // GCOLOR2 + ret = PC98_BIOS_LIO_GCOLOR2(); + break; + case 0xA5: // GCLS + ret = PC98_BIOS_LIO_GCLS(); + break; + case 0xA6: // GPSET + ret = PC98_BIOS_LIO_GPSET(); + break; + case 0xA7: // GLINE + ret = PC98_BIOS_LIO_GLINE(); + break; + case 0xA8: // GCIRCLE + ret = PC98_BIOS_LIO_GCIRCLE(); + break; + case 0xA9: // GPAINT1 + ret = PC98_BIOS_LIO_GPAINT1(); + break; + case 0xAA: // GPAINT2 + ret = PC98_BIOS_LIO_GPAINT2(); + break; + case 0xAB: // GGET + ret = PC98_BIOS_LIO_GGET(); + break; + case 0xAC: // GPUT1 + ret = PC98_BIOS_LIO_GPUT1(); + break; + case 0xAD: // GPUT2 + ret = PC98_BIOS_LIO_GPUT2(); + break; + case 0xAE: // GROLL + call_name = "GROLL"; + goto unknown; + case 0xAF: // GPOINT2 + ret = PC98_BIOS_LIO_GPOINT2(); + break; + case 0xCE: // GCOPY + call_name = "GCOPY"; + goto unknown; + case 0x00: // GRAPH BIO + call_name = "GRAPH BIO"; + goto unknown; + default: + unknown: + /* on entry, AL (from our BIOS code) is set to the call number that lead here */ + LOG_MSG("PC-98 BIOS LIO graphics call 0x%02x '%s' with AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", + reg_al, + call_name, + reg_ax, + reg_bx, + reg_cx, + reg_dx, + reg_si, + reg_di, + SegValue(ds), + SegValue(es)); + break; + }; + // from Yksoft1's patch + reg_ah = ret; + + return CBRET_NONE; +} + + +extern bool enable_weitek; + +static Bitu INT11_Handler(void) { + if (enable_weitek) reg_eax = (1u << 24u)/*Weitek math coprocessor present*/; + reg_ax=mem_readw(BIOS_CONFIGURATION); + return CBRET_NONE; +} +/* + * Define the following define to 1 if you want dosbox-x to check + * the system time every 5 seconds and adjust 1/2 a second to sync them. + */ +#ifndef DOSBOX_CLOCKSYNC +#define DOSBOX_CLOCKSYNC 0 +#endif + +uint32_t BIOS_HostTimeSync(uint32_t /*ticks*/) { +#if 0//DISABLED TEMPORARILY + uint32_t milli = 0; +#if defined(DB_HAVE_CLOCK_GETTIME) && ! defined(WIN32) + struct timespec tp; + clock_gettime(CLOCK_REALTIME,&tp); + + struct tm *loctime; + loctime = localtime(&tp.tv_sec); + milli = (uint32_t) (tp.tv_nsec / 1000000); +#else + /* Setup time and date */ + struct timeb timebuffer; + ftime(&timebuffer); + + const struct tm *loctime; + loctime = localtime (&timebuffer.time); + milli = (uint32_t) timebuffer.millitm; +#endif + /* + loctime->tm_hour = 23; + loctime->tm_min = 59; + loctime->tm_sec = 45; + loctime->tm_mday = 28; + loctime->tm_mon = 2-1; + loctime->tm_year = 2007 - 1900; + */ + +// FIXME: Why is the BIOS filling in the DOS kernel's date? That should be done when DOS boots! + dos.date.day=(uint8_t)loctime->tm_mday; + dos.date.month=(uint8_t)loctime->tm_mon+1; + dos.date.year=(uint16_t)loctime->tm_year+1900; + + uint32_t nticks=(uint32_t)(((double)( + (unsigned int)loctime->tm_hour*3600u*1000u+ + (unsigned int)loctime->tm_min*60u*1000u+ + (unsigned int)loctime->tm_sec*1000u+ + milli))*(((double)PIT_TICK_RATE/65536.0)/1000.0)); + + /* avoid stepping back from off by one errors */ + if (nticks == (ticks - 1u)) + nticks = ticks; + + return nticks; +#endif + return 0; +} + +// TODO: make option +bool enable_bios_timer_synchronize_keyboard_leds = true; + +void KEYBOARD_SetLEDs(uint8_t bits); + +void BIOS_KEYBOARD_SetLEDs(Bitu state) { + Bitu x = mem_readb(BIOS_KEYBOARD_LEDS); + + x &= ~7u; + x |= (state & 7u); + mem_writeb(BIOS_KEYBOARD_LEDS,x); + KEYBOARD_SetLEDs(state); +} + +/* PC-98 IRQ 0 system timer */ +static Bitu INT8_PC98_Handler(void) { + uint16_t counter = mem_readw(0x58A) - 1; + mem_writew(0x58A,counter); + + /* NTS 2018/02/23: I just confirmed from the ROM BIOS of an actual + * PC-98 system that this implementation and Neko Project II + * are 100% accurate to what the BIOS actually does. + * INT 07h really is the "timer tick" interrupt called + * from INT 08h / IRQ 0, and the BIOS really does call + * INT 1Ch AH=3 from INT 08h if the tick count has not + * yet reached zero. + * + * I'm guessing NEC's BIOS developers invented this prior + * to the Intel 80286 and it's INT 07h + * "Coprocessor not present" exception. */ + + if (counter == 0) { + /* mask IRQ 0 */ + IO_WriteB(0x02,IO_ReadB(0x02) | 0x01); + /* ack IRQ 0 */ + IO_WriteB(0x00,0x20); + /* INT 07h */ + CPU_Interrupt(7,CPU_INT_SOFTWARE,reg_eip); + } + else { + /* ack IRQ 0 */ + IO_WriteB(0x00,0x20); + /* make sure it continues ticking */ + PC98_Interval_Timer_Continue(); + } + + return CBRET_NONE; +} + + +extern bool cmos_sync_flag; +extern uint8_t cmos_sync_sec,cmos_sync_min,cmos_sync_hour; + +extern bool sync_time, manualtime; +bool sync_time_timerrate_warning = false; + +uint32_t PIT0_GetAssignedCounter(void); + +static Bitu INT8_Handler(void) { + /* Increase the bios tick counter */ + uint32_t value = mem_readd(BIOS_TIMER) + 1; + if(value >= 0x1800B0) { + // time wrap at midnight + mem_writeb(BIOS_24_HOURS_FLAG,mem_readb(BIOS_24_HOURS_FLAG)+1); + value=0; + } + + /* Legacy BIOS behavior: This isn't documented at all but most BIOSes + check the BIOS data area for LED keyboard status. If it sees that + value change, then it sends it to the keyboard. This is why on + older DOS machines you could change LEDs by writing to 40:17. + We have to emulate this also because Windows 3.1/9x seems to rely on + it when handling the keyboard from its own driver. Their driver does + hook the keyboard and handles keyboard I/O by itself, but it still + allows the BIOS to do the keyboard magic from IRQ 0 (INT 8h). Yech. */ + if (enable_bios_timer_synchronize_keyboard_leds) { + Bitu should_be = (mem_readb(BIOS_KEYBOARD_STATE) >> 4) & 7; + Bitu led_state = (mem_readb(BIOS_KEYBOARD_LEDS) & 7); + + if (should_be != led_state) + BIOS_KEYBOARD_SetLEDs(should_be); + } + + if (sync_time && cmos_sync_flag) { + value = (uint32_t)((cmos_sync_hour*3600+cmos_sync_min*60+cmos_sync_sec)*(float)PIT_TICK_RATE/65536.0); + cmos_sync_flag = false; + } +#if 0//DISABLED TEMPORARILY + if (sync_time&&!manualtime) { +#if DOSBOX_CLOCKSYNC + static bool check = false; + if((value %50)==0) { + if(((value %100)==0) && check) { + check = false; + time_t curtime;struct tm *loctime; + curtime = time (NULL);loctime = localtime (&curtime); + uint32_t ticksnu = (uint32_t)((loctime->tm_hour*3600+loctime->tm_min*60+loctime->tm_sec)*(float)PIT_TICK_RATE/65536.0); + int32_t bios = value;int32_t tn = ticksnu; + int32_t diff = tn - bios; + if(diff>0) { + if(diff < 18) { diff = 0; } else diff = 9; + } else { + if(diff > -18) { diff = 0; } else diff = -9; + } + + value += diff; + } else if((value%100)==50) check = true; + } +#endif + + /* synchronize time=true is based around the assumption + * that the timer is left ticking at the standard 18.2Hz + * rate. If that is not true, and this IRQ0 handler is + * being called faster, then synchronization will not + * work properly. + * + * Two 1996 demoscene entries sl_fokus.zip and sl_haloo.zip + * are known to program the timer to run faster (58Hz and + * 150Hz) yet use BIOS_TIMER from the BIOS data area to + * track the passage of time. Synchronizing time that way + * will only lead to BIOS_TIMER values that repeat or go + * backwards and will break the demo. */ + if (PIT0_GetAssignedCounter() >= 0xFFFF/*Should be 0x10000 but we'll accept some programs might write 0xFFFF*/) { + uint32_t BIOS_HostTimeSync(uint32_t ticks); + value = BIOS_HostTimeSync(value); + + if (sync_time_timerrate_warning) { + sync_time_timerrate_warning = false; + LOG(LOG_MISC,LOG_WARN)("IRQ0 timer rate restored to 18.2Hz and synchronize time=true, resuming synchronization. BIOS_TIMER may jump backwards suddenly."); + } + } + else { + if (!sync_time_timerrate_warning) { + /* Okay, you changed the tick rate. That affects BIOS_TIMER + * and therefore counts as manual time. Sorry. */ + sync_time_timerrate_warning = true; + LOG(LOG_MISC,LOG_WARN)("IRQ0 timer rate is not 18.2Hz and synchronize time=true, disabling synchronization until normal rate restored."); + } + } + } +#endif + mem_writed(BIOS_TIMER,value); + + if(bootdrive>=0) { +#if (defined(WIN32) && !defined(HX_DOS) || defined(LINUX) && C_X11 || defined(MACOSX)) && (defined(C_SDL2) || defined(SDL_DOSBOX_X_SPECIAL)) + SetIMPosition(); +#endif + } else if (IS_DOSV && DOSV_CheckCJKVideoMode()) { + INT8_DOSV(); + } else if(J3_IsJapanese()) { + INT8_J3(); + } else if (IS_DOS_CJK) { +#if (defined(WIN32) && !defined(HX_DOS) || defined(LINUX) && C_X11 || defined(MACOSX)) && (defined(C_SDL2) || defined(SDL_DOSBOX_X_SPECIAL)) + SetIMPosition(); +#endif + } + + /* decrement FDD motor timeout counter; roll over on earlier PC, stop at zero on later PC */ + uint8_t val = mem_readb(BIOS_DISK_MOTOR_TIMEOUT); + if (val || !IS_EGAVGA_ARCH) mem_writeb(BIOS_DISK_MOTOR_TIMEOUT,val-1); + /* clear FDD motor bits when counter reaches zero */ + if (val == 1) mem_writeb(BIOS_DRIVE_RUNNING,mem_readb(BIOS_DRIVE_RUNNING) & 0xF0); + return CBRET_NONE; +} +#undef DOSBOX_CLOCKSYNC + +static Bitu INT1C_Handler(void) { + return CBRET_NONE; +} + +static Bitu INT12_Handler(void) { + reg_ax=mem_readw(BIOS_MEMORY_SIZE); + return CBRET_NONE; +} + +static Bitu INT17_Handler(void) { + if (reg_ah > 0x2 || reg_dx > 0x2) { // 0-2 printer port functions + // and no more than 3 parallel ports + LOG_MSG("BIOS INT17: Unhandled call AH=%2X DX=%4x",reg_ah,reg_dx); + return CBRET_NONE; + } + + switch(reg_ah) { + case 0x00: // PRINTER: Write Character + if(parallelPortObjects[reg_dx]) { + if(parallelPortObjects[reg_dx]->Putchar(reg_al)) + reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); + else reg_ah=1; + } + break; + case 0x01: // PRINTER: Initialize port + if(parallelPortObjects[reg_dx]) { + parallelPortObjects[reg_dx]->initialize(); + reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); + } + break; + case 0x02: // PRINTER: Get Status + if(parallelPortObjects[reg_dx]) + reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); + //LOG_MSG("printer status: %x",reg_ah); + break; + case 0x20: /* Some sort of printerdriver install check*/ + break; + case 0x50: // Printer BIOS for AX + if (!IS_JEGA_ARCH) break; + switch (reg_al) { + case 0x00:// Set JP/US mode in PRT BIOS + LOG(LOG_BIOS, LOG_NORMAL)("AX PRT BIOS 5000h is called. (not implemented)"); + reg_al = 0x01; // Return error (not implemented) + break; + case 0x01:// Get JP/US mode in PRT BIOS + reg_al = 0x01; // Return US mode (not implemented) + break; + default: + LOG(LOG_BIOS, LOG_ERROR)("Unhandled AX Function 50%2X", reg_al); + break; + } + break; + } + return CBRET_NONE; +} + +static bool INT14_Wait(uint16_t port, uint8_t mask, uint8_t timeout, uint8_t* retval) { + double starttime = PIC_FullIndex(); + double timeout_f = timeout * 1000.0; + while (((*retval = IO_ReadB(port)) & mask) != mask) { + if (starttime < (PIC_FullIndex() - timeout_f)) { + return false; + } + CALLBACK_Idle(); + } + return true; +} + +static Bitu INT4B_Handler(void) { + /* TODO: This is where the Virtual DMA specification is accessed on modern systems. + * When we implement that, move this to EMM386 emulation code. */ + + if (reg_ax >= 0x8102 && reg_ax <= 0x810D) { + LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted Virtual DMA specification call (INT 4Bh AX=%04x BX=%04x CX=%04x DX=%04x", + reg_ax,reg_bx,reg_cx,reg_dx); + } + else if (reg_ah == 0x80) { + LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted IBM SCSI interface call"); + } + else if (reg_ah <= 0x02) { + LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted TI Professional PC parallel port function AH=%02x",reg_ah); + } + else { + LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted unknown INT 4Bh call AX=%04x",reg_ax); + } + + /* Oh, I'm just a BIOS that doesn't know what the hell you're doing. CF=1 */ + CALLBACK_SCF(true); + return CBRET_NONE; +} + +static Bitu INT14_Handler(void) { + if (reg_ah > 0x3 || reg_dx > 0x3) { // 0-3 serial port functions + // and no more than 4 serial ports + LOG_MSG("BIOS INT14: Unhandled call AH=%2X DX=%4x",reg_ah,reg_dx); + return CBRET_NONE; + } + + uint16_t port = real_readw(0x40,reg_dx * 2u); // DX is always port number + uint8_t timeout = mem_readb((PhysPt)((unsigned int)BIOS_COM1_TIMEOUT + (unsigned int)reg_dx)); + if (port==0) { + LOG(LOG_BIOS,LOG_NORMAL)("BIOS INT14: port %d does not exist.",reg_dx); + return CBRET_NONE; + } + switch (reg_ah) { + case 0x00: { + // Initialize port + // Parameters: Return: + // AL: port parameters AL: modem status + // AH: line status + + // set baud rate + Bitu baudrate = 9600u; + uint16_t baudresult; + Bitu rawbaud=(Bitu)reg_al>>5u; + + if (rawbaud==0){ baudrate=110u;} + else if (rawbaud==1){ baudrate=150u;} + else if (rawbaud==2){ baudrate=300u;} + else if (rawbaud==3){ baudrate=600u;} + else if (rawbaud==4){ baudrate=1200u;} + else if (rawbaud==5){ baudrate=2400u;} + else if (rawbaud==6){ baudrate=4800u;} + else if (rawbaud==7){ baudrate=9600u;} + + baudresult = (uint16_t)(115200u / baudrate); + + IO_WriteB(port+3u, 0x80u); // enable divider access + IO_WriteB(port, (uint8_t)baudresult&0xffu); + IO_WriteB(port+1u, (uint8_t)(baudresult>>8u)); + + // set line parameters, disable divider access + IO_WriteB(port+3u, reg_al&0x1Fu); // LCR + + // disable interrupts + IO_WriteB(port+1u, 0u); // IER + + // get result + reg_ah=IO_ReadB(port+5u)&0xffu; + reg_al=IO_ReadB(port+6u)&0xffu; + CALLBACK_SCF(false); + break; + } + case 0x01: // Transmit character + // Parameters: Return: + // AL: character AL: unchanged + // AH: 0x01 AH: line status from just before the char was sent + // (0x80 | unpredicted) in case of timeout + // [undoc] (0x80 | line status) in case of tx timeout + // [undoc] (0x80 | modem status) in case of dsr/cts timeout + + // set DTR & RTS on + IO_WriteB(port+4u,0x3u); + // wait for DSR & CTS + if (INT14_Wait(port+6u, 0x30u, timeout, ®_ah)) { + // wait for TX buffer empty + if (INT14_Wait(port+5u, 0x20u, timeout, ®_ah)) { + // finally send the character + IO_WriteB(port,reg_al); + } else + reg_ah |= 0x80u; + } else // timed out + reg_ah |= 0x80u; + + CALLBACK_SCF(false); + break; + case 0x02: // Read character + // Parameters: Return: + // AH: 0x02 AL: received character + // [undoc] will be trashed in case of timeout + // AH: (line status & 0x1E) in case of success + // (0x80 | unpredicted) in case of timeout + // [undoc] (0x80 | line status) in case of rx timeout + // [undoc] (0x80 | modem status) in case of dsr timeout + + // set DTR on + IO_WriteB(port+4u,0x1u); + + // wait for DSR + if (INT14_Wait(port+6, 0x20, timeout, ®_ah)) { + // wait for character to arrive + if (INT14_Wait(port+5, 0x01, timeout, ®_ah)) { + reg_ah &= 0x1E; + reg_al = IO_ReadB(port); + } else + reg_ah |= 0x80; + } else + reg_ah |= 0x80; + + CALLBACK_SCF(false); + break; + case 0x03: // get status + reg_ah=IO_ReadB(port+5u)&0xffu; + reg_al=IO_ReadB(port+6u)&0xffu; + CALLBACK_SCF(false); + break; + + } + return CBRET_NONE; +} + +Bits HLT_Decode(void); +void KEYBOARD_AUX_Write(Bitu val); +unsigned char KEYBOARD_AUX_GetType(); +unsigned char KEYBOARD_AUX_DevStatus(); +unsigned char KEYBOARD_AUX_Resolution(); +unsigned char KEYBOARD_AUX_SampleRate(); +void KEYBOARD_ClrBuffer(void); +void KEYBOARD_AUX_LowerIRQ(); + +static Bitu INT15_Handler(void) { + if( ( machine==MCH_AMSTRAD ) && ( reg_ah<0x07 ) ) { + switch(reg_ah) { + case 0x00: + // Read/Reset Mouse X/Y Counts. + // CX = Signed X Count. + // DX = Signed Y Count. + // CC. + case 0x01: + // Write NVR Location. + // AL = NVR Address to be written (0-63). + // BL = NVR Data to be written. + + // AH = Return Code. + // 00 = NVR Written Successfully. + // 01 = NVR Address out of range. + // 02 = NVR Data write error. + // CC. + case 0x02: + // Read NVR Location. + // AL = NVR Address to be read (0-63). + + // AH = Return Code. + // 00 = NVR read successfully. + // 01 = NVR Address out of range. + // 02 = NVR checksum error. + // AL = Byte read from NVR. + // CC. + case 0x03: + // Write VDU Colour Plane Write Register. + vga.amstrad.write_plane = reg_al & 0x0F; + CALLBACK_SCF(false); + break; + case 0x04: + // Write VDU Colour Plane Read Register. + vga.amstrad.read_plane = reg_al & 0x03; + CALLBACK_SCF(false); + break; + case 0x05: + // Write VDU Graphics Border Register. + vga.amstrad.border_color = reg_al & 0x0F; + CALLBACK_SCF(false); + break; + case 0x06: + // Return ROS Version Number. + reg_bx = 0x0001; + CALLBACK_SCF(false); + break; + default: + LOG(LOG_BIOS, LOG_NORMAL)("INT15 Unsupported PC1512 Call %02X", reg_ah); + return CBRET_NONE; + } + } + switch (reg_ah) { + case 0x06: + LOG(LOG_BIOS,LOG_NORMAL)("INT15 Unknown Function 6 (Amstrad?)"); + break; + case 0x24: //A20 stuff + switch (reg_al) { + case 0: //Disable a20 + MEM_A20_Enable(false); + reg_ah = 0; //call successful + CALLBACK_SCF(false); //clear on success + break; + case 1: //Enable a20 + MEM_A20_Enable( true ); + reg_ah = 0; //call successful + CALLBACK_SCF(false); //clear on success + break; + case 2: //Query a20 + reg_al = MEM_A20_Enabled() ? 0x1 : 0x0; + reg_ah = 0; //call successful + CALLBACK_SCF(false); + break; + case 3: //Get a20 support + reg_bx = 0x3; //Bitmask, keyboard and 0x92 + reg_ah = 0; //call successful + CALLBACK_SCF(false); + break; + default: + goto unhandled; + } + break; + case 0xC0: /* Get Configuration*/ + CPU_SetSegGeneral(es,biosConfigSeg); + reg_bx = 0; + reg_ah = 0; + CALLBACK_SCF(false); + break; + case 0x4f: /* BIOS - Keyboard intercept */ + /* Carry should be set but let's just set it just in case */ + CALLBACK_SCF(true); + break; + case 0x83: /* BIOS - SET EVENT WAIT INTERVAL */ + { + if(reg_al == 0x01) { /* Cancel it */ + mem_writeb(BIOS_WAIT_FLAG_ACTIVE,0); + IO_Write(0x70,0xb); + IO_Write(0x71,IO_Read(0x71)&~0x40); + CALLBACK_SCF(false); + break; + } + if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { + reg_ah=0x80; + CALLBACK_SCF(true); + break; + } + uint32_t count=((uint32_t)reg_cx<<16u)|reg_dx; + mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(SegValue(es),reg_bx)); + mem_writed(BIOS_WAIT_FLAG_COUNT,count); + mem_writeb(BIOS_WAIT_FLAG_ACTIVE,1); + /* Reprogram RTC to start */ + IO_Write(0x70,0xb); + IO_Write(0x71,IO_Read(0x71)|0x40); + CALLBACK_SCF(false); + } + break; + case 0x84: /* BIOS - JOYSTICK SUPPORT (XT after 11/8/82,AT,XT286,PS) */ + if (reg_dx == 0x0000) { + // Get Joystick button status + if (JOYSTICK_IsEnabled(0) || JOYSTICK_IsEnabled(1)) { + reg_al = IO_ReadB(0x201)&0xf0; + CALLBACK_SCF(false); + } else { + // dos values + reg_ax = 0x00f0; reg_dx = 0x0201; + CALLBACK_SCF(true); + } + } else if (reg_dx == 0x0001) { + if (JOYSTICK_IsEnabled(0)) { + reg_ax = (uint16_t)(JOYSTICK_GetMove_X(0)*127+128); + reg_bx = (uint16_t)(JOYSTICK_GetMove_Y(0)*127+128); + if(JOYSTICK_IsEnabled(1)) { + reg_cx = (uint16_t)(JOYSTICK_GetMove_X(1)*127+128); + reg_dx = (uint16_t)(JOYSTICK_GetMove_Y(1)*127+128); + } + else { + reg_cx = reg_dx = 0; + } + CALLBACK_SCF(false); + } else if (JOYSTICK_IsEnabled(1)) { + reg_ax = reg_bx = 0; + reg_cx = (uint16_t)(JOYSTICK_GetMove_X(1)*127+128); + reg_dx = (uint16_t)(JOYSTICK_GetMove_Y(1)*127+128); + CALLBACK_SCF(false); + } else { + reg_ax = reg_bx = reg_cx = reg_dx = 0; + CALLBACK_SCF(true); + } + } else { + LOG(LOG_BIOS,LOG_ERROR)("INT15:84:Unknown Bios Joystick functionality."); + } + break; + case 0x86: /* BIOS - WAIT (AT,PS) */ + { + if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { + reg_ah=0x83; + CALLBACK_SCF(true); + break; + } + uint8_t t; + uint32_t count=((uint32_t)reg_cx<<16u)|reg_dx; + mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(0,BIOS_WAIT_FLAG_TEMP)); + mem_writed(BIOS_WAIT_FLAG_COUNT,count); + mem_writeb(BIOS_WAIT_FLAG_ACTIVE,1); + + /* if the user has not set the option, warn if IRQs are masked */ + if (!int15_wait_force_unmask_irq) { + /* make sure our wait function works by unmasking IRQ 2, and IRQ 8. + * (bugfix for 1993 demo Yodel "Mayday" demo. this demo keeps masking IRQ 2 for some stupid reason.) */ + if ((t=IO_Read(0x21)) & (1 << 2)) { + LOG(LOG_BIOS,LOG_ERROR)("INT15:86:Wait: IRQ 2 masked during wait. " + "Consider adding 'int15 wait force unmask irq=true' to your dosbox-x.conf"); + } + if ((t=IO_Read(0xA1)) & (1 << 0)) { + LOG(LOG_BIOS,LOG_ERROR)("INT15:86:Wait: IRQ 8 masked during wait. " + "Consider adding 'int15 wait force unmask irq=true' to your dosbox-x.conf"); + } + } + + /* Reprogram RTC to start */ + IO_Write(0x70,0xb); + IO_Write(0x71,IO_Read(0x71)|0x40); + while (mem_readd(BIOS_WAIT_FLAG_COUNT)) { + if (int15_wait_force_unmask_irq) { + /* make sure our wait function works by unmasking IRQ 2, and IRQ 8. + * (bugfix for 1993 demo Yodel "Mayday" demo. this demo keeps masking IRQ 2 for some stupid reason.) */ + if ((t=IO_Read(0x21)) & (1 << 2)) { + LOG(LOG_BIOS,LOG_WARN)("INT15:86:Wait: IRQ 2 masked during wait. " + "This condition might result in an infinite wait on " + "some BIOSes. Unmasking IRQ to keep things moving along."); + IO_Write(0x21,t & ~(1 << 2)); + } + if ((t=IO_Read(0xA1)) & (1 << 0)) { + LOG(LOG_BIOS,LOG_WARN)("INT15:86:Wait: IRQ 8 masked during wait. " + "This condition might result in an infinite wait on some " + "BIOSes. Unmasking IRQ to keep things moving along."); + IO_Write(0xA1,t & ~(1 << 0)); + } + } + + CALLBACK_Idle(); + } + CALLBACK_SCF(false); + break; + } + case 0x87: /* Copy extended memory */ + { + bool enabled = MEM_A20_Enabled(); + MEM_A20_Enable(true); + Bitu bytes = reg_cx * 2u; + PhysPt data = SegPhys(es)+reg_si; + PhysPt source = (mem_readd(data+0x12u) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data+0x17u)<<24u); + PhysPt dest = (mem_readd(data+0x1Au) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data+0x1Fu)<<24u); + MEM_BlockCopy(dest,source,bytes); + reg_ax = 0x00; + MEM_A20_Enable(enabled); + Segs.limit[cs] = 0xFFFF; + Segs.limit[ds] = 0xFFFF; + Segs.limit[es] = 0xFFFF; + Segs.limit[ss] = 0xFFFF; + CALLBACK_SCF(false); + break; + } + case 0x88: /* SYSTEM - GET EXTENDED MEMORY SIZE (286+) */ + /* This uses the 16-bit value read back from CMOS which is capped at 64MB */ + reg_ax=other_memsystems?0:size_extended; + LOG(LOG_BIOS,LOG_NORMAL)("INT15:Function 0x88 Remaining %04X kb",reg_ax); + CALLBACK_SCF(false); + break; + case 0x89: /* SYSTEM - SWITCH TO PROTECTED MODE */ + { + IO_Write(0x20,0x10);IO_Write(0x21,reg_bh);IO_Write(0x21,0);IO_Write(0x21,0xFF); + IO_Write(0xA0,0x10);IO_Write(0xA1,reg_bl);IO_Write(0xA1,0);IO_Write(0xA1,0xFF); + MEM_A20_Enable(true); + PhysPt table=SegPhys(es)+reg_si; + CPU_LGDT(mem_readw(table+0x8),mem_readd(table+0x8+0x2) & 0xFFFFFF); + CPU_LIDT(mem_readw(table+0x10),mem_readd(table+0x10+0x2) & 0xFFFFFF); + CPU_SET_CRX(0,CPU_GET_CRX(0)|1); + CPU_SetSegGeneral(ds,0x18); + CPU_SetSegGeneral(es,0x20); + CPU_SetSegGeneral(ss,0x28); + Bitu ret = mem_readw(SegPhys(ss)+reg_sp); + reg_sp+=6; //Clear stack of interrupt frame + CPU_SetFlags(0,FMASK_ALL); + reg_ax=0; + CPU_JMP(false,0x30,ret,0); + } + break; + case 0x8A: /* EXTENDED MEMORY SIZE */ + { + Bitu sz = MEM_TotalPages()*4; + if (sz >= 1024) sz -= 1024; + else sz = 0; + reg_ax = sz & 0xFFFF; + reg_dx = sz >> 16; + CALLBACK_SCF(false); + } + break; + case 0x90: /* OS HOOK - DEVICE BUSY */ + case 0x91: /* OS HOOK - DEVICE POST */ + CALLBACK_SCF(false); + reg_ah=0; + break; + case 0xc2: /* BIOS PS2 Pointing Device Support */ + /* TODO: Our reliance on AUX emulation means that at some point, AUX emulation + * must always be enabled if BIOS PS/2 emulation is enabled. Future planned change: + * + * If biosps2=true and aux=true, carry on what we're already doing now: emulate INT 15h by + * directly writing to the AUX port of the keyboard controller. + * + * If biosps2=false, the aux= setting enables/disables AUX emulation as it already does now. + * biosps2=false implies that we're emulating a keyboard controller with AUX but no BIOS + * support for it (however rare that might be). This gives the user of DOSBox-X the means + * to test that scenario especially in case he/she is developing a homebrew OS and needs + * to ensure their code can handle cases like that gracefully. + * + * If biosps2=true and aux=false, AUX emulation is enabled anyway, but the keyboard emulation + * must act as if the AUX port is not there so the guest OS cannot control it. Again, not + * likely on real hardware, but a useful test case for homebrew OS developers. + * + * If you the user set aux=false, then you obviously want to test a system configuration + * where the keyboard controller has no AUX port. If you set biosps2=true, then you want to + * test an OS that uses BIOS functions to setup the "pointing device" but you do not want the + * guest OS to talk directly to the AUX port on the keyboard controller. + * + * Logically that's not likely to happen on real hardware, but we like giving the end-user + * options to play with, so instead, if aux=false and biosps2=true, DOSBox-X should print + * a warning stating that INT 15h mouse emulation with a PS/2 port is nonstandard and may + * cause problems with OSes that need to talk directly to hardware. + * + * It is noteworthy that PS/2 mouse support in MS-DOS mouse drivers as well as Windows 3.x, + * Windows 95, and Windows 98, is carried out NOT by talking directly to the AUX port but + * instead by relying on the BIOS INT 15h functions here to do the dirty work. For those + * scenarios, biosps2=true and aux=false is perfectly safe and does not cause issues. + * + * OSes that communicate directly with the AUX port however (Linux, Windows NT) will not work + * unless aux=true. */ + if (en_bios_ps2mouse) { +// LOG_MSG("INT 15h AX=%04x BX=%04x\n",reg_ax,reg_bx); + switch (reg_al) { + case 0x00: // enable/disable + if (reg_bh==0) { // disable + KEYBOARD_AUX_Write(0xF5); + Mouse_SetPS2State(false); + reg_ah=0; + CALLBACK_SCF(false); + KEYBOARD_ClrBuffer(); + } else if (reg_bh==0x01) { //enable + if (!Mouse_SetPS2State(true)) { + reg_ah=5; + CALLBACK_SCF(true); + break; + } + KEYBOARD_AUX_Write(0xF4); + KEYBOARD_ClrBuffer(); + reg_ah=0; + CALLBACK_SCF(false); + } else { + CALLBACK_SCF(true); + reg_ah=1; + } + break; + case 0x01: // reset + KEYBOARD_AUX_Write(0xFF); + Mouse_SetPS2State(false); + KEYBOARD_ClrBuffer(); + reg_bx=0x00aa; // mouse (BH=device ID BL=value returned by attached device after reset) [http://www.ctyme.com/intr/rb-1597.htm] + LOG_MSG("INT 15h mouse reset\n"); + KEYBOARD_AUX_Write(0xF6); /* set defaults */ + Mouse_SetPS2State(false); + KEYBOARD_ClrBuffer(); + KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ + CALLBACK_SCF(false); + reg_ah=0; // must return success. Fall through was well intended but, no, causes an error code that confuses mouse drivers + break; + case 0x05: // initialize + if (reg_bh >= 3 && reg_bh <= 4) { + /* TODO: BIOSes remember this value as the number of bytes to store before + * calling the device callback. Setting this value to "1" is perfectly + * valid if you want a byte-stream like mode (at the cost of one + * interrupt per byte!). Most OSes will call this with BH=3 for standard + * PS/2 mouse protocol. You can also call this with BH=4 for Intellimouse + * protocol support, though testing (so far with VirtualBox) shows the + * device callback still only gets the first three bytes on the stack. + * Contrary to what you might think, the BIOS does not interpret the + * bytes at all. + * + * The source code of CuteMouse 1.9 seems to suggest some BIOSes take + * pains to repack the 4th byte in the upper 8 bits of one of the WORDs + * on the stack in Intellimouse mode at the cost of shifting the W and X + * fields around. I can't seem to find any source on who does that or + * if it's even true, so I disregard the example at this time. + * + * Anyway, you need to store off this value somewhere and make use of + * it in src/ints/mouse.cpp device callback emulation to reframe the + * PS/2 mouse bytes coming from AUX (if aux=true) or emulate the + * re-framing if aux=false to emulate this protocol fully. */ + LOG_MSG("INT 15h mouse initialized to %u-byte protocol\n",reg_bh); + Mouse_PS2SetPacketSize(reg_bh); + KEYBOARD_AUX_Write(0xF6); /* set defaults */ + Mouse_SetPS2State(false); + KEYBOARD_ClrBuffer(); + CALLBACK_SCF(false); + reg_ah=0; + } + else { + CALLBACK_SCF(false); + reg_ah=0x02; /* invalid input */ + } + break; + case 0x02: { // set sampling rate + Mouse_PS2SetSamplingRate(reg_bh); + static const unsigned char tbl[7] = {10,20,40,60,80,100,200}; + KEYBOARD_AUX_Write(0xF3); + if (reg_bh > 6) reg_bh = 6; + KEYBOARD_AUX_Write(tbl[reg_bh]); + KEYBOARD_ClrBuffer(); + CALLBACK_SCF(false); + reg_ah=0; + } break; + case 0x03: // set resolution + KEYBOARD_AUX_Write(0xE8); + KEYBOARD_AUX_Write(reg_bh&3); + KEYBOARD_ClrBuffer(); + CALLBACK_SCF(false); + reg_ah=0; + break; + case 0x04: // get type + reg_bh=KEYBOARD_AUX_GetType(); // ID + KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ + LOG_MSG("INT 15h reporting mouse device ID 0x%02x\n",reg_bh); + KEYBOARD_ClrBuffer(); + CALLBACK_SCF(false); + reg_ah=0; + break; + case 0x06: // extended commands + if (reg_bh == 0x00) { + /* Read device status and info. + * Windows 9x does not appear to use this, but Windows NT 3.1 does (prior to entering + * full 32-bit protected mode) */ + CALLBACK_SCF(false); + reg_bx=KEYBOARD_AUX_DevStatus(); + reg_cx=KEYBOARD_AUX_Resolution(); + reg_dx=KEYBOARD_AUX_SampleRate(); + KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ + KEYBOARD_ClrBuffer(); + reg_ah=0; + } + else if ((reg_bh==0x01) || (reg_bh==0x02)) { /* set scaling */ + KEYBOARD_AUX_Write(0xE6u+reg_bh-1u); /* 0xE6 1:1 or 0xE7 2:1 */ + KEYBOARD_ClrBuffer(); + CALLBACK_SCF(false); + reg_ah=0; + } else { + CALLBACK_SCF(true); + reg_ah=1; + } + break; + case 0x07: // set callback + Mouse_ChangePS2Callback(SegValue(es),reg_bx); + CALLBACK_SCF(false); + reg_ah=0; + break; + default: + LOG_MSG("INT 15h unknown mouse call AX=%04x\n",reg_ax); + CALLBACK_SCF(true); + reg_ah=1; + break; + } + } + else { + reg_ah=0x86; + CALLBACK_SCF(true); + if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA)) { + /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ + CALLBACK_SZF(false); + } + } + break; + case 0xc3: /* set carry flag so BorlandRTM doesn't assume a VECTRA/PS2 */ + reg_ah=0x86; + CALLBACK_SCF(true); + break; + case 0xc4: /* BIOS POS Program option Select */ + LOG(LOG_BIOS,LOG_NORMAL)("INT15:Function %X called, bios mouse not supported",reg_ah); + CALLBACK_SCF(true); + break; + case 0x53: // APM BIOS + if (APMBIOS) { + /* Windows 98 calls AH=05h CPU IDLE way too much per second, it makes it difficult to see anything important scroll by. + * Rate limit this particular call in the log file. */ + if (reg_al == 0x05) { + APM_log_cpu_idle++; + if (PIC_FullIndex() >= APM_log_cpu_idle_next_report) { + LOG(LOG_BIOS,LOG_DEBUG)("APM BIOS, %lu calls to AX=%04x BX=0x%04x CX=0x%04x\n",(unsigned long)APM_log_cpu_idle,reg_ax,reg_bx,reg_cx); + APM_log_cpu_idle_next_report = PIC_FullIndex() + 1000; + APM_log_cpu_idle = 0; + } + } + else { + LOG(LOG_BIOS,LOG_DEBUG)("APM BIOS call AX=%04x BX=0x%04x CX=0x%04x\n",reg_ax,reg_bx,reg_cx); + } + + switch(reg_al) { + case 0x00: // installation check + reg_ah = 1; // major + reg_al = APM_BIOS_minor_version; // minor + reg_bx = 0x504d; // 'PM' + reg_cx = (APMBIOS_allow_prot16?0x01:0x00) + (APMBIOS_allow_prot32?0x02:0x00); + // 32-bit interface seems to be needed for standby in win95 + CALLBACK_SCF(false); + break; + case 0x01: // connect real mode interface + if(!APMBIOS_allow_realmode) { + LOG_MSG("APM BIOS: OS attempted real-mode connection, which is disabled in your dosbox-x.conf\n"); + reg_ah = 0x86; // APM not present + CALLBACK_SCF(true); + break; + } + if(reg_bx != 0x0) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } + if(!apm_realmode_connected) { // not yet connected + LOG_MSG("APM BIOS: Connected to real-mode interface\n"); + CALLBACK_SCF(false); + APMBIOS_connect_mode = APMBIOS_CONNECT_REAL; + PowerButtonClicks=0; /* BIOSes probably clear whatever hardware register this involves... we'll see */ + APM_ResumeNotificationFromStandby = false; + APM_ResumeNotificationFromSuspend = false; + apm_realmode_connected=true; + } else { + LOG_MSG("APM BIOS: OS attempted to connect to real-mode interface when already connected\n"); + reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect + CALLBACK_SCF(true); + } + APM_BIOS_connected_minor_version = 0; + break; + case 0x02: // connect 16-bit protected mode interface + if(!APMBIOS_allow_prot16) { + LOG_MSG("APM BIOS: OS attempted 16-bit protected mode connection, which is disabled in your dosbox-x.conf\n"); + reg_ah = 0x06; // not supported + CALLBACK_SCF(true); + break; + } + if(reg_bx != 0x0) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } + if(!apm_realmode_connected) { // not yet connected + /* NTS: We use the same callback address for both 16-bit and 32-bit + * because only the DOS callback and RETF instructions are involved, + * which can be executed as either 16-bit or 32-bit code without problems. */ + LOG_MSG("APM BIOS: Connected to 16-bit protected mode interface\n"); + CALLBACK_SCF(false); + reg_ax = INT15_apm_pmentry >> 16; // AX = 16-bit code segment (real mode base) + reg_bx = INT15_apm_pmentry & 0xFFFF; // BX = offset of entry point + reg_cx = INT15_apm_pmentry >> 16; // CX = 16-bit data segment (NTS: doesn't really matter) + reg_si = 0xFFFF; // SI = code segment length + reg_di = 0xFFFF; // DI = data segment length + APMBIOS_connect_mode = APMBIOS_CONNECT_PROT16; + PowerButtonClicks=0; /* BIOSes probably clear whatever hardware register this involves... we'll see */ + APM_ResumeNotificationFromStandby = false; + APM_ResumeNotificationFromSuspend = false; + apm_realmode_connected=true; + } else { + LOG_MSG("APM BIOS: OS attempted to connect to 16-bit protected mode interface when already connected\n"); + reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect + CALLBACK_SCF(true); + } + APM_BIOS_connected_minor_version = 0; + break; + case 0x03: // connect 32-bit protected mode interface + // Note that Windows 98 will NOT talk to the APM BIOS unless the 32-bit protected mode connection is available. + // And if you lie about it in function 0x00 and then fail, Windows 98 will fail with a "Windows protection error". + if(!APMBIOS_allow_prot32) { + LOG_MSG("APM BIOS: OS attempted 32-bit protected mode connection, which is disabled in your dosbox-x.conf\n"); + reg_ah = 0x08; // not supported + CALLBACK_SCF(true); + break; + } + if(reg_bx != 0x0) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } + if(!apm_realmode_connected) { // not yet connected + LOG_MSG("APM BIOS: Connected to 32-bit protected mode interface\n"); + CALLBACK_SCF(false); + /* NTS: We use the same callback address for both 16-bit and 32-bit + * because only the DOS callback and RETF instructions are involved, + * which can be executed as either 16-bit or 32-bit code without problems. */ + reg_ax = INT15_apm_pmentry >> 16; // AX = 32-bit code segment (real mode base) + reg_ebx = INT15_apm_pmentry & 0xFFFF; // EBX = offset of entry point + reg_cx = INT15_apm_pmentry >> 16; // CX = 16-bit code segment (real mode base) + reg_dx = INT15_apm_pmentry >> 16; // DX = data segment (real mode base) (?? what size?) + reg_esi = 0xFFFFFFFF; // ESI = upper word: 16-bit code segment len lower word: 32-bit code segment length + reg_di = 0xFFFF; // DI = data segment length + APMBIOS_connect_mode = APMBIOS_CONNECT_PROT32; + PowerButtonClicks=0; /* BIOSes probably clear whatever hardware register this involves... we'll see */ + APM_ResumeNotificationFromStandby = false; + APM_ResumeNotificationFromSuspend = false; + apm_realmode_connected=true; + } else { + LOG_MSG("APM BIOS: OS attempted to connect to 32-bit protected mode interface when already connected\n"); + reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect + CALLBACK_SCF(true); + } + APM_BIOS_connected_minor_version = 0; + break; + case 0x04: // DISCONNECT INTERFACE + if(reg_bx != 0x0) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } + if(apm_realmode_connected) { + LOG_MSG("APM BIOS: OS disconnected\n"); + CALLBACK_SCF(false); + apm_realmode_connected=false; + } else { + reg_ah = 0x03; // interface not connected + CALLBACK_SCF(true); + } + APM_BIOS_connected_minor_version = 0; + break; + case 0x05: // CPU IDLE + if(!apm_realmode_connected) { + reg_ah = 0x03; + CALLBACK_SCF(true); + break; + } + + // Trigger CPU HLT instruction. + // NTS: For whatever weird reason, NOT emulating HLT makes Windows 95 + // crashy when the APM driver is active! There's something within + // the Win95 kernel that apparently screws up really badly if + // the APM IDLE call returns immediately. The best case scenario + // seems to be that Win95's APM driver has some sort of timing + // logic to it that if it detects an immediate return, immediately + // shuts down and powers off the machine. Windows 98 also seems + // to require a HLT, and will act erratically without it. + // + // Also need to note that the choice of "HLT" is not arbitrary + // at all. The APM BIOS standard mentions CPU IDLE either stopping + // the CPU clock temporarily or issuing HLT as a valid method. + // + // TODO: Make this a dosbox-x.conf configuration option: what do we do + // on APM idle calls? Allow selection between "nothing" "hlt" + // and "software delay". + if (!(reg_flags&0x200)) { + LOG(LOG_BIOS,LOG_WARN)("APM BIOS warning: CPU IDLE called with IF=0, not HLTing\n"); + } + else if (cpudecoder == &HLT_Decode) { /* do not re-execute HLT, it makes DOSBox-X hang */ + LOG_MSG("APM BIOS warning: CPU IDLE HLT within HLT (DOSBox-X core failure)\n"); + } + else { + CPU_HLT(reg_eip); + } + break; + case 0x06: // CPU BUSY + if(!apm_realmode_connected) { + reg_ah = 0x03; + CALLBACK_SCF(true); + break; + } + + /* OK. whatever. system no longer idle */ + CALLBACK_SCF(false); + break; + case 0x07: + if(reg_bx != 0x1) { + reg_ah = 0x09; // wrong device ID + CALLBACK_SCF(true); + break; + } + if(!apm_realmode_connected) { + reg_ah = 0x03; + CALLBACK_SCF(true); + break; + } + switch(reg_cx) { + case 0x1: // standby + LOG(LOG_MISC,LOG_DEBUG)("Guest attempted to set power state to standby"); + APM_BeginSuspendedMode(); + reg_ah = 0x00;//TODO + CALLBACK_SCF(false); + APM_ResumeNotificationFromStandby = true; + break; + case 0x2: // suspend + LOG(LOG_MISC,LOG_DEBUG)("Guest attempted to set power state to suspend"); + APM_BeginSuspendedMode(); + reg_ah = 0x00;//TODO + CALLBACK_SCF(false); + APM_ResumeNotificationFromSuspend = true; + break; + case 0x3: // power off + throw 0; + case 0x4: // last request processing notification (used by Windows ME) + LOG(LOG_MISC,LOG_DEBUG)("Guest is considering whether to accept the last returned APM event"); + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x5: // reject last request (used by Windows ME) + LOG(LOG_MISC,LOG_DEBUG)("Guest has rejected the last APM event"); + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + default: + reg_ah = 0x0A; // invalid parameter value in CX + CALLBACK_SCF(true); + break; + } + break; + case 0x08: // ENABLE/DISABLE POWER MANAGEMENT + if(reg_bx != 0x0 && reg_bx != 0x1) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } else if(!apm_realmode_connected) { + reg_ah = 0x03; + CALLBACK_SCF(true); + break; + } + if(reg_cx==0x0) LOG_MSG("disable APM for device %4x",reg_bx); + else if(reg_cx==0x1) LOG_MSG("enable APM for device %4x",reg_bx); + else { + reg_ah = 0x0A; // invalid parameter value in CX + CALLBACK_SCF(true); + } + break; + case 0x0a: // GET POWER STATUS + if (!apm_realmode_connected) { + reg_ah = 0x03; // interface not connected + CALLBACK_SCF(true); + break; + } + if (reg_bx != 0x0001 && reg_bx != 0x8001) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } + /* FIXME: Allow configuration and shell commands to dictate whether or + * not we emulate a laptop with a battery */ + reg_bh = 0x01; // AC line status (1=on-line) + reg_bl = 0xFF; // Battery status (unknown) + reg_ch = 0x80; // Battery flag (no system battery) + reg_cl = 0xFF; // Remaining battery charge (unknown) + reg_dx = 0xFFFF; // Remaining battery life (unknown) + reg_si = 0; // Number of battery units (if called with reg_bx == 0x8001) + CALLBACK_SCF(false); + break; + case 0x0b: // GET PM EVENT + if (!apm_realmode_connected) { + reg_ah = 0x03; // interface not connected + CALLBACK_SCF(true); + break; + } + // power button? + if (PowerButtonClicks != 0) { // Hardware and BIOSes probably just set a bit somewhere, so act like it + LOG(LOG_MISC,LOG_DEBUG)("Returning APM power button event to guest OS"); + reg_ah = 0x00; // FIXME: The standard doesn't say anything about AH on success + + if (APM_PowerButtonSendsSuspend) + reg_bx = 0x000A;// user pushed a button, wants to suspend the system + else + reg_bx = 0x0009;// user pushed a button, wants to put the system into standby + + reg_cx = 0x0000; + CALLBACK_SCF(false); + PowerButtonClicks = 0; + break; + } + // resume from standby? Windows 98 will spin in a loop for 5+ seconds until it gets this APM message after suspend + if (APM_ResumeNotificationFromStandby) { + LOG(LOG_MISC,LOG_DEBUG)("Returning APM resume from standby notification event to guest OS"); + reg_ah = 0x00; // FIXME: The standard doesn't say anything about AH on success + reg_bx = 0x000B;// System Standby Resume Notification + reg_cx = 0x0000; + CALLBACK_SCF(false); + APM_ResumeNotificationFromStandby = false; + break; + } + // resume from suspend? Windows 98 will spin in a loop for 5+ seconds until it gets this APM message after suspend + if (APM_ResumeNotificationFromSuspend) { + LOG(LOG_MISC,LOG_DEBUG)("Returning APM resume from suspend notification event to guest OS"); + reg_ah = 0x00; // FIXME: The standard doesn't say anything about AH on success + reg_bx = 0x0003;// Normal Resume System Notification + reg_cx = 0x0000; + CALLBACK_SCF(false); + APM_ResumeNotificationFromSuspend = false; + break; + } + // nothing + reg_ah = 0x80; // no power management events pending + CALLBACK_SCF(true); + break; + case 0x0d: + // NTS: NOT implementing this call can cause Windows 98's APM driver to crash on startup + if(reg_bx != 0x0 && reg_bx != 0x1) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } else if(!apm_realmode_connected) { + reg_ah = 0x03; + CALLBACK_SCF(true); + break; + } + if(reg_cx==0x0) { + LOG_MSG("disable APM for device %4x",reg_bx); + CALLBACK_SCF(false); + } + else if(reg_cx==0x1) { + LOG_MSG("enable APM for device %4x",reg_bx); + CALLBACK_SCF(false); + } + else { + reg_ah = 0x0A; // invalid parameter value in CX + CALLBACK_SCF(true); + } + break; + case 0x0e: + if (APM_BIOS_minor_version != 0) { // APM 1.1 or higher only + if(reg_bx != 0x0) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } else if(!apm_realmode_connected) { + reg_ah = 0x03; // interface not connected + CALLBACK_SCF(true); + break; + } + reg_ah = reg_ch; /* we are called with desired version in CH,CL, return actual version in AH,AL */ + reg_al = reg_cl; + if(reg_ah != 1) reg_ah = 1; // major + if(reg_al > APM_BIOS_minor_version) reg_al = APM_BIOS_minor_version; // minor + APM_BIOS_connected_minor_version = reg_al; // what we decided becomes the interface we emulate + LOG_MSG("APM BIOS negotiated to v1.%u",APM_BIOS_connected_minor_version); + CALLBACK_SCF(false); + } + else { // APM 1.0 does not recognize this call + reg_ah = 0x0C; // function not supported + CALLBACK_SCF(true); + } + break; + case 0x0f: + if(reg_bx != 0x0 && reg_bx != 0x1) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } else if(!apm_realmode_connected) { + reg_ah = 0x03; + CALLBACK_SCF(true); + break; + } + if(reg_cx==0x0) { + LOG_MSG("disengage APM for device %4x",reg_bx); + CALLBACK_SCF(false); + } + else if(reg_cx==0x1) { + LOG_MSG("engage APM for device %4x",reg_bx); + CALLBACK_SCF(false); + } + else { + reg_ah = 0x0A; // invalid parameter value in CX + CALLBACK_SCF(true); + } + break; + case 0x10: + if (!apm_realmode_connected) { + reg_ah = 0x03; // interface not connected + CALLBACK_SCF(true); + break; + } + if (reg_bx != 0) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } + reg_ah = 0; + reg_bl = 0; // number of battery units + reg_cx = 0x03; // can enter suspend/standby and will post standby/resume events + CALLBACK_SCF(false); + break; + case 0x13://enable/disable/query timer based requests + // NTS: NOT implementing this call can cause Windows 98's APM driver to crash on startup + if (!apm_realmode_connected) { + reg_ah = 0x03; // interface not connected + CALLBACK_SCF(true); + break; + } + if (reg_bx != 0) { + reg_ah = 0x09; // unrecognized device ID + CALLBACK_SCF(true); + break; + } + + if (reg_cx == 0) { // disable + APM_inactivity_timer = false; + reg_cx = 0; + CALLBACK_SCF(false); + } + else if (reg_cx == 1) { // enable + APM_inactivity_timer = true; + reg_cx = 1; + CALLBACK_SCF(false); + } + else if (reg_cx == 2) { // get enabled status + reg_cx = APM_inactivity_timer ? 1 : 0; + CALLBACK_SCF(false); + } + else { + reg_ah = 0x0A; // invalid parameter value in CX + CALLBACK_SCF(true); + } + break; + default: + LOG_MSG("Unknown APM BIOS call AX=%04x\n",reg_ax); + if (!apm_realmode_connected) { + reg_ah = 0x03; // interface not connected + CALLBACK_SCF(true); + break; + } + reg_ah = 0x0C; // function not supported + CALLBACK_SCF(true); + break; + } + } + else { + reg_ah=0x86; + CALLBACK_SCF(true); + LOG_MSG("APM BIOS call attempted. set apmbios=1 if you want power management\n"); + if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { + /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ + CALLBACK_SZF(false); + } + } + break; + case 0xe8: + switch (reg_al) { + case 0x01: { /* E801: memory size */ + Bitu sz = MEM_TotalPages()*4; + if (sz >= 1024) sz -= 1024; + else sz = 0; + reg_ax = reg_cx = (sz > 0x3C00) ? 0x3C00 : sz; /* extended memory between 1MB and 16MB in KBs */ + sz -= reg_ax; + sz /= 64; /* extended memory size from 16MB in 64KB blocks */ + if (sz > 65535) sz = 65535; + reg_bx = reg_dx = sz; + CALLBACK_SCF(false); + } + break; + case 0x20: { /* E820: MEMORY LISTING */ + if (reg_edx == 0x534D4150 && reg_ecx >= 20 && (MEM_TotalPages()*4) >= 24000) { + /* return a minimalist list: + * + * 0) 0x000000-0x09EFFF Free memory + * 1) 0x0C0000-0x0FFFFF Reserved + * 2) 0x100000-... Free memory (no ACPI tables) */ + if (reg_ebx < E280_table_entries) { + BIOS_E280_entry &ent = E280_table[reg_ebx]; + Bitu seg = SegValue(es); + + /* write to ES:DI */ + real_writed(seg,reg_di+0x00,ent.base); + real_writed(seg,reg_di+0x04,(uint32_t)(ent.base >> (uint64_t)32u)); + real_writed(seg,reg_di+0x08,ent.length); + real_writed(seg,reg_di+0x0C,(uint32_t)(ent.length >> (uint64_t)32u)); + real_writed(seg,reg_di+0x10,ent.type); + reg_ecx = 20; + + /* return EBX pointing to next entry. wrap around, as most BIOSes do. + * the program is supposed to stop on CF=1 or when we return EBX == 0 */ + if (++reg_ebx >= E280_table_entries) reg_ebx = 0; + } + else { + CALLBACK_SCF(true); + } + + reg_eax = 0x534D4150; + } + else { + reg_eax = 0x8600; + CALLBACK_SCF(true); + } + } + break; + default: + unhandled: + LOG(LOG_BIOS,LOG_ERROR)("INT15:Unknown call ah=E8, al=%2X",reg_al); + reg_ah=0x86; + CALLBACK_SCF(true); + if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { + /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ + CALLBACK_SZF(false); + } + } + break; + case 0x50: + if(isDBCSCP()) { + if(reg_al == 0x00) { + if(reg_bl == 0x00 && reg_bp == 0x00) { + enum DOSV_FONT font = DOSV_FONT_MAX; + if(reg_bh & 0x01) { + if(reg_dh == 16 && reg_dl == 16) { + font = DOSV_FONT_16X16; + } else if(reg_dh == 24 && reg_dl == 24) { + font = DOSV_FONT_24X24; + } + } else { + if(reg_dh == 8) { + if(reg_dl == 16) { + font = DOSV_FONT_8X16; + } else if(reg_dl == 19) { + font = DOSV_FONT_8X19; + } + } else if(reg_dh == 12 && reg_dl == 24) { + font = DOSV_FONT_12X24; + } + } + if(font != DOSV_FONT_MAX) { + reg_ah = 0x00; + SegSet16(es, CB_SEG); + reg_bx = DOSV_GetFontHandlerOffset(font); + CALLBACK_SCF(false); + break; + } + } + } else if(reg_al == 0x01) { + if(reg_dh == 16 && reg_dl == 16) { + reg_ah = 0x00; + SegSet16(es, CB_SEG); + reg_bx = DOSV_GetFontHandlerOffset(DOSV_FONT_16X16_WRITE); + CALLBACK_SCF(false); + break; + } else if(reg_dh == 24 && reg_dl == 24) { + reg_ah = 0x00; + SegSet16(es, CB_SEG); + reg_bx = DOSV_GetFontHandlerOffset(DOSV_FONT_24X24_WRITE); + CALLBACK_SCF(false); + break; + } else { + reg_ah = 0x06; // read only + } + } + CALLBACK_SCF(true); + } + break; + case 0x49: + if(isDBCSCP()) { + reg_ah = 0x00; + reg_bl = 0x00; + CALLBACK_SCF(false); + } else { + CALLBACK_SCF(true); + } + break; + default: + LOG(LOG_BIOS,LOG_ERROR)("INT15:Unknown call ax=%4X",reg_ax); + reg_ah=0x86; + CALLBACK_SCF(true); + if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { + /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ + CALLBACK_SZF(false); + } + } + return CBRET_NONE; +} + +void BIOS_UnsetupKeyboard(void); +void BIOS_SetupKeyboard(void); +void BIOS_UnsetupDisks(void); +void BIOS_SetupDisks(void); +void CPU_Snap_Back_To_Real_Mode(); +void CPU_Snap_Back_Restore(); + +static Bitu Default_IRQ_Handler(void) { + IO_WriteB(0x20, 0x0b); + uint8_t master_isr = IO_ReadB(0x20); + if (master_isr) { + IO_WriteB(0xa0, 0x0b); + uint8_t slave_isr = IO_ReadB(0xa0); + if (slave_isr) { + IO_WriteB(0xa1, IO_ReadB(0xa1) | slave_isr); + IO_WriteB(0xa0, 0x20); + } + else IO_WriteB(0x21, IO_ReadB(0x21) | (master_isr & ~4)); + IO_WriteB(0x20, 0x20); +#if C_DEBUG + uint16_t irq = 0; + uint16_t isr = master_isr; + if (slave_isr) isr = slave_isr << 8; + while (isr >>= 1) irq++; + LOG(LOG_BIOS, LOG_WARN)("Unexpected IRQ %u", irq); +#endif + } + else master_isr = 0xff; + mem_writeb(BIOS_LAST_UNEXPECTED_IRQ, master_isr); + return CBRET_NONE; +} + +static Bitu IRQ14_Dummy(void) { + /* FIXME: That's it? Don't I EOI the PIC? */ + return CBRET_NONE; +} + +static Bitu IRQ15_Dummy(void) { + /* FIXME: That's it? Don't I EOI the PIC? */ + return CBRET_NONE; +} + +void On_Software_CPU_Reset(); + +static Bitu INT18_Handler(void) { + if (ibm_rom_basic_size != 0) { + /* jump to BASIC (usually F600:0000 for IBM 5150 ROM BASIC) */ + SegSet16(cs, ibm_rom_basic_base >> 4); + reg_eip = 0; + } + else { + LOG_MSG("Restart by INT 18h requested\n"); + On_Software_CPU_Reset(); + /* does not return */ + } + return CBRET_NONE; +} + +static Bitu INT19_Handler(void) { + LOG_MSG("Restart by INT 19h requested\n"); + /* FIXME: INT 19h is sort of a BIOS boot BIOS reset-ish thing, not really a CPU reset at all. */ + On_Software_CPU_Reset(); + /* does not return */ + return CBRET_NONE; +} + +void bios_enable_ps2() { + mem_writew(BIOS_CONFIGURATION, + mem_readw(BIOS_CONFIGURATION)|0x04); /* PS/2 mouse */ +} + +void BIOS_ZeroExtendedSize(bool in) { + if(in) other_memsystems++; + else other_memsystems--; + if(other_memsystems < 0) other_memsystems=0; + + if (IS_PC98_ARCH) { + Bitu mempages = MEM_TotalPages(); /* in 4KB pages */ + + /* What applies to IBM PC/AT (zeroing out the extended memory size) + * also applies to PC-98, when HIMEM.SYS is loaded */ + if (in) mempages = 0; + + /* extended memory size (286 systems, below 16MB) */ + if (mempages > (1024UL/4UL)) { + unsigned int ext = ((mempages - (1024UL/4UL)) * 4096UL) / (128UL * 1024UL); /* convert to 128KB units */ + + /* extended memory, up to 16MB capacity (for 286 systems?) + * + * MS-DOS drivers will "allocate" for themselves by taking from the top of + * extended memory then subtracting from this value. + * + * capacity does not include conventional memory below 1MB, nor any memory + * above 16MB. + * + * PC-98 systems may reserve the top 1MB, limiting the top to 15MB instead, + * for the ISA memory hole needed for DOS games that use the 256-color linear framebuffer. + * + * 0x70 = 128KB * 0x70 = 14MB + * 0x78 = 128KB * 0x70 = 15MB */ + if (isa_memory_hole_15mb) { + if (ext > 0x70) ext = 0x70; + } + else { + if (ext > 0x78) ext = 0x78; + } + + mem_writeb(0x401,ext); + } + else { + mem_writeb(0x401,0x00); + } + + /* extended memory size (386 systems, at or above 16MB) */ + if (mempages > ((1024UL*16UL)/4UL)) { + unsigned int ext = ((mempages - ((1024UL*16UL)/4UL)) * 4096UL) / (1024UL * 1024UL); /* convert to MB */ + + /* extended memory, at or above 16MB capacity (for 386+ systems?) + * + * MS-DOS drivers will "allocate" for themselves by taking from the top of + * extended memory then subtracting from this value. + * + * capacity does not include conventional memory below 1MB, nor any memory + * below 16MB. */ + if (ext > 0xFFFE) ext = 0xFFFE; + + mem_writew(0x594,ext); + } + else { + mem_writew(0x594,0x00); + } + } +} + +unsigned char do_isapnp_chksum(const unsigned char* d, int i) { + unsigned char sum = 0; + + while (i-- > 0) + sum += *d++; + + return (0x100 - sum) & 0xFF; +} + +void MEM_ResetPageHandler_Unmapped(Bitu phys_page, Bitu pages); + +unsigned int dos_conventional_limit = 0; + +bool AdapterROM_Read(Bitu address,unsigned long *size) { + unsigned char c[3]; + unsigned int i; + + if ((address & 0x1FF) != 0) { + LOG(LOG_MISC,LOG_DEBUG)("AdapterROM_Read: Caller attempted ROM scan not aligned to 512-byte boundary"); + return false; + } + + for (i=0;i < 3;i++) + c[i] = mem_readb(address+i); + + if (c[0] == 0x55 && c[1] == 0xAA) { + unsigned char chksum=0; + *size = (unsigned long)c[2] * 512UL; + for (i=0;i < (unsigned int)(*size);i++) chksum += mem_readb(address+i); + if (chksum != 0) { + LOG(LOG_MISC,LOG_WARN)("AdapterROM_Read: Found ROM at 0x%lx but checksum failed (got %02xh expect %02xh)\n",(unsigned long)address,chksum,0); + return false; + } + + return true; + } + + return false; +} + +static int bios_pc98_posx = 0; +extern bool tooutttf; + +static void BIOS_Int10RightJustifiedPrint(const int x,int &y,const char *msg, bool boxdraw = false, bool tobold = false) { + if (tooutttf) { + tooutttf = false; + change_output(10); + } + if (control->opt_fastlaunch) return; + const char *s = msg; + if (machine != MCH_PC98) { + unsigned int bold = 0; + while (*s != 0) { + if (*s == '\n') { + y++; + reg_eax = 0x0200u; // set cursor pos + reg_ebx = 0; // page zero + reg_dh = y; // row 4 + reg_dl = x; // column 20 + CALLBACK_RunRealInt(0x10); + s++; + } + else { + if (tobold&&!bold) { + if ((strlen(s)>3&&!strncmp(s, "DEL", 3))||!strncmp(s, "ESC", 3)) bold = 3; + else if (strlen(s)>5&&!strncmp(s, "ENTER", 5)) bold = 5; + else if (strlen(s)>8&&!strncmp(s, "SPACEBAR", 8)) bold = 8; + } + if (bold>0) { + bold--; + reg_eax = 0x0900u | ((unsigned char)(*s++)); + reg_ebx = 0x000fu; + reg_ecx = 0x0001u; + CALLBACK_RunRealInt(0x10); + reg_eax = 0x0300u; + reg_ebx = 0x0000u; + CALLBACK_RunRealInt(0x10); + reg_eax = 0x0200u; + reg_ebx = 0x0000u; + reg_edx++; + CALLBACK_RunRealInt(0x10); + } else { + reg_eax = 0x0E00u | ((unsigned char)(*s++)); + reg_ebx = 0x07u; + CALLBACK_RunRealInt(0x10); + } + } + } + } + else { + unsigned int bo; + + while (*s != 0) { + if (*s == '\n') { + y++; + s++; + bios_pc98_posx = x; + + bo = (((unsigned int)y * 80u) + (unsigned int)bios_pc98_posx) * 2u; + } + else if (*s == '\r') { + s++; /* ignore */ + continue; + } + else { + bo = (((unsigned int)y * 80u) + (unsigned int)(bios_pc98_posx++)) * 2u; /* NTS: note the post increment */ + if (boxdraw) { + unsigned int ch = (unsigned char)*s; + if (ch==0xcd) ch = 0x250B; + else if (ch==0xba) ch = 0x270B; + else if (ch==0xc9) ch = 0x330B; + else if (ch==0xbb) ch = 0x370B; + else if (ch==0xc8) ch = 0x3B0B; + else if (ch==0xbc) ch = 0x3F0B; + mem_writew(0xA0000+bo,ch); + } else + mem_writew(0xA0000+bo,(unsigned char)*s); + mem_writeb(0xA2000+bo,0xE1); + + s++; + bo += 2; /* and keep the cursor following the text */ + } + + reg_eax = 0x1300; // set cursor pos (PC-98) + reg_edx = bo; // byte position + CALLBACK_RunRealInt(0x18); + } + } +} + +char *getSetupLine(const char *capt, const char *cont) { + unsigned int pad1=(unsigned int)(25-strlen(capt)), pad2=(unsigned int)(41-strlen(cont)); + static char line[90]; + sprintf(line, "\x0ba%*c%s%*c%s%*c\x0ba", 12, ' ', capt, pad1, ' ', cont, pad2, ' '); + return line; +} + +const char *GetCPUType(); +void updateDateTime(int x, int y, int pos) +{ + (void)x;//UNUSED + (void)y;//UNUSED + char str[50]; + time_t curtime = time(NULL); + struct tm *loctime = localtime (&curtime); + Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; + unsigned int sec=(uint8_t)((Bitu)time % 60); + time/=60; + unsigned int min=(uint8_t)((Bitu)time % 60); + time/=60; + unsigned int hour=(uint8_t)((Bitu)time % 24); + int val=0; + unsigned int bo; + Bitu edx=0, pdx=0x0500u; + for (int i=1; i<7; i++) { + switch (i) { + case 1: + val = machine==MCH_PC98?loctime->tm_year+1900:dos.date.year; + reg_edx = 0x0326u; + if (i==pos) pdx = reg_edx; + break; + case 2: + val = machine==MCH_PC98?loctime->tm_mon+1:dos.date.month; + reg_edx = 0x032bu; + if (i==pos) pdx = reg_edx; + break; + case 3: + val = machine==MCH_PC98?loctime->tm_mday:dos.date.day; + reg_edx = 0x032eu; + if (i==pos) pdx = reg_edx; + break; + case 4: + val = machine==MCH_PC98?loctime->tm_hour:hour; + reg_edx = 0x0426u; + if (i==pos) pdx = reg_edx; + break; + case 5: + val = machine==MCH_PC98?loctime->tm_min:min; + reg_edx = 0x0429u; + if (i==pos) pdx = reg_edx; + break; + case 6: + val = machine==MCH_PC98?loctime->tm_sec:sec; + reg_edx = 0x042cu; + if (i==pos) pdx = reg_edx; + break; + } + edx = reg_edx; + sprintf(str, i==1?"%04u":"%02u",val); + for (unsigned int j=0; jopt_securemode || control->SecureMode()) + strcpy(pcname, "N/A"); + else { +#if defined(WIN32) + DWORD size = DOSNAMEBUF; + GetComputerName(pcname, &size); + if (!size) +#else + int result = gethostname(pcname, DOSNAMEBUF); + if (result) +#endif + strcpy(pcname, "N/A"); + } + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Computer name:", pcname), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Product name:", ("DOSBox-X "+std::string(VERSION)).c_str()), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Product updated:", UPDATED_STR), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS description:", bios_type_string), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS version:", bios_version_string), true); + uint32_t year,month,day; + if (sscanf(bios_date_string,"%u/%u/%u",&month,&day,&year)==3) { + char datestr[30]; + sprintf(datestr, "%04u-%02u-%02u",year<80?2000+year:(year<100?1900+year:year),month,day); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS date:", datestr), true); + } else + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS date:", bios_date_string), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Processor type:", GetCPUType()), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Processor speed:", (std::to_string(CPU_CycleAutoAdjust?CPU_CyclePercUsed:CPU_CycleMax)+(CPU_CycleAutoAdjust?"%":" cycles/ms")).c_str()), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Coprocessor:", enable_fpu?"Yes":"No"), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Video card:", card), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Video memory:", (std::to_string(vga.mem.memsize/1024)+"K").c_str()), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Total memory:", (std::to_string(MEM_TotalPages()*4096/1024)+"K").c_str()), true); + BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); + BIOS_Int10RightJustifiedPrint(x,y,"\x0c8\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0bc", true); + if (machine == MCH_PC98) + BIOS_Int10RightJustifiedPrint(x,y," ESC = Exit "); + else + BIOS_Int10RightJustifiedPrint(x,y," ESC: Exit Arrows: Select Item +/-: Change Values "); +} + +static Bitu ulimit = 0; +static Bitu t_conv = 0; +static Bitu t_conv_real = 0; +static bool bios_first_init=true; +static bool bios_has_exec_vga_bios=false; +static Bitu adapter_scan_start; + +/* FIXME: At global scope their destructors are called after the rest of DOSBox-X has shut down. Move back into BIOS scope. */ +static CALLBACK_HandlerObject int4b_callback; +static const size_t callback_count = 20; +static CALLBACK_HandlerObject callback[callback_count]; /* <- fixme: this is stupid. just declare one per interrupt. */ +static CALLBACK_HandlerObject cb_bios_post; +static CALLBACK_HandlerObject callback_pc98_lio; +static CALLBACK_HandlerObject callback_pc98_avspcm; + +Bitu call_pnp_r = ~0UL; +Bitu call_pnp_rp = 0; + +Bitu call_pnp_p = ~0UL; +Bitu call_pnp_pp = 0; + +Bitu isapnp_biosstruct_base = 0; + +Bitu BIOS_boot_code_offset = 0; +Bitu BIOS_bootfail_code_offset = 0; + +bool bios_user_reset_vector_blob_run = false; +Bitu bios_user_reset_vector_blob = 0; + +Bitu bios_user_boot_hook = 0; + +void CALLBACK_DeAllocate(Bitu in); + +void BIOS_OnResetComplete(Section *x); + +Bitu call_irq0 = 0; +Bitu call_irq07default = 0; +Bitu call_irq815default = 0; + + +/* NEC PC-98 detection notes: + * - Documented: No ASCII date at F000:FFF5 + * - CWSDPMI (PC-98 patched version): Call INT 10h AH=0F BH=FF. If registers don't change, it's PC-98 + * - DJGPP libc, crt1.c (PC-98 patched version): If the WORD at F000:FFF3 (segment part of JMP FAR) is 0xFD80, it's PC-98 */ + +void write_FFFF_PC98_signature() { + /* this may overwrite the existing signature. + * PC-98 systems DO NOT have an ASCII date at F000:FFF5 + * and the WORD value at F000:FFFE is said to be a checksum of the BIOS */ + + // The farjump at the processor reset entry point (jumps to POST routine) + phys_writeb(0xffff0,0xEA); // FARJMP + + /* Segment value must be 0xFD80 to satisfy PC-98 patched DJGPP check */ + const uint16_t oseg = RealSeg(BIOS_DEFAULT_RESET_LOCATION); + phys_writew(0xffff1,RealOff(BIOS_DEFAULT_RESET_LOCATION)-((0xFD80-oseg)*16)); // offset + phys_writew(0xffff3,0xFD80); // segment + + // write nothing (not used) + for(Bitu i = 0; i < 9; i++) phys_writeb(0xffff5+i,0); + + // fake BIOS checksum + phys_writew(0xffffe,0xABCD); +} + +void gdc_egc_enable_update_vars(void) { + unsigned char b; + + b = mem_readb(0x54D); + b &= ~0x40; + if (enable_pc98_egc) b |= 0x40; + mem_writeb(0x54D,b); + + b = mem_readb(0x597); + b &= ~0x04; + if (enable_pc98_egc) b |= 0x04; + mem_writeb(0x597,b); + + if (!enable_pc98_egc) + pc98_gdc_vramop &= ~(1 << VOPBIT_EGC); +} + +void gdc_grcg_enable_update_vars(void) { + unsigned char b; + + b = mem_readb(0x54C); + b &= ~0x02; + if (enable_pc98_grcg) b |= 0x02; + mem_writeb(0x54C,b); + + //TODO: How to reset GRCG? +} + + +void gdc_16color_enable_update_vars(void) { + unsigned char b; + + b = mem_readb(0x54C); + b &= ~0x05; + if (enable_pc98_16color) b |= 0x05; // bit0 .. DIPSW 1-8 support GLIO 16-colors + mem_writeb(0x54C,b); + + if(!enable_pc98_256color) {//force switch to 16-colors mode + void pc98_port6A_command_write(unsigned char b); + pc98_port6A_command_write(0x20); + } + if(!enable_pc98_16color) {//force switch to 8-colors mode + void pc98_port6A_command_write(unsigned char b); + pc98_port6A_command_write(0x00); + } +} + +uint32_t BIOS_get_PC98_INT_STUB(void) { + return callback[18].Get_RealPointer(); +} + +Bitu call_pc98_default_stop; + +extern bool DOS_BreakFlag; +extern bool DOS_BreakConioFlag; + +static Bitu pc98_default_stop_handler(void) { + // INT 06h, which means someone pressed the STOP key... or the CPU is signalling an invalid opcode. + // The overlap makes it extremely unclear. + LOG_MSG("Invalid opcode or unhandled PC-98 STOP key interrupt 06h"); + + // try to make it work as CTRL+BREAK in the built-in DOS environment. + if (!dos_kernel_disabled) + DOS_BreakFlag = DOS_BreakConioFlag = true; + + return CBRET_NONE; +} + +static unsigned char BCD2BIN(unsigned char x) { + return ((x >> 4) * 10) + (x & 0xF); +} + + +/* NTS: Remember the 8259 is non-sentient, and the term "slave" is used in a computer programming context */ +static Bitu Default_IRQ_Handler_Cooperative_Slave_Pic(void) { + /* PC-98 style IRQ 8-15 handling. + * + * This mimics the recommended procedure [https://www.webtech.co.jp/company/doc/undocumented_mem/io_pic.txt] + * + * mov al,20h ;Send EOI to SLAVE + * out 0008h,al + * jmp $+2 ;I/O WAIT + * mov al,0Bh ;ISR read mode set(slave) + * out 0008h,al + * jmp $+2 ;I/O WAIT + * in al,0008h ;ISR read(slave) + * cmp al,00h ;slave pic in-service ? + * jne EoiEnd + * mov al,20h ;Send EOI to MASTER + * out 0000h,al + */ + IO_WriteB(IS_PC98_ARCH ? 0x08 : 0xA0,0x20); // send EOI to slave + IO_WriteB(IS_PC98_ARCH ? 0x08 : 0xA0,0x0B); // ISR read mode set + if (IO_ReadB(IS_PC98_ARCH ? 0x08 : 0xA0) == 0) // if slave pic in service.. + IO_WriteB(IS_PC98_ARCH ? 0x00 : 0x20,0x20); // then EOI the master + + return CBRET_NONE; +} + +extern uint32_t tandy_128kbase; + +static int bios_post_counter = 0; + +extern void BIOSKEY_PC98_Write_Tables(void); +extern Bitu PC98_AVSDRV_PCM_Handler(void); + +static unsigned int acpiptr2ofs(unsigned char *w) { + return w - ACPI_buffer; +} + +static PhysPt acpiofs2phys(unsigned int o) { + return ACPI_BASE + o; +} + +class ACPISysDescTableWriter { +public: + ACPISysDescTableWriter(); + ~ACPISysDescTableWriter(void); +public: + ACPISysDescTableWriter &begin(unsigned char *w,unsigned char *f,size_t n_tablesize=36); + ACPISysDescTableWriter &setRev(const unsigned char rev); + ACPISysDescTableWriter &setOemID(const char *id); + ACPISysDescTableWriter &setSig(const char *sig); + ACPISysDescTableWriter &setOemTableID(const char *id); + ACPISysDescTableWriter &setOemRev(const uint32_t rev); + ACPISysDescTableWriter &setCreatorID(const uint32_t id); + ACPISysDescTableWriter &setCreatorRev(const uint32_t rev); + ACPISysDescTableWriter &expandto(size_t sz); + unsigned char* getptr(size_t ofs=0,size_t sz=1); + size_t get_tablesize(void) const; + unsigned char* finish(void); +private: + size_t tablesize = 0; + unsigned char* base = NULL; + unsigned char* f = NULL; +}; + +size_t ACPISysDescTableWriter::get_tablesize(void) const { + return tablesize; +} + +ACPISysDescTableWriter::ACPISysDescTableWriter() { +} + +ACPISysDescTableWriter::~ACPISysDescTableWriter(void) { + if (tablesize != 0) LOG(LOG_MISC,LOG_ERROR)("ACPI table writer destructor called without completing a table"); +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::begin(unsigned char *n_w,unsigned char *n_f,size_t n_tablesize) { + if (tablesize != 0) LOG(LOG_MISC,LOG_ERROR)("ACPI table writer asked to begin a table without completing the last table"); + base = n_w; + f = n_f; + tablesize = n_tablesize; + assert(tablesize >= 36); + assert((base+tablesize) <= f); + assert(base != NULL); + assert(f != NULL); + assert(base < f); + + memset(base,0,tablesize); + memcpy(base+10,"DOSBOX",6); // OEM ID + memcpy(base+16,"DOSBox-X",8); // OEM Table ID + host_writed(base+24,1); // OEM revision + memcpy(base+28,"DBOX",4); // Creator ID + host_writed(base+32,1); // Creator revision + + return *this; +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::setRev(const unsigned char rev) { + assert(base != NULL); + assert(tablesize >= 36); + base[8] = rev; + return *this; +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::setOemID(const char *id) { + assert(id != NULL); + assert(base != NULL); + assert(tablesize >= 36); + unsigned char *wp = base+10; + for (unsigned int i=0;i < 6;i++) { + if (*id != 0) + *wp++ = (unsigned char)(*id++); + else + *wp++ = ' '; + } + return *this; +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::setSig(const char *sig) { + assert(sig != NULL); + assert(base != NULL); + assert(tablesize >= 36); + unsigned char *wp = base; + for (unsigned int i=0;i < 4;i++) { + if (*sig != 0) + *wp++ = (unsigned char)(*sig++); + else + *wp++ = ' '; + } + return *this; +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::setOemTableID(const char *id) { + assert(id != NULL); + assert(base != NULL); + assert(tablesize >= 36); + unsigned char *wp = base+16; + for (unsigned int i=0;i < 8;i++) { + if (*id != 0) + *wp++ = (unsigned char)(*id++); + else + *wp++ = ' '; + } + return *this; +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::setOemRev(const uint32_t rev) { + assert(base != NULL); + assert(tablesize >= 36); + host_writed(base+24,rev); + return *this; +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::setCreatorID(const uint32_t id) { + assert(base != NULL); + assert(tablesize >= 36); + host_writed(base+28,id); + return *this; +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::setCreatorRev(const uint32_t rev) { + assert(base != NULL); + assert(tablesize >= 36); + host_writed(base+32,rev); + return *this; +} + +ACPISysDescTableWriter &ACPISysDescTableWriter::expandto(size_t sz) { + assert(base != NULL); + assert((base+sz) <= f); + if (tablesize < sz) tablesize = sz; + return *this; +} + +unsigned char* ACPISysDescTableWriter::getptr(size_t ofs,size_t sz) { + assert(base != NULL); + assert((base+ofs+sz) <= f); + if (tablesize < (ofs+sz)) tablesize = ofs+sz; + return base+ofs; +} + +unsigned char *ACPISysDescTableWriter::finish(void) { + if (base != NULL) { + unsigned char *ret = base + tablesize; + + assert((base+tablesize) <= f); + assert(tablesize >= 36); + + /* update length field */ + host_writed(base+4,tablesize); + + /* update checksum field */ + unsigned int i,c; + base[9] = 0; + c = 0; for (i=0;i < tablesize;i++) c += base[i]; + base[9] = (0 - c) & 0xFFu; + + base = f = NULL; + tablesize = 0; + return ret; + } + + return NULL; +} + +enum class ACPIRegionSpace { + SystemMemory=0, + SystemIO=1, + PCIConfig=2, + EmbeddedControl=3, + SMBus=4 +}; + +namespace ACPIMethodFlags { + static constexpr unsigned char ArgCount(const unsigned c) { + return c&3u; + } + enum { + NotSerialized=(0 << 3), + Serialized=(1 << 3) + }; +} + +static constexpr unsigned int ACPIrtIO_16BitDecode = (1u << 0u); + +static constexpr unsigned int ACPIrtMR24_Writeable = (1u << 0u); +static constexpr unsigned int ACPIrtMR32_Writeable = (1u << 0u); + +namespace ACPIFieldFlag { + namespace AccessType { + enum { + AnyAcc=0, + ByteAcc=1, + WordAcc=2, + DwordAcc=3, + BlockAcc=4, + SMBSendRevAcc=5, + SMBQuickAcc=6 + }; + } + namespace LockRule { + enum { + NoLock=(0 << 4), + Lock=(1 << 4) + }; + } + namespace UpdateRule { + enum { + Preserve=(0 << 5), + WriteAsOnes=(1 << 5), + WriteAsZeros=(2 << 5) + }; + } +} + +enum class ACPIAMLOpcode:unsigned char { + ZeroOp = 0x00, // ACPI 1.0+ + OneOp = 0x01, // ACPI 1.0+ + + AliasOp = 0x06, // ACPI 1.0+ + + NameOp = 0x08, // ACPI 1.0+ + + BytePrefix = 0x0A, // ACPI 1.0+ + WordPrefix = 0x0B, // ACPI 1.0+ + DwordPrefix = 0x0C, // ACPI 1.0+ + StringPrefix = 0x0D, // ACPI 1.0+ + QWordPrefix = 0x0E, // ACPI 2.0+ + + ScopeOp = 0x10, // ACPI 1.0+ + BufferOP = 0x11, // ACPI 1.0+ + PackageOp = 0x12, // ACPI 1.0+ + VarPackageOp = 0x13, // ACPI 2.0+ + MethodOp = 0x14, // ACPI 1.0+ + ExternalOp = 0x15, // ACPI 6.0+ + + DualNamePrefix = 0x2E, // ACPI 1.0+ + MultiNamePrefix = 0x2F, // ACPI 1.0+ + + NameCharA = 0x41, // ACPI 1.0b+ + NameCharB = 0x42, // ACPI 1.0b+ + NameCharC = 0x43, // ACPI 1.0b+ + NameCharD = 0x44, // ACPI 1.0b+ + NameCharE = 0x45, // ACPI 1.0b+ + NameCharF = 0x46, // ACPI 1.0b+ + NameCharG = 0x47, // ACPI 1.0b+ + NameCharH = 0x48, // ACPI 1.0b+ + NameCharI = 0x49, // ACPI 1.0b+ + NameCharJ = 0x4A, // ACPI 1.0b+ + NameCharK = 0x4B, // ACPI 1.0b+ + NameCharL = 0x4C, // ACPI 1.0b+ + NameCharM = 0x4D, // ACPI 1.0b+ + NameCharN = 0x4E, // ACPI 1.0b+ + NameCharO = 0x4F, // ACPI 1.0b+ + NameCharP = 0x50, // ACPI 1.0b+ + NameCharQ = 0x51, // ACPI 1.0b+ + NameCharR = 0x52, // ACPI 1.0b+ + NameCharS = 0x53, // ACPI 1.0b+ + NameCharT = 0x54, // ACPI 1.0b+ + NameCharU = 0x55, // ACPI 1.0b+ + NameCharV = 0x56, // ACPI 1.0b+ + NameCharW = 0x57, // ACPI 1.0b+ + NameCharX = 0x58, // ACPI 1.0b+ + NameCharY = 0x59, // ACPI 1.0b+ + NameCharZ = 0x5A, // ACPI 1.0b+ + + ExtendedOperatorPrefix = 0x5B, // ACPI 1.0+ + RootNamePrefix = 0x5C, // ACPI 1.0+ + + ParentNamePrefix = 0x5E, // ACPI 1.0+ + NameChar_ = 0x5F, // ACPI 2.0+ + + Local0 = 0x60, // ACPI 1.0+ + Local1 = 0x61, // ACPI 1.0+ + Local2 = 0x62, // ACPI 1.0+ + Local3 = 0x63, // ACPI 1.0+ + Local4 = 0x64, // ACPI 1.0+ + Local5 = 0x65, // ACPI 1.0+ + Local6 = 0x66, // ACPI 1.0+ + Local7 = 0x67, // ACPI 1.0+ + Arg0 = 0x68, // ACPI 1.0+ + Arg1 = 0x69, // ACPI 1.0+ + Arg2 = 0x6A, // ACPI 1.0+ + Arg3 = 0x6B, // ACPI 1.0+ + Arg4 = 0x6C, // ACPI 1.0+ + Arg5 = 0x6D, // ACPI 1.0+ + Arg6 = 0x6E, // ACPI 1.0+ + + StoreOp = 0x70, // ACPI 1.0+ + RefOfOp = 0x71, // ACPI 1.0+ + AddOp = 0x72, // ACPI 1.0+ + ConcatOp = 0x73, // ACPI 1.0+ + SubtractOp = 0x74, // ACPI 1.0+ + IncrementOp = 0x75, // ACPI 1.0+ + DecrementOp = 0x76, // ACPI 1.0+ + MultiplyOp = 0x77, // ACPI 1.0+ + DivideOp = 0x78, // ACPI 1.0+ + ShiftLeftOp = 0x79, // ACPI 1.0+ + ShiftRightOp = 0x7A, // ACPI 1.0+ + AndOp = 0x7B, // ACPI 1.0+ + NAndOp = 0x7C, // ACPI 1.0+ + OrOp = 0x7D, // ACPI 1.0+ + NOrOp = 0x7E, // ACPI 1.0+ + XOrOp = 0x7F, // ACPI 1.0+ + NotOp = 0x80, // ACPI 1.0+ + FindSetLeftBitOp = 0x81, // ACPI 1.0+ + FindSetRightBitOp = 0x82, // ACPI 1.0+ + DerefOfOp = 0x83, // ACPI 2.0+ + ConcatResOp = 0x84, // ACPI 2.0+ + ModOp = 0x85, // ACPI 2.0+ + NotifyOp = 0x86, // ACPI 1.0+ + SizeOfOp = 0x87, // ACPI 1.0+ + IndexOp = 0x88, // ACPI 1.0+ + MatchOp = 0x89, // ACPI 1.0+ + DWordFieldOp = 0x8A, // ACPI 1.0+ + CreateDWordFieldOp = 0x8A, // ACPI 1.0b+ + WordFieldOp = 0x8B, // ACPI 1.0+ + CreateWordFieldOp = 0x8B, // ACPI 1.0b+ + ByteFieldOp = 0x8C, // ACPI 1.0+ + CreateByteFieldOp = 0x8C, // ACPI 1.0b+ + BitFieldOp = 0x8D, // ACPI 1.0+ + CreateBitFieldOp = 0x8D, // ACPI 1.0b+ + ObjTypeOp = 0x8E, // ACPI 1.0+ + CreateQWordField = 0x8F, // ACPI 2.0+ + LAndOp = 0x90, // ACPI 1.0+ + LOrOp = 0x91, // ACPI 1.0+ + LNotOp = 0x92, // ACPI 1.0+ + LEQOp = 0x93, // ACPI 1.0+ + LEqualOp = 0x93, // ACPI 1.0b+ same as LEQOp obviously to make opcode name clearer +/* LNotEQOp = 0x93 0x92 */ // ACPI 1.0, seems to be an error in the documentation as that is LEqualOp LNotOp which doesn't make sense +/* LNotEqualOp = 0x92 0x93 */ // ACPI 1.0b+, correction of opcode and to make opcode name clearer. Literally LNotOp LEqualOp + LGOp = 0x94, // ACPI 1.0+ + LGreaterOp = 0x94, // ACPI 1.0b+ same as LGOp obviously to make opcode name clearer +/* LLEQOp = 0x94 0x92 */ // ACPI 1.0, seems to be an error in the documentation as that is LEqualOp LNotOp which doesn't make sense +/* LLessEqualOp = 0x92 0x94 */ // ACPI 1.0b+, correction of opcode and to make opcode name clearer. Literally LNotOp LGreaterOp + LLOp = 0x95, // ACPI 1.0+ + LLessOp = 0x95, // ACPI 1.0b+ same as LLOp obviously to make opcode name clearer +/* LGEQOp = 0x95 0x92 */ // ACPI 1.0, seems to be an error in the documentation as that is LEqualOp LNotOp which doesn't make sense +/* LGreaterEqualOp = 0x95 0x92 */ + // ^ ACPI 1.0b+, um... they kept the same mistake, but does make opcode name clearer, but the definition does correctly say LNotOp LLessOp. + // ^ Um... in fact ACPI 2.0 keeps the mistake and the corrected definition! They didn't fix THAT error until ACPI 3.0! + // ^ Would mistakes like this have anything to do with the Linux kernel reportedly not wanting to support any ACPI BIOS made before the year 2000? +/* LGreaterEqualOp = 0x92 0x95 */ // ACPI 3.0+ corrected byte pattern. Literally LNotOp LLessOp + BuffOp = 0x96, // ACPI 2.0+ + ToBufferOp = 0x96, // ACPI 2.0a+, correction of opcode and to make opcode name clearer + DecStrOp = 0x97, // ACPI 2.0+ + ToDecimalStringOp = 0x97, // ACPI 2.0a+, correction of opcode and to make opcode name clearer + HexStrOp = 0x98, // ACPI 2.0+ + ToHexStringOp = 0x98, // ACPI 2.0a+, correction of opcode and to make opcode name clearer + IntOp = 0x99, // ACPI 2.0+ + ToIntegerOp = 0x99, // ACPI 2.0a+, correction of opcode and to make opcode name clearer + + StringOp = 0x9C, // ACPI 2.0+ + ToStringOp = 0x9C, // ACPI 2.0a+, correction of opcode and to make opcode name clearer + CopyOp = 0x9D, // ACPI 2.0+ + CopyObjectOp = 0x9D, // ACPI 2.0a+, correction of opcode and to make opcode name clearer + MidOp = 0x9E, // ACPI 2.0+ + ContinueOp = 0x9F, // ACPI 2.0+ + IfOp = 0xA0, // ACPI 1.0+ + ElseOp = 0xA1, // ACPI 1.0+ + WhileOp = 0xA2, // ACPI 1.0+ + NoOp = 0xA3, // ACPI 1.0+ + ReturnOp = 0xA4, // ACPI 1.0+ + BreakOp = 0xA5, // ACPI 1.0+ + + BreakPointOp = 0xCC, // ACPI 1.0+ + + OnesOp = 0xFF // ACPI 1.0+ +}; + +enum class ACPIAMLOpcodeEOP5B:unsigned char { + /*0x5B*/MutexOp = 0x01, // ACPI 1.0+ + /*0x5B*/EventOp = 0x02, // ACPI 1.0+ + + /*0x5B*/ShiftRightBitOp = 0x10, // ACPI 1.0 only, disappeared 1.0b + /*0x5B*/ShiftLeftBitOp = 0x11, // ACPI 1.0 only, disappeared 1.0b + /*0x5B*/CondRefOp = 0x12, // ACPI 1.0+ + /*0x5B*/CreateFieldOp = 0x13, // ACPI 1.0+ + + /*0x5B*/LocalTableOp = 0x1F, // ACPI 2.0+ + /*0x5B*/LoadOp = 0x20, // ACPI 1.0+ + /*0x5B*/StallOp = 0x21, // ACPI 1.0+ + /*0x5B*/SleepOp = 0x22, // ACPI 1.0+ + /*0x5B*/AcquireOp = 0x23, // ACPI 1.0+ + /*0x5B*/SignalOp = 0x24, // ACPI 1.0+ + /*0x5B*/WaitOp = 0x25, // ACPI 1.0+ + /*0x5B*/ResetOp = 0x26, // ACPI 1.0+ + /*0x5B*/ReleaseOp = 0x27, // ACPI 1.0+ + /*0x5B*/FromBCDOp = 0x28, // ACPI 1.0+ + /*0x5B*/ToBCD = 0x29, // ACPI 1.0+ + /*0x5B*/UnloadOp = 0x2A, // ACPI 1.0+ + + /*0x5B*/RevisionOp = 0x30, // ACPI 1.0b+ + /*0x5B*/DebugOp = 0x31, // ACPI 1.0+ + /*0x5B*/FatalOp = 0x32, // ACPI 1.0+ + /*0x5B*/TimerOp = 0x33, // ACPI 3.0+ + + /*0x5B*/OpRegionOp = 0x80, // ACPI 1.0+ + /*0x5B*/FieldOp = 0x81, // ACPI 1.0+ + /*0x5B*/DeviceOp = 0x82, // ACPI 1.0+ + /*0x5B*/ProcessorOp = 0x83, // ACPI 1.0+ + /*0x5B*/PowerResOp = 0x84, // ACPI 1.0+ + /*0x5B*/ThermalZoneOp = 0x85, // ACPI 1.0+ + /*0x5B*/IndexFieldOp = 0x86, // ACPI 1.0+ + /*0x5B*/BankFieldOp = 0x87, // ACPI 1.0+ + /*0x5B*/DataRegionOp = 0x88 // ACPI 2.0+ +}; + +#include + +/* ACPI AML (ACPI Machine Language) writer. + * See also ACPI Specification 1.0b [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/BIOS/ACPI%2c%20Advanced%20Configuration%20and%20Power%20Interface/Advanced%20Configuration%20and%20Power%20Interface%20Specification%20%281999%2d02%2d02%29%20v1%2e0b%2epdf]. + * + * WARNING: The 1.0 specification [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/BIOS/ACPI%2c%20Advanced%20Configuration%20and%20Power%20Interface/Advanced%20Configuration%20and%20Power%20Interface%20Specification%20%281996%2d12%2d22%29%20v1%2e0%2epdf] seems to have some mistakes in a few opcodes in how they are defined, which probably means if your BIOS is from 1996-1998 it might have those few erroneous AML opcodes. */ +class ACPIAMLWriter { + public: + static constexpr unsigned int MaxPkgSize = 0xFFFFFFFu; + public: + struct pkg_t { + unsigned char* pkg_len = NULL; + unsigned char* pkg_data = NULL; + unsigned int element_count = 0; + }; + std::stack pkg_stack; + public: + ACPIAMLWriter(); + ~ACPIAMLWriter(); + public: + unsigned char* writeptr(void) const; + void begin(unsigned char *n_w,unsigned char *n_f); + public: + ACPIAMLWriter &rtDMA(const unsigned char bitmask,const unsigned char flags); + ACPIAMLWriter &rtMemRange24(const unsigned int flags,const unsigned int minr,const unsigned int maxr,const unsigned int alignr,const unsigned int rangr); + ACPIAMLWriter &rtMemRange32(const unsigned int flags,const unsigned int minr,const unsigned int maxr,const unsigned int alignr,const unsigned int rangr); + ACPIAMLWriter &rtIO(const unsigned int flags,const uint16_t minport,const uint16_t maxport,const uint8_t alignment,const uint8_t rlength); + ACPIAMLWriter &rtIRQ(const uint16_t bitmask/*bits [15:0] correspond to IRQ 15-0*/,const bool pciStyle=false); + ACPIAMLWriter &rtHdrSmall(const unsigned char itemName,const unsigned int length); + ACPIAMLWriter &rtHdrLarge(const unsigned char itemName,const unsigned int length); + ACPIAMLWriter &rtBegin(void); + ACPIAMLWriter &rtEnd(void); + public: + ACPIAMLWriter &NameOp(const char *name); + ACPIAMLWriter &ByteOp(const unsigned char v); + ACPIAMLWriter &WordOp(const unsigned int v); + ACPIAMLWriter &DwordOp(const unsigned long v); + ACPIAMLWriter &StringOp(const char *str); + ACPIAMLWriter &OpRegionOp(const char *name,const ACPIRegionSpace regionspace); + ACPIAMLWriter &FieldOp(const char *name,const unsigned int pred_size,const unsigned int fieldflag); + ACPIAMLWriter &FieldOpEnd(void); + ACPIAMLWriter &ScopeOp(const unsigned int pred_size=MaxPkgSize); + ACPIAMLWriter &ScopeOpEnd(void); + ACPIAMLWriter &PackageOp(const unsigned int pred_size=MaxPkgSize); + ACPIAMLWriter &RootCharScopeOp(void); + ACPIAMLWriter &PackageOpEnd(void); + ACPIAMLWriter &RootCharOp(void); + ACPIAMLWriter &NothingOp(void); + ACPIAMLWriter &ZeroOp(void); + ACPIAMLWriter &OneOp(void); + ACPIAMLWriter &AliasOp(const char *what,const char *to_what); + ACPIAMLWriter &BufferOpEnd(void); + ACPIAMLWriter &BufferOp(const unsigned int pred_size=MaxPkgSize); + ACPIAMLWriter &BufferOp(const unsigned char *data,const size_t datalen); + ACPIAMLWriter &DeviceOp(const char *name,const unsigned int pred_size=MaxPkgSize); + ACPIAMLWriter &DeviceOpEnd(void); + ACPIAMLWriter &MethodOp(const char *name,const unsigned int pred_size,const unsigned int methodflags); + ACPIAMLWriter &MethodOpEnd(void); + ACPIAMLWriter &ReturnOp(void); + ACPIAMLWriter &IfOp(const unsigned int pred_size=MaxPkgSize); + ACPIAMLWriter &IfOpEnd(void); + ACPIAMLWriter &ElseOp(const unsigned int pred_size=MaxPkgSize); + ACPIAMLWriter &ElseOpEnd(void); + ACPIAMLWriter &LEqualOp(void); + ACPIAMLWriter &LNotEqualOp(void); + ACPIAMLWriter &LNotOp(void); + ACPIAMLWriter &LAndOp(void); + ACPIAMLWriter &AndOp(void); + ACPIAMLWriter &ArgOp(const unsigned int arg); /* Arg0 through Arg6 */ + ACPIAMLWriter &LocalOp(const unsigned int l); /* Local0 through Local7 */ + ACPIAMLWriter &StoreOp(void); + ACPIAMLWriter &NOrOp(void); + ACPIAMLWriter &OrOp(void); + ACPIAMLWriter &NAndOp(void); + public:// ONLY for writing fields! + ACPIAMLWriter &FieldOpElement(const char *name,const unsigned int bits); + public: + ACPIAMLWriter &PkgLength(const unsigned int len,unsigned char* &wp,const unsigned int minlen=1); + ACPIAMLWriter &PkgLength(const unsigned int len,const unsigned int minlen=1); + ACPIAMLWriter &Name(const char *name); + ACPIAMLWriter &MultiNameOp(void); + ACPIAMLWriter &DualNameOp(void); + ACPIAMLWriter &BeginPkg(const unsigned int pred_length=MaxPkgSize); + ACPIAMLWriter &EndPkg(void); + ACPIAMLWriter &CountElement(void); + private: + unsigned char* w=NULL,*f=NULL; + unsigned char* buffer_len_pl = NULL; + unsigned char* rt_start = NULL; +}; + +/* StoreOp Operand Supername: Store Operand into Supername */ +ACPIAMLWriter &ACPIAMLWriter::StoreOp(void) { + *w++ = 0x70; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::LocalOp(const unsigned int l) { + if (l <= 7) + *w++ = 0x60 + l; /* 0x60..0x67 -> Local0..Local7 */ + else + E_Exit("ACPI AML writer LocalOp out of range"); + + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::ArgOp(const unsigned int arg) { + if (arg <= 6) + *w++ = 0x68 + arg; /* 0x68..0x6E -> Arg0..Arg6 */ + else + E_Exit("ACPI AML writer ArgOp out of range"); + + return *this; +} + +/* Binary operators like And and Xor are Operand1 Operand2 Target, and the return value + * of the operator is the result. What the ACPI specification is very unclear about, but + * hints at from a sample bit of ASL concerning PowerResource(), is that if you just + * want to evaluate the operator and do not care to store the result anywhere you can just + * set Target to Zero. + * + * This example doesn't make sense unless you consider that this is how you encode "Nothing" + * in the example on that page in spec 1.0b: + * + * Method(_STA) { + * Return (Xor (GIO.IDEI, One, Zero)) // inverse of isolation + * } + * + * See what they did there? */ +ACPIAMLWriter &ACPIAMLWriter::RootCharOp(void) { + *w++ = '\\'; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::RootCharScopeOp(void) { + RootCharOp(); /* this is how iasl encodes for example Scope(\) */ + ZeroOp(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::NothingOp(void) { + ZeroOp(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::ZeroOp(void) { + *w++ = 0x00; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::OneOp(void) { + *w++ = 0x01; + return *this; +} + +/* LEqual Operand1 Operand2 */ +ACPIAMLWriter &ACPIAMLWriter::LEqualOp(void) { + *w++ = 0x93; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::LNotOp(void) { + *w++ = 0x92; + return *this; +} + +/* LAndOp Operand1 Operand2 == Operand1 && Operand2 */ +ACPIAMLWriter &ACPIAMLWriter::LAndOp(void) { + *w++ = 0x90; + return *this; +} + +/* NAndOp Operand1 Operand2 Target -> Target = Operand1 & Operand2 */ +ACPIAMLWriter &ACPIAMLWriter::NAndOp(void) { + *w++ = 0x7C; + return *this; +} + +/* AndOp Operand1 Operand2 Target -> Target = Operand1 & Operand2 */ +ACPIAMLWriter &ACPIAMLWriter::AndOp(void) { + *w++ = 0x7B; + return *this; +} + +/* NOrOp Operand1 Operand2 Target -> Target = Operand1 & Operand2 */ +ACPIAMLWriter &ACPIAMLWriter::NOrOp(void) { + *w++ = 0x7E; + return *this; +} + +/* OrOp Operand1 Operand2 Target -> Target = Operand1 & Operand2 */ +ACPIAMLWriter &ACPIAMLWriter::OrOp(void) { + *w++ = 0x7D; + return *this; +} + +/* This makes sense if you think of an AML interpreter as something which encounters a LNotOp() + * and then runs the interpreter to parse the following token(s) to evaluate an int so it can + * do a logical NOT on the result of the evaluation. In other words this isn't like x86 assembly + * which you follow instruction by instruction but more like how you parse and evaluate expressions + * such as "4+5*3" properly. */ +ACPIAMLWriter &ACPIAMLWriter::LNotEqualOp(void) { + LNotOp(); + LEqualOp(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::BufferOp(const unsigned char *data,const size_t datalen) { + /* Notice this OP was obviously invented by the Department of Redundant Redundancy somewhere deep within Microsoft. + * This op stores both a PkgLength containing the overall buffer data and then the first bytes are a ByteOp encoding the length of the buffer. + * So basically it stores the length twice. What? Why? */ + *w++ = 0x11; + BeginPkg(datalen+8/*Byte/Word/DwordOp*/); + if (datalen >= 0x10000) DwordOp(datalen); + else if (datalen >= 0x100) WordOp(datalen); + else ByteOp(datalen); + if (datalen > 0) { + memcpy(w,data,datalen); + w += datalen; + } + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::BufferOp(const unsigned int pred_size) { + assert(pred_size >= 10); + *w++ = 0x11; + BeginPkg(pred_size); + DwordOp(0); // placeholder + buffer_len_pl = w - 4; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::BufferOpEnd(void) { + assert(buffer_len_pl != NULL); + host_writed(buffer_len_pl,size_t(w - (buffer_len_pl + 4))); + buffer_len_pl = NULL; + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::AliasOp(const char *what,const char *to_what) { + *w++ = 0x06; + Name(what); + Name(to_what); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::ReturnOp(void) { + *w++ = 0xA4; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::IfOp(const unsigned int pred_size) { + *w++ = 0xA0; + BeginPkg(pred_size); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::IfOpEnd(void) { + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::ElseOp(const unsigned int pred_size) { + *w++ = 0xA1; + BeginPkg(pred_size); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::ElseOpEnd(void) { + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtHdrLarge(const unsigned char itemName,const unsigned int length) { + assert(length <= 65536); + assert(itemName < 128); + *w++ = 0x80 + itemName; + host_writew(w,length); w += 2; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtHdrSmall(const unsigned char itemName,const unsigned int length) { + assert(length < 8); + assert(itemName < 16); + *w++ = (itemName << 3) + length; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtBegin(void) { + rt_start = w; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtEnd(void) { + rtHdrSmall(15/*end tag format*/,1/*length*/); + if (rt_start != NULL) { + unsigned char sum = 0; + for (unsigned char *s=rt_start;s < w;s++) sum += *s++; + *w++ = 0x100 - sum; + } + else { + *w++ = 0; + } + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtMemRange24(const unsigned int flags,const unsigned int minr,const unsigned int maxr,const unsigned int alignr,const unsigned int rangr) { + rtHdrLarge(1/*24-bit memory range format*/,9/*length*/); + *w++ = flags; + host_writew(w,minr >> 8u); w += 2; + host_writew(w,maxr >> 8u); w += 2; + host_writew(w,(alignr + 0xFFu) >> 8u); w += 2; /* FIXME: Um... alignment in bytes but everything else multiple of 256 bytes? */ + host_writew(w,rangr >> 8u); w += 2; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtMemRange32(const unsigned int flags,const unsigned int minr,const unsigned int maxr,const unsigned int alignr,const unsigned int rangr) { + rtHdrLarge(5/*32-bit memory range format*/,17/*length*/); + *w++ = flags; + host_writed(w,minr); w += 4; + host_writed(w,maxr); w += 4; + host_writed(w,alignr); w += 4; + host_writed(w,rangr); w += 4; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtDMA(const unsigned char bitmask,const unsigned char flags) { + rtHdrSmall(5/*DMA format*/,2/*length*/); + *w++ = bitmask; + *w++ = flags; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtIO(const unsigned int flags,const uint16_t minport,const uint16_t maxport,const uint8_t alignment,const uint8_t rlength) { + rtHdrSmall(8/*IO format*/,7/*length*/); + *w++ = (unsigned char)flags; + host_writew(w,minport); w += 2; + host_writew(w,maxport); w += 2; + *w++ = alignment; + *w++ = rlength; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::rtIRQ(const uint16_t bitmask,const bool pciStyle) { + rtHdrSmall(4/*IRQ format*/,3/*length*/); + host_writew(w,bitmask); w += 2; + *w++ = pciStyle ? 0x18/*active low level trigger shareable*/ : 0x01/*active high edge trigger*/; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::NameOp(const char *name) { + *w++ = 0x08; // NameOp + Name(name); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::Name(const char *name) { + for (unsigned int i=0;i < 4;i++) { + if (*name) *w++ = *name++; + else *w++ = '_'; + } + + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::MultiNameOp(void) { + *w++ = 0x2F; // MultiNamePrefix + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::DualNameOp() { + *w++ = 0x2E; // DualNamePrefix + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::ByteOp(const unsigned char v) { + *w++ = 0x0A; // ByteOp + *w++ = v; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::WordOp(const unsigned int v) { + *w++ = 0x0B; // WordOp + host_writew(w,v); w += 2; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::DwordOp(const unsigned long v) { + *w++ = 0x0C; // DwordOp + host_writed(w,v); w += 4; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::StringOp(const char *str) { + /* WARNING: Strings are only supposed to have ASCII 0x01-0x7F */ + *w++ = 0x0D; // StringOp + while (*str != 0) *w++ = *str++; + *w++ = 0x00; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::OpRegionOp(const char *name,const ACPIRegionSpace regionspace) { + *w++ = 0x5B; + *w++ = 0x80; + Name(name); + *w++ = (unsigned char)regionspace; + // and then the caller must write the RegionAddress and RegionLength + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::DeviceOp(const char *name,const unsigned int pred_size) { + *w++ = 0x5B; + *w++ = 0x82; + BeginPkg(pred_size); + Name(name); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::DeviceOpEnd(void) { + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::MethodOp(const char *name,const unsigned int pred_size,const unsigned int methodflags) { + *w++ = 0x14; + BeginPkg(pred_size); + Name(name); + *w++ = (unsigned char)methodflags; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::MethodOpEnd(void) { + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::FieldOp(const char *name,const unsigned int pred_size,const unsigned int fieldflag) { + *w++ = 0x5B; + *w++ = 0x81; + BeginPkg(pred_size); + Name(name); + *w++ = fieldflag; + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::FieldOpEnd(void) { + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::ScopeOp(const unsigned int pred_size) { + *w++ = 0x10; + BeginPkg(pred_size); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::ScopeOpEnd(void) { + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::PackageOp(const unsigned int pred_size) { + *w++ = 0x12; + BeginPkg(pred_size); + *w++ = 0x00; // placeholder for element count + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::PackageOpEnd(void) { + assert(!pkg_stack.empty()); + + pkg_t &ent = pkg_stack.top(); + + if (ent.element_count > 255u) E_Exit("ACPI AML writer too many elements in package"); + *ent.pkg_data = ent.element_count; /* element count follows PkgLength */ + + EndPkg(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::PkgLength(const unsigned int len,const unsigned int minlen) { + return PkgLength(len,w,minlen); +} + +ACPIAMLWriter &ACPIAMLWriter::PkgLength(const unsigned int len,unsigned char* &wp,const unsigned int minlen) { + if (len >= 0x10000000 || minlen > 4) { + E_Exit("ACPI AML writer PkgLength value too large"); + } + else if (len >= 0x100000 || minlen >= 4) { + *wp++ = (unsigned char)( len & 0x0F) | 0xC0; + *wp++ = (unsigned char)((len >> 4) & 0xFF); + *wp++ = (unsigned char)((len >> 12) & 0xFF); + *wp++ = (unsigned char)((len >> 20) & 0xFF); + } + else if (len >= 0x1000 || minlen >= 3) { + *wp++ = (unsigned char)( len & 0x0F) | 0x80; + *wp++ = (unsigned char)((len >> 4) & 0xFF); + *wp++ = (unsigned char)((len >> 12) & 0xFF); + } + else if (len >= 0x40 || minlen >= 2) { + *wp++ = (unsigned char)( len & 0x0F) | 0x40; + *wp++ = (unsigned char)((len >> 4) & 0xFF); + } + else { + *wp++ = (unsigned char)len; + } + + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::FieldOpElement(const char *name,const unsigned int bits) { + if (*name != 0) + Name(name); + else + *w++ = 0; + + PkgLength(bits); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::BeginPkg(const unsigned int /*pred_length*/) { + pkg_t ent; + + /* WARNING: Specify a size large enough. Once written, it cannot be extended if + * needed. By default, this code writes an overlarge field to make sure + * it can always update */ + + if (pkg_stack.size() >= 32) E_Exit("ACPI AML writer BeginPkg too much recursion"); + + ent.pkg_len = w; + PkgLength(MaxPkgSize);//placeholder + ent.pkg_data = w; + + pkg_stack.push(std::move(ent)); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::EndPkg(void) { + if (pkg_stack.empty()) E_Exit("ACPI AML writer EndPkg with empty stack"); + + pkg_t &ent = pkg_stack.top(); + + const unsigned long len = (unsigned long)(w - ent.pkg_len); + const unsigned int lflen = (unsigned int)(ent.pkg_data - ent.pkg_len); + PkgLength(len,ent.pkg_len,lflen); + if (ent.pkg_len != ent.pkg_data) E_Exit("ACPI AML writer length update exceeds pkglength field"); + pkg_stack.pop(); + return *this; +} + +ACPIAMLWriter &ACPIAMLWriter::CountElement(void) { + if (pkg_stack.empty()) E_Exit("ACPI AML writer counting elements not supported unless within package"); + pkg_stack.top().element_count++; + return *this; +} + +ACPIAMLWriter::ACPIAMLWriter() { +} + +ACPIAMLWriter::~ACPIAMLWriter() { +} + +unsigned char* ACPIAMLWriter::writeptr(void) const { + return w; +} + +void ACPIAMLWriter::begin(unsigned char *n_w,unsigned char *n_f) { + w = n_w; + f = n_f; +} + +void BuildACPITable(void) { + uint32_t rsdt_reserved = 16384; + unsigned char *w,*f; + unsigned int i,c; + + if (ACPI_buffer == NULL || ACPI_buffer_size < 32768) return; + w = ACPI_buffer; + f = ACPI_buffer+ACPI_buffer_size-rsdt_reserved; + + /* RSDT starts at last 16KB of ACPI buffer because it needs to build up a list of other tables */ + unsigned char *rsdt = f; + + /* RSD PTR is written to the legacy BIOS region, on a 16-byte boundary */ + Bitu rsdptr = ROMBIOS_GetMemory(20,"ACPI BIOS Root System Description Pointer",/*paragraph align*/16); + if (rsdptr == 0) E_Exit("ACPI BIOS RSD PTR alloc fail"); + LOG(LOG_MISC,LOG_DEBUG)("ACPI: RSD PTR at 0x%lx",(unsigned long)rsdptr); + + phys_writes(rsdptr + 0,"RSD PTR ",8); // Signature + phys_writeb(rsdptr + 8,0); // Checksum (fill in later) + phys_writes(rsdptr + 9,"DOSBOX",6); // OEMID + phys_writeb(rsdptr + 15,0); // Reserved must be zero + phys_writed(rsdptr + 16,acpiofs2phys( acpiptr2ofs( rsdt ) )); // RSDT physical address + c=0; for (i=0;i < 20;i++) c += phys_readb(rsdptr+i); + phys_writeb(rsdptr + 8,(0u - c)&0xFF); // Checksum + + /* RSDT */ + ACPISysDescTableWriter rsdt_tw; + rsdt_tw.begin(rsdt,ACPI_buffer+ACPI_buffer_size).setSig("RSDT").setRev(1); + unsigned int rsdt_tw_ofs = 36; + // leave open for adding one DWORD per table to the end as we go... this is why RSDT is written to the END of the ACPI region. + + /* FACP, which does not have a checksum and does not follow the normal format */ + unsigned char *facs = w; + size_t facs_size = 64; + w += facs_size; + { + assert(w <= f); + memset(facs,0,facs_size); + memcpy(facs+0x00,"FACS",4); + host_writed(facs+0x04,facs_size); + host_writed(facs+0x08,0x12345678UL); // hardware signature + host_writed(facs+0x0C,0); // firmware waking vector + ACPI_buffer_global_lock = acpiptr2ofs(facs+0x10); + host_writed(facs+0x10,0); // global lock + host_writed(facs+0x14,0); // S4BIOS_REQ not supported + LOG(LOG_MISC,LOG_DEBUG)("ACPI: FACS at 0x%lx len 0x%lx",(unsigned long)acpiofs2phys( acpiptr2ofs( facs ) ),(unsigned long)facs_size); + } + + unsigned char *dsdt_base = w; + { + ACPISysDescTableWriter dsdt; + ACPIAMLWriter aml; + + dsdt.begin(w,f).setSig("DSDT").setRev(1); + aml.begin(dsdt.getptr()+dsdt.get_tablesize(),f); + + /* WARNING: To simplify this code, you are responsible for writing the AML in the syntax required. + * See the ACPI BIOS specification for more details. + * + * For reference: + * + * Name := [LeadNameChar NameChar NameChar NameChar] | + * [LeadNameChar NameChar NameChar '_'] | + * [LeadNameChar NameChar '_' '_'] | + * [LeadNameChar '_' '_' '_'] + * + * DefName := NameOp Name DataTerm + * NameOp => 0x08 + * Data := DataTerm [DataTerm ...] + * DataTerm := DataItem | DefPackage + * DataItem := DefBuffer | DefNum | DefString + * + * How to write: ACPIAML1_NameOp(Name) followed by the necessary functions to write the buffer, string, etc. for the name. */ + aml.ScopeOp().RootCharScopeOp();/* Scope (\) */ + aml.OpRegionOp("DBG",ACPIRegionSpace::SystemIO).WordOp(ACPI_DEBUG_IO).ByteOp(0x10); + aml.FieldOp("DBG",ACPIAMLWriter::MaxPkgSize,ACPIFieldFlag::AccessType::DwordAcc|ACPIFieldFlag::UpdateRule::WriteAsZeros); + aml.FieldOpElement("DBGV",32); + aml.FieldOpEnd(); + aml.ScopeOpEnd(); /* } end of Scope(\) */ + + aml.ScopeOp().RootCharOp().Name("_SB"); + if (pcibus_enable) { + aml.DeviceOp("PCI0"); + aml.NameOp("_HID").DwordOp(ISAPNP_ID('P','N','P',0x00,0x0A,0x00,0x03)); + aml.NameOp("_ADR").DwordOp(0); /* [31:16] device [15:0] function */ + aml.NameOp("_UID").DwordOp(0xD05B0C5); + aml.NameOp("_CRS").BufferOp().rtBegin(); /* ResourceTemplate() i.e. resource list */ + aml.rtIO( + ACPIrtIO_16BitDecode, + 0x0CF8,/*min*/ + 0x0CF8,/*max*/ + 0x01,/*align*/ + 0x4/*number of I/O ports req*/); + aml.rtEnd(); + aml.BufferOpEnd(); + } + else { + aml.DeviceOp("ISA"); + aml.NameOp("_HID").DwordOp(ISAPNP_ID('P','N','P',0x00,0x0A,0x00,0x00)); + aml.NameOp("_ADR").DwordOp(0); /* [31:16] device [15:0] function */ + aml.NameOp("_UID").DwordOp(0xD05B0C5); + aml.DeviceOpEnd(); + + } + aml.ScopeOpEnd(); + + assert(aml.writeptr() >= (dsdt.getptr()+dsdt.get_tablesize())); + assert(aml.writeptr() <= f); + dsdt.expandto((size_t)(aml.writeptr() - dsdt.getptr())); + LOG(LOG_MISC,LOG_DEBUG)("ACPI: DSDT at 0x%lx len 0x%lx",(unsigned long)acpiofs2phys( acpiptr2ofs( dsdt_base ) ),(unsigned long)dsdt.get_tablesize()); + w = dsdt.finish(); + } + + { /* Fixed ACPI Description Table (FACP) */ + ACPISysDescTableWriter facp; + const PhysPt facp_offset = acpiofs2phys( acpiptr2ofs( w ) ); + + host_writed(rsdt_tw.getptr(rsdt_tw_ofs,4),(uint32_t)facp_offset); + rsdt_tw_ofs += 4; + + facp.begin(w,f,116).setSig("FACP").setRev(1); + host_writed(w+36,acpiofs2phys( acpiptr2ofs( facs ) ) ); // FIRMWARE_CTRL (FACS table) + host_writed(w+40,acpiofs2phys( acpiptr2ofs( dsdt_base ) ) ); // DSDT + w[44] = 0; // dual PIC PC-AT type implementation + host_writew(w+46,ACPI_IRQ); // SCI_INT + host_writed(w+48,ACPI_SMI_CMD); // SCI_CMD (I/O port) + w[52] = ACPI_ENABLE_CMD; // what the guest writes to SMI_CMD to disable SMI ownership from BIOS during bootup + w[53] = ACPI_DISABLE_CMD; // what the guest writes to SMI_CMD to re-enable SMI ownership to BIOS + // TODO: S4BIOS_REQ + host_writed(w+56,ACPI_PM1A_EVT_BLK); // PM1a_EVT_BLK event register block + host_writed(w+64,ACPI_PM1A_CNT_BLK); // PM1a_CNT_BLK control register block + host_writed(w+76,ACPI_PM_TMR_BLK); // PM_TMR_BLK power management timer control register block + w[88] = 4; // PM1_EVT_LEN + w[89] = 2; // PM1_CNT_LEN + w[90] = 0; // PM2_CNT_LEN + w[91] = 4; // PM_TM_LEN + host_writed(w+112,(1u << 0u)/*WBINVD*/); + LOG(LOG_MISC,LOG_DEBUG)("ACPI: FACP at 0x%lx len 0x%lx",(unsigned long)facp_offset,(unsigned long)facp.get_tablesize()); + w = facp.finish(); + } + + /* Finish RSDT */ + LOG(LOG_MISC,LOG_DEBUG)("ACPI: RDST at 0x%lx len 0x%lx",(unsigned long)acpiofs2phys( acpiptr2ofs( rsdt ) ),(unsigned long)rsdt_tw.get_tablesize()); + rsdt_tw.finish(); +} + +#if C_LIBPNG +# include "dosbox224x93.h" +# include "dosbox224x163.h" +# include "dosbox224x186.h" +# include "dosbox224x224.h" + +static const unsigned char *BIOSLOGO_PNG_PTR = NULL; +static const unsigned char *BIOSLOGO_PNG_FENCE = NULL; + +static void BIOSLOGO_PNG_READ(png_structp context,png_bytep buf,size_t count) { + (void)context; + + while (count > 0 && BIOSLOGO_PNG_PTR < BIOSLOGO_PNG_FENCE) { + *buf++ = *BIOSLOGO_PNG_PTR++; + count--; + } + while (count > 0) { + *buf++ = 0; + count--; + } +} + +#endif + +extern unsigned int INT13Xfer; + +class BIOS:public Module_base{ +private: + static Bitu cb_bios_post__func(void) { + void TIMER_BIOS_INIT_Configure(); +#if C_DEBUG + void DEBUG_CheckCSIP(); + +# if C_HEAVY_DEBUG + /* the game/app obviously crashed, which is way more important + * to log than what we do here in the BIOS at POST */ + void DEBUG_StopLog(void); + DEBUG_StopLog(); +# endif +#endif + + INT13_ElTorito_NoEmuDriveNumber = 0; + INT13_ElTorito_NoEmuCDROMDrive = 0; + INT13_ElTorito_IDEInterface = -1; + INT13Xfer = 0; + + ACPI_mem_enable(false); + ACPI_REGION_SIZE = 0; + ACPI_BASE = 0; + ACPI_enabled = false; + ACPI_version = 0; + ACPI_free(); + ACPI_SCI_EN = false; + ACPI_BM_RLD = false; + ACPI_PM1_Status = 0; + ACPI_PM1_Enable = 0; + + E280_table_entries = 0; + + {/*Conventional memory*/ + BIOS_E280_entry &ent = E280_table[E280_table_entries++]; + ent.base = 0x00000000; + ent.length = 0x9F000; /* 640KB minus the EBDA */ + ent.type = 1;/*Normal RAM*/ + } + {/*Conventional adapter ROM/RAM/BIOS*/ + BIOS_E280_entry &ent = E280_table[E280_table_entries++]; + ent.base = 0x000C0000; + ent.length = 0x40000; + ent.type = 2;/*Reserved*/ + } + if (MEM_TotalPages() > 0x100) { /* more than 1MB of RAM */ + BIOS_E280_entry &ent = E280_table[E280_table_entries++]; + ent.base = 0x00100000; + ent.length = (MEM_TotalPages()-0x100u)*4096u; + ent.type = 1;/*Normal RAM*/ + } + if (MEM_TotalPagesAt4GB() > 0) { /* anything above 4GB? */ + BIOS_E280_entry &ent = E280_table[E280_table_entries++]; + ent.base = uint64_t(0x100000000ull); + ent.length = uint64_t(MEM_TotalPagesAt4GB())*uint64_t(4096ul); + ent.type = 1;/*Normal RAM*/ + } + + /* If we're here because of a JMP to F000:FFF0 from a DOS program, then + * an actual reset is needed to prevent reentrancy problems with the DOS + * kernel shell. The WINNT.EXE install program for Windows NT/2000/XP + * likes to restart the program by JMPing to F000:FFF0 */ + if (!dos_kernel_disabled && first_shell != NULL) { + LOG(LOG_MISC,LOG_DEBUG)("BIOS POST: JMP to F000:FFF0 detected, initiating proper reset"); + throw int(9); + } + + { + Section_prop * section=static_cast(control->GetSection("dosbox")); + int val = section->Get_int("reboot delay"); + + if (val < 0) + val = IS_PC98_ARCH ? 1000 : 500; + + reset_post_delay = (unsigned int)val; + + /* Read the ACPI setting and decide on a ACPI region to use */ + { + std::string s = section->Get_string("acpi"); + + if (IS_PC98_ARCH) { + /* do not enable ACPI, PC-98 does not have it */ + } + else if (MEM_get_address_bits() < 32) { + /* I doubt any 486DX systems with less than 32 address bits has ACPI */ + } + else if (CPU_ArchitectureType < CPU_ARCHTYPE_386) { + /* Your 286 does not have ACPI and it never will. + * Your 386 as well, but the 386 is 32-bit and the user might change it to 486 or higher later though, so we'll allow that */ + } + else if (s == "1.0") { + ACPI_version = 0x100; + ACPI_REGION_SIZE = (256u << 10u); // 256KB + } + else if (s == "1.0b") { + ACPI_version = 0x10B; + ACPI_REGION_SIZE = (256u << 10u); // 256KB + } + } + + /* TODO: Read from dosbox.conf */ + if (ACPI_version != 0) { + ACPI_IRQ = 9; + ACPI_IO_BASE = 0x820; + ACPI_SMI_CMD = 0x828; + } + } + + if (bios_post_counter != 0 && reset_post_delay != 0) { + /* reboot delay, in case the guest OS/application had something to day before hitting the "reset" signal */ + uint32_t lasttick=GetTicks(); + while ((GetTicks()-lasttick) < reset_post_delay) { + void CALLBACK_IdleNoInts(void); + CALLBACK_IdleNoInts(); + } + } + + if (bios_post_counter != 0) { + /* turn off the PC speaker if the guest left it on at reset */ + if (IS_PC98_ARCH) { + IO_Write(0x37,0x07); + } + else { + IO_Write(0x61,IO_Read(0x61) & (~3u)); + } + } + + bios_post_counter++; + + if (bios_first_init) { + /* clear the first 1KB-32KB */ + for (uint16_t i=0x400;i<0x8000;i++) real_writeb(0x0,i,0); + } + + if (IS_PC98_ARCH) { + for (unsigned int i=0;i < callback_count;i++) callback[i].Uninstall(); + + /* clear out 0x50 segment (TODO: 0x40 too?) */ + for (unsigned int i=0;i < 0x100;i++) phys_writeb(0x500+i,0); + + BIOS_ZeroExtendedSize(false); + + if (call_pc98_default_stop == 0) + call_pc98_default_stop = CALLBACK_Allocate(); + + CALLBACK_Setup(call_pc98_default_stop,&pc98_default_stop_handler,CB_IRET,"INT 6h invalid opcode or STOP interrupt"); + + unsigned char memsize_real_code = 0; + Bitu mempages = MEM_TotalPages(); /* in 4KB pages */ + + /* NTS: Fill in the 3-bit code in FLAGS1 that represents + * how much lower conventional memory is in the system. + * + * Note that MEM.EXE requires this value, or else it + * will complain about broken UMB linkage and fail + * to show anything else. */ + /* TODO: In the event we eventually support "high resolution mode" + * we can indicate 768KB here, code == 5, meaning that + * the RAM extends up to 0xBFFFF instead of 0x9FFFF */ + if (mempages >= (640UL/4UL)) /* 640KB */ + memsize_real_code = 4; + else if (mempages >= (512UL/4UL)) /* 512KB */ + memsize_real_code = 3; + else if (mempages >= (384UL/4UL)) /* 384KB */ + memsize_real_code = 2; + else if (mempages >= (256UL/4UL)) /* 256KB */ + memsize_real_code = 1; + else /* 128KB */ + memsize_real_code = 0; + + void pc98_msw3_set_ramsize(const unsigned char b); + pc98_msw3_set_ramsize(memsize_real_code); + + /* CRT status */ + /* bit[7:6] = 00=conventional compatible 01=extended attr JEH 10=extended attr EGH + * bit[5:5] = Single event timer in use flag 1=busy 0=not used + * bit[4:4] = ? + * bit[3:3] = raster scan 1=non-interlaced 0=interlaced + * bit[2:2] = Content ruled line color 1=I/O set value 0=attributes of VRAM + * bit[1:1] = ? + * bit[0:0] = 480-line mode 1=640x480 0=640x400 or 640x200 */ + mem_writeb(0x459,0x08/*non-interlaced*/); + + /* Time stamper */ + /* bit[7:7] = 1=Port 5Fh exists 0=No such port Write to port 0x5F to wait 0.6us + * bit[6:6] = ? + * bit[5:5] = "Power" ? + * bit[4:4] = 1=PCMCIA BIOS running 0=not running + * bit[3:3] = ? + * bit[2:2] = 1=Time stamper (I/O ports 0x5C and 0x5E) available + * bit[1:1] = 1=Card I/O slot function 0=No card slot function + * bit[0:0] = 1=386SL(98) 0=Other */ + mem_writeb(0x45B,(pc98_timestamp5c?0x4:0x0)|0x80/*port 5Fh*/); + + /* CPU/Display */ + /* bit[7:7] = 486SX equivalent (?) 1=yes + * bit[6:6] = PC-9821 Extended Graph Architecture supported (FIXME: Is this the same as having EGC?) 1=yes + * bit[5:5] = LCD display is color 1=yes 0=no + * bit[4:4] = ? + * bit[3:3] = ROM drive allow writing + * bit[2:2] = 98 NOTE PC-9801N-08 expansion I/O box connected + * bit[1:1] = 98 NOTE prohibit transition to power saving mode + * bit[0:0] = 98 NOTE coprocessor function available */ + mem_writeb(0x45C,(enable_pc98_egc ? 0x40/*Extended Graphics*/ : 0x00)); + + /* CPU type in bits [1:0] */ + if (CPU_ArchitectureType >= CPU_ARCHTYPE_286) { + mem_writeb(0x480,CPU_ArchitectureType >= CPU_ARCHTYPE_386 ? 3 : 1); + } + + + /* Keyboard type */ + /* bit[7:7] = ? + * bit[6:6] = keyboard type bit 1 + * bit[5:5] = EMS page frame at B0000h 1=present 0=none + * bit[4:4] = EMS page frame at B0000h 1=page frame 0=G-VRAM + * bit[3:3] = keyboard type bit 0 + * bit[2:2] = High resolution memory window available + * bit[1:1] = ? + * bit[0:0] = ? + * + * keyboard bits[1:0] from bit 6 as bit 1 and bit 3 as bit 0 combined: + * 11 = new keyboard (NUM key, DIP switch 2-7 OFF) + * 10 = new keyboard (without NUM key) + * 01 = new keyboard (NUM key, DIP switch 2-7 ON) + * 00 = old keyboard + * + * The old keyboard is documented not to support software control of CAPS and KANA states */ + /* TODO: Make this a dosbox-x.conf option. Default is new keyboard without NUM key because that is + * what keyboard emulation currently acts like anyway. */ + mem_writeb(0x481,0x40/*bit 6=1 bit 3=0 new keyboard without NUM key*/); + + /* BIOS flags */ + /* bit[7:7] = Startup 1=hot start 0=cold start + * bit[6:6] = BASIC type ?? + * bit[5:5] = Keyboard beep 1=don't beep 0=beep ... when buffer full + * bit[4:4] = Expansion conv RAM 1=present 0=absent + * bit[3:3] = ?? + * bit[2:2] = ?? + * bit[1:1] = HD mode 1=1MB mode 0=640KB mode ... of the floppy drive + * bit[0:0] = Model 1=other 0=PC-9801 original */ + /* NTS: MS-DOS 5.0 appears to reduce it's BIOS calls and render the whole + * console as green IF bit 0 is clear. + * + * If bit 0 is set, INT 1Ah will be hooked by MS-DOS and, for some odd reason, + * MS-DOS's hook proc will call to our INT 1Ah + 0x19 bytes. */ + mem_writeb(0x500,0x01 | 0x02/*high density drive*/); + + /* BIOS flags */ + /* timer setup will set/clear bit 7 */ + /* bit[7:7] = system clock freq 1=8MHz 0=5/10Mhz + * = timer clock freq 1=1.9968MHz 0=2.4576MHz + * bit[6:6] = CPU 1=V30 0=Intel (8086 through Pentium) + * bit[5:5] = Model info 1=Other model 0=PC-9801 Muji, PC-98XA + * bit[4:4] = Model info ... + * bit[3:3] = Model info 1=High res 0=normal + * bit[2:0] = Realmode memsize + * 000=128KB 001=256KB + * 010=384KB 011=512KB + * 100=640KB 101=768KB + * + * Ref: http://hackipedia.org/browse/Computer/Platform/PC,%20NEC%20PC-98/Collections/Undocumented%209801,%209821%20Volume%202%20(webtech.co.jp)/memsys.txt */ + /* NTS: High resolution means 640x400, not the 1120x750 mode known as super high resolution mode. + * DOSBox-X does not yet emulate super high resolution nor does it emulate the 15khz 200-line "standard" mode. + * ref: https://github.com/joncampbell123/dosbox-x/issues/906#issuecomment-434513930 + * ref: https://jisho.org/search?utf8=%E2%9C%93&keyword=%E8%B6%85 */ + mem_writeb(0x501,0x20 | memsize_real_code); + + /* keyboard buffer */ + mem_writew(0x524/*tail*/,0x502); + mem_writew(0x526/*tail*/,0x502); + + /* number of scanlines per text row - 1 */ + mem_writeb(0x53B,0x0F); // CRT_RASTER, 640x400 24.83KHz-hsync 56.42Hz-vsync + + /* Text screen status. + * Note that most of the bits are used verbatim in INT 18h AH=0Ah/AH=0Bh */ + /* bit[7:7] = High resolution display 1=yes 0=no (standard) NOT super high res + * bit[6:6] = vsync 1=VSYNC wait 0=end of vsync handling + * bit[5:5] = unused + * bit[4:4] = Number of lines 1=30 lines 0=20/25 lines + * bit[3:3] = K-CG access mode 1=dot access 0=code access + * bit[2:2] = Attribute mode (how to handle bit 4) 1=Simp. graphic 0=Vertical line + * bit[1:1] = Number of columns 1=40 cols 0=80 cols + * bit[0:0] = Number of lines 1=20/30 lines 0=25 lines */ + mem_writeb(0x53C,(true/*TODO*/ ? 0x80/*high res*/ : 0x00/*standard*/)); + + /* BIOS raster location */ + mem_writew(0x54A,0x1900); + + /* BIOS flags */ + /* bit[7:7] = Graphics display state 1=Visible 0=Blanked (hidden) + * bit[6:6] = CRT type 1=high res 0=standard NOT super high res + * bit[5:5] = Horizontal sync rate 1=31.47KHz 0=24.83KHz + * bit[4:4] = CRT line mode 1=480-line 0=400-line + * bit[3:3] = Number of user-defined characters 1=188+ 0=63 + * bit[2:2] = Extended graphics RAM (for 16-color) 1=present 0=absent + * bit[1:1] = Graphics Charger is present 1=present 0=absent + * bit[0:0] = DIP switch 1-8 at startup 1=ON 0=OFF (support GLIO 16-colors) */ + mem_writeb(0x54C,(true/*TODO*/ ? 0x40/*high res*/ : 0x00/*standard*/) | (enable_pc98_grcg ? 0x02 : 0x00) | (enable_pc98_16color ? 0x05 : 0x00) | (pc98_31khz_mode ? 0x20/*31khz*/ : 0x00/*24khz*/) | (enable_pc98_188usermod ? 0x08 : 0x00)); // PRXCRT, 16-color G-VRAM, GRCG + + /* BIOS flags */ + /* bit[7:7] = PC-9821 graphics mode (INT 18h AH=4Dh CH=01h/00h) 1=extend 0=normal + * bit[6:6] = Enhanced Graphics Charger (EGC) is present + * bit[5:5] = GDC at 5.0MHz at boot up (copy of DIP switch 2-8 at startup) 1=yes 0=no + * bit[4:4] = Always "flickerless" drawing mode + * bit[3:3] = Drawing mode with flicker + * bit[2:2] = GDC clock 1=5MHz 0=2.5MHz + * bit[1:0] = Drawing mode of the GDC + * 00 = REPLACE + * 01 = COMPLEMENT + * 10 = CLEAR + * 11 = SET */ + mem_writeb(0x54D, + (enable_pc98_egc ? 0x40 : 0x00) | + (gdc_5mhz_mode ? 0x20 : 0x00) | + (gdc_5mhz_mode ? 0x04 : 0x00)); // EGC + + /* BIOS flags */ + /* bit[7:7] = INT 18h AH=30h/31h support enabled + * bit[6:3] = 0 (unused) + * bit[2:2] = Enhanced Graphics Mode (EGC) supported + * bit[1:0] = Graphic resolution + * 00 = 640x200 upper half (2/8/16-color mode) + * 01 = 640x200 lower half (2/8/16-color mode) + * 10 = 640x400 (2/8/16/256-color mode) + * 11 = 640x480 256-color mode */ + mem_writeb(0x597,(enable_pc98_egc ? 0x04 : 0x00)/*EGC*/ | + (enable_pc98_egc ? 0x80 : 0x00)/*supports INT 18h AH=30h and AH=31h*/ | + 2/*640x400*/); + /* TODO: I would like to eventually add a dosbox-x.conf option that controls whether INT 18h AH=30h and 31h + * are enabled, so that retro-development can test code to see how it acts on a newer PC-9821 + * that supports it vs an older PC-9821 that doesn't. + * + * If the user doesn't set the option, then it is "auto" and determined by machine= PC-98 model and + * by another option in dosbox-x.conf that determines whether 31khz support is enabled. + * + * NOTED: Neko Project II determines INT 18h AH=30h availability by whether or not it was compiled + * with 31khz hsync support (SUPPORT_CRT31KHZ) */ + + /* Set up the translation table pointer, which is relative to segment 0xFD80 */ + mem_writew(0x522,(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800)); + mem_writew(0x5C6,(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800)); + mem_writew(0x5C8,0xFD80); + } + + if (bios_user_reset_vector_blob != 0 && !bios_user_reset_vector_blob_run) { + LOG_MSG("BIOS POST: Running user reset vector blob at 0x%lx",(unsigned long)bios_user_reset_vector_blob); + bios_user_reset_vector_blob_run = true; + + assert((bios_user_reset_vector_blob&0xF) == 0); /* must be page aligned */ + + SegSet16(cs,bios_user_reset_vector_blob>>4); + reg_eip = 0; + +#if C_DEBUG + /* help the debugger reflect the new instruction pointer */ + DEBUG_CheckCSIP(); +#endif + + return CBRET_NONE; + } + + if (cpu.pmode) E_Exit("BIOS error: POST function called while in protected/vm86 mode"); + + CPU_CLI(); + + /* we need A20 enabled for BIOS boot-up */ + void A20Gate_OverrideOn(Section *sec); + void MEM_A20_Enable(bool enabled); + A20Gate_OverrideOn(NULL); + MEM_A20_Enable(true); + + BIOS_OnResetComplete(NULL); + + adapter_scan_start = 0xC0000; + bios_has_exec_vga_bios = false; + LOG(LOG_MISC,LOG_DEBUG)("BIOS: executing POST routine"); + + if (ACPI_REGION_SIZE != 0 && !IS_PC98_ARCH) { + // place it just below the mirror of the BIOS at FFFF0000 + ACPI_BASE = 0xFFFF0000 - ACPI_REGION_SIZE; + + LOG(LOG_MISC,LOG_DEBUG)("ACPI: Setting up version %u.%02x at 0x%lx-0x%lx", + ACPI_version>>8,ACPI_version&0xFF, + (unsigned long)ACPI_BASE,(unsigned long)(ACPI_BASE+ACPI_REGION_SIZE-1lu)); + + ACPI_init(); + ACPI_enabled = true; + ACPI_mem_enable(true); + memset(ACPI_buffer,0,ACPI_buffer_size); + } + + // TODO: Anything we can test in the CPU here? + + // initialize registers + SegSet16(ds,0x0000); + SegSet16(es,0x0000); + SegSet16(fs,0x0000); + SegSet16(gs,0x0000); + SegSet16(ss,0x0000); + + { + Bitu sz = MEM_TotalPages(); + + /* The standard BIOS is said to put its stack (at least at OS boot time) 512 bytes past the end of the boot sector + * meaning that the boot sector loads to 0000:7C00 and the stack is set grow downward from 0000:8000 */ + + if (sz > 8) sz = 8; /* 4KB * 8 = 32KB = 0x8000 */ + sz *= 4096; + reg_esp = sz - 4; + reg_ebp = 0; + LOG(LOG_MISC,LOG_DEBUG)("BIOS: POST stack set to 0000:%04x",reg_esp); + } + + if (dosbox_int_iocallout != IO_Callout_t_none) { + IO_FreeCallout(dosbox_int_iocallout); + dosbox_int_iocallout = IO_Callout_t_none; + } + + if (isapnp_biosstruct_base != 0) { + ROMBIOS_FreeMemory(isapnp_biosstruct_base); + isapnp_biosstruct_base = 0; + } + + if (acpi_iocallout != IO_Callout_t_none) { + IO_FreeCallout(acpi_iocallout); + acpi_iocallout = IO_Callout_t_none; + } + + if (BOCHS_PORT_E9) { + delete BOCHS_PORT_E9; + BOCHS_PORT_E9=NULL; + } + if (ISAPNP_PNP_ADDRESS_PORT) { + delete ISAPNP_PNP_ADDRESS_PORT; + ISAPNP_PNP_ADDRESS_PORT=NULL; + } + if (ISAPNP_PNP_DATA_PORT) { + delete ISAPNP_PNP_DATA_PORT; + ISAPNP_PNP_DATA_PORT=NULL; + } + if (ISAPNP_PNP_READ_PORT) { + delete ISAPNP_PNP_READ_PORT; + ISAPNP_PNP_READ_PORT=NULL; + } + + if (bochs_port_e9) { + if (BOCHS_PORT_E9 == NULL) { + BOCHS_PORT_E9 = new IO_WriteHandleObject; + BOCHS_PORT_E9->Install(0xE9,bochs_port_e9_write,IO_MB); + } + LOG(LOG_MISC,LOG_DEBUG)("Bochs port E9h emulation is active"); + } + else { + if (BOCHS_PORT_E9 != NULL) { + delete BOCHS_PORT_E9; + BOCHS_PORT_E9 = NULL; + } + } + + extern Bitu call_default; + + if (IS_PC98_ARCH) { + /* INT 00h-FFh generic stub routine */ + /* NTS: MS-DOS on PC-98 will fill all yet-unused interrupt vectors with a stub. + * No vector is left at 0000:0000. On a related note, PC-98 games apparently + * like to call INT 33h (mouse functions) without first checking that the + * vector is non-null. */ + callback[18].Uninstall(); + callback[18].Install(&INTGEN_PC98_Handler,CB_IRET,"Int stub ???"); + for (unsigned int i=0x00;i < 0x100;i++) RealSetVec(i,callback[18].Get_RealPointer()); + + for (unsigned int i=0x00;i < 0x08;i++) + real_writed(0,i*4,CALLBACK_RealPointer(call_default)); + + // STOP interrupt or invalid opcode + real_writed(0,0x06*4,CALLBACK_RealPointer(call_pc98_default_stop)); + + // Magical Girl Pretty Sammy installer + // Installer enters an infinite loop if lower 8 bits of the segment portion of int 7 are 0 + real_writew(0, 7*4, real_readw(0, 7*4) - 0x10); + real_writew(0, 7*4+2, real_readw(0, 7*4+2) + 1); + } + else { + /* Clear the vector table */ + for (uint16_t i=0x70*4;i<0x400;i++) real_writeb(0x00,i,0); + + /* Only setup default handler for first part of interrupt table */ + for (uint16_t ct=0;ct<0x60;ct++) { + real_writed(0,ct*4,CALLBACK_RealPointer(call_default)); + } + for (uint16_t ct=0x68;ct<0x70;ct++) { + if(!IS_J3100 || ct != 0x6f) + real_writed(0,ct*4,CALLBACK_RealPointer(call_default)); + } + + // default handler for IRQ 2-7 + for (uint16_t ct=0x0A;ct <= 0x0F;ct++) + RealSetVec(ct,BIOS_DEFAULT_IRQ07_DEF_LOCATION); + } + + if (unhandled_irq_method == UNHANDLED_IRQ_COOPERATIVE_2ND) { + // PC-98 style: Master PIC ack with 0x20 for IRQ 0-7. + // For the slave PIC, ack with 0x20 on the slave, then only ack the master (cascade interrupt) + // if the ISR register on the slave indicates none are in service. + CALLBACK_Setup(call_irq07default,NULL,CB_IRET_EOI_PIC1,Real2Phys(BIOS_DEFAULT_IRQ07_DEF_LOCATION),"bios irq 0-7 default handler"); + CALLBACK_Setup(call_irq815default,Default_IRQ_Handler_Cooperative_Slave_Pic,CB_IRET,Real2Phys(BIOS_DEFAULT_IRQ815_DEF_LOCATION),"bios irq 8-15 default handler"); + } + else { + // IBM PC style: Master PIC ack with 0x20, slave PIC ack with 0x20, no checking + CALLBACK_Setup(call_irq07default,NULL,CB_IRET_EOI_PIC1,Real2Phys(BIOS_DEFAULT_IRQ07_DEF_LOCATION),"bios irq 0-7 default handler"); + CALLBACK_Setup(call_irq815default,NULL,CB_IRET_EOI_PIC2,Real2Phys(BIOS_DEFAULT_IRQ815_DEF_LOCATION),"bios irq 8-15 default handler"); + } + + if (IS_PC98_ARCH) { + BIOS_UnsetupKeyboard(); + BIOS_UnsetupDisks(); + + /* no such INT 4Bh */ + int4b_callback.Uninstall(); + + /* remove some IBM-style BIOS interrupts that don't exist on PC-98 */ + /* IRQ to INT arrangement + * + * IBM PC-98 IRQ + * -------------------------------- + * 0x08 0x08 0 + * 0x09 0x09 1 + * 0x0A CASCADE 0x0A 2 + * 0x0B 0x0B 3 + * 0x0C 0x0C 4 + * 0x0D 0x0D 5 + * 0x0E 0x0E 6 + * 0x0F 0x0F CASCADE 7 + * 0x70 0x10 8 + * 0x71 0x11 9 + * 0x72 0x12 10 + * 0x73 0x13 11 + * 0x74 0x14 12 + * 0x75 0x15 13 + * 0x76 0x16 14 + * 0x77 0x17 15 + * + * As part of the change the IRQ cascade emulation needs to change for PC-98 as well. + * IBM uses IRQ 2 for cascade. + * PC-98 uses IRQ 7 for cascade. */ + + void INT10_EnterPC98(Section *sec); + INT10_EnterPC98(NULL); /* INT 10h */ + + callback_pc98_lio.Uninstall(); + + callback_pc98_avspcm.Uninstall(); + + callback[1].Uninstall(); /* INT 11h */ + callback[2].Uninstall(); /* INT 12h */ + callback[3].Uninstall(); /* INT 14h */ + callback[4].Uninstall(); /* INT 15h */ + callback[5].Uninstall(); /* INT 17h */ + callback[6].Uninstall(); /* INT 1Ah */ + callback[7].Uninstall(); /* INT 1Ch */ + callback[10].Uninstall(); /* INT 19h */ + callback[11].Uninstall(); /* INT 76h: IDE IRQ 14 */ + callback[12].Uninstall(); /* INT 77h: IDE IRQ 15 */ + callback[15].Uninstall(); /* INT 18h: Enter BASIC */ + callback[19].Uninstall(); /* INT 1Bh */ + + /* IRQ 6 is nothing special */ + callback[13].Uninstall(); /* INT 0Eh: IDE IRQ 6 */ + callback[13].Install(NULL,CB_IRET_EOI_PIC1,"irq 6"); + + /* IRQ 8 is nothing special */ + callback[8].Uninstall(); + callback[8].Install(NULL,CB_IRET_EOI_PIC2,"irq 8"); + + /* IRQ 9 is nothing special */ + callback[9].Uninstall(); + callback[9].Install(NULL,CB_IRET_EOI_PIC2,"irq 9"); + + /* INT 18h keyboard and video display functions */ + callback[1].Install(&INT18_PC98_Handler,CB_INT16,"Int 18 keyboard and display"); + callback[1].Set_RealVec(0x18,/*reinstall*/true); + + /* INT 19h *STUB* */ + callback[2].Install(&INT19_PC98_Handler,CB_IRET,"Int 19 ???"); + callback[2].Set_RealVec(0x19,/*reinstall*/true); + + /* INT 1Ah *STUB* */ + callback[3].Install(&INT1A_PC98_Handler,CB_IRET,"Int 1A ???"); + callback[3].Set_RealVec(0x1A,/*reinstall*/true); + + /* MS-DOS 5.0 FIXUP: + * - For whatever reason, if we set bits in the BIOS data area that + * indicate we're NOT the original model of the PC-98, MS-DOS will + * hook our INT 1Ah and then call down to 0x19 bytes into our + * INT 1Ah procedure. If anyone can explain this, I'd like to hear it. --J.C. + * + * NTS: On real hardware, the BIOS appears to have an INT 1Ah, a bunch of NOPs, + * then at 0x19 bytes into the procedure, the actual handler. This is what + * MS-DOS is pointing at. + * + * But wait, there's more. + * + * MS-DOS calldown pushes DS and DX onto the stack (after the IRET frame) + * before JMPing into the BIOS. + * + * Apparently the function at INT 1Ah + 0x19 is expected to do this: + * + * + * POP DX + * POP DS + * IRET + * + * I can only imaging what a headache this might have caused NEC when + * maintaining the platform and compatibility! */ + { + Bitu addr = callback[3].Get_RealPointer(); + addr = ((addr >> 16) << 4) + (addr & 0xFFFF); + + /* to make this work, we need to pop the two regs, then JMP to our + * callback and proceed as normal. */ + phys_writeb(addr + 0x19,0x5A); // POP DX + phys_writeb(addr + 0x1A,0x1F); // POP DS + phys_writeb(addr + 0x1B,0xEB); // jmp short ... + phys_writeb(addr + 0x1C,0x100 - 0x1D); + } + + /* INT 1Bh *STUB* */ + callback[4].Install(&INT1B_PC98_Handler,CB_IRET,"Int 1B ???"); + callback[4].Set_RealVec(0x1B,/*reinstall*/true); + + /* INT 1Ch *STUB* */ + callback[5].Install(&INT1C_PC98_Handler,CB_IRET,"Int 1C ???"); + callback[5].Set_RealVec(0x1C,/*reinstall*/true); + + /* INT 1Dh *STUB* */ + /* Place it in the PC-98 int vector area at FD80:0000 to satisfy some DOS games + * that detect PC-98 from the segment value of the vector (issue #927). + * Note that on real hardware (PC-9821) INT 1Dh appears to be a stub that IRETs immediately. */ + callback[6].Install(&INT1D_PC98_Handler,CB_IRET,"Int 1D ???"); +// callback[6].Set_RealVec(0x1D,/*reinstall*/true); + { + Bitu ofs = 0xFD813; /* 0xFD80:0013 try not to look like a phony address */ + unsigned int vec = 0x1D; + uint32_t target = callback[6].Get_RealPointer(); + + phys_writeb(ofs+0,0xEA); // JMP FAR + phys_writed(ofs+1,target); + + phys_writew((vec*4)+0,(ofs-0xFD800)); + phys_writew((vec*4)+2,0xFD80); + } + + /* INT 1Eh *STUB* */ + callback[7].Install(&INT1E_PC98_Handler,CB_IRET,"Int 1E ???"); + callback[7].Set_RealVec(0x1E,/*reinstall*/true); + + /* INT 1Fh *STUB* */ + callback[10].Install(&INT1F_PC98_Handler,CB_IRET,"Int 1F ???"); + callback[10].Set_RealVec(0x1F,/*reinstall*/true); + + /* INT DCh *STUB* */ + callback[16].Install(&INTDC_PC98_Handler,CB_IRET,"Int DC ???"); + callback[16].Set_RealVec(0xDC,/*reinstall*/true); + + /* INT F2h *STUB* */ + callback[17].Install(&INTF2_PC98_Handler,CB_IRET,"Int F2 ???"); + callback[17].Set_RealVec(0xF2,/*reinstall*/true); + + // default handler for IRQ 2-7 + for (uint16_t ct=0x0A;ct <= 0x0F;ct++) + RealSetVec(ct,BIOS_DEFAULT_IRQ07_DEF_LOCATION); + + // default handler for IRQ 8-15 + for (uint16_t ct=0;ct < 8;ct++) + RealSetVec(ct+(IS_PC98_ARCH ? 0x10 : 0x70),BIOS_DEFAULT_IRQ815_DEF_LOCATION); + + // LIO graphics interface (number of entry points, unknown WORD value and offset into the segment). + // For more information see Chapter 6 of this PDF [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] + { + callback_pc98_lio.Install(&PC98_BIOS_LIO,CB_IRET,"LIO graphics library"); + + Bitu ofs = 0xF990u << 4u; // F990:0000... + unsigned int entrypoints = 0x11; + Bitu final_addr = callback_pc98_lio.Get_RealPointer(); + + /* NTS: Based on GAME/MAZE 999 behavior, these numbers are interrupt vector numbers. + * The entry point marked 0xA0 is copied by the game to interrupt vector A0 and + * then called with INT A0h even though it blindly assumes the numbers are + * sequential from 0xA0-0xAF. */ + unsigned char entrypoint_indexes[0x11] = { + 0xA0, 0xA1, 0xA2, 0xA3, // +0x00 + 0xA4, 0xA5, 0xA6, 0xA7, // +0x04 + 0xA8, 0xA9, 0xAA, 0xAB, // +0x08 + 0xAC, 0xAD, 0xAE, 0xAF, // +0x0C + 0xCE // +0x10 + }; + + assert(((entrypoints * 4) + 4) <= 0x50); + assert((50 + (entrypoints * 7)) <= 0x100); // a 256-byte region is set aside for this! + + phys_writed(ofs+0,entrypoints); + for (unsigned int ent=0;ent < entrypoints;ent++) { + /* each entry point is "MOV AL, ; JMP FAR " */ + /* Yksoft1's patch suggests a segment offset of 0x50 which I'm OK with */ + unsigned int ins_ofs = ofs + 0x50 + (ent * 7); + + phys_writew(ofs+4+(ent*4)+0,entrypoint_indexes[ent]); + phys_writew(ofs+4+(ent*4)+2,ins_ofs - ofs); + + phys_writeb(ins_ofs+0,0xB0); // MOV AL,(entrypoint index) + phys_writeb(ins_ofs+1,entrypoint_indexes[ent]); + phys_writeb(ins_ofs+2,0xEA); // JMP FAR + phys_writed(ins_ofs+3,final_addr); + // total: ins_ofs+7 + } + } + + callback_pc98_avspcm.Install(&PC98_AVSDRV_PCM_Handler,CB_IRET,"AVSDRV.SYS PCM driver"); + callback_pc98_avspcm.Set_RealVec(0xd9, true); + } + + if (IS_PC98_ARCH) { + real_writew(0,0x58A,0x0000U); // countdown timer value + PIC_SetIRQMask(0,true); /* PC-98 keeps the timer off unless INT 1Ch is called to set a timer interval */ + } + + bool null_68h = false; + + { + Section_prop * section=static_cast(control->GetSection("dos")); + + null_68h = section->Get_bool("zero unused int 68h"); + } + + /* Default IRQ handler */ + if (call_irq_default == 0) + call_irq_default = CALLBACK_Allocate(); + CALLBACK_Setup(call_irq_default, &Default_IRQ_Handler, CB_IRET, "irq default"); + RealSetVec(0x0b, CALLBACK_RealPointer(call_irq_default)); // IRQ 3 + RealSetVec(0x0c, CALLBACK_RealPointer(call_irq_default)); // IRQ 4 + RealSetVec(0x0d, CALLBACK_RealPointer(call_irq_default)); // IRQ 5 + RealSetVec(0x0f, CALLBACK_RealPointer(call_irq_default)); // IRQ 7 + if (!IS_PC98_ARCH) { + RealSetVec(0x72, CALLBACK_RealPointer(call_irq_default)); // IRQ 10 + RealSetVec(0x73, CALLBACK_RealPointer(call_irq_default)); // IRQ 11 + } + + // setup a few interrupt handlers that point to bios IRETs by default + real_writed(0,0x66*4,CALLBACK_RealPointer(call_default)); //war2d + real_writed(0,0x67*4,CALLBACK_RealPointer(call_default)); + if (machine==MCH_CGA || null_68h) real_writed(0,0x68*4,0); //Popcorn + real_writed(0,0x5c*4,CALLBACK_RealPointer(call_default)); //Network stuff + //real_writed(0,0xf*4,0); some games don't like it + + bios_first_init = false; + + DispatchVMEvent(VM_EVENT_BIOS_INIT); + + TIMER_BIOS_INIT_Configure(); + + void INT10_Startup(Section *sec); + INT10_Startup(NULL); + + if (!IS_PC98_ARCH) { + extern uint8_t BIOS_tandy_D4_flag; + real_writeb(0x40,0xd4,BIOS_tandy_D4_flag); + } + + /* INT 13 Bios Disk Support */ + BIOS_SetupDisks(); + + /* INT 16 Keyboard handled in another file */ + BIOS_SetupKeyboard(); + + if (!IS_PC98_ARCH) { + int4b_callback.Set_RealVec(0x4B,/*reinstall*/true); + callback[1].Set_RealVec(0x11,/*reinstall*/true); + callback[2].Set_RealVec(0x12,/*reinstall*/true); + callback[3].Set_RealVec(0x14,/*reinstall*/true); + callback[4].Set_RealVec(0x15,/*reinstall*/true); + callback[5].Set_RealVec(0x17,/*reinstall*/true); + callback[6].Set_RealVec(0x1A,/*reinstall*/true); + callback[7].Set_RealVec(0x1C,/*reinstall*/true); + callback[8].Set_RealVec(0x70,/*reinstall*/true); + callback[9].Set_RealVec(0x71,/*reinstall*/true); + callback[10].Set_RealVec(0x19,/*reinstall*/true); + callback[11].Set_RealVec(0x76,/*reinstall*/true); + callback[12].Set_RealVec(0x77,/*reinstall*/true); + callback[13].Set_RealVec(0x0E,/*reinstall*/true); + callback[15].Set_RealVec(0x18,/*reinstall*/true); + callback[19].Set_RealVec(0x1B,/*reinstall*/true); + } + + // FIXME: We're using IBM PC memory size storage even in PC-98 mode. + // This cannot be removed, because the DOS kernel uses this variable even in PC-98 mode. + mem_writew(BIOS_MEMORY_SIZE,t_conv); + // According to Ripsaw, Tandy systems hold the real memory size in a normally reserved field [https://www.vogons.org/viewtopic.php?p=948898#p948898] + // According to the PCjr hardware reference library that memory location means the same thing + if (machine == MCH_PCJR || machine == MCH_TANDY) mem_writew(BIOS_MEMORY_SIZE+2,t_conv_real); + + RealSetVec(0x08,BIOS_DEFAULT_IRQ0_LOCATION); + // pseudocode for CB_IRQ0: + // sti + // callback INT8_Handler + // push ds,ax,dx + // int 0x1c + // cli + // mov al, 0x20 + // out 0x20, al + // pop dx,ax,ds + // iret + + if (!IS_PC98_ARCH) { + mem_writed(BIOS_TIMER,0); //Calculate the correct time + + // INT 05h: Print Screen + // IRQ1 handler calls it when PrtSc key is pressed; does nothing unless hooked + phys_writeb(Real2Phys(BIOS_DEFAULT_INT5_LOCATION), 0xcf); + RealSetVec(0x05, BIOS_DEFAULT_INT5_LOCATION); + + phys_writew(Real2Phys(RealGetVec(0x12))+0x12,0x20); //Hack for Jurresic + } + + phys_writeb(Real2Phys(BIOS_DEFAULT_HANDLER_LOCATION),0xcf); /* bios default interrupt vector location -> IRET */ + + if (!IS_PC98_ARCH) { + // tandy DAC setup + bool use_tandyDAC=(real_readb(0x40,0xd4)==0xff); + + tandy_sb.port=0; + tandy_dac.port=0; + if (use_tandyDAC) { + /* tandy DAC sound requested, see if soundblaster device is available */ + Bitu tandy_dac_type = 0; + if (Tandy_InitializeSB()) { + tandy_dac_type = 1; + } else if (Tandy_InitializeTS()) { + tandy_dac_type = 2; + } + if (tandy_dac_type) { + real_writew(0x40,0xd0,0x0000); + real_writew(0x40,0xd2,0x0000); + real_writeb(0x40,0xd4,0xff); /* tandy DAC init value */ + real_writed(0x40,0xd6,0x00000000); + /* install the DAC callback handler */ + tandy_DAC_callback[0]=new CALLBACK_HandlerObject(); + tandy_DAC_callback[1]=new CALLBACK_HandlerObject(); + tandy_DAC_callback[0]->Install(&IRQ_TandyDAC,CB_IRET,"Tandy DAC IRQ"); + tandy_DAC_callback[1]->Install(NULL,CB_TDE_IRET,"Tandy DAC end transfer"); + // pseudocode for CB_TDE_IRET: + // push ax + // mov ax, 0x91fb + // int 15 + // cli + // mov al, 0x20 + // out 0x20, al + // pop ax + // iret + + uint8_t tandy_irq = 7; + if (tandy_dac_type==1) tandy_irq = tandy_sb.irq; + else if (tandy_dac_type==2) tandy_irq = tandy_dac.irq; + uint8_t tandy_irq_vector = tandy_irq; + if (tandy_irq_vector<8) tandy_irq_vector += 8; + else tandy_irq_vector += (0x70-8); + + RealPt current_irq=RealGetVec(tandy_irq_vector); + real_writed(0x40,0xd6,current_irq); + for (uint16_t i=0; i<0x10; i++) phys_writeb(PhysMake(0xf000,0xa084+i),0x80); + } else real_writeb(0x40,0xd4,0x00); + } + } + + if (!IS_PC98_ARCH) { + /* Setup some stuff in 0x40 bios segment */ + + // Disney workaround + // uint16_t disney_port = mem_readw(BIOS_ADDRESS_LPT1); + // port timeouts + // always 1 second even if the port does not exist + // BIOS_SetLPTPort(0, disney_port); + for(Bitu i = 1; i < 3; i++) BIOS_SetLPTPort(i, 0); + mem_writeb(BIOS_COM1_TIMEOUT,1); + mem_writeb(BIOS_COM2_TIMEOUT,1); + mem_writeb(BIOS_COM3_TIMEOUT,1); + mem_writeb(BIOS_COM4_TIMEOUT,1); + + void BIOS_Post_register_parports(); + BIOS_Post_register_parports(); + + void BIOS_Post_register_comports(); + BIOS_Post_register_comports(); + } + + if (!IS_PC98_ARCH) { + /* Setup equipment list */ + // look http://www.bioscentral.com/misc/bda.htm + + //uint16_t config=0x4400; //1 Floppy, 2 serial and 1 parallel + uint16_t config = 0x0; + + config |= bios_post_parport_count() << 14; + config |= bios_post_comport_count() << 9; + +#if (C_FPU) + //FPU + if (enable_fpu) + config|=0x2; +#endif + switch (machine) { + case MCH_MDA: + case MCH_HERC: + //Startup monochrome + config|=0x30; + break; + case EGAVGA_ARCH_CASE: + case MCH_CGA: + case MCH_MCGA: + case TANDY_ARCH_CASE: + case MCH_AMSTRAD: + //Startup 80x25 color + config|=0x20; + break; + default: + //EGA VGA + config|=0; + break; + } + + // PS2 mouse + if (KEYBOARD_Report_BIOS_PS2Mouse()) + config |= 0x04; + + // DMA *not* supported - Ancient Art of War CGA uses this to identify PCjr + if (machine==MCH_PCJR) config |= 0x100; + + // Several online sources say bit 0 indicates a floppy drive is installed. + // Testing of a couple BIOSes from 1992 and 1993 showed bit 0 to always be 1, + // even with no floppy drives installed or configured in the BIOS. + // Maybe 0 is possible in older BIOSes. + config |= 0x01; + + // Bit 6 is 1 if there are 2 floppies connected and configured in the BIOS. + // Setting to 1 since DOSBox-X can mount floppy images in both drives A and B. + config |= 0x40; + + // Bit 12 is "game I/O attached" for PCJr, Tandy and PC/XT, and 0 (not used) for PC/AT + if ((CPU_ArchitectureType == CPU_ARCHTYPE_8086) && (joytype != JOY_NONE)) + config |= 0x1000; + + mem_writew(BIOS_CONFIGURATION,config); + if (IS_EGAVGA_ARCH) config &= ~0x30; //EGA/VGA startup display mode differs in CMOS + CMOS_SetRegister(0x14,(uint8_t)(config&0xff)); //Should be updated on changes + } + + if (!IS_PC98_ARCH) { + /* Setup extended memory size */ + IO_Write(0x70,0x30); + size_extended=IO_Read(0x71); + IO_Write(0x70,0x31); + size_extended|=(IO_Read(0x71) << 8); + + uint32_t value = 0; + + RtcUpdateDone(); + IO_Write(0x70,0xB); + IO_Write(0x71,0x02); // BCD + + /* set BIOS_TIMER according to time/date of RTC */ + IO_Write(0x70,0); + const unsigned char sec = BCD2BIN(IO_Read(0x71)); + IO_Write(0x70,2); + const unsigned char min = BCD2BIN(IO_Read(0x71)); + IO_Write(0x70,4); + const unsigned char hour = BCD2BIN(IO_Read(0x71)); + + value = (uint32_t)(((hour * 3600.00) + (min * 60.00) + sec) * ((double)PIT_TICK_RATE/65536.0)); + + mem_writed(BIOS_TIMER,value); + } + else { + /* Provide a valid memory size anyway */ + size_extended=MEM_TotalPages()*4; + if (size_extended >= 1024) size_extended -= 1024; + else size_extended = 0; + } + + /* PS/2 mouse */ + void BIOS_PS2Mouse_Startup(Section *sec); + BIOS_PS2Mouse_Startup(NULL); + + if (!IS_PC98_ARCH) { + /* this belongs HERE not on-demand from INT 15h! */ + biosConfigSeg = ROMBIOS_GetMemory(16/*one paragraph*/,"BIOS configuration (INT 15h AH=0xC0)",/*paragraph align*/16)>>4; + if (biosConfigSeg != 0) { + PhysPt data = PhysMake(biosConfigSeg,0); + phys_writew(data,8); // 8 Bytes following + if (IS_TANDY_ARCH) { + if (machine==MCH_TANDY) { + // Model ID (Tandy) + phys_writeb(data+2,0xFF); + } else { + // Model ID (PCJR) + phys_writeb(data+2,0xFD); + } + phys_writeb(data+3,0x0A); // Submodel ID + phys_writeb(data+4,0x10); // Bios Revision + /* Tandy doesn't have a 2nd PIC, left as is for now */ + phys_writeb(data+5,(1<<6)|(1<<5)|(1<<4)); // Feature Byte 1 + } else { + if (machine==MCH_MCGA) { + /* PC/2 model 30 model */ + phys_writeb(data+2,0xFA); + phys_writeb(data+3,0x00); // Submodel ID (PS/2) model 30 + } else if (PS1AudioCard) { /* FIXME: Won't work because BIOS_Init() comes before PS1SOUND_Init() */ + phys_writeb(data+2,0xFC); // Model ID (PC) + phys_writeb(data+3,0x0B); // Submodel ID (PS/1). + } else { + phys_writeb(data+2,0xFC); // Model ID (PC) + phys_writeb(data+3,0x00); // Submodel ID + } + phys_writeb(data+4,0x01); // Bios Revision + phys_writeb(data+5,(1<<6)|(1<<5)|(1<<4)); // Feature Byte 1 + } + phys_writeb(data+6,(1<<6)); // Feature Byte 2 + phys_writeb(data+7,0); // Feature Byte 3 + phys_writeb(data+8,0); // Feature Byte 4 + phys_writeb(data+9,0); // Feature Byte 5 + } + } + + // ISA Plug & Play I/O ports + if (!IS_PC98_ARCH && ISAPNPPORT) { + ISAPNP_PNP_ADDRESS_PORT = new IO_WriteHandleObject; + ISAPNP_PNP_ADDRESS_PORT->Install(0x279,isapnp_write_port,IO_MB); + ISAPNP_PNP_DATA_PORT = new IO_WriteHandleObject; + ISAPNP_PNP_DATA_PORT->Install(0xA79,isapnp_write_port,IO_MB); + ISAPNP_PNP_READ_PORT = new IO_ReadHandleObject; + ISAPNP_PNP_READ_PORT->Install(ISA_PNP_WPORT,isapnp_read_port,IO_MB); + LOG(LOG_MISC,LOG_DEBUG)("Registered ISA PnP read port at 0x%03x",ISA_PNP_WPORT); + } + + if (enable_integration_device) { + /* integration device callout */ + if (dosbox_int_iocallout == IO_Callout_t_none) + dosbox_int_iocallout = IO_AllocateCallout(IO_TYPE_MB); + if (dosbox_int_iocallout == IO_Callout_t_none) + E_Exit("Failed to get dosbox-x integration IO callout handle"); + + { + IO_CalloutObject *obj = IO_GetCallout(dosbox_int_iocallout); + if (obj == NULL) E_Exit("Failed to get dosbox-x integration IO callout"); + + /* NTS: Ports 28h-2Bh conflict with extended DMA control registers in PC-98 mode. + * TODO: Move again, if DB28h-DB2Bh are taken by something standard on PC-98. */ + obj->Install(IS_PC98_ARCH ? 0xDB28 : 0x28, + IOMASK_Combine(IOMASK_FULL,IOMASK_Range(4)),dosbox_integration_cb_port_r,dosbox_integration_cb_port_w); + IO_PutCallout(obj); + } + + /* DOSBox-X integration device */ + if (!IS_PC98_ARCH && isapnpigdevice == NULL && enable_integration_device_pnp) { + isapnpigdevice = new ISAPnPIntegrationDevice; + ISA_PNP_devreg(isapnpigdevice); + } + } + + // ISA Plug & Play BIOS entrypoint + // NTS: Apparently, Windows 95, 98, and ME will re-enumerate and re-install PnP devices if our entry point changes its address. + if (!IS_PC98_ARCH && ISAPNPBIOS) { + Bitu base; + unsigned int i; + unsigned char c,tmp[256]; + + isapnp_biosstruct_base = base = ROMBIOS_GetMemory(0x21,"ISA Plug & Play BIOS struct",/*paragraph alignment*/0x10); + + if (base == 0) E_Exit("Unable to allocate ISA PnP struct"); + LOG_MSG("ISA Plug & Play BIOS enabled"); + + call_pnp_r = CALLBACK_Allocate(); + call_pnp_rp = PNPentry_real = CALLBACK_RealPointer(call_pnp_r); + CALLBACK_Setup(call_pnp_r,ISAPNP_Handler_RM,CB_RETF,"ISA Plug & Play entry point (real)"); + //LOG_MSG("real entry pt=%08lx\n",PNPentry_real); + + call_pnp_p = CALLBACK_Allocate(); + call_pnp_pp = PNPentry_prot = CALLBACK_RealPointer(call_pnp_p); + CALLBACK_Setup(call_pnp_p,ISAPNP_Handler_PM,CB_RETF,"ISA Plug & Play entry point (protected)"); + //LOG_MSG("prot entry pt=%08lx\n",PNPentry_prot); + + phys_writeb(base+0,'$'); + phys_writeb(base+1,'P'); + phys_writeb(base+2,'n'); + phys_writeb(base+3,'P'); + phys_writeb(base+4,0x10); /* Version: 1.0 */ + phys_writeb(base+5,0x21); /* Length: 0x21 bytes */ + phys_writew(base+6,0x0000); /* Control field: Event notification not supported */ + /* skip checksum atm */ + phys_writed(base+9,0); /* Event notify flag addr: (none) */ + phys_writed(base+0xD,call_pnp_rp); /* Real-mode entry point */ + phys_writew(base+0x11,call_pnp_pp&0xFFFF); /* Protected mode offset */ + phys_writed(base+0x13,(call_pnp_pp >> 12) & 0xFFFF0); /* Protected mode code segment base */ + phys_writed(base+0x17,ISAPNP_ID('D','O','S',0,8,4,0)); /* OEM device identifier (DOSBox-X 0.84.x) */ + phys_writew(base+0x1B,0xF000); /* real-mode data segment */ + phys_writed(base+0x1D,0xF0000); /* protected mode data segment address */ + /* run checksum */ + c=0; + for (i=0;i < 0x21;i++) { + if (i != 8) c += phys_readb(base+i); + } + phys_writeb(base+8,0x100-c); /* checksum value: set so that summing bytes across the struct == 0 */ + + /* input device (keyboard) */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Keyboard,sizeof(ISAPNP_sysdev_Keyboard),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* input device (mouse) */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Mouse,sizeof(ISAPNP_sysdev_Mouse),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* DMA controller */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_DMA_Controller,sizeof(ISAPNP_sysdev_DMA_Controller),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* Interrupt controller */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PIC,sizeof(ISAPNP_sysdev_PIC),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* Timer */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Timer,sizeof(ISAPNP_sysdev_Timer),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* Realtime clock */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_RTC,sizeof(ISAPNP_sysdev_RTC),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* PC speaker */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PC_Speaker,sizeof(ISAPNP_sysdev_PC_Speaker),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* System board */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_System_Board,sizeof(ISAPNP_sysdev_System_Board),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* Motherboard PNP resources and general */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_General_ISAPNP,sizeof(ISAPNP_sysdev_General_ISAPNP),true)) + LOG_MSG("ISAPNP register failed\n"); + + /* ISA bus, meaning, a computer with ISA slots. + * The purpose of this device is to convince Windows 95 to automatically install it's + * "ISA Plug and Play bus" so that PnP devices are recognized automatically */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_ISA_BUS,sizeof(ISAPNP_sysdev_ISA_BUS),true)) + LOG_MSG("ISAPNP register failed\n"); + + if (pcibus_enable) { + /* PCI bus, meaning, a computer with PCI slots. + * The purpose of this device is to tell Windows 95 that a PCI bus is present. Without + * this entry, PCI devices will not be recognized until you manually install the PCI driver. */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PCI_BUS,sizeof(ISAPNP_sysdev_PCI_BUS),true)) + LOG_MSG("ISAPNP register failed\n"); + } + + /* APM BIOS device. To help Windows 95 see our APM BIOS. */ + if (APMBIOS && APMBIOS_pnp) { + LOG_MSG("Registering APM BIOS as ISA Plug & Play BIOS device node"); + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_APM_BIOS,sizeof(ISAPNP_sysdev_APM_BIOS),true)) + LOG_MSG("ISAPNP register failed\n"); + } + +#if (C_FPU) + /* Numeric Coprocessor */ + if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Numeric_Coprocessor,sizeof(ISAPNP_sysdev_Numeric_Coprocessor),true)) + LOG_MSG("ISAPNP register failed\n"); +#endif + + /* RAM resources. we have to construct it */ + /* NTS: We don't do this here, but I have an old Toshiba laptop who's PnP BIOS uses + * this device ID to report both RAM and ROM regions. */ + { + Bitu max = MEM_TotalPages() * 4096; + const unsigned char h1[9] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x1), /* PNP0C01 System device, motherboard resources */ + ISAPNP_TYPE(0x05,0x00,0x00), /* type: Memory, RAM, general */ + 0x0001 | 0x0002) + }; + + i = 0; + memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ + /*----------allocated--------*/ + tmp[i+0] = 0x80 | 6; /* 32-bit memory range */ + tmp[i+1] = 9; /* length=9 */ + tmp[i+2] = 0; + tmp[i+3] = 0x01; /* writeable, no cache, 8-bit, not shadowable, not ROM */ + host_writed(tmp+i+4,0x00000); /* base */ + host_writed(tmp+i+8,max > 0xA0000 ? 0xA0000 : 0x00000); /* length */ + i += 9+3; + + if (max > 0x100000) { + tmp[i+0] = 0x80 | 6; /* 32-bit memory range */ + tmp[i+1] = 9; /* length=9 */ + tmp[i+2] = 0; + tmp[i+3] = 0x01; + host_writed(tmp+i+4,0x100000); /* base */ + host_writed(tmp+i+8,max-0x100000); /* length */ + i += 9+3; + } + + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + /*-------------possible-----------*/ + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + /*-------------compatible---------*/ + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + + if (!ISAPNP_RegisterSysDev(tmp,i)) + LOG_MSG("ISAPNP register failed\n"); + } + + /* register parallel ports */ + for (Bitu portn=0;portn < 3;portn++) { + Bitu port = mem_readw(BIOS_ADDRESS_LPT1+(portn*2)); + if (port != 0) { + const unsigned char h1[9] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0x4,0x0,0x0), /* PNP0400 Standard LPT printer port */ + ISAPNP_TYPE(0x07,0x01,0x00), /* type: General parallel port */ + 0x0001 | 0x0002) + }; + + i = 0; + memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ + /*----------allocated--------*/ + tmp[i+0] = (8 << 3) | 7; /* IO resource */ + tmp[i+1] = 0x01; /* 16-bit decode */ + host_writew(tmp+i+2,port); /* min */ + host_writew(tmp+i+4,port); /* max */ + tmp[i+6] = 0x10; /* align */ + tmp[i+7] = 0x03; /* length */ + i += 7+1; + + /* TODO: If/when LPT emulation handles the IRQ, add IRQ resource here */ + + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + /*-------------possible-----------*/ + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + /*-------------compatible---------*/ + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + + if (!ISAPNP_RegisterSysDev(tmp,i)) + LOG_MSG("ISAPNP register failed\n"); + } + } + + void BIOS_Post_register_comports_PNP(); + BIOS_Post_register_comports_PNP(); + + void BIOS_Post_register_IDE(); + BIOS_Post_register_IDE(); + + void BIOS_Post_register_FDC(); + BIOS_Post_register_FDC(); + } + + if (IS_PC98_ARCH) { + /* initialize IRQ0 timer to default tick interval. + * PC-98 does not pre-initialize timer 0 of the PIT to 0xFFFF the way IBM PC/XT/AT do */ + PC98_Interval_Timer_Continue(); + PIC_SetIRQMask(0,true); /* PC-98 keeps the timer off unless INT 1Ch is called to set a timer interval */ + } + + if (!IS_PC98_ARCH) { + Section_prop * section=static_cast(control->GetSection("speaker")); + bool bit0en = section->Get_bool("pcspeaker clock gate enable at startup"); + + if (bit0en) { + uint8_t x = IO_Read(0x61); + IO_Write(0x61,(x & (~3u)) | 1u); /* set bits[1:0] = 01 (clock gate enable but output gate disable) */ + LOG_MSG("xxxx"); + } + } + + if (ACPI_enabled) { + if (acpi_iocallout == IO_Callout_t_none) + acpi_iocallout = IO_AllocateCallout(IO_TYPE_MB); + if (acpi_iocallout == IO_Callout_t_none) + E_Exit("Failed to get ACPI IO callout handle"); + + { + IO_CalloutObject *obj = IO_GetCallout(acpi_iocallout); + if (obj == NULL) E_Exit("Failed to get ACPI IO callout"); + obj->Install(ACPI_IO_BASE,IOMASK_Combine(IOMASK_FULL,IOMASK_Range(0x20)),acpi_cb_port_r,acpi_cb_port_w); + IO_PutCallout(obj); + } + + BuildACPITable(); + } + + CPU_STI(); + + return CBRET_NONE; + } + CALLBACK_HandlerObject cb_bios_scan_video_bios; + static Bitu cb_bios_scan_video_bios__func(void) { + unsigned long size; + + /* NTS: As far as I can tell, video is integrated into the PC-98 BIOS and there is no separate BIOS */ + if (IS_PC98_ARCH) return CBRET_NONE; + + if (cpu.pmode) E_Exit("BIOS error: VIDEO BIOS SCAN function called while in protected/vm86 mode"); + + if (!bios_has_exec_vga_bios) { + bios_has_exec_vga_bios = true; + if (IS_EGAVGA_ARCH) { + /* make sure VGA BIOS is there at 0xC000:0x0000 */ + if (AdapterROM_Read(0xC0000,&size)) { + LOG(LOG_MISC,LOG_DEBUG)("BIOS VIDEO ROM SCAN found VGA BIOS (size=%lu)",size); + adapter_scan_start = 0xC0000 + size; + + // step back into the callback instruction that triggered this call + reg_eip -= 4; + + // FAR CALL into the VGA BIOS + CPU_CALL(false,0xC000,0x0003,reg_eip); + return CBRET_NONE; + } + else { + LOG(LOG_MISC,LOG_WARN)("BIOS VIDEO ROM SCAN did not find VGA BIOS"); + } + } + else { + // CGA, MDA, Tandy, PCjr. No video BIOS to scan for + } + } + + return CBRET_NONE; + } + CALLBACK_HandlerObject cb_bios_adapter_rom_scan; + static Bitu cb_bios_adapter_rom_scan__func(void) { + unsigned long size; + uint32_t c1; + + /* FIXME: I have no documentation on how PC-98 scans for adapter ROM or even if it supports it */ + if (IS_PC98_ARCH) return CBRET_NONE; + + if (cpu.pmode) E_Exit("BIOS error: ADAPTER ROM function called while in protected/vm86 mode"); + + while (adapter_scan_start < 0xF0000) { + if (AdapterROM_Read(adapter_scan_start,&size)) { + uint16_t segm = (uint16_t)(adapter_scan_start >> 4); + + LOG(LOG_MISC,LOG_DEBUG)("BIOS ADAPTER ROM scan found ROM at 0x%lx (size=%lu)",(unsigned long)adapter_scan_start,size); + + c1 = mem_readd(adapter_scan_start+3); + adapter_scan_start += size; + if (c1 != 0UL) { + LOG(LOG_MISC,LOG_DEBUG)("Running ADAPTER ROM entry point"); + + // step back into the callback instruction that triggered this call + reg_eip -= 4; + + // FAR CALL into the VGA BIOS + CPU_CALL(false,segm,0x0003,reg_eip); + return CBRET_NONE; + } + else { + LOG(LOG_MISC,LOG_DEBUG)("FIXME: ADAPTER ROM entry point does not exist"); + } + } + else { + if (IS_EGAVGA_ARCH) // supposedly newer systems only scan on 2KB boundaries by standard? right? + adapter_scan_start = (adapter_scan_start | 2047UL) + 1UL; + else // while older PC/XT systems scanned on 512-byte boundaries? right? + adapter_scan_start = (adapter_scan_start | 511UL) + 1UL; + } + } + + LOG(LOG_MISC,LOG_DEBUG)("BIOS ADAPTER ROM scan complete"); + return CBRET_NONE; + } + CALLBACK_HandlerObject cb_bios_startup_screen; + static Bitu cb_bios_startup_screen__func(void) { + const Section_prop* section = static_cast(control->GetSection("dosbox")); + const char *logo_text = section->Get_string("logo text"); + const char *logo = section->Get_string("logo"); + bool fastbioslogo=section->Get_bool("fastbioslogo")||control->opt_fastbioslogo||control->opt_fastlaunch; + if (fastbioslogo && machine != MCH_PC98) { +#if defined(USE_TTF) + if (TTF_using()) { + uint32_t lasttick=GetTicks(); + while ((GetTicks()-lasttick)<500) { + reg_eax = 0x0100; + CALLBACK_RunRealInt(0x16); + } + reg_eax = 3; + CALLBACK_RunRealInt(0x10); + } +#endif + if (control->opt_fastlaunch) return CBRET_NONE; + } + extern const char* RunningProgram; + extern void GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused); + RunningProgram = "DOSBOX-X"; + GFX_SetTitle(-1,-1,-1,false); + const char *msg = "DOSBox-X (C) 2011-" COPYRIGHT_END_YEAR " The DOSBox-X Team\nDOSBox-X project maintainer: joncampbell123\nDOSBox-X project homepage: https://dosbox-x.com\nDOSBox-X user guide: https://dosbox-x.com/wiki\n\n"; + bool textsplash = section->Get_bool("disable graphical splash"); +#if defined(USE_TTF) + if (TTF_using()) { + textsplash = true; + if (ttf.cols != 80 || ttf.lins != 25) { + oldcols = ttf.cols; + oldlins = ttf.lins; + } else + oldcols = oldlins = 0; + } +#endif + + textsplash = true; + + char logostr[8][34]; + strcpy(logostr[0], "+---------------------+"); + strcpy(logostr[1], "| Welcome To |"); + strcpy(logostr[2], "| |"); + strcpy(logostr[3], "| D O S B o x - X ! |"); + strcpy(logostr[4], "| Bizhawk Edition |"); + sprintf(logostr[5],"| %d-bit %s |", + OS_BIT_INT, SDL_STRING); + sprintf(logostr[6], "| Version %10s |", VERSION); + strcpy(logostr[7], "+---------------------+"); +startfunction: + int logo_x,logo_y,x=2,y=2; + + logo_y = 2; + if (machine == MCH_HERC || machine == MCH_MDA) + logo_x = 80 - 2 - (224/9); + else + logo_x = 80 - 2 - (224/8); + + if (cpu.pmode) E_Exit("BIOS error: STARTUP function called while in protected/vm86 mode"); + + if (IS_VGA_ARCH) { + reg_eax = 18; // 640x480 16-color + CALLBACK_RunRealInt(0x10); + } + else if (machine == MCH_PC98) { + // clear the graphics layer + for (unsigned int i=0;i < (80*400);i++) { + mem_writeb(0xA8000+i,0); // B + mem_writeb(0xB0000+i,0); // G + mem_writeb(0xB8000+i,0); // R + mem_writeb(0xE0000+i,0); // E + } + + reg_eax = 0x0C00; // enable text layer (PC-98) + CALLBACK_RunRealInt(0x18); + + reg_eax = 0x1100; // show cursor (PC-98) + CALLBACK_RunRealInt(0x18); + + reg_eax = 0x1300; // set cursor pos (PC-98) + reg_edx = 0x0000; // byte position + CALLBACK_RunRealInt(0x18); + + bios_pc98_posx = x; + } + else { + reg_eax = 3; // 80x25 text + CALLBACK_RunRealInt(0x10); + } + +#if defined(USE_TTF) + if (TTF_using() && (ttf.cols != 80 || ttf.lins != 25)) ttf_setlines(80, 25); +#endif + + if (machine != MCH_PC98) { + reg_eax = 0x0200; // set cursor pos + reg_ebx = 0; // page zero + reg_dh = y; // row 4 + reg_dl = x; // column 20 + CALLBACK_RunRealInt(0x10); + } + + BIOS_Int10RightJustifiedPrint(x,y,msg); + +#if defined(C_LIBPNG) + { + png_bytep rows[1]; + unsigned char *row = NULL;/*png_width*/ + png_structp png_context = NULL; + png_infop png_info = NULL; + png_infop png_end = NULL; + png_uint_32 png_width = 0,png_height = 0; + int png_bit_depth = 0,png_color_type = 0,png_interlace = 0,png_filter = 0,png_compression = 0; + png_color *palette = NULL; + int palette_count = 0; + std::string user_filename; + unsigned int rowheight = 8; + const char *filename = NULL; + const unsigned char *inpng = NULL; + size_t inpng_size = 0; + FILE *png_fp = NULL; + + /* If the user wants a custom logo, just put it in the same directory as the .conf file and have at it. + * Requirements: The PNG must be 1/2/4/8bpp with a color palette, not grayscale, not truecolor, and + * no alpha channel data at all. No interlacing. Must be 224x224 or smaller, and should fit the size + * indicated in the filename. There are multiple versions, one for each vertical resolution of common + * CGA/EGA/VGA/etc. modes: 480-line, 400-line, 350-line, and 200-line. All images other than the 480-line + * one have a non-square pixel aspect ratio. Please take that into consideration. */ + if (IS_VGA_ARCH) { + if (logo) user_filename = std::string(logo) + "224x224.png"; + filename = "dosbox224x224.png"; + inpng_size = dosbox224x224_png_len; + inpng = dosbox224x224_png; + rowheight = 16; + } + else if (IS_PC98_ARCH || machine == MCH_MCGA) { + if (logo) user_filename = std::string(logo) + "224x186.png"; + filename = "dosbox224x186.png"; + inpng_size = dosbox224x186_png_len; + inpng = dosbox224x186_png; + rowheight = 16; + } + else if (IS_EGA_ARCH) { + if (ega200) { + if (logo) user_filename = std::string(logo) + "224x93.png"; + filename = "dosbox224x93.png"; + inpng_size = dosbox224x93_png_len; + inpng = dosbox224x93_png; + } + else { + if (logo) user_filename = std::string(logo) + "224x163.png"; + filename = "dosbox224x163.png"; + inpng_size = dosbox224x163_png_len; + inpng = dosbox224x163_png; + rowheight = 14; + } + } + else if (machine == MCH_HERC || machine == MCH_MDA) { + if (logo) user_filename = std::string(logo) + "224x163.png"; + filename = "dosbox224x163.png"; + inpng_size = dosbox224x163_png_len; + inpng = dosbox224x163_png; + rowheight = 14; + } + else { + if (logo) user_filename = std::string(logo) + "224x93.png"; + filename = "dosbox224x93.png"; + inpng_size = dosbox224x93_png_len; + inpng = dosbox224x93_png; + } + + if (png_fp == NULL && !user_filename.empty()) + png_fp = fopen(user_filename.c_str(),"rb"); + if (png_fp == NULL && filename != NULL) + png_fp = fopen(filename,"rb"); + + if (png_fp || inpng) { + png_context = png_create_read_struct(PNG_LIBPNG_VER_STRING,NULL/*err*/,NULL/*err fn*/,NULL/*warn fn*/); + if (png_context) { + png_info = png_create_info_struct(png_context); + if (png_info) { + png_set_user_limits(png_context,320,320); + } + } + } + + if (png_context && png_info) { + if (png_fp) { + LOG(LOG_MISC,LOG_DEBUG)("Using external file logo %s",filename); + png_init_io(png_context,png_fp); + } + else if (inpng) { + LOG(LOG_MISC,LOG_DEBUG)("Using built-in logo"); + BIOSLOGO_PNG_PTR = inpng; + BIOSLOGO_PNG_FENCE = inpng + inpng_size; + png_set_read_fn(png_context,NULL,BIOSLOGO_PNG_READ); + } + else { + abort(); /* should not be here */ + } + + png_read_info(png_context,png_info); + png_get_IHDR(png_context,png_info,&png_width,&png_height,&png_bit_depth,&png_color_type,&png_interlace,&png_compression,&png_filter); + + LOG(LOG_MISC,LOG_DEBUG)("BIOS png image: w=%u h=%u bitdepth=%u ct=%u il=%u compr=%u filt=%u", + png_width,png_height,png_bit_depth,png_color_type,png_interlace,png_compression,png_filter); + + if (png_width != 0 && png_height != 0 && png_bit_depth != 0 && png_bit_depth <= 8 && + (png_color_type&(PNG_COLOR_MASK_PALETTE|PNG_COLOR_MASK_COLOR)) == (PNG_COLOR_MASK_PALETTE|PNG_COLOR_MASK_COLOR)/*palatted color only*/ && + png_interlace == 0/*do not support interlacing*/) { + LOG(LOG_MISC,LOG_DEBUG)("PNG accepted"); + /* please convert everything to 8bpp for us */ + png_set_strip_16(png_context); + png_set_packing(png_context); + png_get_PLTE(png_context,png_info,&palette,&palette_count); + + row = new unsigned char[png_width + 32]; + rows[0] = row; + + if (palette != 0 && palette_count > 0 && palette_count <= 256 && row != NULL) { + textsplash = false; + if (machine == MCH_HERC || machine == MCH_MDA) + VGA_InitBiosLogo(png_width,png_height,logo_x*9,logo_y*rowheight); + else + VGA_InitBiosLogo(png_width,png_height,logo_x*8,logo_y*rowheight); + + { + unsigned char tmp[256*3]; + for (unsigned int x=0;x < (unsigned int)palette_count;x++) { + tmp[(x*3)+0] = palette[x].red; + tmp[(x*3)+1] = palette[x].green; + tmp[(x*3)+2] = palette[x].blue; + } + VGA_WriteBiosLogoPalette(0,palette_count,tmp); + } + + for (unsigned int y=0;y < png_height;y++) { + png_read_rows(png_context,rows,NULL,1); + VGA_WriteBiosLogoBMP(y,row,png_width); + } + VGA_ShowBIOSLogo(); + } + + delete[] row; + } + } + + if (png_context) png_destroy_read_struct(&png_context,&png_info,&png_end); + if (png_fp) fclose(png_fp); + } +#endif + + if (machine == MCH_PC98 && textsplash) { + unsigned int bo, lastline = 7; + for (unsigned int i=0; i<=lastline; i++) { + for (unsigned int j=0; j= ((uint64_t)128 << (uint64_t)20)) + sprintf(tmp,"%uMB memory installed\r\n",(unsigned int)(sz >> (uint64_t)20)); + else + sprintf(tmp,"%uKB memory installed\r\n",(unsigned int)(sz >> (uint64_t)10)); + + BIOS_Int10RightJustifiedPrint(x,y,tmp); + } + + const char *card = "Unknown Graphics Adapter"; + + switch (machine) { + case MCH_CGA: + card = "IBM Color Graphics Adapter"; + break; + case MCH_MCGA: + card = "IBM Multi Color Graphics Adapter"; + break; + case MCH_MDA: + card = "IBM Monochrome Display Adapter"; + break; + case MCH_HERC: + switch (hercCard) { + case HERC_GraphicsCardPlus: + card = "Hercules+ Graphics Adapter"; + break; + case HERC_InColor: + card = "Hercules InColor Graphics Adapter"; + break; + default: + card = "Hercules Graphics Adapter"; + break; + } + break; + case MCH_EGA: + card = "IBM Enhanced Graphics Adapter"; + break; + case MCH_PCJR: + card = "PCjr Graphics Adapter"; + break; + case MCH_TANDY: + card = "Tandy Graphics Adapter"; + break; + case MCH_VGA: + switch (svgaCard) { + case SVGA_TsengET4K: + card = "Tseng ET4000 SVGA"; + break; + case SVGA_TsengET3K: + card = "Tseng ET3000 SVGA"; + break; + case SVGA_ParadisePVGA1A: + card = "Paradise SVGA"; + break; + case SVGA_S3Trio: + card = "S3 Trio SVGA"; + switch (s3Card) { + case S3_86C928: card = "S3 86C928"; break; + case S3_Vision864: card = "S3 Vision864 SVGA"; break; + case S3_Vision868: card = "S3 Vision868 SVGA"; break; + case S3_Vision964: card = "S3 Vision964 SVGA"; break; + case S3_Vision968: card = "S3 Vision968 SVGA"; break; + case S3_Trio32: card = "S3 Trio32 SVGA"; break; + case S3_Trio64: card = "S3 Trio64 SVGA"; break; + case S3_Trio64V: card = "S3 Trio64V+ SVGA"; break; + case S3_ViRGE: card = "S3 ViRGE SVGA"; break; + case S3_ViRGEVX: card = "S3 ViRGE VX SVGA"; break; + case S3_Generic: card = "S3"; break; + } + break; + case SVGA_ATI: + card = "ATI SVGA"; + switch (atiCard) { + case ATI_EGAVGAWonder: card = "ATI EGA/VGA Wonder"; break; + case ATI_VGAWonder: card = "ATI VGA Wonder"; break; + case ATI_VGAWonderPlus: card = "ATI VGA Wonder+"; break; + case ATI_VGAWonderXL: card = "ATI VGA WonderXL"; break; + case ATI_VGAWonderXL24: card = "ATI VGA WonderXL24"; break; + case ATI_Mach8: card = "ATI Mach8"; break; + case ATI_Mach32: card = "ATI Mach32"; break; + case ATI_Mach64: card = "ATI Mach64"; break; + } + break; + default: + card = "Standard VGA"; + break; + } + + break; + case MCH_PC98: + card = "PC98 graphics"; + break; + case MCH_AMSTRAD: + card = "Amstrad graphics"; + break; + default: + abort(); // should not happen + } + + { + char tmp[512]; + sprintf(tmp,"Video card is %s\n",card); + BIOS_Int10RightJustifiedPrint(x,y,tmp); + } + + { + char tmp[512]; + const char *cpuType = "?"; + + switch (CPU_ArchitectureType) { + case CPU_ARCHTYPE_8086: + cpuType = "8086"; + break; + case CPU_ARCHTYPE_80186: + cpuType = "80186"; + break; + case CPU_ARCHTYPE_286: + cpuType = "286"; + break; + case CPU_ARCHTYPE_386: + cpuType = "386"; + break; + case CPU_ARCHTYPE_486OLD: + cpuType = "486 (older generation)"; + break; + case CPU_ARCHTYPE_486NEW: + cpuType = "486 (later generation)"; + break; + case CPU_ARCHTYPE_PENTIUM: + cpuType = "Pentium"; + break; + case CPU_ARCHTYPE_PMMXSLOW: + cpuType = "Pentium MMX"; + break; + case CPU_ARCHTYPE_PPROSLOW: + cpuType = "Pentium Pro"; + break; + case CPU_ARCHTYPE_PENTIUMII: + cpuType = "Pentium II"; + break; + case CPU_ARCHTYPE_PENTIUMIII: + cpuType = "Pentium III"; + break; + case CPU_ARCHTYPE_MIXED: + cpuType = "Auto (mixed)"; + break; + case CPU_ARCHTYPE_EXPERIMENTAL: + cpuType = "Experimental"; + break; + } + + sprintf(tmp,"%s CPU present",cpuType); + BIOS_Int10RightJustifiedPrint(x,y,tmp); + if (enable_fpu) BIOS_Int10RightJustifiedPrint(x,y," with FPU"); + BIOS_Int10RightJustifiedPrint(x,y,"\n"); + } + + if (APMBIOS) { + BIOS_Int10RightJustifiedPrint(x,y,"Advanced Power Management interface active\n"); + } + + if (ISAPNPBIOS) { + BIOS_Int10RightJustifiedPrint(x,y,"ISA Plug & Play BIOS active\n"); + } + + if (*logo_text) { + const size_t max_w = 76; + const char *s = logo_text; + const int saved_y = y; + size_t max_h; + char tmp[81]; + int x,y; + + x = 0; /* use it here as index to tmp[] */ + if (IS_VGA_ARCH) /* VGA 640x480 has 30 lines (480/16) not 25 */ + max_h = 30; + else + max_h = 25; + y = max_h - 3; + + y--; + BIOS_Int10RightJustifiedPrint(x+2,y,"\n"); /* sync cursor */ + + while (*s) { + bool newline = false; + + assert((size_t)x < max_w); + if (isalpha(*s) || isdigit(*s)) { + size_t wi = 1;/*we already know s[0] fits the criteria*/ + while (s[wi] != 0 && (isalpha(s[wi]) || isdigit(s[wi]))) wi++; + + if (wi >= 24) { /* don't let overlong words crowd out the text */ + if (((size_t)x+wi) > max_w) + wi = max_w - (size_t)x; + } + + if (((size_t)x+wi) < max_w) { + memcpy(tmp+x,s,wi); + x += wi; + s += wi; + } + else { + newline = true; + } + } + else if (*s == ' ') { + if ((size_t)x < max_w) tmp[x++] = *s++; + + if ((size_t)x == max_w) { + while (*s == ' ') s++; + newline = true; + } + } + else if (*s == '\\') { + s++; + if (*s == 'n') { + newline = true; /* \n */ + s++; + } + else { + s++; + } + } + else { + tmp[x++] = *s++; + } + + assert((size_t)x <= max_w); + if ((size_t)x >= max_w || newline) { + tmp[x] = 0; + BIOS_Int10RightJustifiedPrint(x+2,y,tmp); + x = 0; + BIOS_Int10RightJustifiedPrint(x+2,y,"\n"); /* next line, which increments y */ + if ((size_t)y >= max_h) break; + } + } + + if (x != 0 && (size_t)y < max_h) { + tmp[x] = 0; + BIOS_Int10RightJustifiedPrint(x+2,y,tmp); + x = 0; + BIOS_Int10RightJustifiedPrint(x+2,y,"\n"); /* next line, which increments y */ + } + + y = saved_y - 1; + BIOS_Int10RightJustifiedPrint(x+2,y,"\n"); /* sync cursor */ + } + +#if !defined(C_EMSCRIPTEN) + BIOS_Int10RightJustifiedPrint(x,y,"\nHit SPACEBAR to pause at this screen\n", false, true); + BIOS_Int10RightJustifiedPrint(x,y,"\nPress DEL to enter BIOS setup screen\n", false, true); + y--; /* next message should overprint */ + if (machine != MCH_PC98) { + reg_eax = 0x0200; // set cursor pos + reg_ebx = 0; // page zero + reg_dh = y; // row 4 + reg_dl = x; // column 20 + CALLBACK_RunRealInt(0x10); + } + else { + reg_eax = 0x1300u; // set cursor pos (PC-98) + reg_edx = (((unsigned int)y * 80u) + (unsigned int)x) * 2u; // byte position + CALLBACK_RunRealInt(0x18); + } +#endif + + // TODO: Then at this screen, we can print messages demonstrating the detection of + // IDE devices, floppy, ISA PnP initialization, anything of importance. + // I also envision adding the ability to hit DEL or F2 at this point to enter + // a "BIOS setup" screen where all DOSBox-X configuration options can be + // modified, with the same look and feel of an old BIOS. + +#if C_EMSCRIPTEN + uint32_t lasttick=GetTicks(); + while ((GetTicks()-lasttick)<1000) { + void CALLBACK_Idle(void); + CALLBACK_Idle(); + emscripten_sleep(100); + } +#else + if (!fastbioslogo&&!bootguest&&!bootfast&&(bootvm||!use_quick_reboot)) { + bool wait_for_user = false, bios_setup = false; + int pos=1; + uint32_t lasttick=GetTicks(); + while ((GetTicks()-lasttick)<1000) { + if (machine == MCH_PC98) { + reg_eax = 0x0100; // sense key + CALLBACK_RunRealInt(0x18); + SETFLAGBIT(ZF,reg_bh == 0); + } + else { + reg_eax = 0x0100; + CALLBACK_RunRealInt(0x16); + } + + if (!GETFLAG(ZF)) { + if (machine == MCH_PC98) { + reg_eax = 0x0000; // read key + CALLBACK_RunRealInt(0x18); + } + else { + reg_eax = 0x0000; + CALLBACK_RunRealInt(0x16); + } + + if (reg_al == 32) { // user hit space + BIOS_Int10RightJustifiedPrint(x,y,"Hit ENTER or ESC to continue \n", false, true); // overprint + BIOS_Int10RightJustifiedPrint(x,y,"\nPress DEL to enter BIOS setup screen\n", false, true); + wait_for_user = true; + break; + } + + if ((machine != MCH_PC98 && reg_ax == 0x5300) || (machine == MCH_PC98 && reg_ax == 0x3900)) { // user hit Del + bios_setup = true; + showBIOSSetup(card, x, y); + break; + } + } + } + + while (wait_for_user) { + if (machine == MCH_PC98) { + reg_eax = 0x0000; // read key + CALLBACK_RunRealInt(0x18); + } + else { + reg_eax = 0x0000; + CALLBACK_RunRealInt(0x16); + } + + if ((machine != MCH_PC98 && reg_ax == 0x5300/*DEL*/) || (machine == MCH_PC98 && reg_ax == 0x3900)) { + bios_setup = true; + VGA_FreeBiosLogo(); + showBIOSSetup(card, x, y); + break; + } + + if (reg_al == 27/*ESC*/ || reg_al == 13/*ENTER*/) + break; + } + + lasttick=GetTicks(); + bool askexit = false, mod = false; + while (bios_setup) { + if (GetTicks()-lasttick>=500 && !askexit) { + lasttick=GetTicks(); + updateDateTime(x,y,pos); + } + if (machine == MCH_PC98) { + reg_eax = 0x0100; // sense key + CALLBACK_RunRealInt(0x18); + SETFLAGBIT(ZF,reg_bh == 0); + } + else { + reg_eax = 0x0100; + CALLBACK_RunRealInt(0x16); + } + + if (!GETFLAG(ZF)) { + if (machine == MCH_PC98) { + reg_eax = 0x0000; // read key + CALLBACK_RunRealInt(0x18); + } + else { + reg_eax = 0x0000; + CALLBACK_RunRealInt(0x16); + } + if (askexit) { + if (reg_al == 'Y' || reg_al == 'y') { + if (machine == MCH_PC98) { + reg_eax = 0x1600; + reg_edx = 0xE100; + CALLBACK_RunRealInt(0x18); + } + goto startfunction; + } else if (machine == MCH_PC98) { + const char *exitstr = "ESC = Exit"; + unsigned int bo; + for (unsigned int i=0; i1?pos-1:6; + lasttick-=500; + } else if ((machine != MCH_PC98 && reg_ax == 0x4D00) || (machine == MCH_PC98 && reg_ax == 0x3C00)) { // Right key + pos=pos<6?pos+1:1; + lasttick-=500; + } else if (((machine != MCH_PC98 && reg_ax == 0x4800) || (machine == MCH_PC98 && reg_ax == 0x3A00)) && pos>3) { // Up key + if (pos==4||pos==5) pos=1; + else if (pos==6) pos=2; + lasttick-=500; + } else if (((machine != MCH_PC98 && reg_ax == 0x5000) || (machine == MCH_PC98 && reg_ax == 0x3D00)) && pos<4) { // Down key + if (pos==1) pos=4; + else if (pos==2||pos==3) pos=6; + lasttick-=500; + } else if (machine != MCH_PC98 && reg_al == 43) { // '+' key + if (pos==1&&dos.date.year<2100) dos.date.year++; + else if (pos==2) dos.date.month=dos.date.month<12?dos.date.month+1:1; + else if (pos==3) dos.date.day=dos.date.day<(dos.date.month==1||dos.date.month==3||dos.date.month==5||dos.date.month==7||dos.date.month==8||dos.date.month==10||dos.date.month==12?31:(dos.date.month==2?29:30))?dos.date.day+1:1; + else if (pos==4||pos==5||pos==6) { + Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; + unsigned int sec=(uint8_t)((Bitu)time % 60); + time/=60; + unsigned int min=(uint8_t)((Bitu)time % 60); + time/=60; + unsigned int hour=(uint8_t)((Bitu)time % 24); + if (pos==4) hour=hour<23?hour+1:0; + else if (pos==5) min=min<59?min+1:0; + else if (pos==6) sec=sec<59?sec+1:0; + mem_writed(BIOS_TIMER,(uint32_t)((double)hour*3600+min*60+sec)*18.206481481); + } + mod = true; + if (sync_time) {manualtime=true;mainMenu.get_item("sync_host_datetime").check(false).refresh_item(mainMenu);} + lasttick-=500; + } else if (machine != MCH_PC98 && reg_al == 45) { // '-' key + if (pos==1&&dos.date.year>1900) dos.date.year--; + else if (pos==2) dos.date.month=dos.date.month>1?dos.date.month-1:12; + else if (pos==3) dos.date.day=dos.date.day>1?dos.date.day-1:(dos.date.month==1||dos.date.month==3||dos.date.month==5||dos.date.month==7||dos.date.month==8||dos.date.month==10||dos.date.month==12?31:(dos.date.month==2?29:30)); + else if (pos==4||pos==5||pos==6) { + Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; + unsigned int sec=(uint8_t)(time % 60); + time/=60; + unsigned int min=(uint8_t)(time % 60); + time/=60; + unsigned int hour=(uint8_t)(time % 24); + if (pos==4) hour=hour>0?hour-1:23; + else if (pos==5) min=min>0?min-1:59; + else if (pos==6) sec=sec>0?sec-1:59; + mem_writed(BIOS_TIMER,(uint32_t)((double)hour*3600+min*60+sec)*18.206481481); + } + mod = true; + if (sync_time) {manualtime=true;mainMenu.get_item("sync_host_datetime").check(false).refresh_item(mainMenu);} + lasttick-=500; + } else if (reg_al == 27/*ESC*/) { + if (machine == MCH_PC98) { + const char *exitstr = "Exit[Y/N]?"; + unsigned int bo; + for (unsigned int i=0; i0 && oldlins>0) { + ttf_setlines(oldcols, oldlins); + oldcols = oldlins = 0; + } +#endif + + return CBRET_NONE; + } + CALLBACK_HandlerObject cb_bios_boot; + CALLBACK_HandlerObject cb_bios_bootfail; + CALLBACK_HandlerObject cb_pc98_rombasic; /* hardcoded entry point used by various PC-98 games that jump to N88 ROM BASIC */ + CALLBACK_HandlerObject cb_ibm_basic; /* hardcoded entry point used by MS-DOS 1.x BASIC.COM and BASICA.COM to jump to IBM ROM BASIC (F600:4C79) */ + static Bitu cb_pc98_entry__func(void) { + /* the purpose of this function is to say "N88 ROM BASIC NOT FOUND" */ + int x,y; + + x = y = 0; + + /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ + BIOS_Int10RightJustifiedPrint(x,y,"N88 ROM BASIC NOT IMPLEMENTED"); + + return CBRET_NONE; + } + static Bitu cb_ibm_basic_entry__func(void) { + /* the purpose of this function is to say "IBM ROM BASIC NOT FOUND" */ + int x,y; + + x = y = 0; + + /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ + BIOS_Int10RightJustifiedPrint(x,y,"IBM ROM BASIC NOT IMPLEMENTED"); + + return CBRET_NONE; + } + static Bitu cb_bios_bootfail__func(void) { + int x,y; + + x = y = 0; + + /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ + BIOS_Int10RightJustifiedPrint(x,y,"Guest OS failed to boot, returned failure"); + + /* and then after this call, there is a JMP $ to loop endlessly */ + return CBRET_NONE; + } + static Bitu cb_bios_boot__func(void) { + /* Reset/power-on overrides the user's A20 gate preferences. + * It's time to revert back to what the user wants. */ + void A20Gate_TakeUserSetting(Section *sec); + void MEM_A20_Enable(bool enabled); + A20Gate_TakeUserSetting(NULL); + MEM_A20_Enable(false); + + if (cpu.pmode) E_Exit("BIOS error: BOOT function called while in protected/vm86 mode"); + DispatchVMEvent(VM_EVENT_BIOS_BOOT); + + // TODO: If instructed to, follow the INT 19h boot pattern, perhaps follow the BIOS Boot Specification, etc. + + // TODO: If instructed to boot a guest OS... + + /* wipe out the stack so it's not there to interfere with the system, point it at top of memory or top of segment */ + reg_esp = std::min((unsigned int)((MEM_TotalPages() << 12) - 0x600 - 4),0xFFFCu); + reg_eip = 0; + CPU_SetSegGeneral(cs, 0x60); + CPU_SetSegGeneral(ss, 0x60); + + LOG(LOG_MISC,LOG_DEBUG)("BIOS boot SS:SP %04x:%04x",(unsigned int)0x60,(unsigned int)reg_esp); + + for (Bitu i=0;i < 0x400;i++) mem_writeb(0x7C00+i,0); + if ((bootguest||(!bootvm&&use_quick_reboot))&&!bootfast&&bootdrive>=0&&imageDiskList[bootdrive]) { + MOUSE_Startup(NULL); + char drive[] = "-QQ A:"; + drive[4]='A'+bootdrive; + runBoot(drive); + } + if (!bootguest&&!bootvm&&!bootfast&&bootdrive>=0) { + void IDE_CDROM_DetachAll(); + IDE_CDROM_DetachAll(); + } + if ((use_quick_reboot||IS_DOSV)&&!bootvm&&!bootfast&&bootdrive<0&&first_shell != NULL) throw int(6); + + bootvm=false; + bootfast=false; + bootguest=false; + bootdrive=-1; + // Begin booting the DOSBox-X shell. NOTE: VM_Boot_DOSBox_Kernel will change CS:IP instruction pointer! + if (!VM_Boot_DOSBox_Kernel()) E_Exit("BIOS error: BOOT function failed to boot DOSBox-X kernel"); + return CBRET_NONE; + } +public: + void write_FFFF_signature() { + /* write the signature at 0xF000:0xFFF0 */ + + // The farjump at the processor reset entry point (jumps to POST routine) + phys_writeb(0xffff0,0xEA); // FARJMP + phys_writew(0xffff1,RealOff(BIOS_DEFAULT_RESET_LOCATION)); // offset + phys_writew(0xffff3,RealSeg(BIOS_DEFAULT_RESET_LOCATION)); // segment + + // write system BIOS date + for(Bitu i = 0; i < strlen(bios_date_string); i++) phys_writeb(0xffff5+i,(uint8_t)bios_date_string[i]); + + /* model byte */ + if (machine==MCH_TANDY || machine==MCH_AMSTRAD) phys_writeb(0xffffe,0xff); /* Tandy model */ + else if (machine==MCH_PCJR) phys_writeb(0xffffe,0xfd); /* PCJr model */ + else if (machine==MCH_MCGA) phys_writeb(0xffffe,0xfa); /* PC/2 model 30 model */ + else phys_writeb(0xffffe,0xfc); /* PC (FIXME: This is listed as model byte PS/2 model 60) */ + + // signature + if (machine==MCH_TANDY) + phys_writeb(0xfffff,0xff); // Needed for Ninja (1986) + else + phys_writeb(0xfffff,0x55); + } + BIOS(Section* configuration):Module_base(configuration){ + isapnp_biosstruct_base = 0; + + { // TODO: Eventually, move this to BIOS POST or init phase + Section_prop * section=static_cast(control->GetSection("dosbox")); + Section_prop * pc98_section=static_cast(control->GetSection("pc98")); + + pc98_timestamp5c = pc98_section->Get_bool("pc-98 time stamp"); + + enable_pc98_copyright_string = pc98_section->Get_bool("pc-98 BIOS copyright string"); + + // NTS: This setting is also valid in PC-98 mode. According to Undocumented PC-98 by Webtech, + // there's nothing at I/O port E9h. I will move the I/O port in PC-98 mode if there is in + // fact a conflict. --J.C. + bochs_port_e9 = section->Get_bool("bochs debug port e9"); + + // TODO: motherboard init, especially when we get around to full Intel Triton/i440FX chipset emulation + { + std::string s = section->Get_string("isa memory hole at 512kb"); -Table [Programmable key setting data buffer structure] - (1) Key specification value 0000h - -------+--------------------+-------------------------------------- - Offset | Key type | Size of key setting data - -------+--------------------+-------------------------------------- - +0000h | [f・1] | 16 bytes (15 bytes of key setting data + 00h) - +0010h | [f・2] | 16 bytes (15 bytes of key setting data + 00h) - +0020h | [f・3] | 16 bytes (15 bytes of key setting data + 00h) - +0030h | [f・4] | 16 bytes (15 bytes of key setting data + 00h) - +0040h | [f・5] | 16 bytes (15 bytes of key setting data + 00h) - +0050h | [f・6] | 16 bytes (15 bytes of key setting data + 00h) - +0060h | [f・7] | 16 bytes (15 bytes of key setting data + 00h) - +0070h | [f・8] | 16 bytes (15 bytes of key setting data + 00h) - +0080h | [f・9] | 16 bytes (15 bytes of key setting data + 00h) - +0090h | [f・10] | 16 bytes (15 bytes of key setting data + 00h) - +00A0h | [SHIFT]+[f・1] | 16 bytes (15 bytes of key setting data + 00h) - +00B0h | [SHIFT]+[f・2] | 16 bytes (15 bytes of key setting data + 00h) - +00C0h | [SHIFT]+[f・3] | 16 bytes (15 bytes of key setting data + 00h) - +00D0h | [SHIFT]+[f・4] | 16 bytes (15 bytes of key setting data + 00h) - +00E0h | [SHIFT]+[f・5] | 16 bytes (15 bytes of key setting data + 00h) - +00F0h | [SHIFT]+[f・6] | 16 bytes (15 bytes of key setting data + 00h) - +0100h | [SHIFT]+[f・7] | 16 bytes (15 bytes of key setting data + 00h) - +0110h | [SHIFT]+[f・8] | 16 bytes (15 bytes of key setting data + 00h) - +0120h | [SHIFT]+[f・9] | 16 bytes (15 bytes of key setting data + 00h) - +0130h | [SHIFT]+[f・10] | 16 bytes (15 bytes of key setting data + 00h) - +0140h | [ROLL UP] | 6 bytes (5 bytes of key setting data + 00h) - +0146h | [ROLL DOWN] | 6 bytes (5 bytes of key setting data + 00h) - +014Ch | [INS] | 6 bytes (5 bytes of key setting data + 00h) - +0152h | [DEL] | 6 bytes (5 bytes of key setting data + 00h) - +0158h | [↑] | 6 bytes (5 bytes of key setting data + 00h) - +015Eh | [←] | 6 bytes (5 bytes of key setting data + 00h) - +0164h | [→] | 6 bytes (5 bytes of key setting data + 00h) - +016Ah | [↓] | 6 bytes (5 bytes of key setting data + 00h) - +0170h | [HOME/CLR] | 6 bytes (5 bytes of key setting data + 00h) - +0176h | [HELP] | 6 bytes (5 bytes of key setting data + 00h) - +017Ch | [SHIFT]+[HOME/CLR] | 6 bytes (5 bytes of key setting data + 00h) - -------+--------------------+-------------------------------------- -===============================================================================================*/ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - - /* function keys F1-F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_STORE_FUNCDEC(ofs,pc98_func_key[f]); - /* function keys Shift+F1 - Shift+F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[f]); - /* editor keys */ - for (unsigned int f=0;f < 11;f++,ofs += 6) - INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[f]); - - goto done; - } - else if (reg_ax >= 0x01 && reg_ax <= 0x0A) { /* Read individual function keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_STORE_FUNCDEC(ofs,pc98_func_key[reg_ax - 0x01]); - goto done; - } - else if (reg_ax >= 0x0B && reg_ax <= 0x14) { /* Read individual shift + function keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[reg_ax - 0x0B]); - goto done; - } - else if (reg_ax >= 0x15 && reg_ax <= 0x1F) { /* Read individual editor keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[reg_ax - 0x15]); - goto done; - } - else if (reg_ax >= 0x20 && reg_ax <= 0x24) { /* Read VF1-VF5 keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key[reg_ax - 0x20]); - goto done; - } - else if (reg_ax >= 0x25 && reg_ax <= 0x29) { /* Read shift VF1-VF5 keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_shortcut[reg_ax - 0x25]); - goto done; - } - else if (reg_ax >= 0x2A && reg_ax <= 0x33) { /* Read individual function keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_STORE_FUNCDEC(ofs,pc98_func_key_ctrl[reg_ax - 0x2A]); - goto done; - } - else if (reg_ax >= 0x34 && reg_ax <= 0x38) { /* Read control VF1-VF5 keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_ctrl[reg_ax - 0x34]); - goto done; - } - else if (reg_ax == 0xFF) { /* Extended version of the API when AX == 0, DS:DX = data to store to */ - /* DS:DX contains - * 16*10 bytes, 16 bytes per entry for function keys F1-F10 - * 16*5 bytes, 16 bytes per entry for VF1-VF5 - * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 - * 16*5 bytes, 16 bytes per entry for shift VF1-VF5 - * 6*11 bytes, 6 bytes per entry for editor keys - * 16*10 bytes, 16 bytes per entry for function key shortcuts Control+F1 to Control+F10 - * 16*5 bytes, 16 bytes per entry for control VF1-VF5 - * - * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - - /* function keys F1-F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_STORE_FUNCDEC(ofs,pc98_func_key[f]); - /* VF1-VF5 */ - for (unsigned int f=0;f < 5;f++,ofs += 16) - INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key[f]); - /* function keys Shift+F1 - Shift+F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_STORE_FUNCDEC(ofs,pc98_func_key_shortcut[f]); - /* VF1-VF5 */ - for (unsigned int f=0;f < 5;f++,ofs += 16) - INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_shortcut[f]); - /* editor keys */ - for (unsigned int f=0;f < 11;f++,ofs += 6) - INTDC_STORE_EDITDEC(ofs,pc98_editor_key_escapes[f]); - /* function keys Control+F1 - Control+F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_STORE_FUNCDEC(ofs,pc98_func_key_ctrl[f]); - /* VF1-VF5 */ - for (unsigned int f=0;f < 5;f++,ofs += 16) - INTDC_STORE_FUNCDEC(ofs,pc98_vfunc_key_ctrl[f]); - - goto done; - } - goto unknown; - case 0x0D: /* CL=0x0D General entry point to set function key state */ - if (reg_ax == 0xFF) { /* Extended version of the API when AX == 0, DS:DX = data to set */ - /* DS:DX contains - * 16*10 bytes, 16 bytes per entry for function keys F1-F10 - * 16*5 bytes, 16 bytes per entry for VF1-VF5 - * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 - * 16*5 bytes, 16 bytes per entry for shift VF1-VF5 - * 6*11 bytes, 6 bytes per entry for editor keys - * 16*10 bytes, 16 bytes per entry for function key shortcuts Control+F1 to Control+F10 - * 16*5 bytes, 16 bytes per entry for control VF1-VF5 - * - * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - - /* function keys F1-F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_LOAD_FUNCDEC(pc98_func_key[f],ofs); - /* VF1-VF5 */ - for (unsigned int f=0;f < 5;f++,ofs += 16) - INTDC_LOAD_FUNCDEC(pc98_vfunc_key[f],ofs); - /* function keys Shift+F1 - Shift+F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[f],ofs); - /* Shift+VF1 - Shift+VF5 */ - for (unsigned int f=0;f < 5;f++,ofs += 16) - INTDC_LOAD_FUNCDEC(pc98_vfunc_key_shortcut[f],ofs); - /* editor keys */ - for (unsigned int f=0;f < 11;f++,ofs += 6) - INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[f],ofs); - /* function keys Control+F1 - Control+F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_LOAD_FUNCDEC(pc98_func_key_ctrl[f],ofs); - /* Shift+VF1 - Shift+VF5 */ - for (unsigned int f=0;f < 5;f++,ofs += 16) - INTDC_LOAD_FUNCDEC(pc98_vfunc_key_ctrl[f],ofs); - - update_pc98_function_row(pc98_function_row_mode,true); - goto done; - } - else if (reg_ax >= 0x01 && reg_ax <= 0x0A) { /* Read individual function keys, DS:DX = data to set */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_LOAD_FUNCDEC(pc98_func_key[reg_ax - 0x01],ofs); - goto done; - } - else if (reg_ax >= 0x0B && reg_ax <= 0x14) { /* Read individual shift + function keys, DS:DX = data to set */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[reg_ax - 0x0B],ofs); - goto done; - } - else if (reg_ax >= 0x15 && reg_ax <= 0x1F) { /* Read individual editor keys, DS:DX = data to set */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[reg_ax - 0x15],ofs); - goto done; - } - else if (reg_ax >= 0x20 && reg_ax <= 0x24) { /* Read VF1-VF5 keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_LOAD_FUNCDEC(pc98_vfunc_key[reg_ax - 0x20],ofs); - goto done; - } - else if (reg_ax >= 0x25 && reg_ax <= 0x29) { /* Read shift VF1-VF5 keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_LOAD_FUNCDEC(pc98_vfunc_key_shortcut[reg_ax - 0x25],ofs); - goto done; - } - else if (reg_ax >= 0x2A && reg_ax <= 0x33) { /* Read individual function keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_LOAD_FUNCDEC(pc98_func_key_ctrl[reg_ax - 0x2A],ofs); - goto done; - } - else if (reg_ax >= 0x34 && reg_ax <= 0x38) { /* Read control VF1-VF5 keys, DS:DX = data to store to */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - INTDC_LOAD_FUNCDEC(pc98_vfunc_key_ctrl[reg_ax - 0x34],ofs); - goto done; - } - else if (reg_ax == 0x00) { /* Read all state, DS:DX = data to set */ - /* DS:DX contains - * 16*10 bytes, 16 bytes per entry for function keys F1-F10 - * 16*10 bytes, 16 bytes per entry for function key shortcuts Shift+F1 to Shift+F10 - * 6*11 bytes, 6 bytes per entry of editor keys (INS, DEL, etc) that match a specific scan code range - * - * For whatever reason, the buffer is copied to the DOS buffer +1, meaning that on write it skips the 0x08 byte. */ - Bitu ofs = (Bitu)(SegValue(ds) << 4ul) + (Bitu)reg_dx; - - /* function keys F1-F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_LOAD_FUNCDEC(pc98_func_key[f],ofs); - /* function keys Shift+F1 - Shift+F10 */ - for (unsigned int f=0;f < 10;f++,ofs += 16) - INTDC_LOAD_FUNCDEC(pc98_func_key_shortcut[f],ofs); - /* editor keys */ - for (unsigned int f=0;f < 11;f++,ofs += 6) - INTDC_LOAD_EDITDEC(pc98_editor_key_escapes[f],ofs); - - update_pc98_function_row(pc98_function_row_mode,true); - goto done; - } - goto unknown; - case 0x0F: - if (reg_ax == 0) { /* inhibit Control+Fn shortcuts */ - real_writeb(0x60,0x10C,real_readb(0x60,0x10C) | 0x01); - goto done; - } - else if (reg_ax == 1) { /* enable Control+Fn shortcuts */ - real_writeb(0x60,0x10C,real_readb(0x60,0x10C) & (~0x01)); - goto done; - } - goto unknown; - case 0x10: - if (reg_ah == 0x00) { /* CL=0x10 AH=0x00 DL=char write char to CON */ - PC98_INTDC_WriteChar(reg_dl); - goto done; - } - else if (reg_ah == 0x01) { /* CL=0x10 AH=0x01 DS:DX write string to CON */ - /* According to the example at http://tepe.tec.fukuoka-u.ac.jp/HP98/studfile/grth/gt10.pdf - * the string ends in '$' just like the main DOS string output function. */ - uint16_t ofs = reg_dx; - do { - unsigned char c = real_readb(SegValue(ds),ofs++); - if (c == '$') break; - PC98_INTDC_WriteChar(c); - } while (1); - goto done; - } - else if (reg_ah == 0x02) { /* CL=0x10 AH=0x02 DL=attribute set console output attribute */ - /* Ref: https://nas.jmc/jmcs/docs/browse/Computer/Platform/PC%2c%20NEC%20PC%2d98/Collections/Undocumented%209801%2c%209821%20Volume%202%20%28webtech.co.jp%29%20English%20translation/memdos%2eenglish%2dgoogle%2dtranslate%2etxt - * - * DL is the attribute byte (in the format written directly to video RAM, not the ANSI code) - * - * NTS: Reverse engineering INT DCh shows it sets both 71Dh and 73Ch as below */ - real_writeb(0x60,0x11D,reg_dl); - real_writeb(0x60,0x13C,reg_dx); - goto done; - } - else if (reg_ah == 0x03) { /* CL=0x10 AH=0x03 DL=X-coord DH=Y-coord set cursor position */ - void INTDC_CL10h_AH03h(uint16_t raw); - INTDC_CL10h_AH03h(reg_dx); - goto done; - } - else if (reg_ah == 0x04) { /* CL=0x10 AH=0x04 Move cursor down one line */ - void INTDC_CL10h_AH04h(void); - INTDC_CL10h_AH04h(); - goto done; - } - else if (reg_ah == 0x05) { /* CL=0x10 AH=0x05 Move cursor up one line */ - void INTDC_CL10h_AH05h(void); - INTDC_CL10h_AH05h(); - goto done; - } - else if (reg_ah == 0x06) { /* CL=0x10 AH=0x06 DX=count Move cursor up multiple lines */ - void INTDC_CL10h_AH06h(uint16_t count); - INTDC_CL10h_AH06h(reg_dx); - goto done; - } - else if (reg_ah == 0x07) { /* CL=0x10 AH=0x07 DX=count Move cursor down multiple lines */ - void INTDC_CL10h_AH07h(uint16_t count); - INTDC_CL10h_AH07h(reg_dx); - goto done; - } - else if (reg_ah == 0x08) { /* CL=0x10 AH=0x08 DX=count Move cursor right multiple lines */ - void INTDC_CL10h_AH08h(uint16_t count); - INTDC_CL10h_AH08h(reg_dx); - goto done; - } - else if (reg_ah == 0x09) { /* CL=0x10 AH=0x09 DX=count Move cursor left multiple lines */ - void INTDC_CL10h_AH09h(uint16_t count); - INTDC_CL10h_AH09h(reg_dx); - goto done; - } - else if (reg_ah == 0x0a) { /* CL=0x10 AH=0x0A DL=pattern Erase screen */ - void INTDC_CL10h_AH0Ah(uint16_t pattern); - INTDC_CL10h_AH0Ah(reg_dx); - goto done; - } - else if (reg_ah == 0x0b) { /* CL=0x10 AH=0x0B DL=pattern Erase lines */ - void INTDC_CL10h_AH0Bh(uint16_t pattern); - INTDC_CL10h_AH0Bh(reg_dx); - goto done; - } - else if (reg_ah == 0x0c) { /* CL=0x10 AH=0x0C DL=count Insert lines */ - void INTDC_CL10h_AH0Ch(uint16_t count); - INTDC_CL10h_AH0Ch(reg_dx); - goto done; - } - else if (reg_ah == 0x0d) { /* CL=0x10 AH=0x0D DL=count Erase lines */ - void INTDC_CL10h_AH0Dh(uint16_t count); - INTDC_CL10h_AH0Dh(reg_dx); - goto done; - } - else if (reg_ah == 0x0E) { /* CL=0x10 AH=0x0E DL=mode Change character mode */ - void pc98_set_char_mode(bool mode); - pc98_set_char_mode(reg_dl == 0); - goto done; - } - goto unknown; - default: /* some compilers don't like not having a default case */ - goto unknown; - } - -done: - return CBRET_NONE; - -unknown: - LOG_MSG("PC-98 INT DCh unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - - return CBRET_NONE; -} - -static Bitu INTF2_PC98_Handler(void) { - LOG_MSG("PC-98 INT F2h unknown call AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - - return CBRET_NONE; -} - -extern void lio_read_parameter(); -extern uint8_t PC98_BIOS_LIO_GINIT(); -extern uint8_t PC98_BIOS_LIO_GSCREEN(); -extern uint8_t PC98_BIOS_LIO_GVIEW(); -extern uint8_t PC98_BIOS_LIO_GCOLOR1(); -extern uint8_t PC98_BIOS_LIO_GCOLOR2(); -extern uint8_t PC98_BIOS_LIO_GCLS(); -extern uint8_t PC98_BIOS_LIO_GPSET(); -extern uint8_t PC98_BIOS_LIO_GLINE(); -extern uint8_t PC98_BIOS_LIO_GCIRCLE(); -extern uint8_t PC98_BIOS_LIO_GPAINT1(); -extern uint8_t PC98_BIOS_LIO_GPAINT2(); -extern uint8_t PC98_BIOS_LIO_GGET(); -extern uint8_t PC98_BIOS_LIO_GPUT1(); -extern uint8_t PC98_BIOS_LIO_GPUT2(); -extern uint8_t PC98_BIOS_LIO_GPOINT2(); - -// for more information see [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] -static Bitu PC98_BIOS_LIO(void) { - uint8_t ret = 0; - const char *call_name = "?"; - - lio_read_parameter(); - switch (reg_al) { - case 0xA0: // GINIT - ret = PC98_BIOS_LIO_GINIT(); - break; - case 0xA1: // GSCREEN - ret = PC98_BIOS_LIO_GSCREEN(); - break; - case 0xA2: // GVIEW - ret = PC98_BIOS_LIO_GVIEW(); - break; - case 0xA3: // GCOLOR1 - ret = PC98_BIOS_LIO_GCOLOR1(); - break; - case 0xA4: // GCOLOR2 - ret = PC98_BIOS_LIO_GCOLOR2(); - break; - case 0xA5: // GCLS - ret = PC98_BIOS_LIO_GCLS(); - break; - case 0xA6: // GPSET - ret = PC98_BIOS_LIO_GPSET(); - break; - case 0xA7: // GLINE - ret = PC98_BIOS_LIO_GLINE(); - break; - case 0xA8: // GCIRCLE - ret = PC98_BIOS_LIO_GCIRCLE(); - break; - case 0xA9: // GPAINT1 - ret = PC98_BIOS_LIO_GPAINT1(); - break; - case 0xAA: // GPAINT2 - ret = PC98_BIOS_LIO_GPAINT2(); - break; - case 0xAB: // GGET - ret = PC98_BIOS_LIO_GGET(); - break; - case 0xAC: // GPUT1 - ret = PC98_BIOS_LIO_GPUT1(); - break; - case 0xAD: // GPUT2 - ret = PC98_BIOS_LIO_GPUT2(); - break; - case 0xAE: // GROLL - call_name = "GROLL"; - goto unknown; - case 0xAF: // GPOINT2 - ret = PC98_BIOS_LIO_GPOINT2(); - break; - case 0xCE: // GCOPY - call_name = "GCOPY"; - goto unknown; - case 0x00: // GRAPH BIO - call_name = "GRAPH BIO"; - goto unknown; - default: - unknown: - /* on entry, AL (from our BIOS code) is set to the call number that lead here */ - LOG_MSG("PC-98 BIOS LIO graphics call 0x%02x '%s' with AX=%04X BX=%04X CX=%04X DX=%04X SI=%04X DI=%04X DS=%04X ES=%04X", - reg_al, - call_name, - reg_ax, - reg_bx, - reg_cx, - reg_dx, - reg_si, - reg_di, - SegValue(ds), - SegValue(es)); - break; - }; - // from Yksoft1's patch - reg_ah = ret; - - return CBRET_NONE; -} - - -extern bool enable_weitek; - -static Bitu INT11_Handler(void) { - if (enable_weitek) reg_eax = (1u << 24u)/*Weitek math coprocessor present*/; - reg_ax=mem_readw(BIOS_CONFIGURATION); - return CBRET_NONE; -} -/* - * Define the following define to 1 if you want dosbox-x to check - * the system time every 5 seconds and adjust 1/2 a second to sync them. - */ -#ifndef DOSBOX_CLOCKSYNC -#define DOSBOX_CLOCKSYNC 0 -#endif - -uint32_t BIOS_HostTimeSync(uint32_t /*ticks*/) { -#if 0//DISABLED TEMPORARILY - uint32_t milli = 0; -#if defined(DB_HAVE_CLOCK_GETTIME) && ! defined(WIN32) - struct timespec tp; - clock_gettime(CLOCK_REALTIME,&tp); - - struct tm *loctime; - loctime = localtime(&tp.tv_sec); - milli = (uint32_t) (tp.tv_nsec / 1000000); -#else - /* Setup time and date */ - struct timeb timebuffer; - ftime(&timebuffer); - - const struct tm *loctime; - loctime = localtime (&timebuffer.time); - milli = (uint32_t) timebuffer.millitm; -#endif - /* - loctime->tm_hour = 23; - loctime->tm_min = 59; - loctime->tm_sec = 45; - loctime->tm_mday = 28; - loctime->tm_mon = 2-1; - loctime->tm_year = 2007 - 1900; - */ - -// FIXME: Why is the BIOS filling in the DOS kernel's date? That should be done when DOS boots! - dos.date.day=(uint8_t)loctime->tm_mday; - dos.date.month=(uint8_t)loctime->tm_mon+1; - dos.date.year=(uint16_t)loctime->tm_year+1900; - - uint32_t nticks=(uint32_t)(((double)( - (unsigned int)loctime->tm_hour*3600u*1000u+ - (unsigned int)loctime->tm_min*60u*1000u+ - (unsigned int)loctime->tm_sec*1000u+ - milli))*(((double)PIT_TICK_RATE/65536.0)/1000.0)); - - /* avoid stepping back from off by one errors */ - if (nticks == (ticks - 1u)) - nticks = ticks; - - return nticks; -#endif - return 0; -} - -// TODO: make option -bool enable_bios_timer_synchronize_keyboard_leds = true; - -void KEYBOARD_SetLEDs(uint8_t bits); - -void BIOS_KEYBOARD_SetLEDs(Bitu state) { - Bitu x = mem_readb(BIOS_KEYBOARD_LEDS); - - x &= ~7u; - x |= (state & 7u); - mem_writeb(BIOS_KEYBOARD_LEDS,x); - KEYBOARD_SetLEDs(state); -} - -/* PC-98 IRQ 0 system timer */ -static Bitu INT8_PC98_Handler(void) { - uint16_t counter = mem_readw(0x58A) - 1; - mem_writew(0x58A,counter); - - /* NTS 2018/02/23: I just confirmed from the ROM BIOS of an actual - * PC-98 system that this implementation and Neko Project II - * are 100% accurate to what the BIOS actually does. - * INT 07h really is the "timer tick" interrupt called - * from INT 08h / IRQ 0, and the BIOS really does call - * INT 1Ch AH=3 from INT 08h if the tick count has not - * yet reached zero. - * - * I'm guessing NEC's BIOS developers invented this prior - * to the Intel 80286 and it's INT 07h - * "Coprocessor not present" exception. */ - - if (counter == 0) { - /* mask IRQ 0 */ - IO_WriteB(0x02,IO_ReadB(0x02) | 0x01); - /* ack IRQ 0 */ - IO_WriteB(0x00,0x20); - /* INT 07h */ - CPU_Interrupt(7,CPU_INT_SOFTWARE,reg_eip); - } - else { - /* ack IRQ 0 */ - IO_WriteB(0x00,0x20); - /* make sure it continues ticking */ - PC98_Interval_Timer_Continue(); - } - - return CBRET_NONE; -} - - -extern bool cmos_sync_flag; -extern uint8_t cmos_sync_sec,cmos_sync_min,cmos_sync_hour; - -extern bool sync_time, manualtime; -bool sync_time_timerrate_warning = false; - -uint32_t PIT0_GetAssignedCounter(void); - -static Bitu INT8_Handler(void) { - /* Increase the bios tick counter */ - uint32_t value = mem_readd(BIOS_TIMER) + 1; - if(value >= 0x1800B0) { - // time wrap at midnight - mem_writeb(BIOS_24_HOURS_FLAG,mem_readb(BIOS_24_HOURS_FLAG)+1); - value=0; - } - - /* Legacy BIOS behavior: This isn't documented at all but most BIOSes - check the BIOS data area for LED keyboard status. If it sees that - value change, then it sends it to the keyboard. This is why on - older DOS machines you could change LEDs by writing to 40:17. - We have to emulate this also because Windows 3.1/9x seems to rely on - it when handling the keyboard from its own driver. Their driver does - hook the keyboard and handles keyboard I/O by itself, but it still - allows the BIOS to do the keyboard magic from IRQ 0 (INT 8h). Yech. */ - if (enable_bios_timer_synchronize_keyboard_leds) { - Bitu should_be = (mem_readb(BIOS_KEYBOARD_STATE) >> 4) & 7; - Bitu led_state = (mem_readb(BIOS_KEYBOARD_LEDS) & 7); - - if (should_be != led_state) - BIOS_KEYBOARD_SetLEDs(should_be); - } - - if (sync_time && cmos_sync_flag) { - value = (uint32_t)((cmos_sync_hour*3600+cmos_sync_min*60+cmos_sync_sec)*(float)PIT_TICK_RATE/65536.0); - cmos_sync_flag = false; - } -#if 0//DISABLED TEMPORARILY - if (sync_time&&!manualtime) { -#if DOSBOX_CLOCKSYNC - static bool check = false; - if((value %50)==0) { - if(((value %100)==0) && check) { - check = false; - time_t curtime;struct tm *loctime; - curtime = time (NULL);loctime = localtime (&curtime); - uint32_t ticksnu = (uint32_t)((loctime->tm_hour*3600+loctime->tm_min*60+loctime->tm_sec)*(float)PIT_TICK_RATE/65536.0); - int32_t bios = value;int32_t tn = ticksnu; - int32_t diff = tn - bios; - if(diff>0) { - if(diff < 18) { diff = 0; } else diff = 9; - } else { - if(diff > -18) { diff = 0; } else diff = -9; - } - - value += diff; - } else if((value%100)==50) check = true; - } -#endif - - /* synchronize time=true is based around the assumption - * that the timer is left ticking at the standard 18.2Hz - * rate. If that is not true, and this IRQ0 handler is - * being called faster, then synchronization will not - * work properly. - * - * Two 1996 demoscene entries sl_fokus.zip and sl_haloo.zip - * are known to program the timer to run faster (58Hz and - * 150Hz) yet use BIOS_TIMER from the BIOS data area to - * track the passage of time. Synchronizing time that way - * will only lead to BIOS_TIMER values that repeat or go - * backwards and will break the demo. */ - if (PIT0_GetAssignedCounter() >= 0xFFFF/*Should be 0x10000 but we'll accept some programs might write 0xFFFF*/) { - uint32_t BIOS_HostTimeSync(uint32_t ticks); - value = BIOS_HostTimeSync(value); - - if (sync_time_timerrate_warning) { - sync_time_timerrate_warning = false; - LOG(LOG_MISC,LOG_WARN)("IRQ0 timer rate restored to 18.2Hz and synchronize time=true, resuming synchronization. BIOS_TIMER may jump backwards suddenly."); - } - } - else { - if (!sync_time_timerrate_warning) { - /* Okay, you changed the tick rate. That affects BIOS_TIMER - * and therefore counts as manual time. Sorry. */ - sync_time_timerrate_warning = true; - LOG(LOG_MISC,LOG_WARN)("IRQ0 timer rate is not 18.2Hz and synchronize time=true, disabling synchronization until normal rate restored."); - } - } - } -#endif - mem_writed(BIOS_TIMER,value); - - if(bootdrive>=0) { -#if (defined(WIN32) && !defined(HX_DOS) || defined(LINUX) && C_X11 || defined(MACOSX)) && (defined(C_SDL2) || defined(SDL_DOSBOX_X_SPECIAL)) - SetIMPosition(); -#endif - } else if (IS_DOSV && DOSV_CheckCJKVideoMode()) { - INT8_DOSV(); - } else if(J3_IsJapanese()) { - INT8_J3(); - } else if (IS_DOS_CJK) { -#if (defined(WIN32) && !defined(HX_DOS) || defined(LINUX) && C_X11 || defined(MACOSX)) && (defined(C_SDL2) || defined(SDL_DOSBOX_X_SPECIAL)) - SetIMPosition(); -#endif - } - - /* decrement FDD motor timeout counter; roll over on earlier PC, stop at zero on later PC */ - uint8_t val = mem_readb(BIOS_DISK_MOTOR_TIMEOUT); - if (val || !IS_EGAVGA_ARCH) mem_writeb(BIOS_DISK_MOTOR_TIMEOUT,val-1); - /* clear FDD motor bits when counter reaches zero */ - if (val == 1) mem_writeb(BIOS_DRIVE_RUNNING,mem_readb(BIOS_DRIVE_RUNNING) & 0xF0); - return CBRET_NONE; -} -#undef DOSBOX_CLOCKSYNC - -static Bitu INT1C_Handler(void) { - return CBRET_NONE; -} - -static Bitu INT12_Handler(void) { - reg_ax=mem_readw(BIOS_MEMORY_SIZE); - return CBRET_NONE; -} - -static Bitu INT17_Handler(void) { - if (reg_ah > 0x2 || reg_dx > 0x2) { // 0-2 printer port functions - // and no more than 3 parallel ports - LOG_MSG("BIOS INT17: Unhandled call AH=%2X DX=%4x",reg_ah,reg_dx); - return CBRET_NONE; - } - - switch(reg_ah) { - case 0x00: // PRINTER: Write Character - if(parallelPortObjects[reg_dx]) { - if(parallelPortObjects[reg_dx]->Putchar(reg_al)) - reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); - else reg_ah=1; - } - break; - case 0x01: // PRINTER: Initialize port - if(parallelPortObjects[reg_dx]) { - parallelPortObjects[reg_dx]->initialize(); - reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); - } - break; - case 0x02: // PRINTER: Get Status - if(parallelPortObjects[reg_dx]) - reg_ah=parallelPortObjects[reg_dx]->getPrinterStatus(); - //LOG_MSG("printer status: %x",reg_ah); - break; - case 0x20: /* Some sort of printerdriver install check*/ - break; - case 0x50: // Printer BIOS for AX - if (!IS_JEGA_ARCH) break; - switch (reg_al) { - case 0x00:// Set JP/US mode in PRT BIOS - LOG(LOG_BIOS, LOG_NORMAL)("AX PRT BIOS 5000h is called. (not implemented)"); - reg_al = 0x01; // Return error (not implemented) - break; - case 0x01:// Get JP/US mode in PRT BIOS - reg_al = 0x01; // Return US mode (not implemented) - break; - default: - LOG(LOG_BIOS, LOG_ERROR)("Unhandled AX Function 50%2X", reg_al); - break; - } - break; - } - return CBRET_NONE; -} - -static bool INT14_Wait(uint16_t port, uint8_t mask, uint8_t timeout, uint8_t* retval) { - double starttime = PIC_FullIndex(); - double timeout_f = timeout * 1000.0; - while (((*retval = IO_ReadB(port)) & mask) != mask) { - if (starttime < (PIC_FullIndex() - timeout_f)) { - return false; - } - CALLBACK_Idle(); - } - return true; -} - -static Bitu INT4B_Handler(void) { - /* TODO: This is where the Virtual DMA specification is accessed on modern systems. - * When we implement that, move this to EMM386 emulation code. */ - - if (reg_ax >= 0x8102 && reg_ax <= 0x810D) { - LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted Virtual DMA specification call (INT 4Bh AX=%04x BX=%04x CX=%04x DX=%04x", - reg_ax,reg_bx,reg_cx,reg_dx); - } - else if (reg_ah == 0x80) { - LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted IBM SCSI interface call"); - } - else if (reg_ah <= 0x02) { - LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted TI Professional PC parallel port function AH=%02x",reg_ah); - } - else { - LOG(LOG_MISC,LOG_DEBUG)("Guest OS attempted unknown INT 4Bh call AX=%04x",reg_ax); - } - - /* Oh, I'm just a BIOS that doesn't know what the hell you're doing. CF=1 */ - CALLBACK_SCF(true); - return CBRET_NONE; -} - -static Bitu INT14_Handler(void) { - if (reg_ah > 0x3 || reg_dx > 0x3) { // 0-3 serial port functions - // and no more than 4 serial ports - LOG_MSG("BIOS INT14: Unhandled call AH=%2X DX=%4x",reg_ah,reg_dx); - return CBRET_NONE; - } - - uint16_t port = real_readw(0x40,reg_dx * 2u); // DX is always port number - uint8_t timeout = mem_readb((PhysPt)((unsigned int)BIOS_COM1_TIMEOUT + (unsigned int)reg_dx)); - if (port==0) { - LOG(LOG_BIOS,LOG_NORMAL)("BIOS INT14: port %d does not exist.",reg_dx); - return CBRET_NONE; - } - switch (reg_ah) { - case 0x00: { - // Initialize port - // Parameters: Return: - // AL: port parameters AL: modem status - // AH: line status - - // set baud rate - Bitu baudrate = 9600u; - uint16_t baudresult; - Bitu rawbaud=(Bitu)reg_al>>5u; - - if (rawbaud==0){ baudrate=110u;} - else if (rawbaud==1){ baudrate=150u;} - else if (rawbaud==2){ baudrate=300u;} - else if (rawbaud==3){ baudrate=600u;} - else if (rawbaud==4){ baudrate=1200u;} - else if (rawbaud==5){ baudrate=2400u;} - else if (rawbaud==6){ baudrate=4800u;} - else if (rawbaud==7){ baudrate=9600u;} - - baudresult = (uint16_t)(115200u / baudrate); - - IO_WriteB(port+3u, 0x80u); // enable divider access - IO_WriteB(port, (uint8_t)baudresult&0xffu); - IO_WriteB(port+1u, (uint8_t)(baudresult>>8u)); - - // set line parameters, disable divider access - IO_WriteB(port+3u, reg_al&0x1Fu); // LCR - - // disable interrupts - IO_WriteB(port+1u, 0u); // IER - - // get result - reg_ah=IO_ReadB(port+5u)&0xffu; - reg_al=IO_ReadB(port+6u)&0xffu; - CALLBACK_SCF(false); - break; - } - case 0x01: // Transmit character - // Parameters: Return: - // AL: character AL: unchanged - // AH: 0x01 AH: line status from just before the char was sent - // (0x80 | unpredicted) in case of timeout - // [undoc] (0x80 | line status) in case of tx timeout - // [undoc] (0x80 | modem status) in case of dsr/cts timeout - - // set DTR & RTS on - IO_WriteB(port+4u,0x3u); - // wait for DSR & CTS - if (INT14_Wait(port+6u, 0x30u, timeout, ®_ah)) { - // wait for TX buffer empty - if (INT14_Wait(port+5u, 0x20u, timeout, ®_ah)) { - // finally send the character - IO_WriteB(port,reg_al); - } else - reg_ah |= 0x80u; - } else // timed out - reg_ah |= 0x80u; - - CALLBACK_SCF(false); - break; - case 0x02: // Read character - // Parameters: Return: - // AH: 0x02 AL: received character - // [undoc] will be trashed in case of timeout - // AH: (line status & 0x1E) in case of success - // (0x80 | unpredicted) in case of timeout - // [undoc] (0x80 | line status) in case of rx timeout - // [undoc] (0x80 | modem status) in case of dsr timeout - - // set DTR on - IO_WriteB(port+4u,0x1u); - - // wait for DSR - if (INT14_Wait(port+6, 0x20, timeout, ®_ah)) { - // wait for character to arrive - if (INT14_Wait(port+5, 0x01, timeout, ®_ah)) { - reg_ah &= 0x1E; - reg_al = IO_ReadB(port); - } else - reg_ah |= 0x80; - } else - reg_ah |= 0x80; - - CALLBACK_SCF(false); - break; - case 0x03: // get status - reg_ah=IO_ReadB(port+5u)&0xffu; - reg_al=IO_ReadB(port+6u)&0xffu; - CALLBACK_SCF(false); - break; - - } - return CBRET_NONE; -} - -Bits HLT_Decode(void); -void KEYBOARD_AUX_Write(Bitu val); -unsigned char KEYBOARD_AUX_GetType(); -unsigned char KEYBOARD_AUX_DevStatus(); -unsigned char KEYBOARD_AUX_Resolution(); -unsigned char KEYBOARD_AUX_SampleRate(); -void KEYBOARD_ClrBuffer(void); -void KEYBOARD_AUX_LowerIRQ(); - -static Bitu INT15_Handler(void) { - if( ( machine==MCH_AMSTRAD ) && ( reg_ah<0x07 ) ) { - switch(reg_ah) { - case 0x00: - // Read/Reset Mouse X/Y Counts. - // CX = Signed X Count. - // DX = Signed Y Count. - // CC. - case 0x01: - // Write NVR Location. - // AL = NVR Address to be written (0-63). - // BL = NVR Data to be written. - - // AH = Return Code. - // 00 = NVR Written Successfully. - // 01 = NVR Address out of range. - // 02 = NVR Data write error. - // CC. - case 0x02: - // Read NVR Location. - // AL = NVR Address to be read (0-63). - - // AH = Return Code. - // 00 = NVR read successfully. - // 01 = NVR Address out of range. - // 02 = NVR checksum error. - // AL = Byte read from NVR. - // CC. - case 0x03: - // Write VDU Colour Plane Write Register. - vga.amstrad.write_plane = reg_al & 0x0F; - CALLBACK_SCF(false); - break; - case 0x04: - // Write VDU Colour Plane Read Register. - vga.amstrad.read_plane = reg_al & 0x03; - CALLBACK_SCF(false); - break; - case 0x05: - // Write VDU Graphics Border Register. - vga.amstrad.border_color = reg_al & 0x0F; - CALLBACK_SCF(false); - break; - case 0x06: - // Return ROS Version Number. - reg_bx = 0x0001; - CALLBACK_SCF(false); - break; - default: - LOG(LOG_BIOS, LOG_NORMAL)("INT15 Unsupported PC1512 Call %02X", reg_ah); - return CBRET_NONE; - } - } - switch (reg_ah) { - case 0x06: - LOG(LOG_BIOS,LOG_NORMAL)("INT15 Unknown Function 6 (Amstrad?)"); - break; - case 0x24: //A20 stuff - switch (reg_al) { - case 0: //Disable a20 - MEM_A20_Enable(false); - reg_ah = 0; //call successful - CALLBACK_SCF(false); //clear on success - break; - case 1: //Enable a20 - MEM_A20_Enable( true ); - reg_ah = 0; //call successful - CALLBACK_SCF(false); //clear on success - break; - case 2: //Query a20 - reg_al = MEM_A20_Enabled() ? 0x1 : 0x0; - reg_ah = 0; //call successful - CALLBACK_SCF(false); - break; - case 3: //Get a20 support - reg_bx = 0x3; //Bitmask, keyboard and 0x92 - reg_ah = 0; //call successful - CALLBACK_SCF(false); - break; - default: - goto unhandled; - } - break; - case 0xC0: /* Get Configuration*/ - CPU_SetSegGeneral(es,biosConfigSeg); - reg_bx = 0; - reg_ah = 0; - CALLBACK_SCF(false); - break; - case 0x4f: /* BIOS - Keyboard intercept */ - /* Carry should be set but let's just set it just in case */ - CALLBACK_SCF(true); - break; - case 0x83: /* BIOS - SET EVENT WAIT INTERVAL */ - { - if(reg_al == 0x01) { /* Cancel it */ - mem_writeb(BIOS_WAIT_FLAG_ACTIVE,0); - IO_Write(0x70,0xb); - IO_Write(0x71,IO_Read(0x71)&~0x40); - CALLBACK_SCF(false); - break; - } - if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { - reg_ah=0x80; - CALLBACK_SCF(true); - break; - } - uint32_t count=((uint32_t)reg_cx<<16u)|reg_dx; - mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(SegValue(es),reg_bx)); - mem_writed(BIOS_WAIT_FLAG_COUNT,count); - mem_writeb(BIOS_WAIT_FLAG_ACTIVE,1); - /* Reprogram RTC to start */ - IO_Write(0x70,0xb); - IO_Write(0x71,IO_Read(0x71)|0x40); - CALLBACK_SCF(false); - } - break; - case 0x84: /* BIOS - JOYSTICK SUPPORT (XT after 11/8/82,AT,XT286,PS) */ - if (reg_dx == 0x0000) { - // Get Joystick button status - if (JOYSTICK_IsEnabled(0) || JOYSTICK_IsEnabled(1)) { - reg_al = IO_ReadB(0x201)&0xf0; - CALLBACK_SCF(false); - } else { - // dos values - reg_ax = 0x00f0; reg_dx = 0x0201; - CALLBACK_SCF(true); - } - } else if (reg_dx == 0x0001) { - if (JOYSTICK_IsEnabled(0)) { - reg_ax = (uint16_t)(JOYSTICK_GetMove_X(0)*127+128); - reg_bx = (uint16_t)(JOYSTICK_GetMove_Y(0)*127+128); - if(JOYSTICK_IsEnabled(1)) { - reg_cx = (uint16_t)(JOYSTICK_GetMove_X(1)*127+128); - reg_dx = (uint16_t)(JOYSTICK_GetMove_Y(1)*127+128); - } - else { - reg_cx = reg_dx = 0; - } - CALLBACK_SCF(false); - } else if (JOYSTICK_IsEnabled(1)) { - reg_ax = reg_bx = 0; - reg_cx = (uint16_t)(JOYSTICK_GetMove_X(1)*127+128); - reg_dx = (uint16_t)(JOYSTICK_GetMove_Y(1)*127+128); - CALLBACK_SCF(false); - } else { - reg_ax = reg_bx = reg_cx = reg_dx = 0; - CALLBACK_SCF(true); - } - } else { - LOG(LOG_BIOS,LOG_ERROR)("INT15:84:Unknown Bios Joystick functionality."); - } - break; - case 0x86: /* BIOS - WAIT (AT,PS) */ - { - if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) { - reg_ah=0x83; - CALLBACK_SCF(true); - break; - } - uint8_t t; - uint32_t count=((uint32_t)reg_cx<<16u)|reg_dx; - mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(0,BIOS_WAIT_FLAG_TEMP)); - mem_writed(BIOS_WAIT_FLAG_COUNT,count); - mem_writeb(BIOS_WAIT_FLAG_ACTIVE,1); - - /* if the user has not set the option, warn if IRQs are masked */ - if (!int15_wait_force_unmask_irq) { - /* make sure our wait function works by unmasking IRQ 2, and IRQ 8. - * (bugfix for 1993 demo Yodel "Mayday" demo. this demo keeps masking IRQ 2 for some stupid reason.) */ - if ((t=IO_Read(0x21)) & (1 << 2)) { - LOG(LOG_BIOS,LOG_ERROR)("INT15:86:Wait: IRQ 2 masked during wait. " - "Consider adding 'int15 wait force unmask irq=true' to your dosbox-x.conf"); - } - if ((t=IO_Read(0xA1)) & (1 << 0)) { - LOG(LOG_BIOS,LOG_ERROR)("INT15:86:Wait: IRQ 8 masked during wait. " - "Consider adding 'int15 wait force unmask irq=true' to your dosbox-x.conf"); - } - } - - /* Reprogram RTC to start */ - IO_Write(0x70,0xb); - IO_Write(0x71,IO_Read(0x71)|0x40); - while (mem_readd(BIOS_WAIT_FLAG_COUNT)) { - if (int15_wait_force_unmask_irq) { - /* make sure our wait function works by unmasking IRQ 2, and IRQ 8. - * (bugfix for 1993 demo Yodel "Mayday" demo. this demo keeps masking IRQ 2 for some stupid reason.) */ - if ((t=IO_Read(0x21)) & (1 << 2)) { - LOG(LOG_BIOS,LOG_WARN)("INT15:86:Wait: IRQ 2 masked during wait. " - "This condition might result in an infinite wait on " - "some BIOSes. Unmasking IRQ to keep things moving along."); - IO_Write(0x21,t & ~(1 << 2)); - } - if ((t=IO_Read(0xA1)) & (1 << 0)) { - LOG(LOG_BIOS,LOG_WARN)("INT15:86:Wait: IRQ 8 masked during wait. " - "This condition might result in an infinite wait on some " - "BIOSes. Unmasking IRQ to keep things moving along."); - IO_Write(0xA1,t & ~(1 << 0)); - } - } - - CALLBACK_Idle(); - } - CALLBACK_SCF(false); - break; - } - case 0x87: /* Copy extended memory */ - { - bool enabled = MEM_A20_Enabled(); - MEM_A20_Enable(true); - Bitu bytes = reg_cx * 2u; - PhysPt data = SegPhys(es)+reg_si; - PhysPt source = (mem_readd(data+0x12u) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data+0x17u)<<24u); - PhysPt dest = (mem_readd(data+0x1Au) & 0x00FFFFFFu) + ((unsigned int)mem_readb(data+0x1Fu)<<24u); - MEM_BlockCopy(dest,source,bytes); - reg_ax = 0x00; - MEM_A20_Enable(enabled); - Segs.limit[cs] = 0xFFFF; - Segs.limit[ds] = 0xFFFF; - Segs.limit[es] = 0xFFFF; - Segs.limit[ss] = 0xFFFF; - CALLBACK_SCF(false); - break; - } - case 0x88: /* SYSTEM - GET EXTENDED MEMORY SIZE (286+) */ - /* This uses the 16-bit value read back from CMOS which is capped at 64MB */ - reg_ax=other_memsystems?0:size_extended; - LOG(LOG_BIOS,LOG_NORMAL)("INT15:Function 0x88 Remaining %04X kb",reg_ax); - CALLBACK_SCF(false); - break; - case 0x89: /* SYSTEM - SWITCH TO PROTECTED MODE */ - { - IO_Write(0x20,0x10);IO_Write(0x21,reg_bh);IO_Write(0x21,0);IO_Write(0x21,0xFF); - IO_Write(0xA0,0x10);IO_Write(0xA1,reg_bl);IO_Write(0xA1,0);IO_Write(0xA1,0xFF); - MEM_A20_Enable(true); - PhysPt table=SegPhys(es)+reg_si; - CPU_LGDT(mem_readw(table+0x8),mem_readd(table+0x8+0x2) & 0xFFFFFF); - CPU_LIDT(mem_readw(table+0x10),mem_readd(table+0x10+0x2) & 0xFFFFFF); - CPU_SET_CRX(0,CPU_GET_CRX(0)|1); - CPU_SetSegGeneral(ds,0x18); - CPU_SetSegGeneral(es,0x20); - CPU_SetSegGeneral(ss,0x28); - Bitu ret = mem_readw(SegPhys(ss)+reg_sp); - reg_sp+=6; //Clear stack of interrupt frame - CPU_SetFlags(0,FMASK_ALL); - reg_ax=0; - CPU_JMP(false,0x30,ret,0); - } - break; - case 0x8A: /* EXTENDED MEMORY SIZE */ - { - Bitu sz = MEM_TotalPages()*4; - if (sz >= 1024) sz -= 1024; - else sz = 0; - reg_ax = sz & 0xFFFF; - reg_dx = sz >> 16; - CALLBACK_SCF(false); - } - break; - case 0x90: /* OS HOOK - DEVICE BUSY */ - case 0x91: /* OS HOOK - DEVICE POST */ - CALLBACK_SCF(false); - reg_ah=0; - break; - case 0xc2: /* BIOS PS2 Pointing Device Support */ - /* TODO: Our reliance on AUX emulation means that at some point, AUX emulation - * must always be enabled if BIOS PS/2 emulation is enabled. Future planned change: - * - * If biosps2=true and aux=true, carry on what we're already doing now: emulate INT 15h by - * directly writing to the AUX port of the keyboard controller. - * - * If biosps2=false, the aux= setting enables/disables AUX emulation as it already does now. - * biosps2=false implies that we're emulating a keyboard controller with AUX but no BIOS - * support for it (however rare that might be). This gives the user of DOSBox-X the means - * to test that scenario especially in case he/she is developing a homebrew OS and needs - * to ensure their code can handle cases like that gracefully. - * - * If biosps2=true and aux=false, AUX emulation is enabled anyway, but the keyboard emulation - * must act as if the AUX port is not there so the guest OS cannot control it. Again, not - * likely on real hardware, but a useful test case for homebrew OS developers. - * - * If you the user set aux=false, then you obviously want to test a system configuration - * where the keyboard controller has no AUX port. If you set biosps2=true, then you want to - * test an OS that uses BIOS functions to setup the "pointing device" but you do not want the - * guest OS to talk directly to the AUX port on the keyboard controller. - * - * Logically that's not likely to happen on real hardware, but we like giving the end-user - * options to play with, so instead, if aux=false and biosps2=true, DOSBox-X should print - * a warning stating that INT 15h mouse emulation with a PS/2 port is nonstandard and may - * cause problems with OSes that need to talk directly to hardware. - * - * It is noteworthy that PS/2 mouse support in MS-DOS mouse drivers as well as Windows 3.x, - * Windows 95, and Windows 98, is carried out NOT by talking directly to the AUX port but - * instead by relying on the BIOS INT 15h functions here to do the dirty work. For those - * scenarios, biosps2=true and aux=false is perfectly safe and does not cause issues. - * - * OSes that communicate directly with the AUX port however (Linux, Windows NT) will not work - * unless aux=true. */ - if (en_bios_ps2mouse) { -// LOG_MSG("INT 15h AX=%04x BX=%04x\n",reg_ax,reg_bx); - switch (reg_al) { - case 0x00: // enable/disable - if (reg_bh==0) { // disable - KEYBOARD_AUX_Write(0xF5); - Mouse_SetPS2State(false); - reg_ah=0; - CALLBACK_SCF(false); - KEYBOARD_ClrBuffer(); - } else if (reg_bh==0x01) { //enable - if (!Mouse_SetPS2State(true)) { - reg_ah=5; - CALLBACK_SCF(true); - break; - } - KEYBOARD_AUX_Write(0xF4); - KEYBOARD_ClrBuffer(); - reg_ah=0; - CALLBACK_SCF(false); - } else { - CALLBACK_SCF(true); - reg_ah=1; - } - break; - case 0x01: // reset - KEYBOARD_AUX_Write(0xFF); - Mouse_SetPS2State(false); - KEYBOARD_ClrBuffer(); - reg_bx=0x00aa; // mouse (BH=device ID BL=value returned by attached device after reset) [http://www.ctyme.com/intr/rb-1597.htm] - LOG_MSG("INT 15h mouse reset\n"); - KEYBOARD_AUX_Write(0xF6); /* set defaults */ - Mouse_SetPS2State(false); - KEYBOARD_ClrBuffer(); - KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ - CALLBACK_SCF(false); - reg_ah=0; // must return success. Fall through was well intended but, no, causes an error code that confuses mouse drivers - break; - case 0x05: // initialize - if (reg_bh >= 3 && reg_bh <= 4) { - /* TODO: BIOSes remember this value as the number of bytes to store before - * calling the device callback. Setting this value to "1" is perfectly - * valid if you want a byte-stream like mode (at the cost of one - * interrupt per byte!). Most OSes will call this with BH=3 for standard - * PS/2 mouse protocol. You can also call this with BH=4 for Intellimouse - * protocol support, though testing (so far with VirtualBox) shows the - * device callback still only gets the first three bytes on the stack. - * Contrary to what you might think, the BIOS does not interpret the - * bytes at all. - * - * The source code of CuteMouse 1.9 seems to suggest some BIOSes take - * pains to repack the 4th byte in the upper 8 bits of one of the WORDs - * on the stack in Intellimouse mode at the cost of shifting the W and X - * fields around. I can't seem to find any source on who does that or - * if it's even true, so I disregard the example at this time. - * - * Anyway, you need to store off this value somewhere and make use of - * it in src/ints/mouse.cpp device callback emulation to reframe the - * PS/2 mouse bytes coming from AUX (if aux=true) or emulate the - * re-framing if aux=false to emulate this protocol fully. */ - LOG_MSG("INT 15h mouse initialized to %u-byte protocol\n",reg_bh); - Mouse_PS2SetPacketSize(reg_bh); - KEYBOARD_AUX_Write(0xF6); /* set defaults */ - Mouse_SetPS2State(false); - KEYBOARD_ClrBuffer(); - CALLBACK_SCF(false); - reg_ah=0; - } - else { - CALLBACK_SCF(false); - reg_ah=0x02; /* invalid input */ - } - break; - case 0x02: { // set sampling rate - Mouse_PS2SetSamplingRate(reg_bh); - static const unsigned char tbl[7] = {10,20,40,60,80,100,200}; - KEYBOARD_AUX_Write(0xF3); - if (reg_bh > 6) reg_bh = 6; - KEYBOARD_AUX_Write(tbl[reg_bh]); - KEYBOARD_ClrBuffer(); - CALLBACK_SCF(false); - reg_ah=0; - } break; - case 0x03: // set resolution - KEYBOARD_AUX_Write(0xE8); - KEYBOARD_AUX_Write(reg_bh&3); - KEYBOARD_ClrBuffer(); - CALLBACK_SCF(false); - reg_ah=0; - break; - case 0x04: // get type - reg_bh=KEYBOARD_AUX_GetType(); // ID - KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ - LOG_MSG("INT 15h reporting mouse device ID 0x%02x\n",reg_bh); - KEYBOARD_ClrBuffer(); - CALLBACK_SCF(false); - reg_ah=0; - break; - case 0x06: // extended commands - if (reg_bh == 0x00) { - /* Read device status and info. - * Windows 9x does not appear to use this, but Windows NT 3.1 does (prior to entering - * full 32-bit protected mode) */ - CALLBACK_SCF(false); - reg_bx=KEYBOARD_AUX_DevStatus(); - reg_cx=KEYBOARD_AUX_Resolution(); - reg_dx=KEYBOARD_AUX_SampleRate(); - KEYBOARD_AUX_LowerIRQ(); /* HACK: Lower IRQ or else it will persist, which can cause problems with Windows 3.1 stock PS/2 mouse drivers */ - KEYBOARD_ClrBuffer(); - reg_ah=0; - } - else if ((reg_bh==0x01) || (reg_bh==0x02)) { /* set scaling */ - KEYBOARD_AUX_Write(0xE6u+reg_bh-1u); /* 0xE6 1:1 or 0xE7 2:1 */ - KEYBOARD_ClrBuffer(); - CALLBACK_SCF(false); - reg_ah=0; - } else { - CALLBACK_SCF(true); - reg_ah=1; - } - break; - case 0x07: // set callback - Mouse_ChangePS2Callback(SegValue(es),reg_bx); - CALLBACK_SCF(false); - reg_ah=0; - break; - default: - LOG_MSG("INT 15h unknown mouse call AX=%04x\n",reg_ax); - CALLBACK_SCF(true); - reg_ah=1; - break; - } - } - else { - reg_ah=0x86; - CALLBACK_SCF(true); - if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA)) { - /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ - CALLBACK_SZF(false); - } - } - break; - case 0xc3: /* set carry flag so BorlandRTM doesn't assume a VECTRA/PS2 */ - reg_ah=0x86; - CALLBACK_SCF(true); - break; - case 0xc4: /* BIOS POS Program option Select */ - LOG(LOG_BIOS,LOG_NORMAL)("INT15:Function %X called, bios mouse not supported",reg_ah); - CALLBACK_SCF(true); - break; - case 0x53: // APM BIOS - if (APMBIOS) { - /* Windows 98 calls AH=05h CPU IDLE way too much per second, it makes it difficult to see anything important scroll by. - * Rate limit this particular call in the log file. */ - if (reg_al == 0x05) { - APM_log_cpu_idle++; - if (PIC_FullIndex() >= APM_log_cpu_idle_next_report) { - LOG(LOG_BIOS,LOG_DEBUG)("APM BIOS, %lu calls to AX=%04x BX=0x%04x CX=0x%04x\n",(unsigned long)APM_log_cpu_idle,reg_ax,reg_bx,reg_cx); - APM_log_cpu_idle_next_report = PIC_FullIndex() + 1000; - APM_log_cpu_idle = 0; - } - } - else { - LOG(LOG_BIOS,LOG_DEBUG)("APM BIOS call AX=%04x BX=0x%04x CX=0x%04x\n",reg_ax,reg_bx,reg_cx); - } - - switch(reg_al) { - case 0x00: // installation check - reg_ah = 1; // major - reg_al = APM_BIOS_minor_version; // minor - reg_bx = 0x504d; // 'PM' - reg_cx = (APMBIOS_allow_prot16?0x01:0x00) + (APMBIOS_allow_prot32?0x02:0x00); - // 32-bit interface seems to be needed for standby in win95 - CALLBACK_SCF(false); - break; - case 0x01: // connect real mode interface - if(!APMBIOS_allow_realmode) { - LOG_MSG("APM BIOS: OS attempted real-mode connection, which is disabled in your dosbox-x.conf\n"); - reg_ah = 0x86; // APM not present - CALLBACK_SCF(true); - break; - } - if(reg_bx != 0x0) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } - if(!apm_realmode_connected) { // not yet connected - LOG_MSG("APM BIOS: Connected to real-mode interface\n"); - CALLBACK_SCF(false); - APMBIOS_connect_mode = APMBIOS_CONNECT_REAL; - PowerButtonClicks=0; /* BIOSes probably clear whatever hardware register this involves... we'll see */ - APM_ResumeNotificationFromStandby = false; - APM_ResumeNotificationFromSuspend = false; - apm_realmode_connected=true; - } else { - LOG_MSG("APM BIOS: OS attempted to connect to real-mode interface when already connected\n"); - reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect - CALLBACK_SCF(true); - } - APM_BIOS_connected_minor_version = 0; - break; - case 0x02: // connect 16-bit protected mode interface - if(!APMBIOS_allow_prot16) { - LOG_MSG("APM BIOS: OS attempted 16-bit protected mode connection, which is disabled in your dosbox-x.conf\n"); - reg_ah = 0x06; // not supported - CALLBACK_SCF(true); - break; - } - if(reg_bx != 0x0) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } - if(!apm_realmode_connected) { // not yet connected - /* NTS: We use the same callback address for both 16-bit and 32-bit - * because only the DOS callback and RETF instructions are involved, - * which can be executed as either 16-bit or 32-bit code without problems. */ - LOG_MSG("APM BIOS: Connected to 16-bit protected mode interface\n"); - CALLBACK_SCF(false); - reg_ax = INT15_apm_pmentry >> 16; // AX = 16-bit code segment (real mode base) - reg_bx = INT15_apm_pmentry & 0xFFFF; // BX = offset of entry point - reg_cx = INT15_apm_pmentry >> 16; // CX = 16-bit data segment (NTS: doesn't really matter) - reg_si = 0xFFFF; // SI = code segment length - reg_di = 0xFFFF; // DI = data segment length - APMBIOS_connect_mode = APMBIOS_CONNECT_PROT16; - PowerButtonClicks=0; /* BIOSes probably clear whatever hardware register this involves... we'll see */ - APM_ResumeNotificationFromStandby = false; - APM_ResumeNotificationFromSuspend = false; - apm_realmode_connected=true; - } else { - LOG_MSG("APM BIOS: OS attempted to connect to 16-bit protected mode interface when already connected\n"); - reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect - CALLBACK_SCF(true); - } - APM_BIOS_connected_minor_version = 0; - break; - case 0x03: // connect 32-bit protected mode interface - // Note that Windows 98 will NOT talk to the APM BIOS unless the 32-bit protected mode connection is available. - // And if you lie about it in function 0x00 and then fail, Windows 98 will fail with a "Windows protection error". - if(!APMBIOS_allow_prot32) { - LOG_MSG("APM BIOS: OS attempted 32-bit protected mode connection, which is disabled in your dosbox-x.conf\n"); - reg_ah = 0x08; // not supported - CALLBACK_SCF(true); - break; - } - if(reg_bx != 0x0) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } - if(!apm_realmode_connected) { // not yet connected - LOG_MSG("APM BIOS: Connected to 32-bit protected mode interface\n"); - CALLBACK_SCF(false); - /* NTS: We use the same callback address for both 16-bit and 32-bit - * because only the DOS callback and RETF instructions are involved, - * which can be executed as either 16-bit or 32-bit code without problems. */ - reg_ax = INT15_apm_pmentry >> 16; // AX = 32-bit code segment (real mode base) - reg_ebx = INT15_apm_pmentry & 0xFFFF; // EBX = offset of entry point - reg_cx = INT15_apm_pmentry >> 16; // CX = 16-bit code segment (real mode base) - reg_dx = INT15_apm_pmentry >> 16; // DX = data segment (real mode base) (?? what size?) - reg_esi = 0xFFFFFFFF; // ESI = upper word: 16-bit code segment len lower word: 32-bit code segment length - reg_di = 0xFFFF; // DI = data segment length - APMBIOS_connect_mode = APMBIOS_CONNECT_PROT32; - PowerButtonClicks=0; /* BIOSes probably clear whatever hardware register this involves... we'll see */ - APM_ResumeNotificationFromStandby = false; - APM_ResumeNotificationFromSuspend = false; - apm_realmode_connected=true; - } else { - LOG_MSG("APM BIOS: OS attempted to connect to 32-bit protected mode interface when already connected\n"); - reg_ah = APMBIOS_connected_already_err(); // interface connection already in effect - CALLBACK_SCF(true); - } - APM_BIOS_connected_minor_version = 0; - break; - case 0x04: // DISCONNECT INTERFACE - if(reg_bx != 0x0) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } - if(apm_realmode_connected) { - LOG_MSG("APM BIOS: OS disconnected\n"); - CALLBACK_SCF(false); - apm_realmode_connected=false; - } else { - reg_ah = 0x03; // interface not connected - CALLBACK_SCF(true); - } - APM_BIOS_connected_minor_version = 0; - break; - case 0x05: // CPU IDLE - if(!apm_realmode_connected) { - reg_ah = 0x03; - CALLBACK_SCF(true); - break; - } - - // Trigger CPU HLT instruction. - // NTS: For whatever weird reason, NOT emulating HLT makes Windows 95 - // crashy when the APM driver is active! There's something within - // the Win95 kernel that apparently screws up really badly if - // the APM IDLE call returns immediately. The best case scenario - // seems to be that Win95's APM driver has some sort of timing - // logic to it that if it detects an immediate return, immediately - // shuts down and powers off the machine. Windows 98 also seems - // to require a HLT, and will act erratically without it. - // - // Also need to note that the choice of "HLT" is not arbitrary - // at all. The APM BIOS standard mentions CPU IDLE either stopping - // the CPU clock temporarily or issuing HLT as a valid method. - // - // TODO: Make this a dosbox-x.conf configuration option: what do we do - // on APM idle calls? Allow selection between "nothing" "hlt" - // and "software delay". - if (!(reg_flags&0x200)) { - LOG(LOG_BIOS,LOG_WARN)("APM BIOS warning: CPU IDLE called with IF=0, not HLTing\n"); - } - else if (cpudecoder == &HLT_Decode) { /* do not re-execute HLT, it makes DOSBox-X hang */ - LOG_MSG("APM BIOS warning: CPU IDLE HLT within HLT (DOSBox-X core failure)\n"); - } - else { - CPU_HLT(reg_eip); - } - break; - case 0x06: // CPU BUSY - if(!apm_realmode_connected) { - reg_ah = 0x03; - CALLBACK_SCF(true); - break; - } - - /* OK. whatever. system no longer idle */ - CALLBACK_SCF(false); - break; - case 0x07: - if(reg_bx != 0x1) { - reg_ah = 0x09; // wrong device ID - CALLBACK_SCF(true); - break; - } - if(!apm_realmode_connected) { - reg_ah = 0x03; - CALLBACK_SCF(true); - break; - } - switch(reg_cx) { - case 0x1: // standby - LOG(LOG_MISC,LOG_DEBUG)("Guest attempted to set power state to standby"); - APM_BeginSuspendedMode(); - reg_ah = 0x00;//TODO - CALLBACK_SCF(false); - APM_ResumeNotificationFromStandby = true; - break; - case 0x2: // suspend - LOG(LOG_MISC,LOG_DEBUG)("Guest attempted to set power state to suspend"); - APM_BeginSuspendedMode(); - reg_ah = 0x00;//TODO - CALLBACK_SCF(false); - APM_ResumeNotificationFromSuspend = true; - break; - case 0x3: // power off - throw 0; - case 0x4: // last request processing notification (used by Windows ME) - LOG(LOG_MISC,LOG_DEBUG)("Guest is considering whether to accept the last returned APM event"); - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x5: // reject last request (used by Windows ME) - LOG(LOG_MISC,LOG_DEBUG)("Guest has rejected the last APM event"); - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - default: - reg_ah = 0x0A; // invalid parameter value in CX - CALLBACK_SCF(true); - break; - } - break; - case 0x08: // ENABLE/DISABLE POWER MANAGEMENT - if(reg_bx != 0x0 && reg_bx != 0x1) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } else if(!apm_realmode_connected) { - reg_ah = 0x03; - CALLBACK_SCF(true); - break; - } - if(reg_cx==0x0) LOG_MSG("disable APM for device %4x",reg_bx); - else if(reg_cx==0x1) LOG_MSG("enable APM for device %4x",reg_bx); - else { - reg_ah = 0x0A; // invalid parameter value in CX - CALLBACK_SCF(true); - } - break; - case 0x0a: // GET POWER STATUS - if (!apm_realmode_connected) { - reg_ah = 0x03; // interface not connected - CALLBACK_SCF(true); - break; - } - if (reg_bx != 0x0001 && reg_bx != 0x8001) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } - /* FIXME: Allow configuration and shell commands to dictate whether or - * not we emulate a laptop with a battery */ - reg_bh = 0x01; // AC line status (1=on-line) - reg_bl = 0xFF; // Battery status (unknown) - reg_ch = 0x80; // Battery flag (no system battery) - reg_cl = 0xFF; // Remaining battery charge (unknown) - reg_dx = 0xFFFF; // Remaining battery life (unknown) - reg_si = 0; // Number of battery units (if called with reg_bx == 0x8001) - CALLBACK_SCF(false); - break; - case 0x0b: // GET PM EVENT - if (!apm_realmode_connected) { - reg_ah = 0x03; // interface not connected - CALLBACK_SCF(true); - break; - } - // power button? - if (PowerButtonClicks != 0) { // Hardware and BIOSes probably just set a bit somewhere, so act like it - LOG(LOG_MISC,LOG_DEBUG)("Returning APM power button event to guest OS"); - reg_ah = 0x00; // FIXME: The standard doesn't say anything about AH on success - - if (APM_PowerButtonSendsSuspend) - reg_bx = 0x000A;// user pushed a button, wants to suspend the system - else - reg_bx = 0x0009;// user pushed a button, wants to put the system into standby - - reg_cx = 0x0000; - CALLBACK_SCF(false); - PowerButtonClicks = 0; - break; - } - // resume from standby? Windows 98 will spin in a loop for 5+ seconds until it gets this APM message after suspend - if (APM_ResumeNotificationFromStandby) { - LOG(LOG_MISC,LOG_DEBUG)("Returning APM resume from standby notification event to guest OS"); - reg_ah = 0x00; // FIXME: The standard doesn't say anything about AH on success - reg_bx = 0x000B;// System Standby Resume Notification - reg_cx = 0x0000; - CALLBACK_SCF(false); - APM_ResumeNotificationFromStandby = false; - break; - } - // resume from suspend? Windows 98 will spin in a loop for 5+ seconds until it gets this APM message after suspend - if (APM_ResumeNotificationFromSuspend) { - LOG(LOG_MISC,LOG_DEBUG)("Returning APM resume from suspend notification event to guest OS"); - reg_ah = 0x00; // FIXME: The standard doesn't say anything about AH on success - reg_bx = 0x0003;// Normal Resume System Notification - reg_cx = 0x0000; - CALLBACK_SCF(false); - APM_ResumeNotificationFromSuspend = false; - break; - } - // nothing - reg_ah = 0x80; // no power management events pending - CALLBACK_SCF(true); - break; - case 0x0d: - // NTS: NOT implementing this call can cause Windows 98's APM driver to crash on startup - if(reg_bx != 0x0 && reg_bx != 0x1) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } else if(!apm_realmode_connected) { - reg_ah = 0x03; - CALLBACK_SCF(true); - break; - } - if(reg_cx==0x0) { - LOG_MSG("disable APM for device %4x",reg_bx); - CALLBACK_SCF(false); - } - else if(reg_cx==0x1) { - LOG_MSG("enable APM for device %4x",reg_bx); - CALLBACK_SCF(false); - } - else { - reg_ah = 0x0A; // invalid parameter value in CX - CALLBACK_SCF(true); - } - break; - case 0x0e: - if (APM_BIOS_minor_version != 0) { // APM 1.1 or higher only - if(reg_bx != 0x0) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } else if(!apm_realmode_connected) { - reg_ah = 0x03; // interface not connected - CALLBACK_SCF(true); - break; - } - reg_ah = reg_ch; /* we are called with desired version in CH,CL, return actual version in AH,AL */ - reg_al = reg_cl; - if(reg_ah != 1) reg_ah = 1; // major - if(reg_al > APM_BIOS_minor_version) reg_al = APM_BIOS_minor_version; // minor - APM_BIOS_connected_minor_version = reg_al; // what we decided becomes the interface we emulate - LOG_MSG("APM BIOS negotiated to v1.%u",APM_BIOS_connected_minor_version); - CALLBACK_SCF(false); - } - else { // APM 1.0 does not recognize this call - reg_ah = 0x0C; // function not supported - CALLBACK_SCF(true); - } - break; - case 0x0f: - if(reg_bx != 0x0 && reg_bx != 0x1) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } else if(!apm_realmode_connected) { - reg_ah = 0x03; - CALLBACK_SCF(true); - break; - } - if(reg_cx==0x0) { - LOG_MSG("disengage APM for device %4x",reg_bx); - CALLBACK_SCF(false); - } - else if(reg_cx==0x1) { - LOG_MSG("engage APM for device %4x",reg_bx); - CALLBACK_SCF(false); - } - else { - reg_ah = 0x0A; // invalid parameter value in CX - CALLBACK_SCF(true); - } - break; - case 0x10: - if (!apm_realmode_connected) { - reg_ah = 0x03; // interface not connected - CALLBACK_SCF(true); - break; - } - if (reg_bx != 0) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } - reg_ah = 0; - reg_bl = 0; // number of battery units - reg_cx = 0x03; // can enter suspend/standby and will post standby/resume events - CALLBACK_SCF(false); - break; - case 0x13://enable/disable/query timer based requests - // NTS: NOT implementing this call can cause Windows 98's APM driver to crash on startup - if (!apm_realmode_connected) { - reg_ah = 0x03; // interface not connected - CALLBACK_SCF(true); - break; - } - if (reg_bx != 0) { - reg_ah = 0x09; // unrecognized device ID - CALLBACK_SCF(true); - break; - } - - if (reg_cx == 0) { // disable - APM_inactivity_timer = false; - reg_cx = 0; - CALLBACK_SCF(false); - } - else if (reg_cx == 1) { // enable - APM_inactivity_timer = true; - reg_cx = 1; - CALLBACK_SCF(false); - } - else if (reg_cx == 2) { // get enabled status - reg_cx = APM_inactivity_timer ? 1 : 0; - CALLBACK_SCF(false); - } - else { - reg_ah = 0x0A; // invalid parameter value in CX - CALLBACK_SCF(true); - } - break; - default: - LOG_MSG("Unknown APM BIOS call AX=%04x\n",reg_ax); - if (!apm_realmode_connected) { - reg_ah = 0x03; // interface not connected - CALLBACK_SCF(true); - break; - } - reg_ah = 0x0C; // function not supported - CALLBACK_SCF(true); - break; - } - } - else { - reg_ah=0x86; - CALLBACK_SCF(true); - LOG_MSG("APM BIOS call attempted. set apmbios=1 if you want power management\n"); - if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { - /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ - CALLBACK_SZF(false); - } - } - break; - case 0xe8: - switch (reg_al) { - case 0x01: { /* E801: memory size */ - Bitu sz = MEM_TotalPages()*4; - if (sz >= 1024) sz -= 1024; - else sz = 0; - reg_ax = reg_cx = (sz > 0x3C00) ? 0x3C00 : sz; /* extended memory between 1MB and 16MB in KBs */ - sz -= reg_ax; - sz /= 64; /* extended memory size from 16MB in 64KB blocks */ - if (sz > 65535) sz = 65535; - reg_bx = reg_dx = sz; - CALLBACK_SCF(false); - } - break; - case 0x20: { /* E820: MEMORY LISTING */ - if (reg_edx == 0x534D4150 && reg_ecx >= 20 && (MEM_TotalPages()*4) >= 24000) { - /* return a minimalist list: - * - * 0) 0x000000-0x09EFFF Free memory - * 1) 0x0C0000-0x0FFFFF Reserved - * 2) 0x100000-... Free memory (no ACPI tables) */ - if (reg_ebx < E280_table_entries) { - BIOS_E280_entry &ent = E280_table[reg_ebx]; - Bitu seg = SegValue(es); - - /* write to ES:DI */ - real_writed(seg,reg_di+0x00,ent.base); - real_writed(seg,reg_di+0x04,(uint32_t)(ent.base >> (uint64_t)32u)); - real_writed(seg,reg_di+0x08,ent.length); - real_writed(seg,reg_di+0x0C,(uint32_t)(ent.length >> (uint64_t)32u)); - real_writed(seg,reg_di+0x10,ent.type); - reg_ecx = 20; - - /* return EBX pointing to next entry. wrap around, as most BIOSes do. - * the program is supposed to stop on CF=1 or when we return EBX == 0 */ - if (++reg_ebx >= E280_table_entries) reg_ebx = 0; - } - else { - CALLBACK_SCF(true); - } - - reg_eax = 0x534D4150; - } - else { - reg_eax = 0x8600; - CALLBACK_SCF(true); - } - } - break; - default: - unhandled: - LOG(LOG_BIOS,LOG_ERROR)("INT15:Unknown call ah=E8, al=%2X",reg_al); - reg_ah=0x86; - CALLBACK_SCF(true); - if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { - /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ - CALLBACK_SZF(false); - } - } - break; - case 0x50: - if(isDBCSCP()) { - if(reg_al == 0x00) { - if(reg_bl == 0x00 && reg_bp == 0x00) { - enum DOSV_FONT font = DOSV_FONT_MAX; - if(reg_bh & 0x01) { - if(reg_dh == 16 && reg_dl == 16) { - font = DOSV_FONT_16X16; - } else if(reg_dh == 24 && reg_dl == 24) { - font = DOSV_FONT_24X24; - } - } else { - if(reg_dh == 8) { - if(reg_dl == 16) { - font = DOSV_FONT_8X16; - } else if(reg_dl == 19) { - font = DOSV_FONT_8X19; - } - } else if(reg_dh == 12 && reg_dl == 24) { - font = DOSV_FONT_12X24; - } - } - if(font != DOSV_FONT_MAX) { - reg_ah = 0x00; - SegSet16(es, CB_SEG); - reg_bx = DOSV_GetFontHandlerOffset(font); - CALLBACK_SCF(false); - break; - } - } - } else if(reg_al == 0x01) { - if(reg_dh == 16 && reg_dl == 16) { - reg_ah = 0x00; - SegSet16(es, CB_SEG); - reg_bx = DOSV_GetFontHandlerOffset(DOSV_FONT_16X16_WRITE); - CALLBACK_SCF(false); - break; - } else if(reg_dh == 24 && reg_dl == 24) { - reg_ah = 0x00; - SegSet16(es, CB_SEG); - reg_bx = DOSV_GetFontHandlerOffset(DOSV_FONT_24X24_WRITE); - CALLBACK_SCF(false); - break; - } else { - reg_ah = 0x06; // read only - } - } - CALLBACK_SCF(true); - } - break; - case 0x49: - if(isDBCSCP()) { - reg_ah = 0x00; - reg_bl = 0x00; - CALLBACK_SCF(false); - } else { - CALLBACK_SCF(true); - } - break; - default: - LOG(LOG_BIOS,LOG_ERROR)("INT15:Unknown call ax=%4X",reg_ax); - reg_ah=0x86; - CALLBACK_SCF(true); - if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA) || (machine==MCH_AMSTRAD)) { - /* relict from comparisons, as int15 exits with a retf2 instead of an iret */ - CALLBACK_SZF(false); - } - } - return CBRET_NONE; -} - -void BIOS_UnsetupKeyboard(void); -void BIOS_SetupKeyboard(void); -void BIOS_UnsetupDisks(void); -void BIOS_SetupDisks(void); -void CPU_Snap_Back_To_Real_Mode(); -void CPU_Snap_Back_Restore(); - -static Bitu Default_IRQ_Handler(void) { - IO_WriteB(0x20, 0x0b); - uint8_t master_isr = IO_ReadB(0x20); - if (master_isr) { - IO_WriteB(0xa0, 0x0b); - uint8_t slave_isr = IO_ReadB(0xa0); - if (slave_isr) { - IO_WriteB(0xa1, IO_ReadB(0xa1) | slave_isr); - IO_WriteB(0xa0, 0x20); - } - else IO_WriteB(0x21, IO_ReadB(0x21) | (master_isr & ~4)); - IO_WriteB(0x20, 0x20); -#if C_DEBUG - uint16_t irq = 0; - uint16_t isr = master_isr; - if (slave_isr) isr = slave_isr << 8; - while (isr >>= 1) irq++; - LOG(LOG_BIOS, LOG_WARN)("Unexpected IRQ %u", irq); -#endif - } - else master_isr = 0xff; - mem_writeb(BIOS_LAST_UNEXPECTED_IRQ, master_isr); - return CBRET_NONE; -} - -static Bitu IRQ14_Dummy(void) { - /* FIXME: That's it? Don't I EOI the PIC? */ - return CBRET_NONE; -} - -static Bitu IRQ15_Dummy(void) { - /* FIXME: That's it? Don't I EOI the PIC? */ - return CBRET_NONE; -} - -void On_Software_CPU_Reset(); - -static Bitu INT18_Handler(void) { - if (ibm_rom_basic_size != 0) { - /* jump to BASIC (usually F600:0000 for IBM 5150 ROM BASIC) */ - SegSet16(cs, ibm_rom_basic_base >> 4); - reg_eip = 0; - } - else { - LOG_MSG("Restart by INT 18h requested\n"); - On_Software_CPU_Reset(); - /* does not return */ - } - return CBRET_NONE; -} - -static Bitu INT19_Handler(void) { - LOG_MSG("Restart by INT 19h requested\n"); - /* FIXME: INT 19h is sort of a BIOS boot BIOS reset-ish thing, not really a CPU reset at all. */ - On_Software_CPU_Reset(); - /* does not return */ - return CBRET_NONE; -} - -void bios_enable_ps2() { - mem_writew(BIOS_CONFIGURATION, - mem_readw(BIOS_CONFIGURATION)|0x04); /* PS/2 mouse */ -} - -void BIOS_ZeroExtendedSize(bool in) { - if(in) other_memsystems++; - else other_memsystems--; - if(other_memsystems < 0) other_memsystems=0; - - if (IS_PC98_ARCH) { - Bitu mempages = MEM_TotalPages(); /* in 4KB pages */ - - /* What applies to IBM PC/AT (zeroing out the extended memory size) - * also applies to PC-98, when HIMEM.SYS is loaded */ - if (in) mempages = 0; - - /* extended memory size (286 systems, below 16MB) */ - if (mempages > (1024UL/4UL)) { - unsigned int ext = ((mempages - (1024UL/4UL)) * 4096UL) / (128UL * 1024UL); /* convert to 128KB units */ - - /* extended memory, up to 16MB capacity (for 286 systems?) - * - * MS-DOS drivers will "allocate" for themselves by taking from the top of - * extended memory then subtracting from this value. - * - * capacity does not include conventional memory below 1MB, nor any memory - * above 16MB. - * - * PC-98 systems may reserve the top 1MB, limiting the top to 15MB instead, - * for the ISA memory hole needed for DOS games that use the 256-color linear framebuffer. - * - * 0x70 = 128KB * 0x70 = 14MB - * 0x78 = 128KB * 0x70 = 15MB */ - if (isa_memory_hole_15mb) { - if (ext > 0x70) ext = 0x70; - } - else { - if (ext > 0x78) ext = 0x78; - } - - mem_writeb(0x401,ext); - } - else { - mem_writeb(0x401,0x00); - } - - /* extended memory size (386 systems, at or above 16MB) */ - if (mempages > ((1024UL*16UL)/4UL)) { - unsigned int ext = ((mempages - ((1024UL*16UL)/4UL)) * 4096UL) / (1024UL * 1024UL); /* convert to MB */ - - /* extended memory, at or above 16MB capacity (for 386+ systems?) - * - * MS-DOS drivers will "allocate" for themselves by taking from the top of - * extended memory then subtracting from this value. - * - * capacity does not include conventional memory below 1MB, nor any memory - * below 16MB. */ - if (ext > 0xFFFE) ext = 0xFFFE; - - mem_writew(0x594,ext); - } - else { - mem_writew(0x594,0x00); - } - } -} - -unsigned char do_isapnp_chksum(const unsigned char* d, int i) { - unsigned char sum = 0; - - while (i-- > 0) - sum += *d++; - - return (0x100 - sum) & 0xFF; -} - -void MEM_ResetPageHandler_Unmapped(Bitu phys_page, Bitu pages); - -unsigned int dos_conventional_limit = 0; - -bool AdapterROM_Read(Bitu address,unsigned long *size) { - unsigned char c[3]; - unsigned int i; - - if ((address & 0x1FF) != 0) { - LOG(LOG_MISC,LOG_DEBUG)("AdapterROM_Read: Caller attempted ROM scan not aligned to 512-byte boundary"); - return false; - } - - for (i=0;i < 3;i++) - c[i] = mem_readb(address+i); - - if (c[0] == 0x55 && c[1] == 0xAA) { - unsigned char chksum=0; - *size = (unsigned long)c[2] * 512UL; - for (i=0;i < (unsigned int)(*size);i++) chksum += mem_readb(address+i); - if (chksum != 0) { - LOG(LOG_MISC,LOG_WARN)("AdapterROM_Read: Found ROM at 0x%lx but checksum failed (got %02xh expect %02xh)\n",(unsigned long)address,chksum,0); - return false; - } - - return true; - } - - return false; -} - -static int bios_pc98_posx = 0; -extern bool tooutttf; - -static void BIOS_Int10RightJustifiedPrint(const int x,int &y,const char *msg, bool boxdraw = false, bool tobold = false) { - if (tooutttf) { - tooutttf = false; - change_output(10); - } - if (control->opt_fastlaunch) return; - const char *s = msg; - if (machine != MCH_PC98) { - unsigned int bold = 0; - while (*s != 0) { - if (*s == '\n') { - y++; - reg_eax = 0x0200u; // set cursor pos - reg_ebx = 0; // page zero - reg_dh = y; // row 4 - reg_dl = x; // column 20 - CALLBACK_RunRealInt(0x10); - s++; - } - else { - if (tobold&&!bold) { - if ((strlen(s)>3&&!strncmp(s, "DEL", 3))||!strncmp(s, "ESC", 3)) bold = 3; - else if (strlen(s)>5&&!strncmp(s, "ENTER", 5)) bold = 5; - else if (strlen(s)>8&&!strncmp(s, "SPACEBAR", 8)) bold = 8; - } - if (bold>0) { - bold--; - reg_eax = 0x0900u | ((unsigned char)(*s++)); - reg_ebx = 0x000fu; - reg_ecx = 0x0001u; - CALLBACK_RunRealInt(0x10); - reg_eax = 0x0300u; - reg_ebx = 0x0000u; - CALLBACK_RunRealInt(0x10); - reg_eax = 0x0200u; - reg_ebx = 0x0000u; - reg_edx++; - CALLBACK_RunRealInt(0x10); - } else { - reg_eax = 0x0E00u | ((unsigned char)(*s++)); - reg_ebx = 0x07u; - CALLBACK_RunRealInt(0x10); - } - } - } - } - else { - unsigned int bo; - - while (*s != 0) { - if (*s == '\n') { - y++; - s++; - bios_pc98_posx = x; - - bo = (((unsigned int)y * 80u) + (unsigned int)bios_pc98_posx) * 2u; - } - else if (*s == '\r') { - s++; /* ignore */ - continue; - } - else { - bo = (((unsigned int)y * 80u) + (unsigned int)(bios_pc98_posx++)) * 2u; /* NTS: note the post increment */ - if (boxdraw) { - unsigned int ch = (unsigned char)*s; - if (ch==0xcd) ch = 0x250B; - else if (ch==0xba) ch = 0x270B; - else if (ch==0xc9) ch = 0x330B; - else if (ch==0xbb) ch = 0x370B; - else if (ch==0xc8) ch = 0x3B0B; - else if (ch==0xbc) ch = 0x3F0B; - mem_writew(0xA0000+bo,ch); - } else - mem_writew(0xA0000+bo,(unsigned char)*s); - mem_writeb(0xA2000+bo,0xE1); - - s++; - bo += 2; /* and keep the cursor following the text */ - } - - reg_eax = 0x1300; // set cursor pos (PC-98) - reg_edx = bo; // byte position - CALLBACK_RunRealInt(0x18); - } - } -} - -char *getSetupLine(const char *capt, const char *cont) { - unsigned int pad1=(unsigned int)(25-strlen(capt)), pad2=(unsigned int)(41-strlen(cont)); - static char line[90]; - sprintf(line, "\x0ba%*c%s%*c%s%*c\x0ba", 12, ' ', capt, pad1, ' ', cont, pad2, ' '); - return line; -} - -const char *GetCPUType(); -void updateDateTime(int x, int y, int pos) -{ - (void)x;//UNUSED - (void)y;//UNUSED - char str[50]; - time_t curtime = time(NULL); - struct tm *loctime = localtime (&curtime); - Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; - unsigned int sec=(uint8_t)((Bitu)time % 60); - time/=60; - unsigned int min=(uint8_t)((Bitu)time % 60); - time/=60; - unsigned int hour=(uint8_t)((Bitu)time % 24); - int val=0; - unsigned int bo; - Bitu edx=0, pdx=0x0500u; - for (int i=1; i<7; i++) { - switch (i) { - case 1: - val = machine==MCH_PC98?loctime->tm_year+1900:dos.date.year; - reg_edx = 0x0326u; - if (i==pos) pdx = reg_edx; - break; - case 2: - val = machine==MCH_PC98?loctime->tm_mon+1:dos.date.month; - reg_edx = 0x032bu; - if (i==pos) pdx = reg_edx; - break; - case 3: - val = machine==MCH_PC98?loctime->tm_mday:dos.date.day; - reg_edx = 0x032eu; - if (i==pos) pdx = reg_edx; - break; - case 4: - val = machine==MCH_PC98?loctime->tm_hour:hour; - reg_edx = 0x0426u; - if (i==pos) pdx = reg_edx; - break; - case 5: - val = machine==MCH_PC98?loctime->tm_min:min; - reg_edx = 0x0429u; - if (i==pos) pdx = reg_edx; - break; - case 6: - val = machine==MCH_PC98?loctime->tm_sec:sec; - reg_edx = 0x042cu; - if (i==pos) pdx = reg_edx; - break; - } - edx = reg_edx; - sprintf(str, i==1?"%04u":"%02u",val); - for (unsigned int j=0; jopt_securemode || control->SecureMode()) - strcpy(pcname, "N/A"); - else { -#if defined(WIN32) - DWORD size = DOSNAMEBUF; - GetComputerName(pcname, &size); - if (!size) -#else - int result = gethostname(pcname, DOSNAMEBUF); - if (result) -#endif - strcpy(pcname, "N/A"); - } - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Computer name:", pcname), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Product name:", ("DOSBox-X "+std::string(VERSION)).c_str()), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Product updated:", UPDATED_STR), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS description:", bios_type_string), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS version:", bios_version_string), true); - uint32_t year,month,day; - if (sscanf(bios_date_string,"%u/%u/%u",&month,&day,&year)==3) { - char datestr[30]; - sprintf(datestr, "%04u-%02u-%02u",year<80?2000+year:(year<100?1900+year:year),month,day); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS date:", datestr), true); - } else - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("BIOS date:", bios_date_string), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Processor type:", GetCPUType()), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Processor speed:", (std::to_string(CPU_CycleAutoAdjust?CPU_CyclePercUsed:CPU_CycleMax)+(CPU_CycleAutoAdjust?"%":" cycles/ms")).c_str()), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Coprocessor:", enable_fpu?"Yes":"No"), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Video card:", card), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Video memory:", (std::to_string(vga.mem.memsize/1024)+"K").c_str()), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("Total memory:", (std::to_string(MEM_TotalPages()*4096/1024)+"K").c_str()), true); - BIOS_Int10RightJustifiedPrint(x,y,getSetupLine("", ""), true); - BIOS_Int10RightJustifiedPrint(x,y,"\x0c8\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0cd\x0bc", true); - if (machine == MCH_PC98) - BIOS_Int10RightJustifiedPrint(x,y," ESC = Exit "); - else - BIOS_Int10RightJustifiedPrint(x,y," ESC: Exit Arrows: Select Item +/-: Change Values "); -} - -static Bitu ulimit = 0; -static Bitu t_conv = 0; -static Bitu t_conv_real = 0; -static bool bios_first_init=true; -static bool bios_has_exec_vga_bios=false; -static Bitu adapter_scan_start; - -/* FIXME: At global scope their destructors are called after the rest of DOSBox-X has shut down. Move back into BIOS scope. */ -static CALLBACK_HandlerObject int4b_callback; -static const size_t callback_count = 20; -static CALLBACK_HandlerObject callback[callback_count]; /* <- fixme: this is stupid. just declare one per interrupt. */ -static CALLBACK_HandlerObject cb_bios_post; -static CALLBACK_HandlerObject callback_pc98_lio; -static CALLBACK_HandlerObject callback_pc98_avspcm; - -Bitu call_pnp_r = ~0UL; -Bitu call_pnp_rp = 0; - -Bitu call_pnp_p = ~0UL; -Bitu call_pnp_pp = 0; - -Bitu isapnp_biosstruct_base = 0; - -Bitu BIOS_boot_code_offset = 0; -Bitu BIOS_bootfail_code_offset = 0; - -bool bios_user_reset_vector_blob_run = false; -Bitu bios_user_reset_vector_blob = 0; - -Bitu bios_user_boot_hook = 0; - -void CALLBACK_DeAllocate(Bitu in); - -void BIOS_OnResetComplete(Section *x); - -Bitu call_irq0 = 0; -Bitu call_irq07default = 0; -Bitu call_irq815default = 0; - + if (s == "true" || s == "1") + isa_memory_hole_512kb = true; + else if (s == "false" || s == "0") + isa_memory_hole_512kb = false; + else + isa_memory_hole_512kb = false; + } -/* NEC PC-98 detection notes: - * - Documented: No ASCII date at F000:FFF5 - * - CWSDPMI (PC-98 patched version): Call INT 10h AH=0F BH=FF. If registers don't change, it's PC-98 - * - DJGPP libc, crt1.c (PC-98 patched version): If the WORD at F000:FFF3 (segment part of JMP FAR) is 0xFD80, it's PC-98 */ + // TODO: motherboard init, especially when we get around to full Intel Triton/i440FX chipset emulation + { + std::string s = section->Get_string("isa memory hole at 15mb"); -void write_FFFF_PC98_signature() { - /* this may overwrite the existing signature. - * PC-98 systems DO NOT have an ASCII date at F000:FFF5 - * and the WORD value at F000:FFFE is said to be a checksum of the BIOS */ - - // The farjump at the processor reset entry point (jumps to POST routine) - phys_writeb(0xffff0,0xEA); // FARJMP + // Do NOT emulate the memory hole if emulating 24 or less address bits! BIOS crashes will result at startup! + // The whole point of the 15MB memory hole is to emulate a hole into hardware as if a 24-bit 386SX. A memalias + // setting of 24 makes it redundant. Furthermore memalias=24 and 15MB memory hole prevents the BIOS from + // mapping correctly and crashes immediately at startup. This is especially necessary for PC-98 mode where + // memalias==24 and memory hole enabled for the PEGC linear framebuffer prevents booting. - /* Segment value must be 0xFD80 to satisfy PC-98 patched DJGPP check */ - const uint16_t oseg = RealSeg(BIOS_DEFAULT_RESET_LOCATION); - phys_writew(0xffff1,RealOff(BIOS_DEFAULT_RESET_LOCATION)-((0xFD80-oseg)*16)); // offset - phys_writew(0xffff3,0xFD80); // segment - - // write nothing (not used) - for(Bitu i = 0; i < 9; i++) phys_writeb(0xffff5+i,0); - - // fake BIOS checksum - phys_writew(0xffffe,0xABCD); -} - -void gdc_egc_enable_update_vars(void) { - unsigned char b; - - b = mem_readb(0x54D); - b &= ~0x40; - if (enable_pc98_egc) b |= 0x40; - mem_writeb(0x54D,b); - - b = mem_readb(0x597); - b &= ~0x04; - if (enable_pc98_egc) b |= 0x04; - mem_writeb(0x597,b); - - if (!enable_pc98_egc) - pc98_gdc_vramop &= ~(1 << VOPBIT_EGC); -} - -void gdc_grcg_enable_update_vars(void) { - unsigned char b; - - b = mem_readb(0x54C); - b &= ~0x02; - if (enable_pc98_grcg) b |= 0x02; - mem_writeb(0x54C,b); - - //TODO: How to reset GRCG? -} - - -void gdc_16color_enable_update_vars(void) { - unsigned char b; - - b = mem_readb(0x54C); - b &= ~0x05; - if (enable_pc98_16color) b |= 0x05; // bit0 .. DIPSW 1-8 support GLIO 16-colors - mem_writeb(0x54C,b); - - if(!enable_pc98_256color) {//force switch to 16-colors mode - void pc98_port6A_command_write(unsigned char b); - pc98_port6A_command_write(0x20); - } - if(!enable_pc98_16color) {//force switch to 8-colors mode - void pc98_port6A_command_write(unsigned char b); - pc98_port6A_command_write(0x00); - } -} - -uint32_t BIOS_get_PC98_INT_STUB(void) { - return callback[18].Get_RealPointer(); -} - -Bitu call_pc98_default_stop; - -extern bool DOS_BreakFlag; -extern bool DOS_BreakConioFlag; - -static Bitu pc98_default_stop_handler(void) { - // INT 06h, which means someone pressed the STOP key... or the CPU is signalling an invalid opcode. - // The overlap makes it extremely unclear. - LOG_MSG("Invalid opcode or unhandled PC-98 STOP key interrupt 06h"); - - // try to make it work as CTRL+BREAK in the built-in DOS environment. - if (!dos_kernel_disabled) - DOS_BreakFlag = DOS_BreakConioFlag = true; - - return CBRET_NONE; -} - -static unsigned char BCD2BIN(unsigned char x) { - return ((x >> 4) * 10) + (x & 0xF); -} - - -/* NTS: Remember the 8259 is non-sentient, and the term "slave" is used in a computer programming context */ -static Bitu Default_IRQ_Handler_Cooperative_Slave_Pic(void) { - /* PC-98 style IRQ 8-15 handling. - * - * This mimics the recommended procedure [https://www.webtech.co.jp/company/doc/undocumented_mem/io_pic.txt] - * - * mov al,20h ;Send EOI to SLAVE - * out 0008h,al - * jmp $+2 ;I/O WAIT - * mov al,0Bh ;ISR read mode set(slave) - * out 0008h,al - * jmp $+2 ;I/O WAIT - * in al,0008h ;ISR read(slave) - * cmp al,00h ;slave pic in-service ? - * jne EoiEnd - * mov al,20h ;Send EOI to MASTER - * out 0000h,al - */ - IO_WriteB(IS_PC98_ARCH ? 0x08 : 0xA0,0x20); // send EOI to slave - IO_WriteB(IS_PC98_ARCH ? 0x08 : 0xA0,0x0B); // ISR read mode set - if (IO_ReadB(IS_PC98_ARCH ? 0x08 : 0xA0) == 0) // if slave pic in service.. - IO_WriteB(IS_PC98_ARCH ? 0x00 : 0x20,0x20); // then EOI the master - - return CBRET_NONE; -} - -extern uint32_t tandy_128kbase; - -static int bios_post_counter = 0; - -extern void BIOSKEY_PC98_Write_Tables(void); -extern Bitu PC98_AVSDRV_PCM_Handler(void); - -static unsigned int acpiptr2ofs(unsigned char *w) { - return w - ACPI_buffer; -} - -static PhysPt acpiofs2phys(unsigned int o) { - return ACPI_BASE + o; -} - -class ACPISysDescTableWriter { -public: - ACPISysDescTableWriter(); - ~ACPISysDescTableWriter(void); -public: - ACPISysDescTableWriter &begin(unsigned char *w,unsigned char *f,size_t n_tablesize=36); - ACPISysDescTableWriter &setRev(const unsigned char rev); - ACPISysDescTableWriter &setOemID(const char *id); - ACPISysDescTableWriter &setSig(const char *sig); - ACPISysDescTableWriter &setOemTableID(const char *id); - ACPISysDescTableWriter &setOemRev(const uint32_t rev); - ACPISysDescTableWriter &setCreatorID(const uint32_t id); - ACPISysDescTableWriter &setCreatorRev(const uint32_t rev); - ACPISysDescTableWriter &expandto(size_t sz); - unsigned char* getptr(size_t ofs=0,size_t sz=1); - size_t get_tablesize(void) const; - unsigned char* finish(void); -private: - size_t tablesize = 0; - unsigned char* base = NULL; - unsigned char* f = NULL; -}; - -size_t ACPISysDescTableWriter::get_tablesize(void) const { - return tablesize; -} - -ACPISysDescTableWriter::ACPISysDescTableWriter() { -} - -ACPISysDescTableWriter::~ACPISysDescTableWriter(void) { - if (tablesize != 0) LOG(LOG_MISC,LOG_ERROR)("ACPI table writer destructor called without completing a table"); -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::begin(unsigned char *n_w,unsigned char *n_f,size_t n_tablesize) { - if (tablesize != 0) LOG(LOG_MISC,LOG_ERROR)("ACPI table writer asked to begin a table without completing the last table"); - base = n_w; - f = n_f; - tablesize = n_tablesize; - assert(tablesize >= 36); - assert((base+tablesize) <= f); - assert(base != NULL); - assert(f != NULL); - assert(base < f); - - memset(base,0,tablesize); - memcpy(base+10,"DOSBOX",6); // OEM ID - memcpy(base+16,"DOSBox-X",8); // OEM Table ID - host_writed(base+24,1); // OEM revision - memcpy(base+28,"DBOX",4); // Creator ID - host_writed(base+32,1); // Creator revision - - return *this; -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::setRev(const unsigned char rev) { - assert(base != NULL); - assert(tablesize >= 36); - base[8] = rev; - return *this; -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::setOemID(const char *id) { - assert(id != NULL); - assert(base != NULL); - assert(tablesize >= 36); - unsigned char *wp = base+10; - for (unsigned int i=0;i < 6;i++) { - if (*id != 0) - *wp++ = (unsigned char)(*id++); - else - *wp++ = ' '; - } - return *this; -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::setSig(const char *sig) { - assert(sig != NULL); - assert(base != NULL); - assert(tablesize >= 36); - unsigned char *wp = base; - for (unsigned int i=0;i < 4;i++) { - if (*sig != 0) - *wp++ = (unsigned char)(*sig++); - else - *wp++ = ' '; - } - return *this; -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::setOemTableID(const char *id) { - assert(id != NULL); - assert(base != NULL); - assert(tablesize >= 36); - unsigned char *wp = base+16; - for (unsigned int i=0;i < 8;i++) { - if (*id != 0) - *wp++ = (unsigned char)(*id++); - else - *wp++ = ' '; - } - return *this; -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::setOemRev(const uint32_t rev) { - assert(base != NULL); - assert(tablesize >= 36); - host_writed(base+24,rev); - return *this; -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::setCreatorID(const uint32_t id) { - assert(base != NULL); - assert(tablesize >= 36); - host_writed(base+28,id); - return *this; -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::setCreatorRev(const uint32_t rev) { - assert(base != NULL); - assert(tablesize >= 36); - host_writed(base+32,rev); - return *this; -} - -ACPISysDescTableWriter &ACPISysDescTableWriter::expandto(size_t sz) { - assert(base != NULL); - assert((base+sz) <= f); - if (tablesize < sz) tablesize = sz; - return *this; -} - -unsigned char* ACPISysDescTableWriter::getptr(size_t ofs,size_t sz) { - assert(base != NULL); - assert((base+ofs+sz) <= f); - if (tablesize < (ofs+sz)) tablesize = ofs+sz; - return base+ofs; -} - -unsigned char *ACPISysDescTableWriter::finish(void) { - if (base != NULL) { - unsigned char *ret = base + tablesize; - - assert((base+tablesize) <= f); - assert(tablesize >= 36); - - /* update length field */ - host_writed(base+4,tablesize); - - /* update checksum field */ - unsigned int i,c; - base[9] = 0; - c = 0; for (i=0;i < tablesize;i++) c += base[i]; - base[9] = (0 - c) & 0xFFu; - - base = f = NULL; - tablesize = 0; - return ret; - } - - return NULL; -} - -enum class ACPIRegionSpace { - SystemMemory=0, - SystemIO=1, - PCIConfig=2, - EmbeddedControl=3, - SMBus=4 -}; - -namespace ACPIMethodFlags { - static constexpr unsigned char ArgCount(const unsigned c) { - return c&3u; - } - enum { - NotSerialized=(0 << 3), - Serialized=(1 << 3) - }; -} - -static constexpr unsigned int ACPIrtIO_16BitDecode = (1u << 0u); - -static constexpr unsigned int ACPIrtMR24_Writeable = (1u << 0u); -static constexpr unsigned int ACPIrtMR32_Writeable = (1u << 0u); - -namespace ACPIFieldFlag { - namespace AccessType { - enum { - AnyAcc=0, - ByteAcc=1, - WordAcc=2, - DwordAcc=3, - BlockAcc=4, - SMBSendRevAcc=5, - SMBQuickAcc=6 - }; - } - namespace LockRule { - enum { - NoLock=(0 << 4), - Lock=(1 << 4) - }; - } - namespace UpdateRule { - enum { - Preserve=(0 << 5), - WriteAsOnes=(1 << 5), - WriteAsZeros=(2 << 5) - }; - } -} - -enum class ACPIAMLOpcode:unsigned char { - ZeroOp = 0x00, // ACPI 1.0+ - OneOp = 0x01, // ACPI 1.0+ - - AliasOp = 0x06, // ACPI 1.0+ - - NameOp = 0x08, // ACPI 1.0+ - - BytePrefix = 0x0A, // ACPI 1.0+ - WordPrefix = 0x0B, // ACPI 1.0+ - DwordPrefix = 0x0C, // ACPI 1.0+ - StringPrefix = 0x0D, // ACPI 1.0+ - QWordPrefix = 0x0E, // ACPI 2.0+ - - ScopeOp = 0x10, // ACPI 1.0+ - BufferOP = 0x11, // ACPI 1.0+ - PackageOp = 0x12, // ACPI 1.0+ - VarPackageOp = 0x13, // ACPI 2.0+ - MethodOp = 0x14, // ACPI 1.0+ - ExternalOp = 0x15, // ACPI 6.0+ - - DualNamePrefix = 0x2E, // ACPI 1.0+ - MultiNamePrefix = 0x2F, // ACPI 1.0+ - - NameCharA = 0x41, // ACPI 1.0b+ - NameCharB = 0x42, // ACPI 1.0b+ - NameCharC = 0x43, // ACPI 1.0b+ - NameCharD = 0x44, // ACPI 1.0b+ - NameCharE = 0x45, // ACPI 1.0b+ - NameCharF = 0x46, // ACPI 1.0b+ - NameCharG = 0x47, // ACPI 1.0b+ - NameCharH = 0x48, // ACPI 1.0b+ - NameCharI = 0x49, // ACPI 1.0b+ - NameCharJ = 0x4A, // ACPI 1.0b+ - NameCharK = 0x4B, // ACPI 1.0b+ - NameCharL = 0x4C, // ACPI 1.0b+ - NameCharM = 0x4D, // ACPI 1.0b+ - NameCharN = 0x4E, // ACPI 1.0b+ - NameCharO = 0x4F, // ACPI 1.0b+ - NameCharP = 0x50, // ACPI 1.0b+ - NameCharQ = 0x51, // ACPI 1.0b+ - NameCharR = 0x52, // ACPI 1.0b+ - NameCharS = 0x53, // ACPI 1.0b+ - NameCharT = 0x54, // ACPI 1.0b+ - NameCharU = 0x55, // ACPI 1.0b+ - NameCharV = 0x56, // ACPI 1.0b+ - NameCharW = 0x57, // ACPI 1.0b+ - NameCharX = 0x58, // ACPI 1.0b+ - NameCharY = 0x59, // ACPI 1.0b+ - NameCharZ = 0x5A, // ACPI 1.0b+ - - ExtendedOperatorPrefix = 0x5B, // ACPI 1.0+ - RootNamePrefix = 0x5C, // ACPI 1.0+ - - ParentNamePrefix = 0x5E, // ACPI 1.0+ - NameChar_ = 0x5F, // ACPI 2.0+ - - Local0 = 0x60, // ACPI 1.0+ - Local1 = 0x61, // ACPI 1.0+ - Local2 = 0x62, // ACPI 1.0+ - Local3 = 0x63, // ACPI 1.0+ - Local4 = 0x64, // ACPI 1.0+ - Local5 = 0x65, // ACPI 1.0+ - Local6 = 0x66, // ACPI 1.0+ - Local7 = 0x67, // ACPI 1.0+ - Arg0 = 0x68, // ACPI 1.0+ - Arg1 = 0x69, // ACPI 1.0+ - Arg2 = 0x6A, // ACPI 1.0+ - Arg3 = 0x6B, // ACPI 1.0+ - Arg4 = 0x6C, // ACPI 1.0+ - Arg5 = 0x6D, // ACPI 1.0+ - Arg6 = 0x6E, // ACPI 1.0+ - - StoreOp = 0x70, // ACPI 1.0+ - RefOfOp = 0x71, // ACPI 1.0+ - AddOp = 0x72, // ACPI 1.0+ - ConcatOp = 0x73, // ACPI 1.0+ - SubtractOp = 0x74, // ACPI 1.0+ - IncrementOp = 0x75, // ACPI 1.0+ - DecrementOp = 0x76, // ACPI 1.0+ - MultiplyOp = 0x77, // ACPI 1.0+ - DivideOp = 0x78, // ACPI 1.0+ - ShiftLeftOp = 0x79, // ACPI 1.0+ - ShiftRightOp = 0x7A, // ACPI 1.0+ - AndOp = 0x7B, // ACPI 1.0+ - NAndOp = 0x7C, // ACPI 1.0+ - OrOp = 0x7D, // ACPI 1.0+ - NOrOp = 0x7E, // ACPI 1.0+ - XOrOp = 0x7F, // ACPI 1.0+ - NotOp = 0x80, // ACPI 1.0+ - FindSetLeftBitOp = 0x81, // ACPI 1.0+ - FindSetRightBitOp = 0x82, // ACPI 1.0+ - DerefOfOp = 0x83, // ACPI 2.0+ - ConcatResOp = 0x84, // ACPI 2.0+ - ModOp = 0x85, // ACPI 2.0+ - NotifyOp = 0x86, // ACPI 1.0+ - SizeOfOp = 0x87, // ACPI 1.0+ - IndexOp = 0x88, // ACPI 1.0+ - MatchOp = 0x89, // ACPI 1.0+ - DWordFieldOp = 0x8A, // ACPI 1.0+ - CreateDWordFieldOp = 0x8A, // ACPI 1.0b+ - WordFieldOp = 0x8B, // ACPI 1.0+ - CreateWordFieldOp = 0x8B, // ACPI 1.0b+ - ByteFieldOp = 0x8C, // ACPI 1.0+ - CreateByteFieldOp = 0x8C, // ACPI 1.0b+ - BitFieldOp = 0x8D, // ACPI 1.0+ - CreateBitFieldOp = 0x8D, // ACPI 1.0b+ - ObjTypeOp = 0x8E, // ACPI 1.0+ - CreateQWordField = 0x8F, // ACPI 2.0+ - LAndOp = 0x90, // ACPI 1.0+ - LOrOp = 0x91, // ACPI 1.0+ - LNotOp = 0x92, // ACPI 1.0+ - LEQOp = 0x93, // ACPI 1.0+ - LEqualOp = 0x93, // ACPI 1.0b+ same as LEQOp obviously to make opcode name clearer -/* LNotEQOp = 0x93 0x92 */ // ACPI 1.0, seems to be an error in the documentation as that is LEqualOp LNotOp which doesn't make sense -/* LNotEqualOp = 0x92 0x93 */ // ACPI 1.0b+, correction of opcode and to make opcode name clearer. Literally LNotOp LEqualOp - LGOp = 0x94, // ACPI 1.0+ - LGreaterOp = 0x94, // ACPI 1.0b+ same as LGOp obviously to make opcode name clearer -/* LLEQOp = 0x94 0x92 */ // ACPI 1.0, seems to be an error in the documentation as that is LEqualOp LNotOp which doesn't make sense -/* LLessEqualOp = 0x92 0x94 */ // ACPI 1.0b+, correction of opcode and to make opcode name clearer. Literally LNotOp LGreaterOp - LLOp = 0x95, // ACPI 1.0+ - LLessOp = 0x95, // ACPI 1.0b+ same as LLOp obviously to make opcode name clearer -/* LGEQOp = 0x95 0x92 */ // ACPI 1.0, seems to be an error in the documentation as that is LEqualOp LNotOp which doesn't make sense -/* LGreaterEqualOp = 0x95 0x92 */ - // ^ ACPI 1.0b+, um... they kept the same mistake, but does make opcode name clearer, but the definition does correctly say LNotOp LLessOp. - // ^ Um... in fact ACPI 2.0 keeps the mistake and the corrected definition! They didn't fix THAT error until ACPI 3.0! - // ^ Would mistakes like this have anything to do with the Linux kernel reportedly not wanting to support any ACPI BIOS made before the year 2000? -/* LGreaterEqualOp = 0x92 0x95 */ // ACPI 3.0+ corrected byte pattern. Literally LNotOp LLessOp - BuffOp = 0x96, // ACPI 2.0+ - ToBufferOp = 0x96, // ACPI 2.0a+, correction of opcode and to make opcode name clearer - DecStrOp = 0x97, // ACPI 2.0+ - ToDecimalStringOp = 0x97, // ACPI 2.0a+, correction of opcode and to make opcode name clearer - HexStrOp = 0x98, // ACPI 2.0+ - ToHexStringOp = 0x98, // ACPI 2.0a+, correction of opcode and to make opcode name clearer - IntOp = 0x99, // ACPI 2.0+ - ToIntegerOp = 0x99, // ACPI 2.0a+, correction of opcode and to make opcode name clearer - - StringOp = 0x9C, // ACPI 2.0+ - ToStringOp = 0x9C, // ACPI 2.0a+, correction of opcode and to make opcode name clearer - CopyOp = 0x9D, // ACPI 2.0+ - CopyObjectOp = 0x9D, // ACPI 2.0a+, correction of opcode and to make opcode name clearer - MidOp = 0x9E, // ACPI 2.0+ - ContinueOp = 0x9F, // ACPI 2.0+ - IfOp = 0xA0, // ACPI 1.0+ - ElseOp = 0xA1, // ACPI 1.0+ - WhileOp = 0xA2, // ACPI 1.0+ - NoOp = 0xA3, // ACPI 1.0+ - ReturnOp = 0xA4, // ACPI 1.0+ - BreakOp = 0xA5, // ACPI 1.0+ - - BreakPointOp = 0xCC, // ACPI 1.0+ - - OnesOp = 0xFF // ACPI 1.0+ -}; - -enum class ACPIAMLOpcodeEOP5B:unsigned char { - /*0x5B*/MutexOp = 0x01, // ACPI 1.0+ - /*0x5B*/EventOp = 0x02, // ACPI 1.0+ - - /*0x5B*/ShiftRightBitOp = 0x10, // ACPI 1.0 only, disappeared 1.0b - /*0x5B*/ShiftLeftBitOp = 0x11, // ACPI 1.0 only, disappeared 1.0b - /*0x5B*/CondRefOp = 0x12, // ACPI 1.0+ - /*0x5B*/CreateFieldOp = 0x13, // ACPI 1.0+ - - /*0x5B*/LocalTableOp = 0x1F, // ACPI 2.0+ - /*0x5B*/LoadOp = 0x20, // ACPI 1.0+ - /*0x5B*/StallOp = 0x21, // ACPI 1.0+ - /*0x5B*/SleepOp = 0x22, // ACPI 1.0+ - /*0x5B*/AcquireOp = 0x23, // ACPI 1.0+ - /*0x5B*/SignalOp = 0x24, // ACPI 1.0+ - /*0x5B*/WaitOp = 0x25, // ACPI 1.0+ - /*0x5B*/ResetOp = 0x26, // ACPI 1.0+ - /*0x5B*/ReleaseOp = 0x27, // ACPI 1.0+ - /*0x5B*/FromBCDOp = 0x28, // ACPI 1.0+ - /*0x5B*/ToBCD = 0x29, // ACPI 1.0+ - /*0x5B*/UnloadOp = 0x2A, // ACPI 1.0+ - - /*0x5B*/RevisionOp = 0x30, // ACPI 1.0b+ - /*0x5B*/DebugOp = 0x31, // ACPI 1.0+ - /*0x5B*/FatalOp = 0x32, // ACPI 1.0+ - /*0x5B*/TimerOp = 0x33, // ACPI 3.0+ - - /*0x5B*/OpRegionOp = 0x80, // ACPI 1.0+ - /*0x5B*/FieldOp = 0x81, // ACPI 1.0+ - /*0x5B*/DeviceOp = 0x82, // ACPI 1.0+ - /*0x5B*/ProcessorOp = 0x83, // ACPI 1.0+ - /*0x5B*/PowerResOp = 0x84, // ACPI 1.0+ - /*0x5B*/ThermalZoneOp = 0x85, // ACPI 1.0+ - /*0x5B*/IndexFieldOp = 0x86, // ACPI 1.0+ - /*0x5B*/BankFieldOp = 0x87, // ACPI 1.0+ - /*0x5B*/DataRegionOp = 0x88 // ACPI 2.0+ -}; - -#include - -/* ACPI AML (ACPI Machine Language) writer. - * See also ACPI Specification 1.0b [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/BIOS/ACPI%2c%20Advanced%20Configuration%20and%20Power%20Interface/Advanced%20Configuration%20and%20Power%20Interface%20Specification%20%281999%2d02%2d02%29%20v1%2e0b%2epdf]. - * - * WARNING: The 1.0 specification [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/BIOS/ACPI%2c%20Advanced%20Configuration%20and%20Power%20Interface/Advanced%20Configuration%20and%20Power%20Interface%20Specification%20%281996%2d12%2d22%29%20v1%2e0%2epdf] seems to have some mistakes in a few opcodes in how they are defined, which probably means if your BIOS is from 1996-1998 it might have those few erroneous AML opcodes. */ -class ACPIAMLWriter { - public: - static constexpr unsigned int MaxPkgSize = 0xFFFFFFFu; - public: - struct pkg_t { - unsigned char* pkg_len = NULL; - unsigned char* pkg_data = NULL; - unsigned int element_count = 0; - }; - std::stack pkg_stack; - public: - ACPIAMLWriter(); - ~ACPIAMLWriter(); - public: - unsigned char* writeptr(void) const; - void begin(unsigned char *n_w,unsigned char *n_f); - public: - ACPIAMLWriter &rtDMA(const unsigned char bitmask,const unsigned char flags); - ACPIAMLWriter &rtMemRange24(const unsigned int flags,const unsigned int minr,const unsigned int maxr,const unsigned int alignr,const unsigned int rangr); - ACPIAMLWriter &rtMemRange32(const unsigned int flags,const unsigned int minr,const unsigned int maxr,const unsigned int alignr,const unsigned int rangr); - ACPIAMLWriter &rtIO(const unsigned int flags,const uint16_t minport,const uint16_t maxport,const uint8_t alignment,const uint8_t rlength); - ACPIAMLWriter &rtIRQ(const uint16_t bitmask/*bits [15:0] correspond to IRQ 15-0*/,const bool pciStyle=false); - ACPIAMLWriter &rtHdrSmall(const unsigned char itemName,const unsigned int length); - ACPIAMLWriter &rtHdrLarge(const unsigned char itemName,const unsigned int length); - ACPIAMLWriter &rtBegin(void); - ACPIAMLWriter &rtEnd(void); - public: - ACPIAMLWriter &NameOp(const char *name); - ACPIAMLWriter &ByteOp(const unsigned char v); - ACPIAMLWriter &WordOp(const unsigned int v); - ACPIAMLWriter &DwordOp(const unsigned long v); - ACPIAMLWriter &StringOp(const char *str); - ACPIAMLWriter &OpRegionOp(const char *name,const ACPIRegionSpace regionspace); - ACPIAMLWriter &FieldOp(const char *name,const unsigned int pred_size,const unsigned int fieldflag); - ACPIAMLWriter &FieldOpEnd(void); - ACPIAMLWriter &ScopeOp(const unsigned int pred_size=MaxPkgSize); - ACPIAMLWriter &ScopeOpEnd(void); - ACPIAMLWriter &PackageOp(const unsigned int pred_size=MaxPkgSize); - ACPIAMLWriter &RootCharScopeOp(void); - ACPIAMLWriter &PackageOpEnd(void); - ACPIAMLWriter &RootCharOp(void); - ACPIAMLWriter &NothingOp(void); - ACPIAMLWriter &ZeroOp(void); - ACPIAMLWriter &OneOp(void); - ACPIAMLWriter &AliasOp(const char *what,const char *to_what); - ACPIAMLWriter &BufferOpEnd(void); - ACPIAMLWriter &BufferOp(const unsigned int pred_size=MaxPkgSize); - ACPIAMLWriter &BufferOp(const unsigned char *data,const size_t datalen); - ACPIAMLWriter &DeviceOp(const char *name,const unsigned int pred_size=MaxPkgSize); - ACPIAMLWriter &DeviceOpEnd(void); - ACPIAMLWriter &MethodOp(const char *name,const unsigned int pred_size,const unsigned int methodflags); - ACPIAMLWriter &MethodOpEnd(void); - ACPIAMLWriter &ReturnOp(void); - ACPIAMLWriter &IfOp(const unsigned int pred_size=MaxPkgSize); - ACPIAMLWriter &IfOpEnd(void); - ACPIAMLWriter &ElseOp(const unsigned int pred_size=MaxPkgSize); - ACPIAMLWriter &ElseOpEnd(void); - ACPIAMLWriter &LEqualOp(void); - ACPIAMLWriter &LNotEqualOp(void); - ACPIAMLWriter &LNotOp(void); - ACPIAMLWriter &LAndOp(void); - ACPIAMLWriter &AndOp(void); - ACPIAMLWriter &ArgOp(const unsigned int arg); /* Arg0 through Arg6 */ - ACPIAMLWriter &LocalOp(const unsigned int l); /* Local0 through Local7 */ - ACPIAMLWriter &StoreOp(void); - ACPIAMLWriter &NOrOp(void); - ACPIAMLWriter &OrOp(void); - ACPIAMLWriter &NAndOp(void); - public:// ONLY for writing fields! - ACPIAMLWriter &FieldOpElement(const char *name,const unsigned int bits); - public: - ACPIAMLWriter &PkgLength(const unsigned int len,unsigned char* &wp,const unsigned int minlen=1); - ACPIAMLWriter &PkgLength(const unsigned int len,const unsigned int minlen=1); - ACPIAMLWriter &Name(const char *name); - ACPIAMLWriter &MultiNameOp(void); - ACPIAMLWriter &DualNameOp(void); - ACPIAMLWriter &BeginPkg(const unsigned int pred_length=MaxPkgSize); - ACPIAMLWriter &EndPkg(void); - ACPIAMLWriter &CountElement(void); - private: - unsigned char* w=NULL,*f=NULL; - unsigned char* buffer_len_pl = NULL; - unsigned char* rt_start = NULL; -}; - -/* StoreOp Operand Supername: Store Operand into Supername */ -ACPIAMLWriter &ACPIAMLWriter::StoreOp(void) { - *w++ = 0x70; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::LocalOp(const unsigned int l) { - if (l <= 7) - *w++ = 0x60 + l; /* 0x60..0x67 -> Local0..Local7 */ - else - E_Exit("ACPI AML writer LocalOp out of range"); - - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::ArgOp(const unsigned int arg) { - if (arg <= 6) - *w++ = 0x68 + arg; /* 0x68..0x6E -> Arg0..Arg6 */ - else - E_Exit("ACPI AML writer ArgOp out of range"); - - return *this; -} - -/* Binary operators like And and Xor are Operand1 Operand2 Target, and the return value - * of the operator is the result. What the ACPI specification is very unclear about, but - * hints at from a sample bit of ASL concerning PowerResource(), is that if you just - * want to evaluate the operator and do not care to store the result anywhere you can just - * set Target to Zero. - * - * This example doesn't make sense unless you consider that this is how you encode "Nothing" - * in the example on that page in spec 1.0b: - * - * Method(_STA) { - * Return (Xor (GIO.IDEI, One, Zero)) // inverse of isolation - * } - * - * See what they did there? */ -ACPIAMLWriter &ACPIAMLWriter::RootCharOp(void) { - *w++ = '\\'; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::RootCharScopeOp(void) { - RootCharOp(); /* this is how iasl encodes for example Scope(\) */ - ZeroOp(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::NothingOp(void) { - ZeroOp(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::ZeroOp(void) { - *w++ = 0x00; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::OneOp(void) { - *w++ = 0x01; - return *this; -} - -/* LEqual Operand1 Operand2 */ -ACPIAMLWriter &ACPIAMLWriter::LEqualOp(void) { - *w++ = 0x93; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::LNotOp(void) { - *w++ = 0x92; - return *this; -} - -/* LAndOp Operand1 Operand2 == Operand1 && Operand2 */ -ACPIAMLWriter &ACPIAMLWriter::LAndOp(void) { - *w++ = 0x90; - return *this; -} - -/* NAndOp Operand1 Operand2 Target -> Target = Operand1 & Operand2 */ -ACPIAMLWriter &ACPIAMLWriter::NAndOp(void) { - *w++ = 0x7C; - return *this; -} - -/* AndOp Operand1 Operand2 Target -> Target = Operand1 & Operand2 */ -ACPIAMLWriter &ACPIAMLWriter::AndOp(void) { - *w++ = 0x7B; - return *this; -} - -/* NOrOp Operand1 Operand2 Target -> Target = Operand1 & Operand2 */ -ACPIAMLWriter &ACPIAMLWriter::NOrOp(void) { - *w++ = 0x7E; - return *this; -} - -/* OrOp Operand1 Operand2 Target -> Target = Operand1 & Operand2 */ -ACPIAMLWriter &ACPIAMLWriter::OrOp(void) { - *w++ = 0x7D; - return *this; -} - -/* This makes sense if you think of an AML interpreter as something which encounters a LNotOp() - * and then runs the interpreter to parse the following token(s) to evaluate an int so it can - * do a logical NOT on the result of the evaluation. In other words this isn't like x86 assembly - * which you follow instruction by instruction but more like how you parse and evaluate expressions - * such as "4+5*3" properly. */ -ACPIAMLWriter &ACPIAMLWriter::LNotEqualOp(void) { - LNotOp(); - LEqualOp(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::BufferOp(const unsigned char *data,const size_t datalen) { - /* Notice this OP was obviously invented by the Department of Redundant Redundancy somewhere deep within Microsoft. - * This op stores both a PkgLength containing the overall buffer data and then the first bytes are a ByteOp encoding the length of the buffer. - * So basically it stores the length twice. What? Why? */ - *w++ = 0x11; - BeginPkg(datalen+8/*Byte/Word/DwordOp*/); - if (datalen >= 0x10000) DwordOp(datalen); - else if (datalen >= 0x100) WordOp(datalen); - else ByteOp(datalen); - if (datalen > 0) { - memcpy(w,data,datalen); - w += datalen; - } - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::BufferOp(const unsigned int pred_size) { - assert(pred_size >= 10); - *w++ = 0x11; - BeginPkg(pred_size); - DwordOp(0); // placeholder - buffer_len_pl = w - 4; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::BufferOpEnd(void) { - assert(buffer_len_pl != NULL); - host_writed(buffer_len_pl,size_t(w - (buffer_len_pl + 4))); - buffer_len_pl = NULL; - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::AliasOp(const char *what,const char *to_what) { - *w++ = 0x06; - Name(what); - Name(to_what); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::ReturnOp(void) { - *w++ = 0xA4; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::IfOp(const unsigned int pred_size) { - *w++ = 0xA0; - BeginPkg(pred_size); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::IfOpEnd(void) { - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::ElseOp(const unsigned int pred_size) { - *w++ = 0xA1; - BeginPkg(pred_size); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::ElseOpEnd(void) { - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtHdrLarge(const unsigned char itemName,const unsigned int length) { - assert(length <= 65536); - assert(itemName < 128); - *w++ = 0x80 + itemName; - host_writew(w,length); w += 2; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtHdrSmall(const unsigned char itemName,const unsigned int length) { - assert(length < 8); - assert(itemName < 16); - *w++ = (itemName << 3) + length; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtBegin(void) { - rt_start = w; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtEnd(void) { - rtHdrSmall(15/*end tag format*/,1/*length*/); - if (rt_start != NULL) { - unsigned char sum = 0; - for (unsigned char *s=rt_start;s < w;s++) sum += *s++; - *w++ = 0x100 - sum; - } - else { - *w++ = 0; - } - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtMemRange24(const unsigned int flags,const unsigned int minr,const unsigned int maxr,const unsigned int alignr,const unsigned int rangr) { - rtHdrLarge(1/*24-bit memory range format*/,9/*length*/); - *w++ = flags; - host_writew(w,minr >> 8u); w += 2; - host_writew(w,maxr >> 8u); w += 2; - host_writew(w,(alignr + 0xFFu) >> 8u); w += 2; /* FIXME: Um... alignment in bytes but everything else multiple of 256 bytes? */ - host_writew(w,rangr >> 8u); w += 2; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtMemRange32(const unsigned int flags,const unsigned int minr,const unsigned int maxr,const unsigned int alignr,const unsigned int rangr) { - rtHdrLarge(5/*32-bit memory range format*/,17/*length*/); - *w++ = flags; - host_writed(w,minr); w += 4; - host_writed(w,maxr); w += 4; - host_writed(w,alignr); w += 4; - host_writed(w,rangr); w += 4; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtDMA(const unsigned char bitmask,const unsigned char flags) { - rtHdrSmall(5/*DMA format*/,2/*length*/); - *w++ = bitmask; - *w++ = flags; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtIO(const unsigned int flags,const uint16_t minport,const uint16_t maxport,const uint8_t alignment,const uint8_t rlength) { - rtHdrSmall(8/*IO format*/,7/*length*/); - *w++ = (unsigned char)flags; - host_writew(w,minport); w += 2; - host_writew(w,maxport); w += 2; - *w++ = alignment; - *w++ = rlength; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::rtIRQ(const uint16_t bitmask,const bool pciStyle) { - rtHdrSmall(4/*IRQ format*/,3/*length*/); - host_writew(w,bitmask); w += 2; - *w++ = pciStyle ? 0x18/*active low level trigger shareable*/ : 0x01/*active high edge trigger*/; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::NameOp(const char *name) { - *w++ = 0x08; // NameOp - Name(name); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::Name(const char *name) { - for (unsigned int i=0;i < 4;i++) { - if (*name) *w++ = *name++; - else *w++ = '_'; - } - - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::MultiNameOp(void) { - *w++ = 0x2F; // MultiNamePrefix - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::DualNameOp() { - *w++ = 0x2E; // DualNamePrefix - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::ByteOp(const unsigned char v) { - *w++ = 0x0A; // ByteOp - *w++ = v; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::WordOp(const unsigned int v) { - *w++ = 0x0B; // WordOp - host_writew(w,v); w += 2; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::DwordOp(const unsigned long v) { - *w++ = 0x0C; // DwordOp - host_writed(w,v); w += 4; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::StringOp(const char *str) { - /* WARNING: Strings are only supposed to have ASCII 0x01-0x7F */ - *w++ = 0x0D; // StringOp - while (*str != 0) *w++ = *str++; - *w++ = 0x00; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::OpRegionOp(const char *name,const ACPIRegionSpace regionspace) { - *w++ = 0x5B; - *w++ = 0x80; - Name(name); - *w++ = (unsigned char)regionspace; - // and then the caller must write the RegionAddress and RegionLength - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::DeviceOp(const char *name,const unsigned int pred_size) { - *w++ = 0x5B; - *w++ = 0x82; - BeginPkg(pred_size); - Name(name); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::DeviceOpEnd(void) { - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::MethodOp(const char *name,const unsigned int pred_size,const unsigned int methodflags) { - *w++ = 0x14; - BeginPkg(pred_size); - Name(name); - *w++ = (unsigned char)methodflags; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::MethodOpEnd(void) { - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::FieldOp(const char *name,const unsigned int pred_size,const unsigned int fieldflag) { - *w++ = 0x5B; - *w++ = 0x81; - BeginPkg(pred_size); - Name(name); - *w++ = fieldflag; - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::FieldOpEnd(void) { - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::ScopeOp(const unsigned int pred_size) { - *w++ = 0x10; - BeginPkg(pred_size); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::ScopeOpEnd(void) { - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::PackageOp(const unsigned int pred_size) { - *w++ = 0x12; - BeginPkg(pred_size); - *w++ = 0x00; // placeholder for element count - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::PackageOpEnd(void) { - assert(!pkg_stack.empty()); - - pkg_t &ent = pkg_stack.top(); - - if (ent.element_count > 255u) E_Exit("ACPI AML writer too many elements in package"); - *ent.pkg_data = ent.element_count; /* element count follows PkgLength */ - - EndPkg(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::PkgLength(const unsigned int len,const unsigned int minlen) { - return PkgLength(len,w,minlen); -} - -ACPIAMLWriter &ACPIAMLWriter::PkgLength(const unsigned int len,unsigned char* &wp,const unsigned int minlen) { - if (len >= 0x10000000 || minlen > 4) { - E_Exit("ACPI AML writer PkgLength value too large"); - } - else if (len >= 0x100000 || minlen >= 4) { - *wp++ = (unsigned char)( len & 0x0F) | 0xC0; - *wp++ = (unsigned char)((len >> 4) & 0xFF); - *wp++ = (unsigned char)((len >> 12) & 0xFF); - *wp++ = (unsigned char)((len >> 20) & 0xFF); - } - else if (len >= 0x1000 || minlen >= 3) { - *wp++ = (unsigned char)( len & 0x0F) | 0x80; - *wp++ = (unsigned char)((len >> 4) & 0xFF); - *wp++ = (unsigned char)((len >> 12) & 0xFF); - } - else if (len >= 0x40 || minlen >= 2) { - *wp++ = (unsigned char)( len & 0x0F) | 0x40; - *wp++ = (unsigned char)((len >> 4) & 0xFF); - } - else { - *wp++ = (unsigned char)len; - } - - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::FieldOpElement(const char *name,const unsigned int bits) { - if (*name != 0) - Name(name); - else - *w++ = 0; - - PkgLength(bits); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::BeginPkg(const unsigned int /*pred_length*/) { - pkg_t ent; - - /* WARNING: Specify a size large enough. Once written, it cannot be extended if - * needed. By default, this code writes an overlarge field to make sure - * it can always update */ - - if (pkg_stack.size() >= 32) E_Exit("ACPI AML writer BeginPkg too much recursion"); - - ent.pkg_len = w; - PkgLength(MaxPkgSize);//placeholder - ent.pkg_data = w; - - pkg_stack.push(std::move(ent)); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::EndPkg(void) { - if (pkg_stack.empty()) E_Exit("ACPI AML writer EndPkg with empty stack"); - - pkg_t &ent = pkg_stack.top(); - - const unsigned long len = (unsigned long)(w - ent.pkg_len); - const unsigned int lflen = (unsigned int)(ent.pkg_data - ent.pkg_len); - PkgLength(len,ent.pkg_len,lflen); - if (ent.pkg_len != ent.pkg_data) E_Exit("ACPI AML writer length update exceeds pkglength field"); - pkg_stack.pop(); - return *this; -} - -ACPIAMLWriter &ACPIAMLWriter::CountElement(void) { - if (pkg_stack.empty()) E_Exit("ACPI AML writer counting elements not supported unless within package"); - pkg_stack.top().element_count++; - return *this; -} - -ACPIAMLWriter::ACPIAMLWriter() { -} - -ACPIAMLWriter::~ACPIAMLWriter() { -} - -unsigned char* ACPIAMLWriter::writeptr(void) const { - return w; -} - -void ACPIAMLWriter::begin(unsigned char *n_w,unsigned char *n_f) { - w = n_w; - f = n_f; -} - -void BuildACPITable(void) { - uint32_t rsdt_reserved = 16384; - unsigned char *w,*f; - unsigned int i,c; - - if (ACPI_buffer == NULL || ACPI_buffer_size < 32768) return; - w = ACPI_buffer; - f = ACPI_buffer+ACPI_buffer_size-rsdt_reserved; - - /* RSDT starts at last 16KB of ACPI buffer because it needs to build up a list of other tables */ - unsigned char *rsdt = f; - - /* RSD PTR is written to the legacy BIOS region, on a 16-byte boundary */ - Bitu rsdptr = ROMBIOS_GetMemory(20,"ACPI BIOS Root System Description Pointer",/*paragraph align*/16); - if (rsdptr == 0) E_Exit("ACPI BIOS RSD PTR alloc fail"); - LOG(LOG_MISC,LOG_DEBUG)("ACPI: RSD PTR at 0x%lx",(unsigned long)rsdptr); - - phys_writes(rsdptr + 0,"RSD PTR ",8); // Signature - phys_writeb(rsdptr + 8,0); // Checksum (fill in later) - phys_writes(rsdptr + 9,"DOSBOX",6); // OEMID - phys_writeb(rsdptr + 15,0); // Reserved must be zero - phys_writed(rsdptr + 16,acpiofs2phys( acpiptr2ofs( rsdt ) )); // RSDT physical address - c=0; for (i=0;i < 20;i++) c += phys_readb(rsdptr+i); - phys_writeb(rsdptr + 8,(0u - c)&0xFF); // Checksum - - /* RSDT */ - ACPISysDescTableWriter rsdt_tw; - rsdt_tw.begin(rsdt,ACPI_buffer+ACPI_buffer_size).setSig("RSDT").setRev(1); - unsigned int rsdt_tw_ofs = 36; - // leave open for adding one DWORD per table to the end as we go... this is why RSDT is written to the END of the ACPI region. - - /* FACP, which does not have a checksum and does not follow the normal format */ - unsigned char *facs = w; - size_t facs_size = 64; - w += facs_size; - { - assert(w <= f); - memset(facs,0,facs_size); - memcpy(facs+0x00,"FACS",4); - host_writed(facs+0x04,facs_size); - host_writed(facs+0x08,0x12345678UL); // hardware signature - host_writed(facs+0x0C,0); // firmware waking vector - ACPI_buffer_global_lock = acpiptr2ofs(facs+0x10); - host_writed(facs+0x10,0); // global lock - host_writed(facs+0x14,0); // S4BIOS_REQ not supported - LOG(LOG_MISC,LOG_DEBUG)("ACPI: FACS at 0x%lx len 0x%lx",(unsigned long)acpiofs2phys( acpiptr2ofs( facs ) ),(unsigned long)facs_size); - } - - unsigned char *dsdt_base = w; - { - ACPISysDescTableWriter dsdt; - ACPIAMLWriter aml; - - dsdt.begin(w,f).setSig("DSDT").setRev(1); - aml.begin(dsdt.getptr()+dsdt.get_tablesize(),f); - - /* WARNING: To simplify this code, you are responsible for writing the AML in the syntax required. - * See the ACPI BIOS specification for more details. - * - * For reference: - * - * Name := [LeadNameChar NameChar NameChar NameChar] | - * [LeadNameChar NameChar NameChar '_'] | - * [LeadNameChar NameChar '_' '_'] | - * [LeadNameChar '_' '_' '_'] - * - * DefName := NameOp Name DataTerm - * NameOp => 0x08 - * Data := DataTerm [DataTerm ...] - * DataTerm := DataItem | DefPackage - * DataItem := DefBuffer | DefNum | DefString - * - * How to write: ACPIAML1_NameOp(Name) followed by the necessary functions to write the buffer, string, etc. for the name. */ - aml.ScopeOp().RootCharScopeOp();/* Scope (\) */ - aml.OpRegionOp("DBG",ACPIRegionSpace::SystemIO).WordOp(ACPI_DEBUG_IO).ByteOp(0x10); - aml.FieldOp("DBG",ACPIAMLWriter::MaxPkgSize,ACPIFieldFlag::AccessType::DwordAcc|ACPIFieldFlag::UpdateRule::WriteAsZeros); - aml.FieldOpElement("DBGV",32); - aml.FieldOpEnd(); - aml.ScopeOpEnd(); /* } end of Scope(\) */ - - aml.ScopeOp().RootCharOp().Name("_SB"); - if (pcibus_enable) { - aml.DeviceOp("PCI0"); - aml.NameOp("_HID").DwordOp(ISAPNP_ID('P','N','P',0x00,0x0A,0x00,0x03)); - aml.NameOp("_ADR").DwordOp(0); /* [31:16] device [15:0] function */ - aml.NameOp("_UID").DwordOp(0xD05B0C5); - aml.NameOp("_CRS").BufferOp().rtBegin(); /* ResourceTemplate() i.e. resource list */ - aml.rtIO( - ACPIrtIO_16BitDecode, - 0x0CF8,/*min*/ - 0x0CF8,/*max*/ - 0x01,/*align*/ - 0x4/*number of I/O ports req*/); - aml.rtEnd(); - aml.BufferOpEnd(); - } - else { - aml.DeviceOp("ISA"); - aml.NameOp("_HID").DwordOp(ISAPNP_ID('P','N','P',0x00,0x0A,0x00,0x00)); - aml.NameOp("_ADR").DwordOp(0); /* [31:16] device [15:0] function */ - aml.NameOp("_UID").DwordOp(0xD05B0C5); - aml.DeviceOpEnd(); - - } - aml.ScopeOpEnd(); - - assert(aml.writeptr() >= (dsdt.getptr()+dsdt.get_tablesize())); - assert(aml.writeptr() <= f); - dsdt.expandto((size_t)(aml.writeptr() - dsdt.getptr())); - LOG(LOG_MISC,LOG_DEBUG)("ACPI: DSDT at 0x%lx len 0x%lx",(unsigned long)acpiofs2phys( acpiptr2ofs( dsdt_base ) ),(unsigned long)dsdt.get_tablesize()); - w = dsdt.finish(); - } - - { /* Fixed ACPI Description Table (FACP) */ - ACPISysDescTableWriter facp; - const PhysPt facp_offset = acpiofs2phys( acpiptr2ofs( w ) ); - - host_writed(rsdt_tw.getptr(rsdt_tw_ofs,4),(uint32_t)facp_offset); - rsdt_tw_ofs += 4; - - facp.begin(w,f,116).setSig("FACP").setRev(1); - host_writed(w+36,acpiofs2phys( acpiptr2ofs( facs ) ) ); // FIRMWARE_CTRL (FACS table) - host_writed(w+40,acpiofs2phys( acpiptr2ofs( dsdt_base ) ) ); // DSDT - w[44] = 0; // dual PIC PC-AT type implementation - host_writew(w+46,ACPI_IRQ); // SCI_INT - host_writed(w+48,ACPI_SMI_CMD); // SCI_CMD (I/O port) - w[52] = ACPI_ENABLE_CMD; // what the guest writes to SMI_CMD to disable SMI ownership from BIOS during bootup - w[53] = ACPI_DISABLE_CMD; // what the guest writes to SMI_CMD to re-enable SMI ownership to BIOS - // TODO: S4BIOS_REQ - host_writed(w+56,ACPI_PM1A_EVT_BLK); // PM1a_EVT_BLK event register block - host_writed(w+64,ACPI_PM1A_CNT_BLK); // PM1a_CNT_BLK control register block - host_writed(w+76,ACPI_PM_TMR_BLK); // PM_TMR_BLK power management timer control register block - w[88] = 4; // PM1_EVT_LEN - w[89] = 2; // PM1_CNT_LEN - w[90] = 0; // PM2_CNT_LEN - w[91] = 4; // PM_TM_LEN - host_writed(w+112,(1u << 0u)/*WBINVD*/); - LOG(LOG_MISC,LOG_DEBUG)("ACPI: FACP at 0x%lx len 0x%lx",(unsigned long)facp_offset,(unsigned long)facp.get_tablesize()); - w = facp.finish(); - } - - /* Finish RSDT */ - LOG(LOG_MISC,LOG_DEBUG)("ACPI: RDST at 0x%lx len 0x%lx",(unsigned long)acpiofs2phys( acpiptr2ofs( rsdt ) ),(unsigned long)rsdt_tw.get_tablesize()); - rsdt_tw.finish(); -} - -#if C_LIBPNG -# include "dosbox224x93.h" -# include "dosbox224x163.h" -# include "dosbox224x186.h" -# include "dosbox224x224.h" - -static const unsigned char *BIOSLOGO_PNG_PTR = NULL; -static const unsigned char *BIOSLOGO_PNG_FENCE = NULL; - -static void BIOSLOGO_PNG_READ(png_structp context,png_bytep buf,size_t count) { - (void)context; - - while (count > 0 && BIOSLOGO_PNG_PTR < BIOSLOGO_PNG_FENCE) { - *buf++ = *BIOSLOGO_PNG_PTR++; - count--; - } - while (count > 0) { - *buf++ = 0; - count--; - } -} - -#endif - -extern unsigned int INT13Xfer; - -class BIOS:public Module_base{ -private: - static Bitu cb_bios_post__func(void) { - void TIMER_BIOS_INIT_Configure(); -#if C_DEBUG - void DEBUG_CheckCSIP(); - -# if C_HEAVY_DEBUG - /* the game/app obviously crashed, which is way more important - * to log than what we do here in the BIOS at POST */ - void DEBUG_StopLog(void); - DEBUG_StopLog(); -# endif -#endif - - INT13_ElTorito_NoEmuDriveNumber = 0; - INT13_ElTorito_NoEmuCDROMDrive = 0; - INT13_ElTorito_IDEInterface = -1; - INT13Xfer = 0; - - ACPI_mem_enable(false); - ACPI_REGION_SIZE = 0; - ACPI_BASE = 0; - ACPI_enabled = false; - ACPI_version = 0; - ACPI_free(); - ACPI_SCI_EN = false; - ACPI_BM_RLD = false; - ACPI_PM1_Status = 0; - ACPI_PM1_Enable = 0; - - E280_table_entries = 0; - - {/*Conventional memory*/ - BIOS_E280_entry &ent = E280_table[E280_table_entries++]; - ent.base = 0x00000000; - ent.length = 0x9F000; /* 640KB minus the EBDA */ - ent.type = 1;/*Normal RAM*/ - } - {/*Conventional adapter ROM/RAM/BIOS*/ - BIOS_E280_entry &ent = E280_table[E280_table_entries++]; - ent.base = 0x000C0000; - ent.length = 0x40000; - ent.type = 2;/*Reserved*/ - } - if (MEM_TotalPages() > 0x100) { /* more than 1MB of RAM */ - BIOS_E280_entry &ent = E280_table[E280_table_entries++]; - ent.base = 0x00100000; - ent.length = (MEM_TotalPages()-0x100u)*4096u; - ent.type = 1;/*Normal RAM*/ - } - if (MEM_TotalPagesAt4GB() > 0) { /* anything above 4GB? */ - BIOS_E280_entry &ent = E280_table[E280_table_entries++]; - ent.base = uint64_t(0x100000000ull); - ent.length = uint64_t(MEM_TotalPagesAt4GB())*uint64_t(4096ul); - ent.type = 1;/*Normal RAM*/ - } - - /* If we're here because of a JMP to F000:FFF0 from a DOS program, then - * an actual reset is needed to prevent reentrancy problems with the DOS - * kernel shell. The WINNT.EXE install program for Windows NT/2000/XP - * likes to restart the program by JMPing to F000:FFF0 */ - if (!dos_kernel_disabled && first_shell != NULL) { - LOG(LOG_MISC,LOG_DEBUG)("BIOS POST: JMP to F000:FFF0 detected, initiating proper reset"); - throw int(9); - } - - { - Section_prop * section=static_cast(control->GetSection("dosbox")); - int val = section->Get_int("reboot delay"); - - if (val < 0) - val = IS_PC98_ARCH ? 1000 : 500; - - reset_post_delay = (unsigned int)val; - - /* Read the ACPI setting and decide on a ACPI region to use */ - { - std::string s = section->Get_string("acpi"); - - if (IS_PC98_ARCH) { - /* do not enable ACPI, PC-98 does not have it */ - } - else if (MEM_get_address_bits() < 32) { - /* I doubt any 486DX systems with less than 32 address bits has ACPI */ - } - else if (CPU_ArchitectureType < CPU_ARCHTYPE_386) { - /* Your 286 does not have ACPI and it never will. - * Your 386 as well, but the 386 is 32-bit and the user might change it to 486 or higher later though, so we'll allow that */ - } - else if (s == "1.0") { - ACPI_version = 0x100; - ACPI_REGION_SIZE = (256u << 10u); // 256KB - } - else if (s == "1.0b") { - ACPI_version = 0x10B; - ACPI_REGION_SIZE = (256u << 10u); // 256KB - } - } - - /* TODO: Read from dosbox.conf */ - if (ACPI_version != 0) { - ACPI_IRQ = 9; - ACPI_IO_BASE = 0x820; - ACPI_SMI_CMD = 0x828; - } - } - - if (bios_post_counter != 0 && reset_post_delay != 0) { - /* reboot delay, in case the guest OS/application had something to day before hitting the "reset" signal */ - uint32_t lasttick=GetTicks(); - while ((GetTicks()-lasttick) < reset_post_delay) { - void CALLBACK_IdleNoInts(void); - CALLBACK_IdleNoInts(); - } - } - - if (bios_post_counter != 0) { - /* turn off the PC speaker if the guest left it on at reset */ - if (IS_PC98_ARCH) { - IO_Write(0x37,0x07); - } - else { - IO_Write(0x61,IO_Read(0x61) & (~3u)); - } - } - - bios_post_counter++; - - if (bios_first_init) { - /* clear the first 1KB-32KB */ - for (uint16_t i=0x400;i<0x8000;i++) real_writeb(0x0,i,0); - } - - if (IS_PC98_ARCH) { - for (unsigned int i=0;i < callback_count;i++) callback[i].Uninstall(); - - /* clear out 0x50 segment (TODO: 0x40 too?) */ - for (unsigned int i=0;i < 0x100;i++) phys_writeb(0x500+i,0); - - BIOS_ZeroExtendedSize(false); - - if (call_pc98_default_stop == 0) - call_pc98_default_stop = CALLBACK_Allocate(); - - CALLBACK_Setup(call_pc98_default_stop,&pc98_default_stop_handler,CB_IRET,"INT 6h invalid opcode or STOP interrupt"); - - unsigned char memsize_real_code = 0; - Bitu mempages = MEM_TotalPages(); /* in 4KB pages */ - - /* NTS: Fill in the 3-bit code in FLAGS1 that represents - * how much lower conventional memory is in the system. - * - * Note that MEM.EXE requires this value, or else it - * will complain about broken UMB linkage and fail - * to show anything else. */ - /* TODO: In the event we eventually support "high resolution mode" - * we can indicate 768KB here, code == 5, meaning that - * the RAM extends up to 0xBFFFF instead of 0x9FFFF */ - if (mempages >= (640UL/4UL)) /* 640KB */ - memsize_real_code = 4; - else if (mempages >= (512UL/4UL)) /* 512KB */ - memsize_real_code = 3; - else if (mempages >= (384UL/4UL)) /* 384KB */ - memsize_real_code = 2; - else if (mempages >= (256UL/4UL)) /* 256KB */ - memsize_real_code = 1; - else /* 128KB */ - memsize_real_code = 0; - - void pc98_msw3_set_ramsize(const unsigned char b); - pc98_msw3_set_ramsize(memsize_real_code); - - /* CRT status */ - /* bit[7:6] = 00=conventional compatible 01=extended attr JEH 10=extended attr EGH - * bit[5:5] = Single event timer in use flag 1=busy 0=not used - * bit[4:4] = ? - * bit[3:3] = raster scan 1=non-interlaced 0=interlaced - * bit[2:2] = Content ruled line color 1=I/O set value 0=attributes of VRAM - * bit[1:1] = ? - * bit[0:0] = 480-line mode 1=640x480 0=640x400 or 640x200 */ - mem_writeb(0x459,0x08/*non-interlaced*/); - - /* Time stamper */ - /* bit[7:7] = 1=Port 5Fh exists 0=No such port Write to port 0x5F to wait 0.6us - * bit[6:6] = ? - * bit[5:5] = "Power" ? - * bit[4:4] = 1=PCMCIA BIOS running 0=not running - * bit[3:3] = ? - * bit[2:2] = 1=Time stamper (I/O ports 0x5C and 0x5E) available - * bit[1:1] = 1=Card I/O slot function 0=No card slot function - * bit[0:0] = 1=386SL(98) 0=Other */ - mem_writeb(0x45B,(pc98_timestamp5c?0x4:0x0)|0x80/*port 5Fh*/); - - /* CPU/Display */ - /* bit[7:7] = 486SX equivalent (?) 1=yes - * bit[6:6] = PC-9821 Extended Graph Architecture supported (FIXME: Is this the same as having EGC?) 1=yes - * bit[5:5] = LCD display is color 1=yes 0=no - * bit[4:4] = ? - * bit[3:3] = ROM drive allow writing - * bit[2:2] = 98 NOTE PC-9801N-08 expansion I/O box connected - * bit[1:1] = 98 NOTE prohibit transition to power saving mode - * bit[0:0] = 98 NOTE coprocessor function available */ - mem_writeb(0x45C,(enable_pc98_egc ? 0x40/*Extended Graphics*/ : 0x00)); - - /* CPU type in bits [1:0] */ - if (CPU_ArchitectureType >= CPU_ARCHTYPE_286) { - mem_writeb(0x480,CPU_ArchitectureType >= CPU_ARCHTYPE_386 ? 3 : 1); - } - - - /* Keyboard type */ - /* bit[7:7] = ? - * bit[6:6] = keyboard type bit 1 - * bit[5:5] = EMS page frame at B0000h 1=present 0=none - * bit[4:4] = EMS page frame at B0000h 1=page frame 0=G-VRAM - * bit[3:3] = keyboard type bit 0 - * bit[2:2] = High resolution memory window available - * bit[1:1] = ? - * bit[0:0] = ? - * - * keyboard bits[1:0] from bit 6 as bit 1 and bit 3 as bit 0 combined: - * 11 = new keyboard (NUM key, DIP switch 2-7 OFF) - * 10 = new keyboard (without NUM key) - * 01 = new keyboard (NUM key, DIP switch 2-7 ON) - * 00 = old keyboard - * - * The old keyboard is documented not to support software control of CAPS and KANA states */ - /* TODO: Make this a dosbox-x.conf option. Default is new keyboard without NUM key because that is - * what keyboard emulation currently acts like anyway. */ - mem_writeb(0x481,0x40/*bit 6=1 bit 3=0 new keyboard without NUM key*/); - - /* BIOS flags */ - /* bit[7:7] = Startup 1=hot start 0=cold start - * bit[6:6] = BASIC type ?? - * bit[5:5] = Keyboard beep 1=don't beep 0=beep ... when buffer full - * bit[4:4] = Expansion conv RAM 1=present 0=absent - * bit[3:3] = ?? - * bit[2:2] = ?? - * bit[1:1] = HD mode 1=1MB mode 0=640KB mode ... of the floppy drive - * bit[0:0] = Model 1=other 0=PC-9801 original */ - /* NTS: MS-DOS 5.0 appears to reduce it's BIOS calls and render the whole - * console as green IF bit 0 is clear. - * - * If bit 0 is set, INT 1Ah will be hooked by MS-DOS and, for some odd reason, - * MS-DOS's hook proc will call to our INT 1Ah + 0x19 bytes. */ - mem_writeb(0x500,0x01 | 0x02/*high density drive*/); - - /* BIOS flags */ - /* timer setup will set/clear bit 7 */ - /* bit[7:7] = system clock freq 1=8MHz 0=5/10Mhz - * = timer clock freq 1=1.9968MHz 0=2.4576MHz - * bit[6:6] = CPU 1=V30 0=Intel (8086 through Pentium) - * bit[5:5] = Model info 1=Other model 0=PC-9801 Muji, PC-98XA - * bit[4:4] = Model info ... - * bit[3:3] = Model info 1=High res 0=normal - * bit[2:0] = Realmode memsize - * 000=128KB 001=256KB - * 010=384KB 011=512KB - * 100=640KB 101=768KB - * - * Ref: http://hackipedia.org/browse/Computer/Platform/PC,%20NEC%20PC-98/Collections/Undocumented%209801,%209821%20Volume%202%20(webtech.co.jp)/memsys.txt */ - /* NTS: High resolution means 640x400, not the 1120x750 mode known as super high resolution mode. - * DOSBox-X does not yet emulate super high resolution nor does it emulate the 15khz 200-line "standard" mode. - * ref: https://github.com/joncampbell123/dosbox-x/issues/906#issuecomment-434513930 - * ref: https://jisho.org/search?utf8=%E2%9C%93&keyword=%E8%B6%85 */ - mem_writeb(0x501,0x20 | memsize_real_code); - - /* keyboard buffer */ - mem_writew(0x524/*tail*/,0x502); - mem_writew(0x526/*tail*/,0x502); - - /* number of scanlines per text row - 1 */ - mem_writeb(0x53B,0x0F); // CRT_RASTER, 640x400 24.83KHz-hsync 56.42Hz-vsync - - /* Text screen status. - * Note that most of the bits are used verbatim in INT 18h AH=0Ah/AH=0Bh */ - /* bit[7:7] = High resolution display 1=yes 0=no (standard) NOT super high res - * bit[6:6] = vsync 1=VSYNC wait 0=end of vsync handling - * bit[5:5] = unused - * bit[4:4] = Number of lines 1=30 lines 0=20/25 lines - * bit[3:3] = K-CG access mode 1=dot access 0=code access - * bit[2:2] = Attribute mode (how to handle bit 4) 1=Simp. graphic 0=Vertical line - * bit[1:1] = Number of columns 1=40 cols 0=80 cols - * bit[0:0] = Number of lines 1=20/30 lines 0=25 lines */ - mem_writeb(0x53C,(true/*TODO*/ ? 0x80/*high res*/ : 0x00/*standard*/)); - - /* BIOS raster location */ - mem_writew(0x54A,0x1900); - - /* BIOS flags */ - /* bit[7:7] = Graphics display state 1=Visible 0=Blanked (hidden) - * bit[6:6] = CRT type 1=high res 0=standard NOT super high res - * bit[5:5] = Horizontal sync rate 1=31.47KHz 0=24.83KHz - * bit[4:4] = CRT line mode 1=480-line 0=400-line - * bit[3:3] = Number of user-defined characters 1=188+ 0=63 - * bit[2:2] = Extended graphics RAM (for 16-color) 1=present 0=absent - * bit[1:1] = Graphics Charger is present 1=present 0=absent - * bit[0:0] = DIP switch 1-8 at startup 1=ON 0=OFF (support GLIO 16-colors) */ - mem_writeb(0x54C,(true/*TODO*/ ? 0x40/*high res*/ : 0x00/*standard*/) | (enable_pc98_grcg ? 0x02 : 0x00) | (enable_pc98_16color ? 0x05 : 0x00) | (pc98_31khz_mode ? 0x20/*31khz*/ : 0x00/*24khz*/) | (enable_pc98_188usermod ? 0x08 : 0x00)); // PRXCRT, 16-color G-VRAM, GRCG - - /* BIOS flags */ - /* bit[7:7] = PC-9821 graphics mode (INT 18h AH=4Dh CH=01h/00h) 1=extend 0=normal - * bit[6:6] = Enhanced Graphics Charger (EGC) is present - * bit[5:5] = GDC at 5.0MHz at boot up (copy of DIP switch 2-8 at startup) 1=yes 0=no - * bit[4:4] = Always "flickerless" drawing mode - * bit[3:3] = Drawing mode with flicker - * bit[2:2] = GDC clock 1=5MHz 0=2.5MHz - * bit[1:0] = Drawing mode of the GDC - * 00 = REPLACE - * 01 = COMPLEMENT - * 10 = CLEAR - * 11 = SET */ - mem_writeb(0x54D, - (enable_pc98_egc ? 0x40 : 0x00) | - (gdc_5mhz_mode ? 0x20 : 0x00) | - (gdc_5mhz_mode ? 0x04 : 0x00)); // EGC - - /* BIOS flags */ - /* bit[7:7] = INT 18h AH=30h/31h support enabled - * bit[6:3] = 0 (unused) - * bit[2:2] = Enhanced Graphics Mode (EGC) supported - * bit[1:0] = Graphic resolution - * 00 = 640x200 upper half (2/8/16-color mode) - * 01 = 640x200 lower half (2/8/16-color mode) - * 10 = 640x400 (2/8/16/256-color mode) - * 11 = 640x480 256-color mode */ - mem_writeb(0x597,(enable_pc98_egc ? 0x04 : 0x00)/*EGC*/ | - (enable_pc98_egc ? 0x80 : 0x00)/*supports INT 18h AH=30h and AH=31h*/ | - 2/*640x400*/); - /* TODO: I would like to eventually add a dosbox-x.conf option that controls whether INT 18h AH=30h and 31h - * are enabled, so that retro-development can test code to see how it acts on a newer PC-9821 - * that supports it vs an older PC-9821 that doesn't. - * - * If the user doesn't set the option, then it is "auto" and determined by machine= PC-98 model and - * by another option in dosbox-x.conf that determines whether 31khz support is enabled. - * - * NOTED: Neko Project II determines INT 18h AH=30h availability by whether or not it was compiled - * with 31khz hsync support (SUPPORT_CRT31KHZ) */ - - /* Set up the translation table pointer, which is relative to segment 0xFD80 */ - mem_writew(0x522,(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800)); - mem_writew(0x5C6,(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800)); - mem_writew(0x5C8,0xFD80); - } - - if (bios_user_reset_vector_blob != 0 && !bios_user_reset_vector_blob_run) { - LOG_MSG("BIOS POST: Running user reset vector blob at 0x%lx",(unsigned long)bios_user_reset_vector_blob); - bios_user_reset_vector_blob_run = true; - - assert((bios_user_reset_vector_blob&0xF) == 0); /* must be page aligned */ - - SegSet16(cs,bios_user_reset_vector_blob>>4); - reg_eip = 0; - -#if C_DEBUG - /* help the debugger reflect the new instruction pointer */ - DEBUG_CheckCSIP(); -#endif - - return CBRET_NONE; - } - - if (cpu.pmode) E_Exit("BIOS error: POST function called while in protected/vm86 mode"); - - CPU_CLI(); - - /* we need A20 enabled for BIOS boot-up */ - void A20Gate_OverrideOn(Section *sec); - void MEM_A20_Enable(bool enabled); - A20Gate_OverrideOn(NULL); - MEM_A20_Enable(true); - - BIOS_OnResetComplete(NULL); - - adapter_scan_start = 0xC0000; - bios_has_exec_vga_bios = false; - LOG(LOG_MISC,LOG_DEBUG)("BIOS: executing POST routine"); - - if (ACPI_REGION_SIZE != 0 && !IS_PC98_ARCH) { - // place it just below the mirror of the BIOS at FFFF0000 - ACPI_BASE = 0xFFFF0000 - ACPI_REGION_SIZE; - - LOG(LOG_MISC,LOG_DEBUG)("ACPI: Setting up version %u.%02x at 0x%lx-0x%lx", - ACPI_version>>8,ACPI_version&0xFF, - (unsigned long)ACPI_BASE,(unsigned long)(ACPI_BASE+ACPI_REGION_SIZE-1lu)); - - ACPI_init(); - ACPI_enabled = true; - ACPI_mem_enable(true); - memset(ACPI_buffer,0,ACPI_buffer_size); - } - - // TODO: Anything we can test in the CPU here? - - // initialize registers - SegSet16(ds,0x0000); - SegSet16(es,0x0000); - SegSet16(fs,0x0000); - SegSet16(gs,0x0000); - SegSet16(ss,0x0000); - - { - Bitu sz = MEM_TotalPages(); - - /* The standard BIOS is said to put its stack (at least at OS boot time) 512 bytes past the end of the boot sector - * meaning that the boot sector loads to 0000:7C00 and the stack is set grow downward from 0000:8000 */ - - if (sz > 8) sz = 8; /* 4KB * 8 = 32KB = 0x8000 */ - sz *= 4096; - reg_esp = sz - 4; - reg_ebp = 0; - LOG(LOG_MISC,LOG_DEBUG)("BIOS: POST stack set to 0000:%04x",reg_esp); - } - - if (dosbox_int_iocallout != IO_Callout_t_none) { - IO_FreeCallout(dosbox_int_iocallout); - dosbox_int_iocallout = IO_Callout_t_none; - } - - if (isapnp_biosstruct_base != 0) { - ROMBIOS_FreeMemory(isapnp_biosstruct_base); - isapnp_biosstruct_base = 0; - } - - if (acpi_iocallout != IO_Callout_t_none) { - IO_FreeCallout(acpi_iocallout); - acpi_iocallout = IO_Callout_t_none; - } - - if (BOCHS_PORT_E9) { - delete BOCHS_PORT_E9; - BOCHS_PORT_E9=NULL; - } - if (ISAPNP_PNP_ADDRESS_PORT) { - delete ISAPNP_PNP_ADDRESS_PORT; - ISAPNP_PNP_ADDRESS_PORT=NULL; - } - if (ISAPNP_PNP_DATA_PORT) { - delete ISAPNP_PNP_DATA_PORT; - ISAPNP_PNP_DATA_PORT=NULL; - } - if (ISAPNP_PNP_READ_PORT) { - delete ISAPNP_PNP_READ_PORT; - ISAPNP_PNP_READ_PORT=NULL; - } - - if (bochs_port_e9) { - if (BOCHS_PORT_E9 == NULL) { - BOCHS_PORT_E9 = new IO_WriteHandleObject; - BOCHS_PORT_E9->Install(0xE9,bochs_port_e9_write,IO_MB); - } - LOG(LOG_MISC,LOG_DEBUG)("Bochs port E9h emulation is active"); - } - else { - if (BOCHS_PORT_E9 != NULL) { - delete BOCHS_PORT_E9; - BOCHS_PORT_E9 = NULL; - } - } - - extern Bitu call_default; - - if (IS_PC98_ARCH) { - /* INT 00h-FFh generic stub routine */ - /* NTS: MS-DOS on PC-98 will fill all yet-unused interrupt vectors with a stub. - * No vector is left at 0000:0000. On a related note, PC-98 games apparently - * like to call INT 33h (mouse functions) without first checking that the - * vector is non-null. */ - callback[18].Uninstall(); - callback[18].Install(&INTGEN_PC98_Handler,CB_IRET,"Int stub ???"); - for (unsigned int i=0x00;i < 0x100;i++) RealSetVec(i,callback[18].Get_RealPointer()); - - for (unsigned int i=0x00;i < 0x08;i++) - real_writed(0,i*4,CALLBACK_RealPointer(call_default)); - - // STOP interrupt or invalid opcode - real_writed(0,0x06*4,CALLBACK_RealPointer(call_pc98_default_stop)); - - // Magical Girl Pretty Sammy installer - // Installer enters an infinite loop if lower 8 bits of the segment portion of int 7 are 0 - real_writew(0, 7*4, real_readw(0, 7*4) - 0x10); - real_writew(0, 7*4+2, real_readw(0, 7*4+2) + 1); - } - else { - /* Clear the vector table */ - for (uint16_t i=0x70*4;i<0x400;i++) real_writeb(0x00,i,0); - - /* Only setup default handler for first part of interrupt table */ - for (uint16_t ct=0;ct<0x60;ct++) { - real_writed(0,ct*4,CALLBACK_RealPointer(call_default)); - } - for (uint16_t ct=0x68;ct<0x70;ct++) { - if(!IS_J3100 || ct != 0x6f) - real_writed(0,ct*4,CALLBACK_RealPointer(call_default)); - } - - // default handler for IRQ 2-7 - for (uint16_t ct=0x0A;ct <= 0x0F;ct++) - RealSetVec(ct,BIOS_DEFAULT_IRQ07_DEF_LOCATION); - } - - if (unhandled_irq_method == UNHANDLED_IRQ_COOPERATIVE_2ND) { - // PC-98 style: Master PIC ack with 0x20 for IRQ 0-7. - // For the slave PIC, ack with 0x20 on the slave, then only ack the master (cascade interrupt) - // if the ISR register on the slave indicates none are in service. - CALLBACK_Setup(call_irq07default,NULL,CB_IRET_EOI_PIC1,Real2Phys(BIOS_DEFAULT_IRQ07_DEF_LOCATION),"bios irq 0-7 default handler"); - CALLBACK_Setup(call_irq815default,Default_IRQ_Handler_Cooperative_Slave_Pic,CB_IRET,Real2Phys(BIOS_DEFAULT_IRQ815_DEF_LOCATION),"bios irq 8-15 default handler"); - } - else { - // IBM PC style: Master PIC ack with 0x20, slave PIC ack with 0x20, no checking - CALLBACK_Setup(call_irq07default,NULL,CB_IRET_EOI_PIC1,Real2Phys(BIOS_DEFAULT_IRQ07_DEF_LOCATION),"bios irq 0-7 default handler"); - CALLBACK_Setup(call_irq815default,NULL,CB_IRET_EOI_PIC2,Real2Phys(BIOS_DEFAULT_IRQ815_DEF_LOCATION),"bios irq 8-15 default handler"); - } - - if (IS_PC98_ARCH) { - BIOS_UnsetupKeyboard(); - BIOS_UnsetupDisks(); - - /* no such INT 4Bh */ - int4b_callback.Uninstall(); - - /* remove some IBM-style BIOS interrupts that don't exist on PC-98 */ - /* IRQ to INT arrangement - * - * IBM PC-98 IRQ - * -------------------------------- - * 0x08 0x08 0 - * 0x09 0x09 1 - * 0x0A CASCADE 0x0A 2 - * 0x0B 0x0B 3 - * 0x0C 0x0C 4 - * 0x0D 0x0D 5 - * 0x0E 0x0E 6 - * 0x0F 0x0F CASCADE 7 - * 0x70 0x10 8 - * 0x71 0x11 9 - * 0x72 0x12 10 - * 0x73 0x13 11 - * 0x74 0x14 12 - * 0x75 0x15 13 - * 0x76 0x16 14 - * 0x77 0x17 15 - * - * As part of the change the IRQ cascade emulation needs to change for PC-98 as well. - * IBM uses IRQ 2 for cascade. - * PC-98 uses IRQ 7 for cascade. */ - - void INT10_EnterPC98(Section *sec); - INT10_EnterPC98(NULL); /* INT 10h */ - - callback_pc98_lio.Uninstall(); - - callback_pc98_avspcm.Uninstall(); - - callback[1].Uninstall(); /* INT 11h */ - callback[2].Uninstall(); /* INT 12h */ - callback[3].Uninstall(); /* INT 14h */ - callback[4].Uninstall(); /* INT 15h */ - callback[5].Uninstall(); /* INT 17h */ - callback[6].Uninstall(); /* INT 1Ah */ - callback[7].Uninstall(); /* INT 1Ch */ - callback[10].Uninstall(); /* INT 19h */ - callback[11].Uninstall(); /* INT 76h: IDE IRQ 14 */ - callback[12].Uninstall(); /* INT 77h: IDE IRQ 15 */ - callback[15].Uninstall(); /* INT 18h: Enter BASIC */ - callback[19].Uninstall(); /* INT 1Bh */ - - /* IRQ 6 is nothing special */ - callback[13].Uninstall(); /* INT 0Eh: IDE IRQ 6 */ - callback[13].Install(NULL,CB_IRET_EOI_PIC1,"irq 6"); - - /* IRQ 8 is nothing special */ - callback[8].Uninstall(); - callback[8].Install(NULL,CB_IRET_EOI_PIC2,"irq 8"); - - /* IRQ 9 is nothing special */ - callback[9].Uninstall(); - callback[9].Install(NULL,CB_IRET_EOI_PIC2,"irq 9"); - - /* INT 18h keyboard and video display functions */ - callback[1].Install(&INT18_PC98_Handler,CB_INT16,"Int 18 keyboard and display"); - callback[1].Set_RealVec(0x18,/*reinstall*/true); - - /* INT 19h *STUB* */ - callback[2].Install(&INT19_PC98_Handler,CB_IRET,"Int 19 ???"); - callback[2].Set_RealVec(0x19,/*reinstall*/true); - - /* INT 1Ah *STUB* */ - callback[3].Install(&INT1A_PC98_Handler,CB_IRET,"Int 1A ???"); - callback[3].Set_RealVec(0x1A,/*reinstall*/true); - - /* MS-DOS 5.0 FIXUP: - * - For whatever reason, if we set bits in the BIOS data area that - * indicate we're NOT the original model of the PC-98, MS-DOS will - * hook our INT 1Ah and then call down to 0x19 bytes into our - * INT 1Ah procedure. If anyone can explain this, I'd like to hear it. --J.C. - * - * NTS: On real hardware, the BIOS appears to have an INT 1Ah, a bunch of NOPs, - * then at 0x19 bytes into the procedure, the actual handler. This is what - * MS-DOS is pointing at. - * - * But wait, there's more. - * - * MS-DOS calldown pushes DS and DX onto the stack (after the IRET frame) - * before JMPing into the BIOS. - * - * Apparently the function at INT 1Ah + 0x19 is expected to do this: - * - * - * POP DX - * POP DS - * IRET - * - * I can only imaging what a headache this might have caused NEC when - * maintaining the platform and compatibility! */ - { - Bitu addr = callback[3].Get_RealPointer(); - addr = ((addr >> 16) << 4) + (addr & 0xFFFF); - - /* to make this work, we need to pop the two regs, then JMP to our - * callback and proceed as normal. */ - phys_writeb(addr + 0x19,0x5A); // POP DX - phys_writeb(addr + 0x1A,0x1F); // POP DS - phys_writeb(addr + 0x1B,0xEB); // jmp short ... - phys_writeb(addr + 0x1C,0x100 - 0x1D); - } - - /* INT 1Bh *STUB* */ - callback[4].Install(&INT1B_PC98_Handler,CB_IRET,"Int 1B ???"); - callback[4].Set_RealVec(0x1B,/*reinstall*/true); - - /* INT 1Ch *STUB* */ - callback[5].Install(&INT1C_PC98_Handler,CB_IRET,"Int 1C ???"); - callback[5].Set_RealVec(0x1C,/*reinstall*/true); - - /* INT 1Dh *STUB* */ - /* Place it in the PC-98 int vector area at FD80:0000 to satisfy some DOS games - * that detect PC-98 from the segment value of the vector (issue #927). - * Note that on real hardware (PC-9821) INT 1Dh appears to be a stub that IRETs immediately. */ - callback[6].Install(&INT1D_PC98_Handler,CB_IRET,"Int 1D ???"); -// callback[6].Set_RealVec(0x1D,/*reinstall*/true); - { - Bitu ofs = 0xFD813; /* 0xFD80:0013 try not to look like a phony address */ - unsigned int vec = 0x1D; - uint32_t target = callback[6].Get_RealPointer(); - - phys_writeb(ofs+0,0xEA); // JMP FAR - phys_writed(ofs+1,target); - - phys_writew((vec*4)+0,(ofs-0xFD800)); - phys_writew((vec*4)+2,0xFD80); - } - - /* INT 1Eh *STUB* */ - callback[7].Install(&INT1E_PC98_Handler,CB_IRET,"Int 1E ???"); - callback[7].Set_RealVec(0x1E,/*reinstall*/true); - - /* INT 1Fh *STUB* */ - callback[10].Install(&INT1F_PC98_Handler,CB_IRET,"Int 1F ???"); - callback[10].Set_RealVec(0x1F,/*reinstall*/true); - - /* INT DCh *STUB* */ - callback[16].Install(&INTDC_PC98_Handler,CB_IRET,"Int DC ???"); - callback[16].Set_RealVec(0xDC,/*reinstall*/true); - - /* INT F2h *STUB* */ - callback[17].Install(&INTF2_PC98_Handler,CB_IRET,"Int F2 ???"); - callback[17].Set_RealVec(0xF2,/*reinstall*/true); - - // default handler for IRQ 2-7 - for (uint16_t ct=0x0A;ct <= 0x0F;ct++) - RealSetVec(ct,BIOS_DEFAULT_IRQ07_DEF_LOCATION); - - // default handler for IRQ 8-15 - for (uint16_t ct=0;ct < 8;ct++) - RealSetVec(ct+(IS_PC98_ARCH ? 0x10 : 0x70),BIOS_DEFAULT_IRQ815_DEF_LOCATION); - - // LIO graphics interface (number of entry points, unknown WORD value and offset into the segment). - // For more information see Chapter 6 of this PDF [https://ia801305.us.archive.org/8/items/PC9800TechnicalDataBookBIOS1992/PC-9800TechnicalDataBook_BIOS_1992_text.pdf] - { - callback_pc98_lio.Install(&PC98_BIOS_LIO,CB_IRET,"LIO graphics library"); - - Bitu ofs = 0xF990u << 4u; // F990:0000... - unsigned int entrypoints = 0x11; - Bitu final_addr = callback_pc98_lio.Get_RealPointer(); - - /* NTS: Based on GAME/MAZE 999 behavior, these numbers are interrupt vector numbers. - * The entry point marked 0xA0 is copied by the game to interrupt vector A0 and - * then called with INT A0h even though it blindly assumes the numbers are - * sequential from 0xA0-0xAF. */ - unsigned char entrypoint_indexes[0x11] = { - 0xA0, 0xA1, 0xA2, 0xA3, // +0x00 - 0xA4, 0xA5, 0xA6, 0xA7, // +0x04 - 0xA8, 0xA9, 0xAA, 0xAB, // +0x08 - 0xAC, 0xAD, 0xAE, 0xAF, // +0x0C - 0xCE // +0x10 - }; - - assert(((entrypoints * 4) + 4) <= 0x50); - assert((50 + (entrypoints * 7)) <= 0x100); // a 256-byte region is set aside for this! - - phys_writed(ofs+0,entrypoints); - for (unsigned int ent=0;ent < entrypoints;ent++) { - /* each entry point is "MOV AL, ; JMP FAR " */ - /* Yksoft1's patch suggests a segment offset of 0x50 which I'm OK with */ - unsigned int ins_ofs = ofs + 0x50 + (ent * 7); - - phys_writew(ofs+4+(ent*4)+0,entrypoint_indexes[ent]); - phys_writew(ofs+4+(ent*4)+2,ins_ofs - ofs); - - phys_writeb(ins_ofs+0,0xB0); // MOV AL,(entrypoint index) - phys_writeb(ins_ofs+1,entrypoint_indexes[ent]); - phys_writeb(ins_ofs+2,0xEA); // JMP FAR - phys_writed(ins_ofs+3,final_addr); - // total: ins_ofs+7 - } - } - - callback_pc98_avspcm.Install(&PC98_AVSDRV_PCM_Handler,CB_IRET,"AVSDRV.SYS PCM driver"); - callback_pc98_avspcm.Set_RealVec(0xd9, true); - } - - if (IS_PC98_ARCH) { - real_writew(0,0x58A,0x0000U); // countdown timer value - PIC_SetIRQMask(0,true); /* PC-98 keeps the timer off unless INT 1Ch is called to set a timer interval */ - } - - bool null_68h = false; - - { - Section_prop * section=static_cast(control->GetSection("dos")); - - null_68h = section->Get_bool("zero unused int 68h"); - } - - /* Default IRQ handler */ - if (call_irq_default == 0) - call_irq_default = CALLBACK_Allocate(); - CALLBACK_Setup(call_irq_default, &Default_IRQ_Handler, CB_IRET, "irq default"); - RealSetVec(0x0b, CALLBACK_RealPointer(call_irq_default)); // IRQ 3 - RealSetVec(0x0c, CALLBACK_RealPointer(call_irq_default)); // IRQ 4 - RealSetVec(0x0d, CALLBACK_RealPointer(call_irq_default)); // IRQ 5 - RealSetVec(0x0f, CALLBACK_RealPointer(call_irq_default)); // IRQ 7 - if (!IS_PC98_ARCH) { - RealSetVec(0x72, CALLBACK_RealPointer(call_irq_default)); // IRQ 10 - RealSetVec(0x73, CALLBACK_RealPointer(call_irq_default)); // IRQ 11 - } - - // setup a few interrupt handlers that point to bios IRETs by default - real_writed(0,0x66*4,CALLBACK_RealPointer(call_default)); //war2d - real_writed(0,0x67*4,CALLBACK_RealPointer(call_default)); - if (machine==MCH_CGA || null_68h) real_writed(0,0x68*4,0); //Popcorn - real_writed(0,0x5c*4,CALLBACK_RealPointer(call_default)); //Network stuff - //real_writed(0,0xf*4,0); some games don't like it - - bios_first_init = false; - - DispatchVMEvent(VM_EVENT_BIOS_INIT); - - TIMER_BIOS_INIT_Configure(); - - void INT10_Startup(Section *sec); - INT10_Startup(NULL); - - if (!IS_PC98_ARCH) { - extern uint8_t BIOS_tandy_D4_flag; - real_writeb(0x40,0xd4,BIOS_tandy_D4_flag); - } - - /* INT 13 Bios Disk Support */ - BIOS_SetupDisks(); - - /* INT 16 Keyboard handled in another file */ - BIOS_SetupKeyboard(); - - if (!IS_PC98_ARCH) { - int4b_callback.Set_RealVec(0x4B,/*reinstall*/true); - callback[1].Set_RealVec(0x11,/*reinstall*/true); - callback[2].Set_RealVec(0x12,/*reinstall*/true); - callback[3].Set_RealVec(0x14,/*reinstall*/true); - callback[4].Set_RealVec(0x15,/*reinstall*/true); - callback[5].Set_RealVec(0x17,/*reinstall*/true); - callback[6].Set_RealVec(0x1A,/*reinstall*/true); - callback[7].Set_RealVec(0x1C,/*reinstall*/true); - callback[8].Set_RealVec(0x70,/*reinstall*/true); - callback[9].Set_RealVec(0x71,/*reinstall*/true); - callback[10].Set_RealVec(0x19,/*reinstall*/true); - callback[11].Set_RealVec(0x76,/*reinstall*/true); - callback[12].Set_RealVec(0x77,/*reinstall*/true); - callback[13].Set_RealVec(0x0E,/*reinstall*/true); - callback[15].Set_RealVec(0x18,/*reinstall*/true); - callback[19].Set_RealVec(0x1B,/*reinstall*/true); - } - - // FIXME: We're using IBM PC memory size storage even in PC-98 mode. - // This cannot be removed, because the DOS kernel uses this variable even in PC-98 mode. - mem_writew(BIOS_MEMORY_SIZE,t_conv); - // According to Ripsaw, Tandy systems hold the real memory size in a normally reserved field [https://www.vogons.org/viewtopic.php?p=948898#p948898] - // According to the PCjr hardware reference library that memory location means the same thing - if (machine == MCH_PCJR || machine == MCH_TANDY) mem_writew(BIOS_MEMORY_SIZE+2,t_conv_real); - - RealSetVec(0x08,BIOS_DEFAULT_IRQ0_LOCATION); - // pseudocode for CB_IRQ0: - // sti - // callback INT8_Handler - // push ds,ax,dx - // int 0x1c - // cli - // mov al, 0x20 - // out 0x20, al - // pop dx,ax,ds - // iret - - if (!IS_PC98_ARCH) { - mem_writed(BIOS_TIMER,0); //Calculate the correct time - - // INT 05h: Print Screen - // IRQ1 handler calls it when PrtSc key is pressed; does nothing unless hooked - phys_writeb(Real2Phys(BIOS_DEFAULT_INT5_LOCATION), 0xcf); - RealSetVec(0x05, BIOS_DEFAULT_INT5_LOCATION); - - phys_writew(Real2Phys(RealGetVec(0x12))+0x12,0x20); //Hack for Jurresic - } - - phys_writeb(Real2Phys(BIOS_DEFAULT_HANDLER_LOCATION),0xcf); /* bios default interrupt vector location -> IRET */ - - if (!IS_PC98_ARCH) { - // tandy DAC setup - bool use_tandyDAC=(real_readb(0x40,0xd4)==0xff); - - tandy_sb.port=0; - tandy_dac.port=0; - if (use_tandyDAC) { - /* tandy DAC sound requested, see if soundblaster device is available */ - Bitu tandy_dac_type = 0; - if (Tandy_InitializeSB()) { - tandy_dac_type = 1; - } else if (Tandy_InitializeTS()) { - tandy_dac_type = 2; - } - if (tandy_dac_type) { - real_writew(0x40,0xd0,0x0000); - real_writew(0x40,0xd2,0x0000); - real_writeb(0x40,0xd4,0xff); /* tandy DAC init value */ - real_writed(0x40,0xd6,0x00000000); - /* install the DAC callback handler */ - tandy_DAC_callback[0]=new CALLBACK_HandlerObject(); - tandy_DAC_callback[1]=new CALLBACK_HandlerObject(); - tandy_DAC_callback[0]->Install(&IRQ_TandyDAC,CB_IRET,"Tandy DAC IRQ"); - tandy_DAC_callback[1]->Install(NULL,CB_TDE_IRET,"Tandy DAC end transfer"); - // pseudocode for CB_TDE_IRET: - // push ax - // mov ax, 0x91fb - // int 15 - // cli - // mov al, 0x20 - // out 0x20, al - // pop ax - // iret - - uint8_t tandy_irq = 7; - if (tandy_dac_type==1) tandy_irq = tandy_sb.irq; - else if (tandy_dac_type==2) tandy_irq = tandy_dac.irq; - uint8_t tandy_irq_vector = tandy_irq; - if (tandy_irq_vector<8) tandy_irq_vector += 8; - else tandy_irq_vector += (0x70-8); - - RealPt current_irq=RealGetVec(tandy_irq_vector); - real_writed(0x40,0xd6,current_irq); - for (uint16_t i=0; i<0x10; i++) phys_writeb(PhysMake(0xf000,0xa084+i),0x80); - } else real_writeb(0x40,0xd4,0x00); - } - } - - if (!IS_PC98_ARCH) { - /* Setup some stuff in 0x40 bios segment */ - - // Disney workaround - // uint16_t disney_port = mem_readw(BIOS_ADDRESS_LPT1); - // port timeouts - // always 1 second even if the port does not exist - // BIOS_SetLPTPort(0, disney_port); - for(Bitu i = 1; i < 3; i++) BIOS_SetLPTPort(i, 0); - mem_writeb(BIOS_COM1_TIMEOUT,1); - mem_writeb(BIOS_COM2_TIMEOUT,1); - mem_writeb(BIOS_COM3_TIMEOUT,1); - mem_writeb(BIOS_COM4_TIMEOUT,1); - - void BIOS_Post_register_parports(); - BIOS_Post_register_parports(); - - void BIOS_Post_register_comports(); - BIOS_Post_register_comports(); - } - - if (!IS_PC98_ARCH) { - /* Setup equipment list */ - // look http://www.bioscentral.com/misc/bda.htm - - //uint16_t config=0x4400; //1 Floppy, 2 serial and 1 parallel - uint16_t config = 0x0; - - config |= bios_post_parport_count() << 14; - config |= bios_post_comport_count() << 9; - -#if (C_FPU) - //FPU - if (enable_fpu) - config|=0x2; -#endif - switch (machine) { - case MCH_MDA: - case MCH_HERC: - //Startup monochrome - config|=0x30; - break; - case EGAVGA_ARCH_CASE: - case MCH_CGA: - case MCH_MCGA: - case TANDY_ARCH_CASE: - case MCH_AMSTRAD: - //Startup 80x25 color - config|=0x20; - break; - default: - //EGA VGA - config|=0; - break; - } - - // PS2 mouse - if (KEYBOARD_Report_BIOS_PS2Mouse()) - config |= 0x04; - - // DMA *not* supported - Ancient Art of War CGA uses this to identify PCjr - if (machine==MCH_PCJR) config |= 0x100; - - // Several online sources say bit 0 indicates a floppy drive is installed. - // Testing of a couple BIOSes from 1992 and 1993 showed bit 0 to always be 1, - // even with no floppy drives installed or configured in the BIOS. - // Maybe 0 is possible in older BIOSes. - config |= 0x01; - - // Bit 6 is 1 if there are 2 floppies connected and configured in the BIOS. - // Setting to 1 since DOSBox-X can mount floppy images in both drives A and B. - config |= 0x40; - - // Bit 12 is "game I/O attached" for PCJr, Tandy and PC/XT, and 0 (not used) for PC/AT - if ((CPU_ArchitectureType == CPU_ARCHTYPE_8086) && (joytype != JOY_NONE)) - config |= 0x1000; - - mem_writew(BIOS_CONFIGURATION,config); - if (IS_EGAVGA_ARCH) config &= ~0x30; //EGA/VGA startup display mode differs in CMOS - CMOS_SetRegister(0x14,(uint8_t)(config&0xff)); //Should be updated on changes - } - - if (!IS_PC98_ARCH) { - /* Setup extended memory size */ - IO_Write(0x70,0x30); - size_extended=IO_Read(0x71); - IO_Write(0x70,0x31); - size_extended|=(IO_Read(0x71) << 8); - - uint32_t value = 0; - - RtcUpdateDone(); - IO_Write(0x70,0xB); - IO_Write(0x71,0x02); // BCD - - /* set BIOS_TIMER according to time/date of RTC */ - IO_Write(0x70,0); - const unsigned char sec = BCD2BIN(IO_Read(0x71)); - IO_Write(0x70,2); - const unsigned char min = BCD2BIN(IO_Read(0x71)); - IO_Write(0x70,4); - const unsigned char hour = BCD2BIN(IO_Read(0x71)); - - value = (uint32_t)(((hour * 3600.00) + (min * 60.00) + sec) * ((double)PIT_TICK_RATE/65536.0)); - - mem_writed(BIOS_TIMER,value); - } - else { - /* Provide a valid memory size anyway */ - size_extended=MEM_TotalPages()*4; - if (size_extended >= 1024) size_extended -= 1024; - else size_extended = 0; - } - - /* PS/2 mouse */ - void BIOS_PS2Mouse_Startup(Section *sec); - BIOS_PS2Mouse_Startup(NULL); - - if (!IS_PC98_ARCH) { - /* this belongs HERE not on-demand from INT 15h! */ - biosConfigSeg = ROMBIOS_GetMemory(16/*one paragraph*/,"BIOS configuration (INT 15h AH=0xC0)",/*paragraph align*/16)>>4; - if (biosConfigSeg != 0) { - PhysPt data = PhysMake(biosConfigSeg,0); - phys_writew(data,8); // 8 Bytes following - if (IS_TANDY_ARCH) { - if (machine==MCH_TANDY) { - // Model ID (Tandy) - phys_writeb(data+2,0xFF); - } else { - // Model ID (PCJR) - phys_writeb(data+2,0xFD); - } - phys_writeb(data+3,0x0A); // Submodel ID - phys_writeb(data+4,0x10); // Bios Revision - /* Tandy doesn't have a 2nd PIC, left as is for now */ - phys_writeb(data+5,(1<<6)|(1<<5)|(1<<4)); // Feature Byte 1 - } else { - if (machine==MCH_MCGA) { - /* PC/2 model 30 model */ - phys_writeb(data+2,0xFA); - phys_writeb(data+3,0x00); // Submodel ID (PS/2) model 30 - } else if (PS1AudioCard) { /* FIXME: Won't work because BIOS_Init() comes before PS1SOUND_Init() */ - phys_writeb(data+2,0xFC); // Model ID (PC) - phys_writeb(data+3,0x0B); // Submodel ID (PS/1). - } else { - phys_writeb(data+2,0xFC); // Model ID (PC) - phys_writeb(data+3,0x00); // Submodel ID - } - phys_writeb(data+4,0x01); // Bios Revision - phys_writeb(data+5,(1<<6)|(1<<5)|(1<<4)); // Feature Byte 1 - } - phys_writeb(data+6,(1<<6)); // Feature Byte 2 - phys_writeb(data+7,0); // Feature Byte 3 - phys_writeb(data+8,0); // Feature Byte 4 - phys_writeb(data+9,0); // Feature Byte 5 - } - } - - // ISA Plug & Play I/O ports - if (!IS_PC98_ARCH && ISAPNPPORT) { - ISAPNP_PNP_ADDRESS_PORT = new IO_WriteHandleObject; - ISAPNP_PNP_ADDRESS_PORT->Install(0x279,isapnp_write_port,IO_MB); - ISAPNP_PNP_DATA_PORT = new IO_WriteHandleObject; - ISAPNP_PNP_DATA_PORT->Install(0xA79,isapnp_write_port,IO_MB); - ISAPNP_PNP_READ_PORT = new IO_ReadHandleObject; - ISAPNP_PNP_READ_PORT->Install(ISA_PNP_WPORT,isapnp_read_port,IO_MB); - LOG(LOG_MISC,LOG_DEBUG)("Registered ISA PnP read port at 0x%03x",ISA_PNP_WPORT); - } - - if (enable_integration_device) { - /* integration device callout */ - if (dosbox_int_iocallout == IO_Callout_t_none) - dosbox_int_iocallout = IO_AllocateCallout(IO_TYPE_MB); - if (dosbox_int_iocallout == IO_Callout_t_none) - E_Exit("Failed to get dosbox-x integration IO callout handle"); - - { - IO_CalloutObject *obj = IO_GetCallout(dosbox_int_iocallout); - if (obj == NULL) E_Exit("Failed to get dosbox-x integration IO callout"); - - /* NTS: Ports 28h-2Bh conflict with extended DMA control registers in PC-98 mode. - * TODO: Move again, if DB28h-DB2Bh are taken by something standard on PC-98. */ - obj->Install(IS_PC98_ARCH ? 0xDB28 : 0x28, - IOMASK_Combine(IOMASK_FULL,IOMASK_Range(4)),dosbox_integration_cb_port_r,dosbox_integration_cb_port_w); - IO_PutCallout(obj); - } - - /* DOSBox-X integration device */ - if (!IS_PC98_ARCH && isapnpigdevice == NULL && enable_integration_device_pnp) { - isapnpigdevice = new ISAPnPIntegrationDevice; - ISA_PNP_devreg(isapnpigdevice); - } - } - - // ISA Plug & Play BIOS entrypoint - // NTS: Apparently, Windows 95, 98, and ME will re-enumerate and re-install PnP devices if our entry point changes its address. - if (!IS_PC98_ARCH && ISAPNPBIOS) { - Bitu base; - unsigned int i; - unsigned char c,tmp[256]; - - isapnp_biosstruct_base = base = ROMBIOS_GetMemory(0x21,"ISA Plug & Play BIOS struct",/*paragraph alignment*/0x10); - - if (base == 0) E_Exit("Unable to allocate ISA PnP struct"); - LOG_MSG("ISA Plug & Play BIOS enabled"); - - call_pnp_r = CALLBACK_Allocate(); - call_pnp_rp = PNPentry_real = CALLBACK_RealPointer(call_pnp_r); - CALLBACK_Setup(call_pnp_r,ISAPNP_Handler_RM,CB_RETF,"ISA Plug & Play entry point (real)"); - //LOG_MSG("real entry pt=%08lx\n",PNPentry_real); - - call_pnp_p = CALLBACK_Allocate(); - call_pnp_pp = PNPentry_prot = CALLBACK_RealPointer(call_pnp_p); - CALLBACK_Setup(call_pnp_p,ISAPNP_Handler_PM,CB_RETF,"ISA Plug & Play entry point (protected)"); - //LOG_MSG("prot entry pt=%08lx\n",PNPentry_prot); - - phys_writeb(base+0,'$'); - phys_writeb(base+1,'P'); - phys_writeb(base+2,'n'); - phys_writeb(base+3,'P'); - phys_writeb(base+4,0x10); /* Version: 1.0 */ - phys_writeb(base+5,0x21); /* Length: 0x21 bytes */ - phys_writew(base+6,0x0000); /* Control field: Event notification not supported */ - /* skip checksum atm */ - phys_writed(base+9,0); /* Event notify flag addr: (none) */ - phys_writed(base+0xD,call_pnp_rp); /* Real-mode entry point */ - phys_writew(base+0x11,call_pnp_pp&0xFFFF); /* Protected mode offset */ - phys_writed(base+0x13,(call_pnp_pp >> 12) & 0xFFFF0); /* Protected mode code segment base */ - phys_writed(base+0x17,ISAPNP_ID('D','O','S',0,8,4,0)); /* OEM device identifier (DOSBox-X 0.84.x) */ - phys_writew(base+0x1B,0xF000); /* real-mode data segment */ - phys_writed(base+0x1D,0xF0000); /* protected mode data segment address */ - /* run checksum */ - c=0; - for (i=0;i < 0x21;i++) { - if (i != 8) c += phys_readb(base+i); - } - phys_writeb(base+8,0x100-c); /* checksum value: set so that summing bytes across the struct == 0 */ - - /* input device (keyboard) */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Keyboard,sizeof(ISAPNP_sysdev_Keyboard),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* input device (mouse) */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Mouse,sizeof(ISAPNP_sysdev_Mouse),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* DMA controller */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_DMA_Controller,sizeof(ISAPNP_sysdev_DMA_Controller),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* Interrupt controller */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PIC,sizeof(ISAPNP_sysdev_PIC),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* Timer */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Timer,sizeof(ISAPNP_sysdev_Timer),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* Realtime clock */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_RTC,sizeof(ISAPNP_sysdev_RTC),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* PC speaker */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PC_Speaker,sizeof(ISAPNP_sysdev_PC_Speaker),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* System board */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_System_Board,sizeof(ISAPNP_sysdev_System_Board),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* Motherboard PNP resources and general */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_General_ISAPNP,sizeof(ISAPNP_sysdev_General_ISAPNP),true)) - LOG_MSG("ISAPNP register failed\n"); - - /* ISA bus, meaning, a computer with ISA slots. - * The purpose of this device is to convince Windows 95 to automatically install it's - * "ISA Plug and Play bus" so that PnP devices are recognized automatically */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_ISA_BUS,sizeof(ISAPNP_sysdev_ISA_BUS),true)) - LOG_MSG("ISAPNP register failed\n"); - - if (pcibus_enable) { - /* PCI bus, meaning, a computer with PCI slots. - * The purpose of this device is to tell Windows 95 that a PCI bus is present. Without - * this entry, PCI devices will not be recognized until you manually install the PCI driver. */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_PCI_BUS,sizeof(ISAPNP_sysdev_PCI_BUS),true)) - LOG_MSG("ISAPNP register failed\n"); - } - - /* APM BIOS device. To help Windows 95 see our APM BIOS. */ - if (APMBIOS && APMBIOS_pnp) { - LOG_MSG("Registering APM BIOS as ISA Plug & Play BIOS device node"); - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_APM_BIOS,sizeof(ISAPNP_sysdev_APM_BIOS),true)) - LOG_MSG("ISAPNP register failed\n"); - } - -#if (C_FPU) - /* Numeric Coprocessor */ - if (!ISAPNP_RegisterSysDev(ISAPNP_sysdev_Numeric_Coprocessor,sizeof(ISAPNP_sysdev_Numeric_Coprocessor),true)) - LOG_MSG("ISAPNP register failed\n"); -#endif - - /* RAM resources. we have to construct it */ - /* NTS: We don't do this here, but I have an old Toshiba laptop who's PnP BIOS uses - * this device ID to report both RAM and ROM regions. */ - { - Bitu max = MEM_TotalPages() * 4096; - const unsigned char h1[9] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0xC,0x0,0x1), /* PNP0C01 System device, motherboard resources */ - ISAPNP_TYPE(0x05,0x00,0x00), /* type: Memory, RAM, general */ - 0x0001 | 0x0002) - }; - - i = 0; - memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ - /*----------allocated--------*/ - tmp[i+0] = 0x80 | 6; /* 32-bit memory range */ - tmp[i+1] = 9; /* length=9 */ - tmp[i+2] = 0; - tmp[i+3] = 0x01; /* writeable, no cache, 8-bit, not shadowable, not ROM */ - host_writed(tmp+i+4,0x00000); /* base */ - host_writed(tmp+i+8,max > 0xA0000 ? 0xA0000 : 0x00000); /* length */ - i += 9+3; - - if (max > 0x100000) { - tmp[i+0] = 0x80 | 6; /* 32-bit memory range */ - tmp[i+1] = 9; /* length=9 */ - tmp[i+2] = 0; - tmp[i+3] = 0x01; - host_writed(tmp+i+4,0x100000); /* base */ - host_writed(tmp+i+8,max-0x100000); /* length */ - i += 9+3; - } - - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - /*-------------possible-----------*/ - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - /*-------------compatible---------*/ - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - - if (!ISAPNP_RegisterSysDev(tmp,i)) - LOG_MSG("ISAPNP register failed\n"); - } - - /* register parallel ports */ - for (Bitu portn=0;portn < 3;portn++) { - Bitu port = mem_readw(BIOS_ADDRESS_LPT1+(portn*2)); - if (port != 0) { - const unsigned char h1[9] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0x4,0x0,0x0), /* PNP0400 Standard LPT printer port */ - ISAPNP_TYPE(0x07,0x01,0x00), /* type: General parallel port */ - 0x0001 | 0x0002) - }; - - i = 0; - memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ - /*----------allocated--------*/ - tmp[i+0] = (8 << 3) | 7; /* IO resource */ - tmp[i+1] = 0x01; /* 16-bit decode */ - host_writew(tmp+i+2,port); /* min */ - host_writew(tmp+i+4,port); /* max */ - tmp[i+6] = 0x10; /* align */ - tmp[i+7] = 0x03; /* length */ - i += 7+1; - - /* TODO: If/when LPT emulation handles the IRQ, add IRQ resource here */ - - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - /*-------------possible-----------*/ - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - /*-------------compatible---------*/ - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - - if (!ISAPNP_RegisterSysDev(tmp,i)) - LOG_MSG("ISAPNP register failed\n"); - } - } - - void BIOS_Post_register_comports_PNP(); - BIOS_Post_register_comports_PNP(); - - void BIOS_Post_register_IDE(); - BIOS_Post_register_IDE(); - - void BIOS_Post_register_FDC(); - BIOS_Post_register_FDC(); - } - - if (IS_PC98_ARCH) { - /* initialize IRQ0 timer to default tick interval. - * PC-98 does not pre-initialize timer 0 of the PIT to 0xFFFF the way IBM PC/XT/AT do */ - PC98_Interval_Timer_Continue(); - PIC_SetIRQMask(0,true); /* PC-98 keeps the timer off unless INT 1Ch is called to set a timer interval */ - } - - if (!IS_PC98_ARCH) { - Section_prop * section=static_cast(control->GetSection("speaker")); - bool bit0en = section->Get_bool("pcspeaker clock gate enable at startup"); - - if (bit0en) { - uint8_t x = IO_Read(0x61); - IO_Write(0x61,(x & (~3u)) | 1u); /* set bits[1:0] = 01 (clock gate enable but output gate disable) */ - LOG_MSG("xxxx"); - } - } - - if (ACPI_enabled) { - if (acpi_iocallout == IO_Callout_t_none) - acpi_iocallout = IO_AllocateCallout(IO_TYPE_MB); - if (acpi_iocallout == IO_Callout_t_none) - E_Exit("Failed to get ACPI IO callout handle"); - - { - IO_CalloutObject *obj = IO_GetCallout(acpi_iocallout); - if (obj == NULL) E_Exit("Failed to get ACPI IO callout"); - obj->Install(ACPI_IO_BASE,IOMASK_Combine(IOMASK_FULL,IOMASK_Range(0x20)),acpi_cb_port_r,acpi_cb_port_w); - IO_PutCallout(obj); - } - - BuildACPITable(); - } - - CPU_STI(); - - return CBRET_NONE; - } - CALLBACK_HandlerObject cb_bios_scan_video_bios; - static Bitu cb_bios_scan_video_bios__func(void) { - unsigned long size; - - /* NTS: As far as I can tell, video is integrated into the PC-98 BIOS and there is no separate BIOS */ - if (IS_PC98_ARCH) return CBRET_NONE; - - if (cpu.pmode) E_Exit("BIOS error: VIDEO BIOS SCAN function called while in protected/vm86 mode"); - - if (!bios_has_exec_vga_bios) { - bios_has_exec_vga_bios = true; - if (IS_EGAVGA_ARCH) { - /* make sure VGA BIOS is there at 0xC000:0x0000 */ - if (AdapterROM_Read(0xC0000,&size)) { - LOG(LOG_MISC,LOG_DEBUG)("BIOS VIDEO ROM SCAN found VGA BIOS (size=%lu)",size); - adapter_scan_start = 0xC0000 + size; - - // step back into the callback instruction that triggered this call - reg_eip -= 4; - - // FAR CALL into the VGA BIOS - CPU_CALL(false,0xC000,0x0003,reg_eip); - return CBRET_NONE; - } - else { - LOG(LOG_MISC,LOG_WARN)("BIOS VIDEO ROM SCAN did not find VGA BIOS"); - } - } - else { - // CGA, MDA, Tandy, PCjr. No video BIOS to scan for - } - } - - return CBRET_NONE; - } - CALLBACK_HandlerObject cb_bios_adapter_rom_scan; - static Bitu cb_bios_adapter_rom_scan__func(void) { - unsigned long size; - uint32_t c1; - - /* FIXME: I have no documentation on how PC-98 scans for adapter ROM or even if it supports it */ - if (IS_PC98_ARCH) return CBRET_NONE; - - if (cpu.pmode) E_Exit("BIOS error: ADAPTER ROM function called while in protected/vm86 mode"); - - while (adapter_scan_start < 0xF0000) { - if (AdapterROM_Read(adapter_scan_start,&size)) { - uint16_t segm = (uint16_t)(adapter_scan_start >> 4); - - LOG(LOG_MISC,LOG_DEBUG)("BIOS ADAPTER ROM scan found ROM at 0x%lx (size=%lu)",(unsigned long)adapter_scan_start,size); - - c1 = mem_readd(adapter_scan_start+3); - adapter_scan_start += size; - if (c1 != 0UL) { - LOG(LOG_MISC,LOG_DEBUG)("Running ADAPTER ROM entry point"); - - // step back into the callback instruction that triggered this call - reg_eip -= 4; - - // FAR CALL into the VGA BIOS - CPU_CALL(false,segm,0x0003,reg_eip); - return CBRET_NONE; - } - else { - LOG(LOG_MISC,LOG_DEBUG)("FIXME: ADAPTER ROM entry point does not exist"); - } - } - else { - if (IS_EGAVGA_ARCH) // supposedly newer systems only scan on 2KB boundaries by standard? right? - adapter_scan_start = (adapter_scan_start | 2047UL) + 1UL; - else // while older PC/XT systems scanned on 512-byte boundaries? right? - adapter_scan_start = (adapter_scan_start | 511UL) + 1UL; - } - } - - LOG(LOG_MISC,LOG_DEBUG)("BIOS ADAPTER ROM scan complete"); - return CBRET_NONE; - } - CALLBACK_HandlerObject cb_bios_startup_screen; - static Bitu cb_bios_startup_screen__func(void) { - const Section_prop* section = static_cast(control->GetSection("dosbox")); - const char *logo_text = section->Get_string("logo text"); - const char *logo = section->Get_string("logo"); - bool fastbioslogo=section->Get_bool("fastbioslogo")||control->opt_fastbioslogo||control->opt_fastlaunch; - if (fastbioslogo && machine != MCH_PC98) { -#if defined(USE_TTF) - if (TTF_using()) { - uint32_t lasttick=GetTicks(); - while ((GetTicks()-lasttick)<500) { - reg_eax = 0x0100; - CALLBACK_RunRealInt(0x16); - } - reg_eax = 3; - CALLBACK_RunRealInt(0x10); - } -#endif - if (control->opt_fastlaunch) return CBRET_NONE; - } - extern const char* RunningProgram; - extern void GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused); - RunningProgram = "DOSBOX-X"; - GFX_SetTitle(-1,-1,-1,false); - const char *msg = "DOSBox-X (C) 2011-" COPYRIGHT_END_YEAR " The DOSBox-X Team\nDOSBox-X project maintainer: joncampbell123\nDOSBox-X project homepage: https://dosbox-x.com\nDOSBox-X user guide: https://dosbox-x.com/wiki\n\n"; - bool textsplash = section->Get_bool("disable graphical splash"); -#if defined(USE_TTF) - if (TTF_using()) { - textsplash = true; - if (ttf.cols != 80 || ttf.lins != 25) { - oldcols = ttf.cols; - oldlins = ttf.lins; - } else - oldcols = oldlins = 0; - } -#endif - - textsplash = true; - - char logostr[8][34]; - strcpy(logostr[0], "+---------------------+"); - strcpy(logostr[1], "| Welcome To |"); - strcpy(logostr[2], "| |"); - strcpy(logostr[3], "| D O S B o x - X ! |"); - strcpy(logostr[4], "| |"); - sprintf(logostr[5],"| %d-bit %s |", - OS_BIT_INT, SDL_STRING); - sprintf(logostr[6], "| Version %10s |", VERSION); - strcpy(logostr[7], "+---------------------+"); -startfunction: - int logo_x,logo_y,x=2,y=2; - - logo_y = 2; - if (machine == MCH_HERC || machine == MCH_MDA) - logo_x = 80 - 2 - (224/9); - else - logo_x = 80 - 2 - (224/8); - - if (cpu.pmode) E_Exit("BIOS error: STARTUP function called while in protected/vm86 mode"); - - if (IS_VGA_ARCH) { - reg_eax = 18; // 640x480 16-color - CALLBACK_RunRealInt(0x10); - } - else if (machine == MCH_PC98) { - // clear the graphics layer - for (unsigned int i=0;i < (80*400);i++) { - mem_writeb(0xA8000+i,0); // B - mem_writeb(0xB0000+i,0); // G - mem_writeb(0xB8000+i,0); // R - mem_writeb(0xE0000+i,0); // E - } - - reg_eax = 0x0C00; // enable text layer (PC-98) - CALLBACK_RunRealInt(0x18); - - reg_eax = 0x1100; // show cursor (PC-98) - CALLBACK_RunRealInt(0x18); - - reg_eax = 0x1300; // set cursor pos (PC-98) - reg_edx = 0x0000; // byte position - CALLBACK_RunRealInt(0x18); - - bios_pc98_posx = x; - } - else { - reg_eax = 3; // 80x25 text - CALLBACK_RunRealInt(0x10); - } - -#if defined(USE_TTF) - if (TTF_using() && (ttf.cols != 80 || ttf.lins != 25)) ttf_setlines(80, 25); -#endif - - if (machine != MCH_PC98) { - reg_eax = 0x0200; // set cursor pos - reg_ebx = 0; // page zero - reg_dh = y; // row 4 - reg_dl = x; // column 20 - CALLBACK_RunRealInt(0x10); - } - - BIOS_Int10RightJustifiedPrint(x,y,msg); - - { - png_bytep rows[1]; - unsigned char *row = NULL;/*png_width*/ - png_structp png_context = NULL; - png_infop png_info = NULL; - png_infop png_end = NULL; - png_uint_32 png_width = 0,png_height = 0; - int png_bit_depth = 0,png_color_type = 0,png_interlace = 0,png_filter = 0,png_compression = 0; - png_color *palette = NULL; - int palette_count = 0; - std::string user_filename; - unsigned int rowheight = 8; - const char *filename = NULL; - const unsigned char *inpng = NULL; - size_t inpng_size = 0; - FILE *png_fp = NULL; - - /* If the user wants a custom logo, just put it in the same directory as the .conf file and have at it. - * Requirements: The PNG must be 1/2/4/8bpp with a color palette, not grayscale, not truecolor, and - * no alpha channel data at all. No interlacing. Must be 224x224 or smaller, and should fit the size - * indicated in the filename. There are multiple versions, one for each vertical resolution of common - * CGA/EGA/VGA/etc. modes: 480-line, 400-line, 350-line, and 200-line. All images other than the 480-line - * one have a non-square pixel aspect ratio. Please take that into consideration. */ - if (IS_VGA_ARCH) { - if (logo) user_filename = std::string(logo) + "224x224.png"; - filename = "dosbox224x224.png"; - inpng_size = dosbox224x224_png_len; - inpng = dosbox224x224_png; - rowheight = 16; - } - else if (IS_PC98_ARCH || machine == MCH_MCGA) { - if (logo) user_filename = std::string(logo) + "224x186.png"; - filename = "dosbox224x186.png"; - inpng_size = dosbox224x186_png_len; - inpng = dosbox224x186_png; - rowheight = 16; - } - else if (IS_EGA_ARCH) { - if (ega200) { - if (logo) user_filename = std::string(logo) + "224x93.png"; - filename = "dosbox224x93.png"; - inpng_size = dosbox224x93_png_len; - inpng = dosbox224x93_png; - } - else { - if (logo) user_filename = std::string(logo) + "224x163.png"; - filename = "dosbox224x163.png"; - inpng_size = dosbox224x163_png_len; - inpng = dosbox224x163_png; - rowheight = 14; - } - } - else if (machine == MCH_HERC || machine == MCH_MDA) { - if (logo) user_filename = std::string(logo) + "224x163.png"; - filename = "dosbox224x163.png"; - inpng_size = dosbox224x163_png_len; - inpng = dosbox224x163_png; - rowheight = 14; - } - else { - if (logo) user_filename = std::string(logo) + "224x93.png"; - filename = "dosbox224x93.png"; - inpng_size = dosbox224x93_png_len; - inpng = dosbox224x93_png; - } - - if (png_fp == NULL && !user_filename.empty()) - png_fp = fopen(user_filename.c_str(),"rb"); - if (png_fp == NULL && filename != NULL) - png_fp = fopen(filename,"rb"); - - if (png_fp || inpng) { - png_context = png_create_read_struct(PNG_LIBPNG_VER_STRING,NULL/*err*/,NULL/*err fn*/,NULL/*warn fn*/); - if (png_context) { - png_info = png_create_info_struct(png_context); - if (png_info) { - png_set_user_limits(png_context,320,320); - } - } - } - - if (png_context && png_info) { - if (png_fp) { - LOG(LOG_MISC,LOG_DEBUG)("Using external file logo %s",filename); - png_init_io(png_context,png_fp); - } - else if (inpng) { - LOG(LOG_MISC,LOG_DEBUG)("Using built-in logo"); - BIOSLOGO_PNG_PTR = inpng; - BIOSLOGO_PNG_FENCE = inpng + inpng_size; - png_set_read_fn(png_context,NULL,BIOSLOGO_PNG_READ); - } - else { - abort(); /* should not be here */ - } - - png_read_info(png_context,png_info); - png_get_IHDR(png_context,png_info,&png_width,&png_height,&png_bit_depth,&png_color_type,&png_interlace,&png_compression,&png_filter); - - LOG(LOG_MISC,LOG_DEBUG)("BIOS png image: w=%u h=%u bitdepth=%u ct=%u il=%u compr=%u filt=%u", - png_width,png_height,png_bit_depth,png_color_type,png_interlace,png_compression,png_filter); - - if (png_width != 0 && png_height != 0 && png_bit_depth != 0 && png_bit_depth <= 8 && - (png_color_type&(PNG_COLOR_MASK_PALETTE|PNG_COLOR_MASK_COLOR)) == (PNG_COLOR_MASK_PALETTE|PNG_COLOR_MASK_COLOR)/*palatted color only*/ && - png_interlace == 0/*do not support interlacing*/) { - LOG(LOG_MISC,LOG_DEBUG)("PNG accepted"); - /* please convert everything to 8bpp for us */ - png_set_strip_16(png_context); - png_set_packing(png_context); - png_get_PLTE(png_context,png_info,&palette,&palette_count); - - row = new unsigned char[png_width + 32]; - rows[0] = row; - - if (palette != 0 && palette_count > 0 && palette_count <= 256 && row != NULL) { - textsplash = false; - if (machine == MCH_HERC || machine == MCH_MDA) - VGA_InitBiosLogo(png_width,png_height,logo_x*9,logo_y*rowheight); - else - VGA_InitBiosLogo(png_width,png_height,logo_x*8,logo_y*rowheight); - - { - unsigned char tmp[256*3]; - for (unsigned int x=0;x < (unsigned int)palette_count;x++) { - tmp[(x*3)+0] = palette[x].red; - tmp[(x*3)+1] = palette[x].green; - tmp[(x*3)+2] = palette[x].blue; - } - VGA_WriteBiosLogoPalette(0,palette_count,tmp); - } - - for (unsigned int y=0;y < png_height;y++) { - png_read_rows(png_context,rows,NULL,1); - VGA_WriteBiosLogoBMP(y,row,png_width); - } - VGA_ShowBIOSLogo(); - } - - delete[] row; - } - } - - if (png_context) png_destroy_read_struct(&png_context,&png_info,&png_end); - if (png_fp) fclose(png_fp); - } - - if (machine == MCH_PC98 && textsplash) { - unsigned int bo, lastline = 7; - for (unsigned int i=0; i<=lastline; i++) { - for (unsigned int j=0; j= ((uint64_t)128 << (uint64_t)20)) - sprintf(tmp,"%uMB memory installed\r\n",(unsigned int)(sz >> (uint64_t)20)); - else - sprintf(tmp,"%uKB memory installed\r\n",(unsigned int)(sz >> (uint64_t)10)); - - BIOS_Int10RightJustifiedPrint(x,y,tmp); - } - - const char *card = "Unknown Graphics Adapter"; - - switch (machine) { - case MCH_CGA: - card = "IBM Color Graphics Adapter"; - break; - case MCH_MCGA: - card = "IBM Multi Color Graphics Adapter"; - break; - case MCH_MDA: - card = "IBM Monochrome Display Adapter"; - break; - case MCH_HERC: - switch (hercCard) { - case HERC_GraphicsCardPlus: - card = "Hercules+ Graphics Adapter"; - break; - case HERC_InColor: - card = "Hercules InColor Graphics Adapter"; - break; - default: - card = "Hercules Graphics Adapter"; - break; - } - break; - case MCH_EGA: - card = "IBM Enhanced Graphics Adapter"; - break; - case MCH_PCJR: - card = "PCjr Graphics Adapter"; - break; - case MCH_TANDY: - card = "Tandy Graphics Adapter"; - break; - case MCH_VGA: - switch (svgaCard) { - case SVGA_TsengET4K: - card = "Tseng ET4000 SVGA"; - break; - case SVGA_TsengET3K: - card = "Tseng ET3000 SVGA"; - break; - case SVGA_ParadisePVGA1A: - card = "Paradise SVGA"; - break; - case SVGA_S3Trio: - card = "S3 Trio SVGA"; - switch (s3Card) { - case S3_86C928: card = "S3 86C928"; break; - case S3_Vision864: card = "S3 Vision864 SVGA"; break; - case S3_Vision868: card = "S3 Vision868 SVGA"; break; - case S3_Vision964: card = "S3 Vision964 SVGA"; break; - case S3_Vision968: card = "S3 Vision968 SVGA"; break; - case S3_Trio32: card = "S3 Trio32 SVGA"; break; - case S3_Trio64: card = "S3 Trio64 SVGA"; break; - case S3_Trio64V: card = "S3 Trio64V+ SVGA"; break; - case S3_ViRGE: card = "S3 ViRGE SVGA"; break; - case S3_ViRGEVX: card = "S3 ViRGE VX SVGA"; break; - case S3_Generic: card = "S3"; break; - } - break; - case SVGA_ATI: - card = "ATI SVGA"; - switch (atiCard) { - case ATI_EGAVGAWonder: card = "ATI EGA/VGA Wonder"; break; - case ATI_VGAWonder: card = "ATI VGA Wonder"; break; - case ATI_VGAWonderPlus: card = "ATI VGA Wonder+"; break; - case ATI_VGAWonderXL: card = "ATI VGA WonderXL"; break; - case ATI_VGAWonderXL24: card = "ATI VGA WonderXL24"; break; - case ATI_Mach8: card = "ATI Mach8"; break; - case ATI_Mach32: card = "ATI Mach32"; break; - case ATI_Mach64: card = "ATI Mach64"; break; - } - break; - default: - card = "Standard VGA"; - break; - } - - break; - case MCH_PC98: - card = "PC98 graphics"; - break; - case MCH_AMSTRAD: - card = "Amstrad graphics"; - break; - default: - abort(); // should not happen - } - - { - char tmp[512]; - sprintf(tmp,"Video card is %s\n",card); - BIOS_Int10RightJustifiedPrint(x,y,tmp); - } - - { - char tmp[512]; - const char *cpuType = "?"; - - switch (CPU_ArchitectureType) { - case CPU_ARCHTYPE_8086: - cpuType = "8086"; - break; - case CPU_ARCHTYPE_80186: - cpuType = "80186"; - break; - case CPU_ARCHTYPE_286: - cpuType = "286"; - break; - case CPU_ARCHTYPE_386: - cpuType = "386"; - break; - case CPU_ARCHTYPE_486OLD: - cpuType = "486 (older generation)"; - break; - case CPU_ARCHTYPE_486NEW: - cpuType = "486 (later generation)"; - break; - case CPU_ARCHTYPE_PENTIUM: - cpuType = "Pentium"; - break; - case CPU_ARCHTYPE_PMMXSLOW: - cpuType = "Pentium MMX"; - break; - case CPU_ARCHTYPE_PPROSLOW: - cpuType = "Pentium Pro"; - break; - case CPU_ARCHTYPE_PENTIUMII: - cpuType = "Pentium II"; - break; - case CPU_ARCHTYPE_PENTIUMIII: - cpuType = "Pentium III"; - break; - case CPU_ARCHTYPE_MIXED: - cpuType = "Auto (mixed)"; - break; - case CPU_ARCHTYPE_EXPERIMENTAL: - cpuType = "Experimental"; - break; - } - - sprintf(tmp,"%s CPU present",cpuType); - BIOS_Int10RightJustifiedPrint(x,y,tmp); - if (enable_fpu) BIOS_Int10RightJustifiedPrint(x,y," with FPU"); - BIOS_Int10RightJustifiedPrint(x,y,"\n"); - } - - if (APMBIOS) { - BIOS_Int10RightJustifiedPrint(x,y,"Advanced Power Management interface active\n"); - } - - if (ISAPNPBIOS) { - BIOS_Int10RightJustifiedPrint(x,y,"ISA Plug & Play BIOS active\n"); - } - - if (*logo_text) { - const size_t max_w = 76; - const char *s = logo_text; - const int saved_y = y; - size_t max_h; - char tmp[81]; - int x,y; - - x = 0; /* use it here as index to tmp[] */ - if (IS_VGA_ARCH) /* VGA 640x480 has 30 lines (480/16) not 25 */ - max_h = 30; - else - max_h = 25; - y = max_h - 3; - - y--; - BIOS_Int10RightJustifiedPrint(x+2,y,"\n"); /* sync cursor */ - - while (*s) { - bool newline = false; - - assert((size_t)x < max_w); - if (isalpha(*s) || isdigit(*s)) { - size_t wi = 1;/*we already know s[0] fits the criteria*/ - while (s[wi] != 0 && (isalpha(s[wi]) || isdigit(s[wi]))) wi++; - - if (wi >= 24) { /* don't let overlong words crowd out the text */ - if (((size_t)x+wi) > max_w) - wi = max_w - (size_t)x; - } - - if (((size_t)x+wi) < max_w) { - memcpy(tmp+x,s,wi); - x += wi; - s += wi; - } - else { - newline = true; - } - } - else if (*s == ' ') { - if ((size_t)x < max_w) tmp[x++] = *s++; - - if ((size_t)x == max_w) { - while (*s == ' ') s++; - newline = true; - } - } - else if (*s == '\\') { - s++; - if (*s == 'n') { - newline = true; /* \n */ - s++; - } - else { - s++; - } - } - else { - tmp[x++] = *s++; - } - - assert((size_t)x <= max_w); - if ((size_t)x >= max_w || newline) { - tmp[x] = 0; - BIOS_Int10RightJustifiedPrint(x+2,y,tmp); - x = 0; - BIOS_Int10RightJustifiedPrint(x+2,y,"\n"); /* next line, which increments y */ - if ((size_t)y >= max_h) break; - } - } - - if (x != 0 && (size_t)y < max_h) { - tmp[x] = 0; - BIOS_Int10RightJustifiedPrint(x+2,y,tmp); - x = 0; - BIOS_Int10RightJustifiedPrint(x+2,y,"\n"); /* next line, which increments y */ - } - - y = saved_y - 1; - BIOS_Int10RightJustifiedPrint(x+2,y,"\n"); /* sync cursor */ - } - -#if !defined(C_EMSCRIPTEN) - BIOS_Int10RightJustifiedPrint(x,y,"\nHit SPACEBAR to pause at this screen\n", false, true); - BIOS_Int10RightJustifiedPrint(x,y,"\nPress DEL to enter BIOS setup screen\n", false, true); - y--; /* next message should overprint */ - if (machine != MCH_PC98) { - reg_eax = 0x0200; // set cursor pos - reg_ebx = 0; // page zero - reg_dh = y; // row 4 - reg_dl = x; // column 20 - CALLBACK_RunRealInt(0x10); - } - else { - reg_eax = 0x1300u; // set cursor pos (PC-98) - reg_edx = (((unsigned int)y * 80u) + (unsigned int)x) * 2u; // byte position - CALLBACK_RunRealInt(0x18); - } -#endif - - // TODO: Then at this screen, we can print messages demonstrating the detection of - // IDE devices, floppy, ISA PnP initialization, anything of importance. - // I also envision adding the ability to hit DEL or F2 at this point to enter - // a "BIOS setup" screen where all DOSBox-X configuration options can be - // modified, with the same look and feel of an old BIOS. - -#if C_EMSCRIPTEN - uint32_t lasttick=GetTicks(); - while ((GetTicks()-lasttick)<1000) { - void CALLBACK_Idle(void); - CALLBACK_Idle(); - emscripten_sleep(100); - } -#else - if (!fastbioslogo&&!bootguest&&!bootfast&&(bootvm||!use_quick_reboot)) { - bool wait_for_user = false, bios_setup = false; - int pos=1; - uint32_t lasttick=GetTicks(); - while ((GetTicks()-lasttick)<1000) { - if (machine == MCH_PC98) { - reg_eax = 0x0100; // sense key - CALLBACK_RunRealInt(0x18); - SETFLAGBIT(ZF,reg_bh == 0); - } - else { - reg_eax = 0x0100; - CALLBACK_RunRealInt(0x16); - } - - if (!GETFLAG(ZF)) { - if (machine == MCH_PC98) { - reg_eax = 0x0000; // read key - CALLBACK_RunRealInt(0x18); - } - else { - reg_eax = 0x0000; - CALLBACK_RunRealInt(0x16); - } - - if (reg_al == 32) { // user hit space - BIOS_Int10RightJustifiedPrint(x,y,"Hit ENTER or ESC to continue \n", false, true); // overprint - BIOS_Int10RightJustifiedPrint(x,y,"\nPress DEL to enter BIOS setup screen\n", false, true); - wait_for_user = true; - break; - } - - if ((machine != MCH_PC98 && reg_ax == 0x5300) || (machine == MCH_PC98 && reg_ax == 0x3900)) { // user hit Del - bios_setup = true; - showBIOSSetup(card, x, y); - break; - } - } - } - - while (wait_for_user) { - if (machine == MCH_PC98) { - reg_eax = 0x0000; // read key - CALLBACK_RunRealInt(0x18); - } - else { - reg_eax = 0x0000; - CALLBACK_RunRealInt(0x16); - } - - if ((machine != MCH_PC98 && reg_ax == 0x5300/*DEL*/) || (machine == MCH_PC98 && reg_ax == 0x3900)) { - bios_setup = true; - VGA_FreeBiosLogo(); - showBIOSSetup(card, x, y); - break; - } - - if (reg_al == 27/*ESC*/ || reg_al == 13/*ENTER*/) - break; - } - - lasttick=GetTicks(); - bool askexit = false, mod = false; - while (bios_setup) { - if (GetTicks()-lasttick>=500 && !askexit) { - lasttick=GetTicks(); - updateDateTime(x,y,pos); - } - if (machine == MCH_PC98) { - reg_eax = 0x0100; // sense key - CALLBACK_RunRealInt(0x18); - SETFLAGBIT(ZF,reg_bh == 0); - } - else { - reg_eax = 0x0100; - CALLBACK_RunRealInt(0x16); - } - - if (!GETFLAG(ZF)) { - if (machine == MCH_PC98) { - reg_eax = 0x0000; // read key - CALLBACK_RunRealInt(0x18); - } - else { - reg_eax = 0x0000; - CALLBACK_RunRealInt(0x16); - } - if (askexit) { - if (reg_al == 'Y' || reg_al == 'y') { - if (machine == MCH_PC98) { - reg_eax = 0x1600; - reg_edx = 0xE100; - CALLBACK_RunRealInt(0x18); - } - goto startfunction; - } else if (machine == MCH_PC98) { - const char *exitstr = "ESC = Exit"; - unsigned int bo; - for (unsigned int i=0; i1?pos-1:6; - lasttick-=500; - } else if ((machine != MCH_PC98 && reg_ax == 0x4D00) || (machine == MCH_PC98 && reg_ax == 0x3C00)) { // Right key - pos=pos<6?pos+1:1; - lasttick-=500; - } else if (((machine != MCH_PC98 && reg_ax == 0x4800) || (machine == MCH_PC98 && reg_ax == 0x3A00)) && pos>3) { // Up key - if (pos==4||pos==5) pos=1; - else if (pos==6) pos=2; - lasttick-=500; - } else if (((machine != MCH_PC98 && reg_ax == 0x5000) || (machine == MCH_PC98 && reg_ax == 0x3D00)) && pos<4) { // Down key - if (pos==1) pos=4; - else if (pos==2||pos==3) pos=6; - lasttick-=500; - } else if (machine != MCH_PC98 && reg_al == 43) { // '+' key - if (pos==1&&dos.date.year<2100) dos.date.year++; - else if (pos==2) dos.date.month=dos.date.month<12?dos.date.month+1:1; - else if (pos==3) dos.date.day=dos.date.day<(dos.date.month==1||dos.date.month==3||dos.date.month==5||dos.date.month==7||dos.date.month==8||dos.date.month==10||dos.date.month==12?31:(dos.date.month==2?29:30))?dos.date.day+1:1; - else if (pos==4||pos==5||pos==6) { - Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; - unsigned int sec=(uint8_t)((Bitu)time % 60); - time/=60; - unsigned int min=(uint8_t)((Bitu)time % 60); - time/=60; - unsigned int hour=(uint8_t)((Bitu)time % 24); - if (pos==4) hour=hour<23?hour+1:0; - else if (pos==5) min=min<59?min+1:0; - else if (pos==6) sec=sec<59?sec+1:0; - mem_writed(BIOS_TIMER,(uint32_t)((double)hour*3600+min*60+sec)*18.206481481); - } - mod = true; - if (sync_time) {manualtime=true;mainMenu.get_item("sync_host_datetime").check(false).refresh_item(mainMenu);} - lasttick-=500; - } else if (machine != MCH_PC98 && reg_al == 45) { // '-' key - if (pos==1&&dos.date.year>1900) dos.date.year--; - else if (pos==2) dos.date.month=dos.date.month>1?dos.date.month-1:12; - else if (pos==3) dos.date.day=dos.date.day>1?dos.date.day-1:(dos.date.month==1||dos.date.month==3||dos.date.month==5||dos.date.month==7||dos.date.month==8||dos.date.month==10||dos.date.month==12?31:(dos.date.month==2?29:30)); - else if (pos==4||pos==5||pos==6) { - Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * mem_readd(BIOS_TIMER))/100; - unsigned int sec=(uint8_t)(time % 60); - time/=60; - unsigned int min=(uint8_t)(time % 60); - time/=60; - unsigned int hour=(uint8_t)(time % 24); - if (pos==4) hour=hour>0?hour-1:23; - else if (pos==5) min=min>0?min-1:59; - else if (pos==6) sec=sec>0?sec-1:59; - mem_writed(BIOS_TIMER,(uint32_t)((double)hour*3600+min*60+sec)*18.206481481); - } - mod = true; - if (sync_time) {manualtime=true;mainMenu.get_item("sync_host_datetime").check(false).refresh_item(mainMenu);} - lasttick-=500; - } else if (reg_al == 27/*ESC*/) { - if (machine == MCH_PC98) { - const char *exitstr = "Exit[Y/N]?"; - unsigned int bo; - for (unsigned int i=0; i0 && oldlins>0) { - ttf_setlines(oldcols, oldlins); - oldcols = oldlins = 0; - } -#endif - - return CBRET_NONE; - } - CALLBACK_HandlerObject cb_bios_boot; - CALLBACK_HandlerObject cb_bios_bootfail; - CALLBACK_HandlerObject cb_pc98_rombasic; /* hardcoded entry point used by various PC-98 games that jump to N88 ROM BASIC */ - CALLBACK_HandlerObject cb_ibm_basic; /* hardcoded entry point used by MS-DOS 1.x BASIC.COM and BASICA.COM to jump to IBM ROM BASIC (F600:4C79) */ - static Bitu cb_pc98_entry__func(void) { - /* the purpose of this function is to say "N88 ROM BASIC NOT FOUND" */ - int x,y; - - x = y = 0; - - /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ - BIOS_Int10RightJustifiedPrint(x,y,"N88 ROM BASIC NOT IMPLEMENTED"); - - return CBRET_NONE; - } - static Bitu cb_ibm_basic_entry__func(void) { - /* the purpose of this function is to say "IBM ROM BASIC NOT FOUND" */ - int x,y; - - x = y = 0; - - /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ - BIOS_Int10RightJustifiedPrint(x,y,"IBM ROM BASIC NOT IMPLEMENTED"); - - return CBRET_NONE; - } - static Bitu cb_bios_bootfail__func(void) { - int x,y; - - x = y = 0; - - /* PC-98 MS-DOS boot sector may RETF back to the BIOS, and this is where execution ends up */ - BIOS_Int10RightJustifiedPrint(x,y,"Guest OS failed to boot, returned failure"); - - /* and then after this call, there is a JMP $ to loop endlessly */ - return CBRET_NONE; - } - static Bitu cb_bios_boot__func(void) { - /* Reset/power-on overrides the user's A20 gate preferences. - * It's time to revert back to what the user wants. */ - void A20Gate_TakeUserSetting(Section *sec); - void MEM_A20_Enable(bool enabled); - A20Gate_TakeUserSetting(NULL); - MEM_A20_Enable(false); - - if (cpu.pmode) E_Exit("BIOS error: BOOT function called while in protected/vm86 mode"); - DispatchVMEvent(VM_EVENT_BIOS_BOOT); - - // TODO: If instructed to, follow the INT 19h boot pattern, perhaps follow the BIOS Boot Specification, etc. - - // TODO: If instructed to boot a guest OS... - - /* wipe out the stack so it's not there to interfere with the system, point it at top of memory or top of segment */ - reg_esp = std::min((unsigned int)((MEM_TotalPages() << 12) - 0x600 - 4),0xFFFCu); - reg_eip = 0; - CPU_SetSegGeneral(cs, 0x60); - CPU_SetSegGeneral(ss, 0x60); - - LOG(LOG_MISC,LOG_DEBUG)("BIOS boot SS:SP %04x:%04x",(unsigned int)0x60,(unsigned int)reg_esp); - - for (Bitu i=0;i < 0x400;i++) mem_writeb(0x7C00+i,0); - if ((bootguest||(!bootvm&&use_quick_reboot))&&!bootfast&&bootdrive>=0&&imageDiskList[bootdrive]) { - MOUSE_Startup(NULL); - char drive[] = "-QQ A:"; - drive[4]='A'+bootdrive; - runBoot(drive); - } - if (!bootguest&&!bootvm&&!bootfast&&bootdrive>=0) { - void IDE_CDROM_DetachAll(); - IDE_CDROM_DetachAll(); - } - if ((use_quick_reboot||IS_DOSV)&&!bootvm&&!bootfast&&bootdrive<0&&first_shell != NULL) throw int(6); - - bootvm=false; - bootfast=false; - bootguest=false; - bootdrive=-1; - // Begin booting the DOSBox-X shell. NOTE: VM_Boot_DOSBox_Kernel will change CS:IP instruction pointer! - if (!VM_Boot_DOSBox_Kernel()) E_Exit("BIOS error: BOOT function failed to boot DOSBox-X kernel"); - return CBRET_NONE; - } -public: - void write_FFFF_signature() { - /* write the signature at 0xF000:0xFFF0 */ - - // The farjump at the processor reset entry point (jumps to POST routine) - phys_writeb(0xffff0,0xEA); // FARJMP - phys_writew(0xffff1,RealOff(BIOS_DEFAULT_RESET_LOCATION)); // offset - phys_writew(0xffff3,RealSeg(BIOS_DEFAULT_RESET_LOCATION)); // segment - - // write system BIOS date - for(Bitu i = 0; i < strlen(bios_date_string); i++) phys_writeb(0xffff5+i,(uint8_t)bios_date_string[i]); - - /* model byte */ - if (machine==MCH_TANDY || machine==MCH_AMSTRAD) phys_writeb(0xffffe,0xff); /* Tandy model */ - else if (machine==MCH_PCJR) phys_writeb(0xffffe,0xfd); /* PCJr model */ - else if (machine==MCH_MCGA) phys_writeb(0xffffe,0xfa); /* PC/2 model 30 model */ - else phys_writeb(0xffffe,0xfc); /* PC (FIXME: This is listed as model byte PS/2 model 60) */ - - // signature - if (machine==MCH_TANDY) - phys_writeb(0xfffff,0xff); // Needed for Ninja (1986) - else - phys_writeb(0xfffff,0x55); - } - BIOS(Section* configuration):Module_base(configuration){ - isapnp_biosstruct_base = 0; - - { // TODO: Eventually, move this to BIOS POST or init phase - Section_prop * section=static_cast(control->GetSection("dosbox")); - Section_prop * pc98_section=static_cast(control->GetSection("pc98")); - - pc98_timestamp5c = pc98_section->Get_bool("pc-98 time stamp"); - - enable_pc98_copyright_string = pc98_section->Get_bool("pc-98 BIOS copyright string"); - - // NTS: This setting is also valid in PC-98 mode. According to Undocumented PC-98 by Webtech, - // there's nothing at I/O port E9h. I will move the I/O port in PC-98 mode if there is in - // fact a conflict. --J.C. - bochs_port_e9 = section->Get_bool("bochs debug port e9"); - - // TODO: motherboard init, especially when we get around to full Intel Triton/i440FX chipset emulation - { - std::string s = section->Get_string("isa memory hole at 512kb"); - - if (s == "true" || s == "1") - isa_memory_hole_512kb = true; - else if (s == "false" || s == "0") - isa_memory_hole_512kb = false; - else - isa_memory_hole_512kb = false; - } - - // TODO: motherboard init, especially when we get around to full Intel Triton/i440FX chipset emulation - { - std::string s = section->Get_string("isa memory hole at 15mb"); - - // Do NOT emulate the memory hole if emulating 24 or less address bits! BIOS crashes will result at startup! - // The whole point of the 15MB memory hole is to emulate a hole into hardware as if a 24-bit 386SX. A memalias - // setting of 24 makes it redundant. Furthermore memalias=24 and 15MB memory hole prevents the BIOS from - // mapping correctly and crashes immediately at startup. This is especially necessary for PC-98 mode where - // memalias==24 and memory hole enabled for the PEGC linear framebuffer prevents booting. - - if (MEM_get_address_bits() <= 24) - isa_memory_hole_15mb = false; - else if (s == "true" || s == "1") - isa_memory_hole_15mb = true; - else if (s == "false" || s == "0") - isa_memory_hole_15mb = false; - else if (IS_PC98_ARCH) - isa_memory_hole_15mb = true; // For the sake of some PC-98 DOS games, enable by default - else - isa_memory_hole_15mb = false; - } - - // FIXME: Erm, well this could've been named better. It refers to the amount of conventional memory - // made available to the operating system below 1MB, which is usually DOS. - dos_conventional_limit = (unsigned int)section->Get_int("dos mem limit"); - - // for PC-98: When accessing the floppy through INT 1Bh, when enabled, run through a waiting loop to make sure - // the timer count is not too high on exit (Ys II) - enable_fdc_timer_hack = pc98_section->Get_bool("pc-98 int 1b fdc timer wait"); - - { - std::string s = section->Get_string("unhandled irq handler"); - - if (s == "simple") - unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; - else if (s == "cooperative_2nd") - unhandled_irq_method = UNHANDLED_IRQ_COOPERATIVE_2ND; - // pick default - else if (IS_PC98_ARCH) - unhandled_irq_method = UNHANDLED_IRQ_COOPERATIVE_2ND; - else - unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; - } - } - - if (IS_PC98_ARCH) { - /* Keyboard translation tables, must exist at segment 0xFD80:0x0E00 because PC-98 MS-DOS assumes it (it writes 0x522 itself on boot) */ - /* The table must be placed back far enough so that (0x60 * 10) bytes do not overlap the lookup table at 0xE28 */ - BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION = PhysToReal416(ROMBIOS_GetMemory(0x60 * 10,"Keyboard translation tables",/*align*/1,0xFD800+0xA13)); - if (ROMBIOS_GetMemory(0x2 * 10,"Keyboard translation shift tables",/*align*/1,0xFD800+0xE28) == (~0u)) E_Exit("Failed to allocate shift tables");//reserve it - BIOSKEY_PC98_Write_Tables(); - } - - /* pick locations */ - /* IBM PC mode: See [https://github.com/skiselev/8088_bios/blob/master/bios.asm]. Some values also provided by Allofich. - * PCJr: The BIOS jumps to an address much lower in segment F000, low enough that the second byte of the offset is zero. - * "Pitstop II" uses that as a method to test for PCjr [https://www.vogons.org/viewtopic.php?t=50417] */ - if (machine == MCH_PCJR) - BIOS_DEFAULT_RESET_LOCATION = PhysToReal416(ROMBIOS_GetMemory(3/*JMP NEAR*/,"BIOS default reset location (JMP, PCjr style)",/*align*/1,0xF0043)); + if (MEM_get_address_bits() <= 24) + isa_memory_hole_15mb = false; + else if (s == "true" || s == "1") + isa_memory_hole_15mb = true; + else if (s == "false" || s == "0") + isa_memory_hole_15mb = false; + else if (IS_PC98_ARCH) + isa_memory_hole_15mb = true; // For the sake of some PC-98 DOS games, enable by default + else + isa_memory_hole_15mb = false; + } + + // FIXME: Erm, well this could've been named better. It refers to the amount of conventional memory + // made available to the operating system below 1MB, which is usually DOS. + dos_conventional_limit = (unsigned int)section->Get_int("dos mem limit"); + + // for PC-98: When accessing the floppy through INT 1Bh, when enabled, run through a waiting loop to make sure + // the timer count is not too high on exit (Ys II) + enable_fdc_timer_hack = pc98_section->Get_bool("pc-98 int 1b fdc timer wait"); + + { + std::string s = section->Get_string("unhandled irq handler"); + + if (s == "simple") + unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; + else if (s == "cooperative_2nd") + unhandled_irq_method = UNHANDLED_IRQ_COOPERATIVE_2ND; + // pick default + else if (IS_PC98_ARCH) + unhandled_irq_method = UNHANDLED_IRQ_COOPERATIVE_2ND; + else + unhandled_irq_method = UNHANDLED_IRQ_SIMPLE; + } + } + + if (IS_PC98_ARCH) { + /* Keyboard translation tables, must exist at segment 0xFD80:0x0E00 because PC-98 MS-DOS assumes it (it writes 0x522 itself on boot) */ + /* The table must be placed back far enough so that (0x60 * 10) bytes do not overlap the lookup table at 0xE28 */ + BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION = PhysToReal416(ROMBIOS_GetMemory(0x60 * 10,"Keyboard translation tables",/*align*/1,0xFD800+0xA13)); + if (ROMBIOS_GetMemory(0x2 * 10,"Keyboard translation shift tables",/*align*/1,0xFD800+0xE28) == (~0u)) E_Exit("Failed to allocate shift tables");//reserve it + BIOSKEY_PC98_Write_Tables(); + } + + /* pick locations */ + /* IBM PC mode: See [https://github.com/skiselev/8088_bios/blob/master/bios.asm]. Some values also provided by Allofich. + * PCJr: The BIOS jumps to an address much lower in segment F000, low enough that the second byte of the offset is zero. + * "Pitstop II" uses that as a method to test for PCjr [https://www.vogons.org/viewtopic.php?t=50417] */ + if (machine == MCH_PCJR) + BIOS_DEFAULT_RESET_LOCATION = PhysToReal416(ROMBIOS_GetMemory(3/*JMP NEAR*/,"BIOS default reset location (JMP, PCjr style)",/*align*/1,0xF0043)); else if (IS_PC98_ARCH) - BIOS_DEFAULT_RESET_LOCATION = PhysToReal416(ROMBIOS_GetMemory(5/*JMP NEAR*/,"BIOS default reset location (JMP, PC-98)",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE05B)); - else - BIOS_DEFAULT_RESET_LOCATION = PhysToReal416(ROMBIOS_GetMemory(3/*JMP NEAR*/,"BIOS default reset location (JMP)",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE05B)); - - BIOS_DEFAULT_RESET_CODE_LOCATION = PhysToReal416(ROMBIOS_GetMemory(64/*several callbacks*/,"BIOS default reset location (CODE)",/*align*/1)); - BIOS_DEFAULT_HANDLER_LOCATION = PhysToReal416(ROMBIOS_GetMemory(1/*IRET*/,"BIOS default handler location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF53)); - BIOS_DEFAULT_INT5_LOCATION = PhysToReal416(ROMBIOS_GetMemory(1/*IRET*/, "BIOS default INT5 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF54)); - BIOS_DEFAULT_IRQ0_LOCATION = PhysToReal416(ROMBIOS_GetMemory(0x13/*see callback.cpp for IRQ0*/,"BIOS default IRQ0 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFEA5)); - BIOS_DEFAULT_IRQ1_LOCATION = PhysToReal416(ROMBIOS_GetMemory(0x20/*see callback.cpp for IRQ1*/,"BIOS default IRQ1 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE987)); - BIOS_DEFAULT_IRQ07_DEF_LOCATION = PhysToReal416(ROMBIOS_GetMemory(7/*see callback.cpp for EOI_PIC1*/,"BIOS default IRQ2-7 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF55)); - BIOS_DEFAULT_IRQ815_DEF_LOCATION = PhysToReal416(ROMBIOS_GetMemory(9/*see callback.cpp for EOI_PIC1*/,"BIOS default IRQ8-15 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE880)); - - write_FFFF_signature(); + BIOS_DEFAULT_RESET_LOCATION = PhysToReal416(ROMBIOS_GetMemory(5/*JMP NEAR*/,"BIOS default reset location (JMP, PC-98)",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE05B)); + else + BIOS_DEFAULT_RESET_LOCATION = PhysToReal416(ROMBIOS_GetMemory(3/*JMP NEAR*/,"BIOS default reset location (JMP)",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE05B)); + + BIOS_DEFAULT_RESET_CODE_LOCATION = PhysToReal416(ROMBIOS_GetMemory(64/*several callbacks*/,"BIOS default reset location (CODE)",/*align*/1)); + BIOS_DEFAULT_HANDLER_LOCATION = PhysToReal416(ROMBIOS_GetMemory(1/*IRET*/,"BIOS default handler location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF53)); + BIOS_DEFAULT_INT5_LOCATION = PhysToReal416(ROMBIOS_GetMemory(1/*IRET*/, "BIOS default INT5 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF54)); + BIOS_DEFAULT_IRQ0_LOCATION = PhysToReal416(ROMBIOS_GetMemory(0x13/*see callback.cpp for IRQ0*/,"BIOS default IRQ0 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFEA5)); + BIOS_DEFAULT_IRQ1_LOCATION = PhysToReal416(ROMBIOS_GetMemory(0x20/*see callback.cpp for IRQ1*/,"BIOS default IRQ1 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE987)); + BIOS_DEFAULT_IRQ07_DEF_LOCATION = PhysToReal416(ROMBIOS_GetMemory(7/*see callback.cpp for EOI_PIC1*/,"BIOS default IRQ2-7 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFFF55)); + BIOS_DEFAULT_IRQ815_DEF_LOCATION = PhysToReal416(ROMBIOS_GetMemory(9/*see callback.cpp for EOI_PIC1*/,"BIOS default IRQ8-15 location",/*align*/1,IS_PC98_ARCH ? 0 : 0xFE880)); + + write_FFFF_signature(); + if (IS_PC98_ARCH) + write_FFFF_PC98_signature(); + + /* Setup all the interrupt handlers the bios controls */ + + /* INT 8 Clock IRQ Handler */ + call_irq0=CALLBACK_Allocate(); if (IS_PC98_ARCH) - write_FFFF_PC98_signature(); - - /* Setup all the interrupt handlers the bios controls */ - - /* INT 8 Clock IRQ Handler */ - call_irq0=CALLBACK_Allocate(); - if (IS_PC98_ARCH) - CALLBACK_Setup(call_irq0,INT8_PC98_Handler,CB_IRET,Real2Phys(BIOS_DEFAULT_IRQ0_LOCATION),"IRQ 0 Clock"); - else - CALLBACK_Setup(call_irq0,INT8_Handler,CB_IRQ0,Real2Phys(BIOS_DEFAULT_IRQ0_LOCATION),"IRQ 0 Clock"); - - /* INT 11 Get equipment list */ - callback[1].Install(&INT11_Handler,CB_IRET,"Int 11 Equipment"); - - /* INT 12 Memory Size default at 640 kb */ - callback[2].Install(&INT12_Handler,CB_IRET,"Int 12 Memory"); - - ulimit = 640; - t_conv = MEM_TotalPages() << 2; /* convert 4096/byte pages -> 1024/byte KB units */ - /* NTS: Tandy machines, because top of memory shares video memory, need more than 640KB of memory to present 640KB of memory - * to DOS. In that case, apparently, that gives 640KB to DOS and 128KB to video memory. 640KB of memory in a Tandy system - * means 624KB for DOS and 16KB for Tandy video memory... except that 16-color higher Tandy modes need 32KB of video - * memory, so the top of memory has to be adjusted or handled carefully to avoid corruption of the MCB chain. In the 768KB - * case video memory is high enough not to conflict with DOS conventional memory at all. - * - * Might and Magic III Isles of Terra will crash in Tandy graphics modes unless we emulate the 768KB Tandy case because the - * game doesn't appear to correctly handle the conflict between the DOS MCB chain and video memory (causing an MCB corruption - * error) and it appears to make some effort to allocate memory blocks from top of memory which makes the problem worse. - * - * I am fairly certain that there is nothing on Tandy systems to occupy A0000-AFFFFh. Unless of course you install EGA/VGA - * hardware in such a system. */ - if (allow_more_than_640kb) { - if (machine == MCH_CGA) - ulimit = 736; /* 640KB + 96KB = 0x00000-0xB7FFF */ - else if (machine == MCH_HERC || machine == MCH_MDA) - ulimit = 704; /* 640KB + 64KB = 0x00000-0xAFFFF */ - else if (machine == MCH_TANDY) - ulimit = 768; /* 640KB + 128KB = 0x00000-0xBFFFF */ - - /* NTS: Yes, this means Tandy video memory at B8000 overlaps conventional memory, but the - * top of conventional memory is stolen as video memory anyway. Tandy documentation - * suggests that memory is only installed in multiples of 128KB so there doesn't seem - * to be a way to install only 704KB for example. */ - - if (t_conv > ulimit) t_conv = ulimit; - if (t_conv > 640 && machine != MCH_TANDY) { - /* because the memory emulation has already set things up - * HOWEVER Tandy emulation has already properly mapped A0000-BFFFF so don't mess with it */ - bool MEM_map_RAM_physmem(Bitu start,Bitu end); - MEM_map_RAM_physmem(0xA0000,(t_conv<<10)-1); - memset(GetMemBase()+(640<<10),0,(t_conv-640)<<10); - } - } - else { - if (t_conv > 640) t_conv = 640; - } - - /* allow user to further limit the available memory below 1MB */ - if (dos_conventional_limit != 0 && t_conv > dos_conventional_limit) - t_conv = dos_conventional_limit; - - // TODO: Allow dosbox-x.conf to specify an option to add an EBDA (Extended BIOS Data Area) - // at the top of the DOS conventional limit, which we then reduce further to hold - // it. Most BIOSes past 1992 or so allocate an EBDA. - - /* if requested to emulate an ISA memory hole at 512KB, further limit the memory */ - if (isa_memory_hole_512kb && t_conv > 512) t_conv = 512; - t_conv_real = t_conv; - - if (machine == MCH_TANDY) { - /* Tandy models are said to have started with 256KB. We'll allow down to 64KB */ - if (t_conv < 64) - t_conv = 64; - if (t_conv < 256) - LOG(LOG_MISC,LOG_WARN)("Warning: Tandy with less than 256KB is unusual"); - - /* The shared video/system memory design, and the placement of video RAM at top - * of conventional memory, means that if conventional memory is less than 640KB - * and not a multiple of 32KB, things can break. */ - if ((t_conv % 32) != 0) - LOG(LOG_MISC,LOG_WARN)("Warning: Conventional memory size %uKB in Tandy mode is not a multiple of 32KB, games may not display graphics correctly",(unsigned int)t_conv); - } - else if (machine == MCH_PCJR) { - if (t_conv < 64) - t_conv = 64; - - /* PCjr also shares video/system memory, but the video memory can only exist - * below 128KB because IBM intended it to only carry 64KB or 128KB on the - * motherboard. Any memory past 128KB is likely provided by addons (sidecars) */ - if (t_conv < 128 && (t_conv % 32) != 0) - LOG(LOG_MISC,LOG_WARN)("Warning: Conventional memory size %uKB in PCjr mode is not a multiple of 32KB, games may not display graphics correctly",(unsigned int)t_conv); - } - - /* and then unmap RAM between t_conv and ulimit */ - if (t_conv < ulimit) { - Bitu start = (t_conv+3)/4; /* start = 1KB to page round up */ - Bitu end = ulimit/4; /* end = 1KB to page round down */ - if (start < end) MEM_ResetPageHandler_Unmapped(start,end-start); - } - - if (isa_memory_hole_15mb) MEM_ResetPageHandler_Unmapped(0xf00,0x100); /* 0xF00000-0xFFFFFF */ - - if (machine == MCH_TANDY) { - /* Take 16KB off the top for video RAM. - * This value never changes after boot, even if you then use the 16-color modes which then moves - * the video RAM region down 16KB to make a 32KB region. Neither MS-DOS nor INT 10h change this - * top of memory value. I hope your DOS game doesn't put any important structures or MCBs above - * the 32KB below top of memory, because it WILL get overwritten with graphics! - * - * This is apparently correct behavior, and DOSBox SVN and other forks follow it too. - * - * See also: [https://www.vogons.org/viewtopic.php?p=948879#p948879] - * Issue: [https://github.com/joncampbell123/dosbox-x/issues/2380] - * - * Mickeys Space Adventure assumes it can find video RAM by calling INT 12h, subtracting 16KB, and - * converting KB to paragraphs. Note that it calls INT 12h while in CGA mode, and subtracts 16KB - * knowing video memory will extend downward 16KB into a 32KB region when it switches into the - * Tandy/PCjr 16-color mode. */ - /* Tandy systems can present full 640KB of conventional memory with 128KB for video memory if 768KB - * is installed! */ - if (t_conv > (640+32)) { - if (t_conv > 640) t_conv = 640; - if (ulimit > 640) ulimit = 640; - - /* Video memory takes the rest */ - tandy_128kbase = 0xA0000; - } - else { - if (t_conv > 640) t_conv = 640; - if (ulimit > 640) ulimit = 640; - t_conv -= 16; - ulimit -= 16; - - /* if 32KB would cross a 128KB boundary, then adjust again or else - * things will horribly break between text and graphics modes */ - if ((t_conv % 128) < 16) - t_conv -= 16; - - /* Our choice also affects which 128KB bank within which the 16KB banks - * select what system memory becomes video memory. - * - * FIXME: Is this controlled by the "extended ram page register?" How? */ - tandy_128kbase = ((t_conv - 16u) << 10u) & 0xE0000; /* byte offset = (KB - 16) * 64, round down to multiple of 128KB */ - } - LOG(LOG_MISC,LOG_DEBUG)("BIOS: setting tandy 128KB base region to %lxh",(unsigned long)tandy_128kbase); - } - else if (machine == MCH_PCJR) { - /* PCjr reserves the top of its internal 128KB of RAM for video RAM. - * Sidecars can extend it past 128KB but it requires DOS drivers or TSRs - * to modify the MCB chain so that it a) marks the video memory as reserved - * and b) creates a new free region above the video RAM region. - * - * Therefore, only subtract 16KB if 128KB or less is configured for this machine. - * - * Note this is not speculation, it's there in the PCjr BIOS source code: - * [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/Video/PCjr/IBM%20Personal%20Computer%20PCjr%20Hardware%20Reference%20Library%20Technical%20Reference%20%281983%2d11%29%20First%20Edition%20Revised%2epdf] ROM BIOS source code page A-16 */ - if (t_conv <= (128+16)) { - if (t_conv > 128) t_conv = 128; - t_conv -= 16; - } - if (ulimit <= (128+16)) { - if (ulimit > 128) ulimit = 128; - ulimit -= 16; - } - } - - /* INT 4B. Now we can safely signal error instead of printing "Invalid interrupt 4B" - * whenever we install Windows 95. Note that Windows 95 would call INT 4Bh because - * that is where the Virtual DMA API lies in relation to EMM386.EXE */ - int4b_callback.Install(&INT4B_Handler,CB_IRET,"INT 4B"); - - /* INT 14 Serial Ports */ - callback[3].Install(&INT14_Handler,CB_IRET_STI,"Int 14 COM-port"); - - /* INT 15 Misc Calls */ - callback[4].Install(&INT15_Handler,CB_IRET,"Int 15 Bios"); - - /* INT 17 Printer Routines */ - callback[5].Install(&INT17_Handler,CB_IRET_STI,"Int 17 Printer"); - - /* INT 1A TIME and some other functions */ - callback[6].Install(&INT1A_Handler,CB_IRET_STI,"Int 1a Time"); - - /* INT 1C System Timer tick called from INT 8 */ - callback[7].Install(&INT1C_Handler,CB_IRET,"Int 1c Timer"); - - /* IRQ 8 RTC Handler */ - callback[8].Install(&INT70_Handler,CB_IRET,"Int 70 RTC"); - - /* Irq 9 rerouted to irq 2 */ - callback[9].Install(NULL,CB_IRQ9,"irq 9 bios"); - - // INT 19h: Boot function - callback[10].Install(&INT19_Handler,CB_IRET,"int 19"); - - // INT 1Bh: IBM PC CTRL+Break - callback[19].Install(&INT1B_Break_Handler,CB_IRET,"BIOS 1Bh stock CTRL+BREAK handler"); - - // INT 76h: IDE IRQ 14 - // This is just a dummy IRQ handler to prevent crashes when - // IDE emulation fires the IRQ and OS's like Win95 expect - // the BIOS to handle the interrupt. - // FIXME: Shouldn't the IRQ send an ACK to the PIC as well?!? - callback[11].Install(&IRQ14_Dummy,CB_IRET_EOI_PIC2,"irq 14 ide"); - - // INT 77h: IDE IRQ 15 - // This is just a dummy IRQ handler to prevent crashes when - // IDE emulation fires the IRQ and OS's like Win95 expect - // the BIOS to handle the interrupt. - // FIXME: Shouldn't the IRQ send an ACK to the PIC as well?!? - callback[12].Install(&IRQ15_Dummy,CB_IRET_EOI_PIC2,"irq 15 ide"); - - // INT 0Eh: IDE IRQ 6 - callback[13].Install(&IRQ15_Dummy,CB_IRET_EOI_PIC1,"irq 6 floppy"); - - // INT 18h: Enter BASIC - // Non-IBM BIOS would display "NO ROM BASIC" here - callback[15].Install(&INT18_Handler,CB_IRET,"int 18"); - - if(IS_J3100) { - callback[16].Install(&INT60_Handler,CB_IRET,"Int 60 Bios"); - callback[16].Set_RealVec(0x60); - - callback[17].Install(&INT6F_Handler,CB_INT6F_ATOK,"Int 6F Bios"); - callback[17].Set_RealVec(0x6f); - } - - init_vm86_fake_io(); - - /* Irq 2-7 */ - call_irq07default=CALLBACK_Allocate(); - - /* Irq 8-15 */ - call_irq815default=CALLBACK_Allocate(); - - /* BIOS boot stages */ - cb_bios_post.Install(&cb_bios_post__func,CB_RETF,"BIOS POST"); - cb_bios_scan_video_bios.Install(&cb_bios_scan_video_bios__func,CB_RETF,"BIOS Scan Video BIOS"); - cb_bios_adapter_rom_scan.Install(&cb_bios_adapter_rom_scan__func,CB_RETF,"BIOS Adapter ROM scan"); - cb_bios_startup_screen.Install(&cb_bios_startup_screen__func,CB_RETF,"BIOS Startup screen"); - cb_bios_boot.Install(&cb_bios_boot__func,CB_RETF,"BIOS BOOT"); - cb_bios_bootfail.Install(&cb_bios_bootfail__func,CB_RETF,"BIOS BOOT FAIL"); - - if (IS_PC98_ARCH) { - cb_pc98_rombasic.Install(&cb_pc98_entry__func,CB_RETF,"N88 ROM BASIC"); - } - else { - /* IBM ROM BASIC resides at segment F600:0000 just below the 5150 ROM BIOS. - * MS-DOS 1.x and 2.x BASIC(A).COM jump to specific addresses in the ROM BASIC to do their thing. - * The purpose of these callbacks is to catch those programs and safely halt emulation to - * state that ROM BASIC is not present */ - cb_ibm_basic.Install(&cb_ibm_basic_entry__func,CB_RETF,"IBM ROM BASIC entry"); - } - - // Compatible POST routine location: jump to the callback - { - Bitu wo_fence; - - { - const Bitu wo = Real2Phys(BIOS_DEFAULT_RESET_LOCATION); + CALLBACK_Setup(call_irq0,INT8_PC98_Handler,CB_IRET,Real2Phys(BIOS_DEFAULT_IRQ0_LOCATION),"IRQ 0 Clock"); + else + CALLBACK_Setup(call_irq0,INT8_Handler,CB_IRQ0,Real2Phys(BIOS_DEFAULT_IRQ0_LOCATION),"IRQ 0 Clock"); + + /* INT 11 Get equipment list */ + callback[1].Install(&INT11_Handler,CB_IRET,"Int 11 Equipment"); + + /* INT 12 Memory Size default at 640 kb */ + callback[2].Install(&INT12_Handler,CB_IRET,"Int 12 Memory"); + + ulimit = 640; + t_conv = MEM_TotalPages() << 2; /* convert 4096/byte pages -> 1024/byte KB units */ + /* NTS: Tandy machines, because top of memory shares video memory, need more than 640KB of memory to present 640KB of memory + * to DOS. In that case, apparently, that gives 640KB to DOS and 128KB to video memory. 640KB of memory in a Tandy system + * means 624KB for DOS and 16KB for Tandy video memory... except that 16-color higher Tandy modes need 32KB of video + * memory, so the top of memory has to be adjusted or handled carefully to avoid corruption of the MCB chain. In the 768KB + * case video memory is high enough not to conflict with DOS conventional memory at all. + * + * Might and Magic III Isles of Terra will crash in Tandy graphics modes unless we emulate the 768KB Tandy case because the + * game doesn't appear to correctly handle the conflict between the DOS MCB chain and video memory (causing an MCB corruption + * error) and it appears to make some effort to allocate memory blocks from top of memory which makes the problem worse. + * + * I am fairly certain that there is nothing on Tandy systems to occupy A0000-AFFFFh. Unless of course you install EGA/VGA + * hardware in such a system. */ + if (allow_more_than_640kb) { + if (machine == MCH_CGA) + ulimit = 736; /* 640KB + 96KB = 0x00000-0xB7FFF */ + else if (machine == MCH_HERC || machine == MCH_MDA) + ulimit = 704; /* 640KB + 64KB = 0x00000-0xAFFFF */ + else if (machine == MCH_TANDY) + ulimit = 768; /* 640KB + 128KB = 0x00000-0xBFFFF */ + + /* NTS: Yes, this means Tandy video memory at B8000 overlaps conventional memory, but the + * top of conventional memory is stolen as video memory anyway. Tandy documentation + * suggests that memory is only installed in multiples of 128KB so there doesn't seem + * to be a way to install only 704KB for example. */ + + if (t_conv > ulimit) t_conv = ulimit; + if (t_conv > 640 && machine != MCH_TANDY) { + /* because the memory emulation has already set things up + * HOWEVER Tandy emulation has already properly mapped A0000-BFFFF so don't mess with it */ + bool MEM_map_RAM_physmem(Bitu start,Bitu end); + MEM_map_RAM_physmem(0xA0000,(t_conv<<10)-1); + memset(GetMemBase()+(640<<10),0,(t_conv-640)<<10); + } + } + else { + if (t_conv > 640) t_conv = 640; + } + + /* allow user to further limit the available memory below 1MB */ + if (dos_conventional_limit != 0 && t_conv > dos_conventional_limit) + t_conv = dos_conventional_limit; + + // TODO: Allow dosbox-x.conf to specify an option to add an EBDA (Extended BIOS Data Area) + // at the top of the DOS conventional limit, which we then reduce further to hold + // it. Most BIOSes past 1992 or so allocate an EBDA. + + /* if requested to emulate an ISA memory hole at 512KB, further limit the memory */ + if (isa_memory_hole_512kb && t_conv > 512) t_conv = 512; + t_conv_real = t_conv; + + if (machine == MCH_TANDY) { + /* Tandy models are said to have started with 256KB. We'll allow down to 64KB */ + if (t_conv < 64) + t_conv = 64; + if (t_conv < 256) + LOG(LOG_MISC,LOG_WARN)("Warning: Tandy with less than 256KB is unusual"); + + /* The shared video/system memory design, and the placement of video RAM at top + * of conventional memory, means that if conventional memory is less than 640KB + * and not a multiple of 32KB, things can break. */ + if ((t_conv % 32) != 0) + LOG(LOG_MISC,LOG_WARN)("Warning: Conventional memory size %uKB in Tandy mode is not a multiple of 32KB, games may not display graphics correctly",(unsigned int)t_conv); + } + else if (machine == MCH_PCJR) { + if (t_conv < 64) + t_conv = 64; + + /* PCjr also shares video/system memory, but the video memory can only exist + * below 128KB because IBM intended it to only carry 64KB or 128KB on the + * motherboard. Any memory past 128KB is likely provided by addons (sidecars) */ + if (t_conv < 128 && (t_conv % 32) != 0) + LOG(LOG_MISC,LOG_WARN)("Warning: Conventional memory size %uKB in PCjr mode is not a multiple of 32KB, games may not display graphics correctly",(unsigned int)t_conv); + } + + /* and then unmap RAM between t_conv and ulimit */ + if (t_conv < ulimit) { + Bitu start = (t_conv+3)/4; /* start = 1KB to page round up */ + Bitu end = ulimit/4; /* end = 1KB to page round down */ + if (start < end) MEM_ResetPageHandler_Unmapped(start,end-start); + } + + if (isa_memory_hole_15mb) MEM_ResetPageHandler_Unmapped(0xf00,0x100); /* 0xF00000-0xFFFFFF */ + + if (machine == MCH_TANDY) { + /* Take 16KB off the top for video RAM. + * This value never changes after boot, even if you then use the 16-color modes which then moves + * the video RAM region down 16KB to make a 32KB region. Neither MS-DOS nor INT 10h change this + * top of memory value. I hope your DOS game doesn't put any important structures or MCBs above + * the 32KB below top of memory, because it WILL get overwritten with graphics! + * + * This is apparently correct behavior, and DOSBox SVN and other forks follow it too. + * + * See also: [https://www.vogons.org/viewtopic.php?p=948879#p948879] + * Issue: [https://github.com/joncampbell123/dosbox-x/issues/2380] + * + * Mickeys Space Adventure assumes it can find video RAM by calling INT 12h, subtracting 16KB, and + * converting KB to paragraphs. Note that it calls INT 12h while in CGA mode, and subtracts 16KB + * knowing video memory will extend downward 16KB into a 32KB region when it switches into the + * Tandy/PCjr 16-color mode. */ + /* Tandy systems can present full 640KB of conventional memory with 128KB for video memory if 768KB + * is installed! */ + if (t_conv > (640+32)) { + if (t_conv > 640) t_conv = 640; + if (ulimit > 640) ulimit = 640; + + /* Video memory takes the rest */ + tandy_128kbase = 0xA0000; + } + else { + if (t_conv > 640) t_conv = 640; + if (ulimit > 640) ulimit = 640; + t_conv -= 16; + ulimit -= 16; + + /* if 32KB would cross a 128KB boundary, then adjust again or else + * things will horribly break between text and graphics modes */ + if ((t_conv % 128) < 16) + t_conv -= 16; + + /* Our choice also affects which 128KB bank within which the 16KB banks + * select what system memory becomes video memory. + * + * FIXME: Is this controlled by the "extended ram page register?" How? */ + tandy_128kbase = ((t_conv - 16u) << 10u) & 0xE0000; /* byte offset = (KB - 16) * 64, round down to multiple of 128KB */ + } + LOG(LOG_MISC,LOG_DEBUG)("BIOS: setting tandy 128KB base region to %lxh",(unsigned long)tandy_128kbase); + } + else if (machine == MCH_PCJR) { + /* PCjr reserves the top of its internal 128KB of RAM for video RAM. + * Sidecars can extend it past 128KB but it requires DOS drivers or TSRs + * to modify the MCB chain so that it a) marks the video memory as reserved + * and b) creates a new free region above the video RAM region. + * + * Therefore, only subtract 16KB if 128KB or less is configured for this machine. + * + * Note this is not speculation, it's there in the PCjr BIOS source code: + * [http://hackipedia.org/browse.cgi/Computer/Platform/PC%2c%20IBM%20compatible/Video/PCjr/IBM%20Personal%20Computer%20PCjr%20Hardware%20Reference%20Library%20Technical%20Reference%20%281983%2d11%29%20First%20Edition%20Revised%2epdf] ROM BIOS source code page A-16 */ + if (t_conv <= (128+16)) { + if (t_conv > 128) t_conv = 128; + t_conv -= 16; + } + if (ulimit <= (128+16)) { + if (ulimit > 128) ulimit = 128; + ulimit -= 16; + } + } + + /* INT 4B. Now we can safely signal error instead of printing "Invalid interrupt 4B" + * whenever we install Windows 95. Note that Windows 95 would call INT 4Bh because + * that is where the Virtual DMA API lies in relation to EMM386.EXE */ + int4b_callback.Install(&INT4B_Handler,CB_IRET,"INT 4B"); + + /* INT 14 Serial Ports */ + callback[3].Install(&INT14_Handler,CB_IRET_STI,"Int 14 COM-port"); + + /* INT 15 Misc Calls */ + callback[4].Install(&INT15_Handler,CB_IRET,"Int 15 Bios"); + + /* INT 17 Printer Routines */ + callback[5].Install(&INT17_Handler,CB_IRET_STI,"Int 17 Printer"); + + /* INT 1A TIME and some other functions */ + callback[6].Install(&INT1A_Handler,CB_IRET_STI,"Int 1a Time"); + + /* INT 1C System Timer tick called from INT 8 */ + callback[7].Install(&INT1C_Handler,CB_IRET,"Int 1c Timer"); + + /* IRQ 8 RTC Handler */ + callback[8].Install(&INT70_Handler,CB_IRET,"Int 70 RTC"); + + /* Irq 9 rerouted to irq 2 */ + callback[9].Install(NULL,CB_IRQ9,"irq 9 bios"); + + // INT 19h: Boot function + callback[10].Install(&INT19_Handler,CB_IRET,"int 19"); + + // INT 1Bh: IBM PC CTRL+Break + callback[19].Install(&INT1B_Break_Handler,CB_IRET,"BIOS 1Bh stock CTRL+BREAK handler"); + + // INT 76h: IDE IRQ 14 + // This is just a dummy IRQ handler to prevent crashes when + // IDE emulation fires the IRQ and OS's like Win95 expect + // the BIOS to handle the interrupt. + // FIXME: Shouldn't the IRQ send an ACK to the PIC as well?!? + callback[11].Install(&IRQ14_Dummy,CB_IRET_EOI_PIC2,"irq 14 ide"); + + // INT 77h: IDE IRQ 15 + // This is just a dummy IRQ handler to prevent crashes when + // IDE emulation fires the IRQ and OS's like Win95 expect + // the BIOS to handle the interrupt. + // FIXME: Shouldn't the IRQ send an ACK to the PIC as well?!? + callback[12].Install(&IRQ15_Dummy,CB_IRET_EOI_PIC2,"irq 15 ide"); + + // INT 0Eh: IDE IRQ 6 + callback[13].Install(&IRQ15_Dummy,CB_IRET_EOI_PIC1,"irq 6 floppy"); + + // INT 18h: Enter BASIC + // Non-IBM BIOS would display "NO ROM BASIC" here + callback[15].Install(&INT18_Handler,CB_IRET,"int 18"); + + if(IS_J3100) { + callback[16].Install(&INT60_Handler,CB_IRET,"Int 60 Bios"); + callback[16].Set_RealVec(0x60); + + callback[17].Install(&INT6F_Handler,CB_INT6F_ATOK,"Int 6F Bios"); + callback[17].Set_RealVec(0x6f); + } + + init_vm86_fake_io(); + + /* Irq 2-7 */ + call_irq07default=CALLBACK_Allocate(); + + /* Irq 8-15 */ + call_irq815default=CALLBACK_Allocate(); + + /* BIOS boot stages */ + cb_bios_post.Install(&cb_bios_post__func,CB_RETF,"BIOS POST"); + cb_bios_scan_video_bios.Install(&cb_bios_scan_video_bios__func,CB_RETF,"BIOS Scan Video BIOS"); + cb_bios_adapter_rom_scan.Install(&cb_bios_adapter_rom_scan__func,CB_RETF,"BIOS Adapter ROM scan"); + cb_bios_startup_screen.Install(&cb_bios_startup_screen__func,CB_RETF,"BIOS Startup screen"); + cb_bios_boot.Install(&cb_bios_boot__func,CB_RETF,"BIOS BOOT"); + cb_bios_bootfail.Install(&cb_bios_bootfail__func,CB_RETF,"BIOS BOOT FAIL"); + + if (IS_PC98_ARCH) { + cb_pc98_rombasic.Install(&cb_pc98_entry__func,CB_RETF,"N88 ROM BASIC"); + } + else { + /* IBM ROM BASIC resides at segment F600:0000 just below the 5150 ROM BIOS. + * MS-DOS 1.x and 2.x BASIC(A).COM jump to specific addresses in the ROM BASIC to do their thing. + * The purpose of these callbacks is to catch those programs and safely halt emulation to + * state that ROM BASIC is not present */ + cb_ibm_basic.Install(&cb_ibm_basic_entry__func,CB_RETF,"IBM ROM BASIC entry"); + } + + // Compatible POST routine location: jump to the callback + { + Bitu wo_fence; + + { + const Bitu wo = Real2Phys(BIOS_DEFAULT_RESET_LOCATION); if (IS_PC98_ARCH) { const unsigned int ofs = Real2Phys(BIOS_DEFAULT_RESET_CODE_LOCATION) - 0xF0000u; phys_writeb(wo+0,0xEA);/*JMP far*/ @@ -12083,703 +12085,703 @@ class BIOS:public Module_base{ phys_writeb(wo+0,0xE9);/*JMP near*/ phys_writew(wo+1,delta); } - } - - Bitu wo = Real2Phys(BIOS_DEFAULT_RESET_CODE_LOCATION); - wo_fence = wo + 64; - - // POST - phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(wo+0x02,(uint16_t)cb_bios_post.Get_callback()); //The immediate word - wo += 4; - - // video bios scan - phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(wo+0x02,(uint16_t)cb_bios_scan_video_bios.Get_callback()); //The immediate word - wo += 4; - - // adapter ROM scan - phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(wo+0x02,(uint16_t)cb_bios_adapter_rom_scan.Get_callback()); //The immediate word - wo += 4; - - // startup screen - phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(wo+0x02,(uint16_t)cb_bios_startup_screen.Get_callback()); //The immediate word - wo += 4; - - // user boot hook - if (bios_user_boot_hook != 0) { - phys_writeb(wo+0x00,0x9C); //PUSHF - phys_writeb(wo+0x01,0x9A); //CALL FAR - phys_writew(wo+0x02,0x0000); //seg:0 - phys_writew(wo+0x04,bios_user_boot_hook>>4); - wo += 6; - } - - // boot - BIOS_boot_code_offset = wo; - phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(wo+0x02,(uint16_t)cb_bios_boot.Get_callback()); //The immediate word - wo += 4; - - // boot fail - BIOS_bootfail_code_offset = wo; - phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(wo+0x02,(uint16_t)cb_bios_bootfail.Get_callback()); //The immediate word - wo += 4; - - /* fence */ - phys_writeb(wo++,0xEB); // JMP $-2 - phys_writeb(wo++,0xFE); - - if (wo > wo_fence) E_Exit("BIOS boot callback overrun"); - - if (IS_PC98_ARCH) { - /* Boot disks that run N88 basic, stopgap */ - PhysPt bo = 0xE8002; // E800:0002 - - ROMBIOS_GetMemory(6,"N88 ROM BASIC entry point",/*align*/1,bo); - - phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(bo+0x02,(uint16_t)cb_pc98_rombasic.Get_callback()); //The immediate word - - phys_writeb(bo+0x04,0xEB); // JMP $-2 - phys_writeb(bo+0x05,0xFE); - - // On careful examination of BIOS.ROM, there's a JMP instruction at E800:0000 as well. - // I don't have any test cases that jump there, but add a JMP forward just in case. - bo = 0xE8000; - phys_writeb(bo+0x00,(uint8_t)0xEB); // JMP $+2 (to next instruction) - phys_writeb(bo+0x01,(uint8_t)0x00); - - /* "Nut Berry" expects a 8-byte lookup table for [AL&7] -> 1 << (AL&7) at 0xFD80:0x0E3C so it's - * custom keyboard interrupt handler can update the keyboard status bitmap in the BIOS data area. - * I don't know if the game even uses it. On a BIOS.ROM image I have, and on real hardware, there - * is clearly that table but at slightly different addresses (One PC-9821 laptop has it at - * 0xFD80:0x0E45) which means whether the game uses it or not the bitmap may have random bits set - * when you exit to DOS. - * - * Assuming no other game does this, this fixed address should be fine. - * - * NOTE: After disassembling the IRQ1 handler on a real PC-9821 laptop, I noticed this game's - * custom ISR bears a strong resemblance to it. In fact, you might say it's an exact instruction - * for instruction copy of the ISR, except that the table addresses in ROM are slightly different. - * Ha. Theoretically then, that means we could also get this game to work fully properly by patching - * it not to hook the keyboard interrupt at all! */ - for (unsigned int i=0;i < 8;i++) phys_writeb(0xFD800+0xE3C+i,1u << i); - - /* "Nut Berry" also assumes shift state table offsets (for all 16 possible combinations) exist - * at 0xFD80:0x0E28. Once again, this means it will not work properly on anything other than the dev's - * machine because on a real PC-9821 laptop used for testing, the table offset is slightly different - * (0xE31 instead of 0xE28). The table mentioned here is used to update the 0x522 offset WORD in the - * BIOS data area to reflect the translation table in effect based on the shift key status, so if you - * misread the table you end up pointing it at junk and then keyboard input doesn't work anymore. */ - // NTS: On a real PC-9821 laptop, the table is apparently 10 entries long. If BDA byte 0x53A is less than - // 8 then it's just a simple lookup. If BDA byte 0x53A has bit 4 set, then use the 8th entry, and - // if bit 4 and 3 are set, use the 9th entry. - for (unsigned int i=0;i < 10;i++) phys_writew(0xFD800+0xE28+(i*2),(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800) + (i * 0x60)); - } - else { - if (ibm_rom_basic_size == 0) { - /* IBM MS-DOS 1.x/2.x BASIC and BASICA, stopgap */ - PhysPt bo; - - bo = 0xF6000+0x2DB0; // F600:2DB0 - - ROMBIOS_GetMemory(6,"IBM ROM BASIC entry point",/*align*/1,bo); - - phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(bo+0x02,(uint16_t)cb_ibm_basic.Get_callback()); //The immediate word - - phys_writeb(bo+0x04,0xEB); // JMP $-2 - phys_writeb(bo+0x05,0xFE); - - bo = 0xF6000+0x4C79; // F600:4C79 - - ROMBIOS_GetMemory(6,"IBM ROM BASIC entry point",/*align*/1,bo); - - phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 - phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction - phys_writew(bo+0x02,(uint16_t)cb_ibm_basic.Get_callback()); //The immediate word - - phys_writeb(bo+0x04,0xEB); // JMP $-2 - phys_writeb(bo+0x05,0xFE); - } - } - - if (IS_PC98_ARCH && enable_pc98_copyright_string) { - size_t i=0; - - ROMBIOS_GetMemory(pc98_copyright_str.length()+1,"NEC PC-98 copyright string",/*align*/1,0xE8000 + 0x0DD8); - - for (;i < pc98_copyright_str.length();i++) - phys_writeb(0xE8000 + 0x0DD8 + (PhysPt)i,(uint8_t)pc98_copyright_str[i]); - - phys_writeb(0xE8000 + 0x0DD8 + (PhysPt)i,0); - - ROMBIOS_GetMemory(sizeof(pc98_epson_check_2),"NEC PC-98 Epson check data #2",/*align*/1,0xF5200 + 0x018E); - - for (i=0;i < sizeof(pc98_epson_check_2);i++) - phys_writeb(0xF5200 + 0x018E + (PhysPt)i,(uint8_t)pc98_epson_check_2[i]); - } - } - } - ~BIOS(){ - /* snap the CPU back to real mode. this code thinks in terms of 16-bit real mode - * and if allowed to do its thing in a 32-bit guest OS like WinNT, will trigger - * a page fault. */ - CPU_Snap_Back_To_Real_Mode(); - - if (acpi_iocallout != IO_Callout_t_none) { - IO_FreeCallout(acpi_iocallout); - acpi_iocallout = IO_Callout_t_none; - } - - if (BOCHS_PORT_E9) { - delete BOCHS_PORT_E9; - BOCHS_PORT_E9=NULL; - } - if (ISAPNP_PNP_ADDRESS_PORT) { - delete ISAPNP_PNP_ADDRESS_PORT; - ISAPNP_PNP_ADDRESS_PORT=NULL; - } - if (ISAPNP_PNP_DATA_PORT) { - delete ISAPNP_PNP_DATA_PORT; - ISAPNP_PNP_DATA_PORT=NULL; - } - if (ISAPNP_PNP_READ_PORT) { - delete ISAPNP_PNP_READ_PORT; - ISAPNP_PNP_READ_PORT=NULL; - } - if (isapnpigdevice) { - /* ISA PnP will auto-free it */ - isapnpigdevice=NULL; - } - - if (dosbox_int_iocallout != IO_Callout_t_none) { - IO_FreeCallout(dosbox_int_iocallout); - dosbox_int_iocallout = IO_Callout_t_none; - } - - /* abort DAC playing */ - if (tandy_sb.port) { - IO_Write(tandy_sb.port+0xcu,0xd3u); - IO_Write(tandy_sb.port+0xcu,0xd0u); - } - real_writeb(0x40,0xd4,0x00); - if (tandy_DAC_callback[0]) { - uint32_t orig_vector=real_readd(0x40,0xd6); - if (orig_vector==tandy_DAC_callback[0]->Get_RealPointer()) { - /* set IRQ vector to old value */ - uint8_t tandy_irq = 7; - if (tandy_sb.port) tandy_irq = tandy_sb.irq; - else if (tandy_dac.port) tandy_irq = tandy_dac.irq; - uint8_t tandy_irq_vector = tandy_irq; - if (tandy_irq_vector<8) tandy_irq_vector += 8; - else tandy_irq_vector += (0x70-8); - - RealSetVec(tandy_irq_vector,real_readd(0x40,0xd6)); - real_writed(0x40,0xd6,0x00000000); - } - delete tandy_DAC_callback[0]; - delete tandy_DAC_callback[1]; - tandy_DAC_callback[0]=NULL; - tandy_DAC_callback[1]=NULL; - } - - /* encourage the callback objects to uninstall HERE while we're in real mode, NOT during the - * destructor stage where we're back in protected mode */ - for (unsigned int i=0;i < callback_count;i++) callback[i].Uninstall(); - - /* assume these were allocated */ - CALLBACK_DeAllocate(call_irq0); - CALLBACK_DeAllocate(call_irq07default); - CALLBACK_DeAllocate(call_irq815default); - - /* done */ - CPU_Snap_Back_Restore(); - } -}; - -void BIOS_Enter_Boot_Phase(void) { - /* direct CS:IP right to the instruction that leads to the boot process */ - /* note that since it's a callback instruction it doesn't really matter - * what CS:IP is as long as it points to the instruction */ - reg_eip = BIOS_boot_code_offset & 0xFUL; - CPU_SetSegGeneral(cs, BIOS_boot_code_offset >> 4UL); -} - -void BIOS_SetCOMPort(Bitu port, uint16_t baseaddr) { - switch(port) { - case 0: - mem_writew(BIOS_BASE_ADDRESS_COM1,baseaddr); - mem_writeb(BIOS_COM1_TIMEOUT, 10); // FIXME: Right?? - break; - case 1: - mem_writew(BIOS_BASE_ADDRESS_COM2,baseaddr); - mem_writeb(BIOS_COM2_TIMEOUT, 10); // FIXME: Right?? - break; - case 2: - mem_writew(BIOS_BASE_ADDRESS_COM3,baseaddr); - mem_writeb(BIOS_COM3_TIMEOUT, 10); // FIXME: Right?? - break; - case 3: - mem_writew(BIOS_BASE_ADDRESS_COM4,baseaddr); - mem_writeb(BIOS_COM4_TIMEOUT, 10); // FIXME: Right?? - break; - } -} - -void BIOS_SetLPTPort(Bitu port, uint16_t baseaddr) { - switch(port) { - case 0: - mem_writew(BIOS_ADDRESS_LPT1,baseaddr); - mem_writeb(BIOS_LPT1_TIMEOUT, 10); - break; - case 1: - mem_writew(BIOS_ADDRESS_LPT2,baseaddr); - mem_writeb(BIOS_LPT2_TIMEOUT, 10); - break; - case 2: - mem_writew(BIOS_ADDRESS_LPT3,baseaddr); - mem_writeb(BIOS_LPT3_TIMEOUT, 10); - break; - } -} - -void BIOS_PnP_ComPortRegister(Bitu port,Bitu irq) { - /* add to PnP BIOS */ - if (ISAPNPBIOS) { - unsigned char tmp[256]; - unsigned int i; - - /* register serial ports */ - const unsigned char h1[9] = { - ISAPNP_SYSDEV_HEADER( - ISAPNP_ID('P','N','P',0x0,0x5,0x0,0x1), /* PNP0501 16550A-compatible COM port */ - ISAPNP_TYPE(0x07,0x00,0x02), /* type: RS-232 communications device, 16550-compatible */ - 0x0001 | 0x0002) - }; - - i = 0; - memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ - /*----------allocated--------*/ - tmp[i+0] = (8 << 3) | 7; /* IO resource */ - tmp[i+1] = 0x01; /* 16-bit decode */ - host_writew(tmp+i+2,port); /* min */ - host_writew(tmp+i+4,port); /* max */ - tmp[i+6] = 0x10; /* align */ - tmp[i+7] = 0x08; /* length */ - i += 7+1; - - if (irq > 0) { - tmp[i+0] = (4 << 3) | 3; /* IRQ resource */ - host_writew(tmp+i+1,1 << irq); - tmp[i+3] = 0x09; /* HTL=1 LTL=1 */ - i += 3+1; - } - - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - /*-------------possible-----------*/ - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - /*-------------compatible---------*/ - tmp[i+0] = 0x79; /* END TAG */ - tmp[i+1] = 0x00; - i += 2; - - if (!ISAPNP_RegisterSysDev(tmp,i)) { - //LOG_MSG("ISAPNP register failed\n"); - } - } -} - -static BIOS* test = NULL; - -void BIOS_Destroy(Section* /*sec*/){ - ROMBIOS_DumpMemory(); - ISA_PNP_FreeAllDevs(); - if (test != NULL) { - delete test; - test = NULL; - } -} - -void BIOS_OnPowerOn(Section* sec) { - (void)sec;//UNUSED - if (test) delete test; - test = new BIOS(control->GetSection("joystick")); -} - -void swapInNextDisk(bool pressed); -void swapInNextCD(bool pressed); - -void INT10_OnResetComplete(); -void CALLBACK_DeAllocate(Bitu in); - -void MOUSE_Unsetup_DOS(void); -void MOUSE_Unsetup_BIOS(void); - -void BIOS_OnResetComplete(Section *x) { - (void)x;//UNUSED - INT10_OnResetComplete(); - - if (IS_PC98_ARCH) { - void PC98_BIOS_Bank_Switch_Reset(void); - PC98_BIOS_Bank_Switch_Reset(); - } - - if (biosConfigSeg != 0u) { - ROMBIOS_FreeMemory((Bitu)(biosConfigSeg << 4u)); /* remember it was alloc'd paragraph aligned, then saved >> 4 */ - biosConfigSeg = 0u; - } - - call_pnp_rp = 0; - if (call_pnp_r != ~0UL) { - CALLBACK_DeAllocate(call_pnp_r); - call_pnp_r = ~0UL; - } - - call_pnp_pp = 0; - if (call_pnp_p != ~0UL) { - CALLBACK_DeAllocate(call_pnp_p); - call_pnp_p = ~0UL; - } - - MOUSE_Unsetup_DOS(); - MOUSE_Unsetup_BIOS(); - - ISA_PNP_FreeAllSysNodeDevs(); -} - -void BIOS_Init() { - DOSBoxMenu::item *item; - - LOG(LOG_MISC,LOG_DEBUG)("Initializing BIOS"); - - /* make sure the array is zeroed */ - ISAPNP_SysDevNodeCount = 0; - ISAPNP_SysDevNodeLargest = 0; - for (int i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) ISAPNP_SysDevNodes[i] = NULL; - - /* make sure CD swap and floppy swap mapper events are available */ - MAPPER_AddHandler(swapInNextDisk,MK_o,MMODHOST,"swapimg","Swap floppy drive",&item); /* Originally "Swap Image" but this version does not swap CDs */ - item->set_text("Swap floppy drive"); - - MAPPER_AddHandler(swapInNextCD,MK_d,MMODHOST,"swapcd","Swap CD drive",&item); /* Variant of "Swap Image" for CDs */ - item->set_text("Swap CD drive"); - - /* NTS: VM_EVENT_BIOS_INIT this callback must be first. */ - AddExitFunction(AddExitFunctionFuncPair(BIOS_Destroy),false); - AddVMEventFunction(VM_EVENT_POWERON,AddVMEventFunctionFuncPair(BIOS_OnPowerOn)); - AddVMEventFunction(VM_EVENT_RESET_END,AddVMEventFunctionFuncPair(BIOS_OnResetComplete)); -} - -void write_ID_version_string() { - Bitu str_id_at,str_ver_at; - size_t str_id_len,str_ver_len; - - /* NTS: We can't move the version and ID strings, it causes programs like MSD.EXE to lose - * track of the "IBM compatible blahblahblah" string. Which means that apparently - * programs looking for this information have the address hardcoded ALTHOUGH - * experiments show you can move the version string around so long as it's - * +1 from a paragraph boundary */ - /* TODO: *DO* allow dynamic relocation however if the dosbox-x.conf indicates that the user - * is not interested in IBM BIOS compatibility. Also, it would be really cool if - * dosbox-x.conf could override these strings and the user could enter custom BIOS - * version and ID strings. Heh heh heh.. :) */ - str_id_at = 0xFE00E; - str_ver_at = 0xFE061; - str_id_len = strlen(bios_type_string)+1; - str_ver_len = strlen(bios_version_string)+1; - if (!IS_PC98_ARCH) { - /* need to mark these strings off-limits so dynamic allocation does not overwrite them */ - ROMBIOS_GetMemory((Bitu)str_id_len+1,"BIOS ID string",1,str_id_at); - ROMBIOS_GetMemory((Bitu)str_ver_len+1,"BIOS version string",1,str_ver_at); - } - if (str_id_at != 0) { - for (size_t i=0;i < str_id_len;i++) phys_writeb(str_id_at+(PhysPt)i,(uint8_t)bios_type_string[i]); - } - if (str_ver_at != 0) { - for (size_t i=0;i < str_ver_len;i++) phys_writeb(str_ver_at+(PhysPt)i,(uint8_t)bios_version_string[i]); - } -} - -void GEN_PowerButton(bool pressed) { - if (!pressed) - return; - - if (PowerManagementEnabledButton()) { - PowerButtonClicks++; - } - else { - LOG(LOG_MISC,LOG_WARN)("Power button: Guest OS is not using power management and is probably ignoring the power button"); - } -} - - -extern uint8_t int10_font_08[256 * 8]; -extern uint16_t j3_font_offset; - -/* NTS: Do not use callbacks! This function is called before CALLBACK_Init() */ -void ROMBIOS_Init() { - Section_prop * section=static_cast(control->GetSection("dosbox")); - Bitu oi; - - /* This is GENERIC. Right now it only ties into the APM BIOS emulation. - * In the future, it will also tie into the ACPI emulation. We'll have - * menu items to trigger specific APM/ACPI events of course, but for - * the mapper, we'll try not to confuse the user with APM vs ACPI for - * the same reason PC manufacturers don't have two power buttons for - * each standard on the front. - * - * Note for PC-98 mode: I'm aware that there are mid to late 1990s - * PC-98 laptops that also have a power button to send some kind of - * power off event. If how that works becomes known, it can be tied - * to this mapper shortcut as well. It's obviously not APM since - * the APM standard is tied to the IBM compatible PC world. */ - - // log - LOG(LOG_MISC,LOG_DEBUG)("Initializing ROM BIOS"); - - ibm_rom_basic.clear(); - ibm_rom_basic_size = 0; - - oi = (Bitu)section->Get_int("rom bios minimum size"); /* in KB */ - oi = (oi + 3u) & ~3u; /* round to 4KB page */ - if (oi > 128u) oi = 128u; - if (oi == 0u) { - if (IS_PC98_ARCH) - oi = 96u; // BIOS standard range is E8000-FFFFF - else - oi = 64u; - } - if (oi < 8) oi = 8; /* because of some of DOSBox's fixed ROM structures we can only go down to 8KB */ - rombios_minimum_size = (oi << 10); /* convert to minimum, using size coming downward from 1MB */ - - oi = (Bitu)section->Get_int("rom bios allocation max"); /* in KB */ - oi = (oi + 3u) & ~3u; /* round to 4KB page */ - if (oi > 128u) oi = 128u; - if (oi == 0u) { - if (IS_PC98_ARCH) - oi = 96u; - else - oi = 64u; - } - if (oi < 8u) oi = 8u; /* because of some of DOSBox's fixed ROM structures we can only go down to 8KB */ - oi <<= 10u; - if (oi < rombios_minimum_size) oi = rombios_minimum_size; - rombios_minimum_location = 0x100000ul - oi; /* convert to minimum, using size coming downward from 1MB */ - - LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS range: 0x%05X-0xFFFFF",(int)rombios_minimum_location); - LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS range according to minimum size: 0x%05X-0xFFFFF",(int)(0x100000 - rombios_minimum_size)); - - if (IS_PC98_ARCH && rombios_minimum_location > 0xE8000) - LOG(LOG_BIOS,LOG_DEBUG)("Caution: Minimum ROM base higher than E8000 will prevent use of actual PC-98 BIOS image or N88 BASIC"); - - if (!MEM_map_ROM_physmem(rombios_minimum_location,0xFFFFF)) E_Exit("Unable to map ROM region as ROM"); - - /* and the BIOS alias at the top of memory (TODO: what about 486/Pentium emulation where the BIOS at the 4GB top is different - * from the BIOS at the legacy 1MB boundary because of shadowing and/or decompressing from ROM at boot? */ - { - uint64_t top = (uint64_t)1UL << (uint64_t)MEM_get_address_bits4GB(); - if (top >= ((uint64_t)1UL << (uint64_t)21UL)) { /* 2MB or more */ - unsigned long alias_base,alias_end; - - alias_base = (unsigned long)top + (unsigned long)rombios_minimum_location - 0x100000UL; - alias_end = (unsigned long)top - 1UL; - - LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS also mapping alias to 0x%08lx-0x%08lx",alias_base,alias_end); - if (!MEM_map_ROM_alias_physmem(alias_base,alias_end)) { - void MEM_cut_RAM_up_to(Bitu addr); - - /* it's possible if memory aliasing is set that memsize is too large to make room. - * let memory emulation know where the ROM BIOS starts so it can unmap the RAM pages, - * reduce the memory reported to the OS, and try again... */ - LOG(LOG_BIOS,LOG_DEBUG)("No room for ROM BIOS alias, reducing reported memory and unmapping RAM pages to make room"); - MEM_cut_RAM_up_to(alias_base); - - if (!MEM_map_ROM_alias_physmem(alias_base,alias_end)) - E_Exit("Unable to map ROM region as ROM alias"); - } - } - } - - /* set up allocation */ - rombios_alloc.name = "ROM BIOS"; - rombios_alloc.topDownAlloc = true; - rombios_alloc.initSetRange(rombios_minimum_location,0xFFFF0 - 1); - - if (IS_PC98_ARCH) { - /* TODO: Is this needed? And where? */ - } - else { - /* prevent dynamic allocation from taking reserved fixed addresses above F000:E000 in IBM PC mode. */ - rombios_alloc.setMaxDynamicAllocationAddress(0xFE000 - 1); - } - - if (!IS_PC98_ARCH) { - ibm_rom_basic = section->Get_string("ibm rom basic"); - if (!ibm_rom_basic.empty()) { - void ResolvePath(std::string& in); - ResolvePath(ibm_rom_basic); - struct stat st; - if (stat(ibm_rom_basic.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size >= (off_t)(32u*1024u) && st.st_size <= (off_t)(64u*1024u) && (st.st_size % 4096) == 0) { - ibm_rom_basic_size = (size_t)st.st_size; - ibm_rom_basic_base = rombios_alloc._max_nonfixed + 1 - st.st_size; - LOG_MSG("Will load IBM ROM BASIC to %05lx-%05lx",(unsigned long)ibm_rom_basic_base,(unsigned long)(ibm_rom_basic_base+ibm_rom_basic_size-1)); - Bitu base = ROMBIOS_GetMemory(ibm_rom_basic_size,"IBM ROM BASIC",1u/*page align*/,ibm_rom_basic_base); - rombios_alloc.setMaxDynamicAllocationAddress(ibm_rom_basic_base - 1); - (void)base; - - FILE *fp = fopen(ibm_rom_basic.c_str(),"rb"); - if (fp != NULL) { - fread(GetMemBase()+ibm_rom_basic_base,ibm_rom_basic_size,1u,fp); - fclose(fp); - } - } - } - } - - write_ID_version_string(); - - if (IS_PC98_ARCH && enable_pc98_copyright_string) { // PC-98 BIOSes have a copyright string at E800:0DD8 - if (ROMBIOS_GetMemory(pc98_copyright_str.length()+1,"PC-98 copyright string",1,0xE8000 + 0x0DD8) == 0) - LOG_MSG("WARNING: Was not able to mark off E800:0DD8 off-limits for PC-98 copyright string"); - if (ROMBIOS_GetMemory(sizeof(pc98_epson_check_2),"PC-98 unknown data / Epson check",1,0xF5200 + 0x018E) == 0) - LOG_MSG("WARNING: Was not able to mark off E800:0DD8 off-limits for PC-98 copyright string"); - } - - /* some structures when enabled are fixed no matter what */ - if (rom_bios_8x8_cga_font && !IS_PC98_ARCH) { - /* line 139, int10_memory.cpp: the 8x8 font at 0xF000:FA6E, first 128 chars. - * allocate this NOW before other things get in the way */ - if (ROMBIOS_GetMemory(128*8,"BIOS 8x8 font (first 128 chars)",1,0xFFA6E) == 0) { - LOG_MSG("WARNING: Was not able to mark off 0xFFA6E off-limits for 8x8 font"); - } - } - - /* PC-98 BIOS vectors appear to reside at segment 0xFD80. This is so common some games - * use it (through INT 1Dh) to detect whether they are running on PC-98 or not (issue #927). - * - * Note that INT 1Dh is one of the few BIOS interrupts not intercepted by PC-98 MS-DOS */ - if (IS_PC98_ARCH) { - if (ROMBIOS_GetMemory(128,"PC-98 INT vector stub segment 0xFD80",1,0xFD800) == 0) { - LOG_MSG("WARNING: Was not able to mark off 0xFD800 off-limits for PC-98 int vector stubs"); - } - } - - /* PC-98 BIOSes have a LIO interface at segment F990 with graphic subroutines for Microsoft BASIC */ - if (IS_PC98_ARCH) { - if (ROMBIOS_GetMemory(256,"PC-98 LIO graphic ROM BIOS library",1,0xF9900) == 0) { - LOG_MSG("WARNING: Was not able to mark off 0xF9900 off-limits for PC-98 LIO graphics library"); - } - } - - /* install the font */ - if (rom_bios_8x8_cga_font) { - for (Bitu i=0;i<128*8;i++) { - phys_writeb(PhysMake(0xf000,0xfa6e)+i,int10_font_08[i]); - } - } - - /* we allow dosbox-x.conf to specify a binary blob to load into ROM BIOS and execute after reset. - * we allow this for both hacker curiosity and automated CPU testing. */ - { - std::string path = section->Get_string("call binary on reset"); - struct stat st; - - if (!path.empty() && stat(path.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size <= (off_t)(128u*1024u)) { - Bitu base = ROMBIOS_GetMemory((Bitu)st.st_size,"User reset vector binary",16u/*page align*/,0u); - - if (base != 0) { - FILE *fp = fopen(path.c_str(),"rb"); - - if (fp != NULL) { - /* NTS: Make sure memory base != NULL, and that it fits within 1MB. - * memory code allocates a minimum 1MB of memory even if - * guest memory is less than 1MB because ROM BIOS emulation - * depends on it. */ - assert(GetMemBase() != NULL); - assert((base+(Bitu)st.st_size) <= 0x100000ul); - size_t readResult = fread(GetMemBase()+base,(size_t)st.st_size,1u,fp); - fclose(fp); - if (readResult != 1) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in ROMBIOS_Init\n"); - return; - } - - LOG_MSG("User reset vector binary '%s' loaded at 0x%lx",path.c_str(),(unsigned long)base); - bios_user_reset_vector_blob = base; - } - else { - LOG_MSG("WARNING: Unable to open file to load user reset vector binary '%s' into ROM BIOS memory",path.c_str()); - } - } - else { - LOG_MSG("WARNING: Unable to load user reset vector binary '%s' into ROM BIOS memory",path.c_str()); - } - } - } - - /* we allow dosbox-x.conf to specify a binary blob to load into ROM BIOS and execute just before boot. - * we allow this for both hacker curiosity and automated CPU testing. */ - { - std::string path = section->Get_string("call binary on boot"); - struct stat st; - - if (!path.empty() && stat(path.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size <= (off_t)(128u*1024u)) { - Bitu base = ROMBIOS_GetMemory((Bitu)st.st_size,"User boot hook binary",16u/*page align*/,0u); - - if (base != 0) { - FILE *fp = fopen(path.c_str(),"rb"); - - if (fp != NULL) { - /* NTS: Make sure memory base != NULL, and that it fits within 1MB. - * memory code allocates a minimum 1MB of memory even if - * guest memory is less than 1MB because ROM BIOS emulation - * depends on it. */ - assert(GetMemBase() != NULL); - assert((base+(Bitu)st.st_size) <= 0x100000ul); - size_t readResult = fread(GetMemBase()+base,(size_t)st.st_size,1u,fp); - fclose(fp); - if (readResult != 1) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in ROMBIOS_Init\n"); - return; - } - - LOG_MSG("User boot hook binary '%s' loaded at 0x%lx",path.c_str(),(unsigned long)base); - bios_user_boot_hook = base; - } - else { - LOG_MSG("WARNING: Unable to open file to load user boot hook binary '%s' into ROM BIOS memory",path.c_str()); - } - } - else { - LOG_MSG("WARNING: Unable to load user boot hook binary '%s' into ROM BIOS memory",path.c_str()); - } - } - } - // J-3100's DOS reads 8x16 font data directly from F000:CA00. - if(IS_J3100) { - ROMBIOS_GetMemory(256*16, "J-3100 8x16 font data", 1, 0xf0000 + j3_font_offset); - } -} - -//! \brief Updates the state of a lockable key. -void UpdateKeyWithLed(int nVirtKey, int flagAct, int flagLed); + } + + Bitu wo = Real2Phys(BIOS_DEFAULT_RESET_CODE_LOCATION); + wo_fence = wo + 64; + + // POST + phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(wo+0x02,(uint16_t)cb_bios_post.Get_callback()); //The immediate word + wo += 4; + + // video bios scan + phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(wo+0x02,(uint16_t)cb_bios_scan_video_bios.Get_callback()); //The immediate word + wo += 4; + + // adapter ROM scan + phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(wo+0x02,(uint16_t)cb_bios_adapter_rom_scan.Get_callback()); //The immediate word + wo += 4; + + // startup screen + phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(wo+0x02,(uint16_t)cb_bios_startup_screen.Get_callback()); //The immediate word + wo += 4; + + // user boot hook + if (bios_user_boot_hook != 0) { + phys_writeb(wo+0x00,0x9C); //PUSHF + phys_writeb(wo+0x01,0x9A); //CALL FAR + phys_writew(wo+0x02,0x0000); //seg:0 + phys_writew(wo+0x04,bios_user_boot_hook>>4); + wo += 6; + } + + // boot + BIOS_boot_code_offset = wo; + phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(wo+0x02,(uint16_t)cb_bios_boot.Get_callback()); //The immediate word + wo += 4; + + // boot fail + BIOS_bootfail_code_offset = wo; + phys_writeb(wo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(wo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(wo+0x02,(uint16_t)cb_bios_bootfail.Get_callback()); //The immediate word + wo += 4; + + /* fence */ + phys_writeb(wo++,0xEB); // JMP $-2 + phys_writeb(wo++,0xFE); + + if (wo > wo_fence) E_Exit("BIOS boot callback overrun"); + + if (IS_PC98_ARCH) { + /* Boot disks that run N88 basic, stopgap */ + PhysPt bo = 0xE8002; // E800:0002 + + ROMBIOS_GetMemory(6,"N88 ROM BASIC entry point",/*align*/1,bo); + + phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(bo+0x02,(uint16_t)cb_pc98_rombasic.Get_callback()); //The immediate word + + phys_writeb(bo+0x04,0xEB); // JMP $-2 + phys_writeb(bo+0x05,0xFE); + + // On careful examination of BIOS.ROM, there's a JMP instruction at E800:0000 as well. + // I don't have any test cases that jump there, but add a JMP forward just in case. + bo = 0xE8000; + phys_writeb(bo+0x00,(uint8_t)0xEB); // JMP $+2 (to next instruction) + phys_writeb(bo+0x01,(uint8_t)0x00); + + /* "Nut Berry" expects a 8-byte lookup table for [AL&7] -> 1 << (AL&7) at 0xFD80:0x0E3C so it's + * custom keyboard interrupt handler can update the keyboard status bitmap in the BIOS data area. + * I don't know if the game even uses it. On a BIOS.ROM image I have, and on real hardware, there + * is clearly that table but at slightly different addresses (One PC-9821 laptop has it at + * 0xFD80:0x0E45) which means whether the game uses it or not the bitmap may have random bits set + * when you exit to DOS. + * + * Assuming no other game does this, this fixed address should be fine. + * + * NOTE: After disassembling the IRQ1 handler on a real PC-9821 laptop, I noticed this game's + * custom ISR bears a strong resemblance to it. In fact, you might say it's an exact instruction + * for instruction copy of the ISR, except that the table addresses in ROM are slightly different. + * Ha. Theoretically then, that means we could also get this game to work fully properly by patching + * it not to hook the keyboard interrupt at all! */ + for (unsigned int i=0;i < 8;i++) phys_writeb(0xFD800+0xE3C+i,1u << i); + + /* "Nut Berry" also assumes shift state table offsets (for all 16 possible combinations) exist + * at 0xFD80:0x0E28. Once again, this means it will not work properly on anything other than the dev's + * machine because on a real PC-9821 laptop used for testing, the table offset is slightly different + * (0xE31 instead of 0xE28). The table mentioned here is used to update the 0x522 offset WORD in the + * BIOS data area to reflect the translation table in effect based on the shift key status, so if you + * misread the table you end up pointing it at junk and then keyboard input doesn't work anymore. */ + // NTS: On a real PC-9821 laptop, the table is apparently 10 entries long. If BDA byte 0x53A is less than + // 8 then it's just a simple lookup. If BDA byte 0x53A has bit 4 set, then use the 8th entry, and + // if bit 4 and 3 are set, use the 9th entry. + for (unsigned int i=0;i < 10;i++) phys_writew(0xFD800+0xE28+(i*2),(unsigned int)(Real2Phys(BIOS_PC98_KEYBOARD_TRANSLATION_LOCATION) - 0xFD800) + (i * 0x60)); + } + else { + if (ibm_rom_basic_size == 0) { + /* IBM MS-DOS 1.x/2.x BASIC and BASICA, stopgap */ + PhysPt bo; + + bo = 0xF6000+0x2DB0; // F600:2DB0 + + ROMBIOS_GetMemory(6,"IBM ROM BASIC entry point",/*align*/1,bo); + + phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(bo+0x02,(uint16_t)cb_ibm_basic.Get_callback()); //The immediate word + + phys_writeb(bo+0x04,0xEB); // JMP $-2 + phys_writeb(bo+0x05,0xFE); + + bo = 0xF6000+0x4C79; // F600:4C79 + + ROMBIOS_GetMemory(6,"IBM ROM BASIC entry point",/*align*/1,bo); + + phys_writeb(bo+0x00,(uint8_t)0xFE); //GRP 4 + phys_writeb(bo+0x01,(uint8_t)0x38); //Extra Callback instruction + phys_writew(bo+0x02,(uint16_t)cb_ibm_basic.Get_callback()); //The immediate word + + phys_writeb(bo+0x04,0xEB); // JMP $-2 + phys_writeb(bo+0x05,0xFE); + } + } + + if (IS_PC98_ARCH && enable_pc98_copyright_string) { + size_t i=0; + + ROMBIOS_GetMemory(pc98_copyright_str.length()+1,"NEC PC-98 copyright string",/*align*/1,0xE8000 + 0x0DD8); + + for (;i < pc98_copyright_str.length();i++) + phys_writeb(0xE8000 + 0x0DD8 + (PhysPt)i,(uint8_t)pc98_copyright_str[i]); + + phys_writeb(0xE8000 + 0x0DD8 + (PhysPt)i,0); + + ROMBIOS_GetMemory(sizeof(pc98_epson_check_2),"NEC PC-98 Epson check data #2",/*align*/1,0xF5200 + 0x018E); + + for (i=0;i < sizeof(pc98_epson_check_2);i++) + phys_writeb(0xF5200 + 0x018E + (PhysPt)i,(uint8_t)pc98_epson_check_2[i]); + } + } + } + ~BIOS(){ + /* snap the CPU back to real mode. this code thinks in terms of 16-bit real mode + * and if allowed to do its thing in a 32-bit guest OS like WinNT, will trigger + * a page fault. */ + CPU_Snap_Back_To_Real_Mode(); + + if (acpi_iocallout != IO_Callout_t_none) { + IO_FreeCallout(acpi_iocallout); + acpi_iocallout = IO_Callout_t_none; + } + + if (BOCHS_PORT_E9) { + delete BOCHS_PORT_E9; + BOCHS_PORT_E9=NULL; + } + if (ISAPNP_PNP_ADDRESS_PORT) { + delete ISAPNP_PNP_ADDRESS_PORT; + ISAPNP_PNP_ADDRESS_PORT=NULL; + } + if (ISAPNP_PNP_DATA_PORT) { + delete ISAPNP_PNP_DATA_PORT; + ISAPNP_PNP_DATA_PORT=NULL; + } + if (ISAPNP_PNP_READ_PORT) { + delete ISAPNP_PNP_READ_PORT; + ISAPNP_PNP_READ_PORT=NULL; + } + if (isapnpigdevice) { + /* ISA PnP will auto-free it */ + isapnpigdevice=NULL; + } + + if (dosbox_int_iocallout != IO_Callout_t_none) { + IO_FreeCallout(dosbox_int_iocallout); + dosbox_int_iocallout = IO_Callout_t_none; + } + + /* abort DAC playing */ + if (tandy_sb.port) { + IO_Write(tandy_sb.port+0xcu,0xd3u); + IO_Write(tandy_sb.port+0xcu,0xd0u); + } + real_writeb(0x40,0xd4,0x00); + if (tandy_DAC_callback[0]) { + uint32_t orig_vector=real_readd(0x40,0xd6); + if (orig_vector==tandy_DAC_callback[0]->Get_RealPointer()) { + /* set IRQ vector to old value */ + uint8_t tandy_irq = 7; + if (tandy_sb.port) tandy_irq = tandy_sb.irq; + else if (tandy_dac.port) tandy_irq = tandy_dac.irq; + uint8_t tandy_irq_vector = tandy_irq; + if (tandy_irq_vector<8) tandy_irq_vector += 8; + else tandy_irq_vector += (0x70-8); + + RealSetVec(tandy_irq_vector,real_readd(0x40,0xd6)); + real_writed(0x40,0xd6,0x00000000); + } + delete tandy_DAC_callback[0]; + delete tandy_DAC_callback[1]; + tandy_DAC_callback[0]=NULL; + tandy_DAC_callback[1]=NULL; + } + + /* encourage the callback objects to uninstall HERE while we're in real mode, NOT during the + * destructor stage where we're back in protected mode */ + for (unsigned int i=0;i < callback_count;i++) callback[i].Uninstall(); + + /* assume these were allocated */ + CALLBACK_DeAllocate(call_irq0); + CALLBACK_DeAllocate(call_irq07default); + CALLBACK_DeAllocate(call_irq815default); + + /* done */ + CPU_Snap_Back_Restore(); + } +}; + +void BIOS_Enter_Boot_Phase(void) { + /* direct CS:IP right to the instruction that leads to the boot process */ + /* note that since it's a callback instruction it doesn't really matter + * what CS:IP is as long as it points to the instruction */ + reg_eip = BIOS_boot_code_offset & 0xFUL; + CPU_SetSegGeneral(cs, BIOS_boot_code_offset >> 4UL); +} + +void BIOS_SetCOMPort(Bitu port, uint16_t baseaddr) { + switch(port) { + case 0: + mem_writew(BIOS_BASE_ADDRESS_COM1,baseaddr); + mem_writeb(BIOS_COM1_TIMEOUT, 10); // FIXME: Right?? + break; + case 1: + mem_writew(BIOS_BASE_ADDRESS_COM2,baseaddr); + mem_writeb(BIOS_COM2_TIMEOUT, 10); // FIXME: Right?? + break; + case 2: + mem_writew(BIOS_BASE_ADDRESS_COM3,baseaddr); + mem_writeb(BIOS_COM3_TIMEOUT, 10); // FIXME: Right?? + break; + case 3: + mem_writew(BIOS_BASE_ADDRESS_COM4,baseaddr); + mem_writeb(BIOS_COM4_TIMEOUT, 10); // FIXME: Right?? + break; + } +} + +void BIOS_SetLPTPort(Bitu port, uint16_t baseaddr) { + switch(port) { + case 0: + mem_writew(BIOS_ADDRESS_LPT1,baseaddr); + mem_writeb(BIOS_LPT1_TIMEOUT, 10); + break; + case 1: + mem_writew(BIOS_ADDRESS_LPT2,baseaddr); + mem_writeb(BIOS_LPT2_TIMEOUT, 10); + break; + case 2: + mem_writew(BIOS_ADDRESS_LPT3,baseaddr); + mem_writeb(BIOS_LPT3_TIMEOUT, 10); + break; + } +} + +void BIOS_PnP_ComPortRegister(Bitu port,Bitu irq) { + /* add to PnP BIOS */ + if (ISAPNPBIOS) { + unsigned char tmp[256]; + unsigned int i; + + /* register serial ports */ + const unsigned char h1[9] = { + ISAPNP_SYSDEV_HEADER( + ISAPNP_ID('P','N','P',0x0,0x5,0x0,0x1), /* PNP0501 16550A-compatible COM port */ + ISAPNP_TYPE(0x07,0x00,0x02), /* type: RS-232 communications device, 16550-compatible */ + 0x0001 | 0x0002) + }; + + i = 0; + memcpy(tmp+i,h1,9); i += 9; /* can't disable, can't configure */ + /*----------allocated--------*/ + tmp[i+0] = (8 << 3) | 7; /* IO resource */ + tmp[i+1] = 0x01; /* 16-bit decode */ + host_writew(tmp+i+2,port); /* min */ + host_writew(tmp+i+4,port); /* max */ + tmp[i+6] = 0x10; /* align */ + tmp[i+7] = 0x08; /* length */ + i += 7+1; + + if (irq > 0) { + tmp[i+0] = (4 << 3) | 3; /* IRQ resource */ + host_writew(tmp+i+1,1 << irq); + tmp[i+3] = 0x09; /* HTL=1 LTL=1 */ + i += 3+1; + } + + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + /*-------------possible-----------*/ + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + /*-------------compatible---------*/ + tmp[i+0] = 0x79; /* END TAG */ + tmp[i+1] = 0x00; + i += 2; + + if (!ISAPNP_RegisterSysDev(tmp,i)) { + //LOG_MSG("ISAPNP register failed\n"); + } + } +} + +static BIOS* test = NULL; + +void BIOS_Destroy(Section* /*sec*/){ + ROMBIOS_DumpMemory(); + ISA_PNP_FreeAllDevs(); + if (test != NULL) { + delete test; + test = NULL; + } +} + +void BIOS_OnPowerOn(Section* sec) { + (void)sec;//UNUSED + if (test) delete test; + test = new BIOS(control->GetSection("joystick")); +} + +void swapInNextDisk(bool pressed); +void swapInNextCD(bool pressed); + +void INT10_OnResetComplete(); +void CALLBACK_DeAllocate(Bitu in); + +void MOUSE_Unsetup_DOS(void); +void MOUSE_Unsetup_BIOS(void); + +void BIOS_OnResetComplete(Section *x) { + (void)x;//UNUSED + INT10_OnResetComplete(); + + if (IS_PC98_ARCH) { + void PC98_BIOS_Bank_Switch_Reset(void); + PC98_BIOS_Bank_Switch_Reset(); + } + + if (biosConfigSeg != 0u) { + ROMBIOS_FreeMemory((Bitu)(biosConfigSeg << 4u)); /* remember it was alloc'd paragraph aligned, then saved >> 4 */ + biosConfigSeg = 0u; + } + + call_pnp_rp = 0; + if (call_pnp_r != ~0UL) { + CALLBACK_DeAllocate(call_pnp_r); + call_pnp_r = ~0UL; + } + + call_pnp_pp = 0; + if (call_pnp_p != ~0UL) { + CALLBACK_DeAllocate(call_pnp_p); + call_pnp_p = ~0UL; + } + + MOUSE_Unsetup_DOS(); + MOUSE_Unsetup_BIOS(); + + ISA_PNP_FreeAllSysNodeDevs(); +} + +void BIOS_Init() { + DOSBoxMenu::item *item; + + LOG(LOG_MISC,LOG_DEBUG)("Initializing BIOS"); + + /* make sure the array is zeroed */ + ISAPNP_SysDevNodeCount = 0; + ISAPNP_SysDevNodeLargest = 0; + for (int i=0;i < MAX_ISA_PNP_SYSDEVNODES;i++) ISAPNP_SysDevNodes[i] = NULL; + + /* make sure CD swap and floppy swap mapper events are available */ + MAPPER_AddHandler(swapInNextDisk,MK_o,MMODHOST,"swapimg","Swap floppy drive",&item); /* Originally "Swap Image" but this version does not swap CDs */ + item->set_text("Swap floppy drive"); + + MAPPER_AddHandler(swapInNextCD,MK_d,MMODHOST,"swapcd","Swap CD drive",&item); /* Variant of "Swap Image" for CDs */ + item->set_text("Swap CD drive"); + + /* NTS: VM_EVENT_BIOS_INIT this callback must be first. */ + AddExitFunction(AddExitFunctionFuncPair(BIOS_Destroy),false); + AddVMEventFunction(VM_EVENT_POWERON,AddVMEventFunctionFuncPair(BIOS_OnPowerOn)); + AddVMEventFunction(VM_EVENT_RESET_END,AddVMEventFunctionFuncPair(BIOS_OnResetComplete)); +} + +void write_ID_version_string() { + Bitu str_id_at,str_ver_at; + size_t str_id_len,str_ver_len; + + /* NTS: We can't move the version and ID strings, it causes programs like MSD.EXE to lose + * track of the "IBM compatible blahblahblah" string. Which means that apparently + * programs looking for this information have the address hardcoded ALTHOUGH + * experiments show you can move the version string around so long as it's + * +1 from a paragraph boundary */ + /* TODO: *DO* allow dynamic relocation however if the dosbox-x.conf indicates that the user + * is not interested in IBM BIOS compatibility. Also, it would be really cool if + * dosbox-x.conf could override these strings and the user could enter custom BIOS + * version and ID strings. Heh heh heh.. :) */ + str_id_at = 0xFE00E; + str_ver_at = 0xFE061; + str_id_len = strlen(bios_type_string)+1; + str_ver_len = strlen(bios_version_string)+1; + if (!IS_PC98_ARCH) { + /* need to mark these strings off-limits so dynamic allocation does not overwrite them */ + ROMBIOS_GetMemory((Bitu)str_id_len+1,"BIOS ID string",1,str_id_at); + ROMBIOS_GetMemory((Bitu)str_ver_len+1,"BIOS version string",1,str_ver_at); + } + if (str_id_at != 0) { + for (size_t i=0;i < str_id_len;i++) phys_writeb(str_id_at+(PhysPt)i,(uint8_t)bios_type_string[i]); + } + if (str_ver_at != 0) { + for (size_t i=0;i < str_ver_len;i++) phys_writeb(str_ver_at+(PhysPt)i,(uint8_t)bios_version_string[i]); + } +} + +void GEN_PowerButton(bool pressed) { + if (!pressed) + return; + + if (PowerManagementEnabledButton()) { + PowerButtonClicks++; + } + else { + LOG(LOG_MISC,LOG_WARN)("Power button: Guest OS is not using power management and is probably ignoring the power button"); + } +} + + +extern uint8_t int10_font_08[256 * 8]; +extern uint16_t j3_font_offset; + +/* NTS: Do not use callbacks! This function is called before CALLBACK_Init() */ +void ROMBIOS_Init() { + Section_prop * section=static_cast(control->GetSection("dosbox")); + Bitu oi; + + /* This is GENERIC. Right now it only ties into the APM BIOS emulation. + * In the future, it will also tie into the ACPI emulation. We'll have + * menu items to trigger specific APM/ACPI events of course, but for + * the mapper, we'll try not to confuse the user with APM vs ACPI for + * the same reason PC manufacturers don't have two power buttons for + * each standard on the front. + * + * Note for PC-98 mode: I'm aware that there are mid to late 1990s + * PC-98 laptops that also have a power button to send some kind of + * power off event. If how that works becomes known, it can be tied + * to this mapper shortcut as well. It's obviously not APM since + * the APM standard is tied to the IBM compatible PC world. */ + + // log + LOG(LOG_MISC,LOG_DEBUG)("Initializing ROM BIOS"); + + ibm_rom_basic.clear(); + ibm_rom_basic_size = 0; + + oi = (Bitu)section->Get_int("rom bios minimum size"); /* in KB */ + oi = (oi + 3u) & ~3u; /* round to 4KB page */ + if (oi > 128u) oi = 128u; + if (oi == 0u) { + if (IS_PC98_ARCH) + oi = 96u; // BIOS standard range is E8000-FFFFF + else + oi = 64u; + } + if (oi < 8) oi = 8; /* because of some of DOSBox's fixed ROM structures we can only go down to 8KB */ + rombios_minimum_size = (oi << 10); /* convert to minimum, using size coming downward from 1MB */ + + oi = (Bitu)section->Get_int("rom bios allocation max"); /* in KB */ + oi = (oi + 3u) & ~3u; /* round to 4KB page */ + if (oi > 128u) oi = 128u; + if (oi == 0u) { + if (IS_PC98_ARCH) + oi = 96u; + else + oi = 64u; + } + if (oi < 8u) oi = 8u; /* because of some of DOSBox's fixed ROM structures we can only go down to 8KB */ + oi <<= 10u; + if (oi < rombios_minimum_size) oi = rombios_minimum_size; + rombios_minimum_location = 0x100000ul - oi; /* convert to minimum, using size coming downward from 1MB */ + + LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS range: 0x%05X-0xFFFFF",(int)rombios_minimum_location); + LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS range according to minimum size: 0x%05X-0xFFFFF",(int)(0x100000 - rombios_minimum_size)); + + if (IS_PC98_ARCH && rombios_minimum_location > 0xE8000) + LOG(LOG_BIOS,LOG_DEBUG)("Caution: Minimum ROM base higher than E8000 will prevent use of actual PC-98 BIOS image or N88 BASIC"); + + if (!MEM_map_ROM_physmem(rombios_minimum_location,0xFFFFF)) E_Exit("Unable to map ROM region as ROM"); + + /* and the BIOS alias at the top of memory (TODO: what about 486/Pentium emulation where the BIOS at the 4GB top is different + * from the BIOS at the legacy 1MB boundary because of shadowing and/or decompressing from ROM at boot? */ + { + uint64_t top = (uint64_t)1UL << (uint64_t)MEM_get_address_bits4GB(); + if (top >= ((uint64_t)1UL << (uint64_t)21UL)) { /* 2MB or more */ + unsigned long alias_base,alias_end; + + alias_base = (unsigned long)top + (unsigned long)rombios_minimum_location - 0x100000UL; + alias_end = (unsigned long)top - 1UL; + + LOG(LOG_BIOS,LOG_DEBUG)("ROM BIOS also mapping alias to 0x%08lx-0x%08lx",alias_base,alias_end); + if (!MEM_map_ROM_alias_physmem(alias_base,alias_end)) { + void MEM_cut_RAM_up_to(Bitu addr); + + /* it's possible if memory aliasing is set that memsize is too large to make room. + * let memory emulation know where the ROM BIOS starts so it can unmap the RAM pages, + * reduce the memory reported to the OS, and try again... */ + LOG(LOG_BIOS,LOG_DEBUG)("No room for ROM BIOS alias, reducing reported memory and unmapping RAM pages to make room"); + MEM_cut_RAM_up_to(alias_base); + + if (!MEM_map_ROM_alias_physmem(alias_base,alias_end)) + E_Exit("Unable to map ROM region as ROM alias"); + } + } + } + + /* set up allocation */ + rombios_alloc.name = "ROM BIOS"; + rombios_alloc.topDownAlloc = true; + rombios_alloc.initSetRange(rombios_minimum_location,0xFFFF0 - 1); + + if (IS_PC98_ARCH) { + /* TODO: Is this needed? And where? */ + } + else { + /* prevent dynamic allocation from taking reserved fixed addresses above F000:E000 in IBM PC mode. */ + rombios_alloc.setMaxDynamicAllocationAddress(0xFE000 - 1); + } + + if (!IS_PC98_ARCH) { + ibm_rom_basic = section->Get_string("ibm rom basic"); + if (!ibm_rom_basic.empty()) { + void ResolvePath(std::string& in); + ResolvePath(ibm_rom_basic); + struct stat st; + if (stat(ibm_rom_basic.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size >= (off_t)(32u*1024u) && st.st_size <= (off_t)(64u*1024u) && (st.st_size % 4096) == 0) { + ibm_rom_basic_size = (size_t)st.st_size; + ibm_rom_basic_base = rombios_alloc._max_nonfixed + 1 - st.st_size; + LOG_MSG("Will load IBM ROM BASIC to %05lx-%05lx",(unsigned long)ibm_rom_basic_base,(unsigned long)(ibm_rom_basic_base+ibm_rom_basic_size-1)); + Bitu base = ROMBIOS_GetMemory(ibm_rom_basic_size,"IBM ROM BASIC",1u/*page align*/,ibm_rom_basic_base); + rombios_alloc.setMaxDynamicAllocationAddress(ibm_rom_basic_base - 1); + (void)base; + + FILE *fp = fopen(ibm_rom_basic.c_str(),"rb"); + if (fp != NULL) { + fread(GetMemBase()+ibm_rom_basic_base,ibm_rom_basic_size,1u,fp); + fclose(fp); + } + } + } + } + + write_ID_version_string(); + + if (IS_PC98_ARCH && enable_pc98_copyright_string) { // PC-98 BIOSes have a copyright string at E800:0DD8 + if (ROMBIOS_GetMemory(pc98_copyright_str.length()+1,"PC-98 copyright string",1,0xE8000 + 0x0DD8) == 0) + LOG_MSG("WARNING: Was not able to mark off E800:0DD8 off-limits for PC-98 copyright string"); + if (ROMBIOS_GetMemory(sizeof(pc98_epson_check_2),"PC-98 unknown data / Epson check",1,0xF5200 + 0x018E) == 0) + LOG_MSG("WARNING: Was not able to mark off E800:0DD8 off-limits for PC-98 copyright string"); + } + + /* some structures when enabled are fixed no matter what */ + if (rom_bios_8x8_cga_font && !IS_PC98_ARCH) { + /* line 139, int10_memory.cpp: the 8x8 font at 0xF000:FA6E, first 128 chars. + * allocate this NOW before other things get in the way */ + if (ROMBIOS_GetMemory(128*8,"BIOS 8x8 font (first 128 chars)",1,0xFFA6E) == 0) { + LOG_MSG("WARNING: Was not able to mark off 0xFFA6E off-limits for 8x8 font"); + } + } + + /* PC-98 BIOS vectors appear to reside at segment 0xFD80. This is so common some games + * use it (through INT 1Dh) to detect whether they are running on PC-98 or not (issue #927). + * + * Note that INT 1Dh is one of the few BIOS interrupts not intercepted by PC-98 MS-DOS */ + if (IS_PC98_ARCH) { + if (ROMBIOS_GetMemory(128,"PC-98 INT vector stub segment 0xFD80",1,0xFD800) == 0) { + LOG_MSG("WARNING: Was not able to mark off 0xFD800 off-limits for PC-98 int vector stubs"); + } + } + + /* PC-98 BIOSes have a LIO interface at segment F990 with graphic subroutines for Microsoft BASIC */ + if (IS_PC98_ARCH) { + if (ROMBIOS_GetMemory(256,"PC-98 LIO graphic ROM BIOS library",1,0xF9900) == 0) { + LOG_MSG("WARNING: Was not able to mark off 0xF9900 off-limits for PC-98 LIO graphics library"); + } + } + + /* install the font */ + if (rom_bios_8x8_cga_font) { + for (Bitu i=0;i<128*8;i++) { + phys_writeb(PhysMake(0xf000,0xfa6e)+i,int10_font_08[i]); + } + } + + /* we allow dosbox-x.conf to specify a binary blob to load into ROM BIOS and execute after reset. + * we allow this for both hacker curiosity and automated CPU testing. */ + { + std::string path = section->Get_string("call binary on reset"); + struct stat st; + + if (!path.empty() && stat(path.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size <= (off_t)(128u*1024u)) { + Bitu base = ROMBIOS_GetMemory((Bitu)st.st_size,"User reset vector binary",16u/*page align*/,0u); + + if (base != 0) { + FILE *fp = fopen(path.c_str(),"rb"); + + if (fp != NULL) { + /* NTS: Make sure memory base != NULL, and that it fits within 1MB. + * memory code allocates a minimum 1MB of memory even if + * guest memory is less than 1MB because ROM BIOS emulation + * depends on it. */ + assert(GetMemBase() != NULL); + assert((base+(Bitu)st.st_size) <= 0x100000ul); + size_t readResult = fread(GetMemBase()+base,(size_t)st.st_size,1u,fp); + fclose(fp); + if (readResult != 1) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in ROMBIOS_Init\n"); + return; + } + + LOG_MSG("User reset vector binary '%s' loaded at 0x%lx",path.c_str(),(unsigned long)base); + bios_user_reset_vector_blob = base; + } + else { + LOG_MSG("WARNING: Unable to open file to load user reset vector binary '%s' into ROM BIOS memory",path.c_str()); + } + } + else { + LOG_MSG("WARNING: Unable to load user reset vector binary '%s' into ROM BIOS memory",path.c_str()); + } + } + } + + /* we allow dosbox-x.conf to specify a binary blob to load into ROM BIOS and execute just before boot. + * we allow this for both hacker curiosity and automated CPU testing. */ + { + std::string path = section->Get_string("call binary on boot"); + struct stat st; + + if (!path.empty() && stat(path.c_str(),&st) == 0 && S_ISREG(st.st_mode) && st.st_size <= (off_t)(128u*1024u)) { + Bitu base = ROMBIOS_GetMemory((Bitu)st.st_size,"User boot hook binary",16u/*page align*/,0u); + + if (base != 0) { + FILE *fp = fopen(path.c_str(),"rb"); + + if (fp != NULL) { + /* NTS: Make sure memory base != NULL, and that it fits within 1MB. + * memory code allocates a minimum 1MB of memory even if + * guest memory is less than 1MB because ROM BIOS emulation + * depends on it. */ + assert(GetMemBase() != NULL); + assert((base+(Bitu)st.st_size) <= 0x100000ul); + size_t readResult = fread(GetMemBase()+base,(size_t)st.st_size,1u,fp); + fclose(fp); + if (readResult != 1) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in ROMBIOS_Init\n"); + return; + } + + LOG_MSG("User boot hook binary '%s' loaded at 0x%lx",path.c_str(),(unsigned long)base); + bios_user_boot_hook = base; + } + else { + LOG_MSG("WARNING: Unable to open file to load user boot hook binary '%s' into ROM BIOS memory",path.c_str()); + } + } + else { + LOG_MSG("WARNING: Unable to load user boot hook binary '%s' into ROM BIOS memory",path.c_str()); + } + } + } + // J-3100's DOS reads 8x16 font data directly from F000:CA00. + if(IS_J3100) { + ROMBIOS_GetMemory(256*16, "J-3100 8x16 font data", 1, 0xf0000 + j3_font_offset); + } +} + +//! \brief Updates the state of a lockable key. +void UpdateKeyWithLed(int nVirtKey, int flagAct, int flagLed); bool IsSafeToMemIOOnBehalfOfGuest() { @@ -12787,60 +12789,60 @@ bool IsSafeToMemIOOnBehalfOfGuest() if(dos_kernel_disabled) return false; // guest OS not running under our own DOS kernel: NO return true; } - -void BIOS_SynchronizeNumLock() -{ -#if defined(WIN32) - UpdateKeyWithLed(VK_NUMLOCK, BIOS_KEYBOARD_FLAGS1_NUMLOCK_ACTIVE, BIOS_KEYBOARD_LEDS_NUM_LOCK); -#endif -} - -void BIOS_SynchronizeCapsLock() -{ -#if defined(WIN32) - UpdateKeyWithLed(VK_CAPITAL, BIOS_KEYBOARD_FLAGS1_CAPS_LOCK_ACTIVE, BIOS_KEYBOARD_LEDS_CAPS_LOCK); -#endif -} - -void BIOS_SynchronizeScrollLock() -{ -#if defined(WIN32) - UpdateKeyWithLed(VK_SCROLL, BIOS_KEYBOARD_FLAGS1_SCROLL_LOCK_ACTIVE, BIOS_KEYBOARD_LEDS_SCROLL_LOCK); -#endif -} - -void UpdateKeyWithLed(int nVirtKey, int flagAct, int flagLed) -{ -#if defined(WIN32) - - const auto state = GetKeyState(nVirtKey); - - const auto flags1 = BIOS_KEYBOARD_FLAGS1; - const auto flags2 = BIOS_KEYBOARD_LEDS; - - auto flag1 = mem_readb(flags1); - auto flag2 = mem_readb(flags2); - - if (state & 1) - { - flag1 |= flagAct; - flag2 |= flagLed; - } - else - { - flag1 &= ~flagAct; - flag2 &= ~flagLed; - } - - mem_writeb(flags1, flag1); - mem_writeb(flags2, flag2); - -#else - - (void)nVirtKey; - (void)flagAct; - (void)flagLed; - -#endif -} + +void BIOS_SynchronizeNumLock() +{ +#if defined(WIN32) + UpdateKeyWithLed(VK_NUMLOCK, BIOS_KEYBOARD_FLAGS1_NUMLOCK_ACTIVE, BIOS_KEYBOARD_LEDS_NUM_LOCK); +#endif +} + +void BIOS_SynchronizeCapsLock() +{ +#if defined(WIN32) + UpdateKeyWithLed(VK_CAPITAL, BIOS_KEYBOARD_FLAGS1_CAPS_LOCK_ACTIVE, BIOS_KEYBOARD_LEDS_CAPS_LOCK); +#endif +} + +void BIOS_SynchronizeScrollLock() +{ +#if defined(WIN32) + UpdateKeyWithLed(VK_SCROLL, BIOS_KEYBOARD_FLAGS1_SCROLL_LOCK_ACTIVE, BIOS_KEYBOARD_LEDS_SCROLL_LOCK); +#endif +} + +void UpdateKeyWithLed(int nVirtKey, int flagAct, int flagLed) +{ +#if defined(WIN32) + + const auto state = GetKeyState(nVirtKey); + + const auto flags1 = BIOS_KEYBOARD_FLAGS1; + const auto flags2 = BIOS_KEYBOARD_LEDS; + + auto flag1 = mem_readb(flags1); + auto flag2 = mem_readb(flags2); + + if (state & 1) + { + flag1 |= flagAct; + flag2 |= flagLed; + } + else + { + flag1 &= ~flagAct; + flag2 &= ~flagLed; + } + + mem_writeb(flags1, flag1); + mem_writeb(flags2, flag2); + +#else + + (void)nVirtKey; + (void)flagAct; + (void)flagLed; + +#endif +} diff --git a/src/ints/bios_disk.cpp b/src/ints/bios_disk.cpp index a087e6b921e..3b2a6cfb336 100644 --- a/src/ints/bios_disk.cpp +++ b/src/ints/bios_disk.cpp @@ -1,3961 +1,4313 @@ -/* - * Copyright (C) 2002-2021 The DOSBox Team - * - * 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 2 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, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include -#include - -#include "dosbox.h" -#include "callback.h" -#include "bios.h" -#include "bios_disk.h" -#include "timer.h" -#include "regs.h" -#include "mem.h" -#include "dos_inc.h" /* for Drives[] */ -#include "../dos/drives.h" -#include "mapper.h" -#include "ide.h" -#include "cpu.h" - -#if defined(_MSC_VER) -# pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ -#endif - -extern unsigned long freec; -extern const uint8_t freedos_mbr[]; -extern int bootdrive, tryconvertcp; -extern bool int13_disk_change_detect_enable, skipintprog, rsize; -extern bool int13_extensions_enable, bootguest, bootvm, use_quick_reboot; -bool isDBCSCP(), isKanji1_gbk(uint8_t chr), shiftjis_lead_byte(int c), CheckDBCSCP(int32_t codepage); -extern bool CodePageGuestToHostUTF16(uint16_t *d/*CROSS_LEN*/,const char *s/*CROSS_LEN*/); - -#define STATIC_ASSERTM(A,B) static_assertion_##A##_##B -#define STATIC_ASSERTN(A,B) STATIC_ASSERTM(A,B) -#define STATIC_ASSERT(cond) typedef char STATIC_ASSERTN(__LINE__,__COUNTER__)[(cond)?1:-1] - -uint32_t DriveCalculateCRC32(const uint8_t *ptr, size_t len, uint32_t crc) -{ - // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ - static const uint32_t s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; - uint32_t crcu32 = ~crc; - while (len--) { uint8_t b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } - return ~crcu32; -} - -bool DriveFileIterator(DOS_Drive* drv, void(*func)(const char* path, bool is_dir, uint32_t size, uint16_t date, uint16_t time, uint8_t attr, Bitu data), Bitu data, int timeout) -{ - if (!drv) return true; - uint32_t starttick = GetTicks(); - struct Iter - { - static bool ParseDir(DOS_Drive* drv, uint32_t startticks, const std::string& dir, std::vector& dirs, void(*func)(const char* path, bool is_dir, uint32_t size, uint16_t date, uint16_t time, uint8_t attr, Bitu data), Bitu data, uint32_t timeout) - { - size_t dirlen = dir.length(); - if (dirlen + DOS_NAMELENGTH >= DOS_PATHLENGTH) return true; - char full_path[DOS_PATHLENGTH+4]; - if (dirlen) - { - memcpy(full_path, &dir[0], dirlen); - full_path[dirlen++] = '\\'; - } - full_path[dirlen] = '\0'; - - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - dta.SetupSearch(255, (uint8_t)(0xffff & ~DOS_ATTR_VOLUME), (char*)"*.*"); - for (bool more = drv->FindFirst((char*)dir.c_str(), dta); more; more = drv->FindNext(dta)) - { - if (startticks && timeout > 0 && GetTicks()-startticks > timeout * 1000) { - LOG_MSG("Timeout iterating directories"); - dos.dta(save_dta); - return false; - } - char dta_name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH+1]; uint32_t dta_size, dta_hsize; uint16_t dta_date, dta_time; uint8_t dta_attr; - dta.GetResult(dta_name, lname, dta_size, dta_hsize, dta_date, dta_time, dta_attr); - strcpy(full_path + dirlen, dta_name); - bool is_dir = !!(dta_attr & DOS_ATTR_DIRECTORY); - //if (is_dir) printf("[%s] [%s] %s (size: %u - date: %u - time: %u - attr: %u)\n", (const char*)data, (dta_attr == 8 ? "V" : (is_dir ? "D" : "F")), full_path, dta_size, dta_date, dta_time, dta_attr); - if (dta_name[0] == '.' && dta_name[dta_name[1] == '.' ? 2 : 1] == '\0') continue; - if (is_dir) dirs.emplace_back(full_path); - func(full_path, is_dir, dta_size, dta_date, dta_time, dta_attr, data); - } - dos.dta(save_dta); - return true; - } - }; - std::vector dirs; - dirs.emplace_back(""); - std::string dir; - while (dirs.size()) - { - std::swap(dirs.back(), dir); - dirs.pop_back(); - if (!Iter::ParseDir(drv, starttick, dir.c_str(), dirs, func, data, timeout)) return false; - } - return true; -} - -template struct StringToPointerHashMap -{ - StringToPointerHashMap() : len(0), maxlen(0), keys(NULL), vals(NULL) { } - ~StringToPointerHashMap() { free(keys); free(vals); } - - static uint32_t Hash(const char* str, uint32_t str_limit = 0xFFFF, uint32_t hash_init = (uint32_t)0x811c9dc5) - { - for (const char* e = str + str_limit; *str && str != e;) - hash_init = ((hash_init * (uint32_t)0x01000193) ^ (uint32_t)*(str++)); - return hash_init; - } - - TVal* Get(const char* str, uint32_t str_limit = 0xFFFF, uint32_t hash_init = (uint32_t)0x811c9dc5) const - { - if (len == 0) return NULL; - for (uint32_t key0 = Hash(str, str_limit, hash_init), key = (key0 ? key0 : 1), i = key;; i++) - { - if (keys[i &= maxlen] == key) return vals[i]; - if (!keys[i]) return NULL; - } - } - - void Put(const char* str, TVal* val, uint32_t str_limit = 0xFFFF, uint32_t hash_init = (uint32_t)0x811c9dc5) - { - if (len * 2 >= maxlen) Grow(); - for (uint32_t key0 = Hash(str, str_limit, hash_init), key = (key0 ? key0 : 1), i = key;; i++) - { - if (!keys[i &= maxlen]) { len++; keys[i] = key; vals[i] = val; return; } - if (keys[i] == key) { vals[i] = val; return; } - } - } - - bool Remove(const char* str, uint32_t str_limit = 0xFFFF, uint32_t hash_init = (uint32_t)0x811c9dc5) - { - if (len == 0) return false; - for (uint32_t key0 = Hash(str, str_limit, hash_init), key = (key0 ? key0 : 1), i = key;; i++) - { - if (keys[i &= maxlen] == key) - { - keys[i] = 0; - len--; - while ((key = keys[i = (i + 1) & maxlen]) != 0) - { - for (uint32_t j = key;; j++) - { - if (keys[j &= maxlen] == key) break; - if (!keys[j]) { keys[i] = 0; keys[j] = key; vals[j] = vals[i]; break; } - } - } - return true; - } - if (!keys[i]) return false; - } - } - - void Clear() { memset(keys, len = 0, (maxlen + 1) * sizeof(uint32_t)); } - - uint32_t Len() const { return len; } - uint32_t Capacity() const { return (maxlen ? maxlen + 1 : 0); } - TVal* GetAtIndex(uint32_t idx) const { return (keys[idx] ? vals[idx] : NULL); } - - struct Iterator - { - Iterator(StringToPointerHashMap& _map, uint32_t _index) : map(_map), index(_index - 1) { this->operator++(); } - StringToPointerHashMap& map; - uint32_t index; - TVal* operator *() const { return map.vals[index]; } - bool operator ==(const Iterator &other) const { return index == other.index; } - bool operator !=(const Iterator &other) const { return index != other.index; } - Iterator& operator ++() - { - if (!map.maxlen) { index = 0; return *this; } - if (++index > map.maxlen) index = map.maxlen + 1; - while (index <= map.maxlen && !map.keys[index]) index++; - return *this; - } - }; - - Iterator begin() { return Iterator(*this, 0); } - Iterator end() { return Iterator(*this, (maxlen ? maxlen + 1 : 0)); } - -private: - uint32_t len, maxlen, *keys; - TVal** vals; - - void Grow() - { - uint32_t oldMax = maxlen, oldCap = (maxlen ? oldMax + 1 : 0), *oldKeys = keys; - TVal **oldVals = vals; - maxlen = (maxlen ? maxlen * 2 + 1 : 15); - keys = (uint32_t*)calloc(maxlen + 1, sizeof(uint32_t)); - vals = (TVal**)malloc((maxlen + 1) * sizeof(TVal*)); - for (uint32_t i = 0; i != oldCap; i++) - { - if (!oldKeys[i]) continue; - for (uint32_t key = oldKeys[i], j = key;; j++) - { - if (!keys[j &= maxlen]) { keys[j] = key; vals[j] = oldVals[i]; break; } - } - } - free(oldKeys); - free(oldVals); - } - - // not copyable - StringToPointerHashMap(const StringToPointerHashMap&); - StringToPointerHashMap& operator=(const StringToPointerHashMap&); -}; - -#ifdef _MSC_VER -#pragma pack (1) -#endif -struct sector { - uint8_t content[512]; -} GCC_ATTRIBUTE(packed); - -typedef struct { - uint8_t sectors; - uint8_t surfaces; - uint16_t cylinders; -} SASIHDD; - -struct bootstrap { - uint8_t nearjmp[3]; - uint8_t oemname[8]; - uint8_t bytespersector[2]; - uint8_t sectorspercluster; - uint16_t reservedsectors; - uint8_t fatcopies; - uint16_t rootdirentries; - uint16_t totalsectorcount; - uint8_t mediadescriptor; - uint16_t sectorsperfat; - uint16_t sectorspertrack; - uint16_t headcount; - uint32_t hiddensectorcount; - uint32_t totalsecdword; - uint8_t bootcode[474]; - uint8_t magic1; /* 0x55 */ - uint8_t magic2; /* 0xaa */ -} GCC_ATTRIBUTE(packed); - -struct lfndirentry { - uint8_t ord; - uint8_t name1[10]; - uint8_t attrib; - uint8_t type; - uint8_t chksum; - uint8_t name2[12]; - uint16_t loFirstClust; - uint8_t name3[4]; - char* Name(int j) { return (char*)(j < 5 ? name1 + j*2 : j < 11 ? name2 + (j-5)*2 : name3 + (j-11)*2); } -} GCC_ATTRIBUTE(packed); -#ifdef _MSC_VER -#pragma pack () -#endif - -/* .HDI and .FDI header (NP2) */ -#pragma pack(push,1) -typedef struct { - uint8_t dummy[4]; // +0x00 - uint8_t hddtype[4]; // +0x04 - uint8_t headersize[4]; // +0x08 - uint8_t hddsize[4]; // +0x0C - uint8_t sectorsize[4]; // +0x10 - uint8_t sectors[4]; // +0x14 - uint8_t surfaces[4]; // +0x18 - uint8_t cylinders[4]; // +0x1C -} HDIHDR; // =0x20 - -typedef struct { - uint8_t dummy[4]; // +0x00 - uint8_t fddtype[4]; // +0x04 - uint8_t headersize[4]; // +0x08 - uint8_t fddsize[4]; // +0x0C - uint8_t sectorsize[4]; // +0x10 - uint8_t sectors[4]; // +0x14 - uint8_t surfaces[4]; // +0x18 - uint8_t cylinders[4]; // +0x1C -} FDIHDR; // =0x20 - -typedef struct { - char sig[16]; // +0x000 - char comment[0x100]; // +0x010 - UINT8 headersize[4]; // +0x110 - uint8_t prot; // +0x114 - uint8_t nhead; // +0x115 - uint8_t _unknown_[10]; // +0x116 -} NFDHDR; // =0x120 - -typedef struct { - char sig[16]; // +0x000 - char comment[0x100]; // +0x010 - UINT8 headersize[4]; // +0x110 - uint8_t prot; // +0x114 - uint8_t nhead; // +0x115 - uint8_t _unknown_[10]; // +0x116 - uint32_t trackheads[164]; // +0x120 - uint32_t addinfo; // +0x3b0 - uint8_t _unknown2_[12]; // +0x3b4 -} NFDHDRR1; // =0x3c0 - -typedef struct { - uint8_t log_cyl; // +0x0 - uint8_t log_head; // +0x1 - uint8_t log_rec; // +0x2 - uint8_t sec_len_pow2; // +0x3 sz = 128 << len_pow2 - uint8_t flMFM; // +0x4 - uint8_t flDDAM; // +0x5 - uint8_t byStatus; // +0x6 - uint8_t bySTS0; // +0x7 - uint8_t bySTS1; // +0x8 - uint8_t bySTS2; // +0x9 - uint8_t byRetry; // +0xA - uint8_t byPDA; // +0xB - uint8_t _unknown_[4]; // +0xC -} NFDHDR_ENTRY; // =0x10 - -typedef struct { - char szFileID[15]; // 識別ID "T98HDDIMAGE.R0" - char Reserve1[1]; // 予約 - char szComment[0x100]; // イメージコメント(ASCIIz) - uint32_t dwHeadSize; // ヘッダ部のサイズ - uint32_t dwCylinder; // シリンダ数 - uint16_t wHead; // ヘッド数 - uint16_t wSect; // 1トラックあたりのセクタ数 - uint16_t wSectLen; // セクタ長 - char Reserve2[2]; // 予約 - char Reserve3[0xe0]; // 予約 -}NHD_FILE_HEAD,*LP_NHD_FILE_HEAD; -#pragma pack(pop) - -#define STOREINTELDWORD(a, b) *((a)+0) = (uint8_t)((b)); *((a)+1) = (uint8_t)((b)>>8); *((a)+2) = (uint8_t)((b)>>16); *((a)+3) = (uint8_t)((b)>>24) - -STATIC_ASSERT(sizeof(direntry) == sizeof(lfndirentry)); -enum -{ - DOS_ATTR_LONG_NAME = (DOS_ATTR_READ_ONLY | DOS_ATTR_HIDDEN | DOS_ATTR_SYSTEM | DOS_ATTR_VOLUME), - DOS_ATTR_LONG_NAME_MASK = (DOS_ATTR_READ_ONLY | DOS_ATTR_HIDDEN | DOS_ATTR_SYSTEM | DOS_ATTR_VOLUME | DOS_ATTR_DIRECTORY | DOS_ATTR_ARCHIVE), - DOS_ATTR_PENDING_SHORT_NAME = 0x80, -}; - -static const uint8_t hdddiskboot[] = { - 0xeb,0x0a,0x90,0x90,0x49,0x50,0x4c,0x31,0x00,0x00,0x00,0x1e, - 0xb8,0x04,0x0a,0xcd,0x18,0xb4,0x16,0xba,0x20,0xe1,0xcd,0x18, - 0xfa,0xfc,0xb8,0x00,0xa0,0x8e,0xc0,0xbe,0x3c,0x00,0x31,0xff, - 0xe8,0x09,0x00,0xbf,0xa0,0x00,0xe8,0x03,0x00,0xf4,0xeb,0xfd, - 0x2e,0xad,0x85,0xc0,0x74,0x05,0xab,0x47,0x47,0xeb,0xf5,0xc3, - 0x04,0x33,0x04,0x4e,0x05,0x4f,0x01,0x3c,0x05,0x49,0x05,0x47, - 0x05,0x23,0x05,0x39,0x05,0x2f,0x05,0x24,0x05,0x61,0x01,0x3c, - 0x05,0x38,0x04,0x4f,0x05,0x55,0x05,0x29,0x01,0x3c,0x05,0x5e, - 0x05,0x43,0x05,0x48,0x04,0x35,0x04,0x6c,0x04,0x46,0x04,0x24, - 0x04,0x5e,0x04,0x3b,0x04,0x73,0x01,0x25,0x00,0x00,0x05,0x47, - 0x05,0x23,0x05,0x39,0x05,0x2f,0x05,0x24,0x05,0x61,0x01,0x3c, - 0x05,0x38,0x04,0x72,0x21,0x5e,0x26,0x7e,0x18,0x65,0x01,0x24, - 0x05,0x6a,0x05,0x3b,0x05,0x43,0x05,0x48,0x04,0x37,0x04,0x46, - 0x12,0x3c,0x04,0x35,0x04,0x24,0x01,0x25,0x00,0x00, -}; - -struct fatFromDOSDrive -{ - DOS_Drive* drive; - - enum ffddDefs : uint32_t - { - BYTESPERSECTOR = 512, - HEADCOUNT = 255, // needs to be >128 to fit 4GB into CHS - SECTORSPERTRACK = 63, - SECT_MBR = 0, - SECT_BOOT = 32, - CACHECOUNT = 256, - KEEPOPENCOUNT = 8, - NULL_CURSOR = (uint32_t)-1, - }; - - partTable mbr; - bootstrap bootsec; - sector header; - sector ipl; - sector pt; - SASIHDD sasi; - uint8_t fatSz; - uint8_t fsinfosec[BYTESPERSECTOR]; - uint32_t sectorsPerCluster, codepage = 0; - bool tryconvcp = false, readOnly = false, success = false, tomany = false; - - struct ffddFile { char path[DOS_PATHLENGTH+1]; uint32_t firstSect; }; - std::vector root, dirs; - std::vector files; - std::vector fileAtSector; - std::vector fat; - uint32_t sect_boot_pc98, sect_disk_end, sect_files_end, sect_files_start, sect_dirs_start, sect_root_start, sect_fat2_start, sect_fat1_start; - - struct ffddBuf { uint8_t data[BYTESPERSECTOR]; }; - struct ffddSec { uint32_t cursor = NULL_CURSOR; }; - std::vector diffSectorBufs; - std::vector diffSectors; - std::vector diffFreeCursors; - uint32_t saveEndCursor = 0; - uint8_t cacheSectorData[CACHECOUNT][BYTESPERSECTOR]; - uint32_t cacheSectorNumber[CACHECOUNT]; - DOS_File* openFiles[KEEPOPENCOUNT]; - uint32_t openIndex[KEEPOPENCOUNT]; - uint32_t openCursor = 0; - - ~fatFromDOSDrive() - { - for (DOS_File* df : openFiles) - if (df) { df->Close(); delete df; } - } - - fatFromDOSDrive(DOS_Drive* drv, uint32_t freeMB, int timeout) : drive(drv) - { - cacheSectorNumber[0] = 1; // must not state that sector 0 is already cached - memset(&cacheSectorNumber[1], 0, sizeof(cacheSectorNumber) - sizeof(cacheSectorNumber[0])); - memset(openFiles, 0, sizeof(openFiles)); - - struct Iter - { - static void SetFAT(fatFromDOSDrive& ffdd, size_t idx, uint32_t val) - { - while (idx >= (uint64_t)ffdd.fat.size() * 8 / ffdd.fatSz) - { - // FAT12 table grows in steps of 3 sectors otherwise the table doesn't align - size_t addSz = (ffdd.fatSz != 12 ? BYTESPERSECTOR : (BYTESPERSECTOR * 3)); - ffdd.fat.resize(ffdd.fat.size() + addSz); - memset(&ffdd.fat[ffdd.fat.size() - addSz], 0, addSz); - } - if (ffdd.fatSz == 32) // FAT32 - var_write((uint32_t *)&ffdd.fat[idx * 4], val); - else if (ffdd.fatSz == 16) // FAT 16 - var_write((uint16_t *)&ffdd.fat[idx * 2], (uint16_t)val); - else if (idx & 1) // FAT12 odd cluster - var_write((uint16_t *)&ffdd.fat[idx + idx / 2], (uint16_t)((var_read((uint16_t *)&ffdd.fat[idx + idx / 2]) & 0xF) | ((val & 0xFFF) << 4))); - else // FAT12 even cluster - var_write((uint16_t *)&ffdd.fat[idx + idx / 2], (uint16_t)((var_read((uint16_t *)&ffdd.fat[idx + idx / 2]) & 0xF000) | (val & 0xFFF))); - } - - static direntry* AddDirEntry(fatFromDOSDrive& ffdd, bool useFAT16Root, size_t& diridx) - { - const uint32_t entriesPerCluster = ffdd.sectorsPerCluster * BYTESPERSECTOR / sizeof(direntry); - if (!useFAT16Root && (diridx % entriesPerCluster) == 0) - { - // link fat (was set to 0xFFFF before but now we knew the chain continues) - if (diridx) SetFAT(ffdd, 2 + (diridx - 1) / entriesPerCluster, (uint32_t)(2 + ffdd.dirs.size() / entriesPerCluster)); - diridx = ffdd.dirs.size(); - ffdd.dirs.resize(diridx + entriesPerCluster); - memset(&ffdd.dirs[diridx], 0, sizeof(direntry) * entriesPerCluster); - SetFAT(ffdd, 2 + diridx / entriesPerCluster, (uint32_t)0xFFFFFFFF); // set as last cluster in chain for now - } - else if (useFAT16Root && diridx && (diridx % 512) == 0) - { - // this actually should never be larger than 512 for some FAT16 drivers - ffdd.root.resize(diridx + 512); - memset(&ffdd.root[diridx], 0, sizeof(direntry) * 512); - } - return &(!useFAT16Root ? ffdd.dirs : ffdd.root)[diridx++]; - } - - static void ParseDir(fatFromDOSDrive& ffdd, char* dir, const StringToPointerHashMap* filter, int dirlen = 0, uint16_t parentFirstCluster = 0) - { - if (ffdd.tomany) return; - const bool useFAT16Root = (!dirlen && ffdd.fatSz != 32), readOnly = ffdd.readOnly; - const size_t firstidx = (!useFAT16Root ? ffdd.dirs.size() : 0); - const uint32_t sectorsPerCluster = ffdd.sectorsPerCluster, bytesPerCluster = sectorsPerCluster * BYTESPERSECTOR, entriesPerCluster = bytesPerCluster / sizeof(direntry); - const uint16_t myFirstCluster = (dirlen ? (uint16_t)(2 + firstidx / entriesPerCluster) : (uint16_t)0) ; - - char finddir[DOS_PATHLENGTH+4]; - memcpy(finddir, dir, dirlen); // because FindFirst can modify this... - finddir[dirlen] = '\0'; - if (dirlen) dir[dirlen++] = '\\'; - - size_t diridx = 0; - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - dta.SetupSearch(255, 0xFF, (char*)"*.*"); - skipintprog = true; - for (bool more = ffdd.drive->FindFirst(finddir, dta); more; more = ffdd.drive->FindNext(dta)) - { - char dta_name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH+1]; uint32_t dta_size, dta_hsize; uint16_t dta_date, dta_time; uint8_t dta_attr; - dta.GetResult(dta_name, lname, dta_size, dta_hsize, dta_date, dta_time, dta_attr); - //LOG_MSG("dta_name %s lname %s\n", dta_name, lname); - const char *fend = dta_name + strlen(dta_name); - const bool dot = (dta_name[0] == '.' && dta_name[1] == '\0'), dotdot = (dta_name[0] == '.' && dta_name[1] == '.' && dta_name[2] == '\0'); - if (!dirlen && (dot || dotdot)) continue; // root shouldn't have dot entries (yet localDrive does...) - - ffddFile f; - memcpy(f.path, dir, dirlen); - memcpy(f.path + dirlen, dta_name, fend - dta_name + 1); - if (filter && filter->Get(f.path, sizeof(f.path))) continue; - - const bool isLongFileName = (!dot && !dotdot && !(dta_attr & DOS_ATTR_VOLUME)); - if (isLongFileName) - { - bool lead = false; - size_t len = 0, lfnlen = strlen(lname); - uint16_t *lfnw = (uint16_t *)malloc((lfnlen + 1) * sizeof(uint16_t)); - if (lfnw == NULL) continue; - char text[3]; - uint16_t uname[4]; -#if defined(WIN32) - uint16_t cp = GetACP(), cpbak = dos.loaded_codepage; - if (tryconvertcp && cpbak == 437 && CheckDBCSCP(cp)) - dos.loaded_codepage = cp; -#endif - for (size_t i=0; i < lfnlen; i++) { - if (lead) { - lead = false; - text[0]=lname[i-1]&0xFF; - text[1]=lname[i]&0xFF; - text[2]=0; - uname[0]=0; - uname[1]=0; - if (CodePageGuestToHostUTF16(uname,text)&&uname[0]!=0&&uname[1]==0) - lfnw[len++] = uname[0]; - else { - lfnw[len++] = lname[i-1]; - lfnw[len++] = lname[i]; - } - } else if (i+1ord = (uint8_t)((lfnblocks - i)|(i == 0 ? 0x40 : 0x0)); - le->attrib = DOS_ATTR_LONG_NAME; - le->type = 0; - le->loFirstClust = 0; - uint16_t* plfn = lfnw + (lfnblocks - i - 1) * 13; - for (int j = 0; j != 13; j++, plfn++) - { - char* p = le->Name(j); - if (plfn > lfn_end) - p[0] = p[1] = (char)0xFF; - else if (plfn == lfn_end) - p[0] = p[1] = 0; - else if (*plfn > 0xFF) { - p[0] = (uint8_t)(*plfn%0x100); - p[1] = (uint8_t)(*plfn/0x100); - } else { - p[0] = *plfn; - p[1] = 0; - } - } - } - free(lfnw); - } - - const char *fext = (dot || dotdot ? NULL : strrchr(dta_name, '.')); - direntry* e = AddDirEntry(ffdd, useFAT16Root, diridx); - memset(e->entryname, ' ', sizeof(e->entryname)); - memcpy(e->entryname, dta_name, (fext ? fext : fend) - dta_name); - if (fext++) memcpy(e->entryname + 8, fext, fend - fext); - - e->attrib = dta_attr | (readOnly ? DOS_ATTR_READ_ONLY : 0) | (isLongFileName ? DOS_ATTR_PENDING_SHORT_NAME : 0); - if (dos.version.major >= 7) { - var_write(&e->crtTime, dta_time); // create date/time is DOS 7.0 and up only - var_write(&e->crtDate, dta_date); // create date/time is DOS 7.0 and up only - } - var_write(&e->accessDate, dta_date); - var_write(&e->modTime, dta_time); - var_write(&e->modDate, dta_date); - - if (dot) - { - e->attrib |= DOS_ATTR_DIRECTORY; // make sure - var_write(&e->loFirstClust, myFirstCluster); - } - else if (dotdot) - { - e->attrib |= DOS_ATTR_DIRECTORY; // make sure - var_write(&e->loFirstClust, parentFirstCluster); - } - else if (dta_attr & DOS_ATTR_VOLUME) - { - if (dirlen || (e->attrib & DOS_ATTR_DIRECTORY) || dta_size) - LOG_MSG("Invalid volume entry - %s\n", e->entryname); - } - else if (!(dta_attr & DOS_ATTR_DIRECTORY)) - { - var_write(&e->entrysize, dta_size); - - uint32_t fileIdx = (uint32_t)ffdd.files.size(); - ffdd.files.push_back(f); - - uint32_t numSects = (dta_size + bytesPerCluster - 1) / bytesPerCluster * sectorsPerCluster; - try { - ffdd.fileAtSector.resize(ffdd.fileAtSector.size() + numSects, fileIdx); - } catch (...) { - LOG_MSG("Too many sectors needed, will discard remaining files (from %s)", lname); - ffdd.tomany = ffdd.readOnly = true; - var_write((uint32_t *)&ffdd.fsinfosec[488], (uint32_t)0x0); - break; - } - } - } - skipintprog = false; - dos.dta(save_dta); - if (dirlen && diridx < firstidx + 2) { - LOG_MSG("Directory need at least . and .. entries - %s\n", finddir); - return; - } - - // Now fill out the subdirectories (can't be done above because only one dos.dta can run simultaneously - std::vector& entries = (!useFAT16Root ? ffdd.dirs : ffdd.root); - for (size_t ei = firstidx; ei != diridx; ei++) - { - direntry& e = entries[ei]; - uint8_t* entryname = e.entryname; - int totlen = dirlen; - if (e.attrib & DOS_ATTR_DIRECTORY) // copy name before modifying SFN - { - if (entryname[0] == '.' && entryname[entryname[1] == '.' ? 2 : 1] == ' ') continue; - for (int i = 0; i != 8 && entryname[i] != ' '; i++) dir[totlen++] = entryname[i]; - if (entryname[8] != ' ') dir[totlen++] = '.'; - for (int i = 8; i != 11 && entryname[i] != ' '; i++) dir[totlen++] = entryname[i]; - } - if (e.attrib & DOS_ATTR_PENDING_SHORT_NAME) // convert LFN to SFN - { - uint8_t chksum = 0; - for (int i = 0; i != 11;) chksum = (chksum >> 1) + (chksum << 7) + e.entryname[i++]; - for (lfndirentry* le = (lfndirentry*)&e; le-- == (lfndirentry*)&e || !(le[1].ord & 0x40);) le->chksum = chksum; - e.attrib &= ~DOS_ATTR_PENDING_SHORT_NAME; - } - if (e.attrib & DOS_ATTR_DIRECTORY) // this reallocates ffdd.dirs so do this last - { - var_write(&e.loFirstClust, (uint16_t)(2 + ffdd.dirs.size() / entriesPerCluster)); - ParseDir(ffdd, dir, filter, totlen, myFirstCluster); - } - } - } - - struct SumInfo { uint64_t used_bytes; const StringToPointerHashMap* filter; }; - static void SumFileSize(const char* path, bool /*is_dir*/, uint32_t size, uint16_t, uint16_t, uint8_t, Bitu data) - { - if (!((SumInfo*)data)->filter || !((SumInfo*)data)->filter->Get(path)) - ((SumInfo*)data)->used_bytes += (size + (32*1024-1)) / (32*1024) * (32*1024); // count as 32 kb clusters - } - }; - - drv->EmptyCache(); - Iter::SumInfo sum = { 0, NULL }; - uint64_t freeSpace = 0, freeSpaceMB = 0; - uint32_t free_clusters = 0; - uint16_t drv_bytes_sector; uint8_t drv_sectors_cluster; uint16_t drv_total_clusters, drv_free_clusters; - rsize=true; - freec=0; - drv->AllocationInfo(&drv_bytes_sector, &drv_sectors_cluster, &drv_total_clusters, &drv_free_clusters); - free_clusters = freec?freec:drv_free_clusters; - freeSpace = (uint64_t)drv_bytes_sector * drv_sectors_cluster * (freec?freec:free_clusters); - freeSpaceMB = freeSpace / (1024*1024); - if (freeMB < freeSpaceMB) freeSpaceMB = freeMB; - rsize=false; - tomany=false; - readOnly = free_clusters == 0 || freeSpaceMB == 0; - if (!DriveFileIterator(drv, Iter::SumFileSize, (Bitu)&sum, timeout)) return; - - uint32_t usedMB = sum.used_bytes / (1024*1024), addFreeMB, totalMB, tsizeMB; - uint64_t tsize = 0; - if (IS_PC98_ARCH) { - if (usedMB < 6) { - sasi.sectors = 33; - sasi.surfaces = 4; - sasi.cylinders = 153; - } else if (usedMB < 16) { - sasi.sectors = 33; - sasi.surfaces = 4; - sasi.cylinders = 310; - } else if (usedMB < 26) { - sasi.sectors = 33; - sasi.surfaces = 6; - sasi.cylinders = 310; - } else if (usedMB < 36) { - sasi.sectors = 33; - sasi.surfaces = 8; - sasi.cylinders = 310; - } else { - sasi.sectors = 33; - uint32_t heads = std::ceil((double)(usedMB+(readOnly?0:(usedMB>=2047?freeSpaceMB:5)))/10); - if (heads > 255) { - sasi.surfaces = 255; - sasi.cylinders = heads * 615 / 255; - } else { - sasi.surfaces = heads; - sasi.cylinders = 615; - } - } - tsize = BYTESPERSECTOR * sasi.sectors * sasi.surfaces * sasi.cylinders; - tsizeMB = sasi.sectors * sasi.surfaces * sasi.cylinders / (1024 * 1024 / BYTESPERSECTOR); - if (tsizeMB < usedMB) readOnly = true; - addFreeMB = readOnly ? 0 : (usedMB >= 2047 ? freeSpaceMB : (std::ceil((double)tsize - sum.used_bytes) / (1024 * 1024) + 1)); - } else - addFreeMB = (readOnly ? 0 : freeSpaceMB); - totalMB = usedMB + (addFreeMB ? (1 + addFreeMB) : 0); - if (totalMB >= 3072) { fatSz = 32; sectorsPerCluster = 64; } // 32 kb clusters ( 98304 ~ FAT entries) - else if (totalMB >= 2048) { fatSz = 32; sectorsPerCluster = 32; } // 16 kb clusters (131072 ~ 196608 FAT entries) - else if (totalMB >= 384) { fatSz = 16; sectorsPerCluster = 64; } // 32 kb clusters ( 12288 ~ 65504 FAT entries) - else if (totalMB >= 192) { fatSz = 16; sectorsPerCluster = 32; } // 16 kb clusters ( 12288 ~ 24576 FAT entries) - else if (totalMB >= 96) { fatSz = 16; sectorsPerCluster = 16; } // 8 kb clusters ( 12288 ~ 24576 FAT entries) - else if (totalMB >= 48) { fatSz = 16; sectorsPerCluster = 8; } // 4 kb clusters ( 12288 ~ 24576 FAT entries) - else if (totalMB >= 12) { fatSz = 16; sectorsPerCluster = 4; } // 2 kb clusters ( 6144 ~ 24576 FAT entries) - else if (totalMB >= 4) { fatSz = 16; sectorsPerCluster = 1; } // .5 kb clusters ( 8192 ~ 24576 FAT entries) - else if (totalMB >= 2) { fatSz = 12; sectorsPerCluster = 4; } // 2 kb clusters ( 1024 ~ 2048 FAT entries) - else if (totalMB >= 1) { fatSz = 12; sectorsPerCluster = 2; } // 1 kb clusters ( 1024 ~ 2048 FAT entries) - else { fatSz = 12; sectorsPerCluster = 1; } // .5 kb clusters ( ~ 2048 FAT entries) - - // mediadescriptor in very first byte of FAT table - Iter::SetFAT(*this, 0, (uint32_t)0xFFFFFF8); - Iter::SetFAT(*this, 1, (uint32_t)0xFFFFFFF); - - if (fatSz != 32) - { - // this actually should never be anything but 512 for some FAT16 drivers - root.resize(512); - memset(&root[0], 0, sizeof(direntry) * 512); - } - - char dirbuf[DOS_PATHLENGTH+4]; - Iter::ParseDir(*this, dirbuf, NULL); - - const uint32_t bytesPerCluster = sectorsPerCluster * BYTESPERSECTOR; - const uint32_t entriesPerCluster = bytesPerCluster / sizeof(direntry); - uint32_t fileCluster = (uint32_t)(2 + dirs.size() / entriesPerCluster); - for (uint32_t fileSect = 0, rootOrDir = 0; rootOrDir != 2; rootOrDir++) - { - for (direntry& e : (rootOrDir ? dirs : root)) - { - if (!e.entrysize || (e.attrib & DOS_ATTR_LONG_NAME_MASK) == DOS_ATTR_LONG_NAME) continue; - var_write(&e.hiFirstClust, (uint16_t)(fileCluster >> 16)); - var_write(&e.loFirstClust, (uint16_t)(fileCluster)); - - // Write FAT link chain - uint32_t numClusters = (var_read(&e.entrysize) + bytesPerCluster - 1) / bytesPerCluster; - for (uint32_t i = fileCluster, iEnd = i + numClusters - 1; i != iEnd; i++) Iter::SetFAT(*this, i, i + 1); - Iter::SetFAT(*this, fileCluster + numClusters - 1, (uint32_t)0xFFFFFFF); - - files[fileAtSector[fileSect]].firstSect = fileSect; - - fileCluster += numClusters; - fileSect += numClusters * sectorsPerCluster; - } - } - - if (IS_PC98_ARCH) { - HDIHDR hdi; - memset(&hdi, 0, sizeof(hdi)); - // STOREINTELDWORD(hdi.hddtype, 0); - STOREINTELDWORD(hdi.headersize, 4096); - STOREINTELDWORD(hdi.hddsize, (uint32_t)tsize); - STOREINTELDWORD(hdi.sectorsize, BYTESPERSECTOR); - STOREINTELDWORD(hdi.sectors, sasi.sectors); - STOREINTELDWORD(hdi.surfaces, sasi.surfaces); - STOREINTELDWORD(hdi.cylinders, sasi.cylinders); - memset(&header, 0, sizeof(header)); - memcpy(&header,&hdi,sizeof(hdi)); - memset(&ipl, 0, sizeof(ipl)); - memcpy(&ipl,&hdddiskboot,sizeof(hdddiskboot)); - ipl.content[0xFE] = 0x55; - ipl.content[0xFF] = 0xaa; - ipl.content[0x1FE] = 0x55; - ipl.content[0x1FF] = 0xaa; - struct _PC98RawPartition pe; - memset(&pe, 0, sizeof(pe)); - STOREINTELDWORD(&pe.mid, 0xa0); - STOREINTELDWORD(&pe.sid, 0xa1); - STOREINTELDWORD(&pe.ipl_cyl, 1); - STOREINTELDWORD(&pe.cyl, 1); - STOREINTELDWORD(&pe.end_cyl, sasi.cylinders); - strncpy(pe.name, "MS-DOS ", 16); - memset(&pt, 0, sizeof(pt)); - memcpy(&pt,&pe,sizeof(pe)); - } - - // Add at least one page after the last file or FAT spec minimum to make ScanDisk happy (even on read-only disks) - const uint32_t FATPageClusters = BYTESPERSECTOR * 8 / fatSz, FATMinCluster = (fatSz == 32 ? 65525 : (fatSz == 16 ? 4085 : 0)) + FATPageClusters; - const uint32_t addFreeClusters = ((addFreeMB * (1024*1024/BYTESPERSECTOR)) + sectorsPerCluster - 1) / sectorsPerCluster; - const uint32_t targetClusters = fileCluster + (addFreeClusters < FATPageClusters ? FATPageClusters : addFreeClusters); - Iter::SetFAT(*this, (targetClusters < FATMinCluster ? FATMinCluster : targetClusters) - 1, 0); - const uint32_t totalClusters = (uint32_t)((uint64_t)fat.size() * 8 / fatSz); // as set by Iter::SetFAT - - // on read-only disks, fill up the end of the FAT table with "Bad sector in cluster or reserved cluster" markers - if (readOnly) - for (uint32_t cluster = fileCluster; cluster != totalClusters; cluster++) - Iter::SetFAT(*this, cluster, 0xFFFFFF7); - - const uint32_t sectorsPerFat = (uint32_t)(fat.size() / BYTESPERSECTOR); - const uint16_t reservedSectors = (fatSz == 32 ? 32 : 1); - const uint32_t partSize = totalClusters * sectorsPerCluster + reservedSectors; - - sect_boot_pc98 = sasi.surfaces * sasi.sectors; - sect_fat1_start = (IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT) + reservedSectors; - sect_fat2_start = sect_fat1_start + sectorsPerFat; - sect_root_start = sect_fat2_start + sectorsPerFat; - sect_dirs_start = sect_root_start + ((root.size() * sizeof(direntry) + BYTESPERSECTOR - 1) / BYTESPERSECTOR); - sect_files_start = sect_dirs_start + ((dirs.size() * sizeof(direntry) + BYTESPERSECTOR - 1) / BYTESPERSECTOR); - sect_files_end = sect_files_start + fileAtSector.size(); - sect_disk_end = (IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT) + partSize; - if (IS_PC98_ARCH && tsize/BYTESPERSECTOR-8 > sect_disk_end) sect_disk_end = tsize/BYTESPERSECTOR-8; - if (sect_disk_end < sect_files_end) return; - - for (ffddFile& f : files) - f.firstSect += sect_files_start; - - uint32_t serial = 0; - if (!serial) - { - serial = DriveCalculateCRC32(&fat[0], fat.size(), 0); - if (root.size()) serial = DriveCalculateCRC32((uint8_t*)&root[0], root.size() * sizeof(direntry), serial); - if (dirs.size()) serial = DriveCalculateCRC32((uint8_t*)&dirs[0], dirs.size() * sizeof(direntry), serial); - } - - memset(&mbr, 0, sizeof(mbr)); - //memcpy(&mbr,freedos_mbr,512); - var_write((uint32_t *)&mbr.booter[440], serial); //4 byte disk serial number - var_write(&mbr.pentry[0].bootflag, 0x80); //Active bootable - if ((sect_disk_end - 1) / (HEADCOUNT * SECTORSPERTRACK) > 0x3FF) - { - mbr.pentry[0].beginchs[0] = mbr.pentry[0].beginchs[1] = mbr.pentry[0].beginchs[2] = 0; - mbr.pentry[0].endchs[0] = mbr.pentry[0].endchs[1] = mbr.pentry[0].endchs[2] = 0; - } - else - { - chs_write(mbr.pentry[0].beginchs, IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT); - chs_write(mbr.pentry[0].endchs, sect_disk_end - 1); - } - var_write(&mbr.pentry[0].absSectStart, IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT); - var_write(&mbr.pentry[0].partSize, partSize); - mbr.magic1 = 0x55; mbr.magic2 = 0xaa; - - memset(&bootsec, 0, sizeof(bootsec)); - memcpy(bootsec.nearjmp, "\xEB\x3C\x90", sizeof(bootsec.nearjmp)); - memcpy(bootsec.oemname, fatSz == 32 ? "MSWIN4.1" : "MSDOS5.0", sizeof(bootsec.oemname)); - var_write((uint16_t *)&bootsec.bytespersector, (uint16_t)BYTESPERSECTOR); - var_write(&bootsec.sectorspercluster, sectorsPerCluster); - var_write(&bootsec.reservedsectors, reservedSectors); - var_write(&bootsec.fatcopies, 2); - var_write(&bootsec.totalsectorcount, 0); // 16 bit field is 0, actual value is in totalsecdword - var_write(&bootsec.mediadescriptor, 0xF8); //also in FAT[0] - var_write(&bootsec.sectorspertrack, IS_PC98_ARCH ? sasi.sectors : SECTORSPERTRACK); - var_write(&bootsec.headcount, IS_PC98_ARCH ? sasi.surfaces : HEADCOUNT); - var_write(&bootsec.hiddensectorcount, IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT); - var_write(&bootsec.totalsecdword, partSize); - bootsec.magic1 = 0x55; bootsec.magic2 = 0xaa; - if (fatSz != 32) // FAT12/FAT16 - { - var_write(&mbr.pentry[0].parttype, (fatSz == 12 ? 0x01 : (sect_disk_end < 65536 ? 0x04 : 0x06))); // FAT12/16 - var_write(&bootsec.rootdirentries, (uint16_t)root.size()); - var_write(&bootsec.sectorsperfat, (uint16_t)sectorsPerFat); - bootsec.bootcode[0] = 0x80; //Physical drive (harddisk) flag - bootsec.bootcode[2] = 0x29; //Extended boot signature - var_write((uint32_t *)&bootsec.bootcode[3], serial + 1); //4 byte partition serial number - memcpy(&bootsec.bootcode[7], "NO NAME ", 11); // volume label - memcpy(&bootsec.bootcode[18], "FAT1 ", 8); // file system string name - bootsec.bootcode[22] = (char)('0' + (fatSz % 10)); // '2' or '6' - } - else // FAT32 - { - var_write(&mbr.pentry[0].parttype, 0x0C); //FAT32 - var_write((uint32_t *)&bootsec.bootcode[0], sectorsPerFat); - var_write((uint32_t *)&bootsec.bootcode[8], (uint32_t)2); // First cluster number of the root directory - var_write((uint16_t *)&bootsec.bootcode[12], (uint16_t)1); // Sector of FSInfo structure in offset from top of the FAT32 volume - var_write((uint16_t *)&bootsec.bootcode[14], (uint16_t)6); // Sector of backup boot sector in offset from top of the FAT32 volume - bootsec.bootcode[28] = 0x80; //Physical drive (harddisk) flag - bootsec.bootcode[30] = 0x29; //Extended boot signature - var_write((uint32_t *)&bootsec.bootcode[31], serial + 1); //4 byte partition serial number - memcpy(&bootsec.bootcode[35], "NO NAME ", 11); // volume label - memcpy(&bootsec.bootcode[46], "FAT32 ", 8); // file system string name - - memset(fsinfosec, 0, sizeof(fsinfosec)); - var_write((uint32_t *)&fsinfosec[0], (uint32_t)0x41615252); //lead signature - var_write((uint32_t *)&fsinfosec[484], (uint32_t)0x61417272); //Another signature - bool ver71 = dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10); - //Bitu freeclusters = readOnly ? 0x0 : (ver71 ? (Bitu)freeSpace / (BYTESPERSECTOR * sectorsPerCluster) : 0xFFFFFFFF); - Bitu freeclusters = readOnly ? 0x0 : (ver71 ? (Bitu)((sect_disk_end - sect_files_end) / sectorsPerCluster): 0xFFFFFFFF); - var_write((uint32_t *)&fsinfosec[488], (uint32_t)(freeclusters < 0xFFFFFFFF ? freeclusters : 0xFFFFFFFF)); //last known free cluster count (all FF is unknown) - var_write((uint32_t *)&fsinfosec[492], (ver71 ? (sect_files_end / sectorsPerCluster): 0xFFFFFFFF)); //the cluster number at which the driver should start looking for free clusters (all FF is unknown) - var_write((uint32_t *)&fsinfosec[508], 0xAA550000); //ending signature - } - - codepage = dos.loaded_codepage; - tryconvcp = tryconvertcp>0; - success = true; - } - - static void chs_write(uint8_t* chs, uint32_t lba) - { - uint32_t cylinder = lba / (HEADCOUNT * SECTORSPERTRACK); - uint32_t head = (lba / SECTORSPERTRACK) % HEADCOUNT; - uint32_t sector = (lba % SECTORSPERTRACK) + 1; - if (head > 0xFF || sector > 0x3F || cylinder > 0x3FF) - LOG_MSG("Warning: Invalid CHS data - %X, %X, %X\n", head, sector, cylinder); - chs[0] = (uint8_t)(head & 0xFF); - chs[1] = (uint8_t)((sector & 0x3F) | ((cylinder >> 8) & 0x3)); - chs[2] = (uint8_t)(cylinder & 0xFF); - } - - uint8_t WriteSector(uint32_t sectnum, const void* data) - { - if (sectnum >= sect_disk_end) return 1; - if (sectnum == SECT_MBR) - { - // Windows 9x writes the disk timestamp into the booter area on startup. - // Just copy that part over so it doesn't get treated as a difference that needs to be stored. - memcpy(mbr.booter, data, sizeof(mbr.booter)); - } - - if (readOnly) return 0; // just return without error to avoid bluescreens in Windows 9x - - if (sectnum >= diffSectors.size()) diffSectors.resize(sectnum + 128); - uint32_t *cursor_ptr = &diffSectors[sectnum].cursor, cursor_val = *cursor_ptr; - - int is_different; - uint8_t filebuf[BYTESPERSECTOR]; - void* unmodified = GetUnmodifiedSector(sectnum, filebuf); - if (!unmodified) - { - is_different = false; // to be equal it must be filled with zeroes - for (uint64_t* p = (uint64_t*)data, *pEnd = p + (BYTESPERSECTOR / sizeof(uint64_t)); p != pEnd; p++) - if (*p) { is_different = true; break; } - } - else is_different = memcmp(unmodified, data, BYTESPERSECTOR); - - if (is_different) - { - if (cursor_val == NULL_CURSOR && diffFreeCursors.size()) - { - *cursor_ptr = cursor_val = diffFreeCursors.back(); - diffFreeCursors.pop_back(); - } - if (cursor_val == NULL_CURSOR) - { - *cursor_ptr = cursor_val = (uint32_t)diffSectorBufs.size(); - diffSectorBufs.resize(cursor_val + 1); - } - memcpy(diffSectorBufs[cursor_val].data, data, BYTESPERSECTOR); - cacheSectorNumber[sectnum % CACHECOUNT] = (uint32_t)-1; // invalidate cache - } - else if (cursor_val != NULL_CURSOR) - { - diffFreeCursors.push_back(cursor_val); - *cursor_ptr = NULL_CURSOR; - cacheSectorNumber[sectnum % CACHECOUNT] = (uint32_t)-1; // invalidate cache - } - return 0; - } - - void* GetUnmodifiedSector(uint32_t sectnum, void* filebuf) - { - if (sectnum >= sect_files_end) {} - else if (sectnum >= sect_files_start) - { - uint32_t idx = fileAtSector[sectnum - sect_files_start]; - ffddFile& f = files[idx]; - DOS_File* df = NULL; - for (uint32_t i = 0; i != KEEPOPENCOUNT; i++) - if (openIndex[i] == idx && openFiles[i]) - { df = openFiles[i]; break; } - if (!df) - { - openCursor = (openCursor + 1) % KEEPOPENCOUNT; - DOS_File*& cachedf = openFiles[openCursor]; - if (cachedf) - { - cachedf->Close(); - delete cachedf; - cachedf = NULL; - } - bool res = drive->FileOpen(&df, f.path, OPEN_READ); - if (!res && codepage && (codepage != dos.loaded_codepage || (tryconvcp && codepage == 437))) { - uint32_t cp = dos.loaded_codepage; - dos.loaded_codepage = codepage; -#if defined(WIN32) - if (tryconvcp && dos.loaded_codepage == 437) dos.loaded_codepage = GetACP(); -#endif - res = drive->FileOpen(&df, f.path, OPEN_READ); - dos.loaded_codepage = cp; - } - if (res) - { - df->AddRef(); - cachedf = df; - openIndex[openCursor] = idx; - } - else return NULL; - } - if (df) - { - uint32_t pos = (sectnum - f.firstSect) * BYTESPERSECTOR; - uint16_t read = (uint16_t)BYTESPERSECTOR; - df->Seek(&pos, DOS_SEEK_SET); - if (!df->Read((uint8_t*)filebuf, &read)) { read = 0; assert(0); } - if (read != BYTESPERSECTOR) - memset((uint8_t*)filebuf + read, 0, BYTESPERSECTOR - read); - return filebuf; - } - } - else if (sectnum >= sect_dirs_start) return &dirs[(sectnum - sect_dirs_start) * (BYTESPERSECTOR / sizeof(direntry))]; - else if (sectnum >= sect_root_start) return &root[(sectnum - sect_root_start) * (BYTESPERSECTOR / sizeof(direntry))]; - else if (sectnum >= sect_fat2_start) return &fat[(sectnum - sect_fat2_start) * BYTESPERSECTOR]; - else if (sectnum >= sect_fat1_start) return &fat[(sectnum - sect_fat1_start) * BYTESPERSECTOR]; - else if (IS_PC98_ARCH) { - if (sectnum == 0) return &ipl; - else if (sectnum == 1) return &pt; - else if (sectnum == sect_boot_pc98) return &bootsec; - else if (sectnum == sect_boot_pc98+1) return fsinfosec; - else if (sectnum == sect_boot_pc98+2) return fsinfosec; // additional boot loader code (anything is ok for us but needs 0x55AA footer signature) - else if (sectnum == sect_boot_pc98+6) return &bootsec; // boot sector copy - else if (sectnum == sect_boot_pc98+7) return fsinfosec; // boot sector copy - else if (sectnum == sect_boot_pc98+8) return fsinfosec; // boot sector copy - return NULL; - } - else if (sectnum == SECT_BOOT) return &bootsec; - else if (sectnum == SECT_MBR) return &mbr; - else if (sectnum == SECT_BOOT+1) return fsinfosec; - else if (sectnum == SECT_BOOT+2) return fsinfosec; // additional boot loader code (anything is ok for us but needs 0x55AA footer signature) - else if (sectnum == SECT_BOOT+6) return &bootsec; // boot sector copy - else if (sectnum == SECT_BOOT+7) return fsinfosec; // boot sector copy - else if (sectnum == SECT_BOOT+8) return fsinfosec; // boot sector copy - return NULL; - } - - uint8_t ReadSector(uint32_t sectnum, void* data) - { - uint32_t sectorHash = sectnum % CACHECOUNT; - void *cachedata = cacheSectorData[sectorHash]; - if (cacheSectorNumber[sectorHash] == sectnum) - { - memcpy(data, cachedata, BYTESPERSECTOR); - return 0; - } - cacheSectorNumber[sectorHash] = sectnum; - - void *src; - uint32_t cursor = (sectnum >= diffSectors.size() ? NULL_CURSOR : diffSectors[sectnum].cursor); - if (cursor != NULL_CURSOR) - src = diffSectorBufs[cursor].data; - else - src = GetUnmodifiedSector(sectnum, cachedata); - - if (src) memcpy(data, src, BYTESPERSECTOR); - else memset(data, 0, BYTESPERSECTOR); - if (src != cachedata) memcpy(cachedata, data, BYTESPERSECTOR); - return 0; - } - - bool SaveImage(const char *name) - { - FILE* f = fopen_wrap(name, "wb"); - if (f) { - uint8_t filebuf[BYTESPERSECTOR]; - if (IS_PC98_ARCH) { - memcpy(filebuf, &header, BYTESPERSECTOR); - if (fwrite(filebuf, 1, BYTESPERSECTOR, f) != BYTESPERSECTOR) {fclose(f);return false;} - memset(filebuf, 0, BYTESPERSECTOR); - for (int i = 0; i < 7; i++) - if (fwrite(filebuf, 1, BYTESPERSECTOR, f) != BYTESPERSECTOR) {fclose(f);return false;} - } - for (unsigned int i = 0; i < sect_disk_end; i++) { - ReadSector(i, filebuf); - if (fwrite(filebuf, 1, BYTESPERSECTOR, f) != BYTESPERSECTOR) { - fclose(f); - return false; - } - } - fclose(f); - return true; - } else - return false; - } -}; - -bool saveDiskImage(imageDisk *image, const char *name) { - return image && image->ffdd && image->ffdd->SaveImage(name); -} - -diskGeo DiskGeometryList[] = { - { 160, 8, 1, 40, 0, 512, 64, 1, 0xFE}, // IBM PC double density 5.25" single-sided 160KB - { 180, 9, 1, 40, 0, 512, 64, 1, 0xFC}, // IBM PC double density 5.25" single-sided 180KB - { 200, 10, 1, 40, 0, 512, 64, 2, 0xFC}, // DEC Rainbow double density 5.25" single-sided 200KB (I think...) - { 320, 8, 2, 40, 1, 512, 112, 2, 0xFF}, // IBM PC double density 5.25" double-sided 320KB - { 360, 9, 2, 40, 1, 512, 112, 2, 0xFD}, // IBM PC double density 5.25" double-sided 360KB - { 400, 10, 2, 40, 1, 512, 112, 2, 0xFD}, // DEC Rainbow double density 5.25" double-sided 400KB (I think...) - { 640, 8, 2, 80, 3, 512, 112, 2, 0xFB}, // IBM PC double density 3.5" double-sided 640KB - { 720, 9, 2, 80, 3, 512, 112, 2, 0xF9}, // IBM PC double density 3.5" double-sided 720KB - {1200, 15, 2, 80, 2, 512, 224, 1, 0xF9}, // IBM PC double density 5.25" double-sided 1.2MB - {1440, 18, 2, 80, 4, 512, 224, 1, 0xF0}, // IBM PC high density 3.5" double-sided 1.44MB - {1680, 21, 2, 80, 4, 512, 16, 4, 0xF0}, // IBM PC high density 3.5" double-sided 1.68MB (DMF) - {2880, 36, 2, 80, 6, 512, 240, 2, 0xF0}, // IBM PC high density 3.5" double-sided 2.88MB - - {1232, 8, 2, 77, 7, 1024,192, 1, 0xFE}, // NEC PC-98 high density 3.5" double-sided 1.2MB "3-mode" - {1520, 19, 2, 80, 2, 512, 224, 1, 0xF9}, // IBM PC high density 5.25" double-sided 1.52MB (XDF) - {1840, 23, 2, 80, 4, 512, 224, 1, 0xF0}, // IBM PC high density 3.5" double-sided 1.84MB (XDF) - - { 0, 0, 0, 0, 0, 0, 0, 0, 0} -}; - -Bitu call_int13 = 0; -Bitu diskparm0 = 0, diskparm1 = 0; -static uint8_t last_status; -static uint8_t last_drive; -uint16_t imgDTASeg; -RealPt imgDTAPtr; -DOS_DTA *imgDTA; -bool killRead; -static bool swapping_requested; - -void CMOS_SetRegister(Bitu regNr, uint8_t val); //For setting equipment word - -/* 2 floppies and 2 harddrives, max */ -bool imageDiskChange[MAX_DISK_IMAGES]={false}; -imageDisk *imageDiskList[MAX_DISK_IMAGES]={NULL}; -imageDisk *diskSwap[MAX_SWAPPABLE_DISKS]={NULL}; -int32_t swapPosition; - -imageDisk *GetINT13FloppyDrive(unsigned char drv) { - if (drv >= 2) - return NULL; - return imageDiskList[drv]; -} - -imageDisk *GetINT13HardDrive(unsigned char drv) { - if (drv < 0x80 || drv >= (0x80+MAX_DISK_IMAGES-2)) - return NULL; - - return imageDiskList[drv-0x80]; -} - -void FreeBIOSDiskList() { - for (int i=0;i < MAX_DISK_IMAGES;i++) { - if (imageDiskList[i] != NULL) { - if (i >= 2) IDE_Hard_Disk_Detach(i); - imageDiskList[i]->Release(); - imageDiskList[i] = NULL; - } - } - - for (int j=0;j < MAX_SWAPPABLE_DISKS;j++) { - if (diskSwap[j] != NULL) { - diskSwap[j]->Release(); - diskSwap[j] = NULL; - } - } -} - -//update BIOS disk parameter tables for first two hard drives -void updateDPT(void) { - uint32_t tmpheads, tmpcyl, tmpsect, tmpsize; - PhysPt dpphysaddr[2] = { CALLBACK_PhysPointer(diskparm0), CALLBACK_PhysPointer(diskparm1) }; - for (int i = 0; i < 2; i++) { - tmpheads = 0; tmpcyl = 0; tmpsect = 0; tmpsize = 0; - if (imageDiskList[i + 2] != NULL) { - imageDiskList[i + 2]->Get_Geometry(&tmpheads, &tmpcyl, &tmpsect, &tmpsize); - } - phys_writew(dpphysaddr[i], (uint16_t)tmpcyl); - phys_writeb(dpphysaddr[i] + 0x2, (uint8_t)tmpheads); - phys_writew(dpphysaddr[i] + 0x3, 0); - phys_writew(dpphysaddr[i] + 0x5, tmpcyl == 0 ? 0 : (uint16_t)-1); - phys_writeb(dpphysaddr[i] + 0x7, 0); - phys_writeb(dpphysaddr[i] + 0x8, tmpcyl == 0 ? 0 : (0xc0 | ((tmpheads > 8) << 3))); - phys_writeb(dpphysaddr[i] + 0x9, 0); - phys_writeb(dpphysaddr[i] + 0xa, 0); - phys_writeb(dpphysaddr[i] + 0xb, 0); - phys_writew(dpphysaddr[i] + 0xc, (uint16_t)tmpcyl); - phys_writeb(dpphysaddr[i] + 0xe, (uint8_t)tmpsect); - } -} - -void incrementFDD(void) { - uint16_t equipment=mem_readw(BIOS_CONFIGURATION); - if(equipment&1) { - Bitu numofdisks = (equipment>>6)&3; - numofdisks++; - if(numofdisks > 1) numofdisks=1;//max 2 floppies at the moment - equipment&=~0x00C0; - equipment|=(numofdisks<<6); - } else equipment|=1; - mem_writew(BIOS_CONFIGURATION,equipment); - if(IS_EGAVGA_ARCH) equipment &= ~0x30; //EGA/VGA startup display mode differs in CMOS - CMOS_SetRegister(0x14, (uint8_t)(equipment&0xff)); -} - -int swapInDisksSpecificDrive = -1; -// -1 = swap across A: and B: (DOSBox / DOSBox-X default behavior) -// 0 = swap across A: only -// 1 = swap across B: only - -void swapInDisks(int drive) { - bool allNull = true; - int32_t diskcount = 0; - Bits diskswapcount = 2; - Bits diskswapdrive = 0; - int32_t swapPos = swapPosition; - int32_t i; - - /* Check to make sure that there is at least one setup image */ - for(i=0;i= 0 && swapInDisksSpecificDrive <= 1 && (drive == -1 || drive == swapInDisksSpecificDrive)) { - diskswapdrive = swapInDisksSpecificDrive; - diskswapcount = 1; - } else if (swapInDisksSpecificDrive != -1 || drive != -1) /* Swap A: and B: drives */ - return; - - /* If only one disk is loaded, this loop will load the same disk in dive A and drive B */ - while(diskcount < diskswapcount) { - if(diskSwap[swapPos] != NULL) { - LOG_MSG("Loaded drive %d disk %d from swaplist position %d - \"%s\"", (int)diskswapdrive, (int)diskcount, (int)swapPos, diskSwap[swapPos]->diskname.c_str()); - - if (imageDiskList[diskswapdrive] != NULL) - imageDiskList[diskswapdrive]->Release(); - - imageDiskList[diskswapdrive] = diskSwap[swapPos]; - imageDiskList[diskswapdrive]->Addref(); - - imageDiskChange[diskswapdrive] = true; - - diskcount++; - diskswapdrive++; - } - - swapPos++; - if(swapPos>=MAX_SWAPPABLE_DISKS) swapPos=0; - } -} - -bool getSwapRequest(void) { - bool sreq=swapping_requested; - swapping_requested = false; - return sreq; -} - -void swapInDrive(int drive, unsigned int position=0) { -#if 0 /* FIX_ME: Disabled to swap CD by IMGSWAP command (Issue #4932). Revert this if any regression occurs */ - //if (drive>1||swapInDisksSpecificDrive!=drive) return; -#endif - if (position<1) swapPosition++; - else swapPosition=position-1; - if(diskSwap[swapPosition] == NULL) swapPosition = 0; - swapInDisks(drive); - swapping_requested = true; - DriveManager::CycleDisks(drive, true, position); - /* Hack/feature: rescan all disks as well */ - LOG_MSG("Diskcaching reset for drive %c.", drive+'A'); - if (Drives[drive] != NULL) { - Drives[drive]->EmptyCache(); - Drives[drive]->MediaChange(); - } -} - -void swapInNextDisk(bool pressed) { - if (!pressed) - return; - - DriveManager::CycleAllDisks(); - /* Hack/feature: rescan all disks as well */ - LOG_MSG("Diskcaching reset for floppy drives."); - for(Bitu i=0;i<2;i++) { /* Swap A: and B: where DOSBox mainline would run through ALL drive letters */ - if (Drives[i] != NULL) { - Drives[i]->EmptyCache(); - Drives[i]->MediaChange(); - } - } - if (swapInDisksSpecificDrive>1) return; - swapPosition++; - if(diskSwap[swapPosition] == NULL) swapPosition = 0; - swapInDisks(-1); - swapping_requested = true; -} - -void swapInNextCD(bool pressed) { - if (!pressed) - return; - DriveManager::CycleAllCDs(); - /* Hack/feature: rescan all disks as well */ - LOG_MSG("Diskcaching reset for normal mounted drives."); - for(Bitu i=2;i(Drives[i]) != NULL) { - Drives[i]->EmptyCache(); - Drives[i]->MediaChange(); - } - } -} - - -uint8_t imageDisk::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { - uint32_t sectnum; - - if (req_sector_size == 0) - req_sector_size = sector_size; - if (req_sector_size != sector_size) - return 0x05; - - if (sector == 0) { - LOG_MSG("Attempted to read invalid sector 0."); - return 0x05; - } - - sectnum = ( (cylinder * heads + head) * sectors ) + sector - 1L; - - return Read_AbsoluteSector(sectnum, data); -} - -uint8_t imageDisk::Read_AbsoluteSector(uint32_t sectnum, void * data) { - if (ffdd) return ffdd->ReadSector(sectnum, data); - - uint64_t bytenum,res; - int got; - - bytenum = (uint64_t)sectnum * (uint64_t)sector_size; - if ((bytenum + sector_size) > this->image_length) { - LOG_MSG("Attempt to read invalid sector in Read_AbsoluteSector for sector %lu.\n", (unsigned long)sectnum); - return 0x05; - } - bytenum += image_base; - - //LOG_MSG("Reading sectors %ld at bytenum %I64d", sectnum, bytenum); - - fseeko64(diskimg,(fseek_ofs_t)bytenum,SEEK_SET); - res = (uint64_t)ftello64(diskimg); - if (res != bytenum) { - LOG_MSG("fseek() failed in Read_AbsoluteSector for sector %lu. Want=%llu Got=%llu\n", - (unsigned long)sectnum,(unsigned long long)bytenum,(unsigned long long)res); - return 0x05; - } - - got = (int)fread(data, 1, sector_size, diskimg); - if ((unsigned int)got != sector_size) { - LOG_MSG("fread() failed in Read_AbsoluteSector for sector %lu. Want=%u got=%d\n", - (unsigned long)sectnum,sector_size,(unsigned int)got); - return 0x05; - } - - return 0x00; -} - -uint8_t imageDisk::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { - uint32_t sectnum; - - if (req_sector_size == 0) - req_sector_size = sector_size; - if (req_sector_size != sector_size) - return 0x05; - - sectnum = ( (cylinder * heads + head) * sectors ) + sector - 1L; - - return Write_AbsoluteSector(sectnum, data); -} - - -uint8_t imageDisk::Write_AbsoluteSector(uint32_t sectnum, const void *data) { - if (ffdd) return ffdd->WriteSector(sectnum, data); - - uint64_t bytenum; - - bytenum = (uint64_t)sectnum * sector_size; - if ((bytenum + sector_size) > this->image_length) { - LOG_MSG("Attempt to read invalid sector in Write_AbsoluteSector for sector %lu.\n", (unsigned long)sectnum); - return 0x05; - } - bytenum += image_base; - - //LOG_MSG("Writing sectors to %ld at bytenum %d", sectnum, bytenum); - - fseeko64(diskimg,(fseek_ofs_t)bytenum,SEEK_SET); - if ((uint64_t)ftello64(diskimg) != bytenum) - LOG_MSG("WARNING: fseek() failed in Write_AbsoluteSector for sector %lu\n",(unsigned long)sectnum); - - size_t ret=fwrite(data, sector_size, 1, diskimg); - - return ((ret>0)?0x00:0x05); - -} - -void imageDisk::Set_Reserved_Cylinders(Bitu resCyl) { - reserved_cylinders = resCyl; -} - -uint32_t imageDisk::Get_Reserved_Cylinders() { - return reserved_cylinders; -} - -imageDisk::imageDisk(IMAGE_TYPE class_id) : class_id(class_id) { -} - -imageDisk::imageDisk(FILE* diskimg, const char* diskName, uint32_t cylinders, uint32_t heads, uint32_t sectors, uint32_t sector_size, bool hardDrive) -{ - if (diskName) this->diskname = diskName; - this->cylinders = cylinders; - this->heads = heads; - this->sectors = sectors; - image_base = 0; - this->image_length = (uint64_t)cylinders * heads * sectors * sector_size; - refcount = 0; - this->sector_size = sector_size; - this->diskSizeK = this->image_length / 1024; - reserved_cylinders = 0; - this->diskimg = diskimg; - class_id = ID_BASE; - active = true; - this->hardDrive = hardDrive; - floppytype = 0; -} - +/* + * Copyright (C) 2002-2021 The DOSBox Team + * + * 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 2 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, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ -void imageDisk::UpdateFloppyType(void) { - uint8_t i=0; + #include + #include + + #include "dosbox.h" + #include "callback.h" + #include "bios.h" + #include "bios_disk.h" + #include "timer.h" + #include "regs.h" + #include "mem.h" + #include "dos_inc.h" /* for Drives[] */ + #include "../dos/drives.h" + #include "mapper.h" + #include "ide.h" + #include "cpu.h" + + #if defined(_MSC_VER) + # pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ + #endif + + extern bool _driveUsed; + extern unsigned long freec; + extern const uint8_t freedos_mbr[]; + extern int bootdrive, tryconvertcp; + extern bool int13_disk_change_detect_enable, skipintprog, rsize; + extern bool int13_extensions_enable, bootguest, bootvm, use_quick_reboot; + bool isDBCSCP(), isKanji1_gbk(uint8_t chr), shiftjis_lead_byte(int c), CheckDBCSCP(int32_t codepage); + extern bool CodePageGuestToHostUTF16(uint16_t *d/*CROSS_LEN*/,const char *s/*CROSS_LEN*/); + + #define STATIC_ASSERTM(A,B) static_assertion_##A##_##B + #define STATIC_ASSERTN(A,B) STATIC_ASSERTM(A,B) + #define STATIC_ASSERT(cond) typedef char STATIC_ASSERTN(__LINE__,__COUNTER__)[(cond)?1:-1] + + uint32_t DriveCalculateCRC32(const uint8_t *ptr, size_t len, uint32_t crc) + { + // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ + static const uint32_t s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + uint32_t crcu32 = ~crc; + while (len--) { uint8_t b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } + return ~crcu32; + } + + bool DriveFileIterator(DOS_Drive* drv, void(*func)(const char* path, bool is_dir, uint32_t size, uint16_t date, uint16_t time, uint8_t attr, Bitu data), Bitu data, int timeout) + { + if (!drv) return true; + uint32_t starttick = GetTicks(); + struct Iter + { + static bool ParseDir(DOS_Drive* drv, uint32_t startticks, const std::string& dir, std::vector& dirs, void(*func)(const char* path, bool is_dir, uint32_t size, uint16_t date, uint16_t time, uint8_t attr, Bitu data), Bitu data, uint32_t timeout) + { + size_t dirlen = dir.length(); + if (dirlen + DOS_NAMELENGTH >= DOS_PATHLENGTH) return true; + char full_path[DOS_PATHLENGTH+4]; + if (dirlen) + { + memcpy(full_path, &dir[0], dirlen); + full_path[dirlen++] = '\\'; + } + full_path[dirlen] = '\0'; + + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + dta.SetupSearch(255, (uint8_t)(0xffff & ~DOS_ATTR_VOLUME), (char*)"*.*"); + for (bool more = drv->FindFirst((char*)dir.c_str(), dta); more; more = drv->FindNext(dta)) + { + if (startticks && timeout > 0 && GetTicks()-startticks > timeout * 1000) { + LOG_MSG("Timeout iterating directories"); + dos.dta(save_dta); + return false; + } + char dta_name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH+1]; uint32_t dta_size, dta_hsize; uint16_t dta_date, dta_time; uint8_t dta_attr; + dta.GetResult(dta_name, lname, dta_size, dta_hsize, dta_date, dta_time, dta_attr); + strcpy(full_path + dirlen, dta_name); + bool is_dir = !!(dta_attr & DOS_ATTR_DIRECTORY); + //if (is_dir) printf("[%s] [%s] %s (size: %u - date: %u - time: %u - attr: %u)\n", (const char*)data, (dta_attr == 8 ? "V" : (is_dir ? "D" : "F")), full_path, dta_size, dta_date, dta_time, dta_attr); + if (dta_name[0] == '.' && dta_name[dta_name[1] == '.' ? 2 : 1] == '\0') continue; + if (is_dir) dirs.emplace_back(full_path); + func(full_path, is_dir, dta_size, dta_date, dta_time, dta_attr, data); + } + dos.dta(save_dta); + return true; + } + }; + std::vector dirs; + dirs.emplace_back(""); + std::string dir; + while (dirs.size()) + { + std::swap(dirs.back(), dir); + dirs.pop_back(); + if (!Iter::ParseDir(drv, starttick, dir.c_str(), dirs, func, data, timeout)) return false; + } + return true; + } + + template struct StringToPointerHashMap + { + StringToPointerHashMap() : len(0), maxlen(0), keys(NULL), vals(NULL) { } + ~StringToPointerHashMap() { free(keys); free(vals); } + + static uint32_t Hash(const char* str, uint32_t str_limit = 0xFFFF, uint32_t hash_init = (uint32_t)0x811c9dc5) + { + for (const char* e = str + str_limit; *str && str != e;) + hash_init = ((hash_init * (uint32_t)0x01000193) ^ (uint32_t)*(str++)); + return hash_init; + } + + TVal* Get(const char* str, uint32_t str_limit = 0xFFFF, uint32_t hash_init = (uint32_t)0x811c9dc5) const + { + if (len == 0) return NULL; + for (uint32_t key0 = Hash(str, str_limit, hash_init), key = (key0 ? key0 : 1), i = key;; i++) + { + if (keys[i &= maxlen] == key) return vals[i]; + if (!keys[i]) return NULL; + } + } + + void Put(const char* str, TVal* val, uint32_t str_limit = 0xFFFF, uint32_t hash_init = (uint32_t)0x811c9dc5) + { + if (len * 2 >= maxlen) Grow(); + for (uint32_t key0 = Hash(str, str_limit, hash_init), key = (key0 ? key0 : 1), i = key;; i++) + { + if (!keys[i &= maxlen]) { len++; keys[i] = key; vals[i] = val; return; } + if (keys[i] == key) { vals[i] = val; return; } + } + } + + bool Remove(const char* str, uint32_t str_limit = 0xFFFF, uint32_t hash_init = (uint32_t)0x811c9dc5) + { + if (len == 0) return false; + for (uint32_t key0 = Hash(str, str_limit, hash_init), key = (key0 ? key0 : 1), i = key;; i++) + { + if (keys[i &= maxlen] == key) + { + keys[i] = 0; + len--; + while ((key = keys[i = (i + 1) & maxlen]) != 0) + { + for (uint32_t j = key;; j++) + { + if (keys[j &= maxlen] == key) break; + if (!keys[j]) { keys[i] = 0; keys[j] = key; vals[j] = vals[i]; break; } + } + } + return true; + } + if (!keys[i]) return false; + } + } + + void Clear() { memset(keys, len = 0, (maxlen + 1) * sizeof(uint32_t)); } + + uint32_t Len() const { return len; } + uint32_t Capacity() const { return (maxlen ? maxlen + 1 : 0); } + TVal* GetAtIndex(uint32_t idx) const { return (keys[idx] ? vals[idx] : NULL); } + + struct Iterator + { + Iterator(StringToPointerHashMap& _map, uint32_t _index) : map(_map), index(_index - 1) { this->operator++(); } + StringToPointerHashMap& map; + uint32_t index; + TVal* operator *() const { return map.vals[index]; } + bool operator ==(const Iterator &other) const { return index == other.index; } + bool operator !=(const Iterator &other) const { return index != other.index; } + Iterator& operator ++() + { + if (!map.maxlen) { index = 0; return *this; } + if (++index > map.maxlen) index = map.maxlen + 1; + while (index <= map.maxlen && !map.keys[index]) index++; + return *this; + } + }; + + Iterator begin() { return Iterator(*this, 0); } + Iterator end() { return Iterator(*this, (maxlen ? maxlen + 1 : 0)); } + + private: + uint32_t len, maxlen, *keys; + TVal** vals; + + void Grow() + { + uint32_t oldMax = maxlen, oldCap = (maxlen ? oldMax + 1 : 0), *oldKeys = keys; + TVal **oldVals = vals; + maxlen = (maxlen ? maxlen * 2 + 1 : 15); + keys = (uint32_t*)calloc(maxlen + 1, sizeof(uint32_t)); + vals = (TVal**)malloc((maxlen + 1) * sizeof(TVal*)); + for (uint32_t i = 0; i != oldCap; i++) + { + if (!oldKeys[i]) continue; + for (uint32_t key = oldKeys[i], j = key;; j++) + { + if (!keys[j &= maxlen]) { keys[j] = key; vals[j] = oldVals[i]; break; } + } + } + free(oldKeys); + free(oldVals); + } + + // not copyable + StringToPointerHashMap(const StringToPointerHashMap&); + StringToPointerHashMap& operator=(const StringToPointerHashMap&); + }; + + #ifdef _MSC_VER + #pragma pack (1) + #endif + struct sector { + uint8_t content[512]; + } GCC_ATTRIBUTE(packed); + + typedef struct { + uint8_t sectors; + uint8_t surfaces; + uint16_t cylinders; + } SASIHDD; + + struct bootstrap { + uint8_t nearjmp[3]; + uint8_t oemname[8]; + uint8_t bytespersector[2]; + uint8_t sectorspercluster; + uint16_t reservedsectors; + uint8_t fatcopies; + uint16_t rootdirentries; + uint16_t totalsectorcount; + uint8_t mediadescriptor; + uint16_t sectorsperfat; + uint16_t sectorspertrack; + uint16_t headcount; + uint32_t hiddensectorcount; + uint32_t totalsecdword; + uint8_t bootcode[474]; + uint8_t magic1; /* 0x55 */ + uint8_t magic2; /* 0xaa */ + } GCC_ATTRIBUTE(packed); + + struct lfndirentry { + uint8_t ord; + uint8_t name1[10]; + uint8_t attrib; + uint8_t type; + uint8_t chksum; + uint8_t name2[12]; + uint16_t loFirstClust; + uint8_t name3[4]; + char* Name(int j) { return (char*)(j < 5 ? name1 + j*2 : j < 11 ? name2 + (j-5)*2 : name3 + (j-11)*2); } + } GCC_ATTRIBUTE(packed); + #ifdef _MSC_VER + #pragma pack () + #endif + + /* .HDI and .FDI header (NP2) */ + #pragma pack(push,1) + typedef struct { + uint8_t dummy[4]; // +0x00 + uint8_t hddtype[4]; // +0x04 + uint8_t headersize[4]; // +0x08 + uint8_t hddsize[4]; // +0x0C + uint8_t sectorsize[4]; // +0x10 + uint8_t sectors[4]; // +0x14 + uint8_t surfaces[4]; // +0x18 + uint8_t cylinders[4]; // +0x1C + } HDIHDR; // =0x20 + + typedef struct { + uint8_t dummy[4]; // +0x00 + uint8_t fddtype[4]; // +0x04 + uint8_t headersize[4]; // +0x08 + uint8_t fddsize[4]; // +0x0C + uint8_t sectorsize[4]; // +0x10 + uint8_t sectors[4]; // +0x14 + uint8_t surfaces[4]; // +0x18 + uint8_t cylinders[4]; // +0x1C + } FDIHDR; // =0x20 + + typedef struct { + char sig[16]; // +0x000 + char comment[0x100]; // +0x010 + UINT8 headersize[4]; // +0x110 + uint8_t prot; // +0x114 + uint8_t nhead; // +0x115 + uint8_t _unknown_[10]; // +0x116 + } NFDHDR; // =0x120 + + typedef struct { + char sig[16]; // +0x000 + char comment[0x100]; // +0x010 + UINT8 headersize[4]; // +0x110 + uint8_t prot; // +0x114 + uint8_t nhead; // +0x115 + uint8_t _unknown_[10]; // +0x116 + uint32_t trackheads[164]; // +0x120 + uint32_t addinfo; // +0x3b0 + uint8_t _unknown2_[12]; // +0x3b4 + } NFDHDRR1; // =0x3c0 + + typedef struct { + uint8_t log_cyl; // +0x0 + uint8_t log_head; // +0x1 + uint8_t log_rec; // +0x2 + uint8_t sec_len_pow2; // +0x3 sz = 128 << len_pow2 + uint8_t flMFM; // +0x4 + uint8_t flDDAM; // +0x5 + uint8_t byStatus; // +0x6 + uint8_t bySTS0; // +0x7 + uint8_t bySTS1; // +0x8 + uint8_t bySTS2; // +0x9 + uint8_t byRetry; // +0xA + uint8_t byPDA; // +0xB + uint8_t _unknown_[4]; // +0xC + } NFDHDR_ENTRY; // =0x10 + + typedef struct { + char szFileID[15]; // 識別ID "T98HDDIMAGE.R0" + char Reserve1[1]; // 予約 + char szComment[0x100]; // イメージコメント(ASCIIz) + uint32_t dwHeadSize; // ヘッダ部のサイズ + uint32_t dwCylinder; // シリンダ数 + uint16_t wHead; // ヘッド数 + uint16_t wSect; // 1トラックあたりのセクタ数 + uint16_t wSectLen; // セクタ長 + char Reserve2[2]; // 予約 + char Reserve3[0xe0]; // 予約 + }NHD_FILE_HEAD,*LP_NHD_FILE_HEAD; + #pragma pack(pop) + + #define STOREINTELDWORD(a, b) *((a)+0) = (uint8_t)((b)); *((a)+1) = (uint8_t)((b)>>8); *((a)+2) = (uint8_t)((b)>>16); *((a)+3) = (uint8_t)((b)>>24) + + STATIC_ASSERT(sizeof(direntry) == sizeof(lfndirentry)); + enum + { + DOS_ATTR_LONG_NAME = (DOS_ATTR_READ_ONLY | DOS_ATTR_HIDDEN | DOS_ATTR_SYSTEM | DOS_ATTR_VOLUME), + DOS_ATTR_LONG_NAME_MASK = (DOS_ATTR_READ_ONLY | DOS_ATTR_HIDDEN | DOS_ATTR_SYSTEM | DOS_ATTR_VOLUME | DOS_ATTR_DIRECTORY | DOS_ATTR_ARCHIVE), + DOS_ATTR_PENDING_SHORT_NAME = 0x80, + }; + + static const uint8_t hdddiskboot[] = { + 0xeb,0x0a,0x90,0x90,0x49,0x50,0x4c,0x31,0x00,0x00,0x00,0x1e, + 0xb8,0x04,0x0a,0xcd,0x18,0xb4,0x16,0xba,0x20,0xe1,0xcd,0x18, + 0xfa,0xfc,0xb8,0x00,0xa0,0x8e,0xc0,0xbe,0x3c,0x00,0x31,0xff, + 0xe8,0x09,0x00,0xbf,0xa0,0x00,0xe8,0x03,0x00,0xf4,0xeb,0xfd, + 0x2e,0xad,0x85,0xc0,0x74,0x05,0xab,0x47,0x47,0xeb,0xf5,0xc3, + 0x04,0x33,0x04,0x4e,0x05,0x4f,0x01,0x3c,0x05,0x49,0x05,0x47, + 0x05,0x23,0x05,0x39,0x05,0x2f,0x05,0x24,0x05,0x61,0x01,0x3c, + 0x05,0x38,0x04,0x4f,0x05,0x55,0x05,0x29,0x01,0x3c,0x05,0x5e, + 0x05,0x43,0x05,0x48,0x04,0x35,0x04,0x6c,0x04,0x46,0x04,0x24, + 0x04,0x5e,0x04,0x3b,0x04,0x73,0x01,0x25,0x00,0x00,0x05,0x47, + 0x05,0x23,0x05,0x39,0x05,0x2f,0x05,0x24,0x05,0x61,0x01,0x3c, + 0x05,0x38,0x04,0x72,0x21,0x5e,0x26,0x7e,0x18,0x65,0x01,0x24, + 0x05,0x6a,0x05,0x3b,0x05,0x43,0x05,0x48,0x04,0x37,0x04,0x46, + 0x12,0x3c,0x04,0x35,0x04,0x24,0x01,0x25,0x00,0x00, + }; + + struct fatFromDOSDrive + { + DOS_Drive* drive; + + enum ffddDefs : uint32_t + { + BYTESPERSECTOR = 512, + HEADCOUNT = 255, // needs to be >128 to fit 4GB into CHS + SECTORSPERTRACK = 63, + SECT_MBR = 0, + SECT_BOOT = 32, + CACHECOUNT = 256, + KEEPOPENCOUNT = 8, + NULL_CURSOR = (uint32_t)-1, + }; + + partTable mbr; + bootstrap bootsec; + sector header; + sector ipl; + sector pt; + SASIHDD sasi; + uint8_t fatSz; + uint8_t fsinfosec[BYTESPERSECTOR]; + uint32_t sectorsPerCluster, codepage = 0; + bool tryconvcp = false, readOnly = false, success = false, tomany = false; + + struct ffddFile { char path[DOS_PATHLENGTH+1]; uint32_t firstSect; }; + std::vector root, dirs; + std::vector files; + std::vector fileAtSector; + std::vector fat; + uint32_t sect_boot_pc98, sect_disk_end, sect_files_end, sect_files_start, sect_dirs_start, sect_root_start, sect_fat2_start, sect_fat1_start; + + struct ffddBuf { uint8_t data[BYTESPERSECTOR]; }; + struct ffddSec { uint32_t cursor = NULL_CURSOR; }; + std::vector diffSectorBufs; + std::vector diffSectors; + std::vector diffFreeCursors; + uint32_t saveEndCursor = 0; + uint8_t cacheSectorData[CACHECOUNT][BYTESPERSECTOR]; + uint32_t cacheSectorNumber[CACHECOUNT]; + DOS_File* openFiles[KEEPOPENCOUNT]; + uint32_t openIndex[KEEPOPENCOUNT]; + uint32_t openCursor = 0; + + ~fatFromDOSDrive() + { + for (DOS_File* df : openFiles) + if (df) { df->Close(); delete df; } + } + + fatFromDOSDrive(DOS_Drive* drv, uint32_t freeMB, int timeout) : drive(drv) + { + cacheSectorNumber[0] = 1; // must not state that sector 0 is already cached + memset(&cacheSectorNumber[1], 0, sizeof(cacheSectorNumber) - sizeof(cacheSectorNumber[0])); + memset(openFiles, 0, sizeof(openFiles)); + + struct Iter + { + static void SetFAT(fatFromDOSDrive& ffdd, size_t idx, uint32_t val) + { + while (idx >= (uint64_t)ffdd.fat.size() * 8 / ffdd.fatSz) + { + // FAT12 table grows in steps of 3 sectors otherwise the table doesn't align + size_t addSz = (ffdd.fatSz != 12 ? BYTESPERSECTOR : (BYTESPERSECTOR * 3)); + ffdd.fat.resize(ffdd.fat.size() + addSz); + memset(&ffdd.fat[ffdd.fat.size() - addSz], 0, addSz); + } + if (ffdd.fatSz == 32) // FAT32 + var_write((uint32_t *)&ffdd.fat[idx * 4], val); + else if (ffdd.fatSz == 16) // FAT 16 + var_write((uint16_t *)&ffdd.fat[idx * 2], (uint16_t)val); + else if (idx & 1) // FAT12 odd cluster + var_write((uint16_t *)&ffdd.fat[idx + idx / 2], (uint16_t)((var_read((uint16_t *)&ffdd.fat[idx + idx / 2]) & 0xF) | ((val & 0xFFF) << 4))); + else // FAT12 even cluster + var_write((uint16_t *)&ffdd.fat[idx + idx / 2], (uint16_t)((var_read((uint16_t *)&ffdd.fat[idx + idx / 2]) & 0xF000) | (val & 0xFFF))); + } + + static direntry* AddDirEntry(fatFromDOSDrive& ffdd, bool useFAT16Root, size_t& diridx) + { + const uint32_t entriesPerCluster = ffdd.sectorsPerCluster * BYTESPERSECTOR / sizeof(direntry); + if (!useFAT16Root && (diridx % entriesPerCluster) == 0) + { + // link fat (was set to 0xFFFF before but now we knew the chain continues) + if (diridx) SetFAT(ffdd, 2 + (diridx - 1) / entriesPerCluster, (uint32_t)(2 + ffdd.dirs.size() / entriesPerCluster)); + diridx = ffdd.dirs.size(); + ffdd.dirs.resize(diridx + entriesPerCluster); + memset(&ffdd.dirs[diridx], 0, sizeof(direntry) * entriesPerCluster); + SetFAT(ffdd, 2 + diridx / entriesPerCluster, (uint32_t)0xFFFFFFFF); // set as last cluster in chain for now + } + else if (useFAT16Root && diridx && (diridx % 512) == 0) + { + // this actually should never be larger than 512 for some FAT16 drivers + ffdd.root.resize(diridx + 512); + memset(&ffdd.root[diridx], 0, sizeof(direntry) * 512); + } + return &(!useFAT16Root ? ffdd.dirs : ffdd.root)[diridx++]; + } + + static void ParseDir(fatFromDOSDrive& ffdd, char* dir, const StringToPointerHashMap* filter, int dirlen = 0, uint16_t parentFirstCluster = 0) + { + if (ffdd.tomany) return; + const bool useFAT16Root = (!dirlen && ffdd.fatSz != 32), readOnly = ffdd.readOnly; + const size_t firstidx = (!useFAT16Root ? ffdd.dirs.size() : 0); + const uint32_t sectorsPerCluster = ffdd.sectorsPerCluster, bytesPerCluster = sectorsPerCluster * BYTESPERSECTOR, entriesPerCluster = bytesPerCluster / sizeof(direntry); + const uint16_t myFirstCluster = (dirlen ? (uint16_t)(2 + firstidx / entriesPerCluster) : (uint16_t)0) ; + + char finddir[DOS_PATHLENGTH+4]; + memcpy(finddir, dir, dirlen); // because FindFirst can modify this... + finddir[dirlen] = '\0'; + if (dirlen) dir[dirlen++] = '\\'; + + size_t diridx = 0; + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + dta.SetupSearch(255, 0xFF, (char*)"*.*"); + skipintprog = true; + for (bool more = ffdd.drive->FindFirst(finddir, dta); more; more = ffdd.drive->FindNext(dta)) + { + char dta_name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH+1]; uint32_t dta_size, dta_hsize; uint16_t dta_date, dta_time; uint8_t dta_attr; + dta.GetResult(dta_name, lname, dta_size, dta_hsize, dta_date, dta_time, dta_attr); + //LOG_MSG("dta_name %s lname %s\n", dta_name, lname); + const char *fend = dta_name + strlen(dta_name); + const bool dot = (dta_name[0] == '.' && dta_name[1] == '\0'), dotdot = (dta_name[0] == '.' && dta_name[1] == '.' && dta_name[2] == '\0'); + if (!dirlen && (dot || dotdot)) continue; // root shouldn't have dot entries (yet localDrive does...) + + ffddFile f; + memcpy(f.path, dir, dirlen); + memcpy(f.path + dirlen, dta_name, fend - dta_name + 1); + if (filter && filter->Get(f.path, sizeof(f.path))) continue; + + const bool isLongFileName = (!dot && !dotdot && !(dta_attr & DOS_ATTR_VOLUME)); + if (isLongFileName) + { + bool lead = false; + size_t len = 0, lfnlen = strlen(lname); + uint16_t *lfnw = (uint16_t *)malloc((lfnlen + 1) * sizeof(uint16_t)); + if (lfnw == NULL) continue; + char text[3]; + uint16_t uname[4]; + #if defined(WIN32) + uint16_t cp = GetACP(), cpbak = dos.loaded_codepage; + if (tryconvertcp && cpbak == 437 && CheckDBCSCP(cp)) + dos.loaded_codepage = cp; + #endif + for (size_t i=0; i < lfnlen; i++) { + if (lead) { + lead = false; + text[0]=lname[i-1]&0xFF; + text[1]=lname[i]&0xFF; + text[2]=0; + uname[0]=0; + uname[1]=0; + if (CodePageGuestToHostUTF16(uname,text)&&uname[0]!=0&&uname[1]==0) + lfnw[len++] = uname[0]; + else { + lfnw[len++] = lname[i-1]; + lfnw[len++] = lname[i]; + } + } else if (i+1ord = (uint8_t)((lfnblocks - i)|(i == 0 ? 0x40 : 0x0)); + le->attrib = DOS_ATTR_LONG_NAME; + le->type = 0; + le->loFirstClust = 0; + uint16_t* plfn = lfnw + (lfnblocks - i - 1) * 13; + for (int j = 0; j != 13; j++, plfn++) + { + char* p = le->Name(j); + if (plfn > lfn_end) + p[0] = p[1] = (char)0xFF; + else if (plfn == lfn_end) + p[0] = p[1] = 0; + else if (*plfn > 0xFF) { + p[0] = (uint8_t)(*plfn%0x100); + p[1] = (uint8_t)(*plfn/0x100); + } else { + p[0] = *plfn; + p[1] = 0; + } + } + } + free(lfnw); + } + + const char *fext = (dot || dotdot ? NULL : strrchr(dta_name, '.')); + direntry* e = AddDirEntry(ffdd, useFAT16Root, diridx); + memset(e->entryname, ' ', sizeof(e->entryname)); + memcpy(e->entryname, dta_name, (fext ? fext : fend) - dta_name); + if (fext++) memcpy(e->entryname + 8, fext, fend - fext); + + e->attrib = dta_attr | (readOnly ? DOS_ATTR_READ_ONLY : 0) | (isLongFileName ? DOS_ATTR_PENDING_SHORT_NAME : 0); + if (dos.version.major >= 7) { + var_write(&e->crtTime, dta_time); // create date/time is DOS 7.0 and up only + var_write(&e->crtDate, dta_date); // create date/time is DOS 7.0 and up only + } + var_write(&e->accessDate, dta_date); + var_write(&e->modTime, dta_time); + var_write(&e->modDate, dta_date); + + if (dot) + { + e->attrib |= DOS_ATTR_DIRECTORY; // make sure + var_write(&e->loFirstClust, myFirstCluster); + } + else if (dotdot) + { + e->attrib |= DOS_ATTR_DIRECTORY; // make sure + var_write(&e->loFirstClust, parentFirstCluster); + } + else if (dta_attr & DOS_ATTR_VOLUME) + { + if (dirlen || (e->attrib & DOS_ATTR_DIRECTORY) || dta_size) + LOG_MSG("Invalid volume entry - %s\n", e->entryname); + } + else if (!(dta_attr & DOS_ATTR_DIRECTORY)) + { + var_write(&e->entrysize, dta_size); + + uint32_t fileIdx = (uint32_t)ffdd.files.size(); + ffdd.files.push_back(f); + + uint32_t numSects = (dta_size + bytesPerCluster - 1) / bytesPerCluster * sectorsPerCluster; + try { + ffdd.fileAtSector.resize(ffdd.fileAtSector.size() + numSects, fileIdx); + } catch (...) { + LOG_MSG("Too many sectors needed, will discard remaining files (from %s)", lname); + ffdd.tomany = ffdd.readOnly = true; + var_write((uint32_t *)&ffdd.fsinfosec[488], (uint32_t)0x0); + break; + } + } + } + skipintprog = false; + dos.dta(save_dta); + if (dirlen && diridx < firstidx + 2) { + LOG_MSG("Directory need at least . and .. entries - %s\n", finddir); + return; + } + + // Now fill out the subdirectories (can't be done above because only one dos.dta can run simultaneously + std::vector& entries = (!useFAT16Root ? ffdd.dirs : ffdd.root); + for (size_t ei = firstidx; ei != diridx; ei++) + { + direntry& e = entries[ei]; + uint8_t* entryname = e.entryname; + int totlen = dirlen; + if (e.attrib & DOS_ATTR_DIRECTORY) // copy name before modifying SFN + { + if (entryname[0] == '.' && entryname[entryname[1] == '.' ? 2 : 1] == ' ') continue; + for (int i = 0; i != 8 && entryname[i] != ' '; i++) dir[totlen++] = entryname[i]; + if (entryname[8] != ' ') dir[totlen++] = '.'; + for (int i = 8; i != 11 && entryname[i] != ' '; i++) dir[totlen++] = entryname[i]; + } + if (e.attrib & DOS_ATTR_PENDING_SHORT_NAME) // convert LFN to SFN + { + uint8_t chksum = 0; + for (int i = 0; i != 11;) chksum = (chksum >> 1) + (chksum << 7) + e.entryname[i++]; + for (lfndirentry* le = (lfndirentry*)&e; le-- == (lfndirentry*)&e || !(le[1].ord & 0x40);) le->chksum = chksum; + e.attrib &= ~DOS_ATTR_PENDING_SHORT_NAME; + } + if (e.attrib & DOS_ATTR_DIRECTORY) // this reallocates ffdd.dirs so do this last + { + var_write(&e.loFirstClust, (uint16_t)(2 + ffdd.dirs.size() / entriesPerCluster)); + ParseDir(ffdd, dir, filter, totlen, myFirstCluster); + } + } + } + + struct SumInfo { uint64_t used_bytes; const StringToPointerHashMap* filter; }; + static void SumFileSize(const char* path, bool /*is_dir*/, uint32_t size, uint16_t, uint16_t, uint8_t, Bitu data) + { + if (!((SumInfo*)data)->filter || !((SumInfo*)data)->filter->Get(path)) + ((SumInfo*)data)->used_bytes += (size + (32*1024-1)) / (32*1024) * (32*1024); // count as 32 kb clusters + } + }; + + drv->EmptyCache(); + Iter::SumInfo sum = { 0, NULL }; + uint64_t freeSpace = 0, freeSpaceMB = 0; + uint32_t free_clusters = 0; + uint16_t drv_bytes_sector; uint8_t drv_sectors_cluster; uint16_t drv_total_clusters, drv_free_clusters; + rsize=true; + freec=0; + drv->AllocationInfo(&drv_bytes_sector, &drv_sectors_cluster, &drv_total_clusters, &drv_free_clusters); + free_clusters = freec?freec:drv_free_clusters; + freeSpace = (uint64_t)drv_bytes_sector * drv_sectors_cluster * (freec?freec:free_clusters); + freeSpaceMB = freeSpace / (1024*1024); + if (freeMB < freeSpaceMB) freeSpaceMB = freeMB; + rsize=false; + tomany=false; + readOnly = free_clusters == 0 || freeSpaceMB == 0; + if (!DriveFileIterator(drv, Iter::SumFileSize, (Bitu)&sum, timeout)) return; + + uint32_t usedMB = sum.used_bytes / (1024*1024), addFreeMB, totalMB, tsizeMB; + uint64_t tsize = 0; + if (IS_PC98_ARCH) { + if (usedMB < 6) { + sasi.sectors = 33; + sasi.surfaces = 4; + sasi.cylinders = 153; + } else if (usedMB < 16) { + sasi.sectors = 33; + sasi.surfaces = 4; + sasi.cylinders = 310; + } else if (usedMB < 26) { + sasi.sectors = 33; + sasi.surfaces = 6; + sasi.cylinders = 310; + } else if (usedMB < 36) { + sasi.sectors = 33; + sasi.surfaces = 8; + sasi.cylinders = 310; + } else { + sasi.sectors = 33; + uint32_t heads = std::ceil((double)(usedMB+(readOnly?0:(usedMB>=2047?freeSpaceMB:5)))/10); + if (heads > 255) { + sasi.surfaces = 255; + sasi.cylinders = heads * 615 / 255; + } else { + sasi.surfaces = heads; + sasi.cylinders = 615; + } + } + tsize = BYTESPERSECTOR * sasi.sectors * sasi.surfaces * sasi.cylinders; + tsizeMB = sasi.sectors * sasi.surfaces * sasi.cylinders / (1024 * 1024 / BYTESPERSECTOR); + if (tsizeMB < usedMB) readOnly = true; + addFreeMB = readOnly ? 0 : (usedMB >= 2047 ? freeSpaceMB : (std::ceil((double)tsize - sum.used_bytes) / (1024 * 1024) + 1)); + } else + addFreeMB = (readOnly ? 0 : freeSpaceMB); + totalMB = usedMB + (addFreeMB ? (1 + addFreeMB) : 0); + if (totalMB >= 3072) { fatSz = 32; sectorsPerCluster = 64; } // 32 kb clusters ( 98304 ~ FAT entries) + else if (totalMB >= 2048) { fatSz = 32; sectorsPerCluster = 32; } // 16 kb clusters (131072 ~ 196608 FAT entries) + else if (totalMB >= 384) { fatSz = 16; sectorsPerCluster = 64; } // 32 kb clusters ( 12288 ~ 65504 FAT entries) + else if (totalMB >= 192) { fatSz = 16; sectorsPerCluster = 32; } // 16 kb clusters ( 12288 ~ 24576 FAT entries) + else if (totalMB >= 96) { fatSz = 16; sectorsPerCluster = 16; } // 8 kb clusters ( 12288 ~ 24576 FAT entries) + else if (totalMB >= 48) { fatSz = 16; sectorsPerCluster = 8; } // 4 kb clusters ( 12288 ~ 24576 FAT entries) + else if (totalMB >= 12) { fatSz = 16; sectorsPerCluster = 4; } // 2 kb clusters ( 6144 ~ 24576 FAT entries) + else if (totalMB >= 4) { fatSz = 16; sectorsPerCluster = 1; } // .5 kb clusters ( 8192 ~ 24576 FAT entries) + else if (totalMB >= 2) { fatSz = 12; sectorsPerCluster = 4; } // 2 kb clusters ( 1024 ~ 2048 FAT entries) + else if (totalMB >= 1) { fatSz = 12; sectorsPerCluster = 2; } // 1 kb clusters ( 1024 ~ 2048 FAT entries) + else { fatSz = 12; sectorsPerCluster = 1; } // .5 kb clusters ( ~ 2048 FAT entries) + + // mediadescriptor in very first byte of FAT table + Iter::SetFAT(*this, 0, (uint32_t)0xFFFFFF8); + Iter::SetFAT(*this, 1, (uint32_t)0xFFFFFFF); + + if (fatSz != 32) + { + // this actually should never be anything but 512 for some FAT16 drivers + root.resize(512); + memset(&root[0], 0, sizeof(direntry) * 512); + } + + char dirbuf[DOS_PATHLENGTH+4]; + Iter::ParseDir(*this, dirbuf, NULL); + + const uint32_t bytesPerCluster = sectorsPerCluster * BYTESPERSECTOR; + const uint32_t entriesPerCluster = bytesPerCluster / sizeof(direntry); + uint32_t fileCluster = (uint32_t)(2 + dirs.size() / entriesPerCluster); + for (uint32_t fileSect = 0, rootOrDir = 0; rootOrDir != 2; rootOrDir++) + { + for (direntry& e : (rootOrDir ? dirs : root)) + { + if (!e.entrysize || (e.attrib & DOS_ATTR_LONG_NAME_MASK) == DOS_ATTR_LONG_NAME) continue; + var_write(&e.hiFirstClust, (uint16_t)(fileCluster >> 16)); + var_write(&e.loFirstClust, (uint16_t)(fileCluster)); + + // Write FAT link chain + uint32_t numClusters = (var_read(&e.entrysize) + bytesPerCluster - 1) / bytesPerCluster; + for (uint32_t i = fileCluster, iEnd = i + numClusters - 1; i != iEnd; i++) Iter::SetFAT(*this, i, i + 1); + Iter::SetFAT(*this, fileCluster + numClusters - 1, (uint32_t)0xFFFFFFF); + + files[fileAtSector[fileSect]].firstSect = fileSect; + + fileCluster += numClusters; + fileSect += numClusters * sectorsPerCluster; + } + } + + if (IS_PC98_ARCH) { + HDIHDR hdi; + memset(&hdi, 0, sizeof(hdi)); + // STOREINTELDWORD(hdi.hddtype, 0); + STOREINTELDWORD(hdi.headersize, 4096); + STOREINTELDWORD(hdi.hddsize, (uint32_t)tsize); + STOREINTELDWORD(hdi.sectorsize, BYTESPERSECTOR); + STOREINTELDWORD(hdi.sectors, sasi.sectors); + STOREINTELDWORD(hdi.surfaces, sasi.surfaces); + STOREINTELDWORD(hdi.cylinders, sasi.cylinders); + memset(&header, 0, sizeof(header)); + memcpy(&header,&hdi,sizeof(hdi)); + memset(&ipl, 0, sizeof(ipl)); + memcpy(&ipl,&hdddiskboot,sizeof(hdddiskboot)); + ipl.content[0xFE] = 0x55; + ipl.content[0xFF] = 0xaa; + ipl.content[0x1FE] = 0x55; + ipl.content[0x1FF] = 0xaa; + struct _PC98RawPartition pe; + memset(&pe, 0, sizeof(pe)); + STOREINTELDWORD(&pe.mid, 0xa0); + STOREINTELDWORD(&pe.sid, 0xa1); + STOREINTELDWORD(&pe.ipl_cyl, 1); + STOREINTELDWORD(&pe.cyl, 1); + STOREINTELDWORD(&pe.end_cyl, sasi.cylinders); + strncpy(pe.name, "MS-DOS ", 16); + memset(&pt, 0, sizeof(pt)); + memcpy(&pt,&pe,sizeof(pe)); + } + + // Add at least one page after the last file or FAT spec minimum to make ScanDisk happy (even on read-only disks) + const uint32_t FATPageClusters = BYTESPERSECTOR * 8 / fatSz, FATMinCluster = (fatSz == 32 ? 65525 : (fatSz == 16 ? 4085 : 0)) + FATPageClusters; + const uint32_t addFreeClusters = ((addFreeMB * (1024*1024/BYTESPERSECTOR)) + sectorsPerCluster - 1) / sectorsPerCluster; + const uint32_t targetClusters = fileCluster + (addFreeClusters < FATPageClusters ? FATPageClusters : addFreeClusters); + Iter::SetFAT(*this, (targetClusters < FATMinCluster ? FATMinCluster : targetClusters) - 1, 0); + const uint32_t totalClusters = (uint32_t)((uint64_t)fat.size() * 8 / fatSz); // as set by Iter::SetFAT + + // on read-only disks, fill up the end of the FAT table with "Bad sector in cluster or reserved cluster" markers + if (readOnly) + for (uint32_t cluster = fileCluster; cluster != totalClusters; cluster++) + Iter::SetFAT(*this, cluster, 0xFFFFFF7); + + const uint32_t sectorsPerFat = (uint32_t)(fat.size() / BYTESPERSECTOR); + const uint16_t reservedSectors = (fatSz == 32 ? 32 : 1); + const uint32_t partSize = totalClusters * sectorsPerCluster + reservedSectors; + + sect_boot_pc98 = sasi.surfaces * sasi.sectors; + sect_fat1_start = (IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT) + reservedSectors; + sect_fat2_start = sect_fat1_start + sectorsPerFat; + sect_root_start = sect_fat2_start + sectorsPerFat; + sect_dirs_start = sect_root_start + ((root.size() * sizeof(direntry) + BYTESPERSECTOR - 1) / BYTESPERSECTOR); + sect_files_start = sect_dirs_start + ((dirs.size() * sizeof(direntry) + BYTESPERSECTOR - 1) / BYTESPERSECTOR); + sect_files_end = sect_files_start + fileAtSector.size(); + sect_disk_end = (IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT) + partSize; + if (IS_PC98_ARCH && tsize/BYTESPERSECTOR-8 > sect_disk_end) sect_disk_end = tsize/BYTESPERSECTOR-8; + if (sect_disk_end < sect_files_end) return; + + for (ffddFile& f : files) + f.firstSect += sect_files_start; + + uint32_t serial = 0; + if (!serial) + { + serial = DriveCalculateCRC32(&fat[0], fat.size(), 0); + if (root.size()) serial = DriveCalculateCRC32((uint8_t*)&root[0], root.size() * sizeof(direntry), serial); + if (dirs.size()) serial = DriveCalculateCRC32((uint8_t*)&dirs[0], dirs.size() * sizeof(direntry), serial); + } + + memset(&mbr, 0, sizeof(mbr)); + //memcpy(&mbr,freedos_mbr,512); + var_write((uint32_t *)&mbr.booter[440], serial); //4 byte disk serial number + var_write(&mbr.pentry[0].bootflag, 0x80); //Active bootable + if ((sect_disk_end - 1) / (HEADCOUNT * SECTORSPERTRACK) > 0x3FF) + { + mbr.pentry[0].beginchs[0] = mbr.pentry[0].beginchs[1] = mbr.pentry[0].beginchs[2] = 0; + mbr.pentry[0].endchs[0] = mbr.pentry[0].endchs[1] = mbr.pentry[0].endchs[2] = 0; + } + else + { + chs_write(mbr.pentry[0].beginchs, IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT); + chs_write(mbr.pentry[0].endchs, sect_disk_end - 1); + } + var_write(&mbr.pentry[0].absSectStart, IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT); + var_write(&mbr.pentry[0].partSize, partSize); + mbr.magic1 = 0x55; mbr.magic2 = 0xaa; + + memset(&bootsec, 0, sizeof(bootsec)); + memcpy(bootsec.nearjmp, "\xEB\x3C\x90", sizeof(bootsec.nearjmp)); + memcpy(bootsec.oemname, fatSz == 32 ? "MSWIN4.1" : "MSDOS5.0", sizeof(bootsec.oemname)); + var_write((uint16_t *)&bootsec.bytespersector, (uint16_t)BYTESPERSECTOR); + var_write(&bootsec.sectorspercluster, sectorsPerCluster); + var_write(&bootsec.reservedsectors, reservedSectors); + var_write(&bootsec.fatcopies, 2); + var_write(&bootsec.totalsectorcount, 0); // 16 bit field is 0, actual value is in totalsecdword + var_write(&bootsec.mediadescriptor, 0xF8); //also in FAT[0] + var_write(&bootsec.sectorspertrack, IS_PC98_ARCH ? sasi.sectors : SECTORSPERTRACK); + var_write(&bootsec.headcount, IS_PC98_ARCH ? sasi.surfaces : HEADCOUNT); + var_write(&bootsec.hiddensectorcount, IS_PC98_ARCH ? sect_boot_pc98 : SECT_BOOT); + var_write(&bootsec.totalsecdword, partSize); + bootsec.magic1 = 0x55; bootsec.magic2 = 0xaa; + if (fatSz != 32) // FAT12/FAT16 + { + var_write(&mbr.pentry[0].parttype, (fatSz == 12 ? 0x01 : (sect_disk_end < 65536 ? 0x04 : 0x06))); // FAT12/16 + var_write(&bootsec.rootdirentries, (uint16_t)root.size()); + var_write(&bootsec.sectorsperfat, (uint16_t)sectorsPerFat); + bootsec.bootcode[0] = 0x80; //Physical drive (harddisk) flag + bootsec.bootcode[2] = 0x29; //Extended boot signature + var_write((uint32_t *)&bootsec.bootcode[3], serial + 1); //4 byte partition serial number + memcpy(&bootsec.bootcode[7], "NO NAME ", 11); // volume label + memcpy(&bootsec.bootcode[18], "FAT1 ", 8); // file system string name + bootsec.bootcode[22] = (char)('0' + (fatSz % 10)); // '2' or '6' + } + else // FAT32 + { + var_write(&mbr.pentry[0].parttype, 0x0C); //FAT32 + var_write((uint32_t *)&bootsec.bootcode[0], sectorsPerFat); + var_write((uint32_t *)&bootsec.bootcode[8], (uint32_t)2); // First cluster number of the root directory + var_write((uint16_t *)&bootsec.bootcode[12], (uint16_t)1); // Sector of FSInfo structure in offset from top of the FAT32 volume + var_write((uint16_t *)&bootsec.bootcode[14], (uint16_t)6); // Sector of backup boot sector in offset from top of the FAT32 volume + bootsec.bootcode[28] = 0x80; //Physical drive (harddisk) flag + bootsec.bootcode[30] = 0x29; //Extended boot signature + var_write((uint32_t *)&bootsec.bootcode[31], serial + 1); //4 byte partition serial number + memcpy(&bootsec.bootcode[35], "NO NAME ", 11); // volume label + memcpy(&bootsec.bootcode[46], "FAT32 ", 8); // file system string name + + memset(fsinfosec, 0, sizeof(fsinfosec)); + var_write((uint32_t *)&fsinfosec[0], (uint32_t)0x41615252); //lead signature + var_write((uint32_t *)&fsinfosec[484], (uint32_t)0x61417272); //Another signature + bool ver71 = dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10); + //Bitu freeclusters = readOnly ? 0x0 : (ver71 ? (Bitu)freeSpace / (BYTESPERSECTOR * sectorsPerCluster) : 0xFFFFFFFF); + Bitu freeclusters = readOnly ? 0x0 : (ver71 ? (Bitu)((sect_disk_end - sect_files_end) / sectorsPerCluster): 0xFFFFFFFF); + var_write((uint32_t *)&fsinfosec[488], (uint32_t)(freeclusters < 0xFFFFFFFF ? freeclusters : 0xFFFFFFFF)); //last known free cluster count (all FF is unknown) + var_write((uint32_t *)&fsinfosec[492], (ver71 ? (sect_files_end / sectorsPerCluster): 0xFFFFFFFF)); //the cluster number at which the driver should start looking for free clusters (all FF is unknown) + var_write((uint32_t *)&fsinfosec[508], 0xAA550000); //ending signature + } + + codepage = dos.loaded_codepage; + tryconvcp = tryconvertcp>0; + success = true; + } + + static void chs_write(uint8_t* chs, uint32_t lba) + { + uint32_t cylinder = lba / (HEADCOUNT * SECTORSPERTRACK); + uint32_t head = (lba / SECTORSPERTRACK) % HEADCOUNT; + uint32_t sector = (lba % SECTORSPERTRACK) + 1; + if (head > 0xFF || sector > 0x3F || cylinder > 0x3FF) + LOG_MSG("Warning: Invalid CHS data - %X, %X, %X\n", head, sector, cylinder); + chs[0] = (uint8_t)(head & 0xFF); + chs[1] = (uint8_t)((sector & 0x3F) | ((cylinder >> 8) & 0x3)); + chs[2] = (uint8_t)(cylinder & 0xFF); + } + + uint8_t WriteSector(uint32_t sectnum, const void* data) + { + _driveUsed = true; + if (sectnum >= sect_disk_end) return 1; + if (sectnum == SECT_MBR) + { + // Windows 9x writes the disk timestamp into the booter area on startup. + // Just copy that part over so it doesn't get treated as a difference that needs to be stored. + memcpy(mbr.booter, data, sizeof(mbr.booter)); + } + + if (readOnly) return 0; // just return without error to avoid bluescreens in Windows 9x + + if (sectnum >= diffSectors.size()) diffSectors.resize(sectnum + 128); + uint32_t *cursor_ptr = &diffSectors[sectnum].cursor, cursor_val = *cursor_ptr; + + int is_different; + uint8_t filebuf[BYTESPERSECTOR]; + void* unmodified = GetUnmodifiedSector(sectnum, filebuf); + if (!unmodified) + { + is_different = false; // to be equal it must be filled with zeroes + for (uint64_t* p = (uint64_t*)data, *pEnd = p + (BYTESPERSECTOR / sizeof(uint64_t)); p != pEnd; p++) + if (*p) { is_different = true; break; } + } + else is_different = memcmp(unmodified, data, BYTESPERSECTOR); + + if (is_different) + { + if (cursor_val == NULL_CURSOR && diffFreeCursors.size()) + { + *cursor_ptr = cursor_val = diffFreeCursors.back(); + diffFreeCursors.pop_back(); + } + if (cursor_val == NULL_CURSOR) + { + *cursor_ptr = cursor_val = (uint32_t)diffSectorBufs.size(); + diffSectorBufs.resize(cursor_val + 1); + } + memcpy(diffSectorBufs[cursor_val].data, data, BYTESPERSECTOR); + cacheSectorNumber[sectnum % CACHECOUNT] = (uint32_t)-1; // invalidate cache + } + else if (cursor_val != NULL_CURSOR) + { + diffFreeCursors.push_back(cursor_val); + *cursor_ptr = NULL_CURSOR; + cacheSectorNumber[sectnum % CACHECOUNT] = (uint32_t)-1; // invalidate cache + } + return 0; + } + + void* GetUnmodifiedSector(uint32_t sectnum, void* filebuf) + { + if (sectnum >= sect_files_end) {} + else if (sectnum >= sect_files_start) + { + uint32_t idx = fileAtSector[sectnum - sect_files_start]; + ffddFile& f = files[idx]; + DOS_File* df = NULL; + for (uint32_t i = 0; i != KEEPOPENCOUNT; i++) + if (openIndex[i] == idx && openFiles[i]) + { df = openFiles[i]; break; } + if (!df) + { + openCursor = (openCursor + 1) % KEEPOPENCOUNT; + DOS_File*& cachedf = openFiles[openCursor]; + if (cachedf) + { + cachedf->Close(); + delete cachedf; + cachedf = NULL; + } + bool res = drive->FileOpen(&df, f.path, OPEN_READ); + if (!res && codepage && (codepage != dos.loaded_codepage || (tryconvcp && codepage == 437))) { + uint32_t cp = dos.loaded_codepage; + dos.loaded_codepage = codepage; + #if defined(WIN32) + if (tryconvcp && dos.loaded_codepage == 437) dos.loaded_codepage = GetACP(); + #endif + res = drive->FileOpen(&df, f.path, OPEN_READ); + dos.loaded_codepage = cp; + } + if (res) + { + df->AddRef(); + cachedf = df; + openIndex[openCursor] = idx; + } + else return NULL; + } + if (df) + { + uint32_t pos = (sectnum - f.firstSect) * BYTESPERSECTOR; + uint16_t read = (uint16_t)BYTESPERSECTOR; + df->Seek(&pos, DOS_SEEK_SET); + if (!df->Read((uint8_t*)filebuf, &read)) { read = 0; assert(0); } + if (read != BYTESPERSECTOR) + memset((uint8_t*)filebuf + read, 0, BYTESPERSECTOR - read); + return filebuf; + } + } + else if (sectnum >= sect_dirs_start) return &dirs[(sectnum - sect_dirs_start) * (BYTESPERSECTOR / sizeof(direntry))]; + else if (sectnum >= sect_root_start) return &root[(sectnum - sect_root_start) * (BYTESPERSECTOR / sizeof(direntry))]; + else if (sectnum >= sect_fat2_start) return &fat[(sectnum - sect_fat2_start) * BYTESPERSECTOR]; + else if (sectnum >= sect_fat1_start) return &fat[(sectnum - sect_fat1_start) * BYTESPERSECTOR]; + else if (IS_PC98_ARCH) { + if (sectnum == 0) return &ipl; + else if (sectnum == 1) return &pt; + else if (sectnum == sect_boot_pc98) return &bootsec; + else if (sectnum == sect_boot_pc98+1) return fsinfosec; + else if (sectnum == sect_boot_pc98+2) return fsinfosec; // additional boot loader code (anything is ok for us but needs 0x55AA footer signature) + else if (sectnum == sect_boot_pc98+6) return &bootsec; // boot sector copy + else if (sectnum == sect_boot_pc98+7) return fsinfosec; // boot sector copy + else if (sectnum == sect_boot_pc98+8) return fsinfosec; // boot sector copy + return NULL; + } + else if (sectnum == SECT_BOOT) return &bootsec; + else if (sectnum == SECT_MBR) return &mbr; + else if (sectnum == SECT_BOOT+1) return fsinfosec; + else if (sectnum == SECT_BOOT+2) return fsinfosec; // additional boot loader code (anything is ok for us but needs 0x55AA footer signature) + else if (sectnum == SECT_BOOT+6) return &bootsec; // boot sector copy + else if (sectnum == SECT_BOOT+7) return fsinfosec; // boot sector copy + else if (sectnum == SECT_BOOT+8) return fsinfosec; // boot sector copy + return NULL; + } + + uint8_t ReadSector(uint32_t sectnum, void* data) + { + _driveUsed = true; + uint32_t sectorHash = sectnum % CACHECOUNT; + void *cachedata = cacheSectorData[sectorHash]; + if (cacheSectorNumber[sectorHash] == sectnum) + { + memcpy(data, cachedata, BYTESPERSECTOR); + return 0; + } + cacheSectorNumber[sectorHash] = sectnum; + + void *src; + uint32_t cursor = (sectnum >= diffSectors.size() ? NULL_CURSOR : diffSectors[sectnum].cursor); + if (cursor != NULL_CURSOR) + src = diffSectorBufs[cursor].data; + else + src = GetUnmodifiedSector(sectnum, cachedata); + + if (src) memcpy(data, src, BYTESPERSECTOR); + else memset(data, 0, BYTESPERSECTOR); + if (src != cachedata) memcpy(cachedata, data, BYTESPERSECTOR); + return 0; + } + + bool SaveImage(const char *name) + { + FILE* f = fopen_wrap(name, "wb"); + if (f) { + uint8_t filebuf[BYTESPERSECTOR]; + if (IS_PC98_ARCH) { + memcpy(filebuf, &header, BYTESPERSECTOR); + if (fwrite(filebuf, 1, BYTESPERSECTOR, f) != BYTESPERSECTOR) {fclose(f);return false;} + memset(filebuf, 0, BYTESPERSECTOR); + for (int i = 0; i < 7; i++) + if (fwrite(filebuf, 1, BYTESPERSECTOR, f) != BYTESPERSECTOR) {fclose(f);return false;} + } + for (unsigned int i = 0; i < sect_disk_end; i++) { + ReadSector(i, filebuf); + if (fwrite(filebuf, 1, BYTESPERSECTOR, f) != BYTESPERSECTOR) { + fclose(f); + return false; + } + } + fclose(f); + return true; + } else + return false; + } + }; + + bool saveDiskImage(imageDisk *image, const char *name) { + return image && image->ffdd && image->ffdd->SaveImage(name); + } + + diskGeo DiskGeometryList[] = { + { 160, 8, 1, 40, 0, 512, 64, 1, 0xFE}, // IBM PC double density 5.25" single-sided 160KB + { 180, 9, 1, 40, 0, 512, 64, 1, 0xFC}, // IBM PC double density 5.25" single-sided 180KB + { 200, 10, 1, 40, 0, 512, 64, 2, 0xFC}, // DEC Rainbow double density 5.25" single-sided 200KB (I think...) + { 320, 8, 2, 40, 1, 512, 112, 2, 0xFF}, // IBM PC double density 5.25" double-sided 320KB + { 360, 9, 2, 40, 1, 512, 112, 2, 0xFD}, // IBM PC double density 5.25" double-sided 360KB + { 400, 10, 2, 40, 1, 512, 112, 2, 0xFD}, // DEC Rainbow double density 5.25" double-sided 400KB (I think...) + { 640, 8, 2, 80, 3, 512, 112, 2, 0xFB}, // IBM PC double density 3.5" double-sided 640KB + { 720, 9, 2, 80, 3, 512, 112, 2, 0xF9}, // IBM PC double density 3.5" double-sided 720KB + {1200, 15, 2, 80, 2, 512, 224, 1, 0xF9}, // IBM PC double density 5.25" double-sided 1.2MB + {1440, 18, 2, 80, 4, 512, 224, 1, 0xF0}, // IBM PC high density 3.5" double-sided 1.44MB + {1680, 21, 2, 80, 4, 512, 16, 4, 0xF0}, // IBM PC high density 3.5" double-sided 1.68MB (DMF) + {2880, 36, 2, 80, 6, 512, 240, 2, 0xF0}, // IBM PC high density 3.5" double-sided 2.88MB + + {1232, 8, 2, 77, 7, 1024,192, 1, 0xFE}, // NEC PC-98 high density 3.5" double-sided 1.2MB "3-mode" + {1520, 19, 2, 80, 2, 512, 224, 1, 0xF9}, // IBM PC high density 5.25" double-sided 1.52MB (XDF) + {1840, 23, 2, 80, 4, 512, 224, 1, 0xF0}, // IBM PC high density 3.5" double-sided 1.84MB (XDF) + + { 0, 0, 0, 0, 0, 0, 0, 0, 0} + }; + + Bitu call_int13 = 0; + Bitu diskparm0 = 0, diskparm1 = 0; + static uint8_t last_status; + static uint8_t last_drive; + uint16_t imgDTASeg; + RealPt imgDTAPtr; + DOS_DTA *imgDTA; + bool killRead; + static bool swapping_requested; + + void CMOS_SetRegister(Bitu regNr, uint8_t val); //For setting equipment word + + /* 2 floppies and 2 harddrives, max */ + bool imageDiskChange[MAX_DISK_IMAGES]={false}; + imageDisk *imageDiskList[MAX_DISK_IMAGES]={NULL}; + imageDisk *diskSwap[MAX_SWAPPABLE_DISKS]={NULL}; + int32_t swapPosition; + + imageDisk *GetINT13FloppyDrive(unsigned char drv) { + if (drv >= 2) + return NULL; + return imageDiskList[drv]; + } + + imageDisk *GetINT13HardDrive(unsigned char drv) { + if (drv < 0x80 || drv >= (0x80+MAX_DISK_IMAGES-2)) + return NULL; + + return imageDiskList[drv-0x80]; + } + + void FreeBIOSDiskList() { + for (int i=0;i < MAX_DISK_IMAGES;i++) { + if (imageDiskList[i] != NULL) { + if (i >= 2) IDE_Hard_Disk_Detach(i); + imageDiskList[i]->Release(); + imageDiskList[i] = NULL; + } + } + + for (int j=0;j < MAX_SWAPPABLE_DISKS;j++) { + if (diskSwap[j] != NULL) { + diskSwap[j]->Release(); + diskSwap[j] = NULL; + } + } + } + + //update BIOS disk parameter tables for first two hard drives + void updateDPT(void) { + uint32_t tmpheads, tmpcyl, tmpsect, tmpsize; + PhysPt dpphysaddr[2] = { CALLBACK_PhysPointer(diskparm0), CALLBACK_PhysPointer(diskparm1) }; + for (int i = 0; i < 2; i++) { + tmpheads = 0; tmpcyl = 0; tmpsect = 0; tmpsize = 0; + if (imageDiskList[i + 2] != NULL) { + imageDiskList[i + 2]->Get_Geometry(&tmpheads, &tmpcyl, &tmpsect, &tmpsize); + } + phys_writew(dpphysaddr[i], (uint16_t)tmpcyl); + phys_writeb(dpphysaddr[i] + 0x2, (uint8_t)tmpheads); + phys_writew(dpphysaddr[i] + 0x3, 0); + phys_writew(dpphysaddr[i] + 0x5, tmpcyl == 0 ? 0 : (uint16_t)-1); + phys_writeb(dpphysaddr[i] + 0x7, 0); + phys_writeb(dpphysaddr[i] + 0x8, tmpcyl == 0 ? 0 : (0xc0 | ((tmpheads > 8) << 3))); + phys_writeb(dpphysaddr[i] + 0x9, 0); + phys_writeb(dpphysaddr[i] + 0xa, 0); + phys_writeb(dpphysaddr[i] + 0xb, 0); + phys_writew(dpphysaddr[i] + 0xc, (uint16_t)tmpcyl); + phys_writeb(dpphysaddr[i] + 0xe, (uint8_t)tmpsect); + } + } + + void incrementFDD(void) { + uint16_t equipment=mem_readw(BIOS_CONFIGURATION); + if(equipment&1) { + Bitu numofdisks = (equipment>>6)&3; + numofdisks++; + if(numofdisks > 1) numofdisks=1;//max 2 floppies at the moment + equipment&=~0x00C0; + equipment|=(numofdisks<<6); + } else equipment|=1; + mem_writew(BIOS_CONFIGURATION,equipment); + if(IS_EGAVGA_ARCH) equipment &= ~0x30; //EGA/VGA startup display mode differs in CMOS + CMOS_SetRegister(0x14, (uint8_t)(equipment&0xff)); + } + + int swapInDisksSpecificDrive = -1; + // -1 = swap across A: and B: (DOSBox / DOSBox-X default behavior) + // 0 = swap across A: only + // 1 = swap across B: only + + void swapInDisks(int drive) { + bool allNull = true; + int32_t diskcount = 0; + Bits diskswapcount = 2; + Bits diskswapdrive = 0; + int32_t swapPos = swapPosition; + int32_t i; + + /* Check to make sure that there is at least one setup image */ + for(i=0;i= 0 && swapInDisksSpecificDrive <= 1 && (drive == -1 || drive == swapInDisksSpecificDrive)) { + diskswapdrive = swapInDisksSpecificDrive; + diskswapcount = 1; + } else if (swapInDisksSpecificDrive != -1 || drive != -1) /* Swap A: and B: drives */ + return; + + /* If only one disk is loaded, this loop will load the same disk in dive A and drive B */ + while(diskcount < diskswapcount) { + if(diskSwap[swapPos] != NULL) { + LOG_MSG("Loaded drive %d disk %d from swaplist position %d - \"%s\"", (int)diskswapdrive, (int)diskcount, (int)swapPos, diskSwap[swapPos]->diskname.c_str()); + + if (imageDiskList[diskswapdrive] != NULL) + imageDiskList[diskswapdrive]->Release(); + + imageDiskList[diskswapdrive] = diskSwap[swapPos]; + imageDiskList[diskswapdrive]->Addref(); + + imageDiskChange[diskswapdrive] = true; + + diskcount++; + diskswapdrive++; + } + + swapPos++; + if(swapPos>=MAX_SWAPPABLE_DISKS) swapPos=0; + } + } + + bool getSwapRequest(void) { + bool sreq=swapping_requested; + swapping_requested = false; + return sreq; + } + + void swapInDrive(int drive, unsigned int position=0) { + #if 0 /* FIX_ME: Disabled to swap CD by IMGSWAP command (Issue #4932). Revert this if any regression occurs */ + //if (drive>1||swapInDisksSpecificDrive!=drive) return; + #endif + swapPosition = position; + // if (position<1) swapPosition++; + // else swapPosition=position-1; + if(diskSwap[swapPosition] == NULL) swapPosition = 0; + swapInDisks(drive); + swapping_requested = true; + DriveManager::CycleDisks(drive, true, position); + /* Hack/feature: rescan all disks as well */ + LOG_MSG("Diskcaching reset for drive %c.", drive+'A'); + if (Drives[drive] != NULL) { + Drives[drive]->EmptyCache(); + Drives[drive]->MediaChange(); + } + } + + void swapInNextDisk(bool pressed) { + if (!pressed) + return; + + DriveManager::CycleAllDisks(); + /* Hack/feature: rescan all disks as well */ + LOG_MSG("Diskcaching reset for floppy drives."); + for(Bitu i=0;i<2;i++) { /* Swap A: and B: where DOSBox mainline would run through ALL drive letters */ + if (Drives[i] != NULL) { + Drives[i]->EmptyCache(); + Drives[i]->MediaChange(); + } + } + if (swapInDisksSpecificDrive>1) return; + swapPosition++; + if(diskSwap[swapPosition] == NULL) swapPosition = 0; + swapInDisks(-1); + swapping_requested = true; + } + + void swapInNextCD(bool pressed) { + if (!pressed) + return; + DriveManager::CycleAllCDs(); + /* Hack/feature: rescan all disks as well */ + LOG_MSG("Diskcaching reset for normal mounted drives."); + for(Bitu i=2;i(Drives[i]) != NULL) { + Drives[i]->EmptyCache(); + Drives[i]->MediaChange(); + } + } + } + + + uint8_t imageDisk::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { + uint32_t sectnum; + + if (req_sector_size == 0) + req_sector_size = sector_size; + if (req_sector_size != sector_size) + return 0x05; + + if (sector == 0) { + LOG_MSG("Attempted to read invalid sector 0."); + return 0x05; + } + + sectnum = ( (cylinder * heads + head) * sectors ) + sector - 1L; + + _driveUsed = true; + return Read_AbsoluteSector(sectnum, data); + } + + uint8_t imageDisk::Read_AbsoluteSector(uint32_t sectnum, void * data) { + if (ffdd) return ffdd->ReadSector(sectnum, data); + _driveUsed = true; - while (DiskGeometryList[i].ksize!=0x0) { - if ((DiskGeometryList[i].ksize==diskSizeK) || (DiskGeometryList[i].ksize+1==diskSizeK)) { - floppytype = i; - LOG_MSG("Updating floppy type to %u BIOS type 0x%02x",floppytype,GetBiosType()); - break; - } - i++; - } -} + uint64_t bytenum,res; + int got; + + bytenum = (uint64_t)sectnum * (uint64_t)sector_size; + if ((bytenum + sector_size) > this->image_length) { + LOG_MSG("Attempt to read invalid sector in Read_AbsoluteSector for sector %lu.\n", (unsigned long)sectnum); + return 0x05; + } + bytenum += image_base; + + //LOG_MSG("Reading sectors %ld at bytenum %I64d", sectnum, bytenum); + + fseeko64(diskimg,(fseek_ofs_t)bytenum,SEEK_SET); + res = (uint64_t)ftello64(diskimg); + if (res != bytenum) { + LOG_MSG("fseek() failed in Read_AbsoluteSector for sector %lu. Want=%llu Got=%llu\n", + (unsigned long)sectnum,(unsigned long long)bytenum,(unsigned long long)res); + return 0x05; + } + + got = (int)fread(data, 1, sector_size, diskimg); + if ((unsigned int)got != sector_size) { + LOG_MSG("fread() failed in Read_AbsoluteSector for sector %lu. Want=%u got=%d\n", + (unsigned long)sectnum,sector_size,(unsigned int)got); + return 0x05; + } + + // size_t checksum = 0; + // for (size_t i = 0; i < sector_size; i++) checksum += ((uint8_t*)data)[i]; + // printf("Read sector %u - From Pos: %lu - Checksum: %lu\n", sectnum, bytenum, checksum); + + return 0x00; + } + + uint8_t imageDisk::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { + uint32_t sectnum; + + if (req_sector_size == 0) + req_sector_size = sector_size; + if (req_sector_size != sector_size) + return 0x05; + + sectnum = ( (cylinder * heads + head) * sectors ) + sector - 1L; + + _driveUsed = true; + return Write_AbsoluteSector(sectnum, data); + } + + + uint8_t imageDisk::Write_AbsoluteSector(uint32_t sectnum, const void *data) { + if (ffdd) return ffdd->WriteSector(sectnum, data); + + uint64_t bytenum; + + bytenum = (uint64_t)sectnum * sector_size; + if ((bytenum + sector_size) > this->image_length) { + LOG_MSG("Attempt to read invalid sector in Write_AbsoluteSector for sector %lu.\n", (unsigned long)sectnum); + return 0x05; + } + bytenum += image_base; + + //LOG_MSG("Writing sectors to %ld at bytenum %d", sectnum, bytenum); + + fseeko64(diskimg,(fseek_ofs_t)bytenum,SEEK_SET); + if ((uint64_t)ftello64(diskimg) != bytenum) + LOG_MSG("WARNING: fseek() failed in Write_AbsoluteSector for sector %lu\n",(unsigned long)sectnum); + + size_t ret=fwrite(data, sector_size, 1, diskimg); + + _driveUsed = true; + return ((ret>0)?0x00:0x05); + + } + + void imageDisk::Set_Reserved_Cylinders(Bitu resCyl) { + reserved_cylinders = resCyl; + } + + uint32_t imageDisk::Get_Reserved_Cylinders() { + return reserved_cylinders; + } + + imageDisk::imageDisk(IMAGE_TYPE class_id) : class_id(class_id) { + } + + imageDisk::imageDisk(FILE* diskimg, const char* diskName, uint32_t cylinders, uint32_t heads, uint32_t sectors, uint32_t sector_size, bool hardDrive) + { + if (diskName) this->diskname = diskName; + this->cylinders = cylinders; + this->heads = heads; + this->sectors = sectors; + image_base = 0; + this->image_length = (uint64_t)cylinders * heads * sectors * sector_size; + refcount = 0; + this->sector_size = sector_size; + this->diskSizeK = this->image_length / 1024; + reserved_cylinders = 0; + this->diskimg = diskimg; + class_id = ID_BASE; + active = true; + this->hardDrive = hardDrive; + floppytype = 0; + } + + + void imageDisk::UpdateFloppyType(void) { + uint8_t i=0; + + while (DiskGeometryList[i].ksize!=0x0) { + if ((DiskGeometryList[i].ksize==diskSizeK) || (DiskGeometryList[i].ksize+1==diskSizeK)) { + floppytype = i; + LOG_MSG("Updating floppy type to %u BIOS type 0x%02x",floppytype,GetBiosType()); + break; + } + i++; + } + } + + imageDisk::imageDisk(FILE* imgFile, const char* imgName, uint32_t imgSizeK, bool isHardDisk) : diskSizeK(imgSizeK), diskimg(imgFile), image_length((uint64_t)imgSizeK * 1024) { + if (imgName != NULL) + diskname = imgName; + + _driveUsed = true; + active = false; + hardDrive = isHardDisk; + if(!isHardDisk) { + bool founddisk = false; + + if (imgName != NULL) { + const char *ext = strrchr((char*)imgName,'.'); + if (ext != NULL) { + if (!strcasecmp(ext,".fdi")) { + if (imgSizeK >= 160) { + FDIHDR fdihdr; + + // PC-98 .FDI images appear to be 4096 bytes of a short header and many zeros. + // followed by a straight sector dump of the disk. The header is NOT NECESSARILY + // 4KB in size, but usually is. + LOG_MSG("Image file has .FDI extension, assuming FDI image and will take on parameters in header."); + + assert(sizeof(fdihdr) == 0x20); + if (fseek(imgFile,0,SEEK_SET) == 0 && ftell(imgFile) == 0 && + fread(&fdihdr,sizeof(fdihdr),1,imgFile) == 1) { + uint32_t ofs = host_readd(fdihdr.headersize); + uint32_t fddsize = host_readd(fdihdr.fddsize); /* includes header */ + uint32_t sectorsize = host_readd(fdihdr.sectorsize); + + if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && + sectorsize >= 256 && sectorsize <= 1024 && + ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/ && + (ofs % 1024) == 0/*offset is a multiple of 1024 because of imgSizeK*/ && + fddsize >= sectorsize && (fddsize/1024) <= (imgSizeK+4)) { + + founddisk = true; + sector_size = sectorsize; + imgSizeK -= (ofs / 1024); + image_base = ofs; + image_length -= ofs; + LOG_MSG("FDI header: sectorsize is %u bytes/sector, header is %u bytes, fdd size (plus header) is %u bytes", + sectorsize,ofs,fddsize); + + /* take on the geometry. */ + sectors = host_readd(fdihdr.sectors); + heads = host_readd(fdihdr.surfaces); + cylinders = host_readd(fdihdr.cylinders); + LOG_MSG("FDI: Geometry is C/H/S %u/%u/%u", + cylinders,heads,sectors); + } + else { + LOG_MSG("FDI header rejected. sectorsize=%u headersize=%u fddsize=%u", + sectorsize,ofs,fddsize); + } + } + else { + LOG_MSG("Unable to read .FDI header"); + } + } + } + } + } + + if (sectors == 0 && heads == 0 && cylinders == 0) { + uint8_t i=0; + while (DiskGeometryList[i].ksize!=0x0) { + if ((DiskGeometryList[i].ksize==imgSizeK) || + (DiskGeometryList[i].ksize+1==imgSizeK)) { + if (DiskGeometryList[i].ksize!=imgSizeK) + LOG_MSG("ImageLoader: image file with additional data, might not load!"); + founddisk = true; + active = true; + floppytype = i; + heads = DiskGeometryList[i].headscyl; + cylinders = DiskGeometryList[i].cylcount; + sectors = DiskGeometryList[i].secttrack; + sector_size = DiskGeometryList[i].bytespersect; + LOG_MSG("Identified '%s' as C/H/S %u/%u/%u %u bytes/sector", + imgName,cylinders,heads,sectors,sector_size); + break; + } + // Supports cases where the size of a 1.2 Mbytes disk image file is 1.44 Mbytes. + if(DiskGeometryList[i].ksize == 1200 && (imgSizeK > 1200 && imgSizeK <= 1440)) { + char buff[0x20]; + if (fseek(imgFile,0,SEEK_SET) == 0 && ftell(imgFile) == 0 && fread(buff,sizeof(buff),1,imgFile) == 1) { + if(buff[0x18] == DiskGeometryList[i].secttrack) { + founddisk = true; + active = true; + floppytype = i; + heads = DiskGeometryList[i].headscyl; + cylinders = DiskGeometryList[i].cylcount; + sectors = DiskGeometryList[i].secttrack; + break; + } + } + } + i++; + } + } + if(!founddisk) { + active = false; + } + } + else { /* hard disk */ + if (imgName != NULL) { + char *ext = strrchr((char*)imgName,'.'); + if (ext != NULL) { + if (!strcasecmp(ext,".nhd")) { + if (imgSizeK >= 160) { + NHD_FILE_HEAD nhdhdr; + + LOG_MSG("Image file has .NHD extension, assuming NHD image and will take on parameters in header."); + + assert(sizeof(nhdhdr) == 0x200); + if (fseek(imgFile,0,SEEK_SET) == 0 && ftell(imgFile) == 0 && + fread(&nhdhdr,sizeof(nhdhdr),1,imgFile) == 1 && + host_readd((ConstHostPt)(&nhdhdr.dwHeadSize)) >= 0x200 && + !memcmp(nhdhdr.szFileID,"T98HDDIMAGE.R0\0",15)) { + uint32_t ofs = host_readd((ConstHostPt)(&nhdhdr.dwHeadSize)); + uint32_t sectorsize = host_readw((ConstHostPt)(&nhdhdr.wSectLen)); + + if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && + sectorsize >= 256 && sectorsize <= 1024 && + ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/) { + + sector_size = sectorsize; + imgSizeK -= (ofs / 1024); + image_base = ofs; + image_length -= ofs; + LOG_MSG("NHD header: sectorsize is %u bytes/sector, header is %u bytes", + sectorsize,ofs); + + /* take on the geometry. + * PC-98 IPL1 support will need it to make sense of the partition table. */ + sectors = host_readw((ConstHostPt)(&nhdhdr.wSect)); + heads = host_readw((ConstHostPt)(&nhdhdr.wHead)); + cylinders = host_readd((ConstHostPt)(&nhdhdr.dwCylinder)); + LOG_MSG("NHD: Geometry is C/H/S %u/%u/%u", + cylinders,heads,sectors); + } + else { + LOG_MSG("NHD header rejected. sectorsize=%u headersize=%u", + sectorsize,ofs); + } + } + else { + LOG_MSG("Unable to read .NHD header"); + } + } + } + if (!strcasecmp(ext,".hdi")) { + if (imgSizeK >= 160) { + HDIHDR hdihdr; + + // PC-98 .HDI images appear to be 4096 bytes of a short header and many zeros. + // followed by a straight sector dump of the disk. The header is NOT NECESSARILY + // 4KB in size, but usually is. + LOG_MSG("Image file has .HDI extension, assuming HDI image and will take on parameters in header."); + + assert(sizeof(hdihdr) == 0x20); + if (fseek(imgFile,0,SEEK_SET) == 0 && ftell(imgFile) == 0 && + fread(&hdihdr,sizeof(hdihdr),1,imgFile) == 1) { + uint32_t ofs = host_readd(hdihdr.headersize); + uint32_t hddsize = host_readd(hdihdr.hddsize); /* includes header */ + uint32_t sectorsize = host_readd(hdihdr.sectorsize); + + if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && + sectorsize >= 256 && sectorsize <= 1024 && + ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/ && + (ofs % 1024) == 0/*offset is a multiple of 1024 because of imgSizeK*/ && + hddsize >= sectorsize && (hddsize/1024) <= (imgSizeK+4)) { + + sector_size = sectorsize; + image_base = ofs; + image_length -= ofs; + LOG_MSG("HDI header: sectorsize is %u bytes/sector, header is %u bytes, hdd size (plus header) is %u bytes", + sectorsize,ofs,hddsize); + + /* take on the geometry. + * PC-98 IPL1 support will need it to make sense of the partition table. */ + sectors = host_readd(hdihdr.sectors); + heads = host_readd(hdihdr.surfaces); + cylinders = host_readd(hdihdr.cylinders); + LOG_MSG("HDI: Geometry is C/H/S %u/%u/%u", + cylinders,heads,sectors); + } + else { + LOG_MSG("HDI header rejected. sectorsize=%u headersize=%u hddsize=%u", + sectorsize,ofs,hddsize); + } + } + else { + LOG_MSG("Unable to read .HDI header"); + } + } + } + } + } + + if (sectors == 0 || heads == 0 || cylinders == 0) + active = false; + } + } + + imageDisk::imageDisk(class DOS_Drive *useDrive, unsigned int letter, uint32_t freeMB, int timeout) + { + ffdd = new fatFromDOSDrive(useDrive, freeMB, timeout); + if (!ffdd->success) { + LOG_MSG("FAT conversion failed"); + delete ffdd; + ffdd = NULL; + return; + } + if (IS_PC98_ARCH) { + cylinders = ffdd->sasi.cylinders; + heads = ffdd->sasi.surfaces; + sectors = ffdd->sasi.sectors; + } + drvnum = letter; + diskimg = NULL; + diskname[0] = '\0'; + hardDrive = true; + Set_GeometryForHardDisk(); + } + + imageDisk::~imageDisk() + { + if(diskimg != NULL) { + fclose(diskimg); + diskimg=NULL; + } + if (ffdd) + delete ffdd; + } + + void imageDisk::Set_GeometryForHardDisk() + { + sector_size = 512; + partTable mbrData; + for (int m = (Read_AbsoluteSector(0, &mbrData) ? 0 : 4); m--;) + { + if(!mbrData.pentry[m].partSize) continue; + bootstrap bootbuffer; + if (Read_AbsoluteSector(mbrData.pentry[m].absSectStart, &bootbuffer)) continue; + bootbuffer.sectorspertrack = var_read(&bootbuffer.sectorspertrack); + bootbuffer.headcount = var_read(&bootbuffer.headcount); + uint32_t setSect = bootbuffer.sectorspertrack; + uint32_t setHeads = bootbuffer.headcount; + uint32_t setCyl = (mbrData.pentry[m].absSectStart + mbrData.pentry[m].partSize) / (setSect * setHeads); + Set_Geometry(setHeads, setCyl, setSect, 512); + return; + } + if (!diskimg) return; + uint32_t diskimgsize; + fseek(diskimg,0,SEEK_END); + diskimgsize = (uint32_t)ftell(diskimg); + fseek(diskimg,current_fpos,SEEK_SET); + Set_Geometry(16, diskimgsize / (512 * 63 * 16), 63, 512); + } + + void imageDisk::Set_Geometry(uint32_t setHeads, uint32_t setCyl, uint32_t setSect, uint32_t setSectSize) { + Bitu bigdisk_shift = 0; + + if (IS_PC98_ARCH) { + /* TODO: PC-98 has its own 4096 cylinder limit */ + } + else { + if(setCyl > 16384) LOG_MSG("Warning: This disk image is too big."); + else if(setCyl > 8192) bigdisk_shift = 4; + else if(setCyl > 4096) bigdisk_shift = 3; + else if(setCyl > 2048) bigdisk_shift = 2; + else if(setCyl > 1024) bigdisk_shift = 1; + } + + heads = setHeads << bigdisk_shift; + cylinders = setCyl >> bigdisk_shift; + sectors = setSect; + sector_size = setSectSize; + active = true; + } + + void imageDisk::Get_Geometry(uint32_t * getHeads, uint32_t *getCyl, uint32_t *getSect, uint32_t *getSectSize) { + *getHeads = heads; + *getCyl = cylinders; + *getSect = sectors; + *getSectSize = sector_size; + } + + uint8_t imageDisk::GetBiosType(void) { + if(!hardDrive) { + return (uint8_t)DiskGeometryList[floppytype].biosval; + } else return 0; + } + + uint32_t imageDisk::getSectSize(void) { + return sector_size; + } + + static uint8_t GetDosDriveNumber(uint8_t biosNum) { + switch(biosNum) { + case 0x0: + return 0x0; + case 0x1: + return 0x1; + case 0x80: + return 0x2; + case 0x81: + return 0x3; + case 0x82: + return 0x4; + case 0x83: + return 0x5; + default: + return 0x7f; + } + } + + static bool driveInactive(uint8_t driveNum) { + if(driveNum>=MAX_DISK_IMAGES) { + int driveCalledFor = reg_dl & 0x7f; + LOG(LOG_BIOS,LOG_ERROR)("Disk %d non-existent", driveCalledFor); + last_status = 0x01; + CALLBACK_SCF(true); + return true; + } + if(imageDiskList[driveNum] == NULL) { + LOG(LOG_BIOS,LOG_ERROR)("Disk %d not active", (int)driveNum); + last_status = 0x01; + CALLBACK_SCF(true); + return true; + } + if(!imageDiskList[driveNum]->active) { + LOG(LOG_BIOS,LOG_ERROR)("Disk %d not active", (int)driveNum); + last_status = 0x01; + CALLBACK_SCF(true); + return true; + } + return false; + } + + static struct { + uint8_t sz; + uint8_t res; + uint16_t num; + uint16_t off; + uint16_t seg; + uint32_t sector; + } dap; + + static void readDAP(uint16_t seg, uint16_t off) { + dap.sz = real_readb(seg,off++); + dap.res = real_readb(seg,off++); + dap.num = real_readw(seg,off); off += 2; + dap.off = real_readw(seg,off); off += 2; + dap.seg = real_readw(seg,off); off += 2; + + /* Although sector size is 64-bit, 32-bit 2TB limit should be more than enough */ + dap.sector = real_readd(seg,off); off +=4; + + if (real_readd(seg,off)) { + LOG(LOG_BIOS,LOG_WARN)("INT13: 64-bit sector addressing not supported"); + dap.num = 0; /* this will cause calling INT 13h code to return an error */ + } + } + + void IDE_ResetDiskByBIOS(unsigned char disk); + void IDE_EmuINT13DiskReadByBIOS(unsigned char disk,unsigned int cyl,unsigned int head,unsigned sect); + bool IDE_GetPhysGeometry(unsigned char disk,uint32_t &heads,uint32_t &cyl,uint32_t §,uint32_t &size); + void IDE_EmuINT13DiskReadByBIOS_LBA(unsigned char disk,uint64_t lba); + + void diskio_delay(Bits value/*bytes*/, int type = -1); + + /* For El Torito "No emulation" INT 13 services */ + unsigned char INT13_ElTorito_NoEmuDriveNumber = 0; + signed char INT13_ElTorito_IDEInterface = -1; /* (controller * 2) + (is_slave?1:0) */ + char INT13_ElTorito_NoEmuCDROMDrive = 0; + + bool GetMSCDEXDrive(unsigned char drive_letter, CDROM_Interface **_cdrom); + + + static Bitu INT13_DiskHandler(void) { + uint16_t segat, bufptr; + uint8_t sectbuf[2048/*CD-ROM support*/]; + uint8_t drivenum; + Bitu i,t; + last_drive = reg_dl; + drivenum = GetDosDriveNumber(reg_dl); + bool any_images = false; + for(i = 0;i < MAX_DISK_IMAGES;i++) { + if(imageDiskList[i]) any_images=true; + } + + // unconditionally enable the interrupt flag + CALLBACK_SIF(true); + + /* map out functions 0x40-0x48 if not emulating INT 13h extensions */ + if (!int13_extensions_enable && reg_ah >= 0x40 && reg_ah <= 0x48) { + LOG_MSG("Warning: Guest is attempting to use INT 13h extensions (AH=0x%02X). Set 'int 13 extensions=1' if you want to enable them.\n",reg_ah); + reg_ah=0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + + //drivenum = 0; + //LOG_MSG("INT13: Function %x called on drive %x (dos drive %d)", reg_ah, reg_dl, drivenum); + + // NOTE: the 0xff error code returned in some cases is questionable; 0x01 seems more correct + switch(reg_ah) { + case 0x0: /* Reset disk */ + { + /* if there aren't any diskimages (so only localdrives and virtual drives) + * always succeed on reset disk. If there are diskimages then and only then + * do real checks + */ + if (any_images && driveInactive(drivenum)) { + /* driveInactive sets carry flag if the specified drive is not available */ + if ((machine==MCH_CGA) || (machine==MCH_AMSTRAD) || (machine==MCH_PCJR)) { + /* those bioses call floppy drive reset for invalid drive values */ + if (((imageDiskList[0]) && (imageDiskList[0]->active)) || ((imageDiskList[1]) && (imageDiskList[1]->active))) { + if (machine!=MCH_PCJR && reg_dl<0x80) reg_ip++; + last_status = 0x00; + CALLBACK_SCF(false); + } + } + return CBRET_NONE; + } + if (machine!=MCH_PCJR && reg_dl<0x80) reg_ip++; + if (reg_dl >= 0x80) IDE_ResetDiskByBIOS(reg_dl); + last_status = 0x00; + CALLBACK_SCF(false); + } + break; + case 0x1: /* Get status of last operation */ + + if(last_status != 0x00) { + reg_ah = last_status; + CALLBACK_SCF(true); + } else { + reg_ah = 0x00; + CALLBACK_SCF(false); + } + break; + case 0x2: /* Read sectors */ + if (reg_al==0) { + reg_ah = 0x01; + CALLBACK_SCF(true); + return CBRET_NONE; + } + if (drivenum >= MAX_DISK_IMAGES || imageDiskList[drivenum] == NULL) { + if (drivenum >= DOS_DRIVES || !Drives[drivenum] || Drives[drivenum]->isRemovable()) { + reg_ah = 0x01; + CALLBACK_SCF(true); + return CBRET_NONE; + } + // Inherit the Earth cdrom and Amberstar use it as a disk test + if (((reg_dl&0x80)==0x80) && (reg_dh==0) && ((reg_cl&0x3f)==1)) { + if (reg_ch==0) { + // write some MBR data into buffer for Amberstar installer + real_writeb(SegValue(es),reg_bx+0x1be,0x80); // first partition is active + real_writeb(SegValue(es),reg_bx+0x1c2,0x06); // first partition is FAT16B + } + reg_ah = 0; + CALLBACK_SCF(false); + return CBRET_NONE; + } + } + if (driveInactive(drivenum)) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + + /* INT 13h is limited to 512 bytes/sector (as far as I know). + * The sector buffer in this function is limited to 512 bytes/sector, + * so this is also a protection against overrunning the stack if you + * mount a PC-98 disk image (1024 bytes/sector) and try to read it with INT 13h. */ + if (imageDiskList[drivenum]->sector_size > sizeof(sectbuf)) { + LOG(LOG_MISC,LOG_DEBUG)("INT 13h: Read failed because disk bytes/sector on drive %c is too large",(char)drivenum+'A'); + + imageDiskChange[drivenum] = false; + + reg_ah = 0x80; /* timeout */ + CALLBACK_SCF(true); + return CBRET_NONE; + } + + /* If the disk changed, the first INT 13h read will signal an error and set AH = 0x06 to indicate disk change */ + if (drivenum < 2 && imageDiskChange[drivenum]) { + LOG(LOG_MISC,LOG_DEBUG)("INT 13h: Failing first read of drive %c to indicate disk change",(char)drivenum+'A'); + + imageDiskChange[drivenum] = false; + + reg_ah = 0x06; /* diskette changed or removed */ + CALLBACK_SCF(true); + return CBRET_NONE; + } + + segat = SegValue(es); + bufptr = reg_bx; + for(i=0;iRead_Sector((uint32_t)reg_dh, (uint32_t)(reg_ch | ((reg_cl & 0xc0)<< 2)), (uint32_t)((reg_cl & 63)+i), sectbuf); + + if (drivenum < 2) + diskio_delay(512, 0); // Floppy + else + diskio_delay(512); + + /* IDE emulation: simulate change of IDE state that would occur on a real machine after INT 13h */ + IDE_EmuINT13DiskReadByBIOS(reg_dl, (uint32_t)(reg_ch | ((reg_cl & 0xc0)<< 2)), (uint32_t)reg_dh, (uint32_t)((reg_cl & 63)+i)); + + if((last_status != 0x00) || killRead) { + LOG_MSG("Error in disk read"); + killRead = false; + reg_ah = 0x04; + CALLBACK_SCF(true); + return CBRET_NONE; + } + for(t=0;t<512;t++) { + real_writeb(segat,bufptr,sectbuf[t]); + bufptr++; + } + } + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x3: /* Write sectors */ + + if(driveInactive(drivenum) || !imageDiskList[drivenum]) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + + /* INT 13h is limited to 512 bytes/sector (as far as I know). + * The sector buffer in this function is limited to 512 bytes/sector, + * so this is also a protection against overrunning the stack if you + * mount a PC-98 disk image (1024 bytes/sector) and try to read it with INT 13h. */ + if (imageDiskList[drivenum]->sector_size > sizeof(sectbuf)) { + LOG(LOG_MISC,LOG_DEBUG)("INT 13h: Write failed because disk bytes/sector on drive %c is too large",(char)drivenum+'A'); + + imageDiskChange[drivenum] = false; + + reg_ah = 0x80; /* timeout */ + CALLBACK_SCF(true); + return CBRET_NONE; + } + + bufptr = reg_bx; + for(i=0;igetSectSize();t++) { + sectbuf[t] = real_readb(SegValue(es),bufptr); + bufptr++; + } + + if(drivenum < 2) + diskio_delay(512, 0); // Floppy + else + diskio_delay(512); + + last_status = imageDiskList[drivenum]->Write_Sector((uint32_t)reg_dh, (uint32_t)(reg_ch | ((reg_cl & 0xc0) << 2)), (uint32_t)((reg_cl & 63) + i), §buf[0]); + if(last_status != 0x00) { + CALLBACK_SCF(true); + return CBRET_NONE; + } + } + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x04: /* Verify sectors */ + if (reg_al==0) { + reg_ah = 0x01; + CALLBACK_SCF(true); + return CBRET_NONE; + } + if(driveInactive(drivenum)) { + reg_ah = last_status; + return CBRET_NONE; + } + + /* TODO: Finish coding this section */ + /* + segat = SegValue(es); + bufptr = reg_bx; + for(i=0;iRead_Sector((uint32_t)reg_dh, (uint32_t)(reg_ch | ((reg_cl & 0xc0)<< 2)), (uint32_t)((reg_cl & 63)+i), sectbuf); + if(last_status != 0x00) { + LOG_MSG("Error in disk read"); + CALLBACK_SCF(true); + return CBRET_NONE; + } + for(t=0;t<512;t++) { + real_writeb(segat,bufptr,sectbuf[t]); + bufptr++; + } + }*/ + reg_ah = 0x00; + //Qbix: The following codes don't match my specs. al should be number of sector verified + //reg_al = 0x10; /* CRC verify failed */ + //reg_al = 0x00; /* CRC verify succeeded */ + CALLBACK_SCF(false); + + break; + case 0x05: /* Format track */ + /* ignore it. I just fucking want FORMAT.COM to write the FAT structure for God's sake */ + LOG_MSG("WARNING: Format track ignored\n"); + if (driveInactive(drivenum)) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + CALLBACK_SCF(false); + reg_ah = 0x00; + break; + case 0x06: /* Format track set bad sector flags */ + /* ignore it. I just fucking want FORMAT.COM to write the FAT structure for God's sake */ + LOG_MSG("WARNING: Format track set bad sector flags ignored (6)\n"); + if (driveInactive(drivenum)) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + CALLBACK_SCF(false); + reg_ah = 0x00; + break; + case 0x07: /* Format track set bad sector flags */ + /* ignore it. I just fucking want FORMAT.COM to write the FAT structure for God's sake */ + LOG_MSG("WARNING: Format track set bad sector flags ignored (7)\n"); + if (driveInactive(drivenum)) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + CALLBACK_SCF(false); + reg_ah = 0x00; + break; + case 0x08: /* Get drive parameters */ + if(driveInactive(drivenum)) { + last_status = 0x07; + reg_ah = last_status; + CALLBACK_SCF(true); + return CBRET_NONE; + } + reg_ax = 0x00; + reg_bl = imageDiskList[drivenum]->GetBiosType(); + uint32_t tmpheads, tmpcyl, tmpsect, tmpsize; + imageDiskList[drivenum]->Get_Geometry(&tmpheads, &tmpcyl, &tmpsect, &tmpsize); + if (tmpcyl==0) LOG(LOG_BIOS,LOG_ERROR)("INT13 DrivParm: cylinder count zero!"); + else tmpcyl--; // cylinder count -> max cylinder + if (tmpheads==0) LOG(LOG_BIOS,LOG_ERROR)("INT13 DrivParm: head count zero!"); + else tmpheads--; // head count -> max head + + /* older BIOSes were known to subtract 1 or 2 additional "reserved" cylinders. + * some code, such as Windows 3.1 WDCTRL, might assume that fact. emulate that here */ + { + uint32_t reserv = imageDiskList[drivenum]->Get_Reserved_Cylinders(); + if (tmpcyl > reserv) tmpcyl -= reserv; + else tmpcyl = 0; + } + + reg_ch = (uint8_t)(tmpcyl & 0xff); + reg_cl = (uint8_t)(((tmpcyl >> 2) & 0xc0) | (tmpsect & 0x3f)); + reg_dh = (uint8_t)tmpheads; + last_status = 0x00; + if (reg_dl&0x80) { // harddisks + reg_dl = 0; + for (int index = 2; index < MAX_DISK_IMAGES; index++) { + if (imageDiskList[index] != NULL) reg_dl++; + } + } else { // floppy disks + reg_dl = 0; + if(imageDiskList[0] != NULL) reg_dl++; + if(imageDiskList[1] != NULL) reg_dl++; + } + CALLBACK_SCF(false); + break; + case 0x11: /* Recalibrate drive */ + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x15: /* Get disk type */ + /* Korean Powerdolls uses this to detect harddrives */ + LOG(LOG_BIOS,LOG_WARN)("INT13: Get disktype used!"); + if (any_images) { + if(driveInactive(drivenum)) { + last_status = 0x07; + reg_ah = last_status; + CALLBACK_SCF(true); + return CBRET_NONE; + } + imageDiskList[drivenum]->Get_Geometry(&tmpheads, &tmpcyl, &tmpsect, &tmpsize); + uint64_t largesize = tmpheads*tmpcyl*tmpsect*tmpsize; + largesize/=512; + uint32_t ts = static_cast(largesize); + reg_ah = (drivenum < 2)?(int13_disk_change_detect_enable?2:1):3; //With 2 for floppy MSDOS starts calling int 13 ah 16 + if(reg_ah == 3) { + reg_cx = static_cast(ts >>16); + reg_dx = static_cast(ts & 0xffff); + } + CALLBACK_SCF(false); + } else { + if (drivenum = 2048, "not big enough" ); + diskio_delay(512); + if (killRead || !src_drive->ReadSectorsHost(sectbuf, false, dap.sector+i, 1)) { + real_writew(SegValue(ds),reg_si+2,i); // According to RBIL this should update the number of blocks field to what was successfully transferred + LOG_MSG("Error in CDROM read"); + killRead = false; + reg_ah = 0x04; + CALLBACK_SCF(true); + return CBRET_NONE; + } + + for(t=0;t<2048;t++) { + real_writeb(segat,bufptr,sectbuf[t]); + bufptr++; + } + } + reg_ah = 0x00; + CALLBACK_SCF(false); + return CBRET_NONE; + } + + if (!any_images) { + // Inherit the Earth cdrom (uses it as disk test) + if (((reg_dl&0x80)==0x80) && (reg_dh==0) && ((reg_cl&0x3f)==1)) { + reg_ah = 0; + CALLBACK_SCF(false); + return CBRET_NONE; + } + } + if (driveInactive(drivenum)) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + + segat = dap.seg; + bufptr = dap.off; + for(i=0;iRead_AbsoluteSector(dap.sector+i, sectbuf); + + if(drivenum < 2) + diskio_delay(512, 0); // Floppy + else + diskio_delay(512); + + IDE_EmuINT13DiskReadByBIOS_LBA(reg_dl,dap.sector+i); + + if((last_status != 0x00) || killRead) { + real_writew(SegValue(ds),reg_si+2,i); // According to RBIL this should update the number of blocks field to what was successfully transferred + LOG_MSG("Error in disk read"); + killRead = false; + reg_ah = 0x04; + CALLBACK_SCF(true); + return CBRET_NONE; + } + for(t=0;t<512;t++) { + real_writeb(segat,bufptr,sectbuf[t]); + bufptr++; + } + } + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x43: /* Extended Write Sectors to Drive */ + if(driveInactive(drivenum)) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + + /* Read Disk Address Packet */ + readDAP(SegValue(ds),reg_si); + + if (dap.num==0) { + reg_ah = 0x01; + CALLBACK_SCF(true); + return CBRET_NONE; + } + + bufptr = dap.off; + for(i=0;igetSectSize();t++) { + sectbuf[t] = real_readb(dap.seg,bufptr); + bufptr++; + } + + if(drivenum < 2) + diskio_delay(512, 0); // Floppy + else + diskio_delay(512); + + last_status = imageDiskList[drivenum]->Write_AbsoluteSector(dap.sector+i, §buf[0]); + if(last_status != 0x00) { + CALLBACK_SCF(true); + return CBRET_NONE; + } + } + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x44: /* Extended Verify Sectors [http://www.ctyme.com/intr/rb-0711.htm] */ + if(driveInactive(drivenum)) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + /* Just signal success, we don't actually verify anything */ + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + case 0x48: { /* get drive parameters */ + uint16_t bufsz; + + if(driveInactive(drivenum)) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + + segat = SegValue(ds); + bufptr = reg_si; + bufsz = real_readw(segat,bufptr+0); + if (bufsz < 0x1A) { + reg_ah = 0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + if (bufsz > 0x1E) bufsz = 0x1E; + else bufsz = 0x1A; + + tmpheads = tmpcyl = tmpsect = tmpsize = 0; + if (!IDE_GetPhysGeometry(drivenum,tmpheads,tmpcyl,tmpsect,tmpsize)) + imageDiskList[drivenum]->Get_Geometry(&tmpheads, &tmpcyl, &tmpsect, &tmpsize); + + real_writew(segat,bufptr+0x00,bufsz); + real_writew(segat,bufptr+0x02,0x0003); /* C/H/S valid, DMA boundary errors handled */ + real_writed(segat,bufptr+0x04,tmpcyl); + real_writed(segat,bufptr+0x08,tmpheads); + real_writed(segat,bufptr+0x0C,tmpsect); + real_writed(segat,bufptr+0x10,tmpcyl*tmpheads*tmpsect); + real_writed(segat,bufptr+0x14,0); + real_writew(segat,bufptr+0x18,512); + if (bufsz >= 0x1E) + real_writed(segat,bufptr+0x1A,0xFFFFFFFF); /* no EDD information available */ + + reg_ah = 0x00; + CALLBACK_SCF(false); + } break; + case 0x4B: /* Terminate disk emulation or get emulation status */ + /* NTS: Windows XP CD-ROM boot requires this call to work or else setup cannot find its own files. */ + if (reg_dl == 0x7F || (INT13_ElTorito_NoEmuDriveNumber != 0 && INT13_ElTorito_NoEmuDriveNumber == reg_dl)) { + if (reg_al <= 1) { + PhysPt p = (SegValue(ds) << 4) + reg_si; + phys_writeb(p + 0x00,0x13); + phys_writeb(p + 0x01,(0/*no emulation*/) + ((INT13_ElTorito_IDEInterface >= 0) ? 0x40 : 0)); + phys_writeb(p + 0x02,INT13_ElTorito_NoEmuDriveNumber); + if (INT13_ElTorito_IDEInterface >= 0) { + phys_writeb(p + 0x03,(unsigned char)(INT13_ElTorito_IDEInterface >> 1)); /* which IDE controller */ + phys_writew(p + 0x08,INT13_ElTorito_IDEInterface & 1);/* bit 0: IDE master/slave */ + } + else { + phys_writeb(p + 0x03,0); + phys_writew(p + 0x08,0); + } + phys_writed(p + 0x04,0); + phys_writew(p + 0x0A,0); + phys_writew(p + 0x0C,0); + phys_writew(p + 0x0E,0); + phys_writeb(p + 0x10,0); + phys_writeb(p + 0x11,0); + phys_writeb(p + 0x12,0); + reg_ah = 0x00; + CALLBACK_SCF(false); + break; + } + else { + reg_ah=0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + } + else { + reg_ah=0xff; + CALLBACK_SCF(true); + return CBRET_NONE; + } + break; + default: + LOG(LOG_BIOS,LOG_ERROR)("INT13: Function %x called on drive %x (dos drive %d)", (int)reg_ah, (int)reg_dl, (int)drivenum); + reg_ah=0xff; + CALLBACK_SCF(true); + } + return CBRET_NONE; + } + + void CALLBACK_DeAllocate(Bitu in); + + void BIOS_UnsetupDisks(void) { + if (call_int13 != 0) { + CALLBACK_DeAllocate(call_int13); + RealSetVec(0x13,0); /* zero INT 13h for now */ + call_int13 = 0; + } + if (diskparm0 != 0) { + CALLBACK_DeAllocate(diskparm0); + diskparm0 = 0; + } + if (diskparm1 != 0) { + CALLBACK_DeAllocate(diskparm1); + diskparm1 = 0; + } + } + + void BIOS_SetupDisks(void) { + unsigned int i; + + if (IS_PC98_ARCH) { + // TODO + return; + } + + /* TODO Start the time correctly */ + call_int13=CALLBACK_Allocate(); + CALLBACK_Setup(call_int13,&INT13_DiskHandler,CB_INT13,"Int 13 Bios disk"); + RealSetVec(0x13,CALLBACK_RealPointer(call_int13)); + + //release the drives after a soft reset + if ((!bootguest&&(bootvm||!use_quick_reboot))||bootdrive<0) FreeBIOSDiskList(); + + /* FIXME: Um... these aren't callbacks. Why are they allocated as callbacks? We have ROM general allocation now. */ + diskparm0 = CALLBACK_Allocate(); + CALLBACK_SetDescription(diskparm0,"BIOS Disk 0 parameter table"); + diskparm1 = CALLBACK_Allocate(); + CALLBACK_SetDescription(diskparm1,"BIOS Disk 1 parameter table"); + swapPosition = 0; + + RealSetVec(0x41,CALLBACK_RealPointer(diskparm0)); + RealSetVec(0x46,CALLBACK_RealPointer(diskparm1)); + + PhysPt dp0physaddr=CALLBACK_PhysPointer(diskparm0); + PhysPt dp1physaddr=CALLBACK_PhysPointer(diskparm1); + for(i=0;i<16;i++) { + phys_writeb(dp0physaddr+i,0); + phys_writeb(dp1physaddr+i,0); + } + + imgDTASeg = 0; + + /* Setup the Bios Area */ + mem_writeb(BIOS_HARDDISK_COUNT,2); + + killRead = false; + swapping_requested = false; + } + + // VFD *.FDD floppy disk format support + + uint8_t imageDiskVFD::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { + const vfdentry *ent; + _driveUsed = true; + + if (req_sector_size == 0) + req_sector_size = sector_size; + + // LOG_MSG("VFD read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); + + ent = findSector(head,cylinder,sector,req_sector_size); + if (ent == NULL) return 0x05; + if (ent->getSectorSize() != req_sector_size) return 0x05; + + if (ent->hasSectorData()) { + fseek(diskimg,(long)ent->data_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; + if (fread(data,req_sector_size,1,diskimg) != 1) return 0x05; + return 0; + } + else if (ent->hasFill()) { + memset(data,ent->fillbyte,req_sector_size); + return 0x00; + } + + return 0x05; + } + + uint8_t imageDiskVFD::Read_AbsoluteSector(uint32_t sectnum, void * data) { + unsigned int c,h,s; + + if (sectors == 0 || heads == 0) + return 0x05; + + s = (sectnum % sectors) + 1; + h = (sectnum / sectors) % heads; + c = (sectnum / sectors / heads); -imageDisk::imageDisk(FILE* imgFile, const char* imgName, uint32_t imgSizeK, bool isHardDisk) : diskSizeK(imgSizeK), diskimg(imgFile), image_length((uint64_t)imgSizeK * 1024) { - if (imgName != NULL) - diskname = imgName; - - active = false; - hardDrive = isHardDisk; - if(!isHardDisk) { - bool founddisk = false; - - if (imgName != NULL) { - const char *ext = strrchr((char*)imgName,'.'); - if (ext != NULL) { - if (!strcasecmp(ext,".fdi")) { - if (imgSizeK >= 160) { - FDIHDR fdihdr; - - // PC-98 .FDI images appear to be 4096 bytes of a short header and many zeros. - // followed by a straight sector dump of the disk. The header is NOT NECESSARILY - // 4KB in size, but usually is. - LOG_MSG("Image file has .FDI extension, assuming FDI image and will take on parameters in header."); - - assert(sizeof(fdihdr) == 0x20); - if (fseek(imgFile,0,SEEK_SET) == 0 && ftell(imgFile) == 0 && - fread(&fdihdr,sizeof(fdihdr),1,imgFile) == 1) { - uint32_t ofs = host_readd(fdihdr.headersize); - uint32_t fddsize = host_readd(fdihdr.fddsize); /* includes header */ - uint32_t sectorsize = host_readd(fdihdr.sectorsize); - - if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && - sectorsize >= 256 && sectorsize <= 1024 && - ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/ && - (ofs % 1024) == 0/*offset is a multiple of 1024 because of imgSizeK*/ && - fddsize >= sectorsize && (fddsize/1024) <= (imgSizeK+4)) { - - founddisk = true; - sector_size = sectorsize; - imgSizeK -= (ofs / 1024); - image_base = ofs; - image_length -= ofs; - LOG_MSG("FDI header: sectorsize is %u bytes/sector, header is %u bytes, fdd size (plus header) is %u bytes", - sectorsize,ofs,fddsize); - - /* take on the geometry. */ - sectors = host_readd(fdihdr.sectors); - heads = host_readd(fdihdr.surfaces); - cylinders = host_readd(fdihdr.cylinders); - LOG_MSG("FDI: Geometry is C/H/S %u/%u/%u", - cylinders,heads,sectors); - } - else { - LOG_MSG("FDI header rejected. sectorsize=%u headersize=%u fddsize=%u", - sectorsize,ofs,fddsize); - } - } - else { - LOG_MSG("Unable to read .FDI header"); - } - } - } - } - } - - if (sectors == 0 && heads == 0 && cylinders == 0) { - uint8_t i=0; - while (DiskGeometryList[i].ksize!=0x0) { - if ((DiskGeometryList[i].ksize==imgSizeK) || - (DiskGeometryList[i].ksize+1==imgSizeK)) { - if (DiskGeometryList[i].ksize!=imgSizeK) - LOG_MSG("ImageLoader: image file with additional data, might not load!"); - founddisk = true; - active = true; - floppytype = i; - heads = DiskGeometryList[i].headscyl; - cylinders = DiskGeometryList[i].cylcount; - sectors = DiskGeometryList[i].secttrack; - sector_size = DiskGeometryList[i].bytespersect; - LOG_MSG("Identified '%s' as C/H/S %u/%u/%u %u bytes/sector", - imgName,cylinders,heads,sectors,sector_size); - break; - } - // Supports cases where the size of a 1.2 Mbytes disk image file is 1.44 Mbytes. - if(DiskGeometryList[i].ksize == 1200 && (imgSizeK > 1200 && imgSizeK <= 1440)) { - char buff[0x20]; - if (fseek(imgFile,0,SEEK_SET) == 0 && ftell(imgFile) == 0 && fread(buff,sizeof(buff),1,imgFile) == 1) { - if(buff[0x18] == DiskGeometryList[i].secttrack) { - founddisk = true; - active = true; - floppytype = i; - heads = DiskGeometryList[i].headscyl; - cylinders = DiskGeometryList[i].cylcount; - sectors = DiskGeometryList[i].secttrack; - break; - } - } - } - i++; - } - } - if(!founddisk) { - active = false; - } - } - else { /* hard disk */ - if (imgName != NULL) { - char *ext = strrchr((char*)imgName,'.'); - if (ext != NULL) { - if (!strcasecmp(ext,".nhd")) { - if (imgSizeK >= 160) { - NHD_FILE_HEAD nhdhdr; - - LOG_MSG("Image file has .NHD extension, assuming NHD image and will take on parameters in header."); - - assert(sizeof(nhdhdr) == 0x200); - if (fseek(imgFile,0,SEEK_SET) == 0 && ftell(imgFile) == 0 && - fread(&nhdhdr,sizeof(nhdhdr),1,imgFile) == 1 && - host_readd((ConstHostPt)(&nhdhdr.dwHeadSize)) >= 0x200 && - !memcmp(nhdhdr.szFileID,"T98HDDIMAGE.R0\0",15)) { - uint32_t ofs = host_readd((ConstHostPt)(&nhdhdr.dwHeadSize)); - uint32_t sectorsize = host_readw((ConstHostPt)(&nhdhdr.wSectLen)); - - if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && - sectorsize >= 256 && sectorsize <= 1024 && - ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/) { - - sector_size = sectorsize; - imgSizeK -= (ofs / 1024); - image_base = ofs; - image_length -= ofs; - LOG_MSG("NHD header: sectorsize is %u bytes/sector, header is %u bytes", - sectorsize,ofs); - - /* take on the geometry. - * PC-98 IPL1 support will need it to make sense of the partition table. */ - sectors = host_readw((ConstHostPt)(&nhdhdr.wSect)); - heads = host_readw((ConstHostPt)(&nhdhdr.wHead)); - cylinders = host_readd((ConstHostPt)(&nhdhdr.dwCylinder)); - LOG_MSG("NHD: Geometry is C/H/S %u/%u/%u", - cylinders,heads,sectors); - } - else { - LOG_MSG("NHD header rejected. sectorsize=%u headersize=%u", - sectorsize,ofs); - } - } - else { - LOG_MSG("Unable to read .NHD header"); - } - } - } - if (!strcasecmp(ext,".hdi")) { - if (imgSizeK >= 160) { - HDIHDR hdihdr; - - // PC-98 .HDI images appear to be 4096 bytes of a short header and many zeros. - // followed by a straight sector dump of the disk. The header is NOT NECESSARILY - // 4KB in size, but usually is. - LOG_MSG("Image file has .HDI extension, assuming HDI image and will take on parameters in header."); - - assert(sizeof(hdihdr) == 0x20); - if (fseek(imgFile,0,SEEK_SET) == 0 && ftell(imgFile) == 0 && - fread(&hdihdr,sizeof(hdihdr),1,imgFile) == 1) { - uint32_t ofs = host_readd(hdihdr.headersize); - uint32_t hddsize = host_readd(hdihdr.hddsize); /* includes header */ - uint32_t sectorsize = host_readd(hdihdr.sectorsize); - - if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && - sectorsize >= 256 && sectorsize <= 1024 && - ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/ && - (ofs % 1024) == 0/*offset is a multiple of 1024 because of imgSizeK*/ && - hddsize >= sectorsize && (hddsize/1024) <= (imgSizeK+4)) { - - sector_size = sectorsize; - image_base = ofs; - image_length -= ofs; - LOG_MSG("HDI header: sectorsize is %u bytes/sector, header is %u bytes, hdd size (plus header) is %u bytes", - sectorsize,ofs,hddsize); - - /* take on the geometry. - * PC-98 IPL1 support will need it to make sense of the partition table. */ - sectors = host_readd(hdihdr.sectors); - heads = host_readd(hdihdr.surfaces); - cylinders = host_readd(hdihdr.cylinders); - LOG_MSG("HDI: Geometry is C/H/S %u/%u/%u", - cylinders,heads,sectors); - } - else { - LOG_MSG("HDI header rejected. sectorsize=%u headersize=%u hddsize=%u", - sectorsize,ofs,hddsize); - } - } - else { - LOG_MSG("Unable to read .HDI header"); - } - } - } - } - } - - if (sectors == 0 || heads == 0 || cylinders == 0) - active = false; - } -} - -imageDisk::imageDisk(class DOS_Drive *useDrive, unsigned int letter, uint32_t freeMB, int timeout) -{ - ffdd = new fatFromDOSDrive(useDrive, freeMB, timeout); - if (!ffdd->success) { - LOG_MSG("FAT conversion failed"); - delete ffdd; - ffdd = NULL; - return; - } - if (IS_PC98_ARCH) { - cylinders = ffdd->sasi.cylinders; - heads = ffdd->sasi.surfaces; - sectors = ffdd->sasi.sectors; - } - drvnum = letter; - diskimg = NULL; - diskname[0] = '\0'; - hardDrive = true; - Set_GeometryForHardDisk(); -} - -imageDisk::~imageDisk() -{ - if(diskimg != NULL) { - fclose(diskimg); - diskimg=NULL; - } - if (ffdd) - delete ffdd; -} - -void imageDisk::Set_GeometryForHardDisk() -{ - sector_size = 512; - partTable mbrData; - for (int m = (Read_AbsoluteSector(0, &mbrData) ? 0 : 4); m--;) - { - if(!mbrData.pentry[m].partSize) continue; - bootstrap bootbuffer; - if (Read_AbsoluteSector(mbrData.pentry[m].absSectStart, &bootbuffer)) continue; - bootbuffer.sectorspertrack = var_read(&bootbuffer.sectorspertrack); - bootbuffer.headcount = var_read(&bootbuffer.headcount); - uint32_t setSect = bootbuffer.sectorspertrack; - uint32_t setHeads = bootbuffer.headcount; - uint32_t setCyl = (mbrData.pentry[m].absSectStart + mbrData.pentry[m].partSize) / (setSect * setHeads); - Set_Geometry(setHeads, setCyl, setSect, 512); - return; - } - if (!diskimg) return; - uint32_t diskimgsize; - fseek(diskimg,0,SEEK_END); - diskimgsize = (uint32_t)ftell(diskimg); - fseek(diskimg,current_fpos,SEEK_SET); - Set_Geometry(16, diskimgsize / (512 * 63 * 16), 63, 512); -} - -void imageDisk::Set_Geometry(uint32_t setHeads, uint32_t setCyl, uint32_t setSect, uint32_t setSectSize) { - Bitu bigdisk_shift = 0; - - if (IS_PC98_ARCH) { - /* TODO: PC-98 has its own 4096 cylinder limit */ - } - else { - if(setCyl > 16384) LOG_MSG("Warning: This disk image is too big."); - else if(setCyl > 8192) bigdisk_shift = 4; - else if(setCyl > 4096) bigdisk_shift = 3; - else if(setCyl > 2048) bigdisk_shift = 2; - else if(setCyl > 1024) bigdisk_shift = 1; - } - - heads = setHeads << bigdisk_shift; - cylinders = setCyl >> bigdisk_shift; - sectors = setSect; - sector_size = setSectSize; - active = true; -} - -void imageDisk::Get_Geometry(uint32_t * getHeads, uint32_t *getCyl, uint32_t *getSect, uint32_t *getSectSize) { - *getHeads = heads; - *getCyl = cylinders; - *getSect = sectors; - *getSectSize = sector_size; -} - -uint8_t imageDisk::GetBiosType(void) { - if(!hardDrive) { - return (uint8_t)DiskGeometryList[floppytype].biosval; - } else return 0; -} - -uint32_t imageDisk::getSectSize(void) { - return sector_size; -} - -static uint8_t GetDosDriveNumber(uint8_t biosNum) { - switch(biosNum) { - case 0x0: - return 0x0; - case 0x1: - return 0x1; - case 0x80: - return 0x2; - case 0x81: - return 0x3; - case 0x82: - return 0x4; - case 0x83: - return 0x5; - default: - return 0x7f; - } -} - -static bool driveInactive(uint8_t driveNum) { - if(driveNum>=MAX_DISK_IMAGES) { - int driveCalledFor = reg_dl & 0x7f; - LOG(LOG_BIOS,LOG_ERROR)("Disk %d non-existent", driveCalledFor); - last_status = 0x01; - CALLBACK_SCF(true); - return true; - } - if(imageDiskList[driveNum] == NULL) { - LOG(LOG_BIOS,LOG_ERROR)("Disk %d not active", (int)driveNum); - last_status = 0x01; - CALLBACK_SCF(true); - return true; - } - if(!imageDiskList[driveNum]->active) { - LOG(LOG_BIOS,LOG_ERROR)("Disk %d not active", (int)driveNum); - last_status = 0x01; - CALLBACK_SCF(true); - return true; - } - return false; -} - -static struct { - uint8_t sz; - uint8_t res; - uint16_t num; - uint16_t off; - uint16_t seg; - uint32_t sector; -} dap; - -static void readDAP(uint16_t seg, uint16_t off) { - dap.sz = real_readb(seg,off++); - dap.res = real_readb(seg,off++); - dap.num = real_readw(seg,off); off += 2; - dap.off = real_readw(seg,off); off += 2; - dap.seg = real_readw(seg,off); off += 2; - - /* Although sector size is 64-bit, 32-bit 2TB limit should be more than enough */ - dap.sector = real_readd(seg,off); off +=4; - - if (real_readd(seg,off)) { - LOG(LOG_BIOS,LOG_WARN)("INT13: 64-bit sector addressing not supported"); - dap.num = 0; /* this will cause calling INT 13h code to return an error */ - } -} - -void IDE_ResetDiskByBIOS(unsigned char disk); -void IDE_EmuINT13DiskReadByBIOS(unsigned char disk,unsigned int cyl,unsigned int head,unsigned sect); -bool IDE_GetPhysGeometry(unsigned char disk,uint32_t &heads,uint32_t &cyl,uint32_t §,uint32_t &size); -void IDE_EmuINT13DiskReadByBIOS_LBA(unsigned char disk,uint64_t lba); - -void diskio_delay(Bits value/*bytes*/, int type = -1); + _driveUsed = true; + return Read_Sector(h,c,s,data); + } + + imageDiskVFD::vfdentry *imageDiskVFD::findSector(uint8_t head,uint8_t track,uint8_t sector/*TODO: physical head?*/,unsigned int req_sector_size) { + std::vector::iterator i = dents.begin(); + unsigned char szb=0xFF; + + if (req_sector_size == 0) + req_sector_size = sector_size; + + if (req_sector_size != ~0U) { + unsigned int c = req_sector_size; + while (c >= 128U) { + c >>= 1U; + szb++; + } + + // LOG_MSG("req=%u c=%u szb=%u",req_sector_size,c,szb); + + if (szb > 8 || c != 64U) + return NULL; + } + + while (i != dents.end()) { + const imageDiskVFD::vfdentry &ent = *i; + + if (ent.head == head && + ent.track == track && + ent.sector == sector && + (ent.sizebyte == szb || req_sector_size == ~0U)) + return &(*i); + + ++i; + } + + return NULL; + } + + uint8_t imageDiskVFD::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { + unsigned long new_offset; + unsigned char tmp[12]; + vfdentry *ent; + _driveUsed = true; -/* For El Torito "No emulation" INT 13 services */ -unsigned char INT13_ElTorito_NoEmuDriveNumber = 0; -signed char INT13_ElTorito_IDEInterface = -1; /* (controller * 2) + (is_slave?1:0) */ -char INT13_ElTorito_NoEmuCDROMDrive = 0; + // LOG_MSG("VFD write sector: CHS %u/%u/%u",cylinder,head,sector); + + if (req_sector_size == 0) + req_sector_size = sector_size; + + ent = findSector(head,cylinder,sector,req_sector_size); + if (ent == NULL) return 0x05; + if (ent->getSectorSize() != req_sector_size) return 0x05; + + if (ent->hasSectorData()) { + fseek(diskimg,(long)ent->data_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; + if (fwrite(data,req_sector_size,1,diskimg) != 1) return 0x05; + return 0; + } + else if (ent->hasFill()) { + bool isfill = false; + + /* well, is the data provided one character repeated? + * note the format cannot represent a fill byte of 0xFF */ + if (((unsigned char*)data)[0] != 0xFF) { + unsigned int i=1; + + do { + if (((unsigned char*)data)[i] == ((unsigned char*)data)[0]) { + if ((++i) == req_sector_size) { + isfill = true; + break; // yes! + } + } + else { + break; // nope + } + } while (1); + } + + if (ent->entry_offset == 0) return 0x05; + + if (isfill) { + fseek(diskimg,(long)ent->entry_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->entry_offset) return 0x05; + if (fread(tmp,12,1,diskimg) != 1) return 0x05; + + tmp[0x04] = ((unsigned char*)data)[0]; // change the fill byte + + LOG_MSG("VFD write: 'fill' sector changing fill byte to 0x%x",tmp[0x04]); + + fseek(diskimg,(long)ent->entry_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->entry_offset) return 0x05; + if (fwrite(tmp,12,1,diskimg) != 1) return 0x05; + } + else { + fseek(diskimg,0,SEEK_END); + new_offset = (unsigned long)ftell(diskimg); + + /* we have to change it from a fill sector to an actual sector */ + LOG_MSG("VFD write: changing 'fill' sector to one with data (data at %lu)",(unsigned long)new_offset); + + fseek(diskimg,(long)ent->entry_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->entry_offset) return 0x05; + if (fread(tmp,12,1,diskimg) != 1) return 0x05; + + tmp[0x00] = ent->track; + tmp[0x01] = ent->head; + tmp[0x02] = ent->sector; + tmp[0x03] = ent->sizebyte; + tmp[0x04] = 0xFF; // no longer a fill byte + tmp[0x05] = 0x00; // TODO ?? + tmp[0x06] = 0x00; // TODO ?? + tmp[0x07] = 0x00; // TODO ?? + *((uint32_t*)(tmp+8)) = new_offset; + ent->fillbyte = 0xFF; + ent->data_offset = (uint32_t)new_offset; + + fseek(diskimg,(long)ent->entry_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->entry_offset) return 0x05; + if (fwrite(tmp,12,1,diskimg) != 1) return 0x05; + + fseek(diskimg,(long)ent->data_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; + if (fwrite(data,req_sector_size,1,diskimg) != 1) return 0x05; + } + } + + return 0x05; + } + + uint8_t imageDiskVFD::Write_AbsoluteSector(uint32_t sectnum,const void *data) { + unsigned int c,h,s; + + if (sectors == 0 || heads == 0) + return 0x05; + + s = (sectnum % sectors) + 1; + h = (sectnum / sectors) % heads; + c = (sectnum / sectors / heads); -bool GetMSCDEXDrive(unsigned char drive_letter, CDROM_Interface **_cdrom); + _driveUsed = true; + return Write_Sector(h,c,s,data); + } + + imageDiskVFD::imageDiskVFD(FILE *imgFile, const char *imgName, uint32_t imgSizeK, bool isHardDisk) : imageDisk(ID_VFD) { + (void)isHardDisk;//UNUSED + unsigned char tmp[16]; + + heads = 1; + cylinders = 0; + image_base = 0; + sectors = 0; + active = false; + sector_size = 0; + reserved_cylinders = 0; + diskSizeK = imgSizeK; + diskimg = imgFile; + + if (imgName != NULL) + diskname = imgName; + + // NOTES: + // + // +0x000: "VFD1.00" + // +0x0DC: array of 12-byte entries each describing a sector + // + // Each entry: + // +0x0: track + // +0x1: head + // +0x2: sector + // +0x3: sector size (128 << this byte) + // +0x4: fill byte, or 0xFF + // +0x5: unknown + // +0x6: unknown + // +0x7: unknown + // +0x8: absolute data offset (32-bit integer) or 0xFFFFFFFF if the entire sector is that fill byte + fseek(diskimg,0,SEEK_SET); + memset(tmp,0,8); + size_t readResult = fread(tmp,1,8,diskimg); + if (readResult != 8) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in imageDiskVFD constructor\n"); + return; + } + + if (!memcmp(tmp,"VFD1.",5)) { + uint32_t stop_at = 0xC3FC; + unsigned long entof; + + // load table. + // we have to determine as we go where to stop reading. + // the source of info I read assumes the whole header (and table) + // is 0xC3FC bytes. I'm not inclined to assume that, so we go by + // that OR the first sector offset whichever is smaller. + // the table seems to trail off into a long series of 0xFF at the end. + fseek(diskimg,0xDC,SEEK_SET); + while ((entof=((unsigned long)ftell(diskimg)+12ul)) <= stop_at) { + memset(tmp,0xFF,12); + readResult = fread(tmp,12,1,diskimg); + if (readResult != 1) { + LOG(LOG_IO, LOG_ERROR) ("Reading error in imageDiskVFD constructor\n"); + return; + } + + if (!memcmp(tmp,"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF",12)) + continue; + if (!memcmp(tmp,"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",12)) + continue; + + struct vfdentry v; + + v.track = tmp[0]; + v.head = tmp[1]; + v.sector = tmp[2]; + v.sizebyte = tmp[3]; + v.fillbyte = tmp[4]; + v.data_offset = *((uint32_t*)(tmp+8)); + v.entry_offset = (uint32_t)entof; + + // maybe the table can end sooner than 0xC3FC? + // if we see sectors appear at an offset lower than our stop_at point + // then adjust the stop_at point. assume the table cannot mix with + // sector data. + if (v.hasSectorData()) { + if (stop_at > v.data_offset) + stop_at = v.data_offset; + } + + dents.push_back(v); + + LOG_MSG("VFD entry: track=%u head=%u sector=%u size=%u fill=0x%2X has_data=%u has_fill=%u entoff=%lu dataoff=%lu", + v.track, + v.head, + v.sector, + v.getSectorSize(), + v.fillbyte, + v.hasSectorData(), + v.hasFill(), + (unsigned long)v.entry_offset, + (unsigned long)v.data_offset); + } + + if (!dents.empty()) { + /* okay, now to figure out what the geometry of the disk is. + * we cannot just work from an "absolute" disk image model + * because there's no VFD header to just say what the geometry is. + * Like the IBM PC BIOS, we have to look at the disk and figure out + * which geometry to apply to it, even if the FDD format allows + * sectors on other tracks to have wild out of range sector, track, + * and head numbers or odd sized sectors. + * + * First, determine sector size according to the boot sector. */ + const vfdentry *ent; + + ent = findSector(/*head*/0,/*track*/0,/*sector*/1,~0U); + if (ent != NULL) { + if (ent->sizebyte <= 3) /* x <= 1024 */ + sector_size = ent->getSectorSize(); + } + + /* oh yeah right, sure. + * I suppose you're one of those FDD images where the sector size is 128 bytes/sector + * in the boot sector and the rest is 256 bytes/sector elsewhere. I have no idea why + * but quite a few FDD images have this arrangement. */ + if (sector_size != 0 && sector_size < 512) { + ent = findSector(/*head*/0,/*track*/1,/*sector*/1,~0U); + if (ent != NULL) { + if (ent->sizebyte <= 3) { /* x <= 1024 */ + unsigned int nsz = ent->getSectorSize(); + if (sector_size != nsz) + LOG_MSG("VFD warning: sector size changes between track 0 and 1"); + if (sector_size < nsz) + sector_size = nsz; + } + } + } + + uint8_t i; + if (sector_size != 0) { + i=0; + while (DiskGeometryList[i].ksize != 0) { + const diskGeo &diskent = DiskGeometryList[i]; + + if (diskent.bytespersect == sector_size) { + ent = findSector(0,0,diskent.secttrack); + if (ent != NULL) { + LOG_MSG("VFD disk probe: %u/%u/%u exists",0,0,diskent.secttrack); + if (sectors < diskent.secttrack) + sectors = diskent.secttrack; + } + } + + i++; + } + } + + if (sector_size != 0 && sectors != 0) { + i=0; + while (DiskGeometryList[i].ksize != 0) { + const diskGeo &diskent = DiskGeometryList[i]; + + if (diskent.bytespersect == sector_size && diskent.secttrack >= sectors) { + ent = findSector(0,diskent.cylcount-1,sectors); + if (ent != NULL) { + LOG_MSG("VFD disk probe: %u/%u/%u exists",0,diskent.cylcount-1,sectors); + if (cylinders < diskent.cylcount) + cylinders = diskent.cylcount; + } + } + + i++; + } + } + + if (sector_size != 0 && sectors != 0 && cylinders != 0) { + ent = findSector(1,0,sectors); + if (ent != NULL) { + LOG_MSG("VFD disk probe: %u/%u/%u exists",1,0,sectors); + heads = 2; + } + } + + // TODO: drive_fat.cpp should use an extension to this API to allow changing the sectors/track + // according to what it reads from the MS-DOS BIOS parameter block, just like real MS-DOS. + // This would allow better representation of strange disk formats such as the "extended" + // floppy format that Microsoft used to use for Word 95 and Windows 95 install floppies. + + LOG_MSG("VFD geometry detection: C/H/S %u/%u/%u %u bytes/sector", + cylinders, heads, sectors, sector_size); + + bool founddisk = false; + if (sector_size != 0 && sectors != 0 && cylinders != 0 && heads != 0) + founddisk = true; + + if(!founddisk) { + active = false; + } else { + incrementFDD(); + } + } + } + } + + imageDiskVFD::~imageDiskVFD() { + if(diskimg != NULL) { + fclose(diskimg); + diskimg=NULL; + } + } + + // D88 *.D88 floppy disk format support + + enum { + D88_TRACKMAX = 164, + D88_HEADERSIZE = 0x20 + (D88_TRACKMAX * 4) + }; + + #pragma pack(push,1) + typedef struct D88HEAD { + char fd_name[17]; // +0x00 Disk Name + unsigned char reserved1[9]; // +0x11 Reserved + unsigned char protect; // +0x1A Write Protect bit:4 + unsigned char fd_type; // +0x1B Disk Format + uint32_t fd_size; // +0x1C Disk Size + uint32_t trackp[D88_TRACKMAX]; // +0x20 164 x 4 = 656 = 0x290 + } D88HEAD; // =0x2B0 total + + typedef struct D88SEC { + unsigned char c; // +0x00 + unsigned char h; // +0x01 + unsigned char r; // +0x02 + unsigned char n; // +0x03 + uint16_t sectors; // +0x04 Sector Count + unsigned char mfm_flg; // +0x06 sides + unsigned char del_flg; // +0x07 DELETED DATA + unsigned char stat; // +0x08 STATUS (FDC ret) + unsigned char seektime; // +0x09 Seek Time + unsigned char reserved[3]; // +0x0A Reserved + unsigned char rpm_flg; // +0x0D rpm 0:1.2 1:1.44 + uint16_t size; // +0x0E Sector Size + // + } D88SEC; // =0x10 total + #pragma pack(pop) + + uint8_t imageDiskD88::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { + const vfdentry *ent; + + if (req_sector_size == 0) + req_sector_size = sector_size; + + // LOG_MSG("D88 read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); + + ent = findSector(head,cylinder,sector,req_sector_size); + if (ent == NULL) return 0x05; + if (ent->getSectorSize() != req_sector_size) return 0x05; + + fseek(diskimg,(long)ent->data_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; + if (fread(data,req_sector_size,1,diskimg) != 1) return 0x05; - -static Bitu INT13_DiskHandler(void) { - uint16_t segat, bufptr; - uint8_t sectbuf[2048/*CD-ROM support*/]; - uint8_t drivenum; - Bitu i,t; - last_drive = reg_dl; - drivenum = GetDosDriveNumber(reg_dl); - bool any_images = false; - for(i = 0;i < MAX_DISK_IMAGES;i++) { - if(imageDiskList[i]) any_images=true; - } - - // unconditionally enable the interrupt flag - CALLBACK_SIF(true); - - /* map out functions 0x40-0x48 if not emulating INT 13h extensions */ - if (!int13_extensions_enable && reg_ah >= 0x40 && reg_ah <= 0x48) { - LOG_MSG("Warning: Guest is attempting to use INT 13h extensions (AH=0x%02X). Set 'int 13 extensions=1' if you want to enable them.\n",reg_ah); - reg_ah=0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - - //drivenum = 0; - //LOG_MSG("INT13: Function %x called on drive %x (dos drive %d)", reg_ah, reg_dl, drivenum); - - // NOTE: the 0xff error code returned in some cases is questionable; 0x01 seems more correct - switch(reg_ah) { - case 0x0: /* Reset disk */ - { - /* if there aren't any diskimages (so only localdrives and virtual drives) - * always succeed on reset disk. If there are diskimages then and only then - * do real checks - */ - if (any_images && driveInactive(drivenum)) { - /* driveInactive sets carry flag if the specified drive is not available */ - if ((machine==MCH_CGA) || (machine==MCH_AMSTRAD) || (machine==MCH_PCJR)) { - /* those bioses call floppy drive reset for invalid drive values */ - if (((imageDiskList[0]) && (imageDiskList[0]->active)) || ((imageDiskList[1]) && (imageDiskList[1]->active))) { - if (machine!=MCH_PCJR && reg_dl<0x80) reg_ip++; - last_status = 0x00; - CALLBACK_SCF(false); - } - } - return CBRET_NONE; - } - if (machine!=MCH_PCJR && reg_dl<0x80) reg_ip++; - if (reg_dl >= 0x80) IDE_ResetDiskByBIOS(reg_dl); - last_status = 0x00; - CALLBACK_SCF(false); - } - break; - case 0x1: /* Get status of last operation */ - - if(last_status != 0x00) { - reg_ah = last_status; - CALLBACK_SCF(true); - } else { - reg_ah = 0x00; - CALLBACK_SCF(false); - } - break; - case 0x2: /* Read sectors */ - if (reg_al==0) { - reg_ah = 0x01; - CALLBACK_SCF(true); - return CBRET_NONE; - } - if (drivenum >= MAX_DISK_IMAGES || imageDiskList[drivenum] == NULL) { - if (drivenum >= DOS_DRIVES || !Drives[drivenum] || Drives[drivenum]->isRemovable()) { - reg_ah = 0x01; - CALLBACK_SCF(true); - return CBRET_NONE; - } - // Inherit the Earth cdrom and Amberstar use it as a disk test - if (((reg_dl&0x80)==0x80) && (reg_dh==0) && ((reg_cl&0x3f)==1)) { - if (reg_ch==0) { - // write some MBR data into buffer for Amberstar installer - real_writeb(SegValue(es),reg_bx+0x1be,0x80); // first partition is active - real_writeb(SegValue(es),reg_bx+0x1c2,0x06); // first partition is FAT16B - } - reg_ah = 0; - CALLBACK_SCF(false); - return CBRET_NONE; - } - } - if (driveInactive(drivenum)) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - - /* INT 13h is limited to 512 bytes/sector (as far as I know). - * The sector buffer in this function is limited to 512 bytes/sector, - * so this is also a protection against overrunning the stack if you - * mount a PC-98 disk image (1024 bytes/sector) and try to read it with INT 13h. */ - if (imageDiskList[drivenum]->sector_size > sizeof(sectbuf)) { - LOG(LOG_MISC,LOG_DEBUG)("INT 13h: Read failed because disk bytes/sector on drive %c is too large",(char)drivenum+'A'); - - imageDiskChange[drivenum] = false; - - reg_ah = 0x80; /* timeout */ - CALLBACK_SCF(true); - return CBRET_NONE; - } - - /* If the disk changed, the first INT 13h read will signal an error and set AH = 0x06 to indicate disk change */ - if (drivenum < 2 && imageDiskChange[drivenum]) { - LOG(LOG_MISC,LOG_DEBUG)("INT 13h: Failing first read of drive %c to indicate disk change",(char)drivenum+'A'); - - imageDiskChange[drivenum] = false; - - reg_ah = 0x06; /* diskette changed or removed */ - CALLBACK_SCF(true); - return CBRET_NONE; - } - - segat = SegValue(es); - bufptr = reg_bx; - for(i=0;iRead_Sector((uint32_t)reg_dh, (uint32_t)(reg_ch | ((reg_cl & 0xc0)<< 2)), (uint32_t)((reg_cl & 63)+i), sectbuf); - - if (drivenum < 2) - diskio_delay(512, 0); // Floppy - else - diskio_delay(512); - - /* IDE emulation: simulate change of IDE state that would occur on a real machine after INT 13h */ - IDE_EmuINT13DiskReadByBIOS(reg_dl, (uint32_t)(reg_ch | ((reg_cl & 0xc0)<< 2)), (uint32_t)reg_dh, (uint32_t)((reg_cl & 63)+i)); - - if((last_status != 0x00) || killRead) { - LOG_MSG("Error in disk read"); - killRead = false; - reg_ah = 0x04; - CALLBACK_SCF(true); - return CBRET_NONE; - } - for(t=0;t<512;t++) { - real_writeb(segat,bufptr,sectbuf[t]); - bufptr++; - } - } - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x3: /* Write sectors */ - - if(driveInactive(drivenum) || !imageDiskList[drivenum]) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - - /* INT 13h is limited to 512 bytes/sector (as far as I know). - * The sector buffer in this function is limited to 512 bytes/sector, - * so this is also a protection against overrunning the stack if you - * mount a PC-98 disk image (1024 bytes/sector) and try to read it with INT 13h. */ - if (imageDiskList[drivenum]->sector_size > sizeof(sectbuf)) { - LOG(LOG_MISC,LOG_DEBUG)("INT 13h: Write failed because disk bytes/sector on drive %c is too large",(char)drivenum+'A'); - - imageDiskChange[drivenum] = false; - - reg_ah = 0x80; /* timeout */ - CALLBACK_SCF(true); - return CBRET_NONE; - } - - bufptr = reg_bx; - for(i=0;igetSectSize();t++) { - sectbuf[t] = real_readb(SegValue(es),bufptr); - bufptr++; - } - - if(drivenum < 2) - diskio_delay(512, 0); // Floppy - else - diskio_delay(512); - - last_status = imageDiskList[drivenum]->Write_Sector((uint32_t)reg_dh, (uint32_t)(reg_ch | ((reg_cl & 0xc0) << 2)), (uint32_t)((reg_cl & 63) + i), §buf[0]); - if(last_status != 0x00) { - CALLBACK_SCF(true); - return CBRET_NONE; - } - } - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x04: /* Verify sectors */ - if (reg_al==0) { - reg_ah = 0x01; - CALLBACK_SCF(true); - return CBRET_NONE; - } - if(driveInactive(drivenum)) { - reg_ah = last_status; - return CBRET_NONE; - } - - /* TODO: Finish coding this section */ - /* - segat = SegValue(es); - bufptr = reg_bx; - for(i=0;iRead_Sector((uint32_t)reg_dh, (uint32_t)(reg_ch | ((reg_cl & 0xc0)<< 2)), (uint32_t)((reg_cl & 63)+i), sectbuf); - if(last_status != 0x00) { - LOG_MSG("Error in disk read"); - CALLBACK_SCF(true); - return CBRET_NONE; - } - for(t=0;t<512;t++) { - real_writeb(segat,bufptr,sectbuf[t]); - bufptr++; - } - }*/ - reg_ah = 0x00; - //Qbix: The following codes don't match my specs. al should be number of sector verified - //reg_al = 0x10; /* CRC verify failed */ - //reg_al = 0x00; /* CRC verify succeeded */ - CALLBACK_SCF(false); - - break; - case 0x05: /* Format track */ - /* ignore it. I just fucking want FORMAT.COM to write the FAT structure for God's sake */ - LOG_MSG("WARNING: Format track ignored\n"); - if (driveInactive(drivenum)) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - CALLBACK_SCF(false); - reg_ah = 0x00; - break; - case 0x06: /* Format track set bad sector flags */ - /* ignore it. I just fucking want FORMAT.COM to write the FAT structure for God's sake */ - LOG_MSG("WARNING: Format track set bad sector flags ignored (6)\n"); - if (driveInactive(drivenum)) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - CALLBACK_SCF(false); - reg_ah = 0x00; - break; - case 0x07: /* Format track set bad sector flags */ - /* ignore it. I just fucking want FORMAT.COM to write the FAT structure for God's sake */ - LOG_MSG("WARNING: Format track set bad sector flags ignored (7)\n"); - if (driveInactive(drivenum)) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - CALLBACK_SCF(false); - reg_ah = 0x00; - break; - case 0x08: /* Get drive parameters */ - if(driveInactive(drivenum)) { - last_status = 0x07; - reg_ah = last_status; - CALLBACK_SCF(true); - return CBRET_NONE; - } - reg_ax = 0x00; - reg_bl = imageDiskList[drivenum]->GetBiosType(); - uint32_t tmpheads, tmpcyl, tmpsect, tmpsize; - imageDiskList[drivenum]->Get_Geometry(&tmpheads, &tmpcyl, &tmpsect, &tmpsize); - if (tmpcyl==0) LOG(LOG_BIOS,LOG_ERROR)("INT13 DrivParm: cylinder count zero!"); - else tmpcyl--; // cylinder count -> max cylinder - if (tmpheads==0) LOG(LOG_BIOS,LOG_ERROR)("INT13 DrivParm: head count zero!"); - else tmpheads--; // head count -> max head - - /* older BIOSes were known to subtract 1 or 2 additional "reserved" cylinders. - * some code, such as Windows 3.1 WDCTRL, might assume that fact. emulate that here */ - { - uint32_t reserv = imageDiskList[drivenum]->Get_Reserved_Cylinders(); - if (tmpcyl > reserv) tmpcyl -= reserv; - else tmpcyl = 0; - } - - reg_ch = (uint8_t)(tmpcyl & 0xff); - reg_cl = (uint8_t)(((tmpcyl >> 2) & 0xc0) | (tmpsect & 0x3f)); - reg_dh = (uint8_t)tmpheads; - last_status = 0x00; - if (reg_dl&0x80) { // harddisks - reg_dl = 0; - for (int index = 2; index < MAX_DISK_IMAGES; index++) { - if (imageDiskList[index] != NULL) reg_dl++; - } - } else { // floppy disks - reg_dl = 0; - if(imageDiskList[0] != NULL) reg_dl++; - if(imageDiskList[1] != NULL) reg_dl++; - } - CALLBACK_SCF(false); - break; - case 0x11: /* Recalibrate drive */ - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x15: /* Get disk type */ - /* Korean Powerdolls uses this to detect harddrives */ - LOG(LOG_BIOS,LOG_WARN)("INT13: Get disktype used!"); - if (any_images) { - if(driveInactive(drivenum)) { - last_status = 0x07; - reg_ah = last_status; - CALLBACK_SCF(true); - return CBRET_NONE; - } - imageDiskList[drivenum]->Get_Geometry(&tmpheads, &tmpcyl, &tmpsect, &tmpsize); - uint64_t largesize = tmpheads*tmpcyl*tmpsect*tmpsize; - largesize/=512; - uint32_t ts = static_cast(largesize); - reg_ah = (drivenum < 2)?(int13_disk_change_detect_enable?2:1):3; //With 2 for floppy MSDOS starts calling int 13 ah 16 - if(reg_ah == 3) { - reg_cx = static_cast(ts >>16); - reg_dx = static_cast(ts & 0xffff); - } - CALLBACK_SCF(false); - } else { - if (drivenum = dents.size()) + return NULL; + + std::vector::iterator i = dents.begin(); + + if (req_sector_size == 0) + req_sector_size = sector_size; + + while (i != dents.end()) { + const imageDiskD88::vfdentry &ent = *i; + + if (ent.head == head && + ent.track == track && + ent.sector == sector && + (ent.sector_size == req_sector_size || req_sector_size == ~0U)) + return &(*i); + + ++i; + } + + return NULL; + } + + uint8_t imageDiskD88::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { + const vfdentry *ent; + + if (req_sector_size == 0) + req_sector_size = sector_size; + + // LOG_MSG("D88 read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); + + ent = findSector(head,cylinder,sector,req_sector_size); + if (ent == NULL) return 0x05; + if (ent->getSectorSize() != req_sector_size) return 0x05; + + fseek(diskimg,(long)ent->data_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; + if (fwrite(data,req_sector_size,1,diskimg) != 1) return 0x05; - segat = dap.seg; - bufptr = dap.off; - for(i=0;i= 2048, "not big enough" ); - diskio_delay(512); - if (killRead || !src_drive->ReadSectorsHost(sectbuf, false, dap.sector+i, 1)) { - real_writew(SegValue(ds),reg_si+2,i); // According to RBIL this should update the number of blocks field to what was successfully transferred - LOG_MSG("Error in CDROM read"); - killRead = false; - reg_ah = 0x04; - CALLBACK_SCF(true); - return CBRET_NONE; - } + _driveUsed = true; + return 0; + } + + uint8_t imageDiskD88::Write_AbsoluteSector(uint32_t sectnum,const void *data) { + unsigned int c,h,s; + + if (sectors == 0 || heads == 0) + return 0x05; + + s = (sectnum % sectors) + 1; + h = (sectnum / sectors) % heads; + c = (sectnum / sectors / heads); - for(t=0;t<2048;t++) { - real_writeb(segat,bufptr,sectbuf[t]); - bufptr++; - } - } - reg_ah = 0x00; - CALLBACK_SCF(false); - return CBRET_NONE; - } + _driveUsed = true; + return Write_Sector(h,c,s,data); + } + + imageDiskD88::imageDiskD88(FILE *imgFile, const char *imgName, uint32_t imgSizeK, bool isHardDisk) : imageDisk(ID_D88) { + (void)isHardDisk;//UNUSED + D88HEAD head; + + fd_type_major = DISKTYPE_2D; + fd_type_minor = 0; + + assert(sizeof(D88HEAD) == 0x2B0); + assert(sizeof(D88SEC) == 0x10); + + heads = 0; + cylinders = 0; + image_base = 0; + sectors = 0; + active = false; + sector_size = 0; + reserved_cylinders = 0; + diskSizeK = imgSizeK; + diskimg = imgFile; + + if (imgName != NULL) + diskname = imgName; + + // NOTES: + // + // +0x000: D88 header + // +0x020: Offset of D88 tracks, per track + // +0x2B0: + // + // Track offsets are sequential, always + // + // Each track is an array of: + // + // ENTRY: + // + // + // + // Array of ENTRY from offset until next track + fseek(diskimg,0,SEEK_END); + off_t fsz = ftell(diskimg); + + fseek(diskimg,0,SEEK_SET); + if (fread(&head,sizeof(head),1,diskimg) != 1) return; + + // validate fd_size + if (host_readd((ConstHostPt)(&head.fd_size)) > (uint32_t)fsz) return; + + fd_type_major = head.fd_type >> 4U; + fd_type_minor = head.fd_type & 0xFU; + + // validate that none of the track offsets extend past the file + { + for (unsigned int i=0;i < D88_TRACKMAX;i++) { + uint32_t trackoff = host_readd((ConstHostPt)(&head.trackp[i])); + + if (trackoff == 0) continue; + + if ((trackoff + 16U) > (uint32_t)fsz) { + LOG_MSG("D88: track starts past end of file"); + return; + } + } + } + + // read each track + for (unsigned int track=0;track < D88_TRACKMAX;track++) { + uint32_t trackoff = host_readd((ConstHostPt)(&head.trackp[track])); + + if (trackoff != 0) { + fseek(diskimg, (long)trackoff, SEEK_SET); + if ((off_t)ftell(diskimg) != (off_t)trackoff) continue; + + D88SEC s; + unsigned int count = 0; + + do { + if (fread(&s,sizeof(s),1,diskimg) != 1) break; + + uint16_t sector_count = host_readw((ConstHostPt)(&s.sectors)); + uint16_t sector_size = host_readw((ConstHostPt)(&s.size)); + + if (sector_count == 0U || sector_size < 128U) break; + if (sector_count > 128U || sector_size > 16384U) break; + if (s.n > 8U) s.n = 8U; + + vfdentry vent; + vent.sector_size = 128 << s.n; + vent.data_offset = (uint32_t)ftell(diskimg); + vent.entry_offset = vent.data_offset - (uint32_t)16; + vent.track = s.c; + vent.head = s.h; + vent.sector = s.r; + + LOG_MSG("D88: trackindex=%u C/H/S/sz=%u/%u/%u/%u data-at=0x%lx", + track,vent.track,vent.head,vent.sector,vent.sector_size,(unsigned long)vent.data_offset); + + dents.push_back(vent); + if ((++count) >= sector_count) break; + + fseek(diskimg, (long)sector_size, SEEK_CUR); + } while (1); + } + } + + if (!dents.empty()) { + /* okay, now to figure out what the geometry of the disk is. + * we cannot just work from an "absolute" disk image model + * because there's no D88 header to just say what the geometry is. + * Like the IBM PC BIOS, we have to look at the disk and figure out + * which geometry to apply to it, even if the FDD format allows + * sectors on other tracks to have wild out of range sector, track, + * and head numbers or odd sized sectors. + * + * First, determine sector size according to the boot sector. */ + bool founddisk = false; + const vfdentry *ent; + + ent = findSector(/*head*/0,/*track*/0,/*sector*/1,~0U); + if (ent != NULL) { + if (ent->getSectorSize() <= 1024) /* x <= 1024 */ + sector_size = ent->getSectorSize(); + } + + /* oh yeah right, sure. + * I suppose you're one of those FDD images where the sector size is 128 bytes/sector + * in the boot sector and the rest is 256 bytes/sector elsewhere. I have no idea why + * but quite a few FDD images have this arrangement. */ + if (sector_size != 0 && sector_size < 512) { + ent = findSector(/*head*/0,/*track*/1,/*sector*/1,~0U); + if (ent != NULL) { + if (ent->getSectorSize() <= 1024) { /* x <= 1024 */ + unsigned int nsz = ent->getSectorSize(); + if (sector_size != nsz) + LOG_MSG("D88 warning: sector size changes between track 0 and 1"); + if (sector_size < nsz) + sector_size = nsz; + } + } + } + + if (sector_size != 0) { + unsigned int i = 0; + while (DiskGeometryList[i].ksize != 0) { + const diskGeo &diskent = DiskGeometryList[i]; + + if (diskent.bytespersect == sector_size) { + ent = findSector(0,0,diskent.secttrack); + if (ent != NULL) { + LOG_MSG("D88 disk probe: %u/%u/%u exists",0,0,diskent.secttrack); + if (sectors < diskent.secttrack) + sectors = diskent.secttrack; + } + } + + i++; + } + } + + if (sector_size != 0 && sectors != 0) { + unsigned int i = 0; + while (DiskGeometryList[i].ksize != 0) { + const diskGeo &diskent = DiskGeometryList[i]; + + if (diskent.bytespersect == sector_size && diskent.secttrack >= sectors) { + ent = findSector(0,diskent.cylcount-1,sectors); + if (ent != NULL) { + LOG_MSG("D88 disk probe: %u/%u/%u exists",0,diskent.cylcount-1,sectors); + if (cylinders < diskent.cylcount) + cylinders = diskent.cylcount; + } + } + + i++; + } + } + + if (sector_size != 0 && sectors != 0 && cylinders != 0) { + ent = findSector(1,0,sectors); + if (ent != NULL) { + LOG_MSG("D88 disk probe: %u/%u/%u exists",1,0,sectors); + heads = 2; + } + } + + // TODO: drive_fat.cpp should use an extension to this API to allow changing the sectors/track + // according to what it reads from the MS-DOS BIOS parameter block, just like real MS-DOS. + // This would allow better representation of strange disk formats such as the "extended" + // floppy format that Microsoft used to use for Word 95 and Windows 95 install floppies. + + LOG_MSG("D88 geometry detection: C/H/S %u/%u/%u %u bytes/sector", + cylinders, heads, sectors, sector_size); + + if (sector_size != 0 && sectors != 0 && cylinders != 0 && heads != 0) + founddisk = true; + + if(!founddisk) { + active = false; + } else { + incrementFDD(); + } + } + } + + imageDiskD88::~imageDiskD88() { + if(diskimg != NULL) { + fclose(diskimg); + diskimg=NULL; + } + } + + /*--------------------------------*/ + + uint8_t imageDiskNFD::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { + const vfdentry *ent; + + if (req_sector_size == 0) + req_sector_size = sector_size; + + // LOG_MSG("NFD read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); + + ent = findSector(head,cylinder,sector,req_sector_size); + if (ent == NULL) return 0x05; + if (ent->getSectorSize() != req_sector_size) return 0x05; + + fseek(diskimg,(long)ent->data_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; + if (fread(data,req_sector_size,1,diskimg) != 1) return 0x05; - if (!any_images) { - // Inherit the Earth cdrom (uses it as disk test) - if (((reg_dl&0x80)==0x80) && (reg_dh==0) && ((reg_cl&0x3f)==1)) { - reg_ah = 0; - CALLBACK_SCF(false); - return CBRET_NONE; - } - } - if (driveInactive(drivenum)) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - - segat = dap.seg; - bufptr = dap.off; - for(i=0;iRead_AbsoluteSector(dap.sector+i, sectbuf); - - if(drivenum < 2) - diskio_delay(512, 0); // Floppy - else - diskio_delay(512); - - IDE_EmuINT13DiskReadByBIOS_LBA(reg_dl,dap.sector+i); - - if((last_status != 0x00) || killRead) { - real_writew(SegValue(ds),reg_si+2,i); // According to RBIL this should update the number of blocks field to what was successfully transferred - LOG_MSG("Error in disk read"); - killRead = false; - reg_ah = 0x04; - CALLBACK_SCF(true); - return CBRET_NONE; - } - for(t=0;t<512;t++) { - real_writeb(segat,bufptr,sectbuf[t]); - bufptr++; - } - } - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x43: /* Extended Write Sectors to Drive */ - if(driveInactive(drivenum)) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - - /* Read Disk Address Packet */ - readDAP(SegValue(ds),reg_si); - - if (dap.num==0) { - reg_ah = 0x01; - CALLBACK_SCF(true); - return CBRET_NONE; - } - - bufptr = dap.off; - for(i=0;igetSectSize();t++) { - sectbuf[t] = real_readb(dap.seg,bufptr); - bufptr++; - } - - if(drivenum < 2) - diskio_delay(512, 0); // Floppy - else - diskio_delay(512); - - last_status = imageDiskList[drivenum]->Write_AbsoluteSector(dap.sector+i, §buf[0]); - if(last_status != 0x00) { - CALLBACK_SCF(true); - return CBRET_NONE; - } - } - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x44: /* Extended Verify Sectors [http://www.ctyme.com/intr/rb-0711.htm] */ - if(driveInactive(drivenum)) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - /* Just signal success, we don't actually verify anything */ - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - case 0x48: { /* get drive parameters */ - uint16_t bufsz; - - if(driveInactive(drivenum)) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - - segat = SegValue(ds); - bufptr = reg_si; - bufsz = real_readw(segat,bufptr+0); - if (bufsz < 0x1A) { - reg_ah = 0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - if (bufsz > 0x1E) bufsz = 0x1E; - else bufsz = 0x1A; - - tmpheads = tmpcyl = tmpsect = tmpsize = 0; - if (!IDE_GetPhysGeometry(drivenum,tmpheads,tmpcyl,tmpsect,tmpsize)) - imageDiskList[drivenum]->Get_Geometry(&tmpheads, &tmpcyl, &tmpsect, &tmpsize); - - real_writew(segat,bufptr+0x00,bufsz); - real_writew(segat,bufptr+0x02,0x0003); /* C/H/S valid, DMA boundary errors handled */ - real_writed(segat,bufptr+0x04,tmpcyl); - real_writed(segat,bufptr+0x08,tmpheads); - real_writed(segat,bufptr+0x0C,tmpsect); - real_writed(segat,bufptr+0x10,tmpcyl*tmpheads*tmpsect); - real_writed(segat,bufptr+0x14,0); - real_writew(segat,bufptr+0x18,512); - if (bufsz >= 0x1E) - real_writed(segat,bufptr+0x1A,0xFFFFFFFF); /* no EDD information available */ - - reg_ah = 0x00; - CALLBACK_SCF(false); - } break; - case 0x4B: /* Terminate disk emulation or get emulation status */ - /* NTS: Windows XP CD-ROM boot requires this call to work or else setup cannot find its own files. */ - if (reg_dl == 0x7F || (INT13_ElTorito_NoEmuDriveNumber != 0 && INT13_ElTorito_NoEmuDriveNumber == reg_dl)) { - if (reg_al <= 1) { - PhysPt p = (SegValue(ds) << 4) + reg_si; - phys_writeb(p + 0x00,0x13); - phys_writeb(p + 0x01,(0/*no emulation*/) + ((INT13_ElTorito_IDEInterface >= 0) ? 0x40 : 0)); - phys_writeb(p + 0x02,INT13_ElTorito_NoEmuDriveNumber); - if (INT13_ElTorito_IDEInterface >= 0) { - phys_writeb(p + 0x03,(unsigned char)(INT13_ElTorito_IDEInterface >> 1)); /* which IDE controller */ - phys_writew(p + 0x08,INT13_ElTorito_IDEInterface & 1);/* bit 0: IDE master/slave */ - } - else { - phys_writeb(p + 0x03,0); - phys_writew(p + 0x08,0); - } - phys_writed(p + 0x04,0); - phys_writew(p + 0x0A,0); - phys_writew(p + 0x0C,0); - phys_writew(p + 0x0E,0); - phys_writeb(p + 0x10,0); - phys_writeb(p + 0x11,0); - phys_writeb(p + 0x12,0); - reg_ah = 0x00; - CALLBACK_SCF(false); - break; - } - else { - reg_ah=0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - } - else { - reg_ah=0xff; - CALLBACK_SCF(true); - return CBRET_NONE; - } - break; - default: - LOG(LOG_BIOS,LOG_ERROR)("INT13: Function %x called on drive %x (dos drive %d)", (int)reg_ah, (int)reg_dl, (int)drivenum); - reg_ah=0xff; - CALLBACK_SCF(true); - } - return CBRET_NONE; -} - -void CALLBACK_DeAllocate(Bitu in); - -void BIOS_UnsetupDisks(void) { - if (call_int13 != 0) { - CALLBACK_DeAllocate(call_int13); - RealSetVec(0x13,0); /* zero INT 13h for now */ - call_int13 = 0; - } - if (diskparm0 != 0) { - CALLBACK_DeAllocate(diskparm0); - diskparm0 = 0; - } - if (diskparm1 != 0) { - CALLBACK_DeAllocate(diskparm1); - diskparm1 = 0; - } -} - -void BIOS_SetupDisks(void) { - unsigned int i; - - if (IS_PC98_ARCH) { - // TODO - return; - } - -/* TODO Start the time correctly */ - call_int13=CALLBACK_Allocate(); - CALLBACK_Setup(call_int13,&INT13_DiskHandler,CB_INT13,"Int 13 Bios disk"); - RealSetVec(0x13,CALLBACK_RealPointer(call_int13)); - - //release the drives after a soft reset - if ((!bootguest&&(bootvm||!use_quick_reboot))||bootdrive<0) FreeBIOSDiskList(); - - /* FIXME: Um... these aren't callbacks. Why are they allocated as callbacks? We have ROM general allocation now. */ - diskparm0 = CALLBACK_Allocate(); - CALLBACK_SetDescription(diskparm0,"BIOS Disk 0 parameter table"); - diskparm1 = CALLBACK_Allocate(); - CALLBACK_SetDescription(diskparm1,"BIOS Disk 1 parameter table"); - swapPosition = 0; - - RealSetVec(0x41,CALLBACK_RealPointer(diskparm0)); - RealSetVec(0x46,CALLBACK_RealPointer(diskparm1)); - - PhysPt dp0physaddr=CALLBACK_PhysPointer(diskparm0); - PhysPt dp1physaddr=CALLBACK_PhysPointer(diskparm1); - for(i=0;i<16;i++) { - phys_writeb(dp0physaddr+i,0); - phys_writeb(dp1physaddr+i,0); - } - - imgDTASeg = 0; - -/* Setup the Bios Area */ - mem_writeb(BIOS_HARDDISK_COUNT,2); - - killRead = false; - swapping_requested = false; -} - -// VFD *.FDD floppy disk format support - -uint8_t imageDiskVFD::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { - const vfdentry *ent; - - if (req_sector_size == 0) - req_sector_size = sector_size; - -// LOG_MSG("VFD read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); - - ent = findSector(head,cylinder,sector,req_sector_size); - if (ent == NULL) return 0x05; - if (ent->getSectorSize() != req_sector_size) return 0x05; - - if (ent->hasSectorData()) { - fseek(diskimg,(long)ent->data_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; - if (fread(data,req_sector_size,1,diskimg) != 1) return 0x05; - return 0; - } - else if (ent->hasFill()) { - memset(data,ent->fillbyte,req_sector_size); - return 0x00; - } - - return 0x05; -} - -uint8_t imageDiskVFD::Read_AbsoluteSector(uint32_t sectnum, void * data) { - unsigned int c,h,s; - - if (sectors == 0 || heads == 0) - return 0x05; - - s = (sectnum % sectors) + 1; - h = (sectnum / sectors) % heads; - c = (sectnum / sectors / heads); - return Read_Sector(h,c,s,data); -} - -imageDiskVFD::vfdentry *imageDiskVFD::findSector(uint8_t head,uint8_t track,uint8_t sector/*TODO: physical head?*/,unsigned int req_sector_size) { - std::vector::iterator i = dents.begin(); - unsigned char szb=0xFF; - - if (req_sector_size == 0) - req_sector_size = sector_size; - - if (req_sector_size != ~0U) { - unsigned int c = req_sector_size; - while (c >= 128U) { - c >>= 1U; - szb++; - } - -// LOG_MSG("req=%u c=%u szb=%u",req_sector_size,c,szb); - - if (szb > 8 || c != 64U) - return NULL; - } - - while (i != dents.end()) { - const imageDiskVFD::vfdentry &ent = *i; - - if (ent.head == head && - ent.track == track && - ent.sector == sector && - (ent.sizebyte == szb || req_sector_size == ~0U)) - return &(*i); - - ++i; - } - - return NULL; -} - -uint8_t imageDiskVFD::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { - unsigned long new_offset; - unsigned char tmp[12]; - vfdentry *ent; - -// LOG_MSG("VFD write sector: CHS %u/%u/%u",cylinder,head,sector); - - if (req_sector_size == 0) - req_sector_size = sector_size; - - ent = findSector(head,cylinder,sector,req_sector_size); - if (ent == NULL) return 0x05; - if (ent->getSectorSize() != req_sector_size) return 0x05; - - if (ent->hasSectorData()) { - fseek(diskimg,(long)ent->data_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; - if (fwrite(data,req_sector_size,1,diskimg) != 1) return 0x05; - return 0; - } - else if (ent->hasFill()) { - bool isfill = false; - - /* well, is the data provided one character repeated? - * note the format cannot represent a fill byte of 0xFF */ - if (((unsigned char*)data)[0] != 0xFF) { - unsigned int i=1; - - do { - if (((unsigned char*)data)[i] == ((unsigned char*)data)[0]) { - if ((++i) == req_sector_size) { - isfill = true; - break; // yes! - } - } - else { - break; // nope - } - } while (1); - } - - if (ent->entry_offset == 0) return 0x05; - - if (isfill) { - fseek(diskimg,(long)ent->entry_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->entry_offset) return 0x05; - if (fread(tmp,12,1,diskimg) != 1) return 0x05; - - tmp[0x04] = ((unsigned char*)data)[0]; // change the fill byte - - LOG_MSG("VFD write: 'fill' sector changing fill byte to 0x%x",tmp[0x04]); - - fseek(diskimg,(long)ent->entry_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->entry_offset) return 0x05; - if (fwrite(tmp,12,1,diskimg) != 1) return 0x05; - } - else { - fseek(diskimg,0,SEEK_END); - new_offset = (unsigned long)ftell(diskimg); - - /* we have to change it from a fill sector to an actual sector */ - LOG_MSG("VFD write: changing 'fill' sector to one with data (data at %lu)",(unsigned long)new_offset); - - fseek(diskimg,(long)ent->entry_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->entry_offset) return 0x05; - if (fread(tmp,12,1,diskimg) != 1) return 0x05; - - tmp[0x00] = ent->track; - tmp[0x01] = ent->head; - tmp[0x02] = ent->sector; - tmp[0x03] = ent->sizebyte; - tmp[0x04] = 0xFF; // no longer a fill byte - tmp[0x05] = 0x00; // TODO ?? - tmp[0x06] = 0x00; // TODO ?? - tmp[0x07] = 0x00; // TODO ?? - *((uint32_t*)(tmp+8)) = new_offset; - ent->fillbyte = 0xFF; - ent->data_offset = (uint32_t)new_offset; - - fseek(diskimg,(long)ent->entry_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->entry_offset) return 0x05; - if (fwrite(tmp,12,1,diskimg) != 1) return 0x05; - - fseek(diskimg,(long)ent->data_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; - if (fwrite(data,req_sector_size,1,diskimg) != 1) return 0x05; - } - } - - return 0x05; -} - -uint8_t imageDiskVFD::Write_AbsoluteSector(uint32_t sectnum,const void *data) { - unsigned int c,h,s; - - if (sectors == 0 || heads == 0) - return 0x05; - - s = (sectnum % sectors) + 1; - h = (sectnum / sectors) % heads; - c = (sectnum / sectors / heads); - return Write_Sector(h,c,s,data); -} - -imageDiskVFD::imageDiskVFD(FILE *imgFile, const char *imgName, uint32_t imgSizeK, bool isHardDisk) : imageDisk(ID_VFD) { - (void)isHardDisk;//UNUSED - unsigned char tmp[16]; - - heads = 1; - cylinders = 0; - image_base = 0; - sectors = 0; - active = false; - sector_size = 0; - reserved_cylinders = 0; - diskSizeK = imgSizeK; - diskimg = imgFile; - - if (imgName != NULL) - diskname = imgName; - - // NOTES: - // - // +0x000: "VFD1.00" - // +0x0DC: array of 12-byte entries each describing a sector - // - // Each entry: - // +0x0: track - // +0x1: head - // +0x2: sector - // +0x3: sector size (128 << this byte) - // +0x4: fill byte, or 0xFF - // +0x5: unknown - // +0x6: unknown - // +0x7: unknown - // +0x8: absolute data offset (32-bit integer) or 0xFFFFFFFF if the entire sector is that fill byte - fseek(diskimg,0,SEEK_SET); - memset(tmp,0,8); - size_t readResult = fread(tmp,1,8,diskimg); - if (readResult != 8) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in imageDiskVFD constructor\n"); - return; - } - - if (!memcmp(tmp,"VFD1.",5)) { - uint32_t stop_at = 0xC3FC; - unsigned long entof; - - // load table. - // we have to determine as we go where to stop reading. - // the source of info I read assumes the whole header (and table) - // is 0xC3FC bytes. I'm not inclined to assume that, so we go by - // that OR the first sector offset whichever is smaller. - // the table seems to trail off into a long series of 0xFF at the end. - fseek(diskimg,0xDC,SEEK_SET); - while ((entof=((unsigned long)ftell(diskimg)+12ul)) <= stop_at) { - memset(tmp,0xFF,12); - readResult = fread(tmp,12,1,diskimg); - if (readResult != 1) { - LOG(LOG_IO, LOG_ERROR) ("Reading error in imageDiskVFD constructor\n"); - return; - } - - if (!memcmp(tmp,"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF",12)) - continue; - if (!memcmp(tmp,"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",12)) - continue; - - struct vfdentry v; - - v.track = tmp[0]; - v.head = tmp[1]; - v.sector = tmp[2]; - v.sizebyte = tmp[3]; - v.fillbyte = tmp[4]; - v.data_offset = *((uint32_t*)(tmp+8)); - v.entry_offset = (uint32_t)entof; - - // maybe the table can end sooner than 0xC3FC? - // if we see sectors appear at an offset lower than our stop_at point - // then adjust the stop_at point. assume the table cannot mix with - // sector data. - if (v.hasSectorData()) { - if (stop_at > v.data_offset) - stop_at = v.data_offset; - } - - dents.push_back(v); - - LOG_MSG("VFD entry: track=%u head=%u sector=%u size=%u fill=0x%2X has_data=%u has_fill=%u entoff=%lu dataoff=%lu", - v.track, - v.head, - v.sector, - v.getSectorSize(), - v.fillbyte, - v.hasSectorData(), - v.hasFill(), - (unsigned long)v.entry_offset, - (unsigned long)v.data_offset); - } - - if (!dents.empty()) { - /* okay, now to figure out what the geometry of the disk is. - * we cannot just work from an "absolute" disk image model - * because there's no VFD header to just say what the geometry is. - * Like the IBM PC BIOS, we have to look at the disk and figure out - * which geometry to apply to it, even if the FDD format allows - * sectors on other tracks to have wild out of range sector, track, - * and head numbers or odd sized sectors. - * - * First, determine sector size according to the boot sector. */ - const vfdentry *ent; - - ent = findSector(/*head*/0,/*track*/0,/*sector*/1,~0U); - if (ent != NULL) { - if (ent->sizebyte <= 3) /* x <= 1024 */ - sector_size = ent->getSectorSize(); - } - - /* oh yeah right, sure. - * I suppose you're one of those FDD images where the sector size is 128 bytes/sector - * in the boot sector and the rest is 256 bytes/sector elsewhere. I have no idea why - * but quite a few FDD images have this arrangement. */ - if (sector_size != 0 && sector_size < 512) { - ent = findSector(/*head*/0,/*track*/1,/*sector*/1,~0U); - if (ent != NULL) { - if (ent->sizebyte <= 3) { /* x <= 1024 */ - unsigned int nsz = ent->getSectorSize(); - if (sector_size != nsz) - LOG_MSG("VFD warning: sector size changes between track 0 and 1"); - if (sector_size < nsz) - sector_size = nsz; - } - } - } - - uint8_t i; - if (sector_size != 0) { - i=0; - while (DiskGeometryList[i].ksize != 0) { - const diskGeo &diskent = DiskGeometryList[i]; - - if (diskent.bytespersect == sector_size) { - ent = findSector(0,0,diskent.secttrack); - if (ent != NULL) { - LOG_MSG("VFD disk probe: %u/%u/%u exists",0,0,diskent.secttrack); - if (sectors < diskent.secttrack) - sectors = diskent.secttrack; - } - } - - i++; - } - } - - if (sector_size != 0 && sectors != 0) { - i=0; - while (DiskGeometryList[i].ksize != 0) { - const diskGeo &diskent = DiskGeometryList[i]; - - if (diskent.bytespersect == sector_size && diskent.secttrack >= sectors) { - ent = findSector(0,diskent.cylcount-1,sectors); - if (ent != NULL) { - LOG_MSG("VFD disk probe: %u/%u/%u exists",0,diskent.cylcount-1,sectors); - if (cylinders < diskent.cylcount) - cylinders = diskent.cylcount; - } - } - - i++; - } - } - - if (sector_size != 0 && sectors != 0 && cylinders != 0) { - ent = findSector(1,0,sectors); - if (ent != NULL) { - LOG_MSG("VFD disk probe: %u/%u/%u exists",1,0,sectors); - heads = 2; - } - } - - // TODO: drive_fat.cpp should use an extension to this API to allow changing the sectors/track - // according to what it reads from the MS-DOS BIOS parameter block, just like real MS-DOS. - // This would allow better representation of strange disk formats such as the "extended" - // floppy format that Microsoft used to use for Word 95 and Windows 95 install floppies. - - LOG_MSG("VFD geometry detection: C/H/S %u/%u/%u %u bytes/sector", - cylinders, heads, sectors, sector_size); - - bool founddisk = false; - if (sector_size != 0 && sectors != 0 && cylinders != 0 && heads != 0) - founddisk = true; - - if(!founddisk) { - active = false; - } else { - incrementFDD(); - } - } - } -} - -imageDiskVFD::~imageDiskVFD() { - if(diskimg != NULL) { - fclose(diskimg); - diskimg=NULL; - } -} - -// D88 *.D88 floppy disk format support - -enum { - D88_TRACKMAX = 164, - D88_HEADERSIZE = 0x20 + (D88_TRACKMAX * 4) -}; - -#pragma pack(push,1) -typedef struct D88HEAD { - char fd_name[17]; // +0x00 Disk Name - unsigned char reserved1[9]; // +0x11 Reserved - unsigned char protect; // +0x1A Write Protect bit:4 - unsigned char fd_type; // +0x1B Disk Format - uint32_t fd_size; // +0x1C Disk Size - uint32_t trackp[D88_TRACKMAX]; // +0x20 164 x 4 = 656 = 0x290 -} D88HEAD; // =0x2B0 total - -typedef struct D88SEC { - unsigned char c; // +0x00 - unsigned char h; // +0x01 - unsigned char r; // +0x02 - unsigned char n; // +0x03 - uint16_t sectors; // +0x04 Sector Count - unsigned char mfm_flg; // +0x06 sides - unsigned char del_flg; // +0x07 DELETED DATA - unsigned char stat; // +0x08 STATUS (FDC ret) - unsigned char seektime; // +0x09 Seek Time - unsigned char reserved[3]; // +0x0A Reserved - unsigned char rpm_flg; // +0x0D rpm 0:1.2 1:1.44 - uint16_t size; // +0x0E Sector Size - // -} D88SEC; // =0x10 total -#pragma pack(pop) - -uint8_t imageDiskD88::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { - const vfdentry *ent; - - if (req_sector_size == 0) - req_sector_size = sector_size; - -// LOG_MSG("D88 read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); - - ent = findSector(head,cylinder,sector,req_sector_size); - if (ent == NULL) return 0x05; - if (ent->getSectorSize() != req_sector_size) return 0x05; - - fseek(diskimg,(long)ent->data_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; - if (fread(data,req_sector_size,1,diskimg) != 1) return 0x05; - return 0; -} - -uint8_t imageDiskD88::Read_AbsoluteSector(uint32_t sectnum, void * data) { - unsigned int c,h,s; - - if (sectors == 0 || heads == 0) - return 0x05; - - s = (sectnum % sectors) + 1; - h = (sectnum / sectors) % heads; - c = (sectnum / sectors / heads); - return Read_Sector(h,c,s,data); -} - -imageDiskD88::vfdentry *imageDiskD88::findSector(uint8_t head,uint8_t track,uint8_t sector/*TODO: physical head?*/,unsigned int req_sector_size) { - if ((size_t)track >= dents.size()) - return NULL; - - std::vector::iterator i = dents.begin(); - - if (req_sector_size == 0) - req_sector_size = sector_size; - - while (i != dents.end()) { - const imageDiskD88::vfdentry &ent = *i; - - if (ent.head == head && - ent.track == track && - ent.sector == sector && - (ent.sector_size == req_sector_size || req_sector_size == ~0U)) - return &(*i); - - ++i; - } - - return NULL; -} - -uint8_t imageDiskD88::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { - const vfdentry *ent; - - if (req_sector_size == 0) - req_sector_size = sector_size; - -// LOG_MSG("D88 read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); - - ent = findSector(head,cylinder,sector,req_sector_size); - if (ent == NULL) return 0x05; - if (ent->getSectorSize() != req_sector_size) return 0x05; - - fseek(diskimg,(long)ent->data_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; - if (fwrite(data,req_sector_size,1,diskimg) != 1) return 0x05; - return 0; -} - -uint8_t imageDiskD88::Write_AbsoluteSector(uint32_t sectnum,const void *data) { - unsigned int c,h,s; - - if (sectors == 0 || heads == 0) - return 0x05; - - s = (sectnum % sectors) + 1; - h = (sectnum / sectors) % heads; - c = (sectnum / sectors / heads); - return Write_Sector(h,c,s,data); -} - -imageDiskD88::imageDiskD88(FILE *imgFile, const char *imgName, uint32_t imgSizeK, bool isHardDisk) : imageDisk(ID_D88) { - (void)isHardDisk;//UNUSED - D88HEAD head; - - fd_type_major = DISKTYPE_2D; - fd_type_minor = 0; - - assert(sizeof(D88HEAD) == 0x2B0); - assert(sizeof(D88SEC) == 0x10); - - heads = 0; - cylinders = 0; - image_base = 0; - sectors = 0; - active = false; - sector_size = 0; - reserved_cylinders = 0; - diskSizeK = imgSizeK; - diskimg = imgFile; - - if (imgName != NULL) - diskname = imgName; - - // NOTES: - // - // +0x000: D88 header - // +0x020: Offset of D88 tracks, per track - // +0x2B0: - // - // Track offsets are sequential, always - // - // Each track is an array of: - // - // ENTRY: - // - // - // - // Array of ENTRY from offset until next track - fseek(diskimg,0,SEEK_END); - off_t fsz = ftell(diskimg); - - fseek(diskimg,0,SEEK_SET); - if (fread(&head,sizeof(head),1,diskimg) != 1) return; - - // validate fd_size - if (host_readd((ConstHostPt)(&head.fd_size)) > (uint32_t)fsz) return; - - fd_type_major = head.fd_type >> 4U; - fd_type_minor = head.fd_type & 0xFU; - - // validate that none of the track offsets extend past the file - { - for (unsigned int i=0;i < D88_TRACKMAX;i++) { - uint32_t trackoff = host_readd((ConstHostPt)(&head.trackp[i])); - - if (trackoff == 0) continue; - - if ((trackoff + 16U) > (uint32_t)fsz) { - LOG_MSG("D88: track starts past end of file"); - return; - } - } - } - - // read each track - for (unsigned int track=0;track < D88_TRACKMAX;track++) { - uint32_t trackoff = host_readd((ConstHostPt)(&head.trackp[track])); - - if (trackoff != 0) { - fseek(diskimg, (long)trackoff, SEEK_SET); - if ((off_t)ftell(diskimg) != (off_t)trackoff) continue; - - D88SEC s; - unsigned int count = 0; - - do { - if (fread(&s,sizeof(s),1,diskimg) != 1) break; - - uint16_t sector_count = host_readw((ConstHostPt)(&s.sectors)); - uint16_t sector_size = host_readw((ConstHostPt)(&s.size)); - - if (sector_count == 0U || sector_size < 128U) break; - if (sector_count > 128U || sector_size > 16384U) break; - if (s.n > 8U) s.n = 8U; - - vfdentry vent; - vent.sector_size = 128 << s.n; - vent.data_offset = (uint32_t)ftell(diskimg); - vent.entry_offset = vent.data_offset - (uint32_t)16; - vent.track = s.c; - vent.head = s.h; - vent.sector = s.r; - - LOG_MSG("D88: trackindex=%u C/H/S/sz=%u/%u/%u/%u data-at=0x%lx", - track,vent.track,vent.head,vent.sector,vent.sector_size,(unsigned long)vent.data_offset); - - dents.push_back(vent); - if ((++count) >= sector_count) break; - - fseek(diskimg, (long)sector_size, SEEK_CUR); - } while (1); - } - } - - if (!dents.empty()) { - /* okay, now to figure out what the geometry of the disk is. - * we cannot just work from an "absolute" disk image model - * because there's no D88 header to just say what the geometry is. - * Like the IBM PC BIOS, we have to look at the disk and figure out - * which geometry to apply to it, even if the FDD format allows - * sectors on other tracks to have wild out of range sector, track, - * and head numbers or odd sized sectors. - * - * First, determine sector size according to the boot sector. */ - bool founddisk = false; - const vfdentry *ent; - - ent = findSector(/*head*/0,/*track*/0,/*sector*/1,~0U); - if (ent != NULL) { - if (ent->getSectorSize() <= 1024) /* x <= 1024 */ - sector_size = ent->getSectorSize(); - } - - /* oh yeah right, sure. - * I suppose you're one of those FDD images where the sector size is 128 bytes/sector - * in the boot sector and the rest is 256 bytes/sector elsewhere. I have no idea why - * but quite a few FDD images have this arrangement. */ - if (sector_size != 0 && sector_size < 512) { - ent = findSector(/*head*/0,/*track*/1,/*sector*/1,~0U); - if (ent != NULL) { - if (ent->getSectorSize() <= 1024) { /* x <= 1024 */ - unsigned int nsz = ent->getSectorSize(); - if (sector_size != nsz) - LOG_MSG("D88 warning: sector size changes between track 0 and 1"); - if (sector_size < nsz) - sector_size = nsz; - } - } - } - - if (sector_size != 0) { - unsigned int i = 0; - while (DiskGeometryList[i].ksize != 0) { - const diskGeo &diskent = DiskGeometryList[i]; - - if (diskent.bytespersect == sector_size) { - ent = findSector(0,0,diskent.secttrack); - if (ent != NULL) { - LOG_MSG("D88 disk probe: %u/%u/%u exists",0,0,diskent.secttrack); - if (sectors < diskent.secttrack) - sectors = diskent.secttrack; - } - } - - i++; - } - } - - if (sector_size != 0 && sectors != 0) { - unsigned int i = 0; - while (DiskGeometryList[i].ksize != 0) { - const diskGeo &diskent = DiskGeometryList[i]; - - if (diskent.bytespersect == sector_size && diskent.secttrack >= sectors) { - ent = findSector(0,diskent.cylcount-1,sectors); - if (ent != NULL) { - LOG_MSG("D88 disk probe: %u/%u/%u exists",0,diskent.cylcount-1,sectors); - if (cylinders < diskent.cylcount) - cylinders = diskent.cylcount; - } - } - - i++; - } - } - - if (sector_size != 0 && sectors != 0 && cylinders != 0) { - ent = findSector(1,0,sectors); - if (ent != NULL) { - LOG_MSG("D88 disk probe: %u/%u/%u exists",1,0,sectors); - heads = 2; - } - } - - // TODO: drive_fat.cpp should use an extension to this API to allow changing the sectors/track - // according to what it reads from the MS-DOS BIOS parameter block, just like real MS-DOS. - // This would allow better representation of strange disk formats such as the "extended" - // floppy format that Microsoft used to use for Word 95 and Windows 95 install floppies. - - LOG_MSG("D88 geometry detection: C/H/S %u/%u/%u %u bytes/sector", - cylinders, heads, sectors, sector_size); - - if (sector_size != 0 && sectors != 0 && cylinders != 0 && heads != 0) - founddisk = true; - - if(!founddisk) { - active = false; - } else { - incrementFDD(); - } - } -} - -imageDiskD88::~imageDiskD88() { - if(diskimg != NULL) { - fclose(diskimg); - diskimg=NULL; - } -} - -/*--------------------------------*/ - -uint8_t imageDiskNFD::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { - const vfdentry *ent; - - if (req_sector_size == 0) - req_sector_size = sector_size; - -// LOG_MSG("NFD read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); - - ent = findSector(head,cylinder,sector,req_sector_size); - if (ent == NULL) return 0x05; - if (ent->getSectorSize() != req_sector_size) return 0x05; - - fseek(diskimg,(long)ent->data_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; - if (fread(data,req_sector_size,1,diskimg) != 1) return 0x05; - return 0; -} - -uint8_t imageDiskNFD::Read_AbsoluteSector(uint32_t sectnum, void * data) { - unsigned int c,h,s; - - if (sectors == 0 || heads == 0) - return 0x05; - - s = (sectnum % sectors) + 1; - h = (sectnum / sectors) % heads; - c = (sectnum / sectors / heads); - return Read_Sector(h,c,s,data); -} - -imageDiskNFD::vfdentry *imageDiskNFD::findSector(uint8_t head,uint8_t track,uint8_t sector/*TODO: physical head?*/,unsigned int req_sector_size) { - if ((size_t)track >= dents.size()) - return NULL; - - std::vector::iterator i = dents.begin(); - - if (req_sector_size == 0) - req_sector_size = sector_size; - - while (i != dents.end()) { - const imageDiskNFD::vfdentry &ent = *i; - - if (ent.head == head && - ent.track == track && - ent.sector == sector && - (ent.sector_size == req_sector_size || req_sector_size == ~0U)) - return &(*i); - - ++i; - } - - return NULL; -} - -uint8_t imageDiskNFD::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { - const vfdentry *ent; - - if (req_sector_size == 0) - req_sector_size = sector_size; - -// LOG_MSG("NFD read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); - - ent = findSector(head,cylinder,sector,req_sector_size); - if (ent == NULL) return 0x05; - if (ent->getSectorSize() != req_sector_size) return 0x05; - - fseek(diskimg,(long)ent->data_offset,SEEK_SET); - if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; - if (fwrite(data,req_sector_size,1,diskimg) != 1) return 0x05; - return 0; -} - -uint8_t imageDiskNFD::Write_AbsoluteSector(uint32_t sectnum,const void *data) { - unsigned int c,h,s; - - if (sectors == 0 || heads == 0) - return 0x05; - - s = (sectnum % sectors) + 1; - h = (sectnum / sectors) % heads; - c = (sectnum / sectors / heads); - return Write_Sector(h,c,s,data); -} - -imageDiskNFD::imageDiskNFD(FILE *imgFile, const char *imgName, uint32_t imgSizeK, bool isHardDisk, unsigned int revision) : imageDisk(ID_NFD) { - (void)isHardDisk;//UNUSED - union { - NFDHDR head; - NFDHDRR1 headr1; - }; // these occupy the same location of memory - - assert(sizeof(NFDHDR) == 0x120); - assert(sizeof(NFDHDRR1) == 0x3C0); - assert(sizeof(NFDHDR_ENTRY) == 0x10); - - heads = 0; - cylinders = 0; - image_base = 0; - sectors = 0; - active = false; - sector_size = 0; - reserved_cylinders = 0; - diskSizeK = imgSizeK; - diskimg = imgFile; - - if (imgName != NULL) - diskname = imgName; - - // NOTES: - // - // +0x000: NFD header - // +0x020: Offset of NFD tracks, per track - // +0x2B0: - // - // Track offsets are sequential, always - // - // Each track is an array of: - // - // ENTRY: - // - // - // - // Array of ENTRY from offset until next track - fseek(diskimg,0,SEEK_END); - off_t fsz = ftell(diskimg); - - fseek(diskimg,0,SEEK_SET); - if (revision == 0) { - if (fread(&head,sizeof(head),1,diskimg) != 1) return; - } - else if (revision == 1) { - if (fread(&headr1,sizeof(headr1),1,diskimg) != 1) return; - } - else { - abort(); - } - - // validate fd_size - if (host_readd((ConstHostPt)(&head.headersize)) < sizeof(head)) return; - if (host_readd((ConstHostPt)(&head.headersize)) > (uint32_t)fsz) return; - - unsigned int data_offset = host_readd((ConstHostPt)(&head.headersize)); - - std::vector< std::pair > seclist; - - if (revision == 0) { - unsigned int secents = (host_readd((ConstHostPt)(&head.headersize)) - sizeof(head)) / sizeof(NFDHDR_ENTRY); - if (secents == 0) return; - secents--; - if (secents == 0) return; - - for (unsigned int i=0;i < secents;i++) { - uint32_t ofs = (uint32_t)ftell(diskimg); - NFDHDR_ENTRY e; - - if (fread(&e,sizeof(e),1,diskimg) != 1) return; - seclist.push_back( std::pair(ofs,e) ); - - if (e.log_cyl == 0xFF || e.log_head == 0xFF || e.log_rec == 0xFF || e.sec_len_pow2 > 7) - continue; - - LOG_MSG("NFD %u/%u: ofs=%lu data=%lu cyl=%u head=%u sec=%u len=%u", - (unsigned int)i, - (unsigned int)secents, - (unsigned long)ofs, - (unsigned long)data_offset, - e.log_cyl, - e.log_head, - e.log_rec, - 128 << e.sec_len_pow2); - - vfdentry vent; - vent.sector_size = 128 << e.sec_len_pow2; - vent.data_offset = (uint32_t)data_offset; - vent.entry_offset = ofs; - vent.track = e.log_cyl; - vent.head = e.log_head; - vent.sector = e.log_rec; - dents.push_back(vent); - - data_offset += 128u << e.sec_len_pow2; - if (data_offset > (unsigned int)fsz) return; - } - } - else { - /* R1 has an array of offsets to where each tracks begins. - * The end of the track is an entry like 0x1A 0x00 0x00 0x00 0x00 0x00 0x00 .... */ - /* The R1 images I have as reference always have offsets in ascending order. */ - for (unsigned int ti=0;ti < 164;ti++) { - uint32_t trkoff = host_readd((ConstHostPt)(&headr1.trackheads[ti])); - - if (trkoff == 0) break; - - fseek(diskimg,(long)trkoff,SEEK_SET); - if ((off_t)ftell(diskimg) != (off_t)trkoff) return; - - NFDHDR_ENTRY e; - - // track id - if (fread(&e,sizeof(e),1,diskimg) != 1) return; - unsigned int sectors = host_readw((ConstHostPt)(&e) + 0); - unsigned int diagcount = host_readw((ConstHostPt)(&e) + 2); - - LOG_MSG("NFD R1 track ent %u offset %lu sectors %u diag %u",ti,(unsigned long)trkoff,sectors,diagcount); - - for (unsigned int s=0;s < sectors;s++) { - uint32_t ofs = (uint32_t)ftell(diskimg); - - if (fread(&e,sizeof(e),1,diskimg) != 1) return; - - LOG_MSG("NFD %u/%u: ofs=%lu data=%lu cyl=%u head=%u sec=%u len=%u rep=%u", - s, - sectors, - (unsigned long)ofs, - (unsigned long)data_offset, - e.log_cyl, - e.log_head, - e.log_rec, - 128 << e.sec_len_pow2, - e.byRetry); - - vfdentry vent; - vent.sector_size = 128 << e.sec_len_pow2; - vent.data_offset = (uint32_t)data_offset; - vent.entry_offset = ofs; - vent.track = e.log_cyl; - vent.head = e.log_head; - vent.sector = e.log_rec; - dents.push_back(vent); - - data_offset += 128u << e.sec_len_pow2; - if (data_offset > (unsigned int)fsz) return; - } - - for (unsigned int d=0;d < diagcount;d++) { - if (fread(&e,sizeof(e),1,diskimg) != 1) return; - - unsigned int retry = e.byRetry; - unsigned int len = host_readd((ConstHostPt)(&e) + 10); - - LOG_MSG("NFD diag %u/%u: retry=%u len=%u data=%lu",d,diagcount,retry,len,(unsigned long)data_offset); - - data_offset += (1+retry) * len; - } - } - } - - if (!dents.empty()) { - /* okay, now to figure out what the geometry of the disk is. - * we cannot just work from an "absolute" disk image model - * because there's no NFD header to just say what the geometry is. - * Like the IBM PC BIOS, we have to look at the disk and figure out - * which geometry to apply to it, even if the FDD format allows - * sectors on other tracks to have wild out of range sector, track, - * and head numbers or odd sized sectors. - * - * First, determine sector size according to the boot sector. */ - bool founddisk = false; - const vfdentry *ent; - - ent = findSector(/*head*/0,/*track*/0,/*sector*/1,~0U); - if (ent != NULL) { - if (ent->getSectorSize() <= 1024) /* x <= 1024 */ - sector_size = ent->getSectorSize(); - } - - /* oh yeah right, sure. - * I suppose you're one of those FDD images where the sector size is 128 bytes/sector - * in the boot sector and the rest is 256 bytes/sector elsewhere. I have no idea why - * but quite a few FDD images have this arrangement. */ - if (sector_size != 0 && sector_size < 512) { - ent = findSector(/*head*/0,/*track*/1,/*sector*/1,~0U); - if (ent != NULL) { - if (ent->getSectorSize() <= 1024) { /* x <= 1024 */ - unsigned int nsz = ent->getSectorSize(); - if (sector_size != nsz) - LOG_MSG("NFD warning: sector size changes between track 0 and 1"); - if (sector_size < nsz) - sector_size = nsz; - } - } - } - - if (sector_size != 0) { - unsigned int i = 0; - while (DiskGeometryList[i].ksize != 0) { - const diskGeo &diskent = DiskGeometryList[i]; - - if (diskent.bytespersect == sector_size) { - ent = findSector(0,0,diskent.secttrack); - if (ent != NULL) { - LOG_MSG("NFD disk probe: %u/%u/%u exists",0,0,diskent.secttrack); - if (sectors < diskent.secttrack) - sectors = diskent.secttrack; - } - } - - i++; - } - } - - if (sector_size != 0 && sectors != 0) { - unsigned int i = 0; - while (DiskGeometryList[i].ksize != 0) { - const diskGeo &diskent = DiskGeometryList[i]; - - if (diskent.bytespersect == sector_size && diskent.secttrack >= sectors) { - ent = findSector(0,diskent.cylcount-1,sectors); - if (ent != NULL) { - LOG_MSG("NFD disk probe: %u/%u/%u exists",0,diskent.cylcount-1,sectors); - if (cylinders < diskent.cylcount) - cylinders = diskent.cylcount; - } - } - - i++; - } - } - - if (sector_size != 0 && sectors != 0 && cylinders != 0) { - ent = findSector(1,0,sectors); - if (ent != NULL) { - LOG_MSG("NFD disk probe: %u/%u/%u exists",1,0,sectors); - heads = 2; - } - } - - // TODO: drive_fat.cpp should use an extension to this API to allow changing the sectors/track - // according to what it reads from the MS-DOS BIOS parameter block, just like real MS-DOS. - // This would allow better representation of strange disk formats such as the "extended" - // floppy format that Microsoft used to use for Word 95 and Windows 95 install floppies. - - LOG_MSG("NFD geometry detection: C/H/S %u/%u/%u %u bytes/sector", - cylinders, heads, sectors, sector_size); - - if (sector_size != 0 && sectors != 0 && cylinders != 0 && heads != 0) - founddisk = true; - - if(!founddisk) { - active = false; - } else { - incrementFDD(); - } - } -} - -imageDiskNFD::~imageDiskNFD() { - if(diskimg != NULL) { - fclose(diskimg); - diskimg=NULL; - } -} - -bool PartitionLoadMBR(std::vector &parts,imageDisk *loadedDisk) { - partTable smbr; - - parts.clear(); - - if (loadedDisk->getSectSize() > sizeof(smbr)) return false; - if (loadedDisk->Read_Sector(0,0,1,&smbr) != 0x00) return false; - if (smbr.magic1 != 0x55 || smbr.magic2 != 0xaa) return false; /* Must have signature */ - - /* first copy the main partition table entries */ - for (size_t i=0;i < 4;i++) - parts.push_back(smbr.pentry[i]); - - /* then, enumerate extended partitions and add the partitions within, doing it in a way that - * allows recursive extended partitions */ - { - size_t i=0; - - do { - if (parts[i].parttype == 0x05/*extended*/ || parts[i].parttype == 0x0F/*LBA extended*/) { - unsigned long sect = parts[i].absSectStart; - unsigned long send = sect + parts[i].partSize; - - /* partitions within an extended partition form a sort of linked list. - * first entry is the partition, sector start relative to parent partition. - * second entry points to next link in the list. */ - - /* parts[i] is the parent partition in this loop. - * this loop will add to the parts vector, the parent - * loop will continue enumerating through the vector - * until all have processed. in this way, extended - * partitions will be expanded into the sub partitions - * until none is left to do. */ - - /* FIXME: Extended partitions within extended partitions not yet tested, - * MS-DOS FDISK.EXE won't generate that. */ - - while (sect < send) { - smbr.magic1 = smbr.magic2 = 0; - loadedDisk->Read_AbsoluteSector(sect,&smbr); - - if (smbr.magic1 != 0x55 || smbr.magic2 != 0xAA) - break; - if (smbr.pentry[0].absSectStart == 0 || smbr.pentry[0].partSize == 0) - break; // FIXME: Not sure what MS-DOS considers the end of the linked list - - const size_t idx = parts.size(); - - /* Right, get this: absolute start sector in entry #0 is relative to this link in the linked list. - * The pointer to the next link in the linked list is relative to the parent partition. Blegh. */ - smbr.pentry[0].absSectStart += sect; - if (smbr.pentry[1].absSectStart != 0) - smbr.pentry[1].absSectStart += parts[i].absSectStart; - - /* if the partition extends past the parent, then stop */ - if ((smbr.pentry[0].absSectStart+smbr.pentry[0].partSize) > (parts[i].absSectStart+parts[i].partSize)) - break; - - parts.push_back(smbr.pentry[0]); - - /* Based on MS-DOS 5.0, the 2nd entry is a link to the next entry, but only if - * start sector is nonzero and type is 0x05/0x0F. I'm not certain if MS-DOS allows - * the linked list to go either direction, but for the sake of preventing infinite - * loops stop if the link points to a lower sector number. */ - if (idx < 256 && (smbr.pentry[1].parttype == 0x05 || smbr.pentry[1].parttype == 0x0F) && - smbr.pentry[1].absSectStart != 0 && smbr.pentry[1].absSectStart > sect) { - sect = smbr.pentry[1].absSectStart; - } - else { - break; - } - } - } - i++; - } while (i < parts.size()); - } - - return true; -} - -bool PartitionLoadIPL1(std::vector<_PC98RawPartition> &parts,imageDisk *loadedDisk) { - unsigned char ipltable[SECTOR_SIZE_MAX]; - - parts.clear(); - - assert(sizeof(_PC98RawPartition) == 32); - if (loadedDisk->getSectSize() > sizeof(ipltable)) return false; - - memset(ipltable,0,sizeof(ipltable)); - if (loadedDisk->Read_Sector(0,0,2,ipltable) != 0) return false; - - const unsigned int max_entries = std::min(16UL,(unsigned long)(loadedDisk->getSectSize() / sizeof(_PC98RawPartition))); - - for (size_t i=0;i < max_entries;i++) { - const _PC98RawPartition *pe = (_PC98RawPartition*)(ipltable+(i * 32)); - - if (pe->mid == 0 && pe->sid == 0 && - pe->ipl_sect == 0 && pe->ipl_head == 0 && pe->ipl_cyl == 0 && - pe->sector == 0 && pe->head == 0 && pe->cyl == 0 && - pe->end_sector == 0 && pe->end_head == 0 && pe->end_cyl == 0) - continue; /* unused */ - - parts.push_back(*pe); - } - - return true; -} - -std::string PartitionIdentifyType(imageDisk *loadedDisk) { - struct partTable mbrData; - - if (loadedDisk->getSectSize() > sizeof(mbrData)) - return std::string(); /* That would cause a buffer overrun */ - - if (loadedDisk->Read_Sector(0,0,1,&mbrData) != 0) - return std::string(); - - if (!memcmp(mbrData.booter+4,"IPL1",4)) - return "IPL1"; /* PC-98 IPL1 */ - - if (mbrData.magic1 == 0x55 && mbrData.magic2 == 0xaa) - return "MBR"; /* IBM PC MBR */ - - return std::string(); -} - -void LogPrintPartitionTable(const std::vector<_PC98RawPartition> &parts) { - for (size_t i=0;i < parts.size();i++) { - const _PC98RawPartition &part = parts[i]; - - LOG(LOG_DOSMISC,LOG_DEBUG)("IPL #%u: boot=%u active=%u startchs=%u/%u/%u endchs=%u/%u/%u '%s'", - (unsigned int)i,(part.mid&0x80)?1:0,(part.sid&0x80)?1:0, - part.cyl,part.head,part.sector,part.end_cyl,part.end_head,part.end_sector, - std::string((char*)part.name,sizeof(part.name)).c_str()); - } -} - -void LogPrintPartitionTable(const std::vector &parts) { - for (size_t i=0;i < parts.size();i++) { - const partTable::partentry_t &part = parts[i]; - - LOG(LOG_DOSMISC,LOG_DEBUG)("MBR #%u: bootflag=%u parttype=0x%02x beginchs=0x%02x%02x%02x endchs=0x%02x%02x%02x start=%llu size=%llu", - (unsigned int)i,(part.bootflag&0x80)?1:0,part.parttype, - part.beginchs[0],part.beginchs[1],part.beginchs[2], - part.endchs[0],part.endchs[1],part.endchs[2], - (unsigned long long)part.absSectStart, - (unsigned long long)part.partSize); - } -} - + _driveUsed = true; + return 0; + } + + uint8_t imageDiskNFD::Read_AbsoluteSector(uint32_t sectnum, void * data) { + unsigned int c,h,s; + + if (sectors == 0 || heads == 0) + return 0x05; + + s = (sectnum % sectors) + 1; + h = (sectnum / sectors) % heads; + c = (sectnum / sectors / heads); -uint8_t imageDiskEmptyDrive::Read_Sector(uint32_t /*head*/,uint32_t /*cylinder*/,uint32_t /*sector*/,void * /*data*/,unsigned int /*req_sector_size*/) { - return 0x05; -} + _driveUsed = true; + return Read_Sector(h,c,s,data); + } + + imageDiskNFD::vfdentry *imageDiskNFD::findSector(uint8_t head,uint8_t track,uint8_t sector/*TODO: physical head?*/,unsigned int req_sector_size) { + if ((size_t)track >= dents.size()) + return NULL; + + std::vector::iterator i = dents.begin(); + + if (req_sector_size == 0) + req_sector_size = sector_size; + + while (i != dents.end()) { + const imageDiskNFD::vfdentry &ent = *i; + + if (ent.head == head && + ent.track == track && + ent.sector == sector && + (ent.sector_size == req_sector_size || req_sector_size == ~0U)) + return &(*i); + + ++i; + } + + return NULL; + } + + uint8_t imageDiskNFD::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { + const vfdentry *ent; + + if (req_sector_size == 0) + req_sector_size = sector_size; + + // LOG_MSG("NFD read sector: CHS %u/%u/%u sz=%u",cylinder,head,sector,req_sector_size); + + ent = findSector(head,cylinder,sector,req_sector_size); + if (ent == NULL) return 0x05; + if (ent->getSectorSize() != req_sector_size) return 0x05; + + fseek(diskimg,(long)ent->data_offset,SEEK_SET); + if ((uint32_t)ftell(diskimg) != ent->data_offset) return 0x05; + if (fwrite(data,req_sector_size,1,diskimg) != 1) return 0x05; -uint8_t imageDiskEmptyDrive::Write_Sector(uint32_t /*head*/,uint32_t /*cylinder*/,uint32_t /*sector*/,const void * /*data*/,unsigned int /*req_sector_size*/) { - return 0x05; -} + _driveUsed = true; + return 0; + } + + uint8_t imageDiskNFD::Write_AbsoluteSector(uint32_t sectnum,const void *data) { + unsigned int c,h,s; + + if (sectors == 0 || heads == 0) + return 0x05; + + s = (sectnum % sectors) + 1; + h = (sectnum / sectors) % heads; + c = (sectnum / sectors / heads); -uint8_t imageDiskEmptyDrive::Read_AbsoluteSector(uint32_t /*sectnum*/, void * /*data*/) { - return 0x05; -} - -uint8_t imageDiskEmptyDrive::Write_AbsoluteSector(uint32_t /*sectnum*/, const void * /*data*/) { - return 0x05; -} - -imageDiskEmptyDrive::imageDiskEmptyDrive() : imageDisk(ID_EMPTY_DRIVE) { - active = true; - sector_size = 512; - heads = 2; - cylinders = 80; - sectors = 18; - diskSizeK = 1440; -} - -imageDiskEmptyDrive::~imageDiskEmptyDrive() { -} - -///// - -unsigned int INT13Xfer = 0; -size_t INT13XferSize = 4096; - -static void imageDiskCallINT13(void) { - unsigned int rv = CALLBACK_RealPointer(call_int13); - Bitu oldIF=GETFLAG(IF); - SETFLAGBIT(IF,true); - uint16_t oldcs=SegValue(cs); - uint32_t oldeip=reg_eip; - SegSet16(cs,rv>>16); - reg_eip=(rv&0xFFFF)+4+5; - DOSBOX_RunMachine(); - reg_eip=oldeip; - SegSet16(cs,oldcs); - SETFLAGBIT(IF,oldIF); -} - -uint8_t imageDiskINT13Drive::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { - if (!enable_int13 || busy) return subdisk->Read_Sector(head,cylinder,sector,data,req_sector_size); - - uint8_t ret = 0x05; - unsigned int retry = 3; - - if (req_sector_size == 0) req_sector_size = sector_size; - -// LOG_MSG("INT13 read C/H/S %u/%u/%u busy=%u",cylinder,head,sector,busy); - - if (!busy && sector_size == req_sector_size && sector_size <= INT13XferSize) { - busy = true; - - if (INT13Xfer == 0) INT13Xfer = DOS_GetMemory(INT13XferSize/16u,"INT 13 transfer buffer"); - - unsigned int s_eax = reg_eax; - unsigned int s_ebx = reg_ebx; - unsigned int s_ecx = reg_ecx; - unsigned int s_edx = reg_edx; - unsigned int s_esi = reg_esi; - unsigned int s_edi = reg_edi; - unsigned int s_esp = reg_esp; - unsigned int s_ebp = reg_ebp; - unsigned int s_es = SegValue(es); - unsigned int s_fl = reg_flags; - -again: - reg_eax = 0x200/*read command*/ | 1/*count*/; - reg_ebx = 0; - reg_ch = cylinder; - reg_cl = sector; - reg_dh = head; - reg_dl = bios_disk; - CPU_SetSegGeneral(es,INT13Xfer); - - imageDiskCallINT13(); - - if (reg_flags & FLAG_CF) { - ret = reg_ah; - if (ret == 0) ret = 0x05; - - if (ret == 6/*disk change*/) { - diskChangeFlag = true; - if (--retry > 0) goto again; - } - } - else { - MEM_BlockRead32(INT13Xfer<<4,data,sector_size); - data = (void*)((char*)data + sector_size); - if ((++sector) >= (sectors + 1)) { - assert(sector == (sectors + 1)); - sector = 1; - if ((++head) >= heads) { - assert(head == heads); - head = 0; - cylinder++; - } - } - } - - reg_eax = s_eax; - reg_ebx = s_ebx; - reg_ecx = s_ecx; - reg_edx = s_edx; - reg_esi = s_esi; - reg_edi = s_edi; - reg_esp = s_esp; - reg_ebp = s_ebp; - reg_flags = s_fl; - CPU_SetSegGeneral(es,s_es); - - busy = false; - } - - return ret; -} - -uint8_t imageDiskINT13Drive::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { - if (INT13Xfer == 0) INT13Xfer = DOS_GetMemory(INT13XferSize/16u,"INT 13 transfer buffer"); - - return subdisk->Write_Sector(head,cylinder,sector,data,req_sector_size); -} - -uint8_t imageDiskINT13Drive::Read_AbsoluteSector(uint32_t sectnum, void * data) { - unsigned int c,h,s; - - if (sectors == 0 || heads == 0) - return 0x05; - - s = (sectnum % sectors) + 1; - h = (sectnum / sectors) % heads; - c = (sectnum / sectors / heads); - return Read_Sector(h,c,s,data); -} - -uint8_t imageDiskINT13Drive::Write_AbsoluteSector(uint32_t sectnum, const void * data) { - unsigned int c,h,s; - - if (sectors == 0 || heads == 0) - return 0x05; - - s = (sectnum % sectors) + 1; - h = (sectnum / sectors) % heads; - c = (sectnum / sectors / heads); - return Write_Sector(h,c,s,data); -} - -void imageDiskINT13Drive::UpdateFloppyType(void) { - subdisk->UpdateFloppyType(); -} - -void imageDiskINT13Drive::Set_Reserved_Cylinders(Bitu resCyl) { - subdisk->Set_Reserved_Cylinders(resCyl); -} - -uint32_t imageDiskINT13Drive::Get_Reserved_Cylinders() { - return subdisk->Get_Reserved_Cylinders(); -} - -void imageDiskINT13Drive::Set_Geometry(uint32_t setHeads, uint32_t setCyl, uint32_t setSect, uint32_t setSectSize) { - heads = setHeads; - cylinders = setCyl; - sectors = setSect; - sector_size = setSectSize; - return subdisk->Set_Geometry(setHeads,setCyl,setSect,setSectSize); -} - -void imageDiskINT13Drive::Get_Geometry(uint32_t * getHeads, uint32_t *getCyl, uint32_t *getSect, uint32_t *getSectSize) { - return subdisk->Get_Geometry(getHeads,getCyl,getSect,getSectSize); -} - -uint8_t imageDiskINT13Drive::GetBiosType(void) { - return subdisk->GetBiosType(); -} - -uint32_t imageDiskINT13Drive::getSectSize(void) { - return subdisk->getSectSize(); -} - -bool imageDiskINT13Drive::detectDiskChange(void) { - if (enable_int13 && !busy) { - busy = true; - - unsigned int s_eax = reg_eax; - unsigned int s_ebx = reg_ebx; - unsigned int s_ecx = reg_ecx; - unsigned int s_edx = reg_edx; - unsigned int s_esi = reg_esi; - unsigned int s_edi = reg_edi; - unsigned int s_esp = reg_esp; - unsigned int s_ebp = reg_ebp; - unsigned int s_fl = reg_flags; - - reg_eax = 0x1600/*disk change detect*/; - reg_dl = bios_disk; - CPU_SetSegGeneral(es,INT13Xfer); - - imageDiskCallINT13(); - - if (reg_flags & FLAG_CF) { - if (reg_ah == 0x06) { - LOG(LOG_MISC,LOG_DEBUG)("INT13 image disk change flag"); - diskChangeFlag = true; - } - } - - reg_eax = s_eax; - reg_ebx = s_ebx; - reg_ecx = s_ecx; - reg_edx = s_edx; - reg_esi = s_esi; - reg_edi = s_edi; - reg_esp = s_esp; - reg_ebp = s_ebp; - reg_flags = s_fl; - - busy = false; - } - - return imageDisk::detectDiskChange(); -} - -imageDiskINT13Drive::imageDiskINT13Drive(imageDisk *sdisk) : imageDisk(ID_INT13) { - subdisk = sdisk; - subdisk->Addref(); - - drvnum = subdisk->drvnum; - diskname = subdisk->diskname; - active = subdisk->active; - sector_size = subdisk->sector_size; - heads = subdisk->heads; - cylinders = subdisk->cylinders; - sectors = subdisk->sectors; - hardDrive = subdisk->hardDrive; - diskSizeK = subdisk->diskSizeK; - diskChangeFlag = subdisk->diskChangeFlag; -} - -imageDiskINT13Drive::~imageDiskINT13Drive() { - subdisk->Release(); -} + _driveUsed = true; + return Write_Sector(h,c,s,data); + } + + imageDiskNFD::imageDiskNFD(FILE *imgFile, const char *imgName, uint32_t imgSizeK, bool isHardDisk, unsigned int revision) : imageDisk(ID_NFD) { + (void)isHardDisk;//UNUSED + union { + NFDHDR head; + NFDHDRR1 headr1; + }; // these occupy the same location of memory + + assert(sizeof(NFDHDR) == 0x120); + assert(sizeof(NFDHDRR1) == 0x3C0); + assert(sizeof(NFDHDR_ENTRY) == 0x10); + + heads = 0; + cylinders = 0; + image_base = 0; + sectors = 0; + active = false; + sector_size = 0; + reserved_cylinders = 0; + diskSizeK = imgSizeK; + diskimg = imgFile; + + if (imgName != NULL) + diskname = imgName; + + // NOTES: + // + // +0x000: NFD header + // +0x020: Offset of NFD tracks, per track + // +0x2B0: + // + // Track offsets are sequential, always + // + // Each track is an array of: + // + // ENTRY: + // + // + // + // Array of ENTRY from offset until next track + fseek(diskimg,0,SEEK_END); + off_t fsz = ftell(diskimg); + + fseek(diskimg,0,SEEK_SET); + if (revision == 0) { + if (fread(&head,sizeof(head),1,diskimg) != 1) return; + } + else if (revision == 1) { + if (fread(&headr1,sizeof(headr1),1,diskimg) != 1) return; + } + else { + abort(); + } + + // validate fd_size + if (host_readd((ConstHostPt)(&head.headersize)) < sizeof(head)) return; + if (host_readd((ConstHostPt)(&head.headersize)) > (uint32_t)fsz) return; + + unsigned int data_offset = host_readd((ConstHostPt)(&head.headersize)); + + std::vector< std::pair > seclist; + + if (revision == 0) { + unsigned int secents = (host_readd((ConstHostPt)(&head.headersize)) - sizeof(head)) / sizeof(NFDHDR_ENTRY); + if (secents == 0) return; + secents--; + if (secents == 0) return; + + for (unsigned int i=0;i < secents;i++) { + uint32_t ofs = (uint32_t)ftell(diskimg); + NFDHDR_ENTRY e; + + if (fread(&e,sizeof(e),1,diskimg) != 1) return; + seclist.push_back( std::pair(ofs,e) ); + + if (e.log_cyl == 0xFF || e.log_head == 0xFF || e.log_rec == 0xFF || e.sec_len_pow2 > 7) + continue; + + LOG_MSG("NFD %u/%u: ofs=%lu data=%lu cyl=%u head=%u sec=%u len=%u", + (unsigned int)i, + (unsigned int)secents, + (unsigned long)ofs, + (unsigned long)data_offset, + e.log_cyl, + e.log_head, + e.log_rec, + 128 << e.sec_len_pow2); + + vfdentry vent; + vent.sector_size = 128 << e.sec_len_pow2; + vent.data_offset = (uint32_t)data_offset; + vent.entry_offset = ofs; + vent.track = e.log_cyl; + vent.head = e.log_head; + vent.sector = e.log_rec; + dents.push_back(vent); + + data_offset += 128u << e.sec_len_pow2; + if (data_offset > (unsigned int)fsz) return; + } + } + else { + /* R1 has an array of offsets to where each tracks begins. + * The end of the track is an entry like 0x1A 0x00 0x00 0x00 0x00 0x00 0x00 .... */ + /* The R1 images I have as reference always have offsets in ascending order. */ + for (unsigned int ti=0;ti < 164;ti++) { + uint32_t trkoff = host_readd((ConstHostPt)(&headr1.trackheads[ti])); + + if (trkoff == 0) break; + + fseek(diskimg,(long)trkoff,SEEK_SET); + if ((off_t)ftell(diskimg) != (off_t)trkoff) return; + + NFDHDR_ENTRY e; + + // track id + if (fread(&e,sizeof(e),1,diskimg) != 1) return; + unsigned int sectors = host_readw((ConstHostPt)(&e) + 0); + unsigned int diagcount = host_readw((ConstHostPt)(&e) + 2); + + LOG_MSG("NFD R1 track ent %u offset %lu sectors %u diag %u",ti,(unsigned long)trkoff,sectors,diagcount); + + for (unsigned int s=0;s < sectors;s++) { + uint32_t ofs = (uint32_t)ftell(diskimg); + + if (fread(&e,sizeof(e),1,diskimg) != 1) return; + + LOG_MSG("NFD %u/%u: ofs=%lu data=%lu cyl=%u head=%u sec=%u len=%u rep=%u", + s, + sectors, + (unsigned long)ofs, + (unsigned long)data_offset, + e.log_cyl, + e.log_head, + e.log_rec, + 128 << e.sec_len_pow2, + e.byRetry); + + vfdentry vent; + vent.sector_size = 128 << e.sec_len_pow2; + vent.data_offset = (uint32_t)data_offset; + vent.entry_offset = ofs; + vent.track = e.log_cyl; + vent.head = e.log_head; + vent.sector = e.log_rec; + dents.push_back(vent); + + data_offset += 128u << e.sec_len_pow2; + if (data_offset > (unsigned int)fsz) return; + } + + for (unsigned int d=0;d < diagcount;d++) { + if (fread(&e,sizeof(e),1,diskimg) != 1) return; + + unsigned int retry = e.byRetry; + unsigned int len = host_readd((ConstHostPt)(&e) + 10); + + LOG_MSG("NFD diag %u/%u: retry=%u len=%u data=%lu",d,diagcount,retry,len,(unsigned long)data_offset); + + data_offset += (1+retry) * len; + } + } + } + + if (!dents.empty()) { + /* okay, now to figure out what the geometry of the disk is. + * we cannot just work from an "absolute" disk image model + * because there's no NFD header to just say what the geometry is. + * Like the IBM PC BIOS, we have to look at the disk and figure out + * which geometry to apply to it, even if the FDD format allows + * sectors on other tracks to have wild out of range sector, track, + * and head numbers or odd sized sectors. + * + * First, determine sector size according to the boot sector. */ + bool founddisk = false; + const vfdentry *ent; + + ent = findSector(/*head*/0,/*track*/0,/*sector*/1,~0U); + if (ent != NULL) { + if (ent->getSectorSize() <= 1024) /* x <= 1024 */ + sector_size = ent->getSectorSize(); + } + + /* oh yeah right, sure. + * I suppose you're one of those FDD images where the sector size is 128 bytes/sector + * in the boot sector and the rest is 256 bytes/sector elsewhere. I have no idea why + * but quite a few FDD images have this arrangement. */ + if (sector_size != 0 && sector_size < 512) { + ent = findSector(/*head*/0,/*track*/1,/*sector*/1,~0U); + if (ent != NULL) { + if (ent->getSectorSize() <= 1024) { /* x <= 1024 */ + unsigned int nsz = ent->getSectorSize(); + if (sector_size != nsz) + LOG_MSG("NFD warning: sector size changes between track 0 and 1"); + if (sector_size < nsz) + sector_size = nsz; + } + } + } + + if (sector_size != 0) { + unsigned int i = 0; + while (DiskGeometryList[i].ksize != 0) { + const diskGeo &diskent = DiskGeometryList[i]; + + if (diskent.bytespersect == sector_size) { + ent = findSector(0,0,diskent.secttrack); + if (ent != NULL) { + LOG_MSG("NFD disk probe: %u/%u/%u exists",0,0,diskent.secttrack); + if (sectors < diskent.secttrack) + sectors = diskent.secttrack; + } + } + + i++; + } + } + + if (sector_size != 0 && sectors != 0) { + unsigned int i = 0; + while (DiskGeometryList[i].ksize != 0) { + const diskGeo &diskent = DiskGeometryList[i]; + + if (diskent.bytespersect == sector_size && diskent.secttrack >= sectors) { + ent = findSector(0,diskent.cylcount-1,sectors); + if (ent != NULL) { + LOG_MSG("NFD disk probe: %u/%u/%u exists",0,diskent.cylcount-1,sectors); + if (cylinders < diskent.cylcount) + cylinders = diskent.cylcount; + } + } + + i++; + } + } + + if (sector_size != 0 && sectors != 0 && cylinders != 0) { + ent = findSector(1,0,sectors); + if (ent != NULL) { + LOG_MSG("NFD disk probe: %u/%u/%u exists",1,0,sectors); + heads = 2; + } + } + + // TODO: drive_fat.cpp should use an extension to this API to allow changing the sectors/track + // according to what it reads from the MS-DOS BIOS parameter block, just like real MS-DOS. + // This would allow better representation of strange disk formats such as the "extended" + // floppy format that Microsoft used to use for Word 95 and Windows 95 install floppies. + + LOG_MSG("NFD geometry detection: C/H/S %u/%u/%u %u bytes/sector", + cylinders, heads, sectors, sector_size); + + if (sector_size != 0 && sectors != 0 && cylinders != 0 && heads != 0) + founddisk = true; + + if(!founddisk) { + active = false; + } else { + incrementFDD(); + } + } + } + + imageDiskNFD::~imageDiskNFD() { + if(diskimg != NULL) { + fclose(diskimg); + + } + } + + bool PartitionLoadMBR(std::vector &parts,imageDisk *loadedDisk) { + partTable smbr; + + parts.clear(); + + if (loadedDisk->getSectSize() > sizeof(smbr)) return false; + if (loadedDisk->Read_Sector(0,0,1,&smbr) != 0x00) return false; + if (smbr.magic1 != 0x55 || smbr.magic2 != 0xaa) return false; /* Must have signature */ + + /* first copy the main partition table entries */ + for (size_t i=0;i < 4;i++) + parts.push_back(smbr.pentry[i]); + + /* then, enumerate extended partitions and add the partitions within, doing it in a way that + * allows recursive extended partitions */ + { + size_t i=0; + + do { + if (parts[i].parttype == 0x05/*extended*/ || parts[i].parttype == 0x0F/*LBA extended*/) { + unsigned long sect = parts[i].absSectStart; + unsigned long send = sect + parts[i].partSize; + + /* partitions within an extended partition form a sort of linked list. + * first entry is the partition, sector start relative to parent partition. + * second entry points to next link in the list. */ + + /* parts[i] is the parent partition in this loop. + * this loop will add to the parts vector, the parent + * loop will continue enumerating through the vector + * until all have processed. in this way, extended + * partitions will be expanded into the sub partitions + * until none is left to do. */ + + /* FIXME: Extended partitions within extended partitions not yet tested, + * MS-DOS FDISK.EXE won't generate that. */ + + while (sect < send) { + smbr.magic1 = smbr.magic2 = 0; + loadedDisk->Read_AbsoluteSector(sect,&smbr); + + if (smbr.magic1 != 0x55 || smbr.magic2 != 0xAA) + break; + if (smbr.pentry[0].absSectStart == 0 || smbr.pentry[0].partSize == 0) + break; // FIXME: Not sure what MS-DOS considers the end of the linked list + + const size_t idx = parts.size(); + + /* Right, get this: absolute start sector in entry #0 is relative to this link in the linked list. + * The pointer to the next link in the linked list is relative to the parent partition. Blegh. */ + smbr.pentry[0].absSectStart += sect; + if (smbr.pentry[1].absSectStart != 0) + smbr.pentry[1].absSectStart += parts[i].absSectStart; + + /* if the partition extends past the parent, then stop */ + if ((smbr.pentry[0].absSectStart+smbr.pentry[0].partSize) > (parts[i].absSectStart+parts[i].partSize)) + break; + + parts.push_back(smbr.pentry[0]); + + /* Based on MS-DOS 5.0, the 2nd entry is a link to the next entry, but only if + * start sector is nonzero and type is 0x05/0x0F. I'm not certain if MS-DOS allows + * the linked list to go either direction, but for the sake of preventing infinite + * loops stop if the link points to a lower sector number. */ + if (idx < 256 && (smbr.pentry[1].parttype == 0x05 || smbr.pentry[1].parttype == 0x0F) && + smbr.pentry[1].absSectStart != 0 && smbr.pentry[1].absSectStart > sect) { + sect = smbr.pentry[1].absSectStart; + } + else { + break; + } + } + } + i++; + } while (i < parts.size()); + } + + return true; + } + + bool PartitionLoadIPL1(std::vector<_PC98RawPartition> &parts,imageDisk *loadedDisk) { + unsigned char ipltable[SECTOR_SIZE_MAX]; + + parts.clear(); + + assert(sizeof(_PC98RawPartition) == 32); + if (loadedDisk->getSectSize() > sizeof(ipltable)) return false; + + memset(ipltable,0,sizeof(ipltable)); + if (loadedDisk->Read_Sector(0,0,2,ipltable) != 0) return false; + + const unsigned int max_entries = std::min(16UL,(unsigned long)(loadedDisk->getSectSize() / sizeof(_PC98RawPartition))); + + for (size_t i=0;i < max_entries;i++) { + const _PC98RawPartition *pe = (_PC98RawPartition*)(ipltable+(i * 32)); + + if (pe->mid == 0 && pe->sid == 0 && + pe->ipl_sect == 0 && pe->ipl_head == 0 && pe->ipl_cyl == 0 && + pe->sector == 0 && pe->head == 0 && pe->cyl == 0 && + pe->end_sector == 0 && pe->end_head == 0 && pe->end_cyl == 0) + continue; /* unused */ + + parts.push_back(*pe); + } + + return true; + } + + std::string PartitionIdentifyType(imageDisk *loadedDisk) { + struct partTable mbrData; + + if (loadedDisk->getSectSize() > sizeof(mbrData)) + return std::string(); /* That would cause a buffer overrun */ + + if (loadedDisk->Read_Sector(0,0,1,&mbrData) != 0) + return std::string(); + + if (!memcmp(mbrData.booter+4,"IPL1",4)) + return "IPL1"; /* PC-98 IPL1 */ + + if (mbrData.magic1 == 0x55 && mbrData.magic2 == 0xaa) + return "MBR"; /* IBM PC MBR */ + + return std::string(); + } + + void LogPrintPartitionTable(const std::vector<_PC98RawPartition> &parts) { + for (size_t i=0;i < parts.size();i++) { + const _PC98RawPartition &part = parts[i]; + + LOG(LOG_DOSMISC,LOG_DEBUG)("IPL #%u: boot=%u active=%u startchs=%u/%u/%u endchs=%u/%u/%u '%s'", + (unsigned int)i,(part.mid&0x80)?1:0,(part.sid&0x80)?1:0, + part.cyl,part.head,part.sector,part.end_cyl,part.end_head,part.end_sector, + std::string((char*)part.name,sizeof(part.name)).c_str()); + } + } + + void LogPrintPartitionTable(const std::vector &parts) { + for (size_t i=0;i < parts.size();i++) { + const partTable::partentry_t &part = parts[i]; + + LOG(LOG_DOSMISC,LOG_DEBUG)("MBR #%u: bootflag=%u parttype=0x%02x beginchs=0x%02x%02x%02x endchs=0x%02x%02x%02x start=%llu size=%llu", + (unsigned int)i,(part.bootflag&0x80)?1:0,part.parttype, + part.beginchs[0],part.beginchs[1],part.beginchs[2], + part.endchs[0],part.endchs[1],part.endchs[2], + (unsigned long long)part.absSectStart, + (unsigned long long)part.partSize); + } + } + + + uint8_t imageDiskEmptyDrive::Read_Sector(uint32_t /*head*/,uint32_t /*cylinder*/,uint32_t /*sector*/,void * /*data*/,unsigned int /*req_sector_size*/) { + _driveUsed = true; + return 0x05; + } + + uint8_t imageDiskEmptyDrive::Write_Sector(uint32_t /*head*/,uint32_t /*cylinder*/,uint32_t /*sector*/,const void * /*data*/,unsigned int /*req_sector_size*/) { + _driveUsed = true; + return 0x05; + } + + uint8_t imageDiskEmptyDrive::Read_AbsoluteSector(uint32_t /*sectnum*/, void * /*data*/) { + _driveUsed = true; + return 0x05; + } + + uint8_t imageDiskEmptyDrive::Write_AbsoluteSector(uint32_t /*sectnum*/, const void * /*data*/) { + _driveUsed = true; + return 0x05; + } + + imageDiskEmptyDrive::imageDiskEmptyDrive() : imageDisk(ID_EMPTY_DRIVE) { + active = true; + sector_size = 512; + heads = 2; + cylinders = 80; + sectors = 18; + diskSizeK = 1440; + } + + imageDiskEmptyDrive::~imageDiskEmptyDrive() { + } + + ///// + + unsigned int INT13Xfer = 0; + size_t INT13XferSize = 4096; + + static void imageDiskCallINT13(void) { + unsigned int rv = CALLBACK_RealPointer(call_int13); + Bitu oldIF=GETFLAG(IF); + SETFLAGBIT(IF,true); + uint16_t oldcs=SegValue(cs); + uint32_t oldeip=reg_eip; + SegSet16(cs,rv>>16); + reg_eip=(rv&0xFFFF)+4+5; + DOSBOX_RunMachine(); + reg_eip=oldeip; + SegSet16(cs,oldcs); + SETFLAGBIT(IF,oldIF); + } + + uint8_t imageDiskINT13Drive::Read_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,void * data,unsigned int req_sector_size) { + if (!enable_int13 || busy) return subdisk->Read_Sector(head,cylinder,sector,data,req_sector_size); + + uint8_t ret = 0x05; + unsigned int retry = 3; + + if (req_sector_size == 0) req_sector_size = sector_size; + + // LOG_MSG("INT13 read C/H/S %u/%u/%u busy=%u",cylinder,head,sector,busy); + + if (!busy && sector_size == req_sector_size && sector_size <= INT13XferSize) { + busy = true; + + if (INT13Xfer == 0) INT13Xfer = DOS_GetMemory(INT13XferSize/16u,"INT 13 transfer buffer"); + + unsigned int s_eax = reg_eax; + unsigned int s_ebx = reg_ebx; + unsigned int s_ecx = reg_ecx; + unsigned int s_edx = reg_edx; + unsigned int s_esi = reg_esi; + unsigned int s_edi = reg_edi; + unsigned int s_esp = reg_esp; + unsigned int s_ebp = reg_ebp; + unsigned int s_es = SegValue(es); + unsigned int s_fl = reg_flags; + + again: + reg_eax = 0x200/*read command*/ | 1/*count*/; + reg_ebx = 0; + reg_ch = cylinder; + reg_cl = sector; + reg_dh = head; + reg_dl = bios_disk; + CPU_SetSegGeneral(es,INT13Xfer); + + imageDiskCallINT13(); + + if (reg_flags & FLAG_CF) { + ret = reg_ah; + if (ret == 0) ret = 0x05; + + if (ret == 6/*disk change*/) { + diskChangeFlag = true; + if (--retry > 0) goto again; + } + } + else { + MEM_BlockRead32(INT13Xfer<<4,data,sector_size); + data = (void*)((char*)data + sector_size); + if ((++sector) >= (sectors + 1)) { + assert(sector == (sectors + 1)); + sector = 1; + if ((++head) >= heads) { + assert(head == heads); + head = 0; + cylinder++; + } + } + } + + reg_eax = s_eax; + reg_ebx = s_ebx; + reg_ecx = s_ecx; + reg_edx = s_edx; + reg_esi = s_esi; + reg_edi = s_edi; + reg_esp = s_esp; + reg_ebp = s_ebp; + reg_flags = s_fl; + CPU_SetSegGeneral(es,s_es); + + busy = false; + } + + _driveUsed = true; + return ret; + } + + uint8_t imageDiskINT13Drive::Write_Sector(uint32_t head,uint32_t cylinder,uint32_t sector,const void * data,unsigned int req_sector_size) { + if (INT13Xfer == 0) INT13Xfer = DOS_GetMemory(INT13XferSize/16u,"INT 13 transfer buffer"); + + _driveUsed = true; + return subdisk->Write_Sector(head,cylinder,sector,data,req_sector_size); + } + + uint8_t imageDiskINT13Drive::Read_AbsoluteSector(uint32_t sectnum, void * data) { + unsigned int c,h,s; + + if (sectors == 0 || heads == 0) + return 0x05; + + s = (sectnum % sectors) + 1; + h = (sectnum / sectors) % heads; + c = (sectnum / sectors / heads); + _driveUsed = true; + return Read_Sector(h,c,s,data); + } + + uint8_t imageDiskINT13Drive::Write_AbsoluteSector(uint32_t sectnum, const void * data) { + unsigned int c,h,s; + + if (sectors == 0 || heads == 0) + return 0x05; + + s = (sectnum % sectors) + 1; + h = (sectnum / sectors) % heads; + c = (sectnum / sectors / heads); + _driveUsed = true; + return Write_Sector(h,c,s,data); + } + + void imageDiskINT13Drive::UpdateFloppyType(void) { + subdisk->UpdateFloppyType(); + } + + void imageDiskINT13Drive::Set_Reserved_Cylinders(Bitu resCyl) { + subdisk->Set_Reserved_Cylinders(resCyl); + } + + uint32_t imageDiskINT13Drive::Get_Reserved_Cylinders() { + return subdisk->Get_Reserved_Cylinders(); + } + + void imageDiskINT13Drive::Set_Geometry(uint32_t setHeads, uint32_t setCyl, uint32_t setSect, uint32_t setSectSize) { + heads = setHeads; + cylinders = setCyl; + sectors = setSect; + sector_size = setSectSize; + return subdisk->Set_Geometry(setHeads,setCyl,setSect,setSectSize); + } + + void imageDiskINT13Drive::Get_Geometry(uint32_t * getHeads, uint32_t *getCyl, uint32_t *getSect, uint32_t *getSectSize) { + return subdisk->Get_Geometry(getHeads,getCyl,getSect,getSectSize); + } + + uint8_t imageDiskINT13Drive::GetBiosType(void) { + return subdisk->GetBiosType(); + } + + uint32_t imageDiskINT13Drive::getSectSize(void) { + return subdisk->getSectSize(); + } + + bool imageDiskINT13Drive::detectDiskChange(void) { + if (enable_int13 && !busy) { + busy = true; + + unsigned int s_eax = reg_eax; + unsigned int s_ebx = reg_ebx; + unsigned int s_ecx = reg_ecx; + unsigned int s_edx = reg_edx; + unsigned int s_esi = reg_esi; + unsigned int s_edi = reg_edi; + unsigned int s_esp = reg_esp; + unsigned int s_ebp = reg_ebp; + unsigned int s_fl = reg_flags; + + reg_eax = 0x1600/*disk change detect*/; + reg_dl = bios_disk; + CPU_SetSegGeneral(es,INT13Xfer); + + imageDiskCallINT13(); + + if (reg_flags & FLAG_CF) { + if (reg_ah == 0x06) { + LOG(LOG_MISC,LOG_DEBUG)("INT13 image disk change flag"); + diskChangeFlag = true; + } + } + + reg_eax = s_eax; + reg_ebx = s_ebx; + reg_ecx = s_ecx; + reg_edx = s_edx; + reg_esi = s_esi; + reg_edi = s_edi; + reg_esp = s_esp; + reg_ebp = s_ebp; + reg_flags = s_fl; + + busy = false; + } + + return imageDisk::detectDiskChange(); + } + + imageDiskINT13Drive::imageDiskINT13Drive(imageDisk *sdisk) : imageDisk(ID_INT13) { + subdisk = sdisk; + subdisk->Addref(); + + drvnum = subdisk->drvnum; + diskname = subdisk->diskname; + active = subdisk->active; + sector_size = subdisk->sector_size; + heads = subdisk->heads; + cylinders = subdisk->cylinders; + sectors = subdisk->sectors; + hardDrive = subdisk->hardDrive; + diskSizeK = subdisk->diskSizeK; + diskChangeFlag = subdisk->diskChangeFlag; + } + + imageDiskINT13Drive::~imageDiskINT13Drive() { + subdisk->Release(); + } + + + /////////////////////////////////////// + + + imageDisk_Mem::imageDisk_Mem(jaffarCommon::file::MemoryFile* memfile, const char* imgName, uint32_t imgSizeK, bool isHardDisk) + { + diskSizeK = imgSizeK; + _memfile = memfile; + image_length = ((uint64_t)imgSizeK * 1024); + + if (imgName != NULL) + diskname = imgName; + + active = false; + hardDrive = isHardDisk; + if(!isHardDisk) { + bool founddisk = false; + + if (imgName != NULL) { + const char *ext = strrchr((char*)imgName,'.'); + if (ext != NULL) { + if (!strcasecmp(ext,".fdi")) { + if (imgSizeK >= 160) { + FDIHDR fdihdr; + + // PC-98 .FDI images appear to be 4096 bytes of a short header and many zeros. + // followed by a straight sector dump of the disk. The header is NOT NECESSARILY + // 4KB in size, but usually is. + LOG_MSG("Image file has .FDI extension, assuming FDI image and will take on parameters in header."); + + assert(sizeof(fdihdr) == 0x20); + if (jaffarCommon::file::MemoryFile::fseek(_memfile,0,SEEK_SET) == 0 && jaffarCommon::file::MemoryFile::ftell(_memfile) == 0 && + jaffarCommon::file::MemoryFile::fread(&fdihdr,sizeof(fdihdr),1,_memfile) == 1) { + uint32_t ofs = host_readd(fdihdr.headersize); + uint32_t fddsize = host_readd(fdihdr.fddsize); /* includes header */ + uint32_t sectorsize = host_readd(fdihdr.sectorsize); + + if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && + sectorsize >= 256 && sectorsize <= 1024 && + ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/ && + (ofs % 1024) == 0/*offset is a multiple of 1024 because of imgSizeK*/ && + fddsize >= sectorsize && (fddsize/1024) <= (imgSizeK+4)) { + + founddisk = true; + sector_size = sectorsize; + imgSizeK -= (ofs / 1024); + image_base = ofs; + image_length -= ofs; + LOG_MSG("FDI header: sectorsize is %u bytes/sector, header is %u bytes, fdd size (plus header) is %u bytes", + sectorsize,ofs,fddsize); + + /* take on the geometry. */ + sectors = host_readd(fdihdr.sectors); + heads = host_readd(fdihdr.surfaces); + cylinders = host_readd(fdihdr.cylinders); + LOG_MSG("FDI: Geometry is C/H/S %u/%u/%u", + cylinders,heads,sectors); + } + else { + LOG_MSG("FDI header rejected. sectorsize=%u headersize=%u fddsize=%u", + sectorsize,ofs,fddsize); + } + } + else { + LOG_MSG("Unable to read .FDI header"); + } + } + } + } + } + + if (sectors == 0 && heads == 0 && cylinders == 0) { + uint8_t i=0; + while (DiskGeometryList[i].ksize!=0x0) { + if ((DiskGeometryList[i].ksize==imgSizeK) || + (DiskGeometryList[i].ksize+1==imgSizeK)) { + if (DiskGeometryList[i].ksize!=imgSizeK) + LOG_MSG("ImageLoader: image file with additional data, might not load!"); + founddisk = true; + active = true; + floppytype = i; + heads = DiskGeometryList[i].headscyl; + cylinders = DiskGeometryList[i].cylcount; + sectors = DiskGeometryList[i].secttrack; + sector_size = DiskGeometryList[i].bytespersect; + LOG_MSG("Identified '%s' as C/H/S %u/%u/%u %u bytes/sector", + imgName,cylinders,heads,sectors,sector_size); + break; + } + // Supports cases where the size of a 1.2 Mbytes disk image file is 1.44 Mbytes. + if(DiskGeometryList[i].ksize == 1200 && (imgSizeK > 1200 && imgSizeK <= 1440)) { + char buff[0x20]; + if (jaffarCommon::file::MemoryFile::fseek(_memfile,0,SEEK_SET) == 0 && jaffarCommon::file::MemoryFile::ftell(_memfile) == 0 && jaffarCommon::file::MemoryFile::fread(buff,sizeof(buff),1,_memfile) == 1) { + if(buff[0x18] == DiskGeometryList[i].secttrack) { + founddisk = true; + active = true; + floppytype = i; + heads = DiskGeometryList[i].headscyl; + cylinders = DiskGeometryList[i].cylcount; + sectors = DiskGeometryList[i].secttrack; + break; + } + } + } + i++; + } + } + if(!founddisk) { + active = false; + } + } + else { /* hard disk */ + if (imgName != NULL) { + char *ext = strrchr((char*)imgName,'.'); + if (ext != NULL) { + if (!strcasecmp(ext,".nhd")) { + if (imgSizeK >= 160) { + NHD_FILE_HEAD nhdhdr; + + LOG_MSG("Image file has .NHD extension, assuming NHD image and will take on parameters in header."); + + assert(sizeof(nhdhdr) == 0x200); + if (jaffarCommon::file::MemoryFile::fseek(_memfile,0,SEEK_SET) == 0 && jaffarCommon::file::MemoryFile::ftell(_memfile) == 0 && + jaffarCommon::file::MemoryFile::fread(&nhdhdr,sizeof(nhdhdr),1,_memfile) == 1 && + host_readd((ConstHostPt)(&nhdhdr.dwHeadSize)) >= 0x200 && + !memcmp(nhdhdr.szFileID,"T98HDDIMAGE.R0\0",15)) { + uint32_t ofs = host_readd((ConstHostPt)(&nhdhdr.dwHeadSize)); + uint32_t sectorsize = host_readw((ConstHostPt)(&nhdhdr.wSectLen)); + + if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && + sectorsize >= 256 && sectorsize <= 1024 && + ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/) { + + sector_size = sectorsize; + imgSizeK -= (ofs / 1024); + image_base = ofs; + image_length -= ofs; + LOG_MSG("NHD header: sectorsize is %u bytes/sector, header is %u bytes", + sectorsize,ofs); + + /* take on the geometry. + * PC-98 IPL1 support will need it to make sense of the partition table. */ + sectors = host_readw((ConstHostPt)(&nhdhdr.wSect)); + heads = host_readw((ConstHostPt)(&nhdhdr.wHead)); + cylinders = host_readd((ConstHostPt)(&nhdhdr.dwCylinder)); + LOG_MSG("NHD: Geometry is C/H/S %u/%u/%u", + cylinders,heads,sectors); + } + else { + LOG_MSG("NHD header rejected. sectorsize=%u headersize=%u", + sectorsize,ofs); + } + } + else { + LOG_MSG("Unable to read .NHD header"); + } + } + } + if (!strcasecmp(ext,".hdi")) { + if (imgSizeK >= 160) { + HDIHDR hdihdr; + + // PC-98 .HDI images appear to be 4096 bytes of a short header and many zeros. + // followed by a straight sector dump of the disk. The header is NOT NECESSARILY + // 4KB in size, but usually is. + LOG_MSG("Image file has .HDI extension, assuming HDI image and will take on parameters in header."); + + assert(sizeof(hdihdr) == 0x20); + if (jaffarCommon::file::MemoryFile::fseek(_memfile,0,SEEK_SET) == 0 && jaffarCommon::file::MemoryFile::ftell(_memfile) == 0 && + jaffarCommon::file::MemoryFile::fread(&hdihdr,sizeof(hdihdr),1,_memfile) == 1) { + uint32_t ofs = host_readd(hdihdr.headersize); + uint32_t hddsize = host_readd(hdihdr.hddsize); /* includes header */ + uint32_t sectorsize = host_readd(hdihdr.sectorsize); + + if (sectorsize != 0 && ((sectorsize & (sectorsize - 1)) == 0/*is power of 2*/) && + sectorsize >= 256 && sectorsize <= 1024 && + ofs != 0 && (ofs % sectorsize) == 0/*offset is nonzero and multiple of sector size*/ && + (ofs % 1024) == 0/*offset is a multiple of 1024 because of imgSizeK*/ && + hddsize >= sectorsize && (hddsize/1024) <= (imgSizeK+4)) { + + sector_size = sectorsize; + image_base = ofs; + image_length -= ofs; + LOG_MSG("HDI header: sectorsize is %u bytes/sector, header is %u bytes, hdd size (plus header) is %u bytes", + sectorsize,ofs,hddsize); + + /* take on the geometry. + * PC-98 IPL1 support will need it to make sense of the partition table. */ + sectors = host_readd(hdihdr.sectors); + heads = host_readd(hdihdr.surfaces); + cylinders = host_readd(hdihdr.cylinders); + LOG_MSG("HDI: Geometry is C/H/S %u/%u/%u", + cylinders,heads,sectors); + } + else { + LOG_MSG("HDI header rejected. sectorsize=%u headersize=%u hddsize=%u", + sectorsize,ofs,hddsize); + } + } + else { + LOG_MSG("Unable to read .HDI header"); + } + } + } + } + } + + if (sectors == 0 || heads == 0 || cylinders == 0) + active = false; + } + } + + uint8_t imageDisk_Mem::Read_AbsoluteSector(uint32_t sectnum, void * data) { + if (ffdd) return ffdd->ReadSector(sectnum, data); + + uint64_t bytenum,res; + int got; + + bytenum = (uint64_t)sectnum * (uint64_t)sector_size; + if ((bytenum + sector_size) > this->image_length) { + LOG_MSG("Attempt to read invalid sector in Read_AbsoluteSector for sector %lu.\n", (unsigned long)sectnum); + return 0x05; + } + bytenum += image_base; + + //LOG_MSG("Reading sectors %ld at bytenum %I64d", sectnum, bytenum); + + jaffarCommon::file::MemoryFile::fseeko64(_memfile,(fseek_ofs_t)bytenum,SEEK_SET); + res = (uint64_t)jaffarCommon::file::MemoryFile::ftello64(_memfile); + if (res != bytenum) { + LOG_MSG("fseek() failed in Read_AbsoluteSector for sector %lu. Want=%llu Got=%llu\n", + (unsigned long)sectnum,(unsigned long long)bytenum,(unsigned long long)res); + return 0x05; + } + + got = (int)jaffarCommon::file::MemoryFile::fread(data, 1, sector_size, _memfile); + if ((unsigned int)got != sector_size) { + LOG_MSG("fread() failed in Read_AbsoluteSector for sector %lu. Want=%u got=%d\n", + (unsigned long)sectnum,sector_size,(unsigned int)got); + return 0x05; + } + + // size_t checksum = 0; + // for (size_t i = 0; i < sector_size; i++) checksum += ((uint8_t*)data)[i]; + // printf("Read sector %u - From Pos: %lu - Checksum: %lu\n", sectnum, bytenum, checksum); + + _driveUsed = true; + return 0x00; + } + + + uint8_t imageDisk_Mem::Write_AbsoluteSector(uint32_t sectnum, const void *data) { + if (ffdd) return ffdd->WriteSector(sectnum, data); + + uint64_t bytenum; + + bytenum = (uint64_t)sectnum * sector_size; + if ((bytenum + sector_size) > this->image_length) { + LOG_MSG("Attempt to read invalid sector in Write_AbsoluteSector for sector %lu.\n", (unsigned long)sectnum); + return 0x05; + } + bytenum += image_base; + + //LOG_MSG("Writing sectors to %ld at bytenum %d", sectnum, bytenum); + + jaffarCommon::file::MemoryFile::fseeko64(_memfile,(fseek_ofs_t)bytenum,SEEK_SET); + if ((uint64_t)jaffarCommon::file::MemoryFile::ftello64(_memfile) != bytenum) + LOG_MSG("WARNING: fseek() failed in Write_AbsoluteSector for sector %lu\n",(unsigned long)sectnum); + + size_t ret=jaffarCommon::file::MemoryFile::fwrite(data, sector_size, 1, _memfile); + + // size_t checksum = 0; + // for (size_t i = 0; i < sector_size; i++) checksum += ((uint8_t*)data)[i]; + // printf("Write sector %u - From Pos: %lu - Checksum: %lu - ret: %ld\n", sectnum, bytenum, checksum, (ssize_t)ret); + + _driveUsed = true; + return ((ret>0)?0x00:0x05); + } + + void imageDisk_Mem::Set_GeometryForHardDisk() + { + sector_size = 512; + partTable mbrData; + for (int m = (Read_AbsoluteSector(0, &mbrData) ? 0 : 4); m--;) + { + if(!mbrData.pentry[m].partSize) continue; + bootstrap bootbuffer; + if (Read_AbsoluteSector(mbrData.pentry[m].absSectStart, &bootbuffer)) continue; + bootbuffer.sectorspertrack = var_read(&bootbuffer.sectorspertrack); + bootbuffer.headcount = var_read(&bootbuffer.headcount); + uint32_t setSect = bootbuffer.sectorspertrack; + uint32_t setHeads = bootbuffer.headcount; + uint32_t setCyl = (mbrData.pentry[m].absSectStart + mbrData.pentry[m].partSize) / (setSect * setHeads); + Set_Geometry(setHeads, setCyl, setSect, 512); + return; + } + if (!_memfile) return; + uint32_t diskimgsize; + jaffarCommon::file::MemoryFile::fseek(_memfile,0,SEEK_END); + diskimgsize = (uint32_t)jaffarCommon::file::MemoryFile::ftell(_memfile); + jaffarCommon::file::MemoryFile::fseek(_memfile,current_fpos,SEEK_SET); + Set_Geometry(16, diskimgsize / (512 * 63 * 16), 63, 512); + } + + imageDisk_Mem::~imageDisk_Mem() + { + _memFileDirectory.fclose(_memfile); + } \ No newline at end of file diff --git a/src/ints/bios_vhd.cpp b/src/ints/bios_vhd.cpp index 8972b1dad3f..c7174590efe 100644 --- a/src/ints/bios_vhd.cpp +++ b/src/ints/bios_vhd.cpp @@ -31,6 +31,7 @@ #include "mapper.h" #include "SDL.h" +extern bool _driveUsed; /* * imageDiskVHD supports fixed, dynamic, and differential VHD file formats * @@ -112,6 +113,7 @@ imageDiskVHD::ErrorCodes imageDiskVHD::Open(const char* fileName, const bool rea FILE * fopen_lock(const char * fname, const char * mode, bool &readonly); imageDiskVHD::ErrorCodes imageDiskVHD::Open(const char* fileName, const bool readOnly, imageDisk** disk, const uint8_t* matchUniqueId) { + _driveUsed = true; //validate input parameters if (fileName == NULL) return ERROR_OPENING; if (disk == NULL) return ERROR_OPENING; @@ -379,6 +381,7 @@ imageDiskVHD::ErrorCodes imageDiskVHD::TryOpenParent(const char* childFileName, } uint8_t imageDiskVHD::Read_AbsoluteSector(uint32_t sectnum, void * data) { + _driveUsed = true; if(vhdType == VHD_TYPE_FIXED) return fixedDisk->Read_AbsoluteSector(sectnum, data); uint32_t blockNumber = sectnum / sectorsPerBlock; uint32_t sectorOffset = sectnum % sectorsPerBlock; @@ -418,6 +421,7 @@ bool imageDiskVHD::is_block_allocated(uint32_t blockNumber) { } uint8_t imageDiskVHD::Write_AbsoluteSector(uint32_t sectnum, const void * data) { + _driveUsed = true; if(vhdType == VHD_TYPE_FIXED) return fixedDisk->Write_AbsoluteSector(sectnum, data); uint32_t blockNumber = sectnum / sectorsPerBlock; uint32_t sectorOffset = sectnum % sectorsPerBlock; @@ -895,6 +899,7 @@ uint32_t imageDiskVHD::ConvertFixed(const char* filename) { } uint32_t imageDiskVHD::GetInfo(VHDInfo* info) { + _driveUsed = true; uint32_t STATUS = 0; if(info == NULL) info = new VHDInfo(); info->vhdType = vhdType; @@ -921,6 +926,7 @@ uint32_t imageDiskVHD::GetInfo(VHDInfo* info) { } uint32_t imageDiskVHD::GetInfo(const char* filename, VHDInfo** info) { + _driveUsed = true; imageDiskVHD* vhd; if (filename == NULL) return ERROR_OPENING; diff --git a/src/ints/mouse.cpp b/src/ints/mouse.cpp index c1061292611..c8ba66b9c62 100644 --- a/src/ints/mouse.cpp +++ b/src/ints/mouse.cpp @@ -47,10 +47,12 @@ # pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ #endif +mouse_t mouse; + static bool adjust_x_max_excess = false,adjust_y_max_excess = false; static unsigned int assume_max_x = 0,assume_max_y = 0; static int adjust_x = 0,adjust_y = 0; -static int mickey_threshold = 0; +int mickey_threshold = 0; #define VMWARE_PORT 0x5658u // communication port #define VMWARE_PORTHB 0x5659u // communication port, high bandwidth @@ -145,23 +147,16 @@ static int16_t oldmouseX, oldmouseY; // serial mouse emulation void on_mouse_event_for_serial(int delta_x,int delta_y,uint8_t buttonstate); -struct button_event { - uint8_t type; - uint8_t buttons; -}; + extern bool enable_slave_pic, rtl; extern uint8_t p7fd8_8255_mouse_int_enable; uint8_t MOUSE_IRQ = 12; // IBM PC/AT default -#define QUEUE_SIZE 32 -#define MOUSE_BUTTONS 3 #define POS_X (static_cast(mouse.x) & mouse.gran_x) #define POS_Y (static_cast(mouse.y) & mouse.gran_y) -#define CURSORX 16 -#define CURSORY 16 #define HIGHESTBIT (1<<(CURSORX-1)) static uint16_t defaultTextAndMask = 0x77FF; @@ -195,70 +190,6 @@ static uint16_t defaultCursorMaskNEC[CURSORY*2] = { static uint16_t userdefScreenMask[CURSORY]; static uint16_t userdefCursorMask[CURSORY*2]; -static struct { - uint8_t buttons; - int16_t wheel; - uint16_t times_pressed[MOUSE_BUTTONS]; - uint16_t times_released[MOUSE_BUTTONS]; - uint16_t last_released_x[MOUSE_BUTTONS]; - uint16_t last_released_y[MOUSE_BUTTONS]; - uint16_t last_pressed_x[MOUSE_BUTTONS]; - uint16_t last_pressed_y[MOUSE_BUTTONS]; - pic_tickindex_t hidden_at; - uint16_t last_scrolled_x; - uint16_t last_scrolled_y; - uint16_t hidden; - float add_x,add_y; - int16_t min_x,max_x,min_y,max_y; - int16_t max_screen_x,max_screen_y; - int32_t mickey_x,mickey_y; - float mickey_accum_x, mickey_accum_y; - float x,y; - float ps2x,ps2y; - button_event event_queue[QUEUE_SIZE]; - uint8_t events;//Increase if QUEUE_SIZE >255 (currently 32) - uint16_t sub_seg,sub_ofs; - uint16_t sub_mask; - - bool background; - int16_t backposx, backposy; - uint8_t backData[CURSORX*CURSORY]; - uint16_t* screenMask; - uint16_t* cursorMask; - int16_t clipx,clipy; - int16_t hotx,hoty; - uint16_t textAndMask, textXorMask; - - float mickeysPerPixel_x; - float mickeysPerPixel_y; - float pixelPerMickey_x; - float pixelPerMickey_y; - uint16_t senv_x_val; - uint16_t senv_y_val; - uint16_t dspeed_val; - float senv_x; - float senv_y; - int16_t updateRegion_x[2]; - int16_t updateRegion_y[2]; - uint16_t doubleSpeedThreshold; - uint16_t language; - uint16_t cursorType; - uint16_t oldhidden; - uint8_t page; - bool enabled; - bool inhibit_draw; - bool timer_in_progress; - bool first_range_setx; - bool first_range_sety; - bool in_UIR; - uint8_t mode; - int16_t gran_x,gran_y; - int scrollwheel; - uint8_t ps2_type; - uint8_t ps2_rate; // sampling rate is not really emulated, but needed for switching between protocols - uint8_t ps2_packet_size; - uint8_t ps2_unlock_idx; -} mouse; double clamp(double d, double min, double max) { const double t = d < min ? min : d; @@ -398,16 +329,6 @@ Bitu PS2_Handler(void) { #define X_MICKEY 8 #define Y_MICKEY 8 -#define MOUSE_HAS_MOVED 1 -#define MOUSE_LEFT_PRESSED 2 -#define MOUSE_LEFT_RELEASED 4 -#define MOUSE_RIGHT_PRESSED 8 -#define MOUSE_RIGHT_RELEASED 16 -#define MOUSE_MIDDLE_PRESSED 32 -#define MOUSE_MIDDLE_RELEASED 64 -#define MOUSE_WHEEL_MOVED 128 -#define MOUSE_ABSOLUTE 256 - unsigned int user_mouse_report_rate = 0; unsigned int mouse_report_rate = 200; /* DOSBox SVN compatible default (MOUSE_DELAY = 5.0 ms) */ pic_tickindex_t MOUSE_DELAY = 5.0; /* This was once a hard #define */ @@ -448,7 +369,7 @@ void MOUSE_Limit_Events(Bitu /*val*/) { } } -INLINE void Mouse_AddEvent(uint8_t type) { +void Mouse_AddEvent(uint8_t type) { if (mouse.events0) { /* Skip duplicate events */ @@ -818,6 +739,7 @@ static bool AllowINT33RMAccess() { /* FIXME: Re-test this code */ void Mouse_CursorMoved(float xrel,float yrel,float x,float y,bool emulate) { + extern bool Mouse_Vertical; float dx = xrel * mouse.pixelPerMickey_x; float dy = (Mouse_Vertical?-yrel:yrel) * mouse.pixelPerMickey_y; @@ -954,6 +876,7 @@ void Mouse_CursorMoved(float xrel,float yrel,float x,float y,bool emulate) { else if (mouse.ps2y <= -32769.0) mouse.ps2y += 65536.0; } + printf("Mouse_CursorMoved %f, %f, %f, %f, %d. X=%f, Y=%f\n", xrel, yrel, x, y, emulate, mouse.x, mouse.y); Mouse_AddEvent(MOUSE_HAS_MOVED); } diff --git a/src/libs/decoders/internal/opus/celt/stack_alloc.h b/src/libs/decoders/internal/opus/celt/stack_alloc.h index cca25119389..d982a1bc38d 100644 --- a/src/libs/decoders/internal/opus/celt/stack_alloc.h +++ b/src/libs/decoders/internal/opus/celt/stack_alloc.h @@ -1,185 +1,186 @@ -/* Copyright (C) 2002-2003 Jean-Marc Valin - Copyright (C) 2007-2009 Xiph.Org Foundation */ -/** - @file stack_alloc.h - @brief Temporary memory allocation on stack -*/ -/* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#define USE_ALLOCA 1 -#ifndef STACK_ALLOC_H -#define STACK_ALLOC_H - -#include "opus_types.h" -#include "opus_defines.h" - -#if (!defined (VAR_ARRAYS) && !defined (USE_ALLOCA) && !defined (NONTHREADSAFE_PSEUDOSTACK)) -#error "Opus requires one of VAR_ARRAYS, USE_ALLOCA, or NONTHREADSAFE_PSEUDOSTACK be defined to select the temporary allocation mode." -#endif - -#ifdef USE_ALLOCA -# ifdef WIN32 -# include -# else -# ifdef HAVE_ALLOCA_H -# include -# else -# include -# endif -# endif -#endif - -/** - * @def ALIGN(stack, size) - * - * Aligns the stack to a 'size' boundary - * - * @param stack Stack - * @param size New size boundary - */ - -/** - * @def PUSH(stack, size, type) - * - * Allocates 'size' elements of type 'type' on the stack - * - * @param stack Stack - * @param size Number of elements - * @param type Type of element - */ - -/** - * @def VARDECL(var) - * - * Declare variable on stack - * - * @param var Variable to declare - */ - -/** - * @def ALLOC(var, size, type) - * - * Allocate 'size' elements of 'type' on stack - * - * @param var Name of variable to allocate - * @param size Number of elements - * @param type Type of element - */ - -#if defined(VAR_ARRAYS) - -#define VARDECL(type, var) -#define ALLOC(var, size, type) type var[size] -#define SAVE_STACK -#define RESTORE_STACK -#define ALLOC_STACK -/* C99 does not allow VLAs of size zero */ -#define ALLOC_NONE 1 - -#elif defined(USE_ALLOCA) - -#define VARDECL(type, var) type *var - -# ifdef WIN32 -# define ALLOC(var, size, type) var = ((type*)_alloca(sizeof(type)*(size))) -# else -# define ALLOC(var, size, type) var = ((type*)alloca(sizeof(type)*(size))) -# endif - -#define SAVE_STACK -#define RESTORE_STACK -#define ALLOC_STACK -#define ALLOC_NONE 0 - -#else - -#ifdef CELT_C -char *scratch_ptr=0; -char *global_stack=0; -#else -extern char *global_stack; -extern char *scratch_ptr; -#endif /* CELT_C */ - -#ifdef ENABLE_VALGRIND - -#include - -#ifdef CELT_C -char *global_stack_top=0; -#else -extern char *global_stack_top; -#endif /* CELT_C */ - -#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1)) -#define PUSH(stack, size, type) (VALGRIND_MAKE_MEM_NOACCESS(stack, global_stack_top-stack),ALIGN((stack),sizeof(type)/sizeof(char)),VALGRIND_MAKE_MEM_UNDEFINED(stack, ((size)*sizeof(type)/sizeof(char))),(stack)+=(2*(size)*sizeof(type)/sizeof(char)),(type*)((stack)-(2*(size)*sizeof(type)/sizeof(char)))) -#define RESTORE_STACK ((global_stack = _saved_stack),VALGRIND_MAKE_MEM_NOACCESS(global_stack, global_stack_top-global_stack)) -#define ALLOC_STACK char *_saved_stack; ((global_stack = (global_stack==0) ? ((global_stack_top=opus_alloc_scratch(GLOBAL_STACK_SIZE*2)+(GLOBAL_STACK_SIZE*2))-(GLOBAL_STACK_SIZE*2)) : global_stack),VALGRIND_MAKE_MEM_NOACCESS(global_stack, global_stack_top-global_stack)); _saved_stack = global_stack; - -#else - -#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1)) -#define PUSH(stack, size, type) (ALIGN((stack),sizeof(type)/sizeof(char)),(stack)+=(size)*(sizeof(type)/sizeof(char)),(type*)((stack)-(size)*(sizeof(type)/sizeof(char)))) -#if 0 /* Set this to 1 to instrument pseudostack usage */ -#define RESTORE_STACK (printf("%ld %s:%d\n", global_stack-scratch_ptr, __FILE__, __LINE__),global_stack = _saved_stack) -#else -#define RESTORE_STACK (global_stack = _saved_stack) -#endif -#define ALLOC_STACK char *_saved_stack; (global_stack = (global_stack==0) ? (scratch_ptr=opus_alloc_scratch(GLOBAL_STACK_SIZE)) : global_stack); _saved_stack = global_stack; - -#endif /* ENABLE_VALGRIND */ - -#include "os_support.h" -#define VARDECL(type, var) type *var -#define ALLOC(var, size, type) var = PUSH(global_stack, size, type) -#define SAVE_STACK char *_saved_stack = global_stack; -#define ALLOC_NONE 0 - -#endif /* VAR_ARRAYS */ - - -#ifdef ENABLE_VALGRIND - -#include -#define OPUS_CHECK_ARRAY(ptr, len) VALGRIND_CHECK_MEM_IS_DEFINED(ptr, len*sizeof(*ptr)) -#define OPUS_CHECK_VALUE(value) VALGRIND_CHECK_VALUE_IS_DEFINED(value) -#define OPUS_CHECK_ARRAY_COND(ptr, len) VALGRIND_CHECK_MEM_IS_DEFINED(ptr, len*sizeof(*ptr)) -#define OPUS_CHECK_VALUE_COND(value) VALGRIND_CHECK_VALUE_IS_DEFINED(value) -#define OPUS_PRINT_INT(value) do {fprintf(stderr, #value " = %d at %s:%d\n", value, __FILE__, __LINE__);}while(0) -#define OPUS_FPRINTF fprintf - -#else - -static OPUS_INLINE int _opus_false(void) {return 0;} -#define OPUS_CHECK_ARRAY(ptr, len) _opus_false() -#define OPUS_CHECK_VALUE(value) _opus_false() -#define OPUS_PRINT_INT(value) do{}while(0) -#define OPUS_FPRINTF (void) - -#endif - - -#endif /* STACK_ALLOC_H */ +/* Copyright (C) 2002-2003 Jean-Marc Valin + Copyright (C) 2007-2009 Xiph.Org Foundation */ +/** + @file stack_alloc.h + @brief Temporary memory allocation on stack +*/ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +//#define USE_ALLOCA 1 +#define VAR_ARRAYS +#ifndef STACK_ALLOC_H +#define STACK_ALLOC_H + +#include "opus_types.h" +#include "opus_defines.h" + +#if (!defined (VAR_ARRAYS) && !defined (USE_ALLOCA) && !defined (NONTHREADSAFE_PSEUDOSTACK)) +#error "Opus requires one of VAR_ARRAYS, USE_ALLOCA, or NONTHREADSAFE_PSEUDOSTACK be defined to select the temporary allocation mode." +#endif + +#ifdef USE_ALLOCA +# ifdef WIN32 +# include +# else +# ifdef HAVE_ALLOCA_H +# include +# else +# include +# endif +# endif +#endif + +/** + * @def ALIGN(stack, size) + * + * Aligns the stack to a 'size' boundary + * + * @param stack Stack + * @param size New size boundary + */ + +/** + * @def PUSH(stack, size, type) + * + * Allocates 'size' elements of type 'type' on the stack + * + * @param stack Stack + * @param size Number of elements + * @param type Type of element + */ + +/** + * @def VARDECL(var) + * + * Declare variable on stack + * + * @param var Variable to declare + */ + +/** + * @def ALLOC(var, size, type) + * + * Allocate 'size' elements of 'type' on stack + * + * @param var Name of variable to allocate + * @param size Number of elements + * @param type Type of element + */ + +#if defined(VAR_ARRAYS) + +#define VARDECL(type, var) +#define ALLOC(var, size, type) type var[size] +#define SAVE_STACK +#define RESTORE_STACK +#define ALLOC_STACK +/* C99 does not allow VLAs of size zero */ +#define ALLOC_NONE 1 + +#elif defined(USE_ALLOCA) + +#define VARDECL(type, var) type *var + +# ifdef WIN32 +# define ALLOC(var, size, type) var = ((type*)_alloca(sizeof(type)*(size))) +# else +# define ALLOC(var, size, type) var = ((type*)alloca(sizeof(type)*(size))) +# endif + +#define SAVE_STACK +#define RESTORE_STACK +#define ALLOC_STACK +#define ALLOC_NONE 0 + +#else + +#ifdef CELT_C +char *scratch_ptr=0; +char *global_stack=0; +#else +extern char *global_stack; +extern char *scratch_ptr; +#endif /* CELT_C */ + +#ifdef ENABLE_VALGRIND + +#include + +#ifdef CELT_C +char *global_stack_top=0; +#else +extern char *global_stack_top; +#endif /* CELT_C */ + +#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1)) +#define PUSH(stack, size, type) (VALGRIND_MAKE_MEM_NOACCESS(stack, global_stack_top-stack),ALIGN((stack),sizeof(type)/sizeof(char)),VALGRIND_MAKE_MEM_UNDEFINED(stack, ((size)*sizeof(type)/sizeof(char))),(stack)+=(2*(size)*sizeof(type)/sizeof(char)),(type*)((stack)-(2*(size)*sizeof(type)/sizeof(char)))) +#define RESTORE_STACK ((global_stack = _saved_stack),VALGRIND_MAKE_MEM_NOACCESS(global_stack, global_stack_top-global_stack)) +#define ALLOC_STACK char *_saved_stack; ((global_stack = (global_stack==0) ? ((global_stack_top=opus_alloc_scratch(GLOBAL_STACK_SIZE*2)+(GLOBAL_STACK_SIZE*2))-(GLOBAL_STACK_SIZE*2)) : global_stack),VALGRIND_MAKE_MEM_NOACCESS(global_stack, global_stack_top-global_stack)); _saved_stack = global_stack; + +#else + +#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1)) +#define PUSH(stack, size, type) (ALIGN((stack),sizeof(type)/sizeof(char)),(stack)+=(size)*(sizeof(type)/sizeof(char)),(type*)((stack)-(size)*(sizeof(type)/sizeof(char)))) +#if 0 /* Set this to 1 to instrument pseudostack usage */ +#define RESTORE_STACK (printf("%ld %s:%d\n", global_stack-scratch_ptr, __FILE__, __LINE__),global_stack = _saved_stack) +#else +#define RESTORE_STACK (global_stack = _saved_stack) +#endif +#define ALLOC_STACK char *_saved_stack; (global_stack = (global_stack==0) ? (scratch_ptr=opus_alloc_scratch(GLOBAL_STACK_SIZE)) : global_stack); _saved_stack = global_stack; + +#endif /* ENABLE_VALGRIND */ + +#include "os_support.h" +#define VARDECL(type, var) type *var +#define ALLOC(var, size, type) var = PUSH(global_stack, size, type) +#define SAVE_STACK char *_saved_stack = global_stack; +#define ALLOC_NONE 0 + +#endif /* VAR_ARRAYS */ + + +#ifdef ENABLE_VALGRIND + +#include +#define OPUS_CHECK_ARRAY(ptr, len) VALGRIND_CHECK_MEM_IS_DEFINED(ptr, len*sizeof(*ptr)) +#define OPUS_CHECK_VALUE(value) VALGRIND_CHECK_VALUE_IS_DEFINED(value) +#define OPUS_CHECK_ARRAY_COND(ptr, len) VALGRIND_CHECK_MEM_IS_DEFINED(ptr, len*sizeof(*ptr)) +#define OPUS_CHECK_VALUE_COND(value) VALGRIND_CHECK_VALUE_IS_DEFINED(value) +#define OPUS_PRINT_INT(value) do {fprintf(stderr, #value " = %d at %s:%d\n", value, __FILE__, __LINE__);}while(0) +#define OPUS_FPRINTF fprintf + +#else + +static OPUS_INLINE int _opus_false(void) {return 0;} +#define OPUS_CHECK_ARRAY(ptr, len) _opus_false() +#define OPUS_CHECK_VALUE(value) _opus_false() +#define OPUS_PRINT_INT(value) do{}while(0) +#define OPUS_FPRINTF (void) + +#endif + + +#endif /* STACK_ALLOC_H */ diff --git a/src/libs/decoders/internal/opus/src/opus_multistream_encoder.c b/src/libs/decoders/internal/opus/src/opus_multistream_encoder.c index 24a8e4bbb08..d8f280510c6 100644 --- a/src/libs/decoders/internal/opus/src/opus_multistream_encoder.c +++ b/src/libs/decoders/internal/opus/src/opus_multistream_encoder.c @@ -1,1328 +1,1328 @@ -/* Copyright (c) 2011 Xiph.Org Foundation - Written by Jean-Marc Valin */ -/* - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "opus_multistream.h" -#include "opus.h" -#include "opus_private.h" -#include "../celt/stack_alloc.h" -#include -#include "../celt/float_cast.h" -#include "../celt/os_support.h" -#include "../celt/mathops.h" -#include "../celt/mdct.h" -#include "../celt/../celt/modes.h" -#include "../celt/bands.h" -#include "../celt/quant_bands.h" -#include "../celt/pitch.h" - -typedef struct { - int nb_streams; - int nb_coupled_streams; - unsigned char mapping[8]; -} VorbisLayout; - -/* Index is nb_channel-1*/ -static const VorbisLayout vorbis_mappings[8] = { - {1, 0, {0}}, /* 1: mono */ - {1, 1, {0, 1}}, /* 2: stereo */ - {2, 1, {0, 2, 1}}, /* 3: 1-d surround */ - {2, 2, {0, 1, 2, 3}}, /* 4: quadraphonic surround */ - {3, 2, {0, 4, 1, 2, 3}}, /* 5: 5-channel surround */ - {4, 2, {0, 4, 1, 2, 3, 5}}, /* 6: 5.1 surround */ - {4, 3, {0, 4, 1, 2, 3, 5, 6}}, /* 7: 6.1 surround */ - {5, 3, {0, 6, 1, 2, 3, 4, 5, 7}}, /* 8: 7.1 surround */ -}; - -static opus_val32 *ms_get_preemph_mem(OpusMSEncoder *st) -{ - int s; - char *ptr; - int coupled_size, mono_size; - - coupled_size = opus_encoder_get_size(2); - mono_size = opus_encoder_get_size(1); - ptr = (char*)st + align(sizeof(OpusMSEncoder)); - for (s=0;slayout.nb_streams;s++) - { - if (s < st->layout.nb_coupled_streams) - ptr += align(coupled_size); - else - ptr += align(mono_size); - } - /* void* cast avoids clang -Wcast-align warning */ - return (opus_val32*)(void*)(ptr+st->layout.nb_channels*120*sizeof(opus_val32)); -} - -static opus_val32 *ms_get_window_mem(OpusMSEncoder *st) -{ - int s; - char *ptr; - int coupled_size, mono_size; - - coupled_size = opus_encoder_get_size(2); - mono_size = opus_encoder_get_size(1); - ptr = (char*)st + align(sizeof(OpusMSEncoder)); - for (s=0;slayout.nb_streams;s++) - { - if (s < st->layout.nb_coupled_streams) - ptr += align(coupled_size); - else - ptr += align(mono_size); - } - /* void* cast avoids clang -Wcast-align warning */ - return (opus_val32*)(void*)ptr; -} - -static int validate_ambisonics(int nb_channels, int *nb_streams, int *nb_coupled_streams) -{ - int order_plus_one; - int acn_channels; - int nondiegetic_channels; - - if (nb_channels < 1 || nb_channels > 227) - return 0; - - order_plus_one = isqrt32(nb_channels); - acn_channels = order_plus_one * order_plus_one; - nondiegetic_channels = nb_channels - acn_channels; - - if (nondiegetic_channels != 0 && nondiegetic_channels != 2) - return 0; - - if (nb_streams) - *nb_streams = acn_channels + (nondiegetic_channels != 0); - if (nb_coupled_streams) - *nb_coupled_streams = nondiegetic_channels != 0; - return 1; -} - -static int validate_encoder_layout(const ChannelLayout *layout) -{ - int s; - for (s=0;snb_streams;s++) - { - if (s < layout->nb_coupled_streams) - { - if (get_left_channel(layout, s, -1)==-1) - return 0; - if (get_right_channel(layout, s, -1)==-1) - return 0; - } else { - if (get_mono_channel(layout, s, -1)==-1) - return 0; - } - } - return 1; -} - -static void channel_pos(int channels, int pos[8]) -{ - /* Position in the mix: 0 don't mix, 1: left, 2: center, 3:right */ - if (channels==4) - { - pos[0]=1; - pos[1]=3; - pos[2]=1; - pos[3]=3; - } else if (channels==3||channels==5||channels==6) - { - pos[0]=1; - pos[1]=2; - pos[2]=3; - pos[3]=1; - pos[4]=3; - pos[5]=0; - } else if (channels==7) - { - pos[0]=1; - pos[1]=2; - pos[2]=3; - pos[3]=1; - pos[4]=3; - pos[5]=2; - pos[6]=0; - } else if (channels==8) - { - pos[0]=1; - pos[1]=2; - pos[2]=3; - pos[3]=1; - pos[4]=3; - pos[5]=1; - pos[6]=3; - pos[7]=0; - } -} - -#if 1 -/* Computes a rough approximation of log2(2^a + 2^b) */ -static opus_val16 logSum(opus_val16 a, opus_val16 b) -{ - opus_val16 max; - opus_val32 diff; - opus_val16 frac; - static const opus_val16 diff_table[17] = { - QCONST16(0.5000000f, DB_SHIFT), QCONST16(0.2924813f, DB_SHIFT), QCONST16(0.1609640f, DB_SHIFT), QCONST16(0.0849625f, DB_SHIFT), - QCONST16(0.0437314f, DB_SHIFT), QCONST16(0.0221971f, DB_SHIFT), QCONST16(0.0111839f, DB_SHIFT), QCONST16(0.0056136f, DB_SHIFT), - QCONST16(0.0028123f, DB_SHIFT) - }; - int low; - if (a>b) - { - max = a; - diff = SUB32(EXTEND32(a),EXTEND32(b)); - } else { - max = b; - diff = SUB32(EXTEND32(b),EXTEND32(a)); - } - if (!(diff < QCONST16(8.f, DB_SHIFT))) /* inverted to catch NaNs */ - return max; -#ifdef FIXED_POINT - low = SHR32(diff, DB_SHIFT-1); - frac = SHL16(diff - SHL16(low, DB_SHIFT-1), 16-DB_SHIFT); -#else - low = (int)floor(2*diff); - frac = 2*diff - low; -#endif - return max + diff_table[low] + MULT16_16_Q15(frac, SUB16(diff_table[low+1], diff_table[low])); -} -#else -opus_val16 logSum(opus_val16 a, opus_val16 b) -{ - return log2(pow(4, a)+ pow(4, b))/2; -} -#endif - -void surround_analysis(const CELTMode *celt_mode, const void *pcm, opus_val16 *bandLogE, opus_val32 *mem, opus_val32 *preemph_mem, - int len, int overlap, int channels, int rate, opus_copy_channel_in_func copy_channel_in, int arch -) -{ - int c; - int i; - int LM; - int pos[8] = {0}; - int upsample; - int frame_size; - int freq_size; - opus_val16 channel_offset; - opus_val32 bandE[21]; - opus_val16 maskLogE[3][21]; - VARDECL(opus_val32, in); - VARDECL(opus_val16, x); - VARDECL(opus_val32, freq); - SAVE_STACK; - - upsample = resampling_factor(rate); - frame_size = len*upsample; - freq_size = IMIN(960, frame_size); - - /* LM = log2(frame_size / 120) */ - for (LM=0;LMmaxLM;LM++) - if (celt_mode->shortMdctSize<preemph, preemph_mem+c, 0); -#ifndef FIXED_POINT - { - opus_val32 sum; - sum = celt_inner_prod(in, in, frame_size+overlap, 0); - /* This should filter out both NaNs and ridiculous signals that could - cause NaNs further down. */ - if (!(sum < 1e18f) || celt_isnan(sum)) - { - OPUS_CLEAR(in, frame_size+overlap); - preemph_mem[c] = 0; - } - } -#endif - OPUS_CLEAR(bandE, 21); - for (frame=0;framemdct, in+960*frame, freq, celt_mode->window, - overlap, celt_mode->maxLM-LM, 1, arch); - if (upsample != 1) - { - int bound = freq_size/upsample; - for (i=0;i=0;i--) - bandLogE[21*c+i] = MAX16(bandLogE[21*c+i], bandLogE[21*c+i+1]-QCONST16(2.f, DB_SHIFT)); - if (pos[c]==1) - { - for (i=0;i<21;i++) - maskLogE[0][i] = logSum(maskLogE[0][i], bandLogE[21*c+i]); - } else if (pos[c]==3) - { - for (i=0;i<21;i++) - maskLogE[2][i] = logSum(maskLogE[2][i], bandLogE[21*c+i]); - } else if (pos[c]==2) - { - for (i=0;i<21;i++) - { - maskLogE[0][i] = logSum(maskLogE[0][i], bandLogE[21*c+i]-QCONST16(.5f, DB_SHIFT)); - maskLogE[2][i] = logSum(maskLogE[2][i], bandLogE[21*c+i]-QCONST16(.5f, DB_SHIFT)); - } - } -#if 0 - for (i=0;i<21;i++) - printf("%f ", bandLogE[21*c+i]); - float sum=0; - for (i=0;i<21;i++) - sum += bandLogE[21*c+i]; - printf("%f ", sum/21); -#endif - OPUS_COPY(mem+c*overlap, in+frame_size, overlap); - } - for (i=0;i<21;i++) - maskLogE[1][i] = MIN32(maskLogE[0][i],maskLogE[2][i]); - channel_offset = HALF16(celt_log2(QCONST32(2.f,14)/(channels-1))); - for (c=0;c<3;c++) - for (i=0;i<21;i++) - maskLogE[c][i] += channel_offset; -#if 0 - for (c=0;c<3;c++) - { - for (i=0;i<21;i++) - printf("%f ", maskLogE[c][i]); - } -#endif - for (c=0;cnb_streams||nb_coupled_streams<0)return 0; - coupled_size = opus_encoder_get_size(2); - mono_size = opus_encoder_get_size(1); - return align(sizeof(OpusMSEncoder)) - + nb_coupled_streams * align(coupled_size) - + (nb_streams-nb_coupled_streams) * align(mono_size); -} - -opus_int32 opus_multistream_surround_encoder_get_size(int channels, int mapping_family) -{ - int nb_streams; - int nb_coupled_streams; - opus_int32 size; - - if (mapping_family==0) - { - if (channels==1) - { - nb_streams=1; - nb_coupled_streams=0; - } else if (channels==2) - { - nb_streams=1; - nb_coupled_streams=1; - } else - return 0; - } else if (mapping_family==1 && channels<=8 && channels>=1) - { - nb_streams=vorbis_mappings[channels-1].nb_streams; - nb_coupled_streams=vorbis_mappings[channels-1].nb_coupled_streams; - } else if (mapping_family==255) - { - nb_streams=channels; - nb_coupled_streams=0; - } else if (mapping_family==2) - { - if (!validate_ambisonics(channels, &nb_streams, &nb_coupled_streams)) - return 0; - } else - return 0; - size = opus_multistream_encoder_get_size(nb_streams, nb_coupled_streams); - if (channels>2) - { - size += channels*(120*sizeof(opus_val32) + sizeof(opus_val32)); - } - return size; -} - -static int opus_multistream_encoder_init_impl( - OpusMSEncoder *st, - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - const unsigned char *mapping, - int application, - MappingType mapping_type -) -{ - int coupled_size; - int mono_size; - int i, ret; - char *ptr; - - if ((channels>255) || (channels<1) || (coupled_streams>streams) || - (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams)) - return OPUS_BAD_ARG; - - st->arch = opus_select_arch(); - st->layout.nb_channels = channels; - st->layout.nb_streams = streams; - st->layout.nb_coupled_streams = coupled_streams; - if (mapping_type != MAPPING_TYPE_SURROUND) - st->lfe_stream = -1; - st->bitrate_bps = OPUS_AUTO; - st->application = application; - st->variable_duration = OPUS_FRAMESIZE_ARG; - for (i=0;ilayout.nb_channels;i++) - st->layout.mapping[i] = mapping[i]; - if (!validate_layout(&st->layout)) - return OPUS_BAD_ARG; - if (mapping_type == MAPPING_TYPE_SURROUND && - !validate_encoder_layout(&st->layout)) - return OPUS_BAD_ARG; - if (mapping_type == MAPPING_TYPE_AMBISONICS && - !validate_ambisonics(st->layout.nb_channels, NULL, NULL)) - return OPUS_BAD_ARG; - ptr = (char*)st + align(sizeof(OpusMSEncoder)); - coupled_size = opus_encoder_get_size(2); - mono_size = opus_encoder_get_size(1); - - for (i=0;ilayout.nb_coupled_streams;i++) - { - ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 2, application); - if(ret!=OPUS_OK)return ret; - if (i==st->lfe_stream) - opus_encoder_ctl((OpusEncoder*)ptr, OPUS_SET_LFE(1)); - ptr += align(coupled_size); - } - for (;ilayout.nb_streams;i++) - { - ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 1, application); - if (i==st->lfe_stream) - opus_encoder_ctl((OpusEncoder*)ptr, OPUS_SET_LFE(1)); - if(ret!=OPUS_OK)return ret; - ptr += align(mono_size); - } - if (mapping_type == MAPPING_TYPE_SURROUND) - { - OPUS_CLEAR(ms_get_preemph_mem(st), channels); - OPUS_CLEAR(ms_get_window_mem(st), channels*120); - } - st->mapping_type = mapping_type; - return OPUS_OK; -} - -int opus_multistream_encoder_init( - OpusMSEncoder *st, - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - const unsigned char *mapping, - int application -) -{ - return opus_multistream_encoder_init_impl(st, Fs, channels, streams, - coupled_streams, mapping, - application, MAPPING_TYPE_NONE); -} - -int opus_multistream_surround_encoder_init( - OpusMSEncoder *st, - opus_int32 Fs, - int channels, - int mapping_family, - int *streams, - int *coupled_streams, - unsigned char *mapping, - int application -) -{ - MappingType mapping_type; - - if ((channels>255) || (channels<1)) - return OPUS_BAD_ARG; - st->lfe_stream = -1; - if (mapping_family==0) - { - if (channels==1) - { - *streams=1; - *coupled_streams=0; - mapping[0]=0; - } else if (channels==2) - { - *streams=1; - *coupled_streams=1; - mapping[0]=0; - mapping[1]=1; - } else - return OPUS_UNIMPLEMENTED; - } else if (mapping_family==1 && channels<=8 && channels>=1) - { - int i; - *streams=vorbis_mappings[channels-1].nb_streams; - *coupled_streams=vorbis_mappings[channels-1].nb_coupled_streams; - for (i=0;i=6) - st->lfe_stream = *streams-1; - } else if (mapping_family==255) - { - int i; - *streams=channels; - *coupled_streams=0; - for(i=0;i2 && mapping_family==1) { - mapping_type = MAPPING_TYPE_SURROUND; - } else if (mapping_family==2) - { - mapping_type = MAPPING_TYPE_AMBISONICS; - } else - { - mapping_type = MAPPING_TYPE_NONE; - } - return opus_multistream_encoder_init_impl(st, Fs, channels, *streams, - *coupled_streams, mapping, - application, mapping_type); -} - -OpusMSEncoder *opus_multistream_encoder_create( - opus_int32 Fs, - int channels, - int streams, - int coupled_streams, - const unsigned char *mapping, - int application, - int *error -) -{ - int ret; - OpusMSEncoder *st; - if ((channels>255) || (channels<1) || (coupled_streams>streams) || - (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams)) - { - if (error) - *error = OPUS_BAD_ARG; - return NULL; - } - st = (OpusMSEncoder *)opus_alloc(opus_multistream_encoder_get_size(streams, coupled_streams)); - if (st==NULL) - { - if (error) - *error = OPUS_ALLOC_FAIL; - return NULL; - } - ret = opus_multistream_encoder_init(st, Fs, channels, streams, coupled_streams, mapping, application); - if (ret != OPUS_OK) - { - opus_free(st); - st = NULL; - } - if (error) - *error = ret; - return st; -} - -OpusMSEncoder *opus_multistream_surround_encoder_create( - opus_int32 Fs, - int channels, - int mapping_family, - int *streams, - int *coupled_streams, - unsigned char *mapping, - int application, - int *error -) -{ - int ret; - opus_int32 size; - OpusMSEncoder *st; - if ((channels>255) || (channels<1)) - { - if (error) - *error = OPUS_BAD_ARG; - return NULL; - } - size = opus_multistream_surround_encoder_get_size(channels, mapping_family); - if (!size) - { - if (error) - *error = OPUS_UNIMPLEMENTED; - return NULL; - } - st = (OpusMSEncoder *)opus_alloc(size); - if (st==NULL) - { - if (error) - *error = OPUS_ALLOC_FAIL; - return NULL; - } - ret = opus_multistream_surround_encoder_init(st, Fs, channels, mapping_family, streams, coupled_streams, mapping, application); - if (ret != OPUS_OK) - { - opus_free(st); - st = NULL; - } - if (error) - *error = ret; - return st; -} - -static void surround_rate_allocation( - OpusMSEncoder *st, - opus_int32 *rate, - int frame_size, - opus_int32 Fs - ) -{ - int i; - opus_int32 channel_rate; - int stream_offset; - int lfe_offset; - int coupled_ratio; /* Q8 */ - int lfe_ratio; /* Q8 */ - int nb_lfe; - int nb_uncoupled; - int nb_coupled; - int nb_normal; - opus_int32 channel_offset; - opus_int32 bitrate; - int total; - - nb_lfe = (st->lfe_stream!=-1); - nb_coupled = st->layout.nb_coupled_streams; - nb_uncoupled = st->layout.nb_streams-nb_coupled-nb_lfe; - nb_normal = 2*nb_coupled + nb_uncoupled; - - /* Give each non-LFE channel enough bits per channel for coding band energy. */ - channel_offset = 40*IMAX(50, Fs/frame_size); - - if (st->bitrate_bps==OPUS_AUTO) - { - bitrate = nb_normal*(channel_offset + Fs + 10000) + 8000*nb_lfe; - } else if (st->bitrate_bps==OPUS_BITRATE_MAX) - { - bitrate = nb_normal*300000 + nb_lfe*128000; - } else { - bitrate = st->bitrate_bps; - } - - /* Give LFE some basic stream_channel allocation but never exceed 1/20 of the - total rate for the non-energy part to avoid problems at really low rate. */ - lfe_offset = IMIN(bitrate/20, 3000) + 15*IMAX(50, Fs/frame_size); - - /* We give each stream (coupled or uncoupled) a starting bitrate. - This models the main saving of coupled channels over uncoupled. */ - stream_offset = (bitrate - channel_offset*nb_normal - lfe_offset*nb_lfe)/nb_normal/2; - stream_offset = IMAX(0, IMIN(20000, stream_offset)); - - /* Coupled streams get twice the mono rate after the offset is allocated. */ - coupled_ratio = 512; - /* Should depend on the bitrate, for now we assume LFE gets 1/8 the bits of mono */ - lfe_ratio = 32; - - total = (nb_uncoupled<<8) /* mono */ - + coupled_ratio*nb_coupled /* stereo */ - + nb_lfe*lfe_ratio; - channel_rate = 256*(opus_int64)(bitrate - lfe_offset*nb_lfe - stream_offset*(nb_coupled+nb_uncoupled) - channel_offset*nb_normal)/total; - - for (i=0;ilayout.nb_streams;i++) - { - if (ilayout.nb_coupled_streams) - rate[i] = 2*channel_offset + IMAX(0, stream_offset+(channel_rate*coupled_ratio>>8)); - else if (i!=st->lfe_stream) - rate[i] = channel_offset + IMAX(0, stream_offset + channel_rate); - else - rate[i] = IMAX(0, lfe_offset+(channel_rate*lfe_ratio>>8)); - } -} - -static void ambisonics_rate_allocation( - OpusMSEncoder *st, - opus_int32 *rate, - int frame_size, - opus_int32 Fs - ) -{ - int i; - opus_int32 total_rate; - opus_int32 per_stream_rate; - - const int nb_channels = st->layout.nb_streams + st->layout.nb_coupled_streams; - - if (st->bitrate_bps==OPUS_AUTO) - { - total_rate = (st->layout.nb_coupled_streams + st->layout.nb_streams) * - (Fs+60*Fs/frame_size) + st->layout.nb_streams * (opus_int32)15000; - } else if (st->bitrate_bps==OPUS_BITRATE_MAX) - { - total_rate = nb_channels * 320000; - } else - { - total_rate = st->bitrate_bps; - } - - /* Allocate equal number of bits to Ambisonic (uncoupled) and non-diegetic - * (coupled) streams */ - per_stream_rate = total_rate / st->layout.nb_streams; - for (i = 0; i < st->layout.nb_streams; i++) - { - rate[i] = per_stream_rate; - } -} - -static opus_int32 rate_allocation( - OpusMSEncoder *st, - opus_int32 *rate, - int frame_size - ) -{ - int i; - opus_int32 rate_sum=0; - opus_int32 Fs; - char *ptr; - - ptr = (char*)st + align(sizeof(OpusMSEncoder)); - opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs)); - - if (st->mapping_type == MAPPING_TYPE_AMBISONICS) { - ambisonics_rate_allocation(st, rate, frame_size, Fs); - } else - { - surround_rate_allocation(st, rate, frame_size, Fs); - } - - for (i=0;ilayout.nb_streams;i++) - { - rate[i] = IMAX(rate[i], 500); - rate_sum += rate[i]; - } - return rate_sum; -} - -/* Max size in case the encoder decides to return six frames (6 x 20 ms = 120 ms) */ -#define MS_FRAME_TMP (6*1275+12) -int opus_multistream_encode_native -( - OpusMSEncoder *st, - opus_copy_channel_in_func copy_channel_in, - const void *pcm, - int analysis_frame_size, - unsigned char *data, - opus_int32 max_data_bytes, - int lsb_depth, - downmix_func downmix, - int float_api, - void *user_data -) -{ - opus_int32 Fs; - int coupled_size; - int mono_size; - int s; - char *ptr; - int tot_size; - VARDECL(opus_val16, buf); - VARDECL(opus_val16, bandSMR); - unsigned char tmp_data[MS_FRAME_TMP]; - OpusRepacketizer rp; - opus_int32 vbr; - const CELTMode *celt_mode; - opus_int32 bitrates[256]; - opus_val16 bandLogE[42]; - opus_val32 *mem = NULL; - opus_val32 *preemph_mem=NULL; - int frame_size; - opus_int32 rate_sum; - opus_int32 smallest_packet; - ALLOC_STACK; - - if (st->mapping_type == MAPPING_TYPE_SURROUND) - { - preemph_mem = ms_get_preemph_mem(st); - mem = ms_get_window_mem(st); - } - - ptr = (char*)st + align(sizeof(OpusMSEncoder)); - opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs)); - opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_VBR(&vbr)); - opus_encoder_ctl((OpusEncoder*)ptr, CELT_GET_MODE(&celt_mode)); - - frame_size = frame_size_select(analysis_frame_size, st->variable_duration, Fs); - if (frame_size <= 0) - { - RESTORE_STACK; - return OPUS_BAD_ARG; - } - - /* Smallest packet the encoder can produce. */ - smallest_packet = st->layout.nb_streams*2-1; - /* 100 ms needs an extra byte per stream for the ToC. */ - if (Fs/frame_size == 10) - smallest_packet += st->layout.nb_streams; - if (max_data_bytes < smallest_packet) - { - RESTORE_STACK; - return OPUS_BUFFER_TOO_SMALL; - } - ALLOC(buf, 2*frame_size, opus_val16); - coupled_size = opus_encoder_get_size(2); - mono_size = opus_encoder_get_size(1); - - ALLOC(bandSMR, 21*st->layout.nb_channels, opus_val16); - if (st->mapping_type == MAPPING_TYPE_SURROUND) - { - surround_analysis(celt_mode, pcm, bandSMR, mem, preemph_mem, frame_size, 120, st->layout.nb_channels, Fs, copy_channel_in, st->arch); - } - - /* Compute bitrate allocation between streams (this could be a lot better) */ - rate_sum = rate_allocation(st, bitrates, frame_size); - - if (!vbr) - { - if (st->bitrate_bps == OPUS_AUTO) - { - max_data_bytes = IMIN(max_data_bytes, 3*rate_sum/(3*8*Fs/frame_size)); - } else if (st->bitrate_bps != OPUS_BITRATE_MAX) - { - max_data_bytes = IMIN(max_data_bytes, IMAX(smallest_packet, - 3*st->bitrate_bps/(3*8*Fs/frame_size))); - } - } - ptr = (char*)st + align(sizeof(OpusMSEncoder)); - for (s=0;slayout.nb_streams;s++) - { - OpusEncoder *enc; - enc = (OpusEncoder*)ptr; - if (s < st->layout.nb_coupled_streams) - ptr += align(coupled_size); - else - ptr += align(mono_size); - opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrates[s])); - if (st->mapping_type == MAPPING_TYPE_SURROUND) - { - opus_int32 equiv_rate; - equiv_rate = st->bitrate_bps; - if (frame_size*50 < Fs) - equiv_rate -= 60*(Fs/frame_size - 50)*st->layout.nb_channels; - if (equiv_rate > 10000*st->layout.nb_channels) - opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_FULLBAND)); - else if (equiv_rate > 7000*st->layout.nb_channels) - opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_SUPERWIDEBAND)); - else if (equiv_rate > 5000*st->layout.nb_channels) - opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_WIDEBAND)); - else - opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_NARROWBAND)); - if (s < st->layout.nb_coupled_streams) - { - /* To preserve the spatial image, force stereo CELT on coupled streams */ - opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY)); - opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(2)); - } - } - else if (st->mapping_type == MAPPING_TYPE_AMBISONICS) { - opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY)); - } - } - - ptr = (char*)st + align(sizeof(OpusMSEncoder)); - /* Counting ToC */ - tot_size = 0; - for (s=0;slayout.nb_streams;s++) - { - OpusEncoder *enc; - int len; - int curr_max; - int c1, c2; - int ret; - - opus_repacketizer_init(&rp); - enc = (OpusEncoder*)ptr; - if (s < st->layout.nb_coupled_streams) - { - int i; - int left, right; - left = get_left_channel(&st->layout, s, -1); - right = get_right_channel(&st->layout, s, -1); - (*copy_channel_in)(buf, 2, - pcm, st->layout.nb_channels, left, frame_size, user_data); - (*copy_channel_in)(buf+1, 2, - pcm, st->layout.nb_channels, right, frame_size, user_data); - ptr += align(coupled_size); - if (st->mapping_type == MAPPING_TYPE_SURROUND) - { - for (i=0;i<21;i++) - { - bandLogE[i] = bandSMR[21*left+i]; - bandLogE[21+i] = bandSMR[21*right+i]; - } - } - c1 = left; - c2 = right; - } else { - int i; - int chan = get_mono_channel(&st->layout, s, -1); - (*copy_channel_in)(buf, 1, - pcm, st->layout.nb_channels, chan, frame_size, user_data); - ptr += align(mono_size); - if (st->mapping_type == MAPPING_TYPE_SURROUND) - { - for (i=0;i<21;i++) - bandLogE[i] = bandSMR[21*chan+i]; - } - c1 = chan; - c2 = -1; - } - if (st->mapping_type == MAPPING_TYPE_SURROUND) - opus_encoder_ctl(enc, OPUS_SET_ENERGY_MASK(bandLogE)); - /* number of bytes left (+Toc) */ - curr_max = max_data_bytes - tot_size; - /* Reserve one byte for the last stream and two for the others */ - curr_max -= IMAX(0,2*(st->layout.nb_streams-s-1)-1); - /* For 100 ms, reserve an extra byte per stream for the ToC */ - if (Fs/frame_size == 10) - curr_max -= st->layout.nb_streams-s-1; - curr_max = IMIN(curr_max,MS_FRAME_TMP); - /* Repacketizer will add one or two bytes for self-delimited frames */ - if (s != st->layout.nb_streams-1) curr_max -= curr_max>253 ? 2 : 1; - if (!vbr && s == st->layout.nb_streams-1) - opus_encoder_ctl(enc, OPUS_SET_BITRATE(curr_max*(8*Fs/frame_size))); - len = opus_encode_native(enc, buf, frame_size, tmp_data, curr_max, lsb_depth, - pcm, analysis_frame_size, c1, c2, st->layout.nb_channels, downmix, float_api); - if (len<0) - { - RESTORE_STACK; - return len; - } - /* We need to use the repacketizer to add the self-delimiting lengths - while taking into account the fact that the encoder can now return - more than one frame at a time (e.g. 60 ms CELT-only) */ - ret = opus_repacketizer_cat(&rp, tmp_data, len); - /* If the opus_repacketizer_cat() fails, then something's seriously wrong - with the encoder. */ - if (ret != OPUS_OK) - { - RESTORE_STACK; - return OPUS_INTERNAL_ERROR; - } - len = opus_repacketizer_out_range_impl(&rp, 0, opus_repacketizer_get_nb_frames(&rp), - data, max_data_bytes-tot_size, s != st->layout.nb_streams-1, !vbr && s == st->layout.nb_streams-1); - data += len; - tot_size += len; - } - /*printf("\n");*/ - RESTORE_STACK; - return tot_size; -} - -#if !defined(DISABLE_FLOAT_API) -static void opus_copy_channel_in_float( - opus_val16 *dst, - int dst_stride, - const void *src, - int src_stride, - int src_channel, - int frame_size, - void *user_data -) -{ - const float *float_src; - opus_int32 i; - (void)user_data; - float_src = (const float *)src; - for (i=0;ilayout.nb_channels, IMAX(500*st->layout.nb_channels, value)); - } - st->bitrate_bps = value; - } - break; - case OPUS_GET_BITRATE_REQUEST: - { - int s; - opus_int32 *value = va_arg(ap, opus_int32*); - if (!value) - { - goto bad_arg; - } - *value = 0; - for (s=0;slayout.nb_streams;s++) - { - opus_int32 rate; - OpusEncoder *enc; - enc = (OpusEncoder*)ptr; - if (s < st->layout.nb_coupled_streams) - ptr += align(coupled_size); - else - ptr += align(mono_size); - opus_encoder_ctl(enc, request, &rate); - *value += rate; - } - } - break; - case OPUS_GET_LSB_DEPTH_REQUEST: - case OPUS_GET_VBR_REQUEST: - case OPUS_GET_APPLICATION_REQUEST: - case OPUS_GET_BANDWIDTH_REQUEST: - case OPUS_GET_COMPLEXITY_REQUEST: - case OPUS_GET_PACKET_LOSS_PERC_REQUEST: - case OPUS_GET_DTX_REQUEST: - case OPUS_GET_VOICE_RATIO_REQUEST: - case OPUS_GET_VBR_CONSTRAINT_REQUEST: - case OPUS_GET_SIGNAL_REQUEST: - case OPUS_GET_LOOKAHEAD_REQUEST: - case OPUS_GET_SAMPLE_RATE_REQUEST: - case OPUS_GET_INBAND_FEC_REQUEST: - case OPUS_GET_FORCE_CHANNELS_REQUEST: - case OPUS_GET_PREDICTION_DISABLED_REQUEST: - case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST: - { - OpusEncoder *enc; - /* For int32* GET params, just query the first stream */ - opus_int32 *value = va_arg(ap, opus_int32*); - enc = (OpusEncoder*)ptr; - ret = opus_encoder_ctl(enc, request, value); - } - break; - case OPUS_GET_FINAL_RANGE_REQUEST: - { - int s; - opus_uint32 *value = va_arg(ap, opus_uint32*); - opus_uint32 tmp; - if (!value) - { - goto bad_arg; - } - *value=0; - for (s=0;slayout.nb_streams;s++) - { - OpusEncoder *enc; - enc = (OpusEncoder*)ptr; - if (s < st->layout.nb_coupled_streams) - ptr += align(coupled_size); - else - ptr += align(mono_size); - ret = opus_encoder_ctl(enc, request, &tmp); - if (ret != OPUS_OK) break; - *value ^= tmp; - } - } - break; - case OPUS_SET_LSB_DEPTH_REQUEST: - case OPUS_SET_COMPLEXITY_REQUEST: - case OPUS_SET_VBR_REQUEST: - case OPUS_SET_VBR_CONSTRAINT_REQUEST: - case OPUS_SET_MAX_BANDWIDTH_REQUEST: - case OPUS_SET_BANDWIDTH_REQUEST: - case OPUS_SET_SIGNAL_REQUEST: - case OPUS_SET_APPLICATION_REQUEST: - case OPUS_SET_INBAND_FEC_REQUEST: - case OPUS_SET_PACKET_LOSS_PERC_REQUEST: - case OPUS_SET_DTX_REQUEST: - case OPUS_SET_FORCE_MODE_REQUEST: - case OPUS_SET_FORCE_CHANNELS_REQUEST: - case OPUS_SET_PREDICTION_DISABLED_REQUEST: - case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST: - { - int s; - /* This works for int32 params */ - opus_int32 value = va_arg(ap, opus_int32); - for (s=0;slayout.nb_streams;s++) - { - OpusEncoder *enc; - - enc = (OpusEncoder*)ptr; - if (s < st->layout.nb_coupled_streams) - ptr += align(coupled_size); - else - ptr += align(mono_size); - ret = opus_encoder_ctl(enc, request, value); - if (ret != OPUS_OK) - break; - } - } - break; - case OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST: - { - int s; - opus_int32 stream_id; - OpusEncoder **value; - stream_id = va_arg(ap, opus_int32); - if (stream_id<0 || stream_id >= st->layout.nb_streams) - goto bad_arg; - value = va_arg(ap, OpusEncoder**); - if (!value) - { - goto bad_arg; - } - for (s=0;slayout.nb_coupled_streams) - ptr += align(coupled_size); - else - ptr += align(mono_size); - } - *value = (OpusEncoder*)ptr; - } - break; - case OPUS_SET_EXPERT_FRAME_DURATION_REQUEST: - { - opus_int32 value = va_arg(ap, opus_int32); - st->variable_duration = value; - } - break; - case OPUS_GET_EXPERT_FRAME_DURATION_REQUEST: - { - opus_int32 *value = va_arg(ap, opus_int32*); - if (!value) - { - goto bad_arg; - } - *value = st->variable_duration; - } - break; - case OPUS_RESET_STATE: - { - int s; - if (st->mapping_type == MAPPING_TYPE_SURROUND) - { - OPUS_CLEAR(ms_get_preemph_mem(st), st->layout.nb_channels); - OPUS_CLEAR(ms_get_window_mem(st), st->layout.nb_channels*120); - } - for (s=0;slayout.nb_streams;s++) - { - OpusEncoder *enc; - enc = (OpusEncoder*)ptr; - if (s < st->layout.nb_coupled_streams) - ptr += align(coupled_size); - else - ptr += align(mono_size); - ret = opus_encoder_ctl(enc, OPUS_RESET_STATE); - if (ret != OPUS_OK) - break; - } - } - break; - default: - ret = OPUS_UNIMPLEMENTED; - break; - } - return ret; -bad_arg: - return OPUS_BAD_ARG; -} - -int opus_multistream_encoder_ctl(OpusMSEncoder *st, int request, ...) -{ - int ret; - va_list ap; - va_start(ap, request); - ret = opus_multistream_encoder_ctl_va_list(st, request, ap); - va_end(ap); - return ret; -} - -void opus_multistream_encoder_destroy(OpusMSEncoder *st) -{ - opus_free(st); -} +/* Copyright (c) 2011 Xiph.Org Foundation + Written by Jean-Marc Valin */ +/* + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "opus_multistream.h" +#include "opus.h" +#include "opus_private.h" +#include "../celt/stack_alloc.h" +#include +#include "../celt/float_cast.h" +#include "../celt/os_support.h" +#include "../celt/mathops.h" +#include "../celt/mdct.h" +#include "../celt/../celt/modes.h" +#include "../celt/bands.h" +#include "../celt/quant_bands.h" +#include "../celt/pitch.h" + +typedef struct { + int nb_streams; + int nb_coupled_streams; + unsigned char mapping[8]; +} VorbisLayout; + +/* Index is nb_channel-1*/ +static const VorbisLayout vorbis_mappings[8] = { + {1, 0, {0}}, /* 1: mono */ + {1, 1, {0, 1}}, /* 2: stereo */ + {2, 1, {0, 2, 1}}, /* 3: 1-d surround */ + {2, 2, {0, 1, 2, 3}}, /* 4: quadraphonic surround */ + {3, 2, {0, 4, 1, 2, 3}}, /* 5: 5-channel surround */ + {4, 2, {0, 4, 1, 2, 3, 5}}, /* 6: 5.1 surround */ + {4, 3, {0, 4, 1, 2, 3, 5, 6}}, /* 7: 6.1 surround */ + {5, 3, {0, 6, 1, 2, 3, 4, 5, 7}}, /* 8: 7.1 surround */ +}; + +static opus_val32 *ms_get_preemph_mem(OpusMSEncoder *st) +{ + int s; + char *ptr; + int coupled_size, mono_size; + + coupled_size = opus_encoder_get_size(2); + mono_size = opus_encoder_get_size(1); + ptr = (char*)st + align(sizeof(OpusMSEncoder)); + for (s=0;slayout.nb_streams;s++) + { + if (s < st->layout.nb_coupled_streams) + ptr += align(coupled_size); + else + ptr += align(mono_size); + } + /* void* cast avoids clang -Wcast-align warning */ + return (opus_val32*)(void*)(ptr+st->layout.nb_channels*120*sizeof(opus_val32)); +} + +static opus_val32 *ms_get_window_mem(OpusMSEncoder *st) +{ + int s; + char *ptr; + int coupled_size, mono_size; + + coupled_size = opus_encoder_get_size(2); + mono_size = opus_encoder_get_size(1); + ptr = (char*)st + align(sizeof(OpusMSEncoder)); + for (s=0;slayout.nb_streams;s++) + { + if (s < st->layout.nb_coupled_streams) + ptr += align(coupled_size); + else + ptr += align(mono_size); + } + /* void* cast avoids clang -Wcast-align warning */ + return (opus_val32*)(void*)ptr; +} + +static int validate_ambisonics(int nb_channels, int *nb_streams, int *nb_coupled_streams) +{ + int order_plus_one; + int acn_channels; + int nondiegetic_channels; + + if (nb_channels < 1 || nb_channels > 227) + return 0; + + order_plus_one = isqrt32(nb_channels); + acn_channels = order_plus_one * order_plus_one; + nondiegetic_channels = nb_channels - acn_channels; + + if (nondiegetic_channels != 0 && nondiegetic_channels != 2) + return 0; + + if (nb_streams) + *nb_streams = acn_channels + (nondiegetic_channels != 0); + if (nb_coupled_streams) + *nb_coupled_streams = nondiegetic_channels != 0; + return 1; +} + +static int validate_encoder_layout(const ChannelLayout *layout) +{ + int s; + for (s=0;snb_streams;s++) + { + if (s < layout->nb_coupled_streams) + { + if (get_left_channel(layout, s, -1)==-1) + return 0; + if (get_right_channel(layout, s, -1)==-1) + return 0; + } else { + if (get_mono_channel(layout, s, -1)==-1) + return 0; + } + } + return 1; +} + +static void channel_pos(int channels, int pos[8]) +{ + /* Position in the mix: 0 don't mix, 1: left, 2: center, 3:right */ + if (channels==4) + { + pos[0]=1; + pos[1]=3; + pos[2]=1; + pos[3]=3; + } else if (channels==3||channels==5||channels==6) + { + pos[0]=1; + pos[1]=2; + pos[2]=3; + pos[3]=1; + pos[4]=3; + pos[5]=0; + } else if (channels==7) + { + pos[0]=1; + pos[1]=2; + pos[2]=3; + pos[3]=1; + pos[4]=3; + pos[5]=2; + pos[6]=0; + } else if (channels==8) + { + pos[0]=1; + pos[1]=2; + pos[2]=3; + pos[3]=1; + pos[4]=3; + pos[5]=1; + pos[6]=3; + pos[7]=0; + } +} + +#if 1 +/* Computes a rough approximation of log2(2^a + 2^b) */ +static opus_val16 logSum(opus_val16 a, opus_val16 b) +{ + opus_val16 max; + opus_val32 diff; + opus_val16 frac; + static const opus_val16 diff_table[17] = { + QCONST16(0.5000000f, DB_SHIFT), QCONST16(0.2924813f, DB_SHIFT), QCONST16(0.1609640f, DB_SHIFT), QCONST16(0.0849625f, DB_SHIFT), + QCONST16(0.0437314f, DB_SHIFT), QCONST16(0.0221971f, DB_SHIFT), QCONST16(0.0111839f, DB_SHIFT), QCONST16(0.0056136f, DB_SHIFT), + QCONST16(0.0028123f, DB_SHIFT) + }; + int low; + if (a>b) + { + max = a; + diff = SUB32(EXTEND32(a),EXTEND32(b)); + } else { + max = b; + diff = SUB32(EXTEND32(b),EXTEND32(a)); + } + if (!(diff < QCONST16(8.f, DB_SHIFT))) /* inverted to catch NaNs */ + return max; +#ifdef FIXED_POINT + low = SHR32(diff, DB_SHIFT-1); + frac = SHL16(diff - SHL16(low, DB_SHIFT-1), 16-DB_SHIFT); +#else + low = (int)floor(2*diff); + frac = 2*diff - low; +#endif + return max + diff_table[low] + MULT16_16_Q15(frac, SUB16(diff_table[low+1], diff_table[low])); +} +#else +opus_val16 logSum(opus_val16 a, opus_val16 b) +{ + return log2(pow(4, a)+ pow(4, b))/2; +} +#endif + +void surround_analysis(const CELTMode *celt_mode, const void *pcm, opus_val16 *bandLogE, opus_val32 *mem, opus_val32 *preemph_mem, + int len, int overlap, int channels, int rate, opus_copy_channel_in_func copy_channel_in, int arch +) +{ + int c; + int i; + int LM; + int pos[8] = {0}; + int upsample; + int frame_size; + int freq_size; + opus_val16 channel_offset; + opus_val32 bandE[21]; + opus_val16 maskLogE[3][21]; + VARDECL(opus_val32, in); + VARDECL(opus_val16, x); + VARDECL(opus_val32, freq); + SAVE_STACK; + + upsample = resampling_factor(rate); + frame_size = len*upsample; + freq_size = IMIN(960, frame_size); + + /* LM = log2(frame_size / 120) */ + for (LM=0;LMmaxLM;LM++) + if (celt_mode->shortMdctSize<preemph, preemph_mem+c, 0); +#ifndef FIXED_POINT + { + opus_val32 sum; + sum = celt_inner_prod(in, in, frame_size+overlap, 0); + /* This should filter out both NaNs and ridiculous signals that could + cause NaNs further down. */ + if (!(sum < 1e18f) || celt_isnan(sum)) + { + OPUS_CLEAR(in, frame_size+overlap); + preemph_mem[c] = 0; + } + } +#endif + OPUS_CLEAR(bandE, 21); + for (frame=0;framemdct, in+960*frame, freq, celt_mode->window, + overlap, celt_mode->maxLM-LM, 1, arch); + if (upsample != 1) + { + int bound = freq_size/upsample; + for (i=0;i=0;i--) + bandLogE[21*c+i] = MAX16(bandLogE[21*c+i], bandLogE[21*c+i+1]-QCONST16(2.f, DB_SHIFT)); + if (pos[c]==1) + { + for (i=0;i<21;i++) + maskLogE[0][i] = logSum(maskLogE[0][i], bandLogE[21*c+i]); + } else if (pos[c]==3) + { + for (i=0;i<21;i++) + maskLogE[2][i] = logSum(maskLogE[2][i], bandLogE[21*c+i]); + } else if (pos[c]==2) + { + for (i=0;i<21;i++) + { + maskLogE[0][i] = logSum(maskLogE[0][i], bandLogE[21*c+i]-QCONST16(.5f, DB_SHIFT)); + maskLogE[2][i] = logSum(maskLogE[2][i], bandLogE[21*c+i]-QCONST16(.5f, DB_SHIFT)); + } + } +#if 0 + for (i=0;i<21;i++) + printf("%f ", bandLogE[21*c+i]); + float sum=0; + for (i=0;i<21;i++) + sum += bandLogE[21*c+i]; + printf("%f ", sum/21); +#endif + OPUS_COPY(mem+c*overlap, in+frame_size, overlap); + } + for (i=0;i<21;i++) + maskLogE[1][i] = MIN32(maskLogE[0][i],maskLogE[2][i]); + channel_offset = HALF16(celt_log2(QCONST32(2.f,14)/(channels-1))); + for (c=0;c<3;c++) + for (i=0;i<21;i++) + maskLogE[c][i] += channel_offset; +#if 0 + for (c=0;c<3;c++) + { + for (i=0;i<21;i++) + printf("%f ", maskLogE[c][i]); + } +#endif + for (c=0;cnb_streams||nb_coupled_streams<0)return 0; + coupled_size = opus_encoder_get_size(2); + mono_size = opus_encoder_get_size(1); + return align(sizeof(OpusMSEncoder)) + + nb_coupled_streams * align(coupled_size) + + (nb_streams-nb_coupled_streams) * align(mono_size); +} + +opus_int32 opus_multistream_surround_encoder_get_size(int channels, int mapping_family) +{ + int nb_streams; + int nb_coupled_streams; + opus_int32 size; + + if (mapping_family==0) + { + if (channels==1) + { + nb_streams=1; + nb_coupled_streams=0; + } else if (channels==2) + { + nb_streams=1; + nb_coupled_streams=1; + } else + return 0; + } else if (mapping_family==1 && channels<=8 && channels>=1) + { + nb_streams=vorbis_mappings[channels-1].nb_streams; + nb_coupled_streams=vorbis_mappings[channels-1].nb_coupled_streams; + } else if (mapping_family==255) + { + nb_streams=channels; + nb_coupled_streams=0; + } else if (mapping_family==2) + { + if (!validate_ambisonics(channels, &nb_streams, &nb_coupled_streams)) + return 0; + } else + return 0; + size = opus_multistream_encoder_get_size(nb_streams, nb_coupled_streams); + if (channels>2) + { + size += channels*(120*sizeof(opus_val32) + sizeof(opus_val32)); + } + return size; +} + +static int opus_multistream_encoder_init_impl( + OpusMSEncoder *st, + opus_int32 Fs, + int channels, + int streams, + int coupled_streams, + const unsigned char *mapping, + int application, + MappingType mapping_type +) +{ + int coupled_size; + int mono_size; + int i, ret; + char *ptr; + + if ((channels>255) || (channels<1) || (coupled_streams>streams) || + (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams)) + return OPUS_BAD_ARG; + + st->arch = opus_select_arch(); + st->layout.nb_channels = channels; + st->layout.nb_streams = streams; + st->layout.nb_coupled_streams = coupled_streams; + if (mapping_type != MAPPING_TYPE_SURROUND) + st->lfe_stream = -1; + st->bitrate_bps = OPUS_AUTO; + st->application = application; + st->variable_duration = OPUS_FRAMESIZE_ARG; + for (i=0;ilayout.nb_channels;i++) + st->layout.mapping[i] = mapping[i]; + if (!validate_layout(&st->layout)) + return OPUS_BAD_ARG; + if (mapping_type == MAPPING_TYPE_SURROUND && + !validate_encoder_layout(&st->layout)) + return OPUS_BAD_ARG; + if (mapping_type == MAPPING_TYPE_AMBISONICS && + !validate_ambisonics(st->layout.nb_channels, NULL, NULL)) + return OPUS_BAD_ARG; + ptr = (char*)st + align(sizeof(OpusMSEncoder)); + coupled_size = opus_encoder_get_size(2); + mono_size = opus_encoder_get_size(1); + + for (i=0;ilayout.nb_coupled_streams;i++) + { + ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 2, application); + if(ret!=OPUS_OK)return ret; + if (i==st->lfe_stream) + opus_encoder_ctl((OpusEncoder*)ptr, OPUS_SET_LFE(1)); + ptr += align(coupled_size); + } + for (;ilayout.nb_streams;i++) + { + ret = opus_encoder_init((OpusEncoder*)ptr, Fs, 1, application); + if (i==st->lfe_stream) + opus_encoder_ctl((OpusEncoder*)ptr, OPUS_SET_LFE(1)); + if(ret!=OPUS_OK)return ret; + ptr += align(mono_size); + } + if (mapping_type == MAPPING_TYPE_SURROUND) + { + OPUS_CLEAR(ms_get_preemph_mem(st), channels); + OPUS_CLEAR(ms_get_window_mem(st), channels*120); + } + st->mapping_type = mapping_type; + return OPUS_OK; +} + +int opus_multistream_encoder_init( + OpusMSEncoder *st, + opus_int32 Fs, + int channels, + int streams, + int coupled_streams, + const unsigned char *mapping, + int application +) +{ + return opus_multistream_encoder_init_impl(st, Fs, channels, streams, + coupled_streams, mapping, + application, MAPPING_TYPE_NONE); +} + +int opus_multistream_surround_encoder_init( + OpusMSEncoder *st, + opus_int32 Fs, + int channels, + int mapping_family, + int *streams, + int *coupled_streams, + unsigned char *mapping, + int application +) +{ + MappingType mapping_type; + + if ((channels>255) || (channels<1)) + return OPUS_BAD_ARG; + st->lfe_stream = -1; + if (mapping_family==0) + { + if (channels==1) + { + *streams=1; + *coupled_streams=0; + mapping[0]=0; + } else if (channels==2) + { + *streams=1; + *coupled_streams=1; + mapping[0]=0; + mapping[1]=1; + } else + return OPUS_UNIMPLEMENTED; + } else if (mapping_family==1 && channels<=8 && channels>=1) + { + int i; + *streams=vorbis_mappings[channels-1].nb_streams; + *coupled_streams=vorbis_mappings[channels-1].nb_coupled_streams; + for (i=0;i=6) + st->lfe_stream = *streams-1; + } else if (mapping_family==255) + { + int i; + *streams=channels; + *coupled_streams=0; + for(i=0;i2 && mapping_family==1) { + mapping_type = MAPPING_TYPE_SURROUND; + } else if (mapping_family==2) + { + mapping_type = MAPPING_TYPE_AMBISONICS; + } else + { + mapping_type = MAPPING_TYPE_NONE; + } + return opus_multistream_encoder_init_impl(st, Fs, channels, *streams, + *coupled_streams, mapping, + application, mapping_type); +} + +OpusMSEncoder *opus_multistream_encoder_create( + opus_int32 Fs, + int channels, + int streams, + int coupled_streams, + const unsigned char *mapping, + int application, + int *error +) +{ + int ret; + OpusMSEncoder *st; + if ((channels>255) || (channels<1) || (coupled_streams>streams) || + (streams<1) || (coupled_streams<0) || (streams>255-coupled_streams)) + { + if (error) + *error = OPUS_BAD_ARG; + return NULL; + } + st = (OpusMSEncoder *)opus_alloc(opus_multistream_encoder_get_size(streams, coupled_streams)); + if (st==NULL) + { + if (error) + *error = OPUS_ALLOC_FAIL; + return NULL; + } + ret = opus_multistream_encoder_init(st, Fs, channels, streams, coupled_streams, mapping, application); + if (ret != OPUS_OK) + { + opus_free(st); + st = NULL; + } + if (error) + *error = ret; + return st; +} + +OpusMSEncoder *opus_multistream_surround_encoder_create( + opus_int32 Fs, + int channels, + int mapping_family, + int *streams, + int *coupled_streams, + unsigned char *mapping, + int application, + int *error +) +{ + int ret; + opus_int32 size; + OpusMSEncoder *st; + if ((channels>255) || (channels<1)) + { + if (error) + *error = OPUS_BAD_ARG; + return NULL; + } + size = opus_multistream_surround_encoder_get_size(channels, mapping_family); + if (!size) + { + if (error) + *error = OPUS_UNIMPLEMENTED; + return NULL; + } + st = (OpusMSEncoder *)opus_alloc(size); + if (st==NULL) + { + if (error) + *error = OPUS_ALLOC_FAIL; + return NULL; + } + ret = opus_multistream_surround_encoder_init(st, Fs, channels, mapping_family, streams, coupled_streams, mapping, application); + if (ret != OPUS_OK) + { + opus_free(st); + st = NULL; + } + if (error) + *error = ret; + return st; +} + +static void surround_rate_allocation( + OpusMSEncoder *st, + opus_int32 *rate, + int frame_size, + opus_int32 Fs + ) +{ + int i; + opus_int32 channel_rate; + int stream_offset; + int lfe_offset; + int coupled_ratio; /* Q8 */ + int lfe_ratio; /* Q8 */ + int nb_lfe; + int nb_uncoupled; + int nb_coupled; + int nb_normal; + opus_int32 channel_offset; + opus_int32 bitrate; + int total; + + nb_lfe = (st->lfe_stream!=-1); + nb_coupled = st->layout.nb_coupled_streams; + nb_uncoupled = st->layout.nb_streams-nb_coupled-nb_lfe; + nb_normal = 2*nb_coupled + nb_uncoupled; + + /* Give each non-LFE channel enough bits per channel for coding band energy. */ + channel_offset = 40*IMAX(50, Fs/frame_size); + + if (st->bitrate_bps==OPUS_AUTO) + { + bitrate = nb_normal*(channel_offset + Fs + 10000) + 8000*nb_lfe; + } else if (st->bitrate_bps==OPUS_BITRATE_MAX) + { + bitrate = nb_normal*300000 + nb_lfe*128000; + } else { + bitrate = st->bitrate_bps; + } + + /* Give LFE some basic stream_channel allocation but never exceed 1/20 of the + total rate for the non-energy part to avoid problems at really low rate. */ + lfe_offset = IMIN(bitrate/20, 3000) + 15*IMAX(50, Fs/frame_size); + + /* We give each stream (coupled or uncoupled) a starting bitrate. + This models the main saving of coupled channels over uncoupled. */ + stream_offset = (bitrate - channel_offset*nb_normal - lfe_offset*nb_lfe)/nb_normal/2; + stream_offset = IMAX(0, IMIN(20000, stream_offset)); + + /* Coupled streams get twice the mono rate after the offset is allocated. */ + coupled_ratio = 512; + /* Should depend on the bitrate, for now we assume LFE gets 1/8 the bits of mono */ + lfe_ratio = 32; + + total = (nb_uncoupled<<8) /* mono */ + + coupled_ratio*nb_coupled /* stereo */ + + nb_lfe*lfe_ratio; + channel_rate = 256*(opus_int64)(bitrate - lfe_offset*nb_lfe - stream_offset*(nb_coupled+nb_uncoupled) - channel_offset*nb_normal)/total; + + for (i=0;ilayout.nb_streams;i++) + { + if (ilayout.nb_coupled_streams) + rate[i] = 2*channel_offset + IMAX(0, stream_offset+(channel_rate*coupled_ratio>>8)); + else if (i!=st->lfe_stream) + rate[i] = channel_offset + IMAX(0, stream_offset + channel_rate); + else + rate[i] = IMAX(0, lfe_offset+(channel_rate*lfe_ratio>>8)); + } +} + +static void ambisonics_rate_allocation( + OpusMSEncoder *st, + opus_int32 *rate, + int frame_size, + opus_int32 Fs + ) +{ + int i; + opus_int32 total_rate; + opus_int32 per_stream_rate; + + const int nb_channels = st->layout.nb_streams + st->layout.nb_coupled_streams; + + if (st->bitrate_bps==OPUS_AUTO) + { + total_rate = (st->layout.nb_coupled_streams + st->layout.nb_streams) * + (Fs+60*Fs/frame_size) + st->layout.nb_streams * (opus_int32)15000; + } else if (st->bitrate_bps==OPUS_BITRATE_MAX) + { + total_rate = nb_channels * 320000; + } else + { + total_rate = st->bitrate_bps; + } + + /* Allocate equal number of bits to Ambisonic (uncoupled) and non-diegetic + * (coupled) streams */ + per_stream_rate = total_rate / st->layout.nb_streams; + for (i = 0; i < st->layout.nb_streams; i++) + { + rate[i] = per_stream_rate; + } +} + +static opus_int32 rate_allocation( + OpusMSEncoder *st, + opus_int32 *rate, + int frame_size + ) +{ + int i; + opus_int32 rate_sum=0; + opus_int32 Fs; + char *ptr; + + ptr = (char*)st + align(sizeof(OpusMSEncoder)); + opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs)); + + if (st->mapping_type == MAPPING_TYPE_AMBISONICS) { + ambisonics_rate_allocation(st, rate, frame_size, Fs); + } else + { + surround_rate_allocation(st, rate, frame_size, Fs); + } + + for (i=0;ilayout.nb_streams;i++) + { + rate[i] = IMAX(rate[i], 500); + rate_sum += rate[i]; + } + return rate_sum; +} + +/* Max size in case the encoder decides to return six frames (6 x 20 ms = 120 ms) */ +#define MS_FRAME_TMP (6*1275+12) +int opus_multistream_encode_native +( + OpusMSEncoder *st, + opus_copy_channel_in_func copy_channel_in, + const void *pcm, + int analysis_frame_size, + unsigned char *data, + opus_int32 max_data_bytes, + int lsb_depth, + downmix_func downmix, + int float_api, + void *user_data +) +{ + opus_int32 Fs; + int coupled_size; + int mono_size; + int s; + char *ptr; + int tot_size; + VARDECL(opus_val16, buf); + VARDECL(opus_val16, bandSMR); + unsigned char tmp_data[MS_FRAME_TMP]; + OpusRepacketizer rp; + opus_int32 vbr; + const CELTMode *celt_mode; + opus_int32 bitrates[256]; + opus_val16 bandLogE[42]; + opus_val32 *mem = NULL; + opus_val32 *preemph_mem=NULL; + int frame_size; + opus_int32 rate_sum; + opus_int32 smallest_packet; + ALLOC_STACK; + + if (st->mapping_type == MAPPING_TYPE_SURROUND) + { + preemph_mem = ms_get_preemph_mem(st); + mem = ms_get_window_mem(st); + } + + ptr = (char*)st + align(sizeof(OpusMSEncoder)); + opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_SAMPLE_RATE(&Fs)); + opus_encoder_ctl((OpusEncoder*)ptr, OPUS_GET_VBR(&vbr)); + opus_encoder_ctl((OpusEncoder*)ptr, CELT_GET_MODE(&celt_mode)); + + frame_size = frame_size_select(analysis_frame_size, st->variable_duration, Fs); + if (frame_size <= 0) + { + RESTORE_STACK; + return OPUS_BAD_ARG; + } + + /* Smallest packet the encoder can produce. */ + smallest_packet = st->layout.nb_streams*2-1; + /* 100 ms needs an extra byte per stream for the ToC. */ + if (Fs/frame_size == 10) + smallest_packet += st->layout.nb_streams; + if (max_data_bytes < smallest_packet) + { + RESTORE_STACK; + return OPUS_BUFFER_TOO_SMALL; + } + ALLOC(buf, 2*frame_size, opus_val16); + coupled_size = opus_encoder_get_size(2); + mono_size = opus_encoder_get_size(1); + + ALLOC(bandSMR, 21*st->layout.nb_channels, opus_val16); + if (st->mapping_type == MAPPING_TYPE_SURROUND) + { + surround_analysis(celt_mode, pcm, bandSMR, mem, preemph_mem, frame_size, 120, st->layout.nb_channels, Fs, copy_channel_in, st->arch); + } + + /* Compute bitrate allocation between streams (this could be a lot better) */ + rate_sum = rate_allocation(st, bitrates, frame_size); + + if (!vbr) + { + if (st->bitrate_bps == OPUS_AUTO) + { + max_data_bytes = IMIN(max_data_bytes, 3*rate_sum/(3*8*Fs/frame_size)); + } else if (st->bitrate_bps != OPUS_BITRATE_MAX) + { + max_data_bytes = IMIN(max_data_bytes, IMAX(smallest_packet, + 3*st->bitrate_bps/(3*8*Fs/frame_size))); + } + } + ptr = (char*)st + align(sizeof(OpusMSEncoder)); + for (s=0;slayout.nb_streams;s++) + { + OpusEncoder *enc; + enc = (OpusEncoder*)ptr; + if (s < st->layout.nb_coupled_streams) + ptr += align(coupled_size); + else + ptr += align(mono_size); + opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrates[s])); + if (st->mapping_type == MAPPING_TYPE_SURROUND) + { + opus_int32 equiv_rate; + equiv_rate = st->bitrate_bps; + if (frame_size*50 < Fs) + equiv_rate -= 60*(Fs/frame_size - 50)*st->layout.nb_channels; + if (equiv_rate > 10000*st->layout.nb_channels) + opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_FULLBAND)); + else if (equiv_rate > 7000*st->layout.nb_channels) + opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_SUPERWIDEBAND)); + else if (equiv_rate > 5000*st->layout.nb_channels) + opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_WIDEBAND)); + else + opus_encoder_ctl(enc, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_NARROWBAND)); + if (s < st->layout.nb_coupled_streams) + { + /* To preserve the spatial image, force stereo CELT on coupled streams */ + opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY)); + opus_encoder_ctl(enc, OPUS_SET_FORCE_CHANNELS(2)); + } + } + else if (st->mapping_type == MAPPING_TYPE_AMBISONICS) { + opus_encoder_ctl(enc, OPUS_SET_FORCE_MODE(MODE_CELT_ONLY)); + } + } + + ptr = (char*)st + align(sizeof(OpusMSEncoder)); + /* Counting ToC */ + tot_size = 0; + for (s=0;slayout.nb_streams;s++) + { + OpusEncoder *enc; + int len; + int curr_max; + int c1, c2; + int ret; + + opus_repacketizer_init(&rp); + enc = (OpusEncoder*)ptr; + if (s < st->layout.nb_coupled_streams) + { + int i; + int left, right; + left = get_left_channel(&st->layout, s, -1); + right = get_right_channel(&st->layout, s, -1); + (*copy_channel_in)(buf, 2, + pcm, st->layout.nb_channels, left, frame_size, user_data); + (*copy_channel_in)(buf+1, 2, + pcm, st->layout.nb_channels, right, frame_size, user_data); + ptr += align(coupled_size); + if (st->mapping_type == MAPPING_TYPE_SURROUND) + { + for (i=0;i<21;i++) + { + bandLogE[i] = bandSMR[21*left+i]; + bandLogE[21+i] = bandSMR[21*right+i]; + } + } + c1 = left; + c2 = right; + } else { + int i; + int chan = get_mono_channel(&st->layout, s, -1); + (*copy_channel_in)(buf, 1, + pcm, st->layout.nb_channels, chan, frame_size, user_data); + ptr += align(mono_size); + if (st->mapping_type == MAPPING_TYPE_SURROUND) + { + for (i=0;i<21;i++) + bandLogE[i] = bandSMR[21*chan+i]; + } + c1 = chan; + c2 = -1; + } + if (st->mapping_type == MAPPING_TYPE_SURROUND) + opus_encoder_ctl(enc, OPUS_SET_ENERGY_MASK(bandLogE)); + /* number of bytes left (+Toc) */ + curr_max = max_data_bytes - tot_size; + /* Reserve one byte for the last stream and two for the others */ + curr_max -= IMAX(0,2*(st->layout.nb_streams-s-1)-1); + /* For 100 ms, reserve an extra byte per stream for the ToC */ + if (Fs/frame_size == 10) + curr_max -= st->layout.nb_streams-s-1; + curr_max = IMIN(curr_max,MS_FRAME_TMP); + /* Repacketizer will add one or two bytes for self-delimited frames */ + if (s != st->layout.nb_streams-1) curr_max -= curr_max>253 ? 2 : 1; + if (!vbr && s == st->layout.nb_streams-1) + opus_encoder_ctl(enc, OPUS_SET_BITRATE(curr_max*(8*Fs/frame_size))); + len = opus_encode_native(enc, buf, frame_size, tmp_data, curr_max, lsb_depth, + pcm, analysis_frame_size, c1, c2, st->layout.nb_channels, downmix, float_api); + if (len<0) + { + RESTORE_STACK; + return len; + } + /* We need to use the repacketizer to add the self-delimiting lengths + while taking into account the fact that the encoder can now return + more than one frame at a time (e.g. 60 ms CELT-only) */ + ret = opus_repacketizer_cat(&rp, tmp_data, len); + /* If the opus_repacketizer_cat() fails, then something's seriously wrong + with the encoder. */ + if (ret != OPUS_OK) + { + RESTORE_STACK; + return OPUS_INTERNAL_ERROR; + } + len = opus_repacketizer_out_range_impl(&rp, 0, opus_repacketizer_get_nb_frames(&rp), + data, max_data_bytes-tot_size, s != st->layout.nb_streams-1, !vbr && s == st->layout.nb_streams-1); + data += len; + tot_size += len; + } + /*printf("\n");*/ + RESTORE_STACK; + return tot_size; +} + +#if !defined(DISABLE_FLOAT_API) +static void opus_copy_channel_in_float( + opus_val16 *dst, + int dst_stride, + const void *src, + int src_stride, + int src_channel, + int frame_size, + void *user_data +) +{ + const float *float_src; + opus_int32 i; + (void)user_data; + float_src = (const float *)src; + for (i=0;ilayout.nb_channels, IMAX(500*st->layout.nb_channels, value)); + } + st->bitrate_bps = value; + } + break; + case OPUS_GET_BITRATE_REQUEST: + { + int s; + opus_int32 *value = va_arg(ap, opus_int32*); + if (!value) + { + goto bad_arg; + } + *value = 0; + for (s=0;slayout.nb_streams;s++) + { + opus_int32 rate; + OpusEncoder *enc; + enc = (OpusEncoder*)ptr; + if (s < st->layout.nb_coupled_streams) + ptr += align(coupled_size); + else + ptr += align(mono_size); + opus_encoder_ctl(enc, request, &rate); + *value += rate; + } + } + break; + case OPUS_GET_LSB_DEPTH_REQUEST: + case OPUS_GET_VBR_REQUEST: + case OPUS_GET_APPLICATION_REQUEST: + case OPUS_GET_BANDWIDTH_REQUEST: + case OPUS_GET_COMPLEXITY_REQUEST: + case OPUS_GET_PACKET_LOSS_PERC_REQUEST: + case OPUS_GET_DTX_REQUEST: + case OPUS_GET_VOICE_RATIO_REQUEST: + case OPUS_GET_VBR_CONSTRAINT_REQUEST: + case OPUS_GET_SIGNAL_REQUEST: + case OPUS_GET_LOOKAHEAD_REQUEST: + case OPUS_GET_SAMPLE_RATE_REQUEST: + case OPUS_GET_INBAND_FEC_REQUEST: + case OPUS_GET_FORCE_CHANNELS_REQUEST: + case OPUS_GET_PREDICTION_DISABLED_REQUEST: + case OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST: + { + OpusEncoder *enc; + /* For int32* GET params, just query the first stream */ + opus_int32 *value = va_arg(ap, opus_int32*); + enc = (OpusEncoder*)ptr; + ret = opus_encoder_ctl(enc, request, value); + } + break; + case OPUS_GET_FINAL_RANGE_REQUEST: + { + int s; + opus_uint32 *value = va_arg(ap, opus_uint32*); + opus_uint32 tmp; + if (!value) + { + goto bad_arg; + } + *value=0; + for (s=0;slayout.nb_streams;s++) + { + OpusEncoder *enc; + enc = (OpusEncoder*)ptr; + if (s < st->layout.nb_coupled_streams) + ptr += align(coupled_size); + else + ptr += align(mono_size); + ret = opus_encoder_ctl(enc, request, &tmp); + if (ret != OPUS_OK) break; + *value ^= tmp; + } + } + break; + case OPUS_SET_LSB_DEPTH_REQUEST: + case OPUS_SET_COMPLEXITY_REQUEST: + case OPUS_SET_VBR_REQUEST: + case OPUS_SET_VBR_CONSTRAINT_REQUEST: + case OPUS_SET_MAX_BANDWIDTH_REQUEST: + case OPUS_SET_BANDWIDTH_REQUEST: + case OPUS_SET_SIGNAL_REQUEST: + case OPUS_SET_APPLICATION_REQUEST: + case OPUS_SET_INBAND_FEC_REQUEST: + case OPUS_SET_PACKET_LOSS_PERC_REQUEST: + case OPUS_SET_DTX_REQUEST: + case OPUS_SET_FORCE_MODE_REQUEST: + case OPUS_SET_FORCE_CHANNELS_REQUEST: + case OPUS_SET_PREDICTION_DISABLED_REQUEST: + case OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST: + { + int s; + /* This works for int32 params */ + opus_int32 value = va_arg(ap, opus_int32); + for (s=0;slayout.nb_streams;s++) + { + OpusEncoder *enc; + + enc = (OpusEncoder*)ptr; + if (s < st->layout.nb_coupled_streams) + ptr += align(coupled_size); + else + ptr += align(mono_size); + ret = opus_encoder_ctl(enc, request, value); + if (ret != OPUS_OK) + break; + } + } + break; + case OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST: + { + int s; + opus_int32 stream_id; + OpusEncoder **value; + stream_id = va_arg(ap, opus_int32); + if (stream_id<0 || stream_id >= st->layout.nb_streams) + goto bad_arg; + value = va_arg(ap, OpusEncoder**); + if (!value) + { + goto bad_arg; + } + for (s=0;slayout.nb_coupled_streams) + ptr += align(coupled_size); + else + ptr += align(mono_size); + } + *value = (OpusEncoder*)ptr; + } + break; + case OPUS_SET_EXPERT_FRAME_DURATION_REQUEST: + { + opus_int32 value = va_arg(ap, opus_int32); + st->variable_duration = value; + } + break; + case OPUS_GET_EXPERT_FRAME_DURATION_REQUEST: + { + opus_int32 *value = va_arg(ap, opus_int32*); + if (!value) + { + goto bad_arg; + } + *value = st->variable_duration; + } + break; + case OPUS_RESET_STATE: + { + int s; + if (st->mapping_type == MAPPING_TYPE_SURROUND) + { + OPUS_CLEAR(ms_get_preemph_mem(st), st->layout.nb_channels); + OPUS_CLEAR(ms_get_window_mem(st), st->layout.nb_channels*120); + } + for (s=0;slayout.nb_streams;s++) + { + OpusEncoder *enc; + enc = (OpusEncoder*)ptr; + if (s < st->layout.nb_coupled_streams) + ptr += align(coupled_size); + else + ptr += align(mono_size); + ret = opus_encoder_ctl(enc, OPUS_RESET_STATE); + if (ret != OPUS_OK) + break; + } + } + break; + default: + ret = OPUS_UNIMPLEMENTED; + break; + } + return ret; +bad_arg: + return OPUS_BAD_ARG; +} + +int opus_multistream_encoder_ctl(OpusMSEncoder *st, int request, ...) +{ + int ret; + va_list ap; + va_start(ap, request); + ret = opus_multistream_encoder_ctl_va_list(st, request, ap); + va_end(ap); + return ret; +} + +void opus_multistream_encoder_destroy(OpusMSEncoder *st) +{ + opus_free(st); +} diff --git a/src/libs/decoders/opus.c b/src/libs/decoders/opus.c deleted file mode 100644 index 91cd5e3bf00..00000000000 --- a/src/libs/decoders/opus.c +++ /dev/null @@ -1,670 +0,0 @@ -/* - * This DOSBox Ogg Opus decoder backend is written and copyright 2019 Kevin R Croft (krcroft@gmail.com) - * - * This decoders makes use of: - * - libopusfile, for .opus file handing and frame decoding - * - speexdsp, for resampling to the original input rate, if needed - * - * Source links - * - libogg: https://github.com/xiph/ogg - * - libopus: https://github.com/xiph/opus - * - opusfile: https://github.com/xiph/opusfile - * - speexdsp: https://github.com/xiph/speexdsp - * - opus-tools: https://github.com/xiph/opus-tools - - * Documentation references - * - Ogg Opus: https://www.opus-codec.org/docs - * - OpusFile: https://mf4.xiph.org/jenkins/view/opus/job/opusfile-unix/ws/doc/html/index.html - * - Resampler: https://www.speex.org/docs/manual/speex-manual/node7.html - * - * Please see the file LICENSE.txt in the source's root directory. - * - * This DOSBox Ogg Opus decoder backend 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 DOSBox Ogg Opus decoder backend 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 - * along with DOSBox. If not, see . - * - */ - -#if HAVE_CONFIG_H -# include -#endif -#include // getenv() - -#include "SDL_sound.h" -#define __SDL_SOUND_INTERNAL__ -#include "SDL_sound_internal.h" - -#include "opusfile.h" -#include "speex/speex_resampler.h" - -// The minimum buffer samples per channel: 120 ms @ 48 samples/ms, defined by opus -#define OPUS_MIN_BUFFER_SAMPLES_PER_CHANNEL 5760 - -// Opus's internal sample rates, to which all encoded streams get resampled -#define OPUS_SAMPLE_RATE 48000 -#define OPUS_SAMPLE_RATE_PER_MS 48 - -static Sint32 opus_init (void); -static void opus_quit (void); -static Sint32 opus_open (Sound_Sample* sample, const char* ext); -static void opus_close (Sound_Sample* sample); -static Uint32 opus_read (Sound_Sample* sample); -static Sint32 opus_rewind (Sound_Sample* sample); -static Sint32 opus_seek (Sound_Sample* sample, const Uint32 ms); - -static const char* extensions_opus[] = { "OPUS", NULL }; - -const Sound_DecoderFunctions __Sound_DecoderFunctions_OPUS = -{ - { - extensions_opus, - "Ogg Opus audio using libopusfile", - "Kevin R Croft ", - "The DOSBox-X project" - }, - - opus_init, /* init() method */ - opus_quit, /* quit() method */ - opus_open, /* open() method */ - opus_close, /* close() method */ - opus_read, /* read() method */ - opus_rewind, /* rewind() method */ - opus_seek /* seek() method */ -}; - - -// Our private-decoder structure where we hold the opusfile, resampler, -// circular buffer, and buffer tracking variables. -typedef struct -{ - Uint64 of_pcm; // absolute position in consumed Opus samples - OggOpusFile* of; // the actual opusfile we open/read/seek within - opus_int16* buffer; // pointer to the start of our circular buffer - SpeexResamplerState* resampler; // pointer to an instantiated resampler - float rate_ratio; // OPUS_RATE (48KHz) divided by desired sample rate - Uint16 buffer_size; // maximum number of samples we can hold in our buffer - Uint16 decoded; // number of samples decoded in our buffer - Uint16 consumed; // number of samples consumed in our buffer - Uint16 frame_size; // number of samples decoded in one opus frame - SDL_bool eof; // indicates if we've hit end-of-file decoding -} opus_t; - - -static Sint32 opus_init(void) -{ - SNDDBG(("Opus init: done\n")); - return 1; /* always succeeds. */ -} /* opus_init */ - - -static void opus_quit(void){ - SNDDBG(("Opus quit: done\n")); -} // no-op - - -/* - * Read-Write Ops Read Callback Wrapper - * ==================================== - * - * OPUS: typedef int(*op_read_func) - * void* _stream --> The stream to read from - * unsigned char* _ptr --> The buffer to store the data in - * int _nbytes --> The maximum number of bytes to read. - * Returns: The number of bytes successfully read, or a negative value on error. - * - * SDL: size_t SDL_RWread - * struct SDL_RWops* context --> a pointer to an SDL_RWops structure - * void* ptr --> a pointer to a buffer to read data into - * size_t size --> the size of each object to read, in bytes - * size_t maxnum --> the maximum number of objects to be read - */ -static Sint32 RWops_opus_read(void* stream, unsigned char* ptr, Sint32 nbytes) -{ - const Sint32 bytes_read = SDL_RWread((SDL_RWops*)stream, - (void*)ptr, - sizeof(unsigned char), - (size_t)nbytes); - SNDDBG(("Opus ops read: " - "{wanted: %d, returned: %ld}\n", nbytes, bytes_read)); - - return bytes_read; -} /* RWops_opus_read */ - - -/* - * Read-Write Ops Seek Callback Wrapper - * ==================================== - * - * OPUS: typedef int(* op_seek_func) - * void* _stream, --> The stream to seek in - * opus_int64 _offset, --> Sets the position indicator for _stream in bytes - * int _whence --> If whence is set to SEEK_SET, SEEK_CUR, or SEEK_END, - * the offset is relative to the start of the stream, - * the current position indicator, or end-of-file, - * respectively - * Returns: 0 Success, or -1 if seeking is not supported or an error occurred. - * define SEEK_SET 0 - * define SEEK_CUR 1 - * define SEEK_END 2 - * - * SDL: Sint64 SDL_RWseek - * SDL_RWops* context --> a pointer to an SDL_RWops structure - * Sint64 offset, --> offset, in bytes - * Sint32 whence --> an offset in bytes, relative to whence location; can be negative - * Returns the final offset in the data stream after the seek or -1 on error. - * RW_SEEK_SET 0 - * RW_SEEK_CUR 1 - * RW_SEEK_END 2 - */ -static Sint32 RWops_opus_seek(void* stream, const opus_int64 offset, const Sint32 whence) -{ - const Sint64 offset_after_seek = SDL_RWseek((SDL_RWops*)stream, offset, whence); - - SNDDBG(("Opus ops seek: " - "{requested offset: %ld, seeked offset: %ld}\n", - offset, offset_after_seek)); - - return (offset_after_seek != -1 ? 0 : -1); -} /* RWops_opus_seek */ - - -/* - * Read-Write Ops Close Callback Wrapper - * ===================================== - * OPUS: typedef int(* op_close_func)(void *_stream) - * SDL: Sint32 SDL_RWclose(struct SDL_RWops* context) - */ -static Sint32 RWops_opus_close(void* stream) -{ - (void)stream;//UNUSED - /* SDL closes this for us */ - // return SDL_RWclose((SDL_RWops*)stream); - return 0; -} /* RWops_opus_close */ - - -/* - * Read-Write Ops Tell Callback Wrapper - * ==================================== - * OPUS: typedef opus_int64(* op_tell_func)(void *_stream) - * SDL: Sint64 SDL_RWtell(struct SDL_RWops* context) - */ -static opus_int64 RWops_opus_tell(void* stream) -{ - const Sint64 current_offset = SDL_RWtell((SDL_RWops*)stream); - - SNDDBG(("Opus ops tell: " - "%ld\n", current_offset)); - - return current_offset; -} /* RWops_opus_tell */ - - -// Populate the opus callback object (in prescribed order), with our callback functions. -static const OpusFileCallbacks RWops_opus_callbacks = -{ - RWops_opus_read, - RWops_opus_seek, - RWops_opus_tell, - RWops_opus_close -}; - -/* Return a human readable version of an OpusFile error code... */ -#if (defined DEBUG_CHATTER) -static const char* opus_error(const Sint8 errnum) -{ - switch(errnum) - { - case OP_FALSE: // -1 - return("A request did not succeed"); - case OP_EOF: // -2 - return("End of file"); - case OP_HOLE: // -3 - return("There was a hole in the page sequence numbers " - "(e.g., a page was corrupt or missing)"); - case OP_EREAD: // -128 - return("An underlying read, seek, or tell operation " - "failed when it should have succeeded"); - case OP_EFAULT: // -129 - return("A NULL pointer was passed where one was unexpected, or an " - "internal memory allocation failed, or an internal library " - "error was encountered"); - case OP_EIMPL: // -130 - return("The stream used a feature that is not implemented," - " such as an unsupported channel family"); - case OP_EINVAL: // -131 - return("One or more parameters to a function were invalid"); - case OP_ENOTFORMAT: // -132 - return("A purported Ogg Opus stream did not begin with an Ogg page, a " - "purported header packet did not start with one of the required " - "strings, `OpusHead` or `OpusTags`, or a link in a chained file " - "was encoun tered that did not contain any logical Opus streams"); - case OP_EBADHEADER: // -133 - return("A required header packet was not properly formatted, contained illegal " - "values, or was missing altogether"); - case OP_EVERSION: // -134 - return("The ID header contained an unrecognized version number"); - case OP_ENOTAUDIO: // -135 - return("Not valid audio"); - case OP_EBADPACKET: // -136 - return("An audio packet failed to decode properly"); - case OP_EBADLINK: // -137 - return("We failed to find data we had seen before, or the bitstream structure was " - "sufficiently malformed that seeking to the target destination was impossible"); - case OP_ENOSEEK: // -138 - return("An operation that requires seeking was requested on an unseekable stream"); - case OP_EBADTIMESTAMP: // -139 - return("The first or last granule position of a link failed basic validity checks"); - } /* switch */ - return "unknown error"; -} /* opus_error */ -#endif - -static __inline__ void output_opus_info(const OggOpusFile* of, const OpusHead* oh) -{ -#if (defined DEBUG_CHATTER) - const OpusTags* ot = op_tags(of, -1); - - // Guard - if ( of == NULL - || oh == NULL - || ot == NULL) return; - - // Dump info - SNDDBG(("Opus serial number: %u\n", op_serialno(of, -1))); - SNDDBG(("Opus format version: %d\n", oh->version)); - SNDDBG(("Opus channel count: %d\n", oh->channel_count )); - SNDDBG(("Opus seekable: %s\n", op_seekable(of) ? "True" : "False")); - SNDDBG(("Opus pre-skip samples: %u\n", oh->pre_skip)); - SNDDBG(("Opus input sample rate: %u\n", oh->input_sample_rate)); - SNDDBG(("Opus logical streams: %d\n", oh->stream_count)); - SNDDBG(("Opus vendor: %s\n", ot->vendor)); - for (int i = 0; i < ot->comments; i++) - SNDDBG(("Opus: user comment: '%s'\n", ot->user_comments[i])); -#else - (void)of;//UNUSED - (void)oh;//UNUSED -#endif -} /* output_opus_comments */ - -/* - * Opus Open - * ========= - * - Creates a new opus file object by using our callback structure for all IO operations. - * - We also initialize and allocate memory for fields in the opus_t decode structure. - * - SDL expects a returns of 1 on success - */ -static Sint32 opus_open(Sound_Sample* sample, const char* ext) -{ - (void)ext;//UNUSED - Sint32 rcode; - Sound_SampleInternal* internal = (Sound_SampleInternal*)sample->opaque; - - // Open the Opus File and print some info - OggOpusFile* of = op_open_callbacks(internal->rw, &RWops_opus_callbacks, NULL, 0, &rcode); - if (rcode != 0) { - op_free(of); - of = NULL; - SNDDBG(("Opus open error: " - "'Could not open opus file: %s'\n", opus_error(rcode))); - BAIL_MACRO("Opus open fatal: 'Not a valid Ogg Opus file'", 0); - } - const OpusHead* oh = op_head(of, -1); - output_opus_info(of, oh); - - // Initialize our decoder struct elements - opus_t* decoder = (opus_t*)SDL_malloc(sizeof(opus_t)); - decoder->of = of; - decoder->of_pcm = 0; - decoder->decoded = 0; - decoder->consumed = 0; - decoder->frame_size = 0; - decoder->eof = SDL_FALSE; - decoder->buffer = NULL; - - // Connect our long-lived internal decoder to the one we're building here - internal->decoder_private = decoder; - - if ( sample->desired.rate != 0 - && sample->desired.rate != OPUS_SAMPLE_RATE - && getenv("SDL_DONT_RESAMPLE") == NULL){ - - // Opus resamples all inputs to 48kHz. By default (if env-var SDL_DONT_RESAMPLE doesn't exist) - // we resample to the desired rate so the receiving SDL_sound application doesn't have to. - // This avoids breaking applications that don't expect 48kHz audio and also gives us - // quality-control by using the speex resampler, which has a noise floor of -140 dB, which - // is ~40dB lower than the -96dB offered by 16-bit CD-quality audio. - // - sample->actual.rate = sample->desired.rate; - decoder->rate_ratio = OPUS_SAMPLE_RATE / (float)(sample->desired.rate); - decoder->resampler = speex_resampler_init(oh->channel_count, - OPUS_SAMPLE_RATE, - sample->desired.rate, - // SPEEX_RESAMPLER_QUALITY_VOIP, // consumes ~20 Mhz - SPEEX_RESAMPLER_QUALITY_DEFAULT, // consumes ~40 Mhz - // SPEEX_RESAMPLER_QUALITY_DESKTOP, // consumes ~80 Mhz - &rcode); - - // If we failed to initialize the resampler, then tear down - if (rcode < 0) { - opus_close(sample); - BAIL_MACRO("Opus: failed initializing the resampler", 0); - } - - // Otherwise use native sampling - } else { - sample->actual.rate = OPUS_SAMPLE_RATE; - decoder->rate_ratio = 1.0; - decoder->resampler = NULL; - } - - // Allocate our buffer to hold PCM samples from the Opus decoder - decoder->buffer_size = oh->channel_count * OPUS_MIN_BUFFER_SAMPLES_PER_CHANNEL * 1.5; - decoder->buffer = (opus_int16 *)SDL_malloc(decoder->buffer_size * sizeof(opus_int16)); - - // Gather static properties about our stream (channels, seek-ability, format, and duration) - sample->actual.channels = (Uint8)(oh->channel_count); - sample->flags = (Sound_SampleFlags)(op_seekable(of) ? SOUND_SAMPLEFLAG_CANSEEK: 0); - sample->actual.format = AUDIO_S16LSB; // returns least-significant-byte order regardless of architecture - - ogg_int64_t total_time = op_pcm_total(of, -1); // total PCM samples in the stream - internal->total_time = total_time == OP_EINVAL ? -1 : // total milliseconds in the stream - (Sint32)( (double)total_time / OPUS_SAMPLE_RATE_PER_MS); - - return 1; -} /* opus_open */ - - -/* - * Opus Close - * ========== - * Free and NULL all allocated memory pointers. - */ -static void opus_close(Sound_Sample* sample) -{ - /* From the Opus docs: if opening a stream/file/or using op_test_callbacks() fails - * then we are still responsible for freeing the OggOpusFile with op_free(). - */ - Sound_SampleInternal* internal = (Sound_SampleInternal*) sample->opaque; - - opus_t* d = (opus_t*)internal->decoder_private; - if (d != NULL) { - - if (d->of != NULL) { - op_free(d->of); - d->of = NULL; - } - - if(d->resampler != NULL) { - speex_resampler_destroy(d->resampler); - d->resampler = NULL; - } - - if(d->buffer != NULL) { - SDL_free(d->buffer); - d->buffer = NULL; - } - - SDL_free(d); - d = NULL; - } - return; - -} /* opus_close */ - - -/* - * Opus Read - * ========= - * Decode, resample (if needed), and write the output to the - * requested buffer. - */ -static Uint32 opus_read(Sound_Sample* sample) -{ - Sound_SampleInternal* internal = (Sound_SampleInternal*) sample->opaque; - opus_t* d = (opus_t*)internal->decoder_private; - - opus_int16* output_buffer = (opus_int16*)internal->buffer; - const Uint16 requested_output_size = internal->buffer_size / sizeof(opus_int16); - const Uint16 derived_consumption_size = (requested_output_size * d->rate_ratio) + 0.5; - - // Three scenarios in order of probability: - // - // 1. consume: resample (if needed) a chunk from our decoded queue - // sufficient to fill the requested buffer. - // - // If the decoder has hit the end-of-file, drain any - // remaining decoded data before setting the EOF flag. - // - // 2. decode: decode chunks until our buffer is full or we hit EOF. - // - // 3. wrap: we've decoded and consumed to edge of our buffer - // so wrap any remaining decoded samples back around. - - Sint32 rcode = 1; - SDL_bool have_consumed = SDL_FALSE; - while (! have_consumed){ - - // consume ... - const Uint16 unconsumed_size = d->decoded - d->consumed; - if (unconsumed_size >= derived_consumption_size || d->eof) { - - // If we're at the start of the stream, ignore 'pre-skip' samples - // per-channel. Pre-skip describes how much data must be decoded - // before valid output is obtained. - // - const OpusHead* oh = op_head(d->of, -1); - if (d->of_pcm == 0) - d->consumed += oh->pre_skip * oh->channel_count; - - // We use these to record the actual consumed and output sizes - Uint32 actual_consumed_size = unconsumed_size; - Uint32 actual_output_size = requested_output_size; - - // If we need to resample - if (d->resampler) - (void) speex_resampler_process_int(d->resampler, 0, - d->buffer + d->consumed, - &actual_consumed_size, - output_buffer, - &actual_output_size); - - // Otherwise copy the bytes - else { - if (unconsumed_size < requested_output_size) - actual_output_size = unconsumed_size; - actual_consumed_size = actual_output_size; - SDL_memcpy(output_buffer, d->buffer + d->consumed, actual_output_size * sizeof(opus_int16)); - } - - // bump our consumption count and absolute pcm position - d->consumed += actual_consumed_size; - d->of_pcm += actual_consumed_size; - - SNDDBG(("Opus read consuming: " - "{output: %u, so_far: %u, remaining_buffer: %u}\n", - actual_output_size, d->consumed, d->decoded - d->consumed)); - - // if we wrote less than requested then we're at the end-of-file - if (actual_output_size < requested_output_size) { - sample->flags |= SOUND_SAMPLEFLAG_EOF; - SNDDBG(("Opus read consuming: " - "{end_of_buffer: True, requested: %u, resampled_output: %u}\n", - requested_output_size, actual_output_size)); - } - - rcode = actual_output_size * sizeof(opus_int16); // covert from samples to bytes - have_consumed = SDL_TRUE; - } - - else { - // wrap ... - if (d->frame_size > 0) { - SDL_memcpy(d->buffer, - d->buffer + d->consumed, - (d->decoded - d->consumed)*sizeof(opus_int16)); - - d->decoded -= d->consumed; - d->consumed = 0; - - SNDDBG(("Opus read wrapping: " - "{wrapped: %u}\n", d->decoded)); - } - - // decode ... - while (rcode > 0 && d->buffer_size - d->decoded >= d->frame_size) { - - rcode = sample->actual.channels * op_read(d->of, - d->buffer + d->decoded, - d->buffer_size - d->decoded, NULL); - // Use the largest decoded frame to know when - // our buffer is too small to hold a frame, to - // avoid constraining the decoder to fill sizes - // smaller than the stream's frame-size - if (rcode > d->frame_size){ - - SNDDBG(("Opus read decoding: " - "{frame_previous: %u, frame_new: %u}\n", - d->frame_size, rcode)); - - d->frame_size = rcode; - } - - // assess the validity of the return code - if (rcode > 0) d->decoded += rcode; // reading - else if (rcode == 0) d->eof = SDL_TRUE; // done - else if (rcode == OP_HOLE) rcode = 1; // hole in the data, carry on - else // (rcode < 0) // error - sample->flags |= SOUND_SAMPLEFLAG_ERROR; - - SNDDBG(("Opus read decoding: " - "{decoded: %u, remaining buffer: %u, end_of_file: %s}\n", - rcode, d->buffer_size - d->decoded, d->eof ? "True" : "False")); - } - } - } // end while. - return rcode; -} /* opus_read */ - - -/* - * Opus Rewind - * =========== - * Sets the current position of the stream to 0. - */ -static Sint32 opus_rewind(Sound_Sample* sample) -{ - const Sint32 rcode = opus_seek(sample, 0); - BAIL_IF_MACRO(rcode < 0, ERR_IO_ERROR, 0); - return rcode; -} /* opus_rewind */ - - -/* - * Opus Seek - * ========= - * Set the current position of the stream to the indicated - * integer offset in milliseconds. - */ -static Sint32 opus_seek(Sound_Sample* sample, const Uint32 ms) -{ - Sound_SampleInternal* internal = (Sound_SampleInternal*) sample->opaque; - opus_t* d = (opus_t *)internal->decoder_private; - int rcode = -1; - - #if (defined DEBUG_CHATTER) - const float total_seconds = (float)ms/1000; - uint8_t minutes = total_seconds / 60; - const float seconds = ((int)total_seconds % 60) + (total_seconds - (int)total_seconds); - const uint8_t hours = minutes / 60; - minutes = minutes % 60; - #endif - - // convert the desired ms offset into OPUS PCM samples - const ogg_int64_t desired_pcm = ms * OPUS_SAMPLE_RATE_PER_MS; - - // Is our stream already positioned at the requested offset? - if (d->of_pcm == (ogg_uint64_t)desired_pcm){ - - SNDDBG(("Opus seek avoided: " - "{requested_time: '%02d:%02d:%.2f', becomes_opus_pcm: %ld, actual_pcm_pos: %ld}\n", - hours, minutes, seconds, desired_pcm, d->of_pcm)); - - rcode = 1; - } - - // If not, check if we can jump within our circular buffer (and not actually seek!) - // In this scenario, we don't have to waste our currently decoded samples - // or incur the cost of 80ms of pre-roll decoding behind the scene in libopus. - else { - Uint64 pcm_start = d->of_pcm - d->consumed; - Uint64 pcm_end = pcm_start + d->decoded; - - // In both scenarios below we're going to seek, in which case - // our sample flags should be reset and let the read function - // re-assess the flag. - // - - // Is the requested pcm offset within our decoded range? - if ((ogg_uint64_t)desired_pcm >= pcm_start && (ogg_uint64_t)desired_pcm <= pcm_end) { - - SNDDBG(("Opus seek avoided: " - "{requested_time: '%02d:%02d:%.2f', becomes_opus_pcm: %ld, buffer_start: %ld, buffer_end: %ld}\n", - hours, minutes, seconds, desired_pcm, pcm_start, pcm_end)); - - // Yes, so simply adjust our existing pcm offset and consumption position - // No seeks or pre-roll needed! - d->consumed = desired_pcm - pcm_start; - d->of_pcm = desired_pcm; - - // reset our sample flags and let our consumption state re-apply - // the flags per its own rules - if (op_seekable(d->of)) - sample->flags = SOUND_SAMPLEFLAG_CANSEEK; - - // note, we don't reset d->eof because our decode state is unchanged - rcode = 1; - // rcode is 1, confirming we successfully seeked - } - - // No; the requested pcm offset is outside our circular decode buffer, - // so actually seek and reset our decode and consumption counters. - else { - rcode = op_pcm_seek(d->of, desired_pcm) + 1; - - // op_pcm_seek(..) returns 0, to which we add 1, on success - // ... or a negative value on error. - if (rcode > 0) { - d->of_pcm = desired_pcm; - d->consumed = 0; - d->decoded = 0; - d->eof = SDL_FALSE; - SNDDBG(("Opus seek in file: " - "{requested_time: '%02d:%02d:%.2f', becomes_opus_pcm: %ld}\n", - hours, minutes, seconds, desired_pcm)); - - // reset our sample flags and let the read function re-apply - // sample flags as it hits them from our offset - if (op_seekable(d->of)) - sample->flags = SOUND_SAMPLEFLAG_CANSEEK; - - } - // otherwise we failed to seek.. so leave everything as-is. - } - } - - BAIL_IF_MACRO(rcode < 0, ERR_IO_ERROR, 0); - return rcode; -} /* opus_seek */ - -/* end of ogg_opus.c ... */ - diff --git a/src/libs/decoders/stb.h b/src/libs/decoders/stb.h index 681045bcde9..94b2bac3a34 100644 --- a/src/libs/decoders/stb.h +++ b/src/libs/decoders/stb.h @@ -5487,7 +5487,8 @@ int stb_fullpath(char *abs, int abs_size, char *rel) return STB_TRUE; } else { int n; - getcwd(abs, abs_size); + strcpy(abs, "."); + // getcwd(abs, abs_size); n = strlen(abs); if (n+(int) strlen(rel)+2 <= abs_size) { abs[n] = '/'; diff --git a/src/libs/gui_tk/gui_tk.h b/src/libs/gui_tk/gui_tk.h index d20a87330f4..399c232508c 100644 --- a/src/libs/gui_tk/gui_tk.h +++ b/src/libs/gui_tk/gui_tk.h @@ -76,7 +76,7 @@ * guiscreen.update(4); // 4 ticks = 40ms * SDL_UpdateRect(screen, 0, 0, screen->w, screen->h); * - * SDL_Delay(40); // wait 40ms + * _Delay(40); // wait 40ms * } * \endcode * @@ -135,6 +135,8 @@ typedef unsigned __int32 uint32_t; #include #include +extern void _Delay(uint32_t ticks); + /// This namespace contains all GUI toolkit classes, types and functions. namespace GUI { diff --git a/src/libs/libchdr/libchdr_chd.c b/src/libs/libchdr/libchdr_chd.c index c3521d35d2a..2eb88a10b37 100644 --- a/src/libs/libchdr/libchdr_chd.c +++ b/src/libs/libchdr/libchdr_chd.c @@ -55,7 +55,7 @@ #if defined(__PS3__) || defined(__PSL1GHT__) #define __MACTYPES__ #endif -#include +// #include #undef TRUE #undef FALSE @@ -205,7 +205,7 @@ struct _zlib_allocator typedef struct _zlib_codec_data zlib_codec_data; struct _zlib_codec_data { - z_stream inflater; + // z_stream inflater; zlib_allocator allocator; }; @@ -370,12 +370,12 @@ static chd_error map_read(chd_file *chd); static chd_error metadata_find_entry(chd_file *chd, uint32_t metatag, uint32_t metaindex, metadata_entry *metaentry); /* zlib compression codec */ -static chd_error zlib_codec_init(void *codec, uint32_t hunkbytes); -static void zlib_codec_free(void *codec); -static chd_error zlib_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); -static voidpf zlib_fast_alloc(voidpf opaque, uInt items, uInt size); -static void zlib_fast_free(voidpf opaque, voidpf address); -static void zlib_allocator_free(voidpf opaque); +// static chd_error zlib_codec_init(void *codec, uint32_t hunkbytes); +// static void zlib_codec_free(void *codec); +// static chd_error zlib_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen); +// // static voidpf zlib_fast_alloc(voidpf opaque, uInt items, uInt size); +// static void zlib_fast_free(voidpf opaque, voidpf address); +// static void zlib_allocator_free(voidpf opaque); /* lzma compression codec */ static chd_error lzma_codec_init(void *codec, uint32_t hunkbytes); @@ -648,6 +648,8 @@ static chd_error lzma_codec_decompress(void* codec, const uint8_t *src, uint32_t return CHDERR_NONE; } +#undef WANT_SUBCODE + /* cdlz */ static chd_error cdlz_codec_init(void* codec, uint32_t hunkbytes) { @@ -746,8 +748,8 @@ static chd_error cdzl_codec_init(void *codec, uint32_t hunkbytes) if (cdzl->buffer == NULL) return CHDERR_OUT_OF_MEMORY; - ret = zlib_codec_init(&cdzl->base_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SECTOR_DATA); - if (ret != CHDERR_NONE) + // ret = zlib_codec_init(&cdzl->base_decompressor, (hunkbytes / CD_FRAME_SIZE) * CD_MAX_SECTOR_DATA); + // if (ret != CHDERR_NONE) return ret; #ifdef WANT_SUBCODE @@ -762,7 +764,7 @@ static chd_error cdzl_codec_init(void *codec, uint32_t hunkbytes) static void cdzl_codec_free(void *codec) { cdzl_codec_data* cdzl = (cdzl_codec_data*)codec; - zlib_codec_free(&cdzl->base_decompressor); + // zlib_codec_free(&cdzl->base_decompressor); #ifdef WANT_SUBCODE zlib_codec_free(&cdzl->subcode_decompressor); #endif @@ -786,7 +788,7 @@ static chd_error cdzl_codec_decompress(void *codec, const uint8_t *src, uint32_t complen_base = (complen_base << 8) | src[ecc_bytes + 2]; /* reset and decode */ - zlib_codec_decompress(&cdzl->base_decompressor, &src[header_bytes], complen_base, &cdzl->buffer[0], frames * CD_MAX_SECTOR_DATA); + // zlib_codec_decompress(&cdzl->base_decompressor, &src[header_bytes], complen_base, &cdzl->buffer[0], frames * CD_MAX_SECTOR_DATA); #ifdef WANT_SUBCODE zlib_codec_decompress(&cdzl->subcode_decompressor, &src[header_bytes + complen_base], complen - complen_base - header_bytes, &cdzl->buffer[frames * CD_MAX_SECTOR_DATA], frames * CD_MAX_SUBCODE_DATA); #endif @@ -1196,9 +1198,9 @@ static const codec_interface codec_interfaces[] = CHDCOMPRESSION_ZLIB, "zlib", FALSE, - zlib_codec_init, - zlib_codec_free, - zlib_codec_decompress, + NULL, + NULL, + NULL, NULL }, @@ -1207,9 +1209,9 @@ static const codec_interface codec_interfaces[] = CHDCOMPRESSION_ZLIB_PLUS, "zlib+", FALSE, - zlib_codec_init, - zlib_codec_free, - zlib_codec_decompress, + NULL, + NULL, + NULL, NULL }, @@ -1218,9 +1220,9 @@ static const codec_interface codec_interfaces[] = CHD_CODEC_ZLIB, "zlib (Deflate)", FALSE, - zlib_codec_init, - zlib_codec_free, - zlib_codec_decompress, + NULL, + NULL, + NULL, NULL }, @@ -3040,6 +3042,8 @@ static chd_error metadata_find_entry(chd_file *chd, uint32_t metatag, uint32_t m static chd_error zlib_codec_init(void *codec, uint32_t hunkbytes) { + #ifdef C_LIBZ + int zerr; chd_error err; zlib_codec_data *data = (zlib_codec_data*)codec; @@ -3064,6 +3068,10 @@ static chd_error zlib_codec_init(void *codec, uint32_t hunkbytes) err = CHDERR_NONE; return err; + + #endif + + return CHDERR_COMPRESSION_ERROR; } /*------------------------------------------------- @@ -3073,6 +3081,8 @@ static chd_error zlib_codec_init(void *codec, uint32_t hunkbytes) static void zlib_codec_free(void *codec) { + #ifdef C_LIBZ + zlib_codec_data *data = (zlib_codec_data *)codec; /* deinit the streams */ @@ -3083,6 +3093,8 @@ static void zlib_codec_free(void *codec) /* free our fast memory */ zlib_allocator_free(&data->allocator); } + + #endif } /*------------------------------------------------- @@ -3092,6 +3104,9 @@ static void zlib_codec_free(void *codec) static chd_error zlib_codec_decompress(void *codec, const uint8_t *src, uint32_t complen, uint8_t *dest, uint32_t destlen) { + + #ifdef C_LIBZ + zlib_codec_data *data = (zlib_codec_data *)codec; int zerr; @@ -3112,96 +3127,114 @@ static chd_error zlib_codec_decompress(void *codec, const uint8_t *src, uint32_t return CHDERR_DECOMPRESSION_ERROR; return CHDERR_NONE; -} - -/*------------------------------------------------- - zlib_fast_alloc - fast malloc for ZLIB, which - allocates and frees memory frequently --------------------------------------------------*/ - -/* Huge alignment values for possible SIMD optimization by compiler (NEON, SSE, AVX) */ -#define ZLIB_MIN_ALIGNMENT_BITS 512 -#define ZLIB_MIN_ALIGNMENT_BYTES (ZLIB_MIN_ALIGNMENT_BITS / 8) - -static voidpf zlib_fast_alloc(voidpf opaque, uInt items, uInt size) -{ - zlib_allocator *alloc = (zlib_allocator *)opaque; - uintptr_t paddr = 0; - uint32_t *ptr; - int i; - - /* compute the size, rounding to the nearest 1k */ - size = (size * items + 0x3ff) & ~0x3ff; - - /* reuse a hunk if we can */ - for (i = 0; i < MAX_ZLIB_ALLOCS; i++) - { - ptr = alloc->allocptr[i]; - if (ptr && size == *ptr) - { - /* set the low bit of the size so we don't match next time */ - *ptr |= 1; - - /* return aligned block address */ - return (voidpf)(alloc->allocptr2[i]); - } - } - - /* alloc a new one */ - ptr = (uint32_t *)malloc(size + sizeof(uint32_t) + ZLIB_MIN_ALIGNMENT_BYTES); - if (!ptr) - return NULL; - - /* put it into the list */ - for (i = 0; i < MAX_ZLIB_ALLOCS; i++) - if (!alloc->allocptr[i]) - { - alloc->allocptr[i] = ptr; - paddr = (((uintptr_t)ptr) + sizeof(uint32_t) + (ZLIB_MIN_ALIGNMENT_BYTES-1)) & (~(ZLIB_MIN_ALIGNMENT_BYTES-1)); - alloc->allocptr2[i] = (uint32_t*)paddr; - break; - } - - /* set the low bit of the size so we don't match next time */ - *ptr = size | 1; - - /* return aligned block address */ - return (voidpf)paddr; -} - -/*------------------------------------------------- - zlib_fast_free - fast free for ZLIB, which - allocates and frees memory frequently --------------------------------------------------*/ -static void zlib_fast_free(voidpf opaque, voidpf address) -{ - zlib_allocator *alloc = (zlib_allocator *)opaque; - uint32_t *ptr = (uint32_t *)address; - int i; - - /* find the hunk */ - for (i = 0; i < MAX_ZLIB_ALLOCS; i++) - if (ptr == alloc->allocptr2[i]) - { - /* clear the low bit of the size to allow matches */ - *(alloc->allocptr[i]) &= ~1; - return; - } -} - -/*------------------------------------------------- - zlib_allocator_free --------------------------------------------------*/ -static void zlib_allocator_free(voidpf opaque) -{ - zlib_allocator *alloc = (zlib_allocator *)opaque; - int i; - - for (i = 0; i < MAX_ZLIB_ALLOCS; i++) - if (alloc->allocptr[i]) - free(alloc->allocptr[i]); -} + #endif + + return CHDERR_COMPRESSION_ERROR; +} + +// /*------------------------------------------------- +// zlib_fast_alloc - fast malloc for ZLIB, which +// allocates and frees memory frequently +// -------------------------------------------------*/ + +// /* Huge alignment values for possible SIMD optimization by compiler (NEON, SSE, AVX) */ +// #define ZLIB_MIN_ALIGNMENT_BITS 512 +// #define ZLIB_MIN_ALIGNMENT_BYTES (ZLIB_MIN_ALIGNMENT_BITS / 8) + +// static voidpf zlib_fast_alloc(voidpf opaque, uInt items, uInt size) +// { +// #ifdef C_LIBZ + +// zlib_allocator *alloc = (zlib_allocator *)opaque; +// uintptr_t paddr = 0; +// uint32_t *ptr; +// int i; + +// /* compute the size, rounding to the nearest 1k */ +// size = (size * items + 0x3ff) & ~0x3ff; + +// /* reuse a hunk if we can */ +// for (i = 0; i < MAX_ZLIB_ALLOCS; i++) +// { +// ptr = alloc->allocptr[i]; +// if (ptr && size == *ptr) +// { +// /* set the low bit of the size so we don't match next time */ +// *ptr |= 1; + +// /* return aligned block address */ +// return (voidpf)(alloc->allocptr2[i]); +// } +// } + +// /* alloc a new one */ +// ptr = (uint32_t *)malloc(size + sizeof(uint32_t) + ZLIB_MIN_ALIGNMENT_BYTES); +// if (!ptr) +// return NULL; + +// /* put it into the list */ +// for (i = 0; i < MAX_ZLIB_ALLOCS; i++) +// if (!alloc->allocptr[i]) +// { +// alloc->allocptr[i] = ptr; +// paddr = (((uintptr_t)ptr) + sizeof(uint32_t) + (ZLIB_MIN_ALIGNMENT_BYTES-1)) & (~(ZLIB_MIN_ALIGNMENT_BYTES-1)); +// alloc->allocptr2[i] = (uint32_t*)paddr; +// break; +// } + +// /* set the low bit of the size so we don't match next time */ +// *ptr = size | 1; + +// /* return aligned block address */ +// return (voidpf)paddr; + +// #endif + +// return nullptr; +// } + +// /*------------------------------------------------- +// zlib_fast_free - fast free for ZLIB, which +// allocates and frees memory frequently +// -------------------------------------------------*/ + +// static void zlib_fast_free(voidpf opaque, voidpf address) +// { +// #ifdef C_LIBZ + +// zlib_allocator *alloc = (zlib_allocator *)opaque; +// uint32_t *ptr = (uint32_t *)address; +// int i; + +// /* find the hunk */ +// for (i = 0; i < MAX_ZLIB_ALLOCS; i++) +// if (ptr == alloc->allocptr2[i]) +// { +// /* clear the low bit of the size to allow matches */ +// *(alloc->allocptr[i]) &= ~1; +// return; +// } + +// #endif +// } + +// /*------------------------------------------------- +// zlib_allocator_free +// -------------------------------------------------*/ +// static void zlib_allocator_free(voidpf opaque) +// { +// #ifdef C_LIBZ + +// zlib_allocator *alloc = (zlib_allocator *)opaque; +// int i; + +// for (i = 0; i < MAX_ZLIB_ALLOCS; i++) +// if (alloc->allocptr[i]) +// free(alloc->allocptr[i]); + +// #endif +// } /*------------------------------------------------- core_stdio_fopen - core_file wrapper over fopen diff --git a/src/libs/passthroughio/passthroughio.cpp b/src/libs/passthroughio/passthroughio.cpp index a2f7d15a44d..2958df5e443 100644 --- a/src/libs/passthroughio/passthroughio.cpp +++ b/src/libs/passthroughio/passthroughio.cpp @@ -478,33 +478,35 @@ bool initPassthroughIO(void) { } bool dropPrivileges(void) { - regainPrivileges(); // The saved UID and GID must be changed too. - - gid_t gid = getgid(); - if(setgid(gid) == -1) { - LOG_MSG("Error: Could not set GID to %u.", gid); - return false; - } - uid_t uid = getuid(); - if(setuid(uid) == -1) { - LOG_MSG("Error: Could not set UID to %u.", uid); - return false; - } - return true; + return false; + // regainPrivileges(); // The saved UID and GID must be changed too. + + // gid_t gid = getgid(); + // if(setgid(gid) == -1) { + // LOG_MSG("Error: Could not set GID to %u.", gid); + // return false; + // } + // uid_t uid = getuid(); + // if(setuid(uid) == -1) { + // LOG_MSG("Error: Could not set UID to %u.", uid); + // return false; + // } + // return true; } bool dropPrivilegesTemp(void) { - gid_t gid = getgid(); - if(setegid(gid) == -1) { - LOG_MSG("Error: Could not set effective GID to %u.", gid); - return false; - } - uid_t uid = getuid(); - if(seteuid(uid) == -1) { - LOG_MSG("Error: Could not set effective UID to %u.", uid); - return false; - } - return true; + return false; + // gid_t gid = getgid(); + // if(setegid(gid) == -1) { + // LOG_MSG("Error: Could not set effective GID to %u.", gid); + // return false; + // } + // uid_t uid = getuid(); + // if(seteuid(uid) == -1) { + // LOG_MSG("Error: Could not set effective UID to %u.", uid); + // return false; + // } + // return true; } bool regainPrivileges(void) { diff --git a/src/libs/physfs/physfs_platform_posix.c b/src/libs/physfs/physfs_platform_posix.c index a56c9bc9464..012f5e46707 100644 --- a/src/libs/physfs/physfs_platform_posix.c +++ b/src/libs/physfs/physfs_platform_posix.c @@ -151,9 +151,10 @@ PHYSFS_EnumerateCallbackResult __PHYSFS_platformEnumerate(const char *dirname, int __PHYSFS_platformMkDir(const char *path) { - const int rc = mkdir(path, S_IRWXU); - BAIL_IF(rc == -1, errcodeFromErrno(), 0); - return 1; + // const int rc = mkdir(path, S_IRWXU); + // BAIL_IF(rc == -1, errcodeFromErrno(), 0); + // return 1; + return 0; } /* __PHYSFS_platformMkDir */ diff --git a/src/misc/cross.cpp b/src/misc/cross.cpp index 64c4e255b2a..ca96a6493ae 100644 --- a/src/misc/cross.cpp +++ b/src/misc/cross.cpp @@ -108,7 +108,7 @@ static void W32_ConfDir(std::string& in,bool create) { char const* appdata = "\\Application Data"; size_t len = strlen(result); if(len + strlen(appdata) < MAX_PATH) strcat(result,appdata); - if(create) _mkdir(result); + //if(create) _mkdir(result); } in = result; } @@ -139,10 +139,10 @@ void Cross::GetPlatformResDir(std::string& in) { in = "/usr/local/share/dosbox-x"; if ((stat(in.c_str(), &info) != 0) || (!(info.st_mode & S_IFDIR))) in = "/usr/share/dosbox-x"; - if ((stat(in.c_str(), &info) != 0) || (!(info.st_mode & S_IFDIR))) { + // if ((stat(in.c_str(), &info) != 0) || (!(info.st_mode & S_IFDIR))) { //LOG_MSG("XDG_DATA_HOME (%s) does not exist. Using %s", in.c_str(), RESDIR); - in = RESDIR; - } + // in = RESDIR; + // } #elif defined(WIN32) in = "C:\\DOSBox-X"; #if defined(RESDIR) @@ -194,7 +194,7 @@ void Cross::CreatePlatformConfigDir(std::string& in) { #if defined(WIN32) && !defined(HX_DOS) W32_ConfDir(in,true); in += "\\DOSBox-X"; - _mkdir(in.c_str()); + //_mkdir(in.c_str()); #elif defined(MACOSX) in = "~/Library/Preferences"; ResolveHomedir(in); @@ -202,7 +202,7 @@ void Cross::CreatePlatformConfigDir(std::string& in) { #elif defined(HAIKU) in = "~/config/settings/dosbox-x"; ResolveHomedir(in); - mkdir(in.c_str(),0700); + //mkdir(in.c_str(),0700); #elif defined(RISCOS) in = "//DosBox-X"; mkdir(in.c_str(),0700); @@ -211,7 +211,7 @@ void Cross::CreatePlatformConfigDir(std::string& in) { const std::string conf_home = xdg_conf_home && xdg_conf_home[0] == '/' ? xdg_conf_home: "~/.config"; in = conf_home + "/dosbox-x"; ResolveHomedir(in); - mkdir(in.c_str(),0700); + //mkdir(in.c_str(),0700); #endif in += CROSS_FILESPLIT; } @@ -235,9 +235,9 @@ void Cross::ResolveHomedir(std::string & temp_line) { void Cross::CreateDir(std::string const& in) { #ifdef WIN32 - _mkdir(in.c_str()); + //_mkdir(in.c_str()); #else - mkdir(in.c_str(),0700); + //mkdir(in.c_str(),0700); #endif } diff --git a/src/misc/programs.cpp b/src/misc/programs.cpp index df6de1691c3..39503e4ae7b 100644 --- a/src/misc/programs.cpp +++ b/src/misc/programs.cpp @@ -17,2172 +17,2177 @@ */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "programs.h" -#include "callback.h" -#include "logging.h" -#include "regs.h" -#include "support.h" -#include "cross.h" -#include "control.h" -#include "shell.h" -#include "menudef.h" -#include "hardware.h" -#include "mapper.h" -#include "menu.h" -#include "bios.h" -#include "timer.h" -#include "jfont.h" -#include "render.h" -#include "../ints/int10.h" -#include "sdlmain.h" -#if defined(WIN32) -#include "windows.h" -RECT monrect; -int curscreen; -#endif - -#include -#include - -Bitu call_program; -extern char lastmount; -extern const char *modifier; -extern unsigned int sendkeymap; -extern std::string langname, configfile, dosbox_title; -extern int autofixwarn, enablelfn, fat32setver, paste_speed, wheel_key, freesizecap, wpType, wpVersion, wpBG, wpFG, lastset, blinkCursor, msgcodepage; -extern bool dos_kernel_disabled, force_nocachedir, wpcolon, convertimg, lockmount, enable_config_as_shell_commands, lesssize, load, winrun, winautorun, startcmd, startwait, startquiet, starttranspath, mountwarning, wheel_guest, clipboard_dosapi, noremark_save_state, force_load_state, sync_time, manualtime, ttfswitch, loadlang, showbold, showital, showline, showsout, char512, printfont, rtl, gbk, chinasea, uao, showdbcs, dbcs_sbcs, autoboxdraw, halfwidthkana, ticksLocked, outcon, enable_dbcs_tables, show_recorded_filename, internal_program, pipetmpdev, notrysgf, uselangcp, incall; - -/* This registers a file on the virtual drive and creates the correct structure for it*/ - -static uint8_t exe_block[]={ - 0xbc,0x00,0x04, //0x100 MOV SP,0x400 decrease stack size - 0xbb,0x40,0x00, //0x103 MOV BX,0x0040 for memory resize - 0xb4,0x4a, //0x106 MOV AH,0x4A Resize memory block - 0xcd,0x21, //0x108 INT 0x21 ... - 0x30,0xc0, //0x10A XOR AL,AL Clear AL (exit code). Program will write AL to modify exit status -//pos 14 is callback number - 0xFE,0x38,0x00,0x00, //0x10C CALLBack number - 0xb4,0x4c, //0x110 Mov AH,0x4C Prepare to exit, preserve AL - 0xcd,0x21 //0x112 INT 0x21 Exit to DOS -}; //0x114 --DONE-- - -#define CB_POS 14 - -class InternalProgramEntry { -public: - InternalProgramEntry() { - main = NULL; - comsize = 0; - comdata = NULL; - } - ~InternalProgramEntry() { - if (comdata != NULL) free(comdata); - comdata = NULL; - comsize = 0; - main = NULL; - } -public: - std::string name; - uint8_t* comdata; - uint32_t comsize; - PROGRAMS_Main* main; -}; - -static std::vector internal_progs; -uint8_t DOS_GetAnsiAttr(void); -int setTTFMap(bool changecp); -char *FormatDate(uint16_t year, uint8_t month, uint8_t day); -bool isDBCSCP(void), CheckBoxDrawing(uint8_t c1, uint8_t c2, uint8_t c3, uint8_t c4), DOS_SetAnsiAttr(uint8_t attr), GFX_GetPreventFullscreen(void), toOutput(const char *what); -void EMS_DoShutDown(void), UpdateDefaultPrinterFont(void), GFX_ForceRedrawScreen(void), resetFontSize(void), ttf_reset_colors(void), makestdcp950table(void), makeseacp951table(void), clearFontCache(void), DOSBox_SetSysMenu(void), MSG_Init(void), initRand(void), PRINTER_Init(void), SetKEYBCP(void); -void EMS_Startup(Section* sec), DOSV_SetConfig(Section_prop *section), DOSBOX_UnlockSpeed2(bool pressed), RebootLanguage(std::string filename, bool confirm=false), SetWindowTransparency(int trans), SetOutputSwitch(const char *outputstr), runRescan(const char *str), runSerial(const char *str), runParallel(const char *str), DOS_AddDays(uint8_t days), PRINTER_Shutdown(Section* sec), setAspectRatio(Section_prop * section); - -void PROGRAMS_Shutdown(void) { - LOG(LOG_MISC,LOG_DEBUG)("Shutting down internal programs list"); - - for (size_t i=0;i < internal_progs.size();i++) { - if (internal_progs[i] != NULL) { - delete internal_progs[i]; - internal_progs[i] = NULL; - } - } - internal_progs.clear(); -} - -void PROGRAMS_MakeFile(char const * const name,PROGRAMS_Main * main,const char *dir) { - uint32_t size=sizeof(exe_block)+sizeof(uint8_t); - InternalProgramEntry *ipe; - uint8_t *comdata; - uint8_t index; - - /* Copy save the pointer in the vector and save its index */ - if (internal_progs.size()>255) E_Exit("PROGRAMS_MakeFile program size too large (%d)",static_cast(internal_progs.size())); - - index = (uint8_t)internal_progs.size(); - comdata = (uint8_t *)malloc(32); //MEM LEAK - memcpy(comdata,&exe_block,sizeof(exe_block)); - memcpy(&comdata[sizeof(exe_block)],&index,sizeof(index)); - comdata[CB_POS]=(uint8_t)(call_program&0xff); - comdata[CB_POS+1]=(uint8_t)((call_program>>8)&0xff); - - ipe = new InternalProgramEntry(); - ipe->main = main; - ipe->name = name; - ipe->comsize = size; - ipe->comdata = comdata; - internal_progs.push_back(ipe); - internal_program = true; - VFILE_Register(name,ipe->comdata,ipe->comsize,dir); - internal_program = false; -} - -static Bitu PROGRAMS_Handler(void) { - /* This sets up everything for a program start up call */ - Bitu size=sizeof(uint8_t); - uint8_t index; - /* Read the index from program code in memory */ - PhysPt reader=PhysMake(dos.psp(),256+sizeof(exe_block)); - HostPt writer=(HostPt)&index; - for (;size>0;size--) *writer++=mem_readb(reader++); - Program * new_program = NULL; - if (index >= internal_progs.size()) E_Exit("something is messing with the memory"); - InternalProgramEntry *ipe = internal_progs[index]; - if (ipe == NULL) E_Exit("Attempt to run internal program slot with nothing allocated"); - if (ipe->main == NULL) return CBRET_NONE; - PROGRAMS_Main * handler = internal_progs[index]->main; - (*handler)(&new_program); - - try { /* "BOOT" can throw an exception (int(2)) */ - new_program->Run(); - delete new_program; - } - catch (...) { /* well if it happened, free the program anyway to avert memory leaks */ - delete new_program; - throw; /* pass it on */ - } - - return CBRET_NONE; -} - -/* Main functions used in all program */ - -Program::Program() { - /* Find the command line and setup the PSP */ - psp = new DOS_PSP(dos.psp()); - /* Scan environment for filename */ - PhysPt envscan=PhysMake(psp->GetEnvironment(),0); - while (mem_readb(envscan)) envscan+=(PhysPt)(mem_strlen(envscan)+1); - envscan+=3; - CommandTail tail; - MEM_BlockRead(PhysMake(dos.psp(),CTBUF+1),&tail,CTBUF+1); - if (tail.countSecureMode() ||*/ cmd->Get_arglength() > 100 && full_arguments.size()) { - CommandLine* temp = new CommandLine(cmd->GetFileName(),full_arguments.c_str()); - delete cmd; - cmd = temp; - } - full_arguments.assign(""); //Clear so it gets even more save -} - -bool resetcolor = false; -static char last_written_character = 0;//For 0xA to OxD 0xA expansion -void Program::WriteOut(const char * format,...) { - uint8_t attr = DOS_GetAnsiAttr(); - char buf[2048]; - va_list msg; - - va_start(msg,format); - vsnprintf(buf,2047,format,msg); - va_end(msg); - - uint16_t size = (uint16_t)strlen(buf); - dos.internal_output=true; - for(uint16_t i = 0; i < size;i++) { - uint8_t out;uint16_t s=1; - if (buf[i] == 0xA && last_written_character != 0xD) { - out = 0xD;DOS_WriteFile(STDOUT,&out,&s); - } - last_written_character = (char)(out = (uint8_t)buf[i]); - DOS_WriteFile(STDOUT,&out,&s); - } - dos.internal_output=false; - if (resetcolor && attr) DOS_SetAnsiAttr(attr); - resetcolor = false; - -// DOS_WriteFile(STDOUT,(uint8_t *)buf,&size); -} - -void Program::WriteOut(const char *format, const char *arguments) { - char buf[2048 + CMD_MAXLINE]; - sprintf(buf,format,arguments); - - uint16_t size = (uint16_t)strlen(buf); - dos.internal_output=true; - for(uint16_t i = 0; i < size;i++) { - uint8_t out;uint16_t s=1; - if (buf[i] == 0xA && last_written_character != 0xD) { - out = 0xD;DOS_WriteFile(STDOUT,&out,&s); - } - last_written_character = (char)(out = (uint8_t)buf[i]); - DOS_WriteFile(STDOUT,&out,&s); - } - dos.internal_output=false; - -// DOS_WriteFile(STDOUT,(uint8_t *)buf,&size); -} - -int Program::WriteOut_NoParsing(const char * format, bool dbcs) { - uint16_t size = (uint16_t)strlen(format); - char const* buf = format; - char last2 = 0, last3 = 0; - int lastcol = 0, COLS=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - uint8_t page=outcon?real_readb(BIOSMEM_SEG,BIOSMEM_CURRENT_PAGE):0; - bool lead=false; - dos.internal_output=true; - int rcount = 0; - for(uint16_t i = 0; i < size;i++) { - uint8_t out;uint16_t s=1; - BIOS_NCOLS; - if (!CURSOR_POS_COL(page)) last2=last3=0; - if (lead) lead = false; - else if ((IS_PC98_ARCH || isDBCSCP()) -#if defined(USE_TTF) - && dbcs_sbcs -#endif - && dbcs && isKanji1(buf[i])) lead = true; - if (buf[i] == 0xA) { - if (last_written_character != 0xD) {out = 0xD;DOS_WriteFile(STDOUT,&out,&s);} - if (outcon) rcount++; - } else if (outcon && lead && CURSOR_POS_COL(page)==COLS-1 && !(TTF_using() -#if defined(USE_TTF) - && autoboxdraw -#endif - && CheckBoxDrawing(last3, last2, last_written_character, buf[i]))) { - out = 0xD;DOS_WriteFile(STDOUT,&out,&s); - out = 0xA;DOS_WriteFile(STDOUT,&out,&s); - rcount++; - } else if (outcon && !CURSOR_POS_COL(page) && lastcol == COLS-1) - rcount++; - lastcol=CURSOR_POS_COL(page); - last3=last2;last2=last_written_character; - last_written_character = (char)(out = (uint8_t)buf[i]); - DOS_WriteFile(STDOUT,&out,&s); - } - dos.internal_output=false; - return rcount; - -// DOS_WriteFile(STDOUT,(uint8_t *)format,&size); -} - -static bool LocateEnvironmentBlock(PhysPt &env_base,PhysPt &env_fence,Bitu env_seg) { - if (env_seg == 0) { - /* The DOS program might have freed it's environment block perhaps. */ - return false; - } - - DOS_MCB env_mcb((uint16_t)(env_seg-1)); /* read the environment block's MCB to determine how large it is */ - env_base = PhysMake((uint16_t)env_seg,0); - env_fence = env_base + (PhysPt)(env_mcb.GetSize() << 4u); - return true; -} - -int EnvPhys_StrCmp(PhysPt es,PhysPt ef,const char *ls) { - (void)ef;//UNUSED - while (1) { - unsigned char a = mem_readb(es++); - unsigned char b = (unsigned char)(*ls++); - if (a == '=') a = 0; - if (a == 0 && b == 0) break; - if (a == b) continue; - return (int)a - (int)b; - } - - return 0; -} - -void EnvPhys_StrCpyToCPPString(std::string &result,PhysPt &env_scan,PhysPt env_fence) { - char tmp[512],*w=tmp,*wf=tmp+sizeof(tmp)-1; - - result.clear(); - while (env_scan < env_fence) { - char c; - if ((c=(char)mem_readb(env_scan++)) == 0) break; - - if (w >= wf) { - *w = 0; - result += tmp; - w = tmp; - } - - assert(w < wf); - *w++ = c; - } - if (w != tmp) { - *w = 0; - result += tmp; - } -} - -bool EnvPhys_ScanUntilNextString(PhysPt &env_scan,PhysPt env_fence) { - /* scan until end of block or NUL */ - while (env_scan < env_fence && mem_readb(env_scan) != 0) env_scan++; - - /* if we hit the fence, that's something to warn about. */ - if (env_scan >= env_fence) { - LOG_MSG("Warning: environment string scan hit the end of the environment block without terminating NUL\n"); - return false; - } - - /* if we stopped at anything other than a NUL, that's something to warn about */ - if (mem_readb(env_scan) != 0) { - LOG_MSG("Warning: environment string scan scan stopped without hitting NUL\n"); - return false; - } - - env_scan++; /* skip NUL */ - return true; -} - -bool Program::GetEnvStr(const char * entry,std::string & result) { - PhysPt env_base,env_fence,env_scan; - - if (dos_kernel_disabled) { - LOG_MSG("BUG: Program::GetEnvNum() called with DOS kernel disabled (such as OS boot).\n"); - return false; - } - - if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { - LOG_MSG("Warning: GetEnvCount() was not able to locate the program's environment block\n"); - return false; - } - - std::string bigentry(entry); - for (std::string::iterator it = bigentry.begin(); it != bigentry.end(); ++it) *it = toupper(*it); - - env_scan = env_base; - while (env_scan < env_fence) { - /* "NAME" + "=" + "VALUE" + "\0" */ - /* end of the block is a NULL string meaning a \0 follows the last string's \0 */ - if (mem_readb(env_scan) == 0) break; /* normal end of block */ - - if (EnvPhys_StrCmp(env_scan,env_fence,bigentry.c_str()) == 0) { - EnvPhys_StrCpyToCPPString(result,env_scan,env_fence); - return true; - } - - if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; - } - - return false; -} - -bool Program::GetEnvNum(Bitu want_num,std::string & result) { - PhysPt env_base,env_fence,env_scan; - Bitu num = 0; - - if (dos_kernel_disabled) { - LOG_MSG("BUG: Program::GetEnvNum() called with DOS kernel disabled (such as OS boot).\n"); - return false; - } - - if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { - LOG_MSG("Warning: GetEnvCount() was not able to locate the program's environment block\n"); - return false; - } - - result.clear(); - env_scan = env_base; - while (env_scan < env_fence) { - /* "NAME" + "=" + "VALUE" + "\0" */ - /* end of the block is a NULL string meaning a \0 follows the last string's \0 */ - if (mem_readb(env_scan) == 0) break; /* normal end of block */ - - if (num == want_num) { - EnvPhys_StrCpyToCPPString(result,env_scan,env_fence); - return true; - } - - num++; - if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; - } - - return false; -} - -Bitu Program::GetEnvCount(void) { - PhysPt env_base,env_fence,env_scan; - Bitu num = 0; - - if (dos_kernel_disabled) { - LOG_MSG("BUG: Program::GetEnvCount() called with DOS kernel disabled (such as OS boot).\n"); - return 0; - } - - if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { - LOG_MSG("Warning: GetEnvCount() was not able to locate the program's environment block\n"); - return false; - } - - env_scan = env_base; - while (env_scan < env_fence) { - /* "NAME" + "=" + "VALUE" + "\0" */ - /* end of the block is a NULL string meaning a \0 follows the last string's \0 */ - if (mem_readb(env_scan++) == 0) break; /* normal end of block */ - num++; - if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; - } - - return num; -} - -void Program::DebugDumpEnv() { - PhysPt env_base,env_fence,env_scan; - unsigned char c; - std::string tmp; - - if (dos_kernel_disabled) - return; - - if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) - return; - - env_scan = env_base; - LOG_MSG("DebugDumpEnv()"); - while (env_scan < env_fence) { - if (mem_readb(env_scan) == 0) break; - - while (env_scan < env_fence) { - if ((c=mem_readb(env_scan++)) == 0) break; - tmp += (char)c; - } - - LOG_MSG("...%s",tmp.c_str()); - tmp = ""; - } -} - -bool Program::FirstEnv(const char * entry) { - PhysPt env_base,env_fence,env_scan,env_first,env_last; - bool found = false; - - if (dos_kernel_disabled) { - LOG_MSG("BUG: Program::FirstEnv() called with DOS kernel disabled (such as OS boot).\n"); - return false; - } - - if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { - LOG_MSG("Warning: GetEnvCount() was not able to locate the program's environment block\n"); - return false; - } - - std::string bigentry(entry); - for (std::string::iterator it = bigentry.begin(); it != bigentry.end(); ++it) *it = toupper(*it); - - env_scan = env_base; - while (env_scan < env_fence) { - /* "NAME" + "=" + "VALUE" + "\0" */ - /* end of the block is a NULL string meaning a \0 follows the last string's \0 */ - if (mem_readb(env_scan) == 0) break; /* normal end of block */ - - if (EnvPhys_StrCmp(env_scan,env_fence,bigentry.c_str()) == 0) { - found = true; - break; - } - - if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; - } - - if (found) { - env_first = env_scan; - if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) return false; - env_last = env_scan; - -#if 0//DEBUG - fprintf(stderr,"Env base=%x fence=%x first=%x last=%x\n", - (unsigned int)env_base, (unsigned int)env_fence, - (unsigned int)env_first, (unsigned int)env_last); -#endif - - assert(env_first <= env_last); - - /* if the variable is already at the beginning, do nothing */ - if (env_first == env_base) return true; - - { - std::vector tmp; - tmp.resize(size_t(env_last-env_first)); - - /* save variable */ - for (size_t i=0;i < tmp.size();i++) - tmp[i] = mem_readb(env_first+(PhysPt)i); - - /* shift all variables prior to it forward over the variable, BACKWARDS */ - const size_t pl = size_t(env_first - env_base); - assert((env_first-pl) == env_base); - assert((env_last-pl) >= env_base); - assert(env_first < env_last); - assert(pl != 0); - for (size_t i=0;i < pl;i++) mem_writeb(env_last-(i+1), mem_readb(env_first-(i+1))); - - /* put the variable in at the beginning */ - assert((env_base+tmp.size()) == (env_last-pl)); - for (size_t i=0;i < tmp.size();i++) - mem_writeb(env_base+(PhysPt)i,tmp[i]); - } - } - - return true; -} - -bool Program::EraseEnv(void) { - PhysPt env_base,env_fence; - size_t nsl = 0,el = 0,needs; - - if (dos_kernel_disabled) { - LOG_MSG("BUG: Program::EraseEnv() called with DOS kernel disabled (such as OS boot).\n"); - return false; - } - - if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { - LOG_MSG("Warning: SetEnv() was not able to locate the program's environment block\n"); - return false; - } - - for (PhysPt w=env_base;w < env_fence;w++) - mem_writeb(w,0); - - return true; -} - -/* NTS: "entry" string must have already been converted to uppercase */ -bool Program::SetEnv(const char * entry,const char * new_string) { - PhysPt env_base,env_fence,env_scan; - size_t nsl = 0,el = 0,needs; - - if (dos_kernel_disabled) { - LOG_MSG("BUG: Program::SetEnv() called with DOS kernel disabled (such as OS boot).\n"); - return false; - } - - if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { - LOG_MSG("Warning: SetEnv() was not able to locate the program's environment block\n"); - return false; - } - - std::string bigentry(entry); - for (std::string::iterator it = bigentry.begin(); it != bigentry.end(); ++it) *it = toupper(*it); - - el = strlen(bigentry.c_str()); - if (*new_string != 0) nsl = strlen(new_string); - needs = nsl+1+el+1+1; /* entry + '=' + new_string + '\0' + '\0' */ - - /* look for the variable in the block. break the loop if found */ - env_scan = env_base; - while (env_scan < env_fence) { - if (mem_readb(env_scan) == 0) break; - - if (EnvPhys_StrCmp(env_scan,env_fence,bigentry.c_str()) == 0) { - /* found it. remove by shifting the rest of the environment block over */ - int zeroes=0; - PhysPt s,d; - - /* before we remove it: is there room for the new value? */ - if (nsl != 0) { - if ((env_scan+needs) > env_fence) { - LOG_MSG("Program::SetEnv() error, insufficient room for environment variable %s=%s (replacement)\n",bigentry.c_str(),new_string); - DebugDumpEnv(); - return false; - } - } - - s = env_scan; d = env_scan; - while (s < env_fence && mem_readb(s) != 0) s++; - if (s < env_fence && mem_readb(s) == 0) s++; - - while (s < env_fence) { - unsigned char b = mem_readb(s++); - - if (b == 0) zeroes++; - else zeroes=0; - - mem_writeb(d++,b); - if (zeroes >= 2) break; /* two consecutive zeros means the end of the block */ - } - } - else { - /* scan to next string */ - if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; - } - } - - /* At this point, env_scan points to the first byte beyond the block */ - /* add the string to the end of the block */ - if (*new_string != 0) { - if ((env_scan+needs) > env_fence) { - LOG_MSG("Program::SetEnv() error, insufficient room for environment variable %s=%s (addition)\n",bigentry.c_str(),new_string); - DebugDumpEnv(); - return false; - } - - assert(env_scan < env_fence); - for (const char *s=bigentry.c_str();*s != 0;) mem_writeb(env_scan++,(uint8_t)(*s++)); - mem_writeb(env_scan++,'='); - - assert(env_scan < env_fence); - for (const char *s=new_string;*s != 0;) mem_writeb(env_scan++,(uint8_t)(*s++)); - mem_writeb(env_scan++,0); - mem_writeb(env_scan++,0); - - assert(env_scan <= env_fence); - } - - return true; -} - -bool MSG_Write(const char *, const char *); - -/*! \brief CONFIG.COM utility to control configuration and files - * - * \description Utility to write configuration, set configuration, - * and other configuration related functions. - */ -class CONFIG : public Program { -public: - /*! \brief Program entry point, when the command is run - */ - void Run(void) override; -private: - void restart(const char* useconfig); - - void writeconf(std::string name, bool configdir,int everything, bool norem) { - // "config -wcd" should write to the config directory - if (configdir) { - // write file to the default config directory - std::string config_path; - Cross::GetPlatformConfigDir(config_path); - struct stat info; - if (!stat(config_path.c_str(), &info) || !(info.st_mode & S_IFDIR)) { -#ifdef WIN32 - CreateDirectory(config_path.c_str(), NULL); -#else - mkdir(config_path.c_str(), 0755); -#endif - } - name = config_path + name; - } - WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_WHICH"),name.c_str()); - if (!control->PrintConfig(name.c_str(),everything,norem)) { - WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_ERROR"),name.c_str()); - } - return; - } - - bool securemode_check() { - if (control->SecureMode()) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); - return true; - } - return false; - } -}; - -void dos_ver_menu(bool start), ReloadMapper(Section_prop *sec, bool init), SetGameState_Run(int value), update_dos_ems_menu(void), MountAllDrives(bool quiet), GFX_SwitchFullScreen(void), RebootConfig(std::string filename, bool confirm=false); -bool set_ver(char *s), GFX_IsFullscreen(void); - -void Load_Language(std::string name) { - if(control->opt_lang != "") control->opt_lang = name; - MSG_Init(); -#if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU || DOSBOXMENU_TYPE == DOSBOXMENU_NSMENU - mainMenu.unbuild(); - mainMenu.rebuild(); -#endif - if (!GFX_GetPreventFullscreen()) { - if (menu.toggle) DOSBox_SetMenu(); else DOSBox_NoMenu(); - } -#if defined(USE_TTF) - if (TTF_using()) resetFontSize(); -#endif -#if 0 - if (!uselangcp && !incall) { - int oldmsgcp = msgcodepage; - msgcodepage = dos.loaded_codepage; - SetKEYBCP(); - msgcodepage = oldmsgcp; - } -#endif -} - -void ApplySetting(std::string pvar, std::string inputline, bool quiet) { - if (!strcasecmp(pvar.c_str(), "dosbox")||!strcasecmp(pvar.c_str(), "dos")||!strcasecmp(pvar.c_str(), "dosv")||!strcasecmp(pvar.c_str(), "cpu")||!strcasecmp(pvar.c_str(), "sdl")||!strcasecmp(pvar.c_str(), "ttf")||!strcasecmp(pvar.c_str(), "render")||!strcasecmp(pvar.c_str(), "serial")||!strcasecmp(pvar.c_str(), "parallel")||!strcasecmp(pvar.c_str(), "printer")) { - Section_prop *section = static_cast(control->GetSection(pvar.c_str())); - if (section != NULL) { - if (!strcasecmp(pvar.c_str(), "dosbox")) { - force_nocachedir = section->Get_bool("nocachedir"); - sync_time = section->Get_bool("synchronize time"); - if (!strcasecmp(inputline.substr(0, 17).c_str(), "synchronize time=")) { - manualtime=false; - mainMenu.get_item("sync_host_datetime").check(sync_time).refresh_item(mainMenu); - } - std::string freesizestr = section->Get_string("freesizecap"); - if (freesizestr == "fixed" || freesizestr == "false" || freesizestr == "0") freesizecap = 0; - else if (freesizestr == "relative" || freesizestr == "2") freesizecap = 2; - else freesizecap = 1; - convertimg = section->Get_bool("convertdrivefat"); - wpcolon = section->Get_bool("leading colon write protect image"); - lockmount = section->Get_bool("locking disk image mount"); - if (!strcasecmp(inputline.substr(0, 9).c_str(), "saveslot=")) SetGameState_Run(section->Get_int("saveslot")-1); - if (!strcasecmp(inputline.substr(0, 11).c_str(), "saveremark=")) { - noremark_save_state = !section->Get_bool("saveremark"); - mainMenu.get_item("noremark_savestate").check(noremark_save_state).refresh_item(mainMenu); - } - if (!strcasecmp(inputline.substr(0, 15).c_str(), "forceloadstate=")) { - force_load_state = section->Get_bool("forceloadstate"); - mainMenu.get_item("force_loadstate").check(force_load_state).refresh_item(mainMenu); - } - if (!strcasecmp(inputline.substr(0, 23).c_str(), "show recorded filename=")) - show_recorded_filename = section->Get_bool("show recorded filename"); - if (!strcasecmp(inputline.substr(0, 6).c_str(), "title=")) { - dosbox_title=section->Get_string("title"); - trim(dosbox_title); - } - if (!strcasecmp(inputline.substr(0, 9).c_str(), "language=")) - Load_Language(section->Get_string("language")); - if (!strcasecmp(inputline.substr(0, 16).c_str(), "mapper send key=")) { - std::string mapsendkey = section->Get_string("mapper send key"); - if (mapsendkey=="winlogo") sendkeymap=1; - else if (mapsendkey=="winmenu") sendkeymap=2; - else if (mapsendkey=="alttab") sendkeymap=3; - else if (mapsendkey=="ctrlesc") sendkeymap=4; - else if (mapsendkey=="ctrlbreak") sendkeymap=5; - else sendkeymap=0; - mainMenu.get_item("sendkey_mapper_winlogo").check(sendkeymap==1).refresh_item(mainMenu); - mainMenu.get_item("sendkey_mapper_winmenu").check(sendkeymap==2).refresh_item(mainMenu); - mainMenu.get_item("sendkey_mapper_alttab").check(sendkeymap==3).refresh_item(mainMenu); - mainMenu.get_item("sendkey_mapper_ctrlesc").check(sendkeymap==4).refresh_item(mainMenu); - mainMenu.get_item("sendkey_mapper_ctrlbreak").check(sendkeymap==5).refresh_item(mainMenu); - mainMenu.get_item("sendkey_mapper_cad").check(!sendkeymap).refresh_item(mainMenu); - } - } else if (!strcasecmp(pvar.c_str(), "sdl")) { - modifier = section->Get_string("clip_key_modifier"); - paste_speed = section->Get_int("clip_paste_speed"); - if (!strcasecmp(inputline.substr(0, 16).c_str(), "mouse_wheel_key=")) { - wheel_key = section->Get_int("mouse_wheel_key"); - wheel_guest=wheel_key>0; - if (wheel_key<0) wheel_key=-wheel_key; - mainMenu.get_item("wheel_updown").check(wheel_key==1).refresh_item(mainMenu); - mainMenu.get_item("wheel_leftright").check(wheel_key==2).refresh_item(mainMenu); - mainMenu.get_item("wheel_pageupdown").check(wheel_key==3).refresh_item(mainMenu); - mainMenu.get_item("wheel_ctrlupdown").check(wheel_key==4).refresh_item(mainMenu); - mainMenu.get_item("wheel_ctrlleftright").check(wheel_key==5).refresh_item(mainMenu); - mainMenu.get_item("wheel_ctrlpageupdown").check(wheel_key==6).refresh_item(mainMenu); - mainMenu.get_item("wheel_ctrlwz").check(wheel_key==7).refresh_item(mainMenu); - mainMenu.get_item("wheel_none").check(wheel_key==0).refresh_item(mainMenu); - mainMenu.get_item("wheel_guest").check(wheel_guest).refresh_item(mainMenu); - } - if (!strcasecmp(inputline.substr(0, 12).c_str(), "sensitivity=")) { - Prop_multival* p3 = static_cast(section)->Get_multival("sensitivity"); - sdl.mouse.xsensitivity = p3->GetSection()->Get_int("xsens"); - sdl.mouse.ysensitivity = p3->GetSection()->Get_int("ysens"); - } -#if C_GAMELINK - if (!strcasecmp(inputline.substr(0, 22).c_str(), "gamelink load address=")) { - sdl.gamelink.loadaddr = section->Get_int("gamelink load address"); - } -#endif - if (!strcasecmp(inputline.substr(0, 11).c_str(), "fullscreen=")) { - if (section->Get_bool("fullscreen")) { - if (!GFX_IsFullscreen()) {GFX_LosingFocus();GFX_SwitchFullScreen();} - } else if (GFX_IsFullscreen()) {GFX_LosingFocus();GFX_SwitchFullScreen();} - } - if (!strcasecmp(inputline.substr(0, 7).c_str(), "output=")) { - std::string output=section->Get_string("output"); - if (output == "default") output=GetDefaultOutput(); - GFX_LosingFocus(); - toOutput(output.c_str()); -#if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU - if (!GFX_GetPreventFullscreen()) { - if (menu.toggle) DOSBox_SetMenu(); else DOSBox_NoMenu(); - } -#endif -#if defined(WIN32) && !defined(HX_DOS) - DOSBox_SetSysMenu(); -#endif - } - if (!strcasecmp(inputline.substr(0, 13).c_str(), "transparency=")) - SetWindowTransparency(section->Get_int("transparency")); -#if defined(C_SDL2) - if (!strcasecmp(inputline.substr(0, 16).c_str(), "mapperfile_sdl2=")) ReloadMapper(section,true); -#else - if (!strcasecmp(inputline.substr(0, 16).c_str(), "mapperfile_sdl1=")) ReloadMapper(section,true); -#if !defined(HAIKU) && !defined(RISCOS) - if (!strcasecmp(inputline.substr(0, 11).c_str(), "mapperfile=")) { - Prop_path* pp; -#if defined(C_SDL2) - pp = section->Get_path("mapperfile_sdl2"); -#else - pp = section->Get_path("mapperfile_sdl1"); -#endif - if (pp->realpath=="") ReloadMapper(section,true); - } - if (!strcasecmp(inputline.substr(0, 13).c_str(), "usescancodes=")) { - void setScanCode(Section_prop * section), loadScanCode(), MAPPER_Init(); - setScanCode(section); - loadScanCode(); - GFX_LosingFocus(); - MAPPER_Init(); - load=true; - } -#endif -#endif - if (!strcasecmp(inputline.substr(0, 8).c_str(), "display=")) { - void SetDisplayNumber(int display); - int numscreen = GetNumScreen(); - const int display = section->Get_int("display"); - if (display >= 0 && display <= numscreen) - SetDisplayNumber(display); - } - if (!strcasecmp(inputline.substr(0, 15).c_str(), "windowposition=")) { - const char* windowposition = section->Get_string("windowposition"); - int GetDisplayNumber(void); -#if defined(C_SDL2) || defined (WIN32) - int posx = -1, posy = -1; -#endif - if (windowposition && *windowposition) { - char result[100]; - safe_strncpy(result, windowposition, sizeof(result)); - char* y = strchr(result, ','); - if (y && *y) { - *y = 0; -#if defined(C_SDL2) || defined (WIN32) - posx = atoi(result); - posy = atoi(y + 1); -#endif - } - } -#if defined(C_SDL2) - SDL_Window* GFX_GetSDLWindow(void); - SDL_SetWindowTitle(GFX_GetSDLWindow(),"DOSBox-X"); - if (posx < 0 || posy < 0) { - SDL_DisplayMode dm; - int w = 640,h = 480; - SDL_GetWindowSize(GFX_GetSDLWindow(), &w, &h); - if (SDL_GetDesktopDisplayMode(GetDisplayNumber()?GetDisplayNumber()-1:0,&dm) == 0) { - posx = (dm.w - w)/2; - posy = (dm.h - h)/2; - } - } - if (GetDisplayNumber()>0) { - int displays = SDL_GetNumVideoDisplays(); - SDL_Rect bound; - for( int i = 1; i <= displays; i++ ) { - bound = SDL_Rect(); - SDL_GetDisplayBounds(i-1, &bound); - if (i == GetDisplayNumber()) { - posx += bound.x; - posy += bound.y; - break; - } - } - } - SDL_SetWindowPosition(GFX_GetSDLWindow(), posx, posy); -#elif defined(WIN32) - RECT rect; - MONITORINFO info; - GetWindowRect(GetHWND(), &rect); -#if !defined(HX_DOS) && !defined(_WIN32_WINDOWS) - if (GetDisplayNumber()>0) { - xyp xy={0}; - xy.x=-1; - xy.y=-1; - curscreen=0; - BOOL CALLBACK EnumDispProc(HMONITOR hMon, HDC dcMon, RECT* pRcMon, LPARAM lParam); - EnumDisplayMonitors(0, 0, EnumDispProc, reinterpret_cast(&xy)); - HMONITOR monitor = MonitorFromRect(&monrect, MONITOR_DEFAULTTONEAREST); - info.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(monitor, &info); - if (posx >=0 && posy >=0) { - posx+=info.rcMonitor.left; - posy+=info.rcMonitor.top; - } else { - posx = info.rcMonitor.left+(info.rcMonitor.right-info.rcMonitor.left-(rect.right-rect.left))/2; - posy = info.rcMonitor.top+(info.rcMonitor.bottom-info.rcMonitor.top-(rect.bottom-rect.top))/2; - } - } else -#endif - if (posx < 0 && posy < 0) { - posx = (GetSystemMetrics(SM_CXSCREEN)-(rect.right-rect.left))/2; - posy = (GetSystemMetrics(SM_CYSCREEN)-(rect.bottom-rect.top))/2; - } - MoveWindow(GetHWND(), posx, posy, rect.right-rect.left, rect.bottom-rect.top, true); -#endif - } - -#if defined(USE_TTF) - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(pvar.c_str(), "cpu")) { - bool turbo = section->Get_bool("turbo"); - if (turbo != ticksLocked) DOSBOX_UnlockSpeed2(true); - } else if (!strcasecmp(pvar.c_str(), "dos")) { - mountwarning = section->Get_bool("mountwarning"); - if (!strcasecmp(inputline.substr(0, 15).c_str(), "autofixwarning=")) { - std::string autofixwarning=section->Get_string("autofixwarning"); - autofixwarn=autofixwarning=="false"||autofixwarning=="0"||autofixwarning=="none"?0:(autofixwarning=="a20fix"?1:(autofixwarning=="loadfix"?2:3)); - } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "lfn=")) { - std::string lfn = section->Get_string("lfn"); - if (lfn=="true"||lfn=="1") enablelfn=1; - else if (lfn=="false"||lfn=="0") enablelfn=0; - else if (lfn=="autostart") enablelfn=-2; - else enablelfn=-1; - mainMenu.get_item("dos_lfn_auto").check(enablelfn==-1).refresh_item(mainMenu); - mainMenu.get_item("dos_lfn_enable").check(enablelfn==1).refresh_item(mainMenu); - mainMenu.get_item("dos_lfn_disable").check(enablelfn==0).refresh_item(mainMenu); - uselfn = enablelfn==1 || ((enablelfn == -1 || enablelfn == -2) && (dos.version.major>6 || winrun)); - } else if (!strcasecmp(inputline.substr(0, 16).c_str(), "fat32setversion=")) { - std::string fat32setverstr = section->Get_string("fat32setversion"); - if (fat32setverstr=="auto") fat32setver=1; - else if (fat32setverstr=="manual") fat32setver=0; - else fat32setver=-1; - } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "ver=")) { - const char *ver = section->Get_string("ver"); - if (!*ver) { - dos.version.minor=0; - dos.version.major=5; - dos_ver_menu(false); - } else if (set_ver((char *)ver)) - dos_ver_menu(false); - } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "ems=")) { - EMS_DoShutDown(); - EMS_Startup(NULL); - update_dos_ems_menu(); - } else if (!strcasecmp(inputline.substr(0, 32).c_str(), "shell configuration as commands=")) { - enable_config_as_shell_commands = section->Get_bool("shell configuration as commands"); - mainMenu.get_item("shell_config_commands").check(enable_config_as_shell_commands).enable(true).refresh_item(mainMenu); - } else if (!strcasecmp(inputline.substr(0, 18).c_str(), "dos clipboard api=")) { - clipboard_dosapi = section->Get_bool("dos clipboard api"); - mainMenu.get_item("clipboard_dosapi").check(clipboard_dosapi).refresh_item(mainMenu); - } else if (!strcasecmp(inputline.substr(0, 22).c_str(), "pipe temporary device=")) { - pipetmpdev = section->Get_bool("pipe temporary device"); -#if defined(WIN32) && !defined(HX_DOS) - } else if (!strcasecmp(inputline.substr(0, 13).c_str(), "automountall=")) { - const char *automountstr = section->Get_string("automountall"); - if (strcmp(automountstr, "0") && strcmp(automountstr, "false")) MountAllDrives(quiet||!strcmp(automountstr, "quiet")); - } else if (!strcasecmp(inputline.substr(0, 9).c_str(), "startcmd=")) { - winautorun = section->Get_bool("startcmd"); - mainMenu.get_item("dos_win_autorun").check(winautorun).enable(true).refresh_item(mainMenu); -#endif -#if defined(WIN32) && !defined(HX_DOS) || defined(LINUX) || defined(MACOSX) - } else if (!strcasecmp(inputline.substr(0, 15).c_str(), "starttranspath=")) { - starttranspath = section->Get_bool("starttranspath"); - mainMenu.get_item("dos_win_transpath").check(starttranspath).enable( -#if defined(WIN32) && !defined(HX_DOS) - true -#else - startcmd -#endif - ).refresh_item(mainMenu); - } else if (!strcasecmp(inputline.substr(0, 10).c_str(), "startwait=")) { - startwait = section->Get_bool("startwait"); - mainMenu.get_item("dos_win_wait").check(startwait).enable( -#if defined(WIN32) && !defined(HX_DOS) - true -#else - startcmd -#endif - ).refresh_item(mainMenu); - } else if (!strcasecmp(inputline.substr(0, 11).c_str(), "startquiet=")) { - startquiet = section->Get_bool("startquiet"); - mainMenu.get_item("dos_win_quiet").check(startquiet).enable( -#if defined(WIN32) && !defined(HX_DOS) - true -#else - startcmd -#endif - ).refresh_item(mainMenu); -#endif - } - } else if (!strcasecmp(pvar.c_str(), "ttf")) { - void ttf_reset(void), ttf_setlines(int cols, int lins), SetBlinkRate(Section_prop* section); - if (!strcasecmp(inputline.substr(0, 5).c_str(), "font=")) { -#if defined(USE_TTF) - if (TTF_using()) { - std::string font = section->Get_string("font"); - if (font.empty() && !IS_PC98_ARCH && !isDBCSCP()) notrysgf = true; - ttf_reset(); - notrysgf = false; - int missing = IS_PC98_ARCH ? 0 : setTTFMap(false); - if (missing > 0 && first_shell) first_shell->WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); - -#if C_PRINTER - if (printfont) UpdateDefaultPrinterFont(); -#endif - } -#endif - } else if (!strcasecmp(inputline.substr(0, 7).c_str(), "ptsize=")||!strcasecmp(inputline.substr(0, 8).c_str(), "winperc=")) { -#if defined(USE_TTF) - lesssize = true; - if (TTF_using()) ttf_reset(); - lesssize = false; -#endif - } else if (!strcasecmp(inputline.substr(0, 5).c_str(), "lins=")||!strcasecmp(inputline.substr(0, 5).c_str(), "cols=")) { -#if defined(USE_TTF) - if (TTF_using()) { - bool iscol=!strcasecmp(inputline.substr(0, 5).c_str(), "cols="); - if (iscol&&IS_PC98_ARCH) - SetVal("render", "cols", "80"); - else if (!CurMode) - ; - else if (CurMode->type==M_TEXT || IS_PC98_ARCH) { - const char *str = "\033[2J"; - uint16_t n = (uint16_t)strlen(str); - DOS_WriteFile(STDOUT,(uint8_t *)str,&n); - if (quiet && first_shell) first_shell->ShowPrompt(); - } else { - reg_ax=CurMode->mode; - CALLBACK_RunRealInt(0x10); - } - lastset=iscol?2:1; - ttf_setlines(0, 0); - lastset=0; - } -#endif - } else if (!strcasecmp(inputline.substr(0, 13).c_str(), "outputswitch=")) { -#if defined(USE_TTF) - SetOutputSwitch(section->Get_string("outputswitch")); -#endif - } else if (!strcasecmp(inputline.substr(0, 7).c_str(), "colors=")) { -#if defined(USE_TTF) - if (TTF_using() && !strlen(section->Get_string("colors"))) ttf_reset_colors(); -#endif - } else if (!strcasecmp(inputline.substr(0, 3).c_str(), "wp=")) { -#if defined(USE_TTF) - const char *wpstr=section->Get_string("wp"); - wpType=wpVersion=0; - if (strlen(wpstr)>1) { - if (!strncasecmp(wpstr, "WP", 2)) wpType=1; - else if (!strncasecmp(wpstr, "WS", 2)) wpType=2; - else if (!strncasecmp(wpstr, "XY", 3)) wpType=3; - if (strlen(wpstr)>2&&wpstr[2]>='1'&&wpstr[2]<='9') wpVersion=wpstr[2]-'0'; - } - mainMenu.get_item("ttf_wpno").check(!wpType).refresh_item(mainMenu); - mainMenu.get_item("ttf_wpwp").check(wpType==1).refresh_item(mainMenu); - mainMenu.get_item("ttf_wpws").check(wpType==2).refresh_item(mainMenu); - mainMenu.get_item("ttf_wpxy").check(wpType==3).refresh_item(mainMenu); - mainMenu.get_item("ttf_wpfe").check(wpType==4).refresh_item(mainMenu); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 5).c_str(), "wpbg=")) { -#if defined(USE_TTF) - wpBG = section->Get_int("wpbg"); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 5).c_str(), "wpfg=")) { -#if defined(USE_TTF) - wpFG = section->Get_int("wpfg"); - if (wpFG<0) wpFG = 7; - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 5).c_str(), "bold=")) { -#if defined(USE_TTF) - showbold = section->Get_bool("bold"); - mainMenu.get_item("ttf_showbold").check(showbold).refresh_item(mainMenu); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 7).c_str(), "italic=")) { -#if defined(USE_TTF) - showital = section->Get_bool("italic"); - mainMenu.get_item("ttf_showital").check(showital).refresh_item(mainMenu); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 10).c_str(), "underline=")) { -#if defined(USE_TTF) - showline = section->Get_bool("underline"); - mainMenu.get_item("ttf_showline").check(showline).refresh_item(mainMenu); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 10).c_str(), "strikeout=")) { -#if defined(USE_TTF) - showsout = section->Get_bool("strikeout"); - mainMenu.get_item("ttf_showsout").check(showsout).refresh_item(mainMenu); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 8).c_str(), "char512=")) { -#if defined(USE_TTF) - char512 = section->Get_bool("char512"); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 12).c_str(), "righttoleft=")) { -#if defined(USE_TTF) - rtl = section->Get_bool("righttoleft"); - mainMenu.get_item("ttf_right_left").check(rtl).refresh_item(mainMenu); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 10).c_str(), "printfont=")) { -#if defined(USE_TTF) && C_PRINTER - printfont = section->Get_bool("printfont"); - mainMenu.get_item("ttf_printfont").check(printfont).refresh_item(mainMenu); - UpdateDefaultPrinterFont(); -#endif - } else if (!strcasecmp(inputline.substr(0, 9).c_str(), "autodbcs=")) { -#if defined(USE_TTF) - dbcs_sbcs = section->Get_bool("autodbcs"); - mainMenu.get_item("mapper_dbcssbcs").check(dbcs_sbcs).refresh_item(mainMenu); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 12).c_str(), "autoboxdraw=")) { -#if defined(USE_TTF) - autoboxdraw = section->Get_bool("autoboxdraw"); - mainMenu.get_item("mapper_autoboxdraw").check(autoboxdraw).refresh_item(mainMenu); - if (TTF_using()) resetFontSize(); -#endif - } else if (!strcasecmp(inputline.substr(0, 14).c_str(), "halfwidthkana=")) { -#if defined(USE_TTF) - halfwidthkana = section->Get_bool("halfwidthkana"); - mainMenu.get_item("ttf_halfwidthkana").check(halfwidthkana||IS_PC98_ARCH||IS_JEGA_ARCH).refresh_item(mainMenu); - if (TTF_using()) {setTTFCodePage();resetFontSize();} -#endif - } else if (!strcasecmp(inputline.substr(0, 7).c_str(), "blinkc=")) { -#if defined(USE_TTF) - SetBlinkRate(section); - mainMenu.get_item("ttf_blinkc").check(blinkCursor>-1).refresh_item(mainMenu); -#endif - } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "gbk=")) { - if (gbk != section->Get_bool("gbk")) { - gbk = !gbk; - if (enable_dbcs_tables&&dos.tables.dbcs&&(IS_PDOSV||dos.loaded_codepage==936)) mem_writeb(Real2Phys(dos.tables.dbcs)+2,gbk?0x81:0xA1); - clearFontCache(); - if (dos.loaded_codepage!=950&&dos.loaded_codepage!=951) mainMenu.get_item("ttf_extcharset").check(dos.loaded_codepage==936?gbk:(gbk&&chinasea)).refresh_item(mainMenu); -#if defined(USE_TTF) - if (TTF_using() && dos.loaded_codepage==936) resetFontSize(); -#endif - } - } else if (!strcasecmp(inputline.substr(0, 9).c_str(), "chinasea=")) { - if (chinasea != section->Get_bool("chinasea")) { - chinasea = !chinasea; - if (!chinasea) makestdcp950table(); - else makeseacp951table(); - clearFontCache(); - if (dos.loaded_codepage!=936) mainMenu.get_item("ttf_extcharset").check(dos.loaded_codepage==950||dos.loaded_codepage==951?chinasea:(gbk&&chinasea)).refresh_item(mainMenu); - if ((TTF_using() || showdbcs) && (dos.loaded_codepage==950 || dos.loaded_codepage==951)) { - MSG_Init(); -#if defined(USE_TTF) - if (TTF_using()) resetFontSize(); -#endif - } - } - } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "uao=")) { - if (uao != section->Get_bool("uao")) { - uao = !uao; - clearFontCache(); - if ((TTF_using() || showdbcs) && dos.loaded_codepage==951) { - MSG_Init(); - DOSBox_SetSysMenu(); -#if defined(USE_TTF) - if (TTF_using()) resetFontSize(); -#endif - runRescan("-A -Q"); - } - } - } - } else if (!strcasecmp(pvar.c_str(), "dosv")) { - if (!strcasecmp(inputline.substr(0, 15).c_str(), "showdbcsnodosv=") -#if defined(USE_TTF) - && !ttfswitch -#endif - ) { - std::string showdbcsstr = section->Get_string("showdbcsnodosv"); -#if defined(USE_TTF) - showdbcs = showdbcsstr=="true"||showdbcsstr=="1"||(showdbcsstr=="auto" && (loadlang || dbcs_sbcs)); -#else - showdbcs = showdbcsstr=="true"||showdbcsstr=="1"||(showdbcsstr=="auto" && loadlang); -#endif - if (!IS_EGAVGA_ARCH) showdbcs = false; - } else if (!strcasecmp(inputline.substr(0, 11).c_str(), "fepcontrol=")||!strcasecmp(inputline.substr(0, 7).c_str(), "vtext1=")||!strcasecmp(inputline.substr(0, 7).c_str(), "vtext2=")) - DOSV_SetConfig(section); - } else if (!strcasecmp(pvar.c_str(), "render")) { - if (!strcasecmp(inputline.substr(0, 9).c_str(), "glshader=")) { -#if C_OPENGL - std::string LoadGLShader(Section_prop * section); - LoadGLShader(section); - GFX_ForceRedrawScreen(); -#endif - } else if (!strcasecmp(inputline.substr(0, 12).c_str(), "pixelshader=")) - GFX_ForceRedrawScreen(); - else if (!strcasecmp(inputline.substr(0, 13).c_str(), "aspect_ratio=")) { - setAspectRatio(section); - if (render.aspect) GFX_ForceRedrawScreen(); - } - } else if (!strcasecmp(pvar.c_str(), "serial")) { - if (!strcasecmp(inputline.substr(0, 6).c_str(), "serial") && inputline[7]=='=') { - std::string val = section->Get_string("serial" + std::string(1, inputline[6])), cmd = std::string(1, inputline[6]) + " " + (val.size()?val:"dummy"); - runSerial(cmd.c_str()); - } - } else if (!strcasecmp(pvar.c_str(), "parallel")) { - if (!strcasecmp(inputline.substr(0, 8).c_str(), "parallel") && inputline[9]=='=') { - std::string val = section->Get_string("parallel" + std::string(1, inputline[8])), cmd = std::string(1, inputline[8]) + " " + (val.size()?val:"disabled"); - runParallel(cmd.c_str()); - } -#if C_PRINTER - } else if (!strcasecmp(pvar.c_str(), "printer")) { - PRINTER_Shutdown(NULL); - PRINTER_Init(); -#endif - } - } - } -} - -void CONFIG::Run(void) { - static const char* const params[] = { - "-r", "-wcp", "-wcd", "-wc", "-writeconf", "-wcpboot", "-wcdboot", "-wcboot", "-writeconfboot", "-bootconf", "-bc", - "-l", "-rmconf", "-h", "-help", "-?", "-axclear", "-axadd", "-axtype", - "-avistart","-avistop", - "-startmapper", - "-get", "-set", "-setf", - "-writelang", "-wl", "-langname", "-ln", - "-securemode", "-setup", "-all", "-mod", "-norem", "-errtest", "-gui", NULL }; -/* HACK: P_ALL is in linux/wait.h */ -#if defined(P_ALL) -#define __P_ALL P_ALL -#undef P_ALL -#endif - enum prs { - P_NOMATCH, P_NOPARAMS, // fixed return values for GetParameterFromList - P_RESTART, - P_WRITECONF_PORTABLE, P_WRITECONF_DEFAULT, P_WRITECONF, P_WRITECONF2, - P_WRITECONF_PORTABLE_REBOOT, P_WRITECONF_DEFAULT_REBOOT, P_WRITECONF_REBOOT, P_WRITECONF2_REBOOT, - P_BOOTCONF, P_BOOTCONF2, P_LISTCONF, P_KILLCONF, - P_HELP, P_HELP2, P_HELP3, - P_AUTOEXEC_CLEAR, P_AUTOEXEC_ADD, P_AUTOEXEC_TYPE, - P_REC_AVI_START, P_REC_AVI_STOP, - P_START_MAPPER, - P_GETPROP, P_SETPROP, P_SETFORCE, - P_WRITELANG, P_WRITELANG2, P_LANGNAME, P_LANGNAME2, - P_SECURE, P_SETUP, P_ALL, P_MOD, P_NOREM, P_ERRTEST, P_GUI - } presult = P_NOMATCH; - - Section_prop * section=static_cast(control->GetSection("dosbox")); - int all = section->Get_bool("show advanced options")?1:-1; - bool first = true, norem = false; - std::vector pvars; - if (cmd->FindExist("-setup", true)) all = 2; - else if (cmd->FindExist("-all", true)) all = 1; - else if (cmd->FindExist("-mod", true)) all = 0; - if (cmd->FindExist("-norem", true)) norem = true; - // Loop through the passed parameters - while(presult != P_NOPARAMS) { - presult = (enum prs)cmd->GetParameterFromList(params, pvars); - switch(presult) { - - case P_SETUP: - all = 2; - break; - - case P_ALL: - if (all<1) all = 1; - break; -#if defined(__P_ALL) -#define P_ALL __P_ALL -#endif - - case P_MOD: - if (all==-1) all = 0; - break; - - case P_NOREM: - norem = true; - break; - - case P_GUI: - void GUI_Run(bool pressed); - GUI_Run(false); - break; - - case P_LANGNAME: case P_LANGNAME2: - if (pvars.size() < 1) { - WriteOut("%s\n", langname.c_str()); - return; - } else - langname=pvars[0]; - break; - - case P_ERRTEST: - exit_status = 1; - WriteExitStatus(); - return; - - case P_RESTART: - WriteOut("-restart is no longer supported\n"); - return; - - case P_LISTCONF: { - Bitu size = (Bitu)control->configfiles.size(); - std::string config_path; - Cross::GetPlatformConfigDir(config_path); - WriteOut(MSG_Get("PROGRAM_CONFIG_CONFDIR"), VERSION,config_path.c_str()); - char cwd[512] = {0}; - char *res = getcwd(cwd,sizeof(cwd)-1); - if (res!=NULL) WriteOut(MSG_Get("PROGRAM_CONFIG_WORKDIR"), cwd); - if (size==0&&!configfile.size()) WriteOut(MSG_Get("PROGRAM_CONFIG_NOCONFIGFILE")); - else { - WriteOut(MSG_Get("PROGRAM_CONFIG_PRIMARY_CONF"),control->configfiles.front().c_str()); - if (size > 1) { - WriteOut(MSG_Get("PROGRAM_CONFIG_ADDITIONAL_CONF")); - for(Bitu i = 1; i < size; i++) - WriteOut("%s\n",control->configfiles[i].c_str()); - } - if (configfile.size()) WriteOut(MSG_Get("PROGRAM_CONFIG_GLOBAL_CONF"),configfile.c_str()); - } - if (control->startup_params.size() > 0) { - std::string test; - for(size_t k = 0; k < control->startup_params.size(); k++) - test += control->startup_params[k] + " "; - WriteOut(MSG_Get("PROGRAM_CONFIG_PRINT_STARTUP"), test.c_str()); - } - break; - } - case P_WRITECONF: case P_WRITECONF2: case P_WRITECONF_REBOOT: case P_WRITECONF2_REBOOT: - if (securemode_check()) return; - if (pvars.size() > 1) return; - else if (pvars.size() == 1) { - // write config to specific file, except if it is an absolute path - writeconf(pvars[0], !Cross::IsPathAbsolute(pvars[0]), all, norem); - if (presult==P_WRITECONF_REBOOT || presult==P_WRITECONF2_REBOOT) RebootConfig(pvars[0]); - } else { - // -wc without parameter: write primary config file - if (control->configfiles.size()) { - writeconf(control->configfiles[0], false, all, norem); - if (presult==P_WRITECONF_REBOOT || presult==P_WRITECONF2_REBOOT) RebootConfig(control->configfiles[0]); - } else WriteOut(MSG_Get("PROGRAM_CONFIG_NOCONFIGFILE")); - } - break; - case P_WRITECONF_DEFAULT: case P_WRITECONF_DEFAULT_REBOOT: { - // write to /userdir/dosbox-x-0.xx.conf - if (securemode_check()) return; - if (pvars.size() > 0) return; - std::string confname; - Cross::GetPlatformConfigName(confname); - writeconf(confname, true, all, norem); - if (presult==P_WRITECONF_DEFAULT_REBOOT) RebootConfig(confname); - break; - } - case P_WRITECONF_PORTABLE: case P_WRITECONF_PORTABLE_REBOOT: - if (securemode_check()) return; - if (pvars.size() > 1) return; - else if (pvars.size() == 1) { - // write config to startup directory - writeconf(pvars[0], false, all, norem); - if (presult==P_WRITECONF_PORTABLE_REBOOT) RebootConfig(pvars[0]); - } else { - // -wcp without parameter: write dosbox-x.conf to startup directory - writeconf(std::string("dosbox-x.conf"), false, all, norem); - if (presult==P_WRITECONF_PORTABLE_REBOOT) RebootConfig(std::string("dosbox-x.conf")); - } - break; - case P_BOOTCONF: case P_BOOTCONF2: - if (securemode_check()) return; - if (pvars.size() > 1) return; - else if (pvars.size() == 1) { - RebootConfig(pvars[0]); - } else { - Bitu size = (Bitu)control->configfiles.size(); - if (size==0) RebootConfig("dosbox-x.conf"); - else RebootConfig(control->configfiles.front().c_str()); - } - break; - case P_NOPARAMS: - if (!first) break; - - case P_NOMATCH: - WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE")); - return; - - case P_HELP: case P_HELP2: case P_HELP3: { - switch(pvars.size()) { - case 0: - WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE")); - return; - case 1: { - if (!strcasecmp("sections",pvars[0].c_str())) { - // list the sections - WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_SECTLIST")); - int i = 0; - while(true) { - Section* sec = control->GetSection(i++); - if (!sec) break; - WriteOut("%s\n",sec->GetName()); - } - return; - } - // if it's a section, leave it as one-param - Section* sec = control->GetSection(pvars[0].c_str()); - if (!sec) { - // could be a property - sec = control->GetSectionFromProperty(pvars[0].c_str()); - if (!sec&&pvars[0].size()>4&&!strcasecmp(pvars[0].substr(0, 4).c_str(), "ttf.")) { - pvars[0].erase(0,4); - sec = control->GetSectionFromProperty(pvars[0].c_str()); - } - if (!sec) { - WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); - return; - } - pvars.insert(pvars.begin(),std::string(sec->GetName())); - } - break; - } - case 2: { - // sanity check - Section* sec = control->GetSection(pvars[0].c_str()); - Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str()); - - if (sec != sec2) { - WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_DUPLICATE")); - } - break; - } - default: - WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE")); - return; - } - // if we have one value in pvars, it's a section - // two values are section + property - Section* sec = control->GetSection(pvars[0].c_str()); - if (sec==NULL) { - WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); - return; - } - Section_prop* psec = dynamic_cast (sec); - if (psec==NULL) { - // failed; maybe it's the autoexec section? - Section_line* pline = dynamic_cast (sec); - if (pline==NULL) E_Exit("Section dynamic cast failed."); - - WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_LINEHLP"), - pline->GetName(), - // this is 'unclean' but the autoexec section has no help associated - MSG_Get("AUTOEXEC_CONFIGFILE_HELP"), - pline->data.c_str() ); - return; - } - if (pvars.size()==1) { - size_t i = 0; - WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_SECTHLP"),pvars[0].c_str()); - while(true) { - // list the properties - Property* p = psec->Get_prop((int)(i++)); - if (p==NULL) break; - if (!(all>0 || (all==-1 && (p->basic() || p->modified())) || (!all && ((p->propname == "rem" && (!strcmp(pvars[0].c_str(), "4dos") || !strcmp(pvars[0].c_str(), "config"))) || p->modified())))) continue; - WriteOut("%s\n", p->propname.c_str()); - } - if (!strcasecmp(pvars[0].c_str(), "config")) - WriteOut("set\ninstall\ninstallhigh\ndevice\ndevicehigh\n"); - } else { - // find the property by its name - size_t i = 0; - while (true) { - Property *p = psec->Get_prop((int)(i++)); - if (p==NULL) break; - if (!strcasecmp(p->propname.c_str(),pvars[1].c_str())) { - // found it; make the list of possible values - std::string propvalues; - std::vector pv = p->GetValues(); - - if (p->Get_type()==Value::V_BOOL) { - // possible values for boolean are true, false - propvalues += "true, false"; - } else if (p->Get_type()==Value::V_INT) { - // print min, max for integer values if used - Prop_int* pint = dynamic_cast (p); - if (pint==NULL) E_Exit("Int property dynamic cast failed."); - if (pint->getMin() != pint->getMax()) { - std::ostringstream oss; - oss << pint->getMin(); - oss << ".."; - oss << pint->getMax(); - propvalues += oss.str(); - } - } - for(Bitu k = 0; k < pv.size(); k++) { - if (pv[k].ToString() =="%u") - propvalues += MSG_Get("PROGRAM_CONFIG_HLP_POSINT"); - else propvalues += pv[k].ToString(); - if ((k+1) < pv.size() && (strcmp(pvars[0].c_str(), "config") || p->propname != "numlock" || pv[k+1].ToString() != "")) propvalues += ", "; - } - - WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_PROPHLP"), - p->propname.c_str(), - sec->GetName(), - p->Get_help(),propvalues.c_str(), - p->Get_Default_Value().ToString().c_str(), - p->GetValue().ToString().c_str()); - // print 'changeability' - if (p->getChange()==Property::Changeable::OnlyAtStart) { - WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_NOCHANGE")); - } - return; - } - } - break; - } - return; - } - case P_AUTOEXEC_CLEAR: { - Section_line* sec = dynamic_cast - (control->GetSection(std::string("autoexec"))); - sec->data.clear(); - break; - } - case P_AUTOEXEC_ADD: { - if (pvars.size() == 0) { - WriteOut(MSG_Get("PROGRAM_CONFIG_MISSINGPARAM")); - return; - } - Section_line* sec = dynamic_cast - (control->GetSection(std::string("autoexec"))); - - for(Bitu i = 0; i < pvars.size(); i++) sec->HandleInputline(pvars[i]); - break; - } - case P_AUTOEXEC_TYPE: { - Section_line* sec = dynamic_cast - (control->GetSection(std::string("autoexec"))); - WriteOut("\n%s",sec->data.c_str()); - break; - } - case P_REC_AVI_START: - CAPTURE_VideoStart(); - break; - case P_REC_AVI_STOP: - CAPTURE_VideoStop(); - break; - case P_START_MAPPER: - if (securemode_check()) return; - MAPPER_Run(false); - break; - case P_GETPROP: { - // "section property" - // "property" - // "section" - // "section" "property" - if (pvars.size()==0) { - WriteOut(MSG_Get("PROGRAM_CONFIG_GET_SYNTAX")); - return; - } - Section* sec = control->GetSectionFromProperty(pvars[0].c_str()); - std::string::size_type spcpos = pvars[0].find_first_of(' '); - // split on the ' ' - if (!sec && spcpos != std::string::npos) { - if (spcpos>1&&pvars[0].c_str()[spcpos-1]==',') - spcpos=pvars[0].find_first_of(' ', spcpos+1); - if (spcpos != std::string::npos) { - pvars.insert(pvars.begin()+1,pvars[0].substr(spcpos+1)); - pvars[0].erase(spcpos); - } - } - switch(pvars.size()) { - case 1: { - // property/section only - // is it a section? - sec = control->GetSection(pvars[0].c_str()); - if (sec) { - // list properties in section - int i = 0; - Section_prop* psec = dynamic_cast (sec); - if (psec==NULL) { - // autoexec section - Section_line* pline = dynamic_cast (sec); - if (pline==NULL) E_Exit("Section dynamic cast failed."); - - WriteOut("%s",pline->data.c_str()); - break; - } - while(true) { - // list the properties - Property* p = psec->Get_prop(i++); - if (p==NULL) break; - if (!(all>0 || (all==-1 && (p->basic() || p->modified())) || (!all && ((p->propname == "rem" && (!strcmp(pvars[0].c_str(), "4dos") || !strcmp(pvars[0].c_str(), "config"))) || p->modified())))) continue; - WriteOut("%s=%s\n", p->propname.c_str(), - p->GetValue().ToString().c_str()); - } - if (!strcasecmp(pvars[0].c_str(), "config")||!strcasecmp(pvars[0].c_str(), "4dos")) { - const char * extra = psec->data.c_str(); - if (extra&&strlen(extra)) { - std::istringstream in(extra); - char linestr[CROSS_LEN+1], cmdstr[CROSS_LEN], valstr[CROSS_LEN]; - char *cmd=cmdstr, *val=valstr, /**lin=linestr,*/ *p; - if (in) for (std::string line; std::getline(in, line); ) { - if (line.length()>CROSS_LEN) { - strncpy(linestr, line.c_str(), CROSS_LEN); - linestr[CROSS_LEN]=0; - } else - strcpy(linestr, line.c_str()); - p=strchr(linestr, '='); - if (p!=NULL) { - *p=0; - strcpy(cmd, linestr); - cmd=trim(cmd); - strcpy(val, p+1); - val=trim(val); - lowcase(cmd); - if (!strcasecmp(pvars[0].c_str(), "4dos")||!strncmp(cmd, "set ", 4)||!strcmp(cmd, "install")||!strcmp(cmd, "installhigh")||!strcmp(cmd, "device")||!strcmp(cmd, "devicehigh")) - if (!((!strcmp(cmd, "install")||!strcmp(cmd, "installhigh")||!strcmp(cmd, "device")||!strcmp(cmd, "devicehigh"))&&!strlen(val)&&!all)) - WriteOut("%s=%s\n", cmd, val); - } - } - } - } - } else { - // no: maybe it's a property? - sec = control->GetSectionFromProperty(pvars[0].c_str()); - if (!sec&&pvars[0].size()>4&&!strcasecmp(pvars[0].substr(0, 4).c_str(), "ttf.")) { - pvars[0].erase(0,4); - sec = control->GetSectionFromProperty(pvars[0].c_str()); - } else if (!sec && pvars[0].size() && !strcasecmp(pvars[0].c_str(), "langcp")) { - pvars[0] = "language"; - sec = control->GetSectionFromProperty(pvars[0].c_str()); - } - if (!sec) { - unsigned int maxWidth, maxHeight; - void GetMaxWidthHeight(unsigned int *pmaxWidth, unsigned int *pmaxHeight), GetDrawWidthHeight(unsigned int *pdrawWidth, unsigned int *pdrawHeight); - if (!strcasecmp(pvars[0].c_str(), "screenwidth")) { - GetMaxWidthHeight(&maxWidth, &maxHeight); - WriteOut("%d\n",maxWidth); - first_shell->SetEnv("CONFIG",std::to_string(maxWidth).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "screenheight")) { - GetMaxWidthHeight(&maxWidth, &maxHeight); - WriteOut("%d\n",maxHeight); - first_shell->SetEnv("CONFIG",std::to_string(maxHeight).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "drawwidth")) { - GetDrawWidthHeight(&maxWidth, &maxHeight); - WriteOut("%d\n",maxWidth); - first_shell->SetEnv("CONFIG",std::to_string(maxWidth).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "drawheight")) { - GetDrawWidthHeight(&maxWidth, &maxHeight); - WriteOut("%d\n",maxHeight); - first_shell->SetEnv("CONFIG",std::to_string(maxHeight).c_str()); -#if defined(C_SDL2) - } else if (!strcasecmp(pvars[0].c_str(), "clientwidth")) { - int w = 640,h = 480; - SDL_Window* GFX_GetSDLWindow(void); - SDL_GetWindowSize(GFX_GetSDLWindow(), &w, &h); - WriteOut("%d\n",w); - first_shell->SetEnv("CONFIG",std::to_string(w).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "clientheight")) { - int w = 640,h = 480; - SDL_Window* GFX_GetSDLWindow(void); - SDL_GetWindowSize(GFX_GetSDLWindow(), &w, &h); - WriteOut("%d\n",h); - first_shell->SetEnv("CONFIG",std::to_string(h).c_str()); -#elif defined(WIN32) - } else if (!strcasecmp(pvars[0].c_str(), "clientwidth")) { - RECT rect; - GetClientRect(GetHWND(), &rect); - WriteOut("%d\n",rect.right-rect.left); - first_shell->SetEnv("CONFIG",std::to_string(rect.right-rect.left).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "clientheight")) { - RECT rect; - GetClientRect(GetHWND(), &rect); - WriteOut("%d\n",rect.bottom-rect.top); - first_shell->SetEnv("CONFIG",std::to_string(rect.bottom-rect.top).c_str()); -#endif -#if defined(WIN32) - } else if (!strcasecmp(pvars[0].c_str(), "windowwidth")) { - RECT rect; - GetWindowRect(GetHWND(), &rect); - WriteOut("%d\n",rect.right-rect.left); - first_shell->SetEnv("CONFIG",std::to_string(rect.right-rect.left).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "windowheight")) { - RECT rect; - GetWindowRect(GetHWND(), &rect); - WriteOut("%d\n",rect.bottom-rect.top); - first_shell->SetEnv("CONFIG",std::to_string(rect.bottom-rect.top).c_str()); -#endif - } else if (!strcasecmp(pvars[0].c_str(), "system")) { - WriteOut("%s\n",PACKAGE); - first_shell->SetEnv("CONFIG",PACKAGE); - } else if (!strcasecmp(pvars[0].c_str(), "version")) { - WriteOut("%s\n",VERSION); - first_shell->SetEnv("CONFIG",VERSION); - } else if (!strcasecmp(pvars[0].c_str(), "hostos")) { - if (securemode_check()) return; - const char *hostos = -#if defined(HX_DOS) - "DOS" -#elif defined(WIN32) - "Windows" -#elif defined(LINUX) - "Linux" -#elif defined(MACOSX) - "macOS" -#elif defined(OS2) - "OS/2" -#else - "Other" -#endif - ; - WriteOut("%s\n",hostos); - first_shell->SetEnv("CONFIG",hostos); - } else if (!strcasecmp(pvars[0].c_str(), "workdir")) { - if (securemode_check()) return; - char cwd[512] = {0}; - char *res = getcwd(cwd,sizeof(cwd)-1); - WriteOut("%s\n",res==NULL?"":cwd); - first_shell->SetEnv("CONFIG",res==NULL?"":cwd); - } else if (!strcasecmp(pvars[0].c_str(), "programdir")) { - if (securemode_check()) return; - std::string GetDOSBoxXPath(bool withexe=false), exepath=GetDOSBoxXPath(); - WriteOut("%s\n",exepath.c_str()); - first_shell->SetEnv("CONFIG",exepath.c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "userconfigdir")) { - if (securemode_check()) return; - std::string config_path; - Cross::GetPlatformConfigDir(config_path); - WriteOut("%s\n",config_path.c_str()); - first_shell->SetEnv("CONFIG",config_path.c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "configdir")) { - if (securemode_check()) return; - std::string configdir=control->configfiles.size()?control->configfiles[control->configfiles.size()-1]:""; - if (configdir.size()) { - std::string::size_type pos = configdir.rfind(CROSS_FILESPLIT); - if(pos == std::string::npos) pos = 0; - configdir.erase(pos); - } - WriteOut("%s\n",configdir.c_str()); - first_shell->SetEnv("CONFIG",configdir.c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "cd")) { - uint8_t drive = DOS_GetDefaultDrive()+'A'; - char dir[DOS_PATHLENGTH]; - DOS_GetCurrentDir(0,dir,true); - WriteOut("%c:\\",drive); - WriteOut_NoParsing(dir, true); - WriteOut("\n"); - first_shell->SetEnv("CONFIG",(std::string(1, drive)+":\\"+std::string(dir)).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "date")) { - uint32_t ticks=mem_readd(BIOS_TIMER); - uint8_t add=mem_readb(BIOS_24_HOURS_FLAG); - mem_writeb(BIOS_24_HOURS_FLAG,0); // reset the "flag" - if (add) DOS_AddDays(add); - const char *date = FormatDate(dos.date.year, dos.date.month, dos.date.day); - WriteOut("%s\n",date); - first_shell->SetEnv("CONFIG",date); - } else if (!strcasecmp(pvars[0].c_str(), "errorlevel")) { - WriteOut("%d\n",dos.return_code); - first_shell->SetEnv("CONFIG",std::to_string(dos.return_code).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "random")) { - initRand(); - int random = rand()%32768; - WriteOut("%s\n",std::to_string(random).c_str()); - first_shell->SetEnv("CONFIG",std::to_string(random).c_str()); - } else if (!strcasecmp(pvars[0].c_str(), "time")) { - uint32_t hour, min, sec; - char c=dos.tables.country[13]; - uint32_t ticks=mem_readd(BIOS_TIMER); - uint8_t add=mem_readb(BIOS_24_HOURS_FLAG); - mem_writeb(BIOS_24_HOURS_FLAG,0); // reset the "flag" - uint16_t cx=(uint16_t)(ticks >> 16u), dx=(uint16_t)(ticks & 0xffff); - if (add) DOS_AddDays(add); - ticks=((Bitu)cx<<16)|dx; - Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * (double)ticks); - time/=100; - sec=(uint8_t)((Bitu)time % 60); // seconds - time/=60; - min=(uint8_t)((Bitu)time % 60); // minutes - time/=60; - hour=(uint8_t)((Bitu)time % 24); // hours - char format[11]; - sprintf(format,"%u%c%02u%c%02u",hour,c,min,c,sec); - WriteOut("%s\n",format); - first_shell->SetEnv("CONFIG",format); - } else if (!strcasecmp(pvars[0].c_str(), "lastmount")) { - if (lastmount) WriteOut("%c:\n",lastmount); - first_shell->SetEnv("CONFIG",lastmount?(std::string(1, lastmount) + ":").c_str():""); - } else - WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); - return; - } - // it's a property name - std::string val = sec->GetPropValue(pvars[0].c_str()); - WriteOut("%s\n",val.c_str()); - first_shell->SetEnv("CONFIG",val.c_str()); - } - break; - } - case 2: { - // section + property - sec = control->GetSection(pvars[0].c_str()); - if (!sec) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SECTION_ERROR"), pvars[0].c_str()); - return; - } - std::string val = sec->GetPropValue(pvars[1].c_str()); - if (val == NO_SUCH_PROPERTY) { - if (!strcasecmp(pvars[0].c_str(), "config") && (!strcasecmp(pvars[1].c_str(), "set") || !strcasecmp(pvars[1].c_str(), "device") || !strcasecmp(pvars[1].c_str(), "devicehigh") || !strcasecmp(pvars[1].c_str(), "install") || !strcasecmp(pvars[1].c_str(), "installhigh"))) { - Section_prop* psec = dynamic_cast (sec); - const char * extra = psec->data.c_str(); - if (extra&&strlen(extra)) { - std::istringstream in(extra); - char linestr[CROSS_LEN+1], cmdstr[CROSS_LEN], valstr[CROSS_LEN]; - char *cmd=cmdstr, *val=valstr, /**lin=linestr,*/ *p; - if (in) for (std::string line; std::getline(in, line); ) { - if (line.length()>CROSS_LEN) { - strncpy(linestr, line.c_str(), CROSS_LEN); - linestr[CROSS_LEN]=0; - } else - strcpy(linestr, line.c_str()); - p=strchr(linestr, '='); - if (p!=NULL) { - *p=0; - strcpy(cmd, linestr); - cmd=trim(cmd); - strcpy(val, p+1); - val=trim(val); - lowcase(cmd); - if (!strncasecmp(cmd, "set ", 4)&&!strcasecmp(pvars[1].c_str(), "set")) - WriteOut("%s=%s\n", trim(cmd+4), val); - else if(!strcasecmp(cmd, pvars[1].c_str())) - WriteOut("%s\n", val); - } - } - } - } else - WriteOut(MSG_Get("PROGRAM_CONFIG_NO_PROPERTY"), pvars[1].c_str(),pvars[0].c_str()); - return; - } - WriteOut("%s\n",val.c_str()); - first_shell->SetEnv("CONFIG",val.c_str()); - break; - } - default: - WriteOut(MSG_Get("PROGRAM_CONFIG_GET_SYNTAX")); - return; - } - return; - } - case P_SETPROP: case P_SETFORCE: { - // Code for the configuration changes - // Official format: config -set "section property=value" - // Accepted: with or without -set, - // "section property=value" - // "property" "value" - // "section" "property=value" - // "section" "property=value" "value" "value" ... - // "section" "property" "value" - // "section" "property" "value" "value" ... - // "section property" "value" "value" ... - // "property" "value" "value" ... - // "property=value" "value" "value" ... - - if (pvars.size()==0) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX")); - return; - } - - // add rest of command - std::string rest; - if (cmd->GetStringRemain(rest)) pvars.push_back(rest); - - Section* sec = control->GetSectionFromProperty(pvars[0].c_str()); - // attempt to split off the first word - std::string::size_type spcpos = pvars[0].find_first_of(' '); - if (spcpos>1&&pvars[0].c_str()[spcpos-1]==',') - spcpos=pvars[0].find_first_of(' ', spcpos+1); - - std::string::size_type equpos = pvars[0].find_first_of('='); - if (equpos != std::string::npos) { - std::string p = pvars[0]; - p.erase(equpos); - sec = control->GetSectionFromProperty(p.c_str()); - } - - uselangcp = false; - if ((equpos != std::string::npos) && - ((spcpos == std::string::npos) || (equpos < spcpos) || sec)) { - // If we have a '=' possibly before a ' ' split on the = - pvars.insert(pvars.begin()+1,pvars[0].substr(equpos+1)); - pvars[0].erase(equpos); - // As we had a = the first thing must be a property now - sec=control->GetSectionFromProperty(pvars[0].c_str()); - if (!sec&&pvars[0].size()>4&&!strcasecmp(pvars[0].substr(0, 4).c_str(), "ttf.")) { - pvars[0].erase(0,4); - sec = control->GetSectionFromProperty(pvars[0].c_str()); - } else if (!sec && pvars[0].size() && !strcasecmp(pvars[0].c_str(), "langcp")) { - pvars[0] = "language"; - sec = control->GetSectionFromProperty(pvars[0].c_str()); - if (sec) uselangcp = true; - } - if (sec) pvars.insert(pvars.begin(),std::string(sec->GetName())); - else { - WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); - uselangcp = false; - return; - } - // order in the vector should be ok now - } else { - if (equpos != std::string::npos && spcpos < equpos) { - // ' ' before a possible '=', split on the ' ' - pvars.insert(pvars.begin()+1,pvars[0].substr(spcpos+1)); - pvars[0].erase(spcpos); - } - // check if the first parameter is a section or property - sec = control->GetSection(pvars[0].c_str()); - if (!sec) { - // not a section: little duplicate from above - sec=control->GetSectionFromProperty(pvars[0].c_str()); - if (sec) pvars.insert(pvars.begin(),std::string(sec->GetName())); - else { - WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); - return; - } - } else { - // first of pvars is most likely a section, but could still be gus - // have a look at the second parameter - if (pvars.size() < 2) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX")); - return; - } - std::string::size_type equpos2 = pvars[1].find_first_of('='); - if (equpos2 != std::string::npos) { - // split on the = - pvars.insert(pvars.begin()+2,pvars[1].substr(equpos2+1)); - pvars[1].erase(equpos2); - } - // is this a property? - Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str()); - if (!sec2) { - // not a property, - Section* sec3 = control->GetSectionFromProperty(pvars[0].c_str()); - if (sec3 && !(equpos != std::string::npos && spcpos != std::string::npos && equpos > spcpos)) { - // section and property name are identical - pvars.insert(pvars.begin(),pvars[0]); - } // else has been checked above already - } - } - } - if(pvars.size() < 3) { - WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX")); - uselangcp = false; - return; - } - // check if the property actually exists in the section - Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str()); - if (!sec2) { - if (!strcasecmp(pvars[0].c_str(), "config") && (!strcasecmp(pvars[1].c_str(), "set") || !strcasecmp(pvars[1].c_str(), "device") || !strcasecmp(pvars[1].c_str(), "devicehigh") || !strcasecmp(pvars[1].c_str(), "install") || !strcasecmp(pvars[1].c_str(), "installhigh"))) - WriteOut("Cannot set property %s in section %s.\n", pvars[1].c_str(),pvars[0].c_str()); - else - WriteOut(MSG_Get("PROGRAM_CONFIG_NO_PROPERTY"), pvars[1].c_str(),pvars[0].c_str()); - uselangcp = false; - return; - } - bool applynew=false; - Property *p = static_cast(sec2)->Get_prop(pvars[1]); - if ((p==NULL||p->getChange()==Property::Changeable::OnlyAtStart)&&presult!=P_SETFORCE) { - WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_NOCHANGE")); -first_1: - WriteOut(MSG_Get("PROGRAM_CONFIG_APPLY_RESTART")); -first_2: - uint8_t c;uint16_t n=1; - DOS_ReadFile (STDIN,&c,&n); - do switch (c) { - case 'n': case 'N': - { - DOS_WriteFile (STDOUT,&c, &n); - DOS_ReadFile (STDIN,&c,&n); - do switch (c) { - case 0xD: WriteOut("\n");goto next; - case 0x03: goto next; - case 0x08: WriteOut("\b \b"); goto first_2; - } while (DOS_ReadFile (STDIN,&c,&n)); - } - case 'y': case 'Y': - { - DOS_WriteFile (STDOUT,&c, &n); - DOS_ReadFile (STDIN,&c,&n); - do switch (c) { - case 0xD: WriteOut("\n"); applynew = true; goto next; - case 0x03: goto next; - case 0x08: WriteOut("\b \b"); goto first_2; - } while (DOS_ReadFile (STDIN,&c,&n)); - } - case 0xD: WriteOut("\n"); goto first_1; - case 0x03: goto next; - case '\t': - case 0x08: - goto first_2; - default: - { - DOS_WriteFile (STDOUT,&c, &n); - DOS_ReadFile (STDIN,&c,&n); - do switch (c) { - case 0xD: WriteOut("\n"); goto first_1; - case 0x03: goto next; - case 0x08: WriteOut("\b \b"); goto first_2; - } while (DOS_ReadFile (STDIN,&c,&n)); - goto first_2; - } - } while (DOS_ReadFile (STDIN,&c,&n)); - } -next: - // Input has been parsed (pvar[0]=section, [1]=property, [2]=value) - // now execute - Section* tsec = control->GetSection(pvars[0]); - std::string value(pvars[2]); - //Due to parsing there can be a = at the start of value. - while (value.size() && (value.at(0) ==' ' ||value.at(0) =='=') ) value.erase(0,1); - for(Bitu i = 3; i < pvars.size(); i++) value += (std::string(" ") + pvars[i]); - std::string inputline = pvars[1] + "=" + value; - bool change_success = tsec->HandleInputline(inputline.c_str()); - if (change_success) { - if (applynew) RebootLanguage(""); - else ApplySetting(pvars[0], inputline, false); - } else WriteOut(MSG_Get("PROGRAM_CONFIG_VALUE_ERROR"), - value.c_str(),pvars[1].c_str()); - uselangcp = false; - return; - } - case P_WRITELANG: case P_WRITELANG2: - // In secure mode don't allow a new languagefile to be created - // Who knows which kind of file we would overwrite. - if (securemode_check()) return; - if (pvars.size() < 1) { - if (control->opt_lang == "") { - WriteOut(MSG_Get("PROGRAM_CONFIG_MISSINGPARAM")); - return; - } else if (!MSG_Write(control->opt_lang.c_str(), NULL)) { - WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_ERROR"),control->opt_lang.c_str()); - return; - } else - WriteOut(MSG_Get("PROGRAM_LANGUAGE_FILE_WHICH"),control->opt_lang.c_str()); - } else if (!MSG_Write(pvars[0].c_str(), NULL)) { - WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_ERROR"),pvars[0].c_str()); - return; - } else - WriteOut(MSG_Get("PROGRAM_LANGUAGE_FILE_WHICH"),pvars[0].c_str()); - break; - - case P_SECURE: - // Code for switching to secure mode - control->SwitchToSecureMode(); - WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_ON")); - return; - - default: - E_Exit("bug"); - break; - } - first = false; - } - return; -} - -void CONFIG_ProgramStart(Program * * make) { - *make=new CONFIG; -} - -void PROGRAMS_DOS_Boot(Section *) { -} - -/* FIXME: Rename the function to clarify it does not init programs, it inits the callback mechanism - * that program generation on drive Z: needs to tie a .COM executable to a callback */ -void PROGRAMS_Init() { - LOG(LOG_MISC,LOG_DEBUG)("PROGRAMS_Init(): initializing Z: drive .COM stub and program management"); - - /* Setup a special callback to start virtual programs */ - call_program=CALLBACK_Allocate(); - CALLBACK_Setup(call_program,&PROGRAMS_Handler,CB_RETF,"internal program"); - - AddVMEventFunction(VM_EVENT_DOS_INIT_KERNEL_READY,AddVMEventFunctionFuncPair(PROGRAMS_DOS_Boot)); - - // listconf - MSG_Add("PROGRAM_CONFIG_NOCONFIGFILE","No config file loaded!\n"); - MSG_Add("PROGRAM_CONFIG_PRIMARY_CONF","Primary config file: \n%s\n"); - MSG_Add("PROGRAM_CONFIG_ADDITIONAL_CONF","Additional config files:\n"); - MSG_Add("PROGRAM_CONFIG_GLOBAL_CONF","\nGlobal config file: \n%s\n"); - MSG_Add("PROGRAM_CONFIG_CONFDIR","DOSBox-X %s user configuration directory: \n%s\n\n"); - MSG_Add("PROGRAM_CONFIG_WORKDIR","DOSBox-X's working directory: \n%s\n\n"); - - // writeconf - MSG_Add("PROGRAM_CONFIG_FILE_ERROR","\nCan't open file %s\n"); - MSG_Add("PROGRAM_CONFIG_FILE_WHICH","Writing config file %s\n"); - MSG_Add("PROGRAM_LANGUAGE_FILE_WHICH","Written to language file %s\n"); - - // help - MSG_Add("PROGRAM_CONFIG_USAGE","The DOSBox-X command-line configuration utility. Supported options:\n"\ - "-wc (or -writeconf) without parameter: Writes to primary loaded config file.\n"\ - "-wc (or -writeconf) with filename: Writes file to the config directory.\n"\ - "-wl (or -writelang) with filename: Writes the current language strings.\n"\ - "-ln (or -langname) Displays (without arguments) or specifies the language name.\n"\ - "-wcp [filename] Writes file to program directory (dosbox-x.conf or filename).\n"\ - "-wcd Writes to the default config file in the config directory.\n"\ - "-all, -mod Use with -wc, -wcp, or -wcd to write ALL or only modified options.\n"\ - "-wcboot, -wcpboot, or -wcdboot will reboot DOSBox-X after writing the file.\n"\ - "-bootconf (or -bc) reboots with specified config file (or primary loaded file).\n"\ - "-norem Use this with -wc, -wcp, or -wcd to not write config option remarks.\n"\ - "-l Lists DOSBox-X's configuration parameters.\n"\ - "-h, -help, -? Shows this help; add the word \"sections\" for a list of sections.\n"\ - "-h, -help, -? section / property Shows info on a specific section or property.\n"\ - "-axclear Clears the [autoexec] section.\n"\ - "-axadd [line] Adds a line to the [autoexec] section.\n"\ - "-axtype Prints the content of the [autoexec] section.\n"\ - "-avistart, -avistop Starts or stops AVI recording.\n"\ - "-securemode Enables secure mode where features like mounting will be disabled.\n"\ - "-startmapper Starts the DOSBox-X mapper editor.\n"\ - "-gui Starts the graphical configuration tool.\n" - "-get \"section property\" returns the value of the property (also to %%CONFIG%%).\n"\ - "-set (-setf for force) \"section property=value\" sets the value of the property.\n"); - MSG_Add("PROGRAM_CONFIG_HLP_PROPHLP","Purpose of property \"%s\" (contained in section \"%s\"):\n%s\n\nPossible Values: %s\nDefault value: %s\nCurrent value: %s\n"); - MSG_Add("PROGRAM_CONFIG_HLP_LINEHLP","Purpose of section \"%s\":\n%s\nCurrent value:\n%s\n"); - MSG_Add("PROGRAM_CONFIG_HLP_NOCHANGE","This property cannot be changed at runtime.\n"); - MSG_Add("PROGRAM_CONFIG_APPLY_RESTART","Do you want to restart now to apply the setting [Y/N]?"); - MSG_Add("PROGRAM_CONFIG_HLP_POSINT","positive integer"); - MSG_Add("PROGRAM_CONFIG_HLP_SECTHLP","Section %s contains the following properties:\n"); - MSG_Add("PROGRAM_CONFIG_HLP_SECTLIST","DOSBox-X configuration contains the following sections:\n\n"); - - MSG_Add("PROGRAM_CONFIG_SECURE_ON","Switched to secure mode.\n"); - MSG_Add("PROGRAM_CONFIG_SECURE_DISALLOW","This operation is not permitted in secure mode.\n"); - MSG_Add("PROGRAM_CONFIG_SECTION_ERROR","Section %s doesn't exist.\n"); - MSG_Add("PROGRAM_CONFIG_VALUE_ERROR","\"%s\" is not a valid value for property %s.\n"); - MSG_Add("PROGRAM_CONFIG_PROPERTY_ERROR","No such section or property.\n"); - MSG_Add("PROGRAM_CONFIG_PROPERTY_DUPLICATE","There may be other sections with the same property name.\n"); - MSG_Add("PROGRAM_CONFIG_NO_PROPERTY","There is no property %s in section %s.\n"); - MSG_Add("PROGRAM_CONFIG_SET_SYNTAX","Correct syntax: config -set \"section property=value\".\n"); - MSG_Add("PROGRAM_CONFIG_GET_SYNTAX","Correct syntax: config -get \"section property\".\n"); - MSG_Add("PROGRAM_CONFIG_PRINT_STARTUP","\nDOSBox-X was started with the following command line parameters:\n%s\n"); - MSG_Add("PROGRAM_CONFIG_MISSINGPARAM","Missing parameter.\n"); -} + #include + #include + #include + #include + #include + #include + #include + #include + #include + + #include "programs.h" + #include "callback.h" + #include "logging.h" + #include "regs.h" + #include "support.h" + #include "cross.h" + #include "control.h" + #include "shell.h" + #include "menudef.h" + #include "hardware.h" + #include "mapper.h" + #include "menu.h" + #include "bios.h" + #include "timer.h" + #include "jfont.h" + #include "render.h" + #include "../ints/int10.h" + #include "sdlmain.h" + #if defined(WIN32) + #include "windows.h" + RECT monrect; + int curscreen; + #endif + + #include + #include + + Bitu call_program; + extern char lastmount; + extern const char *modifier; + extern unsigned int sendkeymap; + extern std::string langname, configfile, dosbox_title; + extern int autofixwarn, enablelfn, fat32setver, paste_speed, wheel_key, freesizecap, wpType, wpVersion, wpBG, wpFG, lastset, blinkCursor, msgcodepage; + extern bool dos_kernel_disabled, force_nocachedir, wpcolon, convertimg, lockmount, enable_config_as_shell_commands, lesssize, load, winrun, winautorun, startcmd, startwait, startquiet, starttranspath, mountwarning, wheel_guest, clipboard_dosapi, noremark_save_state, force_load_state, sync_time, manualtime, ttfswitch, loadlang, showbold, showital, showline, showsout, char512, printfont, rtl, gbk, chinasea, uao, showdbcs, dbcs_sbcs, autoboxdraw, halfwidthkana, ticksLocked, outcon, enable_dbcs_tables, show_recorded_filename, internal_program, pipetmpdev, notrysgf, uselangcp, incall; + + /* This registers a file on the virtual drive and creates the correct structure for it*/ + + static uint8_t exe_block[]={ + 0xbc,0x00,0x04, //0x100 MOV SP,0x400 decrease stack size + 0xbb,0x40,0x00, //0x103 MOV BX,0x0040 for memory resize + 0xb4,0x4a, //0x106 MOV AH,0x4A Resize memory block + 0xcd,0x21, //0x108 INT 0x21 ... + 0x30,0xc0, //0x10A XOR AL,AL Clear AL (exit code). Program will write AL to modify exit status + //pos 14 is callback number + 0xFE,0x38,0x00,0x00, //0x10C CALLBack number + 0xb4,0x4c, //0x110 Mov AH,0x4C Prepare to exit, preserve AL + 0xcd,0x21 //0x112 INT 0x21 Exit to DOS + }; //0x114 --DONE-- + + #define CB_POS 14 + + class InternalProgramEntry { + public: + InternalProgramEntry() { + main = NULL; + comsize = 0; + comdata = NULL; + } + ~InternalProgramEntry() { + if (comdata != NULL) free(comdata); + comdata = NULL; + comsize = 0; + main = NULL; + } + public: + std::string name; + uint8_t* comdata; + uint32_t comsize; + PROGRAMS_Main* main; + }; + + static std::vector internal_progs; + uint8_t DOS_GetAnsiAttr(void); + int setTTFMap(bool changecp); + char *FormatDate(uint16_t year, uint8_t month, uint8_t day); + bool isDBCSCP(void), CheckBoxDrawing(uint8_t c1, uint8_t c2, uint8_t c3, uint8_t c4), DOS_SetAnsiAttr(uint8_t attr), GFX_GetPreventFullscreen(void), toOutput(const char *what); + void EMS_DoShutDown(void), UpdateDefaultPrinterFont(void), GFX_ForceRedrawScreen(void), resetFontSize(void), ttf_reset_colors(void), makestdcp950table(void), makeseacp951table(void), clearFontCache(void), DOSBox_SetSysMenu(void), MSG_Init(void), initRand(void), PRINTER_Init(void), SetKEYBCP(void); + void EMS_Startup(Section* sec), DOSV_SetConfig(Section_prop *section), DOSBOX_UnlockSpeed2(bool pressed), RebootLanguage(std::string filename, bool confirm=false), SetWindowTransparency(int trans), SetOutputSwitch(const char *outputstr), runRescan(const char *str), runSerial(const char *str), runParallel(const char *str), DOS_AddDays(uint8_t days), PRINTER_Shutdown(Section* sec), setAspectRatio(Section_prop * section); + + void PROGRAMS_Shutdown(void) { + LOG(LOG_MISC,LOG_DEBUG)("Shutting down internal programs list"); + + for (size_t i=0;i < internal_progs.size();i++) { + if (internal_progs[i] != NULL) { + delete internal_progs[i]; + internal_progs[i] = NULL; + } + } + internal_progs.clear(); + } + + void PROGRAMS_MakeFile(char const * const name,PROGRAMS_Main * main,const char *dir) { + uint32_t size=sizeof(exe_block)+sizeof(uint8_t); + InternalProgramEntry *ipe; + uint8_t *comdata; + uint8_t index; + + /* Copy save the pointer in the vector and save its index */ + if (internal_progs.size()>255) E_Exit("PROGRAMS_MakeFile program size too large (%d)",static_cast(internal_progs.size())); + + index = (uint8_t)internal_progs.size(); + comdata = (uint8_t *)malloc(32); //MEM LEAK + memcpy(comdata,&exe_block,sizeof(exe_block)); + memcpy(&comdata[sizeof(exe_block)],&index,sizeof(index)); + comdata[CB_POS]=(uint8_t)(call_program&0xff); + comdata[CB_POS+1]=(uint8_t)((call_program>>8)&0xff); + + ipe = new InternalProgramEntry(); + ipe->main = main; + ipe->name = name; + ipe->comsize = size; + ipe->comdata = comdata; + internal_progs.push_back(ipe); + internal_program = true; + VFILE_Register(name,ipe->comdata,ipe->comsize,dir); + internal_program = false; + } + + static Bitu PROGRAMS_Handler(void) { + /* This sets up everything for a program start up call */ + Bitu size=sizeof(uint8_t); + uint8_t index; + /* Read the index from program code in memory */ + PhysPt reader=PhysMake(dos.psp(),256+sizeof(exe_block)); + HostPt writer=(HostPt)&index; + for (;size>0;size--) *writer++=mem_readb(reader++); + Program * new_program = NULL; + if (index >= internal_progs.size()) E_Exit("something is messing with the memory"); + InternalProgramEntry *ipe = internal_progs[index]; + if (ipe == NULL) E_Exit("Attempt to run internal program slot with nothing allocated"); + if (ipe->main == NULL) return CBRET_NONE; + PROGRAMS_Main * handler = internal_progs[index]->main; + (*handler)(&new_program); + + try { /* "BOOT" can throw an exception (int(2)) */ + new_program->Run(); + delete new_program; + } + catch (...) { /* well if it happened, free the program anyway to avert memory leaks */ + delete new_program; + throw; /* pass it on */ + } + + return CBRET_NONE; + } + + /* Main functions used in all program */ + + Program::Program() { + /* Find the command line and setup the PSP */ + psp = new DOS_PSP(dos.psp()); + /* Scan environment for filename */ + PhysPt envscan=PhysMake(psp->GetEnvironment(),0); + while (mem_readb(envscan)) envscan+=(PhysPt)(mem_strlen(envscan)+1); + envscan+=3; + CommandTail tail; + MEM_BlockRead(PhysMake(dos.psp(),CTBUF+1),&tail,CTBUF+1); + if (tail.countSecureMode() ||*/ cmd->Get_arglength() > 100 && full_arguments.size()) { + CommandLine* temp = new CommandLine(cmd->GetFileName(),full_arguments.c_str()); + delete cmd; + cmd = temp; + } + full_arguments.assign(""); //Clear so it gets even more save + } + + bool resetcolor = false; + static char last_written_character = 0;//For 0xA to OxD 0xA expansion + void Program::WriteOut(const char * format,...) { + uint8_t attr = DOS_GetAnsiAttr(); + char buf[2048]; + va_list msg; + + va_start(msg,format); + vsnprintf(buf,2047,format,msg); + va_end(msg); + + // printf("%s", buf); + + uint16_t size = (uint16_t)strlen(buf); + dos.internal_output=true; + for(uint16_t i = 0; i < size;i++) { + uint8_t out;uint16_t s=1; + if (buf[i] == 0xA && last_written_character != 0xD) { + out = 0xD; + DOS_WriteFile(STDOUT,&out,&s); + } + last_written_character = (char)(out = (uint8_t)buf[i]); + DOS_WriteFile(STDOUT,&out,&s); + } + dos.internal_output=false; + if (resetcolor && attr) DOS_SetAnsiAttr(attr); + resetcolor = false; + + // DOS_WriteFile(STDOUT,(uint8_t *)buf,&size); + } + + void Program::WriteOut(const char *format, const char *arguments) { + char buf[2048 + CMD_MAXLINE]; + sprintf(buf,format,arguments); + + // printf("%s", buf); + uint16_t size = (uint16_t)strlen(buf); + dos.internal_output=true; + for(uint16_t i = 0; i < size;i++) { + uint8_t out;uint16_t s=1; + if (buf[i] == 0xA && last_written_character != 0xD) { + out = 0xD;DOS_WriteFile(STDOUT,&out,&s); + } + last_written_character = (char)(out = (uint8_t)buf[i]); + DOS_WriteFile(STDOUT,&out,&s); + } + dos.internal_output=false; + + // DOS_WriteFile(STDOUT,(uint8_t *)buf,&size); + } + + int Program::WriteOut_NoParsing(const char * format, bool dbcs) { + uint16_t size = (uint16_t)strlen(format); + char const* buf = format; + char last2 = 0, last3 = 0; + int lastcol = 0, COLS=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + uint8_t page=outcon?real_readb(BIOSMEM_SEG,BIOSMEM_CURRENT_PAGE):0; + bool lead=false; + dos.internal_output=true; + int rcount = 0; + for(uint16_t i = 0; i < size;i++) { + uint8_t out;uint16_t s=1; + BIOS_NCOLS; + if (!CURSOR_POS_COL(page)) last2=last3=0; + if (lead) lead = false; + else if ((IS_PC98_ARCH || isDBCSCP()) + #if defined(USE_TTF) + && dbcs_sbcs + #endif + && dbcs && isKanji1(buf[i])) lead = true; + if (buf[i] == 0xA) { + if (last_written_character != 0xD) {out = 0xD;DOS_WriteFile(STDOUT,&out,&s);} + if (outcon) rcount++; + } else if (outcon && lead && CURSOR_POS_COL(page)==COLS-1 && !(TTF_using() + #if defined(USE_TTF) + && autoboxdraw + #endif + && CheckBoxDrawing(last3, last2, last_written_character, buf[i]))) { + out = 0xD;DOS_WriteFile(STDOUT,&out,&s); + out = 0xA;DOS_WriteFile(STDOUT,&out,&s); + rcount++; + } else if (outcon && !CURSOR_POS_COL(page) && lastcol == COLS-1) + rcount++; + lastcol=CURSOR_POS_COL(page); + last3=last2;last2=last_written_character; + last_written_character = (char)(out = (uint8_t)buf[i]); + DOS_WriteFile(STDOUT,&out,&s); + } + dos.internal_output=false; + return rcount; + + // DOS_WriteFile(STDOUT,(uint8_t *)format,&size); + } + + static bool LocateEnvironmentBlock(PhysPt &env_base,PhysPt &env_fence,Bitu env_seg) { + if (env_seg == 0) { + /* The DOS program might have freed it's environment block perhaps. */ + return false; + } + + DOS_MCB env_mcb((uint16_t)(env_seg-1)); /* read the environment block's MCB to determine how large it is */ + env_base = PhysMake((uint16_t)env_seg,0); + env_fence = env_base + (PhysPt)(env_mcb.GetSize() << 4u); + return true; + } + + int EnvPhys_StrCmp(PhysPt es,PhysPt ef,const char *ls) { + (void)ef;//UNUSED + while (1) { + unsigned char a = mem_readb(es++); + unsigned char b = (unsigned char)(*ls++); + if (a == '=') a = 0; + if (a == 0 && b == 0) break; + if (a == b) continue; + return (int)a - (int)b; + } + + return 0; + } + + void EnvPhys_StrCpyToCPPString(std::string &result,PhysPt &env_scan,PhysPt env_fence) { + char tmp[512],*w=tmp,*wf=tmp+sizeof(tmp)-1; + + result.clear(); + while (env_scan < env_fence) { + char c; + if ((c=(char)mem_readb(env_scan++)) == 0) break; + + if (w >= wf) { + *w = 0; + result += tmp; + w = tmp; + } + + assert(w < wf); + *w++ = c; + } + if (w != tmp) { + *w = 0; + result += tmp; + } + } + + bool EnvPhys_ScanUntilNextString(PhysPt &env_scan,PhysPt env_fence) { + /* scan until end of block or NUL */ + while (env_scan < env_fence && mem_readb(env_scan) != 0) env_scan++; + + /* if we hit the fence, that's something to warn about. */ + if (env_scan >= env_fence) { + LOG_MSG("Warning: environment string scan hit the end of the environment block without terminating NUL\n"); + return false; + } + + /* if we stopped at anything other than a NUL, that's something to warn about */ + if (mem_readb(env_scan) != 0) { + LOG_MSG("Warning: environment string scan scan stopped without hitting NUL\n"); + return false; + } + + env_scan++; /* skip NUL */ + return true; + } + + bool Program::GetEnvStr(const char * entry,std::string & result) { + PhysPt env_base,env_fence,env_scan; + + if (dos_kernel_disabled) { + LOG_MSG("BUG: Program::GetEnvNum() called with DOS kernel disabled (such as OS boot).\n"); + return false; + } + + if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { + LOG_MSG("Warning: GetEnvCount() was not able to locate the program's environment block\n"); + return false; + } + + std::string bigentry(entry); + for (std::string::iterator it = bigentry.begin(); it != bigentry.end(); ++it) *it = toupper(*it); + + env_scan = env_base; + while (env_scan < env_fence) { + /* "NAME" + "=" + "VALUE" + "\0" */ + /* end of the block is a NULL string meaning a \0 follows the last string's \0 */ + if (mem_readb(env_scan) == 0) break; /* normal end of block */ + + if (EnvPhys_StrCmp(env_scan,env_fence,bigentry.c_str()) == 0) { + EnvPhys_StrCpyToCPPString(result,env_scan,env_fence); + return true; + } + + if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; + } + + return false; + } + + bool Program::GetEnvNum(Bitu want_num,std::string & result) { + PhysPt env_base,env_fence,env_scan; + Bitu num = 0; + + if (dos_kernel_disabled) { + LOG_MSG("BUG: Program::GetEnvNum() called with DOS kernel disabled (such as OS boot).\n"); + return false; + } + + if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { + LOG_MSG("Warning: GetEnvCount() was not able to locate the program's environment block\n"); + return false; + } + + result.clear(); + env_scan = env_base; + while (env_scan < env_fence) { + /* "NAME" + "=" + "VALUE" + "\0" */ + /* end of the block is a NULL string meaning a \0 follows the last string's \0 */ + if (mem_readb(env_scan) == 0) break; /* normal end of block */ + + if (num == want_num) { + EnvPhys_StrCpyToCPPString(result,env_scan,env_fence); + return true; + } + + num++; + if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; + } + + return false; + } + + Bitu Program::GetEnvCount(void) { + PhysPt env_base,env_fence,env_scan; + Bitu num = 0; + + if (dos_kernel_disabled) { + LOG_MSG("BUG: Program::GetEnvCount() called with DOS kernel disabled (such as OS boot).\n"); + return 0; + } + + if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { + LOG_MSG("Warning: GetEnvCount() was not able to locate the program's environment block\n"); + return false; + } + + env_scan = env_base; + while (env_scan < env_fence) { + /* "NAME" + "=" + "VALUE" + "\0" */ + /* end of the block is a NULL string meaning a \0 follows the last string's \0 */ + if (mem_readb(env_scan++) == 0) break; /* normal end of block */ + num++; + if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; + } + + return num; + } + + void Program::DebugDumpEnv() { + PhysPt env_base,env_fence,env_scan; + unsigned char c; + std::string tmp; + + if (dos_kernel_disabled) + return; + + if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) + return; + + env_scan = env_base; + LOG_MSG("DebugDumpEnv()"); + while (env_scan < env_fence) { + if (mem_readb(env_scan) == 0) break; + + while (env_scan < env_fence) { + if ((c=mem_readb(env_scan++)) == 0) break; + tmp += (char)c; + } + + LOG_MSG("...%s",tmp.c_str()); + tmp = ""; + } + } + + bool Program::FirstEnv(const char * entry) { + PhysPt env_base,env_fence,env_scan,env_first,env_last; + bool found = false; + + if (dos_kernel_disabled) { + LOG_MSG("BUG: Program::FirstEnv() called with DOS kernel disabled (such as OS boot).\n"); + return false; + } + + if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { + LOG_MSG("Warning: GetEnvCount() was not able to locate the program's environment block\n"); + return false; + } + + std::string bigentry(entry); + for (std::string::iterator it = bigentry.begin(); it != bigentry.end(); ++it) *it = toupper(*it); + + env_scan = env_base; + while (env_scan < env_fence) { + /* "NAME" + "=" + "VALUE" + "\0" */ + /* end of the block is a NULL string meaning a \0 follows the last string's \0 */ + if (mem_readb(env_scan) == 0) break; /* normal end of block */ + + if (EnvPhys_StrCmp(env_scan,env_fence,bigentry.c_str()) == 0) { + found = true; + break; + } + + if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; + } + + if (found) { + env_first = env_scan; + if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) return false; + env_last = env_scan; + + #if 0//DEBUG + fprintf(stderr,"Env base=%x fence=%x first=%x last=%x\n", + (unsigned int)env_base, (unsigned int)env_fence, + (unsigned int)env_first, (unsigned int)env_last); + #endif + + assert(env_first <= env_last); + + /* if the variable is already at the beginning, do nothing */ + if (env_first == env_base) return true; + + { + std::vector tmp; + tmp.resize(size_t(env_last-env_first)); + + /* save variable */ + for (size_t i=0;i < tmp.size();i++) + tmp[i] = mem_readb(env_first+(PhysPt)i); + + /* shift all variables prior to it forward over the variable, BACKWARDS */ + const size_t pl = size_t(env_first - env_base); + assert((env_first-pl) == env_base); + assert((env_last-pl) >= env_base); + assert(env_first < env_last); + assert(pl != 0); + for (size_t i=0;i < pl;i++) mem_writeb(env_last-(i+1), mem_readb(env_first-(i+1))); + + /* put the variable in at the beginning */ + assert((env_base+tmp.size()) == (env_last-pl)); + for (size_t i=0;i < tmp.size();i++) + mem_writeb(env_base+(PhysPt)i,tmp[i]); + } + } + + return true; + } + + bool Program::EraseEnv(void) { + PhysPt env_base,env_fence; + size_t nsl = 0,el = 0,needs; + + if (dos_kernel_disabled) { + LOG_MSG("BUG: Program::EraseEnv() called with DOS kernel disabled (such as OS boot).\n"); + return false; + } + + if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { + LOG_MSG("Warning: SetEnv() was not able to locate the program's environment block\n"); + return false; + } + + for (PhysPt w=env_base;w < env_fence;w++) + mem_writeb(w,0); + + return true; + } + + /* NTS: "entry" string must have already been converted to uppercase */ + bool Program::SetEnv(const char * entry,const char * new_string) { + PhysPt env_base,env_fence,env_scan; + size_t nsl = 0,el = 0,needs; + + if (dos_kernel_disabled) { + LOG_MSG("BUG: Program::SetEnv() called with DOS kernel disabled (such as OS boot).\n"); + return false; + } + + if (!LocateEnvironmentBlock(env_base,env_fence,psp->GetEnvironment())) { + LOG_MSG("Warning: SetEnv() was not able to locate the program's environment block\n"); + return false; + } + + std::string bigentry(entry); + for (std::string::iterator it = bigentry.begin(); it != bigentry.end(); ++it) *it = toupper(*it); + + el = strlen(bigentry.c_str()); + if (*new_string != 0) nsl = strlen(new_string); + needs = nsl+1+el+1+1; /* entry + '=' + new_string + '\0' + '\0' */ + + /* look for the variable in the block. break the loop if found */ + env_scan = env_base; + while (env_scan < env_fence) { + if (mem_readb(env_scan) == 0) break; + + if (EnvPhys_StrCmp(env_scan,env_fence,bigentry.c_str()) == 0) { + /* found it. remove by shifting the rest of the environment block over */ + int zeroes=0; + PhysPt s,d; + + /* before we remove it: is there room for the new value? */ + if (nsl != 0) { + if ((env_scan+needs) > env_fence) { + LOG_MSG("Program::SetEnv() error, insufficient room for environment variable %s=%s (replacement)\n",bigentry.c_str(),new_string); + DebugDumpEnv(); + return false; + } + } + + s = env_scan; d = env_scan; + while (s < env_fence && mem_readb(s) != 0) s++; + if (s < env_fence && mem_readb(s) == 0) s++; + + while (s < env_fence) { + unsigned char b = mem_readb(s++); + + if (b == 0) zeroes++; + else zeroes=0; + + mem_writeb(d++,b); + if (zeroes >= 2) break; /* two consecutive zeros means the end of the block */ + } + } + else { + /* scan to next string */ + if (!EnvPhys_ScanUntilNextString(env_scan,env_fence)) break; + } + } + + /* At this point, env_scan points to the first byte beyond the block */ + /* add the string to the end of the block */ + if (*new_string != 0) { + if ((env_scan+needs) > env_fence) { + LOG_MSG("Program::SetEnv() error, insufficient room for environment variable %s=%s (addition)\n",bigentry.c_str(),new_string); + DebugDumpEnv(); + return false; + } + + assert(env_scan < env_fence); + for (const char *s=bigentry.c_str();*s != 0;) mem_writeb(env_scan++,(uint8_t)(*s++)); + mem_writeb(env_scan++,'='); + + assert(env_scan < env_fence); + for (const char *s=new_string;*s != 0;) mem_writeb(env_scan++,(uint8_t)(*s++)); + mem_writeb(env_scan++,0); + mem_writeb(env_scan++,0); + + assert(env_scan <= env_fence); + } + + return true; + } + + bool MSG_Write(const char *, const char *); + + /*! \brief CONFIG.COM utility to control configuration and files + * + * \description Utility to write configuration, set configuration, + * and other configuration related functions. + */ + class CONFIG : public Program { + public: + /*! \brief Program entry point, when the command is run + */ + void Run(void) override; + private: + void restart(const char* useconfig); + + void writeconf(std::string name, bool configdir,int everything, bool norem) { + // "config -wcd" should write to the config directory + if (configdir) { + // write file to the default config directory + std::string config_path; + Cross::GetPlatformConfigDir(config_path); + struct stat info; + if (!stat(config_path.c_str(), &info) || !(info.st_mode & S_IFDIR)) { + #ifdef WIN32 + CreateDirectory(config_path.c_str(), NULL); + #else + mkdir(config_path.c_str(), 0755); + #endif + } + name = config_path + name; + } + WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_WHICH"),name.c_str()); + if (!control->PrintConfig(name.c_str(),everything,norem)) { + WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_ERROR"),name.c_str()); + } + return; + } + + bool securemode_check() { + if (control->SecureMode()) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_DISALLOW")); + return true; + } + return false; + } + }; + + void dos_ver_menu(bool start), ReloadMapper(Section_prop *sec, bool init), SetGameState_Run(int value), update_dos_ems_menu(void), MountAllDrives(bool quiet), GFX_SwitchFullScreen(void), RebootConfig(std::string filename, bool confirm=false); + bool set_ver(char *s), GFX_IsFullscreen(void); + + void Load_Language(std::string name) { + if(control->opt_lang != "") control->opt_lang = name; + MSG_Init(); + #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU || DOSBOXMENU_TYPE == DOSBOXMENU_NSMENU + mainMenu.unbuild(); + mainMenu.rebuild(); + #endif + if (!GFX_GetPreventFullscreen()) { + if (menu.toggle) DOSBox_SetMenu(); else DOSBox_NoMenu(); + } + #if defined(USE_TTF) + if (TTF_using()) resetFontSize(); + #endif + #if 0 + if (!uselangcp && !incall) { + int oldmsgcp = msgcodepage; + msgcodepage = dos.loaded_codepage; + SetKEYBCP(); + msgcodepage = oldmsgcp; + } + #endif + } + + void ApplySetting(std::string pvar, std::string inputline, bool quiet) { + if (!strcasecmp(pvar.c_str(), "dosbox")||!strcasecmp(pvar.c_str(), "dos")||!strcasecmp(pvar.c_str(), "dosv")||!strcasecmp(pvar.c_str(), "cpu")||!strcasecmp(pvar.c_str(), "sdl")||!strcasecmp(pvar.c_str(), "ttf")||!strcasecmp(pvar.c_str(), "render")||!strcasecmp(pvar.c_str(), "serial")||!strcasecmp(pvar.c_str(), "parallel")||!strcasecmp(pvar.c_str(), "printer")) { + Section_prop *section = static_cast(control->GetSection(pvar.c_str())); + if (section != NULL) { + if (!strcasecmp(pvar.c_str(), "dosbox")) { + force_nocachedir = section->Get_bool("nocachedir"); + sync_time = section->Get_bool("synchronize time"); + if (!strcasecmp(inputline.substr(0, 17).c_str(), "synchronize time=")) { + manualtime=false; + mainMenu.get_item("sync_host_datetime").check(sync_time).refresh_item(mainMenu); + } + std::string freesizestr = section->Get_string("freesizecap"); + if (freesizestr == "fixed" || freesizestr == "false" || freesizestr == "0") freesizecap = 0; + else if (freesizestr == "relative" || freesizestr == "2") freesizecap = 2; + else freesizecap = 1; + convertimg = section->Get_bool("convertdrivefat"); + wpcolon = section->Get_bool("leading colon write protect image"); + lockmount = section->Get_bool("locking disk image mount"); + if (!strcasecmp(inputline.substr(0, 9).c_str(), "saveslot=")) SetGameState_Run(section->Get_int("saveslot")-1); + if (!strcasecmp(inputline.substr(0, 11).c_str(), "saveremark=")) { + noremark_save_state = !section->Get_bool("saveremark"); + mainMenu.get_item("noremark_savestate").check(noremark_save_state).refresh_item(mainMenu); + } + if (!strcasecmp(inputline.substr(0, 15).c_str(), "forceloadstate=")) { + force_load_state = section->Get_bool("forceloadstate"); + mainMenu.get_item("force_loadstate").check(force_load_state).refresh_item(mainMenu); + } + if (!strcasecmp(inputline.substr(0, 23).c_str(), "show recorded filename=")) + show_recorded_filename = section->Get_bool("show recorded filename"); + if (!strcasecmp(inputline.substr(0, 6).c_str(), "title=")) { + dosbox_title=section->Get_string("title"); + trim(dosbox_title); + } + if (!strcasecmp(inputline.substr(0, 9).c_str(), "language=")) + Load_Language(section->Get_string("language")); + if (!strcasecmp(inputline.substr(0, 16).c_str(), "mapper send key=")) { + std::string mapsendkey = section->Get_string("mapper send key"); + if (mapsendkey=="winlogo") sendkeymap=1; + else if (mapsendkey=="winmenu") sendkeymap=2; + else if (mapsendkey=="alttab") sendkeymap=3; + else if (mapsendkey=="ctrlesc") sendkeymap=4; + else if (mapsendkey=="ctrlbreak") sendkeymap=5; + else sendkeymap=0; + mainMenu.get_item("sendkey_mapper_winlogo").check(sendkeymap==1).refresh_item(mainMenu); + mainMenu.get_item("sendkey_mapper_winmenu").check(sendkeymap==2).refresh_item(mainMenu); + mainMenu.get_item("sendkey_mapper_alttab").check(sendkeymap==3).refresh_item(mainMenu); + mainMenu.get_item("sendkey_mapper_ctrlesc").check(sendkeymap==4).refresh_item(mainMenu); + mainMenu.get_item("sendkey_mapper_ctrlbreak").check(sendkeymap==5).refresh_item(mainMenu); + mainMenu.get_item("sendkey_mapper_cad").check(!sendkeymap).refresh_item(mainMenu); + } + } else if (!strcasecmp(pvar.c_str(), "sdl")) { + modifier = section->Get_string("clip_key_modifier"); + paste_speed = section->Get_int("clip_paste_speed"); + if (!strcasecmp(inputline.substr(0, 16).c_str(), "mouse_wheel_key=")) { + wheel_key = section->Get_int("mouse_wheel_key"); + wheel_guest=wheel_key>0; + if (wheel_key<0) wheel_key=-wheel_key; + mainMenu.get_item("wheel_updown").check(wheel_key==1).refresh_item(mainMenu); + mainMenu.get_item("wheel_leftright").check(wheel_key==2).refresh_item(mainMenu); + mainMenu.get_item("wheel_pageupdown").check(wheel_key==3).refresh_item(mainMenu); + mainMenu.get_item("wheel_ctrlupdown").check(wheel_key==4).refresh_item(mainMenu); + mainMenu.get_item("wheel_ctrlleftright").check(wheel_key==5).refresh_item(mainMenu); + mainMenu.get_item("wheel_ctrlpageupdown").check(wheel_key==6).refresh_item(mainMenu); + mainMenu.get_item("wheel_ctrlwz").check(wheel_key==7).refresh_item(mainMenu); + mainMenu.get_item("wheel_none").check(wheel_key==0).refresh_item(mainMenu); + mainMenu.get_item("wheel_guest").check(wheel_guest).refresh_item(mainMenu); + } + if (!strcasecmp(inputline.substr(0, 12).c_str(), "sensitivity=")) { + Prop_multival* p3 = static_cast(section)->Get_multival("sensitivity"); + sdl.mouse.xsensitivity = p3->GetSection()->Get_int("xsens"); + sdl.mouse.ysensitivity = p3->GetSection()->Get_int("ysens"); + } + #if C_GAMELINK + if (!strcasecmp(inputline.substr(0, 22).c_str(), "gamelink load address=")) { + sdl.gamelink.loadaddr = section->Get_int("gamelink load address"); + } + #endif + if (!strcasecmp(inputline.substr(0, 11).c_str(), "fullscreen=")) { + if (section->Get_bool("fullscreen")) { + if (!GFX_IsFullscreen()) {GFX_LosingFocus();GFX_SwitchFullScreen();} + } else if (GFX_IsFullscreen()) {GFX_LosingFocus();GFX_SwitchFullScreen();} + } + if (!strcasecmp(inputline.substr(0, 7).c_str(), "output=")) { + std::string output=section->Get_string("output"); + if (output == "default") output=GetDefaultOutput(); + GFX_LosingFocus(); + toOutput(output.c_str()); + #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU + if (!GFX_GetPreventFullscreen()) { + if (menu.toggle) DOSBox_SetMenu(); else DOSBox_NoMenu(); + } + #endif + #if defined(WIN32) && !defined(HX_DOS) + DOSBox_SetSysMenu(); + #endif + } + if (!strcasecmp(inputline.substr(0, 13).c_str(), "transparency=")) + SetWindowTransparency(section->Get_int("transparency")); + #if defined(C_SDL2) + if (!strcasecmp(inputline.substr(0, 16).c_str(), "mapperfile_sdl2=")) ReloadMapper(section,true); + #else + if (!strcasecmp(inputline.substr(0, 16).c_str(), "mapperfile_sdl1=")) ReloadMapper(section,true); + #if !defined(HAIKU) && !defined(RISCOS) + if (!strcasecmp(inputline.substr(0, 11).c_str(), "mapperfile=")) { + Prop_path* pp; + #if defined(C_SDL2) + pp = section->Get_path("mapperfile_sdl2"); + #else + pp = section->Get_path("mapperfile_sdl1"); + #endif + if (pp->realpath=="") ReloadMapper(section,true); + } + if (!strcasecmp(inputline.substr(0, 13).c_str(), "usescancodes=")) { + void setScanCode(Section_prop * section), loadScanCode(), MAPPER_Init(); + setScanCode(section); + loadScanCode(); + GFX_LosingFocus(); + MAPPER_Init(); + load=true; + } + #endif + #endif + if (!strcasecmp(inputline.substr(0, 8).c_str(), "display=")) { + void SetDisplayNumber(int display); + int numscreen = GetNumScreen(); + const int display = section->Get_int("display"); + if (display >= 0 && display <= numscreen) + SetDisplayNumber(display); + } + if (!strcasecmp(inputline.substr(0, 15).c_str(), "windowposition=")) { + const char* windowposition = section->Get_string("windowposition"); + int GetDisplayNumber(void); + #if defined(C_SDL2) || defined (WIN32) + int posx = -1, posy = -1; + #endif + if (windowposition && *windowposition) { + char result[100]; + safe_strncpy(result, windowposition, sizeof(result)); + char* y = strchr(result, ','); + if (y && *y) { + *y = 0; + #if defined(C_SDL2) || defined (WIN32) + posx = atoi(result); + posy = atoi(y + 1); + #endif + } + } + #if defined(C_SDL2) + SDL_Window* GFX_GetSDLWindow(void); + SDL_SetWindowTitle(GFX_GetSDLWindow(),"DOSBox-X"); + if (posx < 0 || posy < 0) { + SDL_DisplayMode dm; + int w = 640,h = 480; + SDL_GetWindowSize(GFX_GetSDLWindow(), &w, &h); + if (SDL_GetDesktopDisplayMode(GetDisplayNumber()?GetDisplayNumber()-1:0,&dm) == 0) { + posx = (dm.w - w)/2; + posy = (dm.h - h)/2; + } + } + if (GetDisplayNumber()>0) { + int displays = SDL_GetNumVideoDisplays(); + SDL_Rect bound; + for( int i = 1; i <= displays; i++ ) { + bound = SDL_Rect(); + SDL_GetDisplayBounds(i-1, &bound); + if (i == GetDisplayNumber()) { + posx += bound.x; + posy += bound.y; + break; + } + } + } + SDL_SetWindowPosition(GFX_GetSDLWindow(), posx, posy); + #elif defined(WIN32) + RECT rect; + MONITORINFO info; + GetWindowRect(GetHWND(), &rect); + #if !defined(HX_DOS) && !defined(_WIN32_WINDOWS) + if (GetDisplayNumber()>0) { + xyp xy={0}; + xy.x=-1; + xy.y=-1; + curscreen=0; + BOOL CALLBACK EnumDispProc(HMONITOR hMon, HDC dcMon, RECT* pRcMon, LPARAM lParam); + EnumDisplayMonitors(0, 0, EnumDispProc, reinterpret_cast(&xy)); + HMONITOR monitor = MonitorFromRect(&monrect, MONITOR_DEFAULTTONEAREST); + info.cbSize = sizeof(MONITORINFO); + GetMonitorInfo(monitor, &info); + if (posx >=0 && posy >=0) { + posx+=info.rcMonitor.left; + posy+=info.rcMonitor.top; + } else { + posx = info.rcMonitor.left+(info.rcMonitor.right-info.rcMonitor.left-(rect.right-rect.left))/2; + posy = info.rcMonitor.top+(info.rcMonitor.bottom-info.rcMonitor.top-(rect.bottom-rect.top))/2; + } + } else + #endif + if (posx < 0 && posy < 0) { + posx = (GetSystemMetrics(SM_CXSCREEN)-(rect.right-rect.left))/2; + posy = (GetSystemMetrics(SM_CYSCREEN)-(rect.bottom-rect.top))/2; + } + MoveWindow(GetHWND(), posx, posy, rect.right-rect.left, rect.bottom-rect.top, true); + #endif + } + + #if defined(USE_TTF) + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(pvar.c_str(), "cpu")) { + bool turbo = section->Get_bool("turbo"); + if (turbo != ticksLocked) DOSBOX_UnlockSpeed2(true); + } else if (!strcasecmp(pvar.c_str(), "dos")) { + mountwarning = section->Get_bool("mountwarning"); + if (!strcasecmp(inputline.substr(0, 15).c_str(), "autofixwarning=")) { + std::string autofixwarning=section->Get_string("autofixwarning"); + autofixwarn=autofixwarning=="false"||autofixwarning=="0"||autofixwarning=="none"?0:(autofixwarning=="a20fix"?1:(autofixwarning=="loadfix"?2:3)); + } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "lfn=")) { + std::string lfn = section->Get_string("lfn"); + if (lfn=="true"||lfn=="1") enablelfn=1; + else if (lfn=="false"||lfn=="0") enablelfn=0; + else if (lfn=="autostart") enablelfn=-2; + else enablelfn=-1; + mainMenu.get_item("dos_lfn_auto").check(enablelfn==-1).refresh_item(mainMenu); + mainMenu.get_item("dos_lfn_enable").check(enablelfn==1).refresh_item(mainMenu); + mainMenu.get_item("dos_lfn_disable").check(enablelfn==0).refresh_item(mainMenu); + uselfn = enablelfn==1 || ((enablelfn == -1 || enablelfn == -2) && (dos.version.major>6 || winrun)); + } else if (!strcasecmp(inputline.substr(0, 16).c_str(), "fat32setversion=")) { + std::string fat32setverstr = section->Get_string("fat32setversion"); + if (fat32setverstr=="auto") fat32setver=1; + else if (fat32setverstr=="manual") fat32setver=0; + else fat32setver=-1; + } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "ver=")) { + const char *ver = section->Get_string("ver"); + if (!*ver) { + dos.version.minor=0; + dos.version.major=5; + dos_ver_menu(false); + } else if (set_ver((char *)ver)) + dos_ver_menu(false); + } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "ems=")) { + EMS_DoShutDown(); + EMS_Startup(NULL); + update_dos_ems_menu(); + } else if (!strcasecmp(inputline.substr(0, 32).c_str(), "shell configuration as commands=")) { + enable_config_as_shell_commands = section->Get_bool("shell configuration as commands"); + mainMenu.get_item("shell_config_commands").check(enable_config_as_shell_commands).enable(true).refresh_item(mainMenu); + } else if (!strcasecmp(inputline.substr(0, 18).c_str(), "dos clipboard api=")) { + clipboard_dosapi = section->Get_bool("dos clipboard api"); + mainMenu.get_item("clipboard_dosapi").check(clipboard_dosapi).refresh_item(mainMenu); + } else if (!strcasecmp(inputline.substr(0, 22).c_str(), "pipe temporary device=")) { + pipetmpdev = section->Get_bool("pipe temporary device"); + #if defined(WIN32) && !defined(HX_DOS) + } else if (!strcasecmp(inputline.substr(0, 13).c_str(), "automountall=")) { + const char *automountstr = section->Get_string("automountall"); + if (strcmp(automountstr, "0") && strcmp(automountstr, "false")) MountAllDrives(quiet||!strcmp(automountstr, "quiet")); + } else if (!strcasecmp(inputline.substr(0, 9).c_str(), "startcmd=")) { + winautorun = section->Get_bool("startcmd"); + mainMenu.get_item("dos_win_autorun").check(winautorun).enable(true).refresh_item(mainMenu); + #endif + #if defined(WIN32) && !defined(HX_DOS) || defined(LINUX) || defined(MACOSX) + } else if (!strcasecmp(inputline.substr(0, 15).c_str(), "starttranspath=")) { + starttranspath = section->Get_bool("starttranspath"); + mainMenu.get_item("dos_win_transpath").check(starttranspath).enable( + #if defined(WIN32) && !defined(HX_DOS) + true + #else + startcmd + #endif + ).refresh_item(mainMenu); + } else if (!strcasecmp(inputline.substr(0, 10).c_str(), "startwait=")) { + startwait = section->Get_bool("startwait"); + mainMenu.get_item("dos_win_wait").check(startwait).enable( + #if defined(WIN32) && !defined(HX_DOS) + true + #else + startcmd + #endif + ).refresh_item(mainMenu); + } else if (!strcasecmp(inputline.substr(0, 11).c_str(), "startquiet=")) { + startquiet = section->Get_bool("startquiet"); + mainMenu.get_item("dos_win_quiet").check(startquiet).enable( + #if defined(WIN32) && !defined(HX_DOS) + true + #else + startcmd + #endif + ).refresh_item(mainMenu); + #endif + } + } else if (!strcasecmp(pvar.c_str(), "ttf")) { + void ttf_reset(void), ttf_setlines(int cols, int lins), SetBlinkRate(Section_prop* section); + if (!strcasecmp(inputline.substr(0, 5).c_str(), "font=")) { + #if defined(USE_TTF) + if (TTF_using()) { + std::string font = section->Get_string("font"); + if (font.empty() && !IS_PC98_ARCH && !isDBCSCP()) notrysgf = true; + ttf_reset(); + notrysgf = false; + int missing = IS_PC98_ARCH ? 0 : setTTFMap(false); + if (missing > 0 && first_shell) first_shell->WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); + + #if C_PRINTER + if (printfont) UpdateDefaultPrinterFont(); + #endif + } + #endif + } else if (!strcasecmp(inputline.substr(0, 7).c_str(), "ptsize=")||!strcasecmp(inputline.substr(0, 8).c_str(), "winperc=")) { + #if defined(USE_TTF) + lesssize = true; + if (TTF_using()) ttf_reset(); + lesssize = false; + #endif + } else if (!strcasecmp(inputline.substr(0, 5).c_str(), "lins=")||!strcasecmp(inputline.substr(0, 5).c_str(), "cols=")) { + #if defined(USE_TTF) + if (TTF_using()) { + bool iscol=!strcasecmp(inputline.substr(0, 5).c_str(), "cols="); + if (iscol&&IS_PC98_ARCH) + SetVal("render", "cols", "80"); + else if (!CurMode) + ; + else if (CurMode->type==M_TEXT || IS_PC98_ARCH) { + const char *str = "\033[2J"; + uint16_t n = (uint16_t)strlen(str); + DOS_WriteFile(STDOUT,(uint8_t *)str,&n); + if (quiet && first_shell) first_shell->ShowPrompt(); + } else { + reg_ax=CurMode->mode; + CALLBACK_RunRealInt(0x10); + } + lastset=iscol?2:1; + ttf_setlines(0, 0); + lastset=0; + } + #endif + } else if (!strcasecmp(inputline.substr(0, 13).c_str(), "outputswitch=")) { + #if defined(USE_TTF) + SetOutputSwitch(section->Get_string("outputswitch")); + #endif + } else if (!strcasecmp(inputline.substr(0, 7).c_str(), "colors=")) { + #if defined(USE_TTF) + if (TTF_using() && !strlen(section->Get_string("colors"))) ttf_reset_colors(); + #endif + } else if (!strcasecmp(inputline.substr(0, 3).c_str(), "wp=")) { + #if defined(USE_TTF) + const char *wpstr=section->Get_string("wp"); + wpType=wpVersion=0; + if (strlen(wpstr)>1) { + if (!strncasecmp(wpstr, "WP", 2)) wpType=1; + else if (!strncasecmp(wpstr, "WS", 2)) wpType=2; + else if (!strncasecmp(wpstr, "XY", 3)) wpType=3; + if (strlen(wpstr)>2&&wpstr[2]>='1'&&wpstr[2]<='9') wpVersion=wpstr[2]-'0'; + } + mainMenu.get_item("ttf_wpno").check(!wpType).refresh_item(mainMenu); + mainMenu.get_item("ttf_wpwp").check(wpType==1).refresh_item(mainMenu); + mainMenu.get_item("ttf_wpws").check(wpType==2).refresh_item(mainMenu); + mainMenu.get_item("ttf_wpxy").check(wpType==3).refresh_item(mainMenu); + mainMenu.get_item("ttf_wpfe").check(wpType==4).refresh_item(mainMenu); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 5).c_str(), "wpbg=")) { + #if defined(USE_TTF) + wpBG = section->Get_int("wpbg"); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 5).c_str(), "wpfg=")) { + #if defined(USE_TTF) + wpFG = section->Get_int("wpfg"); + if (wpFG<0) wpFG = 7; + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 5).c_str(), "bold=")) { + #if defined(USE_TTF) + showbold = section->Get_bool("bold"); + mainMenu.get_item("ttf_showbold").check(showbold).refresh_item(mainMenu); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 7).c_str(), "italic=")) { + #if defined(USE_TTF) + showital = section->Get_bool("italic"); + mainMenu.get_item("ttf_showital").check(showital).refresh_item(mainMenu); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 10).c_str(), "underline=")) { + #if defined(USE_TTF) + showline = section->Get_bool("underline"); + mainMenu.get_item("ttf_showline").check(showline).refresh_item(mainMenu); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 10).c_str(), "strikeout=")) { + #if defined(USE_TTF) + showsout = section->Get_bool("strikeout"); + mainMenu.get_item("ttf_showsout").check(showsout).refresh_item(mainMenu); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 8).c_str(), "char512=")) { + #if defined(USE_TTF) + char512 = section->Get_bool("char512"); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 12).c_str(), "righttoleft=")) { + #if defined(USE_TTF) + rtl = section->Get_bool("righttoleft"); + mainMenu.get_item("ttf_right_left").check(rtl).refresh_item(mainMenu); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 10).c_str(), "printfont=")) { + #if defined(USE_TTF) && C_PRINTER + printfont = section->Get_bool("printfont"); + mainMenu.get_item("ttf_printfont").check(printfont).refresh_item(mainMenu); + UpdateDefaultPrinterFont(); + #endif + } else if (!strcasecmp(inputline.substr(0, 9).c_str(), "autodbcs=")) { + #if defined(USE_TTF) + dbcs_sbcs = section->Get_bool("autodbcs"); + mainMenu.get_item("mapper_dbcssbcs").check(dbcs_sbcs).refresh_item(mainMenu); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 12).c_str(), "autoboxdraw=")) { + #if defined(USE_TTF) + autoboxdraw = section->Get_bool("autoboxdraw"); + mainMenu.get_item("mapper_autoboxdraw").check(autoboxdraw).refresh_item(mainMenu); + if (TTF_using()) resetFontSize(); + #endif + } else if (!strcasecmp(inputline.substr(0, 14).c_str(), "halfwidthkana=")) { + #if defined(USE_TTF) + halfwidthkana = section->Get_bool("halfwidthkana"); + mainMenu.get_item("ttf_halfwidthkana").check(halfwidthkana||IS_PC98_ARCH||IS_JEGA_ARCH).refresh_item(mainMenu); + if (TTF_using()) {setTTFCodePage();resetFontSize();} + #endif + } else if (!strcasecmp(inputline.substr(0, 7).c_str(), "blinkc=")) { + #if defined(USE_TTF) + SetBlinkRate(section); + mainMenu.get_item("ttf_blinkc").check(blinkCursor>-1).refresh_item(mainMenu); + #endif + } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "gbk=")) { + if (gbk != section->Get_bool("gbk")) { + gbk = !gbk; + if (enable_dbcs_tables&&dos.tables.dbcs&&(IS_PDOSV||dos.loaded_codepage==936)) mem_writeb(Real2Phys(dos.tables.dbcs)+2,gbk?0x81:0xA1); + clearFontCache(); + if (dos.loaded_codepage!=950&&dos.loaded_codepage!=951) mainMenu.get_item("ttf_extcharset").check(dos.loaded_codepage==936?gbk:(gbk&&chinasea)).refresh_item(mainMenu); + #if defined(USE_TTF) + if (TTF_using() && dos.loaded_codepage==936) resetFontSize(); + #endif + } + } else if (!strcasecmp(inputline.substr(0, 9).c_str(), "chinasea=")) { + if (chinasea != section->Get_bool("chinasea")) { + chinasea = !chinasea; + if (!chinasea) makestdcp950table(); + else makeseacp951table(); + clearFontCache(); + if (dos.loaded_codepage!=936) mainMenu.get_item("ttf_extcharset").check(dos.loaded_codepage==950||dos.loaded_codepage==951?chinasea:(gbk&&chinasea)).refresh_item(mainMenu); + if ((TTF_using() || showdbcs) && (dos.loaded_codepage==950 || dos.loaded_codepage==951)) { + MSG_Init(); + #if defined(USE_TTF) + if (TTF_using()) resetFontSize(); + #endif + } + } + } else if (!strcasecmp(inputline.substr(0, 4).c_str(), "uao=")) { + if (uao != section->Get_bool("uao")) { + uao = !uao; + clearFontCache(); + if ((TTF_using() || showdbcs) && dos.loaded_codepage==951) { + MSG_Init(); + DOSBox_SetSysMenu(); + #if defined(USE_TTF) + if (TTF_using()) resetFontSize(); + #endif + runRescan("-A -Q"); + } + } + } + } else if (!strcasecmp(pvar.c_str(), "dosv")) { + if (!strcasecmp(inputline.substr(0, 15).c_str(), "showdbcsnodosv=") + #if defined(USE_TTF) + && !ttfswitch + #endif + ) { + std::string showdbcsstr = section->Get_string("showdbcsnodosv"); + #if defined(USE_TTF) + showdbcs = showdbcsstr=="true"||showdbcsstr=="1"||(showdbcsstr=="auto" && (loadlang || dbcs_sbcs)); + #else + showdbcs = showdbcsstr=="true"||showdbcsstr=="1"||(showdbcsstr=="auto" && loadlang); + #endif + if (!IS_EGAVGA_ARCH) showdbcs = false; + } else if (!strcasecmp(inputline.substr(0, 11).c_str(), "fepcontrol=")||!strcasecmp(inputline.substr(0, 7).c_str(), "vtext1=")||!strcasecmp(inputline.substr(0, 7).c_str(), "vtext2=")) + DOSV_SetConfig(section); + } else if (!strcasecmp(pvar.c_str(), "render")) { + if (!strcasecmp(inputline.substr(0, 9).c_str(), "glshader=")) { + #if C_OPENGL + std::string LoadGLShader(Section_prop * section); + LoadGLShader(section); + GFX_ForceRedrawScreen(); + #endif + } else if (!strcasecmp(inputline.substr(0, 12).c_str(), "pixelshader=")) + GFX_ForceRedrawScreen(); + else if (!strcasecmp(inputline.substr(0, 13).c_str(), "aspect_ratio=")) { + setAspectRatio(section); + if (render.aspect) GFX_ForceRedrawScreen(); + } + } else if (!strcasecmp(pvar.c_str(), "serial")) { + if (!strcasecmp(inputline.substr(0, 6).c_str(), "serial") && inputline[7]=='=') { + std::string val = section->Get_string("serial" + std::string(1, inputline[6])), cmd = std::string(1, inputline[6]) + " " + (val.size()?val:"dummy"); + runSerial(cmd.c_str()); + } + } else if (!strcasecmp(pvar.c_str(), "parallel")) { + if (!strcasecmp(inputline.substr(0, 8).c_str(), "parallel") && inputline[9]=='=') { + std::string val = section->Get_string("parallel" + std::string(1, inputline[8])), cmd = std::string(1, inputline[8]) + " " + (val.size()?val:"disabled"); + runParallel(cmd.c_str()); + } + #if C_PRINTER + } else if (!strcasecmp(pvar.c_str(), "printer")) { + PRINTER_Shutdown(NULL); + PRINTER_Init(); + #endif + } + } + } + } + + void CONFIG::Run(void) { + static const char* const params[] = { + "-r", "-wcp", "-wcd", "-wc", "-writeconf", "-wcpboot", "-wcdboot", "-wcboot", "-writeconfboot", "-bootconf", "-bc", + "-l", "-rmconf", "-h", "-help", "-?", "-axclear", "-axadd", "-axtype", + "-avistart","-avistop", + "-startmapper", + "-get", "-set", "-setf", + "-writelang", "-wl", "-langname", "-ln", + "-securemode", "-setup", "-all", "-mod", "-norem", "-errtest", "-gui", NULL }; + /* HACK: P_ALL is in linux/wait.h */ + #if defined(P_ALL) + #define __P_ALL P_ALL + #undef P_ALL + #endif + enum prs { + P_NOMATCH, P_NOPARAMS, // fixed return values for GetParameterFromList + P_RESTART, + P_WRITECONF_PORTABLE, P_WRITECONF_DEFAULT, P_WRITECONF, P_WRITECONF2, + P_WRITECONF_PORTABLE_REBOOT, P_WRITECONF_DEFAULT_REBOOT, P_WRITECONF_REBOOT, P_WRITECONF2_REBOOT, + P_BOOTCONF, P_BOOTCONF2, P_LISTCONF, P_KILLCONF, + P_HELP, P_HELP2, P_HELP3, + P_AUTOEXEC_CLEAR, P_AUTOEXEC_ADD, P_AUTOEXEC_TYPE, + P_REC_AVI_START, P_REC_AVI_STOP, + P_START_MAPPER, + P_GETPROP, P_SETPROP, P_SETFORCE, + P_WRITELANG, P_WRITELANG2, P_LANGNAME, P_LANGNAME2, + P_SECURE, P_SETUP, P_ALL, P_MOD, P_NOREM, P_ERRTEST, P_GUI + } presult = P_NOMATCH; + + Section_prop * section=static_cast(control->GetSection("dosbox")); + int all = section->Get_bool("show advanced options")?1:-1; + bool first = true, norem = false; + std::vector pvars; + if (cmd->FindExist("-setup", true)) all = 2; + else if (cmd->FindExist("-all", true)) all = 1; + else if (cmd->FindExist("-mod", true)) all = 0; + if (cmd->FindExist("-norem", true)) norem = true; + // Loop through the passed parameters + while(presult != P_NOPARAMS) { + presult = (enum prs)cmd->GetParameterFromList(params, pvars); + switch(presult) { + + case P_SETUP: + all = 2; + break; + + case P_ALL: + if (all<1) all = 1; + break; + #if defined(__P_ALL) + #define P_ALL __P_ALL + #endif + + case P_MOD: + if (all==-1) all = 0; + break; + + case P_NOREM: + norem = true; + break; + + case P_GUI: + void GUI_Run(bool pressed); + GUI_Run(false); + break; + + case P_LANGNAME: case P_LANGNAME2: + if (pvars.size() < 1) { + WriteOut("%s\n", langname.c_str()); + return; + } else + langname=pvars[0]; + break; + + case P_ERRTEST: + exit_status = 1; + WriteExitStatus(); + return; + + case P_RESTART: + WriteOut("-restart is no longer supported\n"); + return; + + case P_LISTCONF: { + Bitu size = (Bitu)control->configfiles.size(); + std::string config_path; + Cross::GetPlatformConfigDir(config_path); + WriteOut(MSG_Get("PROGRAM_CONFIG_CONFDIR"), VERSION,config_path.c_str()); + char cwd[512] = "."; + // char *res = getcwd(cwd,sizeof(cwd)-1); + // if (res!=NULL) WriteOut(MSG_Get("PROGRAM_CONFIG_WORKDIR"), cwd); + if (size==0&&!configfile.size()) WriteOut(MSG_Get("PROGRAM_CONFIG_NOCONFIGFILE")); + else { + WriteOut(MSG_Get("PROGRAM_CONFIG_PRIMARY_CONF"),control->configfiles.front().c_str()); + if (size > 1) { + WriteOut(MSG_Get("PROGRAM_CONFIG_ADDITIONAL_CONF")); + for(Bitu i = 1; i < size; i++) + WriteOut("%s\n",control->configfiles[i].c_str()); + } + if (configfile.size()) WriteOut(MSG_Get("PROGRAM_CONFIG_GLOBAL_CONF"),configfile.c_str()); + } + if (control->startup_params.size() > 0) { + std::string test; + for(size_t k = 0; k < control->startup_params.size(); k++) + test += control->startup_params[k] + " "; + WriteOut(MSG_Get("PROGRAM_CONFIG_PRINT_STARTUP"), test.c_str()); + } + break; + } + case P_WRITECONF: case P_WRITECONF2: case P_WRITECONF_REBOOT: case P_WRITECONF2_REBOOT: + if (securemode_check()) return; + if (pvars.size() > 1) return; + else if (pvars.size() == 1) { + // write config to specific file, except if it is an absolute path + writeconf(pvars[0], !Cross::IsPathAbsolute(pvars[0]), all, norem); + if (presult==P_WRITECONF_REBOOT || presult==P_WRITECONF2_REBOOT) RebootConfig(pvars[0]); + } else { + // -wc without parameter: write primary config file + if (control->configfiles.size()) { + writeconf(control->configfiles[0], false, all, norem); + if (presult==P_WRITECONF_REBOOT || presult==P_WRITECONF2_REBOOT) RebootConfig(control->configfiles[0]); + } else WriteOut(MSG_Get("PROGRAM_CONFIG_NOCONFIGFILE")); + } + break; + case P_WRITECONF_DEFAULT: case P_WRITECONF_DEFAULT_REBOOT: { + // write to /userdir/dosbox-x-0.xx.conf + if (securemode_check()) return; + if (pvars.size() > 0) return; + std::string confname; + Cross::GetPlatformConfigName(confname); + writeconf(confname, true, all, norem); + if (presult==P_WRITECONF_DEFAULT_REBOOT) RebootConfig(confname); + break; + } + case P_WRITECONF_PORTABLE: case P_WRITECONF_PORTABLE_REBOOT: + if (securemode_check()) return; + if (pvars.size() > 1) return; + else if (pvars.size() == 1) { + // write config to startup directory + writeconf(pvars[0], false, all, norem); + if (presult==P_WRITECONF_PORTABLE_REBOOT) RebootConfig(pvars[0]); + } else { + // -wcp without parameter: write dosbox-x.conf to startup directory + writeconf(std::string("dosbox-x.conf"), false, all, norem); + if (presult==P_WRITECONF_PORTABLE_REBOOT) RebootConfig(std::string("dosbox-x.conf")); + } + break; + case P_BOOTCONF: case P_BOOTCONF2: + if (securemode_check()) return; + if (pvars.size() > 1) return; + else if (pvars.size() == 1) { + RebootConfig(pvars[0]); + } else { + Bitu size = (Bitu)control->configfiles.size(); + if (size==0) RebootConfig("dosbox-x.conf"); + else RebootConfig(control->configfiles.front().c_str()); + } + break; + case P_NOPARAMS: + if (!first) break; + + case P_NOMATCH: + WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE")); + return; + + case P_HELP: case P_HELP2: case P_HELP3: { + switch(pvars.size()) { + case 0: + WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE")); + return; + case 1: { + if (!strcasecmp("sections",pvars[0].c_str())) { + // list the sections + WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_SECTLIST")); + int i = 0; + while(true) { + Section* sec = control->GetSection(i++); + if (!sec) break; + WriteOut("%s\n",sec->GetName()); + } + return; + } + // if it's a section, leave it as one-param + Section* sec = control->GetSection(pvars[0].c_str()); + if (!sec) { + // could be a property + sec = control->GetSectionFromProperty(pvars[0].c_str()); + if (!sec&&pvars[0].size()>4&&!strcasecmp(pvars[0].substr(0, 4).c_str(), "ttf.")) { + pvars[0].erase(0,4); + sec = control->GetSectionFromProperty(pvars[0].c_str()); + } + if (!sec) { + WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); + return; + } + pvars.insert(pvars.begin(),std::string(sec->GetName())); + } + break; + } + case 2: { + // sanity check + Section* sec = control->GetSection(pvars[0].c_str()); + Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str()); + + if (sec != sec2) { + WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_DUPLICATE")); + } + break; + } + default: + WriteOut(MSG_Get("PROGRAM_CONFIG_USAGE")); + return; + } + // if we have one value in pvars, it's a section + // two values are section + property + Section* sec = control->GetSection(pvars[0].c_str()); + if (sec==NULL) { + WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); + return; + } + Section_prop* psec = dynamic_cast (sec); + if (psec==NULL) { + // failed; maybe it's the autoexec section? + Section_line* pline = dynamic_cast (sec); + if (pline==NULL) E_Exit("Section dynamic cast failed."); + + WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_LINEHLP"), + pline->GetName(), + // this is 'unclean' but the autoexec section has no help associated + MSG_Get("AUTOEXEC_CONFIGFILE_HELP"), + pline->data.c_str() ); + return; + } + if (pvars.size()==1) { + size_t i = 0; + WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_SECTHLP"),pvars[0].c_str()); + while(true) { + // list the properties + Property* p = psec->Get_prop((int)(i++)); + if (p==NULL) break; + if (!(all>0 || (all==-1 && (p->basic() || p->modified())) || (!all && ((p->propname == "rem" && (!strcmp(pvars[0].c_str(), "4dos") || !strcmp(pvars[0].c_str(), "config"))) || p->modified())))) continue; + WriteOut("%s\n", p->propname.c_str()); + } + if (!strcasecmp(pvars[0].c_str(), "config")) + WriteOut("set\ninstall\ninstallhigh\ndevice\ndevicehigh\n"); + } else { + // find the property by its name + size_t i = 0; + while (true) { + Property *p = psec->Get_prop((int)(i++)); + if (p==NULL) break; + if (!strcasecmp(p->propname.c_str(),pvars[1].c_str())) { + // found it; make the list of possible values + std::string propvalues; + std::vector pv = p->GetValues(); + + if (p->Get_type()==Value::V_BOOL) { + // possible values for boolean are true, false + propvalues += "true, false"; + } else if (p->Get_type()==Value::V_INT) { + // print min, max for integer values if used + Prop_int* pint = dynamic_cast (p); + if (pint==NULL) E_Exit("Int property dynamic cast failed."); + if (pint->getMin() != pint->getMax()) { + std::ostringstream oss; + oss << pint->getMin(); + oss << ".."; + oss << pint->getMax(); + propvalues += oss.str(); + } + } + for(Bitu k = 0; k < pv.size(); k++) { + if (pv[k].ToString() =="%u") + propvalues += MSG_Get("PROGRAM_CONFIG_HLP_POSINT"); + else propvalues += pv[k].ToString(); + if ((k+1) < pv.size() && (strcmp(pvars[0].c_str(), "config") || p->propname != "numlock" || pv[k+1].ToString() != "")) propvalues += ", "; + } + + WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_PROPHLP"), + p->propname.c_str(), + sec->GetName(), + p->Get_help(),propvalues.c_str(), + p->Get_Default_Value().ToString().c_str(), + p->GetValue().ToString().c_str()); + // print 'changeability' + if (p->getChange()==Property::Changeable::OnlyAtStart) { + WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_NOCHANGE")); + } + return; + } + } + break; + } + return; + } + case P_AUTOEXEC_CLEAR: { + Section_line* sec = dynamic_cast + (control->GetSection(std::string("autoexec"))); + sec->data.clear(); + break; + } + case P_AUTOEXEC_ADD: { + if (pvars.size() == 0) { + WriteOut(MSG_Get("PROGRAM_CONFIG_MISSINGPARAM")); + return; + } + Section_line* sec = dynamic_cast + (control->GetSection(std::string("autoexec"))); + + for(Bitu i = 0; i < pvars.size(); i++) sec->HandleInputline(pvars[i]); + break; + } + case P_AUTOEXEC_TYPE: { + Section_line* sec = dynamic_cast + (control->GetSection(std::string("autoexec"))); + WriteOut("\n%s",sec->data.c_str()); + break; + } + case P_REC_AVI_START: + CAPTURE_VideoStart(); + break; + case P_REC_AVI_STOP: + CAPTURE_VideoStop(); + break; + case P_START_MAPPER: + if (securemode_check()) return; + MAPPER_Run(false); + break; + case P_GETPROP: { + // "section property" + // "property" + // "section" + // "section" "property" + if (pvars.size()==0) { + WriteOut(MSG_Get("PROGRAM_CONFIG_GET_SYNTAX")); + return; + } + Section* sec = control->GetSectionFromProperty(pvars[0].c_str()); + std::string::size_type spcpos = pvars[0].find_first_of(' '); + // split on the ' ' + if (!sec && spcpos != std::string::npos) { + if (spcpos>1&&pvars[0].c_str()[spcpos-1]==',') + spcpos=pvars[0].find_first_of(' ', spcpos+1); + if (spcpos != std::string::npos) { + pvars.insert(pvars.begin()+1,pvars[0].substr(spcpos+1)); + pvars[0].erase(spcpos); + } + } + switch(pvars.size()) { + case 1: { + // property/section only + // is it a section? + sec = control->GetSection(pvars[0].c_str()); + if (sec) { + // list properties in section + int i = 0; + Section_prop* psec = dynamic_cast (sec); + if (psec==NULL) { + // autoexec section + Section_line* pline = dynamic_cast (sec); + if (pline==NULL) E_Exit("Section dynamic cast failed."); + + WriteOut("%s",pline->data.c_str()); + break; + } + while(true) { + // list the properties + Property* p = psec->Get_prop(i++); + if (p==NULL) break; + if (!(all>0 || (all==-1 && (p->basic() || p->modified())) || (!all && ((p->propname == "rem" && (!strcmp(pvars[0].c_str(), "4dos") || !strcmp(pvars[0].c_str(), "config"))) || p->modified())))) continue; + WriteOut("%s=%s\n", p->propname.c_str(), + p->GetValue().ToString().c_str()); + } + if (!strcasecmp(pvars[0].c_str(), "config")||!strcasecmp(pvars[0].c_str(), "4dos")) { + const char * extra = psec->data.c_str(); + if (extra&&strlen(extra)) { + std::istringstream in(extra); + char linestr[CROSS_LEN+1], cmdstr[CROSS_LEN], valstr[CROSS_LEN]; + char *cmd=cmdstr, *val=valstr, /**lin=linestr,*/ *p; + if (in) for (std::string line; std::getline(in, line); ) { + if (line.length()>CROSS_LEN) { + strncpy(linestr, line.c_str(), CROSS_LEN); + linestr[CROSS_LEN]=0; + } else + strcpy(linestr, line.c_str()); + p=strchr(linestr, '='); + if (p!=NULL) { + *p=0; + strcpy(cmd, linestr); + cmd=trim(cmd); + strcpy(val, p+1); + val=trim(val); + lowcase(cmd); + if (!strcasecmp(pvars[0].c_str(), "4dos")||!strncmp(cmd, "set ", 4)||!strcmp(cmd, "install")||!strcmp(cmd, "installhigh")||!strcmp(cmd, "device")||!strcmp(cmd, "devicehigh")) + if (!((!strcmp(cmd, "install")||!strcmp(cmd, "installhigh")||!strcmp(cmd, "device")||!strcmp(cmd, "devicehigh"))&&!strlen(val)&&!all)) + WriteOut("%s=%s\n", cmd, val); + } + } + } + } + } else { + // no: maybe it's a property? + sec = control->GetSectionFromProperty(pvars[0].c_str()); + if (!sec&&pvars[0].size()>4&&!strcasecmp(pvars[0].substr(0, 4).c_str(), "ttf.")) { + pvars[0].erase(0,4); + sec = control->GetSectionFromProperty(pvars[0].c_str()); + } else if (!sec && pvars[0].size() && !strcasecmp(pvars[0].c_str(), "langcp")) { + pvars[0] = "language"; + sec = control->GetSectionFromProperty(pvars[0].c_str()); + } + if (!sec) { + unsigned int maxWidth, maxHeight; + void GetMaxWidthHeight(unsigned int *pmaxWidth, unsigned int *pmaxHeight), GetDrawWidthHeight(unsigned int *pdrawWidth, unsigned int *pdrawHeight); + if (!strcasecmp(pvars[0].c_str(), "screenwidth")) { + GetMaxWidthHeight(&maxWidth, &maxHeight); + WriteOut("%d\n",maxWidth); + first_shell->SetEnv("CONFIG",std::to_string(maxWidth).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "screenheight")) { + GetMaxWidthHeight(&maxWidth, &maxHeight); + WriteOut("%d\n",maxHeight); + first_shell->SetEnv("CONFIG",std::to_string(maxHeight).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "drawwidth")) { + GetDrawWidthHeight(&maxWidth, &maxHeight); + WriteOut("%d\n",maxWidth); + first_shell->SetEnv("CONFIG",std::to_string(maxWidth).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "drawheight")) { + GetDrawWidthHeight(&maxWidth, &maxHeight); + WriteOut("%d\n",maxHeight); + first_shell->SetEnv("CONFIG",std::to_string(maxHeight).c_str()); + #if defined(C_SDL2) + } else if (!strcasecmp(pvars[0].c_str(), "clientwidth")) { + int w = 640,h = 480; + SDL_Window* GFX_GetSDLWindow(void); + SDL_GetWindowSize(GFX_GetSDLWindow(), &w, &h); + WriteOut("%d\n",w); + first_shell->SetEnv("CONFIG",std::to_string(w).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "clientheight")) { + int w = 640,h = 480; + SDL_Window* GFX_GetSDLWindow(void); + SDL_GetWindowSize(GFX_GetSDLWindow(), &w, &h); + WriteOut("%d\n",h); + first_shell->SetEnv("CONFIG",std::to_string(h).c_str()); + #elif defined(WIN32) + } else if (!strcasecmp(pvars[0].c_str(), "clientwidth")) { + RECT rect; + GetClientRect(GetHWND(), &rect); + WriteOut("%d\n",rect.right-rect.left); + first_shell->SetEnv("CONFIG",std::to_string(rect.right-rect.left).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "clientheight")) { + RECT rect; + GetClientRect(GetHWND(), &rect); + WriteOut("%d\n",rect.bottom-rect.top); + first_shell->SetEnv("CONFIG",std::to_string(rect.bottom-rect.top).c_str()); + #endif + #if defined(WIN32) + } else if (!strcasecmp(pvars[0].c_str(), "windowwidth")) { + RECT rect; + GetWindowRect(GetHWND(), &rect); + WriteOut("%d\n",rect.right-rect.left); + first_shell->SetEnv("CONFIG",std::to_string(rect.right-rect.left).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "windowheight")) { + RECT rect; + GetWindowRect(GetHWND(), &rect); + WriteOut("%d\n",rect.bottom-rect.top); + first_shell->SetEnv("CONFIG",std::to_string(rect.bottom-rect.top).c_str()); + #endif + } else if (!strcasecmp(pvars[0].c_str(), "system")) { + WriteOut("%s\n",PACKAGE); + first_shell->SetEnv("CONFIG",PACKAGE); + } else if (!strcasecmp(pvars[0].c_str(), "version")) { + WriteOut("%s\n",VERSION); + first_shell->SetEnv("CONFIG",VERSION); + } else if (!strcasecmp(pvars[0].c_str(), "hostos")) { + if (securemode_check()) return; + const char *hostos = + #if defined(HX_DOS) + "DOS" + #elif defined(WIN32) + "Windows" + #elif defined(LINUX) + "Linux" + #elif defined(MACOSX) + "macOS" + #elif defined(OS2) + "OS/2" + #else + "Other" + #endif + ; + WriteOut("%s\n",hostos); + first_shell->SetEnv("CONFIG",hostos); + } else if (!strcasecmp(pvars[0].c_str(), "workdir")) { + if (securemode_check()) return; + char cwd[512] = "."; + // char *res = getcwd(cwd,sizeof(cwd)-1); + // WriteOut("%s\n",res==NULL?"":cwd); + first_shell->SetEnv("CONFIG",cwd); + } else if (!strcasecmp(pvars[0].c_str(), "programdir")) { + if (securemode_check()) return; + std::string GetDOSBoxXPath(bool withexe=false), exepath=GetDOSBoxXPath(); + WriteOut("%s\n",exepath.c_str()); + first_shell->SetEnv("CONFIG",exepath.c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "userconfigdir")) { + if (securemode_check()) return; + std::string config_path; + Cross::GetPlatformConfigDir(config_path); + WriteOut("%s\n",config_path.c_str()); + first_shell->SetEnv("CONFIG",config_path.c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "configdir")) { + if (securemode_check()) return; + std::string configdir=control->configfiles.size()?control->configfiles[control->configfiles.size()-1]:""; + if (configdir.size()) { + std::string::size_type pos = configdir.rfind(CROSS_FILESPLIT); + if(pos == std::string::npos) pos = 0; + configdir.erase(pos); + } + WriteOut("%s\n",configdir.c_str()); + first_shell->SetEnv("CONFIG",configdir.c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "cd")) { + uint8_t drive = DOS_GetDefaultDrive()+'A'; + char dir[DOS_PATHLENGTH]; + DOS_GetCurrentDir(0,dir,true); + WriteOut("%c:\\",drive); + WriteOut_NoParsing(dir, true); + WriteOut("\n"); + first_shell->SetEnv("CONFIG",(std::string(1, drive)+":\\"+std::string(dir)).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "date")) { + uint32_t ticks=mem_readd(BIOS_TIMER); + uint8_t add=mem_readb(BIOS_24_HOURS_FLAG); + mem_writeb(BIOS_24_HOURS_FLAG,0); // reset the "flag" + if (add) DOS_AddDays(add); + const char *date = FormatDate(dos.date.year, dos.date.month, dos.date.day); + WriteOut("%s\n",date); + first_shell->SetEnv("CONFIG",date); + } else if (!strcasecmp(pvars[0].c_str(), "errorlevel")) { + WriteOut("%d\n",dos.return_code); + first_shell->SetEnv("CONFIG",std::to_string(dos.return_code).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "random")) { + initRand(); + int random = rand()%32768; + WriteOut("%s\n",std::to_string(random).c_str()); + first_shell->SetEnv("CONFIG",std::to_string(random).c_str()); + } else if (!strcasecmp(pvars[0].c_str(), "time")) { + uint32_t hour, min, sec; + char c=dos.tables.country[13]; + uint32_t ticks=mem_readd(BIOS_TIMER); + uint8_t add=mem_readb(BIOS_24_HOURS_FLAG); + mem_writeb(BIOS_24_HOURS_FLAG,0); // reset the "flag" + uint16_t cx=(uint16_t)(ticks >> 16u), dx=(uint16_t)(ticks & 0xffff); + if (add) DOS_AddDays(add); + ticks=((Bitu)cx<<16)|dx; + Bitu time=(Bitu)((100.0/((double)PIT_TICK_RATE/65536.0)) * (double)ticks); + time/=100; + sec=(uint8_t)((Bitu)time % 60); // seconds + time/=60; + min=(uint8_t)((Bitu)time % 60); // minutes + time/=60; + hour=(uint8_t)((Bitu)time % 24); // hours + char format[11]; + sprintf(format,"%u%c%02u%c%02u",hour,c,min,c,sec); + WriteOut("%s\n",format); + first_shell->SetEnv("CONFIG",format); + } else if (!strcasecmp(pvars[0].c_str(), "lastmount")) { + if (lastmount) WriteOut("%c:\n",lastmount); + first_shell->SetEnv("CONFIG",lastmount?(std::string(1, lastmount) + ":").c_str():""); + } else + WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); + return; + } + // it's a property name + std::string val = sec->GetPropValue(pvars[0].c_str()); + WriteOut("%s\n",val.c_str()); + first_shell->SetEnv("CONFIG",val.c_str()); + } + break; + } + case 2: { + // section + property + sec = control->GetSection(pvars[0].c_str()); + if (!sec) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SECTION_ERROR"), pvars[0].c_str()); + return; + } + std::string val = sec->GetPropValue(pvars[1].c_str()); + if (val == NO_SUCH_PROPERTY) { + if (!strcasecmp(pvars[0].c_str(), "config") && (!strcasecmp(pvars[1].c_str(), "set") || !strcasecmp(pvars[1].c_str(), "device") || !strcasecmp(pvars[1].c_str(), "devicehigh") || !strcasecmp(pvars[1].c_str(), "install") || !strcasecmp(pvars[1].c_str(), "installhigh"))) { + Section_prop* psec = dynamic_cast (sec); + const char * extra = psec->data.c_str(); + if (extra&&strlen(extra)) { + std::istringstream in(extra); + char linestr[CROSS_LEN+1], cmdstr[CROSS_LEN], valstr[CROSS_LEN]; + char *cmd=cmdstr, *val=valstr, /**lin=linestr,*/ *p; + if (in) for (std::string line; std::getline(in, line); ) { + if (line.length()>CROSS_LEN) { + strncpy(linestr, line.c_str(), CROSS_LEN); + linestr[CROSS_LEN]=0; + } else + strcpy(linestr, line.c_str()); + p=strchr(linestr, '='); + if (p!=NULL) { + *p=0; + strcpy(cmd, linestr); + cmd=trim(cmd); + strcpy(val, p+1); + val=trim(val); + lowcase(cmd); + if (!strncasecmp(cmd, "set ", 4)&&!strcasecmp(pvars[1].c_str(), "set")) + WriteOut("%s=%s\n", trim(cmd+4), val); + else if(!strcasecmp(cmd, pvars[1].c_str())) + WriteOut("%s\n", val); + } + } + } + } else + WriteOut(MSG_Get("PROGRAM_CONFIG_NO_PROPERTY"), pvars[1].c_str(),pvars[0].c_str()); + return; + } + WriteOut("%s\n",val.c_str()); + first_shell->SetEnv("CONFIG",val.c_str()); + break; + } + default: + WriteOut(MSG_Get("PROGRAM_CONFIG_GET_SYNTAX")); + return; + } + return; + } + case P_SETPROP: case P_SETFORCE: { + // Code for the configuration changes + // Official format: config -set "section property=value" + // Accepted: with or without -set, + // "section property=value" + // "property" "value" + // "section" "property=value" + // "section" "property=value" "value" "value" ... + // "section" "property" "value" + // "section" "property" "value" "value" ... + // "section property" "value" "value" ... + // "property" "value" "value" ... + // "property=value" "value" "value" ... + + if (pvars.size()==0) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX")); + return; + } + + // add rest of command + std::string rest; + if (cmd->GetStringRemain(rest)) pvars.push_back(rest); + + Section* sec = control->GetSectionFromProperty(pvars[0].c_str()); + // attempt to split off the first word + std::string::size_type spcpos = pvars[0].find_first_of(' '); + if (spcpos>1&&pvars[0].c_str()[spcpos-1]==',') + spcpos=pvars[0].find_first_of(' ', spcpos+1); + + std::string::size_type equpos = pvars[0].find_first_of('='); + if (equpos != std::string::npos) { + std::string p = pvars[0]; + p.erase(equpos); + sec = control->GetSectionFromProperty(p.c_str()); + } + + uselangcp = false; + if ((equpos != std::string::npos) && + ((spcpos == std::string::npos) || (equpos < spcpos) || sec)) { + // If we have a '=' possibly before a ' ' split on the = + pvars.insert(pvars.begin()+1,pvars[0].substr(equpos+1)); + pvars[0].erase(equpos); + // As we had a = the first thing must be a property now + sec=control->GetSectionFromProperty(pvars[0].c_str()); + if (!sec&&pvars[0].size()>4&&!strcasecmp(pvars[0].substr(0, 4).c_str(), "ttf.")) { + pvars[0].erase(0,4); + sec = control->GetSectionFromProperty(pvars[0].c_str()); + } else if (!sec && pvars[0].size() && !strcasecmp(pvars[0].c_str(), "langcp")) { + pvars[0] = "language"; + sec = control->GetSectionFromProperty(pvars[0].c_str()); + if (sec) uselangcp = true; + } + if (sec) pvars.insert(pvars.begin(),std::string(sec->GetName())); + else { + WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); + uselangcp = false; + return; + } + // order in the vector should be ok now + } else { + if (equpos != std::string::npos && spcpos < equpos) { + // ' ' before a possible '=', split on the ' ' + pvars.insert(pvars.begin()+1,pvars[0].substr(spcpos+1)); + pvars[0].erase(spcpos); + } + // check if the first parameter is a section or property + sec = control->GetSection(pvars[0].c_str()); + if (!sec) { + // not a section: little duplicate from above + sec=control->GetSectionFromProperty(pvars[0].c_str()); + if (sec) pvars.insert(pvars.begin(),std::string(sec->GetName())); + else { + WriteOut(MSG_Get("PROGRAM_CONFIG_PROPERTY_ERROR")); + return; + } + } else { + // first of pvars is most likely a section, but could still be gus + // have a look at the second parameter + if (pvars.size() < 2) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX")); + return; + } + std::string::size_type equpos2 = pvars[1].find_first_of('='); + if (equpos2 != std::string::npos) { + // split on the = + pvars.insert(pvars.begin()+2,pvars[1].substr(equpos2+1)); + pvars[1].erase(equpos2); + } + // is this a property? + Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str()); + if (!sec2) { + // not a property, + Section* sec3 = control->GetSectionFromProperty(pvars[0].c_str()); + if (sec3 && !(equpos != std::string::npos && spcpos != std::string::npos && equpos > spcpos)) { + // section and property name are identical + pvars.insert(pvars.begin(),pvars[0]); + } // else has been checked above already + } + } + } + if(pvars.size() < 3) { + WriteOut(MSG_Get("PROGRAM_CONFIG_SET_SYNTAX")); + uselangcp = false; + return; + } + // check if the property actually exists in the section + Section* sec2 = control->GetSectionFromProperty(pvars[1].c_str()); + if (!sec2) { + if (!strcasecmp(pvars[0].c_str(), "config") && (!strcasecmp(pvars[1].c_str(), "set") || !strcasecmp(pvars[1].c_str(), "device") || !strcasecmp(pvars[1].c_str(), "devicehigh") || !strcasecmp(pvars[1].c_str(), "install") || !strcasecmp(pvars[1].c_str(), "installhigh"))) + WriteOut("Cannot set property %s in section %s.\n", pvars[1].c_str(),pvars[0].c_str()); + else + WriteOut(MSG_Get("PROGRAM_CONFIG_NO_PROPERTY"), pvars[1].c_str(),pvars[0].c_str()); + uselangcp = false; + return; + } + bool applynew=false; + Property *p = static_cast(sec2)->Get_prop(pvars[1]); + if ((p==NULL||p->getChange()==Property::Changeable::OnlyAtStart)&&presult!=P_SETFORCE) { + WriteOut(MSG_Get("PROGRAM_CONFIG_HLP_NOCHANGE")); + first_1: + WriteOut(MSG_Get("PROGRAM_CONFIG_APPLY_RESTART")); + first_2: + uint8_t c;uint16_t n=1; + DOS_ReadFile (STDIN,&c,&n); + do switch (c) { + case 'n': case 'N': + { + DOS_WriteFile (STDOUT,&c, &n); + DOS_ReadFile (STDIN,&c,&n); + do switch (c) { + case 0xD: WriteOut("\n");goto next; + case 0x03: goto next; + case 0x08: WriteOut("\b \b"); goto first_2; + } while (DOS_ReadFile (STDIN,&c,&n)); + } + case 'y': case 'Y': + { + DOS_WriteFile (STDOUT,&c, &n); + DOS_ReadFile (STDIN,&c,&n); + do switch (c) { + case 0xD: WriteOut("\n"); applynew = true; goto next; + case 0x03: goto next; + case 0x08: WriteOut("\b \b"); goto first_2; + } while (DOS_ReadFile (STDIN,&c,&n)); + } + case 0xD: WriteOut("\n"); goto first_1; + case 0x03: goto next; + case '\t': + case 0x08: + goto first_2; + default: + { + DOS_WriteFile (STDOUT,&c, &n); + DOS_ReadFile (STDIN,&c,&n); + do switch (c) { + case 0xD: WriteOut("\n"); goto first_1; + case 0x03: goto next; + case 0x08: WriteOut("\b \b"); goto first_2; + } while (DOS_ReadFile (STDIN,&c,&n)); + goto first_2; + } + } while (DOS_ReadFile (STDIN,&c,&n)); + } + next: + // Input has been parsed (pvar[0]=section, [1]=property, [2]=value) + // now execute + Section* tsec = control->GetSection(pvars[0]); + std::string value(pvars[2]); + //Due to parsing there can be a = at the start of value. + while (value.size() && (value.at(0) ==' ' ||value.at(0) =='=') ) value.erase(0,1); + for(Bitu i = 3; i < pvars.size(); i++) value += (std::string(" ") + pvars[i]); + std::string inputline = pvars[1] + "=" + value; + bool change_success = tsec->HandleInputline(inputline.c_str()); + if (change_success) { + if (applynew) RebootLanguage(""); + else ApplySetting(pvars[0], inputline, false); + } else WriteOut(MSG_Get("PROGRAM_CONFIG_VALUE_ERROR"), + value.c_str(),pvars[1].c_str()); + uselangcp = false; + return; + } + case P_WRITELANG: case P_WRITELANG2: + // In secure mode don't allow a new languagefile to be created + // Who knows which kind of file we would overwrite. + if (securemode_check()) return; + if (pvars.size() < 1) { + if (control->opt_lang == "") { + WriteOut(MSG_Get("PROGRAM_CONFIG_MISSINGPARAM")); + return; + } else if (!MSG_Write(control->opt_lang.c_str(), NULL)) { + WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_ERROR"),control->opt_lang.c_str()); + return; + } else + WriteOut(MSG_Get("PROGRAM_LANGUAGE_FILE_WHICH"),control->opt_lang.c_str()); + } else if (!MSG_Write(pvars[0].c_str(), NULL)) { + WriteOut(MSG_Get("PROGRAM_CONFIG_FILE_ERROR"),pvars[0].c_str()); + return; + } else + WriteOut(MSG_Get("PROGRAM_LANGUAGE_FILE_WHICH"),pvars[0].c_str()); + break; + + case P_SECURE: + // Code for switching to secure mode + control->SwitchToSecureMode(); + WriteOut(MSG_Get("PROGRAM_CONFIG_SECURE_ON")); + return; + + default: + E_Exit("bug"); + break; + } + first = false; + } + return; + } + + void CONFIG_ProgramStart(Program * * make) { + *make=new CONFIG; + } + + void PROGRAMS_DOS_Boot(Section *) { + } + + /* FIXME: Rename the function to clarify it does not init programs, it inits the callback mechanism + * that program generation on drive Z: needs to tie a .COM executable to a callback */ + void PROGRAMS_Init() { + LOG(LOG_MISC,LOG_DEBUG)("PROGRAMS_Init(): initializing Z: drive .COM stub and program management"); + + /* Setup a special callback to start virtual programs */ + call_program=CALLBACK_Allocate(); + CALLBACK_Setup(call_program,&PROGRAMS_Handler,CB_RETF,"internal program"); + + AddVMEventFunction(VM_EVENT_DOS_INIT_KERNEL_READY,AddVMEventFunctionFuncPair(PROGRAMS_DOS_Boot)); + + // listconf + MSG_Add("PROGRAM_CONFIG_NOCONFIGFILE","No config file loaded!\n"); + MSG_Add("PROGRAM_CONFIG_PRIMARY_CONF","Primary config file: \n%s\n"); + MSG_Add("PROGRAM_CONFIG_ADDITIONAL_CONF","Additional config files:\n"); + MSG_Add("PROGRAM_CONFIG_GLOBAL_CONF","\nGlobal config file: \n%s\n"); + MSG_Add("PROGRAM_CONFIG_CONFDIR","DOSBox-X %s user configuration directory: \n%s\n\n"); + MSG_Add("PROGRAM_CONFIG_WORKDIR","DOSBox-X's working directory: \n%s\n\n"); + + // writeconf + MSG_Add("PROGRAM_CONFIG_FILE_ERROR","\nCan't open file %s\n"); + MSG_Add("PROGRAM_CONFIG_FILE_WHICH","Writing config file %s\n"); + MSG_Add("PROGRAM_LANGUAGE_FILE_WHICH","Written to language file %s\n"); + + // help + MSG_Add("PROGRAM_CONFIG_USAGE","The DOSBox-X command-line configuration utility. Supported options:\n"\ + "-wc (or -writeconf) without parameter: Writes to primary loaded config file.\n"\ + "-wc (or -writeconf) with filename: Writes file to the config directory.\n"\ + "-wl (or -writelang) with filename: Writes the current language strings.\n"\ + "-ln (or -langname) Displays (without arguments) or specifies the language name.\n"\ + "-wcp [filename] Writes file to program directory (dosbox-x.conf or filename).\n"\ + "-wcd Writes to the default config file in the config directory.\n"\ + "-all, -mod Use with -wc, -wcp, or -wcd to write ALL or only modified options.\n"\ + "-wcboot, -wcpboot, or -wcdboot will reboot DOSBox-X after writing the file.\n"\ + "-bootconf (or -bc) reboots with specified config file (or primary loaded file).\n"\ + "-norem Use this with -wc, -wcp, or -wcd to not write config option remarks.\n"\ + "-l Lists DOSBox-X's configuration parameters.\n"\ + "-h, -help, -? Shows this help; add the word \"sections\" for a list of sections.\n"\ + "-h, -help, -? section / property Shows info on a specific section or property.\n"\ + "-axclear Clears the [autoexec] section.\n"\ + "-axadd [line] Adds a line to the [autoexec] section.\n"\ + "-axtype Prints the content of the [autoexec] section.\n"\ + "-avistart, -avistop Starts or stops AVI recording.\n"\ + "-securemode Enables secure mode where features like mounting will be disabled.\n"\ + "-startmapper Starts the DOSBox-X mapper editor.\n"\ + "-gui Starts the graphical configuration tool.\n" + "-get \"section property\" returns the value of the property (also to %%CONFIG%%).\n"\ + "-set (-setf for force) \"section property=value\" sets the value of the property.\n"); + MSG_Add("PROGRAM_CONFIG_HLP_PROPHLP","Purpose of property \"%s\" (contained in section \"%s\"):\n%s\n\nPossible Values: %s\nDefault value: %s\nCurrent value: %s\n"); + MSG_Add("PROGRAM_CONFIG_HLP_LINEHLP","Purpose of section \"%s\":\n%s\nCurrent value:\n%s\n"); + MSG_Add("PROGRAM_CONFIG_HLP_NOCHANGE","This property cannot be changed at runtime.\n"); + MSG_Add("PROGRAM_CONFIG_APPLY_RESTART","Do you want to restart now to apply the setting [Y/N]?"); + MSG_Add("PROGRAM_CONFIG_HLP_POSINT","positive integer"); + MSG_Add("PROGRAM_CONFIG_HLP_SECTHLP","Section %s contains the following properties:\n"); + MSG_Add("PROGRAM_CONFIG_HLP_SECTLIST","DOSBox-X configuration contains the following sections:\n\n"); + + MSG_Add("PROGRAM_CONFIG_SECURE_ON","Switched to secure mode.\n"); + MSG_Add("PROGRAM_CONFIG_SECURE_DISALLOW","This operation is not permitted in secure mode.\n"); + MSG_Add("PROGRAM_CONFIG_SECTION_ERROR","Section %s doesn't exist.\n"); + MSG_Add("PROGRAM_CONFIG_VALUE_ERROR","\"%s\" is not a valid value for property %s.\n"); + MSG_Add("PROGRAM_CONFIG_PROPERTY_ERROR","No such section or property.\n"); + MSG_Add("PROGRAM_CONFIG_PROPERTY_DUPLICATE","There may be other sections with the same property name.\n"); + MSG_Add("PROGRAM_CONFIG_NO_PROPERTY","There is no property %s in section %s.\n"); + MSG_Add("PROGRAM_CONFIG_SET_SYNTAX","Correct syntax: config -set \"section property=value\".\n"); + MSG_Add("PROGRAM_CONFIG_GET_SYNTAX","Correct syntax: config -get \"section property\".\n"); + MSG_Add("PROGRAM_CONFIG_PRINT_STARTUP","\nDOSBox-X was started with the following command line parameters:\n%s\n"); + MSG_Add("PROGRAM_CONFIG_MISSINGPARAM","Missing parameter.\n"); + } + \ No newline at end of file diff --git a/src/misc/savestates.cpp b/src/misc/savestates.cpp index a1f8e767080..0523499899a 100644 --- a/src/misc/savestates.cpp +++ b/src/misc/savestates.cpp @@ -1,929 +1,946 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include "SDL.h" -#include "menu.h" -#include "shell.h" -#include "cross.h" -#include "render.h" -#include "mapper.h" -#include "control.h" -#include "logging.h" -#include "mixer.h" -#include "build_timestamp.h" -#ifdef WIN32 -#include "direct.h" -#endif -#if defined (__OpenBSD__) || defined (__APPLE__) -#else -#include -#endif -#if defined(unix) || defined(__APPLE__) -# include -#endif - -#define MAXU32 0xffffffff -#include "zip.h" -#include "unzip.h" -#include "ioapi.h" -#include "vs/zlib/contrib/minizip/zip.c" -#include "vs/zlib/contrib/minizip/unzip.c" -#include "vs/zlib/contrib/minizip/ioapi.c" -#include "zipcppstdbuf.h" -#if !defined(HX_DOS) -#include "../libs/tinyfiledialogs/tinyfiledialogs.h" -#endif - -#ifdef C_SDL2 -extern SDL_AudioDeviceID SDL2_AudioDevice; /* valid IDs are 2 or higher, 1 for compat, 0 is never a valid ID */ -#endif - -extern unsigned int page; -extern int autosave_last[10], autosave_count; -extern std::string autosave_name[10], savefilename; -extern bool use_save_file, clearline, dos_kernel_disabled; -extern const char* RunningProgram; -bool auto_save_state=false; -bool noremark_save_state = false; -bool force_load_state = false; -std::string saveloaderr=""; -void refresh_slots(void); -void GFX_LosingFocus(void), GFX_ReleaseMouse(void), MAPPER_ReleaseAllKeys(void), resetFontSize(void); -bool systemmessagebox(char const * aTitle, char const * aMessage, char const * aDialogType, char const * aIconType, int aDefaultButton); - -namespace -{ - std::string getTime(bool date=false) - { - const time_t current = time(NULL); - tm* timeinfo; - timeinfo = localtime(¤t); //convert to local time - char buffer[80]; - if (date) - ::strftime(buffer, 80, "%Y-%m-%d %H:%M", timeinfo); - else - ::strftime(buffer, 50, "%H:%M:%S", timeinfo); - return buffer; - } - - std::string getType() { - switch (machine) { - case MCH_HERC: - return "MCH_HERC"; - case MCH_CGA: - return "MCH_CGA"; - case MCH_TANDY: - return "MCH_TANDY"; - case MCH_PCJR: - return "MCH_PCJR"; - case MCH_EGA: - return "MCH_EGA"; - case MCH_VGA: - return "MCH_VGA"; - case MCH_AMSTRAD: - return "MCH_AMSTRAD"; - case MCH_PC98: - return "MCH_PC98"; - case MCH_FM_TOWNS: - return "MCH_FM_TOWNS"; - case MCH_MCGA: - return "MCH_MCGA"; - case MCH_MDA: - return "MCH_MDA"; - default: - return "MCH_OTHER"; - } - } - - size_t GetGameState(); - - class SlotPos - { - public: - SlotPos() : slot(0) {} - - void next() - { - ++slot; - slot %= SaveState::SLOT_COUNT*SaveState::MAX_PAGE; - if (page!=GetGameState()/SaveState::SLOT_COUNT) { - page=(unsigned int)GetGameState()/SaveState::SLOT_COUNT; - refresh_slots(); - } - } - - void previous() - { - slot += SaveState::SLOT_COUNT*SaveState::MAX_PAGE - 1; - slot %= SaveState::SLOT_COUNT*SaveState::MAX_PAGE; - if (page!=GetGameState()/SaveState::SLOT_COUNT) { - page=(unsigned int)GetGameState()/SaveState::SLOT_COUNT; - refresh_slots(); - } - } - - void set(int value) - { - slot = value; - } - - operator size_t() const - { - return slot; - } - private: - size_t slot; - }; - - SlotPos currentSlot; - - void notifyError(const std::string& message, bool log=true) - { - if (log) LOG_MSG("%s",message.c_str()); - systemmessagebox("Error",message.c_str(),"ok","error", 1); - } - - size_t GetGameState(void) { - return currentSlot; - } - - void SetGameState(int value) { - char name[6]="slot0"; - name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); - mainMenu.get_item(name).check(false).refresh_item(mainMenu); - currentSlot.set(value); - if (page!=currentSlot/SaveState::SLOT_COUNT) { - page=(unsigned int)(currentSlot/SaveState::SLOT_COUNT); - refresh_slots(); - } - name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); - mainMenu.get_item(name).check(true).refresh_item(mainMenu); - const bool emptySlot = SaveState::instance().isEmpty(currentSlot); - LOG_MSG("Active save slot: %d %s", (int)currentSlot + 1, emptySlot ? "[Empty]" : ""); - } - - void SaveGameState(bool pressed) { - if (!pressed) return; - - try - { - LOG_MSG("Saving state to slot: %d", (int)currentSlot + 1); - SaveState::instance().save(currentSlot); - if (page!=GetGameState()/SaveState::SLOT_COUNT) - SetGameState((int)currentSlot); - else - refresh_slots(); - } - catch (const SaveState::Error& err) - { - notifyError(err); - } - } - - - void LoadGameState(bool pressed) { - if (!pressed) return; - - // if (SaveState::instance().isEmpty(currentSlot)) - // { - // LOG_MSG("[%s]: State %d is empty!", getTime().c_str(), currentSlot + 1); - // return; - // } - if (!GFX_IsFullscreen()&&render.aspect) GFX_LosingFocus(); - try - { - LOG_MSG("Loading state from slot: %d", (int)currentSlot + 1); - SaveState::instance().load(currentSlot); -#if defined(USE_TTF) - if (ttf.inUse) resetFontSize(); -#endif - } - catch (const SaveState::Error& err) - { - notifyError(err); - } - } - - void NextSaveSlot(bool pressed) { - if (!pressed) return; - - char name[6]="slot0"; - name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); - mainMenu.get_item(name).check(false).refresh_item(mainMenu); - currentSlot.next(); - if (currentSlot/SaveState::SLOT_COUNT==page) { - name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); - mainMenu.get_item(name).check(true).refresh_item(mainMenu); - } - - const bool emptySlot = SaveState::instance().isEmpty(currentSlot); - LOG_MSG("Active save slot: %d %s", (int)currentSlot + 1, emptySlot ? "[Empty]" : ""); - } - - void PreviousSaveSlot(bool pressed) { - if (!pressed) return; - - char name[6]="slot0"; - name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); - mainMenu.get_item(name).check(false).refresh_item(mainMenu); - currentSlot.previous(); - if (currentSlot/SaveState::SLOT_COUNT==page) { - name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); - mainMenu.get_item(name).check(true).refresh_item(mainMenu); - } - - const bool emptySlot = SaveState::instance().isEmpty(currentSlot); - LOG_MSG("Active save slot: %d %s", (int)currentSlot + 1, emptySlot ? "[Empty]" : ""); - } - - void LastAutoSaveSlot(bool pressed) { - if (!pressed) return; - int index=0; - for (int i=1; i<10&&i<=autosave_count; i++) if (autosave_name[i].size()&&!strcasecmp(RunningProgram, autosave_name[i].c_str())) index=i; - if (autosave_last[index]<1) return; - - char name[6]="slot0"; - name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); - mainMenu.get_item(name).check(false).refresh_item(mainMenu); - currentSlot.set(autosave_last[index]-1); - if (page!=currentSlot/SaveState::SLOT_COUNT) { - page=(unsigned int)(currentSlot/SaveState::SLOT_COUNT); - refresh_slots(); - } - name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); - mainMenu.get_item(name).check(true).refresh_item(mainMenu); - - const bool emptySlot = SaveState::instance().isEmpty(currentSlot); - LOG_MSG("Active save slot: %d %s", (int)currentSlot + 1, emptySlot ? "[Empty]" : ""); - } -} - -std::string GetPlatform(bool save) { - char platform[30]; - strcpy(platform, -#if defined(HX_DOS) - "DOS " -#elif defined(__MINGW32__) - "MinGW " -#elif defined(WIN32) - "Windows " -#elif defined(LINUX) - "Linux " -#elif unix - "Unix " -#elif defined(MACOSX) - "macOS " -#elif defined(OS2) - "OS/2 " -#else - save?"Other ":"" -#endif - ); - if (!save) strcat(platform, (std::string(SDL_STRING)+", ").c_str()); -#if defined(_M_X64) || defined (_M_AMD64) || defined (_M_ARM64) || defined (_M_IA64) || defined(__ia64__) || defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(__aarch64__) || defined(__powerpc64__) - strcat(platform, "64"); -#else - strcat(platform, "32"); -#endif - strcat(platform, save?"-bit build":"-bit"); - return std::string(platform); -} - -size_t GetGameState_Run(void) { return GetGameState(); } -void SetGameState_Run(int value) { SetGameState(value); } -void SaveGameState_Run(void) { SaveGameState(true); } -void LoadGameState_Run(void) { LoadGameState(true); } -void NextSaveSlot_Run(void) { NextSaveSlot(true); } -void PreviousSaveSlot_Run(void) { PreviousSaveSlot(true); } -void LastAutoSaveSlot_Run(void) { LastAutoSaveSlot(true); } - -void ShowStateInfo(bool pressed) { - if (!pressed) return; - std::string message = "Save to: "+(use_save_file&&savefilename.size()?"File "+savefilename:"Slot "+std::to_string(GetGameState_Run()+1))+"\n"+SaveState::instance().getName(GetGameState_Run(), true); - systemmessagebox("Saved state information", message.c_str(), "ok","info", 1); -} - -void AddSaveStateMapper() { - DOSBoxMenu::item *item; - MAPPER_AddHandler(SaveGameState, MK_s, MMODHOST,"savestate","Save state", &item); - item->set_text("Save state"); - MAPPER_AddHandler(LoadGameState, MK_l, MMODHOST,"loadstate","Load state", &item); - item->set_text("Load state"); - MAPPER_AddHandler(ShowStateInfo, MK_nothing, 0,"showstate","Display state info", &item); - item->set_text("Display state information"); - MAPPER_AddHandler(PreviousSaveSlot, MK_comma, MMODHOST,"prevslot","Previous save slot", &item); - item->set_text("Select previous slot"); - MAPPER_AddHandler(NextSaveSlot, MK_period, MMODHOST,"nextslot","Next save slot", &item); - item->set_text("Select next slot"); -} - -#ifndef WIN32 -char* itoa(int value, char* str, int radix) { - /** - * C++ version 0.4 char* style "itoa": - * Written by Lukás Chmela - * Released under GPLv3. - */ - // check that the radix if valid - if (radix < 2 || radix > 36) { *str = '\0'; return str; } - - char* ptr = str, *ptr1 = str, tmp_char; - int tmp_value; - - do { - tmp_value = value; - value /= radix; - *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * radix)]; - } while ( value ); - - // Apply negative sign - if (tmp_value < 0) *ptr++ = '-'; - *ptr-- = '\0'; - while(ptr1 < ptr) { - tmp_char = *ptr; - *ptr--= *ptr1; - *ptr1++ = tmp_char; - } - return str; -} -#endif - -SaveState& SaveState::instance() { - static SaveState singleton; - return singleton; -} - -void SaveState::registerComponent(const std::string& uniqueName, Component& comp) { - components.insert(std::make_pair(uniqueName, CompData(comp))); -} - -#define CASESENSITIVITY (0) -#define MAXFILENAME (256) - -void zipSetCurrentTime(zip_fileinfo &zi) { - zi.dosDate = 0; - zi.internal_fa = 0; - zi.external_fa = 0; - zi.tmz_date.tm_sec = 0; - zi.tmz_date.tm_min = 0; - zi.tmz_date.tm_hour = 0; - zi.tmz_date.tm_mday = 0; - zi.tmz_date.tm_mon = 0; - zi.tmz_date.tm_year = 0; - - time_t tm_t = time(NULL); - struct tm* filedate = localtime(&tm_t); - if (filedate != NULL) { - zi.tmz_date.tm_sec = filedate->tm_sec; - zi.tmz_date.tm_min = filedate->tm_min; - zi.tmz_date.tm_hour = filedate->tm_hour; - zi.tmz_date.tm_mday = filedate->tm_mday; - zi.tmz_date.tm_mon = filedate->tm_mon; - zi.tmz_date.tm_year = filedate->tm_year; - } -} - -#ifdef __APPLE__ -// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions -#define FOPEN_FUNC(filename, mode) fopen(filename, mode) -#define FTELLO_FUNC(stream) ftello(stream) -#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) -#else -#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) -#define FTELLO_FUNC(stream) ftello64(stream) -#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) -#endif - -int flagged_backup(char *zip); -int flagged_restore(char* zip); - -int zipOutOpenFile(zipFile zf,const char *zfname,zip_fileinfo &zi,const bool compress) { - const int opt_compress_level = compress ? 9 : 0; - - return zipOpenNewFileInZip3_64(zf,zfname,&zi, - NULL,0,NULL,0,NULL/* comment*/, - (opt_compress_level != 0) ? Z_DEFLATED : 0, - opt_compress_level,0, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL/*password*/,0/*crcFile*/,1/*zip64*/); -} - -void SaveState::save(size_t slot) { //throw (Error) - if (slot >= SLOT_COUNT*MAX_PAGE) return; -#ifdef C_SDL2 - SDL_PauseAudioDevice(SDL2_AudioDevice, 0); -#else - SDL_PauseAudio(0); -#endif - bool save_err=false; - if((MEM_TotalPages()*4096/1024/1024)>1024) { - LOG_MSG("Stopped. 1 GB is the maximum memory size for saving/loading states."); - notifyError("Unsupported memory size for saving states.", false); - return; - } - bool compresssaveparts = static_cast(control->GetSection("dosbox"))->Get_bool("compresssaveparts"); - const char *save_remark = ""; -#if !defined(HX_DOS) - if (auto_save_state) - save_remark = "Auto-save"; - else if (!noremark_save_state) { - /* NTS: tinyfd_inputBox() returns a string from an internal statically declared char array. - * It is not necessary to free the return string, but it is important to understand that - * the next call to tinyfd_inputBox() will obliterate the previously returned string. - * See src/libs/tinyfiledialogs/tinyfiledialogs.c line 5069 --J.C. */ - /* NTS: The code was originally written to declare save_remark as char* default assigned to string - * constant "", but GCC (rightfully so) complains you're pointing char* at something that - * is stored const by the compiler. "save_remark" is not modified past this point, so it - * has been changed to const char* and the return value of tinyfd_inputBox() is given to - * a local temporary char* string where the modification can be made, and *then* assigned - * to the const char* string for the rest of this function. */ - bool fs=GFX_IsFullscreen(); - if (fs) GFX_SwitchFullScreen(); - MAPPER_ReleaseAllKeys(); - GFX_LosingFocus(); - GFX_ReleaseMouse(); - char *new_remark = tinyfd_inputBox("Save state", "Please enter remark for the state (optional; 30 characters maximum). Click the Cancel button to cancel the saving.", " "); - MAPPER_ReleaseAllKeys(); - GFX_LosingFocus(); - if (fs&&!GFX_IsFullscreen()) GFX_SwitchFullScreen(); - if (new_remark==NULL) return; - new_remark=trim(new_remark); - if (strlen(new_remark)>30) new_remark[30]=0; - save_remark = new_remark; - } -#endif - int errclose; - std::string path; - bool Get_Custom_SaveDir(std::string& savedir); - if(Get_Custom_SaveDir(path)) { - path+=CROSS_FILESPLIT; - } else { - extern std::string capturedir; - const size_t last_slash_idx = capturedir.find_last_of("\\/"); - if (std::string::npos != last_slash_idx) { - path = capturedir.substr(0, last_slash_idx); - } else { - path = "."; - } - path+=CROSS_FILESPLIT; - path+="save"; - Cross::CreateDir(path); - path+=CROSS_FILESPLIT; - } - - std::string temp, save2; - std::stringstream slotname; - slotname << slot+1; - temp=path; - std::string save=use_save_file&&savefilename.size()?savefilename:temp+slotname.str()+".sav"; - - zipFile zf; - { - const char *global_comment = "DOSBox-X save state"; - zlib_filefunc64_def ffunc; -#ifdef USEWIN32IOAPI - fill_win32_filefunc64A(&ffunc); -#else - fill_fopen64_filefunc(&ffunc); -#endif - remove(save.c_str()); - zf = zipOpen2_64(save.c_str(),APPEND_STATUS_CREATE,&global_comment,&ffunc); - } - if (zf == NULL) { save_err = true; goto done; } - - { - zip_fileinfo zi; zipSetCurrentTime(zi); - if ((errclose=zipOutOpenFile(zf,"DOSBox-X_Version",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } - zip_ostreambuf zos(zf); std::ostream emulatorversion(&zos); - - emulatorversion << "DOSBox-X " << VERSION << " (" << SDL_STRING << ")" << std::endl << GetPlatform(true) << std::endl << UPDATED_STR; - /* 2025/01/12: Backwards compat: The old code compressed data to zlib, even though the ZIP support code - * already applies compression. This is to tell the old code that we did not compress the - * data (the ZIP support code did though). */ - emulatorversion << std::endl << "No compression"; - - if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } - } - { - zip_fileinfo zi; zipSetCurrentTime(zi); - if ((errclose=zipOutOpenFile(zf,"Program_Name",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } - zip_ostreambuf zos(zf); std::ostream programname(&zos); - - programname << RunningProgram; - - if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } - } - { - zip_fileinfo zi; zipSetCurrentTime(zi); - if ((errclose=zipOutOpenFile(zf,"Memory_Size",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } - zip_ostreambuf zos(zf); std::ostream memorysize(&zos); - - memorysize << MEM_TotalPages(); - - if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } - } - { - zip_fileinfo zi; zipSetCurrentTime(zi); - if ((errclose=zipOutOpenFile(zf,"Machine_Type",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } - zip_ostreambuf zos(zf); std::ostream machinetype(&zos); - - machinetype << getType(); - - if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } - } - { - zip_fileinfo zi; zipSetCurrentTime(zi); - if ((errclose=zipOutOpenFile(zf,"Time_Stamp",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } - zip_ostreambuf zos(zf); std::ostream timestamp(&zos); - - timestamp << getTime(true); - - if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } - } - { - zip_fileinfo zi; zipSetCurrentTime(zi); - if ((errclose=zipOutOpenFile(zf,"Save_Remark",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } - zip_ostreambuf zos(zf); std::ostream saveremark(&zos); - - saveremark << std::string(save_remark); - - if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } - } - for (CompEntry::iterator i = components.begin(); i != components.end(); ++i) { - zip_fileinfo zi; zipSetCurrentTime(zi); - if ((errclose=zipOutOpenFile(zf,i->first.c_str(),zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } - zip_ostreambuf zos(zf); std::ostream ss(&zos); - - i->second.comp.getBytes(ss); - - if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } - } - -done: - if (zf != NULL) { - errclose = zipClose(zf,NULL); - if (errclose != ZIP_OK) save_err = true; - } - - if (!dos_kernel_disabled) flagged_backup((char *)save.c_str()); - - if (save_err) - notifyError("Failed to save the current state."); - else - LOG_MSG("[%s]: Saved. (Slot %d)", getTime().c_str(), (int)slot+1); -} - -void savestatecorrupt(const char* part) { - LOG_MSG("Save state corrupted! Program in inconsistent state! - %s", part); - systemmessagebox("Error","Save state corrupted! Program may not work.","ok","error", 1); -} - -bool confres=false; -bool loadstateconfirm(int ind) { - if (ind<0||ind>4) return false; - confres=true; - GUI_Shortcut(23+ind); - bool ret=confres; - confres=false; - return ret; -} - -void SaveState::load(size_t slot) const { //throw (Error) - // if (isEmpty(slot)) return; - bool load_err=false; - if((MEM_TotalPages()*4096/1024/1024)>1024) { - LOG_MSG("Stopped. 1 GB is the maximum memory size for saving/loading states."); - notifyError("Unsupported memory size for loading states.", false); - return; - } -#ifdef C_SDL2 - SDL_PauseAudioDevice(SDL2_AudioDevice, 0); -#else - SDL_PauseAudio(0); -#endif - extern const char* RunningProgram; - std::string path; - int err; - bool Get_Custom_SaveDir(std::string& savedir); - if(Get_Custom_SaveDir(path)) { - path+=CROSS_FILESPLIT; - } else { - extern std::string capturedir; - const size_t last_slash_idx = capturedir.find_last_of("\\/"); - if (std::string::npos != last_slash_idx) { - path = capturedir.substr(0, last_slash_idx); - } else { - path = "."; - } - path += CROSS_FILESPLIT; - path +="save"; - path += CROSS_FILESPLIT; - } - std::string temp; - temp = path; - std::stringstream slotname; - slotname << slot+1; - std::string save=use_save_file&&savefilename.size()?savefilename:temp+slotname.str()+".sav"; - std::ifstream check_slot; - check_slot.open(save.c_str(), std::ifstream::in); - if(check_slot.fail()) { - LOG_MSG("No saved slot - %d (%s)",(int)slot+1,save.c_str()); - notifyError(use_save_file&&savefilename.size()?"The selected save file is currently empty.":"The selected save slot is an empty slot.", false); - load_err=true; - return; - } - check_slot.close(); - - unz_file_info64 file_info; - unzFile zf; - { - zlib_filefunc64_def ffunc; -#ifdef USEWIN32IOAPI - fill_win32_filefunc64A(&ffunc); -#else - fill_fopen64_filefunc(&ffunc); -#endif - zf = unzOpen2_64(save.c_str(),&ffunc); - } - if (zf == NULL) { load_err=true; goto done; } - - { - if ((err=unzLocateFile(zf,"DOSBox-X_Version",1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } - zip_istreambuf zis(zf); - - char buffer[4096]; - std::streamsize sz = zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)-1); buffer[sz] = 0; - - char *p; - if (strstr(buffer, "\nNo compression") != NULL) { - /* 2025/01/12: Removal of this string is required to match version string below even if now ignored */ - p=strrchr(buffer, '\n'); - if (p!=NULL) *p=0; - } - p=strrchr(buffer, '\n'); /* Remove i.e. "Linux" */ - if (p!=NULL) *p=0; - std::string emulatorversion = std::string("DOSBox-X ") + VERSION + std::string(" (") + SDL_STRING + std::string(")"); - if (strcasecmp(buffer,emulatorversion.c_str())) { - if(!force_load_state&&!loadstateconfirm(0)) { - LOG_MSG("Aborted. Check your DOSBox-X version: %s",buffer); - load_err=true; - goto done; - } - } - - if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } - } - - { - if ((err=unzLocateFile(zf,"Program_Name",1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } - zip_istreambuf zis(zf); - - char buffer[4096]; - size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)-1); buffer[length] = 0; - - if (!length||(size_t)length!=strlen(RunningProgram)||strncmp(buffer,RunningProgram,length)) { - if(!force_load_state&&!loadstateconfirm(1)) { - buffer[length]='\0'; - LOG_MSG("Aborted. Check your program name: %s",buffer); - load_err=true; - goto done; - } - if (length<9) { - static char pname[9]; - if (length) { - strncpy(pname,buffer,length); - pname[length]=0; - } else - strcpy(pname, "DOSBOX-X"); - RunningProgram=pname; - void GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused); - GFX_SetTitle(-1,-1,-1,false); - } - } - - if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } - } - - { - if ((err=unzLocateFile(zf,"Memory_Size",1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } - zip_istreambuf zis(zf); - - char buffer[4096]; - size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)-1); buffer[length] = 0; - - char str[10]; - itoa((int)MEM_TotalPages(), str, 10); - if(!length||(size_t)length!=strlen(str)||strncmp(buffer,str,length)) { - if(!force_load_state&&!loadstateconfirm(2)) { - buffer[length]='\0'; - int size=atoi(buffer)*4096/1024/1024; - LOG_MSG("Aborted. Check your memory size: %d MB", size); - load_err=true; - goto done; - } - } - - if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } - } - - { - if ((err=unzLocateFile(zf,"Machine_Type",1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } - zip_istreambuf zis(zf); - - char buffer[4096]; - size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)-1); buffer[length] = 0; - - char str[20]; - strcpy(str, getType().c_str()); - if(!length||(size_t)length!=strlen(str)||strncmp(buffer,str,length)) { - if(!force_load_state&&!loadstateconfirm(3)) { - LOG_MSG("Aborted. Check your machine type: %s",buffer); - load_err=true; - goto done; - } - } - - if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } - } - - for (CompEntry::const_iterator i = components.begin(); i != components.end(); ++i) { - if ((err=unzLocateFile(zf,i->first.c_str(),1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } - if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } - zip_istreambuf zis(zf); std::istream ss(&zis); - - i->second.comp.setBytes(ss); - - if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } - } - -done: - if (zf != NULL) { - err = unzClose(zf); - if (err != UNZ_OK) load_err = true; - } - - if (!dos_kernel_disabled) flagged_restore((char *)save.c_str()); - if (!load_err) LOG_MSG("[%s]: Loaded. (Slot %d)", getTime().c_str(), (int)slot+1); -} - -bool SaveState::isEmpty(size_t slot) const { - if (slot >= SLOT_COUNT*MAX_PAGE) return true; - std::string path; - bool Get_Custom_SaveDir(std::string& savedir); - if(Get_Custom_SaveDir(path)) { - path+=CROSS_FILESPLIT; - } else { - extern std::string capturedir; - const size_t last_slash_idx = capturedir.find_last_of("\\/"); - if (std::string::npos != last_slash_idx) { - path = capturedir.substr(0, last_slash_idx); - } else { - path = "."; - } - path += CROSS_FILESPLIT; - path +="save"; - path += CROSS_FILESPLIT; - } - std::string temp; - temp = path; - std::stringstream slotname; - slotname << slot+1; - std::string save=temp+slotname.str()+".sav"; - std::ifstream check_slot; - check_slot.open(save.c_str(), std::ifstream::in); - return check_slot.fail(); -} - -void SaveState::removeState(size_t slot) const { - if (slot >= SLOT_COUNT*MAX_PAGE) return; - std::string path; - bool Get_Custom_SaveDir(std::string& savedir); - if(Get_Custom_SaveDir(path)) { - path+=CROSS_FILESPLIT; - } else { - extern std::string capturedir; - const size_t last_slash_idx = capturedir.find_last_of("\\/"); - if (std::string::npos != last_slash_idx) { - path = capturedir.substr(0, last_slash_idx); - } else { - path = "."; - } - path += CROSS_FILESPLIT; - path +="save"; - path += CROSS_FILESPLIT; - } - std::string temp; - temp = path; - std::stringstream slotname; - slotname << slot+1; - std::string save=temp+slotname.str()+".sav"; - std::ifstream check_slot; - check_slot.open(save.c_str(), std::ifstream::in); - if(check_slot.fail()) { - LOG_MSG("No saved slot - %d (%s)",(int)slot+1,save.c_str()); - notifyError("The selected save slot is an empty slot.", false); - return; - } - if (loadstateconfirm(4)) { - check_slot.close(); - remove(save.c_str()); - check_slot.open(save.c_str(), std::ifstream::in); - if (!check_slot.fail()) notifyError("Failed to remove the state in the save slot."); - if (page!=GetGameState()/SaveState::SLOT_COUNT) - SetGameState((int)slot); - else - refresh_slots(); - } -} - -std::string SaveState::getName(size_t slot, bool nl) const { - if (slot >= SLOT_COUNT*MAX_PAGE) return "["+std::string(MSG_Get("EMPTY_SLOT"))+"]"; - std::string path; - bool Get_Custom_SaveDir(std::string& savedir); - if(Get_Custom_SaveDir(path)) { - path+=CROSS_FILESPLIT; - } else { - extern std::string capturedir; - const size_t last_slash_idx = capturedir.find_last_of("\\/"); - if (std::string::npos != last_slash_idx) { - path = capturedir.substr(0, last_slash_idx); - } else { - path = "."; - } - path += CROSS_FILESPLIT; - path +="save"; - path += CROSS_FILESPLIT; - } - std::string temp; - temp = path; - std::stringstream slotname; - slotname << slot+1; - std::string save=nl&&use_save_file&&savefilename.size()?savefilename:temp+slotname.str()+".sav"; - std::ifstream check_slot; - check_slot.open(save.c_str(), std::ifstream::in); - if (check_slot.fail()) return nl?"(Empty state)":"["+std::string(MSG_Get("EMPTY_SLOT"))+"]"; - check_slot.close(); - - unzFile zf; - { - zlib_filefunc64_def ffunc; -#ifdef USEWIN32IOAPI - fill_win32_filefunc64A(&ffunc); -#else - fill_fopen64_filefunc(&ffunc); -#endif - zf = unzOpen2_64(save.c_str(),&ffunc); - } - if (zf == NULL) return "(Error slot)"; - - int err; - std::string ret; - char buffer1[4096]; - unz_file_info64 file_info; - - if ( (err=unzLocateFile(zf,"Program_Name",1/*case sensitive*/)) == UNZ_OK && - (err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) == UNZ_OK) { - if ((err=unzOpenCurrentFile(zf)) == UNZ_OK) { - zip_istreambuf zis(zf); - size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer1,sizeof(buffer1)-1); buffer1[length] = 0; - zis.close(); - ret += nl?"Program: "+(!strlen(buffer1)?"-":std::string(buffer1))+"\n":"[Program: "+std::string(buffer1)+"]"; - } - } - - if ( (err=unzLocateFile(zf,"Time_Stamp",1/*case sensitive*/)) == UNZ_OK && - (err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) == UNZ_OK) { - if ((err=unzOpenCurrentFile(zf)) == UNZ_OK) { - zip_istreambuf zis(zf); - size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer1,sizeof(buffer1)-1); buffer1[length] = 0; - zis.close(); - ret += nl?"Timestamp: "+(!strlen(buffer1)?"-":std::string(buffer1))+"\n":" ("+std::string(buffer1)+")"; - } - } - - if ( (err=unzLocateFile(zf,"Save_Remark",1/*case sensitive*/)) == UNZ_OK && - (err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) == UNZ_OK) { - if ((err=unzOpenCurrentFile(zf)) == UNZ_OK) { - zip_istreambuf zis(zf); - size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer1,sizeof(buffer1)-1); buffer1[length] = 0; - zis.close(); - if (length != 0) ret += nl?"Remark: "+(!strlen(buffer1)?"-":std::string(buffer1))+"\n":" - "+std::string(buffer1); - } - } - - return ret; -} +#include +#include +#include +#include +#include +#include +#include +#include +#include "SDL.h" +#include "menu.h" +#include "shell.h" +#include "cross.h" +#include "render.h" +#include "mapper.h" +#include "control.h" +#include "logging.h" +#include "mixer.h" +#include "build_timestamp.h" +#ifdef WIN32 +#include "direct.h" +#endif +#if defined (__OpenBSD__) || defined (__APPLE__) +#else +#include +#endif +#if defined(unix) || defined(__APPLE__) +# include +#endif + +#define MAXU32 0xffffffff +// #include "zip.h" +// #include "unzip.h" +// #include "ioapi.h" + +#ifdef C_LIBZ +#include "vs/zlib/contrib/minizip/zip.c" +#include "vs/zlib/contrib/minizip/unzip.c" +#include "vs/zlib/contrib/minizip/ioapi.c" +#include "zipcppstdbuf.h" +#endif + +#if !defined(HX_DOS) +#include "../libs/tinyfiledialogs/tinyfiledialogs.h" +#endif + +#ifdef C_SDL2 +extern SDL_AudioDeviceID SDL2_AudioDevice; /* valid IDs are 2 or higher, 1 for compat, 0 is never a valid ID */ +#endif + +extern unsigned int page; +extern int autosave_last[10], autosave_count; +extern std::string autosave_name[10], savefilename; +extern bool use_save_file, clearline, dos_kernel_disabled; +extern const char* RunningProgram; +bool auto_save_state=false; +bool noremark_save_state = false; +bool force_load_state = false; +std::string saveloaderr=""; +void refresh_slots(void); +void GFX_LosingFocus(void), GFX_ReleaseMouse(void), MAPPER_ReleaseAllKeys(void), resetFontSize(void); +bool systemmessagebox(char const * aTitle, char const * aMessage, char const * aDialogType, char const * aIconType, int aDefaultButton); + +namespace +{ + std::string getTime(bool date=false) + { + const time_t current = time(NULL); + tm* timeinfo; + timeinfo = localtime(¤t); //convert to local time + char buffer[80]; + if (date) + ::strftime(buffer, 80, "%Y-%m-%d %H:%M", timeinfo); + else + ::strftime(buffer, 50, "%H:%M:%S", timeinfo); + return buffer; + } + + std::string getType() { + switch (machine) { + case MCH_HERC: + return "MCH_HERC"; + case MCH_CGA: + return "MCH_CGA"; + case MCH_TANDY: + return "MCH_TANDY"; + case MCH_PCJR: + return "MCH_PCJR"; + case MCH_EGA: + return "MCH_EGA"; + case MCH_VGA: + return "MCH_VGA"; + case MCH_AMSTRAD: + return "MCH_AMSTRAD"; + case MCH_PC98: + return "MCH_PC98"; + case MCH_FM_TOWNS: + return "MCH_FM_TOWNS"; + case MCH_MCGA: + return "MCH_MCGA"; + case MCH_MDA: + return "MCH_MDA"; + default: + return "MCH_OTHER"; + } + } + + size_t GetGameState(); + + class SlotPos + { + public: + SlotPos() : slot(0) {} + + void next() + { + ++slot; + slot %= SaveState::SLOT_COUNT*SaveState::MAX_PAGE; + if (page!=GetGameState()/SaveState::SLOT_COUNT) { + page=(unsigned int)GetGameState()/SaveState::SLOT_COUNT; + refresh_slots(); + } + } + + void previous() + { + slot += SaveState::SLOT_COUNT*SaveState::MAX_PAGE - 1; + slot %= SaveState::SLOT_COUNT*SaveState::MAX_PAGE; + if (page!=GetGameState()/SaveState::SLOT_COUNT) { + page=(unsigned int)GetGameState()/SaveState::SLOT_COUNT; + refresh_slots(); + } + } + + void set(int value) + { + slot = value; + } + + operator size_t() const + { + return slot; + } + private: + size_t slot; + }; + + SlotPos currentSlot; + + void notifyError(const std::string& message, bool log=true) + { + if (log) LOG_MSG("%s",message.c_str()); + systemmessagebox("Error",message.c_str(),"ok","error", 1); + } + + size_t GetGameState(void) { + return currentSlot; + } + + void SetGameState(int value) { + char name[6]="slot0"; + name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); + mainMenu.get_item(name).check(false).refresh_item(mainMenu); + currentSlot.set(value); + if (page!=currentSlot/SaveState::SLOT_COUNT) { + page=(unsigned int)(currentSlot/SaveState::SLOT_COUNT); + refresh_slots(); + } + name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); + mainMenu.get_item(name).check(true).refresh_item(mainMenu); + const bool emptySlot = SaveState::instance().isEmpty(currentSlot); + LOG_MSG("Active save slot: %d %s", (int)currentSlot + 1, emptySlot ? "[Empty]" : ""); + } + + void SaveGameState(bool pressed) { + if (!pressed) return; + + try + { + LOG_MSG("Saving state to slot: %d", (int)currentSlot + 1); + SaveState::instance().save(currentSlot); + if (page!=GetGameState()/SaveState::SLOT_COUNT) + SetGameState((int)currentSlot); + else + refresh_slots(); + } + catch (const SaveState::Error& err) + { + notifyError(err); + } + } + + + void LoadGameState(bool pressed) { + if (!pressed) return; + + // if (SaveState::instance().isEmpty(currentSlot)) + // { + // LOG_MSG("[%s]: State %d is empty!", getTime().c_str(), currentSlot + 1); + // return; + // } + if (!GFX_IsFullscreen()&&render.aspect) GFX_LosingFocus(); + try + { + LOG_MSG("Loading state from slot: %d", (int)currentSlot + 1); + SaveState::instance().load(currentSlot); +#if defined(USE_TTF) + if (ttf.inUse) resetFontSize(); +#endif + } + catch (const SaveState::Error& err) + { + notifyError(err); + } + } + + void NextSaveSlot(bool pressed) { + if (!pressed) return; + + char name[6]="slot0"; + name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); + mainMenu.get_item(name).check(false).refresh_item(mainMenu); + currentSlot.next(); + if (currentSlot/SaveState::SLOT_COUNT==page) { + name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); + mainMenu.get_item(name).check(true).refresh_item(mainMenu); + } + + const bool emptySlot = SaveState::instance().isEmpty(currentSlot); + LOG_MSG("Active save slot: %d %s", (int)currentSlot + 1, emptySlot ? "[Empty]" : ""); + } + + void PreviousSaveSlot(bool pressed) { + if (!pressed) return; + + char name[6]="slot0"; + name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); + mainMenu.get_item(name).check(false).refresh_item(mainMenu); + currentSlot.previous(); + if (currentSlot/SaveState::SLOT_COUNT==page) { + name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); + mainMenu.get_item(name).check(true).refresh_item(mainMenu); + } + + const bool emptySlot = SaveState::instance().isEmpty(currentSlot); + LOG_MSG("Active save slot: %d %s", (int)currentSlot + 1, emptySlot ? "[Empty]" : ""); + } + + void LastAutoSaveSlot(bool pressed) { + if (!pressed) return; + int index=0; + for (int i=1; i<10&&i<=autosave_count; i++) if (autosave_name[i].size()&&!strcasecmp(RunningProgram, autosave_name[i].c_str())) index=i; + if (autosave_last[index]<1) return; + + char name[6]="slot0"; + name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); + mainMenu.get_item(name).check(false).refresh_item(mainMenu); + currentSlot.set(autosave_last[index]-1); + if (page!=currentSlot/SaveState::SLOT_COUNT) { + page=(unsigned int)(currentSlot/SaveState::SLOT_COUNT); + refresh_slots(); + } + name[4]='0'+(char)(currentSlot%SaveState::SLOT_COUNT); + mainMenu.get_item(name).check(true).refresh_item(mainMenu); + + const bool emptySlot = SaveState::instance().isEmpty(currentSlot); + LOG_MSG("Active save slot: %d %s", (int)currentSlot + 1, emptySlot ? "[Empty]" : ""); + } +} + +std::string GetPlatform(bool save) { + char platform[30]; + strcpy(platform, +#if defined(HX_DOS) + "DOS " +#elif defined(__MINGW32__) + "MinGW " +#elif defined(WIN32) + "Windows " +#elif defined(LINUX) + "Linux " +#elif unix + "Unix " +#elif defined(MACOSX) + "macOS " +#elif defined(OS2) + "OS/2 " +#else + save?"Other ":"" +#endif + ); + if (!save) strcat(platform, (std::string(SDL_STRING)+", ").c_str()); +#if defined(_M_X64) || defined (_M_AMD64) || defined (_M_ARM64) || defined (_M_IA64) || defined(__ia64__) || defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(__aarch64__) || defined(__powerpc64__) + strcat(platform, "64"); +#else + strcat(platform, "32"); +#endif + strcat(platform, save?"-bit build":"-bit"); + return std::string(platform); +} + +size_t GetGameState_Run(void) { return GetGameState(); } +void SetGameState_Run(int value) { SetGameState(value); } +void SaveGameState_Run(void) { SaveGameState(true); } +void LoadGameState_Run(void) { LoadGameState(true); } +void NextSaveSlot_Run(void) { NextSaveSlot(true); } +void PreviousSaveSlot_Run(void) { PreviousSaveSlot(true); } +void LastAutoSaveSlot_Run(void) { LastAutoSaveSlot(true); } + +void ShowStateInfo(bool pressed) { + if (!pressed) return; + std::string message = "Save to: "+(use_save_file&&savefilename.size()?"File "+savefilename:"Slot "+std::to_string(GetGameState_Run()+1))+"\n"+SaveState::instance().getName(GetGameState_Run(), true); + systemmessagebox("Saved state information", message.c_str(), "ok","info", 1); +} + +void AddSaveStateMapper() { + DOSBoxMenu::item *item; + MAPPER_AddHandler(SaveGameState, MK_s, MMODHOST,"savestate","Save state", &item); + item->set_text("Save state"); + MAPPER_AddHandler(LoadGameState, MK_l, MMODHOST,"loadstate","Load state", &item); + item->set_text("Load state"); + MAPPER_AddHandler(ShowStateInfo, MK_nothing, 0,"showstate","Display state info", &item); + item->set_text("Display state information"); + MAPPER_AddHandler(PreviousSaveSlot, MK_comma, MMODHOST,"prevslot","Previous save slot", &item); + item->set_text("Select previous slot"); + MAPPER_AddHandler(NextSaveSlot, MK_period, MMODHOST,"nextslot","Next save slot", &item); + item->set_text("Select next slot"); +} + +#ifndef WIN32 +char* itoa(int value, char* str, int radix) { + /** + * C++ version 0.4 char* style "itoa": + * Written by Lukás Chmela + * Released under GPLv3. + */ + // check that the radix if valid + if (radix < 2 || radix > 36) { *str = '\0'; return str; } + + char* ptr = str, *ptr1 = str, tmp_char; + int tmp_value; + + do { + tmp_value = value; + value /= radix; + *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * radix)]; + } while ( value ); + + // Apply negative sign + if (tmp_value < 0) *ptr++ = '-'; + *ptr-- = '\0'; + while(ptr1 < ptr) { + tmp_char = *ptr; + *ptr--= *ptr1; + *ptr1++ = tmp_char; + } + return str; +} +#endif + +SaveState& SaveState::instance() { + static SaveState singleton; + return singleton; +} + +void SaveState::registerComponent(const std::string& uniqueName, Component& comp) { + components.insert(std::make_pair(uniqueName, CompData(comp))); +} + +#define CASESENSITIVITY (0) +#define MAXFILENAME (256) + +// void zipSetCurrentTime(zip_fileinfo &zi) { +// zi.dosDate = 0; +// zi.internal_fa = 0; +// zi.external_fa = 0; +// zi.tmz_date.tm_sec = 0; +// zi.tmz_date.tm_min = 0; +// zi.tmz_date.tm_hour = 0; +// zi.tmz_date.tm_mday = 0; +// zi.tmz_date.tm_mon = 0; +// zi.tmz_date.tm_year = 0; + +// time_t tm_t = time(NULL); +// struct tm* filedate = localtime(&tm_t); +// if (filedate != NULL) { +// zi.tmz_date.tm_sec = filedate->tm_sec; +// zi.tmz_date.tm_min = filedate->tm_min; +// zi.tmz_date.tm_hour = filedate->tm_hour; +// zi.tmz_date.tm_mday = filedate->tm_mday; +// zi.tmz_date.tm_mon = filedate->tm_mon; +// zi.tmz_date.tm_year = filedate->tm_year; +// } +// } + +#ifdef __APPLE__ +// In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions +#define FOPEN_FUNC(filename, mode) fopen(filename, mode) +#define FTELLO_FUNC(stream) ftello(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin) +#else +#define FOPEN_FUNC(filename, mode) fopen64(filename, mode) +#define FTELLO_FUNC(stream) ftello64(stream) +#define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin) +#endif + +int flagged_backup(char *zip); +int flagged_restore(char* zip); + +#ifdef C_LIBZ +int zipOutOpenFile(zipFile zf,const char *zfname,zip_fileinfo &zi,const bool compress) { + const int opt_compress_level = compress ? 9 : 0; + + return zipOpenNewFileInZip3_64(zf,zfname,&zi, + NULL,0,NULL,0,NULL/* comment*/, + (opt_compress_level != 0) ? Z_DEFLATED : 0, + opt_compress_level,0, + -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, + NULL/*password*/,0/*crcFile*/,1/*zip64*/); +} +#endif + +void SaveState::save(size_t slot) { //throw (Error) + if (slot >= SLOT_COUNT*MAX_PAGE) return; +#ifdef C_SDL2 + SDL_PauseAudioDevice(SDL2_AudioDevice, 0); +#else + SDL_PauseAudio(0); +#endif + bool save_err=false; + if((MEM_TotalPages()*4096/1024/1024)>1024) { + LOG_MSG("Stopped. 1 GB is the maximum memory size for saving/loading states."); + notifyError("Unsupported memory size for saving states.", false); + return; + } + bool compresssaveparts = static_cast(control->GetSection("dosbox"))->Get_bool("compresssaveparts"); + const char *save_remark = ""; +#if !defined(HX_DOS) + if (auto_save_state) + save_remark = "Auto-save"; + else if (!noremark_save_state) { + /* NTS: tinyfd_inputBox() returns a string from an internal statically declared char array. + * It is not necessary to free the return string, but it is important to understand that + * the next call to tinyfd_inputBox() will obliterate the previously returned string. + * See src/libs/tinyfiledialogs/tinyfiledialogs.c line 5069 --J.C. */ + /* NTS: The code was originally written to declare save_remark as char* default assigned to string + * constant "", but GCC (rightfully so) complains you're pointing char* at something that + * is stored const by the compiler. "save_remark" is not modified past this point, so it + * has been changed to const char* and the return value of tinyfd_inputBox() is given to + * a local temporary char* string where the modification can be made, and *then* assigned + * to the const char* string for the rest of this function. */ + bool fs=GFX_IsFullscreen(); + if (fs) GFX_SwitchFullScreen(); + MAPPER_ReleaseAllKeys(); + GFX_LosingFocus(); + GFX_ReleaseMouse(); + char *new_remark = tinyfd_inputBox("Save state", "Please enter remark for the state (optional; 30 characters maximum). Click the Cancel button to cancel the saving.", " "); + MAPPER_ReleaseAllKeys(); + GFX_LosingFocus(); + if (fs&&!GFX_IsFullscreen()) GFX_SwitchFullScreen(); + if (new_remark==NULL) return; + new_remark=trim(new_remark); + if (strlen(new_remark)>30) new_remark[30]=0; + save_remark = new_remark; + } +#endif + int errclose; + std::string path; + bool Get_Custom_SaveDir(std::string& savedir); + if(Get_Custom_SaveDir(path)) { + path+=CROSS_FILESPLIT; + } else { + extern std::string capturedir; + const size_t last_slash_idx = capturedir.find_last_of("\\/"); + if (std::string::npos != last_slash_idx) { + path = capturedir.substr(0, last_slash_idx); + } else { + path = "."; + } + path+=CROSS_FILESPLIT; + path+="save"; + Cross::CreateDir(path); + path+=CROSS_FILESPLIT; + } + + std::string temp, save2; + std::stringstream slotname; + slotname << slot+1; + temp=path; + std::string save=use_save_file&&savefilename.size()?savefilename:temp+slotname.str()+".sav"; + + #ifdef C_LIBZ + + zipFile zf; + { + const char *global_comment = "DOSBox-X save state"; + zlib_filefunc64_def ffunc; +#ifdef USEWIN32IOAPI + fill_win32_filefunc64A(&ffunc); +#else + fill_fopen64_filefunc(&ffunc); +#endif + remove(save.c_str()); + zf = zipOpen2_64(save.c_str(),APPEND_STATUS_CREATE,&global_comment,&ffunc); + } + if (zf == NULL) { save_err = true; goto done; } + + { + zip_fileinfo zi; zipSetCurrentTime(zi); + if ((errclose=zipOutOpenFile(zf,"DOSBox-X_Version",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } + zip_ostreambuf zos(zf); std::ostream emulatorversion(&zos); + + emulatorversion << "DOSBox-X " << VERSION << " (" << SDL_STRING << ")" << std::endl << GetPlatform(true) << std::endl << UPDATED_STR; + /* 2025/01/12: Backwards compat: The old code compressed data to zlib, even though the ZIP support code + * already applies compression. This is to tell the old code that we did not compress the + * data (the ZIP support code did though). */ + emulatorversion << std::endl << "No compression"; + + if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } + } + { + zip_fileinfo zi; zipSetCurrentTime(zi); + if ((errclose=zipOutOpenFile(zf,"Program_Name",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } + zip_ostreambuf zos(zf); std::ostream programname(&zos); + + programname << RunningProgram; + + if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } + } + { + zip_fileinfo zi; zipSetCurrentTime(zi); + if ((errclose=zipOutOpenFile(zf,"Memory_Size",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } + zip_ostreambuf zos(zf); std::ostream memorysize(&zos); + + memorysize << MEM_TotalPages(); + + if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } + } + { + zip_fileinfo zi; zipSetCurrentTime(zi); + if ((errclose=zipOutOpenFile(zf,"Machine_Type",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } + zip_ostreambuf zos(zf); std::ostream machinetype(&zos); + + machinetype << getType(); + + if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } + } + { + zip_fileinfo zi; zipSetCurrentTime(zi); + if ((errclose=zipOutOpenFile(zf,"Time_Stamp",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } + zip_ostreambuf zos(zf); std::ostream timestamp(&zos); + + timestamp << getTime(true); + + if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } + } + { + zip_fileinfo zi; zipSetCurrentTime(zi); + if ((errclose=zipOutOpenFile(zf,"Save_Remark",zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } + zip_ostreambuf zos(zf); std::ostream saveremark(&zos); + + saveremark << std::string(save_remark); + + if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } + } + for (CompEntry::iterator i = components.begin(); i != components.end(); ++i) { + zip_fileinfo zi; zipSetCurrentTime(zi); + if ((errclose=zipOutOpenFile(zf,i->first.c_str(),zi,compresssaveparts)) != ZIP_OK) { save_err = true; goto done; } + zip_ostreambuf zos(zf); std::ostream ss(&zos); + + i->second.comp.getBytes(ss); + + if ((errclose=zos.close()) != ZIP_OK) { save_err = true; goto done; } + } + +done: + if (zf != NULL) { + errclose = zipClose(zf,NULL); + if (errclose != ZIP_OK) save_err = true; + } + + if (!dos_kernel_disabled) flagged_backup((char *)save.c_str()); + + if (save_err) + notifyError("Failed to save the current state."); + else + LOG_MSG("[%s]: Saved. (Slot %d)", getTime().c_str(), (int)slot+1); +#endif +} + +void savestatecorrupt(const char* part) { + LOG_MSG("Save state corrupted! Program in inconsistent state! - %s", part); + systemmessagebox("Error","Save state corrupted! Program may not work.","ok","error", 1); +} + +bool confres=false; +bool loadstateconfirm(int ind) { + if (ind<0||ind>4) return false; + confres=true; + GUI_Shortcut(23+ind); + bool ret=confres; + confres=false; + return ret; +} + +void SaveState::load(size_t slot) const { //throw (Error) + // if (isEmpty(slot)) return; + bool load_err=false; + if((MEM_TotalPages()*4096/1024/1024)>1024) { + LOG_MSG("Stopped. 1 GB is the maximum memory size for saving/loading states."); + notifyError("Unsupported memory size for loading states.", false); + return; + } +#ifdef C_SDL2 + SDL_PauseAudioDevice(SDL2_AudioDevice, 0); +#else + SDL_PauseAudio(0); +#endif + extern const char* RunningProgram; + std::string path; + int err; + bool Get_Custom_SaveDir(std::string& savedir); + if(Get_Custom_SaveDir(path)) { + path+=CROSS_FILESPLIT; + } else { + extern std::string capturedir; + const size_t last_slash_idx = capturedir.find_last_of("\\/"); + if (std::string::npos != last_slash_idx) { + path = capturedir.substr(0, last_slash_idx); + } else { + path = "."; + } + path += CROSS_FILESPLIT; + path +="save"; + path += CROSS_FILESPLIT; + } + std::string temp; + temp = path; + std::stringstream slotname; + slotname << slot+1; + std::string save=use_save_file&&savefilename.size()?savefilename:temp+slotname.str()+".sav"; + std::ifstream check_slot; + check_slot.open(save.c_str(), std::ifstream::in); + if(check_slot.fail()) { + LOG_MSG("No saved slot - %d (%s)",(int)slot+1,save.c_str()); + notifyError(use_save_file&&savefilename.size()?"The selected save file is currently empty.":"The selected save slot is an empty slot.", false); + load_err=true; + return; + } + check_slot.close(); + + #ifdef C_LIBZ + unz_file_info64 file_info; + unzFile zf; + { + zlib_filefunc64_def ffunc; +#ifdef USEWIN32IOAPI + fill_win32_filefunc64A(&ffunc); +#else + fill_fopen64_filefunc(&ffunc); +#endif + zf = unzOpen2_64(save.c_str(),&ffunc); + } + if (zf == NULL) { load_err=true; goto done; } + + { + if ((err=unzLocateFile(zf,"DOSBox-X_Version",1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } + zip_istreambuf zis(zf); + + char buffer[4096]; + std::streamsize sz = zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)-1); buffer[sz] = 0; + + char *p; + if (strstr(buffer, "\nNo compression") != NULL) { + /* 2025/01/12: Removal of this string is required to match version string below even if now ignored */ + p=strrchr(buffer, '\n'); + if (p!=NULL) *p=0; + } + p=strrchr(buffer, '\n'); /* Remove i.e. "Linux" */ + if (p!=NULL) *p=0; + std::string emulatorversion = std::string("DOSBox-X ") + VERSION + std::string(" (") + SDL_STRING + std::string(")"); + if (strcasecmp(buffer,emulatorversion.c_str())) { + if(!force_load_state&&!loadstateconfirm(0)) { + LOG_MSG("Aborted. Check your DOSBox-X version: %s",buffer); + load_err=true; + goto done; + } + } + + if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } + } + + { + if ((err=unzLocateFile(zf,"Program_Name",1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } + zip_istreambuf zis(zf); + + char buffer[4096]; + size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)-1); buffer[length] = 0; + + if (!length||(size_t)length!=strlen(RunningProgram)||strncmp(buffer,RunningProgram,length)) { + if(!force_load_state&&!loadstateconfirm(1)) { + buffer[length]='\0'; + LOG_MSG("Aborted. Check your program name: %s",buffer); + load_err=true; + goto done; + } + if (length<9) { + static char pname[9]; + if (length) { + strncpy(pname,buffer,length); + pname[length]=0; + } else + strcpy(pname, "DOSBOX-X"); + RunningProgram=pname; + void GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused); + GFX_SetTitle(-1,-1,-1,false); + } + } + + if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } + } + + { + if ((err=unzLocateFile(zf,"Memory_Size",1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } + zip_istreambuf zis(zf); + + char buffer[4096]; + size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)-1); buffer[length] = 0; + + char str[10]; + itoa((int)MEM_TotalPages(), str, 10); + if(!length||(size_t)length!=strlen(str)||strncmp(buffer,str,length)) { + if(!force_load_state&&!loadstateconfirm(2)) { + buffer[length]='\0'; + int size=atoi(buffer)*4096/1024/1024; + LOG_MSG("Aborted. Check your memory size: %d MB", size); + load_err=true; + goto done; + } + } + + if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } + } + + { + if ((err=unzLocateFile(zf,"Machine_Type",1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } + zip_istreambuf zis(zf); + + char buffer[4096]; + size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer,sizeof(buffer)-1); buffer[length] = 0; + + char str[20]; + strcpy(str, getType().c_str()); + if(!length||(size_t)length!=strlen(str)||strncmp(buffer,str,length)) { + if(!force_load_state&&!loadstateconfirm(3)) { + LOG_MSG("Aborted. Check your machine type: %s",buffer); + load_err=true; + goto done; + } + } + + if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } + } + + for (CompEntry::const_iterator i = components.begin(); i != components.end(); ++i) { + if ((err=unzLocateFile(zf,i->first.c_str(),1/*case sensitive*/)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) != UNZ_OK) { load_err=true; goto done; } + if ((err=unzOpenCurrentFile(zf)) != UNZ_OK) { load_err=true; goto done; } + zip_istreambuf zis(zf); std::istream ss(&zis); + + i->second.comp.setBytes(ss); + + if ((err=zis.close()) != ZIP_OK) { load_err=true; goto done; } + } + +done: + if (zf != NULL) { + err = unzClose(zf); + if (err != UNZ_OK) load_err = true; + } + + if (!dos_kernel_disabled) flagged_restore((char *)save.c_str()); + if (!load_err) LOG_MSG("[%s]: Loaded. (Slot %d)", getTime().c_str(), (int)slot+1); + #endif +} + +bool SaveState::isEmpty(size_t slot) const { + if (slot >= SLOT_COUNT*MAX_PAGE) return true; + std::string path; + bool Get_Custom_SaveDir(std::string& savedir); + if(Get_Custom_SaveDir(path)) { + path+=CROSS_FILESPLIT; + } else { + extern std::string capturedir; + const size_t last_slash_idx = capturedir.find_last_of("\\/"); + if (std::string::npos != last_slash_idx) { + path = capturedir.substr(0, last_slash_idx); + } else { + path = "."; + } + path += CROSS_FILESPLIT; + path +="save"; + path += CROSS_FILESPLIT; + } + std::string temp; + temp = path; + std::stringstream slotname; + slotname << slot+1; + std::string save=temp+slotname.str()+".sav"; + std::ifstream check_slot; + check_slot.open(save.c_str(), std::ifstream::in); + return check_slot.fail(); +} + +void SaveState::removeState(size_t slot) const { + if (slot >= SLOT_COUNT*MAX_PAGE) return; + std::string path; + bool Get_Custom_SaveDir(std::string& savedir); + if(Get_Custom_SaveDir(path)) { + path+=CROSS_FILESPLIT; + } else { + extern std::string capturedir; + const size_t last_slash_idx = capturedir.find_last_of("\\/"); + if (std::string::npos != last_slash_idx) { + path = capturedir.substr(0, last_slash_idx); + } else { + path = "."; + } + path += CROSS_FILESPLIT; + path +="save"; + path += CROSS_FILESPLIT; + } + std::string temp; + temp = path; + std::stringstream slotname; + slotname << slot+1; + std::string save=temp+slotname.str()+".sav"; + std::ifstream check_slot; + check_slot.open(save.c_str(), std::ifstream::in); + if(check_slot.fail()) { + LOG_MSG("No saved slot - %d (%s)",(int)slot+1,save.c_str()); + notifyError("The selected save slot is an empty slot.", false); + return; + } + if (loadstateconfirm(4)) { + check_slot.close(); + remove(save.c_str()); + check_slot.open(save.c_str(), std::ifstream::in); + if (!check_slot.fail()) notifyError("Failed to remove the state in the save slot."); + if (page!=GetGameState()/SaveState::SLOT_COUNT) + SetGameState((int)slot); + else + refresh_slots(); + } +} + +std::string SaveState::getName(size_t slot, bool nl) const { + if (slot >= SLOT_COUNT*MAX_PAGE) return "["+std::string(MSG_Get("EMPTY_SLOT"))+"]"; + std::string path; + bool Get_Custom_SaveDir(std::string& savedir); + if(Get_Custom_SaveDir(path)) { + path+=CROSS_FILESPLIT; + } else { + extern std::string capturedir; + const size_t last_slash_idx = capturedir.find_last_of("\\/"); + if (std::string::npos != last_slash_idx) { + path = capturedir.substr(0, last_slash_idx); + } else { + path = "."; + } + path += CROSS_FILESPLIT; + path +="save"; + path += CROSS_FILESPLIT; + } + std::string temp; + temp = path; + std::stringstream slotname; + slotname << slot+1; + std::string save=nl&&use_save_file&&savefilename.size()?savefilename:temp+slotname.str()+".sav"; + std::ifstream check_slot; + check_slot.open(save.c_str(), std::ifstream::in); + if (check_slot.fail()) return nl?"(Empty state)":"["+std::string(MSG_Get("EMPTY_SLOT"))+"]"; + check_slot.close(); + + #ifdef C_LIBZ + + unzFile zf; + { + zlib_filefunc64_def ffunc; +#ifdef USEWIN32IOAPI + fill_win32_filefunc64A(&ffunc); +#else + fill_fopen64_filefunc(&ffunc); +#endif + zf = unzOpen2_64(save.c_str(),&ffunc); + } + if (zf == NULL) return "(Error slot)"; + + int err; + std::string ret; + char buffer1[4096]; + unz_file_info64 file_info; + + if ( (err=unzLocateFile(zf,"Program_Name",1/*case sensitive*/)) == UNZ_OK && + (err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) == UNZ_OK) { + if ((err=unzOpenCurrentFile(zf)) == UNZ_OK) { + zip_istreambuf zis(zf); + size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer1,sizeof(buffer1)-1); buffer1[length] = 0; + zis.close(); + ret += nl?"Program: "+(!strlen(buffer1)?"-":std::string(buffer1))+"\n":"[Program: "+std::string(buffer1)+"]"; + } + } + + if ( (err=unzLocateFile(zf,"Time_Stamp",1/*case sensitive*/)) == UNZ_OK && + (err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) == UNZ_OK) { + if ((err=unzOpenCurrentFile(zf)) == UNZ_OK) { + zip_istreambuf zis(zf); + size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer1,sizeof(buffer1)-1); buffer1[length] = 0; + zis.close(); + ret += nl?"Timestamp: "+(!strlen(buffer1)?"-":std::string(buffer1))+"\n":" ("+std::string(buffer1)+")"; + } + } + + if ( (err=unzLocateFile(zf,"Save_Remark",1/*case sensitive*/)) == UNZ_OK && + (err=unzGetCurrentFileInfo64(zf,&file_info,NULL,0,NULL,0,NULL,0)) == UNZ_OK) { + if ((err=unzOpenCurrentFile(zf)) == UNZ_OK) { + zip_istreambuf zis(zf); + size_t length = (size_t)zis.xsgetn((zip_istreambuf::char_type*)buffer1,sizeof(buffer1)-1); buffer1[length] = 0; + zis.close(); + if (length != 0) ret += nl?"Remark: "+(!strlen(buffer1)?"-":std::string(buffer1))+"\n":" - "+std::string(buffer1); + } + } + + return ret; + + #endif + + return "(Error slot)"; +} diff --git a/src/shell/shell.cpp b/src/shell/shell.cpp index 59911b7eac3..0cc4d3c485a 100644 --- a/src/shell/shell.cpp +++ b/src/shell/shell.cpp @@ -1202,7 +1202,8 @@ class AUTOEXEC:public Module_base { if (line.length() > CROSS_LEN) continue; strcpy(buffer,line.c_str()); if (stat(buffer,&test)) { - if (getcwd(buffer,CROSS_LEN) == NULL) continue; + strcpy(buffer, "."); + // if (getcwd(buffer,CROSS_LEN) == NULL) continue; if (strlen(buffer) + line.length() + 1 > CROSS_LEN) continue; strcat(buffer,cross_filesplit); strcat(buffer,line.c_str()); @@ -1217,7 +1218,8 @@ class AUTOEXEC:public Module_base { char* name = strrchr(buffer,CROSS_FILESPLIT); if (!name) { //Only a filename line = buffer; - if (getcwd(buffer,CROSS_LEN) == NULL) continue; + strcpy(buffer, "."); + // if (getcwd(buffer,CROSS_LEN) == NULL) continue; if (strlen(buffer) + line.length() + 1 > CROSS_LEN) continue; strcat(buffer,cross_filesplit); strcat(buffer,line.c_str()); diff --git a/src/shell/shell_cmds.cpp b/src/shell/shell_cmds.cpp index 58e9fb8f65d..81681f21e29 100644 --- a/src/shell/shell_cmds.cpp +++ b/src/shell/shell_cmds.cpp @@ -22,4765 +22,4772 @@ */ -#include "dosbox.h" -#include "logging.h" -#include "shell.h" -#include "callback.h" -#include "dos_inc.h" -#include "regs.h" -#include "pic.h" -#include "keyboard.h" -#include "timer.h" -#include "../ints/int10.h" -#include -#include -#include "bios.h" -#include "../dos/drives.h" -#include "support.h" -#include "control.h" -#include "paging.h" -#include "menu.h" -#include "jfont.h" -#include "render.h" -#include -#include -#include -#include -#include -#include -#include "sdlmain.h" -#include "menudef.h" -#include "build_timestamp.h" -#include "version_string.h" - -#include - -#if defined(_MSC_VER) -# pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ -#endif - -SHELL_Cmd cmd_list[]={ -{ "DIR", 0, &DOS_Shell::CMD_DIR, "SHELL_CMD_DIR_HELP"}, -{ "CD", 0, &DOS_Shell::CMD_CHDIR, "SHELL_CMD_CHDIR_HELP"}, -{ "ALIAS", 1, &DOS_Shell::CMD_ALIAS, "SHELL_CMD_ALIAS_HELP"}, -{ "ASSOC", 1, &DOS_Shell::CMD_ASSOC, "SHELL_CMD_ASSOC_HELP"}, -{ "ATTRIB", 1, &DOS_Shell::CMD_ATTRIB, "SHELL_CMD_ATTRIB_HELP"}, -{ "BREAK", 1, &DOS_Shell::CMD_BREAK, "SHELL_CMD_BREAK_HELP"}, -{ "CALL", 1, &DOS_Shell::CMD_CALL, "SHELL_CMD_CALL_HELP"}, -{ "CHDIR", 1, &DOS_Shell::CMD_CHDIR, "SHELL_CMD_CHDIR_HELP"}, -//{ "CHOICE", 1, &DOS_Shell::CMD_CHOICE, "SHELL_CMD_CHOICE_HELP"}, // CHOICE as a program (Z:\DOS\CHOICE.COM) instead of shell command -{ "CLS", 0, &DOS_Shell::CMD_CLS, "SHELL_CMD_CLS_HELP"}, -{ "COPY", 0, &DOS_Shell::CMD_COPY, "SHELL_CMD_COPY_HELP"}, -{ "CHCP", 1, &DOS_Shell::CMD_CHCP, "SHELL_CMD_CHCP_HELP"}, -//{ "COUNTRY", 1, &DOS_Shell::CMD_COUNTRY, "SHELL_CMD_COUNTRY_HELP"}, // COUNTRY as a program (Z:\SYSTEM\COUNTRY.COM) instead of shell command -{ "CTTY", 1, &DOS_Shell::CMD_CTTY, "SHELL_CMD_CTTY_HELP"}, -{ "DATE", 0, &DOS_Shell::CMD_DATE, "SHELL_CMD_DATE_HELP"}, -{ "DEL", 0, &DOS_Shell::CMD_DELETE, "SHELL_CMD_DELETE_HELP"}, -//{ "DELTREE", 1, &DOS_Shell::CMD_DELTREE, "SHELL_CMD_DELTREE_HELP"}, // DELTREE as a program (Z:\DOS\DELTREE.EXE) instead of shell command -{ "ECHO", 0, &DOS_Shell::CMD_ECHO, "SHELL_CMD_ECHO_HELP"}, -{ "ERASE", 1, &DOS_Shell::CMD_DELETE, "SHELL_CMD_DELETE_HELP"}, -{ "EXIT", 0, &DOS_Shell::CMD_EXIT, "SHELL_CMD_EXIT_HELP"}, -{ "FOR", 1, &DOS_Shell::CMD_FOR, "SHELL_CMD_FOR_HELP"}, -{ "GOTO", 1, &DOS_Shell::CMD_GOTO, "SHELL_CMD_GOTO_HELP"}, -//{ "HELP", 1, &DOS_Shell::CMD_HELP, "SHELL_CMD_HELP_HELP"}, // HELP as a program (Z:\SYSTEM\HELP.COM) instead of shell command -{ "HISTORY", 1, &DOS_Shell::CMD_HISTORY, "SHELL_CMD_HISTORY_HELP"}, -{ "IF", 1, &DOS_Shell::CMD_IF, "SHELL_CMD_IF_HELP"}, -{ "LFNFOR", 1, &DOS_Shell::CMD_LFNFOR, "SHELL_CMD_LFNFOR_HELP"}, -{ "LH", 1, &DOS_Shell::CMD_LOADHIGH, "SHELL_CMD_LOADHIGH_HELP"}, -{ "LOADHIGH", 1, &DOS_Shell::CMD_LOADHIGH, "SHELL_CMD_LOADHIGH_HELP"}, -//{ "LS", 1, &DOS_Shell::CMD_LS, "SHELL_CMD_LS_HELP"}, // LS as a program (Z:\BIN\LS.COM) instead of shell command -{ "MD", 0, &DOS_Shell::CMD_MKDIR, "SHELL_CMD_MKDIR_HELP"}, -{ "MKDIR", 1, &DOS_Shell::CMD_MKDIR, "SHELL_CMD_MKDIR_HELP"}, -{ "MORE", 1, &DOS_Shell::CMD_MORE, "SHELL_CMD_MORE_HELP"}, -{ "PATH", 1, &DOS_Shell::CMD_PATH, "SHELL_CMD_PATH_HELP"}, -{ "PAUSE", 1, &DOS_Shell::CMD_PAUSE, "SHELL_CMD_PAUSE_HELP"}, -{ "PROMPT", 0, &DOS_Shell::CMD_PROMPT, "SHELL_CMD_PROMPT_HELP"}, -{ "RD", 0, &DOS_Shell::CMD_RMDIR, "SHELL_CMD_RMDIR_HELP"}, -{ "REM", 1, &DOS_Shell::CMD_REM, "SHELL_CMD_REM_HELP"}, -{ "REN", 0, &DOS_Shell::CMD_RENAME, "SHELL_CMD_RENAME_HELP"}, -{ "RENAME", 1, &DOS_Shell::CMD_RENAME, "SHELL_CMD_RENAME_HELP"}, -{ "RMDIR", 1, &DOS_Shell::CMD_RMDIR, "SHELL_CMD_RMDIR_HELP"}, -{ "SET", 1, &DOS_Shell::CMD_SET, "SHELL_CMD_SET_HELP"}, -{ "SHIFT", 1, &DOS_Shell::CMD_SHIFT, "SHELL_CMD_SHIFT_HELP"}, -{ "SUBST", 1, &DOS_Shell::CMD_SUBST, "SHELL_CMD_SUBST_HELP"}, -{ "TIME", 0, &DOS_Shell::CMD_TIME, "SHELL_CMD_TIME_HELP"}, -{ "TRUENAME", 1, &DOS_Shell::CMD_TRUENAME, "SHELL_CMD_TRUENAME_HELP"}, -{ "TYPE", 0, &DOS_Shell::CMD_TYPE, "SHELL_CMD_TYPE_HELP"}, -{ "VER", 0, &DOS_Shell::CMD_VER, "SHELL_CMD_VER_HELP"}, -{ "VERIFY", 1, &DOS_Shell::CMD_VERIFY, "SHELL_CMD_VERIFY_HELP"}, -{ "VOL", 0, &DOS_Shell::CMD_VOL, "SHELL_CMD_VOL_HELP"}, -{ "POPD", 1, &DOS_Shell::CMD_POPD, "SHELL_CMD_POPD_HELP"}, -{ "PUSHD", 1, &DOS_Shell::CMD_PUSHD, "SHELL_CMD_PUSHD_HELP"}, -#if C_DEBUG -// Additional commands for debugging purposes in DOSBox-X -{ "DEBUGBOX", 1, &DOS_Shell::CMD_DEBUGBOX, "SHELL_CMD_DEBUGBOX_HELP"}, -//{ "INT2FDBG", 1, &DOS_Shell::CMD_INT2FDBG, "SHELL_CMD_INT2FDBG_HELP"}, // INT2FDBG as a program (Z:\DEBUG\INT2FDBG.COM) instead of shell command -#endif -// Advanced commands specific to DOSBox-X -//{ "ADDKEY", 1, &DOS_Shell::CMD_ADDKEY, "SHELL_CMD_ADDKEY_HELP"}, // ADDKEY as a program (Z:\BIN\ADDKEY.COM) instead of shell command -{ "DX-CAPTURE", 1, &DOS_Shell::CMD_DXCAPTURE, "SHELL_CMD_DXCAPTURE_HELP"}, -{ nullptr, 0, nullptr, nullptr } -}; - -const char *GetCmdName(int i) { - size_t n = sizeof(cmd_list)/sizeof(cmd_list[0])-1; - return i>n?NULL:cmd_list[i].name; -} - -extern int enablelfn, lfn_filefind_handle, file_access_tries, lastmsgcp; -extern bool date_host_forced, usecon, outcon, rsize, autoboxdraw, dbcs_sbcs, sync_time, manualtime, inshell, noassoc, dotype, loadlang, chinasea; -extern unsigned long freec; -extern uint8_t DOS_GetAnsiAttr(void); -extern uint16_t countryNo, altcp_to_unicode[256]; -extern bool isDBCSCP(), isKanji1(uint8_t chr), shiftjis_lead_byte(int c), TTF_using(void), Network_IsNetworkResource(const char * filename); -extern bool CheckBoxDrawing(uint8_t c1, uint8_t c2, uint8_t c3, uint8_t c4), GFX_GetPreventFullscreen(void), DOS_SetAnsiAttr(uint8_t attr); -extern bool systemmessagebox(char const * aTitle, char const * aMessage, char const * aDialogType, char const * aIconType, int aDefaultButton); -extern void Load_Language(std::string name), GetExpandedPath(std::string &path); -extern void MAPPER_AutoType(std::vector &sequence, const uint32_t wait_ms, const uint32_t pace_ms, bool choice); -extern void DOS_SetCountry(uint16_t countryNo), DOSV_FillScreen(void); -void clearFontCache(void); -std::string GetDOSBoxXPath(bool withexe=false); -FILE *testLoadLangFile(const char *fname); -Bitu DOS_ChangeCodepage(int32_t codepage, const char* codepagefile); -bool CheckDBCSCP(int32_t codepage), SwitchLanguage(int oldcp, int newcp, bool confirm); -void makestdcp950table(), makeseacp951table(); -#if C_OPENGL -bool OpenGL_using(void); -#endif -void UpdateSDLDrawTexture(); - -static int32_t lastsetcp = 0; -bool CHCP_changed = false; - -/* support functions */ -static char empty_char = 0; -static char* empty_string = &empty_char; -static void StripSpaces(char*&args) { - while(args && *args && isspace(*reinterpret_cast(args))) - args++; -} - -static void StripSpaces(char*&args,char also) { - while(args && *args && (isspace(*reinterpret_cast(args)) || (*args == also))) - args++; -} - -static char* ExpandDot(char*args, char* buffer , size_t bufsize, bool expand) { - if(*args == '.') { - if(*(args+1) == 0){ - safe_strncpy(buffer, "*.*", bufsize); - return buffer; - } - if( (*(args+1) != '.') && (*(args+1) != '\\') && expand) { - buffer[0] = '*'; - buffer[1] = 0; - if (bufsize > 2) strncat(buffer,args,bufsize - 1 /*used buffer portion*/ - 1 /*trailing zero*/ ); - return buffer; - } else - safe_strncpy (buffer, args, bufsize); - } - else safe_strncpy(buffer,args, bufsize); - return buffer; -} - -static char* ExpandDotMore(char*args, char* buffer , size_t bufsize) { - char * find_last; - find_last=strrchr_dbcs(args,'\\'); - if (find_last!=NULL) find_last++; - if (find_last!=NULL && *find_last == '.') { - if(*(find_last+1) == 0){ - safe_strncpy(buffer, args, bufsize); - return buffer; - } - if( (*(find_last+1) != '.')) { - *find_last = 0; - strcpy(buffer, args); - *find_last = '.'; - size_t len = strlen(buffer); - buffer[len] = '*'; - buffer[len+1] = 0; - if (bufsize > len + 2) strncat(buffer,find_last,bufsize - len - 1 /*used buffer portion*/ - 1 /*trailing zero*/ ); - else safe_strncpy(buffer, args, bufsize); - return buffer; - } else - safe_strncpy(buffer, args, bufsize); - } - else safe_strncpy(buffer, args, bufsize); - return buffer; -} - -bool DOS_Shell::CheckConfig(char* cmd_in,char*line) { - bool quote=false; - if (strlen(cmd_in)>2&&cmd_in[0]=='"'&&cmd_in[strlen(cmd_in)-1]=='"') { - cmd_in[strlen(cmd_in)-1]=0; - cmd_in++; - quote=true; - } - Section* test = control->GetSectionFromProperty(cmd_in); - if(!test) return false; - if(line && !line[0]) { - std::string val = test->GetPropValue(cmd_in); - if(val != NO_SUCH_PROPERTY) WriteOut("%s\n",val.c_str()); - return true; - } - char newcom[1024]; newcom[0] = 0; strcpy(newcom,"z:\\system\\config -set "); - if (line != NULL) { - line=trim(line); - if (*line=='=') line=trim(++line); - if (line[0]=='"'&&line[strlen(line)-1]=='"') { - line[strlen(line)-1]=0; - line++; - quote=true; - } - if (quote) strcat(newcom,"\""); - strcat(newcom,test->GetName()); strcat(newcom," "); - strcat(newcom,cmd_in); - strcat(newcom, "="); - strcat(newcom, line); - if (quote) strcat(newcom,"\""); - } else - E_Exit("'line' in CheckConfig is NULL"); - DoCommand(newcom); - return true; -} - -bool enable_config_as_shell_commands = false; - -bool DOS_Shell::execute_shell_cmd(char *name, char *arguments) { - // SHELL_Cmd shell_cmd = {}; /* unused */ - uint32_t cmd_index=0; - while (cmd_list[cmd_index].name) { - if (strcasecmp(cmd_list[cmd_index].name,name)==0) { - (this->*(cmd_list[cmd_index].handler))(arguments); - return true; - } - cmd_index++; - } - return false; -} - -void DOS_Shell::DoCommand(char * line) { - /* First split the line into command and arguments */ - std::string origin_cmd_line = line; - std::string last_alias_cmd; - std::string altered_cmd_line; - int alias_counter = 0; -__do_command_begin: - if (alias_counter > 64) { - WriteOut(MSG_Get("SHELL_EXECUTE_ALIAS_EXPAND_OVERFLOW"), origin_cmd_line.c_str()); - } - line=trim(line); - char cmd_buffer[CMD_MAXLINE]; - char * cmd_write=cmd_buffer; - int c=0,q=0; - while (*line) { - if (*line == '/' || *line == '\t') break; - - if ((q & 1) == 0) { - if (*line == ' ' || *line == '=') break; - - if (*line == '.' || *line == ';' || (*line == ':' && !(c == 1 && tolower(*(line-1)) >= 'a' && tolower(*(line-1)) <= 'z')) || *line == '[' || *line == ']' || *line == '\\' || *line == '/' || *line == '\"' || *line == '+') { //allow stuff like cd.. and dir.exe cd\kees - *cmd_write=0; - if (execute_shell_cmd(cmd_buffer,line)) return; - } - } - c++; - if (*line == '"') q++; - *cmd_write++=*line++; - } - *cmd_write=0; - if (strlen(cmd_buffer)==0) { - if (strlen(line)&&line[0]=='/') WriteOut(MSG_Get("SHELL_EXECUTE_ILLEGAL_COMMAND"),line); - return; - } - cmd_alias_map_t::iterator iter = cmd_alias.find(cmd_buffer); - if (iter != cmd_alias.end() && last_alias_cmd != cmd_buffer) { - alias_counter++; - altered_cmd_line = iter->second + " " + line; - line = (char*)altered_cmd_line.c_str(); - last_alias_cmd = iter->first; - goto __do_command_begin; - } - - /* Check the internal list */ - if (execute_shell_cmd(cmd_buffer,line)) return; - - /* This isn't an internal command execute it */ - char ldir[CROSS_LEN], *p=ldir; - if (strchr(cmd_buffer,'\"')&&DOS_GetSFNPath(cmd_buffer,ldir,false)) { - if (!strchr_dbcs(cmd_buffer, '\\') && strrchr_dbcs(ldir, '\\')) - p=strrchr_dbcs(ldir, '\\')+1; - if (uselfn&&strchr(p, ' ')&&!DOS_FileExists(("\""+std::string(p)+"\"").c_str())) { - bool append=false; - if (DOS_FileExists(("\""+std::string(p)+".COM\"").c_str())) {append=true;strcat(p, ".COM");} - else if (DOS_FileExists(("\""+std::string(p)+".EXE\"").c_str())) {append=true;strcat(p, ".EXE");} - else if (DOS_FileExists(("\""+std::string(p)+".BAT\"").c_str())) {append=true;strcat(p, ".BAT");} - if (append&&DOS_GetSFNPath(("\""+std::string(p)+"\"").c_str(), cmd_buffer,false)) if(Execute(cmd_buffer,line)) return; - } - if(Execute(p,line)) return; - } else - if(Execute(cmd_buffer,line)) return; - if(enable_config_as_shell_commands && CheckConfig(cmd_buffer,line)) return; - std::string errhandler = static_cast(control->GetSection("dos"))->Get_string("badcommandhandler"); - if (errhandler.size()&&!noassoc) { - noassoc=true; - LOG_MSG("errhandler %s line %s\n", errhandler.c_str(), origin_cmd_line.c_str()); - DoCommand((char *)(errhandler+" "+origin_cmd_line).c_str()); - noassoc=false; - } else - WriteOut(MSG_Get("SHELL_EXECUTE_ILLEGAL_COMMAND"),cmd_buffer); -} - -#define HELP(command) \ - if (ScanCMDBool(args,"?")) { \ - uint8_t attr = DOS_GetAnsiAttr(); \ - WriteOut(MSG_Get("SHELL_CMD_" command "_HELP")); \ - const char* long_m = MSG_Get("SHELL_CMD_" command "_HELP_LONG"); \ - WriteOut("\n"); \ - if(strcmp("Message not Found!\n",long_m)) WriteOut(long_m); \ - else WriteOut(command "\n"); \ - if (attr) DOS_SetAnsiAttr(attr); \ - return; \ - } - -#if C_DEBUG -extern Bitu int2fdbg_hook_callback; -static Bitu INT2FDBG_Handler(void) { - if (reg_ax == 0x1605) { /* Windows init broadcast */ - int patience = 500; - Bitu st_seg,st_ofs; - - LOG_MSG("INT 2Fh debug hook: Caught Windows init broadcast results (ES:BX=%04x:%04x DS:SI=%04x:%04x CX=%04x DX=%04x DI=%04x)\n", - SegValue(es),reg_bx, - SegValue(ds),reg_si, - reg_cx,reg_dx,reg_di); - - st_seg = SegValue(es); - st_ofs = reg_bx; - while (st_seg != 0 || st_ofs != 0) { - unsigned char v_major,v_minor; - Bitu st_seg_next,st_ofs_next; - Bitu idrc_seg,idrc_ofs; - Bitu vdev_seg,vdev_ofs; - Bitu name_seg,name_ofs; - char devname[64]; - PhysPt st_o; - - if (--patience <= 0) { - LOG_MSG("**WARNING: Chain is too long. Something might have gotten corrupted\n"); - break; - } - - st_o = PhysMake(st_seg,st_ofs); - /* +0x00: Major, minor version of info structure - * +0x02: pointer to next startup info structure or 0000:0000 - * +0x06: pointer to ASCIIZ name of virtual device or 0000:0000 - * +0x0A: virtual device ref data (pointer to?? or actual data??) or 0000:0000 - * +0x0E: pointer to instance data records or 0000:0000 - * Windows 95 or later (v4.0+): - * +0x12: pointer to optionally-instanced data records or 0000:0000 */ - v_major = mem_readb(st_o+0x00); - v_minor = mem_readb(st_o+0x01); - st_seg_next = mem_readw(st_o+0x02+2); - st_ofs_next = mem_readw(st_o+0x02+0); - name_ofs = mem_readw(st_o+0x06+0); - name_seg = mem_readw(st_o+0x06+2); - vdev_ofs = mem_readw(st_o+0x0A+0); - vdev_seg = mem_readw(st_o+0x0A+2); - idrc_ofs = mem_readw(st_o+0x0A+4); /* FIXME: 0x0E+0 and 0x0E+2 generates weird compiler error WTF?? */ - idrc_seg = mem_readw(st_o+0x0A+6); - - { - devname[0] = 0; - if (name_seg != 0 || name_ofs != 0) { - unsigned char c; - unsigned int i; - PhysPt scan; - - scan = PhysMake(name_seg,name_ofs); - for (i=0;i < 63 && (c=mem_readb(scan++)) != 0;) devname[i++] = (char)c; - devname[i] = 0; - } - } - - LOG_MSG(" >> Version %u.%u\n",v_major,v_minor); - LOG_MSG(" Next entry at %04x:%04x\n",(int)st_seg_next,(int)st_ofs_next); - LOG_MSG(" Virtual device name: %04x:%04x '%s'\n",(int)name_seg,(int)name_ofs,devname); - LOG_MSG(" Virtual dev ref data: %04x:%04x\n",(int)vdev_seg,(int)vdev_ofs); - LOG_MSG(" Instance data records: %04x:%04x\n",(int)idrc_seg,(int)idrc_ofs); - - st_seg = st_seg_next; - st_ofs = st_ofs_next; - } - - LOG_MSG("----END CHAIN\n"); - } - - return CBRET_NONE; -} - -void Int2fhook() { - uint32_t old_int2Fh; - PhysPt w; - - int2fdbg_hook_callback = CALLBACK_Allocate(); - CALLBACK_Setup(int2fdbg_hook_callback,&INT2FDBG_Handler,CB_IRET,"INT 2Fh DBG callback"); - - /* record old vector, set our new vector */ - old_int2Fh = RealGetVec(0x2f); - w = CALLBACK_PhysPointer(int2fdbg_hook_callback); - RealSetVec(0x2f,CALLBACK_RealPointer(int2fdbg_hook_callback)); - - /* overwrite the callback with code to chain the call down, then invoke our callback on the way back up: */ - - /* first, chain to the previous INT 15h handler */ - phys_writeb(w++,(uint8_t)0x9C); //PUSHF - phys_writeb(w++,(uint8_t)0x9A); //CALL FAR
- phys_writew(w,(uint16_t)(old_int2Fh&0xFFFF)); w += 2; //offset - phys_writew(w,(uint16_t)((old_int2Fh>>16)&0xFFFF)); w += 2; //seg - - /* then, having returned from it, invoke our callback */ - phys_writeb(w++,(uint8_t)0xFE); //GRP 4 - phys_writeb(w++,(uint8_t)0x38); //Extra Callback instruction - phys_writew(w,(uint16_t)int2fdbg_hook_callback); w += 2; //The immediate word - - /* return */ - phys_writeb(w++,(uint8_t)0xCF); //IRET -} - -/* NTS: I know I could just modify the DOS kernel's INT 2Fh code to receive the init call, - * the problem is that at that point, the registers do not yet contain anything interesting. - * all the interesting results of the call are added by TSRs on the way back UP the call - * chain. The purpose of this program therefore is to hook INT 2Fh on the other end - * of the call chain so that we can see the results just before returning INT 2Fh back - * to WIN.COM */ -void DOS_Shell::CMD_INT2FDBG(char * args) { - //HELP("INT2FDBG"); - while (*args == ' ') args++; - - /* TODO: Allow /U to remove INT 2Fh hook */ - if (ScanCMDBool(args,"I")) { - if (int2fdbg_hook_callback == 0) { - Int2fhook(); - LOG_MSG("INT 2Fh debugging hook set\n"); - WriteOut("INT 2Fh hook has been set.\n"); - } else - WriteOut("INT 2Fh hook was already set up.\n"); - } else if (*args) - WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), args); -} -#endif - -void DOS_Shell::CMD_BREAK(char * args) { - HELP("BREAK"); - args = trim(args); - if (!*args) - WriteOut("BREAK is %s\n", dos.breakcheck ? "on" : "off"); - else if (!strcasecmp(args, "OFF")) - dos.breakcheck = false; - else if (!strcasecmp(args, "ON")) - dos.breakcheck = true; - else - WriteOut("Must specify ON or OFF\n"); -} - -bool is_ANSI_installed(Program *shell); -void DOS_Shell::CMD_CLS(char * args) { - HELP("CLS"); - if ((CurMode->type==M_TEXT || IS_PC98_ARCH) && is_ANSI_installed(this)) - WriteOut("\033[2J"); - else { - uint16_t oldax=reg_ax; - if (IS_DOSV && DOSV_CheckCJKVideoMode()) reg_ax = GetTrueVideoMode(); - else reg_ax=(uint16_t)CurMode->mode; - CALLBACK_RunRealInt(0x10); - reg_ax=oldax; - } -} - -void DOS_Shell::CMD_DELETE(char* args) { - HELP("DELETE"); - bool optP = ScanCMDBool(args, "P"); - bool optF = ScanCMDBool(args, "F"); - bool optQ = ScanCMDBool(args, "Q"); - - const char ch_y = MSG_Get("INT21_6523_YESNO_CHARS")[0]; - const char ch_n = MSG_Get("INT21_6523_YESNO_CHARS")[1]; - const char ch_Y = toupper(ch_y); - const char ch_N = toupper(ch_n); - - // ignore /f, /s, /ar, /as, /ah and /aa switches for compatibility - ScanCMDBool(args, "S"); - ScanCMDBool(args, "AR"); - ScanCMDBool(args, "AS"); - ScanCMDBool(args, "AH"); - ScanCMDBool(args, "AA"); - - char* rem = ScanCMDRemain(args); - if(rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), rem); - return; - } - if(!*args) { - WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); - return; - } - - StripSpaces(args); - args = trim(args); - - /* Command uses dta so set it to our internal dta */ - //DOS_DTA dta(dos.dta()); - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - /* If delete accept switches mind the space in front of them. See the dir /p code */ - - char full[DOS_PATHLENGTH], sfull[DOS_PATHLENGTH + 2]; - char buffer[CROSS_LEN]; - char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH + 1]; - uint32_t size, hsize; uint16_t time, date; uint8_t attr; - args = ExpandDot(args, buffer, CROSS_LEN, false); - StripSpaces(args); - if(!DOS_Canonicalize(args, full)) { WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); dos.dta(save_dta); return; } - if(strlen(args) && args[strlen(args) - 1] != '\\') { - uint16_t fattr; - if(strcmp(args, "*.*") && DOS_GetFileAttr(args, &fattr) && (fattr & DOS_ATTR_DIRECTORY)) - strcat(args, "\\"); - } - if(strlen(args) && args[strlen(args) - 1] == '\\') strcat(args, "*.*"); - else if(!strcmp(args, ".") || (strlen(args) > 1 && (args[strlen(args) - 2] == ':' || args[strlen(args) - 2] == '\\') && args[strlen(args) - 1] == '.')) { - args[strlen(args) - 1] = '*'; - strcat(args, ".*"); - } - else if(uselfn && strchr(args, '*')) { - char* find_last; - find_last = strrchr_dbcs(args, '\\'); - if(find_last == NULL) find_last = args; - else find_last++; - if(strlen(find_last) > 0 && args[strlen(args) - 1] == '*' && strchr(find_last, '.') == NULL) strcat(args, ".*"); - } - if(!strcmp(args, "*.*") || (strlen(args) > 3 && (!strcmp(args + strlen(args) - 4, "\\*.*") || !strcmp(args + strlen(args) - 4, ":*.*")))) { - if(!optQ) { - first_1: - WriteOut(MSG_Get("SHELL_CMD_DEL_SURE")); - first_2: - uint8_t c; uint16_t n = 1; - DOS_ReadFile(STDIN, &c, &n); - do { - if(c == ch_n || c == ch_N) { - DOS_WriteFile(STDOUT, &c, &n); - DOS_ReadFile(STDIN, &c, &n); - do switch(c) { - case 0xD: WriteOut("\n"); dos.dta(save_dta); return; - case 0x03: dos.dta(save_dta); return; - case 0x08: WriteOut("\b \b"); goto first_2; - } while(DOS_ReadFile(STDIN, &c, &n)); - } - - if(c == ch_y || c == ch_Y) { - DOS_WriteFile(STDOUT, &c, &n); - DOS_ReadFile(STDIN, &c, &n); - do switch(c) { - case 0xD: WriteOut("\n"); goto continue_1; - case 0x03: dos.dta(save_dta); return; - case 0x08: WriteOut("\b \b"); goto first_2; - } while(DOS_ReadFile(STDIN, &c, &n)); - } - - if(c == 0xD) { WriteOut("\n"); goto first_1; } - if(c == 0x03) { dos.dta(save_dta); return; } - if(c == '\t' || c == 0x08) goto first_2; - - DOS_WriteFile(STDOUT, &c, &n); - DOS_ReadFile(STDIN, &c, &n); - do switch(c) { - case 0xD: WriteOut("\n"); goto first_1; - case 0x03: dos.dta(save_dta); return; - case 0x08: WriteOut("\b \b"); goto first_2; - } while(DOS_ReadFile(STDIN, &c, &n)); - goto first_2; - } while(DOS_ReadFile(STDIN, &c, &n)); - } - } - -continue_1: - /* Command uses dta so set it to our internal dta */ - if(!DOS_Canonicalize(args, full)) { WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); dos.dta(save_dta); return; } - char path[DOS_PATHLENGTH], spath[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH], * r = strrchr_dbcs(full, '\\'); - if(r != NULL) { - *r = 0; - strcpy(path, full); - strcat(path, "\\"); - strcpy(pattern, r + 1); - *r = '\\'; - } + #include "dosbox.h" + #include "logging.h" + #include "shell.h" + #include "callback.h" + #include "dos_inc.h" + #include "regs.h" + #include "pic.h" + #include "keyboard.h" + #include "timer.h" + #include "../ints/int10.h" + #include + #include + #include "bios.h" + #include "../dos/drives.h" + #include "support.h" + #include "control.h" + #include "paging.h" + #include "menu.h" + #include "jfont.h" + #include "render.h" + #include + #include + #include + #include + #include + #include + #include "sdlmain.h" + #include "menudef.h" + #include "build_timestamp.h" + #include "version_string.h" + + #include + + #if defined(_MSC_VER) + # pragma warning(disable:4244) /* const fmath::local::uint64_t to double possible loss of data */ + #endif + + SHELL_Cmd cmd_list[]={ + { "DIR", 0, &DOS_Shell::CMD_DIR, "SHELL_CMD_DIR_HELP"}, + { "CD", 0, &DOS_Shell::CMD_CHDIR, "SHELL_CMD_CHDIR_HELP"}, + { "ALIAS", 1, &DOS_Shell::CMD_ALIAS, "SHELL_CMD_ALIAS_HELP"}, + { "ASSOC", 1, &DOS_Shell::CMD_ASSOC, "SHELL_CMD_ASSOC_HELP"}, + { "ATTRIB", 1, &DOS_Shell::CMD_ATTRIB, "SHELL_CMD_ATTRIB_HELP"}, + { "BREAK", 1, &DOS_Shell::CMD_BREAK, "SHELL_CMD_BREAK_HELP"}, + { "CALL", 1, &DOS_Shell::CMD_CALL, "SHELL_CMD_CALL_HELP"}, + { "CHDIR", 1, &DOS_Shell::CMD_CHDIR, "SHELL_CMD_CHDIR_HELP"}, + //{ "CHOICE", 1, &DOS_Shell::CMD_CHOICE, "SHELL_CMD_CHOICE_HELP"}, // CHOICE as a program (Z:\DOS\CHOICE.COM) instead of shell command + { "CLS", 0, &DOS_Shell::CMD_CLS, "SHELL_CMD_CLS_HELP"}, + { "COPY", 0, &DOS_Shell::CMD_COPY, "SHELL_CMD_COPY_HELP"}, + { "CHCP", 1, &DOS_Shell::CMD_CHCP, "SHELL_CMD_CHCP_HELP"}, + //{ "COUNTRY", 1, &DOS_Shell::CMD_COUNTRY, "SHELL_CMD_COUNTRY_HELP"}, // COUNTRY as a program (Z:\SYSTEM\COUNTRY.COM) instead of shell command + { "CTTY", 1, &DOS_Shell::CMD_CTTY, "SHELL_CMD_CTTY_HELP"}, + { "DATE", 0, &DOS_Shell::CMD_DATE, "SHELL_CMD_DATE_HELP"}, + { "DEL", 0, &DOS_Shell::CMD_DELETE, "SHELL_CMD_DELETE_HELP"}, + //{ "DELTREE", 1, &DOS_Shell::CMD_DELTREE, "SHELL_CMD_DELTREE_HELP"}, // DELTREE as a program (Z:\DOS\DELTREE.EXE) instead of shell command + { "ECHO", 0, &DOS_Shell::CMD_ECHO, "SHELL_CMD_ECHO_HELP"}, + { "ERASE", 1, &DOS_Shell::CMD_DELETE, "SHELL_CMD_DELETE_HELP"}, + { "EXIT", 0, &DOS_Shell::CMD_EXIT, "SHELL_CMD_EXIT_HELP"}, + { "FOR", 1, &DOS_Shell::CMD_FOR, "SHELL_CMD_FOR_HELP"}, + { "GOTO", 1, &DOS_Shell::CMD_GOTO, "SHELL_CMD_GOTO_HELP"}, + //{ "HELP", 1, &DOS_Shell::CMD_HELP, "SHELL_CMD_HELP_HELP"}, // HELP as a program (Z:\SYSTEM\HELP.COM) instead of shell command + { "HISTORY", 1, &DOS_Shell::CMD_HISTORY, "SHELL_CMD_HISTORY_HELP"}, + { "IF", 1, &DOS_Shell::CMD_IF, "SHELL_CMD_IF_HELP"}, + { "LFNFOR", 1, &DOS_Shell::CMD_LFNFOR, "SHELL_CMD_LFNFOR_HELP"}, + { "LH", 1, &DOS_Shell::CMD_LOADHIGH, "SHELL_CMD_LOADHIGH_HELP"}, + { "LOADHIGH", 1, &DOS_Shell::CMD_LOADHIGH, "SHELL_CMD_LOADHIGH_HELP"}, + //{ "LS", 1, &DOS_Shell::CMD_LS, "SHELL_CMD_LS_HELP"}, // LS as a program (Z:\BIN\LS.COM) instead of shell command + { "MD", 0, &DOS_Shell::CMD_MKDIR, "SHELL_CMD_MKDIR_HELP"}, + { "MKDIR", 1, &DOS_Shell::CMD_MKDIR, "SHELL_CMD_MKDIR_HELP"}, + { "MORE", 1, &DOS_Shell::CMD_MORE, "SHELL_CMD_MORE_HELP"}, + { "PATH", 1, &DOS_Shell::CMD_PATH, "SHELL_CMD_PATH_HELP"}, + { "PAUSE", 1, &DOS_Shell::CMD_PAUSE, "SHELL_CMD_PAUSE_HELP"}, + { "PROMPT", 0, &DOS_Shell::CMD_PROMPT, "SHELL_CMD_PROMPT_HELP"}, + { "RD", 0, &DOS_Shell::CMD_RMDIR, "SHELL_CMD_RMDIR_HELP"}, + { "REM", 1, &DOS_Shell::CMD_REM, "SHELL_CMD_REM_HELP"}, + { "REN", 0, &DOS_Shell::CMD_RENAME, "SHELL_CMD_RENAME_HELP"}, + { "RENAME", 1, &DOS_Shell::CMD_RENAME, "SHELL_CMD_RENAME_HELP"}, + { "RMDIR", 1, &DOS_Shell::CMD_RMDIR, "SHELL_CMD_RMDIR_HELP"}, + { "SET", 1, &DOS_Shell::CMD_SET, "SHELL_CMD_SET_HELP"}, + { "SHIFT", 1, &DOS_Shell::CMD_SHIFT, "SHELL_CMD_SHIFT_HELP"}, + { "SUBST", 1, &DOS_Shell::CMD_SUBST, "SHELL_CMD_SUBST_HELP"}, + { "TIME", 0, &DOS_Shell::CMD_TIME, "SHELL_CMD_TIME_HELP"}, + { "TRUENAME", 1, &DOS_Shell::CMD_TRUENAME, "SHELL_CMD_TRUENAME_HELP"}, + { "TYPE", 0, &DOS_Shell::CMD_TYPE, "SHELL_CMD_TYPE_HELP"}, + { "VER", 0, &DOS_Shell::CMD_VER, "SHELL_CMD_VER_HELP"}, + { "VERIFY", 1, &DOS_Shell::CMD_VERIFY, "SHELL_CMD_VERIFY_HELP"}, + { "VOL", 0, &DOS_Shell::CMD_VOL, "SHELL_CMD_VOL_HELP"}, + { "POPD", 1, &DOS_Shell::CMD_POPD, "SHELL_CMD_POPD_HELP"}, + { "PUSHD", 1, &DOS_Shell::CMD_PUSHD, "SHELL_CMD_PUSHD_HELP"}, + #if C_DEBUG + // Additional commands for debugging purposes in DOSBox-X + { "DEBUGBOX", 1, &DOS_Shell::CMD_DEBUGBOX, "SHELL_CMD_DEBUGBOX_HELP"}, + //{ "INT2FDBG", 1, &DOS_Shell::CMD_INT2FDBG, "SHELL_CMD_INT2FDBG_HELP"}, // INT2FDBG as a program (Z:\DEBUG\INT2FDBG.COM) instead of shell command + #endif + // Advanced commands specific to DOSBox-X + //{ "ADDKEY", 1, &DOS_Shell::CMD_ADDKEY, "SHELL_CMD_ADDKEY_HELP"}, // ADDKEY as a program (Z:\BIN\ADDKEY.COM) instead of shell command + { "DX-CAPTURE", 1, &DOS_Shell::CMD_DXCAPTURE, "SHELL_CMD_DXCAPTURE_HELP"}, + { nullptr, 0, nullptr, nullptr } + }; + + const char *GetCmdName(int i) { + size_t n = sizeof(cmd_list)/sizeof(cmd_list[0])-1; + return i>n?NULL:cmd_list[i].name; + } + + extern int enablelfn, lfn_filefind_handle, file_access_tries, lastmsgcp; + extern bool date_host_forced, usecon, outcon, rsize, autoboxdraw, dbcs_sbcs, sync_time, manualtime, inshell, noassoc, dotype, loadlang, chinasea; + extern unsigned long freec; + extern uint8_t DOS_GetAnsiAttr(void); + extern uint16_t countryNo, altcp_to_unicode[256]; + extern bool isDBCSCP(), isKanji1(uint8_t chr), shiftjis_lead_byte(int c), TTF_using(void), Network_IsNetworkResource(const char * filename); + extern bool CheckBoxDrawing(uint8_t c1, uint8_t c2, uint8_t c3, uint8_t c4), GFX_GetPreventFullscreen(void), DOS_SetAnsiAttr(uint8_t attr); + extern bool systemmessagebox(char const * aTitle, char const * aMessage, char const * aDialogType, char const * aIconType, int aDefaultButton); + extern void Load_Language(std::string name), GetExpandedPath(std::string &path); + extern void MAPPER_AutoType(std::vector &sequence, const uint32_t wait_ms, const uint32_t pace_ms, bool choice); + extern void DOS_SetCountry(uint16_t countryNo), DOSV_FillScreen(void); + void clearFontCache(void); + std::string GetDOSBoxXPath(bool withexe=false); + FILE *testLoadLangFile(const char *fname); + Bitu DOS_ChangeCodepage(int32_t codepage, const char* codepagefile); + bool CheckDBCSCP(int32_t codepage), SwitchLanguage(int oldcp, int newcp, bool confirm); + void makestdcp950table(), makeseacp951table(); + #if C_OPENGL + bool OpenGL_using(void); + #endif + void UpdateSDLDrawTexture(); + + static int32_t lastsetcp = 0; + bool CHCP_changed = false; + + /* support functions */ + static char empty_char = 0; + static char* empty_string = &empty_char; + static void StripSpaces(char*&args) { + while(args && *args && isspace(*reinterpret_cast(args))) + args++; + } + + static void StripSpaces(char*&args,char also) { + while(args && *args && (isspace(*reinterpret_cast(args)) || (*args == also))) + args++; + } + + static char* ExpandDot(char*args, char* buffer , size_t bufsize, bool expand) { + if(*args == '.') { + if(*(args+1) == 0){ + safe_strncpy(buffer, "*.*", bufsize); + return buffer; + } + if( (*(args+1) != '.') && (*(args+1) != '\\') && expand) { + buffer[0] = '*'; + buffer[1] = 0; + if (bufsize > 2) strncat(buffer,args,bufsize - 1 /*used buffer portion*/ - 1 /*trailing zero*/ ); + return buffer; + } else + safe_strncpy (buffer, args, bufsize); + } + else safe_strncpy(buffer,args, bufsize); + return buffer; + } + + static char* ExpandDotMore(char*args, char* buffer , size_t bufsize) { + char * find_last; + find_last=strrchr_dbcs(args,'\\'); + if (find_last!=NULL) find_last++; + if (find_last!=NULL && *find_last == '.') { + if(*(find_last+1) == 0){ + safe_strncpy(buffer, args, bufsize); + return buffer; + } + if( (*(find_last+1) != '.')) { + *find_last = 0; + strcpy(buffer, args); + *find_last = '.'; + size_t len = strlen(buffer); + buffer[len] = '*'; + buffer[len+1] = 0; + if (bufsize > len + 2) strncat(buffer,find_last,bufsize - len - 1 /*used buffer portion*/ - 1 /*trailing zero*/ ); + else safe_strncpy(buffer, args, bufsize); + return buffer; + } else + safe_strncpy(buffer, args, bufsize); + } + else safe_strncpy(buffer, args, bufsize); + return buffer; + } + + bool DOS_Shell::CheckConfig(char* cmd_in,char*line) { + bool quote=false; + if (strlen(cmd_in)>2&&cmd_in[0]=='"'&&cmd_in[strlen(cmd_in)-1]=='"') { + cmd_in[strlen(cmd_in)-1]=0; + cmd_in++; + quote=true; + } + Section* test = control->GetSectionFromProperty(cmd_in); + if(!test) return false; + if(line && !line[0]) { + std::string val = test->GetPropValue(cmd_in); + if(val != NO_SUCH_PROPERTY) WriteOut("%s\n",val.c_str()); + return true; + } + char newcom[1024]; newcom[0] = 0; strcpy(newcom,"z:\\system\\config -set "); + if (line != NULL) { + line=trim(line); + if (*line=='=') line=trim(++line); + if (line[0]=='"'&&line[strlen(line)-1]=='"') { + line[strlen(line)-1]=0; + line++; + quote=true; + } + if (quote) strcat(newcom,"\""); + strcat(newcom,test->GetName()); strcat(newcom," "); + strcat(newcom,cmd_in); + strcat(newcom, "="); + strcat(newcom, line); + if (quote) strcat(newcom,"\""); + } else + E_Exit("'line' in CheckConfig is NULL"); + DoCommand(newcom); + return true; + } + + bool enable_config_as_shell_commands = false; + + bool DOS_Shell::execute_shell_cmd(char *name, char *arguments) { + // SHELL_Cmd shell_cmd = {}; /* unused */ + uint32_t cmd_index=0; + while (cmd_list[cmd_index].name) { + if (strcasecmp(cmd_list[cmd_index].name,name)==0) { + (this->*(cmd_list[cmd_index].handler))(arguments); + return true; + } + cmd_index++; + } + return false; + } + + void DOS_Shell::DoCommand(char * line) { + /* First split the line into command and arguments */ + std::string origin_cmd_line = line; + std::string last_alias_cmd; + std::string altered_cmd_line; + int alias_counter = 0; + __do_command_begin: + if (alias_counter > 64) { + WriteOut(MSG_Get("SHELL_EXECUTE_ALIAS_EXPAND_OVERFLOW"), origin_cmd_line.c_str()); + } + line=trim(line); + char cmd_buffer[CMD_MAXLINE]; + char * cmd_write=cmd_buffer; + int c=0,q=0; + while (*line) { + if (*line == '/' || *line == '\t') break; + + if ((q & 1) == 0) { + if (*line == ' ' || *line == '=') break; + + if (*line == '.' || *line == ';' || (*line == ':' && !(c == 1 && tolower(*(line-1)) >= 'a' && tolower(*(line-1)) <= 'z')) || *line == '[' || *line == ']' || *line == '\\' || *line == '/' || *line == '\"' || *line == '+') { //allow stuff like cd.. and dir.exe cd\kees + *cmd_write=0; + if (execute_shell_cmd(cmd_buffer,line)) return; + } + } + c++; + if (*line == '"') q++; + *cmd_write++=*line++; + } + *cmd_write=0; + if (strlen(cmd_buffer)==0) { + if (strlen(line)&&line[0]=='/') WriteOut(MSG_Get("SHELL_EXECUTE_ILLEGAL_COMMAND"),line); + return; + } + cmd_alias_map_t::iterator iter = cmd_alias.find(cmd_buffer); + if (iter != cmd_alias.end() && last_alias_cmd != cmd_buffer) { + alias_counter++; + altered_cmd_line = iter->second + " " + line; + line = (char*)altered_cmd_line.c_str(); + last_alias_cmd = iter->first; + goto __do_command_begin; + } + + /* Check the internal list */ + if (execute_shell_cmd(cmd_buffer,line)) return; + + /* This isn't an internal command execute it */ + char ldir[CROSS_LEN], *p=ldir; + if (strchr(cmd_buffer,'\"')&&DOS_GetSFNPath(cmd_buffer,ldir,false)) { + if (!strchr_dbcs(cmd_buffer, '\\') && strrchr_dbcs(ldir, '\\')) + p=strrchr_dbcs(ldir, '\\')+1; + if (uselfn&&strchr(p, ' ')&&!DOS_FileExists(("\""+std::string(p)+"\"").c_str())) { + bool append=false; + if (DOS_FileExists(("\""+std::string(p)+".COM\"").c_str())) {append=true;strcat(p, ".COM");} + else if (DOS_FileExists(("\""+std::string(p)+".EXE\"").c_str())) {append=true;strcat(p, ".EXE");} + else if (DOS_FileExists(("\""+std::string(p)+".BAT\"").c_str())) {append=true;strcat(p, ".BAT");} + if (append&&DOS_GetSFNPath(("\""+std::string(p)+"\"").c_str(), cmd_buffer,false)) if(Execute(cmd_buffer,line)) return; + } + if(Execute(p,line)) return; + } else + if(Execute(cmd_buffer,line)) return; + if(enable_config_as_shell_commands && CheckConfig(cmd_buffer,line)) return; + std::string errhandler = static_cast(control->GetSection("dos"))->Get_string("badcommandhandler"); + if (errhandler.size()&&!noassoc) { + noassoc=true; + LOG_MSG("errhandler %s line %s\n", errhandler.c_str(), origin_cmd_line.c_str()); + DoCommand((char *)(errhandler+" "+origin_cmd_line).c_str()); + noassoc=false; + } else + WriteOut(MSG_Get("SHELL_EXECUTE_ILLEGAL_COMMAND"),cmd_buffer); + } + + #define HELP(command) \ + if (ScanCMDBool(args,"?")) { \ + uint8_t attr = DOS_GetAnsiAttr(); \ + WriteOut(MSG_Get("SHELL_CMD_" command "_HELP")); \ + const char* long_m = MSG_Get("SHELL_CMD_" command "_HELP_LONG"); \ + WriteOut("\n"); \ + if(strcmp("Message not Found!\n",long_m)) WriteOut(long_m); \ + else WriteOut(command "\n"); \ + if (attr) DOS_SetAnsiAttr(attr); \ + return; \ + } + + #if C_DEBUG + extern Bitu int2fdbg_hook_callback; + static Bitu INT2FDBG_Handler(void) { + if (reg_ax == 0x1605) { /* Windows init broadcast */ + int patience = 500; + Bitu st_seg,st_ofs; + + LOG_MSG("INT 2Fh debug hook: Caught Windows init broadcast results (ES:BX=%04x:%04x DS:SI=%04x:%04x CX=%04x DX=%04x DI=%04x)\n", + SegValue(es),reg_bx, + SegValue(ds),reg_si, + reg_cx,reg_dx,reg_di); + + st_seg = SegValue(es); + st_ofs = reg_bx; + while (st_seg != 0 || st_ofs != 0) { + unsigned char v_major,v_minor; + Bitu st_seg_next,st_ofs_next; + Bitu idrc_seg,idrc_ofs; + Bitu vdev_seg,vdev_ofs; + Bitu name_seg,name_ofs; + char devname[64]; + PhysPt st_o; + + if (--patience <= 0) { + LOG_MSG("**WARNING: Chain is too long. Something might have gotten corrupted\n"); + break; + } + + st_o = PhysMake(st_seg,st_ofs); + /* +0x00: Major, minor version of info structure + * +0x02: pointer to next startup info structure or 0000:0000 + * +0x06: pointer to ASCIIZ name of virtual device or 0000:0000 + * +0x0A: virtual device ref data (pointer to?? or actual data??) or 0000:0000 + * +0x0E: pointer to instance data records or 0000:0000 + * Windows 95 or later (v4.0+): + * +0x12: pointer to optionally-instanced data records or 0000:0000 */ + v_major = mem_readb(st_o+0x00); + v_minor = mem_readb(st_o+0x01); + st_seg_next = mem_readw(st_o+0x02+2); + st_ofs_next = mem_readw(st_o+0x02+0); + name_ofs = mem_readw(st_o+0x06+0); + name_seg = mem_readw(st_o+0x06+2); + vdev_ofs = mem_readw(st_o+0x0A+0); + vdev_seg = mem_readw(st_o+0x0A+2); + idrc_ofs = mem_readw(st_o+0x0A+4); /* FIXME: 0x0E+0 and 0x0E+2 generates weird compiler error WTF?? */ + idrc_seg = mem_readw(st_o+0x0A+6); + + { + devname[0] = 0; + if (name_seg != 0 || name_ofs != 0) { + unsigned char c; + unsigned int i; + PhysPt scan; + + scan = PhysMake(name_seg,name_ofs); + for (i=0;i < 63 && (c=mem_readb(scan++)) != 0;) devname[i++] = (char)c; + devname[i] = 0; + } + } + + LOG_MSG(" >> Version %u.%u\n",v_major,v_minor); + LOG_MSG(" Next entry at %04x:%04x\n",(int)st_seg_next,(int)st_ofs_next); + LOG_MSG(" Virtual device name: %04x:%04x '%s'\n",(int)name_seg,(int)name_ofs,devname); + LOG_MSG(" Virtual dev ref data: %04x:%04x\n",(int)vdev_seg,(int)vdev_ofs); + LOG_MSG(" Instance data records: %04x:%04x\n",(int)idrc_seg,(int)idrc_ofs); + + st_seg = st_seg_next; + st_ofs = st_ofs_next; + } + + LOG_MSG("----END CHAIN\n"); + } + + return CBRET_NONE; + } + + void Int2fhook() { + uint32_t old_int2Fh; + PhysPt w; + + int2fdbg_hook_callback = CALLBACK_Allocate(); + CALLBACK_Setup(int2fdbg_hook_callback,&INT2FDBG_Handler,CB_IRET,"INT 2Fh DBG callback"); + + /* record old vector, set our new vector */ + old_int2Fh = RealGetVec(0x2f); + w = CALLBACK_PhysPointer(int2fdbg_hook_callback); + RealSetVec(0x2f,CALLBACK_RealPointer(int2fdbg_hook_callback)); + + /* overwrite the callback with code to chain the call down, then invoke our callback on the way back up: */ + + /* first, chain to the previous INT 15h handler */ + phys_writeb(w++,(uint8_t)0x9C); //PUSHF + phys_writeb(w++,(uint8_t)0x9A); //CALL FAR
+ phys_writew(w,(uint16_t)(old_int2Fh&0xFFFF)); w += 2; //offset + phys_writew(w,(uint16_t)((old_int2Fh>>16)&0xFFFF)); w += 2; //seg + + /* then, having returned from it, invoke our callback */ + phys_writeb(w++,(uint8_t)0xFE); //GRP 4 + phys_writeb(w++,(uint8_t)0x38); //Extra Callback instruction + phys_writew(w,(uint16_t)int2fdbg_hook_callback); w += 2; //The immediate word + + /* return */ + phys_writeb(w++,(uint8_t)0xCF); //IRET + } + + /* NTS: I know I could just modify the DOS kernel's INT 2Fh code to receive the init call, + * the problem is that at that point, the registers do not yet contain anything interesting. + * all the interesting results of the call are added by TSRs on the way back UP the call + * chain. The purpose of this program therefore is to hook INT 2Fh on the other end + * of the call chain so that we can see the results just before returning INT 2Fh back + * to WIN.COM */ + void DOS_Shell::CMD_INT2FDBG(char * args) { + //HELP("INT2FDBG"); + while (*args == ' ') args++; + + /* TODO: Allow /U to remove INT 2Fh hook */ + if (ScanCMDBool(args,"I")) { + if (int2fdbg_hook_callback == 0) { + Int2fhook(); + LOG_MSG("INT 2Fh debugging hook set\n"); + WriteOut("INT 2Fh hook has been set.\n"); + } else + WriteOut("INT 2Fh hook was already set up.\n"); + } else if (*args) + WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), args); + } + #endif + + void DOS_Shell::CMD_BREAK(char * args) { + HELP("BREAK"); + args = trim(args); + if (!*args) + WriteOut("BREAK is %s\n", dos.breakcheck ? "on" : "off"); + else if (!strcasecmp(args, "OFF")) + dos.breakcheck = false; + else if (!strcasecmp(args, "ON")) + dos.breakcheck = true; + else + WriteOut("Must specify ON or OFF\n"); + } + + bool is_ANSI_installed(Program *shell); + void DOS_Shell::CMD_CLS(char * args) { + HELP("CLS"); + if ((CurMode->type==M_TEXT || IS_PC98_ARCH) && is_ANSI_installed(this)) + WriteOut("\033[2J"); else { - strcpy(path, ""); - strcpy(pattern, full); - } - int k = 0; - for(int i = 0; i < (int)strlen(pattern); i++) - if(pattern[i] != '\"') - pattern[k++] = pattern[i]; - pattern[k] = 0; - strcpy(spath, path); - if(strchr(args, '\"') || uselfn) { - if(!DOS_GetSFNPath(("\"" + std::string(path) + "\\").c_str(), spath, false)) strcpy(spath, path); - if(!strlen(spath) || spath[strlen(spath) - 1] != '\\') strcat(spath, "\\"); - } - std::string pfull = std::string(spath) + std::string(pattern); - int fbak = lfn_filefind_handle; - lfn_filefind_handle = uselfn ? LFN_FILEFIND_INTERNAL : LFN_FILEFIND_NONE; - bool res = DOS_FindFirst(((uselfn && pfull.length() && pfull[0] != '"' ? "\"" : "") + pfull + (uselfn && pfull.length() && pfull[pfull.length() - 1] != '"' ? "\"" : "")).c_str(), 0xffff & ~DOS_ATTR_VOLUME); - if(!res) { - lfn_filefind_handle = fbak; - WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"), args); - dos.dta(save_dta); - return; - } - lfn_filefind_handle = fbak; - //end can't be 0, but if it is we'll get a nice crash, who cares :) - strcpy(sfull, full); - char* end = strrchr_dbcs(full, '\\') + 1; *end = 0; - char* lend = strrchr_dbcs(sfull, '\\') + 1; *lend = 0; - dta = dos.dta(); - bool exist = false; - lfn_filefind_handle = uselfn ? LFN_FILEFIND_INTERNAL : LFN_FILEFIND_NONE; - while(res) { - dta.GetResult(name, lname, size, hsize, date, time, attr); - if(!optF && (attr & DOS_ATTR_READ_ONLY) && !(attr & DOS_ATTR_DIRECTORY)) { - exist = true; - strcpy(end, name); - strcpy(lend, lname); - WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"), uselfn ? sfull : full); - } - else if(!(attr & DOS_ATTR_DIRECTORY)) { - exist = true; - strcpy(end, name); - strcpy(lend, lname); - if(optP) { - WriteOut(MSG_Get("SHELL_CMD_DEL_CONFIRM"), uselfn ? sfull : full); - uint8_t c; - uint16_t n = 1; - DOS_ReadFile(STDIN, &c, &n); - if(c == 3) break; - c = c == ch_y || c == ch_Y ? ch_Y : ch_N; - WriteOut("%c\r\n", c); - if(c == ch_N) { lfn_filefind_handle = uselfn ? LFN_FILEFIND_INTERNAL : LFN_FILEFIND_NONE; res = DOS_FindNext(); continue; } - } - if(strlen(full)) { - std::string pfull = (uselfn || strchr(full, ' ') ? (full[0] != '"' ? "\"" : "") : "") + std::string(full) + (uselfn || strchr(full, ' ') ? (full[strlen(full) - 1] != '"' ? "\"" : "") : ""); - bool reset = false; - if(optF && (attr & DOS_ATTR_READ_ONLY) && DOS_SetFileAttr(pfull.c_str(), attr & ~DOS_ATTR_READ_ONLY)) reset = true; - if(!DOS_UnlinkFile(pfull.c_str())) { - if(optF && reset) DOS_SetFileAttr(pfull.c_str(), attr); - WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"), uselfn ? sfull : full); - } - } - else WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"), uselfn ? sfull : full); - } - res = DOS_FindNext(); - } - lfn_filefind_handle = fbak; - if(!exist) WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"), args); - dos.dta(save_dta); -} - -size_t GetPauseCount() { - uint16_t rows; - if (IS_PC98_ARCH) - rows=real_readb(0x60,0x113) & 0x01 ? 25 : 20; - else - rows=(IS_EGAVGA_ARCH?real_readb(BIOSMEM_SEG,BIOSMEM_NB_ROWS):24)+1; - return (rows > 2u) ? (rows - 2u) : 23u; -} - -struct DtaResult { - char name[DOS_NAMELENGTH_ASCII]; - char lname[LFN_NAMELENGTH+1]; - uint32_t size; - uint32_t hsize; - uint16_t date; - uint16_t time; - uint8_t attr; - - static bool groupDef(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && strcmp(lhs.name, rhs.name) < 0); } - static bool groupExt(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && strcmp(lhs.getExtension(), rhs.getExtension()) < 0); } - static bool groupSize(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && lhs.size+lhs.hsize*0x100000000 < rhs.size+rhs.hsize*0x100000000); } - static bool groupDate(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && (lhs.date < rhs.date || (lhs.date == rhs.date && lhs.time < rhs.time))); } - static bool groupRevDef(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && strcmp(lhs.name, rhs.name) > 0); } - static bool groupRevExt(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && strcmp(lhs.getExtension(), rhs.getExtension()) > 0); } - static bool groupRevSize(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && lhs.size+lhs.hsize*0x100000000 > rhs.size+rhs.hsize*0x100000000); } - static bool groupRevDate(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && (lhs.date > rhs.date || (lhs.date == rhs.date && lhs.time > rhs.time))); } - static bool groupDirs(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY); } - static bool compareName(const DtaResult &lhs, const DtaResult &rhs) { return strcmp(lhs.name, rhs.name) < 0; } - static bool compareExt(const DtaResult &lhs, const DtaResult &rhs) { return strcmp(lhs.getExtension(), rhs.getExtension()) < 0; } - static bool compareSize(const DtaResult &lhs, const DtaResult &rhs) { return lhs.size+lhs.hsize*0x100000000 < rhs.size+rhs.hsize*0x100000000; } - static bool compareDate(const DtaResult &lhs, const DtaResult &rhs) { return lhs.date < rhs.date || (lhs.date == rhs.date && lhs.time < rhs.time); } - - const char * getExtension() const { - const char * ext = empty_string; - if (name[0] != '.') { - ext = strrchr(name, '.'); - if (!ext) ext = empty_string; - } - return ext; - } - -}; - -extern bool ctrlbrk; -std::vector tdirs; - -static bool doDeltree(DOS_Shell * shell, char * args, DOS_DTA dta, bool optY, bool first) { - const char ch_y = MSG_Get("INT21_6523_YESNO_CHARS")[0]; - const char ch_n = MSG_Get("INT21_6523_YESNO_CHARS")[1]; - const char ch_Y = toupper(ch_y); - const char ch_N = toupper(ch_n); - char spath[DOS_PATHLENGTH],sargs[DOS_PATHLENGTH+4],path[DOS_PATHLENGTH+4],full[DOS_PATHLENGTH],sfull[DOS_PATHLENGTH+2]; - if (!DOS_Canonicalize(args,full)||strrchr_dbcs(full,'\\')==NULL) { shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH"));return false; } - if (!DOS_GetSFNPath(args,spath,false)) { - if (first) shell->WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); - return false; - } - if (!uselfn||!DOS_GetSFNPath(args,sfull,true)) strcpy(sfull,full); - sprintf(sargs,"\"%s\"",spath); - bool found=false, fdir=false, res=DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); - if (!res) return false; - //end can't be 0, but if it is we'll get a nice crash, who cares :) - uint16_t attribute=0; - strcpy(path,full); - if (!first&&strlen(args)>3&&!strcmp(args+strlen(args)-4,"\\.\\.")) { - if (strlen(path)&&path[strlen(path)-1]=='\\') path[strlen(path)-1]=0; - if (strlen(path)&&path[strlen(path)-1]!=':') { - bool reset=false; - if(DOS_GetFileAttr(path,&attribute) && (attribute&DOS_ATTR_READ_ONLY)&&DOS_SetFileAttr(path, attribute & ~DOS_ATTR_READ_ONLY)) reset=true; - if (!DOS_RemoveDir(path)&&!(uselfn&&DOS_RemoveDir(sfull))) { - if (reset) DOS_SetFileAttr(path, attribute); - shell->WriteOut(MSG_Get("SHELL_CMD_RMDIR_ERROR"),uselfn?sfull:full); - } - } - return true; - } - *(strrchr_dbcs(path,'\\')+1)=0; - char * end=strrchr_dbcs(full,'\\')+1;*end=0; - char * lend=strrchr_dbcs(sfull,'\\')+1;*lend=0; - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH+1]; - uint32_t size,hsize;uint16_t time,date;uint8_t attr;uint16_t fattr; - std::vector cdirs, cfiles; - cdirs.clear(); - cfiles.clear(); - std::string pfull; - while (res) { - strcpy(spath, path); - dta.GetResult(name,lname,size,hsize,date,time,attr); - if (!((!strcmp(name, ".") || !strcmp(name, "..")) && attr & DOS_ATTR_DIRECTORY)) { - found=true; - strcpy(end,name); - strcpy(lend,lname); - if (strlen(full)&&DOS_GetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), &fattr)) { - uint8_t c; - uint16_t n=1; - if(attr&DOS_ATTR_DIRECTORY) { - if (strcmp(name, ".")&&strcmp(name, "..")) { - if (!optY&&first) { - shell->WriteOut(MSG_Get("SHELL_CMD_RMDIR_FULLTREE_CONFIRM"), uselfn ? sfull : full); - DOS_ReadFile (STDIN,&c,&n); - if (c==3) {shell->WriteOut("^C\r\n");break;} - c = c==ch_y||c==ch_Y ? ch_Y:ch_N; - shell->WriteOut("%c\r\n", c); - if (c==ch_N) {res = DOS_FindNext();continue;} - } - fdir=true; - strcat(spath, name); - strcat(spath, "\\*.*"); - cdirs.emplace_back(std::string(spath)); - } - } else { - if (!optY&&first) { - shell->WriteOut(MSG_Get("SHELL_CMD_RMDIR_SINGLE_CONFIRM"), uselfn ? sfull : full); - DOS_ReadFile (STDIN,&c,&n); - if (c==3) {shell->WriteOut("^C\r\n");break;} - c = c==ch_y||c==ch_Y ? ch_Y:ch_N; - shell->WriteOut("%c\r\n", c); - if (c==ch_N) {res = DOS_FindNext();continue;} - } - pfull=(uselfn||strchr(uselfn?sfull:full, ' ')?((uselfn?sfull:full)[0]!='"'?"\"":""):"")+std::string(uselfn?sfull:full)+(uselfn||strchr(uselfn?sfull:full, ' ')?((uselfn?sfull:full)[strlen(uselfn?sfull:full)-1]!='"'?"\"":""):""); - cfiles.push_back(pfull); - } - } - } - res=DOS_FindNext(); - } - while (!cfiles.empty()) { - bool reset=false; - pfull = std::string(cfiles.begin()->c_str()); - if ((attr & DOS_ATTR_READ_ONLY)&&DOS_SetFileAttr(pfull.c_str(), attr & ~DOS_ATTR_READ_ONLY)) reset=true; - if (!DOS_UnlinkFile(pfull.c_str())) { - if (reset) DOS_SetFileAttr(pfull.c_str(), attr); - shell->WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"),pfull.c_str()); - } - cfiles.erase(cfiles.begin()); - } - if (!first&&strlen(args)>4&&!strcmp(args+strlen(args)-4,"\\*.*")) { - end=strrchr_dbcs(full,'\\')+1;*end=0; - lend=strrchr_dbcs(sfull,'\\')+1;*lend=0; - if (fdir) { - strcpy(spath, path); - strcat(spath, ".\\."); - cdirs.push_back(std::string(spath)); - } else { - if (strlen(path)&&path[strlen(path)-1]=='\\') path[strlen(path)-1]=0; - if (strlen(path)&&path[strlen(path)-1]!=':') { - bool reset=false; - if(DOS_GetFileAttr(path,&attribute) && (attribute&DOS_ATTR_READ_ONLY)&&DOS_SetFileAttr(path, attribute & ~DOS_ATTR_READ_ONLY)) reset=true; - if (!DOS_RemoveDir(path)&&!(uselfn&&DOS_RemoveDir(sfull))) { - if (reset) DOS_SetFileAttr(path, attribute); - shell->WriteOut(MSG_Get("SHELL_CMD_RMDIR_ERROR"),uselfn?sfull:full); - } - } - } - } - tdirs.insert(tdirs.begin()+1, cdirs.begin(), cdirs.end()); - return found; -} - -void DOS_Shell::CMD_DELTREE(char * args) { - //HELP("DELTREE"); - StripSpaces(args); - bool optY=ScanCMDBool(args,"Y"); - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - return; - } - if (!*args) { - WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); - return; - } - - if (uselfn&&strchr(args, '*')) { - char * find_last; - find_last=strrchr_dbcs(args,'\\'); - if (find_last==NULL) find_last=args; - else find_last++; - if (strlen(find_last)>0&&args[strlen(args)-1]=='*'&&strchr(find_last, '.')==NULL) strcat(args, ".*"); - } - char buffer[CROSS_LEN]; - args = ExpandDot(args,buffer, CROSS_LEN, true); - StripSpaces(args); - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - tdirs.clear(); - tdirs.emplace_back(std::string(args)); - bool first=true, found=false; - ctrlbrk=false; - inshell=true; - while (!tdirs.empty()) { - if (doDeltree(this, (char *)tdirs.begin()->c_str(), dta, optY, first)) - found=true; - first=false; - tdirs.erase(tdirs.begin()); - } - inshell=true; - if (!found) WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); - dos.dta(save_dta); -} - -bool CheckBreak(DOS_Shell * shell) { - if (ctrlbrk || dos.errorcode == 77) { - if (dos.errorcode == 77) dos.errorcode = 0; - else if (ctrlbrk) { - ctrlbrk=false; - uint8_t c;uint16_t n=1; - DOS_ReadFile (STDIN,&c,&n); - if (c == 3 && (inshell || dos.errorcode == 77)) shell->WriteOut("^C\r\n"); - if (dos.errorcode == 77) dos.errorcode = 0; - ctrlbrk=false; - } - return true; - } else - return false; -} - -bool cont[200]; -static bool doTree(DOS_Shell * shell, char * args, DOS_DTA dta, bool optA, bool optF) { - char *p=strchr(args, ':'); - bool found=false, last=false, plast=false; - int level=1; - if (p) { - *p=0; - if (*args=='-') { - plast=true; - args++; - } - level=atoi(args); - args=p+1; - if (tdirs.size()<2) last=true; - else { - char * arg=(char *)(tdirs.begin()+1)->c_str(); - p=strchr(arg, ':'); - if (p) { - *p=0; - if (level!=atoi(*arg=='-'?arg+1:arg)) last=true; - *p=':'; - } - } - } - if (level>=200) return false; - char spath[DOS_PATHLENGTH],sargs[DOS_PATHLENGTH+4],path[DOS_PATHLENGTH+4],full[DOS_PATHLENGTH],sfull[DOS_PATHLENGTH+2]; - if (!DOS_Canonicalize(args,full)||strrchr_dbcs(full,'\\')==NULL) { shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH"));return level; } - if (!DOS_GetSFNPath(args,spath,false)) { - if (!level) shell->WriteOut(MSG_Get("SHELL_CMD_TREE_ERROR")); - return level; - } - if (!uselfn||!DOS_GetSFNPath(args,sfull,true)) strcpy(sfull,full); - if (level&&strlen(sfull)>4&&!strcasecmp(sfull+strlen(sfull)-4, "\\*.*")) { - *(sfull+strlen(sfull)-4)=0; - p=strrchr_dbcs(sfull, '\\'); - char c=optA?(last?'\\':'+'):(last?0xc0:0xc3); - cont[level]=!last; - for (int i=1; iWriteOut("%c ", cont[i]?(optA?'|':0xb3):' '); - shell->WriteOut(("%c"+std::string(3, optA?'-':0xc4)+"%s\n").c_str(), c, p?p+1:sfull); - *(sfull+strlen(sfull))='\\'; - } - sprintf(sargs,"\"%s\"",spath); - bool res=DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); - if (!res) { - if (!level) shell->WriteOut(MSG_Get("SHELL_CMD_TREE_ERROR")); - return level; - } - //uint16_t attribute=0; UNUSED - strcpy(path,full); - *(strrchr_dbcs(path,'\\')+1)=0; - char * end=strrchr_dbcs(full,'\\')+1;*end=0; - char * lend=strrchr_dbcs(sfull,'\\')+1;*lend=0; - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH+1]; - uint32_t size,hsize;uint16_t time,date;uint8_t attr;uint16_t fattr; - std::vector cdirs; - cdirs.clear(); - while (res) { - if (CheckBreak(shell)) return false; - strcpy(spath,((plast||(level==1&&last)?"-":"")+std::to_string(level+1)+":").c_str()); - strcat(spath, path); - dta.GetResult(name,lname,size,hsize,date,time,attr); - if (!((!strcmp(name, ".") || !strcmp(name, "..")) && attr & DOS_ATTR_DIRECTORY)) { - strcpy(end,name); - strcpy(lend,lname); - if (strlen(full)&&DOS_GetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), &fattr)) { - if(attr&DOS_ATTR_DIRECTORY) { - if (strcmp(name, ".")&&strcmp(name, "..")) { - strcat(spath, name); - strcat(spath, "\\*.*"); - cdirs.emplace_back(std::string(spath)); - found=true; - } - } else if (optF) { - for (int i=1; i<=level; i++) shell->WriteOut("%c ", (i==1&&level>1?!plast:cont[i])?(optA?'|':0xb3):' '); - shell->WriteOut(" %s\n", uselfn?lname:name); - } - } - } - res=DOS_FindNext(); - } - if (!found&&!level) { - shell->WriteOut(MSG_Get("SHELL_CMD_TREE_ERROR")); - return false; - } - tdirs.insert(tdirs.begin()+1, cdirs.begin(), cdirs.end()); - return true; -} - -bool tree=false; -void DOS_Shell::CMD_TREE(char * args) { - //HELP("TREE"); - StripSpaces(args); - bool optA=ScanCMDBool(args,"A"); - bool optF=ScanCMDBool(args,"F"); - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - return; - } - StripSpaces(args); - char buffer[CROSS_LEN]; - strcpy(buffer, "0:"); - strcat(buffer, *args?args:"."); - if (strlen(args)==2&&args[1]==':') strcat(buffer, "."); - if (args[strlen(args)-1]!='\\') strcat(buffer, "\\"); - strcat(buffer, "*.*"); - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - if (strlen(args)>1&&args[1]==':') { - char c[]=" _:"; - c[1]=toupper(args[0]); - if (!Drives[c[1]-'A']) { - WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); - return; - } - tree=true; - CMD_VOL(c[1]>='A'&&c[1]<='Z'?c:empty_string); - tree=false; - WriteOut("%c:%s\n", c[1], *args?args+2:"."); - } else { - tree=true; - CMD_VOL(empty_string); - tree=false; - uint8_t drive=DOS_GetDefaultDrive(); - WriteOut("%c:%s\n", 'A'+drive, *args?args:"."); - } - for (int i=0; i<200; i++) cont[i]=false; - ctrlbrk=false; - inshell=true; - tdirs.clear(); - tdirs.emplace_back(std::string(buffer)); - while (!tdirs.empty()) { - if (!doTree(this, (char *)tdirs.begin()->c_str(), dta, optA, optF)) break; - tdirs.erase(tdirs.begin()); - } - inshell=false; - dos.dta(save_dta); -} - -void DOS_Shell::CMD_HELP(char * args){ - HELP("HELP"); - bool optall=ScanCMDBool(args,"A")|ScanCMDBool(args,"ALL"); - /* Print the help */ - args = trim(args); - upcase(args); - uint8_t attr = DOS_GetAnsiAttr(); - if(!optall&&!*args) WriteOut(MSG_Get("SHELL_CMD_HELP")); - uint32_t cmd_index=0,write_count=0; - bool show=false; - while (cmd_list[cmd_index].name) { - if (optall || (*args && !strcmp(args, cmd_list[cmd_index].name)) || (!*args && !cmd_list[cmd_index].flags)) { - show=true; - if (*args && !strcmp(args, cmd_list[cmd_index].name) && !optall) { - std::string cmd=std::string(args); - if (cmd=="CD") cmd="CHDIR"; - else if (cmd=="DEL"||cmd=="ERASE") cmd="DELETE"; - else if (cmd=="LH") cmd="LOADHIGH"; - else if (cmd=="MD") cmd="MKDIR"; - else if (cmd=="RD") cmd="RMDIR"; - else if (cmd=="REN") cmd="RENAME"; - else if (cmd=="DX-CAPTURE") cmd="DXCAPTURE"; - WriteOut("%s\n%s",MSG_Get(cmd_list[cmd_index].help), MSG_Get(("SHELL_CMD_" +cmd+ "_HELP_LONG").c_str())); - } else { - WriteOut("<\033[34;1m%-8s\033[0m> %s",cmd_list[cmd_index].name,MSG_Get(cmd_list[cmd_index].help)); - if(!(++write_count%GetPauseCount())) { - WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) {if (attr) DOS_SetAnsiAttr(attr);return;} - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - } - } - } - cmd_index++; - } - if (optall&&show) - WriteOut(MSG_Get("SHELL_CMD_HELP_END1")); - else if (*args&&!show) { - std::string argc=std::string(StripArg(args)); - if (argc!=""&&argc!="CWSDPMI") DoCommand((char *)(argc+(argc=="DOS4GW"||argc=="DOS32A"||argc=="ZIP"||argc=="UNZIP"?"":" /?")).c_str()); - } - if (!*args&&show) - WriteOut(MSG_Get("SHELL_CMD_HELP_END2")); - if (attr) DOS_SetAnsiAttr(attr); -} - -void removeChar(char *str, char c) { - char *src, *dst; - for (src = dst = str; *src != '\0'; src++) { - *dst = *src; - if (*dst != c) dst++; - } - *dst = '\0'; -} - -void DOS_Shell::CMD_RENAME(char * args){ - HELP("RENAME"); - StripSpaces(args); - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - return; - } - if (!*args) {SyntaxError();return;} - char * arg1=StripArg(args); - StripSpaces(args); - if (!*args) {SyntaxError();return;} - char * arg2=StripArg(args); - StripSpaces(args); - if (*args) {SyntaxError();return;} - char* slash = strrchr_dbcs(arg1,'\\'); - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; - char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH+1], tname1[LFN_NAMELENGTH+1], tname2[LFN_NAMELENGTH+1], text1[LFN_NAMELENGTH+1], text2[LFN_NAMELENGTH+1], tfull[CROSS_LEN+2]; - //dir_source and target are introduced for when we support multiple files being renamed. - char sargs[CROSS_LEN], targs[CROSS_LEN], dir_source[DOS_PATHLENGTH + 4] = {0}, dir_target[CROSS_LEN + 4] = {0}, target[CROSS_LEN + 4] = {0}; //not sure if drive portion is included in pathlength - - if (!slash) slash = strrchr(arg1,':'); - if (slash) { - /* If directory specified (crystal caves installer) - * rename from c:\X : rename c:\abc.exe abc.shr. - * File must appear in C:\ - * Ren X:\A\B C => ren X:\A\B X:\A\C */ - - //Copy first and then modify, makes GCC happy - safe_strncpy(dir_source,arg1,DOS_PATHLENGTH + 4); - char* dummy = strrchr_dbcs(dir_source,'\\'); - if (!dummy) dummy = strrchr(dir_source,':'); - if (!dummy) { //Possible due to length - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - dummy++; - *dummy = 0; - if (strchr_dbcs(arg2,'\\')||strchr(arg2,':')) { - safe_strncpy(dir_target,arg2,DOS_PATHLENGTH + 4); - dummy = strrchr_dbcs(dir_target,'\\'); - if (!dummy) dummy = strrchr(dir_target,':'); - if (dummy) { - dummy++; - *dummy = 0; - if (strcasecmp(dir_source, dir_target)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - } - arg2=strrchr_dbcs(arg2,strrchr_dbcs(arg2,'\\')?'\\':':')+1; - } - if (strlen(dummy)&&dummy[strlen(dummy)-1]==':') - strcat(dummy, ".\\"); - } else { - if (strchr_dbcs(arg2,'\\')||strchr(arg2,':')) {SyntaxError();return;}; - strcpy(dir_source, ".\\"); - } - - strcpy(target,arg2); - - char path[DOS_PATHLENGTH], spath[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH], full[DOS_PATHLENGTH], *r; - if (!DOS_Canonicalize(arg1,full)) return; - r=strrchr_dbcs(full, '\\'); - if (r!=NULL) { - *r=0; - strcpy(path, full); - strcat(path, "\\"); - strcpy(pattern, r+1); - *r='\\'; - } else { - strcpy(path, ""); - strcpy(pattern, full); - } - int k=0; - for (int i=0;i<(int)strlen(pattern);i++) - if (pattern[i]!='\"') - pattern[k++]=pattern[i]; - pattern[k]=0; - strcpy(spath, path); - if (strchr(arg1,'\"')||uselfn) { - if (!DOS_GetSFNPath(("\""+std::string(path)+"\\").c_str(), spath, false)) strcpy(spath, path); - if (!strlen(spath)||spath[strlen(spath)-1]!='\\') strcat(spath, "\\"); - } - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - std::string pfull=std::string(spath)+std::string(pattern); - int fbak=lfn_filefind_handle; - lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; - if (!DOS_FindFirst(((uselfn&&pfull.length()&&pfull[0]!='"'?"\"":"")+pfull+(uselfn&&pfull.length()&&pfull[pfull.length()-1]!='"'?"\"":"")).c_str(), strchr(arg1,'*')!=NULL || strchr(arg1,'?')!=NULL ? 0xffff & ~DOS_ATTR_VOLUME & ~DOS_ATTR_DIRECTORY : 0xffff & ~DOS_ATTR_VOLUME)) { - lfn_filefind_handle=fbak; - WriteOut(MSG_Get("SHELL_CMD_RENAME_ERROR"),arg1); - } else { - std::vector sources; - sources.clear(); - - do { /* File name and extension */ - dta.GetResult(name,lname,size,hsize,date,time,attr); - lfn_filefind_handle=fbak; - - if(!(attr&DOS_ATTR_DIRECTORY && (!strcmp(name, ".") || !strcmp(name, "..")))) { - strcpy(dir_target, target); - removeChar(dir_target, '\"'); - arg2=dir_target; - strcpy(sargs, dir_source); - if (uselfn) removeChar(sargs, '\"'); - strcat(sargs, uselfn?lname:name); - if (uselfn&&strchr(arg2,'*')&&!strchr(arg2,'.')) strcat(arg2, ".*"); - char *dot1=strrchr(uselfn?lname:name,'.'), *dot2=strrchr(arg2,'.'), *star; - if (dot2==NULL) { - star=strchr(arg2,'*'); - if (strchr(arg2,'?')) { - for (unsigned int i=0; i<(uselfn?LFN_NAMELENGTH:DOS_NAMELENGTH) && i<(star?star-arg2:strlen(arg2)); i++) { - if (*(arg2+i)=='?'&&i2&&sargs[0]=='.'&&sargs[1]=='\\'?sargs+2:sargs); - } - lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; - } while ( DOS_FindNext() ); - lfn_filefind_handle=fbak; - if (sources.empty()) WriteOut(MSG_Get("SHELL_CMD_RENAME_ERROR"),arg1); - else { - for (std::vector::iterator source = sources.begin(); source != sources.end(); ++source) { - char *oname=(char *)source->c_str(); - source++; - if (source==sources.end()) break; - char *nname=(char *)source->c_str(); - source++; - if (source==sources.end()||oname==NULL||nname==NULL) break; - char *fname=(char *)source->c_str(); - if (!DOS_Rename(oname,nname)&&fname!=NULL) - WriteOut(MSG_Get("SHELL_CMD_RENAME_ERROR"),fname); - } - } - } - dos.dta(save_dta); -} - -void DOS_Shell::CMD_ECHO(char * args){ - if (!*args) { - if (echo) { WriteOut(MSG_Get("SHELL_CMD_ECHO_ON"));} - else { WriteOut(MSG_Get("SHELL_CMD_ECHO_OFF"));} - return; - } - char buffer[512]; - char* pbuffer = buffer; - safe_strncpy(buffer,args,512); - StripSpaces(pbuffer); - if (strcasecmp(pbuffer,"OFF")==0) { - echo=false; - return; - } - if (strcasecmp(pbuffer,"ON")==0) { - echo=true; - return; - } - if(strcasecmp(pbuffer,"/?")==0) { HELP("ECHO"); } - - args++;//skip first character. either a slash or dot or space - size_t len = strlen(args); //TODO check input of else ook nodig is. - if(len && args[len - 1] == '\r') { - LOG(LOG_MISC,LOG_WARN)("Hu ? carriage return already present. Is this possible?"); - WriteOut_NoParsing(args, true); - WriteOut("\n"); - } else { - WriteOut_NoParsing(args, true); - WriteOut("\r\n"); - } -} - -void DOS_Shell::CMD_EXIT(char * args) { - HELP("EXIT"); - exit = true; -} - -std::vector olddrives; -std::vector olddirs; -void DOS_Shell::CMD_PUSHD(char * args) { - HELP("PUSHD"); - StripSpaces(args); - char sargs[CROSS_LEN]; - if (strlen(args)>1 && args[1]==':' && toupper(args[0])>='A' && toupper(args[0])<='Z' && !Drives[toupper(args[0])-'A']) { - WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); - return; - } - if (*args && !DOS_GetSFNPath(args,sargs,false)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - if (*args) { - char dir[DOS_PATHLENGTH]; - uint8_t drive = DOS_GetDefaultDrive()+'A'; - DOS_GetCurrentDir(0,dir,true); - if (strlen(args)>1 && args[1]==':') DOS_SetDefaultDrive(toupper(args[0])-'A'); - if (DOS_ChangeDir(sargs)) { - olddrives.push_back(drive); - olddirs.emplace_back(std::string(dir)); - } else { - if (strlen(args)>1 && args[1]==':') DOS_SetDefaultDrive(drive-'A'); - WriteOut(MSG_Get("SHELL_CMD_CHDIR_ERROR"),args); - } - } else { - for (int i=(int)(olddrives.size()-1); i>=0; i--) - if (olddrives.at(i)>='A'&&olddrives.at(i)<='Z') - WriteOut("%c:\\%s\n",olddrives.at(i),olddirs.at(i).c_str()); - } -} - -void DOS_Shell::CMD_POPD(char * args) { - HELP("POPD"); - if (!olddrives.size()) return; - uint8_t olddrive=olddrives.back(); - std::string olddir=olddirs.back(); - if (olddrive>='A'&&olddrive<='Z'&&Drives[olddrive-'A']) { - uint8_t drive = DOS_GetDefaultDrive()+'A'; - if (olddrive!=DOS_GetDefaultDrive()+'A') DOS_SetDefaultDrive(olddrive-'A'); - if (Drives[DOS_GetDefaultDrive()]->TestDir(olddir.c_str())) - strcpy(Drives[DOS_GetDefaultDrive()]->curdir,olddir.c_str()); - else - DOS_SetDefaultDrive(drive-'A'); - } - olddrives.pop_back(); - olddirs.pop_back(); -} - -void DOS_Shell::CMD_CHDIR(char * args) { - HELP("CHDIR"); - StripSpaces(args); - char sargs[CROSS_LEN]; - if (*args && !DOS_GetSFNPath(args,sargs,false)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - uint8_t drive = DOS_GetDefaultDrive()+'A'; - char dir[DOS_PATHLENGTH]; - if (!*args) { - DOS_GetCurrentDir(0,dir,true); - WriteOut("%c:\\",drive); - WriteOut_NoParsing(dir, true); - WriteOut("\n"); - } else if(strlen(args) == 2 && args[1]==':') { - uint8_t targetdrive = (args[0] | 0x20)-'a' + 1; - unsigned char targetdisplay = *reinterpret_cast(&args[0]); - if(!DOS_GetCurrentDir(targetdrive,dir,true)) { // verify that this should be true - if(drive == 'Z') { - WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_NOT_FOUND"),toupper(targetdisplay)); - } else { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - } - return; - } - WriteOut("%c:\\",toupper(targetdisplay)); - WriteOut_NoParsing(dir, true); - WriteOut("\n"); - if(drive == 'Z') - WriteOut(MSG_Get("SHELL_CMD_CHDIR_HINT"),toupper(targetdisplay)); - } else if (!DOS_ChangeDir(sargs)) { - /* Changedir failed. Check if the filename is longer than 8 and/or contains spaces */ - - std::string temps(args),slashpart; - std::string::size_type separator = temps.find_first_of("\\/"); - if(!separator) { - slashpart = temps.substr(0,1); - temps.erase(0,1); - } - separator = temps.find_first_of("\""); - if(separator != std::string::npos) temps.erase(separator); - separator = temps.rfind('.'); - if(separator != std::string::npos) temps.erase(separator); - separator = temps.find(' '); - if(separator != std::string::npos) {/* Contains spaces */ - temps.erase(separator); - if(temps.size() >6) temps.erase(6); - temps += "~1"; - WriteOut(MSG_Get("SHELL_CMD_CHDIR_HINT_2"),temps.insert(0,slashpart).c_str()); - } else { - if (drive == 'Z') { - WriteOut(MSG_Get("SHELL_CMD_CHDIR_HINT_3")); - } else { - WriteOut(MSG_Get("SHELL_CMD_CHDIR_ERROR"),args); - } - } - } -} - -void DOS_Shell::CMD_MKDIR(char * args) { - HELP("MKDIR"); - StripSpaces(args); - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - return; - } - if (!*args) { - WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); - return; - } - if (!DOS_MakeDir(args)) { - WriteOut(MSG_Get(dos.errorcode==DOSERR_ACCESS_DENIED?"SHELL_CMD_MKDIR_EXIST":"SHELL_CMD_MKDIR_ERROR"),args); - } -} - -void DOS_Shell::CMD_RMDIR(char * args) { - HELP("RMDIR"); - // ignore /s,and /q switches for compatibility - ScanCMDBool(args,"S"); - ScanCMDBool(args,"Q"); - StripSpaces(args); - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - return; - } - if (!*args) { - WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); - return; - } - if (!DOS_RemoveDir(args)) { - WriteOut(MSG_Get("SHELL_CMD_RMDIR_ERROR"),args); - } -} - -static void FormatNumber(uint64_t num,char * buf) { - uint64_t numo = num; - uint32_t numb,numk,numm,numg,nummi,numgi,numti,numpi,numei; - numb=num % 1000; - num/=1000; - numk=num % 1000; - num/=1000; - numm=num % 1000; - num/=1000; - numg=num % 1000; - numo/=1024; - numo/=1024; - nummi=(numo % 1024) / 10.24 + 0.5; - numo/=1024; - numgi=numo % 1000; - numo/=1000; - numti=numo % 1000; - numo/=1000; - numpi=numo % 1000; - numei=numo / 1000; - if (numei) { - sprintf(buf,"%u%c%03u%c%03u%c%03u%c%02u G",numei,dos.tables.country[7],numpi,dos.tables.country[7],numti,dos.tables.country[7],numgi,dos.tables.country[9],nummi); - return; - } - if (numpi) { - sprintf(buf,"%u%c%03u%c%03u%c%02u G",numpi,dos.tables.country[7],numti,dos.tables.country[7],numgi,dos.tables.country[9],nummi); - return; - } - if (numti) { - sprintf(buf,"%u%c%03u%c%02u G",numti,dos.tables.country[7],numgi,dos.tables.country[9],nummi); - return; - } - if (numg) { - if (numgi>127) sprintf(buf,"%u%c%02u G",numgi,dos.tables.country[9],nummi); - else sprintf(buf,"%u%c%03u%c%03u%c%03u",numg,dos.tables.country[7],numm,dos.tables.country[7],numk,dos.tables.country[7],numb); - return; - } - if (numm) { - sprintf(buf,"%u%c%03u%c%03u",numm,dos.tables.country[7],numk,dos.tables.country[7],numb); - return; - } - if (numk) { - sprintf(buf,"%u%c%03u",numk,dos.tables.country[7],numb); - return; - } - sprintf(buf,"%u",numb); -} - -char buffer[15] = {0}; -char *FormatDate(uint16_t year, uint8_t month, uint8_t day) { - char formatstring[6], c=dos.tables.country[11]; - sprintf(formatstring, dos.tables.country[0]==1?"D%cM%cY":(dos.tables.country[0]==2?"Y%cM%cD":"M%cD%cY"), c, c); - Bitu bufferptr=0; - for(Bitu i = 0; i < 5; i++) { - if(i==1 || i==3) { - buffer[bufferptr] = formatstring[i]; - bufferptr++; - } else { - if(formatstring[i]=='M') bufferptr += (Bitu)sprintf(buffer+bufferptr,"%02u", month); - if(formatstring[i]=='D') bufferptr += (Bitu)sprintf(buffer+bufferptr,"%02u", day); - if(formatstring[i]=='Y') bufferptr += (Bitu)sprintf(buffer+bufferptr,"%04u", year); - } - } - return buffer; -} - -char *FormatTime(Bitu hour, Bitu min, Bitu sec, Bitu msec) { - Bitu fhour=hour; - static char retBuf[14]; - char ampm[3]=""; - if (!(dos.tables.country[17]&1)) { // 12 hour notation? - if (hour!=12) - hour %= 12; - strcpy(ampm, hour != 12 && hour == fhour ? "am" : "pm"); - } - char sep = dos.tables.country[13]; - if (sec>=100&&msec>=100) - sprintf(retBuf, "%2u%c%02u%c", (unsigned int)hour, sep, (unsigned int)min, *ampm); - else - sprintf(retBuf, "%u%c%02u%c%02u%c%02u%s", (unsigned int)hour, sep, (unsigned int)min, sep, (unsigned int)sec, dos.tables.country[9], (unsigned int)msec, ampm); - return retBuf; - } - -uint64_t byte_count; -uint32_t file_count,dir_count; -Bitu p_count; -std::vector dirs, adirs; -static bool dirPaused(DOS_Shell * shell, Bitu w_size, bool optP, bool optW, bool show=true) { - p_count+=optW?5:1; - if (optP && p_count%(GetPauseCount()*w_size)<1) { - shell->WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) {if (show) shell->WriteOut("^C\r\n");return false;} - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - } - return true; -} - -static bool doDir(DOS_Shell * shell, char * args, DOS_DTA dta, char * numformat, Bitu w_size, bool optW, bool optZ, bool optS, bool optP, bool optB, bool optA, bool optAD, bool optAminusD, bool optAS, bool optAminusS, bool optAH, bool optAminusH, bool optAR, bool optAminusR, bool optAA, bool optAminusA, bool optOGN, bool optOGD, bool optOGE, bool optOGS, bool optOG, bool optON, bool optOD, bool optOE, bool optOS, bool reverseSort, bool rev2Sort) { - char path[DOS_PATHLENGTH]; - char sargs[CROSS_LEN], largs[CROSS_LEN], buffer[CROSS_LEN]; - unsigned int tcols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - if (!tcols) tcols=80; - - /* Make a full path in the args */ - if (!DOS_Canonicalize(args,path)) { - shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return true; - } - *(strrchr_dbcs(path,'\\')+1)=0; - if (!DOS_GetSFNPath(path,sargs,false)) { - shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return true; - } - if (!optB&&!optS) { - shell->WriteOut(MSG_Get("SHELL_CMD_DIR_INTRO"),uselfn&&!optZ&&DOS_GetSFNPath(path,largs,true)?largs:sargs); - if (optP) { - p_count+=optW?10:2; - if (p_count%(GetPauseCount()*w_size)<2) { - shell->WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) return false; - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - } - } - } - if (*(sargs+strlen(sargs)-1) != '\\') strcat(sargs,"\\"); - - uint64_t cbyte_count=0; - uint32_t cfile_count=0,w_count=0; - int fbak=lfn_filefind_handle; - lfn_filefind_handle=uselfn&&!optZ?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; - bool ret=DOS_FindFirst(args,0xffff & ~DOS_ATTR_VOLUME), found=true, first=true; - if (!ret) { - size_t len = strlen(args); - args = ExpandDotMore(args,buffer,CROSS_LEN); - if (strlen(args)!=len) ret=DOS_FindFirst(args,0xffff & ~DOS_ATTR_VOLUME); - } - lfn_filefind_handle=fbak; - if (ret) { - std::vector results; - - lfn_filefind_handle=uselfn&&!optZ?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; - do { /* File name and extension */ - DtaResult result; - dta.GetResult(result.name,result.lname,result.size,result.hsize,result.date,result.time,result.attr); - - /* Skip non-directories if option AD is present, or skip dirs in case of A-D */ - if(optAD && !(result.attr&DOS_ATTR_DIRECTORY) ) continue; - else if(optAminusD && (result.attr&DOS_ATTR_DIRECTORY) ) continue; - else if(optAS && !(result.attr&DOS_ATTR_SYSTEM) ) continue; - else if(optAminusS && (result.attr&DOS_ATTR_SYSTEM) ) continue; - else if(optAH && !(result.attr&DOS_ATTR_HIDDEN) ) continue; - else if(optAminusH && (result.attr&DOS_ATTR_HIDDEN) ) continue; - else if(optAR && !(result.attr&DOS_ATTR_READ_ONLY) ) continue; - else if(optAminusR && (result.attr&DOS_ATTR_READ_ONLY) ) continue; - else if(optAA && !(result.attr&DOS_ATTR_ARCHIVE) ) continue; - else if(optAminusA && (result.attr&DOS_ATTR_ARCHIVE) ) continue; - else if(!(optA||optAD||optAminusD||optAS||optAminusS||optAH||optAminusH||optAR||optAminusR||optAA||optAminusA) && (result.attr&DOS_ATTR_SYSTEM || result.attr&DOS_ATTR_HIDDEN) && strcmp(result.name, "..") ) continue; - - results.push_back(result); - - } while ( (ret=DOS_FindNext()) ); - lfn_filefind_handle=fbak; - - bool oneRev = (reverseSort||rev2Sort)&&reverseSort!=rev2Sort; - if (optON) { - // Sort by name - std::sort(results.begin(), results.end(), DtaResult::compareName); - } else if (optOE) { - // Sort by extension - std::sort(results.begin(), results.end(), DtaResult::compareExt); - } else if (optOD) { - // Sort by date - std::sort(results.begin(), results.end(), DtaResult::compareDate); - } else if (optOS) { - // Sort by size - std::sort(results.begin(), results.end(), DtaResult::compareSize); - } else if (optOG) { - // Directories first, then files - std::sort(results.begin(), results.end(), DtaResult::groupDirs); - } else if (optOGN) { - // Directories first, then files, both sort by name - std::sort(results.begin(), results.end(), oneRev?DtaResult::groupRevDef:DtaResult::groupDef); - } else if (optOGE) { - // Directories first, then files, both sort by extension - std::sort(results.begin(), results.end(), oneRev?DtaResult::groupRevExt:DtaResult::groupExt); - } else if (optOGS) { - // Directories first, then files, both sort by size - std::sort(results.begin(), results.end(), oneRev?DtaResult::groupRevSize:DtaResult::groupSize); - } else if (optOGD) { - // Directories first, then files, both sort by date - std::sort(results.begin(), results.end(), oneRev?DtaResult::groupRevDate:DtaResult::groupDate); - } - if (reverseSort) std::reverse(results.begin(), results.end()); - - for (std::vector::iterator iter = results.begin(); iter != results.end(); ++iter) { - if (CheckBreak(shell)) return false; - char * name = iter->name; - char *lname = iter->lname; - uint32_t size = iter->size; - uint32_t hsize = iter->hsize; - uint16_t date = iter->date; - uint16_t time = iter->time; - uint8_t attr = iter->attr; - - /* output the file */ - if (optB) { - // this overrides pretty much everything - if (strcmp(".",uselfn&&!optZ?lname:name) && strcmp("..",uselfn&&!optZ?lname:name)) { - int m=shell->WriteOut_NoParsing(uselfn&&!optZ?lname:name, true); - shell->WriteOut("\n"); - if (optP) { - p_count+=m+1; - if (p_count%GetPauseCount()WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) return false; - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - p_count=0; - } - } - } - } else { - if (first&&optS) { - first=false; - shell->WriteOut("\n"); - shell->WriteOut(MSG_Get("SHELL_CMD_DIR_INTRO"),uselfn&&!optZ&&DOS_GetSFNPath(path,largs,true)?largs:sargs); - if (optP) { - p_count+=optW?15:3; - if (optS&&p_count%(GetPauseCount()*w_size)<3) { - shell->WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) return false; - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - } - } - } - char * ext = empty_string; - if (!optW && (name[0] != '.')) { - ext = strrchr(name, '.'); - if (!ext) ext = empty_string; - else *ext++ = 0; - } - uint8_t day = (uint8_t)(date & 0x001f); - uint8_t month = (uint8_t)((date >> 5) & 0x000f); - uint16_t year = (uint16_t)((date >> 9) + 1980); - uint8_t hour = (uint8_t)((time >> 5 ) >> 6); - uint8_t minute = (uint8_t)((time >> 5) & 0x003f); - unsigned int m=0; - if (attr & DOS_ATTR_DIRECTORY) { - if (optW) { - shell->WriteOut("[%s]",name); - size_t namelen = strlen(name); - if (namelen <= 14) { - for (size_t i=14-namelen;i>0;i--) shell->WriteOut(" "); - } - } else { - shell->WriteOut("%-8s %-3s %-16s %s %s",name,ext,"",FormatDate(year,month,day),FormatTime(hour,minute,100,100)); - if (uselfn&&!optZ) { - shell->WriteOut(" "); - m=shell->WriteOut_NoParsing(lname, true); - } - shell->WriteOut("\n"); - if (optP) { - p_count+=(optW?5:1)*m; - if (p_count%(GetPauseCount()*w_size)WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) return false; - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - p_count=0; - } - } - } - dir_count++; - } else { - if (optW) { - shell->WriteOut("%-16s",name); - } else { - FormatNumber(size+hsize*0x100000000,numformat); - shell->WriteOut("%-8s %-3s %16s %s %s",name,ext,numformat,FormatDate(year,month,day),FormatTime(hour,minute,100,100)); - if (uselfn&&!optZ) { - shell->WriteOut(" "); - m=shell->WriteOut_NoParsing(lname, true); - } - shell->WriteOut("\n"); - if (optP) { - p_count+=(optW?5:1)*m; - if (p_count%(GetPauseCount()*w_size)WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) return false; - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - p_count=0; - } - } - } - if (optS) { - cfile_count++; - cbyte_count+=size+hsize*0x100000000; - } - file_count++; - byte_count+=size+hsize*0x100000000; - } - if (optW) w_count++; - } - if (optW && w_count%5==0 && tcols>80) shell->WriteOut("\n"); - if (optP && !optB && !(++p_count%(GetPauseCount()*w_size))) { - if (optW&&w_count%5) {shell->WriteOut("\n");w_count=0;} - shell->WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) return false; - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - } - } - - if (!results.size()) - found=false; - else if (optW&&w_count%5) - shell->WriteOut("\n"); - } else - found=false; - if (!found&&!optB&&!optS) { - shell->WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); - if (!dirPaused(shell, w_size, optP, optW, false)) return false; - } - if (optS) { - size_t len=strlen(sargs); - strcat(sargs, "*.*"); - bool ret=DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); - *(sargs+len)=0; - if (ret) { - std::vector cdirs; - cdirs.clear(); - do { /* File name and extension */ - DtaResult result; - dta.GetResult(result.name,result.lname,result.size,result.hsize,result.date,result.time,result.attr); - - if(result.attr&DOS_ATTR_DIRECTORY && strcmp(result.name, ".")&&strcmp(result.name, "..")) { - strcat(sargs, result.name); - strcat(sargs, "\\"); - char *fname = strrchr_dbcs(args, '\\'); - if (fname==NULL) fname=args; - else fname++; - strcat(sargs, fname); - cdirs.push_back((sargs[0]!='"'&&sargs[strlen(sargs)-1]=='"'?"\"":"")+std::string(sargs)); - *(sargs+len)=0; - } - } while ( (ret=DOS_FindNext()) ); - dirs.insert(dirs.begin()+1, cdirs.begin(), cdirs.end()); - } - if (found&&!optB) { - FormatNumber(cbyte_count,numformat); - shell->WriteOut(MSG_Get("SHELL_CMD_DIR_BYTES_USED"),cfile_count,numformat); - if (!dirPaused(shell, w_size, optP, optW, false)) return false; - } - } - return true; -} - -void DOS_Shell::CMD_DIR(char * args) { - HELP("DIR"); - char numformat[64]; - char path[DOS_PATHLENGTH]; - char sargs[CROSS_LEN]; - - std::string line; - if(GetEnvStr("DIRCMD",line)){ - std::string::size_type idx = line.find('='); - std::string value=line.substr(idx +1 , std::string::npos); - line = std::string(args) + " " + value; - args=const_cast(line.c_str()); - } - - ScanCMDBool(args,"4"); /* /4 ignored (default) */ - bool optW=ScanCMDBool(args,"W"); - bool optP=ScanCMDBool(args,"P"); - if (ScanCMDBool(args,"WP") || ScanCMDBool(args,"PW")) optW=optP=true; - if (ScanCMDBool(args,"-W")) optW=false; - if (ScanCMDBool(args,"-P")) optP=false; - bool optZ=ScanCMDBool(args,"Z"); - if (ScanCMDBool(args,"-Z")) optZ=false; - bool optS=ScanCMDBool(args,"S"); - if (ScanCMDBool(args,"-S")) optS=false; - bool optB=ScanCMDBool(args,"B"); - if (ScanCMDBool(args,"-B")) optB=false; - bool optA=ScanCMDBool(args,"A"); - bool optAD=ScanCMDBool(args,"AD")||ScanCMDBool(args,"A:D"); - bool optAminusD=ScanCMDBool(args,"A-D")||ScanCMDBool(args,"A:-D"); - bool optAS=ScanCMDBool(args,"AS")||ScanCMDBool(args,"A:S"); - bool optAminusS=ScanCMDBool(args,"A-S")||ScanCMDBool(args,"A:-S"); - bool optAH=ScanCMDBool(args,"AH")||ScanCMDBool(args,"A:H"); - bool optAminusH=ScanCMDBool(args,"A-H")||ScanCMDBool(args,"A:-H"); - bool optAR=ScanCMDBool(args,"AR")||ScanCMDBool(args,"A:R"); - bool optAminusR=ScanCMDBool(args,"A-R")||ScanCMDBool(args,"A:-R"); - bool optAA=ScanCMDBool(args,"AA")||ScanCMDBool(args,"A:A"); - bool optAminusA=ScanCMDBool(args,"A-A")||ScanCMDBool(args,"A:-A"); - if (ScanCMDBool(args,"-A")) { - optA = false; - optAD = false; - optAminusD = false; - optAS = false; - optAminusS = false; - optAH = false; - optAminusH = false; - optAR = false; - optAminusR = false; - optAA = false; - optAminusA = false; - } - // Sorting flags - bool reverseSort = false, rev2Sort = false; - bool optON=ScanCMDBool(args,"ON")||ScanCMDBool(args,"O:N"); - if (ScanCMDBool(args,"O-N")||ScanCMDBool(args,"O:-N")) { - optON = true; - reverseSort = true; - } - bool optOD=ScanCMDBool(args,"OD")||ScanCMDBool(args,"O:D"); - if (ScanCMDBool(args,"O-D")||ScanCMDBool(args,"O:-D")) { - optOD = true; - reverseSort = true; - } - bool optOE=ScanCMDBool(args,"OE")||ScanCMDBool(args,"O:E"); - if (ScanCMDBool(args,"O-E")||ScanCMDBool(args,"O:-E")) { - optOE = true; - reverseSort = true; - } - bool optOS=ScanCMDBool(args,"OS")||ScanCMDBool(args,"O:S"); - if (ScanCMDBool(args,"O-S")||ScanCMDBool(args,"O:-S")) { - optOS = true; - reverseSort = true; - } - bool optOG=ScanCMDBool(args,"OG")||ScanCMDBool(args,"O:G"); - if (ScanCMDBool(args,"O-G")||ScanCMDBool(args,"O:-G")) { - optOG = true; - reverseSort = true; - } - bool b0 = false, b1 = false, b2 = false, b3 = false; - bool optOGN = false, optOGD = false, optOGE = false, optOGS = false; - b0=ScanCMDBool(args,"O")||ScanCMDBool(args,"OGN")||ScanCMDBool(args,"O:GN");b1=ScanCMDBool(args,"O-GN")||ScanCMDBool(args,"O:-GN"); - b2=ScanCMDBool(args,"O-G-N")||ScanCMDBool(args,"O:-G-N"),b3=ScanCMDBool(args,"OG-N")||ScanCMDBool(args,"O:G-N"); - if (b0||b1||b2||b3) { - optOGN = true; - reverseSort = b1||b2; - rev2Sort = b2||b3; - } - b0=ScanCMDBool(args,"OGD")||ScanCMDBool(args,"O:GD");b1=ScanCMDBool(args,"O-GD")||ScanCMDBool(args,"O:-GD"); - b2=ScanCMDBool(args,"O-G-D")||ScanCMDBool(args,"O:-G-D");b3=ScanCMDBool(args,"OG-D")||ScanCMDBool(args,"O:G-D"); - if (b0||b1||b2||b3) { - optOGD = true; - reverseSort = b1||b2; - rev2Sort = b2||b3; - } - b0=ScanCMDBool(args,"OGE")||ScanCMDBool(args,"O:GE");b1=ScanCMDBool(args,"O-GE")||ScanCMDBool(args,"O:-GE"); - b2=ScanCMDBool(args,"O-G-E")||ScanCMDBool(args,"O:-G-E");b3=ScanCMDBool(args,"OG-E")||ScanCMDBool(args,"O:G-E"); - if (b0||b1||b2||b3) { - optOGE = true; - reverseSort = b1||b2; - rev2Sort = b2||b3; - } - b0=ScanCMDBool(args,"OGS")||ScanCMDBool(args,"O:GS");b1=ScanCMDBool(args,"O-GS")||ScanCMDBool(args,"O:-GS"); - b2=ScanCMDBool(args,"O-G-S")||ScanCMDBool(args,"O:-G-S");b3=ScanCMDBool(args,"OG-S")||ScanCMDBool(args,"O:G-S"); - if (b0||b1||b2||b3) { - optOGS = true; - reverseSort = b1||b2; - rev2Sort = b2||b3; - } - if (optOGN||optOGD||optOGE||optOGS) optOG = false; - if (ScanCMDBool(args,"-O")) { - optOG = false; - optON = false; - optOD = false; - optOE = false; - optOS = false; - optOGN = false; - optOGD = false; - optOGE = false; - optOGS = false; - reverseSort = false; - } - const char *valid[] = {"4","W","P","-W","-P","WP","PW","Z","-Z","S","-S","B","-B", - "A","-A","AD","A:D","A-D","A:-D","AS","A:S","A-S","A:-S","AH","A:H","A-H","A:-H","AR","A:R","A-R","A:-R","AA","A:A","A-A","A:-A", - "O","-O","ON","O:N","O-N","O:-N","OD","O:D","O-D","O:-D","OE","O:E","O-E","O:-E","OS","O:S","O-S","O:-S","OG","O:G","O-G","O:-G", - "OGN","O:GN","O-GN","O:-GN","OG-N","O:G-N","O-G-N","O:-G-N","OGD","O:GD","O-GD","O:-GD","OG-D","O:G-D","O-G-D","O:-G-D", - "OGE","O:GE","O-GE","O:-GE","OG-E","O:G-E","O-G-E","O:-G-E","OGS","O:GS","O-GS","O:-GS","OG-S","O:G-S","O-G-S","O:-G-S", - NULL}; - if (args && strlen(args)>1) for (int i=0; valid[i] && *args && strchr(args,'/'); i++) while (ScanCMDBool(args,valid[i])); - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - return; - } - byte_count=0;file_count=0;dir_count=0;p_count=0; - Bitu w_size = optW?5:1; - - char buffer[CROSS_LEN]; - args = trim(args); - size_t argLen = strlen(args); - if (argLen == 0) { - strcpy(args,"*.*"); //no arguments. - } else { - // handle \, C:\, etc. handle C:, etc. - if(check_last_split_char(args, argLen, '\\') || args[argLen-1] == ':') { - strcat(args,"*.*"); - } - } - args = ExpandDot(args,buffer,CROSS_LEN,!uselfn); - - if (DOS_FindDevice(args) != DOS_DEVICES) { - WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); - return; - } - if (!strrchr(args,'*') && !strrchr(args,'?')) { - uint16_t attribute=0; - if(!DOS_GetSFNPath(args,sargs,false)) { - if (strlen(args)>1&&toupper(args[0])>='A'&&toupper(args[0])<='Z'&&args[1]==':'&&!Drives[toupper(args[0])-'A']) - WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); - else - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - if(DOS_GetFileAttr(sargs,&attribute) && (attribute&DOS_ATTR_DIRECTORY) ) { - DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); - DOS_DTA dta(dos.dta()); - strcpy(args,sargs); - strcat(args,"\\*.*"); // if no wildcard and a directory, get its files - } - } - if (!DOS_GetSFNPath(args,sargs,false)) { - if (strlen(args)>1&&toupper(args[0])>='A'&&toupper(args[0])<='Z'&&args[1]==':'&&!Drives[toupper(args[0])-'A']) - WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); - else - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - if (!(uselfn&&!optZ&&strchr(sargs,'*'))&&!strrchr(sargs,'.')) - strcat(sargs,".*"); // if no extension, get them all - sprintf(args,"\"%s\"",sargs); - - /* Make a full path in the args */ - if (!DOS_Canonicalize(args,path)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - *(strrchr_dbcs(path,'\\')+1)=0; - if (!DOS_GetSFNPath(path,sargs,true)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - if (*(sargs+strlen(sargs)-1) != '\\') strcat(sargs,"\\"); - if (!optB) { -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(args)) { - WriteOut("\n"); - if (optP) p_count+=optW?5:1; - } else -#endif - { - if (strlen(sargs)>2&&sargs[1]==':') { - char c[]=" _:"; - c[1]=toupper(sargs[0]); - CMD_VOL(c[1]>='A'&&c[1]<='Z'?c:empty_string); - } else - CMD_VOL(empty_string); - if (optP) p_count+=optW?15:3; - } - } - - /* Command uses dta so set it to our internal dta */ - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - dirs.clear(); - dirs.emplace_back(std::string(args)); - inshell=true; - while (!dirs.empty()) { - ctrlbrk=false; - if (!doDir(this, (char *)dirs.begin()->c_str(), dta, numformat, w_size, optW, optZ, optS, optP, optB, optA, optAD, optAminusD, optAS, optAminusS, optAH, optAminusH, optAR, optAminusR, optAA, optAminusA, optOGN, optOGD, optOGE, optOGS, optOG, optON, optOD, optOE, optOS, reverseSort, rev2Sort)) {dos.dta(save_dta);inshell=false;return;} - dirs.erase(dirs.begin()); - } - inshell=false; - if (!optB) { - if (optS) { - WriteOut("\n"); - if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} - if (!file_count&&!dir_count) - WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); - else - WriteOut(MSG_Get("SHELL_CMD_DIR_FILES_LISTED")); - if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} - } - /* Show the summary of results */ - FormatNumber(byte_count,numformat); - WriteOut(MSG_Get("SHELL_CMD_DIR_BYTES_USED"),file_count,numformat); - if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} - uint8_t drive=dta.GetSearchDrive(); - uint64_t free_space=1024u*1024u*100u; - - if(Drives[drive]) { - uint32_t bytes_sector32; uint32_t sectors_cluster32; uint32_t total_clusters32; uint32_t free_clusters32; - uint64_t total_clusters64; uint64_t free_clusters64; - // Since this is the *internal* shell, we want use maximum available query capability at first - if(Drives[drive]->AllocationInfo64(&bytes_sector32, §ors_cluster32, &total_clusters64, &free_clusters64)) { - freec = 0; - free_space = (uint64_t)bytes_sector32 * (Bitu)sectors_cluster32 * (Bitu)free_clusters64; - } - else if((dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10)) && - Drives[drive]->AllocationInfo32(&bytes_sector32, §ors_cluster32, &total_clusters32, &free_clusters32)) { /* FAT32 aware extended API */ - freec = 0; - free_space = (uint64_t)bytes_sector32 * (Bitu)sectors_cluster32 * (Bitu)free_clusters32; - } - else { - uint16_t bytes_sector; uint8_t sectors_cluster; uint16_t total_clusters; uint16_t free_clusters; - rsize = true; - freec = 0; - Drives[drive]->AllocationInfo(&bytes_sector, §ors_cluster, &total_clusters, &free_clusters); - free_space = (uint64_t)bytes_sector * (Bitu)sectors_cluster * (Bitu)(freec ? freec : free_clusters); - rsize = false; - } - } -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(args)) { - std::string str = MSG_Get("SHELL_CMD_DIR_BYTES_FREE"); - std::string::size_type idx = str.rfind(" %"); - if (idx != std::string::npos) { - str = str.substr(0, idx)+"\n"; // No "nnn Bytes free" - WriteOut(str.c_str(),dir_count); - if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} - } - } else -#endif - { - FormatNumber(free_space,numformat); - WriteOut(MSG_Get("SHELL_CMD_DIR_BYTES_FREE"),dir_count,numformat); - if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} - } - } - dos.dta(save_dta); -} - -void DOS_Shell::CMD_LS(char *args) { - HELP("LS"); - bool optA=ScanCMDBool(args,"A"); - bool optL=ScanCMDBool(args,"L"); - bool optP=ScanCMDBool(args,"P"); - bool optZ=ScanCMDBool(args,"Z"); - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - return; - } - if (!outcon) optL = true; - - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - - std::string pattern = args; - trim(pattern); - - const char last_char = (pattern.length() > 0 ? pattern.back() : '\0'); - switch (last_char) { - case '\0': // No arguments, search for all. - pattern = "*.*"; - break; - case '\\': // Handle \, C:\, etc. - case ':': // Handle C:, etc. - pattern += "*.*"; - break; - default: break; - } - - // Handle patterns starting with a dot. - char buffer[CROSS_LEN]; - pattern = ExpandDot((char *)pattern.c_str(), buffer, sizeof(buffer), true); - - // When there's no wildcard and target is a directory then search files - // inside the directory. - const char *p = pattern.c_str(); - if (!strrchr(p, '*') && !strrchr(p, '?')) { - uint16_t attr = 0; - if (DOS_GetFileAttr(p, &attr) && (attr & DOS_ATTR_DIRECTORY)) - pattern += "\\*.*"; - } - - // If no extension, list all files. - // This makes patterns like foo* work. - if (!strrchr(pattern.c_str(), '.')) - pattern += ".*"; - - char spattern[CROSS_LEN]; - if (!DOS_GetSFNPath(pattern.c_str(),spattern,false)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - return; - } - int fbak=lfn_filefind_handle; - lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; - bool ret = DOS_FindFirst(((uselfn?"\"":"")+std::string(spattern)+(uselfn?"\"":"")).c_str(), 0xffff & ~DOS_ATTR_VOLUME); - if (!ret) { - lfn_filefind_handle=fbak; - if (strlen(trim(args))) - WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"), trim(args)); - else - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - dos.dta(save_dta); - return; - } - - std::vector results; - // reserve space for as many as we can fit into a single memory page - // nothing more to it; make it larger if necessary - results.reserve(MEM_PAGE_SIZE / sizeof(DtaResult)); - - do { - DtaResult result; - dta.GetResult(result.name, result.lname, result.size, result.hsize, result.date, result.time, result.attr); - results.push_back(result); - } while ((ret = DOS_FindNext()) == true); - lfn_filefind_handle=fbak; - - size_t w_count, p_count, col; - unsigned int max[15], total, tcols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - if (!tcols) tcols=80; - int mrow=tcols>80?15:10; - - for (col=mrow; col>0; col--) { - for (int i=0; imax[w_count%col]) max[w_count%col]=(unsigned int)(name.size()+2); - ++w_count; - } - total=0; - for (size_t i=0; i4) { - std::string ext=name.substr(name.length()-4); - std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - if (ext==".exe"||ext==".com"||ext==".bat") is_executable=true; - } - if (col==1) { - if (is_executable) WriteOut("\033[32;1m"); - p_count+=WriteOut_NoParsing(name.c_str(), true); - WriteOut(is_executable?"\033[0m\n":"\n"); - p_count++; - } else - WriteOut(is_executable?"\033[32;1m%-*s\033[0m":"%-*s", max[w_count % col], name.c_str()); - } - if (col>1) { - ++w_count; - if (w_count % col == 0) {p_count++;WriteOut_NoParsing("\n");} - } - if (optP&&p_count>=GetPauseCount()) { - WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==3) {dos.dta(save_dta);return;} - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key - p_count=0; - } - } - if (col>1&&w_count%col) WriteOut_NoParsing("\n"); - dos.dta(save_dta); -} - -struct copysource { - std::string filename; - bool concat; - copysource(std::string& filein,bool concatin): - filename(filein),concat(concatin){ }; - copysource():filename(""),concat(false){ }; -}; - -void DOS_Shell::CMD_COPY(char * args) { - HELP("COPY"); - static std::string defaulttarget = "."; - const char ch_y = MSG_Get("INT21_6523_YESNO_CHARS")[0]; - const char ch_n = MSG_Get("INT21_6523_YESNO_CHARS")[1]; - const char ch_Y = toupper(ch_y); - const char ch_N = toupper(ch_n); - const char ch_a = MSG_Get("SHELL_ALLFILES_CHAR")[0]; - const char ch_A = toupper(ch_a); - StripSpaces(args); - /* Command uses dta so set it to our internal dta */ - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; - char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH+1]; - std::vector sources; - // ignore /b and /t switches: always copy binary - while(ScanCMDBool(args,"B")) ; - while(ScanCMDBool(args,"T")) ; //Shouldn't this be A ? - while(ScanCMDBool(args,"A")) ; - bool optY=ScanCMDBool(args,"Y"); - if (bf||call||exec) optY=true; - std::string line; - if(GetEnvStr("COPYCMD",line)){ - std::string::size_type idx = line.find('='); - std::string value=line.substr(idx +1 , std::string::npos); - char copycmd[CROSS_LEN]; - strcpy(copycmd, value.c_str()); - if (ScanCMDBool(copycmd, "Y") && !ScanCMDBool(copycmd, "-Y")) optY = true; - } - if (ScanCMDBool(args,"-Y")) optY=false; - ScanCMDBool(args,"V"); - - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - dos.dta(save_dta); - return; - } - // Gather all sources (extension to copy more than 1 file specified at command line) - // Concatenating files go as follows: All parts except for the last bear the concat flag. - // This construction allows them to be counted (only the non concat set) - char q[]="\""; - char* source_p = NULL; - char source_x[DOS_PATHLENGTH+CROSS_LEN]; - while ( (source_p = StripArg(args)) && *source_p ) { - do { - char* plus = strchr(source_p,'+'); - // If StripWord() previously cut at a space before a plus then - // set concatenate flag on last source and remove leading plus. - if (plus == source_p && sources.size()) { - sources[sources.size()-1].concat = true; - // If spaces also followed plus then item is only a plus. - if (strlen(++source_p)==0) break; - plus = strchr(source_p,'+'); - } - if (plus) { - char *c=source_p+strlen(source_p)-1; - if (*source_p=='"'&&*c=='"') { - *c=0; - if (strchr(source_p+1,'"')) - *plus++ = 0; - else - plus=NULL; - *c='"'; - } else - *plus++ = 0; - } - safe_strncpy(source_x,source_p,CROSS_LEN); - bool has_drive_spec = false; - size_t source_x_len = strlen(source_x); - if (source_x_len>0) { - if (source_x[source_x_len-1]==':') has_drive_spec = true; - else if (uselfn&&strchr(source_x, '*')) { - char * find_last; - find_last=strrchr_dbcs(source_x,'\\'); - if (find_last==NULL) find_last=source_x; - else find_last++; - if (strlen(find_last)>0&&source_x[source_x_len-1]=='*'&&strchr(find_last, '.')==NULL) strcat(source_x, ".*"); - } - } - if (!has_drive_spec && !strpbrk(source_p,"*?") ) { //doubt that fu*\*.* is valid - char spath[DOS_PATHLENGTH]; - if (DOS_GetSFNPath(source_p,spath,false)) { - bool root=false; - if (strlen(spath)==3&&spath[1]==':'&&spath[2]=='\\') { - root=true; - strcat(spath, "*.*"); - } - if (DOS_FindFirst(spath,0xffff & ~DOS_ATTR_VOLUME)) { - dta.GetResult(name,lname,size,hsize,date,time,attr); - if (attr & DOS_ATTR_DIRECTORY || root) - strcat(source_x,"\\*.*"); - } - } - } - std::string source_xString = std::string(source_x); - sources.push_back(copysource(source_xString,(plus)?true:false)); - source_p = plus; - } while(source_p && *source_p); - } - // At least one source has to be there - if (!sources.size() || !sources[0].filename.size()) { - WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); - dos.dta(save_dta); - return; - } - - copysource target; - // If more than one object exists and last target is not part of a - // concat sequence then make it the target. - if(sources.size()>1 && !sources[sources.size()-2].concat){ - target = sources.back(); - sources.pop_back(); - } - //If no target => default target with concat flag true to detect a+b+c - if(target.filename.size() == 0) target = copysource(defaulttarget,true); - - copysource oldsource; - copysource source; - uint32_t count = 0; - while(sources.size()) { - /* Get next source item and keep track of old source for concat start end */ - oldsource = source; - source = sources[0]; - sources.erase(sources.begin()); - - //Skip first file if doing a+b+c. Set target to first file - if(!oldsource.concat && source.concat && target.concat) { - target = source; - continue; - } - - /* Make a full path in the args */ - char pathSourcePre[DOS_PATHLENGTH], pathSource[DOS_PATHLENGTH+2]; - char pathTarget[DOS_PATHLENGTH]; - - if (!DOS_Canonicalize(const_cast(source.filename.c_str()),pathSourcePre)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - dos.dta(save_dta); - return; - } - strcpy(pathSource,pathSourcePre); - if (uselfn) sprintf(pathSource,"\"%s\"",pathSourcePre); - // cut search pattern - char* pos = strrchr_dbcs(pathSource,'\\'); - if (pos) *(pos+1) = 0; - - if (!DOS_Canonicalize(const_cast(target.filename.c_str()),pathTarget)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - dos.dta(save_dta); - return; - } - char* temp = strstr(pathTarget,"*.*"); - if(temp && (temp == pathTarget || temp[-1] == '\\')) *temp = 0;//strip off *.* from target - - // add '\\' if target is a directory - bool target_is_file = true; - if (pathTarget[strlen(pathTarget)-1]!='\\') { - if (DOS_FindFirst(pathTarget,0xffff & ~DOS_ATTR_VOLUME)) { - dta.GetResult(name,lname,size,hsize,date,time,attr); - if (attr & DOS_ATTR_DIRECTORY) { - strcat(pathTarget,"\\"); - target_is_file = false; - } - } - } else target_is_file = false; - - //Find first sourcefile - char sPath[DOS_PATHLENGTH]; - bool ret=DOS_GetSFNPath(source.filename.c_str(),sPath,false) && DOS_FindFirst(((strchr(sPath, ' ')&&sPath[0]!='"'?"\"":"")+std::string(sPath)+(strchr(sPath, ' ')&&sPath[strlen(sPath)-1]!='"'?"\"":"")).c_str(),0xffff & ~DOS_ATTR_VOLUME); - if (!ret) { - WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),source.filename.c_str()); - dos.dta(save_dta); - return; - } - - uint16_t sourceHandle,targetHandle = 0; - char nameTarget[DOS_PATHLENGTH]; - char nameSource[DOS_PATHLENGTH], nametmp[DOS_PATHLENGTH+2]; - - // Cache so we don't have to recalculate - size_t pathTargetLen = strlen(pathTarget); - - // See if we have to substitute filename or extension - char * ext = nullptr; - size_t replacementOffset = 0; - if (pathTarget[pathTargetLen-1]!='\\') { - // only if it's not a directory - ext = strchr(pathTarget, '.'); - if (ext > pathTarget) { // no possible substitution - if (ext[-1] == '*') { - // we substitute extension, save it, hide the name - ext[-1] = 0; - assert(ext > pathTarget + 1); // pathTarget is fully qualified - if (ext[-2] != '\\') { - // there is something before the asterisk - // save the offset in the source names - - replacementOffset = source.filename.find('*'); - size_t lastSlash = std::string::npos; - bool lead = false; - for (unsigned int i=0; i1&&(nameTarget[1]==':'||nameTarget[2]==':')?(toupper(nameTarget[nameTarget[0]=='"'?1:0])-'A'):-1; - if(drive >= 0 && Drives[drive]) { - uint16_t bytes_sector; uint8_t sectors_cluster; uint16_t total_clusters; uint16_t free_clusters; - uint32_t bytes32 = 0, sectors32 = 0, clusters32 = 0, free32 = 0; - bool no_free_space = true; - rsize = true; - freec = 0; - if(dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10)) { - Drives[drive]->AllocationInfo32(&bytes32, §ors32, &clusters32, &free32); - no_free_space = (uint64_t)bytes32 * (uint64_t)sectors32 * (uint64_t)free32 < size ? true : false; - //LOG_MSG("drive=%u, no_free_space = %d bytes32=%u, sectors32=%u, free32 =%u, free_space=%u, size=%u", - // drive, no_free_space ? 1 : 0, bytes32, sectors32, free32, bytes32*sectors32*free32, size); - } - if(bytes32 == 0 || sectors32 == 0 || dos.version.major < 7 || (dos.version.major == 7 && dos.version.minor < 10)) { - Drives[drive]->AllocationInfo(&bytes_sector, §ors_cluster, &total_clusters, &free_clusters); - no_free_space = (Bitu)bytes_sector* (Bitu)sectors_cluster* (Bitu)(freec ? freec : free_clusters) < size ? true : false; - //LOG_MSG("no_free_space = %d bytes=%u, sectors=%u, free =%u, free_space=%u, size=%u", - // no_free_space ? 1 : 0, bytes_sector, sectors_cluster, freec, bytes_sector*sectors_cluster*free_clusters, size); - } - rsize = false; - if (no_free_space) { - WriteOut(MSG_Get("SHELL_CMD_COPY_NOSPACE"), uselfn?lname:name); - DOS_CloseFile(sourceHandle); - ret = DOS_FindNext(); - continue; - } - } - } - } - //Don't create a new file when in concat mode - if (oldsource.concat || DOS_CreateFile(nameTarget,0,&targetHandle)) { - uint32_t dummy=0; - - if (DOS_FindDevice(name) == DOS_DEVICES && !DOS_SetFileDate(targetHandle, ftime, fdate)) - LOG_MSG("WARNING: COPY unable to apply date/time to dest"); - - //In concat mode. Open the target and seek to the eof - if (!oldsource.concat || (DOS_OpenFile(nameTarget,OPEN_READWRITE,&targetHandle) && - DOS_SeekFile(targetHandle,&dummy,DOS_SEEK_END))) { - // Copy - static uint8_t buffer[0x8000]; // static, otherwise stack overflow possible. - bool failed = false; - uint16_t toread = 0x8000; - bool iscon=DOS_FindDevice(name)==DOS_FindDevice("con"); - if (iscon) dos.echo=true; - bool cont; - do { - if (!DOS_ReadFile(sourceHandle,buffer,&toread)) failed=true; - if (iscon) { - if (dos.errorcode==77) { - dos.dta(save_dta); - DOS_CloseFile(sourceHandle); - DOS_CloseFile(targetHandle); - if (!exist) DOS_UnlinkFile(nameTarget); - dos.echo=echo; - return; - } - cont=true; - for (int i=0;i0 && DOS_FindDevice(name) == DOS_DEVICES) DOS_SetFileDate(targetHandle, ftime, fdate); -#endif - if (!DOS_CloseFile(targetHandle)) failed=true; - if (failed) - WriteOut(MSG_Get("SHELL_CMD_COPY_ERROR"),uselfn?lname:name); - else if (strcmp(name,lname)&&uselfn) - WriteOut(" %s [%s]\n",lname,name); - else - WriteOut(" %s\n",uselfn?lname:name); - if(!source.concat && !special && !failed) count++; //Only count concat files once - } else { - DOS_CloseFile(sourceHandle); - WriteOut(MSG_Get("SHELL_CMD_COPY_FAILURE"),const_cast(target.filename.c_str())); - } - } else { - DOS_CloseFile(sourceHandle); - WriteOut(MSG_Get("SHELL_CMD_COPY_FAILURE"),const_cast(target.filename.c_str())); - } - } else WriteOut(MSG_Get("SHELL_CMD_COPY_FAILURE"),const_cast(source.filename.c_str())); - } - //On to the next file if the previous one wasn't a device - if ((attr&DOS_ATTR_DEVICE) == 0) ret = DOS_FindNext(); - else ret = false; - } - } - - WriteOut(MSG_Get("SHELL_CMD_COPY_SUCCESS"),count); - dos.dta(save_dta); - dos.echo=echo; - Drives[DOS_GetDefaultDrive()]->EmptyCache(); -} - -static void skipspc(char* &pcheck) { - while (*pcheck != 0 && (*pcheck == ' ' || *pcheck == '\t')) pcheck++; -} - -static void readnonspcu(std::string &s,char* &pcheck) { - s.clear(); - while (*pcheck != 0 && !(*pcheck == ' ' || *pcheck == '\t')) s += toupper( *(pcheck++) ); -} - -static void readnonspc(std::string &s,char* &pcheck) { - s.clear(); - while (*pcheck != 0 && !(*pcheck == ' ' || *pcheck == '\t')) s += *(pcheck++); -} - -/* NTS: WARNING, this function modifies the buffer pointed to by char *args */ -void DOS_Shell::CMD_SET(char * args) { - HELP("SET"); - StripSpaces(args); - - enum op_mode_t { - show_all_env, - set_env, - show_env, - erase_env, - first_env - }; - - op_mode_t op_mode = show_all_env; - std::string env_name,env_value; - - const bool zdirpath = static_cast(control->GetSection("dos"))->Get_bool("drive z expand path"); - - { - std::string sw; - - /* parse arguments at the start */ - skipspc(args); - while (*args == '/') { - args++; /* skip / */ - readnonspcu(sw,args); - - if (sw == "P") { - WriteOut("Set /P is not supported. Use Choice!"); /* TODO: What is SET /P supposed to do? */ - return; - } - else if (sw == "ERASE") { /* DOSBox-X extension: Completely erase the environment block */ - op_mode = erase_env; - } - else if (sw == "FIRST") { /* DOSBox-X extension: Move the specified variable to the front of the environment block */ - op_mode = first_env; - } - else { - WriteOut("Unknown switch /"); - WriteOut(sw.c_str()); - WriteOut("\n"); - return; - } - - skipspc(args); - } - } - - if (op_mode == first_env) { - if (*args == 0) return; - readnonspc(env_name,args); - } - else if (op_mode == show_all_env) { - if (*args != 0) { - /* Most SET commands take the form NAME=VALUE */ - char *p = strchr(args,'='); - if (p == NULL) { - /* SET without assignment prints the variable instead */ - op_mode = show_env; - readnonspc(env_name,args); - } else { - /* ASCIIZ snip the args string in two, so that args is C-string name of the variable, - * and "p" is C-string value of the variable */ - op_mode = set_env; - *p++ = 0; env_name = args; env_value = p; - } - } - } - - switch (op_mode) { - case show_all_env: { - const Bitu count = GetEnvCount(); - std::string line; - - for (Bitu a = 0;a < count;a++) { - if (GetEnvNum(a,line)) - WriteOut("%s\n",line.c_str()); - } - break; } - case show_env: - if (GetEnvStr(env_name.c_str(),env_value)) - WriteOut("%s\n",env_value.c_str()); - else - WriteOut(MSG_Get("SHELL_CMD_SET_NOT_SET"),env_name.c_str()); - break; - case set_env: - if(zdirpath && !strcasecmp(env_name.c_str(), "path")) GetExpandedPath(env_value); - - /* No parsing is needed. The command interpreter does the variable substitution for us */ - /* NTS: If Win95 is any example, the command interpreter expands the variables for us */ - if (!SetEnv(env_name.c_str(),env_value.c_str())) - WriteOut(MSG_Get("SHELL_CMD_SET_OUT_OF_SPACE")); - - break; - case erase_env: - if (!EraseEnv()) - WriteOut("Unable to erase environment block\n"); - break; - case first_env: - if (!FirstEnv(env_name.c_str())) - WriteOut("Unable to move environment variable\n"); - break; - default: - abort(); - break; - } -} - -void DOS_Shell::CMD_IF(char * args) { - HELP("IF"); - StripSpaces(args,'='); - bool has_not=false; - - while (strncasecmp(args,"NOT",3) == 0) { - if (!isspace(*reinterpret_cast(&args[3])) && (args[3] != '=')) break; - args += 3; //skip text - //skip more spaces - StripSpaces(args,'='); - has_not = !has_not; - } - - if(strncasecmp(args,"ERRORLEVEL",10) == 0) { - args += 10; //skip text - //Strip spaces and == - StripSpaces(args,'='); - char* word = StripWord(args); - if(!isdigit(*word)) { - WriteOut(MSG_Get("SHELL_CMD_IF_ERRORLEVEL_MISSING_NUMBER")); - return; - } - - uint8_t n = 0; - do n = n * 10 + (*word - '0'); - while (isdigit(*++word)); - if(*word && !isspace(*word)) { - WriteOut(MSG_Get("SHELL_CMD_IF_ERRORLEVEL_INVALID_NUMBER")); - return; - } - /* Read the error code from DOS */ - if ((dos.return_code>=n) ==(!has_not)) DoCommand(args); - return; - } - - if(strncasecmp(args,"EXIST ",6) == 0) { - args += 6; //Skip text - StripSpaces(args); - char* word = StripArg(args); - if (!*word) { - WriteOut(MSG_Get("SHELL_CMD_IF_EXIST_MISSING_FILENAME")); - return; - } - - { /* DOS_FindFirst uses dta so set it to our internal dta */ - char spath[DOS_PATHLENGTH], path[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH], full[DOS_PATHLENGTH], *r; - if (!DOS_Canonicalize(word,full)) { - if (has_not) DoCommand(args); - return; - } - r=strrchr_dbcs(full, '\\'); - if (r!=NULL) { - *r=0; - strcpy(path, full); - strcat(path, "\\"); - strcpy(pattern, r+1); - *r='\\'; - } else { - strcpy(path, ""); - strcpy(pattern, full); - } - int k=0; - for (int i=0;i<(int)strlen(pattern);i++) - if (pattern[i]!='\"') - pattern[k++]=pattern[i]; - pattern[k]=0; - strcpy(spath, path); - if (strchr_dbcs(word,'\"')||uselfn) { - if (!DOS_GetSFNPath(("\""+std::string(path)+"\\").c_str(), spath, false)) strcpy(spath, path); - if (!strlen(spath)||spath[strlen(spath)-1]!='\\') strcat(spath, "\\"); - } - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - int fbak=lfn_filefind_handle; - lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; - std::string sfull=std::string(spath)+std::string(pattern); - bool ret=DOS_FindFirst(((uselfn&&sfull.length()&&sfull[0]!='"'?"\"":"")+sfull+(uselfn&&sfull.length()&&sfull[sfull.length()-1]!='"'?"\"":"")).c_str(),0xffff & ~(DOS_ATTR_VOLUME|DOS_ATTR_DIRECTORY)); - lfn_filefind_handle=fbak; - dos.dta(save_dta); - if (ret==(!has_not)) DoCommand(args); - } - return; - } - - /* Normal if string compare */ - - char* word1 = args; - // first word is until space or = - while (*args && !isspace(*reinterpret_cast(args)) && (*args != '=')) - args++; - char* end_word1 = args; - - // scan for = - while (*args && (*args != '=')) - args++; - // check for == - if ((*args==0) || (args[1] != '=')) { - SyntaxError(); - return; - } - args += 2; - StripSpaces(args,'='); - - char* word2 = args; - // second word is until space or = - while (*args && !isspace(*reinterpret_cast(args)) && (*args != '=')) - args++; - - if (*args) { - *end_word1 = 0; // mark end of first word - *args++ = 0; // mark end of second word - StripSpaces(args,'='); - - if ((strcmp(word1,word2)==0)==(!has_not)) DoCommand(args); - } -} - -void DOS_Shell::CMD_GOTO(char * args) { - HELP("GOTO"); - StripSpaces(args); - if (!bf) return; - if (*args==':') args++; - //label ends at the first space - char* non_space = args; - while (*non_space) { - if((*non_space == ' ') || (*non_space == '\t')) - *non_space = 0; - else non_space++; - } - if (!*args) { - WriteOut(MSG_Get("SHELL_CMD_GOTO_MISSING_LABEL")); - return; - } - if (!bf->Goto(args)) { - WriteOut(MSG_Get("SHELL_CMD_GOTO_LABEL_NOT_FOUND"),args); - return; - } -} - -void DOS_Shell::CMD_SHIFT(char * args ) { - HELP("SHIFT"); - if(bf) bf->Shift(); -} - -void DOS_Shell::CMD_TYPE(char * args) { - HELP("TYPE"); - - // ignore /p /h and /t for compatibility - ScanCMDBool(args,"P"); - ScanCMDBool(args,"H"); - ScanCMDBool(args,"T"); - StripSpaces(args); - if (strcasecmp(args,"nul")==0) return; - if (!*args) { - WriteOut(MSG_Get("SHELL_SYNTAXERROR")); - return; - } - uint16_t handle; - char * word; - bool lead = false; - int COLS = 80; - if (!IS_PC98_ARCH && outcon) COLS=real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - BIOS_NCOLS; - uint8_t page=outcon?real_readb(BIOSMEM_SEG,BIOSMEM_CURRENT_PAGE):0; -nextfile: - word=StripArg(args); - if (!DOS_OpenFile(word,0,&handle)) { - WriteOut(MSG_Get(dos.errorcode==DOSERR_ACCESS_DENIED?"SHELL_CMD_FILE_ACCESS_DENIED":(dos.errorcode==DOSERR_PATH_NOT_FOUND?"SHELL_ILLEGAL_PATH":"SHELL_CMD_FILE_NOT_FOUND")),word); - return; - } - ctrlbrk=false; - uint8_t c,last,last2,last3;uint16_t n=1; - last3=last2=last=0; - bool iscon=DOS_FindDevice(word)==DOS_FindDevice("con"); - while (n) { - DOS_ReadFile(handle,&c,&n); - if (outcon && !CURSOR_POS_COL(page)) last3=last2=last=0; - if (lead) lead=false; - else if ((IS_PC98_ARCH || isDBCSCP()) -#if defined(USE_TTF) - && dbcs_sbcs -#endif - ) lead = isKanji1(c) && !(TTF_using() -#if defined(USE_TTF) - && autoboxdraw -#endif - && CheckBoxDrawing(last3, last2, last, c)); - if (n==0 || c==0x1a) break; // stop at EOF - if (iscon) { - if (c==3) break; - else if (c==13) WriteOut("\r\n"); - } else if (CheckBreak(this)) break; - else if (outcon && lead && CURSOR_POS_COL(page) == COLS-1) WriteOut(" "); - DOS_WriteFile(STDOUT,&c,&n); - if (outcon) {last3=last2;last2=last;last=c;} - } - DOS_CloseFile(handle); - if (*args) goto nextfile; -} - -void DOS_Shell::CMD_REM(char * args) { - HELP("REM"); -} - -static char PAUSED(void) { - uint8_t c; uint16_t n=1, handle; - if (!usecon&&DOS_OpenFile("con", OPEN_READWRITE, &handle)) { - DOS_ReadFile (handle,&c,&n); - DOS_CloseFile(handle); - } else - DOS_ReadFile (STDIN,&c,&n); - return c; -} - -void DOS_Shell::CMD_MORE(char * args) { - HELP("MORE"); - //ScanCMDBool(args,">"); - int nchars = 0, nlines = 0, linecount = 0, LINES = 25, COLS = 80, TABSIZE = 8; - char * word; - uint8_t c,last,last2,last3; - last3=last2=last=0; - bool lead=false; - uint16_t n=1; - StripSpaces(args); - if (IS_PC98_ARCH) { - LINES=real_readb(0x60,0x113) & 0x01 ? 25 : 20; - COLS=80; - if (real_readb(0x60,0x111)) LINES--; // Function keys displayed - } else { - LINES=(IS_EGAVGA_ARCH?real_readb(BIOSMEM_SEG,BIOSMEM_NB_ROWS):24)+1; - COLS=real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - } - LINES--; - if(!*args||!strcasecmp(args, "con")) { - while (true) { - DOS_ReadFile (STDIN,&c,&n); - if (lead) lead=false; - else if ((IS_PC98_ARCH || isDBCSCP()) -#if defined(USE_TTF) - && dbcs_sbcs -#endif - ) lead = isKanji1(c) && !(TTF_using() -#if defined(USE_TTF) - && autoboxdraw -#endif - && CheckBoxDrawing(last3, last2, last, c)); - if (c==3) {dos.echo=echo;return;} - else if (n==0) {if (last!=10) WriteOut("\r\n");dos.echo=echo;return;} - else if (c==13&&last==26) {dos.echo=echo;return;} - else { - if (c==10); - else if (c==13) { - linecount++; - WriteOut("\r\n"); - last3=last2=last=0; - } else if (c=='\t') { - do { - WriteOut(" "); - nchars++; - } while ( nchars < COLS && nchars % TABSIZE ); - } else { - if (lead && nchars == COLS-1) { - last3=last2=last=0; - nlines++; - nchars = 0; - WriteOut("\n"); - if (nlines == LINES) { - WriteOut("-- More -- (%u) --",linecount); - if (PAUSED()==3) return; - WriteOut("\n"); - nlines=0; - } - } - nchars++; - WriteOut("%c", c); - } - if (c == 13 || nchars >= COLS) { - nlines++; - nchars = 0; - if (nlines == LINES) { - WriteOut("-- More -- (%u) --",linecount); - if (PAUSED()==3) return; - WriteOut("\n"); - nlines=0; - } - } - last3=last2;last2=last;last=c; - } - } - } - if (strcasecmp(args,"nul")==0) return; - if (!*args) { - WriteOut(MSG_Get("SHELL_SYNTAXERROR")); - return; - } - uint16_t handle; -nextfile: - word=StripArg(args); - if (!DOS_OpenFile(word,0,&handle)) { - WriteOut(MSG_Get(dos.errorcode==DOSERR_ACCESS_DENIED?"SHELL_CMD_FILE_ACCESS_DENIED":(dos.errorcode==DOSERR_PATH_NOT_FOUND?"SHELL_ILLEGAL_PATH":"SHELL_CMD_FILE_NOT_FOUND")),word); - return; - } - ctrlbrk=false; - lead=false; - last3=last2=last=0; - nlines=0; - do { - n=1; - DOS_ReadFile(handle,&c,&n); - if (lead) lead=false; - else if ((IS_PC98_ARCH || isDBCSCP()) -#if defined(USE_TTF) - && dbcs_sbcs -#endif - ) lead = isKanji1(c) && !(TTF_using() -#if defined(USE_TTF) - && autoboxdraw -#endif - && CheckBoxDrawing(last3, last2, last, c)); - if (lead && nchars == COLS-1) { - last3=last2=last=0; - nlines++; - nchars = 0; - WriteOut("\n"); - if (nlines == LINES && usecon) { - WriteOut("-- More -- %s (%u) --",word,linecount); - if (PAUSED()==3) {DOS_CloseFile(handle);return;} - WriteOut("\n"); - nlines=0; - } - } - DOS_WriteFile(STDOUT,&c,&n); - last3=last2;last2=last;last=c; - if (c != '\t') nchars++; - else do { - WriteOut(" "); - nchars++; - } while ( nchars < COLS && nchars % TABSIZE ); - - if (c == '\n') linecount++; - if (c == '\n' || nchars >= COLS) { - last3=last2=last=0; - nlines++; - nchars = 0; - if (!usecon) { - if (c != '\n') WriteOut("\n"); - } else if (nlines == LINES) { - WriteOut("-- More -- %s (%u) --",word,linecount); - if (PAUSED()==3) {DOS_CloseFile(handle);return;} - WriteOut("\n"); - nlines=0; - } - } - if (CheckBreak(this)) break; - } while (n); - DOS_CloseFile(handle); - if (*args) { - WriteOut("\n"); - if (usecon && PAUSED()==3) return; - goto nextfile; - } -} - -void DOS_Shell::CMD_PAUSE(char * args){ - HELP("PAUSE"); - if(args && *args) { - args++; - WriteOut("%s\n",args); // optional specified message - } else - WriteOut(MSG_Get("SHELL_CMD_PAUSE")); - uint8_t c;uint16_t n=1; - DOS_ReadFile(STDIN,&c,&n); - if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key -} - -void DOS_Shell::CMD_CALL(char * args){ - HELP("CALL"); - this->call=true; /* else the old batchfile will be closed first */ - this->ParseLine(args); - this->call=false; -} - -void DOS_Shell::CMD_DATE(char * args) { - HELP("DATE"); - if(ScanCMDBool(args,"H")) { - // synchronize date with host parameter - time_t curtime; - struct tm *loctime; - curtime = time (NULL); - loctime = localtime (&curtime); - - reg_cx = loctime->tm_year+1900; - reg_dh = loctime->tm_mon+1; - reg_dl = loctime->tm_mday; - - reg_ah=0x2b; // set system date - CALLBACK_RunRealInt(0x21); - if (sync_time) {manualtime=false;mainMenu.get_item("sync_host_datetime").check(true).refresh_item(mainMenu);} - return; - } else if(ScanCMDBool(args,"S")) { - sync_time=true; - manualtime=false; - mainMenu.get_item("sync_host_datetime").check(true).refresh_item(mainMenu); - return; - } else if(ScanCMDBool(args,"F")) { - sync_time=false; - manualtime=false; - mainMenu.get_item("sync_host_datetime").check(false).refresh_item(mainMenu); - return; - } - // check if a date was passed in command line - char c=dos.tables.country[11], c1, c2; - uint32_t newday,newmonth,newyear; - int n=dos.tables.country[0]==1?sscanf(args,"%u%c%u%c%u",&newday,&c1,&newmonth,&c2,&newyear):(dos.tables.country[0]==2?sscanf(args,"%u%c%u%c%u",&newyear,&c1,&newmonth,&c2,&newday):sscanf(args,"%u%c%u%c%u",&newmonth,&c1,&newday,&c2,&newyear)); - if (n==5 && c1==c && c2==c) { - reg_cx = static_cast(newyear); - reg_dh = static_cast(newmonth); - reg_dl = static_cast(newday); - - reg_ah=0x2b; // set system date - CALLBACK_RunRealInt(0x21); - if(reg_al==0xff) WriteOut(MSG_Get("SHELL_CMD_DATE_ERROR")); - return; - } - // display the current date - reg_ah=0x2a; // get system date - CALLBACK_RunRealInt(0x21); - - const char* datestring = MSG_Get("SHELL_CMD_DATE_DAYS"); - uint32_t length; - char day[6] = {0}; - if(sscanf(datestring,"%u",&length) && (length<7) && (strlen(datestring)==((size_t)length*7+1))) { - // date string appears valid - for(uint32_t i = 0; i < length; i++) day[i] = datestring[reg_al*length+1+i]; - } - bool dateonly = ScanCMDBool(args,"T"); - if(!dateonly) WriteOut(MSG_Get("SHELL_CMD_DATE_NOW")); - if (!dateonly) WriteOut("%s ", day); - WriteOut("%s\n",FormatDate((uint16_t)reg_cx, (uint8_t)reg_dh, (uint8_t)reg_dl)); - if(!dateonly) { - char format[11]; - sprintf(format, dos.tables.country[0]==1?"DD%cMM%cYYYY":(dos.tables.country[0]==2?"YYYY%cMM%cDD":"MM%cDD%cYYYY"), c, c); - WriteOut(MSG_Get("SHELL_CMD_DATE_SETHLP"), format); - } -} - -void DOS_Shell::CMD_TIME(char * args) { - HELP("TIME"); - if(ScanCMDBool(args,"H")) { - // synchronize time with host parameter - time_t curtime; - struct tm *loctime; - curtime = time (NULL); - loctime = localtime (&curtime); - - //reg_cx = loctime->; - //reg_dh = loctime->; - //reg_dl = loctime->; - - // reg_ah=0x2d; // set system time TODO - // CALLBACK_RunRealInt(0x21); - - uint32_t ticks=(uint32_t)(((double)(loctime->tm_hour*3600+ - loctime->tm_min*60+ - loctime->tm_sec))*18.206481481); - mem_writed(BIOS_TIMER,ticks); - if (sync_time) {manualtime=false;mainMenu.get_item("sync_host_datetime").check(true).refresh_item(mainMenu);} - return; - } - uint32_t newhour,newminute,newsecond; - char c=dos.tables.country[13], c1, c2; - if (sscanf(args,"%u%c%u%c%u",&newhour,&c1,&newminute,&c2,&newsecond)==5 && c1==c && c2==c) { - reg_ch = static_cast(newhour); - reg_cl = static_cast(newminute); - reg_dx = static_cast(newsecond)<<8; - - reg_ah=0x2d; // set system time - CALLBACK_RunRealInt(0x21); - if(reg_al==0xff) WriteOut(MSG_Get("SHELL_CMD_TIME_ERROR")); - return; - } - bool timeonly = ScanCMDBool(args,"T"); - - reg_ah=0x2c; // get system time - CALLBACK_RunRealInt(0x21); -/* - reg_dl= // 1/100 seconds - reg_dh= // seconds - reg_cl= // minutes - reg_ch= // hours -*/ - if(timeonly) { - WriteOut("%u%c%02u%c%02u\n",reg_ch,dos.tables.country[13],reg_cl,dos.tables.country[13],reg_dh); - } else { - WriteOut(MSG_Get("SHELL_CMD_TIME_NOW")); - WriteOut("%s\n", FormatTime(reg_ch,reg_cl,reg_dh,reg_dl)); - char format[9]; - sprintf(format, "hh%cmm%css", dos.tables.country[13], dos.tables.country[13]); - WriteOut(MSG_Get("SHELL_CMD_TIME_SETHLP"), format); - } -} - -void DOS_Shell::CMD_SUBST(char * args) { -/* If more that one type can be substed think of something else - * E.g. make basedir member dos_drive instead of localdrive + uint16_t oldax=reg_ax; + if (IS_DOSV && DOSV_CheckCJKVideoMode()) reg_ax = GetTrueVideoMode(); + else reg_ax=(uint16_t)CurMode->mode; + CALLBACK_RunRealInt(0x10); + reg_ax=oldax; + } + } + + void DOS_Shell::CMD_DELETE(char* args) { + HELP("DELETE"); + bool optP = ScanCMDBool(args, "P"); + bool optF = ScanCMDBool(args, "F"); + bool optQ = ScanCMDBool(args, "Q"); + + const char ch_y = MSG_Get("INT21_6523_YESNO_CHARS")[0]; + const char ch_n = MSG_Get("INT21_6523_YESNO_CHARS")[1]; + const char ch_Y = toupper(ch_y); + const char ch_N = toupper(ch_n); + + // ignore /f, /s, /ar, /as, /ah and /aa switches for compatibility + ScanCMDBool(args, "S"); + ScanCMDBool(args, "AR"); + ScanCMDBool(args, "AS"); + ScanCMDBool(args, "AH"); + ScanCMDBool(args, "AA"); + + char* rem = ScanCMDRemain(args); + if(rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), rem); + return; + } + if(!*args) { + WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); + return; + } + + StripSpaces(args); + args = trim(args); + + /* Command uses dta so set it to our internal dta */ + //DOS_DTA dta(dos.dta()); + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + /* If delete accept switches mind the space in front of them. See the dir /p code */ + + char full[DOS_PATHLENGTH], sfull[DOS_PATHLENGTH + 2]; + char buffer[CROSS_LEN]; + char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH + 1]; + uint32_t size, hsize; uint16_t time, date; uint8_t attr; + args = ExpandDot(args, buffer, CROSS_LEN, false); + StripSpaces(args); + if(!DOS_Canonicalize(args, full)) { WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); dos.dta(save_dta); return; } + if(strlen(args) && args[strlen(args) - 1] != '\\') { + uint16_t fattr; + if(strcmp(args, "*.*") && DOS_GetFileAttr(args, &fattr) && (fattr & DOS_ATTR_DIRECTORY)) + strcat(args, "\\"); + } + if(strlen(args) && args[strlen(args) - 1] == '\\') strcat(args, "*.*"); + else if(!strcmp(args, ".") || (strlen(args) > 1 && (args[strlen(args) - 2] == ':' || args[strlen(args) - 2] == '\\') && args[strlen(args) - 1] == '.')) { + args[strlen(args) - 1] = '*'; + strcat(args, ".*"); + } + else if(uselfn && strchr(args, '*')) { + char* find_last; + find_last = strrchr_dbcs(args, '\\'); + if(find_last == NULL) find_last = args; + else find_last++; + if(strlen(find_last) > 0 && args[strlen(args) - 1] == '*' && strchr(find_last, '.') == NULL) strcat(args, ".*"); + } + if(!strcmp(args, "*.*") || (strlen(args) > 3 && (!strcmp(args + strlen(args) - 4, "\\*.*") || !strcmp(args + strlen(args) - 4, ":*.*")))) { + if(!optQ) { + first_1: + WriteOut(MSG_Get("SHELL_CMD_DEL_SURE")); + first_2: + uint8_t c; uint16_t n = 1; + DOS_ReadFile(STDIN, &c, &n); + do { + if(c == ch_n || c == ch_N) { + DOS_WriteFile(STDOUT, &c, &n); + DOS_ReadFile(STDIN, &c, &n); + do switch(c) { + case 0xD: WriteOut("\n"); dos.dta(save_dta); return; + case 0x03: dos.dta(save_dta); return; + case 0x08: WriteOut("\b \b"); goto first_2; + } while(DOS_ReadFile(STDIN, &c, &n)); + } + + if(c == ch_y || c == ch_Y) { + DOS_WriteFile(STDOUT, &c, &n); + DOS_ReadFile(STDIN, &c, &n); + do switch(c) { + case 0xD: WriteOut("\n"); goto continue_1; + case 0x03: dos.dta(save_dta); return; + case 0x08: WriteOut("\b \b"); goto first_2; + } while(DOS_ReadFile(STDIN, &c, &n)); + } + + if(c == 0xD) { WriteOut("\n"); goto first_1; } + if(c == 0x03) { dos.dta(save_dta); return; } + if(c == '\t' || c == 0x08) goto first_2; + + DOS_WriteFile(STDOUT, &c, &n); + DOS_ReadFile(STDIN, &c, &n); + do switch(c) { + case 0xD: WriteOut("\n"); goto first_1; + case 0x03: dos.dta(save_dta); return; + case 0x08: WriteOut("\b \b"); goto first_2; + } while(DOS_ReadFile(STDIN, &c, &n)); + goto first_2; + } while(DOS_ReadFile(STDIN, &c, &n)); + } + } + + continue_1: + /* Command uses dta so set it to our internal dta */ + if(!DOS_Canonicalize(args, full)) { WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); dos.dta(save_dta); return; } + char path[DOS_PATHLENGTH], spath[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH], * r = strrchr_dbcs(full, '\\'); + if(r != NULL) { + *r = 0; + strcpy(path, full); + strcat(path, "\\"); + strcpy(pattern, r + 1); + *r = '\\'; + } + else { + strcpy(path, ""); + strcpy(pattern, full); + } + int k = 0; + for(int i = 0; i < (int)strlen(pattern); i++) + if(pattern[i] != '\"') + pattern[k++] = pattern[i]; + pattern[k] = 0; + strcpy(spath, path); + if(strchr(args, '\"') || uselfn) { + if(!DOS_GetSFNPath(("\"" + std::string(path) + "\\").c_str(), spath, false)) strcpy(spath, path); + if(!strlen(spath) || spath[strlen(spath) - 1] != '\\') strcat(spath, "\\"); + } + std::string pfull = std::string(spath) + std::string(pattern); + int fbak = lfn_filefind_handle; + lfn_filefind_handle = uselfn ? LFN_FILEFIND_INTERNAL : LFN_FILEFIND_NONE; + bool res = DOS_FindFirst(((uselfn && pfull.length() && pfull[0] != '"' ? "\"" : "") + pfull + (uselfn && pfull.length() && pfull[pfull.length() - 1] != '"' ? "\"" : "")).c_str(), 0xffff & ~DOS_ATTR_VOLUME); + if(!res) { + lfn_filefind_handle = fbak; + WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"), args); + dos.dta(save_dta); + return; + } + lfn_filefind_handle = fbak; + //end can't be 0, but if it is we'll get a nice crash, who cares :) + strcpy(sfull, full); + char* end = strrchr_dbcs(full, '\\') + 1; *end = 0; + char* lend = strrchr_dbcs(sfull, '\\') + 1; *lend = 0; + dta = dos.dta(); + bool exist = false; + lfn_filefind_handle = uselfn ? LFN_FILEFIND_INTERNAL : LFN_FILEFIND_NONE; + while(res) { + dta.GetResult(name, lname, size, hsize, date, time, attr); + if(!optF && (attr & DOS_ATTR_READ_ONLY) && !(attr & DOS_ATTR_DIRECTORY)) { + exist = true; + strcpy(end, name); + strcpy(lend, lname); + WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"), uselfn ? sfull : full); + } + else if(!(attr & DOS_ATTR_DIRECTORY)) { + exist = true; + strcpy(end, name); + strcpy(lend, lname); + if(optP) { + WriteOut(MSG_Get("SHELL_CMD_DEL_CONFIRM"), uselfn ? sfull : full); + uint8_t c; + uint16_t n = 1; + DOS_ReadFile(STDIN, &c, &n); + if(c == 3) break; + c = c == ch_y || c == ch_Y ? ch_Y : ch_N; + WriteOut("%c\r\n", c); + if(c == ch_N) { lfn_filefind_handle = uselfn ? LFN_FILEFIND_INTERNAL : LFN_FILEFIND_NONE; res = DOS_FindNext(); continue; } + } + if(strlen(full)) { + std::string pfull = (uselfn || strchr(full, ' ') ? (full[0] != '"' ? "\"" : "") : "") + std::string(full) + (uselfn || strchr(full, ' ') ? (full[strlen(full) - 1] != '"' ? "\"" : "") : ""); + bool reset = false; + if(optF && (attr & DOS_ATTR_READ_ONLY) && DOS_SetFileAttr(pfull.c_str(), attr & ~DOS_ATTR_READ_ONLY)) reset = true; + if(!DOS_UnlinkFile(pfull.c_str())) { + if(optF && reset) DOS_SetFileAttr(pfull.c_str(), attr); + WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"), uselfn ? sfull : full); + } + } + else WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"), uselfn ? sfull : full); + } + res = DOS_FindNext(); + } + lfn_filefind_handle = fbak; + if(!exist) WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"), args); + dos.dta(save_dta); + } + + size_t GetPauseCount() { + uint16_t rows; + if (IS_PC98_ARCH) + rows=real_readb(0x60,0x113) & 0x01 ? 25 : 20; + else + rows=(IS_EGAVGA_ARCH?real_readb(BIOSMEM_SEG,BIOSMEM_NB_ROWS):24)+1; + return (rows > 2u) ? (rows - 2u) : 23u; + } + + struct DtaResult { + char name[DOS_NAMELENGTH_ASCII]; + char lname[LFN_NAMELENGTH+1]; + uint32_t size; + uint32_t hsize; + uint16_t date; + uint16_t time; + uint8_t attr; + + static bool groupDef(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && strcmp(lhs.name, rhs.name) < 0); } + static bool groupExt(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && strcmp(lhs.getExtension(), rhs.getExtension()) < 0); } + static bool groupSize(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && lhs.size+lhs.hsize*0x100000000 < rhs.size+rhs.hsize*0x100000000); } + static bool groupDate(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && (lhs.date < rhs.date || (lhs.date == rhs.date && lhs.time < rhs.time))); } + static bool groupRevDef(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && strcmp(lhs.name, rhs.name) > 0); } + static bool groupRevExt(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && strcmp(lhs.getExtension(), rhs.getExtension()) > 0); } + static bool groupRevSize(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && lhs.size+lhs.hsize*0x100000000 > rhs.size+rhs.hsize*0x100000000); } + static bool groupRevDate(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY)?true:((((lhs.attr & DOS_ATTR_DIRECTORY) && (rhs.attr & DOS_ATTR_DIRECTORY)) || (!(lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY))) && (lhs.date > rhs.date || (lhs.date == rhs.date && lhs.time > rhs.time))); } + static bool groupDirs(const DtaResult &lhs, const DtaResult &rhs) { return (lhs.attr & DOS_ATTR_DIRECTORY) && !(rhs.attr & DOS_ATTR_DIRECTORY); } + static bool compareName(const DtaResult &lhs, const DtaResult &rhs) { return strcmp(lhs.name, rhs.name) < 0; } + static bool compareExt(const DtaResult &lhs, const DtaResult &rhs) { return strcmp(lhs.getExtension(), rhs.getExtension()) < 0; } + static bool compareSize(const DtaResult &lhs, const DtaResult &rhs) { return lhs.size+lhs.hsize*0x100000000 < rhs.size+rhs.hsize*0x100000000; } + static bool compareDate(const DtaResult &lhs, const DtaResult &rhs) { return lhs.date < rhs.date || (lhs.date == rhs.date && lhs.time < rhs.time); } + + const char * getExtension() const { + const char * ext = empty_string; + if (name[0] != '.') { + ext = strrchr(name, '.'); + if (!ext) ext = empty_string; + } + return ext; + } + + }; + + extern bool ctrlbrk; + std::vector tdirs; + + static bool doDeltree(DOS_Shell * shell, char * args, DOS_DTA dta, bool optY, bool first) { + const char ch_y = MSG_Get("INT21_6523_YESNO_CHARS")[0]; + const char ch_n = MSG_Get("INT21_6523_YESNO_CHARS")[1]; + const char ch_Y = toupper(ch_y); + const char ch_N = toupper(ch_n); + char spath[DOS_PATHLENGTH],sargs[DOS_PATHLENGTH+4],path[DOS_PATHLENGTH+4],full[DOS_PATHLENGTH],sfull[DOS_PATHLENGTH+2]; + if (!DOS_Canonicalize(args,full)||strrchr_dbcs(full,'\\')==NULL) { shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH"));return false; } + if (!DOS_GetSFNPath(args,spath,false)) { + if (first) shell->WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); + return false; + } + if (!uselfn||!DOS_GetSFNPath(args,sfull,true)) strcpy(sfull,full); + sprintf(sargs,"\"%s\"",spath); + bool found=false, fdir=false, res=DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); + if (!res) return false; + //end can't be 0, but if it is we'll get a nice crash, who cares :) + uint16_t attribute=0; + strcpy(path,full); + if (!first&&strlen(args)>3&&!strcmp(args+strlen(args)-4,"\\.\\.")) { + if (strlen(path)&&path[strlen(path)-1]=='\\') path[strlen(path)-1]=0; + if (strlen(path)&&path[strlen(path)-1]!=':') { + bool reset=false; + if(DOS_GetFileAttr(path,&attribute) && (attribute&DOS_ATTR_READ_ONLY)&&DOS_SetFileAttr(path, attribute & ~DOS_ATTR_READ_ONLY)) reset=true; + if (!DOS_RemoveDir(path)&&!(uselfn&&DOS_RemoveDir(sfull))) { + if (reset) DOS_SetFileAttr(path, attribute); + shell->WriteOut(MSG_Get("SHELL_CMD_RMDIR_ERROR"),uselfn?sfull:full); + } + } + return true; + } + *(strrchr_dbcs(path,'\\')+1)=0; + char * end=strrchr_dbcs(full,'\\')+1;*end=0; + char * lend=strrchr_dbcs(sfull,'\\')+1;*lend=0; + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH+1]; + uint32_t size,hsize;uint16_t time,date;uint8_t attr;uint16_t fattr; + std::vector cdirs, cfiles; + cdirs.clear(); + cfiles.clear(); + std::string pfull; + while (res) { + strcpy(spath, path); + dta.GetResult(name,lname,size,hsize,date,time,attr); + if (!((!strcmp(name, ".") || !strcmp(name, "..")) && attr & DOS_ATTR_DIRECTORY)) { + found=true; + strcpy(end,name); + strcpy(lend,lname); + if (strlen(full)&&DOS_GetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), &fattr)) { + uint8_t c; + uint16_t n=1; + if(attr&DOS_ATTR_DIRECTORY) { + if (strcmp(name, ".")&&strcmp(name, "..")) { + if (!optY&&first) { + shell->WriteOut(MSG_Get("SHELL_CMD_RMDIR_FULLTREE_CONFIRM"), uselfn ? sfull : full); + DOS_ReadFile (STDIN,&c,&n); + if (c==3) {shell->WriteOut("^C\r\n");break;} + c = c==ch_y||c==ch_Y ? ch_Y:ch_N; + shell->WriteOut("%c\r\n", c); + if (c==ch_N) {res = DOS_FindNext();continue;} + } + fdir=true; + strcat(spath, name); + strcat(spath, "\\*.*"); + cdirs.emplace_back(std::string(spath)); + } + } else { + if (!optY&&first) { + shell->WriteOut(MSG_Get("SHELL_CMD_RMDIR_SINGLE_CONFIRM"), uselfn ? sfull : full); + DOS_ReadFile (STDIN,&c,&n); + if (c==3) {shell->WriteOut("^C\r\n");break;} + c = c==ch_y||c==ch_Y ? ch_Y:ch_N; + shell->WriteOut("%c\r\n", c); + if (c==ch_N) {res = DOS_FindNext();continue;} + } + pfull=(uselfn||strchr(uselfn?sfull:full, ' ')?((uselfn?sfull:full)[0]!='"'?"\"":""):"")+std::string(uselfn?sfull:full)+(uselfn||strchr(uselfn?sfull:full, ' ')?((uselfn?sfull:full)[strlen(uselfn?sfull:full)-1]!='"'?"\"":""):""); + cfiles.push_back(pfull); + } + } + } + res=DOS_FindNext(); + } + while (!cfiles.empty()) { + bool reset=false; + pfull = std::string(cfiles.begin()->c_str()); + if ((attr & DOS_ATTR_READ_ONLY)&&DOS_SetFileAttr(pfull.c_str(), attr & ~DOS_ATTR_READ_ONLY)) reset=true; + if (!DOS_UnlinkFile(pfull.c_str())) { + if (reset) DOS_SetFileAttr(pfull.c_str(), attr); + shell->WriteOut(MSG_Get("SHELL_CMD_DEL_ERROR"),pfull.c_str()); + } + cfiles.erase(cfiles.begin()); + } + if (!first&&strlen(args)>4&&!strcmp(args+strlen(args)-4,"\\*.*")) { + end=strrchr_dbcs(full,'\\')+1;*end=0; + lend=strrchr_dbcs(sfull,'\\')+1;*lend=0; + if (fdir) { + strcpy(spath, path); + strcat(spath, ".\\."); + cdirs.push_back(std::string(spath)); + } else { + if (strlen(path)&&path[strlen(path)-1]=='\\') path[strlen(path)-1]=0; + if (strlen(path)&&path[strlen(path)-1]!=':') { + bool reset=false; + if(DOS_GetFileAttr(path,&attribute) && (attribute&DOS_ATTR_READ_ONLY)&&DOS_SetFileAttr(path, attribute & ~DOS_ATTR_READ_ONLY)) reset=true; + if (!DOS_RemoveDir(path)&&!(uselfn&&DOS_RemoveDir(sfull))) { + if (reset) DOS_SetFileAttr(path, attribute); + shell->WriteOut(MSG_Get("SHELL_CMD_RMDIR_ERROR"),uselfn?sfull:full); + } + } + } + } + tdirs.insert(tdirs.begin()+1, cdirs.begin(), cdirs.end()); + return found; + } + + void DOS_Shell::CMD_DELTREE(char * args) { + //HELP("DELTREE"); + StripSpaces(args); + bool optY=ScanCMDBool(args,"Y"); + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + return; + } + if (!*args) { + WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); + return; + } + + if (uselfn&&strchr(args, '*')) { + char * find_last; + find_last=strrchr_dbcs(args,'\\'); + if (find_last==NULL) find_last=args; + else find_last++; + if (strlen(find_last)>0&&args[strlen(args)-1]=='*'&&strchr(find_last, '.')==NULL) strcat(args, ".*"); + } + char buffer[CROSS_LEN]; + args = ExpandDot(args,buffer, CROSS_LEN, true); + StripSpaces(args); + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + tdirs.clear(); + tdirs.emplace_back(std::string(args)); + bool first=true, found=false; + ctrlbrk=false; + inshell=true; + while (!tdirs.empty()) { + if (doDeltree(this, (char *)tdirs.begin()->c_str(), dta, optY, first)) + found=true; + first=false; + tdirs.erase(tdirs.begin()); + } + inshell=true; + if (!found) WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); + dos.dta(save_dta); + } + + bool CheckBreak(DOS_Shell * shell) { + if (ctrlbrk || dos.errorcode == 77) { + if (dos.errorcode == 77) dos.errorcode = 0; + else if (ctrlbrk) { + ctrlbrk=false; + uint8_t c;uint16_t n=1; + DOS_ReadFile (STDIN,&c,&n); + if (c == 3 && (inshell || dos.errorcode == 77)) shell->WriteOut("^C\r\n"); + if (dos.errorcode == 77) dos.errorcode = 0; + ctrlbrk=false; + } + return true; + } else + return false; + } + + bool cont[200]; + static bool doTree(DOS_Shell * shell, char * args, DOS_DTA dta, bool optA, bool optF) { + char *p=strchr(args, ':'); + bool found=false, last=false, plast=false; + int level=1; + if (p) { + *p=0; + if (*args=='-') { + plast=true; + args++; + } + level=atoi(args); + args=p+1; + if (tdirs.size()<2) last=true; + else { + char * arg=(char *)(tdirs.begin()+1)->c_str(); + p=strchr(arg, ':'); + if (p) { + *p=0; + if (level!=atoi(*arg=='-'?arg+1:arg)) last=true; + *p=':'; + } + } + } + if (level>=200) return false; + char spath[DOS_PATHLENGTH],sargs[DOS_PATHLENGTH+4],path[DOS_PATHLENGTH+4],full[DOS_PATHLENGTH],sfull[DOS_PATHLENGTH+2]; + if (!DOS_Canonicalize(args,full)||strrchr_dbcs(full,'\\')==NULL) { shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH"));return level; } + if (!DOS_GetSFNPath(args,spath,false)) { + if (!level) shell->WriteOut(MSG_Get("SHELL_CMD_TREE_ERROR")); + return level; + } + if (!uselfn||!DOS_GetSFNPath(args,sfull,true)) strcpy(sfull,full); + if (level&&strlen(sfull)>4&&!strcasecmp(sfull+strlen(sfull)-4, "\\*.*")) { + *(sfull+strlen(sfull)-4)=0; + p=strrchr_dbcs(sfull, '\\'); + char c=optA?(last?'\\':'+'):(last?0xc0:0xc3); + cont[level]=!last; + for (int i=1; iWriteOut("%c ", cont[i]?(optA?'|':0xb3):' '); + shell->WriteOut(("%c"+std::string(3, optA?'-':0xc4)+"%s\n").c_str(), c, p?p+1:sfull); + *(sfull+strlen(sfull))='\\'; + } + sprintf(sargs,"\"%s\"",spath); + bool res=DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); + if (!res) { + if (!level) shell->WriteOut(MSG_Get("SHELL_CMD_TREE_ERROR")); + return level; + } + //uint16_t attribute=0; UNUSED + strcpy(path,full); + *(strrchr_dbcs(path,'\\')+1)=0; + char * end=strrchr_dbcs(full,'\\')+1;*end=0; + char * lend=strrchr_dbcs(sfull,'\\')+1;*lend=0; + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH+1]; + uint32_t size,hsize;uint16_t time,date;uint8_t attr;uint16_t fattr; + std::vector cdirs; + cdirs.clear(); + while (res) { + if (CheckBreak(shell)) return false; + strcpy(spath,((plast||(level==1&&last)?"-":"")+std::to_string(level+1)+":").c_str()); + strcat(spath, path); + dta.GetResult(name,lname,size,hsize,date,time,attr); + if (!((!strcmp(name, ".") || !strcmp(name, "..")) && attr & DOS_ATTR_DIRECTORY)) { + strcpy(end,name); + strcpy(lend,lname); + if (strlen(full)&&DOS_GetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), &fattr)) { + if(attr&DOS_ATTR_DIRECTORY) { + if (strcmp(name, ".")&&strcmp(name, "..")) { + strcat(spath, name); + strcat(spath, "\\*.*"); + cdirs.emplace_back(std::string(spath)); + found=true; + } + } else if (optF) { + for (int i=1; i<=level; i++) shell->WriteOut("%c ", (i==1&&level>1?!plast:cont[i])?(optA?'|':0xb3):' '); + shell->WriteOut(" %s\n", uselfn?lname:name); + } + } + } + res=DOS_FindNext(); + } + if (!found&&!level) { + shell->WriteOut(MSG_Get("SHELL_CMD_TREE_ERROR")); + return false; + } + tdirs.insert(tdirs.begin()+1, cdirs.begin(), cdirs.end()); + return true; + } + + bool tree=false; + void DOS_Shell::CMD_TREE(char * args) { + //HELP("TREE"); + StripSpaces(args); + bool optA=ScanCMDBool(args,"A"); + bool optF=ScanCMDBool(args,"F"); + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + return; + } + StripSpaces(args); + char buffer[CROSS_LEN]; + strcpy(buffer, "0:"); + strcat(buffer, *args?args:"."); + if (strlen(args)==2&&args[1]==':') strcat(buffer, "."); + if (args[strlen(args)-1]!='\\') strcat(buffer, "\\"); + strcat(buffer, "*.*"); + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + if (strlen(args)>1&&args[1]==':') { + char c[]=" _:"; + c[1]=toupper(args[0]); + if (!Drives[c[1]-'A']) { + WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); + return; + } + tree=true; + CMD_VOL(c[1]>='A'&&c[1]<='Z'?c:empty_string); + tree=false; + WriteOut("%c:%s\n", c[1], *args?args+2:"."); + } else { + tree=true; + CMD_VOL(empty_string); + tree=false; + uint8_t drive=DOS_GetDefaultDrive(); + WriteOut("%c:%s\n", 'A'+drive, *args?args:"."); + } + for (int i=0; i<200; i++) cont[i]=false; + ctrlbrk=false; + inshell=true; + tdirs.clear(); + tdirs.emplace_back(std::string(buffer)); + while (!tdirs.empty()) { + if (!doTree(this, (char *)tdirs.begin()->c_str(), dta, optA, optF)) break; + tdirs.erase(tdirs.begin()); + } + inshell=false; + dos.dta(save_dta); + } + + void DOS_Shell::CMD_HELP(char * args){ + HELP("HELP"); + bool optall=ScanCMDBool(args,"A")|ScanCMDBool(args,"ALL"); + /* Print the help */ + args = trim(args); + upcase(args); + uint8_t attr = DOS_GetAnsiAttr(); + if(!optall&&!*args) WriteOut(MSG_Get("SHELL_CMD_HELP")); + uint32_t cmd_index=0,write_count=0; + bool show=false; + while (cmd_list[cmd_index].name) { + if (optall || (*args && !strcmp(args, cmd_list[cmd_index].name)) || (!*args && !cmd_list[cmd_index].flags)) { + show=true; + if (*args && !strcmp(args, cmd_list[cmd_index].name) && !optall) { + std::string cmd=std::string(args); + if (cmd=="CD") cmd="CHDIR"; + else if (cmd=="DEL"||cmd=="ERASE") cmd="DELETE"; + else if (cmd=="LH") cmd="LOADHIGH"; + else if (cmd=="MD") cmd="MKDIR"; + else if (cmd=="RD") cmd="RMDIR"; + else if (cmd=="REN") cmd="RENAME"; + else if (cmd=="DX-CAPTURE") cmd="DXCAPTURE"; + WriteOut("%s\n%s",MSG_Get(cmd_list[cmd_index].help), MSG_Get(("SHELL_CMD_" +cmd+ "_HELP_LONG").c_str())); + } else { + WriteOut("<\033[34;1m%-8s\033[0m> %s",cmd_list[cmd_index].name,MSG_Get(cmd_list[cmd_index].help)); + if(!(++write_count%GetPauseCount())) { + WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) {if (attr) DOS_SetAnsiAttr(attr);return;} + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + } + } + } + cmd_index++; + } + if (optall&&show) + WriteOut(MSG_Get("SHELL_CMD_HELP_END1")); + else if (*args&&!show) { + std::string argc=std::string(StripArg(args)); + if (argc!=""&&argc!="CWSDPMI") DoCommand((char *)(argc+(argc=="DOS4GW"||argc=="DOS32A"||argc=="ZIP"||argc=="UNZIP"?"":" /?")).c_str()); + } + if (!*args&&show) + WriteOut(MSG_Get("SHELL_CMD_HELP_END2")); + if (attr) DOS_SetAnsiAttr(attr); + } + + void removeChar(char *str, char c) { + char *src, *dst; + for (src = dst = str; *src != '\0'; src++) { + *dst = *src; + if (*dst != c) dst++; + } + *dst = '\0'; + } + + void DOS_Shell::CMD_RENAME(char * args){ + HELP("RENAME"); + StripSpaces(args); + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + return; + } + if (!*args) {SyntaxError();return;} + char * arg1=StripArg(args); + StripSpaces(args); + if (!*args) {SyntaxError();return;} + char * arg2=StripArg(args); + StripSpaces(args); + if (*args) {SyntaxError();return;} + char* slash = strrchr_dbcs(arg1,'\\'); + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; + char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH+1], tname1[LFN_NAMELENGTH+1], tname2[LFN_NAMELENGTH+1], text1[LFN_NAMELENGTH+1], text2[LFN_NAMELENGTH+1], tfull[CROSS_LEN+2]; + //dir_source and target are introduced for when we support multiple files being renamed. + char sargs[CROSS_LEN], targs[CROSS_LEN], dir_source[DOS_PATHLENGTH + 4] = {0}, dir_target[CROSS_LEN + 4] = {0}, target[CROSS_LEN + 4] = {0}; //not sure if drive portion is included in pathlength + + if (!slash) slash = strrchr(arg1,':'); + if (slash) { + /* If directory specified (crystal caves installer) + * rename from c:\X : rename c:\abc.exe abc.shr. + * File must appear in C:\ + * Ren X:\A\B C => ren X:\A\B X:\A\C */ + + //Copy first and then modify, makes GCC happy + safe_strncpy(dir_source,arg1,DOS_PATHLENGTH + 4); + char* dummy = strrchr_dbcs(dir_source,'\\'); + if (!dummy) dummy = strrchr(dir_source,':'); + if (!dummy) { //Possible due to length + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + dummy++; + *dummy = 0; + if (strchr_dbcs(arg2,'\\')||strchr(arg2,':')) { + safe_strncpy(dir_target,arg2,DOS_PATHLENGTH + 4); + dummy = strrchr_dbcs(dir_target,'\\'); + if (!dummy) dummy = strrchr(dir_target,':'); + if (dummy) { + dummy++; + *dummy = 0; + if (strcasecmp(dir_source, dir_target)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + } + arg2=strrchr_dbcs(arg2,strrchr_dbcs(arg2,'\\')?'\\':':')+1; + } + if (strlen(dummy)&&dummy[strlen(dummy)-1]==':') + strcat(dummy, ".\\"); + } else { + if (strchr_dbcs(arg2,'\\')||strchr(arg2,':')) {SyntaxError();return;}; + strcpy(dir_source, ".\\"); + } + + strcpy(target,arg2); + + char path[DOS_PATHLENGTH], spath[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH], full[DOS_PATHLENGTH], *r; + if (!DOS_Canonicalize(arg1,full)) return; + r=strrchr_dbcs(full, '\\'); + if (r!=NULL) { + *r=0; + strcpy(path, full); + strcat(path, "\\"); + strcpy(pattern, r+1); + *r='\\'; + } else { + strcpy(path, ""); + strcpy(pattern, full); + } + int k=0; + for (int i=0;i<(int)strlen(pattern);i++) + if (pattern[i]!='\"') + pattern[k++]=pattern[i]; + pattern[k]=0; + strcpy(spath, path); + if (strchr(arg1,'\"')||uselfn) { + if (!DOS_GetSFNPath(("\""+std::string(path)+"\\").c_str(), spath, false)) strcpy(spath, path); + if (!strlen(spath)||spath[strlen(spath)-1]!='\\') strcat(spath, "\\"); + } + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + std::string pfull=std::string(spath)+std::string(pattern); + int fbak=lfn_filefind_handle; + lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; + if (!DOS_FindFirst(((uselfn&&pfull.length()&&pfull[0]!='"'?"\"":"")+pfull+(uselfn&&pfull.length()&&pfull[pfull.length()-1]!='"'?"\"":"")).c_str(), strchr(arg1,'*')!=NULL || strchr(arg1,'?')!=NULL ? 0xffff & ~DOS_ATTR_VOLUME & ~DOS_ATTR_DIRECTORY : 0xffff & ~DOS_ATTR_VOLUME)) { + lfn_filefind_handle=fbak; + WriteOut(MSG_Get("SHELL_CMD_RENAME_ERROR"),arg1); + } else { + std::vector sources; + sources.clear(); + + do { /* File name and extension */ + dta.GetResult(name,lname,size,hsize,date,time,attr); + lfn_filefind_handle=fbak; + + if(!(attr&DOS_ATTR_DIRECTORY && (!strcmp(name, ".") || !strcmp(name, "..")))) { + strcpy(dir_target, target); + removeChar(dir_target, '\"'); + arg2=dir_target; + strcpy(sargs, dir_source); + if (uselfn) removeChar(sargs, '\"'); + strcat(sargs, uselfn?lname:name); + if (uselfn&&strchr(arg2,'*')&&!strchr(arg2,'.')) strcat(arg2, ".*"); + char *dot1=strrchr(uselfn?lname:name,'.'), *dot2=strrchr(arg2,'.'), *star; + if (dot2==NULL) { + star=strchr(arg2,'*'); + if (strchr(arg2,'?')) { + for (unsigned int i=0; i<(uselfn?LFN_NAMELENGTH:DOS_NAMELENGTH) && i<(star?star-arg2:strlen(arg2)); i++) { + if (*(arg2+i)=='?'&&i2&&sargs[0]=='.'&&sargs[1]=='\\'?sargs+2:sargs); + } + lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; + } while ( DOS_FindNext() ); + lfn_filefind_handle=fbak; + if (sources.empty()) WriteOut(MSG_Get("SHELL_CMD_RENAME_ERROR"),arg1); + else { + for (std::vector::iterator source = sources.begin(); source != sources.end(); ++source) { + char *oname=(char *)source->c_str(); + source++; + if (source==sources.end()) break; + char *nname=(char *)source->c_str(); + source++; + if (source==sources.end()||oname==NULL||nname==NULL) break; + char *fname=(char *)source->c_str(); + if (!DOS_Rename(oname,nname)&&fname!=NULL) + WriteOut(MSG_Get("SHELL_CMD_RENAME_ERROR"),fname); + } + } + } + dos.dta(save_dta); + } + + void DOS_Shell::CMD_ECHO(char * args){ + if (!*args) { + if (echo) { WriteOut(MSG_Get("SHELL_CMD_ECHO_ON"));} + else { WriteOut(MSG_Get("SHELL_CMD_ECHO_OFF"));} + return; + } + char buffer[512]; + char* pbuffer = buffer; + safe_strncpy(buffer,args,512); + StripSpaces(pbuffer); + if (strcasecmp(pbuffer,"OFF")==0) { + echo=false; + return; + } + if (strcasecmp(pbuffer,"ON")==0) { + echo=true; + return; + } + if(strcasecmp(pbuffer,"/?")==0) { HELP("ECHO"); } + + args++;//skip first character. either a slash or dot or space + size_t len = strlen(args); //TODO check input of else ook nodig is. + if(len && args[len - 1] == '\r') { + LOG(LOG_MISC,LOG_WARN)("Hu ? carriage return already present. Is this possible?"); + WriteOut_NoParsing(args, true); + WriteOut("\n"); + } else { + WriteOut_NoParsing(args, true); + WriteOut("\r\n"); + } + } + + void DOS_Shell::CMD_EXIT(char * args) { + HELP("EXIT"); + exit = true; + } + + std::vector olddrives; + std::vector olddirs; + void DOS_Shell::CMD_PUSHD(char * args) { + HELP("PUSHD"); + StripSpaces(args); + char sargs[CROSS_LEN]; + if (strlen(args)>1 && args[1]==':' && toupper(args[0])>='A' && toupper(args[0])<='Z' && !Drives[toupper(args[0])-'A']) { + WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); + return; + } + if (*args && !DOS_GetSFNPath(args,sargs,false)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + if (*args) { + char dir[DOS_PATHLENGTH]; + uint8_t drive = DOS_GetDefaultDrive()+'A'; + DOS_GetCurrentDir(0,dir,true); + if (strlen(args)>1 && args[1]==':') DOS_SetDefaultDrive(toupper(args[0])-'A'); + if (DOS_ChangeDir(sargs)) { + olddrives.push_back(drive); + olddirs.emplace_back(std::string(dir)); + } else { + if (strlen(args)>1 && args[1]==':') DOS_SetDefaultDrive(drive-'A'); + WriteOut(MSG_Get("SHELL_CMD_CHDIR_ERROR"),args); + } + } else { + for (int i=(int)(olddrives.size()-1); i>=0; i--) + if (olddrives.at(i)>='A'&&olddrives.at(i)<='Z') + WriteOut("%c:\\%s\n",olddrives.at(i),olddirs.at(i).c_str()); + } + } + + void DOS_Shell::CMD_POPD(char * args) { + HELP("POPD"); + if (!olddrives.size()) return; + uint8_t olddrive=olddrives.back(); + std::string olddir=olddirs.back(); + if (olddrive>='A'&&olddrive<='Z'&&Drives[olddrive-'A']) { + uint8_t drive = DOS_GetDefaultDrive()+'A'; + if (olddrive!=DOS_GetDefaultDrive()+'A') DOS_SetDefaultDrive(olddrive-'A'); + if (Drives[DOS_GetDefaultDrive()]->TestDir(olddir.c_str())) + strcpy(Drives[DOS_GetDefaultDrive()]->curdir,olddir.c_str()); + else + DOS_SetDefaultDrive(drive-'A'); + } + olddrives.pop_back(); + olddirs.pop_back(); + } + + void DOS_Shell::CMD_CHDIR(char * args) { + HELP("CHDIR"); + StripSpaces(args); + char sargs[CROSS_LEN]; + if (*args && !DOS_GetSFNPath(args,sargs,false)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + uint8_t drive = DOS_GetDefaultDrive()+'A'; + char dir[DOS_PATHLENGTH]; + if (!*args) { + DOS_GetCurrentDir(0,dir,true); + WriteOut("%c:\\",drive); + WriteOut_NoParsing(dir, true); + WriteOut("\n"); + } else if(strlen(args) == 2 && args[1]==':') { + uint8_t targetdrive = (args[0] | 0x20)-'a' + 1; + unsigned char targetdisplay = *reinterpret_cast(&args[0]); + if(!DOS_GetCurrentDir(targetdrive,dir,true)) { // verify that this should be true + if(drive == 'Z') { + WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_NOT_FOUND"),toupper(targetdisplay)); + } else { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + } + return; + } + WriteOut("%c:\\",toupper(targetdisplay)); + WriteOut_NoParsing(dir, true); + WriteOut("\n"); + if(drive == 'Z') + WriteOut(MSG_Get("SHELL_CMD_CHDIR_HINT"),toupper(targetdisplay)); + } else if (!DOS_ChangeDir(sargs)) { + /* Changedir failed. Check if the filename is longer than 8 and/or contains spaces */ + + std::string temps(args),slashpart; + std::string::size_type separator = temps.find_first_of("\\/"); + if(!separator) { + slashpart = temps.substr(0,1); + temps.erase(0,1); + } + separator = temps.find_first_of("\""); + if(separator != std::string::npos) temps.erase(separator); + separator = temps.rfind('.'); + if(separator != std::string::npos) temps.erase(separator); + separator = temps.find(' '); + if(separator != std::string::npos) {/* Contains spaces */ + temps.erase(separator); + if(temps.size() >6) temps.erase(6); + temps += "~1"; + WriteOut(MSG_Get("SHELL_CMD_CHDIR_HINT_2"),temps.insert(0,slashpart).c_str()); + } else { + if (drive == 'Z') { + WriteOut(MSG_Get("SHELL_CMD_CHDIR_HINT_3")); + } else { + WriteOut(MSG_Get("SHELL_CMD_CHDIR_ERROR"),args); + } + } + } + } + + void DOS_Shell::CMD_MKDIR(char * args) { + HELP("MKDIR"); + StripSpaces(args); + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + return; + } + if (!*args) { + WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); + return; + } + if (!DOS_MakeDir(args)) { + WriteOut(MSG_Get(dos.errorcode==DOSERR_ACCESS_DENIED?"SHELL_CMD_MKDIR_EXIST":"SHELL_CMD_MKDIR_ERROR"),args); + } + } + + void DOS_Shell::CMD_RMDIR(char * args) { + HELP("RMDIR"); + // ignore /s,and /q switches for compatibility + ScanCMDBool(args,"S"); + ScanCMDBool(args,"Q"); + StripSpaces(args); + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + return; + } + if (!*args) { + WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); + return; + } + if (!DOS_RemoveDir(args)) { + WriteOut(MSG_Get("SHELL_CMD_RMDIR_ERROR"),args); + } + } + + static void FormatNumber(uint64_t num,char * buf) { + uint64_t numo = num; + uint32_t numb,numk,numm,numg,nummi,numgi,numti,numpi,numei; + numb=num % 1000; + num/=1000; + numk=num % 1000; + num/=1000; + numm=num % 1000; + num/=1000; + numg=num % 1000; + numo/=1024; + numo/=1024; + nummi=(numo % 1024) / 10.24 + 0.5; + numo/=1024; + numgi=numo % 1000; + numo/=1000; + numti=numo % 1000; + numo/=1000; + numpi=numo % 1000; + numei=numo / 1000; + if (numei) { + sprintf(buf,"%u%c%03u%c%03u%c%03u%c%02u G",numei,dos.tables.country[7],numpi,dos.tables.country[7],numti,dos.tables.country[7],numgi,dos.tables.country[9],nummi); + return; + } + if (numpi) { + sprintf(buf,"%u%c%03u%c%03u%c%02u G",numpi,dos.tables.country[7],numti,dos.tables.country[7],numgi,dos.tables.country[9],nummi); + return; + } + if (numti) { + sprintf(buf,"%u%c%03u%c%02u G",numti,dos.tables.country[7],numgi,dos.tables.country[9],nummi); + return; + } + if (numg) { + if (numgi>127) sprintf(buf,"%u%c%02u G",numgi,dos.tables.country[9],nummi); + else sprintf(buf,"%u%c%03u%c%03u%c%03u",numg,dos.tables.country[7],numm,dos.tables.country[7],numk,dos.tables.country[7],numb); + return; + } + if (numm) { + sprintf(buf,"%u%c%03u%c%03u",numm,dos.tables.country[7],numk,dos.tables.country[7],numb); + return; + } + if (numk) { + sprintf(buf,"%u%c%03u",numk,dos.tables.country[7],numb); + return; + } + sprintf(buf,"%u",numb); + } + + char buffer[15] = {0}; + char *FormatDate(uint16_t year, uint8_t month, uint8_t day) { + char formatstring[6], c=dos.tables.country[11]; + sprintf(formatstring, dos.tables.country[0]==1?"D%cM%cY":(dos.tables.country[0]==2?"Y%cM%cD":"M%cD%cY"), c, c); + Bitu bufferptr=0; + for(Bitu i = 0; i < 5; i++) { + if(i==1 || i==3) { + buffer[bufferptr] = formatstring[i]; + bufferptr++; + } else { + if(formatstring[i]=='M') bufferptr += (Bitu)sprintf(buffer+bufferptr,"%02u", month); + if(formatstring[i]=='D') bufferptr += (Bitu)sprintf(buffer+bufferptr,"%02u", day); + if(formatstring[i]=='Y') bufferptr += (Bitu)sprintf(buffer+bufferptr,"%04u", year); + } + } + return buffer; + } + + char *FormatTime(Bitu hour, Bitu min, Bitu sec, Bitu msec) { + Bitu fhour=hour; + static char retBuf[14]; + char ampm[3]=""; + if (!(dos.tables.country[17]&1)) { // 12 hour notation? + if (hour!=12) + hour %= 12; + strcpy(ampm, hour != 12 && hour == fhour ? "am" : "pm"); + } + char sep = dos.tables.country[13]; + if (sec>=100&&msec>=100) + sprintf(retBuf, "%2u%c%02u%c", (unsigned int)hour, sep, (unsigned int)min, *ampm); + else + sprintf(retBuf, "%u%c%02u%c%02u%c%02u%s", (unsigned int)hour, sep, (unsigned int)min, sep, (unsigned int)sec, dos.tables.country[9], (unsigned int)msec, ampm); + return retBuf; + } + + uint64_t byte_count; + uint32_t file_count,dir_count; + Bitu p_count; + std::vector dirs, adirs; + static bool dirPaused(DOS_Shell * shell, Bitu w_size, bool optP, bool optW, bool show=true) { + p_count+=optW?5:1; + if (optP && p_count%(GetPauseCount()*w_size)<1) { + shell->WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) {if (show) shell->WriteOut("^C\r\n");return false;} + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + } + return true; + } + + static bool doDir(DOS_Shell * shell, char * args, DOS_DTA dta, char * numformat, Bitu w_size, bool optW, bool optZ, bool optS, bool optP, bool optB, bool optA, bool optAD, bool optAminusD, bool optAS, bool optAminusS, bool optAH, bool optAminusH, bool optAR, bool optAminusR, bool optAA, bool optAminusA, bool optOGN, bool optOGD, bool optOGE, bool optOGS, bool optOG, bool optON, bool optOD, bool optOE, bool optOS, bool reverseSort, bool rev2Sort) { + char path[DOS_PATHLENGTH]; + char sargs[CROSS_LEN], largs[CROSS_LEN], buffer[CROSS_LEN]; + unsigned int tcols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + if (!tcols) tcols=80; + + /* Make a full path in the args */ + if (!DOS_Canonicalize(args,path)) { + shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return true; + } + *(strrchr_dbcs(path,'\\')+1)=0; + if (!DOS_GetSFNPath(path,sargs,false)) { + shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return true; + } + if (!optB&&!optS) { + shell->WriteOut(MSG_Get("SHELL_CMD_DIR_INTRO"),uselfn&&!optZ&&DOS_GetSFNPath(path,largs,true)?largs:sargs); + if (optP) { + p_count+=optW?10:2; + if (p_count%(GetPauseCount()*w_size)<2) { + shell->WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) return false; + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + } + } + } + if (*(sargs+strlen(sargs)-1) != '\\') strcat(sargs,"\\"); + + uint64_t cbyte_count=0; + uint32_t cfile_count=0,w_count=0; + int fbak=lfn_filefind_handle; + lfn_filefind_handle=uselfn&&!optZ?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; + bool ret=DOS_FindFirst(args,0xffff & ~DOS_ATTR_VOLUME), found=true, first=true; + if (!ret) { + size_t len = strlen(args); + args = ExpandDotMore(args,buffer,CROSS_LEN); + if (strlen(args)!=len) ret=DOS_FindFirst(args,0xffff & ~DOS_ATTR_VOLUME); + } + lfn_filefind_handle=fbak; + if (ret) { + std::vector results; + + lfn_filefind_handle=uselfn&&!optZ?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; + do { /* File name and extension */ + DtaResult result; + dta.GetResult(result.name,result.lname,result.size,result.hsize,result.date,result.time,result.attr); + + /* Skip non-directories if option AD is present, or skip dirs in case of A-D */ + if(optAD && !(result.attr&DOS_ATTR_DIRECTORY) ) continue; + else if(optAminusD && (result.attr&DOS_ATTR_DIRECTORY) ) continue; + else if(optAS && !(result.attr&DOS_ATTR_SYSTEM) ) continue; + else if(optAminusS && (result.attr&DOS_ATTR_SYSTEM) ) continue; + else if(optAH && !(result.attr&DOS_ATTR_HIDDEN) ) continue; + else if(optAminusH && (result.attr&DOS_ATTR_HIDDEN) ) continue; + else if(optAR && !(result.attr&DOS_ATTR_READ_ONLY) ) continue; + else if(optAminusR && (result.attr&DOS_ATTR_READ_ONLY) ) continue; + else if(optAA && !(result.attr&DOS_ATTR_ARCHIVE) ) continue; + else if(optAminusA && (result.attr&DOS_ATTR_ARCHIVE) ) continue; + else if(!(optA||optAD||optAminusD||optAS||optAminusS||optAH||optAminusH||optAR||optAminusR||optAA||optAminusA) && (result.attr&DOS_ATTR_SYSTEM || result.attr&DOS_ATTR_HIDDEN) && strcmp(result.name, "..") ) continue; + + results.push_back(result); + + } while ( (ret=DOS_FindNext()) ); + lfn_filefind_handle=fbak; + + bool oneRev = (reverseSort||rev2Sort)&&reverseSort!=rev2Sort; + if (optON) { + // Sort by name + std::sort(results.begin(), results.end(), DtaResult::compareName); + } else if (optOE) { + // Sort by extension + std::sort(results.begin(), results.end(), DtaResult::compareExt); + } else if (optOD) { + // Sort by date + std::sort(results.begin(), results.end(), DtaResult::compareDate); + } else if (optOS) { + // Sort by size + std::sort(results.begin(), results.end(), DtaResult::compareSize); + } else if (optOG) { + // Directories first, then files + std::sort(results.begin(), results.end(), DtaResult::groupDirs); + } else if (optOGN) { + // Directories first, then files, both sort by name + std::sort(results.begin(), results.end(), oneRev?DtaResult::groupRevDef:DtaResult::groupDef); + } else if (optOGE) { + // Directories first, then files, both sort by extension + std::sort(results.begin(), results.end(), oneRev?DtaResult::groupRevExt:DtaResult::groupExt); + } else if (optOGS) { + // Directories first, then files, both sort by size + std::sort(results.begin(), results.end(), oneRev?DtaResult::groupRevSize:DtaResult::groupSize); + } else if (optOGD) { + // Directories first, then files, both sort by date + std::sort(results.begin(), results.end(), oneRev?DtaResult::groupRevDate:DtaResult::groupDate); + } + if (reverseSort) std::reverse(results.begin(), results.end()); + + for (std::vector::iterator iter = results.begin(); iter != results.end(); ++iter) { + if (CheckBreak(shell)) return false; + char * name = iter->name; + char *lname = iter->lname; + uint32_t size = iter->size; + uint32_t hsize = iter->hsize; + uint16_t date = iter->date; + uint16_t time = iter->time; + uint8_t attr = iter->attr; + + /* output the file */ + if (optB) { + // this overrides pretty much everything + if (strcmp(".",uselfn&&!optZ?lname:name) && strcmp("..",uselfn&&!optZ?lname:name)) { + int m=shell->WriteOut_NoParsing(uselfn&&!optZ?lname:name, true); + shell->WriteOut("\n"); + if (optP) { + p_count+=m+1; + if (p_count%GetPauseCount()WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) return false; + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + p_count=0; + } + } + } + } else { + if (first&&optS) { + first=false; + shell->WriteOut("\n"); + shell->WriteOut(MSG_Get("SHELL_CMD_DIR_INTRO"),uselfn&&!optZ&&DOS_GetSFNPath(path,largs,true)?largs:sargs); + if (optP) { + p_count+=optW?15:3; + if (optS&&p_count%(GetPauseCount()*w_size)<3) { + shell->WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) return false; + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + } + } + } + char * ext = empty_string; + if (!optW && (name[0] != '.')) { + ext = strrchr(name, '.'); + if (!ext) ext = empty_string; + else *ext++ = 0; + } + uint8_t day = (uint8_t)(date & 0x001f); + uint8_t month = (uint8_t)((date >> 5) & 0x000f); + uint16_t year = (uint16_t)((date >> 9) + 1980); + uint8_t hour = (uint8_t)((time >> 5 ) >> 6); + uint8_t minute = (uint8_t)((time >> 5) & 0x003f); + unsigned int m=0; + if (attr & DOS_ATTR_DIRECTORY) { + if (optW) { + shell->WriteOut("[%s]",name); + size_t namelen = strlen(name); + if (namelen <= 14) { + for (size_t i=14-namelen;i>0;i--) shell->WriteOut(" "); + } + } else { + shell->WriteOut("%-8s %-3s %-16s %s %s",name,ext,"",FormatDate(year,month,day),FormatTime(hour,minute,100,100)); + if (uselfn&&!optZ) { + shell->WriteOut(" "); + m=shell->WriteOut_NoParsing(lname, true); + } + shell->WriteOut("\n"); + if (optP) { + p_count+=(optW?5:1)*m; + if (p_count%(GetPauseCount()*w_size)WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) return false; + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + p_count=0; + } + } + } + dir_count++; + } else { + if (optW) { + shell->WriteOut("%-16s",name); + } else { + FormatNumber(size+hsize*0x100000000,numformat); + shell->WriteOut("%-8s %-3s %16s %s %s",name,ext,numformat,FormatDate(year,month,day),FormatTime(hour,minute,100,100)); + if (uselfn&&!optZ) { + shell->WriteOut(" "); + m=shell->WriteOut_NoParsing(lname, true); + } + shell->WriteOut("\n"); + if (optP) { + p_count+=(optW?5:1)*m; + if (p_count%(GetPauseCount()*w_size)WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) return false; + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + p_count=0; + } + } + } + if (optS) { + cfile_count++; + cbyte_count+=size+hsize*0x100000000; + } + file_count++; + byte_count+=size+hsize*0x100000000; + } + if (optW) w_count++; + } + if (optW && w_count%5==0 && tcols>80) shell->WriteOut("\n"); + if (optP && !optB && !(++p_count%(GetPauseCount()*w_size))) { + if (optW&&w_count%5) {shell->WriteOut("\n");w_count=0;} + shell->WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) return false; + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + } + } + + if (!results.size()) + found=false; + else if (optW&&w_count%5) + shell->WriteOut("\n"); + } else + found=false; + if (!found&&!optB&&!optS) { + shell->WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); + if (!dirPaused(shell, w_size, optP, optW, false)) return false; + } + if (optS) { + size_t len=strlen(sargs); + strcat(sargs, "*.*"); + bool ret=DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); + *(sargs+len)=0; + if (ret) { + std::vector cdirs; + cdirs.clear(); + do { /* File name and extension */ + DtaResult result; + dta.GetResult(result.name,result.lname,result.size,result.hsize,result.date,result.time,result.attr); + + if(result.attr&DOS_ATTR_DIRECTORY && strcmp(result.name, ".")&&strcmp(result.name, "..")) { + strcat(sargs, result.name); + strcat(sargs, "\\"); + char *fname = strrchr_dbcs(args, '\\'); + if (fname==NULL) fname=args; + else fname++; + strcat(sargs, fname); + cdirs.push_back((sargs[0]!='"'&&sargs[strlen(sargs)-1]=='"'?"\"":"")+std::string(sargs)); + *(sargs+len)=0; + } + } while ( (ret=DOS_FindNext()) ); + dirs.insert(dirs.begin()+1, cdirs.begin(), cdirs.end()); + } + if (found&&!optB) { + FormatNumber(cbyte_count,numformat); + shell->WriteOut(MSG_Get("SHELL_CMD_DIR_BYTES_USED"),cfile_count,numformat); + if (!dirPaused(shell, w_size, optP, optW, false)) return false; + } + } + return true; + } + + void DOS_Shell::CMD_DIR(char * args) { + HELP("DIR"); + char numformat[64]; + char path[DOS_PATHLENGTH]; + char sargs[CROSS_LEN]; + + std::string line; + if(GetEnvStr("DIRCMD",line)){ + std::string::size_type idx = line.find('='); + std::string value=line.substr(idx +1 , std::string::npos); + line = std::string(args) + " " + value; + args=const_cast(line.c_str()); + } + + ScanCMDBool(args,"4"); /* /4 ignored (default) */ + bool optW=ScanCMDBool(args,"W"); + bool optP=ScanCMDBool(args,"P"); + if (ScanCMDBool(args,"WP") || ScanCMDBool(args,"PW")) optW=optP=true; + if (ScanCMDBool(args,"-W")) optW=false; + if (ScanCMDBool(args,"-P")) optP=false; + bool optZ=ScanCMDBool(args,"Z"); + if (ScanCMDBool(args,"-Z")) optZ=false; + bool optS=ScanCMDBool(args,"S"); + if (ScanCMDBool(args,"-S")) optS=false; + bool optB=ScanCMDBool(args,"B"); + if (ScanCMDBool(args,"-B")) optB=false; + bool optA=ScanCMDBool(args,"A"); + bool optAD=ScanCMDBool(args,"AD")||ScanCMDBool(args,"A:D"); + bool optAminusD=ScanCMDBool(args,"A-D")||ScanCMDBool(args,"A:-D"); + bool optAS=ScanCMDBool(args,"AS")||ScanCMDBool(args,"A:S"); + bool optAminusS=ScanCMDBool(args,"A-S")||ScanCMDBool(args,"A:-S"); + bool optAH=ScanCMDBool(args,"AH")||ScanCMDBool(args,"A:H"); + bool optAminusH=ScanCMDBool(args,"A-H")||ScanCMDBool(args,"A:-H"); + bool optAR=ScanCMDBool(args,"AR")||ScanCMDBool(args,"A:R"); + bool optAminusR=ScanCMDBool(args,"A-R")||ScanCMDBool(args,"A:-R"); + bool optAA=ScanCMDBool(args,"AA")||ScanCMDBool(args,"A:A"); + bool optAminusA=ScanCMDBool(args,"A-A")||ScanCMDBool(args,"A:-A"); + if (ScanCMDBool(args,"-A")) { + optA = false; + optAD = false; + optAminusD = false; + optAS = false; + optAminusS = false; + optAH = false; + optAminusH = false; + optAR = false; + optAminusR = false; + optAA = false; + optAminusA = false; + } + // Sorting flags + bool reverseSort = false, rev2Sort = false; + bool optON=ScanCMDBool(args,"ON")||ScanCMDBool(args,"O:N"); + if (ScanCMDBool(args,"O-N")||ScanCMDBool(args,"O:-N")) { + optON = true; + reverseSort = true; + } + bool optOD=ScanCMDBool(args,"OD")||ScanCMDBool(args,"O:D"); + if (ScanCMDBool(args,"O-D")||ScanCMDBool(args,"O:-D")) { + optOD = true; + reverseSort = true; + } + bool optOE=ScanCMDBool(args,"OE")||ScanCMDBool(args,"O:E"); + if (ScanCMDBool(args,"O-E")||ScanCMDBool(args,"O:-E")) { + optOE = true; + reverseSort = true; + } + bool optOS=ScanCMDBool(args,"OS")||ScanCMDBool(args,"O:S"); + if (ScanCMDBool(args,"O-S")||ScanCMDBool(args,"O:-S")) { + optOS = true; + reverseSort = true; + } + bool optOG=ScanCMDBool(args,"OG")||ScanCMDBool(args,"O:G"); + if (ScanCMDBool(args,"O-G")||ScanCMDBool(args,"O:-G")) { + optOG = true; + reverseSort = true; + } + bool b0 = false, b1 = false, b2 = false, b3 = false; + bool optOGN = false, optOGD = false, optOGE = false, optOGS = false; + b0=ScanCMDBool(args,"O")||ScanCMDBool(args,"OGN")||ScanCMDBool(args,"O:GN");b1=ScanCMDBool(args,"O-GN")||ScanCMDBool(args,"O:-GN"); + b2=ScanCMDBool(args,"O-G-N")||ScanCMDBool(args,"O:-G-N"),b3=ScanCMDBool(args,"OG-N")||ScanCMDBool(args,"O:G-N"); + if (b0||b1||b2||b3) { + optOGN = true; + reverseSort = b1||b2; + rev2Sort = b2||b3; + } + b0=ScanCMDBool(args,"OGD")||ScanCMDBool(args,"O:GD");b1=ScanCMDBool(args,"O-GD")||ScanCMDBool(args,"O:-GD"); + b2=ScanCMDBool(args,"O-G-D")||ScanCMDBool(args,"O:-G-D");b3=ScanCMDBool(args,"OG-D")||ScanCMDBool(args,"O:G-D"); + if (b0||b1||b2||b3) { + optOGD = true; + reverseSort = b1||b2; + rev2Sort = b2||b3; + } + b0=ScanCMDBool(args,"OGE")||ScanCMDBool(args,"O:GE");b1=ScanCMDBool(args,"O-GE")||ScanCMDBool(args,"O:-GE"); + b2=ScanCMDBool(args,"O-G-E")||ScanCMDBool(args,"O:-G-E");b3=ScanCMDBool(args,"OG-E")||ScanCMDBool(args,"O:G-E"); + if (b0||b1||b2||b3) { + optOGE = true; + reverseSort = b1||b2; + rev2Sort = b2||b3; + } + b0=ScanCMDBool(args,"OGS")||ScanCMDBool(args,"O:GS");b1=ScanCMDBool(args,"O-GS")||ScanCMDBool(args,"O:-GS"); + b2=ScanCMDBool(args,"O-G-S")||ScanCMDBool(args,"O:-G-S");b3=ScanCMDBool(args,"OG-S")||ScanCMDBool(args,"O:G-S"); + if (b0||b1||b2||b3) { + optOGS = true; + reverseSort = b1||b2; + rev2Sort = b2||b3; + } + if (optOGN||optOGD||optOGE||optOGS) optOG = false; + if (ScanCMDBool(args,"-O")) { + optOG = false; + optON = false; + optOD = false; + optOE = false; + optOS = false; + optOGN = false; + optOGD = false; + optOGE = false; + optOGS = false; + reverseSort = false; + } + const char *valid[] = {"4","W","P","-W","-P","WP","PW","Z","-Z","S","-S","B","-B", + "A","-A","AD","A:D","A-D","A:-D","AS","A:S","A-S","A:-S","AH","A:H","A-H","A:-H","AR","A:R","A-R","A:-R","AA","A:A","A-A","A:-A", + "O","-O","ON","O:N","O-N","O:-N","OD","O:D","O-D","O:-D","OE","O:E","O-E","O:-E","OS","O:S","O-S","O:-S","OG","O:G","O-G","O:-G", + "OGN","O:GN","O-GN","O:-GN","OG-N","O:G-N","O-G-N","O:-G-N","OGD","O:GD","O-GD","O:-GD","OG-D","O:G-D","O-G-D","O:-G-D", + "OGE","O:GE","O-GE","O:-GE","OG-E","O:G-E","O-G-E","O:-G-E","OGS","O:GS","O-GS","O:-GS","OG-S","O:G-S","O-G-S","O:-G-S", + NULL}; + if (args && strlen(args)>1) for (int i=0; valid[i] && *args && strchr(args,'/'); i++) while (ScanCMDBool(args,valid[i])); + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + return; + } + byte_count=0;file_count=0;dir_count=0;p_count=0; + Bitu w_size = optW?5:1; + + char buffer[CROSS_LEN]; + args = trim(args); + size_t argLen = strlen(args); + if (argLen == 0) { + strcpy(args,"*.*"); //no arguments. + } else { + // handle \, C:\, etc. handle C:, etc. + if(check_last_split_char(args, argLen, '\\') || args[argLen-1] == ':') { + strcat(args,"*.*"); + } + } + args = ExpandDot(args,buffer,CROSS_LEN,!uselfn); + + if (DOS_FindDevice(args) != DOS_DEVICES) { + WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); + return; + } + if (!strrchr(args,'*') && !strrchr(args,'?')) { + uint16_t attribute=0; + if(!DOS_GetSFNPath(args,sargs,false)) { + if (strlen(args)>1&&toupper(args[0])>='A'&&toupper(args[0])<='Z'&&args[1]==':'&&!Drives[toupper(args[0])-'A']) + WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); + else + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + if(DOS_GetFileAttr(sargs,&attribute) && (attribute&DOS_ATTR_DIRECTORY) ) { + DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); + DOS_DTA dta(dos.dta()); + strcpy(args,sargs); + strcat(args,"\\*.*"); // if no wildcard and a directory, get its files + } + } + if (!DOS_GetSFNPath(args,sargs,false)) { + if (strlen(args)>1&&toupper(args[0])>='A'&&toupper(args[0])<='Z'&&args[1]==':'&&!Drives[toupper(args[0])-'A']) + WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); + else + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + if (!(uselfn&&!optZ&&strchr(sargs,'*'))&&!strrchr(sargs,'.')) + strcat(sargs,".*"); // if no extension, get them all + sprintf(args,"\"%s\"",sargs); + + /* Make a full path in the args */ + if (!DOS_Canonicalize(args,path)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + *(strrchr_dbcs(path,'\\')+1)=0; + if (!DOS_GetSFNPath(path,sargs,true)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + if (*(sargs+strlen(sargs)-1) != '\\') strcat(sargs,"\\"); + if (!optB) { + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(args)) { + WriteOut("\n"); + if (optP) p_count+=optW?5:1; + } else + #endif + { + if (strlen(sargs)>2&&sargs[1]==':') { + char c[]=" _:"; + c[1]=toupper(sargs[0]); + CMD_VOL(c[1]>='A'&&c[1]<='Z'?c:empty_string); + } else + CMD_VOL(empty_string); + if (optP) p_count+=optW?15:3; + } + } + + /* Command uses dta so set it to our internal dta */ + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + dirs.clear(); + dirs.emplace_back(std::string(args)); + inshell=true; + while (!dirs.empty()) { + ctrlbrk=false; + if (!doDir(this, (char *)dirs.begin()->c_str(), dta, numformat, w_size, optW, optZ, optS, optP, optB, optA, optAD, optAminusD, optAS, optAminusS, optAH, optAminusH, optAR, optAminusR, optAA, optAminusA, optOGN, optOGD, optOGE, optOGS, optOG, optON, optOD, optOE, optOS, reverseSort, rev2Sort)) {dos.dta(save_dta);inshell=false;return;} + dirs.erase(dirs.begin()); + } + inshell=false; + if (!optB) { + if (optS) { + WriteOut("\n"); + if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} + if (!file_count&&!dir_count) + WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); + else + WriteOut(MSG_Get("SHELL_CMD_DIR_FILES_LISTED")); + if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} + } + /* Show the summary of results */ + FormatNumber(byte_count,numformat); + WriteOut(MSG_Get("SHELL_CMD_DIR_BYTES_USED"),file_count,numformat); + if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} + uint8_t drive=dta.GetSearchDrive(); + uint64_t free_space=1024u*1024u*100u; + + if(Drives[drive]) { + uint32_t bytes_sector32; uint32_t sectors_cluster32; uint32_t total_clusters32; uint32_t free_clusters32; + uint64_t total_clusters64; uint64_t free_clusters64; + // Since this is the *internal* shell, we want use maximum available query capability at first + if(Drives[drive]->AllocationInfo64(&bytes_sector32, §ors_cluster32, &total_clusters64, &free_clusters64)) { + freec = 0; + free_space = (uint64_t)bytes_sector32 * (Bitu)sectors_cluster32 * (Bitu)free_clusters64; + } + else if((dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10)) && + Drives[drive]->AllocationInfo32(&bytes_sector32, §ors_cluster32, &total_clusters32, &free_clusters32)) { /* FAT32 aware extended API */ + freec = 0; + free_space = (uint64_t)bytes_sector32 * (Bitu)sectors_cluster32 * (Bitu)free_clusters32; + } + else { + uint16_t bytes_sector; uint8_t sectors_cluster; uint16_t total_clusters; uint16_t free_clusters; + rsize = true; + freec = 0; + Drives[drive]->AllocationInfo(&bytes_sector, §ors_cluster, &total_clusters, &free_clusters); + free_space = (uint64_t)bytes_sector * (Bitu)sectors_cluster * (Bitu)(freec ? freec : free_clusters); + rsize = false; + } + } + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(args)) { + std::string str = MSG_Get("SHELL_CMD_DIR_BYTES_FREE"); + std::string::size_type idx = str.rfind(" %"); + if (idx != std::string::npos) { + str = str.substr(0, idx)+"\n"; // No "nnn Bytes free" + WriteOut(str.c_str(),dir_count); + if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} + } + } else + #endif + { + FormatNumber(free_space,numformat); + WriteOut(MSG_Get("SHELL_CMD_DIR_BYTES_FREE"),dir_count,numformat); + if (!dirPaused(this, w_size, optP, optW)) {dos.dta(save_dta);return;} + } + } + dos.dta(save_dta); + } + + void DOS_Shell::CMD_LS(char *args) { + HELP("LS"); + bool optA=ScanCMDBool(args,"A"); + bool optL=ScanCMDBool(args,"L"); + bool optP=ScanCMDBool(args,"P"); + bool optZ=ScanCMDBool(args,"Z"); + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + return; + } + if (!outcon) optL = true; + + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + + std::string pattern = args; + trim(pattern); + + const char last_char = (pattern.length() > 0 ? pattern.back() : '\0'); + switch (last_char) { + case '\0': // No arguments, search for all. + pattern = "*.*"; + break; + case '\\': // Handle \, C:\, etc. + case ':': // Handle C:, etc. + pattern += "*.*"; + break; + default: break; + } + + // Handle patterns starting with a dot. + char buffer[CROSS_LEN]; + pattern = ExpandDot((char *)pattern.c_str(), buffer, sizeof(buffer), true); + + // When there's no wildcard and target is a directory then search files + // inside the directory. + const char *p = pattern.c_str(); + if (!strrchr(p, '*') && !strrchr(p, '?')) { + uint16_t attr = 0; + if (DOS_GetFileAttr(p, &attr) && (attr & DOS_ATTR_DIRECTORY)) + pattern += "\\*.*"; + } + + // If no extension, list all files. + // This makes patterns like foo* work. + if (!strrchr(pattern.c_str(), '.')) + pattern += ".*"; + + char spattern[CROSS_LEN]; + if (!DOS_GetSFNPath(pattern.c_str(),spattern,false)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + return; + } + int fbak=lfn_filefind_handle; + lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; + bool ret = DOS_FindFirst(((uselfn?"\"":"")+std::string(spattern)+(uselfn?"\"":"")).c_str(), 0xffff & ~DOS_ATTR_VOLUME); + if (!ret) { + lfn_filefind_handle=fbak; + if (strlen(trim(args))) + WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"), trim(args)); + else + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + dos.dta(save_dta); + return; + } + + std::vector results; + // reserve space for as many as we can fit into a single memory page + // nothing more to it; make it larger if necessary + results.reserve(MEM_PAGE_SIZE / sizeof(DtaResult)); + + do { + DtaResult result; + dta.GetResult(result.name, result.lname, result.size, result.hsize, result.date, result.time, result.attr); + results.push_back(result); + } while ((ret = DOS_FindNext()) == true); + lfn_filefind_handle=fbak; + + size_t w_count, p_count, col; + unsigned int max[15], total, tcols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + if (!tcols) tcols=80; + int mrow=tcols>80?15:10; + + for (col=mrow; col>0; col--) { + for (int i=0; imax[w_count%col]) max[w_count%col]=(unsigned int)(name.size()+2); + ++w_count; + } + total=0; + for (size_t i=0; i4) { + std::string ext=name.substr(name.length()-4); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + if (ext==".exe"||ext==".com"||ext==".bat") is_executable=true; + } + if (col==1) { + if (is_executable) WriteOut("\033[32;1m"); + p_count+=WriteOut_NoParsing(name.c_str(), true); + WriteOut(is_executable?"\033[0m\n":"\n"); + p_count++; + } else + WriteOut(is_executable?"\033[32;1m%-*s\033[0m":"%-*s", max[w_count % col], name.c_str()); + } + if (col>1) { + ++w_count; + if (w_count % col == 0) {p_count++;WriteOut_NoParsing("\n");} + } + if (optP&&p_count>=GetPauseCount()) { + WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==3) {dos.dta(save_dta);return;} + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + p_count=0; + } + } + if (col>1&&w_count%col) WriteOut_NoParsing("\n"); + dos.dta(save_dta); + } + + struct copysource { + std::string filename; + bool concat; + copysource(std::string& filein,bool concatin): + filename(filein),concat(concatin){ }; + copysource():filename(""),concat(false){ }; + }; + + void DOS_Shell::CMD_COPY(char * args) { + HELP("COPY"); + static std::string defaulttarget = "."; + const char ch_y = MSG_Get("INT21_6523_YESNO_CHARS")[0]; + const char ch_n = MSG_Get("INT21_6523_YESNO_CHARS")[1]; + const char ch_Y = toupper(ch_y); + const char ch_N = toupper(ch_n); + const char ch_a = MSG_Get("SHELL_ALLFILES_CHAR")[0]; + const char ch_A = toupper(ch_a); + StripSpaces(args); + /* Command uses dta so set it to our internal dta */ + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; + char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH+1]; + std::vector sources; + // ignore /b and /t switches: always copy binary + while(ScanCMDBool(args,"B")) ; + while(ScanCMDBool(args,"T")) ; //Shouldn't this be A ? + while(ScanCMDBool(args,"A")) ; + bool optY=ScanCMDBool(args,"Y"); + if (bf||call||exec) optY=true; + std::string line; + if(GetEnvStr("COPYCMD",line)){ + std::string::size_type idx = line.find('='); + std::string value=line.substr(idx +1 , std::string::npos); + char copycmd[CROSS_LEN]; + strcpy(copycmd, value.c_str()); + if (ScanCMDBool(copycmd, "Y") && !ScanCMDBool(copycmd, "-Y")) optY = true; + } + if (ScanCMDBool(args,"-Y")) optY=false; + ScanCMDBool(args,"V"); + + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + dos.dta(save_dta); + return; + } + // Gather all sources (extension to copy more than 1 file specified at command line) + // Concatenating files go as follows: All parts except for the last bear the concat flag. + // This construction allows them to be counted (only the non concat set) + char q[]="\""; + char* source_p = NULL; + char source_x[DOS_PATHLENGTH+CROSS_LEN]; + while ( (source_p = StripArg(args)) && *source_p ) { + do { + char* plus = strchr(source_p,'+'); + // If StripWord() previously cut at a space before a plus then + // set concatenate flag on last source and remove leading plus. + if (plus == source_p && sources.size()) { + sources[sources.size()-1].concat = true; + // If spaces also followed plus then item is only a plus. + if (strlen(++source_p)==0) break; + plus = strchr(source_p,'+'); + } + if (plus) { + char *c=source_p+strlen(source_p)-1; + if (*source_p=='"'&&*c=='"') { + *c=0; + if (strchr(source_p+1,'"')) + *plus++ = 0; + else + plus=NULL; + *c='"'; + } else + *plus++ = 0; + } + safe_strncpy(source_x,source_p,CROSS_LEN); + bool has_drive_spec = false; + size_t source_x_len = strlen(source_x); + if (source_x_len>0) { + if (source_x[source_x_len-1]==':') has_drive_spec = true; + else if (uselfn&&strchr(source_x, '*')) { + char * find_last; + find_last=strrchr_dbcs(source_x,'\\'); + if (find_last==NULL) find_last=source_x; + else find_last++; + if (strlen(find_last)>0&&source_x[source_x_len-1]=='*'&&strchr(find_last, '.')==NULL) strcat(source_x, ".*"); + } + } + if (!has_drive_spec && !strpbrk(source_p,"*?") ) { //doubt that fu*\*.* is valid + char spath[DOS_PATHLENGTH]; + if (DOS_GetSFNPath(source_p,spath,false)) { + bool root=false; + if (strlen(spath)==3&&spath[1]==':'&&spath[2]=='\\') { + root=true; + strcat(spath, "*.*"); + } + if (DOS_FindFirst(spath,0xffff & ~DOS_ATTR_VOLUME)) { + dta.GetResult(name,lname,size,hsize,date,time,attr); + if (attr & DOS_ATTR_DIRECTORY || root) + strcat(source_x,"\\*.*"); + } + } + } + std::string source_xString = std::string(source_x); + sources.push_back(copysource(source_xString,(plus)?true:false)); + source_p = plus; + } while(source_p && *source_p); + } + // At least one source has to be there + if (!sources.size() || !sources[0].filename.size()) { + WriteOut(MSG_Get("SHELL_MISSING_PARAMETER")); + dos.dta(save_dta); + return; + } + + copysource target; + // If more than one object exists and last target is not part of a + // concat sequence then make it the target. + if(sources.size()>1 && !sources[sources.size()-2].concat){ + target = sources.back(); + sources.pop_back(); + } + //If no target => default target with concat flag true to detect a+b+c + if(target.filename.size() == 0) target = copysource(defaulttarget,true); + + copysource oldsource; + copysource source; + uint32_t count = 0; + while(sources.size()) { + /* Get next source item and keep track of old source for concat start end */ + oldsource = source; + source = sources[0]; + sources.erase(sources.begin()); + + //Skip first file if doing a+b+c. Set target to first file + if(!oldsource.concat && source.concat && target.concat) { + target = source; + continue; + } + + /* Make a full path in the args */ + char pathSourcePre[DOS_PATHLENGTH], pathSource[DOS_PATHLENGTH+2]; + char pathTarget[DOS_PATHLENGTH]; + + if (!DOS_Canonicalize(const_cast(source.filename.c_str()),pathSourcePre)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + dos.dta(save_dta); + return; + } + strcpy(pathSource,pathSourcePre); + if (uselfn) sprintf(pathSource,"\"%s\"",pathSourcePre); + // cut search pattern + char* pos = strrchr_dbcs(pathSource,'\\'); + if (pos) *(pos+1) = 0; + + if (!DOS_Canonicalize(const_cast(target.filename.c_str()),pathTarget)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + dos.dta(save_dta); + return; + } + char* temp = strstr(pathTarget,"*.*"); + if(temp && (temp == pathTarget || temp[-1] == '\\')) *temp = 0;//strip off *.* from target + + // add '\\' if target is a directory + bool target_is_file = true; + if (pathTarget[strlen(pathTarget)-1]!='\\') { + if (DOS_FindFirst(pathTarget,0xffff & ~DOS_ATTR_VOLUME)) { + dta.GetResult(name,lname,size,hsize,date,time,attr); + if (attr & DOS_ATTR_DIRECTORY) { + strcat(pathTarget,"\\"); + target_is_file = false; + } + } + } else target_is_file = false; + + //Find first sourcefile + char sPath[DOS_PATHLENGTH]; + bool ret=DOS_GetSFNPath(source.filename.c_str(),sPath,false) && DOS_FindFirst(((strchr(sPath, ' ')&&sPath[0]!='"'?"\"":"")+std::string(sPath)+(strchr(sPath, ' ')&&sPath[strlen(sPath)-1]!='"'?"\"":"")).c_str(),0xffff & ~DOS_ATTR_VOLUME); + if (!ret) { + WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),source.filename.c_str()); + dos.dta(save_dta); + return; + } + + uint16_t sourceHandle,targetHandle = 0; + char nameTarget[DOS_PATHLENGTH]; + char nameSource[DOS_PATHLENGTH], nametmp[DOS_PATHLENGTH+2]; + + // Cache so we don't have to recalculate + size_t pathTargetLen = strlen(pathTarget); + + // See if we have to substitute filename or extension + char * ext = nullptr; + size_t replacementOffset = 0; + if (pathTarget[pathTargetLen-1]!='\\') { + // only if it's not a directory + ext = strchr(pathTarget, '.'); + if (ext > pathTarget) { // no possible substitution + if (ext[-1] == '*') { + // we substitute extension, save it, hide the name + ext[-1] = 0; + assert(ext > pathTarget + 1); // pathTarget is fully qualified + if (ext[-2] != '\\') { + // there is something before the asterisk + // save the offset in the source names + + replacementOffset = source.filename.find('*'); + size_t lastSlash = std::string::npos; + bool lead = false; + for (unsigned int i=0; i1&&(nameTarget[1]==':'||nameTarget[2]==':')?(toupper(nameTarget[nameTarget[0]=='"'?1:0])-'A'):-1; + if(drive >= 0 && Drives[drive]) { + uint16_t bytes_sector; uint8_t sectors_cluster; uint16_t total_clusters; uint16_t free_clusters; + uint32_t bytes32 = 0, sectors32 = 0, clusters32 = 0, free32 = 0; + bool no_free_space = true; + rsize = true; + freec = 0; + if(dos.version.major > 7 || (dos.version.major == 7 && dos.version.minor >= 10)) { + Drives[drive]->AllocationInfo32(&bytes32, §ors32, &clusters32, &free32); + no_free_space = (uint64_t)bytes32 * (uint64_t)sectors32 * (uint64_t)free32 < size ? true : false; + //LOG_MSG("drive=%u, no_free_space = %d bytes32=%u, sectors32=%u, free32 =%u, free_space=%u, size=%u", + // drive, no_free_space ? 1 : 0, bytes32, sectors32, free32, bytes32*sectors32*free32, size); + } + if(bytes32 == 0 || sectors32 == 0 || dos.version.major < 7 || (dos.version.major == 7 && dos.version.minor < 10)) { + Drives[drive]->AllocationInfo(&bytes_sector, §ors_cluster, &total_clusters, &free_clusters); + no_free_space = (Bitu)bytes_sector* (Bitu)sectors_cluster* (Bitu)(freec ? freec : free_clusters) < size ? true : false; + //LOG_MSG("no_free_space = %d bytes=%u, sectors=%u, free =%u, free_space=%u, size=%u", + // no_free_space ? 1 : 0, bytes_sector, sectors_cluster, freec, bytes_sector*sectors_cluster*free_clusters, size); + } + rsize = false; + if (no_free_space) { + WriteOut(MSG_Get("SHELL_CMD_COPY_NOSPACE"), uselfn?lname:name); + DOS_CloseFile(sourceHandle); + ret = DOS_FindNext(); + continue; + } + } + } + } + //Don't create a new file when in concat mode + if (oldsource.concat || DOS_CreateFile(nameTarget,0,&targetHandle)) { + uint32_t dummy=0; + + if (DOS_FindDevice(name) == DOS_DEVICES && !DOS_SetFileDate(targetHandle, ftime, fdate)) + LOG_MSG("WARNING: COPY unable to apply date/time to dest"); + + //In concat mode. Open the target and seek to the eof + if (!oldsource.concat || (DOS_OpenFile(nameTarget,OPEN_READWRITE,&targetHandle) && + DOS_SeekFile(targetHandle,&dummy,DOS_SEEK_END))) { + // Copy + static uint8_t buffer[0x8000]; // static, otherwise stack overflow possible. + bool failed = false; + uint16_t toread = 0x8000; + bool iscon=DOS_FindDevice(name)==DOS_FindDevice("con"); + if (iscon) dos.echo=true; + bool cont; + do { + if (!DOS_ReadFile(sourceHandle,buffer,&toread)) failed=true; + if (iscon) { + if (dos.errorcode==77) { + dos.dta(save_dta); + DOS_CloseFile(sourceHandle); + DOS_CloseFile(targetHandle); + if (!exist) DOS_UnlinkFile(nameTarget); + dos.echo=echo; + return; + } + cont=true; + for (int i=0;i0 && DOS_FindDevice(name) == DOS_DEVICES) DOS_SetFileDate(targetHandle, ftime, fdate); + #endif + if (!DOS_CloseFile(targetHandle)) failed=true; + if (failed) + WriteOut(MSG_Get("SHELL_CMD_COPY_ERROR"),uselfn?lname:name); + else if (strcmp(name,lname)&&uselfn) + WriteOut(" %s [%s]\n",lname,name); + else + WriteOut(" %s\n",uselfn?lname:name); + if(!source.concat && !special && !failed) count++; //Only count concat files once + } else { + DOS_CloseFile(sourceHandle); + printf("Fail1\n"); + WriteOut(MSG_Get("SHELL_CMD_COPY_FAILURE"),const_cast(target.filename.c_str())); + } + } else { + DOS_CloseFile(sourceHandle); + printf("Fail2\n"); + WriteOut(MSG_Get("SHELL_CMD_COPY_FAILURE"),const_cast(target.filename.c_str())); + } + } else + { + printf("Fail3\n"); + WriteOut(MSG_Get("SHELL_CMD_COPY_FAILURE"),const_cast(source.filename.c_str())); + } + } + //On to the next file if the previous one wasn't a device + if ((attr&DOS_ATTR_DEVICE) == 0) ret = DOS_FindNext(); + else ret = false; + } + } + + WriteOut(MSG_Get("SHELL_CMD_COPY_SUCCESS"),count); + dos.dta(save_dta); + dos.echo=echo; + Drives[DOS_GetDefaultDrive()]->EmptyCache(); + } + + static void skipspc(char* &pcheck) { + while (*pcheck != 0 && (*pcheck == ' ' || *pcheck == '\t')) pcheck++; + } + + static void readnonspcu(std::string &s,char* &pcheck) { + s.clear(); + while (*pcheck != 0 && !(*pcheck == ' ' || *pcheck == '\t')) s += toupper( *(pcheck++) ); + } + + static void readnonspc(std::string &s,char* &pcheck) { + s.clear(); + while (*pcheck != 0 && !(*pcheck == ' ' || *pcheck == '\t')) s += *(pcheck++); + } + + /* NTS: WARNING, this function modifies the buffer pointed to by char *args */ + void DOS_Shell::CMD_SET(char * args) { + HELP("SET"); + StripSpaces(args); + + enum op_mode_t { + show_all_env, + set_env, + show_env, + erase_env, + first_env + }; + + op_mode_t op_mode = show_all_env; + std::string env_name,env_value; + + const bool zdirpath = static_cast(control->GetSection("dos"))->Get_bool("drive z expand path"); + + { + std::string sw; + + /* parse arguments at the start */ + skipspc(args); + while (*args == '/') { + args++; /* skip / */ + readnonspcu(sw,args); + + if (sw == "P") { + WriteOut("Set /P is not supported. Use Choice!"); /* TODO: What is SET /P supposed to do? */ + return; + } + else if (sw == "ERASE") { /* DOSBox-X extension: Completely erase the environment block */ + op_mode = erase_env; + } + else if (sw == "FIRST") { /* DOSBox-X extension: Move the specified variable to the front of the environment block */ + op_mode = first_env; + } + else { + WriteOut("Unknown switch /"); + WriteOut(sw.c_str()); + WriteOut("\n"); + return; + } + + skipspc(args); + } + } + + if (op_mode == first_env) { + if (*args == 0) return; + readnonspc(env_name,args); + } + else if (op_mode == show_all_env) { + if (*args != 0) { + /* Most SET commands take the form NAME=VALUE */ + char *p = strchr(args,'='); + if (p == NULL) { + /* SET without assignment prints the variable instead */ + op_mode = show_env; + readnonspc(env_name,args); + } else { + /* ASCIIZ snip the args string in two, so that args is C-string name of the variable, + * and "p" is C-string value of the variable */ + op_mode = set_env; + *p++ = 0; env_name = args; env_value = p; + } + } + } + + switch (op_mode) { + case show_all_env: { + const Bitu count = GetEnvCount(); + std::string line; + + for (Bitu a = 0;a < count;a++) { + if (GetEnvNum(a,line)) + WriteOut("%s\n",line.c_str()); + } + break; } + case show_env: + if (GetEnvStr(env_name.c_str(),env_value)) + WriteOut("%s\n",env_value.c_str()); + else + WriteOut(MSG_Get("SHELL_CMD_SET_NOT_SET"),env_name.c_str()); + break; + case set_env: + if(zdirpath && !strcasecmp(env_name.c_str(), "path")) GetExpandedPath(env_value); + + /* No parsing is needed. The command interpreter does the variable substitution for us */ + /* NTS: If Win95 is any example, the command interpreter expands the variables for us */ + if (!SetEnv(env_name.c_str(),env_value.c_str())) + WriteOut(MSG_Get("SHELL_CMD_SET_OUT_OF_SPACE")); + + break; + case erase_env: + if (!EraseEnv()) + WriteOut("Unable to erase environment block\n"); + break; + case first_env: + if (!FirstEnv(env_name.c_str())) + WriteOut("Unable to move environment variable\n"); + break; + default: + abort(); + break; + } + } + + void DOS_Shell::CMD_IF(char * args) { + HELP("IF"); + StripSpaces(args,'='); + bool has_not=false; + + while (strncasecmp(args,"NOT",3) == 0) { + if (!isspace(*reinterpret_cast(&args[3])) && (args[3] != '=')) break; + args += 3; //skip text + //skip more spaces + StripSpaces(args,'='); + has_not = !has_not; + } + + if(strncasecmp(args,"ERRORLEVEL",10) == 0) { + args += 10; //skip text + //Strip spaces and == + StripSpaces(args,'='); + char* word = StripWord(args); + if(!isdigit(*word)) { + WriteOut(MSG_Get("SHELL_CMD_IF_ERRORLEVEL_MISSING_NUMBER")); + return; + } + + uint8_t n = 0; + do n = n * 10 + (*word - '0'); + while (isdigit(*++word)); + if(*word && !isspace(*word)) { + WriteOut(MSG_Get("SHELL_CMD_IF_ERRORLEVEL_INVALID_NUMBER")); + return; + } + /* Read the error code from DOS */ + if ((dos.return_code>=n) ==(!has_not)) DoCommand(args); + return; + } + + if(strncasecmp(args,"EXIST ",6) == 0) { + args += 6; //Skip text + StripSpaces(args); + char* word = StripArg(args); + if (!*word) { + WriteOut(MSG_Get("SHELL_CMD_IF_EXIST_MISSING_FILENAME")); + return; + } + + { /* DOS_FindFirst uses dta so set it to our internal dta */ + char spath[DOS_PATHLENGTH], path[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH], full[DOS_PATHLENGTH], *r; + if (!DOS_Canonicalize(word,full)) { + if (has_not) DoCommand(args); + return; + } + r=strrchr_dbcs(full, '\\'); + if (r!=NULL) { + *r=0; + strcpy(path, full); + strcat(path, "\\"); + strcpy(pattern, r+1); + *r='\\'; + } else { + strcpy(path, ""); + strcpy(pattern, full); + } + int k=0; + for (int i=0;i<(int)strlen(pattern);i++) + if (pattern[i]!='\"') + pattern[k++]=pattern[i]; + pattern[k]=0; + strcpy(spath, path); + if (strchr_dbcs(word,'\"')||uselfn) { + if (!DOS_GetSFNPath(("\""+std::string(path)+"\\").c_str(), spath, false)) strcpy(spath, path); + if (!strlen(spath)||spath[strlen(spath)-1]!='\\') strcat(spath, "\\"); + } + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + int fbak=lfn_filefind_handle; + lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; + std::string sfull=std::string(spath)+std::string(pattern); + bool ret=DOS_FindFirst(((uselfn&&sfull.length()&&sfull[0]!='"'?"\"":"")+sfull+(uselfn&&sfull.length()&&sfull[sfull.length()-1]!='"'?"\"":"")).c_str(),0xffff & ~(DOS_ATTR_VOLUME|DOS_ATTR_DIRECTORY)); + lfn_filefind_handle=fbak; + dos.dta(save_dta); + if (ret==(!has_not)) DoCommand(args); + } + return; + } + + /* Normal if string compare */ + + char* word1 = args; + // first word is until space or = + while (*args && !isspace(*reinterpret_cast(args)) && (*args != '=')) + args++; + char* end_word1 = args; + + // scan for = + while (*args && (*args != '=')) + args++; + // check for == + if ((*args==0) || (args[1] != '=')) { + SyntaxError(); + return; + } + args += 2; + StripSpaces(args,'='); + + char* word2 = args; + // second word is until space or = + while (*args && !isspace(*reinterpret_cast(args)) && (*args != '=')) + args++; + + if (*args) { + *end_word1 = 0; // mark end of first word + *args++ = 0; // mark end of second word + StripSpaces(args,'='); + + if ((strcmp(word1,word2)==0)==(!has_not)) DoCommand(args); + } + } + + void DOS_Shell::CMD_GOTO(char * args) { + HELP("GOTO"); + StripSpaces(args); + if (!bf) return; + if (*args==':') args++; + //label ends at the first space + char* non_space = args; + while (*non_space) { + if((*non_space == ' ') || (*non_space == '\t')) + *non_space = 0; + else non_space++; + } + if (!*args) { + WriteOut(MSG_Get("SHELL_CMD_GOTO_MISSING_LABEL")); + return; + } + if (!bf->Goto(args)) { + WriteOut(MSG_Get("SHELL_CMD_GOTO_LABEL_NOT_FOUND"),args); + return; + } + } + + void DOS_Shell::CMD_SHIFT(char * args ) { + HELP("SHIFT"); + if(bf) bf->Shift(); + } + + void DOS_Shell::CMD_TYPE(char * args) { + HELP("TYPE"); + + // ignore /p /h and /t for compatibility + ScanCMDBool(args,"P"); + ScanCMDBool(args,"H"); + ScanCMDBool(args,"T"); + StripSpaces(args); + if (strcasecmp(args,"nul")==0) return; + if (!*args) { + WriteOut(MSG_Get("SHELL_SYNTAXERROR")); + return; + } + uint16_t handle; + char * word; + bool lead = false; + int COLS = 80; + if (!IS_PC98_ARCH && outcon) COLS=real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + BIOS_NCOLS; + uint8_t page=outcon?real_readb(BIOSMEM_SEG,BIOSMEM_CURRENT_PAGE):0; + nextfile: + word=StripArg(args); + if (!DOS_OpenFile(word,0,&handle)) { + WriteOut(MSG_Get(dos.errorcode==DOSERR_ACCESS_DENIED?"SHELL_CMD_FILE_ACCESS_DENIED":(dos.errorcode==DOSERR_PATH_NOT_FOUND?"SHELL_ILLEGAL_PATH":"SHELL_CMD_FILE_NOT_FOUND")),word); + return; + } + ctrlbrk=false; + uint8_t c,last,last2,last3;uint16_t n=1; + last3=last2=last=0; + bool iscon=DOS_FindDevice(word)==DOS_FindDevice("con"); + while (n) { + DOS_ReadFile(handle,&c,&n); + if (outcon && !CURSOR_POS_COL(page)) last3=last2=last=0; + if (lead) lead=false; + else if ((IS_PC98_ARCH || isDBCSCP()) + #if defined(USE_TTF) + && dbcs_sbcs + #endif + ) lead = isKanji1(c) && !(TTF_using() + #if defined(USE_TTF) + && autoboxdraw + #endif + && CheckBoxDrawing(last3, last2, last, c)); + if (n==0 || c==0x1a) break; // stop at EOF + if (iscon) { + if (c==3) break; + else if (c==13) WriteOut("\r\n"); + } else if (CheckBreak(this)) break; + else if (outcon && lead && CURSOR_POS_COL(page) == COLS-1) WriteOut(" "); + DOS_WriteFile(STDOUT,&c,&n); + if (outcon) {last3=last2;last2=last;last=c;} + } + DOS_CloseFile(handle); + if (*args) goto nextfile; + } + + void DOS_Shell::CMD_REM(char * args) { + HELP("REM"); + } + + static char PAUSED(void) { + uint8_t c; uint16_t n=1, handle; + if (!usecon&&DOS_OpenFile("con", OPEN_READWRITE, &handle)) { + DOS_ReadFile (handle,&c,&n); + DOS_CloseFile(handle); + } else + DOS_ReadFile (STDIN,&c,&n); + return c; + } + + void DOS_Shell::CMD_MORE(char * args) { + HELP("MORE"); + //ScanCMDBool(args,">"); + int nchars = 0, nlines = 0, linecount = 0, LINES = 25, COLS = 80, TABSIZE = 8; + char * word; + uint8_t c,last,last2,last3; + last3=last2=last=0; + bool lead=false; + uint16_t n=1; + StripSpaces(args); + if (IS_PC98_ARCH) { + LINES=real_readb(0x60,0x113) & 0x01 ? 25 : 20; + COLS=80; + if (real_readb(0x60,0x111)) LINES--; // Function keys displayed + } else { + LINES=(IS_EGAVGA_ARCH?real_readb(BIOSMEM_SEG,BIOSMEM_NB_ROWS):24)+1; + COLS=real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + } + LINES--; + if(!*args||!strcasecmp(args, "con")) { + while (true) { + DOS_ReadFile (STDIN,&c,&n); + if (lead) lead=false; + else if ((IS_PC98_ARCH || isDBCSCP()) + #if defined(USE_TTF) + && dbcs_sbcs + #endif + ) lead = isKanji1(c) && !(TTF_using() + #if defined(USE_TTF) + && autoboxdraw + #endif + && CheckBoxDrawing(last3, last2, last, c)); + if (c==3) {dos.echo=echo;return;} + else if (n==0) {if (last!=10) WriteOut("\r\n");dos.echo=echo;return;} + else if (c==13&&last==26) {dos.echo=echo;return;} + else { + if (c==10); + else if (c==13) { + linecount++; + WriteOut("\r\n"); + last3=last2=last=0; + } else if (c=='\t') { + do { + WriteOut(" "); + nchars++; + } while ( nchars < COLS && nchars % TABSIZE ); + } else { + if (lead && nchars == COLS-1) { + last3=last2=last=0; + nlines++; + nchars = 0; + WriteOut("\n"); + if (nlines == LINES) { + WriteOut("-- More -- (%u) --",linecount); + if (PAUSED()==3) return; + WriteOut("\n"); + nlines=0; + } + } + nchars++; + WriteOut("%c", c); + } + if (c == 13 || nchars >= COLS) { + nlines++; + nchars = 0; + if (nlines == LINES) { + WriteOut("-- More -- (%u) --",linecount); + if (PAUSED()==3) return; + WriteOut("\n"); + nlines=0; + } + } + last3=last2;last2=last;last=c; + } + } + } + if (strcasecmp(args,"nul")==0) return; + if (!*args) { + WriteOut(MSG_Get("SHELL_SYNTAXERROR")); + return; + } + uint16_t handle; + nextfile: + word=StripArg(args); + if (!DOS_OpenFile(word,0,&handle)) { + WriteOut(MSG_Get(dos.errorcode==DOSERR_ACCESS_DENIED?"SHELL_CMD_FILE_ACCESS_DENIED":(dos.errorcode==DOSERR_PATH_NOT_FOUND?"SHELL_ILLEGAL_PATH":"SHELL_CMD_FILE_NOT_FOUND")),word); + return; + } + ctrlbrk=false; + lead=false; + last3=last2=last=0; + nlines=0; + do { + n=1; + DOS_ReadFile(handle,&c,&n); + if (lead) lead=false; + else if ((IS_PC98_ARCH || isDBCSCP()) + #if defined(USE_TTF) + && dbcs_sbcs + #endif + ) lead = isKanji1(c) && !(TTF_using() + #if defined(USE_TTF) + && autoboxdraw + #endif + && CheckBoxDrawing(last3, last2, last, c)); + if (lead && nchars == COLS-1) { + last3=last2=last=0; + nlines++; + nchars = 0; + WriteOut("\n"); + if (nlines == LINES && usecon) { + WriteOut("-- More -- %s (%u) --",word,linecount); + if (PAUSED()==3) {DOS_CloseFile(handle);return;} + WriteOut("\n"); + nlines=0; + } + } + DOS_WriteFile(STDOUT,&c,&n); + last3=last2;last2=last;last=c; + if (c != '\t') nchars++; + else do { + WriteOut(" "); + nchars++; + } while ( nchars < COLS && nchars % TABSIZE ); + + if (c == '\n') linecount++; + if (c == '\n' || nchars >= COLS) { + last3=last2=last=0; + nlines++; + nchars = 0; + if (!usecon) { + if (c != '\n') WriteOut("\n"); + } else if (nlines == LINES) { + WriteOut("-- More -- %s (%u) --",word,linecount); + if (PAUSED()==3) {DOS_CloseFile(handle);return;} + WriteOut("\n"); + nlines=0; + } + } + if (CheckBreak(this)) break; + } while (n); + DOS_CloseFile(handle); + if (*args) { + WriteOut("\n"); + if (usecon && PAUSED()==3) return; + goto nextfile; + } + } + + void DOS_Shell::CMD_PAUSE(char * args){ + HELP("PAUSE"); + if(args && *args) { + args++; + WriteOut("%s\n",args); // optional specified message + } else + WriteOut(MSG_Get("SHELL_CMD_PAUSE")); + uint8_t c;uint16_t n=1; + DOS_ReadFile(STDIN,&c,&n); + if (c==0) DOS_ReadFile(STDIN,&c,&n); // read extended key + } + + void DOS_Shell::CMD_CALL(char * args){ + HELP("CALL"); + this->call=true; /* else the old batchfile will be closed first */ + this->ParseLine(args); + this->call=false; + } + + void DOS_Shell::CMD_DATE(char * args) { + HELP("DATE"); + if(ScanCMDBool(args,"H")) { + // synchronize date with host parameter + time_t curtime; + struct tm *loctime; + curtime = time (NULL); + loctime = localtime (&curtime); + + reg_cx = loctime->tm_year+1900; + reg_dh = loctime->tm_mon+1; + reg_dl = loctime->tm_mday; + + reg_ah=0x2b; // set system date + CALLBACK_RunRealInt(0x21); + if (sync_time) {manualtime=false;mainMenu.get_item("sync_host_datetime").check(true).refresh_item(mainMenu);} + return; + } else if(ScanCMDBool(args,"S")) { + sync_time=true; + manualtime=false; + mainMenu.get_item("sync_host_datetime").check(true).refresh_item(mainMenu); + return; + } else if(ScanCMDBool(args,"F")) { + sync_time=false; + manualtime=false; + mainMenu.get_item("sync_host_datetime").check(false).refresh_item(mainMenu); + return; + } + // check if a date was passed in command line + char c=dos.tables.country[11], c1, c2; + uint32_t newday,newmonth,newyear; + int n=dos.tables.country[0]==1?sscanf(args,"%u%c%u%c%u",&newday,&c1,&newmonth,&c2,&newyear):(dos.tables.country[0]==2?sscanf(args,"%u%c%u%c%u",&newyear,&c1,&newmonth,&c2,&newday):sscanf(args,"%u%c%u%c%u",&newmonth,&c1,&newday,&c2,&newyear)); + if (n==5 && c1==c && c2==c) { + reg_cx = static_cast(newyear); + reg_dh = static_cast(newmonth); + reg_dl = static_cast(newday); + + reg_ah=0x2b; // set system date + CALLBACK_RunRealInt(0x21); + if(reg_al==0xff) WriteOut(MSG_Get("SHELL_CMD_DATE_ERROR")); + return; + } + // display the current date + reg_ah=0x2a; // get system date + CALLBACK_RunRealInt(0x21); + + const char* datestring = MSG_Get("SHELL_CMD_DATE_DAYS"); + uint32_t length; + char day[6] = {0}; + if(sscanf(datestring,"%u",&length) && (length<7) && (strlen(datestring)==((size_t)length*7+1))) { + // date string appears valid + for(uint32_t i = 0; i < length; i++) day[i] = datestring[reg_al*length+1+i]; + } + bool dateonly = ScanCMDBool(args,"T"); + if(!dateonly) WriteOut(MSG_Get("SHELL_CMD_DATE_NOW")); + if (!dateonly) WriteOut("%s ", day); + WriteOut("%s\n",FormatDate((uint16_t)reg_cx, (uint8_t)reg_dh, (uint8_t)reg_dl)); + if(!dateonly) { + char format[11]; + sprintf(format, dos.tables.country[0]==1?"DD%cMM%cYYYY":(dos.tables.country[0]==2?"YYYY%cMM%cDD":"MM%cDD%cYYYY"), c, c); + WriteOut(MSG_Get("SHELL_CMD_DATE_SETHLP"), format); + } + } + + void DOS_Shell::CMD_TIME(char * args) { + HELP("TIME"); + if(ScanCMDBool(args,"H")) { + // synchronize time with host parameter + time_t curtime; + struct tm *loctime; + curtime = time (NULL); + loctime = localtime (&curtime); + + //reg_cx = loctime->; + //reg_dh = loctime->; + //reg_dl = loctime->; + + // reg_ah=0x2d; // set system time TODO + // CALLBACK_RunRealInt(0x21); + + uint32_t ticks=(uint32_t)(((double)(loctime->tm_hour*3600+ + loctime->tm_min*60+ + loctime->tm_sec))*18.206481481); + mem_writed(BIOS_TIMER,ticks); + if (sync_time) {manualtime=false;mainMenu.get_item("sync_host_datetime").check(true).refresh_item(mainMenu);} + return; + } + uint32_t newhour,newminute,newsecond; + char c=dos.tables.country[13], c1, c2; + if (sscanf(args,"%u%c%u%c%u",&newhour,&c1,&newminute,&c2,&newsecond)==5 && c1==c && c2==c) { + reg_ch = static_cast(newhour); + reg_cl = static_cast(newminute); + reg_dx = static_cast(newsecond)<<8; + + reg_ah=0x2d; // set system time + CALLBACK_RunRealInt(0x21); + if(reg_al==0xff) WriteOut(MSG_Get("SHELL_CMD_TIME_ERROR")); + return; + } + bool timeonly = ScanCMDBool(args,"T"); + + reg_ah=0x2c; // get system time + CALLBACK_RunRealInt(0x21); + /* + reg_dl= // 1/100 seconds + reg_dh= // seconds + reg_cl= // minutes + reg_ch= // hours */ - HELP("SUBST"); - try { - char mountstring[DOS_PATHLENGTH+CROSS_LEN+20]; - strcpy(mountstring,"MOUNT "); - StripSpaces(args); - std::string arg; - CommandLine command(nullptr, args); - if (!command.GetCount()) { - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; - uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; - /* Command uses dta so set it to our internal dta */ - RealPt save_dta = dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - - WriteOut(MSG_Get("SHELL_CMD_SUBST_DRIVE_LIST")); - WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_FORMAT"),"Drive","Type","Label"); - int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); - if (!cols) cols=80; - for(int p = 0;p < cols;p++) WriteOut("-"); - bool none=true; - for (int d = 0;d < DOS_DRIVES;d++) { - if (!Drives[d]||strncmp(Drives[d]->GetInfo(),"local ",6)) continue; - - char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; - bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); - if (ret) { - dta.GetResult(name,lname,size,hsize,date,time,attr); - DOS_FindNext(); //Mark entry as invalid - } else name[0] = 0; - - /* Change 8.3 to 11.0 */ - const char* dot = strchr(name, '.'); - if(dot && (dot - name == 8) ) { - name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; - } - - root[1] = 0; //This way, the format string can be reused. - WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name); - none=false; - } - if (none) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); - dos.dta(save_dta); - return; - } - - if (command.GetCount() != 2) throw 0 ; - - command.FindCommand(1,arg); - if( (arg.size()>1) && arg[1] !=':') throw(0); - char temp_str[2] = { 0,0 }; - temp_str[0]=(char)toupper(args[0]); - command.FindCommand(2,arg); - if((arg=="/D") || (arg=="/d")) { - if(!Drives[temp_str[0]-'A'] ) throw 1; //targetdrive not in use - strcat(mountstring,"-u "); - strcat(mountstring,temp_str); - this->ParseLine(mountstring); - return; - } - if(Drives[temp_str[0]-'A'] ) throw 2; //targetdrive in use - strcat(mountstring,temp_str); - strcat(mountstring," "); - - uint8_t drive;char dir[DOS_PATHLENGTH+2],fulldir[DOS_PATHLENGTH]; - if (strchr(arg.c_str(),'\"')==NULL) - sprintf(dir,"\"%s\"",arg.c_str()); - else strcpy(dir,arg.c_str()); - if (!DOS_MakeName(dir,fulldir,&drive)) throw 3; - - localDrive * const ldp = dynamic_cast(Drives[drive]); - if (!ldp) throw 4; - char newname[CROSS_LEN]; - strcpy(newname, ldp->basedir); - strcat(newname,fulldir); - CROSS_FILENAME(newname); - ldp->dirCache.ExpandName(newname); - strcat(mountstring,"\""); - strcat(mountstring, newname); - strcat(mountstring,"\""); - this->ParseLine(mountstring); - } - catch(int a){ - switch (a) { - case 1: - WriteOut(MSG_Get("SHELL_CMD_SUBST_NO_REMOVE")); - break; - case 2: - WriteOut(MSG_Get("SHELL_CMD_SUBST_IN_USE")); - break; - case 3: - WriteOut(MSG_Get("SHELL_CMD_SUBST_INVALID_PATH")); - break; - case 4: - WriteOut(MSG_Get("SHELL_CMD_SUBST_NOT_LOCAL")); - break; - default: - WriteOut(MSG_Get("SHELL_CMD_SUBST_FAILURE")); - } - return; - } - catch(...) { //dynamic cast failed =>so no localdrive - WriteOut(MSG_Get("SHELL_CMD_SUBST_FAILURE")); - return; - } + if(timeonly) { + WriteOut("%u%c%02u%c%02u\n",reg_ch,dos.tables.country[13],reg_cl,dos.tables.country[13],reg_dh); + } else { + WriteOut(MSG_Get("SHELL_CMD_TIME_NOW")); + WriteOut("%s\n", FormatTime(reg_ch,reg_cl,reg_dh,reg_dl)); + char format[9]; + sprintf(format, "hh%cmm%css", dos.tables.country[13], dos.tables.country[13]); + WriteOut(MSG_Get("SHELL_CMD_TIME_SETHLP"), format); + } + } + + void DOS_Shell::CMD_SUBST(char * args) { + /* If more that one type can be substed think of something else + * E.g. make basedir member dos_drive instead of localdrive + */ + HELP("SUBST"); + try { + char mountstring[DOS_PATHLENGTH+CROSS_LEN+20]; + strcpy(mountstring,"MOUNT "); + StripSpaces(args); + std::string arg; + CommandLine command(nullptr, args); + if (!command.GetCount()) { + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH]; + uint32_t size,hsize;uint16_t date;uint16_t time;uint8_t attr; + /* Command uses dta so set it to our internal dta */ + RealPt save_dta = dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + + WriteOut(MSG_Get("SHELL_CMD_SUBST_DRIVE_LIST")); + WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_FORMAT"),"Drive","Type","Label"); + int cols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); + if (!cols) cols=80; + for(int p = 0;p < cols;p++) WriteOut("-"); + bool none=true; + for (int d = 0;d < DOS_DRIVES;d++) { + if (!Drives[d]||strncmp(Drives[d]->GetInfo(),"local ",6)) continue; + + char root[7] = {(char)('A'+d),':','\\','*','.','*',0}; + bool ret = DOS_FindFirst(root,DOS_ATTR_VOLUME); + if (ret) { + dta.GetResult(name,lname,size,hsize,date,time,attr); + DOS_FindNext(); //Mark entry as invalid + } else name[0] = 0; + + /* Change 8.3 to 11.0 */ + const char* dot = strchr(name, '.'); + if(dot && (dot - name == 8) ) { + name[8] = name[9];name[9] = name[10];name[10] = name[11];name[11] = 0; + } + + root[1] = 0; //This way, the format string can be reused. + WriteOut(MSG_Get("PROGRAM_MOUNT_STATUS_FORMAT"),root, Drives[d]->GetInfo(),name); + none=false; + } + if (none) WriteOut(MSG_Get("PROGRAM_IMGMOUNT_STATUS_NONE")); + dos.dta(save_dta); + return; + } + + if (command.GetCount() != 2) throw 0 ; - return; -} - -void DOS_Shell::CMD_LOADHIGH(char *args){ - HELP("LOADHIGH"); - uint16_t umb_start=dos_infoblock.GetStartOfUMBChain(); - uint8_t umb_flag=dos_infoblock.GetUMBChainState(); - uint8_t old_memstrat=(uint8_t)(DOS_GetMemAllocStrategy()&0xff); - if (umb_start==0x9fff) { - if ((umb_flag&1)==0) DOS_LinkUMBsToMemChain(1); - DOS_SetMemAllocStrategy(0x80); // search in UMBs first - this->ParseLine(args); - uint8_t current_umb_flag=dos_infoblock.GetUMBChainState(); - if ((current_umb_flag&1)!=(umb_flag&1)) DOS_LinkUMBsToMemChain(umb_flag); - DOS_SetMemAllocStrategy(old_memstrat); // restore strategy - } else this->ParseLine(args); -} - -bool get_param(char *&args, char *&rem, char *&temp, char &wait_char, int &wait_sec) -{ - const char *last = strchr(args, 0); - StripSpaces(args); - temp = ScanCMDRemain(args); - const bool optC = temp && tolower(temp[1]) == 'c'; - const bool optT = temp && tolower(temp[1]) == 't'; - if (temp && *temp && !optC && !optT) - return false; - if (temp) { - if (args == temp) - args = strchr(temp, 0) + 1; - temp += 2; - if (temp[0] == ':') - temp++; - } - if (optC) { - rem = temp; - } else if (optT) { - if (temp && *temp && *(temp + 1) == ',') { - wait_char = *temp; - wait_sec = atoi(temp + 2); - } else - wait_sec = 0; - } - if (args > last) - args = NULL; - if (args) args = trim(args); - return true; -} - -void DOS_Shell::CMD_CHOICE(char * args){ - HELP("CHOICE"); - static char defchoice[3] = {MSG_Get("INT21_6523_YESNO_CHARS")[0],MSG_Get("INT21_6523_YESNO_CHARS")[1],0}; - //char *rem1 = NULL, *rem2 = NULL; /* unused */ - char *rem = NULL, *temp = NULL, waitchar = 0, *ptr; - int waitsec = 0; - //bool optC = false, optT = false; /* unused */ - bool optN = ScanCMDBool(args,"N"); - bool optS = ScanCMDBool(args,"S"); //Case-sensitive matching - // ignore /b and /m switches for compatibility - ScanCMDBool(args,"B"); - ScanCMDBool(args,"M"); // Text - ScanCMDBool(args,"T"); //Default Choice after timeout - - while (args && *trim(args) == '/') { - if (!get_param(args, rem, temp, waitchar, waitsec)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), temp); - return; - } - } - if (!rem || !*rem) rem = defchoice; /* No choices specified use (national) YN */ - ptr = rem; - uint8_t c; - if(!optS) while ((c = (uint8_t)(*ptr))) *ptr++ = (char)toupper(c); /* When in no case-sensitive mode. make everything upcase */ - if(args && *args ) { - StripSpaces(args); - size_t argslen = strlen(args); - if(argslen>1 && args[0] == '"' && args[argslen-1] =='"') { - args[argslen-1] = 0; //Remove quotes - args++; - } - WriteOut(args); - } - /* Show question prompt of the form [a,b]? where a b are the choice values */ - if (!optN) { - if(args && *args) WriteOut(" "); - WriteOut("["); - size_t len = strlen(rem); - for(size_t t = 1; t < len; t++) { - WriteOut("%c,",rem[t-1]); - } - WriteOut("%c]?",rem[len-1]); - } - - // TO-DO: Find out how real DOS handles /T option for making a choice after delay; use AUTOTYPE for now - std::vector sequence; - bool in_char = optS ? (strchr(rem, waitchar) != nullptr) : (strchr(rem, toupper(waitchar)) || strchr(rem, tolower(waitchar))); - if (waitchar && *rem && in_char && waitsec > 0) { - sequence.emplace_back(std::string(1, optS?waitchar:tolower(waitchar))); - MAPPER_AutoType(sequence, waitsec * 1000, 500, true); - } - uint16_t n=1; - do { - dotype = true; - DOS_ReadFile (STDIN,&c,&n); - dotype = false; - if (n==0) {dos.return_code=255;return;} - if (CheckBreak(this) || c==3) {dos.return_code=0;return;} - } while (!c || !(ptr = strchr(rem,(optS?c:toupper(c))))); - c = optS?c:(uint8_t)toupper(c); - DOS_WriteFile (STDOUT,&c, &n); - c = '\r'; DOS_WriteFile (STDOUT,&c, &n); - c = '\n'; DOS_WriteFile (STDOUT,&c, &n); - dos.return_code = (uint8_t)(ptr-rem+1); -} - -static bool doAttrib(DOS_Shell * shell, char * args, DOS_DTA dta, bool optS, bool adda, bool adds, bool addh, bool addr, bool suba, bool subs, bool subh, bool subr) { - char spath[DOS_PATHLENGTH],sargs[DOS_PATHLENGTH+4],path[DOS_PATHLENGTH+4],full[DOS_PATHLENGTH],sfull[DOS_PATHLENGTH+2]; - if (!DOS_Canonicalize(args,full)||strrchr_dbcs(full,'\\')==NULL) { - shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); - if (!optS) ctrlbrk=true; - return false; - } - if (!DOS_GetSFNPath(args,spath,false)) { - shell->WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); - if (!optS) ctrlbrk=true; - return false; - } - if (!uselfn||!DOS_GetSFNPath(args,sfull,true)) strcpy(sfull,full); - sprintf(sargs,"\"%s\"",spath); - bool found=false, res=DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); - if (!res&&!optS) return false; - //end can't be 0, but if it is we'll get a nice crash, who cares :) - strcpy(path,full); - *(strrchr_dbcs(path,'\\')+1)=0; - char * end=strrchr_dbcs(full,'\\')+1;*end=0; - char * lend=strrchr_dbcs(sfull,'\\')+1;*lend=0; - char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH+1]; - uint32_t size,hsize;uint16_t time,date;uint8_t attr;uint16_t fattr; - while (res) { - if (CheckBreak(shell)) {ctrlbrk=true;return false;} - dta.GetResult(name,lname,size,hsize,date,time,attr); - if (!((!strcmp(name, ".") || !strcmp(name, "..") || strchr(sargs, '*')!=NULL || strchr(sargs, '?')!=NULL) && attr & DOS_ATTR_DIRECTORY)) { - found=true; - strcpy(end,name); - strcpy(lend,lname); - if (strlen(full)&&DOS_GetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), &fattr)) { - bool attra=fattr&DOS_ATTR_ARCHIVE, attrs=fattr&DOS_ATTR_SYSTEM, attrh=fattr&DOS_ATTR_HIDDEN, attrr=fattr&DOS_ATTR_READ_ONLY; - if (adda||adds||addh||addr||suba||subs||subh||subr) { - if (adda) fattr|=DOS_ATTR_ARCHIVE; - if (adds) fattr|=DOS_ATTR_SYSTEM; - if (addh) fattr|=DOS_ATTR_HIDDEN; - if (addr) fattr|=DOS_ATTR_READ_ONLY; - if (suba) fattr&=~DOS_ATTR_ARCHIVE; - if (subs) fattr&=~DOS_ATTR_SYSTEM; - if (subh) fattr&=~DOS_ATTR_HIDDEN; - if (subr) fattr&=~DOS_ATTR_READ_ONLY; - if (DOS_SetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), fattr)) { - if (DOS_GetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), &fattr)) { - shell->WriteOut(" %c %c%c%c ", fattr&DOS_ATTR_ARCHIVE?'A':' ', fattr&DOS_ATTR_SYSTEM?'S':' ', fattr&DOS_ATTR_HIDDEN?'H':' ', fattr&DOS_ATTR_READ_ONLY?'R':' '); - shell->WriteOut_NoParsing(uselfn?sfull:full, true); - shell->WriteOut("\n"); - } - } else - shell->WriteOut(MSG_Get("SHELL_CMD_ATTRIB_SET_ERROR"),uselfn?sfull:full); - } else { - shell->WriteOut(" %c %c%c%c ", attra?'A':' ', attrs?'S':' ', attrh?'H':' ', attrr?'R':' '); - shell->WriteOut_NoParsing(uselfn?sfull:full, true); - shell->WriteOut("\n"); - } - } else - shell->WriteOut(MSG_Get("SHELL_CMD_ATTRIB_GET_ERROR"),uselfn?sfull:full); - } - res=DOS_FindNext(); - } - if (optS) { - size_t len=strlen(path); - strcat(path, "*.*"); - bool ret=DOS_FindFirst(path,0xffff & ~DOS_ATTR_VOLUME); - *(path+len)=0; - if (ret) { - std::vector cdirs; - cdirs.clear(); - do { /* File name and extension */ - DtaResult result; - dta.GetResult(result.name,result.lname,result.size,result.hsize,result.date,result.time,result.attr); - - if((result.attr&DOS_ATTR_DIRECTORY) && strcmp(result.name, ".")&&strcmp(result.name, "..")) { - strcat(path, result.name); - strcat(path, "\\"); - char *fname = strrchr_dbcs(args, '\\'); - if (fname!=NULL) fname++; - else { - fname = strrchr(args, ':'); - if (fname!=NULL) fname++; - else fname=args; - } - strcat(path, fname); - cdirs.push_back((path[0]!='"'&&path[strlen(path)-1]=='"'?"\"":"")+std::string(path)); - *(path+len)=0; - } - } while ( (ret=DOS_FindNext()) ); - adirs.insert(adirs.begin()+1, cdirs.begin(), cdirs.end()); - } - } - return found; -} - -void DOS_Shell::CMD_ATTRIB(char *args){ - HELP("ATTRIB"); - StripSpaces(args); - - bool optS=ScanCMDBool(args,"S"); - char * rem=ScanCMDRemain(args); - if (rem) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); - return; - } - - bool adda=false, adds=false, addh=false, addr=false, suba=false, subs=false, subh=false, subr=false; - char sfull[DOS_PATHLENGTH+2]; - char* arg1; - strcpy(sfull, "*.*"); - do { - arg1=StripArg(args); - if (!strcasecmp(arg1, "+A")) adda=true; - else if (!strcasecmp(arg1, "+S")) adds=true; - else if (!strcasecmp(arg1, "+H")) addh=true; - else if (!strcasecmp(arg1, "+R")) addr=true; - else if (!strcasecmp(arg1, "-A")) suba=true; - else if (!strcasecmp(arg1, "-S")) subs=true; - else if (!strcasecmp(arg1, "-H")) subh=true; - else if (!strcasecmp(arg1, "-R")) subr=true; - else if (*arg1) { - strcpy(sfull, arg1); - if (uselfn&&strchr(sfull, '*')) { - char * find_last; - find_last=strrchr_dbcs(sfull,'\\'); - if (find_last==NULL) find_last=sfull; - else find_last++; - if (sfull[strlen(sfull)-1]=='*'&&strchr(find_last, '.')==NULL) strcat(sfull, ".*"); - } - } - } while (*args); - - char buffer[CROSS_LEN]; - args = ExpandDot(sfull,buffer, CROSS_LEN, false); - StripSpaces(args); - RealPt save_dta=dos.dta(); - dos.dta(dos.tables.tempdta); - DOS_DTA dta(dos.dta()); - adirs.clear(); - adirs.emplace_back(std::string(args)); - bool found=false; - inshell=true; - while (!adirs.empty()) { - ctrlbrk=false; - if (doAttrib(this, (char *)adirs.begin()->c_str(), dta, optS, adda, adds, addh, addr, suba, subs, subh, subr)) - found=true; - else if (ctrlbrk) - break; - adirs.erase(adirs.begin()); - } - if (!found&&!ctrlbrk) WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); - inshell=false; - ctrlbrk=false; - dos.dta(save_dta); -} - -void DOS_Shell::CMD_PROMPT(char *args){ - HELP("PROMPT"); - if(args && *args) { - args++; - SetEnv("PROMPT",args); - } else - SetEnv("PROMPT","$P$G"); - return; -} - -void DOS_Shell::CMD_PATH(char *args){ - HELP("PATH"); - if(args && *args){ - char pathstring[DOS_PATHLENGTH+CROSS_LEN+20]={ 0 }; - strcpy(pathstring,"set PATH="); - while(args && (*args=='='|| *args==' ')) - args++; - if (strlen(args) == 1 && *args == ';') - *args = 0; - if (args) { - std::string vstr = args; - bool zdirpath = static_cast(control->GetSection("dos"))->Get_bool("drive z expand path"); - if (zdirpath) GetExpandedPath(vstr); - strcat(pathstring,vstr.c_str()); - } - this->ParseLine(pathstring); - return; - } else { - std::string line; - if(GetEnvStr("PATH",line)) { - WriteOut("%s\n",line.c_str()); - } else { - WriteOut("PATH=(null)\n"); - } - } -} - -void DOS_Shell::CMD_VERIFY(char * args) { - HELP("VERIFY"); - args = trim(args); - if (!*args) - WriteOut("VERIFY is %s\n", dos.verify ? "on" : "off"); - else if (!strcasecmp(args, "OFF")) - dos.verify = false; - else if (!strcasecmp(args, "ON")) - dos.verify = true; - else - WriteOut("Must specify ON or OFF\n"); -} - -void dos_ver_menu(bool start); -bool set_ver(char *s); -void DOS_Shell::CMD_VER(char *args) { - HELP("VER"); - bool optR=ScanCMDBool(args,"R"); - if (char* rem = ScanCMDRemain(args)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), rem); - return; - } - if(!optR && args && *args) { - char* word = StripWord(args); - if(strcasecmp(word,"set")) { - if (*word=='=') word=trim(word+1); - if (isdigit(*word)) { - if (*args) { - WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), args); - return; - } - if (set_ver(word)) - dos_ver_menu(false); - else - WriteOut(MSG_Get("SHELL_CMD_VER_INVALID")); - return; - } - if (*word) { - WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), word); - return; - } - } - if (!*args) { - dos.version.major = 5; - dos.version.minor = 0; - } else if (!set_ver(args)) { - WriteOut(MSG_Get("SHELL_CMD_VER_INVALID")); - return; - } - dos_ver_menu(false); - } else { - WriteOut(MSG_Get("SHELL_CMD_VER_VER"),VERSION,SDL_STRING,dos.version.major,dos.version.minor); - if (optR) WriteOut("DOSBox-X Git commit %s, built on %s\nPlatform: %s %d-bit", GIT_COMMIT_HASH, UPDATED_STR, OS_PLATFORM_LONG, OS_BIT_INT); - } -} - -void DOS_Shell::CMD_VOL(char *args){ - HELP("VOL"); - uint8_t drive=DOS_GetDefaultDrive(); - if(args && *args){ - args++; - uint32_t argLen = (uint32_t)strlen(args); - switch (args[argLen-1]) { - case ':' : - if(!strcasecmp(args,":")) return; - int drive2; drive2= toupper(*reinterpret_cast(&args[0])); - char * c; c = strchr(args,':'); *c = '\0'; - if (Drives[drive2-'A']) drive = drive2 - 'A'; - else { - WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); - return; - } - break; - default: - WriteOut(MSG_Get("SHELL_SYNTAXERROR")); - return; - } - } - char const* bufin = Drives[drive]->GetLabel(); - if (tree) - WriteOut(MSG_Get("SHELL_CMD_VOL_TREE"),bufin); - else { - WriteOut(MSG_Get("SHELL_CMD_VOL_DRIVE"),drive+'A'); - - //if((drive+'A')=='Z') bufin="DOSBOX-X"; - if(strcasecmp(bufin,"")==0) - WriteOut(MSG_Get("SHELL_CMD_VOL_SERIAL_NOLABEL")); - else - WriteOut(MSG_Get("SHELL_CMD_VOL_SERIAL_LABEL"),bufin); - } - - WriteOut(tree?MSG_Get("SHELL_CMD_VOL_SERIAL")+1:MSG_Get("SHELL_CMD_VOL_SERIAL")); - unsigned long serial_number=0x1234; - if (!strncmp(Drives[drive]->GetInfo(),"fatDrive ",9)) { - fatDrive* fdp = dynamic_cast(Drives[drive]); - if (fdp != NULL) serial_number=fdp->GetSerial(); - } -#if defined (WIN32) - if (!strncmp(Drives[drive]->GetInfo(),"local ",6) || !strncmp(Drives[drive]->GetInfo(),"CDRom ",6)) { - localDrive* ldp = !strncmp(Drives[drive]->GetInfo(),"local ",6)?dynamic_cast(Drives[drive]):dynamic_cast(Drives[drive]); - if (ldp != NULL) serial_number=ldp->GetSerial(); - } -#endif - WriteOut("%04X-%04X\n", serial_number/0x10000, serial_number%0x10000); - return; -} - -void DOS_Shell::CMD_TRUENAME(char * args) { - HELP("TRUENAME"); - bool optH=ScanCMDBool(args,"H"); - args = trim(args); - if (!*args) { - WriteOut("No file name given.\n"); - return; - } - if (char* rem = ScanCMDRemain(args)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), rem); - return; - } - char *name = StripArg(args), fullname[DOS_PATHLENGTH]; - uint8_t drive; - if (DOS_MakeName(name, fullname, &drive)) { - if (optH) { - if (!strncmp(Drives[drive]->GetInfo(),"local ",6) || !strncmp(Drives[drive]->GetInfo(),"CDRom ",6)) { - localDrive *ldp = dynamic_cast(Drives[drive]); - Overlay_Drive *odp = dynamic_cast(Drives[drive]); - std::string hostname = ""; - if (odp) hostname = odp->GetHostName(fullname); - else if (ldp) hostname = ldp->GetHostName(fullname); - if (hostname.size()) { - WriteOut_NoParsing(hostname.c_str(), true); - WriteOut("\n"); - } - } - } else -#if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) - if (Network_IsNetworkResource(fullname)) { - WriteOut_NoParsing(name, true); - WriteOut("\r\n"); - } else -#endif - { - WriteOut("%c:\\", drive+'A'); - WriteOut_NoParsing(fullname, true); - WriteOut("\r\n"); - } - } - else - WriteOut(dos.errorcode==DOSERR_PATH_NOT_FOUND?"Path not found\n":"File not found\n"); -} - -void SetVal(const std::string& secname, const std::string& preval, const std::string& val); -static void delayed_press(Bitu key) { KEYBOARD_AddKey((KBD_KEYS)key,true); } -static void delayed_release(Bitu key) { KEYBOARD_AddKey((KBD_KEYS)key,false); } -static void delayed_sdlpress(Bitu core) { - if(core==1) SetVal("cpu","core","normal"); - else if(core==2) SetVal("cpu","core","simple"); - else if(core==3) SetVal("cpu","core","dynamic"); - else if(core==4) SetVal("cpu","core","full"); -} -// ADDKEY patch was created by Moe -void DOS_Shell::CMD_ADDKEY(char * args){ - //HELP("ADDKEY"); - StripSpaces(args); - if (!*args) { - WriteOut(MSG_Get("SHELL_SYNTAXERROR")); - return; - } - pic_tickindex_t delay = 0; - int duration = 0, core = 0; - - while (*args) { - char *word=StripWord(args); - KBD_KEYS scankey = (KBD_KEYS)0; - char *tail; - bool alt = false, ctrl = false, shift = false; - while (word[1] == '-') { - switch (word[0]) { - case 'c': - ctrl = true; - word += 2; - break; - case 's': - shift = true; - word += 2; - break; - case 'a': - alt = true; - word += 2; - break; - default: - WriteOut(MSG_Get("SHELL_SYNTAXERROR")); - return; - } - } - if (!strcasecmp(word,"enter")) { - word[0] = (char)10; - word[1] = (char)0; - } else if (!strcasecmp(word,"space")) { - word[0] = (char)32; - word[1] = (char)0; - } else if (!strcasecmp(word,"bs")) { - word[0] = (char)8; - word[1] = (char)0; - } else if (!strcasecmp(word,"tab")) { - word[0] = (char)9; - word[1] = (char)0; - } else if (!strcasecmp(word,"escape")) { - word[0] = (char)27; - word[1] = (char)0; - } else if (!strcasecmp(word,"up")) { - word[0] = (char)141; - word[1] = (char)0; - } else if (!strcasecmp(word,"down")) { - word[0] = (char)142; - word[1] = (char)0; - } else if (!strcasecmp(word,"left")) { - word[0] = (char)143; - word[1] = (char)0; - } else if (!strcasecmp(word,"right")) { - word[0] = (char)144; - word[1] = (char)0; - } else if (!strcasecmp(word,"ins")) { - word[0] = (char)145; - word[1] = (char)0; - } else if (!strcasecmp(word,"del")) { - word[0] = (char)146; - word[1] = (char)0; - } else if (!strcasecmp(word,"home")) { - word[0] = (char)147; - word[1] = (char)0; - } else if (!strcasecmp(word,"end")) { - word[0] = (char)148; - word[1] = (char)0; - } else if (!strcasecmp(word,"pgup")) { - word[0] = (char)149; - word[1] = (char)0; - } else if (!strcasecmp(word,"pgdown")) { - word[0] = (char)150; - word[1] = (char)0; - } else if (!strcasecmp(word,"normal")) { - core = 1; - } else if (!strcasecmp(word,"simple")) { - core = 2; - } else if (!strcasecmp(word,"dynamic")) { - core = 3; - } else if (!strcasecmp(word,"full")) { - core = 4; - } else if (word[0] == 'k' && word[1] == 'p' && word[2] && !word[3]) { - word[0] = 151+word[2]-'0'; - word[1] = 0; - } else if (word[0] == 'f' && word[1]) { - word[0] = 128+word[1]-'0'; - if (word[1] == '1' && word[2]) word[0] = 128+word[2]-'0'+10; - word[1] = 0; - } - if (!word[1]) { - const int shiftflag = 0x1000000; - const int map[256] = { - 0,0,0,0,0,0,0,0, - KBD_backspace, - KBD_tab, - KBD_enter, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - KBD_esc, - 0,0,0,0, - KBD_space, KBD_1|shiftflag, KBD_quote|shiftflag, KBD_3|shiftflag, KBD_4|shiftflag, KBD_5|shiftflag, KBD_7|shiftflag, KBD_quote, - KBD_9|shiftflag, KBD_0|shiftflag, KBD_8|shiftflag, KBD_equals|shiftflag, KBD_comma, KBD_minus, KBD_period, KBD_slash, - KBD_0, KBD_1, KBD_2, KBD_3, KBD_4, KBD_5, KBD_6, KBD_7, - KBD_8, KBD_9, KBD_semicolon|shiftflag, KBD_semicolon, KBD_comma|shiftflag, KBD_equals, KBD_period|shiftflag, KBD_slash|shiftflag, - KBD_2|shiftflag, KBD_a|shiftflag, KBD_b|shiftflag, KBD_c|shiftflag, KBD_d|shiftflag, KBD_e|shiftflag, KBD_f|shiftflag, KBD_g|shiftflag, - KBD_h|shiftflag, KBD_i|shiftflag, KBD_j|shiftflag, KBD_k|shiftflag, KBD_l|shiftflag, KBD_m|shiftflag, KBD_n|shiftflag, KBD_o|shiftflag, - KBD_p|shiftflag, KBD_q|shiftflag, KBD_r|shiftflag, KBD_s|shiftflag, KBD_t|shiftflag, KBD_u|shiftflag, KBD_v|shiftflag, KBD_w|shiftflag, - KBD_x|shiftflag, KBD_y|shiftflag, KBD_z|shiftflag, KBD_leftbracket, KBD_backslash, KBD_rightbracket, KBD_6|shiftflag, KBD_minus|shiftflag, - KBD_grave, KBD_a, KBD_b, KBD_c, KBD_d, KBD_e, KBD_f, KBD_g, - KBD_h, KBD_i, KBD_j, KBD_k, KBD_l, KBD_m, KBD_n, KBD_o, - KBD_p, KBD_q, KBD_r, KBD_s, KBD_t, KBD_u, KBD_v, KBD_w, - KBD_x, KBD_y, KBD_z, KBD_leftbracket|shiftflag, KBD_backslash|shiftflag, KBD_rightbracket|shiftflag, KBD_grave|shiftflag, 0, - 0, KBD_f1, KBD_f2, KBD_f3, KBD_f4, KBD_f5, KBD_f6, KBD_f7, KBD_f8, KBD_f9, KBD_f10, KBD_f11, KBD_f12, - KBD_up, KBD_down, KBD_left, KBD_right, KBD_insert, KBD_delete, KBD_home, KBD_end, KBD_pageup, KBD_pagedown, - KBD_kp0, KBD_kp1, KBD_kp2, KBD_kp3, KBD_kp4, KBD_kp5, KBD_kp6, KBD_kp7, KBD_kp8, KBD_kp9, - }; - scankey = (KBD_KEYS)(map[(unsigned char)word[0]] & ~shiftflag); - if (map[(unsigned char)word[0]] & shiftflag) shift = true; - if (!scankey && core == 0) { - WriteOut(MSG_Get("SHELL_SYNTAXERROR"),word); - return; - } - if (core == 0) word[0] = 0; - } - if (word[0] == 'p') { - delay += strtol(word+1,&tail,0); - if (tail && *tail) { - WriteOut(MSG_Get("SHELL_SYNTAXERROR"),word); - return; - } - } else if (word[0] == 'l') { - duration = strtol(word+1,&tail,0); - if (tail && *tail) { - WriteOut(MSG_Get("SHELL_SYNTAXERROR"),word); - return; - } - } else if (!word[0] || ((scankey = (KBD_KEYS)strtol(word,NULL,0)) > KBD_NONE && scankey < KBD_LAST)) { - if (shift) { - if (delay == 0) KEYBOARD_AddKey(KBD_leftshift,true); - else PIC_AddEvent(&delayed_press,delay++,KBD_leftshift); - } - if (ctrl) { - if (delay == 0) KEYBOARD_AddKey(KBD_leftctrl,true); - else PIC_AddEvent(&delayed_press,delay++,KBD_leftctrl); - } - if (alt) { - if (delay == 0) KEYBOARD_AddKey(KBD_leftalt,true); - else PIC_AddEvent(&delayed_press,delay++,KBD_leftalt); - } - if (delay == 0) KEYBOARD_AddKey(scankey,true); - else PIC_AddEvent(&delayed_press,delay++,scankey); - - if (delay+duration == 0) KEYBOARD_AddKey(scankey,false); - else PIC_AddEvent(&delayed_release,delay+++duration,scankey); - if (alt) { - if (delay+duration == 0) KEYBOARD_AddKey(KBD_leftalt,false); - else PIC_AddEvent(&delayed_release,delay+++duration,KBD_leftalt); - } - if (ctrl) { - if (delay+duration == 0) KEYBOARD_AddKey(KBD_leftctrl,false); - else PIC_AddEvent(&delayed_release,delay+++duration,KBD_leftctrl); - } - if (shift) { - if (delay+duration == 0) KEYBOARD_AddKey(KBD_leftshift,false); - else PIC_AddEvent(&delayed_release,delay+++duration,KBD_leftshift); - } - } else if (core != 0) { - if (core == 1) { - if (delay == 0) SetVal("cpu","core","normal"); - else PIC_AddEvent(&delayed_sdlpress,delay++,1); - } else if (core == 2) { - if (delay == 0) SetVal("cpu","core","simple"); - else PIC_AddEvent(&delayed_sdlpress,delay++,2); - } else if (core == 3) { - if (delay == 0) SetVal("cpu","core","dynamic"); - else PIC_AddEvent(&delayed_sdlpress,delay++,3); - } else if (core == 4) { - if (delay == 0) SetVal("cpu","core","full"); - else PIC_AddEvent(&delayed_sdlpress,delay++,4); - } - } else { - WriteOut(MSG_Get("SHELL_SYNTAXERROR"),word); - return; - } - } + command.FindCommand(1,arg); + if( (arg.size()>1) && arg[1] !=':') throw(0); + char temp_str[2] = { 0,0 }; + temp_str[0]=(char)toupper(args[0]); + command.FindCommand(2,arg); + if((arg=="/D") || (arg=="/d")) { + if(!Drives[temp_str[0]-'A'] ) throw 1; //targetdrive not in use + strcat(mountstring,"-u "); + strcat(mountstring,temp_str); + this->ParseLine(mountstring); + return; + } + if(Drives[temp_str[0]-'A'] ) throw 2; //targetdrive in use + strcat(mountstring,temp_str); + strcat(mountstring," "); + + uint8_t drive;char dir[DOS_PATHLENGTH+2],fulldir[DOS_PATHLENGTH]; + if (strchr(arg.c_str(),'\"')==NULL) + sprintf(dir,"\"%s\"",arg.c_str()); + else strcpy(dir,arg.c_str()); + if (!DOS_MakeName(dir,fulldir,&drive)) throw 3; + + localDrive * const ldp = dynamic_cast(Drives[drive]); + if (!ldp) throw 4; + char newname[CROSS_LEN]; + strcpy(newname, ldp->basedir); + strcat(newname,fulldir); + CROSS_FILENAME(newname); + ldp->dirCache.ExpandName(newname); + strcat(mountstring,"\""); + strcat(mountstring, newname); + strcat(mountstring,"\""); + this->ParseLine(mountstring); + } + catch(int a){ + switch (a) { + case 1: + WriteOut(MSG_Get("SHELL_CMD_SUBST_NO_REMOVE")); + break; + case 2: + WriteOut(MSG_Get("SHELL_CMD_SUBST_IN_USE")); + break; + case 3: + WriteOut(MSG_Get("SHELL_CMD_SUBST_INVALID_PATH")); + break; + case 4: + WriteOut(MSG_Get("SHELL_CMD_SUBST_NOT_LOCAL")); + break; + default: + WriteOut(MSG_Get("SHELL_CMD_SUBST_FAILURE")); + } + return; + } + catch(...) { //dynamic cast failed =>so no localdrive + WriteOut(MSG_Get("SHELL_CMD_SUBST_FAILURE")); + return; + } + + return; } - -#if C_DEBUG -extern bool tohide; -bool debugger_break_on_exec = false; -void DEBUG_Enable_Handler(bool pressed); -void DOS_Shell::CMD_DEBUGBOX(char * args) { - while (*args == ' ') args++; - std::string argv=std::string(args); - args=StripArg(args); - HELP("DEBUGBOX"); - /* TODO: The command as originally taken from DOSBox SVN supported a /NOMOUSE option to remove the INT 33h vector */ - if (!*args) { - tohide=false; - DEBUG_Enable_Handler(true); - tohide=true; - return; - } else if (!strcmp(args,"-?")) { - args[0]='/'; - HELP("DEBUGBOX"); - return; - } - debugger_break_on_exec = true; - DoCommand((char *)argv.c_str()); - debugger_break_on_exec = false; -} -#endif - -char *str_replace(const char *orig, const char *rep, const char *with) { - char *result, *ins, *tmp; - size_t len_rep, len_with, len_front; - int count; - - if (!orig || !rep) return NULL; - - char* mutable_orig = strdup(orig); // Make a mutable copy of orig - char* original_mutable_orig = mutable_orig; // Store the original address for freeing below - - len_rep = strlen(rep); - if (len_rep == 0) return NULL; - len_with = with?strlen(with):0; - - ins = mutable_orig; - for (count = 0; (tmp = strstr(ins, rep)) != NULL; ++count) - ins = tmp + len_rep; - - tmp = result = (char *)malloc(strlen(mutable_orig) + (len_with - len_rep) * count + 1); - if (!result) return NULL; - - while (count--) { - ins = strstr(mutable_orig, rep); - len_front = ins - mutable_orig; - tmp = strncpy(tmp, mutable_orig, len_front) + len_front; - tmp = strcpy(tmp, with?with:"") + len_with; - mutable_orig += len_front + len_rep; - } - strcpy(tmp, mutable_orig); - free(original_mutable_orig); - return result; -} - -void DOS_Shell::CMD_FOR(char *args) { - HELP("FOR"); - args = ltrim(args); - if (strlen(args)<12){SyntaxError();return;} - char s[3]; - strcpy(s,"%%"); - if (*args=='%' && (isalpha(args[1]) || isdigit(args[1]) || strchr("_-/*.;#$",args[1])) && isspace(args[2])) - s[1]=*(args+1); - else{SyntaxError();return;} - args = ltrim(args+3); - if (strncasecmp(args, "IN", 2) || !isspace(args[2])){SyntaxError();return;} - args = ltrim(args+3); - if (*args=='(') - args = ltrim(args+1); - else{SyntaxError();return;} - char *p=strchr(args, ')'); - if (p==NULL||!isspace(*(p+1))){SyntaxError();return;} - *p=0; - char flist[260], *fp=flist; - if (strlen(ltrim(args))<260) - strcpy(flist, ltrim(args)); - else - { - strncpy(flist, args, 259); - flist[259]=0; - } - *p=')'; - args=ltrim(p+2); - if (strncasecmp(args, "DO", 2) || !isspace(args[2])){SyntaxError();return;} - args = ltrim(args+3); - bool lfn=uselfn&&lfnfor; - while (*fp) { - p=fp; - int q=0; - while (*p&&(q/2*2!=q||(*p!=' '&&*p!=','&&*p!=';'))) - { - if (*p=='"') - q++; - p++; - } - bool last=!!strlen(p); - if (last) *p=0; - if (strchr(fp, '?') || strchr(fp, '*')) { - char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH], spath[DOS_PATHLENGTH], path[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH], full[DOS_PATHLENGTH], *r; - if (!DOS_Canonicalize(fp,full)) return; - r=strrchr_dbcs(full, '\\'); - if (r!=NULL) { - *r=0; - strcpy(path, full); - strcat(path, "\\"); - strcpy(pattern, r+1); - *r='\\'; - } else { - strcpy(path, ""); - strcpy(pattern, full); - } - strcpy(spath, path); - if (strchr(fp,'\"')||uselfn) { - if (!DOS_GetSFNPath(("\""+std::string(path)+"\\").c_str(), spath, false)) strcpy(spath, path); - if (!strlen(spath)||spath[strlen(spath)-1]!='\\') strcat(spath, "\\"); - int k=0; - for (int i=0;i<(int)strlen(path);i++) - if (path[i]!='\"') - path[k++]=path[i]; - path[k]=0; - } - uint32_t size, hsize; - uint16_t date, time; - uint8_t attr; - DOS_DTA dta(dos.dta()); - std::vector sources; - std::string tmp; - int fbak=lfn_filefind_handle; - lfn_filefind_handle=lfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; - if (DOS_FindFirst((std::string(spath)+std::string(pattern)).c_str(), ~(DOS_ATTR_VOLUME|DOS_ATTR_DIRECTORY|DOS_ATTR_DEVICE|DOS_ATTR_HIDDEN|DOS_ATTR_SYSTEM))) - { - dta.GetResult(name, lname, size, hsize, date, time, attr); - tmp=std::string(path)+std::string(lfn?lname:name); - sources.push_back(tmp); - while (DOS_FindNext()) - { - dta.GetResult(name, lname, size, hsize, date, time, attr); - tmp=std::string(path)+std::string(lfn?lname:name); - sources.push_back(tmp); - } - } - lfn_filefind_handle=fbak; - for (std::vector::iterator source = sources.begin(); source != sources.end(); ++source) - DoCommand(str_replace(args, s, source->c_str())); - } else - DoCommand(str_replace(args, s, fp)); - if (last) *p=' '; - fp=ltrim(p); - } -} - -void DOS_Shell::CMD_LFNFOR(char * args) { - HELP("LFNFOR"); - args = trim(args); - if (!*args) - WriteOut("LFNFOR is %s\n", lfnfor ? "on" : "off"); - else if (!strcasecmp(args, "OFF")) - lfnfor = false; - else if (!strcasecmp(args, "ON")) - lfnfor = true; - else - WriteOut("Must specify ON or OFF\n"); -} - -void DOS_Shell::CMD_ALIAS(char* args) { - HELP("ALIAS"); - args = trim(args); - if (!*args || strchr(args, '=') == NULL) { - for (cmd_alias_map_t::iterator iter = cmd_alias.begin(), end = cmd_alias.end(); iter != end; ++iter) { - if (!*args || !strcasecmp(args, iter->first.c_str())) - WriteOut("ALIAS %s='%s'\n", iter->first.c_str(), iter->second.c_str()); - } - } else { - char alias_name[256] = { 0 }; - for (unsigned int offset = 0; *args && offset < sizeof(alias_name)-1; ++offset, ++args) { - if (*args == '=') { - char * const cmd = trim(alias_name); - ++args; - args = trim(args); - size_t args_len = strlen(args); - if ((*args == '"' && args[args_len - 1] == '"') || (*args == '\'' && args[args_len - 1] == '\'')) { - args[args_len - 1] = 0; - ++args; - } - if (!*args) { - cmd_alias.erase(cmd); - } else { - cmd_alias[cmd] = args; - cmd_alias_map_t::iterator iter = cmd_alias.find(cmd); - if (iter != cmd_alias.end()) WriteOut("ALIAS %s='%s'\n", iter->first.c_str(), iter->second.c_str()); - } - break; - } else { - alias_name[offset] = *args; - } - } - } -} - -void DOS_Shell::CMD_ASSOC(char* args) { - HELP("ASSOC"); - args = trim(args); - if (!*args || strchr(args, '=') == NULL) { - for (cmd_assoc_map_t::iterator iter = cmd_assoc.begin(), end = cmd_assoc.end(); iter != end; ++iter) { - if (!*args || !strcasecmp(args, iter->first.c_str())) - WriteOut("%s=%s\n", iter->first.c_str(), iter->second.c_str()); - } - } else { - char assoc_name[256] = { 0 }; - for (unsigned int offset = 0; *args && offset < sizeof(assoc_name)-1; ++offset, ++args) { - if (*args == '=') { - char * const cmd = trim(assoc_name); - if (!*cmd || cmd[0] != '.') { - WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), cmd); - break; - } - ++args; - args = trim(args); - size_t args_len = strlen(args); - if ((*args == '"' && args[args_len - 1] == '"') || (*args == '\'' && args[args_len - 1] == '\'')) { - args[args_len - 1] = 0; - ++args; - } - if (!*args) { - cmd_assoc.erase(cmd); - } else { - cmd_assoc[cmd] = args; - cmd_assoc_map_t::iterator iter = cmd_assoc.find(cmd); - if (iter != cmd_assoc.end()) WriteOut("%s=%s\n", iter->first.c_str(), iter->second.c_str()); - } - break; - } else { - assoc_name[offset] = *args; - } - } - } -} - -void DOS_Shell::CMD_HISTORY(char* args) { - HELP("HISTORY"); - if (ScanCMDBool(args,"C")) - l_history.clear(); - for (auto it = l_history.rbegin(); it != l_history.rend(); ++it) { - WriteOut_NoParsing(it->c_str(), true); - WriteOut("\n"); - } -} - -void CAPTURE_StartCapture(void); -void CAPTURE_StopCapture(void); - -void CAPTURE_StartWave(void); -void CAPTURE_StopWave(void); - -void CAPTURE_StartMTWave(void); -void CAPTURE_StopMTWave(void); - -void CAPTURE_StartOPL(void); -void CAPTURE_StopOPL(void); - -// Explanation: Start capture, run program, stop capture when program exits. -// Great for gameplay footage or demoscene capture. -// -// The command name is chosen not to conform to the 8.3 pattern -// on purpose to avoid conflicts with any existing DOS applications. -void DOS_Shell::CMD_DXCAPTURE(char * args) { - while (*args == ' ') args++; - std::string argv=std::string(args); - args=StripArg(args); - HELP("DXCAPTURE"); - bool cap_video = false; - bool cap_audio = false; - bool cap_mtaudio = false; - bool cap_opl = false; - unsigned long post_exit_delay_ms = 3000; /* 3 sec */ - - if (!strcmp(args,"-?")) { - args[0]='/'; - HELP("DXCAPTURE"); - return; - } - - args=(char *)argv.c_str(); - char *arg1; - while (strlen(args)&&args[0]=='/') { - arg1=StripArg(args); - upcase(arg1); - if (!(strcmp(arg1,"/V"))) - cap_video = true; - else if (!(strcmp(arg1,"/-V"))) - cap_video = false; - else if (!(strcmp(arg1,"/A"))) - cap_audio = true; - else if (!(strcmp(arg1,"/O"))) - cap_opl = true; - else if (!(strcmp(arg1,"/-A"))) - cap_audio = false; - else if (!(strcmp(arg1,"/-O"))) - cap_opl = false; - else if (!(strcmp(arg1,"/M"))) - cap_mtaudio = true; - else if (!(strcmp(arg1,"/-M"))) - cap_mtaudio = false; - else { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),arg1); - return; - } - } - - if (!cap_video && !cap_audio && !cap_mtaudio && !cap_opl) - cap_video = true; - - if (cap_video) - CAPTURE_StartCapture(); - if (cap_audio) - CAPTURE_StartWave(); - if (cap_mtaudio) - CAPTURE_StartMTWave(); - if (cap_opl) - CAPTURE_StartOPL(); - - DoCommand(args); - - if (post_exit_delay_ms > 0) { - LOG_MSG("Pausing for post exit delay (%.3f seconds)",(double)post_exit_delay_ms / 1000); - - uint32_t lasttick=GetTicks(); - while ((GetTicks()-lasttick)0) { - countryNo = newCC; - DOS_SetCountry(countryNo); - return; - } - WriteOut("Invalid country code - %s\n", StripArg(args)); - return; -} - -extern bool jfont_init, finish_prepare, isDBCSCP(); -extern Bitu DOS_LoadKeyboardLayout(const char * layoutname, int32_t codepage, const char * codepagefile); -void runRescan(const char *str), MSG_Init(), JFONT_Init(), InitFontHandle(), ShutFontHandle(), initcodepagefont(), DOSBox_SetSysMenu(); -int toSetCodePage(DOS_Shell *shell, int newCP, int opt) { - if((TTF_using() && isSupportedCP(newCP)) || !TTF_using()) { - int32_t oldcp = dos.loaded_codepage, cpbak = newCP; - Bitu keyb_error; - if(IS_PC98_ARCH || IS_JEGA_ARCH) newCP = 932; - else if(IS_DOSV) { - if(IS_JDOSV) newCP = 932; - else if(IS_PDOSV) newCP = 936; - else if(IS_KDOSV) newCP = 949; - else if(IS_TDOSV) newCP = 950; - } - else if (!CheckDBCSCP(newCP)){ - keyb_error = DOS_ChangeCodepage(newCP, "auto"); - if (keyb_error != KEYB_NOERROR) { - dos.loaded_codepage = oldcp; - return -1; - } - } - if(newCP != cpbak) LOG_MSG("SHELL: Invalid codepage %d, set to %d.", cpbak, newCP); - dos.loaded_codepage = newCP; - int missing = 0; -#if defined(USE_TTF) - missing = TTF_using() ? setTTFCodePage() : 0; -#endif - if (!TTF_using()) initcodepagefont(); - if (opt==-1) { - MSG_Init(); -#if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU - mainMenu.unbuild(); - mainMenu.rebuild(); - if (!GFX_GetPreventFullscreen()) { - if (menu.toggle) DOSBox_SetMenu(); else DOSBox_NoMenu(); - } -#endif - DOSBox_SetSysMenu(); - } - if(isDBCSCP()) { - ShutFontHandle(); - InitFontHandle(); - JFONT_Init(); - SetupDBCSTable(); - if(newCP == 950 && !chinasea) makestdcp950table(); - if(newCP == 951 && chinasea) makeseacp951table(); - } - if (finish_prepare) runRescan("-A -Q"); -#if C_OPENGL && DOSBOXMENU_TYPE == DOSBOXMENU_SDLDRAW - if(OpenGL_using() && control->opt_lang.size()) - UpdateSDLDrawTexture(); -#endif -#if defined(USE_TTF) - if ((opt==-1||opt==-2)&&TTF_using()) { - Section_prop * ttf_section = static_cast(control->GetSection("ttf")); - const char *font = ttf_section->Get_string("font"); - if (!font || !*font) { - ttf_reset(); -#if C_PRINTER - if (printfont) UpdateDefaultPrinterFont(); -#endif - } - } -#endif - if(newCP != lastsetcp) { - LOG_MSG("Codepage set to %d", newCP); - lastsetcp = newCP; - } - return missing; - } else if (opt<1 && shell) { - shell->WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), std::to_string(newCP).c_str()); - } - return -1; -} - -const char* DOS_GetLoadedLayout(void); -Bitu DOS_ChangeCodepage(int32_t codepage, const char* codepagefile); -Bitu DOS_ChangeKeyboardLayout(const char* layoutname, int32_t codepage); - -void DOS_Shell::CMD_CHCP(char * args) { - HELP("CHCP"); - args = trim(args); - if (!*args) { - WriteOut(MSG_Get("SHELL_CMD_CHCP_ACTIVE"), dos.loaded_codepage); - return; - } - if (IS_PC98_ARCH || IS_JEGA_ARCH) { - WriteOut("Changing code page is not supported for the PC-98 or JEGA/AX system.\n"); - return; - } - if (IS_DOSV || IS_J3100) - { - WriteOut("Changing code page is not supported for the DOS/V or J-3100 system.\n"); - return; - } - int32_t newCP; - char buff[256], *r; - int missing = 0, n = sscanf(args, "%d%s", &newCP, buff); - auto iter = langcp_map.find(newCP); - const char* layout_name = DOS_GetLoadedLayout(); - int32_t cp = dos.loaded_codepage; - Bitu keyb_error; - if(n == 1) { - if (!TTF_using() || (TTF_using() && isSupportedCP(newCP))){ - bool load_language = SwitchLanguage(cp, newCP, true); - CHCP_changed = true; - missing = toSetCodePage(this, newCP, load_language ? -1: -2); - if(missing > 0) WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); - else if(missing < 0) { - WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); - CHCP_changed = false; - return; - } - } - else { - if(TTF_using() && !isSupportedCP(newCP)) { - WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); - LOG_MSG("CHCP: Codepage %d not supported for TTF output", newCP); - } - else { - WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); - } - CHCP_changed = false; - return; - } - CHCP_changed = false; - WriteOut(MSG_Get("SHELL_CMD_CHCP_ACTIVE"), dos.loaded_codepage); - } - else if(n == 2 && strlen(buff)) { - if(*buff == ':' && strchr(StripArg(args), ':')) { - std::string name = buff + 1; - if(name.empty() && iter != langcp_map.end()) name = iter->second; - if(!TTF_using() || (TTF_using() && isSupportedCP(newCP))) { - CHCP_changed = true; - missing = toSetCodePage(this, newCP, -1); - if(missing > 0) WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); - else if(missing < 0) { - WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); - CHCP_changed = false; - return; - } - } - if(name.size() && dos.loaded_codepage == newCP) { - SetVal("dosbox", "language", name); - Load_Language(name); - } - WriteOut(MSG_Get("SHELL_CMD_CHCP_ACTIVE"), dos.loaded_codepage); - CHCP_changed = false; - return; - } -#if defined(USE_TTF) - if(ttf.inUse) { - if(isSupportedCP(newCP)) { - missing = toSetCodePage(this, newCP, -1); - if(missing > -1) SwitchLanguage(cp, newCP, true); - if(missing > 0) WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); - LOG_MSG("CHCP: Loading cpi/cpx files ignored for TTF output"); - } - else { - WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); - LOG_MSG("CHCP: Codepage %d not supported for TTF output", newCP); - return; - } - } - else { -#endif - altcp = 0; - for(int i = 0; i < 256; i++) altcp_to_unicode[i] = 0; - std::string cpfile = buff; - FILE* file = fopen(cpfile.c_str(), "r"); /* should check the result */ - std::string exepath = GetDOSBoxXPath(); - if(!file && exepath.size()) file = fopen((exepath + CROSS_FILESPLIT + cpfile).c_str(), "r"); - if(file && newCP > 0 && !CheckDBCSCP(newCP)) { - altcp = newCP; - char line[256], * l = line; - while(fgets(line, sizeof(line), file)) { - l = trim(l); - if(!strlen(l)) continue; - r = strchr(l, '#'); - if(r) *r = 0; - l = trim(l); - if(!strlen(l) || strncasecmp(l, "0x", 2)) continue; - r = strchr(l, ' '); - if(!r) r = strchr(l, '\t'); - if(!r) continue; - *r = 0; - int ind = (int)strtol(l + 2, NULL, 16); - r = trim(r + 1); - if(ind > 0xFF || strncasecmp(r, "0x", 2)) continue; - int map = (int)strtol(r + 2, NULL, 16); - altcp_to_unicode[ind] = map; - } - if(file) fclose(file); - keyb_error = DOS_ChangeCodepage(newCP, cpfile.c_str()); - if(keyb_error == KEYB_NOERROR) { - if(layout_name != NULL) { - keyb_error = DOS_ChangeKeyboardLayout(layout_name, cp); - } + + void DOS_Shell::CMD_LOADHIGH(char *args){ + HELP("LOADHIGH"); + uint16_t umb_start=dos_infoblock.GetStartOfUMBChain(); + uint8_t umb_flag=dos_infoblock.GetUMBChainState(); + uint8_t old_memstrat=(uint8_t)(DOS_GetMemAllocStrategy()&0xff); + if (umb_start==0x9fff) { + if ((umb_flag&1)==0) DOS_LinkUMBsToMemChain(1); + DOS_SetMemAllocStrategy(0x80); // search in UMBs first + this->ParseLine(args); + uint8_t current_umb_flag=dos_infoblock.GetUMBChainState(); + if ((current_umb_flag&1)!=(umb_flag&1)) DOS_LinkUMBsToMemChain(umb_flag); + DOS_SetMemAllocStrategy(old_memstrat); // restore strategy + } else this->ParseLine(args); + } + + bool get_param(char *&args, char *&rem, char *&temp, char &wait_char, int &wait_sec) + { + const char *last = strchr(args, 0); + StripSpaces(args); + temp = ScanCMDRemain(args); + const bool optC = temp && tolower(temp[1]) == 'c'; + const bool optT = temp && tolower(temp[1]) == 't'; + if (temp && *temp && !optC && !optT) + return false; + if (temp) { + if (args == temp) + args = strchr(temp, 0) + 1; + temp += 2; + if (temp[0] == ':') + temp++; + } + if (optC) { + rem = temp; + } else if (optT) { + if (temp && *temp && *(temp + 1) == ',') { + wait_char = *temp; + wait_sec = atoi(temp + 2); + } else + wait_sec = 0; + } + if (args > last) + args = NULL; + if (args) args = trim(args); + return true; + } + + void DOS_Shell::CMD_CHOICE(char * args){ + HELP("CHOICE"); + static char defchoice[3] = {MSG_Get("INT21_6523_YESNO_CHARS")[0],MSG_Get("INT21_6523_YESNO_CHARS")[1],0}; + //char *rem1 = NULL, *rem2 = NULL; /* unused */ + char *rem = NULL, *temp = NULL, waitchar = 0, *ptr; + int waitsec = 0; + //bool optC = false, optT = false; /* unused */ + bool optN = ScanCMDBool(args,"N"); + bool optS = ScanCMDBool(args,"S"); //Case-sensitive matching + // ignore /b and /m switches for compatibility + ScanCMDBool(args,"B"); + ScanCMDBool(args,"M"); // Text + ScanCMDBool(args,"T"); //Default Choice after timeout + + while (args && *trim(args) == '/') { + if (!get_param(args, rem, temp, waitchar, waitsec)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), temp); + return; + } + } + if (!rem || !*rem) rem = defchoice; /* No choices specified use (national) YN */ + ptr = rem; + uint8_t c; + if(!optS) while ((c = (uint8_t)(*ptr))) *ptr++ = (char)toupper(c); /* When in no case-sensitive mode. make everything upcase */ + if(args && *args ) { + StripSpaces(args); + size_t argslen = strlen(args); + if(argslen>1 && args[0] == '"' && args[argslen-1] =='"') { + args[argslen-1] = 0; //Remove quotes + args++; + } + WriteOut(args); + } + /* Show question prompt of the form [a,b]? where a b are the choice values */ + if (!optN) { + if(args && *args) WriteOut(" "); + WriteOut("["); + size_t len = strlen(rem); + for(size_t t = 1; t < len; t++) { + WriteOut("%c,",rem[t-1]); + } + WriteOut("%c]?",rem[len-1]); + } + + // TO-DO: Find out how real DOS handles /T option for making a choice after delay; use AUTOTYPE for now + std::vector sequence; + bool in_char = optS ? (strchr(rem, waitchar) != nullptr) : (strchr(rem, toupper(waitchar)) || strchr(rem, tolower(waitchar))); + if (waitchar && *rem && in_char && waitsec > 0) { + sequence.emplace_back(std::string(1, optS?waitchar:tolower(waitchar))); + MAPPER_AutoType(sequence, waitsec * 1000, 500, true); + } + uint16_t n=1; + do { + dotype = true; + DOS_ReadFile (STDIN,&c,&n); + dotype = false; + if (n==0) {dos.return_code=255;return;} + if (CheckBreak(this) || c==3) {dos.return_code=0;return;} + } while (!c || !(ptr = strchr(rem,(optS?c:toupper(c))))); + c = optS?c:(uint8_t)toupper(c); + DOS_WriteFile (STDOUT,&c, &n); + c = '\r'; DOS_WriteFile (STDOUT,&c, &n); + c = '\n'; DOS_WriteFile (STDOUT,&c, &n); + dos.return_code = (uint8_t)(ptr-rem+1); + } + + static bool doAttrib(DOS_Shell * shell, char * args, DOS_DTA dta, bool optS, bool adda, bool adds, bool addh, bool addr, bool suba, bool subs, bool subh, bool subr) { + char spath[DOS_PATHLENGTH],sargs[DOS_PATHLENGTH+4],path[DOS_PATHLENGTH+4],full[DOS_PATHLENGTH],sfull[DOS_PATHLENGTH+2]; + if (!DOS_Canonicalize(args,full)||strrchr_dbcs(full,'\\')==NULL) { + shell->WriteOut(MSG_Get("SHELL_ILLEGAL_PATH")); + if (!optS) ctrlbrk=true; + return false; + } + if (!DOS_GetSFNPath(args,spath,false)) { + shell->WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); + if (!optS) ctrlbrk=true; + return false; + } + if (!uselfn||!DOS_GetSFNPath(args,sfull,true)) strcpy(sfull,full); + sprintf(sargs,"\"%s\"",spath); + bool found=false, res=DOS_FindFirst(sargs,0xffff & ~DOS_ATTR_VOLUME); + if (!res&&!optS) return false; + //end can't be 0, but if it is we'll get a nice crash, who cares :) + strcpy(path,full); + *(strrchr_dbcs(path,'\\')+1)=0; + char * end=strrchr_dbcs(full,'\\')+1;*end=0; + char * lend=strrchr_dbcs(sfull,'\\')+1;*lend=0; + char name[DOS_NAMELENGTH_ASCII],lname[LFN_NAMELENGTH+1]; + uint32_t size,hsize;uint16_t time,date;uint8_t attr;uint16_t fattr; + while (res) { + if (CheckBreak(shell)) {ctrlbrk=true;return false;} + dta.GetResult(name,lname,size,hsize,date,time,attr); + if (!((!strcmp(name, ".") || !strcmp(name, "..") || strchr(sargs, '*')!=NULL || strchr(sargs, '?')!=NULL) && attr & DOS_ATTR_DIRECTORY)) { + found=true; + strcpy(end,name); + strcpy(lend,lname); + if (strlen(full)&&DOS_GetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), &fattr)) { + bool attra=fattr&DOS_ATTR_ARCHIVE, attrs=fattr&DOS_ATTR_SYSTEM, attrh=fattr&DOS_ATTR_HIDDEN, attrr=fattr&DOS_ATTR_READ_ONLY; + if (adda||adds||addh||addr||suba||subs||subh||subr) { + if (adda) fattr|=DOS_ATTR_ARCHIVE; + if (adds) fattr|=DOS_ATTR_SYSTEM; + if (addh) fattr|=DOS_ATTR_HIDDEN; + if (addr) fattr|=DOS_ATTR_READ_ONLY; + if (suba) fattr&=~DOS_ATTR_ARCHIVE; + if (subs) fattr&=~DOS_ATTR_SYSTEM; + if (subh) fattr&=~DOS_ATTR_HIDDEN; + if (subr) fattr&=~DOS_ATTR_READ_ONLY; + if (DOS_SetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), fattr)) { + if (DOS_GetFileAttr(((uselfn||strchr(full, ' ')?(full[0]!='"'?"\"":""):"")+std::string(full)+(uselfn||strchr(full, ' ')?(full[strlen(full)-1]!='"'?"\"":""):"")).c_str(), &fattr)) { + shell->WriteOut(" %c %c%c%c ", fattr&DOS_ATTR_ARCHIVE?'A':' ', fattr&DOS_ATTR_SYSTEM?'S':' ', fattr&DOS_ATTR_HIDDEN?'H':' ', fattr&DOS_ATTR_READ_ONLY?'R':' '); + shell->WriteOut_NoParsing(uselfn?sfull:full, true); + shell->WriteOut("\n"); + } + } else + shell->WriteOut(MSG_Get("SHELL_CMD_ATTRIB_SET_ERROR"),uselfn?sfull:full); + } else { + shell->WriteOut(" %c %c%c%c ", attra?'A':' ', attrs?'S':' ', attrh?'H':' ', attrr?'R':' '); + shell->WriteOut_NoParsing(uselfn?sfull:full, true); + shell->WriteOut("\n"); + } + } else + shell->WriteOut(MSG_Get("SHELL_CMD_ATTRIB_GET_ERROR"),uselfn?sfull:full); + } + res=DOS_FindNext(); + } + if (optS) { + size_t len=strlen(path); + strcat(path, "*.*"); + bool ret=DOS_FindFirst(path,0xffff & ~DOS_ATTR_VOLUME); + *(path+len)=0; + if (ret) { + std::vector cdirs; + cdirs.clear(); + do { /* File name and extension */ + DtaResult result; + dta.GetResult(result.name,result.lname,result.size,result.hsize,result.date,result.time,result.attr); + + if((result.attr&DOS_ATTR_DIRECTORY) && strcmp(result.name, ".")&&strcmp(result.name, "..")) { + strcat(path, result.name); + strcat(path, "\\"); + char *fname = strrchr_dbcs(args, '\\'); + if (fname!=NULL) fname++; + else { + fname = strrchr(args, ':'); + if (fname!=NULL) fname++; + else fname=args; + } + strcat(path, fname); + cdirs.push_back((path[0]!='"'&&path[strlen(path)-1]=='"'?"\"":"")+std::string(path)); + *(path+len)=0; + } + } while ( (ret=DOS_FindNext()) ); + adirs.insert(adirs.begin()+1, cdirs.begin(), cdirs.end()); + } + } + return found; + } + + void DOS_Shell::CMD_ATTRIB(char *args){ + HELP("ATTRIB"); + StripSpaces(args); + + bool optS=ScanCMDBool(args,"S"); + char * rem=ScanCMDRemain(args); + if (rem) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),rem); + return; + } + + bool adda=false, adds=false, addh=false, addr=false, suba=false, subs=false, subh=false, subr=false; + char sfull[DOS_PATHLENGTH+2]; + char* arg1; + strcpy(sfull, "*.*"); + do { + arg1=StripArg(args); + if (!strcasecmp(arg1, "+A")) adda=true; + else if (!strcasecmp(arg1, "+S")) adds=true; + else if (!strcasecmp(arg1, "+H")) addh=true; + else if (!strcasecmp(arg1, "+R")) addr=true; + else if (!strcasecmp(arg1, "-A")) suba=true; + else if (!strcasecmp(arg1, "-S")) subs=true; + else if (!strcasecmp(arg1, "-H")) subh=true; + else if (!strcasecmp(arg1, "-R")) subr=true; + else if (*arg1) { + strcpy(sfull, arg1); + if (uselfn&&strchr(sfull, '*')) { + char * find_last; + find_last=strrchr_dbcs(sfull,'\\'); + if (find_last==NULL) find_last=sfull; + else find_last++; + if (sfull[strlen(sfull)-1]=='*'&&strchr(find_last, '.')==NULL) strcat(sfull, ".*"); + } + } + } while (*args); + + char buffer[CROSS_LEN]; + args = ExpandDot(sfull,buffer, CROSS_LEN, false); + StripSpaces(args); + RealPt save_dta=dos.dta(); + dos.dta(dos.tables.tempdta); + DOS_DTA dta(dos.dta()); + adirs.clear(); + adirs.emplace_back(std::string(args)); + bool found=false; + inshell=true; + while (!adirs.empty()) { + ctrlbrk=false; + if (doAttrib(this, (char *)adirs.begin()->c_str(), dta, optS, adda, adds, addh, addr, suba, subs, subh, subr)) + found=true; + else if (ctrlbrk) + break; + adirs.erase(adirs.begin()); + } + if (!found&&!ctrlbrk) WriteOut(MSG_Get("SHELL_CMD_FILE_NOT_FOUND"),args); + inshell=false; + ctrlbrk=false; + dos.dta(save_dta); + } + + void DOS_Shell::CMD_PROMPT(char *args){ + HELP("PROMPT"); + if(args && *args) { + args++; + SetEnv("PROMPT",args); + } else + SetEnv("PROMPT","$P$G"); + return; + } + + void DOS_Shell::CMD_PATH(char *args){ + HELP("PATH"); + if(args && *args){ + char pathstring[DOS_PATHLENGTH+CROSS_LEN+20]={ 0 }; + strcpy(pathstring,"set PATH="); + while(args && (*args=='='|| *args==' ')) + args++; + if (strlen(args) == 1 && *args == ';') + *args = 0; + if (args) { + std::string vstr = args; + bool zdirpath = static_cast(control->GetSection("dos"))->Get_bool("drive z expand path"); + if (zdirpath) GetExpandedPath(vstr); + strcat(pathstring,vstr.c_str()); + } + this->ParseLine(pathstring); + return; + } else { + std::string line; + if(GetEnvStr("PATH",line)) { + WriteOut("%s\n",line.c_str()); + } else { + WriteOut("PATH=(null)\n"); + } + } + } + + void DOS_Shell::CMD_VERIFY(char * args) { + HELP("VERIFY"); + args = trim(args); + if (!*args) + WriteOut("VERIFY is %s\n", dos.verify ? "on" : "off"); + else if (!strcasecmp(args, "OFF")) + dos.verify = false; + else if (!strcasecmp(args, "ON")) + dos.verify = true; + else + WriteOut("Must specify ON or OFF\n"); + } + + void dos_ver_menu(bool start); + bool set_ver(char *s); + void DOS_Shell::CMD_VER(char *args) { + HELP("VER"); + bool optR=ScanCMDBool(args,"R"); + if (char* rem = ScanCMDRemain(args)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), rem); + return; + } + if(!optR && args && *args) { + char* word = StripWord(args); + if(strcasecmp(word,"set")) { + if (*word=='=') word=trim(word+1); + if (isdigit(*word)) { + if (*args) { + WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), args); + return; + } + if (set_ver(word)) + dos_ver_menu(false); + else + WriteOut(MSG_Get("SHELL_CMD_VER_INVALID")); + return; + } + if (*word) { + WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), word); + return; + } + } + if (!*args) { + dos.version.major = 5; + dos.version.minor = 0; + } else if (!set_ver(args)) { + WriteOut(MSG_Get("SHELL_CMD_VER_INVALID")); + return; + } + dos_ver_menu(false); + } else { + WriteOut(MSG_Get("SHELL_CMD_VER_VER"),VERSION,SDL_STRING,dos.version.major,dos.version.minor); + if (optR) WriteOut("DOSBox-X Git commit %s, built on %s\nPlatform: %s %d-bit", GIT_COMMIT_HASH, UPDATED_STR, OS_PLATFORM_LONG, OS_BIT_INT); + } + } + + void DOS_Shell::CMD_VOL(char *args){ + HELP("VOL"); + uint8_t drive=DOS_GetDefaultDrive(); + if(args && *args){ + args++; + uint32_t argLen = (uint32_t)strlen(args); + switch (args[argLen-1]) { + case ':' : + if(!strcasecmp(args,":")) return; + int drive2; drive2= toupper(*reinterpret_cast(&args[0])); + char * c; c = strchr(args,':'); *c = '\0'; + if (Drives[drive2-'A']) drive = drive2 - 'A'; + else { + WriteOut(MSG_Get("SHELL_ILLEGAL_DRIVE")); + return; + } + break; + default: + WriteOut(MSG_Get("SHELL_SYNTAXERROR")); + return; + } + } + char const* bufin = Drives[drive]->GetLabel(); + if (tree) + WriteOut(MSG_Get("SHELL_CMD_VOL_TREE"),bufin); + else { + WriteOut(MSG_Get("SHELL_CMD_VOL_DRIVE"),drive+'A'); + + //if((drive+'A')=='Z') bufin="DOSBOX-X"; + if(strcasecmp(bufin,"")==0) + WriteOut(MSG_Get("SHELL_CMD_VOL_SERIAL_NOLABEL")); + else + WriteOut(MSG_Get("SHELL_CMD_VOL_SERIAL_LABEL"),bufin); + } + + WriteOut(tree?MSG_Get("SHELL_CMD_VOL_SERIAL")+1:MSG_Get("SHELL_CMD_VOL_SERIAL")); + unsigned long serial_number=0x1234; + if (!strncmp(Drives[drive]->GetInfo(),"fatDrive ",9)) { + fatDrive* fdp = dynamic_cast(Drives[drive]); + if (fdp != NULL) serial_number=fdp->GetSerial(); + } + #if defined (WIN32) + if (!strncmp(Drives[drive]->GetInfo(),"local ",6) || !strncmp(Drives[drive]->GetInfo(),"CDRom ",6)) { + localDrive* ldp = !strncmp(Drives[drive]->GetInfo(),"local ",6)?dynamic_cast(Drives[drive]):dynamic_cast(Drives[drive]); + if (ldp != NULL) serial_number=ldp->GetSerial(); + } + #endif + WriteOut("%04X-%04X\n", serial_number/0x10000, serial_number%0x10000); + return; + } + + void DOS_Shell::CMD_TRUENAME(char * args) { + HELP("TRUENAME"); + bool optH=ScanCMDBool(args,"H"); + args = trim(args); + if (!*args) { + WriteOut("No file name given.\n"); + return; + } + if (char* rem = ScanCMDRemain(args)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), rem); + return; + } + char *name = StripArg(args), fullname[DOS_PATHLENGTH]; + uint8_t drive; + if (DOS_MakeName(name, fullname, &drive)) { + if (optH) { + if (!strncmp(Drives[drive]->GetInfo(),"local ",6) || !strncmp(Drives[drive]->GetInfo(),"CDRom ",6)) { + localDrive *ldp = dynamic_cast(Drives[drive]); + Overlay_Drive *odp = dynamic_cast(Drives[drive]); + std::string hostname = ""; + if (odp) hostname = odp->GetHostName(fullname); + else if (ldp) hostname = ldp->GetHostName(fullname); + if (hostname.size()) { + WriteOut_NoParsing(hostname.c_str(), true); + WriteOut("\n"); } - WriteOut(MSG_Get("SHELL_CMD_CHCP_ACTIVE"), dos.loaded_codepage); -#if defined(USE_TTF) - if(missing > 0) WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); -#endif } - else - WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); - if(file) fclose(file); -#if defined(USE_TTF) - } -#endif - } - else WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); - return; -} - -void DOS_Shell::CMD_VTEXT(char *args) -{ - HELP("VTEXT"); - if (!IS_DOSV) { - WriteOut("This command is only supported in DOS/V mode.\n"); - return; - } - if (char* rem = ScanCMDRemain(args)) { - WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), rem); - return; - } - args = trim(args); - if(args && *args) { - uint8_t new_mode = 0xff; - char *word = StripWord(args); - if(!strcasecmp(word, "1")) - new_mode = 0x70; - else if(!strcasecmp(word, "2")) - new_mode = 0x78; - else if(!strcasecmp(word, "0")) - new_mode = 0x03; - else { - WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), word); - return; - } - if(new_mode != 0xff) { - uint16_t oldax=reg_ax; - reg_ax = new_mode; - CALLBACK_RunRealInt(0x10); - if(new_mode == 0x78) new_mode = 0x70; - reg_ax = oldax; - } - } - uint8_t mode = real_readb(BIOSMEM_SEG, BIOSMEM_CURRENT_MODE); - WriteOut(MSG_Get(mode == 0x70?"SHELL_CMD_VTEXT_ON":"SHELL_CMD_VTEXT_OFF")); -} + } else + #if defined(WIN32) && !(defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) + if (Network_IsNetworkResource(fullname)) { + WriteOut_NoParsing(name, true); + WriteOut("\r\n"); + } else + #endif + { + WriteOut("%c:\\", drive+'A'); + WriteOut_NoParsing(fullname, true); + WriteOut("\r\n"); + } + } + else + WriteOut(dos.errorcode==DOSERR_PATH_NOT_FOUND?"Path not found\n":"File not found\n"); + } + + void SetVal(const std::string& secname, const std::string& preval, const std::string& val); + static void delayed_press(Bitu key) { KEYBOARD_AddKey((KBD_KEYS)key,true); } + static void delayed_release(Bitu key) { KEYBOARD_AddKey((KBD_KEYS)key,false); } + static void delayed_sdlpress(Bitu core) { + if(core==1) SetVal("cpu","core","normal"); + else if(core==2) SetVal("cpu","core","simple"); + else if(core==3) SetVal("cpu","core","dynamic"); + else if(core==4) SetVal("cpu","core","full"); + } + // ADDKEY patch was created by Moe + void DOS_Shell::CMD_ADDKEY(char * args){ + //HELP("ADDKEY"); + StripSpaces(args); + if (!*args) { + WriteOut(MSG_Get("SHELL_SYNTAXERROR")); + return; + } + pic_tickindex_t delay = 0; + int duration = 0, core = 0; + + while (*args) { + char *word=StripWord(args); + KBD_KEYS scankey = (KBD_KEYS)0; + char *tail; + bool alt = false, ctrl = false, shift = false; + while (word[1] == '-') { + switch (word[0]) { + case 'c': + ctrl = true; + word += 2; + break; + case 's': + shift = true; + word += 2; + break; + case 'a': + alt = true; + word += 2; + break; + default: + WriteOut(MSG_Get("SHELL_SYNTAXERROR")); + return; + } + } + if (!strcasecmp(word,"enter")) { + word[0] = (char)10; + word[1] = (char)0; + } else if (!strcasecmp(word,"space")) { + word[0] = (char)32; + word[1] = (char)0; + } else if (!strcasecmp(word,"bs")) { + word[0] = (char)8; + word[1] = (char)0; + } else if (!strcasecmp(word,"tab")) { + word[0] = (char)9; + word[1] = (char)0; + } else if (!strcasecmp(word,"escape")) { + word[0] = (char)27; + word[1] = (char)0; + } else if (!strcasecmp(word,"up")) { + word[0] = (char)141; + word[1] = (char)0; + } else if (!strcasecmp(word,"down")) { + word[0] = (char)142; + word[1] = (char)0; + } else if (!strcasecmp(word,"left")) { + word[0] = (char)143; + word[1] = (char)0; + } else if (!strcasecmp(word,"right")) { + word[0] = (char)144; + word[1] = (char)0; + } else if (!strcasecmp(word,"ins")) { + word[0] = (char)145; + word[1] = (char)0; + } else if (!strcasecmp(word,"del")) { + word[0] = (char)146; + word[1] = (char)0; + } else if (!strcasecmp(word,"home")) { + word[0] = (char)147; + word[1] = (char)0; + } else if (!strcasecmp(word,"end")) { + word[0] = (char)148; + word[1] = (char)0; + } else if (!strcasecmp(word,"pgup")) { + word[0] = (char)149; + word[1] = (char)0; + } else if (!strcasecmp(word,"pgdown")) { + word[0] = (char)150; + word[1] = (char)0; + } else if (!strcasecmp(word,"normal")) { + core = 1; + } else if (!strcasecmp(word,"simple")) { + core = 2; + } else if (!strcasecmp(word,"dynamic")) { + core = 3; + } else if (!strcasecmp(word,"full")) { + core = 4; + } else if (word[0] == 'k' && word[1] == 'p' && word[2] && !word[3]) { + word[0] = 151+word[2]-'0'; + word[1] = 0; + } else if (word[0] == 'f' && word[1]) { + word[0] = 128+word[1]-'0'; + if (word[1] == '1' && word[2]) word[0] = 128+word[2]-'0'+10; + word[1] = 0; + } + if (!word[1]) { + const int shiftflag = 0x1000000; + const int map[256] = { + 0,0,0,0,0,0,0,0, + KBD_backspace, + KBD_tab, + KBD_enter, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + KBD_esc, + 0,0,0,0, + KBD_space, KBD_1|shiftflag, KBD_quote|shiftflag, KBD_3|shiftflag, KBD_4|shiftflag, KBD_5|shiftflag, KBD_7|shiftflag, KBD_quote, + KBD_9|shiftflag, KBD_0|shiftflag, KBD_8|shiftflag, KBD_equals|shiftflag, KBD_comma, KBD_minus, KBD_period, KBD_slash, + KBD_0, KBD_1, KBD_2, KBD_3, KBD_4, KBD_5, KBD_6, KBD_7, + KBD_8, KBD_9, KBD_semicolon|shiftflag, KBD_semicolon, KBD_comma|shiftflag, KBD_equals, KBD_period|shiftflag, KBD_slash|shiftflag, + KBD_2|shiftflag, KBD_a|shiftflag, KBD_b|shiftflag, KBD_c|shiftflag, KBD_d|shiftflag, KBD_e|shiftflag, KBD_f|shiftflag, KBD_g|shiftflag, + KBD_h|shiftflag, KBD_i|shiftflag, KBD_j|shiftflag, KBD_k|shiftflag, KBD_l|shiftflag, KBD_m|shiftflag, KBD_n|shiftflag, KBD_o|shiftflag, + KBD_p|shiftflag, KBD_q|shiftflag, KBD_r|shiftflag, KBD_s|shiftflag, KBD_t|shiftflag, KBD_u|shiftflag, KBD_v|shiftflag, KBD_w|shiftflag, + KBD_x|shiftflag, KBD_y|shiftflag, KBD_z|shiftflag, KBD_leftbracket, KBD_backslash, KBD_rightbracket, KBD_6|shiftflag, KBD_minus|shiftflag, + KBD_grave, KBD_a, KBD_b, KBD_c, KBD_d, KBD_e, KBD_f, KBD_g, + KBD_h, KBD_i, KBD_j, KBD_k, KBD_l, KBD_m, KBD_n, KBD_o, + KBD_p, KBD_q, KBD_r, KBD_s, KBD_t, KBD_u, KBD_v, KBD_w, + KBD_x, KBD_y, KBD_z, KBD_leftbracket|shiftflag, KBD_backslash|shiftflag, KBD_rightbracket|shiftflag, KBD_grave|shiftflag, 0, + 0, KBD_f1, KBD_f2, KBD_f3, KBD_f4, KBD_f5, KBD_f6, KBD_f7, KBD_f8, KBD_f9, KBD_f10, KBD_f11, KBD_f12, + KBD_up, KBD_down, KBD_left, KBD_right, KBD_insert, KBD_delete, KBD_home, KBD_end, KBD_pageup, KBD_pagedown, + KBD_kp0, KBD_kp1, KBD_kp2, KBD_kp3, KBD_kp4, KBD_kp5, KBD_kp6, KBD_kp7, KBD_kp8, KBD_kp9, + }; + scankey = (KBD_KEYS)(map[(unsigned char)word[0]] & ~shiftflag); + if (map[(unsigned char)word[0]] & shiftflag) shift = true; + if (!scankey && core == 0) { + WriteOut(MSG_Get("SHELL_SYNTAXERROR"),word); + return; + } + if (core == 0) word[0] = 0; + } + if (word[0] == 'p') { + delay += strtol(word+1,&tail,0); + if (tail && *tail) { + WriteOut(MSG_Get("SHELL_SYNTAXERROR"),word); + return; + } + } else if (word[0] == 'l') { + duration = strtol(word+1,&tail,0); + if (tail && *tail) { + WriteOut(MSG_Get("SHELL_SYNTAXERROR"),word); + return; + } + } else if (!word[0] || ((scankey = (KBD_KEYS)strtol(word,NULL,0)) > KBD_NONE && scankey < KBD_LAST)) { + if (shift) { + if (delay == 0) KEYBOARD_AddKey(KBD_leftshift,true); + else PIC_AddEvent(&delayed_press,delay++,KBD_leftshift); + } + if (ctrl) { + if (delay == 0) KEYBOARD_AddKey(KBD_leftctrl,true); + else PIC_AddEvent(&delayed_press,delay++,KBD_leftctrl); + } + if (alt) { + if (delay == 0) KEYBOARD_AddKey(KBD_leftalt,true); + else PIC_AddEvent(&delayed_press,delay++,KBD_leftalt); + } + if (delay == 0) KEYBOARD_AddKey(scankey,true); + else PIC_AddEvent(&delayed_press,delay++,scankey); + + if (delay+duration == 0) KEYBOARD_AddKey(scankey,false); + else PIC_AddEvent(&delayed_release,delay+++duration,scankey); + if (alt) { + if (delay+duration == 0) KEYBOARD_AddKey(KBD_leftalt,false); + else PIC_AddEvent(&delayed_release,delay+++duration,KBD_leftalt); + } + if (ctrl) { + if (delay+duration == 0) KEYBOARD_AddKey(KBD_leftctrl,false); + else PIC_AddEvent(&delayed_release,delay+++duration,KBD_leftctrl); + } + if (shift) { + if (delay+duration == 0) KEYBOARD_AddKey(KBD_leftshift,false); + else PIC_AddEvent(&delayed_release,delay+++duration,KBD_leftshift); + } + } else if (core != 0) { + if (core == 1) { + if (delay == 0) SetVal("cpu","core","normal"); + else PIC_AddEvent(&delayed_sdlpress,delay++,1); + } else if (core == 2) { + if (delay == 0) SetVal("cpu","core","simple"); + else PIC_AddEvent(&delayed_sdlpress,delay++,2); + } else if (core == 3) { + if (delay == 0) SetVal("cpu","core","dynamic"); + else PIC_AddEvent(&delayed_sdlpress,delay++,3); + } else if (core == 4) { + if (delay == 0) SetVal("cpu","core","full"); + else PIC_AddEvent(&delayed_sdlpress,delay++,4); + } + } else { + WriteOut(MSG_Get("SHELL_SYNTAXERROR"),word); + return; + } + } + } + + #if C_DEBUG + extern bool tohide; + bool debugger_break_on_exec = false; + void DEBUG_Enable_Handler(bool pressed); + void DOS_Shell::CMD_DEBUGBOX(char * args) { + while (*args == ' ') args++; + std::string argv=std::string(args); + args=StripArg(args); + HELP("DEBUGBOX"); + /* TODO: The command as originally taken from DOSBox SVN supported a /NOMOUSE option to remove the INT 33h vector */ + if (!*args) { + tohide=false; + DEBUG_Enable_Handler(true); + tohide=true; + return; + } else if (!strcmp(args,"-?")) { + args[0]='/'; + HELP("DEBUGBOX"); + return; + } + debugger_break_on_exec = true; + DoCommand((char *)argv.c_str()); + debugger_break_on_exec = false; + } + #endif + + char *str_replace(const char *orig, const char *rep, const char *with) { + char *result, *ins, *tmp; + size_t len_rep, len_with, len_front; + int count; + + if (!orig || !rep) return NULL; + + char* mutable_orig = strdup(orig); // Make a mutable copy of orig + char* original_mutable_orig = mutable_orig; // Store the original address for freeing below + + len_rep = strlen(rep); + if (len_rep == 0) return NULL; + len_with = with?strlen(with):0; + + ins = mutable_orig; + for (count = 0; (tmp = strstr(ins, rep)) != NULL; ++count) + ins = tmp + len_rep; + + tmp = result = (char *)malloc(strlen(mutable_orig) + (len_with - len_rep) * count + 1); + if (!result) return NULL; + + while (count--) { + ins = strstr(mutable_orig, rep); + len_front = ins - mutable_orig; + tmp = strncpy(tmp, mutable_orig, len_front) + len_front; + tmp = strcpy(tmp, with?with:"") + len_with; + mutable_orig += len_front + len_rep; + } + strcpy(tmp, mutable_orig); + free(original_mutable_orig); + return result; + } + + void DOS_Shell::CMD_FOR(char *args) { + HELP("FOR"); + args = ltrim(args); + if (strlen(args)<12){SyntaxError();return;} + char s[3]; + strcpy(s,"%%"); + if (*args=='%' && (isalpha(args[1]) || isdigit(args[1]) || strchr("_-/*.;#$",args[1])) && isspace(args[2])) + s[1]=*(args+1); + else{SyntaxError();return;} + args = ltrim(args+3); + if (strncasecmp(args, "IN", 2) || !isspace(args[2])){SyntaxError();return;} + args = ltrim(args+3); + if (*args=='(') + args = ltrim(args+1); + else{SyntaxError();return;} + char *p=strchr(args, ')'); + if (p==NULL||!isspace(*(p+1))){SyntaxError();return;} + *p=0; + char flist[260], *fp=flist; + if (strlen(ltrim(args))<260) + strcpy(flist, ltrim(args)); + else + { + strncpy(flist, args, 259); + flist[259]=0; + } + *p=')'; + args=ltrim(p+2); + if (strncasecmp(args, "DO", 2) || !isspace(args[2])){SyntaxError();return;} + args = ltrim(args+3); + bool lfn=uselfn&&lfnfor; + while (*fp) { + p=fp; + int q=0; + while (*p&&(q/2*2!=q||(*p!=' '&&*p!=','&&*p!=';'))) + { + if (*p=='"') + q++; + p++; + } + bool last=!!strlen(p); + if (last) *p=0; + if (strchr(fp, '?') || strchr(fp, '*')) { + char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH], spath[DOS_PATHLENGTH], path[DOS_PATHLENGTH], pattern[DOS_PATHLENGTH], full[DOS_PATHLENGTH], *r; + if (!DOS_Canonicalize(fp,full)) return; + r=strrchr_dbcs(full, '\\'); + if (r!=NULL) { + *r=0; + strcpy(path, full); + strcat(path, "\\"); + strcpy(pattern, r+1); + *r='\\'; + } else { + strcpy(path, ""); + strcpy(pattern, full); + } + strcpy(spath, path); + if (strchr(fp,'\"')||uselfn) { + if (!DOS_GetSFNPath(("\""+std::string(path)+"\\").c_str(), spath, false)) strcpy(spath, path); + if (!strlen(spath)||spath[strlen(spath)-1]!='\\') strcat(spath, "\\"); + int k=0; + for (int i=0;i<(int)strlen(path);i++) + if (path[i]!='\"') + path[k++]=path[i]; + path[k]=0; + } + uint32_t size, hsize; + uint16_t date, time; + uint8_t attr; + DOS_DTA dta(dos.dta()); + std::vector sources; + std::string tmp; + int fbak=lfn_filefind_handle; + lfn_filefind_handle=lfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; + if (DOS_FindFirst((std::string(spath)+std::string(pattern)).c_str(), ~(DOS_ATTR_VOLUME|DOS_ATTR_DIRECTORY|DOS_ATTR_DEVICE|DOS_ATTR_HIDDEN|DOS_ATTR_SYSTEM))) + { + dta.GetResult(name, lname, size, hsize, date, time, attr); + tmp=std::string(path)+std::string(lfn?lname:name); + sources.push_back(tmp); + while (DOS_FindNext()) + { + dta.GetResult(name, lname, size, hsize, date, time, attr); + tmp=std::string(path)+std::string(lfn?lname:name); + sources.push_back(tmp); + } + } + lfn_filefind_handle=fbak; + for (std::vector::iterator source = sources.begin(); source != sources.end(); ++source) + DoCommand(str_replace(args, s, source->c_str())); + } else + DoCommand(str_replace(args, s, fp)); + if (last) *p=' '; + fp=ltrim(p); + } + } + + void DOS_Shell::CMD_LFNFOR(char * args) { + HELP("LFNFOR"); + args = trim(args); + if (!*args) + WriteOut("LFNFOR is %s\n", lfnfor ? "on" : "off"); + else if (!strcasecmp(args, "OFF")) + lfnfor = false; + else if (!strcasecmp(args, "ON")) + lfnfor = true; + else + WriteOut("Must specify ON or OFF\n"); + } + + void DOS_Shell::CMD_ALIAS(char* args) { + HELP("ALIAS"); + args = trim(args); + if (!*args || strchr(args, '=') == NULL) { + for (cmd_alias_map_t::iterator iter = cmd_alias.begin(), end = cmd_alias.end(); iter != end; ++iter) { + if (!*args || !strcasecmp(args, iter->first.c_str())) + WriteOut("ALIAS %s='%s'\n", iter->first.c_str(), iter->second.c_str()); + } + } else { + char alias_name[256] = { 0 }; + for (unsigned int offset = 0; *args && offset < sizeof(alias_name)-1; ++offset, ++args) { + if (*args == '=') { + char * const cmd = trim(alias_name); + ++args; + args = trim(args); + size_t args_len = strlen(args); + if ((*args == '"' && args[args_len - 1] == '"') || (*args == '\'' && args[args_len - 1] == '\'')) { + args[args_len - 1] = 0; + ++args; + } + if (!*args) { + cmd_alias.erase(cmd); + } else { + cmd_alias[cmd] = args; + cmd_alias_map_t::iterator iter = cmd_alias.find(cmd); + if (iter != cmd_alias.end()) WriteOut("ALIAS %s='%s'\n", iter->first.c_str(), iter->second.c_str()); + } + break; + } else { + alias_name[offset] = *args; + } + } + } + } + + void DOS_Shell::CMD_ASSOC(char* args) { + HELP("ASSOC"); + args = trim(args); + if (!*args || strchr(args, '=') == NULL) { + for (cmd_assoc_map_t::iterator iter = cmd_assoc.begin(), end = cmd_assoc.end(); iter != end; ++iter) { + if (!*args || !strcasecmp(args, iter->first.c_str())) + WriteOut("%s=%s\n", iter->first.c_str(), iter->second.c_str()); + } + } else { + char assoc_name[256] = { 0 }; + for (unsigned int offset = 0; *args && offset < sizeof(assoc_name)-1; ++offset, ++args) { + if (*args == '=') { + char * const cmd = trim(assoc_name); + if (!*cmd || cmd[0] != '.') { + WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), cmd); + break; + } + ++args; + args = trim(args); + size_t args_len = strlen(args); + if ((*args == '"' && args[args_len - 1] == '"') || (*args == '\'' && args[args_len - 1] == '\'')) { + args[args_len - 1] = 0; + ++args; + } + if (!*args) { + cmd_assoc.erase(cmd); + } else { + cmd_assoc[cmd] = args; + cmd_assoc_map_t::iterator iter = cmd_assoc.find(cmd); + if (iter != cmd_assoc.end()) WriteOut("%s=%s\n", iter->first.c_str(), iter->second.c_str()); + } + break; + } else { + assoc_name[offset] = *args; + } + } + } + } + + void DOS_Shell::CMD_HISTORY(char* args) { + HELP("HISTORY"); + if (ScanCMDBool(args,"C")) + l_history.clear(); + for (auto it = l_history.rbegin(); it != l_history.rend(); ++it) { + WriteOut_NoParsing(it->c_str(), true); + WriteOut("\n"); + } + } + + void CAPTURE_StartCapture(void); + void CAPTURE_StopCapture(void); + + void CAPTURE_StartWave(void); + void CAPTURE_StopWave(void); + + void CAPTURE_StartMTWave(void); + void CAPTURE_StopMTWave(void); + + void CAPTURE_StartOPL(void); + void CAPTURE_StopOPL(void); + + // Explanation: Start capture, run program, stop capture when program exits. + // Great for gameplay footage or demoscene capture. + // + // The command name is chosen not to conform to the 8.3 pattern + // on purpose to avoid conflicts with any existing DOS applications. + void DOS_Shell::CMD_DXCAPTURE(char * args) { + while (*args == ' ') args++; + std::string argv=std::string(args); + args=StripArg(args); + HELP("DXCAPTURE"); + bool cap_video = false; + bool cap_audio = false; + bool cap_mtaudio = false; + bool cap_opl = false; + unsigned long post_exit_delay_ms = 3000; /* 3 sec */ + + if (!strcmp(args,"-?")) { + args[0]='/'; + HELP("DXCAPTURE"); + return; + } + + args=(char *)argv.c_str(); + char *arg1; + while (strlen(args)&&args[0]=='/') { + arg1=StripArg(args); + upcase(arg1); + if (!(strcmp(arg1,"/V"))) + cap_video = true; + else if (!(strcmp(arg1,"/-V"))) + cap_video = false; + else if (!(strcmp(arg1,"/A"))) + cap_audio = true; + else if (!(strcmp(arg1,"/O"))) + cap_opl = true; + else if (!(strcmp(arg1,"/-A"))) + cap_audio = false; + else if (!(strcmp(arg1,"/-O"))) + cap_opl = false; + else if (!(strcmp(arg1,"/M"))) + cap_mtaudio = true; + else if (!(strcmp(arg1,"/-M"))) + cap_mtaudio = false; + else { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"),arg1); + return; + } + } + + if (!cap_video && !cap_audio && !cap_mtaudio && !cap_opl) + cap_video = true; + + if (cap_video) + CAPTURE_StartCapture(); + if (cap_audio) + CAPTURE_StartWave(); + if (cap_mtaudio) + CAPTURE_StartMTWave(); + if (cap_opl) + CAPTURE_StartOPL(); + + DoCommand(args); + + if (post_exit_delay_ms > 0) { + LOG_MSG("Pausing for post exit delay (%.3f seconds)",(double)post_exit_delay_ms / 1000); + + uint32_t lasttick=GetTicks(); + while ((GetTicks()-lasttick)0) { + countryNo = newCC; + DOS_SetCountry(countryNo); + return; + } + WriteOut("Invalid country code - %s\n", StripArg(args)); + return; + } + + extern bool jfont_init, finish_prepare, isDBCSCP(); + extern Bitu DOS_LoadKeyboardLayout(const char * layoutname, int32_t codepage, const char * codepagefile); + void runRescan(const char *str), MSG_Init(), JFONT_Init(), InitFontHandle(), ShutFontHandle(), initcodepagefont(), DOSBox_SetSysMenu(); + int toSetCodePage(DOS_Shell *shell, int newCP, int opt) { + if((TTF_using() && isSupportedCP(newCP)) || !TTF_using()) { + int32_t oldcp = dos.loaded_codepage, cpbak = newCP; + Bitu keyb_error; + if(IS_PC98_ARCH || IS_JEGA_ARCH) newCP = 932; + else if(IS_DOSV) { + if(IS_JDOSV) newCP = 932; + else if(IS_PDOSV) newCP = 936; + else if(IS_KDOSV) newCP = 949; + else if(IS_TDOSV) newCP = 950; + } + else if (!CheckDBCSCP(newCP)){ + keyb_error = DOS_ChangeCodepage(newCP, "auto"); + if (keyb_error != KEYB_NOERROR) { + dos.loaded_codepage = oldcp; + return -1; + } + } + if(newCP != cpbak) LOG_MSG("SHELL: Invalid codepage %d, set to %d.", cpbak, newCP); + dos.loaded_codepage = newCP; + int missing = 0; + #if defined(USE_TTF) + missing = TTF_using() ? setTTFCodePage() : 0; + #endif + if (!TTF_using()) initcodepagefont(); + if (opt==-1) { + MSG_Init(); + #if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU + mainMenu.unbuild(); + mainMenu.rebuild(); + if (!GFX_GetPreventFullscreen()) { + if (menu.toggle) DOSBox_SetMenu(); else DOSBox_NoMenu(); + } + #endif + DOSBox_SetSysMenu(); + } + if(isDBCSCP()) { + ShutFontHandle(); + InitFontHandle(); + JFONT_Init(); + SetupDBCSTable(); + if(newCP == 950 && !chinasea) makestdcp950table(); + if(newCP == 951 && chinasea) makeseacp951table(); + } + if (finish_prepare) runRescan("-A -Q"); + #if C_OPENGL && DOSBOXMENU_TYPE == DOSBOXMENU_SDLDRAW + if(OpenGL_using() && control->opt_lang.size()) + UpdateSDLDrawTexture(); + #endif + #if defined(USE_TTF) + if ((opt==-1||opt==-2)&&TTF_using()) { + Section_prop * ttf_section = static_cast(control->GetSection("ttf")); + const char *font = ttf_section->Get_string("font"); + if (!font || !*font) { + ttf_reset(); + #if C_PRINTER + if (printfont) UpdateDefaultPrinterFont(); + #endif + } + } + #endif + if(newCP != lastsetcp) { + LOG_MSG("Codepage set to %d", newCP); + lastsetcp = newCP; + } + return missing; + } else if (opt<1 && shell) { + shell->WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), std::to_string(newCP).c_str()); + } + return -1; + } + + const char* DOS_GetLoadedLayout(void); + Bitu DOS_ChangeCodepage(int32_t codepage, const char* codepagefile); + Bitu DOS_ChangeKeyboardLayout(const char* layoutname, int32_t codepage); + + void DOS_Shell::CMD_CHCP(char * args) { + HELP("CHCP"); + args = trim(args); + if (!*args) { + WriteOut(MSG_Get("SHELL_CMD_CHCP_ACTIVE"), dos.loaded_codepage); + return; + } + if (IS_PC98_ARCH || IS_JEGA_ARCH) { + WriteOut("Changing code page is not supported for the PC-98 or JEGA/AX system.\n"); + return; + } + if (IS_DOSV || IS_J3100) + { + WriteOut("Changing code page is not supported for the DOS/V or J-3100 system.\n"); + return; + } + int32_t newCP; + char buff[256], *r; + int missing = 0, n = sscanf(args, "%d%s", &newCP, buff); + auto iter = langcp_map.find(newCP); + const char* layout_name = DOS_GetLoadedLayout(); + int32_t cp = dos.loaded_codepage; + Bitu keyb_error; + if(n == 1) { + if (!TTF_using() || (TTF_using() && isSupportedCP(newCP))){ + bool load_language = SwitchLanguage(cp, newCP, true); + CHCP_changed = true; + missing = toSetCodePage(this, newCP, load_language ? -1: -2); + if(missing > 0) WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); + else if(missing < 0) { + WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); + CHCP_changed = false; + return; + } + } + else { + if(TTF_using() && !isSupportedCP(newCP)) { + WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); + LOG_MSG("CHCP: Codepage %d not supported for TTF output", newCP); + } + else { + WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); + } + CHCP_changed = false; + return; + } + CHCP_changed = false; + WriteOut(MSG_Get("SHELL_CMD_CHCP_ACTIVE"), dos.loaded_codepage); + } + else if(n == 2 && strlen(buff)) { + if(*buff == ':' && strchr(StripArg(args), ':')) { + std::string name = buff + 1; + if(name.empty() && iter != langcp_map.end()) name = iter->second; + if(!TTF_using() || (TTF_using() && isSupportedCP(newCP))) { + CHCP_changed = true; + missing = toSetCodePage(this, newCP, -1); + if(missing > 0) WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); + else if(missing < 0) { + WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); + CHCP_changed = false; + return; + } + } + if(name.size() && dos.loaded_codepage == newCP) { + SetVal("dosbox", "language", name); + Load_Language(name); + } + WriteOut(MSG_Get("SHELL_CMD_CHCP_ACTIVE"), dos.loaded_codepage); + CHCP_changed = false; + return; + } + #if defined(USE_TTF) + if(ttf.inUse) { + if(isSupportedCP(newCP)) { + missing = toSetCodePage(this, newCP, -1); + if(missing > -1) SwitchLanguage(cp, newCP, true); + if(missing > 0) WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); + LOG_MSG("CHCP: Loading cpi/cpx files ignored for TTF output"); + } + else { + WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); + LOG_MSG("CHCP: Codepage %d not supported for TTF output", newCP); + return; + } + } + else { + #endif + altcp = 0; + for(int i = 0; i < 256; i++) altcp_to_unicode[i] = 0; + std::string cpfile = buff; + FILE* file = fopen(cpfile.c_str(), "r"); /* should check the result */ + std::string exepath = GetDOSBoxXPath(); + if(!file && exepath.size()) file = fopen((exepath + CROSS_FILESPLIT + cpfile).c_str(), "r"); + if(file && newCP > 0 && !CheckDBCSCP(newCP)) { + altcp = newCP; + char line[256], * l = line; + while(fgets(line, sizeof(line), file)) { + l = trim(l); + if(!strlen(l)) continue; + r = strchr(l, '#'); + if(r) *r = 0; + l = trim(l); + if(!strlen(l) || strncasecmp(l, "0x", 2)) continue; + r = strchr(l, ' '); + if(!r) r = strchr(l, '\t'); + if(!r) continue; + *r = 0; + int ind = (int)strtol(l + 2, NULL, 16); + r = trim(r + 1); + if(ind > 0xFF || strncasecmp(r, "0x", 2)) continue; + int map = (int)strtol(r + 2, NULL, 16); + altcp_to_unicode[ind] = map; + } + if(file) fclose(file); + keyb_error = DOS_ChangeCodepage(newCP, cpfile.c_str()); + if(keyb_error == KEYB_NOERROR) { + if(layout_name != NULL) { + keyb_error = DOS_ChangeKeyboardLayout(layout_name, cp); + } + } + WriteOut(MSG_Get("SHELL_CMD_CHCP_ACTIVE"), dos.loaded_codepage); + #if defined(USE_TTF) + if(missing > 0) WriteOut(MSG_Get("SHELL_CMD_CHCP_MISSING"), missing); + #endif + } + else + WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); + if(file) fclose(file); + #if defined(USE_TTF) + } + #endif + } + else WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), StripArg(args)); + return; + } + + void DOS_Shell::CMD_VTEXT(char *args) + { + HELP("VTEXT"); + if (!IS_DOSV) { + WriteOut("This command is only supported in DOS/V mode.\n"); + return; + } + if (char* rem = ScanCMDRemain(args)) { + WriteOut(MSG_Get("SHELL_ILLEGAL_SWITCH"), rem); + return; + } + args = trim(args); + if(args && *args) { + uint8_t new_mode = 0xff; + char *word = StripWord(args); + if(!strcasecmp(word, "1")) + new_mode = 0x70; + else if(!strcasecmp(word, "2")) + new_mode = 0x78; + else if(!strcasecmp(word, "0")) + new_mode = 0x03; + else { + WriteOut(MSG_Get("SHELL_INVALID_PARAMETER"), word); + return; + } + if(new_mode != 0xff) { + uint16_t oldax=reg_ax; + reg_ax = new_mode; + CALLBACK_RunRealInt(0x10); + if(new_mode == 0x78) new_mode = 0x70; + reg_ax = oldax; + } + } + uint8_t mode = real_readb(BIOSMEM_SEG, BIOSMEM_CURRENT_MODE); + WriteOut(MSG_Get(mode == 0x70?"SHELL_CMD_VTEXT_ON":"SHELL_CMD_VTEXT_OFF")); + } + \ No newline at end of file diff --git a/third_party/SDL2/LICENSE.txt b/third_party/SDL2/LICENSE.txt new file mode 100644 index 00000000000..23abb73f2b6 --- /dev/null +++ b/third_party/SDL2/LICENSE.txt @@ -0,0 +1,18 @@ +Copyright (C) 1997-2025 Sam Lantinga + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/third_party/SDL2/README.md b/third_party/SDL2/README.md new file mode 100644 index 00000000000..fa7f7ba0b57 --- /dev/null +++ b/third_party/SDL2/README.md @@ -0,0 +1,17 @@ + +# Simple DirectMedia Layer (SDL) Version 2.0 + +https://www.libsdl.org/ + +Simple DirectMedia Layer is a cross-platform development library designed +to provide low level access to audio, keyboard, mouse, joystick, and graphics +hardware via OpenGL and Direct3D. It is used by video playback software, +emulators, and popular games including Valve's award winning catalog +and many Humble Bundle games. + +More extensive documentation is available in the docs directory, starting +with README.md + +Enjoy! + +Sam Lantinga (slouken@libsdl.org) diff --git a/third_party/SDL2/configure.txt b/third_party/SDL2/configure.txt new file mode 100644 index 00000000000..6e8f3137c82 --- /dev/null +++ b/third_party/SDL2/configure.txt @@ -0,0 +1 @@ +./configure --disable-sensor --disable-filesystem --disable-power --disable-file --disable-misc --disable-locale --disable-alsa --disable-esd --disable-jack --disable-pipewire --disable-pulseaudio --disable-arts --disable-nas --disable-sndio --disable-fusionsound --disable-diskaudio --enable-dummyaudio --disable-libsamplerate --disable-video-wayland --disable-libdecor --disable-video-rpi --disable-video-x11 --disable-video-vivante --disable-video-cocoa --disable-video-metal --disable-render-metal --disable-video-directfb --disable-video-kmsdrm --disable-kmsdrm-shared --disable-video-dummy --disable-video-offscreen --disable-video-opengl --disable-video-opengles --disable-video-opengles1 --disable-video-opengles2 --disable-video-vulkan --disable-libudev --disable-dbus --disable-ime --disable-ibus --disable-fcitx --disable-joystick-mfi --disable-pthreads --disable-pthread-sem --disable-directx --disable-xinput --disable-wasapi --disable-hidapi-joystick --disable-mmx --disable-3dnow --disable-sse --disable-sse2 --disable-sse3 --disable-altivec --disable-lsx --disable-oss --enable-video-dummy diff --git a/third_party/SDL2/include/SDL.h b/third_party/SDL2/include/SDL.h new file mode 100644 index 00000000000..0fe0713391a --- /dev/null +++ b/third_party/SDL2/include/SDL.h @@ -0,0 +1,234 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * \file SDL.h + * + * Main include header for the SDL library + */ + +#ifndef SDL_h_ +#define SDL_h_ + +#include "SDL_main.h" +#include "SDL_stdinc.h" +#include "SDL_assert.h" +#include "SDL_atomic.h" +#include "SDL_audio.h" +#include "SDL_clipboard.h" +#include "SDL_cpuinfo.h" +#include "SDL_endian.h" +#include "SDL_error.h" +#include "SDL_events.h" +#include "SDL_filesystem.h" +#include "SDL_gamecontroller.h" +#include "SDL_guid.h" +#include "SDL_haptic.h" +#include "SDL_hidapi.h" +#include "SDL_hints.h" +#include "SDL_joystick.h" +#include "SDL_loadso.h" +#include "SDL_log.h" +#include "SDL_messagebox.h" +#include "SDL_metal.h" +#include "SDL_mutex.h" +#include "SDL_power.h" +#include "SDL_render.h" +#include "SDL_rwops.h" +#include "SDL_sensor.h" +#include "SDL_shape.h" +#include "SDL_system.h" +#include "SDL_thread.h" +#include "SDL_timer.h" +#include "SDL_version.h" +#include "SDL_video.h" +#include "SDL_locale.h" +#include "SDL_misc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* WIKI CATEGORY: Init */ + +/* As of version 0.5, SDL is loaded dynamically into the application */ + +/** + * \name SDL_INIT_* + * + * These are the flags which may be passed to SDL_Init(). You should + * specify the subsystems which you will be using in your application. + */ +/* @{ */ +#define SDL_INIT_TIMER 0x00000001u +#define SDL_INIT_AUDIO 0x00000010u +#define SDL_INIT_VIDEO 0x00000020u /**< SDL_INIT_VIDEO implies SDL_INIT_EVENTS */ +#define SDL_INIT_JOYSTICK 0x00000200u /**< SDL_INIT_JOYSTICK implies SDL_INIT_EVENTS */ +#define SDL_INIT_HAPTIC 0x00001000u +#define SDL_INIT_GAMECONTROLLER 0x00002000u /**< SDL_INIT_GAMECONTROLLER implies SDL_INIT_JOYSTICK */ +#define SDL_INIT_EVENTS 0x00004000u +#define SDL_INIT_SENSOR 0x00008000u +#define SDL_INIT_NOPARACHUTE 0x00100000u /**< compatibility; this flag is ignored. */ +#define SDL_INIT_EVERYTHING ( \ + SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_EVENTS | \ + SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC | SDL_INIT_GAMECONTROLLER | SDL_INIT_SENSOR \ + ) +/* @} */ + +/** + * Initialize the SDL library. + * + * SDL_Init() simply forwards to calling SDL_InitSubSystem(). Therefore, the + * two may be used interchangeably. Though for readability of your code + * SDL_InitSubSystem() might be preferred. + * + * The file I/O (for example: SDL_RWFromFile) and threading (SDL_CreateThread) + * subsystems are initialized by default. Message boxes + * (SDL_ShowSimpleMessageBox) also attempt to work without initializing the + * video subsystem, in hopes of being useful in showing an error dialog when + * SDL_Init fails. You must specifically initialize other subsystems if you + * use them in your application. + * + * Logging (such as SDL_Log) works without initialization, too. + * + * `flags` may be any of the following OR'd together: + * + * - `SDL_INIT_TIMER`: timer subsystem + * - `SDL_INIT_AUDIO`: audio subsystem + * - `SDL_INIT_VIDEO`: video subsystem; automatically initializes the events + * subsystem + * - `SDL_INIT_JOYSTICK`: joystick subsystem; automatically initializes the + * events subsystem + * - `SDL_INIT_HAPTIC`: haptic (force feedback) subsystem + * - `SDL_INIT_GAMECONTROLLER`: controller subsystem; automatically + * initializes the joystick subsystem + * - `SDL_INIT_EVENTS`: events subsystem + * - `SDL_INIT_EVERYTHING`: all of the above subsystems + * - `SDL_INIT_NOPARACHUTE`: compatibility; this flag is ignored + * + * Subsystem initialization is ref-counted, you must call SDL_QuitSubSystem() + * for each SDL_InitSubSystem() to correctly shutdown a subsystem manually (or + * call SDL_Quit() to force shutdown). If a subsystem is already loaded then + * this call will increase the ref-count and return. + * + * \param flags subsystem initialization flags. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_InitSubSystem + * \sa SDL_Quit + * \sa SDL_SetMainReady + * \sa SDL_WasInit + */ +extern DECLSPEC int SDLCALL SDL_Init(Uint32 flags); + +/** + * Compatibility function to initialize the SDL library. + * + * In SDL2, this function and SDL_Init() are interchangeable. + * + * \param flags any of the flags used by SDL_Init(); see SDL_Init for details. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Init + * \sa SDL_Quit + * \sa SDL_QuitSubSystem + */ +extern DECLSPEC int SDLCALL SDL_InitSubSystem(Uint32 flags); + +/** + * Shut down specific SDL subsystems. + * + * If you start a subsystem using a call to that subsystem's init function + * (for example SDL_VideoInit()) instead of SDL_Init() or SDL_InitSubSystem(), + * SDL_QuitSubSystem() and SDL_WasInit() will not work. You will need to use + * that subsystem's quit function (SDL_VideoQuit()) directly instead. But + * generally, you should not be using those functions directly anyhow; use + * SDL_Init() instead. + * + * You still need to call SDL_Quit() even if you close all open subsystems + * with SDL_QuitSubSystem(). + * + * \param flags any of the flags used by SDL_Init(); see SDL_Init for details. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_InitSubSystem + * \sa SDL_Quit + */ +extern DECLSPEC void SDLCALL SDL_QuitSubSystem(Uint32 flags); + +/** + * Get a mask of the specified subsystems which are currently initialized. + * + * \param flags any of the flags used by SDL_Init(); see SDL_Init for details. + * \returns a mask of all initialized subsystems if `flags` is 0, otherwise it + * returns the initialization status of the specified subsystems. + * + * The return value does not include SDL_INIT_NOPARACHUTE. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Init + * \sa SDL_InitSubSystem + */ +extern DECLSPEC Uint32 SDLCALL SDL_WasInit(Uint32 flags); + +/** + * Clean up all initialized subsystems. + * + * You should call this function even if you have already shutdown each + * initialized subsystem with SDL_QuitSubSystem(). It is safe to call this + * function even in the case of errors in initialization. + * + * If you start a subsystem using a call to that subsystem's init function + * (for example SDL_VideoInit()) instead of SDL_Init() or SDL_InitSubSystem(), + * then you must use that subsystem's quit function (SDL_VideoQuit()) to shut + * it down before calling SDL_Quit(). But generally, you should not be using + * those functions directly anyhow; use SDL_Init() instead. + * + * You can use this function with atexit() to ensure that it is run when your + * application is shutdown, but it is not wise to do this from a library or + * other dynamically loaded code. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Init + * \sa SDL_QuitSubSystem + */ +extern DECLSPEC void SDLCALL SDL_Quit(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_assert.h b/third_party/SDL2/include/SDL_assert.h new file mode 100644 index 00000000000..fea3f90f040 --- /dev/null +++ b/third_party/SDL2/include/SDL_assert.h @@ -0,0 +1,324 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_assert_h_ +#define SDL_assert_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef SDL_ASSERT_LEVEL +#ifdef SDL_DEFAULT_ASSERT_LEVEL +#define SDL_ASSERT_LEVEL SDL_DEFAULT_ASSERT_LEVEL +#elif defined(_DEBUG) || defined(DEBUG) || \ + (defined(__GNUC__) && !defined(__OPTIMIZE__)) +#define SDL_ASSERT_LEVEL 2 +#else +#define SDL_ASSERT_LEVEL 1 +#endif +#endif /* SDL_ASSERT_LEVEL */ + +/* +These are macros and not first class functions so that the debugger breaks +on the assertion line and not in some random guts of SDL, and so each +assert can have unique static variables associated with it. +*/ + +#if defined(_MSC_VER) +/* Don't include intrin.h here because it contains C++ code */ + extern void __cdecl __debugbreak(void); + #define SDL_TriggerBreakpoint() __debugbreak() +#elif _SDL_HAS_BUILTIN(__builtin_debugtrap) + #define SDL_TriggerBreakpoint() __builtin_debugtrap() +#elif ( (!defined(__NACL__)) && ((defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))) ) + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "int $3\n\t" ) +#elif (defined(__GNUC__) || defined(__clang__)) && defined(__riscv) + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "ebreak\n\t" ) +#elif ( defined(__APPLE__) && (defined(__arm64__) || defined(__aarch64__)) ) /* this might work on other ARM targets, but this is a known quantity... */ + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "brk #22\n\t" ) +#elif defined(__APPLE__) && defined(__arm__) + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "bkpt #22\n\t" ) +#elif defined(_WIN32) && ((defined(__GNUC__) || defined(__clang__)) && (defined(__arm64__) || defined(__aarch64__)) ) + #define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "brk #0xF000\n\t" ) +#elif defined(__386__) && defined(__WATCOMC__) + #define SDL_TriggerBreakpoint() { _asm { int 0x03 } } +#elif defined(HAVE_SIGNAL_H) && !defined(__WATCOMC__) + #include + #define SDL_TriggerBreakpoint() raise(SIGTRAP) +#else + /* How do we trigger breakpoints on this platform? */ + #define SDL_TriggerBreakpoint() +#endif + +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 supports __func__ as a standard. */ +# define SDL_FUNCTION __func__ +#elif ((defined(__GNUC__) && (__GNUC__ >= 2)) || defined(_MSC_VER) || defined (__WATCOMC__)) +# define SDL_FUNCTION __FUNCTION__ +#else +# define SDL_FUNCTION "???" +#endif +#define SDL_FILE __FILE__ +#define SDL_LINE __LINE__ + +/* +sizeof (x) makes the compiler still parse the expression even without +assertions enabled, so the code is always checked at compile time, but +doesn't actually generate code for it, so there are no side effects or +expensive checks at run time, just the constant size of what x WOULD be, +which presumably gets optimized out as unused. +This also solves the problem of... + + int somevalue = blah(); + SDL_assert(somevalue == 1); + +...which would cause compiles to complain that somevalue is unused if we +disable assertions. +*/ + +/* "while (0,0)" fools Microsoft's compiler's /W4 warning level into thinking + this condition isn't constant. And looks like an owl's face! */ +#ifdef _MSC_VER /* stupid /W4 warnings. */ +#define SDL_NULL_WHILE_LOOP_CONDITION (0,0) +#else +#define SDL_NULL_WHILE_LOOP_CONDITION (0) +#endif + +#define SDL_disabled_assert(condition) \ + do { (void) sizeof ((condition)); } while (SDL_NULL_WHILE_LOOP_CONDITION) + +typedef enum +{ + SDL_ASSERTION_RETRY, /**< Retry the assert immediately. */ + SDL_ASSERTION_BREAK, /**< Make the debugger trigger a breakpoint. */ + SDL_ASSERTION_ABORT, /**< Terminate the program. */ + SDL_ASSERTION_IGNORE, /**< Ignore the assert. */ + SDL_ASSERTION_ALWAYS_IGNORE /**< Ignore the assert from now on. */ +} SDL_AssertState; + +typedef struct SDL_AssertData +{ + int always_ignore; + unsigned int trigger_count; + const char *condition; + const char *filename; + int linenum; + const char *function; + const struct SDL_AssertData *next; +} SDL_AssertData; + +/* Never call this directly. Use the SDL_assert* macros. */ +extern DECLSPEC SDL_AssertState SDLCALL SDL_ReportAssertion(SDL_AssertData *, + const char *, + const char *, int) +#if defined(__clang__) +#if __has_feature(attribute_analyzer_noreturn) +/* this tells Clang's static analysis that we're a custom assert function, + and that the analyzer should assume the condition was always true past this + SDL_assert test. */ + __attribute__((analyzer_noreturn)) +#endif +#endif +; + +/* the do {} while(0) avoids dangling else problems: + if (x) SDL_assert(y); else blah(); + ... without the do/while, the "else" could attach to this macro's "if". + We try to handle just the minimum we need here in a macro...the loop, + the static vars, and break points. The heavy lifting is handled in + SDL_ReportAssertion(), in SDL_assert.c. +*/ +#define SDL_enabled_assert(condition) \ + do { \ + while ( !(condition) ) { \ + static struct SDL_AssertData sdl_assert_data = { 0, 0, #condition, 0, 0, 0, 0 }; \ + const SDL_AssertState sdl_assert_state = SDL_ReportAssertion(&sdl_assert_data, SDL_FUNCTION, SDL_FILE, SDL_LINE); \ + if (sdl_assert_state == SDL_ASSERTION_RETRY) { \ + continue; /* go again. */ \ + } else if (sdl_assert_state == SDL_ASSERTION_BREAK) { \ + SDL_TriggerBreakpoint(); \ + } \ + break; /* not retrying. */ \ + } \ + } while (SDL_NULL_WHILE_LOOP_CONDITION) + +/* Enable various levels of assertions. */ +#if SDL_ASSERT_LEVEL == 0 /* assertions disabled */ +# define SDL_assert(condition) SDL_disabled_assert(condition) +# define SDL_assert_release(condition) SDL_disabled_assert(condition) +# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition) +#elif SDL_ASSERT_LEVEL == 1 /* release settings. */ +# define SDL_assert(condition) SDL_disabled_assert(condition) +# define SDL_assert_release(condition) SDL_enabled_assert(condition) +# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition) +#elif SDL_ASSERT_LEVEL == 2 /* normal settings. */ +# define SDL_assert(condition) SDL_enabled_assert(condition) +# define SDL_assert_release(condition) SDL_enabled_assert(condition) +# define SDL_assert_paranoid(condition) SDL_disabled_assert(condition) +#elif SDL_ASSERT_LEVEL == 3 /* paranoid settings. */ +# define SDL_assert(condition) SDL_enabled_assert(condition) +# define SDL_assert_release(condition) SDL_enabled_assert(condition) +# define SDL_assert_paranoid(condition) SDL_enabled_assert(condition) +#else +# error Unknown assertion level. +#endif + +/* this assertion is never disabled at any level. */ +#define SDL_assert_always(condition) SDL_enabled_assert(condition) + + +/** + * A callback that fires when an SDL assertion fails. + * + * \param data a pointer to the SDL_AssertData structure corresponding to the + * current assertion. + * \param userdata what was passed as `userdata` to SDL_SetAssertionHandler(). + * \returns an SDL_AssertState value indicating how to handle the failure. + */ +typedef SDL_AssertState (SDLCALL *SDL_AssertionHandler)( + const SDL_AssertData* data, void* userdata); + +/** + * Set an application-defined assertion handler. + * + * This function allows an application to show its own assertion UI and/or + * force the response to an assertion failure. If the application doesn't + * provide this, SDL will try to do the right thing, popping up a + * system-specific GUI dialog, and probably minimizing any fullscreen windows. + * + * This callback may fire from any thread, but it runs wrapped in a mutex, so + * it will only fire from one thread at a time. + * + * This callback is NOT reset to SDL's internal handler upon SDL_Quit()! + * + * \param handler the SDL_AssertionHandler function to call when an assertion + * fails or NULL for the default handler. + * \param userdata a pointer that is passed to `handler`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetAssertionHandler + */ +extern DECLSPEC void SDLCALL SDL_SetAssertionHandler( + SDL_AssertionHandler handler, + void *userdata); + +/** + * Get the default assertion handler. + * + * This returns the function pointer that is called by default when an + * assertion is triggered. This is an internal function provided by SDL, that + * is used for assertions when SDL_SetAssertionHandler() hasn't been used to + * provide a different function. + * + * \returns the default SDL_AssertionHandler that is called when an assert + * triggers. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_GetAssertionHandler + */ +extern DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetDefaultAssertionHandler(void); + +/** + * Get the current assertion handler. + * + * This returns the function pointer that is called when an assertion is + * triggered. This is either the value last passed to + * SDL_SetAssertionHandler(), or if no application-specified function is set, + * is equivalent to calling SDL_GetDefaultAssertionHandler(). + * + * The parameter `puserdata` is a pointer to a void*, which will store the + * "userdata" pointer that was passed to SDL_SetAssertionHandler(). This value + * will always be NULL for the default handler. If you don't care about this + * data, it is safe to pass a NULL pointer to this function to ignore it. + * + * \param puserdata pointer which is filled with the "userdata" pointer that + * was passed to SDL_SetAssertionHandler(). + * \returns the SDL_AssertionHandler that is called when an assert triggers. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_SetAssertionHandler + */ +extern DECLSPEC SDL_AssertionHandler SDLCALL SDL_GetAssertionHandler(void **puserdata); + +/** + * Get a list of all assertion failures. + * + * This function gets all assertions triggered since the last call to + * SDL_ResetAssertionReport(), or the start of the program. + * + * The proper way to examine this data looks something like this: + * + * ```c + * const SDL_AssertData *item = SDL_GetAssertionReport(); + * while (item) { + * printf("'%s', %s (%s:%d), triggered %u times, always ignore: %s.\\n", + * item->condition, item->function, item->filename, + * item->linenum, item->trigger_count, + * item->always_ignore ? "yes" : "no"); + * item = item->next; + * } + * ``` + * + * \returns a list of all failed assertions or NULL if the list is empty. This + * memory should not be modified or freed by the application. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ResetAssertionReport + */ +extern DECLSPEC const SDL_AssertData * SDLCALL SDL_GetAssertionReport(void); + +/** + * Clear the list of all assertion failures. + * + * This function will clear the list of all assertions triggered up to that + * point. Immediately following this call, SDL_GetAssertionReport will return + * no items. In addition, any previously-triggered assertions will be reset to + * a trigger_count of zero, and their always_ignore state will be false. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetAssertionReport + */ +extern DECLSPEC void SDLCALL SDL_ResetAssertionReport(void); + + +/* these had wrong naming conventions until 2.0.4. Please update your app! */ +#define SDL_assert_state SDL_AssertState +#define SDL_assert_data SDL_AssertData + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_assert_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_atomic.h b/third_party/SDL2/include/SDL_atomic.h new file mode 100644 index 00000000000..226ec7c67f6 --- /dev/null +++ b/third_party/SDL2/include/SDL_atomic.h @@ -0,0 +1,408 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryAtomic + * + * Atomic operations. + * + * IMPORTANT: If you are not an expert in concurrent lockless programming, you + * should not be using any functions in this file. You should be protecting + * your data structures with full mutexes instead. + * + * ***Seriously, here be dragons!*** + * + * You can find out a little more about lockless programming and the subtle + * issues that can arise here: + * https://learn.microsoft.com/en-us/windows/win32/dxtecharts/lockless-programming + * + * There's also lots of good information here: + * + * - https://www.1024cores.net/home/lock-free-algorithms + * - https://preshing.com/ + * + * These operations may or may not actually be implemented using processor + * specific atomic operations. When possible they are implemented as true + * processor specific atomic operations. When that is not possible the are + * implemented using locks that *do* use the available atomic operations. + * + * All of the atomic operations that modify memory are full memory barriers. + */ + +#ifndef SDL_atomic_h_ +#define SDL_atomic_h_ + +#include "SDL_stdinc.h" +#include "SDL_platform.h" + +#include "begin_code.h" + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \name SDL AtomicLock + * + * The atomic locks are efficient spinlocks using CPU instructions, + * but are vulnerable to starvation and can spin forever if a thread + * holding a lock has been terminated. For this reason you should + * minimize the code executed inside an atomic lock and never do + * expensive things like API or system calls while holding them. + * + * The atomic locks are not safe to lock recursively. + * + * Porting Note: + * The spin lock functions and type are required and can not be + * emulated because they are used in the atomic emulation code. + */ +/* @{ */ + +typedef int SDL_SpinLock; + +/** + * Try to lock a spin lock by setting it to a non-zero value. + * + * ***Please note that spinlocks are dangerous if you don't know what you're + * doing. Please be careful using any sort of spinlock!*** + * + * \param lock a pointer to a lock variable. + * \returns SDL_TRUE if the lock succeeded, SDL_FALSE if the lock is already + * held. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AtomicLock + * \sa SDL_AtomicUnlock + */ +extern DECLSPEC SDL_bool SDLCALL SDL_AtomicTryLock(SDL_SpinLock *lock); + +/** + * Lock a spin lock by setting it to a non-zero value. + * + * ***Please note that spinlocks are dangerous if you don't know what you're + * doing. Please be careful using any sort of spinlock!*** + * + * \param lock a pointer to a lock variable. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AtomicTryLock + * \sa SDL_AtomicUnlock + */ +extern DECLSPEC void SDLCALL SDL_AtomicLock(SDL_SpinLock *lock); + +/** + * Unlock a spin lock by setting it to 0. + * + * Always returns immediately. + * + * ***Please note that spinlocks are dangerous if you don't know what you're + * doing. Please be careful using any sort of spinlock!*** + * + * \param lock a pointer to a lock variable. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AtomicLock + * \sa SDL_AtomicTryLock + */ +extern DECLSPEC void SDLCALL SDL_AtomicUnlock(SDL_SpinLock *lock); + +/* @} *//* SDL AtomicLock */ + + +/** + * The compiler barrier prevents the compiler from reordering + * reads and writes to globally visible variables across the call. + */ +#if defined(_MSC_VER) && (_MSC_VER > 1200) && !defined(__clang__) +void _ReadWriteBarrier(void); +#pragma intrinsic(_ReadWriteBarrier) +#define SDL_CompilerBarrier() _ReadWriteBarrier() +#elif (defined(__GNUC__) && !defined(__EMSCRIPTEN__)) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120)) +/* This is correct for all CPUs when using GCC or Solaris Studio 12.1+. */ +#define SDL_CompilerBarrier() __asm__ __volatile__ ("" : : : "memory") +#elif defined(__WATCOMC__) +extern __inline void SDL_CompilerBarrier(void); +#pragma aux SDL_CompilerBarrier = "" parm [] modify exact []; +#else +#define SDL_CompilerBarrier() \ +{ SDL_SpinLock _tmp = 0; SDL_AtomicLock(&_tmp); SDL_AtomicUnlock(&_tmp); } +#endif + +/** + * Memory barriers are designed to prevent reads and writes from being + * reordered by the compiler and being seen out of order on multi-core CPUs. + * + * A typical pattern would be for thread A to write some data and a flag, and + * for thread B to read the flag and get the data. In this case you would + * insert a release barrier between writing the data and the flag, + * guaranteeing that the data write completes no later than the flag is + * written, and you would insert an acquire barrier between reading the flag + * and reading the data, to ensure that all the reads associated with the flag + * have completed. + * + * In this pattern you should always see a release barrier paired with an + * acquire barrier and you should gate the data reads/writes with a single + * flag variable. + * + * For more information on these semantics, take a look at the blog post: + * http://preshing.com/20120913/acquire-and-release-semantics + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC void SDLCALL SDL_MemoryBarrierReleaseFunction(void); +extern DECLSPEC void SDLCALL SDL_MemoryBarrierAcquireFunction(void); + +#if defined(__GNUC__) && (defined(__powerpc__) || defined(__ppc__)) +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("lwsync" : : : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("lwsync" : : : "memory") +#elif defined(__GNUC__) && defined(__aarch64__) +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory") +#elif defined(__GNUC__) && defined(__arm__) +#if 0 /* defined(__LINUX__) || defined(__ANDROID__) */ +/* Information from: + https://chromium.googlesource.com/chromium/chromium/+/trunk/base/atomicops_internals_arm_gcc.h#19 + + The Linux kernel provides a helper function which provides the right code for a memory barrier, + hard-coded at address 0xffff0fa0 +*/ +typedef void (*SDL_KernelMemoryBarrierFunc)(); +#define SDL_MemoryBarrierRelease() ((SDL_KernelMemoryBarrierFunc)0xffff0fa0)() +#define SDL_MemoryBarrierAcquire() ((SDL_KernelMemoryBarrierFunc)0xffff0fa0)() +#elif 0 /* defined(__QNXNTO__) */ +#include + +#define SDL_MemoryBarrierRelease() __cpu_membarrier() +#define SDL_MemoryBarrierAcquire() __cpu_membarrier() +#else +#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) || defined(__ARM_ARCH_8A__) +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("dmb ish" : : : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("dmb ish" : : : "memory") +#elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6T2__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) +#ifdef __thumb__ +/* The mcr instruction isn't available in thumb mode, use real functions */ +#define SDL_MEMORY_BARRIER_USES_FUNCTION +#define SDL_MemoryBarrierRelease() SDL_MemoryBarrierReleaseFunction() +#define SDL_MemoryBarrierAcquire() SDL_MemoryBarrierAcquireFunction() +#else +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory") +#endif /* __thumb__ */ +#else +#define SDL_MemoryBarrierRelease() __asm__ __volatile__ ("" : : : "memory") +#define SDL_MemoryBarrierAcquire() __asm__ __volatile__ ("" : : : "memory") +#endif /* __LINUX__ || __ANDROID__ */ +#endif /* __GNUC__ && __arm__ */ +#else +#if (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x5120)) +/* This is correct for all CPUs on Solaris when using Solaris Studio 12.1+. */ +#include +#define SDL_MemoryBarrierRelease() __machine_rel_barrier() +#define SDL_MemoryBarrierAcquire() __machine_acq_barrier() +#else +/* This is correct for the x86 and x64 CPUs, and we'll expand this over time. */ +#define SDL_MemoryBarrierRelease() SDL_CompilerBarrier() +#define SDL_MemoryBarrierAcquire() SDL_CompilerBarrier() +#endif +#endif + +/* "REP NOP" is PAUSE, coded for tools that don't know it by that name. */ +#if (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) + #define SDL_CPUPauseInstruction() __asm__ __volatile__("pause\n") /* Some assemblers can't do REP NOP, so go with PAUSE. */ +#elif (defined(__arm__) && defined(__ARM_ARCH) && __ARM_ARCH >= 7) || defined(__aarch64__) + #define SDL_CPUPauseInstruction() __asm__ __volatile__("yield" ::: "memory") +#elif (defined(__powerpc__) || defined(__powerpc64__)) + #define SDL_CPUPauseInstruction() __asm__ __volatile__("or 27,27,27"); +#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) + #define SDL_CPUPauseInstruction() _mm_pause() /* this is actually "rep nop" and not a SIMD instruction. No inline asm in MSVC x86-64! */ +#elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) + #define SDL_CPUPauseInstruction() __yield() +#elif defined(__WATCOMC__) && defined(__386__) + extern __inline void SDL_CPUPauseInstruction(void); + #pragma aux SDL_CPUPauseInstruction = ".686p" ".xmm2" "pause" +#else + #define SDL_CPUPauseInstruction() +#endif + + +/** + * A type representing an atomic integer value. + * + * It is a struct so people don't accidentally use numeric operations on it. + */ +typedef struct SDL_atomic_t { + int value; +} SDL_atomic_t; + +/** + * Set an atomic variable to a new value if it is currently an old value. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_atomic_t variable to be modified. + * \param oldval the old value. + * \param newval the new value. + * \returns SDL_TRUE if the atomic variable was set, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AtomicCASPtr + * \sa SDL_AtomicGet + * \sa SDL_AtomicSet + */ +extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval); + +/** + * Set an atomic variable to a value. + * + * This function also acts as a full memory barrier. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_atomic_t variable to be modified. + * \param v the desired value. + * \returns the previous value of the atomic variable. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_AtomicGet + */ +extern DECLSPEC int SDLCALL SDL_AtomicSet(SDL_atomic_t *a, int v); + +/** + * Get the value of an atomic variable. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_atomic_t variable. + * \returns the current value of an atomic variable. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_AtomicSet + */ +extern DECLSPEC int SDLCALL SDL_AtomicGet(SDL_atomic_t *a); + +/** + * Add to an atomic variable. + * + * This function also acts as a full memory barrier. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to an SDL_atomic_t variable to be modified. + * \param v the desired value to add. + * \returns the previous value of the atomic variable. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_AtomicDecRef + * \sa SDL_AtomicIncRef + */ +extern DECLSPEC int SDLCALL SDL_AtomicAdd(SDL_atomic_t *a, int v); + +/** + * \brief Increment an atomic variable used as a reference count. + */ +#ifndef SDL_AtomicIncRef +#define SDL_AtomicIncRef(a) SDL_AtomicAdd(a, 1) +#endif + +/** + * \brief Decrement an atomic variable used as a reference count. + * + * \return SDL_TRUE if the variable reached zero after decrementing, + * SDL_FALSE otherwise + */ +#ifndef SDL_AtomicDecRef +#define SDL_AtomicDecRef(a) (SDL_AtomicAdd(a, -1) == 1) +#endif + +/** + * Set a pointer to a new value if it is currently an old value. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to a pointer. + * \param oldval the old pointer value. + * \param newval the new pointer value. + * \returns SDL_TRUE if the pointer was set, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AtomicCAS + * \sa SDL_AtomicGetPtr + * \sa SDL_AtomicSetPtr + */ +extern DECLSPEC SDL_bool SDLCALL SDL_AtomicCASPtr(void **a, void *oldval, void *newval); + +/** + * Set a pointer to a value atomically. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to a pointer. + * \param v the desired pointer value. + * \returns the previous value of the pointer. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_AtomicCASPtr + * \sa SDL_AtomicGetPtr + */ +extern DECLSPEC void* SDLCALL SDL_AtomicSetPtr(void **a, void* v); + +/** + * Get the value of a pointer atomically. + * + * ***Note: If you don't know what this function is for, you shouldn't use + * it!*** + * + * \param a a pointer to a pointer. + * \returns the current value of a pointer. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_AtomicCASPtr + * \sa SDL_AtomicSetPtr + */ +extern DECLSPEC void* SDLCALL SDL_AtomicGetPtr(void **a); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif + +#include "close_code.h" + +#endif /* SDL_atomic_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_audio.h b/third_party/SDL2/include/SDL_audio.h new file mode 100644 index 00000000000..cb76e93e43a --- /dev/null +++ b/third_party/SDL2/include/SDL_audio.h @@ -0,0 +1,1502 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* !!! FIXME: several functions in here need Doxygen comments. */ + +/** + * # CategoryAudio + * + * Access to the raw audio mixing buffer for the SDL library. + */ + +#ifndef SDL_audio_h_ +#define SDL_audio_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_endian.h" +#include "SDL_mutex.h" +#include "SDL_thread.h" +#include "SDL_rwops.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Audio format flags. + * + * These are what the 16 bits in SDL_AudioFormat currently mean... + * (Unspecified bits are always zero). + * + * ``` + * ++-----------------------sample is signed if set + * || + * || ++-----------sample is bigendian if set + * || || + * || || ++---sample is float if set + * || || || + * || || || +---sample bit size---+ + * || || || | | + * 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00 + * ``` + * + * There are macros in SDL 2.0 and later to query these bits. + */ +typedef Uint16 SDL_AudioFormat; + +/** + * \name Audio flags + */ +/* @{ */ + +#define SDL_AUDIO_MASK_BITSIZE (0xFF) +#define SDL_AUDIO_MASK_DATATYPE (1<<8) +#define SDL_AUDIO_MASK_ENDIAN (1<<12) +#define SDL_AUDIO_MASK_SIGNED (1<<15) +#define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE) +#define SDL_AUDIO_ISFLOAT(x) (x & SDL_AUDIO_MASK_DATATYPE) +#define SDL_AUDIO_ISBIGENDIAN(x) (x & SDL_AUDIO_MASK_ENDIAN) +#define SDL_AUDIO_ISSIGNED(x) (x & SDL_AUDIO_MASK_SIGNED) +#define SDL_AUDIO_ISINT(x) (!SDL_AUDIO_ISFLOAT(x)) +#define SDL_AUDIO_ISLITTLEENDIAN(x) (!SDL_AUDIO_ISBIGENDIAN(x)) +#define SDL_AUDIO_ISUNSIGNED(x) (!SDL_AUDIO_ISSIGNED(x)) + +/** + * \name Audio format flags + * + * Defaults to LSB byte order. + */ +/* @{ */ +#define AUDIO_U8 0x0008 /**< Unsigned 8-bit samples */ +#define AUDIO_S8 0x8008 /**< Signed 8-bit samples */ +#define AUDIO_U16LSB 0x0010 /**< Unsigned 16-bit samples */ +#define AUDIO_S16LSB 0x8010 /**< Signed 16-bit samples */ +#define AUDIO_U16MSB 0x1010 /**< As above, but big-endian byte order */ +#define AUDIO_S16MSB 0x9010 /**< As above, but big-endian byte order */ +#define AUDIO_U16 AUDIO_U16LSB +#define AUDIO_S16 AUDIO_S16LSB +/* @} */ + +/** + * \name int32 support + */ +/* @{ */ +#define AUDIO_S32LSB 0x8020 /**< 32-bit integer samples */ +#define AUDIO_S32MSB 0x9020 /**< As above, but big-endian byte order */ +#define AUDIO_S32 AUDIO_S32LSB +/* @} */ + +/** + * \name float32 support + */ +/* @{ */ +#define AUDIO_F32LSB 0x8120 /**< 32-bit floating point samples */ +#define AUDIO_F32MSB 0x9120 /**< As above, but big-endian byte order */ +#define AUDIO_F32 AUDIO_F32LSB +/* @} */ + +/** + * \name Native audio byte ordering + */ +/* @{ */ +#if SDL_BYTEORDER == SDL_LIL_ENDIAN +#define AUDIO_U16SYS AUDIO_U16LSB +#define AUDIO_S16SYS AUDIO_S16LSB +#define AUDIO_S32SYS AUDIO_S32LSB +#define AUDIO_F32SYS AUDIO_F32LSB +#else +#define AUDIO_U16SYS AUDIO_U16MSB +#define AUDIO_S16SYS AUDIO_S16MSB +#define AUDIO_S32SYS AUDIO_S32MSB +#define AUDIO_F32SYS AUDIO_F32MSB +#endif +/* @} */ + +/** + * \name Allow change flags + * + * Which audio format changes are allowed when opening a device. + */ +/* @{ */ +#define SDL_AUDIO_ALLOW_FREQUENCY_CHANGE 0x00000001 +#define SDL_AUDIO_ALLOW_FORMAT_CHANGE 0x00000002 +#define SDL_AUDIO_ALLOW_CHANNELS_CHANGE 0x00000004 +#define SDL_AUDIO_ALLOW_SAMPLES_CHANGE 0x00000008 +#define SDL_AUDIO_ALLOW_ANY_CHANGE (SDL_AUDIO_ALLOW_FREQUENCY_CHANGE|SDL_AUDIO_ALLOW_FORMAT_CHANGE|SDL_AUDIO_ALLOW_CHANNELS_CHANGE|SDL_AUDIO_ALLOW_SAMPLES_CHANGE) +/* @} */ + +/* @} *//* Audio flags */ + +/** + * This function is called when the audio device needs more data. + * + * \param userdata An application-specific parameter saved in the + * SDL_AudioSpec structure. + * \param stream A pointer to the audio data buffer. + * \param len Length of **stream** in bytes. + */ +typedef void (SDLCALL * SDL_AudioCallback) (void *userdata, Uint8 * stream, + int len); + +/** + * The calculated values in this structure are calculated by SDL_OpenAudio(). + * + * For multi-channel audio, the default SDL channel mapping is: + * + * ``` + * 2: FL FR (stereo) + * 3: FL FR LFE (2.1 surround) + * 4: FL FR BL BR (quad) + * 5: FL FR LFE BL BR (4.1 surround) + * 6: FL FR FC LFE SL SR (5.1 surround - last two can also be BL BR) + * 7: FL FR FC LFE BC SL SR (6.1 surround) + * 8: FL FR FC LFE BL BR SL SR (7.1 surround) + * ``` + */ +typedef struct SDL_AudioSpec +{ + int freq; /**< DSP frequency -- samples per second */ + SDL_AudioFormat format; /**< Audio data format */ + Uint8 channels; /**< Number of channels: 1 mono, 2 stereo */ + Uint8 silence; /**< Audio buffer silence value (calculated) */ + Uint16 samples; /**< Audio buffer size in sample FRAMES (total samples divided by channel count) */ + Uint16 padding; /**< Necessary for some compile environments */ + Uint32 size; /**< Audio buffer size in bytes (calculated) */ + SDL_AudioCallback callback; /**< Callback that feeds the audio device (NULL to use SDL_QueueAudio()). */ + void *userdata; /**< Userdata passed to callback (ignored for NULL callbacks). */ +} SDL_AudioSpec; + + +struct SDL_AudioCVT; +typedef void (SDLCALL * SDL_AudioFilter) (struct SDL_AudioCVT * cvt, + SDL_AudioFormat format); + +/** + * Upper limit of filters in SDL_AudioCVT + * + * The maximum number of SDL_AudioFilter functions in SDL_AudioCVT is + * currently limited to 9. The SDL_AudioCVT.filters array has 10 pointers, one + * of which is the terminating NULL pointer. + */ +#define SDL_AUDIOCVT_MAX_FILTERS 9 + +/** + * \struct SDL_AudioCVT + * \brief A structure to hold a set of audio conversion filters and buffers. + * + * Note that various parts of the conversion pipeline can take advantage + * of SIMD operations (like SSE2, for example). SDL_AudioCVT doesn't require + * you to pass it aligned data, but can possibly run much faster if you + * set both its (buf) field to a pointer that is aligned to 16 bytes, and its + * (len) field to something that's a multiple of 16, if possible. + */ +#if defined(__GNUC__) && !defined(__CHERI_PURE_CAPABILITY__) +/* This structure is 84 bytes on 32-bit architectures, make sure GCC doesn't + pad it out to 88 bytes to guarantee ABI compatibility between compilers. + This is not a concern on CHERI architectures, where pointers must be stored + at aligned locations otherwise they will become invalid, and thus structs + containing pointers cannot be packed without giving a warning or error. + vvv + The next time we rev the ABI, make sure to size the ints and add padding. +*/ +#define SDL_AUDIOCVT_PACKED __attribute__((packed)) +#else +#define SDL_AUDIOCVT_PACKED +#endif +/* */ +typedef struct SDL_AudioCVT +{ + int needed; /**< Set to 1 if conversion possible */ + SDL_AudioFormat src_format; /**< Source audio format */ + SDL_AudioFormat dst_format; /**< Target audio format */ + double rate_incr; /**< Rate conversion increment */ + Uint8 *buf; /**< Buffer to hold entire audio data */ + int len; /**< Length of original audio buffer */ + int len_cvt; /**< Length of converted audio buffer */ + int len_mult; /**< buffer must be len*len_mult big */ + double len_ratio; /**< Given len, final size is len*len_ratio */ + SDL_AudioFilter filters[SDL_AUDIOCVT_MAX_FILTERS + 1]; /**< NULL-terminated list of filter functions */ + int filter_index; /**< Current audio conversion function */ +} SDL_AUDIOCVT_PACKED SDL_AudioCVT; + + +/* Function prototypes */ + +/** + * \name Driver discovery functions + * + * These functions return the list of built in audio drivers, in the + * order that they are normally initialized by default. + */ +/* @{ */ + +/** + * Use this function to get the number of built-in audio drivers. + * + * This function returns a hardcoded number. This never returns a negative + * value; if there are no drivers compiled into this build of SDL, this + * function returns zero. The presence of a driver in this list does not mean + * it will function, it just means SDL is capable of interacting with that + * interface. For example, a build of SDL might have esound support, but if + * there's no esound server available, SDL's esound driver would fail if used. + * + * By default, SDL tries all drivers, in its preferred order, until one is + * found to be usable. + * + * \returns the number of built-in audio drivers. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetAudioDriver + */ +extern DECLSPEC int SDLCALL SDL_GetNumAudioDrivers(void); + +/** + * Use this function to get the name of a built in audio driver. + * + * The list of audio drivers is given in the order that they are normally + * initialized by default; the drivers that seem more reasonable to choose + * first (as far as the SDL developers believe) are earlier in the list. + * + * The names of drivers are all simple, low-ASCII identifiers, like "alsa", + * "coreaudio" or "xaudio2". These never have Unicode characters, and are not + * meant to be proper names. + * + * \param index the index of the audio driver; the value ranges from 0 to + * SDL_GetNumAudioDrivers() - 1. + * \returns the name of the audio driver at the requested index, or NULL if an + * invalid index was specified. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumAudioDrivers + */ +extern DECLSPEC const char *SDLCALL SDL_GetAudioDriver(int index); +/* @} */ + +/** + * \name Initialization and cleanup + * + * \internal These functions are used internally, and should not be used unless + * you have a specific need to specify the audio driver you want to + * use. You should normally use SDL_Init() or SDL_InitSubSystem(). + */ +/* @{ */ + +/** + * Use this function to initialize a particular audio driver. + * + * This function is used internally, and should not be used unless you have a + * specific need to designate the audio driver you want to use. You should + * normally use SDL_Init() or SDL_InitSubSystem(). + * + * \param driver_name the name of the desired audio driver. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AudioQuit + */ +extern DECLSPEC int SDLCALL SDL_AudioInit(const char *driver_name); + +/** + * Use this function to shut down audio if you initialized it with + * SDL_AudioInit(). + * + * This function is used internally, and should not be used unless you have a + * specific need to specify the audio driver you want to use. You should + * normally use SDL_Quit() or SDL_QuitSubSystem(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AudioInit + */ +extern DECLSPEC void SDLCALL SDL_AudioQuit(void); +/* @} */ + +/** + * Get the name of the current audio driver. + * + * The returned string points to internal static memory and thus never becomes + * invalid, even if you quit the audio subsystem and initialize a new driver + * (although such a case would return a different static string from another + * call to this function, of course). As such, you should not modify or free + * the returned string. + * + * \returns the name of the current audio driver or NULL if no driver has been + * initialized. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AudioInit + */ +extern DECLSPEC const char *SDLCALL SDL_GetCurrentAudioDriver(void); + +/** + * This function is a legacy means of opening the audio device. + * + * This function remains for compatibility with SDL 1.2, but also because it's + * slightly easier to use than the new functions in SDL 2.0. The new, more + * powerful, and preferred way to do this is SDL_OpenAudioDevice(). + * + * This function is roughly equivalent to: + * + * ```c + * SDL_OpenAudioDevice(NULL, 0, desired, obtained, SDL_AUDIO_ALLOW_ANY_CHANGE); + * ``` + * + * With two notable exceptions: + * + * - If `obtained` is NULL, we use `desired` (and allow no changes), which + * means desired will be modified to have the correct values for silence, + * etc, and SDL will convert any differences between your app's specific + * request and the hardware behind the scenes. + * - The return value is always success or failure, and not a device ID, which + * means you can only have one device open at a time with this function. + * + * \param desired an SDL_AudioSpec structure representing the desired output + * format. Please refer to the SDL_OpenAudioDevice + * documentation for details on how to prepare this structure. + * \param obtained an SDL_AudioSpec structure filled in with the actual + * parameters, or NULL. + * \returns 0 if successful, placing the actual hardware parameters in the + * structure pointed to by `obtained`. + * + * If `obtained` is NULL, the audio data passed to the callback + * function will be guaranteed to be in the requested format, and + * will be automatically converted to the actual hardware audio + * format if necessary. If `obtained` is NULL, `desired` will have + * fields modified. + * + * This function returns a negative error code on failure to open the + * audio device or failure to set up the audio thread; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CloseAudio + * \sa SDL_LockAudio + * \sa SDL_PauseAudio + * \sa SDL_UnlockAudio + */ +extern DECLSPEC int SDLCALL SDL_OpenAudio(SDL_AudioSpec * desired, + SDL_AudioSpec * obtained); + +/** + * SDL Audio Device IDs. + * + * A successful call to SDL_OpenAudio() is always device id 1, and legacy SDL + * audio APIs assume you want this device ID. SDL_OpenAudioDevice() calls + * always returns devices >= 2 on success. The legacy calls are good both for + * backwards compatibility and when you don't care about multiple, specific, + * or capture devices. + */ +typedef Uint32 SDL_AudioDeviceID; + +/** + * Get the number of built-in audio devices. + * + * This function is only valid after successfully initializing the audio + * subsystem. + * + * Note that audio capture support is not implemented as of SDL 2.0.4, so the + * `iscapture` parameter is for future expansion and should always be zero for + * now. + * + * This function will return -1 if an explicit list of devices can't be + * determined. Returning -1 is not an error. For example, if SDL is set up to + * talk to a remote audio server, it can't list every one available on the + * Internet, but it will still allow a specific host to be specified in + * SDL_OpenAudioDevice(). + * + * In many common cases, when this function returns a value <= 0, it can still + * successfully open the default device (NULL for first argument of + * SDL_OpenAudioDevice()). + * + * This function may trigger a complete redetect of available hardware. It + * should not be called for each iteration of a loop, but rather once at the + * start of a loop: + * + * ```c + * // Don't do this: + * for (int i = 0; i < SDL_GetNumAudioDevices(0); i++) + * + * // do this instead: + * const int count = SDL_GetNumAudioDevices(0); + * for (int i = 0; i < count; ++i) { do_something_here(); } + * ``` + * + * \param iscapture zero to request playback devices, non-zero to request + * recording devices. + * \returns the number of available devices exposed by the current driver or + * -1 if an explicit list of devices can't be determined. A return + * value of -1 does not necessarily mean an error condition. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetAudioDeviceName + * \sa SDL_OpenAudioDevice + */ +extern DECLSPEC int SDLCALL SDL_GetNumAudioDevices(int iscapture); + +/** + * Get the human-readable name of a specific audio device. + * + * This function is only valid after successfully initializing the audio + * subsystem. The values returned by this function reflect the latest call to + * SDL_GetNumAudioDevices(); re-call that function to redetect available + * hardware. + * + * The string returned by this function is UTF-8 encoded, read-only, and + * managed internally. You are not to free it. If you need to keep the string + * for any length of time, you should make your own copy of it, as it will be + * invalid next time any of several other SDL functions are called. + * + * \param index the index of the audio device; valid values range from 0 to + * SDL_GetNumAudioDevices() - 1. + * \param iscapture non-zero to query the list of recording devices, zero to + * query the list of output devices. + * \returns the name of the audio device at the requested index, or NULL on + * error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumAudioDevices + * \sa SDL_GetDefaultAudioInfo + */ +extern DECLSPEC const char *SDLCALL SDL_GetAudioDeviceName(int index, + int iscapture); + +/** + * Get the preferred audio format of a specific audio device. + * + * This function is only valid after a successfully initializing the audio + * subsystem. The values returned by this function reflect the latest call to + * SDL_GetNumAudioDevices(); re-call that function to redetect available + * hardware. + * + * `spec` will be filled with the sample rate, sample format, and channel + * count. + * + * \param index the index of the audio device; valid values range from 0 to + * SDL_GetNumAudioDevices() - 1. + * \param iscapture non-zero to query the list of recording devices, zero to + * query the list of output devices. + * \param spec The SDL_AudioSpec to be initialized by this function. + * \returns 0 on success, nonzero on error. + * + * \since This function is available since SDL 2.0.16. + * + * \sa SDL_GetNumAudioDevices + * \sa SDL_GetDefaultAudioInfo + */ +extern DECLSPEC int SDLCALL SDL_GetAudioDeviceSpec(int index, + int iscapture, + SDL_AudioSpec *spec); + + +/** + * Get the name and preferred format of the default audio device. + * + * Some (but not all!) platforms have an isolated mechanism to get information + * about the "default" device. This can actually be a completely different + * device that's not in the list you get from SDL_GetAudioDeviceSpec(). It can + * even be a network address! (This is discussed in SDL_OpenAudioDevice().) + * + * As a result, this call is not guaranteed to be performant, as it can query + * the sound server directly every time, unlike the other query functions. You + * should call this function sparingly! + * + * `spec` will be filled with the sample rate, sample format, and channel + * count, if a default device exists on the system. If `name` is provided, + * will be filled with either a dynamically-allocated UTF-8 string or NULL. + * + * \param name A pointer to be filled with the name of the default device (can + * be NULL). Please call SDL_free() when you are done with this + * pointer! + * \param spec The SDL_AudioSpec to be initialized by this function. + * \param iscapture non-zero to query the default recording device, zero to + * query the default output device. + * \returns 0 on success, nonzero on error. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GetAudioDeviceName + * \sa SDL_GetAudioDeviceSpec + * \sa SDL_OpenAudioDevice + */ +extern DECLSPEC int SDLCALL SDL_GetDefaultAudioInfo(char **name, + SDL_AudioSpec *spec, + int iscapture); + + +/** + * Open a specific audio device. + * + * SDL_OpenAudio(), unlike this function, always acts on device ID 1. As such, + * this function will never return a 1 so as not to conflict with the legacy + * function. + * + * Please note that SDL 2.0 before 2.0.5 did not support recording; as such, + * this function would fail if `iscapture` was not zero. Starting with SDL + * 2.0.5, recording is implemented and this value can be non-zero. + * + * Passing in a `device` name of NULL requests the most reasonable default + * (and is equivalent to what SDL_OpenAudio() does to choose a device). The + * `device` name is a UTF-8 string reported by SDL_GetAudioDeviceName(), but + * some drivers allow arbitrary and driver-specific strings, such as a + * hostname/IP address for a remote audio server, or a filename in the + * diskaudio driver. + * + * An opened audio device starts out paused, and should be enabled for playing + * by calling SDL_PauseAudioDevice(devid, 0) when you are ready for your audio + * callback function to be called. Since the audio driver may modify the + * requested size of the audio buffer, you should allocate any local mixing + * buffers after you open the audio device. + * + * The audio callback runs in a separate thread in most cases; you can prevent + * race conditions between your callback and other threads without fully + * pausing playback with SDL_LockAudioDevice(). For more information about the + * callback, see SDL_AudioSpec. + * + * Managing the audio spec via 'desired' and 'obtained': + * + * When filling in the desired audio spec structure: + * + * - `desired->freq` should be the frequency in sample-frames-per-second (Hz). + * - `desired->format` should be the audio format (`AUDIO_S16SYS`, etc). + * - `desired->samples` is the desired size of the audio buffer, in _sample + * frames_ (with stereo output, two samples--left and right--would make a + * single sample frame). This number should be a power of two, and may be + * adjusted by the audio driver to a value more suitable for the hardware. + * Good values seem to range between 512 and 4096 inclusive, depending on + * the application and CPU speed. Smaller values reduce latency, but can + * lead to underflow if the application is doing heavy processing and cannot + * fill the audio buffer in time. Note that the number of sample frames is + * directly related to time by the following formula: `ms = + * (sampleframes*1000)/freq` + * - `desired->size` is the size in _bytes_ of the audio buffer, and is + * calculated by SDL_OpenAudioDevice(). You don't initialize this. + * - `desired->silence` is the value used to set the buffer to silence, and is + * calculated by SDL_OpenAudioDevice(). You don't initialize this. + * - `desired->callback` should be set to a function that will be called when + * the audio device is ready for more data. It is passed a pointer to the + * audio buffer, and the length in bytes of the audio buffer. This function + * usually runs in a separate thread, and so you should protect data + * structures that it accesses by calling SDL_LockAudioDevice() and + * SDL_UnlockAudioDevice() in your code. Alternately, you may pass a NULL + * pointer here, and call SDL_QueueAudio() with some frequency, to queue + * more audio samples to be played (or for capture devices, call + * SDL_DequeueAudio() with some frequency, to obtain audio samples). + * - `desired->userdata` is passed as the first parameter to your callback + * function. If you passed a NULL callback, this value is ignored. + * + * `allowed_changes` can have the following flags OR'd together: + * + * - `SDL_AUDIO_ALLOW_FREQUENCY_CHANGE` + * - `SDL_AUDIO_ALLOW_FORMAT_CHANGE` + * - `SDL_AUDIO_ALLOW_CHANNELS_CHANGE` + * - `SDL_AUDIO_ALLOW_SAMPLES_CHANGE` + * - `SDL_AUDIO_ALLOW_ANY_CHANGE` + * + * These flags specify how SDL should behave when a device cannot offer a + * specific feature. If the application requests a feature that the hardware + * doesn't offer, SDL will always try to get the closest equivalent. + * + * For example, if you ask for float32 audio format, but the sound card only + * supports int16, SDL will set the hardware to int16. If you had set + * SDL_AUDIO_ALLOW_FORMAT_CHANGE, SDL will change the format in the `obtained` + * structure. If that flag was *not* set, SDL will prepare to convert your + * callback's float32 audio to int16 before feeding it to the hardware and + * will keep the originally requested format in the `obtained` structure. + * + * The resulting audio specs, varying depending on hardware and on what + * changes were allowed, will then be written back to `obtained`. + * + * If your application can only handle one specific data format, pass a zero + * for `allowed_changes` and let SDL transparently handle any differences. + * + * \param device a UTF-8 string reported by SDL_GetAudioDeviceName() or a + * driver-specific name as appropriate. NULL requests the most + * reasonable default device. + * \param iscapture non-zero to specify a device should be opened for + * recording, not playback. + * \param desired an SDL_AudioSpec structure representing the desired output + * format; see SDL_OpenAudio() for more information. + * \param obtained an SDL_AudioSpec structure filled in with the actual output + * format; see SDL_OpenAudio() for more information. + * \param allowed_changes 0, or one or more flags OR'd together. + * \returns a valid device ID that is > 0 on success or 0 on failure; call + * SDL_GetError() for more information. + * + * For compatibility with SDL 1.2, this will never return 1, since + * SDL reserves that ID for the legacy SDL_OpenAudio() function. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CloseAudioDevice + * \sa SDL_GetAudioDeviceName + * \sa SDL_LockAudioDevice + * \sa SDL_OpenAudio + * \sa SDL_PauseAudioDevice + * \sa SDL_UnlockAudioDevice + */ +extern DECLSPEC SDL_AudioDeviceID SDLCALL SDL_OpenAudioDevice( + const char *device, + int iscapture, + const SDL_AudioSpec *desired, + SDL_AudioSpec *obtained, + int allowed_changes); + + + +/** + * \name Audio state + * + * Get the current audio state. + */ +/* @{ */ +typedef enum +{ + SDL_AUDIO_STOPPED = 0, + SDL_AUDIO_PLAYING, + SDL_AUDIO_PAUSED +} SDL_AudioStatus; + +/** + * This function is a legacy means of querying the audio device. + * + * New programs might want to use SDL_GetAudioDeviceStatus() instead. This + * function is equivalent to calling... + * + * ```c + * SDL_GetAudioDeviceStatus(1); + * ``` + * + * ...and is only useful if you used the legacy SDL_OpenAudio() function. + * + * \returns the SDL_AudioStatus of the audio device opened by SDL_OpenAudio(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetAudioDeviceStatus + */ +extern DECLSPEC SDL_AudioStatus SDLCALL SDL_GetAudioStatus(void); + +/** + * Use this function to get the current audio state of an audio device. + * + * \param dev the ID of an audio device previously opened with + * SDL_OpenAudioDevice(). + * \returns the SDL_AudioStatus of the specified audio device. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PauseAudioDevice + */ +extern DECLSPEC SDL_AudioStatus SDLCALL SDL_GetAudioDeviceStatus(SDL_AudioDeviceID dev); +/* @} *//* Audio State */ + +/** + * \name Pause audio functions + * + * These functions pause and unpause the audio callback processing. + * They should be called with a parameter of 0 after opening the audio + * device to start playing sound. This is so you can safely initialize + * data for your callback function after opening the audio device. + * Silence will be written to the audio device during the pause. + */ +/* @{ */ + +/** + * This function is a legacy means of pausing the audio device. + * + * New programs might want to use SDL_PauseAudioDevice() instead. This + * function is equivalent to calling... + * + * ```c + * SDL_PauseAudioDevice(1, pause_on); + * ``` + * + * ...and is only useful if you used the legacy SDL_OpenAudio() function. + * + * \param pause_on non-zero to pause, 0 to unpause. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetAudioStatus + * \sa SDL_PauseAudioDevice + */ +extern DECLSPEC void SDLCALL SDL_PauseAudio(int pause_on); + +/** + * Use this function to pause and unpause audio playback on a specified + * device. + * + * This function pauses and unpauses the audio callback processing for a given + * device. Newly-opened audio devices start in the paused state, so you must + * call this function with **pause_on**=0 after opening the specified audio + * device to start playing sound. This allows you to safely initialize data + * for your callback function after opening the audio device. Silence will be + * written to the audio device while paused, and the audio callback is + * guaranteed to not be called. Pausing one device does not prevent other + * unpaused devices from running their callbacks. + * + * Pausing state does not stack; even if you pause a device several times, a + * single unpause will start the device playing again, and vice versa. This is + * different from how SDL_LockAudioDevice() works. + * + * If you just need to protect a few variables from race conditions vs your + * callback, you shouldn't pause the audio device, as it will lead to dropouts + * in the audio playback. Instead, you should use SDL_LockAudioDevice(). + * + * \param dev a device opened by SDL_OpenAudioDevice(). + * \param pause_on non-zero to pause, 0 to unpause. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LockAudioDevice + */ +extern DECLSPEC void SDLCALL SDL_PauseAudioDevice(SDL_AudioDeviceID dev, + int pause_on); +/* @} *//* Pause audio functions */ + +/** + * Load the audio data of a WAVE file into memory. + * + * Loading a WAVE file requires `src`, `spec`, `audio_buf` and `audio_len` to + * be valid pointers. The entire data portion of the file is then loaded into + * memory and decoded if necessary. + * + * If `freesrc` is non-zero, the data source gets automatically closed and + * freed before the function returns. + * + * Supported formats are RIFF WAVE files with the formats PCM (8, 16, 24, and + * 32 bits), IEEE Float (32 bits), Microsoft ADPCM and IMA ADPCM (4 bits), and + * A-law and mu-law (8 bits). Other formats are currently unsupported and + * cause an error. + * + * If this function succeeds, the pointer returned by it is equal to `spec` + * and the pointer to the audio data allocated by the function is written to + * `audio_buf` and its length in bytes to `audio_len`. The SDL_AudioSpec + * members `freq`, `channels`, and `format` are set to the values of the audio + * data in the buffer. The `samples` member is set to a sane default and all + * others are set to zero. + * + * It's necessary to use SDL_FreeWAV() to free the audio data returned in + * `audio_buf` when it is no longer used. + * + * Because of the underspecification of the .WAV format, there are many + * problematic files in the wild that cause issues with strict decoders. To + * provide compatibility with these files, this decoder is lenient in regards + * to the truncation of the file, the fact chunk, and the size of the RIFF + * chunk. The hints `SDL_HINT_WAVE_RIFF_CHUNK_SIZE`, + * `SDL_HINT_WAVE_TRUNCATION`, and `SDL_HINT_WAVE_FACT_CHUNK` can be used to + * tune the behavior of the loading process. + * + * Any file that is invalid (due to truncation, corruption, or wrong values in + * the headers), too big, or unsupported causes an error. Additionally, any + * critical I/O error from the data source will terminate the loading process + * with an error. The function returns NULL on error and in all cases (with + * the exception of `src` being NULL), an appropriate error message will be + * set. + * + * It is required that the data source supports seeking. + * + * Example: + * + * ```c + * SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, &spec, &buf, &len); + * ``` + * + * Note that the SDL_LoadWAV macro does this same thing for you, but in a less + * messy way: + * + * ```c + * SDL_LoadWAV("sample.wav", &spec, &buf, &len); + * ``` + * + * \param src The data source for the WAVE data. + * \param freesrc If non-zero, SDL will _always_ free the data source. + * \param spec An SDL_AudioSpec that will be filled in with the wave file's + * format details. + * \param audio_buf A pointer filled with the audio data, allocated by the + * function. + * \param audio_len A pointer filled with the length of the audio data buffer + * in bytes. + * \returns This function, if successfully called, returns `spec`, which will + * be filled with the audio data format of the wave source data. + * `audio_buf` will be filled with a pointer to an allocated buffer + * containing the audio data, and `audio_len` is filled with the + * length of that audio buffer in bytes. + * + * This function returns NULL if the .WAV file cannot be opened, uses + * an unknown data format, or is corrupt; call SDL_GetError() for + * more information. + * + * When the application is done with the data returned in + * `audio_buf`, it should call SDL_FreeWAV() to dispose of it. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FreeWAV + * \sa SDL_LoadWAV + */ +extern DECLSPEC SDL_AudioSpec *SDLCALL SDL_LoadWAV_RW(SDL_RWops * src, + int freesrc, + SDL_AudioSpec * spec, + Uint8 ** audio_buf, + Uint32 * audio_len); + +/** + * Loads a WAV from a file. + * + * Compatibility convenience function. + */ +#define SDL_LoadWAV(file, spec, audio_buf, audio_len) \ + SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"),1, spec,audio_buf,audio_len) + +/** + * Free data previously allocated with SDL_LoadWAV() or SDL_LoadWAV_RW(). + * + * After a WAVE file has been opened with SDL_LoadWAV() or SDL_LoadWAV_RW() + * its data can eventually be freed with SDL_FreeWAV(). It is safe to call + * this function with a NULL pointer. + * + * \param audio_buf a pointer to the buffer created by SDL_LoadWAV() or + * SDL_LoadWAV_RW(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LoadWAV + * \sa SDL_LoadWAV_RW + */ +extern DECLSPEC void SDLCALL SDL_FreeWAV(Uint8 * audio_buf); + +/** + * Initialize an SDL_AudioCVT structure for conversion. + * + * Before an SDL_AudioCVT structure can be used to convert audio data it must + * be initialized with source and destination information. + * + * This function will zero out every field of the SDL_AudioCVT, so it must be + * called before the application fills in the final buffer information. + * + * Once this function has returned successfully, and reported that a + * conversion is necessary, the application fills in the rest of the fields in + * SDL_AudioCVT, now that it knows how large a buffer it needs to allocate, + * and then can call SDL_ConvertAudio() to complete the conversion. + * + * \param cvt an SDL_AudioCVT structure filled in with audio conversion + * information. + * \param src_format the source format of the audio data; for more info see + * SDL_AudioFormat. + * \param src_channels the number of channels in the source. + * \param src_rate the frequency (sample-frames-per-second) of the source. + * \param dst_format the destination format of the audio data; for more info + * see SDL_AudioFormat. + * \param dst_channels the number of channels in the destination. + * \param dst_rate the frequency (sample-frames-per-second) of the + * destination. + * \returns 1 if the audio filter is prepared, 0 if no conversion is needed, + * or a negative error code on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ConvertAudio + */ +extern DECLSPEC int SDLCALL SDL_BuildAudioCVT(SDL_AudioCVT * cvt, + SDL_AudioFormat src_format, + Uint8 src_channels, + int src_rate, + SDL_AudioFormat dst_format, + Uint8 dst_channels, + int dst_rate); + +/** + * Convert audio data to a desired audio format. + * + * This function does the actual audio data conversion, after the application + * has called SDL_BuildAudioCVT() to prepare the conversion information and + * then filled in the buffer details. + * + * Once the application has initialized the `cvt` structure using + * SDL_BuildAudioCVT(), allocated an audio buffer and filled it with audio + * data in the source format, this function will convert the buffer, in-place, + * to the desired format. + * + * The data conversion may go through several passes; any given pass may + * possibly temporarily increase the size of the data. For example, SDL might + * expand 16-bit data to 32 bits before resampling to a lower frequency, + * shrinking the data size after having grown it briefly. Since the supplied + * buffer will be both the source and destination, converting as necessary + * in-place, the application must allocate a buffer that will fully contain + * the data during its largest conversion pass. After SDL_BuildAudioCVT() + * returns, the application should set the `cvt->len` field to the size, in + * bytes, of the source data, and allocate a buffer that is `cvt->len * + * cvt->len_mult` bytes long for the `buf` field. + * + * The source data should be copied into this buffer before the call to + * SDL_ConvertAudio(). Upon successful return, this buffer will contain the + * converted audio, and `cvt->len_cvt` will be the size of the converted data, + * in bytes. Any bytes in the buffer past `cvt->len_cvt` are undefined once + * this function returns. + * + * \param cvt an SDL_AudioCVT structure that was previously set up by + * SDL_BuildAudioCVT(). + * \returns 0 if the conversion was completed successfully or a negative error + * code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BuildAudioCVT + */ +extern DECLSPEC int SDLCALL SDL_ConvertAudio(SDL_AudioCVT * cvt); + +/* SDL_AudioStream is a new audio conversion interface. + The benefits vs SDL_AudioCVT: + - it can handle resampling data in chunks without generating + artifacts, when it doesn't have the complete buffer available. + - it can handle incoming data in any variable size. + - You push data as you have it, and pull it when you need it + */ +/* this is opaque to the outside world. */ +struct _SDL_AudioStream; +typedef struct _SDL_AudioStream SDL_AudioStream; + +/** + * Create a new audio stream. + * + * \param src_format The format of the source audio. + * \param src_channels The number of channels of the source audio. + * \param src_rate The sampling rate of the source audio. + * \param dst_format The format of the desired audio output. + * \param dst_channels The number of channels of the desired audio output. + * \param dst_rate The sampling rate of the desired audio output. + * \returns 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.7. + * + * \sa SDL_AudioStreamPut + * \sa SDL_AudioStreamGet + * \sa SDL_AudioStreamAvailable + * \sa SDL_AudioStreamFlush + * \sa SDL_AudioStreamClear + * \sa SDL_FreeAudioStream + */ +extern DECLSPEC SDL_AudioStream * SDLCALL SDL_NewAudioStream(const SDL_AudioFormat src_format, + const Uint8 src_channels, + const int src_rate, + const SDL_AudioFormat dst_format, + const Uint8 dst_channels, + const int dst_rate); + +/** + * Add data to be converted/resampled to the stream. + * + * \param stream The stream the audio data is being added to. + * \param buf A pointer to the audio data to add. + * \param len The number of bytes to write to the stream. + * \returns 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.7. + * + * \sa SDL_NewAudioStream + * \sa SDL_AudioStreamGet + * \sa SDL_AudioStreamAvailable + * \sa SDL_AudioStreamFlush + * \sa SDL_AudioStreamClear + * \sa SDL_FreeAudioStream + */ +extern DECLSPEC int SDLCALL SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len); + +/** + * Get converted/resampled data from the stream + * + * \param stream The stream the audio is being requested from. + * \param buf A buffer to fill with audio data. + * \param len The maximum number of bytes to fill. + * \returns the number of bytes read from the stream, or -1 on error. + * + * \since This function is available since SDL 2.0.7. + * + * \sa SDL_NewAudioStream + * \sa SDL_AudioStreamPut + * \sa SDL_AudioStreamAvailable + * \sa SDL_AudioStreamFlush + * \sa SDL_AudioStreamClear + * \sa SDL_FreeAudioStream + */ +extern DECLSPEC int SDLCALL SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len); + +/** + * Get the number of converted/resampled bytes available. + * + * The stream may be buffering data behind the scenes until it has enough to + * resample correctly, so this number might be lower than what you expect, or + * even be zero. Add more data or flush the stream if you need the data now. + * + * \since This function is available since SDL 2.0.7. + * + * \sa SDL_NewAudioStream + * \sa SDL_AudioStreamPut + * \sa SDL_AudioStreamGet + * \sa SDL_AudioStreamFlush + * \sa SDL_AudioStreamClear + * \sa SDL_FreeAudioStream + */ +extern DECLSPEC int SDLCALL SDL_AudioStreamAvailable(SDL_AudioStream *stream); + +/** + * Tell the stream that you're done sending data, and anything being buffered + * should be converted/resampled and made available immediately. + * + * It is legal to add more data to a stream after flushing, but there will be + * audio gaps in the output. Generally this is intended to signal the end of + * input, so the complete output becomes available. + * + * \since This function is available since SDL 2.0.7. + * + * \sa SDL_NewAudioStream + * \sa SDL_AudioStreamPut + * \sa SDL_AudioStreamGet + * \sa SDL_AudioStreamAvailable + * \sa SDL_AudioStreamClear + * \sa SDL_FreeAudioStream + */ +extern DECLSPEC int SDLCALL SDL_AudioStreamFlush(SDL_AudioStream *stream); + +/** + * Clear any pending data in the stream without converting it + * + * \since This function is available since SDL 2.0.7. + * + * \sa SDL_NewAudioStream + * \sa SDL_AudioStreamPut + * \sa SDL_AudioStreamGet + * \sa SDL_AudioStreamAvailable + * \sa SDL_AudioStreamFlush + * \sa SDL_FreeAudioStream + */ +extern DECLSPEC void SDLCALL SDL_AudioStreamClear(SDL_AudioStream *stream); + +/** + * Free an audio stream + * + * \since This function is available since SDL 2.0.7. + * + * \sa SDL_NewAudioStream + * \sa SDL_AudioStreamPut + * \sa SDL_AudioStreamGet + * \sa SDL_AudioStreamAvailable + * \sa SDL_AudioStreamFlush + * \sa SDL_AudioStreamClear + */ +extern DECLSPEC void SDLCALL SDL_FreeAudioStream(SDL_AudioStream *stream); + +/** + * Maximum volume allowed in calls to SDL_MixAudio and SDL_MixAudioFormat. + */ +#define SDL_MIX_MAXVOLUME 128 + +/** + * This function is a legacy means of mixing audio. + * + * This function is equivalent to calling... + * + * ```c + * SDL_MixAudioFormat(dst, src, format, len, volume); + * ``` + * + * ...where `format` is the obtained format of the audio device from the + * legacy SDL_OpenAudio() function. + * + * \param dst the destination for the mixed audio. + * \param src the source audio buffer to be mixed. + * \param len the length of the audio buffer in bytes. + * \param volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME + * for full audio volume. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_MixAudioFormat + */ +extern DECLSPEC void SDLCALL SDL_MixAudio(Uint8 * dst, const Uint8 * src, + Uint32 len, int volume); + +/** + * Mix audio data in a specified format. + * + * This takes an audio buffer `src` of `len` bytes of `format` data and mixes + * it into `dst`, performing addition, volume adjustment, and overflow + * clipping. The buffer pointed to by `dst` must also be `len` bytes of + * `format` data. + * + * This is provided for convenience -- you can mix your own audio data. + * + * Do not use this function for mixing together more than two streams of + * sample data. The output from repeated application of this function may be + * distorted by clipping, because there is no accumulator with greater range + * than the input (not to mention this being an inefficient way of doing it). + * + * It is a common misconception that this function is required to write audio + * data to an output stream in an audio callback. While you can do that, + * SDL_MixAudioFormat() is really only needed when you're mixing a single + * audio stream with a volume adjustment. + * + * \param dst the destination for the mixed audio. + * \param src the source audio buffer to be mixed. + * \param format the SDL_AudioFormat structure representing the desired audio + * format. + * \param len the length of the audio buffer in bytes. + * \param volume ranges from 0 - 128, and should be set to SDL_MIX_MAXVOLUME + * for full audio volume. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC void SDLCALL SDL_MixAudioFormat(Uint8 * dst, + const Uint8 * src, + SDL_AudioFormat format, + Uint32 len, int volume); + +/** + * Queue more audio on non-callback devices. + * + * If you are looking to retrieve queued audio from a non-callback capture + * device, you want SDL_DequeueAudio() instead. SDL_QueueAudio() will return + * -1 to signify an error if you use it with capture devices. + * + * SDL offers two ways to feed audio to the device: you can either supply a + * callback that SDL triggers with some frequency to obtain more audio (pull + * method), or you can supply no callback, and then SDL will expect you to + * supply data at regular intervals (push method) with this function. + * + * There are no limits on the amount of data you can queue, short of + * exhaustion of address space. Queued data will drain to the device as + * necessary without further intervention from you. If the device needs audio + * but there is not enough queued, it will play silence to make up the + * difference. This means you will have skips in your audio playback if you + * aren't routinely queueing sufficient data. + * + * This function copies the supplied data, so you are safe to free it when the + * function returns. This function is thread-safe, but queueing to the same + * device from two threads at once does not promise which buffer will be + * queued first. + * + * You may not queue audio on a device that is using an application-supplied + * callback; doing so returns an error. You have to use the audio callback or + * queue audio with this function, but not both. + * + * You should not call SDL_LockAudio() on the device before queueing; SDL + * handles locking internally for this function. + * + * Note that SDL2 does not support planar audio. You will need to resample + * from planar audio formats into a non-planar one (see SDL_AudioFormat) + * before queuing audio. + * + * \param dev the device ID to which we will queue audio. + * \param data the data to queue to the device for later playback. + * \param len the number of bytes (not samples!) to which `data` points. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_ClearQueuedAudio + * \sa SDL_GetQueuedAudioSize + */ +extern DECLSPEC int SDLCALL SDL_QueueAudio(SDL_AudioDeviceID dev, const void *data, Uint32 len); + +/** + * Dequeue more audio on non-callback devices. + * + * If you are looking to queue audio for output on a non-callback playback + * device, you want SDL_QueueAudio() instead. SDL_DequeueAudio() will always + * return 0 if you use it with playback devices. + * + * SDL offers two ways to retrieve audio from a capture device: you can either + * supply a callback that SDL triggers with some frequency as the device + * records more audio data, (push method), or you can supply no callback, and + * then SDL will expect you to retrieve data at regular intervals (pull + * method) with this function. + * + * There are no limits on the amount of data you can queue, short of + * exhaustion of address space. Data from the device will keep queuing as + * necessary without further intervention from you. This means you will + * eventually run out of memory if you aren't routinely dequeueing data. + * + * Capture devices will not queue data when paused; if you are expecting to + * not need captured audio for some length of time, use SDL_PauseAudioDevice() + * to stop the capture device from queueing more data. This can be useful + * during, say, level loading times. When unpaused, capture devices will start + * queueing data from that point, having flushed any capturable data available + * while paused. + * + * This function is thread-safe, but dequeueing from the same device from two + * threads at once does not promise which thread will dequeue data first. + * + * You may not dequeue audio from a device that is using an + * application-supplied callback; doing so returns an error. You have to use + * the audio callback, or dequeue audio with this function, but not both. + * + * You should not call SDL_LockAudio() on the device before dequeueing; SDL + * handles locking internally for this function. + * + * \param dev the device ID from which we will dequeue audio. + * \param data a pointer into where audio data should be copied. + * \param len the number of bytes (not samples!) to which (data) points. + * \returns the number of bytes dequeued, which could be less than requested; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_ClearQueuedAudio + * \sa SDL_GetQueuedAudioSize + */ +extern DECLSPEC Uint32 SDLCALL SDL_DequeueAudio(SDL_AudioDeviceID dev, void *data, Uint32 len); + +/** + * Get the number of bytes of still-queued audio. + * + * For playback devices: this is the number of bytes that have been queued for + * playback with SDL_QueueAudio(), but have not yet been sent to the hardware. + * + * Once we've sent it to the hardware, this function can not decide the exact + * byte boundary of what has been played. It's possible that we just gave the + * hardware several kilobytes right before you called this function, but it + * hasn't played any of it yet, or maybe half of it, etc. + * + * For capture devices, this is the number of bytes that have been captured by + * the device and are waiting for you to dequeue. This number may grow at any + * time, so this only informs of the lower-bound of available data. + * + * You may not queue or dequeue audio on a device that is using an + * application-supplied callback; calling this function on such a device + * always returns 0. You have to use the audio callback or queue audio, but + * not both. + * + * You should not call SDL_LockAudio() on the device before querying; SDL + * handles locking internally for this function. + * + * \param dev the device ID of which we will query queued audio size. + * \returns the number of bytes (not samples!) of queued audio. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_ClearQueuedAudio + * \sa SDL_QueueAudio + * \sa SDL_DequeueAudio + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetQueuedAudioSize(SDL_AudioDeviceID dev); + +/** + * Drop any queued audio data waiting to be sent to the hardware. + * + * Immediately after this call, SDL_GetQueuedAudioSize() will return 0. For + * output devices, the hardware will start playing silence if more audio isn't + * queued. For capture devices, the hardware will start filling the empty + * queue with new data if the capture device isn't paused. + * + * This will not prevent playback of queued audio that's already been sent to + * the hardware, as we can not undo that, so expect there to be some fraction + * of a second of audio that might still be heard. This can be useful if you + * want to, say, drop any pending music or any unprocessed microphone input + * during a level change in your game. + * + * You may not queue or dequeue audio on a device that is using an + * application-supplied callback; calling this function on such a device + * always returns 0. You have to use the audio callback or queue audio, but + * not both. + * + * You should not call SDL_LockAudio() on the device before clearing the + * queue; SDL handles locking internally for this function. + * + * This function always succeeds and thus returns void. + * + * \param dev the device ID of which to clear the audio queue. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_GetQueuedAudioSize + * \sa SDL_QueueAudio + * \sa SDL_DequeueAudio + */ +extern DECLSPEC void SDLCALL SDL_ClearQueuedAudio(SDL_AudioDeviceID dev); + + +/** + * \name Audio lock functions + * + * The lock manipulated by these functions protects the callback function. + * During a SDL_LockAudio()/SDL_UnlockAudio() pair, you can be guaranteed that + * the callback function is not running. Do not call these from the callback + * function or you will cause deadlock. + */ +/* @{ */ + +/** + * This function is a legacy means of locking the audio device. + * + * New programs might want to use SDL_LockAudioDevice() instead. This function + * is equivalent to calling... + * + * ```c + * SDL_LockAudioDevice(1); + * ``` + * + * ...and is only useful if you used the legacy SDL_OpenAudio() function. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LockAudioDevice + * \sa SDL_UnlockAudio + * \sa SDL_UnlockAudioDevice + */ +extern DECLSPEC void SDLCALL SDL_LockAudio(void); + +/** + * Use this function to lock out the audio callback function for a specified + * device. + * + * The lock manipulated by these functions protects the audio callback + * function specified in SDL_OpenAudioDevice(). During a + * SDL_LockAudioDevice()/SDL_UnlockAudioDevice() pair, you can be guaranteed + * that the callback function for that device is not running, even if the + * device is not paused. While a device is locked, any other unpaused, + * unlocked devices may still run their callbacks. + * + * Calling this function from inside your audio callback is unnecessary. SDL + * obtains this lock before calling your function, and releases it when the + * function returns. + * + * You should not hold the lock longer than absolutely necessary. If you hold + * it too long, you'll experience dropouts in your audio playback. Ideally, + * your application locks the device, sets a few variables and unlocks again. + * Do not do heavy work while holding the lock for a device. + * + * It is safe to lock the audio device multiple times, as long as you unlock + * it an equivalent number of times. The callback will not run until the + * device has been unlocked completely in this way. If your application fails + * to unlock the device appropriately, your callback will never run, you might + * hear repeating bursts of audio, and SDL_CloseAudioDevice() will probably + * deadlock. + * + * Internally, the audio device lock is a mutex; if you lock from two threads + * at once, not only will you block the audio callback, you'll block the other + * thread. + * + * \param dev the ID of the device to be locked. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_UnlockAudioDevice + */ +extern DECLSPEC void SDLCALL SDL_LockAudioDevice(SDL_AudioDeviceID dev); + +/** + * This function is a legacy means of unlocking the audio device. + * + * New programs might want to use SDL_UnlockAudioDevice() instead. This + * function is equivalent to calling... + * + * ```c + * SDL_UnlockAudioDevice(1); + * ``` + * + * ...and is only useful if you used the legacy SDL_OpenAudio() function. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LockAudio + * \sa SDL_UnlockAudioDevice + */ +extern DECLSPEC void SDLCALL SDL_UnlockAudio(void); + +/** + * Use this function to unlock the audio callback function for a specified + * device. + * + * This function should be paired with a previous SDL_LockAudioDevice() call. + * + * \param dev the ID of the device to be unlocked. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LockAudioDevice + */ +extern DECLSPEC void SDLCALL SDL_UnlockAudioDevice(SDL_AudioDeviceID dev); +/* @} *//* Audio lock functions */ + +/** + * This function is a legacy means of closing the audio device. + * + * This function is equivalent to calling... + * + * ```c + * SDL_CloseAudioDevice(1); + * ``` + * + * ...and is only useful if you used the legacy SDL_OpenAudio() function. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_OpenAudio + */ +extern DECLSPEC void SDLCALL SDL_CloseAudio(void); + +/** + * Use this function to shut down audio processing and close the audio device. + * + * The application should close open audio devices once they are no longer + * needed. Calling this function will wait until the device's audio callback + * is not running, release the audio hardware and then clean up internal + * state. No further audio will play from this device once this function + * returns. + * + * This function may block briefly while pending audio data is played by the + * hardware, so that applications don't drop the last buffer of data they + * supplied. + * + * The device ID is invalid as soon as the device is closed, and is eligible + * for reuse in a new SDL_OpenAudioDevice() call immediately. + * + * \param dev an audio device previously opened with SDL_OpenAudioDevice(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_OpenAudioDevice + */ +extern DECLSPEC void SDLCALL SDL_CloseAudioDevice(SDL_AudioDeviceID dev); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_audio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_bits.h b/third_party/SDL2/include/SDL_bits.h new file mode 100644 index 00000000000..747f5565113 --- /dev/null +++ b/third_party/SDL2/include/SDL_bits.h @@ -0,0 +1,132 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryBits + * + * Functions for fiddling with bits and bitmasks. + */ + +#ifndef SDL_bits_h_ +#define SDL_bits_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \file SDL_bits.h + */ + +/** + * Get the index of the most significant bit. Result is undefined when called + * with 0. This operation can also be stated as "count leading zeroes" and + * "log base 2". + * + * \return the index of the most significant bit, or -1 if the value is 0. + */ +#if defined(__WATCOMC__) && defined(__386__) +extern __inline int _SDL_bsr_watcom(Uint32); +#pragma aux _SDL_bsr_watcom = \ + "bsr eax, eax" \ + parm [eax] nomemory \ + value [eax] \ + modify exact [eax] nomemory; +#endif + +/** + * Use this function to get the index of the most significant (set) bit in a + * + * \param x the number to find the MSB of. + * \returns the index of the most significant bit of x, or -1 if x is 0. + */ +SDL_FORCE_INLINE int +SDL_MostSignificantBitIndex32(Uint32 x) +{ +#if defined(__GNUC__) && (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) + /* Count Leading Zeroes builtin in GCC. + * http://gcc.gnu.org/onlinedocs/gcc-4.3.4/gcc/Other-Builtins.html + */ + if (x == 0) { + return -1; + } + return 31 - __builtin_clz(x); +#elif defined(__WATCOMC__) && defined(__386__) + if (x == 0) { + return -1; + } + return _SDL_bsr_watcom(x); +#elif defined(_MSC_VER) + unsigned long index; + if (_BitScanReverse(&index, x)) { + return index; + } + return -1; +#else + /* Based off of Bit Twiddling Hacks by Sean Eron Anderson + * , released in the public domain. + * http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog + */ + const Uint32 b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000}; + const int S[] = {1, 2, 4, 8, 16}; + + int msbIndex = 0; + int i; + + if (x == 0) { + return -1; + } + + for (i = 4; i >= 0; i--) + { + if (x & b[i]) + { + x >>= S[i]; + msbIndex |= S[i]; + } + } + + return msbIndex; +#endif +} + +SDL_FORCE_INLINE SDL_bool +SDL_HasExactlyOneBitSet32(Uint32 x) +{ + if (x && !(x & (x - 1))) { + return SDL_TRUE; + } + return SDL_FALSE; +} + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_bits_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_blendmode.h b/third_party/SDL2/include/SDL_blendmode.h new file mode 100644 index 00000000000..c0c68113315 --- /dev/null +++ b/third_party/SDL2/include/SDL_blendmode.h @@ -0,0 +1,199 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryBlendmode + * + * Header file declaring the SDL_BlendMode enumeration + */ + +#ifndef SDL_blendmode_h_ +#define SDL_blendmode_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The blend mode used in SDL_RenderCopy() and drawing operations. + */ +typedef enum SDL_BlendMode +{ + SDL_BLENDMODE_NONE = 0x00000000, /**< no blending + dstRGBA = srcRGBA */ + SDL_BLENDMODE_BLEND = 0x00000001, /**< alpha blending + dstRGB = (srcRGB * srcA) + (dstRGB * (1-srcA)) + dstA = srcA + (dstA * (1-srcA)) */ + SDL_BLENDMODE_ADD = 0x00000002, /**< additive blending + dstRGB = (srcRGB * srcA) + dstRGB + dstA = dstA */ + SDL_BLENDMODE_MOD = 0x00000004, /**< color modulate + dstRGB = srcRGB * dstRGB + dstA = dstA */ + SDL_BLENDMODE_MUL = 0x00000008, /**< color multiply + dstRGB = (srcRGB * dstRGB) + (dstRGB * (1-srcA)) + dstA = dstA */ + SDL_BLENDMODE_INVALID = 0x7FFFFFFF + + /* Additional custom blend modes can be returned by SDL_ComposeCustomBlendMode() */ + +} SDL_BlendMode; + +/** + * The blend operation used when combining source and destination pixel + * components + */ +typedef enum SDL_BlendOperation +{ + SDL_BLENDOPERATION_ADD = 0x1, /**< dst + src: supported by all renderers */ + SDL_BLENDOPERATION_SUBTRACT = 0x2, /**< src - dst : supported by D3D9, D3D11, OpenGL, OpenGLES */ + SDL_BLENDOPERATION_REV_SUBTRACT = 0x3, /**< dst - src : supported by D3D9, D3D11, OpenGL, OpenGLES */ + SDL_BLENDOPERATION_MINIMUM = 0x4, /**< min(dst, src) : supported by D3D9, D3D11 */ + SDL_BLENDOPERATION_MAXIMUM = 0x5 /**< max(dst, src) : supported by D3D9, D3D11 */ +} SDL_BlendOperation; + +/** + * The normalized factor used to multiply pixel components + */ +typedef enum SDL_BlendFactor +{ + SDL_BLENDFACTOR_ZERO = 0x1, /**< 0, 0, 0, 0 */ + SDL_BLENDFACTOR_ONE = 0x2, /**< 1, 1, 1, 1 */ + SDL_BLENDFACTOR_SRC_COLOR = 0x3, /**< srcR, srcG, srcB, srcA */ + SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR = 0x4, /**< 1-srcR, 1-srcG, 1-srcB, 1-srcA */ + SDL_BLENDFACTOR_SRC_ALPHA = 0x5, /**< srcA, srcA, srcA, srcA */ + SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA = 0x6, /**< 1-srcA, 1-srcA, 1-srcA, 1-srcA */ + SDL_BLENDFACTOR_DST_COLOR = 0x7, /**< dstR, dstG, dstB, dstA */ + SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR = 0x8, /**< 1-dstR, 1-dstG, 1-dstB, 1-dstA */ + SDL_BLENDFACTOR_DST_ALPHA = 0x9, /**< dstA, dstA, dstA, dstA */ + SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA = 0xA /**< 1-dstA, 1-dstA, 1-dstA, 1-dstA */ +} SDL_BlendFactor; + +/** + * Compose a custom blend mode for renderers. + * + * The functions SDL_SetRenderDrawBlendMode and SDL_SetTextureBlendMode accept + * the SDL_BlendMode returned by this function if the renderer supports it. + * + * A blend mode controls how the pixels from a drawing operation (source) get + * combined with the pixels from the render target (destination). First, the + * components of the source and destination pixels get multiplied with their + * blend factors. Then, the blend operation takes the two products and + * calculates the result that will get stored in the render target. + * + * Expressed in pseudocode, it would look like this: + * + * ```c + * dstRGB = colorOperation(srcRGB * srcColorFactor, dstRGB * dstColorFactor); + * dstA = alphaOperation(srcA * srcAlphaFactor, dstA * dstAlphaFactor); + * ``` + * + * Where the functions `colorOperation(src, dst)` and `alphaOperation(src, + * dst)` can return one of the following: + * + * - `src + dst` + * - `src - dst` + * - `dst - src` + * - `min(src, dst)` + * - `max(src, dst)` + * + * The red, green, and blue components are always multiplied with the first, + * second, and third components of the SDL_BlendFactor, respectively. The + * fourth component is not used. + * + * The alpha component is always multiplied with the fourth component of the + * SDL_BlendFactor. The other components are not used in the alpha + * calculation. + * + * Support for these blend modes varies for each renderer. To check if a + * specific SDL_BlendMode is supported, create a renderer and pass it to + * either SDL_SetRenderDrawBlendMode or SDL_SetTextureBlendMode. They will + * return with an error if the blend mode is not supported. + * + * This list describes the support of custom blend modes for each renderer in + * SDL 2.0.6. All renderers support the four blend modes listed in the + * SDL_BlendMode enumeration. + * + * - **direct3d**: Supports all operations with all factors. However, some + * factors produce unexpected results with `SDL_BLENDOPERATION_MINIMUM` and + * `SDL_BLENDOPERATION_MAXIMUM`. + * - **direct3d11**: Same as Direct3D 9. + * - **opengl**: Supports the `SDL_BLENDOPERATION_ADD` operation with all + * factors. OpenGL versions 1.1, 1.2, and 1.3 do not work correctly with SDL + * 2.0.6. + * - **opengles**: Supports the `SDL_BLENDOPERATION_ADD` operation with all + * factors. Color and alpha factors need to be the same. OpenGL ES 1 + * implementation specific: May also support `SDL_BLENDOPERATION_SUBTRACT` + * and `SDL_BLENDOPERATION_REV_SUBTRACT`. May support color and alpha + * operations being different from each other. May support color and alpha + * factors being different from each other. + * - **opengles2**: Supports the `SDL_BLENDOPERATION_ADD`, + * `SDL_BLENDOPERATION_SUBTRACT`, `SDL_BLENDOPERATION_REV_SUBTRACT` + * operations with all factors. + * - **psp**: No custom blend mode support. + * - **software**: No custom blend mode support. + * + * Some renderers do not provide an alpha component for the default render + * target. The `SDL_BLENDFACTOR_DST_ALPHA` and + * `SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA` factors do not have an effect in this + * case. + * + * \param srcColorFactor the SDL_BlendFactor applied to the red, green, and + * blue components of the source pixels. + * \param dstColorFactor the SDL_BlendFactor applied to the red, green, and + * blue components of the destination pixels. + * \param colorOperation the SDL_BlendOperation used to combine the red, + * green, and blue components of the source and + * destination pixels. + * \param srcAlphaFactor the SDL_BlendFactor applied to the alpha component of + * the source pixels. + * \param dstAlphaFactor the SDL_BlendFactor applied to the alpha component of + * the destination pixels. + * \param alphaOperation the SDL_BlendOperation used to combine the alpha + * component of the source and destination pixels. + * \returns an SDL_BlendMode that represents the chosen factors and + * operations. + * + * \since This function is available since SDL 2.0.6. + * + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_GetRenderDrawBlendMode + * \sa SDL_SetTextureBlendMode + * \sa SDL_GetTextureBlendMode + */ +extern DECLSPEC SDL_BlendMode SDLCALL SDL_ComposeCustomBlendMode(SDL_BlendFactor srcColorFactor, + SDL_BlendFactor dstColorFactor, + SDL_BlendOperation colorOperation, + SDL_BlendFactor srcAlphaFactor, + SDL_BlendFactor dstAlphaFactor, + SDL_BlendOperation alphaOperation); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_blendmode_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_clipboard.h b/third_party/SDL2/include/SDL_clipboard.h new file mode 100644 index 00000000000..2ae16a1d05e --- /dev/null +++ b/third_party/SDL2/include/SDL_clipboard.h @@ -0,0 +1,141 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryClipboard + * + * Include file for SDL clipboard handling + */ + +#ifndef SDL_clipboard_h_ +#define SDL_clipboard_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Function prototypes */ + +/** + * Put UTF-8 text into the clipboard. + * + * \param text the text to store in the clipboard. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetClipboardText + * \sa SDL_HasClipboardText + */ +extern DECLSPEC int SDLCALL SDL_SetClipboardText(const char *text); + +/** + * Get UTF-8 text from the clipboard, which must be freed with SDL_free(). + * + * This functions returns empty string if there was not enough memory left for + * a copy of the clipboard's content. + * + * \returns the clipboard text on success or an empty string on failure; call + * SDL_GetError() for more information. Caller must call SDL_free() + * on the returned pointer when done with it (even if there was an + * error). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HasClipboardText + * \sa SDL_SetClipboardText + */ +extern DECLSPEC char * SDLCALL SDL_GetClipboardText(void); + +/** + * Query whether the clipboard exists and contains a non-empty text string. + * + * \returns SDL_TRUE if the clipboard has text, or SDL_FALSE if it does not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetClipboardText + * \sa SDL_SetClipboardText + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasClipboardText(void); + +/** + * Put UTF-8 text into the primary selection. + * + * \param text the text to store in the primary selection. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.26.0. + * + * \sa SDL_GetPrimarySelectionText + * \sa SDL_HasPrimarySelectionText + */ +extern DECLSPEC int SDLCALL SDL_SetPrimarySelectionText(const char *text); + +/** + * Get UTF-8 text from the primary selection, which must be freed with + * SDL_free(). + * + * This functions returns empty string if there was not enough memory left for + * a copy of the primary selection's content. + * + * \returns the primary selection text on success or an empty string on + * failure; call SDL_GetError() for more information. Caller must + * call SDL_free() on the returned pointer when done with it (even if + * there was an error). + * + * \since This function is available since SDL 2.26.0. + * + * \sa SDL_HasPrimarySelectionText + * \sa SDL_SetPrimarySelectionText + */ +extern DECLSPEC char * SDLCALL SDL_GetPrimarySelectionText(void); + +/** + * Query whether the primary selection exists and contains a non-empty text + * string. + * + * \returns SDL_TRUE if the primary selection has text, or SDL_FALSE if it + * does not. + * + * \since This function is available since SDL 2.26.0. + * + * \sa SDL_GetPrimarySelectionText + * \sa SDL_SetPrimarySelectionText + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasPrimarySelectionText(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_clipboard_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_config.h b/third_party/SDL2/include/SDL_config.h new file mode 100644 index 00000000000..c34af2479da --- /dev/null +++ b/third_party/SDL2/include/SDL_config.h @@ -0,0 +1,505 @@ +/* include/SDL_config.h. Generated from SDL_config.h.in by configure. */ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_h_ +#define SDL_config_h_ + +/** + * \file SDL_config.h.in + * + * This is a set of defines to configure the SDL features + */ + +/* General platform specific identifiers */ +#include "SDL_platform.h" + +/* Make sure that this isn't included by Visual C++ */ +#ifdef _MSC_VER +#error You should run git checkout -f include/SDL_config.h +#endif + +/* C language features */ +/* #undef const */ +/* #undef inline */ +/* #undef volatile */ + +/* C datatypes */ +#if defined(__LP64__) || defined(_LP64) || defined(_WIN64) +#define SIZEOF_VOIDP 8 +#else +#define SIZEOF_VOIDP 4 +#endif + +#define HAVE_GCC_ATOMICS 1 +/* #undef HAVE_GCC_SYNC_LOCK_TEST_AND_SET */ + +/* Comment this if you want to build without any C library requirements */ +#define HAVE_LIBC 1 +#ifdef HAVE_LIBC + +/* Useful headers */ +#define STDC_HEADERS 1 +#define HAVE_ALLOCA_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_ICONV_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MATH_H 1 +#define HAVE_MEMORY_H 1 +/* #undef HAVE_SIGNAL_H */ +#define HAVE_STDARG_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_WCHAR_H 1 +#define HAVE_LINUX_INPUT_H 1 +/* #undef HAVE_PTHREAD_NP_H */ +/* #undef HAVE_LIBUNWIND_H */ + +/* C library functions */ +#define HAVE_DLOPEN 1 +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#ifndef __WIN32__ /* Don't use C runtime versions of these on Windows */ +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_UNSETENV 1 +#endif +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_WCSLEN 1 +/* #undef HAVE_WCSLCPY */ +/* #undef HAVE_WCSLCAT */ +/* #undef HAVE__WCSDUP */ +#define HAVE_WCSDUP 1 +#define HAVE_WCSSTR 1 +#define HAVE_WCSCMP 1 +#define HAVE_WCSNCMP 1 +#define HAVE_WCSCASECMP 1 +/* #undef HAVE__WCSICMP */ +#define HAVE_WCSNCASECMP 1 +/* #undef HAVE__WCSNICMP */ +#define HAVE_STRLEN 1 +/* #undef HAVE_STRLCPY */ +/* #undef HAVE_STRLCAT */ +/* #undef HAVE__STRREV */ +/* #undef HAVE__STRUPR */ +/* #undef HAVE__STRLWR */ +#define HAVE_INDEX 1 +#define HAVE_RINDEX 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 +/* #undef HAVE_ITOA */ +/* #undef HAVE__LTOA */ +/* #undef HAVE__UITOA */ +/* #undef HAVE__ULTOA */ +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +/* #undef HAVE__I64TOA */ +/* #undef HAVE__UI64TOA */ +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +/* #undef HAVE__STRICMP */ +#define HAVE_STRCASECMP 1 +/* #undef HAVE__STRNICMP */ +#define HAVE_STRNCASECMP 1 +#define HAVE_STRCASESTR 1 +/* #undef HAVE_SSCANF */ +#define HAVE_VSSCANF 1 +/* #undef HAVE_SNPRINTF */ +#define HAVE_VSNPRINTF 1 +#define HAVE_M_PI /**/ +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEIL 1 +#define HAVE_CEILF 1 +#define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE_FOPEN64 1 +#define HAVE_FSEEKO 1 +#define HAVE_FSEEKO64 1 +/* #undef HAVE_SIGACTION */ +/* #undef HAVE_SA_SIGACTION */ +#define HAVE_SETJMP 1 +#define HAVE_NANOSLEEP 1 +#define HAVE_SYSCONF 1 +/* #undef HAVE_SYSCTLBYNAME */ +#define HAVE_CLOCK_GETTIME 1 +/* #undef HAVE_GETPAGESIZE */ +#define HAVE_MPROTECT 1 +#define HAVE_ICONV 1 +/* #undef SDL_USE_LIBICONV */ +/* #undef HAVE_PTHREAD_SETNAME_NP */ +/* #undef HAVE_PTHREAD_SET_NAME_NP */ +/* #undef HAVE_SEM_TIMEDWAIT */ +#define HAVE_GETAUXVAL 1 +/* #undef HAVE_ELF_AUX_INFO */ +#define HAVE_POLL 1 +#define HAVE_MEMFD_CREATE 1 +#define HAVE_POSIX_FALLOCATE 1 +#define HAVE__EXIT 1 + +#else +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDINT_H 1 +#endif /* HAVE_LIBC */ + +#define SDL_DISABLE_IMMINTRIN_H +#define SDL_DISABLE_MMINTRIN_H +#define SDL_DISABLE_XMMINTRIN_H +#define SDL_DISABLE_EMMINTRIN_H +#define SDL_DISABLE_PMMINTRIN_H + +#define HAVE_O_CLOEXEC 1 +/* #undef HAVE_ALTIVEC_H */ +/* #undef HAVE_DBUS_DBUS_H */ +/* #undef HAVE_FCITX */ +#define HAVE_SYS_INOTIFY_H 1 +#define HAVE_INOTIFY_INIT 1 +#define HAVE_INOTIFY_INIT1 1 +#define HAVE_INOTIFY 1 +/* #undef HAVE_IBUS_IBUS_H */ +//#define HAVE_IMMINTRIN_H 1 +/* #undef HAVE_LIBUDEV_H */ +/* #undef HAVE_LIBUSB */ +/* #undef HAVE_LIBSAMPLERATE_H */ +/* #undef HAVE_LIBDECOR_H */ +/* #undef HAVE_LSXINTRIN_H */ +/* #undef HAVE_LASXINTRIN_H */ + +/* #undef HAVE_DDRAW_H */ +/* #undef HAVE_DINPUT_H */ +/* #undef HAVE_DSOUND_H */ +/* #undef HAVE_DXGI_H */ +/* #undef HAVE_WINDOWS_GAMING_INPUT_H */ +/* #undef HAVE_XINPUT_H */ + +/* #undef HAVE_MMDEVICEAPI_H */ +/* #undef HAVE_AUDIOCLIENT_H */ +/* #undef HAVE_TPCSHRD_H */ +/* #undef HAVE_SENSORSAPI_H */ +/* #undef HAVE_ROAPI_H */ +/* #undef HAVE_SHELLSCALINGAPI_H */ + +/* SDL internal assertion support */ +/* #undef SDL_DEFAULT_ASSERT_LEVEL */ + +/* Allow disabling of core subsystems */ +/* #undef SDL_ATOMIC_DISABLED */ +/* #undef SDL_AUDIO_DISABLED */ +/* #undef SDL_CPUINFO_DISABLED */ +/* #undef SDL_EVENTS_DISABLED */ +#define SDL_FILE_DISABLED 1 +/* #undef SDL_JOYSTICK_DISABLED */ +#define SDL_HAPTIC_DISABLED +/* #undef SDL_HIDAPI_DISABLED */ +#define SDL_SENSOR_DISABLED 1 +/* #undef SDL_LOADSO_DISABLED */ +/* #undef SDL_RENDER_DISABLED */ +#define SDL_THREADS_DISABLED 1 +/* #undef SDL_TIMERS_DISABLED */ +/* #undef SDL_VIDEO_DISABLED */ +#define SDL_POWER_DISABLED 1 +#define SDL_FILESYSTEM_DISABLED 1 +#define SDL_LOCALE_DISABLED 1 +#define SDL_MISC_DISABLED 1 + +/* Enable various audio drivers */ +/* #undef SDL_AUDIO_DRIVER_AAUDIO */ +/* #undef SDL_AUDIO_DRIVER_ALSA */ +/* #undef SDL_AUDIO_DRIVER_ALSA_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_ANDROID */ +/* #undef SDL_AUDIO_DRIVER_ARTS */ +/* #undef SDL_AUDIO_DRIVER_ARTS_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_COREAUDIO */ +/* #undef SDL_AUDIO_DRIVER_DISK */ +/* #undef SDL_AUDIO_DRIVER_DSOUND */ +#define SDL_AUDIO_DRIVER_DUMMY 1 +/* #undef SDL_AUDIO_DRIVER_EMSCRIPTEN */ +/* #undef SDL_AUDIO_DRIVER_ESD */ +/* #undef SDL_AUDIO_DRIVER_ESD_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_FUSIONSOUND */ +/* #undef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_HAIKU */ +/* #undef SDL_AUDIO_DRIVER_JACK */ +/* #undef SDL_AUDIO_DRIVER_JACK_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_NACL */ +/* #undef SDL_AUDIO_DRIVER_NAS */ +/* #undef SDL_AUDIO_DRIVER_NAS_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_NETBSD */ +/* #undef SDL_AUDIO_DRIVER_OPENSLES */ +/* #undef SDL_AUDIO_DRIVER_OSS */ +/* #undef SDL_AUDIO_DRIVER_PAUDIO */ +/* #undef SDL_AUDIO_DRIVER_PIPEWIRE */ +/* #undef SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_PULSEAUDIO */ +/* #undef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_QSA */ +/* #undef SDL_AUDIO_DRIVER_SNDIO */ +/* #undef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC */ +/* #undef SDL_AUDIO_DRIVER_SUNAUDIO */ +/* #undef SDL_AUDIO_DRIVER_WASAPI */ +/* #undef SDL_AUDIO_DRIVER_WINMM */ +/* #undef SDL_AUDIO_DRIVER_OS2 */ + +/* Enable various input drivers */ +/* #undef SDL_INPUT_LINUXEV 1 */ +/* #undef SDL_INPUT_FBSDKBIO */ +#define SDL_INPUT_LINUXKD 1 +/* #undef SDL_INPUT_WSCONS */ +/* #undef SDL_JOYSTICK_HAIKU */ +/* #undef SDL_JOYSTICK_DINPUT */ +/* #undef SDL_JOYSTICK_WGI */ +/* #undef SDL_JOYSTICK_XINPUT */ +#define SDL_JOYSTICK_DUMMY 1 +/* #undef SDL_JOYSTICK_IOKIT */ +/* #undef SDL_JOYSTICK_MFI */ +/* #undef SDL_JOYSTICK_LINUX */ +/* #undef SDL_JOYSTICK_ANDROID */ +/* #undef SDL_JOYSTICK_OS2 */ +/* #undef SDL_JOYSTICK_USBHID */ +/* #undef SDL_HAVE_MACHINE_JOYSTICK_H */ +/* #undef SDL_JOYSTICK_HIDAPI */ +/* #undef SDL_JOYSTICK_RAWINPUT */ +/* #undef SDL_JOYSTICK_EMSCRIPTEN */ +#define SDL_JOYSTICK_VIRTUAL 1 +/* #undef SDL_HAPTIC_DUMMY */ +/* #undef SDL_HAPTIC_ANDROID */ +#define SDL_HAPTIC_LINUX 1 +/* #undef SDL_HAPTIC_IOKIT */ +/* #undef SDL_HAPTIC_DINPUT */ +/* #undef SDL_HAPTIC_XINPUT */ + +/* Enable various sensor drivers */ +/* #undef SDL_SENSOR_ANDROID */ +/* #undef SDL_SENSOR_COREMOTION */ +/* #undef SDL_SENSOR_WINDOWS */ +/* #undef SDL_SENSOR_DUMMY */ + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_DLOPEN 1 +/* #undef SDL_LOADSO_DUMMY */ +/* #undef SDL_LOADSO_LDG */ +/* #undef SDL_LOADSO_WINDOWS */ +/* #undef SDL_LOADSO_OS2 */ + +/* Enable various threading systems */ +/* #undef SDL_THREAD_GENERIC_COND_SUFFIX */ +/* #undef SDL_THREAD_PTHREAD */ +/* #undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX */ +/* #undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP */ +/* #undef SDL_THREAD_WINDOWS */ +/* #undef SDL_THREAD_OS2 */ + +/* Enable various timer systems */ +/* #undef SDL_TIMER_HAIKU */ +/* #undef SDL_TIMER_DUMMY */ +#define SDL_TIMER_UNIX 1 +/* #undef SDL_TIMER_WINDOWS */ +/* #undef SDL_TIMER_OS2 */ + +/* Enable various video drivers */ +/* #undef SDL_VIDEO_DRIVER_HAIKU */ +/* #undef SDL_VIDEO_DRIVER_COCOA */ +/* #undef SDL_VIDEO_DRIVER_DIRECTFB */ +/* #undef SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC */ +#define SDL_VIDEO_DRIVER_DUMMY 1 +/* #undef SDL_VIDEO_DRIVER_WINDOWS */ +/* #undef SDL_VIDEO_DRIVER_WAYLAND */ +/* #undef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH */ +/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC */ +/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL */ +/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR */ +/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON */ +/* #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR */ +/* #undef SDL_VIDEO_DRIVER_X11 */ +/* #undef SDL_VIDEO_DRIVER_RPI */ +/* #undef SDL_VIDEO_DRIVER_KMSDRM */ +/* #undef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC */ +/* #undef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM */ +/* #undef SDL_VIDEO_DRIVER_ANDROID */ +/* #undef SDL_VIDEO_DRIVER_EMSCRIPTEN */ +/* #undef SDL_VIDEO_DRIVER_OFFSCREEN */ +/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC */ +/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT */ +/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR */ +/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 */ +/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XFIXES */ +/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR */ +/* #undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS */ +/* #undef SDL_VIDEO_DRIVER_X11_XCURSOR */ +/* #undef SDL_VIDEO_DRIVER_X11_XDBE */ +/* #undef SDL_VIDEO_DRIVER_X11_XINPUT2 */ +/* #undef SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH */ +/* #undef SDL_VIDEO_DRIVER_X11_XFIXES */ +/* #undef SDL_VIDEO_DRIVER_X11_XRANDR */ +/* #undef SDL_VIDEO_DRIVER_X11_XSCRNSAVER */ +/* #undef SDL_VIDEO_DRIVER_X11_XSHAPE */ +/* #undef SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS */ +/* #undef SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM */ +/* #undef SDL_VIDEO_DRIVER_NACL */ +/* #undef SDL_VIDEO_DRIVER_VIVANTE */ +/* #undef SDL_VIDEO_DRIVER_VIVANTE_VDK */ +/* #undef SDL_VIDEO_DRIVER_OS2 */ +/* #undef SDL_VIDEO_DRIVER_QNX */ +/* #undef SDL_VIDEO_DRIVER_RISCOS */ + +/* #undef SDL_VIDEO_RENDER_D3D */ +/* #undef SDL_VIDEO_RENDER_D3D11 */ +/* #undef SDL_VIDEO_RENDER_D3D12 */ +/* #undef SDL_VIDEO_RENDER_OGL */ +/* #undef SDL_VIDEO_RENDER_OGL_ES */ +/* #undef SDL_VIDEO_RENDER_OGL_ES2 */ +/* #undef SDL_VIDEO_RENDER_DIRECTFB */ +/* #undef SDL_VIDEO_RENDER_METAL */ + +/* Enable OpenGL support */ +/* #undef SDL_VIDEO_OPENGL */ +/* #undef SDL_VIDEO_OPENGL_ES */ +/* #undef SDL_VIDEO_OPENGL_ES2 */ +/* #undef SDL_VIDEO_OPENGL_BGL */ +/* #undef SDL_VIDEO_OPENGL_CGL */ +/* #undef SDL_VIDEO_OPENGL_EGL */ +/* #undef SDL_VIDEO_OPENGL_GLX */ +/* #undef SDL_VIDEO_OPENGL_WGL */ +/* #undef SDL_VIDEO_OPENGL_OSMESA */ +/* #undef SDL_VIDEO_OPENGL_OSMESA_DYNAMIC */ + +/* Enable Vulkan support */ +/* #undef SDL_VIDEO_VULKAN */ + +/* Enable Metal support */ +/* #undef SDL_VIDEO_METAL */ + +/* Enable system power support */ +/* #undef SDL_POWER_LINUX */ +/* #undef SDL_POWER_WINDOWS */ +/* #undef SDL_POWER_MACOSX */ +/* #undef SDL_POWER_HAIKU */ +/* #undef SDL_POWER_ANDROID */ +/* #undef SDL_POWER_EMSCRIPTEN */ +/* #undef SDL_POWER_HARDWIRED */ + +/* Enable system filesystem support */ +/* #undef SDL_FILESYSTEM_ANDROID */ +/* #undef SDL_FILESYSTEM_HAIKU */ +/* #undef SDL_FILESYSTEM_COCOA */ +/* #undef SDL_FILESYSTEM_DUMMY */ +/* #undef SDL_FILESYSTEM_RISCOS */ +/* #undef SDL_FILESYSTEM_UNIX */ +/* #undef SDL_FILESYSTEM_WINDOWS */ +/* #undef SDL_FILESYSTEM_NACL */ +/* #undef SDL_FILESYSTEM_EMSCRIPTEN */ +/* #undef SDL_FILESYSTEM_OS2 */ +/* #undef SDL_FILESYSTEM_VITA */ +/* #undef SDL_FILESYSTEM_PSP */ +/* #undef SDL_FILESYSTEM_PS2 */ + +/* Enable misc subsystem */ +/* #undef SDL_MISC_DUMMY */ + +/* Enable locale subsystem */ +/* #undef SDL_LOCALE_DUMMY */ + +/* Enable assembly routines */ +/* #undef SDL_ALTIVEC_BLITTERS */ +/* #undef SDL_ARM_SIMD_BLITTERS */ +/* #undef SDL_ARM_NEON_BLITTERS */ + +/* Whether SDL_DYNAMIC_API needs dlopen() */ +#define DYNAPI_NEEDS_DLOPEN 1 + +/* Enable ime support */ +/* #undef SDL_USE_IME */ + +/* Enable dynamic udev support */ +/* #undef SDL_UDEV_DYNAMIC */ + +/* Enable dynamic libusb support */ +/* #undef SDL_LIBUSB_DYNAMIC */ + +/* Enable dynamic libsamplerate support */ +/* #undef SDL_LIBSAMPLERATE_DYNAMIC */ + +/* Libdecor get min/max content size functions */ +/* #undef SDL_HAVE_LIBDECOR_GET_MIN_MAX */ + +#endif /* SDL_config_h_ */ diff --git a/third_party/SDL2/include/SDL_config.h.cmake b/third_party/SDL2/include/SDL_config.h.cmake new file mode 100644 index 00000000000..ef014e7ddc4 --- /dev/null +++ b/third_party/SDL2/include/SDL_config.h.cmake @@ -0,0 +1,570 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_h_ +#define SDL_config_h_ + +/** + * \file SDL_config.h.in + * + * This is a set of defines to configure the SDL features + */ + +/* General platform specific identifiers */ +#include "SDL_platform.h" + +/* C language features */ +#cmakedefine const @HAVE_CONST@ +#cmakedefine inline @HAVE_INLINE@ +#cmakedefine volatile @HAVE_VOLATILE@ + +/* C datatypes */ +/* Define SIZEOF_VOIDP for 64/32 architectures */ +#if defined(__LP64__) || defined(_LP64) || defined(_WIN64) +#define SIZEOF_VOIDP 8 +#else +#define SIZEOF_VOIDP 4 +#endif + +#cmakedefine HAVE_GCC_ATOMICS @HAVE_GCC_ATOMICS@ +#cmakedefine HAVE_GCC_SYNC_LOCK_TEST_AND_SET @HAVE_GCC_SYNC_LOCK_TEST_AND_SET@ + +/* Comment this if you want to build without any C library requirements */ +#cmakedefine HAVE_LIBC 1 +#ifdef HAVE_LIBC + +/* Useful headers */ +#cmakedefine STDC_HEADERS 1 +#cmakedefine HAVE_ALLOCA_H 1 +#cmakedefine HAVE_CTYPE_H 1 +#cmakedefine HAVE_FLOAT_H 1 +#cmakedefine HAVE_ICONV_H 1 +#cmakedefine HAVE_INTTYPES_H 1 +#cmakedefine HAVE_LIMITS_H 1 +#cmakedefine HAVE_MALLOC_H 1 +#cmakedefine HAVE_MATH_H 1 +#cmakedefine HAVE_MEMORY_H 1 +#cmakedefine HAVE_SIGNAL_H 1 +#cmakedefine HAVE_STDARG_H 1 +#cmakedefine HAVE_STDDEF_H 1 +#cmakedefine HAVE_STDINT_H 1 +#cmakedefine HAVE_STDIO_H 1 +#cmakedefine HAVE_STDLIB_H 1 +#cmakedefine HAVE_STRINGS_H 1 +#cmakedefine HAVE_STRING_H 1 +#cmakedefine HAVE_SYS_TYPES_H 1 +#cmakedefine HAVE_WCHAR_H 1 +#cmakedefine HAVE_LINUX_INPUT_H 1 +#cmakedefine HAVE_PTHREAD_NP_H 1 +#cmakedefine HAVE_LIBUNWIND_H 1 + +/* C library functions */ +#cmakedefine HAVE_DLOPEN 1 +#cmakedefine HAVE_MALLOC 1 +#cmakedefine HAVE_CALLOC 1 +#cmakedefine HAVE_REALLOC 1 +#cmakedefine HAVE_FREE 1 +#cmakedefine HAVE_ALLOCA 1 +#ifndef __WIN32__ /* Don't use C runtime versions of these on Windows */ +#cmakedefine HAVE_GETENV 1 +#cmakedefine HAVE_SETENV 1 +#cmakedefine HAVE_PUTENV 1 +#cmakedefine HAVE_UNSETENV 1 +#endif +#cmakedefine HAVE_QSORT 1 +#cmakedefine HAVE_BSEARCH 1 +#cmakedefine HAVE_ABS 1 +#cmakedefine HAVE_BCOPY 1 +#cmakedefine HAVE_MEMSET 1 +#cmakedefine HAVE_MEMCPY 1 +#cmakedefine HAVE_MEMMOVE 1 +#cmakedefine HAVE_MEMCMP 1 +#cmakedefine HAVE_WCSLEN 1 +#cmakedefine HAVE_WCSLCPY 1 +#cmakedefine HAVE_WCSLCAT 1 +#cmakedefine HAVE__WCSDUP 1 +#cmakedefine HAVE_WCSDUP 1 +#cmakedefine HAVE_WCSSTR 1 +#cmakedefine HAVE_WCSCMP 1 +#cmakedefine HAVE_WCSNCMP 1 +#cmakedefine HAVE_WCSCASECMP 1 +#cmakedefine HAVE__WCSICMP 1 +#cmakedefine HAVE_WCSNCASECMP 1 +#cmakedefine HAVE__WCSNICMP 1 +#cmakedefine HAVE_STRLEN 1 +#cmakedefine HAVE_STRLCPY 1 +#cmakedefine HAVE_STRLCAT 1 +#cmakedefine HAVE__STRREV 1 +#cmakedefine HAVE__STRUPR 1 +#cmakedefine HAVE__STRLWR 1 +#cmakedefine HAVE_INDEX 1 +#cmakedefine HAVE_RINDEX 1 +#cmakedefine HAVE_STRCHR 1 +#cmakedefine HAVE_STRRCHR 1 +#cmakedefine HAVE_STRSTR 1 +#cmakedefine HAVE_STRTOK_R 1 +#cmakedefine HAVE_ITOA 1 +#cmakedefine HAVE__LTOA 1 +#cmakedefine HAVE__UITOA 1 +#cmakedefine HAVE__ULTOA 1 +#cmakedefine HAVE_STRTOL 1 +#cmakedefine HAVE_STRTOUL 1 +#cmakedefine HAVE__I64TOA 1 +#cmakedefine HAVE__UI64TOA 1 +#cmakedefine HAVE_STRTOLL 1 +#cmakedefine HAVE_STRTOULL 1 +#cmakedefine HAVE_STRTOD 1 +#cmakedefine HAVE_ATOI 1 +#cmakedefine HAVE_ATOF 1 +#cmakedefine HAVE_STRCMP 1 +#cmakedefine HAVE_STRNCMP 1 +#cmakedefine HAVE__STRICMP 1 +#cmakedefine HAVE_STRCASECMP 1 +#cmakedefine HAVE__STRNICMP 1 +#cmakedefine HAVE_STRNCASECMP 1 +#cmakedefine HAVE_STRCASESTR 1 +#cmakedefine HAVE_SSCANF 1 +#cmakedefine HAVE_VSSCANF 1 +#cmakedefine HAVE_VSNPRINTF 1 +#cmakedefine HAVE_M_PI 1 +#cmakedefine HAVE_ACOS 1 +#cmakedefine HAVE_ACOSF 1 +#cmakedefine HAVE_ASIN 1 +#cmakedefine HAVE_ASINF 1 +#cmakedefine HAVE_ATAN 1 +#cmakedefine HAVE_ATANF 1 +#cmakedefine HAVE_ATAN2 1 +#cmakedefine HAVE_ATAN2F 1 +#cmakedefine HAVE_CEIL 1 +#cmakedefine HAVE_CEILF 1 +#cmakedefine HAVE_COPYSIGN 1 +#cmakedefine HAVE_COPYSIGNF 1 +#cmakedefine HAVE_COS 1 +#cmakedefine HAVE_COSF 1 +#cmakedefine HAVE_EXP 1 +#cmakedefine HAVE_EXPF 1 +#cmakedefine HAVE_FABS 1 +#cmakedefine HAVE_FABSF 1 +#cmakedefine HAVE_FLOOR 1 +#cmakedefine HAVE_FLOORF 1 +#cmakedefine HAVE_FMOD 1 +#cmakedefine HAVE_FMODF 1 +#cmakedefine HAVE_LOG 1 +#cmakedefine HAVE_LOGF 1 +#cmakedefine HAVE_LOG10 1 +#cmakedefine HAVE_LOG10F 1 +#cmakedefine HAVE_LROUND 1 +#cmakedefine HAVE_LROUNDF 1 +#cmakedefine HAVE_POW 1 +#cmakedefine HAVE_POWF 1 +#cmakedefine HAVE_ROUND 1 +#cmakedefine HAVE_ROUNDF 1 +#cmakedefine HAVE_SCALBN 1 +#cmakedefine HAVE_SCALBNF 1 +#cmakedefine HAVE_SIN 1 +#cmakedefine HAVE_SINF 1 +#cmakedefine HAVE_SQRT 1 +#cmakedefine HAVE_SQRTF 1 +#cmakedefine HAVE_TAN 1 +#cmakedefine HAVE_TANF 1 +#cmakedefine HAVE_TRUNC 1 +#cmakedefine HAVE_TRUNCF 1 +#cmakedefine HAVE_FOPEN64 1 +#cmakedefine HAVE_FSEEKO 1 +#cmakedefine HAVE_FSEEKO64 1 +#cmakedefine HAVE_MEMFD_CREATE 1 +#cmakedefine HAVE_POSIX_FALLOCATE 1 +#cmakedefine HAVE_SIGACTION 1 +#cmakedefine HAVE_SA_SIGACTION 1 +#cmakedefine HAVE_SETJMP 1 +#cmakedefine HAVE_NANOSLEEP 1 +#cmakedefine HAVE_SYSCONF 1 +#cmakedefine HAVE_SYSCTLBYNAME 1 +#cmakedefine HAVE_CLOCK_GETTIME 1 +#cmakedefine HAVE_GETPAGESIZE 1 +#cmakedefine HAVE_MPROTECT 1 +#cmakedefine HAVE_ICONV 1 +#cmakedefine SDL_USE_LIBICONV 1 +#cmakedefine HAVE_PTHREAD_SETNAME_NP 1 +#cmakedefine HAVE_PTHREAD_SET_NAME_NP 1 +#cmakedefine HAVE_SEM_TIMEDWAIT 1 +#cmakedefine HAVE_GETAUXVAL 1 +#cmakedefine HAVE_ELF_AUX_INFO 1 +#cmakedefine HAVE_POLL 1 +#cmakedefine HAVE__EXIT 1 + +#else +#cmakedefine HAVE_STDARG_H 1 +#cmakedefine HAVE_STDDEF_H 1 +#cmakedefine HAVE_STDINT_H 1 +#cmakedefine HAVE_FLOAT_H 1 +#endif /* HAVE_LIBC */ + +#cmakedefine HAVE_ALTIVEC_H 1 +#cmakedefine HAVE_DBUS_DBUS_H 1 +#cmakedefine HAVE_FCITX 1 +#cmakedefine HAVE_IBUS_IBUS_H 1 +#cmakedefine HAVE_SYS_INOTIFY_H 1 +#cmakedefine HAVE_INOTIFY_INIT 1 +#cmakedefine HAVE_INOTIFY_INIT1 1 +#cmakedefine HAVE_INOTIFY 1 +#cmakedefine HAVE_LIBUSB 1 +#cmakedefine HAVE_O_CLOEXEC 1 + +/* Apple platforms might be building universal binaries, where Intel builds + can use immintrin.h but other architectures can't. */ +#ifdef __APPLE__ +# if defined(__has_include) && (defined(__i386__) || defined(__x86_64)) +# if __has_include() +# define HAVE_IMMINTRIN_H 1 +# endif +# endif +#else /* non-Apple platforms can use the normal CMake check for this. */ +#cmakedefine HAVE_IMMINTRIN_H 1 +#endif + +#cmakedefine HAVE_LIBUDEV_H 1 +#cmakedefine HAVE_LIBSAMPLERATE_H 1 +#cmakedefine HAVE_LIBDECOR_H 1 + +#cmakedefine HAVE_D3D_H @HAVE_D3D_H@ +#cmakedefine HAVE_D3D11_H @HAVE_D3D11_H@ +#cmakedefine HAVE_D3D12_H @HAVE_D3D12_H@ +#cmakedefine HAVE_DDRAW_H @HAVE_DDRAW_H@ +#cmakedefine HAVE_DSOUND_H @HAVE_DSOUND_H@ +#cmakedefine HAVE_DINPUT_H @HAVE_DINPUT_H@ +#cmakedefine HAVE_XINPUT_H @HAVE_XINPUT_H@ +#cmakedefine HAVE_WINDOWS_GAMING_INPUT_H @HAVE_WINDOWS_GAMING_INPUT_H@ +#cmakedefine HAVE_DXGI_H @HAVE_DXGI_H@ + +#cmakedefine HAVE_MMDEVICEAPI_H @HAVE_MMDEVICEAPI_H@ +#cmakedefine HAVE_AUDIOCLIENT_H @HAVE_AUDIOCLIENT_H@ +#cmakedefine HAVE_TPCSHRD_H @HAVE_TPCSHRD_H@ +#cmakedefine HAVE_SENSORSAPI_H @HAVE_SENSORSAPI_H@ +#cmakedefine HAVE_ROAPI_H @HAVE_ROAPI_H@ +#cmakedefine HAVE_SHELLSCALINGAPI_H @HAVE_SHELLSCALINGAPI_H@ + +#cmakedefine USE_POSIX_SPAWN @USE_POSIX_SPAWN@ + +/* SDL internal assertion support */ +#if @SDL_DEFAULT_ASSERT_LEVEL_CONFIGURED@ +#cmakedefine SDL_DEFAULT_ASSERT_LEVEL @SDL_DEFAULT_ASSERT_LEVEL@ +#endif + +/* Allow disabling of core subsystems */ +#cmakedefine SDL_ATOMIC_DISABLED @SDL_ATOMIC_DISABLED@ +#cmakedefine SDL_AUDIO_DISABLED @SDL_AUDIO_DISABLED@ +#cmakedefine SDL_CPUINFO_DISABLED @SDL_CPUINFO_DISABLED@ +#cmakedefine SDL_EVENTS_DISABLED @SDL_EVENTS_DISABLED@ +#cmakedefine SDL_FILE_DISABLED @SDL_FILE_DISABLED@ +#cmakedefine SDL_JOYSTICK_DISABLED @SDL_JOYSTICK_DISABLED@ +#cmakedefine SDL_HAPTIC_DISABLED @SDL_HAPTIC_DISABLED@ +#cmakedefine SDL_HIDAPI_DISABLED @SDL_HIDAPI_DISABLED@ +#cmakedefine SDL_SENSOR_DISABLED @SDL_SENSOR_DISABLED@ +#cmakedefine SDL_LOADSO_DISABLED @SDL_LOADSO_DISABLED@ +#cmakedefine SDL_RENDER_DISABLED @SDL_RENDER_DISABLED@ +#cmakedefine SDL_THREADS_DISABLED @SDL_THREADS_DISABLED@ +#cmakedefine SDL_TIMERS_DISABLED @SDL_TIMERS_DISABLED@ +#cmakedefine SDL_VIDEO_DISABLED @SDL_VIDEO_DISABLED@ +#cmakedefine SDL_POWER_DISABLED @SDL_POWER_DISABLED@ +#cmakedefine SDL_FILESYSTEM_DISABLED @SDL_FILESYSTEM_DISABLED@ +#cmakedefine SDL_LOCALE_DISABLED @SDL_LOCALE_DISABLED@ +#cmakedefine SDL_MISC_DISABLED @SDL_MISC_DISABLED@ + +/* Enable various audio drivers */ +#cmakedefine SDL_AUDIO_DRIVER_ALSA @SDL_AUDIO_DRIVER_ALSA@ +#cmakedefine SDL_AUDIO_DRIVER_ALSA_DYNAMIC @SDL_AUDIO_DRIVER_ALSA_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_ANDROID @SDL_AUDIO_DRIVER_ANDROID@ +#cmakedefine SDL_AUDIO_DRIVER_OPENSLES @SDL_AUDIO_DRIVER_OPENSLES@ +#cmakedefine SDL_AUDIO_DRIVER_AAUDIO @SDL_AUDIO_DRIVER_AAUDIO@ +#cmakedefine SDL_AUDIO_DRIVER_ARTS @SDL_AUDIO_DRIVER_ARTS@ +#cmakedefine SDL_AUDIO_DRIVER_ARTS_DYNAMIC @SDL_AUDIO_DRIVER_ARTS_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_COREAUDIO @SDL_AUDIO_DRIVER_COREAUDIO@ +#cmakedefine SDL_AUDIO_DRIVER_DISK @SDL_AUDIO_DRIVER_DISK@ +#cmakedefine SDL_AUDIO_DRIVER_DSOUND @SDL_AUDIO_DRIVER_DSOUND@ +#cmakedefine SDL_AUDIO_DRIVER_DUMMY @SDL_AUDIO_DRIVER_DUMMY@ +#cmakedefine SDL_AUDIO_DRIVER_EMSCRIPTEN @SDL_AUDIO_DRIVER_EMSCRIPTEN@ +#cmakedefine SDL_AUDIO_DRIVER_ESD @SDL_AUDIO_DRIVER_ESD@ +#cmakedefine SDL_AUDIO_DRIVER_ESD_DYNAMIC @SDL_AUDIO_DRIVER_ESD_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_FUSIONSOUND @SDL_AUDIO_DRIVER_FUSIONSOUND@ +#cmakedefine SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC @SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_HAIKU @SDL_AUDIO_DRIVER_HAIKU@ +#cmakedefine SDL_AUDIO_DRIVER_JACK @SDL_AUDIO_DRIVER_JACK@ +#cmakedefine SDL_AUDIO_DRIVER_JACK_DYNAMIC @SDL_AUDIO_DRIVER_JACK_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_NAS @SDL_AUDIO_DRIVER_NAS@ +#cmakedefine SDL_AUDIO_DRIVER_NAS_DYNAMIC @SDL_AUDIO_DRIVER_NAS_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_NETBSD @SDL_AUDIO_DRIVER_NETBSD@ +#cmakedefine SDL_AUDIO_DRIVER_OSS @SDL_AUDIO_DRIVER_OSS@ +#cmakedefine SDL_AUDIO_DRIVER_PAUDIO @SDL_AUDIO_DRIVER_PAUDIO@ +#cmakedefine SDL_AUDIO_DRIVER_PIPEWIRE @SDL_AUDIO_DRIVER_PIPEWIRE@ +#cmakedefine SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC @SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_PULSEAUDIO @SDL_AUDIO_DRIVER_PULSEAUDIO@ +#cmakedefine SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC @SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_QSA @SDL_AUDIO_DRIVER_QSA@ +#cmakedefine SDL_AUDIO_DRIVER_SNDIO @SDL_AUDIO_DRIVER_SNDIO@ +#cmakedefine SDL_AUDIO_DRIVER_SNDIO_DYNAMIC @SDL_AUDIO_DRIVER_SNDIO_DYNAMIC@ +#cmakedefine SDL_AUDIO_DRIVER_SUNAUDIO @SDL_AUDIO_DRIVER_SUNAUDIO@ +#cmakedefine SDL_AUDIO_DRIVER_WASAPI @SDL_AUDIO_DRIVER_WASAPI@ +#cmakedefine SDL_AUDIO_DRIVER_WINMM @SDL_AUDIO_DRIVER_WINMM@ +#cmakedefine SDL_AUDIO_DRIVER_OS2 @SDL_AUDIO_DRIVER_OS2@ +#cmakedefine SDL_AUDIO_DRIVER_VITA @SDL_AUDIO_DRIVER_VITA@ +#cmakedefine SDL_AUDIO_DRIVER_PSP @SDL_AUDIO_DRIVER_PSP@ +#cmakedefine SDL_AUDIO_DRIVER_PS2 @SDL_AUDIO_DRIVER_PS2@ +#cmakedefine SDL_AUDIO_DRIVER_N3DS @SDL_AUDIO_DRIVER_N3DS@ + +/* Enable various input drivers */ +#cmakedefine SDL_INPUT_LINUXEV @SDL_INPUT_LINUXEV@ +#cmakedefine SDL_INPUT_LINUXKD @SDL_INPUT_LINUXKD@ +#cmakedefine SDL_INPUT_FBSDKBIO @SDL_INPUT_FBSDKBIO@ +#cmakedefine SDL_INPUT_WSCONS @SDL_INPUT_WSCONS@ +#cmakedefine SDL_JOYSTICK_ANDROID @SDL_JOYSTICK_ANDROID@ +#cmakedefine SDL_JOYSTICK_HAIKU @SDL_JOYSTICK_HAIKU@ +#cmakedefine SDL_JOYSTICK_WGI @SDL_JOYSTICK_WGI@ +#cmakedefine SDL_JOYSTICK_DINPUT @SDL_JOYSTICK_DINPUT@ +#cmakedefine SDL_JOYSTICK_XINPUT @SDL_JOYSTICK_XINPUT@ +#cmakedefine SDL_JOYSTICK_DUMMY @SDL_JOYSTICK_DUMMY@ +#cmakedefine SDL_JOYSTICK_IOKIT @SDL_JOYSTICK_IOKIT@ +#cmakedefine SDL_JOYSTICK_MFI @SDL_JOYSTICK_MFI@ +#cmakedefine SDL_JOYSTICK_LINUX @SDL_JOYSTICK_LINUX@ +#cmakedefine SDL_JOYSTICK_OS2 @SDL_JOYSTICK_OS2@ +#cmakedefine SDL_JOYSTICK_USBHID @SDL_JOYSTICK_USBHID@ +#cmakedefine SDL_HAVE_MACHINE_JOYSTICK_H @SDL_HAVE_MACHINE_JOYSTICK_H@ +#cmakedefine SDL_JOYSTICK_HIDAPI @SDL_JOYSTICK_HIDAPI@ +#cmakedefine SDL_JOYSTICK_RAWINPUT @SDL_JOYSTICK_RAWINPUT@ +#cmakedefine SDL_JOYSTICK_EMSCRIPTEN @SDL_JOYSTICK_EMSCRIPTEN@ +#cmakedefine SDL_JOYSTICK_VIRTUAL @SDL_JOYSTICK_VIRTUAL@ +#cmakedefine SDL_JOYSTICK_VITA @SDL_JOYSTICK_VITA@ +#cmakedefine SDL_JOYSTICK_PSP @SDL_JOYSTICK_PSP@ +#cmakedefine SDL_JOYSTICK_PS2 @SDL_JOYSTICK_PS2@ +#cmakedefine SDL_JOYSTICK_N3DS @SDL_JOYSTICK_N3DS@ +#cmakedefine SDL_HAPTIC_DUMMY @SDL_HAPTIC_DUMMY@ +#cmakedefine SDL_HAPTIC_LINUX @SDL_HAPTIC_LINUX@ +#cmakedefine SDL_HAPTIC_IOKIT @SDL_HAPTIC_IOKIT@ +#cmakedefine SDL_HAPTIC_DINPUT @SDL_HAPTIC_DINPUT@ +#cmakedefine SDL_HAPTIC_XINPUT @SDL_HAPTIC_XINPUT@ +#cmakedefine SDL_HAPTIC_ANDROID @SDL_HAPTIC_ANDROID@ +#cmakedefine SDL_LIBUSB_DYNAMIC @SDL_LIBUSB_DYNAMIC@ +#cmakedefine SDL_UDEV_DYNAMIC @SDL_UDEV_DYNAMIC@ + +/* Enable various sensor drivers */ +#cmakedefine SDL_SENSOR_ANDROID @SDL_SENSOR_ANDROID@ +#cmakedefine SDL_SENSOR_COREMOTION @SDL_SENSOR_COREMOTION@ +#cmakedefine SDL_SENSOR_WINDOWS @SDL_SENSOR_WINDOWS@ +#cmakedefine SDL_SENSOR_DUMMY @SDL_SENSOR_DUMMY@ +#cmakedefine SDL_SENSOR_VITA @SDL_SENSOR_VITA@ +#cmakedefine SDL_SENSOR_N3DS @SDL_SENSOR_N3DS@ + +/* Enable various shared object loading systems */ +#cmakedefine SDL_LOADSO_DLOPEN @SDL_LOADSO_DLOPEN@ +#cmakedefine SDL_LOADSO_DUMMY @SDL_LOADSO_DUMMY@ +#cmakedefine SDL_LOADSO_LDG @SDL_LOADSO_LDG@ +#cmakedefine SDL_LOADSO_WINDOWS @SDL_LOADSO_WINDOWS@ +#cmakedefine SDL_LOADSO_OS2 @SDL_LOADSO_OS2@ + +/* Enable various threading systems */ +#cmakedefine SDL_THREAD_GENERIC_COND_SUFFIX @SDL_THREAD_GENERIC_COND_SUFFIX@ +#cmakedefine SDL_THREAD_PTHREAD @SDL_THREAD_PTHREAD@ +#cmakedefine SDL_THREAD_PTHREAD_RECURSIVE_MUTEX @SDL_THREAD_PTHREAD_RECURSIVE_MUTEX@ +#cmakedefine SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP @SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP@ +#cmakedefine SDL_THREAD_WINDOWS @SDL_THREAD_WINDOWS@ +#cmakedefine SDL_THREAD_OS2 @SDL_THREAD_OS2@ +#cmakedefine SDL_THREAD_VITA @SDL_THREAD_VITA@ +#cmakedefine SDL_THREAD_PSP @SDL_THREAD_PSP@ +#cmakedefine SDL_THREAD_PS2 @SDL_THREAD_PS2@ +#cmakedefine SDL_THREAD_N3DS @SDL_THREAD_N3DS@ + +/* Enable various timer systems */ +#cmakedefine SDL_TIMER_HAIKU @SDL_TIMER_HAIKU@ +#cmakedefine SDL_TIMER_DUMMY @SDL_TIMER_DUMMY@ +#cmakedefine SDL_TIMER_UNIX @SDL_TIMER_UNIX@ +#cmakedefine SDL_TIMER_WINDOWS @SDL_TIMER_WINDOWS@ +#cmakedefine SDL_TIMER_OS2 @SDL_TIMER_OS2@ +#cmakedefine SDL_TIMER_VITA @SDL_TIMER_VITA@ +#cmakedefine SDL_TIMER_PSP @SDL_TIMER_PSP@ +#cmakedefine SDL_TIMER_PS2 @SDL_TIMER_PS2@ +#cmakedefine SDL_TIMER_N3DS @SDL_TIMER_N3DS@ + +/* Enable various video drivers */ +#cmakedefine SDL_VIDEO_DRIVER_ANDROID @SDL_VIDEO_DRIVER_ANDROID@ +#cmakedefine SDL_VIDEO_DRIVER_EMSCRIPTEN @SDL_VIDEO_DRIVER_EMSCRIPTEN@ +#cmakedefine SDL_VIDEO_DRIVER_HAIKU @SDL_VIDEO_DRIVER_HAIKU@ +#cmakedefine SDL_VIDEO_DRIVER_COCOA @SDL_VIDEO_DRIVER_COCOA@ +#cmakedefine SDL_VIDEO_DRIVER_UIKIT @SDL_VIDEO_DRIVER_UIKIT@ +#cmakedefine SDL_VIDEO_DRIVER_DIRECTFB @SDL_VIDEO_DRIVER_DIRECTFB@ +#cmakedefine SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC @SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC@ +#cmakedefine SDL_VIDEO_DRIVER_DUMMY @SDL_VIDEO_DRIVER_DUMMY@ +#cmakedefine SDL_VIDEO_DRIVER_OFFSCREEN @SDL_VIDEO_DRIVER_OFFSCREEN@ +#cmakedefine SDL_VIDEO_DRIVER_WINDOWS @SDL_VIDEO_DRIVER_WINDOWS@ +#cmakedefine SDL_VIDEO_DRIVER_WINRT @SDL_VIDEO_DRIVER_WINRT@ +#cmakedefine SDL_VIDEO_DRIVER_WAYLAND @SDL_VIDEO_DRIVER_WAYLAND@ +#cmakedefine SDL_VIDEO_DRIVER_RPI @SDL_VIDEO_DRIVER_RPI@ +#cmakedefine SDL_VIDEO_DRIVER_VIVANTE @SDL_VIDEO_DRIVER_VIVANTE@ +#cmakedefine SDL_VIDEO_DRIVER_VIVANTE_VDK @SDL_VIDEO_DRIVER_VIVANTE_VDK@ +#cmakedefine SDL_VIDEO_DRIVER_OS2 @SDL_VIDEO_DRIVER_OS2@ +#cmakedefine SDL_VIDEO_DRIVER_QNX @SDL_VIDEO_DRIVER_QNX@ +#cmakedefine SDL_VIDEO_DRIVER_RISCOS @SDL_VIDEO_DRIVER_RISCOS@ +#cmakedefine SDL_VIDEO_DRIVER_PSP @SDL_VIDEO_DRIVER_PSP@ +#cmakedefine SDL_VIDEO_DRIVER_PS2 @SDL_VIDEO_DRIVER_PS2@ + +#cmakedefine SDL_VIDEO_DRIVER_KMSDRM @SDL_VIDEO_DRIVER_KMSDRM@ +#cmakedefine SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC @SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC@ +#cmakedefine SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM @SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM@ + +#cmakedefine SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH @SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH@ +#cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC@ +#cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL@ +#cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR@ +#cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON@ +#cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR@ + +#cmakedefine SDL_VIDEO_DRIVER_X11 @SDL_VIDEO_DRIVER_X11@ +#cmakedefine SDL_VIDEO_DRIVER_X11_DYNAMIC @SDL_VIDEO_DRIVER_X11_DYNAMIC@ +#cmakedefine SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT @SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT@ +#cmakedefine SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR @SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR@ +#cmakedefine SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 @SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2@ +#cmakedefine SDL_VIDEO_DRIVER_X11_DYNAMIC_XFIXES @SDL_VIDEO_DRIVER_X11_DYNAMIC_XFIXES@ +#cmakedefine SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR @SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR@ +#cmakedefine SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS @SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS@ +#cmakedefine SDL_VIDEO_DRIVER_X11_XCURSOR @SDL_VIDEO_DRIVER_X11_XCURSOR@ +#cmakedefine SDL_VIDEO_DRIVER_X11_XDBE @SDL_VIDEO_DRIVER_X11_XDBE@ +#cmakedefine SDL_VIDEO_DRIVER_X11_XINPUT2 @SDL_VIDEO_DRIVER_X11_XINPUT2@ +#cmakedefine SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH @SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH@ +#cmakedefine SDL_VIDEO_DRIVER_X11_XFIXES @SDL_VIDEO_DRIVER_X11_XFIXES@ +#cmakedefine SDL_VIDEO_DRIVER_X11_XRANDR @SDL_VIDEO_DRIVER_X11_XRANDR@ +#cmakedefine SDL_VIDEO_DRIVER_X11_XSCRNSAVER @SDL_VIDEO_DRIVER_X11_XSCRNSAVER@ +#cmakedefine SDL_VIDEO_DRIVER_X11_XSHAPE @SDL_VIDEO_DRIVER_X11_XSHAPE@ +#cmakedefine SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS @SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS@ +#cmakedefine SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM @SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM@ +#cmakedefine SDL_VIDEO_DRIVER_VITA @SDL_VIDEO_DRIVER_VITA@ +#cmakedefine SDL_VIDEO_DRIVER_N3DS @SDL_VIDEO_DRIVER_N3DS@ + +#cmakedefine SDL_VIDEO_RENDER_D3D @SDL_VIDEO_RENDER_D3D@ +#cmakedefine SDL_VIDEO_RENDER_D3D11 @SDL_VIDEO_RENDER_D3D11@ +#cmakedefine SDL_VIDEO_RENDER_D3D12 @SDL_VIDEO_RENDER_D3D12@ +#cmakedefine SDL_VIDEO_RENDER_OGL @SDL_VIDEO_RENDER_OGL@ +#cmakedefine SDL_VIDEO_RENDER_OGL_ES @SDL_VIDEO_RENDER_OGL_ES@ +#cmakedefine SDL_VIDEO_RENDER_OGL_ES2 @SDL_VIDEO_RENDER_OGL_ES2@ +#cmakedefine SDL_VIDEO_RENDER_DIRECTFB @SDL_VIDEO_RENDER_DIRECTFB@ +#cmakedefine SDL_VIDEO_RENDER_METAL @SDL_VIDEO_RENDER_METAL@ +#cmakedefine SDL_VIDEO_RENDER_VITA_GXM @SDL_VIDEO_RENDER_VITA_GXM@ +#cmakedefine SDL_VIDEO_RENDER_PS2 @SDL_VIDEO_RENDER_PS2@ +#cmakedefine SDL_VIDEO_RENDER_PSP @SDL_VIDEO_RENDER_PSP@ + +/* Enable OpenGL support */ +#cmakedefine SDL_VIDEO_OPENGL @SDL_VIDEO_OPENGL@ +#cmakedefine SDL_VIDEO_OPENGL_ES @SDL_VIDEO_OPENGL_ES@ +#cmakedefine SDL_VIDEO_OPENGL_ES2 @SDL_VIDEO_OPENGL_ES2@ +#cmakedefine SDL_VIDEO_OPENGL_BGL @SDL_VIDEO_OPENGL_BGL@ +#cmakedefine SDL_VIDEO_OPENGL_CGL @SDL_VIDEO_OPENGL_CGL@ +#cmakedefine SDL_VIDEO_OPENGL_GLX @SDL_VIDEO_OPENGL_GLX@ +#cmakedefine SDL_VIDEO_OPENGL_WGL @SDL_VIDEO_OPENGL_WGL@ +#cmakedefine SDL_VIDEO_OPENGL_EGL @SDL_VIDEO_OPENGL_EGL@ +#cmakedefine SDL_VIDEO_OPENGL_OSMESA @SDL_VIDEO_OPENGL_OSMESA@ +#cmakedefine SDL_VIDEO_OPENGL_OSMESA_DYNAMIC @SDL_VIDEO_OPENGL_OSMESA_DYNAMIC@ + +/* Enable Vulkan support */ +#cmakedefine SDL_VIDEO_VULKAN @SDL_VIDEO_VULKAN@ + +/* Enable Metal support */ +#cmakedefine SDL_VIDEO_METAL @SDL_VIDEO_METAL@ + +/* Enable system power support */ +#cmakedefine SDL_POWER_ANDROID @SDL_POWER_ANDROID@ +#cmakedefine SDL_POWER_LINUX @SDL_POWER_LINUX@ +#cmakedefine SDL_POWER_WINDOWS @SDL_POWER_WINDOWS@ +#cmakedefine SDL_POWER_WINRT @SDL_POWER_WINRT@ +#cmakedefine SDL_POWER_MACOSX @SDL_POWER_MACOSX@ +#cmakedefine SDL_POWER_UIKIT @SDL_POWER_UIKIT@ +#cmakedefine SDL_POWER_HAIKU @SDL_POWER_HAIKU@ +#cmakedefine SDL_POWER_EMSCRIPTEN @SDL_POWER_EMSCRIPTEN@ +#cmakedefine SDL_POWER_HARDWIRED @SDL_POWER_HARDWIRED@ +#cmakedefine SDL_POWER_VITA @SDL_POWER_VITA@ +#cmakedefine SDL_POWER_PSP @SDL_POWER_PSP@ +#cmakedefine SDL_POWER_N3DS @SDL_POWER_N3DS@ + +/* Enable system filesystem support */ +#cmakedefine SDL_FILESYSTEM_ANDROID @SDL_FILESYSTEM_ANDROID@ +#cmakedefine SDL_FILESYSTEM_HAIKU @SDL_FILESYSTEM_HAIKU@ +#cmakedefine SDL_FILESYSTEM_COCOA @SDL_FILESYSTEM_COCOA@ +#cmakedefine SDL_FILESYSTEM_DUMMY @SDL_FILESYSTEM_DUMMY@ +#cmakedefine SDL_FILESYSTEM_RISCOS @SDL_FILESYSTEM_RISCOS@ +#cmakedefine SDL_FILESYSTEM_UNIX @SDL_FILESYSTEM_UNIX@ +#cmakedefine SDL_FILESYSTEM_WINDOWS @SDL_FILESYSTEM_WINDOWS@ +#cmakedefine SDL_FILESYSTEM_EMSCRIPTEN @SDL_FILESYSTEM_EMSCRIPTEN@ +#cmakedefine SDL_FILESYSTEM_OS2 @SDL_FILESYSTEM_OS2@ +#cmakedefine SDL_FILESYSTEM_VITA @SDL_FILESYSTEM_VITA@ +#cmakedefine SDL_FILESYSTEM_PSP @SDL_FILESYSTEM_PSP@ +#cmakedefine SDL_FILESYSTEM_PS2 @SDL_FILESYSTEM_PS2@ +#cmakedefine SDL_FILESYSTEM_N3DS @SDL_FILESYSTEM_N3DS@ + +/* Enable misc subsystem */ +#cmakedefine SDL_MISC_DUMMY @SDL_MISC_DUMMY@ + +/* Enable locale subsystem */ +#cmakedefine SDL_LOCALE_DUMMY @SDL_LOCALE_DUMMY@ + +/* Enable assembly routines */ +#cmakedefine SDL_ALTIVEC_BLITTERS @SDL_ALTIVEC_BLITTERS@ +#cmakedefine SDL_ARM_SIMD_BLITTERS @SDL_ARM_SIMD_BLITTERS@ +#cmakedefine SDL_ARM_NEON_BLITTERS @SDL_ARM_NEON_BLITTERS@ + +/* Whether SDL_DYNAMIC_API needs dlopen */ +#cmakedefine DYNAPI_NEEDS_DLOPEN @DYNAPI_NEEDS_DLOPEN@ + +/* Enable dynamic libsamplerate support */ +#cmakedefine SDL_LIBSAMPLERATE_DYNAMIC @SDL_LIBSAMPLERATE_DYNAMIC@ + +/* Enable ime support */ +#cmakedefine SDL_USE_IME @SDL_USE_IME@ + +/* Platform specific definitions */ +#cmakedefine SDL_IPHONE_KEYBOARD @SDL_IPHONE_KEYBOARD@ +#cmakedefine SDL_IPHONE_LAUNCHSCREEN @SDL_IPHONE_LAUNCHSCREEN@ + +#cmakedefine SDL_VIDEO_VITA_PIB @SDL_VIDEO_VITA_PIB@ +#cmakedefine SDL_VIDEO_VITA_PVR @SDL_VIDEO_VITA_PVR@ +#cmakedefine SDL_VIDEO_VITA_PVR_OGL @SDL_VIDEO_VITA_PVR_OGL@ + +#cmakedefine SDL_HAVE_LIBDECOR_GET_MIN_MAX @SDL_HAVE_LIBDECOR_GET_MIN_MAX@ + +#if !defined(HAVE_STDINT_H) && !defined(_STDINT_H_) +/* Most everything except Visual Studio 2008 and earlier has stdint.h now */ +#if defined(_MSC_VER) && (_MSC_VER < 1600) +typedef signed __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef signed __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef signed __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; +#ifndef _UINTPTR_T_DEFINED +#ifdef _WIN64 +typedef unsigned __int64 uintptr_t; +#else +typedef unsigned int uintptr_t; +#endif +#define _UINTPTR_T_DEFINED +#endif +#endif /* Visual Studio 2008 */ +#endif /* !_STDINT_H_ && !HAVE_STDINT_H */ + +#endif /* SDL_config_h_ */ diff --git a/third_party/SDL2/include/SDL_config.h.in b/third_party/SDL2/include/SDL_config.h.in new file mode 100644 index 00000000000..0d9fa142761 --- /dev/null +++ b/third_party/SDL2/include/SDL_config.h.in @@ -0,0 +1,498 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_h_ +#define SDL_config_h_ + +/** + * \file SDL_config.h.in + * + * This is a set of defines to configure the SDL features + */ + +/* General platform specific identifiers */ +#include "SDL_platform.h" + +/* Make sure that this isn't included by Visual C++ */ +#ifdef _MSC_VER +#error You should run git checkout -f include/SDL_config.h +#endif + +/* C language features */ +#undef const +#undef inline +#undef volatile + +/* C datatypes */ +#if defined(__LP64__) || defined(_LP64) || defined(_WIN64) +#define SIZEOF_VOIDP 8 +#else +#define SIZEOF_VOIDP 4 +#endif + +#undef HAVE_GCC_ATOMICS +#undef HAVE_GCC_SYNC_LOCK_TEST_AND_SET + +/* Comment this if you want to build without any C library requirements */ +#undef HAVE_LIBC +#ifdef HAVE_LIBC + +/* Useful headers */ +#undef STDC_HEADERS +#undef HAVE_ALLOCA_H +#undef HAVE_CTYPE_H +#undef HAVE_FLOAT_H +#undef HAVE_ICONV_H +#undef HAVE_INTTYPES_H +#undef HAVE_LIMITS_H +#undef HAVE_MALLOC_H +#undef HAVE_MATH_H +#undef HAVE_MEMORY_H +#undef HAVE_SIGNAL_H +#undef HAVE_STDARG_H +#undef HAVE_STDINT_H +#undef HAVE_STDIO_H +#undef HAVE_STDLIB_H +#undef HAVE_STRINGS_H +#undef HAVE_STRING_H +#undef HAVE_SYS_TYPES_H +#undef HAVE_WCHAR_H +#undef HAVE_LINUX_INPUT_H +#undef HAVE_PTHREAD_NP_H +#undef HAVE_LIBUNWIND_H + +/* C library functions */ +#undef HAVE_DLOPEN +#undef HAVE_MALLOC +#undef HAVE_CALLOC +#undef HAVE_REALLOC +#undef HAVE_FREE +#undef HAVE_ALLOCA +#ifndef __WIN32__ /* Don't use C runtime versions of these on Windows */ +#undef HAVE_GETENV +#undef HAVE_SETENV +#undef HAVE_PUTENV +#undef HAVE_UNSETENV +#endif +#undef HAVE_QSORT +#undef HAVE_BSEARCH +#undef HAVE_ABS +#undef HAVE_BCOPY +#undef HAVE_MEMSET +#undef HAVE_MEMCPY +#undef HAVE_MEMMOVE +#undef HAVE_MEMCMP +#undef HAVE_WCSLEN +#undef HAVE_WCSLCPY +#undef HAVE_WCSLCAT +#undef HAVE__WCSDUP +#undef HAVE_WCSDUP +#undef HAVE_WCSSTR +#undef HAVE_WCSCMP +#undef HAVE_WCSNCMP +#undef HAVE_WCSCASECMP +#undef HAVE__WCSICMP +#undef HAVE_WCSNCASECMP +#undef HAVE__WCSNICMP +#undef HAVE_STRLEN +#undef HAVE_STRLCPY +#undef HAVE_STRLCAT +#undef HAVE__STRREV +#undef HAVE__STRUPR +#undef HAVE__STRLWR +#undef HAVE_INDEX +#undef HAVE_RINDEX +#undef HAVE_STRCHR +#undef HAVE_STRRCHR +#undef HAVE_STRSTR +#undef HAVE_STRTOK_R +#undef HAVE_ITOA +#undef HAVE__LTOA +#undef HAVE__UITOA +#undef HAVE__ULTOA +#undef HAVE_STRTOL +#undef HAVE_STRTOUL +#undef HAVE__I64TOA +#undef HAVE__UI64TOA +#undef HAVE_STRTOLL +#undef HAVE_STRTOULL +#undef HAVE_STRTOD +#undef HAVE_ATOI +#undef HAVE_ATOF +#undef HAVE_STRCMP +#undef HAVE_STRNCMP +#undef HAVE__STRICMP +#undef HAVE_STRCASECMP +#undef HAVE__STRNICMP +#undef HAVE_STRNCASECMP +#undef HAVE_STRCASESTR +#undef HAVE_SSCANF +#undef HAVE_VSSCANF +#undef HAVE_SNPRINTF +#undef HAVE_VSNPRINTF +#undef HAVE_M_PI +#undef HAVE_ACOS +#undef HAVE_ACOSF +#undef HAVE_ASIN +#undef HAVE_ASINF +#undef HAVE_ATAN +#undef HAVE_ATANF +#undef HAVE_ATAN2 +#undef HAVE_ATAN2F +#undef HAVE_CEIL +#undef HAVE_CEILF +#undef HAVE_COPYSIGN +#undef HAVE_COPYSIGNF +#undef HAVE_COS +#undef HAVE_COSF +#undef HAVE_EXP +#undef HAVE_EXPF +#undef HAVE_FABS +#undef HAVE_FABSF +#undef HAVE_FLOOR +#undef HAVE_FLOORF +#undef HAVE_FMOD +#undef HAVE_FMODF +#undef HAVE_LOG +#undef HAVE_LOGF +#undef HAVE_LOG10 +#undef HAVE_LOG10F +#undef HAVE_LROUND +#undef HAVE_LROUNDF +#undef HAVE_POW +#undef HAVE_POWF +#undef HAVE_ROUND +#undef HAVE_ROUNDF +#undef HAVE_SCALBN +#undef HAVE_SCALBNF +#undef HAVE_SIN +#undef HAVE_SINF +#undef HAVE_SQRT +#undef HAVE_SQRTF +#undef HAVE_TAN +#undef HAVE_TANF +#undef HAVE_TRUNC +#undef HAVE_TRUNCF +#undef HAVE_FOPEN64 +#undef HAVE_FSEEKO +#undef HAVE_FSEEKO64 +#undef HAVE_SIGACTION +#undef HAVE_SA_SIGACTION +#undef HAVE_SETJMP +#undef HAVE_NANOSLEEP +#undef HAVE_SYSCONF +#undef HAVE_SYSCTLBYNAME +#undef HAVE_CLOCK_GETTIME +#undef HAVE_GETPAGESIZE +#undef HAVE_MPROTECT +#undef HAVE_ICONV +#undef SDL_USE_LIBICONV +#undef HAVE_PTHREAD_SETNAME_NP +#undef HAVE_PTHREAD_SET_NAME_NP +#undef HAVE_SEM_TIMEDWAIT +#undef HAVE_GETAUXVAL +#undef HAVE_ELF_AUX_INFO +#undef HAVE_POLL +#undef HAVE_MEMFD_CREATE +#undef HAVE_POSIX_FALLOCATE +#undef HAVE__EXIT + +#else +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDINT_H 1 +#endif /* HAVE_LIBC */ + +#undef HAVE_O_CLOEXEC +#undef HAVE_ALTIVEC_H +#undef HAVE_DBUS_DBUS_H +#undef HAVE_FCITX +#undef HAVE_SYS_INOTIFY_H +#undef HAVE_INOTIFY_INIT +#undef HAVE_INOTIFY_INIT1 +#undef HAVE_INOTIFY +#undef HAVE_IBUS_IBUS_H +#undef HAVE_IMMINTRIN_H +#undef HAVE_LIBUDEV_H +#undef HAVE_LIBUSB +#undef HAVE_LIBSAMPLERATE_H +#undef HAVE_LIBDECOR_H +#undef HAVE_LSXINTRIN_H +#undef HAVE_LASXINTRIN_H + +#undef HAVE_DDRAW_H +#undef HAVE_DINPUT_H +#undef HAVE_DSOUND_H +#undef HAVE_DXGI_H +#undef HAVE_WINDOWS_GAMING_INPUT_H +#undef HAVE_XINPUT_H + +#undef HAVE_MMDEVICEAPI_H +#undef HAVE_AUDIOCLIENT_H +#undef HAVE_TPCSHRD_H +#undef HAVE_SENSORSAPI_H +#undef HAVE_ROAPI_H +#undef HAVE_SHELLSCALINGAPI_H + +/* SDL internal assertion support */ +#undef SDL_DEFAULT_ASSERT_LEVEL + +/* Allow disabling of core subsystems */ +#undef SDL_ATOMIC_DISABLED +#undef SDL_AUDIO_DISABLED +#undef SDL_CPUINFO_DISABLED +#undef SDL_EVENTS_DISABLED +#undef SDL_FILE_DISABLED +#undef SDL_JOYSTICK_DISABLED +#undef SDL_HAPTIC_DISABLED +#undef SDL_HIDAPI_DISABLED +#undef SDL_SENSOR_DISABLED +#undef SDL_LOADSO_DISABLED +#undef SDL_RENDER_DISABLED +#undef SDL_THREADS_DISABLED +#undef SDL_TIMERS_DISABLED +#undef SDL_VIDEO_DISABLED +#undef SDL_POWER_DISABLED +#undef SDL_FILESYSTEM_DISABLED +#undef SDL_LOCALE_DISABLED +#undef SDL_MISC_DISABLED + +/* Enable various audio drivers */ +#undef SDL_AUDIO_DRIVER_AAUDIO +#undef SDL_AUDIO_DRIVER_ALSA +#undef SDL_AUDIO_DRIVER_ALSA_DYNAMIC +#undef SDL_AUDIO_DRIVER_ANDROID +#undef SDL_AUDIO_DRIVER_ARTS +#undef SDL_AUDIO_DRIVER_ARTS_DYNAMIC +#undef SDL_AUDIO_DRIVER_COREAUDIO +#undef SDL_AUDIO_DRIVER_DISK +#undef SDL_AUDIO_DRIVER_DSOUND +#undef SDL_AUDIO_DRIVER_DUMMY +#undef SDL_AUDIO_DRIVER_EMSCRIPTEN +#undef SDL_AUDIO_DRIVER_ESD +#undef SDL_AUDIO_DRIVER_ESD_DYNAMIC +#undef SDL_AUDIO_DRIVER_FUSIONSOUND +#undef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC +#undef SDL_AUDIO_DRIVER_HAIKU +#undef SDL_AUDIO_DRIVER_JACK +#undef SDL_AUDIO_DRIVER_JACK_DYNAMIC +#undef SDL_AUDIO_DRIVER_NACL +#undef SDL_AUDIO_DRIVER_NAS +#undef SDL_AUDIO_DRIVER_NAS_DYNAMIC +#undef SDL_AUDIO_DRIVER_NETBSD +#undef SDL_AUDIO_DRIVER_OPENSLES +#undef SDL_AUDIO_DRIVER_OSS +#undef SDL_AUDIO_DRIVER_PAUDIO +#undef SDL_AUDIO_DRIVER_PIPEWIRE +#undef SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC +#undef SDL_AUDIO_DRIVER_PULSEAUDIO +#undef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC +#undef SDL_AUDIO_DRIVER_QSA +#undef SDL_AUDIO_DRIVER_SNDIO +#undef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC +#undef SDL_AUDIO_DRIVER_SUNAUDIO +#undef SDL_AUDIO_DRIVER_WASAPI +#undef SDL_AUDIO_DRIVER_WINMM +#undef SDL_AUDIO_DRIVER_OS2 + +/* Enable various input drivers */ +#undef SDL_INPUT_LINUXEV +#undef SDL_INPUT_FBSDKBIO +#undef SDL_INPUT_LINUXKD +#undef SDL_INPUT_WSCONS +#undef SDL_JOYSTICK_HAIKU +#undef SDL_JOYSTICK_DINPUT +#undef SDL_JOYSTICK_WGI +#undef SDL_JOYSTICK_XINPUT +#undef SDL_JOYSTICK_DUMMY +#undef SDL_JOYSTICK_IOKIT +#undef SDL_JOYSTICK_MFI +#undef SDL_JOYSTICK_LINUX +#undef SDL_JOYSTICK_ANDROID +#undef SDL_JOYSTICK_OS2 +#undef SDL_JOYSTICK_USBHID +#undef SDL_HAVE_MACHINE_JOYSTICK_H +#undef SDL_JOYSTICK_HIDAPI +#undef SDL_JOYSTICK_RAWINPUT +#undef SDL_JOYSTICK_EMSCRIPTEN +#undef SDL_JOYSTICK_VIRTUAL +#undef SDL_HAPTIC_DUMMY +#undef SDL_HAPTIC_ANDROID +#undef SDL_HAPTIC_LINUX +#undef SDL_HAPTIC_IOKIT +#undef SDL_HAPTIC_DINPUT +#undef SDL_HAPTIC_XINPUT + +/* Enable various sensor drivers */ +#undef SDL_SENSOR_ANDROID +#undef SDL_SENSOR_COREMOTION +#undef SDL_SENSOR_WINDOWS +#undef SDL_SENSOR_DUMMY + +/* Enable various shared object loading systems */ +#undef SDL_LOADSO_DLOPEN +#undef SDL_LOADSO_DUMMY +#undef SDL_LOADSO_LDG +#undef SDL_LOADSO_WINDOWS +#undef SDL_LOADSO_OS2 + +/* Enable various threading systems */ +#undef SDL_THREAD_GENERIC_COND_SUFFIX +#undef SDL_THREAD_PTHREAD +#undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX +#undef SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP +#undef SDL_THREAD_WINDOWS +#undef SDL_THREAD_OS2 + +/* Enable various timer systems */ +#undef SDL_TIMER_HAIKU +#undef SDL_TIMER_DUMMY +#undef SDL_TIMER_UNIX +#undef SDL_TIMER_WINDOWS +#undef SDL_TIMER_OS2 + +/* Enable various video drivers */ +#undef SDL_VIDEO_DRIVER_HAIKU +#undef SDL_VIDEO_DRIVER_COCOA +#undef SDL_VIDEO_DRIVER_DIRECTFB +#undef SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC +#undef SDL_VIDEO_DRIVER_DUMMY +#undef SDL_VIDEO_DRIVER_WINDOWS +#undef SDL_VIDEO_DRIVER_WAYLAND +#undef SDL_VIDEO_DRIVER_WAYLAND_QT_TOUCH +#undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC +#undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL +#undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR +#undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON +#undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_LIBDECOR +#undef SDL_VIDEO_DRIVER_X11 +#undef SDL_VIDEO_DRIVER_RPI +#undef SDL_VIDEO_DRIVER_KMSDRM +#undef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC +#undef SDL_VIDEO_DRIVER_KMSDRM_DYNAMIC_GBM +#undef SDL_VIDEO_DRIVER_ANDROID +#undef SDL_VIDEO_DRIVER_EMSCRIPTEN +#undef SDL_VIDEO_DRIVER_OFFSCREEN +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XFIXES +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR +#undef SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS +#undef SDL_VIDEO_DRIVER_X11_XCURSOR +#undef SDL_VIDEO_DRIVER_X11_XDBE +#undef SDL_VIDEO_DRIVER_X11_XINPUT2 +#undef SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH +#undef SDL_VIDEO_DRIVER_X11_XFIXES +#undef SDL_VIDEO_DRIVER_X11_XRANDR +#undef SDL_VIDEO_DRIVER_X11_XSCRNSAVER +#undef SDL_VIDEO_DRIVER_X11_XSHAPE +#undef SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS +#undef SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM +#undef SDL_VIDEO_DRIVER_NACL +#undef SDL_VIDEO_DRIVER_VIVANTE +#undef SDL_VIDEO_DRIVER_VIVANTE_VDK +#undef SDL_VIDEO_DRIVER_OS2 +#undef SDL_VIDEO_DRIVER_QNX +#undef SDL_VIDEO_DRIVER_RISCOS + +#undef SDL_VIDEO_RENDER_D3D +#undef SDL_VIDEO_RENDER_D3D11 +#undef SDL_VIDEO_RENDER_D3D12 +#undef SDL_VIDEO_RENDER_OGL +#undef SDL_VIDEO_RENDER_OGL_ES +#undef SDL_VIDEO_RENDER_OGL_ES2 +#undef SDL_VIDEO_RENDER_DIRECTFB +#undef SDL_VIDEO_RENDER_METAL + +/* Enable OpenGL support */ +#undef SDL_VIDEO_OPENGL +#undef SDL_VIDEO_OPENGL_ES +#undef SDL_VIDEO_OPENGL_ES2 +#undef SDL_VIDEO_OPENGL_BGL +#undef SDL_VIDEO_OPENGL_CGL +#undef SDL_VIDEO_OPENGL_EGL +#undef SDL_VIDEO_OPENGL_GLX +#undef SDL_VIDEO_OPENGL_WGL +#undef SDL_VIDEO_OPENGL_OSMESA +#undef SDL_VIDEO_OPENGL_OSMESA_DYNAMIC + +/* Enable Vulkan support */ +#undef SDL_VIDEO_VULKAN + +/* Enable Metal support */ +#undef SDL_VIDEO_METAL + +/* Enable system power support */ +#undef SDL_POWER_LINUX +#undef SDL_POWER_WINDOWS +#undef SDL_POWER_MACOSX +#undef SDL_POWER_HAIKU +#undef SDL_POWER_ANDROID +#undef SDL_POWER_EMSCRIPTEN +#undef SDL_POWER_HARDWIRED + +/* Enable system filesystem support */ +#undef SDL_FILESYSTEM_ANDROID +#undef SDL_FILESYSTEM_HAIKU +#undef SDL_FILESYSTEM_COCOA +#undef SDL_FILESYSTEM_DUMMY +#undef SDL_FILESYSTEM_RISCOS +#undef SDL_FILESYSTEM_UNIX +#undef SDL_FILESYSTEM_WINDOWS +#undef SDL_FILESYSTEM_NACL +#undef SDL_FILESYSTEM_EMSCRIPTEN +#undef SDL_FILESYSTEM_OS2 +#undef SDL_FILESYSTEM_VITA +#undef SDL_FILESYSTEM_PSP +#undef SDL_FILESYSTEM_PS2 + +/* Enable misc subsystem */ +#undef SDL_MISC_DUMMY + +/* Enable locale subsystem */ +#undef SDL_LOCALE_DUMMY + +/* Enable assembly routines */ +#undef SDL_ALTIVEC_BLITTERS +#undef SDL_ARM_SIMD_BLITTERS +#undef SDL_ARM_NEON_BLITTERS + +/* Whether SDL_DYNAMIC_API needs dlopen() */ +#undef DYNAPI_NEEDS_DLOPEN + +/* Enable ime support */ +#undef SDL_USE_IME + +/* Enable dynamic udev support */ +#undef SDL_UDEV_DYNAMIC + +/* Enable dynamic libusb support */ +#undef SDL_LIBUSB_DYNAMIC + +/* Enable dynamic libsamplerate support */ +#undef SDL_LIBSAMPLERATE_DYNAMIC + +/* Libdecor get min/max content size functions */ +#undef SDL_HAVE_LIBDECOR_GET_MIN_MAX + +#endif /* SDL_config_h_ */ diff --git a/third_party/SDL2/include/SDL_config_android.h b/third_party/SDL2/include/SDL_config_android.h new file mode 100644 index 00000000000..0609995e97d --- /dev/null +++ b/third_party/SDL2/include/SDL_config_android.h @@ -0,0 +1,194 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_android_h_ +#define SDL_config_android_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +/** + * \file SDL_config_android.h + * + * This is a configuration that can be used to build SDL for Android + */ + +#include + +#define HAVE_GCC_ATOMICS 1 + +#define STDC_HEADERS 1 +#define HAVE_ALLOCA_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 + +/* C library functions */ +#define HAVE_DLOPEN 1 +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_SETENV 1 +#define HAVE_UNSETENV 1 +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_STRCASESTR 1 +#define HAVE_VSSCANF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEIL 1 +#define HAVE_CEILF 1 +#define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE_SIGACTION 1 +#define HAVE_SETJMP 1 +#define HAVE_NANOSLEEP 1 +#define HAVE_SYSCONF 1 +#define HAVE_CLOCK_GETTIME 1 + +#ifdef __LP64__ +#define SIZEOF_VOIDP 8 +#else +#define SIZEOF_VOIDP 4 +#endif + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_ANDROID 1 +#define SDL_AUDIO_DRIVER_OPENSLES 1 +#define SDL_AUDIO_DRIVER_AAUDIO 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_ANDROID 1 +#define SDL_JOYSTICK_HIDAPI 1 +#define SDL_JOYSTICK_VIRTUAL 1 +#define SDL_HAPTIC_ANDROID 1 + +/* Enable sensor driver */ +#define SDL_SENSOR_ANDROID 1 + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_DLOPEN 1 + +/* Enable various threading systems */ +#define SDL_THREAD_PTHREAD 1 +#define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX 1 + +/* Enable various timer systems */ +#define SDL_TIMER_UNIX 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_ANDROID 1 + +/* Enable OpenGL ES */ +#define SDL_VIDEO_OPENGL_ES 1 +#define SDL_VIDEO_OPENGL_ES2 1 +#define SDL_VIDEO_OPENGL_EGL 1 +#define SDL_VIDEO_RENDER_OGL_ES 1 +#define SDL_VIDEO_RENDER_OGL_ES2 1 + +/* Enable Vulkan support */ +/* Android does not support Vulkan in native code using the "armeabi" ABI. */ +#if defined(__ARM_ARCH) && __ARM_ARCH < 7 +#define SDL_VIDEO_VULKAN 0 +#else +#define SDL_VIDEO_VULKAN 1 +#endif + +/* Enable system power support */ +#define SDL_POWER_ANDROID 1 + +/* Enable the filesystem driver */ +#define SDL_FILESYSTEM_ANDROID 1 + +#endif /* SDL_config_android_h_ */ diff --git a/third_party/SDL2/include/SDL_config_emscripten.h b/third_party/SDL2/include/SDL_config_emscripten.h new file mode 100644 index 00000000000..3f064905746 --- /dev/null +++ b/third_party/SDL2/include/SDL_config_emscripten.h @@ -0,0 +1,218 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef _SDL_config_emscripten_h_ +#define _SDL_config_emscripten_h_ + +#include "SDL_platform.h" + +/** + * \file SDL_config_emscripten.h + * + * This is a configuration that can be used to build SDL for Emscripten. + */ + +#ifdef __LP64__ +#define SIZEOF_VOIDP 8 +#else +#define SIZEOF_VOIDP 4 +#endif +#define HAVE_GCC_ATOMICS 1 + +/* Useful headers */ +#define STDC_HEADERS 1 +#define HAVE_ALLOCA_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_ICONV_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MATH_H 1 +#define HAVE_MEMORY_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_WCHAR_H 1 + +/* C library functions */ +#define HAVE_DLOPEN 1 +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_UNSETENV 1 +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_WCSLEN 1 +#define HAVE_WCSDUP 1 +#define HAVE_WCSSTR 1 +#define HAVE_WCSCMP 1 +#define HAVE_WCSNCMP 1 +#define HAVE_WCSCASECMP 1 +#define HAVE_WCSNCASECMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_SSCANF 1 +#define HAVE_VSSCANF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_M_PI 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEIL 1 +#define HAVE_CEILF 1 +#define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE_FSEEKO 1 +#define HAVE_FSEEKO64 1 +#define HAVE_SIGACTION 1 +#define HAVE_SA_SIGACTION 1 +#define HAVE_SETJMP 1 +#define HAVE_NANOSLEEP 1 +#define HAVE_SYSCONF 1 +#define HAVE_CLOCK_GETTIME 1 +/* #undef HAVE_GETPAGESIZE */ +#define HAVE_MPROTECT 1 +#define HAVE_ICONV 1 + +/* SDL internal assertion support */ +/* #undef SDL_DEFAULT_ASSERT_LEVEL */ + +#define SDL_CPUINFO_DISABLED 1 +#define SDL_HAPTIC_DISABLED 1 +#define SDL_HIDAPI_DISABLED 1 +#ifndef __EMSCRIPTEN_PTHREADS__ +#define SDL_THREADS_DISABLED 1 +#endif + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 +#define SDL_AUDIO_DRIVER_EMSCRIPTEN 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_EMSCRIPTEN 1 + +/* Enable various sensor drivers */ +#define SDL_SENSOR_DUMMY 1 + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_DLOPEN 1 + +/* Enable various threading systems */ +#ifdef __EMSCRIPTEN_PTHREADS__ +#define SDL_THREAD_PTHREAD 1 +#define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX 1 +#endif + +/* Enable various timer systems */ +#define SDL_TIMER_UNIX 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_EMSCRIPTEN 1 + +#define SDL_VIDEO_RENDER_OGL_ES2 1 + +/* Enable OpenGL support */ +/* #undef SDL_VIDEO_OPENGL */ +/* #undef SDL_VIDEO_OPENGL_ES */ +#define SDL_VIDEO_OPENGL_ES2 1 +/* #undef SDL_VIDEO_OPENGL_BGL */ +/* #undef SDL_VIDEO_OPENGL_CGL */ +/* #undef SDL_VIDEO_OPENGL_GLX */ +/* #undef SDL_VIDEO_OPENGL_WGL */ +#define SDL_VIDEO_OPENGL_EGL 1 +/* #undef SDL_VIDEO_OPENGL_OSMESA */ +/* #undef SDL_VIDEO_OPENGL_OSMESA_DYNAMIC */ + +/* Enable system power support */ +#define SDL_POWER_EMSCRIPTEN 1 + +/* Enable system filesystem support */ +#define SDL_FILESYSTEM_EMSCRIPTEN 1 + +#endif /* _SDL_config_emscripten_h_ */ diff --git a/third_party/SDL2/include/SDL_config_iphoneos.h b/third_party/SDL2/include/SDL_config_iphoneos.h new file mode 100644 index 00000000000..fed314e8bd6 --- /dev/null +++ b/third_party/SDL2/include/SDL_config_iphoneos.h @@ -0,0 +1,217 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_iphoneos_h_ +#define SDL_config_iphoneos_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +#ifdef __LP64__ +#define SIZEOF_VOIDP 8 +#else +#define SIZEOF_VOIDP 4 +#endif + +#define HAVE_GCC_ATOMICS 1 + +#define STDC_HEADERS 1 +#define HAVE_ALLOCA_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 +/* The libunwind functions are only available on x86 */ +/* #undef HAVE_LIBUNWIND_H */ + +/* C library functions */ +#define HAVE_DLOPEN 1 +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_SETENV 1 +#define HAVE_UNSETENV 1 +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_STRCASESTR 1 +#define HAVE_VSSCANF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_M_PI 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEIL 1 +#define HAVE_CEILF 1 +#define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE_SIGACTION 1 +#define HAVE_SETJMP 1 +#define HAVE_NANOSLEEP 1 +#define HAVE_SYSCONF 1 +#define HAVE_SYSCTLBYNAME 1 +#define HAVE_O_CLOEXEC 1 + +/* enable iPhone version of Core Audio driver */ +#define SDL_AUDIO_DRIVER_COREAUDIO 1 +/* Enable the dummy audio driver (src/audio/dummy/\*.c) */ +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable the stub haptic driver (src/haptic/dummy/\*.c) */ +#define SDL_HAPTIC_DUMMY 1 + +/* Enable joystick support */ +/* Only enable HIDAPI support if you want to support Steam Controllers on iOS and tvOS */ +/*#define SDL_JOYSTICK_HIDAPI 1*/ +#define SDL_JOYSTICK_MFI 1 +#define SDL_JOYSTICK_VIRTUAL 1 + +#ifdef __TVOS__ +#define SDL_SENSOR_DUMMY 1 +#else +/* Enable the CoreMotion sensor driver */ +#define SDL_SENSOR_COREMOTION 1 +#endif + +/* Enable Unix style SO loading */ +#define SDL_LOADSO_DLOPEN 1 + +/* Enable various threading systems */ +#define SDL_THREAD_PTHREAD 1 +#define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX 1 + +/* Enable various timer systems */ +#define SDL_TIMER_UNIX 1 + +/* Supported video drivers */ +#define SDL_VIDEO_DRIVER_UIKIT 1 +#define SDL_VIDEO_DRIVER_DUMMY 1 + +/* Enable OpenGL ES */ +#if !TARGET_OS_MACCATALYST +#define SDL_VIDEO_OPENGL_ES2 1 +#define SDL_VIDEO_OPENGL_ES 1 +#define SDL_VIDEO_RENDER_OGL_ES 1 +#define SDL_VIDEO_RENDER_OGL_ES2 1 +#endif + +/* Metal supported on 64-bit devices running iOS 8.0 and tvOS 9.0 and newer + Also supported in simulator from iOS 13.0 and tvOS 13.0 + */ +#if (TARGET_OS_SIMULATOR && ((__IPHONE_OS_VERSION_MIN_REQUIRED >= 130000) || (__TV_OS_VERSION_MIN_REQUIRED >= 130000))) || (!TARGET_CPU_ARM && ((__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 90000))) +#define SDL_PLATFORM_SUPPORTS_METAL 1 +#else +#define SDL_PLATFORM_SUPPORTS_METAL 0 +#endif + +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_RENDER_METAL 1 +#endif + +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_VULKAN 1 +#endif + +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_METAL 1 +#endif + +/* Enable system power support */ +#define SDL_POWER_UIKIT 1 + +/* enable iPhone keyboard support */ +#define SDL_IPHONE_KEYBOARD 1 + +/* enable iOS extended launch screen */ +#define SDL_IPHONE_LAUNCHSCREEN 1 + +/* enable filesystem support */ +#define SDL_FILESYSTEM_COCOA 1 + +#endif /* SDL_config_iphoneos_h_ */ diff --git a/third_party/SDL2/include/SDL_config_macosx.h b/third_party/SDL2/include/SDL_config_macosx.h new file mode 100644 index 00000000000..e9e6b6d328d --- /dev/null +++ b/third_party/SDL2/include/SDL_config_macosx.h @@ -0,0 +1,277 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_macosx_h_ +#define SDL_config_macosx_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +/* This gets us MAC_OS_X_VERSION_MIN_REQUIRED... */ +#include + +/* This is a set of defines to configure the SDL features */ + +#ifdef __LP64__ + #define SIZEOF_VOIDP 8 +#else + #define SIZEOF_VOIDP 4 +#endif + +/* Useful headers */ +#define STDC_HEADERS 1 +#define HAVE_ALLOCA_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_LIBUNWIND_H 1 + +/* C library functions */ +#define HAVE_DLOPEN 1 +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_UNSETENV 1 +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_STRCASESTR 1 +#define HAVE_VSSCANF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_M_PI 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEIL 1 +#define HAVE_CEILF 1 +#define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE_SIGACTION 1 +#define HAVE_SETJMP 1 +#define HAVE_NANOSLEEP 1 +#define HAVE_SYSCONF 1 +#define HAVE_SYSCTLBYNAME 1 + +#if defined(__has_include) && (defined(__i386__) || defined(__x86_64)) +# if __has_include() +# define HAVE_IMMINTRIN_H 1 +# endif +#endif + +#if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1070) +#define HAVE_O_CLOEXEC 1 +#endif + +#define HAVE_GCC_ATOMICS 1 + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_COREAUDIO 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_HIDAPI 1 +#define SDL_JOYSTICK_IOKIT 1 +#define SDL_JOYSTICK_VIRTUAL 1 +#define SDL_HAPTIC_IOKIT 1 + +/* The MFI controller support requires ARC Objective C runtime */ +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1080 && !defined(__i386__) +#define SDL_JOYSTICK_MFI 1 +#endif + +/* Enable the dummy sensor driver */ +#define SDL_SENSOR_DUMMY 1 + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_DLOPEN 1 + +/* Enable various threading systems */ +#define SDL_THREAD_PTHREAD 1 +#define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX 1 + +/* Enable various timer systems */ +#define SDL_TIMER_UNIX 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_COCOA 1 +#define SDL_VIDEO_DRIVER_DUMMY 1 +#undef SDL_VIDEO_DRIVER_X11 +#define SDL_VIDEO_DRIVER_X11_DYNAMIC "/opt/X11/lib/libX11.6.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT "/opt/X11/lib/libXext.6.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 "/opt/X11/lib/libXi.6.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR "/opt/X11/lib/libXrandr.2.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS "/opt/X11/lib/libXss.1.dylib" +#define SDL_VIDEO_DRIVER_X11_XDBE 1 +#define SDL_VIDEO_DRIVER_X11_XRANDR 1 +#define SDL_VIDEO_DRIVER_X11_XSCRNSAVER 1 +#define SDL_VIDEO_DRIVER_X11_XSHAPE 1 +#define SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM 1 + +#ifdef MAC_OS_X_VERSION_10_8 +/* + * No matter the versions targeted, this is the 10.8 or later SDK, so you have + * to use the external Xquartz, which is a more modern Xlib. Previous SDKs + * used an older Xlib. + */ +#define SDL_VIDEO_DRIVER_X11_XINPUT2 1 +#define SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS 1 +#endif + +#ifndef SDL_VIDEO_RENDER_OGL +#define SDL_VIDEO_RENDER_OGL 1 +#endif + +#ifndef SDL_VIDEO_RENDER_OGL_ES2 +#define SDL_VIDEO_RENDER_OGL_ES2 1 +#endif + +/* Metal only supported on 64-bit architectures with 10.11+ */ +#if TARGET_RT_64_BIT && (MAC_OS_X_VERSION_MAX_ALLOWED >= 101100) +#define SDL_PLATFORM_SUPPORTS_METAL 1 +#else +#define SDL_PLATFORM_SUPPORTS_METAL 0 +#endif + +#ifndef SDL_VIDEO_RENDER_METAL +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_RENDER_METAL 1 +#else +#define SDL_VIDEO_RENDER_METAL 0 +#endif +#endif + +/* Enable OpenGL support */ +#ifndef SDL_VIDEO_OPENGL +#define SDL_VIDEO_OPENGL 1 +#endif +#ifndef SDL_VIDEO_OPENGL_ES2 +#define SDL_VIDEO_OPENGL_ES2 1 +#endif +#ifndef SDL_VIDEO_OPENGL_EGL +#define SDL_VIDEO_OPENGL_EGL 1 +#endif +#ifndef SDL_VIDEO_OPENGL_CGL +#define SDL_VIDEO_OPENGL_CGL 1 +#endif +#ifndef SDL_VIDEO_OPENGL_GLX +#define SDL_VIDEO_OPENGL_GLX 1 +#endif + +/* Enable Vulkan and Metal support */ +#ifndef SDL_VIDEO_VULKAN +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_VULKAN 1 +#else +#define SDL_VIDEO_VULKAN 0 +#endif +#endif + +#ifndef SDL_VIDEO_METAL +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_METAL 1 +#else +#define SDL_VIDEO_METAL 0 +#endif +#endif + +/* Enable system power support */ +#define SDL_POWER_MACOSX 1 + +/* enable filesystem support */ +#define SDL_FILESYSTEM_COCOA 1 + +/* Enable assembly routines */ +#ifdef __ppc__ +#define SDL_ALTIVEC_BLITTERS 1 +#endif + +#endif /* SDL_config_macosx_h_ */ diff --git a/third_party/SDL2/include/SDL_config_minimal.h b/third_party/SDL2/include/SDL_config_minimal.h new file mode 100644 index 00000000000..5695871787f --- /dev/null +++ b/third_party/SDL2/include/SDL_config_minimal.h @@ -0,0 +1,95 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_minimal_h_ +#define SDL_config_minimal_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +/** + * \file SDL_config_minimal.h + * + * This is the minimal configuration that can be used to build SDL. + */ + +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 + +#if !defined(HAVE_STDINT_H) && !defined(_STDINT_H_) +/* Most everything except Visual Studio 2008 and earlier has stdint.h now */ +#if defined(_MSC_VER) && (_MSC_VER < 1600) +typedef signed __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef signed __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef signed __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; +#ifndef _UINTPTR_T_DEFINED +#ifdef _WIN64 +typedef unsigned __int64 uintptr_t; +#else +typedef unsigned int uintptr_t; +#endif +#define _UINTPTR_T_DEFINED +#endif +#else +#define HAVE_STDINT_H 1 +#endif /* Visual Studio 2008 */ +#endif /* !_STDINT_H_ && !HAVE_STDINT_H */ + +#ifdef __GNUC__ +#define HAVE_GCC_SYNC_LOCK_TEST_AND_SET 1 +#endif + +/* Enable the dummy audio driver (src/audio/dummy/\*.c) */ +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable the stub joystick driver (src/joystick/dummy/\*.c) */ +#define SDL_JOYSTICK_DISABLED 1 + +/* Enable the stub haptic driver (src/haptic/dummy/\*.c) */ +#define SDL_HAPTIC_DISABLED 1 + +/* Enable the stub HIDAPI */ +#define SDL_HIDAPI_DISABLED 1 + +/* Enable the stub sensor driver (src/sensor/dummy/\*.c) */ +#define SDL_SENSOR_DISABLED 1 + +/* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ +#define SDL_LOADSO_DISABLED 1 + +/* Enable the stub thread support (src/thread/generic/\*.c) */ +#define SDL_THREADS_DISABLED 1 + +/* Enable the stub timer support (src/timer/dummy/\*.c) */ +#define SDL_TIMERS_DISABLED 1 + +/* Enable the dummy video driver (src/video/dummy/\*.c) */ +#define SDL_VIDEO_DRIVER_DUMMY 1 + +/* Enable the dummy filesystem driver (src/filesystem/dummy/\*.c) */ +#define SDL_FILESYSTEM_DUMMY 1 + +#endif /* SDL_config_minimal_h_ */ diff --git a/third_party/SDL2/include/SDL_config_ngage.h b/third_party/SDL2/include/SDL_config_ngage.h new file mode 100644 index 00000000000..b6042cd19e9 --- /dev/null +++ b/third_party/SDL2/include/SDL_config_ngage.h @@ -0,0 +1,89 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_ngage_h_ +#define SDL_config_ngage_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef signed long long int64_t; +typedef unsigned long long uint64_t; +typedef unsigned long uintptr_t; + +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_MATH_H 1 +#define HAVE_CEIL 1 +#define HAVE_COPYSIGN 1 +#define HAVE_COS 1 +#define HAVE_EXP 1 +#define HAVE_FABS 1 +#define HAVE_FLOOR 1 +#define HAVE_LOG 1 +#define HAVE_LOG10 1 +#define HAVE_SCALBN 1 +#define HAVE_SIN 1 +#define HAVE_SQRT 1 +#define HAVE_TAN 1 +#define HAVE_MALLOC 1 +#define SDL_MAIN_NEEDED 1 +#define LACKS_SYS_MMAN_H 1 + +/* Enable the N-Gage thread support (src/thread/ngage/\*.c) */ +#define SDL_THREAD_NGAGE 1 + +/* Enable the N-Gage timer support (src/timer/ngage/\*.c) */ +#define SDL_TIMER_NGAGE 1 + +/* Enable the N-Gage video driver (src/video/ngage/\*.c) */ +#define SDL_VIDEO_DRIVER_NGAGE 1 + +/* Enable the dummy audio driver (src/audio/dummy/\*.c) */ +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable the stub joystick driver (src/joystick/dummy/\*.c) */ +#define SDL_JOYSTICK_DISABLED 1 + +/* Enable the stub haptic driver (src/haptic/dummy/\*.c) */ +#define SDL_HAPTIC_DISABLED 1 + +/* Enable the stub HIDAPI */ +#define SDL_HIDAPI_DISABLED 1 + +/* Enable the stub sensor driver (src/sensor/dummy/\*.c) */ +#define SDL_SENSOR_DISABLED 1 + +/* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ +#define SDL_LOADSO_DISABLED 1 + +/* Enable the dummy filesystem driver (src/filesystem/dummy/\*.c) */ +#define SDL_FILESYSTEM_DUMMY 1 + +#endif /* SDL_config_ngage_h_ */ diff --git a/third_party/SDL2/include/SDL_config_os2.h b/third_party/SDL2/include/SDL_config_os2.h new file mode 100644 index 00000000000..22fafb1f0e7 --- /dev/null +++ b/third_party/SDL2/include/SDL_config_os2.h @@ -0,0 +1,204 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_os2_h_ +#define SDL_config_os2_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +#define SIZEOF_VOIDP 4 + +#define SDL_AUDIO_DRIVER_DUMMY 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_OS2 1 + +#define SDL_POWER_DISABLED 1 +#define SDL_HAPTIC_DISABLED 1 + +#define SDL_SENSOR_DUMMY 1 +#define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_OS2 1 +#define SDL_JOYSTICK_OS2 1 +#ifndef HAVE_LIBUSB_H /* see Makefile */ +#define SDL_HIDAPI_DISABLED 1 +/*#undef SDL_JOYSTICK_HIDAPI */ +#else +#define SDL_JOYSTICK_HIDAPI 1 +#define HAVE_LIBUSB 1 +/* dynamically loaded libusb-1.0 dll: */ +#define SDL_LIBUSB_DYNAMIC "usb100.dll" +#endif +#define SDL_JOYSTICK_VIRTUAL 1 + +/* Enable OpenGL support */ +/* #undef SDL_VIDEO_OPENGL */ + +#define SDL_THREAD_OS2 1 +#define SDL_LOADSO_OS2 1 +#define SDL_TIMER_OS2 1 +#define SDL_FILESYSTEM_OS2 1 + +/* use libsamplerate for audio rate conversion. */ +/*#define HAVE_LIBSAMPLERATE_H 1 */ + +/* Enable dynamic libsamplerate support */ +#define SDL_LIBSAMPLERATE_DYNAMIC "SAMPRATE.DLL" + +#define HAVE_LIBC 1 + +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDINT_H 1 + +#define HAVE_SYS_TYPES_H 1 +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STDLIB_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MEMORY_H 1 +#define HAVE_STRING_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_WCHAR_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_MATH_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_SIGNAL_H 1 + +#if 0 /* see Makefile */ +#define HAVE_ICONV 1 +#define HAVE_ICONV_H 1 +#endif + +/* #undef HAVE_DLOPEN */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#if defined(__WATCOMC__) +#define HAVE__FSEEKI64 1 +#define HAVE__FTELLI64 1 +#endif +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_PUTENV 1 +/* OpenWatcom requires specific calling conventions for qsort and bsearch */ +#ifndef __WATCOMC__ +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#endif +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_WCSCMP 1 +#define HAVE__WCSICMP 1 +#define HAVE__WCSNICMP 1 +#define HAVE_WCSLEN 1 +#define HAVE_WCSLCPY 1 +#define HAVE_WCSLCAT 1 +/* #undef HAVE_WCSDUP */ +#define HAVE__WCSDUP 1 +#define HAVE_WCSSTR 1 +#define HAVE_WCSCMP 1 +#define HAVE_WCSNCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE__STRREV 1 +#define HAVE__STRUPR 1 +#define HAVE__STRLWR 1 +/* #undef HAVE_INDEX */ +/* #undef HAVE_RINDEX */ +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +/* #undef HAVE_STRTOK_R */ +#define HAVE_ITOA 1 +#define HAVE__LTOA 1 +#define HAVE__ULTOA 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE__I64TOA 1 +#define HAVE__UI64TOA 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRICMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_SSCANF 1 +#define HAVE_VSSCANF 1 +#define HAVE_SNPRINTF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_SETJMP 1 +#define HAVE_ACOS 1 +/* #undef HAVE_ACOSF */ +#define HAVE_ASIN 1 +/* #undef HAVE_ASINF */ +#define HAVE_ATAN 1 +#define HAVE_ATAN2 1 +/* #undef HAVE_ATAN2F */ +#define HAVE_CEIL 1 +/* #undef HAVE_CEILF */ +/* #undef HAVE_COPYSIGN */ +/* #undef HAVE_COPYSIGNF */ +#define HAVE_COS 1 +/* #undef HAVE_COSF */ +#define HAVE_EXP 1 +/* #undef HAVE_EXPF */ +#define HAVE_FABS 1 +/* #undef HAVE_FABSF */ +#define HAVE_FLOOR 1 +/* #undef HAVE_FLOORF */ +#define HAVE_FMOD 1 +/* #undef HAVE_FMODF */ +#define HAVE_LOG 1 +/* #undef HAVE_LOGF */ +#define HAVE_LOG10 1 +/* #undef HAVE_LOG10F */ +#define HAVE_POW 1 +/* #undef HAVE_POWF */ +#define HAVE_SIN 1 +/* #undef HAVE_SINF */ +/* #undef HAVE_SCALBN */ +/* #undef HAVE_SCALBNF */ +#define HAVE_SQRT 1 +/* #undef HAVE_SQRTF */ +#define HAVE_TAN 1 +/* #undef HAVE_TANF */ +/* #undef HAVE_TRUNC */ +/* #undef HAVE_TRUNCF */ +/* #undef HAVE_LROUND */ +/* #undef HAVE_LROUNDF */ +/* #undef HAVE_ROUND */ +/* #undef HAVE_ROUNDF */ + +#endif /* SDL_config_os2_h_ */ diff --git a/third_party/SDL2/include/SDL_config_pandora.h b/third_party/SDL2/include/SDL_config_pandora.h new file mode 100644 index 00000000000..96375c1e059 --- /dev/null +++ b/third_party/SDL2/include/SDL_config_pandora.h @@ -0,0 +1,141 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_pandora_h_ +#define SDL_config_pandora_h_ +#define SDL_config_h_ + +/* This is a set of defines to configure the SDL features */ + +/* General platform specific identifiers */ +#include "SDL_platform.h" + +#ifdef __LP64__ +#define SIZEOF_VOIDP 8 +#else +#define SIZEOF_VOIDP 4 +#endif + +#define SDL_BYTEORDER 1234 + +#define STDC_HEADERS 1 +#define HAVE_ALLOCA_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_ICONV_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MATH_H 1 +#define HAVE_MEMORY_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 + +#define HAVE_DLOPEN 1 +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_UNSETENV 1 +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_STRLEN 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_VSSCANF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_M_PI 1 +#define HAVE_CEIL 1 +#define HAVE_COPYSIGN 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_FABS 1 +#define HAVE_FLOOR 1 +#define HAVE_LOG 1 +#define HAVE_LOG10 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE_SIGACTION 1 +#define HAVE_SETJMP 1 +#define HAVE_NANOSLEEP 1 + +#define SDL_AUDIO_DRIVER_DUMMY 1 +#define SDL_AUDIO_DRIVER_OSS 1 + +#define SDL_INPUT_LINUXEV 1 +#define SDL_JOYSTICK_LINUX 1 +#define SDL_JOYSTICK_VIRTUAL 1 +#define SDL_HAPTIC_LINUX 1 + +#define SDL_SENSOR_DUMMY 1 + +#define SDL_LOADSO_DLOPEN 1 + +#define SDL_THREAD_PTHREAD 1 +#define SDL_THREAD_PTHREAD_RECURSIVE_MUTEX_NP 1 + +#define SDL_TIMER_UNIX 1 +#define SDL_FILESYSTEM_UNIX 1 + +#define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_X11 1 +#define SDL_VIDEO_DRIVER_PANDORA 1 +#define SDL_VIDEO_RENDER_OGL_ES 1 +#define SDL_VIDEO_OPENGL_ES 1 + +#endif /* SDL_config_pandora_h_ */ diff --git a/third_party/SDL2/include/SDL_config_windows.h b/third_party/SDL2/include/SDL_config_windows.h new file mode 100644 index 00000000000..77d2d74fd1a --- /dev/null +++ b/third_party/SDL2/include/SDL_config_windows.h @@ -0,0 +1,333 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_windows_h_ +#define SDL_config_windows_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +/* winsdkver.h defines _WIN32_MAXVER for SDK version detection. It is present since at least the Windows 7 SDK, + * but out of caution we'll only use it if the compiler supports __has_include() to confirm its presence. + * If your compiler doesn't support __has_include() but you have winsdkver.h, define HAVE_WINSDKVER_H. */ +#if !defined(HAVE_WINSDKVER_H) && defined(__has_include) +#if __has_include() +#define HAVE_WINSDKVER_H 1 +#endif +#endif + +#ifdef HAVE_WINSDKVER_H +#include +#endif + +/* sdkddkver.h defines more specific SDK version numbers. This is needed because older versions of the + * Windows 10 SDK have broken declarations for the C API for DirectX 12. */ +#if !defined(HAVE_SDKDDKVER_H) && defined(__has_include) +#if __has_include() +#define HAVE_SDKDDKVER_H 1 +#endif +#endif + +#ifdef HAVE_SDKDDKVER_H +#include +#endif + +/* This is a set of defines to configure the SDL features */ + +#if !defined(HAVE_STDINT_H) && !defined(_STDINT_H_) +/* Most everything except Visual Studio 2008 and earlier has stdint.h now */ +#if defined(_MSC_VER) && (_MSC_VER < 1600) +typedef signed __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef signed __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef signed __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef signed __int64 int64_t; +typedef unsigned __int64 uint64_t; +#ifndef _UINTPTR_T_DEFINED +#ifdef _WIN64 +typedef unsigned __int64 uintptr_t; +#else +typedef unsigned int uintptr_t; +#endif +#define _UINTPTR_T_DEFINED +#endif +#else +#define HAVE_STDINT_H 1 +#endif /* Visual Studio 2008 */ +#endif /* !_STDINT_H_ && !HAVE_STDINT_H */ + +#ifdef _WIN64 +# define SIZEOF_VOIDP 8 +#else +# define SIZEOF_VOIDP 4 +#endif + +#ifdef __clang__ +# define HAVE_GCC_ATOMICS 1 +#endif + +#define HAVE_DDRAW_H 1 +#define HAVE_DINPUT_H 1 +#define HAVE_DSOUND_H 1 +#ifndef __WATCOMC__ +#define HAVE_DXGI_H 1 +#define HAVE_XINPUT_H 1 +#if defined(_WIN32_MAXVER) && _WIN32_MAXVER >= 0x0A00 /* Windows 10 SDK */ +#define HAVE_WINDOWS_GAMING_INPUT_H 1 +#endif +#if defined(_WIN32_MAXVER) && _WIN32_MAXVER >= 0x0602 /* Windows 8 SDK */ +#define HAVE_D3D11_H 1 +#define HAVE_ROAPI_H 1 +#endif +#if defined(__has_include) +#if __has_include() && __has_include() +#define HAVE_D3D12_H 1 +#endif +#endif +#if defined(_WIN32_MAXVER) && _WIN32_MAXVER >= 0x0603 /* Windows 8.1 SDK */ +#define HAVE_SHELLSCALINGAPI_H 1 +#endif +#define HAVE_MMDEVICEAPI_H 1 +#define HAVE_AUDIOCLIENT_H 1 +#define HAVE_TPCSHRD_H 1 +#define HAVE_SENSORSAPI_H 1 +#endif +#if (defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64)) && (defined(_MSC_VER) && _MSC_VER >= 1600) +#define HAVE_IMMINTRIN_H 1 +#elif defined(__has_include) && (defined(__i386__) || defined(__x86_64)) +# if __has_include() +# define HAVE_IMMINTRIN_H 1 +# endif +#endif + +/* This is disabled by default to avoid C runtime dependencies and manifest requirements */ +#ifdef HAVE_LIBC +/* Useful headers */ +#define STDC_HEADERS 1 +#define HAVE_CTYPE_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +/* OpenWatcom requires specific calling conventions for qsort and bsearch */ +#ifndef __WATCOMC__ +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#endif +#define HAVE_ABS 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE__STRREV 1 +/* These functions have security warnings, so we won't use them */ +/* #undef HAVE__STRUPR */ +/* #undef HAVE__STRLWR */ +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +/* #undef HAVE_STRTOK_R */ +/* These functions have security warnings, so we won't use them */ +/* #undef HAVE__LTOA */ +/* #undef HAVE__ULTOA */ +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE__STRICMP 1 +#define HAVE__STRNICMP 1 +#define HAVE__WCSICMP 1 +#define HAVE__WCSNICMP 1 +#define HAVE__WCSDUP 1 +#define HAVE_ACOS 1 +#define HAVE_ASIN 1 +#define HAVE_ATAN 1 +#define HAVE_ATAN2 1 +#define HAVE_CEIL 1 +#define HAVE_COS 1 +#define HAVE_EXP 1 +#define HAVE_FABS 1 +#define HAVE_FLOOR 1 +#define HAVE_FMOD 1 +#define HAVE_LOG 1 +#define HAVE_LOG10 1 +#define HAVE_POW 1 +#define HAVE_SIN 1 +#define HAVE_SQRT 1 +#define HAVE_TAN 1 +#ifndef __WATCOMC__ +#define HAVE_ACOSF 1 +#define HAVE_ASINF 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEILF 1 +#define HAVE__COPYSIGN 1 +#define HAVE_COSF 1 +#define HAVE_EXPF 1 +#define HAVE_FABSF 1 +#define HAVE_FLOORF 1 +#define HAVE_FMODF 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10F 1 +#define HAVE_POWF 1 +#define HAVE_SINF 1 +#define HAVE_SQRTF 1 +#define HAVE_TANF 1 +#endif +#if defined(_MSC_VER) +/* These functions were added with the VC++ 2013 C runtime library */ +#if _MSC_VER >= 1800 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_VSSCANF 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#endif +/* This function is available with at least the VC++ 2008 C runtime library */ +#if _MSC_VER >= 1400 +#define HAVE__FSEEKI64 1 +#endif +#ifdef _USE_MATH_DEFINES +#define HAVE_M_PI 1 +#endif +#elif defined(__WATCOMC__) +#define HAVE__FSEEKI64 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_VSSCANF 1 +#define HAVE_ROUND 1 +#define HAVE_SCALBN 1 +#define HAVE_TRUNC 1 +#else +#define HAVE_M_PI 1 +#endif +#else +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#endif + +/* Enable various audio drivers */ +#if defined(HAVE_MMDEVICEAPI_H) && defined(HAVE_AUDIOCLIENT_H) +#define SDL_AUDIO_DRIVER_WASAPI 1 +#endif +#define SDL_AUDIO_DRIVER_DSOUND 1 +#define SDL_AUDIO_DRIVER_WINMM 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_DINPUT 1 +#define SDL_JOYSTICK_HIDAPI 1 +#ifndef __WINRT__ +#define SDL_JOYSTICK_RAWINPUT 1 +#endif +#define SDL_JOYSTICK_VIRTUAL 1 +#ifdef HAVE_WINDOWS_GAMING_INPUT_H +#define SDL_JOYSTICK_WGI 1 +#endif +#define SDL_JOYSTICK_XINPUT 1 +#define SDL_HAPTIC_DINPUT 1 +#define SDL_HAPTIC_XINPUT 1 + +/* Enable the sensor driver */ +#ifdef HAVE_SENSORSAPI_H +#define SDL_SENSOR_WINDOWS 1 +#else +#define SDL_SENSOR_DUMMY 1 +#endif + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_WINDOWS 1 + +/* Enable various threading systems */ +#define SDL_THREAD_GENERIC_COND_SUFFIX 1 +#define SDL_THREAD_WINDOWS 1 + +/* Enable various timer systems */ +#define SDL_TIMER_WINDOWS 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_WINDOWS 1 + +#ifndef SDL_VIDEO_RENDER_D3D +#define SDL_VIDEO_RENDER_D3D 1 +#endif +#if !defined(SDL_VIDEO_RENDER_D3D11) && defined(HAVE_D3D11_H) +#define SDL_VIDEO_RENDER_D3D11 1 +#endif +#if !defined(SDL_VIDEO_RENDER_D3D12) && defined(HAVE_D3D12_H) +#define SDL_VIDEO_RENDER_D3D12 1 +#endif + +/* Enable OpenGL support */ +#ifndef SDL_VIDEO_OPENGL +#define SDL_VIDEO_OPENGL 1 +#endif +#ifndef SDL_VIDEO_OPENGL_WGL +#define SDL_VIDEO_OPENGL_WGL 1 +#endif +#ifndef SDL_VIDEO_RENDER_OGL +#define SDL_VIDEO_RENDER_OGL 1 +#endif +#ifndef SDL_VIDEO_RENDER_OGL_ES2 +#define SDL_VIDEO_RENDER_OGL_ES2 1 +#endif +#ifndef SDL_VIDEO_OPENGL_ES2 +#define SDL_VIDEO_OPENGL_ES2 1 +#endif +#ifndef SDL_VIDEO_OPENGL_EGL +#define SDL_VIDEO_OPENGL_EGL 1 +#endif + +/* Enable Vulkan support */ +#define SDL_VIDEO_VULKAN 1 + +/* Enable system power support */ +#define SDL_POWER_WINDOWS 1 + +/* Enable filesystem support */ +#define SDL_FILESYSTEM_WINDOWS 1 + +#endif /* SDL_config_windows_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_config_wingdk.h b/third_party/SDL2/include/SDL_config_wingdk.h new file mode 100644 index 00000000000..2e329279db6 --- /dev/null +++ b/third_party/SDL2/include/SDL_config_wingdk.h @@ -0,0 +1,253 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_wingdk_h_ +#define SDL_config_wingdk_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +/* Windows GDK does not need Windows SDK version checks because it requires + * a recent version of the Windows 10 SDK. */ + +/* GDK only supports 64-bit */ +# define SIZEOF_VOIDP 8 + +#ifdef __clang__ +# define HAVE_GCC_ATOMICS 1 +#endif + +#define HAVE_DDRAW_H 1 +#define HAVE_DINPUT_H 1 +#define HAVE_DSOUND_H 1 +/* No SDK version checks needed for these because the SDK has to be new. */ +#define HAVE_DXGI_H 1 +#define HAVE_XINPUT_H 1 +#define HAVE_WINDOWS_GAMING_INPUT_H 1 +#define HAVE_D3D11_H 1 +#define HAVE_ROAPI_H 1 +#define HAVE_D3D12_H 1 +#define HAVE_SHELLSCALINGAPI_H 1 +#define HAVE_MMDEVICEAPI_H 1 +#define HAVE_AUDIOCLIENT_H 1 +#define HAVE_TPCSHRD_H 1 +#define HAVE_SENSORSAPI_H 1 +#if (defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64)) && (defined(_MSC_VER) && _MSC_VER >= 1600) +#define HAVE_IMMINTRIN_H 1 +#elif defined(__has_include) && (defined(__i386__) || defined(__x86_64)) +# if __has_include() +# define HAVE_IMMINTRIN_H 1 +# endif +#endif + +/* This is disabled by default to avoid C runtime dependencies and manifest requirements */ +#ifdef HAVE_LIBC +/* Useful headers */ +#define STDC_HEADERS 1 +#define HAVE_CTYPE_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE__STRREV 1 +/* These functions have security warnings, so we won't use them */ +/* #undef HAVE__STRUPR */ +/* #undef HAVE__STRLWR */ +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +/* #undef HAVE_STRTOK_R */ +/* These functions have security warnings, so we won't use them */ +/* #undef HAVE__LTOA */ +/* #undef HAVE__ULTOA */ +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE__STRICMP 1 +#define HAVE__STRNICMP 1 +#define HAVE__WCSICMP 1 +#define HAVE__WCSNICMP 1 +#define HAVE__WCSDUP 1 +#define HAVE_ACOS 1 +#define HAVE_ASIN 1 +#define HAVE_ATAN 1 +#define HAVE_ATAN2 1 +#define HAVE_CEIL 1 +#define HAVE_COS 1 +#define HAVE_EXP 1 +#define HAVE_FABS 1 +#define HAVE_FLOOR 1 +#define HAVE_FMOD 1 +#define HAVE_LOG 1 +#define HAVE_LOG10 1 +#define HAVE_POW 1 +#define HAVE_SIN 1 +#define HAVE_SQRT 1 +#define HAVE_TAN 1 +#define HAVE_ACOSF 1 +#define HAVE_ASINF 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEILF 1 +#define HAVE__COPYSIGN 1 +#define HAVE_COSF 1 +#define HAVE_EXPF 1 +#define HAVE_FABSF 1 +#define HAVE_FLOORF 1 +#define HAVE_FMODF 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10F 1 +#define HAVE_POWF 1 +#define HAVE_SINF 1 +#define HAVE_SQRTF 1 +#define HAVE_TANF 1 +#if defined(_MSC_VER) +/* These functions were added with the VC++ 2013 C runtime library */ +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_VSSCANF 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE__FSEEKI64 1 +#ifdef _USE_MATH_DEFINES +#define HAVE_M_PI 1 +#endif +#else +#define HAVE_M_PI 1 +#endif +#else +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDINT_H 1 +#endif + +/* Enable various audio drivers */ +#if defined(HAVE_MMDEVICEAPI_H) && defined(HAVE_AUDIOCLIENT_H) +#define SDL_AUDIO_DRIVER_WASAPI 1 +#endif +#define SDL_AUDIO_DRIVER_DSOUND 1 +#define SDL_AUDIO_DRIVER_WINMM 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various input drivers */ +#define SDL_JOYSTICK_DINPUT 1 +#define SDL_JOYSTICK_HIDAPI 1 +#define SDL_JOYSTICK_RAWINPUT 1 +#define SDL_JOYSTICK_VIRTUAL 1 +#ifdef HAVE_WINDOWS_GAMING_INPUT_H +#define SDL_JOYSTICK_WGI 1 +#endif +#define SDL_JOYSTICK_XINPUT 1 +#define SDL_HAPTIC_DINPUT 1 +#define SDL_HAPTIC_XINPUT 1 + +/* Enable the sensor driver */ +#ifdef HAVE_SENSORSAPI_H +#define SDL_SENSOR_WINDOWS 1 +#else +#define SDL_SENSOR_DUMMY 1 +#endif + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_WINDOWS 1 + +/* Enable various threading systems */ +#define SDL_THREAD_GENERIC_COND_SUFFIX 1 +#define SDL_THREAD_WINDOWS 1 + +/* Enable various timer systems */ +#define SDL_TIMER_WINDOWS 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_WINDOWS 1 + +#ifndef SDL_VIDEO_RENDER_D3D +#define SDL_VIDEO_RENDER_D3D 1 +#endif +#if !defined(SDL_VIDEO_RENDER_D3D11) && defined(HAVE_D3D11_H) +#define SDL_VIDEO_RENDER_D3D11 1 +#endif +#if !defined(SDL_VIDEO_RENDER_D3D12) && defined(HAVE_D3D12_H) +#define SDL_VIDEO_RENDER_D3D12 1 +#endif + +/* Enable OpenGL support */ +#ifndef SDL_VIDEO_OPENGL +#define SDL_VIDEO_OPENGL 1 +#endif +#ifndef SDL_VIDEO_OPENGL_WGL +#define SDL_VIDEO_OPENGL_WGL 1 +#endif +#ifndef SDL_VIDEO_RENDER_OGL +#define SDL_VIDEO_RENDER_OGL 1 +#endif +#ifndef SDL_VIDEO_RENDER_OGL_ES2 +#define SDL_VIDEO_RENDER_OGL_ES2 1 +#endif +#ifndef SDL_VIDEO_OPENGL_ES2 +#define SDL_VIDEO_OPENGL_ES2 1 +#endif +#ifndef SDL_VIDEO_OPENGL_EGL +#define SDL_VIDEO_OPENGL_EGL 1 +#endif + +/* Enable Vulkan support */ +#define SDL_VIDEO_VULKAN 1 + +/* Enable system power support */ +#define SDL_POWER_WINDOWS 1 + +/* Enable filesystem support */ +#define SDL_FILESYSTEM_WINDOWS 1 + +#endif /* SDL_config_wingdk_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_config_winrt.h b/third_party/SDL2/include/SDL_config_winrt.h new file mode 100644 index 00000000000..8fe0b66dbfe --- /dev/null +++ b/third_party/SDL2/include/SDL_config_winrt.h @@ -0,0 +1,220 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_winrt_h_ +#define SDL_config_winrt_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +/* Make sure the Windows SDK's NTDDI_VERSION macro gets defined. This is used + by SDL to determine which version of the Windows SDK is being used. +*/ +#include + +/* Define possibly-undefined NTDDI values (used when compiling SDL against + older versions of the Windows SDK. +*/ +#ifndef NTDDI_WINBLUE +#define NTDDI_WINBLUE 0x06030000 +#endif +#ifndef NTDDI_WIN10 +#define NTDDI_WIN10 0x0A000000 +#endif + +/* This is a set of defines to configure the SDL features */ + +#ifdef _WIN64 +# define SIZEOF_VOIDP 8 +#else +# define SIZEOF_VOIDP 4 +#endif + +#ifdef __clang__ +# define HAVE_GCC_ATOMICS 1 +#endif + +/* Useful headers */ +#define HAVE_DXGI_H 1 +#if !SDL_WINAPI_FAMILY_PHONE +#define HAVE_XINPUT_H 1 +#endif + +#define HAVE_MMDEVICEAPI_H 1 +#define HAVE_AUDIOCLIENT_H 1 +#define HAVE_TPCSHRD_H 1 + +#define HAVE_LIBC 1 +#define STDC_HEADERS 1 +#define HAVE_CTYPE_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE__STRREV 1 +#define HAVE__STRUPR 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +/* #undef HAVE_STRTOLL */ +/* #undef HAVE_STRTOULL */ +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE__STRICMP 1 +#define HAVE__STRNICMP 1 +#define HAVE_VSNPRINTF 1 +/* TODO, WinRT: consider using ??_s versions of the following */ +/* #undef HAVE__STRLWR */ +/* #undef HAVE_ITOA */ +/* #undef HAVE__LTOA */ +/* #undef HAVE__ULTOA */ +/* #undef HAVE_SSCANF */ +#define HAVE_M_PI 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEIL 1 +#define HAVE_CEILF 1 +#define HAVE__COPYSIGN 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE__SCALB 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE__FSEEKI64 1 + +#define HAVE_ROAPI_H 1 + +/* Enable various audio drivers */ +#define SDL_AUDIO_DRIVER_WASAPI 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various input drivers */ +#if SDL_WINAPI_FAMILY_PHONE +#define SDL_JOYSTICK_DISABLED 1 +#define SDL_HAPTIC_DISABLED 1 +#else +#define SDL_JOYSTICK_VIRTUAL 1 +#if (NTDDI_VERSION >= NTDDI_WIN10) +#define SDL_JOYSTICK_WGI 1 +#define SDL_HAPTIC_DISABLED 1 +#else +#define SDL_JOYSTICK_XINPUT 1 +#define SDL_HAPTIC_XINPUT 1 +#endif /* WIN10 */ +#endif + +/* WinRT doesn't have HIDAPI available */ +#define SDL_HIDAPI_DISABLED 1 + +/* Enable the dummy sensor driver */ +#define SDL_SENSOR_DUMMY 1 + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_WINDOWS 1 + +/* Enable various threading systems */ +#if (NTDDI_VERSION >= NTDDI_WINBLUE) +#define SDL_THREAD_GENERIC_COND_SUFFIX 1 +#define SDL_THREAD_WINDOWS 1 +#else +/* WinRT on Windows 8.0 and Windows Phone 8.0 don't support CreateThread() */ +#define SDL_THREAD_STDCPP 1 +#endif + +/* Enable various timer systems */ +#define SDL_TIMER_WINDOWS 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_WINRT 1 +#define SDL_VIDEO_DRIVER_DUMMY 1 + +/* Enable OpenGL ES 2.0 (via a modified ANGLE library) */ +#define SDL_VIDEO_OPENGL_ES2 1 +#define SDL_VIDEO_OPENGL_EGL 1 + +/* Enable appropriate renderer(s) */ +#define SDL_VIDEO_RENDER_D3D11 1 + +/* Disable D3D12 as it's not implemented for WinRT */ +/* #undef SDL_VIDEO_RENDER_D3D12 */ + +#ifdef SDL_VIDEO_OPENGL_ES2 +#define SDL_VIDEO_RENDER_OGL_ES2 1 +#endif + +/* Enable system power support */ +#define SDL_POWER_WINRT 1 + +#endif /* SDL_config_winrt_h_ */ diff --git a/third_party/SDL2/include/SDL_config_xbox.h b/third_party/SDL2/include/SDL_config_xbox.h new file mode 100644 index 00000000000..a06f52e544e --- /dev/null +++ b/third_party/SDL2/include/SDL_config_xbox.h @@ -0,0 +1,240 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_wingdk_h_ +#define SDL_config_wingdk_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +/* Windows GDK does not need Windows SDK version checks because it requires + * a recent version of the Windows 10 SDK. */ + +/* GDK only supports 64-bit */ +# define SIZEOF_VOIDP 8 + +#ifdef __clang__ +# define HAVE_GCC_ATOMICS 1 +#endif + +/*#define HAVE_DDRAW_H 1*/ +/*#define HAVE_DINPUT_H 1*/ +/*#define HAVE_DSOUND_H 1*/ +/* No SDK version checks needed for these because the SDK has to be new. */ +/* #define HAVE_DXGI_H 1 */ +#define HAVE_XINPUT_H 1 +/*#define HAVE_WINDOWS_GAMING_INPUT_H 1*/ +/*#define HAVE_D3D11_H 1*/ +/*#define HAVE_ROAPI_H 1*/ +#define HAVE_D3D12_H 1 +/*#define HAVE_SHELLSCALINGAPI_H 1*/ +#define HAVE_MMDEVICEAPI_H 1 +#define HAVE_AUDIOCLIENT_H 1 +/*#define HAVE_TPCSHRD_H 1*/ +/*#define HAVE_SENSORSAPI_H 1*/ +#if (defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64)) && (defined(_MSC_VER) && _MSC_VER >= 1600) +#define HAVE_IMMINTRIN_H 1 +#elif defined(__has_include) && (defined(__i386__) || defined(__x86_64)) +# if __has_include() +# define HAVE_IMMINTRIN_H 1 +# endif +#endif + +/* This is disabled by default to avoid C runtime dependencies and manifest requirements */ +#ifdef HAVE_LIBC +/* Useful headers */ +#define STDC_HEADERS 1 +#define HAVE_CTYPE_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MATH_H 1 +#define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 + +/* C library functions */ +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#define HAVE_ALLOCA 1 +#define HAVE_QSORT 1 +#define HAVE_BSEARCH 1 +#define HAVE_ABS 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_STRLEN 1 +#define HAVE__STRREV 1 +/* These functions have security warnings, so we won't use them */ +/* #undef HAVE__STRUPR */ +/* #undef HAVE__STRLWR */ +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +/* #undef HAVE_STRTOK_R */ +/* These functions have security warnings, so we won't use them */ +/* #undef HAVE__LTOA */ +/* #undef HAVE__ULTOA */ +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE__STRICMP 1 +#define HAVE__STRNICMP 1 +#define HAVE__WCSICMP 1 +#define HAVE__WCSNICMP 1 +#define HAVE__WCSDUP 1 +#define HAVE_ACOS 1 +#define HAVE_ASIN 1 +#define HAVE_ATAN 1 +#define HAVE_ATAN2 1 +#define HAVE_CEIL 1 +#define HAVE_COS 1 +#define HAVE_EXP 1 +#define HAVE_FABS 1 +#define HAVE_FLOOR 1 +#define HAVE_FMOD 1 +#define HAVE_LOG 1 +#define HAVE_LOG10 1 +#define HAVE_POW 1 +#define HAVE_SIN 1 +#define HAVE_SQRT 1 +#define HAVE_TAN 1 +#define HAVE_ACOSF 1 +#define HAVE_ASINF 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEILF 1 +#define HAVE__COPYSIGN 1 +#define HAVE_COSF 1 +#define HAVE_EXPF 1 +#define HAVE_FABSF 1 +#define HAVE_FLOORF 1 +#define HAVE_FMODF 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10F 1 +#define HAVE_POWF 1 +#define HAVE_SINF 1 +#define HAVE_SQRTF 1 +#define HAVE_TANF 1 +#if defined(_MSC_VER) +/* These functions were added with the VC++ 2013 C runtime library */ +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_VSSCANF 1 +#define HAVE_LROUND 1 +#define HAVE_LROUNDF 1 +#define HAVE_ROUND 1 +#define HAVE_ROUNDF 1 +#define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#define HAVE_TRUNC 1 +#define HAVE_TRUNCF 1 +#define HAVE__FSEEKI64 1 +#ifdef _USE_MATH_DEFINES +#define HAVE_M_PI 1 +#endif +#else +#define HAVE_M_PI 1 +#endif +#else +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDINT_H 1 +#endif + +/* Enable various audio drivers */ +#if defined(HAVE_MMDEVICEAPI_H) && defined(HAVE_AUDIOCLIENT_H) +#define SDL_AUDIO_DRIVER_WASAPI 1 +#endif +/*#define SDL_AUDIO_DRIVER_DSOUND 1*/ +/*#define SDL_AUDIO_DRIVER_WINMM 1*/ +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 + +/* Enable various input drivers */ +/*#define SDL_JOYSTICK_DINPUT 1*/ +/*#define SDL_JOYSTICK_HIDAPI 1*/ +/*#define SDL_JOYSTICK_RAWINPUT 1*/ +#define SDL_JOYSTICK_VIRTUAL 1 +#ifdef HAVE_WINDOWS_GAMING_INPUT_H +#define SDL_JOYSTICK_WGI 1 +#endif +#define SDL_JOYSTICK_XINPUT 1 +/*#define SDL_HAPTIC_DINPUT 1*/ +#define SDL_HAPTIC_XINPUT 1 + +/* Enable the sensor driver */ +#ifdef HAVE_SENSORSAPI_H +#define SDL_SENSOR_WINDOWS 1 +#else +#define SDL_SENSOR_DUMMY 1 +#endif + +/* Enable various shared object loading systems */ +#define SDL_LOADSO_WINDOWS 1 + +/* Enable various threading systems */ +#define SDL_THREAD_GENERIC_COND_SUFFIX 1 +#define SDL_THREAD_WINDOWS 1 + +/* Enable various timer systems */ +#define SDL_TIMER_WINDOWS 1 + +/* Enable various video drivers */ +#define SDL_VIDEO_DRIVER_DUMMY 1 +#define SDL_VIDEO_DRIVER_WINDOWS 1 + +#if !defined(SDL_VIDEO_RENDER_D3D12) && defined(HAVE_D3D12_H) +#define SDL_VIDEO_RENDER_D3D12 1 +#endif + +/* Enable OpenGL support */ +#ifndef SDL_VIDEO_OPENGL +#define SDL_VIDEO_OPENGL 1 +#endif +#ifndef SDL_VIDEO_OPENGL_WGL +#define SDL_VIDEO_OPENGL_WGL 1 +#endif +#ifndef SDL_VIDEO_RENDER_OGL +#define SDL_VIDEO_RENDER_OGL 1 +#endif + +/* Enable system power support */ +/*#define SDL_POWER_WINDOWS 1*/ +#define SDL_POWER_HARDWIRED 1 + +/* Enable filesystem support */ +/* #define SDL_FILESYSTEM_WINDOWS 1*/ +#define SDL_FILESYSTEM_XBOX 1 + +/* Disable IME as not supported yet (TODO: Xbox IME?) */ +#define SDL_DISABLE_WINDOWS_IME 1 + +#endif /* SDL_config_wingdk_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_copying.h b/third_party/SDL2/include/SDL_copying.h new file mode 100644 index 00000000000..bde7431896c --- /dev/null +++ b/third_party/SDL2/include/SDL_copying.h @@ -0,0 +1,20 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ diff --git a/third_party/SDL2/include/SDL_cpuinfo.h b/third_party/SDL2/include/SDL_cpuinfo.h new file mode 100644 index 00000000000..047dc0f52ce --- /dev/null +++ b/third_party/SDL2/include/SDL_cpuinfo.h @@ -0,0 +1,602 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: CPUInfo */ + +/** + * # CategoryCPUInfo + * + * CPU feature detection for SDL. + * + * These functions are largely concerned with reporting if the system has + * access to various SIMD instruction sets, but also has other important info + * to share, such as number of logical CPU cores. + */ + +#ifndef SDL_cpuinfo_h_ +#define SDL_cpuinfo_h_ + +#include "SDL_stdinc.h" + +/* Need to do this here because intrin.h has C++ code in it */ +/* Visual Studio 2005 has a bug where intrin.h conflicts with winnt.h */ +#if defined(_MSC_VER) && (_MSC_VER >= 1500) && (defined(_M_IX86) || defined(_M_X64)) +#ifdef __clang__ +/* As of Clang 11, '_m_prefetchw' is conflicting with the winnt.h's version, + so we define the needed '_m_prefetch' here as a pseudo-header, until the issue is fixed. */ + +#ifndef __PRFCHWINTRIN_H +#define __PRFCHWINTRIN_H + +static __inline__ void __attribute__((__always_inline__, __nodebug__)) +_m_prefetch(void *__P) +{ + __builtin_prefetch (__P, 0, 3 /* _MM_HINT_T0 */); +} + +#endif /* __PRFCHWINTRIN_H */ +#endif /* __clang__ */ +#include +#ifndef _WIN64 +// #ifndef __MMX__ +// #define __MMX__ +// #endif +/* +#ifndef __3dNOW__ +#define __3dNOW__ +#endif +*/ +#endif +#ifndef __SSE__ +#define __SSE__ +#endif +#ifndef __SSE2__ +#define __SSE2__ +#endif +#ifndef __SSE3__ +#define __SSE3__ +#endif +#elif defined(__MINGW64_VERSION_MAJOR) +#include +#if !defined(SDL_DISABLE_ARM_NEON_H) && defined(__ARM_NEON) +# include +#endif +#else +/* altivec.h redefining bool causes a number of problems, see bugs 3993 and 4392, so you need to explicitly define SDL_ENABLE_ALTIVEC_H to have it included. */ +#if defined(HAVE_ALTIVEC_H) && defined(__ALTIVEC__) && !defined(__APPLE_ALTIVEC__) && defined(SDL_ENABLE_ALTIVEC_H) +#include +#endif +#if !defined(SDL_DISABLE_ARM_NEON_H) +# if defined(__ARM_NEON) +# include +# elif defined(__WINDOWS__) || defined(__WINRT__) || defined(__GDK__) +/* Visual Studio doesn't define __ARM_ARCH, but _M_ARM (if set, always 7), and _M_ARM64 (if set, always 1). */ +# if defined(_M_ARM) +# include +# include +# define __ARM_NEON 1 /* Set __ARM_NEON so that it can be used elsewhere, at compile time */ +# endif +# if defined (_M_ARM64) +# include +# include +# define __ARM_NEON 1 /* Set __ARM_NEON so that it can be used elsewhere, at compile time */ +# define __ARM_ARCH 8 +# endif +# endif +#endif +#endif /* compiler version */ + +#if defined(__3dNOW__) && !defined(SDL_DISABLE_MM3DNOW_H) +#include +#endif +#if defined(__loongarch_sx) && !defined(SDL_DISABLE_LSX_H) +#include +#define __LSX__ +#endif +#if defined(__loongarch_asx) && !defined(SDL_DISABLE_LASX_H) +#include +#define __LASX__ +#endif +#if defined(HAVE_IMMINTRIN_H) && !defined(SDL_DISABLE_IMMINTRIN_H) +#include +#else +#if defined(__MMX__) && !defined(SDL_DISABLE_MMINTRIN_H) +#include +#endif +#if defined(__SSE__) && !defined(SDL_DISABLE_XMMINTRIN_H) +#include +#endif +#if defined(__SSE2__) && !defined(SDL_DISABLE_EMMINTRIN_H) +#include +#endif +#if defined(__SSE3__) && !defined(SDL_DISABLE_PMMINTRIN_H) +#include +#endif +#endif /* HAVE_IMMINTRIN_H */ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* This is a guess for the cacheline size used for padding. + * Most x86 processors have a 64 byte cache line. + * The 64-bit PowerPC processors have a 128 byte cache line. + * We'll use the larger value to be generally safe. + */ +#define SDL_CACHELINE_SIZE 128 + +/** + * Get the number of CPU cores available. + * + * \returns the total number of logical CPU cores. On CPUs that include + * technologies such as hyperthreading, the number of logical cores + * may be more than the number of physical cores. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_GetCPUCount(void); + +/** + * Determine the L1 cache line size of the CPU. + * + * This is useful for determining multi-threaded structure padding or SIMD + * prefetch sizes. + * + * \returns the L1 cache line size of the CPU, in bytes. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_GetCPUCacheLineSize(void); + +/** + * Determine whether the CPU has the RDTSC instruction. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has the RDTSC instruction or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasRDTSC(void); + +/** + * Determine whether the CPU has AltiVec features. + * + * This always returns false on CPUs that aren't using PowerPC instruction + * sets. + * + * \returns SDL_TRUE if the CPU has AltiVec features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasAltiVec(void); + +/** + * Determine whether the CPU has MMX features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has MMX features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasMMX(void); + +/** + * Determine whether the CPU has 3DNow! features. + * + * This always returns false on CPUs that aren't using AMD instruction sets. + * + * \returns SDL_TRUE if the CPU has 3DNow! features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_Has3DNow(void); + +/** + * Determine whether the CPU has SSE features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has SSE features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE(void); + +/** + * Determine whether the CPU has SSE2 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has SSE2 features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE2(void); + +/** + * Determine whether the CPU has SSE3 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has SSE3 features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE3(void); + +/** + * Determine whether the CPU has SSE4.1 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has SSE4.1 features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE41(void); + +/** + * Determine whether the CPU has SSE4.2 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has SSE4.2 features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasSSE42(void); + +/** + * Determine whether the CPU has AVX features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has AVX features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX2 + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX(void); + +/** + * Determine whether the CPU has AVX2 features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has AVX2 features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_Has3DNow + * \sa SDL_HasAltiVec + * \sa SDL_HasAVX + * \sa SDL_HasMMX + * \sa SDL_HasRDTSC + * \sa SDL_HasSSE + * \sa SDL_HasSSE2 + * \sa SDL_HasSSE3 + * \sa SDL_HasSSE41 + * \sa SDL_HasSSE42 + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX2(void); + +/** + * Determine whether the CPU has AVX-512F (foundation) features. + * + * This always returns false on CPUs that aren't using Intel instruction sets. + * + * \returns SDL_TRUE if the CPU has AVX-512F features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.9. + * + * \sa SDL_HasAVX + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasAVX512F(void); + +/** + * Determine whether the CPU has ARM SIMD (ARMv6) features. + * + * This is different from ARM NEON, which is a different instruction set. + * + * This always returns false on CPUs that aren't using ARM instruction sets. + * + * \returns SDL_TRUE if the CPU has ARM SIMD features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.12. + * + * \sa SDL_HasNEON + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasARMSIMD(void); + +/** + * Determine whether the CPU has NEON (ARM SIMD) features. + * + * This always returns false on CPUs that aren't using ARM instruction sets. + * + * \returns SDL_TRUE if the CPU has ARM NEON features or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasNEON(void); + +/** + * Determine whether the CPU has LSX (LOONGARCH SIMD) features. + * + * This always returns false on CPUs that aren't using LOONGARCH instruction + * sets. + * + * \returns SDL_TRUE if the CPU has LOONGARCH LSX features or SDL_FALSE if + * not. + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasLSX(void); + +/** + * Determine whether the CPU has LASX (LOONGARCH SIMD) features. + * + * This always returns false on CPUs that aren't using LOONGARCH instruction + * sets. + * + * \returns SDL_TRUE if the CPU has LOONGARCH LASX features or SDL_FALSE if + * not. + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasLASX(void); + +/** + * Get the amount of RAM configured in the system. + * + * \returns the amount of RAM configured in the system in MiB. + * + * \since This function is available since SDL 2.0.1. + */ +extern DECLSPEC int SDLCALL SDL_GetSystemRAM(void); + +/** + * Report the alignment this system needs for SIMD allocations. + * + * This will return the minimum number of bytes to which a pointer must be + * aligned to be compatible with SIMD instructions on the current machine. For + * example, if the machine supports SSE only, it will return 16, but if it + * supports AVX-512F, it'll return 64 (etc). This only reports values for + * instruction sets SDL knows about, so if your SDL build doesn't have + * SDL_HasAVX512F(), then it might return 16 for the SSE support it sees and + * not 64 for the AVX-512 instructions that exist but SDL doesn't know about. + * Plan accordingly. + * + * \returns the alignment in bytes needed for available, known SIMD + * instructions. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC size_t SDLCALL SDL_SIMDGetAlignment(void); + +/** + * Allocate memory in a SIMD-friendly way. + * + * This will allocate a block of memory that is suitable for use with SIMD + * instructions. Specifically, it will be properly aligned and padded for the + * system's supported vector instructions. + * + * The memory returned will be padded such that it is safe to read or write an + * incomplete vector at the end of the memory block. This can be useful so you + * don't have to drop back to a scalar fallback at the end of your SIMD + * processing loop to deal with the final elements without overflowing the + * allocated buffer. + * + * You must free this memory with SDL_FreeSIMD(), not free() or SDL_free() or + * delete[], etc. + * + * Note that SDL will only deal with SIMD instruction sets it is aware of; for + * example, SDL 2.0.8 knows that SSE wants 16-byte vectors (SDL_HasSSE()), and + * AVX2 wants 32 bytes (SDL_HasAVX2()), but doesn't know that AVX-512 wants + * 64. To be clear: if you can't decide to use an instruction set with an + * SDL_Has*() function, don't use that instruction set with memory allocated + * through here. + * + * SDL_AllocSIMD(0) will return a non-NULL pointer, assuming the system isn't + * out of memory, but you are not allowed to dereference it (because you only + * own zero bytes of that buffer). + * + * \param len The length, in bytes, of the block to allocate. The actual + * allocated block might be larger due to padding, etc. + * \returns a pointer to the newly-allocated block, NULL if out of memory. + * + * \since This function is available since SDL 2.0.10. + * + * \sa SDL_SIMDGetAlignment + * \sa SDL_SIMDRealloc + * \sa SDL_SIMDFree + */ +extern DECLSPEC void * SDLCALL SDL_SIMDAlloc(const size_t len); + +/** + * Reallocate memory obtained from SDL_SIMDAlloc + * + * It is not valid to use this function on a pointer from anything but + * SDL_SIMDAlloc(). It can't be used on pointers from malloc, realloc, + * SDL_malloc, memalign, new[], etc. + * + * \param mem The pointer obtained from SDL_SIMDAlloc. This function also + * accepts NULL, at which point this function is the same as + * calling SDL_SIMDAlloc with a NULL pointer. + * \param len The length, in bytes, of the block to allocated. The actual + * allocated block might be larger due to padding, etc. Passing 0 + * will return a non-NULL pointer, assuming the system isn't out of + * memory. + * \returns a pointer to the newly-reallocated block, NULL if out of memory. + * + * \since This function is available since SDL 2.0.14. + * + * \sa SDL_SIMDGetAlignment + * \sa SDL_SIMDAlloc + * \sa SDL_SIMDFree + */ +extern DECLSPEC void * SDLCALL SDL_SIMDRealloc(void *mem, const size_t len); + +/** + * Deallocate memory obtained from SDL_SIMDAlloc + * + * It is not valid to use this function on a pointer from anything but + * SDL_SIMDAlloc() or SDL_SIMDRealloc(). It can't be used on pointers from + * malloc, realloc, SDL_malloc, memalign, new[], etc. + * + * However, SDL_SIMDFree(NULL) is a legal no-op. + * + * The memory pointed to by `ptr` is no longer valid for access upon return, + * and may be returned to the system or reused by a future allocation. The + * pointer passed to this function is no longer safe to dereference once this + * function returns, and should be discarded. + * + * \param ptr The pointer, returned from SDL_SIMDAlloc or SDL_SIMDRealloc, to + * deallocate. NULL is a legal no-op. + * + * \since This function is available since SDL 2.0.10. + * + * \sa SDL_SIMDAlloc + * \sa SDL_SIMDRealloc + */ +extern DECLSPEC void SDLCALL SDL_SIMDFree(void *ptr); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_cpuinfo_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_egl.h b/third_party/SDL2/include/SDL_egl.h new file mode 100644 index 00000000000..31290ec25a0 --- /dev/null +++ b/third_party/SDL2/include/SDL_egl.h @@ -0,0 +1,2351 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * This is a simple file to encapsulate the EGL API headers. + */ + +#if !defined(_MSC_VER) && !defined(__ANDROID__) && !defined(SDL_USE_BUILTIN_OPENGL_DEFINITIONS) + +#if defined(__vita__) || defined(__psp2__) +#include +#endif + +#include +#include + +#else /* _MSC_VER */ + +/* EGL headers for Visual Studio */ + +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2018 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Khronos platform-specific types and definitions. + * + * The master copy of khrplatform.h is maintained in the Khronos EGL + * Registry repository at https://github.com/KhronosGroup/EGL-Registry + * The last semantic modification to khrplatform.h was at commit ID: + * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 + * + * Adopters may modify this file to suit their platform. Adopters are + * encouraged to submit platform specific modifications to the Khronos + * group so that they can be included in future versions of this file. + * Please submit changes by filing pull requests or issues on + * the EGL Registry repository linked above. + * + * + * See the Implementer's Guidelines for information about where this file + * should be located on your system and for more details of its use: + * http://www.khronos.org/registry/implementers_guide.pdf + * + * This file should be included as + * #include + * by Khronos client API header files that use its types and defines. + * + * The types in khrplatform.h should only be used to define API-specific types. + * + * Types defined in khrplatform.h: + * khronos_int8_t signed 8 bit + * khronos_uint8_t unsigned 8 bit + * khronos_int16_t signed 16 bit + * khronos_uint16_t unsigned 16 bit + * khronos_int32_t signed 32 bit + * khronos_uint32_t unsigned 32 bit + * khronos_int64_t signed 64 bit + * khronos_uint64_t unsigned 64 bit + * khronos_intptr_t signed same number of bits as a pointer + * khronos_uintptr_t unsigned same number of bits as a pointer + * khronos_ssize_t signed size + * khronos_usize_t unsigned size + * khronos_float_t signed 32 bit floating point + * khronos_time_ns_t unsigned 64 bit time in nanoseconds + * khronos_utime_nanoseconds_t unsigned time interval or absolute time in + * nanoseconds + * khronos_stime_nanoseconds_t signed time interval in nanoseconds + * khronos_boolean_enum_t enumerated boolean type. This should + * only be used as a base type when a client API's boolean type is + * an enum. Client APIs which use an integer or other type for + * booleans cannot use this as the base type for their boolean. + * + * Tokens defined in khrplatform.h: + * + * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. + * + * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. + * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. + * + * Calling convention macros defined in this file: + * KHRONOS_APICALL + * KHRONOS_APIENTRY + * KHRONOS_APIATTRIBUTES + * + * These may be used in function prototypes as: + * + * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( + * int arg1, + * int arg2) KHRONOS_APIATTRIBUTES; + */ + +#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) +# define KHRONOS_STATIC 1 +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(KHRONOS_STATIC) + /* If the preprocessor constant KHRONOS_STATIC is defined, make the + * header compatible with static linking. */ +# define KHRONOS_APICALL +#elif defined(_WIN32) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#elif defined(__ANDROID__) +# define KHRONOS_APICALL __attribute__((visibility("default"))) +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 +/* + * To support platform where unsigned long cannot be used interchangeably with + * inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t. + * Ideally, we could just use (u)intptr_t everywhere, but this could result in + * ABI breakage if khronos_uintptr_t is changed from unsigned long to + * unsigned long long or similar (this results in different C++ name mangling). + * To avoid changes for existing platforms, we restrict usage of intptr_t to + * platforms where the size of a pointer is larger than the size of long. + */ +#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__) +#if __SIZEOF_POINTER__ > __SIZEOF_LONG__ +#define KHRONOS_USE_INTPTR_T +#endif +#endif + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +/* + * Types that differ between LLP64 and LP64 architectures - in LLP64, + * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears + * to be the only LLP64 architecture in current use. + */ +#ifdef KHRONOS_USE_INTPTR_T +typedef intptr_t khronos_intptr_t; +typedef uintptr_t khronos_uintptr_t; +#elif defined(_WIN64) +typedef signed long long int khronos_intptr_t; +typedef unsigned long long int khronos_uintptr_t; +#else +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +#endif + +#if defined(_WIN64) +typedef signed long long int khronos_ssize_t; +typedef unsigned long long int khronos_usize_t; +#else +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; +#endif + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + +/* + * Dummy value used to pad enum types to 32 bits. + */ +#ifndef KHRONOS_MAX_ENUM +#define KHRONOS_MAX_ENUM 0x7FFFFFFF +#endif + +/* + * Enumerated boolean type + * + * Values other than zero should be considered to be true. Therefore + * comparisons should not be made against KHRONOS_TRUE. + */ +typedef enum { + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +} khronos_boolean_enum_t; + +#endif /* __khrplatform_h_ */ + + +#ifndef __eglplatform_h_ +#define __eglplatform_h_ + +/* +** Copyright 2007-2020 The Khronos Group Inc. +** SPDX-License-Identifier: Apache-2.0 +*/ + +/* Platform-specific types and definitions for egl.h + * + * Adopters may modify khrplatform.h and this file to suit their platform. + * You are encouraged to submit all modifications to the Khronos group so that + * they can be included in future versions of this file. Please submit changes + * by filing an issue or pull request on the public Khronos EGL Registry, at + * https://www.github.com/KhronosGroup/EGL-Registry/ + */ + +/*#include */ + +/* Macros used in EGL function prototype declarations. + * + * EGL functions should be prototyped as: + * + * EGLAPI return-type EGLAPIENTRY eglFunction(arguments); + * typedef return-type (EXPAPIENTRYP PFNEGLFUNCTIONPROC) (arguments); + * + * KHRONOS_APICALL and KHRONOS_APIENTRY are defined in KHR/khrplatform.h + */ + +#ifndef EGLAPI +#define EGLAPI KHRONOS_APICALL +#endif + +#ifndef EGLAPIENTRY +#define EGLAPIENTRY KHRONOS_APIENTRY +#endif +#define EGLAPIENTRYP EGLAPIENTRY* + +/* The types NativeDisplayType, NativeWindowType, and NativePixmapType + * are aliases of window-system-dependent types, such as X Display * or + * Windows Device Context. They must be defined in platform-specific + * code below. The EGL-prefixed versions of Native*Type are the same + * types, renamed in EGL 1.3 so all types in the API start with "EGL". + * + * Khronos STRONGLY RECOMMENDS that you use the default definitions + * provided below, since these changes affect both binary and source + * portability of applications using EGL running on different EGL + * implementations. + */ + +#if defined(EGL_NO_PLATFORM_SPECIFIC_TYPES) + +typedef void *EGLNativeDisplayType; +typedef void *EGLNativePixmapType; +typedef void *EGLNativeWindowType; + +#elif defined(_WIN32) || defined(__VC32__) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) /* Win32 and WinCE */ +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include + +typedef HDC EGLNativeDisplayType; +typedef HBITMAP EGLNativePixmapType; +typedef HWND EGLNativeWindowType; + +#elif defined(__EMSCRIPTEN__) + +typedef int EGLNativeDisplayType; +typedef int EGLNativePixmapType; +typedef int EGLNativeWindowType; + +#elif defined(__WINSCW__) || defined(__SYMBIAN32__) /* Symbian */ + +typedef int EGLNativeDisplayType; +typedef void *EGLNativePixmapType; +typedef void *EGLNativeWindowType; + +#elif defined(WL_EGL_PLATFORM) + +typedef struct wl_display *EGLNativeDisplayType; +typedef struct wl_egl_pixmap *EGLNativePixmapType; +typedef struct wl_egl_window *EGLNativeWindowType; + +#elif defined(__GBM__) + +typedef struct gbm_device *EGLNativeDisplayType; +typedef struct gbm_bo *EGLNativePixmapType; +typedef void *EGLNativeWindowType; + +#elif defined(__ANDROID__) || defined(ANDROID) + +struct ANativeWindow; +struct egl_native_pixmap_t; + +typedef void* EGLNativeDisplayType; +typedef struct egl_native_pixmap_t* EGLNativePixmapType; +typedef struct ANativeWindow* EGLNativeWindowType; + +#elif defined(USE_OZONE) + +typedef intptr_t EGLNativeDisplayType; +typedef intptr_t EGLNativePixmapType; +typedef intptr_t EGLNativeWindowType; + +#elif defined(USE_X11) + +/* X11 (tentative) */ +#include +#include + +typedef Display *EGLNativeDisplayType; +typedef Pixmap EGLNativePixmapType; +typedef Window EGLNativeWindowType; + +#elif defined(__unix__) + +typedef void *EGLNativeDisplayType; +typedef khronos_uintptr_t EGLNativePixmapType; +typedef khronos_uintptr_t EGLNativeWindowType; + +#elif defined(__APPLE__) + +typedef int EGLNativeDisplayType; +typedef void *EGLNativePixmapType; +typedef void *EGLNativeWindowType; + +#elif defined(__HAIKU__) + +#include + +typedef void *EGLNativeDisplayType; +typedef khronos_uintptr_t EGLNativePixmapType; +typedef khronos_uintptr_t EGLNativeWindowType; + +#elif defined(__Fuchsia__) + +typedef void *EGLNativeDisplayType; +typedef khronos_uintptr_t EGLNativePixmapType; +typedef khronos_uintptr_t EGLNativeWindowType; + +#else +#error "Platform not recognized" +#endif + +/* EGL 1.2 types, renamed for consistency in EGL 1.3 */ +typedef EGLNativeDisplayType NativeDisplayType; +typedef EGLNativePixmapType NativePixmapType; +typedef EGLNativeWindowType NativeWindowType; + + +/* Define EGLint. This must be a signed integral type large enough to contain + * all legal attribute names and values passed into and out of EGL, whether + * their type is boolean, bitmask, enumerant (symbolic constant), integer, + * handle, or other. While in general a 32-bit integer will suffice, if + * handles are 64 bit types, then EGLint should be defined as a signed 64-bit + * integer type. + */ +typedef khronos_int32_t EGLint; + + +/* C++ / C typecast macros for special EGL handle values */ +#if defined(__cplusplus) +#define EGL_CAST(type, value) (static_cast(value)) +#else +#define EGL_CAST(type, value) ((type) (value)) +#endif + +#endif /* __eglplatform_h */ + + +#ifndef __egl_h_ +#define __egl_h_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright 2013-2020 The Khronos Group Inc. +** SPDX-License-Identifier: Apache-2.0 +** +** This header is generated from the Khronos EGL XML API Registry. +** The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** http://www.khronos.org/registry/egl +** +** Khronos $Git commit SHA1: 6fb1daea15 $ on $Git commit date: 2022-05-25 09:41:13 -0600 $ +*/ + +/*#include */ + +#ifndef EGL_EGL_PROTOTYPES +#define EGL_EGL_PROTOTYPES 1 +#endif + +/* Generated on date 20220525 */ + +/* Generated C header for: + * API: egl + * Versions considered: .* + * Versions emitted: .* + * Default extensions included: None + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ + +#ifndef EGL_VERSION_1_0 +#define EGL_VERSION_1_0 1 +typedef unsigned int EGLBoolean; +typedef void *EGLDisplay; +/*#include */ +/*#include */ +typedef void *EGLConfig; +typedef void *EGLSurface; +typedef void *EGLContext; +typedef void (*__eglMustCastToProperFunctionPointerType)(void); +#define EGL_ALPHA_SIZE 0x3021 +#define EGL_BAD_ACCESS 0x3002 +#define EGL_BAD_ALLOC 0x3003 +#define EGL_BAD_ATTRIBUTE 0x3004 +#define EGL_BAD_CONFIG 0x3005 +#define EGL_BAD_CONTEXT 0x3006 +#define EGL_BAD_CURRENT_SURFACE 0x3007 +#define EGL_BAD_DISPLAY 0x3008 +#define EGL_BAD_MATCH 0x3009 +#define EGL_BAD_NATIVE_PIXMAP 0x300A +#define EGL_BAD_NATIVE_WINDOW 0x300B +#define EGL_BAD_PARAMETER 0x300C +#define EGL_BAD_SURFACE 0x300D +#define EGL_BLUE_SIZE 0x3022 +#define EGL_BUFFER_SIZE 0x3020 +#define EGL_CONFIG_CAVEAT 0x3027 +#define EGL_CONFIG_ID 0x3028 +#define EGL_CORE_NATIVE_ENGINE 0x305B +#define EGL_DEPTH_SIZE 0x3025 +#define EGL_DONT_CARE EGL_CAST(EGLint,-1) +#define EGL_DRAW 0x3059 +#define EGL_EXTENSIONS 0x3055 +#define EGL_FALSE 0 +#define EGL_GREEN_SIZE 0x3023 +#define EGL_HEIGHT 0x3056 +#define EGL_LARGEST_PBUFFER 0x3058 +#define EGL_LEVEL 0x3029 +#define EGL_MAX_PBUFFER_HEIGHT 0x302A +#define EGL_MAX_PBUFFER_PIXELS 0x302B +#define EGL_MAX_PBUFFER_WIDTH 0x302C +#define EGL_NATIVE_RENDERABLE 0x302D +#define EGL_NATIVE_VISUAL_ID 0x302E +#define EGL_NATIVE_VISUAL_TYPE 0x302F +#define EGL_NONE 0x3038 +#define EGL_NON_CONFORMANT_CONFIG 0x3051 +#define EGL_NOT_INITIALIZED 0x3001 +#define EGL_NO_CONTEXT EGL_CAST(EGLContext,0) +#define EGL_NO_DISPLAY EGL_CAST(EGLDisplay,0) +#define EGL_NO_SURFACE EGL_CAST(EGLSurface,0) +#define EGL_PBUFFER_BIT 0x0001 +#define EGL_PIXMAP_BIT 0x0002 +#define EGL_READ 0x305A +#define EGL_RED_SIZE 0x3024 +#define EGL_SAMPLES 0x3031 +#define EGL_SAMPLE_BUFFERS 0x3032 +#define EGL_SLOW_CONFIG 0x3050 +#define EGL_STENCIL_SIZE 0x3026 +#define EGL_SUCCESS 0x3000 +#define EGL_SURFACE_TYPE 0x3033 +#define EGL_TRANSPARENT_BLUE_VALUE 0x3035 +#define EGL_TRANSPARENT_GREEN_VALUE 0x3036 +#define EGL_TRANSPARENT_RED_VALUE 0x3037 +#define EGL_TRANSPARENT_RGB 0x3052 +#define EGL_TRANSPARENT_TYPE 0x3034 +#define EGL_TRUE 1 +#define EGL_VENDOR 0x3053 +#define EGL_VERSION 0x3054 +#define EGL_WIDTH 0x3057 +#define EGL_WINDOW_BIT 0x0004 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCHOOSECONFIGPROC) (EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOPYBUFFERSPROC) (EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target); +typedef EGLContext (EGLAPIENTRYP PFNEGLCREATECONTEXTPROC) (EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list); +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPBUFFERSURFACEPROC) (EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list); +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPIXMAPSURFACEPROC) (EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list); +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEWINDOWSURFACEPROC) (EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYCONTEXTPROC) (EGLDisplay dpy, EGLContext ctx); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSURFACEPROC) (EGLDisplay dpy, EGLSurface surface); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETCONFIGATTRIBPROC) (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETCONFIGSPROC) (EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config); +typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETCURRENTDISPLAYPROC) (void); +typedef EGLSurface (EGLAPIENTRYP PFNEGLGETCURRENTSURFACEPROC) (EGLint readdraw); +typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETDISPLAYPROC) (EGLNativeDisplayType display_id); +typedef EGLint (EGLAPIENTRYP PFNEGLGETERRORPROC) (void); +typedef __eglMustCastToProperFunctionPointerType (EGLAPIENTRYP PFNEGLGETPROCADDRESSPROC) (const char *procname); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLINITIALIZEPROC) (EGLDisplay dpy, EGLint *major, EGLint *minor); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLMAKECURRENTPROC) (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYCONTEXTPROC) (EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value); +typedef const char *(EGLAPIENTRYP PFNEGLQUERYSTRINGPROC) (EGLDisplay dpy, EGLint name); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSPROC) (EGLDisplay dpy, EGLSurface surface); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLTERMINATEPROC) (EGLDisplay dpy); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLWAITGLPROC) (void); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLWAITNATIVEPROC) (EGLint engine); +#if EGL_EGL_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig (EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config); +EGLAPI EGLBoolean EGLAPIENTRY eglCopyBuffers (EGLDisplay dpy, EGLSurface surface, EGLNativePixmapType target); +EGLAPI EGLContext EGLAPIENTRY eglCreateContext (EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface (EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurface (EGLDisplay dpy, EGLConfig config, EGLNativePixmapType pixmap, const EGLint *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreateWindowSurface (EGLDisplay dpy, EGLConfig config, EGLNativeWindowType win, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroyContext (EGLDisplay dpy, EGLContext ctx); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroySurface (EGLDisplay dpy, EGLSurface surface); +EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigAttrib (EGLDisplay dpy, EGLConfig config, EGLint attribute, EGLint *value); +EGLAPI EGLBoolean EGLAPIENTRY eglGetConfigs (EGLDisplay dpy, EGLConfig *configs, EGLint config_size, EGLint *num_config); +EGLAPI EGLDisplay EGLAPIENTRY eglGetCurrentDisplay (void); +EGLAPI EGLSurface EGLAPIENTRY eglGetCurrentSurface (EGLint readdraw); +EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay (EGLNativeDisplayType display_id); +EGLAPI EGLint EGLAPIENTRY eglGetError (void); +EGLAPI __eglMustCastToProperFunctionPointerType EGLAPIENTRY eglGetProcAddress (const char *procname); +EGLAPI EGLBoolean EGLAPIENTRY eglInitialize (EGLDisplay dpy, EGLint *major, EGLint *minor); +EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent (EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryContext (EGLDisplay dpy, EGLContext ctx, EGLint attribute, EGLint *value); +EGLAPI const char *EGLAPIENTRY eglQueryString (EGLDisplay dpy, EGLint name); +EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value); +EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffers (EGLDisplay dpy, EGLSurface surface); +EGLAPI EGLBoolean EGLAPIENTRY eglTerminate (EGLDisplay dpy); +EGLAPI EGLBoolean EGLAPIENTRY eglWaitGL (void); +EGLAPI EGLBoolean EGLAPIENTRY eglWaitNative (EGLint engine); +#endif +#endif /* EGL_VERSION_1_0 */ + +#ifndef EGL_VERSION_1_1 +#define EGL_VERSION_1_1 1 +#define EGL_BACK_BUFFER 0x3084 +#define EGL_BIND_TO_TEXTURE_RGB 0x3039 +#define EGL_BIND_TO_TEXTURE_RGBA 0x303A +#define EGL_CONTEXT_LOST 0x300E +#define EGL_MIN_SWAP_INTERVAL 0x303B +#define EGL_MAX_SWAP_INTERVAL 0x303C +#define EGL_MIPMAP_TEXTURE 0x3082 +#define EGL_MIPMAP_LEVEL 0x3083 +#define EGL_NO_TEXTURE 0x305C +#define EGL_TEXTURE_2D 0x305F +#define EGL_TEXTURE_FORMAT 0x3080 +#define EGL_TEXTURE_RGB 0x305D +#define EGL_TEXTURE_RGBA 0x305E +#define EGL_TEXTURE_TARGET 0x3081 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDTEXIMAGEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint buffer); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLRELEASETEXIMAGEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint buffer); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSURFACEATTRIBPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPINTERVALPROC) (EGLDisplay dpy, EGLint interval); +#if EGL_EGL_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglBindTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer); +EGLAPI EGLBoolean EGLAPIENTRY eglReleaseTexImage (EGLDisplay dpy, EGLSurface surface, EGLint buffer); +EGLAPI EGLBoolean EGLAPIENTRY eglSurfaceAttrib (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint value); +EGLAPI EGLBoolean EGLAPIENTRY eglSwapInterval (EGLDisplay dpy, EGLint interval); +#endif +#endif /* EGL_VERSION_1_1 */ + +#ifndef EGL_VERSION_1_2 +#define EGL_VERSION_1_2 1 +typedef unsigned int EGLenum; +typedef void *EGLClientBuffer; +#define EGL_ALPHA_FORMAT 0x3088 +#define EGL_ALPHA_FORMAT_NONPRE 0x308B +#define EGL_ALPHA_FORMAT_PRE 0x308C +#define EGL_ALPHA_MASK_SIZE 0x303E +#define EGL_BUFFER_PRESERVED 0x3094 +#define EGL_BUFFER_DESTROYED 0x3095 +#define EGL_CLIENT_APIS 0x308D +#define EGL_COLORSPACE 0x3087 +#define EGL_COLORSPACE_sRGB 0x3089 +#define EGL_COLORSPACE_LINEAR 0x308A +#define EGL_COLOR_BUFFER_TYPE 0x303F +#define EGL_CONTEXT_CLIENT_TYPE 0x3097 +#define EGL_DISPLAY_SCALING 10000 +#define EGL_HORIZONTAL_RESOLUTION 0x3090 +#define EGL_LUMINANCE_BUFFER 0x308F +#define EGL_LUMINANCE_SIZE 0x303D +#define EGL_OPENGL_ES_BIT 0x0001 +#define EGL_OPENVG_BIT 0x0002 +#define EGL_OPENGL_ES_API 0x30A0 +#define EGL_OPENVG_API 0x30A1 +#define EGL_OPENVG_IMAGE 0x3096 +#define EGL_PIXEL_ASPECT_RATIO 0x3092 +#define EGL_RENDERABLE_TYPE 0x3040 +#define EGL_RENDER_BUFFER 0x3086 +#define EGL_RGB_BUFFER 0x308E +#define EGL_SINGLE_BUFFER 0x3085 +#define EGL_SWAP_BEHAVIOR 0x3093 +#define EGL_UNKNOWN EGL_CAST(EGLint,-1) +#define EGL_VERTICAL_RESOLUTION 0x3091 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDAPIPROC) (EGLenum api); +typedef EGLenum (EGLAPIENTRYP PFNEGLQUERYAPIPROC) (void); +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPBUFFERFROMCLIENTBUFFERPROC) (EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLRELEASETHREADPROC) (void); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLWAITCLIENTPROC) (void); +#if EGL_EGL_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglBindAPI (EGLenum api); +EGLAPI EGLenum EGLAPIENTRY eglQueryAPI (void); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferFromClientBuffer (EGLDisplay dpy, EGLenum buftype, EGLClientBuffer buffer, EGLConfig config, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglReleaseThread (void); +EGLAPI EGLBoolean EGLAPIENTRY eglWaitClient (void); +#endif +#endif /* EGL_VERSION_1_2 */ + +#ifndef EGL_VERSION_1_3 +#define EGL_VERSION_1_3 1 +#define EGL_CONFORMANT 0x3042 +#define EGL_CONTEXT_CLIENT_VERSION 0x3098 +#define EGL_MATCH_NATIVE_PIXMAP 0x3041 +#define EGL_OPENGL_ES2_BIT 0x0004 +#define EGL_VG_ALPHA_FORMAT 0x3088 +#define EGL_VG_ALPHA_FORMAT_NONPRE 0x308B +#define EGL_VG_ALPHA_FORMAT_PRE 0x308C +#define EGL_VG_ALPHA_FORMAT_PRE_BIT 0x0040 +#define EGL_VG_COLORSPACE 0x3087 +#define EGL_VG_COLORSPACE_sRGB 0x3089 +#define EGL_VG_COLORSPACE_LINEAR 0x308A +#define EGL_VG_COLORSPACE_LINEAR_BIT 0x0020 +#endif /* EGL_VERSION_1_3 */ + +#ifndef EGL_VERSION_1_4 +#define EGL_VERSION_1_4 1 +#define EGL_DEFAULT_DISPLAY EGL_CAST(EGLNativeDisplayType,0) +#define EGL_MULTISAMPLE_RESOLVE_BOX_BIT 0x0200 +#define EGL_MULTISAMPLE_RESOLVE 0x3099 +#define EGL_MULTISAMPLE_RESOLVE_DEFAULT 0x309A +#define EGL_MULTISAMPLE_RESOLVE_BOX 0x309B +#define EGL_OPENGL_API 0x30A2 +#define EGL_OPENGL_BIT 0x0008 +#define EGL_SWAP_BEHAVIOR_PRESERVED_BIT 0x0400 +typedef EGLContext (EGLAPIENTRYP PFNEGLGETCURRENTCONTEXTPROC) (void); +#if EGL_EGL_PROTOTYPES +EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext (void); +#endif +#endif /* EGL_VERSION_1_4 */ + +#ifndef EGL_VERSION_1_5 +#define EGL_VERSION_1_5 1 +typedef void *EGLSync; +typedef intptr_t EGLAttrib; +typedef khronos_utime_nanoseconds_t EGLTime; +typedef void *EGLImage; +#define EGL_CONTEXT_MAJOR_VERSION 0x3098 +#define EGL_CONTEXT_MINOR_VERSION 0x30FB +#define EGL_CONTEXT_OPENGL_PROFILE_MASK 0x30FD +#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY 0x31BD +#define EGL_NO_RESET_NOTIFICATION 0x31BE +#define EGL_LOSE_CONTEXT_ON_RESET 0x31BF +#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT 0x00000001 +#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define EGL_CONTEXT_OPENGL_DEBUG 0x31B0 +#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE 0x31B1 +#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS 0x31B2 +#define EGL_OPENGL_ES3_BIT 0x00000040 +#define EGL_CL_EVENT_HANDLE 0x309C +#define EGL_SYNC_CL_EVENT 0x30FE +#define EGL_SYNC_CL_EVENT_COMPLETE 0x30FF +#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE 0x30F0 +#define EGL_SYNC_TYPE 0x30F7 +#define EGL_SYNC_STATUS 0x30F1 +#define EGL_SYNC_CONDITION 0x30F8 +#define EGL_SIGNALED 0x30F2 +#define EGL_UNSIGNALED 0x30F3 +#define EGL_SYNC_FLUSH_COMMANDS_BIT 0x0001 +#define EGL_FOREVER 0xFFFFFFFFFFFFFFFFull +#define EGL_TIMEOUT_EXPIRED 0x30F5 +#define EGL_CONDITION_SATISFIED 0x30F6 +#define EGL_NO_SYNC EGL_CAST(EGLSync,0) +#define EGL_SYNC_FENCE 0x30F9 +#define EGL_GL_COLORSPACE 0x309D +#define EGL_GL_COLORSPACE_SRGB 0x3089 +#define EGL_GL_COLORSPACE_LINEAR 0x308A +#define EGL_GL_RENDERBUFFER 0x30B9 +#define EGL_GL_TEXTURE_2D 0x30B1 +#define EGL_GL_TEXTURE_LEVEL 0x30BC +#define EGL_GL_TEXTURE_3D 0x30B2 +#define EGL_GL_TEXTURE_ZOFFSET 0x30BD +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x30B3 +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x30B4 +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x30B5 +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x30B6 +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x30B7 +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x30B8 +#define EGL_IMAGE_PRESERVED 0x30D2 +#define EGL_NO_IMAGE EGL_CAST(EGLImage,0) +typedef EGLSync (EGLAPIENTRYP PFNEGLCREATESYNCPROC) (EGLDisplay dpy, EGLenum type, const EGLAttrib *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCPROC) (EGLDisplay dpy, EGLSync sync); +typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCPROC) (EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBPROC) (EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib *value); +typedef EGLImage (EGLAPIENTRYP PFNEGLCREATEIMAGEPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEPROC) (EGLDisplay dpy, EGLImage image); +typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYPROC) (EGLenum platform, void *native_display, const EGLAttrib *attrib_list); +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPLATFORMWINDOWSURFACEPROC) (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLAttrib *attrib_list); +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPLATFORMPIXMAPSURFACEPROC) (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLAttrib *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLWAITSYNCPROC) (EGLDisplay dpy, EGLSync sync, EGLint flags); +#if EGL_EGL_PROTOTYPES +EGLAPI EGLSync EGLAPIENTRY eglCreateSync (EGLDisplay dpy, EGLenum type, const EGLAttrib *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroySync (EGLDisplay dpy, EGLSync sync); +EGLAPI EGLint EGLAPIENTRY eglClientWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags, EGLTime timeout); +EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttrib (EGLDisplay dpy, EGLSync sync, EGLint attribute, EGLAttrib *value); +EGLAPI EGLImage EGLAPIENTRY eglCreateImage (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImage (EGLDisplay dpy, EGLImage image); +EGLAPI EGLDisplay EGLAPIENTRY eglGetPlatformDisplay (EGLenum platform, void *native_display, const EGLAttrib *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformWindowSurface (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLAttrib *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformPixmapSurface (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLAttrib *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglWaitSync (EGLDisplay dpy, EGLSync sync, EGLint flags); +#endif +#endif /* EGL_VERSION_1_5 */ + +#ifdef __cplusplus +} +#endif + +#endif /* __egl_h_ */ + + +#ifndef __eglext_h_ +#define __eglext_h_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright 2013-2020 The Khronos Group Inc. +** SPDX-License-Identifier: Apache-2.0 +** +** This header is generated from the Khronos EGL XML API Registry. +** The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** http://www.khronos.org/registry/egl +** +** Khronos $Git commit SHA1: 6fb1daea15 $ on $Git commit date: 2022-05-25 09:41:13 -0600 $ +*/ + +/*#include */ + +#define EGL_EGLEXT_VERSION 20220525 + +/* Generated C header for: + * API: egl + * Versions considered: .* + * Versions emitted: _nomatch_^ + * Default extensions included: egl + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ + +#ifndef EGL_KHR_cl_event +#define EGL_KHR_cl_event 1 +#define EGL_CL_EVENT_HANDLE_KHR 0x309C +#define EGL_SYNC_CL_EVENT_KHR 0x30FE +#define EGL_SYNC_CL_EVENT_COMPLETE_KHR 0x30FF +#endif /* EGL_KHR_cl_event */ + +#ifndef EGL_KHR_cl_event2 +#define EGL_KHR_cl_event2 1 +typedef void *EGLSyncKHR; +typedef intptr_t EGLAttribKHR; +typedef EGLSyncKHR (EGLAPIENTRYP PFNEGLCREATESYNC64KHRPROC) (EGLDisplay dpy, EGLenum type, const EGLAttribKHR *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSync64KHR (EGLDisplay dpy, EGLenum type, const EGLAttribKHR *attrib_list); +#endif +#endif /* EGL_KHR_cl_event2 */ + +#ifndef EGL_KHR_client_get_all_proc_addresses +#define EGL_KHR_client_get_all_proc_addresses 1 +#endif /* EGL_KHR_client_get_all_proc_addresses */ + +#ifndef EGL_KHR_config_attribs +#define EGL_KHR_config_attribs 1 +#define EGL_CONFORMANT_KHR 0x3042 +#define EGL_VG_COLORSPACE_LINEAR_BIT_KHR 0x0020 +#define EGL_VG_ALPHA_FORMAT_PRE_BIT_KHR 0x0040 +#endif /* EGL_KHR_config_attribs */ + +#ifndef EGL_KHR_context_flush_control +#define EGL_KHR_context_flush_control 1 +#define EGL_CONTEXT_RELEASE_BEHAVIOR_NONE_KHR 0 +#define EGL_CONTEXT_RELEASE_BEHAVIOR_KHR 0x2097 +#define EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR 0x2098 +#endif /* EGL_KHR_context_flush_control */ + +#ifndef EGL_KHR_create_context +#define EGL_KHR_create_context 1 +#define EGL_CONTEXT_MAJOR_VERSION_KHR 0x3098 +#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB +#define EGL_CONTEXT_FLAGS_KHR 0x30FC +#define EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR 0x30FD +#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR 0x31BD +#define EGL_NO_RESET_NOTIFICATION_KHR 0x31BE +#define EGL_LOSE_CONTEXT_ON_RESET_KHR 0x31BF +#define EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR 0x00000001 +#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR 0x00000002 +#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR 0x00000004 +#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR 0x00000001 +#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR 0x00000002 +#define EGL_OPENGL_ES3_BIT_KHR 0x00000040 +#endif /* EGL_KHR_create_context */ + +#ifndef EGL_KHR_create_context_no_error +#define EGL_KHR_create_context_no_error 1 +#define EGL_CONTEXT_OPENGL_NO_ERROR_KHR 0x31B3 +#endif /* EGL_KHR_create_context_no_error */ + +#ifndef EGL_KHR_debug +#define EGL_KHR_debug 1 +typedef void *EGLLabelKHR; +typedef void *EGLObjectKHR; +typedef void (EGLAPIENTRY *EGLDEBUGPROCKHR)(EGLenum error,const char *command,EGLint messageType,EGLLabelKHR threadLabel,EGLLabelKHR objectLabel,const char* message); +#define EGL_OBJECT_THREAD_KHR 0x33B0 +#define EGL_OBJECT_DISPLAY_KHR 0x33B1 +#define EGL_OBJECT_CONTEXT_KHR 0x33B2 +#define EGL_OBJECT_SURFACE_KHR 0x33B3 +#define EGL_OBJECT_IMAGE_KHR 0x33B4 +#define EGL_OBJECT_SYNC_KHR 0x33B5 +#define EGL_OBJECT_STREAM_KHR 0x33B6 +#define EGL_DEBUG_MSG_CRITICAL_KHR 0x33B9 +#define EGL_DEBUG_MSG_ERROR_KHR 0x33BA +#define EGL_DEBUG_MSG_WARN_KHR 0x33BB +#define EGL_DEBUG_MSG_INFO_KHR 0x33BC +#define EGL_DEBUG_CALLBACK_KHR 0x33B8 +typedef EGLint (EGLAPIENTRYP PFNEGLDEBUGMESSAGECONTROLKHRPROC) (EGLDEBUGPROCKHR callback, const EGLAttrib *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEBUGKHRPROC) (EGLint attribute, EGLAttrib *value); +typedef EGLint (EGLAPIENTRYP PFNEGLLABELOBJECTKHRPROC) (EGLDisplay display, EGLenum objectType, EGLObjectKHR object, EGLLabelKHR label); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLint EGLAPIENTRY eglDebugMessageControlKHR (EGLDEBUGPROCKHR callback, const EGLAttrib *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDebugKHR (EGLint attribute, EGLAttrib *value); +EGLAPI EGLint EGLAPIENTRY eglLabelObjectKHR (EGLDisplay display, EGLenum objectType, EGLObjectKHR object, EGLLabelKHR label); +#endif +#endif /* EGL_KHR_debug */ + +#ifndef EGL_KHR_display_reference +#define EGL_KHR_display_reference 1 +#define EGL_TRACK_REFERENCES_KHR 0x3352 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDISPLAYATTRIBKHRPROC) (EGLDisplay dpy, EGLint name, EGLAttrib *value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribKHR (EGLDisplay dpy, EGLint name, EGLAttrib *value); +#endif +#endif /* EGL_KHR_display_reference */ + +#ifndef EGL_KHR_fence_sync +#define EGL_KHR_fence_sync 1 +typedef khronos_utime_nanoseconds_t EGLTimeKHR; +#ifdef KHRONOS_SUPPORT_INT64 +#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_KHR 0x30F0 +#define EGL_SYNC_CONDITION_KHR 0x30F8 +#define EGL_SYNC_FENCE_KHR 0x30F9 +typedef EGLSyncKHR (EGLAPIENTRYP PFNEGLCREATESYNCKHRPROC) (EGLDisplay dpy, EGLenum type, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync); +typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSyncKHR (EGLDisplay dpy, EGLenum type, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncKHR (EGLDisplay dpy, EGLSyncKHR sync); +EGLAPI EGLint EGLAPIENTRY eglClientWaitSyncKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout); +EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttribKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value); +#endif +#endif /* KHRONOS_SUPPORT_INT64 */ +#endif /* EGL_KHR_fence_sync */ + +#ifndef EGL_KHR_get_all_proc_addresses +#define EGL_KHR_get_all_proc_addresses 1 +#endif /* EGL_KHR_get_all_proc_addresses */ + +#ifndef EGL_KHR_gl_colorspace +#define EGL_KHR_gl_colorspace 1 +#define EGL_GL_COLORSPACE_KHR 0x309D +#define EGL_GL_COLORSPACE_SRGB_KHR 0x3089 +#define EGL_GL_COLORSPACE_LINEAR_KHR 0x308A +#endif /* EGL_KHR_gl_colorspace */ + +#ifndef EGL_KHR_gl_renderbuffer_image +#define EGL_KHR_gl_renderbuffer_image 1 +#define EGL_GL_RENDERBUFFER_KHR 0x30B9 +#endif /* EGL_KHR_gl_renderbuffer_image */ + +#ifndef EGL_KHR_gl_texture_2D_image +#define EGL_KHR_gl_texture_2D_image 1 +#define EGL_GL_TEXTURE_2D_KHR 0x30B1 +#define EGL_GL_TEXTURE_LEVEL_KHR 0x30BC +#endif /* EGL_KHR_gl_texture_2D_image */ + +#ifndef EGL_KHR_gl_texture_3D_image +#define EGL_KHR_gl_texture_3D_image 1 +#define EGL_GL_TEXTURE_3D_KHR 0x30B2 +#define EGL_GL_TEXTURE_ZOFFSET_KHR 0x30BD +#endif /* EGL_KHR_gl_texture_3D_image */ + +#ifndef EGL_KHR_gl_texture_cubemap_image +#define EGL_KHR_gl_texture_cubemap_image 1 +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR 0x30B3 +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR 0x30B4 +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR 0x30B5 +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR 0x30B6 +#define EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR 0x30B7 +#define EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR 0x30B8 +#endif /* EGL_KHR_gl_texture_cubemap_image */ + +#ifndef EGL_KHR_image +#define EGL_KHR_image 1 +typedef void *EGLImageKHR; +#define EGL_NATIVE_PIXMAP_KHR 0x30B0 +#define EGL_NO_IMAGE_KHR EGL_CAST(EGLImageKHR,0) +typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEIMAGEKHRPROC) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYIMAGEKHRPROC) (EGLDisplay dpy, EGLImageKHR image); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR (EGLDisplay dpy, EGLImageKHR image); +#endif +#endif /* EGL_KHR_image */ + +#ifndef EGL_KHR_image_base +#define EGL_KHR_image_base 1 +#define EGL_IMAGE_PRESERVED_KHR 0x30D2 +#endif /* EGL_KHR_image_base */ + +#ifndef EGL_KHR_image_pixmap +#define EGL_KHR_image_pixmap 1 +#endif /* EGL_KHR_image_pixmap */ + +#ifndef EGL_KHR_lock_surface +#define EGL_KHR_lock_surface 1 +#define EGL_READ_SURFACE_BIT_KHR 0x0001 +#define EGL_WRITE_SURFACE_BIT_KHR 0x0002 +#define EGL_LOCK_SURFACE_BIT_KHR 0x0080 +#define EGL_OPTIMAL_FORMAT_BIT_KHR 0x0100 +#define EGL_MATCH_FORMAT_KHR 0x3043 +#define EGL_FORMAT_RGB_565_EXACT_KHR 0x30C0 +#define EGL_FORMAT_RGB_565_KHR 0x30C1 +#define EGL_FORMAT_RGBA_8888_EXACT_KHR 0x30C2 +#define EGL_FORMAT_RGBA_8888_KHR 0x30C3 +#define EGL_MAP_PRESERVE_PIXELS_KHR 0x30C4 +#define EGL_LOCK_USAGE_HINT_KHR 0x30C5 +#define EGL_BITMAP_POINTER_KHR 0x30C6 +#define EGL_BITMAP_PITCH_KHR 0x30C7 +#define EGL_BITMAP_ORIGIN_KHR 0x30C8 +#define EGL_BITMAP_PIXEL_RED_OFFSET_KHR 0x30C9 +#define EGL_BITMAP_PIXEL_GREEN_OFFSET_KHR 0x30CA +#define EGL_BITMAP_PIXEL_BLUE_OFFSET_KHR 0x30CB +#define EGL_BITMAP_PIXEL_ALPHA_OFFSET_KHR 0x30CC +#define EGL_BITMAP_PIXEL_LUMINANCE_OFFSET_KHR 0x30CD +#define EGL_LOWER_LEFT_KHR 0x30CE +#define EGL_UPPER_LEFT_KHR 0x30CF +typedef EGLBoolean (EGLAPIENTRYP PFNEGLLOCKSURFACEKHRPROC) (EGLDisplay dpy, EGLSurface surface, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNLOCKSURFACEKHRPROC) (EGLDisplay dpy, EGLSurface surface); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglLockSurfaceKHR (EGLDisplay dpy, EGLSurface surface, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglUnlockSurfaceKHR (EGLDisplay dpy, EGLSurface surface); +#endif +#endif /* EGL_KHR_lock_surface */ + +#ifndef EGL_KHR_lock_surface2 +#define EGL_KHR_lock_surface2 1 +#define EGL_BITMAP_PIXEL_SIZE_KHR 0x3110 +#endif /* EGL_KHR_lock_surface2 */ + +#ifndef EGL_KHR_lock_surface3 +#define EGL_KHR_lock_surface3 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACE64KHRPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLAttribKHR *value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurface64KHR (EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLAttribKHR *value); +#endif +#endif /* EGL_KHR_lock_surface3 */ + +#ifndef EGL_KHR_mutable_render_buffer +#define EGL_KHR_mutable_render_buffer 1 +#define EGL_MUTABLE_RENDER_BUFFER_BIT_KHR 0x1000 +#endif /* EGL_KHR_mutable_render_buffer */ + +#ifndef EGL_KHR_no_config_context +#define EGL_KHR_no_config_context 1 +#define EGL_NO_CONFIG_KHR EGL_CAST(EGLConfig,0) +#endif /* EGL_KHR_no_config_context */ + +#ifndef EGL_KHR_partial_update +#define EGL_KHR_partial_update 1 +#define EGL_BUFFER_AGE_KHR 0x313D +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETDAMAGEREGIONKHRPROC) (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglSetDamageRegionKHR (EGLDisplay dpy, EGLSurface surface, EGLint *rects, EGLint n_rects); +#endif +#endif /* EGL_KHR_partial_update */ + +#ifndef EGL_KHR_platform_android +#define EGL_KHR_platform_android 1 +#define EGL_PLATFORM_ANDROID_KHR 0x3141 +#endif /* EGL_KHR_platform_android */ + +#ifndef EGL_KHR_platform_gbm +#define EGL_KHR_platform_gbm 1 +#define EGL_PLATFORM_GBM_KHR 0x31D7 +#endif /* EGL_KHR_platform_gbm */ + +#ifndef EGL_KHR_platform_wayland +#define EGL_KHR_platform_wayland 1 +#define EGL_PLATFORM_WAYLAND_KHR 0x31D8 +#endif /* EGL_KHR_platform_wayland */ + +#ifndef EGL_KHR_platform_x11 +#define EGL_KHR_platform_x11 1 +#define EGL_PLATFORM_X11_KHR 0x31D5 +#define EGL_PLATFORM_X11_SCREEN_KHR 0x31D6 +#endif /* EGL_KHR_platform_x11 */ + +#ifndef EGL_KHR_reusable_sync +#define EGL_KHR_reusable_sync 1 +#ifdef KHRONOS_SUPPORT_INT64 +#define EGL_SYNC_STATUS_KHR 0x30F1 +#define EGL_SIGNALED_KHR 0x30F2 +#define EGL_UNSIGNALED_KHR 0x30F3 +#define EGL_TIMEOUT_EXPIRED_KHR 0x30F5 +#define EGL_CONDITION_SATISFIED_KHR 0x30F6 +#define EGL_SYNC_TYPE_KHR 0x30F7 +#define EGL_SYNC_REUSABLE_KHR 0x30FA +#define EGL_SYNC_FLUSH_COMMANDS_BIT_KHR 0x0001 +#define EGL_FOREVER_KHR 0xFFFFFFFFFFFFFFFFull +#define EGL_NO_SYNC_KHR EGL_CAST(EGLSyncKHR,0) +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode); +#endif +#endif /* KHRONOS_SUPPORT_INT64 */ +#endif /* EGL_KHR_reusable_sync */ + +#ifndef EGL_KHR_stream +#define EGL_KHR_stream 1 +typedef void *EGLStreamKHR; +typedef khronos_uint64_t EGLuint64KHR; +#ifdef KHRONOS_SUPPORT_INT64 +#define EGL_NO_STREAM_KHR EGL_CAST(EGLStreamKHR,0) +#define EGL_CONSUMER_LATENCY_USEC_KHR 0x3210 +#define EGL_PRODUCER_FRAME_KHR 0x3212 +#define EGL_CONSUMER_FRAME_KHR 0x3213 +#define EGL_STREAM_STATE_KHR 0x3214 +#define EGL_STREAM_STATE_CREATED_KHR 0x3215 +#define EGL_STREAM_STATE_CONNECTING_KHR 0x3216 +#define EGL_STREAM_STATE_EMPTY_KHR 0x3217 +#define EGL_STREAM_STATE_NEW_FRAME_AVAILABLE_KHR 0x3218 +#define EGL_STREAM_STATE_OLD_FRAME_AVAILABLE_KHR 0x3219 +#define EGL_STREAM_STATE_DISCONNECTED_KHR 0x321A +#define EGL_BAD_STREAM_KHR 0x321B +#define EGL_BAD_STATE_KHR 0x321C +typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMKHRPROC) (EGLDisplay dpy, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSTREAMKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint *value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMU64KHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR *value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamKHR (EGLDisplay dpy, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroyStreamKHR (EGLDisplay dpy, EGLStreamKHR stream); +EGLAPI EGLBoolean EGLAPIENTRY eglStreamAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint value); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLint *value); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamu64KHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLuint64KHR *value); +#endif +#endif /* KHRONOS_SUPPORT_INT64 */ +#endif /* EGL_KHR_stream */ + +#ifndef EGL_KHR_stream_attrib +#define EGL_KHR_stream_attrib 1 +#ifdef KHRONOS_SUPPORT_INT64 +typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMATTRIBKHRPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETSTREAMATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib *value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEATTRIBKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamAttribKHR (EGLDisplay dpy, const EGLAttrib *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglSetStreamAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib value); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLAttrib *value); +EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerAcquireAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerReleaseAttribKHR (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); +#endif +#endif /* KHRONOS_SUPPORT_INT64 */ +#endif /* EGL_KHR_stream_attrib */ + +#ifndef EGL_KHR_stream_consumer_gltexture +#define EGL_KHR_stream_consumer_gltexture 1 +#ifdef EGL_KHR_stream +#define EGL_CONSUMER_ACQUIRE_TIMEOUT_USEC_KHR 0x321E +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERACQUIREKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERRELEASEKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerGLTextureExternalKHR (EGLDisplay dpy, EGLStreamKHR stream); +EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerAcquireKHR (EGLDisplay dpy, EGLStreamKHR stream); +EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerReleaseKHR (EGLDisplay dpy, EGLStreamKHR stream); +#endif +#endif /* EGL_KHR_stream */ +#endif /* EGL_KHR_stream_consumer_gltexture */ + +#ifndef EGL_KHR_stream_cross_process_fd +#define EGL_KHR_stream_cross_process_fd 1 +typedef int EGLNativeFileDescriptorKHR; +#ifdef EGL_KHR_stream +#define EGL_NO_FILE_DESCRIPTOR_KHR EGL_CAST(EGLNativeFileDescriptorKHR,-1) +typedef EGLNativeFileDescriptorKHR (EGLAPIENTRYP PFNEGLGETSTREAMFILEDESCRIPTORKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream); +typedef EGLStreamKHR (EGLAPIENTRYP PFNEGLCREATESTREAMFROMFILEDESCRIPTORKHRPROC) (EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLNativeFileDescriptorKHR EGLAPIENTRY eglGetStreamFileDescriptorKHR (EGLDisplay dpy, EGLStreamKHR stream); +EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamFromFileDescriptorKHR (EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor); +#endif +#endif /* EGL_KHR_stream */ +#endif /* EGL_KHR_stream_cross_process_fd */ + +#ifndef EGL_KHR_stream_fifo +#define EGL_KHR_stream_fifo 1 +#ifdef EGL_KHR_stream +#define EGL_STREAM_FIFO_LENGTH_KHR 0x31FC +#define EGL_STREAM_TIME_NOW_KHR 0x31FD +#define EGL_STREAM_TIME_CONSUMER_KHR 0x31FE +#define EGL_STREAM_TIME_PRODUCER_KHR 0x31FF +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMTIMEKHRPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLTimeKHR *value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamTimeKHR (EGLDisplay dpy, EGLStreamKHR stream, EGLenum attribute, EGLTimeKHR *value); +#endif +#endif /* EGL_KHR_stream */ +#endif /* EGL_KHR_stream_fifo */ + +#ifndef EGL_KHR_stream_producer_aldatalocator +#define EGL_KHR_stream_producer_aldatalocator 1 +#ifdef EGL_KHR_stream +#endif /* EGL_KHR_stream */ +#endif /* EGL_KHR_stream_producer_aldatalocator */ + +#ifndef EGL_KHR_stream_producer_eglsurface +#define EGL_KHR_stream_producer_eglsurface 1 +#ifdef EGL_KHR_stream +#define EGL_STREAM_BIT_KHR 0x0800 +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATESTREAMPRODUCERSURFACEKHRPROC) (EGLDisplay dpy, EGLConfig config, EGLStreamKHR stream, const EGLint *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLSurface EGLAPIENTRY eglCreateStreamProducerSurfaceKHR (EGLDisplay dpy, EGLConfig config, EGLStreamKHR stream, const EGLint *attrib_list); +#endif +#endif /* EGL_KHR_stream */ +#endif /* EGL_KHR_stream_producer_eglsurface */ + +#ifndef EGL_KHR_surfaceless_context +#define EGL_KHR_surfaceless_context 1 +#endif /* EGL_KHR_surfaceless_context */ + +#ifndef EGL_KHR_swap_buffers_with_damage +#define EGL_KHR_swap_buffers_with_damage 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSWITHDAMAGEKHRPROC) (EGLDisplay dpy, EGLSurface surface, const EGLint *rects, EGLint n_rects); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersWithDamageKHR (EGLDisplay dpy, EGLSurface surface, const EGLint *rects, EGLint n_rects); +#endif +#endif /* EGL_KHR_swap_buffers_with_damage */ + +#ifndef EGL_KHR_vg_parent_image +#define EGL_KHR_vg_parent_image 1 +#define EGL_VG_PARENT_IMAGE_KHR 0x30BA +#endif /* EGL_KHR_vg_parent_image */ + +#ifndef EGL_KHR_wait_sync +#define EGL_KHR_wait_sync 1 +typedef EGLint (EGLAPIENTRYP PFNEGLWAITSYNCKHRPROC) (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLint EGLAPIENTRY eglWaitSyncKHR (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags); +#endif +#endif /* EGL_KHR_wait_sync */ + +#ifndef EGL_ANDROID_GLES_layers +#define EGL_ANDROID_GLES_layers 1 +#endif /* EGL_ANDROID_GLES_layers */ + +#ifndef EGL_ANDROID_blob_cache +#define EGL_ANDROID_blob_cache 1 +typedef khronos_ssize_t EGLsizeiANDROID; +typedef void (*EGLSetBlobFuncANDROID) (const void *key, EGLsizeiANDROID keySize, const void *value, EGLsizeiANDROID valueSize); +typedef EGLsizeiANDROID (*EGLGetBlobFuncANDROID) (const void *key, EGLsizeiANDROID keySize, void *value, EGLsizeiANDROID valueSize); +typedef void (EGLAPIENTRYP PFNEGLSETBLOBCACHEFUNCSANDROIDPROC) (EGLDisplay dpy, EGLSetBlobFuncANDROID set, EGLGetBlobFuncANDROID get); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI void EGLAPIENTRY eglSetBlobCacheFuncsANDROID (EGLDisplay dpy, EGLSetBlobFuncANDROID set, EGLGetBlobFuncANDROID get); +#endif +#endif /* EGL_ANDROID_blob_cache */ + +#ifndef EGL_ANDROID_create_native_client_buffer +#define EGL_ANDROID_create_native_client_buffer 1 +#define EGL_NATIVE_BUFFER_USAGE_ANDROID 0x3143 +#define EGL_NATIVE_BUFFER_USAGE_PROTECTED_BIT_ANDROID 0x00000001 +#define EGL_NATIVE_BUFFER_USAGE_RENDERBUFFER_BIT_ANDROID 0x00000002 +#define EGL_NATIVE_BUFFER_USAGE_TEXTURE_BIT_ANDROID 0x00000004 +typedef EGLClientBuffer (EGLAPIENTRYP PFNEGLCREATENATIVECLIENTBUFFERANDROIDPROC) (const EGLint *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLClientBuffer EGLAPIENTRY eglCreateNativeClientBufferANDROID (const EGLint *attrib_list); +#endif +#endif /* EGL_ANDROID_create_native_client_buffer */ + +#ifndef EGL_ANDROID_framebuffer_target +#define EGL_ANDROID_framebuffer_target 1 +#define EGL_FRAMEBUFFER_TARGET_ANDROID 0x3147 +#endif /* EGL_ANDROID_framebuffer_target */ + +#ifndef EGL_ANDROID_front_buffer_auto_refresh +#define EGL_ANDROID_front_buffer_auto_refresh 1 +#define EGL_FRONT_BUFFER_AUTO_REFRESH_ANDROID 0x314C +#endif /* EGL_ANDROID_front_buffer_auto_refresh */ + +#ifndef EGL_ANDROID_get_frame_timestamps +#define EGL_ANDROID_get_frame_timestamps 1 +typedef khronos_stime_nanoseconds_t EGLnsecsANDROID; +#define EGL_TIMESTAMP_PENDING_ANDROID EGL_CAST(EGLnsecsANDROID,-2) +#define EGL_TIMESTAMP_INVALID_ANDROID EGL_CAST(EGLnsecsANDROID,-1) +#define EGL_TIMESTAMPS_ANDROID 0x3430 +#define EGL_COMPOSITE_DEADLINE_ANDROID 0x3431 +#define EGL_COMPOSITE_INTERVAL_ANDROID 0x3432 +#define EGL_COMPOSITE_TO_PRESENT_LATENCY_ANDROID 0x3433 +#define EGL_REQUESTED_PRESENT_TIME_ANDROID 0x3434 +#define EGL_RENDERING_COMPLETE_TIME_ANDROID 0x3435 +#define EGL_COMPOSITION_LATCH_TIME_ANDROID 0x3436 +#define EGL_FIRST_COMPOSITION_START_TIME_ANDROID 0x3437 +#define EGL_LAST_COMPOSITION_START_TIME_ANDROID 0x3438 +#define EGL_FIRST_COMPOSITION_GPU_FINISHED_TIME_ANDROID 0x3439 +#define EGL_DISPLAY_PRESENT_TIME_ANDROID 0x343A +#define EGL_DEQUEUE_READY_TIME_ANDROID 0x343B +#define EGL_READS_DONE_TIME_ANDROID 0x343C +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETCOMPOSITORTIMINGSUPPORTEDANDROIDPROC) (EGLDisplay dpy, EGLSurface surface, EGLint name); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETCOMPOSITORTIMINGANDROIDPROC) (EGLDisplay dpy, EGLSurface surface, EGLint numTimestamps, const EGLint *names, EGLnsecsANDROID *values); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETNEXTFRAMEIDANDROIDPROC) (EGLDisplay dpy, EGLSurface surface, EGLuint64KHR *frameId); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC) (EGLDisplay dpy, EGLSurface surface, EGLint timestamp); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETFRAMETIMESTAMPSANDROIDPROC) (EGLDisplay dpy, EGLSurface surface, EGLuint64KHR frameId, EGLint numTimestamps, const EGLint *timestamps, EGLnsecsANDROID *values); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglGetCompositorTimingSupportedANDROID (EGLDisplay dpy, EGLSurface surface, EGLint name); +EGLAPI EGLBoolean EGLAPIENTRY eglGetCompositorTimingANDROID (EGLDisplay dpy, EGLSurface surface, EGLint numTimestamps, const EGLint *names, EGLnsecsANDROID *values); +EGLAPI EGLBoolean EGLAPIENTRY eglGetNextFrameIdANDROID (EGLDisplay dpy, EGLSurface surface, EGLuint64KHR *frameId); +EGLAPI EGLBoolean EGLAPIENTRY eglGetFrameTimestampSupportedANDROID (EGLDisplay dpy, EGLSurface surface, EGLint timestamp); +EGLAPI EGLBoolean EGLAPIENTRY eglGetFrameTimestampsANDROID (EGLDisplay dpy, EGLSurface surface, EGLuint64KHR frameId, EGLint numTimestamps, const EGLint *timestamps, EGLnsecsANDROID *values); +#endif +#endif /* EGL_ANDROID_get_frame_timestamps */ + +#ifndef EGL_ANDROID_get_native_client_buffer +#define EGL_ANDROID_get_native_client_buffer 1 +struct AHardwareBuffer; +typedef EGLClientBuffer (EGLAPIENTRYP PFNEGLGETNATIVECLIENTBUFFERANDROIDPROC) (const struct AHardwareBuffer *buffer); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLClientBuffer EGLAPIENTRY eglGetNativeClientBufferANDROID (const struct AHardwareBuffer *buffer); +#endif +#endif /* EGL_ANDROID_get_native_client_buffer */ + +#ifndef EGL_ANDROID_image_native_buffer +#define EGL_ANDROID_image_native_buffer 1 +#define EGL_NATIVE_BUFFER_ANDROID 0x3140 +#endif /* EGL_ANDROID_image_native_buffer */ + +#ifndef EGL_ANDROID_native_fence_sync +#define EGL_ANDROID_native_fence_sync 1 +#define EGL_SYNC_NATIVE_FENCE_ANDROID 0x3144 +#define EGL_SYNC_NATIVE_FENCE_FD_ANDROID 0x3145 +#define EGL_SYNC_NATIVE_FENCE_SIGNALED_ANDROID 0x3146 +#define EGL_NO_NATIVE_FENCE_FD_ANDROID -1 +typedef EGLint (EGLAPIENTRYP PFNEGLDUPNATIVEFENCEFDANDROIDPROC) (EGLDisplay dpy, EGLSyncKHR sync); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLint EGLAPIENTRY eglDupNativeFenceFDANDROID (EGLDisplay dpy, EGLSyncKHR sync); +#endif +#endif /* EGL_ANDROID_native_fence_sync */ + +#ifndef EGL_ANDROID_presentation_time +#define EGL_ANDROID_presentation_time 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLPRESENTATIONTIMEANDROIDPROC) (EGLDisplay dpy, EGLSurface surface, EGLnsecsANDROID time); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglPresentationTimeANDROID (EGLDisplay dpy, EGLSurface surface, EGLnsecsANDROID time); +#endif +#endif /* EGL_ANDROID_presentation_time */ + +#ifndef EGL_ANDROID_recordable +#define EGL_ANDROID_recordable 1 +#define EGL_RECORDABLE_ANDROID 0x3142 +#endif /* EGL_ANDROID_recordable */ + +#ifndef EGL_ANGLE_d3d_share_handle_client_buffer +#define EGL_ANGLE_d3d_share_handle_client_buffer 1 +#define EGL_D3D_TEXTURE_2D_SHARE_HANDLE_ANGLE 0x3200 +#endif /* EGL_ANGLE_d3d_share_handle_client_buffer */ + +#ifndef EGL_ANGLE_device_d3d +#define EGL_ANGLE_device_d3d 1 +#define EGL_D3D9_DEVICE_ANGLE 0x33A0 +#define EGL_D3D11_DEVICE_ANGLE 0x33A1 +#endif /* EGL_ANGLE_device_d3d */ + +#ifndef EGL_ANGLE_query_surface_pointer +#define EGL_ANGLE_query_surface_pointer 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSURFACEPOINTERANGLEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQuerySurfacePointerANGLE (EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value); +#endif +#endif /* EGL_ANGLE_query_surface_pointer */ + +#ifndef EGL_ANGLE_surface_d3d_texture_2d_share_handle +#define EGL_ANGLE_surface_d3d_texture_2d_share_handle 1 +#endif /* EGL_ANGLE_surface_d3d_texture_2d_share_handle */ + +#ifndef EGL_ANGLE_sync_control_rate +#define EGL_ANGLE_sync_control_rate 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETMSCRATEANGLEPROC) (EGLDisplay dpy, EGLSurface surface, EGLint *numerator, EGLint *denominator); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglGetMscRateANGLE (EGLDisplay dpy, EGLSurface surface, EGLint *numerator, EGLint *denominator); +#endif +#endif /* EGL_ANGLE_sync_control_rate */ + +#ifndef EGL_ANGLE_window_fixed_size +#define EGL_ANGLE_window_fixed_size 1 +#define EGL_FIXED_SIZE_ANGLE 0x3201 +#endif /* EGL_ANGLE_window_fixed_size */ + +#ifndef EGL_ARM_image_format +#define EGL_ARM_image_format 1 +#define EGL_COLOR_COMPONENT_TYPE_UNSIGNED_INTEGER_ARM 0x3287 +#define EGL_COLOR_COMPONENT_TYPE_INTEGER_ARM 0x3288 +#endif /* EGL_ARM_image_format */ + +#ifndef EGL_ARM_implicit_external_sync +#define EGL_ARM_implicit_external_sync 1 +#define EGL_SYNC_PRIOR_COMMANDS_IMPLICIT_EXTERNAL_ARM 0x328A +#endif /* EGL_ARM_implicit_external_sync */ + +#ifndef EGL_ARM_pixmap_multisample_discard +#define EGL_ARM_pixmap_multisample_discard 1 +#define EGL_DISCARD_SAMPLES_ARM 0x3286 +#endif /* EGL_ARM_pixmap_multisample_discard */ + +#ifndef EGL_EXT_bind_to_front +#define EGL_EXT_bind_to_front 1 +#define EGL_FRONT_BUFFER_EXT 0x3464 +#endif /* EGL_EXT_bind_to_front */ + +#ifndef EGL_EXT_buffer_age +#define EGL_EXT_buffer_age 1 +#define EGL_BUFFER_AGE_EXT 0x313D +#endif /* EGL_EXT_buffer_age */ + +#ifndef EGL_EXT_client_extensions +#define EGL_EXT_client_extensions 1 +#endif /* EGL_EXT_client_extensions */ + +#ifndef EGL_EXT_client_sync +#define EGL_EXT_client_sync 1 +#define EGL_SYNC_CLIENT_EXT 0x3364 +#define EGL_SYNC_CLIENT_SIGNAL_EXT 0x3365 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCLIENTSIGNALSYNCEXTPROC) (EGLDisplay dpy, EGLSync sync, const EGLAttrib *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglClientSignalSyncEXT (EGLDisplay dpy, EGLSync sync, const EGLAttrib *attrib_list); +#endif +#endif /* EGL_EXT_client_sync */ + +#ifndef EGL_EXT_compositor +#define EGL_EXT_compositor 1 +#define EGL_PRIMARY_COMPOSITOR_CONTEXT_EXT 0x3460 +#define EGL_EXTERNAL_REF_ID_EXT 0x3461 +#define EGL_COMPOSITOR_DROP_NEWEST_FRAME_EXT 0x3462 +#define EGL_COMPOSITOR_KEEP_NEWEST_FRAME_EXT 0x3463 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETCONTEXTLISTEXTPROC) (const EGLint *external_ref_ids, EGLint num_entries); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETCONTEXTATTRIBUTESEXTPROC) (EGLint external_ref_id, const EGLint *context_attributes, EGLint num_entries); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETWINDOWLISTEXTPROC) (EGLint external_ref_id, const EGLint *external_win_ids, EGLint num_entries); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETWINDOWATTRIBUTESEXTPROC) (EGLint external_win_id, const EGLint *window_attributes, EGLint num_entries); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORBINDTEXWINDOWEXTPROC) (EGLint external_win_id); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSETSIZEEXTPROC) (EGLint external_win_id, EGLint width, EGLint height); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLCOMPOSITORSWAPPOLICYEXTPROC) (EGLint external_win_id, EGLint policy); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetContextListEXT (const EGLint *external_ref_ids, EGLint num_entries); +EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetContextAttributesEXT (EGLint external_ref_id, const EGLint *context_attributes, EGLint num_entries); +EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetWindowListEXT (EGLint external_ref_id, const EGLint *external_win_ids, EGLint num_entries); +EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetWindowAttributesEXT (EGLint external_win_id, const EGLint *window_attributes, EGLint num_entries); +EGLAPI EGLBoolean EGLAPIENTRY eglCompositorBindTexWindowEXT (EGLint external_win_id); +EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSetSizeEXT (EGLint external_win_id, EGLint width, EGLint height); +EGLAPI EGLBoolean EGLAPIENTRY eglCompositorSwapPolicyEXT (EGLint external_win_id, EGLint policy); +#endif +#endif /* EGL_EXT_compositor */ + +#ifndef EGL_EXT_config_select_group +#define EGL_EXT_config_select_group 1 +#define EGL_CONFIG_SELECT_GROUP_EXT 0x34C0 +#endif /* EGL_EXT_config_select_group */ + +#ifndef EGL_EXT_create_context_robustness +#define EGL_EXT_create_context_robustness 1 +#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT 0x30BF +#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT 0x3138 +#define EGL_NO_RESET_NOTIFICATION_EXT 0x31BE +#define EGL_LOSE_CONTEXT_ON_RESET_EXT 0x31BF +#endif /* EGL_EXT_create_context_robustness */ + +#ifndef EGL_EXT_device_base +#define EGL_EXT_device_base 1 +typedef void *EGLDeviceEXT; +#define EGL_NO_DEVICE_EXT EGL_CAST(EGLDeviceEXT,0) +#define EGL_BAD_DEVICE_EXT 0x322B +#define EGL_DEVICE_EXT 0x322C +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEVICEATTRIBEXTPROC) (EGLDeviceEXT device, EGLint attribute, EGLAttrib *value); +typedef const char *(EGLAPIENTRYP PFNEGLQUERYDEVICESTRINGEXTPROC) (EGLDeviceEXT device, EGLint name); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEVICESEXTPROC) (EGLint max_devices, EGLDeviceEXT *devices, EGLint *num_devices); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDISPLAYATTRIBEXTPROC) (EGLDisplay dpy, EGLint attribute, EGLAttrib *value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDeviceAttribEXT (EGLDeviceEXT device, EGLint attribute, EGLAttrib *value); +EGLAPI const char *EGLAPIENTRY eglQueryDeviceStringEXT (EGLDeviceEXT device, EGLint name); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDevicesEXT (EGLint max_devices, EGLDeviceEXT *devices, EGLint *num_devices); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribEXT (EGLDisplay dpy, EGLint attribute, EGLAttrib *value); +#endif +#endif /* EGL_EXT_device_base */ + +#ifndef EGL_EXT_device_drm +#define EGL_EXT_device_drm 1 +#define EGL_DRM_DEVICE_FILE_EXT 0x3233 +#define EGL_DRM_MASTER_FD_EXT 0x333C +#endif /* EGL_EXT_device_drm */ + +#ifndef EGL_EXT_device_drm_render_node +#define EGL_EXT_device_drm_render_node 1 +#define EGL_DRM_RENDER_NODE_FILE_EXT 0x3377 +#endif /* EGL_EXT_device_drm_render_node */ + +#ifndef EGL_EXT_device_enumeration +#define EGL_EXT_device_enumeration 1 +#endif /* EGL_EXT_device_enumeration */ + +#ifndef EGL_EXT_device_openwf +#define EGL_EXT_device_openwf 1 +#define EGL_OPENWF_DEVICE_ID_EXT 0x3237 +#define EGL_OPENWF_DEVICE_EXT 0x333D +#endif /* EGL_EXT_device_openwf */ + +#ifndef EGL_EXT_device_persistent_id +#define EGL_EXT_device_persistent_id 1 +#define EGL_DEVICE_UUID_EXT 0x335C +#define EGL_DRIVER_UUID_EXT 0x335D +#define EGL_DRIVER_NAME_EXT 0x335E +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDEVICEBINARYEXTPROC) (EGLDeviceEXT device, EGLint name, EGLint max_size, void *value, EGLint *size); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDeviceBinaryEXT (EGLDeviceEXT device, EGLint name, EGLint max_size, void *value, EGLint *size); +#endif +#endif /* EGL_EXT_device_persistent_id */ + +#ifndef EGL_EXT_device_query +#define EGL_EXT_device_query 1 +#endif /* EGL_EXT_device_query */ + +#ifndef EGL_EXT_device_query_name +#define EGL_EXT_device_query_name 1 +#define EGL_RENDERER_EXT 0x335F +#endif /* EGL_EXT_device_query_name */ + +#ifndef EGL_EXT_explicit_device +#define EGL_EXT_explicit_device 1 +#endif /* EGL_EXT_explicit_device */ + +#ifndef EGL_EXT_gl_colorspace_bt2020_linear +#define EGL_EXT_gl_colorspace_bt2020_linear 1 +#define EGL_GL_COLORSPACE_BT2020_LINEAR_EXT 0x333F +#endif /* EGL_EXT_gl_colorspace_bt2020_linear */ + +#ifndef EGL_EXT_gl_colorspace_bt2020_pq +#define EGL_EXT_gl_colorspace_bt2020_pq 1 +#define EGL_GL_COLORSPACE_BT2020_PQ_EXT 0x3340 +#endif /* EGL_EXT_gl_colorspace_bt2020_pq */ + +#ifndef EGL_EXT_gl_colorspace_display_p3 +#define EGL_EXT_gl_colorspace_display_p3 1 +#define EGL_GL_COLORSPACE_DISPLAY_P3_EXT 0x3363 +#endif /* EGL_EXT_gl_colorspace_display_p3 */ + +#ifndef EGL_EXT_gl_colorspace_display_p3_linear +#define EGL_EXT_gl_colorspace_display_p3_linear 1 +#define EGL_GL_COLORSPACE_DISPLAY_P3_LINEAR_EXT 0x3362 +#endif /* EGL_EXT_gl_colorspace_display_p3_linear */ + +#ifndef EGL_EXT_gl_colorspace_display_p3_passthrough +#define EGL_EXT_gl_colorspace_display_p3_passthrough 1 +#define EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT 0x3490 +#endif /* EGL_EXT_gl_colorspace_display_p3_passthrough */ + +#ifndef EGL_EXT_gl_colorspace_scrgb +#define EGL_EXT_gl_colorspace_scrgb 1 +#define EGL_GL_COLORSPACE_SCRGB_EXT 0x3351 +#endif /* EGL_EXT_gl_colorspace_scrgb */ + +#ifndef EGL_EXT_gl_colorspace_scrgb_linear +#define EGL_EXT_gl_colorspace_scrgb_linear 1 +#define EGL_GL_COLORSPACE_SCRGB_LINEAR_EXT 0x3350 +#endif /* EGL_EXT_gl_colorspace_scrgb_linear */ + +#ifndef EGL_EXT_image_dma_buf_import +#define EGL_EXT_image_dma_buf_import 1 +#define EGL_LINUX_DMA_BUF_EXT 0x3270 +#define EGL_LINUX_DRM_FOURCC_EXT 0x3271 +#define EGL_DMA_BUF_PLANE0_FD_EXT 0x3272 +#define EGL_DMA_BUF_PLANE0_OFFSET_EXT 0x3273 +#define EGL_DMA_BUF_PLANE0_PITCH_EXT 0x3274 +#define EGL_DMA_BUF_PLANE1_FD_EXT 0x3275 +#define EGL_DMA_BUF_PLANE1_OFFSET_EXT 0x3276 +#define EGL_DMA_BUF_PLANE1_PITCH_EXT 0x3277 +#define EGL_DMA_BUF_PLANE2_FD_EXT 0x3278 +#define EGL_DMA_BUF_PLANE2_OFFSET_EXT 0x3279 +#define EGL_DMA_BUF_PLANE2_PITCH_EXT 0x327A +#define EGL_YUV_COLOR_SPACE_HINT_EXT 0x327B +#define EGL_SAMPLE_RANGE_HINT_EXT 0x327C +#define EGL_YUV_CHROMA_HORIZONTAL_SITING_HINT_EXT 0x327D +#define EGL_YUV_CHROMA_VERTICAL_SITING_HINT_EXT 0x327E +#define EGL_ITU_REC601_EXT 0x327F +#define EGL_ITU_REC709_EXT 0x3280 +#define EGL_ITU_REC2020_EXT 0x3281 +#define EGL_YUV_FULL_RANGE_EXT 0x3282 +#define EGL_YUV_NARROW_RANGE_EXT 0x3283 +#define EGL_YUV_CHROMA_SITING_0_EXT 0x3284 +#define EGL_YUV_CHROMA_SITING_0_5_EXT 0x3285 +#endif /* EGL_EXT_image_dma_buf_import */ + +#ifndef EGL_EXT_image_dma_buf_import_modifiers +#define EGL_EXT_image_dma_buf_import_modifiers 1 +#define EGL_DMA_BUF_PLANE3_FD_EXT 0x3440 +#define EGL_DMA_BUF_PLANE3_OFFSET_EXT 0x3441 +#define EGL_DMA_BUF_PLANE3_PITCH_EXT 0x3442 +#define EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT 0x3443 +#define EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT 0x3444 +#define EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT 0x3445 +#define EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT 0x3446 +#define EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT 0x3447 +#define EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT 0x3448 +#define EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT 0x3449 +#define EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT 0x344A +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDMABUFFORMATSEXTPROC) (EGLDisplay dpy, EGLint max_formats, EGLint *formats, EGLint *num_formats); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDMABUFMODIFIERSEXTPROC) (EGLDisplay dpy, EGLint format, EGLint max_modifiers, EGLuint64KHR *modifiers, EGLBoolean *external_only, EGLint *num_modifiers); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDmaBufFormatsEXT (EGLDisplay dpy, EGLint max_formats, EGLint *formats, EGLint *num_formats); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDmaBufModifiersEXT (EGLDisplay dpy, EGLint format, EGLint max_modifiers, EGLuint64KHR *modifiers, EGLBoolean *external_only, EGLint *num_modifiers); +#endif +#endif /* EGL_EXT_image_dma_buf_import_modifiers */ + +#ifndef EGL_EXT_image_gl_colorspace +#define EGL_EXT_image_gl_colorspace 1 +#define EGL_GL_COLORSPACE_DEFAULT_EXT 0x314D +#endif /* EGL_EXT_image_gl_colorspace */ + +#ifndef EGL_EXT_image_implicit_sync_control +#define EGL_EXT_image_implicit_sync_control 1 +#define EGL_IMPORT_SYNC_TYPE_EXT 0x3470 +#define EGL_IMPORT_IMPLICIT_SYNC_EXT 0x3471 +#define EGL_IMPORT_EXPLICIT_SYNC_EXT 0x3472 +#endif /* EGL_EXT_image_implicit_sync_control */ + +#ifndef EGL_EXT_multiview_window +#define EGL_EXT_multiview_window 1 +#define EGL_MULTIVIEW_VIEW_COUNT_EXT 0x3134 +#endif /* EGL_EXT_multiview_window */ + +#ifndef EGL_EXT_output_base +#define EGL_EXT_output_base 1 +typedef void *EGLOutputLayerEXT; +typedef void *EGLOutputPortEXT; +#define EGL_NO_OUTPUT_LAYER_EXT EGL_CAST(EGLOutputLayerEXT,0) +#define EGL_NO_OUTPUT_PORT_EXT EGL_CAST(EGLOutputPortEXT,0) +#define EGL_BAD_OUTPUT_LAYER_EXT 0x322D +#define EGL_BAD_OUTPUT_PORT_EXT 0x322E +#define EGL_SWAP_INTERVAL_EXT 0x322F +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETOUTPUTLAYERSEXTPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputLayerEXT *layers, EGLint max_layers, EGLint *num_layers); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETOUTPUTPORTSEXTPROC) (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputPortEXT *ports, EGLint max_ports, EGLint *num_ports); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLOUTPUTLAYERATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYOUTPUTLAYERATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib *value); +typedef const char *(EGLAPIENTRYP PFNEGLQUERYOUTPUTLAYERSTRINGEXTPROC) (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint name); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLOUTPUTPORTATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYOUTPUTPORTATTRIBEXTPROC) (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib *value); +typedef const char *(EGLAPIENTRYP PFNEGLQUERYOUTPUTPORTSTRINGEXTPROC) (EGLDisplay dpy, EGLOutputPortEXT port, EGLint name); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglGetOutputLayersEXT (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputLayerEXT *layers, EGLint max_layers, EGLint *num_layers); +EGLAPI EGLBoolean EGLAPIENTRY eglGetOutputPortsEXT (EGLDisplay dpy, const EGLAttrib *attrib_list, EGLOutputPortEXT *ports, EGLint max_ports, EGLint *num_ports); +EGLAPI EGLBoolean EGLAPIENTRY eglOutputLayerAttribEXT (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib value); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryOutputLayerAttribEXT (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint attribute, EGLAttrib *value); +EGLAPI const char *EGLAPIENTRY eglQueryOutputLayerStringEXT (EGLDisplay dpy, EGLOutputLayerEXT layer, EGLint name); +EGLAPI EGLBoolean EGLAPIENTRY eglOutputPortAttribEXT (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib value); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryOutputPortAttribEXT (EGLDisplay dpy, EGLOutputPortEXT port, EGLint attribute, EGLAttrib *value); +EGLAPI const char *EGLAPIENTRY eglQueryOutputPortStringEXT (EGLDisplay dpy, EGLOutputPortEXT port, EGLint name); +#endif +#endif /* EGL_EXT_output_base */ + +#ifndef EGL_EXT_output_drm +#define EGL_EXT_output_drm 1 +#define EGL_DRM_CRTC_EXT 0x3234 +#define EGL_DRM_PLANE_EXT 0x3235 +#define EGL_DRM_CONNECTOR_EXT 0x3236 +#endif /* EGL_EXT_output_drm */ + +#ifndef EGL_EXT_output_openwf +#define EGL_EXT_output_openwf 1 +#define EGL_OPENWF_PIPELINE_ID_EXT 0x3238 +#define EGL_OPENWF_PORT_ID_EXT 0x3239 +#endif /* EGL_EXT_output_openwf */ + +#ifndef EGL_EXT_pixel_format_float +#define EGL_EXT_pixel_format_float 1 +#define EGL_COLOR_COMPONENT_TYPE_EXT 0x3339 +#define EGL_COLOR_COMPONENT_TYPE_FIXED_EXT 0x333A +#define EGL_COLOR_COMPONENT_TYPE_FLOAT_EXT 0x333B +#endif /* EGL_EXT_pixel_format_float */ + +#ifndef EGL_EXT_platform_base +#define EGL_EXT_platform_base 1 +typedef EGLDisplay (EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYEXTPROC) (EGLenum platform, void *native_display, const EGLint *attrib_list); +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC) (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLint *attrib_list); +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPLATFORMPIXMAPSURFACEEXTPROC) (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLint *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLDisplay EGLAPIENTRY eglGetPlatformDisplayEXT (EGLenum platform, void *native_display, const EGLint *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformWindowSurfaceEXT (EGLDisplay dpy, EGLConfig config, void *native_window, const EGLint *attrib_list); +EGLAPI EGLSurface EGLAPIENTRY eglCreatePlatformPixmapSurfaceEXT (EGLDisplay dpy, EGLConfig config, void *native_pixmap, const EGLint *attrib_list); +#endif +#endif /* EGL_EXT_platform_base */ + +#ifndef EGL_EXT_platform_device +#define EGL_EXT_platform_device 1 +#define EGL_PLATFORM_DEVICE_EXT 0x313F +#endif /* EGL_EXT_platform_device */ + +#ifndef EGL_EXT_platform_wayland +#define EGL_EXT_platform_wayland 1 +#define EGL_PLATFORM_WAYLAND_EXT 0x31D8 +#endif /* EGL_EXT_platform_wayland */ + +#ifndef EGL_EXT_platform_x11 +#define EGL_EXT_platform_x11 1 +#define EGL_PLATFORM_X11_EXT 0x31D5 +#define EGL_PLATFORM_X11_SCREEN_EXT 0x31D6 +#endif /* EGL_EXT_platform_x11 */ + +#ifndef EGL_EXT_platform_xcb +#define EGL_EXT_platform_xcb 1 +#define EGL_PLATFORM_XCB_EXT 0x31DC +#define EGL_PLATFORM_XCB_SCREEN_EXT 0x31DE +#endif /* EGL_EXT_platform_xcb */ + +#ifndef EGL_EXT_present_opaque +#define EGL_EXT_present_opaque 1 +#define EGL_PRESENT_OPAQUE_EXT 0x31DF +#endif /* EGL_EXT_present_opaque */ + +#ifndef EGL_EXT_protected_content +#define EGL_EXT_protected_content 1 +#define EGL_PROTECTED_CONTENT_EXT 0x32C0 +#endif /* EGL_EXT_protected_content */ + +#ifndef EGL_EXT_protected_surface +#define EGL_EXT_protected_surface 1 +#endif /* EGL_EXT_protected_surface */ + +#ifndef EGL_EXT_stream_consumer_egloutput +#define EGL_EXT_stream_consumer_egloutput 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMEROUTPUTEXTPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLOutputLayerEXT layer); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerOutputEXT (EGLDisplay dpy, EGLStreamKHR stream, EGLOutputLayerEXT layer); +#endif +#endif /* EGL_EXT_stream_consumer_egloutput */ + +#ifndef EGL_EXT_surface_CTA861_3_metadata +#define EGL_EXT_surface_CTA861_3_metadata 1 +#define EGL_CTA861_3_MAX_CONTENT_LIGHT_LEVEL_EXT 0x3360 +#define EGL_CTA861_3_MAX_FRAME_AVERAGE_LEVEL_EXT 0x3361 +#endif /* EGL_EXT_surface_CTA861_3_metadata */ + +#ifndef EGL_EXT_surface_SMPTE2086_metadata +#define EGL_EXT_surface_SMPTE2086_metadata 1 +#define EGL_SMPTE2086_DISPLAY_PRIMARY_RX_EXT 0x3341 +#define EGL_SMPTE2086_DISPLAY_PRIMARY_RY_EXT 0x3342 +#define EGL_SMPTE2086_DISPLAY_PRIMARY_GX_EXT 0x3343 +#define EGL_SMPTE2086_DISPLAY_PRIMARY_GY_EXT 0x3344 +#define EGL_SMPTE2086_DISPLAY_PRIMARY_BX_EXT 0x3345 +#define EGL_SMPTE2086_DISPLAY_PRIMARY_BY_EXT 0x3346 +#define EGL_SMPTE2086_WHITE_POINT_X_EXT 0x3347 +#define EGL_SMPTE2086_WHITE_POINT_Y_EXT 0x3348 +#define EGL_SMPTE2086_MAX_LUMINANCE_EXT 0x3349 +#define EGL_SMPTE2086_MIN_LUMINANCE_EXT 0x334A +#define EGL_METADATA_SCALING_EXT 50000 +#endif /* EGL_EXT_surface_SMPTE2086_metadata */ + +#ifndef EGL_EXT_surface_compression +#define EGL_EXT_surface_compression 1 +#define EGL_SURFACE_COMPRESSION_EXT 0x34B0 +#define EGL_SURFACE_COMPRESSION_PLANE1_EXT 0x328E +#define EGL_SURFACE_COMPRESSION_PLANE2_EXT 0x328F +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_NONE_EXT 0x34B1 +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_DEFAULT_EXT 0x34B2 +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_1BPC_EXT 0x34B4 +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_2BPC_EXT 0x34B5 +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_3BPC_EXT 0x34B6 +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_4BPC_EXT 0x34B7 +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_5BPC_EXT 0x34B8 +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_6BPC_EXT 0x34B9 +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_7BPC_EXT 0x34BA +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_8BPC_EXT 0x34BB +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_9BPC_EXT 0x34BC +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_10BPC_EXT 0x34BD +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_11BPC_EXT 0x34BE +#define EGL_SURFACE_COMPRESSION_FIXED_RATE_12BPC_EXT 0x34BF +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSUPPORTEDCOMPRESSIONRATESEXTPROC) (EGLDisplay dpy, EGLConfig config, const EGLAttrib *attrib_list, EGLint *rates, EGLint rate_size, EGLint *num_rates); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQuerySupportedCompressionRatesEXT (EGLDisplay dpy, EGLConfig config, const EGLAttrib *attrib_list, EGLint *rates, EGLint rate_size, EGLint *num_rates); +#endif +#endif /* EGL_EXT_surface_compression */ + +#ifndef EGL_EXT_swap_buffers_with_damage +#define EGL_EXT_swap_buffers_with_damage 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC) (EGLDisplay dpy, EGLSurface surface, const EGLint *rects, EGLint n_rects); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersWithDamageEXT (EGLDisplay dpy, EGLSurface surface, const EGLint *rects, EGLint n_rects); +#endif +#endif /* EGL_EXT_swap_buffers_with_damage */ + +#ifndef EGL_EXT_sync_reuse +#define EGL_EXT_sync_reuse 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNSIGNALSYNCEXTPROC) (EGLDisplay dpy, EGLSync sync, const EGLAttrib *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglUnsignalSyncEXT (EGLDisplay dpy, EGLSync sync, const EGLAttrib *attrib_list); +#endif +#endif /* EGL_EXT_sync_reuse */ + +#ifndef EGL_EXT_yuv_surface +#define EGL_EXT_yuv_surface 1 +#define EGL_YUV_ORDER_EXT 0x3301 +#define EGL_YUV_NUMBER_OF_PLANES_EXT 0x3311 +#define EGL_YUV_SUBSAMPLE_EXT 0x3312 +#define EGL_YUV_DEPTH_RANGE_EXT 0x3317 +#define EGL_YUV_CSC_STANDARD_EXT 0x330A +#define EGL_YUV_PLANE_BPP_EXT 0x331A +#define EGL_YUV_BUFFER_EXT 0x3300 +#define EGL_YUV_ORDER_YUV_EXT 0x3302 +#define EGL_YUV_ORDER_YVU_EXT 0x3303 +#define EGL_YUV_ORDER_YUYV_EXT 0x3304 +#define EGL_YUV_ORDER_UYVY_EXT 0x3305 +#define EGL_YUV_ORDER_YVYU_EXT 0x3306 +#define EGL_YUV_ORDER_VYUY_EXT 0x3307 +#define EGL_YUV_ORDER_AYUV_EXT 0x3308 +#define EGL_YUV_SUBSAMPLE_4_2_0_EXT 0x3313 +#define EGL_YUV_SUBSAMPLE_4_2_2_EXT 0x3314 +#define EGL_YUV_SUBSAMPLE_4_4_4_EXT 0x3315 +#define EGL_YUV_DEPTH_RANGE_LIMITED_EXT 0x3318 +#define EGL_YUV_DEPTH_RANGE_FULL_EXT 0x3319 +#define EGL_YUV_CSC_STANDARD_601_EXT 0x330B +#define EGL_YUV_CSC_STANDARD_709_EXT 0x330C +#define EGL_YUV_CSC_STANDARD_2020_EXT 0x330D +#define EGL_YUV_PLANE_BPP_0_EXT 0x331B +#define EGL_YUV_PLANE_BPP_8_EXT 0x331C +#define EGL_YUV_PLANE_BPP_10_EXT 0x331D +#endif /* EGL_EXT_yuv_surface */ + +#ifndef EGL_HI_clientpixmap +#define EGL_HI_clientpixmap 1 +struct EGLClientPixmapHI { + void *pData; + EGLint iWidth; + EGLint iHeight; + EGLint iStride; +}; +#define EGL_CLIENT_PIXMAP_POINTER_HI 0x8F74 +typedef EGLSurface (EGLAPIENTRYP PFNEGLCREATEPIXMAPSURFACEHIPROC) (EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI *pixmap); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLSurface EGLAPIENTRY eglCreatePixmapSurfaceHI (EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI *pixmap); +#endif +#endif /* EGL_HI_clientpixmap */ + +#ifndef EGL_HI_colorformats +#define EGL_HI_colorformats 1 +#define EGL_COLOR_FORMAT_HI 0x8F70 +#define EGL_COLOR_RGB_HI 0x8F71 +#define EGL_COLOR_RGBA_HI 0x8F72 +#define EGL_COLOR_ARGB_HI 0x8F73 +#endif /* EGL_HI_colorformats */ + +#ifndef EGL_IMG_context_priority +#define EGL_IMG_context_priority 1 +#define EGL_CONTEXT_PRIORITY_LEVEL_IMG 0x3100 +#define EGL_CONTEXT_PRIORITY_HIGH_IMG 0x3101 +#define EGL_CONTEXT_PRIORITY_MEDIUM_IMG 0x3102 +#define EGL_CONTEXT_PRIORITY_LOW_IMG 0x3103 +#endif /* EGL_IMG_context_priority */ + +#ifndef EGL_IMG_image_plane_attribs +#define EGL_IMG_image_plane_attribs 1 +#define EGL_NATIVE_BUFFER_MULTIPLANE_SEPARATE_IMG 0x3105 +#define EGL_NATIVE_BUFFER_PLANE_OFFSET_IMG 0x3106 +#endif /* EGL_IMG_image_plane_attribs */ + +#ifndef EGL_MESA_drm_image +#define EGL_MESA_drm_image 1 +#define EGL_DRM_BUFFER_FORMAT_MESA 0x31D0 +#define EGL_DRM_BUFFER_USE_MESA 0x31D1 +#define EGL_DRM_BUFFER_FORMAT_ARGB32_MESA 0x31D2 +#define EGL_DRM_BUFFER_MESA 0x31D3 +#define EGL_DRM_BUFFER_STRIDE_MESA 0x31D4 +#define EGL_DRM_BUFFER_USE_SCANOUT_MESA 0x00000001 +#define EGL_DRM_BUFFER_USE_SHARE_MESA 0x00000002 +#define EGL_DRM_BUFFER_USE_CURSOR_MESA 0x00000004 +typedef EGLImageKHR (EGLAPIENTRYP PFNEGLCREATEDRMIMAGEMESAPROC) (EGLDisplay dpy, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDRMIMAGEMESAPROC) (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLImageKHR EGLAPIENTRY eglCreateDRMImageMESA (EGLDisplay dpy, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglExportDRMImageMESA (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride); +#endif +#endif /* EGL_MESA_drm_image */ + +#ifndef EGL_MESA_image_dma_buf_export +#define EGL_MESA_image_dma_buf_export 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDMABUFIMAGEQUERYMESAPROC) (EGLDisplay dpy, EGLImageKHR image, int *fourcc, int *num_planes, EGLuint64KHR *modifiers); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLEXPORTDMABUFIMAGEMESAPROC) (EGLDisplay dpy, EGLImageKHR image, int *fds, EGLint *strides, EGLint *offsets); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglExportDMABUFImageQueryMESA (EGLDisplay dpy, EGLImageKHR image, int *fourcc, int *num_planes, EGLuint64KHR *modifiers); +EGLAPI EGLBoolean EGLAPIENTRY eglExportDMABUFImageMESA (EGLDisplay dpy, EGLImageKHR image, int *fds, EGLint *strides, EGLint *offsets); +#endif +#endif /* EGL_MESA_image_dma_buf_export */ + +#ifndef EGL_MESA_platform_gbm +#define EGL_MESA_platform_gbm 1 +#define EGL_PLATFORM_GBM_MESA 0x31D7 +#endif /* EGL_MESA_platform_gbm */ + +#ifndef EGL_MESA_platform_surfaceless +#define EGL_MESA_platform_surfaceless 1 +#define EGL_PLATFORM_SURFACELESS_MESA 0x31DD +#endif /* EGL_MESA_platform_surfaceless */ + +#ifndef EGL_MESA_query_driver +#define EGL_MESA_query_driver 1 +typedef char *(EGLAPIENTRYP PFNEGLGETDISPLAYDRIVERCONFIGPROC) (EGLDisplay dpy); +typedef const char *(EGLAPIENTRYP PFNEGLGETDISPLAYDRIVERNAMEPROC) (EGLDisplay dpy); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI char *EGLAPIENTRY eglGetDisplayDriverConfig (EGLDisplay dpy); +EGLAPI const char *EGLAPIENTRY eglGetDisplayDriverName (EGLDisplay dpy); +#endif +#endif /* EGL_MESA_query_driver */ + +#ifndef EGL_NOK_swap_region +#define EGL_NOK_swap_region 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSREGIONNOKPROC) (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersRegionNOK (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects); +#endif +#endif /* EGL_NOK_swap_region */ + +#ifndef EGL_NOK_swap_region2 +#define EGL_NOK_swap_region2 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSWAPBUFFERSREGION2NOKPROC) (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglSwapBuffersRegion2NOK (EGLDisplay dpy, EGLSurface surface, EGLint numRects, const EGLint *rects); +#endif +#endif /* EGL_NOK_swap_region2 */ + +#ifndef EGL_NOK_texture_from_pixmap +#define EGL_NOK_texture_from_pixmap 1 +#define EGL_Y_INVERTED_NOK 0x307F +#endif /* EGL_NOK_texture_from_pixmap */ + +#ifndef EGL_NV_3dvision_surface +#define EGL_NV_3dvision_surface 1 +#define EGL_AUTO_STEREO_NV 0x3136 +#endif /* EGL_NV_3dvision_surface */ + +#ifndef EGL_NV_context_priority_realtime +#define EGL_NV_context_priority_realtime 1 +#define EGL_CONTEXT_PRIORITY_REALTIME_NV 0x3357 +#endif /* EGL_NV_context_priority_realtime */ + +#ifndef EGL_NV_coverage_sample +#define EGL_NV_coverage_sample 1 +#define EGL_COVERAGE_BUFFERS_NV 0x30E0 +#define EGL_COVERAGE_SAMPLES_NV 0x30E1 +#endif /* EGL_NV_coverage_sample */ + +#ifndef EGL_NV_coverage_sample_resolve +#define EGL_NV_coverage_sample_resolve 1 +#define EGL_COVERAGE_SAMPLE_RESOLVE_NV 0x3131 +#define EGL_COVERAGE_SAMPLE_RESOLVE_DEFAULT_NV 0x3132 +#define EGL_COVERAGE_SAMPLE_RESOLVE_NONE_NV 0x3133 +#endif /* EGL_NV_coverage_sample_resolve */ + +#ifndef EGL_NV_cuda_event +#define EGL_NV_cuda_event 1 +#define EGL_CUDA_EVENT_HANDLE_NV 0x323B +#define EGL_SYNC_CUDA_EVENT_NV 0x323C +#define EGL_SYNC_CUDA_EVENT_COMPLETE_NV 0x323D +#endif /* EGL_NV_cuda_event */ + +#ifndef EGL_NV_depth_nonlinear +#define EGL_NV_depth_nonlinear 1 +#define EGL_DEPTH_ENCODING_NV 0x30E2 +#define EGL_DEPTH_ENCODING_NONE_NV 0 +#define EGL_DEPTH_ENCODING_NONLINEAR_NV 0x30E3 +#endif /* EGL_NV_depth_nonlinear */ + +#ifndef EGL_NV_device_cuda +#define EGL_NV_device_cuda 1 +#define EGL_CUDA_DEVICE_NV 0x323A +#endif /* EGL_NV_device_cuda */ + +#ifndef EGL_NV_native_query +#define EGL_NV_native_query 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEDISPLAYNVPROC) (EGLDisplay dpy, EGLNativeDisplayType *display_id); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEWINDOWNVPROC) (EGLDisplay dpy, EGLSurface surf, EGLNativeWindowType *window); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYNATIVEPIXMAPNVPROC) (EGLDisplay dpy, EGLSurface surf, EGLNativePixmapType *pixmap); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativeDisplayNV (EGLDisplay dpy, EGLNativeDisplayType *display_id); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativeWindowNV (EGLDisplay dpy, EGLSurface surf, EGLNativeWindowType *window); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryNativePixmapNV (EGLDisplay dpy, EGLSurface surf, EGLNativePixmapType *pixmap); +#endif +#endif /* EGL_NV_native_query */ + +#ifndef EGL_NV_post_convert_rounding +#define EGL_NV_post_convert_rounding 1 +#endif /* EGL_NV_post_convert_rounding */ + +#ifndef EGL_NV_post_sub_buffer +#define EGL_NV_post_sub_buffer 1 +#define EGL_POST_SUB_BUFFER_SUPPORTED_NV 0x30BE +typedef EGLBoolean (EGLAPIENTRYP PFNEGLPOSTSUBBUFFERNVPROC) (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglPostSubBufferNV (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height); +#endif +#endif /* EGL_NV_post_sub_buffer */ + +#ifndef EGL_NV_quadruple_buffer +#define EGL_NV_quadruple_buffer 1 +#define EGL_QUADRUPLE_BUFFER_NV 0x3231 +#endif /* EGL_NV_quadruple_buffer */ + +#ifndef EGL_NV_robustness_video_memory_purge +#define EGL_NV_robustness_video_memory_purge 1 +#define EGL_GENERATE_RESET_ON_VIDEO_MEMORY_PURGE_NV 0x334C +#endif /* EGL_NV_robustness_video_memory_purge */ + +#ifndef EGL_NV_stream_consumer_eglimage +#define EGL_NV_stream_consumer_eglimage 1 +#define EGL_STREAM_CONSUMER_IMAGE_NV 0x3373 +#define EGL_STREAM_IMAGE_ADD_NV 0x3374 +#define EGL_STREAM_IMAGE_REMOVE_NV 0x3375 +#define EGL_STREAM_IMAGE_AVAILABLE_NV 0x3376 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMIMAGECONSUMERCONNECTNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLint num_modifiers, const EGLuint64KHR *modifiers, const EGLAttrib *attrib_list); +typedef EGLint (EGLAPIENTRYP PFNEGLQUERYSTREAMCONSUMEREVENTNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLTime timeout, EGLenum *event, EGLAttrib *aux); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMACQUIREIMAGENVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLImage *pImage, EGLSync sync); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMRELEASEIMAGENVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLImage image, EGLSync sync); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglStreamImageConsumerConnectNV (EGLDisplay dpy, EGLStreamKHR stream, EGLint num_modifiers, const EGLuint64KHR *modifiers, const EGLAttrib *attrib_list); +EGLAPI EGLint EGLAPIENTRY eglQueryStreamConsumerEventNV (EGLDisplay dpy, EGLStreamKHR stream, EGLTime timeout, EGLenum *event, EGLAttrib *aux); +EGLAPI EGLBoolean EGLAPIENTRY eglStreamAcquireImageNV (EGLDisplay dpy, EGLStreamKHR stream, EGLImage *pImage, EGLSync sync); +EGLAPI EGLBoolean EGLAPIENTRY eglStreamReleaseImageNV (EGLDisplay dpy, EGLStreamKHR stream, EGLImage image, EGLSync sync); +#endif +#endif /* EGL_NV_stream_consumer_eglimage */ + +#ifndef EGL_NV_stream_consumer_gltexture_yuv +#define EGL_NV_stream_consumer_gltexture_yuv 1 +#define EGL_YUV_PLANE0_TEXTURE_UNIT_NV 0x332C +#define EGL_YUV_PLANE1_TEXTURE_UNIT_NV 0x332D +#define EGL_YUV_PLANE2_TEXTURE_UNIT_NV 0x332E +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMCONSUMERGLTEXTUREEXTERNALATTRIBSNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglStreamConsumerGLTextureExternalAttribsNV (EGLDisplay dpy, EGLStreamKHR stream, const EGLAttrib *attrib_list); +#endif +#endif /* EGL_NV_stream_consumer_gltexture_yuv */ + +#ifndef EGL_NV_stream_cross_display +#define EGL_NV_stream_cross_display 1 +#define EGL_STREAM_CROSS_DISPLAY_NV 0x334E +#endif /* EGL_NV_stream_cross_display */ + +#ifndef EGL_NV_stream_cross_object +#define EGL_NV_stream_cross_object 1 +#define EGL_STREAM_CROSS_OBJECT_NV 0x334D +#endif /* EGL_NV_stream_cross_object */ + +#ifndef EGL_NV_stream_cross_partition +#define EGL_NV_stream_cross_partition 1 +#define EGL_STREAM_CROSS_PARTITION_NV 0x323F +#endif /* EGL_NV_stream_cross_partition */ + +#ifndef EGL_NV_stream_cross_process +#define EGL_NV_stream_cross_process 1 +#define EGL_STREAM_CROSS_PROCESS_NV 0x3245 +#endif /* EGL_NV_stream_cross_process */ + +#ifndef EGL_NV_stream_cross_system +#define EGL_NV_stream_cross_system 1 +#define EGL_STREAM_CROSS_SYSTEM_NV 0x334F +#endif /* EGL_NV_stream_cross_system */ + +#ifndef EGL_NV_stream_dma +#define EGL_NV_stream_dma 1 +#define EGL_STREAM_DMA_NV 0x3371 +#define EGL_STREAM_DMA_SERVER_NV 0x3372 +#endif /* EGL_NV_stream_dma */ + +#ifndef EGL_NV_stream_fifo_next +#define EGL_NV_stream_fifo_next 1 +#define EGL_PENDING_FRAME_NV 0x3329 +#define EGL_STREAM_TIME_PENDING_NV 0x332A +#endif /* EGL_NV_stream_fifo_next */ + +#ifndef EGL_NV_stream_fifo_synchronous +#define EGL_NV_stream_fifo_synchronous 1 +#define EGL_STREAM_FIFO_SYNCHRONOUS_NV 0x3336 +#endif /* EGL_NV_stream_fifo_synchronous */ + +#ifndef EGL_NV_stream_flush +#define EGL_NV_stream_flush 1 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSTREAMFLUSHNVPROC) (EGLDisplay dpy, EGLStreamKHR stream); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglStreamFlushNV (EGLDisplay dpy, EGLStreamKHR stream); +#endif +#endif /* EGL_NV_stream_flush */ + +#ifndef EGL_NV_stream_frame_limits +#define EGL_NV_stream_frame_limits 1 +#define EGL_PRODUCER_MAX_FRAME_HINT_NV 0x3337 +#define EGL_CONSUMER_MAX_FRAME_HINT_NV 0x3338 +#endif /* EGL_NV_stream_frame_limits */ + +#ifndef EGL_NV_stream_metadata +#define EGL_NV_stream_metadata 1 +#define EGL_MAX_STREAM_METADATA_BLOCKS_NV 0x3250 +#define EGL_MAX_STREAM_METADATA_BLOCK_SIZE_NV 0x3251 +#define EGL_MAX_STREAM_METADATA_TOTAL_SIZE_NV 0x3252 +#define EGL_PRODUCER_METADATA_NV 0x3253 +#define EGL_CONSUMER_METADATA_NV 0x3254 +#define EGL_PENDING_METADATA_NV 0x3328 +#define EGL_METADATA0_SIZE_NV 0x3255 +#define EGL_METADATA1_SIZE_NV 0x3256 +#define EGL_METADATA2_SIZE_NV 0x3257 +#define EGL_METADATA3_SIZE_NV 0x3258 +#define EGL_METADATA0_TYPE_NV 0x3259 +#define EGL_METADATA1_TYPE_NV 0x325A +#define EGL_METADATA2_TYPE_NV 0x325B +#define EGL_METADATA3_TYPE_NV 0x325C +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYDISPLAYATTRIBNVPROC) (EGLDisplay dpy, EGLint attribute, EGLAttrib *value); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSETSTREAMMETADATANVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLint n, EGLint offset, EGLint size, const void *data); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYSTREAMMETADATANVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum name, EGLint n, EGLint offset, EGLint size, void *data); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglQueryDisplayAttribNV (EGLDisplay dpy, EGLint attribute, EGLAttrib *value); +EGLAPI EGLBoolean EGLAPIENTRY eglSetStreamMetadataNV (EGLDisplay dpy, EGLStreamKHR stream, EGLint n, EGLint offset, EGLint size, const void *data); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryStreamMetadataNV (EGLDisplay dpy, EGLStreamKHR stream, EGLenum name, EGLint n, EGLint offset, EGLint size, void *data); +#endif +#endif /* EGL_NV_stream_metadata */ + +#ifndef EGL_NV_stream_origin +#define EGL_NV_stream_origin 1 +#define EGL_STREAM_FRAME_ORIGIN_X_NV 0x3366 +#define EGL_STREAM_FRAME_ORIGIN_Y_NV 0x3367 +#define EGL_STREAM_FRAME_MAJOR_AXIS_NV 0x3368 +#define EGL_CONSUMER_AUTO_ORIENTATION_NV 0x3369 +#define EGL_PRODUCER_AUTO_ORIENTATION_NV 0x336A +#define EGL_LEFT_NV 0x336B +#define EGL_RIGHT_NV 0x336C +#define EGL_TOP_NV 0x336D +#define EGL_BOTTOM_NV 0x336E +#define EGL_X_AXIS_NV 0x336F +#define EGL_Y_AXIS_NV 0x3370 +#endif /* EGL_NV_stream_origin */ + +#ifndef EGL_NV_stream_remote +#define EGL_NV_stream_remote 1 +#define EGL_STREAM_STATE_INITIALIZING_NV 0x3240 +#define EGL_STREAM_TYPE_NV 0x3241 +#define EGL_STREAM_PROTOCOL_NV 0x3242 +#define EGL_STREAM_ENDPOINT_NV 0x3243 +#define EGL_STREAM_LOCAL_NV 0x3244 +#define EGL_STREAM_PRODUCER_NV 0x3247 +#define EGL_STREAM_CONSUMER_NV 0x3248 +#define EGL_STREAM_PROTOCOL_FD_NV 0x3246 +#endif /* EGL_NV_stream_remote */ + +#ifndef EGL_NV_stream_reset +#define EGL_NV_stream_reset 1 +#define EGL_SUPPORT_RESET_NV 0x3334 +#define EGL_SUPPORT_REUSE_NV 0x3335 +typedef EGLBoolean (EGLAPIENTRYP PFNEGLRESETSTREAMNVPROC) (EGLDisplay dpy, EGLStreamKHR stream); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglResetStreamNV (EGLDisplay dpy, EGLStreamKHR stream); +#endif +#endif /* EGL_NV_stream_reset */ + +#ifndef EGL_NV_stream_socket +#define EGL_NV_stream_socket 1 +#define EGL_STREAM_PROTOCOL_SOCKET_NV 0x324B +#define EGL_SOCKET_HANDLE_NV 0x324C +#define EGL_SOCKET_TYPE_NV 0x324D +#endif /* EGL_NV_stream_socket */ + +#ifndef EGL_NV_stream_socket_inet +#define EGL_NV_stream_socket_inet 1 +#define EGL_SOCKET_TYPE_INET_NV 0x324F +#endif /* EGL_NV_stream_socket_inet */ + +#ifndef EGL_NV_stream_socket_unix +#define EGL_NV_stream_socket_unix 1 +#define EGL_SOCKET_TYPE_UNIX_NV 0x324E +#endif /* EGL_NV_stream_socket_unix */ + +#ifndef EGL_NV_stream_sync +#define EGL_NV_stream_sync 1 +#define EGL_SYNC_NEW_FRAME_NV 0x321F +typedef EGLSyncKHR (EGLAPIENTRYP PFNEGLCREATESTREAMSYNCNVPROC) (EGLDisplay dpy, EGLStreamKHR stream, EGLenum type, const EGLint *attrib_list); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateStreamSyncNV (EGLDisplay dpy, EGLStreamKHR stream, EGLenum type, const EGLint *attrib_list); +#endif +#endif /* EGL_NV_stream_sync */ + +#ifndef EGL_NV_sync +#define EGL_NV_sync 1 +typedef void *EGLSyncNV; +typedef khronos_utime_nanoseconds_t EGLTimeNV; +#ifdef KHRONOS_SUPPORT_INT64 +#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_NV 0x30E6 +#define EGL_SYNC_STATUS_NV 0x30E7 +#define EGL_SIGNALED_NV 0x30E8 +#define EGL_UNSIGNALED_NV 0x30E9 +#define EGL_SYNC_FLUSH_COMMANDS_BIT_NV 0x0001 +#define EGL_FOREVER_NV 0xFFFFFFFFFFFFFFFFull +#define EGL_ALREADY_SIGNALED_NV 0x30EA +#define EGL_TIMEOUT_EXPIRED_NV 0x30EB +#define EGL_CONDITION_SATISFIED_NV 0x30EC +#define EGL_SYNC_TYPE_NV 0x30ED +#define EGL_SYNC_CONDITION_NV 0x30EE +#define EGL_SYNC_FENCE_NV 0x30EF +#define EGL_NO_SYNC_NV EGL_CAST(EGLSyncNV,0) +typedef EGLSyncNV (EGLAPIENTRYP PFNEGLCREATEFENCESYNCNVPROC) (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLDESTROYSYNCNVPROC) (EGLSyncNV sync); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLFENCENVPROC) (EGLSyncNV sync); +typedef EGLint (EGLAPIENTRYP PFNEGLCLIENTWAITSYNCNVPROC) (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLSIGNALSYNCNVPROC) (EGLSyncNV sync, EGLenum mode); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLGETSYNCATTRIBNVPROC) (EGLSyncNV sync, EGLint attribute, EGLint *value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLSyncNV EGLAPIENTRY eglCreateFenceSyncNV (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list); +EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncNV (EGLSyncNV sync); +EGLAPI EGLBoolean EGLAPIENTRY eglFenceNV (EGLSyncNV sync); +EGLAPI EGLint EGLAPIENTRY eglClientWaitSyncNV (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout); +EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncNV (EGLSyncNV sync, EGLenum mode); +EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttribNV (EGLSyncNV sync, EGLint attribute, EGLint *value); +#endif +#endif /* KHRONOS_SUPPORT_INT64 */ +#endif /* EGL_NV_sync */ + +#ifndef EGL_NV_system_time +#define EGL_NV_system_time 1 +typedef khronos_utime_nanoseconds_t EGLuint64NV; +#ifdef KHRONOS_SUPPORT_INT64 +typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC) (void); +typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMENVPROC) (void); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeFrequencyNV (void); +EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeNV (void); +#endif +#endif /* KHRONOS_SUPPORT_INT64 */ +#endif /* EGL_NV_system_time */ + +#ifndef EGL_NV_triple_buffer +#define EGL_NV_triple_buffer 1 +#define EGL_TRIPLE_BUFFER_NV 0x3230 +#endif /* EGL_NV_triple_buffer */ + +#ifndef EGL_TIZEN_image_native_buffer +#define EGL_TIZEN_image_native_buffer 1 +#define EGL_NATIVE_BUFFER_TIZEN 0x32A0 +#endif /* EGL_TIZEN_image_native_buffer */ + +#ifndef EGL_TIZEN_image_native_surface +#define EGL_TIZEN_image_native_surface 1 +#define EGL_NATIVE_SURFACE_TIZEN 0x32A1 +#endif /* EGL_TIZEN_image_native_surface */ + +#ifndef EGL_WL_bind_wayland_display +#define EGL_WL_bind_wayland_display 1 +#define PFNEGLBINDWAYLANDDISPLAYWL PFNEGLBINDWAYLANDDISPLAYWLPROC +#define PFNEGLUNBINDWAYLANDDISPLAYWL PFNEGLUNBINDWAYLANDDISPLAYWLPROC +#define PFNEGLQUERYWAYLANDBUFFERWL PFNEGLQUERYWAYLANDBUFFERWLPROC +struct wl_display; +struct wl_resource; +#define EGL_WAYLAND_BUFFER_WL 0x31D5 +#define EGL_WAYLAND_PLANE_WL 0x31D6 +#define EGL_TEXTURE_Y_U_V_WL 0x31D7 +#define EGL_TEXTURE_Y_UV_WL 0x31D8 +#define EGL_TEXTURE_Y_XUXV_WL 0x31D9 +#define EGL_TEXTURE_EXTERNAL_WL 0x31DA +#define EGL_WAYLAND_Y_INVERTED_WL 0x31DB +typedef EGLBoolean (EGLAPIENTRYP PFNEGLBINDWAYLANDDISPLAYWLPROC) (EGLDisplay dpy, struct wl_display *display); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLUNBINDWAYLANDDISPLAYWLPROC) (EGLDisplay dpy, struct wl_display *display); +typedef EGLBoolean (EGLAPIENTRYP PFNEGLQUERYWAYLANDBUFFERWLPROC) (EGLDisplay dpy, struct wl_resource *buffer, EGLint attribute, EGLint *value); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI EGLBoolean EGLAPIENTRY eglBindWaylandDisplayWL (EGLDisplay dpy, struct wl_display *display); +EGLAPI EGLBoolean EGLAPIENTRY eglUnbindWaylandDisplayWL (EGLDisplay dpy, struct wl_display *display); +EGLAPI EGLBoolean EGLAPIENTRY eglQueryWaylandBufferWL (EGLDisplay dpy, struct wl_resource *buffer, EGLint attribute, EGLint *value); +#endif +#endif /* EGL_WL_bind_wayland_display */ + +#ifndef EGL_WL_create_wayland_buffer_from_image +#define EGL_WL_create_wayland_buffer_from_image 1 +#define PFNEGLCREATEWAYLANDBUFFERFROMIMAGEWL PFNEGLCREATEWAYLANDBUFFERFROMIMAGEWLPROC +struct wl_buffer; +typedef struct wl_buffer *(EGLAPIENTRYP PFNEGLCREATEWAYLANDBUFFERFROMIMAGEWLPROC) (EGLDisplay dpy, EGLImageKHR image); +#ifdef EGL_EGLEXT_PROTOTYPES +EGLAPI struct wl_buffer *EGLAPIENTRY eglCreateWaylandBufferFromImageWL (EGLDisplay dpy, EGLImageKHR image); +#endif +#endif /* EGL_WL_create_wayland_buffer_from_image */ + +#ifdef __cplusplus +} +#endif + +#endif /* __eglext_h_ */ + +#endif /* _MSC_VER */ diff --git a/third_party/SDL2/include/SDL_endian.h b/third_party/SDL2/include/SDL_endian.h new file mode 100644 index 00000000000..5be66eafb9f --- /dev/null +++ b/third_party/SDL2/include/SDL_endian.h @@ -0,0 +1,396 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryEndian + * + * Functions for reading and writing endian-specific values + */ + +#ifndef SDL_endian_h_ +#define SDL_endian_h_ + +#include "SDL_stdinc.h" + +#if defined(_MSC_VER) && (_MSC_VER >= 1400) +/* As of Clang 11, '_m_prefetchw' is conflicting with the winnt.h's version, + so we define the needed '_m_prefetch' here as a pseudo-header, until the issue is fixed. */ +#ifdef __clang__ +#ifndef __PRFCHWINTRIN_H +#define __PRFCHWINTRIN_H +static __inline__ void __attribute__((__always_inline__, __nodebug__)) +_m_prefetch(void *__P) +{ + __builtin_prefetch(__P, 0, 3 /* _MM_HINT_T0 */); +} +#endif /* __PRFCHWINTRIN_H */ +#endif /* __clang__ */ + +#include +#endif + +/** + * \name The two types of endianness + */ +/* @{ */ +#define SDL_LIL_ENDIAN 1234 +#define SDL_BIG_ENDIAN 4321 +/* @} */ + +#ifndef SDL_BYTEORDER /* Not defined in SDL_config.h? */ +#ifdef __linux__ +#include +#define SDL_BYTEORDER __BYTE_ORDER +#elif defined(__sun) && defined(__SVR4) /* Solaris */ +#include +#if defined(_LITTLE_ENDIAN) +#define SDL_BYTEORDER SDL_LIL_ENDIAN +#elif defined(_BIG_ENDIAN) +#define SDL_BYTEORDER SDL_BIG_ENDIAN +#else +#error Unsupported endianness +#endif +#elif defined(__OpenBSD__) || defined(__DragonFly__) +#include +#define SDL_BYTEORDER BYTE_ORDER +#elif defined(__FreeBSD__) || defined(__NetBSD__) +#include +#define SDL_BYTEORDER BYTE_ORDER +/* predefs from newer gcc and clang versions: */ +#elif defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__) && defined(__BYTE_ORDER__) +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +#define SDL_BYTEORDER SDL_LIL_ENDIAN +#elif (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) +#define SDL_BYTEORDER SDL_BIG_ENDIAN +#else +#error Unsupported endianness +#endif /**/ +#else +#if defined(__hppa__) || \ + defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ + (defined(__MIPS__) && defined(__MIPSEB__)) || \ + defined(__ppc__) || defined(__POWERPC__) || defined(__powerpc__) || defined(__PPC__) || \ + defined(__sparc__) || defined(__sparc) +#define SDL_BYTEORDER SDL_BIG_ENDIAN +#else +#define SDL_BYTEORDER SDL_LIL_ENDIAN +#endif +#endif /* __linux__ */ +#endif /* !SDL_BYTEORDER */ + +#ifndef SDL_FLOATWORDORDER /* Not defined in SDL_config.h? */ +/* predefs from newer gcc versions: */ +#if defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__) && defined(__FLOAT_WORD_ORDER__) +#if (__FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__) +#define SDL_FLOATWORDORDER SDL_LIL_ENDIAN +#elif (__FLOAT_WORD_ORDER__ == __ORDER_BIG_ENDIAN__) +#define SDL_FLOATWORDORDER SDL_BIG_ENDIAN +#else +#error Unsupported endianness +#endif /**/ +#elif defined(__MAVERICK__) +/* For Maverick, float words are always little-endian. */ +#define SDL_FLOATWORDORDER SDL_LIL_ENDIAN +#elif (defined(__arm__) || defined(__thumb__)) && !defined(__VFP_FP__) && !defined(__ARM_EABI__) +/* For FPA, float words are always big-endian. */ +#define SDL_FLOATWORDORDER SDL_BIG_ENDIAN +#else +/* By default, assume that floats words follow the memory system mode. */ +#define SDL_FLOATWORDORDER SDL_BYTEORDER +#endif /* __FLOAT_WORD_ORDER__ */ +#endif /* !SDL_FLOATWORDORDER */ + + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \file SDL_endian.h + */ + +/* various modern compilers may have builtin swap */ +#if defined(__GNUC__) || defined(__clang__) +# define HAS_BUILTIN_BSWAP16 (_SDL_HAS_BUILTIN(__builtin_bswap16)) || \ + (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) +# define HAS_BUILTIN_BSWAP32 (_SDL_HAS_BUILTIN(__builtin_bswap32)) || \ + (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +# define HAS_BUILTIN_BSWAP64 (_SDL_HAS_BUILTIN(__builtin_bswap64)) || \ + (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) + + /* this one is broken */ +# define HAS_BROKEN_BSWAP (__GNUC__ == 2 && __GNUC_MINOR__ <= 95) +#else +# define HAS_BUILTIN_BSWAP16 0 +# define HAS_BUILTIN_BSWAP32 0 +# define HAS_BUILTIN_BSWAP64 0 +# define HAS_BROKEN_BSWAP 0 +#endif + +#if HAS_BUILTIN_BSWAP16 +#define SDL_Swap16(x) __builtin_bswap16(x) +#elif (defined(_MSC_VER) && (_MSC_VER >= 1400)) && !defined(__ICL) +#pragma intrinsic(_byteswap_ushort) +#define SDL_Swap16(x) _byteswap_ushort(x) +#elif defined(__i386__) && !HAS_BROKEN_BSWAP +SDL_FORCE_INLINE Uint16 +SDL_Swap16(Uint16 x) +{ + __asm__("xchgb %b0,%h0": "=q"(x):"0"(x)); + return x; +} +#elif defined(__x86_64__) +SDL_FORCE_INLINE Uint16 +SDL_Swap16(Uint16 x) +{ + __asm__("xchgb %b0,%h0": "=Q"(x):"0"(x)); + return x; +} +#elif (defined(__powerpc__) || defined(__ppc__)) +SDL_FORCE_INLINE Uint16 +SDL_Swap16(Uint16 x) +{ + int result; + + __asm__("rlwimi %0,%2,8,16,23": "=&r"(result):"0"(x >> 8), "r"(x)); + return (Uint16)result; +} +#elif (defined(__m68k__) && !defined(__mcoldfire__)) +SDL_FORCE_INLINE Uint16 +SDL_Swap16(Uint16 x) +{ + __asm__("rorw #8,%0": "=d"(x): "0"(x):"cc"); + return x; +} +#elif defined(__WATCOMC__) && defined(__386__) +extern __inline Uint16 SDL_Swap16(Uint16); +#pragma aux SDL_Swap16 = \ + "xchg al, ah" \ + parm [ax] \ + modify [ax]; +#else + +/** + * Use this function to swap the byte order of a 16-bit value. + * + * \param x the value to be swapped. + * \returns the swapped value. + * + * \sa SDL_SwapBE16 + * \sa SDL_SwapLE16 + */ +SDL_FORCE_INLINE Uint16 +SDL_Swap16(Uint16 x) +{ + return SDL_static_cast(Uint16, ((x << 8) | (x >> 8))); +} +#endif + +#if HAS_BUILTIN_BSWAP32 +#define SDL_Swap32(x) __builtin_bswap32(x) +#elif (defined(_MSC_VER) && (_MSC_VER >= 1400)) && !defined(__ICL) +#pragma intrinsic(_byteswap_ulong) +#define SDL_Swap32(x) _byteswap_ulong(x) +#elif defined(__i386__) && !HAS_BROKEN_BSWAP +SDL_FORCE_INLINE Uint32 +SDL_Swap32(Uint32 x) +{ + __asm__("bswap %0": "=r"(x):"0"(x)); + return x; +} +#elif defined(__x86_64__) +SDL_FORCE_INLINE Uint32 +SDL_Swap32(Uint32 x) +{ + __asm__("bswapl %0": "=r"(x):"0"(x)); + return x; +} +#elif (defined(__powerpc__) || defined(__ppc__)) +SDL_FORCE_INLINE Uint32 +SDL_Swap32(Uint32 x) +{ + Uint32 result; + + __asm__("rlwimi %0,%2,24,16,23": "=&r"(result): "0" (x>>24), "r"(x)); + __asm__("rlwimi %0,%2,8,8,15" : "=&r"(result): "0" (result), "r"(x)); + __asm__("rlwimi %0,%2,24,0,7" : "=&r"(result): "0" (result), "r"(x)); + return result; +} +#elif (defined(__m68k__) && !defined(__mcoldfire__)) +SDL_FORCE_INLINE Uint32 +SDL_Swap32(Uint32 x) +{ + __asm__("rorw #8,%0\n\tswap %0\n\trorw #8,%0": "=d"(x): "0"(x):"cc"); + return x; +} +#elif defined(__WATCOMC__) && defined(__386__) +extern __inline Uint32 SDL_Swap32(Uint32); +#pragma aux SDL_Swap32 = \ + "bswap eax" \ + parm [eax] \ + modify [eax]; +#else + +/** + * Use this function to swap the byte order of a 32-bit value. + * + * \param x the value to be swapped. + * \returns the swapped value. + * + * \sa SDL_SwapBE32 + * \sa SDL_SwapLE32 + */ +SDL_FORCE_INLINE Uint32 +SDL_Swap32(Uint32 x) +{ + return SDL_static_cast(Uint32, ((x << 24) | ((x << 8) & 0x00FF0000) | + ((x >> 8) & 0x0000FF00) | (x >> 24))); +} +#endif + +#if HAS_BUILTIN_BSWAP64 +#define SDL_Swap64(x) __builtin_bswap64(x) +#elif (defined(_MSC_VER) && (_MSC_VER >= 1400)) && !defined(__ICL) +#pragma intrinsic(_byteswap_uint64) +#define SDL_Swap64(x) _byteswap_uint64(x) +#elif defined(__i386__) && !HAS_BROKEN_BSWAP +SDL_FORCE_INLINE Uint64 +SDL_Swap64(Uint64 x) +{ + union { + struct { + Uint32 a, b; + } s; + Uint64 u; + } v; + v.u = x; + __asm__("bswapl %0 ; bswapl %1 ; xchgl %0,%1" + : "=r"(v.s.a), "=r"(v.s.b) + : "0" (v.s.a), "1"(v.s.b)); + return v.u; +} +#elif defined(__x86_64__) +SDL_FORCE_INLINE Uint64 +SDL_Swap64(Uint64 x) +{ + __asm__("bswapq %0": "=r"(x):"0"(x)); + return x; +} +#elif defined(__WATCOMC__) && defined(__386__) +extern __inline Uint64 SDL_Swap64(Uint64); +#pragma aux SDL_Swap64 = \ + "bswap eax" \ + "bswap edx" \ + "xchg eax,edx" \ + parm [eax edx] \ + modify [eax edx]; +#else + +/** + * Use this function to swap the byte order of a 64-bit value. + * + * \param x the value to be swapped. + * \returns the swapped value. + * + * \sa SDL_SwapBE64 + * \sa SDL_SwapLE64 + */ +SDL_FORCE_INLINE Uint64 +SDL_Swap64(Uint64 x) +{ + Uint32 hi, lo; + + /* Separate into high and low 32-bit values and swap them */ + lo = SDL_static_cast(Uint32, x & 0xFFFFFFFF); + x >>= 32; + hi = SDL_static_cast(Uint32, x & 0xFFFFFFFF); + x = SDL_Swap32(lo); + x <<= 32; + x |= SDL_Swap32(hi); + return (x); +} +#endif + + +/** + * Use this function to swap the byte order of a floating point value. + * + * \param x the value to be swapped. + * \returns the swapped value. + * + * \sa SDL_SwapFloatBE + * \sa SDL_SwapFloatLE + */ +SDL_FORCE_INLINE float +SDL_SwapFloat(float x) +{ + union { + float f; + Uint32 ui32; + } swapper; + swapper.f = x; + swapper.ui32 = SDL_Swap32(swapper.ui32); + return swapper.f; +} + +/* remove extra macros */ +#undef HAS_BROKEN_BSWAP +#undef HAS_BUILTIN_BSWAP16 +#undef HAS_BUILTIN_BSWAP32 +#undef HAS_BUILTIN_BSWAP64 + +/** + * \name Swap to native + * Byteswap item from the specified endianness to the native endianness. + */ +/* @{ */ +#if SDL_BYTEORDER == SDL_LIL_ENDIAN +#define SDL_SwapLE16(X) (X) +#define SDL_SwapLE32(X) (X) +#define SDL_SwapLE64(X) (X) +#define SDL_SwapFloatLE(X) (X) +#define SDL_SwapBE16(X) SDL_Swap16(X) +#define SDL_SwapBE32(X) SDL_Swap32(X) +#define SDL_SwapBE64(X) SDL_Swap64(X) +#define SDL_SwapFloatBE(X) SDL_SwapFloat(X) +#else +#define SDL_SwapLE16(X) SDL_Swap16(X) +#define SDL_SwapLE32(X) SDL_Swap32(X) +#define SDL_SwapLE64(X) SDL_Swap64(X) +#define SDL_SwapFloatLE(X) SDL_SwapFloat(X) +#define SDL_SwapBE16(X) (X) +#define SDL_SwapBE32(X) (X) +#define SDL_SwapBE64(X) (X) +#define SDL_SwapFloatBE(X) (X) +#endif +/* @} *//* Swap to native */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_endian_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_error.h b/third_party/SDL2/include/SDL_error.h new file mode 100644 index 00000000000..8d9cde0e775 --- /dev/null +++ b/third_party/SDL2/include/SDL_error.h @@ -0,0 +1,163 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryError + * + * Simple error message routines for SDL. + */ + +#ifndef SDL_error_h_ +#define SDL_error_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Public functions */ + + +/** + * Set the SDL error message for the current thread. + * + * Calling this function will replace any previous error message that was set. + * + * This function always returns -1, since SDL frequently uses -1 to signify an + * failing result, leading to this idiom: + * + * ```c + * if (error_code) { + * return SDL_SetError("This operation has failed: %d", error_code); + * } + * ``` + * + * \param fmt a printf()-style message format string. + * \param ... additional parameters matching % tokens in the `fmt` string, if + * any. + * \returns always -1. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ClearError + * \sa SDL_GetError + */ +extern DECLSPEC int SDLCALL SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1); + +/** + * Retrieve a message about the last error that occurred on the current + * thread. + * + * It is possible for multiple errors to occur before calling SDL_GetError(). + * Only the last error is returned. + * + * The message is only applicable when an SDL function has signaled an error. + * You must check the return values of SDL function calls to determine when to + * appropriately call SDL_GetError(). You should *not* use the results of + * SDL_GetError() to decide if an error has occurred! Sometimes SDL will set + * an error string even when reporting success. + * + * SDL will *not* clear the error string for successful API calls. You *must* + * check return values for failure cases before you can assume the error + * string applies. + * + * Error strings are set per-thread, so an error set in a different thread + * will not interfere with the current thread's operation. + * + * The returned string is internally allocated and must not be freed by the + * application. + * + * \returns a message with information about the specific error that occurred, + * or an empty string if there hasn't been an error message set since + * the last call to SDL_ClearError(). The message is only applicable + * when an SDL function has signaled an error. You must check the + * return values of SDL function calls to determine when to + * appropriately call SDL_GetError(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ClearError + * \sa SDL_SetError + */ +extern DECLSPEC const char *SDLCALL SDL_GetError(void); + +/** + * Get the last error message that was set for the current thread. + * + * This allows the caller to copy the error string into a provided buffer, but + * otherwise operates exactly the same as SDL_GetError(). + * + * \param errstr A buffer to fill with the last error message that was set for + * the current thread. + * \param maxlen The size of the buffer pointed to by the errstr parameter. + * \returns the pointer passed in as the `errstr` parameter. + * + * \since This function is available since SDL 2.0.14. + * + * \sa SDL_GetError + */ +extern DECLSPEC char * SDLCALL SDL_GetErrorMsg(char *errstr, int maxlen); + +/** + * Clear any previous error message for this thread. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetError + * \sa SDL_SetError + */ +extern DECLSPEC void SDLCALL SDL_ClearError(void); + +/** + * \name Internal error functions + * + * \internal + * Private error reporting function - used internally. + */ +/* @{ */ +#define SDL_OutOfMemory() SDL_Error(SDL_ENOMEM) +#define SDL_Unsupported() SDL_Error(SDL_UNSUPPORTED) +#define SDL_InvalidParamError(param) SDL_SetError("Parameter '%s' is invalid", (param)) +typedef enum +{ + SDL_ENOMEM, + SDL_EFREAD, + SDL_EFWRITE, + SDL_EFSEEK, + SDL_UNSUPPORTED, + SDL_LASTERROR +} SDL_errorcode; +/* SDL_Error() unconditionally returns -1. */ +extern DECLSPEC int SDLCALL SDL_Error(SDL_errorcode code); +/* @} *//* Internal error functions */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_error_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_events.h b/third_party/SDL2/include/SDL_events.h new file mode 100644 index 00000000000..b9596c0ef5e --- /dev/null +++ b/third_party/SDL2/include/SDL_events.h @@ -0,0 +1,1196 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryEvents + * + * Include file for SDL event handling. + */ + +#ifndef SDL_events_h_ +#define SDL_events_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_video.h" +#include "SDL_keyboard.h" +#include "SDL_mouse.h" +#include "SDL_joystick.h" +#include "SDL_gamecontroller.h" +#include "SDL_quit.h" +#include "SDL_gesture.h" +#include "SDL_touch.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* General keyboard/mouse state definitions */ +#define SDL_RELEASED 0 +#define SDL_PRESSED 1 + +/** + * The types of events that can be delivered. + */ +typedef enum SDL_EventType +{ + SDL_FIRSTEVENT = 0, /**< Unused (do not remove) */ + + /* Application events */ + SDL_QUIT = 0x100, /**< User-requested quit */ + + /* These application events have special meaning on iOS, see README-ios.md for details */ + SDL_APP_TERMINATING, /**< The application is being terminated by the OS + Called on iOS in applicationWillTerminate() + Called on Android in onDestroy() + */ + SDL_APP_LOWMEMORY, /**< The application is low on memory, free memory if possible. + Called on iOS in applicationDidReceiveMemoryWarning() + Called on Android in onLowMemory() + */ + SDL_APP_WILLENTERBACKGROUND, /**< The application is about to enter the background + Called on iOS in applicationWillResignActive() + Called on Android in onPause() + */ + SDL_APP_DIDENTERBACKGROUND, /**< The application did enter the background and may not get CPU for some time + Called on iOS in applicationDidEnterBackground() + Called on Android in onPause() + */ + SDL_APP_WILLENTERFOREGROUND, /**< The application is about to enter the foreground + Called on iOS in applicationWillEnterForeground() + Called on Android in onResume() + */ + SDL_APP_DIDENTERFOREGROUND, /**< The application is now interactive + Called on iOS in applicationDidBecomeActive() + Called on Android in onResume() + */ + + SDL_LOCALECHANGED, /**< The user's locale preferences have changed. */ + + /* Display events */ + SDL_DISPLAYEVENT = 0x150, /**< Display state change */ + + /* Window events */ + SDL_WINDOWEVENT = 0x200, /**< Window state change */ + SDL_SYSWMEVENT, /**< System specific event */ + + /* Keyboard events */ + SDL_KEYDOWN = 0x300, /**< Key pressed */ + SDL_KEYUP, /**< Key released */ + SDL_TEXTEDITING, /**< Keyboard text editing (composition) */ + SDL_TEXTINPUT, /**< Keyboard text input */ + SDL_KEYMAPCHANGED, /**< Keymap changed due to a system event such as an + input language or keyboard layout change. + */ + SDL_TEXTEDITING_EXT, /**< Extended keyboard text editing (composition) */ + + /* Mouse events */ + SDL_MOUSEMOTION = 0x400, /**< Mouse moved */ + SDL_MOUSEBUTTONDOWN, /**< Mouse button pressed */ + SDL_MOUSEBUTTONUP, /**< Mouse button released */ + SDL_MOUSEWHEEL, /**< Mouse wheel motion */ + + /* Joystick events */ + SDL_JOYAXISMOTION = 0x600, /**< Joystick axis motion */ + SDL_JOYBALLMOTION, /**< Joystick trackball motion */ + SDL_JOYHATMOTION, /**< Joystick hat position change */ + SDL_JOYBUTTONDOWN, /**< Joystick button pressed */ + SDL_JOYBUTTONUP, /**< Joystick button released */ + SDL_JOYDEVICEADDED, /**< A new joystick has been inserted into the system */ + SDL_JOYDEVICEREMOVED, /**< An opened joystick has been removed */ + SDL_JOYBATTERYUPDATED, /**< Joystick battery level change */ + + /* Game controller events */ + SDL_CONTROLLERAXISMOTION = 0x650, /**< Game controller axis motion */ + SDL_CONTROLLERBUTTONDOWN, /**< Game controller button pressed */ + SDL_CONTROLLERBUTTONUP, /**< Game controller button released */ + SDL_CONTROLLERDEVICEADDED, /**< A new Game controller has been inserted into the system */ + SDL_CONTROLLERDEVICEREMOVED, /**< An opened Game controller has been removed */ + SDL_CONTROLLERDEVICEREMAPPED, /**< The controller mapping was updated */ + SDL_CONTROLLERTOUCHPADDOWN, /**< Game controller touchpad was touched */ + SDL_CONTROLLERTOUCHPADMOTION, /**< Game controller touchpad finger was moved */ + SDL_CONTROLLERTOUCHPADUP, /**< Game controller touchpad finger was lifted */ + SDL_CONTROLLERSENSORUPDATE, /**< Game controller sensor was updated */ + SDL_CONTROLLERUPDATECOMPLETE_RESERVED_FOR_SDL3, + SDL_CONTROLLERSTEAMHANDLEUPDATED, /**< Game controller Steam handle has changed */ + + /* Touch events */ + SDL_FINGERDOWN = 0x700, + SDL_FINGERUP, + SDL_FINGERMOTION, + + /* Gesture events */ + SDL_DOLLARGESTURE = 0x800, + SDL_DOLLARRECORD, + SDL_MULTIGESTURE, + + /* Clipboard events */ + SDL_CLIPBOARDUPDATE = 0x900, /**< The clipboard or primary selection changed */ + + /* Drag and drop events */ + SDL_DROPFILE = 0x1000, /**< The system requests a file open */ + SDL_DROPTEXT, /**< text/plain drag-and-drop event */ + SDL_DROPBEGIN, /**< A new set of drops is beginning (NULL filename) */ + SDL_DROPCOMPLETE, /**< Current set of drops is now complete (NULL filename) */ + + /* Audio hotplug events */ + SDL_AUDIODEVICEADDED = 0x1100, /**< A new audio device is available */ + SDL_AUDIODEVICEREMOVED, /**< An audio device has been removed. */ + + /* Sensor events */ + SDL_SENSORUPDATE = 0x1200, /**< A sensor was updated */ + + /* Render events */ + SDL_RENDER_TARGETS_RESET = 0x2000, /**< The render targets have been reset and their contents need to be updated */ + SDL_RENDER_DEVICE_RESET, /**< The device has been reset and all textures need to be recreated */ + + /* Internal events */ + SDL_POLLSENTINEL = 0x7F00, /**< Signals the end of an event poll cycle */ + + /** Events SDL_USEREVENT through SDL_LASTEVENT are for your use, + * and should be allocated with SDL_RegisterEvents() + */ + SDL_USEREVENT = 0x8000, + + /** + * This last event is only for bounding internal arrays + */ + SDL_LASTEVENT = 0xFFFF +} SDL_EventType; + +/** + * Fields shared by every event + */ +typedef struct SDL_CommonEvent +{ + Uint32 type; + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ +} SDL_CommonEvent; + +/** + * Display state change event data (event.display.*) + */ +typedef struct SDL_DisplayEvent +{ + Uint32 type; /**< SDL_DISPLAYEVENT */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 display; /**< The associated display index */ + Uint8 event; /**< SDL_DisplayEventID */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; + Sint32 data1; /**< event dependent data */ +} SDL_DisplayEvent; + +/** + * Window state change event data (event.window.*) + */ +typedef struct SDL_WindowEvent +{ + Uint32 type; /**< SDL_WINDOWEVENT */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The associated window */ + Uint8 event; /**< SDL_WindowEventID */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; + Sint32 data1; /**< event dependent data */ + Sint32 data2; /**< event dependent data */ +} SDL_WindowEvent; + +/** + * Keyboard button event structure (event.key.*) + */ +typedef struct SDL_KeyboardEvent +{ + Uint32 type; /**< SDL_KEYDOWN or SDL_KEYUP */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The window with keyboard focus, if any */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ + Uint8 repeat; /**< Non-zero if this is a key repeat */ + Uint8 padding2; + Uint8 padding3; + SDL_Keysym keysym; /**< The key that was pressed or released */ +} SDL_KeyboardEvent; + +#define SDL_TEXTEDITINGEVENT_TEXT_SIZE (32) + +/** + * Keyboard text editing event structure (event.edit.*) + */ +typedef struct SDL_TextEditingEvent +{ + Uint32 type; /**< SDL_TEXTEDITING */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The window with keyboard focus, if any */ + char text[SDL_TEXTEDITINGEVENT_TEXT_SIZE]; /**< The editing text */ + Sint32 start; /**< The start cursor of selected editing text */ + Sint32 length; /**< The length of selected editing text */ +} SDL_TextEditingEvent; + +/** + * Extended keyboard text editing event structure (event.editExt.*) when text + * would be truncated if stored in the text buffer SDL_TextEditingEvent + */ +typedef struct SDL_TextEditingExtEvent +{ + Uint32 type; /**< SDL_TEXTEDITING_EXT */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The window with keyboard focus, if any */ + char* text; /**< The editing text, which should be freed with SDL_free(), and will not be NULL */ + Sint32 start; /**< The start cursor of selected editing text */ + Sint32 length; /**< The length of selected editing text */ +} SDL_TextEditingExtEvent; + +/** + * The maximum bytes of text that can be supplied in an SDL_TextInputEvent. + */ +#define SDL_TEXTINPUTEVENT_TEXT_SIZE (32) + +/** + * Keyboard text input event structure (event.text.*) + * + * `text` is limited to SDL_TEXTINPUTEVENT_TEXT_SIZE bytes. If the incoming + * string is larger than this, SDL will split it and send it in pieces, across + * multiple events. The string is in UTF-8 format, and if split, SDL + * guarantees that it will not split in the middle of a UTF-8 sequence, so any + * event will only contain complete codepoints. However, if there are several + * codepoints that go together into a single glyph (like an emoji "thumbs up" + * followed by a skin color), they may be split between events. + * + * This event will never be delivered unless text input is enabled by calling + * SDL_StartTextInput(). Text input is enabled by default on desktop + * platforms, and disabled by default on mobile platforms! + * + * \sa SDL_StartTextInput + * \sa SDL_StopTextInput + */ +typedef struct SDL_TextInputEvent +{ + Uint32 type; /**< SDL_TEXTINPUT */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The window with keyboard focus, if any */ + char text[SDL_TEXTINPUTEVENT_TEXT_SIZE]; /**< The input text; UTF-8 encoded. */ +} SDL_TextInputEvent; + +/** + * Mouse motion event structure (event.motion.*) + */ +typedef struct SDL_MouseMotionEvent +{ + Uint32 type; /**< SDL_MOUSEMOTION */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The window with mouse focus, if any */ + Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */ + Uint32 state; /**< The current button state */ + Sint32 x; /**< X coordinate, relative to window */ + Sint32 y; /**< Y coordinate, relative to window */ + Sint32 xrel; /**< The relative motion in the X direction */ + Sint32 yrel; /**< The relative motion in the Y direction */ +} SDL_MouseMotionEvent; + +/** + * Mouse button event structure (event.button.*) + */ +typedef struct SDL_MouseButtonEvent +{ + Uint32 type; /**< SDL_MOUSEBUTTONDOWN or SDL_MOUSEBUTTONUP */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The window with mouse focus, if any */ + Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */ + Uint8 button; /**< The mouse button index */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ + Uint8 clicks; /**< 1 for single-click, 2 for double-click, etc. */ + Uint8 padding1; + Sint32 x; /**< X coordinate, relative to window */ + Sint32 y; /**< Y coordinate, relative to window */ +} SDL_MouseButtonEvent; + +/** + * Mouse wheel event structure (event.wheel.*) + */ +typedef struct SDL_MouseWheelEvent +{ + Uint32 type; /**< SDL_MOUSEWHEEL */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The window with mouse focus, if any */ + Uint32 which; /**< The mouse instance id, or SDL_TOUCH_MOUSEID */ + Sint32 x; /**< The amount scrolled horizontally, positive to the right and negative to the left */ + Sint32 y; /**< The amount scrolled vertically, positive away from the user and negative toward the user */ + Uint32 direction; /**< Set to one of the SDL_MOUSEWHEEL_* defines. When FLIPPED the values in X and Y will be opposite. Multiply by -1 to change them back */ + float preciseX; /**< The amount scrolled horizontally, positive to the right and negative to the left, with float precision (added in 2.0.18) */ + float preciseY; /**< The amount scrolled vertically, positive away from the user and negative toward the user, with float precision (added in 2.0.18) */ + Sint32 mouseX; /**< X coordinate, relative to window (added in 2.26.0) */ + Sint32 mouseY; /**< Y coordinate, relative to window (added in 2.26.0) */ +} SDL_MouseWheelEvent; + +/** + * Joystick axis motion event structure (event.jaxis.*) + */ +typedef struct SDL_JoyAxisEvent +{ + Uint32 type; /**< SDL_JOYAXISMOTION */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 axis; /**< The joystick axis index */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; + Sint16 value; /**< The axis value (range: -32768 to 32767) */ + Uint16 padding4; +} SDL_JoyAxisEvent; + +/** + * Joystick trackball motion event structure (event.jball.*) + */ +typedef struct SDL_JoyBallEvent +{ + Uint32 type; /**< SDL_JOYBALLMOTION */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 ball; /**< The joystick trackball index */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; + Sint16 xrel; /**< The relative motion in the X direction */ + Sint16 yrel; /**< The relative motion in the Y direction */ +} SDL_JoyBallEvent; + +/** + * Joystick hat position change event structure (event.jhat.*) + */ +typedef struct SDL_JoyHatEvent +{ + Uint32 type; /**< SDL_JOYHATMOTION */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 hat; /**< The joystick hat index */ + Uint8 value; /**< The hat position value. + * \sa SDL_HAT_LEFTUP SDL_HAT_UP SDL_HAT_RIGHTUP + * \sa SDL_HAT_LEFT SDL_HAT_CENTERED SDL_HAT_RIGHT + * \sa SDL_HAT_LEFTDOWN SDL_HAT_DOWN SDL_HAT_RIGHTDOWN + * + * Note that zero means the POV is centered. + */ + Uint8 padding1; + Uint8 padding2; +} SDL_JoyHatEvent; + +/** + * Joystick button event structure (event.jbutton.*) + */ +typedef struct SDL_JoyButtonEvent +{ + Uint32 type; /**< SDL_JOYBUTTONDOWN or SDL_JOYBUTTONUP */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 button; /**< The joystick button index */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ + Uint8 padding1; + Uint8 padding2; +} SDL_JoyButtonEvent; + +/** + * Joystick device event structure (event.jdevice.*) + * + * SDL will send JOYSTICK_ADDED events for devices that are already plugged in + * during SDL_Init. + * + * \sa SDL_ControllerDeviceEvent + */ +typedef struct SDL_JoyDeviceEvent +{ + Uint32 type; /**< SDL_JOYDEVICEADDED or SDL_JOYDEVICEREMOVED */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Sint32 which; /**< The joystick device index for the ADDED event, instance id for the REMOVED event */ +} SDL_JoyDeviceEvent; + +/** + * Joysick battery level change event structure (event.jbattery.*) + */ +typedef struct SDL_JoyBatteryEvent +{ + Uint32 type; /**< SDL_JOYBATTERYUPDATED */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + SDL_JoystickPowerLevel level; /**< The joystick battery level */ +} SDL_JoyBatteryEvent; + +/** + * Game controller axis motion event structure (event.caxis.*) + */ +typedef struct SDL_ControllerAxisEvent +{ + Uint32 type; /**< SDL_CONTROLLERAXISMOTION */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 axis; /**< The controller axis (SDL_GameControllerAxis) */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; + Sint16 value; /**< The axis value (range: -32768 to 32767) */ + Uint16 padding4; +} SDL_ControllerAxisEvent; + + +/** + * Game controller button event structure (event.cbutton.*) + */ +typedef struct SDL_ControllerButtonEvent +{ + Uint32 type; /**< SDL_CONTROLLERBUTTONDOWN or SDL_CONTROLLERBUTTONUP */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + Uint8 button; /**< The controller button (SDL_GameControllerButton) */ + Uint8 state; /**< SDL_PRESSED or SDL_RELEASED */ + Uint8 padding1; + Uint8 padding2; +} SDL_ControllerButtonEvent; + + +/** + * Controller device event structure (event.cdevice.*) + * + * Joysticks that are supported game controllers receive both an + * SDL_JoyDeviceEvent and an SDL_ControllerDeviceEvent. + * + * SDL will send CONTROLLERDEVICEADDED events for joysticks that are already + * plugged in during SDL_Init() and are recognized as game controllers. + */ +typedef struct SDL_ControllerDeviceEvent +{ + Uint32 type; /**< SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED, or SDL_CONTROLLERSTEAMHANDLEUPDATED */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Sint32 which; /**< The joystick device index for the ADDED event, instance id for the REMOVED or REMAPPED event */ +} SDL_ControllerDeviceEvent; + +/** + * Game controller touchpad event structure (event.ctouchpad.*) + */ +typedef struct SDL_ControllerTouchpadEvent +{ + Uint32 type; /**< SDL_CONTROLLERTOUCHPADDOWN or SDL_CONTROLLERTOUCHPADMOTION or SDL_CONTROLLERTOUCHPADUP */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + Sint32 touchpad; /**< The index of the touchpad */ + Sint32 finger; /**< The index of the finger on the touchpad */ + float x; /**< Normalized in the range 0...1 with 0 being on the left */ + float y; /**< Normalized in the range 0...1 with 0 being at the top */ + float pressure; /**< Normalized in the range 0...1 */ +} SDL_ControllerTouchpadEvent; + +/** + * Game controller sensor event structure (event.csensor.*) + */ +typedef struct SDL_ControllerSensorEvent +{ + Uint32 type; /**< SDL_CONTROLLERSENSORUPDATE */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_JoystickID which; /**< The joystick instance id */ + Sint32 sensor; /**< The type of the sensor, one of the values of SDL_SensorType */ + float data[3]; /**< Up to 3 values from the sensor, as defined in SDL_sensor.h */ + Uint64 timestamp_us; /**< The timestamp of the sensor reading in microseconds, if the hardware provides this information. */ +} SDL_ControllerSensorEvent; + +/** + * Audio device event structure (event.adevice.*) + */ +typedef struct SDL_AudioDeviceEvent +{ + Uint32 type; /**< SDL_AUDIODEVICEADDED, or SDL_AUDIODEVICEREMOVED */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 which; /**< The audio device index for the ADDED event (valid until next SDL_GetNumAudioDevices() call), SDL_AudioDeviceID for the REMOVED event */ + Uint8 iscapture; /**< zero if an output device, non-zero if a capture device. */ + Uint8 padding1; + Uint8 padding2; + Uint8 padding3; +} SDL_AudioDeviceEvent; + + +/** + * Touch finger event structure (event.tfinger.*) + */ +typedef struct SDL_TouchFingerEvent +{ + Uint32 type; /**< SDL_FINGERMOTION or SDL_FINGERDOWN or SDL_FINGERUP */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_TouchID touchId; /**< The touch device id */ + SDL_FingerID fingerId; + float x; /**< Normalized in the range 0...1 */ + float y; /**< Normalized in the range 0...1 */ + float dx; /**< Normalized in the range -1...1 */ + float dy; /**< Normalized in the range -1...1 */ + float pressure; /**< Normalized in the range 0...1 */ + Uint32 windowID; /**< The window underneath the finger, if any */ +} SDL_TouchFingerEvent; + + +/** + * Multiple Finger Gesture Event (event.mgesture.*) + */ +typedef struct SDL_MultiGestureEvent +{ + Uint32 type; /**< SDL_MULTIGESTURE */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_TouchID touchId; /**< The touch device id */ + float dTheta; + float dDist; + float x; + float y; + Uint16 numFingers; + Uint16 padding; +} SDL_MultiGestureEvent; + + +/** + * Dollar Gesture Event (event.dgesture.*) + */ +typedef struct SDL_DollarGestureEvent +{ + Uint32 type; /**< SDL_DOLLARGESTURE or SDL_DOLLARRECORD */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_TouchID touchId; /**< The touch device id */ + SDL_GestureID gestureId; + Uint32 numFingers; + float error; + float x; /**< Normalized center of gesture */ + float y; /**< Normalized center of gesture */ +} SDL_DollarGestureEvent; + + +/** + * An event used to request a file open by the system (event.drop.*) + * + * This event is enabled by default, you can disable it with SDL_EventState(). + * + * If this event is enabled, you must free the filename in the event. + */ +typedef struct SDL_DropEvent +{ + Uint32 type; /**< SDL_DROPBEGIN or SDL_DROPFILE or SDL_DROPTEXT or SDL_DROPCOMPLETE */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + char *file; /**< The file name, which should be freed with SDL_free(), is NULL on begin/complete */ + Uint32 windowID; /**< The window that was dropped on, if any */ +} SDL_DropEvent; + + +/** + * Sensor event structure (event.sensor.*) + */ +typedef struct SDL_SensorEvent +{ + Uint32 type; /**< SDL_SENSORUPDATE */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Sint32 which; /**< The instance ID of the sensor */ + float data[6]; /**< Up to 6 values from the sensor - additional values can be queried using SDL_SensorGetData() */ + Uint64 timestamp_us; /**< The timestamp of the sensor reading in microseconds, if the hardware provides this information. */ +} SDL_SensorEvent; + +/** + * The "quit requested" event + */ +typedef struct SDL_QuitEvent +{ + Uint32 type; /**< SDL_QUIT */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ +} SDL_QuitEvent; + +/** + * A user-defined event type (event.user.*) + */ +typedef struct SDL_UserEvent +{ + Uint32 type; /**< SDL_USEREVENT through SDL_LASTEVENT-1 */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + Uint32 windowID; /**< The associated window if any */ + Sint32 code; /**< User defined event code */ + void *data1; /**< User defined data pointer */ + void *data2; /**< User defined data pointer */ +} SDL_UserEvent; + + +struct SDL_SysWMmsg; +typedef struct SDL_SysWMmsg SDL_SysWMmsg; + +/** + * A video driver dependent system event (event.syswm.*) + * + * This event is disabled by default, you can enable it with SDL_EventState() + * + * If you want to use this event, you should include SDL_syswm.h. + */ +typedef struct SDL_SysWMEvent +{ + Uint32 type; /**< SDL_SYSWMEVENT */ + Uint32 timestamp; /**< In milliseconds, populated using SDL_GetTicks() */ + SDL_SysWMmsg *msg; /**< driver dependent data, defined in SDL_syswm.h */ +} SDL_SysWMEvent; + +/** + * General event structure + * + * The SDL_Event structure is the core of all event handling in SDL. SDL_Event + * is a union of all event structures used in SDL. + */ +typedef union SDL_Event +{ + Uint32 type; /**< Event type, shared with all events */ + SDL_CommonEvent common; /**< Common event data */ + SDL_DisplayEvent display; /**< Display event data */ + SDL_WindowEvent window; /**< Window event data */ + SDL_KeyboardEvent key; /**< Keyboard event data */ + SDL_TextEditingEvent edit; /**< Text editing event data */ + SDL_TextEditingExtEvent editExt; /**< Extended text editing event data */ + SDL_TextInputEvent text; /**< Text input event data */ + SDL_MouseMotionEvent motion; /**< Mouse motion event data */ + SDL_MouseButtonEvent button; /**< Mouse button event data */ + SDL_MouseWheelEvent wheel; /**< Mouse wheel event data */ + SDL_JoyAxisEvent jaxis; /**< Joystick axis event data */ + SDL_JoyBallEvent jball; /**< Joystick ball event data */ + SDL_JoyHatEvent jhat; /**< Joystick hat event data */ + SDL_JoyButtonEvent jbutton; /**< Joystick button event data */ + SDL_JoyDeviceEvent jdevice; /**< Joystick device change event data */ + SDL_JoyBatteryEvent jbattery; /**< Joystick battery event data */ + SDL_ControllerAxisEvent caxis; /**< Game Controller axis event data */ + SDL_ControllerButtonEvent cbutton; /**< Game Controller button event data */ + SDL_ControllerDeviceEvent cdevice; /**< Game Controller device event data */ + SDL_ControllerTouchpadEvent ctouchpad; /**< Game Controller touchpad event data */ + SDL_ControllerSensorEvent csensor; /**< Game Controller sensor event data */ + SDL_AudioDeviceEvent adevice; /**< Audio device event data */ + SDL_SensorEvent sensor; /**< Sensor event data */ + SDL_QuitEvent quit; /**< Quit request event data */ + SDL_UserEvent user; /**< Custom event data */ + SDL_SysWMEvent syswm; /**< System dependent window event data */ + SDL_TouchFingerEvent tfinger; /**< Touch finger event data */ + SDL_MultiGestureEvent mgesture; /**< Gesture event data */ + SDL_DollarGestureEvent dgesture; /**< Gesture event data */ + SDL_DropEvent drop; /**< Drag and drop event data */ + + /* This is necessary for ABI compatibility between Visual C++ and GCC. + Visual C++ will respect the push pack pragma and use 52 bytes (size of + SDL_TextEditingEvent, the largest structure for 32-bit and 64-bit + architectures) for this union, and GCC will use the alignment of the + largest datatype within the union, which is 8 bytes on 64-bit + architectures. + + So... we'll add padding to force the size to be 56 bytes for both. + + On architectures where pointers are 16 bytes, this needs rounding up to + the next multiple of 16, 64, and on architectures where pointers are + even larger the size of SDL_UserEvent will dominate as being 3 pointers. + */ + Uint8 padding[sizeof(void *) <= 8 ? 56 : sizeof(void *) == 16 ? 64 : 3 * sizeof(void *)]; +} SDL_Event; + +/* Make sure we haven't broken binary compatibility */ +SDL_COMPILE_TIME_ASSERT(SDL_Event, sizeof(SDL_Event) == sizeof(((SDL_Event *)NULL)->padding)); + + +/* Function prototypes */ + +/** + * Pump the event loop, gathering events from the input devices. + * + * This function updates the event queue and internal input device state. + * + * **WARNING**: This should only be run in the thread that initialized the + * video subsystem, and for extra safety, you should consider only doing those + * things on the main thread in any case. + * + * SDL_PumpEvents() gathers all the pending input information from devices and + * places it in the event queue. Without calls to SDL_PumpEvents() no events + * would ever be placed on the queue. Often the need for calls to + * SDL_PumpEvents() is hidden from the user since SDL_PollEvent() and + * SDL_WaitEvent() implicitly call SDL_PumpEvents(). However, if you are not + * polling or waiting for events (e.g. you are filtering them), then you must + * call SDL_PumpEvents() to force an event queue update. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PollEvent + * \sa SDL_WaitEvent + */ +extern DECLSPEC void SDLCALL SDL_PumpEvents(void); + +/* @{ */ +typedef enum SDL_eventaction +{ + SDL_ADDEVENT, + SDL_PEEKEVENT, + SDL_GETEVENT +} SDL_eventaction; + +/** + * Check the event queue for messages and optionally return them. + * + * `action` may be any of the following: + * + * - `SDL_ADDEVENT`: up to `numevents` events will be added to the back of the + * event queue. + * - `SDL_PEEKEVENT`: `numevents` events at the front of the event queue, + * within the specified minimum and maximum type, will be returned to the + * caller and will _not_ be removed from the queue. + * - `SDL_GETEVENT`: up to `numevents` events at the front of the event queue, + * within the specified minimum and maximum type, will be returned to the + * caller and will be removed from the queue. + * + * You may have to call SDL_PumpEvents() before calling this function. + * Otherwise, the events may not be ready to be filtered when you call + * SDL_PeepEvents(). + * + * This function is thread-safe. + * + * \param events destination buffer for the retrieved events. + * \param numevents if action is SDL_ADDEVENT, the number of events to add + * back to the event queue; if action is SDL_PEEKEVENT or + * SDL_GETEVENT, the maximum number of events to retrieve. + * \param action action to take; see [[#action|Remarks]] for details. + * \param minType minimum value of the event type to be considered; + * SDL_FIRSTEVENT is a safe choice. + * \param maxType maximum value of the event type to be considered; + * SDL_LASTEVENT is a safe choice. + * \returns the number of events actually stored or a negative error code on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PollEvent + * \sa SDL_PumpEvents + * \sa SDL_PushEvent + */ +extern DECLSPEC int SDLCALL SDL_PeepEvents(SDL_Event * events, int numevents, + SDL_eventaction action, + Uint32 minType, Uint32 maxType); +/* @} */ + +/** + * Check for the existence of a certain event type in the event queue. + * + * If you need to check for a range of event types, use SDL_HasEvents() + * instead. + * + * \param type the type of event to be queried; see SDL_EventType for details. + * \returns SDL_TRUE if events matching `type` are present, or SDL_FALSE if + * events matching `type` are not present. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HasEvents + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasEvent(Uint32 type); + + +/** + * Check for the existence of certain event types in the event queue. + * + * If you need to check for a single event type, use SDL_HasEvent() instead. + * + * \param minType the low end of event type to be queried, inclusive; see + * SDL_EventType for details. + * \param maxType the high end of event type to be queried, inclusive; see + * SDL_EventType for details. + * \returns SDL_TRUE if events with type >= `minType` and <= `maxType` are + * present, or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HasEvents + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasEvents(Uint32 minType, Uint32 maxType); + +/** + * Clear events of a specific type from the event queue. + * + * This will unconditionally remove any events from the queue that match + * `type`. If you need to remove a range of event types, use SDL_FlushEvents() + * instead. + * + * It's also normal to just ignore events you don't care about in your event + * loop without calling this function. + * + * This function only affects currently queued events. If you want to make + * sure that all pending OS events are flushed, you can call SDL_PumpEvents() + * on the main thread immediately before the flush call. + * + * \param type the type of event to be cleared; see SDL_EventType for details. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FlushEvents + */ +extern DECLSPEC void SDLCALL SDL_FlushEvent(Uint32 type); + +/** + * Clear events of a range of types from the event queue. + * + * This will unconditionally remove any events from the queue that are in the + * range of `minType` to `maxType`, inclusive. If you need to remove a single + * event type, use SDL_FlushEvent() instead. + * + * It's also normal to just ignore events you don't care about in your event + * loop without calling this function. + * + * This function only affects currently queued events. If you want to make + * sure that all pending OS events are flushed, you can call SDL_PumpEvents() + * on the main thread immediately before the flush call. + * + * \param minType the low end of event type to be cleared, inclusive; see + * SDL_EventType for details. + * \param maxType the high end of event type to be cleared, inclusive; see + * SDL_EventType for details. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FlushEvent + */ +extern DECLSPEC void SDLCALL SDL_FlushEvents(Uint32 minType, Uint32 maxType); + +/** + * Poll for currently pending events. + * + * If `event` is not NULL, the next event is removed from the queue and stored + * in the SDL_Event structure pointed to by `event`. The 1 returned refers to + * this event, immediately stored in the SDL Event structure -- not an event + * to follow. + * + * If `event` is NULL, it simply returns 1 if there is an event in the queue, + * but will not remove it from the queue. + * + * As this function may implicitly call SDL_PumpEvents(), you can only call + * this function in the thread that set the video mode. + * + * SDL_PollEvent() is the favored way of receiving system events since it can + * be done from the main loop and does not suspend the main loop while waiting + * on an event to be posted. + * + * The common practice is to fully process the event queue once every frame, + * usually as a first step before updating the game's state: + * + * ```c + * while (game_is_still_running) { + * SDL_Event event; + * while (SDL_PollEvent(&event)) { // poll until all events are handled! + * // decide what to do with this event. + * } + * + * // update game state, draw the current frame + * } + * ``` + * + * \param event the SDL_Event structure to be filled with the next event from + * the queue, or NULL. + * \returns 1 if there is a pending event or 0 if there are none available. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetEventFilter + * \sa SDL_PeepEvents + * \sa SDL_PushEvent + * \sa SDL_SetEventFilter + * \sa SDL_WaitEvent + * \sa SDL_WaitEventTimeout + */ +extern DECLSPEC int SDLCALL SDL_PollEvent(SDL_Event * event); + +/** + * Wait indefinitely for the next available event. + * + * If `event` is not NULL, the next event is removed from the queue and stored + * in the SDL_Event structure pointed to by `event`. + * + * As this function may implicitly call SDL_PumpEvents(), you can only call + * this function in the thread that initialized the video subsystem. + * + * \param event the SDL_Event structure to be filled in with the next event + * from the queue, or NULL. + * \returns 1 on success or 0 if there was an error while waiting for events; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PollEvent + * \sa SDL_PumpEvents + * \sa SDL_WaitEventTimeout + */ +extern DECLSPEC int SDLCALL SDL_WaitEvent(SDL_Event * event); + +/** + * Wait until the specified timeout (in milliseconds) for the next available + * event. + * + * If `event` is not NULL, the next event is removed from the queue and stored + * in the SDL_Event structure pointed to by `event`. + * + * As this function may implicitly call SDL_PumpEvents(), you can only call + * this function in the thread that initialized the video subsystem. + * + * \param event the SDL_Event structure to be filled in with the next event + * from the queue, or NULL. + * \param timeout the maximum number of milliseconds to wait for the next + * available event. + * \returns 1 on success or 0 if there was an error while waiting for events; + * call SDL_GetError() for more information. This also returns 0 if + * the timeout elapsed without an event arriving. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PollEvent + * \sa SDL_PumpEvents + * \sa SDL_WaitEvent + */ +extern DECLSPEC int SDLCALL SDL_WaitEventTimeout(SDL_Event * event, + int timeout); + +/** + * Add an event to the event queue. + * + * The event queue can actually be used as a two way communication channel. + * Not only can events be read from the queue, but the user can also push + * their own events onto it. `event` is a pointer to the event structure you + * wish to push onto the queue. The event is copied into the queue, and the + * caller may dispose of the memory pointed to after SDL_PushEvent() returns. + * + * Note: Pushing device input events onto the queue doesn't modify the state + * of the device within SDL. + * + * This function is thread-safe, and can be called from other threads safely. + * + * Note: Events pushed onto the queue with SDL_PushEvent() get passed through + * the event filter but events added with SDL_PeepEvents() do not. + * + * For pushing application-specific events, please use SDL_RegisterEvents() to + * get an event type that does not conflict with other code that also wants + * its own custom event types. + * + * \param event the SDL_Event to be added to the queue. + * \returns 1 on success, 0 if the event was filtered, or a negative error + * code on failure; call SDL_GetError() for more information. A + * common reason for error is the event queue being full. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PeepEvents + * \sa SDL_PollEvent + * \sa SDL_RegisterEvents + */ +extern DECLSPEC int SDLCALL SDL_PushEvent(SDL_Event * event); + +/** + * A function pointer used for callbacks that watch the event queue. + * + * \param userdata what was passed as `userdata` to SDL_SetEventFilter() or + * SDL_AddEventWatch, etc. + * \param event the event that triggered the callback. + * \returns 1 to permit event to be added to the queue, and 0 to disallow it. + * When used with SDL_AddEventWatch, the return value is ignored. + * + * \sa SDL_SetEventFilter + * \sa SDL_AddEventWatch + */ +typedef int (SDLCALL * SDL_EventFilter) (void *userdata, SDL_Event * event); + +/** + * Set up a filter to process all events before they change internal state and + * are posted to the internal event queue. + * + * If the filter function returns 1 when called, then the event will be added + * to the internal queue. If it returns 0, then the event will be dropped from + * the queue, but the internal state will still be updated. This allows + * selective filtering of dynamically arriving events. + * + * **WARNING**: Be very careful of what you do in the event filter function, + * as it may run in a different thread! + * + * On platforms that support it, if the quit event is generated by an + * interrupt signal (e.g. pressing Ctrl-C), it will be delivered to the + * application at the next event poll. + * + * There is one caveat when dealing with the SDL_QuitEvent event type. The + * event filter is only called when the window manager desires to close the + * application window. If the event filter returns 1, then the window will be + * closed, otherwise the window will remain open if possible. + * + * Note: Disabled events never make it to the event filter function; see + * SDL_EventState(). + * + * Note: If you just want to inspect events without filtering, you should use + * SDL_AddEventWatch() instead. + * + * Note: Events pushed onto the queue with SDL_PushEvent() get passed through + * the event filter, but events pushed onto the queue with SDL_PeepEvents() do + * not. + * + * \param filter An SDL_EventFilter function to call when an event happens. + * \param userdata a pointer that is passed to `filter`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AddEventWatch + * \sa SDL_EventState + * \sa SDL_GetEventFilter + * \sa SDL_PeepEvents + * \sa SDL_PushEvent + */ +extern DECLSPEC void SDLCALL SDL_SetEventFilter(SDL_EventFilter filter, + void *userdata); + +/** + * Query the current event filter. + * + * This function can be used to "chain" filters, by saving the existing filter + * before replacing it with a function that will call that saved filter. + * + * \param filter the current callback function will be stored here. + * \param userdata the pointer that is passed to the current event filter will + * be stored here. + * \returns SDL_TRUE on success or SDL_FALSE if there is no event filter set. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetEventFilter + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GetEventFilter(SDL_EventFilter * filter, + void **userdata); + +/** + * Add a callback to be triggered when an event is added to the event queue. + * + * `filter` will be called when an event happens, and its return value is + * ignored. + * + * **WARNING**: Be very careful of what you do in the event filter function, + * as it may run in a different thread! + * + * If the quit event is generated by a signal (e.g. SIGINT), it will bypass + * the internal queue and be delivered to the watch callback immediately, and + * arrive at the next event poll. + * + * Note: the callback is called for events posted by the user through + * SDL_PushEvent(), but not for disabled events, nor for events by a filter + * callback set with SDL_SetEventFilter(), nor for events posted by the user + * through SDL_PeepEvents(). + * + * \param filter an SDL_EventFilter function to call when an event happens. + * \param userdata a pointer that is passed to `filter`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_DelEventWatch + * \sa SDL_SetEventFilter + */ +extern DECLSPEC void SDLCALL SDL_AddEventWatch(SDL_EventFilter filter, + void *userdata); + +/** + * Remove an event watch callback added with SDL_AddEventWatch(). + * + * This function takes the same input as SDL_AddEventWatch() to identify and + * delete the corresponding callback. + * + * \param filter the function originally passed to SDL_AddEventWatch(). + * \param userdata the pointer originally passed to SDL_AddEventWatch(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AddEventWatch + */ +extern DECLSPEC void SDLCALL SDL_DelEventWatch(SDL_EventFilter filter, + void *userdata); + +/** + * Run a specific filter function on the current event queue, removing any + * events for which the filter returns 0. + * + * See SDL_SetEventFilter() for more information. Unlike SDL_SetEventFilter(), + * this function does not change the filter permanently, it only uses the + * supplied filter until this function returns. + * + * \param filter the SDL_EventFilter function to call when an event happens. + * \param userdata a pointer that is passed to `filter`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetEventFilter + * \sa SDL_SetEventFilter + */ +extern DECLSPEC void SDLCALL SDL_FilterEvents(SDL_EventFilter filter, + void *userdata); + +/* @{ */ +#define SDL_QUERY -1 +#define SDL_IGNORE 0 +#define SDL_DISABLE 0 +#define SDL_ENABLE 1 + +/** + * Set the state of processing events by type. + * + * `state` may be any of the following: + * + * - `SDL_QUERY`: returns the current processing state of the specified event + * - `SDL_IGNORE` (aka `SDL_DISABLE`): the event will automatically be dropped + * from the event queue and will not be filtered + * - `SDL_ENABLE`: the event will be processed normally + * + * \param type the type of event; see SDL_EventType for details. + * \param state how to process the event. + * \returns `SDL_DISABLE` or `SDL_ENABLE`, representing the processing state + * of the event before this function makes any changes to it. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetEventState + */ +extern DECLSPEC Uint8 SDLCALL SDL_EventState(Uint32 type, int state); +/* @} */ +#define SDL_GetEventState(type) SDL_EventState(type, SDL_QUERY) + +/** + * Allocate a set of user-defined events, and return the beginning event + * number for that set of events. + * + * Calling this function with `numevents` <= 0 is an error and will return + * (Uint32)-1. + * + * Note, (Uint32)-1 means the maximum unsigned 32-bit integer value (or + * 0xFFFFFFFF), but is clearer to write. + * + * \param numevents the number of events to be allocated. + * \returns the beginning event number, or (Uint32)-1 if there are not enough + * user-defined events left. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PushEvent + */ +extern DECLSPEC Uint32 SDLCALL SDL_RegisterEvents(int numevents); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_events_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_filesystem.h b/third_party/SDL2/include/SDL_filesystem.h new file mode 100644 index 00000000000..c72a6165fe5 --- /dev/null +++ b/third_party/SDL2/include/SDL_filesystem.h @@ -0,0 +1,149 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryFilesystem + * + * Include file for filesystem SDL API functions + */ + +#ifndef SDL_filesystem_h_ +#define SDL_filesystem_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Get the directory where the application was run from. + * + * This is not necessarily a fast call, so you should call this once near + * startup and save the string if you need it. + * + * **Mac OS X and iOS Specific Functionality**: If the application is in a + * ".app" bundle, this function returns the Resource directory (e.g. + * MyApp.app/Contents/Resources/). This behaviour can be overridden by adding + * a property to the Info.plist file. Adding a string key with the name + * SDL_FILESYSTEM_BASE_DIR_TYPE with a supported value will change the + * behaviour. + * + * Supported values for the SDL_FILESYSTEM_BASE_DIR_TYPE property (Given an + * application in /Applications/SDLApp/MyApp.app): + * + * - `resource`: bundle resource directory (the default). For example: + * `/Applications/SDLApp/MyApp.app/Contents/Resources` + * - `bundle`: the Bundle directory. For example: + * `/Applications/SDLApp/MyApp.app/` + * - `parent`: the containing directory of the bundle. For example: + * `/Applications/SDLApp/` + * + * **Nintendo 3DS Specific Functionality**: This function returns "romfs" + * directory of the application as it is uncommon to store resources outside + * the executable. As such it is not a writable directory. + * + * The returned path is guaranteed to end with a path separator ('\\' on + * Windows, '/' on most other platforms). + * + * The pointer returned is owned by the caller. Please call SDL_free() on the + * pointer when done with it. + * + * \returns an absolute path in UTF-8 encoding to the application data + * directory. NULL will be returned on error or when the platform + * doesn't implement this functionality, call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.1. + * + * \sa SDL_GetPrefPath + */ +extern DECLSPEC char *SDLCALL SDL_GetBasePath(void); + +/** + * Get the user-and-app-specific path where files can be written. + * + * Get the "pref dir". This is meant to be where users can write personal + * files (preferences and save games, etc) that are specific to your + * application. This directory is unique per user, per application. + * + * This function will decide the appropriate location in the native + * filesystem, create the directory if necessary, and return a string of the + * absolute path to the directory in UTF-8 encoding. + * + * On Windows, the string might look like: + * + * `C:\\Users\\bob\\AppData\\Roaming\\My Company\\My Program Name\\` + * + * On Linux, the string might look like: + * + * `/home/bob/.local/share/My Program Name/` + * + * On Mac OS X, the string might look like: + * + * `/Users/bob/Library/Application Support/My Program Name/` + * + * You should assume the path returned by this function is the only safe place + * to write files (and that SDL_GetBasePath(), while it might be writable, or + * even the parent of the returned path, isn't where you should be writing + * things). + * + * Both the org and app strings may become part of a directory name, so please + * follow these rules: + * + * - Try to use the same org string (_including case-sensitivity_) for all + * your applications that use this function. + * - Always use a unique app string for each one, and make sure it never + * changes for an app once you've decided on it. + * - Unicode characters are legal, as long as it's UTF-8 encoded, but... + * - ...only use letters, numbers, and spaces. Avoid punctuation like "Game + * Name 2: Bad Guy's Revenge!" ... "Game Name 2" is sufficient. + * + * The returned path is guaranteed to end with a path separator ('\\' on + * Windows, '/' on most other platforms). + * + * The pointer returned is owned by the caller. Please call SDL_free() on the + * pointer when done with it. + * + * \param org the name of your organization. + * \param app the name of your application. + * \returns a UTF-8 string of the user directory in platform-dependent + * notation. NULL if there's a problem (creating directory failed, + * etc.). + * + * \since This function is available since SDL 2.0.1. + * + * \sa SDL_GetBasePath + */ +extern DECLSPEC char *SDLCALL SDL_GetPrefPath(const char *org, const char *app); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_filesystem_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_gamecontroller.h b/third_party/SDL2/include/SDL_gamecontroller.h new file mode 100644 index 00000000000..4d8bcce22bd --- /dev/null +++ b/third_party/SDL2/include/SDL_gamecontroller.h @@ -0,0 +1,1110 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: GameController */ + +/** + * # CategoryGameController + * + * Include file for SDL game controller event handling + */ + +#ifndef SDL_gamecontroller_h_ +#define SDL_gamecontroller_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_rwops.h" +#include "SDL_sensor.h" +#include "SDL_joystick.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \file SDL_gamecontroller.h + * + * In order to use these functions, SDL_Init() must have been called + * with the SDL_INIT_GAMECONTROLLER flag. This causes SDL to scan the system + * for game controllers, and load appropriate drivers. + * + * If you would like to receive controller updates while the application + * is in the background, you should set the following hint before calling + * SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS + */ + +/** + * The gamecontroller structure used to identify an SDL game controller + */ +struct _SDL_GameController; +typedef struct _SDL_GameController SDL_GameController; + +typedef enum SDL_GameControllerType +{ + SDL_CONTROLLER_TYPE_UNKNOWN = 0, + SDL_CONTROLLER_TYPE_XBOX360, + SDL_CONTROLLER_TYPE_XBOXONE, + SDL_CONTROLLER_TYPE_PS3, + SDL_CONTROLLER_TYPE_PS4, + SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO, + SDL_CONTROLLER_TYPE_VIRTUAL, + SDL_CONTROLLER_TYPE_PS5, + SDL_CONTROLLER_TYPE_AMAZON_LUNA, + SDL_CONTROLLER_TYPE_GOOGLE_STADIA, + SDL_CONTROLLER_TYPE_NVIDIA_SHIELD, + SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT, + SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT, + SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR, + SDL_CONTROLLER_TYPE_MAX +} SDL_GameControllerType; + +typedef enum SDL_GameControllerBindType +{ + SDL_CONTROLLER_BINDTYPE_NONE = 0, + SDL_CONTROLLER_BINDTYPE_BUTTON, + SDL_CONTROLLER_BINDTYPE_AXIS, + SDL_CONTROLLER_BINDTYPE_HAT +} SDL_GameControllerBindType; + +/** + * Get the SDL joystick layer binding for this controller button/axis mapping + */ +typedef struct SDL_GameControllerButtonBind +{ + SDL_GameControllerBindType bindType; + union + { + int button; + int axis; + struct { + int hat; + int hat_mask; + } hat; + } value; + +} SDL_GameControllerButtonBind; + + +/** + * To count the number of game controllers in the system for the following: + * + * ```c + * int nJoysticks = SDL_NumJoysticks(); + * int nGameControllers = 0; + * for (int i = 0; i < nJoysticks; i++) { + * if (SDL_IsGameController(i)) { + * nGameControllers++; + * } + * } + * ``` + * + * Using the SDL_HINT_GAMECONTROLLERCONFIG hint or the SDL_GameControllerAddMapping() you can add support for controllers SDL is unaware of or cause an existing controller to have a different binding. The format is: + * guid,name,mappings + * + * Where GUID is the string value from SDL_JoystickGetGUIDString(), name is the human readable string for the device and mappings are controller mappings to joystick ones. + * Under Windows there is a reserved GUID of "xinput" that covers any XInput devices. + * The mapping format for joystick is: + * bX - a joystick button, index X + * hX.Y - hat X with value Y + * aX - axis X of the joystick + * Buttons can be used as a controller axis and vice versa. + * + * This string shows an example of a valid mapping for a controller + * + * ```c + * "03000000341a00003608000000000000,PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7", + * ``` + */ + +/** + * Load a set of Game Controller mappings from a seekable SDL data stream. + * + * You can call this function several times, if needed, to load different + * database files. + * + * If a new mapping is loaded for an already known controller GUID, the later + * version will overwrite the one currently loaded. + * + * If this function is called before SDL_Init, SDL will generate an + * SDL_CONTROLLERDEVICEADDED event for matching controllers that are plugged + * in at the time that SDL_Init is called. + * + * Mappings not belonging to the current platform or with no platform field + * specified will be ignored (i.e. mappings for Linux will be ignored in + * Windows, etc). + * + * This function will load the text database entirely in memory before + * processing it, so take this into consideration if you are in a memory + * constrained environment. + * + * \param rw the data stream for the mappings to be added. + * \param freerw non-zero to close the stream after being read. + * \returns the number of mappings added or -1 on error; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_GameControllerAddMapping + * \sa SDL_GameControllerAddMappingsFromFile + * \sa SDL_GameControllerMappingForGUID + * \sa SDL_CONTROLLERDEVICEADDED + */ +extern DECLSPEC int SDLCALL SDL_GameControllerAddMappingsFromRW(SDL_RWops * rw, int freerw); + +/** + * Load a set of mappings from a file, filtered by the current + * SDL_GetPlatform() + * + * Convenience macro. + */ +#define SDL_GameControllerAddMappingsFromFile(file) SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), 1) + +/** + * Add support for controllers that SDL is unaware of or to cause an existing + * controller to have a different binding. + * + * The mapping string has the format "GUID,name,mapping", where GUID is the + * string value from SDL_JoystickGetGUIDString(), name is the human readable + * string for the device and mappings are controller mappings to joystick + * ones. Under Windows there is a reserved GUID of "xinput" that covers all + * XInput devices. The mapping format for joystick is: {| |bX |a joystick + * button, index X |- |hX.Y |hat X with value Y |- |aX |axis X of the joystick + * |} Buttons can be used as a controller axes and vice versa. + * + * This string shows an example of a valid mapping for a controller: + * + * ```c + * "341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7" + * ``` + * + * If this function is called before SDL_Init, SDL will generate an + * SDL_CONTROLLERDEVICEADDED event for matching controllers that are plugged + * in at the time that SDL_Init is called. + * + * \param mappingString the mapping string. + * \returns 1 if a new mapping is added, 0 if an existing mapping is updated, + * -1 on error; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerMapping + * \sa SDL_GameControllerMappingForGUID + * \sa SDL_CONTROLLERDEVICEADDED + */ +extern DECLSPEC int SDLCALL SDL_GameControllerAddMapping(const char* mappingString); + +/** + * Get the number of mappings installed. + * + * \returns the number of mappings. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerNumMappings(void); + +/** + * Get the mapping at a particular index. + * + * \returns the mapping string. Must be freed with SDL_free(). Returns NULL if + * the index is out of range. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForIndex(int mapping_index); + +/** + * Get the game controller mapping string for a given GUID. + * + * The returned string must be freed with SDL_free(). + * + * \param guid a structure containing the GUID for which a mapping is desired. + * \returns a mapping string or NULL on error; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetDeviceGUID + * \sa SDL_JoystickGetGUID + */ +extern DECLSPEC char * SDLCALL SDL_GameControllerMappingForGUID(SDL_JoystickGUID guid); + +/** + * Get the current mapping of a Game Controller. + * + * The returned string must be freed with SDL_free(). + * + * Details about mappings are discussed with SDL_GameControllerAddMapping(). + * + * \param gamecontroller the game controller you want to get the current + * mapping for. + * \returns a string that has the controller's mapping or NULL if no mapping + * is available; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerAddMapping + * \sa SDL_GameControllerMappingForGUID + */ +extern DECLSPEC char * SDLCALL SDL_GameControllerMapping(SDL_GameController *gamecontroller); + +/** + * Check if the given joystick is supported by the game controller interface. + * + * `joystick_index` is the same as the `device_index` passed to + * SDL_JoystickOpen(). + * + * \param joystick_index the device_index of a device, up to + * SDL_NumJoysticks(). + * \returns SDL_TRUE if the given joystick is supported by the game controller + * interface, SDL_FALSE if it isn't or it's an invalid index. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerNameForIndex + * \sa SDL_GameControllerOpen + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsGameController(int joystick_index); + +/** + * Get the implementation dependent name for the game controller. + * + * This function can be called before any controllers are opened. + * + * `joystick_index` is the same as the `device_index` passed to + * SDL_JoystickOpen(). + * + * \param joystick_index the device_index of a device, from zero to + * SDL_NumJoysticks()-1. + * \returns the implementation-dependent name for the game controller, or NULL + * if there is no name or the index is invalid. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerName + * \sa SDL_GameControllerOpen + * \sa SDL_IsGameController + */ +extern DECLSPEC const char *SDLCALL SDL_GameControllerNameForIndex(int joystick_index); + +/** + * Get the implementation dependent path for the game controller. + * + * This function can be called before any controllers are opened. + * + * `joystick_index` is the same as the `device_index` passed to + * SDL_JoystickOpen(). + * + * \param joystick_index the device_index of a device, from zero to + * SDL_NumJoysticks()-1. + * \returns the implementation-dependent path for the game controller, or NULL + * if there is no path or the index is invalid. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GameControllerPath + */ +extern DECLSPEC const char *SDLCALL SDL_GameControllerPathForIndex(int joystick_index); + +/** + * Get the type of a game controller. + * + * This can be called before any controllers are opened. + * + * \param joystick_index the device_index of a device, from zero to + * SDL_NumJoysticks()-1. + * \returns the controller type. + * + * \since This function is available since SDL 2.0.12. + */ +extern DECLSPEC SDL_GameControllerType SDLCALL SDL_GameControllerTypeForIndex(int joystick_index); + +/** + * Get the mapping of a game controller. + * + * This can be called before any controllers are opened. + * + * \param joystick_index the device_index of a device, from zero to + * SDL_NumJoysticks()-1. + * \returns the mapping string. Must be freed with SDL_free(). Returns NULL if + * no mapping is available. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC char *SDLCALL SDL_GameControllerMappingForDeviceIndex(int joystick_index); + +/** + * Open a game controller for use. + * + * `joystick_index` is the same as the `device_index` passed to + * SDL_JoystickOpen(). + * + * The index passed as an argument refers to the N'th game controller on the + * system. This index is not the value which will identify this controller in + * future controller events. The joystick's instance id (SDL_JoystickID) will + * be used there instead. + * + * \param joystick_index the device_index of a device, up to + * SDL_NumJoysticks(). + * \returns a gamecontroller identifier or NULL if an error occurred; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerClose + * \sa SDL_GameControllerNameForIndex + * \sa SDL_IsGameController + */ +extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerOpen(int joystick_index); + +/** + * Get the SDL_GameController associated with an instance id. + * + * \param joyid the instance id to get the SDL_GameController for. + * \returns an SDL_GameController on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.4. + */ +extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerFromInstanceID(SDL_JoystickID joyid); + +/** + * Get the SDL_GameController associated with a player index. + * + * Please note that the player index is _not_ the device index, nor is it the + * instance id! + * + * \param player_index the player index, which is not the device index or the + * instance id! + * \returns the SDL_GameController associated with a player index. + * + * \since This function is available since SDL 2.0.12. + * + * \sa SDL_GameControllerGetPlayerIndex + * \sa SDL_GameControllerSetPlayerIndex + */ +extern DECLSPEC SDL_GameController *SDLCALL SDL_GameControllerFromPlayerIndex(int player_index); + +/** + * Get the implementation-dependent name for an opened game controller. + * + * This is the same name as returned by SDL_GameControllerNameForIndex(), but + * it takes a controller identifier instead of the (unstable) device index. + * + * \param gamecontroller a game controller identifier previously returned by + * SDL_GameControllerOpen(). + * \returns the implementation dependent name for the game controller, or NULL + * if there is no name or the identifier passed is invalid. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerNameForIndex + * \sa SDL_GameControllerOpen + */ +extern DECLSPEC const char *SDLCALL SDL_GameControllerName(SDL_GameController *gamecontroller); + +/** + * Get the implementation-dependent path for an opened game controller. + * + * This is the same path as returned by SDL_GameControllerNameForIndex(), but + * it takes a controller identifier instead of the (unstable) device index. + * + * \param gamecontroller a game controller identifier previously returned by + * SDL_GameControllerOpen(). + * \returns the implementation dependent path for the game controller, or NULL + * if there is no path or the identifier passed is invalid. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GameControllerPathForIndex + */ +extern DECLSPEC const char *SDLCALL SDL_GameControllerPath(SDL_GameController *gamecontroller); + +/** + * Get the type of this currently opened controller + * + * This is the same name as returned by SDL_GameControllerTypeForIndex(), but + * it takes a controller identifier instead of the (unstable) device index. + * + * \param gamecontroller the game controller object to query. + * \returns the controller type. + * + * \since This function is available since SDL 2.0.12. + */ +extern DECLSPEC SDL_GameControllerType SDLCALL SDL_GameControllerGetType(SDL_GameController *gamecontroller); + +/** + * Get the player index of an opened game controller. + * + * For XInput controllers this returns the XInput user index. + * + * \param gamecontroller the game controller object to query. + * \returns the player index for controller, or -1 if it's not available. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerGetPlayerIndex(SDL_GameController *gamecontroller); + +/** + * Set the player index of an opened game controller. + * + * \param gamecontroller the game controller object to adjust. + * \param player_index Player index to assign to this controller, or -1 to + * clear the player index and turn off player LEDs. + * + * \since This function is available since SDL 2.0.12. + */ +extern DECLSPEC void SDLCALL SDL_GameControllerSetPlayerIndex(SDL_GameController *gamecontroller, int player_index); + +/** + * Get the USB vendor ID of an opened controller, if available. + * + * If the vendor ID isn't available this function returns 0. + * + * \param gamecontroller the game controller object to query. + * \return the USB vendor ID, or zero if unavailable. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetVendor(SDL_GameController *gamecontroller); + +/** + * Get the USB product ID of an opened controller, if available. + * + * If the product ID isn't available this function returns 0. + * + * \param gamecontroller the game controller object to query. + * \return the USB product ID, or zero if unavailable. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProduct(SDL_GameController *gamecontroller); + +/** + * Get the product version of an opened controller, if available. + * + * If the product version isn't available this function returns 0. + * + * \param gamecontroller the game controller object to query. + * \return the USB product version, or zero if unavailable. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetProductVersion(SDL_GameController *gamecontroller); + +/** + * Get the firmware version of an opened controller, if available. + * + * If the firmware version isn't available this function returns 0. + * + * \param gamecontroller the game controller object to query. + * \return the controller firmware version, or zero if unavailable. + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC Uint16 SDLCALL SDL_GameControllerGetFirmwareVersion(SDL_GameController *gamecontroller); + +/** + * Get the serial number of an opened controller, if available. + * + * Returns the serial number of the controller, or NULL if it is not + * available. + * + * \param gamecontroller the game controller object to query. + * \return the serial number, or NULL if unavailable. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC const char * SDLCALL SDL_GameControllerGetSerial(SDL_GameController *gamecontroller); + +/** + * Get the Steam Input handle of an opened controller, if available. + * + * Returns an InputHandle_t for the controller that can be used with Steam + * Input API: https://partner.steamgames.com/doc/api/ISteamInput + * + * \param gamecontroller the game controller object to query. + * \returns the gamepad handle, or 0 if unavailable. + * + * \since This function is available since SDL 2.30.0. + */ +extern DECLSPEC Uint64 SDLCALL SDL_GameControllerGetSteamHandle(SDL_GameController *gamecontroller); + + +/** + * Check if a controller has been opened and is currently connected. + * + * \param gamecontroller a game controller identifier previously returned by + * SDL_GameControllerOpen(). + * \returns SDL_TRUE if the controller has been opened and is currently + * connected, or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerClose + * \sa SDL_GameControllerOpen + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerGetAttached(SDL_GameController *gamecontroller); + +/** + * Get the Joystick ID from a Game Controller. + * + * This function will give you a SDL_Joystick object, which allows you to use + * the SDL_Joystick functions with a SDL_GameController object. This would be + * useful for getting a joystick's position at any given time, even if it + * hasn't moved (moving it would produce an event, which would have the axis' + * value). + * + * The pointer returned is owned by the SDL_GameController. You should not + * call SDL_JoystickClose() on it, for example, since doing so will likely + * cause SDL to crash. + * + * \param gamecontroller the game controller object that you want to get a + * joystick from. + * \returns a SDL_Joystick object; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_Joystick *SDLCALL SDL_GameControllerGetJoystick(SDL_GameController *gamecontroller); + +/** + * Query or change current state of Game Controller events. + * + * If controller events are disabled, you must call SDL_GameControllerUpdate() + * yourself and check the state of the controller when you want controller + * information. + * + * Any number can be passed to SDL_GameControllerEventState(), but only -1, 0, + * and 1 will have any effect. Other numbers will just be returned. + * + * \param state can be one of `SDL_QUERY`, `SDL_IGNORE`, or `SDL_ENABLE`. + * \returns the same value passed to the function, with exception to -1 + * (SDL_QUERY), which will return the current state. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickEventState + */ +extern DECLSPEC int SDLCALL SDL_GameControllerEventState(int state); + +/** + * Manually pump game controller updates if not using the loop. + * + * This function is called automatically by the event loop if events are + * enabled. Under such circumstances, it will not be necessary to call this + * function. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC void SDLCALL SDL_GameControllerUpdate(void); + + +/** + * The list of axes available from a controller + * + * Thumbstick axis values range from SDL_JOYSTICK_AXIS_MIN to + * SDL_JOYSTICK_AXIS_MAX, and are centered within ~8000 of zero, though + * advanced UI will allow users to set or autodetect the dead zone, which + * varies between controllers. + * + * Trigger axis values range from 0 (released) to SDL_JOYSTICK_AXIS_MAX (fully + * pressed) when reported by SDL_GameControllerGetAxis(). Note that this is + * not the same range that will be reported by the lower-level + * SDL_GetJoystickAxis(). + */ +typedef enum SDL_GameControllerAxis +{ + SDL_CONTROLLER_AXIS_INVALID = -1, + SDL_CONTROLLER_AXIS_LEFTX, + SDL_CONTROLLER_AXIS_LEFTY, + SDL_CONTROLLER_AXIS_RIGHTX, + SDL_CONTROLLER_AXIS_RIGHTY, + SDL_CONTROLLER_AXIS_TRIGGERLEFT, + SDL_CONTROLLER_AXIS_TRIGGERRIGHT, + SDL_CONTROLLER_AXIS_MAX +} SDL_GameControllerAxis; + +/** + * Convert a string into SDL_GameControllerAxis enum. + * + * This function is called internally to translate SDL_GameController mapping + * strings for the underlying joystick device into the consistent + * SDL_GameController mapping. You do not normally need to call this function + * unless you are parsing SDL_GameController mappings in your own code. + * + * Note specially that "righttrigger" and "lefttrigger" map to + * `SDL_CONTROLLER_AXIS_TRIGGERRIGHT` and `SDL_CONTROLLER_AXIS_TRIGGERLEFT`, + * respectively. + * + * \param str string representing a SDL_GameController axis. + * \returns the SDL_GameControllerAxis enum corresponding to the input string, + * or `SDL_CONTROLLER_AXIS_INVALID` if no match was found. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerGetStringForAxis + */ +extern DECLSPEC SDL_GameControllerAxis SDLCALL SDL_GameControllerGetAxisFromString(const char *str); + +/** + * Convert from an SDL_GameControllerAxis enum to a string. + * + * The caller should not SDL_free() the returned string. + * + * \param axis an enum value for a given SDL_GameControllerAxis. + * \returns a string for the given axis, or NULL if an invalid axis is + * specified. The string returned is of the format used by + * SDL_GameController mapping strings. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerGetAxisFromString + */ +extern DECLSPEC const char* SDLCALL SDL_GameControllerGetStringForAxis(SDL_GameControllerAxis axis); + +/** + * Get the SDL joystick layer binding for a controller axis mapping. + * + * \param gamecontroller a game controller. + * \param axis an axis enum value (one of the SDL_GameControllerAxis values). + * \returns a SDL_GameControllerButtonBind describing the bind. On failure + * (like the given Controller axis doesn't exist on the device), its + * `.bindType` will be `SDL_CONTROLLER_BINDTYPE_NONE`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerGetBindForButton + */ +extern DECLSPEC SDL_GameControllerButtonBind SDLCALL +SDL_GameControllerGetBindForAxis(SDL_GameController *gamecontroller, + SDL_GameControllerAxis axis); + +/** + * Query whether a game controller has a given axis. + * + * This merely reports whether the controller's mapping defined this axis, as + * that is all the information SDL has about the physical device. + * + * \param gamecontroller a game controller. + * \param axis an axis enum value (an SDL_GameControllerAxis value). + * \returns SDL_TRUE if the controller has this axis, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_bool SDLCALL +SDL_GameControllerHasAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis); + +/** + * Get the current state of an axis control on a game controller. + * + * The axis indices start at index 0. + * + * For thumbsticks, the state is a value ranging from -32768 (up/left) to + * 32767 (down/right). + * + * Triggers range from 0 when released to 32767 when fully pressed, and never + * return a negative value. Note that this differs from the value reported by + * the lower-level SDL_JoystickGetAxis(), which normally uses the full range. + * + * \param gamecontroller a game controller. + * \param axis an axis index (one of the SDL_GameControllerAxis values). + * \returns axis state (including 0) on success or 0 (also) on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerGetButton + */ +extern DECLSPEC Sint16 SDLCALL +SDL_GameControllerGetAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis); + +/** + * The list of buttons available from a controller + */ +typedef enum SDL_GameControllerButton +{ + SDL_CONTROLLER_BUTTON_INVALID = -1, + SDL_CONTROLLER_BUTTON_A, + SDL_CONTROLLER_BUTTON_B, + SDL_CONTROLLER_BUTTON_X, + SDL_CONTROLLER_BUTTON_Y, + SDL_CONTROLLER_BUTTON_BACK, + SDL_CONTROLLER_BUTTON_GUIDE, + SDL_CONTROLLER_BUTTON_START, + SDL_CONTROLLER_BUTTON_LEFTSTICK, + SDL_CONTROLLER_BUTTON_RIGHTSTICK, + SDL_CONTROLLER_BUTTON_LEFTSHOULDER, + SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, + SDL_CONTROLLER_BUTTON_DPAD_UP, + SDL_CONTROLLER_BUTTON_DPAD_DOWN, + SDL_CONTROLLER_BUTTON_DPAD_LEFT, + SDL_CONTROLLER_BUTTON_DPAD_RIGHT, + SDL_CONTROLLER_BUTTON_MISC1, /* Xbox Series X share button, PS5 microphone button, Nintendo Switch Pro capture button, Amazon Luna microphone button */ + SDL_CONTROLLER_BUTTON_PADDLE1, /* Xbox Elite paddle P1 (upper left, facing the back) */ + SDL_CONTROLLER_BUTTON_PADDLE2, /* Xbox Elite paddle P3 (upper right, facing the back) */ + SDL_CONTROLLER_BUTTON_PADDLE3, /* Xbox Elite paddle P2 (lower left, facing the back) */ + SDL_CONTROLLER_BUTTON_PADDLE4, /* Xbox Elite paddle P4 (lower right, facing the back) */ + SDL_CONTROLLER_BUTTON_TOUCHPAD, /* PS4/PS5 touchpad button */ + SDL_CONTROLLER_BUTTON_MAX +} SDL_GameControllerButton; + +/** + * Convert a string into an SDL_GameControllerButton enum. + * + * This function is called internally to translate SDL_GameController mapping + * strings for the underlying joystick device into the consistent + * SDL_GameController mapping. You do not normally need to call this function + * unless you are parsing SDL_GameController mappings in your own code. + * + * \param str string representing a SDL_GameController axis. + * \returns the SDL_GameControllerButton enum corresponding to the input + * string, or `SDL_CONTROLLER_AXIS_INVALID` if no match was found. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_GameControllerButton SDLCALL SDL_GameControllerGetButtonFromString(const char *str); + +/** + * Convert from an SDL_GameControllerButton enum to a string. + * + * The caller should not SDL_free() the returned string. + * + * \param button an enum value for a given SDL_GameControllerButton. + * \returns a string for the given button, or NULL if an invalid button is + * specified. The string returned is of the format used by + * SDL_GameController mapping strings. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerGetButtonFromString + */ +extern DECLSPEC const char* SDLCALL SDL_GameControllerGetStringForButton(SDL_GameControllerButton button); + +/** + * Get the SDL joystick layer binding for a controller button mapping. + * + * \param gamecontroller a game controller. + * \param button an button enum value (an SDL_GameControllerButton value). + * \returns a SDL_GameControllerButtonBind describing the bind. On failure + * (like the given Controller button doesn't exist on the device), + * its `.bindType` will be `SDL_CONTROLLER_BINDTYPE_NONE`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerGetBindForAxis + */ +extern DECLSPEC SDL_GameControllerButtonBind SDLCALL +SDL_GameControllerGetBindForButton(SDL_GameController *gamecontroller, + SDL_GameControllerButton button); + +/** + * Query whether a game controller has a given button. + * + * This merely reports whether the controller's mapping defined this button, + * as that is all the information SDL has about the physical device. + * + * \param gamecontroller a game controller. + * \param button a button enum value (an SDL_GameControllerButton value). + * \returns SDL_TRUE if the controller has this button, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasButton(SDL_GameController *gamecontroller, + SDL_GameControllerButton button); + +/** + * Get the current state of a button on a game controller. + * + * \param gamecontroller a game controller. + * \param button a button index (one of the SDL_GameControllerButton values). + * \returns 1 for pressed state or 0 for not pressed state or error; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerGetAxis + */ +extern DECLSPEC Uint8 SDLCALL SDL_GameControllerGetButton(SDL_GameController *gamecontroller, + SDL_GameControllerButton button); + +/** + * Get the number of touchpads on a game controller. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerGetNumTouchpads(SDL_GameController *gamecontroller); + +/** + * Get the number of supported simultaneous fingers on a touchpad on a game + * controller. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerGetNumTouchpadFingers(SDL_GameController *gamecontroller, int touchpad); + +/** + * Get the current state of a finger on a touchpad on a game controller. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerGetTouchpadFinger(SDL_GameController *gamecontroller, int touchpad, int finger, Uint8 *state, float *x, float *y, float *pressure); + +/** + * Return whether a game controller has a particular sensor. + * + * \param gamecontroller The controller to query. + * \param type The type of sensor to query. + * \returns SDL_TRUE if the sensor exists, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasSensor(SDL_GameController *gamecontroller, SDL_SensorType type); + +/** + * Set whether data reporting for a game controller sensor is enabled. + * + * \param gamecontroller The controller to update. + * \param type The type of sensor to enable/disable. + * \param enabled Whether data reporting should be enabled. + * \returns 0 or -1 if an error occurred. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerSetSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type, SDL_bool enabled); + +/** + * Query whether sensor data reporting is enabled for a game controller. + * + * \param gamecontroller The controller to query. + * \param type The type of sensor to query. + * \returns SDL_TRUE if the sensor is enabled, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerIsSensorEnabled(SDL_GameController *gamecontroller, SDL_SensorType type); + +/** + * Get the data rate (number of events per second) of a game controller + * sensor. + * + * \param gamecontroller The controller to query. + * \param type The type of sensor to query. + * \return the data rate, or 0.0f if the data rate is not available. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC float SDLCALL SDL_GameControllerGetSensorDataRate(SDL_GameController *gamecontroller, SDL_SensorType type); + +/** + * Get the current state of a game controller sensor. + * + * The number of values and interpretation of the data is sensor dependent. + * See SDL_sensor.h for the details for each type of sensor. + * + * \param gamecontroller The controller to query. + * \param type The type of sensor to query. + * \param data A pointer filled with the current sensor state. + * \param num_values The number of values to write to data. + * \return 0 or -1 if an error occurred. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerGetSensorData(SDL_GameController *gamecontroller, SDL_SensorType type, float *data, int num_values); + +/** + * Get the current state of a game controller sensor with the timestamp of the + * last update. + * + * The number of values and interpretation of the data is sensor dependent. + * See SDL_sensor.h for the details for each type of sensor. + * + * \param gamecontroller The controller to query. + * \param type The type of sensor to query. + * \param timestamp A pointer filled with the timestamp in microseconds of the + * current sensor reading if available, or 0 if not. + * \param data A pointer filled with the current sensor state. + * \param num_values The number of values to write to data. + * \return 0 or -1 if an error occurred. + * + * \since This function is available since SDL 2.26.0. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerGetSensorDataWithTimestamp(SDL_GameController *gamecontroller, SDL_SensorType type, Uint64 *timestamp, float *data, int num_values); + +/** + * Start a rumble effect on a game controller. + * + * Each call to this function cancels any previous rumble effect, and calling + * it with 0 intensity stops any rumbling. + * + * \param gamecontroller The controller to vibrate. + * \param low_frequency_rumble The intensity of the low frequency (left) + * rumble motor, from 0 to 0xFFFF. + * \param high_frequency_rumble The intensity of the high frequency (right) + * rumble motor, from 0 to 0xFFFF. + * \param duration_ms The duration of the rumble effect, in milliseconds. + * \returns 0, or -1 if rumble isn't supported on this controller. + * + * \since This function is available since SDL 2.0.9. + * + * \sa SDL_GameControllerHasRumble + */ +extern DECLSPEC int SDLCALL SDL_GameControllerRumble(SDL_GameController *gamecontroller, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms); + +/** + * Start a rumble effect in the game controller's triggers. + * + * Each call to this function cancels any previous trigger rumble effect, and + * calling it with 0 intensity stops any rumbling. + * + * Note that this is rumbling of the _triggers_ and not the game controller as + * a whole. This is currently only supported on Xbox One controllers. If you + * want the (more common) whole-controller rumble, use + * SDL_GameControllerRumble() instead. + * + * \param gamecontroller The controller to vibrate. + * \param left_rumble The intensity of the left trigger rumble motor, from 0 + * to 0xFFFF. + * \param right_rumble The intensity of the right trigger rumble motor, from 0 + * to 0xFFFF. + * \param duration_ms The duration of the rumble effect, in milliseconds. + * \returns 0, or -1 if trigger rumble isn't supported on this controller. + * + * \since This function is available since SDL 2.0.14. + * + * \sa SDL_GameControllerHasRumbleTriggers + */ +extern DECLSPEC int SDLCALL SDL_GameControllerRumbleTriggers(SDL_GameController *gamecontroller, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms); + +/** + * Query whether a game controller has an LED. + * + * \param gamecontroller The controller to query. + * \returns SDL_TRUE, or SDL_FALSE if this controller does not have a + * modifiable LED. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasLED(SDL_GameController *gamecontroller); + +/** + * Query whether a game controller has rumble support. + * + * \param gamecontroller The controller to query. + * \returns SDL_TRUE, or SDL_FALSE if this controller does not have rumble + * support. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_GameControllerRumble + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasRumble(SDL_GameController *gamecontroller); + +/** + * Query whether a game controller has rumble support on triggers. + * + * \param gamecontroller The controller to query. + * \returns SDL_TRUE, or SDL_FALSE if this controller does not have trigger + * rumble support. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_GameControllerRumbleTriggers + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GameControllerHasRumbleTriggers(SDL_GameController *gamecontroller); + +/** + * Update a game controller's LED color. + * + * \param gamecontroller The controller to update. + * \param red The intensity of the red LED. + * \param green The intensity of the green LED. + * \param blue The intensity of the blue LED. + * \returns 0, or -1 if this controller does not have a modifiable LED. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerSetLED(SDL_GameController *gamecontroller, Uint8 red, Uint8 green, Uint8 blue); + +/** + * Send a controller specific effect packet + * + * \param gamecontroller The controller to affect. + * \param data The data to send to the controller. + * \param size The size of the data to send to the controller. + * \returns 0, or -1 if this controller or driver doesn't support effect + * packets. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC int SDLCALL SDL_GameControllerSendEffect(SDL_GameController *gamecontroller, const void *data, int size); + +/** + * Close a game controller previously opened with SDL_GameControllerOpen(). + * + * \param gamecontroller a game controller identifier previously returned by + * SDL_GameControllerOpen(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerOpen + */ +extern DECLSPEC void SDLCALL SDL_GameControllerClose(SDL_GameController *gamecontroller); + +/** + * Return the sfSymbolsName for a given button on a game controller on Apple + * platforms. + * + * \param gamecontroller the controller to query. + * \param button a button on the game controller. + * \returns the sfSymbolsName or NULL if the name can't be found. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_GameControllerGetAppleSFSymbolsNameForAxis + */ +extern DECLSPEC const char* SDLCALL SDL_GameControllerGetAppleSFSymbolsNameForButton(SDL_GameController *gamecontroller, SDL_GameControllerButton button); + +/** + * Return the sfSymbolsName for a given axis on a game controller on Apple + * platforms. + * + * \param gamecontroller the controller to query. + * \param axis an axis on the game controller. + * \returns the sfSymbolsName or NULL if the name can't be found. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_GameControllerGetAppleSFSymbolsNameForButton + */ +extern DECLSPEC const char* SDLCALL SDL_GameControllerGetAppleSFSymbolsNameForAxis(SDL_GameController *gamecontroller, SDL_GameControllerAxis axis); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_gamecontroller_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_gesture.h b/third_party/SDL2/include/SDL_gesture.h new file mode 100644 index 00000000000..acfa56f31f5 --- /dev/null +++ b/third_party/SDL2/include/SDL_gesture.h @@ -0,0 +1,117 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryGesture + * + * Include file for SDL gesture event handling. + */ + +#ifndef SDL_gesture_h_ +#define SDL_gesture_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_video.h" + +#include "SDL_touch.h" + + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +typedef Sint64 SDL_GestureID; + +/* Function prototypes */ + +/** + * Begin recording a gesture on a specified touch device or all touch devices. + * + * If the parameter `touchId` is -1 (i.e., all devices), this function will + * always return 1, regardless of whether there actually are any devices. + * + * \param touchId the touch device id, or -1 for all touch devices. + * \returns 1 on success or 0 if the specified device could not be found. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetTouchDevice + */ +extern DECLSPEC int SDLCALL SDL_RecordGesture(SDL_TouchID touchId); + + +/** + * Save all currently loaded Dollar Gesture templates. + * + * \param dst a SDL_RWops to save to. + * \returns the number of saved templates on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LoadDollarTemplates + * \sa SDL_SaveDollarTemplate + */ +extern DECLSPEC int SDLCALL SDL_SaveAllDollarTemplates(SDL_RWops *dst); + +/** + * Save a currently loaded Dollar Gesture template. + * + * \param gestureId a gesture id. + * \param dst a SDL_RWops to save to. + * \returns 1 on success or 0 on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LoadDollarTemplates + * \sa SDL_SaveAllDollarTemplates + */ +extern DECLSPEC int SDLCALL SDL_SaveDollarTemplate(SDL_GestureID gestureId,SDL_RWops *dst); + + +/** + * Load Dollar Gesture templates from a file. + * + * \param touchId a touch id. + * \param src a SDL_RWops to load from. + * \returns the number of loaded templates on success or a negative error code + * (or 0) on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SaveAllDollarTemplates + * \sa SDL_SaveDollarTemplate + */ +extern DECLSPEC int SDLCALL SDL_LoadDollarTemplates(SDL_TouchID touchId, SDL_RWops *src); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_gesture_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_guid.h b/third_party/SDL2/include/SDL_guid.h new file mode 100644 index 00000000000..fd9a50e3229 --- /dev/null +++ b/third_party/SDL2/include/SDL_guid.h @@ -0,0 +1,107 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: GUID */ + +/** + * # CategoryGUID + * + * A GUID is a 128-bit value that represents something that is uniquely + * identifiable by this value: "globally unique." + */ + +#ifndef SDL_guid_h_ +#define SDL_guid_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An SDL_GUID is a 128-bit identifier. + * + * This is an acronym for "Globally Unique ID." + * + * While a GUID can be used to assign a unique value to almost anything, in + * SDL these are largely used to identify input devices across runs of SDL + * programs on the same platform.If the device is detached and then + * re-attached to a different port, or if the base system is rebooted, the + * device should still report the same GUID. + * + * GUIDs are as precise as possible but are not guaranteed to distinguish + * physically distinct but equivalent devices. For example, two game + * controllers from the same vendor with the same product ID and revision may + * have the same GUID. + * + * GUIDs may be platform-dependent (i.e., the same device may report different + * GUIDs on different operating systems). + */ +typedef struct SDL_GUID { + Uint8 data[16]; +} SDL_GUID; + +/* Function prototypes */ + +/** + * Get an ASCII string representation for a given SDL_GUID. + * + * You should supply at least 33 bytes for pszGUID. + * + * \param guid the SDL_GUID you wish to convert to string. + * \param pszGUID buffer in which to write the ASCII string. + * \param cbGUID the size of pszGUID. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GUIDFromString + */ +extern DECLSPEC void SDLCALL SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID); + +/** + * Convert a GUID string into a SDL_GUID structure. + * + * Performs no error checking. If this function is given a string containing + * an invalid GUID, the function will silently succeed, but the GUID generated + * will not be useful. + * + * \param pchGUID string containing an ASCII representation of a GUID. + * \returns a SDL_GUID structure. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GUIDToString + */ +extern DECLSPEC SDL_GUID SDLCALL SDL_GUIDFromString(const char *pchGUID); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_guid_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_haptic.h b/third_party/SDL2/include/SDL_haptic.h new file mode 100644 index 00000000000..f679c5734ec --- /dev/null +++ b/third_party/SDL2/include/SDL_haptic.h @@ -0,0 +1,1354 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryHaptic + * + * SDL haptic subsystem allows you to control haptic (force feedback) devices. + * + * The basic usage is as follows: + * + * - Initialize the subsystem (SDL_INIT_HAPTIC). + * - Open a haptic device. + * - SDL_HapticOpen() to open from index. + * - SDL_HapticOpenFromJoystick() to open from an existing joystick. + * - Create an effect (SDL_HapticEffect). + * - Upload the effect with SDL_HapticNewEffect(). + * - Run the effect with SDL_HapticRunEffect(). + * - (optional) Free the effect with SDL_HapticDestroyEffect(). + * - Close the haptic device with SDL_HapticClose(). + * + * Simple rumble example: + * + * ```c + * SDL_Haptic *haptic; + * + * // Open the device + * haptic = SDL_HapticOpen( 0 ); + * if (haptic == NULL) + * return -1; + * + * // Initialize simple rumble + * if (SDL_HapticRumbleInit( haptic ) != 0) + * return -1; + * + * // Play effect at 50% strength for 2 seconds + * if (SDL_HapticRumblePlay( haptic, 0.5, 2000 ) != 0) + * return -1; + * SDL_Delay( 2000 ); + * + * // Clean up + * SDL_HapticClose( haptic ); + * ``` + * + * Complete example: + * + * ```c + * int test_haptic( SDL_Joystick * joystick ) { + * SDL_Haptic *haptic; + * SDL_HapticEffect effect; + * int effect_id; + * + * // Open the device + * haptic = SDL_HapticOpenFromJoystick( joystick ); + * if (haptic == NULL) return -1; // Most likely joystick isn't haptic + * + * // See if it can do sine waves + * if ((SDL_HapticQuery(haptic) & SDL_HAPTIC_SINE)==0) { + * SDL_HapticClose(haptic); // No sine effect + * return -1; + * } + * + * // Create the effect + * SDL_memset( &effect, 0, sizeof(SDL_HapticEffect) ); // 0 is safe default + * effect.type = SDL_HAPTIC_SINE; + * effect.periodic.direction.type = SDL_HAPTIC_POLAR; // Polar coordinates + * effect.periodic.direction.dir[0] = 18000; // Force comes from south + * effect.periodic.period = 1000; // 1000 ms + * effect.periodic.magnitude = 20000; // 20000/32767 strength + * effect.periodic.length = 5000; // 5 seconds long + * effect.periodic.attack_length = 1000; // Takes 1 second to get max strength + * effect.periodic.fade_length = 1000; // Takes 1 second to fade away + * + * // Upload the effect + * effect_id = SDL_HapticNewEffect( haptic, &effect ); + * + * // Test the effect + * SDL_HapticRunEffect( haptic, effect_id, 1 ); + * SDL_Delay( 5000); // Wait for the effect to finish + * + * // We destroy the effect, although closing the device also does this + * SDL_HapticDestroyEffect( haptic, effect_id ); + * + * // Close the device + * SDL_HapticClose(haptic); + * + * return 0; // Success + * } + * ``` + */ + +#ifndef SDL_haptic_h_ +#define SDL_haptic_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_joystick.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/* FIXME: For SDL 2.1, adjust all the magnitude variables to be Uint16 (0xFFFF). + * + * At the moment the magnitude variables are mixed between signed/unsigned, and + * it is also not made clear that ALL of those variables expect a max of 0x7FFF. + * + * Some platforms may have higher precision than that (Linux FF, Windows XInput) + * so we should fix the inconsistency in favor of higher possible precision, + * adjusting for platforms that use different scales. + * -flibit + */ + +/** + * \typedef SDL_Haptic + * + * \brief The haptic structure used to identify an SDL haptic. + * + * \sa SDL_HapticOpen + * \sa SDL_HapticOpenFromJoystick + * \sa SDL_HapticClose + */ +struct _SDL_Haptic; +typedef struct _SDL_Haptic SDL_Haptic; + + +/** + * \name Haptic features + * + * Different haptic features a device can have. + */ +/* @{ */ + +/** + * \name Haptic effects + */ +/* @{ */ + +/** + * Constant effect supported. + * + * Constant haptic effect. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_CONSTANT (1u<<0) + +/** + * Sine wave effect supported. + * + * Periodic haptic effect that simulates sine waves. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_SINE (1u<<1) + +/** + * Left/Right effect supported. + * + * Haptic effect for direct control over high/low frequency motors. + * + * \sa SDL_HapticLeftRight + */ +#define SDL_HAPTIC_LEFTRIGHT (1u<<2) + +/* !!! FIXME: put this back when we have more bits in 2.1 */ +/* #define SDL_HAPTIC_SQUARE (1<<2) */ + +/** + * Triangle wave effect supported. + * + * Periodic haptic effect that simulates triangular waves. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_TRIANGLE (1u<<3) + +/** + * Sawtoothup wave effect supported. + * + * Periodic haptic effect that simulates saw tooth up waves. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_SAWTOOTHUP (1u<<4) + +/** + * Sawtoothdown wave effect supported. + * + * Periodic haptic effect that simulates saw tooth down waves. + * + * \sa SDL_HapticPeriodic + */ +#define SDL_HAPTIC_SAWTOOTHDOWN (1u<<5) + +/** + * Ramp effect supported. + * + * Ramp haptic effect. + * + * \sa SDL_HapticRamp + */ +#define SDL_HAPTIC_RAMP (1u<<6) + +/** + * Spring effect supported - uses axes position. + * + * Condition haptic effect that simulates a spring. Effect is based on the + * axes position. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_SPRING (1u<<7) + +/** + * Damper effect supported - uses axes velocity. + * + * Condition haptic effect that simulates dampening. Effect is based on the + * axes velocity. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_DAMPER (1u<<8) + +/** + * Inertia effect supported - uses axes acceleration. + * + * Condition haptic effect that simulates inertia. Effect is based on the axes + * acceleration. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_INERTIA (1u<<9) + +/** + * Friction effect supported - uses axes movement. + * + * Condition haptic effect that simulates friction. Effect is based on the + * axes movement. + * + * \sa SDL_HapticCondition + */ +#define SDL_HAPTIC_FRICTION (1u<<10) + +/** + * Custom effect is supported. + * + * User defined custom haptic effect. + */ +#define SDL_HAPTIC_CUSTOM (1u<<11) + +/* @} *//* Haptic effects */ + +/* These last few are features the device has, not effects */ + +/** + * Device can set global gain. + * + * Device supports setting the global gain. + * + * \sa SDL_HapticSetGain + */ +#define SDL_HAPTIC_GAIN (1u<<12) + +/** + * Device can set autocenter. + * + * Device supports setting autocenter. + * + * \sa SDL_HapticSetAutocenter + */ +#define SDL_HAPTIC_AUTOCENTER (1u<<13) + +/** + * Device can be queried for effect status. + * + * Device supports querying effect status. + * + * \sa SDL_HapticGetEffectStatus + */ +#define SDL_HAPTIC_STATUS (1u<<14) + +/** + * Device can be paused. + * + * Devices supports being paused. + * + * \sa SDL_HapticPause + * \sa SDL_HapticUnpause + */ +#define SDL_HAPTIC_PAUSE (1u<<15) + + +/** + * \name Direction encodings + */ +/* @{ */ + +/** + * Uses polar coordinates for the direction. + * + * \sa SDL_HapticDirection + */ +#define SDL_HAPTIC_POLAR 0 + +/** + * Uses cartesian coordinates for the direction. + * + * \sa SDL_HapticDirection + */ +#define SDL_HAPTIC_CARTESIAN 1 + +/** + * Uses spherical coordinates for the direction. + * + * \sa SDL_HapticDirection + */ +#define SDL_HAPTIC_SPHERICAL 2 + +/** + * Use this value to play an effect on the steering wheel axis. + * + * This provides better compatibility across platforms and devices as SDL will + * guess the correct axis. + * + * \sa SDL_HapticDirection + */ +#define SDL_HAPTIC_STEERING_AXIS 3 + +/* @} *//* Direction encodings */ + +/* @} *//* Haptic features */ + +/* + * Misc defines. + */ + +/** + * Used to play a device an infinite number of times. + * + * \sa SDL_HapticRunEffect + */ +#define SDL_HAPTIC_INFINITY 4294967295U + + +/** + * Structure that represents a haptic direction. + * + * This is the direction where the force comes from, instead of the direction + * in which the force is exerted. + * + * Directions can be specified by: + * + * - SDL_HAPTIC_POLAR : Specified by polar coordinates. + * - SDL_HAPTIC_CARTESIAN : Specified by cartesian coordinates. + * - SDL_HAPTIC_SPHERICAL : Specified by spherical coordinates. + * + * Cardinal directions of the haptic device are relative to the positioning of + * the device. North is considered to be away from the user. + * + * The following diagram represents the cardinal directions: + * + * ``` + * .--. + * |__| .-------. + * |=.| |.-----.| + * |--| || || + * | | |'-----'| + * |__|~')_____(' + * [ COMPUTER ] + * + * + * North (0,-1) + * ^ + * | + * | + * (-1,0) West <----[ HAPTIC ]----> East (1,0) + * | + * | + * v + * South (0,1) + * + * + * [ USER ] + * \|||/ + * (o o) + * ---ooO-(_)-Ooo--- + * ``` + * + * If type is SDL_HAPTIC_POLAR, direction is encoded by hundredths of a degree + * starting north and turning clockwise. SDL_HAPTIC_POLAR only uses the first + * `dir` parameter. The cardinal directions would be: + * + * - North: 0 (0 degrees) + * - East: 9000 (90 degrees) + * - South: 18000 (180 degrees) + * - West: 27000 (270 degrees) + * + * If type is SDL_HAPTIC_CARTESIAN, direction is encoded by three positions (X + * axis, Y axis and Z axis (with 3 axes)). SDL_HAPTIC_CARTESIAN uses the first + * three `dir` parameters. The cardinal directions would be: + * + * - North: 0,-1, 0 + * - East: 1, 0, 0 + * - South: 0, 1, 0 + * - West: -1, 0, 0 + * + * The Z axis represents the height of the effect if supported, otherwise it's + * unused. In cartesian encoding (1, 2) would be the same as (2, 4), you can + * use any multiple you want, only the direction matters. + * + * If type is SDL_HAPTIC_SPHERICAL, direction is encoded by two rotations. The + * first two `dir` parameters are used. The `dir` parameters are as follows + * (all values are in hundredths of degrees): + * + * - Degrees from (1, 0) rotated towards (0, 1). + * - Degrees towards (0, 0, 1) (device needs at least 3 axes). + * + * Example of force coming from the south with all encodings (force coming + * from the south means the user will have to pull the stick to counteract): + * + * ```c + * SDL_HapticDirection direction; + * + * // Cartesian directions + * direction.type = SDL_HAPTIC_CARTESIAN; // Using cartesian direction encoding. + * direction.dir[0] = 0; // X position + * direction.dir[1] = 1; // Y position + * // Assuming the device has 2 axes, we don't need to specify third parameter. + * + * // Polar directions + * direction.type = SDL_HAPTIC_POLAR; // We'll be using polar direction encoding. + * direction.dir[0] = 18000; // Polar only uses first parameter + * + * // Spherical coordinates + * direction.type = SDL_HAPTIC_SPHERICAL; // Spherical encoding + * direction.dir[0] = 9000; // Since we only have two axes we don't need more parameters. + * ``` + * + * \sa SDL_HAPTIC_POLAR + * \sa SDL_HAPTIC_CARTESIAN + * \sa SDL_HAPTIC_SPHERICAL + * \sa SDL_HAPTIC_STEERING_AXIS + * \sa SDL_HapticEffect + * \sa SDL_HapticNumAxes + */ +typedef struct SDL_HapticDirection +{ + Uint8 type; /**< The type of encoding. */ + Sint32 dir[3]; /**< The encoded direction. */ +} SDL_HapticDirection; + + +/** + * A structure containing a template for a Constant effect. + * + * This struct is exclusively for the SDL_HAPTIC_CONSTANT effect. + * + * A constant effect applies a constant force in the specified direction to + * the joystick. + * + * \sa SDL_HAPTIC_CONSTANT + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticConstant +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_CONSTANT */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Constant */ + Sint16 level; /**< Strength of the constant effect. */ + + /* Envelope */ + Uint16 attack_length; /**< Duration of the attack. */ + Uint16 attack_level; /**< Level at the start of the attack. */ + Uint16 fade_length; /**< Duration of the fade. */ + Uint16 fade_level; /**< Level at the end of the fade. */ +} SDL_HapticConstant; + +/** + * A structure containing a template for a Periodic effect. + * + * The struct handles the following effects: + * + * - SDL_HAPTIC_SINE + * - SDL_HAPTIC_SQUARE + * - SDL_HAPTIC_TRIANGLE + * - SDL_HAPTIC_SAWTOOTHUP + * - SDL_HAPTIC_SAWTOOTHDOWN + * + * A periodic effect consists in a wave-shaped effect that repeats itself over + * time. The type determines the shape of the wave and the parameters + * determine the dimensions of the wave. + * + * Phase is given by hundredth of a degree meaning that giving the phase a + * value of 9000 will displace it 25% of its period. Here are sample values: + * + * - 0: No phase displacement. + * - 9000: Displaced 25% of its period. + * - 18000: Displaced 50% of its period. + * - 27000: Displaced 75% of its period. + * - 36000: Displaced 100% of its period, same as 0, but 0 is preferred. + * + * Examples: + * + * ``` + * SDL_HAPTIC_SINE + * __ __ __ __ + * / \ / \ / \ / + * / \__/ \__/ \__/ + * + * SDL_HAPTIC_SQUARE + * __ __ __ __ __ + * | | | | | | | | | | + * | |__| |__| |__| |__| | + * + * SDL_HAPTIC_TRIANGLE + * /\ /\ /\ /\ /\ + * / \ / \ / \ / \ / + * / \/ \/ \/ \/ + * + * SDL_HAPTIC_SAWTOOTHUP + * /| /| /| /| /| /| /| + * / | / | / | / | / | / | / | + * / |/ |/ |/ |/ |/ |/ | + * + * SDL_HAPTIC_SAWTOOTHDOWN + * \ |\ |\ |\ |\ |\ |\ | + * \ | \ | \ | \ | \ | \ | \ | + * \| \| \| \| \| \| \| + * ``` + * + * \sa SDL_HAPTIC_SINE + * \sa SDL_HAPTIC_LEFTRIGHT + * \sa SDL_HAPTIC_TRIANGLE + * \sa SDL_HAPTIC_SAWTOOTHUP + * \sa SDL_HAPTIC_SAWTOOTHDOWN + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticPeriodic +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_SINE, SDL_HAPTIC_LEFTRIGHT, + SDL_HAPTIC_TRIANGLE, SDL_HAPTIC_SAWTOOTHUP or + SDL_HAPTIC_SAWTOOTHDOWN */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Periodic */ + Uint16 period; /**< Period of the wave. */ + Sint16 magnitude; /**< Peak value; if negative, equivalent to 180 degrees extra phase shift. */ + Sint16 offset; /**< Mean value of the wave. */ + Uint16 phase; /**< Positive phase shift given by hundredth of a degree. */ + + /* Envelope */ + Uint16 attack_length; /**< Duration of the attack. */ + Uint16 attack_level; /**< Level at the start of the attack. */ + Uint16 fade_length; /**< Duration of the fade. */ + Uint16 fade_level; /**< Level at the end of the fade. */ +} SDL_HapticPeriodic; + +/** + * A structure containing a template for a Condition effect. + * + * The struct handles the following effects: + * + * - SDL_HAPTIC_SPRING: Effect based on axes position. + * - SDL_HAPTIC_DAMPER: Effect based on axes velocity. + * - SDL_HAPTIC_INERTIA: Effect based on axes acceleration. + * - SDL_HAPTIC_FRICTION: Effect based on axes movement. + * + * Direction is handled by condition internals instead of a direction member. + * The condition effect specific members have three parameters. The first + * refers to the X axis, the second refers to the Y axis and the third refers + * to the Z axis. The right terms refer to the positive side of the axis and + * the left terms refer to the negative side of the axis. Please refer to the + * SDL_HapticDirection diagram for which side is positive and which is + * negative. + * + * \sa SDL_HapticDirection + * \sa SDL_HAPTIC_SPRING + * \sa SDL_HAPTIC_DAMPER + * \sa SDL_HAPTIC_INERTIA + * \sa SDL_HAPTIC_FRICTION + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticCondition +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_SPRING, SDL_HAPTIC_DAMPER, + SDL_HAPTIC_INERTIA or SDL_HAPTIC_FRICTION */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Condition */ + Uint16 right_sat[3]; /**< Level when joystick is to the positive side; max 0xFFFF. */ + Uint16 left_sat[3]; /**< Level when joystick is to the negative side; max 0xFFFF. */ + Sint16 right_coeff[3]; /**< How fast to increase the force towards the positive side. */ + Sint16 left_coeff[3]; /**< How fast to increase the force towards the negative side. */ + Uint16 deadband[3]; /**< Size of the dead zone; max 0xFFFF: whole axis-range when 0-centered. */ + Sint16 center[3]; /**< Position of the dead zone. */ +} SDL_HapticCondition; + +/** + * A structure containing a template for a Ramp effect. + * + * This struct is exclusively for the SDL_HAPTIC_RAMP effect. + * + * The ramp effect starts at start strength and ends at end strength. It + * augments in linear fashion. If you use attack and fade with a ramp the + * effects get added to the ramp effect making the effect become quadratic + * instead of linear. + * + * \sa SDL_HAPTIC_RAMP + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticRamp +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_RAMP */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Ramp */ + Sint16 start; /**< Beginning strength level. */ + Sint16 end; /**< Ending strength level. */ + + /* Envelope */ + Uint16 attack_length; /**< Duration of the attack. */ + Uint16 attack_level; /**< Level at the start of the attack. */ + Uint16 fade_length; /**< Duration of the fade. */ + Uint16 fade_level; /**< Level at the end of the fade. */ +} SDL_HapticRamp; + +/** + * A structure containing a template for a Left/Right effect. + * + * This struct is exclusively for the SDL_HAPTIC_LEFTRIGHT effect. + * + * The Left/Right effect is used to explicitly control the large and small + * motors, commonly found in modern game controllers. The small (right) motor + * is high frequency, and the large (left) motor is low frequency. + * + * \sa SDL_HAPTIC_LEFTRIGHT + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticLeftRight +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_LEFTRIGHT */ + + /* Replay */ + Uint32 length; /**< Duration of the effect in milliseconds. */ + + /* Rumble */ + Uint16 large_magnitude; /**< Control of the large controller motor. */ + Uint16 small_magnitude; /**< Control of the small controller motor. */ +} SDL_HapticLeftRight; + +/** + * A structure containing a template for the SDL_HAPTIC_CUSTOM effect. + * + * This struct is exclusively for the SDL_HAPTIC_CUSTOM effect. + * + * A custom force feedback effect is much like a periodic effect, where the + * application can define its exact shape. You will have to allocate the data + * yourself. Data should consist of channels * samples Uint16 samples. + * + * If channels is one, the effect is rotated using the defined direction. + * Otherwise it uses the samples in data for the different axes. + * + * \sa SDL_HAPTIC_CUSTOM + * \sa SDL_HapticEffect + */ +typedef struct SDL_HapticCustom +{ + /* Header */ + Uint16 type; /**< SDL_HAPTIC_CUSTOM */ + SDL_HapticDirection direction; /**< Direction of the effect. */ + + /* Replay */ + Uint32 length; /**< Duration of the effect. */ + Uint16 delay; /**< Delay before starting the effect. */ + + /* Trigger */ + Uint16 button; /**< Button that triggers the effect. */ + Uint16 interval; /**< How soon it can be triggered again after button. */ + + /* Custom */ + Uint8 channels; /**< Axes to use, minimum of one. */ + Uint16 period; /**< Sample periods. */ + Uint16 samples; /**< Amount of samples. */ + Uint16 *data; /**< Should contain channels*samples items. */ + + /* Envelope */ + Uint16 attack_length; /**< Duration of the attack. */ + Uint16 attack_level; /**< Level at the start of the attack. */ + Uint16 fade_length; /**< Duration of the fade. */ + Uint16 fade_level; /**< Level at the end of the fade. */ +} SDL_HapticCustom; + +/** + * The generic template for any haptic effect. + * + * All values max at 32767 (0x7FFF). Signed values also can be negative. Time + * values unless specified otherwise are in milliseconds. + * + * You can also pass SDL_HAPTIC_INFINITY to length instead of a 0-32767 value. + * Neither delay, interval, attack_length nor fade_length support + * SDL_HAPTIC_INFINITY. Fade will also not be used since effect never ends. + * + * Additionally, the SDL_HAPTIC_RAMP effect does not support a duration of + * SDL_HAPTIC_INFINITY. + * + * Button triggers may not be supported on all devices, it is advised to not + * use them if possible. Buttons start at index 1 instead of index 0 like the + * joystick. + * + * If both attack_length and fade_level are 0, the envelope is not used, + * otherwise both values are used. + * + * Common parts: + * + * ```c + * // Replay - All effects have this + * Uint32 length; // Duration of effect (ms). + * Uint16 delay; // Delay before starting effect. + * + * // Trigger - All effects have this + * Uint16 button; // Button that triggers effect. + * Uint16 interval; // How soon before effect can be triggered again. + * + * // Envelope - All effects except condition effects have this + * Uint16 attack_length; // Duration of the attack (ms). + * Uint16 attack_level; // Level at the start of the attack. + * Uint16 fade_length; // Duration of the fade out (ms). + * Uint16 fade_level; // Level at the end of the fade. + * ``` + * + * Here we have an example of a constant effect evolution in time: + * + * ``` + * Strength + * ^ + * | + * | effect level --> _________________ + * | / \ + * | / \ + * | / \ + * | / \ + * | attack_level --> | \ + * | | | <--- fade_level + * | + * +--------------------------------------------------> Time + * [--] [---] + * attack_length fade_length + * + * [------------------][-----------------------] + * delay length + * ``` + * + * Note either the attack_level or the fade_level may be above the actual + * effect level. + * + * \sa SDL_HapticConstant + * \sa SDL_HapticPeriodic + * \sa SDL_HapticCondition + * \sa SDL_HapticRamp + * \sa SDL_HapticLeftRight + * \sa SDL_HapticCustom + */ +typedef union SDL_HapticEffect +{ + /* Common for all force feedback effects */ + Uint16 type; /**< Effect type. */ + SDL_HapticConstant constant; /**< Constant effect. */ + SDL_HapticPeriodic periodic; /**< Periodic effect. */ + SDL_HapticCondition condition; /**< Condition effect. */ + SDL_HapticRamp ramp; /**< Ramp effect. */ + SDL_HapticLeftRight leftright; /**< Left/Right effect. */ + SDL_HapticCustom custom; /**< Custom effect. */ +} SDL_HapticEffect; + + +/* Function prototypes */ + +/** + * Count the number of haptic devices attached to the system. + * + * \returns the number of haptic devices detected on the system or a negative + * error code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticName + */ +extern DECLSPEC int SDLCALL SDL_NumHaptics(void); + +/** + * Get the implementation dependent name of a haptic device. + * + * This can be called before any joysticks are opened. If no name can be + * found, this function returns NULL. + * + * \param device_index index of the device to query. + * \returns the name of the device or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_NumHaptics + */ +extern DECLSPEC const char *SDLCALL SDL_HapticName(int device_index); + +/** + * Open a haptic device for use. + * + * The index passed as an argument refers to the N'th haptic device on this + * system. + * + * When opening a haptic device, its gain will be set to maximum and + * autocenter will be disabled. To modify these values use SDL_HapticSetGain() + * and SDL_HapticSetAutocenter(). + * + * \param device_index index of the device to open. + * \returns the device identifier or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticClose + * \sa SDL_HapticIndex + * \sa SDL_HapticOpenFromJoystick + * \sa SDL_HapticOpenFromMouse + * \sa SDL_HapticPause + * \sa SDL_HapticSetAutocenter + * \sa SDL_HapticSetGain + * \sa SDL_HapticStopAll + */ +extern DECLSPEC SDL_Haptic *SDLCALL SDL_HapticOpen(int device_index); + +/** + * Check if the haptic device at the designated index has been opened. + * + * \param device_index the index of the device to query. + * \returns 1 if it has been opened, 0 if it hasn't or on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticIndex + * \sa SDL_HapticOpen + */ +extern DECLSPEC int SDLCALL SDL_HapticOpened(int device_index); + +/** + * Get the index of a haptic device. + * + * \param haptic the SDL_Haptic device to query. + * \returns the index of the specified haptic device or a negative error code + * on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticOpen + * \sa SDL_HapticOpened + */ +extern DECLSPEC int SDLCALL SDL_HapticIndex(SDL_Haptic * haptic); + +/** + * Query whether or not the current mouse has haptic capabilities. + * + * \returns SDL_TRUE if the mouse is haptic or SDL_FALSE if it isn't. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticOpenFromMouse + */ +extern DECLSPEC int SDLCALL SDL_MouseIsHaptic(void); + +/** + * Try to open a haptic device from the current mouse. + * + * \returns the haptic device identifier or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticOpen + * \sa SDL_MouseIsHaptic + */ +extern DECLSPEC SDL_Haptic *SDLCALL SDL_HapticOpenFromMouse(void); + +/** + * Query if a joystick has haptic features. + * + * \param joystick the SDL_Joystick to test for haptic capabilities. + * \returns SDL_TRUE if the joystick is haptic, SDL_FALSE if it isn't, or a + * negative error code on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticOpenFromJoystick + */ +extern DECLSPEC int SDLCALL SDL_JoystickIsHaptic(SDL_Joystick * joystick); + +/** + * Open a haptic device for use from a joystick device. + * + * You must still close the haptic device separately. It will not be closed + * with the joystick. + * + * When opened from a joystick you should first close the haptic device before + * closing the joystick device. If not, on some implementations the haptic + * device will also get unallocated and you'll be unable to use force feedback + * on that device. + * + * \param joystick the SDL_Joystick to create a haptic device from. + * \returns a valid haptic device identifier on success or NULL on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticClose + * \sa SDL_HapticOpen + * \sa SDL_JoystickIsHaptic + */ +extern DECLSPEC SDL_Haptic *SDLCALL SDL_HapticOpenFromJoystick(SDL_Joystick * + joystick); + +/** + * Close a haptic device previously opened with SDL_HapticOpen(). + * + * \param haptic the SDL_Haptic device to close. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticOpen + */ +extern DECLSPEC void SDLCALL SDL_HapticClose(SDL_Haptic * haptic); + +/** + * Get the number of effects a haptic device can store. + * + * On some platforms this isn't fully supported, and therefore is an + * approximation. Always check to see if your created effect was actually + * created and do not rely solely on SDL_HapticNumEffects(). + * + * \param haptic the SDL_Haptic device to query. + * \returns the number of effects the haptic device can store or a negative + * error code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticNumEffectsPlaying + * \sa SDL_HapticQuery + */ +extern DECLSPEC int SDLCALL SDL_HapticNumEffects(SDL_Haptic * haptic); + +/** + * Get the number of effects a haptic device can play at the same time. + * + * This is not supported on all platforms, but will always return a value. + * + * \param haptic the SDL_Haptic device to query maximum playing effects. + * \returns the number of effects the haptic device can play at the same time + * or a negative error code on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticNumEffects + * \sa SDL_HapticQuery + */ +extern DECLSPEC int SDLCALL SDL_HapticNumEffectsPlaying(SDL_Haptic * haptic); + +/** + * Get the haptic device's supported features in bitwise manner. + * + * \param haptic the SDL_Haptic device to query. + * \returns a list of supported haptic features in bitwise manner (OR'd), or 0 + * on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticEffectSupported + * \sa SDL_HapticNumEffects + */ +extern DECLSPEC unsigned int SDLCALL SDL_HapticQuery(SDL_Haptic * haptic); + + +/** + * Get the number of haptic axes the device has. + * + * The number of haptic axes might be useful if working with the + * SDL_HapticDirection effect. + * + * \param haptic the SDL_Haptic device to query. + * \returns the number of axes on success or a negative error code on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_HapticNumAxes(SDL_Haptic * haptic); + +/** + * Check to see if an effect is supported by a haptic device. + * + * \param haptic the SDL_Haptic device to query. + * \param effect the desired effect to query. + * \returns SDL_TRUE if effect is supported, SDL_FALSE if it isn't, or a + * negative error code on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticNewEffect + * \sa SDL_HapticQuery + */ +extern DECLSPEC int SDLCALL SDL_HapticEffectSupported(SDL_Haptic * haptic, + SDL_HapticEffect * + effect); + +/** + * Create a new haptic effect on a specified device. + * + * \param haptic an SDL_Haptic device to create the effect on. + * \param effect an SDL_HapticEffect structure containing the properties of + * the effect to create. + * \returns the ID of the effect on success or a negative error code on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticDestroyEffect + * \sa SDL_HapticRunEffect + * \sa SDL_HapticUpdateEffect + */ +extern DECLSPEC int SDLCALL SDL_HapticNewEffect(SDL_Haptic * haptic, + SDL_HapticEffect * effect); + +/** + * Update the properties of an effect. + * + * Can be used dynamically, although behavior when dynamically changing + * direction may be strange. Specifically the effect may re-upload itself and + * start playing from the start. You also cannot change the type either when + * running SDL_HapticUpdateEffect(). + * + * \param haptic the SDL_Haptic device that has the effect. + * \param effect the identifier of the effect to update. + * \param data an SDL_HapticEffect structure containing the new effect + * properties to use. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticDestroyEffect + * \sa SDL_HapticNewEffect + * \sa SDL_HapticRunEffect + */ +extern DECLSPEC int SDLCALL SDL_HapticUpdateEffect(SDL_Haptic * haptic, + int effect, + SDL_HapticEffect * data); + +/** + * Run the haptic effect on its associated haptic device. + * + * To repeat the effect over and over indefinitely, set `iterations` to + * `SDL_HAPTIC_INFINITY`. (Repeats the envelope - attack and fade.) To make + * one instance of the effect last indefinitely (so the effect does not fade), + * set the effect's `length` in its structure/union to `SDL_HAPTIC_INFINITY` + * instead. + * + * \param haptic the SDL_Haptic device to run the effect on. + * \param effect the ID of the haptic effect to run. + * \param iterations the number of iterations to run the effect; use + * `SDL_HAPTIC_INFINITY` to repeat forever. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticDestroyEffect + * \sa SDL_HapticGetEffectStatus + * \sa SDL_HapticStopEffect + */ +extern DECLSPEC int SDLCALL SDL_HapticRunEffect(SDL_Haptic * haptic, + int effect, + Uint32 iterations); + +/** + * Stop the haptic effect on its associated haptic device. + * + * * + * + * \param haptic the SDL_Haptic device to stop the effect on. + * \param effect the ID of the haptic effect to stop. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticDestroyEffect + * \sa SDL_HapticRunEffect + */ +extern DECLSPEC int SDLCALL SDL_HapticStopEffect(SDL_Haptic * haptic, + int effect); + +/** + * Destroy a haptic effect on the device. + * + * This will stop the effect if it's running. Effects are automatically + * destroyed when the device is closed. + * + * \param haptic the SDL_Haptic device to destroy the effect on. + * \param effect the ID of the haptic effect to destroy. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticNewEffect + */ +extern DECLSPEC void SDLCALL SDL_HapticDestroyEffect(SDL_Haptic * haptic, + int effect); + +/** + * Get the status of the current effect on the specified haptic device. + * + * Device must support the SDL_HAPTIC_STATUS feature. + * + * \param haptic the SDL_Haptic device to query for the effect status on. + * \param effect the ID of the haptic effect to query its status. + * \returns 0 if it isn't playing, 1 if it is playing, or a negative error + * code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticRunEffect + * \sa SDL_HapticStopEffect + */ +extern DECLSPEC int SDLCALL SDL_HapticGetEffectStatus(SDL_Haptic * haptic, + int effect); + +/** + * Set the global gain of the specified haptic device. + * + * Device must support the SDL_HAPTIC_GAIN feature. + * + * The user may specify the maximum gain by setting the environment variable + * `SDL_HAPTIC_GAIN_MAX` which should be between 0 and 100. All calls to + * SDL_HapticSetGain() will scale linearly using `SDL_HAPTIC_GAIN_MAX` as the + * maximum. + * + * \param haptic the SDL_Haptic device to set the gain on. + * \param gain value to set the gain to, should be between 0 and 100 (0 - + * 100). + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticQuery + */ +extern DECLSPEC int SDLCALL SDL_HapticSetGain(SDL_Haptic * haptic, int gain); + +/** + * Set the global autocenter of the device. + * + * Autocenter should be between 0 and 100. Setting it to 0 will disable + * autocentering. + * + * Device must support the SDL_HAPTIC_AUTOCENTER feature. + * + * \param haptic the SDL_Haptic device to set autocentering on. + * \param autocenter value to set autocenter to (0-100). + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticQuery + */ +extern DECLSPEC int SDLCALL SDL_HapticSetAutocenter(SDL_Haptic * haptic, + int autocenter); + +/** + * Pause a haptic device. + * + * Device must support the `SDL_HAPTIC_PAUSE` feature. Call + * SDL_HapticUnpause() to resume playback. + * + * Do not modify the effects nor add new ones while the device is paused. That + * can cause all sorts of weird errors. + * + * \param haptic the SDL_Haptic device to pause. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticUnpause + */ +extern DECLSPEC int SDLCALL SDL_HapticPause(SDL_Haptic * haptic); + +/** + * Unpause a haptic device. + * + * Call to unpause after SDL_HapticPause(). + * + * \param haptic the SDL_Haptic device to unpause. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticPause + */ +extern DECLSPEC int SDLCALL SDL_HapticUnpause(SDL_Haptic * haptic); + +/** + * Stop all the currently playing effects on a haptic device. + * + * \param haptic the SDL_Haptic device to stop. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_HapticStopAll(SDL_Haptic * haptic); + +/** + * Check whether rumble is supported on a haptic device. + * + * \param haptic haptic device to check for rumble support. + * \returns SDL_TRUE if effect is supported, SDL_FALSE if it isn't, or a + * negative error code on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticRumbleInit + * \sa SDL_HapticRumblePlay + * \sa SDL_HapticRumbleStop + */ +extern DECLSPEC int SDLCALL SDL_HapticRumbleSupported(SDL_Haptic * haptic); + +/** + * Initialize a haptic device for simple rumble playback. + * + * \param haptic the haptic device to initialize for simple rumble playback. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticOpen + * \sa SDL_HapticRumblePlay + * \sa SDL_HapticRumbleStop + * \sa SDL_HapticRumbleSupported + */ +extern DECLSPEC int SDLCALL SDL_HapticRumbleInit(SDL_Haptic * haptic); + +/** + * Run a simple rumble effect on a haptic device. + * + * \param haptic the haptic device to play the rumble effect on. + * \param strength strength of the rumble to play as a 0-1 float value. + * \param length length of the rumble to play in milliseconds. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticRumbleInit + * \sa SDL_HapticRumbleStop + * \sa SDL_HapticRumbleSupported + */ +extern DECLSPEC int SDLCALL SDL_HapticRumblePlay(SDL_Haptic * haptic, float strength, Uint32 length ); + +/** + * Stop the simple rumble on a haptic device. + * + * \param haptic the haptic device to stop the rumble effect on. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HapticRumbleInit + * \sa SDL_HapticRumblePlay + * \sa SDL_HapticRumbleSupported + */ +extern DECLSPEC int SDLCALL SDL_HapticRumbleStop(SDL_Haptic * haptic); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_haptic_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_hidapi.h b/third_party/SDL2/include/SDL_hidapi.h new file mode 100644 index 00000000000..b14442a6c2b --- /dev/null +++ b/third_party/SDL2/include/SDL_hidapi.h @@ -0,0 +1,443 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: HIDAPI */ + +/** + * # CategoryHIDAPI + * + * Header file for SDL HIDAPI functions. + * + * This is an adaptation of the original HIDAPI interface by Alan Ott, and + * includes source code licensed under the following license: + * + * ``` + * HIDAPI - Multi-Platform library for + * communication with HID devices. + * + * Copyright 2009, Alan Ott, Signal 11 Software. + * All Rights Reserved. + * + * This software may be used by anyone for any reason so + * long as the copyright notice in the source files + * remains intact. + * ``` + * + * (Note that this license is the same as item three of SDL's zlib license, so + * it adds no new requirements on the user.) + * + * If you would like a version of SDL without this code, you can build SDL + * with SDL_HIDAPI_DISABLED defined to 1. You might want to do this for + * example on iOS or tvOS to avoid a dependency on the CoreBluetooth + * framework. + */ + +#ifndef SDL_hidapi_h_ +#define SDL_hidapi_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A handle representing an open HID device + */ +struct SDL_hid_device_; +typedef struct SDL_hid_device_ SDL_hid_device; /**< opaque hidapi structure */ + +/** hidapi info structure */ + +/** + * Information about a connected HID device + */ +typedef struct SDL_hid_device_info +{ + /** Platform-specific device path */ + char *path; + /** Device Vendor ID */ + unsigned short vendor_id; + /** Device Product ID */ + unsigned short product_id; + /** Serial Number */ + wchar_t *serial_number; + /** Device Release Number in binary-coded decimal, + also known as Device Version Number */ + unsigned short release_number; + /** Manufacturer String */ + wchar_t *manufacturer_string; + /** Product string */ + wchar_t *product_string; + /** Usage Page for this Device/Interface + (Windows/Mac only). */ + unsigned short usage_page; + /** Usage for this Device/Interface + (Windows/Mac only).*/ + unsigned short usage; + /** The USB interface which this logical device + represents. + + * Valid on both Linux implementations in all cases. + * Valid on the Windows implementation only if the device + contains more than one interface. */ + int interface_number; + + /** Additional information about the USB interface. + Valid on libusb and Android implementations. */ + int interface_class; + int interface_subclass; + int interface_protocol; + + /** Pointer to the next device */ + struct SDL_hid_device_info *next; +} SDL_hid_device_info; + + +/** + * Initialize the HIDAPI library. + * + * This function initializes the HIDAPI library. Calling it is not strictly + * necessary, as it will be called automatically by SDL_hid_enumerate() and + * any of the SDL_hid_open_*() functions if it is needed. This function should + * be called at the beginning of execution however, if there is a chance of + * HIDAPI handles being opened by different threads simultaneously. + * + * Each call to this function should have a matching call to SDL_hid_exit() + * + * \returns 0 on success and -1 on error. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_hid_exit + */ +extern DECLSPEC int SDLCALL SDL_hid_init(void); + +/** + * Finalize the HIDAPI library. + * + * This function frees all of the static data associated with HIDAPI. It + * should be called at the end of execution to avoid memory leaks. + * + * \returns 0 on success and -1 on error. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_hid_init + */ +extern DECLSPEC int SDLCALL SDL_hid_exit(void); + +/** + * Check to see if devices may have been added or removed. + * + * Enumerating the HID devices is an expensive operation, so you can call this + * to see if there have been any system device changes since the last call to + * this function. A change in the counter returned doesn't necessarily mean + * that anything has changed, but you can call SDL_hid_enumerate() to get an + * updated device list. + * + * Calling this function for the first time may cause a thread or other system + * resource to be allocated to track device change notifications. + * + * \returns a change counter that is incremented with each potential device + * change, or 0 if device change detection isn't available. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_hid_enumerate + */ +extern DECLSPEC Uint32 SDLCALL SDL_hid_device_change_count(void); + +/** + * Enumerate the HID Devices. + * + * This function returns a linked list of all the HID devices attached to the + * system which match vendor_id and product_id. If `vendor_id` is set to 0 + * then any vendor matches. If `product_id` is set to 0 then any product + * matches. If `vendor_id` and `product_id` are both set to 0, then all HID + * devices will be returned. + * + * \param vendor_id The Vendor ID (VID) of the types of device to open. + * \param product_id The Product ID (PID) of the types of device to open. + * \returns a pointer to a linked list of type SDL_hid_device_info, containing + * information about the HID devices attached to the system, or NULL + * in the case of failure. Free this linked list by calling + * SDL_hid_free_enumeration(). + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_hid_device_change_count + */ +extern DECLSPEC SDL_hid_device_info * SDLCALL SDL_hid_enumerate(unsigned short vendor_id, unsigned short product_id); + +/** + * Free an enumeration Linked List + * + * This function frees a linked list created by SDL_hid_enumerate(). + * + * \param devs Pointer to a list of struct_device returned from + * SDL_hid_enumerate(). + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC void SDLCALL SDL_hid_free_enumeration(SDL_hid_device_info *devs); + +/** + * Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally + * a serial number. + * + * If `serial_number` is NULL, the first device with the specified VID and PID + * is opened. + * + * \param vendor_id The Vendor ID (VID) of the device to open. + * \param product_id The Product ID (PID) of the device to open. + * \param serial_number The Serial Number of the device to open (Optionally + * NULL). + * \returns a pointer to a SDL_hid_device object on success or NULL on + * failure. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC SDL_hid_device * SDLCALL SDL_hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number); + +/** + * Open a HID device by its path name. + * + * The path name be determined by calling SDL_hid_enumerate(), or a + * platform-specific path name can be used (eg: /dev/hidraw0 on Linux). + * + * \param path The path name of the device to open. + * \returns a pointer to a SDL_hid_device object on success or NULL on + * failure. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC SDL_hid_device * SDLCALL SDL_hid_open_path(const char *path, int bExclusive); + +/** + * Write an Output report to a HID device. + * + * The first byte of `data` must contain the Report ID. For devices which only + * support a single report, this must be set to 0x0. The remaining bytes + * contain the report data. Since the Report ID is mandatory, calls to + * SDL_hid_write() will always contain one more byte than the report contains. + * For example, if a hid report is 16 bytes long, 17 bytes must be passed to + * SDL_hid_write(), the Report ID (or 0x0, for devices with a single report), + * followed by the report data (16 bytes). In this example, the length passed + * in would be 17. + * + * SDL_hid_write() will send the data on the first OUT endpoint, if one + * exists. If it does not, it will send the data through the Control Endpoint + * (Endpoint 0). + * + * \param dev A device handle returned from SDL_hid_open(). + * \param data The data to send, including the report number as the first + * byte. + * \param length The length in bytes of the data to send. + * \returns the actual number of bytes written and -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_write(SDL_hid_device *dev, const unsigned char *data, size_t length); + +/** + * Read an Input report from a HID device with timeout. + * + * Input reports are returned to the host through the INTERRUPT IN endpoint. + * The first byte will contain the Report number if the device uses numbered + * reports. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param data A buffer to put the read data into. + * \param length The number of bytes to read. For devices with multiple + * reports, make sure to read an extra byte for the report + * number. + * \param milliseconds timeout in milliseconds or -1 for blocking wait. + * \returns the actual number of bytes read and -1 on error. If no packet was + * available to be read within the timeout period, this function + * returns 0. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_read_timeout(SDL_hid_device *dev, unsigned char *data, size_t length, int milliseconds); + +/** + * Read an Input report from a HID device. + * + * Input reports are returned to the host through the INTERRUPT IN endpoint. + * The first byte will contain the Report number if the device uses numbered + * reports. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param data A buffer to put the read data into. + * \param length The number of bytes to read. For devices with multiple + * reports, make sure to read an extra byte for the report + * number. + * \returns the actual number of bytes read and -1 on error. If no packet was + * available to be read and the handle is in non-blocking mode, this + * function returns 0. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_read(SDL_hid_device *dev, unsigned char *data, size_t length); + +/** + * Set the device handle to be non-blocking. + * + * In non-blocking mode calls to SDL_hid_read() will return immediately with a + * value of 0 if there is no data to be read. In blocking mode, SDL_hid_read() + * will wait (block) until there is data to read before returning. + * + * Nonblocking can be turned on and off at any time. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param nonblock enable or not the nonblocking reads - 1 to enable + * nonblocking - 0 to disable nonblocking. + * \returns 0 on success and -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_set_nonblocking(SDL_hid_device *dev, int nonblock); + +/** + * Send a Feature report to the device. + * + * Feature reports are sent over the Control endpoint as a Set_Report + * transfer. The first byte of `data` must contain the Report ID. For devices + * which only support a single report, this must be set to 0x0. The remaining + * bytes contain the report data. Since the Report ID is mandatory, calls to + * SDL_hid_send_feature_report() will always contain one more byte than the + * report contains. For example, if a hid report is 16 bytes long, 17 bytes + * must be passed to SDL_hid_send_feature_report(): the Report ID (or 0x0, for + * devices which do not use numbered reports), followed by the report data (16 + * bytes). In this example, the length passed in would be 17. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param data The data to send, including the report number as the first + * byte. + * \param length The length in bytes of the data to send, including the report + * number. + * \returns the actual number of bytes written and -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_send_feature_report(SDL_hid_device *dev, const unsigned char *data, size_t length); + +/** + * Get a feature report from a HID device. + * + * Set the first byte of `data` to the Report ID of the report to be read. + * Make sure to allow space for this extra byte in `data`. Upon return, the + * first byte will still contain the Report ID, and the report data will start + * in data[1]. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param data A buffer to put the read data into, including the Report ID. + * Set the first byte of `data` to the Report ID of the report to + * be read, or set it to zero if your device does not use numbered + * reports. + * \param length The number of bytes to read, including an extra byte for the + * report ID. The buffer can be longer than the actual report. + * \returns the number of bytes read plus one for the report ID (which is + * still in the first byte), or -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_get_feature_report(SDL_hid_device *dev, unsigned char *data, size_t length); + +/** + * Close a HID device. + * + * \param dev A device handle returned from SDL_hid_open(). + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC void SDLCALL SDL_hid_close(SDL_hid_device *dev); + +/** + * Get The Manufacturer String from a HID device. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param string A wide string buffer to put the data into. + * \param maxlen The length of the buffer in multiples of wchar_t. + * \returns 0 on success and -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_get_manufacturer_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen); + +/** + * Get The Product String from a HID device. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param string A wide string buffer to put the data into. + * \param maxlen The length of the buffer in multiples of wchar_t. + * \returns 0 on success and -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_get_product_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen); + +/** + * Get The Serial Number String from a HID device. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param string A wide string buffer to put the data into. + * \param maxlen The length of the buffer in multiples of wchar_t. + * \returns 0 on success and -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_get_serial_number_string(SDL_hid_device *dev, wchar_t *string, size_t maxlen); + +/** + * Get a string from a HID device, based on its string index. + * + * \param dev A device handle returned from SDL_hid_open(). + * \param string_index The index of the string to get. + * \param string A wide string buffer to put the data into. + * \param maxlen The length of the buffer in multiples of wchar_t. + * \returns 0 on success and -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_hid_get_indexed_string(SDL_hid_device *dev, int string_index, wchar_t *string, size_t maxlen); + +/** + * Start or stop a BLE scan on iOS and tvOS to pair Steam Controllers + * + * \param active SDL_TRUE to start the scan, SDL_FALSE to stop the scan. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC void SDLCALL SDL_hid_ble_scan(SDL_bool active); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_hidapi_h_ */ + +/* vi: set sts=4 ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_hints.h b/third_party/SDL2/include/SDL_hints.h new file mode 100644 index 00000000000..4665107fd2b --- /dev/null +++ b/third_party/SDL2/include/SDL_hints.h @@ -0,0 +1,3282 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryHints + * + * Official documentation for SDL configuration variables + * + * This file contains functions to set and get configuration hints, as well as + * listing each of them alphabetically. + * + * The convention for naming hints is SDL_HINT_X, where "SDL_X" is the + * environment variable that can be used to override the default. + * + * In general these hints are just that - they may or may not be supported or + * applicable on any given platform, but they provide a way for an application + * or user to give the library a hint as to how they would like the library to + * work. + */ + +#ifndef SDL_hints_h_ +#define SDL_hints_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A variable controlling whether the Android / iOS built-in accelerometer + * should be listed as a joystick device. + * + * This variable can be set to the following values: + * + * - "0": The accelerometer is not listed as a joystick + * - "1": The accelerometer is available as a 3 axis joystick (the default). + */ +#define SDL_HINT_ACCELEROMETER_AS_JOYSTICK "SDL_ACCELEROMETER_AS_JOYSTICK" + +/** + * Specify the behavior of Alt+Tab while the keyboard is grabbed. + * + * By default, SDL emulates Alt+Tab functionality while the keyboard is + * grabbed and your window is full-screen. This prevents the user from getting + * stuck in your application if you've enabled keyboard grab. + * + * The variable can be set to the following values: + * + * - "0": SDL will not handle Alt+Tab. Your application is responsible for + * handling Alt+Tab while the keyboard is grabbed. + * - "1": SDL will minimize your window when Alt+Tab is pressed (default) + */ +#define SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED "SDL_ALLOW_ALT_TAB_WHILE_GRABBED" + +/** + * If set to "0" then never set the top most bit on a SDL Window, even if the + * video mode expects it. + * + * This is a debugging aid for developers and not expected to be used by end + * users. The default is "1" + * + * This variable can be set to the following values: + * + * - "0": don't allow topmost + * - "1": allow topmost + */ +#define SDL_HINT_ALLOW_TOPMOST "SDL_ALLOW_TOPMOST" + +/** + * Android APK expansion main file version. + * + * Should be a string number like "1", "2" etc. + * + * Must be set together with + * SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION. + * + * If both hints were set then SDL_RWFromFile() will look into expansion files + * after a given relative path was not found in the internal storage and + * assets. + * + * By default this hint is not set and the APK expansion files are not + * searched. + */ +#define SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION "SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION" + +/** + * Android APK expansion patch file version. + * + * Should be a string number like "1", "2" etc. + * + * Must be set together with SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION. + * + * If both hints were set then SDL_RWFromFile() will look into expansion files + * after a given relative path was not found in the internal storage and + * assets. + * + * By default this hint is not set and the APK expansion files are not + * searched. + */ +#define SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION "SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION" + +/** + * A variable to control whether the event loop will block itself when the app + * is paused. + * + * The variable can be set to the following values: + * + * - "0": Non blocking. + * - "1": Blocking. (default) + * + * The value should be set before SDL is initialized. + */ +#define SDL_HINT_ANDROID_BLOCK_ON_PAUSE "SDL_ANDROID_BLOCK_ON_PAUSE" + +/** + * A variable to control whether SDL will pause audio in background (Requires + * SDL_ANDROID_BLOCK_ON_PAUSE as "Non blocking") + * + * The variable can be set to the following values: + * + * - "0": Non paused. + * - "1": Paused. (default) + * + * The value should be set before SDL is initialized. + */ +#define SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO "SDL_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO" + +/** + * A variable to control whether we trap the Android back button to handle it + * manually. + * + * This is necessary for the right mouse button to work on some Android + * devices, or to be able to trap the back button for use in your code + * reliably. If set to true, the back button will show up as an SDL_KEYDOWN / + * SDL_KEYUP pair with a keycode of SDL_SCANCODE_AC_BACK. + * + * The variable can be set to the following values: + * + * - "0": Back button will be handled as usual for system. (default) + * - "1": Back button will be trapped, allowing you to handle the key press + * manually. (This will also let right mouse click work on systems where the + * right mouse button functions as back.) + * + * The value of this hint is used at runtime, so it can be changed at any + * time. + */ +#define SDL_HINT_ANDROID_TRAP_BACK_BUTTON "SDL_ANDROID_TRAP_BACK_BUTTON" + +/** + * Specify an application name. + * + * This hint lets you specify the application name sent to the OS when + * required. For example, this will often appear in volume control applets for + * audio streams, and in lists of applications which are inhibiting the + * screensaver. You should use a string that describes your program ("My Game + * 2: The Revenge") + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default: probably the application's name or "SDL Application" if SDL + * doesn't have any better information. + * + * Note that, for audio streams, this can be overridden with + * SDL_HINT_AUDIO_DEVICE_APP_NAME. + * + * On targets where this is not supported, this hint does nothing. + */ +#define SDL_HINT_APP_NAME "SDL_APP_NAME" + +/** + * A variable controlling whether controllers used with the Apple TV generate + * UI events. + * + * When UI events are generated by controller input, the app will be + * backgrounded when the Apple TV remote's menu button is pressed, and when + * the pause or B buttons on gamepads are pressed. + * + * More information about properly making use of controllers for the Apple TV + * can be found here: + * https://developer.apple.com/tvos/human-interface-guidelines/remote-and-controllers/ + * + * This variable can be set to the following values: + * + * - "0": Controller input does not generate UI events (the default). + * - "1": Controller input generates UI events. + */ +#define SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS "SDL_APPLE_TV_CONTROLLER_UI_EVENTS" + +/** + * A variable controlling whether the Apple TV remote's joystick axes will + * automatically match the rotation of the remote. + * + * This variable can be set to the following values: + * + * - "0": Remote orientation does not affect joystick axes (the default). + * - "1": Joystick axes are based on the orientation of the remote. + */ +#define SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION" + +/** + * A variable controlling the audio category on iOS and Mac OS X + * + * This variable can be set to the following values: + * + * - "ambient": Use the AVAudioSessionCategoryAmbient audio category, will be + * muted by the phone mute switch (default) + * - "playback": Use the AVAudioSessionCategoryPlayback category + * + * For more information, see Apple's documentation: + * https://developer.apple.com/library/content/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionCategoriesandModes/AudioSessionCategoriesandModes.html + */ +#define SDL_HINT_AUDIO_CATEGORY "SDL_AUDIO_CATEGORY" + +/** + * Specify an application name for an audio device. + * + * Some audio backends (such as PulseAudio) allow you to describe your audio + * stream. Among other things, this description might show up in a system + * control panel that lets the user adjust the volume on specific audio + * streams instead of using one giant master volume slider. + * + * This hints lets you transmit that information to the OS. The contents of + * this hint are used while opening an audio device. You should use a string + * that describes your program ("My Game 2: The Revenge") + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default: this will be the name set with SDL_HINT_APP_NAME, if that hint is + * set. Otherwise, it'll probably the application's name or "SDL Application" + * if SDL doesn't have any better information. + * + * On targets where this is not supported, this hint does nothing. + */ +#define SDL_HINT_AUDIO_DEVICE_APP_NAME "SDL_AUDIO_DEVICE_APP_NAME" + +/** + * Specify an application name for an audio device. + * + * Some audio backends (such as PulseAudio) allow you to describe your audio + * stream. Among other things, this description might show up in a system + * control panel that lets the user adjust the volume on specific audio + * streams instead of using one giant master volume slider. + * + * This hints lets you transmit that information to the OS. The contents of + * this hint are used while opening an audio device. You should use a string + * that describes your what your program is playing ("audio stream" is + * probably sufficient in many cases, but this could be useful for something + * like "team chat" if you have a headset playing VoIP audio separately). + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default: "audio stream" or something similar. + * + * On targets where this is not supported, this hint does nothing. + */ +#define SDL_HINT_AUDIO_DEVICE_STREAM_NAME "SDL_AUDIO_DEVICE_STREAM_NAME" + +/** + * Specify an application role for an audio device. + * + * Some audio backends (such as Pipewire) allow you to describe the role of + * your audio stream. Among other things, this description might show up in a + * system control panel or software for displaying and manipulating media + * playback/capture graphs. + * + * This hints lets you transmit that information to the OS. The contents of + * this hint are used while opening an audio device. You should use a string + * that describes your what your program is playing (Game, Music, Movie, + * etc...). + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default: "Game" or something similar. + * + * On targets where this is not supported, this hint does nothing. + */ +#define SDL_HINT_AUDIO_DEVICE_STREAM_ROLE "SDL_AUDIO_DEVICE_STREAM_ROLE" + +/** + * A variable controlling speed/quality tradeoff of audio resampling. + * + * If available, SDL can use libsamplerate ( http://www.mega-nerd.com/SRC/ ) + * to handle audio resampling. There are different resampling modes available + * that produce different levels of quality, using more CPU. + * + * If this hint isn't specified to a valid setting, or libsamplerate isn't + * available, SDL will use the default, internal resampling algorithm. + * + * As of SDL 2.26, SDL_ConvertAudio() respects this hint when libsamplerate is + * available. + * + * This hint is currently only checked at audio subsystem initialization. + * + * This variable can be set to the following values: + * + * - "0" or "default": Use SDL's internal resampling (Default when not set - + * low quality, fast) + * - "1" or "fast": Use fast, slightly higher quality resampling, if available + * - "2" or "medium": Use medium quality resampling, if available + * - "3" or "best": Use high quality resampling, if available + */ +#define SDL_HINT_AUDIO_RESAMPLING_MODE "SDL_AUDIO_RESAMPLING_MODE" + +/** + * A variable controlling whether SDL updates joystick state when getting + * input events + * + * This variable can be set to the following values: + * + * - "0": You'll call SDL_JoystickUpdate() manually + * - "1": SDL will automatically call SDL_JoystickUpdate() (default) + * + * This hint can be toggled on and off at runtime. + */ +#define SDL_HINT_AUTO_UPDATE_JOYSTICKS "SDL_AUTO_UPDATE_JOYSTICKS" + +/** + * A variable controlling whether SDL updates sensor state when getting input + * events + * + * This variable can be set to the following values: + * + * - "0": You'll call SDL_SensorUpdate() manually + * - "1": SDL will automatically call SDL_SensorUpdate() (default) + * + * This hint can be toggled on and off at runtime. + */ +#define SDL_HINT_AUTO_UPDATE_SENSORS "SDL_AUTO_UPDATE_SENSORS" + +/** + * Prevent SDL from using version 4 of the bitmap header when saving BMPs. + * + * The bitmap header version 4 is required for proper alpha channel support + * and SDL will use it when required. Should this not be desired, this hint + * can force the use of the 40 byte header version which is supported + * everywhere. + * + * The variable can be set to the following values: + * + * - "0": Surfaces with a colorkey or an alpha channel are saved to a 32-bit + * BMP file with an alpha mask. SDL will use the bitmap header version 4 and + * set the alpha mask accordingly. + * - "1": Surfaces with a colorkey or an alpha channel are saved to a 32-bit + * BMP file without an alpha mask. The alpha channel data will be in the + * file, but applications are going to ignore it. + * + * The default value is "0". + */ +#define SDL_HINT_BMP_SAVE_LEGACY_FORMAT "SDL_BMP_SAVE_LEGACY_FORMAT" + +/** + * Override for SDL_GetDisplayUsableBounds() + * + * If set, this hint will override the expected results for + * SDL_GetDisplayUsableBounds() for display index 0. Generally you don't want + * to do this, but this allows an embedded system to request that some of the + * screen be reserved for other uses when paired with a well-behaved + * application. + * + * The contents of this hint must be 4 comma-separated integers, the first is + * the bounds x, then y, width and height, in that order. + */ +#define SDL_HINT_DISPLAY_USABLE_BOUNDS "SDL_DISPLAY_USABLE_BOUNDS" + +/** + * Disable giving back control to the browser automatically when running with + * asyncify + * + * With -s ASYNCIFY, SDL2 calls emscripten_sleep during operations such as + * refreshing the screen or polling events. + * + * This hint only applies to the emscripten platform + * + * The variable can be set to the following values: + * + * - "0": Disable emscripten_sleep calls (if you give back browser control + * manually or use asyncify for other purposes) + * - "1": Enable emscripten_sleep calls (the default) + */ +#define SDL_HINT_EMSCRIPTEN_ASYNCIFY "SDL_EMSCRIPTEN_ASYNCIFY" + +/** + * override the binding element for keyboard inputs for Emscripten builds + * + * This hint only applies to the emscripten platform. + * + * The variable can be one of: + * + * - "#window": the javascript window object (this is the default) + * - "#document": the javascript document object + * - "#screen": the javascript window.screen object + * - "#canvas": the WebGL canvas element + * + * Any other string without a leading # sign applies to the element on the + * page with that ID. + */ +#define SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT "SDL_EMSCRIPTEN_KEYBOARD_ELEMENT" + +/** + * A variable that controls whether the on-screen keyboard should be shown + * when text input is active + * + * The variable can be set to the following values: + * + * - "0": Do not show the on-screen keyboard + * - "1": Show the on-screen keyboard + * + * The default value is "1". This hint must be set before text input is + * activated. + */ +#define SDL_HINT_ENABLE_SCREEN_KEYBOARD "SDL_ENABLE_SCREEN_KEYBOARD" + +/** + * A variable controlling verbosity of the logging of SDL events pushed onto + * the internal queue. + * + * This variable can be set to the following values, from least to most + * verbose: + * + * - "0": Don't log any events (default) + * - "1": Log most events (other than the really spammy ones). + * - "2": Include mouse and finger motion events. + * - "3": Include SDL_SysWMEvent events. + * + * This is generally meant to be used to debug SDL itself, but can be useful + * for application developers that need better visibility into what is going + * on in the event queue. Logged events are sent through SDL_Log(), which + * means by default they appear on stdout on most platforms or maybe + * OutputDebugString() on Windows, and can be funneled by the app with + * SDL_LogSetOutputFunction(), etc. + * + * This hint can be toggled on and off at runtime, if you only need to log + * events for a small subset of program execution. + */ +#define SDL_HINT_EVENT_LOGGING "SDL_EVENT_LOGGING" + +/** + * A variable controlling whether raising the window should be done more + * forcefully + * + * This variable can be set to the following values: + * + * - "0": No forcing (the default) + * - "1": Extra level of forcing + * + * At present, this is only an issue under MS Windows, which makes it nearly + * impossible to programmatically move a window to the foreground, for + * "security" reasons. See http://stackoverflow.com/a/34414846 for a + * discussion. + */ +#define SDL_HINT_FORCE_RAISEWINDOW "SDL_HINT_FORCE_RAISEWINDOW" + +/** + * A variable controlling how 3D acceleration is used to accelerate the SDL + * screen surface. + * + * SDL can try to accelerate the SDL screen surface by using streaming + * textures with a 3D rendering engine. This variable controls whether and how + * this is done. + * + * This variable can be set to the following values: + * + * - "0": Disable 3D acceleration + * - "1": Enable 3D acceleration, using the default renderer. + * - "X": Enable 3D acceleration, using X where X is one of the valid + * rendering drivers. (e.g. "direct3d", "opengl", etc.) + * + * By default SDL tries to make a best guess for each platform whether to use + * acceleration or not. + */ +#define SDL_HINT_FRAMEBUFFER_ACCELERATION "SDL_FRAMEBUFFER_ACCELERATION" + +/** + * A variable that lets you manually hint extra gamecontroller db entries. + * + * The variable should be newline delimited rows of gamecontroller config + * data, see SDL_gamecontroller.h + * + * This hint must be set before calling SDL_Init(SDL_INIT_GAMECONTROLLER) You + * can update mappings after the system is initialized with + * SDL_GameControllerMappingForGUID() and SDL_GameControllerAddMapping() + */ +#define SDL_HINT_GAMECONTROLLERCONFIG "SDL_GAMECONTROLLERCONFIG" + +/** + * A variable that lets you provide a file with extra gamecontroller db + * entries. + * + * The file should contain lines of gamecontroller config data, see + * SDL_gamecontroller.h + * + * This hint must be set before calling SDL_Init(SDL_INIT_GAMECONTROLLER) You + * can update mappings after the system is initialized with + * SDL_GameControllerMappingForGUID() and SDL_GameControllerAddMapping() + */ +#define SDL_HINT_GAMECONTROLLERCONFIG_FILE "SDL_GAMECONTROLLERCONFIG_FILE" + +/** + * A variable that overrides the automatic controller type detection + * + * The variable should be comma separated entries, in the form: VID/PID=type + * + * The VID and PID should be hexadecimal with exactly 4 digits, e.g. 0x00fd + * + * The type should be one of: Xbox360 XboxOne PS3 PS4 PS5 SwitchPro + * + * This hint affects what driver is used, and must be set before calling + * SDL_Init(SDL_INIT_GAMECONTROLLER) + */ +#define SDL_HINT_GAMECONTROLLERTYPE "SDL_GAMECONTROLLERTYPE" + +/** + * A variable containing a list of devices to skip when scanning for game + * controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES "SDL_GAMECONTROLLER_IGNORE_DEVICES" + +/** + * If set, all devices will be skipped when scanning for game controllers + * except for the ones listed in this variable. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT" + +/** + * If set, game controller face buttons report their values according to their + * labels instead of their positional layout. + * + * For example, on Nintendo Switch controllers, normally you'd get: + * + * ``` + * (Y) + * (X) (B) + * (A) + * ``` + * + * but if this hint is set, you'll get: + * + * ``` + * (X) + * (Y) (A) + * (B) + * ``` + * + * The variable can be set to the following values: + * + * - "0": Report the face buttons by position, as though they were on an Xbox + * controller. + * - "1": Report the face buttons by label instead of position + * + * The default value is "1". This hint may be set at any time. + */ +#define SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS "SDL_GAMECONTROLLER_USE_BUTTON_LABELS" + +/** + * A variable controlling whether grabbing input grabs the keyboard + * + * This variable can be set to the following values: + * + * - "0": Grab will affect only the mouse + * - "1": Grab will affect mouse and keyboard + * + * By default SDL will not grab the keyboard so system shortcuts still work. + */ +#define SDL_HINT_GRAB_KEYBOARD "SDL_GRAB_KEYBOARD" + +/** + * A variable containing a list of devices to ignore in SDL_hid_enumerate() + * + * For example, to ignore the Shanwan DS3 controller and any Valve controller, + * you might have the string "0x2563/0x0523,0x28de/0x0000" + */ +#define SDL_HINT_HIDAPI_IGNORE_DEVICES "SDL_HIDAPI_IGNORE_DEVICES" + +/** + * A variable controlling whether the idle timer is disabled on iOS. + * + * When an iOS app does not receive touches for some time, the screen is + * dimmed automatically. For games where the accelerometer is the only input + * this is problematic. This functionality can be disabled by setting this + * hint. + * + * As of SDL 2.0.4, SDL_EnableScreenSaver() and SDL_DisableScreenSaver() + * accomplish the same thing on iOS. They should be preferred over this hint. + * + * This variable can be set to the following values: + * + * - "0": Enable idle timer + * - "1": Disable idle timer + */ +#define SDL_HINT_IDLE_TIMER_DISABLED "SDL_IOS_IDLE_TIMER_DISABLED" + +/** + * A variable to control whether certain IMEs should handle text editing + * internally instead of sending SDL_TEXTEDITING events. + * + * The variable can be set to the following values: + * + * - "0": SDL_TEXTEDITING events are sent, and it is the application's + * responsibility to render the text from these events and differentiate it + * somehow from committed text. (default) + * - "1": If supported by the IME then SDL_TEXTEDITING events are not sent, + * and text that is being composed will be rendered in its own UI. + */ +#define SDL_HINT_IME_INTERNAL_EDITING "SDL_IME_INTERNAL_EDITING" + +/** + * A variable to control whether certain IMEs should show native UI components + * (such as the Candidate List) instead of suppressing them. + * + * The variable can be set to the following values: + * + * - "0": Native UI components are not display. (default) + * - "1": Native UI components are displayed. + */ +#define SDL_HINT_IME_SHOW_UI "SDL_IME_SHOW_UI" + +/** + * A variable to control if extended IME text support is enabled. + * + * If enabled then SDL_TextEditingExtEvent will be issued if the text would be + * truncated otherwise. Additionally SDL_TextInputEvent will be dispatched + * multiple times so that it is not truncated. + * + * The variable can be set to the following values: + * + * - "0": Legacy behavior. Text can be truncated, no heap allocations. + * (default) + * - "1": Modern behavior. + */ +#define SDL_HINT_IME_SUPPORT_EXTENDED_TEXT "SDL_IME_SUPPORT_EXTENDED_TEXT" + +/** + * A variable controlling whether the home indicator bar on iPhone X should be + * hidden. + * + * This variable can be set to the following values: + * + * - "0": The indicator bar is not hidden (default for windowed applications) + * - "1": The indicator bar is hidden and is shown when the screen is touched + * (useful for movie playback applications) + * - "2": The indicator bar is dim and the first swipe makes it visible and + * the second swipe performs the "home" action (default for fullscreen + * applications) + */ +#define SDL_HINT_IOS_HIDE_HOME_INDICATOR "SDL_IOS_HIDE_HOME_INDICATOR" + +/** + * A variable that lets you enable joystick (and gamecontroller) events even + * when your app is in the background. + * + * The variable can be set to the following values: + * + * - "0": Disable joystick & gamecontroller input events when the application + * is in the background. + * - "1": Enable joystick & gamecontroller input events when the application + * is in the background. + * + * The default value is "0". This hint may be set at any time. + */ +#define SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS" + +/** + * A variable containing a list of arcade stick style controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_ARCADESTICK_DEVICES "SDL_JOYSTICK_ARCADESTICK_DEVICES" + +/** + * A variable containing a list of devices that are not arcade stick style + * controllers. + * + * This will override SDL_HINT_JOYSTICK_ARCADESTICK_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_ARCADESTICK_DEVICES_EXCLUDED "SDL_JOYSTICK_ARCADESTICK_DEVICES_EXCLUDED" + +/** + * A variable containing a list of devices that should not be considerd + * joysticks. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_BLACKLIST_DEVICES "SDL_JOYSTICK_BLACKLIST_DEVICES" + +/** + * A variable containing a list of devices that should be considered + * joysticks. + * + * This will override SDL_HINT_JOYSTICK_BLACKLIST_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_BLACKLIST_DEVICES_EXCLUDED "SDL_JOYSTICK_BLACKLIST_DEVICES_EXCLUDED" + +/** + * A variable containing a list of flightstick style controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_FLIGHTSTICK_DEVICES "SDL_JOYSTICK_FLIGHTSTICK_DEVICES" + +/** + * A variable containing a list of devices that are not flightstick style + * controllers. + * + * This will override SDL_HINT_JOYSTICK_FLIGHTSTICK_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_FLIGHTSTICK_DEVICES_EXCLUDED "SDL_JOYSTICK_FLIGHTSTICK_DEVICES_EXCLUDED" + +/** + * A variable containing a list of devices known to have a GameCube form + * factor. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_GAMECUBE_DEVICES "SDL_JOYSTICK_GAMECUBE_DEVICES" + +/** + * A variable containing a list of devices known not to have a GameCube form + * factor. + * + * This will override SDL_HINT_JOYSTICK_GAMECUBE_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_GAMECUBE_DEVICES_EXCLUDED "SDL_JOYSTICK_GAMECUBE_DEVICES_EXCLUDED" + +/** + * A variable controlling whether the HIDAPI joystick drivers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI drivers are not used + * - "1": HIDAPI drivers are used (the default) + * + * This variable is the default for all drivers, but can be overridden by the + * hints for specific drivers below. + */ +#define SDL_HINT_JOYSTICK_HIDAPI "SDL_JOYSTICK_HIDAPI" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo GameCube + * controllers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE "SDL_JOYSTICK_HIDAPI_GAMECUBE" + +/** + * A variable controlling whether "low_frequency_rumble" and + * "high_frequency_rumble" is used to implement the GameCube controller's 3 + * rumble modes, Stop(0), Rumble(1), and StopHard(2) this is useful for + * applications that need full compatibility for things like ADSR envelopes. + * + * Stop is implemented by setting "low_frequency_rumble" to "0" and + * "high_frequency_rumble" ">0" Rumble is both at any arbitrary value, + * StopHard is implemented by setting both "low_frequency_rumble" and + * "high_frequency_rumble" to "0" + * + * This variable can be set to the following values: + * + * - "0": Normal rumble behavior is behavior is used (default) + * - "1": Proper GameCube controller rumble behavior is used + */ +#define SDL_HINT_JOYSTICK_GAMECUBE_RUMBLE_BRAKE "SDL_JOYSTICK_GAMECUBE_RUMBLE_BRAKE" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo Switch + * Joy-Cons should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS "SDL_JOYSTICK_HIDAPI_JOY_CONS" + +/** + * A variable controlling whether Nintendo Switch Joy-Con controllers will be + * combined into a single Pro-like controller when using the HIDAPI driver + * + * This variable can be set to the following values: + * + * - "0": Left and right Joy-Con controllers will not be combined and each + * will be a mini-gamepad + * - "1": Left and right Joy-Con controllers will be combined into a single + * controller (the default) + */ +#define SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS "SDL_JOYSTICK_HIDAPI_COMBINE_JOY_CONS" + +/** + * A variable controlling whether Nintendo Switch Joy-Con controllers will be + * in vertical mode when using the HIDAPI driver + * + * This variable can be set to the following values: + * + * - "0": Left and right Joy-Con controllers will not be in vertical mode (the + * default) + * - "1": Left and right Joy-Con controllers will be in vertical mode + * + * This hint must be set before calling SDL_Init(SDL_INIT_GAMECONTROLLER) + */ +#define SDL_HINT_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS "SDL_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS" + +/** + * A variable controlling whether the HIDAPI driver for Amazon Luna + * controllers connected via Bluetooth should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_LUNA "SDL_JOYSTICK_HIDAPI_LUNA" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo Online + * classic controllers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC "SDL_JOYSTICK_HIDAPI_NINTENDO_CLASSIC" + +/** + * A variable controlling whether the HIDAPI driver for NVIDIA SHIELD + * controllers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_SHIELD "SDL_JOYSTICK_HIDAPI_SHIELD" + +/** + * A variable controlling whether the HIDAPI driver for PS3 controllers should + * be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI on macOS, and "0" on + * other platforms. + * + * It is not possible to use this driver on Windows, due to limitations in the + * default drivers installed. See https://github.com/ViGEm/DsHidMini for an + * alternative driver on Windows. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS3 "SDL_JOYSTICK_HIDAPI_PS3" + +/** + * A variable controlling whether the HIDAPI driver for PS4 controllers should + * be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS4 "SDL_JOYSTICK_HIDAPI_PS4" + +/** + * A variable controlling whether extended input reports should be used for + * PS4 controllers when using the HIDAPI driver. + * + * This variable can be set to the following values: + * + * - "0": extended reports are not enabled (the default) + * - "1": extended reports + * + * Extended input reports allow rumble on Bluetooth PS4 controllers, but break + * DirectInput handling for applications that don't use SDL. + * + * Once extended reports are enabled, they can not be disabled without power + * cycling the controller. + * + * For compatibility with applications written for versions of SDL prior to + * the introduction of PS5 controller support, this value will also control + * the state of extended reports on PS5 controllers when the + * SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE hint is not explicitly set. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE "SDL_JOYSTICK_HIDAPI_PS4_RUMBLE" + +/** + * A variable controlling whether the HIDAPI driver for PS5 controllers should + * be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS5 "SDL_JOYSTICK_HIDAPI_PS5" + +/** + * A variable controlling whether the player LEDs should be lit to indicate + * which player is associated with a PS5 controller. + * + * This variable can be set to the following values: + * + * - "0": player LEDs are not enabled + * - "1": player LEDs are enabled (the default) + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED "SDL_JOYSTICK_HIDAPI_PS5_PLAYER_LED" + +/** + * A variable controlling whether extended input reports should be used for + * PS5 controllers when using the HIDAPI driver. + * + * This variable can be set to the following values: + * + * - "0": extended reports are not enabled (the default) + * - "1": extended reports + * + * Extended input reports allow rumble on Bluetooth PS5 controllers, but break + * DirectInput handling for applications that don't use SDL. + * + * Once extended reports are enabled, they can not be disabled without power + * cycling the controller. + * + * For compatibility with applications written for versions of SDL prior to + * the introduction of PS5 controller support, this value defaults to the + * value of SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE "SDL_JOYSTICK_HIDAPI_PS5_RUMBLE" + +/** + * A variable controlling whether the HIDAPI driver for Google Stadia + * controllers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_STADIA "SDL_JOYSTICK_HIDAPI_STADIA" + +/** + * A variable controlling whether the HIDAPI driver for Bluetooth Steam + * Controllers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used for Steam Controllers, which requires + * Bluetooth access and may prompt the user for permission on iOS and + * Android. + * + * The default is "0" + */ +#define SDL_HINT_JOYSTICK_HIDAPI_STEAM "SDL_JOYSTICK_HIDAPI_STEAM" + +/** + * A variable controlling whether the HIDAPI driver for the Steam Deck builtin + * controller should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_STEAMDECK "SDL_JOYSTICK_HIDAPI_STEAMDECK" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo Switch + * controllers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_SWITCH "SDL_JOYSTICK_HIDAPI_SWITCH" + +/** + * A variable controlling whether the Home button LED should be turned on when + * a Nintendo Switch Pro controller is opened + * + * This variable can be set to the following values: + * + * - "0": home button LED is turned off + * - "1": home button LED is turned on + * + * By default the Home button LED state is not changed. This hint can also be + * set to a floating point value between 0.0 and 1.0 which controls the + * brightness of the Home button LED. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED "SDL_JOYSTICK_HIDAPI_SWITCH_HOME_LED" + +/** + * A variable controlling whether the Home button LED should be turned on when + * a Nintendo Switch Joy-Con controller is opened + * + * This variable can be set to the following values: + * + * - "0": home button LED is turned off + * - "1": home button LED is turned on + * + * By default the Home button LED state is not changed. This hint can also be + * set to a floating point value between 0.0 and 1.0 which controls the + * brightness of the Home button LED. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_JOYCON_HOME_LED "SDL_JOYSTICK_HIDAPI_JOYCON_HOME_LED" + +/** + * A variable controlling whether the player LEDs should be lit to indicate + * which player is associated with a Nintendo Switch controller. + * + * This variable can be set to the following values: + * + * - "0": player LEDs are not enabled + * - "1": player LEDs are enabled (the default) + */ +#define SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED "SDL_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED" + +/** + * A variable controlling whether the HIDAPI driver for Nintendo Wii and Wii U + * controllers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * This driver doesn't work with the dolphinbar, so the default is SDL_FALSE + * for now. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_WII "SDL_JOYSTICK_HIDAPI_WII" + +/** + * A variable controlling whether the player LEDs should be lit to indicate + * which player is associated with a Wii controller. + * + * This variable can be set to the following values: + * + * - "0": player LEDs are not enabled + * - "1": player LEDs are enabled (the default) + */ +#define SDL_HINT_JOYSTICK_HIDAPI_WII_PLAYER_LED "SDL_JOYSTICK_HIDAPI_WII_PLAYER_LED" + +/** + * A variable controlling whether the HIDAPI driver for XBox controllers + * should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is "0" on Windows, otherwise the value of + * SDL_HINT_JOYSTICK_HIDAPI + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX "SDL_JOYSTICK_HIDAPI_XBOX" + +/** + * A variable controlling whether the HIDAPI driver for XBox 360 controllers + * should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI_XBOX + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_360 "SDL_JOYSTICK_HIDAPI_XBOX_360" + +/** + * A variable controlling whether the player LEDs should be lit to indicate + * which player is associated with an Xbox 360 controller. + * + * This variable can be set to the following values: + * + * - "0": player LEDs are not enabled + * - "1": player LEDs are enabled (the default) + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED "SDL_JOYSTICK_HIDAPI_XBOX_360_PLAYER_LED" + +/** + * A variable controlling whether the HIDAPI driver for XBox 360 wireless + * controllers should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI_XBOX_360 + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_360_WIRELESS "SDL_JOYSTICK_HIDAPI_XBOX_360_WIRELESS" + +/** + * A variable controlling whether the HIDAPI driver for XBox One controllers + * should be used. + * + * This variable can be set to the following values: + * + * - "0": HIDAPI driver is not used + * - "1": HIDAPI driver is used + * + * The default is the value of SDL_HINT_JOYSTICK_HIDAPI_XBOX + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE "SDL_JOYSTICK_HIDAPI_XBOX_ONE" + +/** + * A variable controlling whether the Home button LED should be turned on when + * an Xbox One controller is opened + * + * This variable can be set to the following values: + * + * - "0": home button LED is turned off + * - "1": home button LED is turned on + * + * By default the Home button LED state is not changed. This hint can also be + * set to a floating point value between 0.0 and 1.0 which controls the + * brightness of the Home button LED. The default brightness is 0.4. + */ +#define SDL_HINT_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED "SDL_JOYSTICK_HIDAPI_XBOX_ONE_HOME_LED" + +/** + * A variable controlling whether IOKit should be used for controller + * handling. + * + * This variable can be set to the following values: + * + * - "0": IOKit is not used + * - "1": IOKit is used (the default) + */ +#define SDL_HINT_JOYSTICK_IOKIT "SDL_JOYSTICK_IOKIT" + +/** + * A variable controlling whether GCController should be used for controller + * handling. + * + * This variable can be set to the following values: + * + * - "0": GCController is not used + * - "1": GCController is used (the default) + */ +#define SDL_HINT_JOYSTICK_MFI "SDL_JOYSTICK_MFI" + +/** + * A variable controlling whether the RAWINPUT joystick drivers should be used + * for better handling XInput-capable devices. + * + * This variable can be set to the following values: + * + * - "0": RAWINPUT drivers are not used + * - "1": RAWINPUT drivers are used (the default) + */ +#define SDL_HINT_JOYSTICK_RAWINPUT "SDL_JOYSTICK_RAWINPUT" + +/** + * A variable controlling whether the RAWINPUT driver should pull correlated + * data from XInput. + * + * This variable can be set to the following values: + * + * - "0": RAWINPUT driver will only use data from raw input APIs + * - "1": RAWINPUT driver will also pull data from XInput, providing better + * trigger axes, guide button presses, and rumble support for Xbox + * controllers + * + * The default is "1". This hint applies to any joysticks opened after setting + * the hint. + */ +#define SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT "SDL_JOYSTICK_RAWINPUT_CORRELATE_XINPUT" + +/** + * A variable controlling whether the ROG Chakram mice should show up as + * joysticks + * + * This variable can be set to the following values: + * + * - "0": ROG Chakram mice do not show up as joysticks (the default) + * - "1": ROG Chakram mice show up as joysticks + */ +#define SDL_HINT_JOYSTICK_ROG_CHAKRAM "SDL_JOYSTICK_ROG_CHAKRAM" + +/** + * A variable controlling whether a separate thread should be used for + * handling joystick detection and raw input messages on Windows + * + * This variable can be set to the following values: + * + * - "0": A separate thread is not used (the default) + * - "1": A separate thread is used for handling raw input messages + */ +#define SDL_HINT_JOYSTICK_THREAD "SDL_JOYSTICK_THREAD" + +/** + * A variable containing a list of throttle style controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_THROTTLE_DEVICES "SDL_JOYSTICK_THROTTLE_DEVICES" + +/** + * A variable containing a list of devices that are not throttle style + * controllers. + * + * This will override SDL_HINT_JOYSTICK_THROTTLE_DEVICES and the built in + * device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_THROTTLE_DEVICES_EXCLUDED "SDL_JOYSTICK_THROTTLE_DEVICES_EXCLUDED" + +/** + * A variable controlling whether Windows.Gaming.Input should be used for + * controller handling. + * + * This variable can be set to the following values: + * + * - "0": WGI is not used + * - "1": WGI is used (the default) + */ +#define SDL_HINT_JOYSTICK_WGI "SDL_JOYSTICK_WGI" + +/** + * A variable containing a list of wheel style controllers. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_WHEEL_DEVICES "SDL_JOYSTICK_WHEEL_DEVICES" + +/** + * A variable containing a list of devices that are not wheel style + * controllers. + * + * This will override SDL_HINT_JOYSTICK_WHEEL_DEVICES and the built in device + * list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_WHEEL_DEVICES_EXCLUDED "SDL_JOYSTICK_WHEEL_DEVICES_EXCLUDED" + +/** + * A variable containing a list of devices known to have all axes centered at + * zero. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_JOYSTICK_ZERO_CENTERED_DEVICES "SDL_JOYSTICK_ZERO_CENTERED_DEVICES" + +/** + * Determines whether SDL enforces that DRM master is required in order to + * initialize the KMSDRM video backend. + * + * The DRM subsystem has a concept of a "DRM master" which is a DRM client + * that has the ability to set planes, set cursor, etc. When SDL is DRM + * master, it can draw to the screen using the SDL rendering APIs. Without DRM + * master, SDL is still able to process input and query attributes of attached + * displays, but it cannot change display state or draw to the screen + * directly. + * + * In some cases, it can be useful to have the KMSDRM backend even if it + * cannot be used for rendering. An app may want to use SDL for input + * processing while using another rendering API (such as an MMAL overlay on + * Raspberry Pi) or using its own code to render to DRM overlays that SDL + * doesn't support. + * + * This hint must be set before initializing the video subsystem. + * + * This variable can be set to the following values: + * + * - "0": SDL will allow usage of the KMSDRM backend without DRM master + * - "1": SDL Will require DRM master to use the KMSDRM backend (default) + */ +#define SDL_HINT_KMSDRM_REQUIRE_DRM_MASTER "SDL_KMSDRM_REQUIRE_DRM_MASTER" + +/** + * A comma separated list of devices to open as joysticks + * + * This variable is currently only used by the Linux joystick driver. + */ +#define SDL_HINT_JOYSTICK_DEVICE "SDL_JOYSTICK_DEVICE" + +/** + * A variable controlling whether joysticks on Linux will always treat 'hat' + * axis inputs (ABS_HAT0X - ABS_HAT3Y) as 8-way digital hats without checking + * whether they may be analog. + * + * This variable can be set to the following values: + * + * - "0": Only map hat axis inputs to digital hat outputs if the input axes + * appear to actually be digital (the default) + * - "1": Always handle the input axes numbered ABS_HAT0X to ABS_HAT3Y as + * digital hats + */ +#define SDL_HINT_LINUX_DIGITAL_HATS "SDL_LINUX_DIGITAL_HATS" + +/** + * A variable controlling whether digital hats on Linux will apply deadzones + * to their underlying input axes or use unfiltered values. + * + * This variable can be set to the following values: + * + * - "0": Return digital hat values based on unfiltered input axis values + * - "1": Return digital hat values with deadzones on the input axes taken + * into account (the default) + */ +#define SDL_HINT_LINUX_HAT_DEADZONES "SDL_LINUX_HAT_DEADZONES" + +/** + * A variable controlling whether to use the classic /dev/input/js* joystick + * interface or the newer /dev/input/event* joystick interface on Linux + * + * This variable can be set to the following values: + * + * - "0": Use /dev/input/event* + * - "1": Use /dev/input/js* + * + * By default the /dev/input/event* interfaces are used + */ +#define SDL_HINT_LINUX_JOYSTICK_CLASSIC "SDL_LINUX_JOYSTICK_CLASSIC" + +/** + * A variable controlling whether joysticks on Linux adhere to their + * HID-defined deadzones or return unfiltered values. + * + * This variable can be set to the following values: + * + * - "0": Return unfiltered joystick axis values (the default) + * - "1": Return axis values with deadzones taken into account + */ +#define SDL_HINT_LINUX_JOYSTICK_DEADZONES "SDL_LINUX_JOYSTICK_DEADZONES" + +/** + * A variable controlling the default SDL log levels. + * + * This variable is a comma separated set of category=level tokens that define + * the default logging levels for SDL applications. + * + * The category can be a numeric category, one of "app", "error", "assert", + * "system", "audio", "video", "render", "input", "test", or `*` for any + * unspecified category. + * + * The level can be a numeric level, one of "verbose", "debug", "info", + * "warn", "error", "critical", or "quiet" to disable that category. + * + * You can omit the category if you want to set the logging level for all + * categories. + * + * If this hint isn't set, the default log levels are equivalent to: + * "app=info,assert=warn,test=verbose,*=error" + */ +#define SDL_HINT_LOGGING "SDL_LOGGING" + +/** + * When set don't force the SDL app to become a foreground process + * + * This hint only applies to Mac OS X. + */ +#define SDL_HINT_MAC_BACKGROUND_APP "SDL_MAC_BACKGROUND_APP" + +/** + * A variable that determines whether ctrl+click should generate a right-click + * event on Mac + * + * If present, holding ctrl while left clicking will generate a right click + * event when on Mac. + */ +#define SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK" + +/** + * A variable controlling whether dispatching OpenGL context updates should + * block the dispatching thread until the main thread finishes processing + * + * This variable can be set to the following values: + * + * - "0": Dispatching OpenGL context updates will block the dispatching thread + * until the main thread finishes processing (default). + * - "1": Dispatching OpenGL context updates will allow the dispatching thread + * to continue execution. + * + * Generally you want the default, but if you have OpenGL code in a background + * thread on a Mac, and the main thread hangs because it's waiting for that + * background thread, but that background thread is also hanging because it's + * waiting for the main thread to do an update, this might fix your issue. + * + * This hint only applies to macOS. + * + * This hint is available since SDL 2.24.0. + */ +#define SDL_HINT_MAC_OPENGL_ASYNC_DISPATCH "SDL_MAC_OPENGL_ASYNC_DISPATCH" + +/** + * A variable setting the double click radius, in pixels. + */ +#define SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS "SDL_MOUSE_DOUBLE_CLICK_RADIUS" + +/** + * A variable setting the double click time, in milliseconds. + */ +#define SDL_HINT_MOUSE_DOUBLE_CLICK_TIME "SDL_MOUSE_DOUBLE_CLICK_TIME" + +/** + * Allow mouse click events when clicking to focus an SDL window + * + * This variable can be set to the following values: + * + * - "0": Ignore mouse clicks that activate a window + * - "1": Generate events for mouse clicks that activate a window + * + * By default SDL will ignore mouse clicks that activate a window + */ +#define SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH "SDL_MOUSE_FOCUS_CLICKTHROUGH" + +/** + * A variable setting the speed scale for mouse motion, in floating point, + * when the mouse is not in relative mode + */ +#define SDL_HINT_MOUSE_NORMAL_SPEED_SCALE "SDL_MOUSE_NORMAL_SPEED_SCALE" + +/** + * A variable controlling whether relative mouse mode constrains the mouse to + * the center of the window + * + * This variable can be set to the following values: + * + * - "0": Relative mouse mode constrains the mouse to the window + * - "1": Relative mouse mode constrains the mouse to the center of the window + * + * Constraining to the center of the window works better for FPS games and + * when the application is running over RDP. Constraining to the whole window + * works better for 2D games and increases the chance that the mouse will be + * in the correct position when using high DPI mice. + * + * By default SDL will constrain the mouse to the center of the window + */ +#define SDL_HINT_MOUSE_RELATIVE_MODE_CENTER "SDL_MOUSE_RELATIVE_MODE_CENTER" + +/** + * A variable controlling whether relative mouse mode is implemented using + * mouse warping + * + * This variable can be set to the following values: + * + * - "0": Relative mouse mode uses raw input + * - "1": Relative mouse mode uses mouse warping + * + * By default SDL will use raw input for relative mouse mode + */ +#define SDL_HINT_MOUSE_RELATIVE_MODE_WARP "SDL_MOUSE_RELATIVE_MODE_WARP" + +/** + * A variable controlling whether relative mouse motion is affected by + * renderer scaling + * + * This variable can be set to the following values: + * + * - "0": Relative motion is unaffected by DPI or renderer's logical size + * - "1": Relative motion is scaled according to DPI scaling and logical size + * + * By default relative mouse deltas are affected by DPI and renderer scaling + */ +#define SDL_HINT_MOUSE_RELATIVE_SCALING "SDL_MOUSE_RELATIVE_SCALING" + +/** + * A variable setting the scale for mouse motion, in floating point, when the + * mouse is in relative mode + */ +#define SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE "SDL_MOUSE_RELATIVE_SPEED_SCALE" + +/** + * A variable controlling whether the system mouse acceleration curve is used + * for relative mouse motion. + * + * This variable can be set to the following values: + * + * - "0": Relative mouse motion will be unscaled (the default) + * - "1": Relative mouse motion will be scaled using the system mouse + * acceleration curve. + * + * If SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE is set, that will override the + * system speed scale. + */ +#define SDL_HINT_MOUSE_RELATIVE_SYSTEM_SCALE "SDL_MOUSE_RELATIVE_SYSTEM_SCALE" + +/** + * A variable controlling whether a motion event should be generated for mouse + * warping in relative mode. + * + * This variable can be set to the following values: + * + * - "0": Warping the mouse will not generate a motion event in relative mode + * - "1": Warping the mouse will generate a motion event in relative mode + * + * By default warping the mouse will not generate motion events in relative + * mode. This avoids the application having to filter out large relative + * motion due to warping. + */ +#define SDL_HINT_MOUSE_RELATIVE_WARP_MOTION "SDL_MOUSE_RELATIVE_WARP_MOTION" + +/** + * A variable controlling whether the hardware cursor stays visible when + * relative mode is active. + * + * This variable can be set to the following values: "0" - The cursor will be + * hidden while relative mode is active (default) "1" - The cursor will remain + * visible while relative mode is active + * + * Note that for systems without raw hardware inputs, relative mode is + * implemented using warping, so the hardware cursor will visibly warp between + * frames if this is enabled on those systems. + */ +#define SDL_HINT_MOUSE_RELATIVE_CURSOR_VISIBLE "SDL_MOUSE_RELATIVE_CURSOR_VISIBLE" + +/** + * A variable controlling whether mouse events should generate synthetic touch + * events + * + * This variable can be set to the following values: + * + * - "0": Mouse events will not generate touch events (default for desktop + * platforms) + * - "1": Mouse events will generate touch events (default for mobile + * platforms, such as Android and iOS) + */ +#define SDL_HINT_MOUSE_TOUCH_EVENTS "SDL_MOUSE_TOUCH_EVENTS" + +/** + * A variable controlling whether the mouse is captured while mouse buttons + * are pressed + * + * This variable can be set to the following values: + * + * - "0": The mouse is not captured while mouse buttons are pressed + * - "1": The mouse is captured while mouse buttons are pressed + * + * By default the mouse is captured while mouse buttons are pressed so if the + * mouse is dragged outside the window, the application continues to receive + * mouse events until the button is released. + */ +#define SDL_HINT_MOUSE_AUTO_CAPTURE "SDL_MOUSE_AUTO_CAPTURE" + +/** + * Tell SDL not to catch the SIGINT or SIGTERM signals. + * + * This hint only applies to Unix-like platforms, and should set before any + * calls to SDL_Init() + * + * The variable can be set to the following values: + * + * - "0": SDL will install a SIGINT and SIGTERM handler, and when it catches a + * signal, convert it into an SDL_QUIT event. + * - "1": SDL will not install a signal handler at all. + */ +#define SDL_HINT_NO_SIGNAL_HANDLERS "SDL_NO_SIGNAL_HANDLERS" + +/** + * A variable controlling what driver to use for OpenGL ES contexts. + * + * On some platforms, currently Windows and X11, OpenGL drivers may support + * creating contexts with an OpenGL ES profile. By default SDL uses these + * profiles, when available, otherwise it attempts to load an OpenGL ES + * library, e.g. that provided by the ANGLE project. This variable controls + * whether SDL follows this default behaviour or will always load an OpenGL ES + * library. + * + * Circumstances where this is useful include - Testing an app with a + * particular OpenGL ES implementation, e.g ANGLE, or emulator, e.g. those + * from ARM, Imagination or Qualcomm. - Resolving OpenGL ES function addresses + * at link time by linking with the OpenGL ES library instead of querying them + * at run time with SDL_GL_GetProcAddress(). + * + * Caution: for an application to work with the default behaviour across + * different OpenGL drivers it must query the OpenGL ES function addresses at + * run time using SDL_GL_GetProcAddress(). + * + * This variable is ignored on most platforms because OpenGL ES is native or + * not supported. + * + * This variable can be set to the following values: + * + * - "0": Use ES profile of OpenGL, if available. (Default when not set.) + * - "1": Load OpenGL ES library using the default library names. + */ +#define SDL_HINT_OPENGL_ES_DRIVER "SDL_OPENGL_ES_DRIVER" + +/** + * A variable controlling which orientations are allowed on iOS/Android. + * + * In some circumstances it is necessary to be able to explicitly control + * which UI orientations are allowed. + * + * This variable is a space delimited list of the following values: + * + * - "LandscapeLeft" + * - "LandscapeRight" + * - "Portrait" + * - "PortraitUpsideDown" + */ +#define SDL_HINT_ORIENTATIONS "SDL_IOS_ORIENTATIONS" + +/** + * A variable controlling the use of a sentinel event when polling the event + * queue + * + * This variable can be set to the following values: + * + * - "0": Disable poll sentinels + * - "1": Enable poll sentinels + * + * When polling for events, SDL_PumpEvents is used to gather new events from + * devices. If a device keeps producing new events between calls to + * SDL_PumpEvents, a poll loop will become stuck until the new events stop. + * This is most noticeable when moving a high frequency mouse. + * + * By default, poll sentinels are enabled. + */ +#define SDL_HINT_POLL_SENTINEL "SDL_POLL_SENTINEL" + +/** + * Override for SDL_GetPreferredLocales() + * + * If set, this will be favored over anything the OS might report for the + * user's preferred locales. Changing this hint at runtime will not generate a + * SDL_LOCALECHANGED event (but if you can change the hint, you can push your + * own event, if you want). + * + * The format of this hint is a comma-separated list of language and locale, + * combined with an underscore, as is a common format: "en_GB". Locale is + * optional: "en". So you might have a list like this: "en_GB,jp,es_PT" + */ +#define SDL_HINT_PREFERRED_LOCALES "SDL_PREFERRED_LOCALES" + +/** + * A variable describing the content orientation on QtWayland-based platforms. + * + * On QtWayland platforms, windows are rotated client-side to allow for custom + * transitions. In order to correctly position overlays (e.g. volume bar) and + * gestures (e.g. events view, close/minimize gestures), the system needs to + * know in which orientation the application is currently drawing its + * contents. + * + * This does not cause the window to be rotated or resized, the application + * needs to take care of drawing the content in the right orientation (the + * framebuffer is always in portrait mode). + * + * This variable can be one of the following values: + * + * - "primary" (default) + * - "portrait" + * - "landscape" + * - "inverted-portrait" + * - "inverted-landscape" + * + * Since SDL 2.0.22 this variable accepts a comma-separated list of values + * above. + */ +#define SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION "SDL_QTWAYLAND_CONTENT_ORIENTATION" + +/** + * Flags to set on QtWayland windows to integrate with the native window + * manager. + * + * On QtWayland platforms, this hint controls the flags to set on the windows. + * For example, on Sailfish OS "OverridesSystemGestures" disables swipe + * gestures. + * + * This variable is a space-separated list of the following values (empty = no + * flags): + * + * - "OverridesSystemGestures" + * - "StaysOnTop" + * - "BypassWindowManager" + */ +#define SDL_HINT_QTWAYLAND_WINDOW_FLAGS "SDL_QTWAYLAND_WINDOW_FLAGS" + +/** + * A variable controlling whether the 2D render API is compatible or + * efficient. + * + * This variable can be set to the following values: + * + * - "0": Don't use batching to make rendering more efficient. + * - "1": Use batching, but might cause problems if app makes its own direct + * OpenGL calls. + * + * Up to SDL 2.0.9, the render API would draw immediately when requested. Now + * it batches up draw requests and sends them all to the GPU only when forced + * to (during SDL_RenderPresent, when changing render targets, by updating a + * texture that the batch needs, etc). This is significantly more efficient, + * but it can cause problems for apps that expect to render on top of the + * render API's output. As such, SDL will disable batching if a specific + * render backend is requested (since this might indicate that the app is + * planning to use the underlying graphics API directly). This hint can be + * used to explicitly request batching in this instance. It is a contract that + * you will either never use the underlying graphics API directly, or if you + * do, you will call SDL_RenderFlush() before you do so any current batch goes + * to the GPU before your work begins. Not following this contract will result + * in undefined behavior. + */ +#define SDL_HINT_RENDER_BATCHING "SDL_RENDER_BATCHING" + +/** + * A variable controlling how the 2D render API renders lines + * + * This variable can be set to the following values: + * + * - "0": Use the default line drawing method (Bresenham's line algorithm as + * of SDL 2.0.20) + * - "1": Use the driver point API using Bresenham's line algorithm (correct, + * draws many points) + * - "2": Use the driver line API (occasionally misses line endpoints based on + * hardware driver quirks, was the default before 2.0.20) + * - "3": Use the driver geometry API (correct, draws thicker diagonal lines) + * + * This variable should be set when the renderer is created. + */ +#define SDL_HINT_RENDER_LINE_METHOD "SDL_RENDER_LINE_METHOD" + +/** + * A variable controlling whether to enable Direct3D 11+'s Debug Layer. + * + * This variable does not have any effect on the Direct3D 9 based renderer. + * + * This variable can be set to the following values: + * + * - "0": Disable Debug Layer use + * - "1": Enable Debug Layer use + * + * By default, SDL does not use Direct3D Debug Layer. + */ +#define SDL_HINT_RENDER_DIRECT3D11_DEBUG "SDL_RENDER_DIRECT3D11_DEBUG" + +/** + * A variable controlling whether the Direct3D device is initialized for + * thread-safe operations. + * + * This variable can be set to the following values: + * + * - "0": Thread-safety is not enabled (faster) + * - "1": Thread-safety is enabled + * + * By default the Direct3D device is created with thread-safety disabled. + */ +#define SDL_HINT_RENDER_DIRECT3D_THREADSAFE "SDL_RENDER_DIRECT3D_THREADSAFE" + +/** + * A variable specifying which render driver to use. + * + * If the application doesn't pick a specific renderer to use, this variable + * specifies the name of the preferred renderer. If the preferred renderer + * can't be initialized, the normal default renderer is used. + * + * This variable is case insensitive and can be set to the following values: + * + * - "direct3d" + * - "direct3d11" + * - "direct3d12" + * - "opengl" + * - "opengles2" + * - "opengles" + * - "metal" + * - "software" + * + * The default varies by platform, but it's the first one in the list that is + * available on the current platform. + */ +#define SDL_HINT_RENDER_DRIVER "SDL_RENDER_DRIVER" + +/** + * A variable controlling the scaling policy for SDL_RenderSetLogicalSize. + * + * This variable can be set to the following values: + * + * "0" or "letterbox" - Uses letterbox/sidebars to fit the entire rendering on + * screen "1" or "overscan" - Will zoom the rendering so it fills the entire + * screen, allowing edges to be drawn offscreen + * + * By default letterbox is used + */ +#define SDL_HINT_RENDER_LOGICAL_SIZE_MODE "SDL_RENDER_LOGICAL_SIZE_MODE" + +/** + * A variable controlling whether the OpenGL render driver uses shaders if + * they are available. + * + * This variable can be set to the following values: + * + * - "0": Disable shaders + * - "1": Enable shaders + * + * By default shaders are used if OpenGL supports them. + */ +#define SDL_HINT_RENDER_OPENGL_SHADERS "SDL_RENDER_OPENGL_SHADERS" + +/** + * A variable controlling the scaling quality + * + * This variable can be set to the following values: + * + * - "0" or "nearest": Nearest pixel sampling + * - "1" or "linear": Linear filtering (supported by OpenGL and Direct3D) + * - "2" or "best": Currently this is the same as "linear" + * + * By default nearest pixel sampling is used + */ +#define SDL_HINT_RENDER_SCALE_QUALITY "SDL_RENDER_SCALE_QUALITY" + +/** + * A variable controlling whether updates to the SDL screen surface should be + * synchronized with the vertical refresh, to avoid tearing. + * + * This variable can be set to the following values: + * + * - "0": Disable vsync + * - "1": Enable vsync + * + * By default SDL does not sync screen surface updates with vertical refresh. + */ +#define SDL_HINT_RENDER_VSYNC "SDL_RENDER_VSYNC" + +/** + * A variable controlling whether the Metal render driver select low power + * device over default one + * + * This variable can be set to the following values: + * + * - "0": Use the prefered OS device + * - "1": Select a low power one + * + * By default the prefered OS device is used. + */ +#define SDL_HINT_RENDER_METAL_PREFER_LOW_POWER_DEVICE "SDL_RENDER_METAL_PREFER_LOW_POWER_DEVICE" + +/** + * A variable containing a list of ROG gamepad capable mice. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_ROG_GAMEPAD_MICE "SDL_ROG_GAMEPAD_MICE" + +/** + * A variable containing a list of devices that are not ROG gamepad capable + * mice. + * + * This will override SDL_HINT_ROG_GAMEPAD_MICE and the built in device list. + * + * The format of the string is a comma separated list of USB VID/PID pairs in + * hexadecimal form, e.g. + * + * 0xAAAA/0xBBBB,0xCCCC/0xDDDD + * + * The variable can also take the form of @file, in which case the named file + * will be loaded and interpreted as the value of the variable. + */ +#define SDL_HINT_ROG_GAMEPAD_MICE_EXCLUDED "SDL_ROG_GAMEPAD_MICE_EXCLUDED" + +/** + * A variable controlling if VSYNC is automatically disable if doesn't reach + * the enough FPS + * + * This variable can be set to the following values: + * + * - "0": It will be using VSYNC as defined in the main flag. Default + * - "1": If VSYNC was previously enabled, then it will disable VSYNC if + * doesn't reach enough speed + * + * By default SDL does not enable the automatic VSYNC + */ +#define SDL_HINT_PS2_DYNAMIC_VSYNC "SDL_PS2_DYNAMIC_VSYNC" + +/** + * A variable to control whether the return key on the soft keyboard should + * hide the soft keyboard on Android and iOS. + * + * The variable can be set to the following values: + * + * - "0": The return key will be handled as a key event. This is the behaviour + * of SDL <= 2.0.3. (default) + * - "1": The return key will hide the keyboard. + * + * The value of this hint is used at runtime, so it can be changed at any + * time. + */ +#define SDL_HINT_RETURN_KEY_HIDES_IME "SDL_RETURN_KEY_HIDES_IME" + +/** + * Tell SDL which Dispmanx layer to use on a Raspberry PI + * + * Also known as Z-order. The variable can take a negative or positive value. + * The default is 10000. + */ +#define SDL_HINT_RPI_VIDEO_LAYER "SDL_RPI_VIDEO_LAYER" + +/** + * Specify an "activity name" for screensaver inhibition. + * + * Some platforms, notably Linux desktops, list the applications which are + * inhibiting the screensaver or other power-saving features. + * + * This hint lets you specify the "activity name" sent to the OS when + * SDL_DisableScreenSaver() is used (or the screensaver is automatically + * disabled). The contents of this hint are used when the screensaver is + * disabled. You should use a string that describes what your program is doing + * (and, therefore, why the screensaver is disabled). For example, "Playing a + * game" or "Watching a video". + * + * Setting this to "" or leaving it unset will have SDL use a reasonable + * default: "Playing a game" or something similar. + * + * On targets where this is not supported, this hint does nothing. + */ +#define SDL_HINT_SCREENSAVER_INHIBIT_ACTIVITY_NAME "SDL_SCREENSAVER_INHIBIT_ACTIVITY_NAME" + +/** + * Specifies whether SDL_THREAD_PRIORITY_TIME_CRITICAL should be treated as + * realtime. + * + * On some platforms, like Linux, a realtime priority thread may be subject to + * restrictions that require special handling by the application. This hint + * exists to let SDL know that the app is prepared to handle said + * restrictions. + * + * On Linux, SDL will apply the following configuration to any thread that + * becomes realtime: + * + * - The SCHED_RESET_ON_FORK bit will be set on the scheduling policy. + * - An RLIMIT_RTTIME budget will be configured to the rtkit specified limit. + * - Exceeding this limit will result in the kernel sending SIGKILL to the + * app. + * + * Refer to the man pages for more information. + * + * This variable can be set to the following values: + * + * - "0": default platform specific behaviour + * - "1": Force SDL_THREAD_PRIORITY_TIME_CRITICAL to a realtime scheduling + * policy + */ +#define SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL "SDL_THREAD_FORCE_REALTIME_TIME_CRITICAL" + +/** + * A string specifying additional information to use with + * SDL_SetThreadPriority. + * + * By default SDL_SetThreadPriority will make appropriate system changes in + * order to apply a thread priority. For example on systems using pthreads the + * scheduler policy is changed automatically to a policy that works well with + * a given priority. Code which has specific requirements can override SDL's + * default behavior with this hint. + * + * pthread hint values are "current", "other", "fifo" and "rr". Currently no + * other platform hint values are defined but may be in the future. + */ +#define SDL_HINT_THREAD_PRIORITY_POLICY "SDL_THREAD_PRIORITY_POLICY" + +/** + * A string specifying SDL's threads stack size in bytes or "0" for the + * backend's default size + * + * Use this hint in case you need to set SDL's threads stack size to other + * than the default. This is specially useful if you build SDL against a non + * glibc libc library (such as musl) which provides a relatively small default + * thread stack size (a few kilobytes versus the default 8MB glibc uses). + * Support for this hint is currently available only in the pthread, Windows, + * and PSP backend. + * + * Instead of this hint, in 2.0.9 and later, you can use + * SDL_CreateThreadWithStackSize(). This hint only works with the classic + * SDL_CreateThread(). + */ +#define SDL_HINT_THREAD_STACK_SIZE "SDL_THREAD_STACK_SIZE" + +/** + * A variable that controls the timer resolution, in milliseconds. + * + * The higher resolution the timer, the more frequently the CPU services timer + * interrupts, and the more precise delays are, but this takes up power and + * CPU time. This hint is only used on Windows. + * + * See this blog post for more information: + * http://randomascii.wordpress.com/2013/07/08/windows-timer-resolution-megawatts-wasted/ + * + * If this variable is set to "0", the system timer resolution is not set. + * + * The default value is "1". This hint may be set at any time. + */ +#define SDL_HINT_TIMER_RESOLUTION "SDL_TIMER_RESOLUTION" + +/** + * A variable controlling whether touch events should generate synthetic mouse + * events + * + * This variable can be set to the following values: + * + * - "0": Touch events will not generate mouse events + * - "1": Touch events will generate mouse events + * + * By default SDL will generate mouse events for touch events + */ +#define SDL_HINT_TOUCH_MOUSE_EVENTS "SDL_TOUCH_MOUSE_EVENTS" + +/** + * A variable controlling which touchpad should generate synthetic mouse + * events + * + * This variable can be set to the following values: + * + * - "0": Only front touchpad should generate mouse events. Default + * - "1": Only back touchpad should generate mouse events. + * - "2": Both touchpads should generate mouse events. + * + * By default SDL will generate mouse events for all touch devices + */ +#define SDL_HINT_VITA_TOUCH_MOUSE_DEVICE "SDL_HINT_VITA_TOUCH_MOUSE_DEVICE" + +/** + * A variable controlling whether the Android / tvOS remotes should be listed + * as joystick devices, instead of sending keyboard events. + * + * This variable can be set to the following values: + * + * - "0": Remotes send enter/escape/arrow key events + * - "1": Remotes are available as 2 axis, 2 button joysticks (the default). + */ +#define SDL_HINT_TV_REMOTE_AS_JOYSTICK "SDL_TV_REMOTE_AS_JOYSTICK" + +/** + * A variable controlling whether the screensaver is enabled. + * + * This variable can be set to the following values: + * + * - "0": Disable screensaver + * - "1": Enable screensaver + * + * By default SDL will disable the screensaver. + */ +#define SDL_HINT_VIDEO_ALLOW_SCREENSAVER "SDL_VIDEO_ALLOW_SCREENSAVER" + +/** + * Tell the video driver that we only want a double buffer. + * + * By default, most lowlevel 2D APIs will use a triple buffer scheme that + * wastes no CPU time on waiting for vsync after issuing a flip, but + * introduces a frame of latency. On the other hand, using a double buffer + * scheme instead is recommended for cases where low latency is an important + * factor because we save a whole frame of latency. We do so by waiting for + * vsync immediately after issuing a flip, usually just after eglSwapBuffers + * call in the backend's *_SwapWindow function. + * + * Since it's driver-specific, it's only supported where possible and + * implemented. Currently supported the following drivers: + * + * - Wayland (wayland) + * - KMSDRM (kmsdrm) + * - Raspberry Pi (raspberrypi) + */ +#define SDL_HINT_VIDEO_DOUBLE_BUFFER "SDL_VIDEO_DOUBLE_BUFFER" + +/** + * A variable controlling whether the EGL window is allowed to be composited + * as transparent, rather than opaque. + * + * Most window systems will always render windows opaque, even if the surface + * format has an alpha channel. This is not always true, however, so by + * default SDL will try to enforce opaque composition. To override this + * behavior, you can set this hint to "1". + */ +#define SDL_HINT_VIDEO_EGL_ALLOW_TRANSPARENCY "SDL_VIDEO_EGL_ALLOW_TRANSPARENCY" + +/** + * A variable controlling whether the graphics context is externally managed. + * + * This variable can be set to the following values: + * + * - "0": SDL will manage graphics contexts that are attached to windows. + * - "1": Disable graphics context management on windows. + * + * By default SDL will manage OpenGL contexts in certain situations. For + * example, on Android the context will be automatically saved and restored + * when pausing the application. Additionally, some platforms will assume + * usage of OpenGL if Vulkan isn't used. Setting this to "1" will prevent this + * behavior, which is desireable when the application manages the graphics + * context, such as an externally managed OpenGL context or attaching a Vulkan + * surface to the window. + */ +#define SDL_HINT_VIDEO_EXTERNAL_CONTEXT "SDL_VIDEO_EXTERNAL_CONTEXT" + +/** + * If set to 1, then do not allow high-DPI windows. + * + * ("Retina" on Mac and iOS) + */ +#define SDL_HINT_VIDEO_HIGHDPI_DISABLED "SDL_VIDEO_HIGHDPI_DISABLED" + +/** + * A variable that dictates policy for fullscreen Spaces on Mac OS X. + * + * This hint only applies to Mac OS X. + * + * The variable can be set to the following values: + * + * - "0": Disable Spaces support (FULLSCREEN_DESKTOP won't use them and + * SDL_WINDOW_RESIZABLE windows won't offer the "fullscreen" button on their + * titlebars). + * - "1": Enable Spaces support (FULLSCREEN_DESKTOP will use them and + * SDL_WINDOW_RESIZABLE windows will offer the "fullscreen" button on their + * titlebars). + * + * The default value is "1". This hint must be set before any windows are + * created. + */ +#define SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES "SDL_VIDEO_MAC_FULLSCREEN_SPACES" + +/** + * Minimize your SDL_Window if it loses key focus when in fullscreen mode. + * + * Defaults to false. + */ +#define SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS" + +/** + * A variable controlling whether the libdecor Wayland backend is allowed to + * be used. + * + * This variable can be set to the following values: + * + * - "0": libdecor use is disabled. + * - "1": libdecor use is enabled (default). + * + * libdecor is used over xdg-shell when xdg-decoration protocol is + * unavailable. + */ +#define SDL_HINT_VIDEO_WAYLAND_ALLOW_LIBDECOR "SDL_VIDEO_WAYLAND_ALLOW_LIBDECOR" + +/** + * A variable controlling whether the libdecor Wayland backend is preferred + * over native decorations. + * + * When this hint is set, libdecor will be used to provide window decorations, + * even if xdg-decoration is available. (Note that, by default, libdecor will + * use xdg-decoration itself if available). + * + * This variable can be set to the following values: + * + * - "0": libdecor is enabled only if server-side decorations are unavailable. + * - "1": libdecor is always enabled if available. + * + * libdecor is used over xdg-shell when xdg-decoration protocol is + * unavailable. + */ +#define SDL_HINT_VIDEO_WAYLAND_PREFER_LIBDECOR "SDL_VIDEO_WAYLAND_PREFER_LIBDECOR" + +/** + * A variable controlling whether video mode emulation is enabled under + * Wayland. + * + * When this hint is set, a standard set of emulated CVT video modes will be + * exposed for use by the application. If it is disabled, the only modes + * exposed will be the logical desktop size and, in the case of a scaled + * desktop, the native display resolution. + * + * This variable can be set to the following values: + * + * - "0": Video mode emulation is disabled. + * - "1": Video mode emulation is enabled. + * + * By default video mode emulation is enabled. + */ +#define SDL_HINT_VIDEO_WAYLAND_MODE_EMULATION "SDL_VIDEO_WAYLAND_MODE_EMULATION" + +/** + * Enable or disable mouse pointer warp emulation, needed by some older games. + * + * When this hint is set, any SDL will emulate mouse warps using relative + * mouse mode. This is required for some older games (such as Source engine + * games), which warp the mouse to the centre of the screen rather than using + * relative mouse motion. Note that relative mouse mode may have different + * mouse acceleration behaviour than pointer warps. + * + * This variable can be set to the following values: + * + * - "0": All mouse warps fail, as mouse warping is not available under + * wayland. + * - "1": Some mouse warps will be emulated by forcing relative mouse mode. + * + * If not set, this is automatically enabled unless an application uses + * relative mouse mode directly. + */ +#define SDL_HINT_VIDEO_WAYLAND_EMULATE_MOUSE_WARP "SDL_VIDEO_WAYLAND_EMULATE_MOUSE_WARP" + +/** + * A variable that is the address of another SDL_Window* (as a hex string + * formatted with "%p"). + * + * If this hint is set before SDL_CreateWindowFrom() and the SDL_Window* it is + * set to has SDL_WINDOW_OPENGL set (and running on WGL only, currently), then + * two things will occur on the newly created SDL_Window: + * + * 1. Its pixel format will be set to the same pixel format as this + * SDL_Window. This is needed for example when sharing an OpenGL context + * across multiple windows. + * + * 2. The flag SDL_WINDOW_OPENGL will be set on the new window so it can be + * used for OpenGL rendering. + * + * This variable can be set to the following values: The address (as a string + * "%p") of the SDL_Window* that new windows created with + * SDL_CreateWindowFrom() should share a pixel format with. + */ +#define SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT "SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT" + +/** + * When calling SDL_CreateWindowFrom(), make the window compatible with + * OpenGL. + * + * This variable can be set to the following values: + * + * - "0": Don't add any graphics flags to the SDL_WindowFlags + * - "1": Add SDL_WINDOW_OPENGL to the SDL_WindowFlags + * + * By default SDL will not make the foreign window compatible with OpenGL. + */ +#define SDL_HINT_VIDEO_FOREIGN_WINDOW_OPENGL "SDL_VIDEO_FOREIGN_WINDOW_OPENGL" + +/** + * When calling SDL_CreateWindowFrom(), make the window compatible with + * Vulkan. + * + * This variable can be set to the following values: + * + * - "0": Don't add any graphics flags to the SDL_WindowFlags + * - "1": Add SDL_WINDOW_VULKAN to the SDL_WindowFlags + * + * By default SDL will not make the foreign window compatible with Vulkan. + */ +#define SDL_HINT_VIDEO_FOREIGN_WINDOW_VULKAN "SDL_VIDEO_FOREIGN_WINDOW_VULKAN" + +/** + * A variable specifying which shader compiler to preload when using the + * Chrome ANGLE binaries + * + * SDL has EGL and OpenGL ES2 support on Windows via the ANGLE project. It can + * use two different sets of binaries, those compiled by the user from source + * or those provided by the Chrome browser. In the later case, these binaries + * require that SDL loads a DLL providing the shader compiler. + * + * This variable can be set to the following values: + * + * - "d3dcompiler_46.dll: default, best for Vista or later. + * - "d3dcompiler_43.dll: for XP support. + * - "none": do not load any library, useful if you compiled ANGLE from source + * and included the compiler in your binaries. + */ +#define SDL_HINT_VIDEO_WIN_D3DCOMPILER "SDL_VIDEO_WIN_D3DCOMPILER" + +/** + * A variable controlling whether X11 should use GLX or EGL by default + * + * This variable can be set to the following values: + * + * - "0": Use GLX + * - "1": Use EGL + * + * By default SDL will use GLX when both are present. + */ +#define SDL_HINT_VIDEO_X11_FORCE_EGL "SDL_VIDEO_X11_FORCE_EGL" + +/** + * A variable controlling whether the X11 _NET_WM_BYPASS_COMPOSITOR hint + * should be used. + * + * This variable can be set to the following values: + * + * - "0": Disable _NET_WM_BYPASS_COMPOSITOR + * - "1": Enable _NET_WM_BYPASS_COMPOSITOR + * + * By default SDL will use _NET_WM_BYPASS_COMPOSITOR + */ +#define SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR "SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR" + +/** + * A variable controlling whether the X11 _NET_WM_PING protocol should be + * supported. + * + * This variable can be set to the following values: + * + * - "0": Disable _NET_WM_PING + * - "1": Enable _NET_WM_PING + * + * By default SDL will use _NET_WM_PING, but for applications that know they + * will not always be able to respond to ping requests in a timely manner they + * can turn it off to avoid the window manager thinking the app is hung. The + * hint is checked in CreateWindow. + */ +#define SDL_HINT_VIDEO_X11_NET_WM_PING "SDL_VIDEO_X11_NET_WM_PING" + +/** + * A variable forcing the visual ID chosen for new X11 windows + */ +#define SDL_HINT_VIDEO_X11_WINDOW_VISUALID "SDL_VIDEO_X11_WINDOW_VISUALID" + +/** + * A no-longer-used variable controlling whether the X11 Xinerama extension + * should be used. + * + * Before SDL 2.0.24, this would let apps and users disable Xinerama support + * on X11. Now SDL never uses Xinerama, and does not check for this hint at + * all. The preprocessor define is left here for source compatibility. + */ +#define SDL_HINT_VIDEO_X11_XINERAMA "SDL_VIDEO_X11_XINERAMA" + +/** + * A variable controlling whether the X11 XRandR extension should be used. + * + * This variable can be set to the following values: + * + * - "0": Disable XRandR + * - "1": Enable XRandR + * + * By default SDL will use XRandR. + */ +#define SDL_HINT_VIDEO_X11_XRANDR "SDL_VIDEO_X11_XRANDR" + +/** + * A no-longer-used variable controlling whether the X11 VidMode extension + * should be used. + * + * Before SDL 2.0.24, this would let apps and users disable XVidMode support + * on X11. Now SDL never uses XVidMode, and does not check for this hint at + * all. The preprocessor define is left here for source compatibility. + */ +#define SDL_HINT_VIDEO_X11_XVIDMODE "SDL_VIDEO_X11_XVIDMODE" + +/** + * Controls how the fact chunk affects the loading of a WAVE file. + * + * The fact chunk stores information about the number of samples of a WAVE + * file. The Standards Update from Microsoft notes that this value can be used + * to 'determine the length of the data in seconds'. This is especially useful + * for compressed formats (for which this is a mandatory chunk) if they + * produce multiple sample frames per block and truncating the block is not + * allowed. The fact chunk can exactly specify how many sample frames there + * should be in this case. + * + * Unfortunately, most application seem to ignore the fact chunk and so SDL + * ignores it by default as well. + * + * This variable can be set to the following values: + * + * - "truncate": Use the number of samples to truncate the wave data if the + * fact chunk is present and valid + * - "strict": Like "truncate", but raise an error if the fact chunk is + * invalid, not present for non-PCM formats, or if the data chunk doesn't + * have that many samples + * - "ignorezero": Like "truncate", but ignore fact chunk if the number of + * samples is zero + * - "ignore": Ignore fact chunk entirely (default) + */ +#define SDL_HINT_WAVE_FACT_CHUNK "SDL_WAVE_FACT_CHUNK" + +/** + * Controls how the size of the RIFF chunk affects the loading of a WAVE file. + * + * The size of the RIFF chunk (which includes all the sub-chunks of the WAVE + * file) is not always reliable. In case the size is wrong, it's possible to + * just ignore it and step through the chunks until a fixed limit is reached. + * + * Note that files that have trailing data unrelated to the WAVE file or + * corrupt files may slow down the loading process without a reliable + * boundary. By default, SDL stops after 10000 chunks to prevent wasting time. + * Use the environment variable SDL_WAVE_CHUNK_LIMIT to adjust this value. + * + * This variable can be set to the following values: + * + * - "force": Always use the RIFF chunk size as a boundary for the chunk + * search + * - "ignorezero": Like "force", but a zero size searches up to 4 GiB + * (default) + * - "ignore": Ignore the RIFF chunk size and always search up to 4 GiB + * - "maximum": Search for chunks until the end of file (not recommended) + */ +#define SDL_HINT_WAVE_RIFF_CHUNK_SIZE "SDL_WAVE_RIFF_CHUNK_SIZE" + +/** + * Controls how a truncated WAVE file is handled. + * + * A WAVE file is considered truncated if any of the chunks are incomplete or + * the data chunk size is not a multiple of the block size. By default, SDL + * decodes until the first incomplete block, as most applications seem to do. + * + * This variable can be set to the following values: + * + * - "verystrict": Raise an error if the file is truncated + * - "strict": Like "verystrict", but the size of the RIFF chunk is ignored + * - "dropframe": Decode until the first incomplete sample frame + * - "dropblock": Decode until the first incomplete block (default) + */ +#define SDL_HINT_WAVE_TRUNCATION "SDL_WAVE_TRUNCATION" + +/** + * Tell SDL not to name threads on Windows with the 0x406D1388 Exception. + * + * The 0x406D1388 Exception is a trick used to inform Visual Studio of a + * thread's name, but it tends to cause problems with other debuggers, and the + * .NET runtime. Note that SDL 2.0.6 and later will still use the (safer) + * SetThreadDescription API, introduced in the Windows 10 Creators Update, if + * available. + * + * The variable can be set to the following values: + * + * - "0": SDL will raise the 0x406D1388 Exception to name threads. This is the + * default behavior of SDL <= 2.0.4. + * - "1": SDL will not raise this exception, and threads will be unnamed. + * (default) This is necessary with .NET languages or debuggers that aren't + * Visual Studio. + */ +#define SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING "SDL_WINDOWS_DISABLE_THREAD_NAMING" + +/** + * Controls whether menus can be opened with their keyboard shortcut + * (Alt+mnemonic). + * + * If the mnemonics are enabled, then menus can be opened by pressing the Alt + * key and the corresponding mnemonic (for example, Alt+F opens the File + * menu). However, in case an invalid mnemonic is pressed, Windows makes an + * audible beep to convey that nothing happened. This is true even if the + * window has no menu at all! + * + * Because most SDL applications don't have menus, and some want to use the + * Alt key for other purposes, SDL disables mnemonics (and the beeping) by + * default. + * + * Note: This also affects keyboard events: with mnemonics enabled, when a + * menu is opened from the keyboard, you will not receive a KEYUP event for + * the mnemonic key, and *might* not receive one for Alt. + * + * This variable can be set to the following values: + * + * - "0": Alt+mnemonic does nothing, no beeping. (default) + * - "1": Alt+mnemonic opens menus, invalid mnemonics produce a beep. + */ +#define SDL_HINT_WINDOWS_ENABLE_MENU_MNEMONICS "SDL_WINDOWS_ENABLE_MENU_MNEMONICS" + +/** + * A variable controlling whether the windows message loop is processed by SDL + * + * This variable can be set to the following values: + * + * - "0": The window message loop is not run + * - "1": The window message loop is processed in SDL_PumpEvents() + * + * By default SDL will process the windows message loop + */ +#define SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP "SDL_WINDOWS_ENABLE_MESSAGELOOP" + +/** + * Force SDL to use Critical Sections for mutexes on Windows. + * + * On Windows 7 and newer, Slim Reader/Writer Locks are available. They offer + * better performance, allocate no kernel resources and use less memory. SDL + * will fall back to Critical Sections on older OS versions or if forced to by + * this hint. + * + * This variable can be set to the following values: + * + * - "0": Use SRW Locks when available. If not, fall back to Critical + * Sections. (default) + * - "1": Force the use of Critical Sections in all cases. + */ +#define SDL_HINT_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS "SDL_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS" + +/** + * Force SDL to use Kernel Semaphores on Windows. + * + * Kernel Semaphores are inter-process and require a context switch on every + * interaction. On Windows 8 and newer, the WaitOnAddress API is available. + * Using that and atomics to implement semaphores increases performance. SDL + * will fall back to Kernel Objects on older OS versions or if forced to by + * this hint. + * + * This variable can be set to the following values: + * + * - "0": Use Atomics and WaitOnAddress API when available. If not, fall back + * to Kernel Objects. (default) + * - "1": Force the use of Kernel Objects in all cases. + */ +#define SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL "SDL_WINDOWS_FORCE_SEMAPHORE_KERNEL" + +/** + * A variable to specify custom icon resource id from RC file on Windows + * platform + */ +#define SDL_HINT_WINDOWS_INTRESOURCE_ICON "SDL_WINDOWS_INTRESOURCE_ICON" + +/** + * A variable to specify custom icon resource id from RC file on Windows + * platform + */ +#define SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL "SDL_WINDOWS_INTRESOURCE_ICON_SMALL" + +/** + * Tell SDL not to generate window-close events for Alt+F4 on Windows. + * + * The variable can be set to the following values: + * + * - "0": SDL will generate a window-close event when it sees Alt+F4. + * - "1": SDL will only do normal key handling for Alt+F4. + */ +#define SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 "SDL_WINDOWS_NO_CLOSE_ON_ALT_F4" + +/** + * Use the D3D9Ex API introduced in Windows Vista, instead of normal D3D9. + * + * Direct3D 9Ex contains changes to state management that can eliminate device + * loss errors during scenarios like Alt+Tab or UAC prompts. D3D9Ex may + * require some changes to your application to cope with the new behavior, so + * this is disabled by default. + * + * This hint must be set before initializing the video subsystem. + * + * For more information on Direct3D 9Ex, see: - + * https://docs.microsoft.com/en-us/windows/win32/direct3darticles/graphics-apis-in-windows-vista#direct3d-9ex + * - + * https://docs.microsoft.com/en-us/windows/win32/direct3darticles/direct3d-9ex-improvements + * + * This variable can be set to the following values: + * + * - "0": Use the original Direct3D 9 API (default) + * - "1": Use the Direct3D 9Ex API on Vista and later (and fall back if D3D9Ex + * is unavailable) + */ +#define SDL_HINT_WINDOWS_USE_D3D9EX "SDL_WINDOWS_USE_D3D9EX" + +/** + * Controls whether SDL will declare the process to be DPI aware. + * + * This hint must be set before initializing the video subsystem. + * + * The main purpose of declaring DPI awareness is to disable OS bitmap scaling + * of SDL windows on monitors with a DPI scale factor. + * + * This hint is equivalent to requesting DPI awareness via external means + * (e.g. calling SetProcessDpiAwarenessContext) and does not cause SDL to use + * a virtualized coordinate system, so it will generally give you 1 SDL + * coordinate = 1 pixel even on high-DPI displays. + * + * For more information, see: + * https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows + * + * This variable can be set to the following values: + * + * - "": Do not change the DPI awareness (default). + * - "unaware": Declare the process as DPI unaware. (Windows 8.1 and later). + * - "system": Request system DPI awareness. (Vista and later). + * - "permonitor": Request per-monitor DPI awareness. (Windows 8.1 and later). + * - "permonitorv2": Request per-monitor V2 DPI awareness. (Windows 10, + * version 1607 and later). The most visible difference from "permonitor" is + * that window title bar will be scaled to the visually correct size when + * dragging between monitors with different scale factors. This is the + * preferred DPI awareness level. + * + * If the requested DPI awareness is not available on the currently running + * OS, SDL will try to request the best available match. + */ +#define SDL_HINT_WINDOWS_DPI_AWARENESS "SDL_WINDOWS_DPI_AWARENESS" + +/** + * Uses DPI-scaled points as the SDL coordinate system on Windows. + * + * This changes the SDL coordinate system units to be DPI-scaled points, + * rather than pixels everywhere. This means windows will be appropriately + * sized, even when created on high-DPI displays with scaling. + * + * e.g. requesting a 640x480 window from SDL, on a display with 125% scaling + * in Windows display settings, will create a window with an 800x600 client + * area (in pixels). + * + * Setting this to "1" implicitly requests process DPI awareness (setting + * SDL_WINDOWS_DPI_AWARENESS is unnecessary), and forces + * SDL_WINDOW_ALLOW_HIGHDPI on all windows. + * + * This variable can be set to the following values: + * + * - "0": SDL coordinates equal Windows coordinates. No automatic window + * resizing when dragging between monitors with different scale factors + * (unless this is performed by Windows itself, which is the case when the + * process is DPI unaware). + * - "1": SDL coordinates are in DPI-scaled points. Automatically resize + * windows as needed on displays with non-100% scale factors. + */ +#define SDL_HINT_WINDOWS_DPI_SCALING "SDL_WINDOWS_DPI_SCALING" + +/** + * A variable controlling whether the window frame and title bar are + * interactive when the cursor is hidden + * + * This variable can be set to the following values: + * + * - "0": The window frame is not interactive when the cursor is hidden (no + * move, resize, etc) + * - "1": The window frame is interactive when the cursor is hidden + * + * By default SDL will allow interaction with the window frame when the cursor + * is hidden + */ +#define SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN" + +/** + * A variable controlling whether the window is activated when the + * SDL_ShowWindow function is called + * + * This variable can be set to the following values: + * + * - "0": The window is activated when the SDL_ShowWindow function is called + * - "1": The window is not activated when the SDL_ShowWindow function is + * called + * + * By default SDL will activate the window when the SDL_ShowWindow function is + * called + */ +#define SDL_HINT_WINDOW_NO_ACTIVATION_WHEN_SHOWN "SDL_WINDOW_NO_ACTIVATION_WHEN_SHOWN" + +/** Allows back-button-press events on Windows Phone to be marked as handled + * + * Windows Phone devices typically feature a Back button. When pressed, + * the OS will emit back-button-press events, which apps are expected to + * handle in an appropriate manner. If apps do not explicitly mark these + * events as 'Handled', then the OS will invoke its default behavior for + * unhandled back-button-press events, which on Windows Phone 8 and 8.1 is to + * terminate the app (and attempt to switch to the previous app, or to the + * device's home screen). + * + * Setting the SDL_HINT_WINRT_HANDLE_BACK_BUTTON hint to "1" will cause SDL + * to mark back-button-press events as Handled, if and when one is sent to + * the app. + * + * Internally, Windows Phone sends back button events as parameters to + * special back-button-press callback functions. Apps that need to respond + * to back-button-press events are expected to register one or more + * callback functions for such, shortly after being launched (during the + * app's initialization phase). After the back button is pressed, the OS + * will invoke these callbacks. If the app's callback(s) do not explicitly + * mark the event as handled by the time they return, or if the app never + * registers one of these callback, the OS will consider the event + * un-handled, and it will apply its default back button behavior (terminate + * the app). + * + * SDL registers its own back-button-press callback with the Windows Phone + * OS. This callback will emit a pair of SDL key-press events (SDL_KEYDOWN + * and SDL_KEYUP), each with a scancode of SDL_SCANCODE_AC_BACK, after which + * it will check the contents of the hint, SDL_HINT_WINRT_HANDLE_BACK_BUTTON. + * If the hint's value is set to "1", the back button event's Handled + * property will get set to 'true'. If the hint's value is set to something + * else, or if it is unset, SDL will leave the event's Handled property + * alone. (By default, the OS sets this property to 'false', to note.) + * + * SDL apps can either set SDL_HINT_WINRT_HANDLE_BACK_BUTTON well before a + * back button is pressed, or can set it in direct-response to a back button + * being pressed. + * + * In order to get notified when a back button is pressed, SDL apps should + * register a callback function with SDL_AddEventWatch(), and have it listen + * for SDL_KEYDOWN events that have a scancode of SDL_SCANCODE_AC_BACK. + * (Alternatively, SDL_KEYUP events can be listened-for. Listening for + * either event type is suitable.) Any value of SDL_HINT_WINRT_HANDLE_BACK_BUTTON + * set by such a callback, will be applied to the OS' current + * back-button-press event. + * + * More details on back button behavior in Windows Phone apps can be found + * at the following page, on Microsoft's developer site: + * + * http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj247550(v=vs.105).aspx + */ +#define SDL_HINT_WINRT_HANDLE_BACK_BUTTON "SDL_WINRT_HANDLE_BACK_BUTTON" + +/** Label text for a WinRT app's privacy policy link + * + * Network-enabled WinRT apps must include a privacy policy. On Windows 8, 8.1, and RT, + * Microsoft mandates that this policy be available via the Windows Settings charm. + * SDL provides code to add a link there, with its label text being set via the + * optional hint, SDL_HINT_WINRT_PRIVACY_POLICY_LABEL. + * + * Please note that a privacy policy's contents are not set via this hint. A separate + * hint, SDL_HINT_WINRT_PRIVACY_POLICY_URL, is used to link to the actual text of the + * policy. + * + * The contents of this hint should be encoded as a UTF8 string. + * + * The default value is "Privacy Policy". This hint should only be set during app + * initialization, preferably before any calls to SDL_Init(). + * + * For additional information on linking to a privacy policy, see the documentation for + * SDL_HINT_WINRT_PRIVACY_POLICY_URL. + */ +#define SDL_HINT_WINRT_PRIVACY_POLICY_LABEL "SDL_WINRT_PRIVACY_POLICY_LABEL" + +/** + * A URL to a WinRT app's privacy policy + * + * All network-enabled WinRT apps must make a privacy policy available to its + * users. On Windows 8, 8.1, and RT, Microsoft mandates that this policy be be + * available in the Windows Settings charm, as accessed from within the app. + * SDL provides code to add a URL-based link there, which can point to the + * app's privacy policy. + * + * To setup a URL to an app's privacy policy, set + * SDL_HINT_WINRT_PRIVACY_POLICY_URL before calling any SDL_Init() functions. + * The contents of the hint should be a valid URL. For example, + * "http://www.example.com". + * + * The default value is "", which will prevent SDL from adding a privacy + * policy link to the Settings charm. This hint should only be set during app + * init. + * + * The label text of an app's "Privacy Policy" link may be customized via + * another hint, SDL_HINT_WINRT_PRIVACY_POLICY_LABEL. + * + * Please note that on Windows Phone, Microsoft does not provide standard UI + * for displaying a privacy policy link, and as such, + * SDL_HINT_WINRT_PRIVACY_POLICY_URL will not get used on that platform. + * Network-enabled phone apps should display their privacy policy through some + * other, in-app means. + */ +#define SDL_HINT_WINRT_PRIVACY_POLICY_URL "SDL_WINRT_PRIVACY_POLICY_URL" + +/** + * Mark X11 windows as override-redirect. + * + * If set, this _might_ increase framerate at the expense of the desktop not + * working as expected. Override-redirect windows aren't noticed by the window + * manager at all. + * + * You should probably only use this for fullscreen windows, and you probably + * shouldn't even use it for that. But it's here if you want to try! + */ +#define SDL_HINT_X11_FORCE_OVERRIDE_REDIRECT "SDL_X11_FORCE_OVERRIDE_REDIRECT" + +/** + * A variable that lets you disable the detection and use of Xinput gamepad + * devices + * + * The variable can be set to the following values: + * + * - "0": Disable XInput detection (only uses direct input) + * - "1": Enable XInput detection (the default) + */ +#define SDL_HINT_XINPUT_ENABLED "SDL_XINPUT_ENABLED" + +/** + * A variable that lets you disable the detection and use of DirectInput + * gamepad devices + * + * The variable can be set to the following values: + * + * - "0": Disable DirectInput detection (only uses XInput) + * - "1": Enable DirectInput detection (the default) + */ +#define SDL_HINT_DIRECTINPUT_ENABLED "SDL_DIRECTINPUT_ENABLED" + +/** + * A variable that causes SDL to use the old axis and button mapping for + * XInput devices. + * + * This hint is for backwards compatibility only and will be removed in SDL + * 2.1 + * + * The default value is "0". This hint must be set before SDL_Init() + */ +#define SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING "SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING" + +/** + * A variable that causes SDL to not ignore audio "monitors" + * + * This is currently only used for PulseAudio and ignored elsewhere. + * + * By default, SDL ignores audio devices that aren't associated with physical + * hardware. Changing this hint to "1" will expose anything SDL sees that + * appears to be an audio source or sink. This will add "devices" to the list + * that the user probably doesn't want or need, but it can be useful in + * scenarios where you want to hook up SDL to some sort of virtual device, + * etc. + * + * The default value is "0". This hint must be set before SDL_Init(). + * + * This hint is available since SDL 2.0.16. Before then, virtual devices are + * always ignored. + */ +#define SDL_HINT_AUDIO_INCLUDE_MONITORS "SDL_AUDIO_INCLUDE_MONITORS" + +/** + * A variable that forces X11 windows to create as a custom type. + * + * This is currently only used for X11 and ignored elsewhere. + * + * During SDL_CreateWindow, SDL uses the _NET_WM_WINDOW_TYPE X11 property to + * report to the window manager the type of window it wants to create. This + * might be set to various things if SDL_WINDOW_TOOLTIP or + * SDL_WINDOW_POPUP_MENU, etc, were specified. For "normal" windows that + * haven't set a specific type, this hint can be used to specify a custom + * type. For example, a dock window might set this to + * "_NET_WM_WINDOW_TYPE_DOCK". + * + * If not set or set to "", this hint is ignored. This hint must be set before + * the SDL_CreateWindow() call that it is intended to affect. + * + * This hint is available since SDL 2.0.22. + */ +#define SDL_HINT_X11_WINDOW_TYPE "SDL_X11_WINDOW_TYPE" + +/** + * A variable that decides whether to send SDL_QUIT when closing the final + * window. + * + * By default, SDL sends an SDL_QUIT event when there is only one window and + * it receives an SDL_WINDOWEVENT_CLOSE event, under the assumption most apps + * would also take the loss of this window as a signal to terminate the + * program. + * + * However, it's not unreasonable in some cases to have the program continue + * to live on, perhaps to create new windows later. + * + * Changing this hint to "0" will cause SDL to not send an SDL_QUIT event when + * the final window is requesting to close. Note that in this case, there are + * still other legitimate reasons one might get an SDL_QUIT event: choosing + * "Quit" from the macOS menu bar, sending a SIGINT (ctrl-c) on Unix, etc. + * + * The default value is "1". This hint can be changed at any time. + * + * This hint is available since SDL 2.0.22. Before then, you always get an + * SDL_QUIT event when closing the final window. + */ +#define SDL_HINT_QUIT_ON_LAST_WINDOW_CLOSE "SDL_QUIT_ON_LAST_WINDOW_CLOSE" + + +/** + * A variable that decides what video backend to use. + * + * By default, SDL will try all available video backends in a reasonable order + * until it finds one that can work, but this hint allows the app or user to + * force a specific target, such as "x11" if, say, you are on Wayland but want + * to try talking to the X server instead. + * + * This functionality has existed since SDL 2.0.0 (indeed, before that) but + * before 2.0.22 this was an environment variable only. In 2.0.22, it was + * upgraded to a full SDL hint, so you can set the environment variable as + * usual or programatically set the hint with SDL_SetHint, which won't + * propagate to child processes. + * + * The default value is unset, in which case SDL will try to figure out the + * best video backend on your behalf. This hint needs to be set before + * SDL_Init() is called to be useful. + * + * This hint is available since SDL 2.0.22. Before then, you could set the + * environment variable to get the same effect. + */ +#define SDL_HINT_VIDEODRIVER "SDL_VIDEODRIVER" + +/** + * A variable that decides what audio backend to use. + * + * By default, SDL will try all available audio backends in a reasonable order + * until it finds one that can work, but this hint allows the app or user to + * force a specific target, such as "alsa" if, say, you are on PulseAudio but + * want to try talking to the lower level instead. + * + * This functionality has existed since SDL 2.0.0 (indeed, before that) but + * before 2.0.22 this was an environment variable only. In 2.0.22, it was + * upgraded to a full SDL hint, so you can set the environment variable as + * usual or programatically set the hint with SDL_SetHint, which won't + * propagate to child processes. + * + * The default value is unset, in which case SDL will try to figure out the + * best audio backend on your behalf. This hint needs to be set before + * SDL_Init() is called to be useful. + * + * This hint is available since SDL 2.0.22. Before then, you could set the + * environment variable to get the same effect. + */ +#define SDL_HINT_AUDIODRIVER "SDL_AUDIODRIVER" + +/** + * A variable that decides what KMSDRM device to use. + * + * Internally, SDL might open something like "/dev/dri/cardNN" to access + * KMSDRM functionality, where "NN" is a device index number. + * + * SDL makes a guess at the best index to use (usually zero), but the app or + * user can set this hint to a number between 0 and 99 to force selection. + * + * This hint is available since SDL 2.24.0. + */ +#define SDL_HINT_KMSDRM_DEVICE_INDEX "SDL_KMSDRM_DEVICE_INDEX" + + +/** + * A variable that treats trackpads as touch devices. + * + * On macOS (and possibly other platforms in the future), SDL will report + * touches on a trackpad as mouse input, which is generally what users expect + * from this device; however, these are often actually full multitouch-capable + * touch devices, so it might be preferable to some apps to treat them as + * such. + * + * Setting this hint to true will make the trackpad input report as a + * multitouch device instead of a mouse. The default is false. + * + * Note that most platforms don't support this hint. As of 2.24.0, it only + * supports MacBooks' trackpads on macOS. Others may follow later. + * + * This hint is checked during SDL_Init and can not be changed after. + * + * This hint is available since SDL 2.24.0. + */ +#define SDL_HINT_TRACKPAD_IS_TOUCH_ONLY "SDL_TRACKPAD_IS_TOUCH_ONLY" + +/** + * Cause SDL to call dbus_shutdown() on quit. + * + * This is useful as a debug tool to validate memory leaks, but shouldn't ever + * be set in production applications, as other libraries used by the + * application might use dbus under the hood and this cause cause crashes if + * they continue after SDL_Quit(). + * + * This variable can be set to the following values: + * + * - "0": SDL will not call dbus_shutdown() on quit (default) + * - "1": SDL will call dbus_shutdown() on quit + * + * This hint is available since SDL 2.30.0. + */ +#define SDL_HINT_SHUTDOWN_DBUS_ON_QUIT "SDL_SHUTDOWN_DBUS_ON_QUIT" + +/** + * Specify if SDL_RWFromFile should use the resource dir on Apple platforms. + * + * SDL2 has always done this on Apple platforms, but it can be surprising to + * try opening a path to discover that SDL adjusts the path to elsewhere, so + * this hint allows that behavior to be disabled. + * + * If running from a App Bundle, this will be MyApp.app/Contents/Resources. If + * running as a normal Unix-like process, this will be the directory where the + * running binary lives. Setting this hint to 0 avoids this and just uses the + * requested path as-is. + * + * This variable can be set to the following values: + * + * - "0": SDL will not use the app resource directory. + * - "1": SDL will use the app's resource directory (default). + * + * This hint is available since SDL 2.32.0. + */ +#define SDL_HINT_APPLE_RWFROMFILE_USE_RESOURCES "SDL_APPLE_RWFROMFILE_USE_RESOURCES" + + +/** + * An enumeration of hint priorities + */ +typedef enum SDL_HintPriority +{ + SDL_HINT_DEFAULT, + SDL_HINT_NORMAL, + SDL_HINT_OVERRIDE +} SDL_HintPriority; + + +/** + * Set a hint with a specific priority. + * + * The priority controls the behavior when setting a hint that already has a + * value. Hints will replace existing hints of their priority and lower. + * Environment variables are considered to have override priority. + * + * \param name the hint to set. + * \param value the value of the hint variable. + * \param priority the SDL_HintPriority level for the hint. + * \returns SDL_TRUE if the hint was set, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetHint + * \sa SDL_SetHint + */ +extern DECLSPEC SDL_bool SDLCALL SDL_SetHintWithPriority(const char *name, + const char *value, + SDL_HintPriority priority); + +/** + * Set a hint with normal priority. + * + * Hints will not be set if there is an existing override hint or environment + * variable that takes precedence. You can use SDL_SetHintWithPriority() to + * set the hint with override priority instead. + * + * \param name the hint to set. + * \param value the value of the hint variable. + * \returns SDL_TRUE if the hint was set, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetHint + * \sa SDL_SetHintWithPriority + */ +extern DECLSPEC SDL_bool SDLCALL SDL_SetHint(const char *name, + const char *value); + +/** + * Reset a hint to the default value. + * + * This will reset a hint to the value of the environment variable, or NULL if + * the environment isn't set. Callbacks will be called normally with this + * change. + * + * \param name the hint to set. + * \returns SDL_TRUE if the hint was set, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GetHint + * \sa SDL_SetHint + */ +extern DECLSPEC SDL_bool SDLCALL SDL_ResetHint(const char *name); + +/** + * Reset all hints to the default values. + * + * This will reset all hints to the value of the associated environment + * variable, or NULL if the environment isn't set. Callbacks will be called + * normally with this change. + * + * \since This function is available since SDL 2.26.0. + * + * \sa SDL_GetHint + * \sa SDL_SetHint + * \sa SDL_ResetHint + */ +extern DECLSPEC void SDLCALL SDL_ResetHints(void); + +/** + * Get the value of a hint. + * + * \param name the hint to query. + * \returns the string value of a hint or NULL if the hint isn't set. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetHint + * \sa SDL_SetHintWithPriority + */ +extern DECLSPEC const char * SDLCALL SDL_GetHint(const char *name); + +/** + * Get the boolean value of a hint variable. + * + * \param name the name of the hint to get the boolean value from. + * \param default_value the value to return if the hint does not exist. + * \returns the boolean value of a hint or the provided default value if the + * hint does not exist. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_GetHint + * \sa SDL_SetHint + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GetHintBoolean(const char *name, SDL_bool default_value); + +/** + * Type definition of the hint callback function. + * + * \param userdata what was passed as `userdata` to SDL_AddHintCallback(). + * \param name what was passed as `name` to SDL_AddHintCallback(). + * \param oldValue the previous hint value. + * \param newValue the new value hint is to be set to. + */ +typedef void (SDLCALL *SDL_HintCallback)(void *userdata, const char *name, const char *oldValue, const char *newValue); + +/** + * Add a function to watch a particular hint. + * + * \param name the hint to watch. + * \param callback An SDL_HintCallback function that will be called when the + * hint value changes. + * \param userdata a pointer to pass to the callback function. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_DelHintCallback + */ +extern DECLSPEC void SDLCALL SDL_AddHintCallback(const char *name, + SDL_HintCallback callback, + void *userdata); + +/** + * Remove a function watching a particular hint. + * + * \param name the hint being watched. + * \param callback An SDL_HintCallback function that will be called when the + * hint value changes. + * \param userdata a pointer being passed to the callback function. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AddHintCallback + */ +extern DECLSPEC void SDLCALL SDL_DelHintCallback(const char *name, + SDL_HintCallback callback, + void *userdata); + +/** + * Clear all hints. + * + * This function is automatically called during SDL_Quit(), and deletes all + * callbacks without calling them and frees all memory associated with hints. + * If you're calling this from application code you probably want to call + * SDL_ResetHints() instead. + * + * This function will be removed from the API the next time we rev the ABI. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ResetHints + */ +extern DECLSPEC void SDLCALL SDL_ClearHints(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_hints_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_joystick.h b/third_party/SDL2/include/SDL_joystick.h new file mode 100644 index 00000000000..668db5e30f6 --- /dev/null +++ b/third_party/SDL2/include/SDL_joystick.h @@ -0,0 +1,1088 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryJoystick + * + * Include file for SDL joystick event handling + * + * The term "device_index" identifies currently plugged in joystick devices + * between 0 and SDL_NumJoysticks(), with the exact joystick behind a + * device_index changing as joysticks are plugged and unplugged. + * + * The term "instance_id" is the current instantiation of a joystick device in + * the system, if the joystick is removed and then re-inserted then it will + * get a new instance_id, instance_id's are monotonically increasing + * identifiers of a joystick plugged in. + * + * The term "player_index" is the number assigned to a player on a specific + * controller. For XInput controllers this returns the XInput user index. Many + * joysticks will not be able to supply this information. + * + * The term JoystickGUID is a stable 128-bit identifier for a joystick device + * that does not change over time, it identifies class of the device (a X360 + * wired controller for example). This identifier is platform dependent. + */ + +#ifndef SDL_joystick_h_ +#define SDL_joystick_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_guid.h" +#include "SDL_mutex.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \file SDL_joystick.h + * + * In order to use these functions, SDL_Init() must have been called + * with the SDL_INIT_JOYSTICK flag. This causes SDL to scan the system + * for joysticks, and load appropriate drivers. + * + * If you would like to receive joystick updates while the application + * is in the background, you should set the following hint before calling + * SDL_Init(): SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS + */ + +/** + * The joystick structure used to identify an SDL joystick + */ +#ifdef SDL_THREAD_SAFETY_ANALYSIS +extern SDL_mutex *SDL_joystick_lock; +#endif +struct _SDL_Joystick; +typedef struct _SDL_Joystick SDL_Joystick; + +/** + * A structure that encodes the stable unique id for a joystick device. + * + * This is just a standard SDL_GUID by a different name. + */ +typedef SDL_GUID SDL_JoystickGUID; + +/** + * This is a unique ID for a joystick for the time it is connected to the + * system, and is never reused for the lifetime of the application. + * + * If the joystick is disconnected and reconnected, it will get a new ID. + * + * The ID value starts at 0 and increments from there. The value -1 is an + * invalid ID. + */ +typedef Sint32 SDL_JoystickID; + +typedef enum +{ + SDL_JOYSTICK_TYPE_UNKNOWN, + SDL_JOYSTICK_TYPE_GAMECONTROLLER, + SDL_JOYSTICK_TYPE_WHEEL, + SDL_JOYSTICK_TYPE_ARCADE_STICK, + SDL_JOYSTICK_TYPE_FLIGHT_STICK, + SDL_JOYSTICK_TYPE_DANCE_PAD, + SDL_JOYSTICK_TYPE_GUITAR, + SDL_JOYSTICK_TYPE_DRUM_KIT, + SDL_JOYSTICK_TYPE_ARCADE_PAD, + SDL_JOYSTICK_TYPE_THROTTLE +} SDL_JoystickType; + +typedef enum +{ + SDL_JOYSTICK_POWER_UNKNOWN = -1, + SDL_JOYSTICK_POWER_EMPTY, /* <= 5% */ + SDL_JOYSTICK_POWER_LOW, /* <= 20% */ + SDL_JOYSTICK_POWER_MEDIUM, /* <= 70% */ + SDL_JOYSTICK_POWER_FULL, /* <= 100% */ + SDL_JOYSTICK_POWER_WIRED, + SDL_JOYSTICK_POWER_MAX +} SDL_JoystickPowerLevel; + +/* Set max recognized G-force from accelerometer + See src/joystick/uikit/SDL_sysjoystick.m for notes on why this is needed + */ +#define SDL_IPHONE_MAX_GFORCE 5.0 + + +/* Function prototypes */ + +/** + * Locking for multi-threaded access to the joystick API + * + * If you are using the joystick API or handling events from multiple threads + * you should use these locking functions to protect access to the joysticks. + * + * In particular, you are guaranteed that the joystick list won't change, so + * the API functions that take a joystick index will be valid, and joystick + * and game controller events will not be delivered. + * + * As of SDL 2.26.0, you can take the joystick lock around reinitializing the + * joystick subsystem, to prevent other threads from seeing joysticks in an + * uninitialized state. However, all open joysticks will be closed and SDL + * functions called with them will fail. + * + * \since This function is available since SDL 2.0.7. + */ +extern DECLSPEC void SDLCALL SDL_LockJoysticks(void) SDL_ACQUIRE(SDL_joystick_lock); + + +/** + * Unlocking for multi-threaded access to the joystick API + * + * If you are using the joystick API or handling events from multiple threads + * you should use these locking functions to protect access to the joysticks. + * + * In particular, you are guaranteed that the joystick list won't change, so + * the API functions that take a joystick index will be valid, and joystick + * and game controller events will not be delivered. + * + * \since This function is available since SDL 2.0.7. + */ +extern DECLSPEC void SDLCALL SDL_UnlockJoysticks(void) SDL_RELEASE(SDL_joystick_lock); + +/** + * Count the number of joysticks attached to the system. + * + * \returns the number of attached joysticks on success or a negative error + * code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickName + * \sa SDL_JoystickPath + * \sa SDL_JoystickOpen + */ +extern DECLSPEC int SDLCALL SDL_NumJoysticks(void); + +/** + * Get the implementation dependent name of a joystick. + * + * This can be called before any joysticks are opened. + * + * \param device_index the index of the joystick to query (the N'th joystick + * on the system). + * \returns the name of the selected joystick. If no name can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickName + * \sa SDL_JoystickOpen + */ +extern DECLSPEC const char *SDLCALL SDL_JoystickNameForIndex(int device_index); + +/** + * Get the implementation dependent path of a joystick. + * + * This can be called before any joysticks are opened. + * + * \param device_index the index of the joystick to query (the N'th joystick + * on the system). + * \returns the path of the selected joystick. If no path can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_JoystickPath + * \sa SDL_JoystickOpen + */ +extern DECLSPEC const char *SDLCALL SDL_JoystickPathForIndex(int device_index); + +/** + * Get the player index of a joystick, or -1 if it's not available This can be + * called before any joysticks are opened. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC int SDLCALL SDL_JoystickGetDevicePlayerIndex(int device_index); + +/** + * Get the implementation-dependent GUID for the joystick at a given device + * index. + * + * This function can be called before any joysticks are opened. + * + * \param device_index the index of the joystick to query (the N'th joystick + * on the system. + * \returns the GUID of the selected joystick. If called on an invalid index, + * this function returns a zero GUID. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetGUID + * \sa SDL_JoystickGetGUIDString + */ +extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetDeviceGUID(int device_index); + +/** + * Get the USB vendor ID of a joystick, if available. + * + * This can be called before any joysticks are opened. If the vendor ID isn't + * available this function returns 0. + * + * \param device_index the index of the joystick to query (the N'th joystick + * on the system. + * \returns the USB vendor ID of the selected joystick. If called on an + * invalid index, this function returns zero. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceVendor(int device_index); + +/** + * Get the USB product ID of a joystick, if available. + * + * This can be called before any joysticks are opened. If the product ID isn't + * available this function returns 0. + * + * \param device_index the index of the joystick to query (the N'th joystick + * on the system. + * \returns the USB product ID of the selected joystick. If called on an + * invalid index, this function returns zero. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceProduct(int device_index); + +/** + * Get the product version of a joystick, if available. + * + * This can be called before any joysticks are opened. If the product version + * isn't available this function returns 0. + * + * \param device_index the index of the joystick to query (the N'th joystick + * on the system. + * \returns the product version of the selected joystick. If called on an + * invalid index, this function returns zero. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetDeviceProductVersion(int device_index); + +/** + * Get the type of a joystick, if available. + * + * This can be called before any joysticks are opened. + * + * \param device_index the index of the joystick to query (the N'th joystick + * on the system. + * \returns the SDL_JoystickType of the selected joystick. If called on an + * invalid index, this function returns `SDL_JOYSTICK_TYPE_UNKNOWN`. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC SDL_JoystickType SDLCALL SDL_JoystickGetDeviceType(int device_index); + +/** + * Get the instance ID of a joystick. + * + * This can be called before any joysticks are opened. + * + * \param device_index the index of the joystick to query (the N'th joystick + * on the system. + * \returns the instance id of the selected joystick. If called on an invalid + * index, this function returns -1. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC SDL_JoystickID SDLCALL SDL_JoystickGetDeviceInstanceID(int device_index); + +/** + * Open a joystick for use. + * + * The `device_index` argument refers to the N'th joystick presently + * recognized by SDL on the system. It is **NOT** the same as the instance ID + * used to identify the joystick in future events. See + * SDL_JoystickInstanceID() for more details about instance IDs. + * + * The joystick subsystem must be initialized before a joystick can be opened + * for use. + * + * \param device_index the index of the joystick to query. + * \returns a joystick identifier or NULL if an error occurred; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickClose + * \sa SDL_JoystickInstanceID + */ +extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickOpen(int device_index); + +/** + * Get the SDL_Joystick associated with an instance id. + * + * \param instance_id the instance id to get the SDL_Joystick for. + * \returns an SDL_Joystick on success or NULL on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.4. + */ +extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickFromInstanceID(SDL_JoystickID instance_id); + +/** + * Get the SDL_Joystick associated with a player index. + * + * \param player_index the player index to get the SDL_Joystick for. + * \returns an SDL_Joystick on success or NULL on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.12. + */ +extern DECLSPEC SDL_Joystick *SDLCALL SDL_JoystickFromPlayerIndex(int player_index); + +/** + * Attach a new virtual joystick. + * + * \returns the joystick's device index, or -1 if an error occurred. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_JoystickAttachVirtual(SDL_JoystickType type, + int naxes, + int nbuttons, + int nhats); + +/** + * The structure that defines an extended virtual joystick description + * + * The caller must zero the structure and then initialize the version with + * `SDL_VIRTUAL_JOYSTICK_DESC_VERSION` before passing it to + * SDL_JoystickAttachVirtualEx() All other elements of this structure are + * optional and can be left 0. + * + * \sa SDL_JoystickAttachVirtualEx + */ +typedef struct SDL_VirtualJoystickDesc +{ + Uint16 version; /**< `SDL_VIRTUAL_JOYSTICK_DESC_VERSION` */ + Uint16 type; /**< `SDL_JoystickType` */ + Uint16 naxes; /**< the number of axes on this joystick */ + Uint16 nbuttons; /**< the number of buttons on this joystick */ + Uint16 nhats; /**< the number of hats on this joystick */ + Uint16 vendor_id; /**< the USB vendor ID of this joystick */ + Uint16 product_id; /**< the USB product ID of this joystick */ + Uint16 padding; /**< unused */ + Uint32 button_mask; /**< A mask of which buttons are valid for this controller + e.g. (1 << SDL_CONTROLLER_BUTTON_A) */ + Uint32 axis_mask; /**< A mask of which axes are valid for this controller + e.g. (1 << SDL_CONTROLLER_AXIS_LEFTX) */ + const char *name; /**< the name of the joystick */ + + void *userdata; /**< User data pointer passed to callbacks */ + void (SDLCALL *Update)(void *userdata); /**< Called when the joystick state should be updated */ + void (SDLCALL *SetPlayerIndex)(void *userdata, int player_index); /**< Called when the player index is set */ + int (SDLCALL *Rumble)(void *userdata, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble); /**< Implements SDL_JoystickRumble() */ + int (SDLCALL *RumbleTriggers)(void *userdata, Uint16 left_rumble, Uint16 right_rumble); /**< Implements SDL_JoystickRumbleTriggers() */ + int (SDLCALL *SetLED)(void *userdata, Uint8 red, Uint8 green, Uint8 blue); /**< Implements SDL_JoystickSetLED() */ + int (SDLCALL *SendEffect)(void *userdata, const void *data, int size); /**< Implements SDL_JoystickSendEffect() */ + +} SDL_VirtualJoystickDesc; + +/** + * The current version of the SDL_VirtualJoystickDesc structure + */ +#define SDL_VIRTUAL_JOYSTICK_DESC_VERSION 1 + +/** + * Attach a new virtual joystick with extended properties. + * + * \returns the joystick's device index, or -1 if an error occurred. + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC int SDLCALL SDL_JoystickAttachVirtualEx(const SDL_VirtualJoystickDesc *desc); + +/** + * Detach a virtual joystick. + * + * \param device_index a value previously returned from + * SDL_JoystickAttachVirtual(). + * \returns 0 on success, or -1 if an error occurred. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_JoystickDetachVirtual(int device_index); + +/** + * Query whether or not the joystick at a given device index is virtual. + * + * \param device_index a joystick device index. + * \returns SDL_TRUE if the joystick is virtual, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_JoystickIsVirtual(int device_index); + +/** + * Set values on an opened, virtual-joystick's axis. + * + * Please note that values set here will not be applied until the next call to + * SDL_JoystickUpdate, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * Note that when sending trigger axes, you should scale the value to the full + * range of Sint16. For example, a trigger at rest would have the value of + * `SDL_JOYSTICK_AXIS_MIN`. + * + * \param joystick the virtual joystick on which to set state. + * \param axis the specific axis on the virtual joystick to set. + * \param value the new value for the specified axis. + * \returns 0 on success, -1 on error. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualAxis(SDL_Joystick *joystick, int axis, Sint16 value); + +/** + * Set values on an opened, virtual-joystick's button. + * + * Please note that values set here will not be applied until the next call to + * SDL_JoystickUpdate, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * \param joystick the virtual joystick on which to set state. + * \param button the specific button on the virtual joystick to set. + * \param value the new value for the specified button. + * \returns 0 on success, -1 on error. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualButton(SDL_Joystick *joystick, int button, Uint8 value); + +/** + * Set values on an opened, virtual-joystick's hat. + * + * Please note that values set here will not be applied until the next call to + * SDL_JoystickUpdate, which can either be called directly, or can be called + * indirectly through various other SDL APIs, including, but not limited to + * the following: SDL_PollEvent, SDL_PumpEvents, SDL_WaitEventTimeout, + * SDL_WaitEvent. + * + * \param joystick the virtual joystick on which to set state. + * \param hat the specific hat on the virtual joystick to set. + * \param value the new value for the specified hat. + * \returns 0 on success, -1 on error. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_JoystickSetVirtualHat(SDL_Joystick *joystick, int hat, Uint8 value); + +/** + * Get the implementation dependent name of a joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the name of the selected joystick. If no name can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickNameForIndex + * \sa SDL_JoystickOpen + */ +extern DECLSPEC const char *SDLCALL SDL_JoystickName(SDL_Joystick *joystick); + +/** + * Get the implementation dependent path of a joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the path of the selected joystick. If no path can be found, this + * function returns NULL; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_JoystickPathForIndex + */ +extern DECLSPEC const char *SDLCALL SDL_JoystickPath(SDL_Joystick *joystick); + +/** + * Get the player index of an opened joystick. + * + * For XInput controllers this returns the XInput user index. Many joysticks + * will not be able to supply this information. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the player index, or -1 if it's not available. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC int SDLCALL SDL_JoystickGetPlayerIndex(SDL_Joystick *joystick); + +/** + * Set the player index of an opened joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \param player_index Player index to assign to this joystick, or -1 to clear + * the player index and turn off player LEDs. + * + * \since This function is available since SDL 2.0.12. + */ +extern DECLSPEC void SDLCALL SDL_JoystickSetPlayerIndex(SDL_Joystick *joystick, int player_index); + +/** + * Get the implementation-dependent GUID for the joystick. + * + * This function requires an open joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the GUID of the given joystick. If called on an invalid index, + * this function returns a zero GUID; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetDeviceGUID + * \sa SDL_JoystickGetGUIDString + */ +extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUID(SDL_Joystick *joystick); + +/** + * Get the USB vendor ID of an opened joystick, if available. + * + * If the vendor ID isn't available this function returns 0. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the USB vendor ID of the selected joystick, or 0 if unavailable. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetVendor(SDL_Joystick *joystick); + +/** + * Get the USB product ID of an opened joystick, if available. + * + * If the product ID isn't available this function returns 0. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the USB product ID of the selected joystick, or 0 if unavailable. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetProduct(SDL_Joystick *joystick); + +/** + * Get the product version of an opened joystick, if available. + * + * If the product version isn't available this function returns 0. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the product version of the selected joystick, or 0 if unavailable. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetProductVersion(SDL_Joystick *joystick); + +/** + * Get the firmware version of an opened joystick, if available. + * + * If the firmware version isn't available this function returns 0. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the firmware version of the selected joystick, or 0 if + * unavailable. + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC Uint16 SDLCALL SDL_JoystickGetFirmwareVersion(SDL_Joystick *joystick); + +/** + * Get the serial number of an opened joystick, if available. + * + * Returns the serial number of the joystick, or NULL if it is not available. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the serial number of the selected joystick, or NULL if + * unavailable. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC const char * SDLCALL SDL_JoystickGetSerial(SDL_Joystick *joystick); + +/** + * Get the type of an opened joystick. + * + * \param joystick the SDL_Joystick obtained from SDL_JoystickOpen(). + * \returns the SDL_JoystickType of the selected joystick. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC SDL_JoystickType SDLCALL SDL_JoystickGetType(SDL_Joystick *joystick); + +/** + * Get an ASCII string representation for a given SDL_JoystickGUID. + * + * You should supply at least 33 bytes for pszGUID. + * + * \param guid the SDL_JoystickGUID you wish to convert to string. + * \param pszGUID buffer in which to write the ASCII string. + * \param cbGUID the size of pszGUID. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetDeviceGUID + * \sa SDL_JoystickGetGUID + * \sa SDL_JoystickGetGUIDFromString + */ +extern DECLSPEC void SDLCALL SDL_JoystickGetGUIDString(SDL_JoystickGUID guid, char *pszGUID, int cbGUID); + +/** + * Convert a GUID string into a SDL_JoystickGUID structure. + * + * Performs no error checking. If this function is given a string containing + * an invalid GUID, the function will silently succeed, but the GUID generated + * will not be useful. + * + * \param pchGUID string containing an ASCII representation of a GUID. + * \returns a SDL_JoystickGUID structure. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetGUIDString + */ +extern DECLSPEC SDL_JoystickGUID SDLCALL SDL_JoystickGetGUIDFromString(const char *pchGUID); + +/** + * Get the device information encoded in a SDL_JoystickGUID structure + * + * \param guid the SDL_JoystickGUID you wish to get info about. + * \param vendor A pointer filled in with the device VID, or 0 if not + * available. + * \param product A pointer filled in with the device PID, or 0 if not + * available. + * \param version A pointer filled in with the device version, or 0 if not + * available. + * \param crc16 A pointer filled in with a CRC used to distinguish different + * products with the same VID/PID, or 0 if not available. + * + * \since This function is available since SDL 2.26.0. + * + * \sa SDL_JoystickGetDeviceGUID + */ +extern DECLSPEC void SDLCALL SDL_GetJoystickGUIDInfo(SDL_JoystickGUID guid, Uint16 *vendor, Uint16 *product, Uint16 *version, Uint16 *crc16); + +/** + * Get the status of a specified joystick. + * + * \param joystick the joystick to query. + * \returns SDL_TRUE if the joystick has been opened, SDL_FALSE if it has not; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickClose + * \sa SDL_JoystickOpen + */ +extern DECLSPEC SDL_bool SDLCALL SDL_JoystickGetAttached(SDL_Joystick *joystick); + +/** + * Get the instance ID of an opened joystick. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the instance ID of the specified joystick on success or a negative + * error code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickOpen + */ +extern DECLSPEC SDL_JoystickID SDLCALL SDL_JoystickInstanceID(SDL_Joystick *joystick); + +/** + * Get the number of general axis controls on a joystick. + * + * Often, the directional pad on a game controller will either look like 4 + * separate buttons or a POV hat, and not axes, but all of this is up to the + * device and platform. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the number of axis controls/number of axes on success or a + * negative error code on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetAxis + * \sa SDL_JoystickOpen + */ +extern DECLSPEC int SDLCALL SDL_JoystickNumAxes(SDL_Joystick *joystick); + +/** + * Get the number of trackballs on a joystick. + * + * Joystick trackballs have only relative motion events associated with them + * and their state cannot be polled. + * + * Most joysticks do not have trackballs. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the number of trackballs on success or a negative error code on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetBall + */ +extern DECLSPEC int SDLCALL SDL_JoystickNumBalls(SDL_Joystick *joystick); + +/** + * Get the number of POV hats on a joystick. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the number of POV hats on success or a negative error code on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetHat + * \sa SDL_JoystickOpen + */ +extern DECLSPEC int SDLCALL SDL_JoystickNumHats(SDL_Joystick *joystick); + +/** + * Get the number of buttons on a joystick. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \returns the number of buttons on success or a negative error code on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickGetButton + * \sa SDL_JoystickOpen + */ +extern DECLSPEC int SDLCALL SDL_JoystickNumButtons(SDL_Joystick *joystick); + +/** + * Update the current state of the open joysticks. + * + * This is called automatically by the event loop if any joystick events are + * enabled. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickEventState + */ +extern DECLSPEC void SDLCALL SDL_JoystickUpdate(void); + +/** + * Enable/disable joystick event polling. + * + * If joystick events are disabled, you must call SDL_JoystickUpdate() + * yourself and manually check the state of the joystick when you want + * joystick information. + * + * It is recommended that you leave joystick event handling enabled. + * + * **WARNING**: Calling this function may delete all events currently in SDL's + * event queue. + * + * While `param` is meant to be one of `SDL_QUERY`, `SDL_IGNORE`, or + * `SDL_ENABLE`, this function accepts any value, with any non-zero value that + * isn't `SDL_QUERY` being treated as `SDL_ENABLE`. + * + * If SDL was built with events disabled (extremely uncommon!), this will do + * nothing and always return `SDL_IGNORE`. + * + * \param state can be one of `SDL_QUERY`, `SDL_IGNORE`, or `SDL_ENABLE`. + * \returns If `state` is `SDL_QUERY` then the current state is returned, + * otherwise `state` is returned (even if it was not one of the + * allowed values). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GameControllerEventState + */ +extern DECLSPEC int SDLCALL SDL_JoystickEventState(int state); + +/* Limits for joystick axes... */ +#define SDL_JOYSTICK_AXIS_MAX 32767 +#define SDL_JOYSTICK_AXIS_MIN -32768 + +/** + * Get the current state of an axis control on a joystick. + * + * SDL makes no promises about what part of the joystick any given axis refers + * to. Your game should have some sort of configuration UI to let users + * specify what each axis should be bound to. Alternately, SDL's higher-level + * Game Controller API makes a great effort to apply order to this lower-level + * interface, so you know that a specific axis is the "left thumb stick," etc. + * + * The value returned by SDL_JoystickGetAxis() is a signed integer (-32768 to + * 32767) representing the current position of the axis. It may be necessary + * to impose certain tolerances on these values to account for jitter. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \param axis the axis to query; the axis indices start at index 0. + * \returns a 16-bit signed integer representing the current position of the + * axis or 0 on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickNumAxes + */ +extern DECLSPEC Sint16 SDLCALL SDL_JoystickGetAxis(SDL_Joystick *joystick, + int axis); + +/** + * Get the initial state of an axis control on a joystick. + * + * The state is a value ranging from -32768 to 32767. + * + * The axis indices start at index 0. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \param axis the axis to query; the axis indices start at index 0. + * \param state Upon return, the initial value is supplied here. + * \return SDL_TRUE if this axis has any initial value, or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_JoystickGetAxisInitialState(SDL_Joystick *joystick, + int axis, Sint16 *state); + +/** + * \name Hat positions + */ +/* @{ */ +#define SDL_HAT_CENTERED 0x00 +#define SDL_HAT_UP 0x01 +#define SDL_HAT_RIGHT 0x02 +#define SDL_HAT_DOWN 0x04 +#define SDL_HAT_LEFT 0x08 +#define SDL_HAT_RIGHTUP (SDL_HAT_RIGHT|SDL_HAT_UP) +#define SDL_HAT_RIGHTDOWN (SDL_HAT_RIGHT|SDL_HAT_DOWN) +#define SDL_HAT_LEFTUP (SDL_HAT_LEFT|SDL_HAT_UP) +#define SDL_HAT_LEFTDOWN (SDL_HAT_LEFT|SDL_HAT_DOWN) +/* @} */ + +/** + * Get the current state of a POV hat on a joystick. + * + * The returned value will be one of the following positions: + * + * - `SDL_HAT_CENTERED` + * - `SDL_HAT_UP` + * - `SDL_HAT_RIGHT` + * - `SDL_HAT_DOWN` + * - `SDL_HAT_LEFT` + * - `SDL_HAT_RIGHTUP` + * - `SDL_HAT_RIGHTDOWN` + * - `SDL_HAT_LEFTUP` + * - `SDL_HAT_LEFTDOWN` + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \param hat the hat index to get the state from; indices start at index 0. + * \returns the current hat position. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickNumHats + */ +extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetHat(SDL_Joystick *joystick, + int hat); + +/** + * Get the ball axis change since the last poll. + * + * Trackballs can only return relative motion since the last call to + * SDL_JoystickGetBall(), these motion deltas are placed into `dx` and `dy`. + * + * Most joysticks do not have trackballs. + * + * \param joystick the SDL_Joystick to query. + * \param ball the ball index to query; ball indices start at index 0. + * \param dx stores the difference in the x axis position since the last poll. + * \param dy stores the difference in the y axis position since the last poll. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickNumBalls + */ +extern DECLSPEC int SDLCALL SDL_JoystickGetBall(SDL_Joystick *joystick, + int ball, int *dx, int *dy); + +/** + * Get the current state of a button on a joystick. + * + * \param joystick an SDL_Joystick structure containing joystick information. + * \param button the button index to get the state from; indices start at + * index 0. + * \returns 1 if the specified button is pressed, 0 otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickNumButtons + */ +extern DECLSPEC Uint8 SDLCALL SDL_JoystickGetButton(SDL_Joystick *joystick, + int button); + +/** + * Start a rumble effect. + * + * Each call to this function cancels any previous rumble effect, and calling + * it with 0 intensity stops any rumbling. + * + * \param joystick The joystick to vibrate. + * \param low_frequency_rumble The intensity of the low frequency (left) + * rumble motor, from 0 to 0xFFFF. + * \param high_frequency_rumble The intensity of the high frequency (right) + * rumble motor, from 0 to 0xFFFF. + * \param duration_ms The duration of the rumble effect, in milliseconds. + * \returns 0, or -1 if rumble isn't supported on this joystick. + * + * \since This function is available since SDL 2.0.9. + * + * \sa SDL_JoystickHasRumble + */ +extern DECLSPEC int SDLCALL SDL_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble, Uint32 duration_ms); + +/** + * Start a rumble effect in the joystick's triggers + * + * Each call to this function cancels any previous trigger rumble effect, and + * calling it with 0 intensity stops any rumbling. + * + * Note that this is rumbling of the _triggers_ and not the game controller as + * a whole. This is currently only supported on Xbox One controllers. If you + * want the (more common) whole-controller rumble, use SDL_JoystickRumble() + * instead. + * + * \param joystick The joystick to vibrate. + * \param left_rumble The intensity of the left trigger rumble motor, from 0 + * to 0xFFFF. + * \param right_rumble The intensity of the right trigger rumble motor, from 0 + * to 0xFFFF. + * \param duration_ms The duration of the rumble effect, in milliseconds. + * \returns 0, or -1 if trigger rumble isn't supported on this joystick. + * + * \since This function is available since SDL 2.0.14. + * + * \sa SDL_JoystickHasRumbleTriggers + */ +extern DECLSPEC int SDLCALL SDL_JoystickRumbleTriggers(SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble, Uint32 duration_ms); + +/** + * Query whether a joystick has an LED. + * + * An example of a joystick LED is the light on the back of a PlayStation 4's + * DualShock 4 controller. + * + * \param joystick The joystick to query. + * \return SDL_TRUE if the joystick has a modifiable LED, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_JoystickHasLED(SDL_Joystick *joystick); + +/** + * Query whether a joystick has rumble support. + * + * \param joystick The joystick to query. + * \return SDL_TRUE if the joystick has rumble, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_JoystickRumble + */ +extern DECLSPEC SDL_bool SDLCALL SDL_JoystickHasRumble(SDL_Joystick *joystick); + +/** + * Query whether a joystick has rumble support on triggers. + * + * \param joystick The joystick to query. + * \return SDL_TRUE if the joystick has trigger rumble, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_JoystickRumbleTriggers + */ +extern DECLSPEC SDL_bool SDLCALL SDL_JoystickHasRumbleTriggers(SDL_Joystick *joystick); + +/** + * Update a joystick's LED color. + * + * An example of a joystick LED is the light on the back of a PlayStation 4's + * DualShock 4 controller. + * + * \param joystick The joystick to update. + * \param red The intensity of the red LED. + * \param green The intensity of the green LED. + * \param blue The intensity of the blue LED. + * \returns 0 on success, -1 if this joystick does not have a modifiable LED. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_JoystickSetLED(SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue); + +/** + * Send a joystick specific effect packet + * + * \param joystick The joystick to affect. + * \param data The data to send to the joystick. + * \param size The size of the data to send to the joystick. + * \returns 0, or -1 if this joystick or driver doesn't support effect + * packets. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC int SDLCALL SDL_JoystickSendEffect(SDL_Joystick *joystick, const void *data, int size); + +/** + * Close a joystick previously opened with SDL_JoystickOpen(). + * + * \param joystick The joystick device to close. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_JoystickOpen + */ +extern DECLSPEC void SDLCALL SDL_JoystickClose(SDL_Joystick *joystick); + +/** + * Get the battery level of a joystick as SDL_JoystickPowerLevel. + * + * \param joystick the SDL_Joystick to query. + * \returns the current battery level as SDL_JoystickPowerLevel on success or + * `SDL_JOYSTICK_POWER_UNKNOWN` if it is unknown. + * + * \since This function is available since SDL 2.0.4. + */ +extern DECLSPEC SDL_JoystickPowerLevel SDLCALL SDL_JoystickCurrentPowerLevel(SDL_Joystick *joystick); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_joystick_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_keyboard.h b/third_party/SDL2/include/SDL_keyboard.h new file mode 100644 index 00000000000..8c4efdd0786 --- /dev/null +++ b/third_party/SDL2/include/SDL_keyboard.h @@ -0,0 +1,361 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryKeyboard + * + * Include file for SDL keyboard event handling + */ + +#ifndef SDL_keyboard_h_ +#define SDL_keyboard_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_keycode.h" +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The SDL keysym structure, used in key events. + * + * If you are looking for translated character input, see the SDL_TEXTINPUT + * event. + */ +typedef struct SDL_Keysym +{ + SDL_Scancode scancode; /**< SDL physical key code - see SDL_Scancode for details */ + SDL_Keycode sym; /**< SDL virtual key code - see SDL_Keycode for details */ + Uint16 mod; /**< current key modifiers */ + Uint32 unused; +} SDL_Keysym; + +/* Function prototypes */ + +/** + * Query the window which currently has keyboard focus. + * + * \returns the window with keyboard focus. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_Window * SDLCALL SDL_GetKeyboardFocus(void); + +/** + * Get a snapshot of the current state of the keyboard. + * + * The pointer returned is a pointer to an internal SDL array. It will be + * valid for the whole lifetime of the application and should not be freed by + * the caller. + * + * A array element with a value of 1 means that the key is pressed and a value + * of 0 means that it is not. Indexes into this array are obtained by using + * SDL_Scancode values. + * + * Use SDL_PumpEvents() to update the state array. + * + * This function gives you the current state after all events have been + * processed, so if a key or button has been pressed and released before you + * process events, then the pressed state will never show up in the + * SDL_GetKeyboardState() calls. + * + * Note: This function doesn't take into account whether shift has been + * pressed or not. + * + * \param numkeys if non-NULL, receives the length of the returned array. + * \returns a pointer to an array of key states. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PumpEvents + * \sa SDL_ResetKeyboard + */ +extern DECLSPEC const Uint8 *SDLCALL SDL_GetKeyboardState(int *numkeys); + +/** + * Clear the state of the keyboard + * + * This function will generate key up events for all pressed keys. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GetKeyboardState + */ +extern DECLSPEC void SDLCALL SDL_ResetKeyboard(void); + +/** + * Get the current key modifier state for the keyboard. + * + * \returns an OR'd combination of the modifier keys for the keyboard. See + * SDL_Keymod for details. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetKeyboardState + * \sa SDL_SetModState + */ +extern DECLSPEC SDL_Keymod SDLCALL SDL_GetModState(void); + +/** + * Set the current key modifier state for the keyboard. + * + * The inverse of SDL_GetModState(), SDL_SetModState() allows you to impose + * modifier key states on your application. Simply pass your desired modifier + * states into `modstate`. This value may be a bitwise, OR'd combination of + * SDL_Keymod values. + * + * This does not change the keyboard state, only the key modifier flags that + * SDL reports. + * + * \param modstate the desired SDL_Keymod for the keyboard. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetModState + */ +extern DECLSPEC void SDLCALL SDL_SetModState(SDL_Keymod modstate); + +/** + * Get the key code corresponding to the given scancode according to the + * current keyboard layout. + * + * See SDL_Keycode for details. + * + * \param scancode the desired SDL_Scancode to query. + * \returns the SDL_Keycode that corresponds to the given SDL_Scancode. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetKeyName + * \sa SDL_GetScancodeFromKey + */ +extern DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromScancode(SDL_Scancode scancode); + +/** + * Get the scancode corresponding to the given key code according to the + * current keyboard layout. + * + * See SDL_Scancode for details. + * + * \param key the desired SDL_Keycode to query. + * \returns the SDL_Scancode that corresponds to the given SDL_Keycode. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetKeyFromScancode + * \sa SDL_GetScancodeName + */ +extern DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromKey(SDL_Keycode key); + +/** + * Get a human-readable name for a scancode. + * + * See SDL_Scancode for details. + * + * **Warning**: The returned name is by design not stable across platforms, + * e.g. the name for `SDL_SCANCODE_LGUI` is "Left GUI" under Linux but "Left + * Windows" under Microsoft Windows, and some scancodes like + * `SDL_SCANCODE_NONUSBACKSLASH` don't have any name at all. There are even + * scancodes that share names, e.g. `SDL_SCANCODE_RETURN` and + * `SDL_SCANCODE_RETURN2` (both called "Return"). This function is therefore + * unsuitable for creating a stable cross-platform two-way mapping between + * strings and scancodes. + * + * \param scancode the desired SDL_Scancode to query. + * \returns a pointer to the name for the scancode. If the scancode doesn't + * have a name this function returns an empty string (""). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetScancodeFromKey + * \sa SDL_GetScancodeFromName + */ +extern DECLSPEC const char *SDLCALL SDL_GetScancodeName(SDL_Scancode scancode); + +/** + * Get a scancode from a human-readable name. + * + * \param name the human-readable scancode name. + * \returns the SDL_Scancode, or `SDL_SCANCODE_UNKNOWN` if the name wasn't + * recognized; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetKeyFromName + * \sa SDL_GetScancodeFromKey + * \sa SDL_GetScancodeName + */ +extern DECLSPEC SDL_Scancode SDLCALL SDL_GetScancodeFromName(const char *name); + +/** + * Get a human-readable name for a key. + * + * See SDL_Scancode and SDL_Keycode for details. + * + * \param key the desired SDL_Keycode to query. + * \returns a pointer to a UTF-8 string that stays valid at least until the + * next call to this function. If you need it around any longer, you + * must copy it. If the key doesn't have a name, this function + * returns an empty string (""). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetKeyFromName + * \sa SDL_GetKeyFromScancode + * \sa SDL_GetScancodeFromKey + */ +extern DECLSPEC const char *SDLCALL SDL_GetKeyName(SDL_Keycode key); + +/** + * Get a key code from a human-readable name. + * + * \param name the human-readable key name. + * \returns key code, or `SDLK_UNKNOWN` if the name wasn't recognized; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetKeyFromScancode + * \sa SDL_GetKeyName + * \sa SDL_GetScancodeFromName + */ +extern DECLSPEC SDL_Keycode SDLCALL SDL_GetKeyFromName(const char *name); + +/** + * Start accepting Unicode text input events. + * + * This function will start accepting Unicode text input events in the focused + * SDL window, and start emitting SDL_TextInputEvent (SDL_TEXTINPUT) and + * SDL_TextEditingEvent (SDL_TEXTEDITING) events. Please use this function in + * pair with SDL_StopTextInput(). + * + * On some platforms using this function activates the screen keyboard. + * + * On desktop platforms, SDL_StartTextInput() is implicitly called on SDL + * window creation which will cause events SDL_TextInputEvent and + * SDL_TextEditingEvent to begin emitting. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetTextInputRect + * \sa SDL_StopTextInput + */ +extern DECLSPEC void SDLCALL SDL_StartTextInput(void); + +/** + * Check whether or not Unicode text input events are enabled. + * + * \returns SDL_TRUE if text input events are enabled else SDL_FALSE. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_StartTextInput + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsTextInputActive(void); + +/** + * Stop receiving any text input events. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_StartTextInput + */ +extern DECLSPEC void SDLCALL SDL_StopTextInput(void); + +/** + * Dismiss the composition window/IME without disabling the subsystem. + * + * \since This function is available since SDL 2.0.22. + * + * \sa SDL_StartTextInput + * \sa SDL_StopTextInput + */ +extern DECLSPEC void SDLCALL SDL_ClearComposition(void); + +/** + * Returns if an IME Composite or Candidate window is currently shown. + * + * \since This function is available since SDL 2.0.22. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsTextInputShown(void); + +/** + * Set the rectangle used to type Unicode text inputs. + * + * Native input methods will place a window with word suggestions near it, + * without covering the text being inputted. + * + * To start text input in a given location, this function is intended to be + * called before SDL_StartTextInput, although some platforms support moving + * the rectangle even while text input (and a composition) is active. + * + * Note: If you want to use the system native IME window, try setting hint + * **SDL_HINT_IME_SHOW_UI** to **1**, otherwise this function won't give you + * any feedback. + * + * \param rect the SDL_Rect structure representing the rectangle to receive + * text (ignored if NULL). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_StartTextInput + */ +extern DECLSPEC void SDLCALL SDL_SetTextInputRect(const SDL_Rect *rect); + +/** + * Check whether the platform has screen keyboard support. + * + * \returns SDL_TRUE if the platform has some screen keyboard support or + * SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_StartTextInput + * \sa SDL_IsScreenKeyboardShown + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasScreenKeyboardSupport(void); + +/** + * Check whether the screen keyboard is shown for given window. + * + * \param window the window for which screen keyboard should be queried. + * \returns SDL_TRUE if screen keyboard is shown or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HasScreenKeyboardSupport + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenKeyboardShown(SDL_Window *window); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_keyboard_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_keycode.h b/third_party/SDL2/include/SDL_keycode.h new file mode 100644 index 00000000000..eb1678e3861 --- /dev/null +++ b/third_party/SDL2/include/SDL_keycode.h @@ -0,0 +1,358 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryKeycode + * + * Defines constants which identify keyboard keys and modifiers. + */ + +#ifndef SDL_keycode_h_ +#define SDL_keycode_h_ + +#include "SDL_stdinc.h" +#include "SDL_scancode.h" + +/** + * The SDL virtual key representation. + * + * Values of this type are used to represent keyboard keys using the current + * layout of the keyboard. These values include Unicode values representing + * the unmodified character that would be generated by pressing the key, or an + * SDLK_* constant for those keys that do not generate characters. + * + * A special exception is the number keys at the top of the keyboard which map + * to SDLK_0...SDLK_9 on AZERTY layouts. + */ +typedef Sint32 SDL_Keycode; + +#define SDLK_SCANCODE_MASK (1<<30) +#define SDL_SCANCODE_TO_KEYCODE(X) (X | SDLK_SCANCODE_MASK) + +typedef enum SDL_KeyCode +{ + SDLK_UNKNOWN = 0, + + SDLK_RETURN = '\r', + SDLK_ESCAPE = '\x1B', + SDLK_BACKSPACE = '\b', + SDLK_TAB = '\t', + SDLK_SPACE = ' ', + SDLK_EXCLAIM = '!', + SDLK_QUOTEDBL = '"', + SDLK_HASH = '#', + SDLK_PERCENT = '%', + SDLK_DOLLAR = '$', + SDLK_AMPERSAND = '&', + SDLK_QUOTE = '\'', + SDLK_LEFTPAREN = '(', + SDLK_RIGHTPAREN = ')', + SDLK_ASTERISK = '*', + SDLK_PLUS = '+', + SDLK_COMMA = ',', + SDLK_MINUS = '-', + SDLK_PERIOD = '.', + SDLK_SLASH = '/', + SDLK_0 = '0', + SDLK_1 = '1', + SDLK_2 = '2', + SDLK_3 = '3', + SDLK_4 = '4', + SDLK_5 = '5', + SDLK_6 = '6', + SDLK_7 = '7', + SDLK_8 = '8', + SDLK_9 = '9', + SDLK_COLON = ':', + SDLK_SEMICOLON = ';', + SDLK_LESS = '<', + SDLK_EQUALS = '=', + SDLK_GREATER = '>', + SDLK_QUESTION = '?', + SDLK_AT = '@', + + /* + Skip uppercase letters + */ + + SDLK_LEFTBRACKET = '[', + SDLK_BACKSLASH = '\\', + SDLK_RIGHTBRACKET = ']', + SDLK_CARET = '^', + SDLK_UNDERSCORE = '_', + SDLK_BACKQUOTE = '`', + SDLK_a = 'a', + SDLK_b = 'b', + SDLK_c = 'c', + SDLK_d = 'd', + SDLK_e = 'e', + SDLK_f = 'f', + SDLK_g = 'g', + SDLK_h = 'h', + SDLK_i = 'i', + SDLK_j = 'j', + SDLK_k = 'k', + SDLK_l = 'l', + SDLK_m = 'm', + SDLK_n = 'n', + SDLK_o = 'o', + SDLK_p = 'p', + SDLK_q = 'q', + SDLK_r = 'r', + SDLK_s = 's', + SDLK_t = 't', + SDLK_u = 'u', + SDLK_v = 'v', + SDLK_w = 'w', + SDLK_x = 'x', + SDLK_y = 'y', + SDLK_z = 'z', + + SDLK_CAPSLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CAPSLOCK), + + SDLK_F1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F1), + SDLK_F2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F2), + SDLK_F3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F3), + SDLK_F4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F4), + SDLK_F5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F5), + SDLK_F6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F6), + SDLK_F7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F7), + SDLK_F8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F8), + SDLK_F9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F9), + SDLK_F10 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F10), + SDLK_F11 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F11), + SDLK_F12 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F12), + + SDLK_PRINTSCREEN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRINTSCREEN), + SDLK_SCROLLLOCK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SCROLLLOCK), + SDLK_PAUSE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAUSE), + SDLK_INSERT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_INSERT), + SDLK_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HOME), + SDLK_PAGEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEUP), + SDLK_DELETE = '\x7F', + SDLK_END = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_END), + SDLK_PAGEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PAGEDOWN), + SDLK_RIGHT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RIGHT), + SDLK_LEFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LEFT), + SDLK_DOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DOWN), + SDLK_UP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UP), + + SDLK_NUMLOCKCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_NUMLOCKCLEAR), + SDLK_KP_DIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DIVIDE), + SDLK_KP_MULTIPLY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MULTIPLY), + SDLK_KP_MINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MINUS), + SDLK_KP_PLUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUS), + SDLK_KP_ENTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_ENTER), + SDLK_KP_1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_1), + SDLK_KP_2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_2), + SDLK_KP_3 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_3), + SDLK_KP_4 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_4), + SDLK_KP_5 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_5), + SDLK_KP_6 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_6), + SDLK_KP_7 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_7), + SDLK_KP_8 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_8), + SDLK_KP_9 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_9), + SDLK_KP_0 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_0), + SDLK_KP_PERIOD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERIOD), + + SDLK_APPLICATION = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APPLICATION), + SDLK_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_POWER), + SDLK_KP_EQUALS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALS), + SDLK_F13 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F13), + SDLK_F14 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F14), + SDLK_F15 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F15), + SDLK_F16 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F16), + SDLK_F17 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F17), + SDLK_F18 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F18), + SDLK_F19 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F19), + SDLK_F20 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F20), + SDLK_F21 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F21), + SDLK_F22 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F22), + SDLK_F23 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F23), + SDLK_F24 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_F24), + SDLK_EXECUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXECUTE), + SDLK_HELP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_HELP), + SDLK_MENU = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MENU), + SDLK_SELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SELECT), + SDLK_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_STOP), + SDLK_AGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AGAIN), + SDLK_UNDO = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_UNDO), + SDLK_CUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CUT), + SDLK_COPY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COPY), + SDLK_PASTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PASTE), + SDLK_FIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_FIND), + SDLK_MUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MUTE), + SDLK_VOLUMEUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEUP), + SDLK_VOLUMEDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_VOLUMEDOWN), + SDLK_KP_COMMA = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COMMA), + SDLK_KP_EQUALSAS400 = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EQUALSAS400), + + SDLK_ALTERASE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ALTERASE), + SDLK_SYSREQ = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SYSREQ), + SDLK_CANCEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CANCEL), + SDLK_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEAR), + SDLK_PRIOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_PRIOR), + SDLK_RETURN2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RETURN2), + SDLK_SEPARATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SEPARATOR), + SDLK_OUT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OUT), + SDLK_OPER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_OPER), + SDLK_CLEARAGAIN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CLEARAGAIN), + SDLK_CRSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CRSEL), + SDLK_EXSEL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EXSEL), + + SDLK_KP_00 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_00), + SDLK_KP_000 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_000), + SDLK_THOUSANDSSEPARATOR = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_THOUSANDSSEPARATOR), + SDLK_DECIMALSEPARATOR = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DECIMALSEPARATOR), + SDLK_CURRENCYUNIT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYUNIT), + SDLK_CURRENCYSUBUNIT = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CURRENCYSUBUNIT), + SDLK_KP_LEFTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTPAREN), + SDLK_KP_RIGHTPAREN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTPAREN), + SDLK_KP_LEFTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LEFTBRACE), + SDLK_KP_RIGHTBRACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_RIGHTBRACE), + SDLK_KP_TAB = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_TAB), + SDLK_KP_BACKSPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BACKSPACE), + SDLK_KP_A = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_A), + SDLK_KP_B = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_B), + SDLK_KP_C = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_C), + SDLK_KP_D = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_D), + SDLK_KP_E = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_E), + SDLK_KP_F = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_F), + SDLK_KP_XOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_XOR), + SDLK_KP_POWER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_POWER), + SDLK_KP_PERCENT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PERCENT), + SDLK_KP_LESS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_LESS), + SDLK_KP_GREATER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_GREATER), + SDLK_KP_AMPERSAND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AMPERSAND), + SDLK_KP_DBLAMPERSAND = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLAMPERSAND), + SDLK_KP_VERTICALBAR = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_VERTICALBAR), + SDLK_KP_DBLVERTICALBAR = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DBLVERTICALBAR), + SDLK_KP_COLON = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_COLON), + SDLK_KP_HASH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HASH), + SDLK_KP_SPACE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_SPACE), + SDLK_KP_AT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_AT), + SDLK_KP_EXCLAM = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_EXCLAM), + SDLK_KP_MEMSTORE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSTORE), + SDLK_KP_MEMRECALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMRECALL), + SDLK_KP_MEMCLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMCLEAR), + SDLK_KP_MEMADD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMADD), + SDLK_KP_MEMSUBTRACT = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMSUBTRACT), + SDLK_KP_MEMMULTIPLY = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMMULTIPLY), + SDLK_KP_MEMDIVIDE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_MEMDIVIDE), + SDLK_KP_PLUSMINUS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_PLUSMINUS), + SDLK_KP_CLEAR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEAR), + SDLK_KP_CLEARENTRY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_CLEARENTRY), + SDLK_KP_BINARY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_BINARY), + SDLK_KP_OCTAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_OCTAL), + SDLK_KP_DECIMAL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_DECIMAL), + SDLK_KP_HEXADECIMAL = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KP_HEXADECIMAL), + + SDLK_LCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LCTRL), + SDLK_LSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LSHIFT), + SDLK_LALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LALT), + SDLK_LGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_LGUI), + SDLK_RCTRL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RCTRL), + SDLK_RSHIFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RSHIFT), + SDLK_RALT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RALT), + SDLK_RGUI = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_RGUI), + + SDLK_MODE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MODE), + + SDLK_AUDIONEXT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIONEXT), + SDLK_AUDIOPREV = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPREV), + SDLK_AUDIOSTOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOSTOP), + SDLK_AUDIOPLAY = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOPLAY), + SDLK_AUDIOMUTE = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOMUTE), + SDLK_MEDIASELECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MEDIASELECT), + SDLK_WWW = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_WWW), + SDLK_MAIL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_MAIL), + SDLK_CALCULATOR = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALCULATOR), + SDLK_COMPUTER = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_COMPUTER), + SDLK_AC_SEARCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_SEARCH), + SDLK_AC_HOME = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_HOME), + SDLK_AC_BACK = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BACK), + SDLK_AC_FORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_FORWARD), + SDLK_AC_STOP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_STOP), + SDLK_AC_REFRESH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_REFRESH), + SDLK_AC_BOOKMARKS = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AC_BOOKMARKS), + + SDLK_BRIGHTNESSDOWN = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSDOWN), + SDLK_BRIGHTNESSUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_BRIGHTNESSUP), + SDLK_DISPLAYSWITCH = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_DISPLAYSWITCH), + SDLK_KBDILLUMTOGGLE = + SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMTOGGLE), + SDLK_KBDILLUMDOWN = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMDOWN), + SDLK_KBDILLUMUP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_KBDILLUMUP), + SDLK_EJECT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_EJECT), + SDLK_SLEEP = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SLEEP), + SDLK_APP1 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP1), + SDLK_APP2 = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_APP2), + + SDLK_AUDIOREWIND = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOREWIND), + SDLK_AUDIOFASTFORWARD = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_AUDIOFASTFORWARD), + + SDLK_SOFTLEFT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SOFTLEFT), + SDLK_SOFTRIGHT = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_SOFTRIGHT), + SDLK_CALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_CALL), + SDLK_ENDCALL = SDL_SCANCODE_TO_KEYCODE(SDL_SCANCODE_ENDCALL) +} SDL_KeyCode; + +/** + * Enumeration of valid key mods (possibly OR'd together). + */ +typedef enum SDL_Keymod +{ + KMOD_NONE = 0x0000, + KMOD_LSHIFT = 0x0001, + KMOD_RSHIFT = 0x0002, + KMOD_LCTRL = 0x0040, + KMOD_RCTRL = 0x0080, + KMOD_LALT = 0x0100, + KMOD_RALT = 0x0200, + KMOD_LGUI = 0x0400, + KMOD_RGUI = 0x0800, + KMOD_NUM = 0x1000, + KMOD_CAPS = 0x2000, + KMOD_MODE = 0x4000, + KMOD_SCROLL = 0x8000, + + KMOD_CTRL = KMOD_LCTRL | KMOD_RCTRL, + KMOD_SHIFT = KMOD_LSHIFT | KMOD_RSHIFT, + KMOD_ALT = KMOD_LALT | KMOD_RALT, + KMOD_GUI = KMOD_LGUI | KMOD_RGUI, + + KMOD_RESERVED = KMOD_SCROLL /* This is for source-level compatibility with SDL 2.0.0. */ +} SDL_Keymod; + +#endif /* SDL_keycode_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_loadso.h b/third_party/SDL2/include/SDL_loadso.h new file mode 100644 index 00000000000..1763b528012 --- /dev/null +++ b/third_party/SDL2/include/SDL_loadso.h @@ -0,0 +1,117 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: LoadSO */ + +/** + * # CategoryLoadSO + * + * System-dependent library loading routines. + * + * Some things to keep in mind: + * + * - These functions only work on C function names. Other languages may have + * name mangling and intrinsic language support that varies from compiler to + * compiler. + * - Make sure you declare your function pointers with the same calling + * convention as the actual library function. Your code will crash + * mysteriously if you do not do this. + * - Avoid namespace collisions. If you load a symbol from the library, it is + * not defined whether or not it goes into the global symbol namespace for + * the application. If it does and it conflicts with symbols in your code or + * other shared libraries, you will not get the results you expect. :) + */ + +#ifndef SDL_loadso_h_ +#define SDL_loadso_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Dynamically load a shared object. + * + * \param sofile a system-dependent name of the object file. + * \returns an opaque pointer to the object handle or NULL if there was an + * error; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LoadFunction + * \sa SDL_UnloadObject + */ +extern DECLSPEC void *SDLCALL SDL_LoadObject(const char *sofile); + +/** + * Look up the address of the named function in a shared object. + * + * This function pointer is no longer valid after calling SDL_UnloadObject(). + * + * This function can only look up C function names. Other languages may have + * name mangling and intrinsic language support that varies from compiler to + * compiler. + * + * Make sure you declare your function pointers with the same calling + * convention as the actual library function. Your code will crash + * mysteriously if you do not do this. + * + * If the requested function doesn't exist, NULL is returned. + * + * \param handle a valid shared object handle returned by SDL_LoadObject(). + * \param name the name of the function to look up. + * \returns a pointer to the function or NULL if there was an error; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LoadObject + * \sa SDL_UnloadObject + */ +extern DECLSPEC void *SDLCALL SDL_LoadFunction(void *handle, + const char *name); + +/** + * Unload a shared object from memory. + * + * \param handle a valid shared object handle returned by SDL_LoadObject(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LoadFunction + * \sa SDL_LoadObject + */ +extern DECLSPEC void SDLCALL SDL_UnloadObject(void *handle); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_loadso_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_locale.h b/third_party/SDL2/include/SDL_locale.h new file mode 100644 index 00000000000..8126efc79a5 --- /dev/null +++ b/third_party/SDL2/include/SDL_locale.h @@ -0,0 +1,103 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryLocale + * + * Include file for SDL locale services + */ + +#ifndef _SDL_locale_h +#define _SDL_locale_h + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + + +typedef struct SDL_Locale +{ + const char *language; /**< A language name, like "en" for English. */ + const char *country; /**< A country, like "US" for America. Can be NULL. */ +} SDL_Locale; + +/** + * Report the user's preferred locale. + * + * This returns an array of SDL_Locale structs, the final item zeroed out. + * When the caller is done with this array, it should call SDL_free() on the + * returned value; all the memory involved is allocated in a single block, so + * a single SDL_free() will suffice. + * + * Returned language strings are in the format xx, where 'xx' is an ISO-639 + * language specifier (such as "en" for English, "de" for German, etc). + * Country strings are in the format YY, where "YY" is an ISO-3166 country + * code (such as "US" for the United States, "CA" for Canada, etc). Country + * might be NULL if there's no specific guidance on them (so you might get { + * "en", "US" } for American English, but { "en", NULL } means "English + * language, generically"). Language strings are never NULL, except to + * terminate the array. + * + * Please note that not all of these strings are 2 characters; some are three + * or more. + * + * The returned list of locales are in the order of the user's preference. For + * example, a German citizen that is fluent in US English and knows enough + * Japanese to navigate around Tokyo might have a list like: { "de", "en_US", + * "jp", NULL }. Someone from England might prefer British English (where + * "color" is spelled "colour", etc), but will settle for anything like it: { + * "en_GB", "en", NULL }. + * + * This function returns NULL on error, including when the platform does not + * supply this information at all. + * + * This might be a "slow" call that has to query the operating system. It's + * best to ask for this once and save the results. However, this list can + * change, usually because the user has changed a system preference outside of + * your program; SDL will send an SDL_LOCALECHANGED event in this case, if + * possible, and you can call this function again to get an updated copy of + * preferred locales. + * + * \return array of locales, terminated with a locale with a NULL language + * field. Will return NULL on error. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_Locale * SDLCALL SDL_GetPreferredLocales(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif +#include "close_code.h" + +#endif /* _SDL_locale_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_log.h b/third_party/SDL2/include/SDL_log.h new file mode 100644 index 00000000000..75833ba3c37 --- /dev/null +++ b/third_party/SDL2/include/SDL_log.h @@ -0,0 +1,405 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryLog + * + * Simple log messages with categories and priorities. + * + * By default logs are quiet, but if you're debugging SDL you might want: + * + * SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN); + * + * Here's where the messages go on different platforms: + * + * - Windows: debug output stream + * - Android: log output + * - Others: standard error output (stderr) + */ + +#ifndef SDL_log_h_ +#define SDL_log_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * The maximum size of a log message prior to SDL 2.0.24 + * + * As of 2.0.24 there is no limit to the length of SDL log messages. + */ +#define SDL_MAX_LOG_MESSAGE 4096 + +/** + * The predefined log categories + * + * By default the application category is enabled at the INFO level, the + * assert category is enabled at the WARN level, test is enabled at the + * VERBOSE level and all other categories are enabled at the ERROR level. + */ +typedef enum SDL_LogCategory +{ + SDL_LOG_CATEGORY_APPLICATION, + SDL_LOG_CATEGORY_ERROR, + SDL_LOG_CATEGORY_ASSERT, + SDL_LOG_CATEGORY_SYSTEM, + SDL_LOG_CATEGORY_AUDIO, + SDL_LOG_CATEGORY_VIDEO, + SDL_LOG_CATEGORY_RENDER, + SDL_LOG_CATEGORY_INPUT, + SDL_LOG_CATEGORY_TEST, + + /* Reserved for future SDL library use */ + SDL_LOG_CATEGORY_RESERVED1, + SDL_LOG_CATEGORY_RESERVED2, + SDL_LOG_CATEGORY_RESERVED3, + SDL_LOG_CATEGORY_RESERVED4, + SDL_LOG_CATEGORY_RESERVED5, + SDL_LOG_CATEGORY_RESERVED6, + SDL_LOG_CATEGORY_RESERVED7, + SDL_LOG_CATEGORY_RESERVED8, + SDL_LOG_CATEGORY_RESERVED9, + SDL_LOG_CATEGORY_RESERVED10, + + /* Beyond this point is reserved for application use, e.g. + enum { + MYAPP_CATEGORY_AWESOME1 = SDL_LOG_CATEGORY_CUSTOM, + MYAPP_CATEGORY_AWESOME2, + MYAPP_CATEGORY_AWESOME3, + ... + }; + */ + SDL_LOG_CATEGORY_CUSTOM +} SDL_LogCategory; + +/** + * The predefined log priorities + */ +typedef enum SDL_LogPriority +{ + SDL_LOG_PRIORITY_VERBOSE = 1, + SDL_LOG_PRIORITY_DEBUG, + SDL_LOG_PRIORITY_INFO, + SDL_LOG_PRIORITY_WARN, + SDL_LOG_PRIORITY_ERROR, + SDL_LOG_PRIORITY_CRITICAL, + SDL_NUM_LOG_PRIORITIES +} SDL_LogPriority; + + +/** + * Set the priority of all log categories. + * + * \param priority the SDL_LogPriority to assign. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LogSetPriority + */ +extern DECLSPEC void SDLCALL SDL_LogSetAllPriority(SDL_LogPriority priority); + +/** + * Set the priority of a particular log category. + * + * \param category the category to assign a priority to. + * \param priority the SDL_LogPriority to assign. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LogGetPriority + * \sa SDL_LogSetAllPriority + */ +extern DECLSPEC void SDLCALL SDL_LogSetPriority(int category, + SDL_LogPriority priority); + +/** + * Get the priority of a particular log category. + * + * \param category the category to query. + * \returns the SDL_LogPriority for the requested category. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LogSetPriority + */ +extern DECLSPEC SDL_LogPriority SDLCALL SDL_LogGetPriority(int category); + +/** + * Reset all priorities to default. + * + * This is called by SDL_Quit(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LogSetAllPriority + * \sa SDL_LogSetPriority + */ +extern DECLSPEC void SDLCALL SDL_LogResetPriorities(void); + +/** + * Log a message with SDL_LOG_CATEGORY_APPLICATION and SDL_LOG_PRIORITY_INFO. + * + * = * \param fmt a printf() style message format string + * + * \param ... additional parameters matching % tokens in the `fmt` string, if + * any. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern DECLSPEC void SDLCALL SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1); + +/** + * Log a message with SDL_LOG_PRIORITY_VERBOSE. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogWarn + */ +extern DECLSPEC void SDLCALL SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_DEBUG. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern DECLSPEC void SDLCALL SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_INFO. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern DECLSPEC void SDLCALL SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_WARN. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogVerbose + */ +extern DECLSPEC void SDLCALL SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_ERROR. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern DECLSPEC void SDLCALL SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with SDL_LOG_PRIORITY_CRITICAL. + * + * \param category the category of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Log + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogMessageV + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern DECLSPEC void SDLCALL SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/** + * Log a message with the specified category and priority. + * + * \param category the category of the message. + * \param priority the priority of the message. + * \param fmt a printf() style message format string. + * \param ... additional parameters matching % tokens in the **fmt** string, + * if any. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessageV + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern DECLSPEC void SDLCALL SDL_LogMessage(int category, + SDL_LogPriority priority, + SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(3); + +/** + * Log a message with the specified category and priority. + * + * \param category the category of the message. + * \param priority the priority of the message. + * \param fmt a printf() style message format string. + * \param ap a variable argument list. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Log + * \sa SDL_LogCritical + * \sa SDL_LogDebug + * \sa SDL_LogError + * \sa SDL_LogInfo + * \sa SDL_LogMessage + * \sa SDL_LogVerbose + * \sa SDL_LogWarn + */ +extern DECLSPEC void SDLCALL SDL_LogMessageV(int category, + SDL_LogPriority priority, + SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(3); + +/** + * The prototype for the log output callback function. + * + * This function is called by SDL when there is new text to be logged. + * + * \param userdata what was passed as `userdata` to + * SDL_LogSetOutputFunction(). + * \param category the category of the message. + * \param priority the priority of the message. + * \param message the message being output. + */ +typedef void (SDLCALL *SDL_LogOutputFunction)(void *userdata, int category, SDL_LogPriority priority, const char *message); + +/** + * Get the current log output function. + * + * \param callback an SDL_LogOutputFunction filled in with the current log + * callback. + * \param userdata a pointer filled in with the pointer that is passed to + * `callback`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LogSetOutputFunction + */ +extern DECLSPEC void SDLCALL SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata); + +/** + * Replace the default log output function with one of your own. + * + * \param callback an SDL_LogOutputFunction to call instead of the default. + * \param userdata a pointer that is passed to `callback`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LogGetOutputFunction + */ +extern DECLSPEC void SDLCALL SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_log_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_main.h b/third_party/SDL2/include/SDL_main.h new file mode 100644 index 00000000000..a1ef3e74643 --- /dev/null +++ b/third_party/SDL2/include/SDL_main.h @@ -0,0 +1,282 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_main_h_ +#define SDL_main_h_ + +#include "SDL_stdinc.h" + +/** + * # CategoryMain + * + * Redefine main() on some platforms so that it is called by SDL. + */ + +#ifndef SDL_MAIN_HANDLED +#if defined(__WIN32__) +/* On Windows SDL provides WinMain(), which parses the command line and passes + the arguments to your main function. + + If you provide your own WinMain(), you may define SDL_MAIN_HANDLED + */ +#define SDL_MAIN_AVAILABLE + +#elif defined(__WINRT__) +/* On WinRT, SDL provides a main function that initializes CoreApplication, + creating an instance of IFrameworkView in the process. + + Please note that #include'ing SDL_main.h is not enough to get a main() + function working. In non-XAML apps, the file, + src/main/winrt/SDL_WinRT_main_NonXAML.cpp, or a copy of it, must be compiled + into the app itself. In XAML apps, the function, SDL_WinRTRunApp must be + called, with a pointer to the Direct3D-hosted XAML control passed in. +*/ +#define SDL_MAIN_NEEDED + +#elif defined(__GDK__) +/* On GDK, SDL provides a main function that initializes the game runtime. + + Please note that #include'ing SDL_main.h is not enough to get a main() + function working. You must either link against SDL2main or, if not possible, + call the SDL_GDKRunApp function from your entry point. +*/ +#define SDL_MAIN_NEEDED + +#elif defined(__IPHONEOS__) +/* On iOS SDL provides a main function that creates an application delegate + and starts the iOS application run loop. + + If you link with SDL dynamically on iOS, the main function can't be in a + shared library, so you need to link with libSDLmain.a, which includes a + stub main function that calls into the shared library to start execution. + + See src/video/uikit/SDL_uikitappdelegate.m for more details. + */ +#define SDL_MAIN_NEEDED + +#elif defined(__ANDROID__) +/* On Android SDL provides a Java class in SDLActivity.java that is the + main activity entry point. + + See docs/README-android.md for more details on extending that class. + */ +#define SDL_MAIN_NEEDED + +/* We need to export SDL_main so it can be launched from Java */ +#define SDLMAIN_DECLSPEC DECLSPEC + +#elif defined(__NACL__) +/* On NACL we use ppapi_simple to set up the application helper code, + then wait for the first PSE_INSTANCE_DIDCHANGEVIEW event before + starting the user main function. + All user code is run in a separate thread by ppapi_simple, thus + allowing for blocking io to take place via nacl_io +*/ +#define SDL_MAIN_NEEDED + +#elif defined(__PSP__) +/* On PSP SDL provides a main function that sets the module info, + activates the GPU and starts the thread required to be able to exit + the software. + + If you provide this yourself, you may define SDL_MAIN_HANDLED + */ +#define SDL_MAIN_AVAILABLE + +#elif defined(__PS2__) +#define SDL_MAIN_AVAILABLE + +#define SDL_PS2_SKIP_IOP_RESET() \ + void reset_IOP(); \ + void reset_IOP() {} + +#elif defined(__3DS__) +/* + On N3DS, SDL provides a main function that sets up the screens + and storage. + + If you provide this yourself, you may define SDL_MAIN_HANDLED +*/ +#define SDL_MAIN_AVAILABLE + +#endif +#endif /* SDL_MAIN_HANDLED */ + +#ifndef SDLMAIN_DECLSPEC +#define SDLMAIN_DECLSPEC +#endif + +/** + * \file SDL_main.h + * + * The application's main() function must be called with C linkage, + * and should be declared like this: + * ```c + * #ifdef __cplusplus + * extern "C" + * #endif + * int main(int argc, char *argv[]) + * { + * } + * ``` + */ + +#if defined(SDL_MAIN_NEEDED) || defined(SDL_MAIN_AVAILABLE) +#define main SDL_main +#endif + +#include "begin_code.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The prototype for the application's main() function + */ +typedef int (*SDL_main_func)(int argc, char *argv[]); +extern SDLMAIN_DECLSPEC int SDL_main(int argc, char *argv[]); + + +/** + * Circumvent failure of SDL_Init() when not using SDL_main() as an entry + * point. + * + * This function is defined in SDL_main.h, along with the preprocessor rule to + * redefine main() as SDL_main(). Thus to ensure that your main() function + * will not be changed it is necessary to define SDL_MAIN_HANDLED before + * including SDL.h. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_Init + */ +extern DECLSPEC void SDLCALL SDL_SetMainReady(void); + +#if defined(__WIN32__) || defined(__GDK__) + +/** + * Register a win32 window class for SDL's use. + * + * This can be called to set the application window class at startup. It is + * safe to call this multiple times, as long as every call is eventually + * paired with a call to SDL_UnregisterApp, but a second registration attempt + * while a previous registration is still active will be ignored, other than + * to increment a counter. + * + * Most applications do not need to, and should not, call this directly; SDL + * will call it when initializing the video subsystem. + * + * \param name the window class name, in UTF-8 encoding. If NULL, SDL + * currently uses "SDL_app" but this isn't guaranteed. + * \param style the value to use in WNDCLASSEX::style. If `name` is NULL, SDL + * currently uses `(CS_BYTEALIGNCLIENT | CS_OWNDC)` regardless of + * what is specified here. + * \param hInst the HINSTANCE to use in WNDCLASSEX::hInstance. If zero, SDL + * will use `GetModuleHandle(NULL)` instead. + * \returns 0 on success, -1 on error. SDL_GetError() may have details. + * + * \since This function is available since SDL 2.0.2. + */ +extern DECLSPEC int SDLCALL SDL_RegisterApp(const char *name, Uint32 style, void *hInst); + +/** + * Deregister the win32 window class from an SDL_RegisterApp call. + * + * This can be called to undo the effects of SDL_RegisterApp. + * + * Most applications do not need to, and should not, call this directly; SDL + * will call it when deinitializing the video subsystem. + * + * It is safe to call this multiple times, as long as every call is eventually + * paired with a prior call to SDL_RegisterApp. The window class will only be + * deregistered when the registration counter in SDL_RegisterApp decrements to + * zero through calls to this function. + * + * \since This function is available since SDL 2.0.2. + */ +extern DECLSPEC void SDLCALL SDL_UnregisterApp(void); + +#endif /* defined(__WIN32__) || defined(__GDK__) */ + + +#ifdef __WINRT__ + +/** + * Initialize and launch an SDL/WinRT application. + * + * \param mainFunction the SDL app's C-style main(), an SDL_main_func. + * \param reserved reserved for future use; should be NULL. + * \returns 0 on success or -1 on failure; call SDL_GetError() to retrieve + * more information on the failure. + * + * \since This function is available since SDL 2.0.3. + */ +extern DECLSPEC int SDLCALL SDL_WinRTRunApp(SDL_main_func mainFunction, void * reserved); + +#endif /* __WINRT__ */ + +#if defined(__IPHONEOS__) + +/** + * Initializes and launches an SDL application. + * + * \param argc The argc parameter from the application's main() function. + * \param argv The argv parameter from the application's main() function. + * \param mainFunction The SDL app's C-style main(), an SDL_main_func. + * \return the return value from mainFunction. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_UIKitRunApp(int argc, char *argv[], SDL_main_func mainFunction); + +#endif /* __IPHONEOS__ */ + +#ifdef __GDK__ + +/** + * Initialize and launch an SDL GDK application. + * + * \param mainFunction the SDL app's C-style main(), an SDL_main_func. + * \param reserved reserved for future use; should be NULL. + * \returns 0 on success or -1 on failure; call SDL_GetError() to retrieve + * more information on the failure. + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC int SDLCALL SDL_GDKRunApp(SDL_main_func mainFunction, void *reserved); + +/** + * Callback from the application to let the suspend continue. + * + * \since This function is available since SDL 2.28.0. + */ +extern DECLSPEC void SDLCALL SDL_GDKSuspendComplete(void); + +#endif /* __GDK__ */ + +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_main_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_messagebox.h b/third_party/SDL2/include/SDL_messagebox.h new file mode 100644 index 00000000000..725d4124adc --- /dev/null +++ b/third_party/SDL2/include/SDL_messagebox.h @@ -0,0 +1,196 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_messagebox_h_ +#define SDL_messagebox_h_ + +#include "SDL_stdinc.h" +#include "SDL_video.h" /* For SDL_Window */ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * SDL_MessageBox flags. + * + * If supported will display warning icon, etc. + */ +typedef enum SDL_MessageBoxFlags +{ + SDL_MESSAGEBOX_ERROR = 0x00000010, /**< error dialog */ + SDL_MESSAGEBOX_WARNING = 0x00000020, /**< warning dialog */ + SDL_MESSAGEBOX_INFORMATION = 0x00000040, /**< informational dialog */ + SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT = 0x00000080, /**< buttons placed left to right */ + SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT = 0x00000100 /**< buttons placed right to left */ +} SDL_MessageBoxFlags; + +/** + * Flags for SDL_MessageBoxButtonData. + */ +typedef enum SDL_MessageBoxButtonFlags +{ + SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT = 0x00000001, /**< Marks the default button when return is hit */ + SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT = 0x00000002 /**< Marks the default button when escape is hit */ +} SDL_MessageBoxButtonFlags; + +/** + * Individual button data. + */ +typedef struct SDL_MessageBoxButtonData +{ + Uint32 flags; /**< SDL_MessageBoxButtonFlags */ + int buttonid; /**< User defined button id (value returned via SDL_ShowMessageBox) */ + const char * text; /**< The UTF-8 button text */ +} SDL_MessageBoxButtonData; + +/** + * RGB value used in a message box color scheme + */ +typedef struct SDL_MessageBoxColor +{ + Uint8 r, g, b; +} SDL_MessageBoxColor; + +typedef enum SDL_MessageBoxColorType +{ + SDL_MESSAGEBOX_COLOR_BACKGROUND, + SDL_MESSAGEBOX_COLOR_TEXT, + SDL_MESSAGEBOX_COLOR_BUTTON_BORDER, + SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND, + SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED, + SDL_MESSAGEBOX_COLOR_MAX +} SDL_MessageBoxColorType; + +/** + * A set of colors to use for message box dialogs + */ +typedef struct SDL_MessageBoxColorScheme +{ + SDL_MessageBoxColor colors[SDL_MESSAGEBOX_COLOR_MAX]; +} SDL_MessageBoxColorScheme; + +/** + * MessageBox structure containing title, text, window, etc. + */ +typedef struct SDL_MessageBoxData +{ + Uint32 flags; /**< SDL_MessageBoxFlags */ + SDL_Window *window; /**< Parent window, can be NULL */ + const char *title; /**< UTF-8 title */ + const char *message; /**< UTF-8 message text */ + + int numbuttons; + const SDL_MessageBoxButtonData *buttons; + + const SDL_MessageBoxColorScheme *colorScheme; /**< SDL_MessageBoxColorScheme, can be NULL to use system settings */ +} SDL_MessageBoxData; + +/** + * Create a modal message box. + * + * If your needs aren't complex, it might be easier to use + * SDL_ShowSimpleMessageBox. + * + * This function should be called on the thread that created the parent + * window, or on the main thread if the messagebox has no parent. It will + * block execution of that thread until the user clicks a button or closes the + * messagebox. + * + * This function may be called at any time, even before SDL_Init(). This makes + * it useful for reporting errors like a failure to create a renderer or + * OpenGL context. + * + * On X11, SDL rolls its own dialog box with X11 primitives instead of a + * formal toolkit like GTK+ or Qt. + * + * Note that if SDL_Init() would fail because there isn't any available video + * target, this function is likely to fail for the same reasons. If this is a + * concern, check the return value from this function and fall back to writing + * to stderr if you can. + * + * \param messageboxdata the SDL_MessageBoxData structure with title, text and + * other options. + * \param buttonid the pointer to which user id of hit button should be + * copied. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ShowSimpleMessageBox + */ +extern DECLSPEC int SDLCALL SDL_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid); + +/** + * Display a simple modal message box. + * + * If your needs aren't complex, this function is preferred over + * SDL_ShowMessageBox. + * + * `flags` may be any of the following: + * + * - `SDL_MESSAGEBOX_ERROR`: error dialog + * - `SDL_MESSAGEBOX_WARNING`: warning dialog + * - `SDL_MESSAGEBOX_INFORMATION`: informational dialog + * + * This function should be called on the thread that created the parent + * window, or on the main thread if the messagebox has no parent. It will + * block execution of that thread until the user clicks a button or closes the + * messagebox. + * + * This function may be called at any time, even before SDL_Init(). This makes + * it useful for reporting errors like a failure to create a renderer or + * OpenGL context. + * + * On X11, SDL rolls its own dialog box with X11 primitives instead of a + * formal toolkit like GTK+ or Qt. + * + * Note that if SDL_Init() would fail because there isn't any available video + * target, this function is likely to fail for the same reasons. If this is a + * concern, check the return value from this function and fall back to writing + * to stderr if you can. + * + * \param flags an SDL_MessageBoxFlags value. + * \param title UTF-8 title text. + * \param message UTF-8 message text. + * \param window the parent window, or NULL for no parent. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ShowMessageBox + */ +extern DECLSPEC int SDLCALL SDL_ShowSimpleMessageBox(Uint32 flags, const char *title, const char *message, SDL_Window *window); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_messagebox_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_metal.h b/third_party/SDL2/include/SDL_metal.h new file mode 100644 index 00000000000..d3f21d5ecff --- /dev/null +++ b/third_party/SDL2/include/SDL_metal.h @@ -0,0 +1,114 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryMetal + * + * Header file for functions to creating Metal layers and views on SDL + * windows. + */ + +#ifndef SDL_metal_h_ +#define SDL_metal_h_ + +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * A handle to a CAMetalLayer-backed NSView (macOS) or UIView (iOS/tvOS). + * + * This can be cast directly to an NSView or UIView. + */ +typedef void *SDL_MetalView; + +/** + * \name Metal support functions + */ +/* @{ */ + +/** + * Create a CAMetalLayer-backed NSView/UIView and attach it to the specified + * window. + * + * On macOS, this does *not* associate a MTLDevice with the CAMetalLayer on + * its own. It is up to user code to do that. + * + * The returned handle can be casted directly to a NSView or UIView. To access + * the backing CAMetalLayer, call SDL_Metal_GetLayer(). + * + * \since This function is available since SDL 2.0.12. + * + * \sa SDL_Metal_DestroyView + * \sa SDL_Metal_GetLayer + */ +extern DECLSPEC SDL_MetalView SDLCALL SDL_Metal_CreateView(SDL_Window * window); + +/** + * Destroy an existing SDL_MetalView object. + * + * This should be called before SDL_DestroyWindow, if SDL_Metal_CreateView was + * called after SDL_CreateWindow. + * + * \since This function is available since SDL 2.0.12. + * + * \sa SDL_Metal_CreateView + */ +extern DECLSPEC void SDLCALL SDL_Metal_DestroyView(SDL_MetalView view); + +/** + * Get a pointer to the backing CAMetalLayer for the given view. + * + * \since This function is available since SDL 2.0.14. + * + * \sa SDL_Metal_CreateView + */ +extern DECLSPEC void *SDLCALL SDL_Metal_GetLayer(SDL_MetalView view); + +/** + * Get the size of a window's underlying drawable in pixels (for use with + * setting viewport, scissor & etc). + * + * \param window SDL_Window from which the drawable size should be queried. + * \param w Pointer to variable for storing the width in pixels, may be NULL. + * \param h Pointer to variable for storing the height in pixels, may be NULL. + * + * \since This function is available since SDL 2.0.14. + * + * \sa SDL_GetWindowSize + * \sa SDL_CreateWindow + */ +extern DECLSPEC void SDLCALL SDL_Metal_GetDrawableSize(SDL_Window* window, int *w, + int *h); + +/* @} *//* Metal support functions */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_metal_h_ */ diff --git a/third_party/SDL2/include/SDL_misc.h b/third_party/SDL2/include/SDL_misc.h new file mode 100644 index 00000000000..86a82bc5d6a --- /dev/null +++ b/third_party/SDL2/include/SDL_misc.h @@ -0,0 +1,79 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryMisc + * + * Include file for SDL API functions that don't fit elsewhere. + */ + +#ifndef SDL_misc_h_ +#define SDL_misc_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" + +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Open a URL/URI in the browser or other appropriate external application. + * + * Open a URL in a separate, system-provided application. How this works will + * vary wildly depending on the platform. This will likely launch what makes + * sense to handle a specific URL's protocol (a web browser for `http://`, + * etc), but it might also be able to launch file managers for directories and + * other things. + * + * What happens when you open a URL varies wildly as well: your game window + * may lose focus (and may or may not lose focus if your game was fullscreen + * or grabbing input at the time). On mobile devices, your app will likely + * move to the background or your process might be paused. Any given platform + * may or may not handle a given URL. + * + * If this is unimplemented (or simply unavailable) for a platform, this will + * fail with an error. A successful result does not mean the URL loaded, just + * that we launched _something_ to handle it (or at least believe we did). + * + * All this to say: this function can be useful, but you should definitely + * test it on every platform you target. + * + * \param url A valid URL/URI to open. Use `file:///full/path/to/file` for + * local files, if supported. + * \returns 0 on success, or -1 on error; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC int SDLCALL SDL_OpenURL(const char *url); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_misc_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_mouse.h b/third_party/SDL2/include/SDL_mouse.h new file mode 100644 index 00000000000..628b7a2f835 --- /dev/null +++ b/third_party/SDL2/include/SDL_mouse.h @@ -0,0 +1,464 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryMouse + * + * Include file for SDL mouse event handling. + */ + +#ifndef SDL_mouse_h_ +#define SDL_mouse_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct SDL_Cursor SDL_Cursor; /**< Implementation dependent */ + +/** + * Cursor types for SDL_CreateSystemCursor(). + */ +typedef enum SDL_SystemCursor +{ + SDL_SYSTEM_CURSOR_ARROW, /**< Arrow */ + SDL_SYSTEM_CURSOR_IBEAM, /**< I-beam */ + SDL_SYSTEM_CURSOR_WAIT, /**< Wait */ + SDL_SYSTEM_CURSOR_CROSSHAIR, /**< Crosshair */ + SDL_SYSTEM_CURSOR_WAITARROW, /**< Small wait cursor (or Wait if not available) */ + SDL_SYSTEM_CURSOR_SIZENWSE, /**< Double arrow pointing northwest and southeast */ + SDL_SYSTEM_CURSOR_SIZENESW, /**< Double arrow pointing northeast and southwest */ + SDL_SYSTEM_CURSOR_SIZEWE, /**< Double arrow pointing west and east */ + SDL_SYSTEM_CURSOR_SIZENS, /**< Double arrow pointing north and south */ + SDL_SYSTEM_CURSOR_SIZEALL, /**< Four pointed arrow pointing north, south, east, and west */ + SDL_SYSTEM_CURSOR_NO, /**< Slashed circle or crossbones */ + SDL_SYSTEM_CURSOR_HAND, /**< Hand */ + SDL_NUM_SYSTEM_CURSORS +} SDL_SystemCursor; + +/** + * Scroll direction types for the Scroll event + */ +typedef enum SDL_MouseWheelDirection +{ + SDL_MOUSEWHEEL_NORMAL, /**< The scroll direction is normal */ + SDL_MOUSEWHEEL_FLIPPED /**< The scroll direction is flipped / natural */ +} SDL_MouseWheelDirection; + +/* Function prototypes */ + +/** + * Get the window which currently has mouse focus. + * + * \returns the window with mouse focus. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_Window * SDLCALL SDL_GetMouseFocus(void); + +/** + * Retrieve the current state of the mouse. + * + * The current button state is returned as a button bitmask, which can be + * tested using the `SDL_BUTTON(X)` macros (where `X` is generally 1 for the + * left, 2 for middle, 3 for the right button), and `x` and `y` are set to the + * mouse cursor position relative to the focus window. You can pass NULL for + * either `x` or `y`. + * + * \param x the x coordinate of the mouse cursor position relative to the + * focus window. + * \param y the y coordinate of the mouse cursor position relative to the + * focus window. + * \returns a 32-bit button bitmask of the current button state. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetGlobalMouseState + * \sa SDL_GetRelativeMouseState + * \sa SDL_PumpEvents + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetMouseState(int *x, int *y); + +/** + * Get the current state of the mouse in relation to the desktop. + * + * This works similarly to SDL_GetMouseState(), but the coordinates will be + * reported relative to the top-left of the desktop. This can be useful if you + * need to track the mouse outside of a specific window and SDL_CaptureMouse() + * doesn't fit your needs. For example, it could be useful if you need to + * track the mouse while dragging a window, where coordinates relative to a + * window might not be in sync at all times. + * + * Note: SDL_GetMouseState() returns the mouse position as SDL understands it + * from the last pump of the event queue. This function, however, queries the + * OS for the current mouse position, and as such, might be a slightly less + * efficient function. Unless you know what you're doing and have a good + * reason to use this function, you probably want SDL_GetMouseState() instead. + * + * \param x filled in with the current X coord relative to the desktop; can be + * NULL. + * \param y filled in with the current Y coord relative to the desktop; can be + * NULL. + * \returns the current button state as a bitmask which can be tested using + * the SDL_BUTTON(X) macros. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_CaptureMouse + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetGlobalMouseState(int *x, int *y); + +/** + * Retrieve the relative state of the mouse. + * + * The current button state is returned as a button bitmask, which can be + * tested using the `SDL_BUTTON(X)` macros (where `X` is generally 1 for the + * left, 2 for middle, 3 for the right button), and `x` and `y` are set to the + * mouse deltas since the last call to SDL_GetRelativeMouseState() or since + * event initialization. You can pass NULL for either `x` or `y`. + * + * \param x a pointer filled with the last recorded x coordinate of the mouse. + * \param y a pointer filled with the last recorded y coordinate of the mouse. + * \returns a 32-bit button bitmask of the relative button state. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetMouseState + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetRelativeMouseState(int *x, int *y); + +/** + * Move the mouse cursor to the given position within the window. + * + * This function generates a mouse motion event if relative mode is not + * enabled. If relative mode is enabled, you can force mouse events for the + * warp by setting the SDL_HINT_MOUSE_RELATIVE_WARP_MOTION hint. + * + * Note that this function will appear to succeed, but not actually move the + * mouse when used over Microsoft Remote Desktop. + * + * \param window the window to move the mouse into, or NULL for the current + * mouse focus. + * \param x the x coordinate within the window. + * \param y the y coordinate within the window. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WarpMouseGlobal + */ +extern DECLSPEC void SDLCALL SDL_WarpMouseInWindow(SDL_Window * window, + int x, int y); + +/** + * Move the mouse to the given position in global screen space. + * + * This function generates a mouse motion event. + * + * A failure of this function usually means that it is unsupported by a + * platform. + * + * Note that this function will appear to succeed, but not actually move the + * mouse when used over Microsoft Remote Desktop. + * + * \param x the x coordinate. + * \param y the y coordinate. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_WarpMouseInWindow + */ +extern DECLSPEC int SDLCALL SDL_WarpMouseGlobal(int x, int y); + +/** + * Set relative mouse mode. + * + * While the mouse is in relative mode, the cursor is hidden, the mouse + * position is constrained to the window, and SDL will report continuous + * relative mouse motion even if the mouse is at the edge of the window. + * + * This function will flush any pending mouse motion. + * + * \param enabled SDL_TRUE to enable relative mode, SDL_FALSE to disable. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * If relative mode is not supported, this returns -1. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRelativeMouseMode + */ +extern DECLSPEC int SDLCALL SDL_SetRelativeMouseMode(SDL_bool enabled); + +/** + * Capture the mouse and to track input outside an SDL window. + * + * Capturing enables your app to obtain mouse events globally, instead of just + * within your window. Not all video targets support this function. When + * capturing is enabled, the current window will get all mouse events, but + * unlike relative mode, no change is made to the cursor and it is not + * restrained to your window. + * + * This function may also deny mouse input to other windows--both those in + * your application and others on the system--so you should use this function + * sparingly, and in small bursts. For example, you might want to track the + * mouse while the user is dragging something, until the user releases a mouse + * button. It is not recommended that you capture the mouse for long periods + * of time, such as the entire time your app is running. For that, you should + * probably use SDL_SetRelativeMouseMode() or SDL_SetWindowGrab(), depending + * on your goals. + * + * While captured, mouse events still report coordinates relative to the + * current (foreground) window, but those coordinates may be outside the + * bounds of the window (including negative values). Capturing is only allowed + * for the foreground window. If the window loses focus while capturing, the + * capture will be disabled automatically. + * + * While capturing is enabled, the current window will have the + * `SDL_WINDOW_MOUSE_CAPTURE` flag set. + * + * Please note that as of SDL 2.0.22, SDL will attempt to "auto capture" the + * mouse while the user is pressing a button; this is to try and make mouse + * behavior more consistent between platforms, and deal with the common case + * of a user dragging the mouse outside of the window. This means that if you + * are calling SDL_CaptureMouse() only to deal with this situation, you no + * longer have to (although it is safe to do so). If this causes problems for + * your app, you can disable auto capture by setting the + * `SDL_HINT_MOUSE_AUTO_CAPTURE` hint to zero. + * + * \param enabled SDL_TRUE to enable capturing, SDL_FALSE to disable. + * \returns 0 on success or -1 if not supported; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_GetGlobalMouseState + */ +extern DECLSPEC int SDLCALL SDL_CaptureMouse(SDL_bool enabled); + +/** + * Query whether relative mouse mode is enabled. + * + * \returns SDL_TRUE if relative mode is enabled or SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetRelativeMouseMode + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GetRelativeMouseMode(void); + +/** + * Create a cursor using the specified bitmap data and mask (in MSB format). + * + * `mask` has to be in MSB (Most Significant Bit) format. + * + * The cursor width (`w`) must be a multiple of 8 bits. + * + * The cursor is created in black and white according to the following: + * + * - data=0, mask=1: white + * - data=1, mask=1: black + * - data=0, mask=0: transparent + * - data=1, mask=0: inverted color if possible, black if not. + * + * Cursors created with this function must be freed with SDL_FreeCursor(). + * + * If you want to have a color cursor, or create your cursor from an + * SDL_Surface, you should use SDL_CreateColorCursor(). Alternately, you can + * hide the cursor and draw your own as part of your game's rendering, but it + * will be bound to the framerate. + * + * Also, since SDL 2.0.0, SDL_CreateSystemCursor() is available, which + * provides twelve readily available system cursors to pick from. + * + * \param data the color value for each pixel of the cursor. + * \param mask the mask value for each pixel of the cursor. + * \param w the width of the cursor. + * \param h the height of the cursor. + * \param hot_x the X-axis location of the upper left corner of the cursor + * relative to the actual mouse position. + * \param hot_y the Y-axis location of the upper left corner of the cursor + * relative to the actual mouse position. + * \returns a new cursor with the specified parameters on success or NULL on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FreeCursor + * \sa SDL_SetCursor + * \sa SDL_ShowCursor + */ +extern DECLSPEC SDL_Cursor *SDLCALL SDL_CreateCursor(const Uint8 * data, + const Uint8 * mask, + int w, int h, int hot_x, + int hot_y); + +/** + * Create a color cursor. + * + * \param surface an SDL_Surface structure representing the cursor image. + * \param hot_x the x position of the cursor hot spot. + * \param hot_y the y position of the cursor hot spot. + * \returns the new cursor on success or NULL on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateCursor + * \sa SDL_FreeCursor + */ +extern DECLSPEC SDL_Cursor *SDLCALL SDL_CreateColorCursor(SDL_Surface *surface, + int hot_x, + int hot_y); + +/** + * Create a system cursor. + * + * \param id an SDL_SystemCursor enum value. + * \returns a cursor on success or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FreeCursor + */ +extern DECLSPEC SDL_Cursor *SDLCALL SDL_CreateSystemCursor(SDL_SystemCursor id); + +/** + * Set the active cursor. + * + * This function sets the currently active cursor to the specified one. If the + * cursor is currently visible, the change will be immediately represented on + * the display. SDL_SetCursor(NULL) can be used to force cursor redraw, if + * this is desired for any reason. + * + * \param cursor a cursor to make active. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateCursor + * \sa SDL_GetCursor + * \sa SDL_ShowCursor + */ +extern DECLSPEC void SDLCALL SDL_SetCursor(SDL_Cursor * cursor); + +/** + * Get the active cursor. + * + * This function returns a pointer to the current cursor which is owned by the + * library. It is not necessary to free the cursor with SDL_FreeCursor(). + * + * \returns the active cursor or NULL if there is no mouse. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetCursor + */ +extern DECLSPEC SDL_Cursor *SDLCALL SDL_GetCursor(void); + +/** + * Get the default cursor. + * + * You do not have to call SDL_FreeCursor() on the return value, but it is + * safe to do so. + * + * \returns the default cursor on success or NULL on failure. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateSystemCursor + */ +extern DECLSPEC SDL_Cursor *SDLCALL SDL_GetDefaultCursor(void); + +/** + * Free a previously-created cursor. + * + * Use this function to free cursor resources created with SDL_CreateCursor(), + * SDL_CreateColorCursor() or SDL_CreateSystemCursor(). + * + * \param cursor the cursor to free. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateColorCursor + * \sa SDL_CreateCursor + * \sa SDL_CreateSystemCursor + */ +extern DECLSPEC void SDLCALL SDL_FreeCursor(SDL_Cursor * cursor); + +/** + * Toggle whether or not the cursor is shown. + * + * The cursor starts off displayed but can be turned off. Passing `SDL_ENABLE` + * displays the cursor and passing `SDL_DISABLE` hides it. + * + * The current state of the mouse cursor can be queried by passing + * `SDL_QUERY`; either `SDL_DISABLE` or `SDL_ENABLE` will be returned. + * + * \param toggle `SDL_ENABLE` to show the cursor, `SDL_DISABLE` to hide it, + * `SDL_QUERY` to query the current state without changing it. + * \returns `SDL_ENABLE` if the cursor is shown, or `SDL_DISABLE` if the + * cursor is hidden, or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateCursor + * \sa SDL_SetCursor + */ +extern DECLSPEC int SDLCALL SDL_ShowCursor(int toggle); + +/** + * Used as a mask when testing buttons in buttonstate. + * + * - Button 1: Left mouse button + * - Button 2: Middle mouse button + * - Button 3: Right mouse button + */ +#define SDL_BUTTON(X) (1 << ((X)-1)) +#define SDL_BUTTON_LEFT 1 +#define SDL_BUTTON_MIDDLE 2 +#define SDL_BUTTON_RIGHT 3 +#define SDL_BUTTON_X1 4 +#define SDL_BUTTON_X2 5 +#define SDL_BUTTON_LMASK SDL_BUTTON(SDL_BUTTON_LEFT) +#define SDL_BUTTON_MMASK SDL_BUTTON(SDL_BUTTON_MIDDLE) +#define SDL_BUTTON_RMASK SDL_BUTTON(SDL_BUTTON_RIGHT) +#define SDL_BUTTON_X1MASK SDL_BUTTON(SDL_BUTTON_X1) +#define SDL_BUTTON_X2MASK SDL_BUTTON(SDL_BUTTON_X2) + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_mouse_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_mutex.h b/third_party/SDL2/include/SDL_mutex.h new file mode 100644 index 00000000000..0fe3eb5a5f8 --- /dev/null +++ b/third_party/SDL2/include/SDL_mutex.h @@ -0,0 +1,545 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_mutex_h_ +#define SDL_mutex_h_ + +/** + * # CategoryMutex + * + * Functions to provide thread synchronization primitives. + */ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +/******************************************************************************/ +/* Enable thread safety attributes only with clang. + * The attributes can be safely erased when compiling with other compilers. + */ +#if defined(SDL_THREAD_SAFETY_ANALYSIS) && \ + defined(__clang__) && (!defined(SWIG)) +#define SDL_THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) +#else +#define SDL_THREAD_ANNOTATION_ATTRIBUTE__(x) /* no-op */ +#endif + +#define SDL_CAPABILITY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(capability(x)) + +#define SDL_SCOPED_CAPABILITY \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) + +#define SDL_GUARDED_BY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) + +#define SDL_PT_GUARDED_BY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) + +#define SDL_ACQUIRED_BEFORE(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(x)) + +#define SDL_ACQUIRED_AFTER(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(x)) + +#define SDL_REQUIRES(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(x)) + +#define SDL_REQUIRES_SHARED(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(x)) + +#define SDL_ACQUIRE(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(x)) + +#define SDL_ACQUIRE_SHARED(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(x)) + +#define SDL_RELEASE(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(release_capability(x)) + +#define SDL_RELEASE_SHARED(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(x)) + +#define SDL_RELEASE_GENERIC(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(release_generic_capability(x)) + +#define SDL_TRY_ACQUIRE(x, y) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(x, y)) + +#define SDL_TRY_ACQUIRE_SHARED(x, y) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(x, y)) + +#define SDL_EXCLUDES(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(x)) + +#define SDL_ASSERT_CAPABILITY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x)) + +#define SDL_ASSERT_SHARED_CAPABILITY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x)) + +#define SDL_RETURN_CAPABILITY(x) \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) + +#define SDL_NO_THREAD_SAFETY_ANALYSIS \ + SDL_THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) + +/******************************************************************************/ + + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Synchronization functions which can time out return this value if they time + * out. + */ +#define SDL_MUTEX_TIMEDOUT 1 + +/** + * This is the timeout value which corresponds to never time out. + */ +#define SDL_MUTEX_MAXWAIT (~(Uint32)0) + + +/** + * \name Mutex functions + */ +/* @{ */ + +/* The SDL mutex structure, defined in SDL_sysmutex.c */ +struct SDL_mutex; +typedef struct SDL_mutex SDL_mutex; + +/** + * Create a new mutex. + * + * All newly-created mutexes begin in the _unlocked_ state. + * + * Calls to SDL_LockMutex() will not return while the mutex is locked by + * another thread. See SDL_TryLockMutex() to attempt to lock without blocking. + * + * SDL mutexes are reentrant. + * + * \returns the initialized and unlocked mutex or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_DestroyMutex + * \sa SDL_LockMutex + * \sa SDL_TryLockMutex + * \sa SDL_UnlockMutex + */ +extern DECLSPEC SDL_mutex *SDLCALL SDL_CreateMutex(void); + +/** + * Lock the mutex. + * + * This will block until the mutex is available, which is to say it is in the + * unlocked state and the OS has chosen the caller as the next thread to lock + * it. Of all threads waiting to lock the mutex, only one may do so at a time. + * + * It is legal for the owning thread to lock an already-locked mutex. It must + * unlock it the same number of times before it is actually made available for + * other threads in the system (this is known as a "recursive mutex"). + * + * \param mutex the mutex to lock. + * \return 0, or -1 on error. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_LockMutex(SDL_mutex * mutex) SDL_ACQUIRE(mutex); +#define SDL_mutexP(m) SDL_LockMutex(m) + +/** + * Try to lock a mutex without blocking. + * + * This works just like SDL_LockMutex(), but if the mutex is not available, + * this function returns `SDL_MUTEX_TIMEOUT` immediately. + * + * This technique is useful if you need exclusive access to a resource but + * don't want to wait for it, and will return to it to try again later. + * + * \param mutex the mutex to try to lock. + * \returns 0, `SDL_MUTEX_TIMEDOUT`, or -1 on error; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateMutex + * \sa SDL_DestroyMutex + * \sa SDL_LockMutex + * \sa SDL_UnlockMutex + */ +extern DECLSPEC int SDLCALL SDL_TryLockMutex(SDL_mutex * mutex) SDL_TRY_ACQUIRE(0, mutex); + +/** + * Unlock the mutex. + * + * It is legal for the owning thread to lock an already-locked mutex. It must + * unlock it the same number of times before it is actually made available for + * other threads in the system (this is known as a "recursive mutex"). + * + * It is an error to unlock a mutex that has not been locked by the current + * thread, and doing so results in undefined behavior. + * + * It is also an error to unlock a mutex that isn't locked at all. + * + * \param mutex the mutex to unlock. + * \returns 0, or -1 on error. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_UnlockMutex(SDL_mutex * mutex) SDL_RELEASE(mutex); +#define SDL_mutexV(m) SDL_UnlockMutex(m) + +/** + * Destroy a mutex created with SDL_CreateMutex(). + * + * This function must be called on any mutex that is no longer needed. Failure + * to destroy a mutex will result in a system memory or resource leak. While + * it is safe to destroy a mutex that is _unlocked_, it is not safe to attempt + * to destroy a locked mutex, and may result in undefined behavior depending + * on the platform. + * + * \param mutex the mutex to destroy. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateMutex + * \sa SDL_LockMutex + * \sa SDL_TryLockMutex + * \sa SDL_UnlockMutex + */ +extern DECLSPEC void SDLCALL SDL_DestroyMutex(SDL_mutex * mutex); + +/* @} *//* Mutex functions */ + + +/** + * \name Semaphore functions + */ +/* @{ */ + +/* The SDL semaphore structure, defined in SDL_syssem.c */ +struct SDL_semaphore; +typedef struct SDL_semaphore SDL_sem; + +/** + * Create a semaphore. + * + * This function creates a new semaphore and initializes it with the value + * `initial_value`. Each wait operation on the semaphore will atomically + * decrement the semaphore value and potentially block if the semaphore value + * is 0. Each post operation will atomically increment the semaphore value and + * wake waiting threads and allow them to retry the wait operation. + * + * \param initial_value the starting value of the semaphore. + * \returns a new semaphore or NULL on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_DestroySemaphore + * \sa SDL_SemPost + * \sa SDL_SemTryWait + * \sa SDL_SemValue + * \sa SDL_SemWait + * \sa SDL_SemWaitTimeout + */ +extern DECLSPEC SDL_sem *SDLCALL SDL_CreateSemaphore(Uint32 initial_value); + +/** + * Destroy a semaphore. + * + * It is not safe to destroy a semaphore if there are threads currently + * waiting on it. + * + * \param sem the semaphore to destroy. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateSemaphore + * \sa SDL_SemPost + * \sa SDL_SemTryWait + * \sa SDL_SemValue + * \sa SDL_SemWait + * \sa SDL_SemWaitTimeout + */ +extern DECLSPEC void SDLCALL SDL_DestroySemaphore(SDL_sem * sem); + +/** + * Wait until a semaphore has a positive value and then decrements it. + * + * This function suspends the calling thread until either the semaphore + * pointed to by `sem` has a positive value or the call is interrupted by a + * signal or error. If the call is successful it will atomically decrement the + * semaphore value. + * + * This function is the equivalent of calling SDL_SemWaitTimeout() with a time + * length of `SDL_MUTEX_MAXWAIT`. + * + * \param sem the semaphore wait on. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateSemaphore + * \sa SDL_DestroySemaphore + * \sa SDL_SemPost + * \sa SDL_SemTryWait + * \sa SDL_SemValue + * \sa SDL_SemWait + * \sa SDL_SemWaitTimeout + */ +extern DECLSPEC int SDLCALL SDL_SemWait(SDL_sem * sem); + +/** + * See if a semaphore has a positive value and decrement it if it does. + * + * This function checks to see if the semaphore pointed to by `sem` has a + * positive value and atomically decrements the semaphore value if it does. If + * the semaphore doesn't have a positive value, the function immediately + * returns SDL_MUTEX_TIMEDOUT. + * + * \param sem the semaphore to wait on. + * \returns 0 if the wait succeeds, `SDL_MUTEX_TIMEDOUT` if the wait would + * block, or a negative error code on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateSemaphore + * \sa SDL_DestroySemaphore + * \sa SDL_SemPost + * \sa SDL_SemValue + * \sa SDL_SemWait + * \sa SDL_SemWaitTimeout + */ +extern DECLSPEC int SDLCALL SDL_SemTryWait(SDL_sem * sem); + +/** + * Wait until a semaphore has a positive value and then decrements it. + * + * This function suspends the calling thread until either the semaphore + * pointed to by `sem` has a positive value, the call is interrupted by a + * signal or error, or the specified time has elapsed. If the call is + * successful it will atomically decrement the semaphore value. + * + * \param sem the semaphore to wait on. + * \param timeout the length of the timeout, in milliseconds. + * \returns 0 if the wait succeeds, `SDL_MUTEX_TIMEDOUT` if the wait does not + * succeed in the allotted time, or a negative error code on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateSemaphore + * \sa SDL_DestroySemaphore + * \sa SDL_SemPost + * \sa SDL_SemTryWait + * \sa SDL_SemValue + * \sa SDL_SemWait + */ +extern DECLSPEC int SDLCALL SDL_SemWaitTimeout(SDL_sem *sem, Uint32 timeout); + +/** + * Atomically increment a semaphore's value and wake waiting threads. + * + * \param sem the semaphore to increment. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateSemaphore + * \sa SDL_DestroySemaphore + * \sa SDL_SemTryWait + * \sa SDL_SemValue + * \sa SDL_SemWait + * \sa SDL_SemWaitTimeout + */ +extern DECLSPEC int SDLCALL SDL_SemPost(SDL_sem * sem); + +/** + * Get the current value of a semaphore. + * + * \param sem the semaphore to query. + * \returns the current value of the semaphore. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateSemaphore + */ +extern DECLSPEC Uint32 SDLCALL SDL_SemValue(SDL_sem * sem); + +/* @} *//* Semaphore functions */ + + +/** + * \name Condition variable functions + */ +/* @{ */ + +/* The SDL condition variable structure, defined in SDL_syscond.c */ +struct SDL_cond; +typedef struct SDL_cond SDL_cond; + +/** + * Create a condition variable. + * + * \returns a new condition variable or NULL on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CondBroadcast + * \sa SDL_CondSignal + * \sa SDL_CondWait + * \sa SDL_CondWaitTimeout + * \sa SDL_DestroyCond + */ +extern DECLSPEC SDL_cond *SDLCALL SDL_CreateCond(void); + +/** + * Destroy a condition variable. + * + * \param cond the condition variable to destroy. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CondBroadcast + * \sa SDL_CondSignal + * \sa SDL_CondWait + * \sa SDL_CondWaitTimeout + * \sa SDL_CreateCond + */ +extern DECLSPEC void SDLCALL SDL_DestroyCond(SDL_cond * cond); + +/** + * Restart one of the threads that are waiting on the condition variable. + * + * \param cond the condition variable to signal. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CondBroadcast + * \sa SDL_CondWait + * \sa SDL_CondWaitTimeout + * \sa SDL_CreateCond + * \sa SDL_DestroyCond + */ +extern DECLSPEC int SDLCALL SDL_CondSignal(SDL_cond * cond); + +/** + * Restart all threads that are waiting on the condition variable. + * + * \param cond the condition variable to signal. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CondSignal + * \sa SDL_CondWait + * \sa SDL_CondWaitTimeout + * \sa SDL_CreateCond + * \sa SDL_DestroyCond + */ +extern DECLSPEC int SDLCALL SDL_CondBroadcast(SDL_cond * cond); + +/** + * Wait until a condition variable is signaled. + * + * This function unlocks the specified `mutex` and waits for another thread to + * call SDL_CondSignal() or SDL_CondBroadcast() on the condition variable + * `cond`. Once the condition variable is signaled, the mutex is re-locked and + * the function returns. + * + * The mutex must be locked before calling this function. + * + * This function is the equivalent of calling SDL_CondWaitTimeout() with a + * time length of `SDL_MUTEX_MAXWAIT`. + * + * \param cond the condition variable to wait on. + * \param mutex the mutex used to coordinate thread access. + * \returns 0 when it is signaled or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CondBroadcast + * \sa SDL_CondSignal + * \sa SDL_CondWaitTimeout + * \sa SDL_CreateCond + * \sa SDL_DestroyCond + */ +extern DECLSPEC int SDLCALL SDL_CondWait(SDL_cond * cond, SDL_mutex * mutex); + +/** + * Wait until a condition variable is signaled or a certain time has passed. + * + * This function unlocks the specified `mutex` and waits for another thread to + * call SDL_CondSignal() or SDL_CondBroadcast() on the condition variable + * `cond`, or for the specified time to elapse. Once the condition variable is + * signaled or the time elapsed, the mutex is re-locked and the function + * returns. + * + * The mutex must be locked before calling this function. + * + * \param cond the condition variable to wait on. + * \param mutex the mutex used to coordinate thread access. + * \param ms the maximum time to wait, in milliseconds, or `SDL_MUTEX_MAXWAIT` + * to wait indefinitely. + * \returns 0 if the condition variable is signaled, `SDL_MUTEX_TIMEDOUT` if + * the condition is not signaled in the allotted time, or a negative + * error code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CondBroadcast + * \sa SDL_CondSignal + * \sa SDL_CondWait + * \sa SDL_CreateCond + * \sa SDL_DestroyCond + */ +extern DECLSPEC int SDLCALL SDL_CondWaitTimeout(SDL_cond * cond, + SDL_mutex * mutex, Uint32 ms); + +/* @} *//* Condition variable functions */ + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_mutex_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_name.h b/third_party/SDL2/include/SDL_name.h new file mode 100644 index 00000000000..0c48bcf315a --- /dev/null +++ b/third_party/SDL2/include/SDL_name.h @@ -0,0 +1,33 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDLname_h_ +#define SDLname_h_ + +#if defined(__STDC__) || defined(__cplusplus) +#define NeedFunctionPrototypes 1 +#endif + +#define SDL_NAME(X) SDL_##X + +#endif /* SDLname_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_opengl.h b/third_party/SDL2/include/SDL_opengl.h new file mode 100644 index 00000000000..c6250d131b7 --- /dev/null +++ b/third_party/SDL2/include/SDL_opengl.h @@ -0,0 +1,2126 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * This is a simple file to encapsulate the OpenGL API headers. + * + * Define NO_SDL_GLEXT if you have your own version of glext.h and want + * to disable the version included in SDL_opengl.h. + */ + +#ifndef SDL_opengl_h_ +#define SDL_opengl_h_ + +#include "SDL_config.h" + +#ifndef __IPHONEOS__ /* No OpenGL on iOS. */ + +/* + * Mesa 3-D graphics library + * + * Copyright (C) 1999-2006 Brian Paul All Rights Reserved. + * Copyright (C) 2009 VMware, Inc. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef __gl_h_ +#define __gl_h_ + +#if defined(USE_MGL_NAMESPACE) +#include "gl_mangle.h" +#endif + + +/********************************************************************** + * Begin system-specific stuff. + */ + +#if defined(_WIN32) && !defined(__WIN32__) && !defined(__CYGWIN__) +#define __WIN32__ +#endif + +#if defined(__WIN32__) && !defined(__CYGWIN__) +# if (defined(_MSC_VER) || defined(__MINGW32__)) && defined(BUILD_GL32) /* tag specify we're building mesa as a DLL */ +# define GLAPI __declspec(dllexport) +# elif (defined(_MSC_VER) || defined(__MINGW32__)) && defined(_DLL) /* tag specifying we're building for DLL runtime support */ +# define GLAPI __declspec(dllimport) +# else /* for use with static link lib build of Win32 edition only */ +# define GLAPI extern +# endif /* _STATIC_MESA support */ +# if defined(__MINGW32__) && defined(GL_NO_STDCALL) || defined(UNDER_CE) /* The generated DLLs by MingW with STDCALL are not compatible with the ones done by Microsoft's compilers */ +# define GLAPIENTRY +# else +# define GLAPIENTRY __stdcall +# endif +#elif defined(__CYGWIN__) && defined(USE_OPENGL32) /* use native windows opengl32 */ +# define GLAPI extern +# define GLAPIENTRY __stdcall +#elif defined(__OS2__) || defined(__EMX__) /* native os/2 opengl */ +# define GLAPI extern +# define GLAPIENTRY _System +# define APIENTRY _System +# if defined(__GNUC__) && !defined(_System) +# define _System +# endif +#elif (defined(__GNUC__) && __GNUC__ >= 4) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590)) +# define GLAPI __attribute__((visibility("default"))) +# define GLAPIENTRY +#endif /* WIN32 && !CYGWIN */ + +/* + * WINDOWS: Include windows.h here to define APIENTRY. + * It is also useful when applications include this file by + * including only glut.h, since glut.h depends on windows.h. + * Applications needing to include windows.h with parms other + * than "WIN32_LEAN_AND_MEAN" may include windows.h before + * glut.h or gl.h. + */ +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#ifndef NOMINMAX /* don't define min() and max(). */ +#define NOMINMAX +#endif +#include +#endif + +#ifndef GLAPI +#define GLAPI extern +#endif + +#ifndef GLAPIENTRY +#define GLAPIENTRY +#endif + +#ifndef APIENTRY +#define APIENTRY GLAPIENTRY +#endif + +/* "P" suffix to be used for a pointer to a function */ +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif + +#ifndef GLAPIENTRYP +#define GLAPIENTRYP GLAPIENTRY * +#endif + +#if defined(PRAGMA_EXPORT_SUPPORTED) +#pragma export on +#endif + +/* + * End system-specific stuff. + **********************************************************************/ + + + +#ifdef __cplusplus +extern "C" { +#endif + + + +#define GL_VERSION_1_1 1 +#define GL_VERSION_1_2 1 +#define GL_VERSION_1_3 1 +#define GL_ARB_imaging 1 + + +/* + * Datatypes + */ +typedef unsigned int GLenum; +typedef unsigned char GLboolean; +typedef unsigned int GLbitfield; +typedef void GLvoid; +typedef signed char GLbyte; /* 1-byte signed */ +typedef short GLshort; /* 2-byte signed */ +typedef int GLint; /* 4-byte signed */ +typedef unsigned char GLubyte; /* 1-byte unsigned */ +typedef unsigned short GLushort; /* 2-byte unsigned */ +typedef unsigned int GLuint; /* 4-byte unsigned */ +typedef int GLsizei; /* 4-byte signed */ +typedef float GLfloat; /* single precision float */ +typedef float GLclampf; /* single precision float in [0,1] */ +typedef double GLdouble; /* double precision float */ +typedef double GLclampd; /* double precision float in [0,1] */ + + + +/* + * Constants + */ + +/* Boolean values */ +#define GL_FALSE 0 +#define GL_TRUE 1 + +/* Data types */ +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_INT 0x1404 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_2_BYTES 0x1407 +#define GL_3_BYTES 0x1408 +#define GL_4_BYTES 0x1409 +#define GL_DOUBLE 0x140A + +/* Primitives */ +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 +#define GL_QUADS 0x0007 +#define GL_QUAD_STRIP 0x0008 +#define GL_POLYGON 0x0009 + +/* Vertex Arrays */ +#define GL_VERTEX_ARRAY 0x8074 +#define GL_NORMAL_ARRAY 0x8075 +#define GL_COLOR_ARRAY 0x8076 +#define GL_INDEX_ARRAY 0x8077 +#define GL_TEXTURE_COORD_ARRAY 0x8078 +#define GL_EDGE_FLAG_ARRAY 0x8079 +#define GL_VERTEX_ARRAY_SIZE 0x807A +#define GL_VERTEX_ARRAY_TYPE 0x807B +#define GL_VERTEX_ARRAY_STRIDE 0x807C +#define GL_NORMAL_ARRAY_TYPE 0x807E +#define GL_NORMAL_ARRAY_STRIDE 0x807F +#define GL_COLOR_ARRAY_SIZE 0x8081 +#define GL_COLOR_ARRAY_TYPE 0x8082 +#define GL_COLOR_ARRAY_STRIDE 0x8083 +#define GL_INDEX_ARRAY_TYPE 0x8085 +#define GL_INDEX_ARRAY_STRIDE 0x8086 +#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A +#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C +#define GL_VERTEX_ARRAY_POINTER 0x808E +#define GL_NORMAL_ARRAY_POINTER 0x808F +#define GL_COLOR_ARRAY_POINTER 0x8090 +#define GL_INDEX_ARRAY_POINTER 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 +#define GL_V2F 0x2A20 +#define GL_V3F 0x2A21 +#define GL_C4UB_V2F 0x2A22 +#define GL_C4UB_V3F 0x2A23 +#define GL_C3F_V3F 0x2A24 +#define GL_N3F_V3F 0x2A25 +#define GL_C4F_N3F_V3F 0x2A26 +#define GL_T2F_V3F 0x2A27 +#define GL_T4F_V4F 0x2A28 +#define GL_T2F_C4UB_V3F 0x2A29 +#define GL_T2F_C3F_V3F 0x2A2A +#define GL_T2F_N3F_V3F 0x2A2B +#define GL_T2F_C4F_N3F_V3F 0x2A2C +#define GL_T4F_C4F_N3F_V4F 0x2A2D + +/* Matrix Mode */ +#define GL_MATRIX_MODE 0x0BA0 +#define GL_MODELVIEW 0x1700 +#define GL_PROJECTION 0x1701 +#define GL_TEXTURE 0x1702 + +/* Points */ +#define GL_POINT_SMOOTH 0x0B10 +#define GL_POINT_SIZE 0x0B11 +#define GL_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_POINT_SIZE_RANGE 0x0B12 + +/* Lines */ +#define GL_LINE_SMOOTH 0x0B20 +#define GL_LINE_STIPPLE 0x0B24 +#define GL_LINE_STIPPLE_PATTERN 0x0B25 +#define GL_LINE_STIPPLE_REPEAT 0x0B26 +#define GL_LINE_WIDTH 0x0B21 +#define GL_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_LINE_WIDTH_RANGE 0x0B22 + +/* Polygons */ +#define GL_POINT 0x1B00 +#define GL_LINE 0x1B01 +#define GL_FILL 0x1B02 +#define GL_CW 0x0900 +#define GL_CCW 0x0901 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_POLYGON_MODE 0x0B40 +#define GL_POLYGON_SMOOTH 0x0B41 +#define GL_POLYGON_STIPPLE 0x0B42 +#define GL_EDGE_FLAG 0x0B43 +#define GL_CULL_FACE 0x0B44 +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_OFFSET_POINT 0x2A01 +#define GL_POLYGON_OFFSET_LINE 0x2A02 +#define GL_POLYGON_OFFSET_FILL 0x8037 + +/* Display Lists */ +#define GL_COMPILE 0x1300 +#define GL_COMPILE_AND_EXECUTE 0x1301 +#define GL_LIST_BASE 0x0B32 +#define GL_LIST_INDEX 0x0B33 +#define GL_LIST_MODE 0x0B30 + +/* Depth buffer */ +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 +#define GL_DEPTH_TEST 0x0B71 +#define GL_DEPTH_BITS 0x0D56 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_COMPONENT 0x1902 + +/* Lighting */ +#define GL_LIGHTING 0x0B50 +#define GL_LIGHT0 0x4000 +#define GL_LIGHT1 0x4001 +#define GL_LIGHT2 0x4002 +#define GL_LIGHT3 0x4003 +#define GL_LIGHT4 0x4004 +#define GL_LIGHT5 0x4005 +#define GL_LIGHT6 0x4006 +#define GL_LIGHT7 0x4007 +#define GL_SPOT_EXPONENT 0x1205 +#define GL_SPOT_CUTOFF 0x1206 +#define GL_CONSTANT_ATTENUATION 0x1207 +#define GL_LINEAR_ATTENUATION 0x1208 +#define GL_QUADRATIC_ATTENUATION 0x1209 +#define GL_AMBIENT 0x1200 +#define GL_DIFFUSE 0x1201 +#define GL_SPECULAR 0x1202 +#define GL_SHININESS 0x1601 +#define GL_EMISSION 0x1600 +#define GL_POSITION 0x1203 +#define GL_SPOT_DIRECTION 0x1204 +#define GL_AMBIENT_AND_DIFFUSE 0x1602 +#define GL_COLOR_INDEXES 0x1603 +#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 +#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 +#define GL_LIGHT_MODEL_AMBIENT 0x0B53 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_SHADE_MODEL 0x0B54 +#define GL_FLAT 0x1D00 +#define GL_SMOOTH 0x1D01 +#define GL_COLOR_MATERIAL 0x0B57 +#define GL_COLOR_MATERIAL_FACE 0x0B55 +#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 +#define GL_NORMALIZE 0x0BA1 + +/* User clipping planes */ +#define GL_CLIP_PLANE0 0x3000 +#define GL_CLIP_PLANE1 0x3001 +#define GL_CLIP_PLANE2 0x3002 +#define GL_CLIP_PLANE3 0x3003 +#define GL_CLIP_PLANE4 0x3004 +#define GL_CLIP_PLANE5 0x3005 + +/* Accumulation buffer */ +#define GL_ACCUM_RED_BITS 0x0D58 +#define GL_ACCUM_GREEN_BITS 0x0D59 +#define GL_ACCUM_BLUE_BITS 0x0D5A +#define GL_ACCUM_ALPHA_BITS 0x0D5B +#define GL_ACCUM_CLEAR_VALUE 0x0B80 +#define GL_ACCUM 0x0100 +#define GL_ADD 0x0104 +#define GL_LOAD 0x0101 +#define GL_MULT 0x0103 +#define GL_RETURN 0x0102 + +/* Alpha testing */ +#define GL_ALPHA_TEST 0x0BC0 +#define GL_ALPHA_TEST_REF 0x0BC2 +#define GL_ALPHA_TEST_FUNC 0x0BC1 + +/* Blending */ +#define GL_BLEND 0x0BE2 +#define GL_BLEND_SRC 0x0BE1 +#define GL_BLEND_DST 0x0BE0 +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 + +/* Render Mode */ +#define GL_FEEDBACK 0x1C01 +#define GL_RENDER 0x1C00 +#define GL_SELECT 0x1C02 + +/* Feedback */ +#define GL_2D 0x0600 +#define GL_3D 0x0601 +#define GL_3D_COLOR 0x0602 +#define GL_3D_COLOR_TEXTURE 0x0603 +#define GL_4D_COLOR_TEXTURE 0x0604 +#define GL_POINT_TOKEN 0x0701 +#define GL_LINE_TOKEN 0x0702 +#define GL_LINE_RESET_TOKEN 0x0707 +#define GL_POLYGON_TOKEN 0x0703 +#define GL_BITMAP_TOKEN 0x0704 +#define GL_DRAW_PIXEL_TOKEN 0x0705 +#define GL_COPY_PIXEL_TOKEN 0x0706 +#define GL_PASS_THROUGH_TOKEN 0x0700 +#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 +#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 +#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 + +/* Selection */ +#define GL_SELECTION_BUFFER_POINTER 0x0DF3 +#define GL_SELECTION_BUFFER_SIZE 0x0DF4 + +/* Fog */ +#define GL_FOG 0x0B60 +#define GL_FOG_MODE 0x0B65 +#define GL_FOG_DENSITY 0x0B62 +#define GL_FOG_COLOR 0x0B66 +#define GL_FOG_INDEX 0x0B61 +#define GL_FOG_START 0x0B63 +#define GL_FOG_END 0x0B64 +#define GL_LINEAR 0x2601 +#define GL_EXP 0x0800 +#define GL_EXP2 0x0801 + +/* Logic Ops */ +#define GL_LOGIC_OP 0x0BF1 +#define GL_INDEX_LOGIC_OP 0x0BF1 +#define GL_COLOR_LOGIC_OP 0x0BF2 +#define GL_LOGIC_OP_MODE 0x0BF0 +#define GL_CLEAR 0x1500 +#define GL_SET 0x150F +#define GL_COPY 0x1503 +#define GL_COPY_INVERTED 0x150C +#define GL_NOOP 0x1505 +#define GL_INVERT 0x150A +#define GL_AND 0x1501 +#define GL_NAND 0x150E +#define GL_OR 0x1507 +#define GL_NOR 0x1508 +#define GL_XOR 0x1506 +#define GL_EQUIV 0x1509 +#define GL_AND_REVERSE 0x1502 +#define GL_AND_INVERTED 0x1504 +#define GL_OR_REVERSE 0x150B +#define GL_OR_INVERTED 0x150D + +/* Stencil */ +#define GL_STENCIL_BITS 0x0D57 +#define GL_STENCIL_TEST 0x0B90 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_STENCIL_INDEX 0x1901 +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 + +/* Buffers, Pixel Drawing/Reading */ +#define GL_NONE 0 +#define GL_LEFT 0x0406 +#define GL_RIGHT 0x0407 +/*GL_FRONT 0x0404 */ +/*GL_BACK 0x0405 */ +/*GL_FRONT_AND_BACK 0x0408 */ +#define GL_FRONT_LEFT 0x0400 +#define GL_FRONT_RIGHT 0x0401 +#define GL_BACK_LEFT 0x0402 +#define GL_BACK_RIGHT 0x0403 +#define GL_AUX0 0x0409 +#define GL_AUX1 0x040A +#define GL_AUX2 0x040B +#define GL_AUX3 0x040C +#define GL_COLOR_INDEX 0x1900 +#define GL_RED 0x1903 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_ALPHA 0x1906 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE_ALPHA 0x190A +#define GL_ALPHA_BITS 0x0D55 +#define GL_RED_BITS 0x0D52 +#define GL_GREEN_BITS 0x0D53 +#define GL_BLUE_BITS 0x0D54 +#define GL_INDEX_BITS 0x0D51 +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_AUX_BUFFERS 0x0C00 +#define GL_READ_BUFFER 0x0C02 +#define GL_DRAW_BUFFER 0x0C01 +#define GL_DOUBLEBUFFER 0x0C32 +#define GL_STEREO 0x0C33 +#define GL_BITMAP 0x1A00 +#define GL_COLOR 0x1800 +#define GL_DEPTH 0x1801 +#define GL_STENCIL 0x1802 +#define GL_DITHER 0x0BD0 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 + +/* Implementation limits */ +#define GL_MAX_LIST_NESTING 0x0B31 +#define GL_MAX_EVAL_ORDER 0x0D30 +#define GL_MAX_LIGHTS 0x0D31 +#define GL_MAX_CLIP_PLANES 0x0D32 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 +#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 +#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 +#define GL_MAX_NAME_STACK_DEPTH 0x0D37 +#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 +#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B + +/* Gets */ +#define GL_ATTRIB_STACK_DEPTH 0x0BB0 +#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_CURRENT_INDEX 0x0B01 +#define GL_CURRENT_COLOR 0x0B00 +#define GL_CURRENT_NORMAL 0x0B02 +#define GL_CURRENT_RASTER_COLOR 0x0B04 +#define GL_CURRENT_RASTER_DISTANCE 0x0B09 +#define GL_CURRENT_RASTER_INDEX 0x0B05 +#define GL_CURRENT_RASTER_POSITION 0x0B07 +#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 +#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 +#define GL_CURRENT_TEXTURE_COORDS 0x0B03 +#define GL_INDEX_CLEAR_VALUE 0x0C20 +#define GL_INDEX_MODE 0x0C30 +#define GL_INDEX_WRITEMASK 0x0C21 +#define GL_MODELVIEW_MATRIX 0x0BA6 +#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 +#define GL_NAME_STACK_DEPTH 0x0D70 +#define GL_PROJECTION_MATRIX 0x0BA7 +#define GL_PROJECTION_STACK_DEPTH 0x0BA4 +#define GL_RENDER_MODE 0x0C40 +#define GL_RGBA_MODE 0x0C31 +#define GL_TEXTURE_MATRIX 0x0BA8 +#define GL_TEXTURE_STACK_DEPTH 0x0BA5 +#define GL_VIEWPORT 0x0BA2 + +/* Evaluators */ +#define GL_AUTO_NORMAL 0x0D80 +#define GL_MAP1_COLOR_4 0x0D90 +#define GL_MAP1_INDEX 0x0D91 +#define GL_MAP1_NORMAL 0x0D92 +#define GL_MAP1_TEXTURE_COORD_1 0x0D93 +#define GL_MAP1_TEXTURE_COORD_2 0x0D94 +#define GL_MAP1_TEXTURE_COORD_3 0x0D95 +#define GL_MAP1_TEXTURE_COORD_4 0x0D96 +#define GL_MAP1_VERTEX_3 0x0D97 +#define GL_MAP1_VERTEX_4 0x0D98 +#define GL_MAP2_COLOR_4 0x0DB0 +#define GL_MAP2_INDEX 0x0DB1 +#define GL_MAP2_NORMAL 0x0DB2 +#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 +#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 +#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 +#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 +#define GL_MAP2_VERTEX_3 0x0DB7 +#define GL_MAP2_VERTEX_4 0x0DB8 +#define GL_MAP1_GRID_DOMAIN 0x0DD0 +#define GL_MAP1_GRID_SEGMENTS 0x0DD1 +#define GL_MAP2_GRID_DOMAIN 0x0DD2 +#define GL_MAP2_GRID_SEGMENTS 0x0DD3 +#define GL_COEFF 0x0A00 +#define GL_ORDER 0x0A01 +#define GL_DOMAIN 0x0A02 + +/* Hints */ +#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 +#define GL_POINT_SMOOTH_HINT 0x0C51 +#define GL_LINE_SMOOTH_HINT 0x0C52 +#define GL_POLYGON_SMOOTH_HINT 0x0C53 +#define GL_FOG_HINT 0x0C54 +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 + +/* Scissor box */ +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 + +/* Pixel Mode / Transfer */ +#define GL_MAP_COLOR 0x0D10 +#define GL_MAP_STENCIL 0x0D11 +#define GL_INDEX_SHIFT 0x0D12 +#define GL_INDEX_OFFSET 0x0D13 +#define GL_RED_SCALE 0x0D14 +#define GL_RED_BIAS 0x0D15 +#define GL_GREEN_SCALE 0x0D18 +#define GL_GREEN_BIAS 0x0D19 +#define GL_BLUE_SCALE 0x0D1A +#define GL_BLUE_BIAS 0x0D1B +#define GL_ALPHA_SCALE 0x0D1C +#define GL_ALPHA_BIAS 0x0D1D +#define GL_DEPTH_SCALE 0x0D1E +#define GL_DEPTH_BIAS 0x0D1F +#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 +#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 +#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 +#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 +#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 +#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 +#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 +#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 +#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 +#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 +#define GL_PIXEL_MAP_S_TO_S 0x0C71 +#define GL_PIXEL_MAP_I_TO_I 0x0C70 +#define GL_PIXEL_MAP_I_TO_R 0x0C72 +#define GL_PIXEL_MAP_I_TO_G 0x0C73 +#define GL_PIXEL_MAP_I_TO_B 0x0C74 +#define GL_PIXEL_MAP_I_TO_A 0x0C75 +#define GL_PIXEL_MAP_R_TO_R 0x0C76 +#define GL_PIXEL_MAP_G_TO_G 0x0C77 +#define GL_PIXEL_MAP_B_TO_B 0x0C78 +#define GL_PIXEL_MAP_A_TO_A 0x0C79 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_PACK_LSB_FIRST 0x0D01 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SWAP_BYTES 0x0D00 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_UNPACK_LSB_FIRST 0x0CF1 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SWAP_BYTES 0x0CF0 +#define GL_ZOOM_X 0x0D16 +#define GL_ZOOM_Y 0x0D17 + +/* Texture mapping */ +#define GL_TEXTURE_ENV 0x2300 +#define GL_TEXTURE_ENV_MODE 0x2200 +#define GL_TEXTURE_1D 0x0DE0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_ENV_COLOR 0x2201 +#define GL_TEXTURE_GEN_S 0x0C60 +#define GL_TEXTURE_GEN_T 0x0C61 +#define GL_TEXTURE_GEN_R 0x0C62 +#define GL_TEXTURE_GEN_Q 0x0C63 +#define GL_TEXTURE_GEN_MODE 0x2500 +#define GL_TEXTURE_BORDER_COLOR 0x1004 +#define GL_TEXTURE_WIDTH 0x1000 +#define GL_TEXTURE_HEIGHT 0x1001 +#define GL_TEXTURE_BORDER 0x1005 +#define GL_TEXTURE_COMPONENTS 0x1003 +#define GL_TEXTURE_RED_SIZE 0x805C +#define GL_TEXTURE_GREEN_SIZE 0x805D +#define GL_TEXTURE_BLUE_SIZE 0x805E +#define GL_TEXTURE_ALPHA_SIZE 0x805F +#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 +#define GL_TEXTURE_INTENSITY_SIZE 0x8061 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_OBJECT_LINEAR 0x2401 +#define GL_OBJECT_PLANE 0x2501 +#define GL_EYE_LINEAR 0x2400 +#define GL_EYE_PLANE 0x2502 +#define GL_SPHERE_MAP 0x2402 +#define GL_DECAL 0x2101 +#define GL_MODULATE 0x2100 +#define GL_NEAREST 0x2600 +#define GL_REPEAT 0x2901 +#define GL_CLAMP 0x2900 +#define GL_S 0x2000 +#define GL_T 0x2001 +#define GL_R 0x2002 +#define GL_Q 0x2003 + +/* Utility */ +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 + +/* Errors */ +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_STACK_OVERFLOW 0x0503 +#define GL_STACK_UNDERFLOW 0x0504 +#define GL_OUT_OF_MEMORY 0x0505 + +/* glPush/PopAttrib bits */ +#define GL_CURRENT_BIT 0x00000001 +#define GL_POINT_BIT 0x00000002 +#define GL_LINE_BIT 0x00000004 +#define GL_POLYGON_BIT 0x00000008 +#define GL_POLYGON_STIPPLE_BIT 0x00000010 +#define GL_PIXEL_MODE_BIT 0x00000020 +#define GL_LIGHTING_BIT 0x00000040 +#define GL_FOG_BIT 0x00000080 +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_ACCUM_BUFFER_BIT 0x00000200 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_VIEWPORT_BIT 0x00000800 +#define GL_TRANSFORM_BIT 0x00001000 +#define GL_ENABLE_BIT 0x00002000 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_HINT_BIT 0x00008000 +#define GL_EVAL_BIT 0x00010000 +#define GL_LIST_BIT 0x00020000 +#define GL_TEXTURE_BIT 0x00040000 +#define GL_SCISSOR_BIT 0x00080000 +#define GL_ALL_ATTRIB_BITS 0x000FFFFF + + +/* OpenGL 1.1 */ +#define GL_PROXY_TEXTURE_1D 0x8063 +#define GL_PROXY_TEXTURE_2D 0x8064 +#define GL_TEXTURE_PRIORITY 0x8066 +#define GL_TEXTURE_RESIDENT 0x8067 +#define GL_TEXTURE_BINDING_1D 0x8068 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 +#define GL_ALPHA4 0x803B +#define GL_ALPHA8 0x803C +#define GL_ALPHA12 0x803D +#define GL_ALPHA16 0x803E +#define GL_LUMINANCE4 0x803F +#define GL_LUMINANCE8 0x8040 +#define GL_LUMINANCE12 0x8041 +#define GL_LUMINANCE16 0x8042 +#define GL_LUMINANCE4_ALPHA4 0x8043 +#define GL_LUMINANCE6_ALPHA2 0x8044 +#define GL_LUMINANCE8_ALPHA8 0x8045 +#define GL_LUMINANCE12_ALPHA4 0x8046 +#define GL_LUMINANCE12_ALPHA12 0x8047 +#define GL_LUMINANCE16_ALPHA16 0x8048 +#define GL_INTENSITY 0x8049 +#define GL_INTENSITY4 0x804A +#define GL_INTENSITY8 0x804B +#define GL_INTENSITY12 0x804C +#define GL_INTENSITY16 0x804D +#define GL_R3_G3_B2 0x2A10 +#define GL_RGB4 0x804F +#define GL_RGB5 0x8050 +#define GL_RGB8 0x8051 +#define GL_RGB10 0x8052 +#define GL_RGB12 0x8053 +#define GL_RGB16 0x8054 +#define GL_RGBA2 0x8055 +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_RGBA12 0x805A +#define GL_RGBA16 0x805B +#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 +#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 +#define GL_ALL_CLIENT_ATTRIB_BITS 0xFFFFFFFF +#define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF + + + +/* + * Miscellaneous + */ + +GLAPI void GLAPIENTRY glClearIndex( GLfloat c ); + +GLAPI void GLAPIENTRY glClearColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha ); + +GLAPI void GLAPIENTRY glClear( GLbitfield mask ); + +GLAPI void GLAPIENTRY glIndexMask( GLuint mask ); + +GLAPI void GLAPIENTRY glColorMask( GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha ); + +GLAPI void GLAPIENTRY glAlphaFunc( GLenum func, GLclampf ref ); + +GLAPI void GLAPIENTRY glBlendFunc( GLenum sfactor, GLenum dfactor ); + +GLAPI void GLAPIENTRY glLogicOp( GLenum opcode ); + +GLAPI void GLAPIENTRY glCullFace( GLenum mode ); + +GLAPI void GLAPIENTRY glFrontFace( GLenum mode ); + +GLAPI void GLAPIENTRY glPointSize( GLfloat size ); + +GLAPI void GLAPIENTRY glLineWidth( GLfloat width ); + +GLAPI void GLAPIENTRY glLineStipple( GLint factor, GLushort pattern ); + +GLAPI void GLAPIENTRY glPolygonMode( GLenum face, GLenum mode ); + +GLAPI void GLAPIENTRY glPolygonOffset( GLfloat factor, GLfloat units ); + +GLAPI void GLAPIENTRY glPolygonStipple( const GLubyte *mask ); + +GLAPI void GLAPIENTRY glGetPolygonStipple( GLubyte *mask ); + +GLAPI void GLAPIENTRY glEdgeFlag( GLboolean flag ); + +GLAPI void GLAPIENTRY glEdgeFlagv( const GLboolean *flag ); + +GLAPI void GLAPIENTRY glScissor( GLint x, GLint y, GLsizei width, GLsizei height); + +GLAPI void GLAPIENTRY glClipPlane( GLenum plane, const GLdouble *equation ); + +GLAPI void GLAPIENTRY glGetClipPlane( GLenum plane, GLdouble *equation ); + +GLAPI void GLAPIENTRY glDrawBuffer( GLenum mode ); + +GLAPI void GLAPIENTRY glReadBuffer( GLenum mode ); + +GLAPI void GLAPIENTRY glEnable( GLenum cap ); + +GLAPI void GLAPIENTRY glDisable( GLenum cap ); + +GLAPI GLboolean GLAPIENTRY glIsEnabled( GLenum cap ); + + +GLAPI void GLAPIENTRY glEnableClientState( GLenum cap ); /* 1.1 */ + +GLAPI void GLAPIENTRY glDisableClientState( GLenum cap ); /* 1.1 */ + + +GLAPI void GLAPIENTRY glGetBooleanv( GLenum pname, GLboolean *params ); + +GLAPI void GLAPIENTRY glGetDoublev( GLenum pname, GLdouble *params ); + +GLAPI void GLAPIENTRY glGetFloatv( GLenum pname, GLfloat *params ); + +GLAPI void GLAPIENTRY glGetIntegerv( GLenum pname, GLint *params ); + + +GLAPI void GLAPIENTRY glPushAttrib( GLbitfield mask ); + +GLAPI void GLAPIENTRY glPopAttrib( void ); + + +GLAPI void GLAPIENTRY glPushClientAttrib( GLbitfield mask ); /* 1.1 */ + +GLAPI void GLAPIENTRY glPopClientAttrib( void ); /* 1.1 */ + + +GLAPI GLint GLAPIENTRY glRenderMode( GLenum mode ); + +GLAPI GLenum GLAPIENTRY glGetError( void ); + +GLAPI const GLubyte * GLAPIENTRY glGetString( GLenum name ); + +GLAPI void GLAPIENTRY glFinish( void ); + +GLAPI void GLAPIENTRY glFlush( void ); + +GLAPI void GLAPIENTRY glHint( GLenum target, GLenum mode ); + + +/* + * Depth Buffer + */ + +GLAPI void GLAPIENTRY glClearDepth( GLclampd depth ); + +GLAPI void GLAPIENTRY glDepthFunc( GLenum func ); + +GLAPI void GLAPIENTRY glDepthMask( GLboolean flag ); + +GLAPI void GLAPIENTRY glDepthRange( GLclampd near_val, GLclampd far_val ); + + +/* + * Accumulation Buffer + */ + +GLAPI void GLAPIENTRY glClearAccum( GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha ); + +GLAPI void GLAPIENTRY glAccum( GLenum op, GLfloat value ); + + +/* + * Transformation + */ + +GLAPI void GLAPIENTRY glMatrixMode( GLenum mode ); + +GLAPI void GLAPIENTRY glOrtho( GLdouble left, GLdouble right, + GLdouble bottom, GLdouble top, + GLdouble near_val, GLdouble far_val ); + +GLAPI void GLAPIENTRY glFrustum( GLdouble left, GLdouble right, + GLdouble bottom, GLdouble top, + GLdouble near_val, GLdouble far_val ); + +GLAPI void GLAPIENTRY glViewport( GLint x, GLint y, + GLsizei width, GLsizei height ); + +GLAPI void GLAPIENTRY glPushMatrix( void ); + +GLAPI void GLAPIENTRY glPopMatrix( void ); + +GLAPI void GLAPIENTRY glLoadIdentity( void ); + +GLAPI void GLAPIENTRY glLoadMatrixd( const GLdouble *m ); +GLAPI void GLAPIENTRY glLoadMatrixf( const GLfloat *m ); + +GLAPI void GLAPIENTRY glMultMatrixd( const GLdouble *m ); +GLAPI void GLAPIENTRY glMultMatrixf( const GLfloat *m ); + +GLAPI void GLAPIENTRY glRotated( GLdouble angle, + GLdouble x, GLdouble y, GLdouble z ); +GLAPI void GLAPIENTRY glRotatef( GLfloat angle, + GLfloat x, GLfloat y, GLfloat z ); + +GLAPI void GLAPIENTRY glScaled( GLdouble x, GLdouble y, GLdouble z ); +GLAPI void GLAPIENTRY glScalef( GLfloat x, GLfloat y, GLfloat z ); + +GLAPI void GLAPIENTRY glTranslated( GLdouble x, GLdouble y, GLdouble z ); +GLAPI void GLAPIENTRY glTranslatef( GLfloat x, GLfloat y, GLfloat z ); + + +/* + * Display Lists + */ + +GLAPI GLboolean GLAPIENTRY glIsList( GLuint list ); + +GLAPI void GLAPIENTRY glDeleteLists( GLuint list, GLsizei range ); + +GLAPI GLuint GLAPIENTRY glGenLists( GLsizei range ); + +GLAPI void GLAPIENTRY glNewList( GLuint list, GLenum mode ); + +GLAPI void GLAPIENTRY glEndList( void ); + +GLAPI void GLAPIENTRY glCallList( GLuint list ); + +GLAPI void GLAPIENTRY glCallLists( GLsizei n, GLenum type, + const GLvoid *lists ); + +GLAPI void GLAPIENTRY glListBase( GLuint base ); + + +/* + * Drawing Functions + */ + +GLAPI void GLAPIENTRY glBegin( GLenum mode ); + +GLAPI void GLAPIENTRY glEnd( void ); + + +GLAPI void GLAPIENTRY glVertex2d( GLdouble x, GLdouble y ); +GLAPI void GLAPIENTRY glVertex2f( GLfloat x, GLfloat y ); +GLAPI void GLAPIENTRY glVertex2i( GLint x, GLint y ); +GLAPI void GLAPIENTRY glVertex2s( GLshort x, GLshort y ); + +GLAPI void GLAPIENTRY glVertex3d( GLdouble x, GLdouble y, GLdouble z ); +GLAPI void GLAPIENTRY glVertex3f( GLfloat x, GLfloat y, GLfloat z ); +GLAPI void GLAPIENTRY glVertex3i( GLint x, GLint y, GLint z ); +GLAPI void GLAPIENTRY glVertex3s( GLshort x, GLshort y, GLshort z ); + +GLAPI void GLAPIENTRY glVertex4d( GLdouble x, GLdouble y, GLdouble z, GLdouble w ); +GLAPI void GLAPIENTRY glVertex4f( GLfloat x, GLfloat y, GLfloat z, GLfloat w ); +GLAPI void GLAPIENTRY glVertex4i( GLint x, GLint y, GLint z, GLint w ); +GLAPI void GLAPIENTRY glVertex4s( GLshort x, GLshort y, GLshort z, GLshort w ); + +GLAPI void GLAPIENTRY glVertex2dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glVertex2fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glVertex2iv( const GLint *v ); +GLAPI void GLAPIENTRY glVertex2sv( const GLshort *v ); + +GLAPI void GLAPIENTRY glVertex3dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glVertex3fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glVertex3iv( const GLint *v ); +GLAPI void GLAPIENTRY glVertex3sv( const GLshort *v ); + +GLAPI void GLAPIENTRY glVertex4dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glVertex4fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glVertex4iv( const GLint *v ); +GLAPI void GLAPIENTRY glVertex4sv( const GLshort *v ); + + +GLAPI void GLAPIENTRY glNormal3b( GLbyte nx, GLbyte ny, GLbyte nz ); +GLAPI void GLAPIENTRY glNormal3d( GLdouble nx, GLdouble ny, GLdouble nz ); +GLAPI void GLAPIENTRY glNormal3f( GLfloat nx, GLfloat ny, GLfloat nz ); +GLAPI void GLAPIENTRY glNormal3i( GLint nx, GLint ny, GLint nz ); +GLAPI void GLAPIENTRY glNormal3s( GLshort nx, GLshort ny, GLshort nz ); + +GLAPI void GLAPIENTRY glNormal3bv( const GLbyte *v ); +GLAPI void GLAPIENTRY glNormal3dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glNormal3fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glNormal3iv( const GLint *v ); +GLAPI void GLAPIENTRY glNormal3sv( const GLshort *v ); + + +GLAPI void GLAPIENTRY glIndexd( GLdouble c ); +GLAPI void GLAPIENTRY glIndexf( GLfloat c ); +GLAPI void GLAPIENTRY glIndexi( GLint c ); +GLAPI void GLAPIENTRY glIndexs( GLshort c ); +GLAPI void GLAPIENTRY glIndexub( GLubyte c ); /* 1.1 */ + +GLAPI void GLAPIENTRY glIndexdv( const GLdouble *c ); +GLAPI void GLAPIENTRY glIndexfv( const GLfloat *c ); +GLAPI void GLAPIENTRY glIndexiv( const GLint *c ); +GLAPI void GLAPIENTRY glIndexsv( const GLshort *c ); +GLAPI void GLAPIENTRY glIndexubv( const GLubyte *c ); /* 1.1 */ + +GLAPI void GLAPIENTRY glColor3b( GLbyte red, GLbyte green, GLbyte blue ); +GLAPI void GLAPIENTRY glColor3d( GLdouble red, GLdouble green, GLdouble blue ); +GLAPI void GLAPIENTRY glColor3f( GLfloat red, GLfloat green, GLfloat blue ); +GLAPI void GLAPIENTRY glColor3i( GLint red, GLint green, GLint blue ); +GLAPI void GLAPIENTRY glColor3s( GLshort red, GLshort green, GLshort blue ); +GLAPI void GLAPIENTRY glColor3ub( GLubyte red, GLubyte green, GLubyte blue ); +GLAPI void GLAPIENTRY glColor3ui( GLuint red, GLuint green, GLuint blue ); +GLAPI void GLAPIENTRY glColor3us( GLushort red, GLushort green, GLushort blue ); + +GLAPI void GLAPIENTRY glColor4b( GLbyte red, GLbyte green, + GLbyte blue, GLbyte alpha ); +GLAPI void GLAPIENTRY glColor4d( GLdouble red, GLdouble green, + GLdouble blue, GLdouble alpha ); +GLAPI void GLAPIENTRY glColor4f( GLfloat red, GLfloat green, + GLfloat blue, GLfloat alpha ); +GLAPI void GLAPIENTRY glColor4i( GLint red, GLint green, + GLint blue, GLint alpha ); +GLAPI void GLAPIENTRY glColor4s( GLshort red, GLshort green, + GLshort blue, GLshort alpha ); +GLAPI void GLAPIENTRY glColor4ub( GLubyte red, GLubyte green, + GLubyte blue, GLubyte alpha ); +GLAPI void GLAPIENTRY glColor4ui( GLuint red, GLuint green, + GLuint blue, GLuint alpha ); +GLAPI void GLAPIENTRY glColor4us( GLushort red, GLushort green, + GLushort blue, GLushort alpha ); + + +GLAPI void GLAPIENTRY glColor3bv( const GLbyte *v ); +GLAPI void GLAPIENTRY glColor3dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glColor3fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glColor3iv( const GLint *v ); +GLAPI void GLAPIENTRY glColor3sv( const GLshort *v ); +GLAPI void GLAPIENTRY glColor3ubv( const GLubyte *v ); +GLAPI void GLAPIENTRY glColor3uiv( const GLuint *v ); +GLAPI void GLAPIENTRY glColor3usv( const GLushort *v ); + +GLAPI void GLAPIENTRY glColor4bv( const GLbyte *v ); +GLAPI void GLAPIENTRY glColor4dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glColor4fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glColor4iv( const GLint *v ); +GLAPI void GLAPIENTRY glColor4sv( const GLshort *v ); +GLAPI void GLAPIENTRY glColor4ubv( const GLubyte *v ); +GLAPI void GLAPIENTRY glColor4uiv( const GLuint *v ); +GLAPI void GLAPIENTRY glColor4usv( const GLushort *v ); + + +GLAPI void GLAPIENTRY glTexCoord1d( GLdouble s ); +GLAPI void GLAPIENTRY glTexCoord1f( GLfloat s ); +GLAPI void GLAPIENTRY glTexCoord1i( GLint s ); +GLAPI void GLAPIENTRY glTexCoord1s( GLshort s ); + +GLAPI void GLAPIENTRY glTexCoord2d( GLdouble s, GLdouble t ); +GLAPI void GLAPIENTRY glTexCoord2f( GLfloat s, GLfloat t ); +GLAPI void GLAPIENTRY glTexCoord2i( GLint s, GLint t ); +GLAPI void GLAPIENTRY glTexCoord2s( GLshort s, GLshort t ); + +GLAPI void GLAPIENTRY glTexCoord3d( GLdouble s, GLdouble t, GLdouble r ); +GLAPI void GLAPIENTRY glTexCoord3f( GLfloat s, GLfloat t, GLfloat r ); +GLAPI void GLAPIENTRY glTexCoord3i( GLint s, GLint t, GLint r ); +GLAPI void GLAPIENTRY glTexCoord3s( GLshort s, GLshort t, GLshort r ); + +GLAPI void GLAPIENTRY glTexCoord4d( GLdouble s, GLdouble t, GLdouble r, GLdouble q ); +GLAPI void GLAPIENTRY glTexCoord4f( GLfloat s, GLfloat t, GLfloat r, GLfloat q ); +GLAPI void GLAPIENTRY glTexCoord4i( GLint s, GLint t, GLint r, GLint q ); +GLAPI void GLAPIENTRY glTexCoord4s( GLshort s, GLshort t, GLshort r, GLshort q ); + +GLAPI void GLAPIENTRY glTexCoord1dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glTexCoord1fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glTexCoord1iv( const GLint *v ); +GLAPI void GLAPIENTRY glTexCoord1sv( const GLshort *v ); + +GLAPI void GLAPIENTRY glTexCoord2dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glTexCoord2fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glTexCoord2iv( const GLint *v ); +GLAPI void GLAPIENTRY glTexCoord2sv( const GLshort *v ); + +GLAPI void GLAPIENTRY glTexCoord3dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glTexCoord3fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glTexCoord3iv( const GLint *v ); +GLAPI void GLAPIENTRY glTexCoord3sv( const GLshort *v ); + +GLAPI void GLAPIENTRY glTexCoord4dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glTexCoord4fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glTexCoord4iv( const GLint *v ); +GLAPI void GLAPIENTRY glTexCoord4sv( const GLshort *v ); + + +GLAPI void GLAPIENTRY glRasterPos2d( GLdouble x, GLdouble y ); +GLAPI void GLAPIENTRY glRasterPos2f( GLfloat x, GLfloat y ); +GLAPI void GLAPIENTRY glRasterPos2i( GLint x, GLint y ); +GLAPI void GLAPIENTRY glRasterPos2s( GLshort x, GLshort y ); + +GLAPI void GLAPIENTRY glRasterPos3d( GLdouble x, GLdouble y, GLdouble z ); +GLAPI void GLAPIENTRY glRasterPos3f( GLfloat x, GLfloat y, GLfloat z ); +GLAPI void GLAPIENTRY glRasterPos3i( GLint x, GLint y, GLint z ); +GLAPI void GLAPIENTRY glRasterPos3s( GLshort x, GLshort y, GLshort z ); + +GLAPI void GLAPIENTRY glRasterPos4d( GLdouble x, GLdouble y, GLdouble z, GLdouble w ); +GLAPI void GLAPIENTRY glRasterPos4f( GLfloat x, GLfloat y, GLfloat z, GLfloat w ); +GLAPI void GLAPIENTRY glRasterPos4i( GLint x, GLint y, GLint z, GLint w ); +GLAPI void GLAPIENTRY glRasterPos4s( GLshort x, GLshort y, GLshort z, GLshort w ); + +GLAPI void GLAPIENTRY glRasterPos2dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glRasterPos2fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glRasterPos2iv( const GLint *v ); +GLAPI void GLAPIENTRY glRasterPos2sv( const GLshort *v ); + +GLAPI void GLAPIENTRY glRasterPos3dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glRasterPos3fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glRasterPos3iv( const GLint *v ); +GLAPI void GLAPIENTRY glRasterPos3sv( const GLshort *v ); + +GLAPI void GLAPIENTRY glRasterPos4dv( const GLdouble *v ); +GLAPI void GLAPIENTRY glRasterPos4fv( const GLfloat *v ); +GLAPI void GLAPIENTRY glRasterPos4iv( const GLint *v ); +GLAPI void GLAPIENTRY glRasterPos4sv( const GLshort *v ); + + +GLAPI void GLAPIENTRY glRectd( GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2 ); +GLAPI void GLAPIENTRY glRectf( GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2 ); +GLAPI void GLAPIENTRY glRecti( GLint x1, GLint y1, GLint x2, GLint y2 ); +GLAPI void GLAPIENTRY glRects( GLshort x1, GLshort y1, GLshort x2, GLshort y2 ); + + +GLAPI void GLAPIENTRY glRectdv( const GLdouble *v1, const GLdouble *v2 ); +GLAPI void GLAPIENTRY glRectfv( const GLfloat *v1, const GLfloat *v2 ); +GLAPI void GLAPIENTRY glRectiv( const GLint *v1, const GLint *v2 ); +GLAPI void GLAPIENTRY glRectsv( const GLshort *v1, const GLshort *v2 ); + + +/* + * Vertex Arrays (1.1) + */ + +GLAPI void GLAPIENTRY glVertexPointer( GLint size, GLenum type, + GLsizei stride, const GLvoid *ptr ); + +GLAPI void GLAPIENTRY glNormalPointer( GLenum type, GLsizei stride, + const GLvoid *ptr ); + +GLAPI void GLAPIENTRY glColorPointer( GLint size, GLenum type, + GLsizei stride, const GLvoid *ptr ); + +GLAPI void GLAPIENTRY glIndexPointer( GLenum type, GLsizei stride, + const GLvoid *ptr ); + +GLAPI void GLAPIENTRY glTexCoordPointer( GLint size, GLenum type, + GLsizei stride, const GLvoid *ptr ); + +GLAPI void GLAPIENTRY glEdgeFlagPointer( GLsizei stride, const GLvoid *ptr ); + +GLAPI void GLAPIENTRY glGetPointerv( GLenum pname, GLvoid **params ); + +GLAPI void GLAPIENTRY glArrayElement( GLint i ); + +GLAPI void GLAPIENTRY glDrawArrays( GLenum mode, GLint first, GLsizei count ); + +GLAPI void GLAPIENTRY glDrawElements( GLenum mode, GLsizei count, + GLenum type, const GLvoid *indices ); + +GLAPI void GLAPIENTRY glInterleavedArrays( GLenum format, GLsizei stride, + const GLvoid *pointer ); + +/* + * Lighting + */ + +GLAPI void GLAPIENTRY glShadeModel( GLenum mode ); + +GLAPI void GLAPIENTRY glLightf( GLenum light, GLenum pname, GLfloat param ); +GLAPI void GLAPIENTRY glLighti( GLenum light, GLenum pname, GLint param ); +GLAPI void GLAPIENTRY glLightfv( GLenum light, GLenum pname, + const GLfloat *params ); +GLAPI void GLAPIENTRY glLightiv( GLenum light, GLenum pname, + const GLint *params ); + +GLAPI void GLAPIENTRY glGetLightfv( GLenum light, GLenum pname, + GLfloat *params ); +GLAPI void GLAPIENTRY glGetLightiv( GLenum light, GLenum pname, + GLint *params ); + +GLAPI void GLAPIENTRY glLightModelf( GLenum pname, GLfloat param ); +GLAPI void GLAPIENTRY glLightModeli( GLenum pname, GLint param ); +GLAPI void GLAPIENTRY glLightModelfv( GLenum pname, const GLfloat *params ); +GLAPI void GLAPIENTRY glLightModeliv( GLenum pname, const GLint *params ); + +GLAPI void GLAPIENTRY glMaterialf( GLenum face, GLenum pname, GLfloat param ); +GLAPI void GLAPIENTRY glMateriali( GLenum face, GLenum pname, GLint param ); +GLAPI void GLAPIENTRY glMaterialfv( GLenum face, GLenum pname, const GLfloat *params ); +GLAPI void GLAPIENTRY glMaterialiv( GLenum face, GLenum pname, const GLint *params ); + +GLAPI void GLAPIENTRY glGetMaterialfv( GLenum face, GLenum pname, GLfloat *params ); +GLAPI void GLAPIENTRY glGetMaterialiv( GLenum face, GLenum pname, GLint *params ); + +GLAPI void GLAPIENTRY glColorMaterial( GLenum face, GLenum mode ); + + +/* + * Raster functions + */ + +GLAPI void GLAPIENTRY glPixelZoom( GLfloat xfactor, GLfloat yfactor ); + +GLAPI void GLAPIENTRY glPixelStoref( GLenum pname, GLfloat param ); +GLAPI void GLAPIENTRY glPixelStorei( GLenum pname, GLint param ); + +GLAPI void GLAPIENTRY glPixelTransferf( GLenum pname, GLfloat param ); +GLAPI void GLAPIENTRY glPixelTransferi( GLenum pname, GLint param ); + +GLAPI void GLAPIENTRY glPixelMapfv( GLenum map, GLsizei mapsize, + const GLfloat *values ); +GLAPI void GLAPIENTRY glPixelMapuiv( GLenum map, GLsizei mapsize, + const GLuint *values ); +GLAPI void GLAPIENTRY glPixelMapusv( GLenum map, GLsizei mapsize, + const GLushort *values ); + +GLAPI void GLAPIENTRY glGetPixelMapfv( GLenum map, GLfloat *values ); +GLAPI void GLAPIENTRY glGetPixelMapuiv( GLenum map, GLuint *values ); +GLAPI void GLAPIENTRY glGetPixelMapusv( GLenum map, GLushort *values ); + +GLAPI void GLAPIENTRY glBitmap( GLsizei width, GLsizei height, + GLfloat xorig, GLfloat yorig, + GLfloat xmove, GLfloat ymove, + const GLubyte *bitmap ); + +GLAPI void GLAPIENTRY glReadPixels( GLint x, GLint y, + GLsizei width, GLsizei height, + GLenum format, GLenum type, + GLvoid *pixels ); + +GLAPI void GLAPIENTRY glDrawPixels( GLsizei width, GLsizei height, + GLenum format, GLenum type, + const GLvoid *pixels ); + +GLAPI void GLAPIENTRY glCopyPixels( GLint x, GLint y, + GLsizei width, GLsizei height, + GLenum type ); + +/* + * Stenciling + */ + +GLAPI void GLAPIENTRY glStencilFunc( GLenum func, GLint ref, GLuint mask ); + +GLAPI void GLAPIENTRY glStencilMask( GLuint mask ); + +GLAPI void GLAPIENTRY glStencilOp( GLenum fail, GLenum zfail, GLenum zpass ); + +GLAPI void GLAPIENTRY glClearStencil( GLint s ); + + + +/* + * Texture mapping + */ + +GLAPI void GLAPIENTRY glTexGend( GLenum coord, GLenum pname, GLdouble param ); +GLAPI void GLAPIENTRY glTexGenf( GLenum coord, GLenum pname, GLfloat param ); +GLAPI void GLAPIENTRY glTexGeni( GLenum coord, GLenum pname, GLint param ); + +GLAPI void GLAPIENTRY glTexGendv( GLenum coord, GLenum pname, const GLdouble *params ); +GLAPI void GLAPIENTRY glTexGenfv( GLenum coord, GLenum pname, const GLfloat *params ); +GLAPI void GLAPIENTRY glTexGeniv( GLenum coord, GLenum pname, const GLint *params ); + +GLAPI void GLAPIENTRY glGetTexGendv( GLenum coord, GLenum pname, GLdouble *params ); +GLAPI void GLAPIENTRY glGetTexGenfv( GLenum coord, GLenum pname, GLfloat *params ); +GLAPI void GLAPIENTRY glGetTexGeniv( GLenum coord, GLenum pname, GLint *params ); + + +GLAPI void GLAPIENTRY glTexEnvf( GLenum target, GLenum pname, GLfloat param ); +GLAPI void GLAPIENTRY glTexEnvi( GLenum target, GLenum pname, GLint param ); + +GLAPI void GLAPIENTRY glTexEnvfv( GLenum target, GLenum pname, const GLfloat *params ); +GLAPI void GLAPIENTRY glTexEnviv( GLenum target, GLenum pname, const GLint *params ); + +GLAPI void GLAPIENTRY glGetTexEnvfv( GLenum target, GLenum pname, GLfloat *params ); +GLAPI void GLAPIENTRY glGetTexEnviv( GLenum target, GLenum pname, GLint *params ); + + +GLAPI void GLAPIENTRY glTexParameterf( GLenum target, GLenum pname, GLfloat param ); +GLAPI void GLAPIENTRY glTexParameteri( GLenum target, GLenum pname, GLint param ); + +GLAPI void GLAPIENTRY glTexParameterfv( GLenum target, GLenum pname, + const GLfloat *params ); +GLAPI void GLAPIENTRY glTexParameteriv( GLenum target, GLenum pname, + const GLint *params ); + +GLAPI void GLAPIENTRY glGetTexParameterfv( GLenum target, + GLenum pname, GLfloat *params); +GLAPI void GLAPIENTRY glGetTexParameteriv( GLenum target, + GLenum pname, GLint *params ); + +GLAPI void GLAPIENTRY glGetTexLevelParameterfv( GLenum target, GLint level, + GLenum pname, GLfloat *params ); +GLAPI void GLAPIENTRY glGetTexLevelParameteriv( GLenum target, GLint level, + GLenum pname, GLint *params ); + + +GLAPI void GLAPIENTRY glTexImage1D( GLenum target, GLint level, + GLint internalFormat, + GLsizei width, GLint border, + GLenum format, GLenum type, + const GLvoid *pixels ); + +GLAPI void GLAPIENTRY glTexImage2D( GLenum target, GLint level, + GLint internalFormat, + GLsizei width, GLsizei height, + GLint border, GLenum format, GLenum type, + const GLvoid *pixels ); + +GLAPI void GLAPIENTRY glGetTexImage( GLenum target, GLint level, + GLenum format, GLenum type, + GLvoid *pixels ); + + +/* 1.1 functions */ + +GLAPI void GLAPIENTRY glGenTextures( GLsizei n, GLuint *textures ); + +GLAPI void GLAPIENTRY glDeleteTextures( GLsizei n, const GLuint *textures); + +GLAPI void GLAPIENTRY glBindTexture( GLenum target, GLuint texture ); + +GLAPI void GLAPIENTRY glPrioritizeTextures( GLsizei n, + const GLuint *textures, + const GLclampf *priorities ); + +GLAPI GLboolean GLAPIENTRY glAreTexturesResident( GLsizei n, + const GLuint *textures, + GLboolean *residences ); + +GLAPI GLboolean GLAPIENTRY glIsTexture( GLuint texture ); + + +GLAPI void GLAPIENTRY glTexSubImage1D( GLenum target, GLint level, + GLint xoffset, + GLsizei width, GLenum format, + GLenum type, const GLvoid *pixels ); + + +GLAPI void GLAPIENTRY glTexSubImage2D( GLenum target, GLint level, + GLint xoffset, GLint yoffset, + GLsizei width, GLsizei height, + GLenum format, GLenum type, + const GLvoid *pixels ); + + +GLAPI void GLAPIENTRY glCopyTexImage1D( GLenum target, GLint level, + GLenum internalformat, + GLint x, GLint y, + GLsizei width, GLint border ); + + +GLAPI void GLAPIENTRY glCopyTexImage2D( GLenum target, GLint level, + GLenum internalformat, + GLint x, GLint y, + GLsizei width, GLsizei height, + GLint border ); + + +GLAPI void GLAPIENTRY glCopyTexSubImage1D( GLenum target, GLint level, + GLint xoffset, GLint x, GLint y, + GLsizei width ); + + +GLAPI void GLAPIENTRY glCopyTexSubImage2D( GLenum target, GLint level, + GLint xoffset, GLint yoffset, + GLint x, GLint y, + GLsizei width, GLsizei height ); + + +/* + * Evaluators + */ + +GLAPI void GLAPIENTRY glMap1d( GLenum target, GLdouble u1, GLdouble u2, + GLint stride, + GLint order, const GLdouble *points ); +GLAPI void GLAPIENTRY glMap1f( GLenum target, GLfloat u1, GLfloat u2, + GLint stride, + GLint order, const GLfloat *points ); + +GLAPI void GLAPIENTRY glMap2d( GLenum target, + GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, + GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, + const GLdouble *points ); +GLAPI void GLAPIENTRY glMap2f( GLenum target, + GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, + GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, + const GLfloat *points ); + +GLAPI void GLAPIENTRY glGetMapdv( GLenum target, GLenum query, GLdouble *v ); +GLAPI void GLAPIENTRY glGetMapfv( GLenum target, GLenum query, GLfloat *v ); +GLAPI void GLAPIENTRY glGetMapiv( GLenum target, GLenum query, GLint *v ); + +GLAPI void GLAPIENTRY glEvalCoord1d( GLdouble u ); +GLAPI void GLAPIENTRY glEvalCoord1f( GLfloat u ); + +GLAPI void GLAPIENTRY glEvalCoord1dv( const GLdouble *u ); +GLAPI void GLAPIENTRY glEvalCoord1fv( const GLfloat *u ); + +GLAPI void GLAPIENTRY glEvalCoord2d( GLdouble u, GLdouble v ); +GLAPI void GLAPIENTRY glEvalCoord2f( GLfloat u, GLfloat v ); + +GLAPI void GLAPIENTRY glEvalCoord2dv( const GLdouble *u ); +GLAPI void GLAPIENTRY glEvalCoord2fv( const GLfloat *u ); + +GLAPI void GLAPIENTRY glMapGrid1d( GLint un, GLdouble u1, GLdouble u2 ); +GLAPI void GLAPIENTRY glMapGrid1f( GLint un, GLfloat u1, GLfloat u2 ); + +GLAPI void GLAPIENTRY glMapGrid2d( GLint un, GLdouble u1, GLdouble u2, + GLint vn, GLdouble v1, GLdouble v2 ); +GLAPI void GLAPIENTRY glMapGrid2f( GLint un, GLfloat u1, GLfloat u2, + GLint vn, GLfloat v1, GLfloat v2 ); + +GLAPI void GLAPIENTRY glEvalPoint1( GLint i ); + +GLAPI void GLAPIENTRY glEvalPoint2( GLint i, GLint j ); + +GLAPI void GLAPIENTRY glEvalMesh1( GLenum mode, GLint i1, GLint i2 ); + +GLAPI void GLAPIENTRY glEvalMesh2( GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2 ); + + +/* + * Fog + */ + +GLAPI void GLAPIENTRY glFogf( GLenum pname, GLfloat param ); + +GLAPI void GLAPIENTRY glFogi( GLenum pname, GLint param ); + +GLAPI void GLAPIENTRY glFogfv( GLenum pname, const GLfloat *params ); + +GLAPI void GLAPIENTRY glFogiv( GLenum pname, const GLint *params ); + + +/* + * Selection and Feedback + */ + +GLAPI void GLAPIENTRY glFeedbackBuffer( GLsizei size, GLenum type, GLfloat *buffer ); + +GLAPI void GLAPIENTRY glPassThrough( GLfloat token ); + +GLAPI void GLAPIENTRY glSelectBuffer( GLsizei size, GLuint *buffer ); + +GLAPI void GLAPIENTRY glInitNames( void ); + +GLAPI void GLAPIENTRY glLoadName( GLuint name ); + +GLAPI void GLAPIENTRY glPushName( GLuint name ); + +GLAPI void GLAPIENTRY glPopName( void ); + + + +/* + * OpenGL 1.2 + */ + +#define GL_RESCALE_NORMAL 0x803A +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_TEXTURE_BINDING_3D 0x806A + +GLAPI void GLAPIENTRY glDrawRangeElements( GLenum mode, GLuint start, + GLuint end, GLsizei count, GLenum type, const GLvoid *indices ); + +GLAPI void GLAPIENTRY glTexImage3D( GLenum target, GLint level, + GLint internalFormat, + GLsizei width, GLsizei height, + GLsizei depth, GLint border, + GLenum format, GLenum type, + const GLvoid *pixels ); + +GLAPI void GLAPIENTRY glTexSubImage3D( GLenum target, GLint level, + GLint xoffset, GLint yoffset, + GLint zoffset, GLsizei width, + GLsizei height, GLsizei depth, + GLenum format, + GLenum type, const GLvoid *pixels); + +GLAPI void GLAPIENTRY glCopyTexSubImage3D( GLenum target, GLint level, + GLint xoffset, GLint yoffset, + GLint zoffset, GLint x, + GLint y, GLsizei width, + GLsizei height ); + +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); + + +/* + * GL_ARB_imaging + */ + +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_COLOR_TABLE 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2 +#define GL_PROXY_COLOR_TABLE 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5 +#define GL_COLOR_TABLE_SCALE 0x80D6 +#define GL_COLOR_TABLE_BIAS 0x80D7 +#define GL_COLOR_TABLE_FORMAT 0x80D8 +#define GL_COLOR_TABLE_WIDTH 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE 0x80DF +#define GL_CONVOLUTION_1D 0x8010 +#define GL_CONVOLUTION_2D 0x8011 +#define GL_SEPARABLE_2D 0x8012 +#define GL_CONVOLUTION_BORDER_MODE 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS 0x8015 +#define GL_REDUCE 0x8016 +#define GL_CONVOLUTION_FORMAT 0x8017 +#define GL_CONVOLUTION_WIDTH 0x8018 +#define GL_CONVOLUTION_HEIGHT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS 0x8023 +#define GL_CONSTANT_BORDER 0x8151 +#define GL_REPLICATE_BORDER 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR 0x8154 +#define GL_COLOR_MATRIX 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS 0x80BB +#define GL_HISTOGRAM 0x8024 +#define GL_PROXY_HISTOGRAM 0x8025 +#define GL_HISTOGRAM_WIDTH 0x8026 +#define GL_HISTOGRAM_FORMAT 0x8027 +#define GL_HISTOGRAM_RED_SIZE 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE 0x802C +#define GL_HISTOGRAM_SINK 0x802D +#define GL_MINMAX 0x802E +#define GL_MINMAX_FORMAT 0x802F +#define GL_MINMAX_SINK 0x8030 +#define GL_TABLE_TOO_LARGE 0x8031 +#define GL_BLEND_EQUATION 0x8009 +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_BLEND_COLOR 0x8005 + + +GLAPI void GLAPIENTRY glColorTable( GLenum target, GLenum internalformat, + GLsizei width, GLenum format, + GLenum type, const GLvoid *table ); + +GLAPI void GLAPIENTRY glColorSubTable( GLenum target, + GLsizei start, GLsizei count, + GLenum format, GLenum type, + const GLvoid *data ); + +GLAPI void GLAPIENTRY glColorTableParameteriv(GLenum target, GLenum pname, + const GLint *params); + +GLAPI void GLAPIENTRY glColorTableParameterfv(GLenum target, GLenum pname, + const GLfloat *params); + +GLAPI void GLAPIENTRY glCopyColorSubTable( GLenum target, GLsizei start, + GLint x, GLint y, GLsizei width ); + +GLAPI void GLAPIENTRY glCopyColorTable( GLenum target, GLenum internalformat, + GLint x, GLint y, GLsizei width ); + +GLAPI void GLAPIENTRY glGetColorTable( GLenum target, GLenum format, + GLenum type, GLvoid *table ); + +GLAPI void GLAPIENTRY glGetColorTableParameterfv( GLenum target, GLenum pname, + GLfloat *params ); + +GLAPI void GLAPIENTRY glGetColorTableParameteriv( GLenum target, GLenum pname, + GLint *params ); + +GLAPI void GLAPIENTRY glBlendEquation( GLenum mode ); + +GLAPI void GLAPIENTRY glBlendColor( GLclampf red, GLclampf green, + GLclampf blue, GLclampf alpha ); + +GLAPI void GLAPIENTRY glHistogram( GLenum target, GLsizei width, + GLenum internalformat, GLboolean sink ); + +GLAPI void GLAPIENTRY glResetHistogram( GLenum target ); + +GLAPI void GLAPIENTRY glGetHistogram( GLenum target, GLboolean reset, + GLenum format, GLenum type, + GLvoid *values ); + +GLAPI void GLAPIENTRY glGetHistogramParameterfv( GLenum target, GLenum pname, + GLfloat *params ); + +GLAPI void GLAPIENTRY glGetHistogramParameteriv( GLenum target, GLenum pname, + GLint *params ); + +GLAPI void GLAPIENTRY glMinmax( GLenum target, GLenum internalformat, + GLboolean sink ); + +GLAPI void GLAPIENTRY glResetMinmax( GLenum target ); + +GLAPI void GLAPIENTRY glGetMinmax( GLenum target, GLboolean reset, + GLenum format, GLenum types, + GLvoid *values ); + +GLAPI void GLAPIENTRY glGetMinmaxParameterfv( GLenum target, GLenum pname, + GLfloat *params ); + +GLAPI void GLAPIENTRY glGetMinmaxParameteriv( GLenum target, GLenum pname, + GLint *params ); + +GLAPI void GLAPIENTRY glConvolutionFilter1D( GLenum target, + GLenum internalformat, GLsizei width, GLenum format, GLenum type, + const GLvoid *image ); + +GLAPI void GLAPIENTRY glConvolutionFilter2D( GLenum target, + GLenum internalformat, GLsizei width, GLsizei height, GLenum format, + GLenum type, const GLvoid *image ); + +GLAPI void GLAPIENTRY glConvolutionParameterf( GLenum target, GLenum pname, + GLfloat params ); + +GLAPI void GLAPIENTRY glConvolutionParameterfv( GLenum target, GLenum pname, + const GLfloat *params ); + +GLAPI void GLAPIENTRY glConvolutionParameteri( GLenum target, GLenum pname, + GLint params ); + +GLAPI void GLAPIENTRY glConvolutionParameteriv( GLenum target, GLenum pname, + const GLint *params ); + +GLAPI void GLAPIENTRY glCopyConvolutionFilter1D( GLenum target, + GLenum internalformat, GLint x, GLint y, GLsizei width ); + +GLAPI void GLAPIENTRY glCopyConvolutionFilter2D( GLenum target, + GLenum internalformat, GLint x, GLint y, GLsizei width, + GLsizei height); + +GLAPI void GLAPIENTRY glGetConvolutionFilter( GLenum target, GLenum format, + GLenum type, GLvoid *image ); + +GLAPI void GLAPIENTRY glGetConvolutionParameterfv( GLenum target, GLenum pname, + GLfloat *params ); + +GLAPI void GLAPIENTRY glGetConvolutionParameteriv( GLenum target, GLenum pname, + GLint *params ); + +GLAPI void GLAPIENTRY glSeparableFilter2D( GLenum target, + GLenum internalformat, GLsizei width, GLsizei height, GLenum format, + GLenum type, const GLvoid *row, const GLvoid *column ); + +GLAPI void GLAPIENTRY glGetSeparableFilter( GLenum target, GLenum format, + GLenum type, GLvoid *row, GLvoid *column, GLvoid *span ); + + + + +/* + * OpenGL 1.3 + */ + +/* multitexture */ +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +/* texture_cube_map */ +#define GL_NORMAL_MAP 0x8511 +#define GL_REFLECTION_MAP 0x8512 +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +/* texture_compression */ +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +/* multisample */ +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_MULTISAMPLE_BIT 0x20000000 +/* transpose_matrix */ +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +/* texture_env_combine */ +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_RGB 0x8582 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_SUBTRACT 0x84E7 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +/* texture_env_dot3 */ +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +/* texture_border_clamp */ +#define GL_CLAMP_TO_BORDER 0x812D + +GLAPI void GLAPIENTRY glActiveTexture( GLenum texture ); + +GLAPI void GLAPIENTRY glClientActiveTexture( GLenum texture ); + +GLAPI void GLAPIENTRY glCompressedTexImage1D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data ); + +GLAPI void GLAPIENTRY glCompressedTexImage2D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data ); + +GLAPI void GLAPIENTRY glCompressedTexImage3D( GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data ); + +GLAPI void GLAPIENTRY glCompressedTexSubImage1D( GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data ); + +GLAPI void GLAPIENTRY glCompressedTexSubImage2D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data ); + +GLAPI void GLAPIENTRY glCompressedTexSubImage3D( GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data ); + +GLAPI void GLAPIENTRY glGetCompressedTexImage( GLenum target, GLint lod, GLvoid *img ); + +GLAPI void GLAPIENTRY glMultiTexCoord1d( GLenum target, GLdouble s ); + +GLAPI void GLAPIENTRY glMultiTexCoord1dv( GLenum target, const GLdouble *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord1f( GLenum target, GLfloat s ); + +GLAPI void GLAPIENTRY glMultiTexCoord1fv( GLenum target, const GLfloat *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord1i( GLenum target, GLint s ); + +GLAPI void GLAPIENTRY glMultiTexCoord1iv( GLenum target, const GLint *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord1s( GLenum target, GLshort s ); + +GLAPI void GLAPIENTRY glMultiTexCoord1sv( GLenum target, const GLshort *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord2d( GLenum target, GLdouble s, GLdouble t ); + +GLAPI void GLAPIENTRY glMultiTexCoord2dv( GLenum target, const GLdouble *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord2f( GLenum target, GLfloat s, GLfloat t ); + +GLAPI void GLAPIENTRY glMultiTexCoord2fv( GLenum target, const GLfloat *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord2i( GLenum target, GLint s, GLint t ); + +GLAPI void GLAPIENTRY glMultiTexCoord2iv( GLenum target, const GLint *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord2s( GLenum target, GLshort s, GLshort t ); + +GLAPI void GLAPIENTRY glMultiTexCoord2sv( GLenum target, const GLshort *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord3d( GLenum target, GLdouble s, GLdouble t, GLdouble r ); + +GLAPI void GLAPIENTRY glMultiTexCoord3dv( GLenum target, const GLdouble *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord3f( GLenum target, GLfloat s, GLfloat t, GLfloat r ); + +GLAPI void GLAPIENTRY glMultiTexCoord3fv( GLenum target, const GLfloat *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord3i( GLenum target, GLint s, GLint t, GLint r ); + +GLAPI void GLAPIENTRY glMultiTexCoord3iv( GLenum target, const GLint *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord3s( GLenum target, GLshort s, GLshort t, GLshort r ); + +GLAPI void GLAPIENTRY glMultiTexCoord3sv( GLenum target, const GLshort *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord4d( GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q ); + +GLAPI void GLAPIENTRY glMultiTexCoord4dv( GLenum target, const GLdouble *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord4f( GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q ); + +GLAPI void GLAPIENTRY glMultiTexCoord4fv( GLenum target, const GLfloat *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord4i( GLenum target, GLint s, GLint t, GLint r, GLint q ); + +GLAPI void GLAPIENTRY glMultiTexCoord4iv( GLenum target, const GLint *v ); + +GLAPI void GLAPIENTRY glMultiTexCoord4s( GLenum target, GLshort s, GLshort t, GLshort r, GLshort q ); + +GLAPI void GLAPIENTRY glMultiTexCoord4sv( GLenum target, const GLshort *v ); + + +GLAPI void GLAPIENTRY glLoadTransposeMatrixd( const GLdouble m[16] ); + +GLAPI void GLAPIENTRY glLoadTransposeMatrixf( const GLfloat m[16] ); + +GLAPI void GLAPIENTRY glMultTransposeMatrixd( const GLdouble m[16] ); + +GLAPI void GLAPIENTRY glMultTransposeMatrixf( const GLfloat m[16] ); + +GLAPI void GLAPIENTRY glSampleCoverage( GLclampf value, GLboolean invert ); + + +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img); + + + +/* + * GL_ARB_multitexture (ARB extension 1 and OpenGL 1.2.1) + */ +#ifndef GL_ARB_multitexture +#define GL_ARB_multitexture 1 + +#define GL_TEXTURE0_ARB 0x84C0 +#define GL_TEXTURE1_ARB 0x84C1 +#define GL_TEXTURE2_ARB 0x84C2 +#define GL_TEXTURE3_ARB 0x84C3 +#define GL_TEXTURE4_ARB 0x84C4 +#define GL_TEXTURE5_ARB 0x84C5 +#define GL_TEXTURE6_ARB 0x84C6 +#define GL_TEXTURE7_ARB 0x84C7 +#define GL_TEXTURE8_ARB 0x84C8 +#define GL_TEXTURE9_ARB 0x84C9 +#define GL_TEXTURE10_ARB 0x84CA +#define GL_TEXTURE11_ARB 0x84CB +#define GL_TEXTURE12_ARB 0x84CC +#define GL_TEXTURE13_ARB 0x84CD +#define GL_TEXTURE14_ARB 0x84CE +#define GL_TEXTURE15_ARB 0x84CF +#define GL_TEXTURE16_ARB 0x84D0 +#define GL_TEXTURE17_ARB 0x84D1 +#define GL_TEXTURE18_ARB 0x84D2 +#define GL_TEXTURE19_ARB 0x84D3 +#define GL_TEXTURE20_ARB 0x84D4 +#define GL_TEXTURE21_ARB 0x84D5 +#define GL_TEXTURE22_ARB 0x84D6 +#define GL_TEXTURE23_ARB 0x84D7 +#define GL_TEXTURE24_ARB 0x84D8 +#define GL_TEXTURE25_ARB 0x84D9 +#define GL_TEXTURE26_ARB 0x84DA +#define GL_TEXTURE27_ARB 0x84DB +#define GL_TEXTURE28_ARB 0x84DC +#define GL_TEXTURE29_ARB 0x84DD +#define GL_TEXTURE30_ARB 0x84DE +#define GL_TEXTURE31_ARB 0x84DF +#define GL_ACTIVE_TEXTURE_ARB 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 +#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 + +GLAPI void GLAPIENTRY glActiveTextureARB(GLenum texture); +GLAPI void GLAPIENTRY glClientActiveTextureARB(GLenum texture); +GLAPI void GLAPIENTRY glMultiTexCoord1dARB(GLenum target, GLdouble s); +GLAPI void GLAPIENTRY glMultiTexCoord1dvARB(GLenum target, const GLdouble *v); +GLAPI void GLAPIENTRY glMultiTexCoord1fARB(GLenum target, GLfloat s); +GLAPI void GLAPIENTRY glMultiTexCoord1fvARB(GLenum target, const GLfloat *v); +GLAPI void GLAPIENTRY glMultiTexCoord1iARB(GLenum target, GLint s); +GLAPI void GLAPIENTRY glMultiTexCoord1ivARB(GLenum target, const GLint *v); +GLAPI void GLAPIENTRY glMultiTexCoord1sARB(GLenum target, GLshort s); +GLAPI void GLAPIENTRY glMultiTexCoord1svARB(GLenum target, const GLshort *v); +GLAPI void GLAPIENTRY glMultiTexCoord2dARB(GLenum target, GLdouble s, GLdouble t); +GLAPI void GLAPIENTRY glMultiTexCoord2dvARB(GLenum target, const GLdouble *v); +GLAPI void GLAPIENTRY glMultiTexCoord2fARB(GLenum target, GLfloat s, GLfloat t); +GLAPI void GLAPIENTRY glMultiTexCoord2fvARB(GLenum target, const GLfloat *v); +GLAPI void GLAPIENTRY glMultiTexCoord2iARB(GLenum target, GLint s, GLint t); +GLAPI void GLAPIENTRY glMultiTexCoord2ivARB(GLenum target, const GLint *v); +GLAPI void GLAPIENTRY glMultiTexCoord2sARB(GLenum target, GLshort s, GLshort t); +GLAPI void GLAPIENTRY glMultiTexCoord2svARB(GLenum target, const GLshort *v); +GLAPI void GLAPIENTRY glMultiTexCoord3dARB(GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI void GLAPIENTRY glMultiTexCoord3dvARB(GLenum target, const GLdouble *v); +GLAPI void GLAPIENTRY glMultiTexCoord3fARB(GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI void GLAPIENTRY glMultiTexCoord3fvARB(GLenum target, const GLfloat *v); +GLAPI void GLAPIENTRY glMultiTexCoord3iARB(GLenum target, GLint s, GLint t, GLint r); +GLAPI void GLAPIENTRY glMultiTexCoord3ivARB(GLenum target, const GLint *v); +GLAPI void GLAPIENTRY glMultiTexCoord3sARB(GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI void GLAPIENTRY glMultiTexCoord3svARB(GLenum target, const GLshort *v); +GLAPI void GLAPIENTRY glMultiTexCoord4dARB(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI void GLAPIENTRY glMultiTexCoord4dvARB(GLenum target, const GLdouble *v); +GLAPI void GLAPIENTRY glMultiTexCoord4fARB(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI void GLAPIENTRY glMultiTexCoord4fvARB(GLenum target, const GLfloat *v); +GLAPI void GLAPIENTRY glMultiTexCoord4iARB(GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI void GLAPIENTRY glMultiTexCoord4ivARB(GLenum target, const GLint *v); +GLAPI void GLAPIENTRY glMultiTexCoord4sARB(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI void GLAPIENTRY glMultiTexCoord4svARB(GLenum target, const GLshort *v); + +typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v); + +#endif /* GL_ARB_multitexture */ + + + +/* + * Define this token if you want "old-style" header file behaviour (extensions + * defined in gl.h). Otherwise, extensions will be included from glext.h. + */ +#if !defined(NO_SDL_GLEXT) && !defined(GL_GLEXT_LEGACY) +#include "SDL_opengl_glext.h" +#endif /* GL_GLEXT_LEGACY */ + + + +/********************************************************************** + * Begin system-specific stuff + */ +#if defined(PRAGMA_EXPORT_SUPPORTED) +#pragma export off +#endif + +/* + * End system-specific stuff + **********************************************************************/ + + +#ifdef __cplusplus +} +#endif + +#endif /* __gl_h_ */ + +#endif /* !__IPHONEOS__ */ + +#endif /* SDL_opengl_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_opengl_glext.h b/third_party/SDL2/include/SDL_opengl_glext.h new file mode 100644 index 00000000000..ff6ad12cef0 --- /dev/null +++ b/third_party/SDL2/include/SDL_opengl_glext.h @@ -0,0 +1,13213 @@ +/* SDL modified the include guard to be compatible with Mesa and Apple include guards: + * - Mesa uses: __gl_glext_h_ + * - Apple uses: __glext_h_ */ +#if !defined(__glext_h_) && !defined(__gl_glext_h_) +#define __glext_h_ 1 +#define __gl_glext_h_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright 2013-2020 The Khronos Group Inc. +** SPDX-License-Identifier: MIT +** +** This header is generated from the Khronos OpenGL / OpenGL ES XML +** API Registry. The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** https://github.com/KhronosGroup/OpenGL-Registry +*/ + +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include +#endif + +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif +#ifndef GLAPI +#define GLAPI extern +#endif + +#define GL_GLEXT_VERSION 20220530 + +/*#include */ +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2018 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Khronos platform-specific types and definitions. + * + * The master copy of khrplatform.h is maintained in the Khronos EGL + * Registry repository at https://github.com/KhronosGroup/EGL-Registry + * The last semantic modification to khrplatform.h was at commit ID: + * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 + * + * Adopters may modify this file to suit their platform. Adopters are + * encouraged to submit platform specific modifications to the Khronos + * group so that they can be included in future versions of this file. + * Please submit changes by filing pull requests or issues on + * the EGL Registry repository linked above. + * + * + * See the Implementer's Guidelines for information about where this file + * should be located on your system and for more details of its use: + * http://www.khronos.org/registry/implementers_guide.pdf + * + * This file should be included as + * #include + * by Khronos client API header files that use its types and defines. + * + * The types in khrplatform.h should only be used to define API-specific types. + * + * Types defined in khrplatform.h: + * khronos_int8_t signed 8 bit + * khronos_uint8_t unsigned 8 bit + * khronos_int16_t signed 16 bit + * khronos_uint16_t unsigned 16 bit + * khronos_int32_t signed 32 bit + * khronos_uint32_t unsigned 32 bit + * khronos_int64_t signed 64 bit + * khronos_uint64_t unsigned 64 bit + * khronos_intptr_t signed same number of bits as a pointer + * khronos_uintptr_t unsigned same number of bits as a pointer + * khronos_ssize_t signed size + * khronos_usize_t unsigned size + * khronos_float_t signed 32 bit floating point + * khronos_time_ns_t unsigned 64 bit time in nanoseconds + * khronos_utime_nanoseconds_t unsigned time interval or absolute time in + * nanoseconds + * khronos_stime_nanoseconds_t signed time interval in nanoseconds + * khronos_boolean_enum_t enumerated boolean type. This should + * only be used as a base type when a client API's boolean type is + * an enum. Client APIs which use an integer or other type for + * booleans cannot use this as the base type for their boolean. + * + * Tokens defined in khrplatform.h: + * + * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. + * + * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. + * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. + * + * Calling convention macros defined in this file: + * KHRONOS_APICALL + * KHRONOS_APIENTRY + * KHRONOS_APIATTRIBUTES + * + * These may be used in function prototypes as: + * + * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( + * int arg1, + * int arg2) KHRONOS_APIATTRIBUTES; + */ + +#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) +# define KHRONOS_STATIC 1 +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(KHRONOS_STATIC) + /* If the preprocessor constant KHRONOS_STATIC is defined, make the + * header compatible with static linking. */ +# define KHRONOS_APICALL +#elif defined(_WIN32) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#elif defined(__ANDROID__) +# define KHRONOS_APICALL __attribute__((visibility("default"))) +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 +/* + * To support platform where unsigned long cannot be used interchangeably with + * inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t. + * Ideally, we could just use (u)intptr_t everywhere, but this could result in + * ABI breakage if khronos_uintptr_t is changed from unsigned long to + * unsigned long long or similar (this results in different C++ name mangling). + * To avoid changes for existing platforms, we restrict usage of intptr_t to + * platforms where the size of a pointer is larger than the size of long. + */ +#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__) +#if __SIZEOF_POINTER__ > __SIZEOF_LONG__ +#define KHRONOS_USE_INTPTR_T +#endif +#endif + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +/* + * Types that differ between LLP64 and LP64 architectures - in LLP64, + * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears + * to be the only LLP64 architecture in current use. + */ +#ifdef KHRONOS_USE_INTPTR_T +typedef intptr_t khronos_intptr_t; +typedef uintptr_t khronos_uintptr_t; +#elif defined(_WIN64) +typedef signed long long int khronos_intptr_t; +typedef unsigned long long int khronos_uintptr_t; +#else +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +#endif + +#if defined(_WIN64) +typedef signed long long int khronos_ssize_t; +typedef unsigned long long int khronos_usize_t; +#else +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; +#endif + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + +/* + * Dummy value used to pad enum types to 32 bits. + */ +#ifndef KHRONOS_MAX_ENUM +#define KHRONOS_MAX_ENUM 0x7FFFFFFF +#endif + +/* + * Enumerated boolean type + * + * Values other than zero should be considered to be true. Therefore + * comparisons should not be made against KHRONOS_TRUE. + */ +typedef enum { + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +} khronos_boolean_enum_t; + +#endif /* __khrplatform_h_ */ + +/* Generated C header for: + * API: gl + * Profile: compatibility + * Versions considered: .* + * Versions emitted: 1\.[2-9]|[234]\.[0-9] + * Default extensions included: gl + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ + +#ifndef GL_VERSION_1_2 +#define GL_VERSION_1_2 1 +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_RESCALE_NORMAL 0x803A +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +GLAPI void APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif +#endif /* GL_VERSION_1_2 */ + +#ifndef GL_VERSION_1_3 +#define GL_VERSION_1_3 1 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_MULTISAMPLE_BIT 0x20000000 +#define GL_NORMAL_MAP 0x8511 +#define GL_REFLECTION_MAP 0x8512 +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_RGB 0x8582 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_SUBTRACT 0x84E7 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, void *img); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTexture (GLenum texture); +GLAPI void APIENTRY glSampleCoverage (GLfloat value, GLboolean invert); +GLAPI void APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage1D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glGetCompressedTexImage (GLenum target, GLint level, void *img); +GLAPI void APIENTRY glClientActiveTexture (GLenum texture); +GLAPI void APIENTRY glMultiTexCoord1d (GLenum target, GLdouble s); +GLAPI void APIENTRY glMultiTexCoord1dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord1f (GLenum target, GLfloat s); +GLAPI void APIENTRY glMultiTexCoord1fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord1i (GLenum target, GLint s); +GLAPI void APIENTRY glMultiTexCoord1iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord1s (GLenum target, GLshort s); +GLAPI void APIENTRY glMultiTexCoord1sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord2d (GLenum target, GLdouble s, GLdouble t); +GLAPI void APIENTRY glMultiTexCoord2dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord2f (GLenum target, GLfloat s, GLfloat t); +GLAPI void APIENTRY glMultiTexCoord2fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord2i (GLenum target, GLint s, GLint t); +GLAPI void APIENTRY glMultiTexCoord2iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord2s (GLenum target, GLshort s, GLshort t); +GLAPI void APIENTRY glMultiTexCoord2sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord3d (GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI void APIENTRY glMultiTexCoord3dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord3f (GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI void APIENTRY glMultiTexCoord3fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord3i (GLenum target, GLint s, GLint t, GLint r); +GLAPI void APIENTRY glMultiTexCoord3iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord3s (GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI void APIENTRY glMultiTexCoord3sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord4d (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI void APIENTRY glMultiTexCoord4dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI void APIENTRY glMultiTexCoord4fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord4i (GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI void APIENTRY glMultiTexCoord4iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord4s (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI void APIENTRY glMultiTexCoord4sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *m); +GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *m); +GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *m); +GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *m); +#endif +#endif /* GL_VERSION_1_3 */ + +#ifndef GL_VERSION_1_4 +#define GL_VERSION_1_4 1 +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FOG_COORDINATE 0x8451 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_COLOR_SUM 0x8458 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_COMPARE_R_TO_TEXTURE 0x884E +#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_EQUATION 0x8009 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_FUNC_SUBTRACT 0x800A +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord); +typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord); +typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord); +typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +GLAPI void APIENTRY glMultiDrawArrays (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +GLAPI void APIENTRY glMultiDrawElements (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +GLAPI void APIENTRY glPointParameterf (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glPointParameteri (GLenum pname, GLint param); +GLAPI void APIENTRY glPointParameteriv (GLenum pname, const GLint *params); +GLAPI void APIENTRY glFogCoordf (GLfloat coord); +GLAPI void APIENTRY glFogCoordfv (const GLfloat *coord); +GLAPI void APIENTRY glFogCoordd (GLdouble coord); +GLAPI void APIENTRY glFogCoorddv (const GLdouble *coord); +GLAPI void APIENTRY glFogCoordPointer (GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glSecondaryColor3b (GLbyte red, GLbyte green, GLbyte blue); +GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *v); +GLAPI void APIENTRY glSecondaryColor3d (GLdouble red, GLdouble green, GLdouble blue); +GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *v); +GLAPI void APIENTRY glSecondaryColor3f (GLfloat red, GLfloat green, GLfloat blue); +GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *v); +GLAPI void APIENTRY glSecondaryColor3i (GLint red, GLint green, GLint blue); +GLAPI void APIENTRY glSecondaryColor3iv (const GLint *v); +GLAPI void APIENTRY glSecondaryColor3s (GLshort red, GLshort green, GLshort blue); +GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *v); +GLAPI void APIENTRY glSecondaryColor3ub (GLubyte red, GLubyte green, GLubyte blue); +GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *v); +GLAPI void APIENTRY glSecondaryColor3ui (GLuint red, GLuint green, GLuint blue); +GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *v); +GLAPI void APIENTRY glSecondaryColor3us (GLushort red, GLushort green, GLushort blue); +GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *v); +GLAPI void APIENTRY glSecondaryColorPointer (GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glWindowPos2d (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dv (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2f (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fv (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2i (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2iv (const GLint *v); +GLAPI void APIENTRY glWindowPos2s (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2sv (const GLshort *v); +GLAPI void APIENTRY glWindowPos3d (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dv (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3f (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fv (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3i (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3iv (const GLint *v); +GLAPI void APIENTRY glWindowPos3s (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3sv (const GLshort *v); +GLAPI void APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI void APIENTRY glBlendEquation (GLenum mode); +#endif +#endif /* GL_VERSION_1_4 */ + +#ifndef GL_VERSION_1_5 +#define GL_VERSION_1_5 1 +typedef khronos_ssize_t GLsizeiptr; +typedef khronos_intptr_t GLintptr; +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_READ_ONLY 0x88B8 +#define GL_WRITE_ONLY 0x88B9 +#define GL_READ_WRITE 0x88BA +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_SAMPLES_PASSED 0x8914 +#define GL_SRC1_ALPHA 0x8589 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_FOG_COORD_SRC 0x8450 +#define GL_FOG_COORD 0x8451 +#define GL_CURRENT_FOG_COORD 0x8453 +#define GL_FOG_COORD_ARRAY_TYPE 0x8454 +#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORD_ARRAY_POINTER 0x8456 +#define GL_FOG_COORD_ARRAY 0x8457 +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D +#define GL_SRC0_RGB 0x8580 +#define GL_SRC1_RGB 0x8581 +#define GL_SRC2_RGB 0x8582 +#define GL_SRC0_ALPHA 0x8588 +#define GL_SRC2_ALPHA 0x858A +typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, void *data); +typedef void *(APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueries (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteQueries (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsQuery (GLuint id); +GLAPI void APIENTRY glBeginQuery (GLenum target, GLuint id); +GLAPI void APIENTRY glEndQuery (GLenum target); +GLAPI void APIENTRY glGetQueryiv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectiv (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params); +GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer); +GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); +GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); +GLAPI GLboolean APIENTRY glIsBuffer (GLuint buffer); +GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void APIENTRY glGetBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, void *data); +GLAPI void *APIENTRY glMapBuffer (GLenum target, GLenum access); +GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum target); +GLAPI void APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetBufferPointerv (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_VERSION_1_5 */ + +#ifndef GL_VERSION_2_0 +#define GL_VERSION_2_0 1 +typedef char GLchar; +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_SHADER_TYPE 0x8B4F +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_DELETE_STATUS 0x8B80 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_POINT_SPRITE 0x8861 +#define GL_COORD_REPLACE 0x8862 +#define GL_MAX_TEXTURE_COORDS 0x8871 +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); +typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); +typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); +typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); +typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); +typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); +typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI void APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask); +GLAPI void APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask); +GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name); +GLAPI void APIENTRY glCompileShader (GLuint shader); +GLAPI GLuint APIENTRY glCreateProgram (void); +GLAPI GLuint APIENTRY glCreateShader (GLenum type); +GLAPI void APIENTRY glDeleteProgram (GLuint program); +GLAPI void APIENTRY glDeleteShader (GLuint shader); +GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index); +GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index); +GLAPI void APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params); +GLAPI void APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params); +GLAPI void APIENTRY glGetVertexAttribdv (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); +GLAPI GLboolean APIENTRY glIsProgram (GLuint program); +GLAPI GLboolean APIENTRY glIsShader (GLuint shader); +GLAPI void APIENTRY glLinkProgram (GLuint program); +GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +GLAPI void APIENTRY glUseProgram (GLuint program); +GLAPI void APIENTRY glUniform1f (GLint location, GLfloat v0); +GLAPI void APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glUniform1i (GLint location, GLint v0); +GLAPI void APIENTRY glUniform2i (GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glValidateProgram (GLuint program); +GLAPI void APIENTRY glVertexAttrib1d (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1f (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1s (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2d (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2s (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3d (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3s (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4Niv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4Nub (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttrib4bv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4s (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4usv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +#endif +#endif /* GL_VERSION_2_0 */ + +#ifndef GL_VERSION_2_1 +#define GL_VERSION_2_1 1 +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB_ALPHA 0x8C42 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_COMPRESSED_SRGB 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 +#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F +#define GL_SLUMINANCE_ALPHA 0x8C44 +#define GL_SLUMINANCE8_ALPHA8 0x8C45 +#define GL_SLUMINANCE 0x8C46 +#define GL_SLUMINANCE8 0x8C47 +#define GL_COMPRESSED_SLUMINANCE 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#endif +#endif /* GL_VERSION_2_1 */ + +#ifndef GL_VERSION_3_0 +#define GL_VERSION_3_0 1 +typedef khronos_uint16_t GLhalf; +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_CLIP_DISTANCE0 0x3000 +#define GL_CLIP_DISTANCE1 0x3001 +#define GL_CLIP_DISTANCE2 0x3002 +#define GL_CLIP_DISTANCE3 0x3003 +#define GL_CLIP_DISTANCE4 0x3004 +#define GL_CLIP_DISTANCE5 0x3005 +#define GL_CLIP_DISTANCE6 0x3006 +#define GL_CLIP_DISTANCE7 0x3007 +#define GL_MAX_CLIP_DISTANCES 0x0D32 +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_CONTEXT_FLAGS 0x821E +#define GL_COMPRESSED_RED 0x8225 +#define GL_COMPRESSED_RG 0x8226 +#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 +#define GL_RGBA32F 0x8814 +#define GL_RGB32F 0x8815 +#define GL_RGBA16F 0x881A +#define GL_RGB16F 0x881B +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_CLAMP_READ_COLOR 0x891C +#define GL_FIXED_ONLY 0x891D +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_TEXTURE_1D_ARRAY 0x8C18 +#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B +#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_RGB9_E5 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_TEXTURE_SHARED_SIZE 0x8C3F +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_PRIMITIVES_GENERATED 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_RGBA32UI 0x8D70 +#define GL_RGB32UI 0x8D71 +#define GL_RGBA16UI 0x8D76 +#define GL_RGB16UI 0x8D77 +#define GL_RGBA8UI 0x8D7C +#define GL_RGB8UI 0x8D7D +#define GL_RGBA32I 0x8D82 +#define GL_RGB32I 0x8D83 +#define GL_RGBA16I 0x8D88 +#define GL_RGB16I 0x8D89 +#define GL_RGBA8I 0x8D8E +#define GL_RGB8I 0x8D8F +#define GL_RED_INTEGER 0x8D94 +#define GL_GREEN_INTEGER 0x8D95 +#define GL_BLUE_INTEGER 0x8D96 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_BGR_INTEGER 0x8D9A +#define GL_BGRA_INTEGER 0x8D9B +#define GL_SAMPLER_1D_ARRAY 0x8DC0 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_INT_SAMPLER_1D 0x8DC9 +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_QUERY_WAIT 0x8E13 +#define GL_QUERY_NO_WAIT 0x8E14 +#define GL_QUERY_BY_REGION_WAIT 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE 0x88F1 +#define GL_TEXTURE_RED_TYPE 0x8C10 +#define GL_TEXTURE_GREEN_TYPE 0x8C11 +#define GL_TEXTURE_BLUE_TYPE 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE 0x8C13 +#define GL_TEXTURE_DEPTH_TYPE 0x8C16 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_COLOR_ATTACHMENT16 0x8CF0 +#define GL_COLOR_ATTACHMENT17 0x8CF1 +#define GL_COLOR_ATTACHMENT18 0x8CF2 +#define GL_COLOR_ATTACHMENT19 0x8CF3 +#define GL_COLOR_ATTACHMENT20 0x8CF4 +#define GL_COLOR_ATTACHMENT21 0x8CF5 +#define GL_COLOR_ATTACHMENT22 0x8CF6 +#define GL_COLOR_ATTACHMENT23 0x8CF7 +#define GL_COLOR_ATTACHMENT24 0x8CF8 +#define GL_COLOR_ATTACHMENT25 0x8CF9 +#define GL_COLOR_ATTACHMENT26 0x8CFA +#define GL_COLOR_ATTACHMENT27 0x8CFB +#define GL_COLOR_ATTACHMENT28 0x8CFC +#define GL_COLOR_ATTACHMENT29 0x8CFD +#define GL_COLOR_ATTACHMENT30 0x8CFE +#define GL_COLOR_ATTACHMENT31 0x8CFF +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_STENCIL_ATTACHMENT 0x8D20 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_STENCIL_INDEX1 0x8D46 +#define GL_STENCIL_INDEX4 0x8D47 +#define GL_STENCIL_INDEX8 0x8D48 +#define GL_STENCIL_INDEX16 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_INDEX 0x8222 +#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE 0x8C15 +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_HALF_FLOAT 0x140B +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_COMPRESSED_RED_RGTC1 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC +#define GL_COMPRESSED_RG_RGTC2 0x8DBD +#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE +#define GL_RG 0x8227 +#define GL_RG_INTEGER 0x8228 +#define GL_R8 0x8229 +#define GL_R16 0x822A +#define GL_RG8 0x822B +#define GL_RG16 0x822C +#define GL_R16F 0x822D +#define GL_R32F 0x822E +#define GL_RG16F 0x822F +#define GL_RG32F 0x8230 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_CLAMP_VERTEX_COLOR 0x891A +#define GL_CLAMP_FRAGMENT_COLOR 0x891B +#define GL_ALPHA_INTEGER 0x8D97 +typedef void (APIENTRYP PFNGLCOLORMASKIPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data); +typedef void (APIENTRYP PFNGLENABLEIPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEIPROC) (GLenum target, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLCLAMPCOLORPROC) (GLenum target, GLenum clamp); +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC) (GLuint id, GLenum mode); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC) (void); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint index, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC) (GLuint index, GLint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC) (GLuint index, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC) (GLuint index, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC) (GLuint index, GLuint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC) (GLuint index, GLuint x, GLuint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC) (GLuint program, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC) (GLuint program, GLuint color, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORM1UIPROC) (GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLUNIFORM2UIPROC) (GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLUNIFORM3UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLUNIFORM4UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC) (GLenum buffer, GLint drawbuffer, const GLint *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC) (GLenum buffer, GLint drawbuffer, const GLuint *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC) (GLenum buffer, GLint drawbuffer, const GLfloat *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC) (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer); +typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer); +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer); +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers); +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target); +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void *(APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC) (GLuint array); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorMaski (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +GLAPI void APIENTRY glGetBooleani_v (GLenum target, GLuint index, GLboolean *data); +GLAPI void APIENTRY glGetIntegeri_v (GLenum target, GLuint index, GLint *data); +GLAPI void APIENTRY glEnablei (GLenum target, GLuint index); +GLAPI void APIENTRY glDisablei (GLenum target, GLuint index); +GLAPI GLboolean APIENTRY glIsEnabledi (GLenum target, GLuint index); +GLAPI void APIENTRY glBeginTransformFeedback (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedback (void); +GLAPI void APIENTRY glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferBase (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryings (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +GLAPI void APIENTRY glGetTransformFeedbackVarying (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glClampColor (GLenum target, GLenum clamp); +GLAPI void APIENTRY glBeginConditionalRender (GLuint id, GLenum mode); +GLAPI void APIENTRY glEndConditionalRender (void); +GLAPI void APIENTRY glVertexAttribIPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribIiv (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribIuiv (GLuint index, GLenum pname, GLuint *params); +GLAPI void APIENTRY glVertexAttribI1i (GLuint index, GLint x); +GLAPI void APIENTRY glVertexAttribI2i (GLuint index, GLint x, GLint y); +GLAPI void APIENTRY glVertexAttribI3i (GLuint index, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexAttribI4i (GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexAttribI1ui (GLuint index, GLuint x); +GLAPI void APIENTRY glVertexAttribI2ui (GLuint index, GLuint x, GLuint y); +GLAPI void APIENTRY glVertexAttribI3ui (GLuint index, GLuint x, GLuint y, GLuint z); +GLAPI void APIENTRY glVertexAttribI4ui (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glVertexAttribI1iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI2iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI3iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI4iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI1uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI2uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI3uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4bv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttribI4sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttribI4ubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribI4usv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glGetUniformuiv (GLuint program, GLint location, GLuint *params); +GLAPI void APIENTRY glBindFragDataLocation (GLuint program, GLuint color, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glUniform1ui (GLint location, GLuint v0); +GLAPI void APIENTRY glUniform2ui (GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glUniform3ui (GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glUniform4ui (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glUniform1uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform2uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform3uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform4uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glTexParameterIiv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTexParameterIuiv (GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTexParameterIiv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTexParameterIuiv (GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glClearBufferiv (GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI void APIENTRY glClearBufferuiv (GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI void APIENTRY glClearBufferfv (GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI void APIENTRY glClearBufferfi (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index); +GLAPI GLboolean APIENTRY glIsRenderbuffer (GLuint renderbuffer); +GLAPI void APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers); +GLAPI void APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI GLboolean APIENTRY glIsFramebuffer (GLuint framebuffer); +GLAPI void APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer); +GLAPI void APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers); +GLAPI void APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers); +GLAPI GLenum APIENTRY glCheckFramebufferStatus (GLenum target); +GLAPI void APIENTRY glFramebufferTexture1D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture3D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateMipmap (GLenum target); +GLAPI void APIENTRY glBlitFramebuffer (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI void APIENTRY glRenderbufferStorageMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glFramebufferTextureLayer (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void *APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI void APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glBindVertexArray (GLuint array); +GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays); +GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); +GLAPI GLboolean APIENTRY glIsVertexArray (GLuint array); +#endif +#endif /* GL_VERSION_3_0 */ + +#ifndef GL_VERSION_3_1 +#define GL_VERSION_3_1 1 +#define GL_SAMPLER_2D_RECT 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 +#define GL_SAMPLER_BUFFER 0x8DC2 +#define GL_INT_SAMPLER_2D_RECT 0x8DCD +#define GL_INT_SAMPLER_BUFFER 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 +#define GL_TEXTURE_BUFFER 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D +#define GL_TEXTURE_RECTANGLE 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_R16_SNORM 0x8F98 +#define GL_RG16_SNORM 0x8F99 +#define GL_RGB16_SNORM 0x8F9A +#define GL_RGBA16_SNORM 0x8F9B +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART 0x8F9D +#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFFu +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); +typedef void (APIENTRYP PFNGLTEXBUFFERPROC) (GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC) (GLuint index); +typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC) (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); +typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); +typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +GLAPI void APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); +GLAPI void APIENTRY glTexBuffer (GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glPrimitiveRestartIndex (GLuint index); +GLAPI void APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); +GLAPI void APIENTRY glGetActiveUniformsiv (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetActiveUniformName (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); +GLAPI GLuint APIENTRY glGetUniformBlockIndex (GLuint program, const GLchar *uniformBlockName); +GLAPI void APIENTRY glGetActiveUniformBlockiv (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetActiveUniformBlockName (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); +GLAPI void APIENTRY glUniformBlockBinding (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +#endif +#endif /* GL_VERSION_3_1 */ + +#ifndef GL_VERSION_3_2 +#define GL_VERSION_3_2 1 +typedef struct __GLsync *GLsync; +typedef khronos_uint64_t GLuint64; +typedef khronos_int64_t GLint64; +#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_LINES_ADJACENCY 0x000A +#define GL_LINE_STRIP_ADJACENCY 0x000B +#define GL_TRIANGLES_ADJACENCY 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D +#define GL_PROGRAM_POINT_SIZE 0x8642 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 +#define GL_GEOMETRY_SHADER 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT 0x8916 +#define GL_GEOMETRY_INPUT_TYPE 0x8917 +#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_CONTEXT_PROFILE_MASK 0x9126 +#define GL_DEPTH_CLAMP 0x864F +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION 0x8E4D +#define GL_LAST_VERTEX_CONVENTION 0x8E4E +#define GL_PROVOKING_VERTEX 0x8E4F +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_OBJECT_TYPE 0x9112 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_STATUS 0x9114 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_UNSIGNALED 0x9118 +#define GL_SIGNALED 0x9119 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_CONDITION_SATISFIED 0x911C +#define GL_WAIT_FAILED 0x911D +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_SAMPLE_POSITION 0x8E50 +#define GL_SAMPLE_MASK 0x8E51 +#define GL_SAMPLE_MASK_VALUE 0x8E52 +#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 +#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 +#define GL_TEXTURE_SAMPLES 0x9106 +#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D +#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E +#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F +#define GL_MAX_INTEGER_SAMPLES 0x9110 +typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC) (GLenum mode); +typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC) (GLenum condition, GLbitfield flags); +typedef GLboolean (APIENTRYP PFNGLISSYNCPROC) (GLsync sync); +typedef void (APIENTRYP PFNGLDELETESYNCPROC) (GLsync sync); +typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (APIENTRYP PFNGLWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (APIENTRYP PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64 *data); +typedef void (APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei count, GLsizei *length, GLint *values); +typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum target, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat *val); +typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint maskNumber, GLbitfield mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI void APIENTRY glDrawRangeElementsBaseVertex (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI void APIENTRY glDrawElementsInstancedBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +GLAPI void APIENTRY glMultiDrawElementsBaseVertex (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +GLAPI void APIENTRY glProvokingVertex (GLenum mode); +GLAPI GLsync APIENTRY glFenceSync (GLenum condition, GLbitfield flags); +GLAPI GLboolean APIENTRY glIsSync (GLsync sync); +GLAPI void APIENTRY glDeleteSync (GLsync sync); +GLAPI GLenum APIENTRY glClientWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI void APIENTRY glWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI void APIENTRY glGetInteger64v (GLenum pname, GLint64 *data); +GLAPI void APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei count, GLsizei *length, GLint *values); +GLAPI void APIENTRY glGetInteger64i_v (GLenum target, GLuint index, GLint64 *data); +GLAPI void APIENTRY glGetBufferParameteri64v (GLenum target, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glFramebufferTexture (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glTexImage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTexImage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glGetMultisamplefv (GLenum pname, GLuint index, GLfloat *val); +GLAPI void APIENTRY glSampleMaski (GLuint maskNumber, GLbitfield mask); +#endif +#endif /* GL_VERSION_3_2 */ + +#ifndef GL_VERSION_3_3 +#define GL_VERSION_3_3 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_SRC1_COLOR 0x88F9 +#define GL_ONE_MINUS_SRC1_COLOR 0x88FA +#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_SAMPLER_BINDING 0x8919 +#define GL_RGB10_A2UI 0x906F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 +#define GL_TIME_ELAPSED 0x88BF +#define GL_TIMESTAMP 0x8E28 +#define GL_INT_2_10_10_10_REV 0x8D9F +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers); +typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers); +typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC) (GLuint sampler); +typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, const GLuint *param); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC) (GLuint id, GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC) (GLuint id, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC) (GLuint id, GLenum pname, GLuint64 *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP2UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP2UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP3UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP3UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP4UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP4UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLNORMALP3UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLNORMALP3UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLCOLORP3UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLCOLORP3UIVPROC) (GLenum type, const GLuint *color); +typedef void (APIENTRYP PFNGLCOLORP4UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLCOLORP4UIVPROC) (GLenum type, const GLuint *color); +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC) (GLenum type, const GLuint *color); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindFragDataLocationIndexed (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataIndex (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers); +GLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers); +GLAPI GLboolean APIENTRY glIsSampler (GLuint sampler); +GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler); +GLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param); +GLAPI void APIENTRY glSamplerParameteriv (GLuint sampler, GLenum pname, const GLint *param); +GLAPI void APIENTRY glSamplerParameterf (GLuint sampler, GLenum pname, GLfloat param); +GLAPI void APIENTRY glSamplerParameterfv (GLuint sampler, GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glSamplerParameterIiv (GLuint sampler, GLenum pname, const GLint *param); +GLAPI void APIENTRY glSamplerParameterIuiv (GLuint sampler, GLenum pname, const GLuint *param); +GLAPI void APIENTRY glGetSamplerParameteriv (GLuint sampler, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSamplerParameterIiv (GLuint sampler, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSamplerParameterfv (GLuint sampler, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetSamplerParameterIuiv (GLuint sampler, GLenum pname, GLuint *params); +GLAPI void APIENTRY glQueryCounter (GLuint id, GLenum target); +GLAPI void APIENTRY glGetQueryObjecti64v (GLuint id, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetQueryObjectui64v (GLuint id, GLenum pname, GLuint64 *params); +GLAPI void APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor); +GLAPI void APIENTRY glVertexAttribP1ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP1uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP2ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP2uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP3ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP3uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP4ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP4uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexP2ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP2uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glVertexP3ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP3uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glVertexP4ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP4uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glTexCoordP1ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP1uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP2ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP2uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP3ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP3uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP4ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP4uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP1ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP1uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP2ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP2uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP3ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP3uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP4ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP4uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glNormalP3ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glNormalP3uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glColorP3ui (GLenum type, GLuint color); +GLAPI void APIENTRY glColorP3uiv (GLenum type, const GLuint *color); +GLAPI void APIENTRY glColorP4ui (GLenum type, GLuint color); +GLAPI void APIENTRY glColorP4uiv (GLenum type, const GLuint *color); +GLAPI void APIENTRY glSecondaryColorP3ui (GLenum type, GLuint color); +GLAPI void APIENTRY glSecondaryColorP3uiv (GLenum type, const GLuint *color); +#endif +#endif /* GL_VERSION_3_3 */ + +#ifndef GL_VERSION_4_0 +#define GL_VERSION_4_0 1 +#define GL_SAMPLE_SHADING 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37 +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F +#define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B +#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F +#define GL_DRAW_INDIRECT_BUFFER 0x8F3F +#define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 +#define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F +#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A +#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B +#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C +#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D +#define GL_MAX_VERTEX_STREAMS 0x8E71 +#define GL_DOUBLE_VEC2 0x8FFC +#define GL_DOUBLE_VEC3 0x8FFD +#define GL_DOUBLE_VEC4 0x8FFE +#define GL_DOUBLE_MAT2 0x8F46 +#define GL_DOUBLE_MAT3 0x8F47 +#define GL_DOUBLE_MAT4 0x8F48 +#define GL_DOUBLE_MAT2x3 0x8F49 +#define GL_DOUBLE_MAT2x4 0x8F4A +#define GL_DOUBLE_MAT3x2 0x8F4B +#define GL_DOUBLE_MAT3x4 0x8F4C +#define GL_DOUBLE_MAT4x2 0x8F4D +#define GL_DOUBLE_MAT4x3 0x8F4E +#define GL_ACTIVE_SUBROUTINES 0x8DE5 +#define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6 +#define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47 +#define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48 +#define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49 +#define GL_MAX_SUBROUTINES 0x8DE7 +#define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8 +#define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A +#define GL_COMPATIBLE_SUBROUTINES 0x8E4B +#define GL_PATCHES 0x000E +#define GL_PATCH_VERTICES 0x8E72 +#define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 +#define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 +#define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 +#define GL_TESS_GEN_MODE 0x8E76 +#define GL_TESS_GEN_SPACING 0x8E77 +#define GL_TESS_GEN_VERTEX_ORDER 0x8E78 +#define GL_TESS_GEN_POINT_MODE 0x8E79 +#define GL_ISOLINES 0x8E7A +#define GL_FRACTIONAL_ODD 0x8E7B +#define GL_FRACTIONAL_EVEN 0x8E7C +#define GL_MAX_PATCH_VERTICES 0x8E7D +#define GL_MAX_TESS_GEN_LEVEL 0x8E7E +#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F +#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 +#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 +#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 +#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 +#define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84 +#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 +#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 +#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 +#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A +#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C +#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D +#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E +#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 +#define GL_TESS_EVALUATION_SHADER 0x8E87 +#define GL_TESS_CONTROL_SHADER 0x8E88 +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23 +#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 +#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC) (GLfloat value); +typedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLBLENDFUNCIPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect); +typedef void (APIENTRYP PFNGLUNIFORM1DPROC) (GLint location, GLdouble x); +typedef void (APIENTRYP PFNGLUNIFORM2DPROC) (GLint location, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLUNIFORM3DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLUNIFORM4DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLUNIFORM1DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM2DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM3DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM4DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLGETUNIFORMDVPROC) (GLuint program, GLint location, GLdouble *params); +typedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC) (GLuint program, GLenum shadertype, const GLchar *name); +typedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC) (GLuint program, GLenum shadertype, const GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC) (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC) (GLenum shadertype, GLsizei count, const GLuint *indices); +typedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC) (GLenum shadertype, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC) (GLuint program, GLenum shadertype, GLenum pname, GLint *values); +typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC) (GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC) (GLenum pname, const GLfloat *values); +typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint *ids); +typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id); +typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC) (GLenum mode, GLuint id); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC) (GLenum mode, GLuint id, GLuint stream); +typedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC) (GLenum target, GLuint index, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMinSampleShading (GLfloat value); +GLAPI void APIENTRY glBlendEquationi (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparatei (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glBlendFunci (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparatei (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GLAPI void APIENTRY glDrawArraysIndirect (GLenum mode, const void *indirect); +GLAPI void APIENTRY glDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect); +GLAPI void APIENTRY glUniform1d (GLint location, GLdouble x); +GLAPI void APIENTRY glUniform2d (GLint location, GLdouble x, GLdouble y); +GLAPI void APIENTRY glUniform3d (GLint location, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glUniform4d (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glUniform1dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform2dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform3dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform4dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glGetUniformdv (GLuint program, GLint location, GLdouble *params); +GLAPI GLint APIENTRY glGetSubroutineUniformLocation (GLuint program, GLenum shadertype, const GLchar *name); +GLAPI GLuint APIENTRY glGetSubroutineIndex (GLuint program, GLenum shadertype, const GLchar *name); +GLAPI void APIENTRY glGetActiveSubroutineUniformiv (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); +GLAPI void APIENTRY glGetActiveSubroutineUniformName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glGetActiveSubroutineName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glUniformSubroutinesuiv (GLenum shadertype, GLsizei count, const GLuint *indices); +GLAPI void APIENTRY glGetUniformSubroutineuiv (GLenum shadertype, GLint location, GLuint *params); +GLAPI void APIENTRY glGetProgramStageiv (GLuint program, GLenum shadertype, GLenum pname, GLint *values); +GLAPI void APIENTRY glPatchParameteri (GLenum pname, GLint value); +GLAPI void APIENTRY glPatchParameterfv (GLenum pname, const GLfloat *values); +GLAPI void APIENTRY glBindTransformFeedback (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteTransformFeedbacks (GLsizei n, const GLuint *ids); +GLAPI void APIENTRY glGenTransformFeedbacks (GLsizei n, GLuint *ids); +GLAPI GLboolean APIENTRY glIsTransformFeedback (GLuint id); +GLAPI void APIENTRY glPauseTransformFeedback (void); +GLAPI void APIENTRY glResumeTransformFeedback (void); +GLAPI void APIENTRY glDrawTransformFeedback (GLenum mode, GLuint id); +GLAPI void APIENTRY glDrawTransformFeedbackStream (GLenum mode, GLuint id, GLuint stream); +GLAPI void APIENTRY glBeginQueryIndexed (GLenum target, GLuint index, GLuint id); +GLAPI void APIENTRY glEndQueryIndexed (GLenum target, GLuint index); +GLAPI void APIENTRY glGetQueryIndexediv (GLenum target, GLuint index, GLenum pname, GLint *params); +#endif +#endif /* GL_VERSION_4_0 */ + +#ifndef GL_VERSION_4_1 +#define GL_VERSION_4_1 1 +#define GL_FIXED 0x140C +#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B +#define GL_LOW_FLOAT 0x8DF0 +#define GL_MEDIUM_FLOAT 0x8DF1 +#define GL_HIGH_FLOAT 0x8DF2 +#define GL_LOW_INT 0x8DF3 +#define GL_MEDIUM_INT 0x8DF4 +#define GL_HIGH_INT 0x8DF5 +#define GL_SHADER_COMPILER 0x8DFA +#define GL_SHADER_BINARY_FORMATS 0x8DF8 +#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 +#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB +#define GL_MAX_VARYING_VECTORS 0x8DFC +#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD +#define GL_RGB565 0x8D62 +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 +#define GL_PROGRAM_BINARY_LENGTH 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE +#define GL_PROGRAM_BINARY_FORMATS 0x87FF +#define GL_VERTEX_SHADER_BIT 0x00000001 +#define GL_FRAGMENT_SHADER_BIT 0x00000002 +#define GL_GEOMETRY_SHADER_BIT 0x00000004 +#define GL_TESS_CONTROL_SHADER_BIT 0x00000008 +#define GL_TESS_EVALUATION_SHADER_BIT 0x00000010 +#define GL_ALL_SHADER_BITS 0xFFFFFFFF +#define GL_PROGRAM_SEPARABLE 0x8258 +#define GL_ACTIVE_PROGRAM 0x8259 +#define GL_PROGRAM_PIPELINE_BINDING 0x825A +#define GL_MAX_VIEWPORTS 0x825B +#define GL_VIEWPORT_SUBPIXEL_BITS 0x825C +#define GL_VIEWPORT_BOUNDS_RANGE 0x825D +#define GL_LAYER_PROVOKING_VERTEX 0x825E +#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F +#define GL_UNDEFINED_VERTEX 0x8260 +typedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void); +typedef void (APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryFormat, const void *binary, GLsizei length); +typedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +typedef void (APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f); +typedef void (APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d); +typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLUSEPROGRAMSTAGESPROC) (GLuint pipeline, GLbitfield stages, GLuint program); +typedef void (APIENTRYP PFNGLACTIVESHADERPROGRAMPROC) (GLuint pipeline, GLuint program); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMVPROC) (GLenum type, GLsizei count, const GLchar *const*strings); +typedef void (APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC) (GLsizei n, const GLuint *pipelines); +typedef void (APIENTRYP PFNGLGENPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC) (GLuint pipeline, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IPROC) (GLuint program, GLint location, GLint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FPROC) (GLuint program, GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DPROC) (GLuint program, GLint location, GLdouble v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC) (GLuint program, GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IPROC) (GLuint program, GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLVIEWPORTARRAYVPROC) (GLuint first, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLSCISSORARRAYVPROC) (GLuint first, GLsizei count, const GLint *v); +typedef void (APIENTRYP PFNGLSCISSORINDEXEDPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLSCISSORINDEXEDVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLDEPTHRANGEARRAYVPROC) (GLuint first, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC) (GLuint index, GLdouble n, GLdouble f); +typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReleaseShaderCompiler (void); +GLAPI void APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryFormat, const void *binary, GLsizei length); +GLAPI void APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +GLAPI void APIENTRY glDepthRangef (GLfloat n, GLfloat f); +GLAPI void APIENTRY glClearDepthf (GLfloat d); +GLAPI void APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +GLAPI void APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); +GLAPI void APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value); +GLAPI void APIENTRY glUseProgramStages (GLuint pipeline, GLbitfield stages, GLuint program); +GLAPI void APIENTRY glActiveShaderProgram (GLuint pipeline, GLuint program); +GLAPI GLuint APIENTRY glCreateShaderProgramv (GLenum type, GLsizei count, const GLchar *const*strings); +GLAPI void APIENTRY glBindProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glDeleteProgramPipelines (GLsizei n, const GLuint *pipelines); +GLAPI void APIENTRY glGenProgramPipelines (GLsizei n, GLuint *pipelines); +GLAPI GLboolean APIENTRY glIsProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glGetProgramPipelineiv (GLuint pipeline, GLenum pname, GLint *params); +GLAPI void APIENTRY glProgramUniform1i (GLuint program, GLint location, GLint v0); +GLAPI void APIENTRY glProgramUniform1iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform1f (GLuint program, GLint location, GLfloat v0); +GLAPI void APIENTRY glProgramUniform1fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform1d (GLuint program, GLint location, GLdouble v0); +GLAPI void APIENTRY glProgramUniform1dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform1ui (GLuint program, GLint location, GLuint v0); +GLAPI void APIENTRY glProgramUniform1uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform2i (GLuint program, GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glProgramUniform2iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform2f (GLuint program, GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glProgramUniform2fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform2d (GLuint program, GLint location, GLdouble v0, GLdouble v1); +GLAPI void APIENTRY glProgramUniform2dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform2ui (GLuint program, GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glProgramUniform2uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform3i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glProgramUniform3iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform3f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glProgramUniform3fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform3d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); +GLAPI void APIENTRY glProgramUniform3dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform3ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glProgramUniform3uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform4i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glProgramUniform4iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform4f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glProgramUniform4fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform4d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); +GLAPI void APIENTRY glProgramUniform4dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform4ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glProgramUniform4uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniformMatrix2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glValidateProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glGetProgramPipelineInfoLog (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glVertexAttribL1d (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttribL2d (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttribL3d (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttribL4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttribL1dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL2dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL3dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL4dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribLPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribLdv (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glViewportArrayv (GLuint first, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glViewportIndexedf (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +GLAPI void APIENTRY glViewportIndexedfv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glScissorArrayv (GLuint first, GLsizei count, const GLint *v); +GLAPI void APIENTRY glScissorIndexed (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +GLAPI void APIENTRY glScissorIndexedv (GLuint index, const GLint *v); +GLAPI void APIENTRY glDepthRangeArrayv (GLuint first, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glDepthRangeIndexed (GLuint index, GLdouble n, GLdouble f); +GLAPI void APIENTRY glGetFloati_v (GLenum target, GLuint index, GLfloat *data); +GLAPI void APIENTRY glGetDoublei_v (GLenum target, GLuint index, GLdouble *data); +#endif +#endif /* GL_VERSION_4_1 */ + +#ifndef GL_VERSION_4_2 +#define GL_VERSION_4_2 1 +#define GL_COPY_READ_BUFFER_BINDING 0x8F36 +#define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 +#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 +#define GL_UNPACK_COMPRESSED_BLOCK_WIDTH 0x9127 +#define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128 +#define GL_UNPACK_COMPRESSED_BLOCK_DEPTH 0x9129 +#define GL_UNPACK_COMPRESSED_BLOCK_SIZE 0x912A +#define GL_PACK_COMPRESSED_BLOCK_WIDTH 0x912B +#define GL_PACK_COMPRESSED_BLOCK_HEIGHT 0x912C +#define GL_PACK_COMPRESSED_BLOCK_DEPTH 0x912D +#define GL_PACK_COMPRESSED_BLOCK_SIZE 0x912E +#define GL_NUM_SAMPLE_COUNTS 0x9380 +#define GL_MIN_MAP_BUFFER_ALIGNMENT 0x90BC +#define GL_ATOMIC_COUNTER_BUFFER 0x92C0 +#define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 +#define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 +#define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 +#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB +#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE +#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF +#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 +#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 +#define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3 +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4 +#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS 0x92D5 +#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 +#define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC +#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 +#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA +#define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB +#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 +#define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 +#define GL_UNIFORM_BARRIER_BIT 0x00000004 +#define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 +#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 +#define GL_COMMAND_BARRIER_BIT 0x00000040 +#define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 +#define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 +#define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 +#define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 +#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 +#define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 +#define GL_ALL_BARRIER_BITS 0xFFFFFFFF +#define GL_MAX_IMAGE_UNITS 0x8F38 +#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 +#define GL_IMAGE_BINDING_NAME 0x8F3A +#define GL_IMAGE_BINDING_LEVEL 0x8F3B +#define GL_IMAGE_BINDING_LAYERED 0x8F3C +#define GL_IMAGE_BINDING_LAYER 0x8F3D +#define GL_IMAGE_BINDING_ACCESS 0x8F3E +#define GL_IMAGE_1D 0x904C +#define GL_IMAGE_2D 0x904D +#define GL_IMAGE_3D 0x904E +#define GL_IMAGE_2D_RECT 0x904F +#define GL_IMAGE_CUBE 0x9050 +#define GL_IMAGE_BUFFER 0x9051 +#define GL_IMAGE_1D_ARRAY 0x9052 +#define GL_IMAGE_2D_ARRAY 0x9053 +#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 +#define GL_IMAGE_2D_MULTISAMPLE 0x9055 +#define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 +#define GL_INT_IMAGE_1D 0x9057 +#define GL_INT_IMAGE_2D 0x9058 +#define GL_INT_IMAGE_3D 0x9059 +#define GL_INT_IMAGE_2D_RECT 0x905A +#define GL_INT_IMAGE_CUBE 0x905B +#define GL_INT_IMAGE_BUFFER 0x905C +#define GL_INT_IMAGE_1D_ARRAY 0x905D +#define GL_INT_IMAGE_2D_ARRAY 0x905E +#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F +#define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 +#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 +#define GL_UNSIGNED_INT_IMAGE_1D 0x9062 +#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 +#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 +#define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 +#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 +#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 +#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C +#define GL_MAX_IMAGE_SAMPLES 0x906D +#define GL_IMAGE_BINDING_FORMAT 0x906E +#define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 +#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 +#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 +#define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA +#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB +#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC +#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS 0x90CD +#define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE +#define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF +#define GL_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC) (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC) (GLbitfield barriers); +typedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC) (GLenum mode, GLuint id, GLsizei instancecount); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC) (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedBaseInstance (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +GLAPI void APIENTRY glDrawElementsInstancedBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +GLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +GLAPI void APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint *params); +GLAPI void APIENTRY glGetActiveAtomicCounterBufferiv (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +GLAPI void APIENTRY glBindImageTexture (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +GLAPI void APIENTRY glMemoryBarrier (GLbitfield barriers); +GLAPI void APIENTRY glTexStorage1D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glDrawTransformFeedbackInstanced (GLenum mode, GLuint id, GLsizei instancecount); +GLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); +#endif +#endif /* GL_VERSION_4_2 */ + +#ifndef GL_VERSION_4_3 +#define GL_VERSION_4_3 1 +typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#define GL_NUM_SHADING_LANGUAGE_VERSIONS 0x82E9 +#define GL_VERTEX_ATTRIB_ARRAY_LONG 0x874E +#define GL_COMPRESSED_RGB8_ETC2 0x9274 +#define GL_COMPRESSED_SRGB8_ETC2 0x9275 +#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 +#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 +#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 +#define GL_COMPRESSED_R11_EAC 0x9270 +#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 +#define GL_COMPRESSED_RG11_EAC 0x9272 +#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 +#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 +#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A +#define GL_MAX_ELEMENT_INDEX 0x8D6B +#define GL_COMPUTE_SHADER 0x91B9 +#define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB +#define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC +#define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD +#define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 +#define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 +#define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 +#define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 +#define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 +#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB +#define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE +#define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF +#define GL_COMPUTE_WORK_GROUP_SIZE 0x8267 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED +#define GL_DISPATCH_INDIRECT_BUFFER 0x90EE +#define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF +#define GL_COMPUTE_SHADER_BIT 0x00000020 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 +#define GL_DEBUG_SOURCE_API 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION 0x824A +#define GL_DEBUG_SOURCE_OTHER 0x824B +#define GL_DEBUG_TYPE_ERROR 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E +#define GL_DEBUG_TYPE_PORTABILITY 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 +#define GL_DEBUG_TYPE_OTHER 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES 0x9145 +#define GL_DEBUG_SEVERITY_HIGH 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 +#define GL_DEBUG_SEVERITY_LOW 0x9148 +#define GL_DEBUG_TYPE_MARKER 0x8268 +#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 +#define GL_DEBUG_TYPE_POP_GROUP 0x826A +#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C +#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D +#define GL_BUFFER 0x82E0 +#define GL_SHADER 0x82E1 +#define GL_PROGRAM 0x82E2 +#define GL_QUERY 0x82E3 +#define GL_PROGRAM_PIPELINE 0x82E4 +#define GL_SAMPLER 0x82E6 +#define GL_MAX_LABEL_LENGTH 0x82E8 +#define GL_DEBUG_OUTPUT 0x92E0 +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_MAX_UNIFORM_LOCATIONS 0x826E +#define GL_FRAMEBUFFER_DEFAULT_WIDTH 0x9310 +#define GL_FRAMEBUFFER_DEFAULT_HEIGHT 0x9311 +#define GL_FRAMEBUFFER_DEFAULT_LAYERS 0x9312 +#define GL_FRAMEBUFFER_DEFAULT_SAMPLES 0x9313 +#define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314 +#define GL_MAX_FRAMEBUFFER_WIDTH 0x9315 +#define GL_MAX_FRAMEBUFFER_HEIGHT 0x9316 +#define GL_MAX_FRAMEBUFFER_LAYERS 0x9317 +#define GL_MAX_FRAMEBUFFER_SAMPLES 0x9318 +#define GL_INTERNALFORMAT_SUPPORTED 0x826F +#define GL_INTERNALFORMAT_PREFERRED 0x8270 +#define GL_INTERNALFORMAT_RED_SIZE 0x8271 +#define GL_INTERNALFORMAT_GREEN_SIZE 0x8272 +#define GL_INTERNALFORMAT_BLUE_SIZE 0x8273 +#define GL_INTERNALFORMAT_ALPHA_SIZE 0x8274 +#define GL_INTERNALFORMAT_DEPTH_SIZE 0x8275 +#define GL_INTERNALFORMAT_STENCIL_SIZE 0x8276 +#define GL_INTERNALFORMAT_SHARED_SIZE 0x8277 +#define GL_INTERNALFORMAT_RED_TYPE 0x8278 +#define GL_INTERNALFORMAT_GREEN_TYPE 0x8279 +#define GL_INTERNALFORMAT_BLUE_TYPE 0x827A +#define GL_INTERNALFORMAT_ALPHA_TYPE 0x827B +#define GL_INTERNALFORMAT_DEPTH_TYPE 0x827C +#define GL_INTERNALFORMAT_STENCIL_TYPE 0x827D +#define GL_MAX_WIDTH 0x827E +#define GL_MAX_HEIGHT 0x827F +#define GL_MAX_DEPTH 0x8280 +#define GL_MAX_LAYERS 0x8281 +#define GL_MAX_COMBINED_DIMENSIONS 0x8282 +#define GL_COLOR_COMPONENTS 0x8283 +#define GL_DEPTH_COMPONENTS 0x8284 +#define GL_STENCIL_COMPONENTS 0x8285 +#define GL_COLOR_RENDERABLE 0x8286 +#define GL_DEPTH_RENDERABLE 0x8287 +#define GL_STENCIL_RENDERABLE 0x8288 +#define GL_FRAMEBUFFER_RENDERABLE 0x8289 +#define GL_FRAMEBUFFER_RENDERABLE_LAYERED 0x828A +#define GL_FRAMEBUFFER_BLEND 0x828B +#define GL_READ_PIXELS 0x828C +#define GL_READ_PIXELS_FORMAT 0x828D +#define GL_READ_PIXELS_TYPE 0x828E +#define GL_TEXTURE_IMAGE_FORMAT 0x828F +#define GL_TEXTURE_IMAGE_TYPE 0x8290 +#define GL_GET_TEXTURE_IMAGE_FORMAT 0x8291 +#define GL_GET_TEXTURE_IMAGE_TYPE 0x8292 +#define GL_MIPMAP 0x8293 +#define GL_MANUAL_GENERATE_MIPMAP 0x8294 +#define GL_AUTO_GENERATE_MIPMAP 0x8295 +#define GL_COLOR_ENCODING 0x8296 +#define GL_SRGB_READ 0x8297 +#define GL_SRGB_WRITE 0x8298 +#define GL_FILTER 0x829A +#define GL_VERTEX_TEXTURE 0x829B +#define GL_TESS_CONTROL_TEXTURE 0x829C +#define GL_TESS_EVALUATION_TEXTURE 0x829D +#define GL_GEOMETRY_TEXTURE 0x829E +#define GL_FRAGMENT_TEXTURE 0x829F +#define GL_COMPUTE_TEXTURE 0x82A0 +#define GL_TEXTURE_SHADOW 0x82A1 +#define GL_TEXTURE_GATHER 0x82A2 +#define GL_TEXTURE_GATHER_SHADOW 0x82A3 +#define GL_SHADER_IMAGE_LOAD 0x82A4 +#define GL_SHADER_IMAGE_STORE 0x82A5 +#define GL_SHADER_IMAGE_ATOMIC 0x82A6 +#define GL_IMAGE_TEXEL_SIZE 0x82A7 +#define GL_IMAGE_COMPATIBILITY_CLASS 0x82A8 +#define GL_IMAGE_PIXEL_FORMAT 0x82A9 +#define GL_IMAGE_PIXEL_TYPE 0x82AA +#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST 0x82AC +#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST 0x82AD +#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE 0x82AE +#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE 0x82AF +#define GL_TEXTURE_COMPRESSED_BLOCK_WIDTH 0x82B1 +#define GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT 0x82B2 +#define GL_TEXTURE_COMPRESSED_BLOCK_SIZE 0x82B3 +#define GL_CLEAR_BUFFER 0x82B4 +#define GL_TEXTURE_VIEW 0x82B5 +#define GL_VIEW_COMPATIBILITY_CLASS 0x82B6 +#define GL_FULL_SUPPORT 0x82B7 +#define GL_CAVEAT_SUPPORT 0x82B8 +#define GL_IMAGE_CLASS_4_X_32 0x82B9 +#define GL_IMAGE_CLASS_2_X_32 0x82BA +#define GL_IMAGE_CLASS_1_X_32 0x82BB +#define GL_IMAGE_CLASS_4_X_16 0x82BC +#define GL_IMAGE_CLASS_2_X_16 0x82BD +#define GL_IMAGE_CLASS_1_X_16 0x82BE +#define GL_IMAGE_CLASS_4_X_8 0x82BF +#define GL_IMAGE_CLASS_2_X_8 0x82C0 +#define GL_IMAGE_CLASS_1_X_8 0x82C1 +#define GL_IMAGE_CLASS_11_11_10 0x82C2 +#define GL_IMAGE_CLASS_10_10_10_2 0x82C3 +#define GL_VIEW_CLASS_128_BITS 0x82C4 +#define GL_VIEW_CLASS_96_BITS 0x82C5 +#define GL_VIEW_CLASS_64_BITS 0x82C6 +#define GL_VIEW_CLASS_48_BITS 0x82C7 +#define GL_VIEW_CLASS_32_BITS 0x82C8 +#define GL_VIEW_CLASS_24_BITS 0x82C9 +#define GL_VIEW_CLASS_16_BITS 0x82CA +#define GL_VIEW_CLASS_8_BITS 0x82CB +#define GL_VIEW_CLASS_S3TC_DXT1_RGB 0x82CC +#define GL_VIEW_CLASS_S3TC_DXT1_RGBA 0x82CD +#define GL_VIEW_CLASS_S3TC_DXT3_RGBA 0x82CE +#define GL_VIEW_CLASS_S3TC_DXT5_RGBA 0x82CF +#define GL_VIEW_CLASS_RGTC1_RED 0x82D0 +#define GL_VIEW_CLASS_RGTC2_RG 0x82D1 +#define GL_VIEW_CLASS_BPTC_UNORM 0x82D2 +#define GL_VIEW_CLASS_BPTC_FLOAT 0x82D3 +#define GL_UNIFORM 0x92E1 +#define GL_UNIFORM_BLOCK 0x92E2 +#define GL_PROGRAM_INPUT 0x92E3 +#define GL_PROGRAM_OUTPUT 0x92E4 +#define GL_BUFFER_VARIABLE 0x92E5 +#define GL_SHADER_STORAGE_BLOCK 0x92E6 +#define GL_VERTEX_SUBROUTINE 0x92E8 +#define GL_TESS_CONTROL_SUBROUTINE 0x92E9 +#define GL_TESS_EVALUATION_SUBROUTINE 0x92EA +#define GL_GEOMETRY_SUBROUTINE 0x92EB +#define GL_FRAGMENT_SUBROUTINE 0x92EC +#define GL_COMPUTE_SUBROUTINE 0x92ED +#define GL_VERTEX_SUBROUTINE_UNIFORM 0x92EE +#define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF +#define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0 +#define GL_GEOMETRY_SUBROUTINE_UNIFORM 0x92F1 +#define GL_FRAGMENT_SUBROUTINE_UNIFORM 0x92F2 +#define GL_COMPUTE_SUBROUTINE_UNIFORM 0x92F3 +#define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 +#define GL_ACTIVE_RESOURCES 0x92F5 +#define GL_MAX_NAME_LENGTH 0x92F6 +#define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 +#define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8 +#define GL_NAME_LENGTH 0x92F9 +#define GL_TYPE 0x92FA +#define GL_ARRAY_SIZE 0x92FB +#define GL_OFFSET 0x92FC +#define GL_BLOCK_INDEX 0x92FD +#define GL_ARRAY_STRIDE 0x92FE +#define GL_MATRIX_STRIDE 0x92FF +#define GL_IS_ROW_MAJOR 0x9300 +#define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 +#define GL_BUFFER_BINDING 0x9302 +#define GL_BUFFER_DATA_SIZE 0x9303 +#define GL_NUM_ACTIVE_VARIABLES 0x9304 +#define GL_ACTIVE_VARIABLES 0x9305 +#define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 +#define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307 +#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308 +#define GL_REFERENCED_BY_GEOMETRY_SHADER 0x9309 +#define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A +#define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B +#define GL_TOP_LEVEL_ARRAY_SIZE 0x930C +#define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D +#define GL_LOCATION 0x930E +#define GL_LOCATION_INDEX 0x930F +#define GL_IS_PER_PATCH 0x92E7 +#define GL_SHADER_STORAGE_BUFFER 0x90D2 +#define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 +#define GL_SHADER_STORAGE_BUFFER_START 0x90D4 +#define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 +#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 +#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 +#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 +#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 +#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA +#define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB +#define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC +#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD +#define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE +#define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF +#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 +#define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39 +#define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA +#define GL_TEXTURE_BUFFER_OFFSET 0x919D +#define GL_TEXTURE_BUFFER_SIZE 0x919E +#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F +#define GL_TEXTURE_VIEW_MIN_LEVEL 0x82DB +#define GL_TEXTURE_VIEW_NUM_LEVELS 0x82DC +#define GL_TEXTURE_VIEW_MIN_LAYER 0x82DD +#define GL_TEXTURE_VIEW_NUM_LAYERS 0x82DE +#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF +#define GL_VERTEX_ATTRIB_BINDING 0x82D4 +#define GL_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D5 +#define GL_VERTEX_BINDING_DIVISOR 0x82D6 +#define GL_VERTEX_BINDING_OFFSET 0x82D7 +#define GL_VERTEX_BINDING_STRIDE 0x82D8 +#define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9 +#define GL_MAX_VERTEX_ATTRIB_BINDINGS 0x82DA +#define GL_VERTEX_BINDING_BUFFER 0x8F4F +#define GL_DISPLAY_LIST 0x82E7 +typedef void (APIENTRYP PFNGLCLEARBUFFERDATAPROC) (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC) (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC) (GLintptr indirect); +typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATAPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +typedef void (APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETINTERNALFORMATI64VPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint64 *params); +typedef void (APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLINVALIDATETEXIMAGEPROC) (GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLINVALIDATEBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments); +typedef void (APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC) (GLuint program, GLenum programInterface, GLenum pname, GLint *params); +typedef GLuint (APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLint *params); +typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef void (APIENTRYP PFNGLSHADERSTORAGEBLOCKBINDINGPROC) (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); +typedef void (APIENTRYP PFNGLTEXBUFFERRANGEPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTUREVIEWPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERPROC) (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC) (GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC) (GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC) (GLDEBUGPROC callback, const void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +typedef void (APIENTRYP PFNGLPUSHDEBUGGROUPPROC) (GLenum source, GLuint id, GLsizei length, const GLchar *message); +typedef void (APIENTRYP PFNGLPOPDEBUGGROUPPROC) (void); +typedef void (APIENTRYP PFNGLOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +typedef void (APIENTRYP PFNGLOBJECTPTRLABELPROC) (const void *ptr, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTPTRLABELPROC) (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClearBufferData (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearBufferSubData (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glDispatchCompute (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); +GLAPI void APIENTRY glDispatchComputeIndirect (GLintptr indirect); +GLAPI void APIENTRY glCopyImageSubData (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +GLAPI void APIENTRY glFramebufferParameteri (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glGetFramebufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetInternalformati64v (GLenum target, GLenum internalformat, GLenum pname, GLsizei count, GLint64 *params); +GLAPI void APIENTRY glInvalidateTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glInvalidateTexImage (GLuint texture, GLint level); +GLAPI void APIENTRY glInvalidateBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glInvalidateBufferData (GLuint buffer); +GLAPI void APIENTRY glInvalidateFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments); +GLAPI void APIENTRY glInvalidateSubFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glMultiDrawArraysIndirect (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +GLAPI void APIENTRY glGetProgramInterfaceiv (GLuint program, GLenum programInterface, GLenum pname, GLint *params); +GLAPI GLuint APIENTRY glGetProgramResourceIndex (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI void APIENTRY glGetProgramResourceName (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glGetProgramResourceiv (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLint *params); +GLAPI GLint APIENTRY glGetProgramResourceLocation (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI GLint APIENTRY glGetProgramResourceLocationIndex (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI void APIENTRY glShaderStorageBlockBinding (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); +GLAPI void APIENTRY glTexBufferRange (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glTexStorage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTexStorage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureView (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +GLAPI void APIENTRY glBindVertexBuffer (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexAttribFormat (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribIFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribLFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribBinding (GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexBindingDivisor (GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glDebugMessageControl (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsert (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallback (GLDEBUGPROC callback, const void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLog (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +GLAPI void APIENTRY glPushDebugGroup (GLenum source, GLuint id, GLsizei length, const GLchar *message); +GLAPI void APIENTRY glPopDebugGroup (void); +GLAPI void APIENTRY glObjectLabel (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectLabel (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +GLAPI void APIENTRY glObjectPtrLabel (const void *ptr, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectPtrLabel (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +#endif +#endif /* GL_VERSION_4_3 */ + +#ifndef GL_VERSION_4_4 +#define GL_VERSION_4_4 1 +#define GL_MAX_VERTEX_ATTRIB_STRIDE 0x82E5 +#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221 +#define GL_TEXTURE_BUFFER_BINDING 0x8C2A +#define GL_MAP_PERSISTENT_BIT 0x0040 +#define GL_MAP_COHERENT_BIT 0x0080 +#define GL_DYNAMIC_STORAGE_BIT 0x0100 +#define GL_CLIENT_STORAGE_BIT 0x0200 +#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 +#define GL_BUFFER_IMMUTABLE_STORAGE 0x821F +#define GL_BUFFER_STORAGE_FLAGS 0x8220 +#define GL_CLEAR_TEXTURE 0x9365 +#define GL_LOCATION_COMPONENT 0x934A +#define GL_TRANSFORM_FEEDBACK_BUFFER_INDEX 0x934B +#define GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE 0x934C +#define GL_QUERY_BUFFER 0x9192 +#define GL_QUERY_BUFFER_BARRIER_BIT 0x00008000 +#define GL_QUERY_BUFFER_BINDING 0x9193 +#define GL_QUERY_RESULT_NO_WAIT 0x9194 +#define GL_MIRROR_CLAMP_TO_EDGE 0x8743 +typedef void (APIENTRYP PFNGLBUFFERSTORAGEPROC) (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLCLEARTEXIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARTEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLBINDBUFFERSBASEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers); +typedef void (APIENTRYP PFNGLBINDBUFFERSRANGEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); +typedef void (APIENTRYP PFNGLBINDTEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures); +typedef void (APIENTRYP PFNGLBINDSAMPLERSPROC) (GLuint first, GLsizei count, const GLuint *samplers); +typedef void (APIENTRYP PFNGLBINDIMAGETEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures); +typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERSPROC) (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferStorage (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glClearTexImage (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glBindBuffersBase (GLenum target, GLuint first, GLsizei count, const GLuint *buffers); +GLAPI void APIENTRY glBindBuffersRange (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); +GLAPI void APIENTRY glBindTextures (GLuint first, GLsizei count, const GLuint *textures); +GLAPI void APIENTRY glBindSamplers (GLuint first, GLsizei count, const GLuint *samplers); +GLAPI void APIENTRY glBindImageTextures (GLuint first, GLsizei count, const GLuint *textures); +GLAPI void APIENTRY glBindVertexBuffers (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +#endif +#endif /* GL_VERSION_4_4 */ + +#ifndef GL_VERSION_4_5 +#define GL_VERSION_4_5 1 +#define GL_CONTEXT_LOST 0x0507 +#define GL_NEGATIVE_ONE_TO_ONE 0x935E +#define GL_ZERO_TO_ONE 0x935F +#define GL_CLIP_ORIGIN 0x935C +#define GL_CLIP_DEPTH_MODE 0x935D +#define GL_QUERY_WAIT_INVERTED 0x8E17 +#define GL_QUERY_NO_WAIT_INVERTED 0x8E18 +#define GL_QUERY_BY_REGION_WAIT_INVERTED 0x8E19 +#define GL_QUERY_BY_REGION_NO_WAIT_INVERTED 0x8E1A +#define GL_MAX_CULL_DISTANCES 0x82F9 +#define GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES 0x82FA +#define GL_TEXTURE_TARGET 0x1006 +#define GL_QUERY_TARGET 0x82EA +#define GL_GUILTY_CONTEXT_RESET 0x8253 +#define GL_INNOCENT_CONTEXT_RESET 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET 0x8255 +#define GL_RESET_NOTIFICATION_STRATEGY 0x8256 +#define GL_LOSE_CONTEXT_ON_RESET 0x8252 +#define GL_NO_RESET_NOTIFICATION 0x8261 +#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT 0x00000004 +#define GL_COLOR_TABLE 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2 +#define GL_PROXY_COLOR_TABLE 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5 +#define GL_CONVOLUTION_1D 0x8010 +#define GL_CONVOLUTION_2D 0x8011 +#define GL_SEPARABLE_2D 0x8012 +#define GL_HISTOGRAM 0x8024 +#define GL_PROXY_HISTOGRAM 0x8025 +#define GL_MINMAX 0x802E +#define GL_CONTEXT_RELEASE_BEHAVIOR 0x82FB +#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82FC +typedef void (APIENTRYP PFNGLCLIPCONTROLPROC) (GLenum origin, GLenum depth); +typedef void (APIENTRYP PFNGLCREATETRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC) (GLuint xfb, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC) (GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKIVPROC) (GLuint xfb, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); +typedef void (APIENTRYP PFNGLCREATEBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +typedef void (APIENTRYP PFNGLCOPYNAMEDBUFFERSUBDATAPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERPROC) (GLuint buffer, GLenum access); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFERPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERI64VPROC) (GLuint buffer, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVPROC) (GLuint buffer, GLenum pname, void **params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +typedef void (APIENTRYP PFNGLCREATEFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC) (GLuint framebuffer, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC) (GLuint framebuffer, GLenum buf); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC) (GLuint framebuffer, GLenum src); +typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC) (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); +typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC) (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERIVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFIPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +typedef void (APIENTRYP PFNGLBLITNAMEDFRAMEBUFFERPROC) (GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC) (GLuint framebuffer, GLenum target); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC) (GLuint framebuffer, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATERENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC) (GLuint renderbuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATETEXTURESPROC) (GLenum target, GLsizei n, GLuint *textures); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERPROC) (GLuint texture, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEPROC) (GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC) (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC) (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFPROC) (GLuint texture, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVPROC) (GLuint texture, GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIPROC) (GLuint texture, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVPROC) (GLuint texture, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVPROC) (GLuint texture, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVPROC) (GLuint texture, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLBINDTEXTUREUNITPROC) (GLuint unit, GLuint texture); +typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC) (GLuint texture, GLint level, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVPROC) (GLuint texture, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVPROC) (GLuint texture, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVPROC) (GLuint texture, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVPROC) (GLuint texture, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVPROC) (GLuint texture, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVPROC) (GLuint texture, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATEVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLVERTEXARRAYELEMENTBUFFERPROC) (GLuint vaobj, GLuint buffer); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERSPROC) (GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBBINDINGPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBIFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBLFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYBINDINGDIVISORPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYIVPROC) (GLuint vaobj, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXEDIVPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXED64IVPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); +typedef void (APIENTRYP PFNGLCREATESAMPLERSPROC) (GLsizei n, GLuint *samplers); +typedef void (APIENTRYP PFNGLCREATEPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines); +typedef void (APIENTRYP PFNGLCREATEQUERIESPROC) (GLenum target, GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTI64VPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTIVPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUI64VPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUIVPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLMEMORYBARRIERBYREGIONPROC) (GLbitfield barriers); +typedef void (APIENTRYP PFNGLGETTEXTURESUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); +typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSPROC) (void); +typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint lod, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETNTEXIMAGEPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETNUNIFORMDVPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMFVPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMIVPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMUIVPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +typedef void (APIENTRYP PFNGLREADNPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +typedef void (APIENTRYP PFNGLGETNMAPDVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +typedef void (APIENTRYP PFNGLGETNMAPFVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +typedef void (APIENTRYP PFNGLGETNMAPIVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +typedef void (APIENTRYP PFNGLGETNPIXELMAPFVPROC) (GLenum map, GLsizei bufSize, GLfloat *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVPROC) (GLenum map, GLsizei bufSize, GLuint *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVPROC) (GLenum map, GLsizei bufSize, GLushort *values); +typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEPROC) (GLsizei bufSize, GLubyte *pattern); +typedef void (APIENTRYP PFNGLGETNCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +typedef void (APIENTRYP PFNGLGETNHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLGETNMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLTEXTUREBARRIERPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClipControl (GLenum origin, GLenum depth); +GLAPI void APIENTRY glCreateTransformFeedbacks (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glTransformFeedbackBufferBase (GLuint xfb, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackBufferRange (GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glGetTransformFeedbackiv (GLuint xfb, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetTransformFeedbacki_v (GLuint xfb, GLenum pname, GLuint index, GLint *param); +GLAPI void APIENTRY glGetTransformFeedbacki64_v (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); +GLAPI void APIENTRY glCreateBuffers (GLsizei n, GLuint *buffers); +GLAPI void APIENTRY glNamedBufferStorage (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glNamedBufferData (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glNamedBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void APIENTRY glCopyNamedBufferSubData (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glClearNamedBufferData (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearNamedBufferSubData (GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI void *APIENTRY glMapNamedBuffer (GLuint buffer, GLenum access); +GLAPI void *APIENTRY glMapNamedBufferRange (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI GLboolean APIENTRY glUnmapNamedBuffer (GLuint buffer); +GLAPI void APIENTRY glFlushMappedNamedBufferRange (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glGetNamedBufferParameteriv (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedBufferParameteri64v (GLuint buffer, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetNamedBufferPointerv (GLuint buffer, GLenum pname, void **params); +GLAPI void APIENTRY glGetNamedBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +GLAPI void APIENTRY glCreateFramebuffers (GLsizei n, GLuint *framebuffers); +GLAPI void APIENTRY glNamedFramebufferRenderbuffer (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glNamedFramebufferParameteri (GLuint framebuffer, GLenum pname, GLint param); +GLAPI void APIENTRY glNamedFramebufferTexture (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTextureLayer (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glNamedFramebufferDrawBuffer (GLuint framebuffer, GLenum buf); +GLAPI void APIENTRY glNamedFramebufferDrawBuffers (GLuint framebuffer, GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glNamedFramebufferReadBuffer (GLuint framebuffer, GLenum src); +GLAPI void APIENTRY glInvalidateNamedFramebufferData (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); +GLAPI void APIENTRY glInvalidateNamedFramebufferSubData (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glClearNamedFramebufferiv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI void APIENTRY glClearNamedFramebufferuiv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI void APIENTRY glClearNamedFramebufferfv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI void APIENTRY glClearNamedFramebufferfi (GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +GLAPI void APIENTRY glBlitNamedFramebuffer (GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI GLenum APIENTRY glCheckNamedFramebufferStatus (GLuint framebuffer, GLenum target); +GLAPI void APIENTRY glGetNamedFramebufferParameteriv (GLuint framebuffer, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameteriv (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateRenderbuffers (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glNamedRenderbufferStorage (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisample (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetNamedRenderbufferParameteriv (GLuint renderbuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateTextures (GLenum target, GLsizei n, GLuint *textures); +GLAPI void APIENTRY glTextureBuffer (GLuint texture, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glTextureBufferRange (GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glTextureStorage1D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTextureStorage2D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureStorage3D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glTextureStorage2DMultisample (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureStorage3DMultisample (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCompressedTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCopyTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glCopyTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureParameterf (GLuint texture, GLenum pname, GLfloat param); +GLAPI void APIENTRY glTextureParameterfv (GLuint texture, GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glTextureParameteri (GLuint texture, GLenum pname, GLint param); +GLAPI void APIENTRY glTextureParameterIiv (GLuint texture, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureParameterIuiv (GLuint texture, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glTextureParameteriv (GLuint texture, GLenum pname, const GLint *param); +GLAPI void APIENTRY glGenerateTextureMipmap (GLuint texture); +GLAPI void APIENTRY glBindTextureUnit (GLuint unit, GLuint texture); +GLAPI void APIENTRY glGetTextureImage (GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetCompressedTextureImage (GLuint texture, GLint level, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetTextureLevelParameterfv (GLuint texture, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureLevelParameteriv (GLuint texture, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterfv (GLuint texture, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureParameterIiv (GLuint texture, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterIuiv (GLuint texture, GLenum pname, GLuint *params); +GLAPI void APIENTRY glGetTextureParameteriv (GLuint texture, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateVertexArrays (GLsizei n, GLuint *arrays); +GLAPI void APIENTRY glDisableVertexArrayAttrib (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glEnableVertexArrayAttrib (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glVertexArrayElementBuffer (GLuint vaobj, GLuint buffer); +GLAPI void APIENTRY glVertexArrayVertexBuffer (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexArrayVertexBuffers (GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +GLAPI void APIENTRY glVertexArrayAttribBinding (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexArrayAttribFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayAttribIFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayAttribLFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayBindingDivisor (GLuint vaobj, GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glGetVertexArrayiv (GLuint vaobj, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayIndexediv (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayIndexed64iv (GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); +GLAPI void APIENTRY glCreateSamplers (GLsizei n, GLuint *samplers); +GLAPI void APIENTRY glCreateProgramPipelines (GLsizei n, GLuint *pipelines); +GLAPI void APIENTRY glCreateQueries (GLenum target, GLsizei n, GLuint *ids); +GLAPI void APIENTRY glGetQueryBufferObjecti64v (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectiv (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectui64v (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectuiv (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glMemoryBarrierByRegion (GLbitfield barriers); +GLAPI void APIENTRY glGetTextureSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetCompressedTextureSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); +GLAPI GLenum APIENTRY glGetGraphicsResetStatus (void); +GLAPI void APIENTRY glGetnCompressedTexImage (GLenum target, GLint lod, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetnTexImage (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetnUniformdv (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +GLAPI void APIENTRY glGetnUniformfv (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GLAPI void APIENTRY glGetnUniformiv (GLuint program, GLint location, GLsizei bufSize, GLint *params); +GLAPI void APIENTRY glGetnUniformuiv (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +GLAPI void APIENTRY glReadnPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GLAPI void APIENTRY glGetnMapdv (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +GLAPI void APIENTRY glGetnMapfv (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +GLAPI void APIENTRY glGetnMapiv (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +GLAPI void APIENTRY glGetnPixelMapfv (GLenum map, GLsizei bufSize, GLfloat *values); +GLAPI void APIENTRY glGetnPixelMapuiv (GLenum map, GLsizei bufSize, GLuint *values); +GLAPI void APIENTRY glGetnPixelMapusv (GLenum map, GLsizei bufSize, GLushort *values); +GLAPI void APIENTRY glGetnPolygonStipple (GLsizei bufSize, GLubyte *pattern); +GLAPI void APIENTRY glGetnColorTable (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +GLAPI void APIENTRY glGetnConvolutionFilter (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +GLAPI void APIENTRY glGetnSeparableFilter (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +GLAPI void APIENTRY glGetnHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glGetnMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glTextureBarrier (void); +#endif +#endif /* GL_VERSION_4_5 */ + +#ifndef GL_VERSION_4_6 +#define GL_VERSION_4_6 1 +#define GL_SHADER_BINARY_FORMAT_SPIR_V 0x9551 +#define GL_SPIR_V_BINARY 0x9552 +#define GL_PARAMETER_BUFFER 0x80EE +#define GL_PARAMETER_BUFFER_BINDING 0x80EF +#define GL_CONTEXT_FLAG_NO_ERROR_BIT 0x00000008 +#define GL_VERTICES_SUBMITTED 0x82EE +#define GL_PRIMITIVES_SUBMITTED 0x82EF +#define GL_VERTEX_SHADER_INVOCATIONS 0x82F0 +#define GL_TESS_CONTROL_SHADER_PATCHES 0x82F1 +#define GL_TESS_EVALUATION_SHADER_INVOCATIONS 0x82F2 +#define GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED 0x82F3 +#define GL_FRAGMENT_SHADER_INVOCATIONS 0x82F4 +#define GL_COMPUTE_SHADER_INVOCATIONS 0x82F5 +#define GL_CLIPPING_INPUT_PRIMITIVES 0x82F6 +#define GL_CLIPPING_OUTPUT_PRIMITIVES 0x82F7 +#define GL_POLYGON_OFFSET_CLAMP 0x8E1B +#define GL_SPIR_V_EXTENSIONS 0x9553 +#define GL_NUM_SPIR_V_EXTENSIONS 0x9554 +#define GL_TEXTURE_MAX_ANISOTROPY 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY 0x84FF +#define GL_TRANSFORM_FEEDBACK_OVERFLOW 0x82EC +#define GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW 0x82ED +typedef void (APIENTRYP PFNGLSPECIALIZESHADERPROC) (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC) (GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC) (GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLPOLYGONOFFSETCLAMPPROC) (GLfloat factor, GLfloat units, GLfloat clamp); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSpecializeShader (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); +GLAPI void APIENTRY glMultiDrawArraysIndirectCount (GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirectCount (GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +GLAPI void APIENTRY glPolygonOffsetClamp (GLfloat factor, GLfloat units, GLfloat clamp); +#endif +#endif /* GL_VERSION_4_6 */ + +#ifndef GL_ARB_ES2_compatibility +#define GL_ARB_ES2_compatibility 1 +#endif /* GL_ARB_ES2_compatibility */ + +#ifndef GL_ARB_ES3_1_compatibility +#define GL_ARB_ES3_1_compatibility 1 +#endif /* GL_ARB_ES3_1_compatibility */ + +#ifndef GL_ARB_ES3_2_compatibility +#define GL_ARB_ES3_2_compatibility 1 +#define GL_PRIMITIVE_BOUNDING_BOX_ARB 0x92BE +#define GL_MULTISAMPLE_LINE_WIDTH_RANGE_ARB 0x9381 +#define GL_MULTISAMPLE_LINE_WIDTH_GRANULARITY_ARB 0x9382 +typedef void (APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXARBPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPrimitiveBoundingBoxARB (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); +#endif +#endif /* GL_ARB_ES3_2_compatibility */ + +#ifndef GL_ARB_ES3_compatibility +#define GL_ARB_ES3_compatibility 1 +#endif /* GL_ARB_ES3_compatibility */ + +#ifndef GL_ARB_arrays_of_arrays +#define GL_ARB_arrays_of_arrays 1 +#endif /* GL_ARB_arrays_of_arrays */ + +#ifndef GL_ARB_base_instance +#define GL_ARB_base_instance 1 +#endif /* GL_ARB_base_instance */ + +#ifndef GL_ARB_bindless_texture +#define GL_ARB_bindless_texture 1 +typedef khronos_uint64_t GLuint64EXT; +#define GL_UNSIGNED_INT64_ARB 0x140F +typedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLEARBPROC) (GLuint texture); +typedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLEARBPROC) (GLuint texture, GLuint sampler); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC) (GLuint64 handle); +typedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLEARBPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle, GLenum access); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64ARBPROC) (GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC) (GLuint program, GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64ARBPROC) (GLuint index, GLuint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VARBPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VARBPROC) (GLuint index, GLenum pname, GLuint64EXT *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint64 APIENTRY glGetTextureHandleARB (GLuint texture); +GLAPI GLuint64 APIENTRY glGetTextureSamplerHandleARB (GLuint texture, GLuint sampler); +GLAPI void APIENTRY glMakeTextureHandleResidentARB (GLuint64 handle); +GLAPI void APIENTRY glMakeTextureHandleNonResidentARB (GLuint64 handle); +GLAPI GLuint64 APIENTRY glGetImageHandleARB (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +GLAPI void APIENTRY glMakeImageHandleResidentARB (GLuint64 handle, GLenum access); +GLAPI void APIENTRY glMakeImageHandleNonResidentARB (GLuint64 handle); +GLAPI void APIENTRY glUniformHandleui64ARB (GLint location, GLuint64 value); +GLAPI void APIENTRY glUniformHandleui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniformHandleui64ARB (GLuint program, GLint location, GLuint64 value); +GLAPI void APIENTRY glProgramUniformHandleui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +GLAPI GLboolean APIENTRY glIsTextureHandleResidentARB (GLuint64 handle); +GLAPI GLboolean APIENTRY glIsImageHandleResidentARB (GLuint64 handle); +GLAPI void APIENTRY glVertexAttribL1ui64ARB (GLuint index, GLuint64EXT x); +GLAPI void APIENTRY glVertexAttribL1ui64vARB (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glGetVertexAttribLui64vARB (GLuint index, GLenum pname, GLuint64EXT *params); +#endif +#endif /* GL_ARB_bindless_texture */ + +#ifndef GL_ARB_blend_func_extended +#define GL_ARB_blend_func_extended 1 +#endif /* GL_ARB_blend_func_extended */ + +#ifndef GL_ARB_buffer_storage +#define GL_ARB_buffer_storage 1 +#endif /* GL_ARB_buffer_storage */ + +#ifndef GL_ARB_cl_event +#define GL_ARB_cl_event 1 +struct _cl_context; +struct _cl_event; +#define GL_SYNC_CL_EVENT_ARB 0x8240 +#define GL_SYNC_CL_EVENT_COMPLETE_ARB 0x8241 +typedef GLsync (APIENTRYP PFNGLCREATESYNCFROMCLEVENTARBPROC) (struct _cl_context *context, struct _cl_event *event, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLsync APIENTRY glCreateSyncFromCLeventARB (struct _cl_context *context, struct _cl_event *event, GLbitfield flags); +#endif +#endif /* GL_ARB_cl_event */ + +#ifndef GL_ARB_clear_buffer_object +#define GL_ARB_clear_buffer_object 1 +#endif /* GL_ARB_clear_buffer_object */ + +#ifndef GL_ARB_clear_texture +#define GL_ARB_clear_texture 1 +#endif /* GL_ARB_clear_texture */ + +#ifndef GL_ARB_clip_control +#define GL_ARB_clip_control 1 +#endif /* GL_ARB_clip_control */ + +#ifndef GL_ARB_color_buffer_float +#define GL_ARB_color_buffer_float 1 +#define GL_RGBA_FLOAT_MODE_ARB 0x8820 +#define GL_CLAMP_VERTEX_COLOR_ARB 0x891A +#define GL_CLAMP_FRAGMENT_COLOR_ARB 0x891B +#define GL_CLAMP_READ_COLOR_ARB 0x891C +#define GL_FIXED_ONLY_ARB 0x891D +typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClampColorARB (GLenum target, GLenum clamp); +#endif +#endif /* GL_ARB_color_buffer_float */ + +#ifndef GL_ARB_compatibility +#define GL_ARB_compatibility 1 +#endif /* GL_ARB_compatibility */ + +#ifndef GL_ARB_compressed_texture_pixel_storage +#define GL_ARB_compressed_texture_pixel_storage 1 +#endif /* GL_ARB_compressed_texture_pixel_storage */ + +#ifndef GL_ARB_compute_shader +#define GL_ARB_compute_shader 1 +#endif /* GL_ARB_compute_shader */ + +#ifndef GL_ARB_compute_variable_group_size +#define GL_ARB_compute_variable_group_size 1 +#define GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB 0x9344 +#define GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB 0x90EB +#define GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB 0x9345 +#define GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB 0x91BF +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEGROUPSIZEARBPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDispatchComputeGroupSizeARB (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z); +#endif +#endif /* GL_ARB_compute_variable_group_size */ + +#ifndef GL_ARB_conditional_render_inverted +#define GL_ARB_conditional_render_inverted 1 +#endif /* GL_ARB_conditional_render_inverted */ + +#ifndef GL_ARB_conservative_depth +#define GL_ARB_conservative_depth 1 +#endif /* GL_ARB_conservative_depth */ + +#ifndef GL_ARB_copy_buffer +#define GL_ARB_copy_buffer 1 +#endif /* GL_ARB_copy_buffer */ + +#ifndef GL_ARB_copy_image +#define GL_ARB_copy_image 1 +#endif /* GL_ARB_copy_image */ + +#ifndef GL_ARB_cull_distance +#define GL_ARB_cull_distance 1 +#endif /* GL_ARB_cull_distance */ + +#ifndef GL_ARB_debug_output +#define GL_ARB_debug_output 1 +typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#define GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION_ARB 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245 +#define GL_DEBUG_SOURCE_API_ARB 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION_ARB 0x824A +#define GL_DEBUG_SOURCE_OTHER_ARB 0x824B +#define GL_DEBUG_TYPE_ERROR_ARB 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E +#define GL_DEBUG_TYPE_PORTABILITY_ARB 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE_ARB 0x8250 +#define GL_DEBUG_TYPE_OTHER_ARB 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES_ARB 0x9145 +#define GL_DEBUG_SEVERITY_HIGH_ARB 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM_ARB 0x9147 +#define GL_DEBUG_SEVERITY_LOW_ARB 0x9148 +typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLARBPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTARBPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKARBPROC) (GLDEBUGPROCARB callback, const void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDebugMessageControlARB (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsertARB (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallbackARB (GLDEBUGPROCARB callback, const void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLogARB (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +#endif +#endif /* GL_ARB_debug_output */ + +#ifndef GL_ARB_depth_buffer_float +#define GL_ARB_depth_buffer_float 1 +#endif /* GL_ARB_depth_buffer_float */ + +#ifndef GL_ARB_depth_clamp +#define GL_ARB_depth_clamp 1 +#endif /* GL_ARB_depth_clamp */ + +#ifndef GL_ARB_depth_texture +#define GL_ARB_depth_texture 1 +#define GL_DEPTH_COMPONENT16_ARB 0x81A5 +#define GL_DEPTH_COMPONENT24_ARB 0x81A6 +#define GL_DEPTH_COMPONENT32_ARB 0x81A7 +#define GL_TEXTURE_DEPTH_SIZE_ARB 0x884A +#define GL_DEPTH_TEXTURE_MODE_ARB 0x884B +#endif /* GL_ARB_depth_texture */ + +#ifndef GL_ARB_derivative_control +#define GL_ARB_derivative_control 1 +#endif /* GL_ARB_derivative_control */ + +#ifndef GL_ARB_direct_state_access +#define GL_ARB_direct_state_access 1 +#endif /* GL_ARB_direct_state_access */ + +#ifndef GL_ARB_draw_buffers +#define GL_ARB_draw_buffers 1 +#define GL_MAX_DRAW_BUFFERS_ARB 0x8824 +#define GL_DRAW_BUFFER0_ARB 0x8825 +#define GL_DRAW_BUFFER1_ARB 0x8826 +#define GL_DRAW_BUFFER2_ARB 0x8827 +#define GL_DRAW_BUFFER3_ARB 0x8828 +#define GL_DRAW_BUFFER4_ARB 0x8829 +#define GL_DRAW_BUFFER5_ARB 0x882A +#define GL_DRAW_BUFFER6_ARB 0x882B +#define GL_DRAW_BUFFER7_ARB 0x882C +#define GL_DRAW_BUFFER8_ARB 0x882D +#define GL_DRAW_BUFFER9_ARB 0x882E +#define GL_DRAW_BUFFER10_ARB 0x882F +#define GL_DRAW_BUFFER11_ARB 0x8830 +#define GL_DRAW_BUFFER12_ARB 0x8831 +#define GL_DRAW_BUFFER13_ARB 0x8832 +#define GL_DRAW_BUFFER14_ARB 0x8833 +#define GL_DRAW_BUFFER15_ARB 0x8834 +typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawBuffersARB (GLsizei n, const GLenum *bufs); +#endif +#endif /* GL_ARB_draw_buffers */ + +#ifndef GL_ARB_draw_buffers_blend +#define GL_ARB_draw_buffers_blend 1 +typedef void (APIENTRYP PFNGLBLENDEQUATIONIARBPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIARBPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLBLENDFUNCIARBPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIARBPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationiARB (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparateiARB (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glBlendFunciARB (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparateiARB (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +#endif +#endif /* GL_ARB_draw_buffers_blend */ + +#ifndef GL_ARB_draw_elements_base_vertex +#define GL_ARB_draw_elements_base_vertex 1 +#endif /* GL_ARB_draw_elements_base_vertex */ + +#ifndef GL_ARB_draw_indirect +#define GL_ARB_draw_indirect 1 +#endif /* GL_ARB_draw_indirect */ + +#ifndef GL_ARB_draw_instanced +#define GL_ARB_draw_instanced 1 +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDARBPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDARBPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedARB (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +GLAPI void APIENTRY glDrawElementsInstancedARB (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#endif +#endif /* GL_ARB_draw_instanced */ + +#ifndef GL_ARB_enhanced_layouts +#define GL_ARB_enhanced_layouts 1 +#endif /* GL_ARB_enhanced_layouts */ + +#ifndef GL_ARB_explicit_attrib_location +#define GL_ARB_explicit_attrib_location 1 +#endif /* GL_ARB_explicit_attrib_location */ + +#ifndef GL_ARB_explicit_uniform_location +#define GL_ARB_explicit_uniform_location 1 +#endif /* GL_ARB_explicit_uniform_location */ + +#ifndef GL_ARB_fragment_coord_conventions +#define GL_ARB_fragment_coord_conventions 1 +#endif /* GL_ARB_fragment_coord_conventions */ + +#ifndef GL_ARB_fragment_layer_viewport +#define GL_ARB_fragment_layer_viewport 1 +#endif /* GL_ARB_fragment_layer_viewport */ + +#ifndef GL_ARB_fragment_program +#define GL_ARB_fragment_program 1 +#define GL_FRAGMENT_PROGRAM_ARB 0x8804 +#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 +#define GL_PROGRAM_LENGTH_ARB 0x8627 +#define GL_PROGRAM_FORMAT_ARB 0x8876 +#define GL_PROGRAM_BINDING_ARB 0x8677 +#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 +#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 +#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 +#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 +#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 +#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 +#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 +#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 +#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 +#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 +#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA +#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB +#define GL_PROGRAM_ATTRIBS_ARB 0x88AC +#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD +#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE +#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF +#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 +#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 +#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 +#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 +#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 +#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 +#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 +#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 +#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A +#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B +#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C +#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D +#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E +#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F +#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 +#define GL_PROGRAM_STRING_ARB 0x8628 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_CURRENT_MATRIX_ARB 0x8641 +#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 +#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 +#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F +#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E +#define GL_MAX_TEXTURE_COORDS_ARB 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_MATRIX0_ARB 0x88C0 +#define GL_MATRIX1_ARB 0x88C1 +#define GL_MATRIX2_ARB 0x88C2 +#define GL_MATRIX3_ARB 0x88C3 +#define GL_MATRIX4_ARB 0x88C4 +#define GL_MATRIX5_ARB 0x88C5 +#define GL_MATRIX6_ARB 0x88C6 +#define GL_MATRIX7_ARB 0x88C7 +#define GL_MATRIX8_ARB 0x88C8 +#define GL_MATRIX9_ARB 0x88C9 +#define GL_MATRIX10_ARB 0x88CA +#define GL_MATRIX11_ARB 0x88CB +#define GL_MATRIX12_ARB 0x88CC +#define GL_MATRIX13_ARB 0x88CD +#define GL_MATRIX14_ARB 0x88CE +#define GL_MATRIX15_ARB 0x88CF +#define GL_MATRIX16_ARB 0x88D0 +#define GL_MATRIX17_ARB 0x88D1 +#define GL_MATRIX18_ARB 0x88D2 +#define GL_MATRIX19_ARB 0x88D3 +#define GL_MATRIX20_ARB 0x88D4 +#define GL_MATRIX21_ARB 0x88D5 +#define GL_MATRIX22_ARB 0x88D6 +#define GL_MATRIX23_ARB 0x88D7 +#define GL_MATRIX24_ARB 0x88D8 +#define GL_MATRIX25_ARB 0x88D9 +#define GL_MATRIX26_ARB 0x88DA +#define GL_MATRIX27_ARB 0x88DB +#define GL_MATRIX28_ARB 0x88DC +#define GL_MATRIX29_ARB 0x88DD +#define GL_MATRIX30_ARB 0x88DE +#define GL_MATRIX31_ARB 0x88DF +typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const void *string); +typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program); +typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, void *string); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramStringARB (GLenum target, GLenum format, GLsizei len, const void *string); +GLAPI void APIENTRY glBindProgramARB (GLenum target, GLuint program); +GLAPI void APIENTRY glDeleteProgramsARB (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glGenProgramsARB (GLsizei n, GLuint *programs); +GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetProgramivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramStringARB (GLenum target, GLenum pname, void *string); +GLAPI GLboolean APIENTRY glIsProgramARB (GLuint program); +#endif +#endif /* GL_ARB_fragment_program */ + +#ifndef GL_ARB_fragment_program_shadow +#define GL_ARB_fragment_program_shadow 1 +#endif /* GL_ARB_fragment_program_shadow */ + +#ifndef GL_ARB_fragment_shader +#define GL_ARB_fragment_shader 1 +#define GL_FRAGMENT_SHADER_ARB 0x8B30 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B +#endif /* GL_ARB_fragment_shader */ + +#ifndef GL_ARB_fragment_shader_interlock +#define GL_ARB_fragment_shader_interlock 1 +#endif /* GL_ARB_fragment_shader_interlock */ + +#ifndef GL_ARB_framebuffer_no_attachments +#define GL_ARB_framebuffer_no_attachments 1 +#endif /* GL_ARB_framebuffer_no_attachments */ + +#ifndef GL_ARB_framebuffer_object +#define GL_ARB_framebuffer_object 1 +#endif /* GL_ARB_framebuffer_object */ + +#ifndef GL_ARB_framebuffer_sRGB +#define GL_ARB_framebuffer_sRGB 1 +#endif /* GL_ARB_framebuffer_sRGB */ + +#ifndef GL_ARB_geometry_shader4 +#define GL_ARB_geometry_shader4 1 +#define GL_LINES_ADJACENCY_ARB 0x000A +#define GL_LINE_STRIP_ADJACENCY_ARB 0x000B +#define GL_TRIANGLES_ADJACENCY_ARB 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_ARB 0x000D +#define GL_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB 0x8C29 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB 0x8DA9 +#define GL_GEOMETRY_SHADER_ARB 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT_ARB 0x8DDA +#define GL_GEOMETRY_INPUT_TYPE_ARB 0x8DDB +#define GL_GEOMETRY_OUTPUT_TYPE_ARB 0x8DDC +#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB 0x8DDD +#define GL_MAX_VERTEX_VARYING_COMPONENTS_ARB 0x8DDE +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB 0x8DE1 +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIARBPROC) (GLuint program, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramParameteriARB (GLuint program, GLenum pname, GLint value); +GLAPI void APIENTRY glFramebufferTextureARB (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTextureLayerARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glFramebufferTextureFaceARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#endif +#endif /* GL_ARB_geometry_shader4 */ + +#ifndef GL_ARB_get_program_binary +#define GL_ARB_get_program_binary 1 +#endif /* GL_ARB_get_program_binary */ + +#ifndef GL_ARB_get_texture_sub_image +#define GL_ARB_get_texture_sub_image 1 +#endif /* GL_ARB_get_texture_sub_image */ + +#ifndef GL_ARB_gl_spirv +#define GL_ARB_gl_spirv 1 +#define GL_SHADER_BINARY_FORMAT_SPIR_V_ARB 0x9551 +#define GL_SPIR_V_BINARY_ARB 0x9552 +typedef void (APIENTRYP PFNGLSPECIALIZESHADERARBPROC) (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSpecializeShaderARB (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); +#endif +#endif /* GL_ARB_gl_spirv */ + +#ifndef GL_ARB_gpu_shader5 +#define GL_ARB_gpu_shader5 1 +#endif /* GL_ARB_gpu_shader5 */ + +#ifndef GL_ARB_gpu_shader_fp64 +#define GL_ARB_gpu_shader_fp64 1 +#endif /* GL_ARB_gpu_shader_fp64 */ + +#ifndef GL_ARB_gpu_shader_int64 +#define GL_ARB_gpu_shader_int64 1 +#define GL_INT64_ARB 0x140E +#define GL_INT64_VEC2_ARB 0x8FE9 +#define GL_INT64_VEC3_ARB 0x8FEA +#define GL_INT64_VEC4_ARB 0x8FEB +#define GL_UNSIGNED_INT64_VEC2_ARB 0x8FF5 +#define GL_UNSIGNED_INT64_VEC3_ARB 0x8FF6 +#define GL_UNSIGNED_INT64_VEC4_ARB 0x8FF7 +typedef void (APIENTRYP PFNGLUNIFORM1I64ARBPROC) (GLint location, GLint64 x); +typedef void (APIENTRYP PFNGLUNIFORM2I64ARBPROC) (GLint location, GLint64 x, GLint64 y); +typedef void (APIENTRYP PFNGLUNIFORM3I64ARBPROC) (GLint location, GLint64 x, GLint64 y, GLint64 z); +typedef void (APIENTRYP PFNGLUNIFORM4I64ARBPROC) (GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); +typedef void (APIENTRYP PFNGLUNIFORM1I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM2I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM3I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM4I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM1UI64ARBPROC) (GLint location, GLuint64 x); +typedef void (APIENTRYP PFNGLUNIFORM2UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y); +typedef void (APIENTRYP PFNGLUNIFORM3UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y, GLuint64 z); +typedef void (APIENTRYP PFNGLUNIFORM4UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); +typedef void (APIENTRYP PFNGLUNIFORM1UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM2UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM3UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLUNIFORM4UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLGETUNIFORMI64VARBPROC) (GLuint program, GLint location, GLint64 *params); +typedef void (APIENTRYP PFNGLGETUNIFORMUI64VARBPROC) (GLuint program, GLint location, GLuint64 *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMI64VARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint64 *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMUI64VARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint64 *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64ARBPROC) (GLuint program, GLint location, GLint64 x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64ARBPROC) (GLuint program, GLint location, GLuint64 x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniform1i64ARB (GLint location, GLint64 x); +GLAPI void APIENTRY glUniform2i64ARB (GLint location, GLint64 x, GLint64 y); +GLAPI void APIENTRY glUniform3i64ARB (GLint location, GLint64 x, GLint64 y, GLint64 z); +GLAPI void APIENTRY glUniform4i64ARB (GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); +GLAPI void APIENTRY glUniform1i64vARB (GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glUniform2i64vARB (GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glUniform3i64vARB (GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glUniform4i64vARB (GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glUniform1ui64ARB (GLint location, GLuint64 x); +GLAPI void APIENTRY glUniform2ui64ARB (GLint location, GLuint64 x, GLuint64 y); +GLAPI void APIENTRY glUniform3ui64ARB (GLint location, GLuint64 x, GLuint64 y, GLuint64 z); +GLAPI void APIENTRY glUniform4ui64ARB (GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); +GLAPI void APIENTRY glUniform1ui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glUniform2ui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glUniform3ui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glUniform4ui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glGetUniformi64vARB (GLuint program, GLint location, GLint64 *params); +GLAPI void APIENTRY glGetUniformui64vARB (GLuint program, GLint location, GLuint64 *params); +GLAPI void APIENTRY glGetnUniformi64vARB (GLuint program, GLint location, GLsizei bufSize, GLint64 *params); +GLAPI void APIENTRY glGetnUniformui64vARB (GLuint program, GLint location, GLsizei bufSize, GLuint64 *params); +GLAPI void APIENTRY glProgramUniform1i64ARB (GLuint program, GLint location, GLint64 x); +GLAPI void APIENTRY glProgramUniform2i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y); +GLAPI void APIENTRY glProgramUniform3i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z); +GLAPI void APIENTRY glProgramUniform4i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); +GLAPI void APIENTRY glProgramUniform1i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glProgramUniform2i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glProgramUniform3i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glProgramUniform4i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); +GLAPI void APIENTRY glProgramUniform1ui64ARB (GLuint program, GLint location, GLuint64 x); +GLAPI void APIENTRY glProgramUniform2ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y); +GLAPI void APIENTRY glProgramUniform3ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z); +GLAPI void APIENTRY glProgramUniform4ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); +GLAPI void APIENTRY glProgramUniform1ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniform2ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniform3ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniform4ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); +#endif +#endif /* GL_ARB_gpu_shader_int64 */ + +#ifndef GL_ARB_half_float_pixel +#define GL_ARB_half_float_pixel 1 +typedef khronos_uint16_t GLhalfARB; +#define GL_HALF_FLOAT_ARB 0x140B +#endif /* GL_ARB_half_float_pixel */ + +#ifndef GL_ARB_half_float_vertex +#define GL_ARB_half_float_vertex 1 +#endif /* GL_ARB_half_float_vertex */ + +#ifndef GL_ARB_imaging +#define GL_ARB_imaging 1 +#define GL_CONVOLUTION_BORDER_MODE 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS 0x8015 +#define GL_REDUCE 0x8016 +#define GL_CONVOLUTION_FORMAT 0x8017 +#define GL_CONVOLUTION_WIDTH 0x8018 +#define GL_CONVOLUTION_HEIGHT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS 0x8023 +#define GL_HISTOGRAM_WIDTH 0x8026 +#define GL_HISTOGRAM_FORMAT 0x8027 +#define GL_HISTOGRAM_RED_SIZE 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE 0x802C +#define GL_HISTOGRAM_SINK 0x802D +#define GL_MINMAX_FORMAT 0x802F +#define GL_MINMAX_SINK 0x8030 +#define GL_TABLE_TOO_LARGE 0x8031 +#define GL_COLOR_MATRIX 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS 0x80BB +#define GL_COLOR_TABLE_SCALE 0x80D6 +#define GL_COLOR_TABLE_BIAS 0x80D7 +#define GL_COLOR_TABLE_FORMAT 0x80D8 +#define GL_COLOR_TABLE_WIDTH 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE 0x80DF +#define GL_CONSTANT_BORDER 0x8151 +#define GL_REPLICATE_BORDER 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR 0x8154 +typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, void *image); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target); +typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTable (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glColorTableParameterfv (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glColorTableParameteriv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyColorTable (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glGetColorTable (GLenum target, GLenum format, GLenum type, void *table); +GLAPI void APIENTRY glGetColorTableParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetColorTableParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glColorSubTable (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glCopyColorSubTable (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glConvolutionFilter1D (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionParameterf (GLenum target, GLenum pname, GLfloat params); +GLAPI void APIENTRY glConvolutionParameterfv (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glConvolutionParameteri (GLenum target, GLenum pname, GLint params); +GLAPI void APIENTRY glConvolutionParameteriv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetConvolutionFilter (GLenum target, GLenum format, GLenum type, void *image); +GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSeparableFilter (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +GLAPI void APIENTRY glSeparableFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +GLAPI void APIENTRY glGetHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetHistogramParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetHistogramParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glHistogram (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glMinmax (GLenum target, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glResetHistogram (GLenum target); +GLAPI void APIENTRY glResetMinmax (GLenum target); +#endif +#endif /* GL_ARB_imaging */ + +#ifndef GL_ARB_indirect_parameters +#define GL_ARB_indirect_parameters 1 +#define GL_PARAMETER_BUFFER_ARB 0x80EE +#define GL_PARAMETER_BUFFER_BINDING_ARB 0x80EF +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTARBPROC) (GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTARBPROC) (GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectCountARB (GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirectCountARB (GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#endif +#endif /* GL_ARB_indirect_parameters */ + +#ifndef GL_ARB_instanced_arrays +#define GL_ARB_instanced_arrays 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB 0x88FE +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORARBPROC) (GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribDivisorARB (GLuint index, GLuint divisor); +#endif +#endif /* GL_ARB_instanced_arrays */ + +#ifndef GL_ARB_internalformat_query +#define GL_ARB_internalformat_query 1 +#endif /* GL_ARB_internalformat_query */ + +#ifndef GL_ARB_internalformat_query2 +#define GL_ARB_internalformat_query2 1 +#define GL_SRGB_DECODE_ARB 0x8299 +#define GL_VIEW_CLASS_EAC_R11 0x9383 +#define GL_VIEW_CLASS_EAC_RG11 0x9384 +#define GL_VIEW_CLASS_ETC2_RGB 0x9385 +#define GL_VIEW_CLASS_ETC2_RGBA 0x9386 +#define GL_VIEW_CLASS_ETC2_EAC_RGBA 0x9387 +#define GL_VIEW_CLASS_ASTC_4x4_RGBA 0x9388 +#define GL_VIEW_CLASS_ASTC_5x4_RGBA 0x9389 +#define GL_VIEW_CLASS_ASTC_5x5_RGBA 0x938A +#define GL_VIEW_CLASS_ASTC_6x5_RGBA 0x938B +#define GL_VIEW_CLASS_ASTC_6x6_RGBA 0x938C +#define GL_VIEW_CLASS_ASTC_8x5_RGBA 0x938D +#define GL_VIEW_CLASS_ASTC_8x6_RGBA 0x938E +#define GL_VIEW_CLASS_ASTC_8x8_RGBA 0x938F +#define GL_VIEW_CLASS_ASTC_10x5_RGBA 0x9390 +#define GL_VIEW_CLASS_ASTC_10x6_RGBA 0x9391 +#define GL_VIEW_CLASS_ASTC_10x8_RGBA 0x9392 +#define GL_VIEW_CLASS_ASTC_10x10_RGBA 0x9393 +#define GL_VIEW_CLASS_ASTC_12x10_RGBA 0x9394 +#define GL_VIEW_CLASS_ASTC_12x12_RGBA 0x9395 +#endif /* GL_ARB_internalformat_query2 */ + +#ifndef GL_ARB_invalidate_subdata +#define GL_ARB_invalidate_subdata 1 +#endif /* GL_ARB_invalidate_subdata */ + +#ifndef GL_ARB_map_buffer_alignment +#define GL_ARB_map_buffer_alignment 1 +#endif /* GL_ARB_map_buffer_alignment */ + +#ifndef GL_ARB_map_buffer_range +#define GL_ARB_map_buffer_range 1 +#endif /* GL_ARB_map_buffer_range */ + +#ifndef GL_ARB_matrix_palette +#define GL_ARB_matrix_palette 1 +#define GL_MATRIX_PALETTE_ARB 0x8840 +#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841 +#define GL_MAX_PALETTE_MATRICES_ARB 0x8842 +#define GL_CURRENT_PALETTE_MATRIX_ARB 0x8843 +#define GL_MATRIX_INDEX_ARRAY_ARB 0x8844 +#define GL_CURRENT_MATRIX_INDEX_ARB 0x8845 +#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB 0x8846 +#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB 0x8847 +#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB 0x8848 +#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849 +typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index); +typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint index); +GLAPI void APIENTRY glMatrixIndexubvARB (GLint size, const GLubyte *indices); +GLAPI void APIENTRY glMatrixIndexusvARB (GLint size, const GLushort *indices); +GLAPI void APIENTRY glMatrixIndexuivARB (GLint size, const GLuint *indices); +GLAPI void APIENTRY glMatrixIndexPointerARB (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_ARB_matrix_palette */ + +#ifndef GL_ARB_multi_bind +#define GL_ARB_multi_bind 1 +#endif /* GL_ARB_multi_bind */ + +#ifndef GL_ARB_multi_draw_indirect +#define GL_ARB_multi_draw_indirect 1 +#endif /* GL_ARB_multi_draw_indirect */ + +#ifndef GL_ARB_multisample +#define GL_ARB_multisample 1 +#define GL_MULTISAMPLE_ARB 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F +#define GL_SAMPLE_COVERAGE_ARB 0x80A0 +#define GL_SAMPLE_BUFFERS_ARB 0x80A8 +#define GL_SAMPLES_ARB 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB +#define GL_MULTISAMPLE_BIT_ARB 0x20000000 +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLfloat value, GLboolean invert); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleCoverageARB (GLfloat value, GLboolean invert); +#endif +#endif /* GL_ARB_multisample */ + +#ifndef GL_ARB_multitexture +#define GL_ARB_multitexture 1 +#define GL_TEXTURE0_ARB 0x84C0 +#define GL_TEXTURE1_ARB 0x84C1 +#define GL_TEXTURE2_ARB 0x84C2 +#define GL_TEXTURE3_ARB 0x84C3 +#define GL_TEXTURE4_ARB 0x84C4 +#define GL_TEXTURE5_ARB 0x84C5 +#define GL_TEXTURE6_ARB 0x84C6 +#define GL_TEXTURE7_ARB 0x84C7 +#define GL_TEXTURE8_ARB 0x84C8 +#define GL_TEXTURE9_ARB 0x84C9 +#define GL_TEXTURE10_ARB 0x84CA +#define GL_TEXTURE11_ARB 0x84CB +#define GL_TEXTURE12_ARB 0x84CC +#define GL_TEXTURE13_ARB 0x84CD +#define GL_TEXTURE14_ARB 0x84CE +#define GL_TEXTURE15_ARB 0x84CF +#define GL_TEXTURE16_ARB 0x84D0 +#define GL_TEXTURE17_ARB 0x84D1 +#define GL_TEXTURE18_ARB 0x84D2 +#define GL_TEXTURE19_ARB 0x84D3 +#define GL_TEXTURE20_ARB 0x84D4 +#define GL_TEXTURE21_ARB 0x84D5 +#define GL_TEXTURE22_ARB 0x84D6 +#define GL_TEXTURE23_ARB 0x84D7 +#define GL_TEXTURE24_ARB 0x84D8 +#define GL_TEXTURE25_ARB 0x84D9 +#define GL_TEXTURE26_ARB 0x84DA +#define GL_TEXTURE27_ARB 0x84DB +#define GL_TEXTURE28_ARB 0x84DC +#define GL_TEXTURE29_ARB 0x84DD +#define GL_TEXTURE30_ARB 0x84DE +#define GL_TEXTURE31_ARB 0x84DF +#define GL_ACTIVE_TEXTURE_ARB 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 +#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 +typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTextureARB (GLenum texture); +GLAPI void APIENTRY glClientActiveTextureARB (GLenum texture); +GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum target, GLdouble s); +GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum target, GLfloat s); +GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum target, GLint s); +GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum target, GLshort s); +GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum target, GLdouble s, GLdouble t); +GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum target, GLfloat s, GLfloat t); +GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum target, GLint s, GLint t); +GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum target, GLshort s, GLshort t); +GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum target, GLint s, GLint t, GLint r); +GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum target, const GLshort *v); +#endif +#endif /* GL_ARB_multitexture */ + +#ifndef GL_ARB_occlusion_query +#define GL_ARB_occlusion_query 1 +#define GL_QUERY_COUNTER_BITS_ARB 0x8864 +#define GL_CURRENT_QUERY_ARB 0x8865 +#define GL_QUERY_RESULT_ARB 0x8866 +#define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867 +#define GL_SAMPLES_PASSED_ARB 0x8914 +typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueriesARB (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteQueriesARB (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsQueryARB (GLuint id); +GLAPI void APIENTRY glBeginQueryARB (GLenum target, GLuint id); +GLAPI void APIENTRY glEndQueryARB (GLenum target); +GLAPI void APIENTRY glGetQueryivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectivARB (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint id, GLenum pname, GLuint *params); +#endif +#endif /* GL_ARB_occlusion_query */ + +#ifndef GL_ARB_occlusion_query2 +#define GL_ARB_occlusion_query2 1 +#endif /* GL_ARB_occlusion_query2 */ + +#ifndef GL_ARB_parallel_shader_compile +#define GL_ARB_parallel_shader_compile 1 +#define GL_MAX_SHADER_COMPILER_THREADS_ARB 0x91B0 +#define GL_COMPLETION_STATUS_ARB 0x91B1 +typedef void (APIENTRYP PFNGLMAXSHADERCOMPILERTHREADSARBPROC) (GLuint count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMaxShaderCompilerThreadsARB (GLuint count); +#endif +#endif /* GL_ARB_parallel_shader_compile */ + +#ifndef GL_ARB_pipeline_statistics_query +#define GL_ARB_pipeline_statistics_query 1 +#define GL_VERTICES_SUBMITTED_ARB 0x82EE +#define GL_PRIMITIVES_SUBMITTED_ARB 0x82EF +#define GL_VERTEX_SHADER_INVOCATIONS_ARB 0x82F0 +#define GL_TESS_CONTROL_SHADER_PATCHES_ARB 0x82F1 +#define GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB 0x82F2 +#define GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB 0x82F3 +#define GL_FRAGMENT_SHADER_INVOCATIONS_ARB 0x82F4 +#define GL_COMPUTE_SHADER_INVOCATIONS_ARB 0x82F5 +#define GL_CLIPPING_INPUT_PRIMITIVES_ARB 0x82F6 +#define GL_CLIPPING_OUTPUT_PRIMITIVES_ARB 0x82F7 +#endif /* GL_ARB_pipeline_statistics_query */ + +#ifndef GL_ARB_pixel_buffer_object +#define GL_ARB_pixel_buffer_object 1 +#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF +#endif /* GL_ARB_pixel_buffer_object */ + +#ifndef GL_ARB_point_parameters +#define GL_ARB_point_parameters 1 +#define GL_POINT_SIZE_MIN_ARB 0x8126 +#define GL_POINT_SIZE_MAX_ARB 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_ARB 0x8128 +#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfARB (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvARB (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_ARB_point_parameters */ + +#ifndef GL_ARB_point_sprite +#define GL_ARB_point_sprite 1 +#define GL_POINT_SPRITE_ARB 0x8861 +#define GL_COORD_REPLACE_ARB 0x8862 +#endif /* GL_ARB_point_sprite */ + +#ifndef GL_ARB_polygon_offset_clamp +#define GL_ARB_polygon_offset_clamp 1 +#endif /* GL_ARB_polygon_offset_clamp */ + +#ifndef GL_ARB_post_depth_coverage +#define GL_ARB_post_depth_coverage 1 +#endif /* GL_ARB_post_depth_coverage */ + +#ifndef GL_ARB_program_interface_query +#define GL_ARB_program_interface_query 1 +#endif /* GL_ARB_program_interface_query */ + +#ifndef GL_ARB_provoking_vertex +#define GL_ARB_provoking_vertex 1 +#endif /* GL_ARB_provoking_vertex */ + +#ifndef GL_ARB_query_buffer_object +#define GL_ARB_query_buffer_object 1 +#endif /* GL_ARB_query_buffer_object */ + +#ifndef GL_ARB_robust_buffer_access_behavior +#define GL_ARB_robust_buffer_access_behavior 1 +#endif /* GL_ARB_robust_buffer_access_behavior */ + +#ifndef GL_ARB_robustness +#define GL_ARB_robustness 1 +#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004 +#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 +#define GL_GUILTY_CONTEXT_RESET_ARB 0x8253 +#define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255 +#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 +#define GL_NO_RESET_NOTIFICATION_ARB 0x8261 +typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC) (void); +typedef void (APIENTRYP PFNGLGETNTEXIMAGEARBPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); +typedef void (APIENTRYP PFNGLREADNPIXELSARBPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint lod, GLsizei bufSize, void *img); +typedef void (APIENTRYP PFNGLGETNUNIFORMFVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMUIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNMAPDVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +typedef void (APIENTRYP PFNGLGETNMAPFVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +typedef void (APIENTRYP PFNGLGETNMAPIVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +typedef void (APIENTRYP PFNGLGETNPIXELMAPFVARBPROC) (GLenum map, GLsizei bufSize, GLfloat *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVARBPROC) (GLenum map, GLsizei bufSize, GLuint *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVARBPROC) (GLenum map, GLsizei bufSize, GLushort *values); +typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEARBPROC) (GLsizei bufSize, GLubyte *pattern); +typedef void (APIENTRYP PFNGLGETNCOLORTABLEARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +typedef void (APIENTRYP PFNGLGETNHISTOGRAMARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLGETNMINMAXARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLenum APIENTRY glGetGraphicsResetStatusARB (void); +GLAPI void APIENTRY glGetnTexImageARB (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); +GLAPI void APIENTRY glReadnPixelsARB (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GLAPI void APIENTRY glGetnCompressedTexImageARB (GLenum target, GLint lod, GLsizei bufSize, void *img); +GLAPI void APIENTRY glGetnUniformfvARB (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GLAPI void APIENTRY glGetnUniformivARB (GLuint program, GLint location, GLsizei bufSize, GLint *params); +GLAPI void APIENTRY glGetnUniformuivARB (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +GLAPI void APIENTRY glGetnUniformdvARB (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +GLAPI void APIENTRY glGetnMapdvARB (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +GLAPI void APIENTRY glGetnMapfvARB (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +GLAPI void APIENTRY glGetnMapivARB (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +GLAPI void APIENTRY glGetnPixelMapfvARB (GLenum map, GLsizei bufSize, GLfloat *values); +GLAPI void APIENTRY glGetnPixelMapuivARB (GLenum map, GLsizei bufSize, GLuint *values); +GLAPI void APIENTRY glGetnPixelMapusvARB (GLenum map, GLsizei bufSize, GLushort *values); +GLAPI void APIENTRY glGetnPolygonStippleARB (GLsizei bufSize, GLubyte *pattern); +GLAPI void APIENTRY glGetnColorTableARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +GLAPI void APIENTRY glGetnConvolutionFilterARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +GLAPI void APIENTRY glGetnSeparableFilterARB (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +GLAPI void APIENTRY glGetnHistogramARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glGetnMinmaxARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +#endif +#endif /* GL_ARB_robustness */ + +#ifndef GL_ARB_robustness_isolation +#define GL_ARB_robustness_isolation 1 +#endif /* GL_ARB_robustness_isolation */ + +#ifndef GL_ARB_sample_locations +#define GL_ARB_sample_locations 1 +#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_ARB 0x933D +#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_ARB 0x933E +#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_ARB 0x933F +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_ARB 0x9340 +#define GL_SAMPLE_LOCATION_ARB 0x8E50 +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_ARB 0x9341 +#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB 0x9342 +#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB 0x9343 +typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVARBPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVARBPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLEVALUATEDEPTHVALUESARBPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferSampleLocationsfvARB (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glNamedFramebufferSampleLocationsfvARB (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glEvaluateDepthValuesARB (void); +#endif +#endif /* GL_ARB_sample_locations */ + +#ifndef GL_ARB_sample_shading +#define GL_ARB_sample_shading 1 +#define GL_SAMPLE_SHADING_ARB 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE_ARB 0x8C37 +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGARBPROC) (GLfloat value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMinSampleShadingARB (GLfloat value); +#endif +#endif /* GL_ARB_sample_shading */ + +#ifndef GL_ARB_sampler_objects +#define GL_ARB_sampler_objects 1 +#endif /* GL_ARB_sampler_objects */ + +#ifndef GL_ARB_seamless_cube_map +#define GL_ARB_seamless_cube_map 1 +#endif /* GL_ARB_seamless_cube_map */ + +#ifndef GL_ARB_seamless_cubemap_per_texture +#define GL_ARB_seamless_cubemap_per_texture 1 +#endif /* GL_ARB_seamless_cubemap_per_texture */ + +#ifndef GL_ARB_separate_shader_objects +#define GL_ARB_separate_shader_objects 1 +#endif /* GL_ARB_separate_shader_objects */ + +#ifndef GL_ARB_shader_atomic_counter_ops +#define GL_ARB_shader_atomic_counter_ops 1 +#endif /* GL_ARB_shader_atomic_counter_ops */ + +#ifndef GL_ARB_shader_atomic_counters +#define GL_ARB_shader_atomic_counters 1 +#endif /* GL_ARB_shader_atomic_counters */ + +#ifndef GL_ARB_shader_ballot +#define GL_ARB_shader_ballot 1 +#endif /* GL_ARB_shader_ballot */ + +#ifndef GL_ARB_shader_bit_encoding +#define GL_ARB_shader_bit_encoding 1 +#endif /* GL_ARB_shader_bit_encoding */ + +#ifndef GL_ARB_shader_clock +#define GL_ARB_shader_clock 1 +#endif /* GL_ARB_shader_clock */ + +#ifndef GL_ARB_shader_draw_parameters +#define GL_ARB_shader_draw_parameters 1 +#endif /* GL_ARB_shader_draw_parameters */ + +#ifndef GL_ARB_shader_group_vote +#define GL_ARB_shader_group_vote 1 +#endif /* GL_ARB_shader_group_vote */ + +#ifndef GL_ARB_shader_image_load_store +#define GL_ARB_shader_image_load_store 1 +#endif /* GL_ARB_shader_image_load_store */ + +#ifndef GL_ARB_shader_image_size +#define GL_ARB_shader_image_size 1 +#endif /* GL_ARB_shader_image_size */ + +#ifndef GL_ARB_shader_objects +#define GL_ARB_shader_objects 1 +#ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif +typedef char GLcharARB; +#define GL_PROGRAM_OBJECT_ARB 0x8B40 +#define GL_SHADER_OBJECT_ARB 0x8B48 +#define GL_OBJECT_TYPE_ARB 0x8B4E +#define GL_OBJECT_SUBTYPE_ARB 0x8B4F +#define GL_FLOAT_VEC2_ARB 0x8B50 +#define GL_FLOAT_VEC3_ARB 0x8B51 +#define GL_FLOAT_VEC4_ARB 0x8B52 +#define GL_INT_VEC2_ARB 0x8B53 +#define GL_INT_VEC3_ARB 0x8B54 +#define GL_INT_VEC4_ARB 0x8B55 +#define GL_BOOL_ARB 0x8B56 +#define GL_BOOL_VEC2_ARB 0x8B57 +#define GL_BOOL_VEC3_ARB 0x8B58 +#define GL_BOOL_VEC4_ARB 0x8B59 +#define GL_FLOAT_MAT2_ARB 0x8B5A +#define GL_FLOAT_MAT3_ARB 0x8B5B +#define GL_FLOAT_MAT4_ARB 0x8B5C +#define GL_SAMPLER_1D_ARB 0x8B5D +#define GL_SAMPLER_2D_ARB 0x8B5E +#define GL_SAMPLER_3D_ARB 0x8B5F +#define GL_SAMPLER_CUBE_ARB 0x8B60 +#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61 +#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62 +#define GL_SAMPLER_2D_RECT_ARB 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64 +#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80 +#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 +#define GL_OBJECT_LINK_STATUS_ARB 0x8B82 +#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83 +#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 +#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85 +#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86 +#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87 +#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88 +typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj); +typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname); +typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj); +typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType); +typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); +typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj); +typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void); +typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj); +typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); +typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params); +typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB obj); +GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum pname); +GLAPI void APIENTRY glDetachObjectARB (GLhandleARB containerObj, GLhandleARB attachedObj); +GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum shaderType); +GLAPI void APIENTRY glShaderSourceARB (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); +GLAPI void APIENTRY glCompileShaderARB (GLhandleARB shaderObj); +GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void); +GLAPI void APIENTRY glAttachObjectARB (GLhandleARB containerObj, GLhandleARB obj); +GLAPI void APIENTRY glLinkProgramARB (GLhandleARB programObj); +GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB programObj); +GLAPI void APIENTRY glValidateProgramARB (GLhandleARB programObj); +GLAPI void APIENTRY glUniform1fARB (GLint location, GLfloat v0); +GLAPI void APIENTRY glUniform2fARB (GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glUniform3fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glUniform4fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glUniform1iARB (GLint location, GLint v0); +GLAPI void APIENTRY glUniform2iARB (GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glUniform3iARB (GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glUniform4iARB (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glUniform1fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform2fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform3fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform4fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform1ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform2ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform3ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform4ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniformMatrix2fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB obj, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB obj, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); +GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); +GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB programObj, const GLcharARB *name); +GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB programObj, GLint location, GLfloat *params); +GLAPI void APIENTRY glGetUniformivARB (GLhandleARB programObj, GLint location, GLint *params); +GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); +#endif +#endif /* GL_ARB_shader_objects */ + +#ifndef GL_ARB_shader_precision +#define GL_ARB_shader_precision 1 +#endif /* GL_ARB_shader_precision */ + +#ifndef GL_ARB_shader_stencil_export +#define GL_ARB_shader_stencil_export 1 +#endif /* GL_ARB_shader_stencil_export */ + +#ifndef GL_ARB_shader_storage_buffer_object +#define GL_ARB_shader_storage_buffer_object 1 +#endif /* GL_ARB_shader_storage_buffer_object */ + +#ifndef GL_ARB_shader_subroutine +#define GL_ARB_shader_subroutine 1 +#endif /* GL_ARB_shader_subroutine */ + +#ifndef GL_ARB_shader_texture_image_samples +#define GL_ARB_shader_texture_image_samples 1 +#endif /* GL_ARB_shader_texture_image_samples */ + +#ifndef GL_ARB_shader_texture_lod +#define GL_ARB_shader_texture_lod 1 +#endif /* GL_ARB_shader_texture_lod */ + +#ifndef GL_ARB_shader_viewport_layer_array +#define GL_ARB_shader_viewport_layer_array 1 +#endif /* GL_ARB_shader_viewport_layer_array */ + +#ifndef GL_ARB_shading_language_100 +#define GL_ARB_shading_language_100 1 +#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C +#endif /* GL_ARB_shading_language_100 */ + +#ifndef GL_ARB_shading_language_420pack +#define GL_ARB_shading_language_420pack 1 +#endif /* GL_ARB_shading_language_420pack */ + +#ifndef GL_ARB_shading_language_include +#define GL_ARB_shading_language_include 1 +#define GL_SHADER_INCLUDE_ARB 0x8DAE +#define GL_NAMED_STRING_LENGTH_ARB 0x8DE9 +#define GL_NAMED_STRING_TYPE_ARB 0x8DEA +typedef void (APIENTRYP PFNGLNAMEDSTRINGARBPROC) (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string); +typedef void (APIENTRYP PFNGLDELETENAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name); +typedef void (APIENTRYP PFNGLCOMPILESHADERINCLUDEARBPROC) (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length); +typedef GLboolean (APIENTRYP PFNGLISNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name); +typedef void (APIENTRYP PFNGLGETNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string); +typedef void (APIENTRYP PFNGLGETNAMEDSTRINGIVARBPROC) (GLint namelen, const GLchar *name, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glNamedStringARB (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string); +GLAPI void APIENTRY glDeleteNamedStringARB (GLint namelen, const GLchar *name); +GLAPI void APIENTRY glCompileShaderIncludeARB (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length); +GLAPI GLboolean APIENTRY glIsNamedStringARB (GLint namelen, const GLchar *name); +GLAPI void APIENTRY glGetNamedStringARB (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string); +GLAPI void APIENTRY glGetNamedStringivARB (GLint namelen, const GLchar *name, GLenum pname, GLint *params); +#endif +#endif /* GL_ARB_shading_language_include */ + +#ifndef GL_ARB_shading_language_packing +#define GL_ARB_shading_language_packing 1 +#endif /* GL_ARB_shading_language_packing */ + +#ifndef GL_ARB_shadow +#define GL_ARB_shadow 1 +#define GL_TEXTURE_COMPARE_MODE_ARB 0x884C +#define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D +#define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E +#endif /* GL_ARB_shadow */ + +#ifndef GL_ARB_shadow_ambient +#define GL_ARB_shadow_ambient 1 +#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF +#endif /* GL_ARB_shadow_ambient */ + +#ifndef GL_ARB_sparse_buffer +#define GL_ARB_sparse_buffer 1 +#define GL_SPARSE_STORAGE_BIT_ARB 0x0400 +#define GL_SPARSE_BUFFER_PAGE_SIZE_ARB 0x82F8 +typedef void (APIENTRYP PFNGLBUFFERPAGECOMMITMENTARBPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit); +typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTARBPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferPageCommitmentARB (GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit); +GLAPI void APIENTRY glNamedBufferPageCommitmentEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +GLAPI void APIENTRY glNamedBufferPageCommitmentARB (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +#endif +#endif /* GL_ARB_sparse_buffer */ + +#ifndef GL_ARB_sparse_texture +#define GL_ARB_sparse_texture 1 +#define GL_TEXTURE_SPARSE_ARB 0x91A6 +#define GL_VIRTUAL_PAGE_SIZE_INDEX_ARB 0x91A7 +#define GL_NUM_SPARSE_LEVELS_ARB 0x91AA +#define GL_NUM_VIRTUAL_PAGE_SIZES_ARB 0x91A8 +#define GL_VIRTUAL_PAGE_SIZE_X_ARB 0x9195 +#define GL_VIRTUAL_PAGE_SIZE_Y_ARB 0x9196 +#define GL_VIRTUAL_PAGE_SIZE_Z_ARB 0x9197 +#define GL_MAX_SPARSE_TEXTURE_SIZE_ARB 0x9198 +#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB 0x9199 +#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB 0x919A +#define GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB 0x91A9 +typedef void (APIENTRYP PFNGLTEXPAGECOMMITMENTARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexPageCommitmentARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +#endif +#endif /* GL_ARB_sparse_texture */ + +#ifndef GL_ARB_sparse_texture2 +#define GL_ARB_sparse_texture2 1 +#endif /* GL_ARB_sparse_texture2 */ + +#ifndef GL_ARB_sparse_texture_clamp +#define GL_ARB_sparse_texture_clamp 1 +#endif /* GL_ARB_sparse_texture_clamp */ + +#ifndef GL_ARB_spirv_extensions +#define GL_ARB_spirv_extensions 1 +#endif /* GL_ARB_spirv_extensions */ + +#ifndef GL_ARB_stencil_texturing +#define GL_ARB_stencil_texturing 1 +#endif /* GL_ARB_stencil_texturing */ + +#ifndef GL_ARB_sync +#define GL_ARB_sync 1 +#endif /* GL_ARB_sync */ + +#ifndef GL_ARB_tessellation_shader +#define GL_ARB_tessellation_shader 1 +#endif /* GL_ARB_tessellation_shader */ + +#ifndef GL_ARB_texture_barrier +#define GL_ARB_texture_barrier 1 +#endif /* GL_ARB_texture_barrier */ + +#ifndef GL_ARB_texture_border_clamp +#define GL_ARB_texture_border_clamp 1 +#define GL_CLAMP_TO_BORDER_ARB 0x812D +#endif /* GL_ARB_texture_border_clamp */ + +#ifndef GL_ARB_texture_buffer_object +#define GL_ARB_texture_buffer_object 1 +#define GL_TEXTURE_BUFFER_ARB 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE_ARB 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER_ARB 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB 0x8C2D +#define GL_TEXTURE_BUFFER_FORMAT_ARB 0x8C2E +typedef void (APIENTRYP PFNGLTEXBUFFERARBPROC) (GLenum target, GLenum internalformat, GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBufferARB (GLenum target, GLenum internalformat, GLuint buffer); +#endif +#endif /* GL_ARB_texture_buffer_object */ + +#ifndef GL_ARB_texture_buffer_object_rgb32 +#define GL_ARB_texture_buffer_object_rgb32 1 +#endif /* GL_ARB_texture_buffer_object_rgb32 */ + +#ifndef GL_ARB_texture_buffer_range +#define GL_ARB_texture_buffer_range 1 +#endif /* GL_ARB_texture_buffer_range */ + +#ifndef GL_ARB_texture_compression +#define GL_ARB_texture_compression 1 +#define GL_COMPRESSED_ALPHA_ARB 0x84E9 +#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB +#define GL_COMPRESSED_INTENSITY_ARB 0x84EC +#define GL_COMPRESSED_RGB_ARB 0x84ED +#define GL_COMPRESSED_RGBA_ARB 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 +#define GL_TEXTURE_COMPRESSED_ARB 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, void *img); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum target, GLint level, void *img); +#endif +#endif /* GL_ARB_texture_compression */ + +#ifndef GL_ARB_texture_compression_bptc +#define GL_ARB_texture_compression_bptc 1 +#define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F +#endif /* GL_ARB_texture_compression_bptc */ + +#ifndef GL_ARB_texture_compression_rgtc +#define GL_ARB_texture_compression_rgtc 1 +#endif /* GL_ARB_texture_compression_rgtc */ + +#ifndef GL_ARB_texture_cube_map +#define GL_ARB_texture_cube_map 1 +#define GL_NORMAL_MAP_ARB 0x8511 +#define GL_REFLECTION_MAP_ARB 0x8512 +#define GL_TEXTURE_CUBE_MAP_ARB 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C +#endif /* GL_ARB_texture_cube_map */ + +#ifndef GL_ARB_texture_cube_map_array +#define GL_ARB_texture_cube_map_array 1 +#define GL_TEXTURE_CUBE_MAP_ARRAY_ARB 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB 0x900A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB 0x900B +#define GL_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F +#endif /* GL_ARB_texture_cube_map_array */ + +#ifndef GL_ARB_texture_env_add +#define GL_ARB_texture_env_add 1 +#endif /* GL_ARB_texture_env_add */ + +#ifndef GL_ARB_texture_env_combine +#define GL_ARB_texture_env_combine 1 +#define GL_COMBINE_ARB 0x8570 +#define GL_COMBINE_RGB_ARB 0x8571 +#define GL_COMBINE_ALPHA_ARB 0x8572 +#define GL_SOURCE0_RGB_ARB 0x8580 +#define GL_SOURCE1_RGB_ARB 0x8581 +#define GL_SOURCE2_RGB_ARB 0x8582 +#define GL_SOURCE0_ALPHA_ARB 0x8588 +#define GL_SOURCE1_ALPHA_ARB 0x8589 +#define GL_SOURCE2_ALPHA_ARB 0x858A +#define GL_OPERAND0_RGB_ARB 0x8590 +#define GL_OPERAND1_RGB_ARB 0x8591 +#define GL_OPERAND2_RGB_ARB 0x8592 +#define GL_OPERAND0_ALPHA_ARB 0x8598 +#define GL_OPERAND1_ALPHA_ARB 0x8599 +#define GL_OPERAND2_ALPHA_ARB 0x859A +#define GL_RGB_SCALE_ARB 0x8573 +#define GL_ADD_SIGNED_ARB 0x8574 +#define GL_INTERPOLATE_ARB 0x8575 +#define GL_SUBTRACT_ARB 0x84E7 +#define GL_CONSTANT_ARB 0x8576 +#define GL_PRIMARY_COLOR_ARB 0x8577 +#define GL_PREVIOUS_ARB 0x8578 +#endif /* GL_ARB_texture_env_combine */ + +#ifndef GL_ARB_texture_env_crossbar +#define GL_ARB_texture_env_crossbar 1 +#endif /* GL_ARB_texture_env_crossbar */ + +#ifndef GL_ARB_texture_env_dot3 +#define GL_ARB_texture_env_dot3 1 +#define GL_DOT3_RGB_ARB 0x86AE +#define GL_DOT3_RGBA_ARB 0x86AF +#endif /* GL_ARB_texture_env_dot3 */ + +#ifndef GL_ARB_texture_filter_anisotropic +#define GL_ARB_texture_filter_anisotropic 1 +#endif /* GL_ARB_texture_filter_anisotropic */ + +#ifndef GL_ARB_texture_filter_minmax +#define GL_ARB_texture_filter_minmax 1 +#define GL_TEXTURE_REDUCTION_MODE_ARB 0x9366 +#define GL_WEIGHTED_AVERAGE_ARB 0x9367 +#endif /* GL_ARB_texture_filter_minmax */ + +#ifndef GL_ARB_texture_float +#define GL_ARB_texture_float 1 +#define GL_TEXTURE_RED_TYPE_ARB 0x8C10 +#define GL_TEXTURE_GREEN_TYPE_ARB 0x8C11 +#define GL_TEXTURE_BLUE_TYPE_ARB 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE_ARB 0x8C13 +#define GL_TEXTURE_LUMINANCE_TYPE_ARB 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE_ARB 0x8C15 +#define GL_TEXTURE_DEPTH_TYPE_ARB 0x8C16 +#define GL_UNSIGNED_NORMALIZED_ARB 0x8C17 +#define GL_RGBA32F_ARB 0x8814 +#define GL_RGB32F_ARB 0x8815 +#define GL_ALPHA32F_ARB 0x8816 +#define GL_INTENSITY32F_ARB 0x8817 +#define GL_LUMINANCE32F_ARB 0x8818 +#define GL_LUMINANCE_ALPHA32F_ARB 0x8819 +#define GL_RGBA16F_ARB 0x881A +#define GL_RGB16F_ARB 0x881B +#define GL_ALPHA16F_ARB 0x881C +#define GL_INTENSITY16F_ARB 0x881D +#define GL_LUMINANCE16F_ARB 0x881E +#define GL_LUMINANCE_ALPHA16F_ARB 0x881F +#endif /* GL_ARB_texture_float */ + +#ifndef GL_ARB_texture_gather +#define GL_ARB_texture_gather 1 +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F +#define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB 0x8F9F +#endif /* GL_ARB_texture_gather */ + +#ifndef GL_ARB_texture_mirror_clamp_to_edge +#define GL_ARB_texture_mirror_clamp_to_edge 1 +#endif /* GL_ARB_texture_mirror_clamp_to_edge */ + +#ifndef GL_ARB_texture_mirrored_repeat +#define GL_ARB_texture_mirrored_repeat 1 +#define GL_MIRRORED_REPEAT_ARB 0x8370 +#endif /* GL_ARB_texture_mirrored_repeat */ + +#ifndef GL_ARB_texture_multisample +#define GL_ARB_texture_multisample 1 +#endif /* GL_ARB_texture_multisample */ + +#ifndef GL_ARB_texture_non_power_of_two +#define GL_ARB_texture_non_power_of_two 1 +#endif /* GL_ARB_texture_non_power_of_two */ + +#ifndef GL_ARB_texture_query_levels +#define GL_ARB_texture_query_levels 1 +#endif /* GL_ARB_texture_query_levels */ + +#ifndef GL_ARB_texture_query_lod +#define GL_ARB_texture_query_lod 1 +#endif /* GL_ARB_texture_query_lod */ + +#ifndef GL_ARB_texture_rectangle +#define GL_ARB_texture_rectangle 1 +#define GL_TEXTURE_RECTANGLE_ARB 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE_ARB 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE_ARB 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8 +#endif /* GL_ARB_texture_rectangle */ + +#ifndef GL_ARB_texture_rg +#define GL_ARB_texture_rg 1 +#endif /* GL_ARB_texture_rg */ + +#ifndef GL_ARB_texture_rgb10_a2ui +#define GL_ARB_texture_rgb10_a2ui 1 +#endif /* GL_ARB_texture_rgb10_a2ui */ + +#ifndef GL_ARB_texture_stencil8 +#define GL_ARB_texture_stencil8 1 +#endif /* GL_ARB_texture_stencil8 */ + +#ifndef GL_ARB_texture_storage +#define GL_ARB_texture_storage 1 +#endif /* GL_ARB_texture_storage */ + +#ifndef GL_ARB_texture_storage_multisample +#define GL_ARB_texture_storage_multisample 1 +#endif /* GL_ARB_texture_storage_multisample */ + +#ifndef GL_ARB_texture_swizzle +#define GL_ARB_texture_swizzle 1 +#endif /* GL_ARB_texture_swizzle */ + +#ifndef GL_ARB_texture_view +#define GL_ARB_texture_view 1 +#endif /* GL_ARB_texture_view */ + +#ifndef GL_ARB_timer_query +#define GL_ARB_timer_query 1 +#endif /* GL_ARB_timer_query */ + +#ifndef GL_ARB_transform_feedback2 +#define GL_ARB_transform_feedback2 1 +#endif /* GL_ARB_transform_feedback2 */ + +#ifndef GL_ARB_transform_feedback3 +#define GL_ARB_transform_feedback3 1 +#endif /* GL_ARB_transform_feedback3 */ + +#ifndef GL_ARB_transform_feedback_instanced +#define GL_ARB_transform_feedback_instanced 1 +#endif /* GL_ARB_transform_feedback_instanced */ + +#ifndef GL_ARB_transform_feedback_overflow_query +#define GL_ARB_transform_feedback_overflow_query 1 +#define GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB 0x82EC +#define GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB 0x82ED +#endif /* GL_ARB_transform_feedback_overflow_query */ + +#ifndef GL_ARB_transpose_matrix +#define GL_ARB_transpose_matrix 1 +#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX_ARB 0x84E6 +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *m); +GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *m); +GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *m); +GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *m); +#endif +#endif /* GL_ARB_transpose_matrix */ + +#ifndef GL_ARB_uniform_buffer_object +#define GL_ARB_uniform_buffer_object 1 +#endif /* GL_ARB_uniform_buffer_object */ + +#ifndef GL_ARB_vertex_array_bgra +#define GL_ARB_vertex_array_bgra 1 +#endif /* GL_ARB_vertex_array_bgra */ + +#ifndef GL_ARB_vertex_array_object +#define GL_ARB_vertex_array_object 1 +#endif /* GL_ARB_vertex_array_object */ + +#ifndef GL_ARB_vertex_attrib_64bit +#define GL_ARB_vertex_attrib_64bit 1 +#endif /* GL_ARB_vertex_attrib_64bit */ + +#ifndef GL_ARB_vertex_attrib_binding +#define GL_ARB_vertex_attrib_binding 1 +#endif /* GL_ARB_vertex_attrib_binding */ + +#ifndef GL_ARB_vertex_blend +#define GL_ARB_vertex_blend 1 +#define GL_MAX_VERTEX_UNITS_ARB 0x86A4 +#define GL_ACTIVE_VERTEX_UNITS_ARB 0x86A5 +#define GL_WEIGHT_SUM_UNITY_ARB 0x86A6 +#define GL_VERTEX_BLEND_ARB 0x86A7 +#define GL_CURRENT_WEIGHT_ARB 0x86A8 +#define GL_WEIGHT_ARRAY_TYPE_ARB 0x86A9 +#define GL_WEIGHT_ARRAY_STRIDE_ARB 0x86AA +#define GL_WEIGHT_ARRAY_SIZE_ARB 0x86AB +#define GL_WEIGHT_ARRAY_POINTER_ARB 0x86AC +#define GL_WEIGHT_ARRAY_ARB 0x86AD +#define GL_MODELVIEW0_ARB 0x1700 +#define GL_MODELVIEW1_ARB 0x850A +#define GL_MODELVIEW2_ARB 0x8722 +#define GL_MODELVIEW3_ARB 0x8723 +#define GL_MODELVIEW4_ARB 0x8724 +#define GL_MODELVIEW5_ARB 0x8725 +#define GL_MODELVIEW6_ARB 0x8726 +#define GL_MODELVIEW7_ARB 0x8727 +#define GL_MODELVIEW8_ARB 0x8728 +#define GL_MODELVIEW9_ARB 0x8729 +#define GL_MODELVIEW10_ARB 0x872A +#define GL_MODELVIEW11_ARB 0x872B +#define GL_MODELVIEW12_ARB 0x872C +#define GL_MODELVIEW13_ARB 0x872D +#define GL_MODELVIEW14_ARB 0x872E +#define GL_MODELVIEW15_ARB 0x872F +#define GL_MODELVIEW16_ARB 0x8730 +#define GL_MODELVIEW17_ARB 0x8731 +#define GL_MODELVIEW18_ARB 0x8732 +#define GL_MODELVIEW19_ARB 0x8733 +#define GL_MODELVIEW20_ARB 0x8734 +#define GL_MODELVIEW21_ARB 0x8735 +#define GL_MODELVIEW22_ARB 0x8736 +#define GL_MODELVIEW23_ARB 0x8737 +#define GL_MODELVIEW24_ARB 0x8738 +#define GL_MODELVIEW25_ARB 0x8739 +#define GL_MODELVIEW26_ARB 0x873A +#define GL_MODELVIEW27_ARB 0x873B +#define GL_MODELVIEW28_ARB 0x873C +#define GL_MODELVIEW29_ARB 0x873D +#define GL_MODELVIEW30_ARB 0x873E +#define GL_MODELVIEW31_ARB 0x873F +typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights); +typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights); +typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights); +typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights); +typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights); +typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights); +typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights); +typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights); +typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWeightbvARB (GLint size, const GLbyte *weights); +GLAPI void APIENTRY glWeightsvARB (GLint size, const GLshort *weights); +GLAPI void APIENTRY glWeightivARB (GLint size, const GLint *weights); +GLAPI void APIENTRY glWeightfvARB (GLint size, const GLfloat *weights); +GLAPI void APIENTRY glWeightdvARB (GLint size, const GLdouble *weights); +GLAPI void APIENTRY glWeightubvARB (GLint size, const GLubyte *weights); +GLAPI void APIENTRY glWeightusvARB (GLint size, const GLushort *weights); +GLAPI void APIENTRY glWeightuivARB (GLint size, const GLuint *weights); +GLAPI void APIENTRY glWeightPointerARB (GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glVertexBlendARB (GLint count); +#endif +#endif /* GL_ARB_vertex_blend */ + +#ifndef GL_ARB_vertex_buffer_object +#define GL_ARB_vertex_buffer_object 1 +typedef khronos_ssize_t GLsizeiptrARB; +typedef khronos_intptr_t GLintptrARB; +#define GL_BUFFER_SIZE_ARB 0x8764 +#define GL_BUFFER_USAGE_ARB 0x8765 +#define GL_ARRAY_BUFFER_ARB 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893 +#define GL_ARRAY_BUFFER_BINDING_ARB 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895 +#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F +#define GL_READ_ONLY_ARB 0x88B8 +#define GL_WRITE_ONLY_ARB 0x88B9 +#define GL_READ_WRITE_ARB 0x88BA +#define GL_BUFFER_ACCESS_ARB 0x88BB +#define GL_BUFFER_MAPPED_ARB 0x88BC +#define GL_BUFFER_MAP_POINTER_ARB 0x88BD +#define GL_STREAM_DRAW_ARB 0x88E0 +#define GL_STREAM_READ_ARB 0x88E1 +#define GL_STREAM_COPY_ARB 0x88E2 +#define GL_STATIC_DRAW_ARB 0x88E4 +#define GL_STATIC_READ_ARB 0x88E5 +#define GL_STATIC_COPY_ARB 0x88E6 +#define GL_DYNAMIC_DRAW_ARB 0x88E8 +#define GL_DYNAMIC_READ_ARB 0x88E9 +#define GL_DYNAMIC_COPY_ARB 0x88EA +typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers); +typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data); +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data); +typedef void *(APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindBufferARB (GLenum target, GLuint buffer); +GLAPI void APIENTRY glDeleteBuffersARB (GLsizei n, const GLuint *buffers); +GLAPI void APIENTRY glGenBuffersARB (GLsizei n, GLuint *buffers); +GLAPI GLboolean APIENTRY glIsBufferARB (GLuint buffer); +GLAPI void APIENTRY glBufferDataARB (GLenum target, GLsizeiptrARB size, const void *data, GLenum usage); +GLAPI void APIENTRY glBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data); +GLAPI void APIENTRY glGetBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data); +GLAPI void *APIENTRY glMapBufferARB (GLenum target, GLenum access); +GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum target); +GLAPI void APIENTRY glGetBufferParameterivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetBufferPointervARB (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_ARB_vertex_buffer_object */ + +#ifndef GL_ARB_vertex_program +#define GL_ARB_vertex_program 1 +#define GL_COLOR_SUM_ARB 0x8458 +#define GL_VERTEX_PROGRAM_ARB 0x8620 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 +#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A +#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 +#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 +#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 +#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttrib1dARB (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1fARB (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1sARB (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2dARB (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2fARB (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2sARB (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3sARB (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4sARB (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribPointerARB (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint index); +GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint index); +GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribivARB (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint index, GLenum pname, void **pointer); +#endif +#endif /* GL_ARB_vertex_program */ + +#ifndef GL_ARB_vertex_shader +#define GL_ARB_vertex_shader 1 +#define GL_VERTEX_SHADER_ARB 0x8B31 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A +#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D +#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89 +#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name); +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB programObj, GLuint index, const GLcharARB *name); +GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB programObj, const GLcharARB *name); +#endif +#endif /* GL_ARB_vertex_shader */ + +#ifndef GL_ARB_vertex_type_10f_11f_11f_rev +#define GL_ARB_vertex_type_10f_11f_11f_rev 1 +#endif /* GL_ARB_vertex_type_10f_11f_11f_rev */ + +#ifndef GL_ARB_vertex_type_2_10_10_10_rev +#define GL_ARB_vertex_type_2_10_10_10_rev 1 +#endif /* GL_ARB_vertex_type_2_10_10_10_rev */ + +#ifndef GL_ARB_viewport_array +#define GL_ARB_viewport_array 1 +typedef void (APIENTRYP PFNGLDEPTHRANGEARRAYDVNVPROC) (GLuint first, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDDNVPROC) (GLuint index, GLdouble n, GLdouble f); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDepthRangeArraydvNV (GLuint first, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glDepthRangeIndexeddNV (GLuint index, GLdouble n, GLdouble f); +#endif +#endif /* GL_ARB_viewport_array */ + +#ifndef GL_ARB_window_pos +#define GL_ARB_window_pos 1 +typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowPos2dARB (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2fARB (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2iARB (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2ivARB (const GLint *v); +GLAPI void APIENTRY glWindowPos2sARB (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2svARB (const GLshort *v); +GLAPI void APIENTRY glWindowPos3dARB (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3fARB (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3iARB (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3ivARB (const GLint *v); +GLAPI void APIENTRY glWindowPos3sARB (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3svARB (const GLshort *v); +#endif +#endif /* GL_ARB_window_pos */ + +#ifndef GL_KHR_blend_equation_advanced +#define GL_KHR_blend_equation_advanced 1 +#define GL_MULTIPLY_KHR 0x9294 +#define GL_SCREEN_KHR 0x9295 +#define GL_OVERLAY_KHR 0x9296 +#define GL_DARKEN_KHR 0x9297 +#define GL_LIGHTEN_KHR 0x9298 +#define GL_COLORDODGE_KHR 0x9299 +#define GL_COLORBURN_KHR 0x929A +#define GL_HARDLIGHT_KHR 0x929B +#define GL_SOFTLIGHT_KHR 0x929C +#define GL_DIFFERENCE_KHR 0x929E +#define GL_EXCLUSION_KHR 0x92A0 +#define GL_HSL_HUE_KHR 0x92AD +#define GL_HSL_SATURATION_KHR 0x92AE +#define GL_HSL_COLOR_KHR 0x92AF +#define GL_HSL_LUMINOSITY_KHR 0x92B0 +typedef void (APIENTRYP PFNGLBLENDBARRIERKHRPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendBarrierKHR (void); +#endif +#endif /* GL_KHR_blend_equation_advanced */ + +#ifndef GL_KHR_blend_equation_advanced_coherent +#define GL_KHR_blend_equation_advanced_coherent 1 +#define GL_BLEND_ADVANCED_COHERENT_KHR 0x9285 +#endif /* GL_KHR_blend_equation_advanced_coherent */ + +#ifndef GL_KHR_context_flush_control +#define GL_KHR_context_flush_control 1 +#endif /* GL_KHR_context_flush_control */ + +#ifndef GL_KHR_debug +#define GL_KHR_debug 1 +#endif /* GL_KHR_debug */ + +#ifndef GL_KHR_no_error +#define GL_KHR_no_error 1 +#define GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR 0x00000008 +#endif /* GL_KHR_no_error */ + +#ifndef GL_KHR_parallel_shader_compile +#define GL_KHR_parallel_shader_compile 1 +#define GL_MAX_SHADER_COMPILER_THREADS_KHR 0x91B0 +#define GL_COMPLETION_STATUS_KHR 0x91B1 +typedef void (APIENTRYP PFNGLMAXSHADERCOMPILERTHREADSKHRPROC) (GLuint count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMaxShaderCompilerThreadsKHR (GLuint count); +#endif +#endif /* GL_KHR_parallel_shader_compile */ + +#ifndef GL_KHR_robust_buffer_access_behavior +#define GL_KHR_robust_buffer_access_behavior 1 +#endif /* GL_KHR_robust_buffer_access_behavior */ + +#ifndef GL_KHR_robustness +#define GL_KHR_robustness 1 +#define GL_CONTEXT_ROBUST_ACCESS 0x90F3 +#endif /* GL_KHR_robustness */ + +#ifndef GL_KHR_shader_subgroup +#define GL_KHR_shader_subgroup 1 +#define GL_SUBGROUP_SIZE_KHR 0x9532 +#define GL_SUBGROUP_SUPPORTED_STAGES_KHR 0x9533 +#define GL_SUBGROUP_SUPPORTED_FEATURES_KHR 0x9534 +#define GL_SUBGROUP_QUAD_ALL_STAGES_KHR 0x9535 +#define GL_SUBGROUP_FEATURE_BASIC_BIT_KHR 0x00000001 +#define GL_SUBGROUP_FEATURE_VOTE_BIT_KHR 0x00000002 +#define GL_SUBGROUP_FEATURE_ARITHMETIC_BIT_KHR 0x00000004 +#define GL_SUBGROUP_FEATURE_BALLOT_BIT_KHR 0x00000008 +#define GL_SUBGROUP_FEATURE_SHUFFLE_BIT_KHR 0x00000010 +#define GL_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT_KHR 0x00000020 +#define GL_SUBGROUP_FEATURE_CLUSTERED_BIT_KHR 0x00000040 +#define GL_SUBGROUP_FEATURE_QUAD_BIT_KHR 0x00000080 +#endif /* GL_KHR_shader_subgroup */ + +#ifndef GL_KHR_texture_compression_astc_hdr +#define GL_KHR_texture_compression_astc_hdr 1 +#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0 +#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1 +#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2 +#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3 +#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4 +#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5 +#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6 +#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7 +#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8 +#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9 +#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA +#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB +#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC +#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD +#endif /* GL_KHR_texture_compression_astc_hdr */ + +#ifndef GL_KHR_texture_compression_astc_ldr +#define GL_KHR_texture_compression_astc_ldr 1 +#endif /* GL_KHR_texture_compression_astc_ldr */ + +#ifndef GL_KHR_texture_compression_astc_sliced_3d +#define GL_KHR_texture_compression_astc_sliced_3d 1 +#endif /* GL_KHR_texture_compression_astc_sliced_3d */ + +#ifndef GL_OES_byte_coordinates +#define GL_OES_byte_coordinates 1 +typedef void (APIENTRYP PFNGLMULTITEXCOORD1BOESPROC) (GLenum texture, GLbyte s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2BOESPROC) (GLenum texture, GLbyte s, GLbyte t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3BOESPROC) (GLenum texture, GLbyte s, GLbyte t, GLbyte r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4BOESPROC) (GLenum texture, GLbyte s, GLbyte t, GLbyte r, GLbyte q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD1BOESPROC) (GLbyte s); +typedef void (APIENTRYP PFNGLTEXCOORD1BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD2BOESPROC) (GLbyte s, GLbyte t); +typedef void (APIENTRYP PFNGLTEXCOORD2BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD3BOESPROC) (GLbyte s, GLbyte t, GLbyte r); +typedef void (APIENTRYP PFNGLTEXCOORD3BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD4BOESPROC) (GLbyte s, GLbyte t, GLbyte r, GLbyte q); +typedef void (APIENTRYP PFNGLTEXCOORD4BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX2BOESPROC) (GLbyte x, GLbyte y); +typedef void (APIENTRYP PFNGLVERTEX2BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX3BOESPROC) (GLbyte x, GLbyte y, GLbyte z); +typedef void (APIENTRYP PFNGLVERTEX3BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX4BOESPROC) (GLbyte x, GLbyte y, GLbyte z, GLbyte w); +typedef void (APIENTRYP PFNGLVERTEX4BVOESPROC) (const GLbyte *coords); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiTexCoord1bOES (GLenum texture, GLbyte s); +GLAPI void APIENTRY glMultiTexCoord1bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord2bOES (GLenum texture, GLbyte s, GLbyte t); +GLAPI void APIENTRY glMultiTexCoord2bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord3bOES (GLenum texture, GLbyte s, GLbyte t, GLbyte r); +GLAPI void APIENTRY glMultiTexCoord3bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord4bOES (GLenum texture, GLbyte s, GLbyte t, GLbyte r, GLbyte q); +GLAPI void APIENTRY glMultiTexCoord4bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glTexCoord1bOES (GLbyte s); +GLAPI void APIENTRY glTexCoord1bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord2bOES (GLbyte s, GLbyte t); +GLAPI void APIENTRY glTexCoord2bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord3bOES (GLbyte s, GLbyte t, GLbyte r); +GLAPI void APIENTRY glTexCoord3bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord4bOES (GLbyte s, GLbyte t, GLbyte r, GLbyte q); +GLAPI void APIENTRY glTexCoord4bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex2bOES (GLbyte x, GLbyte y); +GLAPI void APIENTRY glVertex2bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex3bOES (GLbyte x, GLbyte y, GLbyte z); +GLAPI void APIENTRY glVertex3bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex4bOES (GLbyte x, GLbyte y, GLbyte z, GLbyte w); +GLAPI void APIENTRY glVertex4bvOES (const GLbyte *coords); +#endif +#endif /* GL_OES_byte_coordinates */ + +#ifndef GL_OES_compressed_paletted_texture +#define GL_OES_compressed_paletted_texture 1 +#define GL_PALETTE4_RGB8_OES 0x8B90 +#define GL_PALETTE4_RGBA8_OES 0x8B91 +#define GL_PALETTE4_R5_G6_B5_OES 0x8B92 +#define GL_PALETTE4_RGBA4_OES 0x8B93 +#define GL_PALETTE4_RGB5_A1_OES 0x8B94 +#define GL_PALETTE8_RGB8_OES 0x8B95 +#define GL_PALETTE8_RGBA8_OES 0x8B96 +#define GL_PALETTE8_R5_G6_B5_OES 0x8B97 +#define GL_PALETTE8_RGBA4_OES 0x8B98 +#define GL_PALETTE8_RGB5_A1_OES 0x8B99 +#endif /* GL_OES_compressed_paletted_texture */ + +#ifndef GL_OES_fixed_point +#define GL_OES_fixed_point 1 +typedef khronos_int32_t GLfixed; +#define GL_FIXED_OES 0x140C +typedef void (APIENTRYP PFNGLALPHAFUNCXOESPROC) (GLenum func, GLfixed ref); +typedef void (APIENTRYP PFNGLCLEARCOLORXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCLEARDEPTHXOESPROC) (GLfixed depth); +typedef void (APIENTRYP PFNGLCLIPPLANEXOESPROC) (GLenum plane, const GLfixed *equation); +typedef void (APIENTRYP PFNGLCOLOR4XOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLDEPTHRANGEXOESPROC) (GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLFOGXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLFOGXVOESPROC) (GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLFRUSTUMXOESPROC) (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLGETCLIPPLANEXOESPROC) (GLenum plane, GLfixed *equation); +typedef void (APIENTRYP PFNGLGETFIXEDVOESPROC) (GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXENVXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLLIGHTMODELXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLLIGHTMODELXVOESPROC) (GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLLIGHTXVOESPROC) (GLenum light, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLLINEWIDTHXOESPROC) (GLfixed width); +typedef void (APIENTRYP PFNGLLOADMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLMATERIALXVOESPROC) (GLenum face, GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLMULTMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4XOESPROC) (GLenum texture, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +typedef void (APIENTRYP PFNGLNORMAL3XOESPROC) (GLfixed nx, GLfixed ny, GLfixed nz); +typedef void (APIENTRYP PFNGLORTHOXOESPROC) (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLPOINTPARAMETERXVOESPROC) (GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLPOINTSIZEXOESPROC) (GLfixed size); +typedef void (APIENTRYP PFNGLPOLYGONOFFSETXOESPROC) (GLfixed factor, GLfixed units); +typedef void (APIENTRYP PFNGLROTATEXOESPROC) (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLSCALEXOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLTEXENVXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXENVXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLTRANSLATEXOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLACCUMXOESPROC) (GLenum op, GLfixed value); +typedef void (APIENTRYP PFNGLBITMAPXOESPROC) (GLsizei width, GLsizei height, GLfixed xorig, GLfixed yorig, GLfixed xmove, GLfixed ymove, const GLubyte *bitmap); +typedef void (APIENTRYP PFNGLBLENDCOLORXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCLEARACCUMXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCOLOR3XOESPROC) (GLfixed red, GLfixed green, GLfixed blue); +typedef void (APIENTRYP PFNGLCOLOR3XVOESPROC) (const GLfixed *components); +typedef void (APIENTRYP PFNGLCOLOR4XVOESPROC) (const GLfixed *components); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLEVALCOORD1XOESPROC) (GLfixed u); +typedef void (APIENTRYP PFNGLEVALCOORD1XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLEVALCOORD2XOESPROC) (GLfixed u, GLfixed v); +typedef void (APIENTRYP PFNGLEVALCOORD2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLFEEDBACKBUFFERXOESPROC) (GLsizei n, GLenum type, const GLfixed *buffer); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETMAPXVOESPROC) (GLenum target, GLenum query, GLfixed *v); +typedef void (APIENTRYP PFNGLGETMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLGETPIXELMAPXVPROC) (GLenum map, GLint size, GLfixed *values); +typedef void (APIENTRYP PFNGLGETTEXGENXVOESPROC) (GLenum coord, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERXVOESPROC) (GLenum target, GLint level, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLINDEXXOESPROC) (GLfixed component); +typedef void (APIENTRYP PFNGLINDEXXVOESPROC) (const GLfixed *component); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMAP1XOESPROC) (GLenum target, GLfixed u1, GLfixed u2, GLint stride, GLint order, GLfixed points); +typedef void (APIENTRYP PFNGLMAP2XOESPROC) (GLenum target, GLfixed u1, GLfixed u2, GLint ustride, GLint uorder, GLfixed v1, GLfixed v2, GLint vstride, GLint vorder, GLfixed points); +typedef void (APIENTRYP PFNGLMAPGRID1XOESPROC) (GLint n, GLfixed u1, GLfixed u2); +typedef void (APIENTRYP PFNGLMAPGRID2XOESPROC) (GLint n, GLfixed u1, GLfixed u2, GLfixed v1, GLfixed v2); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1XOESPROC) (GLenum texture, GLfixed s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2XOESPROC) (GLenum texture, GLfixed s, GLfixed t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3XOESPROC) (GLenum texture, GLfixed s, GLfixed t, GLfixed r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLNORMAL3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLPASSTHROUGHXOESPROC) (GLfixed token); +typedef void (APIENTRYP PFNGLPIXELMAPXPROC) (GLenum map, GLint size, const GLfixed *values); +typedef void (APIENTRYP PFNGLPIXELSTOREXPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLPIXELTRANSFERXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLPIXELZOOMXOESPROC) (GLfixed xfactor, GLfixed yfactor); +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESXOESPROC) (GLsizei n, const GLuint *textures, const GLfixed *priorities); +typedef void (APIENTRYP PFNGLRASTERPOS2XOESPROC) (GLfixed x, GLfixed y); +typedef void (APIENTRYP PFNGLRASTERPOS2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRASTERPOS3XOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLRASTERPOS3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRASTERPOS4XOESPROC) (GLfixed x, GLfixed y, GLfixed z, GLfixed w); +typedef void (APIENTRYP PFNGLRASTERPOS4XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRECTXOESPROC) (GLfixed x1, GLfixed y1, GLfixed x2, GLfixed y2); +typedef void (APIENTRYP PFNGLRECTXVOESPROC) (const GLfixed *v1, const GLfixed *v2); +typedef void (APIENTRYP PFNGLTEXCOORD1XOESPROC) (GLfixed s); +typedef void (APIENTRYP PFNGLTEXCOORD1XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD2XOESPROC) (GLfixed s, GLfixed t); +typedef void (APIENTRYP PFNGLTEXCOORD2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD3XOESPROC) (GLfixed s, GLfixed t, GLfixed r); +typedef void (APIENTRYP PFNGLTEXCOORD3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD4XOESPROC) (GLfixed s, GLfixed t, GLfixed r, GLfixed q); +typedef void (APIENTRYP PFNGLTEXCOORD4XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXGENXOESPROC) (GLenum coord, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXGENXVOESPROC) (GLenum coord, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLVERTEX2XOESPROC) (GLfixed x); +typedef void (APIENTRYP PFNGLVERTEX2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLVERTEX3XOESPROC) (GLfixed x, GLfixed y); +typedef void (APIENTRYP PFNGLVERTEX3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLVERTEX4XOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLVERTEX4XVOESPROC) (const GLfixed *coords); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAlphaFuncxOES (GLenum func, GLfixed ref); +GLAPI void APIENTRY glClearColorxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glClearDepthxOES (GLfixed depth); +GLAPI void APIENTRY glClipPlanexOES (GLenum plane, const GLfixed *equation); +GLAPI void APIENTRY glColor4xOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glDepthRangexOES (GLfixed n, GLfixed f); +GLAPI void APIENTRY glFogxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glFogxvOES (GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glFrustumxOES (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +GLAPI void APIENTRY glGetClipPlanexOES (GLenum plane, GLfixed *equation); +GLAPI void APIENTRY glGetFixedvOES (GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexEnvxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glLightModelxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glLightModelxvOES (GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glLightxOES (GLenum light, GLenum pname, GLfixed param); +GLAPI void APIENTRY glLightxvOES (GLenum light, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glLineWidthxOES (GLfixed width); +GLAPI void APIENTRY glLoadMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMaterialxOES (GLenum face, GLenum pname, GLfixed param); +GLAPI void APIENTRY glMaterialxvOES (GLenum face, GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glMultMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMultiTexCoord4xOES (GLenum texture, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +GLAPI void APIENTRY glNormal3xOES (GLfixed nx, GLfixed ny, GLfixed nz); +GLAPI void APIENTRY glOrthoxOES (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +GLAPI void APIENTRY glPointParameterxvOES (GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glPointSizexOES (GLfixed size); +GLAPI void APIENTRY glPolygonOffsetxOES (GLfixed factor, GLfixed units); +GLAPI void APIENTRY glRotatexOES (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glScalexOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glTexEnvxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexEnvxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glTexParameterxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexParameterxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glTranslatexOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glAccumxOES (GLenum op, GLfixed value); +GLAPI void APIENTRY glBitmapxOES (GLsizei width, GLsizei height, GLfixed xorig, GLfixed yorig, GLfixed xmove, GLfixed ymove, const GLubyte *bitmap); +GLAPI void APIENTRY glBlendColorxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glClearAccumxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glColor3xOES (GLfixed red, GLfixed green, GLfixed blue); +GLAPI void APIENTRY glColor3xvOES (const GLfixed *components); +GLAPI void APIENTRY glColor4xvOES (const GLfixed *components); +GLAPI void APIENTRY glConvolutionParameterxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glConvolutionParameterxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glEvalCoord1xOES (GLfixed u); +GLAPI void APIENTRY glEvalCoord1xvOES (const GLfixed *coords); +GLAPI void APIENTRY glEvalCoord2xOES (GLfixed u, GLfixed v); +GLAPI void APIENTRY glEvalCoord2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glFeedbackBufferxOES (GLsizei n, GLenum type, const GLfixed *buffer); +GLAPI void APIENTRY glGetConvolutionParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetHistogramParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetLightxOES (GLenum light, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetMapxvOES (GLenum target, GLenum query, GLfixed *v); +GLAPI void APIENTRY glGetMaterialxOES (GLenum face, GLenum pname, GLfixed param); +GLAPI void APIENTRY glGetPixelMapxv (GLenum map, GLint size, GLfixed *values); +GLAPI void APIENTRY glGetTexGenxvOES (GLenum coord, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexLevelParameterxvOES (GLenum target, GLint level, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glIndexxOES (GLfixed component); +GLAPI void APIENTRY glIndexxvOES (const GLfixed *component); +GLAPI void APIENTRY glLoadTransposeMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMap1xOES (GLenum target, GLfixed u1, GLfixed u2, GLint stride, GLint order, GLfixed points); +GLAPI void APIENTRY glMap2xOES (GLenum target, GLfixed u1, GLfixed u2, GLint ustride, GLint uorder, GLfixed v1, GLfixed v2, GLint vstride, GLint vorder, GLfixed points); +GLAPI void APIENTRY glMapGrid1xOES (GLint n, GLfixed u1, GLfixed u2); +GLAPI void APIENTRY glMapGrid2xOES (GLint n, GLfixed u1, GLfixed u2, GLfixed v1, GLfixed v2); +GLAPI void APIENTRY glMultTransposeMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMultiTexCoord1xOES (GLenum texture, GLfixed s); +GLAPI void APIENTRY glMultiTexCoord1xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord2xOES (GLenum texture, GLfixed s, GLfixed t); +GLAPI void APIENTRY glMultiTexCoord2xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord3xOES (GLenum texture, GLfixed s, GLfixed t, GLfixed r); +GLAPI void APIENTRY glMultiTexCoord3xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord4xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glNormal3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glPassThroughxOES (GLfixed token); +GLAPI void APIENTRY glPixelMapx (GLenum map, GLint size, const GLfixed *values); +GLAPI void APIENTRY glPixelStorex (GLenum pname, GLfixed param); +GLAPI void APIENTRY glPixelTransferxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glPixelZoomxOES (GLfixed xfactor, GLfixed yfactor); +GLAPI void APIENTRY glPrioritizeTexturesxOES (GLsizei n, const GLuint *textures, const GLfixed *priorities); +GLAPI void APIENTRY glRasterPos2xOES (GLfixed x, GLfixed y); +GLAPI void APIENTRY glRasterPos2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRasterPos3xOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glRasterPos3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRasterPos4xOES (GLfixed x, GLfixed y, GLfixed z, GLfixed w); +GLAPI void APIENTRY glRasterPos4xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRectxOES (GLfixed x1, GLfixed y1, GLfixed x2, GLfixed y2); +GLAPI void APIENTRY glRectxvOES (const GLfixed *v1, const GLfixed *v2); +GLAPI void APIENTRY glTexCoord1xOES (GLfixed s); +GLAPI void APIENTRY glTexCoord1xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord2xOES (GLfixed s, GLfixed t); +GLAPI void APIENTRY glTexCoord2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord3xOES (GLfixed s, GLfixed t, GLfixed r); +GLAPI void APIENTRY glTexCoord3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord4xOES (GLfixed s, GLfixed t, GLfixed r, GLfixed q); +GLAPI void APIENTRY glTexCoord4xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexGenxOES (GLenum coord, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexGenxvOES (GLenum coord, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glVertex2xOES (GLfixed x); +GLAPI void APIENTRY glVertex2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glVertex3xOES (GLfixed x, GLfixed y); +GLAPI void APIENTRY glVertex3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glVertex4xOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glVertex4xvOES (const GLfixed *coords); +#endif +#endif /* GL_OES_fixed_point */ + +#ifndef GL_OES_query_matrix +#define GL_OES_query_matrix 1 +typedef GLbitfield (APIENTRYP PFNGLQUERYMATRIXXOESPROC) (GLfixed *mantissa, GLint *exponent); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLbitfield APIENTRY glQueryMatrixxOES (GLfixed *mantissa, GLint *exponent); +#endif +#endif /* GL_OES_query_matrix */ + +#ifndef GL_OES_read_format +#define GL_OES_read_format 1 +#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B +#endif /* GL_OES_read_format */ + +#ifndef GL_OES_single_precision +#define GL_OES_single_precision 1 +typedef void (APIENTRYP PFNGLCLEARDEPTHFOESPROC) (GLclampf depth); +typedef void (APIENTRYP PFNGLCLIPPLANEFOESPROC) (GLenum plane, const GLfloat *equation); +typedef void (APIENTRYP PFNGLDEPTHRANGEFOESPROC) (GLclampf n, GLclampf f); +typedef void (APIENTRYP PFNGLFRUSTUMFOESPROC) (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +typedef void (APIENTRYP PFNGLGETCLIPPLANEFOESPROC) (GLenum plane, GLfloat *equation); +typedef void (APIENTRYP PFNGLORTHOFOESPROC) (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClearDepthfOES (GLclampf depth); +GLAPI void APIENTRY glClipPlanefOES (GLenum plane, const GLfloat *equation); +GLAPI void APIENTRY glDepthRangefOES (GLclampf n, GLclampf f); +GLAPI void APIENTRY glFrustumfOES (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +GLAPI void APIENTRY glGetClipPlanefOES (GLenum plane, GLfloat *equation); +GLAPI void APIENTRY glOrthofOES (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +#endif +#endif /* GL_OES_single_precision */ + +#ifndef GL_3DFX_multisample +#define GL_3DFX_multisample 1 +#define GL_MULTISAMPLE_3DFX 0x86B2 +#define GL_SAMPLE_BUFFERS_3DFX 0x86B3 +#define GL_SAMPLES_3DFX 0x86B4 +#define GL_MULTISAMPLE_BIT_3DFX 0x20000000 +#endif /* GL_3DFX_multisample */ + +#ifndef GL_3DFX_tbuffer +#define GL_3DFX_tbuffer 1 +typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTbufferMask3DFX (GLuint mask); +#endif +#endif /* GL_3DFX_tbuffer */ + +#ifndef GL_3DFX_texture_compression_FXT1 +#define GL_3DFX_texture_compression_FXT1 1 +#define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0 +#define GL_COMPRESSED_RGBA_FXT1_3DFX 0x86B1 +#endif /* GL_3DFX_texture_compression_FXT1 */ + +#ifndef GL_AMD_blend_minmax_factor +#define GL_AMD_blend_minmax_factor 1 +#define GL_FACTOR_MIN_AMD 0x901C +#define GL_FACTOR_MAX_AMD 0x901D +#endif /* GL_AMD_blend_minmax_factor */ + +#ifndef GL_AMD_conservative_depth +#define GL_AMD_conservative_depth 1 +#endif /* GL_AMD_conservative_depth */ + +#ifndef GL_AMD_debug_output +#define GL_AMD_debug_output 1 +typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); +#define GL_MAX_DEBUG_MESSAGE_LENGTH_AMD 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES_AMD 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES_AMD 0x9145 +#define GL_DEBUG_SEVERITY_HIGH_AMD 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM_AMD 0x9147 +#define GL_DEBUG_SEVERITY_LOW_AMD 0x9148 +#define GL_DEBUG_CATEGORY_API_ERROR_AMD 0x9149 +#define GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD 0x914A +#define GL_DEBUG_CATEGORY_DEPRECATION_AMD 0x914B +#define GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD 0x914C +#define GL_DEBUG_CATEGORY_PERFORMANCE_AMD 0x914D +#define GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD 0x914E +#define GL_DEBUG_CATEGORY_APPLICATION_AMD 0x914F +#define GL_DEBUG_CATEGORY_OTHER_AMD 0x9150 +typedef void (APIENTRYP PFNGLDEBUGMESSAGEENABLEAMDPROC) (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTAMDPROC) (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKAMDPROC) (GLDEBUGPROCAMD callback, void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGAMDPROC) (GLuint count, GLsizei bufSize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDebugMessageEnableAMD (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsertAMD (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallbackAMD (GLDEBUGPROCAMD callback, void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLogAMD (GLuint count, GLsizei bufSize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message); +#endif +#endif /* GL_AMD_debug_output */ + +#ifndef GL_AMD_depth_clamp_separate +#define GL_AMD_depth_clamp_separate 1 +#define GL_DEPTH_CLAMP_NEAR_AMD 0x901E +#define GL_DEPTH_CLAMP_FAR_AMD 0x901F +#endif /* GL_AMD_depth_clamp_separate */ + +#ifndef GL_AMD_draw_buffers_blend +#define GL_AMD_draw_buffers_blend 1 +typedef void (APIENTRYP PFNGLBLENDFUNCINDEXEDAMDPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +typedef void (APIENTRYP PFNGLBLENDEQUATIONINDEXEDAMDPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncIndexedAMD (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparateIndexedAMD (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GLAPI void APIENTRY glBlendEquationIndexedAMD (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparateIndexedAMD (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +#endif +#endif /* GL_AMD_draw_buffers_blend */ + +#ifndef GL_AMD_framebuffer_multisample_advanced +#define GL_AMD_framebuffer_multisample_advanced 1 +#define GL_RENDERBUFFER_STORAGE_SAMPLES_AMD 0x91B2 +#define GL_MAX_COLOR_FRAMEBUFFER_SAMPLES_AMD 0x91B3 +#define GL_MAX_COLOR_FRAMEBUFFER_STORAGE_SAMPLES_AMD 0x91B4 +#define GL_MAX_DEPTH_STENCIL_FRAMEBUFFER_SAMPLES_AMD 0x91B5 +#define GL_NUM_SUPPORTED_MULTISAMPLE_MODES_AMD 0x91B6 +#define GL_SUPPORTED_MULTISAMPLE_MODES_AMD 0x91B7 +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC) (GLenum target, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC) (GLuint renderbuffer, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderbufferStorageMultisampleAdvancedAMD (GLenum target, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleAdvancedAMD (GLuint renderbuffer, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_AMD_framebuffer_multisample_advanced */ + +#ifndef GL_AMD_framebuffer_sample_positions +#define GL_AMD_framebuffer_sample_positions 1 +#define GL_SUBSAMPLE_DISTANCE_AMD 0x883F +#define GL_PIXELS_PER_SAMPLE_PATTERN_X_AMD 0x91AE +#define GL_PIXELS_PER_SAMPLE_PATTERN_Y_AMD 0x91AF +#define GL_ALL_PIXELS_AMD 0xFFFFFFFF +typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLEPOSITIONSFVAMDPROC) (GLenum target, GLuint numsamples, GLuint pixelindex, const GLfloat *values); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLEPOSITIONSFVAMDPROC) (GLuint framebuffer, GLuint numsamples, GLuint pixelindex, const GLfloat *values); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERFVAMDPROC) (GLenum target, GLenum pname, GLuint numsamples, GLuint pixelindex, GLsizei size, GLfloat *values); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERFVAMDPROC) (GLuint framebuffer, GLenum pname, GLuint numsamples, GLuint pixelindex, GLsizei size, GLfloat *values); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferSamplePositionsfvAMD (GLenum target, GLuint numsamples, GLuint pixelindex, const GLfloat *values); +GLAPI void APIENTRY glNamedFramebufferSamplePositionsfvAMD (GLuint framebuffer, GLuint numsamples, GLuint pixelindex, const GLfloat *values); +GLAPI void APIENTRY glGetFramebufferParameterfvAMD (GLenum target, GLenum pname, GLuint numsamples, GLuint pixelindex, GLsizei size, GLfloat *values); +GLAPI void APIENTRY glGetNamedFramebufferParameterfvAMD (GLuint framebuffer, GLenum pname, GLuint numsamples, GLuint pixelindex, GLsizei size, GLfloat *values); +#endif +#endif /* GL_AMD_framebuffer_sample_positions */ + +#ifndef GL_AMD_gcn_shader +#define GL_AMD_gcn_shader 1 +#endif /* GL_AMD_gcn_shader */ + +#ifndef GL_AMD_gpu_shader_half_float +#define GL_AMD_gpu_shader_half_float 1 +#define GL_FLOAT16_NV 0x8FF8 +#define GL_FLOAT16_VEC2_NV 0x8FF9 +#define GL_FLOAT16_VEC3_NV 0x8FFA +#define GL_FLOAT16_VEC4_NV 0x8FFB +#define GL_FLOAT16_MAT2_AMD 0x91C5 +#define GL_FLOAT16_MAT3_AMD 0x91C6 +#define GL_FLOAT16_MAT4_AMD 0x91C7 +#define GL_FLOAT16_MAT2x3_AMD 0x91C8 +#define GL_FLOAT16_MAT2x4_AMD 0x91C9 +#define GL_FLOAT16_MAT3x2_AMD 0x91CA +#define GL_FLOAT16_MAT3x4_AMD 0x91CB +#define GL_FLOAT16_MAT4x2_AMD 0x91CC +#define GL_FLOAT16_MAT4x3_AMD 0x91CD +#endif /* GL_AMD_gpu_shader_half_float */ + +#ifndef GL_AMD_gpu_shader_int16 +#define GL_AMD_gpu_shader_int16 1 +#endif /* GL_AMD_gpu_shader_int16 */ + +#ifndef GL_AMD_gpu_shader_int64 +#define GL_AMD_gpu_shader_int64 1 +typedef khronos_int64_t GLint64EXT; +#define GL_INT64_NV 0x140E +#define GL_UNSIGNED_INT64_NV 0x140F +#define GL_INT8_NV 0x8FE0 +#define GL_INT8_VEC2_NV 0x8FE1 +#define GL_INT8_VEC3_NV 0x8FE2 +#define GL_INT8_VEC4_NV 0x8FE3 +#define GL_INT16_NV 0x8FE4 +#define GL_INT16_VEC2_NV 0x8FE5 +#define GL_INT16_VEC3_NV 0x8FE6 +#define GL_INT16_VEC4_NV 0x8FE7 +#define GL_INT64_VEC2_NV 0x8FE9 +#define GL_INT64_VEC3_NV 0x8FEA +#define GL_INT64_VEC4_NV 0x8FEB +#define GL_UNSIGNED_INT8_NV 0x8FEC +#define GL_UNSIGNED_INT8_VEC2_NV 0x8FED +#define GL_UNSIGNED_INT8_VEC3_NV 0x8FEE +#define GL_UNSIGNED_INT8_VEC4_NV 0x8FEF +#define GL_UNSIGNED_INT16_NV 0x8FF0 +#define GL_UNSIGNED_INT16_VEC2_NV 0x8FF1 +#define GL_UNSIGNED_INT16_VEC3_NV 0x8FF2 +#define GL_UNSIGNED_INT16_VEC4_NV 0x8FF3 +#define GL_UNSIGNED_INT64_VEC2_NV 0x8FF5 +#define GL_UNSIGNED_INT64_VEC3_NV 0x8FF6 +#define GL_UNSIGNED_INT64_VEC4_NV 0x8FF7 +typedef void (APIENTRYP PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x); +typedef void (APIENTRYP PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x); +typedef void (APIENTRYP PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniform1i64NV (GLint location, GLint64EXT x); +GLAPI void APIENTRY glUniform2i64NV (GLint location, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glUniform3i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glUniform4i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glUniform1i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform2i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform3i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform4i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform1ui64NV (GLint location, GLuint64EXT x); +GLAPI void APIENTRY glUniform2ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glUniform3ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glUniform4ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glUniform1ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform2ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform3ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform4ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glGetUniformi64vNV (GLuint program, GLint location, GLint64EXT *params); +GLAPI void APIENTRY glGetUniformui64vNV (GLuint program, GLint location, GLuint64EXT *params); +GLAPI void APIENTRY glProgramUniform1i64NV (GLuint program, GLint location, GLint64EXT x); +GLAPI void APIENTRY glProgramUniform2i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glProgramUniform3i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glProgramUniform4i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glProgramUniform1i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform2i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform3i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform4i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform1ui64NV (GLuint program, GLint location, GLuint64EXT x); +GLAPI void APIENTRY glProgramUniform2ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glProgramUniform3ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glProgramUniform4ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glProgramUniform1ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform2ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform3ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform4ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif +#endif /* GL_AMD_gpu_shader_int64 */ + +#ifndef GL_AMD_interleaved_elements +#define GL_AMD_interleaved_elements 1 +#define GL_VERTEX_ELEMENT_SWIZZLE_AMD 0x91A4 +#define GL_VERTEX_ID_SWIZZLE_AMD 0x91A5 +typedef void (APIENTRYP PFNGLVERTEXATTRIBPARAMETERIAMDPROC) (GLuint index, GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribParameteriAMD (GLuint index, GLenum pname, GLint param); +#endif +#endif /* GL_AMD_interleaved_elements */ + +#ifndef GL_AMD_multi_draw_indirect +#define GL_AMD_multi_draw_indirect 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTAMDPROC) (GLenum mode, const void *indirect, GLsizei primcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTAMDPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei primcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectAMD (GLenum mode, const void *indirect, GLsizei primcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirectAMD (GLenum mode, GLenum type, const void *indirect, GLsizei primcount, GLsizei stride); +#endif +#endif /* GL_AMD_multi_draw_indirect */ + +#ifndef GL_AMD_name_gen_delete +#define GL_AMD_name_gen_delete 1 +#define GL_DATA_BUFFER_AMD 0x9151 +#define GL_PERFORMANCE_MONITOR_AMD 0x9152 +#define GL_QUERY_OBJECT_AMD 0x9153 +#define GL_VERTEX_ARRAY_OBJECT_AMD 0x9154 +#define GL_SAMPLER_OBJECT_AMD 0x9155 +typedef void (APIENTRYP PFNGLGENNAMESAMDPROC) (GLenum identifier, GLuint num, GLuint *names); +typedef void (APIENTRYP PFNGLDELETENAMESAMDPROC) (GLenum identifier, GLuint num, const GLuint *names); +typedef GLboolean (APIENTRYP PFNGLISNAMEAMDPROC) (GLenum identifier, GLuint name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenNamesAMD (GLenum identifier, GLuint num, GLuint *names); +GLAPI void APIENTRY glDeleteNamesAMD (GLenum identifier, GLuint num, const GLuint *names); +GLAPI GLboolean APIENTRY glIsNameAMD (GLenum identifier, GLuint name); +#endif +#endif /* GL_AMD_name_gen_delete */ + +#ifndef GL_AMD_occlusion_query_event +#define GL_AMD_occlusion_query_event 1 +#define GL_OCCLUSION_QUERY_EVENT_MASK_AMD 0x874F +#define GL_QUERY_DEPTH_PASS_EVENT_BIT_AMD 0x00000001 +#define GL_QUERY_DEPTH_FAIL_EVENT_BIT_AMD 0x00000002 +#define GL_QUERY_STENCIL_FAIL_EVENT_BIT_AMD 0x00000004 +#define GL_QUERY_DEPTH_BOUNDS_FAIL_EVENT_BIT_AMD 0x00000008 +#define GL_QUERY_ALL_EVENT_BITS_AMD 0xFFFFFFFF +typedef void (APIENTRYP PFNGLQUERYOBJECTPARAMETERUIAMDPROC) (GLenum target, GLuint id, GLenum pname, GLuint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glQueryObjectParameteruiAMD (GLenum target, GLuint id, GLenum pname, GLuint param); +#endif +#endif /* GL_AMD_occlusion_query_event */ + +#ifndef GL_AMD_performance_monitor +#define GL_AMD_performance_monitor 1 +#define GL_COUNTER_TYPE_AMD 0x8BC0 +#define GL_COUNTER_RANGE_AMD 0x8BC1 +#define GL_UNSIGNED_INT64_AMD 0x8BC2 +#define GL_PERCENTAGE_AMD 0x8BC3 +#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4 +#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5 +#define GL_PERFMON_RESULT_AMD 0x8BC6 +typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); +typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data); +typedef void (APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); +typedef void (APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); +typedef void (APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); +typedef void (APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor); +typedef void (APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups); +GLAPI void APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); +GLAPI void APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); +GLAPI void APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); +GLAPI void APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data); +GLAPI void APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors); +GLAPI void APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors); +GLAPI void APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); +GLAPI void APIENTRY glBeginPerfMonitorAMD (GLuint monitor); +GLAPI void APIENTRY glEndPerfMonitorAMD (GLuint monitor); +GLAPI void APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); +#endif +#endif /* GL_AMD_performance_monitor */ + +#ifndef GL_AMD_pinned_memory +#define GL_AMD_pinned_memory 1 +#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160 +#endif /* GL_AMD_pinned_memory */ + +#ifndef GL_AMD_query_buffer_object +#define GL_AMD_query_buffer_object 1 +#define GL_QUERY_BUFFER_AMD 0x9192 +#define GL_QUERY_BUFFER_BINDING_AMD 0x9193 +#define GL_QUERY_RESULT_NO_WAIT_AMD 0x9194 +#endif /* GL_AMD_query_buffer_object */ + +#ifndef GL_AMD_sample_positions +#define GL_AMD_sample_positions 1 +typedef void (APIENTRYP PFNGLSETMULTISAMPLEFVAMDPROC) (GLenum pname, GLuint index, const GLfloat *val); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSetMultisamplefvAMD (GLenum pname, GLuint index, const GLfloat *val); +#endif +#endif /* GL_AMD_sample_positions */ + +#ifndef GL_AMD_seamless_cubemap_per_texture +#define GL_AMD_seamless_cubemap_per_texture 1 +#endif /* GL_AMD_seamless_cubemap_per_texture */ + +#ifndef GL_AMD_shader_atomic_counter_ops +#define GL_AMD_shader_atomic_counter_ops 1 +#endif /* GL_AMD_shader_atomic_counter_ops */ + +#ifndef GL_AMD_shader_ballot +#define GL_AMD_shader_ballot 1 +#endif /* GL_AMD_shader_ballot */ + +#ifndef GL_AMD_shader_explicit_vertex_parameter +#define GL_AMD_shader_explicit_vertex_parameter 1 +#endif /* GL_AMD_shader_explicit_vertex_parameter */ + +#ifndef GL_AMD_shader_gpu_shader_half_float_fetch +#define GL_AMD_shader_gpu_shader_half_float_fetch 1 +#endif /* GL_AMD_shader_gpu_shader_half_float_fetch */ + +#ifndef GL_AMD_shader_image_load_store_lod +#define GL_AMD_shader_image_load_store_lod 1 +#endif /* GL_AMD_shader_image_load_store_lod */ + +#ifndef GL_AMD_shader_stencil_export +#define GL_AMD_shader_stencil_export 1 +#endif /* GL_AMD_shader_stencil_export */ + +#ifndef GL_AMD_shader_trinary_minmax +#define GL_AMD_shader_trinary_minmax 1 +#endif /* GL_AMD_shader_trinary_minmax */ + +#ifndef GL_AMD_sparse_texture +#define GL_AMD_sparse_texture 1 +#define GL_VIRTUAL_PAGE_SIZE_X_AMD 0x9195 +#define GL_VIRTUAL_PAGE_SIZE_Y_AMD 0x9196 +#define GL_VIRTUAL_PAGE_SIZE_Z_AMD 0x9197 +#define GL_MAX_SPARSE_TEXTURE_SIZE_AMD 0x9198 +#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_AMD 0x9199 +#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS 0x919A +#define GL_MIN_SPARSE_LEVEL_AMD 0x919B +#define GL_MIN_LOD_WARNING_AMD 0x919C +#define GL_TEXTURE_STORAGE_SPARSE_BIT_AMD 0x00000001 +typedef void (APIENTRYP PFNGLTEXSTORAGESPARSEAMDPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +typedef void (APIENTRYP PFNGLTEXTURESTORAGESPARSEAMDPROC) (GLuint texture, GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexStorageSparseAMD (GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +GLAPI void APIENTRY glTextureStorageSparseAMD (GLuint texture, GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +#endif +#endif /* GL_AMD_sparse_texture */ + +#ifndef GL_AMD_stencil_operation_extended +#define GL_AMD_stencil_operation_extended 1 +#define GL_SET_AMD 0x874A +#define GL_REPLACE_VALUE_AMD 0x874B +#define GL_STENCIL_OP_VALUE_AMD 0x874C +#define GL_STENCIL_BACK_OP_VALUE_AMD 0x874D +typedef void (APIENTRYP PFNGLSTENCILOPVALUEAMDPROC) (GLenum face, GLuint value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilOpValueAMD (GLenum face, GLuint value); +#endif +#endif /* GL_AMD_stencil_operation_extended */ + +#ifndef GL_AMD_texture_gather_bias_lod +#define GL_AMD_texture_gather_bias_lod 1 +#endif /* GL_AMD_texture_gather_bias_lod */ + +#ifndef GL_AMD_texture_texture4 +#define GL_AMD_texture_texture4 1 +#endif /* GL_AMD_texture_texture4 */ + +#ifndef GL_AMD_transform_feedback3_lines_triangles +#define GL_AMD_transform_feedback3_lines_triangles 1 +#endif /* GL_AMD_transform_feedback3_lines_triangles */ + +#ifndef GL_AMD_transform_feedback4 +#define GL_AMD_transform_feedback4 1 +#define GL_STREAM_RASTERIZATION_AMD 0x91A0 +#endif /* GL_AMD_transform_feedback4 */ + +#ifndef GL_AMD_vertex_shader_layer +#define GL_AMD_vertex_shader_layer 1 +#endif /* GL_AMD_vertex_shader_layer */ + +#ifndef GL_AMD_vertex_shader_tessellator +#define GL_AMD_vertex_shader_tessellator 1 +#define GL_SAMPLER_BUFFER_AMD 0x9001 +#define GL_INT_SAMPLER_BUFFER_AMD 0x9002 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_AMD 0x9003 +#define GL_TESSELLATION_MODE_AMD 0x9004 +#define GL_TESSELLATION_FACTOR_AMD 0x9005 +#define GL_DISCRETE_AMD 0x9006 +#define GL_CONTINUOUS_AMD 0x9007 +typedef void (APIENTRYP PFNGLTESSELLATIONFACTORAMDPROC) (GLfloat factor); +typedef void (APIENTRYP PFNGLTESSELLATIONMODEAMDPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTessellationFactorAMD (GLfloat factor); +GLAPI void APIENTRY glTessellationModeAMD (GLenum mode); +#endif +#endif /* GL_AMD_vertex_shader_tessellator */ + +#ifndef GL_AMD_vertex_shader_viewport_index +#define GL_AMD_vertex_shader_viewport_index 1 +#endif /* GL_AMD_vertex_shader_viewport_index */ + +#ifndef GL_APPLE_aux_depth_stencil +#define GL_APPLE_aux_depth_stencil 1 +#define GL_AUX_DEPTH_STENCIL_APPLE 0x8A14 +#endif /* GL_APPLE_aux_depth_stencil */ + +#ifndef GL_APPLE_client_storage +#define GL_APPLE_client_storage 1 +#define GL_UNPACK_CLIENT_STORAGE_APPLE 0x85B2 +#endif /* GL_APPLE_client_storage */ + +#ifndef GL_APPLE_element_array +#define GL_APPLE_element_array 1 +#define GL_ELEMENT_ARRAY_APPLE 0x8A0C +#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8A0D +#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x8A0E +typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glElementPointerAPPLE (GLenum type, const void *pointer); +GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum mode, GLint first, GLsizei count); +GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count); +GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount); +#endif +#endif /* GL_APPLE_element_array */ + +#ifndef GL_APPLE_fence +#define GL_APPLE_fence 1 +#define GL_DRAW_PIXELS_APPLE 0x8A0A +#define GL_FENCE_APPLE 0x8A0B +typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences); +typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences); +typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name); +typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenFencesAPPLE (GLsizei n, GLuint *fences); +GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei n, const GLuint *fences); +GLAPI void APIENTRY glSetFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint fence); +GLAPI void APIENTRY glFinishFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum object, GLuint name); +GLAPI void APIENTRY glFinishObjectAPPLE (GLenum object, GLint name); +#endif +#endif /* GL_APPLE_fence */ + +#ifndef GL_APPLE_float_pixels +#define GL_APPLE_float_pixels 1 +#define GL_HALF_APPLE 0x140B +#define GL_RGBA_FLOAT32_APPLE 0x8814 +#define GL_RGB_FLOAT32_APPLE 0x8815 +#define GL_ALPHA_FLOAT32_APPLE 0x8816 +#define GL_INTENSITY_FLOAT32_APPLE 0x8817 +#define GL_LUMINANCE_FLOAT32_APPLE 0x8818 +#define GL_LUMINANCE_ALPHA_FLOAT32_APPLE 0x8819 +#define GL_RGBA_FLOAT16_APPLE 0x881A +#define GL_RGB_FLOAT16_APPLE 0x881B +#define GL_ALPHA_FLOAT16_APPLE 0x881C +#define GL_INTENSITY_FLOAT16_APPLE 0x881D +#define GL_LUMINANCE_FLOAT16_APPLE 0x881E +#define GL_LUMINANCE_ALPHA_FLOAT16_APPLE 0x881F +#define GL_COLOR_FLOAT_APPLE 0x8A0F +#endif /* GL_APPLE_float_pixels */ + +#ifndef GL_APPLE_flush_buffer_range +#define GL_APPLE_flush_buffer_range 1 +#define GL_BUFFER_SERIALIZED_MODIFY_APPLE 0x8A12 +#define GL_BUFFER_FLUSHING_UNMAP_APPLE 0x8A13 +typedef void (APIENTRYP PFNGLBUFFERPARAMETERIAPPLEPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC) (GLenum target, GLintptr offset, GLsizeiptr size); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferParameteriAPPLE (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glFlushMappedBufferRangeAPPLE (GLenum target, GLintptr offset, GLsizeiptr size); +#endif +#endif /* GL_APPLE_flush_buffer_range */ + +#ifndef GL_APPLE_object_purgeable +#define GL_APPLE_object_purgeable 1 +#define GL_BUFFER_OBJECT_APPLE 0x85B3 +#define GL_RELEASED_APPLE 0x8A19 +#define GL_VOLATILE_APPLE 0x8A1A +#define GL_RETAINED_APPLE 0x8A1B +#define GL_UNDEFINED_APPLE 0x8A1C +#define GL_PURGEABLE_APPLE 0x8A1D +typedef GLenum (APIENTRYP PFNGLOBJECTPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option); +typedef GLenum (APIENTRYP PFNGLOBJECTUNPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVAPPLEPROC) (GLenum objectType, GLuint name, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLenum APIENTRY glObjectPurgeableAPPLE (GLenum objectType, GLuint name, GLenum option); +GLAPI GLenum APIENTRY glObjectUnpurgeableAPPLE (GLenum objectType, GLuint name, GLenum option); +GLAPI void APIENTRY glGetObjectParameterivAPPLE (GLenum objectType, GLuint name, GLenum pname, GLint *params); +#endif +#endif /* GL_APPLE_object_purgeable */ + +#ifndef GL_APPLE_rgb_422 +#define GL_APPLE_rgb_422 1 +#define GL_RGB_422_APPLE 0x8A1F +#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB +#define GL_RGB_RAW_422_APPLE 0x8A51 +#endif /* GL_APPLE_rgb_422 */ + +#ifndef GL_APPLE_row_bytes +#define GL_APPLE_row_bytes 1 +#define GL_PACK_ROW_BYTES_APPLE 0x8A15 +#define GL_UNPACK_ROW_BYTES_APPLE 0x8A16 +#endif /* GL_APPLE_row_bytes */ + +#ifndef GL_APPLE_specular_vector +#define GL_APPLE_specular_vector 1 +#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0 +#endif /* GL_APPLE_specular_vector */ + +#ifndef GL_APPLE_texture_range +#define GL_APPLE_texture_range 1 +#define GL_TEXTURE_RANGE_LENGTH_APPLE 0x85B7 +#define GL_TEXTURE_RANGE_POINTER_APPLE 0x85B8 +#define GL_TEXTURE_STORAGE_HINT_APPLE 0x85BC +#define GL_STORAGE_PRIVATE_APPLE 0x85BD +#define GL_STORAGE_CACHED_APPLE 0x85BE +#define GL_STORAGE_SHARED_APPLE 0x85BF +typedef void (APIENTRYP PFNGLTEXTURERANGEAPPLEPROC) (GLenum target, GLsizei length, const void *pointer); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERPOINTERVAPPLEPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureRangeAPPLE (GLenum target, GLsizei length, const void *pointer); +GLAPI void APIENTRY glGetTexParameterPointervAPPLE (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_APPLE_texture_range */ + +#ifndef GL_APPLE_transform_hint +#define GL_APPLE_transform_hint 1 +#define GL_TRANSFORM_HINT_APPLE 0x85B1 +#endif /* GL_APPLE_transform_hint */ + +#ifndef GL_APPLE_vertex_array_object +#define GL_APPLE_vertex_array_object 1 +#define GL_VERTEX_ARRAY_BINDING_APPLE 0x85B5 +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array); +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, GLuint *arrays); +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint array); +GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei n, const GLuint *arrays); +GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei n, GLuint *arrays); +GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint array); +#endif +#endif /* GL_APPLE_vertex_array_object */ + +#ifndef GL_APPLE_vertex_array_range +#define GL_APPLE_vertex_array_range 1 +#define GL_VERTEX_ARRAY_RANGE_APPLE 0x851D +#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E +#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F +#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521 +#define GL_STORAGE_CLIENT_APPLE 0x85B4 +typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void *pointer); +typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void *pointer); +typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei length, void *pointer); +GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei length, void *pointer); +GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum pname, GLint param); +#endif +#endif /* GL_APPLE_vertex_array_range */ + +#ifndef GL_APPLE_vertex_program_evaluators +#define GL_APPLE_vertex_program_evaluators 1 +#define GL_VERTEX_ATTRIB_MAP1_APPLE 0x8A00 +#define GL_VERTEX_ATTRIB_MAP2_APPLE 0x8A01 +#define GL_VERTEX_ATTRIB_MAP1_SIZE_APPLE 0x8A02 +#define GL_VERTEX_ATTRIB_MAP1_COEFF_APPLE 0x8A03 +#define GL_VERTEX_ATTRIB_MAP1_ORDER_APPLE 0x8A04 +#define GL_VERTEX_ATTRIB_MAP1_DOMAIN_APPLE 0x8A05 +#define GL_VERTEX_ATTRIB_MAP2_SIZE_APPLE 0x8A06 +#define GL_VERTEX_ATTRIB_MAP2_COEFF_APPLE 0x8A07 +#define GL_VERTEX_ATTRIB_MAP2_ORDER_APPLE 0x8A08 +#define GL_VERTEX_ATTRIB_MAP2_DOMAIN_APPLE 0x8A09 +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname); +typedef GLboolean (APIENTRYP PFNGLISVERTEXATTRIBENABLEDAPPLEPROC) (GLuint index, GLenum pname); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glEnableVertexAttribAPPLE (GLuint index, GLenum pname); +GLAPI void APIENTRY glDisableVertexAttribAPPLE (GLuint index, GLenum pname); +GLAPI GLboolean APIENTRY glIsVertexAttribEnabledAPPLE (GLuint index, GLenum pname); +GLAPI void APIENTRY glMapVertexAttrib1dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); +GLAPI void APIENTRY glMapVertexAttrib1fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); +GLAPI void APIENTRY glMapVertexAttrib2dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); +GLAPI void APIENTRY glMapVertexAttrib2fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); +#endif +#endif /* GL_APPLE_vertex_program_evaluators */ + +#ifndef GL_APPLE_ycbcr_422 +#define GL_APPLE_ycbcr_422 1 +#define GL_YCBCR_422_APPLE 0x85B9 +#endif /* GL_APPLE_ycbcr_422 */ + +#ifndef GL_ATI_draw_buffers +#define GL_ATI_draw_buffers 1 +#define GL_MAX_DRAW_BUFFERS_ATI 0x8824 +#define GL_DRAW_BUFFER0_ATI 0x8825 +#define GL_DRAW_BUFFER1_ATI 0x8826 +#define GL_DRAW_BUFFER2_ATI 0x8827 +#define GL_DRAW_BUFFER3_ATI 0x8828 +#define GL_DRAW_BUFFER4_ATI 0x8829 +#define GL_DRAW_BUFFER5_ATI 0x882A +#define GL_DRAW_BUFFER6_ATI 0x882B +#define GL_DRAW_BUFFER7_ATI 0x882C +#define GL_DRAW_BUFFER8_ATI 0x882D +#define GL_DRAW_BUFFER9_ATI 0x882E +#define GL_DRAW_BUFFER10_ATI 0x882F +#define GL_DRAW_BUFFER11_ATI 0x8830 +#define GL_DRAW_BUFFER12_ATI 0x8831 +#define GL_DRAW_BUFFER13_ATI 0x8832 +#define GL_DRAW_BUFFER14_ATI 0x8833 +#define GL_DRAW_BUFFER15_ATI 0x8834 +typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawBuffersATI (GLsizei n, const GLenum *bufs); +#endif +#endif /* GL_ATI_draw_buffers */ + +#ifndef GL_ATI_element_array +#define GL_ATI_element_array 1 +#define GL_ELEMENT_ARRAY_ATI 0x8768 +#define GL_ELEMENT_ARRAY_TYPE_ATI 0x8769 +#define GL_ELEMENT_ARRAY_POINTER_ATI 0x876A +typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glElementPointerATI (GLenum type, const void *pointer); +GLAPI void APIENTRY glDrawElementArrayATI (GLenum mode, GLsizei count); +GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum mode, GLuint start, GLuint end, GLsizei count); +#endif +#endif /* GL_ATI_element_array */ + +#ifndef GL_ATI_envmap_bumpmap +#define GL_ATI_envmap_bumpmap 1 +#define GL_BUMP_ROT_MATRIX_ATI 0x8775 +#define GL_BUMP_ROT_MATRIX_SIZE_ATI 0x8776 +#define GL_BUMP_NUM_TEX_UNITS_ATI 0x8777 +#define GL_BUMP_TEX_UNITS_ATI 0x8778 +#define GL_DUDV_ATI 0x8779 +#define GL_DU8DV8_ATI 0x877A +#define GL_BUMP_ENVMAP_ATI 0x877B +#define GL_BUMP_TARGET_ATI 0x877C +typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBumpParameterivATI (GLenum pname, const GLint *param); +GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum pname, GLint *param); +GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum pname, GLfloat *param); +#endif +#endif /* GL_ATI_envmap_bumpmap */ + +#ifndef GL_ATI_fragment_shader +#define GL_ATI_fragment_shader 1 +#define GL_FRAGMENT_SHADER_ATI 0x8920 +#define GL_REG_0_ATI 0x8921 +#define GL_REG_1_ATI 0x8922 +#define GL_REG_2_ATI 0x8923 +#define GL_REG_3_ATI 0x8924 +#define GL_REG_4_ATI 0x8925 +#define GL_REG_5_ATI 0x8926 +#define GL_REG_6_ATI 0x8927 +#define GL_REG_7_ATI 0x8928 +#define GL_REG_8_ATI 0x8929 +#define GL_REG_9_ATI 0x892A +#define GL_REG_10_ATI 0x892B +#define GL_REG_11_ATI 0x892C +#define GL_REG_12_ATI 0x892D +#define GL_REG_13_ATI 0x892E +#define GL_REG_14_ATI 0x892F +#define GL_REG_15_ATI 0x8930 +#define GL_REG_16_ATI 0x8931 +#define GL_REG_17_ATI 0x8932 +#define GL_REG_18_ATI 0x8933 +#define GL_REG_19_ATI 0x8934 +#define GL_REG_20_ATI 0x8935 +#define GL_REG_21_ATI 0x8936 +#define GL_REG_22_ATI 0x8937 +#define GL_REG_23_ATI 0x8938 +#define GL_REG_24_ATI 0x8939 +#define GL_REG_25_ATI 0x893A +#define GL_REG_26_ATI 0x893B +#define GL_REG_27_ATI 0x893C +#define GL_REG_28_ATI 0x893D +#define GL_REG_29_ATI 0x893E +#define GL_REG_30_ATI 0x893F +#define GL_REG_31_ATI 0x8940 +#define GL_CON_0_ATI 0x8941 +#define GL_CON_1_ATI 0x8942 +#define GL_CON_2_ATI 0x8943 +#define GL_CON_3_ATI 0x8944 +#define GL_CON_4_ATI 0x8945 +#define GL_CON_5_ATI 0x8946 +#define GL_CON_6_ATI 0x8947 +#define GL_CON_7_ATI 0x8948 +#define GL_CON_8_ATI 0x8949 +#define GL_CON_9_ATI 0x894A +#define GL_CON_10_ATI 0x894B +#define GL_CON_11_ATI 0x894C +#define GL_CON_12_ATI 0x894D +#define GL_CON_13_ATI 0x894E +#define GL_CON_14_ATI 0x894F +#define GL_CON_15_ATI 0x8950 +#define GL_CON_16_ATI 0x8951 +#define GL_CON_17_ATI 0x8952 +#define GL_CON_18_ATI 0x8953 +#define GL_CON_19_ATI 0x8954 +#define GL_CON_20_ATI 0x8955 +#define GL_CON_21_ATI 0x8956 +#define GL_CON_22_ATI 0x8957 +#define GL_CON_23_ATI 0x8958 +#define GL_CON_24_ATI 0x8959 +#define GL_CON_25_ATI 0x895A +#define GL_CON_26_ATI 0x895B +#define GL_CON_27_ATI 0x895C +#define GL_CON_28_ATI 0x895D +#define GL_CON_29_ATI 0x895E +#define GL_CON_30_ATI 0x895F +#define GL_CON_31_ATI 0x8960 +#define GL_MOV_ATI 0x8961 +#define GL_ADD_ATI 0x8963 +#define GL_MUL_ATI 0x8964 +#define GL_SUB_ATI 0x8965 +#define GL_DOT3_ATI 0x8966 +#define GL_DOT4_ATI 0x8967 +#define GL_MAD_ATI 0x8968 +#define GL_LERP_ATI 0x8969 +#define GL_CND_ATI 0x896A +#define GL_CND0_ATI 0x896B +#define GL_DOT2_ADD_ATI 0x896C +#define GL_SECONDARY_INTERPOLATOR_ATI 0x896D +#define GL_NUM_FRAGMENT_REGISTERS_ATI 0x896E +#define GL_NUM_FRAGMENT_CONSTANTS_ATI 0x896F +#define GL_NUM_PASSES_ATI 0x8970 +#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI 0x8971 +#define GL_NUM_INSTRUCTIONS_TOTAL_ATI 0x8972 +#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973 +#define GL_NUM_LOOPBACK_COMPONENTS_ATI 0x8974 +#define GL_COLOR_ALPHA_PAIRING_ATI 0x8975 +#define GL_SWIZZLE_STR_ATI 0x8976 +#define GL_SWIZZLE_STQ_ATI 0x8977 +#define GL_SWIZZLE_STR_DR_ATI 0x8978 +#define GL_SWIZZLE_STQ_DQ_ATI 0x8979 +#define GL_SWIZZLE_STRQ_ATI 0x897A +#define GL_SWIZZLE_STRQ_DQ_ATI 0x897B +#define GL_RED_BIT_ATI 0x00000001 +#define GL_GREEN_BIT_ATI 0x00000002 +#define GL_BLUE_BIT_ATI 0x00000004 +#define GL_2X_BIT_ATI 0x00000001 +#define GL_4X_BIT_ATI 0x00000002 +#define GL_8X_BIT_ATI 0x00000004 +#define GL_HALF_BIT_ATI 0x00000008 +#define GL_QUARTER_BIT_ATI 0x00000010 +#define GL_EIGHTH_BIT_ATI 0x00000020 +#define GL_SATURATE_BIT_ATI 0x00000040 +#define GL_COMP_BIT_ATI 0x00000002 +#define GL_NEGATE_BIT_ATI 0x00000004 +#define GL_BIAS_BIT_ATI 0x00000008 +typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range); +typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id); +typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void); +typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void); +typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle); +typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint range); +GLAPI void APIENTRY glBindFragmentShaderATI (GLuint id); +GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint id); +GLAPI void APIENTRY glBeginFragmentShaderATI (void); +GLAPI void APIENTRY glEndFragmentShaderATI (void); +GLAPI void APIENTRY glPassTexCoordATI (GLuint dst, GLuint coord, GLenum swizzle); +GLAPI void APIENTRY glSampleMapATI (GLuint dst, GLuint interp, GLenum swizzle); +GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint dst, const GLfloat *value); +#endif +#endif /* GL_ATI_fragment_shader */ + +#ifndef GL_ATI_map_object_buffer +#define GL_ATI_map_object_buffer 1 +typedef void *(APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void *APIENTRY glMapObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint buffer); +#endif +#endif /* GL_ATI_map_object_buffer */ + +#ifndef GL_ATI_meminfo +#define GL_ATI_meminfo 1 +#define GL_VBO_FREE_MEMORY_ATI 0x87FB +#define GL_TEXTURE_FREE_MEMORY_ATI 0x87FC +#define GL_RENDERBUFFER_FREE_MEMORY_ATI 0x87FD +#endif /* GL_ATI_meminfo */ + +#ifndef GL_ATI_pixel_format_float +#define GL_ATI_pixel_format_float 1 +#define GL_RGBA_FLOAT_MODE_ATI 0x8820 +#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835 +#endif /* GL_ATI_pixel_format_float */ + +#ifndef GL_ATI_pn_triangles +#define GL_ATI_pn_triangles 1 +#define GL_PN_TRIANGLES_ATI 0x87F0 +#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1 +#define GL_PN_TRIANGLES_POINT_MODE_ATI 0x87F2 +#define GL_PN_TRIANGLES_NORMAL_MODE_ATI 0x87F3 +#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4 +#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5 +#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6 +#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7 +#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8 +typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPNTrianglesiATI (GLenum pname, GLint param); +GLAPI void APIENTRY glPNTrianglesfATI (GLenum pname, GLfloat param); +#endif +#endif /* GL_ATI_pn_triangles */ + +#ifndef GL_ATI_separate_stencil +#define GL_ATI_separate_stencil 1 +#define GL_STENCIL_BACK_FUNC_ATI 0x8800 +#define GL_STENCIL_BACK_FAIL_ATI 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803 +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilOpSeparateATI (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); +#endif +#endif /* GL_ATI_separate_stencil */ + +#ifndef GL_ATI_text_fragment_shader +#define GL_ATI_text_fragment_shader 1 +#define GL_TEXT_FRAGMENT_SHADER_ATI 0x8200 +#endif /* GL_ATI_text_fragment_shader */ + +#ifndef GL_ATI_texture_env_combine3 +#define GL_ATI_texture_env_combine3 1 +#define GL_MODULATE_ADD_ATI 0x8744 +#define GL_MODULATE_SIGNED_ADD_ATI 0x8745 +#define GL_MODULATE_SUBTRACT_ATI 0x8746 +#endif /* GL_ATI_texture_env_combine3 */ + +#ifndef GL_ATI_texture_float +#define GL_ATI_texture_float 1 +#define GL_RGBA_FLOAT32_ATI 0x8814 +#define GL_RGB_FLOAT32_ATI 0x8815 +#define GL_ALPHA_FLOAT32_ATI 0x8816 +#define GL_INTENSITY_FLOAT32_ATI 0x8817 +#define GL_LUMINANCE_FLOAT32_ATI 0x8818 +#define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819 +#define GL_RGBA_FLOAT16_ATI 0x881A +#define GL_RGB_FLOAT16_ATI 0x881B +#define GL_ALPHA_FLOAT16_ATI 0x881C +#define GL_INTENSITY_FLOAT16_ATI 0x881D +#define GL_LUMINANCE_FLOAT16_ATI 0x881E +#define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F +#endif /* GL_ATI_texture_float */ + +#ifndef GL_ATI_texture_mirror_once +#define GL_ATI_texture_mirror_once 1 +#define GL_MIRROR_CLAMP_ATI 0x8742 +#define GL_MIRROR_CLAMP_TO_EDGE_ATI 0x8743 +#endif /* GL_ATI_texture_mirror_once */ + +#ifndef GL_ATI_vertex_array_object +#define GL_ATI_vertex_array_object 1 +#define GL_STATIC_ATI 0x8760 +#define GL_DYNAMIC_ATI 0x8761 +#define GL_PRESERVE_ATI 0x8762 +#define GL_DISCARD_ATI 0x8763 +#define GL_OBJECT_BUFFER_SIZE_ATI 0x8764 +#define GL_OBJECT_BUFFER_USAGE_ATI 0x8765 +#define GL_ARRAY_OBJECT_BUFFER_ATI 0x8766 +#define GL_ARRAY_OBJECT_OFFSET_ATI 0x8767 +typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const void *pointer, GLenum usage); +typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const void *pointer, GLenum preserve); +typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei size, const void *pointer, GLenum usage); +GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint buffer, GLuint offset, GLsizei size, const void *pointer, GLenum preserve); +GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint buffer, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetObjectBufferivATI (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glFreeObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glArrayObjectATI (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum array, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetArrayObjectivATI (GLenum array, GLenum pname, GLint *params); +GLAPI void APIENTRY glVariantArrayObjectATI (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint id, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint id, GLenum pname, GLint *params); +#endif +#endif /* GL_ATI_vertex_array_object */ + +#ifndef GL_ATI_vertex_attrib_array_object +#define GL_ATI_vertex_attrib_array_object 1 +typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint index, GLenum pname, GLint *params); +#endif +#endif /* GL_ATI_vertex_attrib_array_object */ + +#ifndef GL_ATI_vertex_streams +#define GL_ATI_vertex_streams 1 +#define GL_MAX_VERTEX_STREAMS_ATI 0x876B +#define GL_VERTEX_STREAM0_ATI 0x876C +#define GL_VERTEX_STREAM1_ATI 0x876D +#define GL_VERTEX_STREAM2_ATI 0x876E +#define GL_VERTEX_STREAM3_ATI 0x876F +#define GL_VERTEX_STREAM4_ATI 0x8770 +#define GL_VERTEX_STREAM5_ATI 0x8771 +#define GL_VERTEX_STREAM6_ATI 0x8772 +#define GL_VERTEX_STREAM7_ATI 0x8773 +#define GL_VERTEX_SOURCE_ATI 0x8774 +typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream); +typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexStream1sATI (GLenum stream, GLshort x); +GLAPI void APIENTRY glVertexStream1svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream1iATI (GLenum stream, GLint x); +GLAPI void APIENTRY glVertexStream1ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream1fATI (GLenum stream, GLfloat x); +GLAPI void APIENTRY glVertexStream1fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream1dATI (GLenum stream, GLdouble x); +GLAPI void APIENTRY glVertexStream1dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream2sATI (GLenum stream, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexStream2svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream2iATI (GLenum stream, GLint x, GLint y); +GLAPI void APIENTRY glVertexStream2ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream2fATI (GLenum stream, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexStream2fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream2dATI (GLenum stream, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexStream2dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream3sATI (GLenum stream, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexStream3svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream3iATI (GLenum stream, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexStream3ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream3fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexStream3fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream3dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexStream3dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream4sATI (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexStream4svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream4iATI (GLenum stream, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexStream4ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream4fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexStream4fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream4dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexStream4dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glNormalStream3bATI (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz); +GLAPI void APIENTRY glNormalStream3bvATI (GLenum stream, const GLbyte *coords); +GLAPI void APIENTRY glNormalStream3sATI (GLenum stream, GLshort nx, GLshort ny, GLshort nz); +GLAPI void APIENTRY glNormalStream3svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glNormalStream3iATI (GLenum stream, GLint nx, GLint ny, GLint nz); +GLAPI void APIENTRY glNormalStream3ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glNormalStream3fATI (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz); +GLAPI void APIENTRY glNormalStream3fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glNormalStream3dATI (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz); +GLAPI void APIENTRY glNormalStream3dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum stream); +GLAPI void APIENTRY glVertexBlendEnviATI (GLenum pname, GLint param); +GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum pname, GLfloat param); +#endif +#endif /* GL_ATI_vertex_streams */ + +#ifndef GL_EXT_422_pixels +#define GL_EXT_422_pixels 1 +#define GL_422_EXT 0x80CC +#define GL_422_REV_EXT 0x80CD +#define GL_422_AVERAGE_EXT 0x80CE +#define GL_422_REV_AVERAGE_EXT 0x80CF +#endif /* GL_EXT_422_pixels */ + +#ifndef GL_EXT_EGL_image_storage +#define GL_EXT_EGL_image_storage 1 +typedef void *GLeglImageOES; +typedef void (APIENTRYP PFNGLEGLIMAGETARGETTEXSTORAGEEXTPROC) (GLenum target, GLeglImageOES image, const GLint* attrib_list); +typedef void (APIENTRYP PFNGLEGLIMAGETARGETTEXTURESTORAGEEXTPROC) (GLuint texture, GLeglImageOES image, const GLint* attrib_list); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glEGLImageTargetTexStorageEXT (GLenum target, GLeglImageOES image, const GLint* attrib_list); +GLAPI void APIENTRY glEGLImageTargetTextureStorageEXT (GLuint texture, GLeglImageOES image, const GLint* attrib_list); +#endif +#endif /* GL_EXT_EGL_image_storage */ + +#ifndef GL_EXT_EGL_sync +#define GL_EXT_EGL_sync 1 +#endif /* GL_EXT_EGL_sync */ + +#ifndef GL_EXT_abgr +#define GL_EXT_abgr 1 +#define GL_ABGR_EXT 0x8000 +#endif /* GL_EXT_abgr */ + +#ifndef GL_EXT_bgra +#define GL_EXT_bgra 1 +#define GL_BGR_EXT 0x80E0 +#define GL_BGRA_EXT 0x80E1 +#endif /* GL_EXT_bgra */ + +#ifndef GL_EXT_bindable_uniform +#define GL_EXT_bindable_uniform 1 +#define GL_MAX_VERTEX_BINDABLE_UNIFORMS_EXT 0x8DE2 +#define GL_MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT 0x8DE3 +#define GL_MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT 0x8DE4 +#define GL_MAX_BINDABLE_UNIFORM_SIZE_EXT 0x8DED +#define GL_UNIFORM_BUFFER_EXT 0x8DEE +#define GL_UNIFORM_BUFFER_BINDING_EXT 0x8DEF +typedef void (APIENTRYP PFNGLUNIFORMBUFFEREXTPROC) (GLuint program, GLint location, GLuint buffer); +typedef GLint (APIENTRYP PFNGLGETUNIFORMBUFFERSIZEEXTPROC) (GLuint program, GLint location); +typedef GLintptr (APIENTRYP PFNGLGETUNIFORMOFFSETEXTPROC) (GLuint program, GLint location); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniformBufferEXT (GLuint program, GLint location, GLuint buffer); +GLAPI GLint APIENTRY glGetUniformBufferSizeEXT (GLuint program, GLint location); +GLAPI GLintptr APIENTRY glGetUniformOffsetEXT (GLuint program, GLint location); +#endif +#endif /* GL_EXT_bindable_uniform */ + +#ifndef GL_EXT_blend_color +#define GL_EXT_blend_color 1 +#define GL_CONSTANT_COLOR_EXT 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR_EXT 0x8002 +#define GL_CONSTANT_ALPHA_EXT 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT 0x8004 +#define GL_BLEND_COLOR_EXT 0x8005 +typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendColorEXT (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#endif +#endif /* GL_EXT_blend_color */ + +#ifndef GL_EXT_blend_equation_separate +#define GL_EXT_blend_equation_separate 1 +#define GL_BLEND_EQUATION_RGB_EXT 0x8009 +#define GL_BLEND_EQUATION_ALPHA_EXT 0x883D +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum modeRGB, GLenum modeAlpha); +#endif +#endif /* GL_EXT_blend_equation_separate */ + +#ifndef GL_EXT_blend_func_separate +#define GL_EXT_blend_func_separate 1 +#define GL_BLEND_DST_RGB_EXT 0x80C8 +#define GL_BLEND_SRC_RGB_EXT 0x80C9 +#define GL_BLEND_DST_ALPHA_EXT 0x80CA +#define GL_BLEND_SRC_ALPHA_EXT 0x80CB +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#endif +#endif /* GL_EXT_blend_func_separate */ + +#ifndef GL_EXT_blend_logic_op +#define GL_EXT_blend_logic_op 1 +#endif /* GL_EXT_blend_logic_op */ + +#ifndef GL_EXT_blend_minmax +#define GL_EXT_blend_minmax 1 +#define GL_MIN_EXT 0x8007 +#define GL_MAX_EXT 0x8008 +#define GL_FUNC_ADD_EXT 0x8006 +#define GL_BLEND_EQUATION_EXT 0x8009 +typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationEXT (GLenum mode); +#endif +#endif /* GL_EXT_blend_minmax */ + +#ifndef GL_EXT_blend_subtract +#define GL_EXT_blend_subtract 1 +#define GL_FUNC_SUBTRACT_EXT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT_EXT 0x800B +#endif /* GL_EXT_blend_subtract */ + +#ifndef GL_EXT_clip_volume_hint +#define GL_EXT_clip_volume_hint 1 +#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT 0x80F0 +#endif /* GL_EXT_clip_volume_hint */ + +#ifndef GL_EXT_cmyka +#define GL_EXT_cmyka 1 +#define GL_CMYK_EXT 0x800C +#define GL_CMYKA_EXT 0x800D +#define GL_PACK_CMYK_HINT_EXT 0x800E +#define GL_UNPACK_CMYK_HINT_EXT 0x800F +#endif /* GL_EXT_cmyka */ + +#ifndef GL_EXT_color_subtable +#define GL_EXT_color_subtable 1 +typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorSubTableEXT (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +#endif +#endif /* GL_EXT_color_subtable */ + +#ifndef GL_EXT_compiled_vertex_array +#define GL_EXT_compiled_vertex_array 1 +#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT 0x81A8 +#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT 0x81A9 +typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLockArraysEXT (GLint first, GLsizei count); +GLAPI void APIENTRY glUnlockArraysEXT (void); +#endif +#endif /* GL_EXT_compiled_vertex_array */ + +#ifndef GL_EXT_convolution +#define GL_EXT_convolution 1 +#define GL_CONVOLUTION_1D_EXT 0x8010 +#define GL_CONVOLUTION_2D_EXT 0x8011 +#define GL_SEPARABLE_2D_EXT 0x8012 +#define GL_CONVOLUTION_BORDER_MODE_EXT 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE_EXT 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS_EXT 0x8015 +#define GL_REDUCE_EXT 0x8016 +#define GL_CONVOLUTION_FORMAT_EXT 0x8017 +#define GL_CONVOLUTION_WIDTH_EXT 0x8018 +#define GL_CONVOLUTION_HEIGHT_EXT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH_EXT 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT_EXT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS_EXT 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023 +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, void *image); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum target, GLenum pname, GLfloat params); +GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum target, GLenum pname, GLint params); +GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum target, GLenum format, GLenum type, void *image); +GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +#endif +#endif /* GL_EXT_convolution */ + +#ifndef GL_EXT_coordinate_frame +#define GL_EXT_coordinate_frame 1 +#define GL_TANGENT_ARRAY_EXT 0x8439 +#define GL_BINORMAL_ARRAY_EXT 0x843A +#define GL_CURRENT_TANGENT_EXT 0x843B +#define GL_CURRENT_BINORMAL_EXT 0x843C +#define GL_TANGENT_ARRAY_TYPE_EXT 0x843E +#define GL_TANGENT_ARRAY_STRIDE_EXT 0x843F +#define GL_BINORMAL_ARRAY_TYPE_EXT 0x8440 +#define GL_BINORMAL_ARRAY_STRIDE_EXT 0x8441 +#define GL_TANGENT_ARRAY_POINTER_EXT 0x8442 +#define GL_BINORMAL_ARRAY_POINTER_EXT 0x8443 +#define GL_MAP1_TANGENT_EXT 0x8444 +#define GL_MAP2_TANGENT_EXT 0x8445 +#define GL_MAP1_BINORMAL_EXT 0x8446 +#define GL_MAP2_BINORMAL_EXT 0x8447 +typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz); +typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz); +typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz); +typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz); +typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz); +typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz); +typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz); +typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz); +typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz); +typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz); +typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTangent3bEXT (GLbyte tx, GLbyte ty, GLbyte tz); +GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glTangent3dEXT (GLdouble tx, GLdouble ty, GLdouble tz); +GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glTangent3fEXT (GLfloat tx, GLfloat ty, GLfloat tz); +GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glTangent3iEXT (GLint tx, GLint ty, GLint tz); +GLAPI void APIENTRY glTangent3ivEXT (const GLint *v); +GLAPI void APIENTRY glTangent3sEXT (GLshort tx, GLshort ty, GLshort tz); +GLAPI void APIENTRY glTangent3svEXT (const GLshort *v); +GLAPI void APIENTRY glBinormal3bEXT (GLbyte bx, GLbyte by, GLbyte bz); +GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glBinormal3dEXT (GLdouble bx, GLdouble by, GLdouble bz); +GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glBinormal3fEXT (GLfloat bx, GLfloat by, GLfloat bz); +GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glBinormal3iEXT (GLint bx, GLint by, GLint bz); +GLAPI void APIENTRY glBinormal3ivEXT (const GLint *v); +GLAPI void APIENTRY glBinormal3sEXT (GLshort bx, GLshort by, GLshort bz); +GLAPI void APIENTRY glBinormal3svEXT (const GLshort *v); +GLAPI void APIENTRY glTangentPointerEXT (GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glBinormalPointerEXT (GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_coordinate_frame */ + +#ifndef GL_EXT_copy_texture +#define GL_EXT_copy_texture 1 +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif +#endif /* GL_EXT_copy_texture */ + +#ifndef GL_EXT_cull_vertex +#define GL_EXT_cull_vertex 1 +#define GL_CULL_VERTEX_EXT 0x81AA +#define GL_CULL_VERTEX_EYE_POSITION_EXT 0x81AB +#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC +typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCullParameterdvEXT (GLenum pname, GLdouble *params); +GLAPI void APIENTRY glCullParameterfvEXT (GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_cull_vertex */ + +#ifndef GL_EXT_debug_label +#define GL_EXT_debug_label 1 +#define GL_PROGRAM_PIPELINE_OBJECT_EXT 0x8A4F +#define GL_PROGRAM_OBJECT_EXT 0x8B40 +#define GL_SHADER_OBJECT_EXT 0x8B48 +#define GL_BUFFER_OBJECT_EXT 0x9151 +#define GL_QUERY_OBJECT_EXT 0x9153 +#define GL_VERTEX_ARRAY_OBJECT_EXT 0x9154 +typedef void (APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); +#endif +#endif /* GL_EXT_debug_label */ + +#ifndef GL_EXT_debug_marker +#define GL_EXT_debug_marker 1 +typedef void (APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker); +typedef void (APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker); +typedef void (APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker); +GLAPI void APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker); +GLAPI void APIENTRY glPopGroupMarkerEXT (void); +#endif +#endif /* GL_EXT_debug_marker */ + +#ifndef GL_EXT_depth_bounds_test +#define GL_EXT_depth_bounds_test 1 +#define GL_DEPTH_BOUNDS_TEST_EXT 0x8890 +#define GL_DEPTH_BOUNDS_EXT 0x8891 +typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDepthBoundsEXT (GLclampd zmin, GLclampd zmax); +#endif +#endif /* GL_EXT_depth_bounds_test */ + +#ifndef GL_EXT_direct_state_access +#define GL_EXT_direct_state_access 1 +#define GL_PROGRAM_MATRIX_EXT 0x8E2D +#define GL_TRANSPOSE_PROGRAM_MATRIX_EXT 0x8E2E +#define GL_PROGRAM_MATRIX_STACK_DEPTH_EXT 0x8E2F +typedef void (APIENTRYP PFNGLMATRIXLOADFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXMULTFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXLOADIDENTITYEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLMATRIXROTATEFEXTPROC) (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXROTATEDEXTPROC) (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXSCALEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXSCALEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXTRANSLATEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXTRANSLATEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXFRUSTUMEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLMATRIXORTHOEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLMATRIXPOPEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLMATRIXPUSHEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLBINDMULTITEXTUREEXTPROC) (GLenum texunit, GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORDPOINTEREXTPROC) (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLMULTITEXENVFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXENVIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXGENDEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble param); +typedef void (APIENTRYP PFNGLMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params); +typedef void (APIENTRYP PFNGLMULTITEXGENFEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXGENIEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLGETFLOATINDEXEDVEXTPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (APIENTRYP PFNGLGETDOUBLEINDEXEDVEXTPROC) (GLenum target, GLuint index, GLdouble *data); +typedef void (APIENTRYP PFNGLGETPOINTERINDEXEDVEXTPROC) (GLenum target, GLuint index, void **data); +typedef void (APIENTRYP PFNGLENABLEINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISENABLEDINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLGETINTEGERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLint *data); +typedef void (APIENTRYP PFNGLGETBOOLEANINDEXEDVEXTPROC) (GLenum target, GLuint index, GLboolean *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint lod, void *img); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint lod, void *img); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFEREXTPROC) (GLuint buffer, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVEXTPROC) (GLuint buffer, GLenum pname, void **params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLTEXTUREBUFFEREXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLMULTITEXBUFFEREXTPROC) (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC) (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint *params); +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMIVEXTPROC) (GLuint program, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum pname, void *string); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC) (GLuint renderbuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC) (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC) (GLuint framebuffer, GLenum target); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPEXTPROC) (GLuint texture, GLenum target); +typedef void (APIENTRYP PFNGLGENERATEMULTITEXMIPMAPEXTPROC) (GLenum texunit, GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC) (GLuint framebuffer, GLenum mode); +typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLFRAMEBUFFERREADBUFFEREXTPROC) (GLuint framebuffer, GLenum mode); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face); +typedef void (APIENTRYP PFNGLTEXTURERENDERBUFFEREXTPROC) (GLuint texture, GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLMULTITEXRENDERBUFFEREXTPROC) (GLenum texunit, GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYINDEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYNORMALOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERVEXTPROC) (GLuint vaobj, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERVEXTPROC) (GLuint vaobj, GLenum pname, void **param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC) (GLuint framebuffer, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DEXTPROC) (GLuint program, GLint location, GLdouble x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEEXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLTEXTUREPAGECOMMITMENTEXTPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBDIVISOREXTPROC) (GLuint vaobj, GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMatrixLoadfEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoaddEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixMultfEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultdEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixLoadIdentityEXT (GLenum mode); +GLAPI void APIENTRY glMatrixRotatefEXT (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixRotatedEXT (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixScalefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixScaledEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixTranslatefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixTranslatedEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixFrustumEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glMatrixOrthoEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glMatrixPopEXT (GLenum mode); +GLAPI void APIENTRY glMatrixPushEXT (GLenum mode); +GLAPI void APIENTRY glClientAttribDefaultEXT (GLbitfield mask); +GLAPI void APIENTRY glPushClientAttribDefaultEXT (GLbitfield mask); +GLAPI void APIENTRY glTextureParameterfEXT (GLuint texture, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glTextureParameteriEXT (GLuint texture, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetTextureImageEXT (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI void APIENTRY glGetTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureLevelParameterfvEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureLevelParameterivEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glBindMultiTextureEXT (GLenum texunit, GLenum target, GLuint texture); +GLAPI void APIENTRY glMultiTexCoordPointerEXT (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glMultiTexEnvfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexEnviEXT (GLenum texunit, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexGendEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble param); +GLAPI void APIENTRY glMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params); +GLAPI void APIENTRY glMultiTexGenfEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexGeniEXT (GLenum texunit, GLenum coord, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, const GLint *params); +GLAPI void APIENTRY glGetMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, GLint *params); +GLAPI void APIENTRY glMultiTexParameteriEXT (GLenum texunit, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexParameterfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetMultiTexImageEXT (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI void APIENTRY glGetMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexLevelParameterfvEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexLevelParameterivEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glEnableClientStateIndexedEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glDisableClientStateIndexedEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glGetFloatIndexedvEXT (GLenum target, GLuint index, GLfloat *data); +GLAPI void APIENTRY glGetDoubleIndexedvEXT (GLenum target, GLuint index, GLdouble *data); +GLAPI void APIENTRY glGetPointerIndexedvEXT (GLenum target, GLuint index, void **data); +GLAPI void APIENTRY glEnableIndexedEXT (GLenum target, GLuint index); +GLAPI void APIENTRY glDisableIndexedEXT (GLenum target, GLuint index); +GLAPI GLboolean APIENTRY glIsEnabledIndexedEXT (GLenum target, GLuint index); +GLAPI void APIENTRY glGetIntegerIndexedvEXT (GLenum target, GLuint index, GLint *data); +GLAPI void APIENTRY glGetBooleanIndexedvEXT (GLenum target, GLuint index, GLboolean *data); +GLAPI void APIENTRY glCompressedTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glGetCompressedTextureImageEXT (GLuint texture, GLenum target, GLint lod, void *img); +GLAPI void APIENTRY glCompressedMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glGetCompressedMultiTexImageEXT (GLenum texunit, GLenum target, GLint lod, void *img); +GLAPI void APIENTRY glMatrixLoadTransposefEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoadTransposedEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixMultTransposefEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultTransposedEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glNamedBufferDataEXT (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void *APIENTRY glMapNamedBufferEXT (GLuint buffer, GLenum access); +GLAPI GLboolean APIENTRY glUnmapNamedBufferEXT (GLuint buffer); +GLAPI void APIENTRY glGetNamedBufferParameterivEXT (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedBufferPointervEXT (GLuint buffer, GLenum pname, void **params); +GLAPI void APIENTRY glGetNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +GLAPI void APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0); +GLAPI void APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0); +GLAPI void APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glTextureBufferEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glMultiTexBufferEXT (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0); +GLAPI void APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glNamedProgramLocalParameters4fvEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glNamedProgramLocalParameterI4iEXT (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glNamedProgramLocalParameterI4ivEXT (GLuint program, GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glNamedProgramLocalParametersI4ivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glNamedProgramLocalParameterI4uiEXT (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glNamedProgramLocalParameterI4uivEXT (GLuint program, GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glNamedProgramLocalParametersI4uivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterIivEXT (GLuint program, GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterIuivEXT (GLuint program, GLenum target, GLuint index, GLuint *params); +GLAPI void APIENTRY glEnableClientStateiEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glDisableClientStateiEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glGetFloati_vEXT (GLenum pname, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetDoublei_vEXT (GLenum pname, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetPointeri_vEXT (GLenum pname, GLuint index, void **params); +GLAPI void APIENTRY glNamedProgramStringEXT (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string); +GLAPI void APIENTRY glNamedProgramLocalParameter4dEXT (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glNamedProgramLocalParameter4dvEXT (GLuint program, GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glNamedProgramLocalParameter4fEXT (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glNamedProgramLocalParameter4fvEXT (GLuint program, GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterdvEXT (GLuint program, GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterfvEXT (GLuint program, GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetNamedProgramivEXT (GLuint program, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedProgramStringEXT (GLuint program, GLenum target, GLenum pname, void *string); +GLAPI void APIENTRY glNamedRenderbufferStorageEXT (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetNamedRenderbufferParameterivEXT (GLuint renderbuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleEXT (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleCoverageEXT (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI GLenum APIENTRY glCheckNamedFramebufferStatusEXT (GLuint framebuffer, GLenum target); +GLAPI void APIENTRY glNamedFramebufferTexture1DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTexture2DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTexture3DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glNamedFramebufferRenderbufferEXT (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameterivEXT (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateTextureMipmapEXT (GLuint texture, GLenum target); +GLAPI void APIENTRY glGenerateMultiTexMipmapEXT (GLenum texunit, GLenum target); +GLAPI void APIENTRY glFramebufferDrawBufferEXT (GLuint framebuffer, GLenum mode); +GLAPI void APIENTRY glFramebufferDrawBuffersEXT (GLuint framebuffer, GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glFramebufferReadBufferEXT (GLuint framebuffer, GLenum mode); +GLAPI void APIENTRY glGetFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glNamedCopyBufferSubDataEXT (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glNamedFramebufferTextureEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTextureLayerEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glNamedFramebufferTextureFaceEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face); +GLAPI void APIENTRY glTextureRenderbufferEXT (GLuint texture, GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glMultiTexRenderbufferEXT (GLenum texunit, GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glVertexArrayVertexOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayEdgeFlagOffsetEXT (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayIndexOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayNormalOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayMultiTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayFogCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArraySecondaryColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayVertexAttribOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayVertexAttribIOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glEnableVertexArrayEXT (GLuint vaobj, GLenum array); +GLAPI void APIENTRY glDisableVertexArrayEXT (GLuint vaobj, GLenum array); +GLAPI void APIENTRY glEnableVertexArrayAttribEXT (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glDisableVertexArrayAttribEXT (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glGetVertexArrayIntegervEXT (GLuint vaobj, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayPointervEXT (GLuint vaobj, GLenum pname, void **param); +GLAPI void APIENTRY glGetVertexArrayIntegeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayPointeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, void **param); +GLAPI void *APIENTRY glMapNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI void APIENTRY glFlushMappedNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glNamedBufferStorageEXT (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glClearNamedBufferDataEXT (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearNamedBufferSubDataEXT (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glNamedFramebufferParameteriEXT (GLuint framebuffer, GLenum pname, GLint param); +GLAPI void APIENTRY glGetNamedFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glProgramUniform1dEXT (GLuint program, GLint location, GLdouble x); +GLAPI void APIENTRY glProgramUniform2dEXT (GLuint program, GLint location, GLdouble x, GLdouble y); +GLAPI void APIENTRY glProgramUniform3dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glProgramUniform4dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramUniform1dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform2dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform3dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform4dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glTextureBufferRangeEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glTextureStorage2DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureStorage3DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glVertexArrayBindVertexBufferEXT (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexArrayVertexAttribFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribIFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribLFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribBindingEXT (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexArrayVertexBindingDivisorEXT (GLuint vaobj, GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glVertexArrayVertexAttribLOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glTexturePageCommitmentEXT (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +GLAPI void APIENTRY glVertexArrayVertexAttribDivisorEXT (GLuint vaobj, GLuint index, GLuint divisor); +#endif +#endif /* GL_EXT_direct_state_access */ + +#ifndef GL_EXT_draw_buffers2 +#define GL_EXT_draw_buffers2 1 +typedef void (APIENTRYP PFNGLCOLORMASKINDEXEDEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorMaskIndexedEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +#endif +#endif /* GL_EXT_draw_buffers2 */ + +#ifndef GL_EXT_draw_instanced +#define GL_EXT_draw_instanced 1 +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +GLAPI void APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#endif +#endif /* GL_EXT_draw_instanced */ + +#ifndef GL_EXT_draw_range_elements +#define GL_EXT_draw_range_elements 1 +#define GL_MAX_ELEMENTS_VERTICES_EXT 0x80E8 +#define GL_MAX_ELEMENTS_INDICES_EXT 0x80E9 +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +#endif +#endif /* GL_EXT_draw_range_elements */ + +#ifndef GL_EXT_external_buffer +#define GL_EXT_external_buffer 1 +typedef void *GLeglClientBufferEXT; +typedef void (APIENTRYP PFNGLBUFFERSTORAGEEXTERNALEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTERNALEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferStorageExternalEXT (GLenum target, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags); +GLAPI void APIENTRY glNamedBufferStorageExternalEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags); +#endif +#endif /* GL_EXT_external_buffer */ + +#ifndef GL_EXT_fog_coord +#define GL_EXT_fog_coord 1 +#define GL_FOG_COORDINATE_SOURCE_EXT 0x8450 +#define GL_FOG_COORDINATE_EXT 0x8451 +#define GL_FRAGMENT_DEPTH_EXT 0x8452 +#define GL_CURRENT_FOG_COORDINATE_EXT 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456 +#define GL_FOG_COORDINATE_ARRAY_EXT 0x8457 +typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord); +typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord); +typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord); +typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFogCoordfEXT (GLfloat coord); +GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *coord); +GLAPI void APIENTRY glFogCoorddEXT (GLdouble coord); +GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *coord); +GLAPI void APIENTRY glFogCoordPointerEXT (GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_fog_coord */ + +#ifndef GL_EXT_framebuffer_blit +#define GL_EXT_framebuffer_blit 1 +#define GL_READ_FRAMEBUFFER_EXT 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlitFramebufferEXT (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#endif +#endif /* GL_EXT_framebuffer_blit */ + +#ifndef GL_EXT_framebuffer_multisample +#define GL_EXT_framebuffer_multisample 1 +#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 +#define GL_MAX_SAMPLES_EXT 0x8D57 +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_EXT_framebuffer_multisample */ + +#ifndef GL_EXT_framebuffer_multisample_blit_scaled +#define GL_EXT_framebuffer_multisample_blit_scaled 1 +#define GL_SCALED_RESOLVE_FASTEST_EXT 0x90BA +#define GL_SCALED_RESOLVE_NICEST_EXT 0x90BB +#endif /* GL_EXT_framebuffer_multisample_blit_scaled */ + +#ifndef GL_EXT_framebuffer_object +#define GL_EXT_framebuffer_object 1 +#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 +#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 +#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 +#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 +#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 +#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 +#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 +#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 +#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 +#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 +#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 +#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 +#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA +#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB +#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC +#define GL_COLOR_ATTACHMENT13_EXT 0x8CED +#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE +#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#define GL_STENCIL_ATTACHMENT_EXT 0x8D20 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_RENDERBUFFER_EXT 0x8D41 +#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 +#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 +#define GL_STENCIL_INDEX1_EXT 0x8D46 +#define GL_STENCIL_INDEX4_EXT 0x8D47 +#define GL_STENCIL_INDEX8_EXT 0x8D48 +#define GL_STENCIL_INDEX16_EXT 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer); +typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer); +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer); +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers); +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint renderbuffer); +GLAPI void APIENTRY glBindRenderbufferEXT (GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei n, const GLuint *renderbuffers); +GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint framebuffer); +GLAPI void APIENTRY glBindFramebufferEXT (GLenum target, GLuint framebuffer); +GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei n, const GLuint *framebuffers); +GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei n, GLuint *framebuffers); +GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum target); +GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateMipmapEXT (GLenum target); +#endif +#endif /* GL_EXT_framebuffer_object */ + +#ifndef GL_EXT_framebuffer_sRGB +#define GL_EXT_framebuffer_sRGB 1 +#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9 +#define GL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x8DBA +#endif /* GL_EXT_framebuffer_sRGB */ + +#ifndef GL_EXT_geometry_shader4 +#define GL_EXT_geometry_shader4 1 +#define GL_GEOMETRY_SHADER_EXT 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT_EXT 0x8DDA +#define GL_GEOMETRY_INPUT_TYPE_EXT 0x8DDB +#define GL_GEOMETRY_OUTPUT_TYPE_EXT 0x8DDC +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29 +#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT 0x8DDD +#define GL_MAX_VERTEX_VARYING_COMPONENTS_EXT 0x8DDE +#define GL_MAX_VARYING_COMPONENTS_EXT 0x8B4B +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1 +#define GL_LINES_ADJACENCY_EXT 0x000A +#define GL_LINE_STRIP_ADJACENCY_EXT 0x000B +#define GL_TRIANGLES_ADJACENCY_EXT 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0x000D +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 +#define GL_PROGRAM_POINT_SIZE_EXT 0x8642 +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value); +#endif +#endif /* GL_EXT_geometry_shader4 */ + +#ifndef GL_EXT_gpu_program_parameters +#define GL_EXT_gpu_program_parameters 1 +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramEnvParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glProgramLocalParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +#endif +#endif /* GL_EXT_gpu_program_parameters */ + +#ifndef GL_EXT_gpu_shader4 +#define GL_EXT_gpu_shader4 1 +#define GL_SAMPLER_1D_ARRAY_EXT 0x8DC0 +#define GL_SAMPLER_2D_ARRAY_EXT 0x8DC1 +#define GL_SAMPLER_BUFFER_EXT 0x8DC2 +#define GL_SAMPLER_1D_ARRAY_SHADOW_EXT 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW_EXT 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW_EXT 0x8DC5 +#define GL_UNSIGNED_INT_VEC2_EXT 0x8DC6 +#define GL_UNSIGNED_INT_VEC3_EXT 0x8DC7 +#define GL_UNSIGNED_INT_VEC4_EXT 0x8DC8 +#define GL_INT_SAMPLER_1D_EXT 0x8DC9 +#define GL_INT_SAMPLER_2D_EXT 0x8DCA +#define GL_INT_SAMPLER_3D_EXT 0x8DCB +#define GL_INT_SAMPLER_CUBE_EXT 0x8DCC +#define GL_INT_SAMPLER_2D_RECT_EXT 0x8DCD +#define GL_INT_SAMPLER_1D_ARRAY_EXT 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY_EXT 0x8DCF +#define GL_INT_SAMPLER_BUFFER_EXT 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_1D_EXT 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D_EXT 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D_EXT 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE_EXT 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT 0x8DD7 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8 +#define GL_MIN_PROGRAM_TEXEL_OFFSET_EXT 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET_EXT 0x8905 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_EXT 0x88FD +typedef void (APIENTRYP PFNGLGETUNIFORMUIVEXTPROC) (GLuint program, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONEXTPROC) (GLuint program, GLuint color, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONEXTPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORM1UIEXTPROC) (GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLUNIFORM2UIEXTPROC) (GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLUNIFORM3UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLUNIFORM4UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLUNIFORM1UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM2UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM3UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM4UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IEXTPROC) (GLuint index, GLint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IEXTPROC) (GLuint index, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IEXTPROC) (GLuint index, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IEXTPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIEXTPROC) (GLuint index, GLuint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIEXTPROC) (GLuint index, GLuint x, GLuint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVEXTPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVEXTPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVEXTPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVEXTPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVEXTPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVEXTPROC) (GLuint index, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetUniformuivEXT (GLuint program, GLint location, GLuint *params); +GLAPI void APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataLocationEXT (GLuint program, const GLchar *name); +GLAPI void APIENTRY glUniform1uiEXT (GLint location, GLuint v0); +GLAPI void APIENTRY glUniform2uiEXT (GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glUniform3uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glUniform4uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glUniform1uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform2uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform3uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform4uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glVertexAttribI1iEXT (GLuint index, GLint x); +GLAPI void APIENTRY glVertexAttribI2iEXT (GLuint index, GLint x, GLint y); +GLAPI void APIENTRY glVertexAttribI3iEXT (GLuint index, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexAttribI4iEXT (GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexAttribI1uiEXT (GLuint index, GLuint x); +GLAPI void APIENTRY glVertexAttribI2uiEXT (GLuint index, GLuint x, GLuint y); +GLAPI void APIENTRY glVertexAttribI3uiEXT (GLuint index, GLuint x, GLuint y, GLuint z); +GLAPI void APIENTRY glVertexAttribI4uiEXT (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glVertexAttribI1ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI2ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI3ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI4ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI1uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI2uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI3uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4bvEXT (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttribI4svEXT (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttribI4ubvEXT (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribI4usvEXT (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribIPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribIivEXT (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribIuivEXT (GLuint index, GLenum pname, GLuint *params); +#endif +#endif /* GL_EXT_gpu_shader4 */ + +#ifndef GL_EXT_histogram +#define GL_EXT_histogram 1 +#define GL_HISTOGRAM_EXT 0x8024 +#define GL_PROXY_HISTOGRAM_EXT 0x8025 +#define GL_HISTOGRAM_WIDTH_EXT 0x8026 +#define GL_HISTOGRAM_FORMAT_EXT 0x8027 +#define GL_HISTOGRAM_RED_SIZE_EXT 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE_EXT 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE_EXT 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE_EXT 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT 0x802C +#define GL_HISTOGRAM_SINK_EXT 0x802D +#define GL_MINMAX_EXT 0x802E +#define GL_MINMAX_FORMAT_EXT 0x802F +#define GL_MINMAX_SINK_EXT 0x8030 +#define GL_TABLE_TOO_LARGE_EXT 0x8031 +typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target); +typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetHistogramEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMinmaxEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glHistogramEXT (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glMinmaxEXT (GLenum target, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glResetHistogramEXT (GLenum target); +GLAPI void APIENTRY glResetMinmaxEXT (GLenum target); +#endif +#endif /* GL_EXT_histogram */ + +#ifndef GL_EXT_index_array_formats +#define GL_EXT_index_array_formats 1 +#define GL_IUI_V2F_EXT 0x81AD +#define GL_IUI_V3F_EXT 0x81AE +#define GL_IUI_N3F_V2F_EXT 0x81AF +#define GL_IUI_N3F_V3F_EXT 0x81B0 +#define GL_T2F_IUI_V2F_EXT 0x81B1 +#define GL_T2F_IUI_V3F_EXT 0x81B2 +#define GL_T2F_IUI_N3F_V2F_EXT 0x81B3 +#define GL_T2F_IUI_N3F_V3F_EXT 0x81B4 +#endif /* GL_EXT_index_array_formats */ + +#ifndef GL_EXT_index_func +#define GL_EXT_index_func 1 +#define GL_INDEX_TEST_EXT 0x81B5 +#define GL_INDEX_TEST_FUNC_EXT 0x81B6 +#define GL_INDEX_TEST_REF_EXT 0x81B7 +typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIndexFuncEXT (GLenum func, GLclampf ref); +#endif +#endif /* GL_EXT_index_func */ + +#ifndef GL_EXT_index_material +#define GL_EXT_index_material 1 +#define GL_INDEX_MATERIAL_EXT 0x81B8 +#define GL_INDEX_MATERIAL_PARAMETER_EXT 0x81B9 +#define GL_INDEX_MATERIAL_FACE_EXT 0x81BA +typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIndexMaterialEXT (GLenum face, GLenum mode); +#endif +#endif /* GL_EXT_index_material */ + +#ifndef GL_EXT_index_texture +#define GL_EXT_index_texture 1 +#endif /* GL_EXT_index_texture */ + +#ifndef GL_EXT_light_texture +#define GL_EXT_light_texture 1 +#define GL_FRAGMENT_MATERIAL_EXT 0x8349 +#define GL_FRAGMENT_NORMAL_EXT 0x834A +#define GL_FRAGMENT_COLOR_EXT 0x834C +#define GL_ATTENUATION_EXT 0x834D +#define GL_SHADOW_ATTENUATION_EXT 0x834E +#define GL_TEXTURE_APPLICATION_MODE_EXT 0x834F +#define GL_TEXTURE_LIGHT_EXT 0x8350 +#define GL_TEXTURE_MATERIAL_FACE_EXT 0x8351 +#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352 +typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname); +typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glApplyTextureEXT (GLenum mode); +GLAPI void APIENTRY glTextureLightEXT (GLenum pname); +GLAPI void APIENTRY glTextureMaterialEXT (GLenum face, GLenum mode); +#endif +#endif /* GL_EXT_light_texture */ + +#ifndef GL_EXT_memory_object +#define GL_EXT_memory_object 1 +#define GL_TEXTURE_TILING_EXT 0x9580 +#define GL_DEDICATED_MEMORY_OBJECT_EXT 0x9581 +#define GL_PROTECTED_MEMORY_OBJECT_EXT 0x959B +#define GL_NUM_TILING_TYPES_EXT 0x9582 +#define GL_TILING_TYPES_EXT 0x9583 +#define GL_OPTIMAL_TILING_EXT 0x9584 +#define GL_LINEAR_TILING_EXT 0x9585 +#define GL_NUM_DEVICE_UUIDS_EXT 0x9596 +#define GL_DEVICE_UUID_EXT 0x9597 +#define GL_DRIVER_UUID_EXT 0x9598 +#define GL_UUID_SIZE_EXT 16 +typedef void (APIENTRYP PFNGLGETUNSIGNEDBYTEVEXTPROC) (GLenum pname, GLubyte *data); +typedef void (APIENTRYP PFNGLGETUNSIGNEDBYTEI_VEXTPROC) (GLenum target, GLuint index, GLubyte *data); +typedef void (APIENTRYP PFNGLDELETEMEMORYOBJECTSEXTPROC) (GLsizei n, const GLuint *memoryObjects); +typedef GLboolean (APIENTRYP PFNGLISMEMORYOBJECTEXTPROC) (GLuint memoryObject); +typedef void (APIENTRYP PFNGLCREATEMEMORYOBJECTSEXTPROC) (GLsizei n, GLuint *memoryObjects); +typedef void (APIENTRYP PFNGLMEMORYOBJECTPARAMETERIVEXTPROC) (GLuint memoryObject, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETMEMORYOBJECTPARAMETERIVEXTPROC) (GLuint memoryObject, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLTEXSTORAGEMEM2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXSTORAGEMEM2DMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXSTORAGEMEM3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXSTORAGEMEM3DMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLBUFFERSTORAGEMEMEXTPROC) (GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXTURESTORAGEMEM2DEXTPROC) (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXTURESTORAGEMEM2DMULTISAMPLEEXTPROC) (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXTURESTORAGEMEM3DEXTPROC) (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXTURESTORAGEMEM3DMULTISAMPLEEXTPROC) (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEMEMEXTPROC) (GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXSTORAGEMEM1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXTURESTORAGEMEM1DEXTPROC) (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetUnsignedBytevEXT (GLenum pname, GLubyte *data); +GLAPI void APIENTRY glGetUnsignedBytei_vEXT (GLenum target, GLuint index, GLubyte *data); +GLAPI void APIENTRY glDeleteMemoryObjectsEXT (GLsizei n, const GLuint *memoryObjects); +GLAPI GLboolean APIENTRY glIsMemoryObjectEXT (GLuint memoryObject); +GLAPI void APIENTRY glCreateMemoryObjectsEXT (GLsizei n, GLuint *memoryObjects); +GLAPI void APIENTRY glMemoryObjectParameterivEXT (GLuint memoryObject, GLenum pname, const GLint *params); +GLAPI void APIENTRY glGetMemoryObjectParameterivEXT (GLuint memoryObject, GLenum pname, GLint *params); +GLAPI void APIENTRY glTexStorageMem2DEXT (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTexStorageMem2DMultisampleEXT (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTexStorageMem3DEXT (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTexStorageMem3DMultisampleEXT (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glBufferStorageMemEXT (GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTextureStorageMem2DEXT (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTextureStorageMem2DMultisampleEXT (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTextureStorageMem3DEXT (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTextureStorageMem3DMultisampleEXT (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glNamedBufferStorageMemEXT (GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTexStorageMem1DEXT (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTextureStorageMem1DEXT (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); +#endif +#endif /* GL_EXT_memory_object */ + +#ifndef GL_EXT_memory_object_fd +#define GL_EXT_memory_object_fd 1 +#define GL_HANDLE_TYPE_OPAQUE_FD_EXT 0x9586 +typedef void (APIENTRYP PFNGLIMPORTMEMORYFDEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, GLint fd); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glImportMemoryFdEXT (GLuint memory, GLuint64 size, GLenum handleType, GLint fd); +#endif +#endif /* GL_EXT_memory_object_fd */ + +#ifndef GL_EXT_memory_object_win32 +#define GL_EXT_memory_object_win32 1 +#define GL_HANDLE_TYPE_OPAQUE_WIN32_EXT 0x9587 +#define GL_HANDLE_TYPE_OPAQUE_WIN32_KMT_EXT 0x9588 +#define GL_DEVICE_LUID_EXT 0x9599 +#define GL_DEVICE_NODE_MASK_EXT 0x959A +#define GL_LUID_SIZE_EXT 8 +#define GL_HANDLE_TYPE_D3D12_TILEPOOL_EXT 0x9589 +#define GL_HANDLE_TYPE_D3D12_RESOURCE_EXT 0x958A +#define GL_HANDLE_TYPE_D3D11_IMAGE_EXT 0x958B +#define GL_HANDLE_TYPE_D3D11_IMAGE_KMT_EXT 0x958C +typedef void (APIENTRYP PFNGLIMPORTMEMORYWIN32HANDLEEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, void *handle); +typedef void (APIENTRYP PFNGLIMPORTMEMORYWIN32NAMEEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, const void *name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glImportMemoryWin32HandleEXT (GLuint memory, GLuint64 size, GLenum handleType, void *handle); +GLAPI void APIENTRY glImportMemoryWin32NameEXT (GLuint memory, GLuint64 size, GLenum handleType, const void *name); +#endif +#endif /* GL_EXT_memory_object_win32 */ + +#ifndef GL_EXT_misc_attribute +#define GL_EXT_misc_attribute 1 +#endif /* GL_EXT_misc_attribute */ + +#ifndef GL_EXT_multi_draw_arrays +#define GL_EXT_multi_draw_arrays 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); +#endif +#endif /* GL_EXT_multi_draw_arrays */ + +#ifndef GL_EXT_multisample +#define GL_EXT_multisample 1 +#define GL_MULTISAMPLE_EXT 0x809D +#define GL_SAMPLE_ALPHA_TO_MASK_EXT 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F +#define GL_SAMPLE_MASK_EXT 0x80A0 +#define GL_1PASS_EXT 0x80A1 +#define GL_2PASS_0_EXT 0x80A2 +#define GL_2PASS_1_EXT 0x80A3 +#define GL_4PASS_0_EXT 0x80A4 +#define GL_4PASS_1_EXT 0x80A5 +#define GL_4PASS_2_EXT 0x80A6 +#define GL_4PASS_3_EXT 0x80A7 +#define GL_SAMPLE_BUFFERS_EXT 0x80A8 +#define GL_SAMPLES_EXT 0x80A9 +#define GL_SAMPLE_MASK_VALUE_EXT 0x80AA +#define GL_SAMPLE_MASK_INVERT_EXT 0x80AB +#define GL_SAMPLE_PATTERN_EXT 0x80AC +#define GL_MULTISAMPLE_BIT_EXT 0x20000000 +typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleMaskEXT (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glSamplePatternEXT (GLenum pattern); +#endif +#endif /* GL_EXT_multisample */ + +#ifndef GL_EXT_multiview_tessellation_geometry_shader +#define GL_EXT_multiview_tessellation_geometry_shader 1 +#endif /* GL_EXT_multiview_tessellation_geometry_shader */ + +#ifndef GL_EXT_multiview_texture_multisample +#define GL_EXT_multiview_texture_multisample 1 +#endif /* GL_EXT_multiview_texture_multisample */ + +#ifndef GL_EXT_multiview_timer_query +#define GL_EXT_multiview_timer_query 1 +#endif /* GL_EXT_multiview_timer_query */ + +#ifndef GL_EXT_packed_depth_stencil +#define GL_EXT_packed_depth_stencil 1 +#define GL_DEPTH_STENCIL_EXT 0x84F9 +#define GL_UNSIGNED_INT_24_8_EXT 0x84FA +#define GL_DEPTH24_STENCIL8_EXT 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE_EXT 0x88F1 +#endif /* GL_EXT_packed_depth_stencil */ + +#ifndef GL_EXT_packed_float +#define GL_EXT_packed_float 1 +#define GL_R11F_G11F_B10F_EXT 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV_EXT 0x8C3B +#define GL_RGBA_SIGNED_COMPONENTS_EXT 0x8C3C +#endif /* GL_EXT_packed_float */ + +#ifndef GL_EXT_packed_pixels +#define GL_EXT_packed_pixels 1 +#define GL_UNSIGNED_BYTE_3_3_2_EXT 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4_EXT 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1_EXT 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8_EXT 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2_EXT 0x8036 +#endif /* GL_EXT_packed_pixels */ + +#ifndef GL_EXT_paletted_texture +#define GL_EXT_paletted_texture 1 +#define GL_COLOR_INDEX1_EXT 0x80E2 +#define GL_COLOR_INDEX2_EXT 0x80E3 +#define GL_COLOR_INDEX4_EXT 0x80E4 +#define GL_COLOR_INDEX8_EXT 0x80E5 +#define GL_COLOR_INDEX12_EXT 0x80E6 +#define GL_COLOR_INDEX16_EXT 0x80E7 +#define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED +typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, void *data); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTableEXT (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glGetColorTableEXT (GLenum target, GLenum format, GLenum type, void *data); +GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_paletted_texture */ + +#ifndef GL_EXT_pixel_buffer_object +#define GL_EXT_pixel_buffer_object 1 +#define GL_PIXEL_PACK_BUFFER_EXT 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_EXT 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_EXT 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF +#endif /* GL_EXT_pixel_buffer_object */ + +#ifndef GL_EXT_pixel_transform +#define GL_EXT_pixel_transform 1 +#define GL_PIXEL_TRANSFORM_2D_EXT 0x8330 +#define GL_PIXEL_MAG_FILTER_EXT 0x8331 +#define GL_PIXEL_MIN_FILTER_EXT 0x8332 +#define GL_PIXEL_CUBIC_WEIGHT_EXT 0x8333 +#define GL_CUBIC_EXT 0x8334 +#define GL_AVERAGE_EXT 0x8335 +#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336 +#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337 +#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT 0x8338 +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetPixelTransformParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetPixelTransformParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_pixel_transform */ + +#ifndef GL_EXT_pixel_transform_color_table +#define GL_EXT_pixel_transform_color_table 1 +#endif /* GL_EXT_pixel_transform_color_table */ + +#ifndef GL_EXT_point_parameters +#define GL_EXT_point_parameters 1 +#define GL_POINT_SIZE_MIN_EXT 0x8126 +#define GL_POINT_SIZE_MAX_EXT 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128 +#define GL_DISTANCE_ATTENUATION_EXT 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfEXT (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvEXT (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_EXT_point_parameters */ + +#ifndef GL_EXT_polygon_offset +#define GL_EXT_polygon_offset 1 +#define GL_POLYGON_OFFSET_EXT 0x8037 +#define GL_POLYGON_OFFSET_FACTOR_EXT 0x8038 +#define GL_POLYGON_OFFSET_BIAS_EXT 0x8039 +typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat factor, GLfloat bias); +#endif +#endif /* GL_EXT_polygon_offset */ + +#ifndef GL_EXT_polygon_offset_clamp +#define GL_EXT_polygon_offset_clamp 1 +#define GL_POLYGON_OFFSET_CLAMP_EXT 0x8E1B +typedef void (APIENTRYP PFNGLPOLYGONOFFSETCLAMPEXTPROC) (GLfloat factor, GLfloat units, GLfloat clamp); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPolygonOffsetClampEXT (GLfloat factor, GLfloat units, GLfloat clamp); +#endif +#endif /* GL_EXT_polygon_offset_clamp */ + +#ifndef GL_EXT_post_depth_coverage +#define GL_EXT_post_depth_coverage 1 +#endif /* GL_EXT_post_depth_coverage */ + +#ifndef GL_EXT_provoking_vertex +#define GL_EXT_provoking_vertex 1 +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION_EXT 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION_EXT 0x8E4D +#define GL_LAST_VERTEX_CONVENTION_EXT 0x8E4E +#define GL_PROVOKING_VERTEX_EXT 0x8E4F +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProvokingVertexEXT (GLenum mode); +#endif +#endif /* GL_EXT_provoking_vertex */ + +#ifndef GL_EXT_raster_multisample +#define GL_EXT_raster_multisample 1 +#define GL_RASTER_MULTISAMPLE_EXT 0x9327 +#define GL_RASTER_SAMPLES_EXT 0x9328 +#define GL_MAX_RASTER_SAMPLES_EXT 0x9329 +#define GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT 0x932A +#define GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT 0x932B +#define GL_EFFECTIVE_RASTER_SAMPLES_EXT 0x932C +typedef void (APIENTRYP PFNGLRASTERSAMPLESEXTPROC) (GLuint samples, GLboolean fixedsamplelocations); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRasterSamplesEXT (GLuint samples, GLboolean fixedsamplelocations); +#endif +#endif /* GL_EXT_raster_multisample */ + +#ifndef GL_EXT_rescale_normal +#define GL_EXT_rescale_normal 1 +#define GL_RESCALE_NORMAL_EXT 0x803A +#endif /* GL_EXT_rescale_normal */ + +#ifndef GL_EXT_secondary_color +#define GL_EXT_secondary_color 1 +#define GL_COLOR_SUM_EXT 0x8458 +#define GL_CURRENT_SECONDARY_COLOR_EXT 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D +#define GL_SECONDARY_COLOR_ARRAY_EXT 0x845E +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte red, GLbyte green, GLbyte blue); +GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble red, GLdouble green, GLdouble blue); +GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat red, GLfloat green, GLfloat blue); +GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glSecondaryColor3iEXT (GLint red, GLint green, GLint blue); +GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *v); +GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort red, GLshort green, GLshort blue); +GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *v); +GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte red, GLubyte green, GLubyte blue); +GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *v); +GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint red, GLuint green, GLuint blue); +GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *v); +GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort red, GLushort green, GLushort blue); +GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *v); +GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_secondary_color */ + +#ifndef GL_EXT_semaphore +#define GL_EXT_semaphore 1 +#define GL_LAYOUT_GENERAL_EXT 0x958D +#define GL_LAYOUT_COLOR_ATTACHMENT_EXT 0x958E +#define GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT 0x958F +#define GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT 0x9590 +#define GL_LAYOUT_SHADER_READ_ONLY_EXT 0x9591 +#define GL_LAYOUT_TRANSFER_SRC_EXT 0x9592 +#define GL_LAYOUT_TRANSFER_DST_EXT 0x9593 +#define GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT 0x9530 +#define GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT 0x9531 +typedef void (APIENTRYP PFNGLGENSEMAPHORESEXTPROC) (GLsizei n, GLuint *semaphores); +typedef void (APIENTRYP PFNGLDELETESEMAPHORESEXTPROC) (GLsizei n, const GLuint *semaphores); +typedef GLboolean (APIENTRYP PFNGLISSEMAPHOREEXTPROC) (GLuint semaphore); +typedef void (APIENTRYP PFNGLSEMAPHOREPARAMETERUI64VEXTPROC) (GLuint semaphore, GLenum pname, const GLuint64 *params); +typedef void (APIENTRYP PFNGLGETSEMAPHOREPARAMETERUI64VEXTPROC) (GLuint semaphore, GLenum pname, GLuint64 *params); +typedef void (APIENTRYP PFNGLWAITSEMAPHOREEXTPROC) (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts); +typedef void (APIENTRYP PFNGLSIGNALSEMAPHOREEXTPROC) (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenSemaphoresEXT (GLsizei n, GLuint *semaphores); +GLAPI void APIENTRY glDeleteSemaphoresEXT (GLsizei n, const GLuint *semaphores); +GLAPI GLboolean APIENTRY glIsSemaphoreEXT (GLuint semaphore); +GLAPI void APIENTRY glSemaphoreParameterui64vEXT (GLuint semaphore, GLenum pname, const GLuint64 *params); +GLAPI void APIENTRY glGetSemaphoreParameterui64vEXT (GLuint semaphore, GLenum pname, GLuint64 *params); +GLAPI void APIENTRY glWaitSemaphoreEXT (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts); +GLAPI void APIENTRY glSignalSemaphoreEXT (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts); +#endif +#endif /* GL_EXT_semaphore */ + +#ifndef GL_EXT_semaphore_fd +#define GL_EXT_semaphore_fd 1 +typedef void (APIENTRYP PFNGLIMPORTSEMAPHOREFDEXTPROC) (GLuint semaphore, GLenum handleType, GLint fd); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glImportSemaphoreFdEXT (GLuint semaphore, GLenum handleType, GLint fd); +#endif +#endif /* GL_EXT_semaphore_fd */ + +#ifndef GL_EXT_semaphore_win32 +#define GL_EXT_semaphore_win32 1 +#define GL_HANDLE_TYPE_D3D12_FENCE_EXT 0x9594 +#define GL_D3D12_FENCE_VALUE_EXT 0x9595 +typedef void (APIENTRYP PFNGLIMPORTSEMAPHOREWIN32HANDLEEXTPROC) (GLuint semaphore, GLenum handleType, void *handle); +typedef void (APIENTRYP PFNGLIMPORTSEMAPHOREWIN32NAMEEXTPROC) (GLuint semaphore, GLenum handleType, const void *name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glImportSemaphoreWin32HandleEXT (GLuint semaphore, GLenum handleType, void *handle); +GLAPI void APIENTRY glImportSemaphoreWin32NameEXT (GLuint semaphore, GLenum handleType, const void *name); +#endif +#endif /* GL_EXT_semaphore_win32 */ + +#ifndef GL_EXT_separate_shader_objects +#define GL_EXT_separate_shader_objects 1 +#define GL_ACTIVE_PROGRAM_EXT 0x8B8D +typedef void (APIENTRYP PFNGLUSESHADERPROGRAMEXTPROC) (GLenum type, GLuint program); +typedef void (APIENTRYP PFNGLACTIVEPROGRAMEXTPROC) (GLuint program); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMEXTPROC) (GLenum type, const GLchar *string); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUseShaderProgramEXT (GLenum type, GLuint program); +GLAPI void APIENTRY glActiveProgramEXT (GLuint program); +GLAPI GLuint APIENTRY glCreateShaderProgramEXT (GLenum type, const GLchar *string); +#endif +#endif /* GL_EXT_separate_shader_objects */ + +#ifndef GL_EXT_separate_specular_color +#define GL_EXT_separate_specular_color 1 +#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT 0x81F8 +#define GL_SINGLE_COLOR_EXT 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR_EXT 0x81FA +#endif /* GL_EXT_separate_specular_color */ + +#ifndef GL_EXT_shader_framebuffer_fetch +#define GL_EXT_shader_framebuffer_fetch 1 +#define GL_FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT 0x8A52 +#endif /* GL_EXT_shader_framebuffer_fetch */ + +#ifndef GL_EXT_shader_framebuffer_fetch_non_coherent +#define GL_EXT_shader_framebuffer_fetch_non_coherent 1 +typedef void (APIENTRYP PFNGLFRAMEBUFFERFETCHBARRIEREXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferFetchBarrierEXT (void); +#endif +#endif /* GL_EXT_shader_framebuffer_fetch_non_coherent */ + +#ifndef GL_EXT_shader_image_load_formatted +#define GL_EXT_shader_image_load_formatted 1 +#endif /* GL_EXT_shader_image_load_formatted */ + +#ifndef GL_EXT_shader_image_load_store +#define GL_EXT_shader_image_load_store 1 +#define GL_MAX_IMAGE_UNITS_EXT 0x8F38 +#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS_EXT 0x8F39 +#define GL_IMAGE_BINDING_NAME_EXT 0x8F3A +#define GL_IMAGE_BINDING_LEVEL_EXT 0x8F3B +#define GL_IMAGE_BINDING_LAYERED_EXT 0x8F3C +#define GL_IMAGE_BINDING_LAYER_EXT 0x8F3D +#define GL_IMAGE_BINDING_ACCESS_EXT 0x8F3E +#define GL_IMAGE_1D_EXT 0x904C +#define GL_IMAGE_2D_EXT 0x904D +#define GL_IMAGE_3D_EXT 0x904E +#define GL_IMAGE_2D_RECT_EXT 0x904F +#define GL_IMAGE_CUBE_EXT 0x9050 +#define GL_IMAGE_BUFFER_EXT 0x9051 +#define GL_IMAGE_1D_ARRAY_EXT 0x9052 +#define GL_IMAGE_2D_ARRAY_EXT 0x9053 +#define GL_IMAGE_CUBE_MAP_ARRAY_EXT 0x9054 +#define GL_IMAGE_2D_MULTISAMPLE_EXT 0x9055 +#define GL_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9056 +#define GL_INT_IMAGE_1D_EXT 0x9057 +#define GL_INT_IMAGE_2D_EXT 0x9058 +#define GL_INT_IMAGE_3D_EXT 0x9059 +#define GL_INT_IMAGE_2D_RECT_EXT 0x905A +#define GL_INT_IMAGE_CUBE_EXT 0x905B +#define GL_INT_IMAGE_BUFFER_EXT 0x905C +#define GL_INT_IMAGE_1D_ARRAY_EXT 0x905D +#define GL_INT_IMAGE_2D_ARRAY_EXT 0x905E +#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x905F +#define GL_INT_IMAGE_2D_MULTISAMPLE_EXT 0x9060 +#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9061 +#define GL_UNSIGNED_INT_IMAGE_1D_EXT 0x9062 +#define GL_UNSIGNED_INT_IMAGE_2D_EXT 0x9063 +#define GL_UNSIGNED_INT_IMAGE_3D_EXT 0x9064 +#define GL_UNSIGNED_INT_IMAGE_2D_RECT_EXT 0x9065 +#define GL_UNSIGNED_INT_IMAGE_CUBE_EXT 0x9066 +#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT 0x9067 +#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY_EXT 0x9068 +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY_EXT 0x9069 +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_EXT 0x906B +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x906C +#define GL_MAX_IMAGE_SAMPLES_EXT 0x906D +#define GL_IMAGE_BINDING_FORMAT_EXT 0x906E +#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT_EXT 0x00000001 +#define GL_ELEMENT_ARRAY_BARRIER_BIT_EXT 0x00000002 +#define GL_UNIFORM_BARRIER_BIT_EXT 0x00000004 +#define GL_TEXTURE_FETCH_BARRIER_BIT_EXT 0x00000008 +#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT_EXT 0x00000020 +#define GL_COMMAND_BARRIER_BIT_EXT 0x00000040 +#define GL_PIXEL_BUFFER_BARRIER_BIT_EXT 0x00000080 +#define GL_TEXTURE_UPDATE_BARRIER_BIT_EXT 0x00000100 +#define GL_BUFFER_UPDATE_BARRIER_BIT_EXT 0x00000200 +#define GL_FRAMEBUFFER_BARRIER_BIT_EXT 0x00000400 +#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT_EXT 0x00000800 +#define GL_ATOMIC_COUNTER_BARRIER_BIT_EXT 0x00001000 +#define GL_ALL_BARRIER_BITS_EXT 0xFFFFFFFF +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREEXTPROC) (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format); +typedef void (APIENTRYP PFNGLMEMORYBARRIEREXTPROC) (GLbitfield barriers); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindImageTextureEXT (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format); +GLAPI void APIENTRY glMemoryBarrierEXT (GLbitfield barriers); +#endif +#endif /* GL_EXT_shader_image_load_store */ + +#ifndef GL_EXT_shader_integer_mix +#define GL_EXT_shader_integer_mix 1 +#endif /* GL_EXT_shader_integer_mix */ + +#ifndef GL_EXT_shader_samples_identical +#define GL_EXT_shader_samples_identical 1 +#endif /* GL_EXT_shader_samples_identical */ + +#ifndef GL_EXT_shadow_funcs +#define GL_EXT_shadow_funcs 1 +#endif /* GL_EXT_shadow_funcs */ + +#ifndef GL_EXT_shared_texture_palette +#define GL_EXT_shared_texture_palette 1 +#define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB +#endif /* GL_EXT_shared_texture_palette */ + +#ifndef GL_EXT_sparse_texture2 +#define GL_EXT_sparse_texture2 1 +#endif /* GL_EXT_sparse_texture2 */ + +#ifndef GL_EXT_stencil_clear_tag +#define GL_EXT_stencil_clear_tag 1 +#define GL_STENCIL_TAG_BITS_EXT 0x88F2 +#define GL_STENCIL_CLEAR_TAG_VALUE_EXT 0x88F3 +typedef void (APIENTRYP PFNGLSTENCILCLEARTAGEXTPROC) (GLsizei stencilTagBits, GLuint stencilClearTag); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilClearTagEXT (GLsizei stencilTagBits, GLuint stencilClearTag); +#endif +#endif /* GL_EXT_stencil_clear_tag */ + +#ifndef GL_EXT_stencil_two_side +#define GL_EXT_stencil_two_side 1 +#define GL_STENCIL_TEST_TWO_SIDE_EXT 0x8910 +#define GL_ACTIVE_STENCIL_FACE_EXT 0x8911 +typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum face); +#endif +#endif /* GL_EXT_stencil_two_side */ + +#ifndef GL_EXT_stencil_wrap +#define GL_EXT_stencil_wrap 1 +#define GL_INCR_WRAP_EXT 0x8507 +#define GL_DECR_WRAP_EXT 0x8508 +#endif /* GL_EXT_stencil_wrap */ + +#ifndef GL_EXT_subtexture +#define GL_EXT_subtexture 1 +typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_EXT_subtexture */ + +#ifndef GL_EXT_texture +#define GL_EXT_texture 1 +#define GL_ALPHA4_EXT 0x803B +#define GL_ALPHA8_EXT 0x803C +#define GL_ALPHA12_EXT 0x803D +#define GL_ALPHA16_EXT 0x803E +#define GL_LUMINANCE4_EXT 0x803F +#define GL_LUMINANCE8_EXT 0x8040 +#define GL_LUMINANCE12_EXT 0x8041 +#define GL_LUMINANCE16_EXT 0x8042 +#define GL_LUMINANCE4_ALPHA4_EXT 0x8043 +#define GL_LUMINANCE6_ALPHA2_EXT 0x8044 +#define GL_LUMINANCE8_ALPHA8_EXT 0x8045 +#define GL_LUMINANCE12_ALPHA4_EXT 0x8046 +#define GL_LUMINANCE12_ALPHA12_EXT 0x8047 +#define GL_LUMINANCE16_ALPHA16_EXT 0x8048 +#define GL_INTENSITY_EXT 0x8049 +#define GL_INTENSITY4_EXT 0x804A +#define GL_INTENSITY8_EXT 0x804B +#define GL_INTENSITY12_EXT 0x804C +#define GL_INTENSITY16_EXT 0x804D +#define GL_RGB2_EXT 0x804E +#define GL_RGB4_EXT 0x804F +#define GL_RGB5_EXT 0x8050 +#define GL_RGB8_EXT 0x8051 +#define GL_RGB10_EXT 0x8052 +#define GL_RGB12_EXT 0x8053 +#define GL_RGB16_EXT 0x8054 +#define GL_RGBA2_EXT 0x8055 +#define GL_RGBA4_EXT 0x8056 +#define GL_RGB5_A1_EXT 0x8057 +#define GL_RGBA8_EXT 0x8058 +#define GL_RGB10_A2_EXT 0x8059 +#define GL_RGBA12_EXT 0x805A +#define GL_RGBA16_EXT 0x805B +#define GL_TEXTURE_RED_SIZE_EXT 0x805C +#define GL_TEXTURE_GREEN_SIZE_EXT 0x805D +#define GL_TEXTURE_BLUE_SIZE_EXT 0x805E +#define GL_TEXTURE_ALPHA_SIZE_EXT 0x805F +#define GL_TEXTURE_LUMINANCE_SIZE_EXT 0x8060 +#define GL_TEXTURE_INTENSITY_SIZE_EXT 0x8061 +#define GL_REPLACE_EXT 0x8062 +#define GL_PROXY_TEXTURE_1D_EXT 0x8063 +#define GL_PROXY_TEXTURE_2D_EXT 0x8064 +#define GL_TEXTURE_TOO_LARGE_EXT 0x8065 +#endif /* GL_EXT_texture */ + +#ifndef GL_EXT_texture3D +#define GL_EXT_texture3D 1 +#define GL_PACK_SKIP_IMAGES_EXT 0x806B +#define GL_PACK_IMAGE_HEIGHT_EXT 0x806C +#define GL_UNPACK_SKIP_IMAGES_EXT 0x806D +#define GL_UNPACK_IMAGE_HEIGHT_EXT 0x806E +#define GL_TEXTURE_3D_EXT 0x806F +#define GL_PROXY_TEXTURE_3D_EXT 0x8070 +#define GL_TEXTURE_DEPTH_EXT 0x8071 +#define GL_TEXTURE_WRAP_R_EXT 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE_EXT 0x8073 +typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage3DEXT (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_EXT_texture3D */ + +#ifndef GL_EXT_texture_array +#define GL_EXT_texture_array 1 +#define GL_TEXTURE_1D_ARRAY_EXT 0x8C18 +#define GL_PROXY_TEXTURE_1D_ARRAY_EXT 0x8C19 +#define GL_TEXTURE_2D_ARRAY_EXT 0x8C1A +#define GL_PROXY_TEXTURE_2D_ARRAY_EXT 0x8C1B +#define GL_TEXTURE_BINDING_1D_ARRAY_EXT 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY_EXT 0x8C1D +#define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT 0x88FF +#define GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT 0x884E +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferTextureLayerEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +#endif +#endif /* GL_EXT_texture_array */ + +#ifndef GL_EXT_texture_buffer_object +#define GL_EXT_texture_buffer_object 1 +#define GL_TEXTURE_BUFFER_EXT 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE_EXT 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER_EXT 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT 0x8C2D +#define GL_TEXTURE_BUFFER_FORMAT_EXT 0x8C2E +typedef void (APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer); +#endif +#endif /* GL_EXT_texture_buffer_object */ + +#ifndef GL_EXT_texture_compression_latc +#define GL_EXT_texture_compression_latc 1 +#define GL_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70 +#define GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71 +#define GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72 +#define GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73 +#endif /* GL_EXT_texture_compression_latc */ + +#ifndef GL_EXT_texture_compression_rgtc +#define GL_EXT_texture_compression_rgtc 1 +#define GL_COMPRESSED_RED_RGTC1_EXT 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC +#define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD +#define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE +#endif /* GL_EXT_texture_compression_rgtc */ + +#ifndef GL_EXT_texture_compression_s3tc +#define GL_EXT_texture_compression_s3tc 1 +#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 +#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 +#endif /* GL_EXT_texture_compression_s3tc */ + +#ifndef GL_EXT_texture_cube_map +#define GL_EXT_texture_cube_map 1 +#define GL_NORMAL_MAP_EXT 0x8511 +#define GL_REFLECTION_MAP_EXT 0x8512 +#define GL_TEXTURE_CUBE_MAP_EXT 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_EXT 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP_EXT 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT 0x851C +#endif /* GL_EXT_texture_cube_map */ + +#ifndef GL_EXT_texture_env_add +#define GL_EXT_texture_env_add 1 +#endif /* GL_EXT_texture_env_add */ + +#ifndef GL_EXT_texture_env_combine +#define GL_EXT_texture_env_combine 1 +#define GL_COMBINE_EXT 0x8570 +#define GL_COMBINE_RGB_EXT 0x8571 +#define GL_COMBINE_ALPHA_EXT 0x8572 +#define GL_RGB_SCALE_EXT 0x8573 +#define GL_ADD_SIGNED_EXT 0x8574 +#define GL_INTERPOLATE_EXT 0x8575 +#define GL_CONSTANT_EXT 0x8576 +#define GL_PRIMARY_COLOR_EXT 0x8577 +#define GL_PREVIOUS_EXT 0x8578 +#define GL_SOURCE0_RGB_EXT 0x8580 +#define GL_SOURCE1_RGB_EXT 0x8581 +#define GL_SOURCE2_RGB_EXT 0x8582 +#define GL_SOURCE0_ALPHA_EXT 0x8588 +#define GL_SOURCE1_ALPHA_EXT 0x8589 +#define GL_SOURCE2_ALPHA_EXT 0x858A +#define GL_OPERAND0_RGB_EXT 0x8590 +#define GL_OPERAND1_RGB_EXT 0x8591 +#define GL_OPERAND2_RGB_EXT 0x8592 +#define GL_OPERAND0_ALPHA_EXT 0x8598 +#define GL_OPERAND1_ALPHA_EXT 0x8599 +#define GL_OPERAND2_ALPHA_EXT 0x859A +#endif /* GL_EXT_texture_env_combine */ + +#ifndef GL_EXT_texture_env_dot3 +#define GL_EXT_texture_env_dot3 1 +#define GL_DOT3_RGB_EXT 0x8740 +#define GL_DOT3_RGBA_EXT 0x8741 +#endif /* GL_EXT_texture_env_dot3 */ + +#ifndef GL_EXT_texture_filter_anisotropic +#define GL_EXT_texture_filter_anisotropic 1 +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#endif /* GL_EXT_texture_filter_anisotropic */ + +#ifndef GL_EXT_texture_filter_minmax +#define GL_EXT_texture_filter_minmax 1 +#define GL_TEXTURE_REDUCTION_MODE_EXT 0x9366 +#define GL_WEIGHTED_AVERAGE_EXT 0x9367 +#endif /* GL_EXT_texture_filter_minmax */ + +#ifndef GL_EXT_texture_integer +#define GL_EXT_texture_integer 1 +#define GL_RGBA32UI_EXT 0x8D70 +#define GL_RGB32UI_EXT 0x8D71 +#define GL_ALPHA32UI_EXT 0x8D72 +#define GL_INTENSITY32UI_EXT 0x8D73 +#define GL_LUMINANCE32UI_EXT 0x8D74 +#define GL_LUMINANCE_ALPHA32UI_EXT 0x8D75 +#define GL_RGBA16UI_EXT 0x8D76 +#define GL_RGB16UI_EXT 0x8D77 +#define GL_ALPHA16UI_EXT 0x8D78 +#define GL_INTENSITY16UI_EXT 0x8D79 +#define GL_LUMINANCE16UI_EXT 0x8D7A +#define GL_LUMINANCE_ALPHA16UI_EXT 0x8D7B +#define GL_RGBA8UI_EXT 0x8D7C +#define GL_RGB8UI_EXT 0x8D7D +#define GL_ALPHA8UI_EXT 0x8D7E +#define GL_INTENSITY8UI_EXT 0x8D7F +#define GL_LUMINANCE8UI_EXT 0x8D80 +#define GL_LUMINANCE_ALPHA8UI_EXT 0x8D81 +#define GL_RGBA32I_EXT 0x8D82 +#define GL_RGB32I_EXT 0x8D83 +#define GL_ALPHA32I_EXT 0x8D84 +#define GL_INTENSITY32I_EXT 0x8D85 +#define GL_LUMINANCE32I_EXT 0x8D86 +#define GL_LUMINANCE_ALPHA32I_EXT 0x8D87 +#define GL_RGBA16I_EXT 0x8D88 +#define GL_RGB16I_EXT 0x8D89 +#define GL_ALPHA16I_EXT 0x8D8A +#define GL_INTENSITY16I_EXT 0x8D8B +#define GL_LUMINANCE16I_EXT 0x8D8C +#define GL_LUMINANCE_ALPHA16I_EXT 0x8D8D +#define GL_RGBA8I_EXT 0x8D8E +#define GL_RGB8I_EXT 0x8D8F +#define GL_ALPHA8I_EXT 0x8D90 +#define GL_INTENSITY8I_EXT 0x8D91 +#define GL_LUMINANCE8I_EXT 0x8D92 +#define GL_LUMINANCE_ALPHA8I_EXT 0x8D93 +#define GL_RED_INTEGER_EXT 0x8D94 +#define GL_GREEN_INTEGER_EXT 0x8D95 +#define GL_BLUE_INTEGER_EXT 0x8D96 +#define GL_ALPHA_INTEGER_EXT 0x8D97 +#define GL_RGB_INTEGER_EXT 0x8D98 +#define GL_RGBA_INTEGER_EXT 0x8D99 +#define GL_BGR_INTEGER_EXT 0x8D9A +#define GL_BGRA_INTEGER_EXT 0x8D9B +#define GL_LUMINANCE_INTEGER_EXT 0x8D9C +#define GL_LUMINANCE_ALPHA_INTEGER_EXT 0x8D9D +#define GL_RGBA_INTEGER_MODE_EXT 0x8D9E +typedef void (APIENTRYP PFNGLTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLCLEARCOLORIIEXTPROC) (GLint red, GLint green, GLint blue, GLint alpha); +typedef void (APIENTRYP PFNGLCLEARCOLORIUIEXTPROC) (GLuint red, GLuint green, GLuint blue, GLuint alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glClearColorIiEXT (GLint red, GLint green, GLint blue, GLint alpha); +GLAPI void APIENTRY glClearColorIuiEXT (GLuint red, GLuint green, GLuint blue, GLuint alpha); +#endif +#endif /* GL_EXT_texture_integer */ + +#ifndef GL_EXT_texture_lod_bias +#define GL_EXT_texture_lod_bias 1 +#define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD +#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500 +#define GL_TEXTURE_LOD_BIAS_EXT 0x8501 +#endif /* GL_EXT_texture_lod_bias */ + +#ifndef GL_EXT_texture_mirror_clamp +#define GL_EXT_texture_mirror_clamp 1 +#define GL_MIRROR_CLAMP_EXT 0x8742 +#define GL_MIRROR_CLAMP_TO_EDGE_EXT 0x8743 +#define GL_MIRROR_CLAMP_TO_BORDER_EXT 0x8912 +#endif /* GL_EXT_texture_mirror_clamp */ + +#ifndef GL_EXT_texture_object +#define GL_EXT_texture_object 1 +#define GL_TEXTURE_PRIORITY_EXT 0x8066 +#define GL_TEXTURE_RESIDENT_EXT 0x8067 +#define GL_TEXTURE_1D_BINDING_EXT 0x8068 +#define GL_TEXTURE_2D_BINDING_EXT 0x8069 +#define GL_TEXTURE_3D_BINDING_EXT 0x806A +typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences); +typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures); +typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei n, const GLuint *textures, GLboolean *residences); +GLAPI void APIENTRY glBindTextureEXT (GLenum target, GLuint texture); +GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei n, const GLuint *textures); +GLAPI void APIENTRY glGenTexturesEXT (GLsizei n, GLuint *textures); +GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint texture); +GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei n, const GLuint *textures, const GLclampf *priorities); +#endif +#endif /* GL_EXT_texture_object */ + +#ifndef GL_EXT_texture_perturb_normal +#define GL_EXT_texture_perturb_normal 1 +#define GL_PERTURB_EXT 0x85AE +#define GL_TEXTURE_NORMAL_EXT 0x85AF +typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureNormalEXT (GLenum mode); +#endif +#endif /* GL_EXT_texture_perturb_normal */ + +#ifndef GL_EXT_texture_sRGB +#define GL_EXT_texture_sRGB 1 +#define GL_SRGB_EXT 0x8C40 +#define GL_SRGB8_EXT 0x8C41 +#define GL_SRGB_ALPHA_EXT 0x8C42 +#define GL_SRGB8_ALPHA8_EXT 0x8C43 +#define GL_SLUMINANCE_ALPHA_EXT 0x8C44 +#define GL_SLUMINANCE8_ALPHA8_EXT 0x8C45 +#define GL_SLUMINANCE_EXT 0x8C46 +#define GL_SLUMINANCE8_EXT 0x8C47 +#define GL_COMPRESSED_SRGB_EXT 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA_EXT 0x8C49 +#define GL_COMPRESSED_SLUMINANCE_EXT 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA_EXT 0x8C4B +#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F +#endif /* GL_EXT_texture_sRGB */ + +#ifndef GL_EXT_texture_sRGB_R8 +#define GL_EXT_texture_sRGB_R8 1 +#define GL_SR8_EXT 0x8FBD +#endif /* GL_EXT_texture_sRGB_R8 */ + +#ifndef GL_EXT_texture_sRGB_RG8 +#define GL_EXT_texture_sRGB_RG8 1 +#define GL_SRG8_EXT 0x8FBE +#endif /* GL_EXT_texture_sRGB_RG8 */ + +#ifndef GL_EXT_texture_sRGB_decode +#define GL_EXT_texture_sRGB_decode 1 +#define GL_TEXTURE_SRGB_DECODE_EXT 0x8A48 +#define GL_DECODE_EXT 0x8A49 +#define GL_SKIP_DECODE_EXT 0x8A4A +#endif /* GL_EXT_texture_sRGB_decode */ + +#ifndef GL_EXT_texture_shadow_lod +#define GL_EXT_texture_shadow_lod 1 +#endif /* GL_EXT_texture_shadow_lod */ + +#ifndef GL_EXT_texture_shared_exponent +#define GL_EXT_texture_shared_exponent 1 +#define GL_RGB9_E5_EXT 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV_EXT 0x8C3E +#define GL_TEXTURE_SHARED_SIZE_EXT 0x8C3F +#endif /* GL_EXT_texture_shared_exponent */ + +#ifndef GL_EXT_texture_snorm +#define GL_EXT_texture_snorm 1 +#define GL_ALPHA_SNORM 0x9010 +#define GL_LUMINANCE_SNORM 0x9011 +#define GL_LUMINANCE_ALPHA_SNORM 0x9012 +#define GL_INTENSITY_SNORM 0x9013 +#define GL_ALPHA8_SNORM 0x9014 +#define GL_LUMINANCE8_SNORM 0x9015 +#define GL_LUMINANCE8_ALPHA8_SNORM 0x9016 +#define GL_INTENSITY8_SNORM 0x9017 +#define GL_ALPHA16_SNORM 0x9018 +#define GL_LUMINANCE16_SNORM 0x9019 +#define GL_LUMINANCE16_ALPHA16_SNORM 0x901A +#define GL_INTENSITY16_SNORM 0x901B +#define GL_RED_SNORM 0x8F90 +#define GL_RG_SNORM 0x8F91 +#define GL_RGB_SNORM 0x8F92 +#define GL_RGBA_SNORM 0x8F93 +#endif /* GL_EXT_texture_snorm */ + +#ifndef GL_EXT_texture_storage +#define GL_EXT_texture_storage 1 +#define GL_TEXTURE_IMMUTABLE_FORMAT_EXT 0x912F +#define GL_RGBA32F_EXT 0x8814 +#define GL_RGB32F_EXT 0x8815 +#define GL_ALPHA32F_EXT 0x8816 +#define GL_LUMINANCE32F_EXT 0x8818 +#define GL_LUMINANCE_ALPHA32F_EXT 0x8819 +#define GL_RGBA16F_EXT 0x881A +#define GL_RGB16F_EXT 0x881B +#define GL_ALPHA16F_EXT 0x881C +#define GL_LUMINANCE16F_EXT 0x881E +#define GL_LUMINANCE_ALPHA16F_EXT 0x881F +#define GL_BGRA8_EXT 0x93A1 +#define GL_R8_EXT 0x8229 +#define GL_RG8_EXT 0x822B +#define GL_R32F_EXT 0x822E +#define GL_RG32F_EXT 0x8230 +#define GL_R16F_EXT 0x822D +#define GL_RG16F_EXT 0x822F +typedef void (APIENTRYP PFNGLTEXSTORAGE1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXSTORAGE2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXSTORAGE3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexStorage1DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTexStorage2DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTexStorage3DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +#endif +#endif /* GL_EXT_texture_storage */ + +#ifndef GL_EXT_texture_swizzle +#define GL_EXT_texture_swizzle 1 +#define GL_TEXTURE_SWIZZLE_R_EXT 0x8E42 +#define GL_TEXTURE_SWIZZLE_G_EXT 0x8E43 +#define GL_TEXTURE_SWIZZLE_B_EXT 0x8E44 +#define GL_TEXTURE_SWIZZLE_A_EXT 0x8E45 +#define GL_TEXTURE_SWIZZLE_RGBA_EXT 0x8E46 +#endif /* GL_EXT_texture_swizzle */ + +#ifndef GL_EXT_timer_query +#define GL_EXT_timer_query 1 +#define GL_TIME_ELAPSED_EXT 0x88BF +typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64 *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64 *params); +#endif +#endif /* GL_EXT_timer_query */ + +#ifndef GL_EXT_transform_feedback +#define GL_EXT_transform_feedback 1 +#define GL_TRANSFORM_FEEDBACK_BUFFER_EXT 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_START_EXT 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_EXT 0x8C85 +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_EXT 0x8C8F +#define GL_INTERLEAVED_ATTRIBS_EXT 0x8C8C +#define GL_SEPARATE_ATTRIBS_EXT 0x8C8D +#define GL_PRIMITIVES_GENERATED_EXT 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT 0x8C88 +#define GL_RASTERIZER_DISCARD_EXT 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_EXT 0x8C8B +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS_EXT 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_EXT 0x8C7F +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT 0x8C76 +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKEXTPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKEXTPROC) (void); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGEEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +typedef void (APIENTRYP PFNGLBINDBUFFERBASEEXTPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSEXTPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGEXTPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginTransformFeedbackEXT (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedbackEXT (void); +GLAPI void APIENTRY glBindBufferRangeEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferOffsetEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +GLAPI void APIENTRY glBindBufferBaseEXT (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryingsEXT (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +GLAPI void APIENTRY glGetTransformFeedbackVaryingEXT (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +#endif +#endif /* GL_EXT_transform_feedback */ + +#ifndef GL_EXT_vertex_array +#define GL_EXT_vertex_array 1 +#define GL_VERTEX_ARRAY_EXT 0x8074 +#define GL_NORMAL_ARRAY_EXT 0x8075 +#define GL_COLOR_ARRAY_EXT 0x8076 +#define GL_INDEX_ARRAY_EXT 0x8077 +#define GL_TEXTURE_COORD_ARRAY_EXT 0x8078 +#define GL_EDGE_FLAG_ARRAY_EXT 0x8079 +#define GL_VERTEX_ARRAY_SIZE_EXT 0x807A +#define GL_VERTEX_ARRAY_TYPE_EXT 0x807B +#define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C +#define GL_VERTEX_ARRAY_COUNT_EXT 0x807D +#define GL_NORMAL_ARRAY_TYPE_EXT 0x807E +#define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F +#define GL_NORMAL_ARRAY_COUNT_EXT 0x8080 +#define GL_COLOR_ARRAY_SIZE_EXT 0x8081 +#define GL_COLOR_ARRAY_TYPE_EXT 0x8082 +#define GL_COLOR_ARRAY_STRIDE_EXT 0x8083 +#define GL_COLOR_ARRAY_COUNT_EXT 0x8084 +#define GL_INDEX_ARRAY_TYPE_EXT 0x8085 +#define GL_INDEX_ARRAY_STRIDE_EXT 0x8086 +#define GL_INDEX_ARRAY_COUNT_EXT 0x8087 +#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A +#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B +#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C +#define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D +#define GL_VERTEX_ARRAY_POINTER_EXT 0x808E +#define GL_NORMAL_ARRAY_POINTER_EXT 0x808F +#define GL_COLOR_ARRAY_POINTER_EXT 0x8090 +#define GL_INDEX_ARRAY_POINTER_EXT 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093 +typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i); +typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer); +typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, void **params); +typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glArrayElementEXT (GLint i); +GLAPI void APIENTRY glColorPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glDrawArraysEXT (GLenum mode, GLint first, GLsizei count); +GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei stride, GLsizei count, const GLboolean *pointer); +GLAPI void APIENTRY glGetPointervEXT (GLenum pname, void **params); +GLAPI void APIENTRY glIndexPointerEXT (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glNormalPointerEXT (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glTexCoordPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glVertexPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +#endif +#endif /* GL_EXT_vertex_array */ + +#ifndef GL_EXT_vertex_array_bgra +#define GL_EXT_vertex_array_bgra 1 +#endif /* GL_EXT_vertex_array_bgra */ + +#ifndef GL_EXT_vertex_attrib_64bit +#define GL_EXT_vertex_attrib_64bit 1 +#define GL_DOUBLE_VEC2_EXT 0x8FFC +#define GL_DOUBLE_VEC3_EXT 0x8FFD +#define GL_DOUBLE_VEC4_EXT 0x8FFE +#define GL_DOUBLE_MAT2_EXT 0x8F46 +#define GL_DOUBLE_MAT3_EXT 0x8F47 +#define GL_DOUBLE_MAT4_EXT 0x8F48 +#define GL_DOUBLE_MAT2x3_EXT 0x8F49 +#define GL_DOUBLE_MAT2x4_EXT 0x8F4A +#define GL_DOUBLE_MAT3x2_EXT 0x8F4B +#define GL_DOUBLE_MAT3x4_EXT 0x8F4C +#define GL_DOUBLE_MAT4x2_EXT 0x8F4D +#define GL_DOUBLE_MAT4x3_EXT 0x8F4E +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DEXTPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DEXTPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVEXTPROC) (GLuint index, GLenum pname, GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribL1dEXT (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttribL2dEXT (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttribL3dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttribL4dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttribL1dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL2dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL3dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL4dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribLPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribLdvEXT (GLuint index, GLenum pname, GLdouble *params); +#endif +#endif /* GL_EXT_vertex_attrib_64bit */ + +#ifndef GL_EXT_vertex_shader +#define GL_EXT_vertex_shader 1 +#define GL_VERTEX_SHADER_EXT 0x8780 +#define GL_VERTEX_SHADER_BINDING_EXT 0x8781 +#define GL_OP_INDEX_EXT 0x8782 +#define GL_OP_NEGATE_EXT 0x8783 +#define GL_OP_DOT3_EXT 0x8784 +#define GL_OP_DOT4_EXT 0x8785 +#define GL_OP_MUL_EXT 0x8786 +#define GL_OP_ADD_EXT 0x8787 +#define GL_OP_MADD_EXT 0x8788 +#define GL_OP_FRAC_EXT 0x8789 +#define GL_OP_MAX_EXT 0x878A +#define GL_OP_MIN_EXT 0x878B +#define GL_OP_SET_GE_EXT 0x878C +#define GL_OP_SET_LT_EXT 0x878D +#define GL_OP_CLAMP_EXT 0x878E +#define GL_OP_FLOOR_EXT 0x878F +#define GL_OP_ROUND_EXT 0x8790 +#define GL_OP_EXP_BASE_2_EXT 0x8791 +#define GL_OP_LOG_BASE_2_EXT 0x8792 +#define GL_OP_POWER_EXT 0x8793 +#define GL_OP_RECIP_EXT 0x8794 +#define GL_OP_RECIP_SQRT_EXT 0x8795 +#define GL_OP_SUB_EXT 0x8796 +#define GL_OP_CROSS_PRODUCT_EXT 0x8797 +#define GL_OP_MULTIPLY_MATRIX_EXT 0x8798 +#define GL_OP_MOV_EXT 0x8799 +#define GL_OUTPUT_VERTEX_EXT 0x879A +#define GL_OUTPUT_COLOR0_EXT 0x879B +#define GL_OUTPUT_COLOR1_EXT 0x879C +#define GL_OUTPUT_TEXTURE_COORD0_EXT 0x879D +#define GL_OUTPUT_TEXTURE_COORD1_EXT 0x879E +#define GL_OUTPUT_TEXTURE_COORD2_EXT 0x879F +#define GL_OUTPUT_TEXTURE_COORD3_EXT 0x87A0 +#define GL_OUTPUT_TEXTURE_COORD4_EXT 0x87A1 +#define GL_OUTPUT_TEXTURE_COORD5_EXT 0x87A2 +#define GL_OUTPUT_TEXTURE_COORD6_EXT 0x87A3 +#define GL_OUTPUT_TEXTURE_COORD7_EXT 0x87A4 +#define GL_OUTPUT_TEXTURE_COORD8_EXT 0x87A5 +#define GL_OUTPUT_TEXTURE_COORD9_EXT 0x87A6 +#define GL_OUTPUT_TEXTURE_COORD10_EXT 0x87A7 +#define GL_OUTPUT_TEXTURE_COORD11_EXT 0x87A8 +#define GL_OUTPUT_TEXTURE_COORD12_EXT 0x87A9 +#define GL_OUTPUT_TEXTURE_COORD13_EXT 0x87AA +#define GL_OUTPUT_TEXTURE_COORD14_EXT 0x87AB +#define GL_OUTPUT_TEXTURE_COORD15_EXT 0x87AC +#define GL_OUTPUT_TEXTURE_COORD16_EXT 0x87AD +#define GL_OUTPUT_TEXTURE_COORD17_EXT 0x87AE +#define GL_OUTPUT_TEXTURE_COORD18_EXT 0x87AF +#define GL_OUTPUT_TEXTURE_COORD19_EXT 0x87B0 +#define GL_OUTPUT_TEXTURE_COORD20_EXT 0x87B1 +#define GL_OUTPUT_TEXTURE_COORD21_EXT 0x87B2 +#define GL_OUTPUT_TEXTURE_COORD22_EXT 0x87B3 +#define GL_OUTPUT_TEXTURE_COORD23_EXT 0x87B4 +#define GL_OUTPUT_TEXTURE_COORD24_EXT 0x87B5 +#define GL_OUTPUT_TEXTURE_COORD25_EXT 0x87B6 +#define GL_OUTPUT_TEXTURE_COORD26_EXT 0x87B7 +#define GL_OUTPUT_TEXTURE_COORD27_EXT 0x87B8 +#define GL_OUTPUT_TEXTURE_COORD28_EXT 0x87B9 +#define GL_OUTPUT_TEXTURE_COORD29_EXT 0x87BA +#define GL_OUTPUT_TEXTURE_COORD30_EXT 0x87BB +#define GL_OUTPUT_TEXTURE_COORD31_EXT 0x87BC +#define GL_OUTPUT_FOG_EXT 0x87BD +#define GL_SCALAR_EXT 0x87BE +#define GL_VECTOR_EXT 0x87BF +#define GL_MATRIX_EXT 0x87C0 +#define GL_VARIANT_EXT 0x87C1 +#define GL_INVARIANT_EXT 0x87C2 +#define GL_LOCAL_CONSTANT_EXT 0x87C3 +#define GL_LOCAL_EXT 0x87C4 +#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5 +#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6 +#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7 +#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8 +#define GL_MAX_VERTEX_SHADER_LOCALS_EXT 0x87C9 +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE +#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF +#define GL_VERTEX_SHADER_VARIANTS_EXT 0x87D0 +#define GL_VERTEX_SHADER_INVARIANTS_EXT 0x87D1 +#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2 +#define GL_VERTEX_SHADER_LOCALS_EXT 0x87D3 +#define GL_VERTEX_SHADER_OPTIMIZED_EXT 0x87D4 +#define GL_X_EXT 0x87D5 +#define GL_Y_EXT 0x87D6 +#define GL_Z_EXT 0x87D7 +#define GL_W_EXT 0x87D8 +#define GL_NEGATIVE_X_EXT 0x87D9 +#define GL_NEGATIVE_Y_EXT 0x87DA +#define GL_NEGATIVE_Z_EXT 0x87DB +#define GL_NEGATIVE_W_EXT 0x87DC +#define GL_ZERO_EXT 0x87DD +#define GL_ONE_EXT 0x87DE +#define GL_NEGATIVE_ONE_EXT 0x87DF +#define GL_NORMALIZED_RANGE_EXT 0x87E0 +#define GL_FULL_RANGE_EXT 0x87E1 +#define GL_CURRENT_VERTEX_EXT 0x87E2 +#define GL_MVP_MATRIX_EXT 0x87E3 +#define GL_VARIANT_VALUE_EXT 0x87E4 +#define GL_VARIANT_DATATYPE_EXT 0x87E5 +#define GL_VARIANT_ARRAY_STRIDE_EXT 0x87E6 +#define GL_VARIANT_ARRAY_TYPE_EXT 0x87E7 +#define GL_VARIANT_ARRAY_EXT 0x87E8 +#define GL_VARIANT_ARRAY_POINTER_EXT 0x87E9 +#define GL_INVARIANT_VALUE_EXT 0x87EA +#define GL_INVARIANT_DATATYPE_EXT 0x87EB +#define GL_LOCAL_CONSTANT_VALUE_EXT 0x87EC +#define GL_LOCAL_CONSTANT_DATATYPE_EXT 0x87ED +typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void); +typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void); +typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id); +typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range); +typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id); +typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1); +typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2); +typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3); +typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); +typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); +typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components); +typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const void *addr); +typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const void *addr); +typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr); +typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr); +typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr); +typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr); +typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr); +typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr); +typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr); +typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr); +typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const void *addr); +typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); +typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); +typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value); +typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap); +typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, void **data); +typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginVertexShaderEXT (void); +GLAPI void APIENTRY glEndVertexShaderEXT (void); +GLAPI void APIENTRY glBindVertexShaderEXT (GLuint id); +GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint range); +GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint id); +GLAPI void APIENTRY glShaderOp1EXT (GLenum op, GLuint res, GLuint arg1); +GLAPI void APIENTRY glShaderOp2EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2); +GLAPI void APIENTRY glShaderOp3EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3); +GLAPI void APIENTRY glSwizzleEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +GLAPI void APIENTRY glWriteMaskEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +GLAPI void APIENTRY glInsertComponentEXT (GLuint res, GLuint src, GLuint num); +GLAPI void APIENTRY glExtractComponentEXT (GLuint res, GLuint src, GLuint num); +GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum datatype, GLenum storagetype, GLenum range, GLuint components); +GLAPI void APIENTRY glSetInvariantEXT (GLuint id, GLenum type, const void *addr); +GLAPI void APIENTRY glSetLocalConstantEXT (GLuint id, GLenum type, const void *addr); +GLAPI void APIENTRY glVariantbvEXT (GLuint id, const GLbyte *addr); +GLAPI void APIENTRY glVariantsvEXT (GLuint id, const GLshort *addr); +GLAPI void APIENTRY glVariantivEXT (GLuint id, const GLint *addr); +GLAPI void APIENTRY glVariantfvEXT (GLuint id, const GLfloat *addr); +GLAPI void APIENTRY glVariantdvEXT (GLuint id, const GLdouble *addr); +GLAPI void APIENTRY glVariantubvEXT (GLuint id, const GLubyte *addr); +GLAPI void APIENTRY glVariantusvEXT (GLuint id, const GLushort *addr); +GLAPI void APIENTRY glVariantuivEXT (GLuint id, const GLuint *addr); +GLAPI void APIENTRY glVariantPointerEXT (GLuint id, GLenum type, GLuint stride, const void *addr); +GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint id); +GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint id); +GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum light, GLenum value); +GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum face, GLenum value); +GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum unit, GLenum coord, GLenum value); +GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum unit, GLenum value); +GLAPI GLuint APIENTRY glBindParameterEXT (GLenum value); +GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint id, GLenum cap); +GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +GLAPI void APIENTRY glGetVariantPointervEXT (GLuint id, GLenum value, void **data); +GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +#endif +#endif /* GL_EXT_vertex_shader */ + +#ifndef GL_EXT_vertex_weighting +#define GL_EXT_vertex_weighting 1 +#define GL_MODELVIEW0_STACK_DEPTH_EXT 0x0BA3 +#define GL_MODELVIEW1_STACK_DEPTH_EXT 0x8502 +#define GL_MODELVIEW0_MATRIX_EXT 0x0BA6 +#define GL_MODELVIEW1_MATRIX_EXT 0x8506 +#define GL_VERTEX_WEIGHTING_EXT 0x8509 +#define GL_MODELVIEW0_EXT 0x1700 +#define GL_MODELVIEW1_EXT 0x850A +#define GL_CURRENT_VERTEX_WEIGHT_EXT 0x850B +#define GL_VERTEX_WEIGHT_ARRAY_EXT 0x850C +#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT 0x850D +#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT 0x850E +#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F +#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510 +typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexWeightfEXT (GLfloat weight); +GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *weight); +GLAPI void APIENTRY glVertexWeightPointerEXT (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_vertex_weighting */ + +#ifndef GL_EXT_win32_keyed_mutex +#define GL_EXT_win32_keyed_mutex 1 +typedef GLboolean (APIENTRYP PFNGLACQUIREKEYEDMUTEXWIN32EXTPROC) (GLuint memory, GLuint64 key, GLuint timeout); +typedef GLboolean (APIENTRYP PFNGLRELEASEKEYEDMUTEXWIN32EXTPROC) (GLuint memory, GLuint64 key); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAcquireKeyedMutexWin32EXT (GLuint memory, GLuint64 key, GLuint timeout); +GLAPI GLboolean APIENTRY glReleaseKeyedMutexWin32EXT (GLuint memory, GLuint64 key); +#endif +#endif /* GL_EXT_win32_keyed_mutex */ + +#ifndef GL_EXT_window_rectangles +#define GL_EXT_window_rectangles 1 +#define GL_INCLUSIVE_EXT 0x8F10 +#define GL_EXCLUSIVE_EXT 0x8F11 +#define GL_WINDOW_RECTANGLE_EXT 0x8F12 +#define GL_WINDOW_RECTANGLE_MODE_EXT 0x8F13 +#define GL_MAX_WINDOW_RECTANGLES_EXT 0x8F14 +#define GL_NUM_WINDOW_RECTANGLES_EXT 0x8F15 +typedef void (APIENTRYP PFNGLWINDOWRECTANGLESEXTPROC) (GLenum mode, GLsizei count, const GLint *box); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowRectanglesEXT (GLenum mode, GLsizei count, const GLint *box); +#endif +#endif /* GL_EXT_window_rectangles */ + +#ifndef GL_EXT_x11_sync_object +#define GL_EXT_x11_sync_object 1 +#define GL_SYNC_X11_FENCE_EXT 0x90E1 +typedef GLsync (APIENTRYP PFNGLIMPORTSYNCEXTPROC) (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLsync APIENTRY glImportSyncEXT (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags); +#endif +#endif /* GL_EXT_x11_sync_object */ + +#ifndef GL_GREMEDY_frame_terminator +#define GL_GREMEDY_frame_terminator 1 +typedef void (APIENTRYP PFNGLFRAMETERMINATORGREMEDYPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFrameTerminatorGREMEDY (void); +#endif +#endif /* GL_GREMEDY_frame_terminator */ + +#ifndef GL_GREMEDY_string_marker +#define GL_GREMEDY_string_marker 1 +typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const void *string); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei len, const void *string); +#endif +#endif /* GL_GREMEDY_string_marker */ + +#ifndef GL_HP_convolution_border_modes +#define GL_HP_convolution_border_modes 1 +#define GL_IGNORE_BORDER_HP 0x8150 +#define GL_CONSTANT_BORDER_HP 0x8151 +#define GL_REPLICATE_BORDER_HP 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR_HP 0x8154 +#endif /* GL_HP_convolution_border_modes */ + +#ifndef GL_HP_image_transform +#define GL_HP_image_transform 1 +#define GL_IMAGE_SCALE_X_HP 0x8155 +#define GL_IMAGE_SCALE_Y_HP 0x8156 +#define GL_IMAGE_TRANSLATE_X_HP 0x8157 +#define GL_IMAGE_TRANSLATE_Y_HP 0x8158 +#define GL_IMAGE_ROTATE_ANGLE_HP 0x8159 +#define GL_IMAGE_ROTATE_ORIGIN_X_HP 0x815A +#define GL_IMAGE_ROTATE_ORIGIN_Y_HP 0x815B +#define GL_IMAGE_MAG_FILTER_HP 0x815C +#define GL_IMAGE_MIN_FILTER_HP 0x815D +#define GL_IMAGE_CUBIC_WEIGHT_HP 0x815E +#define GL_CUBIC_HP 0x815F +#define GL_AVERAGE_HP 0x8160 +#define GL_IMAGE_TRANSFORM_2D_HP 0x8161 +#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162 +#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163 +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glImageTransformParameteriHP (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glImageTransformParameterfHP (GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glImageTransformParameterivHP (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_HP_image_transform */ + +#ifndef GL_HP_occlusion_test +#define GL_HP_occlusion_test 1 +#define GL_OCCLUSION_TEST_HP 0x8165 +#define GL_OCCLUSION_TEST_RESULT_HP 0x8166 +#endif /* GL_HP_occlusion_test */ + +#ifndef GL_HP_texture_lighting +#define GL_HP_texture_lighting 1 +#define GL_TEXTURE_LIGHTING_MODE_HP 0x8167 +#define GL_TEXTURE_POST_SPECULAR_HP 0x8168 +#define GL_TEXTURE_PRE_SPECULAR_HP 0x8169 +#endif /* GL_HP_texture_lighting */ + +#ifndef GL_IBM_cull_vertex +#define GL_IBM_cull_vertex 1 +#define GL_CULL_VERTEX_IBM 103050 +#endif /* GL_IBM_cull_vertex */ + +#ifndef GL_IBM_multimode_draw_arrays +#define GL_IBM_multimode_draw_arrays 1 +typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride); +typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, GLint modestride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride); +GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, GLint modestride); +#endif +#endif /* GL_IBM_multimode_draw_arrays */ + +#ifndef GL_IBM_rasterpos_clip +#define GL_IBM_rasterpos_clip 1 +#define GL_RASTER_POSITION_UNCLIPPED_IBM 0x19262 +#endif /* GL_IBM_rasterpos_clip */ + +#ifndef GL_IBM_static_data +#define GL_IBM_static_data 1 +#define GL_ALL_STATIC_DATA_IBM 103060 +#define GL_STATIC_VERTEX_ARRAY_IBM 103061 +typedef void (APIENTRYP PFNGLFLUSHSTATICDATAIBMPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushStaticDataIBM (GLenum target); +#endif +#endif /* GL_IBM_static_data */ + +#ifndef GL_IBM_texture_mirrored_repeat +#define GL_IBM_texture_mirrored_repeat 1 +#define GL_MIRRORED_REPEAT_IBM 0x8370 +#endif /* GL_IBM_texture_mirrored_repeat */ + +#ifndef GL_IBM_vertex_array_lists +#define GL_IBM_vertex_array_lists 1 +#define GL_VERTEX_ARRAY_LIST_IBM 103070 +#define GL_NORMAL_ARRAY_LIST_IBM 103071 +#define GL_COLOR_ARRAY_LIST_IBM 103072 +#define GL_INDEX_ARRAY_LIST_IBM 103073 +#define GL_TEXTURE_COORD_ARRAY_LIST_IBM 103074 +#define GL_EDGE_FLAG_ARRAY_LIST_IBM 103075 +#define GL_FOG_COORDINATE_ARRAY_LIST_IBM 103076 +#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077 +#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM 103080 +#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM 103081 +#define GL_COLOR_ARRAY_LIST_STRIDE_IBM 103082 +#define GL_INDEX_ARRAY_LIST_STRIDE_IBM 103083 +#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084 +#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085 +#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086 +#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087 +typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint stride, const GLboolean **pointer, GLint ptrstride); +GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glIndexPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glNormalPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glTexCoordPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glVertexPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +#endif +#endif /* GL_IBM_vertex_array_lists */ + +#ifndef GL_INGR_blend_func_separate +#define GL_INGR_blend_func_separate 1 +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#endif +#endif /* GL_INGR_blend_func_separate */ + +#ifndef GL_INGR_color_clamp +#define GL_INGR_color_clamp 1 +#define GL_RED_MIN_CLAMP_INGR 0x8560 +#define GL_GREEN_MIN_CLAMP_INGR 0x8561 +#define GL_BLUE_MIN_CLAMP_INGR 0x8562 +#define GL_ALPHA_MIN_CLAMP_INGR 0x8563 +#define GL_RED_MAX_CLAMP_INGR 0x8564 +#define GL_GREEN_MAX_CLAMP_INGR 0x8565 +#define GL_BLUE_MAX_CLAMP_INGR 0x8566 +#define GL_ALPHA_MAX_CLAMP_INGR 0x8567 +#endif /* GL_INGR_color_clamp */ + +#ifndef GL_INGR_interlace_read +#define GL_INGR_interlace_read 1 +#define GL_INTERLACE_READ_INGR 0x8568 +#endif /* GL_INGR_interlace_read */ + +#ifndef GL_INTEL_blackhole_render +#define GL_INTEL_blackhole_render 1 +#define GL_BLACKHOLE_RENDER_INTEL 0x83FC +#endif /* GL_INTEL_blackhole_render */ + +#ifndef GL_INTEL_conservative_rasterization +#define GL_INTEL_conservative_rasterization 1 +#define GL_CONSERVATIVE_RASTERIZATION_INTEL 0x83FE +#endif /* GL_INTEL_conservative_rasterization */ + +#ifndef GL_INTEL_fragment_shader_ordering +#define GL_INTEL_fragment_shader_ordering 1 +#endif /* GL_INTEL_fragment_shader_ordering */ + +#ifndef GL_INTEL_framebuffer_CMAA +#define GL_INTEL_framebuffer_CMAA 1 +typedef void (APIENTRYP PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glApplyFramebufferAttachmentCMAAINTEL (void); +#endif +#endif /* GL_INTEL_framebuffer_CMAA */ + +#ifndef GL_INTEL_map_texture +#define GL_INTEL_map_texture 1 +#define GL_TEXTURE_MEMORY_LAYOUT_INTEL 0x83FF +#define GL_LAYOUT_DEFAULT_INTEL 0 +#define GL_LAYOUT_LINEAR_INTEL 1 +#define GL_LAYOUT_LINEAR_CPU_CACHED_INTEL 2 +typedef void (APIENTRYP PFNGLSYNCTEXTUREINTELPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLUNMAPTEXTURE2DINTELPROC) (GLuint texture, GLint level); +typedef void *(APIENTRYP PFNGLMAPTEXTURE2DINTELPROC) (GLuint texture, GLint level, GLbitfield access, GLint *stride, GLenum *layout); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSyncTextureINTEL (GLuint texture); +GLAPI void APIENTRY glUnmapTexture2DINTEL (GLuint texture, GLint level); +GLAPI void *APIENTRY glMapTexture2DINTEL (GLuint texture, GLint level, GLbitfield access, GLint *stride, GLenum *layout); +#endif +#endif /* GL_INTEL_map_texture */ + +#ifndef GL_INTEL_parallel_arrays +#define GL_INTEL_parallel_arrays 1 +#define GL_PARALLEL_ARRAYS_INTEL 0x83F4 +#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5 +#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6 +#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7 +#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8 +typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexPointervINTEL (GLint size, GLenum type, const void **pointer); +GLAPI void APIENTRY glNormalPointervINTEL (GLenum type, const void **pointer); +GLAPI void APIENTRY glColorPointervINTEL (GLint size, GLenum type, const void **pointer); +GLAPI void APIENTRY glTexCoordPointervINTEL (GLint size, GLenum type, const void **pointer); +#endif +#endif /* GL_INTEL_parallel_arrays */ + +#ifndef GL_INTEL_performance_query +#define GL_INTEL_performance_query 1 +#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000 +#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001 +#define GL_PERFQUERY_WAIT_INTEL 0x83FB +#define GL_PERFQUERY_FLUSH_INTEL 0x83FA +#define GL_PERFQUERY_DONOT_FLUSH_INTEL 0x83F9 +#define GL_PERFQUERY_COUNTER_EVENT_INTEL 0x94F0 +#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1 +#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2 +#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3 +#define GL_PERFQUERY_COUNTER_RAW_INTEL 0x94F4 +#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5 +#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8 +#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9 +#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA +#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB +#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC +#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD +#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE +#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF +#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500 +typedef void (APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle); +typedef void (APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId); +typedef void (APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId); +typedef void (APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); +typedef void (APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, void *data, GLuint *bytesWritten); +typedef void (APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId); +typedef void (APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle); +GLAPI void APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glEndPerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId); +GLAPI void APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId); +GLAPI void APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); +GLAPI void APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, void *data, GLuint *bytesWritten); +GLAPI void APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId); +GLAPI void APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); +#endif +#endif /* GL_INTEL_performance_query */ + +#ifndef GL_MESAX_texture_stack +#define GL_MESAX_texture_stack 1 +#define GL_TEXTURE_1D_STACK_MESAX 0x8759 +#define GL_TEXTURE_2D_STACK_MESAX 0x875A +#define GL_PROXY_TEXTURE_1D_STACK_MESAX 0x875B +#define GL_PROXY_TEXTURE_2D_STACK_MESAX 0x875C +#define GL_TEXTURE_1D_STACK_BINDING_MESAX 0x875D +#define GL_TEXTURE_2D_STACK_BINDING_MESAX 0x875E +#endif /* GL_MESAX_texture_stack */ + +#ifndef GL_MESA_framebuffer_flip_x +#define GL_MESA_framebuffer_flip_x 1 +#define GL_FRAMEBUFFER_FLIP_X_MESA 0x8BBC +#endif /* GL_MESA_framebuffer_flip_x */ + +#ifndef GL_MESA_framebuffer_flip_y +#define GL_MESA_framebuffer_flip_y 1 +#define GL_FRAMEBUFFER_FLIP_Y_MESA 0x8BBB +typedef void (APIENTRYP PFNGLFRAMEBUFFERPARAMETERIMESAPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVMESAPROC) (GLenum target, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferParameteriMESA (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glGetFramebufferParameterivMESA (GLenum target, GLenum pname, GLint *params); +#endif +#endif /* GL_MESA_framebuffer_flip_y */ + +#ifndef GL_MESA_framebuffer_swap_xy +#define GL_MESA_framebuffer_swap_xy 1 +#define GL_FRAMEBUFFER_SWAP_XY_MESA 0x8BBD +#endif /* GL_MESA_framebuffer_swap_xy */ + +#ifndef GL_MESA_pack_invert +#define GL_MESA_pack_invert 1 +#define GL_PACK_INVERT_MESA 0x8758 +#endif /* GL_MESA_pack_invert */ + +#ifndef GL_MESA_program_binary_formats +#define GL_MESA_program_binary_formats 1 +#define GL_PROGRAM_BINARY_FORMAT_MESA 0x875F +#endif /* GL_MESA_program_binary_formats */ + +#ifndef GL_MESA_resize_buffers +#define GL_MESA_resize_buffers 1 +typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glResizeBuffersMESA (void); +#endif +#endif /* GL_MESA_resize_buffers */ + +#ifndef GL_MESA_shader_integer_functions +#define GL_MESA_shader_integer_functions 1 +#endif /* GL_MESA_shader_integer_functions */ + +#ifndef GL_MESA_tile_raster_order +#define GL_MESA_tile_raster_order 1 +#define GL_TILE_RASTER_ORDER_FIXED_MESA 0x8BB8 +#define GL_TILE_RASTER_ORDER_INCREASING_X_MESA 0x8BB9 +#define GL_TILE_RASTER_ORDER_INCREASING_Y_MESA 0x8BBA +#endif /* GL_MESA_tile_raster_order */ + +#ifndef GL_MESA_window_pos +#define GL_MESA_window_pos 1 +typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowPos2dMESA (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2fMESA (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2iMESA (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos2sMESA (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *v); +GLAPI void APIENTRY glWindowPos3dMESA (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3fMESA (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3iMESA (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos3sMESA (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *v); +GLAPI void APIENTRY glWindowPos4dMESA (GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos4fMESA (GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos4iMESA (GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos4sMESA (GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *v); +#endif +#endif /* GL_MESA_window_pos */ + +#ifndef GL_MESA_ycbcr_texture +#define GL_MESA_ycbcr_texture 1 +#define GL_UNSIGNED_SHORT_8_8_MESA 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_MESA 0x85BB +#define GL_YCBCR_MESA 0x8757 +#endif /* GL_MESA_ycbcr_texture */ + +#ifndef GL_NVX_blend_equation_advanced_multi_draw_buffers +#define GL_NVX_blend_equation_advanced_multi_draw_buffers 1 +#endif /* GL_NVX_blend_equation_advanced_multi_draw_buffers */ + +#ifndef GL_NVX_conditional_render +#define GL_NVX_conditional_render 1 +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVXPROC) (GLuint id); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginConditionalRenderNVX (GLuint id); +GLAPI void APIENTRY glEndConditionalRenderNVX (void); +#endif +#endif /* GL_NVX_conditional_render */ + +#ifndef GL_NVX_gpu_memory_info +#define GL_NVX_gpu_memory_info 1 +#define GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX 0x9047 +#define GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048 +#define GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049 +#define GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX 0x904A +#define GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX 0x904B +#endif /* GL_NVX_gpu_memory_info */ + +#ifndef GL_NVX_gpu_multicast2 +#define GL_NVX_gpu_multicast2 1 +#define GL_UPLOAD_GPU_MASK_NVX 0x954A +typedef void (APIENTRYP PFNGLUPLOADGPUMASKNVXPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLMULTICASTVIEWPORTARRAYVNVXPROC) (GLuint gpu, GLuint first, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTICASTVIEWPORTPOSITIONWSCALENVXPROC) (GLuint gpu, GLuint index, GLfloat xcoeff, GLfloat ycoeff); +typedef void (APIENTRYP PFNGLMULTICASTSCISSORARRAYVNVXPROC) (GLuint gpu, GLuint first, GLsizei count, const GLint *v); +typedef GLuint (APIENTRYP PFNGLASYNCCOPYBUFFERSUBDATANVXPROC) (GLsizei waitSemaphoreCount, const GLuint *waitSemaphoreArray, const GLuint64 *fenceValueArray, GLuint readGpu, GLbitfield writeGpuMask, GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size, GLsizei signalSemaphoreCount, const GLuint *signalSemaphoreArray, const GLuint64 *signalValueArray); +typedef GLuint (APIENTRYP PFNGLASYNCCOPYIMAGESUBDATANVXPROC) (GLsizei waitSemaphoreCount, const GLuint *waitSemaphoreArray, const GLuint64 *waitValueArray, GLuint srcGpu, GLbitfield dstGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth, GLsizei signalSemaphoreCount, const GLuint *signalSemaphoreArray, const GLuint64 *signalValueArray); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUploadGpuMaskNVX (GLbitfield mask); +GLAPI void APIENTRY glMulticastViewportArrayvNVX (GLuint gpu, GLuint first, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glMulticastViewportPositionWScaleNVX (GLuint gpu, GLuint index, GLfloat xcoeff, GLfloat ycoeff); +GLAPI void APIENTRY glMulticastScissorArrayvNVX (GLuint gpu, GLuint first, GLsizei count, const GLint *v); +GLAPI GLuint APIENTRY glAsyncCopyBufferSubDataNVX (GLsizei waitSemaphoreCount, const GLuint *waitSemaphoreArray, const GLuint64 *fenceValueArray, GLuint readGpu, GLbitfield writeGpuMask, GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size, GLsizei signalSemaphoreCount, const GLuint *signalSemaphoreArray, const GLuint64 *signalValueArray); +GLAPI GLuint APIENTRY glAsyncCopyImageSubDataNVX (GLsizei waitSemaphoreCount, const GLuint *waitSemaphoreArray, const GLuint64 *waitValueArray, GLuint srcGpu, GLbitfield dstGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth, GLsizei signalSemaphoreCount, const GLuint *signalSemaphoreArray, const GLuint64 *signalValueArray); +#endif +#endif /* GL_NVX_gpu_multicast2 */ + +#ifndef GL_NVX_linked_gpu_multicast +#define GL_NVX_linked_gpu_multicast 1 +#define GL_LGPU_SEPARATE_STORAGE_BIT_NVX 0x0800 +#define GL_MAX_LGPU_GPUS_NVX 0x92BA +typedef void (APIENTRYP PFNGLLGPUNAMEDBUFFERSUBDATANVXPROC) (GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +typedef void (APIENTRYP PFNGLLGPUCOPYIMAGESUBDATANVXPROC) (GLuint sourceGpu, GLbitfield destinationGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srxY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLLGPUINTERLOCKNVXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLGPUNamedBufferSubDataNVX (GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void APIENTRY glLGPUCopyImageSubDataNVX (GLuint sourceGpu, GLbitfield destinationGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srxY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glLGPUInterlockNVX (void); +#endif +#endif /* GL_NVX_linked_gpu_multicast */ + +#ifndef GL_NVX_progress_fence +#define GL_NVX_progress_fence 1 +typedef GLuint (APIENTRYP PFNGLCREATEPROGRESSFENCENVXPROC) (void); +typedef void (APIENTRYP PFNGLSIGNALSEMAPHOREUI64NVXPROC) (GLuint signalGpu, GLsizei fenceObjectCount, const GLuint *semaphoreArray, const GLuint64 *fenceValueArray); +typedef void (APIENTRYP PFNGLWAITSEMAPHOREUI64NVXPROC) (GLuint waitGpu, GLsizei fenceObjectCount, const GLuint *semaphoreArray, const GLuint64 *fenceValueArray); +typedef void (APIENTRYP PFNGLCLIENTWAITSEMAPHOREUI64NVXPROC) (GLsizei fenceObjectCount, const GLuint *semaphoreArray, const GLuint64 *fenceValueArray); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glCreateProgressFenceNVX (void); +GLAPI void APIENTRY glSignalSemaphoreui64NVX (GLuint signalGpu, GLsizei fenceObjectCount, const GLuint *semaphoreArray, const GLuint64 *fenceValueArray); +GLAPI void APIENTRY glWaitSemaphoreui64NVX (GLuint waitGpu, GLsizei fenceObjectCount, const GLuint *semaphoreArray, const GLuint64 *fenceValueArray); +GLAPI void APIENTRY glClientWaitSemaphoreui64NVX (GLsizei fenceObjectCount, const GLuint *semaphoreArray, const GLuint64 *fenceValueArray); +#endif +#endif /* GL_NVX_progress_fence */ + +#ifndef GL_NV_alpha_to_coverage_dither_control +#define GL_NV_alpha_to_coverage_dither_control 1 +#define GL_ALPHA_TO_COVERAGE_DITHER_DEFAULT_NV 0x934D +#define GL_ALPHA_TO_COVERAGE_DITHER_ENABLE_NV 0x934E +#define GL_ALPHA_TO_COVERAGE_DITHER_DISABLE_NV 0x934F +#define GL_ALPHA_TO_COVERAGE_DITHER_MODE_NV 0x92BF +typedef void (APIENTRYP PFNGLALPHATOCOVERAGEDITHERCONTROLNVPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAlphaToCoverageDitherControlNV (GLenum mode); +#endif +#endif /* GL_NV_alpha_to_coverage_dither_control */ + +#ifndef GL_NV_bindless_multi_draw_indirect +#define GL_NV_bindless_multi_draw_indirect 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectBindlessNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +GLAPI void APIENTRY glMultiDrawElementsIndirectBindlessNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +#endif +#endif /* GL_NV_bindless_multi_draw_indirect */ + +#ifndef GL_NV_bindless_multi_draw_indirect_count +#define GL_NV_bindless_multi_draw_indirect_count 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSCOUNTNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSCOUNTNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectBindlessCountNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +GLAPI void APIENTRY glMultiDrawElementsIndirectBindlessCountNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +#endif +#endif /* GL_NV_bindless_multi_draw_indirect_count */ + +#ifndef GL_NV_bindless_texture +#define GL_NV_bindless_texture 1 +typedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLENVPROC) (GLuint texture); +typedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLENVPROC) (GLuint texture, GLuint sampler); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC) (GLuint64 handle); +typedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLENVPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle, GLenum access); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64NVPROC) (GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VNVPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC) (GLuint program, GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); +typedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint64 APIENTRY glGetTextureHandleNV (GLuint texture); +GLAPI GLuint64 APIENTRY glGetTextureSamplerHandleNV (GLuint texture, GLuint sampler); +GLAPI void APIENTRY glMakeTextureHandleResidentNV (GLuint64 handle); +GLAPI void APIENTRY glMakeTextureHandleNonResidentNV (GLuint64 handle); +GLAPI GLuint64 APIENTRY glGetImageHandleNV (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +GLAPI void APIENTRY glMakeImageHandleResidentNV (GLuint64 handle, GLenum access); +GLAPI void APIENTRY glMakeImageHandleNonResidentNV (GLuint64 handle); +GLAPI void APIENTRY glUniformHandleui64NV (GLint location, GLuint64 value); +GLAPI void APIENTRY glUniformHandleui64vNV (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniformHandleui64NV (GLuint program, GLint location, GLuint64 value); +GLAPI void APIENTRY glProgramUniformHandleui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +GLAPI GLboolean APIENTRY glIsTextureHandleResidentNV (GLuint64 handle); +GLAPI GLboolean APIENTRY glIsImageHandleResidentNV (GLuint64 handle); +#endif +#endif /* GL_NV_bindless_texture */ + +#ifndef GL_NV_blend_equation_advanced +#define GL_NV_blend_equation_advanced 1 +#define GL_BLEND_OVERLAP_NV 0x9281 +#define GL_BLEND_PREMULTIPLIED_SRC_NV 0x9280 +#define GL_BLUE_NV 0x1905 +#define GL_COLORBURN_NV 0x929A +#define GL_COLORDODGE_NV 0x9299 +#define GL_CONJOINT_NV 0x9284 +#define GL_CONTRAST_NV 0x92A1 +#define GL_DARKEN_NV 0x9297 +#define GL_DIFFERENCE_NV 0x929E +#define GL_DISJOINT_NV 0x9283 +#define GL_DST_ATOP_NV 0x928F +#define GL_DST_IN_NV 0x928B +#define GL_DST_NV 0x9287 +#define GL_DST_OUT_NV 0x928D +#define GL_DST_OVER_NV 0x9289 +#define GL_EXCLUSION_NV 0x92A0 +#define GL_GREEN_NV 0x1904 +#define GL_HARDLIGHT_NV 0x929B +#define GL_HARDMIX_NV 0x92A9 +#define GL_HSL_COLOR_NV 0x92AF +#define GL_HSL_HUE_NV 0x92AD +#define GL_HSL_LUMINOSITY_NV 0x92B0 +#define GL_HSL_SATURATION_NV 0x92AE +#define GL_INVERT_OVG_NV 0x92B4 +#define GL_INVERT_RGB_NV 0x92A3 +#define GL_LIGHTEN_NV 0x9298 +#define GL_LINEARBURN_NV 0x92A5 +#define GL_LINEARDODGE_NV 0x92A4 +#define GL_LINEARLIGHT_NV 0x92A7 +#define GL_MINUS_CLAMPED_NV 0x92B3 +#define GL_MINUS_NV 0x929F +#define GL_MULTIPLY_NV 0x9294 +#define GL_OVERLAY_NV 0x9296 +#define GL_PINLIGHT_NV 0x92A8 +#define GL_PLUS_CLAMPED_ALPHA_NV 0x92B2 +#define GL_PLUS_CLAMPED_NV 0x92B1 +#define GL_PLUS_DARKER_NV 0x9292 +#define GL_PLUS_NV 0x9291 +#define GL_RED_NV 0x1903 +#define GL_SCREEN_NV 0x9295 +#define GL_SOFTLIGHT_NV 0x929C +#define GL_SRC_ATOP_NV 0x928E +#define GL_SRC_IN_NV 0x928A +#define GL_SRC_NV 0x9286 +#define GL_SRC_OUT_NV 0x928C +#define GL_SRC_OVER_NV 0x9288 +#define GL_UNCORRELATED_NV 0x9282 +#define GL_VIVIDLIGHT_NV 0x92A6 +#define GL_XOR_NV 0x1506 +typedef void (APIENTRYP PFNGLBLENDPARAMETERINVPROC) (GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLBLENDBARRIERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendParameteriNV (GLenum pname, GLint value); +GLAPI void APIENTRY glBlendBarrierNV (void); +#endif +#endif /* GL_NV_blend_equation_advanced */ + +#ifndef GL_NV_blend_equation_advanced_coherent +#define GL_NV_blend_equation_advanced_coherent 1 +#define GL_BLEND_ADVANCED_COHERENT_NV 0x9285 +#endif /* GL_NV_blend_equation_advanced_coherent */ + +#ifndef GL_NV_blend_minmax_factor +#define GL_NV_blend_minmax_factor 1 +#endif /* GL_NV_blend_minmax_factor */ + +#ifndef GL_NV_blend_square +#define GL_NV_blend_square 1 +#endif /* GL_NV_blend_square */ + +#ifndef GL_NV_clip_space_w_scaling +#define GL_NV_clip_space_w_scaling 1 +#define GL_VIEWPORT_POSITION_W_SCALE_NV 0x937C +#define GL_VIEWPORT_POSITION_W_SCALE_X_COEFF_NV 0x937D +#define GL_VIEWPORT_POSITION_W_SCALE_Y_COEFF_NV 0x937E +typedef void (APIENTRYP PFNGLVIEWPORTPOSITIONWSCALENVPROC) (GLuint index, GLfloat xcoeff, GLfloat ycoeff); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glViewportPositionWScaleNV (GLuint index, GLfloat xcoeff, GLfloat ycoeff); +#endif +#endif /* GL_NV_clip_space_w_scaling */ + +#ifndef GL_NV_command_list +#define GL_NV_command_list 1 +#define GL_TERMINATE_SEQUENCE_COMMAND_NV 0x0000 +#define GL_NOP_COMMAND_NV 0x0001 +#define GL_DRAW_ELEMENTS_COMMAND_NV 0x0002 +#define GL_DRAW_ARRAYS_COMMAND_NV 0x0003 +#define GL_DRAW_ELEMENTS_STRIP_COMMAND_NV 0x0004 +#define GL_DRAW_ARRAYS_STRIP_COMMAND_NV 0x0005 +#define GL_DRAW_ELEMENTS_INSTANCED_COMMAND_NV 0x0006 +#define GL_DRAW_ARRAYS_INSTANCED_COMMAND_NV 0x0007 +#define GL_ELEMENT_ADDRESS_COMMAND_NV 0x0008 +#define GL_ATTRIBUTE_ADDRESS_COMMAND_NV 0x0009 +#define GL_UNIFORM_ADDRESS_COMMAND_NV 0x000A +#define GL_BLEND_COLOR_COMMAND_NV 0x000B +#define GL_STENCIL_REF_COMMAND_NV 0x000C +#define GL_LINE_WIDTH_COMMAND_NV 0x000D +#define GL_POLYGON_OFFSET_COMMAND_NV 0x000E +#define GL_ALPHA_REF_COMMAND_NV 0x000F +#define GL_VIEWPORT_COMMAND_NV 0x0010 +#define GL_SCISSOR_COMMAND_NV 0x0011 +#define GL_FRONT_FACE_COMMAND_NV 0x0012 +typedef void (APIENTRYP PFNGLCREATESTATESNVPROC) (GLsizei n, GLuint *states); +typedef void (APIENTRYP PFNGLDELETESTATESNVPROC) (GLsizei n, const GLuint *states); +typedef GLboolean (APIENTRYP PFNGLISSTATENVPROC) (GLuint state); +typedef void (APIENTRYP PFNGLSTATECAPTURENVPROC) (GLuint state, GLenum mode); +typedef GLuint (APIENTRYP PFNGLGETCOMMANDHEADERNVPROC) (GLenum tokenID, GLuint size); +typedef GLushort (APIENTRYP PFNGLGETSTAGEINDEXNVPROC) (GLenum shadertype); +typedef void (APIENTRYP PFNGLDRAWCOMMANDSNVPROC) (GLenum primitiveMode, GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, GLuint count); +typedef void (APIENTRYP PFNGLDRAWCOMMANDSADDRESSNVPROC) (GLenum primitiveMode, const GLuint64 *indirects, const GLsizei *sizes, GLuint count); +typedef void (APIENTRYP PFNGLDRAWCOMMANDSSTATESNVPROC) (GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +typedef void (APIENTRYP PFNGLDRAWCOMMANDSSTATESADDRESSNVPROC) (const GLuint64 *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +typedef void (APIENTRYP PFNGLCREATECOMMANDLISTSNVPROC) (GLsizei n, GLuint *lists); +typedef void (APIENTRYP PFNGLDELETECOMMANDLISTSNVPROC) (GLsizei n, const GLuint *lists); +typedef GLboolean (APIENTRYP PFNGLISCOMMANDLISTNVPROC) (GLuint list); +typedef void (APIENTRYP PFNGLLISTDRAWCOMMANDSSTATESCLIENTNVPROC) (GLuint list, GLuint segment, const void **indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +typedef void (APIENTRYP PFNGLCOMMANDLISTSEGMENTSNVPROC) (GLuint list, GLuint segments); +typedef void (APIENTRYP PFNGLCOMPILECOMMANDLISTNVPROC) (GLuint list); +typedef void (APIENTRYP PFNGLCALLCOMMANDLISTNVPROC) (GLuint list); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCreateStatesNV (GLsizei n, GLuint *states); +GLAPI void APIENTRY glDeleteStatesNV (GLsizei n, const GLuint *states); +GLAPI GLboolean APIENTRY glIsStateNV (GLuint state); +GLAPI void APIENTRY glStateCaptureNV (GLuint state, GLenum mode); +GLAPI GLuint APIENTRY glGetCommandHeaderNV (GLenum tokenID, GLuint size); +GLAPI GLushort APIENTRY glGetStageIndexNV (GLenum shadertype); +GLAPI void APIENTRY glDrawCommandsNV (GLenum primitiveMode, GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, GLuint count); +GLAPI void APIENTRY glDrawCommandsAddressNV (GLenum primitiveMode, const GLuint64 *indirects, const GLsizei *sizes, GLuint count); +GLAPI void APIENTRY glDrawCommandsStatesNV (GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +GLAPI void APIENTRY glDrawCommandsStatesAddressNV (const GLuint64 *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +GLAPI void APIENTRY glCreateCommandListsNV (GLsizei n, GLuint *lists); +GLAPI void APIENTRY glDeleteCommandListsNV (GLsizei n, const GLuint *lists); +GLAPI GLboolean APIENTRY glIsCommandListNV (GLuint list); +GLAPI void APIENTRY glListDrawCommandsStatesClientNV (GLuint list, GLuint segment, const void **indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); +GLAPI void APIENTRY glCommandListSegmentsNV (GLuint list, GLuint segments); +GLAPI void APIENTRY glCompileCommandListNV (GLuint list); +GLAPI void APIENTRY glCallCommandListNV (GLuint list); +#endif +#endif /* GL_NV_command_list */ + +#ifndef GL_NV_compute_program5 +#define GL_NV_compute_program5 1 +#define GL_COMPUTE_PROGRAM_NV 0x90FB +#define GL_COMPUTE_PROGRAM_PARAMETER_BUFFER_NV 0x90FC +#endif /* GL_NV_compute_program5 */ + +#ifndef GL_NV_compute_shader_derivatives +#define GL_NV_compute_shader_derivatives 1 +#endif /* GL_NV_compute_shader_derivatives */ + +#ifndef GL_NV_conditional_render +#define GL_NV_conditional_render 1 +#define GL_QUERY_WAIT_NV 0x8E13 +#define GL_QUERY_NO_WAIT_NV 0x8E14 +#define GL_QUERY_BY_REGION_WAIT_NV 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT_NV 0x8E16 +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode); +GLAPI void APIENTRY glEndConditionalRenderNV (void); +#endif +#endif /* GL_NV_conditional_render */ + +#ifndef GL_NV_conservative_raster +#define GL_NV_conservative_raster 1 +#define GL_CONSERVATIVE_RASTERIZATION_NV 0x9346 +#define GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV 0x9347 +#define GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV 0x9348 +#define GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV 0x9349 +typedef void (APIENTRYP PFNGLSUBPIXELPRECISIONBIASNVPROC) (GLuint xbits, GLuint ybits); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSubpixelPrecisionBiasNV (GLuint xbits, GLuint ybits); +#endif +#endif /* GL_NV_conservative_raster */ + +#ifndef GL_NV_conservative_raster_dilate +#define GL_NV_conservative_raster_dilate 1 +#define GL_CONSERVATIVE_RASTER_DILATE_NV 0x9379 +#define GL_CONSERVATIVE_RASTER_DILATE_RANGE_NV 0x937A +#define GL_CONSERVATIVE_RASTER_DILATE_GRANULARITY_NV 0x937B +typedef void (APIENTRYP PFNGLCONSERVATIVERASTERPARAMETERFNVPROC) (GLenum pname, GLfloat value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glConservativeRasterParameterfNV (GLenum pname, GLfloat value); +#endif +#endif /* GL_NV_conservative_raster_dilate */ + +#ifndef GL_NV_conservative_raster_pre_snap +#define GL_NV_conservative_raster_pre_snap 1 +#define GL_CONSERVATIVE_RASTER_MODE_PRE_SNAP_NV 0x9550 +#endif /* GL_NV_conservative_raster_pre_snap */ + +#ifndef GL_NV_conservative_raster_pre_snap_triangles +#define GL_NV_conservative_raster_pre_snap_triangles 1 +#define GL_CONSERVATIVE_RASTER_MODE_NV 0x954D +#define GL_CONSERVATIVE_RASTER_MODE_POST_SNAP_NV 0x954E +#define GL_CONSERVATIVE_RASTER_MODE_PRE_SNAP_TRIANGLES_NV 0x954F +typedef void (APIENTRYP PFNGLCONSERVATIVERASTERPARAMETERINVPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glConservativeRasterParameteriNV (GLenum pname, GLint param); +#endif +#endif /* GL_NV_conservative_raster_pre_snap_triangles */ + +#ifndef GL_NV_conservative_raster_underestimation +#define GL_NV_conservative_raster_underestimation 1 +#endif /* GL_NV_conservative_raster_underestimation */ + +#ifndef GL_NV_copy_depth_to_color +#define GL_NV_copy_depth_to_color 1 +#define GL_DEPTH_STENCIL_TO_RGBA_NV 0x886E +#define GL_DEPTH_STENCIL_TO_BGRA_NV 0x886F +#endif /* GL_NV_copy_depth_to_color */ + +#ifndef GL_NV_copy_image +#define GL_NV_copy_image 1 +typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATANVPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCopyImageSubDataNV (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +#endif +#endif /* GL_NV_copy_image */ + +#ifndef GL_NV_deep_texture3D +#define GL_NV_deep_texture3D 1 +#define GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV 0x90D0 +#define GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV 0x90D1 +#endif /* GL_NV_deep_texture3D */ + +#ifndef GL_NV_depth_buffer_float +#define GL_NV_depth_buffer_float 1 +#define GL_DEPTH_COMPONENT32F_NV 0x8DAB +#define GL_DEPTH32F_STENCIL8_NV 0x8DAC +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV_NV 0x8DAD +#define GL_DEPTH_BUFFER_FLOAT_MODE_NV 0x8DAF +typedef void (APIENTRYP PFNGLDEPTHRANGEDNVPROC) (GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLCLEARDEPTHDNVPROC) (GLdouble depth); +typedef void (APIENTRYP PFNGLDEPTHBOUNDSDNVPROC) (GLdouble zmin, GLdouble zmax); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDepthRangedNV (GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glClearDepthdNV (GLdouble depth); +GLAPI void APIENTRY glDepthBoundsdNV (GLdouble zmin, GLdouble zmax); +#endif +#endif /* GL_NV_depth_buffer_float */ + +#ifndef GL_NV_depth_clamp +#define GL_NV_depth_clamp 1 +#define GL_DEPTH_CLAMP_NV 0x864F +#endif /* GL_NV_depth_clamp */ + +#ifndef GL_NV_draw_texture +#define GL_NV_draw_texture 1 +typedef void (APIENTRYP PFNGLDRAWTEXTURENVPROC) (GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawTextureNV (GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +#endif +#endif /* GL_NV_draw_texture */ + +#ifndef GL_NV_draw_vulkan_image +#define GL_NV_draw_vulkan_image 1 +typedef void (APIENTRY *GLVULKANPROCNV)(void); +typedef void (APIENTRYP PFNGLDRAWVKIMAGENVPROC) (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +typedef GLVULKANPROCNV (APIENTRYP PFNGLGETVKPROCADDRNVPROC) (const GLchar *name); +typedef void (APIENTRYP PFNGLWAITVKSEMAPHORENVPROC) (GLuint64 vkSemaphore); +typedef void (APIENTRYP PFNGLSIGNALVKSEMAPHORENVPROC) (GLuint64 vkSemaphore); +typedef void (APIENTRYP PFNGLSIGNALVKFENCENVPROC) (GLuint64 vkFence); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawVkImageNV (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +GLAPI GLVULKANPROCNV APIENTRY glGetVkProcAddrNV (const GLchar *name); +GLAPI void APIENTRY glWaitVkSemaphoreNV (GLuint64 vkSemaphore); +GLAPI void APIENTRY glSignalVkSemaphoreNV (GLuint64 vkSemaphore); +GLAPI void APIENTRY glSignalVkFenceNV (GLuint64 vkFence); +#endif +#endif /* GL_NV_draw_vulkan_image */ + +#ifndef GL_NV_evaluators +#define GL_NV_evaluators 1 +#define GL_EVAL_2D_NV 0x86C0 +#define GL_EVAL_TRIANGULAR_2D_NV 0x86C1 +#define GL_MAP_TESSELLATION_NV 0x86C2 +#define GL_MAP_ATTRIB_U_ORDER_NV 0x86C3 +#define GL_MAP_ATTRIB_V_ORDER_NV 0x86C4 +#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5 +#define GL_EVAL_VERTEX_ATTRIB0_NV 0x86C6 +#define GL_EVAL_VERTEX_ATTRIB1_NV 0x86C7 +#define GL_EVAL_VERTEX_ATTRIB2_NV 0x86C8 +#define GL_EVAL_VERTEX_ATTRIB3_NV 0x86C9 +#define GL_EVAL_VERTEX_ATTRIB4_NV 0x86CA +#define GL_EVAL_VERTEX_ATTRIB5_NV 0x86CB +#define GL_EVAL_VERTEX_ATTRIB6_NV 0x86CC +#define GL_EVAL_VERTEX_ATTRIB7_NV 0x86CD +#define GL_EVAL_VERTEX_ATTRIB8_NV 0x86CE +#define GL_EVAL_VERTEX_ATTRIB9_NV 0x86CF +#define GL_EVAL_VERTEX_ATTRIB10_NV 0x86D0 +#define GL_EVAL_VERTEX_ATTRIB11_NV 0x86D1 +#define GL_EVAL_VERTEX_ATTRIB12_NV 0x86D2 +#define GL_EVAL_VERTEX_ATTRIB13_NV 0x86D3 +#define GL_EVAL_VERTEX_ATTRIB14_NV 0x86D4 +#define GL_EVAL_VERTEX_ATTRIB15_NV 0x86D5 +#define GL_MAX_MAP_TESSELLATION_NV 0x86D6 +#define GL_MAX_RATIONAL_EVAL_ORDER_NV 0x86D7 +typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const void *points); +typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, void *points); +typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const void *points); +GLAPI void APIENTRY glMapParameterivNV (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMapParameterfvNV (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, void *points); +GLAPI void APIENTRY glGetMapParameterivNV (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMapParameterfvNV (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum target, GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glEvalMapsNV (GLenum target, GLenum mode); +#endif +#endif /* GL_NV_evaluators */ + +#ifndef GL_NV_explicit_multisample +#define GL_NV_explicit_multisample 1 +#define GL_SAMPLE_POSITION_NV 0x8E50 +#define GL_SAMPLE_MASK_NV 0x8E51 +#define GL_SAMPLE_MASK_VALUE_NV 0x8E52 +#define GL_TEXTURE_BINDING_RENDERBUFFER_NV 0x8E53 +#define GL_TEXTURE_RENDERBUFFER_DATA_STORE_BINDING_NV 0x8E54 +#define GL_TEXTURE_RENDERBUFFER_NV 0x8E55 +#define GL_SAMPLER_RENDERBUFFER_NV 0x8E56 +#define GL_INT_SAMPLER_RENDERBUFFER_NV 0x8E57 +#define GL_UNSIGNED_INT_SAMPLER_RENDERBUFFER_NV 0x8E58 +#define GL_MAX_SAMPLE_MASK_WORDS_NV 0x8E59 +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVNVPROC) (GLenum pname, GLuint index, GLfloat *val); +typedef void (APIENTRYP PFNGLSAMPLEMASKINDEXEDNVPROC) (GLuint index, GLbitfield mask); +typedef void (APIENTRYP PFNGLTEXRENDERBUFFERNVPROC) (GLenum target, GLuint renderbuffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetMultisamplefvNV (GLenum pname, GLuint index, GLfloat *val); +GLAPI void APIENTRY glSampleMaskIndexedNV (GLuint index, GLbitfield mask); +GLAPI void APIENTRY glTexRenderbufferNV (GLenum target, GLuint renderbuffer); +#endif +#endif /* GL_NV_explicit_multisample */ + +#ifndef GL_NV_fence +#define GL_NV_fence 1 +#define GL_ALL_COMPLETED_NV 0x84F2 +#define GL_FENCE_STATUS_NV 0x84F3 +#define GL_FENCE_CONDITION_NV 0x84F4 +typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences); +typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences); +typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences); +GLAPI void APIENTRY glGenFencesNV (GLsizei n, GLuint *fences); +GLAPI GLboolean APIENTRY glIsFenceNV (GLuint fence); +GLAPI GLboolean APIENTRY glTestFenceNV (GLuint fence); +GLAPI void APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params); +GLAPI void APIENTRY glFinishFenceNV (GLuint fence); +GLAPI void APIENTRY glSetFenceNV (GLuint fence, GLenum condition); +#endif +#endif /* GL_NV_fence */ + +#ifndef GL_NV_fill_rectangle +#define GL_NV_fill_rectangle 1 +#define GL_FILL_RECTANGLE_NV 0x933C +#endif /* GL_NV_fill_rectangle */ + +#ifndef GL_NV_float_buffer +#define GL_NV_float_buffer 1 +#define GL_FLOAT_R_NV 0x8880 +#define GL_FLOAT_RG_NV 0x8881 +#define GL_FLOAT_RGB_NV 0x8882 +#define GL_FLOAT_RGBA_NV 0x8883 +#define GL_FLOAT_R16_NV 0x8884 +#define GL_FLOAT_R32_NV 0x8885 +#define GL_FLOAT_RG16_NV 0x8886 +#define GL_FLOAT_RG32_NV 0x8887 +#define GL_FLOAT_RGB16_NV 0x8888 +#define GL_FLOAT_RGB32_NV 0x8889 +#define GL_FLOAT_RGBA16_NV 0x888A +#define GL_FLOAT_RGBA32_NV 0x888B +#define GL_TEXTURE_FLOAT_COMPONENTS_NV 0x888C +#define GL_FLOAT_CLEAR_COLOR_VALUE_NV 0x888D +#define GL_FLOAT_RGBA_MODE_NV 0x888E +#endif /* GL_NV_float_buffer */ + +#ifndef GL_NV_fog_distance +#define GL_NV_fog_distance 1 +#define GL_FOG_DISTANCE_MODE_NV 0x855A +#define GL_EYE_RADIAL_NV 0x855B +#define GL_EYE_PLANE_ABSOLUTE_NV 0x855C +#endif /* GL_NV_fog_distance */ + +#ifndef GL_NV_fragment_coverage_to_color +#define GL_NV_fragment_coverage_to_color 1 +#define GL_FRAGMENT_COVERAGE_TO_COLOR_NV 0x92DD +#define GL_FRAGMENT_COVERAGE_COLOR_NV 0x92DE +typedef void (APIENTRYP PFNGLFRAGMENTCOVERAGECOLORNVPROC) (GLuint color); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFragmentCoverageColorNV (GLuint color); +#endif +#endif /* GL_NV_fragment_coverage_to_color */ + +#ifndef GL_NV_fragment_program +#define GL_NV_fragment_program 1 +#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868 +#define GL_FRAGMENT_PROGRAM_NV 0x8870 +#define GL_MAX_TEXTURE_COORDS_NV 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872 +#define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873 +#define GL_PROGRAM_ERROR_STRING_NV 0x8874 +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v); +typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); +GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v); +GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params); +GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params); +#endif +#endif /* GL_NV_fragment_program */ + +#ifndef GL_NV_fragment_program2 +#define GL_NV_fragment_program2 1 +#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4 +#define GL_MAX_PROGRAM_CALL_DEPTH_NV 0x88F5 +#define GL_MAX_PROGRAM_IF_DEPTH_NV 0x88F6 +#define GL_MAX_PROGRAM_LOOP_DEPTH_NV 0x88F7 +#define GL_MAX_PROGRAM_LOOP_COUNT_NV 0x88F8 +#endif /* GL_NV_fragment_program2 */ + +#ifndef GL_NV_fragment_program4 +#define GL_NV_fragment_program4 1 +#endif /* GL_NV_fragment_program4 */ + +#ifndef GL_NV_fragment_program_option +#define GL_NV_fragment_program_option 1 +#endif /* GL_NV_fragment_program_option */ + +#ifndef GL_NV_fragment_shader_barycentric +#define GL_NV_fragment_shader_barycentric 1 +#endif /* GL_NV_fragment_shader_barycentric */ + +#ifndef GL_NV_fragment_shader_interlock +#define GL_NV_fragment_shader_interlock 1 +#endif /* GL_NV_fragment_shader_interlock */ + +#ifndef GL_NV_framebuffer_mixed_samples +#define GL_NV_framebuffer_mixed_samples 1 +#define GL_COVERAGE_MODULATION_TABLE_NV 0x9331 +#define GL_COLOR_SAMPLES_NV 0x8E20 +#define GL_DEPTH_SAMPLES_NV 0x932D +#define GL_STENCIL_SAMPLES_NV 0x932E +#define GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV 0x932F +#define GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV 0x9330 +#define GL_COVERAGE_MODULATION_NV 0x9332 +#define GL_COVERAGE_MODULATION_TABLE_SIZE_NV 0x9333 +typedef void (APIENTRYP PFNGLCOVERAGEMODULATIONTABLENVPROC) (GLsizei n, const GLfloat *v); +typedef void (APIENTRYP PFNGLGETCOVERAGEMODULATIONTABLENVPROC) (GLsizei bufSize, GLfloat *v); +typedef void (APIENTRYP PFNGLCOVERAGEMODULATIONNVPROC) (GLenum components); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCoverageModulationTableNV (GLsizei n, const GLfloat *v); +GLAPI void APIENTRY glGetCoverageModulationTableNV (GLsizei bufSize, GLfloat *v); +GLAPI void APIENTRY glCoverageModulationNV (GLenum components); +#endif +#endif /* GL_NV_framebuffer_mixed_samples */ + +#ifndef GL_NV_framebuffer_multisample_coverage +#define GL_NV_framebuffer_multisample_coverage 1 +#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB +#define GL_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E10 +#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E11 +#define GL_MULTISAMPLE_COVERAGE_MODES_NV 0x8E12 +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderbufferStorageMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_NV_framebuffer_multisample_coverage */ + +#ifndef GL_NV_geometry_program4 +#define GL_NV_geometry_program4 1 +#define GL_GEOMETRY_PROGRAM_NV 0x8C26 +#define GL_MAX_PROGRAM_OUTPUT_VERTICES_NV 0x8C27 +#define GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV 0x8C28 +typedef void (APIENTRYP PFNGLPROGRAMVERTEXLIMITNVPROC) (GLenum target, GLint limit); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramVertexLimitNV (GLenum target, GLint limit); +GLAPI void APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTextureFaceEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#endif +#endif /* GL_NV_geometry_program4 */ + +#ifndef GL_NV_geometry_shader4 +#define GL_NV_geometry_shader4 1 +#endif /* GL_NV_geometry_shader4 */ + +#ifndef GL_NV_geometry_shader_passthrough +#define GL_NV_geometry_shader_passthrough 1 +#endif /* GL_NV_geometry_shader_passthrough */ + +#ifndef GL_NV_gpu_multicast +#define GL_NV_gpu_multicast 1 +#define GL_PER_GPU_STORAGE_BIT_NV 0x0800 +#define GL_MULTICAST_GPUS_NV 0x92BA +#define GL_RENDER_GPU_MASK_NV 0x9558 +#define GL_PER_GPU_STORAGE_NV 0x9548 +#define GL_MULTICAST_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9549 +typedef void (APIENTRYP PFNGLRENDERGPUMASKNVPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLMULTICASTBUFFERSUBDATANVPROC) (GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +typedef void (APIENTRYP PFNGLMULTICASTCOPYBUFFERSUBDATANVPROC) (GLuint readGpu, GLbitfield writeGpuMask, GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLMULTICASTCOPYIMAGESUBDATANVPROC) (GLuint srcGpu, GLbitfield dstGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +typedef void (APIENTRYP PFNGLMULTICASTBLITFRAMEBUFFERNVPROC) (GLuint srcGpu, GLuint dstGpu, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef void (APIENTRYP PFNGLMULTICASTFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint gpu, GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTICASTBARRIERNVPROC) (void); +typedef void (APIENTRYP PFNGLMULTICASTWAITSYNCNVPROC) (GLuint signalGpu, GLbitfield waitGpuMask); +typedef void (APIENTRYP PFNGLMULTICASTGETQUERYOBJECTIVNVPROC) (GLuint gpu, GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLMULTICASTGETQUERYOBJECTUIVNVPROC) (GLuint gpu, GLuint id, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLMULTICASTGETQUERYOBJECTI64VNVPROC) (GLuint gpu, GLuint id, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLMULTICASTGETQUERYOBJECTUI64VNVPROC) (GLuint gpu, GLuint id, GLenum pname, GLuint64 *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderGpuMaskNV (GLbitfield mask); +GLAPI void APIENTRY glMulticastBufferSubDataNV (GLbitfield gpuMask, GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void APIENTRY glMulticastCopyBufferSubDataNV (GLuint readGpu, GLbitfield writeGpuMask, GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glMulticastCopyImageSubDataNV (GLuint srcGpu, GLbitfield dstGpuMask, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +GLAPI void APIENTRY glMulticastBlitFramebufferNV (GLuint srcGpu, GLuint dstGpu, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI void APIENTRY glMulticastFramebufferSampleLocationsfvNV (GLuint gpu, GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glMulticastBarrierNV (void); +GLAPI void APIENTRY glMulticastWaitSyncNV (GLuint signalGpu, GLbitfield waitGpuMask); +GLAPI void APIENTRY glMulticastGetQueryObjectivNV (GLuint gpu, GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glMulticastGetQueryObjectuivNV (GLuint gpu, GLuint id, GLenum pname, GLuint *params); +GLAPI void APIENTRY glMulticastGetQueryObjecti64vNV (GLuint gpu, GLuint id, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glMulticastGetQueryObjectui64vNV (GLuint gpu, GLuint id, GLenum pname, GLuint64 *params); +#endif +#endif /* GL_NV_gpu_multicast */ + +#ifndef GL_NV_gpu_program4 +#define GL_NV_gpu_program4 1 +#define GL_MIN_PROGRAM_TEXEL_OFFSET_NV 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET_NV 0x8905 +#define GL_PROGRAM_ATTRIB_COMPONENTS_NV 0x8906 +#define GL_PROGRAM_RESULT_COMPONENTS_NV 0x8907 +#define GL_MAX_PROGRAM_ATTRIB_COMPONENTS_NV 0x8908 +#define GL_MAX_PROGRAM_RESULT_COMPONENTS_NV 0x8909 +#define GL_MAX_PROGRAM_GENERIC_ATTRIBS_NV 0x8DA5 +#define GL_MAX_PROGRAM_GENERIC_RESULTS_NV 0x8DA6 +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramLocalParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glProgramLocalParameterI4ivNV (GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glProgramLocalParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramLocalParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glProgramLocalParameterI4uivNV (GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glProgramLocalParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glProgramEnvParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glProgramEnvParameterI4ivNV (GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glProgramEnvParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramEnvParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glProgramEnvParameterI4uivNV (GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glProgramEnvParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetProgramLocalParameterIivNV (GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetProgramLocalParameterIuivNV (GLenum target, GLuint index, GLuint *params); +GLAPI void APIENTRY glGetProgramEnvParameterIivNV (GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetProgramEnvParameterIuivNV (GLenum target, GLuint index, GLuint *params); +#endif +#endif /* GL_NV_gpu_program4 */ + +#ifndef GL_NV_gpu_program5 +#define GL_NV_gpu_program5 1 +#define GL_MAX_GEOMETRY_PROGRAM_INVOCATIONS_NV 0x8E5A +#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5B +#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5C +#define GL_FRAGMENT_PROGRAM_INTERPOLATION_OFFSET_BITS_NV 0x8E5D +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5F +#define GL_MAX_PROGRAM_SUBROUTINE_PARAMETERS_NV 0x8F44 +#define GL_MAX_PROGRAM_SUBROUTINE_NUM_NV 0x8F45 +typedef void (APIENTRYP PFNGLPROGRAMSUBROUTINEPARAMETERSUIVNVPROC) (GLenum target, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSUBROUTINEPARAMETERUIVNVPROC) (GLenum target, GLuint index, GLuint *param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramSubroutineParametersuivNV (GLenum target, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetProgramSubroutineParameteruivNV (GLenum target, GLuint index, GLuint *param); +#endif +#endif /* GL_NV_gpu_program5 */ + +#ifndef GL_NV_gpu_program5_mem_extended +#define GL_NV_gpu_program5_mem_extended 1 +#endif /* GL_NV_gpu_program5_mem_extended */ + +#ifndef GL_NV_gpu_shader5 +#define GL_NV_gpu_shader5 1 +#endif /* GL_NV_gpu_shader5 */ + +#ifndef GL_NV_half_float +#define GL_NV_half_float 1 +typedef unsigned short GLhalfNV; +#define GL_HALF_FLOAT_NV 0x140B +typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y); +typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z); +typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz); +typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha); +typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s); +typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t); +typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r); +typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog); +typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertex2hNV (GLhalfNV x, GLhalfNV y); +GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertex3hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z); +GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertex4hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glNormal3hNV (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz); +GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glColor4hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha); +GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV s); +GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV s, GLhalfNV t); +GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r); +GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum target, GLhalfNV s); +GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum target, GLhalfNV s, GLhalfNV t); +GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r); +GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glFogCoordhNV (GLhalfNV fog); +GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *fog); +GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV weight); +GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *weight); +GLAPI void APIENTRY glVertexAttrib1hNV (GLuint index, GLhalfNV x); +GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib2hNV (GLuint index, GLhalfNV x, GLhalfNV y); +GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib3hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z); +GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib4hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +#endif +#endif /* GL_NV_half_float */ + +#ifndef GL_NV_internalformat_sample_query +#define GL_NV_internalformat_sample_query 1 +#define GL_MULTISAMPLES_NV 0x9371 +#define GL_SUPERSAMPLE_SCALE_X_NV 0x9372 +#define GL_SUPERSAMPLE_SCALE_Y_NV 0x9373 +#define GL_CONFORMANT_NV 0x9374 +typedef void (APIENTRYP PFNGLGETINTERNALFORMATSAMPLEIVNVPROC) (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei count, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetInternalformatSampleivNV (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei count, GLint *params); +#endif +#endif /* GL_NV_internalformat_sample_query */ + +#ifndef GL_NV_light_max_exponent +#define GL_NV_light_max_exponent 1 +#define GL_MAX_SHININESS_NV 0x8504 +#define GL_MAX_SPOT_EXPONENT_NV 0x8505 +#endif /* GL_NV_light_max_exponent */ + +#ifndef GL_NV_memory_attachment +#define GL_NV_memory_attachment 1 +#define GL_ATTACHED_MEMORY_OBJECT_NV 0x95A4 +#define GL_ATTACHED_MEMORY_OFFSET_NV 0x95A5 +#define GL_MEMORY_ATTACHABLE_ALIGNMENT_NV 0x95A6 +#define GL_MEMORY_ATTACHABLE_SIZE_NV 0x95A7 +#define GL_MEMORY_ATTACHABLE_NV 0x95A8 +#define GL_DETACHED_MEMORY_INCARNATION_NV 0x95A9 +#define GL_DETACHED_TEXTURES_NV 0x95AA +#define GL_DETACHED_BUFFERS_NV 0x95AB +#define GL_MAX_DETACHED_TEXTURES_NV 0x95AC +#define GL_MAX_DETACHED_BUFFERS_NV 0x95AD +typedef void (APIENTRYP PFNGLGETMEMORYOBJECTDETACHEDRESOURCESUIVNVPROC) (GLuint memory, GLenum pname, GLint first, GLsizei count, GLuint *params); +typedef void (APIENTRYP PFNGLRESETMEMORYOBJECTPARAMETERNVPROC) (GLuint memory, GLenum pname); +typedef void (APIENTRYP PFNGLTEXATTACHMEMORYNVPROC) (GLenum target, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLBUFFERATTACHMEMORYNVPROC) (GLenum target, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLTEXTUREATTACHMEMORYNVPROC) (GLuint texture, GLuint memory, GLuint64 offset); +typedef void (APIENTRYP PFNGLNAMEDBUFFERATTACHMEMORYNVPROC) (GLuint buffer, GLuint memory, GLuint64 offset); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetMemoryObjectDetachedResourcesuivNV (GLuint memory, GLenum pname, GLint first, GLsizei count, GLuint *params); +GLAPI void APIENTRY glResetMemoryObjectParameterNV (GLuint memory, GLenum pname); +GLAPI void APIENTRY glTexAttachMemoryNV (GLenum target, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glBufferAttachMemoryNV (GLenum target, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glTextureAttachMemoryNV (GLuint texture, GLuint memory, GLuint64 offset); +GLAPI void APIENTRY glNamedBufferAttachMemoryNV (GLuint buffer, GLuint memory, GLuint64 offset); +#endif +#endif /* GL_NV_memory_attachment */ + +#ifndef GL_NV_memory_object_sparse +#define GL_NV_memory_object_sparse 1 +typedef void (APIENTRYP PFNGLBUFFERPAGECOMMITMENTMEMNVPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit); +typedef void (APIENTRYP PFNGLTEXPAGECOMMITMENTMEMNVPROC) (GLenum target, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit); +typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTMEMNVPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit); +typedef void (APIENTRYP PFNGLTEXTUREPAGECOMMITMENTMEMNVPROC) (GLuint texture, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferPageCommitmentMemNV (GLenum target, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit); +GLAPI void APIENTRY glTexPageCommitmentMemNV (GLenum target, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit); +GLAPI void APIENTRY glNamedBufferPageCommitmentMemNV (GLuint buffer, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit); +GLAPI void APIENTRY glTexturePageCommitmentMemNV (GLuint texture, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit); +#endif +#endif /* GL_NV_memory_object_sparse */ + +#ifndef GL_NV_mesh_shader +#define GL_NV_mesh_shader 1 +#define GL_MESH_SHADER_NV 0x9559 +#define GL_TASK_SHADER_NV 0x955A +#define GL_MAX_MESH_UNIFORM_BLOCKS_NV 0x8E60 +#define GL_MAX_MESH_TEXTURE_IMAGE_UNITS_NV 0x8E61 +#define GL_MAX_MESH_IMAGE_UNIFORMS_NV 0x8E62 +#define GL_MAX_MESH_UNIFORM_COMPONENTS_NV 0x8E63 +#define GL_MAX_MESH_ATOMIC_COUNTER_BUFFERS_NV 0x8E64 +#define GL_MAX_MESH_ATOMIC_COUNTERS_NV 0x8E65 +#define GL_MAX_MESH_SHADER_STORAGE_BLOCKS_NV 0x8E66 +#define GL_MAX_COMBINED_MESH_UNIFORM_COMPONENTS_NV 0x8E67 +#define GL_MAX_TASK_UNIFORM_BLOCKS_NV 0x8E68 +#define GL_MAX_TASK_TEXTURE_IMAGE_UNITS_NV 0x8E69 +#define GL_MAX_TASK_IMAGE_UNIFORMS_NV 0x8E6A +#define GL_MAX_TASK_UNIFORM_COMPONENTS_NV 0x8E6B +#define GL_MAX_TASK_ATOMIC_COUNTER_BUFFERS_NV 0x8E6C +#define GL_MAX_TASK_ATOMIC_COUNTERS_NV 0x8E6D +#define GL_MAX_TASK_SHADER_STORAGE_BLOCKS_NV 0x8E6E +#define GL_MAX_COMBINED_TASK_UNIFORM_COMPONENTS_NV 0x8E6F +#define GL_MAX_MESH_WORK_GROUP_INVOCATIONS_NV 0x95A2 +#define GL_MAX_TASK_WORK_GROUP_INVOCATIONS_NV 0x95A3 +#define GL_MAX_MESH_TOTAL_MEMORY_SIZE_NV 0x9536 +#define GL_MAX_TASK_TOTAL_MEMORY_SIZE_NV 0x9537 +#define GL_MAX_MESH_OUTPUT_VERTICES_NV 0x9538 +#define GL_MAX_MESH_OUTPUT_PRIMITIVES_NV 0x9539 +#define GL_MAX_TASK_OUTPUT_COUNT_NV 0x953A +#define GL_MAX_DRAW_MESH_TASKS_COUNT_NV 0x953D +#define GL_MAX_MESH_VIEWS_NV 0x9557 +#define GL_MESH_OUTPUT_PER_VERTEX_GRANULARITY_NV 0x92DF +#define GL_MESH_OUTPUT_PER_PRIMITIVE_GRANULARITY_NV 0x9543 +#define GL_MAX_MESH_WORK_GROUP_SIZE_NV 0x953B +#define GL_MAX_TASK_WORK_GROUP_SIZE_NV 0x953C +#define GL_MESH_WORK_GROUP_SIZE_NV 0x953E +#define GL_TASK_WORK_GROUP_SIZE_NV 0x953F +#define GL_MESH_VERTICES_OUT_NV 0x9579 +#define GL_MESH_PRIMITIVES_OUT_NV 0x957A +#define GL_MESH_OUTPUT_TYPE_NV 0x957B +#define GL_UNIFORM_BLOCK_REFERENCED_BY_MESH_SHADER_NV 0x959C +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TASK_SHADER_NV 0x959D +#define GL_REFERENCED_BY_MESH_SHADER_NV 0x95A0 +#define GL_REFERENCED_BY_TASK_SHADER_NV 0x95A1 +#define GL_MESH_SHADER_BIT_NV 0x00000040 +#define GL_TASK_SHADER_BIT_NV 0x00000080 +#define GL_MESH_SUBROUTINE_NV 0x957C +#define GL_TASK_SUBROUTINE_NV 0x957D +#define GL_MESH_SUBROUTINE_UNIFORM_NV 0x957E +#define GL_TASK_SUBROUTINE_UNIFORM_NV 0x957F +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_MESH_SHADER_NV 0x959E +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TASK_SHADER_NV 0x959F +typedef void (APIENTRYP PFNGLDRAWMESHTASKSNVPROC) (GLuint first, GLuint count); +typedef void (APIENTRYP PFNGLDRAWMESHTASKSINDIRECTNVPROC) (GLintptr indirect); +typedef void (APIENTRYP PFNGLMULTIDRAWMESHTASKSINDIRECTNVPROC) (GLintptr indirect, GLsizei drawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWMESHTASKSINDIRECTCOUNTNVPROC) (GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawMeshTasksNV (GLuint first, GLuint count); +GLAPI void APIENTRY glDrawMeshTasksIndirectNV (GLintptr indirect); +GLAPI void APIENTRY glMultiDrawMeshTasksIndirectNV (GLintptr indirect, GLsizei drawcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawMeshTasksIndirectCountNV (GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#endif +#endif /* GL_NV_mesh_shader */ + +#ifndef GL_NV_multisample_coverage +#define GL_NV_multisample_coverage 1 +#endif /* GL_NV_multisample_coverage */ + +#ifndef GL_NV_multisample_filter_hint +#define GL_NV_multisample_filter_hint 1 +#define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534 +#endif /* GL_NV_multisample_filter_hint */ + +#ifndef GL_NV_occlusion_query +#define GL_NV_occlusion_query 1 +#define GL_PIXEL_COUNTER_BITS_NV 0x8864 +#define GL_CURRENT_OCCLUSION_QUERY_ID_NV 0x8865 +#define GL_PIXEL_COUNT_NV 0x8866 +#define GL_PIXEL_COUNT_AVAILABLE_NV 0x8867 +typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void); +typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint id); +GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint id); +GLAPI void APIENTRY glEndOcclusionQueryNV (void); +GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint id, GLenum pname, GLuint *params); +#endif +#endif /* GL_NV_occlusion_query */ + +#ifndef GL_NV_packed_depth_stencil +#define GL_NV_packed_depth_stencil 1 +#define GL_DEPTH_STENCIL_NV 0x84F9 +#define GL_UNSIGNED_INT_24_8_NV 0x84FA +#endif /* GL_NV_packed_depth_stencil */ + +#ifndef GL_NV_parameter_buffer_object +#define GL_NV_parameter_buffer_object 1 +#define GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV 0x8DA0 +#define GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV 0x8DA1 +#define GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV 0x8DA2 +#define GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV 0x8DA3 +#define GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV 0x8DA4 +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSFVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIIVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIUIVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramBufferParametersfvNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glProgramBufferParametersIivNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramBufferParametersIuivNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLuint *params); +#endif +#endif /* GL_NV_parameter_buffer_object */ + +#ifndef GL_NV_parameter_buffer_object2 +#define GL_NV_parameter_buffer_object2 1 +#endif /* GL_NV_parameter_buffer_object2 */ + +#ifndef GL_NV_path_rendering +#define GL_NV_path_rendering 1 +#define GL_PATH_FORMAT_SVG_NV 0x9070 +#define GL_PATH_FORMAT_PS_NV 0x9071 +#define GL_STANDARD_FONT_NAME_NV 0x9072 +#define GL_SYSTEM_FONT_NAME_NV 0x9073 +#define GL_FILE_NAME_NV 0x9074 +#define GL_PATH_STROKE_WIDTH_NV 0x9075 +#define GL_PATH_END_CAPS_NV 0x9076 +#define GL_PATH_INITIAL_END_CAP_NV 0x9077 +#define GL_PATH_TERMINAL_END_CAP_NV 0x9078 +#define GL_PATH_JOIN_STYLE_NV 0x9079 +#define GL_PATH_MITER_LIMIT_NV 0x907A +#define GL_PATH_DASH_CAPS_NV 0x907B +#define GL_PATH_INITIAL_DASH_CAP_NV 0x907C +#define GL_PATH_TERMINAL_DASH_CAP_NV 0x907D +#define GL_PATH_DASH_OFFSET_NV 0x907E +#define GL_PATH_CLIENT_LENGTH_NV 0x907F +#define GL_PATH_FILL_MODE_NV 0x9080 +#define GL_PATH_FILL_MASK_NV 0x9081 +#define GL_PATH_FILL_COVER_MODE_NV 0x9082 +#define GL_PATH_STROKE_COVER_MODE_NV 0x9083 +#define GL_PATH_STROKE_MASK_NV 0x9084 +#define GL_COUNT_UP_NV 0x9088 +#define GL_COUNT_DOWN_NV 0x9089 +#define GL_PATH_OBJECT_BOUNDING_BOX_NV 0x908A +#define GL_CONVEX_HULL_NV 0x908B +#define GL_BOUNDING_BOX_NV 0x908D +#define GL_TRANSLATE_X_NV 0x908E +#define GL_TRANSLATE_Y_NV 0x908F +#define GL_TRANSLATE_2D_NV 0x9090 +#define GL_TRANSLATE_3D_NV 0x9091 +#define GL_AFFINE_2D_NV 0x9092 +#define GL_AFFINE_3D_NV 0x9094 +#define GL_TRANSPOSE_AFFINE_2D_NV 0x9096 +#define GL_TRANSPOSE_AFFINE_3D_NV 0x9098 +#define GL_UTF8_NV 0x909A +#define GL_UTF16_NV 0x909B +#define GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV 0x909C +#define GL_PATH_COMMAND_COUNT_NV 0x909D +#define GL_PATH_COORD_COUNT_NV 0x909E +#define GL_PATH_DASH_ARRAY_COUNT_NV 0x909F +#define GL_PATH_COMPUTED_LENGTH_NV 0x90A0 +#define GL_PATH_FILL_BOUNDING_BOX_NV 0x90A1 +#define GL_PATH_STROKE_BOUNDING_BOX_NV 0x90A2 +#define GL_SQUARE_NV 0x90A3 +#define GL_ROUND_NV 0x90A4 +#define GL_TRIANGULAR_NV 0x90A5 +#define GL_BEVEL_NV 0x90A6 +#define GL_MITER_REVERT_NV 0x90A7 +#define GL_MITER_TRUNCATE_NV 0x90A8 +#define GL_SKIP_MISSING_GLYPH_NV 0x90A9 +#define GL_USE_MISSING_GLYPH_NV 0x90AA +#define GL_PATH_ERROR_POSITION_NV 0x90AB +#define GL_ACCUM_ADJACENT_PAIRS_NV 0x90AD +#define GL_ADJACENT_PAIRS_NV 0x90AE +#define GL_FIRST_TO_REST_NV 0x90AF +#define GL_PATH_GEN_MODE_NV 0x90B0 +#define GL_PATH_GEN_COEFF_NV 0x90B1 +#define GL_PATH_GEN_COMPONENTS_NV 0x90B3 +#define GL_PATH_STENCIL_FUNC_NV 0x90B7 +#define GL_PATH_STENCIL_REF_NV 0x90B8 +#define GL_PATH_STENCIL_VALUE_MASK_NV 0x90B9 +#define GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV 0x90BD +#define GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV 0x90BE +#define GL_PATH_COVER_DEPTH_FUNC_NV 0x90BF +#define GL_PATH_DASH_OFFSET_RESET_NV 0x90B4 +#define GL_MOVE_TO_RESETS_NV 0x90B5 +#define GL_MOVE_TO_CONTINUES_NV 0x90B6 +#define GL_CLOSE_PATH_NV 0x00 +#define GL_MOVE_TO_NV 0x02 +#define GL_RELATIVE_MOVE_TO_NV 0x03 +#define GL_LINE_TO_NV 0x04 +#define GL_RELATIVE_LINE_TO_NV 0x05 +#define GL_HORIZONTAL_LINE_TO_NV 0x06 +#define GL_RELATIVE_HORIZONTAL_LINE_TO_NV 0x07 +#define GL_VERTICAL_LINE_TO_NV 0x08 +#define GL_RELATIVE_VERTICAL_LINE_TO_NV 0x09 +#define GL_QUADRATIC_CURVE_TO_NV 0x0A +#define GL_RELATIVE_QUADRATIC_CURVE_TO_NV 0x0B +#define GL_CUBIC_CURVE_TO_NV 0x0C +#define GL_RELATIVE_CUBIC_CURVE_TO_NV 0x0D +#define GL_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0E +#define GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0F +#define GL_SMOOTH_CUBIC_CURVE_TO_NV 0x10 +#define GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV 0x11 +#define GL_SMALL_CCW_ARC_TO_NV 0x12 +#define GL_RELATIVE_SMALL_CCW_ARC_TO_NV 0x13 +#define GL_SMALL_CW_ARC_TO_NV 0x14 +#define GL_RELATIVE_SMALL_CW_ARC_TO_NV 0x15 +#define GL_LARGE_CCW_ARC_TO_NV 0x16 +#define GL_RELATIVE_LARGE_CCW_ARC_TO_NV 0x17 +#define GL_LARGE_CW_ARC_TO_NV 0x18 +#define GL_RELATIVE_LARGE_CW_ARC_TO_NV 0x19 +#define GL_RESTART_PATH_NV 0xF0 +#define GL_DUP_FIRST_CUBIC_CURVE_TO_NV 0xF2 +#define GL_DUP_LAST_CUBIC_CURVE_TO_NV 0xF4 +#define GL_RECT_NV 0xF6 +#define GL_CIRCULAR_CCW_ARC_TO_NV 0xF8 +#define GL_CIRCULAR_CW_ARC_TO_NV 0xFA +#define GL_CIRCULAR_TANGENT_ARC_TO_NV 0xFC +#define GL_ARC_TO_NV 0xFE +#define GL_RELATIVE_ARC_TO_NV 0xFF +#define GL_BOLD_BIT_NV 0x01 +#define GL_ITALIC_BIT_NV 0x02 +#define GL_GLYPH_WIDTH_BIT_NV 0x01 +#define GL_GLYPH_HEIGHT_BIT_NV 0x02 +#define GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV 0x04 +#define GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV 0x08 +#define GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV 0x10 +#define GL_GLYPH_VERTICAL_BEARING_X_BIT_NV 0x20 +#define GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV 0x40 +#define GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV 0x80 +#define GL_GLYPH_HAS_KERNING_BIT_NV 0x100 +#define GL_FONT_X_MIN_BOUNDS_BIT_NV 0x00010000 +#define GL_FONT_Y_MIN_BOUNDS_BIT_NV 0x00020000 +#define GL_FONT_X_MAX_BOUNDS_BIT_NV 0x00040000 +#define GL_FONT_Y_MAX_BOUNDS_BIT_NV 0x00080000 +#define GL_FONT_UNITS_PER_EM_BIT_NV 0x00100000 +#define GL_FONT_ASCENDER_BIT_NV 0x00200000 +#define GL_FONT_DESCENDER_BIT_NV 0x00400000 +#define GL_FONT_HEIGHT_BIT_NV 0x00800000 +#define GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV 0x01000000 +#define GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV 0x02000000 +#define GL_FONT_UNDERLINE_POSITION_BIT_NV 0x04000000 +#define GL_FONT_UNDERLINE_THICKNESS_BIT_NV 0x08000000 +#define GL_FONT_HAS_KERNING_BIT_NV 0x10000000 +#define GL_ROUNDED_RECT_NV 0xE8 +#define GL_RELATIVE_ROUNDED_RECT_NV 0xE9 +#define GL_ROUNDED_RECT2_NV 0xEA +#define GL_RELATIVE_ROUNDED_RECT2_NV 0xEB +#define GL_ROUNDED_RECT4_NV 0xEC +#define GL_RELATIVE_ROUNDED_RECT4_NV 0xED +#define GL_ROUNDED_RECT8_NV 0xEE +#define GL_RELATIVE_ROUNDED_RECT8_NV 0xEF +#define GL_RELATIVE_RECT_NV 0xF7 +#define GL_FONT_GLYPHS_AVAILABLE_NV 0x9368 +#define GL_FONT_TARGET_UNAVAILABLE_NV 0x9369 +#define GL_FONT_UNAVAILABLE_NV 0x936A +#define GL_FONT_UNINTELLIGIBLE_NV 0x936B +#define GL_CONIC_CURVE_TO_NV 0x1A +#define GL_RELATIVE_CONIC_CURVE_TO_NV 0x1B +#define GL_FONT_NUM_GLYPH_INDICES_BIT_NV 0x20000000 +#define GL_STANDARD_FONT_FORMAT_NV 0x936C +#define GL_2_BYTES_NV 0x1407 +#define GL_3_BYTES_NV 0x1408 +#define GL_4_BYTES_NV 0x1409 +#define GL_EYE_LINEAR_NV 0x2400 +#define GL_OBJECT_LINEAR_NV 0x2401 +#define GL_CONSTANT_NV 0x8576 +#define GL_PATH_FOG_GEN_MODE_NV 0x90AC +#define GL_PRIMARY_COLOR_NV 0x852C +#define GL_SECONDARY_COLOR_NV 0x852D +#define GL_PATH_GEN_COLOR_FORMAT_NV 0x90B2 +#define GL_PATH_PROJECTION_NV 0x1701 +#define GL_PATH_MODELVIEW_NV 0x1700 +#define GL_PATH_MODELVIEW_STACK_DEPTH_NV 0x0BA3 +#define GL_PATH_MODELVIEW_MATRIX_NV 0x0BA6 +#define GL_PATH_MAX_MODELVIEW_STACK_DEPTH_NV 0x0D36 +#define GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV 0x84E3 +#define GL_PATH_PROJECTION_STACK_DEPTH_NV 0x0BA4 +#define GL_PATH_PROJECTION_MATRIX_NV 0x0BA7 +#define GL_PATH_MAX_PROJECTION_STACK_DEPTH_NV 0x0D38 +#define GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV 0x84E4 +#define GL_FRAGMENT_INPUT_NV 0x936D +typedef GLuint (APIENTRYP PFNGLGENPATHSNVPROC) (GLsizei range); +typedef void (APIENTRYP PFNGLDELETEPATHSNVPROC) (GLuint path, GLsizei range); +typedef GLboolean (APIENTRYP PFNGLISPATHNVPROC) (GLuint path); +typedef void (APIENTRYP PFNGLPATHCOMMANDSNVPROC) (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHCOORDSNVPROC) (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSUBCOMMANDSNVPROC) (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSUBCOORDSNVPROC) (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSTRINGNVPROC) (GLuint path, GLenum format, GLsizei length, const void *pathString); +typedef void (APIENTRYP PFNGLPATHGLYPHSNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLPATHGLYPHRANGENVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLWEIGHTPATHSNVPROC) (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); +typedef void (APIENTRYP PFNGLCOPYPATHNVPROC) (GLuint resultPath, GLuint srcPath); +typedef void (APIENTRYP PFNGLINTERPOLATEPATHSNVPROC) (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); +typedef void (APIENTRYP PFNGLTRANSFORMPATHNVPROC) (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, const GLint *value); +typedef void (APIENTRYP PFNGLPATHPARAMETERINVPROC) (GLuint path, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, const GLfloat *value); +typedef void (APIENTRYP PFNGLPATHPARAMETERFNVPROC) (GLuint path, GLenum pname, GLfloat value); +typedef void (APIENTRYP PFNGLPATHDASHARRAYNVPROC) (GLuint path, GLsizei dashCount, const GLfloat *dashArray); +typedef void (APIENTRYP PFNGLPATHSTENCILFUNCNVPROC) (GLenum func, GLint ref, GLuint mask); +typedef void (APIENTRYP PFNGLPATHSTENCILDEPTHOFFSETNVPROC) (GLfloat factor, GLfloat units); +typedef void (APIENTRYP PFNGLSTENCILFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLPATHCOVERDEPTHFUNCNVPROC) (GLenum func); +typedef void (APIENTRYP PFNGLCOVERFILLPATHNVPROC) (GLuint path, GLenum coverMode); +typedef void (APIENTRYP PFNGLCOVERSTROKEPATHNVPROC) (GLuint path, GLenum coverMode); +typedef void (APIENTRYP PFNGLCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLGETPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, GLfloat *value); +typedef void (APIENTRYP PFNGLGETPATHCOMMANDSNVPROC) (GLuint path, GLubyte *commands); +typedef void (APIENTRYP PFNGLGETPATHCOORDSNVPROC) (GLuint path, GLfloat *coords); +typedef void (APIENTRYP PFNGLGETPATHDASHARRAYNVPROC) (GLuint path, GLfloat *dashArray); +typedef void (APIENTRYP PFNGLGETPATHMETRICSNVPROC) (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); +typedef void (APIENTRYP PFNGLGETPATHMETRICRANGENVPROC) (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); +typedef void (APIENTRYP PFNGLGETPATHSPACINGNVPROC) (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); +typedef GLboolean (APIENTRYP PFNGLISPOINTINFILLPATHNVPROC) (GLuint path, GLuint mask, GLfloat x, GLfloat y); +typedef GLboolean (APIENTRYP PFNGLISPOINTINSTROKEPATHNVPROC) (GLuint path, GLfloat x, GLfloat y); +typedef GLfloat (APIENTRYP PFNGLGETPATHLENGTHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments); +typedef GLboolean (APIENTRYP PFNGLPOINTALONGPATHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); +typedef void (APIENTRYP PFNGLMATRIXLOAD3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOAD3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULT3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULT3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask, GLenum coverMode); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef GLenum (APIENTRYP PFNGLPATHGLYPHINDEXRANGENVPROC) (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint *baseAndCount); +typedef GLenum (APIENTRYP PFNGLPATHGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef GLenum (APIENTRYP PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC) (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEFVNVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLfloat *params); +typedef void (APIENTRYP PFNGLPATHCOLORGENNVPROC) (GLenum color, GLenum genMode, GLenum colorFormat, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLPATHTEXGENNVPROC) (GLenum texCoordSet, GLenum genMode, GLint components, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLPATHFOGGENNVPROC) (GLenum genMode); +typedef void (APIENTRYP PFNGLGETPATHCOLORGENIVNVPROC) (GLenum color, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHCOLORGENFVNVPROC) (GLenum color, GLenum pname, GLfloat *value); +typedef void (APIENTRYP PFNGLGETPATHTEXGENIVNVPROC) (GLenum texCoordSet, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHTEXGENFVNVPROC) (GLenum texCoordSet, GLenum pname, GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glGenPathsNV (GLsizei range); +GLAPI void APIENTRY glDeletePathsNV (GLuint path, GLsizei range); +GLAPI GLboolean APIENTRY glIsPathNV (GLuint path); +GLAPI void APIENTRY glPathCommandsNV (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathCoordsNV (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathSubCommandsNV (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathSubCoordsNV (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathStringNV (GLuint path, GLenum format, GLsizei length, const void *pathString); +GLAPI void APIENTRY glPathGlyphsNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glPathGlyphRangeNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glWeightPathsNV (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); +GLAPI void APIENTRY glCopyPathNV (GLuint resultPath, GLuint srcPath); +GLAPI void APIENTRY glInterpolatePathsNV (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); +GLAPI void APIENTRY glTransformPathNV (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glPathParameterivNV (GLuint path, GLenum pname, const GLint *value); +GLAPI void APIENTRY glPathParameteriNV (GLuint path, GLenum pname, GLint value); +GLAPI void APIENTRY glPathParameterfvNV (GLuint path, GLenum pname, const GLfloat *value); +GLAPI void APIENTRY glPathParameterfNV (GLuint path, GLenum pname, GLfloat value); +GLAPI void APIENTRY glPathDashArrayNV (GLuint path, GLsizei dashCount, const GLfloat *dashArray); +GLAPI void APIENTRY glPathStencilFuncNV (GLenum func, GLint ref, GLuint mask); +GLAPI void APIENTRY glPathStencilDepthOffsetNV (GLfloat factor, GLfloat units); +GLAPI void APIENTRY glStencilFillPathNV (GLuint path, GLenum fillMode, GLuint mask); +GLAPI void APIENTRY glStencilStrokePathNV (GLuint path, GLint reference, GLuint mask); +GLAPI void APIENTRY glStencilFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glStencilStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glPathCoverDepthFuncNV (GLenum func); +GLAPI void APIENTRY glCoverFillPathNV (GLuint path, GLenum coverMode); +GLAPI void APIENTRY glCoverStrokePathNV (GLuint path, GLenum coverMode); +GLAPI void APIENTRY glCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glGetPathParameterivNV (GLuint path, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathParameterfvNV (GLuint path, GLenum pname, GLfloat *value); +GLAPI void APIENTRY glGetPathCommandsNV (GLuint path, GLubyte *commands); +GLAPI void APIENTRY glGetPathCoordsNV (GLuint path, GLfloat *coords); +GLAPI void APIENTRY glGetPathDashArrayNV (GLuint path, GLfloat *dashArray); +GLAPI void APIENTRY glGetPathMetricsNV (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); +GLAPI void APIENTRY glGetPathMetricRangeNV (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); +GLAPI void APIENTRY glGetPathSpacingNV (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); +GLAPI GLboolean APIENTRY glIsPointInFillPathNV (GLuint path, GLuint mask, GLfloat x, GLfloat y); +GLAPI GLboolean APIENTRY glIsPointInStrokePathNV (GLuint path, GLfloat x, GLfloat y); +GLAPI GLfloat APIENTRY glGetPathLengthNV (GLuint path, GLsizei startSegment, GLsizei numSegments); +GLAPI GLboolean APIENTRY glPointAlongPathNV (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); +GLAPI void APIENTRY glMatrixLoad3x2fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoad3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoadTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMult3x2fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMult3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glStencilThenCoverFillPathNV (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); +GLAPI void APIENTRY glStencilThenCoverStrokePathNV (GLuint path, GLint reference, GLuint mask, GLenum coverMode); +GLAPI void APIENTRY glStencilThenCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glStencilThenCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI GLenum APIENTRY glPathGlyphIndexRangeNV (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint *baseAndCount); +GLAPI GLenum APIENTRY glPathGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI GLenum APIENTRY glPathMemoryGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glProgramPathFragmentInputGenNV (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); +GLAPI void APIENTRY glGetProgramResourcefvNV (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLfloat *params); +GLAPI void APIENTRY glPathColorGenNV (GLenum color, GLenum genMode, GLenum colorFormat, const GLfloat *coeffs); +GLAPI void APIENTRY glPathTexGenNV (GLenum texCoordSet, GLenum genMode, GLint components, const GLfloat *coeffs); +GLAPI void APIENTRY glPathFogGenNV (GLenum genMode); +GLAPI void APIENTRY glGetPathColorGenivNV (GLenum color, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathColorGenfvNV (GLenum color, GLenum pname, GLfloat *value); +GLAPI void APIENTRY glGetPathTexGenivNV (GLenum texCoordSet, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathTexGenfvNV (GLenum texCoordSet, GLenum pname, GLfloat *value); +#endif +#endif /* GL_NV_path_rendering */ + +#ifndef GL_NV_path_rendering_shared_edge +#define GL_NV_path_rendering_shared_edge 1 +#define GL_SHARED_EDGE_NV 0xC0 +#endif /* GL_NV_path_rendering_shared_edge */ + +#ifndef GL_NV_pixel_data_range +#define GL_NV_pixel_data_range 1 +#define GL_WRITE_PIXEL_DATA_RANGE_NV 0x8878 +#define GL_READ_PIXEL_DATA_RANGE_NV 0x8879 +#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A +#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B +#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C +#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D +typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, const void *pointer); +typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelDataRangeNV (GLenum target, GLsizei length, const void *pointer); +GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum target); +#endif +#endif /* GL_NV_pixel_data_range */ + +#ifndef GL_NV_point_sprite +#define GL_NV_point_sprite 1 +#define GL_POINT_SPRITE_NV 0x8861 +#define GL_COORD_REPLACE_NV 0x8862 +#define GL_POINT_SPRITE_R_MODE_NV 0x8863 +typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameteriNV (GLenum pname, GLint param); +GLAPI void APIENTRY glPointParameterivNV (GLenum pname, const GLint *params); +#endif +#endif /* GL_NV_point_sprite */ + +#ifndef GL_NV_present_video +#define GL_NV_present_video 1 +#define GL_FRAME_NV 0x8E26 +#define GL_FIELDS_NV 0x8E27 +#define GL_CURRENT_TIME_NV 0x8E28 +#define GL_NUM_FILL_STREAMS_NV 0x8E29 +#define GL_PRESENT_TIME_NV 0x8E2A +#define GL_PRESENT_DURATION_NV 0x8E2B +typedef void (APIENTRYP PFNGLPRESENTFRAMEKEYEDNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1); +typedef void (APIENTRYP PFNGLPRESENTFRAMEDUALFILLNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3); +typedef void (APIENTRYP PFNGLGETVIDEOIVNVPROC) (GLuint video_slot, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOUIVNVPROC) (GLuint video_slot, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLGETVIDEOI64VNVPROC) (GLuint video_slot, GLenum pname, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETVIDEOUI64VNVPROC) (GLuint video_slot, GLenum pname, GLuint64EXT *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPresentFrameKeyedNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1); +GLAPI void APIENTRY glPresentFrameDualFillNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3); +GLAPI void APIENTRY glGetVideoivNV (GLuint video_slot, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideouivNV (GLuint video_slot, GLenum pname, GLuint *params); +GLAPI void APIENTRY glGetVideoi64vNV (GLuint video_slot, GLenum pname, GLint64EXT *params); +GLAPI void APIENTRY glGetVideoui64vNV (GLuint video_slot, GLenum pname, GLuint64EXT *params); +#endif +#endif /* GL_NV_present_video */ + +#ifndef GL_NV_primitive_restart +#define GL_NV_primitive_restart 1 +#define GL_PRIMITIVE_RESTART_NV 0x8558 +#define GL_PRIMITIVE_RESTART_INDEX_NV 0x8559 +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void); +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPrimitiveRestartNV (void); +GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint index); +#endif +#endif /* GL_NV_primitive_restart */ + +#ifndef GL_NV_primitive_shading_rate +#define GL_NV_primitive_shading_rate 1 +#define GL_SHADING_RATE_IMAGE_PER_PRIMITIVE_NV 0x95B1 +#define GL_SHADING_RATE_IMAGE_PALETTE_COUNT_NV 0x95B2 +#endif /* GL_NV_primitive_shading_rate */ + +#ifndef GL_NV_query_resource +#define GL_NV_query_resource 1 +#define GL_QUERY_RESOURCE_TYPE_VIDMEM_ALLOC_NV 0x9540 +#define GL_QUERY_RESOURCE_MEMTYPE_VIDMEM_NV 0x9542 +#define GL_QUERY_RESOURCE_SYS_RESERVED_NV 0x9544 +#define GL_QUERY_RESOURCE_TEXTURE_NV 0x9545 +#define GL_QUERY_RESOURCE_RENDERBUFFER_NV 0x9546 +#define GL_QUERY_RESOURCE_BUFFEROBJECT_NV 0x9547 +typedef GLint (APIENTRYP PFNGLQUERYRESOURCENVPROC) (GLenum queryType, GLint tagId, GLuint count, GLint *buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLint APIENTRY glQueryResourceNV (GLenum queryType, GLint tagId, GLuint count, GLint *buffer); +#endif +#endif /* GL_NV_query_resource */ + +#ifndef GL_NV_query_resource_tag +#define GL_NV_query_resource_tag 1 +typedef void (APIENTRYP PFNGLGENQUERYRESOURCETAGNVPROC) (GLsizei n, GLint *tagIds); +typedef void (APIENTRYP PFNGLDELETEQUERYRESOURCETAGNVPROC) (GLsizei n, const GLint *tagIds); +typedef void (APIENTRYP PFNGLQUERYRESOURCETAGNVPROC) (GLint tagId, const GLchar *tagString); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueryResourceTagNV (GLsizei n, GLint *tagIds); +GLAPI void APIENTRY glDeleteQueryResourceTagNV (GLsizei n, const GLint *tagIds); +GLAPI void APIENTRY glQueryResourceTagNV (GLint tagId, const GLchar *tagString); +#endif +#endif /* GL_NV_query_resource_tag */ + +#ifndef GL_NV_register_combiners +#define GL_NV_register_combiners 1 +#define GL_REGISTER_COMBINERS_NV 0x8522 +#define GL_VARIABLE_A_NV 0x8523 +#define GL_VARIABLE_B_NV 0x8524 +#define GL_VARIABLE_C_NV 0x8525 +#define GL_VARIABLE_D_NV 0x8526 +#define GL_VARIABLE_E_NV 0x8527 +#define GL_VARIABLE_F_NV 0x8528 +#define GL_VARIABLE_G_NV 0x8529 +#define GL_CONSTANT_COLOR0_NV 0x852A +#define GL_CONSTANT_COLOR1_NV 0x852B +#define GL_SPARE0_NV 0x852E +#define GL_SPARE1_NV 0x852F +#define GL_DISCARD_NV 0x8530 +#define GL_E_TIMES_F_NV 0x8531 +#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532 +#define GL_UNSIGNED_IDENTITY_NV 0x8536 +#define GL_UNSIGNED_INVERT_NV 0x8537 +#define GL_EXPAND_NORMAL_NV 0x8538 +#define GL_EXPAND_NEGATE_NV 0x8539 +#define GL_HALF_BIAS_NORMAL_NV 0x853A +#define GL_HALF_BIAS_NEGATE_NV 0x853B +#define GL_SIGNED_IDENTITY_NV 0x853C +#define GL_SIGNED_NEGATE_NV 0x853D +#define GL_SCALE_BY_TWO_NV 0x853E +#define GL_SCALE_BY_FOUR_NV 0x853F +#define GL_SCALE_BY_ONE_HALF_NV 0x8540 +#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV 0x8541 +#define GL_COMBINER_INPUT_NV 0x8542 +#define GL_COMBINER_MAPPING_NV 0x8543 +#define GL_COMBINER_COMPONENT_USAGE_NV 0x8544 +#define GL_COMBINER_AB_DOT_PRODUCT_NV 0x8545 +#define GL_COMBINER_CD_DOT_PRODUCT_NV 0x8546 +#define GL_COMBINER_MUX_SUM_NV 0x8547 +#define GL_COMBINER_SCALE_NV 0x8548 +#define GL_COMBINER_BIAS_NV 0x8549 +#define GL_COMBINER_AB_OUTPUT_NV 0x854A +#define GL_COMBINER_CD_OUTPUT_NV 0x854B +#define GL_COMBINER_SUM_OUTPUT_NV 0x854C +#define GL_MAX_GENERAL_COMBINERS_NV 0x854D +#define GL_NUM_GENERAL_COMBINERS_NV 0x854E +#define GL_COLOR_SUM_CLAMP_NV 0x854F +#define GL_COMBINER0_NV 0x8550 +#define GL_COMBINER1_NV 0x8551 +#define GL_COMBINER2_NV 0x8552 +#define GL_COMBINER3_NV 0x8553 +#define GL_COMBINER4_NV 0x8554 +#define GL_COMBINER5_NV 0x8555 +#define GL_COMBINER6_NV 0x8556 +#define GL_COMBINER7_NV 0x8557 +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); +typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCombinerParameterfvNV (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glCombinerParameterfNV (GLenum pname, GLfloat param); +GLAPI void APIENTRY glCombinerParameterivNV (GLenum pname, const GLint *params); +GLAPI void APIENTRY glCombinerParameteriNV (GLenum pname, GLint param); +GLAPI void APIENTRY glCombinerInputNV (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +GLAPI void APIENTRY glCombinerOutputNV (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); +GLAPI void APIENTRY glFinalCombinerInputNV (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum stage, GLenum portion, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum stage, GLenum portion, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum variable, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum variable, GLenum pname, GLint *params); +#endif +#endif /* GL_NV_register_combiners */ + +#ifndef GL_NV_register_combiners2 +#define GL_NV_register_combiners2 1 +#define GL_PER_STAGE_CONSTANTS_NV 0x8535 +typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum stage, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum stage, GLenum pname, GLfloat *params); +#endif +#endif /* GL_NV_register_combiners2 */ + +#ifndef GL_NV_representative_fragment_test +#define GL_NV_representative_fragment_test 1 +#define GL_REPRESENTATIVE_FRAGMENT_TEST_NV 0x937F +#endif /* GL_NV_representative_fragment_test */ + +#ifndef GL_NV_robustness_video_memory_purge +#define GL_NV_robustness_video_memory_purge 1 +#define GL_PURGED_CONTEXT_RESET_NV 0x92BB +#endif /* GL_NV_robustness_video_memory_purge */ + +#ifndef GL_NV_sample_locations +#define GL_NV_sample_locations 1 +#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV 0x933D +#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV 0x933E +#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV 0x933F +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV 0x9340 +#define GL_SAMPLE_LOCATION_NV 0x8E50 +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9341 +#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV 0x9342 +#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV 0x9343 +typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLRESOLVEDEPTHVALUESNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferSampleLocationsfvNV (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glNamedFramebufferSampleLocationsfvNV (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glResolveDepthValuesNV (void); +#endif +#endif /* GL_NV_sample_locations */ + +#ifndef GL_NV_sample_mask_override_coverage +#define GL_NV_sample_mask_override_coverage 1 +#endif /* GL_NV_sample_mask_override_coverage */ + +#ifndef GL_NV_scissor_exclusive +#define GL_NV_scissor_exclusive 1 +#define GL_SCISSOR_TEST_EXCLUSIVE_NV 0x9555 +#define GL_SCISSOR_BOX_EXCLUSIVE_NV 0x9556 +typedef void (APIENTRYP PFNGLSCISSOREXCLUSIVENVPROC) (GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLSCISSOREXCLUSIVEARRAYVNVPROC) (GLuint first, GLsizei count, const GLint *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glScissorExclusiveNV (GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glScissorExclusiveArrayvNV (GLuint first, GLsizei count, const GLint *v); +#endif +#endif /* GL_NV_scissor_exclusive */ + +#ifndef GL_NV_shader_atomic_counters +#define GL_NV_shader_atomic_counters 1 +#endif /* GL_NV_shader_atomic_counters */ + +#ifndef GL_NV_shader_atomic_float +#define GL_NV_shader_atomic_float 1 +#endif /* GL_NV_shader_atomic_float */ + +#ifndef GL_NV_shader_atomic_float64 +#define GL_NV_shader_atomic_float64 1 +#endif /* GL_NV_shader_atomic_float64 */ + +#ifndef GL_NV_shader_atomic_fp16_vector +#define GL_NV_shader_atomic_fp16_vector 1 +#endif /* GL_NV_shader_atomic_fp16_vector */ + +#ifndef GL_NV_shader_atomic_int64 +#define GL_NV_shader_atomic_int64 1 +#endif /* GL_NV_shader_atomic_int64 */ + +#ifndef GL_NV_shader_buffer_load +#define GL_NV_shader_buffer_load 1 +#define GL_BUFFER_GPU_ADDRESS_NV 0x8F1D +#define GL_GPU_ADDRESS_NV 0x8F34 +#define GL_MAX_SHADER_BUFFER_ADDRESS_NV 0x8F35 +typedef void (APIENTRYP PFNGLMAKEBUFFERRESIDENTNVPROC) (GLenum target, GLenum access); +typedef void (APIENTRYP PFNGLMAKEBUFFERNONRESIDENTNVPROC) (GLenum target); +typedef GLboolean (APIENTRYP PFNGLISBUFFERRESIDENTNVPROC) (GLenum target); +typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERRESIDENTNVPROC) (GLuint buffer, GLenum access); +typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC) (GLuint buffer); +typedef GLboolean (APIENTRYP PFNGLISNAMEDBUFFERRESIDENTNVPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERUI64VNVPROC) (GLenum target, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC) (GLuint buffer, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLGETINTEGERUI64VNVPROC) (GLenum value, GLuint64EXT *result); +typedef void (APIENTRYP PFNGLUNIFORMUI64NVPROC) (GLint location, GLuint64EXT value); +typedef void (APIENTRYP PFNGLUNIFORMUI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMakeBufferResidentNV (GLenum target, GLenum access); +GLAPI void APIENTRY glMakeBufferNonResidentNV (GLenum target); +GLAPI GLboolean APIENTRY glIsBufferResidentNV (GLenum target); +GLAPI void APIENTRY glMakeNamedBufferResidentNV (GLuint buffer, GLenum access); +GLAPI void APIENTRY glMakeNamedBufferNonResidentNV (GLuint buffer); +GLAPI GLboolean APIENTRY glIsNamedBufferResidentNV (GLuint buffer); +GLAPI void APIENTRY glGetBufferParameterui64vNV (GLenum target, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glGetNamedBufferParameterui64vNV (GLuint buffer, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glGetIntegerui64vNV (GLenum value, GLuint64EXT *result); +GLAPI void APIENTRY glUniformui64NV (GLint location, GLuint64EXT value); +GLAPI void APIENTRY glUniformui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniformui64NV (GLuint program, GLint location, GLuint64EXT value); +GLAPI void APIENTRY glProgramUniformui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif +#endif /* GL_NV_shader_buffer_load */ + +#ifndef GL_NV_shader_buffer_store +#define GL_NV_shader_buffer_store 1 +#define GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV 0x00000010 +#endif /* GL_NV_shader_buffer_store */ + +#ifndef GL_NV_shader_storage_buffer_object +#define GL_NV_shader_storage_buffer_object 1 +#endif /* GL_NV_shader_storage_buffer_object */ + +#ifndef GL_NV_shader_subgroup_partitioned +#define GL_NV_shader_subgroup_partitioned 1 +#define GL_SUBGROUP_FEATURE_PARTITIONED_BIT_NV 0x00000100 +#endif /* GL_NV_shader_subgroup_partitioned */ + +#ifndef GL_NV_shader_texture_footprint +#define GL_NV_shader_texture_footprint 1 +#endif /* GL_NV_shader_texture_footprint */ + +#ifndef GL_NV_shader_thread_group +#define GL_NV_shader_thread_group 1 +#define GL_WARP_SIZE_NV 0x9339 +#define GL_WARPS_PER_SM_NV 0x933A +#define GL_SM_COUNT_NV 0x933B +#endif /* GL_NV_shader_thread_group */ + +#ifndef GL_NV_shader_thread_shuffle +#define GL_NV_shader_thread_shuffle 1 +#endif /* GL_NV_shader_thread_shuffle */ + +#ifndef GL_NV_shading_rate_image +#define GL_NV_shading_rate_image 1 +#define GL_SHADING_RATE_IMAGE_NV 0x9563 +#define GL_SHADING_RATE_NO_INVOCATIONS_NV 0x9564 +#define GL_SHADING_RATE_1_INVOCATION_PER_PIXEL_NV 0x9565 +#define GL_SHADING_RATE_1_INVOCATION_PER_1X2_PIXELS_NV 0x9566 +#define GL_SHADING_RATE_1_INVOCATION_PER_2X1_PIXELS_NV 0x9567 +#define GL_SHADING_RATE_1_INVOCATION_PER_2X2_PIXELS_NV 0x9568 +#define GL_SHADING_RATE_1_INVOCATION_PER_2X4_PIXELS_NV 0x9569 +#define GL_SHADING_RATE_1_INVOCATION_PER_4X2_PIXELS_NV 0x956A +#define GL_SHADING_RATE_1_INVOCATION_PER_4X4_PIXELS_NV 0x956B +#define GL_SHADING_RATE_2_INVOCATIONS_PER_PIXEL_NV 0x956C +#define GL_SHADING_RATE_4_INVOCATIONS_PER_PIXEL_NV 0x956D +#define GL_SHADING_RATE_8_INVOCATIONS_PER_PIXEL_NV 0x956E +#define GL_SHADING_RATE_16_INVOCATIONS_PER_PIXEL_NV 0x956F +#define GL_SHADING_RATE_IMAGE_BINDING_NV 0x955B +#define GL_SHADING_RATE_IMAGE_TEXEL_WIDTH_NV 0x955C +#define GL_SHADING_RATE_IMAGE_TEXEL_HEIGHT_NV 0x955D +#define GL_SHADING_RATE_IMAGE_PALETTE_SIZE_NV 0x955E +#define GL_MAX_COARSE_FRAGMENT_SAMPLES_NV 0x955F +#define GL_SHADING_RATE_SAMPLE_ORDER_DEFAULT_NV 0x95AE +#define GL_SHADING_RATE_SAMPLE_ORDER_PIXEL_MAJOR_NV 0x95AF +#define GL_SHADING_RATE_SAMPLE_ORDER_SAMPLE_MAJOR_NV 0x95B0 +typedef void (APIENTRYP PFNGLBINDSHADINGRATEIMAGENVPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLGETSHADINGRATEIMAGEPALETTENVPROC) (GLuint viewport, GLuint entry, GLenum *rate); +typedef void (APIENTRYP PFNGLGETSHADINGRATESAMPLELOCATIONIVNVPROC) (GLenum rate, GLuint samples, GLuint index, GLint *location); +typedef void (APIENTRYP PFNGLSHADINGRATEIMAGEBARRIERNVPROC) (GLboolean synchronize); +typedef void (APIENTRYP PFNGLSHADINGRATEIMAGEPALETTENVPROC) (GLuint viewport, GLuint first, GLsizei count, const GLenum *rates); +typedef void (APIENTRYP PFNGLSHADINGRATESAMPLEORDERNVPROC) (GLenum order); +typedef void (APIENTRYP PFNGLSHADINGRATESAMPLEORDERCUSTOMNVPROC) (GLenum rate, GLuint samples, const GLint *locations); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindShadingRateImageNV (GLuint texture); +GLAPI void APIENTRY glGetShadingRateImagePaletteNV (GLuint viewport, GLuint entry, GLenum *rate); +GLAPI void APIENTRY glGetShadingRateSampleLocationivNV (GLenum rate, GLuint samples, GLuint index, GLint *location); +GLAPI void APIENTRY glShadingRateImageBarrierNV (GLboolean synchronize); +GLAPI void APIENTRY glShadingRateImagePaletteNV (GLuint viewport, GLuint first, GLsizei count, const GLenum *rates); +GLAPI void APIENTRY glShadingRateSampleOrderNV (GLenum order); +GLAPI void APIENTRY glShadingRateSampleOrderCustomNV (GLenum rate, GLuint samples, const GLint *locations); +#endif +#endif /* GL_NV_shading_rate_image */ + +#ifndef GL_NV_stereo_view_rendering +#define GL_NV_stereo_view_rendering 1 +#endif /* GL_NV_stereo_view_rendering */ + +#ifndef GL_NV_tessellation_program5 +#define GL_NV_tessellation_program5 1 +#define GL_MAX_PROGRAM_PATCH_ATTRIBS_NV 0x86D8 +#define GL_TESS_CONTROL_PROGRAM_NV 0x891E +#define GL_TESS_EVALUATION_PROGRAM_NV 0x891F +#define GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV 0x8C74 +#define GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV 0x8C75 +#endif /* GL_NV_tessellation_program5 */ + +#ifndef GL_NV_texgen_emboss +#define GL_NV_texgen_emboss 1 +#define GL_EMBOSS_LIGHT_NV 0x855D +#define GL_EMBOSS_CONSTANT_NV 0x855E +#define GL_EMBOSS_MAP_NV 0x855F +#endif /* GL_NV_texgen_emboss */ + +#ifndef GL_NV_texgen_reflection +#define GL_NV_texgen_reflection 1 +#define GL_NORMAL_MAP_NV 0x8511 +#define GL_REFLECTION_MAP_NV 0x8512 +#endif /* GL_NV_texgen_reflection */ + +#ifndef GL_NV_texture_barrier +#define GL_NV_texture_barrier 1 +typedef void (APIENTRYP PFNGLTEXTUREBARRIERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureBarrierNV (void); +#endif +#endif /* GL_NV_texture_barrier */ + +#ifndef GL_NV_texture_compression_vtc +#define GL_NV_texture_compression_vtc 1 +#endif /* GL_NV_texture_compression_vtc */ + +#ifndef GL_NV_texture_env_combine4 +#define GL_NV_texture_env_combine4 1 +#define GL_COMBINE4_NV 0x8503 +#define GL_SOURCE3_RGB_NV 0x8583 +#define GL_SOURCE3_ALPHA_NV 0x858B +#define GL_OPERAND3_RGB_NV 0x8593 +#define GL_OPERAND3_ALPHA_NV 0x859B +#endif /* GL_NV_texture_env_combine4 */ + +#ifndef GL_NV_texture_expand_normal +#define GL_NV_texture_expand_normal 1 +#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F +#endif /* GL_NV_texture_expand_normal */ + +#ifndef GL_NV_texture_multisample +#define GL_NV_texture_multisample 1 +#define GL_TEXTURE_COVERAGE_SAMPLES_NV 0x9045 +#define GL_TEXTURE_COLOR_SAMPLES_NV 0x9046 +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage2DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTexImage3DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage2DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage3DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage2DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage3DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +#endif +#endif /* GL_NV_texture_multisample */ + +#ifndef GL_NV_texture_rectangle +#define GL_NV_texture_rectangle 1 +#define GL_TEXTURE_RECTANGLE_NV 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE_NV 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE_NV 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV 0x84F8 +#endif /* GL_NV_texture_rectangle */ + +#ifndef GL_NV_texture_rectangle_compressed +#define GL_NV_texture_rectangle_compressed 1 +#endif /* GL_NV_texture_rectangle_compressed */ + +#ifndef GL_NV_texture_shader +#define GL_NV_texture_shader 1 +#define GL_OFFSET_TEXTURE_RECTANGLE_NV 0x864C +#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D +#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E +#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9 +#define GL_UNSIGNED_INT_S8_S8_8_8_NV 0x86DA +#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV 0x86DB +#define GL_DSDT_MAG_INTENSITY_NV 0x86DC +#define GL_SHADER_CONSISTENT_NV 0x86DD +#define GL_TEXTURE_SHADER_NV 0x86DE +#define GL_SHADER_OPERATION_NV 0x86DF +#define GL_CULL_MODES_NV 0x86E0 +#define GL_OFFSET_TEXTURE_MATRIX_NV 0x86E1 +#define GL_OFFSET_TEXTURE_SCALE_NV 0x86E2 +#define GL_OFFSET_TEXTURE_BIAS_NV 0x86E3 +#define GL_OFFSET_TEXTURE_2D_MATRIX_NV 0x86E1 +#define GL_OFFSET_TEXTURE_2D_SCALE_NV 0x86E2 +#define GL_OFFSET_TEXTURE_2D_BIAS_NV 0x86E3 +#define GL_PREVIOUS_TEXTURE_INPUT_NV 0x86E4 +#define GL_CONST_EYE_NV 0x86E5 +#define GL_PASS_THROUGH_NV 0x86E6 +#define GL_CULL_FRAGMENT_NV 0x86E7 +#define GL_OFFSET_TEXTURE_2D_NV 0x86E8 +#define GL_DEPENDENT_AR_TEXTURE_2D_NV 0x86E9 +#define GL_DEPENDENT_GB_TEXTURE_2D_NV 0x86EA +#define GL_DOT_PRODUCT_NV 0x86EC +#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV 0x86ED +#define GL_DOT_PRODUCT_TEXTURE_2D_NV 0x86EE +#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0 +#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1 +#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2 +#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3 +#define GL_HILO_NV 0x86F4 +#define GL_DSDT_NV 0x86F5 +#define GL_DSDT_MAG_NV 0x86F6 +#define GL_DSDT_MAG_VIB_NV 0x86F7 +#define GL_HILO16_NV 0x86F8 +#define GL_SIGNED_HILO_NV 0x86F9 +#define GL_SIGNED_HILO16_NV 0x86FA +#define GL_SIGNED_RGBA_NV 0x86FB +#define GL_SIGNED_RGBA8_NV 0x86FC +#define GL_SIGNED_RGB_NV 0x86FE +#define GL_SIGNED_RGB8_NV 0x86FF +#define GL_SIGNED_LUMINANCE_NV 0x8701 +#define GL_SIGNED_LUMINANCE8_NV 0x8702 +#define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703 +#define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704 +#define GL_SIGNED_ALPHA_NV 0x8705 +#define GL_SIGNED_ALPHA8_NV 0x8706 +#define GL_SIGNED_INTENSITY_NV 0x8707 +#define GL_SIGNED_INTENSITY8_NV 0x8708 +#define GL_DSDT8_NV 0x8709 +#define GL_DSDT8_MAG8_NV 0x870A +#define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B +#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C +#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D +#define GL_HI_SCALE_NV 0x870E +#define GL_LO_SCALE_NV 0x870F +#define GL_DS_SCALE_NV 0x8710 +#define GL_DT_SCALE_NV 0x8711 +#define GL_MAGNITUDE_SCALE_NV 0x8712 +#define GL_VIBRANCE_SCALE_NV 0x8713 +#define GL_HI_BIAS_NV 0x8714 +#define GL_LO_BIAS_NV 0x8715 +#define GL_DS_BIAS_NV 0x8716 +#define GL_DT_BIAS_NV 0x8717 +#define GL_MAGNITUDE_BIAS_NV 0x8718 +#define GL_VIBRANCE_BIAS_NV 0x8719 +#define GL_TEXTURE_BORDER_VALUES_NV 0x871A +#define GL_TEXTURE_HI_SIZE_NV 0x871B +#define GL_TEXTURE_LO_SIZE_NV 0x871C +#define GL_TEXTURE_DS_SIZE_NV 0x871D +#define GL_TEXTURE_DT_SIZE_NV 0x871E +#define GL_TEXTURE_MAG_SIZE_NV 0x871F +#endif /* GL_NV_texture_shader */ + +#ifndef GL_NV_texture_shader2 +#define GL_NV_texture_shader2 1 +#define GL_DOT_PRODUCT_TEXTURE_3D_NV 0x86EF +#endif /* GL_NV_texture_shader2 */ + +#ifndef GL_NV_texture_shader3 +#define GL_NV_texture_shader3 1 +#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850 +#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851 +#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852 +#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853 +#define GL_OFFSET_HILO_TEXTURE_2D_NV 0x8854 +#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855 +#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856 +#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857 +#define GL_DEPENDENT_HILO_TEXTURE_2D_NV 0x8858 +#define GL_DEPENDENT_RGB_TEXTURE_3D_NV 0x8859 +#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A +#define GL_DOT_PRODUCT_PASS_THROUGH_NV 0x885B +#define GL_DOT_PRODUCT_TEXTURE_1D_NV 0x885C +#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D +#define GL_HILO8_NV 0x885E +#define GL_SIGNED_HILO8_NV 0x885F +#define GL_FORCE_BLUE_TO_ONE_NV 0x8860 +#endif /* GL_NV_texture_shader3 */ + +#ifndef GL_NV_timeline_semaphore +#define GL_NV_timeline_semaphore 1 +#define GL_TIMELINE_SEMAPHORE_VALUE_NV 0x9595 +#define GL_SEMAPHORE_TYPE_NV 0x95B3 +#define GL_SEMAPHORE_TYPE_BINARY_NV 0x95B4 +#define GL_SEMAPHORE_TYPE_TIMELINE_NV 0x95B5 +#define GL_MAX_TIMELINE_SEMAPHORE_VALUE_DIFFERENCE_NV 0x95B6 +typedef void (APIENTRYP PFNGLCREATESEMAPHORESNVPROC) (GLsizei n, GLuint *semaphores); +typedef void (APIENTRYP PFNGLSEMAPHOREPARAMETERIVNVPROC) (GLuint semaphore, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETSEMAPHOREPARAMETERIVNVPROC) (GLuint semaphore, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCreateSemaphoresNV (GLsizei n, GLuint *semaphores); +GLAPI void APIENTRY glSemaphoreParameterivNV (GLuint semaphore, GLenum pname, const GLint *params); +GLAPI void APIENTRY glGetSemaphoreParameterivNV (GLuint semaphore, GLenum pname, GLint *params); +#endif +#endif /* GL_NV_timeline_semaphore */ + +#ifndef GL_NV_transform_feedback +#define GL_NV_transform_feedback 1 +#define GL_BACK_PRIMARY_COLOR_NV 0x8C77 +#define GL_BACK_SECONDARY_COLOR_NV 0x8C78 +#define GL_TEXTURE_COORD_NV 0x8C79 +#define GL_CLIP_DISTANCE_NV 0x8C7A +#define GL_VERTEX_ID_NV 0x8C7B +#define GL_PRIMITIVE_ID_NV 0x8C7C +#define GL_GENERIC_ATTRIB_NV 0x8C7D +#define GL_TRANSFORM_FEEDBACK_ATTRIBS_NV 0x8C7E +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV 0x8C80 +#define GL_ACTIVE_VARYINGS_NV 0x8C81 +#define GL_ACTIVE_VARYING_MAX_LENGTH_NV 0x8C82 +#define GL_TRANSFORM_FEEDBACK_VARYINGS_NV 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START_NV 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV 0x8C85 +#define GL_TRANSFORM_FEEDBACK_RECORD_NV 0x8C86 +#define GL_PRIMITIVES_GENERATED_NV 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV 0x8C88 +#define GL_RASTERIZER_DISCARD_NV 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_NV 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV 0x8C8B +#define GL_INTERLEAVED_ATTRIBS_NV 0x8C8C +#define GL_SEPARATE_ATTRIBS_NV 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER_NV 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV 0x8C8F +#define GL_LAYER_NV 0x8DAA +#define GL_NEXT_BUFFER_NV -2 +#define GL_SKIP_COMPONENTS4_NV -3 +#define GL_SKIP_COMPONENTS3_NV -4 +#define GL_SKIP_COMPONENTS2_NV -5 +#define GL_SKIP_COMPONENTS1_NV -6 +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKNVPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC) (GLsizei count, const GLint *attribs, GLenum bufferMode); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGENVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETNVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +typedef void (APIENTRYP PFNGLBINDBUFFERBASENVPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC) (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode); +typedef void (APIENTRYP PFNGLACTIVEVARYINGNVPROC) (GLuint program, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETVARYINGLOCATIONNVPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVEVARYINGNVPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC) (GLuint program, GLuint index, GLint *location); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC) (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginTransformFeedbackNV (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedbackNV (void); +GLAPI void APIENTRY glTransformFeedbackAttribsNV (GLsizei count, const GLint *attribs, GLenum bufferMode); +GLAPI void APIENTRY glBindBufferRangeNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferOffsetNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +GLAPI void APIENTRY glBindBufferBaseNV (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryingsNV (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode); +GLAPI void APIENTRY glActiveVaryingNV (GLuint program, const GLchar *name); +GLAPI GLint APIENTRY glGetVaryingLocationNV (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetActiveVaryingNV (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetTransformFeedbackVaryingNV (GLuint program, GLuint index, GLint *location); +GLAPI void APIENTRY glTransformFeedbackStreamAttribsNV (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode); +#endif +#endif /* GL_NV_transform_feedback */ + +#ifndef GL_NV_transform_feedback2 +#define GL_NV_transform_feedback2 1 +#define GL_TRANSFORM_FEEDBACK_NV 0x8E22 +#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED_NV 0x8E23 +#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE_NV 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING_NV 0x8E25 +typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKNVPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSNVPROC) (GLsizei n, const GLuint *ids); +typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSNVPROC) (GLsizei n, GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKNVPROC) (GLenum mode, GLuint id); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindTransformFeedbackNV (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteTransformFeedbacksNV (GLsizei n, const GLuint *ids); +GLAPI void APIENTRY glGenTransformFeedbacksNV (GLsizei n, GLuint *ids); +GLAPI GLboolean APIENTRY glIsTransformFeedbackNV (GLuint id); +GLAPI void APIENTRY glPauseTransformFeedbackNV (void); +GLAPI void APIENTRY glResumeTransformFeedbackNV (void); +GLAPI void APIENTRY glDrawTransformFeedbackNV (GLenum mode, GLuint id); +#endif +#endif /* GL_NV_transform_feedback2 */ + +#ifndef GL_NV_uniform_buffer_unified_memory +#define GL_NV_uniform_buffer_unified_memory 1 +#define GL_UNIFORM_BUFFER_UNIFIED_NV 0x936E +#define GL_UNIFORM_BUFFER_ADDRESS_NV 0x936F +#define GL_UNIFORM_BUFFER_LENGTH_NV 0x9370 +#endif /* GL_NV_uniform_buffer_unified_memory */ + +#ifndef GL_NV_vdpau_interop +#define GL_NV_vdpau_interop 1 +typedef GLintptr GLvdpauSurfaceNV; +#define GL_SURFACE_STATE_NV 0x86EB +#define GL_SURFACE_REGISTERED_NV 0x86FD +#define GL_SURFACE_MAPPED_NV 0x8700 +#define GL_WRITE_DISCARD_NV 0x88BE +typedef void (APIENTRYP PFNGLVDPAUINITNVPROC) (const void *vdpDevice, const void *getProcAddress); +typedef void (APIENTRYP PFNGLVDPAUFININVPROC) (void); +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTERVIDEOSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTEROUTPUTSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +typedef GLboolean (APIENTRYP PFNGLVDPAUISSURFACENVPROC) (GLvdpauSurfaceNV surface); +typedef void (APIENTRYP PFNGLVDPAUUNREGISTERSURFACENVPROC) (GLvdpauSurfaceNV surface); +typedef void (APIENTRYP PFNGLVDPAUGETSURFACEIVNVPROC) (GLvdpauSurfaceNV surface, GLenum pname, GLsizei count, GLsizei *length, GLint *values); +typedef void (APIENTRYP PFNGLVDPAUSURFACEACCESSNVPROC) (GLvdpauSurfaceNV surface, GLenum access); +typedef void (APIENTRYP PFNGLVDPAUMAPSURFACESNVPROC) (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces); +typedef void (APIENTRYP PFNGLVDPAUUNMAPSURFACESNVPROC) (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVDPAUInitNV (const void *vdpDevice, const void *getProcAddress); +GLAPI void APIENTRY glVDPAUFiniNV (void); +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterVideoSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterOutputSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +GLAPI GLboolean APIENTRY glVDPAUIsSurfaceNV (GLvdpauSurfaceNV surface); +GLAPI void APIENTRY glVDPAUUnregisterSurfaceNV (GLvdpauSurfaceNV surface); +GLAPI void APIENTRY glVDPAUGetSurfaceivNV (GLvdpauSurfaceNV surface, GLenum pname, GLsizei count, GLsizei *length, GLint *values); +GLAPI void APIENTRY glVDPAUSurfaceAccessNV (GLvdpauSurfaceNV surface, GLenum access); +GLAPI void APIENTRY glVDPAUMapSurfacesNV (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces); +GLAPI void APIENTRY glVDPAUUnmapSurfacesNV (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces); +#endif +#endif /* GL_NV_vdpau_interop */ + +#ifndef GL_NV_vdpau_interop2 +#define GL_NV_vdpau_interop2 1 +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTERVIDEOSURFACEWITHPICTURESTRUCTURENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames, GLboolean isFrameStructure); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterVideoSurfaceWithPictureStructureNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames, GLboolean isFrameStructure); +#endif +#endif /* GL_NV_vdpau_interop2 */ + +#ifndef GL_NV_vertex_array_range +#define GL_NV_vertex_array_range 1 +#define GL_VERTEX_ARRAY_RANGE_NV 0x851D +#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV 0x851E +#define GL_VERTEX_ARRAY_RANGE_VALID_NV 0x851F +#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520 +#define GL_VERTEX_ARRAY_RANGE_POINTER_NV 0x8521 +typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void); +typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushVertexArrayRangeNV (void); +GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei length, const void *pointer); +#endif +#endif /* GL_NV_vertex_array_range */ + +#ifndef GL_NV_vertex_array_range2 +#define GL_NV_vertex_array_range2 1 +#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533 +#endif /* GL_NV_vertex_array_range2 */ + +#ifndef GL_NV_vertex_attrib_integer_64bit +#define GL_NV_vertex_attrib_integer_64bit 1 +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64NVPROC) (GLuint index, GLint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64NVPROC) (GLuint index, GLuint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLI64VNVPROC) (GLuint index, GLenum pname, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VNVPROC) (GLuint index, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribL1i64NV (GLuint index, GLint64EXT x); +GLAPI void APIENTRY glVertexAttribL2i64NV (GLuint index, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glVertexAttribL3i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glVertexAttribL4i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glVertexAttribL1i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL2i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL3i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL4i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL1ui64NV (GLuint index, GLuint64EXT x); +GLAPI void APIENTRY glVertexAttribL2ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glVertexAttribL3ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glVertexAttribL4ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glVertexAttribL1ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL2ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL3ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL4ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glGetVertexAttribLi64vNV (GLuint index, GLenum pname, GLint64EXT *params); +GLAPI void APIENTRY glGetVertexAttribLui64vNV (GLuint index, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glVertexAttribLFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride); +#endif +#endif /* GL_NV_vertex_attrib_integer_64bit */ + +#ifndef GL_NV_vertex_buffer_unified_memory +#define GL_NV_vertex_buffer_unified_memory 1 +#define GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV 0x8F1E +#define GL_ELEMENT_ARRAY_UNIFIED_NV 0x8F1F +#define GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV 0x8F20 +#define GL_VERTEX_ARRAY_ADDRESS_NV 0x8F21 +#define GL_NORMAL_ARRAY_ADDRESS_NV 0x8F22 +#define GL_COLOR_ARRAY_ADDRESS_NV 0x8F23 +#define GL_INDEX_ARRAY_ADDRESS_NV 0x8F24 +#define GL_TEXTURE_COORD_ARRAY_ADDRESS_NV 0x8F25 +#define GL_EDGE_FLAG_ARRAY_ADDRESS_NV 0x8F26 +#define GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV 0x8F27 +#define GL_FOG_COORD_ARRAY_ADDRESS_NV 0x8F28 +#define GL_ELEMENT_ARRAY_ADDRESS_NV 0x8F29 +#define GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV 0x8F2A +#define GL_VERTEX_ARRAY_LENGTH_NV 0x8F2B +#define GL_NORMAL_ARRAY_LENGTH_NV 0x8F2C +#define GL_COLOR_ARRAY_LENGTH_NV 0x8F2D +#define GL_INDEX_ARRAY_LENGTH_NV 0x8F2E +#define GL_TEXTURE_COORD_ARRAY_LENGTH_NV 0x8F2F +#define GL_EDGE_FLAG_ARRAY_LENGTH_NV 0x8F30 +#define GL_SECONDARY_COLOR_ARRAY_LENGTH_NV 0x8F31 +#define GL_FOG_COORD_ARRAY_LENGTH_NV 0x8F32 +#define GL_ELEMENT_ARRAY_LENGTH_NV 0x8F33 +#define GL_DRAW_INDIRECT_UNIFIED_NV 0x8F40 +#define GL_DRAW_INDIRECT_ADDRESS_NV 0x8F41 +#define GL_DRAW_INDIRECT_LENGTH_NV 0x8F42 +typedef void (APIENTRYP PFNGLBUFFERADDRESSRANGENVPROC) (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length); +typedef void (APIENTRYP PFNGLVERTEXFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLNORMALFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLINDEXFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLTEXCOORDFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLEDGEFLAGFORMATNVPROC) (GLsizei stride); +typedef void (APIENTRYP PFNGLSECONDARYCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLFOGCOORDFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferAddressRangeNV (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length); +GLAPI void APIENTRY glVertexFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glNormalFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glColorFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glIndexFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glTexCoordFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glEdgeFlagFormatNV (GLsizei stride); +GLAPI void APIENTRY glSecondaryColorFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glFogCoordFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glVertexAttribFormatNV (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride); +GLAPI void APIENTRY glVertexAttribIFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glGetIntegerui64i_vNV (GLenum value, GLuint index, GLuint64EXT *result); +#endif +#endif /* GL_NV_vertex_buffer_unified_memory */ + +#ifndef GL_NV_vertex_program +#define GL_NV_vertex_program 1 +#define GL_VERTEX_PROGRAM_NV 0x8620 +#define GL_VERTEX_STATE_PROGRAM_NV 0x8621 +#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623 +#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624 +#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625 +#define GL_CURRENT_ATTRIB_NV 0x8626 +#define GL_PROGRAM_LENGTH_NV 0x8627 +#define GL_PROGRAM_STRING_NV 0x8628 +#define GL_MODELVIEW_PROJECTION_NV 0x8629 +#define GL_IDENTITY_NV 0x862A +#define GL_INVERSE_NV 0x862B +#define GL_TRANSPOSE_NV 0x862C +#define GL_INVERSE_TRANSPOSE_NV 0x862D +#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E +#define GL_MAX_TRACK_MATRICES_NV 0x862F +#define GL_MATRIX0_NV 0x8630 +#define GL_MATRIX1_NV 0x8631 +#define GL_MATRIX2_NV 0x8632 +#define GL_MATRIX3_NV 0x8633 +#define GL_MATRIX4_NV 0x8634 +#define GL_MATRIX5_NV 0x8635 +#define GL_MATRIX6_NV 0x8636 +#define GL_MATRIX7_NV 0x8637 +#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640 +#define GL_CURRENT_MATRIX_NV 0x8641 +#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643 +#define GL_PROGRAM_PARAMETER_NV 0x8644 +#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645 +#define GL_PROGRAM_TARGET_NV 0x8646 +#define GL_PROGRAM_RESIDENT_NV 0x8647 +#define GL_TRACK_MATRIX_NV 0x8648 +#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649 +#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A +#define GL_PROGRAM_ERROR_POSITION_NV 0x864B +#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650 +#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651 +#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652 +#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653 +#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654 +#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655 +#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656 +#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657 +#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658 +#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659 +#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A +#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B +#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C +#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D +#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E +#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F +#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660 +#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661 +#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662 +#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663 +#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664 +#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665 +#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666 +#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667 +#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668 +#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669 +#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A +#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B +#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C +#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D +#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E +#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F +#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670 +#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671 +#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672 +#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673 +#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674 +#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675 +#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676 +#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677 +#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678 +#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679 +#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A +#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B +#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C +#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D +#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E +#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F +typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences); +typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params); +typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs); +typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program); +typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, void **pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei n, const GLuint *programs, GLboolean *residences); +GLAPI void APIENTRY glBindProgramNV (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteProgramsNV (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glExecuteProgramNV (GLenum target, GLuint id, const GLfloat *params); +GLAPI void APIENTRY glGenProgramsNV (GLsizei n, GLuint *programs); +GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum target, GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetProgramivNV (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramStringNV (GLuint id, GLenum pname, GLubyte *program); +GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum target, GLuint address, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribivNV (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint index, GLenum pname, void **pointer); +GLAPI GLboolean APIENTRY glIsProgramNV (GLuint id); +GLAPI void APIENTRY glLoadProgramNV (GLenum target, GLuint id, GLsizei len, const GLubyte *program); +GLAPI void APIENTRY glProgramParameter4dNV (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramParameter4dvNV (GLenum target, GLuint index, const GLdouble *v); +GLAPI void APIENTRY glProgramParameter4fNV (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramParameter4fvNV (GLenum target, GLuint index, const GLfloat *v); +GLAPI void APIENTRY glProgramParameters4dvNV (GLenum target, GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glProgramParameters4fvNV (GLenum target, GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glTrackMatrixNV (GLenum target, GLuint address, GLenum matrix, GLenum transform); +GLAPI void APIENTRY glVertexAttribPointerNV (GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glVertexAttrib1dNV (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1fNV (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1sNV (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2dNV (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2fNV (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2sNV (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3sNV (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4sNV (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs1svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs2svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs3svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs4svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint index, GLsizei count, const GLubyte *v); +#endif +#endif /* GL_NV_vertex_program */ + +#ifndef GL_NV_vertex_program1_1 +#define GL_NV_vertex_program1_1 1 +#endif /* GL_NV_vertex_program1_1 */ + +#ifndef GL_NV_vertex_program2 +#define GL_NV_vertex_program2 1 +#endif /* GL_NV_vertex_program2 */ + +#ifndef GL_NV_vertex_program2_option +#define GL_NV_vertex_program2_option 1 +#endif /* GL_NV_vertex_program2_option */ + +#ifndef GL_NV_vertex_program3 +#define GL_NV_vertex_program3 1 +#endif /* GL_NV_vertex_program3 */ + +#ifndef GL_NV_vertex_program4 +#define GL_NV_vertex_program4 1 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_NV 0x88FD +#endif /* GL_NV_vertex_program4 */ + +#ifndef GL_NV_video_capture +#define GL_NV_video_capture 1 +#define GL_VIDEO_BUFFER_NV 0x9020 +#define GL_VIDEO_BUFFER_BINDING_NV 0x9021 +#define GL_FIELD_UPPER_NV 0x9022 +#define GL_FIELD_LOWER_NV 0x9023 +#define GL_NUM_VIDEO_CAPTURE_STREAMS_NV 0x9024 +#define GL_NEXT_VIDEO_CAPTURE_BUFFER_STATUS_NV 0x9025 +#define GL_VIDEO_CAPTURE_TO_422_SUPPORTED_NV 0x9026 +#define GL_LAST_VIDEO_CAPTURE_STATUS_NV 0x9027 +#define GL_VIDEO_BUFFER_PITCH_NV 0x9028 +#define GL_VIDEO_COLOR_CONVERSION_MATRIX_NV 0x9029 +#define GL_VIDEO_COLOR_CONVERSION_MAX_NV 0x902A +#define GL_VIDEO_COLOR_CONVERSION_MIN_NV 0x902B +#define GL_VIDEO_COLOR_CONVERSION_OFFSET_NV 0x902C +#define GL_VIDEO_BUFFER_INTERNAL_FORMAT_NV 0x902D +#define GL_PARTIAL_SUCCESS_NV 0x902E +#define GL_SUCCESS_NV 0x902F +#define GL_FAILURE_NV 0x9030 +#define GL_YCBYCR8_422_NV 0x9031 +#define GL_YCBAYCR8A_4224_NV 0x9032 +#define GL_Z6Y10Z6CB10Z6Y10Z6CR10_422_NV 0x9033 +#define GL_Z6Y10Z6CB10Z6A10Z6Y10Z6CR10Z6A10_4224_NV 0x9034 +#define GL_Z4Y12Z4CB12Z4Y12Z4CR12_422_NV 0x9035 +#define GL_Z4Y12Z4CB12Z4A12Z4Y12Z4CR12Z4A12_4224_NV 0x9036 +#define GL_Z4Y12Z4CB12Z4CR12_444_NV 0x9037 +#define GL_VIDEO_CAPTURE_FRAME_WIDTH_NV 0x9038 +#define GL_VIDEO_CAPTURE_FRAME_HEIGHT_NV 0x9039 +#define GL_VIDEO_CAPTURE_FIELD_UPPER_HEIGHT_NV 0x903A +#define GL_VIDEO_CAPTURE_FIELD_LOWER_HEIGHT_NV 0x903B +#define GL_VIDEO_CAPTURE_SURFACE_ORIGIN_NV 0x903C +typedef void (APIENTRYP PFNGLBEGINVIDEOCAPTURENVPROC) (GLuint video_capture_slot); +typedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMBUFFERNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset); +typedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMTEXTURENVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLENDVIDEOCAPTURENVPROC) (GLuint video_capture_slot); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTUREIVNVPROC) (GLuint video_capture_slot, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params); +typedef GLenum (APIENTRYP PFNGLVIDEOCAPTURENVPROC) (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginVideoCaptureNV (GLuint video_capture_slot); +GLAPI void APIENTRY glBindVideoCaptureStreamBufferNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset); +GLAPI void APIENTRY glBindVideoCaptureStreamTextureNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture); +GLAPI void APIENTRY glEndVideoCaptureNV (GLuint video_capture_slot); +GLAPI void APIENTRY glGetVideoCaptureivNV (GLuint video_capture_slot, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideoCaptureStreamivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideoCaptureStreamfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVideoCaptureStreamdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params); +GLAPI GLenum APIENTRY glVideoCaptureNV (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time); +GLAPI void APIENTRY glVideoCaptureStreamParameterivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params); +GLAPI void APIENTRY glVideoCaptureStreamParameterfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glVideoCaptureStreamParameterdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params); +#endif +#endif /* GL_NV_video_capture */ + +#ifndef GL_NV_viewport_array2 +#define GL_NV_viewport_array2 1 +#endif /* GL_NV_viewport_array2 */ + +#ifndef GL_NV_viewport_swizzle +#define GL_NV_viewport_swizzle 1 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_X_NV 0x9350 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_X_NV 0x9351 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_Y_NV 0x9352 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Y_NV 0x9353 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_Z_NV 0x9354 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Z_NV 0x9355 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_W_NV 0x9356 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_W_NV 0x9357 +#define GL_VIEWPORT_SWIZZLE_X_NV 0x9358 +#define GL_VIEWPORT_SWIZZLE_Y_NV 0x9359 +#define GL_VIEWPORT_SWIZZLE_Z_NV 0x935A +#define GL_VIEWPORT_SWIZZLE_W_NV 0x935B +typedef void (APIENTRYP PFNGLVIEWPORTSWIZZLENVPROC) (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glViewportSwizzleNV (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew); +#endif +#endif /* GL_NV_viewport_swizzle */ + +#ifndef GL_OML_interlace +#define GL_OML_interlace 1 +#define GL_INTERLACE_OML 0x8980 +#define GL_INTERLACE_READ_OML 0x8981 +#endif /* GL_OML_interlace */ + +#ifndef GL_OML_resample +#define GL_OML_resample 1 +#define GL_PACK_RESAMPLE_OML 0x8984 +#define GL_UNPACK_RESAMPLE_OML 0x8985 +#define GL_RESAMPLE_REPLICATE_OML 0x8986 +#define GL_RESAMPLE_ZERO_FILL_OML 0x8987 +#define GL_RESAMPLE_AVERAGE_OML 0x8988 +#define GL_RESAMPLE_DECIMATE_OML 0x8989 +#endif /* GL_OML_resample */ + +#ifndef GL_OML_subsample +#define GL_OML_subsample 1 +#define GL_FORMAT_SUBSAMPLE_24_24_OML 0x8982 +#define GL_FORMAT_SUBSAMPLE_244_244_OML 0x8983 +#endif /* GL_OML_subsample */ + +#ifndef GL_OVR_multiview +#define GL_OVR_multiview 1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR 0x9630 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR 0x9632 +#define GL_MAX_VIEWS_OVR 0x9631 +#define GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR 0x9633 +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferTextureMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); +#endif +#endif /* GL_OVR_multiview */ + +#ifndef GL_OVR_multiview2 +#define GL_OVR_multiview2 1 +#endif /* GL_OVR_multiview2 */ + +#ifndef GL_PGI_misc_hints +#define GL_PGI_misc_hints 1 +#define GL_PREFER_DOUBLEBUFFER_HINT_PGI 0x1A1F8 +#define GL_CONSERVE_MEMORY_HINT_PGI 0x1A1FD +#define GL_RECLAIM_MEMORY_HINT_PGI 0x1A1FE +#define GL_NATIVE_GRAPHICS_HANDLE_PGI 0x1A202 +#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203 +#define GL_NATIVE_GRAPHICS_END_HINT_PGI 0x1A204 +#define GL_ALWAYS_FAST_HINT_PGI 0x1A20C +#define GL_ALWAYS_SOFT_HINT_PGI 0x1A20D +#define GL_ALLOW_DRAW_OBJ_HINT_PGI 0x1A20E +#define GL_ALLOW_DRAW_WIN_HINT_PGI 0x1A20F +#define GL_ALLOW_DRAW_FRG_HINT_PGI 0x1A210 +#define GL_ALLOW_DRAW_MEM_HINT_PGI 0x1A211 +#define GL_STRICT_DEPTHFUNC_HINT_PGI 0x1A216 +#define GL_STRICT_LIGHTING_HINT_PGI 0x1A217 +#define GL_STRICT_SCISSOR_HINT_PGI 0x1A218 +#define GL_FULL_STIPPLE_HINT_PGI 0x1A219 +#define GL_CLIP_NEAR_HINT_PGI 0x1A220 +#define GL_CLIP_FAR_HINT_PGI 0x1A221 +#define GL_WIDE_LINE_HINT_PGI 0x1A222 +#define GL_BACK_NORMALS_HINT_PGI 0x1A223 +typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glHintPGI (GLenum target, GLint mode); +#endif +#endif /* GL_PGI_misc_hints */ + +#ifndef GL_PGI_vertex_hints +#define GL_PGI_vertex_hints 1 +#define GL_VERTEX_DATA_HINT_PGI 0x1A22A +#define GL_VERTEX_CONSISTENT_HINT_PGI 0x1A22B +#define GL_MATERIAL_SIDE_HINT_PGI 0x1A22C +#define GL_MAX_VERTEX_HINT_PGI 0x1A22D +#define GL_COLOR3_BIT_PGI 0x00010000 +#define GL_COLOR4_BIT_PGI 0x00020000 +#define GL_EDGEFLAG_BIT_PGI 0x00040000 +#define GL_INDEX_BIT_PGI 0x00080000 +#define GL_MAT_AMBIENT_BIT_PGI 0x00100000 +#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000 +#define GL_MAT_DIFFUSE_BIT_PGI 0x00400000 +#define GL_MAT_EMISSION_BIT_PGI 0x00800000 +#define GL_MAT_COLOR_INDEXES_BIT_PGI 0x01000000 +#define GL_MAT_SHININESS_BIT_PGI 0x02000000 +#define GL_MAT_SPECULAR_BIT_PGI 0x04000000 +#define GL_NORMAL_BIT_PGI 0x08000000 +#define GL_TEXCOORD1_BIT_PGI 0x10000000 +#define GL_TEXCOORD2_BIT_PGI 0x20000000 +#define GL_TEXCOORD3_BIT_PGI 0x40000000 +#define GL_TEXCOORD4_BIT_PGI 0x80000000 +#define GL_VERTEX23_BIT_PGI 0x00000004 +#define GL_VERTEX4_BIT_PGI 0x00000008 +#endif /* GL_PGI_vertex_hints */ + +#ifndef GL_REND_screen_coordinates +#define GL_REND_screen_coordinates 1 +#define GL_SCREEN_COORDINATES_REND 0x8490 +#define GL_INVERTED_SCREEN_W_REND 0x8491 +#endif /* GL_REND_screen_coordinates */ + +#ifndef GL_S3_s3tc +#define GL_S3_s3tc 1 +#define GL_RGB_S3TC 0x83A0 +#define GL_RGB4_S3TC 0x83A1 +#define GL_RGBA_S3TC 0x83A2 +#define GL_RGBA4_S3TC 0x83A3 +#define GL_RGBA_DXT5_S3TC 0x83A4 +#define GL_RGBA4_DXT5_S3TC 0x83A5 +#endif /* GL_S3_s3tc */ + +#ifndef GL_SGIS_detail_texture +#define GL_SGIS_detail_texture 1 +#define GL_DETAIL_TEXTURE_2D_SGIS 0x8095 +#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096 +#define GL_LINEAR_DETAIL_SGIS 0x8097 +#define GL_LINEAR_DETAIL_ALPHA_SGIS 0x8098 +#define GL_LINEAR_DETAIL_COLOR_SGIS 0x8099 +#define GL_DETAIL_TEXTURE_LEVEL_SGIS 0x809A +#define GL_DETAIL_TEXTURE_MODE_SGIS 0x809B +#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C +typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum target, GLfloat *points); +#endif +#endif /* GL_SGIS_detail_texture */ + +#ifndef GL_SGIS_fog_function +#define GL_SGIS_fog_function 1 +#define GL_FOG_FUNC_SGIS 0x812A +#define GL_FOG_FUNC_POINTS_SGIS 0x812B +#define GL_MAX_FOG_FUNC_POINTS_SGIS 0x812C +typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFogFuncSGIS (GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *points); +#endif +#endif /* GL_SGIS_fog_function */ + +#ifndef GL_SGIS_generate_mipmap +#define GL_SGIS_generate_mipmap 1 +#define GL_GENERATE_MIPMAP_SGIS 0x8191 +#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 +#endif /* GL_SGIS_generate_mipmap */ + +#ifndef GL_SGIS_multisample +#define GL_SGIS_multisample 1 +#define GL_MULTISAMPLE_SGIS 0x809D +#define GL_SAMPLE_ALPHA_TO_MASK_SGIS 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_SGIS 0x809F +#define GL_SAMPLE_MASK_SGIS 0x80A0 +#define GL_1PASS_SGIS 0x80A1 +#define GL_2PASS_0_SGIS 0x80A2 +#define GL_2PASS_1_SGIS 0x80A3 +#define GL_4PASS_0_SGIS 0x80A4 +#define GL_4PASS_1_SGIS 0x80A5 +#define GL_4PASS_2_SGIS 0x80A6 +#define GL_4PASS_3_SGIS 0x80A7 +#define GL_SAMPLE_BUFFERS_SGIS 0x80A8 +#define GL_SAMPLES_SGIS 0x80A9 +#define GL_SAMPLE_MASK_VALUE_SGIS 0x80AA +#define GL_SAMPLE_MASK_INVERT_SGIS 0x80AB +#define GL_SAMPLE_PATTERN_SGIS 0x80AC +typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleMaskSGIS (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glSamplePatternSGIS (GLenum pattern); +#endif +#endif /* GL_SGIS_multisample */ + +#ifndef GL_SGIS_pixel_texture +#define GL_SGIS_pixel_texture 1 +#define GL_PIXEL_TEXTURE_SGIS 0x8353 +#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354 +#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355 +#define GL_PIXEL_GROUP_COLOR_SGIS 0x8356 +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum pname, GLint param); +GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum pname, const GLint *params); +GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum pname, GLint *params); +GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum pname, GLfloat *params); +#endif +#endif /* GL_SGIS_pixel_texture */ + +#ifndef GL_SGIS_point_line_texgen +#define GL_SGIS_point_line_texgen 1 +#define GL_EYE_DISTANCE_TO_POINT_SGIS 0x81F0 +#define GL_OBJECT_DISTANCE_TO_POINT_SGIS 0x81F1 +#define GL_EYE_DISTANCE_TO_LINE_SGIS 0x81F2 +#define GL_OBJECT_DISTANCE_TO_LINE_SGIS 0x81F3 +#define GL_EYE_POINT_SGIS 0x81F4 +#define GL_OBJECT_POINT_SGIS 0x81F5 +#define GL_EYE_LINE_SGIS 0x81F6 +#define GL_OBJECT_LINE_SGIS 0x81F7 +#endif /* GL_SGIS_point_line_texgen */ + +#ifndef GL_SGIS_point_parameters +#define GL_SGIS_point_parameters 1 +#define GL_POINT_SIZE_MIN_SGIS 0x8126 +#define GL_POINT_SIZE_MAX_SGIS 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128 +#define GL_DISTANCE_ATTENUATION_SGIS 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfSGIS (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvSGIS (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_SGIS_point_parameters */ + +#ifndef GL_SGIS_sharpen_texture +#define GL_SGIS_sharpen_texture 1 +#define GL_LINEAR_SHARPEN_SGIS 0x80AD +#define GL_LINEAR_SHARPEN_ALPHA_SGIS 0x80AE +#define GL_LINEAR_SHARPEN_COLOR_SGIS 0x80AF +#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0 +typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum target, GLfloat *points); +#endif +#endif /* GL_SGIS_sharpen_texture */ + +#ifndef GL_SGIS_texture4D +#define GL_SGIS_texture4D 1 +#define GL_PACK_SKIP_VOLUMES_SGIS 0x8130 +#define GL_PACK_IMAGE_DEPTH_SGIS 0x8131 +#define GL_UNPACK_SKIP_VOLUMES_SGIS 0x8132 +#define GL_UNPACK_IMAGE_DEPTH_SGIS 0x8133 +#define GL_TEXTURE_4D_SGIS 0x8134 +#define GL_PROXY_TEXTURE_4D_SGIS 0x8135 +#define GL_TEXTURE_4DSIZE_SGIS 0x8136 +#define GL_TEXTURE_WRAP_Q_SGIS 0x8137 +#define GL_MAX_4D_TEXTURE_SIZE_SGIS 0x8138 +#define GL_TEXTURE_4D_BINDING_SGIS 0x814F +typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage4DSGIS (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_SGIS_texture4D */ + +#ifndef GL_SGIS_texture_border_clamp +#define GL_SGIS_texture_border_clamp 1 +#define GL_CLAMP_TO_BORDER_SGIS 0x812D +#endif /* GL_SGIS_texture_border_clamp */ + +#ifndef GL_SGIS_texture_color_mask +#define GL_SGIS_texture_color_mask 1 +#define GL_TEXTURE_COLOR_WRITEMASK_SGIS 0x81EF +typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +#endif +#endif /* GL_SGIS_texture_color_mask */ + +#ifndef GL_SGIS_texture_edge_clamp +#define GL_SGIS_texture_edge_clamp 1 +#define GL_CLAMP_TO_EDGE_SGIS 0x812F +#endif /* GL_SGIS_texture_edge_clamp */ + +#ifndef GL_SGIS_texture_filter4 +#define GL_SGIS_texture_filter4 1 +#define GL_FILTER4_SGIS 0x8146 +#define GL_TEXTURE_FILTER4_SIZE_SGIS 0x8147 +typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights); +typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum target, GLenum filter, GLfloat *weights); +GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); +#endif +#endif /* GL_SGIS_texture_filter4 */ + +#ifndef GL_SGIS_texture_lod +#define GL_SGIS_texture_lod 1 +#define GL_TEXTURE_MIN_LOD_SGIS 0x813A +#define GL_TEXTURE_MAX_LOD_SGIS 0x813B +#define GL_TEXTURE_BASE_LEVEL_SGIS 0x813C +#define GL_TEXTURE_MAX_LEVEL_SGIS 0x813D +#endif /* GL_SGIS_texture_lod */ + +#ifndef GL_SGIS_texture_select +#define GL_SGIS_texture_select 1 +#define GL_DUAL_ALPHA4_SGIS 0x8110 +#define GL_DUAL_ALPHA8_SGIS 0x8111 +#define GL_DUAL_ALPHA12_SGIS 0x8112 +#define GL_DUAL_ALPHA16_SGIS 0x8113 +#define GL_DUAL_LUMINANCE4_SGIS 0x8114 +#define GL_DUAL_LUMINANCE8_SGIS 0x8115 +#define GL_DUAL_LUMINANCE12_SGIS 0x8116 +#define GL_DUAL_LUMINANCE16_SGIS 0x8117 +#define GL_DUAL_INTENSITY4_SGIS 0x8118 +#define GL_DUAL_INTENSITY8_SGIS 0x8119 +#define GL_DUAL_INTENSITY12_SGIS 0x811A +#define GL_DUAL_INTENSITY16_SGIS 0x811B +#define GL_DUAL_LUMINANCE_ALPHA4_SGIS 0x811C +#define GL_DUAL_LUMINANCE_ALPHA8_SGIS 0x811D +#define GL_QUAD_ALPHA4_SGIS 0x811E +#define GL_QUAD_ALPHA8_SGIS 0x811F +#define GL_QUAD_LUMINANCE4_SGIS 0x8120 +#define GL_QUAD_LUMINANCE8_SGIS 0x8121 +#define GL_QUAD_INTENSITY4_SGIS 0x8122 +#define GL_QUAD_INTENSITY8_SGIS 0x8123 +#define GL_DUAL_TEXTURE_SELECT_SGIS 0x8124 +#define GL_QUAD_TEXTURE_SELECT_SGIS 0x8125 +#endif /* GL_SGIS_texture_select */ + +#ifndef GL_SGIX_async +#define GL_SGIX_async 1 +#define GL_ASYNC_MARKER_SGIX 0x8329 +typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker); +typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp); +typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp); +typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range); +typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range); +typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint marker); +GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *markerp); +GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *markerp); +GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei range); +GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint marker, GLsizei range); +GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint marker); +#endif +#endif /* GL_SGIX_async */ + +#ifndef GL_SGIX_async_histogram +#define GL_SGIX_async_histogram 1 +#define GL_ASYNC_HISTOGRAM_SGIX 0x832C +#define GL_MAX_ASYNC_HISTOGRAM_SGIX 0x832D +#endif /* GL_SGIX_async_histogram */ + +#ifndef GL_SGIX_async_pixel +#define GL_SGIX_async_pixel 1 +#define GL_ASYNC_TEX_IMAGE_SGIX 0x835C +#define GL_ASYNC_DRAW_PIXELS_SGIX 0x835D +#define GL_ASYNC_READ_PIXELS_SGIX 0x835E +#define GL_MAX_ASYNC_TEX_IMAGE_SGIX 0x835F +#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX 0x8360 +#define GL_MAX_ASYNC_READ_PIXELS_SGIX 0x8361 +#endif /* GL_SGIX_async_pixel */ + +#ifndef GL_SGIX_blend_alpha_minmax +#define GL_SGIX_blend_alpha_minmax 1 +#define GL_ALPHA_MIN_SGIX 0x8320 +#define GL_ALPHA_MAX_SGIX 0x8321 +#endif /* GL_SGIX_blend_alpha_minmax */ + +#ifndef GL_SGIX_calligraphic_fragment +#define GL_SGIX_calligraphic_fragment 1 +#define GL_CALLIGRAPHIC_FRAGMENT_SGIX 0x8183 +#endif /* GL_SGIX_calligraphic_fragment */ + +#ifndef GL_SGIX_clipmap +#define GL_SGIX_clipmap 1 +#define GL_LINEAR_CLIPMAP_LINEAR_SGIX 0x8170 +#define GL_TEXTURE_CLIPMAP_CENTER_SGIX 0x8171 +#define GL_TEXTURE_CLIPMAP_FRAME_SGIX 0x8172 +#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX 0x8173 +#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174 +#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175 +#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX 0x8176 +#define GL_MAX_CLIPMAP_DEPTH_SGIX 0x8177 +#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178 +#define GL_NEAREST_CLIPMAP_NEAREST_SGIX 0x844D +#define GL_NEAREST_CLIPMAP_LINEAR_SGIX 0x844E +#define GL_LINEAR_CLIPMAP_NEAREST_SGIX 0x844F +#endif /* GL_SGIX_clipmap */ + +#ifndef GL_SGIX_convolution_accuracy +#define GL_SGIX_convolution_accuracy 1 +#define GL_CONVOLUTION_HINT_SGIX 0x8316 +#endif /* GL_SGIX_convolution_accuracy */ + +#ifndef GL_SGIX_depth_pass_instrument +#define GL_SGIX_depth_pass_instrument 1 +#endif /* GL_SGIX_depth_pass_instrument */ + +#ifndef GL_SGIX_depth_texture +#define GL_SGIX_depth_texture 1 +#define GL_DEPTH_COMPONENT16_SGIX 0x81A5 +#define GL_DEPTH_COMPONENT24_SGIX 0x81A6 +#define GL_DEPTH_COMPONENT32_SGIX 0x81A7 +#endif /* GL_SGIX_depth_texture */ + +#ifndef GL_SGIX_flush_raster +#define GL_SGIX_flush_raster 1 +typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushRasterSGIX (void); +#endif +#endif /* GL_SGIX_flush_raster */ + +#ifndef GL_SGIX_fog_offset +#define GL_SGIX_fog_offset 1 +#define GL_FOG_OFFSET_SGIX 0x8198 +#define GL_FOG_OFFSET_VALUE_SGIX 0x8199 +#endif /* GL_SGIX_fog_offset */ + +#ifndef GL_SGIX_fragment_lighting +#define GL_SGIX_fragment_lighting 1 +#define GL_FRAGMENT_LIGHTING_SGIX 0x8400 +#define GL_FRAGMENT_COLOR_MATERIAL_SGIX 0x8401 +#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402 +#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403 +#define GL_MAX_FRAGMENT_LIGHTS_SGIX 0x8404 +#define GL_MAX_ACTIVE_LIGHTS_SGIX 0x8405 +#define GL_CURRENT_RASTER_NORMAL_SGIX 0x8406 +#define GL_LIGHT_ENV_MODE_SGIX 0x8407 +#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408 +#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409 +#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A +#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B +#define GL_FRAGMENT_LIGHT0_SGIX 0x840C +#define GL_FRAGMENT_LIGHT1_SGIX 0x840D +#define GL_FRAGMENT_LIGHT2_SGIX 0x840E +#define GL_FRAGMENT_LIGHT3_SGIX 0x840F +#define GL_FRAGMENT_LIGHT4_SGIX 0x8410 +#define GL_FRAGMENT_LIGHT5_SGIX 0x8411 +#define GL_FRAGMENT_LIGHT6_SGIX 0x8412 +#define GL_FRAGMENT_LIGHT7_SGIX 0x8413 +typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum face, GLenum mode); +GLAPI void APIENTRY glFragmentLightfSGIX (GLenum light, GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum light, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentLightiSGIX (GLenum light, GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentLightivSGIX (GLenum light, GLenum pname, const GLint *params); +GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum pname, const GLint *params); +GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum face, GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum face, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum face, GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum face, GLenum pname, const GLint *params); +GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum light, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum light, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum face, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum face, GLenum pname, GLint *params); +GLAPI void APIENTRY glLightEnviSGIX (GLenum pname, GLint param); +#endif +#endif /* GL_SGIX_fragment_lighting */ + +#ifndef GL_SGIX_framezoom +#define GL_SGIX_framezoom 1 +#define GL_FRAMEZOOM_SGIX 0x818B +#define GL_FRAMEZOOM_FACTOR_SGIX 0x818C +#define GL_MAX_FRAMEZOOM_FACTOR_SGIX 0x818D +typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFrameZoomSGIX (GLint factor); +#endif +#endif /* GL_SGIX_framezoom */ + +#ifndef GL_SGIX_igloo_interface +#define GL_SGIX_igloo_interface 1 +typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const void *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum pname, const void *params); +#endif +#endif /* GL_SGIX_igloo_interface */ + +#ifndef GL_SGIX_instruments +#define GL_SGIX_instruments 1 +#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180 +#define GL_INSTRUMENT_MEASUREMENTS_SGIX 0x8181 +typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void); +typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer); +typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p); +typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker); +typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void); +typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLint APIENTRY glGetInstrumentsSGIX (void); +GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei size, GLint *buffer); +GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *marker_p); +GLAPI void APIENTRY glReadInstrumentsSGIX (GLint marker); +GLAPI void APIENTRY glStartInstrumentsSGIX (void); +GLAPI void APIENTRY glStopInstrumentsSGIX (GLint marker); +#endif +#endif /* GL_SGIX_instruments */ + +#ifndef GL_SGIX_interlace +#define GL_SGIX_interlace 1 +#define GL_INTERLACE_SGIX 0x8094 +#endif /* GL_SGIX_interlace */ + +#ifndef GL_SGIX_ir_instrument1 +#define GL_SGIX_ir_instrument1 1 +#define GL_IR_INSTRUMENT1_SGIX 0x817F +#endif /* GL_SGIX_ir_instrument1 */ + +#ifndef GL_SGIX_list_priority +#define GL_SGIX_list_priority 1 +#define GL_LIST_PRIORITY_SGIX 0x8182 +typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint list, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetListParameterivSGIX (GLuint list, GLenum pname, GLint *params); +GLAPI void APIENTRY glListParameterfSGIX (GLuint list, GLenum pname, GLfloat param); +GLAPI void APIENTRY glListParameterfvSGIX (GLuint list, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glListParameteriSGIX (GLuint list, GLenum pname, GLint param); +GLAPI void APIENTRY glListParameterivSGIX (GLuint list, GLenum pname, const GLint *params); +#endif +#endif /* GL_SGIX_list_priority */ + +#ifndef GL_SGIX_pixel_texture +#define GL_SGIX_pixel_texture 1 +#define GL_PIXEL_TEX_GEN_SGIX 0x8139 +#define GL_PIXEL_TEX_GEN_MODE_SGIX 0x832B +typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTexGenSGIX (GLenum mode); +#endif +#endif /* GL_SGIX_pixel_texture */ + +#ifndef GL_SGIX_pixel_tiles +#define GL_SGIX_pixel_tiles 1 +#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E +#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F +#define GL_PIXEL_TILE_WIDTH_SGIX 0x8140 +#define GL_PIXEL_TILE_HEIGHT_SGIX 0x8141 +#define GL_PIXEL_TILE_GRID_WIDTH_SGIX 0x8142 +#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX 0x8143 +#define GL_PIXEL_TILE_GRID_DEPTH_SGIX 0x8144 +#define GL_PIXEL_TILE_CACHE_SIZE_SGIX 0x8145 +#endif /* GL_SGIX_pixel_tiles */ + +#ifndef GL_SGIX_polynomial_ffd +#define GL_SGIX_polynomial_ffd 1 +#define GL_TEXTURE_DEFORMATION_BIT_SGIX 0x00000001 +#define GL_GEOMETRY_DEFORMATION_BIT_SGIX 0x00000002 +#define GL_GEOMETRY_DEFORMATION_SGIX 0x8194 +#define GL_TEXTURE_DEFORMATION_SGIX 0x8195 +#define GL_DEFORMATIONS_MASK_SGIX 0x8196 +#define GL_MAX_DEFORMATION_ORDER_SGIX 0x8197 +typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points); +typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points); +typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points); +GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points); +GLAPI void APIENTRY glDeformSGIX (GLbitfield mask); +GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield mask); +#endif +#endif /* GL_SGIX_polynomial_ffd */ + +#ifndef GL_SGIX_reference_plane +#define GL_SGIX_reference_plane 1 +#define GL_REFERENCE_PLANE_SGIX 0x817D +#define GL_REFERENCE_PLANE_EQUATION_SGIX 0x817E +typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *equation); +#endif +#endif /* GL_SGIX_reference_plane */ + +#ifndef GL_SGIX_resample +#define GL_SGIX_resample 1 +#define GL_PACK_RESAMPLE_SGIX 0x842E +#define GL_UNPACK_RESAMPLE_SGIX 0x842F +#define GL_RESAMPLE_REPLICATE_SGIX 0x8433 +#define GL_RESAMPLE_ZERO_FILL_SGIX 0x8434 +#define GL_RESAMPLE_DECIMATE_SGIX 0x8430 +#endif /* GL_SGIX_resample */ + +#ifndef GL_SGIX_scalebias_hint +#define GL_SGIX_scalebias_hint 1 +#define GL_SCALEBIAS_HINT_SGIX 0x8322 +#endif /* GL_SGIX_scalebias_hint */ + +#ifndef GL_SGIX_shadow +#define GL_SGIX_shadow 1 +#define GL_TEXTURE_COMPARE_SGIX 0x819A +#define GL_TEXTURE_COMPARE_OPERATOR_SGIX 0x819B +#define GL_TEXTURE_LEQUAL_R_SGIX 0x819C +#define GL_TEXTURE_GEQUAL_R_SGIX 0x819D +#endif /* GL_SGIX_shadow */ + +#ifndef GL_SGIX_shadow_ambient +#define GL_SGIX_shadow_ambient 1 +#define GL_SHADOW_AMBIENT_SGIX 0x80BF +#endif /* GL_SGIX_shadow_ambient */ + +#ifndef GL_SGIX_sprite +#define GL_SGIX_sprite 1 +#define GL_SPRITE_SGIX 0x8148 +#define GL_SPRITE_MODE_SGIX 0x8149 +#define GL_SPRITE_AXIS_SGIX 0x814A +#define GL_SPRITE_TRANSLATION_SGIX 0x814B +#define GL_SPRITE_AXIAL_SGIX 0x814C +#define GL_SPRITE_OBJECT_ALIGNED_SGIX 0x814D +#define GL_SPRITE_EYE_ALIGNED_SGIX 0x814E +typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum pname, GLfloat param); +GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum pname, GLint param); +GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum pname, const GLint *params); +#endif +#endif /* GL_SGIX_sprite */ + +#ifndef GL_SGIX_subsample +#define GL_SGIX_subsample 1 +#define GL_PACK_SUBSAMPLE_RATE_SGIX 0x85A0 +#define GL_UNPACK_SUBSAMPLE_RATE_SGIX 0x85A1 +#define GL_PIXEL_SUBSAMPLE_4444_SGIX 0x85A2 +#define GL_PIXEL_SUBSAMPLE_2424_SGIX 0x85A3 +#define GL_PIXEL_SUBSAMPLE_4242_SGIX 0x85A4 +#endif /* GL_SGIX_subsample */ + +#ifndef GL_SGIX_tag_sample_buffer +#define GL_SGIX_tag_sample_buffer 1 +typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTagSampleBufferSGIX (void); +#endif +#endif /* GL_SGIX_tag_sample_buffer */ + +#ifndef GL_SGIX_texture_add_env +#define GL_SGIX_texture_add_env 1 +#define GL_TEXTURE_ENV_BIAS_SGIX 0x80BE +#endif /* GL_SGIX_texture_add_env */ + +#ifndef GL_SGIX_texture_coordinate_clamp +#define GL_SGIX_texture_coordinate_clamp 1 +#define GL_TEXTURE_MAX_CLAMP_S_SGIX 0x8369 +#define GL_TEXTURE_MAX_CLAMP_T_SGIX 0x836A +#define GL_TEXTURE_MAX_CLAMP_R_SGIX 0x836B +#endif /* GL_SGIX_texture_coordinate_clamp */ + +#ifndef GL_SGIX_texture_lod_bias +#define GL_SGIX_texture_lod_bias 1 +#define GL_TEXTURE_LOD_BIAS_S_SGIX 0x818E +#define GL_TEXTURE_LOD_BIAS_T_SGIX 0x818F +#define GL_TEXTURE_LOD_BIAS_R_SGIX 0x8190 +#endif /* GL_SGIX_texture_lod_bias */ + +#ifndef GL_SGIX_texture_multi_buffer +#define GL_SGIX_texture_multi_buffer 1 +#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E +#endif /* GL_SGIX_texture_multi_buffer */ + +#ifndef GL_SGIX_texture_scale_bias +#define GL_SGIX_texture_scale_bias 1 +#define GL_POST_TEXTURE_FILTER_BIAS_SGIX 0x8179 +#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A +#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B +#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C +#endif /* GL_SGIX_texture_scale_bias */ + +#ifndef GL_SGIX_vertex_preclip +#define GL_SGIX_vertex_preclip 1 +#define GL_VERTEX_PRECLIP_SGIX 0x83EE +#define GL_VERTEX_PRECLIP_HINT_SGIX 0x83EF +#endif /* GL_SGIX_vertex_preclip */ + +#ifndef GL_SGIX_ycrcb +#define GL_SGIX_ycrcb 1 +#define GL_YCRCB_422_SGIX 0x81BB +#define GL_YCRCB_444_SGIX 0x81BC +#endif /* GL_SGIX_ycrcb */ + +#ifndef GL_SGIX_ycrcb_subsample +#define GL_SGIX_ycrcb_subsample 1 +#endif /* GL_SGIX_ycrcb_subsample */ + +#ifndef GL_SGIX_ycrcba +#define GL_SGIX_ycrcba 1 +#define GL_YCRCB_SGIX 0x8318 +#define GL_YCRCBA_SGIX 0x8319 +#endif /* GL_SGIX_ycrcba */ + +#ifndef GL_SGI_color_matrix +#define GL_SGI_color_matrix 1 +#define GL_COLOR_MATRIX_SGI 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB +#endif /* GL_SGI_color_matrix */ + +#ifndef GL_SGI_color_table +#define GL_SGI_color_table 1 +#define GL_COLOR_TABLE_SGI 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2 +#define GL_PROXY_COLOR_TABLE_SGI 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5 +#define GL_COLOR_TABLE_SCALE_SGI 0x80D6 +#define GL_COLOR_TABLE_BIAS_SGI 0x80D7 +#define GL_COLOR_TABLE_FORMAT_SGI 0x80D8 +#define GL_COLOR_TABLE_WIDTH_SGI 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE_SGI 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE_SGI 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE_SGI 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE_SGI 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF +typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTableSGI (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glColorTableParameterivSGI (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyColorTableSGI (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glGetColorTableSGI (GLenum target, GLenum format, GLenum type, void *table); +GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum target, GLenum pname, GLint *params); +#endif +#endif /* GL_SGI_color_table */ + +#ifndef GL_SGI_texture_color_table +#define GL_SGI_texture_color_table 1 +#define GL_TEXTURE_COLOR_TABLE_SGI 0x80BC +#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI 0x80BD +#endif /* GL_SGI_texture_color_table */ + +#ifndef GL_SUNX_constant_data +#define GL_SUNX_constant_data 1 +#define GL_UNPACK_CONSTANT_DATA_SUNX 0x81D5 +#define GL_TEXTURE_CONSTANT_DATA_SUNX 0x81D6 +typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFinishTextureSUNX (void); +#endif +#endif /* GL_SUNX_constant_data */ + +#ifndef GL_SUN_convolution_border_modes +#define GL_SUN_convolution_border_modes 1 +#define GL_WRAP_BORDER_SUN 0x81D4 +#endif /* GL_SUN_convolution_border_modes */ + +#ifndef GL_SUN_global_alpha +#define GL_SUN_global_alpha 1 +#define GL_GLOBAL_ALPHA_SUN 0x81D9 +#define GL_GLOBAL_ALPHA_FACTOR_SUN 0x81DA +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte factor); +GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort factor); +GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint factor); +GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat factor); +GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble factor); +GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte factor); +GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort factor); +GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint factor); +#endif +#endif /* GL_SUN_global_alpha */ + +#ifndef GL_SUN_mesh_array +#define GL_SUN_mesh_array 1 +#define GL_QUAD_MESH_SUN 0x8614 +#define GL_TRIANGLE_MESH_SUN 0x8615 +typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum mode, GLint first, GLsizei count, GLsizei width); +#endif +#endif /* GL_SUN_mesh_array */ + +#ifndef GL_SUN_slice_accum +#define GL_SUN_slice_accum 1 +#define GL_SLICE_ACCUM_SUN 0x85CC +#endif /* GL_SUN_slice_accum */ + +#ifndef GL_SUN_triangle_list +#define GL_SUN_triangle_list 1 +#define GL_RESTART_SUN 0x0001 +#define GL_REPLACE_MIDDLE_SUN 0x0002 +#define GL_REPLACE_OLDEST_SUN 0x0003 +#define GL_TRIANGLE_LIST_SUN 0x81D7 +#define GL_REPLACEMENT_CODE_SUN 0x81D8 +#define GL_REPLACEMENT_CODE_ARRAY_SUN 0x85C0 +#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1 +#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2 +#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3 +#define GL_R1UI_V3F_SUN 0x85C4 +#define GL_R1UI_C4UB_V3F_SUN 0x85C5 +#define GL_R1UI_C3F_V3F_SUN 0x85C6 +#define GL_R1UI_N3F_V3F_SUN 0x85C7 +#define GL_R1UI_C4F_N3F_V3F_SUN 0x85C8 +#define GL_R1UI_T2F_V3F_SUN 0x85C9 +#define GL_R1UI_T2F_N3F_V3F_SUN 0x85CA +#define GL_R1UI_T2F_C4F_N3F_V3F_SUN 0x85CB +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint code); +GLAPI void APIENTRY glReplacementCodeusSUN (GLushort code); +GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte code); +GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *code); +GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *code); +GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *code); +GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum type, GLsizei stride, const void **pointer); +#endif +#endif /* GL_SUN_triangle_list */ + +#ifndef GL_SUN_vertex +#define GL_SUN_vertex 1 +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y); +GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *tc, const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint rc, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *rc, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *rc, const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +#endif +#endif /* GL_SUN_vertex */ + +#ifndef GL_WIN_phong_shading +#define GL_WIN_phong_shading 1 +#define GL_PHONG_WIN 0x80EA +#define GL_PHONG_HINT_WIN 0x80EB +#endif /* GL_WIN_phong_shading */ + +#ifndef GL_WIN_specular_fog +#define GL_WIN_specular_fog 1 +#define GL_FOG_SPECULAR_TEXTURE_WIN 0x80EC +#endif /* GL_WIN_specular_fog */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/third_party/SDL2/include/SDL_opengles.h b/third_party/SDL2/include/SDL_opengles.h new file mode 100644 index 00000000000..adf6ef782f7 --- /dev/null +++ b/third_party/SDL2/include/SDL_opengles.h @@ -0,0 +1,38 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * This is a simple file to encapsulate the OpenGL ES 1.X API headers. + */ + +#include "SDL_config.h" + +#ifdef __IPHONEOS__ +#include +#include +#else +#include +#include +#endif + +#ifndef APIENTRY +#define APIENTRY +#endif diff --git a/third_party/SDL2/include/SDL_opengles2.h b/third_party/SDL2/include/SDL_opengles2.h new file mode 100644 index 00000000000..5514197124a --- /dev/null +++ b/third_party/SDL2/include/SDL_opengles2.h @@ -0,0 +1,51 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * This is a simple file to encapsulate the OpenGL ES 2.0 API headers. + */ + +#include "SDL_config.h" + +#if !defined(_MSC_VER) && !defined(SDL_USE_BUILTIN_OPENGL_DEFINITIONS) + +#ifdef __IPHONEOS__ +#include +#include +#else +#include +#include +#include +#endif + +#else /* _MSC_VER */ + +/* OpenGL ES2 headers for Visual Studio */ +#include "SDL_opengles2_khrplatform.h" +#include "SDL_opengles2_gl2platform.h" +#include "SDL_opengles2_gl2.h" +#include "SDL_opengles2_gl2ext.h" + +#endif /* _MSC_VER */ + +#ifndef APIENTRY +#define APIENTRY GL_APIENTRY +#endif diff --git a/third_party/SDL2/include/SDL_opengles2_gl2.h b/third_party/SDL2/include/SDL_opengles2_gl2.h new file mode 100644 index 00000000000..d13622aae91 --- /dev/null +++ b/third_party/SDL2/include/SDL_opengles2_gl2.h @@ -0,0 +1,656 @@ +#ifndef __gles2_gl2_h_ +#define __gles2_gl2_h_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright 2013-2020 The Khronos Group Inc. +** SPDX-License-Identifier: MIT +** +** This header is generated from the Khronos OpenGL / OpenGL ES XML +** API Registry. The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** https://github.com/KhronosGroup/OpenGL-Registry +*/ + +/*#include */ + +#ifndef GL_APIENTRYP +#define GL_APIENTRYP GL_APIENTRY* +#endif + +#ifndef GL_GLES_PROTOTYPES +#define GL_GLES_PROTOTYPES 1 +#endif + +/* Generated on date 20220530 */ + +/* Generated C header for: + * API: gles2 + * Profile: common + * Versions considered: 2\.[0-9] + * Versions emitted: .* + * Default extensions included: None + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ + +#ifndef GL_ES_VERSION_2_0 +#define GL_ES_VERSION_2_0 1 +/*#include */ +typedef khronos_int8_t GLbyte; +typedef khronos_float_t GLclampf; +typedef khronos_int32_t GLfixed; +typedef khronos_int16_t GLshort; +typedef khronos_uint16_t GLushort; +typedef void GLvoid; +typedef struct __GLsync *GLsync; +typedef khronos_int64_t GLint64; +typedef khronos_uint64_t GLuint64; +typedef unsigned int GLenum; +typedef unsigned int GLuint; +typedef char GLchar; +typedef khronos_float_t GLfloat; +typedef khronos_ssize_t GLsizeiptr; +typedef khronos_intptr_t GLintptr; +typedef unsigned int GLbitfield; +typedef int GLint; +typedef unsigned char GLboolean; +typedef int GLsizei; +typedef khronos_uint8_t GLubyte; +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_FALSE 0 +#define GL_TRUE 1 +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_FUNC_ADD 0x8006 +#define GL_BLEND_EQUATION 0x8009 +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +#define GL_BLEND_COLOR 0x8005 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_STREAM_DRAW 0x88E0 +#define GL_STATIC_DRAW 0x88E4 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_CULL_FACE 0x0B44 +#define GL_BLEND 0x0BE2 +#define GL_DITHER 0x0BD0 +#define GL_STENCIL_TEST 0x0B90 +#define GL_DEPTH_TEST 0x0B71 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_OUT_OF_MEMORY 0x0505 +#define GL_CW 0x0900 +#define GL_CCW 0x0901 +#define GL_LINE_WIDTH 0x0B21 +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_VIEWPORT 0x0BA2 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_RED_BITS 0x0D52 +#define GL_GREEN_BITS 0x0D53 +#define GL_BLUE_BITS 0x0D54 +#define GL_ALPHA_BITS 0x0D55 +#define GL_DEPTH_BITS 0x0D56 +#define GL_STENCIL_BITS 0x0D57 +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_INT 0x1404 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_FIXED 0x140C +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_ALPHA 0x1906 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE_ALPHA 0x190A +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB +#define GL_MAX_VARYING_VECTORS 0x8DFC +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD +#define GL_SHADER_TYPE 0x8B4F +#define GL_DELETE_STATUS 0x8B80 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 +#define GL_INVERT 0x150A +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_TEXTURE 0x1702 +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_REPEAT 0x2901 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B +#define GL_COMPILE_STATUS 0x8B81 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_SHADER_COMPILER 0x8DFA +#define GL_SHADER_BINARY_FORMATS 0x8DF8 +#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 +#define GL_LOW_FLOAT 0x8DF0 +#define GL_MEDIUM_FLOAT 0x8DF1 +#define GL_HIGH_FLOAT 0x8DF2 +#define GL_LOW_INT 0x8DF3 +#define GL_MEDIUM_INT 0x8DF4 +#define GL_HIGH_INT 0x8DF5 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGB565 0x8D62 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_STENCIL_INDEX8 0x8D48 +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_STENCIL_ATTACHMENT 0x8D20 +#define GL_NONE 0 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +typedef void (GL_APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); +typedef void (GL_APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (GL_APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); +typedef void (GL_APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); +typedef void (GL_APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer); +typedef void (GL_APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer); +typedef void (GL_APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture); +typedef void (GL_APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); +typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); +typedef void (GL_APIENTRYP PFNGLBLENDFUNCPROC) (GLenum sfactor, GLenum dfactor); +typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +typedef void (GL_APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +typedef void (GL_APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +typedef GLenum (GL_APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target); +typedef void (GL_APIENTRYP PFNGLCLEARPROC) (GLbitfield mask); +typedef void (GL_APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (GL_APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d); +typedef void (GL_APIENTRYP PFNGLCLEARSTENCILPROC) (GLint s); +typedef void (GL_APIENTRYP PFNGLCOLORMASKPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +typedef void (GL_APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); +typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (GL_APIENTRYP PFNGLCOPYTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef GLuint (GL_APIENTRYP PFNGLCREATEPROGRAMPROC) (void); +typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); +typedef void (GL_APIENTRYP PFNGLCULLFACEPROC) (GLenum mode); +typedef void (GL_APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); +typedef void (GL_APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers); +typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); +typedef void (GL_APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers); +typedef void (GL_APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); +typedef void (GL_APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures); +typedef void (GL_APIENTRYP PFNGLDEPTHFUNCPROC) (GLenum func); +typedef void (GL_APIENTRYP PFNGLDEPTHMASKPROC) (GLboolean flag); +typedef void (GL_APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f); +typedef void (GL_APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (GL_APIENTRYP PFNGLDISABLEPROC) (GLenum cap); +typedef void (GL_APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (GL_APIENTRYP PFNGLDRAWARRAYSPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices); +typedef void (GL_APIENTRYP PFNGLENABLEPROC) (GLenum cap); +typedef void (GL_APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (GL_APIENTRYP PFNGLFINISHPROC) (void); +typedef void (GL_APIENTRYP PFNGLFLUSHPROC) (void); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (GL_APIENTRYP PFNGLFRONTFACEPROC) (GLenum mode); +typedef void (GL_APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef void (GL_APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target); +typedef void (GL_APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); +typedef void (GL_APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (GL_APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures); +typedef void (GL_APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (GL_APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +typedef GLint (GL_APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (GL_APIENTRYP PFNGLGETBOOLEANVPROC) (GLenum pname, GLboolean *data); +typedef void (GL_APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef GLenum (GL_APIENTRYP PFNGLGETERRORPROC) (void); +typedef void (GL_APIENTRYP PFNGLGETFLOATVPROC) (GLenum pname, GLfloat *data); +typedef void (GL_APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data); +typedef void (GL_APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (GL_APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (GL_APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +typedef void (GL_APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +typedef const GLubyte *(GL_APIENTRYP PFNGLGETSTRINGPROC) (GLenum name); +typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); +typedef void (GL_APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); +typedef GLint (GL_APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); +typedef void (GL_APIENTRYP PFNGLHINTPROC) (GLenum target, GLenum mode); +typedef GLboolean (GL_APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); +typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDPROC) (GLenum cap); +typedef GLboolean (GL_APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer); +typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); +typedef GLboolean (GL_APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer); +typedef GLboolean (GL_APIENTRYP PFNGLISSHADERPROC) (GLuint shader); +typedef GLboolean (GL_APIENTRYP PFNGLISTEXTUREPROC) (GLuint texture); +typedef void (GL_APIENTRYP PFNGLLINEWIDTHPROC) (GLfloat width); +typedef void (GL_APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); +typedef void (GL_APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param); +typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETPROC) (GLfloat factor, GLfloat units); +typedef void (GL_APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); +typedef void (GL_APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void); +typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert); +typedef void (GL_APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryFormat, const void *binary, GLsizei length); +typedef void (GL_APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +typedef void (GL_APIENTRYP PFNGLSTENCILFUNCPROC) (GLenum func, GLint ref, GLuint mask); +typedef void (GL_APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask); +typedef void (GL_APIENTRYP PFNGLSTENCILMASKPROC) (GLuint mask); +typedef void (GL_APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); +typedef void (GL_APIENTRYP PFNGLSTENCILOPPROC) (GLenum fail, GLenum zfail, GLenum zpass); +typedef void (GL_APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (GL_APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (GL_APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); +typedef void (GL_APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); +typedef void (GL_APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (GL_APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); +typedef void (GL_APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (GL_APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (GL_APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (GL_APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (GL_APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); +typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +typedef void (GL_APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height); +#if GL_GLES_PROTOTYPES +GL_APICALL void GL_APIENTRY glActiveTexture (GLenum texture); +GL_APICALL void GL_APIENTRY glAttachShader (GLuint program, GLuint shader); +GL_APICALL void GL_APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name); +GL_APICALL void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer); +GL_APICALL void GL_APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer); +GL_APICALL void GL_APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer); +GL_APICALL void GL_APIENTRY glBindTexture (GLenum target, GLuint texture); +GL_APICALL void GL_APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GL_APICALL void GL_APIENTRY glBlendEquation (GLenum mode); +GL_APICALL void GL_APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); +GL_APICALL void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor); +GL_APICALL void GL_APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +GL_APICALL void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +GL_APICALL void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +GL_APICALL GLenum GL_APIENTRY glCheckFramebufferStatus (GLenum target); +GL_APICALL void GL_APIENTRY glClear (GLbitfield mask); +GL_APICALL void GL_APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GL_APICALL void GL_APIENTRY glClearDepthf (GLfloat d); +GL_APICALL void GL_APIENTRY glClearStencil (GLint s); +GL_APICALL void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +GL_APICALL void GL_APIENTRY glCompileShader (GLuint shader); +GL_APICALL void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GL_APICALL void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GL_APICALL void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GL_APICALL void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GL_APICALL GLuint GL_APIENTRY glCreateProgram (void); +GL_APICALL GLuint GL_APIENTRY glCreateShader (GLenum type); +GL_APICALL void GL_APIENTRY glCullFace (GLenum mode); +GL_APICALL void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); +GL_APICALL void GL_APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers); +GL_APICALL void GL_APIENTRY glDeleteProgram (GLuint program); +GL_APICALL void GL_APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers); +GL_APICALL void GL_APIENTRY glDeleteShader (GLuint shader); +GL_APICALL void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures); +GL_APICALL void GL_APIENTRY glDepthFunc (GLenum func); +GL_APICALL void GL_APIENTRY glDepthMask (GLboolean flag); +GL_APICALL void GL_APIENTRY glDepthRangef (GLfloat n, GLfloat f); +GL_APICALL void GL_APIENTRY glDetachShader (GLuint program, GLuint shader); +GL_APICALL void GL_APIENTRY glDisable (GLenum cap); +GL_APICALL void GL_APIENTRY glDisableVertexAttribArray (GLuint index); +GL_APICALL void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count); +GL_APICALL void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices); +GL_APICALL void GL_APIENTRY glEnable (GLenum cap); +GL_APICALL void GL_APIENTRY glEnableVertexAttribArray (GLuint index); +GL_APICALL void GL_APIENTRY glFinish (void); +GL_APICALL void GL_APIENTRY glFlush (void); +GL_APICALL void GL_APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GL_APICALL void GL_APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GL_APICALL void GL_APIENTRY glFrontFace (GLenum mode); +GL_APICALL void GL_APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); +GL_APICALL void GL_APIENTRY glGenerateMipmap (GLenum target); +GL_APICALL void GL_APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers); +GL_APICALL void GL_APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers); +GL_APICALL void GL_APIENTRY glGenTextures (GLsizei n, GLuint *textures); +GL_APICALL void GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GL_APICALL void GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GL_APICALL void GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +GL_APICALL GLint GL_APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); +GL_APICALL void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean *data); +GL_APICALL void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); +GL_APICALL GLenum GL_APIENTRY glGetError (void); +GL_APICALL void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat *data); +GL_APICALL void GL_APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetIntegerv (GLenum pname, GLint *data); +GL_APICALL void GL_APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GL_APICALL void GL_APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GL_APICALL void GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +GL_APICALL void GL_APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +GL_APICALL const GLubyte *GL_APIENTRY glGetString (GLenum name); +GL_APICALL void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params); +GL_APICALL void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params); +GL_APICALL void GL_APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params); +GL_APICALL GLint GL_APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); +GL_APICALL void GL_APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params); +GL_APICALL void GL_APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); +GL_APICALL void GL_APIENTRY glHint (GLenum target, GLenum mode); +GL_APICALL GLboolean GL_APIENTRY glIsBuffer (GLuint buffer); +GL_APICALL GLboolean GL_APIENTRY glIsEnabled (GLenum cap); +GL_APICALL GLboolean GL_APIENTRY glIsFramebuffer (GLuint framebuffer); +GL_APICALL GLboolean GL_APIENTRY glIsProgram (GLuint program); +GL_APICALL GLboolean GL_APIENTRY glIsRenderbuffer (GLuint renderbuffer); +GL_APICALL GLboolean GL_APIENTRY glIsShader (GLuint shader); +GL_APICALL GLboolean GL_APIENTRY glIsTexture (GLuint texture); +GL_APICALL void GL_APIENTRY glLineWidth (GLfloat width); +GL_APICALL void GL_APIENTRY glLinkProgram (GLuint program); +GL_APICALL void GL_APIENTRY glPixelStorei (GLenum pname, GLint param); +GL_APICALL void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units); +GL_APICALL void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); +GL_APICALL void GL_APIENTRY glReleaseShaderCompiler (void); +GL_APICALL void GL_APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glSampleCoverage (GLfloat value, GLboolean invert); +GL_APICALL void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryFormat, const void *binary, GLsizei length); +GL_APICALL void GL_APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +GL_APICALL void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask); +GL_APICALL void GL_APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask); +GL_APICALL void GL_APIENTRY glStencilMask (GLuint mask); +GL_APICALL void GL_APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask); +GL_APICALL void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass); +GL_APICALL void GL_APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GL_APICALL void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GL_APICALL void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param); +GL_APICALL void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params); +GL_APICALL void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param); +GL_APICALL void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params); +GL_APICALL void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GL_APICALL void GL_APIENTRY glUniform1f (GLint location, GLfloat v0); +GL_APICALL void GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniform1i (GLint location, GLint v0); +GL_APICALL void GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value); +GL_APICALL void GL_APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1); +GL_APICALL void GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniform2i (GLint location, GLint v0, GLint v1); +GL_APICALL void GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value); +GL_APICALL void GL_APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GL_APICALL void GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2); +GL_APICALL void GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value); +GL_APICALL void GL_APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GL_APICALL void GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GL_APICALL void GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value); +GL_APICALL void GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUseProgram (GLuint program); +GL_APICALL void GL_APIENTRY glValidateProgram (GLuint program); +GL_APICALL void GL_APIENTRY glVertexAttrib1f (GLuint index, GLfloat x); +GL_APICALL void GL_APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v); +GL_APICALL void GL_APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y); +GL_APICALL void GL_APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v); +GL_APICALL void GL_APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GL_APICALL void GL_APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v); +GL_APICALL void GL_APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GL_APICALL void GL_APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v); +GL_APICALL void GL_APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +GL_APICALL void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height); +#endif +#endif /* GL_ES_VERSION_2_0 */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/third_party/SDL2/include/SDL_opengles2_gl2ext.h b/third_party/SDL2/include/SDL_opengles2_gl2ext.h new file mode 100644 index 00000000000..9448ce09fc7 --- /dev/null +++ b/third_party/SDL2/include/SDL_opengles2_gl2ext.h @@ -0,0 +1,4033 @@ +#ifndef __gles2_gl2ext_h_ +#define __gles2_gl2ext_h_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright 2013-2020 The Khronos Group Inc. +** SPDX-License-Identifier: MIT +** +** This header is generated from the Khronos OpenGL / OpenGL ES XML +** API Registry. The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** https://github.com/KhronosGroup/OpenGL-Registry +*/ + +#ifndef GL_APIENTRYP +#define GL_APIENTRYP GL_APIENTRY* +#endif + +/* Generated on date 20220530 */ + +/* Generated C header for: + * API: gles2 + * Profile: common + * Versions considered: 2\.[0-9] + * Versions emitted: _nomatch_^ + * Default extensions included: gles2 + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ + +#ifndef GL_KHR_blend_equation_advanced +#define GL_KHR_blend_equation_advanced 1 +#define GL_MULTIPLY_KHR 0x9294 +#define GL_SCREEN_KHR 0x9295 +#define GL_OVERLAY_KHR 0x9296 +#define GL_DARKEN_KHR 0x9297 +#define GL_LIGHTEN_KHR 0x9298 +#define GL_COLORDODGE_KHR 0x9299 +#define GL_COLORBURN_KHR 0x929A +#define GL_HARDLIGHT_KHR 0x929B +#define GL_SOFTLIGHT_KHR 0x929C +#define GL_DIFFERENCE_KHR 0x929E +#define GL_EXCLUSION_KHR 0x92A0 +#define GL_HSL_HUE_KHR 0x92AD +#define GL_HSL_SATURATION_KHR 0x92AE +#define GL_HSL_COLOR_KHR 0x92AF +#define GL_HSL_LUMINOSITY_KHR 0x92B0 +typedef void (GL_APIENTRYP PFNGLBLENDBARRIERKHRPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBlendBarrierKHR (void); +#endif +#endif /* GL_KHR_blend_equation_advanced */ + +#ifndef GL_KHR_blend_equation_advanced_coherent +#define GL_KHR_blend_equation_advanced_coherent 1 +#define GL_BLEND_ADVANCED_COHERENT_KHR 0x9285 +#endif /* GL_KHR_blend_equation_advanced_coherent */ + +#ifndef GL_KHR_context_flush_control +#define GL_KHR_context_flush_control 1 +#define GL_CONTEXT_RELEASE_BEHAVIOR_KHR 0x82FB +#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR 0x82FC +#endif /* GL_KHR_context_flush_control */ + +#ifndef GL_KHR_debug +#define GL_KHR_debug 1 +typedef void (GL_APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#define GL_SAMPLER 0x82E6 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_KHR 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION_KHR 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM_KHR 0x8245 +#define GL_DEBUG_SOURCE_API_KHR 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER_KHR 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY_KHR 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION_KHR 0x824A +#define GL_DEBUG_SOURCE_OTHER_KHR 0x824B +#define GL_DEBUG_TYPE_ERROR_KHR 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR 0x824E +#define GL_DEBUG_TYPE_PORTABILITY_KHR 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE_KHR 0x8250 +#define GL_DEBUG_TYPE_OTHER_KHR 0x8251 +#define GL_DEBUG_TYPE_MARKER_KHR 0x8268 +#define GL_DEBUG_TYPE_PUSH_GROUP_KHR 0x8269 +#define GL_DEBUG_TYPE_POP_GROUP_KHR 0x826A +#define GL_DEBUG_SEVERITY_NOTIFICATION_KHR 0x826B +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH_KHR 0x826C +#define GL_DEBUG_GROUP_STACK_DEPTH_KHR 0x826D +#define GL_BUFFER_KHR 0x82E0 +#define GL_SHADER_KHR 0x82E1 +#define GL_PROGRAM_KHR 0x82E2 +#define GL_VERTEX_ARRAY_KHR 0x8074 +#define GL_QUERY_KHR 0x82E3 +#define GL_PROGRAM_PIPELINE_KHR 0x82E4 +#define GL_SAMPLER_KHR 0x82E6 +#define GL_MAX_LABEL_LENGTH_KHR 0x82E8 +#define GL_MAX_DEBUG_MESSAGE_LENGTH_KHR 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES_KHR 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES_KHR 0x9145 +#define GL_DEBUG_SEVERITY_HIGH_KHR 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM_KHR 0x9147 +#define GL_DEBUG_SEVERITY_LOW_KHR 0x9148 +#define GL_DEBUG_OUTPUT_KHR 0x92E0 +#define GL_CONTEXT_FLAG_DEBUG_BIT_KHR 0x00000002 +#define GL_STACK_OVERFLOW_KHR 0x0503 +#define GL_STACK_UNDERFLOW_KHR 0x0504 +typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGECONTROLKHRPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGEINSERTKHRPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGECALLBACKKHRPROC) (GLDEBUGPROCKHR callback, const void *userParam); +typedef GLuint (GL_APIENTRYP PFNGLGETDEBUGMESSAGELOGKHRPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +typedef void (GL_APIENTRYP PFNGLPUSHDEBUGGROUPKHRPROC) (GLenum source, GLuint id, GLsizei length, const GLchar *message); +typedef void (GL_APIENTRYP PFNGLPOPDEBUGGROUPKHRPROC) (void); +typedef void (GL_APIENTRYP PFNGLOBJECTLABELKHRPROC) (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +typedef void (GL_APIENTRYP PFNGLGETOBJECTLABELKHRPROC) (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +typedef void (GL_APIENTRYP PFNGLOBJECTPTRLABELKHRPROC) (const void *ptr, GLsizei length, const GLchar *label); +typedef void (GL_APIENTRYP PFNGLGETOBJECTPTRLABELKHRPROC) (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +typedef void (GL_APIENTRYP PFNGLGETPOINTERVKHRPROC) (GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDebugMessageControlKHR (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GL_APICALL void GL_APIENTRY glDebugMessageInsertKHR (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GL_APICALL void GL_APIENTRY glDebugMessageCallbackKHR (GLDEBUGPROCKHR callback, const void *userParam); +GL_APICALL GLuint GL_APIENTRY glGetDebugMessageLogKHR (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +GL_APICALL void GL_APIENTRY glPushDebugGroupKHR (GLenum source, GLuint id, GLsizei length, const GLchar *message); +GL_APICALL void GL_APIENTRY glPopDebugGroupKHR (void); +GL_APICALL void GL_APIENTRY glObjectLabelKHR (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +GL_APICALL void GL_APIENTRY glGetObjectLabelKHR (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +GL_APICALL void GL_APIENTRY glObjectPtrLabelKHR (const void *ptr, GLsizei length, const GLchar *label); +GL_APICALL void GL_APIENTRY glGetObjectPtrLabelKHR (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +GL_APICALL void GL_APIENTRY glGetPointervKHR (GLenum pname, void **params); +#endif +#endif /* GL_KHR_debug */ + +#ifndef GL_KHR_no_error +#define GL_KHR_no_error 1 +#define GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR 0x00000008 +#endif /* GL_KHR_no_error */ + +#ifndef GL_KHR_parallel_shader_compile +#define GL_KHR_parallel_shader_compile 1 +#define GL_MAX_SHADER_COMPILER_THREADS_KHR 0x91B0 +#define GL_COMPLETION_STATUS_KHR 0x91B1 +typedef void (GL_APIENTRYP PFNGLMAXSHADERCOMPILERTHREADSKHRPROC) (GLuint count); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glMaxShaderCompilerThreadsKHR (GLuint count); +#endif +#endif /* GL_KHR_parallel_shader_compile */ + +#ifndef GL_KHR_robust_buffer_access_behavior +#define GL_KHR_robust_buffer_access_behavior 1 +#endif /* GL_KHR_robust_buffer_access_behavior */ + +#ifndef GL_KHR_robustness +#define GL_KHR_robustness 1 +#define GL_CONTEXT_ROBUST_ACCESS_KHR 0x90F3 +#define GL_LOSE_CONTEXT_ON_RESET_KHR 0x8252 +#define GL_GUILTY_CONTEXT_RESET_KHR 0x8253 +#define GL_INNOCENT_CONTEXT_RESET_KHR 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET_KHR 0x8255 +#define GL_RESET_NOTIFICATION_STRATEGY_KHR 0x8256 +#define GL_NO_RESET_NOTIFICATION_KHR 0x8261 +#define GL_CONTEXT_LOST_KHR 0x0507 +typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSKHRPROC) (void); +typedef void (GL_APIENTRYP PFNGLREADNPIXELSKHRPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETNUNIFORMUIVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL GLenum GL_APIENTRY glGetGraphicsResetStatusKHR (void); +GL_APICALL void GL_APIENTRY glReadnPixelsKHR (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GL_APICALL void GL_APIENTRY glGetnUniformfvKHR (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GL_APICALL void GL_APIENTRY glGetnUniformivKHR (GLuint program, GLint location, GLsizei bufSize, GLint *params); +GL_APICALL void GL_APIENTRY glGetnUniformuivKHR (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +#endif +#endif /* GL_KHR_robustness */ + +#ifndef GL_KHR_shader_subgroup +#define GL_KHR_shader_subgroup 1 +#define GL_SUBGROUP_SIZE_KHR 0x9532 +#define GL_SUBGROUP_SUPPORTED_STAGES_KHR 0x9533 +#define GL_SUBGROUP_SUPPORTED_FEATURES_KHR 0x9534 +#define GL_SUBGROUP_QUAD_ALL_STAGES_KHR 0x9535 +#define GL_SUBGROUP_FEATURE_BASIC_BIT_KHR 0x00000001 +#define GL_SUBGROUP_FEATURE_VOTE_BIT_KHR 0x00000002 +#define GL_SUBGROUP_FEATURE_ARITHMETIC_BIT_KHR 0x00000004 +#define GL_SUBGROUP_FEATURE_BALLOT_BIT_KHR 0x00000008 +#define GL_SUBGROUP_FEATURE_SHUFFLE_BIT_KHR 0x00000010 +#define GL_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT_KHR 0x00000020 +#define GL_SUBGROUP_FEATURE_CLUSTERED_BIT_KHR 0x00000040 +#define GL_SUBGROUP_FEATURE_QUAD_BIT_KHR 0x00000080 +#endif /* GL_KHR_shader_subgroup */ + +#ifndef GL_KHR_texture_compression_astc_hdr +#define GL_KHR_texture_compression_astc_hdr 1 +#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0 +#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1 +#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2 +#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3 +#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4 +#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5 +#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6 +#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7 +#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8 +#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9 +#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA +#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB +#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC +#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD +#endif /* GL_KHR_texture_compression_astc_hdr */ + +#ifndef GL_KHR_texture_compression_astc_ldr +#define GL_KHR_texture_compression_astc_ldr 1 +#endif /* GL_KHR_texture_compression_astc_ldr */ + +#ifndef GL_KHR_texture_compression_astc_sliced_3d +#define GL_KHR_texture_compression_astc_sliced_3d 1 +#endif /* GL_KHR_texture_compression_astc_sliced_3d */ + +#ifndef GL_OES_EGL_image +#define GL_OES_EGL_image 1 +typedef void *GLeglImageOES; +typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image); +typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image); +GL_APICALL void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image); +#endif +#endif /* GL_OES_EGL_image */ + +#ifndef GL_OES_EGL_image_external +#define GL_OES_EGL_image_external 1 +#define GL_TEXTURE_EXTERNAL_OES 0x8D65 +#define GL_TEXTURE_BINDING_EXTERNAL_OES 0x8D67 +#define GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES 0x8D68 +#define GL_SAMPLER_EXTERNAL_OES 0x8D66 +#endif /* GL_OES_EGL_image_external */ + +#ifndef GL_OES_EGL_image_external_essl3 +#define GL_OES_EGL_image_external_essl3 1 +#endif /* GL_OES_EGL_image_external_essl3 */ + +#ifndef GL_OES_compressed_ETC1_RGB8_sub_texture +#define GL_OES_compressed_ETC1_RGB8_sub_texture 1 +#endif /* GL_OES_compressed_ETC1_RGB8_sub_texture */ + +#ifndef GL_OES_compressed_ETC1_RGB8_texture +#define GL_OES_compressed_ETC1_RGB8_texture 1 +#define GL_ETC1_RGB8_OES 0x8D64 +#endif /* GL_OES_compressed_ETC1_RGB8_texture */ + +#ifndef GL_OES_compressed_paletted_texture +#define GL_OES_compressed_paletted_texture 1 +#define GL_PALETTE4_RGB8_OES 0x8B90 +#define GL_PALETTE4_RGBA8_OES 0x8B91 +#define GL_PALETTE4_R5_G6_B5_OES 0x8B92 +#define GL_PALETTE4_RGBA4_OES 0x8B93 +#define GL_PALETTE4_RGB5_A1_OES 0x8B94 +#define GL_PALETTE8_RGB8_OES 0x8B95 +#define GL_PALETTE8_RGBA8_OES 0x8B96 +#define GL_PALETTE8_R5_G6_B5_OES 0x8B97 +#define GL_PALETTE8_RGBA4_OES 0x8B98 +#define GL_PALETTE8_RGB5_A1_OES 0x8B99 +#endif /* GL_OES_compressed_paletted_texture */ + +#ifndef GL_OES_copy_image +#define GL_OES_copy_image 1 +typedef void (GL_APIENTRYP PFNGLCOPYIMAGESUBDATAOESPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glCopyImageSubDataOES (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +#endif +#endif /* GL_OES_copy_image */ + +#ifndef GL_OES_depth24 +#define GL_OES_depth24 1 +#define GL_DEPTH_COMPONENT24_OES 0x81A6 +#endif /* GL_OES_depth24 */ + +#ifndef GL_OES_depth32 +#define GL_OES_depth32 1 +#define GL_DEPTH_COMPONENT32_OES 0x81A7 +#endif /* GL_OES_depth32 */ + +#ifndef GL_OES_depth_texture +#define GL_OES_depth_texture 1 +#endif /* GL_OES_depth_texture */ + +#ifndef GL_OES_draw_buffers_indexed +#define GL_OES_draw_buffers_indexed 1 +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +typedef void (GL_APIENTRYP PFNGLENABLEIOESPROC) (GLenum target, GLuint index); +typedef void (GL_APIENTRYP PFNGLDISABLEIOESPROC) (GLenum target, GLuint index); +typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONIOESPROC) (GLuint buf, GLenum mode); +typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEIOESPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +typedef void (GL_APIENTRYP PFNGLBLENDFUNCIOESPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEIOESPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +typedef void (GL_APIENTRYP PFNGLCOLORMASKIOESPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDIOESPROC) (GLenum target, GLuint index); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glEnableiOES (GLenum target, GLuint index); +GL_APICALL void GL_APIENTRY glDisableiOES (GLenum target, GLuint index); +GL_APICALL void GL_APIENTRY glBlendEquationiOES (GLuint buf, GLenum mode); +GL_APICALL void GL_APIENTRY glBlendEquationSeparateiOES (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GL_APICALL void GL_APIENTRY glBlendFunciOES (GLuint buf, GLenum src, GLenum dst); +GL_APICALL void GL_APIENTRY glBlendFuncSeparateiOES (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GL_APICALL void GL_APIENTRY glColorMaskiOES (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +GL_APICALL GLboolean GL_APIENTRY glIsEnablediOES (GLenum target, GLuint index); +#endif +#endif /* GL_OES_draw_buffers_indexed */ + +#ifndef GL_OES_draw_elements_base_vertex +#define GL_OES_draw_elements_base_vertex 1 +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXOESPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (GL_APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXOESPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawElementsBaseVertexOES (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GL_APICALL void GL_APIENTRY glDrawRangeElementsBaseVertexOES (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexOES (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +GL_APICALL void GL_APIENTRY glMultiDrawElementsBaseVertexEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +#endif +#endif /* GL_OES_draw_elements_base_vertex */ + +#ifndef GL_OES_element_index_uint +#define GL_OES_element_index_uint 1 +#endif /* GL_OES_element_index_uint */ + +#ifndef GL_OES_fbo_render_mipmap +#define GL_OES_fbo_render_mipmap 1 +#endif /* GL_OES_fbo_render_mipmap */ + +#ifndef GL_OES_fragment_precision_high +#define GL_OES_fragment_precision_high 1 +#endif /* GL_OES_fragment_precision_high */ + +#ifndef GL_OES_geometry_point_size +#define GL_OES_geometry_point_size 1 +#endif /* GL_OES_geometry_point_size */ + +#ifndef GL_OES_geometry_shader +#define GL_OES_geometry_shader 1 +#define GL_GEOMETRY_SHADER_OES 0x8DD9 +#define GL_GEOMETRY_SHADER_BIT_OES 0x00000004 +#define GL_GEOMETRY_LINKED_VERTICES_OUT_OES 0x8916 +#define GL_GEOMETRY_LINKED_INPUT_TYPE_OES 0x8917 +#define GL_GEOMETRY_LINKED_OUTPUT_TYPE_OES 0x8918 +#define GL_GEOMETRY_SHADER_INVOCATIONS_OES 0x887F +#define GL_LAYER_PROVOKING_VERTEX_OES 0x825E +#define GL_LINES_ADJACENCY_OES 0x000A +#define GL_LINE_STRIP_ADJACENCY_OES 0x000B +#define GL_TRIANGLES_ADJACENCY_OES 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_OES 0x000D +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_OES 0x8DDF +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS_OES 0x8A2C +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS_OES 0x8A32 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS_OES 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS_OES 0x9124 +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_OES 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_OES 0x8DE1 +#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS_OES 0x8E5A +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_OES 0x8C29 +#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS_OES 0x92CF +#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS_OES 0x92D5 +#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS_OES 0x90CD +#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS_OES 0x90D7 +#define GL_FIRST_VERTEX_CONVENTION_OES 0x8E4D +#define GL_LAST_VERTEX_CONVENTION_OES 0x8E4E +#define GL_UNDEFINED_VERTEX_OES 0x8260 +#define GL_PRIMITIVES_GENERATED_OES 0x8C87 +#define GL_FRAMEBUFFER_DEFAULT_LAYERS_OES 0x9312 +#define GL_MAX_FRAMEBUFFER_LAYERS_OES 0x9317 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_OES 0x8DA8 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_OES 0x8DA7 +#define GL_REFERENCED_BY_GEOMETRY_SHADER_OES 0x9309 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREOESPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferTextureOES (GLenum target, GLenum attachment, GLuint texture, GLint level); +#endif +#endif /* GL_OES_geometry_shader */ + +#ifndef GL_OES_get_program_binary +#define GL_OES_get_program_binary 1 +#define GL_PROGRAM_BINARY_LENGTH_OES 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS_OES 0x87FE +#define GL_PROGRAM_BINARY_FORMATS_OES 0x87FF +typedef void (GL_APIENTRYP PFNGLGETPROGRAMBINARYOESPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +typedef void (GL_APIENTRYP PFNGLPROGRAMBINARYOESPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLint length); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGetProgramBinaryOES (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +GL_APICALL void GL_APIENTRY glProgramBinaryOES (GLuint program, GLenum binaryFormat, const void *binary, GLint length); +#endif +#endif /* GL_OES_get_program_binary */ + +#ifndef GL_OES_gpu_shader5 +#define GL_OES_gpu_shader5 1 +#endif /* GL_OES_gpu_shader5 */ + +#ifndef GL_OES_mapbuffer +#define GL_OES_mapbuffer 1 +#define GL_WRITE_ONLY_OES 0x88B9 +#define GL_BUFFER_ACCESS_OES 0x88BB +#define GL_BUFFER_MAPPED_OES 0x88BC +#define GL_BUFFER_MAP_POINTER_OES 0x88BD +typedef void *(GL_APIENTRYP PFNGLMAPBUFFEROESPROC) (GLenum target, GLenum access); +typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFEROESPROC) (GLenum target); +typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVOESPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void *GL_APIENTRY glMapBufferOES (GLenum target, GLenum access); +GL_APICALL GLboolean GL_APIENTRY glUnmapBufferOES (GLenum target); +GL_APICALL void GL_APIENTRY glGetBufferPointervOES (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_OES_mapbuffer */ + +#ifndef GL_OES_packed_depth_stencil +#define GL_OES_packed_depth_stencil 1 +#define GL_DEPTH_STENCIL_OES 0x84F9 +#define GL_UNSIGNED_INT_24_8_OES 0x84FA +#define GL_DEPTH24_STENCIL8_OES 0x88F0 +#endif /* GL_OES_packed_depth_stencil */ + +#ifndef GL_OES_primitive_bounding_box +#define GL_OES_primitive_bounding_box 1 +#define GL_PRIMITIVE_BOUNDING_BOX_OES 0x92BE +typedef void (GL_APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXOESPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glPrimitiveBoundingBoxOES (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); +#endif +#endif /* GL_OES_primitive_bounding_box */ + +#ifndef GL_OES_required_internalformat +#define GL_OES_required_internalformat 1 +#define GL_ALPHA8_OES 0x803C +#define GL_DEPTH_COMPONENT16_OES 0x81A5 +#define GL_LUMINANCE4_ALPHA4_OES 0x8043 +#define GL_LUMINANCE8_ALPHA8_OES 0x8045 +#define GL_LUMINANCE8_OES 0x8040 +#define GL_RGBA4_OES 0x8056 +#define GL_RGB5_A1_OES 0x8057 +#define GL_RGB565_OES 0x8D62 +#define GL_RGB8_OES 0x8051 +#define GL_RGBA8_OES 0x8058 +#define GL_RGB10_EXT 0x8052 +#define GL_RGB10_A2_EXT 0x8059 +#endif /* GL_OES_required_internalformat */ + +#ifndef GL_OES_rgb8_rgba8 +#define GL_OES_rgb8_rgba8 1 +#endif /* GL_OES_rgb8_rgba8 */ + +#ifndef GL_OES_sample_shading +#define GL_OES_sample_shading 1 +#define GL_SAMPLE_SHADING_OES 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE_OES 0x8C37 +typedef void (GL_APIENTRYP PFNGLMINSAMPLESHADINGOESPROC) (GLfloat value); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glMinSampleShadingOES (GLfloat value); +#endif +#endif /* GL_OES_sample_shading */ + +#ifndef GL_OES_sample_variables +#define GL_OES_sample_variables 1 +#endif /* GL_OES_sample_variables */ + +#ifndef GL_OES_shader_image_atomic +#define GL_OES_shader_image_atomic 1 +#endif /* GL_OES_shader_image_atomic */ + +#ifndef GL_OES_shader_io_blocks +#define GL_OES_shader_io_blocks 1 +#endif /* GL_OES_shader_io_blocks */ + +#ifndef GL_OES_shader_multisample_interpolation +#define GL_OES_shader_multisample_interpolation 1 +#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_OES 0x8E5B +#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_OES 0x8E5C +#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS_OES 0x8E5D +#endif /* GL_OES_shader_multisample_interpolation */ + +#ifndef GL_OES_standard_derivatives +#define GL_OES_standard_derivatives 1 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES 0x8B8B +#endif /* GL_OES_standard_derivatives */ + +#ifndef GL_OES_stencil1 +#define GL_OES_stencil1 1 +#define GL_STENCIL_INDEX1_OES 0x8D46 +#endif /* GL_OES_stencil1 */ + +#ifndef GL_OES_stencil4 +#define GL_OES_stencil4 1 +#define GL_STENCIL_INDEX4_OES 0x8D47 +#endif /* GL_OES_stencil4 */ + +#ifndef GL_OES_surfaceless_context +#define GL_OES_surfaceless_context 1 +#define GL_FRAMEBUFFER_UNDEFINED_OES 0x8219 +#endif /* GL_OES_surfaceless_context */ + +#ifndef GL_OES_tessellation_point_size +#define GL_OES_tessellation_point_size 1 +#endif /* GL_OES_tessellation_point_size */ + +#ifndef GL_OES_tessellation_shader +#define GL_OES_tessellation_shader 1 +#define GL_PATCHES_OES 0x000E +#define GL_PATCH_VERTICES_OES 0x8E72 +#define GL_TESS_CONTROL_OUTPUT_VERTICES_OES 0x8E75 +#define GL_TESS_GEN_MODE_OES 0x8E76 +#define GL_TESS_GEN_SPACING_OES 0x8E77 +#define GL_TESS_GEN_VERTEX_ORDER_OES 0x8E78 +#define GL_TESS_GEN_POINT_MODE_OES 0x8E79 +#define GL_ISOLINES_OES 0x8E7A +#define GL_QUADS_OES 0x0007 +#define GL_FRACTIONAL_ODD_OES 0x8E7B +#define GL_FRACTIONAL_EVEN_OES 0x8E7C +#define GL_MAX_PATCH_VERTICES_OES 0x8E7D +#define GL_MAX_TESS_GEN_LEVEL_OES 0x8E7E +#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS_OES 0x8E7F +#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS_OES 0x8E80 +#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS_OES 0x8E81 +#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS_OES 0x8E82 +#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS_OES 0x8E83 +#define GL_MAX_TESS_PATCH_COMPONENTS_OES 0x8E84 +#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS_OES 0x8E85 +#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS_OES 0x8E86 +#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS_OES 0x8E89 +#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS_OES 0x8E8A +#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS_OES 0x886C +#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS_OES 0x886D +#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS_OES 0x8E1E +#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS_OES 0x8E1F +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS_OES 0x92CD +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS_OES 0x92CE +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS_OES 0x92D3 +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS_OES 0x92D4 +#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS_OES 0x90CB +#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS_OES 0x90CC +#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS_OES 0x90D8 +#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS_OES 0x90D9 +#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED_OES 0x8221 +#define GL_IS_PER_PATCH_OES 0x92E7 +#define GL_REFERENCED_BY_TESS_CONTROL_SHADER_OES 0x9307 +#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER_OES 0x9308 +#define GL_TESS_CONTROL_SHADER_OES 0x8E88 +#define GL_TESS_EVALUATION_SHADER_OES 0x8E87 +#define GL_TESS_CONTROL_SHADER_BIT_OES 0x00000008 +#define GL_TESS_EVALUATION_SHADER_BIT_OES 0x00000010 +typedef void (GL_APIENTRYP PFNGLPATCHPARAMETERIOESPROC) (GLenum pname, GLint value); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glPatchParameteriOES (GLenum pname, GLint value); +#endif +#endif /* GL_OES_tessellation_shader */ + +#ifndef GL_OES_texture_3D +#define GL_OES_texture_3D 1 +#define GL_TEXTURE_WRAP_R_OES 0x8072 +#define GL_TEXTURE_3D_OES 0x806F +#define GL_TEXTURE_BINDING_3D_OES 0x806A +#define GL_MAX_3D_TEXTURE_SIZE_OES 0x8073 +#define GL_SAMPLER_3D_OES 0x8B5F +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES 0x8CD4 +typedef void (GL_APIENTRYP PFNGLTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DOESPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GL_APICALL void GL_APIENTRY glTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GL_APICALL void GL_APIENTRY glCopyTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glCompressedTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GL_APICALL void GL_APIENTRY glCompressedTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GL_APICALL void GL_APIENTRY glFramebufferTexture3DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +#endif +#endif /* GL_OES_texture_3D */ + +#ifndef GL_OES_texture_border_clamp +#define GL_OES_texture_border_clamp 1 +#define GL_TEXTURE_BORDER_COLOR_OES 0x1004 +#define GL_CLAMP_TO_BORDER_OES 0x812D +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIIVOESPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIUIVOESPROC) (GLenum target, GLenum pname, const GLuint *params); +typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIIVOESPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIUIVOESPROC) (GLenum target, GLenum pname, GLuint *params); +typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIIVOESPROC) (GLuint sampler, GLenum pname, const GLint *param); +typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIUIVOESPROC) (GLuint sampler, GLenum pname, const GLuint *param); +typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIIVOESPROC) (GLuint sampler, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVOESPROC) (GLuint sampler, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexParameterIivOES (GLenum target, GLenum pname, const GLint *params); +GL_APICALL void GL_APIENTRY glTexParameterIuivOES (GLenum target, GLenum pname, const GLuint *params); +GL_APICALL void GL_APIENTRY glGetTexParameterIivOES (GLenum target, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetTexParameterIuivOES (GLenum target, GLenum pname, GLuint *params); +GL_APICALL void GL_APIENTRY glSamplerParameterIivOES (GLuint sampler, GLenum pname, const GLint *param); +GL_APICALL void GL_APIENTRY glSamplerParameterIuivOES (GLuint sampler, GLenum pname, const GLuint *param); +GL_APICALL void GL_APIENTRY glGetSamplerParameterIivOES (GLuint sampler, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetSamplerParameterIuivOES (GLuint sampler, GLenum pname, GLuint *params); +#endif +#endif /* GL_OES_texture_border_clamp */ + +#ifndef GL_OES_texture_buffer +#define GL_OES_texture_buffer 1 +#define GL_TEXTURE_BUFFER_OES 0x8C2A +#define GL_TEXTURE_BUFFER_BINDING_OES 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE_OES 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER_OES 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_OES 0x8C2D +#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT_OES 0x919F +#define GL_SAMPLER_BUFFER_OES 0x8DC2 +#define GL_INT_SAMPLER_BUFFER_OES 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_OES 0x8DD8 +#define GL_IMAGE_BUFFER_OES 0x9051 +#define GL_INT_IMAGE_BUFFER_OES 0x905C +#define GL_UNSIGNED_INT_IMAGE_BUFFER_OES 0x9067 +#define GL_TEXTURE_BUFFER_OFFSET_OES 0x919D +#define GL_TEXTURE_BUFFER_SIZE_OES 0x919E +typedef void (GL_APIENTRYP PFNGLTEXBUFFEROESPROC) (GLenum target, GLenum internalformat, GLuint buffer); +typedef void (GL_APIENTRYP PFNGLTEXBUFFERRANGEOESPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexBufferOES (GLenum target, GLenum internalformat, GLuint buffer); +GL_APICALL void GL_APIENTRY glTexBufferRangeOES (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +#endif +#endif /* GL_OES_texture_buffer */ + +#ifndef GL_OES_texture_compression_astc +#define GL_OES_texture_compression_astc 1 +#define GL_COMPRESSED_RGBA_ASTC_3x3x3_OES 0x93C0 +#define GL_COMPRESSED_RGBA_ASTC_4x3x3_OES 0x93C1 +#define GL_COMPRESSED_RGBA_ASTC_4x4x3_OES 0x93C2 +#define GL_COMPRESSED_RGBA_ASTC_4x4x4_OES 0x93C3 +#define GL_COMPRESSED_RGBA_ASTC_5x4x4_OES 0x93C4 +#define GL_COMPRESSED_RGBA_ASTC_5x5x4_OES 0x93C5 +#define GL_COMPRESSED_RGBA_ASTC_5x5x5_OES 0x93C6 +#define GL_COMPRESSED_RGBA_ASTC_6x5x5_OES 0x93C7 +#define GL_COMPRESSED_RGBA_ASTC_6x6x5_OES 0x93C8 +#define GL_COMPRESSED_RGBA_ASTC_6x6x6_OES 0x93C9 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_3x3x3_OES 0x93E0 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x3x3_OES 0x93E1 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x3_OES 0x93E2 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x4_OES 0x93E3 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4x4_OES 0x93E4 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x4_OES 0x93E5 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x5_OES 0x93E6 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5x5_OES 0x93E7 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x5_OES 0x93E8 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x6_OES 0x93E9 +#endif /* GL_OES_texture_compression_astc */ + +#ifndef GL_OES_texture_cube_map_array +#define GL_OES_texture_cube_map_array 1 +#define GL_TEXTURE_CUBE_MAP_ARRAY_OES 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_OES 0x900A +#define GL_SAMPLER_CUBE_MAP_ARRAY_OES 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_OES 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_OES 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_OES 0x900F +#define GL_IMAGE_CUBE_MAP_ARRAY_OES 0x9054 +#define GL_INT_IMAGE_CUBE_MAP_ARRAY_OES 0x905F +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_OES 0x906A +#endif /* GL_OES_texture_cube_map_array */ + +#ifndef GL_OES_texture_float +#define GL_OES_texture_float 1 +#endif /* GL_OES_texture_float */ + +#ifndef GL_OES_texture_float_linear +#define GL_OES_texture_float_linear 1 +#endif /* GL_OES_texture_float_linear */ + +#ifndef GL_OES_texture_half_float +#define GL_OES_texture_half_float 1 +#define GL_HALF_FLOAT_OES 0x8D61 +#endif /* GL_OES_texture_half_float */ + +#ifndef GL_OES_texture_half_float_linear +#define GL_OES_texture_half_float_linear 1 +#endif /* GL_OES_texture_half_float_linear */ + +#ifndef GL_OES_texture_npot +#define GL_OES_texture_npot 1 +#endif /* GL_OES_texture_npot */ + +#ifndef GL_OES_texture_stencil8 +#define GL_OES_texture_stencil8 1 +#define GL_STENCIL_INDEX_OES 0x1901 +#define GL_STENCIL_INDEX8_OES 0x8D48 +#endif /* GL_OES_texture_stencil8 */ + +#ifndef GL_OES_texture_storage_multisample_2d_array +#define GL_OES_texture_storage_multisample_2d_array 1 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES 0x9102 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY_OES 0x9105 +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910B +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910C +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910D +typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEOESPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexStorage3DMultisampleOES (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +#endif +#endif /* GL_OES_texture_storage_multisample_2d_array */ + +#ifndef GL_OES_texture_view +#define GL_OES_texture_view 1 +#define GL_TEXTURE_VIEW_MIN_LEVEL_OES 0x82DB +#define GL_TEXTURE_VIEW_NUM_LEVELS_OES 0x82DC +#define GL_TEXTURE_VIEW_MIN_LAYER_OES 0x82DD +#define GL_TEXTURE_VIEW_NUM_LAYERS_OES 0x82DE +#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF +typedef void (GL_APIENTRYP PFNGLTEXTUREVIEWOESPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTextureViewOES (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +#endif +#endif /* GL_OES_texture_view */ + +#ifndef GL_OES_vertex_array_object +#define GL_OES_vertex_array_object 1 +#define GL_VERTEX_ARRAY_BINDING_OES 0x85B5 +typedef void (GL_APIENTRYP PFNGLBINDVERTEXARRAYOESPROC) (GLuint array); +typedef void (GL_APIENTRYP PFNGLDELETEVERTEXARRAYSOESPROC) (GLsizei n, const GLuint *arrays); +typedef void (GL_APIENTRYP PFNGLGENVERTEXARRAYSOESPROC) (GLsizei n, GLuint *arrays); +typedef GLboolean (GL_APIENTRYP PFNGLISVERTEXARRAYOESPROC) (GLuint array); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBindVertexArrayOES (GLuint array); +GL_APICALL void GL_APIENTRY glDeleteVertexArraysOES (GLsizei n, const GLuint *arrays); +GL_APICALL void GL_APIENTRY glGenVertexArraysOES (GLsizei n, GLuint *arrays); +GL_APICALL GLboolean GL_APIENTRY glIsVertexArrayOES (GLuint array); +#endif +#endif /* GL_OES_vertex_array_object */ + +#ifndef GL_OES_vertex_half_float +#define GL_OES_vertex_half_float 1 +#endif /* GL_OES_vertex_half_float */ + +#ifndef GL_OES_vertex_type_10_10_10_2 +#define GL_OES_vertex_type_10_10_10_2 1 +#define GL_UNSIGNED_INT_10_10_10_2_OES 0x8DF6 +#define GL_INT_10_10_10_2_OES 0x8DF7 +#endif /* GL_OES_vertex_type_10_10_10_2 */ + +#ifndef GL_OES_viewport_array +#define GL_OES_viewport_array 1 +#define GL_MAX_VIEWPORTS_OES 0x825B +#define GL_VIEWPORT_SUBPIXEL_BITS_OES 0x825C +#define GL_VIEWPORT_BOUNDS_RANGE_OES 0x825D +#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX_OES 0x825F +typedef void (GL_APIENTRYP PFNGLVIEWPORTARRAYVOESPROC) (GLuint first, GLsizei count, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFOESPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFVOESPROC) (GLuint index, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLSCISSORARRAYVOESPROC) (GLuint first, GLsizei count, const GLint *v); +typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDOESPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDVOESPROC) (GLuint index, const GLint *v); +typedef void (GL_APIENTRYP PFNGLDEPTHRANGEARRAYFVOESPROC) (GLuint first, GLsizei count, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLDEPTHRANGEINDEXEDFOESPROC) (GLuint index, GLfloat n, GLfloat f); +typedef void (GL_APIENTRYP PFNGLGETFLOATI_VOESPROC) (GLenum target, GLuint index, GLfloat *data); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glViewportArrayvOES (GLuint first, GLsizei count, const GLfloat *v); +GL_APICALL void GL_APIENTRY glViewportIndexedfOES (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +GL_APICALL void GL_APIENTRY glViewportIndexedfvOES (GLuint index, const GLfloat *v); +GL_APICALL void GL_APIENTRY glScissorArrayvOES (GLuint first, GLsizei count, const GLint *v); +GL_APICALL void GL_APIENTRY glScissorIndexedOES (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glScissorIndexedvOES (GLuint index, const GLint *v); +GL_APICALL void GL_APIENTRY glDepthRangeArrayfvOES (GLuint first, GLsizei count, const GLfloat *v); +GL_APICALL void GL_APIENTRY glDepthRangeIndexedfOES (GLuint index, GLfloat n, GLfloat f); +GL_APICALL void GL_APIENTRY glGetFloati_vOES (GLenum target, GLuint index, GLfloat *data); +#endif +#endif /* GL_OES_viewport_array */ + +#ifndef GL_AMD_compressed_3DC_texture +#define GL_AMD_compressed_3DC_texture 1 +#define GL_3DC_X_AMD 0x87F9 +#define GL_3DC_XY_AMD 0x87FA +#endif /* GL_AMD_compressed_3DC_texture */ + +#ifndef GL_AMD_compressed_ATC_texture +#define GL_AMD_compressed_ATC_texture 1 +#define GL_ATC_RGB_AMD 0x8C92 +#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93 +#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE +#endif /* GL_AMD_compressed_ATC_texture */ + +#ifndef GL_AMD_framebuffer_multisample_advanced +#define GL_AMD_framebuffer_multisample_advanced 1 +#define GL_RENDERBUFFER_STORAGE_SAMPLES_AMD 0x91B2 +#define GL_MAX_COLOR_FRAMEBUFFER_SAMPLES_AMD 0x91B3 +#define GL_MAX_COLOR_FRAMEBUFFER_STORAGE_SAMPLES_AMD 0x91B4 +#define GL_MAX_DEPTH_STENCIL_FRAMEBUFFER_SAMPLES_AMD 0x91B5 +#define GL_NUM_SUPPORTED_MULTISAMPLE_MODES_AMD 0x91B6 +#define GL_SUPPORTED_MULTISAMPLE_MODES_AMD 0x91B7 +typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC) (GLenum target, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEADVANCEDAMDPROC) (GLuint renderbuffer, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleAdvancedAMD (GLenum target, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glNamedRenderbufferStorageMultisampleAdvancedAMD (GLuint renderbuffer, GLsizei samples, GLsizei storageSamples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_AMD_framebuffer_multisample_advanced */ + +#ifndef GL_AMD_performance_monitor +#define GL_AMD_performance_monitor 1 +#define GL_COUNTER_TYPE_AMD 0x8BC0 +#define GL_COUNTER_RANGE_AMD 0x8BC1 +#define GL_UNSIGNED_INT64_AMD 0x8BC2 +#define GL_PERCENTAGE_AMD 0x8BC3 +#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4 +#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5 +#define GL_PERFMON_RESULT_AMD 0x8BC6 +typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups); +typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); +typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); +typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); +typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data); +typedef void (GL_APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); +typedef void (GL_APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); +typedef void (GL_APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); +typedef void (GL_APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor); +typedef void (GL_APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor); +typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups); +GL_APICALL void GL_APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); +GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); +GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); +GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data); +GL_APICALL void GL_APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors); +GL_APICALL void GL_APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors); +GL_APICALL void GL_APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); +GL_APICALL void GL_APIENTRY glBeginPerfMonitorAMD (GLuint monitor); +GL_APICALL void GL_APIENTRY glEndPerfMonitorAMD (GLuint monitor); +GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); +#endif +#endif /* GL_AMD_performance_monitor */ + +#ifndef GL_AMD_program_binary_Z400 +#define GL_AMD_program_binary_Z400 1 +#define GL_Z400_BINARY_AMD 0x8740 +#endif /* GL_AMD_program_binary_Z400 */ + +#ifndef GL_ANDROID_extension_pack_es31a +#define GL_ANDROID_extension_pack_es31a 1 +#endif /* GL_ANDROID_extension_pack_es31a */ + +#ifndef GL_ANGLE_depth_texture +#define GL_ANGLE_depth_texture 1 +#endif /* GL_ANGLE_depth_texture */ + +#ifndef GL_ANGLE_framebuffer_blit +#define GL_ANGLE_framebuffer_blit 1 +#define GL_READ_FRAMEBUFFER_ANGLE 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_ANGLE 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING_ANGLE 0x8CA6 +#define GL_READ_FRAMEBUFFER_BINDING_ANGLE 0x8CAA +typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERANGLEPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBlitFramebufferANGLE (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#endif +#endif /* GL_ANGLE_framebuffer_blit */ + +#ifndef GL_ANGLE_framebuffer_multisample +#define GL_ANGLE_framebuffer_multisample 1 +#define GL_RENDERBUFFER_SAMPLES_ANGLE 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE 0x8D56 +#define GL_MAX_SAMPLES_ANGLE 0x8D57 +typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleANGLE (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_ANGLE_framebuffer_multisample */ + +#ifndef GL_ANGLE_instanced_arrays +#define GL_ANGLE_instanced_arrays 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE 0x88FE +typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDANGLEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDANGLEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORANGLEPROC) (GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawArraysInstancedANGLE (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +GL_APICALL void GL_APIENTRY glDrawElementsInstancedANGLE (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +GL_APICALL void GL_APIENTRY glVertexAttribDivisorANGLE (GLuint index, GLuint divisor); +#endif +#endif /* GL_ANGLE_instanced_arrays */ + +#ifndef GL_ANGLE_pack_reverse_row_order +#define GL_ANGLE_pack_reverse_row_order 1 +#define GL_PACK_REVERSE_ROW_ORDER_ANGLE 0x93A4 +#endif /* GL_ANGLE_pack_reverse_row_order */ + +#ifndef GL_ANGLE_program_binary +#define GL_ANGLE_program_binary 1 +#define GL_PROGRAM_BINARY_ANGLE 0x93A6 +#endif /* GL_ANGLE_program_binary */ + +#ifndef GL_ANGLE_texture_compression_dxt3 +#define GL_ANGLE_texture_compression_dxt3 1 +#define GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE 0x83F2 +#endif /* GL_ANGLE_texture_compression_dxt3 */ + +#ifndef GL_ANGLE_texture_compression_dxt5 +#define GL_ANGLE_texture_compression_dxt5 1 +#define GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE 0x83F3 +#endif /* GL_ANGLE_texture_compression_dxt5 */ + +#ifndef GL_ANGLE_texture_usage +#define GL_ANGLE_texture_usage 1 +#define GL_TEXTURE_USAGE_ANGLE 0x93A2 +#define GL_FRAMEBUFFER_ATTACHMENT_ANGLE 0x93A3 +#endif /* GL_ANGLE_texture_usage */ + +#ifndef GL_ANGLE_translated_shader_source +#define GL_ANGLE_translated_shader_source 1 +#define GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE 0x93A0 +typedef void (GL_APIENTRYP PFNGLGETTRANSLATEDSHADERSOURCEANGLEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGetTranslatedShaderSourceANGLE (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +#endif +#endif /* GL_ANGLE_translated_shader_source */ + +#ifndef GL_APPLE_clip_distance +#define GL_APPLE_clip_distance 1 +#define GL_MAX_CLIP_DISTANCES_APPLE 0x0D32 +#define GL_CLIP_DISTANCE0_APPLE 0x3000 +#define GL_CLIP_DISTANCE1_APPLE 0x3001 +#define GL_CLIP_DISTANCE2_APPLE 0x3002 +#define GL_CLIP_DISTANCE3_APPLE 0x3003 +#define GL_CLIP_DISTANCE4_APPLE 0x3004 +#define GL_CLIP_DISTANCE5_APPLE 0x3005 +#define GL_CLIP_DISTANCE6_APPLE 0x3006 +#define GL_CLIP_DISTANCE7_APPLE 0x3007 +#endif /* GL_APPLE_clip_distance */ + +#ifndef GL_APPLE_color_buffer_packed_float +#define GL_APPLE_color_buffer_packed_float 1 +#endif /* GL_APPLE_color_buffer_packed_float */ + +#ifndef GL_APPLE_copy_texture_levels +#define GL_APPLE_copy_texture_levels 1 +typedef void (GL_APIENTRYP PFNGLCOPYTEXTURELEVELSAPPLEPROC) (GLuint destinationTexture, GLuint sourceTexture, GLint sourceBaseLevel, GLsizei sourceLevelCount); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glCopyTextureLevelsAPPLE (GLuint destinationTexture, GLuint sourceTexture, GLint sourceBaseLevel, GLsizei sourceLevelCount); +#endif +#endif /* GL_APPLE_copy_texture_levels */ + +#ifndef GL_APPLE_framebuffer_multisample +#define GL_APPLE_framebuffer_multisample 1 +#define GL_RENDERBUFFER_SAMPLES_APPLE 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE 0x8D56 +#define GL_MAX_SAMPLES_APPLE 0x8D57 +#define GL_READ_FRAMEBUFFER_APPLE 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_APPLE 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING_APPLE 0x8CA6 +#define GL_READ_FRAMEBUFFER_BINDING_APPLE 0x8CAA +typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleAPPLE (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glResolveMultisampleFramebufferAPPLE (void); +#endif +#endif /* GL_APPLE_framebuffer_multisample */ + +#ifndef GL_APPLE_rgb_422 +#define GL_APPLE_rgb_422 1 +#define GL_RGB_422_APPLE 0x8A1F +#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB +#define GL_RGB_RAW_422_APPLE 0x8A51 +#endif /* GL_APPLE_rgb_422 */ + +#ifndef GL_APPLE_sync +#define GL_APPLE_sync 1 +#define GL_SYNC_OBJECT_APPLE 0x8A53 +#define GL_MAX_SERVER_WAIT_TIMEOUT_APPLE 0x9111 +#define GL_OBJECT_TYPE_APPLE 0x9112 +#define GL_SYNC_CONDITION_APPLE 0x9113 +#define GL_SYNC_STATUS_APPLE 0x9114 +#define GL_SYNC_FLAGS_APPLE 0x9115 +#define GL_SYNC_FENCE_APPLE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE_APPLE 0x9117 +#define GL_UNSIGNALED_APPLE 0x9118 +#define GL_SIGNALED_APPLE 0x9119 +#define GL_ALREADY_SIGNALED_APPLE 0x911A +#define GL_TIMEOUT_EXPIRED_APPLE 0x911B +#define GL_CONDITION_SATISFIED_APPLE 0x911C +#define GL_WAIT_FAILED_APPLE 0x911D +#define GL_SYNC_FLUSH_COMMANDS_BIT_APPLE 0x00000001 +#define GL_TIMEOUT_IGNORED_APPLE 0xFFFFFFFFFFFFFFFFull +typedef GLsync (GL_APIENTRYP PFNGLFENCESYNCAPPLEPROC) (GLenum condition, GLbitfield flags); +typedef GLboolean (GL_APIENTRYP PFNGLISSYNCAPPLEPROC) (GLsync sync); +typedef void (GL_APIENTRYP PFNGLDELETESYNCAPPLEPROC) (GLsync sync); +typedef GLenum (GL_APIENTRYP PFNGLCLIENTWAITSYNCAPPLEPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (GL_APIENTRYP PFNGLWAITSYNCAPPLEPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (GL_APIENTRYP PFNGLGETINTEGER64VAPPLEPROC) (GLenum pname, GLint64 *params); +typedef void (GL_APIENTRYP PFNGLGETSYNCIVAPPLEPROC) (GLsync sync, GLenum pname, GLsizei count, GLsizei *length, GLint *values); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL GLsync GL_APIENTRY glFenceSyncAPPLE (GLenum condition, GLbitfield flags); +GL_APICALL GLboolean GL_APIENTRY glIsSyncAPPLE (GLsync sync); +GL_APICALL void GL_APIENTRY glDeleteSyncAPPLE (GLsync sync); +GL_APICALL GLenum GL_APIENTRY glClientWaitSyncAPPLE (GLsync sync, GLbitfield flags, GLuint64 timeout); +GL_APICALL void GL_APIENTRY glWaitSyncAPPLE (GLsync sync, GLbitfield flags, GLuint64 timeout); +GL_APICALL void GL_APIENTRY glGetInteger64vAPPLE (GLenum pname, GLint64 *params); +GL_APICALL void GL_APIENTRY glGetSyncivAPPLE (GLsync sync, GLenum pname, GLsizei count, GLsizei *length, GLint *values); +#endif +#endif /* GL_APPLE_sync */ + +#ifndef GL_APPLE_texture_format_BGRA8888 +#define GL_APPLE_texture_format_BGRA8888 1 +#define GL_BGRA_EXT 0x80E1 +#define GL_BGRA8_EXT 0x93A1 +#endif /* GL_APPLE_texture_format_BGRA8888 */ + +#ifndef GL_APPLE_texture_max_level +#define GL_APPLE_texture_max_level 1 +#define GL_TEXTURE_MAX_LEVEL_APPLE 0x813D +#endif /* GL_APPLE_texture_max_level */ + +#ifndef GL_APPLE_texture_packed_float +#define GL_APPLE_texture_packed_float 1 +#define GL_UNSIGNED_INT_10F_11F_11F_REV_APPLE 0x8C3B +#define GL_UNSIGNED_INT_5_9_9_9_REV_APPLE 0x8C3E +#define GL_R11F_G11F_B10F_APPLE 0x8C3A +#define GL_RGB9_E5_APPLE 0x8C3D +#endif /* GL_APPLE_texture_packed_float */ + +#ifndef GL_ARM_mali_program_binary +#define GL_ARM_mali_program_binary 1 +#define GL_MALI_PROGRAM_BINARY_ARM 0x8F61 +#endif /* GL_ARM_mali_program_binary */ + +#ifndef GL_ARM_mali_shader_binary +#define GL_ARM_mali_shader_binary 1 +#define GL_MALI_SHADER_BINARY_ARM 0x8F60 +#endif /* GL_ARM_mali_shader_binary */ + +#ifndef GL_ARM_rgba8 +#define GL_ARM_rgba8 1 +#endif /* GL_ARM_rgba8 */ + +#ifndef GL_ARM_shader_framebuffer_fetch +#define GL_ARM_shader_framebuffer_fetch 1 +#define GL_FETCH_PER_SAMPLE_ARM 0x8F65 +#define GL_FRAGMENT_SHADER_FRAMEBUFFER_FETCH_MRT_ARM 0x8F66 +#endif /* GL_ARM_shader_framebuffer_fetch */ + +#ifndef GL_ARM_shader_framebuffer_fetch_depth_stencil +#define GL_ARM_shader_framebuffer_fetch_depth_stencil 1 +#endif /* GL_ARM_shader_framebuffer_fetch_depth_stencil */ + +#ifndef GL_ARM_texture_unnormalized_coordinates +#define GL_ARM_texture_unnormalized_coordinates 1 +#define GL_TEXTURE_UNNORMALIZED_COORDINATES_ARM 0x8F6A +#endif /* GL_ARM_texture_unnormalized_coordinates */ + +#ifndef GL_DMP_program_binary +#define GL_DMP_program_binary 1 +#define GL_SMAPHS30_PROGRAM_BINARY_DMP 0x9251 +#define GL_SMAPHS_PROGRAM_BINARY_DMP 0x9252 +#define GL_DMP_PROGRAM_BINARY_DMP 0x9253 +#endif /* GL_DMP_program_binary */ + +#ifndef GL_DMP_shader_binary +#define GL_DMP_shader_binary 1 +#define GL_SHADER_BINARY_DMP 0x9250 +#endif /* GL_DMP_shader_binary */ + +#ifndef GL_EXT_EGL_image_array +#define GL_EXT_EGL_image_array 1 +#endif /* GL_EXT_EGL_image_array */ + +#ifndef GL_EXT_EGL_image_storage +#define GL_EXT_EGL_image_storage 1 +typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXSTORAGEEXTPROC) (GLenum target, GLeglImageOES image, const GLint* attrib_list); +typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURESTORAGEEXTPROC) (GLuint texture, GLeglImageOES image, const GLint* attrib_list); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glEGLImageTargetTexStorageEXT (GLenum target, GLeglImageOES image, const GLint* attrib_list); +GL_APICALL void GL_APIENTRY glEGLImageTargetTextureStorageEXT (GLuint texture, GLeglImageOES image, const GLint* attrib_list); +#endif +#endif /* GL_EXT_EGL_image_storage */ + +#ifndef GL_EXT_EGL_image_storage_compression +#define GL_EXT_EGL_image_storage_compression 1 +#define GL_SURFACE_COMPRESSION_EXT 0x96C0 +#define GL_SURFACE_COMPRESSION_FIXED_RATE_NONE_EXT 0x96C1 +#define GL_SURFACE_COMPRESSION_FIXED_RATE_DEFAULT_EXT 0x96C2 +#endif /* GL_EXT_EGL_image_storage_compression */ + +#ifndef GL_EXT_YUV_target +#define GL_EXT_YUV_target 1 +#define GL_SAMPLER_EXTERNAL_2D_Y2Y_EXT 0x8BE7 +#endif /* GL_EXT_YUV_target */ + +#ifndef GL_EXT_base_instance +#define GL_EXT_base_instance 1 +typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawArraysInstancedBaseInstanceEXT (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseInstanceEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexBaseInstanceEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +#endif +#endif /* GL_EXT_base_instance */ + +#ifndef GL_EXT_blend_func_extended +#define GL_EXT_blend_func_extended 1 +#define GL_SRC1_COLOR_EXT 0x88F9 +#define GL_SRC1_ALPHA_EXT 0x8589 +#define GL_ONE_MINUS_SRC1_COLOR_EXT 0x88FA +#define GL_ONE_MINUS_SRC1_ALPHA_EXT 0x88FB +#define GL_SRC_ALPHA_SATURATE_EXT 0x0308 +#define GL_LOCATION_INDEX_EXT 0x930F +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT 0x88FC +typedef void (GL_APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +typedef void (GL_APIENTRYP PFNGLBINDFRAGDATALOCATIONEXTPROC) (GLuint program, GLuint color, const GLchar *name); +typedef GLint (GL_APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXEXTPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef GLint (GL_APIENTRYP PFNGLGETFRAGDATAINDEXEXTPROC) (GLuint program, const GLchar *name); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBindFragDataLocationIndexedEXT (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +GL_APICALL void GL_APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name); +GL_APICALL GLint GL_APIENTRY glGetProgramResourceLocationIndexEXT (GLuint program, GLenum programInterface, const GLchar *name); +GL_APICALL GLint GL_APIENTRY glGetFragDataIndexEXT (GLuint program, const GLchar *name); +#endif +#endif /* GL_EXT_blend_func_extended */ + +#ifndef GL_EXT_blend_minmax +#define GL_EXT_blend_minmax 1 +#define GL_MIN_EXT 0x8007 +#define GL_MAX_EXT 0x8008 +#endif /* GL_EXT_blend_minmax */ + +#ifndef GL_EXT_buffer_storage +#define GL_EXT_buffer_storage 1 +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_PERSISTENT_BIT_EXT 0x0040 +#define GL_MAP_COHERENT_BIT_EXT 0x0080 +#define GL_DYNAMIC_STORAGE_BIT_EXT 0x0100 +#define GL_CLIENT_STORAGE_BIT_EXT 0x0200 +#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT_EXT 0x00004000 +#define GL_BUFFER_IMMUTABLE_STORAGE_EXT 0x821F +#define GL_BUFFER_STORAGE_FLAGS_EXT 0x8220 +typedef void (GL_APIENTRYP PFNGLBUFFERSTORAGEEXTPROC) (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBufferStorageEXT (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +#endif +#endif /* GL_EXT_buffer_storage */ + +#ifndef GL_EXT_clear_texture +#define GL_EXT_clear_texture 1 +typedef void (GL_APIENTRYP PFNGLCLEARTEXIMAGEEXTPROC) (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +typedef void (GL_APIENTRYP PFNGLCLEARTEXSUBIMAGEEXTPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glClearTexImageEXT (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +GL_APICALL void GL_APIENTRY glClearTexSubImageEXT (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +#endif +#endif /* GL_EXT_clear_texture */ + +#ifndef GL_EXT_clip_control +#define GL_EXT_clip_control 1 +#define GL_LOWER_LEFT_EXT 0x8CA1 +#define GL_UPPER_LEFT_EXT 0x8CA2 +#define GL_NEGATIVE_ONE_TO_ONE_EXT 0x935E +#define GL_ZERO_TO_ONE_EXT 0x935F +#define GL_CLIP_ORIGIN_EXT 0x935C +#define GL_CLIP_DEPTH_MODE_EXT 0x935D +typedef void (GL_APIENTRYP PFNGLCLIPCONTROLEXTPROC) (GLenum origin, GLenum depth); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glClipControlEXT (GLenum origin, GLenum depth); +#endif +#endif /* GL_EXT_clip_control */ + +#ifndef GL_EXT_clip_cull_distance +#define GL_EXT_clip_cull_distance 1 +#define GL_MAX_CLIP_DISTANCES_EXT 0x0D32 +#define GL_MAX_CULL_DISTANCES_EXT 0x82F9 +#define GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES_EXT 0x82FA +#define GL_CLIP_DISTANCE0_EXT 0x3000 +#define GL_CLIP_DISTANCE1_EXT 0x3001 +#define GL_CLIP_DISTANCE2_EXT 0x3002 +#define GL_CLIP_DISTANCE3_EXT 0x3003 +#define GL_CLIP_DISTANCE4_EXT 0x3004 +#define GL_CLIP_DISTANCE5_EXT 0x3005 +#define GL_CLIP_DISTANCE6_EXT 0x3006 +#define GL_CLIP_DISTANCE7_EXT 0x3007 +#endif /* GL_EXT_clip_cull_distance */ + +#ifndef GL_EXT_color_buffer_float +#define GL_EXT_color_buffer_float 1 +#endif /* GL_EXT_color_buffer_float */ + +#ifndef GL_EXT_color_buffer_half_float +#define GL_EXT_color_buffer_half_float 1 +#define GL_RGBA16F_EXT 0x881A +#define GL_RGB16F_EXT 0x881B +#define GL_RG16F_EXT 0x822F +#define GL_R16F_EXT 0x822D +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT 0x8211 +#define GL_UNSIGNED_NORMALIZED_EXT 0x8C17 +#endif /* GL_EXT_color_buffer_half_float */ + +#ifndef GL_EXT_conservative_depth +#define GL_EXT_conservative_depth 1 +#endif /* GL_EXT_conservative_depth */ + +#ifndef GL_EXT_copy_image +#define GL_EXT_copy_image 1 +typedef void (GL_APIENTRYP PFNGLCOPYIMAGESUBDATAEXTPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glCopyImageSubDataEXT (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +#endif +#endif /* GL_EXT_copy_image */ + +#ifndef GL_EXT_debug_label +#define GL_EXT_debug_label 1 +#define GL_PROGRAM_PIPELINE_OBJECT_EXT 0x8A4F +#define GL_PROGRAM_OBJECT_EXT 0x8B40 +#define GL_SHADER_OBJECT_EXT 0x8B48 +#define GL_BUFFER_OBJECT_EXT 0x9151 +#define GL_QUERY_OBJECT_EXT 0x9153 +#define GL_VERTEX_ARRAY_OBJECT_EXT 0x9154 +#define GL_TRANSFORM_FEEDBACK 0x8E22 +typedef void (GL_APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label); +typedef void (GL_APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label); +GL_APICALL void GL_APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); +#endif +#endif /* GL_EXT_debug_label */ + +#ifndef GL_EXT_debug_marker +#define GL_EXT_debug_marker 1 +typedef void (GL_APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker); +typedef void (GL_APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker); +typedef void (GL_APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker); +GL_APICALL void GL_APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker); +GL_APICALL void GL_APIENTRY glPopGroupMarkerEXT (void); +#endif +#endif /* GL_EXT_debug_marker */ + +#ifndef GL_EXT_depth_clamp +#define GL_EXT_depth_clamp 1 +#define GL_DEPTH_CLAMP_EXT 0x864F +#endif /* GL_EXT_depth_clamp */ + +#ifndef GL_EXT_discard_framebuffer +#define GL_EXT_discard_framebuffer 1 +#define GL_COLOR_EXT 0x1800 +#define GL_DEPTH_EXT 0x1801 +#define GL_STENCIL_EXT 0x1802 +typedef void (GL_APIENTRYP PFNGLDISCARDFRAMEBUFFEREXTPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDiscardFramebufferEXT (GLenum target, GLsizei numAttachments, const GLenum *attachments); +#endif +#endif /* GL_EXT_discard_framebuffer */ + +#ifndef GL_EXT_disjoint_timer_query +#define GL_EXT_disjoint_timer_query 1 +#define GL_QUERY_COUNTER_BITS_EXT 0x8864 +#define GL_CURRENT_QUERY_EXT 0x8865 +#define GL_QUERY_RESULT_EXT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE_EXT 0x8867 +#define GL_TIME_ELAPSED_EXT 0x88BF +#define GL_TIMESTAMP_EXT 0x8E28 +#define GL_GPU_DISJOINT_EXT 0x8FBB +typedef void (GL_APIENTRYP PFNGLGENQUERIESEXTPROC) (GLsizei n, GLuint *ids); +typedef void (GL_APIENTRYP PFNGLDELETEQUERIESEXTPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (GL_APIENTRYP PFNGLISQUERYEXTPROC) (GLuint id); +typedef void (GL_APIENTRYP PFNGLBEGINQUERYEXTPROC) (GLenum target, GLuint id); +typedef void (GL_APIENTRYP PFNGLENDQUERYEXTPROC) (GLenum target); +typedef void (GL_APIENTRYP PFNGLQUERYCOUNTEREXTPROC) (GLuint id, GLenum target); +typedef void (GL_APIENTRYP PFNGLGETQUERYIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTIVEXTPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUIVEXTPROC) (GLuint id, GLenum pname, GLuint *params); +typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64 *params); +typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64 *params); +typedef void (GL_APIENTRYP PFNGLGETINTEGER64VEXTPROC) (GLenum pname, GLint64 *data); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGenQueriesEXT (GLsizei n, GLuint *ids); +GL_APICALL void GL_APIENTRY glDeleteQueriesEXT (GLsizei n, const GLuint *ids); +GL_APICALL GLboolean GL_APIENTRY glIsQueryEXT (GLuint id); +GL_APICALL void GL_APIENTRY glBeginQueryEXT (GLenum target, GLuint id); +GL_APICALL void GL_APIENTRY glEndQueryEXT (GLenum target); +GL_APICALL void GL_APIENTRY glQueryCounterEXT (GLuint id, GLenum target); +GL_APICALL void GL_APIENTRY glGetQueryivEXT (GLenum target, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetQueryObjectivEXT (GLuint id, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetQueryObjectuivEXT (GLuint id, GLenum pname, GLuint *params); +GL_APICALL void GL_APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64 *params); +GL_APICALL void GL_APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64 *params); +GL_APICALL void GL_APIENTRY glGetInteger64vEXT (GLenum pname, GLint64 *data); +#endif +#endif /* GL_EXT_disjoint_timer_query */ + +#ifndef GL_EXT_draw_buffers +#define GL_EXT_draw_buffers 1 +#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF +#define GL_MAX_DRAW_BUFFERS_EXT 0x8824 +#define GL_DRAW_BUFFER0_EXT 0x8825 +#define GL_DRAW_BUFFER1_EXT 0x8826 +#define GL_DRAW_BUFFER2_EXT 0x8827 +#define GL_DRAW_BUFFER3_EXT 0x8828 +#define GL_DRAW_BUFFER4_EXT 0x8829 +#define GL_DRAW_BUFFER5_EXT 0x882A +#define GL_DRAW_BUFFER6_EXT 0x882B +#define GL_DRAW_BUFFER7_EXT 0x882C +#define GL_DRAW_BUFFER8_EXT 0x882D +#define GL_DRAW_BUFFER9_EXT 0x882E +#define GL_DRAW_BUFFER10_EXT 0x882F +#define GL_DRAW_BUFFER11_EXT 0x8830 +#define GL_DRAW_BUFFER12_EXT 0x8831 +#define GL_DRAW_BUFFER13_EXT 0x8832 +#define GL_DRAW_BUFFER14_EXT 0x8833 +#define GL_DRAW_BUFFER15_EXT 0x8834 +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 +#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 +#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 +#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 +#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 +#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 +#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 +#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 +#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 +#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA +#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB +#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC +#define GL_COLOR_ATTACHMENT13_EXT 0x8CED +#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE +#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF +typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSEXTPROC) (GLsizei n, const GLenum *bufs); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawBuffersEXT (GLsizei n, const GLenum *bufs); +#endif +#endif /* GL_EXT_draw_buffers */ + +#ifndef GL_EXT_draw_buffers_indexed +#define GL_EXT_draw_buffers_indexed 1 +typedef void (GL_APIENTRYP PFNGLENABLEIEXTPROC) (GLenum target, GLuint index); +typedef void (GL_APIENTRYP PFNGLDISABLEIEXTPROC) (GLenum target, GLuint index); +typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONIEXTPROC) (GLuint buf, GLenum mode); +typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEIEXTPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +typedef void (GL_APIENTRYP PFNGLBLENDFUNCIEXTPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEIEXTPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +typedef void (GL_APIENTRYP PFNGLCOLORMASKIEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDIEXTPROC) (GLenum target, GLuint index); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glEnableiEXT (GLenum target, GLuint index); +GL_APICALL void GL_APIENTRY glDisableiEXT (GLenum target, GLuint index); +GL_APICALL void GL_APIENTRY glBlendEquationiEXT (GLuint buf, GLenum mode); +GL_APICALL void GL_APIENTRY glBlendEquationSeparateiEXT (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GL_APICALL void GL_APIENTRY glBlendFunciEXT (GLuint buf, GLenum src, GLenum dst); +GL_APICALL void GL_APIENTRY glBlendFuncSeparateiEXT (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GL_APICALL void GL_APIENTRY glColorMaskiEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +GL_APICALL GLboolean GL_APIENTRY glIsEnablediEXT (GLenum target, GLuint index); +#endif +#endif /* GL_EXT_draw_buffers_indexed */ + +#ifndef GL_EXT_draw_elements_base_vertex +#define GL_EXT_draw_elements_base_vertex 1 +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (GL_APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawElementsBaseVertexEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GL_APICALL void GL_APIENTRY glDrawRangeElementsBaseVertexEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +#endif +#endif /* GL_EXT_draw_elements_base_vertex */ + +#ifndef GL_EXT_draw_instanced +#define GL_EXT_draw_instanced 1 +typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +GL_APICALL void GL_APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#endif +#endif /* GL_EXT_draw_instanced */ + +#ifndef GL_EXT_draw_transform_feedback +#define GL_EXT_draw_transform_feedback 1 +typedef void (GL_APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKEXTPROC) (GLenum mode, GLuint id); +typedef void (GL_APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDEXTPROC) (GLenum mode, GLuint id, GLsizei instancecount); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawTransformFeedbackEXT (GLenum mode, GLuint id); +GL_APICALL void GL_APIENTRY glDrawTransformFeedbackInstancedEXT (GLenum mode, GLuint id, GLsizei instancecount); +#endif +#endif /* GL_EXT_draw_transform_feedback */ + +#ifndef GL_EXT_external_buffer +#define GL_EXT_external_buffer 1 +typedef void *GLeglClientBufferEXT; +typedef void (GL_APIENTRYP PFNGLBUFFERSTORAGEEXTERNALEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags); +typedef void (GL_APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTERNALEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBufferStorageExternalEXT (GLenum target, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags); +GL_APICALL void GL_APIENTRY glNamedBufferStorageExternalEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLeglClientBufferEXT clientBuffer, GLbitfield flags); +#endif +#endif /* GL_EXT_external_buffer */ + +#ifndef GL_EXT_float_blend +#define GL_EXT_float_blend 1 +#endif /* GL_EXT_float_blend */ + +#ifndef GL_EXT_fragment_shading_rate +#define GL_EXT_fragment_shading_rate 1 +#define GL_SHADING_RATE_1X1_PIXELS_EXT 0x96A6 +#define GL_SHADING_RATE_1X2_PIXELS_EXT 0x96A7 +#define GL_SHADING_RATE_2X1_PIXELS_EXT 0x96A8 +#define GL_SHADING_RATE_2X2_PIXELS_EXT 0x96A9 +#define GL_SHADING_RATE_1X4_PIXELS_EXT 0x96AA +#define GL_SHADING_RATE_4X1_PIXELS_EXT 0x96AB +#define GL_SHADING_RATE_4X2_PIXELS_EXT 0x96AC +#define GL_SHADING_RATE_2X4_PIXELS_EXT 0x96AD +#define GL_SHADING_RATE_4X4_PIXELS_EXT 0x96AE +#define GL_SHADING_RATE_EXT 0x96D0 +#define GL_SHADING_RATE_ATTACHMENT_EXT 0x96D1 +#define GL_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_EXT 0x96D2 +#define GL_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_EXT 0x96D3 +#define GL_FRAGMENT_SHADING_RATE_COMBINER_OP_MIN_EXT 0x96D4 +#define GL_FRAGMENT_SHADING_RATE_COMBINER_OP_MAX_EXT 0x96D5 +#define GL_FRAGMENT_SHADING_RATE_COMBINER_OP_MUL_EXT 0x96D6 +#define GL_MIN_FRAGMENT_SHADING_RATE_ATTACHMENT_TEXEL_WIDTH_EXT 0x96D7 +#define GL_MAX_FRAGMENT_SHADING_RATE_ATTACHMENT_TEXEL_WIDTH_EXT 0x96D8 +#define GL_MIN_FRAGMENT_SHADING_RATE_ATTACHMENT_TEXEL_HEIGHT_EXT 0x96D9 +#define GL_MAX_FRAGMENT_SHADING_RATE_ATTACHMENT_TEXEL_HEIGHT_EXT 0x96DA +#define GL_MAX_FRAGMENT_SHADING_RATE_ATTACHMENT_TEXEL_ASPECT_RATIO_EXT 0x96DB +#define GL_MAX_FRAGMENT_SHADING_RATE_ATTACHMENT_LAYERS_EXT 0x96DC +#define GL_FRAGMENT_SHADING_RATE_WITH_SHADER_DEPTH_STENCIL_WRITES_SUPPORTED_EXT 0x96DD +#define GL_FRAGMENT_SHADING_RATE_WITH_SAMPLE_MASK_SUPPORTED_EXT 0x96DE +#define GL_FRAGMENT_SHADING_RATE_ATTACHMENT_WITH_DEFAULT_FRAMEBUFFER_SUPPORTED_EXT 0x96DF +#define GL_FRAGMENT_SHADING_RATE_NON_TRIVIAL_COMBINERS_SUPPORTED_EXT 0x8F6F +typedef void (GL_APIENTRYP PFNGLGETFRAGMENTSHADINGRATESEXTPROC) (GLsizei samples, GLsizei maxCount, GLsizei *count, GLenum *shadingRates); +typedef void (GL_APIENTRYP PFNGLSHADINGRATEEXTPROC) (GLenum rate); +typedef void (GL_APIENTRYP PFNGLSHADINGRATECOMBINEROPSEXTPROC) (GLenum combinerOp0, GLenum combinerOp1); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERSHADINGRATEEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint baseLayer, GLsizei numLayers, GLsizei texelWidth, GLsizei texelHeight); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGetFragmentShadingRatesEXT (GLsizei samples, GLsizei maxCount, GLsizei *count, GLenum *shadingRates); +GL_APICALL void GL_APIENTRY glShadingRateEXT (GLenum rate); +GL_APICALL void GL_APIENTRY glShadingRateCombinerOpsEXT (GLenum combinerOp0, GLenum combinerOp1); +GL_APICALL void GL_APIENTRY glFramebufferShadingRateEXT (GLenum target, GLenum attachment, GLuint texture, GLint baseLayer, GLsizei numLayers, GLsizei texelWidth, GLsizei texelHeight); +#endif +#endif /* GL_EXT_fragment_shading_rate */ + +#ifndef GL_EXT_geometry_point_size +#define GL_EXT_geometry_point_size 1 +#endif /* GL_EXT_geometry_point_size */ + +#ifndef GL_EXT_geometry_shader +#define GL_EXT_geometry_shader 1 +#define GL_GEOMETRY_SHADER_EXT 0x8DD9 +#define GL_GEOMETRY_SHADER_BIT_EXT 0x00000004 +#define GL_GEOMETRY_LINKED_VERTICES_OUT_EXT 0x8916 +#define GL_GEOMETRY_LINKED_INPUT_TYPE_EXT 0x8917 +#define GL_GEOMETRY_LINKED_OUTPUT_TYPE_EXT 0x8918 +#define GL_GEOMETRY_SHADER_INVOCATIONS_EXT 0x887F +#define GL_LAYER_PROVOKING_VERTEX_EXT 0x825E +#define GL_LINES_ADJACENCY_EXT 0x000A +#define GL_LINE_STRIP_ADJACENCY_EXT 0x000B +#define GL_TRIANGLES_ADJACENCY_EXT 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0x000D +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS_EXT 0x8A2C +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8A32 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS_EXT 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS_EXT 0x9124 +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1 +#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS_EXT 0x8E5A +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29 +#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS_EXT 0x92CF +#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS_EXT 0x92D5 +#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS_EXT 0x90CD +#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS_EXT 0x90D7 +#define GL_FIRST_VERTEX_CONVENTION_EXT 0x8E4D +#define GL_LAST_VERTEX_CONVENTION_EXT 0x8E4E +#define GL_UNDEFINED_VERTEX_EXT 0x8260 +#define GL_PRIMITIVES_GENERATED_EXT 0x8C87 +#define GL_FRAMEBUFFER_DEFAULT_LAYERS_EXT 0x9312 +#define GL_MAX_FRAMEBUFFER_LAYERS_EXT 0x9317 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 +#define GL_REFERENCED_BY_GEOMETRY_SHADER_EXT 0x9309 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level); +#endif +#endif /* GL_EXT_geometry_shader */ + +#ifndef GL_EXT_gpu_shader5 +#define GL_EXT_gpu_shader5 1 +#endif /* GL_EXT_gpu_shader5 */ + +#ifndef GL_EXT_instanced_arrays +#define GL_EXT_instanced_arrays 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_EXT 0x88FE +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISOREXTPROC) (GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glVertexAttribDivisorEXT (GLuint index, GLuint divisor); +#endif +#endif /* GL_EXT_instanced_arrays */ + +#ifndef GL_EXT_map_buffer_range +#define GL_EXT_map_buffer_range 1 +#define GL_MAP_READ_BIT_EXT 0x0001 +#define GL_MAP_WRITE_BIT_EXT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT_EXT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT_EXT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT_EXT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT_EXT 0x0020 +typedef void *(GL_APIENTRYP PFNGLMAPBUFFERRANGEEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (GL_APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr length); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void *GL_APIENTRY glMapBufferRangeEXT (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +GL_APICALL void GL_APIENTRY glFlushMappedBufferRangeEXT (GLenum target, GLintptr offset, GLsizeiptr length); +#endif +#endif /* GL_EXT_map_buffer_range */ + +#ifndef GL_EXT_memory_object +#define GL_EXT_memory_object 1 +#define GL_TEXTURE_TILING_EXT 0x9580 +#define GL_DEDICATED_MEMORY_OBJECT_EXT 0x9581 +#define GL_PROTECTED_MEMORY_OBJECT_EXT 0x959B +#define GL_NUM_TILING_TYPES_EXT 0x9582 +#define GL_TILING_TYPES_EXT 0x9583 +#define GL_OPTIMAL_TILING_EXT 0x9584 +#define GL_LINEAR_TILING_EXT 0x9585 +#define GL_NUM_DEVICE_UUIDS_EXT 0x9596 +#define GL_DEVICE_UUID_EXT 0x9597 +#define GL_DRIVER_UUID_EXT 0x9598 +#define GL_UUID_SIZE_EXT 16 +typedef void (GL_APIENTRYP PFNGLGETUNSIGNEDBYTEVEXTPROC) (GLenum pname, GLubyte *data); +typedef void (GL_APIENTRYP PFNGLGETUNSIGNEDBYTEI_VEXTPROC) (GLenum target, GLuint index, GLubyte *data); +typedef void (GL_APIENTRYP PFNGLDELETEMEMORYOBJECTSEXTPROC) (GLsizei n, const GLuint *memoryObjects); +typedef GLboolean (GL_APIENTRYP PFNGLISMEMORYOBJECTEXTPROC) (GLuint memoryObject); +typedef void (GL_APIENTRYP PFNGLCREATEMEMORYOBJECTSEXTPROC) (GLsizei n, GLuint *memoryObjects); +typedef void (GL_APIENTRYP PFNGLMEMORYOBJECTPARAMETERIVEXTPROC) (GLuint memoryObject, GLenum pname, const GLint *params); +typedef void (GL_APIENTRYP PFNGLGETMEMORYOBJECTPARAMETERIVEXTPROC) (GLuint memoryObject, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLTEXSTORAGEMEM2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLTEXSTORAGEMEM2DMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLTEXSTORAGEMEM3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLTEXSTORAGEMEM3DMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLBUFFERSTORAGEMEMEXTPROC) (GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGEMEM2DEXTPROC) (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGEMEM2DMULTISAMPLEEXTPROC) (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGEMEM3DEXTPROC) (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGEMEM3DMULTISAMPLEEXTPROC) (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLNAMEDBUFFERSTORAGEMEMEXTPROC) (GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGetUnsignedBytevEXT (GLenum pname, GLubyte *data); +GL_APICALL void GL_APIENTRY glGetUnsignedBytei_vEXT (GLenum target, GLuint index, GLubyte *data); +GL_APICALL void GL_APIENTRY glDeleteMemoryObjectsEXT (GLsizei n, const GLuint *memoryObjects); +GL_APICALL GLboolean GL_APIENTRY glIsMemoryObjectEXT (GLuint memoryObject); +GL_APICALL void GL_APIENTRY glCreateMemoryObjectsEXT (GLsizei n, GLuint *memoryObjects); +GL_APICALL void GL_APIENTRY glMemoryObjectParameterivEXT (GLuint memoryObject, GLenum pname, const GLint *params); +GL_APICALL void GL_APIENTRY glGetMemoryObjectParameterivEXT (GLuint memoryObject, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glTexStorageMem2DEXT (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glTexStorageMem2DMultisampleEXT (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glTexStorageMem3DEXT (GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glTexStorageMem3DMultisampleEXT (GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glBufferStorageMemEXT (GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glTextureStorageMem2DEXT (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glTextureStorageMem2DMultisampleEXT (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glTextureStorageMem3DEXT (GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glTextureStorageMem3DMultisampleEXT (GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glNamedBufferStorageMemEXT (GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset); +#endif +#endif /* GL_EXT_memory_object */ + +#ifndef GL_EXT_memory_object_fd +#define GL_EXT_memory_object_fd 1 +#define GL_HANDLE_TYPE_OPAQUE_FD_EXT 0x9586 +typedef void (GL_APIENTRYP PFNGLIMPORTMEMORYFDEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, GLint fd); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glImportMemoryFdEXT (GLuint memory, GLuint64 size, GLenum handleType, GLint fd); +#endif +#endif /* GL_EXT_memory_object_fd */ + +#ifndef GL_EXT_memory_object_win32 +#define GL_EXT_memory_object_win32 1 +#define GL_HANDLE_TYPE_OPAQUE_WIN32_EXT 0x9587 +#define GL_HANDLE_TYPE_OPAQUE_WIN32_KMT_EXT 0x9588 +#define GL_DEVICE_LUID_EXT 0x9599 +#define GL_DEVICE_NODE_MASK_EXT 0x959A +#define GL_LUID_SIZE_EXT 8 +#define GL_HANDLE_TYPE_D3D12_TILEPOOL_EXT 0x9589 +#define GL_HANDLE_TYPE_D3D12_RESOURCE_EXT 0x958A +#define GL_HANDLE_TYPE_D3D11_IMAGE_EXT 0x958B +#define GL_HANDLE_TYPE_D3D11_IMAGE_KMT_EXT 0x958C +typedef void (GL_APIENTRYP PFNGLIMPORTMEMORYWIN32HANDLEEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, void *handle); +typedef void (GL_APIENTRYP PFNGLIMPORTMEMORYWIN32NAMEEXTPROC) (GLuint memory, GLuint64 size, GLenum handleType, const void *name); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glImportMemoryWin32HandleEXT (GLuint memory, GLuint64 size, GLenum handleType, void *handle); +GL_APICALL void GL_APIENTRY glImportMemoryWin32NameEXT (GLuint memory, GLuint64 size, GLenum handleType, const void *name); +#endif +#endif /* GL_EXT_memory_object_win32 */ + +#ifndef GL_EXT_multi_draw_arrays +#define GL_EXT_multi_draw_arrays 1 +typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glMultiDrawArraysEXT (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +GL_APICALL void GL_APIENTRY glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); +#endif +#endif /* GL_EXT_multi_draw_arrays */ + +#ifndef GL_EXT_multi_draw_indirect +#define GL_EXT_multi_draw_indirect 1 +typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC) (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTEXTPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glMultiDrawArraysIndirectEXT (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +GL_APICALL void GL_APIENTRY glMultiDrawElementsIndirectEXT (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +#endif +#endif /* GL_EXT_multi_draw_indirect */ + +#ifndef GL_EXT_multisampled_compatibility +#define GL_EXT_multisampled_compatibility 1 +#define GL_MULTISAMPLE_EXT 0x809D +#define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F +#endif /* GL_EXT_multisampled_compatibility */ + +#ifndef GL_EXT_multisampled_render_to_texture +#define GL_EXT_multisampled_render_to_texture 1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT 0x8D6C +#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 +#define GL_MAX_SAMPLES_EXT 0x8D57 +typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); +#endif +#endif /* GL_EXT_multisampled_render_to_texture */ + +#ifndef GL_EXT_multisampled_render_to_texture2 +#define GL_EXT_multisampled_render_to_texture2 1 +#endif /* GL_EXT_multisampled_render_to_texture2 */ + +#ifndef GL_EXT_multiview_draw_buffers +#define GL_EXT_multiview_draw_buffers 1 +#define GL_COLOR_ATTACHMENT_EXT 0x90F0 +#define GL_MULTIVIEW_EXT 0x90F1 +#define GL_DRAW_BUFFER_EXT 0x0C01 +#define GL_READ_BUFFER_EXT 0x0C02 +#define GL_MAX_MULTIVIEW_BUFFERS_EXT 0x90F2 +typedef void (GL_APIENTRYP PFNGLREADBUFFERINDEXEDEXTPROC) (GLenum src, GLint index); +typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSINDEXEDEXTPROC) (GLint n, const GLenum *location, const GLint *indices); +typedef void (GL_APIENTRYP PFNGLGETINTEGERI_VEXTPROC) (GLenum target, GLuint index, GLint *data); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glReadBufferIndexedEXT (GLenum src, GLint index); +GL_APICALL void GL_APIENTRY glDrawBuffersIndexedEXT (GLint n, const GLenum *location, const GLint *indices); +GL_APICALL void GL_APIENTRY glGetIntegeri_vEXT (GLenum target, GLuint index, GLint *data); +#endif +#endif /* GL_EXT_multiview_draw_buffers */ + +#ifndef GL_EXT_multiview_tessellation_geometry_shader +#define GL_EXT_multiview_tessellation_geometry_shader 1 +#endif /* GL_EXT_multiview_tessellation_geometry_shader */ + +#ifndef GL_EXT_multiview_texture_multisample +#define GL_EXT_multiview_texture_multisample 1 +#endif /* GL_EXT_multiview_texture_multisample */ + +#ifndef GL_EXT_multiview_timer_query +#define GL_EXT_multiview_timer_query 1 +#endif /* GL_EXT_multiview_timer_query */ + +#ifndef GL_EXT_occlusion_query_boolean +#define GL_EXT_occlusion_query_boolean 1 +#define GL_ANY_SAMPLES_PASSED_EXT 0x8C2F +#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT 0x8D6A +#endif /* GL_EXT_occlusion_query_boolean */ + +#ifndef GL_EXT_polygon_offset_clamp +#define GL_EXT_polygon_offset_clamp 1 +#define GL_POLYGON_OFFSET_CLAMP_EXT 0x8E1B +typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETCLAMPEXTPROC) (GLfloat factor, GLfloat units, GLfloat clamp); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glPolygonOffsetClampEXT (GLfloat factor, GLfloat units, GLfloat clamp); +#endif +#endif /* GL_EXT_polygon_offset_clamp */ + +#ifndef GL_EXT_post_depth_coverage +#define GL_EXT_post_depth_coverage 1 +#endif /* GL_EXT_post_depth_coverage */ + +#ifndef GL_EXT_primitive_bounding_box +#define GL_EXT_primitive_bounding_box 1 +#define GL_PRIMITIVE_BOUNDING_BOX_EXT 0x92BE +typedef void (GL_APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXEXTPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glPrimitiveBoundingBoxEXT (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); +#endif +#endif /* GL_EXT_primitive_bounding_box */ + +#ifndef GL_EXT_protected_textures +#define GL_EXT_protected_textures 1 +#define GL_CONTEXT_FLAG_PROTECTED_CONTENT_BIT_EXT 0x00000010 +#define GL_TEXTURE_PROTECTED_EXT 0x8BFA +#endif /* GL_EXT_protected_textures */ + +#ifndef GL_EXT_pvrtc_sRGB +#define GL_EXT_pvrtc_sRGB 1 +#define GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54 +#define GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55 +#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56 +#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57 +#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV2_IMG 0x93F0 +#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV2_IMG 0x93F1 +#endif /* GL_EXT_pvrtc_sRGB */ + +#ifndef GL_EXT_raster_multisample +#define GL_EXT_raster_multisample 1 +#define GL_RASTER_MULTISAMPLE_EXT 0x9327 +#define GL_RASTER_SAMPLES_EXT 0x9328 +#define GL_MAX_RASTER_SAMPLES_EXT 0x9329 +#define GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT 0x932A +#define GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT 0x932B +#define GL_EFFECTIVE_RASTER_SAMPLES_EXT 0x932C +typedef void (GL_APIENTRYP PFNGLRASTERSAMPLESEXTPROC) (GLuint samples, GLboolean fixedsamplelocations); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glRasterSamplesEXT (GLuint samples, GLboolean fixedsamplelocations); +#endif +#endif /* GL_EXT_raster_multisample */ + +#ifndef GL_EXT_read_format_bgra +#define GL_EXT_read_format_bgra 1 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT 0x8366 +#endif /* GL_EXT_read_format_bgra */ + +#ifndef GL_EXT_render_snorm +#define GL_EXT_render_snorm 1 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_R16_SNORM_EXT 0x8F98 +#define GL_RG16_SNORM_EXT 0x8F99 +#define GL_RGBA16_SNORM_EXT 0x8F9B +#endif /* GL_EXT_render_snorm */ + +#ifndef GL_EXT_robustness +#define GL_EXT_robustness 1 +#define GL_GUILTY_CONTEXT_RESET_EXT 0x8253 +#define GL_INNOCENT_CONTEXT_RESET_EXT 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET_EXT 0x8255 +#define GL_CONTEXT_ROBUST_ACCESS_EXT 0x90F3 +#define GL_RESET_NOTIFICATION_STRATEGY_EXT 0x8256 +#define GL_LOSE_CONTEXT_ON_RESET_EXT 0x8252 +#define GL_NO_RESET_NOTIFICATION_EXT 0x8261 +typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSEXTPROC) (void); +typedef void (GL_APIENTRYP PFNGLREADNPIXELSEXTPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL GLenum GL_APIENTRY glGetGraphicsResetStatusEXT (void); +GL_APICALL void GL_APIENTRY glReadnPixelsEXT (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GL_APICALL void GL_APIENTRY glGetnUniformfvEXT (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GL_APICALL void GL_APIENTRY glGetnUniformivEXT (GLuint program, GLint location, GLsizei bufSize, GLint *params); +#endif +#endif /* GL_EXT_robustness */ + +#ifndef GL_EXT_sRGB +#define GL_EXT_sRGB 1 +#define GL_SRGB_EXT 0x8C40 +#define GL_SRGB_ALPHA_EXT 0x8C42 +#define GL_SRGB8_ALPHA8_EXT 0x8C43 +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT 0x8210 +#endif /* GL_EXT_sRGB */ + +#ifndef GL_EXT_sRGB_write_control +#define GL_EXT_sRGB_write_control 1 +#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9 +#endif /* GL_EXT_sRGB_write_control */ + +#ifndef GL_EXT_semaphore +#define GL_EXT_semaphore 1 +#define GL_LAYOUT_GENERAL_EXT 0x958D +#define GL_LAYOUT_COLOR_ATTACHMENT_EXT 0x958E +#define GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT 0x958F +#define GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT 0x9590 +#define GL_LAYOUT_SHADER_READ_ONLY_EXT 0x9591 +#define GL_LAYOUT_TRANSFER_SRC_EXT 0x9592 +#define GL_LAYOUT_TRANSFER_DST_EXT 0x9593 +#define GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT 0x9530 +#define GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT 0x9531 +typedef void (GL_APIENTRYP PFNGLGENSEMAPHORESEXTPROC) (GLsizei n, GLuint *semaphores); +typedef void (GL_APIENTRYP PFNGLDELETESEMAPHORESEXTPROC) (GLsizei n, const GLuint *semaphores); +typedef GLboolean (GL_APIENTRYP PFNGLISSEMAPHOREEXTPROC) (GLuint semaphore); +typedef void (GL_APIENTRYP PFNGLSEMAPHOREPARAMETERUI64VEXTPROC) (GLuint semaphore, GLenum pname, const GLuint64 *params); +typedef void (GL_APIENTRYP PFNGLGETSEMAPHOREPARAMETERUI64VEXTPROC) (GLuint semaphore, GLenum pname, GLuint64 *params); +typedef void (GL_APIENTRYP PFNGLWAITSEMAPHOREEXTPROC) (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts); +typedef void (GL_APIENTRYP PFNGLSIGNALSEMAPHOREEXTPROC) (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGenSemaphoresEXT (GLsizei n, GLuint *semaphores); +GL_APICALL void GL_APIENTRY glDeleteSemaphoresEXT (GLsizei n, const GLuint *semaphores); +GL_APICALL GLboolean GL_APIENTRY glIsSemaphoreEXT (GLuint semaphore); +GL_APICALL void GL_APIENTRY glSemaphoreParameterui64vEXT (GLuint semaphore, GLenum pname, const GLuint64 *params); +GL_APICALL void GL_APIENTRY glGetSemaphoreParameterui64vEXT (GLuint semaphore, GLenum pname, GLuint64 *params); +GL_APICALL void GL_APIENTRY glWaitSemaphoreEXT (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts); +GL_APICALL void GL_APIENTRY glSignalSemaphoreEXT (GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts); +#endif +#endif /* GL_EXT_semaphore */ + +#ifndef GL_EXT_semaphore_fd +#define GL_EXT_semaphore_fd 1 +typedef void (GL_APIENTRYP PFNGLIMPORTSEMAPHOREFDEXTPROC) (GLuint semaphore, GLenum handleType, GLint fd); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glImportSemaphoreFdEXT (GLuint semaphore, GLenum handleType, GLint fd); +#endif +#endif /* GL_EXT_semaphore_fd */ + +#ifndef GL_EXT_semaphore_win32 +#define GL_EXT_semaphore_win32 1 +#define GL_HANDLE_TYPE_D3D12_FENCE_EXT 0x9594 +#define GL_D3D12_FENCE_VALUE_EXT 0x9595 +typedef void (GL_APIENTRYP PFNGLIMPORTSEMAPHOREWIN32HANDLEEXTPROC) (GLuint semaphore, GLenum handleType, void *handle); +typedef void (GL_APIENTRYP PFNGLIMPORTSEMAPHOREWIN32NAMEEXTPROC) (GLuint semaphore, GLenum handleType, const void *name); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glImportSemaphoreWin32HandleEXT (GLuint semaphore, GLenum handleType, void *handle); +GL_APICALL void GL_APIENTRY glImportSemaphoreWin32NameEXT (GLuint semaphore, GLenum handleType, const void *name); +#endif +#endif /* GL_EXT_semaphore_win32 */ + +#ifndef GL_EXT_separate_depth_stencil +#define GL_EXT_separate_depth_stencil 1 +#endif /* GL_EXT_separate_depth_stencil */ + +#ifndef GL_EXT_separate_shader_objects +#define GL_EXT_separate_shader_objects 1 +#define GL_ACTIVE_PROGRAM_EXT 0x8259 +#define GL_VERTEX_SHADER_BIT_EXT 0x00000001 +#define GL_FRAGMENT_SHADER_BIT_EXT 0x00000002 +#define GL_ALL_SHADER_BITS_EXT 0xFFFFFFFF +#define GL_PROGRAM_SEPARABLE_EXT 0x8258 +#define GL_PROGRAM_PIPELINE_BINDING_EXT 0x825A +typedef void (GL_APIENTRYP PFNGLACTIVESHADERPROGRAMEXTPROC) (GLuint pipeline, GLuint program); +typedef void (GL_APIENTRYP PFNGLBINDPROGRAMPIPELINEEXTPROC) (GLuint pipeline); +typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROGRAMVEXTPROC) (GLenum type, GLsizei count, const GLchar **strings); +typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPIPELINESEXTPROC) (GLsizei n, const GLuint *pipelines); +typedef void (GL_APIENTRYP PFNGLGENPROGRAMPIPELINESEXTPROC) (GLsizei n, GLuint *pipelines); +typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEIVEXTPROC) (GLuint pipeline, GLenum pname, GLint *params); +typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPIPELINEEXTPROC) (GLuint pipeline); +typedef void (GL_APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUSEPROGRAMSTAGESEXTPROC) (GLuint pipeline, GLbitfield stages, GLuint program); +typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEEXTPROC) (GLuint pipeline); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glActiveShaderProgramEXT (GLuint pipeline, GLuint program); +GL_APICALL void GL_APIENTRY glBindProgramPipelineEXT (GLuint pipeline); +GL_APICALL GLuint GL_APIENTRY glCreateShaderProgramvEXT (GLenum type, GLsizei count, const GLchar **strings); +GL_APICALL void GL_APIENTRY glDeleteProgramPipelinesEXT (GLsizei n, const GLuint *pipelines); +GL_APICALL void GL_APIENTRY glGenProgramPipelinesEXT (GLsizei n, GLuint *pipelines); +GL_APICALL void GL_APIENTRY glGetProgramPipelineInfoLogEXT (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GL_APICALL void GL_APIENTRY glGetProgramPipelineivEXT (GLuint pipeline, GLenum pname, GLint *params); +GL_APICALL GLboolean GL_APIENTRY glIsProgramPipelineEXT (GLuint pipeline); +GL_APICALL void GL_APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value); +GL_APICALL void GL_APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0); +GL_APICALL void GL_APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0); +GL_APICALL void GL_APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GL_APICALL void GL_APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1); +GL_APICALL void GL_APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1); +GL_APICALL void GL_APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GL_APICALL void GL_APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GL_APICALL void GL_APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +GL_APICALL void GL_APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GL_APICALL void GL_APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GL_APICALL void GL_APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GL_APICALL void GL_APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUseProgramStagesEXT (GLuint pipeline, GLbitfield stages, GLuint program); +GL_APICALL void GL_APIENTRY glValidateProgramPipelineEXT (GLuint pipeline); +GL_APICALL void GL_APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0); +GL_APICALL void GL_APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1); +GL_APICALL void GL_APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +GL_APICALL void GL_APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GL_APICALL void GL_APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GL_APICALL void GL_APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GL_APICALL void GL_APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GL_APICALL void GL_APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#endif +#endif /* GL_EXT_separate_shader_objects */ + +#ifndef GL_EXT_shader_framebuffer_fetch +#define GL_EXT_shader_framebuffer_fetch 1 +#define GL_FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT 0x8A52 +#endif /* GL_EXT_shader_framebuffer_fetch */ + +#ifndef GL_EXT_shader_framebuffer_fetch_non_coherent +#define GL_EXT_shader_framebuffer_fetch_non_coherent 1 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERFETCHBARRIEREXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferFetchBarrierEXT (void); +#endif +#endif /* GL_EXT_shader_framebuffer_fetch_non_coherent */ + +#ifndef GL_EXT_shader_group_vote +#define GL_EXT_shader_group_vote 1 +#endif /* GL_EXT_shader_group_vote */ + +#ifndef GL_EXT_shader_implicit_conversions +#define GL_EXT_shader_implicit_conversions 1 +#endif /* GL_EXT_shader_implicit_conversions */ + +#ifndef GL_EXT_shader_integer_mix +#define GL_EXT_shader_integer_mix 1 +#endif /* GL_EXT_shader_integer_mix */ + +#ifndef GL_EXT_shader_io_blocks +#define GL_EXT_shader_io_blocks 1 +#endif /* GL_EXT_shader_io_blocks */ + +#ifndef GL_EXT_shader_non_constant_global_initializers +#define GL_EXT_shader_non_constant_global_initializers 1 +#endif /* GL_EXT_shader_non_constant_global_initializers */ + +#ifndef GL_EXT_shader_pixel_local_storage +#define GL_EXT_shader_pixel_local_storage 1 +#define GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_FAST_SIZE_EXT 0x8F63 +#define GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_SIZE_EXT 0x8F67 +#define GL_SHADER_PIXEL_LOCAL_STORAGE_EXT 0x8F64 +#endif /* GL_EXT_shader_pixel_local_storage */ + +#ifndef GL_EXT_shader_pixel_local_storage2 +#define GL_EXT_shader_pixel_local_storage2 1 +#define GL_MAX_SHADER_COMBINED_LOCAL_STORAGE_FAST_SIZE_EXT 0x9650 +#define GL_MAX_SHADER_COMBINED_LOCAL_STORAGE_SIZE_EXT 0x9651 +#define GL_FRAMEBUFFER_INCOMPLETE_INSUFFICIENT_SHADER_COMBINED_LOCAL_STORAGE_EXT 0x9652 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC) (GLuint target, GLsizei size); +typedef GLsizei (GL_APIENTRYP PFNGLGETFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC) (GLuint target); +typedef void (GL_APIENTRYP PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC) (GLsizei offset, GLsizei n, const GLuint *values); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferPixelLocalStorageSizeEXT (GLuint target, GLsizei size); +GL_APICALL GLsizei GL_APIENTRY glGetFramebufferPixelLocalStorageSizeEXT (GLuint target); +GL_APICALL void GL_APIENTRY glClearPixelLocalStorageuiEXT (GLsizei offset, GLsizei n, const GLuint *values); +#endif +#endif /* GL_EXT_shader_pixel_local_storage2 */ + +#ifndef GL_EXT_shader_samples_identical +#define GL_EXT_shader_samples_identical 1 +#endif /* GL_EXT_shader_samples_identical */ + +#ifndef GL_EXT_shader_texture_lod +#define GL_EXT_shader_texture_lod 1 +#endif /* GL_EXT_shader_texture_lod */ + +#ifndef GL_EXT_shadow_samplers +#define GL_EXT_shadow_samplers 1 +#define GL_TEXTURE_COMPARE_MODE_EXT 0x884C +#define GL_TEXTURE_COMPARE_FUNC_EXT 0x884D +#define GL_COMPARE_REF_TO_TEXTURE_EXT 0x884E +#define GL_SAMPLER_2D_SHADOW_EXT 0x8B62 +#endif /* GL_EXT_shadow_samplers */ + +#ifndef GL_EXT_sparse_texture +#define GL_EXT_sparse_texture 1 +#define GL_TEXTURE_SPARSE_EXT 0x91A6 +#define GL_VIRTUAL_PAGE_SIZE_INDEX_EXT 0x91A7 +#define GL_NUM_SPARSE_LEVELS_EXT 0x91AA +#define GL_NUM_VIRTUAL_PAGE_SIZES_EXT 0x91A8 +#define GL_VIRTUAL_PAGE_SIZE_X_EXT 0x9195 +#define GL_VIRTUAL_PAGE_SIZE_Y_EXT 0x9196 +#define GL_VIRTUAL_PAGE_SIZE_Z_EXT 0x9197 +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_TEXTURE_3D 0x806F +#define GL_MAX_SPARSE_TEXTURE_SIZE_EXT 0x9198 +#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_EXT 0x9199 +#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_EXT 0x919A +#define GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_EXT 0x91A9 +typedef void (GL_APIENTRYP PFNGLTEXPAGECOMMITMENTEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexPageCommitmentEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); +#endif +#endif /* GL_EXT_sparse_texture */ + +#ifndef GL_EXT_sparse_texture2 +#define GL_EXT_sparse_texture2 1 +#endif /* GL_EXT_sparse_texture2 */ + +#ifndef GL_EXT_tessellation_point_size +#define GL_EXT_tessellation_point_size 1 +#endif /* GL_EXT_tessellation_point_size */ + +#ifndef GL_EXT_tessellation_shader +#define GL_EXT_tessellation_shader 1 +#define GL_PATCHES_EXT 0x000E +#define GL_PATCH_VERTICES_EXT 0x8E72 +#define GL_TESS_CONTROL_OUTPUT_VERTICES_EXT 0x8E75 +#define GL_TESS_GEN_MODE_EXT 0x8E76 +#define GL_TESS_GEN_SPACING_EXT 0x8E77 +#define GL_TESS_GEN_VERTEX_ORDER_EXT 0x8E78 +#define GL_TESS_GEN_POINT_MODE_EXT 0x8E79 +#define GL_ISOLINES_EXT 0x8E7A +#define GL_QUADS_EXT 0x0007 +#define GL_FRACTIONAL_ODD_EXT 0x8E7B +#define GL_FRACTIONAL_EVEN_EXT 0x8E7C +#define GL_MAX_PATCH_VERTICES_EXT 0x8E7D +#define GL_MAX_TESS_GEN_LEVEL_EXT 0x8E7E +#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS_EXT 0x8E7F +#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS_EXT 0x8E80 +#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS_EXT 0x8E81 +#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS_EXT 0x8E82 +#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS_EXT 0x8E83 +#define GL_MAX_TESS_PATCH_COMPONENTS_EXT 0x8E84 +#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS_EXT 0x8E85 +#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS_EXT 0x8E86 +#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS_EXT 0x8E89 +#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS_EXT 0x8E8A +#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS_EXT 0x886C +#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS_EXT 0x886D +#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS_EXT 0x8E1E +#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS_EXT 0x8E1F +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS_EXT 0x92CD +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS_EXT 0x92CE +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS_EXT 0x92D3 +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS_EXT 0x92D4 +#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS_EXT 0x90CB +#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS_EXT 0x90CC +#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS_EXT 0x90D8 +#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS_EXT 0x90D9 +#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221 +#define GL_IS_PER_PATCH_EXT 0x92E7 +#define GL_REFERENCED_BY_TESS_CONTROL_SHADER_EXT 0x9307 +#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER_EXT 0x9308 +#define GL_TESS_CONTROL_SHADER_EXT 0x8E88 +#define GL_TESS_EVALUATION_SHADER_EXT 0x8E87 +#define GL_TESS_CONTROL_SHADER_BIT_EXT 0x00000008 +#define GL_TESS_EVALUATION_SHADER_BIT_EXT 0x00000010 +typedef void (GL_APIENTRYP PFNGLPATCHPARAMETERIEXTPROC) (GLenum pname, GLint value); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glPatchParameteriEXT (GLenum pname, GLint value); +#endif +#endif /* GL_EXT_tessellation_shader */ + +#ifndef GL_EXT_texture_border_clamp +#define GL_EXT_texture_border_clamp 1 +#define GL_TEXTURE_BORDER_COLOR_EXT 0x1004 +#define GL_CLAMP_TO_BORDER_EXT 0x812D +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, const GLuint *params); +typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, GLuint *params); +typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIIVEXTPROC) (GLuint sampler, GLenum pname, const GLint *param); +typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIUIVEXTPROC) (GLuint sampler, GLenum pname, const GLuint *param); +typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIIVEXTPROC) (GLuint sampler, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVEXTPROC) (GLuint sampler, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params); +GL_APICALL void GL_APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params); +GL_APICALL void GL_APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params); +GL_APICALL void GL_APIENTRY glSamplerParameterIivEXT (GLuint sampler, GLenum pname, const GLint *param); +GL_APICALL void GL_APIENTRY glSamplerParameterIuivEXT (GLuint sampler, GLenum pname, const GLuint *param); +GL_APICALL void GL_APIENTRY glGetSamplerParameterIivEXT (GLuint sampler, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glGetSamplerParameterIuivEXT (GLuint sampler, GLenum pname, GLuint *params); +#endif +#endif /* GL_EXT_texture_border_clamp */ + +#ifndef GL_EXT_texture_buffer +#define GL_EXT_texture_buffer 1 +#define GL_TEXTURE_BUFFER_EXT 0x8C2A +#define GL_TEXTURE_BUFFER_BINDING_EXT 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE_EXT 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER_EXT 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT 0x8C2D +#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT_EXT 0x919F +#define GL_SAMPLER_BUFFER_EXT 0x8DC2 +#define GL_INT_SAMPLER_BUFFER_EXT 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8 +#define GL_IMAGE_BUFFER_EXT 0x9051 +#define GL_INT_IMAGE_BUFFER_EXT 0x905C +#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT 0x9067 +#define GL_TEXTURE_BUFFER_OFFSET_EXT 0x919D +#define GL_TEXTURE_BUFFER_SIZE_EXT 0x919E +typedef void (GL_APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer); +typedef void (GL_APIENTRYP PFNGLTEXBUFFERRANGEEXTPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer); +GL_APICALL void GL_APIENTRY glTexBufferRangeEXT (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +#endif +#endif /* GL_EXT_texture_buffer */ + +#ifndef GL_EXT_texture_compression_astc_decode_mode +#define GL_EXT_texture_compression_astc_decode_mode 1 +#define GL_TEXTURE_ASTC_DECODE_PRECISION_EXT 0x8F69 +#endif /* GL_EXT_texture_compression_astc_decode_mode */ + +#ifndef GL_EXT_texture_compression_bptc +#define GL_EXT_texture_compression_bptc 1 +#define GL_COMPRESSED_RGBA_BPTC_UNORM_EXT 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT 0x8E8F +#endif /* GL_EXT_texture_compression_bptc */ + +#ifndef GL_EXT_texture_compression_dxt1 +#define GL_EXT_texture_compression_dxt1 1 +#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 +#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#endif /* GL_EXT_texture_compression_dxt1 */ + +#ifndef GL_EXT_texture_compression_rgtc +#define GL_EXT_texture_compression_rgtc 1 +#define GL_COMPRESSED_RED_RGTC1_EXT 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC +#define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD +#define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE +#endif /* GL_EXT_texture_compression_rgtc */ + +#ifndef GL_EXT_texture_compression_s3tc +#define GL_EXT_texture_compression_s3tc 1 +#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 +#endif /* GL_EXT_texture_compression_s3tc */ + +#ifndef GL_EXT_texture_compression_s3tc_srgb +#define GL_EXT_texture_compression_s3tc_srgb 1 +#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F +#endif /* GL_EXT_texture_compression_s3tc_srgb */ + +#ifndef GL_EXT_texture_cube_map_array +#define GL_EXT_texture_cube_map_array 1 +#define GL_TEXTURE_CUBE_MAP_ARRAY_EXT 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_EXT 0x900A +#define GL_SAMPLER_CUBE_MAP_ARRAY_EXT 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_EXT 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_EXT 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_EXT 0x900F +#define GL_IMAGE_CUBE_MAP_ARRAY_EXT 0x9054 +#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x905F +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A +#endif /* GL_EXT_texture_cube_map_array */ + +#ifndef GL_EXT_texture_filter_anisotropic +#define GL_EXT_texture_filter_anisotropic 1 +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#endif /* GL_EXT_texture_filter_anisotropic */ + +#ifndef GL_EXT_texture_filter_minmax +#define GL_EXT_texture_filter_minmax 1 +#define GL_TEXTURE_REDUCTION_MODE_EXT 0x9366 +#define GL_WEIGHTED_AVERAGE_EXT 0x9367 +#endif /* GL_EXT_texture_filter_minmax */ + +#ifndef GL_EXT_texture_format_BGRA8888 +#define GL_EXT_texture_format_BGRA8888 1 +#endif /* GL_EXT_texture_format_BGRA8888 */ + +#ifndef GL_EXT_texture_format_sRGB_override +#define GL_EXT_texture_format_sRGB_override 1 +#define GL_TEXTURE_FORMAT_SRGB_OVERRIDE_EXT 0x8FBF +#endif /* GL_EXT_texture_format_sRGB_override */ + +#ifndef GL_EXT_texture_mirror_clamp_to_edge +#define GL_EXT_texture_mirror_clamp_to_edge 1 +#define GL_MIRROR_CLAMP_TO_EDGE_EXT 0x8743 +#endif /* GL_EXT_texture_mirror_clamp_to_edge */ + +#ifndef GL_EXT_texture_norm16 +#define GL_EXT_texture_norm16 1 +#define GL_R16_EXT 0x822A +#define GL_RG16_EXT 0x822C +#define GL_RGBA16_EXT 0x805B +#define GL_RGB16_EXT 0x8054 +#define GL_RGB16_SNORM_EXT 0x8F9A +#endif /* GL_EXT_texture_norm16 */ + +#ifndef GL_EXT_texture_query_lod +#define GL_EXT_texture_query_lod 1 +#endif /* GL_EXT_texture_query_lod */ + +#ifndef GL_EXT_texture_rg +#define GL_EXT_texture_rg 1 +#define GL_RED_EXT 0x1903 +#define GL_RG_EXT 0x8227 +#define GL_R8_EXT 0x8229 +#define GL_RG8_EXT 0x822B +#endif /* GL_EXT_texture_rg */ + +#ifndef GL_EXT_texture_sRGB_R8 +#define GL_EXT_texture_sRGB_R8 1 +#define GL_SR8_EXT 0x8FBD +#endif /* GL_EXT_texture_sRGB_R8 */ + +#ifndef GL_EXT_texture_sRGB_RG8 +#define GL_EXT_texture_sRGB_RG8 1 +#define GL_SRG8_EXT 0x8FBE +#endif /* GL_EXT_texture_sRGB_RG8 */ + +#ifndef GL_EXT_texture_sRGB_decode +#define GL_EXT_texture_sRGB_decode 1 +#define GL_TEXTURE_SRGB_DECODE_EXT 0x8A48 +#define GL_DECODE_EXT 0x8A49 +#define GL_SKIP_DECODE_EXT 0x8A4A +#endif /* GL_EXT_texture_sRGB_decode */ + +#ifndef GL_EXT_texture_shadow_lod +#define GL_EXT_texture_shadow_lod 1 +#endif /* GL_EXT_texture_shadow_lod */ + +#ifndef GL_EXT_texture_storage +#define GL_EXT_texture_storage 1 +#define GL_TEXTURE_IMMUTABLE_FORMAT_EXT 0x912F +#define GL_ALPHA8_EXT 0x803C +#define GL_LUMINANCE8_EXT 0x8040 +#define GL_LUMINANCE8_ALPHA8_EXT 0x8045 +#define GL_RGBA32F_EXT 0x8814 +#define GL_RGB32F_EXT 0x8815 +#define GL_ALPHA32F_EXT 0x8816 +#define GL_LUMINANCE32F_EXT 0x8818 +#define GL_LUMINANCE_ALPHA32F_EXT 0x8819 +#define GL_ALPHA16F_EXT 0x881C +#define GL_LUMINANCE16F_EXT 0x881E +#define GL_LUMINANCE_ALPHA16F_EXT 0x881F +#define GL_R32F_EXT 0x822E +#define GL_RG32F_EXT 0x8230 +typedef void (GL_APIENTRYP PFNGLTEXSTORAGE1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexStorage1DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GL_APICALL void GL_APIENTRY glTexStorage2DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glTexStorage3DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GL_APICALL void GL_APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GL_APICALL void GL_APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +#endif +#endif /* GL_EXT_texture_storage */ + +#ifndef GL_EXT_texture_storage_compression +#define GL_EXT_texture_storage_compression 1 +#define GL_NUM_SURFACE_COMPRESSION_FIXED_RATES_EXT 0x8F6E +#define GL_SURFACE_COMPRESSION_FIXED_RATE_1BPC_EXT 0x96C4 +#define GL_SURFACE_COMPRESSION_FIXED_RATE_2BPC_EXT 0x96C5 +#define GL_SURFACE_COMPRESSION_FIXED_RATE_3BPC_EXT 0x96C6 +#define GL_SURFACE_COMPRESSION_FIXED_RATE_4BPC_EXT 0x96C7 +#define GL_SURFACE_COMPRESSION_FIXED_RATE_5BPC_EXT 0x96C8 +#define GL_SURFACE_COMPRESSION_FIXED_RATE_6BPC_EXT 0x96C9 +#define GL_SURFACE_COMPRESSION_FIXED_RATE_7BPC_EXT 0x96CA +#define GL_SURFACE_COMPRESSION_FIXED_RATE_8BPC_EXT 0x96CB +#define GL_SURFACE_COMPRESSION_FIXED_RATE_9BPC_EXT 0x96CC +#define GL_SURFACE_COMPRESSION_FIXED_RATE_10BPC_EXT 0x96CD +#define GL_SURFACE_COMPRESSION_FIXED_RATE_11BPC_EXT 0x96CE +#define GL_SURFACE_COMPRESSION_FIXED_RATE_12BPC_EXT 0x96CF +typedef void (GL_APIENTRYP PFNGLTEXSTORAGEATTRIBS2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, const GLint* attrib_list); +typedef void (GL_APIENTRYP PFNGLTEXSTORAGEATTRIBS3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, const GLint* attrib_list); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexStorageAttribs2DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, const GLint* attrib_list); +GL_APICALL void GL_APIENTRY glTexStorageAttribs3DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, const GLint* attrib_list); +#endif +#endif /* GL_EXT_texture_storage_compression */ + +#ifndef GL_EXT_texture_type_2_10_10_10_REV +#define GL_EXT_texture_type_2_10_10_10_REV 1 +#define GL_UNSIGNED_INT_2_10_10_10_REV_EXT 0x8368 +#endif /* GL_EXT_texture_type_2_10_10_10_REV */ + +#ifndef GL_EXT_texture_view +#define GL_EXT_texture_view 1 +#define GL_TEXTURE_VIEW_MIN_LEVEL_EXT 0x82DB +#define GL_TEXTURE_VIEW_NUM_LEVELS_EXT 0x82DC +#define GL_TEXTURE_VIEW_MIN_LAYER_EXT 0x82DD +#define GL_TEXTURE_VIEW_NUM_LAYERS_EXT 0x82DE +typedef void (GL_APIENTRYP PFNGLTEXTUREVIEWEXTPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTextureViewEXT (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +#endif +#endif /* GL_EXT_texture_view */ + +#ifndef GL_EXT_unpack_subimage +#define GL_EXT_unpack_subimage 1 +#define GL_UNPACK_ROW_LENGTH_EXT 0x0CF2 +#define GL_UNPACK_SKIP_ROWS_EXT 0x0CF3 +#define GL_UNPACK_SKIP_PIXELS_EXT 0x0CF4 +#endif /* GL_EXT_unpack_subimage */ + +#ifndef GL_EXT_win32_keyed_mutex +#define GL_EXT_win32_keyed_mutex 1 +typedef GLboolean (GL_APIENTRYP PFNGLACQUIREKEYEDMUTEXWIN32EXTPROC) (GLuint memory, GLuint64 key, GLuint timeout); +typedef GLboolean (GL_APIENTRYP PFNGLRELEASEKEYEDMUTEXWIN32EXTPROC) (GLuint memory, GLuint64 key); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL GLboolean GL_APIENTRY glAcquireKeyedMutexWin32EXT (GLuint memory, GLuint64 key, GLuint timeout); +GL_APICALL GLboolean GL_APIENTRY glReleaseKeyedMutexWin32EXT (GLuint memory, GLuint64 key); +#endif +#endif /* GL_EXT_win32_keyed_mutex */ + +#ifndef GL_EXT_window_rectangles +#define GL_EXT_window_rectangles 1 +#define GL_INCLUSIVE_EXT 0x8F10 +#define GL_EXCLUSIVE_EXT 0x8F11 +#define GL_WINDOW_RECTANGLE_EXT 0x8F12 +#define GL_WINDOW_RECTANGLE_MODE_EXT 0x8F13 +#define GL_MAX_WINDOW_RECTANGLES_EXT 0x8F14 +#define GL_NUM_WINDOW_RECTANGLES_EXT 0x8F15 +typedef void (GL_APIENTRYP PFNGLWINDOWRECTANGLESEXTPROC) (GLenum mode, GLsizei count, const GLint *box); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glWindowRectanglesEXT (GLenum mode, GLsizei count, const GLint *box); +#endif +#endif /* GL_EXT_window_rectangles */ + +#ifndef GL_FJ_shader_binary_GCCSO +#define GL_FJ_shader_binary_GCCSO 1 +#define GL_GCCSO_SHADER_BINARY_FJ 0x9260 +#endif /* GL_FJ_shader_binary_GCCSO */ + +#ifndef GL_IMG_bindless_texture +#define GL_IMG_bindless_texture 1 +typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTUREHANDLEIMGPROC) (GLuint texture); +typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTURESAMPLERHANDLEIMGPROC) (GLuint texture, GLuint sampler); +typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64IMGPROC) (GLint location, GLuint64 value); +typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64VIMGPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64IMGPROC) (GLuint program, GLint location, GLuint64 value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VIMGPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL GLuint64 GL_APIENTRY glGetTextureHandleIMG (GLuint texture); +GL_APICALL GLuint64 GL_APIENTRY glGetTextureSamplerHandleIMG (GLuint texture, GLuint sampler); +GL_APICALL void GL_APIENTRY glUniformHandleui64IMG (GLint location, GLuint64 value); +GL_APICALL void GL_APIENTRY glUniformHandleui64vIMG (GLint location, GLsizei count, const GLuint64 *value); +GL_APICALL void GL_APIENTRY glProgramUniformHandleui64IMG (GLuint program, GLint location, GLuint64 value); +GL_APICALL void GL_APIENTRY glProgramUniformHandleui64vIMG (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +#endif +#endif /* GL_IMG_bindless_texture */ + +#ifndef GL_IMG_framebuffer_downsample +#define GL_IMG_framebuffer_downsample 1 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_AND_DOWNSAMPLE_IMG 0x913C +#define GL_NUM_DOWNSAMPLE_SCALES_IMG 0x913D +#define GL_DOWNSAMPLE_SCALES_IMG 0x913E +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SCALE_IMG 0x913F +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint xscale, GLint yscale); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERDOWNSAMPLEIMGPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer, GLint xscale, GLint yscale); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferTexture2DDownsampleIMG (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint xscale, GLint yscale); +GL_APICALL void GL_APIENTRY glFramebufferTextureLayerDownsampleIMG (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer, GLint xscale, GLint yscale); +#endif +#endif /* GL_IMG_framebuffer_downsample */ + +#ifndef GL_IMG_multisampled_render_to_texture +#define GL_IMG_multisampled_render_to_texture 1 +#define GL_RENDERBUFFER_SAMPLES_IMG 0x9133 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG 0x9134 +#define GL_MAX_SAMPLES_IMG 0x9135 +#define GL_TEXTURE_SAMPLES_IMG 0x9136 +typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleIMG (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleIMG (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); +#endif +#endif /* GL_IMG_multisampled_render_to_texture */ + +#ifndef GL_IMG_program_binary +#define GL_IMG_program_binary 1 +#define GL_SGX_PROGRAM_BINARY_IMG 0x9130 +#endif /* GL_IMG_program_binary */ + +#ifndef GL_IMG_read_format +#define GL_IMG_read_format 1 +#define GL_BGRA_IMG 0x80E1 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG 0x8365 +#endif /* GL_IMG_read_format */ + +#ifndef GL_IMG_shader_binary +#define GL_IMG_shader_binary 1 +#define GL_SGX_BINARY_IMG 0x8C0A +#endif /* GL_IMG_shader_binary */ + +#ifndef GL_IMG_texture_compression_pvrtc +#define GL_IMG_texture_compression_pvrtc 1 +#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 +#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01 +#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 +#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03 +#endif /* GL_IMG_texture_compression_pvrtc */ + +#ifndef GL_IMG_texture_compression_pvrtc2 +#define GL_IMG_texture_compression_pvrtc2 1 +#define GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG 0x9137 +#define GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG 0x9138 +#endif /* GL_IMG_texture_compression_pvrtc2 */ + +#ifndef GL_IMG_texture_filter_cubic +#define GL_IMG_texture_filter_cubic 1 +#define GL_CUBIC_IMG 0x9139 +#define GL_CUBIC_MIPMAP_NEAREST_IMG 0x913A +#define GL_CUBIC_MIPMAP_LINEAR_IMG 0x913B +#endif /* GL_IMG_texture_filter_cubic */ + +#ifndef GL_INTEL_blackhole_render +#define GL_INTEL_blackhole_render 1 +#define GL_BLACKHOLE_RENDER_INTEL 0x83FC +#endif /* GL_INTEL_blackhole_render */ + +#ifndef GL_INTEL_conservative_rasterization +#define GL_INTEL_conservative_rasterization 1 +#define GL_CONSERVATIVE_RASTERIZATION_INTEL 0x83FE +#endif /* GL_INTEL_conservative_rasterization */ + +#ifndef GL_INTEL_framebuffer_CMAA +#define GL_INTEL_framebuffer_CMAA 1 +typedef void (GL_APIENTRYP PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glApplyFramebufferAttachmentCMAAINTEL (void); +#endif +#endif /* GL_INTEL_framebuffer_CMAA */ + +#ifndef GL_INTEL_performance_query +#define GL_INTEL_performance_query 1 +#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000 +#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001 +#define GL_PERFQUERY_WAIT_INTEL 0x83FB +#define GL_PERFQUERY_FLUSH_INTEL 0x83FA +#define GL_PERFQUERY_DONOT_FLUSH_INTEL 0x83F9 +#define GL_PERFQUERY_COUNTER_EVENT_INTEL 0x94F0 +#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1 +#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2 +#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3 +#define GL_PERFQUERY_COUNTER_RAW_INTEL 0x94F4 +#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5 +#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8 +#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9 +#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA +#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB +#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC +#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD +#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE +#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF +#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500 +typedef void (GL_APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (GL_APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle); +typedef void (GL_APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (GL_APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (GL_APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId); +typedef void (GL_APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId); +typedef void (GL_APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); +typedef void (GL_APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, void *data, GLuint *bytesWritten); +typedef void (GL_APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId); +typedef void (GL_APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle); +GL_APICALL void GL_APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle); +GL_APICALL void GL_APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle); +GL_APICALL void GL_APIENTRY glEndPerfQueryINTEL (GLuint queryHandle); +GL_APICALL void GL_APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId); +GL_APICALL void GL_APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId); +GL_APICALL void GL_APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); +GL_APICALL void GL_APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, void *data, GLuint *bytesWritten); +GL_APICALL void GL_APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId); +GL_APICALL void GL_APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); +#endif +#endif /* GL_INTEL_performance_query */ + +#ifndef GL_MESA_bgra +#define GL_MESA_bgra 1 +#define GL_BGR_EXT 0x80E0 +#endif /* GL_MESA_bgra */ + +#ifndef GL_MESA_framebuffer_flip_x +#define GL_MESA_framebuffer_flip_x 1 +#define GL_FRAMEBUFFER_FLIP_X_MESA 0x8BBC +#endif /* GL_MESA_framebuffer_flip_x */ + +#ifndef GL_MESA_framebuffer_flip_y +#define GL_MESA_framebuffer_flip_y 1 +#define GL_FRAMEBUFFER_FLIP_Y_MESA 0x8BBB +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERPARAMETERIMESAPROC) (GLenum target, GLenum pname, GLint param); +typedef void (GL_APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVMESAPROC) (GLenum target, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferParameteriMESA (GLenum target, GLenum pname, GLint param); +GL_APICALL void GL_APIENTRY glGetFramebufferParameterivMESA (GLenum target, GLenum pname, GLint *params); +#endif +#endif /* GL_MESA_framebuffer_flip_y */ + +#ifndef GL_MESA_framebuffer_swap_xy +#define GL_MESA_framebuffer_swap_xy 1 +#define GL_FRAMEBUFFER_SWAP_XY_MESA 0x8BBD +#endif /* GL_MESA_framebuffer_swap_xy */ + +#ifndef GL_MESA_program_binary_formats +#define GL_MESA_program_binary_formats 1 +#define GL_PROGRAM_BINARY_FORMAT_MESA 0x875F +#endif /* GL_MESA_program_binary_formats */ + +#ifndef GL_MESA_shader_integer_functions +#define GL_MESA_shader_integer_functions 1 +#endif /* GL_MESA_shader_integer_functions */ + +#ifndef GL_NVX_blend_equation_advanced_multi_draw_buffers +#define GL_NVX_blend_equation_advanced_multi_draw_buffers 1 +#endif /* GL_NVX_blend_equation_advanced_multi_draw_buffers */ + +#ifndef GL_NV_bindless_texture +#define GL_NV_bindless_texture 1 +typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTUREHANDLENVPROC) (GLuint texture); +typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTURESAMPLERHANDLENVPROC) (GLuint texture, GLuint sampler); +typedef void (GL_APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); +typedef void (GL_APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC) (GLuint64 handle); +typedef GLuint64 (GL_APIENTRYP PFNGLGETIMAGEHANDLENVPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +typedef void (GL_APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle, GLenum access); +typedef void (GL_APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC) (GLuint64 handle); +typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64NVPROC) (GLint location, GLuint64 value); +typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64VNVPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC) (GLuint program, GLint location, GLuint64 value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +typedef GLboolean (GL_APIENTRYP PFNGLISTEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); +typedef GLboolean (GL_APIENTRYP PFNGLISIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL GLuint64 GL_APIENTRY glGetTextureHandleNV (GLuint texture); +GL_APICALL GLuint64 GL_APIENTRY glGetTextureSamplerHandleNV (GLuint texture, GLuint sampler); +GL_APICALL void GL_APIENTRY glMakeTextureHandleResidentNV (GLuint64 handle); +GL_APICALL void GL_APIENTRY glMakeTextureHandleNonResidentNV (GLuint64 handle); +GL_APICALL GLuint64 GL_APIENTRY glGetImageHandleNV (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +GL_APICALL void GL_APIENTRY glMakeImageHandleResidentNV (GLuint64 handle, GLenum access); +GL_APICALL void GL_APIENTRY glMakeImageHandleNonResidentNV (GLuint64 handle); +GL_APICALL void GL_APIENTRY glUniformHandleui64NV (GLint location, GLuint64 value); +GL_APICALL void GL_APIENTRY glUniformHandleui64vNV (GLint location, GLsizei count, const GLuint64 *value); +GL_APICALL void GL_APIENTRY glProgramUniformHandleui64NV (GLuint program, GLint location, GLuint64 value); +GL_APICALL void GL_APIENTRY glProgramUniformHandleui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +GL_APICALL GLboolean GL_APIENTRY glIsTextureHandleResidentNV (GLuint64 handle); +GL_APICALL GLboolean GL_APIENTRY glIsImageHandleResidentNV (GLuint64 handle); +#endif +#endif /* GL_NV_bindless_texture */ + +#ifndef GL_NV_blend_equation_advanced +#define GL_NV_blend_equation_advanced 1 +#define GL_BLEND_OVERLAP_NV 0x9281 +#define GL_BLEND_PREMULTIPLIED_SRC_NV 0x9280 +#define GL_BLUE_NV 0x1905 +#define GL_COLORBURN_NV 0x929A +#define GL_COLORDODGE_NV 0x9299 +#define GL_CONJOINT_NV 0x9284 +#define GL_CONTRAST_NV 0x92A1 +#define GL_DARKEN_NV 0x9297 +#define GL_DIFFERENCE_NV 0x929E +#define GL_DISJOINT_NV 0x9283 +#define GL_DST_ATOP_NV 0x928F +#define GL_DST_IN_NV 0x928B +#define GL_DST_NV 0x9287 +#define GL_DST_OUT_NV 0x928D +#define GL_DST_OVER_NV 0x9289 +#define GL_EXCLUSION_NV 0x92A0 +#define GL_GREEN_NV 0x1904 +#define GL_HARDLIGHT_NV 0x929B +#define GL_HARDMIX_NV 0x92A9 +#define GL_HSL_COLOR_NV 0x92AF +#define GL_HSL_HUE_NV 0x92AD +#define GL_HSL_LUMINOSITY_NV 0x92B0 +#define GL_HSL_SATURATION_NV 0x92AE +#define GL_INVERT_OVG_NV 0x92B4 +#define GL_INVERT_RGB_NV 0x92A3 +#define GL_LIGHTEN_NV 0x9298 +#define GL_LINEARBURN_NV 0x92A5 +#define GL_LINEARDODGE_NV 0x92A4 +#define GL_LINEARLIGHT_NV 0x92A7 +#define GL_MINUS_CLAMPED_NV 0x92B3 +#define GL_MINUS_NV 0x929F +#define GL_MULTIPLY_NV 0x9294 +#define GL_OVERLAY_NV 0x9296 +#define GL_PINLIGHT_NV 0x92A8 +#define GL_PLUS_CLAMPED_ALPHA_NV 0x92B2 +#define GL_PLUS_CLAMPED_NV 0x92B1 +#define GL_PLUS_DARKER_NV 0x9292 +#define GL_PLUS_NV 0x9291 +#define GL_RED_NV 0x1903 +#define GL_SCREEN_NV 0x9295 +#define GL_SOFTLIGHT_NV 0x929C +#define GL_SRC_ATOP_NV 0x928E +#define GL_SRC_IN_NV 0x928A +#define GL_SRC_NV 0x9286 +#define GL_SRC_OUT_NV 0x928C +#define GL_SRC_OVER_NV 0x9288 +#define GL_UNCORRELATED_NV 0x9282 +#define GL_VIVIDLIGHT_NV 0x92A6 +#define GL_XOR_NV 0x1506 +typedef void (GL_APIENTRYP PFNGLBLENDPARAMETERINVPROC) (GLenum pname, GLint value); +typedef void (GL_APIENTRYP PFNGLBLENDBARRIERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBlendParameteriNV (GLenum pname, GLint value); +GL_APICALL void GL_APIENTRY glBlendBarrierNV (void); +#endif +#endif /* GL_NV_blend_equation_advanced */ + +#ifndef GL_NV_blend_equation_advanced_coherent +#define GL_NV_blend_equation_advanced_coherent 1 +#define GL_BLEND_ADVANCED_COHERENT_NV 0x9285 +#endif /* GL_NV_blend_equation_advanced_coherent */ + +#ifndef GL_NV_blend_minmax_factor +#define GL_NV_blend_minmax_factor 1 +#define GL_FACTOR_MIN_AMD 0x901C +#define GL_FACTOR_MAX_AMD 0x901D +#endif /* GL_NV_blend_minmax_factor */ + +#ifndef GL_NV_clip_space_w_scaling +#define GL_NV_clip_space_w_scaling 1 +#define GL_VIEWPORT_POSITION_W_SCALE_NV 0x937C +#define GL_VIEWPORT_POSITION_W_SCALE_X_COEFF_NV 0x937D +#define GL_VIEWPORT_POSITION_W_SCALE_Y_COEFF_NV 0x937E +typedef void (GL_APIENTRYP PFNGLVIEWPORTPOSITIONWSCALENVPROC) (GLuint index, GLfloat xcoeff, GLfloat ycoeff); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glViewportPositionWScaleNV (GLuint index, GLfloat xcoeff, GLfloat ycoeff); +#endif +#endif /* GL_NV_clip_space_w_scaling */ + +#ifndef GL_NV_compute_shader_derivatives +#define GL_NV_compute_shader_derivatives 1 +#endif /* GL_NV_compute_shader_derivatives */ + +#ifndef GL_NV_conditional_render +#define GL_NV_conditional_render 1 +#define GL_QUERY_WAIT_NV 0x8E13 +#define GL_QUERY_NO_WAIT_NV 0x8E14 +#define GL_QUERY_BY_REGION_WAIT_NV 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT_NV 0x8E16 +typedef void (GL_APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode); +typedef void (GL_APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode); +GL_APICALL void GL_APIENTRY glEndConditionalRenderNV (void); +#endif +#endif /* GL_NV_conditional_render */ + +#ifndef GL_NV_conservative_raster +#define GL_NV_conservative_raster 1 +#define GL_CONSERVATIVE_RASTERIZATION_NV 0x9346 +#define GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV 0x9347 +#define GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV 0x9348 +#define GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV 0x9349 +typedef void (GL_APIENTRYP PFNGLSUBPIXELPRECISIONBIASNVPROC) (GLuint xbits, GLuint ybits); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glSubpixelPrecisionBiasNV (GLuint xbits, GLuint ybits); +#endif +#endif /* GL_NV_conservative_raster */ + +#ifndef GL_NV_conservative_raster_pre_snap +#define GL_NV_conservative_raster_pre_snap 1 +#define GL_CONSERVATIVE_RASTER_MODE_PRE_SNAP_NV 0x9550 +#endif /* GL_NV_conservative_raster_pre_snap */ + +#ifndef GL_NV_conservative_raster_pre_snap_triangles +#define GL_NV_conservative_raster_pre_snap_triangles 1 +#define GL_CONSERVATIVE_RASTER_MODE_NV 0x954D +#define GL_CONSERVATIVE_RASTER_MODE_POST_SNAP_NV 0x954E +#define GL_CONSERVATIVE_RASTER_MODE_PRE_SNAP_TRIANGLES_NV 0x954F +typedef void (GL_APIENTRYP PFNGLCONSERVATIVERASTERPARAMETERINVPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glConservativeRasterParameteriNV (GLenum pname, GLint param); +#endif +#endif /* GL_NV_conservative_raster_pre_snap_triangles */ + +#ifndef GL_NV_copy_buffer +#define GL_NV_copy_buffer 1 +#define GL_COPY_READ_BUFFER_NV 0x8F36 +#define GL_COPY_WRITE_BUFFER_NV 0x8F37 +typedef void (GL_APIENTRYP PFNGLCOPYBUFFERSUBDATANVPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glCopyBufferSubDataNV (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +#endif +#endif /* GL_NV_copy_buffer */ + +#ifndef GL_NV_coverage_sample +#define GL_NV_coverage_sample 1 +#define GL_COVERAGE_COMPONENT_NV 0x8ED0 +#define GL_COVERAGE_COMPONENT4_NV 0x8ED1 +#define GL_COVERAGE_ATTACHMENT_NV 0x8ED2 +#define GL_COVERAGE_BUFFERS_NV 0x8ED3 +#define GL_COVERAGE_SAMPLES_NV 0x8ED4 +#define GL_COVERAGE_ALL_FRAGMENTS_NV 0x8ED5 +#define GL_COVERAGE_EDGE_FRAGMENTS_NV 0x8ED6 +#define GL_COVERAGE_AUTOMATIC_NV 0x8ED7 +#define GL_COVERAGE_BUFFER_BIT_NV 0x00008000 +typedef void (GL_APIENTRYP PFNGLCOVERAGEMASKNVPROC) (GLboolean mask); +typedef void (GL_APIENTRYP PFNGLCOVERAGEOPERATIONNVPROC) (GLenum operation); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glCoverageMaskNV (GLboolean mask); +GL_APICALL void GL_APIENTRY glCoverageOperationNV (GLenum operation); +#endif +#endif /* GL_NV_coverage_sample */ + +#ifndef GL_NV_depth_nonlinear +#define GL_NV_depth_nonlinear 1 +#define GL_DEPTH_COMPONENT16_NONLINEAR_NV 0x8E2C +#endif /* GL_NV_depth_nonlinear */ + +#ifndef GL_NV_draw_buffers +#define GL_NV_draw_buffers 1 +#define GL_MAX_DRAW_BUFFERS_NV 0x8824 +#define GL_DRAW_BUFFER0_NV 0x8825 +#define GL_DRAW_BUFFER1_NV 0x8826 +#define GL_DRAW_BUFFER2_NV 0x8827 +#define GL_DRAW_BUFFER3_NV 0x8828 +#define GL_DRAW_BUFFER4_NV 0x8829 +#define GL_DRAW_BUFFER5_NV 0x882A +#define GL_DRAW_BUFFER6_NV 0x882B +#define GL_DRAW_BUFFER7_NV 0x882C +#define GL_DRAW_BUFFER8_NV 0x882D +#define GL_DRAW_BUFFER9_NV 0x882E +#define GL_DRAW_BUFFER10_NV 0x882F +#define GL_DRAW_BUFFER11_NV 0x8830 +#define GL_DRAW_BUFFER12_NV 0x8831 +#define GL_DRAW_BUFFER13_NV 0x8832 +#define GL_DRAW_BUFFER14_NV 0x8833 +#define GL_DRAW_BUFFER15_NV 0x8834 +#define GL_COLOR_ATTACHMENT0_NV 0x8CE0 +#define GL_COLOR_ATTACHMENT1_NV 0x8CE1 +#define GL_COLOR_ATTACHMENT2_NV 0x8CE2 +#define GL_COLOR_ATTACHMENT3_NV 0x8CE3 +#define GL_COLOR_ATTACHMENT4_NV 0x8CE4 +#define GL_COLOR_ATTACHMENT5_NV 0x8CE5 +#define GL_COLOR_ATTACHMENT6_NV 0x8CE6 +#define GL_COLOR_ATTACHMENT7_NV 0x8CE7 +#define GL_COLOR_ATTACHMENT8_NV 0x8CE8 +#define GL_COLOR_ATTACHMENT9_NV 0x8CE9 +#define GL_COLOR_ATTACHMENT10_NV 0x8CEA +#define GL_COLOR_ATTACHMENT11_NV 0x8CEB +#define GL_COLOR_ATTACHMENT12_NV 0x8CEC +#define GL_COLOR_ATTACHMENT13_NV 0x8CED +#define GL_COLOR_ATTACHMENT14_NV 0x8CEE +#define GL_COLOR_ATTACHMENT15_NV 0x8CEF +typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSNVPROC) (GLsizei n, const GLenum *bufs); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawBuffersNV (GLsizei n, const GLenum *bufs); +#endif +#endif /* GL_NV_draw_buffers */ + +#ifndef GL_NV_draw_instanced +#define GL_NV_draw_instanced 1 +typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDNVPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDNVPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawArraysInstancedNV (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +GL_APICALL void GL_APIENTRY glDrawElementsInstancedNV (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#endif +#endif /* GL_NV_draw_instanced */ + +#ifndef GL_NV_draw_vulkan_image +#define GL_NV_draw_vulkan_image 1 +typedef void (GL_APIENTRY *GLVULKANPROCNV)(void); +typedef void (GL_APIENTRYP PFNGLDRAWVKIMAGENVPROC) (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +typedef GLVULKANPROCNV (GL_APIENTRYP PFNGLGETVKPROCADDRNVPROC) (const GLchar *name); +typedef void (GL_APIENTRYP PFNGLWAITVKSEMAPHORENVPROC) (GLuint64 vkSemaphore); +typedef void (GL_APIENTRYP PFNGLSIGNALVKSEMAPHORENVPROC) (GLuint64 vkSemaphore); +typedef void (GL_APIENTRYP PFNGLSIGNALVKFENCENVPROC) (GLuint64 vkFence); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawVkImageNV (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +GL_APICALL GLVULKANPROCNV GL_APIENTRY glGetVkProcAddrNV (const GLchar *name); +GL_APICALL void GL_APIENTRY glWaitVkSemaphoreNV (GLuint64 vkSemaphore); +GL_APICALL void GL_APIENTRY glSignalVkSemaphoreNV (GLuint64 vkSemaphore); +GL_APICALL void GL_APIENTRY glSignalVkFenceNV (GLuint64 vkFence); +#endif +#endif /* GL_NV_draw_vulkan_image */ + +#ifndef GL_NV_explicit_attrib_location +#define GL_NV_explicit_attrib_location 1 +#endif /* GL_NV_explicit_attrib_location */ + +#ifndef GL_NV_fbo_color_attachments +#define GL_NV_fbo_color_attachments 1 +#define GL_MAX_COLOR_ATTACHMENTS_NV 0x8CDF +#endif /* GL_NV_fbo_color_attachments */ + +#ifndef GL_NV_fence +#define GL_NV_fence 1 +#define GL_ALL_COMPLETED_NV 0x84F2 +#define GL_FENCE_STATUS_NV 0x84F3 +#define GL_FENCE_CONDITION_NV 0x84F4 +typedef void (GL_APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences); +typedef void (GL_APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences); +typedef GLboolean (GL_APIENTRYP PFNGLISFENCENVPROC) (GLuint fence); +typedef GLboolean (GL_APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence); +typedef void (GL_APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence); +typedef void (GL_APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences); +GL_APICALL void GL_APIENTRY glGenFencesNV (GLsizei n, GLuint *fences); +GL_APICALL GLboolean GL_APIENTRY glIsFenceNV (GLuint fence); +GL_APICALL GLboolean GL_APIENTRY glTestFenceNV (GLuint fence); +GL_APICALL void GL_APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glFinishFenceNV (GLuint fence); +GL_APICALL void GL_APIENTRY glSetFenceNV (GLuint fence, GLenum condition); +#endif +#endif /* GL_NV_fence */ + +#ifndef GL_NV_fill_rectangle +#define GL_NV_fill_rectangle 1 +#define GL_FILL_RECTANGLE_NV 0x933C +#endif /* GL_NV_fill_rectangle */ + +#ifndef GL_NV_fragment_coverage_to_color +#define GL_NV_fragment_coverage_to_color 1 +#define GL_FRAGMENT_COVERAGE_TO_COLOR_NV 0x92DD +#define GL_FRAGMENT_COVERAGE_COLOR_NV 0x92DE +typedef void (GL_APIENTRYP PFNGLFRAGMENTCOVERAGECOLORNVPROC) (GLuint color); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFragmentCoverageColorNV (GLuint color); +#endif +#endif /* GL_NV_fragment_coverage_to_color */ + +#ifndef GL_NV_fragment_shader_barycentric +#define GL_NV_fragment_shader_barycentric 1 +#endif /* GL_NV_fragment_shader_barycentric */ + +#ifndef GL_NV_fragment_shader_interlock +#define GL_NV_fragment_shader_interlock 1 +#endif /* GL_NV_fragment_shader_interlock */ + +#ifndef GL_NV_framebuffer_blit +#define GL_NV_framebuffer_blit 1 +#define GL_READ_FRAMEBUFFER_NV 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_NV 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING_NV 0x8CA6 +#define GL_READ_FRAMEBUFFER_BINDING_NV 0x8CAA +typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERNVPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBlitFramebufferNV (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#endif +#endif /* GL_NV_framebuffer_blit */ + +#ifndef GL_NV_framebuffer_mixed_samples +#define GL_NV_framebuffer_mixed_samples 1 +#define GL_COVERAGE_MODULATION_TABLE_NV 0x9331 +#define GL_COLOR_SAMPLES_NV 0x8E20 +#define GL_DEPTH_SAMPLES_NV 0x932D +#define GL_STENCIL_SAMPLES_NV 0x932E +#define GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV 0x932F +#define GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV 0x9330 +#define GL_COVERAGE_MODULATION_NV 0x9332 +#define GL_COVERAGE_MODULATION_TABLE_SIZE_NV 0x9333 +typedef void (GL_APIENTRYP PFNGLCOVERAGEMODULATIONTABLENVPROC) (GLsizei n, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLGETCOVERAGEMODULATIONTABLENVPROC) (GLsizei bufSize, GLfloat *v); +typedef void (GL_APIENTRYP PFNGLCOVERAGEMODULATIONNVPROC) (GLenum components); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glCoverageModulationTableNV (GLsizei n, const GLfloat *v); +GL_APICALL void GL_APIENTRY glGetCoverageModulationTableNV (GLsizei bufSize, GLfloat *v); +GL_APICALL void GL_APIENTRY glCoverageModulationNV (GLenum components); +#endif +#endif /* GL_NV_framebuffer_mixed_samples */ + +#ifndef GL_NV_framebuffer_multisample +#define GL_NV_framebuffer_multisample 1 +#define GL_RENDERBUFFER_SAMPLES_NV 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV 0x8D56 +#define GL_MAX_SAMPLES_NV 0x8D57 +typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLENVPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleNV (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_NV_framebuffer_multisample */ + +#ifndef GL_NV_generate_mipmap_sRGB +#define GL_NV_generate_mipmap_sRGB 1 +#endif /* GL_NV_generate_mipmap_sRGB */ + +#ifndef GL_NV_geometry_shader_passthrough +#define GL_NV_geometry_shader_passthrough 1 +#endif /* GL_NV_geometry_shader_passthrough */ + +#ifndef GL_NV_gpu_shader5 +#define GL_NV_gpu_shader5 1 +typedef khronos_int64_t GLint64EXT; +typedef khronos_uint64_t GLuint64EXT; +#define GL_INT64_NV 0x140E +#define GL_UNSIGNED_INT64_NV 0x140F +#define GL_INT8_NV 0x8FE0 +#define GL_INT8_VEC2_NV 0x8FE1 +#define GL_INT8_VEC3_NV 0x8FE2 +#define GL_INT8_VEC4_NV 0x8FE3 +#define GL_INT16_NV 0x8FE4 +#define GL_INT16_VEC2_NV 0x8FE5 +#define GL_INT16_VEC3_NV 0x8FE6 +#define GL_INT16_VEC4_NV 0x8FE7 +#define GL_INT64_VEC2_NV 0x8FE9 +#define GL_INT64_VEC3_NV 0x8FEA +#define GL_INT64_VEC4_NV 0x8FEB +#define GL_UNSIGNED_INT8_NV 0x8FEC +#define GL_UNSIGNED_INT8_VEC2_NV 0x8FED +#define GL_UNSIGNED_INT8_VEC3_NV 0x8FEE +#define GL_UNSIGNED_INT8_VEC4_NV 0x8FEF +#define GL_UNSIGNED_INT16_NV 0x8FF0 +#define GL_UNSIGNED_INT16_VEC2_NV 0x8FF1 +#define GL_UNSIGNED_INT16_VEC3_NV 0x8FF2 +#define GL_UNSIGNED_INT16_VEC4_NV 0x8FF3 +#define GL_UNSIGNED_INT64_VEC2_NV 0x8FF5 +#define GL_UNSIGNED_INT64_VEC3_NV 0x8FF6 +#define GL_UNSIGNED_INT64_VEC4_NV 0x8FF7 +#define GL_FLOAT16_NV 0x8FF8 +#define GL_FLOAT16_VEC2_NV 0x8FF9 +#define GL_FLOAT16_VEC3_NV 0x8FFA +#define GL_FLOAT16_VEC4_NV 0x8FFB +#define GL_PATCHES 0x000E +typedef void (GL_APIENTRYP PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x); +typedef void (GL_APIENTRYP PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y); +typedef void (GL_APIENTRYP PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (GL_APIENTRYP PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (GL_APIENTRYP PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x); +typedef void (GL_APIENTRYP PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y); +typedef void (GL_APIENTRYP PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (GL_APIENTRYP PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (GL_APIENTRYP PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (GL_APIENTRYP PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (GL_APIENTRYP PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT *params); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glUniform1i64NV (GLint location, GLint64EXT x); +GL_APICALL void GL_APIENTRY glUniform2i64NV (GLint location, GLint64EXT x, GLint64EXT y); +GL_APICALL void GL_APIENTRY glUniform3i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GL_APICALL void GL_APIENTRY glUniform4i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GL_APICALL void GL_APIENTRY glUniform1i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GL_APICALL void GL_APIENTRY glUniform2i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GL_APICALL void GL_APIENTRY glUniform3i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GL_APICALL void GL_APIENTRY glUniform4i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GL_APICALL void GL_APIENTRY glUniform1ui64NV (GLint location, GLuint64EXT x); +GL_APICALL void GL_APIENTRY glUniform2ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y); +GL_APICALL void GL_APIENTRY glUniform3ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GL_APICALL void GL_APIENTRY glUniform4ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GL_APICALL void GL_APIENTRY glUniform1ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GL_APICALL void GL_APIENTRY glUniform2ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GL_APICALL void GL_APIENTRY glUniform3ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GL_APICALL void GL_APIENTRY glUniform4ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GL_APICALL void GL_APIENTRY glGetUniformi64vNV (GLuint program, GLint location, GLint64EXT *params); +GL_APICALL void GL_APIENTRY glProgramUniform1i64NV (GLuint program, GLint location, GLint64EXT x); +GL_APICALL void GL_APIENTRY glProgramUniform2i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); +GL_APICALL void GL_APIENTRY glProgramUniform3i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GL_APICALL void GL_APIENTRY glProgramUniform4i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GL_APICALL void GL_APIENTRY glProgramUniform1i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GL_APICALL void GL_APIENTRY glProgramUniform2i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GL_APICALL void GL_APIENTRY glProgramUniform3i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GL_APICALL void GL_APIENTRY glProgramUniform4i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GL_APICALL void GL_APIENTRY glProgramUniform1ui64NV (GLuint program, GLint location, GLuint64EXT x); +GL_APICALL void GL_APIENTRY glProgramUniform2ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); +GL_APICALL void GL_APIENTRY glProgramUniform3ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GL_APICALL void GL_APIENTRY glProgramUniform4ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GL_APICALL void GL_APIENTRY glProgramUniform1ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GL_APICALL void GL_APIENTRY glProgramUniform2ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GL_APICALL void GL_APIENTRY glProgramUniform3ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GL_APICALL void GL_APIENTRY glProgramUniform4ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif +#endif /* GL_NV_gpu_shader5 */ + +#ifndef GL_NV_image_formats +#define GL_NV_image_formats 1 +#endif /* GL_NV_image_formats */ + +#ifndef GL_NV_instanced_arrays +#define GL_NV_instanced_arrays 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_NV 0x88FE +typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORNVPROC) (GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glVertexAttribDivisorNV (GLuint index, GLuint divisor); +#endif +#endif /* GL_NV_instanced_arrays */ + +#ifndef GL_NV_internalformat_sample_query +#define GL_NV_internalformat_sample_query 1 +#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 +#define GL_MULTISAMPLES_NV 0x9371 +#define GL_SUPERSAMPLE_SCALE_X_NV 0x9372 +#define GL_SUPERSAMPLE_SCALE_Y_NV 0x9373 +#define GL_CONFORMANT_NV 0x9374 +typedef void (GL_APIENTRYP PFNGLGETINTERNALFORMATSAMPLEIVNVPROC) (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei count, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGetInternalformatSampleivNV (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei count, GLint *params); +#endif +#endif /* GL_NV_internalformat_sample_query */ + +#ifndef GL_NV_memory_attachment +#define GL_NV_memory_attachment 1 +#define GL_ATTACHED_MEMORY_OBJECT_NV 0x95A4 +#define GL_ATTACHED_MEMORY_OFFSET_NV 0x95A5 +#define GL_MEMORY_ATTACHABLE_ALIGNMENT_NV 0x95A6 +#define GL_MEMORY_ATTACHABLE_SIZE_NV 0x95A7 +#define GL_MEMORY_ATTACHABLE_NV 0x95A8 +#define GL_DETACHED_MEMORY_INCARNATION_NV 0x95A9 +#define GL_DETACHED_TEXTURES_NV 0x95AA +#define GL_DETACHED_BUFFERS_NV 0x95AB +#define GL_MAX_DETACHED_TEXTURES_NV 0x95AC +#define GL_MAX_DETACHED_BUFFERS_NV 0x95AD +typedef void (GL_APIENTRYP PFNGLGETMEMORYOBJECTDETACHEDRESOURCESUIVNVPROC) (GLuint memory, GLenum pname, GLint first, GLsizei count, GLuint *params); +typedef void (GL_APIENTRYP PFNGLRESETMEMORYOBJECTPARAMETERNVPROC) (GLuint memory, GLenum pname); +typedef void (GL_APIENTRYP PFNGLTEXATTACHMEMORYNVPROC) (GLenum target, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLBUFFERATTACHMEMORYNVPROC) (GLenum target, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLTEXTUREATTACHMEMORYNVPROC) (GLuint texture, GLuint memory, GLuint64 offset); +typedef void (GL_APIENTRYP PFNGLNAMEDBUFFERATTACHMEMORYNVPROC) (GLuint buffer, GLuint memory, GLuint64 offset); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGetMemoryObjectDetachedResourcesuivNV (GLuint memory, GLenum pname, GLint first, GLsizei count, GLuint *params); +GL_APICALL void GL_APIENTRY glResetMemoryObjectParameterNV (GLuint memory, GLenum pname); +GL_APICALL void GL_APIENTRY glTexAttachMemoryNV (GLenum target, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glBufferAttachMemoryNV (GLenum target, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glTextureAttachMemoryNV (GLuint texture, GLuint memory, GLuint64 offset); +GL_APICALL void GL_APIENTRY glNamedBufferAttachMemoryNV (GLuint buffer, GLuint memory, GLuint64 offset); +#endif +#endif /* GL_NV_memory_attachment */ + +#ifndef GL_NV_memory_object_sparse +#define GL_NV_memory_object_sparse 1 +typedef void (GL_APIENTRYP PFNGLBUFFERPAGECOMMITMENTMEMNVPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit); +typedef void (GL_APIENTRYP PFNGLTEXPAGECOMMITMENTMEMNVPROC) (GLenum target, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit); +typedef void (GL_APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTMEMNVPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit); +typedef void (GL_APIENTRYP PFNGLTEXTUREPAGECOMMITMENTMEMNVPROC) (GLuint texture, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBufferPageCommitmentMemNV (GLenum target, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit); +GL_APICALL void GL_APIENTRY glTexPageCommitmentMemNV (GLenum target, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit); +GL_APICALL void GL_APIENTRY glNamedBufferPageCommitmentMemNV (GLuint buffer, GLintptr offset, GLsizeiptr size, GLuint memory, GLuint64 memOffset, GLboolean commit); +GL_APICALL void GL_APIENTRY glTexturePageCommitmentMemNV (GLuint texture, GLint layer, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset, GLboolean commit); +#endif +#endif /* GL_NV_memory_object_sparse */ + +#ifndef GL_NV_mesh_shader +#define GL_NV_mesh_shader 1 +#define GL_MESH_SHADER_NV 0x9559 +#define GL_TASK_SHADER_NV 0x955A +#define GL_MAX_MESH_UNIFORM_BLOCKS_NV 0x8E60 +#define GL_MAX_MESH_TEXTURE_IMAGE_UNITS_NV 0x8E61 +#define GL_MAX_MESH_IMAGE_UNIFORMS_NV 0x8E62 +#define GL_MAX_MESH_UNIFORM_COMPONENTS_NV 0x8E63 +#define GL_MAX_MESH_ATOMIC_COUNTER_BUFFERS_NV 0x8E64 +#define GL_MAX_MESH_ATOMIC_COUNTERS_NV 0x8E65 +#define GL_MAX_MESH_SHADER_STORAGE_BLOCKS_NV 0x8E66 +#define GL_MAX_COMBINED_MESH_UNIFORM_COMPONENTS_NV 0x8E67 +#define GL_MAX_TASK_UNIFORM_BLOCKS_NV 0x8E68 +#define GL_MAX_TASK_TEXTURE_IMAGE_UNITS_NV 0x8E69 +#define GL_MAX_TASK_IMAGE_UNIFORMS_NV 0x8E6A +#define GL_MAX_TASK_UNIFORM_COMPONENTS_NV 0x8E6B +#define GL_MAX_TASK_ATOMIC_COUNTER_BUFFERS_NV 0x8E6C +#define GL_MAX_TASK_ATOMIC_COUNTERS_NV 0x8E6D +#define GL_MAX_TASK_SHADER_STORAGE_BLOCKS_NV 0x8E6E +#define GL_MAX_COMBINED_TASK_UNIFORM_COMPONENTS_NV 0x8E6F +#define GL_MAX_MESH_WORK_GROUP_INVOCATIONS_NV 0x95A2 +#define GL_MAX_TASK_WORK_GROUP_INVOCATIONS_NV 0x95A3 +#define GL_MAX_MESH_TOTAL_MEMORY_SIZE_NV 0x9536 +#define GL_MAX_TASK_TOTAL_MEMORY_SIZE_NV 0x9537 +#define GL_MAX_MESH_OUTPUT_VERTICES_NV 0x9538 +#define GL_MAX_MESH_OUTPUT_PRIMITIVES_NV 0x9539 +#define GL_MAX_TASK_OUTPUT_COUNT_NV 0x953A +#define GL_MAX_DRAW_MESH_TASKS_COUNT_NV 0x953D +#define GL_MAX_MESH_VIEWS_NV 0x9557 +#define GL_MESH_OUTPUT_PER_VERTEX_GRANULARITY_NV 0x92DF +#define GL_MESH_OUTPUT_PER_PRIMITIVE_GRANULARITY_NV 0x9543 +#define GL_MAX_MESH_WORK_GROUP_SIZE_NV 0x953B +#define GL_MAX_TASK_WORK_GROUP_SIZE_NV 0x953C +#define GL_MESH_WORK_GROUP_SIZE_NV 0x953E +#define GL_TASK_WORK_GROUP_SIZE_NV 0x953F +#define GL_MESH_VERTICES_OUT_NV 0x9579 +#define GL_MESH_PRIMITIVES_OUT_NV 0x957A +#define GL_MESH_OUTPUT_TYPE_NV 0x957B +#define GL_UNIFORM_BLOCK_REFERENCED_BY_MESH_SHADER_NV 0x959C +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TASK_SHADER_NV 0x959D +#define GL_REFERENCED_BY_MESH_SHADER_NV 0x95A0 +#define GL_REFERENCED_BY_TASK_SHADER_NV 0x95A1 +#define GL_MESH_SHADER_BIT_NV 0x00000040 +#define GL_TASK_SHADER_BIT_NV 0x00000080 +#define GL_MESH_SUBROUTINE_NV 0x957C +#define GL_TASK_SUBROUTINE_NV 0x957D +#define GL_MESH_SUBROUTINE_UNIFORM_NV 0x957E +#define GL_TASK_SUBROUTINE_UNIFORM_NV 0x957F +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_MESH_SHADER_NV 0x959E +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TASK_SHADER_NV 0x959F +typedef void (GL_APIENTRYP PFNGLDRAWMESHTASKSNVPROC) (GLuint first, GLuint count); +typedef void (GL_APIENTRYP PFNGLDRAWMESHTASKSINDIRECTNVPROC) (GLintptr indirect); +typedef void (GL_APIENTRYP PFNGLMULTIDRAWMESHTASKSINDIRECTNVPROC) (GLintptr indirect, GLsizei drawcount, GLsizei stride); +typedef void (GL_APIENTRYP PFNGLMULTIDRAWMESHTASKSINDIRECTCOUNTNVPROC) (GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glDrawMeshTasksNV (GLuint first, GLuint count); +GL_APICALL void GL_APIENTRY glDrawMeshTasksIndirectNV (GLintptr indirect); +GL_APICALL void GL_APIENTRY glMultiDrawMeshTasksIndirectNV (GLintptr indirect, GLsizei drawcount, GLsizei stride); +GL_APICALL void GL_APIENTRY glMultiDrawMeshTasksIndirectCountNV (GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#endif +#endif /* GL_NV_mesh_shader */ + +#ifndef GL_NV_non_square_matrices +#define GL_NV_non_square_matrices 1 +#define GL_FLOAT_MAT2x3_NV 0x8B65 +#define GL_FLOAT_MAT2x4_NV 0x8B66 +#define GL_FLOAT_MAT3x2_NV 0x8B67 +#define GL_FLOAT_MAT3x4_NV 0x8B68 +#define GL_FLOAT_MAT4x2_NV 0x8B69 +#define GL_FLOAT_MAT4x3_NV 0x8B6A +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X3FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X2FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X4FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X2FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X4FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X3FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glUniformMatrix2x3fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniformMatrix3x2fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniformMatrix2x4fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniformMatrix4x2fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniformMatrix3x4fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GL_APICALL void GL_APIENTRY glUniformMatrix4x3fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#endif +#endif /* GL_NV_non_square_matrices */ + +#ifndef GL_NV_path_rendering +#define GL_NV_path_rendering 1 +typedef double GLdouble; +#define GL_PATH_FORMAT_SVG_NV 0x9070 +#define GL_PATH_FORMAT_PS_NV 0x9071 +#define GL_STANDARD_FONT_NAME_NV 0x9072 +#define GL_SYSTEM_FONT_NAME_NV 0x9073 +#define GL_FILE_NAME_NV 0x9074 +#define GL_PATH_STROKE_WIDTH_NV 0x9075 +#define GL_PATH_END_CAPS_NV 0x9076 +#define GL_PATH_INITIAL_END_CAP_NV 0x9077 +#define GL_PATH_TERMINAL_END_CAP_NV 0x9078 +#define GL_PATH_JOIN_STYLE_NV 0x9079 +#define GL_PATH_MITER_LIMIT_NV 0x907A +#define GL_PATH_DASH_CAPS_NV 0x907B +#define GL_PATH_INITIAL_DASH_CAP_NV 0x907C +#define GL_PATH_TERMINAL_DASH_CAP_NV 0x907D +#define GL_PATH_DASH_OFFSET_NV 0x907E +#define GL_PATH_CLIENT_LENGTH_NV 0x907F +#define GL_PATH_FILL_MODE_NV 0x9080 +#define GL_PATH_FILL_MASK_NV 0x9081 +#define GL_PATH_FILL_COVER_MODE_NV 0x9082 +#define GL_PATH_STROKE_COVER_MODE_NV 0x9083 +#define GL_PATH_STROKE_MASK_NV 0x9084 +#define GL_COUNT_UP_NV 0x9088 +#define GL_COUNT_DOWN_NV 0x9089 +#define GL_PATH_OBJECT_BOUNDING_BOX_NV 0x908A +#define GL_CONVEX_HULL_NV 0x908B +#define GL_BOUNDING_BOX_NV 0x908D +#define GL_TRANSLATE_X_NV 0x908E +#define GL_TRANSLATE_Y_NV 0x908F +#define GL_TRANSLATE_2D_NV 0x9090 +#define GL_TRANSLATE_3D_NV 0x9091 +#define GL_AFFINE_2D_NV 0x9092 +#define GL_AFFINE_3D_NV 0x9094 +#define GL_TRANSPOSE_AFFINE_2D_NV 0x9096 +#define GL_TRANSPOSE_AFFINE_3D_NV 0x9098 +#define GL_UTF8_NV 0x909A +#define GL_UTF16_NV 0x909B +#define GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV 0x909C +#define GL_PATH_COMMAND_COUNT_NV 0x909D +#define GL_PATH_COORD_COUNT_NV 0x909E +#define GL_PATH_DASH_ARRAY_COUNT_NV 0x909F +#define GL_PATH_COMPUTED_LENGTH_NV 0x90A0 +#define GL_PATH_FILL_BOUNDING_BOX_NV 0x90A1 +#define GL_PATH_STROKE_BOUNDING_BOX_NV 0x90A2 +#define GL_SQUARE_NV 0x90A3 +#define GL_ROUND_NV 0x90A4 +#define GL_TRIANGULAR_NV 0x90A5 +#define GL_BEVEL_NV 0x90A6 +#define GL_MITER_REVERT_NV 0x90A7 +#define GL_MITER_TRUNCATE_NV 0x90A8 +#define GL_SKIP_MISSING_GLYPH_NV 0x90A9 +#define GL_USE_MISSING_GLYPH_NV 0x90AA +#define GL_PATH_ERROR_POSITION_NV 0x90AB +#define GL_ACCUM_ADJACENT_PAIRS_NV 0x90AD +#define GL_ADJACENT_PAIRS_NV 0x90AE +#define GL_FIRST_TO_REST_NV 0x90AF +#define GL_PATH_GEN_MODE_NV 0x90B0 +#define GL_PATH_GEN_COEFF_NV 0x90B1 +#define GL_PATH_GEN_COMPONENTS_NV 0x90B3 +#define GL_PATH_STENCIL_FUNC_NV 0x90B7 +#define GL_PATH_STENCIL_REF_NV 0x90B8 +#define GL_PATH_STENCIL_VALUE_MASK_NV 0x90B9 +#define GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV 0x90BD +#define GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV 0x90BE +#define GL_PATH_COVER_DEPTH_FUNC_NV 0x90BF +#define GL_PATH_DASH_OFFSET_RESET_NV 0x90B4 +#define GL_MOVE_TO_RESETS_NV 0x90B5 +#define GL_MOVE_TO_CONTINUES_NV 0x90B6 +#define GL_CLOSE_PATH_NV 0x00 +#define GL_MOVE_TO_NV 0x02 +#define GL_RELATIVE_MOVE_TO_NV 0x03 +#define GL_LINE_TO_NV 0x04 +#define GL_RELATIVE_LINE_TO_NV 0x05 +#define GL_HORIZONTAL_LINE_TO_NV 0x06 +#define GL_RELATIVE_HORIZONTAL_LINE_TO_NV 0x07 +#define GL_VERTICAL_LINE_TO_NV 0x08 +#define GL_RELATIVE_VERTICAL_LINE_TO_NV 0x09 +#define GL_QUADRATIC_CURVE_TO_NV 0x0A +#define GL_RELATIVE_QUADRATIC_CURVE_TO_NV 0x0B +#define GL_CUBIC_CURVE_TO_NV 0x0C +#define GL_RELATIVE_CUBIC_CURVE_TO_NV 0x0D +#define GL_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0E +#define GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0F +#define GL_SMOOTH_CUBIC_CURVE_TO_NV 0x10 +#define GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV 0x11 +#define GL_SMALL_CCW_ARC_TO_NV 0x12 +#define GL_RELATIVE_SMALL_CCW_ARC_TO_NV 0x13 +#define GL_SMALL_CW_ARC_TO_NV 0x14 +#define GL_RELATIVE_SMALL_CW_ARC_TO_NV 0x15 +#define GL_LARGE_CCW_ARC_TO_NV 0x16 +#define GL_RELATIVE_LARGE_CCW_ARC_TO_NV 0x17 +#define GL_LARGE_CW_ARC_TO_NV 0x18 +#define GL_RELATIVE_LARGE_CW_ARC_TO_NV 0x19 +#define GL_RESTART_PATH_NV 0xF0 +#define GL_DUP_FIRST_CUBIC_CURVE_TO_NV 0xF2 +#define GL_DUP_LAST_CUBIC_CURVE_TO_NV 0xF4 +#define GL_RECT_NV 0xF6 +#define GL_CIRCULAR_CCW_ARC_TO_NV 0xF8 +#define GL_CIRCULAR_CW_ARC_TO_NV 0xFA +#define GL_CIRCULAR_TANGENT_ARC_TO_NV 0xFC +#define GL_ARC_TO_NV 0xFE +#define GL_RELATIVE_ARC_TO_NV 0xFF +#define GL_BOLD_BIT_NV 0x01 +#define GL_ITALIC_BIT_NV 0x02 +#define GL_GLYPH_WIDTH_BIT_NV 0x01 +#define GL_GLYPH_HEIGHT_BIT_NV 0x02 +#define GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV 0x04 +#define GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV 0x08 +#define GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV 0x10 +#define GL_GLYPH_VERTICAL_BEARING_X_BIT_NV 0x20 +#define GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV 0x40 +#define GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV 0x80 +#define GL_GLYPH_HAS_KERNING_BIT_NV 0x100 +#define GL_FONT_X_MIN_BOUNDS_BIT_NV 0x00010000 +#define GL_FONT_Y_MIN_BOUNDS_BIT_NV 0x00020000 +#define GL_FONT_X_MAX_BOUNDS_BIT_NV 0x00040000 +#define GL_FONT_Y_MAX_BOUNDS_BIT_NV 0x00080000 +#define GL_FONT_UNITS_PER_EM_BIT_NV 0x00100000 +#define GL_FONT_ASCENDER_BIT_NV 0x00200000 +#define GL_FONT_DESCENDER_BIT_NV 0x00400000 +#define GL_FONT_HEIGHT_BIT_NV 0x00800000 +#define GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV 0x01000000 +#define GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV 0x02000000 +#define GL_FONT_UNDERLINE_POSITION_BIT_NV 0x04000000 +#define GL_FONT_UNDERLINE_THICKNESS_BIT_NV 0x08000000 +#define GL_FONT_HAS_KERNING_BIT_NV 0x10000000 +#define GL_ROUNDED_RECT_NV 0xE8 +#define GL_RELATIVE_ROUNDED_RECT_NV 0xE9 +#define GL_ROUNDED_RECT2_NV 0xEA +#define GL_RELATIVE_ROUNDED_RECT2_NV 0xEB +#define GL_ROUNDED_RECT4_NV 0xEC +#define GL_RELATIVE_ROUNDED_RECT4_NV 0xED +#define GL_ROUNDED_RECT8_NV 0xEE +#define GL_RELATIVE_ROUNDED_RECT8_NV 0xEF +#define GL_RELATIVE_RECT_NV 0xF7 +#define GL_FONT_GLYPHS_AVAILABLE_NV 0x9368 +#define GL_FONT_TARGET_UNAVAILABLE_NV 0x9369 +#define GL_FONT_UNAVAILABLE_NV 0x936A +#define GL_FONT_UNINTELLIGIBLE_NV 0x936B +#define GL_CONIC_CURVE_TO_NV 0x1A +#define GL_RELATIVE_CONIC_CURVE_TO_NV 0x1B +#define GL_FONT_NUM_GLYPH_INDICES_BIT_NV 0x20000000 +#define GL_STANDARD_FONT_FORMAT_NV 0x936C +#define GL_PATH_PROJECTION_NV 0x1701 +#define GL_PATH_MODELVIEW_NV 0x1700 +#define GL_PATH_MODELVIEW_STACK_DEPTH_NV 0x0BA3 +#define GL_PATH_MODELVIEW_MATRIX_NV 0x0BA6 +#define GL_PATH_MAX_MODELVIEW_STACK_DEPTH_NV 0x0D36 +#define GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV 0x84E3 +#define GL_PATH_PROJECTION_STACK_DEPTH_NV 0x0BA4 +#define GL_PATH_PROJECTION_MATRIX_NV 0x0BA7 +#define GL_PATH_MAX_PROJECTION_STACK_DEPTH_NV 0x0D38 +#define GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV 0x84E4 +#define GL_FRAGMENT_INPUT_NV 0x936D +typedef GLuint (GL_APIENTRYP PFNGLGENPATHSNVPROC) (GLsizei range); +typedef void (GL_APIENTRYP PFNGLDELETEPATHSNVPROC) (GLuint path, GLsizei range); +typedef GLboolean (GL_APIENTRYP PFNGLISPATHNVPROC) (GLuint path); +typedef void (GL_APIENTRYP PFNGLPATHCOMMANDSNVPROC) (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (GL_APIENTRYP PFNGLPATHCOORDSNVPROC) (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (GL_APIENTRYP PFNGLPATHSUBCOMMANDSNVPROC) (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (GL_APIENTRYP PFNGLPATHSUBCOORDSNVPROC) (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (GL_APIENTRYP PFNGLPATHSTRINGNVPROC) (GLuint path, GLenum format, GLsizei length, const void *pathString); +typedef void (GL_APIENTRYP PFNGLPATHGLYPHSNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (GL_APIENTRYP PFNGLPATHGLYPHRANGENVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (GL_APIENTRYP PFNGLWEIGHTPATHSNVPROC) (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); +typedef void (GL_APIENTRYP PFNGLCOPYPATHNVPROC) (GLuint resultPath, GLuint srcPath); +typedef void (GL_APIENTRYP PFNGLINTERPOLATEPATHSNVPROC) (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); +typedef void (GL_APIENTRYP PFNGLTRANSFORMPATHNVPROC) (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); +typedef void (GL_APIENTRYP PFNGLPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, const GLint *value); +typedef void (GL_APIENTRYP PFNGLPATHPARAMETERINVPROC) (GLuint path, GLenum pname, GLint value); +typedef void (GL_APIENTRYP PFNGLPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, const GLfloat *value); +typedef void (GL_APIENTRYP PFNGLPATHPARAMETERFNVPROC) (GLuint path, GLenum pname, GLfloat value); +typedef void (GL_APIENTRYP PFNGLPATHDASHARRAYNVPROC) (GLuint path, GLsizei dashCount, const GLfloat *dashArray); +typedef void (GL_APIENTRYP PFNGLPATHSTENCILFUNCNVPROC) (GLenum func, GLint ref, GLuint mask); +typedef void (GL_APIENTRYP PFNGLPATHSTENCILDEPTHOFFSETNVPROC) (GLfloat factor, GLfloat units); +typedef void (GL_APIENTRYP PFNGLSTENCILFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask); +typedef void (GL_APIENTRYP PFNGLSTENCILSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask); +typedef void (GL_APIENTRYP PFNGLSTENCILFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); +typedef void (GL_APIENTRYP PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); +typedef void (GL_APIENTRYP PFNGLPATHCOVERDEPTHFUNCNVPROC) (GLenum func); +typedef void (GL_APIENTRYP PFNGLCOVERFILLPATHNVPROC) (GLuint path, GLenum coverMode); +typedef void (GL_APIENTRYP PFNGLCOVERSTROKEPATHNVPROC) (GLuint path, GLenum coverMode); +typedef void (GL_APIENTRYP PFNGLCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (GL_APIENTRYP PFNGLCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (GL_APIENTRYP PFNGLGETPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, GLint *value); +typedef void (GL_APIENTRYP PFNGLGETPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, GLfloat *value); +typedef void (GL_APIENTRYP PFNGLGETPATHCOMMANDSNVPROC) (GLuint path, GLubyte *commands); +typedef void (GL_APIENTRYP PFNGLGETPATHCOORDSNVPROC) (GLuint path, GLfloat *coords); +typedef void (GL_APIENTRYP PFNGLGETPATHDASHARRAYNVPROC) (GLuint path, GLfloat *dashArray); +typedef void (GL_APIENTRYP PFNGLGETPATHMETRICSNVPROC) (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); +typedef void (GL_APIENTRYP PFNGLGETPATHMETRICRANGENVPROC) (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); +typedef void (GL_APIENTRYP PFNGLGETPATHSPACINGNVPROC) (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); +typedef GLboolean (GL_APIENTRYP PFNGLISPOINTINFILLPATHNVPROC) (GLuint path, GLuint mask, GLfloat x, GLfloat y); +typedef GLboolean (GL_APIENTRYP PFNGLISPOINTINSTROKEPATHNVPROC) (GLuint path, GLfloat x, GLfloat y); +typedef GLfloat (GL_APIENTRYP PFNGLGETPATHLENGTHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments); +typedef GLboolean (GL_APIENTRYP PFNGLPOINTALONGPATHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); +typedef void (GL_APIENTRYP PFNGLMATRIXLOAD3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXLOAD3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXMULT3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXMULT3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); +typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask, GLenum coverMode); +typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef GLenum (GL_APIENTRYP PFNGLPATHGLYPHINDEXRANGENVPROC) (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint *baseAndCount); +typedef GLenum (GL_APIENTRYP PFNGLPATHGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef GLenum (GL_APIENTRYP PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (GL_APIENTRYP PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC) (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); +typedef void (GL_APIENTRYP PFNGLGETPROGRAMRESOURCEFVNVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLfloat *params); +typedef void (GL_APIENTRYP PFNGLMATRIXFRUSTUMEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (GL_APIENTRYP PFNGLMATRIXLOADIDENTITYEXTPROC) (GLenum mode); +typedef void (GL_APIENTRYP PFNGLMATRIXLOADTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXLOADTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (GL_APIENTRYP PFNGLMATRIXLOADFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXLOADDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (GL_APIENTRYP PFNGLMATRIXMULTTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXMULTTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (GL_APIENTRYP PFNGLMATRIXMULTFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (GL_APIENTRYP PFNGLMATRIXMULTDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (GL_APIENTRYP PFNGLMATRIXORTHOEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (GL_APIENTRYP PFNGLMATRIXPOPEXTPROC) (GLenum mode); +typedef void (GL_APIENTRYP PFNGLMATRIXPUSHEXTPROC) (GLenum mode); +typedef void (GL_APIENTRYP PFNGLMATRIXROTATEFEXTPROC) (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +typedef void (GL_APIENTRYP PFNGLMATRIXROTATEDEXTPROC) (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +typedef void (GL_APIENTRYP PFNGLMATRIXSCALEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +typedef void (GL_APIENTRYP PFNGLMATRIXSCALEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +typedef void (GL_APIENTRYP PFNGLMATRIXTRANSLATEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +typedef void (GL_APIENTRYP PFNGLMATRIXTRANSLATEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL GLuint GL_APIENTRY glGenPathsNV (GLsizei range); +GL_APICALL void GL_APIENTRY glDeletePathsNV (GLuint path, GLsizei range); +GL_APICALL GLboolean GL_APIENTRY glIsPathNV (GLuint path); +GL_APICALL void GL_APIENTRY glPathCommandsNV (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +GL_APICALL void GL_APIENTRY glPathCoordsNV (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); +GL_APICALL void GL_APIENTRY glPathSubCommandsNV (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +GL_APICALL void GL_APIENTRY glPathSubCoordsNV (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); +GL_APICALL void GL_APIENTRY glPathStringNV (GLuint path, GLenum format, GLsizei length, const void *pathString); +GL_APICALL void GL_APIENTRY glPathGlyphsNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GL_APICALL void GL_APIENTRY glPathGlyphRangeNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GL_APICALL void GL_APIENTRY glWeightPathsNV (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); +GL_APICALL void GL_APIENTRY glCopyPathNV (GLuint resultPath, GLuint srcPath); +GL_APICALL void GL_APIENTRY glInterpolatePathsNV (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); +GL_APICALL void GL_APIENTRY glTransformPathNV (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); +GL_APICALL void GL_APIENTRY glPathParameterivNV (GLuint path, GLenum pname, const GLint *value); +GL_APICALL void GL_APIENTRY glPathParameteriNV (GLuint path, GLenum pname, GLint value); +GL_APICALL void GL_APIENTRY glPathParameterfvNV (GLuint path, GLenum pname, const GLfloat *value); +GL_APICALL void GL_APIENTRY glPathParameterfNV (GLuint path, GLenum pname, GLfloat value); +GL_APICALL void GL_APIENTRY glPathDashArrayNV (GLuint path, GLsizei dashCount, const GLfloat *dashArray); +GL_APICALL void GL_APIENTRY glPathStencilFuncNV (GLenum func, GLint ref, GLuint mask); +GL_APICALL void GL_APIENTRY glPathStencilDepthOffsetNV (GLfloat factor, GLfloat units); +GL_APICALL void GL_APIENTRY glStencilFillPathNV (GLuint path, GLenum fillMode, GLuint mask); +GL_APICALL void GL_APIENTRY glStencilStrokePathNV (GLuint path, GLint reference, GLuint mask); +GL_APICALL void GL_APIENTRY glStencilFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); +GL_APICALL void GL_APIENTRY glStencilStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); +GL_APICALL void GL_APIENTRY glPathCoverDepthFuncNV (GLenum func); +GL_APICALL void GL_APIENTRY glCoverFillPathNV (GLuint path, GLenum coverMode); +GL_APICALL void GL_APIENTRY glCoverStrokePathNV (GLuint path, GLenum coverMode); +GL_APICALL void GL_APIENTRY glCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GL_APICALL void GL_APIENTRY glCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GL_APICALL void GL_APIENTRY glGetPathParameterivNV (GLuint path, GLenum pname, GLint *value); +GL_APICALL void GL_APIENTRY glGetPathParameterfvNV (GLuint path, GLenum pname, GLfloat *value); +GL_APICALL void GL_APIENTRY glGetPathCommandsNV (GLuint path, GLubyte *commands); +GL_APICALL void GL_APIENTRY glGetPathCoordsNV (GLuint path, GLfloat *coords); +GL_APICALL void GL_APIENTRY glGetPathDashArrayNV (GLuint path, GLfloat *dashArray); +GL_APICALL void GL_APIENTRY glGetPathMetricsNV (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); +GL_APICALL void GL_APIENTRY glGetPathMetricRangeNV (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); +GL_APICALL void GL_APIENTRY glGetPathSpacingNV (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); +GL_APICALL GLboolean GL_APIENTRY glIsPointInFillPathNV (GLuint path, GLuint mask, GLfloat x, GLfloat y); +GL_APICALL GLboolean GL_APIENTRY glIsPointInStrokePathNV (GLuint path, GLfloat x, GLfloat y); +GL_APICALL GLfloat GL_APIENTRY glGetPathLengthNV (GLuint path, GLsizei startSegment, GLsizei numSegments); +GL_APICALL GLboolean GL_APIENTRY glPointAlongPathNV (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); +GL_APICALL void GL_APIENTRY glMatrixLoad3x2fNV (GLenum matrixMode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixLoad3x3fNV (GLenum matrixMode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixLoadTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixMult3x2fNV (GLenum matrixMode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixMult3x3fNV (GLenum matrixMode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixMultTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glStencilThenCoverFillPathNV (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); +GL_APICALL void GL_APIENTRY glStencilThenCoverStrokePathNV (GLuint path, GLint reference, GLuint mask, GLenum coverMode); +GL_APICALL void GL_APIENTRY glStencilThenCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GL_APICALL void GL_APIENTRY glStencilThenCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GL_APICALL GLenum GL_APIENTRY glPathGlyphIndexRangeNV (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint *baseAndCount); +GL_APICALL GLenum GL_APIENTRY glPathGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GL_APICALL GLenum GL_APIENTRY glPathMemoryGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GL_APICALL void GL_APIENTRY glProgramPathFragmentInputGenNV (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); +GL_APICALL void GL_APIENTRY glGetProgramResourcefvNV (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei count, GLsizei *length, GLfloat *params); +GL_APICALL void GL_APIENTRY glMatrixFrustumEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GL_APICALL void GL_APIENTRY glMatrixLoadIdentityEXT (GLenum mode); +GL_APICALL void GL_APIENTRY glMatrixLoadTransposefEXT (GLenum mode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixLoadTransposedEXT (GLenum mode, const GLdouble *m); +GL_APICALL void GL_APIENTRY glMatrixLoadfEXT (GLenum mode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixLoaddEXT (GLenum mode, const GLdouble *m); +GL_APICALL void GL_APIENTRY glMatrixMultTransposefEXT (GLenum mode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixMultTransposedEXT (GLenum mode, const GLdouble *m); +GL_APICALL void GL_APIENTRY glMatrixMultfEXT (GLenum mode, const GLfloat *m); +GL_APICALL void GL_APIENTRY glMatrixMultdEXT (GLenum mode, const GLdouble *m); +GL_APICALL void GL_APIENTRY glMatrixOrthoEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GL_APICALL void GL_APIENTRY glMatrixPopEXT (GLenum mode); +GL_APICALL void GL_APIENTRY glMatrixPushEXT (GLenum mode); +GL_APICALL void GL_APIENTRY glMatrixRotatefEXT (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +GL_APICALL void GL_APIENTRY glMatrixRotatedEXT (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +GL_APICALL void GL_APIENTRY glMatrixScalefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +GL_APICALL void GL_APIENTRY glMatrixScaledEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +GL_APICALL void GL_APIENTRY glMatrixTranslatefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +GL_APICALL void GL_APIENTRY glMatrixTranslatedEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +#endif +#endif /* GL_NV_path_rendering */ + +#ifndef GL_NV_path_rendering_shared_edge +#define GL_NV_path_rendering_shared_edge 1 +#define GL_SHARED_EDGE_NV 0xC0 +#endif /* GL_NV_path_rendering_shared_edge */ + +#ifndef GL_NV_pixel_buffer_object +#define GL_NV_pixel_buffer_object 1 +#define GL_PIXEL_PACK_BUFFER_NV 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_NV 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_NV 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_NV 0x88EF +#endif /* GL_NV_pixel_buffer_object */ + +#ifndef GL_NV_polygon_mode +#define GL_NV_polygon_mode 1 +#define GL_POLYGON_MODE_NV 0x0B40 +#define GL_POLYGON_OFFSET_POINT_NV 0x2A01 +#define GL_POLYGON_OFFSET_LINE_NV 0x2A02 +#define GL_POINT_NV 0x1B00 +#define GL_LINE_NV 0x1B01 +#define GL_FILL_NV 0x1B02 +typedef void (GL_APIENTRYP PFNGLPOLYGONMODENVPROC) (GLenum face, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glPolygonModeNV (GLenum face, GLenum mode); +#endif +#endif /* GL_NV_polygon_mode */ + +#ifndef GL_NV_primitive_shading_rate +#define GL_NV_primitive_shading_rate 1 +#define GL_SHADING_RATE_IMAGE_PER_PRIMITIVE_NV 0x95B1 +#define GL_SHADING_RATE_IMAGE_PALETTE_COUNT_NV 0x95B2 +#endif /* GL_NV_primitive_shading_rate */ + +#ifndef GL_NV_read_buffer +#define GL_NV_read_buffer 1 +#define GL_READ_BUFFER_NV 0x0C02 +typedef void (GL_APIENTRYP PFNGLREADBUFFERNVPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glReadBufferNV (GLenum mode); +#endif +#endif /* GL_NV_read_buffer */ + +#ifndef GL_NV_read_buffer_front +#define GL_NV_read_buffer_front 1 +#endif /* GL_NV_read_buffer_front */ + +#ifndef GL_NV_read_depth +#define GL_NV_read_depth 1 +#endif /* GL_NV_read_depth */ + +#ifndef GL_NV_read_depth_stencil +#define GL_NV_read_depth_stencil 1 +#endif /* GL_NV_read_depth_stencil */ + +#ifndef GL_NV_read_stencil +#define GL_NV_read_stencil 1 +#endif /* GL_NV_read_stencil */ + +#ifndef GL_NV_representative_fragment_test +#define GL_NV_representative_fragment_test 1 +#define GL_REPRESENTATIVE_FRAGMENT_TEST_NV 0x937F +#endif /* GL_NV_representative_fragment_test */ + +#ifndef GL_NV_sRGB_formats +#define GL_NV_sRGB_formats 1 +#define GL_SLUMINANCE_NV 0x8C46 +#define GL_SLUMINANCE_ALPHA_NV 0x8C44 +#define GL_SRGB8_NV 0x8C41 +#define GL_SLUMINANCE8_NV 0x8C47 +#define GL_SLUMINANCE8_ALPHA8_NV 0x8C45 +#define GL_COMPRESSED_SRGB_S3TC_DXT1_NV 0x8C4C +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F +#define GL_ETC1_SRGB8_NV 0x88EE +#endif /* GL_NV_sRGB_formats */ + +#ifndef GL_NV_sample_locations +#define GL_NV_sample_locations 1 +#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV 0x933D +#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV 0x933E +#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV 0x933F +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV 0x9340 +#define GL_SAMPLE_LOCATION_NV 0x8E50 +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9341 +#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV 0x9342 +#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV 0x9343 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLRESOLVEDEPTHVALUESNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferSampleLocationsfvNV (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +GL_APICALL void GL_APIENTRY glNamedFramebufferSampleLocationsfvNV (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +GL_APICALL void GL_APIENTRY glResolveDepthValuesNV (void); +#endif +#endif /* GL_NV_sample_locations */ + +#ifndef GL_NV_sample_mask_override_coverage +#define GL_NV_sample_mask_override_coverage 1 +#endif /* GL_NV_sample_mask_override_coverage */ + +#ifndef GL_NV_scissor_exclusive +#define GL_NV_scissor_exclusive 1 +#define GL_SCISSOR_TEST_EXCLUSIVE_NV 0x9555 +#define GL_SCISSOR_BOX_EXCLUSIVE_NV 0x9556 +typedef void (GL_APIENTRYP PFNGLSCISSOREXCLUSIVENVPROC) (GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLSCISSOREXCLUSIVEARRAYVNVPROC) (GLuint first, GLsizei count, const GLint *v); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glScissorExclusiveNV (GLint x, GLint y, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glScissorExclusiveArrayvNV (GLuint first, GLsizei count, const GLint *v); +#endif +#endif /* GL_NV_scissor_exclusive */ + +#ifndef GL_NV_shader_atomic_fp16_vector +#define GL_NV_shader_atomic_fp16_vector 1 +#endif /* GL_NV_shader_atomic_fp16_vector */ + +#ifndef GL_NV_shader_noperspective_interpolation +#define GL_NV_shader_noperspective_interpolation 1 +#endif /* GL_NV_shader_noperspective_interpolation */ + +#ifndef GL_NV_shader_subgroup_partitioned +#define GL_NV_shader_subgroup_partitioned 1 +#define GL_SUBGROUP_FEATURE_PARTITIONED_BIT_NV 0x00000100 +#endif /* GL_NV_shader_subgroup_partitioned */ + +#ifndef GL_NV_shader_texture_footprint +#define GL_NV_shader_texture_footprint 1 +#endif /* GL_NV_shader_texture_footprint */ + +#ifndef GL_NV_shading_rate_image +#define GL_NV_shading_rate_image 1 +#define GL_SHADING_RATE_IMAGE_NV 0x9563 +#define GL_SHADING_RATE_NO_INVOCATIONS_NV 0x9564 +#define GL_SHADING_RATE_1_INVOCATION_PER_PIXEL_NV 0x9565 +#define GL_SHADING_RATE_1_INVOCATION_PER_1X2_PIXELS_NV 0x9566 +#define GL_SHADING_RATE_1_INVOCATION_PER_2X1_PIXELS_NV 0x9567 +#define GL_SHADING_RATE_1_INVOCATION_PER_2X2_PIXELS_NV 0x9568 +#define GL_SHADING_RATE_1_INVOCATION_PER_2X4_PIXELS_NV 0x9569 +#define GL_SHADING_RATE_1_INVOCATION_PER_4X2_PIXELS_NV 0x956A +#define GL_SHADING_RATE_1_INVOCATION_PER_4X4_PIXELS_NV 0x956B +#define GL_SHADING_RATE_2_INVOCATIONS_PER_PIXEL_NV 0x956C +#define GL_SHADING_RATE_4_INVOCATIONS_PER_PIXEL_NV 0x956D +#define GL_SHADING_RATE_8_INVOCATIONS_PER_PIXEL_NV 0x956E +#define GL_SHADING_RATE_16_INVOCATIONS_PER_PIXEL_NV 0x956F +#define GL_SHADING_RATE_IMAGE_BINDING_NV 0x955B +#define GL_SHADING_RATE_IMAGE_TEXEL_WIDTH_NV 0x955C +#define GL_SHADING_RATE_IMAGE_TEXEL_HEIGHT_NV 0x955D +#define GL_SHADING_RATE_IMAGE_PALETTE_SIZE_NV 0x955E +#define GL_MAX_COARSE_FRAGMENT_SAMPLES_NV 0x955F +#define GL_SHADING_RATE_SAMPLE_ORDER_DEFAULT_NV 0x95AE +#define GL_SHADING_RATE_SAMPLE_ORDER_PIXEL_MAJOR_NV 0x95AF +#define GL_SHADING_RATE_SAMPLE_ORDER_SAMPLE_MAJOR_NV 0x95B0 +typedef void (GL_APIENTRYP PFNGLBINDSHADINGRATEIMAGENVPROC) (GLuint texture); +typedef void (GL_APIENTRYP PFNGLGETSHADINGRATEIMAGEPALETTENVPROC) (GLuint viewport, GLuint entry, GLenum *rate); +typedef void (GL_APIENTRYP PFNGLGETSHADINGRATESAMPLELOCATIONIVNVPROC) (GLenum rate, GLuint samples, GLuint index, GLint *location); +typedef void (GL_APIENTRYP PFNGLSHADINGRATEIMAGEBARRIERNVPROC) (GLboolean synchronize); +typedef void (GL_APIENTRYP PFNGLSHADINGRATEIMAGEPALETTENVPROC) (GLuint viewport, GLuint first, GLsizei count, const GLenum *rates); +typedef void (GL_APIENTRYP PFNGLSHADINGRATESAMPLEORDERNVPROC) (GLenum order); +typedef void (GL_APIENTRYP PFNGLSHADINGRATESAMPLEORDERCUSTOMNVPROC) (GLenum rate, GLuint samples, const GLint *locations); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glBindShadingRateImageNV (GLuint texture); +GL_APICALL void GL_APIENTRY glGetShadingRateImagePaletteNV (GLuint viewport, GLuint entry, GLenum *rate); +GL_APICALL void GL_APIENTRY glGetShadingRateSampleLocationivNV (GLenum rate, GLuint samples, GLuint index, GLint *location); +GL_APICALL void GL_APIENTRY glShadingRateImageBarrierNV (GLboolean synchronize); +GL_APICALL void GL_APIENTRY glShadingRateImagePaletteNV (GLuint viewport, GLuint first, GLsizei count, const GLenum *rates); +GL_APICALL void GL_APIENTRY glShadingRateSampleOrderNV (GLenum order); +GL_APICALL void GL_APIENTRY glShadingRateSampleOrderCustomNV (GLenum rate, GLuint samples, const GLint *locations); +#endif +#endif /* GL_NV_shading_rate_image */ + +#ifndef GL_NV_shadow_samplers_array +#define GL_NV_shadow_samplers_array 1 +#define GL_SAMPLER_2D_ARRAY_SHADOW_NV 0x8DC4 +#endif /* GL_NV_shadow_samplers_array */ + +#ifndef GL_NV_shadow_samplers_cube +#define GL_NV_shadow_samplers_cube 1 +#define GL_SAMPLER_CUBE_SHADOW_NV 0x8DC5 +#endif /* GL_NV_shadow_samplers_cube */ + +#ifndef GL_NV_stereo_view_rendering +#define GL_NV_stereo_view_rendering 1 +#endif /* GL_NV_stereo_view_rendering */ + +#ifndef GL_NV_texture_border_clamp +#define GL_NV_texture_border_clamp 1 +#define GL_TEXTURE_BORDER_COLOR_NV 0x1004 +#define GL_CLAMP_TO_BORDER_NV 0x812D +#endif /* GL_NV_texture_border_clamp */ + +#ifndef GL_NV_texture_compression_s3tc_update +#define GL_NV_texture_compression_s3tc_update 1 +#endif /* GL_NV_texture_compression_s3tc_update */ + +#ifndef GL_NV_texture_npot_2D_mipmap +#define GL_NV_texture_npot_2D_mipmap 1 +#endif /* GL_NV_texture_npot_2D_mipmap */ + +#ifndef GL_NV_timeline_semaphore +#define GL_NV_timeline_semaphore 1 +#define GL_TIMELINE_SEMAPHORE_VALUE_NV 0x9595 +#define GL_SEMAPHORE_TYPE_NV 0x95B3 +#define GL_SEMAPHORE_TYPE_BINARY_NV 0x95B4 +#define GL_SEMAPHORE_TYPE_TIMELINE_NV 0x95B5 +#define GL_MAX_TIMELINE_SEMAPHORE_VALUE_DIFFERENCE_NV 0x95B6 +typedef void (GL_APIENTRYP PFNGLCREATESEMAPHORESNVPROC) (GLsizei n, GLuint *semaphores); +typedef void (GL_APIENTRYP PFNGLSEMAPHOREPARAMETERIVNVPROC) (GLuint semaphore, GLenum pname, const GLint *params); +typedef void (GL_APIENTRYP PFNGLGETSEMAPHOREPARAMETERIVNVPROC) (GLuint semaphore, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glCreateSemaphoresNV (GLsizei n, GLuint *semaphores); +GL_APICALL void GL_APIENTRY glSemaphoreParameterivNV (GLuint semaphore, GLenum pname, const GLint *params); +GL_APICALL void GL_APIENTRY glGetSemaphoreParameterivNV (GLuint semaphore, GLenum pname, GLint *params); +#endif +#endif /* GL_NV_timeline_semaphore */ + +#ifndef GL_NV_viewport_array +#define GL_NV_viewport_array 1 +#define GL_MAX_VIEWPORTS_NV 0x825B +#define GL_VIEWPORT_SUBPIXEL_BITS_NV 0x825C +#define GL_VIEWPORT_BOUNDS_RANGE_NV 0x825D +#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX_NV 0x825F +typedef void (GL_APIENTRYP PFNGLVIEWPORTARRAYVNVPROC) (GLuint first, GLsizei count, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFVNVPROC) (GLuint index, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLSCISSORARRAYVNVPROC) (GLuint first, GLsizei count, const GLint *v); +typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDNVPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDVNVPROC) (GLuint index, const GLint *v); +typedef void (GL_APIENTRYP PFNGLDEPTHRANGEARRAYFVNVPROC) (GLuint first, GLsizei count, const GLfloat *v); +typedef void (GL_APIENTRYP PFNGLDEPTHRANGEINDEXEDFNVPROC) (GLuint index, GLfloat n, GLfloat f); +typedef void (GL_APIENTRYP PFNGLGETFLOATI_VNVPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (GL_APIENTRYP PFNGLENABLEINVPROC) (GLenum target, GLuint index); +typedef void (GL_APIENTRYP PFNGLDISABLEINVPROC) (GLenum target, GLuint index); +typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDINVPROC) (GLenum target, GLuint index); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glViewportArrayvNV (GLuint first, GLsizei count, const GLfloat *v); +GL_APICALL void GL_APIENTRY glViewportIndexedfNV (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +GL_APICALL void GL_APIENTRY glViewportIndexedfvNV (GLuint index, const GLfloat *v); +GL_APICALL void GL_APIENTRY glScissorArrayvNV (GLuint first, GLsizei count, const GLint *v); +GL_APICALL void GL_APIENTRY glScissorIndexedNV (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +GL_APICALL void GL_APIENTRY glScissorIndexedvNV (GLuint index, const GLint *v); +GL_APICALL void GL_APIENTRY glDepthRangeArrayfvNV (GLuint first, GLsizei count, const GLfloat *v); +GL_APICALL void GL_APIENTRY glDepthRangeIndexedfNV (GLuint index, GLfloat n, GLfloat f); +GL_APICALL void GL_APIENTRY glGetFloati_vNV (GLenum target, GLuint index, GLfloat *data); +GL_APICALL void GL_APIENTRY glEnableiNV (GLenum target, GLuint index); +GL_APICALL void GL_APIENTRY glDisableiNV (GLenum target, GLuint index); +GL_APICALL GLboolean GL_APIENTRY glIsEnablediNV (GLenum target, GLuint index); +#endif +#endif /* GL_NV_viewport_array */ + +#ifndef GL_NV_viewport_array2 +#define GL_NV_viewport_array2 1 +#endif /* GL_NV_viewport_array2 */ + +#ifndef GL_NV_viewport_swizzle +#define GL_NV_viewport_swizzle 1 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_X_NV 0x9350 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_X_NV 0x9351 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_Y_NV 0x9352 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Y_NV 0x9353 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_Z_NV 0x9354 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Z_NV 0x9355 +#define GL_VIEWPORT_SWIZZLE_POSITIVE_W_NV 0x9356 +#define GL_VIEWPORT_SWIZZLE_NEGATIVE_W_NV 0x9357 +#define GL_VIEWPORT_SWIZZLE_X_NV 0x9358 +#define GL_VIEWPORT_SWIZZLE_Y_NV 0x9359 +#define GL_VIEWPORT_SWIZZLE_Z_NV 0x935A +#define GL_VIEWPORT_SWIZZLE_W_NV 0x935B +typedef void (GL_APIENTRYP PFNGLVIEWPORTSWIZZLENVPROC) (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glViewportSwizzleNV (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew); +#endif +#endif /* GL_NV_viewport_swizzle */ + +#ifndef GL_OVR_multiview +#define GL_OVR_multiview 1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR 0x9630 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR 0x9632 +#define GL_MAX_VIEWS_OVR 0x9631 +#define GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR 0x9633 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferTextureMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); +#endif +#endif /* GL_OVR_multiview */ + +#ifndef GL_OVR_multiview2 +#define GL_OVR_multiview2 1 +#endif /* GL_OVR_multiview2 */ + +#ifndef GL_OVR_multiview_multisampled_render_to_texture +#define GL_OVR_multiview_multisampled_render_to_texture 1 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTISAMPLEMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLsizei samples, GLint baseViewIndex, GLsizei numViews); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferTextureMultisampleMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLsizei samples, GLint baseViewIndex, GLsizei numViews); +#endif +#endif /* GL_OVR_multiview_multisampled_render_to_texture */ + +#ifndef GL_QCOM_YUV_texture_gather +#define GL_QCOM_YUV_texture_gather 1 +#endif /* GL_QCOM_YUV_texture_gather */ + +#ifndef GL_QCOM_alpha_test +#define GL_QCOM_alpha_test 1 +#define GL_ALPHA_TEST_QCOM 0x0BC0 +#define GL_ALPHA_TEST_FUNC_QCOM 0x0BC1 +#define GL_ALPHA_TEST_REF_QCOM 0x0BC2 +typedef void (GL_APIENTRYP PFNGLALPHAFUNCQCOMPROC) (GLenum func, GLclampf ref); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glAlphaFuncQCOM (GLenum func, GLclampf ref); +#endif +#endif /* GL_QCOM_alpha_test */ + +#ifndef GL_QCOM_binning_control +#define GL_QCOM_binning_control 1 +#define GL_BINNING_CONTROL_HINT_QCOM 0x8FB0 +#define GL_CPU_OPTIMIZED_QCOM 0x8FB1 +#define GL_GPU_OPTIMIZED_QCOM 0x8FB2 +#define GL_RENDER_DIRECT_TO_FRAMEBUFFER_QCOM 0x8FB3 +#endif /* GL_QCOM_binning_control */ + +#ifndef GL_QCOM_driver_control +#define GL_QCOM_driver_control 1 +typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSQCOMPROC) (GLint *num, GLsizei size, GLuint *driverControls); +typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSTRINGQCOMPROC) (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString); +typedef void (GL_APIENTRYP PFNGLENABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl); +typedef void (GL_APIENTRYP PFNGLDISABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glGetDriverControlsQCOM (GLint *num, GLsizei size, GLuint *driverControls); +GL_APICALL void GL_APIENTRY glGetDriverControlStringQCOM (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString); +GL_APICALL void GL_APIENTRY glEnableDriverControlQCOM (GLuint driverControl); +GL_APICALL void GL_APIENTRY glDisableDriverControlQCOM (GLuint driverControl); +#endif +#endif /* GL_QCOM_driver_control */ + +#ifndef GL_QCOM_extended_get +#define GL_QCOM_extended_get 1 +#define GL_TEXTURE_WIDTH_QCOM 0x8BD2 +#define GL_TEXTURE_HEIGHT_QCOM 0x8BD3 +#define GL_TEXTURE_DEPTH_QCOM 0x8BD4 +#define GL_TEXTURE_INTERNAL_FORMAT_QCOM 0x8BD5 +#define GL_TEXTURE_FORMAT_QCOM 0x8BD6 +#define GL_TEXTURE_TYPE_QCOM 0x8BD7 +#define GL_TEXTURE_IMAGE_VALID_QCOM 0x8BD8 +#define GL_TEXTURE_NUM_LEVELS_QCOM 0x8BD9 +#define GL_TEXTURE_TARGET_QCOM 0x8BDA +#define GL_TEXTURE_OBJECT_VALID_QCOM 0x8BDB +#define GL_STATE_RESTORE 0x8BDC +typedef void (GL_APIENTRYP PFNGLEXTGETTEXTURESQCOMPROC) (GLuint *textures, GLint maxTextures, GLint *numTextures); +typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERSQCOMPROC) (GLuint *buffers, GLint maxBuffers, GLint *numBuffers); +typedef void (GL_APIENTRYP PFNGLEXTGETRENDERBUFFERSQCOMPROC) (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers); +typedef void (GL_APIENTRYP PFNGLEXTGETFRAMEBUFFERSQCOMPROC) (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers); +typedef void (GL_APIENTRYP PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC) (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params); +typedef void (GL_APIENTRYP PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC) (GLenum target, GLenum pname, GLint param); +typedef void (GL_APIENTRYP PFNGLEXTGETTEXSUBIMAGEQCOMPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, void *texels); +typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERPOINTERVQCOMPROC) (GLenum target, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glExtGetTexturesQCOM (GLuint *textures, GLint maxTextures, GLint *numTextures); +GL_APICALL void GL_APIENTRY glExtGetBuffersQCOM (GLuint *buffers, GLint maxBuffers, GLint *numBuffers); +GL_APICALL void GL_APIENTRY glExtGetRenderbuffersQCOM (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers); +GL_APICALL void GL_APIENTRY glExtGetFramebuffersQCOM (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers); +GL_APICALL void GL_APIENTRY glExtGetTexLevelParameterivQCOM (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params); +GL_APICALL void GL_APIENTRY glExtTexObjectStateOverrideiQCOM (GLenum target, GLenum pname, GLint param); +GL_APICALL void GL_APIENTRY glExtGetTexSubImageQCOM (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, void *texels); +GL_APICALL void GL_APIENTRY glExtGetBufferPointervQCOM (GLenum target, void **params); +#endif +#endif /* GL_QCOM_extended_get */ + +#ifndef GL_QCOM_extended_get2 +#define GL_QCOM_extended_get2 1 +typedef void (GL_APIENTRYP PFNGLEXTGETSHADERSQCOMPROC) (GLuint *shaders, GLint maxShaders, GLint *numShaders); +typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMSQCOMPROC) (GLuint *programs, GLint maxPrograms, GLint *numPrograms); +typedef GLboolean (GL_APIENTRYP PFNGLEXTISPROGRAMBINARYQCOMPROC) (GLuint program); +typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC) (GLuint program, GLenum shadertype, GLchar *source, GLint *length); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glExtGetShadersQCOM (GLuint *shaders, GLint maxShaders, GLint *numShaders); +GL_APICALL void GL_APIENTRY glExtGetProgramsQCOM (GLuint *programs, GLint maxPrograms, GLint *numPrograms); +GL_APICALL GLboolean GL_APIENTRY glExtIsProgramBinaryQCOM (GLuint program); +GL_APICALL void GL_APIENTRY glExtGetProgramBinarySourceQCOM (GLuint program, GLenum shadertype, GLchar *source, GLint *length); +#endif +#endif /* GL_QCOM_extended_get2 */ + +#ifndef GL_QCOM_frame_extrapolation +#define GL_QCOM_frame_extrapolation 1 +typedef void (GL_APIENTRYP PFNGLEXTRAPOLATETEX2DQCOMPROC) (GLuint src1, GLuint src2, GLuint output, GLfloat scaleFactor); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glExtrapolateTex2DQCOM (GLuint src1, GLuint src2, GLuint output, GLfloat scaleFactor); +#endif +#endif /* GL_QCOM_frame_extrapolation */ + +#ifndef GL_QCOM_framebuffer_foveated +#define GL_QCOM_framebuffer_foveated 1 +#define GL_FOVEATION_ENABLE_BIT_QCOM 0x00000001 +#define GL_FOVEATION_SCALED_BIN_METHOD_BIT_QCOM 0x00000002 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERFOVEATIONCONFIGQCOMPROC) (GLuint framebuffer, GLuint numLayers, GLuint focalPointsPerLayer, GLuint requestedFeatures, GLuint *providedFeatures); +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERFOVEATIONPARAMETERSQCOMPROC) (GLuint framebuffer, GLuint layer, GLuint focalPoint, GLfloat focalX, GLfloat focalY, GLfloat gainX, GLfloat gainY, GLfloat foveaArea); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferFoveationConfigQCOM (GLuint framebuffer, GLuint numLayers, GLuint focalPointsPerLayer, GLuint requestedFeatures, GLuint *providedFeatures); +GL_APICALL void GL_APIENTRY glFramebufferFoveationParametersQCOM (GLuint framebuffer, GLuint layer, GLuint focalPoint, GLfloat focalX, GLfloat focalY, GLfloat gainX, GLfloat gainY, GLfloat foveaArea); +#endif +#endif /* GL_QCOM_framebuffer_foveated */ + +#ifndef GL_QCOM_motion_estimation +#define GL_QCOM_motion_estimation 1 +#define GL_MOTION_ESTIMATION_SEARCH_BLOCK_X_QCOM 0x8C90 +#define GL_MOTION_ESTIMATION_SEARCH_BLOCK_Y_QCOM 0x8C91 +typedef void (GL_APIENTRYP PFNGLTEXESTIMATEMOTIONQCOMPROC) (GLuint ref, GLuint target, GLuint output); +typedef void (GL_APIENTRYP PFNGLTEXESTIMATEMOTIONREGIONSQCOMPROC) (GLuint ref, GLuint target, GLuint output, GLuint mask); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTexEstimateMotionQCOM (GLuint ref, GLuint target, GLuint output); +GL_APICALL void GL_APIENTRY glTexEstimateMotionRegionsQCOM (GLuint ref, GLuint target, GLuint output, GLuint mask); +#endif +#endif /* GL_QCOM_motion_estimation */ + +#ifndef GL_QCOM_perfmon_global_mode +#define GL_QCOM_perfmon_global_mode 1 +#define GL_PERFMON_GLOBAL_MODE_QCOM 0x8FA0 +#endif /* GL_QCOM_perfmon_global_mode */ + +#ifndef GL_QCOM_render_shared_exponent +#define GL_QCOM_render_shared_exponent 1 +#endif /* GL_QCOM_render_shared_exponent */ + +#ifndef GL_QCOM_shader_framebuffer_fetch_noncoherent +#define GL_QCOM_shader_framebuffer_fetch_noncoherent 1 +#define GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM 0x96A2 +typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERFETCHBARRIERQCOMPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glFramebufferFetchBarrierQCOM (void); +#endif +#endif /* GL_QCOM_shader_framebuffer_fetch_noncoherent */ + +#ifndef GL_QCOM_shader_framebuffer_fetch_rate +#define GL_QCOM_shader_framebuffer_fetch_rate 1 +#endif /* GL_QCOM_shader_framebuffer_fetch_rate */ + +#ifndef GL_QCOM_shading_rate +#define GL_QCOM_shading_rate 1 +#define GL_SHADING_RATE_QCOM 0x96A4 +#define GL_SHADING_RATE_PRESERVE_ASPECT_RATIO_QCOM 0x96A5 +#define GL_SHADING_RATE_1X1_PIXELS_QCOM 0x96A6 +#define GL_SHADING_RATE_1X2_PIXELS_QCOM 0x96A7 +#define GL_SHADING_RATE_2X1_PIXELS_QCOM 0x96A8 +#define GL_SHADING_RATE_2X2_PIXELS_QCOM 0x96A9 +#define GL_SHADING_RATE_4X2_PIXELS_QCOM 0x96AC +#define GL_SHADING_RATE_4X4_PIXELS_QCOM 0x96AE +typedef void (GL_APIENTRYP PFNGLSHADINGRATEQCOMPROC) (GLenum rate); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glShadingRateQCOM (GLenum rate); +#endif +#endif /* GL_QCOM_shading_rate */ + +#ifndef GL_QCOM_texture_foveated +#define GL_QCOM_texture_foveated 1 +#define GL_TEXTURE_FOVEATED_FEATURE_BITS_QCOM 0x8BFB +#define GL_TEXTURE_FOVEATED_MIN_PIXEL_DENSITY_QCOM 0x8BFC +#define GL_TEXTURE_FOVEATED_FEATURE_QUERY_QCOM 0x8BFD +#define GL_TEXTURE_FOVEATED_NUM_FOCAL_POINTS_QUERY_QCOM 0x8BFE +#define GL_FRAMEBUFFER_INCOMPLETE_FOVEATION_QCOM 0x8BFF +typedef void (GL_APIENTRYP PFNGLTEXTUREFOVEATIONPARAMETERSQCOMPROC) (GLuint texture, GLuint layer, GLuint focalPoint, GLfloat focalX, GLfloat focalY, GLfloat gainX, GLfloat gainY, GLfloat foveaArea); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glTextureFoveationParametersQCOM (GLuint texture, GLuint layer, GLuint focalPoint, GLfloat focalX, GLfloat focalY, GLfloat gainX, GLfloat gainY, GLfloat foveaArea); +#endif +#endif /* GL_QCOM_texture_foveated */ + +#ifndef GL_QCOM_texture_foveated2 +#define GL_QCOM_texture_foveated2 1 +#define GL_TEXTURE_FOVEATED_CUTOFF_DENSITY_QCOM 0x96A0 +#endif /* GL_QCOM_texture_foveated2 */ + +#ifndef GL_QCOM_texture_foveated_subsampled_layout +#define GL_QCOM_texture_foveated_subsampled_layout 1 +#define GL_FOVEATION_SUBSAMPLED_LAYOUT_METHOD_BIT_QCOM 0x00000004 +#define GL_MAX_SHADER_SUBSAMPLED_IMAGE_UNITS_QCOM 0x8FA1 +#endif /* GL_QCOM_texture_foveated_subsampled_layout */ + +#ifndef GL_QCOM_tiled_rendering +#define GL_QCOM_tiled_rendering 1 +#define GL_COLOR_BUFFER_BIT0_QCOM 0x00000001 +#define GL_COLOR_BUFFER_BIT1_QCOM 0x00000002 +#define GL_COLOR_BUFFER_BIT2_QCOM 0x00000004 +#define GL_COLOR_BUFFER_BIT3_QCOM 0x00000008 +#define GL_COLOR_BUFFER_BIT4_QCOM 0x00000010 +#define GL_COLOR_BUFFER_BIT5_QCOM 0x00000020 +#define GL_COLOR_BUFFER_BIT6_QCOM 0x00000040 +#define GL_COLOR_BUFFER_BIT7_QCOM 0x00000080 +#define GL_DEPTH_BUFFER_BIT0_QCOM 0x00000100 +#define GL_DEPTH_BUFFER_BIT1_QCOM 0x00000200 +#define GL_DEPTH_BUFFER_BIT2_QCOM 0x00000400 +#define GL_DEPTH_BUFFER_BIT3_QCOM 0x00000800 +#define GL_DEPTH_BUFFER_BIT4_QCOM 0x00001000 +#define GL_DEPTH_BUFFER_BIT5_QCOM 0x00002000 +#define GL_DEPTH_BUFFER_BIT6_QCOM 0x00004000 +#define GL_DEPTH_BUFFER_BIT7_QCOM 0x00008000 +#define GL_STENCIL_BUFFER_BIT0_QCOM 0x00010000 +#define GL_STENCIL_BUFFER_BIT1_QCOM 0x00020000 +#define GL_STENCIL_BUFFER_BIT2_QCOM 0x00040000 +#define GL_STENCIL_BUFFER_BIT3_QCOM 0x00080000 +#define GL_STENCIL_BUFFER_BIT4_QCOM 0x00100000 +#define GL_STENCIL_BUFFER_BIT5_QCOM 0x00200000 +#define GL_STENCIL_BUFFER_BIT6_QCOM 0x00400000 +#define GL_STENCIL_BUFFER_BIT7_QCOM 0x00800000 +#define GL_MULTISAMPLE_BUFFER_BIT0_QCOM 0x01000000 +#define GL_MULTISAMPLE_BUFFER_BIT1_QCOM 0x02000000 +#define GL_MULTISAMPLE_BUFFER_BIT2_QCOM 0x04000000 +#define GL_MULTISAMPLE_BUFFER_BIT3_QCOM 0x08000000 +#define GL_MULTISAMPLE_BUFFER_BIT4_QCOM 0x10000000 +#define GL_MULTISAMPLE_BUFFER_BIT5_QCOM 0x20000000 +#define GL_MULTISAMPLE_BUFFER_BIT6_QCOM 0x40000000 +#define GL_MULTISAMPLE_BUFFER_BIT7_QCOM 0x80000000 +typedef void (GL_APIENTRYP PFNGLSTARTTILINGQCOMPROC) (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask); +typedef void (GL_APIENTRYP PFNGLENDTILINGQCOMPROC) (GLbitfield preserveMask); +#ifdef GL_GLEXT_PROTOTYPES +GL_APICALL void GL_APIENTRY glStartTilingQCOM (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask); +GL_APICALL void GL_APIENTRY glEndTilingQCOM (GLbitfield preserveMask); +#endif +#endif /* GL_QCOM_tiled_rendering */ + +#ifndef GL_QCOM_writeonly_rendering +#define GL_QCOM_writeonly_rendering 1 +#define GL_WRITEONLY_RENDERING_QCOM 0x8823 +#endif /* GL_QCOM_writeonly_rendering */ + +#ifndef GL_VIV_shader_binary +#define GL_VIV_shader_binary 1 +#define GL_SHADER_BINARY_VIV 0x8FC4 +#endif /* GL_VIV_shader_binary */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/third_party/SDL2/include/SDL_opengles2_gl2platform.h b/third_party/SDL2/include/SDL_opengles2_gl2platform.h new file mode 100644 index 00000000000..426796ef2a7 --- /dev/null +++ b/third_party/SDL2/include/SDL_opengles2_gl2platform.h @@ -0,0 +1,27 @@ +#ifndef __gl2platform_h_ +#define __gl2platform_h_ + +/* +** Copyright 2017-2020 The Khronos Group Inc. +** SPDX-License-Identifier: Apache-2.0 +*/ + +/* Platform-specific types and definitions for OpenGL ES 2.X gl2.h + * + * Adopters may modify khrplatform.h and this file to suit their platform. + * Please contribute modifications back to Khronos as pull requests on the + * public github repository: + * https://github.com/KhronosGroup/OpenGL-Registry + */ + +/*#include */ + +#ifndef GL_APICALL +#define GL_APICALL KHRONOS_APICALL +#endif + +#ifndef GL_APIENTRY +#define GL_APIENTRY KHRONOS_APIENTRY +#endif + +#endif /* __gl2platform_h_ */ diff --git a/third_party/SDL2/include/SDL_opengles2_khrplatform.h b/third_party/SDL2/include/SDL_opengles2_khrplatform.h new file mode 100644 index 00000000000..01646449cae --- /dev/null +++ b/third_party/SDL2/include/SDL_opengles2_khrplatform.h @@ -0,0 +1,311 @@ +#ifndef __khrplatform_h_ +#define __khrplatform_h_ + +/* +** Copyright (c) 2008-2018 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ + +/* Khronos platform-specific types and definitions. + * + * The master copy of khrplatform.h is maintained in the Khronos EGL + * Registry repository at https://github.com/KhronosGroup/EGL-Registry + * The last semantic modification to khrplatform.h was at commit ID: + * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 + * + * Adopters may modify this file to suit their platform. Adopters are + * encouraged to submit platform specific modifications to the Khronos + * group so that they can be included in future versions of this file. + * Please submit changes by filing pull requests or issues on + * the EGL Registry repository linked above. + * + * + * See the Implementer's Guidelines for information about where this file + * should be located on your system and for more details of its use: + * http://www.khronos.org/registry/implementers_guide.pdf + * + * This file should be included as + * #include + * by Khronos client API header files that use its types and defines. + * + * The types in khrplatform.h should only be used to define API-specific types. + * + * Types defined in khrplatform.h: + * khronos_int8_t signed 8 bit + * khronos_uint8_t unsigned 8 bit + * khronos_int16_t signed 16 bit + * khronos_uint16_t unsigned 16 bit + * khronos_int32_t signed 32 bit + * khronos_uint32_t unsigned 32 bit + * khronos_int64_t signed 64 bit + * khronos_uint64_t unsigned 64 bit + * khronos_intptr_t signed same number of bits as a pointer + * khronos_uintptr_t unsigned same number of bits as a pointer + * khronos_ssize_t signed size + * khronos_usize_t unsigned size + * khronos_float_t signed 32 bit floating point + * khronos_time_ns_t unsigned 64 bit time in nanoseconds + * khronos_utime_nanoseconds_t unsigned time interval or absolute time in + * nanoseconds + * khronos_stime_nanoseconds_t signed time interval in nanoseconds + * khronos_boolean_enum_t enumerated boolean type. This should + * only be used as a base type when a client API's boolean type is + * an enum. Client APIs which use an integer or other type for + * booleans cannot use this as the base type for their boolean. + * + * Tokens defined in khrplatform.h: + * + * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. + * + * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. + * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. + * + * Calling convention macros defined in this file: + * KHRONOS_APICALL + * KHRONOS_APIENTRY + * KHRONOS_APIATTRIBUTES + * + * These may be used in function prototypes as: + * + * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( + * int arg1, + * int arg2) KHRONOS_APIATTRIBUTES; + */ + +#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) +# define KHRONOS_STATIC 1 +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APICALL + *------------------------------------------------------------------------- + * This precedes the return type of the function in the function prototype. + */ +#if defined(KHRONOS_STATIC) + /* If the preprocessor constant KHRONOS_STATIC is defined, make the + * header compatible with static linking. */ +# define KHRONOS_APICALL +#elif defined(_WIN32) +# define KHRONOS_APICALL __declspec(dllimport) +#elif defined (__SYMBIAN32__) +# define KHRONOS_APICALL IMPORT_C +#elif defined(__ANDROID__) +# define KHRONOS_APICALL __attribute__((visibility("default"))) +#else +# define KHRONOS_APICALL +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIENTRY + *------------------------------------------------------------------------- + * This follows the return type of the function and precedes the function + * name in the function prototype. + */ +#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) + /* Win32 but not WinCE */ +# define KHRONOS_APIENTRY __stdcall +#else +# define KHRONOS_APIENTRY +#endif + +/*------------------------------------------------------------------------- + * Definition of KHRONOS_APIATTRIBUTES + *------------------------------------------------------------------------- + * This follows the closing parenthesis of the function prototype arguments. + */ +#if defined (__ARMCC_2__) +#define KHRONOS_APIATTRIBUTES __softfp +#else +#define KHRONOS_APIATTRIBUTES +#endif + +/*------------------------------------------------------------------------- + * basic type definitions + *-----------------------------------------------------------------------*/ +#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) + + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 +/* + * To support platform where unsigned long cannot be used interchangeably with + * inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t. + * Ideally, we could just use (u)intptr_t everywhere, but this could result in + * ABI breakage if khronos_uintptr_t is changed from unsigned long to + * unsigned long long or similar (this results in different C++ name mangling). + * To avoid changes for existing platforms, we restrict usage of intptr_t to + * platforms where the size of a pointer is larger than the size of long. + */ +#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__) +#if __SIZEOF_POINTER__ > __SIZEOF_LONG__ +#define KHRONOS_USE_INTPTR_T +#endif +#endif + +#elif defined(__VMS ) || defined(__sgi) + +/* + * Using + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) + +/* + * Win32 + */ +typedef __int32 khronos_int32_t; +typedef unsigned __int32 khronos_uint32_t; +typedef __int64 khronos_int64_t; +typedef unsigned __int64 khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif defined(__sun__) || defined(__digital__) + +/* + * Sun or Digital + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#if defined(__arch64__) || defined(_LP64) +typedef long int khronos_int64_t; +typedef unsigned long int khronos_uint64_t; +#else +typedef long long int khronos_int64_t; +typedef unsigned long long int khronos_uint64_t; +#endif /* __arch64__ */ +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#elif 0 + +/* + * Hypothetical platform with no float or int64 support + */ +typedef int khronos_int32_t; +typedef unsigned int khronos_uint32_t; +#define KHRONOS_SUPPORT_INT64 0 +#define KHRONOS_SUPPORT_FLOAT 0 + +#else + +/* + * Generic fallback + */ +#include +typedef int32_t khronos_int32_t; +typedef uint32_t khronos_uint32_t; +typedef int64_t khronos_int64_t; +typedef uint64_t khronos_uint64_t; +#define KHRONOS_SUPPORT_INT64 1 +#define KHRONOS_SUPPORT_FLOAT 1 + +#endif + + +/* + * Types that are (so far) the same on all platforms + */ +typedef signed char khronos_int8_t; +typedef unsigned char khronos_uint8_t; +typedef signed short int khronos_int16_t; +typedef unsigned short int khronos_uint16_t; + +/* + * Types that differ between LLP64 and LP64 architectures - in LLP64, + * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears + * to be the only LLP64 architecture in current use. + */ +#ifdef KHRONOS_USE_INTPTR_T +typedef intptr_t khronos_intptr_t; +typedef uintptr_t khronos_uintptr_t; +#elif defined(_WIN64) +typedef signed long long int khronos_intptr_t; +typedef unsigned long long int khronos_uintptr_t; +#else +typedef signed long int khronos_intptr_t; +typedef unsigned long int khronos_uintptr_t; +#endif + +#if defined(_WIN64) +typedef signed long long int khronos_ssize_t; +typedef unsigned long long int khronos_usize_t; +#else +typedef signed long int khronos_ssize_t; +typedef unsigned long int khronos_usize_t; +#endif + +#if KHRONOS_SUPPORT_FLOAT +/* + * Float type + */ +typedef float khronos_float_t; +#endif + +#if KHRONOS_SUPPORT_INT64 +/* Time types + * + * These types can be used to represent a time interval in nanoseconds or + * an absolute Unadjusted System Time. Unadjusted System Time is the number + * of nanoseconds since some arbitrary system event (e.g. since the last + * time the system booted). The Unadjusted System Time is an unsigned + * 64 bit value that wraps back to 0 every 584 years. Time intervals + * may be either signed or unsigned. + */ +typedef khronos_uint64_t khronos_utime_nanoseconds_t; +typedef khronos_int64_t khronos_stime_nanoseconds_t; +#endif + +/* + * Dummy value used to pad enum types to 32 bits. + */ +#ifndef KHRONOS_MAX_ENUM +#define KHRONOS_MAX_ENUM 0x7FFFFFFF +#endif + +/* + * Enumerated boolean type + * + * Values other than zero should be considered to be true. Therefore + * comparisons should not be made against KHRONOS_TRUE. + */ +typedef enum { + KHRONOS_FALSE = 0, + KHRONOS_TRUE = 1, + KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM +} khronos_boolean_enum_t; + +#endif /* __khrplatform_h_ */ diff --git a/third_party/SDL2/include/SDL_pixels.h b/third_party/SDL2/include/SDL_pixels.h new file mode 100644 index 00000000000..6f29811d337 --- /dev/null +++ b/third_party/SDL2/include/SDL_pixels.h @@ -0,0 +1,686 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryPixels + * + * Header for the enumerated pixel format definitions. + */ + +#ifndef SDL_pixels_h_ +#define SDL_pixels_h_ + +#include "SDL_stdinc.h" +#include "SDL_endian.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \name Transparency definitions + * + * These define alpha as the opacity of a surface. + */ +/* @{ */ +#define SDL_ALPHA_OPAQUE 255 +#define SDL_ALPHA_TRANSPARENT 0 +/* @} */ + +/** Pixel type. */ +typedef enum +{ + SDL_PIXELTYPE_UNKNOWN, + SDL_PIXELTYPE_INDEX1, + SDL_PIXELTYPE_INDEX4, + SDL_PIXELTYPE_INDEX8, + SDL_PIXELTYPE_PACKED8, + SDL_PIXELTYPE_PACKED16, + SDL_PIXELTYPE_PACKED32, + SDL_PIXELTYPE_ARRAYU8, + SDL_PIXELTYPE_ARRAYU16, + SDL_PIXELTYPE_ARRAYU32, + SDL_PIXELTYPE_ARRAYF16, + SDL_PIXELTYPE_ARRAYF32, + + /* This must be at the end of the list to avoid breaking the existing ABI */ + SDL_PIXELTYPE_INDEX2 +} SDL_PixelType; + +/** Bitmap pixel order, high bit -> low bit. */ +typedef enum +{ + SDL_BITMAPORDER_NONE, + SDL_BITMAPORDER_4321, + SDL_BITMAPORDER_1234 +} SDL_BitmapOrder; + +/** Packed component order, high bit -> low bit. */ +typedef enum +{ + SDL_PACKEDORDER_NONE, + SDL_PACKEDORDER_XRGB, + SDL_PACKEDORDER_RGBX, + SDL_PACKEDORDER_ARGB, + SDL_PACKEDORDER_RGBA, + SDL_PACKEDORDER_XBGR, + SDL_PACKEDORDER_BGRX, + SDL_PACKEDORDER_ABGR, + SDL_PACKEDORDER_BGRA +} SDL_PackedOrder; + +/** Array component order, low byte -> high byte. */ +/* !!! FIXME: in 2.1, make these not overlap differently with + !!! FIXME: SDL_PACKEDORDER_*, so we can simplify SDL_ISPIXELFORMAT_ALPHA */ +typedef enum +{ + SDL_ARRAYORDER_NONE, + SDL_ARRAYORDER_RGB, + SDL_ARRAYORDER_RGBA, + SDL_ARRAYORDER_ARGB, + SDL_ARRAYORDER_BGR, + SDL_ARRAYORDER_BGRA, + SDL_ARRAYORDER_ABGR +} SDL_ArrayOrder; + +/** Packed component layout. */ +typedef enum +{ + SDL_PACKEDLAYOUT_NONE, + SDL_PACKEDLAYOUT_332, + SDL_PACKEDLAYOUT_4444, + SDL_PACKEDLAYOUT_1555, + SDL_PACKEDLAYOUT_5551, + SDL_PACKEDLAYOUT_565, + SDL_PACKEDLAYOUT_8888, + SDL_PACKEDLAYOUT_2101010, + SDL_PACKEDLAYOUT_1010102 +} SDL_PackedLayout; + +#define SDL_DEFINE_PIXELFOURCC(A, B, C, D) SDL_FOURCC(A, B, C, D) + +#define SDL_DEFINE_PIXELFORMAT(type, order, layout, bits, bytes) \ + ((1 << 28) | ((type) << 24) | ((order) << 20) | ((layout) << 16) | \ + ((bits) << 8) | ((bytes) << 0)) + +#define SDL_PIXELFLAG(X) (((X) >> 28) & 0x0F) +#define SDL_PIXELTYPE(X) (((X) >> 24) & 0x0F) +#define SDL_PIXELORDER(X) (((X) >> 20) & 0x0F) +#define SDL_PIXELLAYOUT(X) (((X) >> 16) & 0x0F) +#define SDL_BITSPERPIXEL(X) (((X) >> 8) & 0xFF) +#define SDL_BYTESPERPIXEL(X) \ + (SDL_ISPIXELFORMAT_FOURCC(X) ? \ + ((((X) == SDL_PIXELFORMAT_YUY2) || \ + ((X) == SDL_PIXELFORMAT_UYVY) || \ + ((X) == SDL_PIXELFORMAT_YVYU)) ? 2 : 1) : (((X) >> 0) & 0xFF)) + +#define SDL_ISPIXELFORMAT_INDEXED(format) \ + (!SDL_ISPIXELFORMAT_FOURCC(format) && \ + ((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX1) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX2) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX4) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX8))) + +#define SDL_ISPIXELFORMAT_PACKED(format) \ + (!SDL_ISPIXELFORMAT_FOURCC(format) && \ + ((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED8) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED16) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32))) + +#define SDL_ISPIXELFORMAT_ARRAY(format) \ + (!SDL_ISPIXELFORMAT_FOURCC(format) && \ + ((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU8) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU16) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU32) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16) || \ + (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32))) + +#define SDL_ISPIXELFORMAT_ALPHA(format) \ + ((SDL_ISPIXELFORMAT_PACKED(format) && \ + ((SDL_PIXELORDER(format) == SDL_PACKEDORDER_ARGB) || \ + (SDL_PIXELORDER(format) == SDL_PACKEDORDER_RGBA) || \ + (SDL_PIXELORDER(format) == SDL_PACKEDORDER_ABGR) || \ + (SDL_PIXELORDER(format) == SDL_PACKEDORDER_BGRA))) || \ + (SDL_ISPIXELFORMAT_ARRAY(format) && \ + ((SDL_PIXELORDER(format) == SDL_ARRAYORDER_ARGB) || \ + (SDL_PIXELORDER(format) == SDL_ARRAYORDER_RGBA) || \ + (SDL_PIXELORDER(format) == SDL_ARRAYORDER_ABGR) || \ + (SDL_PIXELORDER(format) == SDL_ARRAYORDER_BGRA)))) + +/* The flag is set to 1 because 0x1? is not in the printable ASCII range */ +#define SDL_ISPIXELFORMAT_FOURCC(format) \ + ((format) && (SDL_PIXELFLAG(format) != 1)) + +/* Note: If you modify this list, update SDL_GetPixelFormatName() */ +typedef enum +{ + SDL_PIXELFORMAT_UNKNOWN, + SDL_PIXELFORMAT_INDEX1LSB = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX1, SDL_BITMAPORDER_4321, 0, + 1, 0), + SDL_PIXELFORMAT_INDEX1MSB = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX1, SDL_BITMAPORDER_1234, 0, + 1, 0), + SDL_PIXELFORMAT_INDEX2LSB = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX2, SDL_BITMAPORDER_4321, 0, + 2, 0), + SDL_PIXELFORMAT_INDEX2MSB = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX2, SDL_BITMAPORDER_1234, 0, + 2, 0), + SDL_PIXELFORMAT_INDEX4LSB = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX4, SDL_BITMAPORDER_4321, 0, + 4, 0), + SDL_PIXELFORMAT_INDEX4MSB = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX4, SDL_BITMAPORDER_1234, 0, + 4, 0), + SDL_PIXELFORMAT_INDEX8 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_INDEX8, 0, 0, 8, 1), + SDL_PIXELFORMAT_RGB332 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED8, SDL_PACKEDORDER_XRGB, + SDL_PACKEDLAYOUT_332, 8, 1), + SDL_PIXELFORMAT_XRGB4444 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XRGB, + SDL_PACKEDLAYOUT_4444, 12, 2), + SDL_PIXELFORMAT_RGB444 = SDL_PIXELFORMAT_XRGB4444, + SDL_PIXELFORMAT_XBGR4444 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XBGR, + SDL_PACKEDLAYOUT_4444, 12, 2), + SDL_PIXELFORMAT_BGR444 = SDL_PIXELFORMAT_XBGR4444, + SDL_PIXELFORMAT_XRGB1555 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XRGB, + SDL_PACKEDLAYOUT_1555, 15, 2), + SDL_PIXELFORMAT_RGB555 = SDL_PIXELFORMAT_XRGB1555, + SDL_PIXELFORMAT_XBGR1555 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XBGR, + SDL_PACKEDLAYOUT_1555, 15, 2), + SDL_PIXELFORMAT_BGR555 = SDL_PIXELFORMAT_XBGR1555, + SDL_PIXELFORMAT_ARGB4444 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_ARGB, + SDL_PACKEDLAYOUT_4444, 16, 2), + SDL_PIXELFORMAT_RGBA4444 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_RGBA, + SDL_PACKEDLAYOUT_4444, 16, 2), + SDL_PIXELFORMAT_ABGR4444 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_ABGR, + SDL_PACKEDLAYOUT_4444, 16, 2), + SDL_PIXELFORMAT_BGRA4444 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_BGRA, + SDL_PACKEDLAYOUT_4444, 16, 2), + SDL_PIXELFORMAT_ARGB1555 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_ARGB, + SDL_PACKEDLAYOUT_1555, 16, 2), + SDL_PIXELFORMAT_RGBA5551 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_RGBA, + SDL_PACKEDLAYOUT_5551, 16, 2), + SDL_PIXELFORMAT_ABGR1555 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_ABGR, + SDL_PACKEDLAYOUT_1555, 16, 2), + SDL_PIXELFORMAT_BGRA5551 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_BGRA, + SDL_PACKEDLAYOUT_5551, 16, 2), + SDL_PIXELFORMAT_RGB565 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XRGB, + SDL_PACKEDLAYOUT_565, 16, 2), + SDL_PIXELFORMAT_BGR565 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED16, SDL_PACKEDORDER_XBGR, + SDL_PACKEDLAYOUT_565, 16, 2), + SDL_PIXELFORMAT_RGB24 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU8, SDL_ARRAYORDER_RGB, 0, + 24, 3), + SDL_PIXELFORMAT_BGR24 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_ARRAYU8, SDL_ARRAYORDER_BGR, 0, + 24, 3), + SDL_PIXELFORMAT_XRGB8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_XRGB, + SDL_PACKEDLAYOUT_8888, 24, 4), + SDL_PIXELFORMAT_RGB888 = SDL_PIXELFORMAT_XRGB8888, + SDL_PIXELFORMAT_RGBX8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_RGBX, + SDL_PACKEDLAYOUT_8888, 24, 4), + SDL_PIXELFORMAT_XBGR8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_XBGR, + SDL_PACKEDLAYOUT_8888, 24, 4), + SDL_PIXELFORMAT_BGR888 = SDL_PIXELFORMAT_XBGR8888, + SDL_PIXELFORMAT_BGRX8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_BGRX, + SDL_PACKEDLAYOUT_8888, 24, 4), + SDL_PIXELFORMAT_ARGB8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ARGB, + SDL_PACKEDLAYOUT_8888, 32, 4), + SDL_PIXELFORMAT_RGBA8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_RGBA, + SDL_PACKEDLAYOUT_8888, 32, 4), + SDL_PIXELFORMAT_ABGR8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ABGR, + SDL_PACKEDLAYOUT_8888, 32, 4), + SDL_PIXELFORMAT_BGRA8888 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_BGRA, + SDL_PACKEDLAYOUT_8888, 32, 4), + SDL_PIXELFORMAT_ARGB2101010 = + SDL_DEFINE_PIXELFORMAT(SDL_PIXELTYPE_PACKED32, SDL_PACKEDORDER_ARGB, + SDL_PACKEDLAYOUT_2101010, 32, 4), + + /* Aliases for RGBA byte arrays of color data, for the current platform */ +#if SDL_BYTEORDER == SDL_BIG_ENDIAN + SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_RGBA8888, + SDL_PIXELFORMAT_ARGB32 = SDL_PIXELFORMAT_ARGB8888, + SDL_PIXELFORMAT_BGRA32 = SDL_PIXELFORMAT_BGRA8888, + SDL_PIXELFORMAT_ABGR32 = SDL_PIXELFORMAT_ABGR8888, + SDL_PIXELFORMAT_RGBX32 = SDL_PIXELFORMAT_RGBX8888, + SDL_PIXELFORMAT_XRGB32 = SDL_PIXELFORMAT_XRGB8888, + SDL_PIXELFORMAT_BGRX32 = SDL_PIXELFORMAT_BGRX8888, + SDL_PIXELFORMAT_XBGR32 = SDL_PIXELFORMAT_XBGR8888, +#else + SDL_PIXELFORMAT_RGBA32 = SDL_PIXELFORMAT_ABGR8888, + SDL_PIXELFORMAT_ARGB32 = SDL_PIXELFORMAT_BGRA8888, + SDL_PIXELFORMAT_BGRA32 = SDL_PIXELFORMAT_ARGB8888, + SDL_PIXELFORMAT_ABGR32 = SDL_PIXELFORMAT_RGBA8888, + SDL_PIXELFORMAT_RGBX32 = SDL_PIXELFORMAT_XBGR8888, + SDL_PIXELFORMAT_XRGB32 = SDL_PIXELFORMAT_BGRX8888, + SDL_PIXELFORMAT_BGRX32 = SDL_PIXELFORMAT_XRGB8888, + SDL_PIXELFORMAT_XBGR32 = SDL_PIXELFORMAT_RGBX8888, +#endif + + SDL_PIXELFORMAT_YV12 = /**< Planar mode: Y + V + U (3 planes) */ + SDL_DEFINE_PIXELFOURCC('Y', 'V', '1', '2'), + SDL_PIXELFORMAT_IYUV = /**< Planar mode: Y + U + V (3 planes) */ + SDL_DEFINE_PIXELFOURCC('I', 'Y', 'U', 'V'), + SDL_PIXELFORMAT_YUY2 = /**< Packed mode: Y0+U0+Y1+V0 (1 plane) */ + SDL_DEFINE_PIXELFOURCC('Y', 'U', 'Y', '2'), + SDL_PIXELFORMAT_UYVY = /**< Packed mode: U0+Y0+V0+Y1 (1 plane) */ + SDL_DEFINE_PIXELFOURCC('U', 'Y', 'V', 'Y'), + SDL_PIXELFORMAT_YVYU = /**< Packed mode: Y0+V0+Y1+U0 (1 plane) */ + SDL_DEFINE_PIXELFOURCC('Y', 'V', 'Y', 'U'), + SDL_PIXELFORMAT_NV12 = /**< Planar mode: Y + U/V interleaved (2 planes) */ + SDL_DEFINE_PIXELFOURCC('N', 'V', '1', '2'), + SDL_PIXELFORMAT_NV21 = /**< Planar mode: Y + V/U interleaved (2 planes) */ + SDL_DEFINE_PIXELFOURCC('N', 'V', '2', '1'), + SDL_PIXELFORMAT_EXTERNAL_OES = /**< Android video texture format */ + SDL_DEFINE_PIXELFOURCC('O', 'E', 'S', ' ') +} SDL_PixelFormatEnum; + +/** + * The bits of this structure can be directly reinterpreted as an + * integer-packed color which uses the SDL_PIXELFORMAT_RGBA32 format + * (SDL_PIXELFORMAT_ABGR8888 on little-endian systems and + * SDL_PIXELFORMAT_RGBA8888 on big-endian systems). + */ +typedef struct SDL_Color +{ + Uint8 r; + Uint8 g; + Uint8 b; + Uint8 a; +} SDL_Color; +#define SDL_Colour SDL_Color + +typedef struct SDL_Palette +{ + int ncolors; + SDL_Color *colors; + Uint32 version; + int refcount; +} SDL_Palette; + +/** + * A structure that contains pixel format information. + * + * Everything in the pixel format structure is read-only. + * + * A pixel format has either a palette or masks. If a palette is used `Rmask`, + * `Gmask`, `Bmask`, and `Amask` will be 0. + * + * An SDL_PixelFormat describes the format of the pixel data stored at the + * `pixels` field of an SDL_Surface. Every surface stores an SDL_PixelFormat + * in the `format` field. + * + * If you wish to do pixel level modifications on a surface, then + * understanding how SDL stores its color information is essential. + * + * For information on modern pixel color spaces, see the following Wikipedia + * article: http://en.wikipedia.org/wiki/RGBA_color_space + * + * \sa SDL_ConvertSurface + * \sa SDL_GetRGB + * \sa SDL_GetRGBA + * \sa SDL_MapRGB + * \sa SDL_MapRGBA + * \sa SDL_AllocFormat + * \sa SDL_FreeFormat + */ +typedef struct SDL_PixelFormat +{ + Uint32 format; + SDL_Palette *palette; + Uint8 BitsPerPixel; + Uint8 BytesPerPixel; + Uint8 padding[2]; + Uint32 Rmask; + Uint32 Gmask; + Uint32 Bmask; + Uint32 Amask; + Uint8 Rloss; + Uint8 Gloss; + Uint8 Bloss; + Uint8 Aloss; + Uint8 Rshift; + Uint8 Gshift; + Uint8 Bshift; + Uint8 Ashift; + int refcount; + struct SDL_PixelFormat *next; +} SDL_PixelFormat; + +/** + * Get the human readable name of a pixel format. + * + * \param format the pixel format to query. + * \returns the human readable name of the specified pixel format or + * `SDL_PIXELFORMAT_UNKNOWN` if the format isn't recognized. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC const char* SDLCALL SDL_GetPixelFormatName(Uint32 format); + +/** + * Convert one of the enumerated pixel formats to a bpp value and RGBA masks. + * + * \param format one of the SDL_PixelFormatEnum values. + * \param bpp a bits per pixel value; usually 15, 16, or 32. + * \param Rmask a pointer filled in with the red mask for the format. + * \param Gmask a pointer filled in with the green mask for the format. + * \param Bmask a pointer filled in with the blue mask for the format. + * \param Amask a pointer filled in with the alpha mask for the format. + * \returns SDL_TRUE on success or SDL_FALSE if the conversion wasn't + * possible; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_MasksToPixelFormatEnum + */ +extern DECLSPEC SDL_bool SDLCALL SDL_PixelFormatEnumToMasks(Uint32 format, + int *bpp, + Uint32 * Rmask, + Uint32 * Gmask, + Uint32 * Bmask, + Uint32 * Amask); + +/** + * Convert a bpp value and RGBA masks to an enumerated pixel format. + * + * This will return `SDL_PIXELFORMAT_UNKNOWN` if the conversion wasn't + * possible. + * + * \param bpp a bits per pixel value; usually 15, 16, or 32. + * \param Rmask the red mask for the format. + * \param Gmask the green mask for the format. + * \param Bmask the blue mask for the format. + * \param Amask the alpha mask for the format. + * \returns one of the SDL_PixelFormatEnum values. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_PixelFormatEnumToMasks + */ +extern DECLSPEC Uint32 SDLCALL SDL_MasksToPixelFormatEnum(int bpp, + Uint32 Rmask, + Uint32 Gmask, + Uint32 Bmask, + Uint32 Amask); + +/** + * Create an SDL_PixelFormat structure corresponding to a pixel format. + * + * Returned structure may come from a shared global cache (i.e. not newly + * allocated), and hence should not be modified, especially the palette. Weird + * errors such as `Blit combination not supported` may occur. + * + * \param pixel_format one of the SDL_PixelFormatEnum values. + * \returns the new SDL_PixelFormat structure or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FreeFormat + */ +extern DECLSPEC SDL_PixelFormat * SDLCALL SDL_AllocFormat(Uint32 pixel_format); + +/** + * Free an SDL_PixelFormat structure allocated by SDL_AllocFormat(). + * + * \param format the SDL_PixelFormat structure to free. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AllocFormat + */ +extern DECLSPEC void SDLCALL SDL_FreeFormat(SDL_PixelFormat *format); + +/** + * Create a palette structure with the specified number of color entries. + * + * The palette entries are initialized to white. + * + * \param ncolors represents the number of color entries in the color palette. + * \returns a new SDL_Palette structure on success or NULL on failure (e.g. if + * there wasn't enough memory); call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FreePalette + */ +extern DECLSPEC SDL_Palette *SDLCALL SDL_AllocPalette(int ncolors); + +/** + * Set the palette for a pixel format structure. + * + * \param format the SDL_PixelFormat structure that will use the palette. + * \param palette the SDL_Palette structure that will be used. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AllocPalette + * \sa SDL_FreePalette + */ +extern DECLSPEC int SDLCALL SDL_SetPixelFormatPalette(SDL_PixelFormat * format, + SDL_Palette *palette); + +/** + * Set a range of colors in a palette. + * + * \param palette the SDL_Palette structure to modify. + * \param colors an array of SDL_Color structures to copy into the palette. + * \param firstcolor the index of the first palette entry to modify. + * \param ncolors the number of entries to modify. + * \returns 0 on success or a negative error code if not all of the colors + * could be set; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AllocPalette + * \sa SDL_CreateRGBSurface + */ +extern DECLSPEC int SDLCALL SDL_SetPaletteColors(SDL_Palette * palette, + const SDL_Color * colors, + int firstcolor, int ncolors); + +/** + * Free a palette created with SDL_AllocPalette(). + * + * \param palette the SDL_Palette structure to be freed. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AllocPalette + */ +extern DECLSPEC void SDLCALL SDL_FreePalette(SDL_Palette * palette); + +/** + * Map an RGB triple to an opaque pixel value for a given pixel format. + * + * This function maps the RGB color value to the specified pixel format and + * returns the pixel value best approximating the given RGB color value for + * the given pixel format. + * + * If the format has a palette (8-bit) the index of the closest matching color + * in the palette will be returned. + * + * If the specified pixel format has an alpha component it will be returned as + * all 1 bits (fully opaque). + * + * If the pixel format bpp (color depth) is less than 32-bpp then the unused + * upper bits of the return value can safely be ignored (e.g., with a 16-bpp + * format the return value can be assigned to a Uint16, and similarly a Uint8 + * for an 8-bpp format). + * + * \param format an SDL_PixelFormat structure describing the pixel format. + * \param r the red component of the pixel in the range 0-255. + * \param g the green component of the pixel in the range 0-255. + * \param b the blue component of the pixel in the range 0-255. + * \returns a pixel value. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRGB + * \sa SDL_GetRGBA + * \sa SDL_MapRGBA + */ +extern DECLSPEC Uint32 SDLCALL SDL_MapRGB(const SDL_PixelFormat * format, + Uint8 r, Uint8 g, Uint8 b); + +/** + * Map an RGBA quadruple to a pixel value for a given pixel format. + * + * This function maps the RGBA color value to the specified pixel format and + * returns the pixel value best approximating the given RGBA color value for + * the given pixel format. + * + * If the specified pixel format has no alpha component the alpha value will + * be ignored (as it will be in formats with a palette). + * + * If the format has a palette (8-bit) the index of the closest matching color + * in the palette will be returned. + * + * If the pixel format bpp (color depth) is less than 32-bpp then the unused + * upper bits of the return value can safely be ignored (e.g., with a 16-bpp + * format the return value can be assigned to a Uint16, and similarly a Uint8 + * for an 8-bpp format). + * + * \param format an SDL_PixelFormat structure describing the format of the + * pixel. + * \param r the red component of the pixel in the range 0-255. + * \param g the green component of the pixel in the range 0-255. + * \param b the blue component of the pixel in the range 0-255. + * \param a the alpha component of the pixel in the range 0-255. + * \returns a pixel value. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRGB + * \sa SDL_GetRGBA + * \sa SDL_MapRGB + */ +extern DECLSPEC Uint32 SDLCALL SDL_MapRGBA(const SDL_PixelFormat * format, + Uint8 r, Uint8 g, Uint8 b, + Uint8 a); + +/** + * Get RGB values from a pixel in the specified format. + * + * This function uses the entire 8-bit [0..255] range when converting color + * components from pixel formats with less than 8-bits per RGB component + * (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff, + * 0xff, 0xff] not [0xf8, 0xfc, 0xf8]). + * + * \param pixel a pixel value. + * \param format an SDL_PixelFormat structure describing the format of the + * pixel. + * \param r a pointer filled in with the red component. + * \param g a pointer filled in with the green component. + * \param b a pointer filled in with the blue component. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRGBA + * \sa SDL_MapRGB + * \sa SDL_MapRGBA + */ +extern DECLSPEC void SDLCALL SDL_GetRGB(Uint32 pixel, + const SDL_PixelFormat * format, + Uint8 * r, Uint8 * g, Uint8 * b); + +/** + * Get RGBA values from a pixel in the specified format. + * + * This function uses the entire 8-bit [0..255] range when converting color + * components from pixel formats with less than 8-bits per RGB component + * (e.g., a completely white pixel in 16-bit RGB565 format would return [0xff, + * 0xff, 0xff] not [0xf8, 0xfc, 0xf8]). + * + * If the surface has no alpha component, the alpha will be returned as 0xff + * (100% opaque). + * + * \param pixel a pixel value. + * \param format an SDL_PixelFormat structure describing the format of the + * pixel. + * \param r a pointer filled in with the red component. + * \param g a pointer filled in with the green component. + * \param b a pointer filled in with the blue component. + * \param a a pointer filled in with the alpha component. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRGB + * \sa SDL_MapRGB + * \sa SDL_MapRGBA + */ +extern DECLSPEC void SDLCALL SDL_GetRGBA(Uint32 pixel, + const SDL_PixelFormat * format, + Uint8 * r, Uint8 * g, Uint8 * b, + Uint8 * a); + +/** + * Calculate a 256 entry gamma ramp for a gamma value. + * + * \param gamma a gamma value where 0.0 is black and 1.0 is identity. + * \param ramp an array of 256 values filled in with the gamma ramp. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetWindowGammaRamp + */ +extern DECLSPEC void SDLCALL SDL_CalculateGammaRamp(float gamma, Uint16 * ramp); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_pixels_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_platform.h b/third_party/SDL2/include/SDL_platform.h new file mode 100644 index 00000000000..64ece4fe70a --- /dev/null +++ b/third_party/SDL2/include/SDL_platform.h @@ -0,0 +1,275 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryPlatform + * + * Try to get a standard set of platform defines. + */ + +#ifndef SDL_platform_h_ +#define SDL_platform_h_ + +#if defined(_AIX) +#undef __AIX__ +#define __AIX__ 1 +#endif +#if defined(__HAIKU__) +#undef __HAIKU__ +#define __HAIKU__ 1 +#endif +#if defined(bsdi) || defined(__bsdi) || defined(__bsdi__) +#undef __BSDI__ +#define __BSDI__ 1 +#endif +#if defined(_arch_dreamcast) +#undef __DREAMCAST__ +#define __DREAMCAST__ 1 +#endif +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) +#undef __FREEBSD__ +#define __FREEBSD__ 1 +#endif +#if defined(hpux) || defined(__hpux) || defined(__hpux__) +#undef __HPUX__ +#define __HPUX__ 1 +#endif +#if defined(sgi) || defined(__sgi) || defined(__sgi__) || defined(_SGI_SOURCE) +#undef __IRIX__ +#define __IRIX__ 1 +#endif +#if (defined(linux) || defined(__linux) || defined(__linux__)) +#undef __LINUX__ +#define __LINUX__ 1 +#endif +#if defined(ANDROID) || defined(__ANDROID__) +#undef __ANDROID__ +#undef __LINUX__ /* do we need to do this? */ +#define __ANDROID__ 1 +#endif +#if defined(__NGAGE__) +#undef __NGAGE__ +#define __NGAGE__ 1 +#endif + +#if defined(__APPLE__) +/* lets us know what version of Mac OS X we're compiling on */ +#include +#ifndef __has_extension /* Older compilers don't support this */ +#define __has_extension(x) 0 +#include +#undef __has_extension +#else +#include +#endif + +/* Fix building with older SDKs that don't define these + See this for more information: + https://stackoverflow.com/questions/12132933/preprocessor-macro-for-os-x-targets +*/ +#ifndef TARGET_OS_MACCATALYST +#define TARGET_OS_MACCATALYST 0 +#endif +#ifndef TARGET_OS_IOS +#define TARGET_OS_IOS 0 +#endif +#ifndef TARGET_OS_IPHONE +#define TARGET_OS_IPHONE 0 +#endif +#ifndef TARGET_OS_TV +#define TARGET_OS_TV 0 +#endif +#ifndef TARGET_OS_SIMULATOR +#define TARGET_OS_SIMULATOR 0 +#endif + +#if TARGET_OS_TV +#undef __TVOS__ +#define __TVOS__ 1 +#endif +#if TARGET_OS_IPHONE +/* if compiling for iOS */ +#undef __IPHONEOS__ +#define __IPHONEOS__ 1 +#undef __MACOSX__ +#else +/* if not compiling for iOS */ +#undef __MACOSX__ +#define __MACOSX__ 1 +#if MAC_OS_X_VERSION_MIN_REQUIRED < 1070 +# error SDL for Mac OS X only supports deploying on 10.7 and above. +#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < 1070 */ +#endif /* TARGET_OS_IPHONE */ +#endif /* defined(__APPLE__) */ + +#if defined(__NetBSD__) +#undef __NETBSD__ +#define __NETBSD__ 1 +#endif +#if defined(__OpenBSD__) +#undef __OPENBSD__ +#define __OPENBSD__ 1 +#endif +#if defined(__OS2__) || defined(__EMX__) +#undef __OS2__ +#define __OS2__ 1 +#endif +#if defined(osf) || defined(__osf) || defined(__osf__) || defined(_OSF_SOURCE) +#undef __OSF__ +#define __OSF__ 1 +#endif +#if defined(__QNXNTO__) +#undef __QNXNTO__ +#define __QNXNTO__ 1 +#endif +#if defined(riscos) || defined(__riscos) || defined(__riscos__) +#undef __RISCOS__ +#define __RISCOS__ 1 +#endif +#if defined(__sun) && defined(__SVR4) +#undef __SOLARIS__ +#define __SOLARIS__ 1 +#endif + +#if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) +/* Try to find out if we're compiling for WinRT, GDK or non-WinRT/GDK */ +#if defined(_MSC_VER) && defined(__has_include) +#if __has_include() +#define HAVE_WINAPIFAMILY_H 1 +#else +#define HAVE_WINAPIFAMILY_H 0 +#endif + +/* If _USING_V110_SDK71_ is defined it means we are using the Windows XP toolset. */ +#elif defined(_MSC_VER) && (_MSC_VER >= 1700 && !_USING_V110_SDK71_) /* _MSC_VER == 1700 for Visual Studio 2012 */ +#define HAVE_WINAPIFAMILY_H 1 +#else +#define HAVE_WINAPIFAMILY_H 0 +#endif + +#if HAVE_WINAPIFAMILY_H +#include +#define WINAPI_FAMILY_WINRT (!WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)) +#else +#define WINAPI_FAMILY_WINRT 0 +#endif /* HAVE_WINAPIFAMILY_H */ + +#if (HAVE_WINAPIFAMILY_H) && defined(WINAPI_FAMILY_PHONE_APP) +#define SDL_WINAPI_FAMILY_PHONE (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) +#else +#define SDL_WINAPI_FAMILY_PHONE 0 +#endif + +#if WINAPI_FAMILY_WINRT +#undef __WINRT__ +#define __WINRT__ 1 +#elif defined(_GAMING_DESKTOP) /* GDK project configuration always defines _GAMING_XXX */ +#undef __WINGDK__ +#define __WINGDK__ 1 +#elif defined(_GAMING_XBOX_XBOXONE) +#undef __XBOXONE__ +#define __XBOXONE__ 1 +#elif defined(_GAMING_XBOX_SCARLETT) +#undef __XBOXSERIES__ +#define __XBOXSERIES__ 1 +#else +#undef __WINDOWS__ +#define __WINDOWS__ 1 +#endif +#endif /* defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) */ + +#if defined(__WINDOWS__) +#undef __WIN32__ +#define __WIN32__ 1 +#endif +/* This is to support generic "any GDK" separate from a platform-specific GDK */ +#if defined(__WINGDK__) || defined(__XBOXONE__) || defined(__XBOXSERIES__) +#undef __GDK__ +#define __GDK__ 1 +#endif +#if defined(__PSP__) || defined(__psp__) +#ifdef __PSP__ +#undef __PSP__ +#endif +#define __PSP__ 1 +#endif +#if defined(PS2) +#define __PS2__ 1 +#endif + +/* The NACL compiler defines __native_client__ and __pnacl__ + * Ref: http://www.chromium.org/nativeclient/pnacl/stability-of-the-pnacl-bitcode-abi + */ +#if defined(__native_client__) +#undef __LINUX__ +#undef __NACL__ +#define __NACL__ 1 +#endif +#if defined(__pnacl__) +#undef __LINUX__ +#undef __PNACL__ +#define __PNACL__ 1 +/* PNACL with newlib supports static linking only */ +#define __SDL_NOGETPROCADDR__ +#endif + +#if defined(__vita__) +#define __VITA__ 1 +#endif + +#if defined(__3DS__) +#undef __3DS__ +#define __3DS__ 1 +#endif + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Get the name of the platform. + * + * Here are the names returned for some (but not all) supported platforms: + * + * - "Windows" + * - "Mac OS X" + * - "Linux" + * - "iOS" + * - "Android" + * + * \returns the name of the platform. If the correct platform name is not + * available, returns a string beginning with the text "Unknown". + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC const char * SDLCALL SDL_GetPlatform (void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_platform_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_power.h b/third_party/SDL2/include/SDL_power.h new file mode 100644 index 00000000000..755c5d42a39 --- /dev/null +++ b/third_party/SDL2/include/SDL_power.h @@ -0,0 +1,87 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_power_h_ +#define SDL_power_h_ + +/** + * # CategoryPower + * + * Header for the SDL power management routines. + */ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The basic state for the system's power supply. + */ +typedef enum SDL_PowerState +{ + SDL_POWERSTATE_UNKNOWN, /**< cannot determine power status */ + SDL_POWERSTATE_ON_BATTERY, /**< Not plugged in, running on the battery */ + SDL_POWERSTATE_NO_BATTERY, /**< Plugged in, no battery available */ + SDL_POWERSTATE_CHARGING, /**< Plugged in, charging battery */ + SDL_POWERSTATE_CHARGED /**< Plugged in, battery charged */ +} SDL_PowerState; + +/** + * Get the current power supply details. + * + * You should never take a battery status as absolute truth. Batteries + * (especially failing batteries) are delicate hardware, and the values + * reported here are best estimates based on what that hardware reports. It's + * not uncommon for older batteries to lose stored power much faster than it + * reports, or completely drain when reporting it has 20 percent left, etc. + * + * Battery status can change at any time; if you are concerned with power + * state, you should call this function frequently, and perhaps ignore changes + * until they seem to be stable for a few seconds. + * + * It's possible a platform can only report battery percentage or time left + * but not both. + * + * \param seconds seconds of battery life left, you can pass a NULL here if + * you don't care, will return -1 if we can't determine a + * value, or we're not running on a battery. + * \param percent percentage of battery life left, between 0 and 100, you can + * pass a NULL here if you don't care, will return -1 if we + * can't determine a value, or we're not running on a battery. + * \returns an SDL_PowerState enum representing the current battery state. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_PowerState SDLCALL SDL_GetPowerInfo(int *seconds, int *percent); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_power_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_quit.h b/third_party/SDL2/include/SDL_quit.h new file mode 100644 index 00000000000..03630e232b4 --- /dev/null +++ b/third_party/SDL2/include/SDL_quit.h @@ -0,0 +1,50 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryQuit + * + * An SDL_QUIT event is generated when the user tries to close the application + * window. If it is ignored or filtered out, the window will remain open. If + * it is not ignored or filtered, it is queued normally and the window is + * allowed to close. When the window is closed, screen updates will complete, + * but have no effect. + * + * SDL_Init() installs signal handlers for SIGINT (keyboard interrupt) and + * SIGTERM (system termination request), if handlers do not already exist, + * that generate SDL_QUIT events as well. There is no way to determine the + * cause of an SDL_QUIT event, but setting a signal handler in your + * application will override the default generation of quit events for that + * signal. + */ + +#ifndef SDL_quit_h_ +#define SDL_quit_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +/* There are no functions directly affecting the quit event */ + +#define SDL_QuitRequested() \ + (SDL_PumpEvents(), (SDL_PeepEvents(NULL,0,SDL_PEEKEVENT,SDL_QUIT,SDL_QUIT) > 0)) + +#endif /* SDL_quit_h_ */ diff --git a/third_party/SDL2/include/SDL_rect.h b/third_party/SDL2/include/SDL_rect.h new file mode 100644 index 00000000000..b7e609d941e --- /dev/null +++ b/third_party/SDL2/include/SDL_rect.h @@ -0,0 +1,376 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryRect + * + * Header file for SDL_rect definition and management functions. + */ + +#ifndef SDL_rect_h_ +#define SDL_rect_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_pixels.h" +#include "SDL_rwops.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The structure that defines a point (integer) + * + * \sa SDL_EnclosePoints + * \sa SDL_PointInRect + */ +typedef struct SDL_Point +{ + int x; + int y; +} SDL_Point; + +/** + * The structure that defines a point (floating point) + * + * \sa SDL_EncloseFPoints + * \sa SDL_PointInFRect + */ +typedef struct SDL_FPoint +{ + float x; + float y; +} SDL_FPoint; + + +/** + * A rectangle, with the origin at the upper left (integer). + * + * \sa SDL_RectEmpty + * \sa SDL_RectEquals + * \sa SDL_HasIntersection + * \sa SDL_IntersectRect + * \sa SDL_IntersectRectAndLine + * \sa SDL_UnionRect + * \sa SDL_EnclosePoints + */ +typedef struct SDL_Rect +{ + int x, y; + int w, h; +} SDL_Rect; + + +/** + * A rectangle, with the origin at the upper left (floating point). + * + * \sa SDL_FRectEmpty + * \sa SDL_FRectEquals + * \sa SDL_FRectEqualsEpsilon + * \sa SDL_HasIntersectionF + * \sa SDL_IntersectFRect + * \sa SDL_IntersectFRectAndLine + * \sa SDL_UnionFRect + * \sa SDL_EncloseFPoints + * \sa SDL_PointInFRect + */ +typedef struct SDL_FRect +{ + float x; + float y; + float w; + float h; +} SDL_FRect; + + +/** + * Returns true if point resides inside a rectangle. + */ +SDL_FORCE_INLINE SDL_bool SDL_PointInRect(const SDL_Point *p, const SDL_Rect *r) +{ + return ( (p->x >= r->x) && (p->x < (r->x + r->w)) && + (p->y >= r->y) && (p->y < (r->y + r->h)) ) ? SDL_TRUE : SDL_FALSE; +} + +/** + * Returns true if the rectangle has no area. + */ +SDL_FORCE_INLINE SDL_bool SDL_RectEmpty(const SDL_Rect *r) +{ + return ((!r) || (r->w <= 0) || (r->h <= 0)) ? SDL_TRUE : SDL_FALSE; +} + +/** + * Returns true if the two rectangles are equal. + */ +SDL_FORCE_INLINE SDL_bool SDL_RectEquals(const SDL_Rect *a, const SDL_Rect *b) +{ + return (a && b && (a->x == b->x) && (a->y == b->y) && + (a->w == b->w) && (a->h == b->h)) ? SDL_TRUE : SDL_FALSE; +} + +/** + * Determine whether two rectangles intersect. + * + * If either pointer is NULL the function will return SDL_FALSE. + * + * \param A an SDL_Rect structure representing the first rectangle. + * \param B an SDL_Rect structure representing the second rectangle. + * \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_IntersectRect + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasIntersection(const SDL_Rect * A, + const SDL_Rect * B); + +/** + * Calculate the intersection of two rectangles. + * + * If `result` is NULL then this function will return SDL_FALSE. + * + * \param A an SDL_Rect structure representing the first rectangle. + * \param B an SDL_Rect structure representing the second rectangle. + * \param result an SDL_Rect structure filled in with the intersection of + * rectangles `A` and `B`. + * \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HasIntersection + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IntersectRect(const SDL_Rect * A, + const SDL_Rect * B, + SDL_Rect * result); + +/** + * Calculate the union of two rectangles. + * + * \param A an SDL_Rect structure representing the first rectangle. + * \param B an SDL_Rect structure representing the second rectangle. + * \param result an SDL_Rect structure filled in with the union of rectangles + * `A` and `B`. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC void SDLCALL SDL_UnionRect(const SDL_Rect * A, + const SDL_Rect * B, + SDL_Rect * result); + +/** + * Calculate a minimal rectangle enclosing a set of points. + * + * If `clip` is not NULL then only points inside of the clipping rectangle are + * considered. + * + * \param points an array of SDL_Point structures representing points to be + * enclosed. + * \param count the number of structures in the `points` array. + * \param clip an SDL_Rect used for clipping or NULL to enclose all points. + * \param result an SDL_Rect structure filled in with the minimal enclosing + * rectangle. + * \returns SDL_TRUE if any points were enclosed or SDL_FALSE if all the + * points were outside of the clipping rectangle. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_EnclosePoints(const SDL_Point * points, + int count, + const SDL_Rect * clip, + SDL_Rect * result); + +/** + * Calculate the intersection of a rectangle and line segment. + * + * This function is used to clip a line segment to a rectangle. A line segment + * contained entirely within the rectangle or that does not intersect will + * remain unchanged. A line segment that crosses the rectangle at either or + * both ends will be clipped to the boundary of the rectangle and the new + * coordinates saved in `X1`, `Y1`, `X2`, and/or `Y2` as necessary. + * + * \param rect an SDL_Rect structure representing the rectangle to intersect. + * \param X1 a pointer to the starting X-coordinate of the line. + * \param Y1 a pointer to the starting Y-coordinate of the line. + * \param X2 a pointer to the ending X-coordinate of the line. + * \param Y2 a pointer to the ending Y-coordinate of the line. + * \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IntersectRectAndLine(const SDL_Rect * + rect, int *X1, + int *Y1, int *X2, + int *Y2); + + +/* SDL_FRect versions... */ + +/** + * Returns true if point resides inside a rectangle. + */ +SDL_FORCE_INLINE SDL_bool SDL_PointInFRect(const SDL_FPoint *p, const SDL_FRect *r) +{ + return ( (p->x >= r->x) && (p->x < (r->x + r->w)) && + (p->y >= r->y) && (p->y < (r->y + r->h)) ) ? SDL_TRUE : SDL_FALSE; +} + +/** + * Returns true if the rectangle has no area. + */ +SDL_FORCE_INLINE SDL_bool SDL_FRectEmpty(const SDL_FRect *r) +{ + return ((!r) || (r->w <= 0.0f) || (r->h <= 0.0f)) ? SDL_TRUE : SDL_FALSE; +} + +/** + * Returns true if the two rectangles are equal, within some given epsilon. + * + * \since This function is available since SDL 2.0.22. + */ +SDL_FORCE_INLINE SDL_bool SDL_FRectEqualsEpsilon(const SDL_FRect *a, const SDL_FRect *b, const float epsilon) +{ + return (a && b && ((a == b) || + ((SDL_fabsf(a->x - b->x) <= epsilon) && + (SDL_fabsf(a->y - b->y) <= epsilon) && + (SDL_fabsf(a->w - b->w) <= epsilon) && + (SDL_fabsf(a->h - b->h) <= epsilon)))) + ? SDL_TRUE : SDL_FALSE; +} + +/** + * Returns true if the two rectangles are equal, using a default epsilon. + * + * \since This function is available since SDL 2.0.22. + */ +SDL_FORCE_INLINE SDL_bool SDL_FRectEquals(const SDL_FRect *a, const SDL_FRect *b) +{ + return SDL_FRectEqualsEpsilon(a, b, SDL_FLT_EPSILON); +} + +/** + * Determine whether two rectangles intersect with float precision. + * + * If either pointer is NULL the function will return SDL_FALSE. + * + * \param A an SDL_FRect structure representing the first rectangle. + * \param B an SDL_FRect structure representing the second rectangle. + * \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.22. + * + * \sa SDL_IntersectRect + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasIntersectionF(const SDL_FRect * A, + const SDL_FRect * B); + +/** + * Calculate the intersection of two rectangles with float precision. + * + * If `result` is NULL then this function will return SDL_FALSE. + * + * \param A an SDL_FRect structure representing the first rectangle. + * \param B an SDL_FRect structure representing the second rectangle. + * \param result an SDL_FRect structure filled in with the intersection of + * rectangles `A` and `B`. + * \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.22. + * + * \sa SDL_HasIntersectionF + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IntersectFRect(const SDL_FRect * A, + const SDL_FRect * B, + SDL_FRect * result); + +/** + * Calculate the union of two rectangles with float precision. + * + * \param A an SDL_FRect structure representing the first rectangle. + * \param B an SDL_FRect structure representing the second rectangle. + * \param result an SDL_FRect structure filled in with the union of rectangles + * `A` and `B`. + * + * \since This function is available since SDL 2.0.22. + */ +extern DECLSPEC void SDLCALL SDL_UnionFRect(const SDL_FRect * A, + const SDL_FRect * B, + SDL_FRect * result); + +/** + * Calculate a minimal rectangle enclosing a set of points with float + * precision. + * + * If `clip` is not NULL then only points inside of the clipping rectangle are + * considered. + * + * \param points an array of SDL_FPoint structures representing points to be + * enclosed. + * \param count the number of structures in the `points` array. + * \param clip an SDL_FRect used for clipping or NULL to enclose all points. + * \param result an SDL_FRect structure filled in with the minimal enclosing + * rectangle. + * \returns SDL_TRUE if any points were enclosed or SDL_FALSE if all the + * points were outside of the clipping rectangle. + * + * \since This function is available since SDL 2.0.22. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_EncloseFPoints(const SDL_FPoint * points, + int count, + const SDL_FRect * clip, + SDL_FRect * result); + +/** + * Calculate the intersection of a rectangle and line segment with float + * precision. + * + * This function is used to clip a line segment to a rectangle. A line segment + * contained entirely within the rectangle or that does not intersect will + * remain unchanged. A line segment that crosses the rectangle at either or + * both ends will be clipped to the boundary of the rectangle and the new + * coordinates saved in `X1`, `Y1`, `X2`, and/or `Y2` as necessary. + * + * \param rect an SDL_FRect structure representing the rectangle to intersect. + * \param X1 a pointer to the starting X-coordinate of the line. + * \param Y1 a pointer to the starting Y-coordinate of the line. + * \param X2 a pointer to the ending X-coordinate of the line. + * \param Y2 a pointer to the ending Y-coordinate of the line. + * \returns SDL_TRUE if there is an intersection, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.22. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IntersectFRectAndLine(const SDL_FRect * + rect, float *X1, + float *Y1, float *X2, + float *Y2); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_rect_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_render.h b/third_party/SDL2/include/SDL_render.h new file mode 100644 index 00000000000..2118ed99cc8 --- /dev/null +++ b/third_party/SDL2/include/SDL_render.h @@ -0,0 +1,1932 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryRender + * + * Header file for SDL 2D rendering functions. + * + * This API supports the following features: + * + * - single pixel points + * - single pixel lines + * - filled rectangles + * - texture images + * + * The primitives may be drawn in opaque, blended, or additive modes. + * + * The texture images may be drawn in opaque, blended, or additive modes. They + * can have an additional color tint or alpha modulation applied to them, and + * may also be stretched with linear interpolation. + * + * This API is designed to accelerate simple 2D operations. You may want more + * functionality such as polygons and particle effects and in that case you + * should use SDL's OpenGL/Direct3D support or one of the many good 3D + * engines. + * + * These functions must be called from the main thread. See this bug for + * details: https://github.com/libsdl-org/SDL/issues/986 + */ + +#ifndef SDL_render_h_ +#define SDL_render_h_ + +#include "SDL_stdinc.h" +#include "SDL_rect.h" +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Flags used when creating a rendering context + */ +typedef enum SDL_RendererFlags +{ + SDL_RENDERER_SOFTWARE = 0x00000001, /**< The renderer is a software fallback */ + SDL_RENDERER_ACCELERATED = 0x00000002, /**< The renderer uses hardware + acceleration */ + SDL_RENDERER_PRESENTVSYNC = 0x00000004, /**< Present is synchronized + with the refresh rate */ + SDL_RENDERER_TARGETTEXTURE = 0x00000008 /**< The renderer supports + rendering to texture */ +} SDL_RendererFlags; + +/** + * Information on the capabilities of a render driver or context. + */ +typedef struct SDL_RendererInfo +{ + const char *name; /**< The name of the renderer */ + Uint32 flags; /**< Supported SDL_RendererFlags */ + Uint32 num_texture_formats; /**< The number of available texture formats */ + Uint32 texture_formats[16]; /**< The available texture formats */ + int max_texture_width; /**< The maximum texture width */ + int max_texture_height; /**< The maximum texture height */ +} SDL_RendererInfo; + +/** + * Vertex structure + */ +typedef struct SDL_Vertex +{ + SDL_FPoint position; /**< Vertex position, in SDL_Renderer coordinates */ + SDL_Color color; /**< Vertex color */ + SDL_FPoint tex_coord; /**< Normalized texture coordinates, if needed */ +} SDL_Vertex; + +/** + * The scaling mode for a texture. + */ +typedef enum SDL_ScaleMode +{ + SDL_ScaleModeNearest, /**< nearest pixel sampling */ + SDL_ScaleModeLinear, /**< linear filtering */ + SDL_ScaleModeBest /**< anisotropic filtering */ +} SDL_ScaleMode; + +/** + * The access pattern allowed for a texture. + */ +typedef enum SDL_TextureAccess +{ + SDL_TEXTUREACCESS_STATIC, /**< Changes rarely, not lockable */ + SDL_TEXTUREACCESS_STREAMING, /**< Changes frequently, lockable */ + SDL_TEXTUREACCESS_TARGET /**< Texture can be used as a render target */ +} SDL_TextureAccess; + +/** + * The texture channel modulation used in SDL_RenderCopy(). + */ +typedef enum SDL_TextureModulate +{ + SDL_TEXTUREMODULATE_NONE = 0x00000000, /**< No modulation */ + SDL_TEXTUREMODULATE_COLOR = 0x00000001, /**< srcC = srcC * color */ + SDL_TEXTUREMODULATE_ALPHA = 0x00000002 /**< srcA = srcA * alpha */ +} SDL_TextureModulate; + +/** + * Flip constants for SDL_RenderCopyEx + */ +typedef enum SDL_RendererFlip +{ + SDL_FLIP_NONE = 0x00000000, /**< Do not flip */ + SDL_FLIP_HORIZONTAL = 0x00000001, /**< flip horizontally */ + SDL_FLIP_VERTICAL = 0x00000002 /**< flip vertically */ +} SDL_RendererFlip; + +/** + * A structure representing rendering state + */ +struct SDL_Renderer; +typedef struct SDL_Renderer SDL_Renderer; + +/** + * An efficient driver-specific representation of pixel data + */ +struct SDL_Texture; +typedef struct SDL_Texture SDL_Texture; + +/* Function prototypes */ + +/** + * Get the number of 2D rendering drivers available for the current display. + * + * A render driver is a set of code that handles rendering and texture + * management on a particular display. Normally there is only one, but some + * drivers may have several available with different capabilities. + * + * There may be none if SDL was compiled without render support. + * + * \returns a number >= 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_GetRenderDriverInfo + */ +extern DECLSPEC int SDLCALL SDL_GetNumRenderDrivers(void); + +/** + * Get info about a specific 2D rendering driver for the current display. + * + * \param index the index of the driver to query information about. + * \param info an SDL_RendererInfo structure to be filled with information on + * the rendering driver. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_GetNumRenderDrivers + */ +extern DECLSPEC int SDLCALL SDL_GetRenderDriverInfo(int index, + SDL_RendererInfo * info); + +/** + * Create a window and default renderer. + * + * \param width the width of the window. + * \param height the height of the window. + * \param window_flags the flags used to create the window (see + * SDL_CreateWindow()). + * \param window a pointer filled with the window, or NULL on error. + * \param renderer a pointer filled with the renderer, or NULL on error. + * \returns 0 on success, or -1 on error; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_CreateWindow + */ +extern DECLSPEC int SDLCALL SDL_CreateWindowAndRenderer( + int width, int height, Uint32 window_flags, + SDL_Window **window, SDL_Renderer **renderer); + + +/** + * Create a 2D rendering context for a window. + * + * \param window the window where rendering is displayed. + * \param index the index of the rendering driver to initialize, or -1 to + * initialize the first one supporting the requested flags. + * \param flags 0, or one or more SDL_RendererFlags OR'd together. + * \returns a valid rendering context or NULL if there was an error; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateSoftwareRenderer + * \sa SDL_DestroyRenderer + * \sa SDL_GetNumRenderDrivers + * \sa SDL_GetRendererInfo + */ +extern DECLSPEC SDL_Renderer * SDLCALL SDL_CreateRenderer(SDL_Window * window, + int index, Uint32 flags); + +/** + * Create a 2D software rendering context for a surface. + * + * Two other API which can be used to create SDL_Renderer: + * SDL_CreateRenderer() and SDL_CreateWindowAndRenderer(). These can _also_ + * create a software renderer, but they are intended to be used with an + * SDL_Window as the final destination and not an SDL_Surface. + * + * \param surface the SDL_Surface structure representing the surface where + * rendering is done. + * \returns a valid rendering context or NULL if there was an error; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_CreateWindowRenderer + * \sa SDL_DestroyRenderer + */ +extern DECLSPEC SDL_Renderer * SDLCALL SDL_CreateSoftwareRenderer(SDL_Surface * surface); + +/** + * Get the renderer associated with a window. + * + * \param window the window to query. + * \returns the rendering context on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRenderer + */ +extern DECLSPEC SDL_Renderer * SDLCALL SDL_GetRenderer(SDL_Window * window); + +/** + * Get the window associated with a renderer. + * + * \param renderer the renderer to query. + * \returns the window on success or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.22. + */ +extern DECLSPEC SDL_Window * SDLCALL SDL_RenderGetWindow(SDL_Renderer *renderer); + +/** + * Get information about a rendering context. + * + * \param renderer the rendering context. + * \param info an SDL_RendererInfo structure filled with information about the + * current renderer. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRenderer + */ +extern DECLSPEC int SDLCALL SDL_GetRendererInfo(SDL_Renderer * renderer, + SDL_RendererInfo * info); + +/** + * Get the output size in pixels of a rendering context. + * + * Due to high-dpi displays, you might end up with a rendering context that + * has more pixels than the window that contains it, so use this instead of + * SDL_GetWindowSize() to decide how much drawing area you have. + * + * \param renderer the rendering context. + * \param w an int filled with the width. + * \param h an int filled with the height. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRenderer + */ +extern DECLSPEC int SDLCALL SDL_GetRendererOutputSize(SDL_Renderer * renderer, + int *w, int *h); + +/** + * Create a texture for a rendering context. + * + * You can set the texture scaling method by setting + * `SDL_HINT_RENDER_SCALE_QUALITY` before creating the texture. + * + * \param renderer the rendering context. + * \param format one of the enumerated values in SDL_PixelFormatEnum. + * \param access one of the enumerated values in SDL_TextureAccess. + * \param w the width of the texture in pixels. + * \param h the height of the texture in pixels. + * \returns a pointer to the created texture or NULL if no rendering context + * was active, the format was unsupported, or the width or height + * were out of range; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateTextureFromSurface + * \sa SDL_DestroyTexture + * \sa SDL_QueryTexture + * \sa SDL_UpdateTexture + */ +extern DECLSPEC SDL_Texture * SDLCALL SDL_CreateTexture(SDL_Renderer * renderer, + Uint32 format, + int access, int w, + int h); + +/** + * Create a texture from an existing surface. + * + * The surface is not modified or freed by this function. + * + * The SDL_TextureAccess hint for the created texture is + * `SDL_TEXTUREACCESS_STATIC`. + * + * The pixel format of the created texture may be different from the pixel + * format of the surface. Use SDL_QueryTexture() to query the pixel format of + * the texture. + * + * \param renderer the rendering context. + * \param surface the SDL_Surface structure containing pixel data used to fill + * the texture. + * \returns the created texture or NULL on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateTexture + * \sa SDL_DestroyTexture + * \sa SDL_QueryTexture + */ +extern DECLSPEC SDL_Texture * SDLCALL SDL_CreateTextureFromSurface(SDL_Renderer * renderer, SDL_Surface * surface); + +/** + * Query the attributes of a texture. + * + * \param texture the texture to query. + * \param format a pointer filled in with the raw format of the texture; the + * actual format may differ, but pixel transfers will use this + * format (one of the SDL_PixelFormatEnum values). This argument + * can be NULL if you don't need this information. + * \param access a pointer filled in with the actual access to the texture + * (one of the SDL_TextureAccess values). This argument can be + * NULL if you don't need this information. + * \param w a pointer filled in with the width of the texture in pixels. This + * argument can be NULL if you don't need this information. + * \param h a pointer filled in with the height of the texture in pixels. This + * argument can be NULL if you don't need this information. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateTexture + */ +extern DECLSPEC int SDLCALL SDL_QueryTexture(SDL_Texture * texture, + Uint32 * format, int *access, + int *w, int *h); + +/** + * Set an additional color value multiplied into render copy operations. + * + * When this texture is rendered, during the copy operation each source color + * channel is modulated by the appropriate color value according to the + * following formula: + * + * `srcC = srcC * (color / 255)` + * + * Color modulation is not always supported by the renderer; it will return -1 + * if color modulation is not supported. + * + * \param texture the texture to update. + * \param r the red color value multiplied into copy operations. + * \param g the green color value multiplied into copy operations. + * \param b the blue color value multiplied into copy operations. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetTextureColorMod + * \sa SDL_SetTextureAlphaMod + */ +extern DECLSPEC int SDLCALL SDL_SetTextureColorMod(SDL_Texture * texture, + Uint8 r, Uint8 g, Uint8 b); + + +/** + * Get the additional color value multiplied into render copy operations. + * + * \param texture the texture to query. + * \param r a pointer filled in with the current red color value. + * \param g a pointer filled in with the current green color value. + * \param b a pointer filled in with the current blue color value. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetTextureAlphaMod + * \sa SDL_SetTextureColorMod + */ +extern DECLSPEC int SDLCALL SDL_GetTextureColorMod(SDL_Texture * texture, + Uint8 * r, Uint8 * g, + Uint8 * b); + +/** + * Set an additional alpha value multiplied into render copy operations. + * + * When this texture is rendered, during the copy operation the source alpha + * value is modulated by this alpha value according to the following formula: + * + * `srcA = srcA * (alpha / 255)` + * + * Alpha modulation is not always supported by the renderer; it will return -1 + * if alpha modulation is not supported. + * + * \param texture the texture to update. + * \param alpha the source alpha value multiplied into copy operations. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetTextureAlphaMod + * \sa SDL_SetTextureColorMod + */ +extern DECLSPEC int SDLCALL SDL_SetTextureAlphaMod(SDL_Texture * texture, + Uint8 alpha); + +/** + * Get the additional alpha value multiplied into render copy operations. + * + * \param texture the texture to query. + * \param alpha a pointer filled in with the current alpha value. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetTextureColorMod + * \sa SDL_SetTextureAlphaMod + */ +extern DECLSPEC int SDLCALL SDL_GetTextureAlphaMod(SDL_Texture * texture, + Uint8 * alpha); + +/** + * Set the blend mode for a texture, used by SDL_RenderCopy(). + * + * If the blend mode is not supported, the closest supported mode is chosen + * and this function returns -1. + * + * \param texture the texture to update. + * \param blendMode the SDL_BlendMode to use for texture blending. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetTextureBlendMode + * \sa SDL_RenderCopy + */ +extern DECLSPEC int SDLCALL SDL_SetTextureBlendMode(SDL_Texture * texture, + SDL_BlendMode blendMode); + +/** + * Get the blend mode used for texture copy operations. + * + * \param texture the texture to query. + * \param blendMode a pointer filled in with the current SDL_BlendMode. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetTextureBlendMode + */ +extern DECLSPEC int SDLCALL SDL_GetTextureBlendMode(SDL_Texture * texture, + SDL_BlendMode *blendMode); + +/** + * Set the scale mode used for texture scale operations. + * + * If the scale mode is not supported, the closest supported mode is chosen. + * + * \param texture The texture to update. + * \param scaleMode the SDL_ScaleMode to use for texture scaling. + * \returns 0 on success, or -1 if the texture is not valid. + * + * \since This function is available since SDL 2.0.12. + * + * \sa SDL_GetTextureScaleMode + */ +extern DECLSPEC int SDLCALL SDL_SetTextureScaleMode(SDL_Texture * texture, + SDL_ScaleMode scaleMode); + +/** + * Get the scale mode used for texture scale operations. + * + * \param texture the texture to query. + * \param scaleMode a pointer filled in with the current scale mode. + * \return 0 on success, or -1 if the texture is not valid. + * + * \since This function is available since SDL 2.0.12. + * + * \sa SDL_SetTextureScaleMode + */ +extern DECLSPEC int SDLCALL SDL_GetTextureScaleMode(SDL_Texture * texture, + SDL_ScaleMode *scaleMode); + +/** + * Associate a user-specified pointer with a texture. + * + * \param texture the texture to update. + * \param userdata the pointer to associate with the texture. + * \returns 0 on success, or -1 if the texture is not valid. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_GetTextureUserData + */ +extern DECLSPEC int SDLCALL SDL_SetTextureUserData(SDL_Texture * texture, + void *userdata); + +/** + * Get the user-specified pointer associated with a texture + * + * \param texture the texture to query. + * \return the pointer associated with the texture, or NULL if the texture is + * not valid. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_SetTextureUserData + */ +extern DECLSPEC void * SDLCALL SDL_GetTextureUserData(SDL_Texture * texture); + +/** + * Update the given texture rectangle with new pixel data. + * + * The pixel data must be in the pixel format of the texture. Use + * SDL_QueryTexture() to query the pixel format of the texture. + * + * This is a fairly slow function, intended for use with static textures that + * do not change often. + * + * If the texture is intended to be updated often, it is preferred to create + * the texture as streaming and use the locking functions referenced below. + * While this function will work with streaming textures, for optimization + * reasons you may not get the pixels back if you lock the texture afterward. + * + * \param texture the texture to update. + * \param rect an SDL_Rect structure representing the area to update, or NULL + * to update the entire texture. + * \param pixels the raw pixel data in the format of the texture. + * \param pitch the number of bytes in a row of pixel data, including padding + * between lines. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateTexture + * \sa SDL_LockTexture + * \sa SDL_UnlockTexture + */ +extern DECLSPEC int SDLCALL SDL_UpdateTexture(SDL_Texture * texture, + const SDL_Rect * rect, + const void *pixels, int pitch); + +/** + * Update a rectangle within a planar YV12 or IYUV texture with new pixel + * data. + * + * You can use SDL_UpdateTexture() as long as your pixel data is a contiguous + * block of Y and U/V planes in the proper order, but this function is + * available if your pixel data is not contiguous. + * + * \param texture the texture to update. + * \param rect a pointer to the rectangle of pixels to update, or NULL to + * update the entire texture. + * \param Yplane the raw pixel data for the Y plane. + * \param Ypitch the number of bytes between rows of pixel data for the Y + * plane. + * \param Uplane the raw pixel data for the U plane. + * \param Upitch the number of bytes between rows of pixel data for the U + * plane. + * \param Vplane the raw pixel data for the V plane. + * \param Vpitch the number of bytes between rows of pixel data for the V + * plane. + * \returns 0 on success or -1 if the texture is not valid; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.1. + * + * \sa SDL_UpdateTexture + */ +extern DECLSPEC int SDLCALL SDL_UpdateYUVTexture(SDL_Texture * texture, + const SDL_Rect * rect, + const Uint8 *Yplane, int Ypitch, + const Uint8 *Uplane, int Upitch, + const Uint8 *Vplane, int Vpitch); + +/** + * Update a rectangle within a planar NV12 or NV21 texture with new pixels. + * + * You can use SDL_UpdateTexture() as long as your pixel data is a contiguous + * block of NV12/21 planes in the proper order, but this function is available + * if your pixel data is not contiguous. + * + * \param texture the texture to update. + * \param rect a pointer to the rectangle of pixels to update, or NULL to + * update the entire texture. + * \param Yplane the raw pixel data for the Y plane. + * \param Ypitch the number of bytes between rows of pixel data for the Y + * plane. + * \param UVplane the raw pixel data for the UV plane. + * \param UVpitch the number of bytes between rows of pixel data for the UV + * plane. + * \return 0 on success, or -1 if the texture is not valid. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC int SDLCALL SDL_UpdateNVTexture(SDL_Texture * texture, + const SDL_Rect * rect, + const Uint8 *Yplane, int Ypitch, + const Uint8 *UVplane, int UVpitch); + +/** + * Lock a portion of the texture for **write-only** pixel access. + * + * As an optimization, the pixels made available for editing don't necessarily + * contain the old texture data. This is a write-only operation, and if you + * need to keep a copy of the texture data you should do that at the + * application level. + * + * You must use SDL_UnlockTexture() to unlock the pixels and apply any + * changes. + * + * \param texture the texture to lock for access, which was created with + * `SDL_TEXTUREACCESS_STREAMING`. + * \param rect an SDL_Rect structure representing the area to lock for access; + * NULL to lock the entire texture. + * \param pixels this is filled in with a pointer to the locked pixels, + * appropriately offset by the locked area. + * \param pitch this is filled in with the pitch of the locked pixels; the + * pitch is the length of one row in bytes. + * \returns 0 on success or a negative error code if the texture is not valid + * or was not created with `SDL_TEXTUREACCESS_STREAMING`; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_UnlockTexture + */ +extern DECLSPEC int SDLCALL SDL_LockTexture(SDL_Texture * texture, + const SDL_Rect * rect, + void **pixels, int *pitch); + +/** + * Lock a portion of the texture for **write-only** pixel access, and expose + * it as a SDL surface. + * + * Besides providing an SDL_Surface instead of raw pixel data, this function + * operates like SDL_LockTexture. + * + * As an optimization, the pixels made available for editing don't necessarily + * contain the old texture data. This is a write-only operation, and if you + * need to keep a copy of the texture data you should do that at the + * application level. + * + * You must use SDL_UnlockTexture() to unlock the pixels and apply any + * changes. + * + * The returned surface is freed internally after calling SDL_UnlockTexture() + * or SDL_DestroyTexture(). The caller should not free it. + * + * \param texture the texture to lock for access, which was created with + * `SDL_TEXTUREACCESS_STREAMING`. + * \param rect a pointer to the rectangle to lock for access. If the rect is + * NULL, the entire texture will be locked. + * \param surface this is filled in with an SDL surface representing the + * locked area. + * \returns 0 on success, or -1 if the texture is not valid or was not created + * with `SDL_TEXTUREACCESS_STREAMING`. + * + * \since This function is available since SDL 2.0.12. + * + * \sa SDL_LockTexture + * \sa SDL_UnlockTexture + */ +extern DECLSPEC int SDLCALL SDL_LockTextureToSurface(SDL_Texture *texture, + const SDL_Rect *rect, + SDL_Surface **surface); + +/** + * Unlock a texture, uploading the changes to video memory, if needed. + * + * **Warning**: Please note that SDL_LockTexture() is intended to be + * write-only; it will not guarantee the previous contents of the texture will + * be provided. You must fully initialize any area of a texture that you lock + * before unlocking it, as the pixels might otherwise be uninitialized memory. + * + * Which is to say: locking and immediately unlocking a texture can result in + * corrupted textures, depending on the renderer in use. + * + * \param texture a texture locked by SDL_LockTexture(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LockTexture + */ +extern DECLSPEC void SDLCALL SDL_UnlockTexture(SDL_Texture * texture); + +/** + * Determine whether a renderer supports the use of render targets. + * + * \param renderer the renderer that will be checked. + * \returns SDL_TRUE if supported or SDL_FALSE if not. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetRenderTarget + */ +extern DECLSPEC SDL_bool SDLCALL SDL_RenderTargetSupported(SDL_Renderer *renderer); + +/** + * Set a texture as the current rendering target. + * + * Before using this function, you should check the + * `SDL_RENDERER_TARGETTEXTURE` bit in the flags of SDL_RendererInfo to see if + * render targets are supported. + * + * The default render target is the window for which the renderer was created. + * To stop rendering to a texture and render to the window again, call this + * function with a NULL `texture`. This will reset the renderer's viewport, + * clipping rectangle, and scaling settings to the state they were in before + * setting a non-NULL `texture` target, losing any changes made in the + * meantime. + * + * \param renderer the rendering context. + * \param texture the targeted texture, which must be created with the + * `SDL_TEXTUREACCESS_TARGET` flag, or NULL to render to the + * window instead of a texture. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRenderTarget + */ +extern DECLSPEC int SDLCALL SDL_SetRenderTarget(SDL_Renderer *renderer, + SDL_Texture *texture); + +/** + * Get the current render target. + * + * The default render target is the window for which the renderer was created, + * and is reported a NULL here. + * + * \param renderer the rendering context. + * \returns the current render target or NULL for the default render target. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetRenderTarget + */ +extern DECLSPEC SDL_Texture * SDLCALL SDL_GetRenderTarget(SDL_Renderer *renderer); + +/** + * Set a device independent resolution for rendering. + * + * This function uses the viewport and scaling functionality to allow a fixed + * logical resolution for rendering, regardless of the actual output + * resolution. If the actual output resolution doesn't have the same aspect + * ratio the output rendering will be centered within the output display. + * + * If the output display is a window, mouse and touch events in the window + * will be filtered and scaled so they seem to arrive within the logical + * resolution. The SDL_HINT_MOUSE_RELATIVE_SCALING hint controls whether + * relative motion events are also scaled. + * + * If this function results in scaling or subpixel drawing by the rendering + * backend, it will be handled using the appropriate quality hints. + * + * \param renderer the renderer for which resolution should be set. + * \param w the width of the logical resolution. + * \param h the height of the logical resolution. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderGetLogicalSize + */ +extern DECLSPEC int SDLCALL SDL_RenderSetLogicalSize(SDL_Renderer * renderer, int w, int h); + +/** + * Get device independent resolution for rendering. + * + * When using the main rendering target (eg no target texture is set): this + * may return 0 for `w` and `h` if the SDL_Renderer has never had its logical + * size set by SDL_RenderSetLogicalSize(). Otherwise it returns the logical + * width and height. + * + * When using a target texture: Never return 0 for `w` and `h` at first. Then + * it returns the logical width and height that are set. + * + * \param renderer a rendering context. + * \param w an int to be filled with the width. + * \param h an int to be filled with the height. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderSetLogicalSize + */ +extern DECLSPEC void SDLCALL SDL_RenderGetLogicalSize(SDL_Renderer * renderer, int *w, int *h); + +/** + * Set whether to force integer scales for resolution-independent rendering. + * + * This function restricts the logical viewport to integer values - that is, + * when a resolution is between two multiples of a logical size, the viewport + * size is rounded down to the lower multiple. + * + * \param renderer the renderer for which integer scaling should be set. + * \param enable enable or disable the integer scaling for rendering. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_RenderGetIntegerScale + * \sa SDL_RenderSetLogicalSize + */ +extern DECLSPEC int SDLCALL SDL_RenderSetIntegerScale(SDL_Renderer * renderer, + SDL_bool enable); + +/** + * Get whether integer scales are forced for resolution-independent rendering. + * + * \param renderer the renderer from which integer scaling should be queried. + * \returns SDL_TRUE if integer scales are forced or SDL_FALSE if not and on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_RenderSetIntegerScale + */ +extern DECLSPEC SDL_bool SDLCALL SDL_RenderGetIntegerScale(SDL_Renderer * renderer); + +/** + * Set the drawing area for rendering on the current target. + * + * When the window is resized, the viewport is reset to fill the entire new + * window size. + * + * \param renderer the rendering context. + * \param rect the SDL_Rect structure representing the drawing area, or NULL + * to set the viewport to the entire target. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderGetViewport + */ +extern DECLSPEC int SDLCALL SDL_RenderSetViewport(SDL_Renderer * renderer, + const SDL_Rect * rect); + +/** + * Get the drawing area for the current target. + * + * \param renderer the rendering context. + * \param rect an SDL_Rect structure filled in with the current drawing area. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderSetViewport + */ +extern DECLSPEC void SDLCALL SDL_RenderGetViewport(SDL_Renderer * renderer, + SDL_Rect * rect); + +/** + * Set the clip rectangle for rendering on the specified target. + * + * \param renderer the rendering context for which clip rectangle should be + * set. + * \param rect an SDL_Rect structure representing the clip area, relative to + * the viewport, or NULL to disable clipping. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderGetClipRect + * \sa SDL_RenderIsClipEnabled + */ +extern DECLSPEC int SDLCALL SDL_RenderSetClipRect(SDL_Renderer * renderer, + const SDL_Rect * rect); + +/** + * Get the clip rectangle for the current target. + * + * \param renderer the rendering context from which clip rectangle should be + * queried. + * \param rect an SDL_Rect structure filled in with the current clipping area + * or an empty rectangle if clipping is disabled. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderIsClipEnabled + * \sa SDL_RenderSetClipRect + */ +extern DECLSPEC void SDLCALL SDL_RenderGetClipRect(SDL_Renderer * renderer, + SDL_Rect * rect); + +/** + * Get whether clipping is enabled on the given renderer. + * + * \param renderer the renderer from which clip state should be queried. + * \returns SDL_TRUE if clipping is enabled or SDL_FALSE if not; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_RenderGetClipRect + * \sa SDL_RenderSetClipRect + */ +extern DECLSPEC SDL_bool SDLCALL SDL_RenderIsClipEnabled(SDL_Renderer * renderer); + + +/** + * Set the drawing scale for rendering on the current target. + * + * The drawing coordinates are scaled by the x/y scaling factors before they + * are used by the renderer. This allows resolution independent drawing with a + * single coordinate system. + * + * If this results in scaling or subpixel drawing by the rendering backend, it + * will be handled using the appropriate quality hints. For best results use + * integer scaling factors. + * + * \param renderer a rendering context. + * \param scaleX the horizontal scaling factor. + * \param scaleY the vertical scaling factor. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderGetScale + * \sa SDL_RenderSetLogicalSize + */ +extern DECLSPEC int SDLCALL SDL_RenderSetScale(SDL_Renderer * renderer, + float scaleX, float scaleY); + +/** + * Get the drawing scale for the current target. + * + * \param renderer the renderer from which drawing scale should be queried. + * \param scaleX a pointer filled in with the horizontal scaling factor. + * \param scaleY a pointer filled in with the vertical scaling factor. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderSetScale + */ +extern DECLSPEC void SDLCALL SDL_RenderGetScale(SDL_Renderer * renderer, + float *scaleX, float *scaleY); + +/** + * Get logical coordinates of point in renderer when given real coordinates of + * point in window. + * + * Logical coordinates will differ from real coordinates when render is scaled + * and logical renderer size set + * + * \param renderer the renderer from which the logical coordinates should be + * calculated. + * \param windowX the real X coordinate in the window. + * \param windowY the real Y coordinate in the window. + * \param logicalX the pointer filled with the logical x coordinate. + * \param logicalY the pointer filled with the logical y coordinate. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_RenderGetScale + * \sa SDL_RenderSetScale + * \sa SDL_RenderGetLogicalSize + * \sa SDL_RenderSetLogicalSize + */ +extern DECLSPEC void SDLCALL SDL_RenderWindowToLogical(SDL_Renderer * renderer, + int windowX, int windowY, + float *logicalX, float *logicalY); + + +/** + * Get real coordinates of point in window when given logical coordinates of + * point in renderer. + * + * Logical coordinates will differ from real coordinates when render is scaled + * and logical renderer size set + * + * \param renderer the renderer from which the window coordinates should be + * calculated. + * \param logicalX the logical x coordinate. + * \param logicalY the logical y coordinate. + * \param windowX the pointer filled with the real X coordinate in the window. + * \param windowY the pointer filled with the real Y coordinate in the window. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_RenderGetScale + * \sa SDL_RenderSetScale + * \sa SDL_RenderGetLogicalSize + * \sa SDL_RenderSetLogicalSize + */ +extern DECLSPEC void SDLCALL SDL_RenderLogicalToWindow(SDL_Renderer * renderer, + float logicalX, float logicalY, + int *windowX, int *windowY); + +/** + * Set the color used for drawing operations (Rect, Line and Clear). + * + * Set the color for drawing or filling rectangles, lines, and points, and for + * SDL_RenderClear(). + * + * \param renderer the rendering context. + * \param r the red value used to draw on the rendering target. + * \param g the green value used to draw on the rendering target. + * \param b the blue value used to draw on the rendering target. + * \param a the alpha value used to draw on the rendering target; usually + * `SDL_ALPHA_OPAQUE` (255). Use SDL_SetRenderDrawBlendMode to + * specify how the alpha channel is used. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRenderDrawColor + * \sa SDL_RenderClear + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + */ +extern DECLSPEC int SDLCALL SDL_SetRenderDrawColor(SDL_Renderer * renderer, + Uint8 r, Uint8 g, Uint8 b, + Uint8 a); + +/** + * Get the color used for drawing operations (Rect, Line and Clear). + * + * \param renderer the rendering context. + * \param r a pointer filled in with the red value used to draw on the + * rendering target. + * \param g a pointer filled in with the green value used to draw on the + * rendering target. + * \param b a pointer filled in with the blue value used to draw on the + * rendering target. + * \param a a pointer filled in with the alpha value used to draw on the + * rendering target; usually `SDL_ALPHA_OPAQUE` (255). + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_GetRenderDrawColor(SDL_Renderer * renderer, + Uint8 * r, Uint8 * g, Uint8 * b, + Uint8 * a); + +/** + * Set the blend mode used for drawing operations (Fill and Line). + * + * If the blend mode is not supported, the closest supported mode is chosen. + * + * \param renderer the rendering context. + * \param blendMode the SDL_BlendMode to use for blending. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRenderDrawBlendMode + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + */ +extern DECLSPEC int SDLCALL SDL_SetRenderDrawBlendMode(SDL_Renderer * renderer, + SDL_BlendMode blendMode); + +/** + * Get the blend mode used for drawing operations. + * + * \param renderer the rendering context. + * \param blendMode a pointer filled in with the current SDL_BlendMode. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetRenderDrawBlendMode + */ +extern DECLSPEC int SDLCALL SDL_GetRenderDrawBlendMode(SDL_Renderer * renderer, + SDL_BlendMode *blendMode); + +/** + * Clear the current rendering target with the drawing color. + * + * This function clears the entire rendering target, ignoring the viewport and + * the clip rectangle. + * + * \param renderer the rendering context. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_RenderClear(SDL_Renderer * renderer); + +/** + * Draw a point on the current rendering target. + * + * SDL_RenderDrawPoint() draws a single point. If you want to draw multiple, + * use SDL_RenderDrawPoints() instead. + * + * \param renderer the rendering context. + * \param x the x coordinate of the point. + * \param y the y coordinate of the point. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + * \sa SDL_RenderPresent + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawPoint(SDL_Renderer * renderer, + int x, int y); + +/** + * Draw multiple points on the current rendering target. + * + * \param renderer the rendering context. + * \param points an array of SDL_Point structures that represent the points to + * draw. + * \param count the number of points to draw. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + * \sa SDL_RenderPresent + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawPoints(SDL_Renderer * renderer, + const SDL_Point * points, + int count); + +/** + * Draw a line on the current rendering target. + * + * SDL_RenderDrawLine() draws the line to include both end points. If you want + * to draw multiple, connecting lines use SDL_RenderDrawLines() instead. + * + * \param renderer the rendering context. + * \param x1 the x coordinate of the start point. + * \param y1 the y coordinate of the start point. + * \param x2 the x coordinate of the end point. + * \param y2 the y coordinate of the end point. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + * \sa SDL_RenderPresent + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawLine(SDL_Renderer * renderer, + int x1, int y1, int x2, int y2); + +/** + * Draw a series of connected lines on the current rendering target. + * + * \param renderer the rendering context. + * \param points an array of SDL_Point structures representing points along + * the lines. + * \param count the number of points, drawing count-1 lines. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + * \sa SDL_RenderPresent + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawLines(SDL_Renderer * renderer, + const SDL_Point * points, + int count); + +/** + * Draw a rectangle on the current rendering target. + * + * \param renderer the rendering context. + * \param rect an SDL_Rect structure representing the rectangle to draw, or + * NULL to outline the entire rendering target. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + * \sa SDL_RenderPresent + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawRect(SDL_Renderer * renderer, + const SDL_Rect * rect); + +/** + * Draw some number of rectangles on the current rendering target. + * + * \param renderer the rendering context. + * \param rects an array of SDL_Rect structures representing the rectangles to + * be drawn. + * \param count the number of rectangles. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + * \sa SDL_RenderPresent + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawRects(SDL_Renderer * renderer, + const SDL_Rect * rects, + int count); + +/** + * Fill a rectangle on the current rendering target with the drawing color. + * + * The current drawing color is set by SDL_SetRenderDrawColor(), and the + * color's alpha value is ignored unless blending is enabled with the + * appropriate call to SDL_SetRenderDrawBlendMode(). + * + * \param renderer the rendering context. + * \param rect the SDL_Rect structure representing the rectangle to fill, or + * NULL for the entire rendering target. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRects + * \sa SDL_RenderPresent + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC int SDLCALL SDL_RenderFillRect(SDL_Renderer * renderer, + const SDL_Rect * rect); + +/** + * Fill some number of rectangles on the current rendering target with the + * drawing color. + * + * \param renderer the rendering context. + * \param rects an array of SDL_Rect structures representing the rectangles to + * be filled. + * \param count the number of rectangles. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderPresent + */ +extern DECLSPEC int SDLCALL SDL_RenderFillRects(SDL_Renderer * renderer, + const SDL_Rect * rects, + int count); + +/** + * Copy a portion of the texture to the current rendering target. + * + * The texture is blended with the destination based on its blend mode set + * with SDL_SetTextureBlendMode(). + * + * The texture color is affected based on its color modulation set by + * SDL_SetTextureColorMod(). + * + * The texture alpha is affected based on its alpha modulation set by + * SDL_SetTextureAlphaMod(). + * + * \param renderer the rendering context. + * \param texture the source texture. + * \param srcrect the source SDL_Rect structure or NULL for the entire + * texture. + * \param dstrect the destination SDL_Rect structure or NULL for the entire + * rendering target; the texture will be stretched to fill the + * given rectangle. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderCopyEx + * \sa SDL_SetTextureAlphaMod + * \sa SDL_SetTextureBlendMode + * \sa SDL_SetTextureColorMod + */ +extern DECLSPEC int SDLCALL SDL_RenderCopy(SDL_Renderer * renderer, + SDL_Texture * texture, + const SDL_Rect * srcrect, + const SDL_Rect * dstrect); + +/** + * Copy a portion of the texture to the current rendering, with optional + * rotation and flipping. + * + * Copy a portion of the texture to the current rendering target, optionally + * rotating it by angle around the given center and also flipping it + * top-bottom and/or left-right. + * + * The texture is blended with the destination based on its blend mode set + * with SDL_SetTextureBlendMode(). + * + * The texture color is affected based on its color modulation set by + * SDL_SetTextureColorMod(). + * + * The texture alpha is affected based on its alpha modulation set by + * SDL_SetTextureAlphaMod(). + * + * \param renderer the rendering context. + * \param texture the source texture. + * \param srcrect the source SDL_Rect structure or NULL for the entire + * texture. + * \param dstrect the destination SDL_Rect structure or NULL for the entire + * rendering target. + * \param angle an angle in degrees that indicates the rotation that will be + * applied to dstrect, rotating it in a clockwise direction. + * \param center a pointer to a point indicating the point around which + * dstrect will be rotated (if NULL, rotation will be done + * around `dstrect.w / 2`, `dstrect.h / 2`). + * \param flip a SDL_RendererFlip value stating which flipping actions should + * be performed on the texture. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RenderCopy + * \sa SDL_SetTextureAlphaMod + * \sa SDL_SetTextureBlendMode + * \sa SDL_SetTextureColorMod + */ +extern DECLSPEC int SDLCALL SDL_RenderCopyEx(SDL_Renderer * renderer, + SDL_Texture * texture, + const SDL_Rect * srcrect, + const SDL_Rect * dstrect, + const double angle, + const SDL_Point *center, + const SDL_RendererFlip flip); + + +/** + * Draw a point on the current rendering target at subpixel precision. + * + * \param renderer The renderer which should draw a point. + * \param x The x coordinate of the point. + * \param y The y coordinate of the point. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawPointF(SDL_Renderer * renderer, + float x, float y); + +/** + * Draw multiple points on the current rendering target at subpixel precision. + * + * \param renderer The renderer which should draw multiple points. + * \param points The points to draw. + * \param count The number of points to draw. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawPointsF(SDL_Renderer * renderer, + const SDL_FPoint * points, + int count); + +/** + * Draw a line on the current rendering target at subpixel precision. + * + * \param renderer The renderer which should draw a line. + * \param x1 The x coordinate of the start point. + * \param y1 The y coordinate of the start point. + * \param x2 The x coordinate of the end point. + * \param y2 The y coordinate of the end point. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawLineF(SDL_Renderer * renderer, + float x1, float y1, float x2, float y2); + +/** + * Draw a series of connected lines on the current rendering target at + * subpixel precision. + * + * \param renderer The renderer which should draw multiple lines. + * \param points The points along the lines. + * \param count The number of points, drawing count-1 lines. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawLinesF(SDL_Renderer * renderer, + const SDL_FPoint * points, + int count); + +/** + * Draw a rectangle on the current rendering target at subpixel precision. + * + * \param renderer The renderer which should draw a rectangle. + * \param rect A pointer to the destination rectangle, or NULL to outline the + * entire rendering target. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawRectF(SDL_Renderer * renderer, + const SDL_FRect * rect); + +/** + * Draw some number of rectangles on the current rendering target at subpixel + * precision. + * + * \param renderer The renderer which should draw multiple rectangles. + * \param rects A pointer to an array of destination rectangles. + * \param count The number of rectangles. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderDrawRectsF(SDL_Renderer * renderer, + const SDL_FRect * rects, + int count); + +/** + * Fill a rectangle on the current rendering target with the drawing color at + * subpixel precision. + * + * \param renderer The renderer which should fill a rectangle. + * \param rect A pointer to the destination rectangle, or NULL for the entire + * rendering target. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderFillRectF(SDL_Renderer * renderer, + const SDL_FRect * rect); + +/** + * Fill some number of rectangles on the current rendering target with the + * drawing color at subpixel precision. + * + * \param renderer The renderer which should fill multiple rectangles. + * \param rects A pointer to an array of destination rectangles. + * \param count The number of rectangles. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderFillRectsF(SDL_Renderer * renderer, + const SDL_FRect * rects, + int count); + +/** + * Copy a portion of the texture to the current rendering target at subpixel + * precision. + * + * \param renderer The renderer which should copy parts of a texture. + * \param texture The source texture. + * \param srcrect A pointer to the source rectangle, or NULL for the entire + * texture. + * \param dstrect A pointer to the destination rectangle, or NULL for the + * entire rendering target. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderCopyF(SDL_Renderer * renderer, + SDL_Texture * texture, + const SDL_Rect * srcrect, + const SDL_FRect * dstrect); + +/** + * Copy a portion of the source texture to the current rendering target, with + * rotation and flipping, at subpixel precision. + * + * \param renderer The renderer which should copy parts of a texture. + * \param texture The source texture. + * \param srcrect A pointer to the source rectangle, or NULL for the entire + * texture. + * \param dstrect A pointer to the destination rectangle, or NULL for the + * entire rendering target. + * \param angle An angle in degrees that indicates the rotation that will be + * applied to dstrect, rotating it in a clockwise direction. + * \param center A pointer to a point indicating the point around which + * dstrect will be rotated (if NULL, rotation will be done + * around dstrect.w/2, dstrect.h/2). + * \param flip An SDL_RendererFlip value stating which flipping actions should + * be performed on the texture. + * \return 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderCopyExF(SDL_Renderer * renderer, + SDL_Texture * texture, + const SDL_Rect * srcrect, + const SDL_FRect * dstrect, + const double angle, + const SDL_FPoint *center, + const SDL_RendererFlip flip); + +/** + * Render a list of triangles, optionally using a texture and indices into the + * vertex array Color and alpha modulation is done per vertex + * (SDL_SetTextureColorMod and SDL_SetTextureAlphaMod are ignored). + * + * \param renderer The rendering context. + * \param texture (optional) The SDL texture to use. + * \param vertices Vertices. + * \param num_vertices Number of vertices. + * \param indices (optional) An array of integer indices into the 'vertices' + * array, if NULL all vertices will be rendered in sequential + * order. + * \param num_indices Number of indices. + * \return 0 on success, or -1 if the operation is not supported. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_RenderGeometryRaw + * \sa SDL_Vertex + */ +extern DECLSPEC int SDLCALL SDL_RenderGeometry(SDL_Renderer *renderer, + SDL_Texture *texture, + const SDL_Vertex *vertices, int num_vertices, + const int *indices, int num_indices); + +/** + * Render a list of triangles, optionally using a texture and indices into the + * vertex arrays Color and alpha modulation is done per vertex + * (SDL_SetTextureColorMod and SDL_SetTextureAlphaMod are ignored). + * + * \param renderer The rendering context. + * \param texture (optional) The SDL texture to use. + * \param xy Vertex positions. + * \param xy_stride Byte size to move from one element to the next element. + * \param color Vertex colors (as SDL_Color). + * \param color_stride Byte size to move from one element to the next element. + * \param uv Vertex normalized texture coordinates. + * \param uv_stride Byte size to move from one element to the next element. + * \param num_vertices Number of vertices. + * \param indices (optional) An array of indices into the 'vertices' arrays, + * if NULL all vertices will be rendered in sequential order. + * \param num_indices Number of indices. + * \param size_indices Index size: 1 (byte), 2 (short), 4 (int). + * \return 0 on success, or -1 if the operation is not supported. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_RenderGeometry + * \sa SDL_Vertex + */ +extern DECLSPEC int SDLCALL SDL_RenderGeometryRaw(SDL_Renderer *renderer, + SDL_Texture *texture, + const float *xy, int xy_stride, + const SDL_Color *color, int color_stride, + const float *uv, int uv_stride, + int num_vertices, + const void *indices, int num_indices, int size_indices); + +/** + * Read pixels from the current rendering target to an array of pixels. + * + * **WARNING**: This is a very slow operation, and should not be used + * frequently. If you're using this on the main rendering target, it should be + * called after rendering and before SDL_RenderPresent(). + * + * `pitch` specifies the number of bytes between rows in the destination + * `pixels` data. This allows you to write to a subrectangle or have padded + * rows in the destination. Generally, `pitch` should equal the number of + * pixels per row in the `pixels` data times the number of bytes per pixel, + * but it might contain additional padding (for example, 24bit RGB Windows + * Bitmap data pads all rows to multiples of 4 bytes). + * + * \param renderer the rendering context. + * \param rect an SDL_Rect structure representing the area to read, or NULL + * for the entire render target. + * \param format an SDL_PixelFormatEnum value of the desired format of the + * pixel data, or 0 to use the format of the rendering target. + * \param pixels a pointer to the pixel data to copy into. + * \param pitch the pitch of the `pixels` parameter. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_RenderReadPixels(SDL_Renderer * renderer, + const SDL_Rect * rect, + Uint32 format, + void *pixels, int pitch); + +/** + * Update the screen with any rendering performed since the previous call. + * + * SDL's rendering functions operate on a backbuffer; that is, calling a + * rendering function such as SDL_RenderDrawLine() does not directly put a + * line on the screen, but rather updates the backbuffer. As such, you compose + * your entire scene and *present* the composed backbuffer to the screen as a + * complete picture. + * + * Therefore, when using SDL's rendering API, one does all drawing intended + * for the frame, and then calls this function once per frame to present the + * final drawing to the user. + * + * The backbuffer should be considered invalidated after each present; do not + * assume that previous contents will exist between frames. You are strongly + * encouraged to call SDL_RenderClear() to initialize the backbuffer before + * starting each new frame's drawing, even if you plan to overwrite every + * pixel. + * + * \param renderer the rendering context. + * + * \threadsafety You may only call this function on the main thread. If this + * happens to work on a background thread on any given platform + * or backend, it's purely by luck and you should not rely on it + * to work next time. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRenderer + * \sa SDL_RenderClear + * \sa SDL_RenderDrawLine + * \sa SDL_RenderDrawLines + * \sa SDL_RenderDrawPoint + * \sa SDL_RenderDrawPoints + * \sa SDL_RenderDrawRect + * \sa SDL_RenderDrawRects + * \sa SDL_RenderFillRect + * \sa SDL_RenderFillRects + * \sa SDL_SetRenderDrawBlendMode + * \sa SDL_SetRenderDrawColor + */ +extern DECLSPEC void SDLCALL SDL_RenderPresent(SDL_Renderer * renderer); + +/** + * Destroy the specified texture. + * + * Passing NULL or an otherwise invalid texture will set the SDL error message + * to "Invalid texture". + * + * \param texture the texture to destroy. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateTexture + * \sa SDL_CreateTextureFromSurface + */ +extern DECLSPEC void SDLCALL SDL_DestroyTexture(SDL_Texture * texture); + +/** + * Destroy the rendering context for a window and free associated textures. + * + * If `renderer` is NULL, this function will return immediately after setting + * the SDL error message to "Invalid renderer". See SDL_GetError(). + * + * \param renderer the rendering context. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRenderer + */ +extern DECLSPEC void SDLCALL SDL_DestroyRenderer(SDL_Renderer * renderer); + +/** + * Force the rendering context to flush any pending commands to the underlying + * rendering API. + * + * You do not need to (and in fact, shouldn't) call this function unless you + * are planning to call into OpenGL/Direct3D/Metal/whatever directly in + * addition to using an SDL_Renderer. + * + * This is for a very-specific case: if you are using SDL's render API, you + * asked for a specific renderer backend (OpenGL, Direct3D, etc), you set + * SDL_HINT_RENDER_BATCHING to "1", and you plan to make OpenGL/D3D/whatever + * calls in addition to SDL render API calls. If all of this applies, you + * should call SDL_RenderFlush() between calls to SDL's render API and the + * low-level API you're using in cooperation. + * + * In all other cases, you can ignore this function. This is only here to get + * maximum performance out of a specific situation. In all other cases, SDL + * will do the right thing, perhaps at a performance loss. + * + * This function is first available in SDL 2.0.10, and is not needed in 2.0.9 + * and earlier, as earlier versions did not queue rendering commands at all, + * instead flushing them to the OS immediately. + * + * \param renderer the rendering context. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC int SDLCALL SDL_RenderFlush(SDL_Renderer * renderer); + + +/** + * Bind an OpenGL/ES/ES2 texture to the current context. + * + * This is for use with OpenGL instructions when rendering OpenGL primitives + * directly. + * + * If not NULL, `texw` and `texh` will be filled with the width and height + * values suitable for the provided texture. In most cases, both will be 1.0, + * however, on systems that support the GL_ARB_texture_rectangle extension, + * these values will actually be the pixel width and height used to create the + * texture, so this factor needs to be taken into account when providing + * texture coordinates to OpenGL. + * + * You need a renderer to create an SDL_Texture, therefore you can only use + * this function with an implicit OpenGL context from SDL_CreateRenderer(), + * not with your own OpenGL context. If you need control over your OpenGL + * context, you need to write your own texture-loading methods. + * + * Also note that SDL may upload RGB textures as BGR (or vice-versa), and + * re-order the color channels in the shaders phase, so the uploaded texture + * may have swapped color channels. + * + * \param texture the texture to bind to the current OpenGL/ES/ES2 context. + * \param texw a pointer to a float value which will be filled with the + * texture width or NULL if you don't need that value. + * \param texh a pointer to a float value which will be filled with the + * texture height or NULL if you don't need that value. + * \returns 0 on success, or -1 if the operation is not supported; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_MakeCurrent + * \sa SDL_GL_UnbindTexture + */ +extern DECLSPEC int SDLCALL SDL_GL_BindTexture(SDL_Texture *texture, float *texw, float *texh); + +/** + * Unbind an OpenGL/ES/ES2 texture from the current context. + * + * See SDL_GL_BindTexture() for examples on how to use these functions + * + * \param texture the texture to unbind from the current OpenGL/ES/ES2 + * context. + * \returns 0 on success, or -1 if the operation is not supported. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_BindTexture + * \sa SDL_GL_MakeCurrent + */ +extern DECLSPEC int SDLCALL SDL_GL_UnbindTexture(SDL_Texture *texture); + +/** + * Get the CAMetalLayer associated with the given Metal renderer. + * + * This function returns `void *`, so SDL doesn't have to include Metal's + * headers, but it can be safely cast to a `CAMetalLayer *`. + * + * \param renderer The renderer to query. + * \returns a `CAMetalLayer *` on success, or NULL if the renderer isn't a + * Metal renderer. + * + * \since This function is available since SDL 2.0.8. + * + * \sa SDL_RenderGetMetalCommandEncoder + */ +extern DECLSPEC void *SDLCALL SDL_RenderGetMetalLayer(SDL_Renderer * renderer); + +/** + * Get the Metal command encoder for the current frame + * + * This function returns `void *`, so SDL doesn't have to include Metal's + * headers, but it can be safely cast to an `id`. + * + * Note that as of SDL 2.0.18, this will return NULL if Metal refuses to give + * SDL a drawable to render to, which might happen if the window is + * hidden/minimized/offscreen. This doesn't apply to command encoders for + * render targets, just the window's backbuffer. Check your return values! + * + * \param renderer The renderer to query. + * \returns an `id` on success, or NULL if the + * renderer isn't a Metal renderer or there was an error. + * + * \since This function is available since SDL 2.0.8. + * + * \sa SDL_RenderGetMetalLayer + */ +extern DECLSPEC void *SDLCALL SDL_RenderGetMetalCommandEncoder(SDL_Renderer * renderer); + +/** + * Toggle VSync of the given renderer. + * + * \param renderer The renderer to toggle. + * \param vsync 1 for on, 0 for off. All other values are reserved. + * \returns a 0 int on success, or non-zero on failure. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_RenderSetVSync(SDL_Renderer* renderer, int vsync); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_render_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_revision.h b/third_party/SDL2/include/SDL_revision.h new file mode 100644 index 00000000000..a1e6edaa2d4 --- /dev/null +++ b/third_party/SDL2/include/SDL_revision.h @@ -0,0 +1,7 @@ +/* Generated by updaterev.sh, do not edit */ +#ifdef SDL_VENDOR_INFO +#define SDL_REVISION "SDL-release-2.32.0-0-g7a44b1ab0 (" SDL_VENDOR_INFO ")" +#else +#define SDL_REVISION "SDL-release-2.32.0-0-g7a44b1ab0" +#endif +#define SDL_REVISION_NUMBER 0 diff --git a/third_party/SDL2/include/SDL_revision.h.cmake b/third_party/SDL2/include/SDL_revision.h.cmake new file mode 100644 index 00000000000..84e5f414a83 --- /dev/null +++ b/third_party/SDL2/include/SDL_revision.h.cmake @@ -0,0 +1,8 @@ +#cmakedefine SDL_VENDOR_INFO "@SDL_VENDOR_INFO@" +#define SDL_REVISION_NUMBER 0 + +#ifdef SDL_VENDOR_INFO +#define SDL_REVISION "@SDL_REVISION@ (" SDL_VENDOR_INFO ")" +#else +#define SDL_REVISION "@SDL_REVISION@" +#endif diff --git a/third_party/SDL2/include/SDL_rwops.h b/third_party/SDL2/include/SDL_rwops.h new file mode 100644 index 00000000000..43c1b0ec777 --- /dev/null +++ b/third_party/SDL2/include/SDL_rwops.h @@ -0,0 +1,844 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: RWOPS */ + +/** + * # CategoryRWOPS + * + * This file provides a general interface for SDL to read and write data + * streams. It can easily be extended to files, memory, etc. + */ + +#ifndef SDL_rwops_h_ +#define SDL_rwops_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* RWops Types */ +#define SDL_RWOPS_UNKNOWN 0U /**< Unknown stream type */ +#define SDL_RWOPS_WINFILE 1U /**< Win32 file */ +#define SDL_RWOPS_STDFILE 2U /**< Stdio file */ +#define SDL_RWOPS_JNIFILE 3U /**< Android asset */ +#define SDL_RWOPS_MEMORY 4U /**< Memory stream */ +#define SDL_RWOPS_MEMORY_RO 5U /**< Read-Only memory stream */ + +/** + * This is the read/write operation structure -- very basic. + */ +typedef struct SDL_RWops +{ + /** + * Return the size of the file in this rwops, or -1 if unknown + */ + Sint64 (SDLCALL * size) (struct SDL_RWops * context); + + /** + * Seek to `offset` relative to `whence`, one of stdio's whence values: + * RW_SEEK_SET, RW_SEEK_CUR, RW_SEEK_END + * + * \return the final offset in the data stream, or -1 on error. + */ + Sint64 (SDLCALL * seek) (struct SDL_RWops * context, Sint64 offset, + int whence); + + /** + * Read up to `maxnum` objects each of size `size` from the data + * stream to the area pointed at by `ptr`. + * + * \return the number of objects read, or 0 at error or end of file. + */ + size_t (SDLCALL * read) (struct SDL_RWops * context, void *ptr, + size_t size, size_t maxnum); + + /** + * Write exactly `num` objects each of size `size` from the area + * pointed at by `ptr` to data stream. + * + * \return the number of objects written, or 0 at error or end of file. + */ + size_t (SDLCALL * write) (struct SDL_RWops * context, const void *ptr, + size_t size, size_t num); + + /** + * Close and free an allocated SDL_RWops structure. + * + * \return 0 if successful or -1 on write error when flushing data. + */ + int (SDLCALL * close) (struct SDL_RWops * context); + + Uint32 type; + union + { +#if defined(__ANDROID__) + struct + { + void *asset; + } androidio; +#elif defined(__WIN32__) || defined(__GDK__) + struct + { + SDL_bool append; + void *h; + struct + { + void *data; + size_t size; + size_t left; + } buffer; + } windowsio; +#endif + +#ifdef HAVE_STDIO_H + struct + { + SDL_bool autoclose; + FILE *fp; + } stdio; +#endif + struct + { + Uint8 *base; + Uint8 *here; + Uint8 *stop; + } mem; + struct + { + void *data1; + void *data2; + } unknown; + } hidden; + +} SDL_RWops; + + +/** + * \name RWFrom functions + * + * Functions to create SDL_RWops structures from various data streams. + */ +/* @{ */ + +/** + * Use this function to create a new SDL_RWops structure for reading from + * and/or writing to a named file. + * + * The `mode` string is treated roughly the same as in a call to the C + * library's fopen(), even if SDL doesn't happen to use fopen() behind the + * scenes. + * + * Available `mode` strings: + * + * - "r": Open a file for reading. The file must exist. + * - "w": Create an empty file for writing. If a file with the same name + * already exists its content is erased and the file is treated as a new + * empty file. + * - "a": Append to a file. Writing operations append data at the end of the + * file. The file is created if it does not exist. + * - "r+": Open a file for update both reading and writing. The file must + * exist. + * - "w+": Create an empty file for both reading and writing. If a file with + * the same name already exists its content is erased and the file is + * treated as a new empty file. + * - "a+": Open a file for reading and appending. All writing operations are + * performed at the end of the file, protecting the previous content to be + * overwritten. You can reposition (fseek, rewind) the internal pointer to + * anywhere in the file for reading, but writing operations will move it + * back to the end of file. The file is created if it does not exist. + * + * **NOTE**: In order to open a file as a binary file, a "b" character has to + * be included in the `mode` string. This additional "b" character can either + * be appended at the end of the string (thus making the following compound + * modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or be inserted between the + * letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+"). + * Additional characters may follow the sequence, although they should have no + * effect. For example, "t" is sometimes appended to make explicit the file is + * a text file. + * + * This function supports Unicode filenames, but they must be encoded in UTF-8 + * format, regardless of the underlying operating system. + * + * As a fallback, SDL_RWFromFile() will transparently open a matching filename + * in an Android app's `assets`. + * + * Closing the SDL_RWops will close the file handle SDL is holding internally. + * + * \param file a UTF-8 string representing the filename to open. + * \param mode an ASCII string representing the mode to be used for opening + * the file. + * \returns a pointer to the SDL_RWops structure that is created, or NULL on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RWclose + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFP + * \sa SDL_RWFromMem + * \sa SDL_RWread + * \sa SDL_RWseek + * \sa SDL_RWtell + * \sa SDL_RWwrite + */ +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFile(const char *file, + const char *mode); + +#ifdef HAVE_STDIO_H + +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(FILE * fp, SDL_bool autoclose); + +#else + +/** + * Use this function to create an SDL_RWops structure from a standard I/O file + * pointer (stdio.h's `FILE*`). + * + * This function is not available on Windows, since files opened in an + * application on that platform cannot be used by a dynamically linked + * library. + * + * On some platforms, the first parameter is a `void*`, on others, it's a + * `FILE*`, depending on what system headers are available to SDL. It is + * always intended to be the `FILE*` type from the C runtime's stdio.h. + * + * \param fp the `FILE*` that feeds the SDL_RWops stream. + * \param autoclose SDL_TRUE to close the `FILE*` when closing the SDL_RWops, + * SDL_FALSE to leave the `FILE*` open when the RWops is + * closed. + * \returns a pointer to the SDL_RWops structure that is created, or NULL on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RWclose + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFile + * \sa SDL_RWFromMem + * \sa SDL_RWread + * \sa SDL_RWseek + * \sa SDL_RWtell + * \sa SDL_RWwrite + */ +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromFP(void * fp, + SDL_bool autoclose); +#endif + +/** + * Use this function to prepare a read-write memory buffer for use with + * SDL_RWops. + * + * This function sets up an SDL_RWops struct based on a memory area of a + * certain size, for both read and write access. + * + * This memory buffer is not copied by the RWops; the pointer you provide must + * remain valid until you close the stream. Closing the stream will not free + * the original buffer. + * + * If you need to make sure the RWops never writes to the memory buffer, you + * should use SDL_RWFromConstMem() with a read-only buffer of memory instead. + * + * \param mem a pointer to a buffer to feed an SDL_RWops stream. + * \param size the buffer size, in bytes. + * \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RWclose + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFile + * \sa SDL_RWFromFP + * \sa SDL_RWFromMem + * \sa SDL_RWread + * \sa SDL_RWseek + * \sa SDL_RWtell + * \sa SDL_RWwrite + */ +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromMem(void *mem, int size); + +/** + * Use this function to prepare a read-only memory buffer for use with RWops. + * + * This function sets up an SDL_RWops struct based on a memory area of a + * certain size. It assumes the memory area is not writable. + * + * Attempting to write to this RWops stream will report an error without + * writing to the memory buffer. + * + * This memory buffer is not copied by the RWops; the pointer you provide must + * remain valid until you close the stream. Closing the stream will not free + * the original buffer. + * + * If you need to write to a memory buffer, you should use SDL_RWFromMem() + * with a writable buffer of memory instead. + * + * \param mem a pointer to a read-only buffer to feed an SDL_RWops stream. + * \param size the buffer size, in bytes. + * \returns a pointer to a new SDL_RWops structure, or NULL if it fails; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RWclose + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFile + * \sa SDL_RWFromFP + * \sa SDL_RWFromMem + * \sa SDL_RWread + * \sa SDL_RWseek + * \sa SDL_RWtell + */ +extern DECLSPEC SDL_RWops *SDLCALL SDL_RWFromConstMem(const void *mem, + int size); + +/* @} *//* RWFrom functions */ + + +/** + * Use this function to allocate an empty, unpopulated SDL_RWops structure. + * + * Applications do not need to use this function unless they are providing + * their own SDL_RWops implementation. If you just need a SDL_RWops to + * read/write a common data source, you should use the built-in + * implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc. + * + * You must free the returned pointer with SDL_FreeRW(). Depending on your + * operating system and compiler, there may be a difference between the + * malloc() and free() your program uses and the versions SDL calls + * internally. Trying to mix the two can cause crashing such as segmentation + * faults. Since all SDL_RWops must free themselves when their **close** + * method is called, all SDL_RWops must be allocated through this function, so + * they can all be freed correctly with SDL_FreeRW(). + * + * \returns a pointer to the allocated memory on success, or NULL on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FreeRW + */ +extern DECLSPEC SDL_RWops *SDLCALL SDL_AllocRW(void); + +/** + * Use this function to free an SDL_RWops structure allocated by + * SDL_AllocRW(). + * + * Applications do not need to use this function unless they are providing + * their own SDL_RWops implementation. If you just need a SDL_RWops to + * read/write a common data source, you should use the built-in + * implementations in SDL, like SDL_RWFromFile() or SDL_RWFromMem(), etc, and + * call the **close** method on those SDL_RWops pointers when you are done + * with them. + * + * Only use SDL_FreeRW() on pointers returned by SDL_AllocRW(). The pointer is + * invalid as soon as this function returns. Any extra memory allocated during + * creation of the SDL_RWops is not freed by SDL_FreeRW(); the programmer must + * be responsible for managing that memory in their **close** method. + * + * \param area the SDL_RWops structure to be freed. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AllocRW + */ +extern DECLSPEC void SDLCALL SDL_FreeRW(SDL_RWops * area); + +/* Possible `whence` values for SDL_RWops seeking... */ +#define RW_SEEK_SET 0 /**< Seek from the beginning of data */ +#define RW_SEEK_CUR 1 /**< Seek relative to current read point */ +#define RW_SEEK_END 2 /**< Seek relative to the end of data */ + +/** + * Use this function to get the size of the data stream in an SDL_RWops. + * + * Prior to SDL 2.0.10, this function was a macro. + * + * \param context the SDL_RWops to get the size of the data stream from. + * \returns the size of the data stream in the SDL_RWops on success, -1 if + * unknown or a negative error code on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC Sint64 SDLCALL SDL_RWsize(SDL_RWops *context); + +/** + * Seek within an SDL_RWops data stream. + * + * This function seeks to byte `offset`, relative to `whence`. + * + * `whence` may be any of the following values: + * + * - `RW_SEEK_SET`: seek from the beginning of data + * - `RW_SEEK_CUR`: seek relative to current read point + * - `RW_SEEK_END`: seek relative to the end of data + * + * If this stream can not seek, it will return -1. + * + * SDL_RWseek() is actually a wrapper function that calls the SDL_RWops's + * `seek` method appropriately, to simplify application development. + * + * Prior to SDL 2.0.10, this function was a macro. + * + * \param context a pointer to an SDL_RWops structure. + * \param offset an offset in bytes, relative to **whence** location; can be + * negative. + * \param whence any of `RW_SEEK_SET`, `RW_SEEK_CUR`, `RW_SEEK_END`. + * \returns the final offset in the data stream after the seek or -1 on error. + * + * \since This function is available since SDL 2.0.10. + * + * \sa SDL_RWclose + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFile + * \sa SDL_RWFromFP + * \sa SDL_RWFromMem + * \sa SDL_RWread + * \sa SDL_RWtell + * \sa SDL_RWwrite + */ +extern DECLSPEC Sint64 SDLCALL SDL_RWseek(SDL_RWops *context, + Sint64 offset, int whence); + +/** + * Determine the current read/write offset in an SDL_RWops data stream. + * + * SDL_RWtell is actually a wrapper function that calls the SDL_RWops's `seek` + * method, with an offset of 0 bytes from `RW_SEEK_CUR`, to simplify + * application development. + * + * Prior to SDL 2.0.10, this function was a macro. + * + * \param context a SDL_RWops data stream object from which to get the current + * offset. + * \returns the current offset in the stream, or -1 if the information can not + * be determined. + * + * \since This function is available since SDL 2.0.10. + * + * \sa SDL_RWclose + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFile + * \sa SDL_RWFromFP + * \sa SDL_RWFromMem + * \sa SDL_RWread + * \sa SDL_RWseek + * \sa SDL_RWwrite + */ +extern DECLSPEC Sint64 SDLCALL SDL_RWtell(SDL_RWops *context); + +/** + * Read from a data source. + * + * This function reads up to `maxnum` objects each of size `size` from the + * data source to the area pointed at by `ptr`. This function may read less + * objects than requested. It will return zero when there has been an error or + * the data stream is completely read. + * + * SDL_RWread() is actually a function wrapper that calls the SDL_RWops's + * `read` method appropriately, to simplify application development. + * + * Prior to SDL 2.0.10, this function was a macro. + * + * \param context a pointer to an SDL_RWops structure. + * \param ptr a pointer to a buffer to read data into. + * \param size the size of each object to read, in bytes. + * \param maxnum the maximum number of objects to be read. + * \returns the number of objects read, or 0 at error or end of file; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.10. + * + * \sa SDL_RWclose + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFile + * \sa SDL_RWFromFP + * \sa SDL_RWFromMem + * \sa SDL_RWseek + * \sa SDL_RWwrite + */ +extern DECLSPEC size_t SDLCALL SDL_RWread(SDL_RWops *context, + void *ptr, size_t size, + size_t maxnum); + +/** + * Write to an SDL_RWops data stream. + * + * This function writes exactly `num` objects each of size `size` from the + * area pointed at by `ptr` to the stream. If this fails for any reason, it'll + * return less than `num` to demonstrate how far the write progressed. On + * success, it returns `num`. + * + * SDL_RWwrite is actually a function wrapper that calls the SDL_RWops's + * `write` method appropriately, to simplify application development. + * + * Prior to SDL 2.0.10, this function was a macro. + * + * \param context a pointer to an SDL_RWops structure. + * \param ptr a pointer to a buffer containing data to write. + * \param size the size of an object to write, in bytes. + * \param num the number of objects to write. + * \returns the number of objects written, which will be less than **num** on + * error; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.10. + * + * \sa SDL_RWclose + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFile + * \sa SDL_RWFromFP + * \sa SDL_RWFromMem + * \sa SDL_RWread + * \sa SDL_RWseek + */ +extern DECLSPEC size_t SDLCALL SDL_RWwrite(SDL_RWops *context, + const void *ptr, size_t size, + size_t num); + +/** + * Close and free an allocated SDL_RWops structure. + * + * SDL_RWclose() closes and cleans up the SDL_RWops stream. It releases any + * resources used by the stream and frees the SDL_RWops itself with + * SDL_FreeRW(). This returns 0 on success, or -1 if the stream failed to + * flush to its output (e.g. to disk). + * + * Note that if this fails to flush the stream to disk, this function reports + * an error, but the SDL_RWops is still invalid once this function returns. + * + * Prior to SDL 2.0.10, this function was a macro. + * + * \param context SDL_RWops structure to close. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.10. + * + * \sa SDL_RWFromConstMem + * \sa SDL_RWFromFile + * \sa SDL_RWFromFP + * \sa SDL_RWFromMem + * \sa SDL_RWread + * \sa SDL_RWseek + * \sa SDL_RWwrite + */ +extern DECLSPEC int SDLCALL SDL_RWclose(SDL_RWops *context); + +/** + * Load all the data from an SDL data stream. + * + * The data is allocated with a zero byte at the end (null terminated) for + * convenience. This extra byte is not included in the value reported via + * `datasize`. + * + * The data should be freed with SDL_free(). + * + * \param src the SDL_RWops to read all available data from. + * \param datasize if not NULL, will store the number of bytes read. + * \param freesrc if non-zero, calls SDL_RWclose() on `src` before returning. + * \returns the data, or NULL if there was an error. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC void *SDLCALL SDL_LoadFile_RW(SDL_RWops *src, + size_t *datasize, + int freesrc); + +/** + * Load all the data from a file path. + * + * The data is allocated with a zero byte at the end (null terminated) for + * convenience. This extra byte is not included in the value reported via + * `datasize`. + * + * The data should be freed with SDL_free(). + * + * Prior to SDL 2.0.10, this function was a macro wrapping around + * SDL_LoadFile_RW. + * + * \param file the path to read all available data from. + * \param datasize if not NULL, will store the number of bytes read. + * \returns the data, or NULL if there was an error. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC void *SDLCALL SDL_LoadFile(const char *file, size_t *datasize); + +/** + * \name Read endian functions + * + * Read an item of the specified endianness and return in native format. + */ +/* @{ */ + +/** + * Use this function to read a byte from an SDL_RWops. + * + * \param src the SDL_RWops to read from. + * \returns the read byte on success or 0 on failure; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WriteU8 + */ +extern DECLSPEC Uint8 SDLCALL SDL_ReadU8(SDL_RWops * src); + +/** + * Use this function to read 16 bits of little-endian data from an SDL_RWops + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * \param src the stream from which to read data. + * \returns 16 bits of data in the native byte order of the platform. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ReadBE16 + */ +extern DECLSPEC Uint16 SDLCALL SDL_ReadLE16(SDL_RWops * src); + +/** + * Use this function to read 16 bits of big-endian data from an SDL_RWops and + * return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * \param src the stream from which to read data. + * \returns 16 bits of data in the native byte order of the platform. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ReadLE16 + */ +extern DECLSPEC Uint16 SDLCALL SDL_ReadBE16(SDL_RWops * src); + +/** + * Use this function to read 32 bits of little-endian data from an SDL_RWops + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * \param src the stream from which to read data. + * \returns 32 bits of data in the native byte order of the platform. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ReadBE32 + */ +extern DECLSPEC Uint32 SDLCALL SDL_ReadLE32(SDL_RWops * src); + +/** + * Use this function to read 32 bits of big-endian data from an SDL_RWops and + * return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * \param src the stream from which to read data. + * \returns 32 bits of data in the native byte order of the platform. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ReadLE32 + */ +extern DECLSPEC Uint32 SDLCALL SDL_ReadBE32(SDL_RWops * src); + +/** + * Use this function to read 64 bits of little-endian data from an SDL_RWops + * and return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * \param src the stream from which to read data. + * \returns 64 bits of data in the native byte order of the platform. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ReadBE64 + */ +extern DECLSPEC Uint64 SDLCALL SDL_ReadLE64(SDL_RWops * src); + +/** + * Use this function to read 64 bits of big-endian data from an SDL_RWops and + * return in native format. + * + * SDL byteswaps the data only if necessary, so the data returned will be in + * the native byte order. + * + * \param src the stream from which to read data. + * \returns 64 bits of data in the native byte order of the platform. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ReadLE64 + */ +extern DECLSPEC Uint64 SDLCALL SDL_ReadBE64(SDL_RWops * src); +/* @} *//* Read endian functions */ + +/** + * \name Write endian functions + * + * Write an item of native format to the specified endianness. + */ +/* @{ */ + +/** + * Use this function to write a byte to an SDL_RWops. + * + * \param dst the SDL_RWops to write to. + * \param value the byte value to write. + * \returns 1 on success or 0 on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ReadU8 + */ +extern DECLSPEC size_t SDLCALL SDL_WriteU8(SDL_RWops * dst, Uint8 value); + +/** + * Use this function to write 16 bits in native format to a SDL_RWops as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns 1 on successful write, 0 on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WriteBE16 + */ +extern DECLSPEC size_t SDLCALL SDL_WriteLE16(SDL_RWops * dst, Uint16 value); + +/** + * Use this function to write 16 bits in native format to a SDL_RWops as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns 1 on successful write, 0 on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WriteLE16 + */ +extern DECLSPEC size_t SDLCALL SDL_WriteBE16(SDL_RWops * dst, Uint16 value); + +/** + * Use this function to write 32 bits in native format to a SDL_RWops as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns 1 on successful write, 0 on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WriteBE32 + */ +extern DECLSPEC size_t SDLCALL SDL_WriteLE32(SDL_RWops * dst, Uint32 value); + +/** + * Use this function to write 32 bits in native format to a SDL_RWops as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns 1 on successful write, 0 on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WriteLE32 + */ +extern DECLSPEC size_t SDLCALL SDL_WriteBE32(SDL_RWops * dst, Uint32 value); + +/** + * Use this function to write 64 bits in native format to a SDL_RWops as + * little-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in little-endian + * format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns 1 on successful write, 0 on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WriteBE64 + */ +extern DECLSPEC size_t SDLCALL SDL_WriteLE64(SDL_RWops * dst, Uint64 value); + +/** + * Use this function to write 64 bits in native format to a SDL_RWops as + * big-endian data. + * + * SDL byteswaps the data only if necessary, so the application always + * specifies native format, and the data written will be in big-endian format. + * + * \param dst the stream to which data will be written. + * \param value the data to be written, in native format. + * \returns 1 on successful write, 0 on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WriteLE64 + */ +extern DECLSPEC size_t SDLCALL SDL_WriteBE64(SDL_RWops * dst, Uint64 value); +/* @} *//* Write endian functions */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_rwops_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_scancode.h b/third_party/SDL2/include/SDL_scancode.h new file mode 100644 index 00000000000..0652d7ef66d --- /dev/null +++ b/third_party/SDL2/include/SDL_scancode.h @@ -0,0 +1,438 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryScancode + * + * Defines keyboard scancodes. + */ + +#ifndef SDL_scancode_h_ +#define SDL_scancode_h_ + +#include "SDL_stdinc.h" + +/** + * The SDL keyboard scancode representation. + * + * Values of this type are used to represent keyboard keys, among other places + * in the SDL_Keysym::scancode key.keysym.scancode field of the SDL_Event + * structure. + * + * The values in this enumeration are based on the USB usage page standard: + * https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf + */ +typedef enum SDL_Scancode +{ + SDL_SCANCODE_UNKNOWN = 0, + + /** + * \name Usage page 0x07 + * + * These values are from usage page 0x07 (USB keyboard page). + */ + /* @{ */ + + SDL_SCANCODE_A = 4, + SDL_SCANCODE_B = 5, + SDL_SCANCODE_C = 6, + SDL_SCANCODE_D = 7, + SDL_SCANCODE_E = 8, + SDL_SCANCODE_F = 9, + SDL_SCANCODE_G = 10, + SDL_SCANCODE_H = 11, + SDL_SCANCODE_I = 12, + SDL_SCANCODE_J = 13, + SDL_SCANCODE_K = 14, + SDL_SCANCODE_L = 15, + SDL_SCANCODE_M = 16, + SDL_SCANCODE_N = 17, + SDL_SCANCODE_O = 18, + SDL_SCANCODE_P = 19, + SDL_SCANCODE_Q = 20, + SDL_SCANCODE_R = 21, + SDL_SCANCODE_S = 22, + SDL_SCANCODE_T = 23, + SDL_SCANCODE_U = 24, + SDL_SCANCODE_V = 25, + SDL_SCANCODE_W = 26, + SDL_SCANCODE_X = 27, + SDL_SCANCODE_Y = 28, + SDL_SCANCODE_Z = 29, + + SDL_SCANCODE_1 = 30, + SDL_SCANCODE_2 = 31, + SDL_SCANCODE_3 = 32, + SDL_SCANCODE_4 = 33, + SDL_SCANCODE_5 = 34, + SDL_SCANCODE_6 = 35, + SDL_SCANCODE_7 = 36, + SDL_SCANCODE_8 = 37, + SDL_SCANCODE_9 = 38, + SDL_SCANCODE_0 = 39, + + SDL_SCANCODE_RETURN = 40, + SDL_SCANCODE_ESCAPE = 41, + SDL_SCANCODE_BACKSPACE = 42, + SDL_SCANCODE_TAB = 43, + SDL_SCANCODE_SPACE = 44, + + SDL_SCANCODE_MINUS = 45, + SDL_SCANCODE_EQUALS = 46, + SDL_SCANCODE_LEFTBRACKET = 47, + SDL_SCANCODE_RIGHTBRACKET = 48, + SDL_SCANCODE_BACKSLASH = 49, /**< Located at the lower left of the return + * key on ISO keyboards and at the right end + * of the QWERTY row on ANSI keyboards. + * Produces REVERSE SOLIDUS (backslash) and + * VERTICAL LINE in a US layout, REVERSE + * SOLIDUS and VERTICAL LINE in a UK Mac + * layout, NUMBER SIGN and TILDE in a UK + * Windows layout, DOLLAR SIGN and POUND SIGN + * in a Swiss German layout, NUMBER SIGN and + * APOSTROPHE in a German layout, GRAVE + * ACCENT and POUND SIGN in a French Mac + * layout, and ASTERISK and MICRO SIGN in a + * French Windows layout. + */ + SDL_SCANCODE_NONUSHASH = 50, /**< ISO USB keyboards actually use this code + * instead of 49 for the same key, but all + * OSes I've seen treat the two codes + * identically. So, as an implementor, unless + * your keyboard generates both of those + * codes and your OS treats them differently, + * you should generate SDL_SCANCODE_BACKSLASH + * instead of this code. As a user, you + * should not rely on this code because SDL + * will never generate it with most (all?) + * keyboards. + */ + SDL_SCANCODE_SEMICOLON = 51, + SDL_SCANCODE_APOSTROPHE = 52, + SDL_SCANCODE_GRAVE = 53, /**< Located in the top left corner (on both ANSI + * and ISO keyboards). Produces GRAVE ACCENT and + * TILDE in a US Windows layout and in US and UK + * Mac layouts on ANSI keyboards, GRAVE ACCENT + * and NOT SIGN in a UK Windows layout, SECTION + * SIGN and PLUS-MINUS SIGN in US and UK Mac + * layouts on ISO keyboards, SECTION SIGN and + * DEGREE SIGN in a Swiss German layout (Mac: + * only on ISO keyboards), CIRCUMFLEX ACCENT and + * DEGREE SIGN in a German layout (Mac: only on + * ISO keyboards), SUPERSCRIPT TWO and TILDE in a + * French Windows layout, COMMERCIAL AT and + * NUMBER SIGN in a French Mac layout on ISO + * keyboards, and LESS-THAN SIGN and GREATER-THAN + * SIGN in a Swiss German, German, or French Mac + * layout on ANSI keyboards. + */ + SDL_SCANCODE_COMMA = 54, + SDL_SCANCODE_PERIOD = 55, + SDL_SCANCODE_SLASH = 56, + + SDL_SCANCODE_CAPSLOCK = 57, + + SDL_SCANCODE_F1 = 58, + SDL_SCANCODE_F2 = 59, + SDL_SCANCODE_F3 = 60, + SDL_SCANCODE_F4 = 61, + SDL_SCANCODE_F5 = 62, + SDL_SCANCODE_F6 = 63, + SDL_SCANCODE_F7 = 64, + SDL_SCANCODE_F8 = 65, + SDL_SCANCODE_F9 = 66, + SDL_SCANCODE_F10 = 67, + SDL_SCANCODE_F11 = 68, + SDL_SCANCODE_F12 = 69, + + SDL_SCANCODE_PRINTSCREEN = 70, + SDL_SCANCODE_SCROLLLOCK = 71, + SDL_SCANCODE_PAUSE = 72, + SDL_SCANCODE_INSERT = 73, /**< insert on PC, help on some Mac keyboards (but + does send code 73, not 117) */ + SDL_SCANCODE_HOME = 74, + SDL_SCANCODE_PAGEUP = 75, + SDL_SCANCODE_DELETE = 76, + SDL_SCANCODE_END = 77, + SDL_SCANCODE_PAGEDOWN = 78, + SDL_SCANCODE_RIGHT = 79, + SDL_SCANCODE_LEFT = 80, + SDL_SCANCODE_DOWN = 81, + SDL_SCANCODE_UP = 82, + + SDL_SCANCODE_NUMLOCKCLEAR = 83, /**< num lock on PC, clear on Mac keyboards + */ + SDL_SCANCODE_KP_DIVIDE = 84, + SDL_SCANCODE_KP_MULTIPLY = 85, + SDL_SCANCODE_KP_MINUS = 86, + SDL_SCANCODE_KP_PLUS = 87, + SDL_SCANCODE_KP_ENTER = 88, + SDL_SCANCODE_KP_1 = 89, + SDL_SCANCODE_KP_2 = 90, + SDL_SCANCODE_KP_3 = 91, + SDL_SCANCODE_KP_4 = 92, + SDL_SCANCODE_KP_5 = 93, + SDL_SCANCODE_KP_6 = 94, + SDL_SCANCODE_KP_7 = 95, + SDL_SCANCODE_KP_8 = 96, + SDL_SCANCODE_KP_9 = 97, + SDL_SCANCODE_KP_0 = 98, + SDL_SCANCODE_KP_PERIOD = 99, + + SDL_SCANCODE_NONUSBACKSLASH = 100, /**< This is the additional key that ISO + * keyboards have over ANSI ones, + * located between left shift and Y. + * Produces GRAVE ACCENT and TILDE in a + * US or UK Mac layout, REVERSE SOLIDUS + * (backslash) and VERTICAL LINE in a + * US or UK Windows layout, and + * LESS-THAN SIGN and GREATER-THAN SIGN + * in a Swiss German, German, or French + * layout. */ + SDL_SCANCODE_APPLICATION = 101, /**< windows contextual menu, compose */ + SDL_SCANCODE_POWER = 102, /**< The USB document says this is a status flag, + * not a physical key - but some Mac keyboards + * do have a power key. */ + SDL_SCANCODE_KP_EQUALS = 103, + SDL_SCANCODE_F13 = 104, + SDL_SCANCODE_F14 = 105, + SDL_SCANCODE_F15 = 106, + SDL_SCANCODE_F16 = 107, + SDL_SCANCODE_F17 = 108, + SDL_SCANCODE_F18 = 109, + SDL_SCANCODE_F19 = 110, + SDL_SCANCODE_F20 = 111, + SDL_SCANCODE_F21 = 112, + SDL_SCANCODE_F22 = 113, + SDL_SCANCODE_F23 = 114, + SDL_SCANCODE_F24 = 115, + SDL_SCANCODE_EXECUTE = 116, + SDL_SCANCODE_HELP = 117, /**< AL Integrated Help Center */ + SDL_SCANCODE_MENU = 118, /**< Menu (show menu) */ + SDL_SCANCODE_SELECT = 119, + SDL_SCANCODE_STOP = 120, /**< AC Stop */ + SDL_SCANCODE_AGAIN = 121, /**< AC Redo/Repeat */ + SDL_SCANCODE_UNDO = 122, /**< AC Undo */ + SDL_SCANCODE_CUT = 123, /**< AC Cut */ + SDL_SCANCODE_COPY = 124, /**< AC Copy */ + SDL_SCANCODE_PASTE = 125, /**< AC Paste */ + SDL_SCANCODE_FIND = 126, /**< AC Find */ + SDL_SCANCODE_MUTE = 127, + SDL_SCANCODE_VOLUMEUP = 128, + SDL_SCANCODE_VOLUMEDOWN = 129, +/* not sure whether there's a reason to enable these */ +/* SDL_SCANCODE_LOCKINGCAPSLOCK = 130, */ +/* SDL_SCANCODE_LOCKINGNUMLOCK = 131, */ +/* SDL_SCANCODE_LOCKINGSCROLLLOCK = 132, */ + SDL_SCANCODE_KP_COMMA = 133, + SDL_SCANCODE_KP_EQUALSAS400 = 134, + + SDL_SCANCODE_INTERNATIONAL1 = 135, /**< used on Asian keyboards, see + footnotes in USB doc */ + SDL_SCANCODE_INTERNATIONAL2 = 136, + SDL_SCANCODE_INTERNATIONAL3 = 137, /**< Yen */ + SDL_SCANCODE_INTERNATIONAL4 = 138, + SDL_SCANCODE_INTERNATIONAL5 = 139, + SDL_SCANCODE_INTERNATIONAL6 = 140, + SDL_SCANCODE_INTERNATIONAL7 = 141, + SDL_SCANCODE_INTERNATIONAL8 = 142, + SDL_SCANCODE_INTERNATIONAL9 = 143, + SDL_SCANCODE_LANG1 = 144, /**< Hangul/English toggle */ + SDL_SCANCODE_LANG2 = 145, /**< Hanja conversion */ + SDL_SCANCODE_LANG3 = 146, /**< Katakana */ + SDL_SCANCODE_LANG4 = 147, /**< Hiragana */ + SDL_SCANCODE_LANG5 = 148, /**< Zenkaku/Hankaku */ + SDL_SCANCODE_LANG6 = 149, /**< reserved */ + SDL_SCANCODE_LANG7 = 150, /**< reserved */ + SDL_SCANCODE_LANG8 = 151, /**< reserved */ + SDL_SCANCODE_LANG9 = 152, /**< reserved */ + + SDL_SCANCODE_ALTERASE = 153, /**< Erase-Eaze */ + SDL_SCANCODE_SYSREQ = 154, + SDL_SCANCODE_CANCEL = 155, /**< AC Cancel */ + SDL_SCANCODE_CLEAR = 156, + SDL_SCANCODE_PRIOR = 157, + SDL_SCANCODE_RETURN2 = 158, + SDL_SCANCODE_SEPARATOR = 159, + SDL_SCANCODE_OUT = 160, + SDL_SCANCODE_OPER = 161, + SDL_SCANCODE_CLEARAGAIN = 162, + SDL_SCANCODE_CRSEL = 163, + SDL_SCANCODE_EXSEL = 164, + + SDL_SCANCODE_KP_00 = 176, + SDL_SCANCODE_KP_000 = 177, + SDL_SCANCODE_THOUSANDSSEPARATOR = 178, + SDL_SCANCODE_DECIMALSEPARATOR = 179, + SDL_SCANCODE_CURRENCYUNIT = 180, + SDL_SCANCODE_CURRENCYSUBUNIT = 181, + SDL_SCANCODE_KP_LEFTPAREN = 182, + SDL_SCANCODE_KP_RIGHTPAREN = 183, + SDL_SCANCODE_KP_LEFTBRACE = 184, + SDL_SCANCODE_KP_RIGHTBRACE = 185, + SDL_SCANCODE_KP_TAB = 186, + SDL_SCANCODE_KP_BACKSPACE = 187, + SDL_SCANCODE_KP_A = 188, + SDL_SCANCODE_KP_B = 189, + SDL_SCANCODE_KP_C = 190, + SDL_SCANCODE_KP_D = 191, + SDL_SCANCODE_KP_E = 192, + SDL_SCANCODE_KP_F = 193, + SDL_SCANCODE_KP_XOR = 194, + SDL_SCANCODE_KP_POWER = 195, + SDL_SCANCODE_KP_PERCENT = 196, + SDL_SCANCODE_KP_LESS = 197, + SDL_SCANCODE_KP_GREATER = 198, + SDL_SCANCODE_KP_AMPERSAND = 199, + SDL_SCANCODE_KP_DBLAMPERSAND = 200, + SDL_SCANCODE_KP_VERTICALBAR = 201, + SDL_SCANCODE_KP_DBLVERTICALBAR = 202, + SDL_SCANCODE_KP_COLON = 203, + SDL_SCANCODE_KP_HASH = 204, + SDL_SCANCODE_KP_SPACE = 205, + SDL_SCANCODE_KP_AT = 206, + SDL_SCANCODE_KP_EXCLAM = 207, + SDL_SCANCODE_KP_MEMSTORE = 208, + SDL_SCANCODE_KP_MEMRECALL = 209, + SDL_SCANCODE_KP_MEMCLEAR = 210, + SDL_SCANCODE_KP_MEMADD = 211, + SDL_SCANCODE_KP_MEMSUBTRACT = 212, + SDL_SCANCODE_KP_MEMMULTIPLY = 213, + SDL_SCANCODE_KP_MEMDIVIDE = 214, + SDL_SCANCODE_KP_PLUSMINUS = 215, + SDL_SCANCODE_KP_CLEAR = 216, + SDL_SCANCODE_KP_CLEARENTRY = 217, + SDL_SCANCODE_KP_BINARY = 218, + SDL_SCANCODE_KP_OCTAL = 219, + SDL_SCANCODE_KP_DECIMAL = 220, + SDL_SCANCODE_KP_HEXADECIMAL = 221, + + SDL_SCANCODE_LCTRL = 224, + SDL_SCANCODE_LSHIFT = 225, + SDL_SCANCODE_LALT = 226, /**< alt, option */ + SDL_SCANCODE_LGUI = 227, /**< windows, command (apple), meta */ + SDL_SCANCODE_RCTRL = 228, + SDL_SCANCODE_RSHIFT = 229, + SDL_SCANCODE_RALT = 230, /**< alt gr, option */ + SDL_SCANCODE_RGUI = 231, /**< windows, command (apple), meta */ + + SDL_SCANCODE_MODE = 257, /**< I'm not sure if this is really not covered + * by any of the above, but since there's a + * special KMOD_MODE for it I'm adding it here + */ + + /* @} *//* Usage page 0x07 */ + + /** + * \name Usage page 0x0C + * + * These values are mapped from usage page 0x0C (USB consumer page). + * See https://usb.org/sites/default/files/hut1_2.pdf + * + * There are way more keys in the spec than we can represent in the + * current scancode range, so pick the ones that commonly come up in + * real world usage. + */ + /* @{ */ + + SDL_SCANCODE_AUDIONEXT = 258, + SDL_SCANCODE_AUDIOPREV = 259, + SDL_SCANCODE_AUDIOSTOP = 260, + SDL_SCANCODE_AUDIOPLAY = 261, + SDL_SCANCODE_AUDIOMUTE = 262, + SDL_SCANCODE_MEDIASELECT = 263, + SDL_SCANCODE_WWW = 264, /**< AL Internet Browser */ + SDL_SCANCODE_MAIL = 265, + SDL_SCANCODE_CALCULATOR = 266, /**< AL Calculator */ + SDL_SCANCODE_COMPUTER = 267, + SDL_SCANCODE_AC_SEARCH = 268, /**< AC Search */ + SDL_SCANCODE_AC_HOME = 269, /**< AC Home */ + SDL_SCANCODE_AC_BACK = 270, /**< AC Back */ + SDL_SCANCODE_AC_FORWARD = 271, /**< AC Forward */ + SDL_SCANCODE_AC_STOP = 272, /**< AC Stop */ + SDL_SCANCODE_AC_REFRESH = 273, /**< AC Refresh */ + SDL_SCANCODE_AC_BOOKMARKS = 274, /**< AC Bookmarks */ + + /* @} *//* Usage page 0x0C */ + + /** + * \name Walther keys + * + * These are values that Christian Walther added (for mac keyboard?). + */ + /* @{ */ + + SDL_SCANCODE_BRIGHTNESSDOWN = 275, + SDL_SCANCODE_BRIGHTNESSUP = 276, + SDL_SCANCODE_DISPLAYSWITCH = 277, /**< display mirroring/dual display + switch, video mode switch */ + SDL_SCANCODE_KBDILLUMTOGGLE = 278, + SDL_SCANCODE_KBDILLUMDOWN = 279, + SDL_SCANCODE_KBDILLUMUP = 280, + SDL_SCANCODE_EJECT = 281, + SDL_SCANCODE_SLEEP = 282, /**< SC System Sleep */ + + SDL_SCANCODE_APP1 = 283, + SDL_SCANCODE_APP2 = 284, + + /* @} *//* Walther keys */ + + /** + * \name Usage page 0x0C (additional media keys) + * + * These values are mapped from usage page 0x0C (USB consumer page). + */ + /* @{ */ + + SDL_SCANCODE_AUDIOREWIND = 285, + SDL_SCANCODE_AUDIOFASTFORWARD = 286, + + /* @} *//* Usage page 0x0C (additional media keys) */ + + /** + * \name Mobile keys + * + * These are values that are often used on mobile phones. + */ + /* @{ */ + + SDL_SCANCODE_SOFTLEFT = 287, /**< Usually situated below the display on phones and + used as a multi-function feature key for selecting + a software defined function shown on the bottom left + of the display. */ + SDL_SCANCODE_SOFTRIGHT = 288, /**< Usually situated below the display on phones and + used as a multi-function feature key for selecting + a software defined function shown on the bottom right + of the display. */ + SDL_SCANCODE_CALL = 289, /**< Used for accepting phone calls. */ + SDL_SCANCODE_ENDCALL = 290, /**< Used for rejecting phone calls. */ + + /* @} *//* Mobile keys */ + + /* Add any other keys here. */ + + SDL_NUM_SCANCODES = 512 /**< not a key, just marks the number of scancodes + for array bounds */ +} SDL_Scancode; + +#endif /* SDL_scancode_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_sensor.h b/third_party/SDL2/include/SDL_sensor.h new file mode 100644 index 00000000000..d4b1c511d7d --- /dev/null +++ b/third_party/SDL2/include/SDL_sensor.h @@ -0,0 +1,329 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategorySensor + * + * Include file for SDL sensor event handling + */ + +#ifndef SDL_sensor_h_ +#define SDL_sensor_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +extern "C" { +/* *INDENT-ON* */ +#endif + +/** + * \brief SDL_sensor.h + * + * In order to use these functions, SDL_Init() must have been called + * with the SDL_INIT_SENSOR flag. This causes SDL to scan the system + * for sensors, and load appropriate drivers. + */ + +struct _SDL_Sensor; +typedef struct _SDL_Sensor SDL_Sensor; + +/** + * This is a unique ID for a sensor for the time it is connected to the + * system, and is never reused for the lifetime of the application. + * + * The ID value starts at 0 and increments from there. The value -1 is an + * invalid ID. + */ +typedef Sint32 SDL_SensorID; + +/** + * The different sensors defined by SDL. + * + * Additional sensors may be available, using platform dependent semantics. + * + * Here are the additional Android sensors: + * + * https://developer.android.com/reference/android/hardware/SensorEvent.html#values + * + * Accelerometer sensor notes: + * + * The accelerometer returns the current acceleration in SI meters per second + * squared. This measurement includes the force of gravity, so a device at + * rest will have an value of SDL_STANDARD_GRAVITY away from the center of the + * earth, which is a positive Y value. + * + * - `values[0]`: Acceleration on the x axis + * - `values[1]`: Acceleration on the y axis + * - `values[2]`: Acceleration on the z axis + * + * For phones and tablets held in natural orientation and game controllers + * held in front of you, the axes are defined as follows: + * + * - -X ... +X : left ... right + * - -Y ... +Y : bottom ... top + * - -Z ... +Z : farther ... closer + * + * The accelerometer axis data is not changed when the device is rotated. + * + * Gyroscope sensor notes: + * + * The gyroscope returns the current rate of rotation in radians per second. + * The rotation is positive in the counter-clockwise direction. That is, an + * observer looking from a positive location on one of the axes would see + * positive rotation on that axis when it appeared to be rotating + * counter-clockwise. + * + * - `values[0]`: Angular speed around the x axis (pitch) + * - `values[1]`: Angular speed around the y axis (yaw) + * - `values[2]`: Angular speed around the z axis (roll) + * + * For phones and tablets held in natural orientation and game controllers + * held in front of you, the axes are defined as follows: + * + * - -X ... +X : left ... right + * - -Y ... +Y : bottom ... top + * - -Z ... +Z : farther ... closer + * + * The gyroscope axis data is not changed when the device is rotated. + * + * \sa SDL_GetDisplayOrientation + */ +typedef enum SDL_SensorType +{ + SDL_SENSOR_INVALID = -1, /**< Returned for an invalid sensor */ + SDL_SENSOR_UNKNOWN, /**< Unknown sensor type */ + SDL_SENSOR_ACCEL, /**< Accelerometer */ + SDL_SENSOR_GYRO, /**< Gyroscope */ + SDL_SENSOR_ACCEL_L, /**< Accelerometer for left Joy-Con controller and Wii nunchuk */ + SDL_SENSOR_GYRO_L, /**< Gyroscope for left Joy-Con controller */ + SDL_SENSOR_ACCEL_R, /**< Accelerometer for right Joy-Con controller */ + SDL_SENSOR_GYRO_R /**< Gyroscope for right Joy-Con controller */ +} SDL_SensorType; + +/** + * A constant to represent standard gravity for accelerometer sensors. + * + * The accelerometer returns the current acceleration in SI meters per second + * squared. This measurement includes the force of gravity, so a device at + * rest will have an value of SDL_STANDARD_GRAVITY away from the center of the + * earth, which is a positive Y value. + */ +#define SDL_STANDARD_GRAVITY 9.80665f + +/* Function prototypes */ + +/** + * Locking for multi-threaded access to the sensor API + * + * If you are using the sensor API or handling events from multiple threads + * you should use these locking functions to protect access to the sensors. + * + * In particular, you are guaranteed that the sensor list won't change, so the + * API functions that take a sensor index will be valid, and sensor events + * will not be delivered. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC void SDLCALL SDL_LockSensors(void); +extern DECLSPEC void SDLCALL SDL_UnlockSensors(void); + +/** + * Count the number of sensors attached to the system right now. + * + * \returns the number of sensors detected. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC int SDLCALL SDL_NumSensors(void); + +/** + * Get the implementation dependent name of a sensor. + * + * \param device_index The sensor to obtain name from. + * \returns the sensor name, or NULL if `device_index` is out of range. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC const char *SDLCALL SDL_SensorGetDeviceName(int device_index); + +/** + * Get the type of a sensor. + * + * \param device_index The sensor to get the type from. + * \returns the SDL_SensorType, or `SDL_SENSOR_INVALID` if `device_index` is + * out of range. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_SensorType SDLCALL SDL_SensorGetDeviceType(int device_index); + +/** + * Get the platform dependent type of a sensor. + * + * \param device_index The sensor to check. + * \returns the sensor platform dependent type, or -1 if `device_index` is out + * of range. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC int SDLCALL SDL_SensorGetDeviceNonPortableType(int device_index); + +/** + * Get the instance ID of a sensor. + * + * \param device_index The sensor to get instance id from. + * \returns the sensor instance ID, or -1 if `device_index` is out of range. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_SensorID SDLCALL SDL_SensorGetDeviceInstanceID(int device_index); + +/** + * Open a sensor for use. + * + * \param device_index The sensor to open. + * \returns an SDL_Sensor sensor object, or NULL if an error occurred. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_Sensor *SDLCALL SDL_SensorOpen(int device_index); + +/** + * Return the SDL_Sensor associated with an instance id. + * + * \param instance_id The sensor from instance id. + * \returns an SDL_Sensor object. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_Sensor *SDLCALL SDL_SensorFromInstanceID(SDL_SensorID instance_id); + +/** + * Get the implementation dependent name of a sensor + * + * \param sensor The SDL_Sensor object. + * \returns the sensor name, or NULL if `sensor` is NULL. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC const char *SDLCALL SDL_SensorGetName(SDL_Sensor *sensor); + +/** + * Get the type of a sensor. + * + * \param sensor The SDL_Sensor object to inspect. + * \returns the SDL_SensorType type, or `SDL_SENSOR_INVALID` if `sensor` is + * NULL. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_SensorType SDLCALL SDL_SensorGetType(SDL_Sensor *sensor); + +/** + * Get the platform dependent type of a sensor. + * + * \param sensor The SDL_Sensor object to inspect. + * \returns the sensor platform dependent type, or -1 if `sensor` is NULL. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC int SDLCALL SDL_SensorGetNonPortableType(SDL_Sensor *sensor); + +/** + * Get the instance ID of a sensor. + * + * \param sensor The SDL_Sensor object to inspect. + * \returns the sensor instance ID, or -1 if `sensor` is NULL. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_SensorID SDLCALL SDL_SensorGetInstanceID(SDL_Sensor *sensor); + +/** + * Get the current state of an opened sensor. + * + * The number of values and interpretation of the data is sensor dependent. + * + * \param sensor The SDL_Sensor object to query. + * \param data A pointer filled with the current sensor state. + * \param num_values The number of values to write to data. + * \returns 0 or -1 if an error occurred. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC int SDLCALL SDL_SensorGetData(SDL_Sensor *sensor, float *data, int num_values); + +/** + * Get the current state of an opened sensor with the timestamp of the last + * update. + * + * The number of values and interpretation of the data is sensor dependent. + * + * \param sensor The SDL_Sensor object to query. + * \param timestamp A pointer filled with the timestamp in microseconds of the + * current sensor reading if available, or 0 if not. + * \param data A pointer filled with the current sensor state. + * \param num_values The number of values to write to data. + * \returns 0 or -1 if an error occurred. + * + * \since This function is available since SDL 2.26.0. + */ +extern DECLSPEC int SDLCALL SDL_SensorGetDataWithTimestamp(SDL_Sensor *sensor, Uint64 *timestamp, float *data, int num_values); + +/** + * Close a sensor previously opened with SDL_SensorOpen(). + * + * \param sensor The SDL_Sensor object to close. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC void SDLCALL SDL_SensorClose(SDL_Sensor *sensor); + +/** + * Update the current state of the open sensors. + * + * This is called automatically by the event loop if sensor events are + * enabled. + * + * This needs to be called from the thread that initialized the sensor + * subsystem. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC void SDLCALL SDL_SensorUpdate(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +/* *INDENT-OFF* */ +} +/* *INDENT-ON* */ +#endif +#include "close_code.h" + +#endif /* SDL_sensor_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_shape.h b/third_party/SDL2/include/SDL_shape.h new file mode 100644 index 00000000000..d3560845f85 --- /dev/null +++ b/third_party/SDL2/include/SDL_shape.h @@ -0,0 +1,155 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_shape_h_ +#define SDL_shape_h_ + +#include "SDL_stdinc.h" +#include "SDL_pixels.h" +#include "SDL_rect.h" +#include "SDL_surface.h" +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** \file SDL_shape.h + * + * Header file for the shaped window API. + */ + +#define SDL_NONSHAPEABLE_WINDOW -1 +#define SDL_INVALID_SHAPE_ARGUMENT -2 +#define SDL_WINDOW_LACKS_SHAPE -3 + +/** + * Create a window that can be shaped with the specified position, dimensions, + * and flags. + * + * \param title The title of the window, in UTF-8 encoding. + * \param x The x position of the window, SDL_WINDOWPOS_CENTERED, or + * SDL_WINDOWPOS_UNDEFINED. + * \param y The y position of the window, SDL_WINDOWPOS_CENTERED, or + * SDL_WINDOWPOS_UNDEFINED. + * \param w The width of the window. + * \param h The height of the window. + * \param flags The flags for the window, a mask of SDL_WINDOW_BORDERLESS with + * any of the following: SDL_WINDOW_OPENGL, + * SDL_WINDOW_INPUT_GRABBED, SDL_WINDOW_HIDDEN, + * SDL_WINDOW_RESIZABLE, SDL_WINDOW_MAXIMIZED, + * SDL_WINDOW_MINIMIZED, SDL_WINDOW_BORDERLESS is always set, and + * SDL_WINDOW_FULLSCREEN is always unset. + * \return the window created, or NULL if window creation failed. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_DestroyWindow + */ +extern DECLSPEC SDL_Window * SDLCALL SDL_CreateShapedWindow(const char *title,unsigned int x,unsigned int y,unsigned int w,unsigned int h,Uint32 flags); + +/** + * Return whether the given window is a shaped window. + * + * \param window The window to query for being shaped. + * \return SDL_TRUE if the window is a window that can be shaped, SDL_FALSE if + * the window is unshaped or NULL. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateShapedWindow + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsShapedWindow(const SDL_Window *window); + +/** \brief An enum denoting the specific type of contents present in an SDL_WindowShapeParams union. */ +typedef enum { + /** \brief The default mode, a binarized alpha cutoff of 1. */ + ShapeModeDefault, + /** \brief A binarized alpha cutoff with a given integer value. */ + ShapeModeBinarizeAlpha, + /** \brief A binarized alpha cutoff with a given integer value, but with the opposite comparison. */ + ShapeModeReverseBinarizeAlpha, + /** \brief A color key is applied. */ + ShapeModeColorKey +} WindowShapeMode; + +#define SDL_SHAPEMODEALPHA(mode) (mode == ShapeModeDefault || mode == ShapeModeBinarizeAlpha || mode == ShapeModeReverseBinarizeAlpha) + +/** \brief A union containing parameters for shaped windows. */ +typedef union { + /** \brief A cutoff alpha value for binarization of the window shape's alpha channel. */ + Uint8 binarizationCutoff; + SDL_Color colorKey; +} SDL_WindowShapeParams; + +/** \brief A struct that tags the SDL_WindowShapeParams union with an enum describing the type of its contents. */ +typedef struct SDL_WindowShapeMode { + /** \brief The mode of these window-shape parameters. */ + WindowShapeMode mode; + /** \brief Window-shape parameters. */ + SDL_WindowShapeParams parameters; +} SDL_WindowShapeMode; + +/** + * Set the shape and parameters of a shaped window. + * + * \param window The shaped window whose parameters should be set. + * \param shape A surface encoding the desired shape for the window. + * \param shape_mode The parameters to set for the shaped window. + * \return 0 on success, SDL_INVALID_SHAPE_ARGUMENT on an invalid shape + * argument, or SDL_NONSHAPEABLE_WINDOW if the SDL_Window given does + * not reference a valid shaped window. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WindowShapeMode + * \sa SDL_GetShapedWindowMode + */ +extern DECLSPEC int SDLCALL SDL_SetWindowShape(SDL_Window *window,SDL_Surface *shape,SDL_WindowShapeMode *shape_mode); + +/** + * Get the shape parameters of a shaped window. + * + * \param window The shaped window whose parameters should be retrieved. + * \param shape_mode An empty shape-mode structure to fill, or NULL to check + * whether the window has a shape. + * \return 0 if the window has a shape and, provided shape_mode was not NULL, + * shape_mode has been filled with the mode data, + * SDL_NONSHAPEABLE_WINDOW if the SDL_Window given is not a shaped + * window, or SDL_WINDOW_LACKS_SHAPE if the SDL_Window given is a + * shapeable window currently lacking a shape. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_WindowShapeMode + * \sa SDL_SetWindowShape + */ +extern DECLSPEC int SDLCALL SDL_GetShapedWindowMode(SDL_Window *window,SDL_WindowShapeMode *shape_mode); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_shape_h_ */ diff --git a/third_party/SDL2/include/SDL_stdinc.h b/third_party/SDL2/include/SDL_stdinc.h new file mode 100644 index 00000000000..71fcea5e4cf --- /dev/null +++ b/third_party/SDL2/include/SDL_stdinc.h @@ -0,0 +1,869 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: StdInc */ + +/** + * # CategoryStdInc + * + * This is a general header that includes C language support. + */ + +#ifndef SDL_stdinc_h_ +#define SDL_stdinc_h_ + +#include "SDL_config.h" + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_STDIO_H +#include +#endif +#if defined(STDC_HEADERS) +# include +# include +# include +#else +# if defined(HAVE_STDLIB_H) +# include +# elif defined(HAVE_MALLOC_H) +# include +# endif +# if defined(HAVE_STDDEF_H) +# include +# endif +# if defined(HAVE_STDARG_H) +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined(STDC_HEADERS) && defined(HAVE_MEMORY_H) +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_WCHAR_H +# include +#endif +#if defined(HAVE_INTTYPES_H) +# include +#elif defined(HAVE_STDINT_H) +# include +#endif +#ifdef HAVE_CTYPE_H +# include +#endif +#ifdef HAVE_MATH_H +# if defined(_MSC_VER) +/* Defining _USE_MATH_DEFINES is required to get M_PI to be defined on + Visual Studio. See http://msdn.microsoft.com/en-us/library/4hwaceh6.aspx + for more information. +*/ +# ifndef _USE_MATH_DEFINES +# define _USE_MATH_DEFINES +# endif +# endif +# include +#endif +#ifdef HAVE_FLOAT_H +# include +#endif +#if defined(HAVE_ALLOCA) && !defined(alloca) +# if defined(HAVE_ALLOCA_H) +# include +# elif defined(__GNUC__) +# define alloca __builtin_alloca +# elif defined(_MSC_VER) +# include +# define alloca _alloca +# elif defined(__WATCOMC__) +# include +# elif defined(__BORLANDC__) +# include +# elif defined(__DMC__) +# include +# elif defined(__AIX__) +#pragma alloca +# elif defined(__MRC__) +void *alloca(unsigned); +# else +void *alloca(size_t); +# endif +#endif + +#ifdef SIZE_MAX +# define SDL_SIZE_MAX SIZE_MAX +#else +# define SDL_SIZE_MAX ((size_t) -1) +#endif + +/** + * Check if the compiler supports a given builtin. + * Supported by virtually all clang versions and recent gcc. Use this + * instead of checking the clang version if possible. + */ +#ifdef __has_builtin +#define _SDL_HAS_BUILTIN(x) __has_builtin(x) +#else +#define _SDL_HAS_BUILTIN(x) 0 +#endif + +/** + * The number of elements in an array. + */ +#define SDL_arraysize(array) (sizeof(array)/sizeof(array[0])) +#define SDL_TABLESIZE(table) SDL_arraysize(table) + +/** + * Macro useful for building other macros with strings in them + * + * e.g: + * + * ```c + * #define LOG_ERROR(X) OutputDebugString(SDL_STRINGIFY_ARG(__FUNCTION__) ": " X "\n") + * ``` + */ +#define SDL_STRINGIFY_ARG(arg) #arg + +/** + * \name Cast operators + * + * Use proper C++ casts when compiled as C++ to be compatible with the option + * -Wold-style-cast of GCC (and -Werror=old-style-cast in GCC 4.2 and above). + */ +/* @{ */ +#ifdef __cplusplus +#define SDL_reinterpret_cast(type, expression) reinterpret_cast(expression) +#define SDL_static_cast(type, expression) static_cast(expression) +#define SDL_const_cast(type, expression) const_cast(expression) +#else +#define SDL_reinterpret_cast(type, expression) ((type)(expression)) +#define SDL_static_cast(type, expression) ((type)(expression)) +#define SDL_const_cast(type, expression) ((type)(expression)) +#endif +/* @} *//* Cast operators */ + +/* Define a four character code as a Uint32 */ +#define SDL_FOURCC(A, B, C, D) \ + ((SDL_static_cast(Uint32, SDL_static_cast(Uint8, (A))) << 0) | \ + (SDL_static_cast(Uint32, SDL_static_cast(Uint8, (B))) << 8) | \ + (SDL_static_cast(Uint32, SDL_static_cast(Uint8, (C))) << 16) | \ + (SDL_static_cast(Uint32, SDL_static_cast(Uint8, (D))) << 24)) + +/** + * \name Basic data types + */ +/* @{ */ + +#ifdef __CC_ARM +/* ARM's compiler throws warnings if we use an enum: like "SDL_bool x = a < b;" */ +#define SDL_FALSE 0 +#define SDL_TRUE 1 +typedef int SDL_bool; +#else +typedef enum +{ + SDL_FALSE = 0, + SDL_TRUE = 1 +} SDL_bool; +#endif + +/** + * A signed 8-bit integer type. + */ +typedef int8_t Sint8; +#define SDL_MAX_SINT8 ((Sint8)0x7F) /* 127 */ +#define SDL_MIN_SINT8 ((Sint8)(~0x7F)) /* -128 */ + +/** + * An unsigned 8-bit integer type. + */ +typedef uint8_t Uint8; +#define SDL_MAX_UINT8 ((Uint8)0xFF) /* 255 */ +#define SDL_MIN_UINT8 ((Uint8)0x00) /* 0 */ + +/** + * A signed 16-bit integer type. + */ +typedef int16_t Sint16; +#define SDL_MAX_SINT16 ((Sint16)0x7FFF) /* 32767 */ +#define SDL_MIN_SINT16 ((Sint16)(~0x7FFF)) /* -32768 */ + +/** + * An unsigned 16-bit integer type. + */ +typedef uint16_t Uint16; +#define SDL_MAX_UINT16 ((Uint16)0xFFFF) /* 65535 */ +#define SDL_MIN_UINT16 ((Uint16)0x0000) /* 0 */ + +/** + * A signed 32-bit integer type. + */ +typedef int32_t Sint32; +#define SDL_MAX_SINT32 ((Sint32)0x7FFFFFFF) /* 2147483647 */ +#define SDL_MIN_SINT32 ((Sint32)(~0x7FFFFFFF)) /* -2147483648 */ + +/** + * An unsigned 32-bit integer type. + */ +typedef uint32_t Uint32; +#define SDL_MAX_UINT32 ((Uint32)0xFFFFFFFFu) /* 4294967295 */ +#define SDL_MIN_UINT32 ((Uint32)0x00000000) /* 0 */ + +/** + * A signed 64-bit integer type. + */ +typedef int64_t Sint64; +#define SDL_MAX_SINT64 ((Sint64)0x7FFFFFFFFFFFFFFFll) /* 9223372036854775807 */ +#define SDL_MIN_SINT64 ((Sint64)(~0x7FFFFFFFFFFFFFFFll)) /* -9223372036854775808 */ + +/** + * An unsigned 64-bit integer type. + */ +typedef uint64_t Uint64; +#define SDL_MAX_UINT64 ((Uint64)0xFFFFFFFFFFFFFFFFull) /* 18446744073709551615 */ +#define SDL_MIN_UINT64 ((Uint64)(0x0000000000000000ull)) /* 0 */ + + +/* @} *//* Basic data types */ + +/** + * \name Floating-point constants + */ +/* @{ */ + +#ifdef FLT_EPSILON +#define SDL_FLT_EPSILON FLT_EPSILON +#else +#define SDL_FLT_EPSILON 1.1920928955078125e-07F /* 0x0.000002p0 */ +#endif + +/* @} *//* Floating-point constants */ + +/* Make sure we have macros for printing width-based integers. + * should define these but this is not true all platforms. + * (for example win32) */ +#ifndef SDL_PRIs64 +#if defined(__WIN32__) || defined(__GDK__) +#define SDL_PRIs64 "I64d" +#elif defined(PRId64) +#define SDL_PRIs64 PRId64 +#elif defined(__LP64__) && !defined(__APPLE__) && !defined(__EMSCRIPTEN__) +#define SDL_PRIs64 "ld" +#else +#define SDL_PRIs64 "lld" +#endif +#endif +#ifndef SDL_PRIu64 +#if defined(__WIN32__) || defined(__GDK__) +#define SDL_PRIu64 "I64u" +#elif defined(PRIu64) +#define SDL_PRIu64 PRIu64 +#elif defined(__LP64__) && !defined(__APPLE__) +#define SDL_PRIu64 "lu" +#else +#define SDL_PRIu64 "llu" +#endif +#endif +#ifndef SDL_PRIx64 +#if defined(__WIN32__) || defined(__GDK__) +#define SDL_PRIx64 "I64x" +#elif defined(PRIx64) +#define SDL_PRIx64 PRIx64 +#elif defined(__LP64__) && !defined(__APPLE__) +#define SDL_PRIx64 "lx" +#else +#define SDL_PRIx64 "llx" +#endif +#endif +#ifndef SDL_PRIX64 +#if defined(__WIN32__) || defined(__GDK__) +#define SDL_PRIX64 "I64X" +#elif defined(PRIX64) +#define SDL_PRIX64 PRIX64 +#elif defined(__LP64__) && !defined(__APPLE__) +#define SDL_PRIX64 "lX" +#else +#define SDL_PRIX64 "llX" +#endif +#endif +#ifndef SDL_PRIs32 +#ifdef PRId32 +#define SDL_PRIs32 PRId32 +#else +#define SDL_PRIs32 "d" +#endif +#endif +#ifndef SDL_PRIu32 +#ifdef PRIu32 +#define SDL_PRIu32 PRIu32 +#else +#define SDL_PRIu32 "u" +#endif +#endif +#ifndef SDL_PRIx32 +#ifdef PRIx32 +#define SDL_PRIx32 PRIx32 +#else +#define SDL_PRIx32 "x" +#endif +#endif +#ifndef SDL_PRIX32 +#ifdef PRIX32 +#define SDL_PRIX32 PRIX32 +#else +#define SDL_PRIX32 "X" +#endif +#endif + +/* Annotations to help code analysis tools */ +#ifdef SDL_DISABLE_ANALYZE_MACROS +#define SDL_IN_BYTECAP(x) +#define SDL_INOUT_Z_CAP(x) +#define SDL_OUT_Z_CAP(x) +#define SDL_OUT_CAP(x) +#define SDL_OUT_BYTECAP(x) +#define SDL_OUT_Z_BYTECAP(x) +#define SDL_PRINTF_FORMAT_STRING +#define SDL_SCANF_FORMAT_STRING +#define SDL_PRINTF_VARARG_FUNC( fmtargnumber ) +#define SDL_PRINTF_VARARG_FUNCV( fmtargnumber ) +#define SDL_SCANF_VARARG_FUNC( fmtargnumber ) +#define SDL_SCANF_VARARG_FUNCV( fmtargnumber ) +#else +#if defined(_MSC_VER) && (_MSC_VER >= 1600) /* VS 2010 and above */ +#include + +#define SDL_IN_BYTECAP(x) _In_bytecount_(x) +#define SDL_INOUT_Z_CAP(x) _Inout_z_cap_(x) +#define SDL_OUT_Z_CAP(x) _Out_z_cap_(x) +#define SDL_OUT_CAP(x) _Out_cap_(x) +#define SDL_OUT_BYTECAP(x) _Out_bytecap_(x) +#define SDL_OUT_Z_BYTECAP(x) _Out_z_bytecap_(x) + +#define SDL_PRINTF_FORMAT_STRING _Printf_format_string_ +#define SDL_SCANF_FORMAT_STRING _Scanf_format_string_impl_ +#else +#define SDL_IN_BYTECAP(x) +#define SDL_INOUT_Z_CAP(x) +#define SDL_OUT_Z_CAP(x) +#define SDL_OUT_CAP(x) +#define SDL_OUT_BYTECAP(x) +#define SDL_OUT_Z_BYTECAP(x) +#define SDL_PRINTF_FORMAT_STRING +#define SDL_SCANF_FORMAT_STRING +#endif +#if defined(__GNUC__) +#define SDL_PRINTF_VARARG_FUNC( fmtargnumber ) __attribute__ (( format( __printf__, fmtargnumber, fmtargnumber+1 ))) +#define SDL_PRINTF_VARARG_FUNCV( fmtargnumber ) __attribute__(( format( __printf__, fmtargnumber, 0 ))) +#define SDL_SCANF_VARARG_FUNC( fmtargnumber ) __attribute__ (( format( __scanf__, fmtargnumber, fmtargnumber+1 ))) +#define SDL_SCANF_VARARG_FUNCV( fmtargnumber ) __attribute__(( format( __scanf__, fmtargnumber, 0 ))) +#else +#define SDL_PRINTF_VARARG_FUNC( fmtargnumber ) +#define SDL_PRINTF_VARARG_FUNCV( fmtargnumber ) +#define SDL_SCANF_VARARG_FUNC( fmtargnumber ) +#define SDL_SCANF_VARARG_FUNCV( fmtargnumber ) +#endif +#endif /* SDL_DISABLE_ANALYZE_MACROS */ + +#ifndef SDL_COMPILE_TIME_ASSERT +#if defined(__cplusplus) +/* Keep C++ case alone: Some versions of gcc will define __STDC_VERSION__ even when compiling in C++ mode. */ +#if (__cplusplus >= 201103L) +#define SDL_COMPILE_TIME_ASSERT(name, x) static_assert(x, #x) +#endif +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 202311L) +#define SDL_COMPILE_TIME_ASSERT(name, x) static_assert(x, #x) +#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) +#define SDL_COMPILE_TIME_ASSERT(name, x) _Static_assert(x, #x) +#endif +#endif /* !SDL_COMPILE_TIME_ASSERT */ + +#ifndef SDL_COMPILE_TIME_ASSERT +/* universal, but may trigger -Wunused-local-typedefs */ +#define SDL_COMPILE_TIME_ASSERT(name, x) \ + typedef int SDL_compile_time_assert_ ## name[(x) * 2 - 1] +#endif + +/** \cond */ +#ifndef DOXYGEN_SHOULD_IGNORE_THIS +SDL_COMPILE_TIME_ASSERT(uint8, sizeof(Uint8) == 1); +SDL_COMPILE_TIME_ASSERT(sint8, sizeof(Sint8) == 1); +SDL_COMPILE_TIME_ASSERT(uint16, sizeof(Uint16) == 2); +SDL_COMPILE_TIME_ASSERT(sint16, sizeof(Sint16) == 2); +SDL_COMPILE_TIME_ASSERT(uint32, sizeof(Uint32) == 4); +SDL_COMPILE_TIME_ASSERT(sint32, sizeof(Sint32) == 4); +SDL_COMPILE_TIME_ASSERT(uint64, sizeof(Uint64) == 8); +SDL_COMPILE_TIME_ASSERT(sint64, sizeof(Sint64) == 8); +#endif /* DOXYGEN_SHOULD_IGNORE_THIS */ +/** \endcond */ + +/* Check to make sure enums are the size of ints, for structure packing. + For both Watcom C/C++ and Borland C/C++ the compiler option that makes + enums having the size of an int must be enabled. + This is "-b" for Borland C/C++ and "-ei" for Watcom C/C++ (v11). +*/ + +/** \cond */ +#ifndef DOXYGEN_SHOULD_IGNORE_THIS +#if !defined(__VITA__) && !defined(__3DS__) +/* TODO: include/SDL_stdinc.h:422: error: size of array 'SDL_dummy_enum' is negative */ +typedef enum +{ + DUMMY_ENUM_VALUE +} SDL_DUMMY_ENUM; + +SDL_COMPILE_TIME_ASSERT(enum, sizeof(SDL_DUMMY_ENUM) == sizeof(int)); +#endif +#endif /* DOXYGEN_SHOULD_IGNORE_THIS */ +/** \endcond */ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef HAVE_ALLOCA +#define SDL_stack_alloc(type, count) (type*)alloca(sizeof(type)*(count)) +#define SDL_stack_free(data) +#else +#define SDL_stack_alloc(type, count) (type*)SDL_malloc(sizeof(type)*(count)) +#define SDL_stack_free(data) SDL_free(data) +#endif + +extern DECLSPEC void *SDLCALL SDL_malloc(size_t size); +extern DECLSPEC void *SDLCALL SDL_calloc(size_t nmemb, size_t size); +extern DECLSPEC void *SDLCALL SDL_realloc(void *mem, size_t size); +extern DECLSPEC void SDLCALL SDL_free(void *mem); + +typedef void *(SDLCALL *SDL_malloc_func)(size_t size); +typedef void *(SDLCALL *SDL_calloc_func)(size_t nmemb, size_t size); +typedef void *(SDLCALL *SDL_realloc_func)(void *mem, size_t size); +typedef void (SDLCALL *SDL_free_func)(void *mem); + +/** + * Get the original set of SDL memory functions + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC void SDLCALL SDL_GetOriginalMemoryFunctions(SDL_malloc_func *malloc_func, + SDL_calloc_func *calloc_func, + SDL_realloc_func *realloc_func, + SDL_free_func *free_func); + +/** + * Get the current set of SDL memory functions + * + * \since This function is available since SDL 2.0.7. + */ +extern DECLSPEC void SDLCALL SDL_GetMemoryFunctions(SDL_malloc_func *malloc_func, + SDL_calloc_func *calloc_func, + SDL_realloc_func *realloc_func, + SDL_free_func *free_func); + +/** + * Replace SDL's memory allocation functions with a custom set + * + * \since This function is available since SDL 2.0.7. + */ +extern DECLSPEC int SDLCALL SDL_SetMemoryFunctions(SDL_malloc_func malloc_func, + SDL_calloc_func calloc_func, + SDL_realloc_func realloc_func, + SDL_free_func free_func); + +/** + * Get the number of outstanding (unfreed) allocations + * + * \since This function is available since SDL 2.0.7. + */ +extern DECLSPEC int SDLCALL SDL_GetNumAllocations(void); + +extern DECLSPEC char *SDLCALL SDL_getenv(const char *name); +extern DECLSPEC int SDLCALL SDL_setenv(const char *name, const char *value, int overwrite); + +typedef int (SDLCALL *SDL_CompareCallback)(const void *, const void *); +extern DECLSPEC void SDLCALL SDL_qsort(void *base, size_t nmemb, size_t size, SDL_CompareCallback compare); +extern DECLSPEC void * SDLCALL SDL_bsearch(const void *key, const void *base, size_t nmemb, size_t size, SDL_CompareCallback compare); + +extern DECLSPEC int SDLCALL SDL_abs(int x); + +/* NOTE: these double-evaluate their arguments, so you should never have side effects in the parameters */ +#define SDL_min(x, y) (((x) < (y)) ? (x) : (y)) +#define SDL_max(x, y) (((x) > (y)) ? (x) : (y)) +#define SDL_clamp(x, a, b) (((x) < (a)) ? (a) : (((x) > (b)) ? (b) : (x))) + +extern DECLSPEC int SDLCALL SDL_isalpha(int x); +extern DECLSPEC int SDLCALL SDL_isalnum(int x); +extern DECLSPEC int SDLCALL SDL_isblank(int x); +extern DECLSPEC int SDLCALL SDL_iscntrl(int x); +extern DECLSPEC int SDLCALL SDL_isdigit(int x); +extern DECLSPEC int SDLCALL SDL_isxdigit(int x); +extern DECLSPEC int SDLCALL SDL_ispunct(int x); +extern DECLSPEC int SDLCALL SDL_isspace(int x); +extern DECLSPEC int SDLCALL SDL_isupper(int x); +extern DECLSPEC int SDLCALL SDL_islower(int x); +extern DECLSPEC int SDLCALL SDL_isprint(int x); +extern DECLSPEC int SDLCALL SDL_isgraph(int x); +extern DECLSPEC int SDLCALL SDL_toupper(int x); +extern DECLSPEC int SDLCALL SDL_tolower(int x); + +extern DECLSPEC Uint16 SDLCALL SDL_crc16(Uint16 crc, const void *data, size_t len); +extern DECLSPEC Uint32 SDLCALL SDL_crc32(Uint32 crc, const void *data, size_t len); + +extern DECLSPEC void *SDLCALL SDL_memset(SDL_OUT_BYTECAP(len) void *dst, int c, size_t len); + +/* Some safe(r) macros for zero'ing structures... */ +#define SDL_zero(x) SDL_memset(&(x), 0, sizeof((x))) +#define SDL_zerop(x) SDL_memset((x), 0, sizeof(*(x))) +#define SDL_zeroa(x) SDL_memset((x), 0, sizeof((x))) + +#define SDL_copyp(dst, src) \ + { SDL_COMPILE_TIME_ASSERT(SDL_copyp, sizeof (*(dst)) == sizeof (*(src))); } \ + SDL_memcpy((dst), (src), sizeof (*(src))) + + +/* Note that memset() is a byte assignment and this is a 32-bit assignment, so they're not directly equivalent. */ +SDL_FORCE_INLINE void SDL_memset4(void *dst, Uint32 val, size_t dwords) +{ +#if defined(__GNUC__) && defined(__i386__) + int u0, u1, u2; + __asm__ __volatile__ ( + "cld \n\t" + "rep ; stosl \n\t" + : "=&D" (u0), "=&a" (u1), "=&c" (u2) + : "0" (dst), "1" (val), "2" (SDL_static_cast(Uint32, dwords)) + : "memory" + ); +#else + size_t _n = (dwords + 3) / 4; + Uint32 *_p = SDL_static_cast(Uint32 *, dst); + Uint32 _val = (val); + if (dwords == 0) { + return; + } + switch (dwords % 4) { + case 0: do { *_p++ = _val; SDL_FALLTHROUGH; + case 3: *_p++ = _val; SDL_FALLTHROUGH; + case 2: *_p++ = _val; SDL_FALLTHROUGH; + case 1: *_p++ = _val; + } while ( --_n ); + } +#endif +} + +extern DECLSPEC void *SDLCALL SDL_memcpy(SDL_OUT_BYTECAP(len) void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len); + +extern DECLSPEC void *SDLCALL SDL_memmove(SDL_OUT_BYTECAP(len) void *dst, SDL_IN_BYTECAP(len) const void *src, size_t len); +extern DECLSPEC int SDLCALL SDL_memcmp(const void *s1, const void *s2, size_t len); + +extern DECLSPEC size_t SDLCALL SDL_wcslen(const wchar_t *wstr); +extern DECLSPEC size_t SDLCALL SDL_wcslcpy(SDL_OUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen); +extern DECLSPEC size_t SDLCALL SDL_wcslcat(SDL_INOUT_Z_CAP(maxlen) wchar_t *dst, const wchar_t *src, size_t maxlen); +extern DECLSPEC wchar_t *SDLCALL SDL_wcsdup(const wchar_t *wstr); +extern DECLSPEC wchar_t *SDLCALL SDL_wcsstr(const wchar_t *haystack, const wchar_t *needle); + +extern DECLSPEC int SDLCALL SDL_wcscmp(const wchar_t *str1, const wchar_t *str2); +extern DECLSPEC int SDLCALL SDL_wcsncmp(const wchar_t *str1, const wchar_t *str2, size_t maxlen); +extern DECLSPEC int SDLCALL SDL_wcscasecmp(const wchar_t *str1, const wchar_t *str2); +extern DECLSPEC int SDLCALL SDL_wcsncasecmp(const wchar_t *str1, const wchar_t *str2, size_t len); + +extern DECLSPEC size_t SDLCALL SDL_strlen(const char *str); +extern DECLSPEC size_t SDLCALL SDL_strlcpy(SDL_OUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen); +extern DECLSPEC size_t SDLCALL SDL_utf8strlcpy(SDL_OUT_Z_CAP(dst_bytes) char *dst, const char *src, size_t dst_bytes); +extern DECLSPEC size_t SDLCALL SDL_strlcat(SDL_INOUT_Z_CAP(maxlen) char *dst, const char *src, size_t maxlen); +extern DECLSPEC char *SDLCALL SDL_strdup(const char *str); +extern DECLSPEC char *SDLCALL SDL_strrev(char *str); +extern DECLSPEC char *SDLCALL SDL_strupr(char *str); +extern DECLSPEC char *SDLCALL SDL_strlwr(char *str); +extern DECLSPEC char *SDLCALL SDL_strchr(const char *str, int c); +extern DECLSPEC char *SDLCALL SDL_strrchr(const char *str, int c); +extern DECLSPEC char *SDLCALL SDL_strstr(const char *haystack, const char *needle); +extern DECLSPEC char *SDLCALL SDL_strcasestr(const char *haystack, const char *needle); +extern DECLSPEC char *SDLCALL SDL_strtokr(char *s1, const char *s2, char **saveptr); +extern DECLSPEC size_t SDLCALL SDL_utf8strlen(const char *str); +extern DECLSPEC size_t SDLCALL SDL_utf8strnlen(const char *str, size_t bytes); + +extern DECLSPEC char *SDLCALL SDL_itoa(int value, char *str, int radix); +extern DECLSPEC char *SDLCALL SDL_uitoa(unsigned int value, char *str, int radix); +extern DECLSPEC char *SDLCALL SDL_ltoa(long value, char *str, int radix); +extern DECLSPEC char *SDLCALL SDL_ultoa(unsigned long value, char *str, int radix); +extern DECLSPEC char *SDLCALL SDL_lltoa(Sint64 value, char *str, int radix); +extern DECLSPEC char *SDLCALL SDL_ulltoa(Uint64 value, char *str, int radix); + +extern DECLSPEC int SDLCALL SDL_atoi(const char *str); +extern DECLSPEC double SDLCALL SDL_atof(const char *str); +extern DECLSPEC long SDLCALL SDL_strtol(const char *str, char **endp, int base); +extern DECLSPEC unsigned long SDLCALL SDL_strtoul(const char *str, char **endp, int base); +extern DECLSPEC Sint64 SDLCALL SDL_strtoll(const char *str, char **endp, int base); +extern DECLSPEC Uint64 SDLCALL SDL_strtoull(const char *str, char **endp, int base); +extern DECLSPEC double SDLCALL SDL_strtod(const char *str, char **endp); + +extern DECLSPEC int SDLCALL SDL_strcmp(const char *str1, const char *str2); +extern DECLSPEC int SDLCALL SDL_strncmp(const char *str1, const char *str2, size_t maxlen); +extern DECLSPEC int SDLCALL SDL_strcasecmp(const char *str1, const char *str2); +extern DECLSPEC int SDLCALL SDL_strncasecmp(const char *str1, const char *str2, size_t len); + +extern DECLSPEC int SDLCALL SDL_sscanf(const char *text, SDL_SCANF_FORMAT_STRING const char *fmt, ...) SDL_SCANF_VARARG_FUNC(2); +extern DECLSPEC int SDLCALL SDL_vsscanf(const char *text, SDL_SCANF_FORMAT_STRING const char *fmt, va_list ap) SDL_SCANF_VARARG_FUNCV(2); +extern DECLSPEC int SDLCALL SDL_snprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, ... ) SDL_PRINTF_VARARG_FUNC(3); +extern DECLSPEC int SDLCALL SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(3); +extern DECLSPEC int SDLCALL SDL_asprintf(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); +extern DECLSPEC int SDLCALL SDL_vasprintf(char **strp, SDL_PRINTF_FORMAT_STRING const char *fmt, va_list ap) SDL_PRINTF_VARARG_FUNCV(2); + +#ifndef HAVE_M_PI +#ifndef M_PI +#define M_PI 3.14159265358979323846264338327950288 /**< pi */ +#endif +#endif + +/** + * Use this function to compute arc cosine of `x`. + * + * The definition of `y = acos(x)` is `x = cos(y)`. + * + * Domain: `-1 <= x <= 1` + * + * Range: `0 <= y <= Pi` + * + * \param x floating point value, in radians. + * \returns arc cosine of `x`. + * + * \since This function is available since SDL 2.0.2. + */ +extern DECLSPEC double SDLCALL SDL_acos(double x); +extern DECLSPEC float SDLCALL SDL_acosf(float x); +extern DECLSPEC double SDLCALL SDL_asin(double x); +extern DECLSPEC float SDLCALL SDL_asinf(float x); +extern DECLSPEC double SDLCALL SDL_atan(double x); +extern DECLSPEC float SDLCALL SDL_atanf(float x); +extern DECLSPEC double SDLCALL SDL_atan2(double y, double x); +extern DECLSPEC float SDLCALL SDL_atan2f(float y, float x); +extern DECLSPEC double SDLCALL SDL_ceil(double x); +extern DECLSPEC float SDLCALL SDL_ceilf(float x); +extern DECLSPEC double SDLCALL SDL_copysign(double x, double y); +extern DECLSPEC float SDLCALL SDL_copysignf(float x, float y); +extern DECLSPEC double SDLCALL SDL_cos(double x); +extern DECLSPEC float SDLCALL SDL_cosf(float x); +extern DECLSPEC double SDLCALL SDL_exp(double x); +extern DECLSPEC float SDLCALL SDL_expf(float x); +extern DECLSPEC double SDLCALL SDL_fabs(double x); +extern DECLSPEC float SDLCALL SDL_fabsf(float x); +extern DECLSPEC double SDLCALL SDL_floor(double x); +extern DECLSPEC float SDLCALL SDL_floorf(float x); +extern DECLSPEC double SDLCALL SDL_trunc(double x); +extern DECLSPEC float SDLCALL SDL_truncf(float x); +extern DECLSPEC double SDLCALL SDL_fmod(double x, double y); +extern DECLSPEC float SDLCALL SDL_fmodf(float x, float y); +extern DECLSPEC double SDLCALL SDL_log(double x); +extern DECLSPEC float SDLCALL SDL_logf(float x); +extern DECLSPEC double SDLCALL SDL_log10(double x); +extern DECLSPEC float SDLCALL SDL_log10f(float x); +extern DECLSPEC double SDLCALL SDL_pow(double x, double y); +extern DECLSPEC float SDLCALL SDL_powf(float x, float y); +extern DECLSPEC double SDLCALL SDL_round(double x); +extern DECLSPEC float SDLCALL SDL_roundf(float x); +extern DECLSPEC long SDLCALL SDL_lround(double x); +extern DECLSPEC long SDLCALL SDL_lroundf(float x); +extern DECLSPEC double SDLCALL SDL_scalbn(double x, int n); +extern DECLSPEC float SDLCALL SDL_scalbnf(float x, int n); +extern DECLSPEC double SDLCALL SDL_sin(double x); +extern DECLSPEC float SDLCALL SDL_sinf(float x); +extern DECLSPEC double SDLCALL SDL_sqrt(double x); +extern DECLSPEC float SDLCALL SDL_sqrtf(float x); +extern DECLSPEC double SDLCALL SDL_tan(double x); +extern DECLSPEC float SDLCALL SDL_tanf(float x); + +/* The SDL implementation of iconv() returns these error codes */ +#define SDL_ICONV_ERROR (size_t)-1 +#define SDL_ICONV_E2BIG (size_t)-2 +#define SDL_ICONV_EILSEQ (size_t)-3 +#define SDL_ICONV_EINVAL (size_t)-4 + +/* SDL_iconv_* are now always real symbols/types, not macros or inlined. */ +typedef struct _SDL_iconv_t *SDL_iconv_t; +extern DECLSPEC SDL_iconv_t SDLCALL SDL_iconv_open(const char *tocode, + const char *fromcode); +extern DECLSPEC int SDLCALL SDL_iconv_close(SDL_iconv_t cd); +extern DECLSPEC size_t SDLCALL SDL_iconv(SDL_iconv_t cd, const char **inbuf, + size_t * inbytesleft, char **outbuf, + size_t * outbytesleft); + +/** + * This function converts a buffer or string between encodings in one pass, + * returning a string that must be freed with SDL_free() or NULL on error. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC char *SDLCALL SDL_iconv_string(const char *tocode, + const char *fromcode, + const char *inbuf, + size_t inbytesleft); + +/* Some helper macros for common cases... */ +#define SDL_iconv_utf8_locale(S) SDL_iconv_string("", "UTF-8", S, SDL_strlen(S)+1) +#define SDL_iconv_utf8_ucs2(S) (Uint16 *)SDL_iconv_string("UCS-2", "UTF-8", S, SDL_strlen(S)+1) +#define SDL_iconv_utf8_ucs4(S) (Uint32 *)SDL_iconv_string("UCS-4", "UTF-8", S, SDL_strlen(S)+1) +#define SDL_iconv_wchar_utf8(S) SDL_iconv_string("UTF-8", "WCHAR_T", (char *)S, (SDL_wcslen(S)+1)*sizeof(wchar_t)) + +/* force builds using Clang's static analysis tools to use literal C runtime + here, since there are possibly tests that are ineffective otherwise. */ +#if defined(__clang_analyzer__) && !defined(SDL_DISABLE_ANALYZE_MACROS) + +/* The analyzer knows about strlcpy even when the system doesn't provide it */ +#ifndef HAVE_STRLCPY +size_t strlcpy(char* dst, const char* src, size_t size); +#endif + +/* The analyzer knows about strlcat even when the system doesn't provide it */ +#ifndef HAVE_STRLCAT +size_t strlcat(char* dst, const char* src, size_t size); +#endif + +#ifndef HAVE_WCSLCPY +size_t wcslcpy(wchar_t *dst, const wchar_t *src, size_t size); +#endif + +#ifndef HAVE_WCSLCAT +size_t wcslcat(wchar_t *dst, const wchar_t *src, size_t size); +#endif + +/* strdup is not ANSI but POSIX, and its prototype might be hidden... */ +char *strdup(const char *str); + +/* Starting LLVM 16, the analyser errors out if these functions do not have + their prototype defined (clang-diagnostic-implicit-function-declaration) */ +#include +#include +#include + +#define SDL_malloc malloc +#define SDL_calloc calloc +#define SDL_realloc realloc +#define SDL_free free +#define SDL_memset memset +#define SDL_memcpy memcpy +#define SDL_memmove memmove +#define SDL_memcmp memcmp +#define SDL_strlcpy strlcpy +#define SDL_strlcat strlcat +#define SDL_strlen strlen +#define SDL_wcslen wcslen +#define SDL_wcslcpy wcslcpy +#define SDL_wcslcat wcslcat +#define SDL_strdup strdup +#define SDL_wcsdup wcsdup +#define SDL_strchr strchr +#define SDL_strrchr strrchr +#define SDL_strstr strstr +#define SDL_wcsstr wcsstr +#define SDL_strtokr strtok_r +#define SDL_strcmp strcmp +#define SDL_wcscmp wcscmp +#define SDL_strncmp strncmp +#define SDL_wcsncmp wcsncmp +#define SDL_strcasecmp strcasecmp +#define SDL_strncasecmp strncasecmp +#define SDL_sscanf sscanf +#define SDL_vsscanf vsscanf +#define SDL_snprintf snprintf +#define SDL_vsnprintf vsnprintf +#endif + +SDL_FORCE_INLINE void *SDL_memcpy4(SDL_OUT_BYTECAP(dwords*4) void *dst, SDL_IN_BYTECAP(dwords*4) const void *src, size_t dwords) +{ + return SDL_memcpy(dst, src, dwords * 4); +} + +/** + * If a * b would overflow, return -1. + * + * Otherwise store a * b via ret and return 0. + * + * \since This function is available since SDL 2.24.0. + */ +SDL_FORCE_INLINE int SDL_size_mul_overflow (size_t a, + size_t b, + size_t *ret) +{ + if (a != 0 && b > SDL_SIZE_MAX / a) { + return -1; + } + *ret = a * b; + return 0; +} + +#if _SDL_HAS_BUILTIN(__builtin_mul_overflow) +/* This needs to be wrapped in an inline rather than being a direct #define, + * because __builtin_mul_overflow() is type-generic, but we want to be + * consistent about interpreting a and b as size_t. */ +SDL_FORCE_INLINE int _SDL_size_mul_overflow_builtin (size_t a, + size_t b, + size_t *ret) +{ + return __builtin_mul_overflow(a, b, ret) == 0 ? 0 : -1; +} +#define SDL_size_mul_overflow(a, b, ret) (_SDL_size_mul_overflow_builtin(a, b, ret)) +#endif + +/** + * If a + b would overflow, return -1. + * + * Otherwise store a + b via ret and return 0. + * + * \since This function is available since SDL 2.24.0. + */ +SDL_FORCE_INLINE int SDL_size_add_overflow (size_t a, + size_t b, + size_t *ret) +{ + if (b > SDL_SIZE_MAX - a) { + return -1; + } + *ret = a + b; + return 0; +} + +#if _SDL_HAS_BUILTIN(__builtin_add_overflow) +/* This needs to be wrapped in an inline rather than being a direct #define, + * the same as the call to __builtin_mul_overflow() above. */ +SDL_FORCE_INLINE int _SDL_size_add_overflow_builtin (size_t a, + size_t b, + size_t *ret) +{ + return __builtin_add_overflow(a, b, ret) == 0 ? 0 : -1; +} +#define SDL_size_add_overflow(a, b, ret) (_SDL_size_add_overflow_builtin(a, b, ret)) +#endif + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_stdinc_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_surface.h b/third_party/SDL2/include/SDL_surface.h new file mode 100644 index 00000000000..6169e66ebe0 --- /dev/null +++ b/third_party/SDL2/include/SDL_surface.h @@ -0,0 +1,1001 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategorySurface + * + * Header file for SDL_Surface definition and management functions. + */ + +#ifndef SDL_surface_h_ +#define SDL_surface_h_ + +#include "SDL_stdinc.h" +#include "SDL_pixels.h" +#include "SDL_rect.h" +#include "SDL_blendmode.h" +#include "SDL_rwops.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \name Surface flags + * + * These are the currently supported flags for the SDL_Surface. + * + * \internal + * Used internally (read-only). + */ +/* @{ */ +#define SDL_SWSURFACE 0 /**< Just here for compatibility */ +#define SDL_PREALLOC 0x00000001 /**< Surface uses preallocated memory */ +#define SDL_RLEACCEL 0x00000002 /**< Surface is RLE encoded */ +#define SDL_DONTFREE 0x00000004 /**< Surface is referenced internally */ +#define SDL_SIMD_ALIGNED 0x00000008 /**< Surface uses aligned memory */ +/* @} *//* Surface flags */ + +/** + * Evaluates to true if the surface needs to be locked before access. + */ +#define SDL_MUSTLOCK(S) (((S)->flags & SDL_RLEACCEL) != 0) + +typedef struct SDL_BlitMap SDL_BlitMap; /* this is an opaque type. */ + +/** + * A collection of pixels used in software blitting. + * + * This structure should be treated as read-only, except for `pixels`, which, + * if not NULL, contains the raw pixel data for the surface. + */ +typedef struct SDL_Surface +{ + Uint32 flags; /**< Read-only */ + SDL_PixelFormat *format; /**< Read-only */ + int w, h; /**< Read-only */ + int pitch; /**< Read-only */ + void *pixels; /**< Read-write */ + + /** Application data associated with the surface */ + void *userdata; /**< Read-write */ + + /** information needed for surfaces requiring locks */ + int locked; /**< Read-only */ + + /** list of BlitMap that hold a reference to this surface */ + void *list_blitmap; /**< Private */ + + /** clipping information */ + SDL_Rect clip_rect; /**< Read-only */ + + /** info for fast blit mapping to other surfaces */ + SDL_BlitMap *map; /**< Private */ + + /** Reference count -- used when freeing surface */ + int refcount; /**< Read-mostly */ +} SDL_Surface; + +/** + * The type of function used for surface blitting functions. + */ +typedef int (SDLCALL *SDL_blit) (struct SDL_Surface * src, SDL_Rect * srcrect, + struct SDL_Surface * dst, SDL_Rect * dstrect); + +/** + * The formula used for converting between YUV and RGB + */ +typedef enum SDL_YUV_CONVERSION_MODE +{ + SDL_YUV_CONVERSION_JPEG, /**< Full range JPEG */ + SDL_YUV_CONVERSION_BT601, /**< BT.601 (the default) */ + SDL_YUV_CONVERSION_BT709, /**< BT.709 */ + SDL_YUV_CONVERSION_AUTOMATIC /**< BT.601 for SD content, BT.709 for HD content */ +} SDL_YUV_CONVERSION_MODE; + +/** + * Allocate a new RGB surface. + * + * If `depth` is 4 or 8 bits, an empty palette is allocated for the surface. + * If `depth` is greater than 8 bits, the pixel format is set using the + * [RGBA]mask parameters. + * + * The [RGBA]mask parameters are the bitmasks used to extract that color from + * a pixel. For instance, `Rmask` being 0xFF000000 means the red data is + * stored in the most significant byte. Using zeros for the RGB masks sets a + * default value, based on the depth. For example: + * + * ```c++ + * SDL_CreateRGBSurface(0,w,h,32,0,0,0,0); + * ``` + * + * However, using zero for the Amask results in an Amask of 0. + * + * By default surfaces with an alpha mask are set up for blending as with: + * + * ```c++ + * SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND) + * ``` + * + * You can change this by calling SDL_SetSurfaceBlendMode() and selecting a + * different `blendMode`. + * + * \param flags the flags are unused and should be set to 0. + * \param width the width of the surface. + * \param height the height of the surface. + * \param depth the depth of the surface in bits. + * \param Rmask the red mask for the pixels. + * \param Gmask the green mask for the pixels. + * \param Bmask the blue mask for the pixels. + * \param Amask the alpha mask for the pixels. + * \returns the new SDL_Surface structure that is created or NULL if it fails; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRGBSurfaceFrom + * \sa SDL_CreateRGBSurfaceWithFormat + * \sa SDL_FreeSurface + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurface + (Uint32 flags, int width, int height, int depth, + Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask); + + +/* !!! FIXME for 2.1: why does this ask for depth? Format provides that. */ + +/** + * Allocate a new RGB surface with a specific pixel format. + * + * This function operates mostly like SDL_CreateRGBSurface(), except instead + * of providing pixel color masks, you provide it with a predefined format + * from SDL_PixelFormatEnum. + * + * \param flags the flags are unused and should be set to 0. + * \param width the width of the surface. + * \param height the height of the surface. + * \param depth the depth of the surface in bits. + * \param format the SDL_PixelFormatEnum for the new surface's pixel format. + * \returns the new SDL_Surface structure that is created or NULL if it fails; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_CreateRGBSurface + * \sa SDL_CreateRGBSurfaceFrom + * \sa SDL_FreeSurface + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurfaceWithFormat + (Uint32 flags, int width, int height, int depth, Uint32 format); + +/** + * Allocate a new RGB surface with existing pixel data. + * + * This function operates mostly like SDL_CreateRGBSurface(), except it does + * not allocate memory for the pixel data, instead the caller provides an + * existing buffer of data for the surface to use. + * + * No copy is made of the pixel data. Pixel data is not managed automatically; + * you must free the surface before you free the pixel data. + * + * \param pixels a pointer to existing pixel data. + * \param width the width of the surface. + * \param height the height of the surface. + * \param depth the depth of the surface in bits. + * \param pitch the pitch of the surface in bytes. + * \param Rmask the red mask for the pixels. + * \param Gmask the green mask for the pixels. + * \param Bmask the blue mask for the pixels. + * \param Amask the alpha mask for the pixels. + * \returns the new SDL_Surface structure that is created or NULL if it fails; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRGBSurface + * \sa SDL_CreateRGBSurfaceWithFormat + * \sa SDL_CreateRGBSurfaceWithFormatFrom + * \sa SDL_FreeSurface + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurfaceFrom(void *pixels, + int width, + int height, + int depth, + int pitch, + Uint32 Rmask, + Uint32 Gmask, + Uint32 Bmask, + Uint32 Amask); + +/* !!! FIXME for 2.1: why does this ask for depth? Format provides that. */ + +/** + * Allocate a new RGB surface with with a specific pixel format and existing + * pixel data. + * + * This function operates mostly like SDL_CreateRGBSurfaceFrom(), except + * instead of providing pixel color masks, you provide it with a predefined + * format from SDL_PixelFormatEnum. + * + * No copy is made of the pixel data. Pixel data is not managed automatically; + * you must free the surface before you free the pixel data. + * + * \param pixels a pointer to existing pixel data. + * \param width the width of the surface. + * \param height the height of the surface. + * \param depth the depth of the surface in bits. + * \param pitch the pitch of the surface in bytes. + * \param format the SDL_PixelFormatEnum for the new surface's pixel format. + * \returns the new SDL_Surface structure that is created or NULL if it fails; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_CreateRGBSurfaceFrom + * \sa SDL_CreateRGBSurfaceWithFormat + * \sa SDL_FreeSurface + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_CreateRGBSurfaceWithFormatFrom + (void *pixels, int width, int height, int depth, int pitch, Uint32 format); + +/** + * Free an RGB surface. + * + * It is safe to pass NULL to this function. + * + * \param surface the SDL_Surface to free. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateRGBSurface + * \sa SDL_CreateRGBSurfaceFrom + * \sa SDL_LoadBMP + * \sa SDL_LoadBMP_RW + */ +extern DECLSPEC void SDLCALL SDL_FreeSurface(SDL_Surface * surface); + +/** + * Set the palette used by a surface. + * + * A single palette can be shared with many surfaces. + * + * \param surface the SDL_Surface structure to update. + * \param palette the SDL_Palette structure to use. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_SetSurfacePalette(SDL_Surface * surface, + SDL_Palette * palette); + +/** + * Set up a surface for directly accessing the pixels. + * + * Between calls to SDL_LockSurface() / SDL_UnlockSurface(), you can write to + * and read from `surface->pixels`, using the pixel format stored in + * `surface->format`. Once you are done accessing the surface, you should use + * SDL_UnlockSurface() to release it. + * + * Not all surfaces require locking. If `SDL_MUSTLOCK(surface)` evaluates to + * 0, then you can read and write to the surface at any time, and the pixel + * format of the surface will not change. + * + * \param surface the SDL_Surface structure to be locked. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_MUSTLOCK + * \sa SDL_UnlockSurface + */ +extern DECLSPEC int SDLCALL SDL_LockSurface(SDL_Surface * surface); + +/** + * Release a surface after directly accessing the pixels. + * + * \param surface the SDL_Surface structure to be unlocked. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LockSurface + */ +extern DECLSPEC void SDLCALL SDL_UnlockSurface(SDL_Surface * surface); + +/** + * Load a BMP image from a seekable SDL data stream. + * + * The new surface should be freed with SDL_FreeSurface(). Not doing so will + * result in a memory leak. + * + * src is an open SDL_RWops buffer, typically loaded with SDL_RWFromFile. + * Alternatively, you might also use the macro SDL_LoadBMP to load a bitmap + * from a file, convert it to an SDL_Surface and then close the file. + * + * \param src the data stream for the surface. + * \param freesrc non-zero to close the stream after being read. + * \returns a pointer to a new SDL_Surface structure or NULL if there was an + * error; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FreeSurface + * \sa SDL_RWFromFile + * \sa SDL_LoadBMP + * \sa SDL_SaveBMP_RW + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_LoadBMP_RW(SDL_RWops * src, + int freesrc); + +/** + * Load a surface from a file. + * + * Convenience macro. + */ +#define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), 1) + +/** + * Save a surface to a seekable SDL data stream in BMP format. + * + * Surfaces with a 24-bit, 32-bit and paletted 8-bit format get saved in the + * BMP directly. Other RGB formats with 8-bit or higher get converted to a + * 24-bit surface or, if they have an alpha mask or a colorkey, to a 32-bit + * surface before they are saved. YUV and paletted 1-bit and 4-bit formats are + * not supported. + * + * \param surface the SDL_Surface structure containing the image to be saved. + * \param dst a data stream to save to. + * \param freedst non-zero to close the stream after being written. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_LoadBMP_RW + * \sa SDL_SaveBMP + */ +extern DECLSPEC int SDLCALL SDL_SaveBMP_RW + (SDL_Surface * surface, SDL_RWops * dst, int freedst); + +/** + * Save a surface to a file. + * + * Convenience macro. + */ +#define SDL_SaveBMP(surface, file) \ + SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), 1) + +/** + * Set the RLE acceleration hint for a surface. + * + * If RLE is enabled, color key and alpha blending blits are much faster, but + * the surface must be locked before directly accessing the pixels. + * + * \param surface the SDL_Surface structure to optimize. + * \param flag 0 to disable, non-zero to enable RLE acceleration. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitSurface + * \sa SDL_LockSurface + * \sa SDL_UnlockSurface + */ +extern DECLSPEC int SDLCALL SDL_SetSurfaceRLE(SDL_Surface * surface, + int flag); + +/** + * Returns whether the surface is RLE enabled + * + * It is safe to pass a NULL `surface` here; it will return SDL_FALSE. + * + * \param surface the SDL_Surface structure to query. + * \returns SDL_TRUE if the surface is RLE enabled, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.14. + * + * \sa SDL_SetSurfaceRLE + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasSurfaceRLE(SDL_Surface * surface); + +/** + * Set the color key (transparent pixel) in a surface. + * + * The color key defines a pixel value that will be treated as transparent in + * a blit. For example, one can use this to specify that cyan pixels should be + * considered transparent, and therefore not rendered. + * + * It is a pixel of the format used by the surface, as generated by + * SDL_MapRGB(). + * + * RLE acceleration can substantially speed up blitting of images with large + * horizontal runs of transparent pixels. See SDL_SetSurfaceRLE() for details. + * + * \param surface the SDL_Surface structure to update. + * \param flag SDL_TRUE to enable color key, SDL_FALSE to disable color key. + * \param key the transparent pixel. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitSurface + * \sa SDL_GetColorKey + */ +extern DECLSPEC int SDLCALL SDL_SetColorKey(SDL_Surface * surface, + int flag, Uint32 key); + +/** + * Returns whether the surface has a color key + * + * It is safe to pass a NULL `surface` here; it will return SDL_FALSE. + * + * \param surface the SDL_Surface structure to query. + * \return SDL_TRUE if the surface has a color key, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.9. + * + * \sa SDL_SetColorKey + * \sa SDL_GetColorKey + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasColorKey(SDL_Surface * surface); + +/** + * Get the color key (transparent pixel) for a surface. + * + * The color key is a pixel of the format used by the surface, as generated by + * SDL_MapRGB(). + * + * If the surface doesn't have color key enabled this function returns -1. + * + * \param surface the SDL_Surface structure to query. + * \param key a pointer filled in with the transparent pixel. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitSurface + * \sa SDL_SetColorKey + */ +extern DECLSPEC int SDLCALL SDL_GetColorKey(SDL_Surface * surface, + Uint32 * key); + +/** + * Set an additional color value multiplied into blit operations. + * + * When this surface is blitted, during the blit operation each source color + * channel is modulated by the appropriate color value according to the + * following formula: + * + * `srcC = srcC * (color / 255)` + * + * \param surface the SDL_Surface structure to update. + * \param r the red color value multiplied into blit operations. + * \param g the green color value multiplied into blit operations. + * \param b the blue color value multiplied into blit operations. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetSurfaceColorMod + * \sa SDL_SetSurfaceAlphaMod + */ +extern DECLSPEC int SDLCALL SDL_SetSurfaceColorMod(SDL_Surface * surface, + Uint8 r, Uint8 g, Uint8 b); + + +/** + * Get the additional color value multiplied into blit operations. + * + * \param surface the SDL_Surface structure to query. + * \param r a pointer filled in with the current red color value. + * \param g a pointer filled in with the current green color value. + * \param b a pointer filled in with the current blue color value. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetSurfaceAlphaMod + * \sa SDL_SetSurfaceColorMod + */ +extern DECLSPEC int SDLCALL SDL_GetSurfaceColorMod(SDL_Surface * surface, + Uint8 * r, Uint8 * g, + Uint8 * b); + +/** + * Set an additional alpha value used in blit operations. + * + * When this surface is blitted, during the blit operation the source alpha + * value is modulated by this alpha value according to the following formula: + * + * `srcA = srcA * (alpha / 255)` + * + * \param surface the SDL_Surface structure to update. + * \param alpha the alpha value multiplied into blit operations. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetSurfaceAlphaMod + * \sa SDL_SetSurfaceColorMod + */ +extern DECLSPEC int SDLCALL SDL_SetSurfaceAlphaMod(SDL_Surface * surface, + Uint8 alpha); + +/** + * Get the additional alpha value used in blit operations. + * + * \param surface the SDL_Surface structure to query. + * \param alpha a pointer filled in with the current alpha value. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetSurfaceColorMod + * \sa SDL_SetSurfaceAlphaMod + */ +extern DECLSPEC int SDLCALL SDL_GetSurfaceAlphaMod(SDL_Surface * surface, + Uint8 * alpha); + +/** + * Set the blend mode used for blit operations. + * + * To copy a surface to another surface (or texture) without blending with the + * existing data, the blendmode of the SOURCE surface should be set to + * `SDL_BLENDMODE_NONE`. + * + * \param surface the SDL_Surface structure to update. + * \param blendMode the SDL_BlendMode to use for blit blending. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetSurfaceBlendMode + */ +extern DECLSPEC int SDLCALL SDL_SetSurfaceBlendMode(SDL_Surface * surface, + SDL_BlendMode blendMode); + +/** + * Get the blend mode used for blit operations. + * + * \param surface the SDL_Surface structure to query. + * \param blendMode a pointer filled in with the current SDL_BlendMode. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetSurfaceBlendMode + */ +extern DECLSPEC int SDLCALL SDL_GetSurfaceBlendMode(SDL_Surface * surface, + SDL_BlendMode *blendMode); + +/** + * Set the clipping rectangle for a surface. + * + * When `surface` is the destination of a blit, only the area within the clip + * rectangle is drawn into. + * + * Note that blits are automatically clipped to the edges of the source and + * destination surfaces. + * + * \param surface the SDL_Surface structure to be clipped. + * \param rect the SDL_Rect structure representing the clipping rectangle, or + * NULL to disable clipping. + * \returns SDL_TRUE if the rectangle intersects the surface, otherwise + * SDL_FALSE and blits will be completely clipped. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitSurface + * \sa SDL_GetClipRect + */ +extern DECLSPEC SDL_bool SDLCALL SDL_SetClipRect(SDL_Surface * surface, + const SDL_Rect * rect); + +/** + * Get the clipping rectangle for a surface. + * + * When `surface` is the destination of a blit, only the area within the clip + * rectangle is drawn into. + * + * \param surface the SDL_Surface structure representing the surface to be + * clipped. + * \param rect an SDL_Rect structure filled in with the clipping rectangle for + * the surface. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitSurface + * \sa SDL_SetClipRect + */ +extern DECLSPEC void SDLCALL SDL_GetClipRect(SDL_Surface * surface, + SDL_Rect * rect); + +/* + * Creates a new surface identical to the existing surface. + * + * The returned surface should be freed with SDL_FreeSurface(). + * + * \param surface the surface to duplicate. + * \returns a copy of the surface, or NULL on failure; call SDL_GetError() for + * more information. + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_DuplicateSurface(SDL_Surface * surface); + +/** + * Copy an existing surface to a new surface of the specified format. + * + * This function is used to optimize images for faster *repeat* blitting. This + * is accomplished by converting the original and storing the result as a new + * surface. The new, optimized surface can then be used as the source for + * future blits, making them faster. + * + * \param src the existing SDL_Surface structure to convert. + * \param fmt the SDL_PixelFormat structure that the new surface is optimized + * for. + * \param flags the flags are unused and should be set to 0; this is a + * leftover from SDL 1.2's API. + * \returns the new SDL_Surface structure that is created or NULL if it fails; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AllocFormat + * \sa SDL_ConvertSurfaceFormat + * \sa SDL_CreateRGBSurface + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_ConvertSurface + (SDL_Surface * src, const SDL_PixelFormat * fmt, Uint32 flags); + +/** + * Copy an existing surface to a new surface of the specified format enum. + * + * This function operates just like SDL_ConvertSurface(), but accepts an + * SDL_PixelFormatEnum value instead of an SDL_PixelFormat structure. As such, + * it might be easier to call but it doesn't have access to palette + * information for the destination surface, in case that would be important. + * + * \param src the existing SDL_Surface structure to convert. + * \param pixel_format the SDL_PixelFormatEnum that the new surface is + * optimized for. + * \param flags the flags are unused and should be set to 0; this is a + * leftover from SDL 1.2's API. + * \returns the new SDL_Surface structure that is created or NULL if it fails; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AllocFormat + * \sa SDL_ConvertSurface + * \sa SDL_CreateRGBSurface + */ +extern DECLSPEC SDL_Surface *SDLCALL SDL_ConvertSurfaceFormat + (SDL_Surface * src, Uint32 pixel_format, Uint32 flags); + +/** + * Copy a block of pixels of one format to another format. + * + * \param width the width of the block to copy, in pixels. + * \param height the height of the block to copy, in pixels. + * \param src_format an SDL_PixelFormatEnum value of the `src` pixels format. + * \param src a pointer to the source pixels. + * \param src_pitch the pitch of the source pixels, in bytes. + * \param dst_format an SDL_PixelFormatEnum value of the `dst` pixels format. + * \param dst a pointer to be filled in with new pixel data. + * \param dst_pitch the pitch of the destination pixels, in bytes. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_ConvertPixels(int width, int height, + Uint32 src_format, + const void * src, int src_pitch, + Uint32 dst_format, + void * dst, int dst_pitch); + +/** + * Premultiply the alpha on a block of pixels. + * + * This is safe to use with src == dst, but not for other overlapping areas. + * + * This function is currently only implemented for SDL_PIXELFORMAT_ARGB8888. + * + * \param width the width of the block to convert, in pixels. + * \param height the height of the block to convert, in pixels. + * \param src_format an SDL_PixelFormatEnum value of the `src` pixels format. + * \param src a pointer to the source pixels. + * \param src_pitch the pitch of the source pixels, in bytes. + * \param dst_format an SDL_PixelFormatEnum value of the `dst` pixels format. + * \param dst a pointer to be filled in with premultiplied pixel data. + * \param dst_pitch the pitch of the destination pixels, in bytes. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_PremultiplyAlpha(int width, int height, + Uint32 src_format, + const void * src, int src_pitch, + Uint32 dst_format, + void * dst, int dst_pitch); + +/** + * Perform a fast fill of a rectangle with a specific color. + * + * `color` should be a pixel of the format used by the surface, and can be + * generated by SDL_MapRGB() or SDL_MapRGBA(). If the color value contains an + * alpha component then the destination is simply filled with that alpha + * information, no blending takes place. + * + * If there is a clip rectangle set on the destination (set via + * SDL_SetClipRect()), then this function will fill based on the intersection + * of the clip rectangle and `rect`. + * + * \param dst the SDL_Surface structure that is the drawing target. + * \param rect the SDL_Rect structure representing the rectangle to fill, or + * NULL to fill the entire surface. + * \param color the color to fill with. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FillRects + */ +extern DECLSPEC int SDLCALL SDL_FillRect + (SDL_Surface * dst, const SDL_Rect * rect, Uint32 color); + +/** + * Perform a fast fill of a set of rectangles with a specific color. + * + * `color` should be a pixel of the format used by the surface, and can be + * generated by SDL_MapRGB() or SDL_MapRGBA(). If the color value contains an + * alpha component then the destination is simply filled with that alpha + * information, no blending takes place. + * + * If there is a clip rectangle set on the destination (set via + * SDL_SetClipRect()), then this function will fill based on the intersection + * of the clip rectangle and `rect`. + * + * \param dst the SDL_Surface structure that is the drawing target. + * \param rects an array of SDL_Rect representing the rectangles to fill. + * \param count the number of rectangles in the array. + * \param color the color to fill with. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_FillRect + */ +extern DECLSPEC int SDLCALL SDL_FillRects + (SDL_Surface * dst, const SDL_Rect * rects, int count, Uint32 color); + +/* !!! FIXME: merge this documentation with the wiki */ + +/** + * Performs a fast blit from the source surface to the destination surface. + * + * This assumes that the source and destination rectangles are the same size. + * If either `srcrect` or `dstrect` are NULL, the entire surface (`src` or + * `dst`) is copied. The final blit rectangles are saved in `srcrect` and + * `dstrect` after all clipping is performed. + * + * The blit function should not be called on a locked surface. + * + * The blit semantics for surfaces with and without blending and colorkey are + * defined as follows: + * + * ``` + * RGBA->RGB: + * Source surface blend mode set to SDL_BLENDMODE_BLEND: + * alpha-blend (using the source alpha-channel and per-surface alpha) + * SDL_SRCCOLORKEY ignored. + * Source surface blend mode set to SDL_BLENDMODE_NONE: + * copy RGB. + * if SDL_SRCCOLORKEY set, only copy the pixels matching the + * RGB values of the source color key, ignoring alpha in the + * comparison. + * + * RGB->RGBA: + * Source surface blend mode set to SDL_BLENDMODE_BLEND: + * alpha-blend (using the source per-surface alpha) + * Source surface blend mode set to SDL_BLENDMODE_NONE: + * copy RGB, set destination alpha to source per-surface alpha value. + * both: + * if SDL_SRCCOLORKEY set, only copy the pixels matching the + * source color key. + * + * RGBA->RGBA: + * Source surface blend mode set to SDL_BLENDMODE_BLEND: + * alpha-blend (using the source alpha-channel and per-surface alpha) + * SDL_SRCCOLORKEY ignored. + * Source surface blend mode set to SDL_BLENDMODE_NONE: + * copy all of RGBA to the destination. + * if SDL_SRCCOLORKEY set, only copy the pixels matching the + * RGB values of the source color key, ignoring alpha in the + * comparison. + * + * RGB->RGB: + * Source surface blend mode set to SDL_BLENDMODE_BLEND: + * alpha-blend (using the source per-surface alpha) + * Source surface blend mode set to SDL_BLENDMODE_NONE: + * copy RGB. + * both: + * if SDL_SRCCOLORKEY set, only copy the pixels matching the + * source color key. + * ``` + * + * You should call SDL_BlitSurface() unless you know exactly how SDL blitting + * works internally and how to use the other blit functions. + * + * \returns 0 if the blit is successful, otherwise it returns -1. + */ +#define SDL_BlitSurface SDL_UpperBlit + +/** + * Perform a fast blit from the source surface to the destination surface. + * + * SDL_UpperBlit() has been replaced by SDL_BlitSurface(), which is merely a + * macro for this function with a less confusing name. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitSurface + */ +extern DECLSPEC int SDLCALL SDL_UpperBlit + (SDL_Surface * src, const SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); + +/** + * Perform low-level surface blitting only. + * + * This is a semi-private blit function and it performs low-level surface + * blitting, assuming the input rectangles have already been clipped. + * + * Unless you know what you're doing, you should be using SDL_BlitSurface() + * instead. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied, or NULL to copy the entire surface. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the rectangle that is + * copied into. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitSurface + */ +extern DECLSPEC int SDLCALL SDL_LowerBlit + (SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); + + +/** + * Perform a fast, low quality, stretch blit between two surfaces of the same + * format. + * + * Please use SDL_BlitScaled() instead. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_SoftStretch(SDL_Surface * src, + const SDL_Rect * srcrect, + SDL_Surface * dst, + const SDL_Rect * dstrect); + +/** + * Perform bilinear scaling between two surfaces of the same format, 32BPP. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC int SDLCALL SDL_SoftStretchLinear(SDL_Surface * src, + const SDL_Rect * srcrect, + SDL_Surface * dst, + const SDL_Rect * dstrect); + + +/** + * Perform a scaled surface copy to a destination surface. + * + * SDL_UpperBlitScaled() has been replaced by SDL_BlitScaled(), which is + * merely a macro for this function with a less confusing name. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitScaled + */ +extern DECLSPEC int SDLCALL SDL_UpperBlitScaled + (SDL_Surface * src, const SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); + +#define SDL_BlitScaled SDL_UpperBlitScaled + + +/** + * Perform low-level surface scaled blitting only. + * + * This is a semi-private function and it performs low-level surface blitting, + * assuming the input rectangles have already been clipped. + * + * \param src the SDL_Surface structure to be copied from. + * \param srcrect the SDL_Rect structure representing the rectangle to be + * copied. + * \param dst the SDL_Surface structure that is the blit target. + * \param dstrect the SDL_Rect structure representing the rectangle that is + * copied into. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_BlitScaled + */ +extern DECLSPEC int SDLCALL SDL_LowerBlitScaled + (SDL_Surface * src, SDL_Rect * srcrect, + SDL_Surface * dst, SDL_Rect * dstrect); + +/** + * Set the YUV conversion mode + * + * \since This function is available since SDL 2.0.8. + */ +extern DECLSPEC void SDLCALL SDL_SetYUVConversionMode(SDL_YUV_CONVERSION_MODE mode); + +/** + * Get the YUV conversion mode + * + * \since This function is available since SDL 2.0.8. + */ +extern DECLSPEC SDL_YUV_CONVERSION_MODE SDLCALL SDL_GetYUVConversionMode(void); + +/** + * Get the YUV conversion mode, returning the correct mode for the resolution + * when the current conversion mode is SDL_YUV_CONVERSION_AUTOMATIC + * + * \since This function is available since SDL 2.0.8. + */ +extern DECLSPEC SDL_YUV_CONVERSION_MODE SDLCALL SDL_GetYUVConversionModeForResolution(int width, int height); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_surface_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_system.h b/third_party/SDL2/include/SDL_system.h new file mode 100644 index 00000000000..2f7a236f17e --- /dev/null +++ b/third_party/SDL2/include/SDL_system.h @@ -0,0 +1,642 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategorySystem + * + * Include file for platform specific SDL API functions + */ + +#ifndef SDL_system_h_ +#define SDL_system_h_ + +#include "SDL_stdinc.h" +#include "SDL_keyboard.h" +#include "SDL_render.h" +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + + +/* Platform specific functions for Windows */ +#if defined(__WIN32__) || defined(__GDK__) + +typedef void (SDLCALL * SDL_WindowsMessageHook)(void *userdata, void *hWnd, unsigned int message, Uint64 wParam, Sint64 lParam); + +/** + * Set a callback for every Windows message, run before TranslateMessage(). + * + * \param callback The SDL_WindowsMessageHook function to call. + * \param userdata a pointer to pass to every iteration of `callback`. + * + * \since This function is available since SDL 2.0.4. + */ +extern DECLSPEC void SDLCALL SDL_SetWindowsMessageHook(SDL_WindowsMessageHook callback, void *userdata); + +#endif /* defined(__WIN32__) || defined(__GDK__) */ + +#if defined(__WIN32__) || defined(__WINGDK__) + +/** + * Get the D3D9 adapter index that matches the specified display index. + * + * The returned adapter index can be passed to `IDirect3D9::CreateDevice` and + * controls on which monitor a full screen application will appear. + * + * \param displayIndex the display index for which to get the D3D9 adapter + * index. + * \returns the D3D9 adapter index on success or a negative error code on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.1. + */ +extern DECLSPEC int SDLCALL SDL_Direct3D9GetAdapterIndex( int displayIndex ); + +typedef struct IDirect3DDevice9 IDirect3DDevice9; + +/** + * Get the D3D9 device associated with a renderer. + * + * Once you are done using the device, you should release it to avoid a + * resource leak. + * + * \param renderer the renderer from which to get the associated D3D device. + * \returns the D3D9 device associated with given renderer or NULL if it is + * not a D3D9 renderer; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.1. + */ +extern DECLSPEC IDirect3DDevice9* SDLCALL SDL_RenderGetD3D9Device(SDL_Renderer * renderer); + +typedef struct ID3D11Device ID3D11Device; + +/** + * Get the D3D11 device associated with a renderer. + * + * Once you are done using the device, you should release it to avoid a + * resource leak. + * + * \param renderer the renderer from which to get the associated D3D11 device. + * \returns the D3D11 device associated with given renderer or NULL if it is + * not a D3D11 renderer; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC ID3D11Device* SDLCALL SDL_RenderGetD3D11Device(SDL_Renderer * renderer); + +#endif /* defined(__WIN32__) || defined(__WINGDK__) */ + +#if defined(__WIN32__) || defined(__GDK__) + +typedef struct ID3D12Device ID3D12Device; + +/** + * Get the D3D12 device associated with a renderer. + * + * Once you are done using the device, you should release it to avoid a + * resource leak. + * + * \param renderer the renderer from which to get the associated D3D12 device. + * \returns the D3D12 device associated with given renderer or NULL if it is + * not a D3D12 renderer; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC ID3D12Device* SDLCALL SDL_RenderGetD3D12Device(SDL_Renderer* renderer); + +#endif /* defined(__WIN32__) || defined(__GDK__) */ + +#if defined(__WIN32__) || defined(__WINGDK__) + +/** + * Get the DXGI Adapter and Output indices for the specified display index. + * + * The DXGI Adapter and Output indices can be passed to `EnumAdapters` and + * `EnumOutputs` respectively to get the objects required to create a DX10 or + * DX11 device and swap chain. + * + * Before SDL 2.0.4 this function did not return a value. Since SDL 2.0.4 it + * returns an SDL_bool. + * + * \param displayIndex the display index for which to get both indices. + * \param adapterIndex a pointer to be filled in with the adapter index. + * \param outputIndex a pointer to be filled in with the output index. + * \returns SDL_TRUE on success or SDL_FALSE on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.2. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_DXGIGetOutputInfo( int displayIndex, int *adapterIndex, int *outputIndex ); + +#endif /* defined(__WIN32__) || defined(__WINGDK__) */ + +/* Platform specific functions for Linux */ +#ifdef __LINUX__ + +/** + * Sets the UNIX nice value for a thread. + * + * This uses setpriority() if possible, and RealtimeKit if available. + * + * \param threadID the Unix thread ID to change priority of. + * \param priority The new, Unix-specific, priority value. + * \returns 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC int SDLCALL SDL_LinuxSetThreadPriority(Sint64 threadID, int priority); + +/** + * Sets the priority (not nice level) and scheduling policy for a thread. + * + * This uses setpriority() if possible, and RealtimeKit if available. + * + * \param threadID The Unix thread ID to change priority of. + * \param sdlPriority The new SDL_ThreadPriority value. + * \param schedPolicy The new scheduling policy (SCHED_FIFO, SCHED_RR, + * SCHED_OTHER, etc...). + * \returns 0 on success, or -1 on error. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC int SDLCALL SDL_LinuxSetThreadPriorityAndPolicy(Sint64 threadID, int sdlPriority, int schedPolicy); + +#endif /* __LINUX__ */ + +/* Platform specific functions for iOS */ +#ifdef __IPHONEOS__ + +typedef void (SDLCALL *SDL_iOSAnimationCallback)(void*); + +/** + * Use this function to set the animation callback on Apple iOS. + * + * The function prototype for `callback` is: + * + * ```c + * void callback(void* callbackParam); + * ``` + * + * Where its parameter, `callbackParam`, is what was passed as `callbackParam` + * to SDL_iPhoneSetAnimationCallback(). + * + * This function is only available on Apple iOS. + * + * For more information see: + * https://github.com/libsdl-org/SDL/blob/main/docs/README-ios.md + * + * This functions is also accessible using the macro + * SDL_iOSSetAnimationCallback() since SDL 2.0.4. + * + * \param window the window for which the animation callback should be set. + * \param interval the number of frames after which **callback** will be + * called. + * \param callback the function to call for every frame. + * \param callbackParam a pointer that is passed to `callback`. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_iPhoneSetEventPump + */ +extern DECLSPEC int SDLCALL SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, SDL_iOSAnimationCallback callback, void *callbackParam); + +#define SDL_iOSSetAnimationCallback(window, interval, callback, callbackParam) SDL_iPhoneSetAnimationCallback(window, interval, callback, callbackParam) + + +/** + * Use this function to enable or disable the SDL event pump on Apple iOS. + * + * This function is only available on Apple iOS. + * + * This functions is also accessible using the macro SDL_iOSSetEventPump() + * since SDL 2.0.4. + * + * \param enabled SDL_TRUE to enable the event pump, SDL_FALSE to disable it. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_iPhoneSetAnimationCallback + */ +extern DECLSPEC void SDLCALL SDL_iPhoneSetEventPump(SDL_bool enabled); + +#define SDL_iOSSetEventPump(enabled) SDL_iPhoneSetEventPump(enabled) + +/* end of iOS-specific functions. */ +#endif /* __IPHONEOS__ */ + + +/* Platform specific functions for Android */ +#ifdef __ANDROID__ + +/** + * Get the Android Java Native Interface Environment of the current thread. + * + * This is the JNIEnv one needs to access the Java virtual machine from native + * code, and is needed for many Android APIs to be usable from C. + * + * The prototype of the function in SDL's code actually declare a void* return + * type, even if the implementation returns a pointer to a JNIEnv. The + * rationale being that the SDL headers can avoid including jni.h. + * + * \returns a pointer to Java native interface object (JNIEnv) to which the + * current thread is attached, or 0 on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AndroidGetActivity + */ +extern DECLSPEC void * SDLCALL SDL_AndroidGetJNIEnv(void); + +/** + * Retrieve the Java instance of the Android activity class. + * + * The prototype of the function in SDL's code actually declares a void* + * return type, even if the implementation returns a jobject. The rationale + * being that the SDL headers can avoid including jni.h. + * + * The jobject returned by the function is a local reference and must be + * released by the caller. See the PushLocalFrame() and PopLocalFrame() or + * DeleteLocalRef() functions of the Java native interface: + * + * https://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html + * + * \returns the jobject representing the instance of the Activity class of the + * Android application, or NULL on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AndroidGetJNIEnv + */ +extern DECLSPEC void * SDLCALL SDL_AndroidGetActivity(void); + +/** + * Query Android API level of the current device. + * + * - API level 31: Android 12 + * - API level 30: Android 11 + * - API level 29: Android 10 + * - API level 28: Android 9 + * - API level 27: Android 8.1 + * - API level 26: Android 8.0 + * - API level 25: Android 7.1 + * - API level 24: Android 7.0 + * - API level 23: Android 6.0 + * - API level 22: Android 5.1 + * - API level 21: Android 5.0 + * - API level 20: Android 4.4W + * - API level 19: Android 4.4 + * - API level 18: Android 4.3 + * - API level 17: Android 4.2 + * - API level 16: Android 4.1 + * - API level 15: Android 4.0.3 + * - API level 14: Android 4.0 + * - API level 13: Android 3.2 + * - API level 12: Android 3.1 + * - API level 11: Android 3.0 + * - API level 10: Android 2.3.3 + * + * \returns the Android API level. + * + * \since This function is available since SDL 2.0.12. + */ +extern DECLSPEC int SDLCALL SDL_GetAndroidSDKVersion(void); + +/** + * Query if the application is running on Android TV. + * + * \returns SDL_TRUE if this is Android TV, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.8. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsAndroidTV(void); + +/** + * Query if the application is running on a Chromebook. + * + * \returns SDL_TRUE if this is a Chromebook, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsChromebook(void); + +/** + * Query if the application is running on a Samsung DeX docking station. + * + * \returns SDL_TRUE if this is a DeX docking station, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsDeXMode(void); + +/** + * Trigger the Android system back button behavior. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC void SDLCALL SDL_AndroidBackButton(void); + +/** + * See the official Android developer guide for more information: + * http://developer.android.com/guide/topics/data/data-storage.html + */ +#define SDL_ANDROID_EXTERNAL_STORAGE_READ 0x01 +#define SDL_ANDROID_EXTERNAL_STORAGE_WRITE 0x02 + +/** + * Get the path used for internal storage for this application. + * + * This path is unique to your application and cannot be written to by other + * applications. + * + * Your internal storage path is typically: + * `/data/data/your.app.package/files`. + * + * \returns the path used for internal storage or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AndroidGetExternalStorageState + */ +extern DECLSPEC const char * SDLCALL SDL_AndroidGetInternalStoragePath(void); + +/** + * Get the current state of external storage. + * + * The current state of external storage, a bitmask of these values: + * `SDL_ANDROID_EXTERNAL_STORAGE_READ`, `SDL_ANDROID_EXTERNAL_STORAGE_WRITE`. + * + * If external storage is currently unavailable, this will return 0. + * + * \returns the current state of external storage on success or 0 on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AndroidGetExternalStoragePath + */ +extern DECLSPEC int SDLCALL SDL_AndroidGetExternalStorageState(void); + +/** + * Get the path used for external storage for this application. + * + * This path is unique to your application, but is public and can be written + * to by other applications. + * + * Your external storage path is typically: + * `/storage/sdcard0/Android/data/your.app.package/files`. + * + * \returns the path used for external storage for this application on success + * or NULL on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AndroidGetExternalStorageState + */ +extern DECLSPEC const char * SDLCALL SDL_AndroidGetExternalStoragePath(void); + +/** + * Request permissions at runtime. + * + * This blocks the calling thread until the permission is granted or denied. + * + * \param permission The permission to request. + * \returns SDL_TRUE if the permission was granted, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.14. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_AndroidRequestPermission(const char *permission); + +/** + * Shows an Android toast notification. + * + * Toasts are a sort of lightweight notification that are unique to Android. + * + * https://developer.android.com/guide/topics/ui/notifiers/toasts + * + * Shows toast in UI thread. + * + * For the `gravity` parameter, choose a value from here, or -1 if you don't + * have a preference: + * + * https://developer.android.com/reference/android/view/Gravity + * + * \param message text message to be shown. + * \param duration 0=short, 1=long. + * \param gravity where the notification should appear on the screen. + * \param xoffset set this parameter only when gravity >=0. + * \param yoffset set this parameter only when gravity >=0. + * \returns 0 if success, -1 if any error occurs. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC int SDLCALL SDL_AndroidShowToast(const char* message, int duration, int gravity, int xoffset, int yoffset); + +/** + * Send a user command to SDLActivity. + * + * Override "boolean onUnhandledMessage(Message msg)" to handle the message. + * + * \param command user command that must be greater or equal to 0x8000. + * \param param user parameter. + * + * \since This function is available since SDL 2.0.22. + */ +extern DECLSPEC int SDLCALL SDL_AndroidSendMessage(Uint32 command, int param); + +#endif /* __ANDROID__ */ + +/* Platform specific functions for WinRT */ +#ifdef __WINRT__ + +/** + * WinRT / Windows Phone path types + */ +typedef enum SDL_WinRT_Path +{ + /** \brief The installed app's root directory. + Files here are likely to be read-only. */ + SDL_WINRT_PATH_INSTALLED_LOCATION, + + /** \brief The app's local data store. Files may be written here */ + SDL_WINRT_PATH_LOCAL_FOLDER, + + /** \brief The app's roaming data store. Unsupported on Windows Phone. + Files written here may be copied to other machines via a network + connection. + */ + SDL_WINRT_PATH_ROAMING_FOLDER, + + /** \brief The app's temporary data store. Unsupported on Windows Phone. + Files written here may be deleted at any time. */ + SDL_WINRT_PATH_TEMP_FOLDER +} SDL_WinRT_Path; + + +/** + * WinRT Device Family + */ +typedef enum SDL_WinRT_DeviceFamily +{ + /** \brief Unknown family */ + SDL_WINRT_DEVICEFAMILY_UNKNOWN, + + /** \brief Desktop family*/ + SDL_WINRT_DEVICEFAMILY_DESKTOP, + + /** \brief Mobile family (for example smartphone) */ + SDL_WINRT_DEVICEFAMILY_MOBILE, + + /** \brief XBox family */ + SDL_WINRT_DEVICEFAMILY_XBOX, +} SDL_WinRT_DeviceFamily; + + +/** + * Retrieve a WinRT defined path on the local file system. + * + * Not all paths are available on all versions of Windows. This is especially + * true on Windows Phone. Check the documentation for the given SDL_WinRT_Path + * for more information on which path types are supported where. + * + * Documentation on most app-specific path types on WinRT can be found on + * MSDN, at the URL: + * + * https://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx + * + * \param pathType the type of path to retrieve, one of SDL_WinRT_Path. + * \returns a UCS-2 string (16-bit, wide-char) containing the path, or NULL if + * the path is not available for any reason; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.3. + * + * \sa SDL_WinRTGetFSPathUTF8 + */ +extern DECLSPEC const wchar_t * SDLCALL SDL_WinRTGetFSPathUNICODE(SDL_WinRT_Path pathType); + +/** + * Retrieve a WinRT defined path on the local file system. + * + * Not all paths are available on all versions of Windows. This is especially + * true on Windows Phone. Check the documentation for the given SDL_WinRT_Path + * for more information on which path types are supported where. + * + * Documentation on most app-specific path types on WinRT can be found on + * MSDN, at the URL: + * + * https://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx + * + * \param pathType the type of path to retrieve, one of SDL_WinRT_Path. + * \returns a UTF-8 string (8-bit, multi-byte) containing the path, or NULL if + * the path is not available for any reason; call SDL_GetError() for + * more information. + * + * \since This function is available since SDL 2.0.3. + * + * \sa SDL_WinRTGetFSPathUNICODE + */ +extern DECLSPEC const char * SDLCALL SDL_WinRTGetFSPathUTF8(SDL_WinRT_Path pathType); + +/** + * Detects the device family of WinRT platform at runtime. + * + * \returns a value from the SDL_WinRT_DeviceFamily enum. + * + * \since This function is available since SDL 2.0.8. + */ +extern DECLSPEC SDL_WinRT_DeviceFamily SDLCALL SDL_WinRTGetDeviceFamily(); + +#endif /* __WINRT__ */ + +/** + * Query if the current device is a tablet. + * + * If SDL can't determine this, it will return SDL_FALSE. + * + * \returns SDL_TRUE if the device is a tablet, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.9. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsTablet(void); + +/* Functions used by iOS application delegates to notify SDL about state changes */ +extern DECLSPEC void SDLCALL SDL_OnApplicationWillTerminate(void); +extern DECLSPEC void SDLCALL SDL_OnApplicationDidReceiveMemoryWarning(void); +extern DECLSPEC void SDLCALL SDL_OnApplicationWillResignActive(void); +extern DECLSPEC void SDLCALL SDL_OnApplicationDidEnterBackground(void); +extern DECLSPEC void SDLCALL SDL_OnApplicationWillEnterForeground(void); +extern DECLSPEC void SDLCALL SDL_OnApplicationDidBecomeActive(void); +#ifdef __IPHONEOS__ +extern DECLSPEC void SDLCALL SDL_OnApplicationDidChangeStatusBarOrientation(void); +#endif + +/* Functions used only by GDK */ +#if defined(__GDK__) +typedef struct XTaskQueueObject *XTaskQueueHandle; +typedef struct XUser *XUserHandle; + +/** + * Gets a reference to the global async task queue handle for GDK, + * initializing if needed. + * + * Once you are done with the task queue, you should call + * XTaskQueueCloseHandle to reduce the reference count to avoid a resource + * leak. + * + * \param outTaskQueue a pointer to be filled in with task queue handle. + * \returns 0 if success, -1 if any error occurs. + * + * \since This function is available since SDL 2.24.0. + */ +extern DECLSPEC int SDLCALL SDL_GDKGetTaskQueue(XTaskQueueHandle * outTaskQueue); + +/** + * Gets a reference to the default user handle for GDK. + * + * This is effectively a synchronous version of XUserAddAsync, which always + * prefers the default user and allows a sign-in UI. + * + * \param outUserHandle a pointer to be filled in with the default user + * handle. + * \returns 0 if success, -1 if any error occurs. + * + * \since This function is available since SDL 2.28.0. + */ +extern DECLSPEC int SDLCALL SDL_GDKGetDefaultUser(XUserHandle * outUserHandle); + +#endif + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_system_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_syswm.h b/third_party/SDL2/include/SDL_syswm.h new file mode 100644 index 00000000000..18f6873299d --- /dev/null +++ b/third_party/SDL2/include/SDL_syswm.h @@ -0,0 +1,386 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: SYSWM */ + +/* + * # CategorySYSWM + * + * Include file for SDL custom system window manager hooks. + * + * Your application has access to a special type of event SDL_SYSWMEVENT, + * which contains window-manager specific information and arrives whenever + * an unhandled window event occurs. This event is ignored by default, but + * you can enable it with SDL_EventState(). + */ + +#ifndef SDL_syswm_h_ +#define SDL_syswm_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_video.h" +#include "SDL_version.h" + +struct SDL_SysWMinfo; + +#if !defined(SDL_PROTOTYPES_ONLY) + +#if defined(SDL_VIDEO_DRIVER_WINDOWS) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX /* don't define min() and max(). */ +#define NOMINMAX +#endif +#include +#endif + +#if defined(SDL_VIDEO_DRIVER_WINRT) +#include +#endif + +/* This is the structure for custom window manager events */ +#if defined(SDL_VIDEO_DRIVER_X11) +#if defined(__APPLE__) && defined(__MACH__) +/* conflicts with Quickdraw.h */ +#define Cursor X11Cursor +#endif + +#include +#include + +#if defined(__APPLE__) && defined(__MACH__) +/* matches the re-define above */ +#undef Cursor +#endif + +#endif /* defined(SDL_VIDEO_DRIVER_X11) */ + +#if defined(SDL_VIDEO_DRIVER_DIRECTFB) +#include +#endif + +#if defined(SDL_VIDEO_DRIVER_COCOA) +#ifdef __OBJC__ +@class NSWindow; +#else +typedef struct _NSWindow NSWindow; +#endif +#endif + +#if defined(SDL_VIDEO_DRIVER_UIKIT) +#ifdef __OBJC__ +#include +#else +typedef struct _UIWindow UIWindow; +typedef struct _UIViewController UIViewController; +#endif +typedef Uint32 GLuint; +#endif + +#if defined(SDL_VIDEO_VULKAN) || defined(SDL_VIDEO_METAL) +#define SDL_METALVIEW_TAG 255 +#endif + +#if defined(SDL_VIDEO_DRIVER_ANDROID) +typedef struct ANativeWindow ANativeWindow; +typedef void *EGLSurface; +#endif + +#if defined(SDL_VIDEO_DRIVER_VIVANTE) +#include "SDL_egl.h" +#endif + +#if defined(SDL_VIDEO_DRIVER_OS2) +#define INCL_WIN +#include +#endif +#endif /* SDL_PROTOTYPES_ONLY */ + +#if defined(SDL_VIDEO_DRIVER_KMSDRM) +struct gbm_device; +#endif + + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(SDL_PROTOTYPES_ONLY) + +/** + * These are the various supported windowing subsystems + */ +typedef enum SDL_SYSWM_TYPE +{ + SDL_SYSWM_UNKNOWN, + SDL_SYSWM_WINDOWS, + SDL_SYSWM_X11, + SDL_SYSWM_DIRECTFB, + SDL_SYSWM_COCOA, + SDL_SYSWM_UIKIT, + SDL_SYSWM_WAYLAND, + SDL_SYSWM_MIR, /* no longer available, left for API/ABI compatibility. Remove in 2.1! */ + SDL_SYSWM_WINRT, + SDL_SYSWM_ANDROID, + SDL_SYSWM_VIVANTE, + SDL_SYSWM_OS2, + SDL_SYSWM_HAIKU, + SDL_SYSWM_KMSDRM, + SDL_SYSWM_RISCOS +} SDL_SYSWM_TYPE; + +/** + * The custom event structure. + */ +struct SDL_SysWMmsg +{ + SDL_version version; + SDL_SYSWM_TYPE subsystem; + union + { +#if defined(SDL_VIDEO_DRIVER_WINDOWS) + struct { + HWND hwnd; /**< The window for the message */ + UINT msg; /**< The type of message */ + WPARAM wParam; /**< WORD message parameter */ + LPARAM lParam; /**< LONG message parameter */ + } win; +#endif +#if defined(SDL_VIDEO_DRIVER_X11) + struct { + XEvent event; + } x11; +#endif +#if defined(SDL_VIDEO_DRIVER_DIRECTFB) + struct { + DFBEvent event; + } dfb; +#endif +#if defined(SDL_VIDEO_DRIVER_COCOA) + struct + { + /* Latest version of Xcode clang complains about empty structs in C v. C++: + error: empty struct has size 0 in C, size 1 in C++ + */ + int dummy; + /* No Cocoa window events yet */ + } cocoa; +#endif +#if defined(SDL_VIDEO_DRIVER_UIKIT) + struct + { + int dummy; + /* No UIKit window events yet */ + } uikit; +#endif +#if defined(SDL_VIDEO_DRIVER_VIVANTE) + struct + { + int dummy; + /* No Vivante window events yet */ + } vivante; +#endif +#if defined(SDL_VIDEO_DRIVER_OS2) + struct + { + BOOL fFrame; /**< TRUE if hwnd is a frame window */ + HWND hwnd; /**< The window receiving the message */ + ULONG msg; /**< The message identifier */ + MPARAM mp1; /**< The first first message parameter */ + MPARAM mp2; /**< The second first message parameter */ + } os2; +#endif + /* Can't have an empty union */ + int dummy; + } msg; +}; + +/** + * The custom window manager information structure. + * + * When this structure is returned, it holds information about which low level + * system it is using, and will be one of SDL_SYSWM_TYPE. + */ +struct SDL_SysWMinfo +{ + SDL_version version; + SDL_SYSWM_TYPE subsystem; + union + { +#if defined(SDL_VIDEO_DRIVER_WINDOWS) + struct + { + HWND window; /**< The window handle */ + HDC hdc; /**< The window device context */ + HINSTANCE hinstance; /**< The instance handle */ + } win; +#endif +#if defined(SDL_VIDEO_DRIVER_WINRT) + struct + { + IInspectable * window; /**< The WinRT CoreWindow */ + } winrt; +#endif +#if defined(SDL_VIDEO_DRIVER_X11) + struct + { + Display *display; /**< The X11 display */ + Window window; /**< The X11 window */ + } x11; +#endif +#if defined(SDL_VIDEO_DRIVER_DIRECTFB) + struct + { + IDirectFB *dfb; /**< The directfb main interface */ + IDirectFBWindow *window; /**< The directfb window handle */ + IDirectFBSurface *surface; /**< The directfb client surface */ + } dfb; +#endif +#if defined(SDL_VIDEO_DRIVER_COCOA) + struct + { +#if defined(__OBJC__) && defined(__has_feature) + #if __has_feature(objc_arc) + NSWindow __unsafe_unretained *window; /**< The Cocoa window */ + #else + NSWindow *window; /**< The Cocoa window */ + #endif +#else + NSWindow *window; /**< The Cocoa window */ +#endif + } cocoa; +#endif +#if defined(SDL_VIDEO_DRIVER_UIKIT) + struct + { +#if defined(__OBJC__) && defined(__has_feature) + #if __has_feature(objc_arc) + UIWindow __unsafe_unretained *window; /**< The UIKit window */ + #else + UIWindow *window; /**< The UIKit window */ + #endif +#else + UIWindow *window; /**< The UIKit window */ +#endif + GLuint framebuffer; /**< The GL view's Framebuffer Object. It must be bound when rendering to the screen using GL. */ + GLuint colorbuffer; /**< The GL view's color Renderbuffer Object. It must be bound when SDL_GL_SwapWindow is called. */ + GLuint resolveFramebuffer; /**< The Framebuffer Object which holds the resolve color Renderbuffer, when MSAA is used. */ + } uikit; +#endif +#if defined(SDL_VIDEO_DRIVER_WAYLAND) + struct + { + struct wl_display *display; /**< Wayland display */ + struct wl_surface *surface; /**< Wayland surface */ + void *shell_surface; /**< DEPRECATED Wayland shell_surface (window manager handle) */ + struct wl_egl_window *egl_window; /**< Wayland EGL window (native window) */ + struct xdg_surface *xdg_surface; /**< Wayland xdg surface (window manager handle) */ + struct xdg_toplevel *xdg_toplevel; /**< Wayland xdg toplevel role */ + struct xdg_popup *xdg_popup; /**< Wayland xdg popup role */ + struct xdg_positioner *xdg_positioner; /**< Wayland xdg positioner, for popup */ + } wl; +#endif +#if defined(SDL_VIDEO_DRIVER_MIR) /* no longer available, left for API/ABI compatibility. Remove in 2.1! */ + struct + { + void *connection; /**< Mir display server connection */ + void *surface; /**< Mir surface */ + } mir; +#endif + +#if defined(SDL_VIDEO_DRIVER_ANDROID) + struct + { + ANativeWindow *window; + EGLSurface surface; + } android; +#endif + +#if defined(SDL_VIDEO_DRIVER_OS2) + struct + { + HWND hwnd; /**< The window handle */ + HWND hwndFrame; /**< The frame window handle */ + } os2; +#endif + +#if defined(SDL_VIDEO_DRIVER_VIVANTE) + struct + { + EGLNativeDisplayType display; + EGLNativeWindowType window; + } vivante; +#endif + +#if defined(SDL_VIDEO_DRIVER_KMSDRM) + struct + { + int dev_index; /**< Device index (ex: the X in /dev/dri/cardX) */ + int drm_fd; /**< DRM FD (unavailable on Vulkan windows) */ + struct gbm_device *gbm_dev; /**< GBM device (unavailable on Vulkan windows) */ + } kmsdrm; +#endif + + /* Make sure this union is always 64 bytes (8 64-bit pointers). */ + /* Be careful not to overflow this if you add a new target! */ + Uint8 dummy[64]; + } info; +}; + +#endif /* SDL_PROTOTYPES_ONLY */ + +typedef struct SDL_SysWMinfo SDL_SysWMinfo; + + +/** + * Get driver-specific information about a window. + * + * You must include SDL_syswm.h for the declaration of SDL_SysWMinfo. + * + * The caller must initialize the `info` structure's version by using + * `SDL_VERSION(&info.version)`, and then this function will fill in the rest + * of the structure with information about the given window. + * + * \param window the window about which information is being requested. + * \param info an SDL_SysWMinfo structure filled in with window information. + * \returns SDL_TRUE if the function is implemented and the `version` member + * of the `info` struct is valid, or SDL_FALSE if the information + * could not be retrieved; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowWMInfo(SDL_Window * window, + SDL_SysWMinfo * info); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_syswm_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test.h b/third_party/SDL2/include/SDL_test.h new file mode 100644 index 00000000000..78a7e623e4c --- /dev/null +++ b/third_party/SDL2/include/SDL_test.h @@ -0,0 +1,69 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +#ifndef SDL_test_h_ +#define SDL_test_h_ + +#include "SDL.h" +#include "SDL_test_assert.h" +#include "SDL_test_common.h" +#include "SDL_test_compare.h" +#include "SDL_test_crc32.h" +#include "SDL_test_font.h" +#include "SDL_test_fuzzer.h" +#include "SDL_test_harness.h" +#include "SDL_test_images.h" +#include "SDL_test_log.h" +#include "SDL_test_md5.h" +#include "SDL_test_memory.h" +#include "SDL_test_random.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Global definitions */ + +/* + * Note: Maximum size of SDLTest log message is less than SDL's limit + * to ensure we can fit additional information such as the timestamp. + */ +#define SDLTEST_MAX_LOGMESSAGE_LENGTH 3584 + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_assert.h b/third_party/SDL2/include/SDL_test_assert.h new file mode 100644 index 00000000000..ff3b6b6bcd8 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_assert.h @@ -0,0 +1,105 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_assert.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + * + * Assert API for test code and test cases + * + */ + +#ifndef SDL_test_assert_h_ +#define SDL_test_assert_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* + * \brief Fails the assert. + */ +#define ASSERT_FAIL 0 + +/* + * \brief Passes the assert. + */ +#define ASSERT_PASS 1 + +/* + * \brief Assert that logs and break execution flow on failures. + * + * \param assertCondition Evaluated condition or variable to assert; fail (==0) or pass (!=0). + * \param assertDescription Message to log with the assert describing it. + */ +void SDLTest_Assert(int assertCondition, SDL_PRINTF_FORMAT_STRING const char *assertDescription, ...) SDL_PRINTF_VARARG_FUNC(2); + +/* + * \brief Assert for test cases that logs but does not break execution flow on failures. Updates assertion counters. + * + * \param assertCondition Evaluated condition or variable to assert; fail (==0) or pass (!=0). + * \param assertDescription Message to log with the assert describing it. + * + * \returns the assertCondition so it can be used to externally to break execution flow if desired. + */ +int SDLTest_AssertCheck(int assertCondition, SDL_PRINTF_FORMAT_STRING const char *assertDescription, ...) SDL_PRINTF_VARARG_FUNC(2); + +/* + * \brief Explicitly pass without checking an assertion condition. Updates assertion counter. + * + * \param assertDescription Message to log with the assert describing it. + */ +void SDLTest_AssertPass(SDL_PRINTF_FORMAT_STRING const char *assertDescription, ...) SDL_PRINTF_VARARG_FUNC(1); + +/* + * \brief Resets the assert summary counters to zero. + */ +void SDLTest_ResetAssertSummary(void); + +/* + * \brief Logs summary of all assertions (total, pass, fail) since last reset as INFO or ERROR. + */ +void SDLTest_LogAssertSummary(void); + + +/* + * \brief Converts the current assert summary state to a test result. + * + * \returns TEST_RESULT_PASSED, TEST_RESULT_FAILED, or TEST_RESULT_NO_ASSERT + */ +int SDLTest_AssertSummaryToTestResult(void); + +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_assert_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_common.h b/third_party/SDL2/include/SDL_test_common.h new file mode 100644 index 00000000000..64b5f83e808 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_common.h @@ -0,0 +1,236 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_common.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* Ported from original test\common.h file. */ + +#ifndef SDL_test_common_h_ +#define SDL_test_common_h_ + +#include "SDL.h" + +#if defined(__PSP__) +#define DEFAULT_WINDOW_WIDTH 480 +#define DEFAULT_WINDOW_HEIGHT 272 +#elif defined(__VITA__) +#define DEFAULT_WINDOW_WIDTH 960 +#define DEFAULT_WINDOW_HEIGHT 544 +#else +#define DEFAULT_WINDOW_WIDTH 640 +#define DEFAULT_WINDOW_HEIGHT 480 +#endif + +#define VERBOSE_VIDEO 0x00000001 +#define VERBOSE_MODES 0x00000002 +#define VERBOSE_RENDER 0x00000004 +#define VERBOSE_EVENT 0x00000008 +#define VERBOSE_AUDIO 0x00000010 +#define VERBOSE_MOTION 0x00000020 + +typedef struct +{ + /* SDL init flags */ + char **argv; + Uint32 flags; + Uint32 verbose; + + /* Video info */ + const char *videodriver; + int display; + const char *window_title; + const char *window_icon; + Uint32 window_flags; + SDL_bool flash_on_focus_loss; + int window_x; + int window_y; + int window_w; + int window_h; + int window_minW; + int window_minH; + int window_maxW; + int window_maxH; + int logical_w; + int logical_h; + float scale; + int depth; + int refresh_rate; + int num_windows; + SDL_Window **windows; + + /* Renderer info */ + const char *renderdriver; + Uint32 render_flags; + SDL_bool skip_renderer; + SDL_Renderer **renderers; + SDL_Texture **targets; + + /* Audio info */ + const char *audiodriver; + SDL_AudioSpec audiospec; + + /* GL settings */ + int gl_red_size; + int gl_green_size; + int gl_blue_size; + int gl_alpha_size; + int gl_buffer_size; + int gl_depth_size; + int gl_stencil_size; + int gl_double_buffer; + int gl_accum_red_size; + int gl_accum_green_size; + int gl_accum_blue_size; + int gl_accum_alpha_size; + int gl_stereo; + int gl_multisamplebuffers; + int gl_multisamplesamples; + int gl_retained_backing; + int gl_accelerated; + int gl_major_version; + int gl_minor_version; + int gl_debug; + int gl_profile_mask; + + /* Additional fields added in 2.0.18 */ + SDL_Rect confine; + +} SDLTest_CommonState; + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Function prototypes */ + +/* + * \brief Parse command line parameters and create common state. + * + * \param argv Array of command line parameters + * \param flags Flags indicating which subsystem to initialize (i.e. SDL_INIT_VIDEO | SDL_INIT_AUDIO) + * + * \returns a newly allocated common state object. + */ +SDLTest_CommonState *SDLTest_CommonCreateState(char **argv, Uint32 flags); + +/* + * \brief Process one common argument. + * + * \param state The common state describing the test window to create. + * \param index The index of the argument to process in argv[]. + * + * \returns the number of arguments processed (i.e. 1 for --fullscreen, 2 for --video [videodriver], or -1 on error. + */ +int SDLTest_CommonArg(SDLTest_CommonState * state, int index); + + +/* + * \brief Logs command line usage info. + * + * This logs the appropriate command line options for the subsystems in use + * plus other common options, and then any application-specific options. + * This uses the SDL_Log() function and splits up output to be friendly to + * 80-character-wide terminals. + * + * \param state The common state describing the test window for the app. + * \param argv0 argv[0], as passed to main/SDL_main. + * \param options an array of strings for application specific options. The last element of the array should be NULL. + */ +void SDLTest_CommonLogUsage(SDLTest_CommonState * state, const char *argv0, const char **options); + +/* + * \brief Returns common usage information + * + * You should (probably) be using SDLTest_CommonLogUsage() instead, but this + * function remains for binary compatibility. Strings returned from this + * function are valid until SDLTest_CommonQuit() is called, in which case + * those strings' memory is freed and can no longer be used. + * + * \param state The common state describing the test window to create. + * \returns a string with usage information + */ +const char *SDLTest_CommonUsage(SDLTest_CommonState * state); + +/* + * \brief Open test window. + * + * \param state The common state describing the test window to create. + * + * \returns SDL_TRUE if initialization succeeded, false otherwise + */ +SDL_bool SDLTest_CommonInit(SDLTest_CommonState * state); + +/* + * \brief Easy argument handling when test app doesn't need any custom args. + * + * \param state The common state describing the test window to create. + * \param argc argc, as supplied to SDL_main + * \param argv argv, as supplied to SDL_main + * + * \returns SDL_FALSE if app should quit, true otherwise. + */ +SDL_bool SDLTest_CommonDefaultArgs(SDLTest_CommonState * state, const int argc, char **argv); + +/* + * \brief Common event handler for test windows. + * + * \param state The common state used to create test window. + * \param event The event to handle. + * \param done Flag indicating we are done. + * + */ +void SDLTest_CommonEvent(SDLTest_CommonState * state, SDL_Event * event, int *done); + +/* + * \brief Close test window. + * + * \param state The common state used to create test window. + * + */ +void SDLTest_CommonQuit(SDLTest_CommonState * state); + +/* + * \brief Draws various window information (position, size, etc.) to the renderer. + * + * \param renderer The renderer to draw to. + * \param window The window whose information should be displayed. + * \param usedHeight Returns the height used, so the caller can draw more below. + * + */ +void SDLTest_CommonDrawWindowInfo(SDL_Renderer * renderer, SDL_Window * window, int * usedHeight); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_common_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_compare.h b/third_party/SDL2/include/SDL_test_compare.h new file mode 100644 index 00000000000..3fcb935970c --- /dev/null +++ b/third_party/SDL2/include/SDL_test_compare.h @@ -0,0 +1,69 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_compare.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + + Defines comparison functions (i.e. for surfaces). + +*/ + +#ifndef SDL_test_compare_h_ +#define SDL_test_compare_h_ + +#include "SDL.h" + +#include "SDL_test_images.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* + * \brief Compares a surface and with reference image data for equality + * + * \param surface Surface used in comparison + * \param referenceSurface Test Surface used in comparison + * \param allowable_error Allowable difference (=sum of squared difference for each RGB component) in blending accuracy. + * + * \returns 0 if comparison succeeded, >0 (=number of pixels for which the comparison failed) if comparison failed, -1 if any of the surfaces were NULL, -2 if the surface sizes differ. + */ +int SDLTest_CompareSurfaces(SDL_Surface *surface, SDL_Surface *referenceSurface, int allowable_error); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_compare_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_crc32.h b/third_party/SDL2/include/SDL_test_crc32.h new file mode 100644 index 00000000000..1dbeef27685 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_crc32.h @@ -0,0 +1,124 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_crc32.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + + Implements CRC32 calculations (default output is Perl String::CRC32 compatible). + +*/ + +#ifndef SDL_test_crc32_h_ +#define SDL_test_crc32_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + + +/* ------------ Definitions --------- */ + +/* Definition shared by all CRC routines */ + +#ifndef CrcUint32 + #define CrcUint32 unsigned int +#endif +#ifndef CrcUint8 + #define CrcUint8 unsigned char +#endif + +#ifdef ORIGINAL_METHOD + #define CRC32_POLY 0x04c11db7 /* AUTODIN II, Ethernet, & FDDI */ +#else + #define CRC32_POLY 0xEDB88320 /* Perl String::CRC32 compatible */ +#endif + +/* + * Data structure for CRC32 (checksum) computation + */ + typedef struct { + CrcUint32 crc32_table[256]; /* CRC table */ + } SDLTest_Crc32Context; + +/* ---------- Function Prototypes ------------- */ + +/* + * \brief Initialize the CRC context + * + * Note: The function initializes the crc table required for all crc calculations. + * + * \param crcContext pointer to context variable + * + * \returns 0 for OK, -1 on error + * + */ + int SDLTest_Crc32Init(SDLTest_Crc32Context * crcContext); + + +/* + * \brief calculate a crc32 from a data block + * + * \param crcContext pointer to context variable + * \param inBuf input buffer to checksum + * \param inLen length of input buffer + * \param crc32 pointer to Uint32 to store the final CRC into + * + * \returns 0 for OK, -1 on error + * + */ +int SDLTest_Crc32Calc(SDLTest_Crc32Context * crcContext, CrcUint8 *inBuf, CrcUint32 inLen, CrcUint32 *crc32); + +/* Same routine broken down into three steps */ +int SDLTest_Crc32CalcStart(SDLTest_Crc32Context * crcContext, CrcUint32 *crc32); +int SDLTest_Crc32CalcEnd(SDLTest_Crc32Context * crcContext, CrcUint32 *crc32); +int SDLTest_Crc32CalcBuffer(SDLTest_Crc32Context * crcContext, CrcUint8 *inBuf, CrcUint32 inLen, CrcUint32 *crc32); + + +/* + * \brief clean up CRC context + * + * \param crcContext pointer to context variable + * + * \returns 0 for OK, -1 on error + * +*/ + +int SDLTest_Crc32Done(SDLTest_Crc32Context * crcContext); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_crc32_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_font.h b/third_party/SDL2/include/SDL_test_font.h new file mode 100644 index 00000000000..0eade923944 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_font.h @@ -0,0 +1,168 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_font.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +#ifndef SDL_test_font_h_ +#define SDL_test_font_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Function prototypes */ + +#define FONT_CHARACTER_SIZE 8 +#define FONT_LINE_HEIGHT (FONT_CHARACTER_SIZE + 2) + +/* + * \brief Draw a string in the currently set font. + * + * \param renderer The renderer to draw on. + * \param x The X coordinate of the upper left corner of the character. + * \param y The Y coordinate of the upper left corner of the character. + * \param c The character to draw. + * + * \returns 0 on success, -1 on failure. + */ +int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, Uint32 c); + +/* + * \brief Draw a UTF-8 string in the currently set font. + * + * The font currently only supports characters in the Basic Latin and Latin-1 Supplement sets. + * + * \param renderer The renderer to draw on. + * \param x The X coordinate of the upper left corner of the string. + * \param y The Y coordinate of the upper left corner of the string. + * \param s The string to draw. + * + * \returns 0 on success, -1 on failure. + */ +int SDLTest_DrawString(SDL_Renderer *renderer, int x, int y, const char *s); + +/* + * \brief Data used for multi-line text output + */ +typedef struct SDLTest_TextWindow +{ + SDL_Rect rect; + int current; + int numlines; + char **lines; +} SDLTest_TextWindow; + +/* + * \brief Create a multi-line text output window + * + * \param x The X coordinate of the upper left corner of the window. + * \param y The Y coordinate of the upper left corner of the window. + * \param w The width of the window (currently ignored) + * \param h The height of the window (currently ignored) + * + * \returns the new window, or NULL on failure. + * + * \since This function is available since SDL 2.24.0 + */ +SDLTest_TextWindow *SDLTest_TextWindowCreate(int x, int y, int w, int h); + +/* + * \brief Display a multi-line text output window + * + * This function should be called every frame to display the text + * + * \param textwin The text output window + * \param renderer The renderer to use for display + * + * \since This function is available since SDL 2.24.0 + */ +void SDLTest_TextWindowDisplay(SDLTest_TextWindow *textwin, SDL_Renderer *renderer); + +/* + * \brief Add text to a multi-line text output window + * + * Adds UTF-8 text to the end of the current text. The newline character starts a + * new line of text. The backspace character deletes the last character or, if the + * line is empty, deletes the line and goes to the end of the previous line. + * + * \param textwin The text output window + * \param fmt A printf() style format string + * \param ... additional parameters matching % tokens in the `fmt` string, if any + * + * \since This function is available since SDL 2.24.0 + */ +void SDLTest_TextWindowAddText(SDLTest_TextWindow *textwin, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(2); + +/* + * \brief Add text to a multi-line text output window + * + * Adds UTF-8 text to the end of the current text. The newline character starts a + * new line of text. The backspace character deletes the last character or, if the + * line is empty, deletes the line and goes to the end of the previous line. + * + * \param textwin The text output window + * \param text The text to add to the window + * \param len The length, in bytes, of the text to add to the window + * + * \since This function is available since SDL 2.24.0 + */ +void SDLTest_TextWindowAddTextWithLength(SDLTest_TextWindow *textwin, const char *text, size_t len); + +/* + * \brief Clear the text in a multi-line text output window + * + * \param textwin The text output window + * + * \since This function is available since SDL 2.24.0 + */ +void SDLTest_TextWindowClear(SDLTest_TextWindow *textwin); + +/* + * \brief Free the storage associated with a multi-line text output window + * + * \param textwin The text output window + * + * \since This function is available since SDL 2.24.0 + */ +void SDLTest_TextWindowDestroy(SDLTest_TextWindow *textwin); + +/* + * \brief Cleanup textures used by font drawing functions. + */ +void SDLTest_CleanupTextDrawing(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_font_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_fuzzer.h b/third_party/SDL2/include/SDL_test_fuzzer.h new file mode 100644 index 00000000000..c6978ac8109 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_fuzzer.h @@ -0,0 +1,387 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_fuzzer.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + + Data generators for fuzzing test data in a reproducible way. + +*/ + +#ifndef SDL_test_fuzzer_h_ +#define SDL_test_fuzzer_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + + +/* + Based on GSOC code by Markus Kauppila +*/ + + +/* + * \file + * Note: The fuzzer implementation uses a static instance of random context + * internally which makes it thread-UNsafe. + */ + +/* + * Initializes the fuzzer for a test + * + * \param execKey Execution "Key" that initializes the random number generator uniquely for the test. + * + */ +void SDLTest_FuzzerInit(Uint64 execKey); + + +/* + * Returns a random Uint8 + * + * \returns a generated integer + */ +Uint8 SDLTest_RandomUint8(void); + +/* + * Returns a random Sint8 + * + * \returns a generated signed integer + */ +Sint8 SDLTest_RandomSint8(void); + + +/* + * Returns a random Uint16 + * + * \returns a generated integer + */ +Uint16 SDLTest_RandomUint16(void); + +/* + * Returns a random Sint16 + * + * \returns a generated signed integer + */ +Sint16 SDLTest_RandomSint16(void); + + +/* + * Returns a random integer + * + * \returns a generated integer + */ +Sint32 SDLTest_RandomSint32(void); + + +/* + * Returns a random positive integer + * + * \returns a generated integer + */ +Uint32 SDLTest_RandomUint32(void); + +/* + * Returns random Uint64. + * + * \returns a generated integer + */ +Uint64 SDLTest_RandomUint64(void); + + +/* + * Returns random Sint64. + * + * \returns a generated signed integer + */ +Sint64 SDLTest_RandomSint64(void); + +/* + * \returns a random float in range [0.0 - 1.0] + */ +float SDLTest_RandomUnitFloat(void); + +/* + * \returns a random double in range [0.0 - 1.0] + */ +double SDLTest_RandomUnitDouble(void); + +/* + * \returns a random float. + * + */ +float SDLTest_RandomFloat(void); + +/* + * \returns a random double. + * + */ +double SDLTest_RandomDouble(void); + +/* + * Returns a random boundary value for Uint8 within the given boundaries. + * Boundaries are inclusive, see the usage examples below. If validDomain + * is true, the function will only return valid boundaries, otherwise non-valid + * boundaries are also possible. + * If boundary1 > boundary2, the values are swapped + * + * Usage examples: + * RandomUint8BoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 + * RandomUint8BoundaryValue(1, 20, SDL_FALSE) returns 0 or 21 + * RandomUint8BoundaryValue(0, 99, SDL_FALSE) returns 100 + * RandomUint8BoundaryValue(0, 255, SDL_FALSE) returns 0 (error set) + * + * \param boundary1 Lower boundary limit + * \param boundary2 Upper boundary limit + * \param validDomain Should the generated boundary be valid (=within the bounds) or not? + * + * \returns a random boundary value for the given range and domain or 0 with error set + */ +Uint8 SDLTest_RandomUint8BoundaryValue(Uint8 boundary1, Uint8 boundary2, SDL_bool validDomain); + +/* + * Returns a random boundary value for Uint16 within the given boundaries. + * Boundaries are inclusive, see the usage examples below. If validDomain + * is true, the function will only return valid boundaries, otherwise non-valid + * boundaries are also possible. + * If boundary1 > boundary2, the values are swapped + * + * Usage examples: + * RandomUint16BoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 + * RandomUint16BoundaryValue(1, 20, SDL_FALSE) returns 0 or 21 + * RandomUint16BoundaryValue(0, 99, SDL_FALSE) returns 100 + * RandomUint16BoundaryValue(0, 0xFFFF, SDL_FALSE) returns 0 (error set) + * + * \param boundary1 Lower boundary limit + * \param boundary2 Upper boundary limit + * \param validDomain Should the generated boundary be valid (=within the bounds) or not? + * + * \returns a random boundary value for the given range and domain or 0 with error set + */ +Uint16 SDLTest_RandomUint16BoundaryValue(Uint16 boundary1, Uint16 boundary2, SDL_bool validDomain); + +/* + * Returns a random boundary value for Uint32 within the given boundaries. + * Boundaries are inclusive, see the usage examples below. If validDomain + * is true, the function will only return valid boundaries, otherwise non-valid + * boundaries are also possible. + * If boundary1 > boundary2, the values are swapped + * + * Usage examples: + * RandomUint32BoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 + * RandomUint32BoundaryValue(1, 20, SDL_FALSE) returns 0 or 21 + * RandomUint32BoundaryValue(0, 99, SDL_FALSE) returns 100 + * RandomUint32BoundaryValue(0, 0xFFFFFFFF, SDL_FALSE) returns 0 (with error set) + * + * \param boundary1 Lower boundary limit + * \param boundary2 Upper boundary limit + * \param validDomain Should the generated boundary be valid (=within the bounds) or not? + * + * \returns a random boundary value for the given range and domain or 0 with error set + */ +Uint32 SDLTest_RandomUint32BoundaryValue(Uint32 boundary1, Uint32 boundary2, SDL_bool validDomain); + +/* + * Returns a random boundary value for Uint64 within the given boundaries. + * Boundaries are inclusive, see the usage examples below. If validDomain + * is true, the function will only return valid boundaries, otherwise non-valid + * boundaries are also possible. + * If boundary1 > boundary2, the values are swapped + * + * Usage examples: + * RandomUint64BoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 + * RandomUint64BoundaryValue(1, 20, SDL_FALSE) returns 0 or 21 + * RandomUint64BoundaryValue(0, 99, SDL_FALSE) returns 100 + * RandomUint64BoundaryValue(0, 0xFFFFFFFFFFFFFFFF, SDL_FALSE) returns 0 (with error set) + * + * \param boundary1 Lower boundary limit + * \param boundary2 Upper boundary limit + * \param validDomain Should the generated boundary be valid (=within the bounds) or not? + * + * \returns a random boundary value for the given range and domain or 0 with error set + */ +Uint64 SDLTest_RandomUint64BoundaryValue(Uint64 boundary1, Uint64 boundary2, SDL_bool validDomain); + +/* + * Returns a random boundary value for Sint8 within the given boundaries. + * Boundaries are inclusive, see the usage examples below. If validDomain + * is true, the function will only return valid boundaries, otherwise non-valid + * boundaries are also possible. + * If boundary1 > boundary2, the values are swapped + * + * Usage examples: + * RandomSint8BoundaryValue(-10, 20, SDL_TRUE) returns -11, -10, 19 or 20 + * RandomSint8BoundaryValue(-100, -10, SDL_FALSE) returns -101 or -9 + * RandomSint8BoundaryValue(SINT8_MIN, 99, SDL_FALSE) returns 100 + * RandomSint8BoundaryValue(SINT8_MIN, SINT8_MAX, SDL_FALSE) returns SINT8_MIN (== error value) with error set + * + * \param boundary1 Lower boundary limit + * \param boundary2 Upper boundary limit + * \param validDomain Should the generated boundary be valid (=within the bounds) or not? + * + * \returns a random boundary value for the given range and domain or SINT8_MIN with error set + */ +Sint8 SDLTest_RandomSint8BoundaryValue(Sint8 boundary1, Sint8 boundary2, SDL_bool validDomain); + + +/* + * Returns a random boundary value for Sint16 within the given boundaries. + * Boundaries are inclusive, see the usage examples below. If validDomain + * is true, the function will only return valid boundaries, otherwise non-valid + * boundaries are also possible. + * If boundary1 > boundary2, the values are swapped + * + * Usage examples: + * RandomSint16BoundaryValue(-10, 20, SDL_TRUE) returns -11, -10, 19 or 20 + * RandomSint16BoundaryValue(-100, -10, SDL_FALSE) returns -101 or -9 + * RandomSint16BoundaryValue(SINT16_MIN, 99, SDL_FALSE) returns 100 + * RandomSint16BoundaryValue(SINT16_MIN, SINT16_MAX, SDL_FALSE) returns SINT16_MIN (== error value) with error set + * + * \param boundary1 Lower boundary limit + * \param boundary2 Upper boundary limit + * \param validDomain Should the generated boundary be valid (=within the bounds) or not? + * + * \returns a random boundary value for the given range and domain or SINT16_MIN with error set + */ +Sint16 SDLTest_RandomSint16BoundaryValue(Sint16 boundary1, Sint16 boundary2, SDL_bool validDomain); + +/* + * Returns a random boundary value for Sint32 within the given boundaries. + * Boundaries are inclusive, see the usage examples below. If validDomain + * is true, the function will only return valid boundaries, otherwise non-valid + * boundaries are also possible. + * If boundary1 > boundary2, the values are swapped + * + * Usage examples: + * RandomSint32BoundaryValue(-10, 20, SDL_TRUE) returns -11, -10, 19 or 20 + * RandomSint32BoundaryValue(-100, -10, SDL_FALSE) returns -101 or -9 + * RandomSint32BoundaryValue(SINT32_MIN, 99, SDL_FALSE) returns 100 + * RandomSint32BoundaryValue(SINT32_MIN, SINT32_MAX, SDL_FALSE) returns SINT32_MIN (== error value) + * + * \param boundary1 Lower boundary limit + * \param boundary2 Upper boundary limit + * \param validDomain Should the generated boundary be valid (=within the bounds) or not? + * + * \returns a random boundary value for the given range and domain or SINT32_MIN with error set + */ +Sint32 SDLTest_RandomSint32BoundaryValue(Sint32 boundary1, Sint32 boundary2, SDL_bool validDomain); + +/* + * Returns a random boundary value for Sint64 within the given boundaries. + * Boundaries are inclusive, see the usage examples below. If validDomain + * is true, the function will only return valid boundaries, otherwise non-valid + * boundaries are also possible. + * If boundary1 > boundary2, the values are swapped + * + * Usage examples: + * RandomSint64BoundaryValue(-10, 20, SDL_TRUE) returns -11, -10, 19 or 20 + * RandomSint64BoundaryValue(-100, -10, SDL_FALSE) returns -101 or -9 + * RandomSint64BoundaryValue(SINT64_MIN, 99, SDL_FALSE) returns 100 + * RandomSint64BoundaryValue(SINT64_MIN, SINT64_MAX, SDL_FALSE) returns SINT64_MIN (== error value) and error set + * + * \param boundary1 Lower boundary limit + * \param boundary2 Upper boundary limit + * \param validDomain Should the generated boundary be valid (=within the bounds) or not? + * + * \returns a random boundary value for the given range and domain or SINT64_MIN with error set + */ +Sint64 SDLTest_RandomSint64BoundaryValue(Sint64 boundary1, Sint64 boundary2, SDL_bool validDomain); + + +/* + * Returns integer in range [min, max] (inclusive). + * Min and max values can be negative values. + * If Max in smaller than min, then the values are swapped. + * Min and max are the same value, that value will be returned. + * + * \param min Minimum inclusive value of returned random number + * \param max Maximum inclusive value of returned random number + * + * \returns a generated random integer in range + */ +Sint32 SDLTest_RandomIntegerInRange(Sint32 min, Sint32 max); + + +/* + * Generates random null-terminated string. The minimum length for + * the string is 1 character, maximum length for the string is 255 + * characters and it can contain ASCII characters from 32 to 126. + * + * Note: Returned string needs to be deallocated. + * + * \returns a newly allocated random string; or NULL if length was invalid or string could not be allocated. + */ +char * SDLTest_RandomAsciiString(void); + + +/* + * Generates random null-terminated string. The maximum length for + * the string is defined by the maxLength parameter. + * String can contain ASCII characters from 32 to 126. + * + * Note: Returned string needs to be deallocated. + * + * \param maxLength The maximum length of the generated string. + * + * \returns a newly allocated random string; or NULL if maxLength was invalid or string could not be allocated. + */ +char * SDLTest_RandomAsciiStringWithMaximumLength(int maxLength); + + +/* + * Generates random null-terminated string. The length for + * the string is defined by the size parameter. + * String can contain ASCII characters from 32 to 126. + * + * Note: Returned string needs to be deallocated. + * + * \param size The length of the generated string + * + * \returns a newly allocated random string; or NULL if size was invalid or string could not be allocated. + */ +char * SDLTest_RandomAsciiStringOfSize(int size); + + +/* + * Get the invocation count for the fuzzer since last ...FuzzerInit. + * + * \returns the invocation count. + */ +int SDLTest_GetFuzzerInvocationCount(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_fuzzer_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_harness.h b/third_party/SDL2/include/SDL_test_harness.h new file mode 100644 index 00000000000..cfd62e8401b --- /dev/null +++ b/third_party/SDL2/include/SDL_test_harness.h @@ -0,0 +1,134 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_harness.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + Defines types for test case definitions and the test execution harness API. + + Based on original GSOC code by Markus Kauppila +*/ + +#ifndef SDL_test_h_arness_h +#define SDL_test_h_arness_h + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + + +/* ! Definitions for test case structures */ +#define TEST_ENABLED 1 +#define TEST_DISABLED 0 + +/* ! Definition of all the possible test return values of the test case method */ +#define TEST_ABORTED -1 +#define TEST_STARTED 0 +#define TEST_COMPLETED 1 +#define TEST_SKIPPED 2 + +/* ! Definition of all the possible test results for the harness */ +#define TEST_RESULT_PASSED 0 +#define TEST_RESULT_FAILED 1 +#define TEST_RESULT_NO_ASSERT 2 +#define TEST_RESULT_SKIPPED 3 +#define TEST_RESULT_SETUP_FAILURE 4 + +/* !< Function pointer to a test case setup function (run before every test) */ +typedef void (*SDLTest_TestCaseSetUpFp)(void *arg); + +/* !< Function pointer to a test case function */ +typedef int (*SDLTest_TestCaseFp)(void *arg); + +/* !< Function pointer to a test case teardown function (run after every test) */ +typedef void (*SDLTest_TestCaseTearDownFp)(void *arg); + +/* + * Holds information about a single test case. + */ +typedef struct SDLTest_TestCaseReference { + /* !< Func2Stress */ + SDLTest_TestCaseFp testCase; + /* !< Short name (or function name) "Func2Stress" */ + const char *name; + /* !< Long name or full description "This test pushes func2() to the limit." */ + const char *description; + /* !< Set to TEST_ENABLED or TEST_DISABLED (test won't be run) */ + int enabled; +} SDLTest_TestCaseReference; + +/* + * Holds information about a test suite (multiple test cases). + */ +typedef struct SDLTest_TestSuiteReference { + /* !< "PlatformSuite" */ + const char *name; + /* !< The function that is run before each test. NULL skips. */ + SDLTest_TestCaseSetUpFp testSetUp; + /* !< The test cases that are run as part of the suite. Last item should be NULL. */ + const SDLTest_TestCaseReference **testCases; + /* !< The function that is run after each test. NULL skips. */ + SDLTest_TestCaseTearDownFp testTearDown; +} SDLTest_TestSuiteReference; + + +/* + * \brief Generates a random run seed string for the harness. The generated seed will contain alphanumeric characters (0-9A-Z). + * + * Note: The returned string needs to be deallocated by the caller. + * + * \param length The length of the seed string to generate + * + * \returns the generated seed string + */ +char *SDLTest_GenerateRunSeed(const int length); + +/* + * \brief Execute a test suite using the given run seed and execution key. + * + * \param testSuites Suites containing the test case. + * \param userRunSeed Custom run seed provided by user, or NULL to autogenerate one. + * \param userExecKey Custom execution key provided by user, or 0 to autogenerate one. + * \param filter Filter specification. NULL disables. Case sensitive. + * \param testIterations Number of iterations to run each test case. + * + * \returns the test run result: 0 when all tests passed, 1 if any tests failed. + */ +int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *userRunSeed, Uint64 userExecKey, const char *filter, int testIterations); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_h_arness_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_images.h b/third_party/SDL2/include/SDL_test_images.h new file mode 100644 index 00000000000..d593a31565b --- /dev/null +++ b/third_party/SDL2/include/SDL_test_images.h @@ -0,0 +1,78 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_images.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + + Defines some images for tests. + +*/ + +#ifndef SDL_test_images_h_ +#define SDL_test_images_h_ + +#include "SDL.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* + *Type for test images. + */ +typedef struct SDLTest_SurfaceImage_s { + int width; + int height; + unsigned int bytes_per_pixel; /* 3:RGB, 4:RGBA */ + const char *pixel_data; +} SDLTest_SurfaceImage_t; + +/* Test images */ +SDL_Surface *SDLTest_ImageBlit(void); +SDL_Surface *SDLTest_ImageBlitColor(void); +SDL_Surface *SDLTest_ImageBlitAlpha(void); +SDL_Surface *SDLTest_ImageBlitBlendAdd(void); +SDL_Surface *SDLTest_ImageBlitBlend(void); +SDL_Surface *SDLTest_ImageBlitBlendMod(void); +SDL_Surface *SDLTest_ImageBlitBlendNone(void); +SDL_Surface *SDLTest_ImageBlitBlendAll(void); +SDL_Surface *SDLTest_ImageFace(void); +SDL_Surface *SDLTest_ImagePrimitives(void); +SDL_Surface *SDLTest_ImagePrimitivesBlend(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_images_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_log.h b/third_party/SDL2/include/SDL_test_log.h new file mode 100644 index 00000000000..6f7f66145b0 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_log.h @@ -0,0 +1,67 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_log.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + * + * Wrapper to log in the TEST category + * + */ + +#ifndef SDL_test_log_h_ +#define SDL_test_log_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* + * \brief Prints given message with a timestamp in the TEST category and INFO priority. + * + * \param fmt Message to be logged + */ +void SDLTest_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1); + +/* + * \brief Prints given message with a timestamp in the TEST category and the ERROR priority. + * + * \param fmt Message to be logged + */ +void SDLTest_LogError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_log_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_md5.h b/third_party/SDL2/include/SDL_test_md5.h new file mode 100644 index 00000000000..edd79451c70 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_md5.h @@ -0,0 +1,129 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_md5.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + *********************************************************************** + ** Header file for implementation of MD5 ** + ** RSA Data Security, Inc. MD5 Message-Digest Algorithm ** + ** Created: 2/17/90 RLR ** + ** Revised: 12/27/90 SRD,AJ,BSK,JT Reference C version ** + ** Revised (for MD5): RLR 4/27/91 ** + ** -- G modified to have y&~z instead of y&z ** + ** -- FF, GG, HH modified to add in last register done ** + ** -- Access pattern: round 2 works mod 5, round 3 works mod 3 ** + ** -- distinct additive constant for each step ** + ** -- round 4 added, working mod 7 ** + *********************************************************************** +*/ + +/* + *********************************************************************** + ** Message-digest routines: ** + ** To form the message digest for a message M ** + ** (1) Initialize a context buffer mdContext using MD5Init ** + ** (2) Call MD5Update on mdContext and M ** + ** (3) Call MD5Final on mdContext ** + ** The message digest is now in mdContext->digest[0...15] ** + *********************************************************************** +*/ + +#ifndef SDL_test_md5_h_ +#define SDL_test_md5_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------ Definitions --------- */ + +/* typedef a 32-bit type */ + typedef unsigned long int MD5UINT4; + +/* Data structure for MD5 (Message-Digest) computation */ + typedef struct { + MD5UINT4 i[2]; /* number of _bits_ handled mod 2^64 */ + MD5UINT4 buf[4]; /* scratch buffer */ + unsigned char in[64]; /* input buffer */ + unsigned char digest[16]; /* actual digest after Md5Final call */ + } SDLTest_Md5Context; + +/* ---------- Function Prototypes ------------- */ + +/* + * \brief initialize the context + * + * \param mdContext pointer to context variable + * + * Note: The function initializes the message-digest context + * mdContext. Call before each new use of the context - + * all fields are set to zero. + */ + void SDLTest_Md5Init(SDLTest_Md5Context * mdContext); + + +/* + * \brief update digest from variable length data + * + * \param mdContext pointer to context variable + * \param inBuf pointer to data array/string + * \param inLen length of data array/string + * + * Note: The function updates the message-digest context to account + * for the presence of each of the characters inBuf[0..inLen-1] + * in the message whose digest is being computed. +*/ + + void SDLTest_Md5Update(SDLTest_Md5Context * mdContext, unsigned char *inBuf, + unsigned int inLen); + + +/* + * \brief complete digest computation + * + * \param mdContext pointer to context variable + * + * Note: The function terminates the message-digest computation and + * ends with the desired message digest in mdContext.digest[0..15]. + * Always call before using the digest[] variable. +*/ + + void SDLTest_Md5Final(SDLTest_Md5Context * mdContext); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_md5_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_memory.h b/third_party/SDL2/include/SDL_test_memory.h new file mode 100644 index 00000000000..e789fa802a5 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_memory.h @@ -0,0 +1,63 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_memory.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +#ifndef SDL_test_memory_h_ +#define SDL_test_memory_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + + +/* + * \brief Start tracking SDL memory allocations + * + * \note This should be called before any other SDL functions for complete tracking coverage + */ +int SDLTest_TrackAllocations(void); + +/* + * \brief Print a log of any outstanding allocations + * + * \note This can be called after SDL_Quit() + */ +void SDLTest_LogAllocations(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_memory_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_test_random.h b/third_party/SDL2/include/SDL_test_random.h new file mode 100644 index 00000000000..05d6d3ee5e2 --- /dev/null +++ b/third_party/SDL2/include/SDL_test_random.h @@ -0,0 +1,115 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* + * \file SDL_test_random.h + * + * Include file for SDL test framework. + * + * This code is a part of the SDL2_test library, not the main SDL library. + */ + +/* + + A "32-bit Multiply with carry random number generator. Very fast. + Includes a list of recommended multipliers. + + multiply-with-carry generator: x(n) = a*x(n-1) + carry mod 2^32. + period: (a*2^31)-1 + +*/ + +#ifndef SDL_test_random_h_ +#define SDL_test_random_h_ + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* --- Definitions */ + +/* + * Macros that return a random number in a specific format. + */ +#define SDLTest_RandomInt(c) ((int)SDLTest_Random(c)) + +/* + * Context structure for the random number generator state. + */ + typedef struct { + unsigned int a; + unsigned int x; + unsigned int c; + unsigned int ah; + unsigned int al; + } SDLTest_RandomContext; + + +/* --- Function prototypes */ + +/* + * \brief Initialize random number generator with two integers. + * + * Note: The random sequence of numbers returned by ...Random() is the + * same for the same two integers and has a period of 2^31. + * + * \param rndContext pointer to context structure + * \param xi integer that defines the random sequence + * \param ci integer that defines the random sequence + * + */ + void SDLTest_RandomInit(SDLTest_RandomContext * rndContext, unsigned int xi, + unsigned int ci); + +/* + * \brief Initialize random number generator based on current system time. + * + * \param rndContext pointer to context structure + * + */ + void SDLTest_RandomInitTime(SDLTest_RandomContext *rndContext); + + +/* + * \brief Initialize random number generator based on current system time. + * + * Note: ...RandomInit() or ...RandomInitTime() must have been called + * before using this function. + * + * \param rndContext pointer to context structure + * + * \returns a random number (32bit unsigned integer) + * + */ + unsigned int SDLTest_Random(SDLTest_RandomContext *rndContext); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_test_random_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_thread.h b/third_party/SDL2/include/SDL_thread.h new file mode 100644 index 00000000000..ac405d85ed5 --- /dev/null +++ b/third_party/SDL2/include/SDL_thread.h @@ -0,0 +1,468 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_thread_h_ +#define SDL_thread_h_ + +/** + * # CategoryThread + * + * Header for the SDL thread management routines. + */ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +/* Thread synchronization primitives */ +#include "SDL_atomic.h" +#include "SDL_mutex.h" + +#if (defined(__WIN32__) || defined(__GDK__)) && !defined(__WINRT__) +#include /* _beginthreadex() and _endthreadex() */ +#endif +#if defined(__OS2__) /* for _beginthread() and _endthread() */ +#ifndef __EMX__ +#include +#else +#include +#endif +#endif + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* The SDL thread structure, defined in SDL_thread.c */ +struct SDL_Thread; +typedef struct SDL_Thread SDL_Thread; + +/* The SDL thread ID */ +typedef unsigned long SDL_threadID; + +/* Thread local storage ID, 0 is the invalid ID */ +typedef unsigned int SDL_TLSID; + +/** + * The SDL thread priority. + * + * SDL will make system changes as necessary in order to apply the thread + * priority. Code which attempts to control thread state related to priority + * should be aware that calling SDL_SetThreadPriority may alter such state. + * SDL_HINT_THREAD_PRIORITY_POLICY can be used to control aspects of this + * behavior. + * + * On many systems you require special privileges to set high or time critical + * priority. + */ +typedef enum SDL_ThreadPriority { + SDL_THREAD_PRIORITY_LOW, + SDL_THREAD_PRIORITY_NORMAL, + SDL_THREAD_PRIORITY_HIGH, + SDL_THREAD_PRIORITY_TIME_CRITICAL +} SDL_ThreadPriority; + +/** + * The function passed to SDL_CreateThread(). + * + * \param data what was passed as `data` to SDL_CreateThread(). + * \returns a value that can be reported through SDL_WaitThread(). + */ +typedef int (SDLCALL * SDL_ThreadFunction) (void *data); + + +#if (defined(__WIN32__) || defined(__GDK__)) && !defined(__WINRT__) +/** + * \file SDL_thread.h + * + * We compile SDL into a DLL. This means, that it's the DLL which + * creates a new thread for the calling process with the SDL_CreateThread() + * API. There is a problem with this, that only the RTL of the SDL2.DLL will + * be initialized for those threads, and not the RTL of the calling + * application! + * + * To solve this, we make a little hack here. + * + * We'll always use the caller's _beginthread() and _endthread() APIs to + * start a new thread. This way, if it's the SDL2.DLL which uses this API, + * then the RTL of SDL2.DLL will be used to create the new thread, and if it's + * the application, then the RTL of the application will be used. + * + * So, in short: + * Always use the _beginthread() and _endthread() of the calling runtime + * library! + */ +#define SDL_PASSED_BEGINTHREAD_ENDTHREAD + +typedef uintptr_t (__cdecl * pfnSDL_CurrentBeginThread) + (void *, unsigned, unsigned (__stdcall *func)(void *), + void * /*arg*/, unsigned, unsigned * /* threadID */); +typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code); + +#ifndef SDL_beginthread +#define SDL_beginthread _beginthreadex +#endif +#ifndef SDL_endthread +#define SDL_endthread _endthreadex +#endif + +extern DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data, + pfnSDL_CurrentBeginThread pfnBeginThread, + pfnSDL_CurrentEndThread pfnEndThread); + +extern DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, + const char *name, const size_t stacksize, void *data, + pfnSDL_CurrentBeginThread pfnBeginThread, + pfnSDL_CurrentEndThread pfnEndThread); + + +#if defined(SDL_CreateThread) && SDL_DYNAMIC_API +#undef SDL_CreateThread +#define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) +#undef SDL_CreateThreadWithStackSize +#define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize_REAL(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) +#else +#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) +#define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) +#endif + +#elif defined(__OS2__) +/* + * just like the windows case above: We compile SDL2 + * into a dll with Watcom's runtime statically linked. + */ +#define SDL_PASSED_BEGINTHREAD_ENDTHREAD + +typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void * /*arg*/); +typedef void (*pfnSDL_CurrentEndThread)(void); + +#ifndef SDL_beginthread +#define SDL_beginthread _beginthread +#endif +#ifndef SDL_endthread +#define SDL_endthread _endthread +#endif + +extern DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data, + pfnSDL_CurrentBeginThread pfnBeginThread, + pfnSDL_CurrentEndThread pfnEndThread); +extern DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, const size_t stacksize, void *data, + pfnSDL_CurrentBeginThread pfnBeginThread, + pfnSDL_CurrentEndThread pfnEndThread); + +#if defined(SDL_CreateThread) && SDL_DYNAMIC_API +#undef SDL_CreateThread +#define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) +#undef SDL_CreateThreadWithStackSize +#define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize_REAL(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) +#else +#define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) +#define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) +#endif + +#else + +/** + * Create a new thread with a default stack size. + * + * This is equivalent to calling: + * + * ```c + * SDL_CreateThreadWithStackSize(fn, name, 0, data); + * ``` + * + * \param fn the SDL_ThreadFunction function to call in the new thread. + * \param name the name of the thread. + * \param data a pointer that is passed to `fn`. + * \returns an opaque pointer to the new thread object on success, NULL if the + * new thread could not be created; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateThreadWithStackSize + * \sa SDL_WaitThread + */ +extern DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data); + +/** + * Create a new thread with a specific stack size. + * + * SDL makes an attempt to report `name` to the system, so that debuggers can + * display it. Not all platforms support this. + * + * Thread naming is a little complicated: Most systems have very small limits + * for the string length (Haiku has 32 bytes, Linux currently has 16, Visual + * C++ 6.0 has _nine_!), and possibly other arbitrary rules. You'll have to + * see what happens with your system's debugger. The name should be UTF-8 (but + * using the naming limits of C identifiers is a better bet). There are no + * requirements for thread naming conventions, so long as the string is + * null-terminated UTF-8, but these guidelines are helpful in choosing a name: + * + * https://stackoverflow.com/questions/149932/naming-conventions-for-threads + * + * If a system imposes requirements, SDL will try to munge the string for it + * (truncate, etc), but the original string contents will be available from + * SDL_GetThreadName(). + * + * The size (in bytes) of the new stack can be specified. Zero means "use the + * system default" which might be wildly different between platforms. x86 + * Linux generally defaults to eight megabytes, an embedded device might be a + * few kilobytes instead. You generally need to specify a stack that is a + * multiple of the system's page size (in many cases, this is 4 kilobytes, but + * check your system documentation). + * + * In SDL 2.1, stack size will be folded into the original SDL_CreateThread + * function, but for backwards compatibility, this is currently a separate + * function. + * + * \param fn the SDL_ThreadFunction function to call in the new thread. + * \param name the name of the thread. + * \param stacksize the size, in bytes, to allocate for the new thread stack. + * \param data a pointer that is passed to `fn`. + * \returns an opaque pointer to the new thread object on success, NULL if the + * new thread could not be created; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.9. + * + * \sa SDL_WaitThread + */ +extern DECLSPEC SDL_Thread *SDLCALL +SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, const size_t stacksize, void *data); + +#endif + +/** + * Get the thread name as it was specified in SDL_CreateThread(). + * + * This is internal memory, not to be freed by the caller, and remains valid + * until the specified thread is cleaned up by SDL_WaitThread(). + * + * \param thread the thread to query. + * \returns a pointer to a UTF-8 string that names the specified thread, or + * NULL if it doesn't have a name. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateThread + */ +extern DECLSPEC const char *SDLCALL SDL_GetThreadName(SDL_Thread *thread); + +/** + * Get the thread identifier for the current thread. + * + * This thread identifier is as reported by the underlying operating system. + * If SDL is running on a platform that does not support threads the return + * value will always be zero. + * + * This function also returns a valid thread ID when called from the main + * thread. + * + * \returns the ID of the current thread. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetThreadID + */ +extern DECLSPEC SDL_threadID SDLCALL SDL_ThreadID(void); + +/** + * Get the thread identifier for the specified thread. + * + * This thread identifier is as reported by the underlying operating system. + * If SDL is running on a platform that does not support threads the return + * value will always be zero. + * + * \param thread the thread to query. + * \returns the ID of the specified thread, or the ID of the current thread if + * `thread` is NULL. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ThreadID + */ +extern DECLSPEC SDL_threadID SDLCALL SDL_GetThreadID(SDL_Thread * thread); + +/** + * Set the priority for the current thread. + * + * Note that some platforms will not let you alter the priority (or at least, + * promote the thread to a higher priority) at all, and some require you to be + * an administrator account. Be prepared for this to fail. + * + * \param priority the SDL_ThreadPriority to set. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC int SDLCALL SDL_SetThreadPriority(SDL_ThreadPriority priority); + +/** + * Wait for a thread to finish. + * + * Threads that haven't been detached will remain (as a "zombie") until this + * function cleans them up. Not doing so is a resource leak. + * + * Once a thread has been cleaned up through this function, the SDL_Thread + * that references it becomes invalid and should not be referenced again. As + * such, only one thread may call SDL_WaitThread() on another. + * + * The return code for the thread function is placed in the area pointed to by + * `status`, if `status` is not NULL. + * + * You may not wait on a thread that has been used in a call to + * SDL_DetachThread(). Use either that function or this one, but not both, or + * behavior is undefined. + * + * It is safe to pass a NULL thread to this function; it is a no-op. + * + * Note that the thread pointer is freed by this function and is not valid + * afterward. + * + * \param thread the SDL_Thread pointer that was returned from the + * SDL_CreateThread() call that started this thread. + * \param status pointer to an integer that will receive the value returned + * from the thread function by its 'return', or NULL to not + * receive such value back. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateThread + * \sa SDL_DetachThread + */ +extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread * thread, int *status); + +/** + * Let a thread clean up on exit without intervention. + * + * A thread may be "detached" to signify that it should not remain until + * another thread has called SDL_WaitThread() on it. Detaching a thread is + * useful for long-running threads that nothing needs to synchronize with or + * further manage. When a detached thread is done, it simply goes away. + * + * There is no way to recover the return code of a detached thread. If you + * need this, don't detach the thread and instead use SDL_WaitThread(). + * + * Once a thread is detached, you should usually assume the SDL_Thread isn't + * safe to reference again, as it will become invalid immediately upon the + * detached thread's exit, instead of remaining until someone has called + * SDL_WaitThread() to finally clean it up. As such, don't detach the same + * thread more than once. + * + * If a thread has already exited when passed to SDL_DetachThread(), it will + * stop waiting for a call to SDL_WaitThread() and clean up immediately. It is + * not safe to detach a thread that might be used with SDL_WaitThread(). + * + * You may not call SDL_WaitThread() on a thread that has been detached. Use + * either that function or this one, but not both, or behavior is undefined. + * + * It is safe to pass NULL to this function; it is a no-op. + * + * \param thread the SDL_Thread pointer that was returned from the + * SDL_CreateThread() call that started this thread. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_CreateThread + * \sa SDL_WaitThread + */ +extern DECLSPEC void SDLCALL SDL_DetachThread(SDL_Thread * thread); + +/** + * Create a piece of thread-local storage. + * + * This creates an identifier that is globally visible to all threads but + * refers to data that is thread-specific. + * + * \returns the newly created thread local storage identifier or 0 on error. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_TLSGet + * \sa SDL_TLSSet + */ +extern DECLSPEC SDL_TLSID SDLCALL SDL_TLSCreate(void); + +/** + * Get the current thread's value associated with a thread local storage ID. + * + * \param id the thread local storage ID. + * \returns the value associated with the ID for the current thread or NULL if + * no value has been set; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_TLSCreate + * \sa SDL_TLSSet + */ +extern DECLSPEC void * SDLCALL SDL_TLSGet(SDL_TLSID id); + +typedef void (SDLCALL *SDL_TLSDestructorCallback)(void*); + +/** + * Set the current thread's value associated with a thread local storage ID. + * + * The function prototype for `destructor` is: + * + * ```c + * void destructor(void *value) + * ``` + * + * where its parameter `value` is what was passed as `value` to SDL_TLSSet(). + * + * \param id the thread local storage ID. + * \param value the value to associate with the ID for the current thread. + * \param destructor a function called when the thread exits, to free the + * value. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_TLSCreate + * \sa SDL_TLSGet + */ +extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, SDL_TLSDestructorCallback destructor); + +/** + * Cleanup all TLS data for this thread. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC void SDLCALL SDL_TLSCleanup(void); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_thread_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_timer.h b/third_party/SDL2/include/SDL_timer.h new file mode 100644 index 00000000000..60969690b23 --- /dev/null +++ b/third_party/SDL2/include/SDL_timer.h @@ -0,0 +1,222 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_timer_h_ +#define SDL_timer_h_ + +/** + * # CategoryTimer + * + * Header for the SDL time management routines. + */ + +#include "SDL_stdinc.h" +#include "SDL_error.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Get the number of milliseconds since SDL library initialization. + * + * This value wraps if the program runs for more than ~49 days. + * + * This function is not recommended as of SDL 2.0.18; use SDL_GetTicks64() + * instead, where the value doesn't wrap every ~49 days. There are places in + * SDL where we provide a 32-bit timestamp that can not change without + * breaking binary compatibility, though, so this function isn't officially + * deprecated. + * + * \returns an unsigned 32-bit value representing the number of milliseconds + * since the SDL library initialized. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_TICKS_PASSED + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void); + +/** + * Get the number of milliseconds since SDL library initialization. + * + * Note that you should not use the SDL_TICKS_PASSED macro with values + * returned by this function, as that macro does clever math to compensate for + * the 32-bit overflow every ~49 days that SDL_GetTicks() suffers from. 64-bit + * values from this function can be safely compared directly. + * + * For example, if you want to wait 100 ms, you could do this: + * + * ```c + * const Uint64 timeout = SDL_GetTicks64() + 100; + * while (SDL_GetTicks64() < timeout) { + * // ... do work until timeout has elapsed + * } + * ``` + * + * \returns an unsigned 64-bit value representing the number of milliseconds + * since the SDL library initialized. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC Uint64 SDLCALL SDL_GetTicks64(void); + +/** + * Compare 32-bit SDL ticks values, and return true if `A` has passed `B`. + * + * This should be used with results from SDL_GetTicks(), as this macro + * attempts to deal with the 32-bit counter wrapping back to zero every ~49 + * days, but should _not_ be used with SDL_GetTicks64(), which does not have + * that problem. + * + * For example, with SDL_GetTicks(), if you want to wait 100 ms, you could do + * this: + * + * ```c + * const Uint32 timeout = SDL_GetTicks() + 100; + * while (!SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) { + * // ... do work until timeout has elapsed + * } + * ``` + * + * Note that this does not handle tick differences greater than 2^31 so take + * care when using the above kind of code with large timeout delays (tens of + * days). + */ +#define SDL_TICKS_PASSED(A, B) ((Sint32)((B) - (A)) <= 0) + +/** + * Get the current value of the high resolution counter. + * + * This function is typically used for profiling. + * + * The counter values are only meaningful relative to each other. Differences + * between values can be converted to times by using + * SDL_GetPerformanceFrequency(). + * + * \returns the current counter value. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetPerformanceFrequency + */ +extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceCounter(void); + +/** + * Get the count per second of the high resolution counter. + * + * \returns a platform-specific count per second. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetPerformanceCounter + */ +extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceFrequency(void); + +/** + * Wait a specified number of milliseconds before returning. + * + * This function waits a specified number of milliseconds before returning. It + * waits at least the specified time, but possibly longer due to OS + * scheduling. + * + * \param ms the number of milliseconds to delay. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms); + +/** + * Function prototype for the timer callback function. + * + * The callback function is passed the current timer interval and returns the + * next timer interval. If the returned value is the same as the one passed + * in, the periodic alarm continues, otherwise a new alarm is scheduled. If + * the callback returns 0, the periodic alarm is cancelled. + */ +typedef Uint32 (SDLCALL * SDL_TimerCallback) (Uint32 interval, void *param); + +/** + * Definition of the timer ID type. + */ +typedef int SDL_TimerID; + +/** + * Call a callback function at a future time. + * + * If you use this function, you must pass `SDL_INIT_TIMER` to SDL_Init(). + * + * The callback function is passed the current timer interval and the user + * supplied parameter from the SDL_AddTimer() call and should return the next + * timer interval. If the value returned from the callback is 0, the timer is + * canceled. + * + * The callback is run on a separate thread. + * + * Timers take into account the amount of time it took to execute the + * callback. For example, if the callback took 250 ms to execute and returned + * 1000 (ms), the timer would only wait another 750 ms before its next + * iteration. + * + * Timing may be inexact due to OS scheduling. Be sure to note the current + * time with SDL_GetTicks() or SDL_GetPerformanceCounter() in case your + * callback needs to adjust for variances. + * + * \param interval the timer delay, in milliseconds, passed to `callback`. + * \param callback the SDL_TimerCallback function to call when the specified + * `interval` elapses. + * \param param a pointer that is passed to `callback`. + * \returns a timer ID or 0 if an error occurs; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RemoveTimer + */ +extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, + SDL_TimerCallback callback, + void *param); + +/** + * Remove a timer created with SDL_AddTimer(). + * + * \param id the ID of the timer to remove. + * \returns SDL_TRUE if the timer is removed or SDL_FALSE if the timer wasn't + * found. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_AddTimer + */ +extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID id); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_timer_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_touch.h b/third_party/SDL2/include/SDL_touch.h new file mode 100644 index 00000000000..80a0fef8ac6 --- /dev/null +++ b/third_party/SDL2/include/SDL_touch.h @@ -0,0 +1,150 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryTouch + * + * Include file for SDL touch event handling. + */ + +#ifndef SDL_touch_h_ +#define SDL_touch_h_ + +#include "SDL_stdinc.h" +#include "SDL_error.h" +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +typedef Sint64 SDL_TouchID; +typedef Sint64 SDL_FingerID; + +typedef enum +{ + SDL_TOUCH_DEVICE_INVALID = -1, + SDL_TOUCH_DEVICE_DIRECT, /* touch screen with window-relative coordinates */ + SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE, /* trackpad with absolute device coordinates */ + SDL_TOUCH_DEVICE_INDIRECT_RELATIVE /* trackpad with screen cursor-relative coordinates */ +} SDL_TouchDeviceType; + +typedef struct SDL_Finger +{ + SDL_FingerID id; + float x; + float y; + float pressure; +} SDL_Finger; + +/* Used as the device ID for mouse events simulated with touch input */ +#define SDL_TOUCH_MOUSEID ((Uint32)-1) + +/* Used as the SDL_TouchID for touch events simulated with mouse input */ +#define SDL_MOUSE_TOUCHID ((Sint64)-1) + + +/** + * Get the number of registered touch devices. + * + * On some platforms SDL first sees the touch device if it was actually used. + * Therefore SDL_GetNumTouchDevices() may return 0 although devices are + * available. After using all devices at least once the number will be + * correct. + * + * This was fixed for Android in SDL 2.0.1. + * + * \returns the number of registered touch devices. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetTouchDevice + */ +extern DECLSPEC int SDLCALL SDL_GetNumTouchDevices(void); + +/** + * Get the touch ID with the given index. + * + * \param index the touch device index. + * \returns the touch ID with the given index on success or 0 if the index is + * invalid; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumTouchDevices + */ +extern DECLSPEC SDL_TouchID SDLCALL SDL_GetTouchDevice(int index); + +/** + * Get the touch device name as reported from the driver or NULL if the index + * is invalid. + * + * \since This function is available since SDL 2.0.22. + */ +extern DECLSPEC const char* SDLCALL SDL_GetTouchName(int index); + +/** + * Get the type of the given touch device. + * + * \since This function is available since SDL 2.0.10. + */ +extern DECLSPEC SDL_TouchDeviceType SDLCALL SDL_GetTouchDeviceType(SDL_TouchID touchID); + +/** + * Get the number of active fingers for a given touch device. + * + * \param touchID the ID of a touch device. + * \returns the number of active fingers for a given touch device on success + * or 0 on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetTouchFinger + */ +extern DECLSPEC int SDLCALL SDL_GetNumTouchFingers(SDL_TouchID touchID); + +/** + * Get the finger object for specified touch device ID and finger index. + * + * The returned resource is owned by SDL and should not be deallocated. + * + * \param touchID the ID of the requested touch device. + * \param index the index of the requested finger. + * \returns a pointer to the SDL_Finger object or NULL if no object at the + * given ID and index could be found. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_RecordGesture + */ +extern DECLSPEC SDL_Finger * SDLCALL SDL_GetTouchFinger(SDL_TouchID touchID, int index); + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_touch_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_types.h b/third_party/SDL2/include/SDL_types.h new file mode 100644 index 00000000000..cb3b4a8df1a --- /dev/null +++ b/third_party/SDL2/include/SDL_types.h @@ -0,0 +1,24 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* DEPRECATED */ + +#include "SDL_stdinc.h" diff --git a/third_party/SDL2/include/SDL_version.h b/third_party/SDL2/include/SDL_version.h new file mode 100644 index 00000000000..32d1133beea --- /dev/null +++ b/third_party/SDL2/include/SDL_version.h @@ -0,0 +1,205 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryVersion + * + * This header defines the current SDL version. + */ + +#ifndef SDL_version_h_ +#define SDL_version_h_ + +#include "SDL_stdinc.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Information about the version of SDL in use. + * + * Represents the library's version as three levels: major revision + * (increments with massive changes, additions, and enhancements), minor + * revision (increments with backwards-compatible changes to the major + * revision), and patchlevel (increments with fixes to the minor revision). + * + * \sa SDL_VERSION + * \sa SDL_GetVersion + */ +typedef struct SDL_version +{ + Uint8 major; /**< major version */ + Uint8 minor; /**< minor version */ + Uint8 patch; /**< update version */ +} SDL_version; + +/* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL +*/ +#define SDL_MAJOR_VERSION 2 +#define SDL_MINOR_VERSION 32 +#define SDL_PATCHLEVEL 0 + +/** + * Macro to determine SDL version program was compiled against. + * + * This macro fills in a SDL_version structure with the version of the library + * you compiled against. This is determined by what header the compiler uses. + * Note that if you dynamically linked the library, you might have a slightly + * newer or older version at runtime. That version can be determined with + * SDL_GetVersion(), which, unlike SDL_VERSION(), is not a macro. + * + * \param x A pointer to a SDL_version struct to initialize. + * + * \sa SDL_version + * \sa SDL_GetVersion + */ +#define SDL_VERSION(x) \ +{ \ + (x)->major = SDL_MAJOR_VERSION; \ + (x)->minor = SDL_MINOR_VERSION; \ + (x)->patch = SDL_PATCHLEVEL; \ +} + +/* TODO: Remove this whole block in SDL 3 */ +#if SDL_MAJOR_VERSION < 3 + +/** + * This macro turns the version numbers into a numeric value: + * + * ``` + * (1,2,3) -> (1203) + * ``` + * + * This assumes that there will never be more than 100 patchlevels. + * + * In versions higher than 2.9.0, the minor version overflows into the + * thousands digit: for example, 2.23.0 is encoded as 4300, and 2.255.99 would + * be encoded as 25799. + * + * This macro will not be available in SDL 3.x. + */ +#define SDL_VERSIONNUM(X, Y, Z) \ + ((X)*1000 + (Y)*100 + (Z)) + +/** + * This is the version number macro for the current SDL version. + * + * In versions higher than 2.9.0, the minor version overflows into the + * thousands digit: for example, 2.23.0 is encoded as 4300. This macro will + * not be available in SDL 3.x. + * + * Deprecated, use SDL_VERSION_ATLEAST or SDL_VERSION instead. + */ +#define SDL_COMPILEDVERSION \ + SDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL) +#endif /* SDL_MAJOR_VERSION < 3 */ + +/** + * This macro will evaluate to true if compiled with SDL at least X.Y.Z. + */ +#define SDL_VERSION_ATLEAST(X, Y, Z) \ + ((SDL_MAJOR_VERSION >= X) && \ + (SDL_MAJOR_VERSION > X || SDL_MINOR_VERSION >= Y) && \ + (SDL_MAJOR_VERSION > X || SDL_MINOR_VERSION > Y || SDL_PATCHLEVEL >= Z)) + +/** + * Get the version of SDL that is linked against your program. + * + * If you are linking to SDL dynamically, then it is possible that the current + * version will be different than the version you compiled against. This + * function returns the current version, while SDL_VERSION() is a macro that + * tells you what version you compiled with. + * + * This function may be called safely at any time, even before SDL_Init(). + * + * \param ver the SDL_version structure that contains the version information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRevision + */ +extern DECLSPEC void SDLCALL SDL_GetVersion(SDL_version * ver); + +/** + * Get the code revision of SDL that is linked against your program. + * + * This value is the revision of the code you are linked with and may be + * different from the code you are compiling with, which is found in the + * constant SDL_REVISION. + * + * The revision is arbitrary string (a hash value) uniquely identifying the + * exact revision of the SDL library in use, and is only useful in comparing + * against other revisions. It is NOT an incrementing number. + * + * If SDL wasn't built from a git repository with the appropriate tools, this + * will return an empty string. + * + * Prior to SDL 2.0.16, before development moved to GitHub, this returned a + * hash for a Mercurial repository. + * + * You shouldn't use this function for anything but logging it for debugging + * purposes. The string is not intended to be reliable in any way. + * + * \returns an arbitrary string, uniquely identifying the exact revision of + * the SDL library in use. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetVersion + */ +extern DECLSPEC const char *SDLCALL SDL_GetRevision(void); + +/** + * Obsolete function, do not use. + * + * When SDL was hosted in a Mercurial repository, and was built carefully, + * this would return the revision number that the build was created from. This + * number was not reliable for several reasons, but more importantly, SDL is + * now hosted in a git repository, which does not offer numbers at all, only + * hashes. This function only ever returns zero now. Don't use it. + * + * Before SDL 2.0.16, this might have returned an unreliable, but non-zero + * number. + * + * \deprecated Use SDL_GetRevision() instead; if SDL was carefully built, it + * will return a git hash. + * + * \returns zero, always, in modern SDL releases. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetRevision + */ +extern SDL_DEPRECATED DECLSPEC int SDLCALL SDL_GetRevisionNumber(void); + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_version_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_video.h b/third_party/SDL2/include/SDL_video.h new file mode 100644 index 00000000000..2db5552fa22 --- /dev/null +++ b/third_party/SDL2/include/SDL_video.h @@ -0,0 +1,2228 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryVideo + * + * Header file for SDL video functions. + */ + +#ifndef SDL_video_h_ +#define SDL_video_h_ + +#include "SDL_stdinc.h" +#include "SDL_pixels.h" +#include "SDL_rect.h" +#include "SDL_surface.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The structure that defines a display mode + * + * \sa SDL_GetNumDisplayModes + * \sa SDL_GetDisplayMode + * \sa SDL_GetDesktopDisplayMode + * \sa SDL_GetCurrentDisplayMode + * \sa SDL_GetClosestDisplayMode + * \sa SDL_SetWindowDisplayMode + * \sa SDL_GetWindowDisplayMode + */ +typedef struct SDL_DisplayMode +{ + Uint32 format; /**< pixel format */ + int w; /**< width, in screen coordinates */ + int h; /**< height, in screen coordinates */ + int refresh_rate; /**< refresh rate (or zero for unspecified) */ + void *driverdata; /**< driver-specific data, initialize to 0 */ +} SDL_DisplayMode; + +/** + * The opaque type used to identify a window. + * + * \sa SDL_CreateWindow + * \sa SDL_CreateWindowFrom + * \sa SDL_DestroyWindow + * \sa SDL_FlashWindow + * \sa SDL_GetWindowData + * \sa SDL_GetWindowFlags + * \sa SDL_GetWindowGrab + * \sa SDL_GetWindowKeyboardGrab + * \sa SDL_GetWindowMouseGrab + * \sa SDL_GetWindowPosition + * \sa SDL_GetWindowSize + * \sa SDL_GetWindowTitle + * \sa SDL_HideWindow + * \sa SDL_MaximizeWindow + * \sa SDL_MinimizeWindow + * \sa SDL_RaiseWindow + * \sa SDL_RestoreWindow + * \sa SDL_SetWindowData + * \sa SDL_SetWindowFullscreen + * \sa SDL_SetWindowGrab + * \sa SDL_SetWindowKeyboardGrab + * \sa SDL_SetWindowMouseGrab + * \sa SDL_SetWindowIcon + * \sa SDL_SetWindowPosition + * \sa SDL_SetWindowSize + * \sa SDL_SetWindowBordered + * \sa SDL_SetWindowResizable + * \sa SDL_SetWindowTitle + * \sa SDL_ShowWindow + */ +typedef struct SDL_Window SDL_Window; + +/** + * The flags on a window + * + * \sa SDL_GetWindowFlags + */ +typedef enum SDL_WindowFlags +{ + SDL_WINDOW_FULLSCREEN = 0x00000001, /**< fullscreen window */ + SDL_WINDOW_OPENGL = 0x00000002, /**< window usable with OpenGL context */ + SDL_WINDOW_SHOWN = 0x00000004, /**< window is visible */ + SDL_WINDOW_HIDDEN = 0x00000008, /**< window is not visible */ + SDL_WINDOW_BORDERLESS = 0x00000010, /**< no window decoration */ + SDL_WINDOW_RESIZABLE = 0x00000020, /**< window can be resized */ + SDL_WINDOW_MINIMIZED = 0x00000040, /**< window is minimized */ + SDL_WINDOW_MAXIMIZED = 0x00000080, /**< window is maximized */ + SDL_WINDOW_MOUSE_GRABBED = 0x00000100, /**< window has grabbed mouse input */ + SDL_WINDOW_INPUT_FOCUS = 0x00000200, /**< window has input focus */ + SDL_WINDOW_MOUSE_FOCUS = 0x00000400, /**< window has mouse focus */ + SDL_WINDOW_FULLSCREEN_DESKTOP = ( SDL_WINDOW_FULLSCREEN | 0x00001000 ), + SDL_WINDOW_FOREIGN = 0x00000800, /**< window not created by SDL */ + SDL_WINDOW_ALLOW_HIGHDPI = 0x00002000, /**< window should be created in high-DPI mode if supported. + On macOS NSHighResolutionCapable must be set true in the + application's Info.plist for this to have any effect. */ + SDL_WINDOW_MOUSE_CAPTURE = 0x00004000, /**< window has mouse captured (unrelated to MOUSE_GRABBED) */ + SDL_WINDOW_ALWAYS_ON_TOP = 0x00008000, /**< window should always be above others */ + SDL_WINDOW_SKIP_TASKBAR = 0x00010000, /**< window should not be added to the taskbar */ + SDL_WINDOW_UTILITY = 0x00020000, /**< window should be treated as a utility window */ + SDL_WINDOW_TOOLTIP = 0x00040000, /**< window should be treated as a tooltip */ + SDL_WINDOW_POPUP_MENU = 0x00080000, /**< window should be treated as a popup menu */ + SDL_WINDOW_KEYBOARD_GRABBED = 0x00100000, /**< window has grabbed keyboard input */ + SDL_WINDOW_VULKAN = 0x10000000, /**< window usable for Vulkan surface */ + SDL_WINDOW_METAL = 0x20000000, /**< window usable for Metal view */ + + SDL_WINDOW_INPUT_GRABBED = SDL_WINDOW_MOUSE_GRABBED /**< equivalent to SDL_WINDOW_MOUSE_GRABBED for compatibility */ +} SDL_WindowFlags; + +/** + * Used to indicate that you don't care what the window position is. + */ +#define SDL_WINDOWPOS_UNDEFINED_MASK 0x1FFF0000u +#define SDL_WINDOWPOS_UNDEFINED_DISPLAY(X) (SDL_WINDOWPOS_UNDEFINED_MASK|(X)) +#define SDL_WINDOWPOS_UNDEFINED SDL_WINDOWPOS_UNDEFINED_DISPLAY(0) +#define SDL_WINDOWPOS_ISUNDEFINED(X) \ + (((X)&0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK) + +/** + * Used to indicate that the window position should be centered. + */ +#define SDL_WINDOWPOS_CENTERED_MASK 0x2FFF0000u +#define SDL_WINDOWPOS_CENTERED_DISPLAY(X) (SDL_WINDOWPOS_CENTERED_MASK|(X)) +#define SDL_WINDOWPOS_CENTERED SDL_WINDOWPOS_CENTERED_DISPLAY(0) +#define SDL_WINDOWPOS_ISCENTERED(X) \ + (((X)&0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK) + +/** + * Event subtype for window events + */ +typedef enum SDL_WindowEventID +{ + SDL_WINDOWEVENT_NONE, /**< Never used */ + SDL_WINDOWEVENT_SHOWN, /**< Window has been shown */ + SDL_WINDOWEVENT_HIDDEN, /**< Window has been hidden */ + SDL_WINDOWEVENT_EXPOSED, /**< Window has been exposed and should be + redrawn */ + SDL_WINDOWEVENT_MOVED, /**< Window has been moved to data1, data2 + */ + SDL_WINDOWEVENT_RESIZED, /**< Window has been resized to data1xdata2 */ + SDL_WINDOWEVENT_SIZE_CHANGED, /**< The window size has changed, either as + a result of an API call or through the + system or user changing the window size. */ + SDL_WINDOWEVENT_MINIMIZED, /**< Window has been minimized */ + SDL_WINDOWEVENT_MAXIMIZED, /**< Window has been maximized */ + SDL_WINDOWEVENT_RESTORED, /**< Window has been restored to normal size + and position */ + SDL_WINDOWEVENT_ENTER, /**< Window has gained mouse focus */ + SDL_WINDOWEVENT_LEAVE, /**< Window has lost mouse focus */ + SDL_WINDOWEVENT_FOCUS_GAINED, /**< Window has gained keyboard focus */ + SDL_WINDOWEVENT_FOCUS_LOST, /**< Window has lost keyboard focus */ + SDL_WINDOWEVENT_CLOSE, /**< The window manager requests that the window be closed */ + SDL_WINDOWEVENT_TAKE_FOCUS, /**< Window is being offered a focus (should SetWindowInputFocus() on itself or a subwindow, or ignore) */ + SDL_WINDOWEVENT_HIT_TEST, /**< Window had a hit test that wasn't SDL_HITTEST_NORMAL. */ + SDL_WINDOWEVENT_ICCPROF_CHANGED,/**< The ICC profile of the window's display has changed. */ + SDL_WINDOWEVENT_DISPLAY_CHANGED /**< Window has been moved to display data1. */ +} SDL_WindowEventID; + +/** + * Event subtype for display events + */ +typedef enum SDL_DisplayEventID +{ + SDL_DISPLAYEVENT_NONE, /**< Never used */ + SDL_DISPLAYEVENT_ORIENTATION, /**< Display orientation has changed to data1 */ + SDL_DISPLAYEVENT_CONNECTED, /**< Display has been added to the system */ + SDL_DISPLAYEVENT_DISCONNECTED, /**< Display has been removed from the system */ + SDL_DISPLAYEVENT_MOVED /**< Display has changed position */ +} SDL_DisplayEventID; + +/** + * Display orientation + */ +typedef enum SDL_DisplayOrientation +{ + SDL_ORIENTATION_UNKNOWN, /**< The display orientation can't be determined */ + SDL_ORIENTATION_LANDSCAPE, /**< The display is in landscape mode, with the right side up, relative to portrait mode */ + SDL_ORIENTATION_LANDSCAPE_FLIPPED, /**< The display is in landscape mode, with the left side up, relative to portrait mode */ + SDL_ORIENTATION_PORTRAIT, /**< The display is in portrait mode */ + SDL_ORIENTATION_PORTRAIT_FLIPPED /**< The display is in portrait mode, upside down */ +} SDL_DisplayOrientation; + +/** + * Window flash operation + */ +typedef enum SDL_FlashOperation +{ + SDL_FLASH_CANCEL, /**< Cancel any window flash state */ + SDL_FLASH_BRIEFLY, /**< Flash the window briefly to get attention */ + SDL_FLASH_UNTIL_FOCUSED /**< Flash the window until it gets focus */ +} SDL_FlashOperation; + +/** + * An opaque handle to an OpenGL context. + * + * \sa SDL_GL_CreateContext + */ +typedef void *SDL_GLContext; + +/** + * OpenGL configuration attributes. + * + * While you can set most OpenGL attributes normally, the attributes listed + * above must be known before SDL creates the window that will be used with + * the OpenGL context. These attributes are set and read with + * SDL_GL_SetAttribute and SDL_GL_GetAttribute. + * + * In some cases, these attributes are minimum requests; the GL does not + * promise to give you exactly what you asked for. It's possible to ask for a + * 16-bit depth buffer and get a 24-bit one instead, for example, or to ask + * for no stencil buffer and still have one available. Context creation should + * fail if the GL can't provide your requested attributes at a minimum, but + * you should check to see exactly what you got. + * + * + * [Multisample anti-aliasing](http://en.wikipedia.org/wiki/Multisample_anti-aliasing) + * is a type of full screen anti-aliasing. Multipsampling defaults to off but + * can be turned on by setting SDL_GL_MULTISAMPLEBUFFERS to 1 and + * SDL_GL_MULTISAMPLESAMPLES to a value greater than 0. Typical values are 2 + * and 4. + * + * SDL_GL_CONTEXT_PROFILE_MASK determines the type of context created, while + * both SDL_GL_CONTEXT_MAJOR_VERSION and SDL_GL_CONTEXT_MINOR_VERSION + * determine which version. All three attributes must be set prior to creating + * the first window, and in general you can't change the value of + * SDL_GL_CONTEXT_PROFILE_MASK without first destroying all windows created + * with the previous setting. + * + * SDL_GL_CONTEXT_RELEASE_BEHAVIOR can be set to + * SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE or + * SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH. + */ +typedef enum SDL_GLattr +{ + SDL_GL_RED_SIZE, /**< the minimum number of bits for the red channel of the color buffer; defaults to 3. */ + SDL_GL_GREEN_SIZE, /**< the minimum number of bits for the green channel of the color buffer; defaults to 3. */ + SDL_GL_BLUE_SIZE, /**< the minimum number of bits for the blue channel of the color buffer; defaults to 2. */ + SDL_GL_ALPHA_SIZE, /**< the minimum number of bits for the alpha channel of the color buffer; defaults to 0. */ + SDL_GL_BUFFER_SIZE, /**< the minimum number of bits for frame buffer size; defaults to 0. */ + SDL_GL_DOUBLEBUFFER, /**< whether the output is single or double buffered; defaults to double buffering on. */ + SDL_GL_DEPTH_SIZE, /**< the minimum number of bits in the depth buffer; defaults to 16. */ + SDL_GL_STENCIL_SIZE, /**< the minimum number of bits in the stencil buffer; defaults to 0. */ + SDL_GL_ACCUM_RED_SIZE, /**< the minimum number of bits for the red channel of the accumulation buffer; defaults to 0. */ + SDL_GL_ACCUM_GREEN_SIZE, /**< the minimum number of bits for the green channel of the accumulation buffer; defaults to 0. */ + SDL_GL_ACCUM_BLUE_SIZE, /**< the minimum number of bits for the blue channel of the accumulation buffer; defaults to 0. */ + SDL_GL_ACCUM_ALPHA_SIZE, /**< the minimum number of bits for the alpha channel of the accumulation buffer; defaults to 0. */ + SDL_GL_STEREO, /**< whether the output is stereo 3D; defaults to off. */ + SDL_GL_MULTISAMPLEBUFFERS, /**< the number of buffers used for multisample anti-aliasing; defaults to 0. */ + SDL_GL_MULTISAMPLESAMPLES, /**< the number of samples used around the current pixel used for multisample anti-aliasing. */ + SDL_GL_ACCELERATED_VISUAL, /**< set to 1 to require hardware acceleration, set to 0 to force software rendering; defaults to allow either. */ + SDL_GL_RETAINED_BACKING, /**< not used (deprecated). */ + SDL_GL_CONTEXT_MAJOR_VERSION, /**< OpenGL context major version. */ + SDL_GL_CONTEXT_MINOR_VERSION, /**< OpenGL context minor version. */ + SDL_GL_CONTEXT_EGL, /**< deprecated: set SDL_GL_CONTEXT_PROFILE_MASK to SDL_GL_CONTEXT_PROFILE_ES to enable instead. */ + SDL_GL_CONTEXT_FLAGS, /**< some combination of 0 or more of elements of the SDL_GLcontextFlag enumeration; defaults to 0. */ + SDL_GL_CONTEXT_PROFILE_MASK, /**< type of GL context (Core, Compatibility, ES). See SDL_GLprofile; default value depends on platform. */ + SDL_GL_SHARE_WITH_CURRENT_CONTEXT, /**< OpenGL context sharing; defaults to 0. */ + SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, /**< requests sRGB capable visual; defaults to 0. (>= SDL 2.0.1) */ + SDL_GL_CONTEXT_RELEASE_BEHAVIOR, /**< sets context the release behavior; defaults to 1. (>= SDL 2.0.4) */ + SDL_GL_CONTEXT_RESET_NOTIFICATION, + SDL_GL_CONTEXT_NO_ERROR, + SDL_GL_FLOATBUFFERS +} SDL_GLattr; + +typedef enum SDL_GLprofile +{ + SDL_GL_CONTEXT_PROFILE_CORE = 0x0001, + SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 0x0002, + SDL_GL_CONTEXT_PROFILE_ES = 0x0004 /**< GLX_CONTEXT_ES2_PROFILE_BIT_EXT */ +} SDL_GLprofile; + +typedef enum SDL_GLcontextFlag +{ + SDL_GL_CONTEXT_DEBUG_FLAG = 0x0001, + SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 0x0002, + SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 0x0004, + SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 0x0008 +} SDL_GLcontextFlag; + +typedef enum SDL_GLcontextReleaseFlag +{ + SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0x0000, + SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 0x0001 +} SDL_GLcontextReleaseFlag; + +typedef enum SDL_GLContextResetNotification +{ + SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0x0000, + SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 0x0001 +} SDL_GLContextResetNotification; + +/* Function prototypes */ + +/** + * Get the number of video drivers compiled into SDL. + * + * \returns a number >= 1 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetVideoDriver + */ +extern DECLSPEC int SDLCALL SDL_GetNumVideoDrivers(void); + +/** + * Get the name of a built in video driver. + * + * The video drivers are presented in the order in which they are normally + * checked during initialization. + * + * \param index the index of a video driver. + * \returns the name of the video driver with the given **index**. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumVideoDrivers + */ +extern DECLSPEC const char *SDLCALL SDL_GetVideoDriver(int index); + +/** + * Initialize the video subsystem, optionally specifying a video driver. + * + * This function initializes the video subsystem, setting up a connection to + * the window manager, etc, and determines the available display modes and + * pixel formats, but does not initialize a window or graphics mode. + * + * If you use this function and you haven't used the SDL_INIT_VIDEO flag with + * either SDL_Init() or SDL_InitSubSystem(), you should call SDL_VideoQuit() + * before calling SDL_Quit(). + * + * It is safe to call this function multiple times. SDL_VideoInit() will call + * SDL_VideoQuit() itself if the video subsystem has already been initialized. + * + * You can use SDL_GetNumVideoDrivers() and SDL_GetVideoDriver() to find a + * specific `driver_name`. + * + * \param driver_name the name of a video driver to initialize, or NULL for + * the default driver. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumVideoDrivers + * \sa SDL_GetVideoDriver + * \sa SDL_InitSubSystem + * \sa SDL_VideoQuit + */ +extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name); + +/** + * Shut down the video subsystem, if initialized with SDL_VideoInit(). + * + * This function closes all windows, and restores the original video mode. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_VideoInit + */ +extern DECLSPEC void SDLCALL SDL_VideoQuit(void); + +/** + * Get the name of the currently initialized video driver. + * + * \returns the name of the current video driver or NULL if no driver has been + * initialized. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumVideoDrivers + * \sa SDL_GetVideoDriver + */ +extern DECLSPEC const char *SDLCALL SDL_GetCurrentVideoDriver(void); + +/** + * Get the number of available video displays. + * + * \returns a number >= 1 or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetDisplayBounds + */ +extern DECLSPEC int SDLCALL SDL_GetNumVideoDisplays(void); + +/** + * Get the name of a display in UTF-8 encoding. + * + * \param displayIndex the index of display from which the name should be + * queried. + * \returns the name of a display or NULL for an invalid display index or + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC const char * SDLCALL SDL_GetDisplayName(int displayIndex); + +/** + * Get the desktop area represented by a display. + * + * The primary display (`displayIndex` zero) is always located at 0,0. + * + * \param displayIndex the index of the display to query. + * \param rect the SDL_Rect structure filled in with the display bounds. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC int SDLCALL SDL_GetDisplayBounds(int displayIndex, SDL_Rect * rect); + +/** + * Get the usable desktop area represented by a display. + * + * The primary display (`displayIndex` zero) is always located at 0,0. + * + * This is the same area as SDL_GetDisplayBounds() reports, but with portions + * reserved by the system removed. For example, on Apple's macOS, this + * subtracts the area occupied by the menu bar and dock. + * + * Setting a window to be fullscreen generally bypasses these unusable areas, + * so these are good guidelines for the maximum space available to a + * non-fullscreen window. + * + * The parameter `rect` is ignored if it is NULL. + * + * This function also returns -1 if the parameter `displayIndex` is out of + * range. + * + * \param displayIndex the index of the display to query the usable bounds + * from. + * \param rect the SDL_Rect structure filled in with the display bounds. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_GetDisplayBounds + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC int SDLCALL SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect * rect); + +/** + * Get the dots/pixels-per-inch for a display. + * + * Diagonal, horizontal and vertical DPI can all be optionally returned if the + * appropriate parameter is non-NULL. + * + * A failure of this function usually means that either no DPI information is + * available or the `displayIndex` is out of range. + * + * **WARNING**: This reports the DPI that the hardware reports, and it is not + * always reliable! It is almost always better to use SDL_GetWindowSize() to + * find the window size, which might be in logical points instead of pixels, + * and then SDL_GL_GetDrawableSize(), SDL_Vulkan_GetDrawableSize(), + * SDL_Metal_GetDrawableSize(), or SDL_GetRendererOutputSize(), and compare + * the two values to get an actual scaling value between the two. We will be + * rethinking how high-dpi details should be managed in SDL3 to make things + * more consistent, reliable, and clear. + * + * \param displayIndex the index of the display from which DPI information + * should be queried. + * \param ddpi a pointer filled in with the diagonal DPI of the display; may + * be NULL. + * \param hdpi a pointer filled in with the horizontal DPI of the display; may + * be NULL. + * \param vdpi a pointer filled in with the vertical DPI of the display; may + * be NULL. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC int SDLCALL SDL_GetDisplayDPI(int displayIndex, float * ddpi, float * hdpi, float * vdpi); + +/** + * Get the orientation of a display. + * + * \param displayIndex the index of the display to query. + * \returns The SDL_DisplayOrientation enum value of the display, or + * `SDL_ORIENTATION_UNKNOWN` if it isn't available. + * + * \since This function is available since SDL 2.0.9. + * + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC SDL_DisplayOrientation SDLCALL SDL_GetDisplayOrientation(int displayIndex); + +/** + * Get the number of available display modes. + * + * The `displayIndex` needs to be in the range from 0 to + * SDL_GetNumVideoDisplays() - 1. + * + * \param displayIndex the index of the display to query. + * \returns a number >= 1 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetDisplayMode + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC int SDLCALL SDL_GetNumDisplayModes(int displayIndex); + +/** + * Get information about a specific display mode. + * + * The display modes are sorted in this priority: + * + * - width -> largest to smallest + * - height -> largest to smallest + * - bits per pixel -> more colors to fewer colors + * - packed pixel layout -> largest to smallest + * - refresh rate -> highest to lowest + * + * \param displayIndex the index of the display to query. + * \param modeIndex the index of the display mode to query. + * \param mode an SDL_DisplayMode structure filled in with the mode at + * `modeIndex`. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetNumDisplayModes + */ +extern DECLSPEC int SDLCALL SDL_GetDisplayMode(int displayIndex, int modeIndex, + SDL_DisplayMode * mode); + +/** + * Get information about the desktop's display mode. + * + * There's a difference between this function and SDL_GetCurrentDisplayMode() + * when SDL runs fullscreen and has changed the resolution. In that case this + * function will return the previous native display mode, and not the current + * display mode. + * + * \param displayIndex the index of the display to query. + * \param mode an SDL_DisplayMode structure filled in with the current display + * mode. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetCurrentDisplayMode + * \sa SDL_GetDisplayMode + * \sa SDL_SetWindowDisplayMode + */ +extern DECLSPEC int SDLCALL SDL_GetDesktopDisplayMode(int displayIndex, SDL_DisplayMode * mode); + +/** + * Get information about the current display mode. + * + * There's a difference between this function and SDL_GetDesktopDisplayMode() + * when SDL runs fullscreen and has changed the resolution. In that case this + * function will return the current display mode, and not the previous native + * display mode. + * + * \param displayIndex the index of the display to query. + * \param mode an SDL_DisplayMode structure filled in with the current display + * mode. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetDesktopDisplayMode + * \sa SDL_GetDisplayMode + * \sa SDL_GetNumVideoDisplays + * \sa SDL_SetWindowDisplayMode + */ +extern DECLSPEC int SDLCALL SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode); + + +/** + * Get the closest match to the requested display mode. + * + * The available display modes are scanned and `closest` is filled in with the + * closest mode matching the requested mode and returned. The mode format and + * refresh rate default to the desktop mode if they are set to 0. The modes + * are scanned with size being first priority, format being second priority, + * and finally checking the refresh rate. If all the available modes are too + * small, then NULL is returned. + * + * \param displayIndex the index of the display to query. + * \param mode an SDL_DisplayMode structure containing the desired display + * mode. + * \param closest an SDL_DisplayMode structure filled in with the closest + * match of the available display modes. + * \returns the passed in value `closest` or NULL if no matching video mode + * was available; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetDisplayMode + * \sa SDL_GetNumDisplayModes + */ +extern DECLSPEC SDL_DisplayMode * SDLCALL SDL_GetClosestDisplayMode(int displayIndex, const SDL_DisplayMode * mode, SDL_DisplayMode * closest); + +/** + * Get the index of the display containing a point + * + * \param point the point to query. + * \returns the index of the display containing the point or a negative error + * code on failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GetDisplayBounds + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC int SDLCALL SDL_GetPointDisplayIndex(const SDL_Point * point); + +/** + * Get the index of the display primarily containing a rect + * + * \param rect the rect to query. + * \returns the index of the display entirely containing the rect or closest + * to the center of the rect on success or a negative error code on + * failure; call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.24.0. + * + * \sa SDL_GetDisplayBounds + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC int SDLCALL SDL_GetRectDisplayIndex(const SDL_Rect * rect); + +/** + * Get the index of the display associated with a window. + * + * \param window the window to query. + * \returns the index of the display containing the center of the window on + * success or a negative error code on failure; call SDL_GetError() + * for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetDisplayBounds + * \sa SDL_GetNumVideoDisplays + */ +extern DECLSPEC int SDLCALL SDL_GetWindowDisplayIndex(SDL_Window * window); + +/** + * Set the display mode to use when a window is visible at fullscreen. + * + * This only affects the display mode used when the window is fullscreen. To + * change the window size when the window is not fullscreen, use + * SDL_SetWindowSize(). + * + * \param window the window to affect. + * \param mode the SDL_DisplayMode structure representing the mode to use, or + * NULL to use the window's dimensions and the desktop's format + * and refresh rate. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowDisplayMode + * \sa SDL_SetWindowFullscreen + */ +extern DECLSPEC int SDLCALL SDL_SetWindowDisplayMode(SDL_Window * window, + const SDL_DisplayMode * mode); + +/** + * Query the display mode to use when a window is visible at fullscreen. + * + * \param window the window to query. + * \param mode an SDL_DisplayMode structure filled in with the fullscreen + * display mode. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetWindowDisplayMode + * \sa SDL_SetWindowFullscreen + */ +extern DECLSPEC int SDLCALL SDL_GetWindowDisplayMode(SDL_Window * window, + SDL_DisplayMode * mode); + +/** + * Get the raw ICC profile data for the screen the window is currently on. + * + * Data returned should be freed with SDL_free. + * + * \param window the window to query. + * \param size the size of the ICC profile. + * \returns the raw ICC profile data on success or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.18. + */ +extern DECLSPEC void* SDLCALL SDL_GetWindowICCProfile(SDL_Window * window, size_t* size); + +/** + * Get the pixel format associated with the window. + * + * \param window the window to query. + * \returns the pixel format of the window on success or + * SDL_PIXELFORMAT_UNKNOWN on failure; call SDL_GetError() for more + * information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetWindowPixelFormat(SDL_Window * window); + +/** + * Create a window with the specified position, dimensions, and flags. + * + * `flags` may be any of the following OR'd together: + * + * - `SDL_WINDOW_FULLSCREEN`: fullscreen window + * - `SDL_WINDOW_FULLSCREEN_DESKTOP`: fullscreen window at desktop resolution + * - `SDL_WINDOW_OPENGL`: window usable with an OpenGL context + * - `SDL_WINDOW_VULKAN`: window usable with a Vulkan instance + * - `SDL_WINDOW_METAL`: window usable with a Metal instance + * - `SDL_WINDOW_HIDDEN`: window is not visible + * - `SDL_WINDOW_BORDERLESS`: no window decoration + * - `SDL_WINDOW_RESIZABLE`: window can be resized + * - `SDL_WINDOW_MINIMIZED`: window is minimized + * - `SDL_WINDOW_MAXIMIZED`: window is maximized + * - `SDL_WINDOW_INPUT_GRABBED`: window has grabbed input focus + * - `SDL_WINDOW_ALLOW_HIGHDPI`: window should be created in high-DPI mode if + * supported (>= SDL 2.0.1) + * + * `SDL_WINDOW_SHOWN` is ignored by SDL_CreateWindow(). The SDL_Window is + * implicitly shown if SDL_WINDOW_HIDDEN is not set. `SDL_WINDOW_SHOWN` may be + * queried later using SDL_GetWindowFlags(). + * + * On Apple's macOS, you **must** set the NSHighResolutionCapable Info.plist + * property to YES, otherwise you will not receive a High-DPI OpenGL canvas. + * + * If the window is created with the `SDL_WINDOW_ALLOW_HIGHDPI` flag, its size + * in pixels may differ from its size in screen coordinates on platforms with + * high-DPI support (e.g. iOS and macOS). Use SDL_GetWindowSize() to query the + * client area's size in screen coordinates, and SDL_GL_GetDrawableSize() or + * SDL_GetRendererOutputSize() to query the drawable size in pixels. Note that + * when this flag is set, the drawable size can vary after the window is + * created and should be queried after major window events such as when the + * window is resized or moved between displays. + * + * If the window is set fullscreen, the width and height parameters `w` and + * `h` will not be used. However, invalid size parameters (e.g. too large) may + * still fail. Window size is actually limited to 16384 x 16384 for all + * platforms at window creation. + * + * If the window is created with any of the SDL_WINDOW_OPENGL or + * SDL_WINDOW_VULKAN flags, then the corresponding LoadLibrary function + * (SDL_GL_LoadLibrary or SDL_Vulkan_LoadLibrary) is called and the + * corresponding UnloadLibrary function is called by SDL_DestroyWindow(). + * + * If SDL_WINDOW_VULKAN is specified and there isn't a working Vulkan driver, + * SDL_CreateWindow() will fail because SDL_Vulkan_LoadLibrary() will fail. + * + * If SDL_WINDOW_METAL is specified on an OS that does not support Metal, + * SDL_CreateWindow() will fail. + * + * On non-Apple devices, SDL requires you to either not link to the Vulkan + * loader or link to a dynamic library version. This limitation may be removed + * in a future version of SDL. + * + * \param title the title of the window, in UTF-8 encoding. + * \param x the x position of the window, `SDL_WINDOWPOS_CENTERED`, or + * `SDL_WINDOWPOS_UNDEFINED`. + * \param y the y position of the window, `SDL_WINDOWPOS_CENTERED`, or + * `SDL_WINDOWPOS_UNDEFINED`. + * \param w the width of the window, in screen coordinates. + * \param h the height of the window, in screen coordinates. + * \param flags 0, or one or more SDL_WindowFlags OR'd together. + * \returns the `SDL_Window` that was created or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateWindowFrom + * \sa SDL_DestroyWindow + */ +extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindow(const char *title, + int x, int y, int w, + int h, Uint32 flags); + +/** + * Create an SDL window from an existing native window. + * + * In some cases (e.g. OpenGL) and on some platforms (e.g. Microsoft Windows) + * the hint `SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT` needs to be configured + * before using SDL_CreateWindowFrom(). + * + * \param data a pointer to driver-dependent window creation data, typically + * your native window cast to a void*. + * \returns the window that was created or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateWindow + * \sa SDL_DestroyWindow + */ +extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindowFrom(const void *data); + +/** + * Get the numeric ID of a window. + * + * The numeric ID is what SDL_WindowEvent references, and is necessary to map + * these events to specific SDL_Window objects. + * + * \param window the window to query. + * \returns the ID of the window on success or 0 on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowFromID + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetWindowID(SDL_Window * window); + +/** + * Get a window from a stored ID. + * + * The numeric ID is what SDL_WindowEvent references, and is necessary to map + * these events to specific SDL_Window objects. + * + * \param id the ID of the window. + * \returns the window associated with `id` or NULL if it doesn't exist; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowID + */ +extern DECLSPEC SDL_Window * SDLCALL SDL_GetWindowFromID(Uint32 id); + +/** + * Get the window flags. + * + * \param window the window to query. + * \returns a mask of the SDL_WindowFlags associated with `window`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateWindow + * \sa SDL_HideWindow + * \sa SDL_MaximizeWindow + * \sa SDL_MinimizeWindow + * \sa SDL_SetWindowFullscreen + * \sa SDL_SetWindowGrab + * \sa SDL_ShowWindow + */ +extern DECLSPEC Uint32 SDLCALL SDL_GetWindowFlags(SDL_Window * window); + +/** + * Set the title of a window. + * + * This string is expected to be in UTF-8 encoding. + * + * \param window the window to change. + * \param title the desired window title in UTF-8 format. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowTitle + */ +extern DECLSPEC void SDLCALL SDL_SetWindowTitle(SDL_Window * window, + const char *title); + +/** + * Get the title of a window. + * + * \param window the window to query. + * \returns the title of the window in UTF-8 format or "" if there is no + * title. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetWindowTitle + */ +extern DECLSPEC const char *SDLCALL SDL_GetWindowTitle(SDL_Window * window); + +/** + * Set the icon for a window. + * + * \param window the window to change. + * \param icon an SDL_Surface structure containing the icon for the window. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC void SDLCALL SDL_SetWindowIcon(SDL_Window * window, + SDL_Surface * icon); + +/** + * Associate an arbitrary named pointer with a window. + * + * `name` is case-sensitive. + * + * \param window the window to associate with the pointer. + * \param name the name of the pointer. + * \param userdata the associated pointer. + * \returns the previous value associated with `name`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowData + */ +extern DECLSPEC void* SDLCALL SDL_SetWindowData(SDL_Window * window, + const char *name, + void *userdata); + +/** + * Retrieve the data pointer associated with a window. + * + * \param window the window to query. + * \param name the name of the pointer. + * \returns the value associated with `name`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetWindowData + */ +extern DECLSPEC void *SDLCALL SDL_GetWindowData(SDL_Window * window, + const char *name); + +/** + * Set the position of a window. + * + * The window coordinate origin is the upper left of the display. + * + * \param window the window to reposition. + * \param x the x coordinate of the window in screen coordinates, or + * `SDL_WINDOWPOS_CENTERED` or `SDL_WINDOWPOS_UNDEFINED`. + * \param y the y coordinate of the window in screen coordinates, or + * `SDL_WINDOWPOS_CENTERED` or `SDL_WINDOWPOS_UNDEFINED`. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowPosition + */ +extern DECLSPEC void SDLCALL SDL_SetWindowPosition(SDL_Window * window, + int x, int y); + +/** + * Get the position of a window. + * + * If you do not need the value for one of the positions a NULL may be passed + * in the `x` or `y` parameter. + * + * \param window the window to query. + * \param x a pointer filled in with the x position of the window, in screen + * coordinates, may be NULL. + * \param y a pointer filled in with the y position of the window, in screen + * coordinates, may be NULL. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetWindowPosition + */ +extern DECLSPEC void SDLCALL SDL_GetWindowPosition(SDL_Window * window, + int *x, int *y); + +/** + * Set the size of a window's client area. + * + * The window size in screen coordinates may differ from the size in pixels, + * if the window was created with `SDL_WINDOW_ALLOW_HIGHDPI` on a platform + * with high-dpi support (e.g. iOS or macOS). Use SDL_GL_GetDrawableSize() or + * SDL_GetRendererOutputSize() to get the real client area size in pixels. + * + * Fullscreen windows automatically match the size of the display mode, and + * you should use SDL_SetWindowDisplayMode() to change their size. + * + * \param window the window to change. + * \param w the width of the window in pixels, in screen coordinates, must be + * > 0. + * \param h the height of the window in pixels, in screen coordinates, must be + * > 0. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowSize + * \sa SDL_SetWindowDisplayMode + */ +extern DECLSPEC void SDLCALL SDL_SetWindowSize(SDL_Window * window, int w, + int h); + +/** + * Get the size of a window's client area. + * + * NULL can safely be passed as the `w` or `h` parameter if the width or + * height value is not desired. + * + * The window size in screen coordinates may differ from the size in pixels, + * if the window was created with `SDL_WINDOW_ALLOW_HIGHDPI` on a platform + * with high-dpi support (e.g. iOS or macOS). Use SDL_GL_GetDrawableSize(), + * SDL_Vulkan_GetDrawableSize(), or SDL_GetRendererOutputSize() to get the + * real client area size in pixels. + * + * \param window the window to query the width and height from. + * \param w a pointer filled in with the width of the window, in screen + * coordinates, may be NULL. + * \param h a pointer filled in with the height of the window, in screen + * coordinates, may be NULL. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_GetDrawableSize + * \sa SDL_Vulkan_GetDrawableSize + * \sa SDL_SetWindowSize + */ +extern DECLSPEC void SDLCALL SDL_GetWindowSize(SDL_Window * window, int *w, + int *h); + +/** + * Get the size of a window's borders (decorations) around the client area. + * + * Note: If this function fails (returns -1), the size values will be + * initialized to 0, 0, 0, 0 (if a non-NULL pointer is provided), as if the + * window in question was borderless. + * + * Note: This function may fail on systems where the window has not yet been + * decorated by the display server (for example, immediately after calling + * SDL_CreateWindow). It is recommended that you wait at least until the + * window has been presented and composited, so that the window system has a + * chance to decorate the window and provide the border dimensions to SDL. + * + * This function also returns -1 if getting the information is not supported. + * + * \param window the window to query the size values of the border + * (decorations) from. + * \param top pointer to variable for storing the size of the top border; NULL + * is permitted. + * \param left pointer to variable for storing the size of the left border; + * NULL is permitted. + * \param bottom pointer to variable for storing the size of the bottom + * border; NULL is permitted. + * \param right pointer to variable for storing the size of the right border; + * NULL is permitted. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_GetWindowSize + */ +extern DECLSPEC int SDLCALL SDL_GetWindowBordersSize(SDL_Window * window, + int *top, int *left, + int *bottom, int *right); + +/** + * Get the size of a window in pixels. + * + * This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI + * drawable, i.e. the window was created with `SDL_WINDOW_ALLOW_HIGHDPI` on a + * platform with high-DPI support (Apple calls this "Retina"), and not + * disabled by the `SDL_HINT_VIDEO_HIGHDPI_DISABLED` hint. + * + * \param window the window from which the drawable size should be queried. + * \param w a pointer to variable for storing the width in pixels, may be + * NULL. + * \param h a pointer to variable for storing the height in pixels, may be + * NULL. + * + * \since This function is available since SDL 2.26.0. + * + * \sa SDL_CreateWindow + * \sa SDL_GetWindowSize + */ +extern DECLSPEC void SDLCALL SDL_GetWindowSizeInPixels(SDL_Window * window, + int *w, int *h); + +/** + * Set the minimum size of a window's client area. + * + * \param window the window to change. + * \param min_w the minimum width of the window in pixels. + * \param min_h the minimum height of the window in pixels. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowMinimumSize + * \sa SDL_SetWindowMaximumSize + */ +extern DECLSPEC void SDLCALL SDL_SetWindowMinimumSize(SDL_Window * window, + int min_w, int min_h); + +/** + * Get the minimum size of a window's client area. + * + * \param window the window to query. + * \param w a pointer filled in with the minimum width of the window, may be + * NULL. + * \param h a pointer filled in with the minimum height of the window, may be + * NULL. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowMaximumSize + * \sa SDL_SetWindowMinimumSize + */ +extern DECLSPEC void SDLCALL SDL_GetWindowMinimumSize(SDL_Window * window, + int *w, int *h); + +/** + * Set the maximum size of a window's client area. + * + * \param window the window to change. + * \param max_w the maximum width of the window in pixels. + * \param max_h the maximum height of the window in pixels. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowMaximumSize + * \sa SDL_SetWindowMinimumSize + */ +extern DECLSPEC void SDLCALL SDL_SetWindowMaximumSize(SDL_Window * window, + int max_w, int max_h); + +/** + * Get the maximum size of a window's client area. + * + * \param window the window to query. + * \param w a pointer filled in with the maximum width of the window, may be + * NULL. + * \param h a pointer filled in with the maximum height of the window, may be + * NULL. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowMinimumSize + * \sa SDL_SetWindowMaximumSize + */ +extern DECLSPEC void SDLCALL SDL_GetWindowMaximumSize(SDL_Window * window, + int *w, int *h); + +/** + * Set the border state of a window. + * + * This will add or remove the window's `SDL_WINDOW_BORDERLESS` flag and add + * or remove the border from the actual window. This is a no-op if the + * window's border already matches the requested state. + * + * You can't change the border state of a fullscreen window. + * + * \param window the window of which to change the border state. + * \param bordered SDL_FALSE to remove border, SDL_TRUE to add border. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowFlags + */ +extern DECLSPEC void SDLCALL SDL_SetWindowBordered(SDL_Window * window, + SDL_bool bordered); + +/** + * Set the user-resizable state of a window. + * + * This will add or remove the window's `SDL_WINDOW_RESIZABLE` flag and + * allow/disallow user resizing of the window. This is a no-op if the window's + * resizable state already matches the requested state. + * + * You can't change the resizable state of a fullscreen window. + * + * \param window the window of which to change the resizable state. + * \param resizable SDL_TRUE to allow resizing, SDL_FALSE to disallow. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_GetWindowFlags + */ +extern DECLSPEC void SDLCALL SDL_SetWindowResizable(SDL_Window * window, + SDL_bool resizable); + +/** + * Set the window to always be above the others. + * + * This will add or remove the window's `SDL_WINDOW_ALWAYS_ON_TOP` flag. This + * will bring the window to the front and keep the window above the rest. + * + * \param window The window of which to change the always on top state. + * \param on_top SDL_TRUE to set the window always on top, SDL_FALSE to + * disable. + * + * \since This function is available since SDL 2.0.16. + * + * \sa SDL_GetWindowFlags + */ +extern DECLSPEC void SDLCALL SDL_SetWindowAlwaysOnTop(SDL_Window * window, + SDL_bool on_top); + +/** + * Show a window. + * + * \param window the window to show. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_HideWindow + * \sa SDL_RaiseWindow + */ +extern DECLSPEC void SDLCALL SDL_ShowWindow(SDL_Window * window); + +/** + * Hide a window. + * + * \param window the window to hide. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_ShowWindow + */ +extern DECLSPEC void SDLCALL SDL_HideWindow(SDL_Window * window); + +/** + * Raise a window above other windows and set the input focus. + * + * \param window the window to raise. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC void SDLCALL SDL_RaiseWindow(SDL_Window * window); + +/** + * Make a window as large as possible. + * + * \param window the window to maximize. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_MinimizeWindow + * \sa SDL_RestoreWindow + */ +extern DECLSPEC void SDLCALL SDL_MaximizeWindow(SDL_Window * window); + +/** + * Minimize a window to an iconic representation. + * + * \param window the window to minimize. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_MaximizeWindow + * \sa SDL_RestoreWindow + */ +extern DECLSPEC void SDLCALL SDL_MinimizeWindow(SDL_Window * window); + +/** + * Restore the size and position of a minimized or maximized window. + * + * \param window the window to restore. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_MaximizeWindow + * \sa SDL_MinimizeWindow + */ +extern DECLSPEC void SDLCALL SDL_RestoreWindow(SDL_Window * window); + +/** + * Set a window's fullscreen state. + * + * `flags` may be `SDL_WINDOW_FULLSCREEN`, for "real" fullscreen with a + * videomode change; `SDL_WINDOW_FULLSCREEN_DESKTOP` for "fake" fullscreen + * that takes the size of the desktop; and 0 for windowed mode. + * + * Note that for some renderers, this function may trigger an + * SDL_RENDER_TARGETS_RESET event. Your application should be prepared to + * handle this event by reuploading textures! + * + * \param window the window to change. + * \param flags `SDL_WINDOW_FULLSCREEN`, `SDL_WINDOW_FULLSCREEN_DESKTOP` or 0. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowDisplayMode + * \sa SDL_SetWindowDisplayMode + */ +extern DECLSPEC int SDLCALL SDL_SetWindowFullscreen(SDL_Window * window, + Uint32 flags); + +/** + * Return whether the window has a surface associated with it. + * + * \returns SDL_TRUE if there is a surface associated with the window, or + * SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.28.0. + * + * \sa SDL_GetWindowSurface + */ +extern DECLSPEC SDL_bool SDLCALL SDL_HasWindowSurface(SDL_Window *window); + +/** + * Get the SDL surface associated with the window. + * + * A new surface will be created with the optimal format for the window, if + * necessary. This surface will be freed when the window is destroyed. Do not + * free this surface. + * + * This surface will be invalidated if the window is resized. After resizing a + * window this function must be called again to return a valid surface. + * + * Note that on some platforms the pixels pointer of the surface may be + * modified after each call to SDL_UpdateWindowSurface(), so that the platform + * code can implement efficient double or triple buffering. + * + * You may not combine this with 3D or the rendering API on this window. + * + * This function is affected by `SDL_HINT_FRAMEBUFFER_ACCELERATION`. + * + * \param window the window to query. + * \returns the surface associated with the window, or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_DestroyWindowSurface + * \sa SDL_HasWindowSurface + * \sa SDL_UpdateWindowSurface + * \sa SDL_UpdateWindowSurfaceRects + */ +extern DECLSPEC SDL_Surface * SDLCALL SDL_GetWindowSurface(SDL_Window * window); + +/** + * Copy the window surface to the screen. + * + * This is the function you use to reflect any changes to the surface on the + * screen. + * + * This function is equivalent to the SDL 1.2 API SDL_Flip(). + * + * \param window the window to update. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowSurface + * \sa SDL_UpdateWindowSurfaceRects + */ +extern DECLSPEC int SDLCALL SDL_UpdateWindowSurface(SDL_Window * window); + +/** + * Copy areas of the window surface to the screen. + * + * This is the function you use to reflect changes to portions of the surface + * on the screen. + * + * This function is equivalent to the SDL 1.2 API SDL_UpdateRects(). + * + * Note that this function will update _at least_ the rectangles specified, + * but this is only intended as an optimization; in practice, this might + * update more of the screen (or all of the screen!), depending on what method + * SDL uses to send pixels to the system. + * + * \param window the window to update. + * \param rects an array of SDL_Rect structures representing areas of the + * surface to copy, in pixels. + * \param numrects the number of rectangles. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowSurface + * \sa SDL_UpdateWindowSurface + */ +extern DECLSPEC int SDLCALL SDL_UpdateWindowSurfaceRects(SDL_Window * window, + const SDL_Rect * rects, + int numrects); + +/** + * Destroy the surface associated with the window. + * + * \param window the window to update. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.28.0. + * + * \sa SDL_GetWindowSurface + * \sa SDL_HasWindowSurface + */ +extern DECLSPEC int SDLCALL SDL_DestroyWindowSurface(SDL_Window *window); + +/** + * Set a window's input grab mode. + * + * When input is grabbed, the mouse is confined to the window. This function + * will also grab the keyboard if `SDL_HINT_GRAB_KEYBOARD` is set. To grab the + * keyboard without also grabbing the mouse, use SDL_SetWindowKeyboardGrab(). + * + * If the caller enables a grab while another window is currently grabbed, the + * other window loses its grab in favor of the caller's window. + * + * \param window the window for which the input grab mode should be set. + * \param grabbed SDL_TRUE to grab input or SDL_FALSE to release input. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetGrabbedWindow + * \sa SDL_GetWindowGrab + */ +extern DECLSPEC void SDLCALL SDL_SetWindowGrab(SDL_Window * window, + SDL_bool grabbed); + +/** + * Set a window's keyboard grab mode. + * + * Keyboard grab enables capture of system keyboard shortcuts like Alt+Tab or + * the Meta/Super key. Note that not all system keyboard shortcuts can be + * captured by applications (one example is Ctrl+Alt+Del on Windows). + * + * This is primarily intended for specialized applications such as VNC clients + * or VM frontends. Normal games should not use keyboard grab. + * + * When keyboard grab is enabled, SDL will continue to handle Alt+Tab when the + * window is full-screen to ensure the user is not trapped in your + * application. If you have a custom keyboard shortcut to exit fullscreen + * mode, you may suppress this behavior with + * `SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED`. + * + * If the caller enables a grab while another window is currently grabbed, the + * other window loses its grab in favor of the caller's window. + * + * \param window The window for which the keyboard grab mode should be set. + * \param grabbed This is SDL_TRUE to grab keyboard, and SDL_FALSE to release. + * + * \since This function is available since SDL 2.0.16. + * + * \sa SDL_GetWindowKeyboardGrab + * \sa SDL_SetWindowMouseGrab + * \sa SDL_SetWindowGrab + */ +extern DECLSPEC void SDLCALL SDL_SetWindowKeyboardGrab(SDL_Window * window, + SDL_bool grabbed); + +/** + * Set a window's mouse grab mode. + * + * Mouse grab confines the mouse cursor to the window. + * + * \param window The window for which the mouse grab mode should be set. + * \param grabbed This is SDL_TRUE to grab mouse, and SDL_FALSE to release. + * + * \since This function is available since SDL 2.0.16. + * + * \sa SDL_GetWindowMouseGrab + * \sa SDL_SetWindowKeyboardGrab + * \sa SDL_SetWindowGrab + */ +extern DECLSPEC void SDLCALL SDL_SetWindowMouseGrab(SDL_Window * window, + SDL_bool grabbed); + +/** + * Get a window's input grab mode. + * + * \param window the window to query. + * \returns SDL_TRUE if input is grabbed, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetWindowGrab + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowGrab(SDL_Window * window); + +/** + * Get a window's keyboard grab mode. + * + * \param window the window to query. + * \returns SDL_TRUE if keyboard is grabbed, and SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.16. + * + * \sa SDL_SetWindowKeyboardGrab + * \sa SDL_GetWindowGrab + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowKeyboardGrab(SDL_Window * window); + +/** + * Get a window's mouse grab mode. + * + * \param window the window to query. + * \returns SDL_TRUE if mouse is grabbed, and SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.16. + * + * \sa SDL_SetWindowKeyboardGrab + * \sa SDL_GetWindowGrab + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowMouseGrab(SDL_Window * window); + +/** + * Get the window that currently has an input grab enabled. + * + * \returns the window if input is grabbed or NULL otherwise. + * + * \since This function is available since SDL 2.0.4. + * + * \sa SDL_GetWindowGrab + * \sa SDL_SetWindowGrab + */ +extern DECLSPEC SDL_Window * SDLCALL SDL_GetGrabbedWindow(void); + +/** + * Confines the cursor to the specified area of a window. + * + * Note that this does NOT grab the cursor, it only defines the area a cursor + * is restricted to when the window has mouse focus. + * + * \param window The window that will be associated with the barrier. + * \param rect A rectangle area in window-relative coordinates. If NULL the + * barrier for the specified window will be destroyed. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_GetWindowMouseRect + * \sa SDL_SetWindowMouseGrab + */ +extern DECLSPEC int SDLCALL SDL_SetWindowMouseRect(SDL_Window * window, const SDL_Rect * rect); + +/** + * Get the mouse confinement rectangle of a window. + * + * \param window The window to query. + * \returns A pointer to the mouse confinement rectangle of a window, or NULL + * if there isn't one. + * + * \since This function is available since SDL 2.0.18. + * + * \sa SDL_SetWindowMouseRect + */ +extern DECLSPEC const SDL_Rect * SDLCALL SDL_GetWindowMouseRect(SDL_Window * window); + +/** + * Set the brightness (gamma multiplier) for a given window's display. + * + * Despite the name and signature, this method sets the brightness of the + * entire display, not an individual window. A window is considered to be + * owned by the display that contains the window's center pixel. (The index of + * this display can be retrieved using SDL_GetWindowDisplayIndex().) The + * brightness set will not follow the window if it is moved to another + * display. + * + * Many platforms will refuse to set the display brightness in modern times. + * You are better off using a shader to adjust gamma during rendering, or + * something similar. + * + * \param window the window used to select the display whose brightness will + * be changed. + * \param brightness the brightness (gamma multiplier) value to set where 0.0 + * is completely dark and 1.0 is normal brightness. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowBrightness + * \sa SDL_SetWindowGammaRamp + */ +extern DECLSPEC int SDLCALL SDL_SetWindowBrightness(SDL_Window * window, float brightness); + +/** + * Get the brightness (gamma multiplier) for a given window's display. + * + * Despite the name and signature, this method retrieves the brightness of the + * entire display, not an individual window. A window is considered to be + * owned by the display that contains the window's center pixel. (The index of + * this display can be retrieved using SDL_GetWindowDisplayIndex().) + * + * \param window the window used to select the display whose brightness will + * be queried. + * \returns the brightness for the display where 0.0 is completely dark and + * 1.0 is normal brightness. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetWindowBrightness + */ +extern DECLSPEC float SDLCALL SDL_GetWindowBrightness(SDL_Window * window); + +/** + * Set the opacity for a window. + * + * The parameter `opacity` will be clamped internally between 0.0f + * (transparent) and 1.0f (opaque). + * + * This function also returns -1 if setting the opacity isn't supported. + * + * \param window the window which will be made transparent or opaque. + * \param opacity the opacity value (0.0f - transparent, 1.0f - opaque). + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_GetWindowOpacity + */ +extern DECLSPEC int SDLCALL SDL_SetWindowOpacity(SDL_Window * window, float opacity); + +/** + * Get the opacity of a window. + * + * If transparency isn't supported on this platform, opacity will be reported + * as 1.0f without error. + * + * The parameter `opacity` is ignored if it is NULL. + * + * This function also returns -1 if an invalid window was provided. + * + * \param window the window to get the current opacity value from. + * \param out_opacity the float filled in (0.0f - transparent, 1.0f - opaque). + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_SetWindowOpacity + */ +extern DECLSPEC int SDLCALL SDL_GetWindowOpacity(SDL_Window * window, float * out_opacity); + +/** + * Set the window as a modal for another window. + * + * \param modal_window the window that should be set modal. + * \param parent_window the parent window for the modal window. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + */ +extern DECLSPEC int SDLCALL SDL_SetWindowModalFor(SDL_Window * modal_window, SDL_Window * parent_window); + +/** + * Explicitly set input focus to the window. + * + * You almost certainly want SDL_RaiseWindow() instead of this function. Use + * this with caution, as you might give focus to a window that is completely + * obscured by other windows. + * + * \param window the window that should get the input focus. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.5. + * + * \sa SDL_RaiseWindow + */ +extern DECLSPEC int SDLCALL SDL_SetWindowInputFocus(SDL_Window * window); + +/** + * Set the gamma ramp for the display that owns a given window. + * + * Set the gamma translation table for the red, green, and blue channels of + * the video hardware. Each table is an array of 256 16-bit quantities, + * representing a mapping between the input and output for that channel. The + * input is the index into the array, and the output is the 16-bit gamma value + * at that index, scaled to the output color precision. + * + * Despite the name and signature, this method sets the gamma ramp of the + * entire display, not an individual window. A window is considered to be + * owned by the display that contains the window's center pixel. (The index of + * this display can be retrieved using SDL_GetWindowDisplayIndex().) The gamma + * ramp set will not follow the window if it is moved to another display. + * + * \param window the window used to select the display whose gamma ramp will + * be changed. + * \param red a 256 element array of 16-bit quantities representing the + * translation table for the red channel, or NULL. + * \param green a 256 element array of 16-bit quantities representing the + * translation table for the green channel, or NULL. + * \param blue a 256 element array of 16-bit quantities representing the + * translation table for the blue channel, or NULL. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GetWindowGammaRamp + */ +extern DECLSPEC int SDLCALL SDL_SetWindowGammaRamp(SDL_Window * window, + const Uint16 * red, + const Uint16 * green, + const Uint16 * blue); + +/** + * Get the gamma ramp for a given window's display. + * + * Despite the name and signature, this method retrieves the gamma ramp of the + * entire display, not an individual window. A window is considered to be + * owned by the display that contains the window's center pixel. (The index of + * this display can be retrieved using SDL_GetWindowDisplayIndex().) + * + * \param window the window used to select the display whose gamma ramp will + * be queried. + * \param red a 256 element array of 16-bit quantities filled in with the + * translation table for the red channel, or NULL. + * \param green a 256 element array of 16-bit quantities filled in with the + * translation table for the green channel, or NULL. + * \param blue a 256 element array of 16-bit quantities filled in with the + * translation table for the blue channel, or NULL. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_SetWindowGammaRamp + */ +extern DECLSPEC int SDLCALL SDL_GetWindowGammaRamp(SDL_Window * window, + Uint16 * red, + Uint16 * green, + Uint16 * blue); + +/** + * Possible return values from the SDL_HitTest callback. + * + * \sa SDL_HitTest + */ +typedef enum SDL_HitTestResult +{ + SDL_HITTEST_NORMAL, /**< Region is normal. No special properties. */ + SDL_HITTEST_DRAGGABLE, /**< Region can drag entire window. */ + SDL_HITTEST_RESIZE_TOPLEFT, + SDL_HITTEST_RESIZE_TOP, + SDL_HITTEST_RESIZE_TOPRIGHT, + SDL_HITTEST_RESIZE_RIGHT, + SDL_HITTEST_RESIZE_BOTTOMRIGHT, + SDL_HITTEST_RESIZE_BOTTOM, + SDL_HITTEST_RESIZE_BOTTOMLEFT, + SDL_HITTEST_RESIZE_LEFT +} SDL_HitTestResult; + +/** + * Callback used for hit-testing. + * + * \param win the SDL_Window where hit-testing was set on. + * \param area an SDL_Point which should be hit-tested. + * \param data what was passed as `callback_data` to SDL_SetWindowHitTest(). + * \return an SDL_HitTestResult value. + * + * \sa SDL_SetWindowHitTest + */ +typedef SDL_HitTestResult (SDLCALL *SDL_HitTest)(SDL_Window *win, + const SDL_Point *area, + void *data); + +/** + * Provide a callback that decides if a window region has special properties. + * + * Normally windows are dragged and resized by decorations provided by the + * system window manager (a title bar, borders, etc), but for some apps, it + * makes sense to drag them from somewhere else inside the window itself; for + * example, one might have a borderless window that wants to be draggable from + * any part, or simulate its own title bar, etc. + * + * This function lets the app provide a callback that designates pieces of a + * given window as special. This callback is run during event processing if we + * need to tell the OS to treat a region of the window specially; the use of + * this callback is known as "hit testing." + * + * Mouse input may not be delivered to your application if it is within a + * special area; the OS will often apply that input to moving the window or + * resizing the window and not deliver it to the application. + * + * Specifying NULL for a callback disables hit-testing. Hit-testing is + * disabled by default. + * + * Platforms that don't support this functionality will return -1 + * unconditionally, even if you're attempting to disable hit-testing. + * + * Your callback may fire at any time, and its firing does not indicate any + * specific behavior (for example, on Windows, this certainly might fire when + * the OS is deciding whether to drag your window, but it fires for lots of + * other reasons, too, some unrelated to anything you probably care about _and + * when the mouse isn't actually at the location it is testing_). Since this + * can fire at any time, you should try to keep your callback efficient, + * devoid of allocations, etc. + * + * \param window the window to set hit-testing on. + * \param callback the function to call when doing a hit-test. + * \param callback_data an app-defined void pointer passed to **callback**. + * \returns 0 on success or -1 on error (including unsupported); call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.4. + */ +extern DECLSPEC int SDLCALL SDL_SetWindowHitTest(SDL_Window * window, + SDL_HitTest callback, + void *callback_data); + +/** + * Request a window to demand attention from the user. + * + * \param window the window to be flashed. + * \param operation the flash operation. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.16. + */ +extern DECLSPEC int SDLCALL SDL_FlashWindow(SDL_Window * window, SDL_FlashOperation operation); + +/** + * Destroy a window. + * + * If `window` is NULL, this function will return immediately after setting + * the SDL error message to "Invalid window". See SDL_GetError(). + * + * \param window the window to destroy. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_CreateWindow + * \sa SDL_CreateWindowFrom + */ +extern DECLSPEC void SDLCALL SDL_DestroyWindow(SDL_Window * window); + + +/** + * Check whether the screensaver is currently enabled. + * + * The screensaver is disabled by default since SDL 2.0.2. Before SDL 2.0.2 + * the screensaver was enabled by default. + * + * The default can also be changed using `SDL_HINT_VIDEO_ALLOW_SCREENSAVER`. + * + * \returns SDL_TRUE if the screensaver is enabled, SDL_FALSE if it is + * disabled. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_DisableScreenSaver + * \sa SDL_EnableScreenSaver + */ +extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenSaverEnabled(void); + +/** + * Allow the screen to be blanked by a screen saver. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_DisableScreenSaver + * \sa SDL_IsScreenSaverEnabled + */ +extern DECLSPEC void SDLCALL SDL_EnableScreenSaver(void); + +/** + * Prevent the screen from being blanked by a screen saver. + * + * If you disable the screensaver, it is automatically re-enabled when SDL + * quits. + * + * The screensaver is disabled by default since SDL 2.0.2. Before SDL 2.0.2 + * the screensaver was enabled by default. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_EnableScreenSaver + * \sa SDL_IsScreenSaverEnabled + */ +extern DECLSPEC void SDLCALL SDL_DisableScreenSaver(void); + + +/** + * \name OpenGL support functions + */ +/* @{ */ + +/** + * Dynamically load an OpenGL library. + * + * This should be done after initializing the video driver, but before + * creating any OpenGL windows. If no OpenGL library is loaded, the default + * library will be loaded upon creation of the first OpenGL window. + * + * If you do this, you need to retrieve all of the GL functions used in your + * program from the dynamic library using SDL_GL_GetProcAddress(). + * + * \param path the platform dependent OpenGL library name, or NULL to open the + * default OpenGL library. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_GetProcAddress + * \sa SDL_GL_UnloadLibrary + */ +extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path); + +/** + * Get an OpenGL function by name. + * + * If the GL library is loaded at runtime with SDL_GL_LoadLibrary(), then all + * GL functions must be retrieved this way. Usually this is used to retrieve + * function pointers to OpenGL extensions. + * + * There are some quirks to looking up OpenGL functions that require some + * extra care from the application. If you code carefully, you can handle + * these quirks without any platform-specific code, though: + * + * - On Windows, function pointers are specific to the current GL context; + * this means you need to have created a GL context and made it current + * before calling SDL_GL_GetProcAddress(). If you recreate your context or + * create a second context, you should assume that any existing function + * pointers aren't valid to use with it. This is (currently) a + * Windows-specific limitation, and in practice lots of drivers don't suffer + * this limitation, but it is still the way the wgl API is documented to + * work and you should expect crashes if you don't respect it. Store a copy + * of the function pointers that comes and goes with context lifespan. + * - On X11, function pointers returned by this function are valid for any + * context, and can even be looked up before a context is created at all. + * This means that, for at least some common OpenGL implementations, if you + * look up a function that doesn't exist, you'll get a non-NULL result that + * is _NOT_ safe to call. You must always make sure the function is actually + * available for a given GL context before calling it, by checking for the + * existence of the appropriate extension with SDL_GL_ExtensionSupported(), + * or verifying that the version of OpenGL you're using offers the function + * as core functionality. + * - Some OpenGL drivers, on all platforms, *will* return NULL if a function + * isn't supported, but you can't count on this behavior. Check for + * extensions you use, and if you get a NULL anyway, act as if that + * extension wasn't available. This is probably a bug in the driver, but you + * can code defensively for this scenario anyhow. + * - Just because you're on Linux/Unix, don't assume you'll be using X11. + * Next-gen display servers are waiting to replace it, and may or may not + * make the same promises about function pointers. + * - OpenGL function pointers must be declared `APIENTRY` as in the example + * code. This will ensure the proper calling convention is followed on + * platforms where this matters (Win32) thereby avoiding stack corruption. + * + * \param proc the name of an OpenGL function. + * \returns a pointer to the named OpenGL function. The returned pointer + * should be cast to the appropriate function signature. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_ExtensionSupported + * \sa SDL_GL_LoadLibrary + * \sa SDL_GL_UnloadLibrary + */ +extern DECLSPEC void *SDLCALL SDL_GL_GetProcAddress(const char *proc); + +/** + * Unload the OpenGL library previously loaded by SDL_GL_LoadLibrary(). + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_LoadLibrary + */ +extern DECLSPEC void SDLCALL SDL_GL_UnloadLibrary(void); + +/** + * Check if an OpenGL extension is supported for the current context. + * + * This function operates on the current GL context; you must have created a + * context and it must be current before calling this function. Do not assume + * that all contexts you create will have the same set of extensions + * available, or that recreating an existing context will offer the same + * extensions again. + * + * While it's probably not a massive overhead, this function is not an O(1) + * operation. Check the extensions you care about after creating the GL + * context and save that information somewhere instead of calling the function + * every time you need to know. + * + * \param extension the name of the extension to check. + * \returns SDL_TRUE if the extension is supported, SDL_FALSE otherwise. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_bool SDLCALL SDL_GL_ExtensionSupported(const char + *extension); + +/** + * Reset all previously set OpenGL context attributes to their default values. + * + * \since This function is available since SDL 2.0.2. + * + * \sa SDL_GL_GetAttribute + * \sa SDL_GL_SetAttribute + */ +extern DECLSPEC void SDLCALL SDL_GL_ResetAttributes(void); + +/** + * Set an OpenGL window attribute before window creation. + * + * This function sets the OpenGL attribute `attr` to `value`. The requested + * attributes should be set before creating an OpenGL window. You should use + * SDL_GL_GetAttribute() to check the values after creating the OpenGL + * context, since the values obtained can differ from the requested ones. + * + * \param attr an SDL_GLattr enum value specifying the OpenGL attribute to + * set. + * \param value the desired value for the attribute. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_GetAttribute + * \sa SDL_GL_ResetAttributes + */ +extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value); + +/** + * Get the actual value for an attribute from the current context. + * + * \param attr an SDL_GLattr enum value specifying the OpenGL attribute to + * get. + * \param value a pointer filled in with the current value of `attr`. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_ResetAttributes + * \sa SDL_GL_SetAttribute + */ +extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int *value); + +/** + * Create an OpenGL context for an OpenGL window, and make it current. + * + * Windows users new to OpenGL should note that, for historical reasons, GL + * functions added after OpenGL version 1.1 are not available by default. + * Those functions must be loaded at run-time, either with an OpenGL + * extension-handling library or with SDL_GL_GetProcAddress() and its related + * functions. + * + * SDL_GLContext is an alias for `void *`. It's opaque to the application. + * + * \param window the window to associate with the context. + * \returns the OpenGL context associated with `window` or NULL on error; call + * SDL_GetError() for more details. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_DeleteContext + * \sa SDL_GL_MakeCurrent + */ +extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_CreateContext(SDL_Window * + window); + +/** + * Set up an OpenGL context for rendering into an OpenGL window. + * + * The context must have been created with a compatible window. + * + * \param window the window to associate with the context. + * \param context the OpenGL context to associate with the window. + * \returns 0 on success or a negative error code on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_CreateContext + */ +extern DECLSPEC int SDLCALL SDL_GL_MakeCurrent(SDL_Window * window, + SDL_GLContext context); + +/** + * Get the currently active OpenGL window. + * + * \returns the currently active OpenGL window on success or NULL on failure; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC SDL_Window* SDLCALL SDL_GL_GetCurrentWindow(void); + +/** + * Get the currently active OpenGL context. + * + * \returns the currently active OpenGL context or NULL on failure; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_MakeCurrent + */ +extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_GetCurrentContext(void); + +/** + * Get the size of a window's underlying drawable in pixels. + * + * This returns info useful for calling glViewport(). + * + * This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI + * drawable, i.e. the window was created with `SDL_WINDOW_ALLOW_HIGHDPI` on a + * platform with high-DPI support (Apple calls this "Retina"), and not + * disabled by the `SDL_HINT_VIDEO_HIGHDPI_DISABLED` hint. + * + * \param window the window from which the drawable size should be queried. + * \param w a pointer to variable for storing the width in pixels, may be + * NULL. + * \param h a pointer to variable for storing the height in pixels, may be + * NULL. + * + * \since This function is available since SDL 2.0.1. + * + * \sa SDL_CreateWindow + * \sa SDL_GetWindowSize + */ +extern DECLSPEC void SDLCALL SDL_GL_GetDrawableSize(SDL_Window * window, int *w, + int *h); + +/** + * Set the swap interval for the current OpenGL context. + * + * Some systems allow specifying -1 for the interval, to enable adaptive + * vsync. Adaptive vsync works the same as vsync, but if you've already missed + * the vertical retrace for a given frame, it swaps buffers immediately, which + * might be less jarring for the user during occasional framerate drops. If an + * application requests adaptive vsync and the system does not support it, + * this function will fail and return -1. In such a case, you should probably + * retry the call with 1 for the interval. + * + * Adaptive vsync is implemented for some glX drivers with + * GLX_EXT_swap_control_tear, and for some Windows drivers with + * WGL_EXT_swap_control_tear. + * + * Read more on the Khronos wiki: + * https://www.khronos.org/opengl/wiki/Swap_Interval#Adaptive_Vsync + * + * \param interval 0 for immediate updates, 1 for updates synchronized with + * the vertical retrace, -1 for adaptive vsync. + * \returns 0 on success or -1 if setting the swap interval is not supported; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_GetSwapInterval + */ +extern DECLSPEC int SDLCALL SDL_GL_SetSwapInterval(int interval); + +/** + * Get the swap interval for the current OpenGL context. + * + * If the system can't determine the swap interval, or there isn't a valid + * current context, this function will return 0 as a safe default. + * + * \returns 0 if there is no vertical retrace synchronization, 1 if the buffer + * swap is synchronized with the vertical retrace, and -1 if late + * swaps happen immediately instead of waiting for the next retrace; + * call SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_SetSwapInterval + */ +extern DECLSPEC int SDLCALL SDL_GL_GetSwapInterval(void); + +/** + * Update a window with OpenGL rendering. + * + * This is used with double-buffered OpenGL contexts, which are the default. + * + * On macOS, make sure you bind 0 to the draw framebuffer before swapping the + * window, otherwise nothing will happen. If you aren't using + * glBindFramebuffer(), this is the default and you won't have to do anything + * extra. + * + * \param window the window to change. + * + * \since This function is available since SDL 2.0.0. + */ +extern DECLSPEC void SDLCALL SDL_GL_SwapWindow(SDL_Window * window); + +/** + * Delete an OpenGL context. + * + * \param context the OpenGL context to be deleted. + * + * \since This function is available since SDL 2.0.0. + * + * \sa SDL_GL_CreateContext + */ +extern DECLSPEC void SDLCALL SDL_GL_DeleteContext(SDL_GLContext context); + +/* @} *//* OpenGL support functions */ + + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_video_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/include/SDL_vulkan.h b/third_party/SDL2/include/SDL_vulkan.h new file mode 100644 index 00000000000..e005ed373ba --- /dev/null +++ b/third_party/SDL2/include/SDL_vulkan.h @@ -0,0 +1,219 @@ +/* + Simple DirectMedia Layer + Copyright (C) 2017, Mark Callow + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * # CategoryVulkan + * + * Header file for functions to creating Vulkan surfaces on SDL windows. + */ + +#ifndef SDL_vulkan_h_ +#define SDL_vulkan_h_ + +#include "SDL_video.h" + +#include "begin_code.h" +/* Set up for C function definitions, even when using C++ */ +#ifdef __cplusplus +extern "C" { +#endif + +/* Avoid including vulkan.h, don't define VkInstance if it's already included */ +#ifdef VULKAN_H_ +#define NO_SDL_VULKAN_TYPEDEFS +#endif +#ifndef NO_SDL_VULKAN_TYPEDEFS +#define VK_DEFINE_HANDLE(object) typedef struct object##_T* object; + +#if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) +#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object; +#else +#define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object; +#endif + +VK_DEFINE_HANDLE(VkInstance) +VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR) + +/* Make sure to undef to avoid issues in case of later vulkan include */ +#undef VK_DEFINE_HANDLE +#undef VK_DEFINE_NON_DISPATCHABLE_HANDLE + +#endif /* !NO_SDL_VULKAN_TYPEDEFS */ + +typedef VkInstance SDL_vulkanInstance; +typedef VkSurfaceKHR SDL_vulkanSurface; /* for compatibility with Tizen */ + +/** + * \name Vulkan support functions + * + * \note SDL_Vulkan_GetInstanceExtensions & SDL_Vulkan_CreateSurface API + * is compatable with Tizen's implementation of Vulkan in SDL. + */ +/* @{ */ + +/** + * Dynamically load the Vulkan loader library. + * + * This should be called after initializing the video driver, but before + * creating any Vulkan windows. If no Vulkan loader library is loaded, the + * default library will be loaded upon creation of the first Vulkan window. + * + * It is fairly common for Vulkan applications to link with libvulkan instead + * of explicitly loading it at run time. This will work with SDL provided the + * application links to a dynamic library and both it and SDL use the same + * search path. + * + * If you specify a non-NULL `path`, an application should retrieve all of the + * Vulkan functions it uses from the dynamic library using + * SDL_Vulkan_GetVkGetInstanceProcAddr unless you can guarantee `path` points + * to the same vulkan loader library the application linked to. + * + * On Apple devices, if `path` is NULL, SDL will attempt to find the + * `vkGetInstanceProcAddr` address within all the Mach-O images of the current + * process. This is because it is fairly common for Vulkan applications to + * link with libvulkan (and historically MoltenVK was provided as a static + * library). If it is not found, on macOS, SDL will attempt to load + * `vulkan.framework/vulkan`, `libvulkan.1.dylib`, + * `MoltenVK.framework/MoltenVK`, and `libMoltenVK.dylib`, in that order. On + * iOS, SDL will attempt to load `libMoltenVK.dylib`. Applications using a + * dynamic framework or .dylib must ensure it is included in its application + * bundle. + * + * On non-Apple devices, application linking with a static libvulkan is not + * supported. Either do not link to the Vulkan loader or link to a dynamic + * library version. + * + * \param path The platform dependent Vulkan loader library name or NULL. + * \returns 0 on success or -1 if the library couldn't be loaded; call + * SDL_GetError() for more information. + * + * \since This function is available since SDL 2.0.6. + * + * \sa SDL_Vulkan_GetVkGetInstanceProcAddr + * \sa SDL_Vulkan_UnloadLibrary + */ +extern DECLSPEC int SDLCALL SDL_Vulkan_LoadLibrary(const char *path); + +/** + * Get the address of the `vkGetInstanceProcAddr` function. + * + * This should be called after either calling SDL_Vulkan_LoadLibrary() or + * creating an SDL_Window with the `SDL_WINDOW_VULKAN` flag. + * + * \returns the function pointer for `vkGetInstanceProcAddr` or NULL on error. + * + * \since This function is available since SDL 2.0.6. + */ +extern DECLSPEC void *SDLCALL SDL_Vulkan_GetVkGetInstanceProcAddr(void); + +/** + * Unload the Vulkan library previously loaded by SDL_Vulkan_LoadLibrary() + * + * \since This function is available since SDL 2.0.6. + * + * \sa SDL_Vulkan_LoadLibrary + */ +extern DECLSPEC void SDLCALL SDL_Vulkan_UnloadLibrary(void); + +/** + * Get the names of the Vulkan instance extensions needed to create a surface + * with SDL_Vulkan_CreateSurface. + * + * If `pNames` is NULL, then the number of required Vulkan instance extensions + * is returned in `pCount`. Otherwise, `pCount` must point to a variable set + * to the number of elements in the `pNames` array, and on return the variable + * is overwritten with the number of names actually written to `pNames`. If + * `pCount` is less than the number of required extensions, at most `pCount` + * structures will be written. If `pCount` is smaller than the number of + * required extensions, SDL_FALSE will be returned instead of SDL_TRUE, to + * indicate that not all the required extensions were returned. + * + * The `window` parameter is currently needed to be valid as of SDL 2.0.8, + * however, this parameter will likely be removed in future releases + * + * \param window A window for which the required Vulkan instance extensions + * should be retrieved (will be deprecated in a future release). + * \param pCount A pointer to an unsigned int corresponding to the number of + * extensions to be returned. + * \param pNames NULL or a pointer to an array to be filled with required + * Vulkan instance extensions. + * \returns SDL_TRUE on success, SDL_FALSE on error. + * + * \since This function is available since SDL 2.0.6. + * + * \sa SDL_Vulkan_CreateSurface + */ +extern DECLSPEC SDL_bool SDLCALL SDL_Vulkan_GetInstanceExtensions(SDL_Window *window, + unsigned int *pCount, + const char **pNames); + +/** + * Create a Vulkan rendering surface for a window. + * + * The `window` must have been created with the `SDL_WINDOW_VULKAN` flag and + * `instance` must have been created with extensions returned by + * SDL_Vulkan_GetInstanceExtensions() enabled. + * + * \param window The window to which to attach the Vulkan surface. + * \param instance The Vulkan instance handle. + * \param surface A pointer to a VkSurfaceKHR handle to output the newly + * created surface. + * \returns SDL_TRUE on success, SDL_FALSE on error. + * + * \since This function is available since SDL 2.0.6. + * + * \sa SDL_Vulkan_GetInstanceExtensions + * \sa SDL_Vulkan_GetDrawableSize + */ +extern DECLSPEC SDL_bool SDLCALL SDL_Vulkan_CreateSurface(SDL_Window *window, + VkInstance instance, + VkSurfaceKHR* surface); + +/** + * Get the size of the window's underlying drawable dimensions in pixels. + * + * This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI + * drawable, i.e. the window was created with `SDL_WINDOW_ALLOW_HIGHDPI` on a + * platform with high-DPI support (Apple calls this "Retina"), and not + * disabled by the `SDL_HINT_VIDEO_HIGHDPI_DISABLED` hint. + * + * \param window an SDL_Window for which the size is to be queried. + * \param w Pointer to the variable to write the width to or NULL. + * \param h Pointer to the variable to write the height to or NULL. + * + * \since This function is available since SDL 2.0.6. + * + * \sa SDL_GetWindowSize + * \sa SDL_CreateWindow + * \sa SDL_Vulkan_CreateSurface + */ +extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window * window, + int *w, int *h); + +/* @} *//* Vulkan support functions */ + +/* Ends C function definitions when using C++ */ +#ifdef __cplusplus +} +#endif +#include "close_code.h" + +#endif /* SDL_vulkan_h_ */ diff --git a/third_party/SDL2/include/begin_code.h b/third_party/SDL2/include/begin_code.h new file mode 100644 index 00000000000..2044e5cb06e --- /dev/null +++ b/third_party/SDL2/include/begin_code.h @@ -0,0 +1,189 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* WIKI CATEGORY: BeginCode */ + +/** + * begin_code.h sets things up for C dynamic library function definitions, + * static inlined functions, and structures aligned at 4-byte alignment. + * If you don't like ugly C preprocessor code, don't look at this file. :) + */ + +/* This shouldn't be nested -- included it around code only. */ +#ifdef SDL_begin_code_h +#error Nested inclusion of begin_code.h +#endif +#define SDL_begin_code_h + +#ifndef SDL_DEPRECATED +# if defined(__GNUC__) && (__GNUC__ >= 4) /* technically, this arrived in gcc 3.1, but oh well. */ +# define SDL_DEPRECATED __attribute__((deprecated)) +# elif defined(_MSC_VER) +# define SDL_DEPRECATED __declspec(deprecated) +# else +# define SDL_DEPRECATED +# endif +#endif + +#ifndef SDL_UNUSED +# ifdef __GNUC__ +# define SDL_UNUSED __attribute__((unused)) +# else +# define SDL_UNUSED +# endif +#endif + +/* Some compilers use a special export keyword */ +#ifndef DECLSPEC +# if defined(__WIN32__) || defined(__WINRT__) || defined(__CYGWIN__) || defined(__GDK__) +# ifdef DLL_EXPORT +# define DECLSPEC __declspec(dllexport) +# else +# define DECLSPEC +# endif +# elif defined(__OS2__) +# ifdef BUILD_SDL +# define DECLSPEC __declspec(dllexport) +# else +# define DECLSPEC +# endif +# else +# if defined(__GNUC__) && __GNUC__ >= 4 +# define DECLSPEC __attribute__ ((visibility("default"))) +# else +# define DECLSPEC +# endif +# endif +#endif + +/* By default SDL uses the C calling convention */ +#ifndef SDLCALL +#if (defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__)) && !defined(__GNUC__) +#define SDLCALL __cdecl +#elif defined(__OS2__) || defined(__EMX__) +#define SDLCALL _System +# if defined (__GNUC__) && !defined(_System) +# define _System /* for old EMX/GCC compat. */ +# endif +#else +#define SDLCALL +#endif +#endif /* SDLCALL */ + +/* Removed DECLSPEC on Symbian OS because SDL cannot be a DLL in EPOC */ +#ifdef __SYMBIAN32__ +#undef DECLSPEC +#define DECLSPEC +#endif /* __SYMBIAN32__ */ + +/* Force structure packing at 4 byte alignment. + This is necessary if the header is included in code which has structure + packing set to an alternate value, say for loading structures from disk. + The packing is reset to the previous value in close_code.h + */ +#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__) +#ifdef _MSC_VER +#pragma warning(disable: 4103) +#endif +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wpragma-pack" +#endif +#ifdef __BORLANDC__ +#pragma nopackwarning +#endif +#ifdef _WIN64 +/* Use 8-byte alignment on 64-bit architectures, so pointers are aligned */ +#pragma pack(push,8) +#else +#pragma pack(push,4) +#endif +#endif /* Compiler needs structure packing set */ + +#ifndef SDL_INLINE +#if defined(__GNUC__) +#define SDL_INLINE __inline__ +#elif defined(_MSC_VER) || defined(__BORLANDC__) || \ + defined(__DMC__) || defined(__SC__) || \ + defined(__WATCOMC__) || defined(__LCC__) || \ + defined(__DECC) || defined(__CC_ARM) +#define SDL_INLINE __inline +#ifndef __inline__ +#define __inline__ __inline +#endif +#else +#define SDL_INLINE inline +#ifndef __inline__ +#define __inline__ inline +#endif +#endif +#endif /* SDL_INLINE not defined */ + +#ifndef SDL_FORCE_INLINE +#if defined(_MSC_VER) +#define SDL_FORCE_INLINE __forceinline +#elif ( (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) ) +#define SDL_FORCE_INLINE __attribute__((always_inline)) static __inline__ +#else +#define SDL_FORCE_INLINE static SDL_INLINE +#endif +#endif /* SDL_FORCE_INLINE not defined */ + +#ifndef SDL_NORETURN +#if defined(__GNUC__) +#define SDL_NORETURN __attribute__((noreturn)) +#elif defined(_MSC_VER) +#define SDL_NORETURN __declspec(noreturn) +#else +#define SDL_NORETURN +#endif +#endif /* SDL_NORETURN not defined */ + +/* Apparently this is needed by several Windows compilers */ +#if !defined(__MACH__) +#ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else +#define NULL ((void *)0) +#endif +#endif /* NULL */ +#endif /* ! Mac OS X - breaks precompiled headers */ + +#ifndef SDL_FALLTHROUGH +#if (defined(__cplusplus) && __cplusplus >= 201703L) || \ + (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L) +#define SDL_FALLTHROUGH [[fallthrough]] +#else +#if defined(__has_attribute) && !defined(__SUNPRO_C) && !defined(__SUNPRO_CC) +#define SDL_HAS_FALLTHROUGH __has_attribute(__fallthrough__) +#else +#define SDL_HAS_FALLTHROUGH 0 +#endif /* __has_attribute */ +#if SDL_HAS_FALLTHROUGH && \ + ((defined(__GNUC__) && __GNUC__ >= 7) || \ + (defined(__clang_major__) && __clang_major__ >= 10)) +#define SDL_FALLTHROUGH __attribute__((__fallthrough__)) +#else +#define SDL_FALLTHROUGH do {} while (0) /* fallthrough */ +#endif /* SDL_HAS_FALLTHROUGH */ +#undef SDL_HAS_FALLTHROUGH +#endif /* C++17 or C2x */ +#endif /* SDL_FALLTHROUGH not defined */ diff --git a/third_party/SDL2/include/close_code.h b/third_party/SDL2/include/close_code.h new file mode 100644 index 00000000000..f991f458d59 --- /dev/null +++ b/third_party/SDL2/include/close_code.h @@ -0,0 +1,40 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/** + * \file close_code.h + * + * This file reverses the effects of begin_code.h and should be included + * after you finish any function and structure declarations in your headers + */ + +#ifndef SDL_begin_code_h +#error close_code.h included without matching begin_code.h +#endif +#undef SDL_begin_code_h + +/* Reset structure packing at previous byte alignment */ +#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__) +#ifdef __BORLANDC__ +#pragma nopackwarning +#endif +#pragma pack(pop) +#endif /* Compiler needs structure packing set */ diff --git a/third_party/SDL2/meson.build b/third_party/SDL2/meson.build new file mode 100644 index 00000000000..fcbb803f44e --- /dev/null +++ b/third_party/SDL2/meson.build @@ -0,0 +1,163 @@ +project('SDL2','c', + version: '1.0.0', + default_options : ['buildtype=release'] +) + +SDL2Dependency = declare_dependency( + compile_args : [ + '-DSDL_BUILD_MAJOR_VERSION=2', + '-DSDL_BUILD_MINOR_VERSION=32', + '-DSDL_BUILD_MICRO_VERSION=0', + '-DMESA_EGL_NO_X11_HEADERS', + '-DEGL_NO_X11', + '-DHAVE_LINUX_VERSION_H', + '-DUSING_GENERATED_CONFIG_H', + '-DHAVE_CONFIG_H', + '-Wfatal-errors', + '-D_POSIX_C_SOURCE=200809L', + '-DRESDIR="/usr/share/dosbox-x"', + '-Wno-deprecated-enum-enum-conversion', + '-Wno-deprecated-declarations', + '-DNDEBUG=1', + '-Wno-error=incompatible-pointer-types', + '-Wno-unused-result', + '-D__LINUX__' + ], + + link_args : [], + include_directories : include_directories(['src', 'include']), + sources : [ + 'src/SDL.c', + 'src/SDL_assert.c', + 'src/SDL_dataqueue.c', + 'src/SDL_error.c', + 'src/SDL_guid.c', + 'src/SDL_hints.c', + 'src/SDL_list.c', + 'src/SDL_log.c', + 'src/SDL_utils.c', + 'src/atomic/SDL_atomic.c', + 'src/atomic/SDL_spinlock.c', + 'src/audio/SDL_audio.c', + 'src/audio/SDL_audiocvt.c', + 'src/audio/SDL_audiodev.c', + 'src/audio/SDL_audiotypecvt.c', + 'src/audio/SDL_mixer.c', + 'src/audio/SDL_wave.c', + 'src/cpuinfo/SDL_cpuinfo.c', + 'src/dynapi/SDL_dynapi.c', + 'src/events/SDL_clipboardevents.c', + 'src/events/SDL_displayevents.c', + 'src/events/SDL_dropevents.c', + 'src/events/SDL_events.c', + 'src/events/SDL_gesture.c', + 'src/events/SDL_keyboard.c', + 'src/events/SDL_keysym_to_scancode.c', + 'src/events/SDL_mouse.c', + 'src/events/SDL_quit.c', + 'src/events/SDL_scancode_tables.c', + 'src/events/SDL_touch.c', + 'src/events/SDL_windowevents.c', + 'src/events/imKStoUCS.c', + 'src/file/SDL_rwops.c', + 'src/hidapi/SDL_hidapi.c', + 'src/joystick/SDL_gamecontroller.c', + 'src/joystick/SDL_joystick.c', + 'src/joystick/SDL_steam_virtual_gamepad.c', + 'src/joystick/controller_type.c', + 'src/haptic/SDL_haptic.c', + 'src/haptic/dummy/SDL_syshaptic.c', + 'src/joystick/dummy/SDL_sysjoystick.c', + 'src/joystick/virtual/SDL_virtualjoystick.c', + 'src/libm/e_atan2.c', + 'src/libm/e_exp.c', + 'src/libm/e_fmod.c', + 'src/libm/e_log.c', + 'src/libm/e_log10.c', + 'src/libm/e_pow.c', + 'src/libm/e_rem_pio2.c', + 'src/libm/e_sqrt.c', + 'src/libm/k_cos.c', + 'src/libm/k_rem_pio2.c', + 'src/libm/k_sin.c', + 'src/libm/k_tan.c', + 'src/libm/s_atan.c', + 'src/libm/s_copysign.c', + 'src/libm/s_cos.c', + 'src/libm/s_fabs.c', + 'src/libm/s_floor.c', + 'src/libm/s_scalbn.c', + 'src/libm/s_sin.c', + 'src/libm/s_tan.c', + 'src/misc/SDL_url.c', + 'src/power/SDL_power.c', + 'src/render/SDL_d3dmath.c', + 'src/render/SDL_render.c', + 'src/render/SDL_yuv_sw.c', + 'src/render/software/SDL_blendfillrect.c', + 'src/render/software/SDL_blendline.c', + 'src/render/software/SDL_blendpoint.c', + 'src/render/software/SDL_drawline.c', + 'src/render/software/SDL_drawpoint.c', + 'src/render/software/SDL_render_sw.c', + 'src/render/software/SDL_rotate.c', + 'src/render/software/SDL_triangle.c', + 'src/sensor/SDL_sensor.c', + 'src/stdlib/SDL_crc16.c', + 'src/stdlib/SDL_crc32.c', + 'src/stdlib/SDL_getenv.c', + 'src/stdlib/SDL_iconv.c', + 'src/stdlib/SDL_malloc.c', + 'src/stdlib/SDL_mslibc.c', + 'src/stdlib/SDL_qsort.c', + 'src/stdlib/SDL_stdlib.c', + 'src/stdlib/SDL_string.c', + 'src/stdlib/SDL_strtokr.c', + 'src/thread/SDL_thread.c', + 'src/timer/SDL_timer.c', + 'src/video/SDL_RLEaccel.c', + 'src/video/SDL_blit.c', + 'src/video/SDL_blit_0.c', + 'src/video/SDL_blit_1.c', + 'src/video/SDL_blit_A.c', + 'src/video/SDL_blit_N.c', + 'src/video/SDL_blit_auto.c', + 'src/video/SDL_blit_copy.c', + 'src/video/SDL_blit_slow.c', + 'src/video/SDL_bmp.c', + 'src/video/SDL_clipboard.c', + 'src/video/SDL_egl.c', + 'src/video/SDL_fillrect.c', + 'src/video/SDL_pixels.c', + 'src/video/SDL_rect.c', + 'src/video/SDL_shape.c', + 'src/video/SDL_stretch.c', + 'src/video/SDL_surface.c', + 'src/video/SDL_video.c', + 'src/video/SDL_vulkan_utils.c', + 'src/video/SDL_yuv.c', + 'src/video/yuv2rgb/yuv_rgb_lsx.c', + 'src/video/yuv2rgb/yuv_rgb_sse.c', + 'src/video/yuv2rgb/yuv_rgb_std.c', + 'src/locale/SDL_locale.c', + 'src/video/dummy/SDL_nullevents.c', + 'src/video/dummy/SDL_nullframebuffer.c', + 'src/video/dummy/SDL_nullvideo.c', + 'src/audio/dummy/SDL_dummyaudio.c', + 'src/loadso/dlopen/SDL_sysloadso.c', + 'src/timer/unix/SDL_systimer.c', + 'src/core/linux/SDL_threadprio.c', + 'src/core/linux/SDL_sandbox.c', + 'src/core/unix/SDL_poll.c', + 'src/misc/dummy/SDL_sysurl.c', + 'src/locale/dummy/SDL_syslocale.c', + 'src/sensor/dummy/SDL_dummysensor.c', + 'src/thread/generic/SDL_syscond.c', + 'src/thread/generic/SDL_sysmutex.c', + 'src/thread/generic/SDL_syssem.c', + 'src/thread/generic/SDL_systhread.c', + 'src/thread/generic/SDL_systls.c', + 'src/filesystem/dummy/SDL_sysfilesystem.c', + ], + dependencies : [] + ) \ No newline at end of file diff --git a/third_party/SDL2/src/SDL.c b/third_party/SDL2/src/SDL.c new file mode 100644 index 00000000000..e21b500abb1 --- /dev/null +++ b/third_party/SDL2/src/SDL.c @@ -0,0 +1,683 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +#if defined(__WIN32__) || defined(__GDK__) +#include "core/windows/SDL_windows.h" +#elif defined(__OS2__) +#include /* _exit() */ +#elif !defined(__WINRT__) +#include /* _exit(), etc. */ +#endif +#if defined(__OS2__) +#include "core/os2/SDL_os2.h" +#endif + +/* this checks for HAVE_DBUS_DBUS_H internally. */ +#include "core/linux/SDL_dbus.h" + +#if defined(__EMSCRIPTEN__) +#include +#endif + +/* Initialization code for SDL */ + +#include "SDL.h" +#include "SDL_bits.h" +#include "SDL_revision.h" +#include "SDL_assert_c.h" +#include "SDL_log_c.h" +#include "events/SDL_events_c.h" +#include "haptic/SDL_haptic_c.h" +#include "joystick/SDL_joystick_c.h" +#include "sensor/SDL_sensor_c.h" +#include "thread/SDL_thread_c.h" + +/* Initialization/Cleanup routines */ +#ifndef SDL_TIMERS_DISABLED +#include "timer/SDL_timer_c.h" +#endif +#ifdef SDL_VIDEO_DRIVER_WINDOWS +extern int SDL_HelperWindowCreate(void); +extern int SDL_HelperWindowDestroy(void); +#endif + +#ifdef SDL_BUILD_MAJOR_VERSION +SDL_COMPILE_TIME_ASSERT(SDL_BUILD_MAJOR_VERSION, + SDL_MAJOR_VERSION == SDL_BUILD_MAJOR_VERSION); +SDL_COMPILE_TIME_ASSERT(SDL_BUILD_MINOR_VERSION, + SDL_MINOR_VERSION == SDL_BUILD_MINOR_VERSION); +SDL_COMPILE_TIME_ASSERT(SDL_BUILD_MICRO_VERSION, + SDL_PATCHLEVEL == SDL_BUILD_MICRO_VERSION); +#endif + +SDL_COMPILE_TIME_ASSERT(SDL_MAJOR_VERSION_min, SDL_MAJOR_VERSION >= 0); +/* Limited only by the need to fit in SDL_version */ +SDL_COMPILE_TIME_ASSERT(SDL_MAJOR_VERSION_max, SDL_MAJOR_VERSION <= 255); + +SDL_COMPILE_TIME_ASSERT(SDL_MINOR_VERSION_min, SDL_MINOR_VERSION >= 0); +/* Limited only by the need to fit in SDL_version */ +SDL_COMPILE_TIME_ASSERT(SDL_MINOR_VERSION_max, SDL_MINOR_VERSION <= 255); + +SDL_COMPILE_TIME_ASSERT(SDL_PATCHLEVEL_min, SDL_PATCHLEVEL >= 0); +/* Limited by its encoding in SDL_VERSIONNUM and in the ABI versions */ +SDL_COMPILE_TIME_ASSERT(SDL_PATCHLEVEL_max, SDL_PATCHLEVEL <= 99); + +/* This is not declared in any header, although it is shared between some + parts of SDL, because we don't want anything calling it without an + extremely good reason. */ +extern SDL_NORETURN void SDL_ExitProcess(int exitcode); +SDL_NORETURN void SDL_ExitProcess(int exitcode) +{ +#if defined(__WIN32__) || defined(__GDK__) + /* "if you do not know the state of all threads in your process, it is + better to call TerminateProcess than ExitProcess" + https://msdn.microsoft.com/en-us/library/windows/desktop/ms682658(v=vs.85).aspx */ + TerminateProcess(GetCurrentProcess(), exitcode); + /* MingW doesn't have TerminateProcess marked as noreturn, so add an + ExitProcess here that will never be reached but make MingW happy. */ + ExitProcess(exitcode); +#elif defined(__EMSCRIPTEN__) + emscripten_cancel_main_loop(); /* this should "kill" the app. */ + emscripten_force_exit(exitcode); /* this should "kill" the app. */ + exit(exitcode); +#elif defined(__HAIKU__) /* Haiku has _Exit, but it's not marked noreturn. */ + _exit(exitcode); +#elif defined(HAVE__EXIT) /* Upper case _Exit() */ + _Exit(exitcode); +#else + _exit(exitcode); +#endif +} + +/* The initialized subsystems */ +#ifdef SDL_MAIN_NEEDED +static SDL_bool SDL_MainIsReady = SDL_FALSE; +#else +static SDL_bool SDL_MainIsReady = SDL_TRUE; +#endif +static SDL_bool SDL_main_thread_initialized = SDL_FALSE; +static SDL_bool SDL_bInMainQuit = SDL_FALSE; +static Uint8 SDL_SubsystemRefCount[32]; + +/* Private helper to increment a subsystem's ref counter. */ +static void SDL_PrivateSubsystemRefCountIncr(Uint32 subsystem) +{ + const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255)); + if (subsystem_index >= 0) { + ++SDL_SubsystemRefCount[subsystem_index]; + } +} + +/* Private helper to decrement a subsystem's ref counter. */ +static void SDL_PrivateSubsystemRefCountDecr(Uint32 subsystem) +{ + const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + if ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] > 0)) { + --SDL_SubsystemRefCount[subsystem_index]; + } +} + +/* Private helper to check if a system needs init. */ +static SDL_bool SDL_PrivateShouldInitSubsystem(Uint32 subsystem) +{ + const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255)); + return ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 0)) ? SDL_TRUE : SDL_FALSE; +} + +/* Private helper to check if a system needs to be quit. */ +static SDL_bool SDL_PrivateShouldQuitSubsystem(Uint32 subsystem) +{ + const int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + if ((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 0)) { + return SDL_FALSE; + } + + /* If we're in SDL_Quit, we shut down every subsystem, even if refcount + * isn't zero. + */ + return (((subsystem_index >= 0) && (SDL_SubsystemRefCount[subsystem_index] == 1)) || SDL_bInMainQuit) ? SDL_TRUE : SDL_FALSE; +} + +/* Private helper to either increment's existing ref counter, + * or fully init a new subsystem. */ +static SDL_bool SDL_PrivateInitOrIncrSubsystem(Uint32 subsystem) +{ + int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); + SDL_assert((subsystem_index < 0) || (SDL_SubsystemRefCount[subsystem_index] < 255)); + if (subsystem_index < 0) { + return SDL_FALSE; + } + if (SDL_SubsystemRefCount[subsystem_index] > 0) { + ++SDL_SubsystemRefCount[subsystem_index]; + return SDL_TRUE; + } + return SDL_InitSubSystem(subsystem) == 0; +} + +void SDL_SetMainReady(void) +{ + SDL_MainIsReady = SDL_TRUE; +} + +void SDL_InitMainThread(void) +{ + if (SDL_main_thread_initialized) { + return; + } + + SDL_InitTLSData(); +#ifndef SDL_TIMERS_DISABLED + SDL_TicksInit(); +#endif + SDL_LogInit(); + + SDL_main_thread_initialized = SDL_TRUE; +} + +static void SDL_QuitMainThread(void) +{ + if (!SDL_main_thread_initialized) { + return; + } + + SDL_LogQuit(); +#ifndef SDL_TIMERS_DISABLED + SDL_TicksQuit(); +#endif + SDL_QuitTLSData(); + + SDL_main_thread_initialized = SDL_FALSE; +} + +int SDL_InitSubSystem(Uint32 flags) +{ + Uint32 flags_initialized = 0; + + if (!SDL_MainIsReady) { + return SDL_SetError("Application didn't initialize properly, did you include SDL_main.h in the file containing your main() function?"); + } + + /* Clear the error message */ + SDL_ClearError(); + +#ifdef SDL_USE_LIBDBUS + SDL_DBus_Init(); +#endif + +#ifdef SDL_VIDEO_DRIVER_WINDOWS + if (flags & (SDL_INIT_HAPTIC | SDL_INIT_JOYSTICK)) { + if (SDL_HelperWindowCreate() < 0) { + goto quit_and_error; + } + } +#endif + + /* Initialize the event subsystem */ + if (flags & SDL_INIT_EVENTS) { +#ifndef SDL_EVENTS_DISABLED + if (SDL_PrivateShouldInitSubsystem(SDL_INIT_EVENTS)) { + if (SDL_EventsInit() < 0) { + goto quit_and_error; + } + } + SDL_PrivateSubsystemRefCountIncr(SDL_INIT_EVENTS); + flags_initialized |= SDL_INIT_EVENTS; +#else + SDL_SetError("SDL not built with events support"); + goto quit_and_error; +#endif + } + + /* Initialize the timer subsystem */ + if (flags & SDL_INIT_TIMER) { +#if !defined(SDL_TIMERS_DISABLED) && !defined(SDL_TIMER_DUMMY) + if (SDL_PrivateShouldInitSubsystem(SDL_INIT_TIMER)) { + if (SDL_TimerInit() < 0) { + goto quit_and_error; + } + } + SDL_PrivateSubsystemRefCountIncr(SDL_INIT_TIMER); + flags_initialized |= SDL_INIT_TIMER; +#else + SDL_SetError("SDL not built with timer support"); + goto quit_and_error; +#endif + } + + /* Initialize the video subsystem */ + if (flags & SDL_INIT_VIDEO) { +#ifndef SDL_VIDEO_DISABLED + if (SDL_PrivateShouldInitSubsystem(SDL_INIT_VIDEO)) { + /* video implies events */ + if (!SDL_PrivateInitOrIncrSubsystem(SDL_INIT_EVENTS)) { + goto quit_and_error; + } + + if (SDL_VideoInit(NULL) < 0) { + goto quit_and_error; + } + } + SDL_PrivateSubsystemRefCountIncr(SDL_INIT_VIDEO); + flags_initialized |= SDL_INIT_VIDEO; +#else + SDL_SetError("SDL not built with video support"); + goto quit_and_error; +#endif + } + + /* Initialize the audio subsystem */ + if (flags & SDL_INIT_AUDIO) { +#ifndef SDL_AUDIO_DISABLED + if (SDL_PrivateShouldInitSubsystem(SDL_INIT_AUDIO)) { + /* audio implies events */ + if (!SDL_PrivateInitOrIncrSubsystem(SDL_INIT_EVENTS)) { + goto quit_and_error; + } + + if (SDL_AudioInit(NULL) < 0) { + goto quit_and_error; + } + } + SDL_PrivateSubsystemRefCountIncr(SDL_INIT_AUDIO); + flags_initialized |= SDL_INIT_AUDIO; +#else + SDL_SetError("SDL not built with audio support"); + goto quit_and_error; +#endif + } + + /* Initialize the joystick subsystem */ + if (flags & SDL_INIT_JOYSTICK) { +#ifndef SDL_JOYSTICK_DISABLED + if (SDL_PrivateShouldInitSubsystem(SDL_INIT_JOYSTICK)) { + /* joystick implies events */ + if (!SDL_PrivateInitOrIncrSubsystem(SDL_INIT_EVENTS)) { + goto quit_and_error; + } + + if (SDL_JoystickInit() < 0) { + goto quit_and_error; + } + } + SDL_PrivateSubsystemRefCountIncr(SDL_INIT_JOYSTICK); + flags_initialized |= SDL_INIT_JOYSTICK; +#else + SDL_SetError("SDL not built with joystick support"); + goto quit_and_error; +#endif + } + + if (flags & SDL_INIT_GAMECONTROLLER) { +#ifndef SDL_JOYSTICK_DISABLED + if (SDL_PrivateShouldInitSubsystem(SDL_INIT_GAMECONTROLLER)) { + /* game controller implies joystick */ + if (!SDL_PrivateInitOrIncrSubsystem(SDL_INIT_JOYSTICK)) { + goto quit_and_error; + } + + if (SDL_GameControllerInit() < 0) { + goto quit_and_error; + } + } + SDL_PrivateSubsystemRefCountIncr(SDL_INIT_GAMECONTROLLER); + flags_initialized |= SDL_INIT_GAMECONTROLLER; +#else + SDL_SetError("SDL not built with joystick support"); + goto quit_and_error; +#endif + } + + /* Initialize the haptic subsystem */ + if (flags & SDL_INIT_HAPTIC) { +#ifndef SDL_HAPTIC_DISABLED + if (SDL_PrivateShouldInitSubsystem(SDL_INIT_HAPTIC)) { + if (SDL_HapticInit() < 0) { + goto quit_and_error; + } + } + SDL_PrivateSubsystemRefCountIncr(SDL_INIT_HAPTIC); + flags_initialized |= SDL_INIT_HAPTIC; +#else + SDL_SetError("SDL not built with haptic (force feedback) support"); + goto quit_and_error; +#endif + } + + /* Initialize the sensor subsystem */ + if (flags & SDL_INIT_SENSOR) { +#ifndef SDL_SENSOR_DISABLED + if (SDL_PrivateShouldInitSubsystem(SDL_INIT_SENSOR)) { + if (SDL_SensorInit() < 0) { + goto quit_and_error; + } + } + SDL_PrivateSubsystemRefCountIncr(SDL_INIT_SENSOR); + flags_initialized |= SDL_INIT_SENSOR; +#else + SDL_SetError("SDL not built with sensor support"); + goto quit_and_error; +#endif + } + + (void)flags_initialized; /* make static analysis happy, since this only gets used in error cases. */ + + return 0; + +quit_and_error: + SDL_QuitSubSystem(flags_initialized); + return -1; +} + +int SDL_Init(Uint32 flags) +{ + return SDL_InitSubSystem(flags); +} + +void SDL_QuitSubSystem(Uint32 flags) +{ +#if defined(__OS2__) + SDL_OS2Quit(); +#endif + + /* Shut down requested initialized subsystems */ +#ifndef SDL_SENSOR_DISABLED + if (flags & SDL_INIT_SENSOR) { + if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_SENSOR)) { + SDL_SensorQuit(); + } + SDL_PrivateSubsystemRefCountDecr(SDL_INIT_SENSOR); + } +#endif + +#ifndef SDL_JOYSTICK_DISABLED + if (flags & SDL_INIT_GAMECONTROLLER) { + if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_GAMECONTROLLER)) { + SDL_GameControllerQuit(); + /* game controller implies joystick */ + SDL_QuitSubSystem(SDL_INIT_JOYSTICK); + } + SDL_PrivateSubsystemRefCountDecr(SDL_INIT_GAMECONTROLLER); + } + + if (flags & SDL_INIT_JOYSTICK) { + if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_JOYSTICK)) { + SDL_JoystickQuit(); + /* joystick implies events */ + SDL_QuitSubSystem(SDL_INIT_EVENTS); + } + SDL_PrivateSubsystemRefCountDecr(SDL_INIT_JOYSTICK); + } +#endif + +#ifndef SDL_HAPTIC_DISABLED + if (flags & SDL_INIT_HAPTIC) { + if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_HAPTIC)) { + SDL_HapticQuit(); + } + SDL_PrivateSubsystemRefCountDecr(SDL_INIT_HAPTIC); + } +#endif + +#ifndef SDL_AUDIO_DISABLED + if (flags & SDL_INIT_AUDIO) { + if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_AUDIO)) { + SDL_AudioQuit(); + /* audio implies events */ + SDL_QuitSubSystem(SDL_INIT_EVENTS); + } + SDL_PrivateSubsystemRefCountDecr(SDL_INIT_AUDIO); + } +#endif + +#ifndef SDL_VIDEO_DISABLED + if (flags & SDL_INIT_VIDEO) { + if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_VIDEO)) { + SDL_VideoQuit(); + /* video implies events */ + SDL_QuitSubSystem(SDL_INIT_EVENTS); + } + SDL_PrivateSubsystemRefCountDecr(SDL_INIT_VIDEO); + } +#endif + +#if !defined(SDL_TIMERS_DISABLED) && !defined(SDL_TIMER_DUMMY) + if (flags & SDL_INIT_TIMER) { + if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_TIMER)) { + SDL_TimerQuit(); + } + SDL_PrivateSubsystemRefCountDecr(SDL_INIT_TIMER); + } +#endif + +#ifndef SDL_EVENTS_DISABLED + if (flags & SDL_INIT_EVENTS) { + if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_EVENTS)) { + SDL_EventsQuit(); + } + SDL_PrivateSubsystemRefCountDecr(SDL_INIT_EVENTS); + } +#endif +} + +Uint32 SDL_WasInit(Uint32 flags) +{ + int i; + int num_subsystems = SDL_arraysize(SDL_SubsystemRefCount); + Uint32 initialized = 0; + + /* Fast path for checking one flag */ + if (SDL_HasExactlyOneBitSet32(flags)) { + int subsystem_index = SDL_MostSignificantBitIndex32(flags); + return SDL_SubsystemRefCount[subsystem_index] ? flags : 0; + } + + if (!flags) { + flags = SDL_INIT_EVERYTHING; + } + + num_subsystems = SDL_min(num_subsystems, SDL_MostSignificantBitIndex32(flags) + 1); + + /* Iterate over each bit in flags, and check the matching subsystem. */ + for (i = 0; i < num_subsystems; ++i) { + if ((flags & 1) && SDL_SubsystemRefCount[i] > 0) { + initialized |= (1 << i); + } + + flags >>= 1; + } + + return initialized; +} + +void SDL_Quit(void) +{ + SDL_bInMainQuit = SDL_TRUE; + + /* Quit all subsystems */ +#ifdef SDL_VIDEO_DRIVER_WINDOWS + SDL_HelperWindowDestroy(); +#endif + SDL_QuitSubSystem(SDL_INIT_EVERYTHING); + +#ifdef SDL_USE_LIBDBUS + SDL_DBus_Quit(); +#endif + + SDL_ClearHints(); + SDL_AssertionsQuit(); + + /* Now that every subsystem has been quit, we reset the subsystem refcount + * and the list of initialized subsystems. + */ + SDL_memset(SDL_SubsystemRefCount, 0x0, sizeof(SDL_SubsystemRefCount)); + + SDL_QuitMainThread(); + + SDL_bInMainQuit = SDL_FALSE; +} + +/* Get the library version number */ +void SDL_GetVersion(SDL_version *ver) +{ + static SDL_bool check_hint = SDL_TRUE; + static SDL_bool legacy_version = SDL_FALSE; + + if (!ver) { + return; + } + + SDL_VERSION(ver); + + if (check_hint) { + check_hint = SDL_FALSE; + legacy_version = SDL_GetHintBoolean("SDL_LEGACY_VERSION", SDL_FALSE); + } + + if (legacy_version) { + /* Prior to SDL 2.24.0, the patch version was incremented with every release */ + ver->patch = ver->minor; + ver->minor = 0; + } +} + +/* Get the library source revision */ +const char *SDL_GetRevision(void) +{ + return SDL_REVISION; +} + +/* Get the library source revision number */ +int SDL_GetRevisionNumber(void) +{ + return 0; /* doesn't make sense without Mercurial. */ +} + +/* Get the name of the platform */ +const char *SDL_GetPlatform(void) +{ +#if defined(__AIX__) + return "AIX"; +#elif defined(__ANDROID__) + return "Android"; +#elif defined(__BSDI__) + return "BSDI"; +#elif defined(__DREAMCAST__) + return "Dreamcast"; +#elif defined(__EMSCRIPTEN__) + return "Emscripten"; +#elif defined(__FREEBSD__) + return "FreeBSD"; +#elif defined(__HAIKU__) + return "Haiku"; +#elif defined(__HPUX__) + return "HP-UX"; +#elif defined(__IRIX__) + return "Irix"; +#elif defined(__LINUX__) + return "Linux"; +#elif defined(__MINT__) + return "Atari MiNT"; +#elif defined(__MACOS__) + return "MacOS Classic"; +#elif defined(__MACOSX__) + return "Mac OS X"; +#elif defined(__NACL__) + return "NaCl"; +#elif defined(__NETBSD__) + return "NetBSD"; +#elif defined(__OPENBSD__) + return "OpenBSD"; +#elif defined(__OS2__) + return "OS/2"; +#elif defined(__OSF__) + return "OSF/1"; +#elif defined(__QNXNTO__) + return "QNX Neutrino"; +#elif defined(__RISCOS__) + return "RISC OS"; +#elif defined(__SOLARIS__) + return "Solaris"; +#elif defined(__WIN32__) + return "Windows"; +#elif defined(__WINRT__) + return "WinRT"; +#elif defined(__WINGDK__) + return "WinGDK"; +#elif defined(__XBOXONE__) + return "Xbox One"; +#elif defined(__XBOXSERIES__) + return "Xbox Series X|S"; +#elif defined(__TVOS__) + return "tvOS"; +#elif defined(__IPHONEOS__) + return "iOS"; +#elif defined(__PS2__) + return "PlayStation 2"; +#elif defined(__PSP__) + return "PlayStation Portable"; +#elif defined(__VITA__) + return "PlayStation Vita"; +#elif defined(__NGAGE__) + return "Nokia N-Gage"; +#elif defined(__3DS__) + return "Nintendo 3DS"; +#else + return "Unknown (see SDL_platform.h)"; +#endif +} + +SDL_bool SDL_IsTablet(void) +{ +#if defined(__ANDROID__) + extern SDL_bool SDL_IsAndroidTablet(void); + return SDL_IsAndroidTablet(); +#elif defined(__IPHONEOS__) + extern SDL_bool SDL_IsIPad(void); + return SDL_IsIPad(); +#else + return SDL_FALSE; +#endif +} + +#if defined(__WIN32__) + +#if (!defined(HAVE_LIBC) || defined(__WATCOMC__)) && !defined(SDL_STATIC_LIB) +/* FIXME: Still need to include DllMain() on Watcom C ? */ + +BOOL APIENTRY MINGW32_FORCEALIGN _DllMainCRTStartup(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) +{ + switch (ul_reason_for_call) { + case DLL_PROCESS_ATTACH: + case DLL_THREAD_ATTACH: + case DLL_THREAD_DETACH: + case DLL_PROCESS_DETACH: + break; + } + return TRUE; +} +#endif /* Building DLL */ + +#endif /* defined(__WIN32__) || defined(__GDK__) */ + +/* vi: set sts=4 ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_assert.c b/third_party/SDL2/src/SDL_assert.c new file mode 100644 index 00000000000..76c7491fa7d --- /dev/null +++ b/third_party/SDL2/src/SDL_assert.c @@ -0,0 +1,465 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +#if defined(__WIN32__) || defined(__GDK__) +#include "core/windows/SDL_windows.h" +#endif + +#include "SDL.h" +#include "SDL_atomic.h" +#include "SDL_messagebox.h" +#include "SDL_video.h" +#include "SDL_assert.h" +#include "SDL_assert_c.h" +#include "video/SDL_sysvideo.h" + +#if defined(__WIN32__) || defined(__GDK__) +#ifndef WS_OVERLAPPEDWINDOW +#define WS_OVERLAPPEDWINDOW 0 +#endif +#else /* fprintf, etc. */ +#include +#include +#endif + +#if defined(__EMSCRIPTEN__) + #include + /* older Emscriptens don't have this, but we need to for wasm64 compatibility. */ + #ifndef MAIN_THREAD_EM_ASM_PTR + #ifdef __wasm64__ + #error You need to upgrade your Emscripten compiler to support wasm64 + #else + #define MAIN_THREAD_EM_ASM_PTR MAIN_THREAD_EM_ASM_INT + #endif + #endif +#endif + +/* The size of the stack buffer to use for rendering assert messages. */ +#define SDL_MAX_ASSERT_MESSAGE_STACK 256 + +static SDL_assert_state SDLCALL SDL_PromptAssertion(const SDL_assert_data *data, void *userdata); + +/* + * We keep all triggered assertions in a singly-linked list so we can + * generate a report later. + */ +static SDL_assert_data *triggered_assertions = NULL; + +#ifndef SDL_THREADS_DISABLED +static SDL_mutex *assertion_mutex = NULL; +#endif + +static SDL_AssertionHandler assertion_handler = SDL_PromptAssertion; +static void *assertion_userdata = NULL; + +#ifdef __GNUC__ +static void debug_print(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +#endif + +static void debug_print(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + SDL_LogMessageV(SDL_LOG_CATEGORY_ASSERT, SDL_LOG_PRIORITY_WARN, fmt, ap); + va_end(ap); +} + +static void SDL_AddAssertionToReport(SDL_assert_data *data) +{ + /* (data) is always a static struct defined with the assert macros, so + we don't have to worry about copying or allocating them. */ + data->trigger_count++; + if (data->trigger_count == 1) { /* not yet added? */ + data->next = triggered_assertions; + triggered_assertions = data; + } +} + +#if defined(__WIN32__) || defined(__GDK__) +#define ENDLINE "\r\n" +#else +#define ENDLINE "\n" +#endif + +static int SDL_RenderAssertMessage(char *buf, size_t buf_len, const SDL_assert_data *data) +{ + return SDL_snprintf(buf, buf_len, + "Assertion failure at %s (%s:%d), triggered %u %s:" ENDLINE " '%s'", + data->function, data->filename, data->linenum, + data->trigger_count, (data->trigger_count == 1) ? "time" : "times", + data->condition); +} + +static void SDL_GenerateAssertionReport(void) +{ + const SDL_assert_data *item = triggered_assertions; + + /* only do this if the app hasn't assigned an assertion handler. */ + if ((item) && (assertion_handler != SDL_PromptAssertion)) { + debug_print("\n\nSDL assertion report.\n"); + debug_print("All SDL assertions between last init/quit:\n\n"); + + while (item) { + debug_print( + "'%s'\n" + " * %s (%s:%d)\n" + " * triggered %u time%s.\n" + " * always ignore: %s.\n", + item->condition, item->function, item->filename, + item->linenum, item->trigger_count, + (item->trigger_count == 1) ? "" : "s", + item->always_ignore ? "yes" : "no"); + item = item->next; + } + debug_print("\n"); + + SDL_ResetAssertionReport(); + } +} + +/* This is not declared in any header, although it is shared between some + parts of SDL, because we don't want anything calling it without an + extremely good reason. */ +#if defined(__WATCOMC__) +extern void SDL_ExitProcess(int exitcode); +#pragma aux SDL_ExitProcess aborts; +#endif +extern SDL_NORETURN void SDL_ExitProcess(int exitcode); + +#if defined(__WATCOMC__) +static void SDL_AbortAssertion(void); +#pragma aux SDL_AbortAssertion aborts; +#endif +static SDL_NORETURN void SDL_AbortAssertion(void) +{ + SDL_Quit(); + SDL_ExitProcess(42); +} + +static SDL_assert_state SDLCALL SDL_PromptAssertion(const SDL_assert_data *data, void *userdata) +{ + const char *envr; + SDL_assert_state state = SDL_ASSERTION_ABORT; + SDL_Window *window; + SDL_MessageBoxData messagebox; + SDL_MessageBoxButtonData buttons[] = { + { 0, SDL_ASSERTION_RETRY, "Retry" }, + { 0, SDL_ASSERTION_BREAK, "Break" }, + { 0, SDL_ASSERTION_ABORT, "Abort" }, + { SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, + SDL_ASSERTION_IGNORE, "Ignore" }, + { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, + SDL_ASSERTION_ALWAYS_IGNORE, "Always Ignore" } + }; + int selected; + + char stack_buf[SDL_MAX_ASSERT_MESSAGE_STACK]; + char *message = stack_buf; + size_t buf_len = sizeof(stack_buf); + int len; + + (void)userdata; /* unused in default handler. */ + + /* Assume the output will fit... */ + len = SDL_RenderAssertMessage(message, buf_len, data); + + /* .. and if it didn't, try to allocate as much room as we actually need. */ + if (len >= (int)buf_len) { + if (SDL_size_add_overflow(len, 1, &buf_len) == 0) { + message = (char *)SDL_malloc(buf_len); + if (message) { + len = SDL_RenderAssertMessage(message, buf_len, data); + } else { + message = stack_buf; + } + } + } + + /* Something went very wrong */ + if (len < 0) { + if (message != stack_buf) { + SDL_free(message); + } + return SDL_ASSERTION_ABORT; + } + + debug_print("\n\n%s\n\n", message); + + /* let env. variable override, so unit tests won't block in a GUI. */ + envr = SDL_getenv("SDL_ASSERT"); + if (envr) { + if (message != stack_buf) { + SDL_free(message); + } + + if (SDL_strcmp(envr, "abort") == 0) { + return SDL_ASSERTION_ABORT; + } else if (SDL_strcmp(envr, "break") == 0) { + return SDL_ASSERTION_BREAK; + } else if (SDL_strcmp(envr, "retry") == 0) { + return SDL_ASSERTION_RETRY; + } else if (SDL_strcmp(envr, "ignore") == 0) { + return SDL_ASSERTION_IGNORE; + } else if (SDL_strcmp(envr, "always_ignore") == 0) { + return SDL_ASSERTION_ALWAYS_IGNORE; + } else { + return SDL_ASSERTION_ABORT; /* oh well. */ + } + } + + /* Leave fullscreen mode, if possible (scary!) */ + window = SDL_GetFocusWindow(); + if (window) { + if (SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN) { + SDL_MinimizeWindow(window); + } else { + /* !!! FIXME: ungrab the input if we're not fullscreen? */ + /* No need to mess with the window */ + window = NULL; + } + } + + /* Show a messagebox if we can, otherwise fall back to stdio */ + SDL_zero(messagebox); + messagebox.flags = SDL_MESSAGEBOX_WARNING; + messagebox.window = window; + messagebox.title = "Assertion Failed"; + messagebox.message = message; + messagebox.numbuttons = SDL_arraysize(buttons); + messagebox.buttons = buttons; + + if (SDL_ShowMessageBox(&messagebox, &selected) == 0) { + if (selected == -1) { + state = SDL_ASSERTION_IGNORE; + } else { + state = (SDL_assert_state)selected; + } + } else { +#if defined(__EMSCRIPTEN__) + /* This is nasty, but we can't block on a custom UI. */ + for (;;) { + SDL_bool okay = SDL_TRUE; + /* *INDENT-OFF* */ /* clang-format off */ + char *buf = (char *) MAIN_THREAD_EM_ASM_PTR({ + var str = + UTF8ToString($0) + '\n\n' + + 'Abort/Retry/Ignore/AlwaysIgnore? [ariA] :'; + var reply = window.prompt(str, "i"); + if (reply === null) { + reply = "i"; + } + return allocate(intArrayFromString(reply), 'i8', ALLOC_NORMAL); + }, message); + /* *INDENT-ON* */ /* clang-format on */ + + if (SDL_strcmp(buf, "a") == 0) { + state = SDL_ASSERTION_ABORT; +#if 0 /* (currently) no break functionality on Emscripten */ + } else if (SDL_strcmp(buf, "b") == 0) { + state = SDL_ASSERTION_BREAK; +#endif + } else if (SDL_strcmp(buf, "r") == 0) { + state = SDL_ASSERTION_RETRY; + } else if (SDL_strcmp(buf, "i") == 0) { + state = SDL_ASSERTION_IGNORE; + } else if (SDL_strcmp(buf, "A") == 0) { + state = SDL_ASSERTION_ALWAYS_IGNORE; + } else { + okay = SDL_FALSE; + } + free(buf); + + if (okay) { + break; + } + } +#elif defined(HAVE_STDIO_H) && !defined(__3DS__) + /* this is a little hacky. */ + for (;;) { + char buf[32]; + (void)fprintf(stderr, "Abort/Break/Retry/Ignore/AlwaysIgnore? [abriA] : "); + (void)fflush(stderr); + if (fgets(buf, sizeof(buf), stdin) == NULL) { + break; + } + + if (SDL_strncmp(buf, "a", 1) == 0) { + state = SDL_ASSERTION_ABORT; + break; + } else if (SDL_strncmp(buf, "b", 1) == 0) { + state = SDL_ASSERTION_BREAK; + break; + } else if (SDL_strncmp(buf, "r", 1) == 0) { + state = SDL_ASSERTION_RETRY; + break; + } else if (SDL_strncmp(buf, "i", 1) == 0) { + state = SDL_ASSERTION_IGNORE; + break; + } else if (SDL_strncmp(buf, "A", 1) == 0) { + state = SDL_ASSERTION_ALWAYS_IGNORE; + break; + } + } +#else + SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Assertion Failed", message, window); +#endif /* HAVE_STDIO_H */ + } + + /* Re-enter fullscreen mode */ + if (window) { + SDL_RestoreWindow(window); + } + + if (message != stack_buf) { + SDL_free(message); + } + + return state; +} + +SDL_assert_state SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file, int line) +{ + SDL_assert_state state = SDL_ASSERTION_IGNORE; + static int assertion_running = 0; + +#ifndef SDL_THREADS_DISABLED + static SDL_SpinLock spinlock = 0; + SDL_AtomicLock(&spinlock); + if (!assertion_mutex) { /* never called SDL_Init()? */ + assertion_mutex = SDL_CreateMutex(); + if (!assertion_mutex) { + SDL_AtomicUnlock(&spinlock); + return SDL_ASSERTION_IGNORE; /* oh well, I guess. */ + } + } + SDL_AtomicUnlock(&spinlock); + + SDL_LockMutex(assertion_mutex); +#endif /* !SDL_THREADS_DISABLED */ + + /* doing this because Visual C is upset over assigning in the macro. */ + if (data->trigger_count == 0) { + data->function = func; + data->filename = file; + data->linenum = line; + } + + SDL_AddAssertionToReport(data); + + assertion_running++; + if (assertion_running > 1) { /* assert during assert! Abort. */ + if (assertion_running == 2) { + SDL_AbortAssertion(); + } else if (assertion_running == 3) { /* Abort asserted! */ + SDL_ExitProcess(42); + } else { + while (1) { /* do nothing but spin; what else can you do?! */ + } + } + } + + if (!data->always_ignore) { + state = assertion_handler(data, assertion_userdata); + } + + switch (state) { + case SDL_ASSERTION_ALWAYS_IGNORE: + state = SDL_ASSERTION_IGNORE; + data->always_ignore = 1; + break; + + case SDL_ASSERTION_IGNORE: + case SDL_ASSERTION_RETRY: + case SDL_ASSERTION_BREAK: + break; /* macro handles these. */ + + case SDL_ASSERTION_ABORT: + SDL_AbortAssertion(); + /*break; ...shouldn't return, but oh well. */ + } + + assertion_running--; + +#ifndef SDL_THREADS_DISABLED + SDL_UnlockMutex(assertion_mutex); +#endif + + return state; +} + +void SDL_AssertionsQuit(void) +{ +#if SDL_ASSERT_LEVEL > 0 + SDL_GenerateAssertionReport(); +#ifndef SDL_THREADS_DISABLED + if (assertion_mutex) { + SDL_DestroyMutex(assertion_mutex); + assertion_mutex = NULL; + } +#endif +#endif /* SDL_ASSERT_LEVEL > 0 */ +} + +void SDL_SetAssertionHandler(SDL_AssertionHandler handler, void *userdata) +{ + if (handler != NULL) { + assertion_handler = handler; + assertion_userdata = userdata; + } else { + assertion_handler = SDL_PromptAssertion; + assertion_userdata = NULL; + } +} + +const SDL_assert_data *SDL_GetAssertionReport(void) +{ + return triggered_assertions; +} + +void SDL_ResetAssertionReport(void) +{ + SDL_assert_data *next = NULL; + SDL_assert_data *item; + for (item = triggered_assertions; item; item = next) { + next = (SDL_assert_data *)item->next; + item->always_ignore = SDL_FALSE; + item->trigger_count = 0; + item->next = NULL; + } + + triggered_assertions = NULL; +} + +SDL_AssertionHandler SDL_GetDefaultAssertionHandler(void) +{ + return SDL_PromptAssertion; +} + +SDL_AssertionHandler SDL_GetAssertionHandler(void **userdata) +{ + if (userdata) { + *userdata = assertion_userdata; + } + return assertion_handler; +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_assert_c.h b/third_party/SDL2/src/SDL_assert_c.h new file mode 100644 index 00000000000..69cd9c3e4c0 --- /dev/null +++ b/third_party/SDL2/src/SDL_assert_c.h @@ -0,0 +1,29 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_assert_c_h_ +#define SDL_assert_c_h_ + +extern void SDL_AssertionsQuit(void); + +#endif /* SDL_assert_c_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_dataqueue.c b/third_party/SDL2/src/SDL_dataqueue.c new file mode 100644 index 00000000000..0498e1259c0 --- /dev/null +++ b/third_party/SDL2/src/SDL_dataqueue.c @@ -0,0 +1,323 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +#include "SDL.h" +#include "./SDL_dataqueue.h" + +typedef struct SDL_DataQueuePacket +{ + size_t datalen; /* bytes currently in use in this packet. */ + size_t startpos; /* bytes currently consumed in this packet. */ + struct SDL_DataQueuePacket *next; /* next item in linked list. */ + Uint8 data[SDL_VARIABLE_LENGTH_ARRAY]; /* packet data */ +} SDL_DataQueuePacket; + +struct SDL_DataQueue +{ + SDL_mutex *lock; + SDL_DataQueuePacket *head; /* device fed from here. */ + SDL_DataQueuePacket *tail; /* queue fills to here. */ + SDL_DataQueuePacket *pool; /* these are unused packets. */ + size_t packet_size; /* size of new packets */ + size_t queued_bytes; /* number of bytes of data in the queue. */ +}; + +static void SDL_FreeDataQueueList(SDL_DataQueuePacket *packet) +{ + while (packet) { + SDL_DataQueuePacket *next = packet->next; + SDL_free(packet); + packet = next; + } +} + +SDL_DataQueue *SDL_NewDataQueue(const size_t _packetlen, const size_t initialslack) +{ + SDL_DataQueue *queue = (SDL_DataQueue *)SDL_calloc(1, sizeof(SDL_DataQueue)); + + if (!queue) { + SDL_OutOfMemory(); + } else { + const size_t packetlen = _packetlen ? _packetlen : 1024; + const size_t wantpackets = (initialslack + (packetlen - 1)) / packetlen; + size_t i; + + queue->packet_size = packetlen; + + queue->lock = SDL_CreateMutex(); + if (!queue->lock) { + SDL_free(queue); + return NULL; + } + + for (i = 0; i < wantpackets; i++) { + SDL_DataQueuePacket *packet = (SDL_DataQueuePacket *)SDL_malloc(sizeof(SDL_DataQueuePacket) + packetlen); + if (packet) { /* don't care if this fails, we'll deal later. */ + packet->datalen = 0; + packet->startpos = 0; + packet->next = queue->pool; + queue->pool = packet; + } + } + } + + return queue; +} + +void SDL_FreeDataQueue(SDL_DataQueue *queue) +{ + if (queue) { + SDL_FreeDataQueueList(queue->head); + SDL_FreeDataQueueList(queue->pool); + SDL_DestroyMutex(queue->lock); + SDL_free(queue); + } +} + +void SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack) +{ + const size_t packet_size = queue ? queue->packet_size : 1; + const size_t slackpackets = (slack + (packet_size - 1)) / packet_size; + SDL_DataQueuePacket *packet; + SDL_DataQueuePacket *prev = NULL; + size_t i; + + if (!queue) { + return; + } + + SDL_LockMutex(queue->lock); + + packet = queue->head; + + /* merge the available pool and the current queue into one list. */ + if (packet) { + queue->tail->next = queue->pool; + } else { + packet = queue->pool; + } + + /* Remove the queued packets from the device. */ + queue->tail = NULL; + queue->head = NULL; + queue->queued_bytes = 0; + queue->pool = packet; + + /* Optionally keep some slack in the pool to reduce memory allocation pressure. */ + for (i = 0; packet && (i < slackpackets); i++) { + prev = packet; + packet = packet->next; + } + + if (prev) { + prev->next = NULL; + } else { + queue->pool = NULL; + } + + SDL_UnlockMutex(queue->lock); + + SDL_FreeDataQueueList(packet); /* free extra packets */ +} + +/* You must hold queue->lock before calling this! */ +static SDL_DataQueuePacket *AllocateDataQueuePacket(SDL_DataQueue *queue) +{ + SDL_DataQueuePacket *packet; + + SDL_assert(queue != NULL); + + packet = queue->pool; + if (packet) { + /* we have one available in the pool. */ + queue->pool = packet->next; + } else { + /* Have to allocate a new one! */ + packet = (SDL_DataQueuePacket *)SDL_malloc(sizeof(SDL_DataQueuePacket) + queue->packet_size); + if (!packet) { + return NULL; + } + } + + packet->datalen = 0; + packet->startpos = 0; + packet->next = NULL; + + SDL_assert((queue->head != NULL) == (queue->queued_bytes != 0)); + if (!queue->tail) { + queue->head = packet; + } else { + queue->tail->next = packet; + } + queue->tail = packet; + return packet; +} + +int SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *_data, const size_t _len) +{ + size_t len = _len; + const Uint8 *data = (const Uint8 *)_data; + const size_t packet_size = queue ? queue->packet_size : 0; + SDL_DataQueuePacket *orighead; + SDL_DataQueuePacket *origtail; + size_t origlen; + size_t datalen; + + if (!queue) { + return SDL_InvalidParamError("queue"); + } + + SDL_LockMutex(queue->lock); + + orighead = queue->head; + origtail = queue->tail; + origlen = origtail ? origtail->datalen : 0; + + while (len > 0) { + SDL_DataQueuePacket *packet = queue->tail; + SDL_assert(packet == NULL || (packet->datalen <= packet_size)); + if (!packet || (packet->datalen >= packet_size)) { + /* tail packet missing or completely full; we need a new packet. */ + packet = AllocateDataQueuePacket(queue); + if (!packet) { + /* uhoh, reset so we've queued nothing new, free what we can. */ + if (!origtail) { + packet = queue->head; /* whole queue. */ + } else { + packet = origtail->next; /* what we added to existing queue. */ + origtail->next = NULL; + origtail->datalen = origlen; + } + queue->head = orighead; + queue->tail = origtail; + queue->pool = NULL; + + SDL_UnlockMutex(queue->lock); + SDL_FreeDataQueueList(packet); /* give back what we can. */ + return SDL_OutOfMemory(); + } + } + + datalen = SDL_min(len, packet_size - packet->datalen); + SDL_memcpy(packet->data + packet->datalen, data, datalen); + data += datalen; + len -= datalen; + packet->datalen += datalen; + queue->queued_bytes += datalen; + } + + SDL_UnlockMutex(queue->lock); + + return 0; +} + +size_t +SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len) +{ + size_t len = _len; + Uint8 *buf = (Uint8 *)_buf; + Uint8 *ptr = buf; + SDL_DataQueuePacket *packet; + + if (!queue) { + return 0; + } + + SDL_LockMutex(queue->lock); + + for (packet = queue->head; len && packet; packet = packet->next) { + const size_t avail = packet->datalen - packet->startpos; + const size_t cpy = SDL_min(len, avail); + SDL_assert(queue->queued_bytes >= avail); + + SDL_memcpy(ptr, packet->data + packet->startpos, cpy); + ptr += cpy; + len -= cpy; + } + + SDL_UnlockMutex(queue->lock); + + return (size_t)(ptr - buf); +} + +size_t +SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len) +{ + size_t len = _len; + Uint8 *buf = (Uint8 *)_buf; + Uint8 *ptr = buf; + SDL_DataQueuePacket *packet; + + if (!queue) { + return 0; + } + + SDL_LockMutex(queue->lock); + + while ((len > 0) && ((packet = queue->head) != NULL)) { + const size_t avail = packet->datalen - packet->startpos; + const size_t cpy = SDL_min(len, avail); + SDL_assert(queue->queued_bytes >= avail); + + SDL_memcpy(ptr, packet->data + packet->startpos, cpy); + packet->startpos += cpy; + ptr += cpy; + queue->queued_bytes -= cpy; + len -= cpy; + + if (packet->startpos == packet->datalen) { /* packet is done, put it in the pool. */ + queue->head = packet->next; + SDL_assert((packet->next != NULL) || (packet == queue->tail)); + packet->next = queue->pool; + queue->pool = packet; + } + } + + SDL_assert((queue->head != NULL) == (queue->queued_bytes != 0)); + + if (!queue->head) { + queue->tail = NULL; /* in case we drained the queue entirely. */ + } + + SDL_UnlockMutex(queue->lock); + + return (size_t)(ptr - buf); +} + +size_t +SDL_CountDataQueue(SDL_DataQueue *queue) +{ + size_t retval = 0; + if (queue) { + SDL_LockMutex(queue->lock); + retval = queue->queued_bytes; + SDL_UnlockMutex(queue->lock); + } + return retval; +} + +SDL_mutex *SDL_GetDataQueueMutex(SDL_DataQueue *queue) +{ + return queue ? queue->lock : NULL; +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_dataqueue.h b/third_party/SDL2/src/SDL_dataqueue.h new file mode 100644 index 00000000000..6c671adadc6 --- /dev/null +++ b/third_party/SDL2/src/SDL_dataqueue.h @@ -0,0 +1,40 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#ifndef SDL_dataqueue_h_ +#define SDL_dataqueue_h_ + +/* this is not (currently) a public API. But maybe it should be! */ + +struct SDL_DataQueue; +typedef struct SDL_DataQueue SDL_DataQueue; + +SDL_DataQueue *SDL_NewDataQueue(const size_t packetlen, const size_t initialslack); +void SDL_FreeDataQueue(SDL_DataQueue *queue); +void SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack); +int SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *data, const size_t len); +size_t SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *buf, const size_t len); +size_t SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *buf, const size_t len); +size_t SDL_CountDataQueue(SDL_DataQueue *queue); +SDL_mutex *SDL_GetDataQueueMutex(SDL_DataQueue *queue); /* don't destroy this, obviously. */ + +#endif /* SDL_dataqueue_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_error.c b/third_party/SDL2/src/SDL_error.c new file mode 100644 index 00000000000..db24b3bce6f --- /dev/null +++ b/third_party/SDL2/src/SDL_error.c @@ -0,0 +1,123 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +/* Simple error handling in SDL */ + +#include "SDL_error.h" +#include "SDL_error_c.h" + +int SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + /* Ignore call if invalid format pointer was passed */ + if (fmt) { + va_list ap; + int result; + SDL_error *error = SDL_GetErrBuf(); + + error->error = 1; /* mark error as valid */ + + va_start(ap, fmt); + result = SDL_vsnprintf(error->str, error->len, fmt, ap); + va_end(ap); + + if (result >= 0 && (size_t)result >= error->len && error->realloc_func) { + size_t len = (size_t)result + 1; + char *str = (char *)error->realloc_func(error->str, len); + if (str) { + error->str = str; + error->len = len; + va_start(ap, fmt); + (void)SDL_vsnprintf(error->str, error->len, fmt, ap); + va_end(ap); + } + } + + if (SDL_LogGetPriority(SDL_LOG_CATEGORY_ERROR) <= SDL_LOG_PRIORITY_DEBUG) { + /* If we are in debug mode, print out the error message */ + SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", error->str); + } + } + + return -1; +} + +/* Available for backwards compatibility */ +const char *SDL_GetError(void) +{ + const SDL_error *error = SDL_GetErrBuf(); + return error->error ? error->str : ""; +} + +void SDL_ClearError(void) +{ + SDL_GetErrBuf()->error = 0; +} + +/* Very common errors go here */ +int SDL_Error(SDL_errorcode code) +{ + switch (code) { + case SDL_ENOMEM: + return SDL_SetError("Out of memory"); + case SDL_EFREAD: + return SDL_SetError("Error reading from datastream"); + case SDL_EFWRITE: + return SDL_SetError("Error writing to datastream"); + case SDL_EFSEEK: + return SDL_SetError("Error seeking in datastream"); + case SDL_UNSUPPORTED: + return SDL_SetError("That operation is not supported"); + default: + return SDL_SetError("Unknown SDL error"); + } +} + +#ifdef TEST_ERROR +int main(int argc, char *argv[]) +{ + char buffer[BUFSIZ + 1]; + + SDL_SetError("Hi there!"); + printf("Error 1: %s\n", SDL_GetError()); + SDL_ClearError(); + SDL_memset(buffer, '1', BUFSIZ); + buffer[BUFSIZ] = 0; + SDL_SetError("This is the error: %s (%f)", buffer, 1.0); + printf("Error 2: %s\n", SDL_GetError()); + exit(0); +} +#endif + +char *SDL_GetErrorMsg(char *errstr, int maxlen) +{ + const SDL_error *error = SDL_GetErrBuf(); + + if (error->error) { + SDL_strlcpy(errstr, error->str, maxlen); + } else { + *errstr = '\0'; + } + + return errstr; +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_error_c.h b/third_party/SDL2/src/SDL_error_c.h new file mode 100644 index 00000000000..ae9f5dfed01 --- /dev/null +++ b/third_party/SDL2/src/SDL_error_c.h @@ -0,0 +1,44 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +/* This file defines a structure that carries language-independent + error messages +*/ + +#ifndef SDL_error_c_h_ +#define SDL_error_c_h_ + +typedef struct SDL_error +{ + int error; /* This is a numeric value corresponding to the current error */ + char *str; + size_t len; + SDL_realloc_func realloc_func; + SDL_free_func free_func; +} SDL_error; + +/* Defined in SDL_thread.c */ +extern SDL_error *SDL_GetErrBuf(void); + +#endif /* SDL_error_c_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_guid.c b/third_party/SDL2/src/SDL_guid.c new file mode 100644 index 00000000000..0e4c34b1c97 --- /dev/null +++ b/third_party/SDL2/src/SDL_guid.c @@ -0,0 +1,91 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + + +#include "SDL_guid.h" + +/* convert the guid to a printable string */ +void SDL_GUIDToString(SDL_GUID guid, char *pszGUID, int cbGUID) +{ + static const char k_rgchHexToASCII[] = "0123456789abcdef"; + int i; + + if ((!pszGUID) || (cbGUID <= 0)) { + return; + } + + for (i = 0; i < sizeof(guid.data) && i < (cbGUID - 1) / 2; i++) { + /* each input byte writes 2 ascii chars, and might write a null byte. */ + /* If we don't have room for next input byte, stop */ + unsigned char c = guid.data[i]; + + *pszGUID++ = k_rgchHexToASCII[c >> 4]; + *pszGUID++ = k_rgchHexToASCII[c & 0x0F]; + } + *pszGUID = '\0'; +} + +/*----------------------------------------------------------------------------- + * Purpose: Returns the 4 bit nibble for a hex character + * Input : c - + * Output : unsigned char + *-----------------------------------------------------------------------------*/ +static unsigned char nibble(unsigned char c) +{ + if ((c >= '0') && (c <= '9')) { + return c - '0'; + } + + if ((c >= 'A') && (c <= 'F')) { + return c - 'A' + 0x0a; + } + + if ((c >= 'a') && (c <= 'f')) { + return c - 'a' + 0x0a; + } + + /* received an invalid character, and no real way to return an error */ + /* AssertMsg1(false, "Q_nibble invalid hex character '%c' ", c); */ + return 0; +} + +/* convert the string version of a guid to the struct */ +SDL_GUID SDL_GUIDFromString(const char *pchGUID) +{ + SDL_GUID guid; + int maxoutputbytes = sizeof(guid); + size_t len = SDL_strlen(pchGUID); + Uint8 *p; + size_t i; + + /* Make sure it's even */ + len = (len) & ~0x1; + + SDL_memset(&guid, 0x00, sizeof(guid)); + + p = (Uint8 *)&guid; + for (i = 0; (i < len) && ((p - (Uint8 *)&guid) < maxoutputbytes); i += 2, p++) { + *p = (nibble((unsigned char)pchGUID[i]) << 4) | nibble((unsigned char)pchGUID[i + 1]); + } + + return guid; +} diff --git a/third_party/SDL2/src/SDL_hints.c b/third_party/SDL2/src/SDL_hints.c new file mode 100644 index 00000000000..f8e9ba4c2a3 --- /dev/null +++ b/third_party/SDL2/src/SDL_hints.c @@ -0,0 +1,303 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +#include "SDL_hints.h" +#include "SDL_error.h" +#include "SDL_hints_c.h" + +/* Assuming there aren't many hints set and they aren't being queried in + critical performance paths, we'll just use linked lists here. + */ +typedef struct SDL_HintWatch +{ + SDL_HintCallback callback; + void *userdata; + struct SDL_HintWatch *next; +} SDL_HintWatch; + +typedef struct SDL_Hint +{ + char *name; + char *value; + SDL_HintPriority priority; + SDL_HintWatch *callbacks; + struct SDL_Hint *next; +} SDL_Hint; + +static SDL_Hint *SDL_hints; + +SDL_bool SDL_SetHintWithPriority(const char *name, const char *value, SDL_HintPriority priority) +{ + const char *env; + SDL_Hint *hint; + SDL_HintWatch *entry; + + if (!name) { + return SDL_FALSE; + } + + env = SDL_getenv(name); + if (env && priority < SDL_HINT_OVERRIDE) { + return SDL_FALSE; + } + + for (hint = SDL_hints; hint; hint = hint->next) { + if (SDL_strcmp(name, hint->name) == 0) { + if (priority < hint->priority) { + return SDL_FALSE; + } + if (hint->value != value && + (!value || !hint->value || SDL_strcmp(hint->value, value) != 0)) { + for (entry = hint->callbacks; entry;) { + /* Save the next entry in case this one is deleted */ + SDL_HintWatch *next = entry->next; + entry->callback(entry->userdata, name, hint->value, value); + entry = next; + } + SDL_free(hint->value); + hint->value = value ? SDL_strdup(value) : NULL; + } + hint->priority = priority; + return SDL_TRUE; + } + } + + /* Couldn't find the hint, add a new one */ + hint = (SDL_Hint *)SDL_malloc(sizeof(*hint)); + if (!hint) { + return SDL_FALSE; + } + hint->name = SDL_strdup(name); + hint->value = value ? SDL_strdup(value) : NULL; + hint->priority = priority; + hint->callbacks = NULL; + hint->next = SDL_hints; + SDL_hints = hint; + return SDL_TRUE; +} + +SDL_bool SDL_ResetHint(const char *name) +{ + const char *env; + SDL_Hint *hint; + SDL_HintWatch *entry; + + if (!name) { + return SDL_FALSE; + } + + env = SDL_getenv(name); + for (hint = SDL_hints; hint; hint = hint->next) { + if (SDL_strcmp(name, hint->name) == 0) { + if ((!env && hint->value) || + (env && !hint->value) || + (env && SDL_strcmp(env, hint->value) != 0)) { + for (entry = hint->callbacks; entry;) { + /* Save the next entry in case this one is deleted */ + SDL_HintWatch *next = entry->next; + entry->callback(entry->userdata, name, hint->value, env); + entry = next; + } + } + SDL_free(hint->value); + hint->value = NULL; + hint->priority = SDL_HINT_DEFAULT; + return SDL_TRUE; + } + } + return SDL_FALSE; +} + +void SDL_ResetHints(void) +{ + const char *env; + SDL_Hint *hint; + SDL_HintWatch *entry; + + for (hint = SDL_hints; hint; hint = hint->next) { + env = SDL_getenv(hint->name); + if ((!env && hint->value) || + (env && !hint->value) || + (env && SDL_strcmp(env, hint->value) != 0)) { + for (entry = hint->callbacks; entry;) { + /* Save the next entry in case this one is deleted */ + SDL_HintWatch *next = entry->next; + entry->callback(entry->userdata, hint->name, hint->value, env); + entry = next; + } + } + SDL_free(hint->value); + hint->value = NULL; + hint->priority = SDL_HINT_DEFAULT; + } +} + +SDL_bool SDL_SetHint(const char *name, const char *value) +{ + return SDL_SetHintWithPriority(name, value, SDL_HINT_NORMAL); +} + +const char *SDL_GetHint(const char *name) +{ + const char *env; + SDL_Hint *hint; + + if (!name) { + return NULL; + } + + env = SDL_getenv(name); + for (hint = SDL_hints; hint; hint = hint->next) { + if (SDL_strcmp(name, hint->name) == 0) { + if (!env || hint->priority == SDL_HINT_OVERRIDE) { + return hint->value; + } + break; + } + } + return env; +} + +SDL_bool SDL_GetStringBoolean(const char *value, SDL_bool default_value) +{ + if (!value || !*value) { + return default_value; + } + if (*value == '0' || SDL_strcasecmp(value, "false") == 0) { + return SDL_FALSE; + } + return SDL_TRUE; +} + +SDL_bool SDL_GetHintBoolean(const char *name, SDL_bool default_value) +{ + const char *hint = SDL_GetHint(name); + return SDL_GetStringBoolean(hint, default_value); +} + +void SDL_AddHintCallback(const char *name, SDL_HintCallback callback, void *userdata) +{ + SDL_Hint *hint; + SDL_HintWatch *entry; + const char *value; + + if (!name || !*name) { + SDL_InvalidParamError("name"); + return; + } + if (!callback) { + SDL_InvalidParamError("callback"); + return; + } + + SDL_DelHintCallback(name, callback, userdata); + + entry = (SDL_HintWatch *)SDL_malloc(sizeof(*entry)); + if (!entry) { + SDL_OutOfMemory(); + return; + } + entry->callback = callback; + entry->userdata = userdata; + + for (hint = SDL_hints; hint; hint = hint->next) { + if (SDL_strcmp(name, hint->name) == 0) { + break; + } + } + if (!hint) { + /* Need to add a hint entry for this watcher */ + hint = (SDL_Hint *)SDL_malloc(sizeof(*hint)); + if (!hint) { + SDL_OutOfMemory(); + SDL_free(entry); + return; + } + hint->name = SDL_strdup(name); + if (!hint->name) { + SDL_free(entry); + SDL_free(hint); + SDL_OutOfMemory(); + return; + } + hint->value = NULL; + hint->priority = SDL_HINT_DEFAULT; + hint->callbacks = NULL; + hint->next = SDL_hints; + SDL_hints = hint; + } + + /* Add it to the callbacks for this hint */ + entry->next = hint->callbacks; + hint->callbacks = entry; + + /* Now call it with the current value */ + value = SDL_GetHint(name); + callback(userdata, name, value, value); +} + +void SDL_DelHintCallback(const char *name, SDL_HintCallback callback, void *userdata) +{ + SDL_Hint *hint; + SDL_HintWatch *entry, *prev; + + for (hint = SDL_hints; hint; hint = hint->next) { + if (SDL_strcmp(name, hint->name) == 0) { + prev = NULL; + for (entry = hint->callbacks; entry; entry = entry->next) { + if (callback == entry->callback && userdata == entry->userdata) { + if (prev) { + prev->next = entry->next; + } else { + hint->callbacks = entry->next; + } + SDL_free(entry); + break; + } + prev = entry; + } + return; + } + } +} + +void SDL_ClearHints(void) +{ + SDL_Hint *hint; + SDL_HintWatch *entry; + + while (SDL_hints) { + hint = SDL_hints; + SDL_hints = hint->next; + + SDL_free(hint->name); + SDL_free(hint->value); + for (entry = hint->callbacks; entry;) { + SDL_HintWatch *freeable = entry; + entry = entry->next; + SDL_free(freeable); + } + SDL_free(hint); + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_hints_c.h b/third_party/SDL2/src/SDL_hints_c.h new file mode 100644 index 00000000000..097a0d9dacb --- /dev/null +++ b/third_party/SDL2/src/SDL_hints_c.h @@ -0,0 +1,32 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +/* This file defines useful function for working with SDL hints */ + +#ifndef SDL_hints_c_h_ +#define SDL_hints_c_h_ + +extern SDL_bool SDL_GetStringBoolean(const char *value, SDL_bool default_value); + +#endif /* SDL_hints_c_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_internal.h b/third_party/SDL2/src/SDL_internal.h new file mode 100644 index 00000000000..aa6391493c7 --- /dev/null +++ b/third_party/SDL2/src/SDL_internal.h @@ -0,0 +1,215 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#ifndef SDL_internal_h_ +#define SDL_internal_h_ + +/* Many of SDL's features require _GNU_SOURCE on various platforms */ +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +/* This is for a variable-length array at the end of a struct: + struct x { int y; char z[SDL_VARIABLE_LENGTH_ARRAY]; }; + Use this because GCC 2 needs different magic than other compilers. */ +#if (defined(__GNUC__) && (__GNUC__ <= 2)) || defined(__CC_ARM) || defined(__cplusplus) +#define SDL_VARIABLE_LENGTH_ARRAY 1 +#else +#define SDL_VARIABLE_LENGTH_ARRAY +#endif + +#define SDL_MAX_SMALL_ALLOC_STACKSIZE 128 +#define SDL_small_alloc(type, count, pisstack) ((*(pisstack) = ((sizeof(type) * (count)) < SDL_MAX_SMALL_ALLOC_STACKSIZE)), (*(pisstack) ? SDL_stack_alloc(type, count) : (type *)SDL_malloc(sizeof(type) * (count)))) +#define SDL_small_free(ptr, isstack) \ + if ((isstack)) { \ + SDL_stack_free(ptr); \ + } else { \ + SDL_free(ptr); \ + } + +#include "dynapi/SDL_dynapi.h" + +#if SDL_DYNAMIC_API +#include "dynapi/SDL_dynapi_overrides.h" +/* force DECLSPEC off...it's all internal symbols now. + These will have actual #defines during SDL_dynapi.c only */ +#define DECLSPEC +#endif + +#include "SDL_config.h" + +/* If you run into a warning that O_CLOEXEC is redefined, update the SDL configuration header for your platform to add HAVE_O_CLOEXEC */ +#ifndef HAVE_O_CLOEXEC +#define O_CLOEXEC 0 +#endif + +/* A few #defines to reduce SDL2 footprint. + Only effective when library is statically linked. + You have to manually edit this file. */ +#ifndef SDL_LEAN_AND_MEAN +#define SDL_LEAN_AND_MEAN 0 +#endif + +/* Optimized functions from 'SDL_blit_0.c' + - blit with source BitsPerPixel < 8, palette */ +#ifndef SDL_HAVE_BLIT_0 +#define SDL_HAVE_BLIT_0 !SDL_LEAN_AND_MEAN +#endif + +/* Optimized functions from 'SDL_blit_1.c' + - blit with source BytesPerPixel == 1, palette */ +#ifndef SDL_HAVE_BLIT_1 +#define SDL_HAVE_BLIT_1 !SDL_LEAN_AND_MEAN +#endif + +/* Optimized functions from 'SDL_blit_A.c' + - blit with 'SDL_BLENDMODE_BLEND' blending mode */ +#ifndef SDL_HAVE_BLIT_A +#define SDL_HAVE_BLIT_A !SDL_LEAN_AND_MEAN +#endif + +/* Optimized functions from 'SDL_blit_N.c' + - blit with COLORKEY mode, or nothing */ +#ifndef SDL_HAVE_BLIT_N +#define SDL_HAVE_BLIT_N !SDL_LEAN_AND_MEAN +#endif + +/* Optimized functions from 'SDL_blit_N.c' + - RGB565 conversion with Lookup tables */ +#ifndef SDL_HAVE_BLIT_N_RGB565 +#define SDL_HAVE_BLIT_N_RGB565 !SDL_LEAN_AND_MEAN +#endif + +/* Optimized functions from 'SDL_blit_AUTO.c' + - blit with modulate color, modulate alpha, any blending mode + - scaling or not */ +#ifndef SDL_HAVE_BLIT_AUTO +#define SDL_HAVE_BLIT_AUTO !SDL_LEAN_AND_MEAN +#endif + +/* Run-Length-Encoding + - SDL_SetColorKey() called with SDL_RLEACCEL flag */ +#ifndef SDL_HAVE_RLE +#define SDL_HAVE_RLE !SDL_LEAN_AND_MEAN +#endif + +/* Software SDL_Renderer + - creation of software renderer + - *not* general blitting functions + - {blend,draw}{fillrect,line,point} internal functions */ +#ifndef SDL_VIDEO_RENDER_SW +#define SDL_VIDEO_RENDER_SW !SDL_LEAN_AND_MEAN +#endif + +/* YUV formats + - handling of YUV surfaces + - blitting and conversion functions */ +#ifndef SDL_HAVE_YUV +#define SDL_HAVE_YUV !SDL_LEAN_AND_MEAN +#endif + +#ifndef SDL_RENDER_DISABLED +/* define the not defined ones as 0 */ +#ifndef SDL_VIDEO_RENDER_D3D +#define SDL_VIDEO_RENDER_D3D 0 +#endif +#ifndef SDL_VIDEO_RENDER_D3D11 +#define SDL_VIDEO_RENDER_D3D11 0 +#endif +#ifndef SDL_VIDEO_RENDER_D3D12 +#define SDL_VIDEO_RENDER_D3D12 0 +#endif +#ifndef SDL_VIDEO_RENDER_METAL +#define SDL_VIDEO_RENDER_METAL 0 +#endif +#ifndef SDL_VIDEO_RENDER_OGL +#define SDL_VIDEO_RENDER_OGL 0 +#endif +#ifndef SDL_VIDEO_RENDER_OGL_ES +#define SDL_VIDEO_RENDER_OGL_ES 0 +#endif +#ifndef SDL_VIDEO_RENDER_OGL_ES2 +#define SDL_VIDEO_RENDER_OGL_ES2 0 +#endif +#ifndef SDL_VIDEO_RENDER_DIRECTFB +#define SDL_VIDEO_RENDER_DIRECTFB 0 +#endif +#ifndef SDL_VIDEO_RENDER_PS2 +#define SDL_VIDEO_RENDER_PS2 0 +#endif +#ifndef SDL_VIDEO_RENDER_PSP +#define SDL_VIDEO_RENDER_PSP 0 +#endif +#ifndef SDL_VIDEO_RENDER_VITA_GXM +#define SDL_VIDEO_RENDER_VITA_GXM 0 +#endif +#else /* define all as 0 */ +#undef SDL_VIDEO_RENDER_SW +#define SDL_VIDEO_RENDER_SW 0 +#undef SDL_VIDEO_RENDER_D3D +#define SDL_VIDEO_RENDER_D3D 0 +#undef SDL_VIDEO_RENDER_D3D11 +#define SDL_VIDEO_RENDER_D3D11 0 +#undef SDL_VIDEO_RENDER_D3D12 +#define SDL_VIDEO_RENDER_D3D12 0 +#undef SDL_VIDEO_RENDER_METAL +#define SDL_VIDEO_RENDER_METAL 0 +#undef SDL_VIDEO_RENDER_OGL +#define SDL_VIDEO_RENDER_OGL 0 +#undef SDL_VIDEO_RENDER_OGL_ES +#define SDL_VIDEO_RENDER_OGL_ES 0 +#undef SDL_VIDEO_RENDER_OGL_ES2 +#define SDL_VIDEO_RENDER_OGL_ES2 0 +#undef SDL_VIDEO_RENDER_DIRECTFB +#define SDL_VIDEO_RENDER_DIRECTFB 0 +#undef SDL_VIDEO_RENDER_PS2 +#define SDL_VIDEO_RENDER_PS2 0 +#undef SDL_VIDEO_RENDER_PSP +#define SDL_VIDEO_RENDER_PSP 0 +#undef SDL_VIDEO_RENDER_VITA_GXM +#define SDL_VIDEO_RENDER_VITA_GXM 0 +#endif /* SDL_RENDER_DISABLED */ + +#define SDL_HAS_RENDER_DRIVER \ + (SDL_VIDEO_RENDER_SW | \ + SDL_VIDEO_RENDER_D3D | \ + SDL_VIDEO_RENDER_D3D11 | \ + SDL_VIDEO_RENDER_D3D12 | \ + SDL_VIDEO_RENDER_METAL | \ + SDL_VIDEO_RENDER_OGL | \ + SDL_VIDEO_RENDER_OGL_ES | \ + SDL_VIDEO_RENDER_OGL_ES2 | \ + SDL_VIDEO_RENDER_DIRECTFB | \ + SDL_VIDEO_RENDER_PS2 | \ + SDL_VIDEO_RENDER_PSP | \ + SDL_VIDEO_RENDER_VITA_GXM) + +#if !defined(SDL_RENDER_DISABLED) && !SDL_HAS_RENDER_DRIVER +#error SDL_RENDER enabled without any backend drivers. +#endif + +#include "SDL_assert.h" +#include "SDL_log.h" + +extern void SDL_InitMainThread(void); + +#endif /* SDL_internal_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_list.c b/third_party/SDL2/src/SDL_list.c new file mode 100644 index 00000000000..88730029c2b --- /dev/null +++ b/third_party/SDL2/src/SDL_list.c @@ -0,0 +1,89 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +#include "SDL.h" +#include "./SDL_list.h" + +/* Push */ +int SDL_ListAdd(SDL_ListNode **head, void *ent) +{ + SDL_ListNode *node = SDL_malloc(sizeof(*node)); + + if (!node) { + return SDL_OutOfMemory(); + } + + node->entry = ent; + node->next = *head; + *head = node; + return 0; +} + +/* Pop from end as a FIFO (if add with SDL_ListAdd) */ +void SDL_ListPop(SDL_ListNode **head, void **ent) +{ + SDL_ListNode **ptr = head; + + /* Invalid or empty */ + if (!head || !*head) { + return; + } + + while ((*ptr)->next) { + ptr = &(*ptr)->next; + } + + if (ent) { + *ent = (*ptr)->entry; + } + + SDL_free(*ptr); + *ptr = NULL; +} + +void SDL_ListRemove(SDL_ListNode **head, void *ent) +{ + SDL_ListNode **ptr = head; + + while (*ptr) { + if ((*ptr)->entry == ent) { + SDL_ListNode *tmp = *ptr; + *ptr = (*ptr)->next; + SDL_free(tmp); + return; + } + ptr = &(*ptr)->next; + } +} + +void SDL_ListClear(SDL_ListNode **head) +{ + SDL_ListNode *l = *head; + *head = NULL; + while (l) { + SDL_ListNode *tmp = l; + l = l->next; + SDL_free(tmp); + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_list.h b/third_party/SDL2/src/SDL_list.h new file mode 100644 index 00000000000..16079b84b7d --- /dev/null +++ b/third_party/SDL2/src/SDL_list.h @@ -0,0 +1,38 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_list_h_ +#define SDL_list_h_ + +typedef struct SDL_ListNode +{ + void *entry; + struct SDL_ListNode *next; +} SDL_ListNode; + +int SDL_ListAdd(SDL_ListNode **head, void *ent); +void SDL_ListPop(SDL_ListNode **head, void **ent); +void SDL_ListRemove(SDL_ListNode **head, void *ent); +void SDL_ListClear(SDL_ListNode **head); + +#endif /* SDL_list_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_log.c b/third_party/SDL2/src/SDL_log.c new file mode 100644 index 00000000000..47f5b7251ea --- /dev/null +++ b/third_party/SDL2/src/SDL_log.c @@ -0,0 +1,611 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +#if defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__) +#include "core/windows/SDL_windows.h" +#endif + +/* Simple log messages in SDL */ + +#include "SDL_error.h" +#include "SDL_log.h" +#include "SDL_hints.h" +#include "SDL_mutex.h" +#include "SDL_log_c.h" + +#ifdef HAVE_STDIO_H +#include +#endif + +#if defined(__ANDROID__) +#include +#endif + +#include "stdlib/SDL_vacopy.h" + +/* The size of the stack buffer to use for rendering log messages. */ +#define SDL_MAX_LOG_MESSAGE_STACK 256 + +#define DEFAULT_CATEGORY -1 + +typedef struct SDL_LogLevel +{ + int category; + SDL_LogPriority priority; + struct SDL_LogLevel *next; +} SDL_LogLevel; + +/* The default log output function */ +static void SDLCALL SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority, const char *message); + +static SDL_LogLevel *SDL_loglevels; +static SDL_bool SDL_forced_priority = SDL_FALSE; +static SDL_LogPriority SDL_forced_priority_level; +static SDL_LogOutputFunction SDL_log_function = SDL_LogOutput; +static void *SDL_log_userdata = NULL; +static SDL_mutex *log_function_mutex = NULL; + +/* If this list changes, update the documentation for SDL_HINT_LOGGING */ +static const char *SDL_priority_prefixes[] = { + NULL, + "VERBOSE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "CRITICAL" +}; +SDL_COMPILE_TIME_ASSERT(priority_prefixes, SDL_arraysize(SDL_priority_prefixes) == SDL_NUM_LOG_PRIORITIES); + +/* If this list changes, update the documentation for SDL_HINT_LOGGING */ +static const char *SDL_category_prefixes[] = { + "APP", + "ERROR", + "ASSERT", + "SYSTEM", + "AUDIO", + "VIDEO", + "RENDER", + "INPUT", + "TEST" +}; +SDL_COMPILE_TIME_ASSERT(category_prefixes, SDL_arraysize(SDL_category_prefixes) == SDL_LOG_CATEGORY_RESERVED1); + +#ifdef __ANDROID__ +static int SDL_android_priority[SDL_NUM_LOG_PRIORITIES] = { + ANDROID_LOG_UNKNOWN, + ANDROID_LOG_VERBOSE, + ANDROID_LOG_DEBUG, + ANDROID_LOG_INFO, + ANDROID_LOG_WARN, + ANDROID_LOG_ERROR, + ANDROID_LOG_FATAL +}; +#endif /* __ANDROID__ */ + +void SDL_LogInit(void) +{ + if (!log_function_mutex) { + /* if this fails we'll try to continue without it. */ + log_function_mutex = SDL_CreateMutex(); + } +} + +void SDL_LogQuit(void) +{ + SDL_LogResetPriorities(); + if (log_function_mutex) { + SDL_DestroyMutex(log_function_mutex); + log_function_mutex = NULL; + } +} + +void SDL_LogSetAllPriority(SDL_LogPriority priority) +{ + SDL_LogLevel *entry; + + for (entry = SDL_loglevels; entry; entry = entry->next) { + entry->priority = priority; + } + + SDL_forced_priority = SDL_TRUE; + SDL_forced_priority_level = priority; +} + +void SDL_LogSetPriority(int category, SDL_LogPriority priority) +{ + SDL_LogLevel *entry; + + for (entry = SDL_loglevels; entry; entry = entry->next) { + if (entry->category == category) { + entry->priority = priority; + return; + } + } + + /* Create a new entry */ + entry = (SDL_LogLevel *)SDL_malloc(sizeof(*entry)); + if (entry) { + entry->category = category; + entry->priority = priority; + entry->next = SDL_loglevels; + SDL_loglevels = entry; + } +} + +static SDL_bool SDL_ParseLogCategory(const char *string, size_t length, int *category) +{ + int i; + + if (SDL_isdigit(*string)) { + *category = SDL_atoi(string); + return SDL_TRUE; + } + + if (*string == '*') { + *category = DEFAULT_CATEGORY; + return SDL_TRUE; + } + + for (i = 0; i < SDL_arraysize(SDL_category_prefixes); ++i) { + if (SDL_strncasecmp(string, SDL_category_prefixes[i], length) == 0) { + *category = i; + return SDL_TRUE; + } + } + return SDL_FALSE; +} + +static SDL_bool SDL_ParseLogPriority(const char *string, size_t length, SDL_LogPriority *priority) +{ + int i; + + if (SDL_isdigit(*string)) { + i = SDL_atoi(string); + if (i == 0) { + /* 0 has a special meaning of "disable this category" */ + *priority = SDL_NUM_LOG_PRIORITIES; + return SDL_TRUE; + } + if (i >= SDL_LOG_PRIORITY_VERBOSE && i < SDL_NUM_LOG_PRIORITIES) { + *priority = (SDL_LogPriority)i; + return SDL_TRUE; + } + return SDL_FALSE; + } + + if (SDL_strncasecmp(string, "quiet", length) == 0) { + *priority = SDL_NUM_LOG_PRIORITIES; + return SDL_TRUE; + } + + for (i = SDL_LOG_PRIORITY_VERBOSE; i < SDL_NUM_LOG_PRIORITIES; ++i) { + if (SDL_strncasecmp(string, SDL_priority_prefixes[i], length) == 0) { + *priority = (SDL_LogPriority)i; + return SDL_TRUE; + } + } + return SDL_FALSE; +} + +static SDL_bool SDL_ParseLogCategoryPriority(const char *hint, int category, SDL_LogPriority *priority) +{ + const char *name, *next; + int current_category; + + if (category == DEFAULT_CATEGORY && SDL_strchr(hint, '=') == NULL) { + return SDL_ParseLogPriority(hint, SDL_strlen(hint), priority); + } + + for (name = hint; name; name = next) { + const char *sep = SDL_strchr(name, '='); + if (!sep) { + break; + } + next = SDL_strchr(sep, ','); + if (next) { + ++next; + } + + if (SDL_ParseLogCategory(name, (sep - name), ¤t_category)) { + if (current_category == category) { + const char *value = sep + 1; + size_t len; + if (next) { + len = (next - value - 1); + } else { + len = SDL_strlen(value); + } + return SDL_ParseLogPriority(value, len, priority); + } + } + } + return SDL_FALSE; +} + +static SDL_LogPriority SDL_GetDefaultLogPriority(int category) +{ + const char *hint = SDL_GetHint(SDL_HINT_LOGGING); + if (hint) { + SDL_LogPriority priority; + + if (SDL_ParseLogCategoryPriority(hint, category, &priority)) { + return priority; + } + if (SDL_ParseLogCategoryPriority(hint, DEFAULT_CATEGORY, &priority)) { + return priority; + } + } + + switch (category) { + case SDL_LOG_CATEGORY_APPLICATION: + return SDL_LOG_PRIORITY_INFO; + case SDL_LOG_CATEGORY_ASSERT: + return SDL_LOG_PRIORITY_WARN; + case SDL_LOG_CATEGORY_TEST: + return SDL_LOG_PRIORITY_VERBOSE; + default: + return SDL_LOG_PRIORITY_ERROR; + } +} + +SDL_LogPriority SDL_LogGetPriority(int category) +{ + SDL_LogLevel *entry; + + for (entry = SDL_loglevels; entry; entry = entry->next) { + if (entry->category == category) { + return entry->priority; + } + } + + if (SDL_forced_priority) { + return SDL_forced_priority_level; + } + + return SDL_GetDefaultLogPriority(category); +} + +void SDL_LogResetPriorities(void) +{ + SDL_LogLevel *entry; + + while (SDL_loglevels) { + entry = SDL_loglevels; + SDL_loglevels = entry->next; + SDL_free(entry); + } + SDL_forced_priority = SDL_FALSE; +} + +void SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); + va_end(ap); +} + +void SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_VERBOSE, fmt, ap); + va_end(ap); +} + +void SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_DEBUG, fmt, ap); + va_end(ap); +} + +void SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_INFO, fmt, ap); + va_end(ap); +} + +void SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_WARN, fmt, ap); + va_end(ap); +} + +void SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_ERROR, fmt, ap); + va_end(ap); +} + +void SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, SDL_LOG_PRIORITY_CRITICAL, fmt, ap); + va_end(ap); +} + +void SDL_LogMessage(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + SDL_LogMessageV(category, priority, fmt, ap); + va_end(ap); +} + +#ifdef __ANDROID__ +static const char *GetCategoryPrefix(int category) +{ + if (category < SDL_LOG_CATEGORY_RESERVED1) { + return SDL_category_prefixes[category]; + } + if (category < SDL_LOG_CATEGORY_CUSTOM) { + return "RESERVED"; + } + return "CUSTOM"; +} +#endif /* __ANDROID__ */ + +void SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list ap) +{ + char *message = NULL; + char stack_buf[SDL_MAX_LOG_MESSAGE_STACK]; + size_t len_plus_term; + int len; + va_list aq; + + /* Nothing to do if we don't have an output function */ + if (!SDL_log_function) { + return; + } + + /* Make sure we don't exceed array bounds */ + if ((int)priority < 0 || priority >= SDL_NUM_LOG_PRIORITIES) { + return; + } + + /* See if we want to do anything with this message */ + if (priority < SDL_LogGetPriority(category)) { + return; + } + + if (!log_function_mutex) { + /* this mutex creation can race if you log from two threads at startup. You should have called SDL_Init first! */ + log_function_mutex = SDL_CreateMutex(); + } + + /* Render into stack buffer */ + va_copy(aq, ap); + len = SDL_vsnprintf(stack_buf, sizeof(stack_buf), fmt, aq); + va_end(aq); + + if (len < 0) { + return; + } + + /* If message truncated, allocate and re-render */ + if (len >= sizeof(stack_buf) && SDL_size_add_overflow(len, 1, &len_plus_term) == 0) { + /* Allocate exactly what we need, including the zero-terminator */ + message = (char *)SDL_malloc(len_plus_term); + if (!message) { + return; + } + va_copy(aq, ap); + len = SDL_vsnprintf(message, len_plus_term, fmt, aq); + va_end(aq); + } else { + message = stack_buf; + } + + /* Chop off final endline. */ + if ((len > 0) && (message[len - 1] == '\n')) { + message[--len] = '\0'; + if ((len > 0) && (message[len - 1] == '\r')) { /* catch "\r\n", too. */ + message[--len] = '\0'; + } + } + + SDL_LockMutex(log_function_mutex); + SDL_log_function(SDL_log_userdata, category, priority, message); + SDL_UnlockMutex(log_function_mutex); + + /* Free only if dynamically allocated */ + if (message != stack_buf) { + SDL_free(message); + } +} + +#if defined(__WIN32__) && !defined(HAVE_STDIO_H) && !defined(__WINRT__) && !defined(__GDK__) +/* Flag tracking the attachment of the console: 0=unattached, 1=attached to a console, 2=attached to a file, -1=error */ +static int consoleAttached = 0; + +/* Handle to stderr output of console. */ +static HANDLE stderrHandle = NULL; +#endif + +static void SDLCALL SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority, + const char *message) +{ +#if defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__) + /* Way too many allocations here, urgh */ + /* Note: One can't call SDL_SetError here, since that function itself logs. */ + { + char *output; + size_t length; + LPTSTR tstr; + SDL_bool isstack; + +#if !defined(HAVE_STDIO_H) && !defined(__WINRT__) && !defined(__GDK__) + BOOL attachResult; + DWORD attachError; + DWORD charsWritten; + DWORD consoleMode; + + /* Maybe attach console and get stderr handle */ + if (consoleAttached == 0) { + attachResult = AttachConsole(ATTACH_PARENT_PROCESS); + if (!attachResult) { + attachError = GetLastError(); + if (attachError == ERROR_INVALID_HANDLE) { + /* This is expected when running from Visual Studio */ + /*OutputDebugString(TEXT("Parent process has no console\r\n"));*/ + consoleAttached = -1; + } else if (attachError == ERROR_GEN_FAILURE) { + OutputDebugString(TEXT("Could not attach to console of parent process\r\n")); + consoleAttached = -1; + } else if (attachError == ERROR_ACCESS_DENIED) { + /* Already attached */ + consoleAttached = 1; + } else { + OutputDebugString(TEXT("Error attaching console\r\n")); + consoleAttached = -1; + } + } else { + /* Newly attached */ + consoleAttached = 1; + } + + if (consoleAttached == 1) { + stderrHandle = GetStdHandle(STD_ERROR_HANDLE); + + if (GetConsoleMode(stderrHandle, &consoleMode) == 0) { + /* WriteConsole fails if the output is redirected to a file. Must use WriteFile instead. */ + consoleAttached = 2; + } + } + } +#endif /* !defined(HAVE_STDIO_H) && !defined(__WINRT__) && !defined(__GDK__) */ + + length = SDL_strlen(SDL_priority_prefixes[priority]) + 2 + SDL_strlen(message) + 1 + 1 + 1; + output = SDL_small_alloc(char, length, &isstack); + (void)SDL_snprintf(output, length, "%s: %s\r\n", SDL_priority_prefixes[priority], message); + tstr = WIN_UTF8ToString(output); + + /* Output to debugger */ + OutputDebugString(tstr); + +#if !defined(HAVE_STDIO_H) && !defined(__WINRT__) && !defined(__GDK__) + /* Screen output to stderr, if console was attached. */ + if (consoleAttached == 1) { + if (!WriteConsole(stderrHandle, tstr, (DWORD)SDL_tcslen(tstr), &charsWritten, NULL)) { + OutputDebugString(TEXT("Error calling WriteConsole\r\n")); + if (GetLastError() == ERROR_NOT_ENOUGH_MEMORY) { + OutputDebugString(TEXT("Insufficient heap memory to write message\r\n")); + } + } + + } else if (consoleAttached == 2) { + if (!WriteFile(stderrHandle, output, (DWORD)SDL_strlen(output), &charsWritten, NULL)) { + OutputDebugString(TEXT("Error calling WriteFile\r\n")); + } + } +#endif /* !defined(HAVE_STDIO_H) && !defined(__WINRT__) && !defined(__GDK__) */ + + SDL_free(tstr); + SDL_small_free(output, isstack); + } +#elif defined(__ANDROID__) + { + char tag[32]; + + SDL_snprintf(tag, SDL_arraysize(tag), "SDL/%s", GetCategoryPrefix(category)); + __android_log_write(SDL_android_priority[priority], tag, message); + } +#elif defined(__APPLE__) && (defined(SDL_VIDEO_DRIVER_COCOA) || defined(SDL_VIDEO_DRIVER_UIKIT)) + /* Technically we don't need Cocoa/UIKit, but that's where this function is defined for now. + */ + extern void SDL_NSLog(const char *prefix, const char *text); + { + SDL_NSLog(SDL_priority_prefixes[priority], message); + return; + } +#elif defined(__PSP__) || defined(__PS2__) + { + FILE *pFile; + pFile = fopen("SDL_Log.txt", "a"); + if (pFile) { + (void)fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message); + (void)fclose(pFile); + } + } +#elif defined(__VITA__) + { + FILE *pFile; + pFile = fopen("ux0:/data/SDL_Log.txt", "a"); + if (pFile) { + (void)fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message); + (void)fclose(pFile); + } + } +#elif defined(__3DS__) + { + FILE *pFile; + pFile = fopen("sdmc:/3ds/SDL_Log.txt", "a"); + if (pFile) { + (void)fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message); + (void)fclose(pFile); + } + } +#endif +#if defined(HAVE_STDIO_H) && \ + !(defined(__APPLE__) && (defined(SDL_VIDEO_DRIVER_COCOA) || defined(SDL_VIDEO_DRIVER_UIKIT))) + fprintf(stderr, "%s: %s\n", SDL_priority_prefixes[priority], message); +#ifdef __NACL__ + fflush(stderr); +#endif +#endif +} + +void SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata) +{ + if (callback) { + *callback = SDL_log_function; + } + if (userdata) { + *userdata = SDL_log_userdata; + } +} + +void SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata) +{ + SDL_log_function = callback; + SDL_log_userdata = userdata; +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_log_c.h b/third_party/SDL2/src/SDL_log_c.h new file mode 100644 index 00000000000..7fdd5142ddd --- /dev/null +++ b/third_party/SDL2/src/SDL_log_c.h @@ -0,0 +1,33 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "./SDL_internal.h" + +/* This file defines useful function for working with SDL logging */ + +#ifndef SDL_log_c_h_ +#define SDL_log_c_h_ + +extern void SDL_LogInit(void); +extern void SDL_LogQuit(void); + +#endif /* SDL_log_c_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_utils.c b/third_party/SDL2/src/SDL_utils.c new file mode 100644 index 00000000000..f4ebcf9dba8 --- /dev/null +++ b/third_party/SDL2/src/SDL_utils.c @@ -0,0 +1,52 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_utils_c.h" + +/* Common utility functions that aren't in the public API */ + +int SDL_powerof2(int x) +{ + int value; + + if (x <= 0) { + /* Return some sane value - we shouldn't hit this in our use cases */ + return 1; + } + + /* This trick works for 32-bit values */ + { + SDL_COMPILE_TIME_ASSERT(SDL_powerof2, sizeof(x) == sizeof(Uint32)); + } + value = x; + value -= 1; + value |= value >> 1; + value |= value >> 2; + value |= value >> 4; + value |= value >> 8; + value |= value >> 16; + value += 1; + + return value; +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/SDL_utils_c.h b/third_party/SDL2/src/SDL_utils_c.h new file mode 100644 index 00000000000..eb870c79214 --- /dev/null +++ b/third_party/SDL2/src/SDL_utils_c.h @@ -0,0 +1,32 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_utils_h_ +#define SDL_utils_h_ + +/* Common utility functions that aren't in the public API */ + +/* Return the smallest power of 2 greater than or equal to 'x' */ +extern int SDL_powerof2(int x); + +#endif /* SDL_utils_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/atomic/SDL_atomic.c b/third_party/SDL2/src/atomic/SDL_atomic.c new file mode 100644 index 00000000000..ea65796e7fc --- /dev/null +++ b/third_party/SDL2/src/atomic/SDL_atomic.c @@ -0,0 +1,305 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +#include "SDL_atomic.h" + +#if defined(_MSC_VER) && (_MSC_VER >= 1500) +#include +#define HAVE_MSC_ATOMICS 1 +#endif + +#if defined(__MACOSX__) /* !!! FIXME: should we favor gcc atomics? */ +#include +#endif + +#if !defined(HAVE_GCC_ATOMICS) && defined(__SOLARIS__) +#include +#endif + +/* The __atomic_load_n() intrinsic showed up in different times for different compilers. */ +#if defined(__clang__) +#if __has_builtin(__atomic_load_n) || defined(HAVE_GCC_ATOMICS) +/* !!! FIXME: this advertises as available in the NDK but uses an external symbol we don't have. + It might be in a later NDK or we might need an extra library? --ryan. */ +#if !defined(__ANDROID__) +#define HAVE_ATOMIC_LOAD_N 1 +#endif +#endif +#elif defined(__GNUC__) +#if (__GNUC__ >= 5) +#define HAVE_ATOMIC_LOAD_N 1 +#endif +#endif + +/* *INDENT-OFF* */ /* clang-format off */ +#if defined(__WATCOMC__) && defined(__386__) +SDL_COMPILE_TIME_ASSERT(intsize, 4==sizeof(int)); +#define HAVE_WATCOM_ATOMICS +extern __inline int _SDL_xchg_watcom(volatile int *a, int v); +#pragma aux _SDL_xchg_watcom = \ + "lock xchg [ecx], eax" \ + parm [ecx] [eax] \ + value [eax] \ + modify exact [eax]; + +extern __inline unsigned char _SDL_cmpxchg_watcom(volatile int *a, int newval, int oldval); +#pragma aux _SDL_cmpxchg_watcom = \ + "lock cmpxchg [edx], ecx" \ + "setz al" \ + parm [edx] [ecx] [eax] \ + value [al] \ + modify exact [eax]; + +extern __inline int _SDL_xadd_watcom(volatile int *a, int v); +#pragma aux _SDL_xadd_watcom = \ + "lock xadd [ecx], eax" \ + parm [ecx] [eax] \ + value [eax] \ + modify exact [eax]; + +#endif /* __WATCOMC__ && __386__ */ +/* *INDENT-ON* */ /* clang-format on */ + +/* + If any of the operations are not provided then we must emulate some + of them. That means we need a nice implementation of spin locks + that avoids the "one big lock" problem. We use a vector of spin + locks and pick which one to use based on the address of the operand + of the function. + + To generate the index of the lock we first shift by 3 bits to get + rid on the zero bits that result from 32 and 64 bit allignment of + data. We then mask off all but 5 bits and use those 5 bits as an + index into the table. + + Picking the lock this way insures that accesses to the same data at + the same time will go to the same lock. OTOH, accesses to different + data have only a 1/32 chance of hitting the same lock. That should + pretty much eliminate the chances of several atomic operations on + different data from waiting on the same "big lock". If it isn't + then the table of locks can be expanded to a new size so long as + the new size is a power of two. + + Contributed by Bob Pendleton, bob@pendleton.com +*/ + +#if !defined(HAVE_MSC_ATOMICS) && !defined(HAVE_GCC_ATOMICS) && !defined(__MACOSX__) && !defined(__SOLARIS__) && !defined(HAVE_WATCOM_ATOMICS) +#define EMULATE_CAS +#endif + +#ifdef EMULATE_CAS +static SDL_SpinLock locks[32]; + +static SDL_INLINE void enterLock(void *a) +{ + uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f); + + SDL_AtomicLock(&locks[index]); +} + +static SDL_INLINE void leaveLock(void *a) +{ + uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f); + + SDL_AtomicUnlock(&locks[index]); +} +#endif + +SDL_bool SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval) +{ +#ifdef HAVE_MSC_ATOMICS + SDL_COMPILE_TIME_ASSERT(atomic_cas, sizeof(long) == sizeof(a->value)); + return _InterlockedCompareExchange((long *)&a->value, (long)newval, (long)oldval) == (long)oldval; +#elif defined(HAVE_WATCOM_ATOMICS) + return (SDL_bool)_SDL_cmpxchg_watcom(&a->value, newval, oldval); +#elif defined(HAVE_GCC_ATOMICS) + return (SDL_bool) __sync_bool_compare_and_swap(&a->value, oldval, newval); +#elif defined(__MACOSX__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ + return (SDL_bool) OSAtomicCompareAndSwap32Barrier(oldval, newval, &a->value); +#elif defined(__SOLARIS__) + return (SDL_bool)((int)atomic_cas_uint((volatile uint_t *)&a->value, (uint_t)oldval, (uint_t)newval) == oldval); +#elif defined(EMULATE_CAS) + SDL_bool retval = SDL_FALSE; + + enterLock(a); + if (a->value == oldval) { + a->value = newval; + retval = SDL_TRUE; + } + leaveLock(a); + + return retval; +#else +#error Please define your platform. +#endif +} + +SDL_bool SDL_AtomicCASPtr(void **a, void *oldval, void *newval) +{ +#if defined(HAVE_MSC_ATOMICS) + return _InterlockedCompareExchangePointer(a, newval, oldval) == oldval; +#elif defined(HAVE_WATCOM_ATOMICS) + return (SDL_bool)_SDL_cmpxchg_watcom((int *)a, (long)newval, (long)oldval); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_bool_compare_and_swap(a, oldval, newval); +#elif defined(__MACOSX__) && defined(__LP64__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ + return (SDL_bool) OSAtomicCompareAndSwap64Barrier((int64_t)oldval, (int64_t)newval, (int64_t*) a); +#elif defined(__MACOSX__) && !defined(__LP64__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ + return (SDL_bool) OSAtomicCompareAndSwap32Barrier((int32_t)oldval, (int32_t)newval, (int32_t*) a); +#elif defined(__SOLARIS__) + return (SDL_bool)(atomic_cas_ptr(a, oldval, newval) == oldval); +#elif defined(EMULATE_CAS) + SDL_bool retval = SDL_FALSE; + + enterLock(a); + if (*a == oldval) { + *a = newval; + retval = SDL_TRUE; + } + leaveLock(a); + + return retval; +#else +#error Please define your platform. +#endif +} + +int SDL_AtomicSet(SDL_atomic_t *a, int v) +{ +#ifdef HAVE_MSC_ATOMICS + SDL_COMPILE_TIME_ASSERT(atomic_set, sizeof(long) == sizeof(a->value)); + return _InterlockedExchange((long *)&a->value, v); +#elif defined(HAVE_WATCOM_ATOMICS) + return _SDL_xchg_watcom(&a->value, v); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_lock_test_and_set(&a->value, v); +#elif defined(__SOLARIS__) + return (int)atomic_swap_uint((volatile uint_t *)&a->value, v); +#else + int value; + do { + value = a->value; + } while (!SDL_AtomicCAS(a, value, v)); + return value; +#endif +} + +void *SDL_AtomicSetPtr(void **a, void *v) +{ +#if defined(HAVE_MSC_ATOMICS) + return _InterlockedExchangePointer(a, v); +#elif defined(HAVE_WATCOM_ATOMICS) + return (void *)_SDL_xchg_watcom((int *)a, (long)v); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_lock_test_and_set(a, v); +#elif defined(__SOLARIS__) + return atomic_swap_ptr(a, v); +#else + void *value; + do { + value = *a; + } while (!SDL_AtomicCASPtr(a, value, v)); + return value; +#endif +} + +int SDL_AtomicAdd(SDL_atomic_t *a, int v) +{ +#ifdef HAVE_MSC_ATOMICS + SDL_COMPILE_TIME_ASSERT(atomic_add, sizeof(long) == sizeof(a->value)); + return _InterlockedExchangeAdd((long *)&a->value, v); +#elif defined(HAVE_WATCOM_ATOMICS) + return _SDL_xadd_watcom(&a->value, v); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_fetch_and_add(&a->value, v); +#elif defined(__SOLARIS__) + int pv = a->value; + membar_consumer(); + atomic_add_int((volatile uint_t *)&a->value, v); + return pv; +#else + int value; + do { + value = a->value; + } while (!SDL_AtomicCAS(a, value, (value + v))); + return value; +#endif +} + +int SDL_AtomicGet(SDL_atomic_t *a) +{ +#ifdef HAVE_ATOMIC_LOAD_N + return __atomic_load_n(&a->value, __ATOMIC_SEQ_CST); +#elif defined(HAVE_MSC_ATOMICS) + SDL_COMPILE_TIME_ASSERT(atomic_get, sizeof(long) == sizeof(a->value)); + return _InterlockedOr((long *)&a->value, 0); +#elif defined(HAVE_WATCOM_ATOMICS) + return _SDL_xadd_watcom(&a->value, 0); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_or_and_fetch(&a->value, 0); +#elif defined(__MACOSX__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ + return sizeof(a->value) == sizeof(uint32_t) ? OSAtomicOr32Barrier(0, (volatile uint32_t *)&a->value) : OSAtomicAdd64Barrier(0, (volatile int64_t *)&a->value); +#elif defined(__SOLARIS__) + return atomic_or_uint_nv((volatile uint_t *)&a->value, 0); +#else + int value; + do { + value = a->value; + } while (!SDL_AtomicCAS(a, value, value)); + return value; +#endif +} + +void *SDL_AtomicGetPtr(void **a) +{ +#ifdef HAVE_ATOMIC_LOAD_N + return __atomic_load_n(a, __ATOMIC_SEQ_CST); +#elif defined(HAVE_MSC_ATOMICS) + return _InterlockedCompareExchangePointer(a, NULL, NULL); +#elif defined(HAVE_GCC_ATOMICS) + return __sync_val_compare_and_swap(a, (void *)0, (void *)0); +#elif defined(__SOLARIS__) + return atomic_cas_ptr(a, (void *)0, (void *)0); +#else + void *value; + do { + value = *a; + } while (!SDL_AtomicCASPtr(a, value, value)); + return value; +#endif +} + +#ifdef SDL_MEMORY_BARRIER_USES_FUNCTION +#error This file should be built in arm mode so the mcr instruction is available for memory barriers +#endif + +void SDL_MemoryBarrierReleaseFunction(void) +{ + SDL_MemoryBarrierRelease(); +} + +void SDL_MemoryBarrierAcquireFunction(void) +{ + SDL_MemoryBarrierAcquire(); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/atomic/SDL_spinlock.c b/third_party/SDL2/src/atomic/SDL_spinlock.c new file mode 100644 index 00000000000..bdfa082d0d5 --- /dev/null +++ b/third_party/SDL2/src/atomic/SDL_spinlock.c @@ -0,0 +1,213 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +#if defined(__WIN32__) || defined(__WINRT__) || defined(__GDK__) +#include "../core/windows/SDL_windows.h" +#endif + +#include "SDL_atomic.h" +#include "SDL_mutex.h" +#include "SDL_timer.h" + +#if !defined(HAVE_GCC_ATOMICS) && defined(__SOLARIS__) +#include +#endif + +#if !defined(HAVE_GCC_ATOMICS) && defined(__RISCOS__) +#include +#endif + +#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) +#include +#endif + +#if defined(PS2) +#include +#endif + +#if !defined(HAVE_GCC_ATOMICS) && defined(__MACOSX__) +#include +#endif + +/* *INDENT-OFF* */ /* clang-format off */ +#if defined(__WATCOMC__) && defined(__386__) +SDL_COMPILE_TIME_ASSERT(locksize, 4==sizeof(SDL_SpinLock)); +extern __inline int _SDL_xchg_watcom(volatile int *a, int v); +#pragma aux _SDL_xchg_watcom = \ + "lock xchg [ecx], eax" \ + parm [ecx] [eax] \ + value [eax] \ + modify exact [eax]; +#endif /* __WATCOMC__ && __386__ */ +/* *INDENT-ON* */ /* clang-format on */ + +/* This function is where all the magic happens... */ +SDL_bool SDL_AtomicTryLock(SDL_SpinLock *lock) +{ +#ifdef SDL_ATOMIC_DISABLED + /* Terrible terrible damage */ + static SDL_mutex *_spinlock_mutex; + + if (!_spinlock_mutex) { + /* Race condition on first lock... */ + _spinlock_mutex = SDL_CreateMutex(); + } + SDL_LockMutex(_spinlock_mutex); + if (*lock == 0) { + *lock = 1; + SDL_UnlockMutex(_spinlock_mutex); + return SDL_TRUE; + } else { + SDL_UnlockMutex(_spinlock_mutex); + return SDL_FALSE; + } + +#elif defined(HAVE_GCC_ATOMICS) || defined(HAVE_GCC_SYNC_LOCK_TEST_AND_SET) + return __sync_lock_test_and_set(lock, 1) == 0; + +#elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) + return _InterlockedExchange_acq(lock, 1) == 0; + +#elif defined(_MSC_VER) + SDL_COMPILE_TIME_ASSERT(locksize, sizeof(*lock) == sizeof(long)); + return InterlockedExchange((long *)lock, 1) == 0; + +#elif defined(__WATCOMC__) && defined(__386__) + return _SDL_xchg_watcom(lock, 1) == 0; + +#elif defined(__GNUC__) && defined(__arm__) && \ + (defined(__ARM_ARCH_3__) || defined(__ARM_ARCH_3M__) || \ + defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__) || \ + defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5TE__) || \ + defined(__ARM_ARCH_5TEJ__)) + int result; + +#if defined(__RISCOS__) + if (__cpucap_have_rex()) { + __asm__ __volatile__( + "ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]" + : "=&r"(result) + : "r"(1), "r"(lock) + : "cc", "memory"); + return result == 0; + } +#endif + + __asm__ __volatile__( + "swp %0, %1, [%2]\n" + : "=&r,&r"(result) + : "r,0"(1), "r,r"(lock) + : "memory"); + return result == 0; + +#elif defined(__GNUC__) && defined(__arm__) + int result; + __asm__ __volatile__( + "ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]" + : "=&r"(result) + : "r"(1), "r"(lock) + : "cc", "memory"); + return result == 0; + +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) + int result; + __asm__ __volatile__( + "lock ; xchgl %0, (%1)\n" + : "=r"(result) + : "r"(lock), "0"(1) + : "cc", "memory"); + return result == 0; + +#elif defined(__MACOSX__) || defined(__IPHONEOS__) + /* Maybe used for PowerPC, but the Intel asm or gcc atomics are favored. */ + return OSAtomicCompareAndSwap32Barrier(0, 1, lock); + +#elif defined(__SOLARIS__) && defined(_LP64) + /* Used for Solaris with non-gcc compilers. */ + return (SDL_bool)((int)atomic_cas_64((volatile uint64_t *)lock, 0, 1) == 0); + +#elif defined(__SOLARIS__) && !defined(_LP64) + /* Used for Solaris with non-gcc compilers. */ + return (SDL_bool)((int)atomic_cas_32((volatile uint32_t *)lock, 0, 1) == 0); +#elif defined(PS2) + uint32_t oldintr; + SDL_bool res = SDL_FALSE; + // disable interuption + oldintr = DIntr(); + + if (*lock == 0) { + *lock = 1; + res = SDL_TRUE; + } + // enable interuption + if (oldintr) { + EIntr(); + } + return res; +#else +#error Please implement for your platform. + return SDL_FALSE; +#endif +} + +void SDL_AtomicLock(SDL_SpinLock *lock) +{ + int iterations = 0; + /* FIXME: Should we have an eventual timeout? */ + while (!SDL_AtomicTryLock(lock)) { + if (iterations < 32) { + iterations++; + SDL_CPUPauseInstruction(); + } else { + /* !!! FIXME: this doesn't definitely give up the current timeslice, it does different things on various platforms. */ + SDL_Delay(0); + } + } +} + +void SDL_AtomicUnlock(SDL_SpinLock *lock) +{ +#if defined(HAVE_GCC_ATOMICS) || defined(HAVE_GCC_SYNC_LOCK_TEST_AND_SET) + __sync_lock_release(lock); + +#elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) + _InterlockedExchange_rel(lock, 0); + +#elif defined(_MSC_VER) + _ReadWriteBarrier(); + *lock = 0; + +#elif defined(__WATCOMC__) && defined(__386__) + SDL_CompilerBarrier(); + *lock = 0; + +#elif defined(__SOLARIS__) + /* Used for Solaris when not using gcc. */ + *lock = 0; + membar_producer(); + +#else + *lock = 0; +#endif +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_audio.c b/third_party/SDL2/src/audio/SDL_audio.c new file mode 100644 index 00000000000..1ab847aa490 --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_audio.c @@ -0,0 +1,1797 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +/* Allow access to a raw mixing buffer */ + +#include "SDL.h" +#include "SDL_audio.h" +#include "SDL_audio_c.h" +#include "SDL_sysaudio.h" +#include "../thread/SDL_systhread.h" +#include "../SDL_utils_c.h" + +#define _THIS SDL_AudioDevice *_this + +typedef struct AudioThreadStartupData +{ + SDL_AudioDevice *device; + SDL_sem *startup_semaphore; +} AudioThreadStartupData; + +static SDL_AudioDriver current_audio; +static SDL_AudioDevice *open_devices[16]; + +/* Available audio drivers */ +static const AudioBootStrap *const bootstrap[] = { +#ifdef SDL_AUDIO_DRIVER_PULSEAUDIO + &PULSEAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_ALSA + &ALSA_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_SNDIO + &SNDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_NETBSD + &NETBSDAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_QSA + &QSAAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_SUNAUDIO + &SUNAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_ARTS + &ARTS_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_ESD + &ESD_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_NACL + &NACLAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_NAS + &NAS_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_WASAPI + &WASAPI_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_DSOUND + &DSOUND_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_WINMM + &WINMM_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_PAUDIO + &PAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_HAIKU + &HAIKUAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_COREAUDIO + &COREAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_FUSIONSOUND + &FUSIONSOUND_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_OPENSLES + &openslES_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_AAUDIO + &aaudio_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_ANDROID + &ANDROIDAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_PS2 + &PS2AUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_PSP + &PSPAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_VITA + &VITAAUD_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_N3DS + &N3DSAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_EMSCRIPTEN + &EMSCRIPTENAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_JACK + &JACK_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_PIPEWIRE + &PIPEWIRE_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_OSS + &DSP_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_OS2 + &OS2AUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_DISK + &DISKAUDIO_bootstrap, +#endif +#ifdef SDL_AUDIO_DRIVER_DUMMY + &DUMMYAUDIO_bootstrap, +#endif + NULL +}; + +#ifdef HAVE_LIBSAMPLERATE_H +#ifdef SDL_LIBSAMPLERATE_DYNAMIC +static void *SRC_lib = NULL; +#endif +SDL_bool SRC_available = SDL_FALSE; +int SRC_converter = 0; +SRC_STATE *(*SRC_src_new)(int converter_type, int channels, int *error) = NULL; +int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data) = NULL; +int (*SRC_src_reset)(SRC_STATE *state) = NULL; +SRC_STATE *(*SRC_src_delete)(SRC_STATE *state) = NULL; +const char *(*SRC_src_strerror)(int error) = NULL; +int (*SRC_src_simple)(SRC_DATA *data, int converter_type, int channels) = NULL; + +static SDL_bool LoadLibSampleRate(void) +{ + const char *hint = SDL_GetHint(SDL_HINT_AUDIO_RESAMPLING_MODE); + + SRC_available = SDL_FALSE; + SRC_converter = 0; + + if (!hint || *hint == '0' || SDL_strcasecmp(hint, "default") == 0) { + return SDL_FALSE; /* don't load anything. */ + } else if (*hint == '1' || SDL_strcasecmp(hint, "fast") == 0) { + SRC_converter = SRC_SINC_FASTEST; + } else if (*hint == '2' || SDL_strcasecmp(hint, "medium") == 0) { + SRC_converter = SRC_SINC_MEDIUM_QUALITY; + } else if (*hint == '3' || SDL_strcasecmp(hint, "best") == 0) { + SRC_converter = SRC_SINC_BEST_QUALITY; + } else if (*hint == '4' || SDL_strcasecmp(hint, "linear") == 0) { + SRC_converter = SRC_LINEAR; + } else { + return SDL_FALSE; /* treat it like "default", don't load anything. */ + } + +#ifdef SDL_LIBSAMPLERATE_DYNAMIC + SDL_assert(SRC_lib == NULL); + SRC_lib = SDL_LoadObject(SDL_LIBSAMPLERATE_DYNAMIC); + if (!SRC_lib) { + SDL_ClearError(); + return SDL_FALSE; + } + + /* *INDENT-OFF* */ /* clang-format off */ + SRC_src_new = (SRC_STATE* (*)(int converter_type, int channels, int *error))SDL_LoadFunction(SRC_lib, "src_new"); + SRC_src_process = (int (*)(SRC_STATE *state, SRC_DATA *data))SDL_LoadFunction(SRC_lib, "src_process"); + SRC_src_reset = (int(*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_reset"); + SRC_src_delete = (SRC_STATE* (*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_delete"); + SRC_src_strerror = (const char* (*)(int error))SDL_LoadFunction(SRC_lib, "src_strerror"); + SRC_src_simple = (int(*)(SRC_DATA *data, int converter_type, int channels))SDL_LoadFunction(SRC_lib, "src_simple"); +/* *INDENT-ON* */ /* clang-format on */ + + if (!SRC_src_new || !SRC_src_process || !SRC_src_reset || !SRC_src_delete || !SRC_src_strerror || !SRC_src_simple) { + SDL_UnloadObject(SRC_lib); + SRC_lib = NULL; + return SDL_FALSE; + } +#else + SRC_src_new = src_new; + SRC_src_process = src_process; + SRC_src_reset = src_reset; + SRC_src_delete = src_delete; + SRC_src_strerror = src_strerror; + SRC_src_simple = src_simple; +#endif + + SRC_available = SDL_TRUE; + return SDL_TRUE; +} + +static void UnloadLibSampleRate(void) +{ +#ifdef SDL_LIBSAMPLERATE_DYNAMIC + if (SRC_lib != NULL) { + SDL_UnloadObject(SRC_lib); + } + SRC_lib = NULL; +#endif + + SRC_available = SDL_FALSE; + SRC_src_new = NULL; + SRC_src_process = NULL; + SRC_src_reset = NULL; + SRC_src_delete = NULL; + SRC_src_strerror = NULL; +} +#endif + +static SDL_AudioDevice *get_audio_device(SDL_AudioDeviceID id) +{ + id--; + if ((id >= SDL_arraysize(open_devices)) || (open_devices[id] == NULL)) { + SDL_SetError("Invalid audio device ID"); + return NULL; + } + + return open_devices[id]; +} + +/* stubs for audio drivers that don't need a specific entry point... */ +static void SDL_AudioDetectDevices_Default(void) +{ + /* you have to write your own implementation if these assertions fail. */ + SDL_assert(current_audio.impl.OnlyHasDefaultOutputDevice); + SDL_assert(current_audio.impl.OnlyHasDefaultCaptureDevice || !current_audio.impl.HasCaptureSupport); + + SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *)((size_t)0x1)); + if (current_audio.impl.HasCaptureSupport) { + SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *)((size_t)0x2)); + } +} + +static void SDL_AudioThreadInit_Default(_THIS) +{ /* no-op. */ +} + +static void SDL_AudioThreadDeinit_Default(_THIS) +{ /* no-op. */ +} + +static void SDL_AudioWaitDevice_Default(_THIS) +{ /* no-op. */ +} + +static void SDL_AudioPlayDevice_Default(_THIS) +{ /* no-op. */ +} + +static Uint8 *SDL_AudioGetDeviceBuf_Default(_THIS) +{ + return NULL; +} + +static int SDL_AudioCaptureFromDevice_Default(_THIS, void *buffer, int buflen) +{ + return -1; /* just fail immediately. */ +} + +static void SDL_AudioFlushCapture_Default(_THIS) +{ /* no-op. */ +} + +static void SDL_AudioCloseDevice_Default(_THIS) +{ /* no-op. */ +} + +static void SDL_AudioDeinitialize_Default(void) +{ /* no-op. */ +} + +static void SDL_AudioFreeDeviceHandle_Default(void *handle) +{ /* no-op. */ +} + +static int SDL_AudioOpenDevice_Default(_THIS, const char *devname) +{ + return SDL_Unsupported(); +} + +static SDL_INLINE SDL_bool is_in_audio_device_thread(SDL_AudioDevice *device) +{ + /* The device thread locks the same mutex, but not through the public API. + This check is in case the application, in the audio callback, + tries to lock the thread that we've already locked from the + device thread...just in case we only have non-recursive mutexes. */ + if (device->thread && (SDL_ThreadID() == device->threadid)) { + return SDL_TRUE; + } + + return SDL_FALSE; +} + +static void SDL_AudioLockDevice_Default(SDL_AudioDevice *device) SDL_NO_THREAD_SAFETY_ANALYSIS /* clang assumes recursive locks */ +{ + if (!is_in_audio_device_thread(device)) { + SDL_LockMutex(device->mixer_lock); + } +} + +static void SDL_AudioUnlockDevice_Default(SDL_AudioDevice *device) SDL_NO_THREAD_SAFETY_ANALYSIS /* clang assumes recursive locks */ +{ + if (!is_in_audio_device_thread(device)) { + SDL_UnlockMutex(device->mixer_lock); + } +} + +static void finish_audio_entry_points_init(void) +{ + /* + * Fill in stub functions for unused driver entry points. This lets us + * blindly call them without having to check for validity first. + */ + +#define FILL_STUB(x) \ + if (current_audio.impl.x == NULL) { \ + current_audio.impl.x = SDL_Audio##x##_Default; \ + } + FILL_STUB(DetectDevices); + FILL_STUB(OpenDevice); + FILL_STUB(ThreadInit); + FILL_STUB(ThreadDeinit); + FILL_STUB(WaitDevice); + FILL_STUB(PlayDevice); + FILL_STUB(GetDeviceBuf); + FILL_STUB(CaptureFromDevice); + FILL_STUB(FlushCapture); + FILL_STUB(CloseDevice); + FILL_STUB(LockDevice); + FILL_STUB(UnlockDevice); + FILL_STUB(FreeDeviceHandle); + FILL_STUB(Deinitialize); +#undef FILL_STUB +} + +/* device hotplug support... */ + +static int add_audio_device(const char *name, SDL_AudioSpec *spec, void *handle, SDL_AudioDeviceItem **devices, int *devCount) +{ + int retval = -1; + SDL_AudioDeviceItem *item; + const SDL_AudioDeviceItem *i; + int dupenum = 0; + + SDL_assert(handle != NULL); /* we reserve NULL, audio backends can't use it. */ + SDL_assert(name != NULL); + + item = (SDL_AudioDeviceItem *)SDL_malloc(sizeof(SDL_AudioDeviceItem)); + if (!item) { + return SDL_OutOfMemory(); + } + + item->original_name = SDL_strdup(name); + if (!item->original_name) { + SDL_free(item); + return SDL_OutOfMemory(); + } + + item->dupenum = 0; + item->name = item->original_name; + if (spec != NULL) { + SDL_copyp(&item->spec, spec); + } else { + SDL_zero(item->spec); + } + item->handle = handle; + + SDL_LockMutex(current_audio.detectionLock); + + for (i = *devices; i != NULL; i = i->next) { + if (SDL_strcmp(name, i->original_name) == 0) { + dupenum = i->dupenum + 1; + break; /* stop at the highest-numbered dupe. */ + } + } + + if (dupenum) { + const size_t len = SDL_strlen(name) + 16; + char *replacement = (char *)SDL_malloc(len); + if (!replacement) { + SDL_UnlockMutex(current_audio.detectionLock); + SDL_free(item->original_name); + SDL_free(item); + return SDL_OutOfMemory(); + } + + (void)SDL_snprintf(replacement, len, "%s (%d)", name, dupenum + 1); + item->dupenum = dupenum; + item->name = replacement; + } + + item->next = *devices; + *devices = item; + retval = (*devCount)++; /* !!! FIXME: this should be an atomic increment */ + + SDL_UnlockMutex(current_audio.detectionLock); + + return retval; +} + +static SDL_INLINE int add_capture_device(const char *name, SDL_AudioSpec *spec, void *handle) +{ + SDL_assert(current_audio.impl.HasCaptureSupport); + return add_audio_device(name, spec, handle, ¤t_audio.inputDevices, ¤t_audio.inputDeviceCount); +} + +static SDL_INLINE int add_output_device(const char *name, SDL_AudioSpec *spec, void *handle) +{ + return add_audio_device(name, spec, handle, ¤t_audio.outputDevices, ¤t_audio.outputDeviceCount); +} + +static void free_device_list(SDL_AudioDeviceItem **devices, int *devCount) +{ + SDL_AudioDeviceItem *item, *next; + for (item = *devices; item != NULL; item = next) { + next = item->next; + if (item->handle != NULL) { + current_audio.impl.FreeDeviceHandle(item->handle); + } + /* these two pointers are the same if not a duplicate devname */ + if (item->name != item->original_name) { + SDL_free(item->name); + } + SDL_free(item->original_name); + SDL_free(item); + } + *devices = NULL; + *devCount = 0; +} + +/* The audio backends call this when a new device is plugged in. */ +void SDL_AddAudioDevice(const SDL_bool iscapture, const char *name, SDL_AudioSpec *spec, void *handle) +{ + const int device_index = iscapture ? add_capture_device(name, spec, handle) : add_output_device(name, spec, handle); + if (device_index != -1) { + /* Post the event, if desired */ + if (SDL_GetEventState(SDL_AUDIODEVICEADDED) == SDL_ENABLE) { + SDL_Event event; + SDL_zero(event); + event.adevice.type = SDL_AUDIODEVICEADDED; + event.adevice.which = device_index; + event.adevice.iscapture = iscapture; + SDL_PushEvent(&event); + } + } +} + +/* The audio backends call this when a currently-opened device is lost. */ +void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device) +{ + SDL_assert(get_audio_device(device->id) == device); + + if (!SDL_AtomicGet(&device->enabled)) { + return; /* don't report disconnects more than once. */ + } + + if (SDL_AtomicGet(&device->shutdown)) { + return; /* don't report disconnect if we're trying to close device. */ + } + + /* Ends the audio callback and mark the device as STOPPED, but the + app still needs to close the device to free resources. */ + current_audio.impl.LockDevice(device); + SDL_AtomicSet(&device->enabled, 0); + current_audio.impl.UnlockDevice(device); + + /* Post the event, if desired */ + if (SDL_GetEventState(SDL_AUDIODEVICEREMOVED) == SDL_ENABLE) { + SDL_Event event; + SDL_zero(event); + event.adevice.type = SDL_AUDIODEVICEREMOVED; + event.adevice.which = device->id; + event.adevice.iscapture = device->iscapture ? 1 : 0; + SDL_PushEvent(&event); + } +} + +static void mark_device_removed(void *handle, SDL_AudioDeviceItem *devices, SDL_bool *removedFlag) +{ + SDL_AudioDeviceItem *item; + SDL_assert(handle != NULL); + for (item = devices; item != NULL; item = item->next) { + if (item->handle == handle) { + item->handle = NULL; + *removedFlag = SDL_TRUE; + return; + } + } +} + +/* The audio backends call this when a device is removed from the system. */ +void SDL_RemoveAudioDevice(const SDL_bool iscapture, void *handle) +{ + int device_index; + SDL_AudioDevice *device = NULL; + SDL_bool device_was_opened = SDL_FALSE; + + SDL_LockMutex(current_audio.detectionLock); + if (iscapture) { + mark_device_removed(handle, current_audio.inputDevices, ¤t_audio.captureDevicesRemoved); + } else { + mark_device_removed(handle, current_audio.outputDevices, ¤t_audio.outputDevicesRemoved); + } + for (device_index = 0; device_index < SDL_arraysize(open_devices); device_index++) { + device = open_devices[device_index]; + if (device != NULL && device->handle == handle) { + device_was_opened = SDL_TRUE; + SDL_OpenedAudioDeviceDisconnected(device); + break; + } + } + + /* Devices that aren't opened, as of 2.24.0, will post an + SDL_AUDIODEVICEREMOVED event with the `which` field set to zero. + Apps can use this to decide if they need to refresh a list of + available devices instead of closing an opened one. + Note that opened devices will send the non-zero event in + SDL_OpenedAudioDeviceDisconnected(). */ + if (!device_was_opened) { + if (SDL_GetEventState(SDL_AUDIODEVICEREMOVED) == SDL_ENABLE) { + SDL_Event event; + SDL_zero(event); + event.adevice.type = SDL_AUDIODEVICEREMOVED; + event.adevice.which = 0; + event.adevice.iscapture = iscapture ? 1 : 0; + SDL_PushEvent(&event); + } + } + + SDL_UnlockMutex(current_audio.detectionLock); + + current_audio.impl.FreeDeviceHandle(handle); +} + +/* buffer queueing support... */ + +static void SDLCALL SDL_BufferQueueDrainCallback(void *userdata, Uint8 *stream, int len) +{ + /* this function always holds the mixer lock before being called. */ + SDL_AudioDevice *device = (SDL_AudioDevice *)userdata; + size_t dequeued; + + SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */ + SDL_assert(!device->iscapture); /* this shouldn't ever happen, right?! */ + SDL_assert(len >= 0); /* this shouldn't ever happen, right?! */ + + dequeued = SDL_ReadFromDataQueue(device->buffer_queue, stream, len); + stream += dequeued; + len -= (int)dequeued; + + if (len > 0) { /* fill any remaining space in the stream with silence. */ + SDL_assert(SDL_CountDataQueue(device->buffer_queue) == 0); + SDL_memset(stream, device->callbackspec.silence, len); + } +} + +static void SDLCALL SDL_BufferQueueFillCallback(void *userdata, Uint8 *stream, int len) +{ + /* this function always holds the mixer lock before being called. */ + SDL_AudioDevice *device = (SDL_AudioDevice *)userdata; + + SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */ + SDL_assert(device->iscapture); /* this shouldn't ever happen, right?! */ + SDL_assert(len >= 0); /* this shouldn't ever happen, right?! */ + + /* note that if this needs to allocate more space and run out of memory, + we have no choice but to quietly drop the data and hope it works out + later, but you probably have bigger problems in this case anyhow. */ + SDL_WriteToDataQueue(device->buffer_queue, stream, len); +} + +int SDL_QueueAudio(SDL_AudioDeviceID devid, const void *data, Uint32 len) +{ + SDL_AudioDevice *device = get_audio_device(devid); + int rc = 0; + + if (!device) { + return -1; /* get_audio_device() will have set the error state */ + } else if (device->iscapture) { + return SDL_SetError("This is a capture device, queueing not allowed"); + } else if (device->callbackspec.callback != SDL_BufferQueueDrainCallback) { + return SDL_SetError("Audio device has a callback, queueing not allowed"); + } + + if (len > 0) { + current_audio.impl.LockDevice(device); + rc = SDL_WriteToDataQueue(device->buffer_queue, data, len); + current_audio.impl.UnlockDevice(device); + } + + return rc; +} + +Uint32 SDL_DequeueAudio(SDL_AudioDeviceID devid, void *data, Uint32 len) +{ + SDL_AudioDevice *device = get_audio_device(devid); + Uint32 rc; + + if ((len == 0) || /* nothing to do? */ + (!device) || /* called with bogus device id */ + (!device->iscapture) || /* playback devices can't dequeue */ + (device->callbackspec.callback != SDL_BufferQueueFillCallback)) { /* not set for queueing */ + return 0; /* just report zero bytes dequeued. */ + } + + current_audio.impl.LockDevice(device); + rc = (Uint32)SDL_ReadFromDataQueue(device->buffer_queue, data, len); + current_audio.impl.UnlockDevice(device); + return rc; +} + +Uint32 SDL_GetQueuedAudioSize(SDL_AudioDeviceID devid) +{ + Uint32 retval = 0; + SDL_AudioDevice *device = get_audio_device(devid); + + if (!device) { + return 0; + } + + /* Nothing to do unless we're set up for queueing. */ + if (device->callbackspec.callback == SDL_BufferQueueDrainCallback || + device->callbackspec.callback == SDL_BufferQueueFillCallback) { + current_audio.impl.LockDevice(device); + retval = (Uint32)SDL_CountDataQueue(device->buffer_queue); + current_audio.impl.UnlockDevice(device); + } + + return retval; +} + +void SDL_ClearQueuedAudio(SDL_AudioDeviceID devid) +{ + SDL_AudioDevice *device = get_audio_device(devid); + + if (!device) { + return; /* nothing to do. */ + } + + /* Blank out the device and release the mutex. Free it afterwards. */ + current_audio.impl.LockDevice(device); + + /* Keep up to two packets in the pool to reduce future memory allocation pressure. */ + SDL_ClearDataQueue(device->buffer_queue, SDL_AUDIOBUFFERQUEUE_PACKETLEN * 2); + + current_audio.impl.UnlockDevice(device); +} + +#ifdef SDL_AUDIO_DRIVER_ANDROID +extern void Android_JNI_AudioSetThreadPriority(int, int); +#endif + +/* The general mixing thread function */ +static int SDLCALL SDL_RunAudio(void *userdata) +{ + const AudioThreadStartupData *startup_data = (const AudioThreadStartupData *) userdata; + SDL_AudioDevice *device = startup_data->device; + void *udata = device->callbackspec.userdata; + SDL_AudioCallback callback = device->callbackspec.callback; + int data_len = 0; + Uint8 *data; + Uint8 *device_buf_keepsafe = NULL; + + SDL_assert(!device->iscapture); + +#ifdef SDL_AUDIO_DRIVER_ANDROID + { + /* Set thread priority to THREAD_PRIORITY_AUDIO */ + Android_JNI_AudioSetThreadPriority(device->iscapture, device->id); + } +#else + /* The audio mixing is always a high priority thread */ + SDL_SetThreadPriority(SDL_THREAD_PRIORITY_TIME_CRITICAL); +#endif + + /* Perform any thread setup */ + device->threadid = SDL_ThreadID(); + + SDL_SemPost(startup_data->startup_semaphore); /* SDL_OpenAudioDevice may now continue. */ + + current_audio.impl.ThreadInit(device); + + /* Loop, filling the audio buffers */ + while (!SDL_AtomicGet(&device->shutdown)) { + /* Fill the current buffer with sound */ + if (!device->stream && SDL_AtomicGet(&device->enabled)) { + data = current_audio.impl.GetDeviceBuf(device); + + if (device->stream && SDL_AtomicGet(&device->enabled)) { + /* Oops. Audio device reset and now we suddenly use a stream, */ + /* so save this devicebuf for later, to prevent de-sync */ + if (data != NULL) { + device_buf_keepsafe = data; + } + data = NULL; + } + } else { + /* if the device isn't enabled, we still write to the + work_buffer, so the app's callback will fire with + a regular frequency, in case they depend on that + for timing or progress. They can use hotplug + now to know if the device failed. + Streaming playback uses work_buffer, too. */ + data = NULL; + } + + if (data == NULL) { + data = device->work_buffer; + } + + data_len = device->callbackspec.size; + + /* !!! FIXME: this should be LockDevice. */ + SDL_LockMutex(device->mixer_lock); + if (SDL_AtomicGet(&device->paused)) { + SDL_memset(data, device->callbackspec.silence, data_len); + } else { + callback(udata, data, data_len); + } + SDL_UnlockMutex(device->mixer_lock); + + if (device->stream) { + /* Stream available audio to device, converting/resampling. */ + /* if this fails...oh well. We'll play silence here. */ + SDL_AudioStreamPut(device->stream, data, data_len); + + while (SDL_AudioStreamAvailable(device->stream) >= ((int)device->spec.size)) { + int got; + if (SDL_AtomicGet(&device->enabled)) { + /* if device reset occured - a switch from direct output to streaming */ + /* use the already aquired device buffer */ + if (device_buf_keepsafe) { + data = device_buf_keepsafe; + device_buf_keepsafe = NULL; + } else { + /* else - normal flow, just acquire the device buffer here */ + data = current_audio.impl.GetDeviceBuf(device); + } + } else { + data = NULL; + } + got = SDL_AudioStreamGet(device->stream, data ? data : device->work_buffer, device->spec.size); + SDL_assert((got <= 0) || (got == device->spec.size)); + + if (data == NULL) { /* device is having issues... */ + const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq); + SDL_Delay(delay); /* wait for as long as this buffer would have played. Maybe device recovers later? */ + } else { + if (got != device->spec.size) { + SDL_memset(data, device->spec.silence, device->spec.size); + } + current_audio.impl.PlayDevice(device); + current_audio.impl.WaitDevice(device); + } + } + + /* it seems resampling was not fast enough, device_buf_keepsafe was not released yet, so play silence here */ + if (device_buf_keepsafe) { + SDL_memset(device_buf_keepsafe, device->spec.silence, device->spec.size); + current_audio.impl.PlayDevice(device); + current_audio.impl.WaitDevice(device); + device_buf_keepsafe = NULL; + } + } else if (data == device->work_buffer) { + /* nothing to do; pause like we queued a buffer to play. */ + const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq); + SDL_Delay(delay); + } else { /* writing directly to the device. */ + /* queue this buffer and wait for it to finish playing. */ + current_audio.impl.PlayDevice(device); + current_audio.impl.WaitDevice(device); + } + } + + /* Wait for the audio to drain. */ + SDL_Delay(((device->spec.samples * 1000) / device->spec.freq) * 2); + + current_audio.impl.ThreadDeinit(device); + + return 0; +} + +/* !!! FIXME: this needs to deal with device spec changes. */ +/* The general capture thread function */ +static int SDLCALL SDL_CaptureAudio(void *userdata) +{ + const AudioThreadStartupData *startup_data = (const AudioThreadStartupData *) userdata; + SDL_AudioDevice *device = startup_data->device; + const int silence = (int)device->spec.silence; + const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq); + const int data_len = device->spec.size; + Uint8 *data; + void *udata = device->callbackspec.userdata; + SDL_AudioCallback callback = device->callbackspec.callback; + + SDL_assert(device->iscapture); + +#ifdef SDL_AUDIO_DRIVER_ANDROID + { + /* Set thread priority to THREAD_PRIORITY_AUDIO */ + Android_JNI_AudioSetThreadPriority(device->iscapture, device->id); + } +#else + /* The audio mixing is always a high priority thread */ + SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH); +#endif + + /* Perform any thread setup */ + device->threadid = SDL_ThreadID(); + + SDL_SemPost(startup_data->startup_semaphore); /* SDL_OpenAudioDevice may now continue. */ + + current_audio.impl.ThreadInit(device); + + /* Loop, filling the audio buffers */ + while (!SDL_AtomicGet(&device->shutdown)) { + int still_need; + Uint8 *ptr; + + if (SDL_AtomicGet(&device->paused)) { + SDL_Delay(delay); /* just so we don't cook the CPU. */ + if (device->stream) { + SDL_AudioStreamClear(device->stream); + } + current_audio.impl.FlushCapture(device); /* dump anything pending. */ + continue; + } + + /* Fill the current buffer with sound */ + still_need = data_len; + + /* Use the work_buffer to hold data read from the device. */ + data = device->work_buffer; + SDL_assert(data != NULL); + + ptr = data; + + /* We still read from the device when "paused" to keep the state sane, + and block when there isn't data so this thread isn't eating CPU. + But we don't process it further or call the app's callback. */ + + if (!SDL_AtomicGet(&device->enabled)) { + SDL_Delay(delay); /* try to keep callback firing at normal pace. */ + } else { + while (still_need > 0) { + const int rc = current_audio.impl.CaptureFromDevice(device, ptr, still_need); + SDL_assert(rc <= still_need); /* device should not overflow buffer. :) */ + if (rc > 0) { + still_need -= rc; + ptr += rc; + } else { /* uhoh, device failed for some reason! */ + SDL_OpenedAudioDeviceDisconnected(device); + break; + } + } + } + + if (still_need > 0) { + /* Keep any data we already read, silence the rest. */ + SDL_memset(ptr, silence, still_need); + } + + if (device->stream) { + /* if this fails...oh well. */ + SDL_AudioStreamPut(device->stream, data, data_len); + + while (SDL_AudioStreamAvailable(device->stream) >= ((int)device->callbackspec.size)) { + const int got = SDL_AudioStreamGet(device->stream, device->work_buffer, device->callbackspec.size); + SDL_assert((got < 0) || (got == device->callbackspec.size)); + if (got != device->callbackspec.size) { + SDL_memset(device->work_buffer, device->spec.silence, device->callbackspec.size); + } + + /* !!! FIXME: this should be LockDevice. */ + SDL_LockMutex(device->mixer_lock); + if (!SDL_AtomicGet(&device->paused)) { + callback(udata, device->work_buffer, device->callbackspec.size); + } + SDL_UnlockMutex(device->mixer_lock); + } + } else { /* feeding user callback directly without streaming. */ + /* !!! FIXME: this should be LockDevice. */ + SDL_LockMutex(device->mixer_lock); + if (!SDL_AtomicGet(&device->paused)) { + callback(udata, data, device->callbackspec.size); + } + SDL_UnlockMutex(device->mixer_lock); + } + } + + current_audio.impl.FlushCapture(device); + + current_audio.impl.ThreadDeinit(device); + + return 0; +} + +static SDL_AudioFormat SDL_ParseAudioFormat(const char *string) +{ +#define CHECK_FMT_STRING(x) \ + if (SDL_strcmp(string, #x) == 0) \ + return AUDIO_##x + CHECK_FMT_STRING(U8); + CHECK_FMT_STRING(S8); + CHECK_FMT_STRING(U16LSB); + CHECK_FMT_STRING(S16LSB); + CHECK_FMT_STRING(U16MSB); + CHECK_FMT_STRING(S16MSB); + CHECK_FMT_STRING(U16SYS); + CHECK_FMT_STRING(S16SYS); + CHECK_FMT_STRING(U16); + CHECK_FMT_STRING(S16); + CHECK_FMT_STRING(S32LSB); + CHECK_FMT_STRING(S32MSB); + CHECK_FMT_STRING(S32SYS); + CHECK_FMT_STRING(S32); + CHECK_FMT_STRING(F32LSB); + CHECK_FMT_STRING(F32MSB); + CHECK_FMT_STRING(F32SYS); + CHECK_FMT_STRING(F32); +#undef CHECK_FMT_STRING + return 0; +} + +int SDL_GetNumAudioDrivers(void) +{ + return SDL_arraysize(bootstrap) - 1; +} + +const char *SDL_GetAudioDriver(int index) +{ + if (index >= 0 && index < SDL_GetNumAudioDrivers()) { + return bootstrap[index]->name; + } + return NULL; +} + +int SDL_AudioInit(const char *driver_name) +{ + int i; + SDL_bool initialized = SDL_FALSE, tried_to_init = SDL_FALSE; + + if (SDL_GetCurrentAudioDriver()) { + SDL_AudioQuit(); /* shutdown driver if already running. */ + } + + SDL_zeroa(open_devices); + + /* Select the proper audio driver */ + if (driver_name == NULL) { + driver_name = SDL_GetHint(SDL_HINT_AUDIODRIVER); + } + + if (driver_name != NULL && *driver_name != 0) { + const char *driver_attempt = driver_name; + while (driver_attempt != NULL && *driver_attempt != 0 && !initialized) { + const char *driver_attempt_end = SDL_strchr(driver_attempt, ','); + size_t driver_attempt_len = (driver_attempt_end != NULL) ? (driver_attempt_end - driver_attempt) + : SDL_strlen(driver_attempt); +#ifdef SDL_AUDIO_DRIVER_DSOUND + /* SDL 1.2 uses the name "dsound", so we'll support both. */ + if (driver_attempt_len == SDL_strlen("dsound") && + (SDL_strncasecmp(driver_attempt, "dsound", driver_attempt_len) == 0)) { + driver_attempt = "directsound"; + driver_attempt_len = SDL_strlen("directsound"); + } +#endif + +#ifdef SDL_AUDIO_DRIVER_PULSEAUDIO + /* SDL 1.2 uses the name "pulse", so we'll support both. */ + if (driver_attempt_len == SDL_strlen("pulse") && + (SDL_strncasecmp(driver_attempt, "pulse", driver_attempt_len) == 0)) { + driver_attempt = "pulseaudio"; + driver_attempt_len = SDL_strlen("pulseaudio"); + } +#endif + + for (i = 0; bootstrap[i]; ++i) { + if ((driver_attempt_len == SDL_strlen(bootstrap[i]->name)) && + (SDL_strncasecmp(bootstrap[i]->name, driver_attempt, driver_attempt_len) == 0)) { + tried_to_init = SDL_TRUE; + SDL_zero(current_audio); + current_audio.name = bootstrap[i]->name; + current_audio.desc = bootstrap[i]->desc; + initialized = bootstrap[i]->init(¤t_audio.impl); + break; + } + } + + driver_attempt = (driver_attempt_end) ? (driver_attempt_end + 1) : NULL; + } + } else { + for (i = 0; (!initialized) && (bootstrap[i]); ++i) { + if (bootstrap[i]->demand_only) { + continue; + } + + tried_to_init = SDL_TRUE; + SDL_zero(current_audio); + current_audio.name = bootstrap[i]->name; + current_audio.desc = bootstrap[i]->desc; + initialized = bootstrap[i]->init(¤t_audio.impl); + } + } + + if (!initialized) { + /* specific drivers will set the error message if they fail... */ + if (!tried_to_init) { + if (driver_name) { + SDL_SetError("Audio target '%s' not available", driver_name); + } else { + SDL_SetError("No available audio device"); + } + } + + SDL_zero(current_audio); + return -1; /* No driver was available, so fail. */ + } + + current_audio.detectionLock = SDL_CreateMutex(); + + finish_audio_entry_points_init(); + + /* Make sure we have a list of devices available at startup. */ + current_audio.impl.DetectDevices(); + +#ifdef HAVE_LIBSAMPLERATE_H + LoadLibSampleRate(); +#endif + + return 0; +} + +/* + * Get the current audio driver name + */ +const char *SDL_GetCurrentAudioDriver(void) +{ + return current_audio.name; +} + +/* Clean out devices that we've removed but had to keep around for stability. */ +static void clean_out_device_list(SDL_AudioDeviceItem **devices, int *devCount, SDL_bool *removedFlag) +{ + SDL_AudioDeviceItem *item = *devices; + SDL_AudioDeviceItem *prev = NULL; + int total = 0; + + while (item) { + SDL_AudioDeviceItem *next = item->next; + if (item->handle != NULL) { + total++; + prev = item; + } else { + if (prev) { + prev->next = next; + } else { + *devices = next; + } + /* these two pointers are the same if not a duplicate devname */ + if (item->name != item->original_name) { + SDL_free(item->name); + } + SDL_free(item->original_name); + SDL_free(item); + } + item = next; + } + + *devCount = total; + *removedFlag = SDL_FALSE; +} + +int SDL_GetNumAudioDevices(int iscapture) +{ + int retval = 0; + + if (!SDL_GetCurrentAudioDriver()) { + return -1; + } + + SDL_LockMutex(current_audio.detectionLock); + if (iscapture && current_audio.captureDevicesRemoved) { + clean_out_device_list(¤t_audio.inputDevices, ¤t_audio.inputDeviceCount, ¤t_audio.captureDevicesRemoved); + } + + if (!iscapture && current_audio.outputDevicesRemoved) { + clean_out_device_list(¤t_audio.outputDevices, ¤t_audio.outputDeviceCount, ¤t_audio.outputDevicesRemoved); + } + + retval = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount; + SDL_UnlockMutex(current_audio.detectionLock); + + return retval; +} + +const char *SDL_GetAudioDeviceName(int index, int iscapture) +{ + SDL_AudioDeviceItem *item; + int i; + const char *retval; + + if (!SDL_GetCurrentAudioDriver()) { + SDL_SetError("Audio subsystem is not initialized"); + return NULL; + } + + SDL_LockMutex(current_audio.detectionLock); + item = iscapture ? current_audio.inputDevices : current_audio.outputDevices; + i = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount; + if (index >= 0 && index < i) { + for (i--; i > index; i--, item = item->next) { + SDL_assert(item != NULL); + } + SDL_assert(item != NULL); + retval = item->name; + } else { + SDL_InvalidParamError("index"); + retval = NULL; + } + SDL_UnlockMutex(current_audio.detectionLock); + + return retval; +} + +int SDL_GetAudioDeviceSpec(int index, int iscapture, SDL_AudioSpec *spec) +{ + SDL_AudioDeviceItem *item; + int i, retval; + + if (spec == NULL) { + return SDL_InvalidParamError("spec"); + } + + if (!SDL_GetCurrentAudioDriver()) { + return SDL_SetError("Audio subsystem is not initialized"); + } + + SDL_LockMutex(current_audio.detectionLock); + item = iscapture ? current_audio.inputDevices : current_audio.outputDevices; + i = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount; + if (index >= 0 && index < i) { + for (i--; i > index; i--, item = item->next) { + SDL_assert(item != NULL); + } + SDL_assert(item != NULL); + SDL_copyp(spec, &item->spec); + retval = 0; + } else { + retval = SDL_InvalidParamError("index"); + } + SDL_UnlockMutex(current_audio.detectionLock); + + return retval; +} + +int SDL_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture) +{ + if (spec == NULL) { + return SDL_InvalidParamError("spec"); + } + + if (!SDL_GetCurrentAudioDriver()) { + return SDL_SetError("Audio subsystem is not initialized"); + } + + if (current_audio.impl.GetDefaultAudioInfo == NULL) { + return SDL_Unsupported(); + } + return current_audio.impl.GetDefaultAudioInfo(name, spec, iscapture); +} + +static void close_audio_device(SDL_AudioDevice *device) +{ + if (!device) { + return; + } + + /* make sure the device is paused before we do anything else, so the + audio callback definitely won't fire again. */ + current_audio.impl.LockDevice(device); + SDL_AtomicSet(&device->paused, 1); + SDL_AtomicSet(&device->shutdown, 1); + SDL_AtomicSet(&device->enabled, 0); + current_audio.impl.UnlockDevice(device); + + if (device->thread != NULL) { + SDL_WaitThread(device->thread, NULL); + } + if (device->mixer_lock != NULL) { + SDL_DestroyMutex(device->mixer_lock); + } + + SDL_free(device->work_buffer); + SDL_FreeAudioStream(device->stream); + + if (device->id > 0) { + SDL_AudioDevice *opendev = open_devices[device->id - 1]; + SDL_assert((opendev == device) || (opendev == NULL)); + if (opendev == device) { + open_devices[device->id - 1] = NULL; + } + } + + if (device->hidden != NULL) { + current_audio.impl.CloseDevice(device); + } + + SDL_FreeDataQueue(device->buffer_queue); + + SDL_free(device); +} + +static Uint16 GetDefaultSamplesFromFreq(int freq) +{ + /* Pick a default of ~46 ms at desired frequency */ + /* !!! FIXME: remove this when the non-Po2 resampling is in. */ + const Uint16 max_sample = (freq / 1000) * 46; + Uint16 current_sample = 1; + while (current_sample < max_sample) { + current_sample *= 2; + } + return current_sample; +} + +/* + * Sanity check desired AudioSpec for SDL_OpenAudio() in (orig). + * Fills in a sanitized copy in (prepared). + * Returns non-zero if okay, zero on fatal parameters in (orig). + */ +static int prepare_audiospec(const SDL_AudioSpec *orig, SDL_AudioSpec *prepared) +{ + SDL_copyp(prepared, orig); + + if (orig->freq == 0) { + static const int DEFAULT_FREQ = 22050; + const char *env = SDL_getenv("SDL_AUDIO_FREQUENCY"); + if (env != NULL) { + int freq = SDL_atoi(env); + prepared->freq = freq != 0 ? freq : DEFAULT_FREQ; + } else { + prepared->freq = DEFAULT_FREQ; + } + } + + if (orig->format == 0) { + const char *env = SDL_getenv("SDL_AUDIO_FORMAT"); + if (env != NULL) { + const SDL_AudioFormat format = SDL_ParseAudioFormat(env); + prepared->format = format != 0 ? format : AUDIO_S16; + } else { + prepared->format = AUDIO_S16; + } + } + + if (orig->channels == 0) { + const char *env = SDL_getenv("SDL_AUDIO_CHANNELS"); + if (env != NULL) { + Uint8 channels = (Uint8)SDL_atoi(env); + prepared->channels = channels != 0 ? channels : 2; + } else { + prepared->channels = 2; + } + } else if (orig->channels > 8) { + SDL_SetError("Unsupported number of audio channels."); + return 0; + } + + if (orig->samples == 0) { + const char *env = SDL_getenv("SDL_AUDIO_SAMPLES"); + if (env != NULL) { + Uint16 samples = (Uint16)SDL_atoi(env); + prepared->samples = samples != 0 ? samples : GetDefaultSamplesFromFreq(prepared->freq); + } else { + prepared->samples = GetDefaultSamplesFromFreq(prepared->freq); + } + } + + /* Calculate the silence and size of the audio specification */ + SDL_CalculateAudioSpec(prepared); + + return 1; +} + +static SDL_AudioDeviceID open_audio_device(const char *devname, int iscapture, + const SDL_AudioSpec *desired, SDL_AudioSpec *obtained, + int allowed_changes, int min_id) +{ + SDL_AudioDeviceID id = 0; + SDL_AudioSpec _obtained; + SDL_AudioDevice *device; + SDL_bool build_stream; + void *handle = NULL; + int i = 0; + + if (!SDL_GetCurrentAudioDriver()) { + SDL_SetError("Audio subsystem is not initialized"); + return 0; + } + + if (iscapture && !current_audio.impl.HasCaptureSupport) { + SDL_SetError("No capture support"); + return 0; + } + + if (!obtained) { + obtained = &_obtained; + } + if (!prepare_audiospec(desired, obtained)) { + return 0; + } + + /* If app doesn't care about a specific device, let the user override. */ + if (devname == NULL) { + devname = SDL_getenv("SDL_AUDIO_DEVICE_NAME"); + } + + /* + * Catch device names at the high level for the simple case... + * This lets us have a basic "device enumeration" for systems that + * don't have multiple devices, but makes sure the device name is + * always NULL when it hits the low level. + * + * Also make sure that the simple case prevents multiple simultaneous + * opens of the default system device. + */ + + if ((iscapture) && (current_audio.impl.OnlyHasDefaultCaptureDevice)) { + if ((devname) && (SDL_strcmp(devname, DEFAULT_INPUT_DEVNAME) != 0)) { + SDL_SetError("No such device"); + return 0; + } + devname = NULL; + + SDL_LockMutex(current_audio.detectionLock); + for (i = 0; i < SDL_arraysize(open_devices); i++) { + if ((open_devices[i]) && (open_devices[i]->iscapture)) { + SDL_SetError("Audio device already open"); + SDL_UnlockMutex(current_audio.detectionLock); + return 0; + } + } + SDL_UnlockMutex(current_audio.detectionLock); + } else if ((!iscapture) && (current_audio.impl.OnlyHasDefaultOutputDevice)) { + if ((devname) && (SDL_strcmp(devname, DEFAULT_OUTPUT_DEVNAME) != 0)) { + SDL_SetError("No such device"); + return 0; + } + devname = NULL; + + SDL_LockMutex(current_audio.detectionLock); + for (i = 0; i < SDL_arraysize(open_devices); i++) { + if ((open_devices[i]) && (!open_devices[i]->iscapture)) { + SDL_UnlockMutex(current_audio.detectionLock); + SDL_SetError("Audio device already open"); + return 0; + } + } + SDL_UnlockMutex(current_audio.detectionLock); + } else if (devname != NULL) { + /* if the app specifies an exact string, we can pass the backend + an actual device handle thingey, which saves them the effort of + figuring out what device this was (such as, reenumerating + everything again to find the matching human-readable name). + It might still need to open a device based on the string for, + say, a network audio server, but this optimizes some cases. */ + SDL_AudioDeviceItem *item; + SDL_LockMutex(current_audio.detectionLock); + for (item = iscapture ? current_audio.inputDevices : current_audio.outputDevices; item; item = item->next) { + if ((item->handle != NULL) && (SDL_strcmp(item->name, devname) == 0)) { + handle = item->handle; + break; + } + } + SDL_UnlockMutex(current_audio.detectionLock); + } + + if (!current_audio.impl.AllowsArbitraryDeviceNames) { + /* has to be in our device list, or the default device. */ + if ((handle == NULL) && (devname != NULL)) { + SDL_SetError("No such device."); + return 0; + } + } + + device = (SDL_AudioDevice *)SDL_calloc(1, sizeof(SDL_AudioDevice)); + if (device == NULL) { + SDL_OutOfMemory(); + return 0; + } + device->spec = *obtained; + device->iscapture = iscapture ? SDL_TRUE : SDL_FALSE; + device->handle = handle; + + SDL_AtomicSet(&device->shutdown, 0); /* just in case. */ + SDL_AtomicSet(&device->paused, 1); + SDL_AtomicSet(&device->enabled, 1); + + /* Create a mutex for locking the sound buffers */ + if (current_audio.impl.LockDevice == SDL_AudioLockDevice_Default) { + device->mixer_lock = SDL_CreateMutex(); + if (device->mixer_lock == NULL) { + close_audio_device(device); + SDL_SetError("Couldn't create mixer lock"); + return 0; + } + } + + /* For backends that require a power-of-two value for spec.samples, take the + * value we got from 'desired' and round up to the nearest value + */ + if (!current_audio.impl.SupportsNonPow2Samples && device->spec.samples > 0) { + device->spec.samples = SDL_powerof2(device->spec.samples); + } + + if (current_audio.impl.OpenDevice(device, devname) < 0) { + close_audio_device(device); + return 0; + } + + /* if your target really doesn't need it, set it to 0x1 or something. */ + /* otherwise, close_audio_device() won't call impl.CloseDevice(). */ + SDL_assert(device->hidden != NULL); + + /* See if we need to do any conversion */ + build_stream = SDL_FALSE; + if (obtained->freq != device->spec.freq) { + if (allowed_changes & SDL_AUDIO_ALLOW_FREQUENCY_CHANGE) { + obtained->freq = device->spec.freq; + } else { + build_stream = SDL_TRUE; + } + } + if (obtained->format != device->spec.format) { + if (allowed_changes & SDL_AUDIO_ALLOW_FORMAT_CHANGE) { + obtained->format = device->spec.format; + } else { + build_stream = SDL_TRUE; + } + } + if (obtained->channels != device->spec.channels) { + if (allowed_changes & SDL_AUDIO_ALLOW_CHANNELS_CHANGE) { + obtained->channels = device->spec.channels; + } else { + build_stream = SDL_TRUE; + } + } + if (device->spec.samples != obtained->samples) { + if (allowed_changes & SDL_AUDIO_ALLOW_SAMPLES_CHANGE) { + obtained->samples = device->spec.samples; + } else { + build_stream = SDL_TRUE; + } + } + + SDL_CalculateAudioSpec(obtained); /* recalc after possible changes. */ + + device->callbackspec = *obtained; + + if (build_stream) { + if (iscapture) { + device->stream = SDL_NewAudioStream(device->spec.format, + device->spec.channels, device->spec.freq, + obtained->format, obtained->channels, obtained->freq); + } else { + device->stream = SDL_NewAudioStream(obtained->format, obtained->channels, + obtained->freq, device->spec.format, + device->spec.channels, device->spec.freq); + } + + if (!device->stream) { + close_audio_device(device); + return 0; + } + } + + if (device->spec.callback == NULL) { /* use buffer queueing? */ + /* pool a few packets to start. Enough for two callbacks. */ + device->buffer_queue = SDL_NewDataQueue(SDL_AUDIOBUFFERQUEUE_PACKETLEN, obtained->size * 2); + if (!device->buffer_queue) { + close_audio_device(device); + SDL_SetError("Couldn't create audio buffer queue"); + return 0; + } + device->callbackspec.callback = iscapture ? SDL_BufferQueueFillCallback : SDL_BufferQueueDrainCallback; + device->callbackspec.userdata = device; + } + + /* Allocate a scratch audio buffer */ + device->work_buffer_len = build_stream ? device->callbackspec.size : 0; + if (device->spec.size > device->work_buffer_len) { + device->work_buffer_len = device->spec.size; + } + SDL_assert(device->work_buffer_len > 0); + + device->work_buffer = (Uint8 *)SDL_malloc(device->work_buffer_len); + if (device->work_buffer == NULL) { + close_audio_device(device); + SDL_OutOfMemory(); + return 0; + } + + /* Find an available device ID... */ + SDL_LockMutex(current_audio.detectionLock); + for (id = min_id - 1; id < SDL_arraysize(open_devices); id++) { + if (open_devices[id] == NULL) { + break; + } + } + + if (id == SDL_arraysize(open_devices)) { + close_audio_device(device); + SDL_SetError("Too many open audio devices"); + SDL_UnlockMutex(current_audio.detectionLock); + return 0; + } + + device->id = id + 1; + open_devices[id] = device; /* add it to our list of open devices. */ + SDL_UnlockMutex(current_audio.detectionLock); + + /* Start the audio thread if necessary */ + if (!current_audio.impl.ProvidesOwnCallbackThread) { + /* Start the audio thread */ + char threadname[64]; + AudioThreadStartupData startup_data; + + startup_data.device = device; + startup_data.startup_semaphore = SDL_CreateSemaphore(0); + if (!startup_data.startup_semaphore) { + close_audio_device(device); + SDL_SetError("Couldn't create audio thread startup semaphore"); + return 0; + } + + (void)SDL_snprintf(threadname, sizeof(threadname), "SDLAudio%c%" SDL_PRIu32, (iscapture) ? 'C' : 'P', device->id); + + device->thread = SDL_CreateThreadInternal(iscapture ? SDL_CaptureAudio : SDL_RunAudio, threadname, 0, &startup_data); + if (device->thread == NULL) { + SDL_DestroySemaphore(startup_data.startup_semaphore); + close_audio_device(device); + SDL_SetError("Couldn't create audio thread"); + return 0; + } + + SDL_SemWait(startup_data.startup_semaphore); + SDL_DestroySemaphore(startup_data.startup_semaphore); + } + + return device->id; +} + +int SDL_OpenAudio(SDL_AudioSpec *desired, SDL_AudioSpec *obtained) +{ + SDL_AudioDeviceID id = 0; + + /* Start up the audio driver, if necessary. This is legacy behaviour! */ + if (!SDL_WasInit(SDL_INIT_AUDIO)) { + if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { + return -1; + } + } + + /* SDL_OpenAudio() is legacy and can only act on Device ID #1. */ + if (open_devices[0] != NULL) { + return SDL_SetError("Audio device is already opened"); + } + + if (obtained) { + id = open_audio_device(NULL, 0, desired, obtained, + SDL_AUDIO_ALLOW_ANY_CHANGE, 1); + } else { + SDL_AudioSpec _obtained; + SDL_zero(_obtained); + id = open_audio_device(NULL, 0, desired, &_obtained, 0, 1); + /* On successful open, copy calculated values into 'desired'. */ + if (id > 0) { + desired->size = _obtained.size; + desired->silence = _obtained.silence; + } + } + + SDL_assert((id == 0) || (id == 1)); + return (id == 0) ? -1 : 0; +} + +SDL_AudioDeviceID SDL_OpenAudioDevice(const char *device, int iscapture, + const SDL_AudioSpec *desired, SDL_AudioSpec *obtained, + int allowed_changes) +{ + return open_audio_device(device, iscapture, desired, obtained, + allowed_changes, 2); +} + +SDL_AudioStatus SDL_GetAudioDeviceStatus(SDL_AudioDeviceID devid) +{ + SDL_AudioDevice *device = get_audio_device(devid); + SDL_AudioStatus status = SDL_AUDIO_STOPPED; + if (device && SDL_AtomicGet(&device->enabled)) { + if (SDL_AtomicGet(&device->paused)) { + status = SDL_AUDIO_PAUSED; + } else { + status = SDL_AUDIO_PLAYING; + } + } + return status; +} + +SDL_AudioStatus SDL_GetAudioStatus(void) +{ + return SDL_GetAudioDeviceStatus(1); +} + +void SDL_PauseAudioDevice(SDL_AudioDeviceID devid, int pause_on) +{ + SDL_AudioDevice *device = get_audio_device(devid); + if (device) { + current_audio.impl.LockDevice(device); + SDL_AtomicSet(&device->paused, pause_on ? 1 : 0); + current_audio.impl.UnlockDevice(device); + } +} + +void SDL_PauseAudio(int pause_on) +{ + SDL_PauseAudioDevice(1, pause_on); +} + +void SDL_LockAudioDevice(SDL_AudioDeviceID devid) +{ + /* Obtain a lock on the mixing buffers */ + SDL_AudioDevice *device = get_audio_device(devid); + if (device) { + current_audio.impl.LockDevice(device); + } +} + +void SDL_LockAudio(void) +{ + SDL_LockAudioDevice(1); +} + +void SDL_UnlockAudioDevice(SDL_AudioDeviceID devid) +{ + /* Obtain a lock on the mixing buffers */ + SDL_AudioDevice *device = get_audio_device(devid); + if (device) { + current_audio.impl.UnlockDevice(device); + } +} + +void SDL_UnlockAudio(void) +{ + SDL_UnlockAudioDevice(1); +} + +void SDL_CloseAudioDevice(SDL_AudioDeviceID devid) +{ + close_audio_device(get_audio_device(devid)); +} + +void SDL_CloseAudio(void) +{ + SDL_CloseAudioDevice(1); +} + +void SDL_AudioQuit(void) +{ + SDL_AudioDeviceID i; + + if (!current_audio.name) { /* not initialized?! */ + return; + } + + for (i = 0; i < SDL_arraysize(open_devices); i++) { + close_audio_device(open_devices[i]); + } + + free_device_list(¤t_audio.outputDevices, ¤t_audio.outputDeviceCount); + free_device_list(¤t_audio.inputDevices, ¤t_audio.inputDeviceCount); + + /* Free the driver data */ + current_audio.impl.Deinitialize(); + + SDL_DestroyMutex(current_audio.detectionLock); + + SDL_zero(current_audio); + SDL_zeroa(open_devices); + +#ifdef HAVE_LIBSAMPLERATE_H + UnloadLibSampleRate(); +#endif +} + +#define NUM_FORMATS 10 +static int format_idx; +static int format_idx_sub; +static SDL_AudioFormat format_list[NUM_FORMATS][NUM_FORMATS] = { + { AUDIO_U8, AUDIO_S8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, + AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB }, + { AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, + AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB }, + { AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S32LSB, + AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8 }, + { AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S32MSB, + AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8 }, + { AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_S32LSB, + AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8 }, + { AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_S32MSB, + AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8 }, + { AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S16LSB, + AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8 }, + { AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S16MSB, + AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8 }, + { AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_S16LSB, + AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8 }, + { AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_S16MSB, + AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8 }, +}; + +SDL_AudioFormat SDL_FirstAudioFormat(SDL_AudioFormat format) +{ + for (format_idx = 0; format_idx < NUM_FORMATS; ++format_idx) { + if (format_list[format_idx][0] == format) { + break; + } + } + format_idx_sub = 0; + return SDL_NextAudioFormat(); +} + +SDL_AudioFormat SDL_NextAudioFormat(void) +{ + if ((format_idx == NUM_FORMATS) || (format_idx_sub == NUM_FORMATS)) { + return 0; + } + return format_list[format_idx][format_idx_sub++]; +} + +Uint8 SDL_SilenceValueForFormat(const SDL_AudioFormat format) +{ + switch (format) { + /* !!! FIXME: 0x80 isn't perfect for U16, but we can't fit 0x8000 in a + !!! FIXME: byte for SDL_memset() use. This is actually 0.1953 percent + !!! FIXME: off from silence. Maybe just don't use U16. */ + case AUDIO_U16LSB: + case AUDIO_U16MSB: + case AUDIO_U8: + return 0x80; + + default: + break; + } + + return 0x00; +} + +void SDL_CalculateAudioSpec(SDL_AudioSpec *spec) +{ + spec->silence = SDL_SilenceValueForFormat(spec->format); + spec->size = SDL_AUDIO_BITSIZE(spec->format) / 8; + spec->size *= spec->channels; + spec->size *= spec->samples; +} + +/* + * Moved here from SDL_mixer.c, since it relies on internals of an opened + * audio device (and is deprecated, by the way!). + */ +void SDL_MixAudio(Uint8 *dst, const Uint8 *src, Uint32 len, int volume) +{ + /* Mix the user-level audio format */ + SDL_AudioDevice *device = get_audio_device(1); + if (device != NULL) { + SDL_MixAudioFormat(dst, src, device->callbackspec.format, len, volume); + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_audio_c.h b/third_party/SDL2/src/audio/SDL_audio_c.h new file mode 100644 index 00000000000..49019e13d95 --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_audio_c.h @@ -0,0 +1,76 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_audio_c_h_ +#define SDL_audio_c_h_ + +#include "../SDL_internal.h" + +#ifndef DEBUG_CONVERT +#define DEBUG_CONVERT 0 +#endif + +#if DEBUG_CONVERT +#define LOG_DEBUG_CONVERT(from, to) SDL_Log("SDL_AUDIO_CONVERT: Converting %s to %s.\n", from, to); +#else +#define LOG_DEBUG_CONVERT(from, to) +#endif + +/* Functions and variables exported from SDL_audio.c for SDL_sysaudio.c */ + +#ifdef HAVE_LIBSAMPLERATE_H +#include "samplerate.h" +extern SDL_bool SRC_available; +extern int SRC_converter; +extern SRC_STATE *(*SRC_src_new)(int converter_type, int channels, int *error); +extern int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data); +extern int (*SRC_src_reset)(SRC_STATE *state); +extern SRC_STATE *(*SRC_src_delete)(SRC_STATE *state); +extern const char *(*SRC_src_strerror)(int error); +extern int (*SRC_src_simple)(SRC_DATA *data, int converter_type, int channels); +#endif + +/* Functions to get a list of "close" audio formats */ +extern SDL_AudioFormat SDL_FirstAudioFormat(SDL_AudioFormat format); +extern SDL_AudioFormat SDL_NextAudioFormat(void); + +/* Function to calculate the size and silence for a SDL_AudioSpec */ +extern Uint8 SDL_SilenceValueForFormat(const SDL_AudioFormat format); +extern void SDL_CalculateAudioSpec(SDL_AudioSpec *spec); + +/* Choose the audio filter functions below */ +extern void SDL_ChooseAudioConverters(void); + +/* These pointers get set during SDL_ChooseAudioConverters() to various SIMD implementations. */ +extern SDL_AudioFilter SDL_Convert_S8_to_F32; +extern SDL_AudioFilter SDL_Convert_U8_to_F32; +extern SDL_AudioFilter SDL_Convert_S16_to_F32; +extern SDL_AudioFilter SDL_Convert_U16_to_F32; +extern SDL_AudioFilter SDL_Convert_S32_to_F32; +extern SDL_AudioFilter SDL_Convert_F32_to_S8; +extern SDL_AudioFilter SDL_Convert_F32_to_U8; +extern SDL_AudioFilter SDL_Convert_F32_to_S16; +extern SDL_AudioFilter SDL_Convert_F32_to_U16; +extern SDL_AudioFilter SDL_Convert_F32_to_S32; + +#endif /* SDL_audio_c_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_audio_channel_converters.h b/third_party/SDL2/src/audio/SDL_audio_channel_converters.h new file mode 100644 index 00000000000..1e6fd6e5f0d --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_audio_channel_converters.h @@ -0,0 +1,1402 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* DO NOT EDIT, THIS FILE WAS GENERATED BY build-scripts/gen_audio_channel_conversion.c */ + +static void SDLCALL SDL_ConvertMonoToStereo(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 1) * 2))) - 2; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 1; + int i; + + LOG_DEBUG_CONVERT("mono", "stereo"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 1); i; i--, src -= 1, dst -= 2) { + const float srcFC = src[0]; + dst[1] /* FR */ = srcFC; + dst[0] /* FL */ = srcFC; + } + + cvt->len_cvt = cvt->len_cvt * 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertMonoTo21(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 1) * 3))) - 3; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 1; + int i; + + LOG_DEBUG_CONVERT("mono", "2.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 1); i; i--, src -= 1, dst -= 3) { + const float srcFC = src[0]; + dst[2] /* LFE */ = 0.0f; + dst[1] /* FR */ = srcFC; + dst[0] /* FL */ = srcFC; + } + + cvt->len_cvt = cvt->len_cvt * 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertMonoToQuad(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 1) * 4))) - 4; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 1; + int i; + + LOG_DEBUG_CONVERT("mono", "quad"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 1); i; i--, src -= 1, dst -= 4) { + const float srcFC = src[0]; + dst[3] /* BR */ = 0.0f; + dst[2] /* BL */ = 0.0f; + dst[1] /* FR */ = srcFC; + dst[0] /* FL */ = srcFC; + } + + cvt->len_cvt = cvt->len_cvt * 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertMonoTo41(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 1) * 5))) - 5; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 1; + int i; + + LOG_DEBUG_CONVERT("mono", "4.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 1); i; i--, src -= 1, dst -= 5) { + const float srcFC = src[0]; + dst[4] /* BR */ = 0.0f; + dst[3] /* BL */ = 0.0f; + dst[2] /* LFE */ = 0.0f; + dst[1] /* FR */ = srcFC; + dst[0] /* FL */ = srcFC; + } + + cvt->len_cvt = cvt->len_cvt * 5; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertMonoTo51(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 1) * 6))) - 6; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 1; + int i; + + LOG_DEBUG_CONVERT("mono", "5.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 1); i; i--, src -= 1, dst -= 6) { + const float srcFC = src[0]; + dst[5] /* BR */ = 0.0f; + dst[4] /* BL */ = 0.0f; + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = srcFC; + dst[0] /* FL */ = srcFC; + } + + cvt->len_cvt = cvt->len_cvt * 6; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertMonoTo61(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 1) * 7))) - 7; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 1; + int i; + + LOG_DEBUG_CONVERT("mono", "6.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 1); i; i--, src -= 1, dst -= 7) { + const float srcFC = src[0]; + dst[6] /* SR */ = 0.0f; + dst[5] /* SL */ = 0.0f; + dst[4] /* BC */ = 0.0f; + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = srcFC; + dst[0] /* FL */ = srcFC; + } + + cvt->len_cvt = cvt->len_cvt * 7; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertMonoTo71(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 1) * 8))) - 8; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 1; + int i; + + LOG_DEBUG_CONVERT("mono", "7.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 1); i; i--, src -= 1, dst -= 8) { + const float srcFC = src[0]; + dst[7] /* SR */ = 0.0f; + dst[6] /* SL */ = 0.0f; + dst[5] /* BR */ = 0.0f; + dst[4] /* BL */ = 0.0f; + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = srcFC; + dst[0] /* FL */ = srcFC; + } + + cvt->len_cvt = cvt->len_cvt * 8; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertStereoToMono(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("stereo", "mono"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 2); i; i--, src += 2, dst += 1) { + dst[0] /* FC */ = (src[0] * 0.500000000f) + (src[1] * 0.500000000f); + } + + cvt->len_cvt = cvt->len_cvt / 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertStereoTo21(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 2) * 3))) - 3; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 2; + int i; + + LOG_DEBUG_CONVERT("stereo", "2.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 2); i; i--, src -= 2, dst -= 3) { + dst[2] /* LFE */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 2) * 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertStereoToQuad(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 2) * 4))) - 4; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 2; + int i; + + LOG_DEBUG_CONVERT("stereo", "quad"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 2); i; i--, src -= 2, dst -= 4) { + dst[3] /* BR */ = 0.0f; + dst[2] /* BL */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 2) * 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertStereoTo41(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 2) * 5))) - 5; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 2; + int i; + + LOG_DEBUG_CONVERT("stereo", "4.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 2); i; i--, src -= 2, dst -= 5) { + dst[4] /* BR */ = 0.0f; + dst[3] /* BL */ = 0.0f; + dst[2] /* LFE */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 2) * 5; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertStereoTo51(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 2) * 6))) - 6; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 2; + int i; + + LOG_DEBUG_CONVERT("stereo", "5.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 2); i; i--, src -= 2, dst -= 6) { + dst[5] /* BR */ = 0.0f; + dst[4] /* BL */ = 0.0f; + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 2) * 6; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertStereoTo61(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 2) * 7))) - 7; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 2; + int i; + + LOG_DEBUG_CONVERT("stereo", "6.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 2); i; i--, src -= 2, dst -= 7) { + dst[6] /* SR */ = 0.0f; + dst[5] /* SL */ = 0.0f; + dst[4] /* BC */ = 0.0f; + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 2) * 7; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertStereoTo71(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 2) * 8))) - 8; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 2; + int i; + + LOG_DEBUG_CONVERT("stereo", "7.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 2); i; i--, src -= 2, dst -= 8) { + dst[7] /* SR */ = 0.0f; + dst[6] /* SL */ = 0.0f; + dst[5] /* BR */ = 0.0f; + dst[4] /* BL */ = 0.0f; + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 2) * 8; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert21ToMono(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("2.1", "mono"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 3); i; i--, src += 3, dst += 1) { + dst[0] /* FC */ = (src[0] * 0.333333343f) + (src[1] * 0.333333343f) + (src[2] * 0.333333343f); + } + + cvt->len_cvt = cvt->len_cvt / 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert21ToStereo(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("2.1", "stereo"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 3); i; i--, src += 3, dst += 2) { + const float srcLFE = src[2]; + dst[0] /* FL */ = (src[0] * 0.800000012f) + (srcLFE * 0.200000003f); + dst[1] /* FR */ = (src[1] * 0.800000012f) + (srcLFE * 0.200000003f); + } + + cvt->len_cvt = (cvt->len_cvt / 3) * 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert21ToQuad(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 3) * 4))) - 4; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 3; + int i; + + LOG_DEBUG_CONVERT("2.1", "quad"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 3); i; i--, src -= 3, dst -= 4) { + const float srcLFE = src[2]; + dst[3] /* BR */ = (srcLFE * 0.111111112f); + dst[2] /* BL */ = (srcLFE * 0.111111112f); + dst[1] /* FR */ = (srcLFE * 0.111111112f) + (src[1] * 0.888888896f); + dst[0] /* FL */ = (srcLFE * 0.111111112f) + (src[0] * 0.888888896f); + } + + cvt->len_cvt = (cvt->len_cvt / 3) * 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert21To41(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 3) * 5))) - 5; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 3; + int i; + + LOG_DEBUG_CONVERT("2.1", "4.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 3); i; i--, src -= 3, dst -= 5) { + dst[4] /* BR */ = 0.0f; + dst[3] /* BL */ = 0.0f; + dst[2] /* LFE */ = src[2]; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 3) * 5; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert21To51(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 3) * 6))) - 6; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 3; + int i; + + LOG_DEBUG_CONVERT("2.1", "5.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 3); i; i--, src -= 3, dst -= 6) { + dst[5] /* BR */ = 0.0f; + dst[4] /* BL */ = 0.0f; + dst[3] /* LFE */ = src[2]; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 3) * 6; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert21To61(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 3) * 7))) - 7; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 3; + int i; + + LOG_DEBUG_CONVERT("2.1", "6.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 3); i; i--, src -= 3, dst -= 7) { + dst[6] /* SR */ = 0.0f; + dst[5] /* SL */ = 0.0f; + dst[4] /* BC */ = 0.0f; + dst[3] /* LFE */ = src[2]; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 3) * 7; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert21To71(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 3) * 8))) - 8; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 3; + int i; + + LOG_DEBUG_CONVERT("2.1", "7.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 3); i; i--, src -= 3, dst -= 8) { + dst[7] /* SR */ = 0.0f; + dst[6] /* SL */ = 0.0f; + dst[5] /* BR */ = 0.0f; + dst[4] /* BL */ = 0.0f; + dst[3] /* LFE */ = src[2]; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 3) * 8; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertQuadToMono(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("quad", "mono"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 4); i; i--, src += 4, dst += 1) { + dst[0] /* FC */ = (src[0] * 0.250000000f) + (src[1] * 0.250000000f) + (src[2] * 0.250000000f) + (src[3] * 0.250000000f); + } + + cvt->len_cvt = cvt->len_cvt / 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertQuadToStereo(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("quad", "stereo"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 4); i; i--, src += 4, dst += 2) { + const float srcBL = src[2]; + const float srcBR = src[3]; + dst[0] /* FL */ = (src[0] * 0.421000004f) + (srcBL * 0.358999997f) + (srcBR * 0.219999999f); + dst[1] /* FR */ = (src[1] * 0.421000004f) + (srcBL * 0.219999999f) + (srcBR * 0.358999997f); + } + + cvt->len_cvt = (cvt->len_cvt / 4) * 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertQuadTo21(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("quad", "2.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 4); i; i--, src += 4, dst += 3) { + const float srcBL = src[2]; + const float srcBR = src[3]; + dst[0] /* FL */ = (src[0] * 0.421000004f) + (srcBL * 0.358999997f) + (srcBR * 0.219999999f); + dst[1] /* FR */ = (src[1] * 0.421000004f) + (srcBL * 0.219999999f) + (srcBR * 0.358999997f); + dst[2] /* LFE */ = 0.0f; + } + + cvt->len_cvt = (cvt->len_cvt / 4) * 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertQuadTo41(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 4) * 5))) - 5; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 4; + int i; + + LOG_DEBUG_CONVERT("quad", "4.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 4); i; i--, src -= 4, dst -= 5) { + dst[4] /* BR */ = src[3]; + dst[3] /* BL */ = src[2]; + dst[2] /* LFE */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 4) * 5; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertQuadTo51(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 4) * 6))) - 6; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 4; + int i; + + LOG_DEBUG_CONVERT("quad", "5.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 4); i; i--, src -= 4, dst -= 6) { + dst[5] /* BR */ = src[3]; + dst[4] /* BL */ = src[2]; + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 4) * 6; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertQuadTo61(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 4) * 7))) - 7; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 4; + int i; + + LOG_DEBUG_CONVERT("quad", "6.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 4); i; i--, src -= 4, dst -= 7) { + const float srcBL = src[2]; + const float srcBR = src[3]; + dst[6] /* SR */ = (srcBR * 0.796000004f); + dst[5] /* SL */ = (srcBL * 0.796000004f); + dst[4] /* BC */ = (srcBR * 0.500000000f) + (srcBL * 0.500000000f); + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = (src[1] * 0.939999998f); + dst[0] /* FL */ = (src[0] * 0.939999998f); + } + + cvt->len_cvt = (cvt->len_cvt / 4) * 7; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_ConvertQuadTo71(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 4) * 8))) - 8; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 4; + int i; + + LOG_DEBUG_CONVERT("quad", "7.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 4); i; i--, src -= 4, dst -= 8) { + dst[7] /* SR */ = 0.0f; + dst[6] /* SL */ = 0.0f; + dst[5] /* BR */ = src[3]; + dst[4] /* BL */ = src[2]; + dst[3] /* LFE */ = 0.0f; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 4) * 8; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert41ToMono(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("4.1", "mono"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 5); i; i--, src += 5, dst += 1) { + dst[0] /* FC */ = (src[0] * 0.200000003f) + (src[1] * 0.200000003f) + (src[2] * 0.200000003f) + (src[3] * 0.200000003f) + (src[4] * 0.200000003f); + } + + cvt->len_cvt = cvt->len_cvt / 5; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert41ToStereo(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("4.1", "stereo"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 5); i; i--, src += 5, dst += 2) { + const float srcLFE = src[2]; + const float srcBL = src[3]; + const float srcBR = src[4]; + dst[0] /* FL */ = (src[0] * 0.374222219f) + (srcLFE * 0.111111112f) + (srcBL * 0.319111109f) + (srcBR * 0.195555553f); + dst[1] /* FR */ = (src[1] * 0.374222219f) + (srcLFE * 0.111111112f) + (srcBL * 0.195555553f) + (srcBR * 0.319111109f); + } + + cvt->len_cvt = (cvt->len_cvt / 5) * 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert41To21(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("4.1", "2.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 5); i; i--, src += 5, dst += 3) { + const float srcBL = src[3]; + const float srcBR = src[4]; + dst[0] /* FL */ = (src[0] * 0.421000004f) + (srcBL * 0.358999997f) + (srcBR * 0.219999999f); + dst[1] /* FR */ = (src[1] * 0.421000004f) + (srcBL * 0.219999999f) + (srcBR * 0.358999997f); + dst[2] /* LFE */ = src[2]; + } + + cvt->len_cvt = (cvt->len_cvt / 5) * 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert41ToQuad(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("4.1", "quad"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 5); i; i--, src += 5, dst += 4) { + const float srcLFE = src[2]; + dst[0] /* FL */ = (src[0] * 0.941176474f) + (srcLFE * 0.058823530f); + dst[1] /* FR */ = (src[1] * 0.941176474f) + (srcLFE * 0.058823530f); + dst[2] /* BL */ = (srcLFE * 0.058823530f) + (src[3] * 0.941176474f); + dst[3] /* BR */ = (srcLFE * 0.058823530f) + (src[4] * 0.941176474f); + } + + cvt->len_cvt = (cvt->len_cvt / 5) * 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert41To51(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 5) * 6))) - 6; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 5; + int i; + + LOG_DEBUG_CONVERT("4.1", "5.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 5); i; i--, src -= 5, dst -= 6) { + dst[5] /* BR */ = src[4]; + dst[4] /* BL */ = src[3]; + dst[3] /* LFE */ = src[2]; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 5) * 6; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert41To61(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 5) * 7))) - 7; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 5; + int i; + + LOG_DEBUG_CONVERT("4.1", "6.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 5); i; i--, src -= 5, dst -= 7) { + const float srcBL = src[3]; + const float srcBR = src[4]; + dst[6] /* SR */ = (srcBR * 0.796000004f); + dst[5] /* SL */ = (srcBL * 0.796000004f); + dst[4] /* BC */ = (srcBR * 0.500000000f) + (srcBL * 0.500000000f); + dst[3] /* LFE */ = src[2]; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = (src[1] * 0.939999998f); + dst[0] /* FL */ = (src[0] * 0.939999998f); + } + + cvt->len_cvt = (cvt->len_cvt / 5) * 7; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert41To71(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 5) * 8))) - 8; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 5; + int i; + + LOG_DEBUG_CONVERT("4.1", "7.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 5); i; i--, src -= 5, dst -= 8) { + dst[7] /* SR */ = 0.0f; + dst[6] /* SL */ = 0.0f; + dst[5] /* BR */ = src[4]; + dst[4] /* BL */ = src[3]; + dst[3] /* LFE */ = src[2]; + dst[2] /* FC */ = 0.0f; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 5) * 8; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert51ToMono(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("5.1", "mono"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 6); i; i--, src += 6, dst += 1) { + dst[0] /* FC */ = (src[0] * 0.166666672f) + (src[1] * 0.166666672f) + (src[2] * 0.166666672f) + (src[3] * 0.166666672f) + (src[4] * 0.166666672f) + (src[5] * 0.166666672f); + } + + cvt->len_cvt = cvt->len_cvt / 6; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert51ToStereo(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("5.1", "stereo"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 6); i; i--, src += 6, dst += 2) { + const float srcFC = src[2]; + const float srcLFE = src[3]; + const float srcBL = src[4]; + const float srcBR = src[5]; + dst[0] /* FL */ = (src[0] * 0.294545442f) + (srcFC * 0.208181813f) + (srcLFE * 0.090909094f) + (srcBL * 0.251818180f) + (srcBR * 0.154545456f); + dst[1] /* FR */ = (src[1] * 0.294545442f) + (srcFC * 0.208181813f) + (srcLFE * 0.090909094f) + (srcBL * 0.154545456f) + (srcBR * 0.251818180f); + } + + cvt->len_cvt = (cvt->len_cvt / 6) * 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert51To21(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("5.1", "2.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 6); i; i--, src += 6, dst += 3) { + const float srcFC = src[2]; + const float srcBL = src[4]; + const float srcBR = src[5]; + dst[0] /* FL */ = (src[0] * 0.324000001f) + (srcFC * 0.229000002f) + (srcBL * 0.277000010f) + (srcBR * 0.170000002f); + dst[1] /* FR */ = (src[1] * 0.324000001f) + (srcFC * 0.229000002f) + (srcBL * 0.170000002f) + (srcBR * 0.277000010f); + dst[2] /* LFE */ = src[3]; + } + + cvt->len_cvt = (cvt->len_cvt / 6) * 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert51ToQuad(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("5.1", "quad"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 6); i; i--, src += 6, dst += 4) { + const float srcFC = src[2]; + const float srcLFE = src[3]; + dst[0] /* FL */ = (src[0] * 0.558095276f) + (srcFC * 0.394285709f) + (srcLFE * 0.047619049f); + dst[1] /* FR */ = (src[1] * 0.558095276f) + (srcFC * 0.394285709f) + (srcLFE * 0.047619049f); + dst[2] /* BL */ = (srcLFE * 0.047619049f) + (src[4] * 0.558095276f); + dst[3] /* BR */ = (srcLFE * 0.047619049f) + (src[5] * 0.558095276f); + } + + cvt->len_cvt = (cvt->len_cvt / 6) * 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert51To41(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("5.1", "4.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 6); i; i--, src += 6, dst += 5) { + const float srcFC = src[2]; + dst[0] /* FL */ = (src[0] * 0.586000025f) + (srcFC * 0.414000005f); + dst[1] /* FR */ = (src[1] * 0.586000025f) + (srcFC * 0.414000005f); + dst[2] /* LFE */ = src[3]; + dst[3] /* BL */ = (src[4] * 0.586000025f); + dst[4] /* BR */ = (src[5] * 0.586000025f); + } + + cvt->len_cvt = (cvt->len_cvt / 6) * 5; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert51To61(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 6) * 7))) - 7; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 6; + int i; + + LOG_DEBUG_CONVERT("5.1", "6.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 6); i; i--, src -= 6, dst -= 7) { + const float srcBL = src[4]; + const float srcBR = src[5]; + dst[6] /* SR */ = (srcBR * 0.796000004f); + dst[5] /* SL */ = (srcBL * 0.796000004f); + dst[4] /* BC */ = (srcBR * 0.500000000f) + (srcBL * 0.500000000f); + dst[3] /* LFE */ = src[3]; + dst[2] /* FC */ = (src[2] * 0.939999998f); + dst[1] /* FR */ = (src[1] * 0.939999998f); + dst[0] /* FL */ = (src[0] * 0.939999998f); + } + + cvt->len_cvt = (cvt->len_cvt / 6) * 7; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert51To71(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 6) * 8))) - 8; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 6; + int i; + + LOG_DEBUG_CONVERT("5.1", "7.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 6); i; i--, src -= 6, dst -= 8) { + dst[7] /* SR */ = 0.0f; + dst[6] /* SL */ = 0.0f; + dst[5] /* BR */ = src[5]; + dst[4] /* BL */ = src[4]; + dst[3] /* LFE */ = src[3]; + dst[2] /* FC */ = src[2]; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 6) * 8; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert61ToMono(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("6.1", "mono"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 7); i; i--, src += 7, dst += 1) { + dst[0] /* FC */ = (src[0] * 0.143142849f) + (src[1] * 0.143142849f) + (src[2] * 0.143142849f) + (src[3] * 0.142857149f) + (src[4] * 0.143142849f) + (src[5] * 0.143142849f) + (src[6] * 0.143142849f); + } + + cvt->len_cvt = cvt->len_cvt / 7; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert61ToStereo(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("6.1", "stereo"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 7); i; i--, src += 7, dst += 2) { + const float srcFC = src[2]; + const float srcLFE = src[3]; + const float srcBC = src[4]; + const float srcSL = src[5]; + const float srcSR = src[6]; + dst[0] /* FL */ = (src[0] * 0.247384623f) + (srcFC * 0.174461529f) + (srcLFE * 0.076923080f) + (srcBC * 0.174461529f) + (srcSL * 0.226153851f) + (srcSR * 0.100615382f); + dst[1] /* FR */ = (src[1] * 0.247384623f) + (srcFC * 0.174461529f) + (srcLFE * 0.076923080f) + (srcBC * 0.174461529f) + (srcSL * 0.100615382f) + (srcSR * 0.226153851f); + } + + cvt->len_cvt = (cvt->len_cvt / 7) * 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert61To21(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("6.1", "2.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 7); i; i--, src += 7, dst += 3) { + const float srcFC = src[2]; + const float srcBC = src[4]; + const float srcSL = src[5]; + const float srcSR = src[6]; + dst[0] /* FL */ = (src[0] * 0.268000007f) + (srcFC * 0.188999996f) + (srcBC * 0.188999996f) + (srcSL * 0.245000005f) + (srcSR * 0.108999997f); + dst[1] /* FR */ = (src[1] * 0.268000007f) + (srcFC * 0.188999996f) + (srcBC * 0.188999996f) + (srcSL * 0.108999997f) + (srcSR * 0.245000005f); + dst[2] /* LFE */ = src[3]; + } + + cvt->len_cvt = (cvt->len_cvt / 7) * 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert61ToQuad(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("6.1", "quad"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 7); i; i--, src += 7, dst += 4) { + const float srcFC = src[2]; + const float srcLFE = src[3]; + const float srcBC = src[4]; + const float srcSL = src[5]; + const float srcSR = src[6]; + dst[0] /* FL */ = (src[0] * 0.463679999f) + (srcFC * 0.327360004f) + (srcLFE * 0.040000003f) + (srcSL * 0.168960005f); + dst[1] /* FR */ = (src[1] * 0.463679999f) + (srcFC * 0.327360004f) + (srcLFE * 0.040000003f) + (srcSR * 0.168960005f); + dst[2] /* BL */ = (srcLFE * 0.040000003f) + (srcBC * 0.327360004f) + (srcSL * 0.431039989f); + dst[3] /* BR */ = (srcLFE * 0.040000003f) + (srcBC * 0.327360004f) + (srcSR * 0.431039989f); + } + + cvt->len_cvt = (cvt->len_cvt / 7) * 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert61To41(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("6.1", "4.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 7); i; i--, src += 7, dst += 5) { + const float srcFC = src[2]; + const float srcBC = src[4]; + const float srcSL = src[5]; + const float srcSR = src[6]; + dst[0] /* FL */ = (src[0] * 0.483000010f) + (srcFC * 0.340999991f) + (srcSL * 0.175999999f); + dst[1] /* FR */ = (src[1] * 0.483000010f) + (srcFC * 0.340999991f) + (srcSR * 0.175999999f); + dst[2] /* LFE */ = src[3]; + dst[3] /* BL */ = (srcBC * 0.340999991f) + (srcSL * 0.449000001f); + dst[4] /* BR */ = (srcBC * 0.340999991f) + (srcSR * 0.449000001f); + } + + cvt->len_cvt = (cvt->len_cvt / 7) * 5; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert61To51(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("6.1", "5.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 7); i; i--, src += 7, dst += 6) { + const float srcBC = src[4]; + const float srcSL = src[5]; + const float srcSR = src[6]; + dst[0] /* FL */ = (src[0] * 0.611000001f) + (srcSL * 0.223000005f); + dst[1] /* FR */ = (src[1] * 0.611000001f) + (srcSR * 0.223000005f); + dst[2] /* FC */ = (src[2] * 0.611000001f); + dst[3] /* LFE */ = src[3]; + dst[4] /* BL */ = (srcBC * 0.432000011f) + (srcSL * 0.568000019f); + dst[5] /* BR */ = (srcBC * 0.432000011f) + (srcSR * 0.568000019f); + } + + cvt->len_cvt = (cvt->len_cvt / 7) * 6; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert61To71(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + ((cvt->len_cvt / 7) * 8))) - 8; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 7; + int i; + + LOG_DEBUG_CONVERT("6.1", "7.1"); + SDL_assert(format == AUDIO_F32SYS); + + /* convert backwards, since output is growing in-place. */ + for (i = cvt->len_cvt / (sizeof(float) * 7); i; i--, src -= 7, dst -= 8) { + const float srcBC = src[4]; + dst[7] /* SR */ = src[6]; + dst[6] /* SL */ = src[5]; + dst[5] /* BR */ = (srcBC * 0.707000017f); + dst[4] /* BL */ = (srcBC * 0.707000017f); + dst[3] /* LFE */ = src[3]; + dst[2] /* FC */ = src[2]; + dst[1] /* FR */ = src[1]; + dst[0] /* FL */ = src[0]; + } + + cvt->len_cvt = (cvt->len_cvt / 7) * 8; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert71ToMono(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("7.1", "mono"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 8); i; i--, src += 8, dst += 1) { + dst[0] /* FC */ = (src[0] * 0.125125006f) + (src[1] * 0.125125006f) + (src[2] * 0.125125006f) + (src[3] * 0.125000000f) + (src[4] * 0.125125006f) + (src[5] * 0.125125006f) + (src[6] * 0.125125006f) + (src[7] * 0.125125006f); + } + + cvt->len_cvt = cvt->len_cvt / 8; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert71ToStereo(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("7.1", "stereo"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 8); i; i--, src += 8, dst += 2) { + const float srcFC = src[2]; + const float srcLFE = src[3]; + const float srcBL = src[4]; + const float srcBR = src[5]; + const float srcSL = src[6]; + const float srcSR = src[7]; + dst[0] /* FL */ = (src[0] * 0.211866662f) + (srcFC * 0.150266662f) + (srcLFE * 0.066666670f) + (srcBL * 0.181066677f) + (srcBR * 0.111066669f) + (srcSL * 0.194133341f) + (srcSR * 0.085866667f); + dst[1] /* FR */ = (src[1] * 0.211866662f) + (srcFC * 0.150266662f) + (srcLFE * 0.066666670f) + (srcBL * 0.111066669f) + (srcBR * 0.181066677f) + (srcSL * 0.085866667f) + (srcSR * 0.194133341f); + } + + cvt->len_cvt = (cvt->len_cvt / 8) * 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert71To21(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("7.1", "2.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 8); i; i--, src += 8, dst += 3) { + const float srcFC = src[2]; + const float srcBL = src[4]; + const float srcBR = src[5]; + const float srcSL = src[6]; + const float srcSR = src[7]; + dst[0] /* FL */ = (src[0] * 0.226999998f) + (srcFC * 0.160999998f) + (srcBL * 0.194000006f) + (srcBR * 0.119000003f) + (srcSL * 0.208000004f) + (srcSR * 0.092000000f); + dst[1] /* FR */ = (src[1] * 0.226999998f) + (srcFC * 0.160999998f) + (srcBL * 0.119000003f) + (srcBR * 0.194000006f) + (srcSL * 0.092000000f) + (srcSR * 0.208000004f); + dst[2] /* LFE */ = src[3]; + } + + cvt->len_cvt = (cvt->len_cvt / 8) * 3; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert71ToQuad(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("7.1", "quad"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 8); i; i--, src += 8, dst += 4) { + const float srcFC = src[2]; + const float srcLFE = src[3]; + const float srcSL = src[6]; + const float srcSR = src[7]; + dst[0] /* FL */ = (src[0] * 0.466344833f) + (srcFC * 0.329241365f) + (srcLFE * 0.034482758f) + (srcSL * 0.169931039f); + dst[1] /* FR */ = (src[1] * 0.466344833f) + (srcFC * 0.329241365f) + (srcLFE * 0.034482758f) + (srcSR * 0.169931039f); + dst[2] /* BL */ = (srcLFE * 0.034482758f) + (src[4] * 0.466344833f) + (srcSL * 0.433517247f); + dst[3] /* BR */ = (srcLFE * 0.034482758f) + (src[5] * 0.466344833f) + (srcSR * 0.433517247f); + } + + cvt->len_cvt = (cvt->len_cvt / 8) * 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert71To41(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("7.1", "4.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 8); i; i--, src += 8, dst += 5) { + const float srcFC = src[2]; + const float srcSL = src[6]; + const float srcSR = src[7]; + dst[0] /* FL */ = (src[0] * 0.483000010f) + (srcFC * 0.340999991f) + (srcSL * 0.175999999f); + dst[1] /* FR */ = (src[1] * 0.483000010f) + (srcFC * 0.340999991f) + (srcSR * 0.175999999f); + dst[2] /* LFE */ = src[3]; + dst[3] /* BL */ = (src[4] * 0.483000010f) + (srcSL * 0.449000001f); + dst[4] /* BR */ = (src[5] * 0.483000010f) + (srcSR * 0.449000001f); + } + + cvt->len_cvt = (cvt->len_cvt / 8) * 5; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert71To51(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("7.1", "5.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 8); i; i--, src += 8, dst += 6) { + const float srcSL = src[6]; + const float srcSR = src[7]; + dst[0] /* FL */ = (src[0] * 0.518000007f) + (srcSL * 0.188999996f); + dst[1] /* FR */ = (src[1] * 0.518000007f) + (srcSR * 0.188999996f); + dst[2] /* FC */ = (src[2] * 0.518000007f); + dst[3] /* LFE */ = src[3]; + dst[4] /* BL */ = (src[4] * 0.518000007f) + (srcSL * 0.481999993f); + dst[5] /* BR */ = (src[5] * 0.518000007f) + (srcSR * 0.481999993f); + } + + cvt->len_cvt = (cvt->len_cvt / 8) * 6; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static void SDLCALL SDL_Convert71To61(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = (float *)cvt->buf; + const float *src = dst; + int i; + + LOG_DEBUG_CONVERT("7.1", "6.1"); + SDL_assert(format == AUDIO_F32SYS); + + for (i = cvt->len_cvt / (sizeof(float) * 8); i; i--, src += 8, dst += 7) { + const float srcBL = src[4]; + const float srcBR = src[5]; + dst[0] /* FL */ = (src[0] * 0.541000009f); + dst[1] /* FR */ = (src[1] * 0.541000009f); + dst[2] /* FC */ = (src[2] * 0.541000009f); + dst[3] /* LFE */ = src[3]; + dst[4] /* BC */ = (srcBL * 0.287999988f) + (srcBR * 0.287999988f); + dst[5] /* SL */ = (srcBL * 0.458999991f) + (src[6] * 0.541000009f); + dst[6] /* SR */ = (srcBR * 0.458999991f) + (src[7] * 0.541000009f); + } + + cvt->len_cvt = (cvt->len_cvt / 8) * 7; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static const SDL_AudioFilter channel_converters[8][8] = { /* [from][to] */ + { NULL, SDL_ConvertMonoToStereo, SDL_ConvertMonoTo21, SDL_ConvertMonoToQuad, SDL_ConvertMonoTo41, SDL_ConvertMonoTo51, SDL_ConvertMonoTo61, SDL_ConvertMonoTo71 }, + { SDL_ConvertStereoToMono, NULL, SDL_ConvertStereoTo21, SDL_ConvertStereoToQuad, SDL_ConvertStereoTo41, SDL_ConvertStereoTo51, SDL_ConvertStereoTo61, SDL_ConvertStereoTo71 }, + { SDL_Convert21ToMono, SDL_Convert21ToStereo, NULL, SDL_Convert21ToQuad, SDL_Convert21To41, SDL_Convert21To51, SDL_Convert21To61, SDL_Convert21To71 }, + { SDL_ConvertQuadToMono, SDL_ConvertQuadToStereo, SDL_ConvertQuadTo21, NULL, SDL_ConvertQuadTo41, SDL_ConvertQuadTo51, SDL_ConvertQuadTo61, SDL_ConvertQuadTo71 }, + { SDL_Convert41ToMono, SDL_Convert41ToStereo, SDL_Convert41To21, SDL_Convert41ToQuad, NULL, SDL_Convert41To51, SDL_Convert41To61, SDL_Convert41To71 }, + { SDL_Convert51ToMono, SDL_Convert51ToStereo, SDL_Convert51To21, SDL_Convert51ToQuad, SDL_Convert51To41, NULL, SDL_Convert51To61, SDL_Convert51To71 }, + { SDL_Convert61ToMono, SDL_Convert61ToStereo, SDL_Convert61To21, SDL_Convert61ToQuad, SDL_Convert61To41, SDL_Convert61To51, NULL, SDL_Convert61To71 }, + { SDL_Convert71ToMono, SDL_Convert71ToStereo, SDL_Convert71To21, SDL_Convert71ToQuad, SDL_Convert71To41, SDL_Convert71To51, SDL_Convert71To61, NULL } +}; + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_audio_resampler_filter.h b/third_party/SDL2/src/audio/SDL_audio_resampler_filter.h new file mode 100644 index 00000000000..be728eaf275 --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_audio_resampler_filter.h @@ -0,0 +1,1061 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* DO NOT EDIT, THIS FILE WAS GENERATED BY build-scripts/gen_audio_resampler_filter.c */ + +#define RESAMPLER_ZERO_CROSSINGS 5 +#define RESAMPLER_BITS_PER_SAMPLE 16 +#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1)) +#define RESAMPLER_FILTER_SIZE ((RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS) + 1) + +static const float ResamplerFilter[RESAMPLER_FILTER_SIZE] = { + 1.000000000f, 0.999993682f, 0.999974370f, 0.999941289f, 0.999894559f, + 0.999834180f, 0.999760151f, 0.999672413f, 0.999571025f, 0.999455988f, + 0.999327302f, 0.999184966f, 0.999028981f, 0.998859286f, 0.998676121f, + 0.998479128f, 0.998268604f, 0.998044431f, 0.997806668f, 0.997555375f, + 0.997290313f, 0.997011721f, 0.996719599f, 0.996413827f, 0.996094406f, + 0.995761573f, 0.995415151f, 0.995055199f, 0.994681656f, 0.994294584f, + 0.993894041f, 0.993480027f, 0.993052363f, 0.992611289f, 0.992156804f, + 0.991688788f, 0.991207361f, 0.990712583f, 0.990204275f, 0.989682615f, + 0.989147604f, 0.988599122f, 0.988037288f, 0.987462223f, 0.986873686f, + 0.986271918f, 0.985656738f, 0.985028386f, 0.984386861f, 0.983731806f, + 0.983063757f, 0.982382476f, 0.981687963f, 0.980980217f, 0.980259418f, + 0.979525447f, 0.978778243f, 0.978018105f, 0.977244914f, 0.976458490f, + 0.975659251f, 0.974846840f, 0.974021494f, 0.973183155f, 0.972331941f, + 0.971467674f, 0.970590651f, 0.969700634f, 0.968797863f, 0.967882276f, + 0.966953754f, 0.966012537f, 0.965058565f, 0.964091897f, 0.963112533f, + 0.962120414f, 0.961115718f, 0.960098326f, 0.959068418f, 0.958025992f, + 0.956970990f, 0.955903471f, 0.954823375f, 0.953730941f, 0.952626109f, + 0.951508820f, 0.950379193f, 0.949237227f, 0.948082924f, 0.946916521f, + 0.945737660f, 0.944546640f, 0.943343520f, 0.942128360f, 0.940900803f, + 0.939661384f, 0.938409984f, 0.937146366f, 0.935870886f, 0.934583426f, + 0.933284163f, 0.931972861f, 0.930649877f, 0.929314911f, 0.927968264f, + 0.926609993f, 0.925239921f, 0.923858225f, 0.922464967f, 0.921060085f, + 0.919643581f, 0.918215632f, 0.916776240f, 0.915325403f, 0.913863063f, + 0.912389517f, 0.910904646f, 0.909408391f, 0.907901049f, 0.906382322f, + 0.904852629f, 0.903311789f, 0.901759744f, 0.900196850f, 0.898622811f, + 0.897037864f, 0.895442069f, 0.893835366f, 0.892217875f, 0.890589595f, + 0.888950586f, 0.887300909f, 0.885640502f, 0.883969545f, 0.882288039f, + 0.880595982f, 0.878893554f, 0.877180517f, 0.875457227f, 0.873723626f, + 0.871979713f, 0.870225549f, 0.868461132f, 0.866686642f, 0.864902079f, + 0.863107383f, 0.861302733f, 0.859488070f, 0.857663572f, 0.855829120f, + 0.853984952f, 0.852130949f, 0.850267172f, 0.848393857f, 0.846510828f, + 0.844618261f, 0.842716157f, 0.840804636f, 0.838883698f, 0.836953342f, + 0.835013688f, 0.833064795f, 0.831106603f, 0.829139292f, 0.827162862f, + 0.825177312f, 0.823182821f, 0.821179330f, 0.819167018f, 0.817145705f, + 0.815115690f, 0.813076973f, 0.811029494f, 0.808973312f, 0.806908667f, + 0.804835379f, 0.802753687f, 0.800663531f, 0.798565030f, 0.796458125f, + 0.794343054f, 0.792219698f, 0.790088236f, 0.787948668f, 0.785801113f, + 0.783645451f, 0.781481922f, 0.779310465f, 0.777131259f, 0.774944246f, + 0.772749543f, 0.770547271f, 0.768337309f, 0.766119778f, 0.763894856f, + 0.761662483f, 0.759422719f, 0.757175624f, 0.754921377f, 0.752659857f, + 0.750391185f, 0.748115480f, 0.745832801f, 0.743543088f, 0.741246462f, + 0.738943100f, 0.736632884f, 0.734315932f, 0.731992364f, 0.729662120f, + 0.727325320f, 0.724982083f, 0.722632408f, 0.720276356f, 0.717914045f, + 0.715545416f, 0.713170588f, 0.710789680f, 0.708402693f, 0.706009746f, + 0.703610778f, 0.701205969f, 0.698795319f, 0.696378946f, 0.693956852f, + 0.691529095f, 0.689095736f, 0.686656833f, 0.684212506f, 0.681762815f, + 0.679307759f, 0.676847458f, 0.674381971f, 0.671911240f, 0.669435501f, + 0.666954637f, 0.664468944f, 0.661978245f, 0.659482718f, 0.656982541f, + 0.654477477f, 0.651967824f, 0.649453580f, 0.646934807f, 0.644411504f, + 0.641883910f, 0.639351964f, 0.636815608f, 0.634275198f, 0.631730616f, + 0.629181862f, 0.626629114f, 0.624072373f, 0.621511757f, 0.618947387f, + 0.616379082f, 0.613807201f, 0.611231565f, 0.608652413f, 0.606069744f, + 0.603483617f, 0.600894034f, 0.598301172f, 0.595705032f, 0.593105674f, + 0.590503156f, 0.587897599f, 0.585289061f, 0.582677484f, 0.580063045f, + 0.577445805f, 0.574825764f, 0.572203040f, 0.569577694f, 0.566949785f, + 0.564319372f, 0.561686456f, 0.559051216f, 0.556413651f, 0.553773820f, + 0.551131785f, 0.548487663f, 0.545841396f, 0.543193221f, 0.540543079f, + 0.537890971f, 0.535237134f, 0.532581568f, 0.529924273f, 0.527265370f, + 0.524604917f, 0.521942914f, 0.519279540f, 0.516614795f, 0.513948679f, + 0.511281490f, 0.508612931f, 0.505943298f, 0.503272593f, 0.500600994f, + 0.497928351f, 0.495254934f, 0.492580622f, 0.489905566f, 0.487229884f, + 0.484553576f, 0.481876701f, 0.479199320f, 0.476521552f, 0.473843396f, + 0.471164882f, 0.468486160f, 0.465807229f, 0.463128209f, 0.460449100f, + 0.457770079f, 0.455091029f, 0.452412128f, 0.449733406f, 0.447054923f, + 0.444376737f, 0.441698909f, 0.439021617f, 0.436344713f, 0.433668375f, + 0.430992693f, 0.428317666f, 0.425643355f, 0.422969848f, 0.420297176f, + 0.417625397f, 0.414954633f, 0.412284881f, 0.409616232f, 0.406948745f, + 0.404282451f, 0.401617438f, 0.398953736f, 0.396291435f, 0.393630594f, + 0.390971363f, 0.388313591f, 0.385657459f, 0.383003026f, 0.380350292f, + 0.377699375f, 0.375050306f, 0.372403204f, 0.369758040f, 0.367114902f, + 0.364473879f, 0.361834973f, 0.359198302f, 0.356563985f, 0.353931844f, + 0.351302117f, 0.348674864f, 0.346050024f, 0.343427807f, 0.340808123f, + 0.338191152f, 0.335576862f, 0.332965344f, 0.330356658f, 0.327750862f, + 0.325147986f, 0.322548091f, 0.319951355f, 0.317357630f, 0.314767033f, + 0.312179655f, 0.309595555f, 0.307014734f, 0.304437339f, 0.301863313f, + 0.299292803f, 0.296725839f, 0.294162393f, 0.291602641f, 0.289046586f, + 0.286494225f, 0.283945769f, 0.281401068f, 0.278860301f, 0.276323408f, + 0.273790598f, 0.271261781f, 0.268737078f, 0.266216546f, 0.263700217f, + 0.261188149f, 0.258680373f, 0.256176978f, 0.253677934f, 0.251183391f, + 0.248693451f, 0.246207923f, 0.243727028f, 0.241250798f, 0.238779247f, + 0.236312449f, 0.233850464f, 0.231393293f, 0.228941023f, 0.226493701f, + 0.224051371f, 0.221614078f, 0.219181836f, 0.216754735f, 0.214332923f, + 0.211916193f, 0.209504753f, 0.207098618f, 0.204697832f, 0.202302471f, + 0.199912533f, 0.197528124f, 0.195149198f, 0.192775860f, 0.190408155f, + 0.188046113f, 0.185689807f, 0.183339253f, 0.180994540f, 0.178655609f, + 0.176322535f, 0.173995405f, 0.171674222f, 0.169359058f, 0.167049929f, + 0.164746925f, 0.162450001f, 0.160159275f, 0.157874763f, 0.155596510f, + 0.153324530f, 0.151058972f, 0.148799688f, 0.146546826f, 0.144300416f, + 0.142060474f, 0.139827073f, 0.137600228f, 0.135380000f, 0.133166388f, + 0.130959451f, 0.128759250f, 0.126565769f, 0.124379098f, 0.122199245f, + 0.120026320f, 0.117860198f, 0.115701027f, 0.113548823f, 0.111403592f, + 0.109265402f, 0.107134290f, 0.105010264f, 0.102893390f, 0.100783676f, + 0.098681159f, 0.096585885f, 0.094497882f, 0.092417173f, 0.090343870f, + 0.088277847f, 0.086219221f, 0.084168032f, 0.082124293f, 0.080088042f, + 0.078059308f, 0.076038122f, 0.074024513f, 0.072018512f, 0.070020139f, + 0.068029441f, 0.066046432f, 0.064071149f, 0.062103685f, 0.060143925f, + 0.058191977f, 0.056247860f, 0.054311592f, 0.052383222f, 0.050462760f, + 0.048550237f, 0.046645675f, 0.044749107f, 0.042860553f, 0.040980037f, + 0.039107583f, 0.037243221f, 0.035387039f, 0.033538923f, 0.031698968f, + 0.029867193f, 0.028043624f, 0.026228283f, 0.024421191f, 0.022622371f, + 0.020831848f, 0.019049639f, 0.017275762f, 0.015510243f, 0.013753103f, + 0.012004361f, 0.010264101f, 0.008532210f, 0.006808777f, 0.005093819f, + 0.003387353f, 0.001689399f, -0.000000024f, -0.001680900f, -0.003353210f, + -0.005016938f, -0.006672067f, -0.008318579f, -0.009956459f, -0.011585629f, + -0.013206195f, -0.014818084f, -0.016421281f, -0.018015765f, -0.019601526f, + -0.021178551f, -0.022746822f, -0.024306327f, -0.025857056f, -0.027398987f, + -0.028932119f, -0.030456433f, -0.031971917f, -0.033478502f, -0.034976289f, + -0.036465216f, -0.037945267f, -0.039416436f, -0.040878706f, -0.042332072f, + -0.043776520f, -0.045212042f, -0.046638630f, -0.048056271f, -0.049464963f, + -0.050864697f, -0.052255459f, -0.053637192f, -0.055009995f, -0.056373812f, + -0.057728622f, -0.059074435f, -0.060411237f, -0.061739020f, -0.063057788f, + -0.064367518f, -0.065668218f, -0.066959888f, -0.068242513f, -0.069516085f, + -0.070780613f, -0.072036028f, -0.073282443f, -0.074519798f, -0.075748093f, + -0.076967306f, -0.078177467f, -0.079378553f, -0.080570564f, -0.081753515f, + -0.082927369f, -0.084092163f, -0.085247882f, -0.086394526f, -0.087532081f, + -0.088660523f, -0.089779936f, -0.090890266f, -0.091991536f, -0.093083732f, + -0.094166860f, -0.095240898f, -0.096305899f, -0.097361818f, -0.098408684f, + -0.099446490f, -0.100475237f, -0.101494931f, -0.102505587f, -0.103507154f, + -0.104499720f, -0.105483264f, -0.106457770f, -0.107423261f, -0.108379729f, + -0.109327182f, -0.110265635f, -0.111195073f, -0.112115517f, -0.113026999f, + -0.113929473f, -0.114823014f, -0.115707509f, -0.116583094f, -0.117449738f, + -0.118307441f, -0.119156219f, -0.119996056f, -0.120826989f, -0.121649019f, + -0.122462146f, -0.123266406f, -0.124061778f, -0.124848284f, -0.125625938f, + -0.126394749f, -0.127154693f, -0.127905846f, -0.128648207f, -0.129381746f, + -0.130106509f, -0.130822510f, -0.131529734f, -0.132228225f, -0.132917970f, + -0.133599013f, -0.134271339f, -0.134934962f, -0.135589913f, -0.136236191f, + -0.136873797f, -0.137502789f, -0.138123170f, -0.138734937f, -0.139338136f, + -0.139932722f, -0.140518770f, -0.141096294f, -0.141665265f, -0.142225727f, + -0.142777696f, -0.143321201f, -0.143856242f, -0.144382849f, -0.144900993f, + -0.145410761f, -0.145912141f, -0.146405146f, -0.146889821f, -0.147366136f, + -0.147834152f, -0.148293883f, -0.148745313f, -0.149188504f, -0.149623469f, + -0.150050193f, -0.150468737f, -0.150879115f, -0.151281342f, -0.151675433f, + -0.152061403f, -0.152439296f, -0.152809098f, -0.153170869f, -0.153524607f, + -0.153870359f, -0.154208109f, -0.154537901f, -0.154859766f, -0.155173704f, + -0.155479759f, -0.155777946f, -0.156068295f, -0.156350806f, -0.156625539f, + -0.156892478f, -0.157151699f, -0.157403171f, -0.157646939f, -0.157883018f, + -0.158111468f, -0.158332288f, -0.158545509f, -0.158751160f, -0.158949256f, + -0.159139827f, -0.159322888f, -0.159498483f, -0.159666643f, -0.159827381f, + -0.159980699f, -0.160126686f, -0.160265297f, -0.160396621f, -0.160520658f, + -0.160637438f, -0.160746962f, -0.160849288f, -0.160944447f, -0.161032468f, + -0.161113337f, -0.161187142f, -0.161253884f, -0.161313564f, -0.161366254f, + -0.161411941f, -0.161450699f, -0.161482543f, -0.161507472f, -0.161525562f, + -0.161536828f, -0.161541268f, -0.161538944f, -0.161529869f, -0.161514089f, + -0.161491618f, -0.161462501f, -0.161426738f, -0.161384419f, -0.161335513f, + -0.161280081f, -0.161218151f, -0.161149755f, -0.161074907f, -0.160993651f, + -0.160906032f, -0.160812065f, -0.160711765f, -0.160605207f, -0.160492390f, + -0.160373345f, -0.160248131f, -0.160116762f, -0.159979254f, -0.159835666f, + -0.159686014f, -0.159530357f, -0.159368694f, -0.159201056f, -0.159027517f, + -0.158848062f, -0.158662766f, -0.158471599f, -0.158274680f, -0.158071980f, + -0.157863557f, -0.157649443f, -0.157429650f, -0.157204241f, -0.156973228f, + -0.156736642f, -0.156494558f, -0.156246960f, -0.155993909f, -0.155735433f, + -0.155471563f, -0.155202329f, -0.154927775f, -0.154647917f, -0.154362813f, + -0.154072478f, -0.153776988f, -0.153476328f, -0.153170541f, -0.152859688f, + -0.152543753f, -0.152222827f, -0.151896924f, -0.151566073f, -0.151230305f, + -0.150889665f, -0.150544196f, -0.150193915f, -0.149838865f, -0.149479061f, + -0.149114594f, -0.148745432f, -0.148371637f, -0.147993281f, -0.147610337f, + -0.147222877f, -0.146830946f, -0.146434546f, -0.146033719f, -0.145628527f, + -0.145218968f, -0.144805118f, -0.144386992f, -0.143964618f, -0.143538073f, + -0.143107325f, -0.142672464f, -0.142233476f, -0.141790435f, -0.141343385f, + -0.140892327f, -0.140437320f, -0.139978394f, -0.139515579f, -0.139048934f, + -0.138578460f, -0.138104215f, -0.137626216f, -0.137144551f, -0.136659175f, + -0.136170194f, -0.135677606f, -0.135181442f, -0.134681761f, -0.134178594f, + -0.133671984f, -0.133161947f, -0.132648528f, -0.132131740f, -0.131611660f, + -0.131088302f, -0.130561695f, -0.130031943f, -0.129498973f, -0.128962860f, + -0.128423676f, -0.127881393f, -0.127336115f, -0.126787826f, -0.126236603f, + -0.125682443f, -0.125125393f, -0.124565504f, -0.124002807f, -0.123437323f, + -0.122869089f, -0.122298159f, -0.121724561f, -0.121148311f, -0.120569460f, + -0.119988061f, -0.119404130f, -0.118817687f, -0.118228793f, -0.117637470f, + -0.117043748f, -0.116447672f, -0.115849286f, -0.115248613f, -0.114645667f, + -0.114040568f, -0.113433234f, -0.112823755f, -0.112212166f, -0.111598492f, + -0.110982776f, -0.110365056f, -0.109745361f, -0.109123722f, -0.108500175f, + -0.107874751f, -0.107247494f, -0.106618427f, -0.105987601f, -0.105355024f, + -0.104720749f, -0.104084812f, -0.103447236f, -0.102808066f, -0.102167316f, + -0.101525046f, -0.100881256f, -0.100236014f, -0.099589340f, -0.098941252f, + -0.098291807f, -0.097641021f, -0.096988983f, -0.096335620f, -0.095681041f, + -0.095025249f, -0.094368286f, -0.093710184f, -0.093050972f, -0.092390701f, + -0.091729380f, -0.091067046f, -0.090403758f, -0.089739501f, -0.089074343f, + -0.088408306f, -0.087741412f, -0.087073699f, -0.086405218f, -0.085735977f, + -0.085065998f, -0.084395349f, -0.083724037f, -0.083052084f, -0.082379535f, + -0.081706434f, -0.081032783f, -0.080358639f, -0.079684012f, -0.079008937f, + -0.078333504f, -0.077657640f, -0.076981425f, -0.076304883f, -0.075628042f, + -0.074950956f, -0.074273616f, -0.073596083f, -0.072918370f, -0.072240517f, + -0.071562558f, -0.070884496f, -0.070206381f, -0.069528244f, -0.068850100f, + -0.068171993f, -0.067493953f, -0.066815972f, -0.066138126f, -0.065460421f, + -0.064782880f, -0.064105548f, -0.063428439f, -0.062751584f, -0.062075011f, + -0.061398748f, -0.060722828f, -0.060047265f, -0.059372153f, -0.058697399f, + -0.058023106f, -0.057349272f, -0.056675948f, -0.056003150f, -0.055330887f, + -0.054659221f, -0.053988155f, -0.053317714f, -0.052647941f, -0.051978838f, + -0.051310450f, -0.050642796f, -0.049975898f, -0.049309790f, -0.048644483f, + -0.047980014f, -0.047316402f, -0.046653673f, -0.045991853f, -0.045330971f, + -0.044671040f, -0.044012092f, -0.043354150f, -0.042697236f, -0.042041373f, + -0.041386627f, -0.040732939f, -0.040080376f, -0.039428953f, -0.038778704f, + -0.038129643f, -0.037481792f, -0.036835186f, -0.036189832f, -0.035545766f, + -0.034902997f, -0.034261558f, -0.033621464f, -0.032982741f, -0.032345407f, + -0.031709481f, -0.031074993f, -0.030441960f, -0.029810399f, -0.029180335f, + -0.028551787f, -0.027924776f, -0.027299322f, -0.026675448f, -0.026053172f, + -0.025432510f, -0.024813488f, -0.024196124f, -0.023580479f, -0.022966485f, + -0.022354206f, -0.021743659f, -0.021134868f, -0.020527845f, -0.019922616f, + -0.019319192f, -0.018717598f, -0.018117845f, -0.017519956f, -0.016923945f, + -0.016329836f, -0.015737642f, -0.015147380f, -0.014559067f, -0.013972721f, + -0.013388360f, -0.012805998f, -0.012225654f, -0.011647343f, -0.011071082f, + -0.010496887f, -0.009924773f, -0.009354758f, -0.008786854f, -0.008221081f, + -0.007657450f, -0.007096022f, -0.006536725f, -0.005979617f, -0.005424712f, + -0.004872025f, -0.004321571f, -0.003773364f, -0.003227417f, -0.002683746f, + -0.002142363f, -0.001603282f, -0.001066516f, -0.000532080f, 0.000000015f, + 0.000529755f, 0.001057127f, 0.001582118f, 0.002104717f, 0.002624909f, + 0.003142685f, 0.003658031f, 0.004170935f, 0.004681387f, 0.005189373f, + 0.005694883f, 0.006197905f, 0.006698429f, 0.007196404f, 0.007691898f, + 0.008184860f, 0.008675281f, 0.009163151f, 0.009648458f, 0.010131192f, + 0.010611345f, 0.011088905f, 0.011563865f, 0.012036213f, 0.012505942f, + 0.012973041f, 0.013437501f, 0.013899315f, 0.014358475f, 0.014814967f, + 0.015268789f, 0.015719930f, 0.016168380f, 0.016614137f, 0.017057184f, + 0.017497523f, 0.017935142f, 0.018370032f, 0.018802188f, 0.019231608f, + 0.019658273f, 0.020082152f, 0.020503307f, 0.020921690f, 0.021337299f, + 0.021750130f, 0.022160176f, 0.022567427f, 0.022971880f, 0.023373535f, + 0.023772376f, 0.024168408f, 0.024561619f, 0.024952007f, 0.025339566f, + 0.025724288f, 0.026106175f, 0.026485221f, 0.026861422f, 0.027234772f, + 0.027605265f, 0.027972901f, 0.028337676f, 0.028699588f, 0.029058624f, + 0.029414795f, 0.029768089f, 0.030118505f, 0.030466037f, 0.030810660f, + 0.031152423f, 0.031491302f, 0.031827286f, 0.032160383f, 0.032490581f, + 0.032817882f, 0.033142287f, 0.033463787f, 0.033782389f, 0.034098089f, + 0.034410883f, 0.034720775f, 0.035027757f, 0.035331838f, 0.035633009f, + 0.035931274f, 0.036226626f, 0.036519073f, 0.036808614f, 0.037095241f, + 0.037378959f, 0.037659772f, 0.037937686f, 0.038212679f, 0.038484775f, + 0.038753960f, 0.039020218f, 0.039283592f, 0.039544068f, 0.039801639f, + 0.040056318f, 0.040308096f, 0.040556971f, 0.040802956f, 0.041046046f, + 0.041286245f, 0.041523557f, 0.041757982f, 0.041989524f, 0.042218179f, + 0.042443957f, 0.042666860f, 0.042886890f, 0.043104045f, 0.043318339f, + 0.043529764f, 0.043738328f, 0.043944035f, 0.044146888f, 0.044346895f, + 0.044544052f, 0.044738363f, 0.044929843f, 0.045118481f, 0.045304272f, + 0.045487255f, 0.045667417f, 0.045844764f, 0.046019293f, 0.046191018f, + 0.046359941f, 0.046526067f, 0.046689399f, 0.046849940f, 0.047007702f, + 0.047162689f, 0.047314901f, 0.047464348f, 0.047611035f, 0.047754966f, + 0.047896147f, 0.048034586f, 0.048170291f, 0.048303265f, 0.048433512f, + 0.048561048f, 0.048685864f, 0.048807982f, 0.048927400f, 0.049044125f, + 0.049158167f, 0.049269531f, 0.049378205f, 0.049484238f, 0.049587611f, + 0.049688339f, 0.049786422f, 0.049881872f, 0.049974691f, 0.050064899f, + 0.050152492f, 0.050237484f, 0.050319877f, 0.050399683f, 0.050476916f, + 0.050551571f, 0.050623666f, 0.050693203f, 0.050760195f, 0.050824653f, + 0.050886583f, 0.050945986f, 0.051002879f, 0.051057268f, 0.051109165f, + 0.051158577f, 0.051205512f, 0.051249981f, 0.051291991f, 0.051331542f, + 0.051368665f, 0.051403359f, 0.051435627f, 0.051465489f, 0.051492948f, + 0.051518012f, 0.051540703f, 0.051561009f, 0.051578961f, 0.051594563f, + 0.051607810f, 0.051618744f, 0.051627338f, 0.051633626f, 0.051637612f, + 0.051639307f, 0.051638719f, 0.051635865f, 0.051630747f, 0.051623378f, + 0.051613763f, 0.051601931f, 0.051587880f, 0.051571615f, 0.051553156f, + 0.051532514f, 0.051509693f, 0.051484708f, 0.051457576f, 0.051428299f, + 0.051396891f, 0.051363368f, 0.051327739f, 0.051290002f, 0.051250193f, + 0.051208302f, 0.051164351f, 0.051118344f, 0.051070303f, 0.051020239f, + 0.050968144f, 0.050914053f, 0.050857969f, 0.050799899f, 0.050739862f, + 0.050677869f, 0.050613929f, 0.050548054f, 0.050480254f, 0.050410546f, + 0.050338943f, 0.050265454f, 0.050190084f, 0.050112855f, 0.050033774f, + 0.049952857f, 0.049870111f, 0.049785554f, 0.049699202f, 0.049611051f, + 0.049521122f, 0.049429435f, 0.049335998f, 0.049240820f, 0.049143907f, + 0.049045283f, 0.048944961f, 0.048842940f, 0.048739251f, 0.048633892f, + 0.048526883f, 0.048418235f, 0.048307955f, 0.048196062f, 0.048082568f, + 0.047967490f, 0.047850832f, 0.047732603f, 0.047612831f, 0.047491513f, + 0.047368675f, 0.047244325f, 0.047118478f, 0.046991132f, 0.046862319f, + 0.046732042f, 0.046600312f, 0.046467155f, 0.046332560f, 0.046196572f, + 0.046059173f, 0.045920394f, 0.045780238f, 0.045638733f, 0.045495875f, + 0.045351684f, 0.045206167f, 0.045059349f, 0.044911236f, 0.044761848f, + 0.044611182f, 0.044459261f, 0.044306096f, 0.044151701f, 0.043996092f, + 0.043839272f, 0.043681268f, 0.043522079f, 0.043361723f, 0.043200217f, + 0.043037571f, 0.042873796f, 0.042708915f, 0.042542927f, 0.042375844f, + 0.042207699f, 0.042038482f, 0.041868217f, 0.041696910f, 0.041524585f, + 0.041351244f, 0.041176908f, 0.041001581f, 0.040825289f, 0.040648032f, + 0.040469825f, 0.040290687f, 0.040110629f, 0.039929654f, 0.039747790f, + 0.039565038f, 0.039381415f, 0.039196935f, 0.039011609f, 0.038825445f, + 0.038638465f, 0.038450673f, 0.038262092f, 0.038072724f, 0.037882581f, + 0.037691690f, 0.037500042f, 0.037307668f, 0.037114572f, 0.036920771f, + 0.036726266f, 0.036531083f, 0.036335230f, 0.036138717f, 0.035941560f, + 0.035743766f, 0.035545345f, 0.035346344f, 0.035146721f, 0.034946512f, + 0.034745730f, 0.034544386f, 0.034342494f, 0.034140065f, 0.033937111f, + 0.033733644f, 0.033529676f, 0.033325221f, 0.033120286f, 0.032914892f, + 0.032709036f, 0.032502741f, 0.032296017f, 0.032088876f, 0.031881329f, + 0.031673383f, 0.031465057f, 0.031256359f, 0.031047301f, 0.030837893f, + 0.030628148f, 0.030418083f, 0.030207697f, 0.029997014f, 0.029786035f, + 0.029574780f, 0.029363252f, 0.029151469f, 0.028939439f, 0.028727176f, + 0.028514685f, 0.028301982f, 0.028089074f, 0.027875982f, 0.027662706f, + 0.027449260f, 0.027235655f, 0.027021904f, 0.026808018f, 0.026594002f, + 0.026379872f, 0.026165638f, 0.025951311f, 0.025736896f, 0.025522409f, + 0.025307864f, 0.025093259f, 0.024878617f, 0.024663944f, 0.024449248f, + 0.024234539f, 0.024019832f, 0.023805158f, 0.023590479f, 0.023375830f, + 0.023161218f, 0.022946658f, 0.022732155f, 0.022517720f, 0.022303363f, + 0.022089096f, 0.021874927f, 0.021660868f, 0.021446921f, 0.021233102f, + 0.021019425f, 0.020805888f, 0.020592507f, 0.020379292f, 0.020166250f, + 0.019953389f, 0.019740723f, 0.019528257f, 0.019316001f, 0.019103965f, + 0.018892156f, 0.018680587f, 0.018469261f, 0.018258194f, 0.018047387f, + 0.017836852f, 0.017626595f, 0.017416634f, 0.017206967f, 0.016997607f, + 0.016788563f, 0.016579840f, 0.016371451f, 0.016163401f, 0.015955698f, + 0.015748354f, 0.015541371f, 0.015334761f, 0.015128531f, 0.014922690f, + 0.014717245f, 0.014512201f, 0.014307571f, 0.014103360f, 0.013899575f, + 0.013696224f, 0.013493315f, 0.013290856f, 0.013088853f, 0.012887316f, + 0.012686247f, 0.012485661f, 0.012285583f, 0.012085971f, 0.011886863f, + 0.011688258f, 0.011490168f, 0.011292599f, 0.011095556f, 0.010899050f, + 0.010703083f, 0.010507663f, 0.010312798f, 0.010118493f, 0.009924755f, + 0.009731592f, 0.009539006f, 0.009347008f, 0.009155600f, 0.008964794f, + 0.008774590f, 0.008584999f, 0.008396022f, 0.008207668f, 0.008019943f, + 0.007832851f, 0.007646400f, 0.007460595f, 0.007275441f, 0.007090943f, + 0.006907108f, 0.006723941f, 0.006541446f, 0.006359630f, 0.006178498f, + 0.005998055f, 0.005818305f, 0.005639255f, 0.005460909f, 0.005283272f, + 0.005106349f, 0.004930146f, 0.004754666f, 0.004579914f, 0.004405896f, + 0.004232615f, 0.004060077f, 0.003888285f, 0.003717245f, 0.003546960f, + 0.003377435f, 0.003208674f, 0.003040682f, 0.002873462f, 0.002707019f, + 0.002541356f, 0.002376478f, 0.002212389f, 0.002049116f, 0.001886615f, + 0.001724914f, 0.001564016f, 0.001403926f, 0.001244646f, 0.001086180f, + 0.000928532f, 0.000771705f, 0.000615702f, 0.000460527f, 0.000306183f, + 0.000152673f, -0.000000001f, -0.000151834f, -0.000302824f, -0.000452968f, + -0.000602263f, -0.000750707f, -0.000898296f, -0.001045028f, -0.001190900f, + -0.001335910f, -0.001480055f, -0.001623332f, -0.001765741f, -0.001907276f, + -0.002047938f, -0.002187723f, -0.002326628f, -0.002464653f, -0.002601795f, + -0.002738052f, -0.002873422f, -0.003007903f, -0.003141493f, -0.003274190f, + -0.003405993f, -0.003536900f, -0.003666909f, -0.003796018f, -0.003924227f, + -0.004051533f, -0.004177936f, -0.004303433f, -0.004428024f, -0.004551707f, + -0.004674482f, -0.004796346f, -0.004917298f, -0.005037338f, -0.005156465f, + -0.005274678f, -0.005391975f, -0.005508356f, -0.005623801f, -0.005738347f, + -0.005851975f, -0.005964684f, -0.006076474f, -0.006187343f, -0.006297291f, + -0.006406318f, -0.006514424f, -0.006621608f, -0.006727869f, -0.006833209f, + -0.006937624f, -0.007041118f, -0.007143687f, -0.007245334f, -0.007346058f, + -0.007445859f, -0.007544736f, -0.007642691f, -0.007739722f, -0.007835831f, + -0.007931018f, -0.008025283f, -0.008118626f, -0.008211047f, -0.008302549f, + -0.008393129f, -0.008482790f, -0.008571531f, -0.008659353f, -0.008746257f, + -0.008832245f, -0.008917316f, -0.009001471f, -0.009084711f, -0.009167036f, + -0.009248449f, -0.009328948f, -0.009408538f, -0.009487216f, -0.009564986f, + -0.009641849f, -0.009717803f, -0.009792852f, -0.009866998f, -0.009940239f, + -0.010012579f, -0.010084019f, -0.010154560f, -0.010224204f, -0.010292951f, + -0.010360803f, -0.010427763f, -0.010493831f, -0.010558996f, -0.010623286f, + -0.010686691f, -0.010749210f, -0.010810846f, -0.010871602f, -0.010931478f, + -0.010990476f, -0.011048601f, -0.011105850f, -0.011162230f, -0.011217739f, + -0.011272381f, -0.011326157f, -0.011379071f, -0.011431124f, -0.011482318f, + -0.011532655f, -0.011582140f, -0.011630770f, -0.011678550f, -0.011725485f, + -0.011771576f, -0.011816822f, -0.011861229f, -0.011904799f, -0.011947533f, + -0.011989436f, -0.012030509f, -0.012070752f, -0.012110173f, -0.012148771f, + -0.012186551f, -0.012223513f, -0.012259661f, -0.012295000f, -0.012329529f, + -0.012363252f, -0.012396174f, -0.012428297f, -0.012459621f, -0.012490152f, + -0.012519893f, -0.012548844f, -0.012577013f, -0.012604399f, -0.012631006f, + -0.012656839f, -0.012681897f, -0.012706185f, -0.012729709f, -0.012752469f, + -0.012774469f, -0.012795713f, -0.012816204f, -0.012835944f, -0.012854930f, + -0.012873179f, -0.012890689f, -0.012907463f, -0.012923501f, -0.012938812f, + -0.012953395f, -0.012967254f, -0.012980393f, -0.012992817f, -0.013004529f, + -0.013015532f, -0.013025828f, -0.013035421f, -0.013044316f, -0.013052518f, + -0.013060026f, -0.013066847f, -0.013072984f, -0.013078442f, -0.013083221f, + -0.013087329f, -0.013090767f, -0.013093537f, -0.013095647f, -0.013097100f, + -0.013097897f, -0.013098043f, -0.013097542f, -0.013096399f, -0.013094617f, + -0.013092197f, -0.013089147f, -0.013085471f, -0.013081170f, -0.013076247f, + -0.013070711f, -0.013064560f, -0.013057803f, -0.013050442f, -0.013042479f, + -0.013033919f, -0.013024768f, -0.013015027f, -0.013004702f, -0.012993797f, + -0.012982314f, -0.012970260f, -0.012957636f, -0.012944449f, -0.012930701f, + -0.012916395f, -0.012901539f, -0.012886133f, -0.012870182f, -0.012853689f, + -0.012836664f, -0.012819104f, -0.012801019f, -0.012782406f, -0.012763276f, + -0.012743629f, -0.012723471f, -0.012702805f, -0.012681637f, -0.012659966f, + -0.012637801f, -0.012615148f, -0.012592005f, -0.012568381f, -0.012544277f, + -0.012519698f, -0.012494650f, -0.012469133f, -0.012443157f, -0.012416720f, + -0.012389832f, -0.012362492f, -0.012334707f, -0.012306482f, -0.012277817f, + -0.012248720f, -0.012219194f, -0.012189244f, -0.012158873f, -0.012128084f, + -0.012096884f, -0.012065274f, -0.012033261f, -0.012000849f, -0.011968041f, + -0.011934839f, -0.011901250f, -0.011867279f, -0.011832927f, -0.011798202f, + -0.011763104f, -0.011727640f, -0.011691812f, -0.011655626f, -0.011619086f, + -0.011582195f, -0.011544957f, -0.011507377f, -0.011469459f, -0.011431207f, + -0.011392625f, -0.011353718f, -0.011314487f, -0.011274938f, -0.011235079f, + -0.011194907f, -0.011154431f, -0.011113651f, -0.011072575f, -0.011031206f, + -0.010989547f, -0.010947601f, -0.010905375f, -0.010862871f, -0.010820094f, + -0.010777046f, -0.010733733f, -0.010690158f, -0.010646327f, -0.010602240f, + -0.010557905f, -0.010513324f, -0.010468500f, -0.010423439f, -0.010378144f, + -0.010332618f, -0.010286866f, -0.010240891f, -0.010194698f, -0.010148291f, + -0.010101672f, -0.010054846f, -0.010007816f, -0.009960588f, -0.009913164f, + -0.009865548f, -0.009817744f, -0.009769755f, -0.009721586f, -0.009673241f, + -0.009624721f, -0.009576033f, -0.009527179f, -0.009478163f, -0.009428989f, + -0.009379660f, -0.009330180f, -0.009280552f, -0.009230781f, -0.009180869f, + -0.009130822f, -0.009080641f, -0.009030331f, -0.008979894f, -0.008929336f, + -0.008878659f, -0.008827867f, -0.008776963f, -0.008725950f, -0.008674833f, + -0.008623619f, -0.008572303f, -0.008520893f, -0.008469390f, -0.008417801f, + -0.008366127f, -0.008314372f, -0.008262540f, -0.008210634f, -0.008158657f, + -0.008106613f, -0.008054503f, -0.008002332f, -0.007950104f, -0.007897821f, + -0.007845488f, -0.007793106f, -0.007740679f, -0.007688211f, -0.007635703f, + -0.007583159f, -0.007530585f, -0.007477981f, -0.007425350f, -0.007372697f, + -0.007320023f, -0.007267332f, -0.007214627f, -0.007161912f, -0.007109188f, + -0.007056459f, -0.007003729f, -0.006951000f, -0.006898273f, -0.006845553f, + -0.006792843f, -0.006740147f, -0.006687465f, -0.006634800f, -0.006582157f, + -0.006529537f, -0.006476944f, -0.006424380f, -0.006371849f, -0.006319351f, + -0.006266891f, -0.006214471f, -0.006162094f, -0.006109761f, -0.006057477f, + -0.006005243f, -0.005953063f, -0.005900938f, -0.005848871f, -0.005796865f, + -0.005744927f, -0.005693051f, -0.005641241f, -0.005589503f, -0.005537837f, + -0.005486248f, -0.005434736f, -0.005383304f, -0.005331955f, -0.005280690f, + -0.005229514f, -0.005178426f, -0.005127430f, -0.005076529f, -0.005025723f, + -0.004975016f, -0.004924410f, -0.004873907f, -0.004823509f, -0.004773218f, + -0.004723036f, -0.004672966f, -0.004623009f, -0.004573168f, -0.004523444f, + -0.004473840f, -0.004424357f, -0.004374999f, -0.004325765f, -0.004276660f, + -0.004227683f, -0.004178838f, -0.004130126f, -0.004081549f, -0.004033110f, + -0.003984808f, -0.003936647f, -0.003888629f, -0.003840754f, -0.003793026f, + -0.003745445f, -0.003698014f, -0.003650733f, -0.003603605f, -0.003556631f, + -0.003509813f, -0.003463153f, -0.003416652f, -0.003370312f, -0.003324133f, + -0.003278119f, -0.003232269f, -0.003186587f, -0.003141073f, -0.003095729f, + -0.003050560f, -0.003005560f, -0.002960733f, -0.002916081f, -0.002871606f, + -0.002827310f, -0.002783192f, -0.002739255f, -0.002695500f, -0.002651928f, + -0.002608541f, -0.002565339f, -0.002522324f, -0.002479498f, -0.002436860f, + -0.002394413f, -0.002352157f, -0.002310094f, -0.002268225f, -0.002226550f, + -0.002185071f, -0.002143790f, -0.002102705f, -0.002061821f, -0.002021135f, + -0.001980651f, -0.001940368f, -0.001900289f, -0.001860412f, -0.001820740f, + -0.001781274f, -0.001742014f, -0.001702961f, -0.001664116f, -0.001625479f, + -0.001587052f, -0.001548836f, -0.001510830f, -0.001473036f, -0.001435455f, + -0.001398086f, -0.001360932f, -0.001323992f, -0.001287267f, -0.001250757f, + -0.001214464f, -0.001178389f, -0.001142530f, -0.001106890f, -0.001071468f, + -0.001036266f, -0.001001283f, -0.000966520f, -0.000931978f, -0.000897657f, + -0.000863557f, -0.000829685f, -0.000796029f, -0.000762597f, -0.000729387f, + -0.000696401f, -0.000663639f, -0.000631101f, -0.000598788f, -0.000566699f, + -0.000534836f, -0.000503197f, -0.000471784f, -0.000440597f, -0.000409636f, + -0.000378901f, -0.000348393f, -0.000318111f, -0.000288056f, -0.000258228f, + -0.000228626f, -0.000199252f, -0.000170105f, -0.000141186f, -0.000112493f, + -0.000084028f, -0.000055791f, -0.000027781f, 0.000000002f, 0.000027557f, + 0.000054884f, 0.000081984f, 0.000108857f, 0.000135502f, 0.000161920f, + 0.000188111f, 0.000214075f, 0.000239812f, 0.000265322f, 0.000290606f, + 0.000315663f, 0.000340493f, 0.000365097f, 0.000389476f, 0.000413628f, + 0.000437555f, 0.000461256f, 0.000484733f, 0.000507984f, 0.000531011f, + 0.000553814f, 0.000576393f, 0.000598748f, 0.000620879f, 0.000642788f, + 0.000664473f, 0.000685933f, 0.000707174f, 0.000728194f, 0.000748993f, + 0.000769570f, 0.000789927f, 0.000810064f, 0.000829982f, 0.000849680f, + 0.000869160f, 0.000888421f, 0.000907465f, 0.000926291f, 0.000944901f, + 0.000963294f, 0.000981472f, 0.000999434f, 0.001017181f, 0.001034715f, + 0.001052034f, 0.001069141f, 0.001086035f, 0.001102717f, 0.001119188f, + 0.001135448f, 0.001151499f, 0.001167339f, 0.001182971f, 0.001198395f, + 0.001213611f, 0.001228620f, 0.001243423f, 0.001258021f, 0.001272413f, + 0.001286602f, 0.001300586f, 0.001314368f, 0.001327948f, 0.001341327f, + 0.001354505f, 0.001367483f, 0.001380263f, 0.001392843f, 0.001405226f, + 0.001417413f, 0.001429403f, 0.001441198f, 0.001452798f, 0.001464205f, + 0.001475418f, 0.001486440f, 0.001497271f, 0.001507911f, 0.001518361f, + 0.001528623f, 0.001538696f, 0.001548581f, 0.001558281f, 0.001567796f, + 0.001577127f, 0.001586274f, 0.001595238f, 0.001604020f, 0.001612622f, + 0.001621043f, 0.001629285f, 0.001637349f, 0.001645236f, 0.001652946f, + 0.001660481f, 0.001667841f, 0.001675027f, 0.001682041f, 0.001688883f, + 0.001695554f, 0.001702055f, 0.001708387f, 0.001714552f, 0.001720549f, + 0.001726380f, 0.001732047f, 0.001737549f, 0.001742888f, 0.001748065f, + 0.001753081f, 0.001757936f, 0.001762632f, 0.001767171f, 0.001771552f, + 0.001775777f, 0.001779847f, 0.001783762f, 0.001787525f, 0.001791135f, + 0.001794595f, 0.001797904f, 0.001801064f, 0.001804076f, 0.001806941f, + 0.001809660f, 0.001812234f, 0.001814664f, 0.001816952f, 0.001819097f, + 0.001821102f, 0.001822967f, 0.001824693f, 0.001826282f, 0.001827733f, + 0.001829050f, 0.001830231f, 0.001831278f, 0.001832194f, 0.001832979f, + 0.001833633f, 0.001834158f, 0.001834554f, 0.001834824f, 0.001834967f, + 0.001834986f, 0.001834880f, 0.001834651f, 0.001834301f, 0.001833830f, + 0.001833239f, 0.001832529f, 0.001831702f, 0.001830758f, 0.001829698f, + 0.001828525f, 0.001827237f, 0.001825838f, 0.001824327f, 0.001822706f, + 0.001820976f, 0.001819138f, 0.001817193f, 0.001815141f, 0.001812985f, + 0.001810725f, 0.001808363f, 0.001805898f, 0.001803333f, 0.001800668f, + 0.001797904f, 0.001795043f, 0.001792086f, 0.001789033f, 0.001785886f, + 0.001782645f, 0.001779312f, 0.001775887f, 0.001772373f, 0.001768769f, + 0.001765078f, 0.001761299f, 0.001757434f, 0.001753483f, 0.001749449f, + 0.001745332f, 0.001741133f, 0.001736853f, 0.001732493f, 0.001728054f, + 0.001723537f, 0.001718944f, 0.001714273f, 0.001709529f, 0.001704710f, + 0.001699819f, 0.001694857f, 0.001689823f, 0.001684719f, 0.001679546f, + 0.001674306f, 0.001668998f, 0.001663625f, 0.001658187f, 0.001652685f, + 0.001647120f, 0.001641493f, 0.001635804f, 0.001630056f, 0.001624249f, + 0.001618383f, 0.001612461f, 0.001606481f, 0.001600448f, 0.001594359f, + 0.001588217f, 0.001582022f, 0.001575776f, 0.001569480f, 0.001563134f, + 0.001556739f, 0.001550296f, 0.001543806f, 0.001537270f, 0.001530689f, + 0.001524064f, 0.001517395f, 0.001510684f, 0.001503932f, 0.001497139f, + 0.001490306f, 0.001483435f, 0.001476525f, 0.001469578f, 0.001462596f, + 0.001455577f, 0.001448524f, 0.001441438f, 0.001434318f, 0.001427167f, + 0.001419984f, 0.001412771f, 0.001405529f, 0.001398258f, 0.001390959f, + 0.001383633f, 0.001376281f, 0.001368903f, 0.001361501f, 0.001354076f, + 0.001346627f, 0.001339155f, 0.001331663f, 0.001324150f, 0.001316617f, + 0.001309064f, 0.001301494f, 0.001293906f, 0.001286301f, 0.001278680f, + 0.001271044f, 0.001263393f, 0.001255728f, 0.001248050f, 0.001240360f, + 0.001232658f, 0.001224945f, 0.001217221f, 0.001209488f, 0.001201747f, + 0.001193997f, 0.001186240f, 0.001178476f, 0.001170706f, 0.001162930f, + 0.001155150f, 0.001147365f, 0.001139577f, 0.001131787f, 0.001123994f, + 0.001116200f, 0.001108405f, 0.001100609f, 0.001092814f, 0.001085020f, + 0.001077228f, 0.001069438f, 0.001061651f, 0.001053867f, 0.001046087f, + 0.001038312f, 0.001030542f, 0.001022778f, 0.001015020f, 0.001007270f, + 0.000999526f, 0.000991791f, 0.000984065f, 0.000976347f, 0.000968640f, + 0.000960942f, 0.000953256f, 0.000945580f, 0.000937917f, 0.000930266f, + 0.000922628f, 0.000915002f, 0.000907391f, 0.000899794f, 0.000892212f, + 0.000884646f, 0.000877095f, 0.000869560f, 0.000862042f, 0.000854541f, + 0.000847058f, 0.000839593f, 0.000832147f, 0.000824719f, 0.000817311f, + 0.000809923f, 0.000802555f, 0.000795208f, 0.000787881f, 0.000780577f, + 0.000773294f, 0.000766033f, 0.000758795f, 0.000751581f, 0.000744389f, + 0.000737222f, 0.000730079f, 0.000722960f, 0.000715866f, 0.000708798f, + 0.000701755f, 0.000694738f, 0.000687748f, 0.000680784f, 0.000673847f, + 0.000666937f, 0.000660055f, 0.000653202f, 0.000646376f, 0.000639579f, + 0.000632810f, 0.000626071f, 0.000619362f, 0.000612682f, 0.000606032f, + 0.000599412f, 0.000592823f, 0.000586265f, 0.000579738f, 0.000573242f, + 0.000566777f, 0.000560345f, 0.000553944f, 0.000547577f, 0.000541241f, + 0.000534938f, 0.000528668f, 0.000522432f, 0.000516228f, 0.000510059f, + 0.000503923f, 0.000497821f, 0.000491753f, 0.000485720f, 0.000479721f, + 0.000473757f, 0.000467828f, 0.000461934f, 0.000456075f, 0.000450252f, + 0.000444464f, 0.000438712f, 0.000432996f, 0.000427316f, 0.000421672f, + 0.000416064f, 0.000410493f, 0.000404958f, 0.000399460f, 0.000393998f, + 0.000388574f, 0.000383186f, 0.000377836f, 0.000372523f, 0.000367247f, + 0.000362008f, 0.000356807f, 0.000351643f, 0.000346517f, 0.000341429f, + 0.000336378f, 0.000331366f, 0.000326391f, 0.000321454f, 0.000316555f, + 0.000311695f, 0.000306872f, 0.000302088f, 0.000297341f, 0.000292633f, + 0.000287963f, 0.000283332f, 0.000278739f, 0.000274184f, 0.000269667f, + 0.000265189f, 0.000260749f, 0.000256348f, 0.000251985f, 0.000247661f, + 0.000243374f, 0.000239126f, 0.000234917f, 0.000230745f, 0.000226613f, + 0.000222518f, 0.000218462f, 0.000214443f, 0.000210464f, 0.000206522f, + 0.000202618f, 0.000198753f, 0.000194926f, 0.000191136f, 0.000187385f, + 0.000183671f, 0.000179996f, 0.000176358f, 0.000172758f, 0.000169195f, + 0.000165670f, 0.000162183f, 0.000158733f, 0.000155321f, 0.000151945f, + 0.000148607f, 0.000145307f, 0.000142043f, 0.000138816f, 0.000135626f, + 0.000132473f, 0.000129356f, 0.000126276f, 0.000123233f, 0.000120225f, + 0.000117255f, 0.000114320f, 0.000111421f, 0.000108558f, 0.000105731f, + 0.000102940f, 0.000100184f, 0.000097463f, 0.000094778f, 0.000092128f, + 0.000089513f, 0.000086933f, 0.000084388f, 0.000081878f, 0.000079402f, + 0.000076960f, 0.000074552f, 0.000072179f, 0.000069839f, 0.000067534f, + 0.000065261f, 0.000063023f, 0.000060817f, 0.000058645f, 0.000056506f, + 0.000054399f, 0.000052326f, 0.000050284f, 0.000048275f, 0.000046299f, + 0.000044354f, 0.000042441f, 0.000040560f, 0.000038710f, 0.000036891f, + 0.000035104f, 0.000033348f, 0.000031622f, 0.000029927f, 0.000028263f, + 0.000026628f, 0.000025024f, 0.000023450f, 0.000021905f, 0.000020390f, + 0.000018904f, 0.000017447f, 0.000016019f, 0.000014620f, 0.000013249f, + 0.000011907f, 0.000010593f, 0.000009307f, 0.000008048f, 0.000006818f, + 0.000005614f, 0.000004438f, 0.000003288f, 0.000002166f, 0.000001070f, + -0.000000000f +}; + +static const float ResamplerFilterDifference[RESAMPLER_FILTER_SIZE] = { + -0.000006318f, -0.000019312f, -0.000033081f, -0.000046730f, -0.000060380f, + -0.000074029f, -0.000087738f, -0.000101388f, -0.000115037f, -0.000128686f, + -0.000142336f, -0.000155985f, -0.000169694f, -0.000183165f, -0.000196993f, + -0.000210524f, -0.000224173f, -0.000237763f, -0.000251293f, -0.000265062f, + -0.000278592f, -0.000292122f, -0.000305772f, -0.000319421f, -0.000332832f, + -0.000346422f, -0.000359952f, -0.000373542f, -0.000387073f, -0.000400543f, + -0.000414014f, -0.000427663f, -0.000441074f, -0.000454485f, -0.000468016f, + -0.000481427f, -0.000494778f, -0.000508308f, -0.000521660f, -0.000535011f, + -0.000548482f, -0.000561833f, -0.000575066f, -0.000588536f, -0.000601768f, + -0.000615180f, -0.000628352f, -0.000641525f, -0.000655055f, -0.000668049f, + -0.000681281f, -0.000694513f, -0.000707746f, -0.000720799f, -0.000733972f, + -0.000747204f, -0.000760138f, -0.000773191f, -0.000786424f, -0.000799239f, + -0.000812411f, -0.000825346f, -0.000838339f, -0.000851214f, -0.000864267f, + -0.000877023f, -0.000890017f, -0.000902772f, -0.000915587f, -0.000928521f, + -0.000941217f, -0.000953972f, -0.000966668f, -0.000979364f, -0.000992119f, + -0.001004696f, -0.001017392f, -0.001029909f, -0.001042426f, -0.001055002f, + -0.001067519f, -0.001080096f, -0.001092434f, -0.001104832f, -0.001117289f, + -0.001129627f, -0.001141965f, -0.001154304f, -0.001166403f, -0.001178861f, + -0.001191020f, -0.001203120f, -0.001215160f, -0.001227558f, -0.001239419f, + -0.001251400f, -0.001263618f, -0.001275480f, -0.001287460f, -0.001299262f, + -0.001311302f, -0.001322985f, -0.001334965f, -0.001346648f, -0.001358271f, + -0.001370072f, -0.001381695f, -0.001393259f, -0.001404881f, -0.001416504f, + -0.001427948f, -0.001439393f, -0.001450837f, -0.001462340f, -0.001473546f, + -0.001484871f, -0.001496255f, -0.001507342f, -0.001518726f, -0.001529694f, + -0.001540840f, -0.001552045f, -0.001562893f, -0.001574039f, -0.001584947f, + -0.001595795f, -0.001606703f, -0.001617491f, -0.001628280f, -0.001639009f, + -0.001649678f, -0.001660407f, -0.001670957f, -0.001681507f, -0.001692057f, + -0.001702428f, -0.001713037f, -0.001723289f, -0.001733601f, -0.001743913f, + -0.001754165f, -0.001764417f, -0.001774490f, -0.001784563f, -0.001794696f, + -0.001804650f, -0.001814663f, -0.001824498f, -0.001834452f, -0.001844168f, + -0.001854002f, -0.001863778f, -0.001873314f, -0.001883030f, -0.001892567f, + -0.001902103f, -0.001911521f, -0.001920938f, -0.001930356f, -0.001939654f, + -0.001948893f, -0.001958191f, -0.001967311f, -0.001976430f, -0.001985550f, + -0.001994491f, -0.002003491f, -0.002012312f, -0.002021313f, -0.002030015f, + -0.002038717f, -0.002047479f, -0.002056181f, -0.002064645f, -0.002073288f, + -0.002081692f, -0.002090156f, -0.002098501f, -0.002106905f, -0.002115071f, + -0.002123356f, -0.002131462f, -0.002139568f, -0.002147555f, -0.002155662f, + -0.002163529f, -0.002171457f, -0.002179205f, -0.002187014f, -0.002194703f, + -0.002202272f, -0.002209961f, -0.002217531f, -0.002224922f, -0.002232373f, + -0.002239764f, -0.002247095f, -0.002254248f, -0.002261519f, -0.002268672f, + -0.002275705f, -0.002282679f, -0.002289712f, -0.002296627f, -0.002303362f, + -0.002310216f, -0.002316952f, -0.002323568f, -0.002330244f, -0.002336800f, + -0.002343237f, -0.002349675f, -0.002356052f, -0.002362311f, -0.002368629f, + -0.002374828f, -0.002380908f, -0.002386987f, -0.002392948f, -0.002398968f, + -0.002404809f, -0.002410650f, -0.002416372f, -0.002422094f, -0.002427757f, + -0.002433360f, -0.002438903f, -0.002444327f, -0.002449691f, -0.002455056f, + -0.002460301f, -0.002465487f, -0.002470732f, -0.002475739f, -0.002480865f, + -0.002485693f, -0.002490699f, -0.002495527f, -0.002500176f, -0.002505064f, + -0.002509654f, -0.002514243f, -0.002518773f, -0.002523303f, -0.002527595f, + -0.002531946f, -0.002536356f, -0.002540410f, -0.002544582f, -0.002548754f, + -0.002552748f, -0.002556741f, -0.002560616f, -0.002564371f, -0.002568305f, + -0.002571881f, -0.002575636f, -0.002579153f, -0.002582669f, -0.002586126f, + -0.002589583f, -0.002592862f, -0.002596140f, -0.002599359f, -0.002602518f, + -0.002605557f, -0.002608538f, -0.002611578f, -0.002614439f, -0.002617240f, + -0.002620041f, -0.002622724f, -0.002625346f, -0.002627909f, -0.002630413f, + -0.002632916f, -0.002635241f, -0.002637565f, -0.002639830f, -0.002642035f, + -0.002644122f, -0.002646267f, -0.002648175f, -0.002650142f, -0.002652109f, + -0.002653837f, -0.002655566f, -0.002657294f, -0.002658904f, -0.002660453f, + -0.002662003f, -0.002663374f, -0.002664745f, -0.002666116f, -0.002667189f, + -0.002668560f, -0.002669632f, -0.002670705f, -0.002671599f, -0.002672642f, + -0.002673417f, -0.002674311f, -0.002675056f, -0.002675682f, -0.002676308f, + -0.002676874f, -0.002677381f, -0.002677768f, -0.002678156f, -0.002678514f, + -0.002678722f, -0.002678931f, -0.002679020f, -0.002679110f, -0.002679020f, + -0.002679050f, -0.002678901f, -0.002678722f, -0.002678484f, -0.002678186f, + -0.002677828f, -0.002677292f, -0.002676904f, -0.002676338f, -0.002675682f, + -0.002675027f, -0.002674311f, -0.002673507f, -0.002672672f, -0.002671778f, + -0.002670765f, -0.002669752f, -0.002668649f, -0.002667487f, -0.002666295f, + -0.002665013f, -0.002663702f, -0.002662301f, -0.002660841f, -0.002659231f, + -0.002657771f, -0.002656132f, -0.002654433f, -0.002652735f, -0.002650917f, + -0.002649069f, -0.002647102f, -0.002645165f, -0.002643138f, -0.002641022f, + -0.002638906f, -0.002636671f, -0.002634317f, -0.002632141f, -0.002629727f, + -0.002627254f, -0.002624840f, -0.002622217f, -0.002619684f, -0.002616972f, + -0.002614290f, -0.002611518f, -0.002608687f, -0.002605796f, -0.002602875f, + -0.002599895f, -0.002596736f, -0.002593726f, -0.002590597f, -0.002587378f, + -0.002584100f, -0.002580822f, -0.002577394f, -0.002574027f, -0.002570510f, + -0.002566963f, -0.002563447f, -0.002559751f, -0.002556056f, -0.002552360f, + -0.002548456f, -0.002544701f, -0.002540767f, -0.002536893f, -0.002532810f, + -0.002528816f, -0.002524704f, -0.002520531f, -0.002516329f, -0.002512068f, + -0.002507776f, -0.002503395f, -0.002499044f, -0.002494544f, -0.002489939f, + -0.002485529f, -0.002480894f, -0.002476230f, -0.002471551f, -0.002466798f, + -0.002461985f, -0.002457172f, -0.002452269f, -0.002447322f, -0.002442330f, + -0.002437294f, -0.002432242f, -0.002427101f, -0.002421811f, -0.002416730f, + -0.002411440f, -0.002406135f, -0.002400786f, -0.002395362f, -0.002389938f, + -0.002384409f, -0.002378926f, -0.002373338f, -0.002367705f, -0.002362043f, + -0.002356306f, -0.002350554f, -0.002344713f, -0.002338931f, -0.002333075f, + -0.002327129f, -0.002321184f, -0.002315164f, -0.002309129f, -0.002303004f, + -0.002296925f, -0.002290726f, -0.002284512f, -0.002278253f, -0.002271980f, + -0.002265558f, -0.002259284f, -0.002252862f, -0.002246410f, -0.002239943f, + -0.002233401f, -0.002226844f, -0.002220228f, -0.002213612f, -0.002206936f, + -0.002200201f, -0.002193481f, -0.002186671f, -0.002179854f, -0.002172925f, + -0.002166122f, -0.002159171f, -0.002152205f, -0.002145231f, -0.002138190f, + -0.002131112f, -0.002124026f, -0.002116874f, -0.002109714f, -0.002102517f, + -0.002095275f, -0.002088003f, -0.002080709f, -0.002073303f, -0.002066024f, + -0.002058625f, -0.002051190f, -0.002043739f, -0.002036251f, -0.002028733f, + -0.002021186f, -0.002013609f, -0.002006002f, -0.001998372f, -0.001990698f, + -0.001983009f, -0.001975283f, -0.001967464f, -0.001959760f, -0.001951948f, + -0.001944117f, -0.001936268f, -0.001928370f, -0.001920462f, -0.001912523f, + -0.001904562f, -0.001896568f, -0.001888555f, -0.001880515f, -0.001872454f, + -0.001864363f, -0.001856182f, -0.001848117f, -0.001839954f, -0.001831776f, + -0.001823569f, -0.001815341f, -0.001807092f, -0.001798820f, -0.001790524f, + -0.001782209f, -0.001773877f, -0.001765518f, -0.001757140f, -0.001748742f, + -0.001740261f, -0.001731890f, -0.001723433f, -0.001714959f, -0.001706466f, + -0.001697953f, -0.001689423f, -0.001680876f, -0.001672311f, -0.001663728f, + -0.001655128f, -0.001646512f, -0.001637880f, -0.001629170f, -0.001620566f, + -0.001611889f, -0.001603196f, -0.001594484f, -0.001585761f, -0.001577025f, + -0.001568271f, -0.001559505f, -0.001550728f, -0.001541931f, -0.001533132f, + -0.001524314f, -0.001515483f, -0.001506586f, -0.001497786f, -0.001488928f, + -0.001480050f, -0.001471169f, -0.001462270f, -0.001453366f, -0.001444448f, + -0.001435522f, -0.001426589f, -0.001417641f, -0.001408692f, -0.001399733f, + -0.001390763f, -0.001381733f, -0.001372803f, -0.001363818f, -0.001354810f, + -0.001345813f, -0.001336802f, -0.001327783f, -0.001318768f, -0.001309730f, + -0.001300700f, -0.001291670f, -0.001282625f, -0.001273572f, -0.001264527f, + -0.001255415f, -0.001246415f, -0.001237355f, -0.001228295f, -0.001219213f, + -0.001210161f, -0.001201086f, -0.001192011f, -0.001182951f, -0.001173854f, + -0.001164794f, -0.001155719f, -0.001146644f, -0.001137555f, -0.001128443f, + -0.001119412f, -0.001110330f, -0.001101270f, -0.001092196f, -0.001083128f, + -0.001074038f, -0.001065001f, -0.001055919f, -0.001046866f, -0.001037806f, + -0.001028746f, -0.001019694f, -0.001010656f, -0.001001567f, -0.000992566f, + -0.000983544f, -0.000974506f, -0.000965491f, -0.000956468f, -0.000947453f, + -0.000938453f, -0.000929438f, -0.000920445f, -0.000911482f, -0.000902474f, + -0.000893541f, -0.000884496f, -0.000875585f, -0.000866644f, -0.000857703f, + -0.000848778f, -0.000839837f, -0.000830933f, -0.000822030f, -0.000813127f, + -0.000804260f, -0.000795372f, -0.000786506f, -0.000777654f, -0.000768811f, + -0.000759944f, -0.000751153f, -0.000742361f, -0.000733539f, -0.000724763f, + -0.000716001f, -0.000707224f, -0.000698492f, -0.000689745f, -0.000681043f, + -0.000672325f, -0.000663623f, -0.000654951f, -0.000646278f, -0.000637606f, + -0.000628993f, -0.000620380f, -0.000611767f, -0.000603199f, -0.000594586f, + -0.000586048f, -0.000577524f, -0.000568971f, -0.000560462f, -0.000551969f, + -0.000543505f, -0.000535041f, -0.000526607f, -0.000518143f, -0.000509769f, + -0.000501379f, -0.000493005f, -0.000484675f, -0.000476316f, -0.000468016f, + -0.000459731f, -0.000451431f, -0.000443190f, -0.000434965f, -0.000426725f, + -0.000418544f, -0.000410378f, -0.000402227f, -0.000394091f, -0.000385970f, + -0.000377893f, -0.000369802f, -0.000361770f, -0.000353739f, -0.000345752f, + -0.000337750f, -0.000329792f, -0.000321865f, -0.000313938f, -0.000306055f, + -0.000298187f, -0.000290349f, -0.000282511f, -0.000274733f, -0.000266939f, + -0.000259221f, -0.000251472f, -0.000243768f, -0.000236079f, -0.000228450f, + -0.000220820f, -0.000213221f, -0.000205651f, -0.000198096f, -0.000190571f, + -0.000183061f, -0.000175595f, -0.000168160f, -0.000160739f, -0.000153318f, + -0.000145987f, -0.000138611f, -0.000131324f, -0.000124037f, -0.000116780f, + -0.000109524f, -0.000102326f, -0.000095159f, -0.000088021f, -0.000080869f, + -0.000073805f, -0.000066742f, -0.000059679f, -0.000052691f, -0.000045687f, + -0.000038758f, -0.000031844f, -0.000024930f, -0.000018090f, -0.000011265f, + -0.000004441f, 0.000002325f, 0.000009075f, 0.000015780f, 0.000022471f, + 0.000029117f, 0.000035763f, 0.000042319f, 0.000048906f, 0.000055432f, + 0.000061929f, 0.000068396f, 0.000074849f, 0.000081256f, 0.000087619f, + 0.000093967f, 0.000100300f, 0.000106558f, 0.000112817f, 0.000119045f, + 0.000125214f, 0.000131369f, 0.000137508f, 0.000143588f, 0.000149652f, + 0.000155658f, 0.000161663f, 0.000167638f, 0.000173539f, 0.000179455f, + 0.000185296f, 0.000191167f, 0.000196919f, 0.000202700f, 0.000208423f, + 0.000214115f, 0.000219792f, 0.000225410f, 0.000231013f, 0.000236586f, + 0.000242084f, 0.000247598f, 0.000253052f, 0.000258476f, 0.000263870f, + 0.000269234f, 0.000274554f, 0.000279859f, 0.000285104f, 0.000290334f, + 0.000295490f, 0.000300661f, 0.000305787f, 0.000310853f, 0.000315934f, + 0.000320926f, 0.000325903f, 0.000330850f, 0.000335768f, 0.000340641f, + 0.000345469f, 0.000350282f, 0.000355050f, 0.000359803f, 0.000364468f, + 0.000369161f, 0.000373796f, 0.000378355f, 0.000382945f, 0.000387460f, + 0.000391930f, 0.000396401f, 0.000400826f, 0.000405192f, 0.000409558f, + 0.000413850f, 0.000418127f, 0.000422373f, 0.000426546f, 0.000430748f, + 0.000434861f, 0.000438988f, 0.000443041f, 0.000447050f, 0.000451058f, + 0.000455007f, 0.000458926f, 0.000462815f, 0.000466645f, 0.000470474f, + 0.000474244f, 0.000477999f, 0.000481665f, 0.000485376f, 0.000488982f, + 0.000492588f, 0.000496164f, 0.000499681f, 0.000503168f, 0.000506610f, + 0.000510037f, 0.000513420f, 0.000516787f, 0.000520080f, 0.000523359f, + 0.000526607f, 0.000529751f, 0.000532970f, 0.000536114f, 0.000539184f, + 0.000542283f, 0.000545278f, 0.000548288f, 0.000551224f, 0.000554159f, + 0.000557050f, 0.000559889f, 0.000562698f, 0.000565484f, 0.000568233f, + 0.000570931f, 0.000573598f, 0.000576250f, 0.000578851f, 0.000581399f, + 0.000583932f, 0.000586443f, 0.000588894f, 0.000591323f, 0.000593722f, + 0.000596076f, 0.000598386f, 0.000600673f, 0.000602946f, 0.000605099f, + 0.000607334f, 0.000609480f, 0.000611588f, 0.000613675f, 0.000615716f, + 0.000617720f, 0.000619695f, 0.000621639f, 0.000623547f, 0.000625424f, + 0.000627257f, 0.000629067f, 0.000630826f, 0.000632577f, 0.000634275f, + 0.000635937f, 0.000637576f, 0.000639170f, 0.000640750f, 0.000642270f, + 0.000643790f, 0.000645243f, 0.000646673f, 0.000648089f, 0.000649445f, + 0.000650786f, 0.000652038f, 0.000653364f, 0.000654578f, 0.000655793f, + 0.000656962f, 0.000658102f, 0.000659212f, 0.000660270f, 0.000661321f, + 0.000662334f, 0.000663288f, 0.000664257f, 0.000665158f, 0.000666037f, + 0.000666894f, 0.000667714f, 0.000668481f, 0.000669241f, 0.000669979f, + 0.000670649f, 0.000671312f, 0.000671953f, 0.000672549f, 0.000673100f, + 0.000673652f, 0.000674143f, 0.000674628f, 0.000675075f, 0.000675432f, + 0.000675865f, 0.000676215f, 0.000676543f, 0.000676841f, 0.000677086f, + 0.000677340f, 0.000677533f, 0.000677712f, 0.000677854f, 0.000677958f, + 0.000678062f, 0.000678115f, 0.000678137f, 0.000678144f, 0.000678107f, + 0.000678040f, 0.000677980f, 0.000677846f, 0.000677705f, 0.000677541f, + 0.000677332f, 0.000677109f, 0.000676855f, 0.000676572f, 0.000676263f, + 0.000675920f, 0.000675563f, 0.000675112f, 0.000674754f, 0.000674292f, + 0.000673834f, 0.000673324f, 0.000672799f, 0.000672262f, 0.000671666f, + 0.000671066f, 0.000670440f, 0.000669774f, 0.000669103f, 0.000668388f, + 0.000667654f, 0.000666898f, 0.000666108f, 0.000665307f, 0.000664469f, + 0.000663612f, 0.000662729f, 0.000661820f, 0.000660881f, 0.000659931f, + 0.000658948f, 0.000657942f, 0.000656914f, 0.000655863f, 0.000654746f, + 0.000653688f, 0.000652563f, 0.000651423f, 0.000650249f, 0.000649061f, + 0.000647850f, 0.000646606f, 0.000645354f, 0.000644065f, 0.000642769f, + 0.000641439f, 0.000640094f, 0.000638723f, 0.000637334f, 0.000635926f, + 0.000634488f, 0.000633033f, 0.000631562f, 0.000630064f, 0.000628548f, + 0.000627011f, 0.000625454f, 0.000623874f, 0.000622276f, 0.000620661f, + 0.000619022f, 0.000617364f, 0.000615645f, 0.000613993f, 0.000612279f, + 0.000610547f, 0.000608791f, 0.000607023f, 0.000605229f, 0.000603424f, + 0.000601593f, 0.000599753f, 0.000597889f, 0.000596011f, 0.000594109f, + 0.000592194f, 0.000590262f, 0.000588313f, 0.000586346f, 0.000584361f, + 0.000582362f, 0.000580344f, 0.000578311f, 0.000576260f, 0.000574195f, + 0.000572114f, 0.000570015f, 0.000567904f, 0.000565774f, 0.000563630f, + 0.000561428f, 0.000559297f, 0.000557108f, 0.000554904f, 0.000552687f, + 0.000550454f, 0.000548207f, 0.000545946f, 0.000543671f, 0.000541383f, + 0.000539081f, 0.000536765f, 0.000534437f, 0.000532095f, 0.000529740f, + 0.000527372f, 0.000524992f, 0.000522598f, 0.000520193f, 0.000517776f, + 0.000515345f, 0.000512904f, 0.000510451f, 0.000507986f, 0.000505510f, + 0.000503022f, 0.000500523f, 0.000497975f, 0.000495494f, 0.000492963f, + 0.000490420f, 0.000487870f, 0.000485308f, 0.000482734f, 0.000480153f, + 0.000477560f, 0.000474961f, 0.000472347f, 0.000469729f, 0.000467099f, + 0.000464460f, 0.000461814f, 0.000459160f, 0.000456492f, 0.000453821f, + 0.000451141f, 0.000448450f, 0.000445757f, 0.000443047f, 0.000440339f, + 0.000437619f, 0.000434890f, 0.000432156f, 0.000429420f, 0.000426665f, + 0.000423878f, 0.000421155f, 0.000418384f, 0.000415608f, 0.000412831f, + 0.000410046f, 0.000407251f, 0.000404453f, 0.000401655f, 0.000398841f, + 0.000396032f, 0.000393212f, 0.000390388f, 0.000387559f, 0.000384722f, + 0.000381887f, 0.000379046f, 0.000376200f, 0.000373350f, 0.000370493f, + 0.000367636f, 0.000364775f, 0.000361912f, 0.000359036f, 0.000356171f, + 0.000353293f, 0.000350416f, 0.000347532f, 0.000344623f, 0.000341764f, + 0.000338878f, 0.000335984f, 0.000333097f, 0.000330199f, 0.000327300f, + 0.000324406f, 0.000321500f, 0.000318602f, 0.000315700f, 0.000312794f, + 0.000309892f, 0.000306983f, 0.000304081f, 0.000301171f, 0.000298265f, + 0.000295352f, 0.000292446f, 0.000289541f, 0.000286628f, 0.000283718f, + 0.000280812f, 0.000277914f, 0.000274993f, 0.000272095f, 0.000269186f, + 0.000266258f, 0.000263374f, 0.000260476f, 0.000257570f, 0.000254679f, + 0.000251777f, 0.000248875f, 0.000245985f, 0.000243090f, 0.000240199f, + 0.000237312f, 0.000234425f, 0.000231542f, 0.000228655f, 0.000225779f, + 0.000222903f, 0.000220031f, 0.000217155f, 0.000214294f, 0.000211425f, + 0.000208564f, 0.000205707f, 0.000202853f, 0.000200007f, 0.000197157f, + 0.000194311f, 0.000191480f, 0.000188638f, 0.000185791f, 0.000182983f, + 0.000180162f, 0.000177346f, 0.000174530f, 0.000171725f, 0.000168923f, + 0.000166126f, 0.000163332f, 0.000160541f, 0.000157762f, 0.000154987f, + 0.000152212f, 0.000149447f, 0.000146687f, 0.000143930f, 0.000141181f, + 0.000138439f, 0.000135705f, 0.000132974f, 0.000130247f, 0.000127535f, + 0.000124816f, 0.000122119f, 0.000119418f, 0.000116725f, 0.000114042f, + 0.000111364f, 0.000108674f, 0.000106033f, 0.000103373f, 0.000100728f, + 0.000098083f, 0.000095449f, 0.000092819f, 0.000090208f, 0.000087593f, + 0.000084992f, 0.000082392f, 0.000079807f, 0.000077233f, 0.000074655f, + 0.000072096f, 0.000069536f, 0.000066992f, 0.000064459f, 0.000061929f, + 0.000059403f, 0.000056893f, 0.000054389f, 0.000051897f, 0.000049412f, + 0.000046935f, 0.000044469f, 0.000042010f, 0.000039551f, 0.000037123f, + 0.000034694f, 0.000032268f, 0.000029862f, 0.000027459f, 0.000025064f, + 0.000022691f, 0.000020307f, 0.000017952f, 0.000015602f, 0.000013247f, + 0.000010934f, 0.000008594f, 0.000006288f, 0.000003986f, 0.000001695f, + -0.000000589f, -0.000002854f, -0.000005119f, -0.000007369f, -0.000009615f, + -0.000011832f, -0.000014052f, -0.000016265f, -0.000018459f, -0.000020642f, + -0.000022821f, -0.000024986f, -0.000027131f, -0.000029277f, -0.000031408f, + -0.000033524f, -0.000035629f, -0.000037737f, -0.000039808f, -0.000041891f, + -0.000043951f, -0.000046007f, -0.000048041f, -0.000050064f, -0.000052094f, + -0.000054091f, -0.000056084f, -0.000058070f, -0.000060037f, -0.000061993f, + -0.000063941f, -0.000065874f, -0.000067800f, -0.000069708f, -0.000071604f, + -0.000073489f, -0.000075370f, -0.000077229f, -0.000079080f, -0.000080917f, + -0.000082746f, -0.000084557f, -0.000086352f, -0.000088152f, -0.000089929f, + -0.000091687f, -0.000093438f, -0.000095177f, -0.000096913f, -0.000098623f, + -0.000100322f, -0.000102021f, -0.000103690f, -0.000105359f, -0.000107009f, + -0.000108648f, -0.000110280f, -0.000111893f, -0.000113495f, -0.000115078f, + -0.000116657f, -0.000118230f, -0.000119772f, -0.000121318f, -0.000122838f, + -0.000124350f, -0.000125848f, -0.000127345f, -0.000128813f, -0.000130277f, + -0.000131730f, -0.000133157f, -0.000134595f, -0.000135988f, -0.000137400f, + -0.000138778f, -0.000140157f, -0.000141505f, -0.000142857f, -0.000144191f, + -0.000145517f, -0.000146817f, -0.000148114f, -0.000149388f, -0.000150666f, + -0.000151921f, -0.000153165f, -0.000154395f, -0.000155609f, -0.000156820f, + -0.000158004f, -0.000159189f, -0.000160355f, -0.000161506f, -0.000162646f, + -0.000163775f, -0.000164881f, -0.000165988f, -0.000167083f, -0.000168145f, + -0.000169218f, -0.000170264f, -0.000171307f, -0.000172324f, -0.000173341f, + -0.000174336f, -0.000175327f, -0.000176292f, -0.000177257f, -0.000178207f, + -0.000179138f, -0.000180058f, -0.000180975f, -0.000181865f, -0.000182752f, + -0.000183623f, -0.000184480f, -0.000185326f, -0.000186164f, -0.000186980f, + -0.000187792f, -0.000188582f, -0.000189368f, -0.000190143f, -0.000190891f, + -0.000191648f, -0.000192374f, -0.000193097f, -0.000193801f, -0.000194505f, + -0.000195183f, -0.000195853f, -0.000196513f, -0.000197157f, -0.000197794f, + -0.000198420f, -0.000199001f, -0.000199623f, -0.000200208f, -0.000200782f, + -0.000201344f, -0.000201892f, -0.000202429f, -0.000202954f, -0.000203468f, + -0.000203967f, -0.000204455f, -0.000204936f, -0.000205394f, -0.000205856f, + -0.000206295f, -0.000206724f, -0.000207141f, -0.000207547f, -0.000207946f, + -0.000208326f, -0.000208698f, -0.000209058f, -0.000209408f, -0.000209745f, + -0.000210065f, -0.000210386f, -0.000210684f, -0.000210978f, -0.000211256f, + -0.000211528f, -0.000211783f, -0.000212030f, -0.000212263f, -0.000212491f, + -0.000212703f, -0.000212908f, -0.000213092f, -0.000213277f, -0.000213446f, + -0.000213604f, -0.000213752f, -0.000213886f, -0.000214016f, -0.000214130f, + -0.000214234f, -0.000214327f, -0.000214415f, -0.000214487f, -0.000214545f, + -0.000214605f, -0.000214642f, -0.000214674f, -0.000214696f, -0.000214709f, + -0.000214707f, -0.000214674f, -0.000214679f, -0.000214649f, -0.000214612f, + -0.000214560f, -0.000214502f, -0.000214435f, -0.000214357f, -0.000214268f, + -0.000214169f, -0.000214059f, -0.000213947f, -0.000213819f, -0.000213677f, + -0.000213537f, -0.000213381f, -0.000213215f, -0.000213042f, -0.000212861f, + -0.000212666f, -0.000212466f, -0.000212256f, -0.000212036f, -0.000211809f, + -0.000211569f, -0.000211326f, -0.000211067f, -0.000210807f, -0.000210535f, + -0.000210257f, -0.000209961f, -0.000209667f, -0.000209359f, -0.000209045f, + -0.000208722f, -0.000208389f, -0.000208050f, -0.000207704f, -0.000207344f, + -0.000206983f, -0.000206610f, -0.000206229f, -0.000205842f, -0.000205445f, + -0.000205044f, -0.000204630f, -0.000204211f, -0.000203785f, -0.000203351f, + -0.000202909f, -0.000202459f, -0.000202003f, -0.000201537f, -0.000201069f, + -0.000200586f, -0.000200078f, -0.000199611f, -0.000199108f, -0.000198605f, + -0.000198090f, -0.000197569f, -0.000197043f, -0.000196506f, -0.000195967f, + -0.000195420f, -0.000194865f, -0.000194305f, -0.000193738f, -0.000193163f, + -0.000192585f, -0.000191999f, -0.000191407f, -0.000190807f, -0.000190204f, + -0.000189591f, -0.000188977f, -0.000188354f, -0.000187725f, -0.000187092f, + -0.000186451f, -0.000185805f, -0.000185154f, -0.000184498f, -0.000183835f, + -0.000183167f, -0.000182495f, -0.000181816f, -0.000181132f, -0.000180443f, + -0.000179750f, -0.000179050f, -0.000178346f, -0.000177636f, -0.000176923f, + -0.000176203f, -0.000175480f, -0.000174752f, -0.000174019f, -0.000173280f, + -0.000172539f, -0.000171792f, -0.000171040f, -0.000170285f, -0.000169525f, + -0.000168761f, -0.000167992f, -0.000167220f, -0.000166443f, -0.000165662f, + -0.000164878f, -0.000164090f, -0.000163272f, -0.000162501f, -0.000161701f, + -0.000160898f, -0.000160091f, -0.000159280f, -0.000158466f, -0.000157648f, + -0.000156827f, -0.000156003f, -0.000155175f, -0.000154344f, -0.000153510f, + -0.000152673f, -0.000151833f, -0.000150990f, -0.000150144f, -0.000149295f, + -0.000148444f, -0.000147589f, -0.000146732f, -0.000145872f, -0.000145010f, + -0.000144145f, -0.000143277f, -0.000142408f, -0.000141536f, -0.000140661f, + -0.000139785f, -0.000138906f, -0.000138025f, -0.000137142f, -0.000136257f, + -0.000135370f, -0.000134481f, -0.000133590f, -0.000132697f, -0.000131803f, + -0.000130907f, -0.000130009f, -0.000129110f, -0.000128209f, -0.000127306f, + -0.000126403f, -0.000125497f, -0.000124591f, -0.000123683f, -0.000122774f, + -0.000121864f, -0.000120952f, -0.000120040f, -0.000119127f, -0.000118212f, + -0.000117297f, -0.000116381f, -0.000115445f, -0.000114546f, -0.000113628f, + -0.000112709f, -0.000111789f, -0.000110869f, -0.000109948f, -0.000109027f, + -0.000108106f, -0.000107184f, -0.000106262f, -0.000105340f, -0.000104415f, + -0.000103494f, -0.000102570f, -0.000101647f, -0.000100723f, -0.000099801f, + -0.000098877f, -0.000097955f, -0.000097031f, -0.000096109f, -0.000095187f, + -0.000094265f, -0.000093343f, -0.000092422f, -0.000091502f, -0.000090580f, + -0.000089660f, -0.000088741f, -0.000087823f, -0.000086904f, -0.000085988f, + -0.000085071f, -0.000084155f, -0.000083240f, -0.000082325f, -0.000081412f, + -0.000080500f, -0.000079590f, -0.000078678f, -0.000077770f, -0.000076862f, + -0.000075955f, -0.000075049f, -0.000074145f, -0.000073241f, -0.000072340f, + -0.000071440f, -0.000070541f, -0.000069643f, -0.000068747f, -0.000067852f, + -0.000066960f, -0.000066068f, -0.000065166f, -0.000064289f, -0.000063405f, + -0.000062519f, -0.000061636f, -0.000060757f, -0.000059876f, -0.000058998f, + -0.000058125f, -0.000057249f, -0.000056379f, -0.000055509f, -0.000054643f, + -0.000053776f, -0.000052913f, -0.000052053f, -0.000051194f, -0.000050337f, + -0.000049485f, -0.000048630f, -0.000047781f, -0.000046935f, -0.000046090f, + -0.000045246f, -0.000044407f, -0.000043570f, -0.000042734f, -0.000041903f, + -0.000041073f, -0.000040242f, -0.000039421f, -0.000038599f, -0.000037779f, + -0.000036962f, -0.000036148f, -0.000035339f, -0.000034529f, -0.000033723f, + -0.000032922f, -0.000032122f, -0.000031324f, -0.000030532f, -0.000029741f, + -0.000028951f, -0.000028169f, -0.000027386f, -0.000026607f, -0.000025833f, + -0.000025058f, -0.000024288f, -0.000023524f, -0.000022760f, -0.000022001f, + -0.000021243f, -0.000020491f, -0.000019740f, -0.000018986f, -0.000018249f, + -0.000017510f, -0.000016774f, -0.000016038f, -0.000015311f, -0.000014583f, + -0.000013859f, -0.000013139f, -0.000012424f, -0.000011712f, -0.000011003f, + -0.000010296f, -0.000009594f, -0.000008895f, -0.000008201f, -0.000007508f, + -0.000006821f, -0.000006137f, -0.000005458f, -0.000004780f, -0.000004107f, + -0.000003438f, -0.000002770f, -0.000002110f, -0.000001453f, -0.000000797f, + -0.000000146f, 0.000000501f, 0.000001144f, 0.000001782f, 0.000002420f, + 0.000003050f, 0.000003677f, 0.000004301f, 0.000004923f, 0.000005536f, + 0.000006150f, 0.000006758f, 0.000007361f, 0.000007963f, 0.000008560f, + 0.000009151f, 0.000009741f, 0.000010326f, 0.000010905f, 0.000011482f, + 0.000012054f, 0.000012624f, 0.000013188f, 0.000013747f, 0.000014306f, + 0.000014856f, 0.000015406f, 0.000015951f, 0.000016493f, 0.000017026f, + 0.000017560f, 0.000018085f, 0.000018612f, 0.000019130f, 0.000019647f, + 0.000020158f, 0.000020666f, 0.000021168f, 0.000021671f, 0.000022165f, + 0.000022653f, 0.000023143f, 0.000023624f, 0.000024104f, 0.000024579f, + 0.000025048f, 0.000025516f, 0.000025976f, 0.000026437f, 0.000026888f, + 0.000027340f, 0.000027785f, 0.000028226f, 0.000028664f, 0.000029097f, + 0.000029526f, 0.000029950f, 0.000030371f, 0.000030789f, 0.000031200f, + 0.000031610f, 0.000032012f, 0.000032413f, 0.000032808f, 0.000033202f, + 0.000033589f, 0.000033971f, 0.000034352f, 0.000034725f, 0.000035098f, + 0.000035464f, 0.000035828f, 0.000036187f, 0.000036540f, 0.000036892f, + 0.000037238f, 0.000037580f, 0.000037918f, 0.000038252f, 0.000038582f, + 0.000038907f, 0.000039231f, 0.000039549f, 0.000039860f, 0.000040172f, + 0.000040476f, 0.000040780f, 0.000041076f, 0.000041369f, 0.000041659f, + 0.000041946f, 0.000042226f, 0.000042504f, 0.000042778f, 0.000043048f, + 0.000043313f, 0.000043575f, 0.000043831f, 0.000044088f, 0.000044335f, + 0.000044581f, 0.000044825f, 0.000045061f, 0.000045295f, 0.000045526f, + 0.000045752f, 0.000045975f, 0.000046193f, 0.000046407f, 0.000046619f, + 0.000046826f, 0.000047030f, 0.000047228f, 0.000047424f, 0.000047616f, + 0.000047805f, 0.000047988f, 0.000048169f, 0.000048346f, 0.000048519f, + 0.000048689f, 0.000048853f, 0.000049016f, 0.000049174f, 0.000049329f, + 0.000049480f, 0.000049627f, 0.000049771f, 0.000049912f, 0.000050047f, + 0.000050181f, 0.000050310f, 0.000050437f, 0.000050558f, 0.000050677f, + 0.000050792f, 0.000050904f, 0.000051012f, 0.000051118f, 0.000051214f, + 0.000051316f, 0.000051410f, 0.000051503f, 0.000051589f, 0.000051674f, + 0.000051755f, 0.000051832f, 0.000051906f, 0.000051977f, 0.000052044f, + 0.000052109f, 0.000052171f, 0.000052229f, 0.000052283f, 0.000052333f, + 0.000052382f, 0.000052427f, 0.000052468f, 0.000052508f, 0.000052543f, + 0.000052574f, 0.000052604f, 0.000052631f, 0.000052653f, 0.000052674f, + 0.000052691f, 0.000052704f, 0.000052716f, 0.000052724f, 0.000052729f, + 0.000052730f, 0.000052730f, 0.000052726f, 0.000052720f, 0.000052710f, + 0.000052697f, 0.000052682f, 0.000052664f, 0.000052643f, 0.000052620f, + 0.000052593f, 0.000052564f, 0.000052531f, 0.000052498f, 0.000052460f, + 0.000052420f, 0.000052377f, 0.000052333f, 0.000052284f, 0.000052234f, + 0.000052180f, 0.000052125f, 0.000052067f, 0.000052006f, 0.000051938f, + 0.000051877f, 0.000051809f, 0.000051738f, 0.000051666f, 0.000051590f, + 0.000051512f, 0.000051432f, 0.000051349f, 0.000051265f, 0.000051177f, + 0.000051088f, 0.000050996f, 0.000050901f, 0.000050805f, 0.000050707f, + 0.000050606f, 0.000050503f, 0.000050398f, 0.000050291f, 0.000050182f, + 0.000050070f, 0.000049957f, 0.000049842f, 0.000049724f, 0.000049604f, + 0.000049483f, 0.000049358f, 0.000049234f, 0.000049105f, 0.000048977f, + 0.000048845f, 0.000048712f, 0.000048577f, 0.000048439f, 0.000048302f, + 0.000048161f, 0.000048019f, 0.000047874f, 0.000047728f, 0.000047581f, + 0.000047431f, 0.000047280f, 0.000047128f, 0.000046974f, 0.000046818f, + 0.000046660f, 0.000046501f, 0.000046341f, 0.000046178f, 0.000046015f, + 0.000045849f, 0.000045683f, 0.000045514f, 0.000045344f, 0.000045168f, + 0.000045001f, 0.000044827f, 0.000044652f, 0.000044475f, 0.000044297f, + 0.000044117f, 0.000043937f, 0.000043755f, 0.000043572f, 0.000043387f, + 0.000043201f, 0.000043015f, 0.000042827f, 0.000042638f, 0.000042447f, + 0.000042256f, 0.000042063f, 0.000041869f, 0.000041675f, 0.000041479f, + 0.000041282f, 0.000041084f, 0.000040885f, 0.000040685f, 0.000040484f, + 0.000040283f, 0.000040080f, 0.000039876f, 0.000039672f, 0.000039466f, + 0.000039260f, 0.000039053f, 0.000038845f, 0.000038636f, 0.000038427f, + 0.000038217f, 0.000038006f, 0.000037794f, 0.000037581f, 0.000037368f, + 0.000037155f, 0.000036940f, 0.000036725f, 0.000036509f, 0.000036293f, + 0.000036076f, 0.000035858f, 0.000035640f, 0.000035422f, 0.000035202f, + 0.000034983f, 0.000034763f, 0.000034542f, 0.000034321f, 0.000034100f, + 0.000033873f, 0.000033655f, 0.000033432f, 0.000033209f, 0.000032986f, + 0.000032762f, 0.000032538f, 0.000032313f, 0.000032089f, 0.000031864f, + 0.000031638f, 0.000031413f, 0.000031187f, 0.000030961f, 0.000030735f, + 0.000030508f, 0.000030282f, 0.000030055f, 0.000029828f, 0.000029601f, + 0.000029374f, 0.000029147f, 0.000028920f, 0.000028692f, 0.000028465f, + 0.000028237f, 0.000028010f, 0.000027782f, 0.000027555f, 0.000027328f, + 0.000027100f, 0.000026873f, 0.000026645f, 0.000026418f, 0.000026191f, + 0.000025964f, 0.000025737f, 0.000025510f, 0.000025283f, 0.000025057f, + 0.000024830f, 0.000024604f, 0.000024378f, 0.000024152f, 0.000023927f, + 0.000023702f, 0.000023476f, 0.000023252f, 0.000023027f, 0.000022803f, + 0.000022579f, 0.000022355f, 0.000022132f, 0.000021908f, 0.000021686f, + 0.000021460f, 0.000021241f, 0.000021020f, 0.000020798f, 0.000020578f, + 0.000020357f, 0.000020137f, 0.000019917f, 0.000019698f, 0.000019480f, + 0.000019261f, 0.000019044f, 0.000018826f, 0.000018609f, 0.000018393f, + 0.000018177f, 0.000017962f, 0.000017748f, 0.000017533f, 0.000017320f, + 0.000017107f, 0.000016894f, 0.000016682f, 0.000016471f, 0.000016260f, + 0.000016050f, 0.000015841f, 0.000015632f, 0.000015424f, 0.000015216f, + 0.000015009f, 0.000014803f, 0.000014597f, 0.000014393f, 0.000014188f, + 0.000013985f, 0.000013782f, 0.000013580f, 0.000013379f, 0.000013178f, + 0.000012978f, 0.000012779f, 0.000012581f, 0.000012383f, 0.000012186f, + 0.000011990f, 0.000011795f, 0.000011600f, 0.000011407f, 0.000011214f, + 0.000011022f, 0.000010830f, 0.000010640f, 0.000010450f, 0.000010262f, + 0.000010074f, 0.000009884f, 0.000009700f, 0.000009515f, 0.000009331f, + 0.000009147f, 0.000008964f, 0.000008782f, 0.000008601f, 0.000008421f, + 0.000008242f, 0.000008064f, 0.000007887f, 0.000007710f, 0.000007535f, + 0.000007360f, 0.000007186f, 0.000007014f, 0.000006842f, 0.000006671f, + 0.000006501f, 0.000006332f, 0.000006164f, 0.000005997f, 0.000005831f, + 0.000005667f, 0.000005502f, 0.000005339f, 0.000005177f, 0.000005016f, + 0.000004855f, 0.000004696f, 0.000004538f, 0.000004381f, 0.000004225f, + 0.000004070f, 0.000003916f, 0.000003763f, 0.000003610f, 0.000003459f, + 0.000003309f, 0.000003160f, 0.000003012f, 0.000002865f, 0.000002719f, + 0.000002574f, 0.000002430f, 0.000002287f, 0.000002146f, 0.000002005f, + 0.000001865f, 0.000001726f, 0.000001589f, 0.000001452f, 0.000001316f, + 0.000001182f, 0.000001047f, 0.000000916f, 0.000000785f, 0.000000654f, + 0.000000525f, 0.000000397f, 0.000000270f, 0.000000143f, 0.000000019f, + -0.000000106f, -0.000000228f, -0.000000351f, -0.000000471f, -0.000000591f, + -0.000000710f, -0.000000827f, -0.000000944f, -0.000001059f, -0.000001174f, + -0.000001287f, -0.000001399f, -0.000001511f, -0.000001621f, -0.000001730f, + -0.000001838f, -0.000001945f, -0.000002051f, -0.000002156f, -0.000002260f, + -0.000002363f, -0.000002465f, -0.000002565f, -0.000002665f, -0.000002763f, + -0.000002861f, -0.000002958f, -0.000003053f, -0.000003147f, -0.000003241f, + -0.000003333f, -0.000003424f, -0.000003514f, -0.000003604f, -0.000003692f, + -0.000003779f, -0.000003865f, -0.000003950f, -0.000004034f, -0.000004117f, + -0.000004199f, -0.000004280f, -0.000004360f, -0.000004439f, -0.000004517f, + -0.000004594f, -0.000004670f, -0.000004744f, -0.000004819f, -0.000004891f, + -0.000004963f, -0.000005034f, -0.000005104f, -0.000005173f, -0.000005240f, + -0.000005307f, -0.000005373f, -0.000005438f, -0.000005502f, -0.000005565f, + -0.000005627f, -0.000005688f, -0.000005748f, -0.000005807f, -0.000005866f, + -0.000005922f, -0.000005979f, -0.000006034f, -0.000006089f, -0.000006142f, + -0.000006194f, -0.000006246f, -0.000006297f, -0.000006346f, -0.000006395f, + -0.000006443f, -0.000006490f, -0.000006536f, -0.000006581f, -0.000006625f, + -0.000006668f, -0.000006711f, -0.000006752f, -0.000006793f, -0.000006833f, + -0.000006872f, -0.000006909f, -0.000006947f, -0.000006983f, -0.000007018f, + -0.000007053f, -0.000007086f, -0.000007119f, -0.000007151f, -0.000007183f, + -0.000007213f, -0.000007242f, -0.000007271f, -0.000007299f, -0.000007326f, + -0.000007352f, -0.000007377f, -0.000007402f, -0.000007426f, -0.000007449f, + -0.000007471f, -0.000007493f, -0.000007513f, -0.000007533f, -0.000007552f, + -0.000007570f, -0.000007588f, -0.000007605f, -0.000007621f, -0.000007636f, + -0.000007651f, -0.000007665f, -0.000007678f, -0.000007690f, -0.000007702f, + -0.000007713f, -0.000007723f, -0.000007733f, -0.000007742f, -0.000007750f, + -0.000007757f, -0.000007764f, -0.000007770f, -0.000007775f, -0.000007780f, + -0.000007784f, -0.000007788f, -0.000007791f, -0.000007793f, -0.000007794f, + -0.000007795f, -0.000007795f, -0.000007795f, -0.000007794f, -0.000007792f, + -0.000007790f, -0.000007787f, -0.000007784f, -0.000007780f, -0.000007775f, + -0.000007770f, -0.000007764f, -0.000007758f, -0.000007751f, -0.000007743f, + -0.000007735f, -0.000007726f, -0.000007717f, -0.000007708f, -0.000007698f, + -0.000007687f, -0.000007675f, -0.000007663f, -0.000007651f, -0.000007638f, + -0.000007625f, -0.000007611f, -0.000007597f, -0.000007582f, -0.000007567f, + -0.000007551f, -0.000007535f, -0.000007518f, -0.000007501f, -0.000007483f, + -0.000007465f, -0.000007446f, -0.000007427f, -0.000007408f, -0.000007388f, + -0.000007368f, -0.000007347f, -0.000007326f, -0.000007305f, -0.000007283f, + -0.000007261f, -0.000007238f, -0.000007215f, -0.000007191f, -0.000007168f, + -0.000007143f, -0.000007119f, -0.000007094f, -0.000007068f, -0.000007043f, + -0.000007017f, -0.000006991f, -0.000006964f, -0.000006937f, -0.000006909f, + -0.000006882f, -0.000006854f, -0.000006826f, -0.000006797f, -0.000006768f, + -0.000006739f, -0.000006710f, -0.000006680f, -0.000006650f, -0.000006620f, + -0.000006589f, -0.000006558f, -0.000006527f, -0.000006496f, -0.000006464f, + -0.000006432f, -0.000006400f, -0.000006368f, -0.000006336f, -0.000006303f, + -0.000006270f, -0.000006237f, -0.000006203f, -0.000006170f, -0.000006136f, + -0.000006102f, -0.000006068f, -0.000006033f, -0.000005999f, -0.000005964f, + -0.000005929f, -0.000005894f, -0.000005859f, -0.000005823f, -0.000005788f, + -0.000005752f, -0.000005716f, -0.000005680f, -0.000005644f, -0.000005608f, + -0.000005571f, -0.000005535f, -0.000005498f, -0.000005461f, -0.000005424f, + -0.000005388f, -0.000005350f, -0.000005313f, -0.000005276f, -0.000005239f, + -0.000005201f, -0.000005164f, -0.000005126f, -0.000005088f, -0.000005051f, + -0.000005013f, -0.000004975f, -0.000004937f, -0.000004899f, -0.000004861f, + -0.000004823f, -0.000004784f, -0.000004746f, -0.000004708f, -0.000004670f, + -0.000004632f, -0.000004593f, -0.000004555f, -0.000004517f, -0.000004478f, + -0.000004440f, -0.000004401f, -0.000004363f, -0.000004324f, -0.000004286f, + -0.000004248f, -0.000004210f, -0.000004171f, -0.000004133f, -0.000004095f, + -0.000004056f, -0.000004018f, -0.000003980f, -0.000003942f, -0.000003904f, + -0.000003865f, -0.000003827f, -0.000003789f, -0.000003751f, -0.000003714f, + -0.000003676f, -0.000003638f, -0.000003600f, -0.000003562f, -0.000003525f, + -0.000003487f, -0.000003450f, -0.000003412f, -0.000003375f, -0.000003338f, + -0.000003301f, -0.000003264f, -0.000003227f, -0.000003190f, -0.000003153f, + -0.000003117f, -0.000003080f, -0.000003044f, -0.000003007f, -0.000002971f, + -0.000002935f, -0.000002899f, -0.000002863f, -0.000002827f, -0.000002791f, + -0.000002756f, -0.000002720f, -0.000002685f, -0.000002650f, -0.000002615f, + -0.000002580f, -0.000002545f, -0.000002511f, -0.000002476f, -0.000002442f, + -0.000002408f, -0.000002373f, -0.000002340f, -0.000002306f, -0.000002272f, + -0.000002239f, -0.000002205f, -0.000002172f, -0.000002139f, -0.000002106f, + -0.000002074f, -0.000002041f, -0.000002009f, -0.000001977f, -0.000001945f, + -0.000001913f, -0.000001881f, -0.000001850f, -0.000001818f, -0.000001787f, + -0.000001756f, -0.000001726f, -0.000001695f, -0.000001665f, -0.000001634f, + -0.000001604f, -0.000001574f, -0.000001545f, -0.000001515f, -0.000001486f, + -0.000001457f, -0.000001428f, -0.000001399f, -0.000001371f, -0.000001342f, + -0.000001314f, -0.000001286f, -0.000001258f, -0.000001231f, -0.000001203f, + -0.000001176f, -0.000001149f, -0.000001123f, -0.000001096f, -0.000001070f, + 0.000000000f +}; + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_audiocvt.c b/third_party/SDL2/src/audio/SDL_audiocvt.c new file mode 100644 index 00000000000..4327ca37191 --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_audiocvt.c @@ -0,0 +1,1429 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +/* Functions for audio drivers to perform runtime conversion of audio format */ + +#include "SDL.h" +#include "SDL_audio.h" +#include "SDL_audio_c.h" + +#include "SDL_loadso.h" +#include "../SDL_dataqueue.h" +#include "SDL_cpuinfo.h" + +#define DEBUG_AUDIOSTREAM 0 + +#ifdef __ARM_NEON +#define HAVE_NEON_INTRINSICS 1 +#endif + +#ifdef __SSE__ +// #define HAVE_SSE_INTRINSICS 1 +#endif + +#ifdef __SSE3__ +// #define HAVE_SSE3_INTRINSICS 1 +#endif + +#if defined(HAVE_IMMINTRIN_H) && !defined(SDL_DISABLE_IMMINTRIN_H) +#define HAVE_AVX_INTRINSICS 1 +#endif +#if defined __clang__ +#if (!__has_attribute(target)) +#undef HAVE_AVX_INTRINSICS +#endif +#if (defined(_MSC_VER) || defined(__SCE__)) && !defined(__AVX__) +#undef HAVE_AVX_INTRINSICS +#endif +#elif defined __GNUC__ +#if (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 9) +#undef HAVE_AVX_INTRINSICS +#endif +#endif + +/* + * CHANNEL LAYOUTS AS SDL EXPECTS THEM: + * + * (Even if the platform expects something else later, that + * SDL will swizzle between the app and the platform). + * + * Abbreviations: + * - FRONT=single mono speaker + * - FL=front left speaker + * - FR=front right speaker + * - FC=front center speaker + * - BL=back left speaker + * - BR=back right speaker + * - SR=surround right speaker + * - SL=surround left speaker + * - BC=back center speaker + * - LFE=low-frequency speaker + * + * These are listed in the order they are laid out in + * memory, so "FL+FR" means "the front left speaker is + * layed out in memory first, then the front right, then + * it repeats for the next audio frame". + * + * 1 channel (mono) layout: FRONT + * 2 channels (stereo) layout: FL+FR + * 3 channels (2.1) layout: FL+FR+LFE + * 4 channels (quad) layout: FL+FR+BL+BR + * 5 channels (4.1) layout: FL+FR+LFE+BL+BR + * 6 channels (5.1) layout: FL+FR+FC+LFE+BL+BR + * 7 channels (6.1) layout: FL+FR+FC+LFE+BC+SL+SR + * 8 channels (7.1) layout: FL+FR+FC+LFE+BL+BR+SL+SR + */ + +#ifdef HAVE_SSE3_INTRINSICS +/* Convert from stereo to mono. Average left and right. */ +static void SDLCALL SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const __m128 divby2 = _mm_set1_ps(0.5f); + float *dst = (float *)cvt->buf; + const float *src = dst; + int i = cvt->len_cvt / 8; + + LOG_DEBUG_CONVERT("stereo", "mono (using SSE3)"); + SDL_assert(format == AUDIO_F32SYS); + + /* Do SSE blocks as long as we have 16 bytes available. + Just use unaligned load/stores, if the memory at runtime is + aligned it'll be just as fast on modern processors */ + while (i >= 4) { /* 4 * float32 */ + _mm_storeu_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_loadu_ps(src), _mm_loadu_ps(src + 4)), divby2)); + i -= 4; + src += 8; + dst += 4; + } + + /* Finish off any leftovers with scalar operations. */ + while (i) { + *dst = (src[0] + src[1]) * 0.5f; + dst++; + i--; + src += 2; + } + + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} +#endif + +#ifdef HAVE_SSE_INTRINSICS +/* Convert from mono to stereo. Duplicate to stereo left and right. */ +static void SDLCALL SDL_ConvertMonoToStereo_SSE(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + float *dst = ((float *)(cvt->buf + (cvt->len_cvt * 2))) - 8; + const float *src = ((const float *)(cvt->buf + cvt->len_cvt)) - 4; + int i = cvt->len_cvt / sizeof(float); + + LOG_DEBUG_CONVERT("mono", "stereo (using SSE)"); + SDL_assert(format == AUDIO_F32SYS); + + /* Do SSE blocks as long as we have 16 bytes available. + Just use unaligned load/stores, if the memory at runtime is + aligned it'll be just as fast on modern processors */ + /* convert backwards, since output is growing in-place. */ + while (i >= 4) { /* 4 * float32 */ + const __m128 input = _mm_loadu_ps(src); /* A B C D */ + _mm_storeu_ps(dst, _mm_unpacklo_ps(input, input)); /* A A B B */ + _mm_storeu_ps(dst + 4, _mm_unpackhi_ps(input, input)); /* C C D D */ + i -= 4; + src -= 4; + dst -= 8; + } + + /* Finish off any leftovers with scalar operations. */ + src += 3; + dst += 6; /* adjust for smaller buffers. */ + while (i) { /* convert backwards, since output is growing in-place. */ + const float srcFC = src[0]; + dst[1] /* FR */ = srcFC; + dst[0] /* FL */ = srcFC; + i--; + src--; + dst -= 2; + } + + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} +#endif + +/* Include the autogenerated channel converters... */ +#include "SDL_audio_channel_converters.h" + +/* SDL's resampler uses a "bandlimited interpolation" algorithm: + https://ccrma.stanford.edu/~jos/resample/ */ + +#include "SDL_audio_resampler_filter.h" + +static Sint32 ResamplerPadding(const Sint32 inrate, const Sint32 outrate) +{ + /* This function uses integer arithmetics to avoid precision loss caused + * by large floating point numbers. Sint32 is needed for the large number + * multiplication. The integers are assumed to be non-negative so that + * division rounds by truncation. */ + if (inrate == outrate) { + return 0; + } + if (inrate > outrate) { + return (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * inrate + outrate - 1) / outrate; + } + return RESAMPLER_SAMPLES_PER_ZERO_CROSSING; +} + +/* lpadding and rpadding are expected to be buffers of (ResamplePadding(inrate, outrate) * chans * sizeof(float)) bytes. */ +static int SDL_ResampleAudio(const int chans, const int inrate, const int outrate, + const float *lpadding, const float *rpadding, + const float *inbuf, const int inbuflen, + float *outbuf, const int outbuflen) +{ + /* This function uses integer arithmetics to avoid precision loss caused + * by large floating point numbers. For some operations, Sint32 or Sint64 + * are needed for the large number multiplications. The input integers are + * assumed to be non-negative so that division rounds by truncation and + * modulo is always non-negative. Note that the operator order is important + * for these integer divisions. */ + const int paddinglen = ResamplerPadding(inrate, outrate); + const int framelen = chans * (int)sizeof(float); + const int inframes = inbuflen / framelen; + /* outbuflen isn't total to write, it's total available. */ + const int wantedoutframes = (int)((Sint64)inframes * outrate / inrate); + const int maxoutframes = outbuflen / framelen; + const int outframes = SDL_min(wantedoutframes, maxoutframes); + float *dst = outbuf; + int i, j, chan; + + for (i = 0; i < outframes; i++) { + const int srcindex = (int)((Sint64)i * inrate / outrate); + /* Calculating the following way avoids subtraction or modulo of large + * floats which have low result precision. + * interpolation1 + * = (i / outrate * inrate) - floor(i / outrate * inrate) + * = mod(i / outrate * inrate, 1) + * = mod(i * inrate, outrate) / outrate */ + const int srcfraction = ((Sint64)i) * inrate % outrate; + const float interpolation1 = ((float)srcfraction) / ((float)outrate); + const int filterindex1 = ((Sint32)srcfraction) * RESAMPLER_SAMPLES_PER_ZERO_CROSSING / outrate; + const float interpolation2 = 1.0f - interpolation1; + const int filterindex2 = ((Sint32)(outrate - srcfraction)) * RESAMPLER_SAMPLES_PER_ZERO_CROSSING / outrate; + + for (chan = 0; chan < chans; chan++) { + float outsample = 0.0f; + + /* do this twice to calculate the sample, once for the "left wing" and then same for the right. */ + for (j = 0; (filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) { + const int filt_ind = filterindex1 + j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING; + const int srcframe = srcindex - j; + /* !!! FIXME: we can bubble this conditional out of here by doing a pre loop. */ + const float insample = (srcframe < 0) ? lpadding[((paddinglen + srcframe) * chans) + chan] : inbuf[(srcframe * chans) + chan]; + outsample += (float) (insample * (ResamplerFilter[filt_ind] + (interpolation1 * ResamplerFilterDifference[filt_ind]))); + } + + /* Do the right wing! */ + for (j = 0; (filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) { + const int filt_ind = filterindex2 + j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING; + const int srcframe = srcindex + 1 + j; + /* !!! FIXME: we can bubble this conditional out of here by doing a post loop. */ + const float insample = (srcframe >= inframes) ? rpadding[((srcframe - inframes) * chans) + chan] : inbuf[(srcframe * chans) + chan]; + outsample += (float) (insample * (ResamplerFilter[filt_ind] + (interpolation2 * ResamplerFilterDifference[filt_ind]))); + } + + *(dst++) = outsample; + } + } + + return outframes * chans * sizeof(float); +} + +int SDL_ConvertAudio(SDL_AudioCVT *cvt) +{ + /* !!! FIXME: (cvt) should be const; stack-copy it here. */ + /* !!! FIXME: (actually, we can't...len_cvt needs to be updated. Grr.) */ + + /* Make sure there's data to convert */ + if (!cvt->buf) { + return SDL_SetError("No buffer allocated for conversion"); + } + + /* Return okay if no conversion is necessary */ + cvt->len_cvt = cvt->len; + if (cvt->filters[0] == NULL) { + return 0; + } + + /* Set up the conversion and go! */ + cvt->filter_index = 0; + cvt->filters[0](cvt, cvt->src_format); + return 0; +} + +static void SDLCALL SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ +#if DEBUG_CONVERT + SDL_Log("SDL_AUDIO_CONVERT: Converting byte order\n"); +#endif + + switch (SDL_AUDIO_BITSIZE(format)) { +#define CASESWAP(b) \ + case b: \ + { \ + Uint##b *ptr = (Uint##b *)cvt->buf; \ + int i; \ + for (i = cvt->len_cvt / sizeof(*ptr); i; --i, ++ptr) { \ + *ptr = SDL_Swap##b(*ptr); \ + } \ + break; \ + } + + CASESWAP(16); + CASESWAP(32); + CASESWAP(64); + +#undef CASESWAP + + default: + SDL_assert(!"unhandled byteswap datatype!"); + break; + } + + if (cvt->filters[++cvt->filter_index]) { + /* flip endian flag for data. */ + if (format & SDL_AUDIO_MASK_ENDIAN) { + format &= ~SDL_AUDIO_MASK_ENDIAN; + } else { + format |= SDL_AUDIO_MASK_ENDIAN; + } + cvt->filters[cvt->filter_index](cvt, format); + } +} + +static int SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, SDL_AudioFilter filter) +{ + if (cvt->filter_index >= SDL_AUDIOCVT_MAX_FILTERS) { + return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS); + } + SDL_assert(filter != NULL); + cvt->filters[cvt->filter_index++] = filter; + cvt->filters[cvt->filter_index] = NULL; /* Moving terminator */ + return 0; +} + +static int SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt) +{ + int retval = 0; /* 0 == no conversion necessary. */ + + if ((SDL_AUDIO_ISBIGENDIAN(src_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN) && SDL_AUDIO_BITSIZE(src_fmt) > 8) { + if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) { + return -1; + } + retval = 1; /* added a converter. */ + } + + if (!SDL_AUDIO_ISFLOAT(src_fmt)) { + const Uint16 src_bitsize = SDL_AUDIO_BITSIZE(src_fmt); + const Uint16 dst_bitsize = 32; + SDL_AudioFilter filter = NULL; + + switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) { + case AUDIO_S8: + filter = SDL_Convert_S8_to_F32; + break; + case AUDIO_U8: + filter = SDL_Convert_U8_to_F32; + break; + case AUDIO_S16: + filter = SDL_Convert_S16_to_F32; + break; + case AUDIO_U16: + filter = SDL_Convert_U16_to_F32; + break; + case AUDIO_S32: + filter = SDL_Convert_S32_to_F32; + break; + default: + SDL_assert(!"Unexpected audio format!"); + break; + } + + if (!filter) { + return SDL_SetError("No conversion from source format to float available"); + } + + if (SDL_AddAudioCVTFilter(cvt, filter) < 0) { + return -1; + } + if (src_bitsize < dst_bitsize) { + const int mult = (dst_bitsize / src_bitsize); + cvt->len_mult *= mult; + cvt->len_ratio *= mult; + } else if (src_bitsize > dst_bitsize) { + const int div = (src_bitsize / dst_bitsize); + cvt->len_ratio /= div; + } + + retval = 1; /* added a converter. */ + } + + return retval; +} + +static int SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt) +{ + int retval = 0; /* 0 == no conversion necessary. */ + + if (!SDL_AUDIO_ISFLOAT(dst_fmt)) { + const Uint16 dst_bitsize = SDL_AUDIO_BITSIZE(dst_fmt); + const Uint16 src_bitsize = 32; + SDL_AudioFilter filter = NULL; + switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) { + case AUDIO_S8: + filter = SDL_Convert_F32_to_S8; + break; + case AUDIO_U8: + filter = SDL_Convert_F32_to_U8; + break; + case AUDIO_S16: + filter = SDL_Convert_F32_to_S16; + break; + case AUDIO_U16: + filter = SDL_Convert_F32_to_U16; + break; + case AUDIO_S32: + filter = SDL_Convert_F32_to_S32; + break; + default: + SDL_assert(!"Unexpected audio format!"); + break; + } + + if (!filter) { + return SDL_SetError("No conversion from float to format 0x%.4x available", dst_fmt); + } + + if (SDL_AddAudioCVTFilter(cvt, filter) < 0) { + return -1; + } + if (src_bitsize < dst_bitsize) { + const int mult = (dst_bitsize / src_bitsize); + cvt->len_mult *= mult; + cvt->len_ratio *= mult; + } else if (src_bitsize > dst_bitsize) { + const int div = (src_bitsize / dst_bitsize); + cvt->len_ratio /= div; + } + retval = 1; /* added a converter. */ + } + + if ((SDL_AUDIO_ISBIGENDIAN(dst_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN) && SDL_AUDIO_BITSIZE(dst_fmt) > 8) { + if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) { + return -1; + } + retval = 1; /* added a converter. */ + } + + return retval; +} + +#ifdef HAVE_LIBSAMPLERATE_H + +static void SDL_ResampleCVT_SRC(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + const int srclen = cvt->len_cvt; + float *dst = (float *)(cvt->buf + srclen); + const int dstlen = (cvt->len * cvt->len_mult) - srclen; + const int framelen = sizeof(float) * chans; + int result = 0; + SRC_DATA data; + + SDL_zero(data); + + data.data_in = (float *)src; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */ + data.input_frames = srclen / framelen; + + data.data_out = dst; + data.output_frames = dstlen / framelen; + + data.src_ratio = cvt->rate_incr; + + result = SRC_src_simple(&data, SRC_converter, chans); /* Simple API converts the whole buffer at once. No need for initialization. */ +/* !!! FIXME: Handle library failures? */ +#if DEBUG_CONVERT + if (result != 0) { + SDL_Log("src_simple() failed: %s", SRC_src_strerror(result)); + } +#else + (void)result; +#endif + + cvt->len_cvt = data.output_frames_gen * framelen; + + SDL_memmove(cvt->buf, dst, cvt->len_cvt); + + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +#endif /* HAVE_LIBSAMPLERATE_H */ + +static void SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format) +{ + /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator). + !!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates, + !!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */ + const int inrate = (int)(size_t)cvt->filters[SDL_AUDIOCVT_MAX_FILTERS - 1]; + const int outrate = (int)(size_t)cvt->filters[SDL_AUDIOCVT_MAX_FILTERS]; + const float *src = (const float *)cvt->buf; + const int srclen = cvt->len_cvt; + /*float *dst = (float *) cvt->buf; + const int dstlen = (cvt->len * cvt->len_mult);*/ + /* !!! FIXME: remove this if we can get the resampler to work in-place again. */ + float *dst = (float *)(cvt->buf + srclen); + const int dstlen = (cvt->len * cvt->len_mult) - srclen; + const int requestedpadding = ResamplerPadding(inrate, outrate); + int paddingsamples; + float *padding; + + if (requestedpadding < SDL_MAX_SINT32 / chans) { + paddingsamples = requestedpadding * chans; + } else { + paddingsamples = 0; + } + SDL_assert(format == AUDIO_F32SYS); + + /* we keep no streaming state here, so pad with silence on both ends. */ + padding = (float *)SDL_calloc(paddingsamples ? paddingsamples : 1, sizeof(float)); + if (!padding) { + SDL_OutOfMemory(); + return; + } + + cvt->len_cvt = SDL_ResampleAudio(chans, inrate, outrate, padding, padding, src, srclen, dst, dstlen); + + SDL_free(padding); + + SDL_memmove(cvt->buf, dst, cvt->len_cvt); /* !!! FIXME: remove this if we can get the resampler to work in-place again. */ + + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, format); + } +} + +/* !!! FIXME: We only have this macro salsa because SDL_AudioCVT doesn't + !!! FIXME: store channel info, so we have to have function entry + !!! FIXME: points for each supported channel count and multiple + !!! FIXME: vs arbitrary. When we rev the ABI, clean this up. */ +#define RESAMPLER_FUNCS(chans) \ + static void SDLCALL \ + SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) \ + { \ + SDL_ResampleCVT(cvt, chans, format); \ + } +RESAMPLER_FUNCS(1) +RESAMPLER_FUNCS(2) +RESAMPLER_FUNCS(4) +RESAMPLER_FUNCS(6) +RESAMPLER_FUNCS(8) +#undef RESAMPLER_FUNCS + +#ifdef HAVE_LIBSAMPLERATE_H +#define RESAMPLER_FUNCS(chans) \ + static void SDLCALL \ + SDL_ResampleCVT_SRC_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) \ + { \ + SDL_ResampleCVT_SRC(cvt, chans, format); \ + } +RESAMPLER_FUNCS(1) +RESAMPLER_FUNCS(2) +RESAMPLER_FUNCS(4) +RESAMPLER_FUNCS(6) +RESAMPLER_FUNCS(8) +#undef RESAMPLER_FUNCS +#endif /* HAVE_LIBSAMPLERATE_H */ + +static SDL_AudioFilter ChooseCVTResampler(const int dst_channels) +{ +#ifdef HAVE_LIBSAMPLERATE_H + if (SRC_available) { + switch (dst_channels) { + case 1: + return SDL_ResampleCVT_SRC_c1; + case 2: + return SDL_ResampleCVT_SRC_c2; + case 4: + return SDL_ResampleCVT_SRC_c4; + case 6: + return SDL_ResampleCVT_SRC_c6; + case 8: + return SDL_ResampleCVT_SRC_c8; + default: + break; + } + } +#endif /* HAVE_LIBSAMPLERATE_H */ + + switch (dst_channels) { + case 1: + return SDL_ResampleCVT_c1; + case 2: + return SDL_ResampleCVT_c2; + case 4: + return SDL_ResampleCVT_c4; + case 6: + return SDL_ResampleCVT_c6; + case 8: + return SDL_ResampleCVT_c8; + default: + break; + } + + return NULL; +} + +static int SDL_BuildAudioResampleCVT(SDL_AudioCVT *cvt, const int dst_channels, + const int src_rate, const int dst_rate) +{ + SDL_AudioFilter filter; + + if (src_rate == dst_rate) { + return 0; /* no conversion necessary. */ + } + + filter = ChooseCVTResampler(dst_channels); + if (!filter) { + return SDL_SetError("No conversion available for these rates"); + } + + /* Update (cvt) with filter details... */ + if (SDL_AddAudioCVTFilter(cvt, filter) < 0) { + return -1; + } + + /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator). + !!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates, + !!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */ + if (cvt->filter_index >= (SDL_AUDIOCVT_MAX_FILTERS - 2)) { + return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS - 2); + } + cvt->filters[SDL_AUDIOCVT_MAX_FILTERS - 1] = (SDL_AudioFilter)(uintptr_t)src_rate; + cvt->filters[SDL_AUDIOCVT_MAX_FILTERS] = (SDL_AudioFilter)(uintptr_t)dst_rate; + + if (src_rate < dst_rate) { + const double mult = ((double)dst_rate) / ((double)src_rate); + cvt->len_mult *= (int)SDL_ceil(mult); + cvt->len_ratio *= mult; + } else { + cvt->len_ratio /= ((double)src_rate) / ((double)dst_rate); + } + + /* !!! FIXME: remove this if we can get the resampler to work in-place again. */ + /* the buffer is big enough to hold the destination now, but + we need it large enough to hold a separate scratch buffer. */ + cvt->len_mult *= 2; + + return 1; /* added a converter. */ +} + +static SDL_bool SDL_SupportedAudioFormat(const SDL_AudioFormat fmt) +{ + switch (fmt) { + case AUDIO_U8: + case AUDIO_S8: + case AUDIO_U16LSB: + case AUDIO_S16LSB: + case AUDIO_U16MSB: + case AUDIO_S16MSB: + case AUDIO_S32LSB: + case AUDIO_S32MSB: + case AUDIO_F32LSB: + case AUDIO_F32MSB: + return SDL_TRUE; /* supported. */ + + default: + break; + } + + return SDL_FALSE; /* unsupported. */ +} + +static SDL_bool SDL_SupportedChannelCount(const int channels) +{ + return ((channels >= 1) && (channels <= 8)) ? SDL_TRUE : SDL_FALSE; +} + +/* Creates a set of audio filters to convert from one format to another. + Returns 0 if no conversion is needed, 1 if the audio filter is set up, + or -1 if an error like invalid parameter, unsupported format, etc. occurred. +*/ + +int SDL_BuildAudioCVT(SDL_AudioCVT *cvt, + SDL_AudioFormat src_format, Uint8 src_channels, int src_rate, + SDL_AudioFormat dst_format, Uint8 dst_channels, int dst_rate) +{ + SDL_AudioFilter channel_converter = NULL; + + /* Sanity check target pointer */ + if (!cvt) { + return SDL_InvalidParamError("cvt"); + } + + /* Make sure we zero out the audio conversion before error checking */ + SDL_zerop(cvt); + + if (!SDL_SupportedAudioFormat(src_format)) { + return SDL_SetError("Invalid source format"); + } + if (!SDL_SupportedAudioFormat(dst_format)) { + return SDL_SetError("Invalid destination format"); + } + if (!SDL_SupportedChannelCount(src_channels)) { + return SDL_SetError("Invalid source channels"); + } + if (!SDL_SupportedChannelCount(dst_channels)) { + return SDL_SetError("Invalid destination channels"); + } + if (src_rate <= 0) { + return SDL_SetError("Source rate is equal to or less than zero"); + } + if (dst_rate <= 0) { + return SDL_SetError("Destination rate is equal to or less than zero"); + } + if (src_rate >= SDL_MAX_SINT32 / RESAMPLER_SAMPLES_PER_ZERO_CROSSING) { + return SDL_SetError("Source rate is too high"); + } + if (dst_rate >= SDL_MAX_SINT32 / RESAMPLER_SAMPLES_PER_ZERO_CROSSING) { + return SDL_SetError("Destination rate is too high"); + } + +#if DEBUG_CONVERT + SDL_Log("SDL_AUDIO_CONVERT: Build format %04x->%04x, channels %u->%u, rate %d->%d\n", + src_format, dst_format, src_channels, dst_channels, src_rate, dst_rate); +#endif + + /* Start off with no conversion necessary */ + cvt->src_format = src_format; + cvt->dst_format = dst_format; + cvt->needed = 0; + cvt->filter_index = 0; + SDL_zeroa(cvt->filters); + cvt->len_mult = 1; + cvt->len_ratio = 1.0; + cvt->rate_incr = ((double)dst_rate) / ((double)src_rate); + + /* Make sure we've chosen audio conversion functions (SIMD, scalar, etc.) */ + SDL_ChooseAudioConverters(); + + /* Type conversion goes like this now: + - byteswap to CPU native format first if necessary. + - convert to native Float32 if necessary. + - resample and change channel count if necessary. + - convert to final data format. + - byteswap back to foreign format if necessary. + + The expectation is we can process data faster in float32 + (possibly with SIMD), and making several passes over the same + buffer is likely to be CPU cache-friendly, avoiding the + biggest performance hit in modern times. Previously we had + (script-generated) custom converters for every data type and + it was a bloat on SDL compile times and final library size. */ + + /* see if we can skip float conversion entirely. */ + if (src_rate == dst_rate && src_channels == dst_channels) { + if (src_format == dst_format) { + return 0; + } + + /* just a byteswap needed? */ + if ((src_format & ~SDL_AUDIO_MASK_ENDIAN) == (dst_format & ~SDL_AUDIO_MASK_ENDIAN)) { + if (SDL_AUDIO_BITSIZE(dst_format) == 8) { + return 0; + } + if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) { + return -1; + } + cvt->needed = 1; + return 1; + } + } + + /* Convert data types, if necessary. Updates (cvt). */ + if (SDL_BuildAudioTypeCVTToFloat(cvt, src_format) < 0) { + return -1; /* shouldn't happen, but just in case... */ + } + + /* Channel conversion */ + + /* SDL_SupportedChannelCount should have caught these asserts, or we added a new format and forgot to update the table. */ + SDL_assert(src_channels <= SDL_arraysize(channel_converters)); + SDL_assert(dst_channels <= SDL_arraysize(channel_converters[0])); + + channel_converter = channel_converters[src_channels - 1][dst_channels - 1]; + if ((!channel_converter) != (src_channels == dst_channels)) { + /* All combinations of supported channel counts should have been handled by now, but let's be defensive */ + return SDL_SetError("Invalid channel combination"); + } else if (channel_converter != NULL) { + /* swap in some SIMD versions for a few of these. */ + if (channel_converter == SDL_ConvertStereoToMono) { + SDL_AudioFilter filter = NULL; +#ifdef HAVE_SSE3_INTRINSICS + if (!filter && SDL_HasSSE3()) { + filter = SDL_ConvertStereoToMono_SSE3; + } +#endif + if (filter) { + channel_converter = filter; + } + } else if (channel_converter == SDL_ConvertMonoToStereo) { + SDL_AudioFilter filter = NULL; +#ifdef HAVE_SSE_INTRINSICS + if (!filter && SDL_HasSSE()) { + filter = SDL_ConvertMonoToStereo_SSE; + } +#endif + if (filter) { + channel_converter = filter; + } + } + + if (SDL_AddAudioCVTFilter(cvt, channel_converter) < 0) { + return -1; + } + + if (src_channels < dst_channels) { + cvt->len_mult = ((cvt->len_mult * dst_channels) + (src_channels - 1)) / src_channels; + } + + cvt->len_ratio = (cvt->len_ratio * dst_channels) / src_channels; + src_channels = dst_channels; + } + + /* Do rate conversion, if necessary. Updates (cvt). */ + if (SDL_BuildAudioResampleCVT(cvt, dst_channels, src_rate, dst_rate) < 0) { + return -1; /* shouldn't happen, but just in case... */ + } + + /* Move to final data type. */ + if (SDL_BuildAudioTypeCVTFromFloat(cvt, dst_format) < 0) { + return -1; /* shouldn't happen, but just in case... */ + } + + cvt->needed = (cvt->filter_index != 0); + return cvt->needed; +} + +typedef int (*SDL_ResampleAudioStreamFunc)(SDL_AudioStream *stream, const void *inbuf, const int inbuflen, void *outbuf, const int outbuflen); +typedef void (*SDL_ResetAudioStreamResamplerFunc)(SDL_AudioStream *stream); +typedef void (*SDL_CleanupAudioStreamResamplerFunc)(SDL_AudioStream *stream); + +struct _SDL_AudioStream +{ + SDL_AudioCVT cvt_before_resampling; + SDL_AudioCVT cvt_after_resampling; + SDL_DataQueue *queue; + SDL_bool first_run; + Uint8 *staging_buffer; + int staging_buffer_size; + int staging_buffer_filled; + Uint8 *work_buffer_base; /* maybe unaligned pointer from SDL_realloc(). */ + int work_buffer_len; + int src_sample_frame_size; + SDL_AudioFormat src_format; + Uint8 src_channels; + int src_rate; + int dst_sample_frame_size; + SDL_AudioFormat dst_format; + Uint8 dst_channels; + int dst_rate; + double rate_incr; + Uint8 pre_resample_channels; + int packetlen; + int resampler_padding_samples; + float *resampler_padding; + void *resampler_state; + SDL_ResampleAudioStreamFunc resampler_func; + SDL_ResetAudioStreamResamplerFunc reset_resampler_func; + SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func; +}; + +static Uint8 *EnsureStreamBufferSize(SDL_AudioStream *stream, int newlen) +{ + Uint8 *ptr; + size_t offset; + + if (stream->work_buffer_len >= newlen) { + ptr = stream->work_buffer_base; + } else { + ptr = (Uint8 *)SDL_realloc(stream->work_buffer_base, (size_t)newlen + 32); + if (!ptr) { + SDL_OutOfMemory(); + return NULL; + } + /* Make sure we're aligned to 16 bytes for SIMD code. */ + stream->work_buffer_base = ptr; + stream->work_buffer_len = newlen; + } + + offset = ((size_t)ptr) & 15; + return offset ? ptr + (16 - offset) : ptr; +} + +#ifdef HAVE_LIBSAMPLERATE_H +static int SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen) +{ + const float *inbuf = (const float *)_inbuf; + float *outbuf = (float *)_outbuf; + const int framelen = sizeof(float) * stream->pre_resample_channels; + SRC_STATE *state = (SRC_STATE *)stream->resampler_state; + SRC_DATA data; + int result; + + SDL_assert(inbuf != ((const float *)outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */ + + data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */ + data.input_frames = inbuflen / framelen; + data.input_frames_used = 0; + + data.data_out = outbuf; + data.output_frames = outbuflen / framelen; + + data.end_of_input = 0; + data.src_ratio = stream->rate_incr; + + result = SRC_src_process(state, &data); + if (result != 0) { + SDL_SetError("src_process() failed: %s", SRC_src_strerror(result)); + return 0; + } + + /* If this fails, we need to store them off somewhere */ + SDL_assert(data.input_frames_used == data.input_frames); + + return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels); +} + +static void SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream) +{ + SRC_src_reset((SRC_STATE *)stream->resampler_state); +} + +static void SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream) +{ + SRC_STATE *state = (SRC_STATE *)stream->resampler_state; + if (state) { + SRC_src_delete(state); + } + + stream->resampler_state = NULL; + stream->resampler_func = NULL; + stream->reset_resampler_func = NULL; + stream->cleanup_resampler_func = NULL; +} + +static SDL_bool SetupLibSampleRateResampling(SDL_AudioStream *stream) +{ + int result = 0; + SRC_STATE *state = NULL; + + if (SRC_available) { + state = SRC_src_new(SRC_converter, stream->pre_resample_channels, &result); + if (!state) { + SDL_SetError("src_new() failed: %s", SRC_src_strerror(result)); + } + } + + if (!state) { + SDL_CleanupAudioStreamResampler_SRC(stream); + return SDL_FALSE; + } + + stream->resampler_state = state; + stream->resampler_func = SDL_ResampleAudioStream_SRC; + stream->reset_resampler_func = SDL_ResetAudioStreamResampler_SRC; + stream->cleanup_resampler_func = SDL_CleanupAudioStreamResampler_SRC; + + return SDL_TRUE; +} +#endif /* HAVE_LIBSAMPLERATE_H */ + +static int SDL_ResampleAudioStream(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen) +{ + const Uint8 *inbufend = ((const Uint8 *)_inbuf) + inbuflen; + const float *inbuf = (const float *)_inbuf; + float *outbuf = (float *)_outbuf; + const int chans = (int)stream->pre_resample_channels; + const int inrate = stream->src_rate; + const int outrate = stream->dst_rate; + const int paddingsamples = stream->resampler_padding_samples; + const int paddingbytes = paddingsamples * sizeof(float); + float *lpadding = (float *)stream->resampler_state; + const float *rpadding = (const float *)inbufend; /* we set this up so there are valid padding samples at the end of the input buffer. */ + const int cpy = SDL_min(inbuflen, paddingbytes); + int retval; + + SDL_assert(inbuf != ((const float *)outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */ + + retval = SDL_ResampleAudio(chans, inrate, outrate, lpadding, rpadding, inbuf, inbuflen, outbuf, outbuflen); + + /* update our left padding with end of current input, for next run. */ + SDL_memcpy((lpadding + paddingsamples) - (cpy / sizeof(float)), inbufend - cpy, cpy); + return retval; +} + +static void SDL_ResetAudioStreamResampler(SDL_AudioStream *stream) +{ + /* set all the padding to silence. */ + const int len = stream->resampler_padding_samples; + SDL_memset(stream->resampler_state, '\0', len * sizeof(float)); +} + +static void SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream) +{ + SDL_free(stream->resampler_state); +} + +SDL_AudioStream *SDL_NewAudioStream(const SDL_AudioFormat src_format, + const Uint8 src_channels, + const int src_rate, + const SDL_AudioFormat dst_format, + const Uint8 dst_channels, + const int dst_rate) +{ + int packetlen = 4096; /* !!! FIXME: good enough for now. */ + Uint8 pre_resample_channels; + SDL_AudioStream *retval; + + if (src_channels == 0) { + SDL_InvalidParamError("src_channels"); + return NULL; + } + + if (dst_channels == 0) { + SDL_InvalidParamError("dst_channels"); + return NULL; + } + + retval = (SDL_AudioStream *)SDL_calloc(1, sizeof(SDL_AudioStream)); + if (!retval) { + SDL_OutOfMemory(); + return NULL; + } + + /* If increasing channels, do it after resampling, since we'd just + do more work to resample duplicate channels. If we're decreasing, do + it first so we resample the interpolated data instead of interpolating + the resampled data (!!! FIXME: decide if that works in practice, though!). */ + pre_resample_channels = SDL_min(src_channels, dst_channels); + + retval->first_run = SDL_TRUE; + retval->src_sample_frame_size = (SDL_AUDIO_BITSIZE(src_format) / 8) * src_channels; + retval->src_format = src_format; + retval->src_channels = src_channels; + retval->src_rate = src_rate; + retval->dst_sample_frame_size = (SDL_AUDIO_BITSIZE(dst_format) / 8) * dst_channels; + retval->dst_format = dst_format; + retval->dst_channels = dst_channels; + retval->dst_rate = dst_rate; + retval->pre_resample_channels = pre_resample_channels; + retval->packetlen = packetlen; + retval->rate_incr = ((double)dst_rate) / ((double)src_rate); + retval->resampler_padding_samples = ResamplerPadding(retval->src_rate, retval->dst_rate) * pre_resample_channels; + retval->resampler_padding = (float *)SDL_calloc(retval->resampler_padding_samples ? retval->resampler_padding_samples : 1, sizeof(float)); + + if (!retval->resampler_padding) { + SDL_FreeAudioStream(retval); + SDL_OutOfMemory(); + return NULL; + } + + retval->staging_buffer_size = ((retval->resampler_padding_samples / retval->pre_resample_channels) * retval->src_sample_frame_size); + if (retval->staging_buffer_size > 0) { + retval->staging_buffer = (Uint8 *)SDL_malloc(retval->staging_buffer_size); + if (!retval->staging_buffer) { + SDL_FreeAudioStream(retval); + SDL_OutOfMemory(); + return NULL; + } + } + + /* Not resampling? It's an easy conversion (and maybe not even that!) */ + if (src_rate == dst_rate) { + retval->cvt_before_resampling.needed = SDL_FALSE; + if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, src_format, src_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) { + SDL_FreeAudioStream(retval); + return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */ + } + } else { + /* Don't resample at first. Just get us to Float32 format. */ + /* !!! FIXME: convert to int32 on devices without hardware float. */ + if (SDL_BuildAudioCVT(&retval->cvt_before_resampling, src_format, src_channels, src_rate, AUDIO_F32SYS, pre_resample_channels, src_rate) < 0) { + SDL_FreeAudioStream(retval); + return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */ + } + +#ifdef HAVE_LIBSAMPLERATE_H + SetupLibSampleRateResampling(retval); +#endif + + if (!retval->resampler_func) { + retval->resampler_state = SDL_calloc(retval->resampler_padding_samples, sizeof(float)); + if (!retval->resampler_state) { + SDL_FreeAudioStream(retval); + SDL_OutOfMemory(); + return NULL; + } + + retval->resampler_func = SDL_ResampleAudioStream; + retval->reset_resampler_func = SDL_ResetAudioStreamResampler; + retval->cleanup_resampler_func = SDL_CleanupAudioStreamResampler; + } + + /* Convert us to the final format after resampling. */ + if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, AUDIO_F32SYS, pre_resample_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) { + SDL_FreeAudioStream(retval); + return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */ + } + } + + retval->queue = SDL_NewDataQueue(packetlen, (size_t)packetlen * 2); + if (!retval->queue) { + SDL_FreeAudioStream(retval); + return NULL; /* SDL_NewDataQueue should have called SDL_SetError. */ + } + + return retval; +} + +static int SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, int *maxputbytes) +{ + int buflen = len; + int workbuflen; + Uint8 *workbuf; + Uint8 *resamplebuf = NULL; + int resamplebuflen = 0; + int neededpaddingbytes; + int paddingbytes; + + /* !!! FIXME: several converters can take advantage of SIMD, but only + !!! FIXME: if the data is aligned to 16 bytes. EnsureStreamBufferSize() + !!! FIXME: guarantees the buffer will align, but the + !!! FIXME: converters will iterate over the data backwards if + !!! FIXME: the output grows, and this means we won't align if buflen + !!! FIXME: isn't a multiple of 16. In these cases, we should chop off + !!! FIXME: a few samples at the end and convert them separately. */ + + /* no padding prepended on first run. */ + neededpaddingbytes = stream->resampler_padding_samples * sizeof(float); + paddingbytes = stream->first_run ? 0 : neededpaddingbytes; + stream->first_run = SDL_FALSE; + + /* Make sure the work buffer can hold all the data we need at once... */ + workbuflen = buflen; + if (stream->cvt_before_resampling.needed) { + workbuflen *= stream->cvt_before_resampling.len_mult; + } + + if (stream->dst_rate != stream->src_rate) { + /* resamples can't happen in place, so make space for second buf. */ + const int framesize = stream->pre_resample_channels * sizeof(float); + const int frames = workbuflen / framesize; + resamplebuflen = ((int)SDL_ceil(frames * stream->rate_incr)) * framesize; +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: will resample %d bytes to %d (ratio=%.6f)\n", workbuflen, resamplebuflen, stream->rate_incr); +#endif + workbuflen += resamplebuflen; + } + + if (stream->cvt_after_resampling.needed) { + /* !!! FIXME: buffer might be big enough already? */ + workbuflen *= stream->cvt_after_resampling.len_mult; + } + + workbuflen += neededpaddingbytes; + +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: Putting %d bytes of preconverted audio, need %d byte work buffer\n", buflen, workbuflen); +#endif + + workbuf = EnsureStreamBufferSize(stream, workbuflen); + if (!workbuf) { + return -1; /* probably out of memory. */ + } + + resamplebuf = workbuf; /* default if not resampling. */ + + SDL_memcpy(workbuf + paddingbytes, buf, buflen); + + if (stream->cvt_before_resampling.needed) { + stream->cvt_before_resampling.buf = workbuf + paddingbytes; + stream->cvt_before_resampling.len = buflen; + if (SDL_ConvertAudio(&stream->cvt_before_resampling) == -1) { + return -1; /* uhoh! */ + } + buflen = stream->cvt_before_resampling.len_cvt; + +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: After initial conversion we have %d bytes\n", buflen); +#endif + } + + if (stream->dst_rate != stream->src_rate) { + /* save off some samples at the end; they are used for padding now so + the resampler is coherent and then used at the start of the next + put operation. Prepend last put operation's padding, too. */ + + /* prepend prior put's padding. :P */ + if (paddingbytes) { + SDL_memcpy(workbuf, stream->resampler_padding, paddingbytes); + buflen += paddingbytes; + } + + /* save off the data at the end for the next run. */ + SDL_memcpy(stream->resampler_padding, workbuf + (buflen - neededpaddingbytes), neededpaddingbytes); + + resamplebuf = workbuf + buflen; /* skip to second piece of workbuf. */ + SDL_assert(buflen >= neededpaddingbytes); + if (buflen > neededpaddingbytes) { + buflen = stream->resampler_func(stream, workbuf, buflen - neededpaddingbytes, resamplebuf, resamplebuflen); + } else { + buflen = 0; + } + +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: After resampling we have %d bytes\n", buflen); +#endif + } + + if (stream->cvt_after_resampling.needed && (buflen > 0)) { + stream->cvt_after_resampling.buf = resamplebuf; + stream->cvt_after_resampling.len = buflen; + if (SDL_ConvertAudio(&stream->cvt_after_resampling) == -1) { + return -1; /* uhoh! */ + } + buflen = stream->cvt_after_resampling.len_cvt; + +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: After final conversion we have %d bytes\n", buflen); +#endif + } + +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: Final output is %d bytes\n", buflen); +#endif + + if (maxputbytes) { + const int maxbytes = *maxputbytes; + if (buflen > maxbytes) { + buflen = maxbytes; + } + *maxputbytes -= buflen; + } + + /* resamplebuf holds the final output, even if we didn't resample. */ + return buflen ? SDL_WriteToDataQueue(stream->queue, resamplebuf, buflen) : 0; +} + +int SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len) +{ + /* !!! FIXME: several converters can take advantage of SIMD, but only + !!! FIXME: if the data is aligned to 16 bytes. EnsureStreamBufferSize() + !!! FIXME: guarantees the buffer will align, but the + !!! FIXME: converters will iterate over the data backwards if + !!! FIXME: the output grows, and this means we won't align if buflen + !!! FIXME: isn't a multiple of 16. In these cases, we should chop off + !!! FIXME: a few samples at the end and convert them separately. */ + +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: wants to put %d preconverted bytes\n", buflen); +#endif + + if (!stream) { + return SDL_InvalidParamError("stream"); + } + if (!buf) { + return SDL_InvalidParamError("buf"); + } + if (len == 0) { + return 0; /* nothing to do. */ + } + if ((len % stream->src_sample_frame_size) != 0) { + return SDL_SetError("Can't add partial sample frames"); + } + + if (!stream->cvt_before_resampling.needed && + (stream->dst_rate == stream->src_rate) && + !stream->cvt_after_resampling.needed) { +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: no conversion needed at all, queueing %d bytes.\n", len); +#endif + return SDL_WriteToDataQueue(stream->queue, buf, len); + } + + while (len > 0) { + int amount; + + /* If we don't have a staging buffer or we're given enough data that + we don't need to store it for later, skip the staging process. + */ + if (!stream->staging_buffer_filled && len >= stream->staging_buffer_size) { + return SDL_AudioStreamPutInternal(stream, buf, len, NULL); + } + + /* If there's not enough data to fill the staging buffer, just save it */ + if ((stream->staging_buffer_filled + len) < stream->staging_buffer_size) { + SDL_memcpy(stream->staging_buffer + stream->staging_buffer_filled, buf, len); + stream->staging_buffer_filled += len; + return 0; + } + + /* Fill the staging buffer, process it, and continue */ + amount = (stream->staging_buffer_size - stream->staging_buffer_filled); + SDL_assert(amount > 0); + SDL_memcpy(stream->staging_buffer + stream->staging_buffer_filled, buf, amount); + stream->staging_buffer_filled = 0; + if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, NULL) < 0) { + return -1; + } + buf = (void *)((Uint8 *)buf + amount); + len -= amount; + } + return 0; +} + +int SDL_AudioStreamFlush(SDL_AudioStream *stream) +{ + if (!stream) { + return SDL_InvalidParamError("stream"); + } + +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: flushing! staging_buffer_filled=%d bytes\n", stream->staging_buffer_filled); +#endif + + /* shouldn't use a staging buffer if we're not resampling. */ + SDL_assert((stream->dst_rate != stream->src_rate) || (stream->staging_buffer_filled == 0)); + + if (stream->staging_buffer_filled > 0) { + /* push the staging buffer + silence. We need to flush out not just + the staging buffer, but the piece that the stream was saving off + for right-side resampler padding. */ + const SDL_bool first_run = stream->first_run; + const int filled = stream->staging_buffer_filled; + int actual_input_frames = filled / stream->src_sample_frame_size; + if (!first_run) { + actual_input_frames += stream->resampler_padding_samples / stream->pre_resample_channels; + } + + if (actual_input_frames > 0) { /* don't bother if nothing to flush. */ + /* This is how many bytes we're expecting without silence appended. */ + int flush_remaining = ((int)SDL_ceil(actual_input_frames * stream->rate_incr)) * stream->dst_sample_frame_size; + +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: flushing with padding to get max %d bytes!\n", flush_remaining); +#endif + + SDL_memset(stream->staging_buffer + filled, '\0', stream->staging_buffer_size - filled); + if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, &flush_remaining) < 0) { + return -1; + } + + /* we have flushed out (or initially filled) the pending right-side + resampler padding, but we need to push more silence to guarantee + the staging buffer is fully flushed out, too. */ + SDL_memset(stream->staging_buffer, '\0', filled); + if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, &flush_remaining) < 0) { + return -1; + } + } + } + + stream->staging_buffer_filled = 0; + stream->first_run = SDL_TRUE; + + return 0; +} + +/* get converted/resampled data from the stream */ +int SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len) +{ +#if DEBUG_AUDIOSTREAM + SDL_Log("AUDIOSTREAM: want to get %d converted bytes\n", len); +#endif + + if (!stream) { + return SDL_InvalidParamError("stream"); + } + if (!buf) { + return SDL_InvalidParamError("buf"); + } + if (len <= 0) { + return 0; /* nothing to do. */ + } + if ((len % stream->dst_sample_frame_size) != 0) { + return SDL_SetError("Can't request partial sample frames"); + } + + return (int)SDL_ReadFromDataQueue(stream->queue, buf, len); +} + +/* number of converted/resampled bytes available */ +int SDL_AudioStreamAvailable(SDL_AudioStream *stream) +{ + return stream ? (int)SDL_CountDataQueue(stream->queue) : 0; +} + +void SDL_AudioStreamClear(SDL_AudioStream *stream) +{ + if (!stream) { + SDL_InvalidParamError("stream"); + } else { + SDL_ClearDataQueue(stream->queue, (size_t)stream->packetlen * 2); + if (stream->reset_resampler_func) { + stream->reset_resampler_func(stream); + } + stream->first_run = SDL_TRUE; + stream->staging_buffer_filled = 0; + } +} + +/* dispose of a stream */ +void SDL_FreeAudioStream(SDL_AudioStream *stream) +{ + if (stream) { + if (stream->cleanup_resampler_func) { + stream->cleanup_resampler_func(stream); + } + SDL_FreeDataQueue(stream->queue); + SDL_free(stream->staging_buffer); + SDL_free(stream->work_buffer_base); + SDL_free(stream->resampler_padding); + SDL_free(stream); + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_audiodev.c b/third_party/SDL2/src/audio/SDL_audiodev.c new file mode 100644 index 00000000000..3ecaa05ee01 --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_audiodev.c @@ -0,0 +1,128 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +/* Get the name of the audio device we use for output */ + +#if defined(SDL_AUDIO_DRIVER_NETBSD) || defined(SDL_AUDIO_DRIVER_OSS) || defined(SDL_AUDIO_DRIVER_SUNAUDIO) + +#include +#include +#include +#include /* For close() */ + +#include "SDL_stdinc.h" +#include "SDL_audiodev_c.h" + +#ifndef _PATH_DEV_DSP +#if defined(__NETBSD__) || defined(__OPENBSD__) +#define _PATH_DEV_DSP "/dev/audio" +#else +#define _PATH_DEV_DSP "/dev/dsp" +#endif +#endif +#ifndef _PATH_DEV_DSP24 +#define _PATH_DEV_DSP24 "/dev/sound/dsp" +#endif +#ifndef _PATH_DEV_AUDIO +#define _PATH_DEV_AUDIO "/dev/audio" +#endif + +static void test_device(const int iscapture, const char *fname, int flags, int (*test)(int fd)) +{ + struct stat sb; + if ((stat(fname, &sb) == 0) && (S_ISCHR(sb.st_mode))) { + const int audio_fd = open(fname, flags | O_CLOEXEC, 0); + if (audio_fd >= 0) { + const int okay = test(audio_fd); + close(audio_fd); + if (okay) { + static size_t dummyhandle = 0; + dummyhandle++; + SDL_assert(dummyhandle != 0); + + /* Note that spec is NULL; while we are opening the device + * endpoint here, the endpoint does not provide any mix format + * information, making this information inaccessible at + * enumeration time + */ + SDL_AddAudioDevice(iscapture, fname, NULL, (void *)(uintptr_t)dummyhandle); + } + } + } +} + +static int test_stub(int fd) +{ + return 1; +} + +static void SDL_EnumUnixAudioDevices_Internal(const int iscapture, const int classic, int (*test)(int)) +{ + const int flags = iscapture ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT; + const char *audiodev; + char audiopath[1024]; + + if (!test) { + test = test_stub; + } + + /* Figure out what our audio device is */ + audiodev = SDL_getenv("SDL_PATH_DSP"); + if (!audiodev) { + audiodev = SDL_getenv("AUDIODEV"); + } + if (!audiodev) { + if (classic) { + audiodev = _PATH_DEV_AUDIO; + } else { + struct stat sb; + + /* Added support for /dev/sound/\* in Linux 2.4 */ + if (((stat("/dev/sound", &sb) == 0) && S_ISDIR(sb.st_mode)) && ((stat(_PATH_DEV_DSP24, &sb) == 0) && S_ISCHR(sb.st_mode))) { + audiodev = _PATH_DEV_DSP24; + } else { + audiodev = _PATH_DEV_DSP; + } + } + } + test_device(iscapture, audiodev, flags, test); + + if (SDL_strlen(audiodev) < (sizeof(audiopath) - 3)) { + int instance = 0; + while (instance <= 64) { + (void)SDL_snprintf(audiopath, SDL_arraysize(audiopath), + "%s%d", audiodev, instance); + instance++; + test_device(iscapture, audiopath, flags, test); + } + } +} + +void SDL_EnumUnixAudioDevices(const int classic, int (*test)(int)) +{ + SDL_EnumUnixAudioDevices_Internal(SDL_TRUE, classic, test); + SDL_EnumUnixAudioDevices_Internal(SDL_FALSE, classic, test); +} + +#endif /* Audio driver selection */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_audiodev_c.h b/third_party/SDL2/src/audio/SDL_audiodev_c.h new file mode 100644 index 00000000000..7aefc0d203e --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_audiodev_c.h @@ -0,0 +1,44 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_audiodev_c_h_ +#define SDL_audiodev_c_h_ + +#include "SDL.h" +#include "../SDL_internal.h" +#include "SDL_sysaudio.h" + +/* Open the audio device for playback, and don't block if busy */ +/* #define USE_BLOCKING_WRITES */ + +#ifdef USE_BLOCKING_WRITES +#define OPEN_FLAGS_OUTPUT O_WRONLY +#define OPEN_FLAGS_INPUT O_RDONLY +#else +#define OPEN_FLAGS_OUTPUT (O_WRONLY | O_NONBLOCK) +#define OPEN_FLAGS_INPUT (O_RDONLY | O_NONBLOCK) +#endif + +extern void SDL_EnumUnixAudioDevices(const int classic, int (*test)(int)); + +#endif /* SDL_audiodev_c_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_audiotypecvt.c b/third_party/SDL2/src/audio/SDL_audiotypecvt.c new file mode 100644 index 00000000000..c801d26d71d --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_audiotypecvt.c @@ -0,0 +1,1466 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +#include "SDL_audio.h" +#include "SDL_audio_c.h" +#include "SDL_cpuinfo.h" + +#ifdef __ARM_NEON +//#define HAVE_NEON_INTRINSICS 1 +#endif + +#ifdef __SSE2__ +//#define HAVE_SSE2_INTRINSICS +#endif + +#if defined(__x86_64__) && defined(HAVE_SSE2_INTRINSICS) +#define NEED_SCALAR_CONVERTER_FALLBACKS 0 /* x86_64 guarantees SSE2. */ +#elif defined(__MACOSX__) && defined(HAVE_SSE2_INTRINSICS) +#define NEED_SCALAR_CONVERTER_FALLBACKS 0 /* Mac OS X/Intel guarantees SSE2. */ +#elif defined(__ARM_ARCH) && (__ARM_ARCH >= 8) && defined(HAVE_NEON_INTRINSICS) +#define NEED_SCALAR_CONVERTER_FALLBACKS 0 /* ARMv8+ promise NEON. */ +#elif defined(__APPLE__) && defined(__ARM_ARCH) && (__ARM_ARCH >= 7) && defined(HAVE_NEON_INTRINSICS) +#define NEED_SCALAR_CONVERTER_FALLBACKS 0 /* All Apple ARMv7 chips promise NEON support. */ +#endif + +/* Set to zero if platform is guaranteed to use a SIMD codepath here. */ +#ifndef NEED_SCALAR_CONVERTER_FALLBACKS +#define NEED_SCALAR_CONVERTER_FALLBACKS 1 +#endif + +/* Function pointers set to a CPU-specific implementation. */ +SDL_AudioFilter SDL_Convert_S8_to_F32 = NULL; +SDL_AudioFilter SDL_Convert_U8_to_F32 = NULL; +SDL_AudioFilter SDL_Convert_S16_to_F32 = NULL; +SDL_AudioFilter SDL_Convert_U16_to_F32 = NULL; +SDL_AudioFilter SDL_Convert_S32_to_F32 = NULL; +SDL_AudioFilter SDL_Convert_F32_to_S8 = NULL; +SDL_AudioFilter SDL_Convert_F32_to_U8 = NULL; +SDL_AudioFilter SDL_Convert_F32_to_S16 = NULL; +SDL_AudioFilter SDL_Convert_F32_to_U16 = NULL; +SDL_AudioFilter SDL_Convert_F32_to_S32 = NULL; + +#define DIVBY128 0.0078125f +#define DIVBY32768 0.000030517578125f +#define DIVBY8388607 0.00000011920930376163766f +#define DIVBY2147483648 0.0000000004656612873077392578125f /* 0x1p-31f */ + +#if NEED_SCALAR_CONVERTER_FALLBACKS + +/* This code requires that floats are in the IEEE-754 binary32 format */ +SDL_COMPILE_TIME_ASSERT(float_bits, sizeof(float) == sizeof(Uint32)); + +union float_bits { + Uint32 u32; + float f32; +}; + +/* Create a bit-mask based on the sign-bit. Should optimize to a single arithmetic-shift-right */ +#define SIGNMASK(x) (Uint32)(0u - ((Uint32)(x) >> 31)) + +static void SDLCALL SDL_Convert_S8_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const int num_samples = cvt->len_cvt; + const Sint8 *src = (const Sint8 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_S8", "AUDIO_F32"); + + for (i = num_samples - 1; i >= 0; --i) { + /* 1) Construct a float in the range [65536.0, 65538.0) + * 2) Shift the float range to [-1.0, 1.0) */ + union float_bits x; + x.u32 = (Uint8)src[i] ^ 0x47800080u; + dst[i] = x.f32 - 65537.0f; + } + + cvt->len_cvt *= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_U8_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const int num_samples = cvt->len_cvt; + const Uint8 *src = (const Uint8 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_U8", "AUDIO_F32"); + + for (i = num_samples - 1; i >= 0; --i) { + /* 1) Construct a float in the range [65536.0, 65538.0) + * 2) Shift the float range to [-1.0, 1.0) */ + union float_bits x; + x.u32 = src[i] ^ 0x47800000u; + dst[i] = x.f32 - 65537.0f; + } + + cvt->len_cvt *= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_S16_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const int num_samples = cvt->len_cvt / sizeof(Sint16); + const Sint16 *src = (const Sint16 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_S16", "AUDIO_F32"); + + for (i = num_samples - 1; i >= 0; --i) { + /* 1) Construct a float in the range [256.0, 258.0) + * 2) Shift the float range to [-1.0, 1.0) */ + union float_bits x; + x.u32 = (Uint16)src[i] ^ 0x43808000u; + dst[i] = x.f32 - 257.0f; + } + + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_U16_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Uint16 *src = ((const Uint16 *)(cvt->buf + cvt->len_cvt)) - 1; + float *dst = ((float *)(cvt->buf + cvt->len_cvt * 2)) - 1; + int i; + + LOG_DEBUG_CONVERT("AUDIO_U16", "AUDIO_F32"); + + for (i = cvt->len_cvt / sizeof(Uint16); i; --i, --src, --dst) { + *dst = (((float)*src) * DIVBY32768) - 1.0f; + } + + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_S32_to_F32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Sint32 *src = (const Sint32 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_S32", "AUDIO_F32"); + + for (i = cvt->len_cvt / sizeof(Sint32); i; --i, ++src, ++dst) { + *dst = ((float)(*src >> 8)) * DIVBY8388607; + } + + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_S8_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const int num_samples = cvt->len_cvt / sizeof (float); + const float *src = (const float *)cvt->buf; + Sint8 *dst = (Sint8 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S8"); + + for (i = 0; i < num_samples; ++i) { + /* 1) Shift the float range from [-1.0, 1.0] to [98303.0, 98305.0] + * 2) Shift the integer range from [0x47BFFF80, 0x47C00080] to [-128, 128] + * 3) Clamp the value to [-128, 127] */ + union float_bits x; + Uint32 y, z; + x.f32 = src[i] + 98304.0f; + + y = x.u32 - 0x47C00000u; + z = 0x7Fu - (y ^ SIGNMASK(y)); + y = y ^ (z & SIGNMASK(z)); + + dst[i] = (Sint8)(y & 0xFF); + } + + cvt->len_cvt /= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S8); + } +} + +static void SDLCALL SDL_Convert_F32_to_U8_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const int num_samples = cvt->len_cvt / sizeof (float); + const float *src = (const float *)cvt->buf; + Uint8 *dst = (Uint8 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U8"); + + for (i = 0; i < num_samples; ++i) { + /* 1) Shift the float range from [-1.0, 1.0] to [98303.0, 98305.0] + * 2) Shift the integer range from [0x47BFFF80, 0x47C00080] to [-128, 128] + * 3) Clamp the value to [-128, 127] + * 4) Shift the integer range from [-128, 127] to [0, 255] */ + union float_bits x; + Uint32 y, z; + x.f32 = src[i] + 98304.0f; + + y = x.u32 - 0x47C00000u; + z = 0x7Fu - (y ^ SIGNMASK(y)); + y = (y ^ 0x80u) ^ (z & SIGNMASK(z)); + + dst[i] = (Uint8)(y & 0xFF); + } + + cvt->len_cvt /= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_U8); + } +} + +static void SDLCALL SDL_Convert_F32_to_S16_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const int num_samples = cvt->len_cvt / sizeof (float); + const float *src = (const float *)cvt->buf; + Sint16 *dst = (Sint16 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S16"); + + for (i = 0; i < num_samples; ++i) { + /* 1) Shift the float range from [-1.0, 1.0] to [383.0, 385.0] + * 2) Shift the integer range from [0x43BF8000, 0x43C08000] to [-32768, 32768] + * 3) Clamp values outside the [-32768, 32767] range */ + union float_bits x; + Uint32 y, z; + x.f32 = src[i] + 384.0f; + + y = x.u32 - 0x43C00000u; + z = 0x7FFFu - (y ^ SIGNMASK(y)); + y = y ^ (z & SIGNMASK(z)); + + dst[i] = (Sint16)(y & 0xFFFF); + } + + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S16SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_U16_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Uint16 *dst = (Uint16 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U16"); + + for (i = cvt->len_cvt / sizeof(float); i; --i, ++src, ++dst) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 65535; + } else if (sample <= -1.0f) { + *dst = 0; + } else { + *dst = (Uint16)((sample + 1.0f) * 32767.0f); + } + } + + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_U16SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_S32_Scalar(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const int num_samples = cvt->len_cvt / sizeof (float); + const float *src = (const float *)cvt->buf; + Sint32 *dst = (Sint32 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S32"); + + for (i = 0; i < num_samples; ++i) { + /* 1) Shift the float range from [-1.0, 1.0] to [-2147483648.0, 2147483648.0] + * 2) Set values outside the [-2147483648.0, 2147483647.0] range to -2147483648.0 + * 3) Convert the float to an integer, and fixup values outside the valid range */ + union float_bits x; + Uint32 y, z; + x.f32 = src[i]; + + y = x.u32 + 0x0F800000u; + z = y - 0xCF000000u; + z &= SIGNMASK(y ^ z); + x.u32 = y - z; + + dst[i] = (Sint32)x.f32 ^ (Sint32)SIGNMASK(z); + } + + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S32SYS); + } +} +#endif + +#ifdef HAVE_SSE2_INTRINSICS +static void SDLCALL SDL_Convert_S8_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Sint8 *src = (const Sint8 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i = cvt->len_cvt; + + /* 1) Flip the sign bit to convert from S8 to U8 format + * 2) Construct a float in the range [65536.0, 65538.0) + * 3) Shift the float range to [-1.0, 1.0) + * dst[i] = i2f((src[i] ^ 0x80) | 0x47800000) - 65537.0 */ + const __m128i zero = _mm_setzero_si128(); + const __m128i flipper = _mm_set1_epi8(-0x80); + const __m128i caster = _mm_set1_epi16(0x4780 /* 0x47800000 = f2i(65536.0) */); + const __m128 offset = _mm_set1_ps(-65537.0); + + LOG_DEBUG_CONVERT("AUDIO_S8", "AUDIO_F32 (using SSE2)"); + + while (i >= 16) { + i -= 16; + + { + const __m128i bytes = _mm_xor_si128(_mm_loadu_si128((const __m128i *)&src[i]), flipper); + + const __m128i shorts1 = _mm_unpacklo_epi8(bytes, zero); + const __m128i shorts2 = _mm_unpackhi_epi8(bytes, zero); + + const __m128 floats1 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts1, caster)), offset); + const __m128 floats2 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts1, caster)), offset); + const __m128 floats3 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts2, caster)), offset); + const __m128 floats4 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts2, caster)), offset); + + _mm_storeu_ps(&dst[i], floats1); + _mm_storeu_ps(&dst[i + 4], floats2); + _mm_storeu_ps(&dst[i + 8], floats3); + _mm_storeu_ps(&dst[i + 12], floats4); + } + } + + while (i) { + --i; + _mm_store_ss(&dst[i], _mm_add_ss(_mm_castsi128_ps(_mm_cvtsi32_si128((Uint8)src[i] ^ 0x47800080u)), offset)); + } + + cvt->len_cvt *= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_U8_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Sint8 *src = (const Sint8 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i = cvt->len_cvt; + + /* 1) Construct a float in the range [65536.0, 65538.0) + * 2) Shift the float range to [-1.0, 1.0) + * dst[i] = i2f(src[i] | 0x47800000) - 65537.0 */ + const __m128i zero = _mm_setzero_si128(); + const __m128i caster = _mm_set1_epi16(0x4780 /* 0x47800000 = f2i(65536.0) */); + const __m128 offset = _mm_set1_ps(-65537.0); + + LOG_DEBUG_CONVERT("AUDIO_U8", "AUDIO_F32 (using SSE2)"); + + while (i >= 16) { + i -= 16; + + { + const __m128i bytes = _mm_loadu_si128((const __m128i *)&src[i]); + + const __m128i shorts1 = _mm_unpacklo_epi8(bytes, zero); + const __m128i shorts2 = _mm_unpackhi_epi8(bytes, zero); + + const __m128 floats1 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts1, caster)), offset); + const __m128 floats2 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts1, caster)), offset); + const __m128 floats3 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts2, caster)), offset); + const __m128 floats4 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts2, caster)), offset); + + _mm_storeu_ps(&dst[i], floats1); + _mm_storeu_ps(&dst[i + 4], floats2); + _mm_storeu_ps(&dst[i + 8], floats3); + _mm_storeu_ps(&dst[i + 12], floats4); + } + } + + while (i) { + --i; + _mm_store_ss(&dst[i], _mm_add_ss(_mm_castsi128_ps(_mm_cvtsi32_si128((Uint8)src[i] ^ 0x47800000u)), offset)); + } + + cvt->len_cvt *= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_S16_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Sint16 *src = (const Sint16 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i = cvt->len_cvt / 2; + + /* 1) Flip the sign bit to convert from S16 to U16 format + * 2) Construct a float in the range [256.0, 258.0) + * 3) Shift the float range to [-1.0, 1.0) + * dst[i] = i2f((src[i] ^ 0x8000) | 0x43800000) - 257.0 */ + const __m128i flipper = _mm_set1_epi16(-0x8000); + const __m128i caster = _mm_set1_epi16(0x4380 /* 0x43800000 = f2i(256.0) */); + const __m128 offset = _mm_set1_ps(-257.0f); + + LOG_DEBUG_CONVERT("AUDIO_S16", "AUDIO_F32 (using SSE2)"); + + while (i >= 16) { + i -= 16; + + { + const __m128i shorts1 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)&src[i]), flipper); + const __m128i shorts2 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)&src[i + 8]), flipper); + + const __m128 floats1 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts1, caster)), offset); + const __m128 floats2 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts1, caster)), offset); + const __m128 floats3 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts2, caster)), offset); + const __m128 floats4 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts2, caster)), offset); + + _mm_storeu_ps(&dst[i], floats1); + _mm_storeu_ps(&dst[i + 4], floats2); + _mm_storeu_ps(&dst[i + 8], floats3); + _mm_storeu_ps(&dst[i + 12], floats4); + } + } + + while (i) { + --i; + _mm_store_ss(&dst[i], _mm_add_ss(_mm_castsi128_ps(_mm_cvtsi32_si128((Uint16)src[i] ^ 0x43808000u)), offset)); + } + + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_U16_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Uint16 *src = ((const Uint16 *)(cvt->buf + cvt->len_cvt)) - 1; + float *dst = ((float *)(cvt->buf + cvt->len_cvt * 2)) - 1; + int i; + + LOG_DEBUG_CONVERT("AUDIO_U16", "AUDIO_F32 (using SSE2)"); + + /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */ + for (i = cvt->len_cvt / sizeof(Sint16); i && (((size_t)(dst - 7)) & 15); --i, --src, --dst) { + *dst = (((float)*src) * DIVBY32768) - 1.0f; + } + + src -= 7; + dst -= 7; /* adjust to read SSE blocks from the start. */ + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do SSE blocks as long as we have 16 bytes available. */ + const __m128 divby32768 = _mm_set1_ps(DIVBY32768); + const __m128 minus1 = _mm_set1_ps(-1.0f); + while (i >= 8) { /* 8 * 16-bit */ + const __m128i ints = _mm_load_si128((__m128i const *)src); /* get 8 sint16 into an XMM register. */ + /* treat as int32, shift left to clear every other sint16, then back right with zero-extend. Now sint32. */ + const __m128i a = _mm_srli_epi32(_mm_slli_epi32(ints, 16), 16); + /* right-shift-sign-extend gets us sint32 with the other set of values. */ + const __m128i b = _mm_srli_epi32(ints, 16); + /* Interleave these back into the right order, convert to float, multiply, store. */ + _mm_store_ps(dst, _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi32(a, b)), divby32768), minus1)); + _mm_store_ps(dst + 4, _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi32(a, b)), divby32768), minus1)); + i -= 8; + src -= 8; + dst -= 8; + } + } + + src += 7; + dst += 7; /* adjust for any scalar finishing. */ + + /* Finish off any leftovers with scalar operations. */ + while (i) { + *dst = (((float)*src) * DIVBY32768) - 1.0f; + i--; + src--; + dst--; + } + + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_S32_to_F32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Sint32 *src = (const Sint32 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i = cvt->len_cvt / 4; + + /* dst[i] = f32(src[i]) / f32(0x80000000) */ + const __m128 scaler = _mm_set1_ps(DIVBY2147483648); + + LOG_DEBUG_CONVERT("AUDIO_S32", "AUDIO_F32 (using SSE2)"); + + while (i >= 16) { + i -= 16; + + { + const __m128i ints1 = _mm_loadu_si128((const __m128i *)&src[i]); + const __m128i ints2 = _mm_loadu_si128((const __m128i *)&src[i + 4]); + const __m128i ints3 = _mm_loadu_si128((const __m128i *)&src[i + 8]); + const __m128i ints4 = _mm_loadu_si128((const __m128i *)&src[i + 12]); + + const __m128 floats1 = _mm_mul_ps(_mm_cvtepi32_ps(ints1), scaler); + const __m128 floats2 = _mm_mul_ps(_mm_cvtepi32_ps(ints2), scaler); + const __m128 floats3 = _mm_mul_ps(_mm_cvtepi32_ps(ints3), scaler); + const __m128 floats4 = _mm_mul_ps(_mm_cvtepi32_ps(ints4), scaler); + + _mm_storeu_ps(&dst[i], floats1); + _mm_storeu_ps(&dst[i + 4], floats2); + _mm_storeu_ps(&dst[i + 8], floats3); + _mm_storeu_ps(&dst[i + 12], floats4); + } + } + + while (i) { + --i; + _mm_store_ss(&dst[i], _mm_mul_ss(_mm_cvt_si2ss(_mm_setzero_ps(), src[i]), scaler)); + } + + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_S8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Sint8 *dst = (Sint8 *)cvt->buf; + int i = cvt->len_cvt / 4; + + /* 1) Shift the float range from [-1.0, 1.0] to [98303.0, 98305.0] + * 2) Extract the lowest 16 bits and clamp to [-128, 127] + * Overflow is correctly handled for inputs between roughly [-255.0, 255.0] + * dst[i] = clamp(i16(f2i(src[i] + 98304.0) & 0xFFFF), -128, 127) */ + const __m128 offset = _mm_set1_ps(98304.0f); + const __m128i mask = _mm_set1_epi16(0xFF); + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S8 (using SSE2)"); + + while (i >= 16) { + const __m128 floats1 = _mm_loadu_ps(&src[0]); + const __m128 floats2 = _mm_loadu_ps(&src[4]); + const __m128 floats3 = _mm_loadu_ps(&src[8]); + const __m128 floats4 = _mm_loadu_ps(&src[12]); + + const __m128i ints1 = _mm_castps_si128(_mm_add_ps(floats1, offset)); + const __m128i ints2 = _mm_castps_si128(_mm_add_ps(floats2, offset)); + const __m128i ints3 = _mm_castps_si128(_mm_add_ps(floats3, offset)); + const __m128i ints4 = _mm_castps_si128(_mm_add_ps(floats4, offset)); + + const __m128i shorts1 = _mm_and_si128(_mm_packs_epi16(ints1, ints2), mask); + const __m128i shorts2 = _mm_and_si128(_mm_packs_epi16(ints3, ints4), mask); + + const __m128i bytes = _mm_packus_epi16(shorts1, shorts2); + + _mm_storeu_si128((__m128i*)dst, bytes); + + i -= 16; + src += 16; + dst += 16; + } + + while (i) { + const __m128i ints = _mm_castps_si128(_mm_add_ss(_mm_load_ss(src), offset)); + *dst = (Sint8)(_mm_cvtsi128_si32(_mm_packs_epi16(ints, ints)) & 0xFF); + + --i; + ++src; + ++dst; + } + + cvt->len_cvt /= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S8); + } +} + +static void SDLCALL SDL_Convert_F32_to_U8_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Uint8 *dst = cvt->buf; + int i = cvt->len_cvt / 4; + + /* 1) Shift the float range from [-1.0, 1.0] to [98304.0, 98306.0] + * 2) Extract the lowest 16 bits and clamp to [0, 255] + * Overflow is correctly handled for inputs between roughly [-254.0, 254.0] + * dst[i] = clamp(i16(f2i(src[i] + 98305.0) & 0xFFFF), 0, 255) */ + const __m128 offset = _mm_set1_ps(98305.0f); + const __m128i mask = _mm_set1_epi16(0xFF); + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U8 (using SSE2)"); + + while (i >= 16) { + const __m128 floats1 = _mm_loadu_ps(&src[0]); + const __m128 floats2 = _mm_loadu_ps(&src[4]); + const __m128 floats3 = _mm_loadu_ps(&src[8]); + const __m128 floats4 = _mm_loadu_ps(&src[12]); + + const __m128i ints1 = _mm_castps_si128(_mm_add_ps(floats1, offset)); + const __m128i ints2 = _mm_castps_si128(_mm_add_ps(floats2, offset)); + const __m128i ints3 = _mm_castps_si128(_mm_add_ps(floats3, offset)); + const __m128i ints4 = _mm_castps_si128(_mm_add_ps(floats4, offset)); + + const __m128i shorts1 = _mm_and_si128(_mm_packus_epi16(ints1, ints2), mask); + const __m128i shorts2 = _mm_and_si128(_mm_packus_epi16(ints3, ints4), mask); + + const __m128i bytes = _mm_packus_epi16(shorts1, shorts2); + + _mm_storeu_si128((__m128i*)dst, bytes); + + i -= 16; + src += 16; + dst += 16; + } + + while (i) { + const __m128i ints = _mm_castps_si128(_mm_add_ss(_mm_load_ss(src), offset)); + *dst = (Uint8)(_mm_cvtsi128_si32(_mm_packus_epi16(ints, ints)) & 0xFF); + + --i; + ++src; + ++dst; + } + + cvt->len_cvt /= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_U8); + } +} + +static void SDLCALL SDL_Convert_F32_to_S16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Sint16 *dst = (Sint16 *)cvt->buf; + int i = cvt->len_cvt / 4; + + /* 1) Shift the float range from [-1.0, 1.0] to [256.0, 258.0] + * 2) Shift the int range from [0x43800000, 0x43810000] to [-32768,32768] + * 3) Clamp to range [-32768,32767] + * Overflow is correctly handled for inputs between roughly [-257.0, +inf) + * dst[i] = clamp(f2i(src[i] + 257.0) - 0x43808000, -32768, 32767) */ + const __m128 offset = _mm_set1_ps(257.0f); + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S16 (using SSE2)"); + + while (i >= 16) { + const __m128 floats1 = _mm_loadu_ps(&src[0]); + const __m128 floats2 = _mm_loadu_ps(&src[4]); + const __m128 floats3 = _mm_loadu_ps(&src[8]); + const __m128 floats4 = _mm_loadu_ps(&src[12]); + + const __m128i ints1 = _mm_sub_epi32(_mm_castps_si128(_mm_add_ps(floats1, offset)), _mm_castps_si128(offset)); + const __m128i ints2 = _mm_sub_epi32(_mm_castps_si128(_mm_add_ps(floats2, offset)), _mm_castps_si128(offset)); + const __m128i ints3 = _mm_sub_epi32(_mm_castps_si128(_mm_add_ps(floats3, offset)), _mm_castps_si128(offset)); + const __m128i ints4 = _mm_sub_epi32(_mm_castps_si128(_mm_add_ps(floats4, offset)), _mm_castps_si128(offset)); + + const __m128i shorts1 = _mm_packs_epi32(ints1, ints2); + const __m128i shorts2 = _mm_packs_epi32(ints3, ints4); + + _mm_storeu_si128((__m128i*)&dst[0], shorts1); + _mm_storeu_si128((__m128i*)&dst[8], shorts2); + + i -= 16; + src += 16; + dst += 16; + } + + while (i) { + const __m128i ints = _mm_sub_epi32(_mm_castps_si128(_mm_add_ss(_mm_load_ss(src), offset)), _mm_castps_si128(offset)); + *dst = (Sint16)(_mm_cvtsi128_si32(_mm_packs_epi32(ints, ints)) & 0xFFFF); + + --i; + ++src; + ++dst; + } + + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S16SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_U16_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Uint16 *dst = (Uint16 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U16 (using SSE2)"); + + /* Get dst aligned to 16 bytes */ + for (i = cvt->len_cvt / sizeof(float); i && (((size_t)dst) & 15); --i, ++src, ++dst) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 65535; + } else if (sample <= -1.0f) { + *dst = 0; + } else { + *dst = (Uint16)((sample + 1.0f) * 32767.0f); + } + } + + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do SSE blocks as long as we have 16 bytes available. */ + /* This calculates differently than the scalar path because SSE2 can't + pack int32 data down to unsigned int16. _mm_packs_epi32 does signed + saturation, so that would corrupt our data. _mm_packus_epi32 exists, + but not before SSE 4.1. So we convert from float to sint16, packing + that down with legit signed saturation, and then xor the top bit + against 1. This results in the correct unsigned 16-bit value, even + though it looks like dark magic. */ + const __m128 mulby32767 = _mm_set1_ps(32767.0f); + const __m128i topbit = _mm_set1_epi16(-32768); + const __m128 one = _mm_set1_ps(1.0f); + const __m128 negone = _mm_set1_ps(-1.0f); + __m128i *mmdst = (__m128i *)dst; + while (i >= 8) { /* 8 * float32 */ + const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */ + const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src + 4)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */ + _mm_store_si128(mmdst, _mm_xor_si128(_mm_packs_epi32(ints1, ints2), topbit)); /* pack to sint16, xor top bit, store out. */ + i -= 8; + src += 8; + mmdst++; + } + dst = (Uint16 *)mmdst; + } + + /* Finish off any leftovers with scalar operations. */ + while (i) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 65535; + } else if (sample <= -1.0f) { + *dst = 0; + } else { + *dst = (Uint16)((sample + 1.0f) * 32767.0f); + } + i--; + src++; + dst++; + } + + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_U16SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_S32_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Sint32 *dst = (Sint32 *)cvt->buf; + int i = cvt->len_cvt / 4; + + /* 1) Scale the float range from [-1.0, 1.0] to [-2147483648.0, 2147483648.0] + * 2) Convert to integer (values too small/large become 0x80000000 = -2147483648) + * 3) Fixup values which were too large (0x80000000 ^ 0xFFFFFFFF = 2147483647) + * dst[i] = i32(src[i] * 2147483648.0) ^ ((src[i] >= 2147483648.0) ? 0xFFFFFFFF : 0x00000000) */ + const __m128 limit = _mm_set1_ps(2147483648.0f); + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S32 (using SSE2)"); + + while (i >= 16) { + const __m128 floats1 = _mm_loadu_ps(&src[0]); + const __m128 floats2 = _mm_loadu_ps(&src[4]); + const __m128 floats3 = _mm_loadu_ps(&src[8]); + const __m128 floats4 = _mm_loadu_ps(&src[12]); + + const __m128 values1 = _mm_mul_ps(floats1, limit); + const __m128 values2 = _mm_mul_ps(floats2, limit); + const __m128 values3 = _mm_mul_ps(floats3, limit); + const __m128 values4 = _mm_mul_ps(floats4, limit); + + const __m128i ints1 = _mm_xor_si128(_mm_cvttps_epi32(values1), _mm_castps_si128(_mm_cmpge_ps(values1, limit))); + const __m128i ints2 = _mm_xor_si128(_mm_cvttps_epi32(values2), _mm_castps_si128(_mm_cmpge_ps(values2, limit))); + const __m128i ints3 = _mm_xor_si128(_mm_cvttps_epi32(values3), _mm_castps_si128(_mm_cmpge_ps(values3, limit))); + const __m128i ints4 = _mm_xor_si128(_mm_cvttps_epi32(values4), _mm_castps_si128(_mm_cmpge_ps(values4, limit))); + + _mm_storeu_si128((__m128i*)&dst[0], ints1); + _mm_storeu_si128((__m128i*)&dst[4], ints2); + _mm_storeu_si128((__m128i*)&dst[8], ints3); + _mm_storeu_si128((__m128i*)&dst[12], ints4); + + i -= 16; + src += 16; + dst += 16; + } + + while (i) { + const __m128 floats = _mm_load_ss(src); + const __m128 values = _mm_mul_ss(floats, limit); + const __m128i ints = _mm_xor_si128(_mm_cvttps_epi32(values), _mm_castps_si128(_mm_cmpge_ss(values, limit))); + *dst = (Sint32)_mm_cvtsi128_si32(ints); + + --i; + ++src; + ++dst; + } + + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S32SYS); + } +} +#endif + +#ifdef HAVE_NEON_INTRINSICS +static void SDLCALL SDL_Convert_S8_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Sint8 *src = ((const Sint8 *)(cvt->buf + cvt->len_cvt)) - 1; + float *dst = ((float *)(cvt->buf + cvt->len_cvt * 4)) - 1; + int i; + + LOG_DEBUG_CONVERT("AUDIO_S8", "AUDIO_F32 (using NEON)"); + + /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */ + for (i = cvt->len_cvt; i && (((size_t)(dst - 15)) & 15); --i, --src, --dst) { + *dst = ((float)*src) * DIVBY128; + } + + src -= 15; + dst -= 15; /* adjust to read NEON blocks from the start. */ + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const int8_t *mmsrc = (const int8_t *)src; + const float32x4_t divby128 = vdupq_n_f32(DIVBY128); + while (i >= 16) { /* 16 * 8-bit */ + const int8x16_t bytes = vld1q_s8(mmsrc); /* get 16 sint8 into a NEON register. */ + const int16x8_t int16hi = vmovl_s8(vget_high_s8(bytes)); /* convert top 8 bytes to 8 int16 */ + const int16x8_t int16lo = vmovl_s8(vget_low_s8(bytes)); /* convert bottom 8 bytes to 8 int16 */ + /* split int16 to two int32, then convert to float, then multiply to normalize, store. */ + vst1q_f32(dst, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(int16lo))), divby128)); + vst1q_f32(dst + 4, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(int16lo))), divby128)); + vst1q_f32(dst + 8, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(int16hi))), divby128)); + vst1q_f32(dst + 12, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(int16hi))), divby128)); + i -= 16; + mmsrc -= 16; + dst -= 16; + } + + src = (const Sint8 *)mmsrc; + } + + src += 15; + dst += 15; /* adjust for any scalar finishing. */ + + /* Finish off any leftovers with scalar operations. */ + while (i) { + *dst = ((float)*src) * DIVBY128; + i--; + src--; + dst--; + } + + cvt->len_cvt *= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_U8_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Uint8 *src = ((const Uint8 *)(cvt->buf + cvt->len_cvt)) - 1; + float *dst = ((float *)(cvt->buf + cvt->len_cvt * 4)) - 1; + int i; + + LOG_DEBUG_CONVERT("AUDIO_U8", "AUDIO_F32 (using NEON)"); + + /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */ + for (i = cvt->len_cvt; i && (((size_t)(dst - 15)) & 15); --i, --src, --dst) { + *dst = (((float)*src) * DIVBY128) - 1.0f; + } + + src -= 15; + dst -= 15; /* adjust to read NEON blocks from the start. */ + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const uint8_t *mmsrc = (const uint8_t *)src; + const float32x4_t divby128 = vdupq_n_f32(DIVBY128); + const float32x4_t negone = vdupq_n_f32(-1.0f); + while (i >= 16) { /* 16 * 8-bit */ + const uint8x16_t bytes = vld1q_u8(mmsrc); /* get 16 uint8 into a NEON register. */ + const uint16x8_t uint16hi = vmovl_u8(vget_high_u8(bytes)); /* convert top 8 bytes to 8 uint16 */ + const uint16x8_t uint16lo = vmovl_u8(vget_low_u8(bytes)); /* convert bottom 8 bytes to 8 uint16 */ + /* split uint16 to two uint32, then convert to float, then multiply to normalize, subtract to adjust for sign, store. */ + vst1q_f32(dst, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_low_u16(uint16lo))), divby128)); + vst1q_f32(dst + 4, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_high_u16(uint16lo))), divby128)); + vst1q_f32(dst + 8, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_low_u16(uint16hi))), divby128)); + vst1q_f32(dst + 12, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_high_u16(uint16hi))), divby128)); + i -= 16; + mmsrc -= 16; + dst -= 16; + } + + src = (const Uint8 *)mmsrc; + } + + src += 15; + dst += 15; /* adjust for any scalar finishing. */ + + /* Finish off any leftovers with scalar operations. */ + while (i) { + *dst = (((float)*src) * DIVBY128) - 1.0f; + i--; + src--; + dst--; + } + + cvt->len_cvt *= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_S16_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Sint16 *src = ((const Sint16 *)(cvt->buf + cvt->len_cvt)) - 1; + float *dst = ((float *)(cvt->buf + cvt->len_cvt * 2)) - 1; + int i; + + LOG_DEBUG_CONVERT("AUDIO_S16", "AUDIO_F32 (using NEON)"); + + /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */ + for (i = cvt->len_cvt / sizeof(Sint16); i && (((size_t)(dst - 7)) & 15); --i, --src, --dst) { + *dst = ((float)*src) * DIVBY32768; + } + + src -= 7; + dst -= 7; /* adjust to read NEON blocks from the start. */ + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const float32x4_t divby32768 = vdupq_n_f32(DIVBY32768); + while (i >= 8) { /* 8 * 16-bit */ + const int16x8_t ints = vld1q_s16((int16_t const *)src); /* get 8 sint16 into a NEON register. */ + /* split int16 to two int32, then convert to float, then multiply to normalize, store. */ + vst1q_f32(dst, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(ints))), divby32768)); + vst1q_f32(dst + 4, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(ints))), divby32768)); + i -= 8; + src -= 8; + dst -= 8; + } + } + + src += 7; + dst += 7; /* adjust for any scalar finishing. */ + + /* Finish off any leftovers with scalar operations. */ + while (i) { + *dst = ((float)*src) * DIVBY32768; + i--; + src--; + dst--; + } + + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_U16_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Uint16 *src = ((const Uint16 *)(cvt->buf + cvt->len_cvt)) - 1; + float *dst = ((float *)(cvt->buf + cvt->len_cvt * 2)) - 1; + int i; + + LOG_DEBUG_CONVERT("AUDIO_U16", "AUDIO_F32 (using NEON)"); + + /* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */ + for (i = cvt->len_cvt / sizeof(Sint16); i && (((size_t)(dst - 7)) & 15); --i, --src, --dst) { + *dst = (((float)*src) * DIVBY32768) - 1.0f; + } + + src -= 7; + dst -= 7; /* adjust to read NEON blocks from the start. */ + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const float32x4_t divby32768 = vdupq_n_f32(DIVBY32768); + const float32x4_t negone = vdupq_n_f32(-1.0f); + while (i >= 8) { /* 8 * 16-bit */ + const uint16x8_t uints = vld1q_u16((uint16_t const *)src); /* get 8 uint16 into a NEON register. */ + /* split uint16 to two int32, then convert to float, then multiply to normalize, subtract for sign, store. */ + vst1q_f32(dst, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_low_u16(uints))), divby32768)); + vst1q_f32(dst + 4, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_high_u16(uints))), divby32768)); + i -= 8; + src -= 8; + dst -= 8; + } + } + + src += 7; + dst += 7; /* adjust for any scalar finishing. */ + + /* Finish off any leftovers with scalar operations. */ + while (i) { + *dst = (((float)*src) * DIVBY32768) - 1.0f; + i--; + src--; + dst--; + } + + cvt->len_cvt *= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_S32_to_F32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const Sint32 *src = (const Sint32 *)cvt->buf; + float *dst = (float *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_S32", "AUDIO_F32 (using NEON)"); + + /* Get dst aligned to 16 bytes */ + for (i = cvt->len_cvt / sizeof(Sint32); i && (((size_t)dst) & 15); --i, ++src, ++dst) { + *dst = ((float)(*src >> 8)) * DIVBY8388607; + } + + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const float32x4_t divby8388607 = vdupq_n_f32(DIVBY8388607); + const int32_t *mmsrc = (const int32_t *)src; + while (i >= 4) { /* 4 * sint32 */ + /* shift out lowest bits so int fits in a float32. Small precision loss, but much faster. */ + vst1q_f32(dst, vmulq_f32(vcvtq_f32_s32(vshrq_n_s32(vld1q_s32(mmsrc), 8)), divby8388607)); + i -= 4; + mmsrc += 4; + dst += 4; + } + src = (const Sint32 *)mmsrc; + } + + /* Finish off any leftovers with scalar operations. */ + while (i) { + *dst = ((float)(*src >> 8)) * DIVBY8388607; + i--; + src++; + dst++; + } + + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_S8_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Sint8 *dst = (Sint8 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S8 (using NEON)"); + + /* Get dst aligned to 16 bytes */ + for (i = cvt->len_cvt / sizeof(float); i && (((size_t)dst) & 15); --i, ++src, ++dst) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 127; + } else if (sample <= -1.0f) { + *dst = -128; + } else { + *dst = (Sint8)(sample * 127.0f); + } + } + + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const float32x4_t one = vdupq_n_f32(1.0f); + const float32x4_t negone = vdupq_n_f32(-1.0f); + const float32x4_t mulby127 = vdupq_n_f32(127.0f); + int8_t *mmdst = (int8_t *)dst; + while (i >= 16) { /* 16 * float32 */ + const int32x4_t ints1 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */ + const int32x4_t ints2 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src + 4)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */ + const int32x4_t ints3 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src + 8)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */ + const int32x4_t ints4 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src + 12)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */ + const int8x8_t i8lo = vmovn_s16(vcombine_s16(vmovn_s32(ints1), vmovn_s32(ints2))); /* narrow to sint16, combine, narrow to sint8 */ + const int8x8_t i8hi = vmovn_s16(vcombine_s16(vmovn_s32(ints3), vmovn_s32(ints4))); /* narrow to sint16, combine, narrow to sint8 */ + vst1q_s8(mmdst, vcombine_s8(i8lo, i8hi)); /* combine to int8x16_t, store out */ + i -= 16; + src += 16; + mmdst += 16; + } + dst = (Sint8 *)mmdst; + } + + /* Finish off any leftovers with scalar operations. */ + while (i) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 127; + } else if (sample <= -1.0f) { + *dst = -128; + } else { + *dst = (Sint8)(sample * 127.0f); + } + i--; + src++; + dst++; + } + + cvt->len_cvt /= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S8); + } +} + +static void SDLCALL SDL_Convert_F32_to_U8_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Uint8 *dst = cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U8 (using NEON)"); + + /* Get dst aligned to 16 bytes */ + for (i = cvt->len_cvt / sizeof(float); i && (((size_t)dst) & 15); --i, ++src, ++dst) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 255; + } else if (sample <= -1.0f) { + *dst = 0; + } else { + *dst = (Uint8)((sample + 1.0f) * 127.0f); + } + } + + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const float32x4_t one = vdupq_n_f32(1.0f); + const float32x4_t negone = vdupq_n_f32(-1.0f); + const float32x4_t mulby127 = vdupq_n_f32(127.0f); + uint8_t *mmdst = (uint8_t *)dst; + while (i >= 16) { /* 16 * float32 */ + const uint32x4_t uints1 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), one), mulby127)); /* load 4 floats, clamp, convert to uint32 */ + const uint32x4_t uints2 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src + 4)), one), one), mulby127)); /* load 4 floats, clamp, convert to uint32 */ + const uint32x4_t uints3 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src + 8)), one), one), mulby127)); /* load 4 floats, clamp, convert to uint32 */ + const uint32x4_t uints4 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src + 12)), one), one), mulby127)); /* load 4 floats, clamp, convert to uint32 */ + const uint8x8_t ui8lo = vmovn_u16(vcombine_u16(vmovn_u32(uints1), vmovn_u32(uints2))); /* narrow to uint16, combine, narrow to uint8 */ + const uint8x8_t ui8hi = vmovn_u16(vcombine_u16(vmovn_u32(uints3), vmovn_u32(uints4))); /* narrow to uint16, combine, narrow to uint8 */ + vst1q_u8(mmdst, vcombine_u8(ui8lo, ui8hi)); /* combine to uint8x16_t, store out */ + i -= 16; + src += 16; + mmdst += 16; + } + + dst = (Uint8 *)mmdst; + } + + /* Finish off any leftovers with scalar operations. */ + while (i) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 255; + } else if (sample <= -1.0f) { + *dst = 0; + } else { + *dst = (Uint8)((sample + 1.0f) * 127.0f); + } + i--; + src++; + dst++; + } + + cvt->len_cvt /= 4; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_U8); + } +} + +static void SDLCALL SDL_Convert_F32_to_S16_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Sint16 *dst = (Sint16 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S16 (using NEON)"); + + /* Get dst aligned to 16 bytes */ + for (i = cvt->len_cvt / sizeof(float); i && (((size_t)dst) & 15); --i, ++src, ++dst) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 32767; + } else if (sample <= -1.0f) { + *dst = -32768; + } else { + *dst = (Sint16)(sample * 32767.0f); + } + } + + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const float32x4_t one = vdupq_n_f32(1.0f); + const float32x4_t negone = vdupq_n_f32(-1.0f); + const float32x4_t mulby32767 = vdupq_n_f32(32767.0f); + int16_t *mmdst = (int16_t *)dst; + while (i >= 8) { /* 8 * float32 */ + const int32x4_t ints1 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */ + const int32x4_t ints2 = vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src + 4)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */ + vst1q_s16(mmdst, vcombine_s16(vmovn_s32(ints1), vmovn_s32(ints2))); /* narrow to sint16, combine, store out. */ + i -= 8; + src += 8; + mmdst += 8; + } + dst = (Sint16 *)mmdst; + } + + /* Finish off any leftovers with scalar operations. */ + while (i) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 32767; + } else if (sample <= -1.0f) { + *dst = -32768; + } else { + *dst = (Sint16)(sample * 32767.0f); + } + i--; + src++; + dst++; + } + + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S16SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_U16_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Uint16 *dst = (Uint16 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U16 (using NEON)"); + + /* Get dst aligned to 16 bytes */ + for (i = cvt->len_cvt / sizeof(float); i && (((size_t)dst) & 15); --i, ++src, ++dst) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 65535; + } else if (sample <= -1.0f) { + *dst = 0; + } else { + *dst = (Uint16)((sample + 1.0f) * 32767.0f); + } + } + + SDL_assert(!i || !(((size_t)dst) & 15)); + + /* Make sure src is aligned too. */ + if (!(((size_t)src) & 15)) { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const float32x4_t one = vdupq_n_f32(1.0f); + const float32x4_t negone = vdupq_n_f32(-1.0f); + const float32x4_t mulby32767 = vdupq_n_f32(32767.0f); + uint16_t *mmdst = (uint16_t *)dst; + while (i >= 8) { /* 8 * float32 */ + const uint32x4_t uints1 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), one), mulby32767)); /* load 4 floats, clamp, convert to uint32 */ + const uint32x4_t uints2 = vcvtq_u32_f32(vmulq_f32(vaddq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src + 4)), one), one), mulby32767)); /* load 4 floats, clamp, convert to uint32 */ + vst1q_u16(mmdst, vcombine_u16(vmovn_u32(uints1), vmovn_u32(uints2))); /* narrow to uint16, combine, store out. */ + i -= 8; + src += 8; + mmdst += 8; + } + dst = (Uint16 *)mmdst; + } + + /* Finish off any leftovers with scalar operations. */ + while (i) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 65535; + } else if (sample <= -1.0f) { + *dst = 0; + } else { + *dst = (Uint16)((sample + 1.0f) * 32767.0f); + } + i--; + src++; + dst++; + } + + cvt->len_cvt /= 2; + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_U16SYS); + } +} + +static void SDLCALL SDL_Convert_F32_to_S32_NEON(SDL_AudioCVT *cvt, SDL_AudioFormat format) +{ + const float *src = (const float *)cvt->buf; + Sint32 *dst = (Sint32 *)cvt->buf; + int i; + + LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_S32 (using NEON)"); + + /* Get dst aligned to 16 bytes */ + for (i = cvt->len_cvt / sizeof(float); i && (((size_t)dst) & 15); --i, ++src, ++dst) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 2147483647; + } else if (sample <= -1.0f) { + *dst = (-2147483647) - 1; + } else { + *dst = ((Sint32)(sample * 8388607.0f)) << 8; + } + } + + SDL_assert(!i || !(((size_t)dst) & 15)); + SDL_assert(!i || !(((size_t)src) & 15)); + + { + /* Aligned! Do NEON blocks as long as we have 16 bytes available. */ + const float32x4_t one = vdupq_n_f32(1.0f); + const float32x4_t negone = vdupq_n_f32(-1.0f); + const float32x4_t mulby8388607 = vdupq_n_f32(8388607.0f); + int32_t *mmdst = (int32_t *)dst; + while (i >= 4) { /* 4 * float32 */ + vst1q_s32(mmdst, vshlq_n_s32(vcvtq_s32_f32(vmulq_f32(vminq_f32(vmaxq_f32(negone, vld1q_f32(src)), one), mulby8388607)), 8)); + i -= 4; + src += 4; + mmdst += 4; + } + dst = (Sint32 *)mmdst; + } + + /* Finish off any leftovers with scalar operations. */ + while (i) { + const float sample = *src; + if (sample >= 1.0f) { + *dst = 2147483647; + } else if (sample <= -1.0f) { + *dst = (-2147483647) - 1; + } else { + *dst = ((Sint32)(sample * 8388607.0f)) << 8; + } + i--; + src++; + dst++; + } + + if (cvt->filters[++cvt->filter_index]) { + cvt->filters[cvt->filter_index](cvt, AUDIO_S32SYS); + } +} +#endif + +void SDL_ChooseAudioConverters(void) +{ + static SDL_bool converters_chosen = SDL_FALSE; + + if (converters_chosen) { + return; + } + +#define SET_CONVERTER_FUNCS(fntype) \ + SDL_Convert_S8_to_F32 = SDL_Convert_S8_to_F32_##fntype; \ + SDL_Convert_U8_to_F32 = SDL_Convert_U8_to_F32_##fntype; \ + SDL_Convert_S16_to_F32 = SDL_Convert_S16_to_F32_##fntype; \ + SDL_Convert_U16_to_F32 = SDL_Convert_U16_to_F32_##fntype; \ + SDL_Convert_S32_to_F32 = SDL_Convert_S32_to_F32_##fntype; \ + SDL_Convert_F32_to_S8 = SDL_Convert_F32_to_S8_##fntype; \ + SDL_Convert_F32_to_U8 = SDL_Convert_F32_to_U8_##fntype; \ + SDL_Convert_F32_to_S16 = SDL_Convert_F32_to_S16_##fntype; \ + SDL_Convert_F32_to_U16 = SDL_Convert_F32_to_U16_##fntype; \ + SDL_Convert_F32_to_S32 = SDL_Convert_F32_to_S32_##fntype; \ + converters_chosen = SDL_TRUE + +#ifdef HAVE_SSE2_INTRINSICS + if (SDL_HasSSE2()) { + SET_CONVERTER_FUNCS(SSE2); + return; + } +#endif + +#ifdef HAVE_NEON_INTRINSICS + if (SDL_HasNEON()) { + SET_CONVERTER_FUNCS(NEON); + return; + } +#endif + +#if NEED_SCALAR_CONVERTER_FALLBACKS + SET_CONVERTER_FUNCS(Scalar); +#endif + +#undef SET_CONVERTER_FUNCS + + SDL_assert(converters_chosen == SDL_TRUE); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_mixer.c b/third_party/SDL2/src/audio/SDL_mixer.c new file mode 100644 index 00000000000..bb42fe72748 --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_mixer.c @@ -0,0 +1,345 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +/* This provides the default mixing callback for the SDL audio routines */ + +#include "SDL_cpuinfo.h" +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "SDL_sysaudio.h" + +/* This table is used to add two sound values together and pin + * the value to avoid overflow. (used with permission from ARDI) + */ +static const Uint8 mix8[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, + 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, + 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, + 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, + 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, + 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, + 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, + 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, + 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, + 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, + 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, + 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, + 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, + 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, + 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, + 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, + 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, + 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, + 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, + 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, + 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF +}; + +/* The volume ranges from 0 - 128 */ +#define ADJUST_VOLUME(s, v) (s = (s * v) / SDL_MIX_MAXVOLUME) +#define ADJUST_VOLUME_U8(s, v) (s = (((s - 128) * v) / SDL_MIX_MAXVOLUME) + 128) +#define ADJUST_VOLUME_U16(s, v) (s = (((s - 32768) * v) / SDL_MIX_MAXVOLUME) + 32768) + +void SDL_MixAudioFormat(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format, + Uint32 len, int volume) +{ + if (volume == 0) { + return; + } + + switch (format) { + + case AUDIO_U8: + { + Uint8 src_sample; + + while (len--) { + src_sample = *src; + ADJUST_VOLUME_U8(src_sample, volume); + *dst = mix8[*dst + src_sample]; + ++dst; + ++src; + } + } break; + + case AUDIO_S8: + { + Sint8 *dst8, *src8; + Sint8 src_sample; + int dst_sample; + const int max_audioval = SDL_MAX_SINT8; + const int min_audioval = SDL_MIN_SINT8; + + src8 = (Sint8 *)src; + dst8 = (Sint8 *)dst; + while (len--) { + src_sample = *src8; + ADJUST_VOLUME(src_sample, volume); + dst_sample = *dst8 + src_sample; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + *dst8 = dst_sample; + ++dst8; + ++src8; + } + } break; + + case AUDIO_S16LSB: + { + Sint16 src1, src2; + int dst_sample; + const int max_audioval = SDL_MAX_SINT16; + const int min_audioval = SDL_MIN_SINT16; + + len /= 2; + while (len--) { + src1 = SDL_SwapLE16(*(Sint16 *)src); + ADJUST_VOLUME(src1, volume); + src2 = SDL_SwapLE16(*(Sint16 *)dst); + src += 2; + dst_sample = src1 + src2; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + *(Sint16 *)dst = SDL_SwapLE16(dst_sample); + dst += 2; + } + } break; + + case AUDIO_S16MSB: + { + Sint16 src1, src2; + int dst_sample; + const int max_audioval = SDL_MAX_SINT16; + const int min_audioval = SDL_MIN_SINT16; + + len /= 2; + while (len--) { + src1 = SDL_SwapBE16(*(Sint16 *)src); + ADJUST_VOLUME(src1, volume); + src2 = SDL_SwapBE16(*(Sint16 *)dst); + src += 2; + dst_sample = src1 + src2; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + *(Sint16 *)dst = SDL_SwapBE16(dst_sample); + dst += 2; + } + } break; + + case AUDIO_U16LSB: + { + Uint16 src1, src2; + int dst_sample; + const int max_audioval = SDL_MAX_SINT16; + const int min_audioval = SDL_MIN_SINT16; + + len /= 2; + while (len--) { + src1 = SDL_SwapLE16(*(Uint16 *)src); + ADJUST_VOLUME_U16(src1, volume); + src2 = SDL_SwapLE16(*(Uint16 *)dst); + src += 2; + dst_sample = src1 + src2 - 32768 * 2; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + dst_sample += 32768; + *(Uint16 *)dst = SDL_SwapLE16(dst_sample); + dst += 2; + } + } break; + + case AUDIO_U16MSB: + { + Uint16 src1, src2; + int dst_sample; + const int max_audioval = SDL_MAX_SINT16; + const int min_audioval = SDL_MIN_SINT16; + + len /= 2; + while (len--) { + src1 = SDL_SwapBE16(*(Uint16 *)src); + ADJUST_VOLUME_U16(src1, volume); + src2 = SDL_SwapBE16(*(Uint16 *)dst); + src += 2; + dst_sample = src1 + src2 - 32768 * 2; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + dst_sample += 32768; + *(Uint16 *)dst = SDL_SwapBE16(dst_sample); + dst += 2; + } + } break; + + case AUDIO_S32LSB: + { + const Uint32 *src32 = (Uint32 *)src; + Uint32 *dst32 = (Uint32 *)dst; + Sint64 src1, src2; + Sint64 dst_sample; + const Sint64 max_audioval = SDL_MAX_SINT32; + const Sint64 min_audioval = SDL_MIN_SINT32; + + len /= 4; + while (len--) { + src1 = (Sint64)((Sint32)SDL_SwapLE32(*src32)); + src32++; + ADJUST_VOLUME(src1, volume); + src2 = (Sint64)((Sint32)SDL_SwapLE32(*dst32)); + dst_sample = src1 + src2; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + *(dst32++) = SDL_SwapLE32((Uint32)((Sint32)dst_sample)); + } + } break; + + case AUDIO_S32MSB: + { + const Uint32 *src32 = (Uint32 *)src; + Uint32 *dst32 = (Uint32 *)dst; + Sint64 src1, src2; + Sint64 dst_sample; + const Sint64 max_audioval = SDL_MAX_SINT32; + const Sint64 min_audioval = SDL_MIN_SINT32; + + len /= 4; + while (len--) { + src1 = (Sint64)((Sint32)SDL_SwapBE32(*src32)); + src32++; + ADJUST_VOLUME(src1, volume); + src2 = (Sint64)((Sint32)SDL_SwapBE32(*dst32)); + dst_sample = src1 + src2; + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + *(dst32++) = SDL_SwapBE32((Uint32)((Sint32)dst_sample)); + } + } break; + + case AUDIO_F32LSB: + { + const float fmaxvolume = 1.0f / ((float)SDL_MIX_MAXVOLUME); + const float fvolume = (float)volume; + const float *src32 = (float *)src; + float *dst32 = (float *)dst; + float src1, src2; + double dst_sample; + /* !!! FIXME: are these right? */ + const double max_audioval = 3.402823466e+38F; + const double min_audioval = -3.402823466e+38F; + + len /= 4; + while (len--) { + src1 = ((SDL_SwapFloatLE(*src32) * fvolume) * fmaxvolume); + src2 = SDL_SwapFloatLE(*dst32); + src32++; + + dst_sample = ((double)src1) + ((double)src2); + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + *(dst32++) = SDL_SwapFloatLE((float)dst_sample); + } + } break; + + case AUDIO_F32MSB: + { + const float fmaxvolume = 1.0f / ((float)SDL_MIX_MAXVOLUME); + const float fvolume = (float)volume; + const float *src32 = (float *)src; + float *dst32 = (float *)dst; + float src1, src2; + double dst_sample; + /* !!! FIXME: are these right? */ + const double max_audioval = 3.402823466e+38F; + const double min_audioval = -3.402823466e+38F; + + len /= 4; + while (len--) { + src1 = ((SDL_SwapFloatBE(*src32) * fvolume) * fmaxvolume); + src2 = SDL_SwapFloatBE(*dst32); + src32++; + + dst_sample = ((double)src1) + ((double)src2); + if (dst_sample > max_audioval) { + dst_sample = max_audioval; + } else if (dst_sample < min_audioval) { + dst_sample = min_audioval; + } + *(dst32++) = SDL_SwapFloatBE((float)dst_sample); + } + } break; + + default: /* If this happens... FIXME! */ + SDL_SetError("SDL_MixAudioFormat(): unknown audio format"); + return; + } +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_sysaudio.h b/third_party/SDL2/src/audio/SDL_sysaudio.h new file mode 100644 index 00000000000..6e8de52915b --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_sysaudio.h @@ -0,0 +1,215 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +#ifndef SDL_sysaudio_h_ +#define SDL_sysaudio_h_ + +#include "SDL_mutex.h" +#include "SDL_thread.h" +#include "../SDL_dataqueue.h" +#include "./SDL_audio_c.h" + +/* !!! FIXME: These are wordy and unlocalized... */ +#define DEFAULT_OUTPUT_DEVNAME "System audio output device" +#define DEFAULT_INPUT_DEVNAME "System audio capture device" + +/* The SDL audio driver */ +typedef struct SDL_AudioDevice SDL_AudioDevice; +#define _THIS SDL_AudioDevice *_this + +/* Audio targets should call this as devices are added to the system (such as + a USB headset being plugged in), and should also be called for + for every device found during DetectDevices(). */ +extern void SDL_AddAudioDevice(const SDL_bool iscapture, const char *name, SDL_AudioSpec *spec, void *handle); + +/* Audio targets should call this as devices are removed, so SDL can update + its list of available devices. */ +extern void SDL_RemoveAudioDevice(const SDL_bool iscapture, void *handle); + +/* Audio targets should call this if an opened audio device is lost while + being used. This can happen due to i/o errors, or a device being unplugged, + etc. If the device is totally gone, please also call SDL_RemoveAudioDevice() + as appropriate so SDL's list of devices is accurate. */ +extern void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device); + +/* This is the size of a packet when using SDL_QueueAudio(). We allocate + these as necessary and pool them, under the assumption that we'll + eventually end up with a handful that keep recycling, meeting whatever + the app needs. We keep packing data tightly as more arrives to avoid + wasting space, and if we get a giant block of data, we'll split them + into multiple packets behind the scenes. My expectation is that most + apps will have 2-3 of these in the pool. 8k should cover most needs, but + if this is crippling for some embedded system, we can #ifdef this. + The system preallocates enough packets for 2 callbacks' worth of data. */ +#define SDL_AUDIOBUFFERQUEUE_PACKETLEN (8 * 1024) + +typedef struct SDL_AudioDriverImpl +{ + void (*DetectDevices)(void); + int (*OpenDevice)(_THIS, const char *devname); + void (*ThreadInit)(_THIS); /* Called by audio thread at start */ + void (*ThreadDeinit)(_THIS); /* Called by audio thread at end */ + void (*WaitDevice)(_THIS); + void (*PlayDevice)(_THIS); + Uint8 *(*GetDeviceBuf)(_THIS); + int (*CaptureFromDevice)(_THIS, void *buffer, int buflen); + void (*FlushCapture)(_THIS); + void (*CloseDevice)(_THIS); + void (*LockDevice)(_THIS); + void (*UnlockDevice)(_THIS); + void (*FreeDeviceHandle)(void *handle); /**< SDL is done with handle from SDL_AddAudioDevice() */ + void (*Deinitialize)(void); + int (*GetDefaultAudioInfo)(char **name, SDL_AudioSpec *spec, int iscapture); + + /* !!! FIXME: add pause(), so we can optimize instead of mixing silence. */ + + /* Some flags to push duplicate code into the core and reduce #ifdefs. */ + SDL_bool ProvidesOwnCallbackThread; + SDL_bool HasCaptureSupport; + SDL_bool OnlyHasDefaultOutputDevice; + SDL_bool OnlyHasDefaultCaptureDevice; + SDL_bool AllowsArbitraryDeviceNames; + SDL_bool SupportsNonPow2Samples; +} SDL_AudioDriverImpl; + +typedef struct SDL_AudioDeviceItem +{ + void *handle; + char *name; + char *original_name; + SDL_AudioSpec spec; + int dupenum; + struct SDL_AudioDeviceItem *next; +} SDL_AudioDeviceItem; + +typedef struct SDL_AudioDriver +{ + /* * * */ + /* The name of this audio driver */ + const char *name; + + /* * * */ + /* The description of this audio driver */ + const char *desc; + + SDL_AudioDriverImpl impl; + + /* A mutex for device detection */ + SDL_mutex *detectionLock; + SDL_bool captureDevicesRemoved; + SDL_bool outputDevicesRemoved; + int outputDeviceCount; + int inputDeviceCount; + SDL_AudioDeviceItem *outputDevices; + SDL_AudioDeviceItem *inputDevices; +} SDL_AudioDriver; + +/* Define the SDL audio driver structure */ +struct SDL_AudioDevice +{ + /* * * */ + /* Data common to all devices */ + SDL_AudioDeviceID id; + + /* The device's current audio specification */ + SDL_AudioSpec spec; + + /* The callback's expected audio specification (converted vs device's spec). */ + SDL_AudioSpec callbackspec; + + /* Stream that converts and resamples. NULL if not needed. */ + SDL_AudioStream *stream; + + /* Current state flags */ + SDL_atomic_t shutdown; /* true if we are signaling the play thread to end. */ + SDL_atomic_t enabled; /* true if device is functioning and connected. */ + SDL_atomic_t paused; + SDL_bool iscapture; + + /* Scratch buffer used in the bridge between SDL and the user callback. */ + Uint8 *work_buffer; + + /* Size, in bytes, of work_buffer. */ + Uint32 work_buffer_len; + + /* A mutex for locking the mixing buffers */ + SDL_mutex *mixer_lock; + + /* A thread to feed the audio device */ + SDL_Thread *thread; + SDL_threadID threadid; + + /* Queued buffers (if app not using callback). */ + SDL_DataQueue *buffer_queue; + + /* * * */ + /* Data private to this driver */ + struct SDL_PrivateAudioData *hidden; + + void *handle; +}; +#undef _THIS + +typedef struct AudioBootStrap +{ + const char *name; + const char *desc; + SDL_bool (*init)(SDL_AudioDriverImpl *impl); + SDL_bool demand_only; /* 1==request explicitly, or it won't be available. */ +} AudioBootStrap; + +/* Not all of these are available in a given build. Use #ifdefs, etc. */ +extern AudioBootStrap PIPEWIRE_bootstrap; +extern AudioBootStrap PULSEAUDIO_bootstrap; +extern AudioBootStrap ALSA_bootstrap; +extern AudioBootStrap JACK_bootstrap; +extern AudioBootStrap SNDIO_bootstrap; +extern AudioBootStrap NETBSDAUDIO_bootstrap; +extern AudioBootStrap DSP_bootstrap; +extern AudioBootStrap QSAAUDIO_bootstrap; +extern AudioBootStrap SUNAUDIO_bootstrap; +extern AudioBootStrap ARTS_bootstrap; +extern AudioBootStrap ESD_bootstrap; +extern AudioBootStrap NACLAUDIO_bootstrap; +extern AudioBootStrap NAS_bootstrap; +extern AudioBootStrap WASAPI_bootstrap; +extern AudioBootStrap DSOUND_bootstrap; +extern AudioBootStrap WINMM_bootstrap; +extern AudioBootStrap PAUDIO_bootstrap; +extern AudioBootStrap HAIKUAUDIO_bootstrap; +extern AudioBootStrap COREAUDIO_bootstrap; +extern AudioBootStrap DISKAUDIO_bootstrap; +extern AudioBootStrap DUMMYAUDIO_bootstrap; +extern AudioBootStrap FUSIONSOUND_bootstrap; +extern AudioBootStrap aaudio_bootstrap; +extern AudioBootStrap openslES_bootstrap; +extern AudioBootStrap ANDROIDAUDIO_bootstrap; +extern AudioBootStrap PS2AUDIO_bootstrap; +extern AudioBootStrap PSPAUDIO_bootstrap; +extern AudioBootStrap VITAAUD_bootstrap; +extern AudioBootStrap N3DSAUDIO_bootstrap; +extern AudioBootStrap EMSCRIPTENAUDIO_bootstrap; +extern AudioBootStrap OS2AUDIO_bootstrap; + +#endif /* SDL_sysaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_wave.c b/third_party/SDL2/src/audio/SDL_wave.c new file mode 100644 index 00000000000..e71235e0a95 --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_wave.c @@ -0,0 +1,2137 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +#ifdef HAVE_LIMITS_H +#include +#endif +#ifndef INT_MAX +/* Make a lucky guess. */ +#define INT_MAX SDL_MAX_SINT32 +#endif +#ifndef SIZE_MAX +#define SIZE_MAX ((size_t)-1) +#endif + +/* Microsoft WAVE file loading routines */ + +#include "SDL_hints.h" +#include "SDL_audio.h" +#include "SDL_wave.h" +#include "SDL_audio_c.h" + +/* Reads the value stored at the location of the f1 pointer, multiplies it + * with the second argument and then stores the result to f1. + * Returns 0 on success, or -1 if the multiplication overflows, in which case f1 + * does not get modified. + */ +static int SafeMult(size_t *f1, size_t f2) +{ + if (*f1 > 0 && SIZE_MAX / *f1 <= f2) { + return -1; + } + *f1 *= f2; + return 0; +} + +typedef struct ADPCM_DecoderState +{ + Uint32 channels; /* Number of channels. */ + size_t blocksize; /* Size of an ADPCM block in bytes. */ + size_t blockheadersize; /* Size of an ADPCM block header in bytes. */ + size_t samplesperblock; /* Number of samples per channel in an ADPCM block. */ + size_t framesize; /* Size of a sample frame (16-bit PCM) in bytes. */ + Sint64 framestotal; /* Total number of sample frames. */ + Sint64 framesleft; /* Number of sample frames still to be decoded. */ + void *ddata; /* Decoder data from initialization. */ + void *cstate; /* Decoding state for each channel. */ + + /* ADPCM data. */ + struct + { + Uint8 *data; + size_t size; + size_t pos; + } input; + + /* Current ADPCM block in the ADPCM data above. */ + struct + { + Uint8 *data; + size_t size; + size_t pos; + } block; + + /* Decoded 16-bit PCM data. */ + struct + { + Sint16 *data; + size_t size; + size_t pos; + } output; +} ADPCM_DecoderState; + +typedef struct MS_ADPCM_CoeffData +{ + Uint16 coeffcount; + Sint16 *coeff; + Sint16 aligndummy; /* Has to be last member. */ +} MS_ADPCM_CoeffData; + +typedef struct MS_ADPCM_ChannelState +{ + Uint16 delta; + Sint16 coeff1; + Sint16 coeff2; +} MS_ADPCM_ChannelState; + +#ifdef SDL_WAVE_DEBUG_LOG_FORMAT +static void WaveDebugLogFormat(WaveFile *file) +{ + WaveFormat *format = &file->format; + const char *fmtstr = "WAVE file: %s, %u Hz, %s, %u bits, %u %s/s"; + const char *waveformat, *wavechannel, *wavebpsunit = "B"; + Uint32 wavebps = format->byterate; + char channelstr[64]; + + SDL_zeroa(channelstr); + + switch (format->encoding) { + case PCM_CODE: + waveformat = "PCM"; + break; + case IEEE_FLOAT_CODE: + waveformat = "IEEE Float"; + break; + case ALAW_CODE: + waveformat = "A-law"; + break; + case MULAW_CODE: + waveformat = "\xc2\xb5-law"; + break; + case MS_ADPCM_CODE: + waveformat = "MS ADPCM"; + break; + case IMA_ADPCM_CODE: + waveformat = "IMA ADPCM"; + break; + default: + waveformat = "Unknown"; + break; + } + +#define SDL_WAVE_DEBUG_CHANNELCFG(STR, CODE) \ + case CODE: \ + wavechannel = STR; \ + break; +#define SDL_WAVE_DEBUG_CHANNELSTR(STR, CODE) \ + if (format->channelmask & CODE) { \ + SDL_strlcat(channelstr, channelstr[0] ? "-" STR : STR, sizeof(channelstr)); \ + } + + if (format->formattag == EXTENSIBLE_CODE && format->channelmask > 0) { + switch (format->channelmask) { + SDL_WAVE_DEBUG_CHANNELCFG("1.0 Mono", 0x4) + SDL_WAVE_DEBUG_CHANNELCFG("1.1 Mono", 0xc) + SDL_WAVE_DEBUG_CHANNELCFG("2.0 Stereo", 0x3) + SDL_WAVE_DEBUG_CHANNELCFG("2.1 Stereo", 0xb) + SDL_WAVE_DEBUG_CHANNELCFG("3.0 Stereo", 0x7) + SDL_WAVE_DEBUG_CHANNELCFG("3.1 Stereo", 0xf) + SDL_WAVE_DEBUG_CHANNELCFG("3.0 Surround", 0x103) + SDL_WAVE_DEBUG_CHANNELCFG("3.1 Surround", 0x10b) + SDL_WAVE_DEBUG_CHANNELCFG("4.0 Quad", 0x33) + SDL_WAVE_DEBUG_CHANNELCFG("4.1 Quad", 0x3b) + SDL_WAVE_DEBUG_CHANNELCFG("4.0 Surround", 0x107) + SDL_WAVE_DEBUG_CHANNELCFG("4.1 Surround", 0x10f) + SDL_WAVE_DEBUG_CHANNELCFG("5.0", 0x37) + SDL_WAVE_DEBUG_CHANNELCFG("5.1", 0x3f) + SDL_WAVE_DEBUG_CHANNELCFG("5.0 Side", 0x607) + SDL_WAVE_DEBUG_CHANNELCFG("5.1 Side", 0x60f) + SDL_WAVE_DEBUG_CHANNELCFG("6.0", 0x137) + SDL_WAVE_DEBUG_CHANNELCFG("6.1", 0x13f) + SDL_WAVE_DEBUG_CHANNELCFG("6.0 Side", 0x707) + SDL_WAVE_DEBUG_CHANNELCFG("6.1 Side", 0x70f) + SDL_WAVE_DEBUG_CHANNELCFG("7.0", 0xf7) + SDL_WAVE_DEBUG_CHANNELCFG("7.1", 0xff) + SDL_WAVE_DEBUG_CHANNELCFG("7.0 Side", 0x6c7) + SDL_WAVE_DEBUG_CHANNELCFG("7.1 Side", 0x6cf) + SDL_WAVE_DEBUG_CHANNELCFG("7.0 Surround", 0x637) + SDL_WAVE_DEBUG_CHANNELCFG("7.1 Surround", 0x63f) + SDL_WAVE_DEBUG_CHANNELCFG("9.0 Surround", 0x5637) + SDL_WAVE_DEBUG_CHANNELCFG("9.1 Surround", 0x563f) + SDL_WAVE_DEBUG_CHANNELCFG("11.0 Surround", 0x56f7) + SDL_WAVE_DEBUG_CHANNELCFG("11.1 Surround", 0x56ff) + default: + SDL_WAVE_DEBUG_CHANNELSTR("FL", 0x1) + SDL_WAVE_DEBUG_CHANNELSTR("FR", 0x2) + SDL_WAVE_DEBUG_CHANNELSTR("FC", 0x4) + SDL_WAVE_DEBUG_CHANNELSTR("LF", 0x8) + SDL_WAVE_DEBUG_CHANNELSTR("BL", 0x10) + SDL_WAVE_DEBUG_CHANNELSTR("BR", 0x20) + SDL_WAVE_DEBUG_CHANNELSTR("FLC", 0x40) + SDL_WAVE_DEBUG_CHANNELSTR("FRC", 0x80) + SDL_WAVE_DEBUG_CHANNELSTR("BC", 0x100) + SDL_WAVE_DEBUG_CHANNELSTR("SL", 0x200) + SDL_WAVE_DEBUG_CHANNELSTR("SR", 0x400) + SDL_WAVE_DEBUG_CHANNELSTR("TC", 0x800) + SDL_WAVE_DEBUG_CHANNELSTR("TFL", 0x1000) + SDL_WAVE_DEBUG_CHANNELSTR("TFC", 0x2000) + SDL_WAVE_DEBUG_CHANNELSTR("TFR", 0x4000) + SDL_WAVE_DEBUG_CHANNELSTR("TBL", 0x8000) + SDL_WAVE_DEBUG_CHANNELSTR("TBC", 0x10000) + SDL_WAVE_DEBUG_CHANNELSTR("TBR", 0x20000) + break; + } + } else { + switch (format->channels) { + default: + if (SDL_snprintf(channelstr, sizeof(channelstr), "%u channels", format->channels) >= 0) { + wavechannel = channelstr; + break; + } + case 0: + wavechannel = "Unknown"; + break; + case 1: + wavechannel = "Mono"; + break; + case 2: + wavechannel = "Setero"; + break; + } + } + +#undef SDL_WAVE_DEBUG_CHANNELCFG +#undef SDL_WAVE_DEBUG_CHANNELSTR + + if (wavebps >= 1024) { + wavebpsunit = "KiB"; + wavebps = wavebps / 1024 + (wavebps & 0x3ff ? 1 : 0); + } + + SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, fmtstr, waveformat, format->frequency, wavechannel, format->bitspersample, wavebps, wavebpsunit); +} +#endif + +#ifdef SDL_WAVE_DEBUG_DUMP_FORMAT +static void WaveDebugDumpFormat(WaveFile *file, Uint32 rifflen, Uint32 fmtlen, Uint32 datalen) +{ + WaveFormat *format = &file->format; + const char *fmtstr1 = "WAVE chunk dump:\n" + "-------------------------------------------\n" + "RIFF %11u\n" + "-------------------------------------------\n" + " fmt %11u\n" + " wFormatTag 0x%04x\n" + " nChannels %11u\n" + " nSamplesPerSec %11u\n" + " nAvgBytesPerSec %11u\n" + " nBlockAlign %11u\n"; + const char *fmtstr2 = " wBitsPerSample %11u\n"; + const char *fmtstr3 = " cbSize %11u\n"; + const char *fmtstr4a = " wValidBitsPerSample %11u\n"; + const char *fmtstr4b = " wSamplesPerBlock %11u\n"; + const char *fmtstr5 = " dwChannelMask 0x%08x\n" + " SubFormat\n" + " %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x\n"; + const char *fmtstr6 = "-------------------------------------------\n" + " fact\n" + " dwSampleLength %11u\n"; + const char *fmtstr7 = "-------------------------------------------\n" + " data %11u\n" + "-------------------------------------------\n"; + char *dumpstr; + size_t dumppos = 0; + const size_t bufsize = 1024; + int res; + + dumpstr = SDL_malloc(bufsize); + if (!dumpstr) { + return; + } + dumpstr[0] = 0; + + res = SDL_snprintf(dumpstr, bufsize, fmtstr1, rifflen, fmtlen, format->formattag, format->channels, format->frequency, format->byterate, format->blockalign); + dumppos += res > 0 ? res : 0; + if (fmtlen >= 16) { + res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr2, format->bitspersample); + dumppos += res > 0 ? res : 0; + } + if (fmtlen >= 18) { + res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr3, format->extsize); + dumppos += res > 0 ? res : 0; + } + if (format->formattag == EXTENSIBLE_CODE && fmtlen >= 40 && format->extsize >= 22) { + const Uint8 *g = format->subformat; + const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24); + const Uint32 g2 = g[4] | ((Uint32)g[5] << 8); + const Uint32 g3 = g[6] | ((Uint32)g[7] << 8); + + switch (format->encoding) { + default: + res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4a, format->validsamplebits); + dumppos += res > 0 ? res : 0; + break; + case MS_ADPCM_CODE: + case IMA_ADPCM_CODE: + res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock); + dumppos += res > 0 ? res : 0; + break; + } + res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr5, format->channelmask, g1, g2, g3, g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]); + dumppos += res > 0 ? res : 0; + } else { + switch (format->encoding) { + case MS_ADPCM_CODE: + case IMA_ADPCM_CODE: + if (fmtlen >= 20 && format->extsize >= 2) { + res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock); + dumppos += res > 0 ? res : 0; + } + break; + } + } + if (file->fact.status >= 1) { + res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr6, file->fact.samplelength); + dumppos += res > 0 ? res : 0; + } + res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr7, datalen); + dumppos += res > 0 ? res : 0; + + SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, "%s", dumpstr); + + SDL_free(dumpstr); +} +#endif + +static Sint64 WaveAdjustToFactValue(WaveFile *file, Sint64 sampleframes) +{ + if (file->fact.status == 2) { + if (file->facthint == FactStrict && sampleframes < file->fact.samplelength) { + return SDL_SetError("Invalid number of sample frames in WAVE fact chunk (too many)"); + } else if (sampleframes > file->fact.samplelength) { + return file->fact.samplelength; + } + } + + return sampleframes; +} + +static int MS_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength) +{ + WaveFormat *format = &file->format; + const size_t blockheadersize = (size_t)file->format.channels * 7; + const size_t availableblocks = datalength / file->format.blockalign; + const size_t blockframebitsize = (size_t)file->format.bitspersample * file->format.channels; + const size_t trailingdata = datalength % file->format.blockalign; + + if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { + /* The size of the data chunk must be a multiple of the block size. */ + if (datalength < blockheadersize || trailingdata > 0) { + return SDL_SetError("Truncated MS ADPCM block"); + } + } + + /* Calculate number of sample frames that will be decoded. */ + file->sampleframes = (Sint64)availableblocks * format->samplesperblock; + if (trailingdata > 0) { + /* The last block is truncated. Check if we can get any samples out of it. */ + if (file->trunchint == TruncDropFrame) { + /* Drop incomplete sample frame. */ + if (trailingdata >= blockheadersize) { + size_t trailingsamples = 2 + (trailingdata - blockheadersize) * 8 / blockframebitsize; + if (trailingsamples > format->samplesperblock) { + trailingsamples = format->samplesperblock; + } + file->sampleframes += trailingsamples; + } + } + } + + file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes); + if (file->sampleframes < 0) { + return -1; + } + + return 0; +} + +static int MS_ADPCM_Init(WaveFile *file, size_t datalength) +{ + WaveFormat *format = &file->format; + WaveChunk *chunk = &file->chunk; + const size_t blockheadersize = (size_t)format->channels * 7; + const size_t blockdatasize = (size_t)format->blockalign - blockheadersize; + const size_t blockframebitsize = (size_t)format->bitspersample * format->channels; + const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize; + const Sint16 presetcoeffs[14] = { 256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232 }; + size_t i, coeffcount; + MS_ADPCM_CoeffData *coeffdata; + + /* Sanity checks. */ + + /* While it's clear how IMA ADPCM handles more than two channels, the nibble + * order of MS ADPCM makes it awkward. The Standards Update does not talk + * about supporting more than stereo anyway. + */ + if (format->channels > 2) { + return SDL_SetError("Invalid number of channels"); + } + + if (format->bitspersample != 4) { + return SDL_SetError("Invalid MS ADPCM bits per sample of %u", (unsigned int)format->bitspersample); + } + + /* The block size must be big enough to contain the block header. */ + if (format->blockalign < blockheadersize) { + return SDL_SetError("Invalid MS ADPCM block size (nBlockAlign)"); + } + + if (format->formattag == EXTENSIBLE_CODE) { + /* Does have a GUID (like all format tags), but there's no specification + * for how the data is packed into the extensible header. Making + * assumptions here could lead to new formats nobody wants to support. + */ + return SDL_SetError("MS ADPCM with the extensible header is not supported"); + } + + /* There are wSamplesPerBlock, wNumCoef, and at least 7 coefficient pairs in + * the extended part of the header. + */ + if (chunk->size < 22) { + return SDL_SetError("Could not read MS ADPCM format header"); + } + + format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8); + /* Number of coefficient pairs. A pair has two 16-bit integers. */ + coeffcount = chunk->data[20] | ((size_t)chunk->data[21] << 8); + /* bPredictor, the integer offset into the coefficients array, is only + * 8 bits. It can only address the first 256 coefficients. Let's limit + * the count number here. + */ + if (coeffcount > 256) { + coeffcount = 256; + } + + if (chunk->size < 22 + coeffcount * 4) { + return SDL_SetError("Could not read custom coefficients in MS ADPCM format header"); + } else if (format->extsize < 4 + coeffcount * 4) { + return SDL_SetError("Invalid MS ADPCM format header (too small)"); + } else if (coeffcount < 7) { + return SDL_SetError("Missing required coefficients in MS ADPCM format header"); + } + + coeffdata = (MS_ADPCM_CoeffData *)SDL_malloc(sizeof(MS_ADPCM_CoeffData) + coeffcount * 4); + file->decoderdata = coeffdata; /* Freed in cleanup. */ + if (!coeffdata) { + return SDL_OutOfMemory(); + } + coeffdata->coeff = &coeffdata->aligndummy; + coeffdata->coeffcount = (Uint16)coeffcount; + + /* Copy the 16-bit pairs. */ + for (i = 0; i < coeffcount * 2; i++) { + Sint32 c = chunk->data[22 + i * 2] | ((Sint32)chunk->data[23 + i * 2] << 8); + if (c >= 0x8000) { + c -= 0x10000; + } + if (i < 14 && c != presetcoeffs[i]) { + return SDL_SetError("Wrong preset coefficients in MS ADPCM format header"); + } + coeffdata->coeff[i] = (Sint16)c; + } + + /* Technically, wSamplesPerBlock is required, but we have all the + * information in the other fields to calculate it, if it's zero. + */ + if (format->samplesperblock == 0) { + /* Let's be nice to the encoders that didn't know how to fill this. + * The Standards Update calculates it this way: + * + * x = Block size (in bits) minus header size (in bits) + * y = Bit depth multiplied by channel count + * z = Number of samples per channel in block header + * wSamplesPerBlock = x / y + z + */ + format->samplesperblock = (Uint32)blockdatasamples + 2; + } + + /* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if + * the number of samples doesn't fit into the block. The Standards Update + * also describes wSamplesPerBlock with a formula that makes it necessary to + * always fill the block with the maximum amount of samples, but this is not + * enforced here as there are no compatibility issues. + * A truncated block header with just one sample is not supported. + */ + if (format->samplesperblock == 1 || blockdatasamples < format->samplesperblock - 2) { + return SDL_SetError("Invalid number of samples per MS ADPCM block (wSamplesPerBlock)"); + } + + if (MS_ADPCM_CalculateSampleFrames(file, datalength) < 0) { + return -1; + } + + return 0; +} + +static Sint16 MS_ADPCM_ProcessNibble(MS_ADPCM_ChannelState *cstate, Sint32 sample1, Sint32 sample2, Uint8 nybble) +{ + const Sint32 max_audioval = 32767; + const Sint32 min_audioval = -32768; + const Uint16 max_deltaval = 65535; + const Uint16 adaptive[] = { + 230, 230, 230, 230, 307, 409, 512, 614, + 768, 614, 512, 409, 307, 230, 230, 230 + }; + Sint32 new_sample; + Sint32 errordelta; + Uint32 delta = cstate->delta; + + new_sample = (sample1 * cstate->coeff1 + sample2 * cstate->coeff2) / 256; + /* The nibble is a signed 4-bit error delta. */ + errordelta = (Sint32)nybble - (nybble >= 0x08 ? 0x10 : 0); + new_sample += (Sint32)delta * errordelta; + if (new_sample < min_audioval) { + new_sample = min_audioval; + } else if (new_sample > max_audioval) { + new_sample = max_audioval; + } + delta = (delta * adaptive[nybble]) / 256; + if (delta < 16) { + delta = 16; + } else if (delta > max_deltaval) { + /* This issue is not described in the Standards Update and therefore + * undefined. It seems sensible to prevent overflows with a limit. + */ + delta = max_deltaval; + } + + cstate->delta = (Uint16)delta; + return (Sint16)new_sample; +} + +static int MS_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state) +{ + Uint8 coeffindex; + const Uint32 channels = state->channels; + Sint32 sample; + Uint32 c; + MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate; + MS_ADPCM_CoeffData *ddata = (MS_ADPCM_CoeffData *)state->ddata; + + for (c = 0; c < channels; c++) { + size_t o = c; + + /* Load the coefficient pair into the channel state. */ + coeffindex = state->block.data[o]; + if (coeffindex > ddata->coeffcount) { + return SDL_SetError("Invalid MS ADPCM coefficient index in block header"); + } + cstate[c].coeff1 = ddata->coeff[coeffindex * 2]; + cstate[c].coeff2 = ddata->coeff[coeffindex * 2 + 1]; + + /* Initial delta value. */ + o = (size_t)channels + c * 2; + cstate[c].delta = state->block.data[o] | ((Uint16)state->block.data[o + 1] << 8); + + /* Load the samples from the header. Interestingly, the sample later in + * the output stream comes first. + */ + o = (size_t)channels * 3 + c * 2; + sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8); + if (sample >= 0x8000) { + sample -= 0x10000; + } + state->output.data[state->output.pos + channels] = (Sint16)sample; + + o = (size_t)channels * 5 + c * 2; + sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8); + if (sample >= 0x8000) { + sample -= 0x10000; + } + state->output.data[state->output.pos] = (Sint16)sample; + + state->output.pos++; + } + + state->block.pos += state->blockheadersize; + + /* Skip second sample frame that came from the header. */ + state->output.pos += state->channels; + + /* Header provided two sample frames. */ + state->framesleft -= 2; + + return 0; +} + +/* Decodes the data of the MS ADPCM block. Decoding will stop if a block is too + * short, returning with none or partially decoded data. The partial data + * will always contain full sample frames (same sample count for each channel). + * Incomplete sample frames are discarded. + */ +static int MS_ADPCM_DecodeBlockData(ADPCM_DecoderState *state) +{ + Uint16 nybble = 0; + Sint16 sample1, sample2; + const Uint32 channels = state->channels; + Uint32 c; + MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate; + + size_t blockpos = state->block.pos; + size_t blocksize = state->block.size; + + size_t outpos = state->output.pos; + + Sint64 blockframesleft = state->samplesperblock - 2; + if (blockframesleft > state->framesleft) { + blockframesleft = state->framesleft; + } + + while (blockframesleft > 0) { + for (c = 0; c < channels; c++) { + if (nybble & 0x4000) { + nybble <<= 4; + } else if (blockpos < blocksize) { + nybble = state->block.data[blockpos++] | 0x4000; + } else { + /* Out of input data. Drop the incomplete frame and return. */ + state->output.pos = outpos - c; + return -1; + } + + /* Load previous samples which may come from the block header. */ + sample1 = state->output.data[outpos - channels]; + sample2 = state->output.data[outpos - channels * 2]; + + sample1 = MS_ADPCM_ProcessNibble(cstate + c, sample1, sample2, (nybble >> 4) & 0x0f); + state->output.data[outpos++] = sample1; + } + + state->framesleft--; + blockframesleft--; + } + + state->output.pos = outpos; + + return 0; +} + +static int MS_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) +{ + int result; + size_t bytesleft, outputsize; + WaveChunk *chunk = &file->chunk; + ADPCM_DecoderState state; + MS_ADPCM_ChannelState cstate[2]; + + SDL_zero(state); + SDL_zeroa(cstate); + + if (chunk->size != chunk->length) { + /* Could not read everything. Recalculate number of sample frames. */ + if (MS_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) { + return -1; + } + } + + /* Nothing to decode, nothing to return. */ + if (file->sampleframes == 0) { + *audio_buf = NULL; + *audio_len = 0; + return 0; + } + + state.blocksize = file->format.blockalign; + state.channels = file->format.channels; + state.blockheadersize = (size_t)state.channels * 7; + state.samplesperblock = file->format.samplesperblock; + state.framesize = state.channels * sizeof(Sint16); + state.ddata = file->decoderdata; + state.framestotal = file->sampleframes; + state.framesleft = state.framestotal; + + state.input.data = chunk->data; + state.input.size = chunk->size; + state.input.pos = 0; + + /* The output size in bytes. May get modified if data is truncated. */ + outputsize = (size_t)state.framestotal; + if (SafeMult(&outputsize, state.framesize)) { + return SDL_OutOfMemory(); + } else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) { + return SDL_SetError("WAVE file too big"); + } + + state.output.pos = 0; + state.output.size = outputsize / sizeof(Sint16); + state.output.data = (Sint16 *)SDL_calloc(1, outputsize); + if (!state.output.data) { + return SDL_OutOfMemory(); + } + + state.cstate = cstate; + + /* Decode block by block. A truncated block will stop the decoding. */ + bytesleft = state.input.size - state.input.pos; + while (state.framesleft > 0 && bytesleft >= state.blockheadersize) { + state.block.data = state.input.data + state.input.pos; + state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize; + state.block.pos = 0; + + if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) { + /* Somehow didn't allocate enough space for the output. */ + SDL_free(state.output.data); + return SDL_SetError("Unexpected overflow in MS ADPCM decoder"); + } + + /* Initialize decoder with the values from the block header. */ + result = MS_ADPCM_DecodeBlockHeader(&state); + if (result == -1) { + SDL_free(state.output.data); + return -1; + } + + /* Decode the block data. It stores the samples directly in the output. */ + result = MS_ADPCM_DecodeBlockData(&state); + if (result == -1) { + /* Unexpected end. Stop decoding and return partial data if necessary. */ + if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { + SDL_free(state.output.data); + return SDL_SetError("Truncated data chunk"); + } else if (file->trunchint != TruncDropFrame) { + state.output.pos -= state.output.pos % (state.samplesperblock * state.channels); + } + outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */ + break; + } + + state.input.pos += state.block.size; + bytesleft = state.input.size - state.input.pos; + } + + *audio_buf = (Uint8 *)state.output.data; + *audio_len = (Uint32)outputsize; + + return 0; +} + +static int IMA_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength) +{ + WaveFormat *format = &file->format; + const size_t blockheadersize = (size_t)format->channels * 4; + const size_t subblockframesize = (size_t)format->channels * 4; + const size_t availableblocks = datalength / format->blockalign; + const size_t trailingdata = datalength % format->blockalign; + + if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { + /* The size of the data chunk must be a multiple of the block size. */ + if (datalength < blockheadersize || trailingdata > 0) { + return SDL_SetError("Truncated IMA ADPCM block"); + } + } + + /* Calculate number of sample frames that will be decoded. */ + file->sampleframes = (Uint64)availableblocks * format->samplesperblock; + if (trailingdata > 0) { + /* The last block is truncated. Check if we can get any samples out of it. */ + if (file->trunchint == TruncDropFrame && trailingdata > blockheadersize - 2) { + /* The sample frame in the header of the truncated block is present. + * Drop incomplete sample frames. + */ + size_t trailingsamples = 1; + + if (trailingdata > blockheadersize) { + /* More data following after the header. */ + const size_t trailingblockdata = trailingdata - blockheadersize; + const size_t trailingsubblockdata = trailingblockdata % subblockframesize; + trailingsamples += (trailingblockdata / subblockframesize) * 8; + /* Due to the interleaved sub-blocks, the last 4 bytes determine + * how many samples of the truncated sub-block are lost. + */ + if (trailingsubblockdata > subblockframesize - 4) { + trailingsamples += (trailingsubblockdata % 4) * 2; + } + } + + if (trailingsamples > format->samplesperblock) { + trailingsamples = format->samplesperblock; + } + file->sampleframes += trailingsamples; + } + } + + file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes); + if (file->sampleframes < 0) { + return -1; + } + + return 0; +} + +static int IMA_ADPCM_Init(WaveFile *file, size_t datalength) +{ + WaveFormat *format = &file->format; + WaveChunk *chunk = &file->chunk; + const size_t blockheadersize = (size_t)format->channels * 4; + const size_t blockdatasize = (size_t)format->blockalign - blockheadersize; + const size_t blockframebitsize = (size_t)format->bitspersample * format->channels; + const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize; + + /* Sanity checks. */ + + /* IMA ADPCM can also have 3-bit samples, but it's not supported by SDL at this time. */ + if (format->bitspersample == 3) { + return SDL_SetError("3-bit IMA ADPCM currently not supported"); + } else if (format->bitspersample != 4) { + return SDL_SetError("Invalid IMA ADPCM bits per sample of %u", (unsigned int)format->bitspersample); + } + + /* The block size is required to be a multiple of 4 and it must be able to + * hold a block header. + */ + if (format->blockalign < blockheadersize || format->blockalign % 4) { + return SDL_SetError("Invalid IMA ADPCM block size (nBlockAlign)"); + } + + if (format->formattag == EXTENSIBLE_CODE) { + /* There's no specification for this, but it's basically the same + * format because the extensible header has wSampePerBlocks too. + */ + } else { + /* The Standards Update says there 'should' be 2 bytes for wSamplesPerBlock. */ + if (chunk->size >= 20 && format->extsize >= 2) { + format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8); + } + } + + if (format->samplesperblock == 0) { + /* Field zero? No problem. We just assume the encoder packed the block. + * The specification calculates it this way: + * + * x = Block size (in bits) minus header size (in bits) + * y = Bit depth multiplied by channel count + * z = Number of samples per channel in header + * wSamplesPerBlock = x / y + z + */ + format->samplesperblock = (Uint32)blockdatasamples + 1; + } + + /* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if + * the number of samples doesn't fit into the block. The Standards Update + * also describes wSamplesPerBlock with a formula that makes it necessary + * to always fill the block with the maximum amount of samples, but this is + * not enforced here as there are no compatibility issues. + */ + if (blockdatasamples < format->samplesperblock - 1) { + return SDL_SetError("Invalid number of samples per IMA ADPCM block (wSamplesPerBlock)"); + } + + if (IMA_ADPCM_CalculateSampleFrames(file, datalength) < 0) { + return -1; + } + + return 0; +} + +static Sint16 IMA_ADPCM_ProcessNibble(Sint8 *cindex, Sint16 lastsample, Uint8 nybble) +{ + const Sint32 max_audioval = 32767; + const Sint32 min_audioval = -32768; + const Sint8 index_table_4b[16] = { + -1, -1, -1, -1, + 2, 4, 6, 8, + -1, -1, -1, -1, + 2, 4, 6, 8 + }; + const Uint16 step_table[89] = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, + 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, + 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, + 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, + 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, + 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, + 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, + 22385, 24623, 27086, 29794, 32767 + }; + Uint32 step; + Sint32 sample, delta; + Sint8 index = *cindex; + + /* Clamp index into valid range. */ + if (index > 88) { + index = 88; + } else if (index < 0) { + index = 0; + } + + /* explicit cast to avoid gcc warning about using 'char' as array index */ + step = step_table[(size_t)index]; + + /* Update index value */ + *cindex = index + index_table_4b[nybble]; + + /* This calculation uses shifts and additions because multiplications were + * much slower back then. Sadly, this can't just be replaced with an actual + * multiplication now as the old algorithm drops some bits. The closest + * approximation I could find is something like this: + * (nybble & 0x8 ? -1 : 1) * ((nybble & 0x7) * step / 4 + step / 8) + */ + delta = step >> 3; + if (nybble & 0x04) { + delta += step; + } + if (nybble & 0x02) { + delta += step >> 1; + } + if (nybble & 0x01) { + delta += step >> 2; + } + if (nybble & 0x08) { + delta = -delta; + } + + sample = lastsample + delta; + + /* Clamp output sample */ + if (sample > max_audioval) { + sample = max_audioval; + } else if (sample < min_audioval) { + sample = min_audioval; + } + + return (Sint16)sample; +} + +static int IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state) +{ + Sint16 step; + Uint32 c; + Uint8 *cstate = (Uint8 *)state->cstate; + + for (c = 0; c < state->channels; c++) { + size_t o = state->block.pos + c * 4; + + /* Extract the sample from the header. */ + Sint32 sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8); + if (sample >= 0x8000) { + sample -= 0x10000; + } + state->output.data[state->output.pos++] = (Sint16)sample; + + /* Channel step index. */ + step = (Sint16)state->block.data[o + 2]; + cstate[c] = (Sint8)(step > 0x80 ? step - 0x100 : step); + + /* Reserved byte in block header, should be 0. */ + if (state->block.data[o + 3] != 0) { + /* Uh oh, corrupt data? Buggy code? */; + } + } + + state->block.pos += state->blockheadersize; + + /* Header provided one sample frame. */ + state->framesleft--; + + return 0; +} + +/* Decodes the data of the IMA ADPCM block. Decoding will stop if a block is too + * short, returning with none or partially decoded data. The partial data always + * contains full sample frames (same sample count for each channel). + * Incomplete sample frames are discarded. + */ +static int IMA_ADPCM_DecodeBlockData(ADPCM_DecoderState *state) +{ + size_t i; + int retval = 0; + const Uint32 channels = state->channels; + const size_t subblockframesize = (size_t)channels * 4; + Uint64 bytesrequired; + Uint32 c; + + size_t blockpos = state->block.pos; + size_t blocksize = state->block.size; + size_t blockleft = blocksize - blockpos; + + size_t outpos = state->output.pos; + + Sint64 blockframesleft = state->samplesperblock - 1; + if (blockframesleft > state->framesleft) { + blockframesleft = state->framesleft; + } + + bytesrequired = (blockframesleft + 7) / 8 * subblockframesize; + if (blockleft < bytesrequired) { + /* Data truncated. Calculate how many samples we can get out if it. */ + const size_t guaranteedframes = blockleft / subblockframesize; + const size_t remainingbytes = blockleft % subblockframesize; + blockframesleft = guaranteedframes; + if (remainingbytes > subblockframesize - 4) { + blockframesleft += (remainingbytes % 4) * 2; + } + /* Signal the truncation. */ + retval = -1; + } + + /* Each channel has their nibbles packed into 32-bit blocks. These blocks + * are interleaved and make up the data part of the ADPCM block. This loop + * decodes the samples as they come from the input data and puts them at + * the appropriate places in the output data. + */ + while (blockframesleft > 0) { + const size_t subblocksamples = blockframesleft < 8 ? (size_t)blockframesleft : 8; + + for (c = 0; c < channels; c++) { + Uint8 nybble = 0; + /* Load previous sample which may come from the block header. */ + Sint16 sample = state->output.data[outpos + c - channels]; + + for (i = 0; i < subblocksamples; i++) { + if (i & 1) { + nybble >>= 4; + } else { + nybble = state->block.data[blockpos++]; + } + + sample = IMA_ADPCM_ProcessNibble((Sint8 *)state->cstate + c, sample, nybble & 0x0f); + state->output.data[outpos + c + i * channels] = sample; + } + } + + outpos += channels * subblocksamples; + state->framesleft -= subblocksamples; + blockframesleft -= subblocksamples; + } + + state->block.pos = blockpos; + state->output.pos = outpos; + + return retval; +} + +static int IMA_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) +{ + int result; + size_t bytesleft, outputsize; + WaveChunk *chunk = &file->chunk; + ADPCM_DecoderState state; + Sint8 *cstate; + + if (chunk->size != chunk->length) { + /* Could not read everything. Recalculate number of sample frames. */ + if (IMA_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) { + return -1; + } + } + + /* Nothing to decode, nothing to return. */ + if (file->sampleframes == 0) { + *audio_buf = NULL; + *audio_len = 0; + return 0; + } + + SDL_zero(state); + state.channels = file->format.channels; + state.blocksize = file->format.blockalign; + state.blockheadersize = (size_t)state.channels * 4; + state.samplesperblock = file->format.samplesperblock; + state.framesize = state.channels * sizeof(Sint16); + state.framestotal = file->sampleframes; + state.framesleft = state.framestotal; + + state.input.data = chunk->data; + state.input.size = chunk->size; + state.input.pos = 0; + + /* The output size in bytes. May get modified if data is truncated. */ + outputsize = (size_t)state.framestotal; + if (SafeMult(&outputsize, state.framesize)) { + return SDL_OutOfMemory(); + } else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) { + return SDL_SetError("WAVE file too big"); + } + + state.output.pos = 0; + state.output.size = outputsize / sizeof(Sint16); + state.output.data = (Sint16 *)SDL_malloc(outputsize); + if (!state.output.data) { + return SDL_OutOfMemory(); + } + + cstate = (Sint8 *)SDL_calloc(state.channels, sizeof(Sint8)); + if (!cstate) { + SDL_free(state.output.data); + return SDL_OutOfMemory(); + } + state.cstate = cstate; + + /* Decode block by block. A truncated block will stop the decoding. */ + bytesleft = state.input.size - state.input.pos; + while (state.framesleft > 0 && bytesleft >= state.blockheadersize) { + state.block.data = state.input.data + state.input.pos; + state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize; + state.block.pos = 0; + + if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) { + /* Somehow didn't allocate enough space for the output. */ + SDL_free(state.output.data); + SDL_free(cstate); + return SDL_SetError("Unexpected overflow in IMA ADPCM decoder"); + } + + /* Initialize decoder with the values from the block header. */ + result = IMA_ADPCM_DecodeBlockHeader(&state); + if (result == 0) { + /* Decode the block data. It stores the samples directly in the output. */ + result = IMA_ADPCM_DecodeBlockData(&state); + } + + if (result == -1) { + /* Unexpected end. Stop decoding and return partial data if necessary. */ + if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { + SDL_free(state.output.data); + SDL_free(cstate); + return SDL_SetError("Truncated data chunk"); + } else if (file->trunchint != TruncDropFrame) { + state.output.pos -= state.output.pos % (state.samplesperblock * state.channels); + } + outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */ + break; + } + + state.input.pos += state.block.size; + bytesleft = state.input.size - state.input.pos; + } + + *audio_buf = (Uint8 *)state.output.data; + *audio_len = (Uint32)outputsize; + + SDL_free(cstate); + + return 0; +} + +static int LAW_Init(WaveFile *file, size_t datalength) +{ + WaveFormat *format = &file->format; + + /* Standards Update requires this to be 8. */ + if (format->bitspersample != 8) { + return SDL_SetError("Invalid companded bits per sample of %u", (unsigned int)format->bitspersample); + } + + /* Not going to bother with weird padding. */ + if (format->blockalign != format->channels) { + return SDL_SetError("Unsupported block alignment"); + } + + if ((file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict)) { + if (format->blockalign > 1 && datalength % format->blockalign) { + return SDL_SetError("Truncated data chunk in WAVE file"); + } + } + + file->sampleframes = WaveAdjustToFactValue(file, datalength / format->blockalign); + if (file->sampleframes < 0) { + return -1; + } + + return 0; +} + +static int LAW_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) +{ +#ifdef SDL_WAVE_LAW_LUT + const Sint16 alaw_lut[256] = { + -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752, + -2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016, + -20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136, -11008, + -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544, -14080, -13568, -344, + -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88, + -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376, + -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688, + -656, -752, -720, -560, -528, -624, -592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504, + 5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784, 2752, + 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392, 22016, + 20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008, + 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, 344, + 328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88, + 72, 120, 104, 24, 8, 56, 40, 216, 200, 248, 232, 152, 136, 184, 168, 1376, + 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, 688, + 656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848 + }; + const Sint16 mulaw_lut[256] = { + -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, -15996, + -15484, -14972, -14460, -13948, -13436, -12924, -12412, -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932, + -7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900, + -3772, -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884, + -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, -876, + -844, -812, -780, -748, -716, -684, -652, -620, -588, -556, -524, -492, -460, -428, -396, -372, + -356, -340, -324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164, -148, -132, -120, + -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, -8, 0, 32124, + 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, + 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932, + 7676, 7420, 7164, 6908, 6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900, + 3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884, + 1820, 1756, 1692, 1628, 1564, 1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876, + 844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524, 492, 460, 428, 396, 372, + 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, + 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0 + }; +#endif + + WaveFormat *format = &file->format; + WaveChunk *chunk = &file->chunk; + size_t i, sample_count, expanded_len; + Uint8 *src; + Sint16 *dst; + + if (chunk->length != chunk->size) { + file->sampleframes = WaveAdjustToFactValue(file, chunk->size / format->blockalign); + if (file->sampleframes < 0) { + return -1; + } + } + + /* Nothing to decode, nothing to return. */ + if (file->sampleframes == 0) { + *audio_buf = NULL; + *audio_len = 0; + return 0; + } + + sample_count = (size_t)file->sampleframes; + if (SafeMult(&sample_count, format->channels)) { + return SDL_OutOfMemory(); + } + + expanded_len = sample_count; + if (SafeMult(&expanded_len, sizeof(Sint16))) { + return SDL_OutOfMemory(); + } else if (expanded_len > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) { + return SDL_SetError("WAVE file too big"); + } + + /* 1 to avoid allocating zero bytes, to keep static analysis happy. */ + src = (Uint8 *)SDL_realloc(chunk->data, expanded_len ? expanded_len : 1); + if (!src) { + return SDL_OutOfMemory(); + } + chunk->data = NULL; + chunk->size = 0; + + dst = (Sint16 *)src; + + /* Work backwards, since we're expanding in-place. SDL_AudioSpec.format will + * inform the caller about the byte order. + */ + i = sample_count; + switch (file->format.encoding) { +#ifdef SDL_WAVE_LAW_LUT + case ALAW_CODE: + while (i--) { + dst[i] = alaw_lut[src[i]]; + } + break; + case MULAW_CODE: + while (i--) { + dst[i] = mulaw_lut[src[i]]; + } + break; +#else + case ALAW_CODE: + while (i--) { + Uint8 nibble = src[i]; + Uint8 exponent = (nibble & 0x7f) ^ 0x55; + Sint16 mantissa = exponent & 0xf; + + exponent >>= 4; + if (exponent > 0) { + mantissa |= 0x10; + } + mantissa = (mantissa << 4) | 0x8; + if (exponent > 1) { + mantissa <<= exponent - 1; + } + + dst[i] = nibble & 0x80 ? mantissa : -mantissa; + } + break; + case MULAW_CODE: + while (i--) { + Uint8 nibble = ~src[i]; + Sint16 mantissa = nibble & 0xf; + Uint8 exponent = (nibble >> 4) & 0x7; + Sint16 step = 4 << (exponent + 1); + + mantissa = (0x80 << exponent) + step * mantissa + step / 2 - 132; + + dst[i] = nibble & 0x80 ? -mantissa : mantissa; + } + break; +#endif + default: + SDL_free(src); + return SDL_SetError("Unknown companded encoding"); + } + + *audio_buf = src; + *audio_len = (Uint32)expanded_len; + + return 0; +} + +static int PCM_Init(WaveFile *file, size_t datalength) +{ + WaveFormat *format = &file->format; + + if (format->encoding == PCM_CODE) { + switch (format->bitspersample) { + case 8: + case 16: + case 24: + case 32: + /* These are supported. */ + break; + default: + return SDL_SetError("%u-bit PCM format not supported", (unsigned int)format->bitspersample); + } + } else if (format->encoding == IEEE_FLOAT_CODE) { + if (format->bitspersample != 32) { + return SDL_SetError("%u-bit IEEE floating-point format not supported", (unsigned int)format->bitspersample); + } + } + + /* It wouldn't be that hard to support more exotic block sizes, but + * the most common formats should do for now. + */ + /* Make sure we're a multiple of the blockalign, at least. */ + if ((format->channels * format->bitspersample) % (format->blockalign * 8)) { + return SDL_SetError("Unsupported block alignment"); + } + + if ((file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict)) { + if (format->blockalign > 1 && datalength % format->blockalign) { + return SDL_SetError("Truncated data chunk in WAVE file"); + } + } + + file->sampleframes = WaveAdjustToFactValue(file, datalength / format->blockalign); + if (file->sampleframes < 0) { + return -1; + } + + return 0; +} + +static int PCM_ConvertSint24ToSint32(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) +{ + WaveFormat *format = &file->format; + WaveChunk *chunk = &file->chunk; + size_t i, expanded_len, sample_count; + Uint8 *ptr; + + sample_count = (size_t)file->sampleframes; + if (SafeMult(&sample_count, format->channels)) { + return SDL_OutOfMemory(); + } + + expanded_len = sample_count; + if (SafeMult(&expanded_len, sizeof(Sint32))) { + return SDL_OutOfMemory(); + } else if (expanded_len > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) { + return SDL_SetError("WAVE file too big"); + } + + /* 1 to avoid allocating zero bytes, to keep static analysis happy. */ + ptr = (Uint8 *)SDL_realloc(chunk->data, expanded_len ? expanded_len : 1); + if (!ptr) { + return SDL_OutOfMemory(); + } + + /* This pointer is now invalid. */ + chunk->data = NULL; + chunk->size = 0; + + *audio_buf = ptr; + *audio_len = (Uint32)expanded_len; + + /* work from end to start, since we're expanding in-place. */ + for (i = sample_count; i > 0; i--) { + const size_t o = i - 1; + uint8_t b[4]; + + b[0] = 0; + b[1] = ptr[o * 3]; + b[2] = ptr[o * 3 + 1]; + b[3] = ptr[o * 3 + 2]; + + ptr[o * 4 + 0] = b[0]; + ptr[o * 4 + 1] = b[1]; + ptr[o * 4 + 2] = b[2]; + ptr[o * 4 + 3] = b[3]; + } + + return 0; +} + +static int PCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) +{ + WaveFormat *format = &file->format; + WaveChunk *chunk = &file->chunk; + size_t outputsize; + + if (chunk->length != chunk->size) { + file->sampleframes = WaveAdjustToFactValue(file, chunk->size / format->blockalign); + if (file->sampleframes < 0) { + return -1; + } + } + + /* Nothing to decode, nothing to return. */ + if (file->sampleframes == 0) { + *audio_buf = NULL; + *audio_len = 0; + return 0; + } + + /* 24-bit samples get shifted to 32 bits. */ + if (format->encoding == PCM_CODE && format->bitspersample == 24) { + return PCM_ConvertSint24ToSint32(file, audio_buf, audio_len); + } + + outputsize = (size_t)file->sampleframes; + if (SafeMult(&outputsize, format->blockalign)) { + return SDL_OutOfMemory(); + } else if (outputsize > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) { + return SDL_SetError("WAVE file too big"); + } + + *audio_buf = chunk->data; + *audio_len = (Uint32)outputsize; + + /* This pointer is going to be returned to the caller. Prevent free in cleanup. */ + chunk->data = NULL; + chunk->size = 0; + + return 0; +} + +static WaveRiffSizeHint WaveGetRiffSizeHint(void) +{ + const char *hint = SDL_GetHint(SDL_HINT_WAVE_RIFF_CHUNK_SIZE); + + if (hint) { + if (SDL_strcmp(hint, "force") == 0) { + return RiffSizeForce; + } else if (SDL_strcmp(hint, "ignore") == 0) { + return RiffSizeIgnore; + } else if (SDL_strcmp(hint, "ignorezero") == 0) { + return RiffSizeIgnoreZero; + } else if (SDL_strcmp(hint, "maximum") == 0) { + return RiffSizeMaximum; + } + } + + return RiffSizeNoHint; +} + +static WaveTruncationHint WaveGetTruncationHint(void) +{ + const char *hint = SDL_GetHint(SDL_HINT_WAVE_TRUNCATION); + + if (hint) { + if (SDL_strcmp(hint, "verystrict") == 0) { + return TruncVeryStrict; + } else if (SDL_strcmp(hint, "strict") == 0) { + return TruncStrict; + } else if (SDL_strcmp(hint, "dropframe") == 0) { + return TruncDropFrame; + } else if (SDL_strcmp(hint, "dropblock") == 0) { + return TruncDropBlock; + } + } + + return TruncNoHint; +} + +static WaveFactChunkHint WaveGetFactChunkHint(void) +{ + const char *hint = SDL_GetHint(SDL_HINT_WAVE_FACT_CHUNK); + + if (hint) { + if (SDL_strcmp(hint, "truncate") == 0) { + return FactTruncate; + } else if (SDL_strcmp(hint, "strict") == 0) { + return FactStrict; + } else if (SDL_strcmp(hint, "ignorezero") == 0) { + return FactIgnoreZero; + } else if (SDL_strcmp(hint, "ignore") == 0) { + return FactIgnore; + } + } + + return FactNoHint; +} + +static void WaveFreeChunkData(WaveChunk *chunk) +{ + if (chunk->data) { + SDL_free(chunk->data); + chunk->data = NULL; + } + chunk->size = 0; +} + +static int WaveNextChunk(SDL_RWops *src, WaveChunk *chunk) +{ + Uint32 chunkheader[2]; + Sint64 nextposition = chunk->position + chunk->length; + + /* Data is no longer valid after this function returns. */ + WaveFreeChunkData(chunk); + + /* Error on overflows. */ + if (SDL_MAX_SINT64 - chunk->length < chunk->position || SDL_MAX_SINT64 - 8 < nextposition) { + return -1; + } + + /* RIFF chunks have a 2-byte alignment. Skip padding byte. */ + if (chunk->length & 1) { + nextposition++; + } + + if (SDL_RWseek(src, nextposition, RW_SEEK_SET) != nextposition) { + /* Not sure how we ended up here. Just abort. */ + return -2; + } else if (SDL_RWread(src, chunkheader, 4, 2) != 2) { + return -1; + } + + chunk->fourcc = SDL_SwapLE32(chunkheader[0]); + chunk->length = SDL_SwapLE32(chunkheader[1]); + chunk->position = nextposition + 8; + + return 0; +} + +static int WaveReadPartialChunkData(SDL_RWops *src, WaveChunk *chunk, size_t length) +{ + WaveFreeChunkData(chunk); + + if (length > chunk->length) { + length = chunk->length; + } + + if (length > 0) { + chunk->data = (Uint8 *)SDL_malloc(length); + if (!chunk->data) { + return SDL_OutOfMemory(); + } + + if (SDL_RWseek(src, chunk->position, RW_SEEK_SET) != chunk->position) { + /* Not sure how we ended up here. Just abort. */ + return -2; + } + + chunk->size = SDL_RWread(src, chunk->data, 1, length); + if (chunk->size != length) { + /* Expected to be handled by the caller. */ + } + } + + return 0; +} + +static int WaveReadChunkData(SDL_RWops *src, WaveChunk *chunk) +{ + return WaveReadPartialChunkData(src, chunk, chunk->length); +} + +typedef struct WaveExtensibleGUID +{ + Uint16 encoding; + Uint8 guid[16]; +} WaveExtensibleGUID; + +/* Some of the GUIDs that are used by WAVEFORMATEXTENSIBLE. */ +#define WAVE_FORMATTAG_GUID(tag) \ + { \ + (tag) & 0xff, (tag) >> 8, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113 \ + } +static WaveExtensibleGUID extensible_guids[] = { + { PCM_CODE, WAVE_FORMATTAG_GUID(PCM_CODE) }, + { MS_ADPCM_CODE, WAVE_FORMATTAG_GUID(MS_ADPCM_CODE) }, + { IEEE_FLOAT_CODE, WAVE_FORMATTAG_GUID(IEEE_FLOAT_CODE) }, + { ALAW_CODE, WAVE_FORMATTAG_GUID(ALAW_CODE) }, + { MULAW_CODE, WAVE_FORMATTAG_GUID(MULAW_CODE) }, + { IMA_ADPCM_CODE, WAVE_FORMATTAG_GUID(IMA_ADPCM_CODE) } +}; + +static Uint16 WaveGetFormatGUIDEncoding(WaveFormat *format) +{ + size_t i; + for (i = 0; i < SDL_arraysize(extensible_guids); i++) { + if (SDL_memcmp(format->subformat, extensible_guids[i].guid, 16) == 0) { + return extensible_guids[i].encoding; + } + } + return UNKNOWN_CODE; +} + +static int WaveReadFormat(WaveFile *file) +{ + WaveChunk *chunk = &file->chunk; + WaveFormat *format = &file->format; + SDL_RWops *fmtsrc; + size_t fmtlen = chunk->size; + + if (fmtlen > SDL_MAX_SINT32) { + /* Limit given by SDL_RWFromConstMem. */ + return SDL_SetError("Data of WAVE fmt chunk too big"); + } + fmtsrc = SDL_RWFromConstMem(chunk->data, (int)chunk->size); + if (!fmtsrc) { + return SDL_OutOfMemory(); + } + + format->formattag = SDL_ReadLE16(fmtsrc); + format->encoding = format->formattag; + format->channels = SDL_ReadLE16(fmtsrc); + format->frequency = SDL_ReadLE32(fmtsrc); + format->byterate = SDL_ReadLE32(fmtsrc); + format->blockalign = SDL_ReadLE16(fmtsrc); + + /* This is PCM specific in the first version of the specification. */ + if (fmtlen >= 16) { + format->bitspersample = SDL_ReadLE16(fmtsrc); + } else if (format->encoding == PCM_CODE) { + SDL_RWclose(fmtsrc); + return SDL_SetError("Missing wBitsPerSample field in WAVE fmt chunk"); + } + + /* The earlier versions also don't have this field. */ + if (fmtlen >= 18) { + format->extsize = SDL_ReadLE16(fmtsrc); + } + + if (format->formattag == EXTENSIBLE_CODE) { + /* note that this ignores channel masks, smaller valid bit counts + * inside a larger container, and most subtypes. This is just enough + * to get things that didn't really _need_ WAVE_FORMAT_EXTENSIBLE + * to be useful working when they use this format flag. + */ + + /* Extensible header must be at least 22 bytes. */ + if (fmtlen < 40 || format->extsize < 22) { + SDL_RWclose(fmtsrc); + return SDL_SetError("Extensible WAVE header too small"); + } + + format->validsamplebits = SDL_ReadLE16(fmtsrc); + format->samplesperblock = format->validsamplebits; + format->channelmask = SDL_ReadLE32(fmtsrc); + SDL_RWread(fmtsrc, format->subformat, 1, 16); + format->encoding = WaveGetFormatGUIDEncoding(format); + } + + SDL_RWclose(fmtsrc); + + return 0; +} + +static int WaveCheckFormat(WaveFile *file, size_t datalength) +{ + WaveFormat *format = &file->format; + + /* Check for some obvious issues. */ + + if (format->channels == 0) { + return SDL_SetError("Invalid number of channels"); + } else if (format->channels > 255) { + /* Limit given by SDL_AudioSpec.channels. */ + return SDL_SetError("Number of channels exceeds limit of 255"); + } + + if (format->frequency == 0) { + return SDL_SetError("Invalid sample rate"); + } else if (format->frequency > INT_MAX) { + /* Limit given by SDL_AudioSpec.freq. */ + return SDL_SetError("Sample rate exceeds limit of %d", INT_MAX); + } + + /* Reject invalid fact chunks in strict mode. */ + if (file->facthint == FactStrict && file->fact.status == -1) { + return SDL_SetError("Invalid fact chunk in WAVE file"); + } + + /* Check for issues common to all encodings. Some unsupported formats set + * the bits per sample to zero. These fall through to the 'unsupported + * format' error. + */ + switch (format->encoding) { + case IEEE_FLOAT_CODE: + case ALAW_CODE: + case MULAW_CODE: + case MS_ADPCM_CODE: + case IMA_ADPCM_CODE: + /* These formats require a fact chunk. */ + if (file->facthint == FactStrict && file->fact.status <= 0) { + return SDL_SetError("Missing fact chunk in WAVE file"); + } + SDL_FALLTHROUGH; + case PCM_CODE: + /* All supported formats require a non-zero bit depth. */ + if (file->chunk.size < 16) { + return SDL_SetError("Missing wBitsPerSample field in WAVE fmt chunk"); + } else if (format->bitspersample == 0) { + return SDL_SetError("Invalid bits per sample"); + } + + /* All supported formats must have a proper block size. */ + if (format->blockalign == 0) { + format->blockalign = 1; /* force it to 1 if it was unset. */ + } + + /* If the fact chunk is valid and the appropriate hint is set, the + * decoders will use the number of sample frames from the fact chunk. + */ + if (file->fact.status == 1) { + WaveFactChunkHint hint = file->facthint; + Uint32 samples = file->fact.samplelength; + if (hint == FactTruncate || hint == FactStrict || (hint == FactIgnoreZero && samples > 0)) { + file->fact.status = 2; + } + } + } + + /* Check the format for encoding specific issues and initialize decoders. */ + switch (format->encoding) { + case PCM_CODE: + case IEEE_FLOAT_CODE: + if (PCM_Init(file, datalength) < 0) { + return -1; + } + break; + case ALAW_CODE: + case MULAW_CODE: + if (LAW_Init(file, datalength) < 0) { + return -1; + } + break; + case MS_ADPCM_CODE: + if (MS_ADPCM_Init(file, datalength) < 0) { + return -1; + } + break; + case IMA_ADPCM_CODE: + if (IMA_ADPCM_Init(file, datalength) < 0) { + return -1; + } + break; + case MPEG_CODE: + case MPEGLAYER3_CODE: + return SDL_SetError("MPEG formats not supported"); + default: + if (format->formattag == EXTENSIBLE_CODE) { + const char *errstr = "Unknown WAVE format GUID: %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x"; + const Uint8 *g = format->subformat; + const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24); + const Uint32 g2 = g[4] | ((Uint32)g[5] << 8); + const Uint32 g3 = g[6] | ((Uint32)g[7] << 8); + return SDL_SetError(errstr, g1, g2, g3, g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]); + } + return SDL_SetError("Unknown WAVE format tag: 0x%04x", (unsigned int)format->encoding); + } + + return 0; +} + +static int WaveLoad(SDL_RWops *src, WaveFile *file, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len) +{ + int result; + Uint32 chunkcount = 0; + Uint32 chunkcountlimit = 10000; + char *envchunkcountlimit; + Sint64 RIFFstart, RIFFend, lastchunkpos; + SDL_bool RIFFlengthknown = SDL_FALSE; + WaveFormat *format = &file->format; + WaveChunk *chunk = &file->chunk; + WaveChunk RIFFchunk; + WaveChunk fmtchunk; + WaveChunk datachunk; + + SDL_zero(RIFFchunk); + SDL_zero(fmtchunk); + SDL_zero(datachunk); + + envchunkcountlimit = SDL_getenv("SDL_WAVE_CHUNK_LIMIT"); + if (envchunkcountlimit) { + unsigned int count; + if (SDL_sscanf(envchunkcountlimit, "%u", &count) == 1) { + chunkcountlimit = count <= SDL_MAX_UINT32 ? count : SDL_MAX_UINT32; + } + } + + RIFFstart = SDL_RWtell(src); + if (RIFFstart < 0) { + return SDL_SetError("Could not seek in file"); + } + + RIFFchunk.position = RIFFstart; + if (WaveNextChunk(src, &RIFFchunk) < 0) { + return SDL_SetError("Could not read RIFF header"); + } + + /* Check main WAVE file identifiers. */ + if (RIFFchunk.fourcc == RIFF) { + Uint32 formtype; + /* Read the form type. "WAVE" expected. */ + if (SDL_RWread(src, &formtype, sizeof(Uint32), 1) != 1) { + return SDL_SetError("Could not read RIFF form type"); + } else if (SDL_SwapLE32(formtype) != WAVE) { + return SDL_SetError("RIFF form type is not WAVE (not a Waveform file)"); + } + } else if (RIFFchunk.fourcc == WAVE) { + /* RIFF chunk missing or skipped. Length unknown. */ + RIFFchunk.position = 0; + RIFFchunk.length = 0; + } else { + return SDL_SetError("Could not find RIFF or WAVE identifiers (not a Waveform file)"); + } + + /* The 4-byte form type is immediately followed by the first chunk.*/ + chunk->position = RIFFchunk.position + 4; + + /* Use the RIFF chunk size to limit the search for the chunks. This is not + * always reliable and the hint can be used to tune the behavior. By + * default, it will never search past 4 GiB. + */ + switch (file->riffhint) { + case RiffSizeIgnore: + RIFFend = RIFFchunk.position + SDL_MAX_UINT32; + break; + default: + case RiffSizeIgnoreZero: + if (RIFFchunk.length == 0) { + RIFFend = RIFFchunk.position + SDL_MAX_UINT32; + break; + } + SDL_FALLTHROUGH; + case RiffSizeForce: + RIFFend = RIFFchunk.position + RIFFchunk.length; + RIFFlengthknown = SDL_TRUE; + break; + case RiffSizeMaximum: + RIFFend = SDL_MAX_SINT64; + break; + } + + /* Step through all chunks and save information on the fmt, data, and fact + * chunks. Ignore the chunks we don't know as per specification. This + * currently also ignores cue, list, and slnt chunks. + */ + while ((Uint64)RIFFend > (Uint64)chunk->position + chunk->length + (chunk->length & 1)) { + /* Abort after too many chunks or else corrupt files may waste time. */ + if (chunkcount++ >= chunkcountlimit) { + return SDL_SetError("Chunk count in WAVE file exceeds limit of %" SDL_PRIu32, chunkcountlimit); + } + + result = WaveNextChunk(src, chunk); + if (result == -1) { + /* Unexpected EOF. Corrupt file or I/O issues. */ + if (file->trunchint == TruncVeryStrict) { + return SDL_SetError("Unexpected end of WAVE file"); + } + /* Let the checks after this loop sort this issue out. */ + break; + } else if (result == -2) { + return SDL_SetError("Could not seek to WAVE chunk header"); + } + + if (chunk->fourcc == FMT) { + if (fmtchunk.fourcc == FMT) { + /* Multiple fmt chunks. Ignore or error? */ + } else { + /* The fmt chunk must occur before the data chunk. */ + if (datachunk.fourcc == DATA) { + return SDL_SetError("fmt chunk after data chunk in WAVE file"); + } + fmtchunk = *chunk; + } + } else if (chunk->fourcc == DATA) { + /* Only use the first data chunk. Handling the wavl list madness + * may require a different approach. + */ + if (datachunk.fourcc != DATA) { + datachunk = *chunk; + } + } else if (chunk->fourcc == FACT) { + /* The fact chunk data must be at least 4 bytes for the + * dwSampleLength field. Ignore all fact chunks after the first one. + */ + if (file->fact.status == 0) { + if (chunk->length < 4) { + file->fact.status = -1; + } else { + /* Let's use src directly, it's just too convenient. */ + Sint64 position = SDL_RWseek(src, chunk->position, RW_SEEK_SET); + Uint32 samplelength; + if (position == chunk->position && SDL_RWread(src, &samplelength, sizeof(Uint32), 1) == 1) { + file->fact.status = 1; + file->fact.samplelength = SDL_SwapLE32(samplelength); + } else { + file->fact.status = -1; + } + } + } + } + + /* Go through all chunks in verystrict mode or stop the search early if + * all required chunks were found. + */ + if (file->trunchint == TruncVeryStrict) { + if ((Uint64)RIFFend < (Uint64)chunk->position + chunk->length) { + return SDL_SetError("RIFF size truncates chunk"); + } + } else if (fmtchunk.fourcc == FMT && datachunk.fourcc == DATA) { + if (file->fact.status == 1 || file->facthint == FactIgnore || file->facthint == FactNoHint) { + break; + } + } + } + + /* Save the position after the last chunk. This position will be used if the + * RIFF length is unknown. + */ + lastchunkpos = chunk->position + chunk->length; + + /* The fmt chunk is mandatory. */ + if (fmtchunk.fourcc != FMT) { + return SDL_SetError("Missing fmt chunk in WAVE file"); + } + /* A data chunk must be present. */ + if (datachunk.fourcc != DATA) { + return SDL_SetError("Missing data chunk in WAVE file"); + } + /* Check if the last chunk has all of its data in verystrict mode. */ + if (file->trunchint == TruncVeryStrict) { + /* data chunk is handled later. */ + if (chunk->fourcc != DATA && chunk->length > 0) { + Uint8 tmp; + Uint64 position = (Uint64)chunk->position + chunk->length - 1; + if (position > SDL_MAX_SINT64 || SDL_RWseek(src, (Sint64)position, RW_SEEK_SET) != (Sint64)position) { + return SDL_SetError("Could not seek to WAVE chunk data"); + } else if (SDL_RWread(src, &tmp, 1, 1) != 1) { + return SDL_SetError("RIFF size truncates chunk"); + } + } + } + + /* Process fmt chunk. */ + *chunk = fmtchunk; + + /* No need to read more than 1046 bytes of the fmt chunk data with the + * formats that are currently supported. (1046 because of MS ADPCM coefficients) + */ + if (WaveReadPartialChunkData(src, chunk, 1046) < 0) { + return SDL_SetError("Could not read data of WAVE fmt chunk"); + } + + /* The fmt chunk data must be at least 14 bytes to include all common fields. + * It usually is 16 and larger depending on the header and encoding. + */ + if (chunk->length < 14) { + return SDL_SetError("Invalid WAVE fmt chunk length (too small)"); + } else if (chunk->size < 14) { + return SDL_SetError("Could not read data of WAVE fmt chunk"); + } else if (WaveReadFormat(file) < 0) { + return -1; + } else if (WaveCheckFormat(file, (size_t)datachunk.length) < 0) { + return -1; + } + +#ifdef SDL_WAVE_DEBUG_LOG_FORMAT + WaveDebugLogFormat(file); +#endif +#ifdef SDL_WAVE_DEBUG_DUMP_FORMAT + WaveDebugDumpFormat(file, RIFFchunk.length, fmtchunk.length, datachunk.length); +#endif + + WaveFreeChunkData(chunk); + + /* Process data chunk. */ + *chunk = datachunk; + + if (chunk->length > 0) { + result = WaveReadChunkData(src, chunk); + if (result == -1) { + return -1; + } else if (result == -2) { + return SDL_SetError("Could not seek data of WAVE data chunk"); + } + } + + if (chunk->length != chunk->size) { + /* I/O issues or corrupt file. */ + if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { + return SDL_SetError("Could not read data of WAVE data chunk"); + } + /* The decoders handle this truncation. */ + } + + /* Decode or convert the data if necessary. */ + switch (format->encoding) { + case PCM_CODE: + case IEEE_FLOAT_CODE: + if (PCM_Decode(file, audio_buf, audio_len) < 0) { + return -1; + } + break; + case ALAW_CODE: + case MULAW_CODE: + if (LAW_Decode(file, audio_buf, audio_len) < 0) { + return -1; + } + break; + case MS_ADPCM_CODE: + if (MS_ADPCM_Decode(file, audio_buf, audio_len) < 0) { + return -1; + } + break; + case IMA_ADPCM_CODE: + if (IMA_ADPCM_Decode(file, audio_buf, audio_len) < 0) { + return -1; + } + break; + } + + /* Setting up the SDL_AudioSpec. All unsupported formats were filtered out + * by checks earlier in this function. + */ + SDL_zerop(spec); + spec->freq = format->frequency; + spec->channels = (Uint8)format->channels; + spec->samples = 4096; /* Good default buffer size */ + + switch (format->encoding) { + case MS_ADPCM_CODE: + case IMA_ADPCM_CODE: + case ALAW_CODE: + case MULAW_CODE: + /* These can be easily stored in the byte order of the system. */ + spec->format = AUDIO_S16SYS; + break; + case IEEE_FLOAT_CODE: + spec->format = AUDIO_F32LSB; + break; + case PCM_CODE: + switch (format->bitspersample) { + case 8: + spec->format = AUDIO_U8; + break; + case 16: + spec->format = AUDIO_S16LSB; + break; + case 24: /* Has been shifted to 32 bits. */ + case 32: + spec->format = AUDIO_S32LSB; + break; + default: + /* Just in case something unexpected happened in the checks. */ + return SDL_SetError("Unexpected %u-bit PCM data format", (unsigned int)format->bitspersample); + } + break; + } + + spec->silence = SDL_SilenceValueForFormat(spec->format); + + /* Report the end position back to the cleanup code. */ + if (RIFFlengthknown) { + chunk->position = RIFFend; + } else { + chunk->position = lastchunkpos; + } + + return 0; +} + +SDL_AudioSpec *SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len) +{ + int result; + WaveFile file; + + SDL_zero(file); + + /* Make sure we are passed a valid data source */ + if (!src) { + /* Error may come from RWops. */ + return NULL; + } else if (!spec) { + SDL_InvalidParamError("spec"); + return NULL; + } else if (!audio_buf) { + SDL_InvalidParamError("audio_buf"); + return NULL; + } else if (!audio_len) { + SDL_InvalidParamError("audio_len"); + return NULL; + } + + *audio_buf = NULL; + *audio_len = 0; + + file.riffhint = WaveGetRiffSizeHint(); + file.trunchint = WaveGetTruncationHint(); + file.facthint = WaveGetFactChunkHint(); + + result = WaveLoad(src, &file, spec, audio_buf, audio_len); + if (result < 0) { + SDL_free(*audio_buf); + spec = NULL; + audio_buf = NULL; + audio_len = 0; + } + + /* Cleanup */ + if (freesrc) { + SDL_RWclose(src); + } else { + SDL_RWseek(src, file.chunk.position, RW_SEEK_SET); + } + WaveFreeChunkData(&file.chunk); + SDL_free(file.decoderdata); + + return spec; +} + +/* Since the WAV memory is allocated in the shared library, it must also + be freed here. (Necessary under Win32, VC++) + */ +void SDL_FreeWAV(Uint8 *audio_buf) +{ + SDL_free(audio_buf); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/SDL_wave.h b/third_party/SDL2/src/audio/SDL_wave.h new file mode 100644 index 00000000000..b0e0e68aca4 --- /dev/null +++ b/third_party/SDL2/src/audio/SDL_wave.h @@ -0,0 +1,153 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../SDL_internal.h" + +/* RIFF WAVE files are little-endian */ + +/*******************************************/ +/* Define values for Microsoft WAVE format */ +/*******************************************/ +/* FOURCC */ +#define RIFF 0x46464952 /* "RIFF" */ +#define WAVE 0x45564157 /* "WAVE" */ +#define FACT 0x74636166 /* "fact" */ +#define LIST 0x5453494c /* "LIST" */ +#define BEXT 0x74786562 /* "bext" */ +#define JUNK 0x4B4E554A /* "JUNK" */ +#define FMT 0x20746D66 /* "fmt " */ +#define DATA 0x61746164 /* "data" */ +/* Format tags */ +#define UNKNOWN_CODE 0x0000 +#define PCM_CODE 0x0001 +#define MS_ADPCM_CODE 0x0002 +#define IEEE_FLOAT_CODE 0x0003 +#define ALAW_CODE 0x0006 +#define MULAW_CODE 0x0007 +#define IMA_ADPCM_CODE 0x0011 +#define MPEG_CODE 0x0050 +#define MPEGLAYER3_CODE 0x0055 +#define EXTENSIBLE_CODE 0xFFFE + +/* Stores the WAVE format information. */ +typedef struct WaveFormat +{ + Uint16 formattag; /* Raw value of the first field in the fmt chunk data. */ + Uint16 encoding; /* Actual encoding, possibly from the extensible header. */ + Uint16 channels; /* Number of channels. */ + Uint32 frequency; /* Sampling rate in Hz. */ + Uint32 byterate; /* Average bytes per second. */ + Uint16 blockalign; /* Bytes per block. */ + Uint16 bitspersample; /* Currently supported are 8, 16, 24, 32, and 4 for ADPCM. */ + + /* Extra information size. Number of extra bytes starting at byte 18 in the + * fmt chunk data. This is at least 22 for the extensible header. + */ + Uint16 extsize; + + /* Extensible WAVE header fields */ + Uint16 validsamplebits; + Uint32 samplesperblock; /* For compressed formats. Can be zero. Actually 16 bits in the header. */ + Uint32 channelmask; + Uint8 subformat[16]; /* A format GUID. */ +} WaveFormat; + +/* Stores information on the fact chunk. */ +typedef struct WaveFact +{ + /* Represents the state of the fact chunk in the WAVE file. + * Set to -1 if the fact chunk is invalid. + * Set to 0 if the fact chunk is not present + * Set to 1 if the fact chunk is present and valid. + * Set to 2 if samplelength is going to be used as the number of sample frames. + */ + Sint32 status; + + /* Version 1 of the RIFF specification calls the field in the fact chunk + * dwFileSize. The Standards Update then calls it dwSampleLength and specifies + * that it is 'the length of the data in samples'. WAVE files from Windows + * with this chunk have it set to the samples per channel (sample frames). + * This is useful to truncate compressed audio to a specific sample count + * because a compressed block is usually decoded to a fixed number of + * sample frames. + */ + Uint32 samplelength; /* Raw sample length value from the fact chunk. */ +} WaveFact; + +/* Generic struct for the chunks in the WAVE file. */ +typedef struct WaveChunk +{ + Uint32 fourcc; /* FOURCC of the chunk. */ + Uint32 length; /* Size of the chunk data. */ + Sint64 position; /* Position of the data in the stream. */ + Uint8 *data; /* When allocated, this points to the chunk data. length is used for the memory allocation size. */ + size_t size; /* Number of bytes in data that could be read from the stream. Can be smaller than length. */ +} WaveChunk; + +/* Controls how the size of the RIFF chunk affects the loading of a WAVE file. */ +typedef enum WaveRiffSizeHint +{ + RiffSizeNoHint, + RiffSizeForce, + RiffSizeIgnoreZero, + RiffSizeIgnore, + RiffSizeMaximum +} WaveRiffSizeHint; + +/* Controls how a truncated WAVE file is handled. */ +typedef enum WaveTruncationHint +{ + TruncNoHint, + TruncVeryStrict, + TruncStrict, + TruncDropFrame, + TruncDropBlock +} WaveTruncationHint; + +/* Controls how the fact chunk affects the loading of a WAVE file. */ +typedef enum WaveFactChunkHint +{ + FactNoHint, + FactTruncate, + FactStrict, + FactIgnoreZero, + FactIgnore +} WaveFactChunkHint; + +typedef struct WaveFile +{ + WaveChunk chunk; + WaveFormat format; + WaveFact fact; + + /* Number of sample frames that will be decoded. Calculated either with the + * size of the data chunk or, if the appropriate hint is enabled, with the + * sample length value from the fact chunk. + */ + Sint64 sampleframes; + + void *decoderdata; /* Some decoders require extra data for a state. */ + + WaveRiffSizeHint riffhint; + WaveTruncationHint trunchint; + WaveFactChunkHint facthint; +} WaveFile; + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/aaudio/SDL_aaudio.c b/third_party/SDL2/src/audio/aaudio/SDL_aaudio.c new file mode 100644 index 00000000000..93bcaf3f78c --- /dev/null +++ b/third_party/SDL2/src/audio/aaudio/SDL_aaudio.c @@ -0,0 +1,528 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_AAUDIO + +#include "SDL_audio.h" +#include "SDL_loadso.h" +#include "../SDL_audio_c.h" +#include "../../core/android/SDL_android.h" +#include "SDL_aaudio.h" + +/* Debug */ +#if 0 +#define LOGI(...) SDL_Log(__VA_ARGS__); +#else +#define LOGI(...) +#endif + +typedef struct AAUDIO_Data +{ + AAudioStreamBuilder *builder; + void *handle; +#define SDL_PROC(ret, func, params) ret (*func) params; +#include "SDL_aaudiofuncs.h" +#undef SDL_PROC +} AAUDIO_Data; +static AAUDIO_Data ctx; + +static SDL_AudioDevice *audioDevice = NULL; +static SDL_AudioDevice *captureDevice = NULL; + +static int aaudio_LoadFunctions(AAUDIO_Data *data) +{ +#define SDL_PROC(ret, func, params) \ + do { \ + data->func = SDL_LoadFunction(data->handle, #func); \ + if (!data->func) { \ + return SDL_SetError("Couldn't load AAUDIO function %s: %s", #func, SDL_GetError()); \ + } \ + } while (0); +#include "SDL_aaudiofuncs.h" +#undef SDL_PROC + return 0; +} + +void aaudio_errorCallback(AAudioStream *stream, void *userData, aaudio_result_t error); +void aaudio_errorCallback(AAudioStream *stream, void *userData, aaudio_result_t error) +{ + LOGI("SDL aaudio_errorCallback: %d - %s", error, ctx.AAudio_convertResultToText(error)); +} + +#define LIB_AAUDIO_SO "libaaudio.so" + +static int aaudio_OpenDevice(_THIS, const char *devname) +{ + struct SDL_PrivateAudioData *private; + SDL_bool iscapture = this->iscapture; + aaudio_result_t res; + LOGI(__func__); + + SDL_assert((captureDevice == NULL) || !iscapture); + SDL_assert((audioDevice == NULL) || iscapture); + + if (iscapture) { + if (!Android_JNI_RequestPermission("android.permission.RECORD_AUDIO")) { + LOGI("This app doesn't have RECORD_AUDIO permission"); + return SDL_SetError("This app doesn't have RECORD_AUDIO permission"); + } + } + + if (iscapture) { + captureDevice = this; + } else { + audioDevice = this; + } + + this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + private = this->hidden; + + ctx.AAudioStreamBuilder_setSampleRate(ctx.builder, this->spec.freq); + ctx.AAudioStreamBuilder_setChannelCount(ctx.builder, this->spec.channels); + if(devname) { + private->devid = SDL_atoi(devname); + LOGI("Opening device id %d", private->devid); + ctx.AAudioStreamBuilder_setDeviceId(ctx.builder, private->devid); + } + { + const aaudio_direction_t direction = (iscapture ? AAUDIO_DIRECTION_INPUT : AAUDIO_DIRECTION_OUTPUT); + ctx.AAudioStreamBuilder_setDirection(ctx.builder, direction); + } + { + const aaudio_format_t format = (this->spec.format == AUDIO_S16SYS) ? AAUDIO_FORMAT_PCM_I16 : AAUDIO_FORMAT_PCM_FLOAT; + ctx.AAudioStreamBuilder_setFormat(ctx.builder, format); + } + + ctx.AAudioStreamBuilder_setErrorCallback(ctx.builder, aaudio_errorCallback, private); + + LOGI("AAudio Try to open %u hz %u bit chan %u %s samples %u", + this->spec.freq, SDL_AUDIO_BITSIZE(this->spec.format), + this->spec.channels, (this->spec.format & 0x1000) ? "BE" : "LE", this->spec.samples); + + res = ctx.AAudioStreamBuilder_openStream(ctx.builder, &private->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStreamBuilder_openStream %d", res); + return SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + } + + this->spec.freq = ctx.AAudioStream_getSampleRate(private->stream); + this->spec.channels = ctx.AAudioStream_getChannelCount(private->stream); + { + aaudio_format_t fmt = ctx.AAudioStream_getFormat(private->stream); + if (fmt == AAUDIO_FORMAT_PCM_I16) { + this->spec.format = AUDIO_S16SYS; + } else if (fmt == AAUDIO_FORMAT_PCM_FLOAT) { + this->spec.format = AUDIO_F32SYS; + } + } + + LOGI("AAudio Try to open %u hz %u bit chan %u %s samples %u", + this->spec.freq, SDL_AUDIO_BITSIZE(this->spec.format), + this->spec.channels, (this->spec.format & 0x1000) ? "BE" : "LE", this->spec.samples); + + SDL_CalculateAudioSpec(&this->spec); + + /* Allocate mixing buffer */ + if (!iscapture) { + private->mixlen = this->spec.size; + private->mixbuf = (Uint8 *)SDL_malloc(private->mixlen); + if (!private->mixbuf) { + return SDL_OutOfMemory(); + } + SDL_memset(private->mixbuf, this->spec.silence, this->spec.size); + } + + private->frame_size = this->spec.channels * (SDL_AUDIO_BITSIZE(this->spec.format) / 8); + + res = ctx.AAudioStream_requestStart(private->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStream_requestStart %d iscapture:%d", res, iscapture); + return SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + } + + LOGI("SDL AAudioStream_requestStart OK"); + return 0; +} + +static void aaudio_CloseDevice(_THIS) +{ + struct SDL_PrivateAudioData *private = this->hidden; + aaudio_result_t res; + LOGI(__func__); + + if (private->stream) { + res = ctx.AAudioStream_requestStop(private->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStream_requestStop %d", res); + SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + return; + } + + res = ctx.AAudioStream_close(private->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStreamBuilder_delete %d", res); + SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + return; + } + } + + if (this->iscapture) { + SDL_assert(captureDevice == this); + captureDevice = NULL; + } else { + SDL_assert(audioDevice == this); + audioDevice = NULL; + } + + SDL_free(this->hidden->mixbuf); + SDL_free(this->hidden); +} + +static Uint8 *aaudio_GetDeviceBuf(_THIS) +{ + struct SDL_PrivateAudioData *private = this->hidden; + return private->mixbuf; +} + +/* Try to reestablish an AAudioStream. + + This needs to get a stream with the same format as the previous one, + even if this means AAudio needs to handle a conversion it didn't when + we initially opened the device. If we can't get that, we are forced + to give up here. + + (This is more robust in SDL3, which is designed to handle + abrupt format changes.) +*/ +static int RebuildAAudioStream(SDL_AudioDevice *device) +{ + struct SDL_PrivateAudioData *hidden = device->hidden; + const SDL_bool iscapture = device->iscapture; + aaudio_result_t res; + + ctx.AAudioStreamBuilder_setSampleRate(ctx.builder, device->spec.freq); + ctx.AAudioStreamBuilder_setChannelCount(ctx.builder, device->spec.channels); + if(hidden->devid) { + LOGI("Reopening device id %d", hidden->devid); + ctx.AAudioStreamBuilder_setDeviceId(ctx.builder, hidden->devid); + } + { + const aaudio_direction_t direction = (iscapture ? AAUDIO_DIRECTION_INPUT : AAUDIO_DIRECTION_OUTPUT); + ctx.AAudioStreamBuilder_setDirection(ctx.builder, direction); + } + { + const aaudio_format_t format = (device->spec.format == AUDIO_S16SYS) ? AAUDIO_FORMAT_PCM_I16 : AAUDIO_FORMAT_PCM_FLOAT; + ctx.AAudioStreamBuilder_setFormat(ctx.builder, format); + } + + ctx.AAudioStreamBuilder_setErrorCallback(ctx.builder, aaudio_errorCallback, hidden); + + LOGI("AAudio Try to reopen %u hz %u bit chan %u %s samples %u", + device->spec.freq, SDL_AUDIO_BITSIZE(device->spec.format), + device->spec.channels, (device->spec.format & 0x1000) ? "BE" : "LE", device->spec.samples); + + res = ctx.AAudioStreamBuilder_openStream(ctx.builder, &hidden->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStreamBuilder_openStream %d", res); + return SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + } + + { + const aaudio_format_t fmt = ctx.AAudioStream_getFormat(hidden->stream); + SDL_AudioFormat sdlfmt = (SDL_AudioFormat) 0; + if (fmt == AAUDIO_FORMAT_PCM_I16) { + sdlfmt = AUDIO_S16SYS; + } else if (fmt == AAUDIO_FORMAT_PCM_FLOAT) { + sdlfmt = AUDIO_F32SYS; + } + + /* We handle this better in SDL3, but this _needs_ to match the previous stream for SDL2. */ + if ( (device->spec.freq != ctx.AAudioStream_getSampleRate(hidden->stream)) || + (device->spec.channels != ctx.AAudioStream_getChannelCount(hidden->stream)) || + (device->spec.format != sdlfmt) ) { + LOGI("Didn't get an identical spec from AAudioStream during reopen!"); + ctx.AAudioStream_close(hidden->stream); + hidden->stream = NULL; + return SDL_SetError("Didn't get an identical spec from AAudioStream during reopen!"); + } + } + + res = ctx.AAudioStream_requestStart(hidden->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStream_requestStart %d iscapture:%d", res, iscapture); + return SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + } + + return 0; +} + +static int RecoverAAudioDevice(SDL_AudioDevice *device) +{ + struct SDL_PrivateAudioData *hidden = device->hidden; + AAudioStream *stream = hidden->stream; + + /* attempt to build a new stream, in case there's a new default device. */ + hidden->stream = NULL; + ctx.AAudioStream_requestStop(stream); + ctx.AAudioStream_close(stream); + + if (RebuildAAudioStream(device) < 0) { + return -1; // oh well, we tried. + } + + return 0; +} + + +static void aaudio_PlayDevice(_THIS) +{ + struct SDL_PrivateAudioData *private = this->hidden; + aaudio_result_t res; + int64_t timeoutNanoseconds = 1 * 1000 * 1000; /* 8 ms */ + res = ctx.AAudioStream_write(private->stream, private->mixbuf, private->mixlen / private->frame_size, timeoutNanoseconds); + if (res < 0) { + LOGI("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + if (RecoverAAudioDevice(this) < 0) { + return; /* oh well, we went down hard. */ + } + } else { + LOGI("SDL AAudio play: %d frames, wanted:%d frames", (int)res, private->mixlen / private->frame_size); + } + +#if 0 + /* Log under-run count */ + { + static int prev = 0; + int32_t cnt = ctx.AAudioStream_getXRunCount(private->stream); + if (cnt != prev) { + SDL_Log("AAudio underrun: %d - total: %d", cnt - prev, cnt); + prev = cnt; + } + } +#endif +} + +static int aaudio_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + struct SDL_PrivateAudioData *private = this->hidden; + aaudio_result_t res; + int64_t timeoutNanoseconds = 8 * 1000 * 1000; /* 8 ms */ + res = ctx.AAudioStream_read(private->stream, buffer, buflen / private->frame_size, timeoutNanoseconds); + if (res < 0) { + LOGI("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + return -1; + } + LOGI("SDL AAudio capture:%d frames, wanted:%d frames", (int)res, buflen / private->frame_size); + return res * private->frame_size; +} + +static void aaudio_Deinitialize(void) +{ + LOGI(__func__); + if (ctx.handle) { + if (ctx.builder) { + aaudio_result_t res; + res = ctx.AAudioStreamBuilder_delete(ctx.builder); + if (res != AAUDIO_OK) { + SDL_SetError("Failed AAudioStreamBuilder_delete %s", ctx.AAudio_convertResultToText(res)); + } + } + SDL_UnloadObject(ctx.handle); + } + ctx.handle = NULL; + ctx.builder = NULL; + LOGI("End AAUDIO %s", SDL_GetError()); +} + +static SDL_bool aaudio_Init(SDL_AudioDriverImpl *impl) +{ + aaudio_result_t res; + LOGI(__func__); + + /* AAudio was introduced in Android 8.0, but has reference counting crash issues in that release, + * so don't use it until 8.1. + * + * See https://github.com/google/oboe/issues/40 for more information. + */ + if (SDL_GetAndroidSDKVersion() < 27) { + return SDL_FALSE; + } + + SDL_zero(ctx); + + ctx.handle = SDL_LoadObject(LIB_AAUDIO_SO); + if (!ctx.handle) { + LOGI("SDL couldn't find " LIB_AAUDIO_SO); + goto failure; + } + + if (aaudio_LoadFunctions(&ctx) < 0) { + goto failure; + } + + res = ctx.AAudio_createStreamBuilder(&ctx.builder); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudio_createStreamBuilder %d", res); + goto failure; + } + + if (!ctx.builder) { + LOGI("SDL Failed AAudio_createStreamBuilder - builder NULL"); + goto failure; + } + + impl->DetectDevices = Android_DetectDevices; + impl->Deinitialize = aaudio_Deinitialize; + impl->OpenDevice = aaudio_OpenDevice; + impl->CloseDevice = aaudio_CloseDevice; + impl->PlayDevice = aaudio_PlayDevice; + impl->GetDeviceBuf = aaudio_GetDeviceBuf; + impl->CaptureFromDevice = aaudio_CaptureFromDevice; + impl->AllowsArbitraryDeviceNames = SDL_TRUE; + + /* and the capabilities */ + impl->HasCaptureSupport = SDL_TRUE; + impl->OnlyHasDefaultOutputDevice = SDL_FALSE; + impl->OnlyHasDefaultCaptureDevice = SDL_FALSE; + + /* this audio target is available. */ + LOGI("SDL aaudio_Init OK"); + return SDL_TRUE; + +failure: + if (ctx.handle) { + if (ctx.builder) { + ctx.AAudioStreamBuilder_delete(ctx.builder); + } + SDL_UnloadObject(ctx.handle); + } + ctx.handle = NULL; + ctx.builder = NULL; + return SDL_FALSE; +} + +AudioBootStrap aaudio_bootstrap = { + "AAudio", "AAudio audio driver", aaudio_Init, SDL_FALSE +}; + +/* Pause (block) all non already paused audio devices by taking their mixer lock */ +void aaudio_PauseDevices(void) +{ + /* TODO: Handle multiple devices? */ + struct SDL_PrivateAudioData *private; + if (audioDevice && audioDevice->hidden) { + SDL_LockMutex(audioDevice->mixer_lock); + private = (struct SDL_PrivateAudioData *)audioDevice->hidden; + if (private->stream) { + aaudio_result_t res = ctx.AAudioStream_requestPause(private->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStream_requestPause %d", res); + SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + } + } + } + + if (captureDevice && captureDevice->hidden) { + SDL_LockMutex(captureDevice->mixer_lock); + private = (struct SDL_PrivateAudioData *)captureDevice->hidden; + if (private->stream) { + /* Pause() isn't implemented for 'capture', use Stop() */ + aaudio_result_t res = ctx.AAudioStream_requestStop(private->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStream_requestStop %d", res); + SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + } + } + } +} + +/* Resume (unblock) all non already paused audio devices by releasing their mixer lock */ +void aaudio_ResumeDevices(void) +{ + /* TODO: Handle multiple devices? */ + struct SDL_PrivateAudioData *private; + if (audioDevice && audioDevice->hidden) { + private = (struct SDL_PrivateAudioData *)audioDevice->hidden; + if (private->stream) { + aaudio_result_t res = ctx.AAudioStream_requestStart(private->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStream_requestStart %d", res); + SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + } + } + SDL_UnlockMutex(audioDevice->mixer_lock); + } + + if (captureDevice && captureDevice->hidden) { + private = (struct SDL_PrivateAudioData *)captureDevice->hidden; + if (private->stream) { + aaudio_result_t res = ctx.AAudioStream_requestStart(private->stream); + if (res != AAUDIO_OK) { + LOGI("SDL Failed AAudioStream_requestStart %d", res); + SDL_SetError("%s : %s", __func__, ctx.AAudio_convertResultToText(res)); + } + } + SDL_UnlockMutex(captureDevice->mixer_lock); + } +} + +/* + We can sometimes get into a state where AAudioStream_write() will just block forever until we pause and unpause. + None of the standard state queries indicate any problem in my testing. And the error callback doesn't actually get called. + But, AAudioStream_getTimestamp() does return AAUDIO_ERROR_INVALID_STATE +*/ +SDL_bool aaudio_DetectBrokenPlayState(void) +{ + AAudioStream *stream; + struct SDL_PrivateAudioData *private; + int64_t framePosition, timeNanoseconds; + aaudio_result_t res; + + if (!audioDevice || !audioDevice->hidden) { + return SDL_FALSE; + } + + private = audioDevice->hidden; + stream = private->stream; + if (!stream) { + return SDL_FALSE; + } + + res = ctx.AAudioStream_getTimestamp(stream, CLOCK_MONOTONIC, &framePosition, &timeNanoseconds); + if (res == AAUDIO_ERROR_INVALID_STATE) { + aaudio_stream_state_t currentState = ctx.AAudioStream_getState(stream); + /* AAudioStream_getTimestamp() will also return AAUDIO_ERROR_INVALID_STATE while the stream is still initially starting. But we only care if it silently went invalid while playing. */ + if (currentState == AAUDIO_STREAM_STATE_STARTED) { + LOGI("SDL aaudio_DetectBrokenPlayState: detected invalid audio device state: AAudioStream_getTimestamp result=%d, framePosition=%lld, timeNanoseconds=%lld, getState=%d", (int)res, (long long)framePosition, (long long)timeNanoseconds, (int)currentState); + return SDL_TRUE; + } + } + + return SDL_FALSE; +} + +#endif /* SDL_AUDIO_DRIVER_AAUDIO */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/aaudio/SDL_aaudio.h b/third_party/SDL2/src/audio/aaudio/SDL_aaudio.h new file mode 100644 index 00000000000..b988a5c1ee9 --- /dev/null +++ b/third_party/SDL2/src/audio/aaudio/SDL_aaudio.h @@ -0,0 +1,50 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef _SDL_aaudio_h +#define _SDL_aaudio_h + +#include "../SDL_sysaudio.h" +#include +#include + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + AAudioStream *stream; + + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; + int frame_size; + int devid; +}; + +void aaudio_ResumeDevices(void); +void aaudio_PauseDevices(void); +SDL_bool aaudio_DetectBrokenPlayState(void); + +#endif /* _SDL_aaudio_h */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/aaudio/SDL_aaudiofuncs.h b/third_party/SDL2/src/audio/aaudio/SDL_aaudiofuncs.h new file mode 100644 index 00000000000..c2fff183002 --- /dev/null +++ b/third_party/SDL2/src/audio/aaudio/SDL_aaudiofuncs.h @@ -0,0 +1,79 @@ +/* + Simple DirectMedia Layer + Copyright , (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#define SDL_PROC_UNUSED(ret, func, params) + +SDL_PROC(const char *, AAudio_convertResultToText, (aaudio_result_t returnCode)) +SDL_PROC(const char *, AAudio_convertStreamStateToText, (aaudio_stream_state_t state)) +SDL_PROC(aaudio_result_t, AAudio_createStreamBuilder, (AAudioStreamBuilder * *builder)) +SDL_PROC(void, AAudioStreamBuilder_setDeviceId, (AAudioStreamBuilder * builder, int32_t deviceId)) +SDL_PROC(void, AAudioStreamBuilder_setSampleRate, (AAudioStreamBuilder * builder, int32_t sampleRate)) +SDL_PROC(void, AAudioStreamBuilder_setChannelCount, (AAudioStreamBuilder * builder, int32_t channelCount)) +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSamplesPerFrame, (AAudioStreamBuilder * builder, int32_t samplesPerFrame)) +SDL_PROC(void, AAudioStreamBuilder_setFormat, (AAudioStreamBuilder * builder, aaudio_format_t format)) +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSharingMode, (AAudioStreamBuilder * builder, aaudio_sharing_mode_t sharingMode)) +SDL_PROC(void, AAudioStreamBuilder_setDirection, (AAudioStreamBuilder * builder, aaudio_direction_t direction)) +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setBufferCapacityInFrames, (AAudioStreamBuilder * builder, int32_t numFrames)) +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setPerformanceMode, (AAudioStreamBuilder * builder, aaudio_performance_mode_t mode)) +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setUsage, (AAudioStreamBuilder * builder, aaudio_usage_t usage)) /* API 28 */ +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setContentType, (AAudioStreamBuilder * builder, aaudio_content_type_t contentType)) /* API 28 */ +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setInputPreset, (AAudioStreamBuilder * builder, aaudio_input_preset_t inputPreset)) /* API 28 */ +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setAllowedCapturePolicy, (AAudioStreamBuilder * builder, aaudio_allowed_capture_policy_t capturePolicy)) /* API 29 */ +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setSessionId, (AAudioStreamBuilder * builder, aaudio_session_id_t sessionId)) /* API 28 */ +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setPrivacySensitive, (AAudioStreamBuilder * builder, bool privacySensitive)) /* API 30 */ +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setDataCallback, (AAudioStreamBuilder * builder, AAudioStream_dataCallback callback, void *userData)) +SDL_PROC_UNUSED(void, AAudioStreamBuilder_setFramesPerDataCallback, (AAudioStreamBuilder * builder, int32_t numFrames)) +SDL_PROC(void, AAudioStreamBuilder_setErrorCallback, (AAudioStreamBuilder * builder, AAudioStream_errorCallback callback, void *userData)) +SDL_PROC(aaudio_result_t, AAudioStreamBuilder_openStream, (AAudioStreamBuilder * builder, AAudioStream **stream)) +SDL_PROC(aaudio_result_t, AAudioStreamBuilder_delete, (AAudioStreamBuilder * builder)) +SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_release, (AAudioStream * stream)) /* API 30 */ +SDL_PROC(aaudio_result_t, AAudioStream_close, (AAudioStream * stream)) +SDL_PROC(aaudio_result_t, AAudioStream_requestStart, (AAudioStream * stream)) +SDL_PROC(aaudio_result_t, AAudioStream_requestPause, (AAudioStream * stream)) +SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_requestFlush, (AAudioStream * stream)) +SDL_PROC(aaudio_result_t, AAudioStream_requestStop, (AAudioStream * stream)) +SDL_PROC(aaudio_stream_state_t, AAudioStream_getState, (AAudioStream * stream)) +SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_waitForStateChange, (AAudioStream * stream, aaudio_stream_state_t inputState, aaudio_stream_state_t *nextState, int64_t timeoutNanoseconds)) +SDL_PROC(aaudio_result_t, AAudioStream_read, (AAudioStream * stream, void *buffer, int32_t numFrames, int64_t timeoutNanoseconds)) +SDL_PROC(aaudio_result_t, AAudioStream_write, (AAudioStream * stream, const void *buffer, int32_t numFrames, int64_t timeoutNanoseconds)) +SDL_PROC_UNUSED(aaudio_result_t, AAudioStream_setBufferSizeInFrames, (AAudioStream * stream, int32_t numFrames)) +SDL_PROC_UNUSED(int32_t, AAudioStream_getBufferSizeInFrames, (AAudioStream * stream)) +SDL_PROC_UNUSED(int32_t, AAudioStream_getFramesPerBurst, (AAudioStream * stream)) +SDL_PROC_UNUSED(int32_t, AAudioStream_getBufferCapacityInFrames, (AAudioStream * stream)) +SDL_PROC_UNUSED(int32_t, AAudioStream_getFramesPerDataCallback, (AAudioStream * stream)) +SDL_PROC(int32_t, AAudioStream_getXRunCount, (AAudioStream * stream)) +SDL_PROC(int32_t, AAudioStream_getSampleRate, (AAudioStream * stream)) +SDL_PROC(int32_t, AAudioStream_getChannelCount, (AAudioStream * stream)) +SDL_PROC_UNUSED(int32_t, AAudioStream_getSamplesPerFrame, (AAudioStream * stream)) +SDL_PROC_UNUSED(int32_t, AAudioStream_getDeviceId, (AAudioStream * stream)) +SDL_PROC(aaudio_format_t, AAudioStream_getFormat, (AAudioStream * stream)) +SDL_PROC_UNUSED(aaudio_sharing_mode_t, AAudioStream_getSharingMode, (AAudioStream * stream)) +SDL_PROC_UNUSED(aaudio_performance_mode_t, AAudioStream_getPerformanceMode, (AAudioStream * stream)) +SDL_PROC_UNUSED(aaudio_direction_t, AAudioStream_getDirection, (AAudioStream * stream)) +SDL_PROC_UNUSED(int64_t, AAudioStream_getFramesWritten, (AAudioStream * stream)) +SDL_PROC_UNUSED(int64_t, AAudioStream_getFramesRead, (AAudioStream * stream)) +SDL_PROC_UNUSED(aaudio_session_id_t, AAudioStream_getSessionId, (AAudioStream * stream)) /* API 28 */ +SDL_PROC(aaudio_result_t, AAudioStream_getTimestamp, (AAudioStream * stream, clockid_t clockid, int64_t *framePosition, int64_t *timeNanoseconds)) +SDL_PROC_UNUSED(aaudio_usage_t, AAudioStream_getUsage, (AAudioStream * stream)) /* API 28 */ +SDL_PROC_UNUSED(aaudio_content_type_t, AAudioStream_getContentType, (AAudioStream * stream)) /* API 28 */ +SDL_PROC_UNUSED(aaudio_input_preset_t, AAudioStream_getInputPreset, (AAudioStream * stream)) /* API 28 */ +SDL_PROC_UNUSED(aaudio_allowed_capture_policy_t, AAudioStream_getAllowedCapturePolicy, (AAudioStream * stream)) /* API 29 */ +SDL_PROC_UNUSED(bool, AAudioStream_isPrivacySensitive, (AAudioStream * stream)) /* API 30 */ diff --git a/third_party/SDL2/src/audio/alsa/SDL_alsa_audio.c b/third_party/SDL2/src/audio/alsa/SDL_alsa_audio.c new file mode 100644 index 00000000000..3e0e7acaf98 --- /dev/null +++ b/third_party/SDL2/src/audio/alsa/SDL_alsa_audio.c @@ -0,0 +1,991 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_ALSA + +#ifndef SDL_ALSA_NON_BLOCKING +#define SDL_ALSA_NON_BLOCKING 0 +#endif + +/* without the thread, you will detect devices on startup, but will not get futher hotplug events. But that might be okay. */ +#ifndef SDL_ALSA_HOTPLUG_THREAD +#define SDL_ALSA_HOTPLUG_THREAD 1 +#endif + +/* Allow access to a raw mixing buffer */ + +#include +#include /* For kill() */ +#include + +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_alsa_audio.h" + +#ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC +#include "SDL_loadso.h" +#endif + +static int (*ALSA_snd_pcm_open)(snd_pcm_t **, const char *, snd_pcm_stream_t, int); +static int (*ALSA_snd_pcm_close)(snd_pcm_t *pcm); +static snd_pcm_sframes_t (*ALSA_snd_pcm_writei)(snd_pcm_t *, const void *, snd_pcm_uframes_t); +static snd_pcm_sframes_t (*ALSA_snd_pcm_readi)(snd_pcm_t *, void *, snd_pcm_uframes_t); +static int (*ALSA_snd_pcm_recover)(snd_pcm_t *, int, int); +static int (*ALSA_snd_pcm_prepare)(snd_pcm_t *); +static int (*ALSA_snd_pcm_drain)(snd_pcm_t *); +static const char *(*ALSA_snd_strerror)(int); +static size_t (*ALSA_snd_pcm_hw_params_sizeof)(void); +static size_t (*ALSA_snd_pcm_sw_params_sizeof)(void); +static void (*ALSA_snd_pcm_hw_params_copy)(snd_pcm_hw_params_t *, const snd_pcm_hw_params_t *); +static int (*ALSA_snd_pcm_hw_params_any)(snd_pcm_t *, snd_pcm_hw_params_t *); +static int (*ALSA_snd_pcm_hw_params_set_access)(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_access_t); +static int (*ALSA_snd_pcm_hw_params_set_format)(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_format_t); +static int (*ALSA_snd_pcm_hw_params_set_channels)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int); +static int (*ALSA_snd_pcm_hw_params_get_channels)(const snd_pcm_hw_params_t *, unsigned int *); +static int (*ALSA_snd_pcm_hw_params_set_rate_near)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *); +static int (*ALSA_snd_pcm_hw_params_set_period_size_near)(snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_uframes_t *, int *); +static int (*ALSA_snd_pcm_hw_params_get_period_size)(const snd_pcm_hw_params_t *, snd_pcm_uframes_t *, int *); +static int (*ALSA_snd_pcm_hw_params_set_periods_min)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *); +static int (*ALSA_snd_pcm_hw_params_set_periods_first)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *); +static int (*ALSA_snd_pcm_hw_params_get_periods)(const snd_pcm_hw_params_t *, unsigned int *, int *); +static int (*ALSA_snd_pcm_hw_params_set_buffer_size_near)(snd_pcm_t *pcm, snd_pcm_hw_params_t *, snd_pcm_uframes_t *); +static int (*ALSA_snd_pcm_hw_params_get_buffer_size)(const snd_pcm_hw_params_t *, snd_pcm_uframes_t *); +static int (*ALSA_snd_pcm_hw_params)(snd_pcm_t *, snd_pcm_hw_params_t *); +static int (*ALSA_snd_pcm_sw_params_current)(snd_pcm_t *, + snd_pcm_sw_params_t *); +static int (*ALSA_snd_pcm_sw_params_set_start_threshold)(snd_pcm_t *, snd_pcm_sw_params_t *, snd_pcm_uframes_t); +static int (*ALSA_snd_pcm_sw_params)(snd_pcm_t *, snd_pcm_sw_params_t *); +static int (*ALSA_snd_pcm_nonblock)(snd_pcm_t *, int); +static int (*ALSA_snd_pcm_wait)(snd_pcm_t *, int); +static int (*ALSA_snd_pcm_sw_params_set_avail_min)(snd_pcm_t *, snd_pcm_sw_params_t *, snd_pcm_uframes_t); +static int (*ALSA_snd_pcm_reset)(snd_pcm_t *); +static int (*ALSA_snd_device_name_hint)(int, const char *, void ***); +static char *(*ALSA_snd_device_name_get_hint)(const void *, const char *); +static int (*ALSA_snd_device_name_free_hint)(void **); +static snd_pcm_sframes_t (*ALSA_snd_pcm_avail)(snd_pcm_t *); +#ifdef SND_CHMAP_API_VERSION +static snd_pcm_chmap_t *(*ALSA_snd_pcm_get_chmap)(snd_pcm_t *); +static int (*ALSA_snd_pcm_chmap_print)(const snd_pcm_chmap_t *map, size_t maxlen, char *buf); +#endif + +#ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC +#define snd_pcm_hw_params_sizeof ALSA_snd_pcm_hw_params_sizeof +#define snd_pcm_sw_params_sizeof ALSA_snd_pcm_sw_params_sizeof + +static const char *alsa_library = SDL_AUDIO_DRIVER_ALSA_DYNAMIC; +static void *alsa_handle = NULL; + +static int load_alsa_sym(const char *fn, void **addr) +{ + *addr = SDL_LoadFunction(alsa_handle, fn); + if (!*addr) { + /* Don't call SDL_SetError(): SDL_LoadFunction already did. */ + return 0; + } + + return 1; +} + +/* cast funcs to char* first, to please GCC's strict aliasing rules. */ +#define SDL_ALSA_SYM(x) \ + if (!load_alsa_sym(#x, (void **)(char *)&ALSA_##x)) \ + return -1 +#else +#define SDL_ALSA_SYM(x) ALSA_##x = x +#endif + +static int load_alsa_syms(void) +{ + SDL_ALSA_SYM(snd_pcm_open); + SDL_ALSA_SYM(snd_pcm_close); + SDL_ALSA_SYM(snd_pcm_writei); + SDL_ALSA_SYM(snd_pcm_readi); + SDL_ALSA_SYM(snd_pcm_recover); + SDL_ALSA_SYM(snd_pcm_prepare); + SDL_ALSA_SYM(snd_pcm_drain); + SDL_ALSA_SYM(snd_strerror); + SDL_ALSA_SYM(snd_pcm_hw_params_sizeof); + SDL_ALSA_SYM(snd_pcm_sw_params_sizeof); + SDL_ALSA_SYM(snd_pcm_hw_params_copy); + SDL_ALSA_SYM(snd_pcm_hw_params_any); + SDL_ALSA_SYM(snd_pcm_hw_params_set_access); + SDL_ALSA_SYM(snd_pcm_hw_params_set_format); + SDL_ALSA_SYM(snd_pcm_hw_params_set_channels); + SDL_ALSA_SYM(snd_pcm_hw_params_get_channels); + SDL_ALSA_SYM(snd_pcm_hw_params_set_rate_near); + SDL_ALSA_SYM(snd_pcm_hw_params_set_period_size_near); + SDL_ALSA_SYM(snd_pcm_hw_params_get_period_size); + SDL_ALSA_SYM(snd_pcm_hw_params_set_periods_min); + SDL_ALSA_SYM(snd_pcm_hw_params_set_periods_first); + SDL_ALSA_SYM(snd_pcm_hw_params_get_periods); + SDL_ALSA_SYM(snd_pcm_hw_params_set_buffer_size_near); + SDL_ALSA_SYM(snd_pcm_hw_params_get_buffer_size); + SDL_ALSA_SYM(snd_pcm_hw_params); + SDL_ALSA_SYM(snd_pcm_sw_params_current); + SDL_ALSA_SYM(snd_pcm_sw_params_set_start_threshold); + SDL_ALSA_SYM(snd_pcm_sw_params); + SDL_ALSA_SYM(snd_pcm_nonblock); + SDL_ALSA_SYM(snd_pcm_wait); + SDL_ALSA_SYM(snd_pcm_sw_params_set_avail_min); + SDL_ALSA_SYM(snd_pcm_reset); + SDL_ALSA_SYM(snd_device_name_hint); + SDL_ALSA_SYM(snd_device_name_get_hint); + SDL_ALSA_SYM(snd_device_name_free_hint); + SDL_ALSA_SYM(snd_pcm_avail); +#ifdef SND_CHMAP_API_VERSION + SDL_ALSA_SYM(snd_pcm_get_chmap); + SDL_ALSA_SYM(snd_pcm_chmap_print); +#endif + + return 0; +} + +#undef SDL_ALSA_SYM + +#ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC + +static void UnloadALSALibrary(void) +{ + if (alsa_handle) { + SDL_UnloadObject(alsa_handle); + alsa_handle = NULL; + } +} + +static int LoadALSALibrary(void) +{ + int retval = 0; + if (!alsa_handle) { + alsa_handle = SDL_LoadObject(alsa_library); + if (!alsa_handle) { + retval = -1; + /* Don't call SDL_SetError(): SDL_LoadObject already did. */ + } else { + retval = load_alsa_syms(); + if (retval < 0) { + UnloadALSALibrary(); + } + } + } + return retval; +} + +#else + +static void UnloadALSALibrary(void) +{ +} + +static int LoadALSALibrary(void) +{ + load_alsa_syms(); + return 0; +} + +#endif /* SDL_AUDIO_DRIVER_ALSA_DYNAMIC */ + +static const char *get_audio_device(void *handle, const int channels) +{ + const char *device; + + if (handle) { + return (const char *)handle; + } + + /* !!! FIXME: we also check "SDL_AUDIO_DEVICE_NAME" at the higher level. */ + device = SDL_getenv("AUDIODEV"); /* Is there a standard variable name? */ + if (device) { + return device; + } + + if (channels == 6) { + return "plug:surround51"; + } else if (channels == 4) { + return "plug:surround40"; + } + + return "default"; +} + +/* This function waits until it is possible to write a full sound buffer */ +static void ALSA_WaitDevice(_THIS) +{ +#if SDL_ALSA_NON_BLOCKING + const snd_pcm_sframes_t needed = (snd_pcm_sframes_t)this->spec.samples; + while (SDL_AtomicGet(&this->enabled)) { + const snd_pcm_sframes_t rc = ALSA_snd_pcm_avail(this->hidden->pcm_handle); + if ((rc < 0) && (rc != -EAGAIN)) { + /* Hmm, not much we can do - abort */ + fprintf(stderr, "ALSA snd_pcm_avail failed (unrecoverable): %s\n", + ALSA_snd_strerror(rc)); + SDL_OpenedAudioDeviceDisconnected(this); + return; + } else if (rc < needed) { + const Uint32 delay = ((needed - (SDL_max(rc, 0))) * 1000) / this->spec.freq; + SDL_Delay(SDL_max(delay, 10)); + } else { + break; /* ready to go! */ + } + } +#endif +} + +/* !!! FIXME: is there a channel swizzler in alsalib instead? */ +/* + * https://bugzilla.libsdl.org/show_bug.cgi?id=110 + * "For Linux ALSA, this is FL-FR-RL-RR-C-LFE + * and for Windows DirectX [and CoreAudio], this is FL-FR-C-LFE-RL-RR" + */ +#define SWIZ6(T) \ + static void swizzle_alsa_channels_6_##T(void *buffer, const Uint32 bufferlen) \ + { \ + T *ptr = (T *)buffer; \ + Uint32 i; \ + for (i = 0; i < bufferlen; i++, ptr += 6) { \ + T tmp; \ + tmp = ptr[2]; \ + ptr[2] = ptr[4]; \ + ptr[4] = tmp; \ + tmp = ptr[3]; \ + ptr[3] = ptr[5]; \ + ptr[5] = tmp; \ + } \ + } + +/* !!! FIXME: is there a channel swizzler in alsalib instead? */ +/* !!! FIXME: this screams for a SIMD shuffle operation. */ +/* + * https://docs.microsoft.com/en-us/windows-hardware/drivers/audio/mapping-stream-formats-to-speaker-configurations + * For Linux ALSA, this appears to be FL-FR-RL-RR-C-LFE-SL-SR + * and for Windows DirectX [and CoreAudio], this is FL-FR-C-LFE-SL-SR-RL-RR" + */ +#define SWIZ8(T) \ + static void swizzle_alsa_channels_8_##T(void *buffer, const Uint32 bufferlen) \ + { \ + T *ptr = (T *)buffer; \ + Uint32 i; \ + for (i = 0; i < bufferlen; i++, ptr += 6) { \ + const T center = ptr[2]; \ + const T subwoofer = ptr[3]; \ + const T side_left = ptr[4]; \ + const T side_right = ptr[5]; \ + const T rear_left = ptr[6]; \ + const T rear_right = ptr[7]; \ + ptr[2] = rear_left; \ + ptr[3] = rear_right; \ + ptr[4] = center; \ + ptr[5] = subwoofer; \ + ptr[6] = side_left; \ + ptr[7] = side_right; \ + } \ + } + +#define CHANNEL_SWIZZLE(x) \ + x(Uint64) \ + x(Uint32) \ + x(Uint16) \ + x(Uint8) + +CHANNEL_SWIZZLE(SWIZ6) +CHANNEL_SWIZZLE(SWIZ8) + +#undef CHANNEL_SWIZZLE +#undef SWIZ6 +#undef SWIZ8 + +/* + * Called right before feeding this->hidden->mixbuf to the hardware. Swizzle + * channels from Windows/Mac order to the format alsalib will want. + */ +static void swizzle_alsa_channels(_THIS, void *buffer, Uint32 bufferlen) +{ + switch (this->spec.channels) { +#define CHANSWIZ(chans) \ + case chans: \ + switch ((this->spec.format & (0xFF))) { \ + case 8: \ + swizzle_alsa_channels_##chans##_Uint8(buffer, bufferlen); \ + break; \ + case 16: \ + swizzle_alsa_channels_##chans##_Uint16(buffer, bufferlen); \ + break; \ + case 32: \ + swizzle_alsa_channels_##chans##_Uint32(buffer, bufferlen); \ + break; \ + case 64: \ + swizzle_alsa_channels_##chans##_Uint64(buffer, bufferlen); \ + break; \ + default: \ + SDL_assert(!"unhandled bitsize"); \ + break; \ + } \ + return; + + CHANSWIZ(6); + CHANSWIZ(8); +#undef CHANSWIZ + default: + break; + } +} + +#ifdef SND_CHMAP_API_VERSION +/* Some devices have the right channel map, no swizzling necessary */ +static void no_swizzle(_THIS, void *buffer, Uint32 bufferlen) +{ +} +#endif /* SND_CHMAP_API_VERSION */ + +static void ALSA_PlayDevice(_THIS) +{ + const Uint8 *sample_buf = (const Uint8 *)this->hidden->mixbuf; + const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) * + this->spec.channels; + snd_pcm_uframes_t frames_left = ((snd_pcm_uframes_t)this->spec.samples); + + this->hidden->swizzle_func(this, this->hidden->mixbuf, frames_left); + + while (frames_left > 0 && SDL_AtomicGet(&this->enabled)) { + int status = ALSA_snd_pcm_writei(this->hidden->pcm_handle, + sample_buf, frames_left); + + if (status < 0) { + if (status == -EAGAIN) { + /* Apparently snd_pcm_recover() doesn't handle this case - + does it assume snd_pcm_wait() above? */ + SDL_Delay(1); + continue; + } + status = ALSA_snd_pcm_recover(this->hidden->pcm_handle, status, 0); + if (status < 0) { + /* Hmm, not much we can do - abort */ + SDL_LogError(SDL_LOG_CATEGORY_AUDIO, + "ALSA write failed (unrecoverable): %s\n", + ALSA_snd_strerror(status)); + SDL_OpenedAudioDeviceDisconnected(this); + return; + } + continue; + } else if (status == 0) { + /* No frames were written (no available space in pcm device). + Allow other threads to catch up. */ + Uint32 delay = (frames_left / 2 * 1000) / this->spec.freq; + SDL_Delay(delay); + } + + sample_buf += status * frame_size; + frames_left -= status; + } +} + +static Uint8 *ALSA_GetDeviceBuf(_THIS) +{ + return this->hidden->mixbuf; +} + +static int ALSA_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + Uint8 *sample_buf = (Uint8 *)buffer; + const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) * + this->spec.channels; + const int total_frames = buflen / frame_size; + snd_pcm_uframes_t frames_left = total_frames; + snd_pcm_uframes_t wait_time = frame_size / 2; + + SDL_assert((buflen % frame_size) == 0); + + while (frames_left > 0 && SDL_AtomicGet(&this->enabled)) { + int status; + + status = ALSA_snd_pcm_readi(this->hidden->pcm_handle, + sample_buf, frames_left); + + if (status == -EAGAIN) { + ALSA_snd_pcm_wait(this->hidden->pcm_handle, wait_time); + status = 0; + } else if (status < 0) { + /*printf("ALSA: capture error %d\n", status);*/ + status = ALSA_snd_pcm_recover(this->hidden->pcm_handle, status, 0); + if (status < 0) { + /* Hmm, not much we can do - abort */ + SDL_LogError(SDL_LOG_CATEGORY_AUDIO, + "ALSA read failed (unrecoverable): %s\n", + ALSA_snd_strerror(status)); + return -1; + } + continue; + } + + /*printf("ALSA: captured %d bytes\n", status * frame_size);*/ + sample_buf += status * frame_size; + frames_left -= status; + } + + this->hidden->swizzle_func(this, buffer, total_frames - frames_left); + + return (total_frames - frames_left) * frame_size; +} + +static void ALSA_FlushCapture(_THIS) +{ + ALSA_snd_pcm_reset(this->hidden->pcm_handle); +} + +static void ALSA_CloseDevice(_THIS) +{ + if (this->hidden->pcm_handle) { + /* Wait for the submitted audio to drain + ALSA_snd_pcm_drop() can hang, so don't use that. + */ + Uint32 delay = ((this->spec.samples * 1000) / this->spec.freq) * 2; + SDL_Delay(delay); + + ALSA_snd_pcm_close(this->hidden->pcm_handle); + } + SDL_free(this->hidden->mixbuf); + SDL_free(this->hidden); +} + +static int ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params) +{ + int status; + snd_pcm_hw_params_t *hwparams; + snd_pcm_uframes_t persize; + unsigned int periods; + + /* Copy the hardware parameters for this setup */ + snd_pcm_hw_params_alloca(&hwparams); + ALSA_snd_pcm_hw_params_copy(hwparams, params); + + /* Attempt to match the period size to the requested buffer size */ + persize = this->spec.samples; + status = ALSA_snd_pcm_hw_params_set_period_size_near( + this->hidden->pcm_handle, hwparams, &persize, NULL); + if (status < 0) { + return -1; + } + + /* Need to at least double buffer */ + periods = 2; + status = ALSA_snd_pcm_hw_params_set_periods_min( + this->hidden->pcm_handle, hwparams, &periods, NULL); + if (status < 0) { + return -1; + } + + status = ALSA_snd_pcm_hw_params_set_periods_first( + this->hidden->pcm_handle, hwparams, &periods, NULL); + if (status < 0) { + return -1; + } + + /* "set" the hardware with the desired parameters */ + status = ALSA_snd_pcm_hw_params(this->hidden->pcm_handle, hwparams); + if (status < 0) { + return -1; + } + + this->spec.samples = persize; + + /* This is useful for debugging */ + if (SDL_getenv("SDL_AUDIO_ALSA_DEBUG")) { + snd_pcm_uframes_t bufsize; + + ALSA_snd_pcm_hw_params_get_buffer_size(hwparams, &bufsize); + + SDL_LogError(SDL_LOG_CATEGORY_AUDIO, + "ALSA: period size = %ld, periods = %u, buffer size = %lu\n", + persize, periods, bufsize); + } + + return 0; +} + +static int ALSA_OpenDevice(_THIS, const char *devname) +{ + int status = 0; + SDL_bool iscapture = this->iscapture; + snd_pcm_t *pcm_handle = NULL; + snd_pcm_hw_params_t *hwparams = NULL; + snd_pcm_sw_params_t *swparams = NULL; + snd_pcm_format_t format = 0; + SDL_AudioFormat test_format = 0; + unsigned int rate = 0; + unsigned int channels = 0; +#ifdef SND_CHMAP_API_VERSION + snd_pcm_chmap_t *chmap; + char chmap_str[64]; +#endif + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); + + /* Open the audio device */ + /* Name of device should depend on # channels in spec */ + status = ALSA_snd_pcm_open(&pcm_handle, + get_audio_device(this->handle, this->spec.channels), + iscapture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, + SND_PCM_NONBLOCK); + + if (status < 0) { + return SDL_SetError("ALSA: Couldn't open audio device: %s", ALSA_snd_strerror(status)); + } + + this->hidden->pcm_handle = pcm_handle; + + /* Figure out what the hardware is capable of */ + snd_pcm_hw_params_alloca(&hwparams); + status = ALSA_snd_pcm_hw_params_any(pcm_handle, hwparams); + if (status < 0) { + return SDL_SetError("ALSA: Couldn't get hardware config: %s", ALSA_snd_strerror(status)); + } + + /* SDL only uses interleaved sample output */ + status = ALSA_snd_pcm_hw_params_set_access(pcm_handle, hwparams, + SND_PCM_ACCESS_RW_INTERLEAVED); + if (status < 0) { + return SDL_SetError("ALSA: Couldn't set interleaved access: %s", ALSA_snd_strerror(status)); + } + + /* Try for a closest match on audio format */ + for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { + switch (test_format) { + case AUDIO_U8: + format = SND_PCM_FORMAT_U8; + break; + case AUDIO_S8: + format = SND_PCM_FORMAT_S8; + break; + case AUDIO_S16LSB: + format = SND_PCM_FORMAT_S16_LE; + break; + case AUDIO_S16MSB: + format = SND_PCM_FORMAT_S16_BE; + break; + case AUDIO_U16LSB: + format = SND_PCM_FORMAT_U16_LE; + break; + case AUDIO_U16MSB: + format = SND_PCM_FORMAT_U16_BE; + break; + case AUDIO_S32LSB: + format = SND_PCM_FORMAT_S32_LE; + break; + case AUDIO_S32MSB: + format = SND_PCM_FORMAT_S32_BE; + break; + case AUDIO_F32LSB: + format = SND_PCM_FORMAT_FLOAT_LE; + break; + case AUDIO_F32MSB: + format = SND_PCM_FORMAT_FLOAT_BE; + break; + default: + continue; + } + if (ALSA_snd_pcm_hw_params_set_format(pcm_handle, hwparams, format) >= 0) { + break; + } + } + if (!test_format) { + return SDL_SetError("%s: Unsupported audio format", "alsa"); + } + this->spec.format = test_format; + + /* Validate number of channels and determine if swizzling is necessary + * Assume original swizzling, until proven otherwise. + */ + this->hidden->swizzle_func = swizzle_alsa_channels; +#ifdef SND_CHMAP_API_VERSION + chmap = ALSA_snd_pcm_get_chmap(pcm_handle); + if (chmap) { + if (ALSA_snd_pcm_chmap_print(chmap, sizeof(chmap_str), chmap_str) > 0) { + if (SDL_strcmp("FL FR FC LFE RL RR", chmap_str) == 0 || + SDL_strcmp("FL FR FC LFE SL SR", chmap_str) == 0) { + this->hidden->swizzle_func = no_swizzle; + } + } + free(chmap); + } +#endif /* SND_CHMAP_API_VERSION */ + + /* Set the number of channels */ + status = ALSA_snd_pcm_hw_params_set_channels(pcm_handle, hwparams, + this->spec.channels); + channels = this->spec.channels; + if (status < 0) { + status = ALSA_snd_pcm_hw_params_get_channels(hwparams, &channels); + if (status < 0) { + return SDL_SetError("ALSA: Couldn't set audio channels"); + } + this->spec.channels = channels; + } + + /* Set the audio rate */ + rate = this->spec.freq; + status = ALSA_snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, + &rate, NULL); + if (status < 0) { + return SDL_SetError("ALSA: Couldn't set audio frequency: %s", ALSA_snd_strerror(status)); + } + this->spec.freq = rate; + + /* Set the buffer size, in samples */ + status = ALSA_set_buffer_size(this, hwparams); + if (status < 0) { + return SDL_SetError("Couldn't set hardware audio parameters: %s", ALSA_snd_strerror(status)); + } + + /* Set the software parameters */ + snd_pcm_sw_params_alloca(&swparams); + status = ALSA_snd_pcm_sw_params_current(pcm_handle, swparams); + if (status < 0) { + return SDL_SetError("ALSA: Couldn't get software config: %s", ALSA_snd_strerror(status)); + } + status = ALSA_snd_pcm_sw_params_set_avail_min(pcm_handle, swparams, this->spec.samples); + if (status < 0) { + return SDL_SetError("Couldn't set minimum available samples: %s", ALSA_snd_strerror(status)); + } + status = + ALSA_snd_pcm_sw_params_set_start_threshold(pcm_handle, swparams, 1); + if (status < 0) { + return SDL_SetError("ALSA: Couldn't set start threshold: %s", ALSA_snd_strerror(status)); + } + status = ALSA_snd_pcm_sw_params(pcm_handle, swparams); + if (status < 0) { + return SDL_SetError("Couldn't set software audio parameters: %s", ALSA_snd_strerror(status)); + } + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&this->spec); + + /* Allocate mixing buffer */ + if (!iscapture) { + this->hidden->mixlen = this->spec.size; + this->hidden->mixbuf = (Uint8 *)SDL_malloc(this->hidden->mixlen); + if (!this->hidden->mixbuf) { + return SDL_OutOfMemory(); + } + SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen); + } + +#if !SDL_ALSA_NON_BLOCKING + if (!iscapture) { + ALSA_snd_pcm_nonblock(pcm_handle, 0); + } +#endif + + /* We're ready to rock and roll. :-) */ + return 0; +} + +typedef struct ALSA_Device +{ + char *name; + SDL_bool iscapture; + struct ALSA_Device *next; +} ALSA_Device; + +static void add_device(const int iscapture, const char *name, void *hint, ALSA_Device **pSeen) +{ + ALSA_Device *dev = SDL_malloc(sizeof(ALSA_Device)); + char *desc; + char *handle = NULL; + char *ptr; + + if (!dev) { + return; + } + + /* Not all alsa devices are enumerable via snd_device_name_get_hint + (i.e. bluetooth devices). Therefore if hint is passed in to this + function as NULL, assume name contains desc. + Make sure not to free the storage associated with desc in this case */ + if (hint) { + desc = ALSA_snd_device_name_get_hint(hint, "DESC"); + if (!desc) { + SDL_free(dev); + return; + } + } else { + desc = (char *)name; + } + + SDL_assert(name != NULL); + + /* some strings have newlines, like "HDA NVidia, HDMI 0\nHDMI Audio Output". + just chop the extra lines off, this seems to get a reasonable device + name without extra details. */ + ptr = SDL_strchr(desc, '\n'); + if (ptr) { + *ptr = '\0'; + } + + /*printf("ALSA: adding %s device '%s' (%s)\n", iscapture ? "capture" : "output", name, desc);*/ + + handle = SDL_strdup(name); + if (!handle) { + if (hint) { + free(desc); + } + SDL_free(dev); + return; + } + + /* Note that spec is NULL, because we are required to open the device before + * acquiring the mix format, making this information inaccessible at + * enumeration time + */ + SDL_AddAudioDevice(iscapture, desc, NULL, handle); + if (hint) { + free(desc); + } + dev->name = handle; + dev->iscapture = iscapture; + dev->next = *pSeen; + *pSeen = dev; +} + +static ALSA_Device *hotplug_devices = NULL; + +static void ALSA_HotplugIteration(void) +{ + void **hints = NULL; + ALSA_Device *dev; + ALSA_Device *unseen; + ALSA_Device *seen; + ALSA_Device *next; + ALSA_Device *prev; + + if (ALSA_snd_device_name_hint(-1, "pcm", &hints) == 0) { + int i, j; + const char *match = NULL; + int bestmatch = 0xFFFF; + size_t match_len = 0; + int defaultdev = -1; + static const char *const prefixes[] = { + "hw:", "sysdefault:", "default:", NULL + }; + + unseen = hotplug_devices; + seen = NULL; + + /* Apparently there are several different ways that ALSA lists + actual hardware. It could be prefixed with "hw:" or "default:" + or "sysdefault:" and maybe others. Go through the list and see + if we can find a preferred prefix for the system. */ + for (i = 0; hints[i]; i++) { + char *name = ALSA_snd_device_name_get_hint(hints[i], "NAME"); + if (!name) { + continue; + } + + /* full name, not a prefix */ + if ((defaultdev == -1) && (SDL_strcmp(name, "default") == 0)) { + defaultdev = i; + } + + for (j = 0; prefixes[j]; j++) { + const char *prefix = prefixes[j]; + const size_t prefixlen = SDL_strlen(prefix); + if (SDL_strncmp(name, prefix, prefixlen) == 0) { + if (j < bestmatch) { + bestmatch = j; + match = prefix; + match_len = prefixlen; + } + } + } + + free(name); + } + + /* look through the list of device names to find matches */ + for (i = 0; hints[i]; i++) { + char *name; + + /* if we didn't find a device name prefix we like at all... */ + if ((!match) && (defaultdev != i)) { + continue; /* ...skip anything that isn't the default device. */ + } + + name = ALSA_snd_device_name_get_hint(hints[i], "NAME"); + if (!name) { + continue; + } + + /* only want physical hardware interfaces */ + if (!match || (SDL_strncmp(name, match, match_len) == 0)) { + char *ioid = ALSA_snd_device_name_get_hint(hints[i], "IOID"); + const SDL_bool isoutput = (!ioid) || (SDL_strcmp(ioid, "Output") == 0); + const SDL_bool isinput = (!ioid) || (SDL_strcmp(ioid, "Input") == 0); + SDL_bool have_output = SDL_FALSE; + SDL_bool have_input = SDL_FALSE; + + free(ioid); + + if (!isoutput && !isinput) { + free(name); + continue; + } + + prev = NULL; + for (dev = unseen; dev; dev = next) { + next = dev->next; + if ((SDL_strcmp(dev->name, name) == 0) && (((isinput) && dev->iscapture) || ((isoutput) && !dev->iscapture))) { + if (prev) { + prev->next = next; + } else { + unseen = next; + } + dev->next = seen; + seen = dev; + if (isinput) { + have_input = SDL_TRUE; + } + if (isoutput) { + have_output = SDL_TRUE; + } + } else { + prev = dev; + } + } + + if (isinput && !have_input) { + add_device(SDL_TRUE, name, hints[i], &seen); + } + if (isoutput && !have_output) { + add_device(SDL_FALSE, name, hints[i], &seen); + } + } + + free(name); + } + + ALSA_snd_device_name_free_hint(hints); + + hotplug_devices = seen; /* now we have a known-good list of attached devices. */ + + /* report anything still in unseen as removed. */ + for (dev = unseen; dev; dev = next) { + /*printf("ALSA: removing usb %s device '%s'\n", dev->iscapture ? "capture" : "output", dev->name);*/ + next = dev->next; + SDL_RemoveAudioDevice(dev->iscapture, dev->name); + SDL_free(dev->name); + SDL_free(dev); + } + } +} + +#if SDL_ALSA_HOTPLUG_THREAD +static SDL_atomic_t ALSA_hotplug_shutdown; +static SDL_Thread *ALSA_hotplug_thread; + +static int SDLCALL ALSA_HotplugThread(void *arg) +{ + SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW); + + while (!SDL_AtomicGet(&ALSA_hotplug_shutdown)) { + /* Block awhile before checking again, unless we're told to stop. */ + const Uint32 ticks = SDL_GetTicks() + 5000; + while (!SDL_AtomicGet(&ALSA_hotplug_shutdown) && !SDL_TICKS_PASSED(SDL_GetTicks(), ticks)) { + SDL_Delay(100); + } + + ALSA_HotplugIteration(); /* run the check. */ + } + + return 0; +} +#endif + +static void ALSA_DetectDevices(void) +{ + ALSA_HotplugIteration(); /* run once now before a thread continues to check. */ + +#if SDL_ALSA_HOTPLUG_THREAD + SDL_AtomicSet(&ALSA_hotplug_shutdown, 0); + ALSA_hotplug_thread = SDL_CreateThread(ALSA_HotplugThread, "SDLHotplugALSA", NULL); + /* if the thread doesn't spin, oh well, you just don't get further hotplug events. */ +#endif +} + +static void ALSA_Deinitialize(void) +{ + ALSA_Device *dev; + ALSA_Device *next; + +#if SDL_ALSA_HOTPLUG_THREAD + if (ALSA_hotplug_thread) { + SDL_AtomicSet(&ALSA_hotplug_shutdown, 1); + SDL_WaitThread(ALSA_hotplug_thread, NULL); + ALSA_hotplug_thread = NULL; + } +#endif + + /* Shutting down! Clean up any data we've gathered. */ + for (dev = hotplug_devices; dev; dev = next) { + /*printf("ALSA: at shutdown, removing %s device '%s'\n", dev->iscapture ? "capture" : "output", dev->name);*/ + next = dev->next; + SDL_free(dev->name); + SDL_free(dev); + } + hotplug_devices = NULL; + + UnloadALSALibrary(); +} + +static SDL_bool ALSA_Init(SDL_AudioDriverImpl *impl) +{ + if (LoadALSALibrary() < 0) { + return SDL_FALSE; + } + + /* Set the function pointers */ + impl->DetectDevices = ALSA_DetectDevices; + impl->OpenDevice = ALSA_OpenDevice; + impl->WaitDevice = ALSA_WaitDevice; + impl->GetDeviceBuf = ALSA_GetDeviceBuf; + impl->PlayDevice = ALSA_PlayDevice; + impl->CloseDevice = ALSA_CloseDevice; + impl->Deinitialize = ALSA_Deinitialize; + impl->CaptureFromDevice = ALSA_CaptureFromDevice; + impl->FlushCapture = ALSA_FlushCapture; + + impl->HasCaptureSupport = SDL_TRUE; + impl->SupportsNonPow2Samples = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap ALSA_bootstrap = { + "alsa", "ALSA PCM audio", ALSA_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_ALSA */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/alsa/SDL_alsa_audio.h b/third_party/SDL2/src/audio/alsa/SDL_alsa_audio.h new file mode 100644 index 00000000000..200e8e7bf5a --- /dev/null +++ b/third_party/SDL2/src/audio/alsa/SDL_alsa_audio.h @@ -0,0 +1,48 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_ALSA_audio_h_ +#define SDL_ALSA_audio_h_ + +#include + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + /* The audio device handle */ + snd_pcm_t *pcm_handle; + + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; + + /* swizzle function */ + void (*swizzle_func)(_THIS, void *buffer, Uint32 bufferlen); +}; + +#endif /* SDL_ALSA_audio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/android/SDL_androidaudio.c b/third_party/SDL2/src/audio/android/SDL_androidaudio.c new file mode 100644 index 00000000000..c45e031df82 --- /dev/null +++ b/third_party/SDL2/src/audio/android/SDL_androidaudio.c @@ -0,0 +1,180 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_ANDROID + +/* Output audio to Android */ + +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_androidaudio.h" + +#include "../../core/android/SDL_android.h" + +#include + +static SDL_AudioDevice *audioDevice = NULL; +static SDL_AudioDevice *captureDevice = NULL; + + +static int ANDROIDAUDIO_OpenDevice(_THIS, const char *devname) +{ + SDL_AudioFormat test_format; + SDL_bool iscapture = this->iscapture; + + SDL_assert((captureDevice == NULL) || !iscapture); + SDL_assert((audioDevice == NULL) || iscapture); + + if (iscapture) { + captureDevice = this; + } else { + audioDevice = this; + } + + this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + + for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { + if ((test_format == AUDIO_U8) || + (test_format == AUDIO_S16) || + (test_format == AUDIO_F32)) { + this->spec.format = test_format; + break; + } + } + + if (!test_format) { + /* Didn't find a compatible format :( */ + return SDL_SetError("%s: Unsupported audio format", "android"); + } + + { + int audio_device_id = 0; + if (devname) { + audio_device_id = SDL_atoi(devname); + } + if (Android_JNI_OpenAudioDevice(iscapture, audio_device_id, &this->spec) < 0) { + return -1; + } + } + + SDL_CalculateAudioSpec(&this->spec); + + return 0; +} + +static void ANDROIDAUDIO_PlayDevice(_THIS) +{ + Android_JNI_WriteAudioBuffer(); +} + +static Uint8 *ANDROIDAUDIO_GetDeviceBuf(_THIS) +{ + return Android_JNI_GetAudioBuffer(); +} + +static int ANDROIDAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + return Android_JNI_CaptureAudioBuffer(buffer, buflen); +} + +static void ANDROIDAUDIO_FlushCapture(_THIS) +{ + Android_JNI_FlushCapturedAudio(); +} + +static void ANDROIDAUDIO_CloseDevice(_THIS) +{ + /* At this point SDL_CloseAudioDevice via close_audio_device took care of terminating the audio thread + so it's safe to terminate the Java side buffer and AudioTrack + */ + Android_JNI_CloseAudioDevice(this->iscapture); + if (this->iscapture) { + SDL_assert(captureDevice == this); + captureDevice = NULL; + } else { + SDL_assert(audioDevice == this); + audioDevice = NULL; + } + SDL_free(this->hidden); +} + +static SDL_bool ANDROIDAUDIO_Init(SDL_AudioDriverImpl *impl) +{ + /* Set the function pointers */ + impl->DetectDevices = Android_DetectDevices; + impl->OpenDevice = ANDROIDAUDIO_OpenDevice; + impl->PlayDevice = ANDROIDAUDIO_PlayDevice; + impl->GetDeviceBuf = ANDROIDAUDIO_GetDeviceBuf; + impl->CloseDevice = ANDROIDAUDIO_CloseDevice; + impl->CaptureFromDevice = ANDROIDAUDIO_CaptureFromDevice; + impl->FlushCapture = ANDROIDAUDIO_FlushCapture; + impl->AllowsArbitraryDeviceNames = SDL_TRUE; + + /* and the capabilities */ + impl->HasCaptureSupport = SDL_TRUE; + impl->OnlyHasDefaultOutputDevice = SDL_FALSE; + impl->OnlyHasDefaultCaptureDevice = SDL_FALSE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap ANDROIDAUDIO_bootstrap = { + "android", "SDL Android audio driver", ANDROIDAUDIO_Init, SDL_FALSE +}; + +/* Pause (block) all non already paused audio devices by taking their mixer lock */ +void ANDROIDAUDIO_PauseDevices(void) +{ + /* TODO: Handle multiple devices? */ + if (audioDevice && audioDevice->hidden) { + SDL_LockMutex(audioDevice->mixer_lock); + } + + if (captureDevice && captureDevice->hidden) { + SDL_LockMutex(captureDevice->mixer_lock); + } +} + +/* Resume (unblock) all non already paused audio devices by releasing their mixer lock */ +void ANDROIDAUDIO_ResumeDevices(void) +{ + /* TODO: Handle multiple devices? */ + if (audioDevice && audioDevice->hidden) { + SDL_UnlockMutex(audioDevice->mixer_lock); + } + + if (captureDevice && captureDevice->hidden) { + SDL_UnlockMutex(captureDevice->mixer_lock); + } +} + +#else + +void ANDROIDAUDIO_ResumeDevices(void) {} +void ANDROIDAUDIO_PauseDevices(void) {} + +#endif /* SDL_AUDIO_DRIVER_ANDROID */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/android/SDL_androidaudio.h b/third_party/SDL2/src/audio/android/SDL_androidaudio.h new file mode 100644 index 00000000000..e9c2ef62beb --- /dev/null +++ b/third_party/SDL2/src/audio/android/SDL_androidaudio.h @@ -0,0 +1,41 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_androidaudio_h_ +#define SDL_androidaudio_h_ + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + int unused; +}; + +void ANDROIDAUDIO_ResumeDevices(void); +void ANDROIDAUDIO_PauseDevices(void); + +#endif /* SDL_androidaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/arts/SDL_artsaudio.c b/third_party/SDL2/src/audio/arts/SDL_artsaudio.c new file mode 100644 index 00000000000..420588b962e --- /dev/null +++ b/third_party/SDL2/src/audio/arts/SDL_artsaudio.c @@ -0,0 +1,344 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_ARTS + +/* Allow access to a raw mixing buffer */ + +#ifdef HAVE_SIGNAL_H +#include +#endif +#include +#include + +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_artsaudio.h" + +#ifdef SDL_AUDIO_DRIVER_ARTS_DYNAMIC +#include "SDL_name.h" +#include "SDL_loadso.h" +#else +#define SDL_NAME(X) X +#endif + +#ifdef SDL_AUDIO_DRIVER_ARTS_DYNAMIC + +static const char *arts_library = SDL_AUDIO_DRIVER_ARTS_DYNAMIC; +static void *arts_handle = NULL; + +/* !!! FIXME: I hate this SDL_NAME clutter...it makes everything so messy! */ +static int (*SDL_NAME(arts_init)) (void); +static void (*SDL_NAME(arts_free)) (void); +static arts_stream_t(*SDL_NAME(arts_play_stream)) (int rate, int bits, + int channels, + const char *name); +static int (*SDL_NAME(arts_stream_set)) (arts_stream_t s, + arts_parameter_t param, int value); +static int (*SDL_NAME(arts_stream_get)) (arts_stream_t s, + arts_parameter_t param); +static int (*SDL_NAME(arts_write)) (arts_stream_t s, const void *buffer, + int count); +static void (*SDL_NAME(arts_close_stream)) (arts_stream_t s); +static int (*SDL_NAME(arts_suspend))(void); +static int (*SDL_NAME(arts_suspended)) (void); +static const char *(*SDL_NAME(arts_error_text)) (int errorcode); + +#define SDL_ARTS_SYM(x) { #x, (void **) (char *) &SDL_NAME(x) } +static struct +{ + const char *name; + void **func; +} arts_functions[] = { +/* *INDENT-OFF* */ + SDL_ARTS_SYM(arts_init), + SDL_ARTS_SYM(arts_free), + SDL_ARTS_SYM(arts_play_stream), + SDL_ARTS_SYM(arts_stream_set), + SDL_ARTS_SYM(arts_stream_get), + SDL_ARTS_SYM(arts_write), + SDL_ARTS_SYM(arts_close_stream), + SDL_ARTS_SYM(arts_suspend), + SDL_ARTS_SYM(arts_suspended), + SDL_ARTS_SYM(arts_error_text), +/* *INDENT-ON* */ +}; + +#undef SDL_ARTS_SYM + +static void UnloadARTSLibrary(void) +{ + if (arts_handle) { + SDL_UnloadObject(arts_handle); + arts_handle = NULL; + } +} + +static int LoadARTSLibrary(void) +{ + int i, retval = -1; + + if (!arts_handle) { + arts_handle = SDL_LoadObject(arts_library); + if (arts_handle) { + retval = 0; + for (i = 0; i < SDL_arraysize(arts_functions); ++i) { + *arts_functions[i].func = + SDL_LoadFunction(arts_handle, arts_functions[i].name); + if (!*arts_functions[i].func) { + retval = -1; + UnloadARTSLibrary(); + break; + } + } + } + } + + return retval; +} + +#else + +static void UnloadARTSLibrary(void) +{ + return; +} + +static int LoadARTSLibrary(void) +{ + return 0; +} + +#endif /* SDL_AUDIO_DRIVER_ARTS_DYNAMIC */ + +/* This function waits until it is possible to write a full sound buffer */ +static void ARTS_WaitDevice(_THIS) +{ + Sint32 ticks; + + /* Check to see if the thread-parent process is still alive */ + { + static int cnt = 0; + /* Note that this only works with thread implementations + that use a different process id for each thread. + */ + /* Check every 10 loops */ + if (this->hidden->parent && (((++cnt) % 10) == 0)) { + if (kill(this->hidden->parent, 0) < 0 && errno == ESRCH) { + SDL_OpenedAudioDeviceDisconnected(this); + } + } + } + + /* Use timer for general audio synchronization */ + ticks = + ((Sint32) (this->hidden->next_frame - SDL_GetTicks())) - FUDGE_TICKS; + if (ticks > 0) { + SDL_Delay(ticks); + } +} + +static void ARTS_PlayDevice(_THIS) +{ + /* Write the audio data */ + int written = SDL_NAME(arts_write) (this->hidden->stream, + this->hidden->mixbuf, + this->hidden->mixlen); + + /* If timer synchronization is enabled, set the next write frame */ + if (this->hidden->frame_ticks) { + this->hidden->next_frame += this->hidden->frame_ticks; + } + + /* If we couldn't write, assume fatal error for now */ + if (written < 0) { + SDL_OpenedAudioDeviceDisconnected(this); + } +#ifdef DEBUG_AUDIO + fprintf(stderr, "Wrote %d bytes of audio data\n", written); +#endif +} + +static Uint8 *ARTS_GetDeviceBuf(_THIS) +{ + return (this->hidden->mixbuf); +} + + +static void ARTS_CloseDevice(_THIS) +{ + if (this->hidden->stream) { + SDL_NAME(arts_close_stream) (this->hidden->stream); + } + SDL_NAME(arts_free) (); + SDL_free(this->hidden->mixbuf); + SDL_free(this->hidden); +} + +static int ARTS_Suspend(void) +{ + const Uint32 abortms = SDL_GetTicks() + 3000; /* give up after 3 secs */ + while ( (!SDL_NAME(arts_suspended)()) && !SDL_TICKS_PASSED(SDL_GetTicks(), abortms) ) { + if ( SDL_NAME(arts_suspend)() ) { + break; + } + } + return SDL_NAME(arts_suspended)(); +} + +static int ARTS_OpenDevice(_THIS, const char *devname) +{ + int rc = 0; + int bits, frag_spec = 0; + SDL_AudioFormat test_format = 0; + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); + + /* Try for a closest match on audio format */ + for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { +#ifdef DEBUG_AUDIO + fprintf(stderr, "Trying format 0x%4.4x\n", test_format); +#endif + switch (test_format) { + case AUDIO_U8: + case AUDIO_S16LSB: + break; + default: + continue; + } + break; + } + if (!test_format) { + return SDL_SetError("%s: Unsupported audio format", "arts"); + } + this->spec.format = test_format; + bits = SDL_AUDIO_BITSIZE(test_format); + + if ((rc = SDL_NAME(arts_init) ()) != 0) { + return SDL_SetError("Unable to initialize ARTS: %s", + SDL_NAME(arts_error_text) (rc)); + } + + if (!ARTS_Suspend()) { + return SDL_SetError("ARTS can not open audio device"); + } + + this->hidden->stream = SDL_NAME(arts_play_stream) (this->spec.freq, + bits, + this->spec.channels, + "SDL"); + + /* Play nothing so we have at least one write (server bug workaround). */ + SDL_NAME(arts_write) (this->hidden->stream, "", 0); + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&this->spec); + + /* Determine the power of two of the fragment size */ + for (frag_spec = 0; (0x01 << frag_spec) < this->spec.size; ++frag_spec); + if ((0x01 << frag_spec) != this->spec.size) { + return SDL_SetError("Fragment size must be a power of two"); + } + frag_spec |= 0x00020000; /* two fragments, for low latency */ + +#ifdef ARTS_P_PACKET_SETTINGS + SDL_NAME(arts_stream_set) (this->hidden->stream, + ARTS_P_PACKET_SETTINGS, frag_spec); +#else + SDL_NAME(arts_stream_set) (this->hidden->stream, ARTS_P_PACKET_SIZE, + frag_spec & 0xffff); + SDL_NAME(arts_stream_set) (this->hidden->stream, ARTS_P_PACKET_COUNT, + frag_spec >> 16); +#endif + this->spec.size = SDL_NAME(arts_stream_get) (this->hidden->stream, + ARTS_P_PACKET_SIZE); + + /* Allocate mixing buffer */ + this->hidden->mixlen = this->spec.size; + this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); + if (!this->hidden->mixbuf) { + return SDL_OutOfMemory(); + } + SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); + + /* Get the parent process id (we're the parent of the audio thread) */ + this->hidden->parent = getpid(); + + /* We're ready to rock and roll. :-) */ + return 0; +} + + +static void ARTS_Deinitialize(void) +{ + UnloadARTSLibrary(); +} + + +static SDL_bool ARTS_Init(SDL_AudioDriverImpl *impl) +{ + if (LoadARTSLibrary() < 0) { + return SDL_FALSE; + } else { + if (SDL_NAME(arts_init) () != 0) { + UnloadARTSLibrary(); + SDL_SetError("ARTS: arts_init failed (no audio server?)"); + return SDL_FALSE; + } + + /* Play a stream so aRts doesn't crash */ + if (ARTS_Suspend()) { + arts_stream_t stream; + stream = SDL_NAME(arts_play_stream) (44100, 16, 2, "SDL"); + SDL_NAME(arts_write) (stream, "", 0); + SDL_NAME(arts_close_stream) (stream); + } + + SDL_NAME(arts_free) (); + } + + /* Set the function pointers */ + impl->OpenDevice = ARTS_OpenDevice; + impl->PlayDevice = ARTS_PlayDevice; + impl->WaitDevice = ARTS_WaitDevice; + impl->GetDeviceBuf = ARTS_GetDeviceBuf; + impl->CloseDevice = ARTS_CloseDevice; + impl->Deinitialize = ARTS_Deinitialize; + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + + +AudioBootStrap ARTS_bootstrap = { + "arts", "Analog RealTime Synthesizer", ARTS_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_ARTS */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/arts/SDL_artsaudio.h b/third_party/SDL2/src/audio/arts/SDL_artsaudio.h new file mode 100644 index 00000000000..e7f4fc175c1 --- /dev/null +++ b/third_party/SDL2/src/audio/arts/SDL_artsaudio.h @@ -0,0 +1,53 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_artsaudio_h_ +#define SDL_artsaudio_h_ + +#include + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + /* The stream descriptor for the audio device */ + arts_stream_t stream; + + /* The parent process id, to detect when application quits */ + pid_t parent; + + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; + + /* Support for audio timing using a timer, in addition to SDL_IOReady() */ + float frame_ticks; + float next_frame; +}; +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ + +#endif /* SDL_artsaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/coreaudio/SDL_coreaudio.h b/third_party/SDL2/src/audio/coreaudio/SDL_coreaudio.h new file mode 100644 index 00000000000..2a9fac2cc32 --- /dev/null +++ b/third_party/SDL2/src/audio/coreaudio/SDL_coreaudio.h @@ -0,0 +1,76 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_coreaudio_h_ +#define SDL_coreaudio_h_ + +#include "../SDL_sysaudio.h" + +#if !defined(__IPHONEOS__) +#define MACOSX_COREAUDIO +#endif + +#ifdef MACOSX_COREAUDIO +#include +#else +#import +#import +#endif + +#include +#include + +/* Things named "Master" were renamed to "Main" in macOS 12.0's SDK. */ +#ifdef MACOSX_COREAUDIO +#include +#ifndef MAC_OS_VERSION_12_0 +#define kAudioObjectPropertyElementMain kAudioObjectPropertyElementMaster +#endif +#endif + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + SDL_Thread *thread; + AudioQueueRef audioQueue; + int numAudioBuffers; + AudioQueueBufferRef *audioBuffer; + void *buffer; + UInt32 bufferOffset; + UInt32 bufferSize; + AudioStreamBasicDescription strdesc; + SDL_sem *ready_semaphore; + char *thread_error; +#ifdef MACOSX_COREAUDIO + AudioDeviceID deviceID; + SDL_atomic_t device_change_flag; +#else + SDL_bool interrupted; + CFTypeRef interruption_listener; +#endif +}; + +#endif /* SDL_coreaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/coreaudio/SDL_coreaudio.m b/third_party/SDL2/src/audio/coreaudio/SDL_coreaudio.m new file mode 100644 index 00000000000..edf6e236174 --- /dev/null +++ b/third_party/SDL2/src/audio/coreaudio/SDL_coreaudio.m @@ -0,0 +1,1349 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_COREAUDIO + +/* !!! FIXME: clean out some of the macro salsa in here. */ + +#include "SDL_audio.h" +#include "SDL_hints.h" +#include "../SDL_audio_c.h" +#include "../SDL_sysaudio.h" +#include "SDL_coreaudio.h" +#include "../../thread/SDL_systhread.h" + +#define DEBUG_COREAUDIO 0 + +#if DEBUG_COREAUDIO +#define CHECK_RESULT(msg) \ + if (result != noErr) { \ + printf("COREAUDIO: Got error %d from '%s'!\n", (int)result, msg); \ + SDL_SetError("CoreAudio error (%s): %d", msg, (int)result); \ + return 0; \ + } +#else +#define CHECK_RESULT(msg) \ + if (result != noErr) { \ + SDL_SetError("CoreAudio error (%s): %d", msg, (int)result); \ + return 0; \ + } +#endif + +#ifdef MACOSX_COREAUDIO +static const AudioObjectPropertyAddress devlist_address = { + kAudioHardwarePropertyDevices, + kAudioObjectPropertyScopeGlobal, + kAudioObjectPropertyElementMain +}; + +typedef void (*addDevFn)(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data); + +typedef struct AudioDeviceList +{ + AudioDeviceID devid; + SDL_bool alive; + struct AudioDeviceList *next; +} AudioDeviceList; + +static AudioDeviceList *output_devs = NULL; +static AudioDeviceList *capture_devs = NULL; + +static SDL_bool add_to_internal_dev_list(const int iscapture, AudioDeviceID devId) +{ + AudioDeviceList *item = (AudioDeviceList *)SDL_malloc(sizeof(AudioDeviceList)); + if (item == NULL) { + return SDL_FALSE; + } + item->devid = devId; + item->alive = SDL_TRUE; + item->next = iscapture ? capture_devs : output_devs; + if (iscapture) { + capture_devs = item; + } else { + output_devs = item; + } + + return SDL_TRUE; +} + +static void addToDevList(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data) +{ + if (add_to_internal_dev_list(iscapture, devId)) { + SDL_AddAudioDevice(iscapture, name, spec, (void *)((size_t)devId)); + } +} + +static void build_device_list(int iscapture, addDevFn addfn, void *addfndata) +{ + OSStatus result = noErr; + UInt32 size = 0; + AudioDeviceID *devs = NULL; + UInt32 i = 0; + UInt32 max = 0; + + result = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, + &devlist_address, 0, NULL, &size); + if (result != kAudioHardwareNoError) { + return; + } + + devs = (AudioDeviceID *)alloca(size); + if (devs == NULL) { + return; + } + + result = AudioObjectGetPropertyData(kAudioObjectSystemObject, + &devlist_address, 0, NULL, &size, devs); + if (result != kAudioHardwareNoError) { + return; + } + + max = size / sizeof(AudioDeviceID); + for (i = 0; i < max; i++) { + CFStringRef cfstr = NULL; + char *ptr = NULL; + AudioDeviceID dev = devs[i]; + AudioBufferList *buflist = NULL; + int usable = 0; + CFIndex len = 0; + double sampleRate = 0; + SDL_AudioSpec spec; + const AudioObjectPropertyAddress addr = { + kAudioDevicePropertyStreamConfiguration, + iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMain + }; + const AudioObjectPropertyAddress nameaddr = { + kAudioObjectPropertyName, + iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMain + }; + const AudioObjectPropertyAddress freqaddr = { + kAudioDevicePropertyNominalSampleRate, + iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMain + }; + + result = AudioObjectGetPropertyDataSize(dev, &addr, 0, NULL, &size); + if (result != noErr) { + continue; + } + + buflist = (AudioBufferList *)SDL_malloc(size); + if (buflist == NULL) { + continue; + } + + result = AudioObjectGetPropertyData(dev, &addr, 0, NULL, + &size, buflist); + + SDL_zero(spec); + if (result == noErr) { + UInt32 j; + for (j = 0; j < buflist->mNumberBuffers; j++) { + spec.channels += buflist->mBuffers[j].mNumberChannels; + } + } + + SDL_free(buflist); + + if (spec.channels == 0) { + continue; + } + + size = sizeof(sampleRate); + result = AudioObjectGetPropertyData(dev, &freqaddr, 0, NULL, &size, &sampleRate); + if (result == noErr) { + spec.freq = (int)sampleRate; + } + + size = sizeof(CFStringRef); + result = AudioObjectGetPropertyData(dev, &nameaddr, 0, NULL, &size, &cfstr); + if (result != kAudioHardwareNoError) { + continue; + } + + len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr), + kCFStringEncodingUTF8); + + ptr = (char *)SDL_malloc(len + 1); + usable = ((ptr != NULL) && + (CFStringGetCString(cfstr, ptr, len + 1, kCFStringEncodingUTF8))); + + CFRelease(cfstr); + + if (usable) { + len = strlen(ptr); + /* Some devices have whitespace at the end...trim it. */ + while ((len > 0) && (ptr[len - 1] == ' ')) { + len--; + } + usable = (len > 0); + } + + if (usable) { + ptr[len] = '\0'; + +#if DEBUG_COREAUDIO + printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n", + ((iscapture) ? "capture" : "output"), + (int)i, ptr, (int)dev); +#endif + addfn(ptr, &spec, iscapture, dev, addfndata); + } + SDL_free(ptr); /* addfn() would have copied the string. */ + } +} + +static void free_audio_device_list(AudioDeviceList **list) +{ + AudioDeviceList *item = *list; + while (item) { + AudioDeviceList *next = item->next; + SDL_free(item); + item = next; + } + *list = NULL; +} + +static void COREAUDIO_DetectDevices(void) +{ + build_device_list(SDL_TRUE, addToDevList, NULL); + build_device_list(SDL_FALSE, addToDevList, NULL); +} + +static void build_device_change_list(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data) +{ + AudioDeviceList **list = (AudioDeviceList **)data; + AudioDeviceList *item; + for (item = *list; item != NULL; item = item->next) { + if (item->devid == devId) { + item->alive = SDL_TRUE; + return; + } + } + + add_to_internal_dev_list(iscapture, devId); /* new device, add it. */ + SDL_AddAudioDevice(iscapture, name, spec, (void *)((size_t)devId)); +} + +static void reprocess_device_list(const int iscapture, AudioDeviceList **list) +{ + AudioDeviceList *item; + AudioDeviceList *prev = NULL; + for (item = *list; item != NULL; item = item->next) { + item->alive = SDL_FALSE; + } + + build_device_list(iscapture, build_device_change_list, list); + + /* free items in the list that aren't still alive. */ + item = *list; + while (item != NULL) { + AudioDeviceList *next = item->next; + if (item->alive) { + prev = item; + } else { + SDL_RemoveAudioDevice(iscapture, (void *)((size_t)item->devid)); + if (prev) { + prev->next = item->next; + } else { + *list = item->next; + } + SDL_free(item); + } + item = next; + } +} + +/* this is called when the system's list of available audio devices changes. */ +static OSStatus device_list_changed(AudioObjectID systemObj, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data) +{ + reprocess_device_list(SDL_TRUE, &capture_devs); + reprocess_device_list(SDL_FALSE, &output_devs); + return 0; +} +#endif + +static int open_playback_devices; +static int open_capture_devices; +static int num_open_devices; +static SDL_AudioDevice **open_devices; + +#ifndef MACOSX_COREAUDIO + +static BOOL session_active = NO; + +static void pause_audio_devices(void) +{ + int i; + + if (!open_devices) { + return; + } + + for (i = 0; i < num_open_devices; ++i) { + SDL_AudioDevice *device = open_devices[i]; + if (device->hidden->audioQueue && !device->hidden->interrupted) { + AudioQueuePause(device->hidden->audioQueue); + } + } +} + +static void resume_audio_devices(void) +{ + int i; + + if (!open_devices) { + return; + } + + for (i = 0; i < num_open_devices; ++i) { + SDL_AudioDevice *device = open_devices[i]; + if (device->hidden->audioQueue && !device->hidden->interrupted) { + AudioQueueStart(device->hidden->audioQueue, NULL); + } + } +} + +static void interruption_begin(_THIS) +{ + if (this != NULL && this->hidden->audioQueue != NULL) { + this->hidden->interrupted = SDL_TRUE; + AudioQueuePause(this->hidden->audioQueue); + } +} + +static void interruption_end(_THIS) +{ + if (this != NULL && this->hidden != NULL && this->hidden->audioQueue != NULL && this->hidden->interrupted && AudioQueueStart(this->hidden->audioQueue, NULL) == AVAudioSessionErrorCodeNone) { + this->hidden->interrupted = SDL_FALSE; + } +} + +@interface SDLInterruptionListener : NSObject + +@property(nonatomic, assign) SDL_AudioDevice *device; + +@end + +@implementation SDLInterruptionListener + +- (void)audioSessionInterruption:(NSNotification *)note +{ + @synchronized(self) { + NSNumber *type = note.userInfo[AVAudioSessionInterruptionTypeKey]; + if (type.unsignedIntegerValue == AVAudioSessionInterruptionTypeBegan) { + interruption_begin(self.device); + } else { + interruption_end(self.device); + } + } +} + +- (void)applicationBecameActive:(NSNotification *)note +{ + @synchronized(self) { + interruption_end(self.device); + } +} + +@end + +static BOOL update_audio_session(_THIS, SDL_bool open, SDL_bool allow_playandrecord) +{ + @autoreleasepool { + AVAudioSession *session = [AVAudioSession sharedInstance]; + NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; + + NSString *category = AVAudioSessionCategoryPlayback; + NSString *mode = AVAudioSessionModeDefault; + NSUInteger options = AVAudioSessionCategoryOptionMixWithOthers; + NSError *err = nil; + const char *hint; + + hint = SDL_GetHint(SDL_HINT_AUDIO_CATEGORY); + if (hint) { + if (SDL_strcasecmp(hint, "AVAudioSessionCategoryAmbient") == 0) { + category = AVAudioSessionCategoryAmbient; + } else if (SDL_strcasecmp(hint, "AVAudioSessionCategorySoloAmbient") == 0) { + category = AVAudioSessionCategorySoloAmbient; + options &= ~AVAudioSessionCategoryOptionMixWithOthers; + } else if (SDL_strcasecmp(hint, "AVAudioSessionCategoryPlayback") == 0 || + SDL_strcasecmp(hint, "playback") == 0) { + category = AVAudioSessionCategoryPlayback; + options &= ~AVAudioSessionCategoryOptionMixWithOthers; + } else if (SDL_strcasecmp(hint, "AVAudioSessionCategoryPlayAndRecord") == 0 || + SDL_strcasecmp(hint, "playandrecord") == 0) { + if (allow_playandrecord) { + category = AVAudioSessionCategoryPlayAndRecord; + } + } + } else if (open_playback_devices && open_capture_devices) { + category = AVAudioSessionCategoryPlayAndRecord; + } else if (open_capture_devices) { + category = AVAudioSessionCategoryRecord; + } + +#if !TARGET_OS_TV + if (category == AVAudioSessionCategoryPlayAndRecord) { + options |= AVAudioSessionCategoryOptionDefaultToSpeaker; + } +#endif + if (category == AVAudioSessionCategoryRecord || + category == AVAudioSessionCategoryPlayAndRecord) { + /* AVAudioSessionCategoryOptionAllowBluetooth isn't available in the SDK for + Apple TV but is still needed in order to output to Bluetooth devices. + */ + options |= 0x4; /* AVAudioSessionCategoryOptionAllowBluetooth; */ + } + if (category == AVAudioSessionCategoryPlayAndRecord) { + options |= AVAudioSessionCategoryOptionAllowBluetoothA2DP | + AVAudioSessionCategoryOptionAllowAirPlay; + } + if (category == AVAudioSessionCategoryPlayback || + category == AVAudioSessionCategoryPlayAndRecord) { + options |= AVAudioSessionCategoryOptionDuckOthers; + } + + if ([session respondsToSelector:@selector(setCategory:mode:options:error:)]) { + if (![session.category isEqualToString:category] || session.categoryOptions != options) { + /* Stop the current session so we don't interrupt other application audio */ + pause_audio_devices(); + [session setActive:NO error:nil]; + session_active = NO; + + if (![session setCategory:category mode:mode options:options error:&err]) { + NSString *desc = err.description; + SDL_SetError("Could not set Audio Session category: %s", desc.UTF8String); + return NO; + } + } + } else { + if (![session.category isEqualToString:category]) { + /* Stop the current session so we don't interrupt other application audio */ + pause_audio_devices(); + [session setActive:NO error:nil]; + session_active = NO; + + if (![session setCategory:category error:&err]) { + NSString *desc = err.description; + SDL_SetError("Could not set Audio Session category: %s", desc.UTF8String); + return NO; + } + } + } + + if ((open_playback_devices || open_capture_devices) && !session_active) { + if (![session setActive:YES error:&err]) { + NSString *desc; + if ([err code] == AVAudioSessionErrorCodeResourceNotAvailable && + category == AVAudioSessionCategoryPlayAndRecord) { + return update_audio_session(this, open, SDL_FALSE); + } + + desc = err.description; + SDL_SetError("Could not activate Audio Session: %s", desc.UTF8String); + return NO; + } + session_active = YES; + resume_audio_devices(); + } else if (!open_playback_devices && !open_capture_devices && session_active) { + pause_audio_devices(); + [session setActive:NO error:nil]; + session_active = NO; + } + + if (open) { + SDLInterruptionListener *listener = [SDLInterruptionListener new]; + listener.device = this; + + [center addObserver:listener + selector:@selector(audioSessionInterruption:) + name:AVAudioSessionInterruptionNotification + object:session]; + + /* An interruption end notification is not guaranteed to be sent if + we were previously interrupted... resuming if needed when the app + becomes active seems to be the way to go. */ + // Note: object: below needs to be nil, as otherwise it filters by the object, and session doesn't send foreground / active notifications. johna + [center addObserver:listener + selector:@selector(applicationBecameActive:) + name:UIApplicationDidBecomeActiveNotification + object:nil]; + + [center addObserver:listener + selector:@selector(applicationBecameActive:) + name:UIApplicationWillEnterForegroundNotification + object:nil]; + + this->hidden->interruption_listener = CFBridgingRetain(listener); + } else { + SDLInterruptionListener *listener = nil; + listener = (SDLInterruptionListener *)CFBridgingRelease(this->hidden->interruption_listener); + [center removeObserver:listener]; + @synchronized(listener) { + listener.device = NULL; + } + } + } + + return YES; +} +#endif + +/* The AudioQueue callback */ +static void outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) +{ + SDL_AudioDevice *this = (SDL_AudioDevice *)inUserData; + + /* This flag is set before this->mixer_lock is destroyed during + shutdown, so check it before grabbing the mutex, and then check it + again _after_ in case we blocked waiting on the lock. */ + if (SDL_AtomicGet(&this->shutdown)) { + return; /* don't do anything, since we don't even want to enqueue this buffer again. */ + } + + SDL_LockMutex(this->mixer_lock); + + if (SDL_AtomicGet(&this->shutdown)) { + SDL_UnlockMutex(this->mixer_lock); + return; /* don't do anything, since we don't even want to enqueue this buffer again. */ + } + + if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) { + /* Supply silence if audio is not enabled or paused */ + SDL_memset(inBuffer->mAudioData, this->spec.silence, inBuffer->mAudioDataBytesCapacity); + if (this->stream) { + SDL_AudioStreamClear(this->stream); + } + } else if (this->stream) { + UInt32 remaining = inBuffer->mAudioDataBytesCapacity; + Uint8 *ptr = (Uint8 *)inBuffer->mAudioData; + + while (remaining > 0) { + if (SDL_AudioStreamAvailable(this->stream) == 0) { + /* Generate the data */ + (*this->callbackspec.callback)(this->callbackspec.userdata, + this->hidden->buffer, this->hidden->bufferSize); + this->hidden->bufferOffset = 0; + SDL_AudioStreamPut(this->stream, this->hidden->buffer, this->hidden->bufferSize); + } + if (SDL_AudioStreamAvailable(this->stream) > 0) { + int got; + UInt32 len = SDL_AudioStreamAvailable(this->stream); + if (len > remaining) { + len = remaining; + } + got = SDL_AudioStreamGet(this->stream, ptr, len); + SDL_assert((got < 0) || (got == len)); + if (got != len) { + SDL_memset(ptr, this->spec.silence, len); + } + ptr = ptr + len; + remaining -= len; + } + } + } else { + UInt32 remaining = inBuffer->mAudioDataBytesCapacity; + Uint8 *ptr = (Uint8 *)inBuffer->mAudioData; + + while (remaining > 0) { + UInt32 len; + if (this->hidden->bufferOffset >= this->hidden->bufferSize) { + /* Generate the data */ + (*this->callbackspec.callback)(this->callbackspec.userdata, + this->hidden->buffer, this->hidden->bufferSize); + this->hidden->bufferOffset = 0; + } + + len = this->hidden->bufferSize - this->hidden->bufferOffset; + if (len > remaining) { + len = remaining; + } + SDL_memcpy(ptr, (char *)this->hidden->buffer + this->hidden->bufferOffset, len); + ptr = ptr + len; + remaining -= len; + this->hidden->bufferOffset += len; + } + } + + AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL); + + inBuffer->mAudioDataByteSize = inBuffer->mAudioDataBytesCapacity; + + SDL_UnlockMutex(this->mixer_lock); +} + +static void inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, + const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions, + const AudioStreamPacketDescription *inPacketDescs) +{ + SDL_AudioDevice *this = (SDL_AudioDevice *)inUserData; + + if (SDL_AtomicGet(&this->shutdown)) { + return; /* don't do anything. */ + } + + /* ignore unless we're active. */ + if (!SDL_AtomicGet(&this->paused) && SDL_AtomicGet(&this->enabled)) { + const Uint8 *ptr = (const Uint8 *)inBuffer->mAudioData; + UInt32 remaining = inBuffer->mAudioDataByteSize; + while (remaining > 0) { + UInt32 len = this->hidden->bufferSize - this->hidden->bufferOffset; + if (len > remaining) { + len = remaining; + } + + SDL_memcpy((char *)this->hidden->buffer + this->hidden->bufferOffset, ptr, len); + ptr += len; + remaining -= len; + this->hidden->bufferOffset += len; + + if (this->hidden->bufferOffset >= this->hidden->bufferSize) { + SDL_LockMutex(this->mixer_lock); + (*this->callbackspec.callback)(this->callbackspec.userdata, this->hidden->buffer, this->hidden->bufferSize); + SDL_UnlockMutex(this->mixer_lock); + this->hidden->bufferOffset = 0; + } + } + } + + AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL); +} + +#ifdef MACOSX_COREAUDIO +static const AudioObjectPropertyAddress alive_address = { + kAudioDevicePropertyDeviceIsAlive, + kAudioObjectPropertyScopeGlobal, + kAudioObjectPropertyElementMain +}; + +static OSStatus device_unplugged(AudioObjectID devid, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data) +{ + SDL_AudioDevice *this = (SDL_AudioDevice *)data; + SDL_bool dead = SDL_FALSE; + UInt32 isAlive = 1; + UInt32 size = sizeof(isAlive); + OSStatus error; + + if (!SDL_AtomicGet(&this->enabled)) { + return 0; /* already known to be dead. */ + } + + error = AudioObjectGetPropertyData(this->hidden->deviceID, &alive_address, + 0, NULL, &size, &isAlive); + + if (error == kAudioHardwareBadDeviceError) { + dead = SDL_TRUE; /* device was unplugged. */ + } else if ((error == kAudioHardwareNoError) && (!isAlive)) { + dead = SDL_TRUE; /* device died in some other way. */ + } + + if (dead) { + SDL_OpenedAudioDeviceDisconnected(this); + } + + return 0; +} + +/* macOS calls this when the default device changed (if we have a default device open). */ +static OSStatus default_device_changed(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inUserData) +{ + SDL_AudioDevice *this = (SDL_AudioDevice *)inUserData; +#if DEBUG_COREAUDIO + printf("COREAUDIO: default device changed for SDL audio device %p!\n", this); +#endif + + /* due to a bug (?) in CoreAudio, this seems able to fire for a device pointer that's already closed, so check our list to make sure + the pointer is still valid before touching it. https://github.com/libsdl-org/SDL/issues/10432 */ + if (open_devices) { + int i; + for (i = 0; i < num_open_devices; i++) { + SDL_AudioDevice *device = open_devices[i]; + if (device == this) { + if (this->hidden) { + SDL_AtomicSet(&this->hidden->device_change_flag, 1); /* let the audioqueue thread pick up on this when safe to do so. */ + } + return noErr; + } + } + } + return noErr; +} +#endif + +static void COREAUDIO_CloseDevice(_THIS) +{ + const SDL_bool iscapture = this->iscapture; + int i; + +/* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */ +/* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */ +#ifdef MACOSX_COREAUDIO + if (this->handle != NULL) { /* we don't register this listener for default devices. */ + AudioObjectRemovePropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this); + } +#endif + + /* if callback fires again, feed silence; don't call into the app. */ + SDL_AtomicSet(&this->paused, 1); + + /* dispose of the audio queue before waiting on the thread, or it might stall for a long time! */ + if (this->hidden->audioQueue) { + AudioQueueFlush(this->hidden->audioQueue); + AudioQueueStop(this->hidden->audioQueue, 0); + AudioQueueDispose(this->hidden->audioQueue, 0); + } + + if (this->hidden->thread) { + SDL_assert(SDL_AtomicGet(&this->shutdown) != 0); /* should have been set by SDL_audio.c */ + SDL_WaitThread(this->hidden->thread, NULL); + } + + if (iscapture) { + open_capture_devices--; + } else { + open_playback_devices--; + } + +#ifndef MACOSX_COREAUDIO + update_audio_session(this, SDL_FALSE, SDL_TRUE); +#endif + + for (i = 0; i < num_open_devices; ++i) { + if (open_devices[i] == this) { + --num_open_devices; + if (i < num_open_devices) { + SDL_memmove(&open_devices[i], &open_devices[i + 1], sizeof(open_devices[i]) * (num_open_devices - i)); + } + break; + } + } + if (num_open_devices == 0) { + SDL_free(open_devices); + open_devices = NULL; + } + + if (this->hidden->ready_semaphore) { + SDL_DestroySemaphore(this->hidden->ready_semaphore); + } + + /* AudioQueueDispose() frees the actual buffer objects. */ + SDL_free(this->hidden->audioBuffer); + SDL_free(this->hidden->thread_error); + SDL_free(this->hidden->buffer); + SDL_free(this->hidden); +} + +#ifdef MACOSX_COREAUDIO +static int prepare_device(_THIS) +{ + void *handle = this->handle; + SDL_bool iscapture = this->iscapture; + AudioDeviceID devid = (AudioDeviceID)((size_t)handle); + OSStatus result = noErr; + UInt32 size = 0; + UInt32 alive = 0; + pid_t pid = 0; + + AudioObjectPropertyAddress addr = { + 0, + kAudioObjectPropertyScopeGlobal, + kAudioObjectPropertyElementMain + }; + + if (handle == NULL) { + size = sizeof(AudioDeviceID); + addr.mSelector = + ((iscapture) ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice); + result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, + 0, NULL, &size, &devid); + CHECK_RESULT("AudioHardwareGetProperty (default device)"); + } + + addr.mSelector = kAudioDevicePropertyDeviceIsAlive; + addr.mScope = iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; + + size = sizeof(alive); + result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &alive); + CHECK_RESULT("AudioDeviceGetProperty (kAudioDevicePropertyDeviceIsAlive)"); + + if (!alive) { + SDL_SetError("CoreAudio: requested device exists, but isn't alive."); + return 0; + } + + addr.mSelector = kAudioDevicePropertyHogMode; + size = sizeof(pid); + result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &pid); + + /* some devices don't support this property, so errors are fine here. */ + if ((result == noErr) && (pid != -1)) { + SDL_SetError("CoreAudio: requested device is being hogged."); + return 0; + } + + this->hidden->deviceID = devid; + return 1; +} + +static int assign_device_to_audioqueue(_THIS) +{ + const AudioObjectPropertyAddress prop = { + kAudioDevicePropertyDeviceUID, + this->iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMain + }; + + OSStatus result; + CFStringRef devuid; + UInt32 devuidsize = sizeof(devuid); + result = AudioObjectGetPropertyData(this->hidden->deviceID, &prop, 0, NULL, &devuidsize, &devuid); + CHECK_RESULT("AudioObjectGetPropertyData (kAudioDevicePropertyDeviceUID)"); + result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_CurrentDevice, &devuid, devuidsize); + CFRelease(devuid); /* Release devuid; we're done with it and AudioQueueSetProperty should have retained if it wants to keep it. */ + CHECK_RESULT("AudioQueueSetProperty (kAudioQueueProperty_CurrentDevice)"); + return 1; +} +#endif + +static int prepare_audioqueue(_THIS) +{ + const AudioStreamBasicDescription *strdesc = &this->hidden->strdesc; + const int iscapture = this->iscapture; + OSStatus result; + int i, numAudioBuffers = 2; + AudioChannelLayout layout; + double MINIMUM_AUDIO_BUFFER_TIME_MS; + const double msecs = (this->spec.samples / ((double)this->spec.freq)) * 1000.0; + ; + + SDL_assert(CFRunLoopGetCurrent() != NULL); + + if (iscapture) { + result = AudioQueueNewInput(strdesc, inputCallback, this, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 0, &this->hidden->audioQueue); + CHECK_RESULT("AudioQueueNewInput"); + } else { + result = AudioQueueNewOutput(strdesc, outputCallback, this, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 0, &this->hidden->audioQueue); + CHECK_RESULT("AudioQueueNewOutput"); + } + +#ifdef MACOSX_COREAUDIO + if (!assign_device_to_audioqueue(this)) { + return 0; + } + + /* only listen for unplugging on specific devices, not the default device, as that should + switch to a different device (or hang out silently if there _is_ no other device). */ + if (this->handle != NULL) { + /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */ + /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */ + /* Fire a callback if the device stops being "alive" (disconnected, etc). */ + /* If this fails, oh well, we won't notice a device had an extraordinary event take place. */ + AudioObjectAddPropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this); + } +#endif + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&this->spec); + + /* Set the channel layout for the audio queue */ + SDL_zero(layout); + switch (this->spec.channels) { + case 1: + // a standard mono stream + layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono; + break; + case 2: + // a standard stereo stream (L R) - implied playback + layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo; + break; + case 3: + // L R LFE + layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; + break; + case 4: + // front left, front right, back left, back right + layout.mChannelLayoutTag = kAudioChannelLayoutTag_Quadraphonic; + break; + case 5: + // L R LFE Ls Rs + layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_6; + break; + case 6: + // L R C LFE Ls Rs + layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_12; + break; +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000) || \ + (defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 101500) + case 7: + // L R C LFE Cs Ls Rs + if (@available(macOS 10.15, iOS 13, *)) { + layout.mChannelLayoutTag = kAudioChannelLayoutTag_WAVE_6_1; + } else { + return SDL_SetError("Unsupported audio channels"); + } + break; + case 8: + // L R C LFE Rls Rrs Ls Rs + if (@available(macOS 10.15, iOS 13, *)) { + layout.mChannelLayoutTag = kAudioChannelLayoutTag_WAVE_7_1; + } else { + return SDL_SetError("Unsupported audio channels"); + } + break; +#endif + default: + return SDL_SetError("Unsupported audio channels"); + } + if (layout.mChannelLayoutTag != 0) { + result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_ChannelLayout, &layout, sizeof(layout)); + CHECK_RESULT("AudioQueueSetProperty(kAudioQueueProperty_ChannelLayout)"); + } + + /* Allocate a sample buffer */ + this->hidden->bufferSize = this->spec.size; + this->hidden->bufferOffset = iscapture ? 0 : this->hidden->bufferSize; + + this->hidden->buffer = SDL_malloc(this->hidden->bufferSize); + if (this->hidden->buffer == NULL) { + SDL_OutOfMemory(); + return 0; + } + + /* Make sure we can feed the device a minimum amount of time */ + MINIMUM_AUDIO_BUFFER_TIME_MS = 15.0; +#if defined(__IPHONEOS__) + if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) { + /* Older iOS hardware, use 40 ms as a minimum time */ + MINIMUM_AUDIO_BUFFER_TIME_MS = 40.0; + } +#endif + if (msecs < MINIMUM_AUDIO_BUFFER_TIME_MS) { /* use more buffers if we have a VERY small sample set. */ + numAudioBuffers = ((int)SDL_ceil(MINIMUM_AUDIO_BUFFER_TIME_MS / msecs) * 2); + } + + this->hidden->numAudioBuffers = numAudioBuffers; + this->hidden->audioBuffer = SDL_calloc(1, sizeof(AudioQueueBufferRef) * numAudioBuffers); + if (this->hidden->audioBuffer == NULL) { + SDL_OutOfMemory(); + return 0; + } + +#if DEBUG_COREAUDIO + printf("COREAUDIO: numAudioBuffers == %d\n", numAudioBuffers); +#endif + + for (i = 0; i < numAudioBuffers; i++) { + result = AudioQueueAllocateBuffer(this->hidden->audioQueue, this->spec.size, &this->hidden->audioBuffer[i]); + CHECK_RESULT("AudioQueueAllocateBuffer"); + SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity); + this->hidden->audioBuffer[i]->mAudioDataByteSize = this->hidden->audioBuffer[i]->mAudioDataBytesCapacity; + /* !!! FIXME: should we use AudioQueueEnqueueBufferWithParameters and specify all frames be "trimmed" so these are immediately ready to refill with SDL callback data? */ + result = AudioQueueEnqueueBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i], 0, NULL); + CHECK_RESULT("AudioQueueEnqueueBuffer"); + } + + result = AudioQueueStart(this->hidden->audioQueue, NULL); + CHECK_RESULT("AudioQueueStart"); + + /* We're running! */ + return 1; +} + +static int audioqueue_thread(void *arg) +{ + SDL_AudioDevice *this = (SDL_AudioDevice *)arg; + int rc; + +#ifdef MACOSX_COREAUDIO + const AudioObjectPropertyAddress default_device_address = { + this->iscapture ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice, + kAudioObjectPropertyScopeGlobal, + kAudioObjectPropertyElementMain + }; + + if (this->handle == NULL) { /* opened the default device? Register to know if the user picks a new default. */ + /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */ + AudioObjectAddPropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this); + } +#endif + + rc = prepare_audioqueue(this); + if (!rc) { + this->hidden->thread_error = SDL_strdup(SDL_GetError()); + SDL_SemPost(this->hidden->ready_semaphore); + return 0; + } + + SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH); + + /* init was successful, alert parent thread and start running... */ + SDL_SemPost(this->hidden->ready_semaphore); + + while (!SDL_AtomicGet(&this->shutdown)) { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1); + +#ifdef MACOSX_COREAUDIO + if ((this->handle == NULL) && SDL_AtomicGet(&this->hidden->device_change_flag)) { + const AudioDeviceID prev_devid = this->hidden->deviceID; + SDL_AtomicSet(&this->hidden->device_change_flag, 0); + +#if DEBUG_COREAUDIO + printf("COREAUDIO: audioqueue_thread is trying to switch to new default device!\n"); +#endif + + /* if any of this fails, there's not much to do but wait to see if the user gives up + and quits (flagging the audioqueue for shutdown), or toggles to some other system + output device (in which case we'll try again). */ + if (prepare_device(this) && (prev_devid != this->hidden->deviceID)) { + AudioQueueStop(this->hidden->audioQueue, 1); + if (assign_device_to_audioqueue(this)) { + int i; + for (i = 0; i < this->hidden->numAudioBuffers; i++) { + SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity); + /* !!! FIXME: should we use AudioQueueEnqueueBufferWithParameters and specify all frames be "trimmed" so these are immediately ready to refill with SDL callback data? */ + AudioQueueEnqueueBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i], 0, NULL); + } + AudioQueueStart(this->hidden->audioQueue, NULL); + } + } + } +#endif + } + + if (!this->iscapture) { /* Drain off any pending playback. */ + const CFTimeInterval secs = (((this->spec.size / (SDL_AUDIO_BITSIZE(this->spec.format) / 8.0)) / this->spec.channels) / ((CFTimeInterval)this->spec.freq)) * 2.0; + CFRunLoopRunInMode(kCFRunLoopDefaultMode, secs, 0); + } + +#ifdef MACOSX_COREAUDIO + if (this->handle == NULL) { + /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */ + AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this); + } +#endif + + return 0; +} + +static int COREAUDIO_OpenDevice(_THIS, const char *devname) +{ + AudioStreamBasicDescription *strdesc; + SDL_AudioFormat test_format; + SDL_bool iscapture = this->iscapture; + SDL_AudioDevice **new_open_devices; + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); + if (this->hidden == NULL) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); + + strdesc = &this->hidden->strdesc; + + if (iscapture) { + open_capture_devices++; + } else { + open_playback_devices++; + } + + new_open_devices = (SDL_AudioDevice **)SDL_realloc(open_devices, sizeof(open_devices[0]) * (num_open_devices + 1)); + if (new_open_devices) { + open_devices = new_open_devices; + open_devices[num_open_devices++] = this; + } + +#ifndef MACOSX_COREAUDIO + if (!update_audio_session(this, SDL_TRUE, SDL_TRUE)) { + return -1; + } + + /* Stop CoreAudio from doing expensive audio rate conversion */ + @autoreleasepool { + AVAudioSession *session = [AVAudioSession sharedInstance]; + [session setPreferredSampleRate:this->spec.freq error:nil]; + this->spec.freq = (int)session.sampleRate; +#if TARGET_OS_TV + if (iscapture) { + [session setPreferredInputNumberOfChannels:this->spec.channels error:nil]; + this->spec.channels = session.preferredInputNumberOfChannels; + } else { + [session setPreferredOutputNumberOfChannels:this->spec.channels error:nil]; + this->spec.channels = session.preferredOutputNumberOfChannels; + } +#else + /* Calling setPreferredOutputNumberOfChannels seems to break audio output on iOS */ +#endif /* TARGET_OS_TV */ + } +#endif + + /* Setup a AudioStreamBasicDescription with the requested format */ + SDL_zerop(strdesc); + strdesc->mFormatID = kAudioFormatLinearPCM; + strdesc->mFormatFlags = kLinearPCMFormatFlagIsPacked; + strdesc->mChannelsPerFrame = this->spec.channels; + strdesc->mSampleRate = this->spec.freq; + strdesc->mFramesPerPacket = 1; + + for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { + /* CoreAudio handles most of SDL's formats natively, but not U16, apparently. */ + switch (test_format) { + case AUDIO_U8: + case AUDIO_S8: + case AUDIO_S16LSB: + case AUDIO_S16MSB: + case AUDIO_S32LSB: + case AUDIO_S32MSB: + case AUDIO_F32LSB: + case AUDIO_F32MSB: + break; + + default: + continue; + } + break; + } + + if (!test_format) { /* shouldn't happen, but just in case... */ + return SDL_SetError("%s: Unsupported audio format", "coreaudio"); + } + this->spec.format = test_format; + strdesc->mBitsPerChannel = SDL_AUDIO_BITSIZE(test_format); + if (SDL_AUDIO_ISBIGENDIAN(test_format)) { + strdesc->mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; + } + + if (SDL_AUDIO_ISFLOAT(test_format)) { + strdesc->mFormatFlags |= kLinearPCMFormatFlagIsFloat; + } else if (SDL_AUDIO_ISSIGNED(test_format)) { + strdesc->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger; + } + + strdesc->mBytesPerFrame = strdesc->mChannelsPerFrame * strdesc->mBitsPerChannel / 8; + strdesc->mBytesPerPacket = strdesc->mBytesPerFrame * strdesc->mFramesPerPacket; + +#ifdef MACOSX_COREAUDIO + if (!prepare_device(this)) { + return -1; + } +#endif + + /* This has to init in a new thread so it can get its own CFRunLoop. :/ */ + this->hidden->ready_semaphore = SDL_CreateSemaphore(0); + if (!this->hidden->ready_semaphore) { + return -1; /* oh well. */ + } + + this->hidden->thread = SDL_CreateThreadInternal(audioqueue_thread, "AudioQueue thread", 512 * 1024, this); + if (!this->hidden->thread) { + return -1; + } + + SDL_SemWait(this->hidden->ready_semaphore); + SDL_DestroySemaphore(this->hidden->ready_semaphore); + this->hidden->ready_semaphore = NULL; + + if ((this->hidden->thread != NULL) && (this->hidden->thread_error != NULL)) { + return SDL_SetError("%s", this->hidden->thread_error); + } + + return (this->hidden->thread != NULL) ? 0 : -1; +} + +#ifndef MACOSX_COREAUDIO +static int COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture) +{ + AVAudioSession *session = [AVAudioSession sharedInstance]; + + if (name != NULL) { + *name = NULL; + } + SDL_zerop(spec); + spec->freq = [session sampleRate]; + spec->channels = [session outputNumberOfChannels]; + return 0; +} +#else /* MACOSX_COREAUDIO */ +static int COREAUDIO_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture) +{ + AudioDeviceID devid; + AudioBufferList *buflist; + OSStatus result; + UInt32 size; + CFStringRef cfstr; + char *devname; + int usable; + double sampleRate; + CFIndex len; + + AudioObjectPropertyAddress addr = { + iscapture ? kAudioHardwarePropertyDefaultInputDevice + : kAudioHardwarePropertyDefaultOutputDevice, + iscapture ? kAudioDevicePropertyScopeInput + : kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMain + }; + AudioObjectPropertyAddress nameaddr = { + kAudioObjectPropertyName, + iscapture ? kAudioDevicePropertyScopeInput + : kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMain + }; + AudioObjectPropertyAddress freqaddr = { + kAudioDevicePropertyNominalSampleRate, + iscapture ? kAudioDevicePropertyScopeInput + : kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMain + }; + AudioObjectPropertyAddress bufaddr = { + kAudioDevicePropertyStreamConfiguration, + iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, + kAudioObjectPropertyElementMain + }; + + /* Get the Device ID */ + cfstr = NULL; + size = sizeof(AudioDeviceID); + result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, + 0, NULL, &size, &devid); + + if (result != noErr) { + return SDL_SetError("%s: Default Device ID not found", "coreaudio"); + } + + if (name != NULL) { + /* Use the Device ID to get the name */ + size = sizeof(CFStringRef); + result = AudioObjectGetPropertyData(devid, &nameaddr, 0, NULL, &size, &cfstr); + + if (result != noErr) { + return SDL_SetError("%s: Default Device Name not found", "coreaudio"); + } + + len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr), + kCFStringEncodingUTF8); + devname = (char *)SDL_malloc(len + 1); + usable = ((devname != NULL) && + (CFStringGetCString(cfstr, devname, len + 1, kCFStringEncodingUTF8))); + CFRelease(cfstr); + + if (usable) { + usable = 0; + len = strlen(devname); + /* Some devices have whitespace at the end...trim it. */ + while ((len > 0) && (devname[len - 1] == ' ')) { + len--; + usable = len; + } + } + + if (usable) { + devname[len] = '\0'; + } + *name = devname; + } + + /* Uses the Device ID to get the spec */ + SDL_zerop(spec); + + sampleRate = 0; + size = sizeof(sampleRate); + result = AudioObjectGetPropertyData(devid, &freqaddr, 0, NULL, &size, &sampleRate); + + if (result != noErr) { + return SDL_SetError("%s: Default Device Sample Rate not found", "coreaudio"); + } + + spec->freq = (int)sampleRate; + + result = AudioObjectGetPropertyDataSize(devid, &bufaddr, 0, NULL, &size); + if (result != noErr) { + return SDL_SetError("%s: Default Device Data Size not found", "coreaudio"); + } + + buflist = (AudioBufferList *)SDL_malloc(size); + if (buflist == NULL) { + return SDL_SetError("%s: Default Device Buffer List not found", "coreaudio"); + } + + result = AudioObjectGetPropertyData(devid, &bufaddr, 0, NULL, + &size, buflist); + + if (result == noErr) { + UInt32 j; + for (j = 0; j < buflist->mNumberBuffers; j++) { + spec->channels += buflist->mBuffers[j].mNumberChannels; + } + } + + SDL_free(buflist); + + if (spec->channels == 0) { + return SDL_SetError("%s: Default Device has no channels!", "coreaudio"); + } + + return 0; +} +#endif /* MACOSX_COREAUDIO */ + +static void COREAUDIO_Deinitialize(void) +{ +#ifdef MACOSX_COREAUDIO + AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &devlist_address, device_list_changed, NULL); + free_audio_device_list(&capture_devs); + free_audio_device_list(&output_devs); +#endif +} + +static SDL_bool COREAUDIO_Init(SDL_AudioDriverImpl *impl) +{ + /* Set the function pointers */ + impl->OpenDevice = COREAUDIO_OpenDevice; + impl->CloseDevice = COREAUDIO_CloseDevice; + impl->Deinitialize = COREAUDIO_Deinitialize; + impl->GetDefaultAudioInfo = COREAUDIO_GetDefaultAudioInfo; + +#ifdef MACOSX_COREAUDIO + impl->DetectDevices = COREAUDIO_DetectDevices; + AudioObjectAddPropertyListener(kAudioObjectSystemObject, &devlist_address, device_list_changed, NULL); +#else + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + impl->OnlyHasDefaultCaptureDevice = SDL_TRUE; +#endif + + impl->ProvidesOwnCallbackThread = SDL_TRUE; + impl->HasCaptureSupport = SDL_TRUE; + impl->SupportsNonPow2Samples = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap COREAUDIO_bootstrap = { + "coreaudio", "CoreAudio", COREAUDIO_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_COREAUDIO */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/directsound/SDL_directsound.c b/third_party/SDL2/src/audio/directsound/SDL_directsound.c new file mode 100644 index 00000000000..9d52c38399a --- /dev/null +++ b/third_party/SDL2/src/audio/directsound/SDL_directsound.c @@ -0,0 +1,659 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_DSOUND + +/* Allow access to a raw mixing buffer */ + +#include "SDL_timer.h" +#include "SDL_loadso.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_directsound.h" +#include +#ifdef HAVE_MMDEVICEAPI_H +#include "../../core/windows/SDL_immdevice.h" +#endif /* HAVE_MMDEVICEAPI_H */ + +#ifndef WAVE_FORMAT_IEEE_FLOAT +#define WAVE_FORMAT_IEEE_FLOAT 0x0003 +#endif + +/* For Vista+, we can enumerate DSound devices with IMMDevice */ +#ifdef HAVE_MMDEVICEAPI_H +static SDL_bool SupportsIMMDevice = SDL_FALSE; +#endif /* HAVE_MMDEVICEAPI_H */ + +/* DirectX function pointers for audio */ +static void *DSoundDLL = NULL; +typedef HRESULT(WINAPI *fnDirectSoundCreate8)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN); +typedef HRESULT(WINAPI *fnDirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID); +typedef HRESULT(WINAPI *fnDirectSoundCaptureCreate8)(LPCGUID, LPDIRECTSOUNDCAPTURE8 *, LPUNKNOWN); +typedef HRESULT(WINAPI *fnDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW, LPVOID); +static fnDirectSoundCreate8 pDirectSoundCreate8 = NULL; +static fnDirectSoundEnumerateW pDirectSoundEnumerateW = NULL; +static fnDirectSoundCaptureCreate8 pDirectSoundCaptureCreate8 = NULL; +static fnDirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW = NULL; + +static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; +static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; + +static void DSOUND_Unload(void) +{ + pDirectSoundCreate8 = NULL; + pDirectSoundEnumerateW = NULL; + pDirectSoundCaptureCreate8 = NULL; + pDirectSoundCaptureEnumerateW = NULL; + + if (DSoundDLL) { + SDL_UnloadObject(DSoundDLL); + DSoundDLL = NULL; + } +} + +static int DSOUND_Load(void) +{ + int loaded = 0; + + DSOUND_Unload(); + + DSoundDLL = SDL_LoadObject("DSOUND.DLL"); + if (!DSoundDLL) { + SDL_SetError("DirectSound: failed to load DSOUND.DLL"); + } else { +/* Now make sure we have DirectX 8 or better... */ +#define DSOUNDLOAD(f) \ + { \ + p##f = (fn##f)SDL_LoadFunction(DSoundDLL, #f); \ + if (!p##f) \ + loaded = 0; \ + } + loaded = 1; /* will reset if necessary. */ + DSOUNDLOAD(DirectSoundCreate8); + DSOUNDLOAD(DirectSoundEnumerateW); + DSOUNDLOAD(DirectSoundCaptureCreate8); + DSOUNDLOAD(DirectSoundCaptureEnumerateW); +#undef DSOUNDLOAD + + if (!loaded) { + SDL_SetError("DirectSound: System doesn't appear to have DX8."); + } + } + + if (!loaded) { + DSOUND_Unload(); + } + + return loaded; +} + +static int SetDSerror(const char *function, int code) +{ + const char *error; + + switch (code) { + case E_NOINTERFACE: + error = "Unsupported interface -- Is DirectX 8.0 or later installed?"; + break; + case DSERR_ALLOCATED: + error = "Audio device in use"; + break; + case DSERR_BADFORMAT: + error = "Unsupported audio format"; + break; + case DSERR_BUFFERLOST: + error = "Mixing buffer was lost"; + break; + case DSERR_CONTROLUNAVAIL: + error = "Control requested is not available"; + break; + case DSERR_INVALIDCALL: + error = "Invalid call for the current state"; + break; + case DSERR_INVALIDPARAM: + error = "Invalid parameter"; + break; + case DSERR_NODRIVER: + error = "No audio device found"; + break; + case DSERR_OUTOFMEMORY: + error = "Out of memory"; + break; + case DSERR_PRIOLEVELNEEDED: + error = "Caller doesn't have priority"; + break; + case DSERR_UNSUPPORTED: + error = "Function not supported"; + break; + default: + error = "Unknown DirectSound error"; + break; + } + + return SDL_SetError("%s: %s (0x%x)", function, error, code); +} + +static void DSOUND_FreeDeviceHandle(void *handle) +{ + SDL_free(handle); +} + +static int DSOUND_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture) +{ +#ifdef HAVE_MMDEVICEAPI_H + if (SupportsIMMDevice) { + return SDL_IMMDevice_GetDefaultAudioInfo(name, spec, iscapture); + } +#endif /* HAVE_MMDEVICEAPI_H */ + return SDL_Unsupported(); +} + +static BOOL CALLBACK FindAllDevs(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVOID data) +{ + const int iscapture = (int)((size_t)data); + if (guid != NULL) { /* skip default device */ + char *str = WIN_LookupAudioDeviceName(desc, guid); + if (str) { + LPGUID cpyguid = (LPGUID)SDL_malloc(sizeof(GUID)); + SDL_memcpy(cpyguid, guid, sizeof(GUID)); + + /* Note that spec is NULL, because we are required to connect to the + * device before getting the channel mask and output format, making + * this information inaccessible at enumeration time + */ + SDL_AddAudioDevice(iscapture, str, NULL, cpyguid); + SDL_free(str); /* addfn() makes a copy of this string. */ + } + } + return TRUE; /* keep enumerating. */ +} + +static void DSOUND_DetectDevices(void) +{ +#ifdef HAVE_MMDEVICEAPI_H + if (SupportsIMMDevice) { + SDL_IMMDevice_EnumerateEndpoints(SDL_TRUE); + } else { +#endif /* HAVE_MMDEVICEAPI_H */ + pDirectSoundCaptureEnumerateW(FindAllDevs, (void *)((size_t)1)); + pDirectSoundEnumerateW(FindAllDevs, (void *)((size_t)0)); +#ifdef HAVE_MMDEVICEAPI_H + } +#endif /* HAVE_MMDEVICEAPI_H*/ +} + +static void DSOUND_WaitDevice(_THIS) +{ + DWORD status = 0; + DWORD cursor = 0; + DWORD junk = 0; + HRESULT result = DS_OK; + + /* Semi-busy wait, since we have no way of getting play notification + on a primary mixing buffer located in hardware (DirectX 5.0) + */ + result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, + &junk, &cursor); + if (result != DS_OK) { + if (result == DSERR_BUFFERLOST) { + IDirectSoundBuffer_Restore(this->hidden->mixbuf); + } +#ifdef DEBUG_SOUND + SetDSerror("DirectSound GetCurrentPosition", result); +#endif + return; + } + + while ((cursor / this->spec.size) == this->hidden->lastchunk) { + /* FIXME: find out how much time is left and sleep that long */ + SDL_Delay(1); + + /* Try to restore a lost sound buffer */ + IDirectSoundBuffer_GetStatus(this->hidden->mixbuf, &status); + if (status & DSBSTATUS_BUFFERLOST) { + IDirectSoundBuffer_Restore(this->hidden->mixbuf); + IDirectSoundBuffer_GetStatus(this->hidden->mixbuf, &status); + if (status & DSBSTATUS_BUFFERLOST) { + break; + } + } + if (!(status & DSBSTATUS_PLAYING)) { + result = IDirectSoundBuffer_Play(this->hidden->mixbuf, 0, 0, + DSBPLAY_LOOPING); + if (result == DS_OK) { + continue; + } +#ifdef DEBUG_SOUND + SetDSerror("DirectSound Play", result); +#endif + return; + } + + /* Find out where we are playing */ + result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, + &junk, &cursor); + if (result != DS_OK) { + SetDSerror("DirectSound GetCurrentPosition", result); + return; + } + } +} + +static void DSOUND_PlayDevice(_THIS) +{ + /* Unlock the buffer, allowing it to play */ + if (this->hidden->locked_buf) { + IDirectSoundBuffer_Unlock(this->hidden->mixbuf, + this->hidden->locked_buf, + this->spec.size, NULL, 0); + } +} + +static Uint8 *DSOUND_GetDeviceBuf(_THIS) +{ + DWORD cursor = 0; + DWORD junk = 0; + HRESULT result = DS_OK; + DWORD rawlen = 0; + + /* Figure out which blocks to fill next */ + this->hidden->locked_buf = NULL; + result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, + &junk, &cursor); + if (result == DSERR_BUFFERLOST) { + IDirectSoundBuffer_Restore(this->hidden->mixbuf); + result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, + &junk, &cursor); + } + if (result != DS_OK) { + SetDSerror("DirectSound GetCurrentPosition", result); + return NULL; + } + cursor /= this->spec.size; +#ifdef DEBUG_SOUND + /* Detect audio dropouts */ + { + DWORD spot = cursor; + if (spot < this->hidden->lastchunk) { + spot += this->hidden->num_buffers; + } + if (spot > this->hidden->lastchunk + 1) { + fprintf(stderr, "Audio dropout, missed %d fragments\n", + (spot - (this->hidden->lastchunk + 1))); + } + } +#endif + this->hidden->lastchunk = cursor; + cursor = (cursor + 1) % this->hidden->num_buffers; + cursor *= this->spec.size; + + /* Lock the audio buffer */ + result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor, + this->spec.size, + (LPVOID *)&this->hidden->locked_buf, + &rawlen, NULL, &junk, 0); + if (result == DSERR_BUFFERLOST) { + IDirectSoundBuffer_Restore(this->hidden->mixbuf); + result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor, + this->spec.size, + (LPVOID *)&this->hidden->locked_buf, &rawlen, NULL, + &junk, 0); + } + if (result != DS_OK) { + SetDSerror("DirectSound Lock", result); + return NULL; + } + return this->hidden->locked_buf; +} + +static int DSOUND_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + struct SDL_PrivateAudioData *h = this->hidden; + DWORD junk, cursor, ptr1len, ptr2len; + VOID *ptr1, *ptr2; + + SDL_assert(buflen == this->spec.size); + + while (SDL_TRUE) { + if (SDL_AtomicGet(&this->shutdown)) { /* in case the buffer froze... */ + SDL_memset(buffer, this->spec.silence, buflen); + return buflen; + } + + if (IDirectSoundCaptureBuffer_GetCurrentPosition(h->capturebuf, &junk, &cursor) != DS_OK) { + return -1; + } + if ((cursor / this->spec.size) == h->lastchunk) { + SDL_Delay(1); /* FIXME: find out how much time is left and sleep that long */ + } else { + break; + } + } + + if (IDirectSoundCaptureBuffer_Lock(h->capturebuf, h->lastchunk * this->spec.size, this->spec.size, &ptr1, &ptr1len, &ptr2, &ptr2len, 0) != DS_OK) { + return -1; + } + + SDL_assert(ptr1len == this->spec.size); + SDL_assert(ptr2 == NULL); + SDL_assert(ptr2len == 0); + + SDL_memcpy(buffer, ptr1, ptr1len); + + if (IDirectSoundCaptureBuffer_Unlock(h->capturebuf, ptr1, ptr1len, ptr2, ptr2len) != DS_OK) { + return -1; + } + + h->lastchunk = (h->lastchunk + 1) % h->num_buffers; + + return ptr1len; +} + +static void DSOUND_FlushCapture(_THIS) +{ + struct SDL_PrivateAudioData *h = this->hidden; + DWORD junk, cursor; + if (IDirectSoundCaptureBuffer_GetCurrentPosition(h->capturebuf, &junk, &cursor) == DS_OK) { + h->lastchunk = cursor / this->spec.size; + } +} + +static void DSOUND_CloseDevice(_THIS) +{ + if (this->hidden->mixbuf) { + IDirectSoundBuffer_Stop(this->hidden->mixbuf); + IDirectSoundBuffer_Release(this->hidden->mixbuf); + } + if (this->hidden->sound) { + IDirectSound_Release(this->hidden->sound); + } + if (this->hidden->capturebuf) { + IDirectSoundCaptureBuffer_Stop(this->hidden->capturebuf); + IDirectSoundCaptureBuffer_Release(this->hidden->capturebuf); + } + if (this->hidden->capture) { + IDirectSoundCapture_Release(this->hidden->capture); + } + SDL_free(this->hidden); +} + +/* This function tries to create a secondary audio buffer, and returns the + number of audio chunks available in the created buffer. This is for + playback devices, not capture. +*/ +static int CreateSecondary(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt) +{ + LPDIRECTSOUND sndObj = this->hidden->sound; + LPDIRECTSOUNDBUFFER *sndbuf = &this->hidden->mixbuf; + HRESULT result = DS_OK; + DSBUFFERDESC format; + LPVOID pvAudioPtr1, pvAudioPtr2; + DWORD dwAudioBytes1, dwAudioBytes2; + + /* Try to create the secondary buffer */ + SDL_zero(format); + format.dwSize = sizeof(format); + format.dwFlags = DSBCAPS_GETCURRENTPOSITION2; + format.dwFlags |= DSBCAPS_GLOBALFOCUS; + format.dwBufferBytes = bufsize; + format.lpwfxFormat = wfmt; + result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL); + if (result != DS_OK) { + return SetDSerror("DirectSound CreateSoundBuffer", result); + } + IDirectSoundBuffer_SetFormat(*sndbuf, wfmt); + + /* Silence the initial audio buffer */ + result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes, + (LPVOID *)&pvAudioPtr1, &dwAudioBytes1, + (LPVOID *)&pvAudioPtr2, &dwAudioBytes2, + DSBLOCK_ENTIREBUFFER); + if (result == DS_OK) { + SDL_memset(pvAudioPtr1, this->spec.silence, dwAudioBytes1); + IDirectSoundBuffer_Unlock(*sndbuf, + (LPVOID)pvAudioPtr1, dwAudioBytes1, + (LPVOID)pvAudioPtr2, dwAudioBytes2); + } + + /* We're ready to go */ + return 0; +} + +/* This function tries to create a capture buffer, and returns the + number of audio chunks available in the created buffer. This is for + capture devices, not playback. +*/ +static int CreateCaptureBuffer(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt) +{ + LPDIRECTSOUNDCAPTURE capture = this->hidden->capture; + LPDIRECTSOUNDCAPTUREBUFFER *capturebuf = &this->hidden->capturebuf; + DSCBUFFERDESC format; + HRESULT result; + + SDL_zero(format); + format.dwSize = sizeof(format); + format.dwFlags = DSCBCAPS_WAVEMAPPED; + format.dwBufferBytes = bufsize; + format.lpwfxFormat = wfmt; + + result = IDirectSoundCapture_CreateCaptureBuffer(capture, &format, capturebuf, NULL); + if (result != DS_OK) { + return SetDSerror("DirectSound CreateCaptureBuffer", result); + } + + result = IDirectSoundCaptureBuffer_Start(*capturebuf, DSCBSTART_LOOPING); + if (result != DS_OK) { + IDirectSoundCaptureBuffer_Release(*capturebuf); + return SetDSerror("DirectSound Start", result); + } + +#if 0 + /* presumably this starts at zero, but just in case... */ + result = IDirectSoundCaptureBuffer_GetCurrentPosition(*capturebuf, &junk, &cursor); + if (result != DS_OK) { + IDirectSoundCaptureBuffer_Stop(*capturebuf); + IDirectSoundCaptureBuffer_Release(*capturebuf); + return SetDSerror("DirectSound GetCurrentPosition", result); + } + + this->hidden->lastchunk = cursor / this->spec.size; +#endif + + return 0; +} + +static int DSOUND_OpenDevice(_THIS, const char *devname) +{ + const DWORD numchunks = 8; + HRESULT result; + SDL_bool tried_format = SDL_FALSE; + SDL_bool iscapture = this->iscapture; + SDL_AudioFormat test_format; + LPGUID guid = (LPGUID)this->handle; + DWORD bufsize; + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); + + /* Open the audio device */ + if (iscapture) { + result = pDirectSoundCaptureCreate8(guid, &this->hidden->capture, NULL); + if (result != DS_OK) { + return SetDSerror("DirectSoundCaptureCreate8", result); + } + } else { + result = pDirectSoundCreate8(guid, &this->hidden->sound, NULL); + if (result != DS_OK) { + return SetDSerror("DirectSoundCreate8", result); + } + result = IDirectSound_SetCooperativeLevel(this->hidden->sound, + GetDesktopWindow(), + DSSCL_NORMAL); + if (result != DS_OK) { + return SetDSerror("DirectSound SetCooperativeLevel", result); + } + } + + for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { + switch (test_format) { + case AUDIO_U8: + case AUDIO_S16: + case AUDIO_S32: + case AUDIO_F32: + tried_format = SDL_TRUE; + + this->spec.format = test_format; + + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(&this->spec); + + bufsize = numchunks * this->spec.size; + if ((bufsize < DSBSIZE_MIN) || (bufsize > DSBSIZE_MAX)) { + SDL_SetError("Sound buffer size must be between %d and %d", + (int)((DSBSIZE_MIN < numchunks) ? 1 : DSBSIZE_MIN / numchunks), + (int)(DSBSIZE_MAX / numchunks)); + } else { + int rc; + WAVEFORMATEXTENSIBLE wfmt; + SDL_zero(wfmt); + if (this->spec.channels > 2) { + wfmt.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + wfmt.Format.cbSize = sizeof(wfmt) - sizeof(WAVEFORMATEX); + + if (SDL_AUDIO_ISFLOAT(this->spec.format)) { + SDL_memcpy(&wfmt.SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID)); + } else { + SDL_memcpy(&wfmt.SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)); + } + wfmt.Samples.wValidBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format); + + switch (this->spec.channels) { + case 3: /* 3.0 (or 2.1) */ + wfmt.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER; + break; + case 4: /* 4.0 */ + wfmt.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; + break; + case 5: /* 5.0 (or 4.1) */ + wfmt.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; + break; + case 6: /* 5.1 */ + wfmt.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; + break; + case 7: /* 6.1 */ + wfmt.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_BACK_CENTER; + break; + case 8: /* 7.1 */ + wfmt.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT; + break; + default: + SDL_assert(0 && "Unsupported channel count!"); + break; + } + } else if (SDL_AUDIO_ISFLOAT(this->spec.format)) { + wfmt.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT; + } else { + wfmt.Format.wFormatTag = WAVE_FORMAT_PCM; + } + + wfmt.Format.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format); + wfmt.Format.nChannels = this->spec.channels; + wfmt.Format.nSamplesPerSec = this->spec.freq; + wfmt.Format.nBlockAlign = wfmt.Format.nChannels * (wfmt.Format.wBitsPerSample / 8); + wfmt.Format.nAvgBytesPerSec = wfmt.Format.nSamplesPerSec * wfmt.Format.nBlockAlign; + + rc = iscapture ? CreateCaptureBuffer(this, bufsize, (WAVEFORMATEX *)&wfmt) : CreateSecondary(this, bufsize, (WAVEFORMATEX *)&wfmt); + if (rc == 0) { + this->hidden->num_buffers = numchunks; + break; + } + } + continue; + default: + continue; + } + break; + } + + if (!test_format) { + if (tried_format) { + return -1; /* CreateSecondary() should have called SDL_SetError(). */ + } + return SDL_SetError("%s: Unsupported audio format", "directsound"); + } + + /* Playback buffers will auto-start playing in DSOUND_WaitDevice() */ + + return 0; /* good to go. */ +} + +static void DSOUND_Deinitialize(void) +{ +#ifdef HAVE_MMDEVICEAPI_H + if (SupportsIMMDevice) { + SDL_IMMDevice_Quit(); + SupportsIMMDevice = SDL_FALSE; + } +#endif /* HAVE_MMDEVICEAPI_H */ + DSOUND_Unload(); +} + +static SDL_bool DSOUND_Init(SDL_AudioDriverImpl *impl) +{ + if (!DSOUND_Load()) { + return SDL_FALSE; + } + +#ifdef HAVE_MMDEVICEAPI_H + SupportsIMMDevice = !(SDL_IMMDevice_Init() < 0); +#endif /* HAVE_MMDEVICEAPI_H */ + + /* Set the function pointers */ + impl->DetectDevices = DSOUND_DetectDevices; + impl->OpenDevice = DSOUND_OpenDevice; + impl->PlayDevice = DSOUND_PlayDevice; + impl->WaitDevice = DSOUND_WaitDevice; + impl->GetDeviceBuf = DSOUND_GetDeviceBuf; + impl->CaptureFromDevice = DSOUND_CaptureFromDevice; + impl->FlushCapture = DSOUND_FlushCapture; + impl->CloseDevice = DSOUND_CloseDevice; + impl->FreeDeviceHandle = DSOUND_FreeDeviceHandle; + impl->Deinitialize = DSOUND_Deinitialize; + impl->GetDefaultAudioInfo = DSOUND_GetDefaultAudioInfo; + + impl->HasCaptureSupport = SDL_TRUE; + impl->SupportsNonPow2Samples = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap DSOUND_bootstrap = { + "directsound", "DirectSound", DSOUND_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_DSOUND */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/directsound/SDL_directsound.h b/third_party/SDL2/src/audio/directsound/SDL_directsound.h new file mode 100644 index 00000000000..6de044a2d27 --- /dev/null +++ b/third_party/SDL2/src/audio/directsound/SDL_directsound.h @@ -0,0 +1,47 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_directsound_h_ +#define SDL_directsound_h_ + +#include "../../core/windows/SDL_directx.h" + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +/* The DirectSound objects */ +struct SDL_PrivateAudioData +{ + LPDIRECTSOUND sound; + LPDIRECTSOUNDBUFFER mixbuf; + LPDIRECTSOUNDCAPTURE capture; + LPDIRECTSOUNDCAPTUREBUFFER capturebuf; + int num_buffers; + DWORD lastchunk; + Uint8 *locked_buf; +}; + +#endif /* SDL_directsound_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/disk/SDL_diskaudio.c b/third_party/SDL2/src/audio/disk/SDL_diskaudio.c new file mode 100644 index 00000000000..49a39f7d340 --- /dev/null +++ b/third_party/SDL2/src/audio/disk/SDL_diskaudio.c @@ -0,0 +1,197 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_DISK + +/* Output raw audio data to a file. */ + +#ifdef HAVE_STDIO_H +#include +#endif + +#include "SDL_rwops.h" +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_diskaudio.h" + +/* !!! FIXME: these should be SDL hints, not environment variables. */ +/* environment variables and defaults. */ +#define DISKENVR_OUTFILE "SDL_DISKAUDIOFILE" +#define DISKDEFAULT_OUTFILE "sdlaudio.raw" +#define DISKENVR_INFILE "SDL_DISKAUDIOFILEIN" +#define DISKDEFAULT_INFILE "sdlaudio-in.raw" +#define DISKENVR_IODELAY "SDL_DISKAUDIODELAY" + +/* This function waits until it is possible to write a full sound buffer */ +static void DISKAUDIO_WaitDevice(_THIS) +{ + SDL_Delay(_this->hidden->io_delay); +} + +static void DISKAUDIO_PlayDevice(_THIS) +{ + const size_t written = SDL_RWwrite(_this->hidden->io, + _this->hidden->mixbuf, + 1, _this->spec.size); + + /* If we couldn't write, assume fatal error for now */ + if (written != _this->spec.size) { + SDL_OpenedAudioDeviceDisconnected(_this); + } +#ifdef DEBUG_AUDIO + fprintf(stderr, "Wrote %d bytes of audio data\n", written); +#endif +} + +static Uint8 *DISKAUDIO_GetDeviceBuf(_THIS) +{ + return _this->hidden->mixbuf; +} + +static int DISKAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + struct SDL_PrivateAudioData *h = _this->hidden; + const int origbuflen = buflen; + + SDL_Delay(h->io_delay); + + if (h->io) { + const size_t br = SDL_RWread(h->io, buffer, 1, buflen); + buflen -= (int)br; + buffer = ((Uint8 *)buffer) + br; + if (buflen > 0) { /* EOF (or error, but whatever). */ + SDL_RWclose(h->io); + h->io = NULL; + } + } + + /* if we ran out of file, just write silence. */ + SDL_memset(buffer, _this->spec.silence, buflen); + + return origbuflen; +} + +static void DISKAUDIO_FlushCapture(_THIS) +{ + /* no op...we don't advance the file pointer or anything. */ +} + +static void DISKAUDIO_CloseDevice(_THIS) +{ + if (_this->hidden->io) { + SDL_RWclose(_this->hidden->io); + } + SDL_free(_this->hidden->mixbuf); + SDL_free(_this->hidden); +} + +static const char *get_filename(const SDL_bool iscapture, const char *devname) +{ + if (!devname) { + devname = SDL_getenv(iscapture ? DISKENVR_INFILE : DISKENVR_OUTFILE); + if (!devname) { + devname = iscapture ? DISKDEFAULT_INFILE : DISKDEFAULT_OUTFILE; + } + } + return devname; +} + +static int DISKAUDIO_OpenDevice(_THIS, const char *devname) +{ + void *handle = _this->handle; + /* handle != NULL means "user specified the placeholder name on the fake detected device list" */ + SDL_bool iscapture = _this->iscapture; + const char *fname = get_filename(iscapture, handle ? NULL : devname); + const char *envr = SDL_getenv(DISKENVR_IODELAY); + + _this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc(sizeof(*_this->hidden)); + if (!_this->hidden) { + return SDL_OutOfMemory(); + } + SDL_zerop(_this->hidden); + + if (envr) { + _this->hidden->io_delay = SDL_atoi(envr); + } else { + _this->hidden->io_delay = ((_this->spec.samples * 1000) / _this->spec.freq); + } + + /* Open the audio device */ + _this->hidden->io = SDL_RWFromFile(fname, iscapture ? "rb" : "wb"); + if (!_this->hidden->io) { + return -1; + } + + /* Allocate mixing buffer */ + if (!iscapture) { + _this->hidden->mixbuf = (Uint8 *)SDL_malloc(_this->spec.size); + if (!_this->hidden->mixbuf) { + return SDL_OutOfMemory(); + } + SDL_memset(_this->hidden->mixbuf, _this->spec.silence, _this->spec.size); + } + + SDL_LogCritical(SDL_LOG_CATEGORY_AUDIO, + "You are using the SDL disk i/o audio driver!\n"); + SDL_LogCritical(SDL_LOG_CATEGORY_AUDIO, + " %s file [%s].\n", iscapture ? "Reading from" : "Writing to", + fname); + + /* We're ready to rock and roll. :-) */ + return 0; +} + +static void DISKAUDIO_DetectDevices(void) +{ + SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *)0x1); + SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *)0x2); +} + +static SDL_bool DISKAUDIO_Init(SDL_AudioDriverImpl *impl) +{ + /* Set the function pointers */ + impl->OpenDevice = DISKAUDIO_OpenDevice; + impl->WaitDevice = DISKAUDIO_WaitDevice; + impl->PlayDevice = DISKAUDIO_PlayDevice; + impl->GetDeviceBuf = DISKAUDIO_GetDeviceBuf; + impl->CaptureFromDevice = DISKAUDIO_CaptureFromDevice; + impl->FlushCapture = DISKAUDIO_FlushCapture; + + impl->CloseDevice = DISKAUDIO_CloseDevice; + impl->DetectDevices = DISKAUDIO_DetectDevices; + + impl->AllowsArbitraryDeviceNames = SDL_TRUE; + impl->HasCaptureSupport = SDL_TRUE; + impl->SupportsNonPow2Samples = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap DISKAUDIO_bootstrap = { + "disk", "direct-to-disk audio", DISKAUDIO_Init, SDL_TRUE +}; + +#endif /* SDL_AUDIO_DRIVER_DISK */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/disk/SDL_diskaudio.h b/third_party/SDL2/src/audio/disk/SDL_diskaudio.h new file mode 100644 index 00000000000..a7e7e01d92f --- /dev/null +++ b/third_party/SDL2/src/audio/disk/SDL_diskaudio.h @@ -0,0 +1,41 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_diskaudio_h_ +#define SDL_diskaudio_h_ + +#include "SDL_rwops.h" +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *_this + +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + SDL_RWops *io; + Uint32 io_delay; + Uint8 *mixbuf; +}; + +#endif /* SDL_diskaudio_h_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/dsp/SDL_dspaudio.c b/third_party/SDL2/src/audio/dsp/SDL_dspaudio.c new file mode 100644 index 00000000000..ffba531aa64 --- /dev/null +++ b/third_party/SDL2/src/audio/dsp/SDL_dspaudio.c @@ -0,0 +1,318 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_OSS + +/* Allow access to a raw mixing buffer */ + +#include /* For perror() */ +#include /* For strerror() */ +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "../SDL_audiodev_c.h" +#include "SDL_dspaudio.h" + +static void DSP_DetectDevices(void) +{ + SDL_EnumUnixAudioDevices(0, NULL); +} + +static void DSP_CloseDevice(_THIS) +{ + if (this->hidden->audio_fd >= 0) { + close(this->hidden->audio_fd); + } + SDL_free(this->hidden->mixbuf); + SDL_free(this->hidden); +} + +static int DSP_OpenDevice(_THIS, const char *devname) +{ + SDL_bool iscapture = this->iscapture; + const int flags = ((iscapture) ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT); + int format; + int value; + int frag_spec; + SDL_AudioFormat test_format; + + /* We don't care what the devname is...we'll try to open anything. */ + /* ...but default to first name in the list... */ + if (!devname) { + devname = SDL_GetAudioDeviceName(0, iscapture); + if (!devname) { + return SDL_SetError("No such audio device"); + } + } + + /* Make sure fragment size stays a power of 2, or OSS fails. */ + /* I don't know which of these are actually legal values, though... */ + if (this->spec.channels > 8) { + this->spec.channels = 8; + } else if (this->spec.channels > 4) { + this->spec.channels = 4; + } else if (this->spec.channels > 2) { + this->spec.channels = 2; + } + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc(sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); + + /* Open the audio device */ + this->hidden->audio_fd = open(devname, flags | O_CLOEXEC, 0); + if (this->hidden->audio_fd < 0) { + return SDL_SetError("Couldn't open %s: %s", devname, strerror(errno)); + } + + /* Make the file descriptor use blocking i/o with fcntl() */ + { + long ctlflags; + ctlflags = fcntl(this->hidden->audio_fd, F_GETFL); + ctlflags &= ~O_NONBLOCK; + if (fcntl(this->hidden->audio_fd, F_SETFL, ctlflags) < 0) { + return SDL_SetError("Couldn't set audio blocking mode"); + } + } + + /* Get a list of supported hardware formats */ + if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0) { + perror("SNDCTL_DSP_GETFMTS"); + return SDL_SetError("Couldn't get audio format list"); + } + + /* Try for a closest match on audio format */ + format = 0; + for (test_format = SDL_FirstAudioFormat(this->spec.format); + !format && test_format;) { +#ifdef DEBUG_AUDIO + fprintf(stderr, "Trying format 0x%4.4x\n", test_format); +#endif + switch (test_format) { + case AUDIO_U8: + if (value & AFMT_U8) { + format = AFMT_U8; + } + break; + case AUDIO_S16LSB: + if (value & AFMT_S16_LE) { + format = AFMT_S16_LE; + } + break; + case AUDIO_S16MSB: + if (value & AFMT_S16_BE) { + format = AFMT_S16_BE; + } + break; +#if 0 +/* + * These formats are not used by any real life systems so they are not + * needed here. + */ + case AUDIO_S8: + if (value & AFMT_S8) { + format = AFMT_S8; + } + break; + case AUDIO_U16LSB: + if (value & AFMT_U16_LE) { + format = AFMT_U16_LE; + } + break; + case AUDIO_U16MSB: + if (value & AFMT_U16_BE) { + format = AFMT_U16_BE; + } + break; +#endif + default: + format = 0; + break; + } + if (!format) { + test_format = SDL_NextAudioFormat(); + } + } + if (format == 0) { + return SDL_SetError("Couldn't find any hardware audio formats"); + } + this->spec.format = test_format; + + /* Set the audio format */ + value = format; + if ((ioctl(this->hidden->audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || + (value != format)) { + perror("SNDCTL_DSP_SETFMT"); + return SDL_SetError("Couldn't set audio format"); + } + + /* Set the number of channels of output */ + value = this->spec.channels; + if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0) { + perror("SNDCTL_DSP_CHANNELS"); + return SDL_SetError("Cannot set the number of channels"); + } + this->spec.channels = value; + + /* Set the DSP frequency */ + value = this->spec.freq; + if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_SPEED, &value) < 0) { + perror("SNDCTL_DSP_SPEED"); + return SDL_SetError("Couldn't set audio frequency"); + } + this->spec.freq = value; + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&this->spec); + + /* Determine the power of two of the fragment size */ + for (frag_spec = 0; (0x01U << frag_spec) < this->spec.size; ++frag_spec) { + } + if ((0x01U << frag_spec) != this->spec.size) { + return SDL_SetError("Fragment size must be a power of two"); + } + frag_spec |= 0x00020000; /* two fragments, for low latency */ + + /* Set the audio buffering parameters */ +#ifdef DEBUG_AUDIO + fprintf(stderr, "Requesting %d fragments of size %d\n", + (frag_spec >> 16), 1 << (frag_spec & 0xFFFF)); +#endif + if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0) { + perror("SNDCTL_DSP_SETFRAGMENT"); + } +#ifdef DEBUG_AUDIO + { + audio_buf_info info; + ioctl(this->hidden->audio_fd, SNDCTL_DSP_GETOSPACE, &info); + fprintf(stderr, "fragments = %d\n", info.fragments); + fprintf(stderr, "fragstotal = %d\n", info.fragstotal); + fprintf(stderr, "fragsize = %d\n", info.fragsize); + fprintf(stderr, "bytes = %d\n", info.bytes); + } +#endif + + /* Allocate mixing buffer */ + if (!iscapture) { + this->hidden->mixlen = this->spec.size; + this->hidden->mixbuf = (Uint8 *)SDL_malloc(this->hidden->mixlen); + if (!this->hidden->mixbuf) { + return SDL_OutOfMemory(); + } + SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); + } + + /* We're ready to rock and roll. :-) */ + return 0; +} + +static void DSP_PlayDevice(_THIS) +{ + struct SDL_PrivateAudioData *h = this->hidden; + if (write(h->audio_fd, h->mixbuf, h->mixlen) == -1) { + perror("Audio write"); + SDL_OpenedAudioDeviceDisconnected(this); + } +#ifdef DEBUG_AUDIO + fprintf(stderr, "Wrote %d bytes of audio data\n", h->mixlen); +#endif +} + +static Uint8 *DSP_GetDeviceBuf(_THIS) +{ + return this->hidden->mixbuf; +} + +static int DSP_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + return (int)read(this->hidden->audio_fd, buffer, buflen); +} + +static void DSP_FlushCapture(_THIS) +{ + struct SDL_PrivateAudioData *h = this->hidden; + audio_buf_info info; + if (ioctl(h->audio_fd, SNDCTL_DSP_GETISPACE, &info) == 0) { + while (info.bytes > 0) { + char buf[512]; + const size_t len = SDL_min(sizeof(buf), info.bytes); + const ssize_t br = read(h->audio_fd, buf, len); + if (br <= 0) { + break; + } + info.bytes -= br; + } + } +} + +static SDL_bool InitTimeDevicesExist = SDL_FALSE; +static int look_for_devices_test(int fd) +{ + InitTimeDevicesExist = SDL_TRUE; /* note that _something_ exists. */ + /* Don't add to the device list, we're just seeing if any devices exist. */ + return 0; +} + +static SDL_bool DSP_Init(SDL_AudioDriverImpl *impl) +{ + InitTimeDevicesExist = SDL_FALSE; + SDL_EnumUnixAudioDevices(0, look_for_devices_test); + if (!InitTimeDevicesExist) { + SDL_SetError("dsp: No such audio device"); + return SDL_FALSE; /* maybe try a different backend. */ + } + + /* Set the function pointers */ + impl->DetectDevices = DSP_DetectDevices; + impl->OpenDevice = DSP_OpenDevice; + impl->PlayDevice = DSP_PlayDevice; + impl->GetDeviceBuf = DSP_GetDeviceBuf; + impl->CloseDevice = DSP_CloseDevice; + impl->CaptureFromDevice = DSP_CaptureFromDevice; + impl->FlushCapture = DSP_FlushCapture; + + impl->AllowsArbitraryDeviceNames = SDL_TRUE; + impl->HasCaptureSupport = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap DSP_bootstrap = { + "dsp", "OSS /dev/dsp standard audio", DSP_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_OSS */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/dsp/SDL_dspaudio.h b/third_party/SDL2/src/audio/dsp/SDL_dspaudio.h new file mode 100644 index 00000000000..c710a7ec9b1 --- /dev/null +++ b/third_party/SDL2/src/audio/dsp/SDL_dspaudio.h @@ -0,0 +1,43 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_dspaudio_h_ +#define SDL_dspaudio_h_ + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + int audio_fd; + + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; +}; +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ + +#endif /* SDL_dspaudio_h_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/dummy/SDL_dummyaudio.c b/third_party/SDL2/src/audio/dummy/SDL_dummyaudio.c new file mode 100644 index 00000000000..a9bdd84a5a0 --- /dev/null +++ b/third_party/SDL2/src/audio/dummy/SDL_dummyaudio.c @@ -0,0 +1,68 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_DUMMY + +/* Output audio to nowhere... */ + +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_dummyaudio.h" + +static int DUMMYAUDIO_OpenDevice(_THIS, const char *devname) +{ + _this->hidden = (void *)0x1; /* just something non-NULL */ + + return 0; /* always succeeds. */ +} + +static int DUMMYAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + /* Delay to make this sort of simulate real audio input. */ + SDL_Delay((_this->spec.samples * 1000) / _this->spec.freq); + + /* always return a full buffer of silence. */ + SDL_memset(buffer, _this->spec.silence, buflen); + return buflen; +} + +static SDL_bool DUMMYAUDIO_Init(SDL_AudioDriverImpl *impl) +{ + /* Set the function pointers */ + impl->OpenDevice = DUMMYAUDIO_OpenDevice; + impl->CaptureFromDevice = DUMMYAUDIO_CaptureFromDevice; + + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + impl->OnlyHasDefaultCaptureDevice = SDL_TRUE; + impl->HasCaptureSupport = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap DUMMYAUDIO_bootstrap = { + "dummy", "SDL dummy audio driver", DUMMYAUDIO_Init, SDL_TRUE +}; + +#endif + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/dummy/SDL_dummyaudio.h b/third_party/SDL2/src/audio/dummy/SDL_dummyaudio.h new file mode 100644 index 00000000000..e0e77e523ca --- /dev/null +++ b/third_party/SDL2/src/audio/dummy/SDL_dummyaudio.h @@ -0,0 +1,41 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_dummyaudio_h_ +#define SDL_dummyaudio_h_ + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *_this + +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + Uint8 *mixbuf; + Uint32 mixlen; + Uint32 write_delay; + Uint32 initial_calls; +}; + +#endif /* SDL_dummyaudio_h_ */ +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/emscripten/SDL_emscriptenaudio.c b/third_party/SDL2/src/audio/emscripten/SDL_emscriptenaudio.c new file mode 100644 index 00000000000..3600fb5c587 --- /dev/null +++ b/third_party/SDL2/src/audio/emscripten/SDL_emscriptenaudio.c @@ -0,0 +1,442 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_EMSCRIPTEN + +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_emscriptenaudio.h" + +#include + +/* !!! FIXME: this currently expects that the audio callback runs in the main thread, + !!! FIXME: in intervals when the application isn't running, but that may not be + !!! FIXME: true always once pthread support becomes widespread. Revisit this code + !!! FIXME: at some point and see what needs to be done for that! */ + +static void FeedAudioDevice(_THIS, const void *buf, const int buflen) +{ + const int framelen = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels; + /* *INDENT-OFF* */ /* clang-format off */ + MAIN_THREAD_EM_ASM({ + var SDL2 = Module['SDL2']; + /* Convert incoming buf pointer to a HEAPF32 offset. */ +#ifdef __wasm64__ + var buf = $0 / 4; +#else + var buf = $0 >>> 2; +#endif + var numChannels = SDL2.audio.currentOutputBuffer['numberOfChannels']; + for (var c = 0; c < numChannels; ++c) { + var channelData = SDL2.audio.currentOutputBuffer['getChannelData'](c); + if (channelData.length != $1) { + throw 'Web Audio output buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!'; + } + + for (var j = 0; j < $1; ++j) { + channelData[j] = HEAPF32[buf + (j*numChannels + c)]; + } + } + }, buf, buflen / framelen); +/* *INDENT-ON* */ /* clang-format on */ +} + +static void HandleAudioProcess(_THIS) +{ + SDL_AudioCallback callback = this->callbackspec.callback; + const int stream_len = this->callbackspec.size; + + /* Only do something if audio is enabled */ + if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) { + if (this->stream) { + SDL_AudioStreamClear(this->stream); + } + + SDL_memset(this->work_buffer, this->spec.silence, this->spec.size); + FeedAudioDevice(this, this->work_buffer, this->spec.size); + return; + } + + if (!this->stream) { /* no conversion necessary. */ + SDL_assert(this->spec.size == stream_len); + callback(this->callbackspec.userdata, this->work_buffer, stream_len); + } else { /* streaming/converting */ + int got; + while (SDL_AudioStreamAvailable(this->stream) < ((int)this->spec.size)) { + callback(this->callbackspec.userdata, this->work_buffer, stream_len); + if (SDL_AudioStreamPut(this->stream, this->work_buffer, stream_len) == -1) { + SDL_AudioStreamClear(this->stream); + SDL_AtomicSet(&this->enabled, 0); + break; + } + } + + got = SDL_AudioStreamGet(this->stream, this->work_buffer, this->spec.size); + SDL_assert((got < 0) || (got == this->spec.size)); + if (got != this->spec.size) { + SDL_memset(this->work_buffer, this->spec.silence, this->spec.size); + } + } + + FeedAudioDevice(this, this->work_buffer, this->spec.size); +} + +static void HandleCaptureProcess(_THIS) +{ + SDL_AudioCallback callback = this->callbackspec.callback; + const int stream_len = this->callbackspec.size; + + /* Only do something if audio is enabled */ + if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) { + SDL_AudioStreamClear(this->stream); + return; + } + + /* *INDENT-OFF* */ /* clang-format off */ + MAIN_THREAD_EM_ASM({ + var SDL2 = Module['SDL2']; + var numChannels = SDL2.capture.currentCaptureBuffer.numberOfChannels; + for (var c = 0; c < numChannels; ++c) { + var channelData = SDL2.capture.currentCaptureBuffer.getChannelData(c); + if (channelData.length != $1) { + throw 'Web Audio capture buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!'; + } + + if (numChannels == 1) { /* fastpath this a little for the common (mono) case. */ + for (var j = 0; j < $1; ++j) { + setValue($0 + (j * 4), channelData[j], 'float'); + } + } else { + for (var j = 0; j < $1; ++j) { + setValue($0 + (((j * numChannels) + c) * 4), channelData[j], 'float'); + } + } + } + }, this->work_buffer, (this->spec.size / sizeof(float)) / this->spec.channels); +/* *INDENT-ON* */ /* clang-format on */ + + /* okay, we've got an interleaved float32 array in C now. */ + + if (!this->stream) { /* no conversion necessary. */ + SDL_assert(this->spec.size == stream_len); + callback(this->callbackspec.userdata, this->work_buffer, stream_len); + } else { /* streaming/converting */ + if (SDL_AudioStreamPut(this->stream, this->work_buffer, this->spec.size) == -1) { + SDL_AtomicSet(&this->enabled, 0); + } + + while (SDL_AudioStreamAvailable(this->stream) >= stream_len) { + const int got = SDL_AudioStreamGet(this->stream, this->work_buffer, stream_len); + SDL_assert((got < 0) || (got == stream_len)); + if (got != stream_len) { + SDL_memset(this->work_buffer, this->callbackspec.silence, stream_len); + } + callback(this->callbackspec.userdata, this->work_buffer, stream_len); /* Send it to the app. */ + } + } +} + +static void EMSCRIPTENAUDIO_CloseDevice(_THIS) +{ + /* *INDENT-OFF* */ /* clang-format off */ + MAIN_THREAD_EM_ASM({ + var SDL2 = Module['SDL2']; + if ($0) { + if (SDL2.capture.silenceTimer !== undefined) { + clearInterval(SDL2.capture.silenceTimer); + } + if (SDL2.capture.stream !== undefined) { + var tracks = SDL2.capture.stream.getAudioTracks(); + for (var i = 0; i < tracks.length; i++) { + SDL2.capture.stream.removeTrack(tracks[i]); + } + } + if (SDL2.capture.scriptProcessorNode !== undefined) { + SDL2.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) {}; + SDL2.capture.scriptProcessorNode.disconnect(); + } + if (SDL2.capture.mediaStreamNode !== undefined) { + SDL2.capture.mediaStreamNode.disconnect(); + } + SDL2.capture = undefined; + } else { + if (SDL2.audio.scriptProcessorNode != undefined) { + SDL2.audio.scriptProcessorNode.disconnect(); + } + if (SDL2.audio.silenceTimer !== undefined) { + clearInterval(SDL2.audio.silenceTimer); + } + SDL2.audio = undefined; + } + if ((SDL2.audioContext !== undefined) && (SDL2.audio === undefined) && (SDL2.capture === undefined)) { + SDL2.audioContext.close(); + SDL2.audioContext = undefined; + } + }, this->iscapture); +/* *INDENT-ON* */ /* clang-format on */ + +#if 0 /* !!! FIXME: currently not used. Can we move some stuff off the SDL2 namespace? --ryan. */ + SDL_free(this->hidden); +#endif +} + +EM_JS_DEPS(sdlaudio, "$autoResumeAudioContext,$dynCall"); + +static int EMSCRIPTENAUDIO_OpenDevice(_THIS, const char *devname) +{ + SDL_AudioFormat test_format; + SDL_bool iscapture = this->iscapture; + int result; + + /* based on parts of library_sdl.js */ + + /* *INDENT-OFF* */ /* clang-format off */ + /* create context */ + result = MAIN_THREAD_EM_ASM_INT({ + if(typeof(Module['SDL2']) === 'undefined') { + Module['SDL2'] = {}; + } + var SDL2 = Module['SDL2']; + if (!$0) { + SDL2.audio = {}; + } else { + SDL2.capture = {}; + } + + if (!SDL2.audioContext) { + if (typeof(AudioContext) !== 'undefined') { + SDL2.audioContext = new AudioContext(); + } else if (typeof(webkitAudioContext) !== 'undefined') { + SDL2.audioContext = new webkitAudioContext(); + } + if (SDL2.audioContext) { + if ((typeof navigator.userActivation) === 'undefined') { + autoResumeAudioContext(SDL2.audioContext); + } + } + } + return SDL2.audioContext === undefined ? -1 : 0; + }, iscapture); +/* *INDENT-ON* */ /* clang-format on */ + + if (result < 0) { + return SDL_SetError("Web Audio API is not available!"); + } + + for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { + switch (test_format) { + case AUDIO_F32: /* web audio only supports floats */ + break; + default: + continue; + } + break; + } + + if (!test_format) { + /* Didn't find a compatible format :( */ + return SDL_SetError("%s: Unsupported audio format", "emscripten"); + } + this->spec.format = test_format; + + /* Initialize all variables that we clean on shutdown */ +#if 0 /* !!! FIXME: currently not used. Can we move some stuff off the SDL2 namespace? --ryan. */ + this->hidden = (struct SDL_PrivateAudioData *) + SDL_malloc(sizeof(*this->hidden)); + if (this->hidden == NULL) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); +#endif + this->hidden = (struct SDL_PrivateAudioData *)0x1; + + /* limit to native freq */ + this->spec.freq = EM_ASM_INT({ + var SDL2 = Module['SDL2']; + return SDL2.audioContext.sampleRate; + }); + + SDL_CalculateAudioSpec(&this->spec); + + /* *INDENT-OFF* */ /* clang-format off */ + if (iscapture) { + /* The idea is to take the capture media stream, hook it up to an + audio graph where we can pass it through a ScriptProcessorNode + to access the raw PCM samples and push them to the SDL app's + callback. From there, we "process" the audio data into silence + and forget about it. */ + + /* This should, strictly speaking, use MediaRecorder for capture, but + this API is cleaner to use and better supported, and fires a + callback whenever there's enough data to fire down into the app. + The downside is that we are spending CPU time silencing a buffer + that the audiocontext uselessly mixes into any output. On the + upside, both of those things are not only run in native code in + the browser, they're probably SIMD code, too. MediaRecorder + feels like it's a pretty inefficient tapdance in similar ways, + to be honest. */ + + MAIN_THREAD_EM_ASM({ + var SDL2 = Module['SDL2']; + var have_microphone = function(stream) { + //console.log('SDL audio capture: we have a microphone! Replacing silence callback.'); + if (SDL2.capture.silenceTimer !== undefined) { + clearInterval(SDL2.capture.silenceTimer); + SDL2.capture.silenceTimer = undefined; + SDL2.capture.silenceBuffer = undefined + } + SDL2.capture.mediaStreamNode = SDL2.audioContext.createMediaStreamSource(stream); + SDL2.capture.scriptProcessorNode = SDL2.audioContext.createScriptProcessor($1, $0, 1); + SDL2.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) { + if ((SDL2 === undefined) || (SDL2.capture === undefined)) { return; } + audioProcessingEvent.outputBuffer.getChannelData(0).fill(0.0); + SDL2.capture.currentCaptureBuffer = audioProcessingEvent.inputBuffer; + dynCall('vi', $2, [$3]); + }; + SDL2.capture.mediaStreamNode.connect(SDL2.capture.scriptProcessorNode); + SDL2.capture.scriptProcessorNode.connect(SDL2.audioContext.destination); + SDL2.capture.stream = stream; + }; + + var no_microphone = function(error) { + //console.log('SDL audio capture: we DO NOT have a microphone! (' + error.name + ')...leaving silence callback running.'); + }; + + /* we write silence to the audio callback until the microphone is available (user approves use, etc). */ + SDL2.capture.silenceBuffer = SDL2.audioContext.createBuffer($0, $1, SDL2.audioContext.sampleRate); + SDL2.capture.silenceBuffer.getChannelData(0).fill(0.0); + var silence_callback = function() { + SDL2.capture.currentCaptureBuffer = SDL2.capture.silenceBuffer; + dynCall('vi', $2, [$3]); + }; + + SDL2.capture.silenceTimer = setInterval(silence_callback, ($1 / SDL2.audioContext.sampleRate) * 1000); + + if ((navigator.mediaDevices !== undefined) && (navigator.mediaDevices.getUserMedia !== undefined)) { + navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(have_microphone).catch(no_microphone); + } else if (navigator.webkitGetUserMedia !== undefined) { + navigator.webkitGetUserMedia({ audio: true, video: false }, have_microphone, no_microphone); + } + }, this->spec.channels, this->spec.samples, HandleCaptureProcess, this); + } else { + /* setup a ScriptProcessorNode */ + MAIN_THREAD_EM_ASM({ + var SDL2 = Module['SDL2']; + SDL2.audio.scriptProcessorNode = SDL2.audioContext['createScriptProcessor']($1, 0, $0); + SDL2.audio.scriptProcessorNode['onaudioprocess'] = function (e) { + if ((SDL2 === undefined) || (SDL2.audio === undefined)) { return; } + // if we're actually running the node, we don't need the fake callback anymore, so kill it. + if (SDL2.audio.silenceTimer !== undefined) { + clearInterval(SDL2.audio.silenceTimer); + SDL2.audio.silenceTimer = undefined; + SDL2.audio.silenceBuffer = undefined; + } + SDL2.audio.currentOutputBuffer = e['outputBuffer']; + dynCall('vi', $2, [$3]); + }; + + SDL2.audio.scriptProcessorNode['connect'](SDL2.audioContext['destination']); + + if (SDL2.audioContext.state === 'suspended') { // uhoh, autoplay is blocked. + SDL2.audio.silenceBuffer = SDL2.audioContext.createBuffer($0, $1, SDL2.audioContext.sampleRate); + SDL2.audio.silenceBuffer.getChannelData(0).fill(0.0); + var silence_callback = function() { + if ((typeof navigator.userActivation) !== 'undefined') { + if (navigator.userActivation.hasBeenActive) { + SDL2.audioContext.resume(); + } + } + + // the buffer that gets filled here just gets ignored, so the app can make progress + // and/or avoid flooding audio queues until we can actually play audio. + SDL2.audio.currentOutputBuffer = SDL2.audio.silenceBuffer; + dynCall('vi', $2, [$3]); + SDL2.audio.currentOutputBuffer = undefined; + }; + + SDL2.audio.silenceTimer = setInterval(silence_callback, ($1 / SDL2.audioContext.sampleRate) * 1000); + } + }, this->spec.channels, this->spec.samples, HandleAudioProcess, this); + } +/* *INDENT-ON* */ /* clang-format on */ + + return 0; +} + +static void EMSCRIPTENAUDIO_LockOrUnlockDeviceWithNoMixerLock(SDL_AudioDevice *device) +{ +} + +static SDL_bool EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl *impl) +{ + SDL_bool available, capture_available; + + /* Set the function pointers */ + impl->OpenDevice = EMSCRIPTENAUDIO_OpenDevice; + impl->CloseDevice = EMSCRIPTENAUDIO_CloseDevice; + + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + + /* no threads here */ + impl->LockDevice = impl->UnlockDevice = EMSCRIPTENAUDIO_LockOrUnlockDeviceWithNoMixerLock; + impl->ProvidesOwnCallbackThread = SDL_TRUE; + + /* *INDENT-OFF* */ /* clang-format off */ + /* check availability */ + available = MAIN_THREAD_EM_ASM_INT({ + if (typeof(AudioContext) !== 'undefined') { + return true; + } else if (typeof(webkitAudioContext) !== 'undefined') { + return true; + } + return false; + }); +/* *INDENT-ON* */ /* clang-format on */ + + if (!available) { + SDL_SetError("No audio context available"); + } + + /* *INDENT-OFF* */ /* clang-format off */ + capture_available = available && MAIN_THREAD_EM_ASM_INT({ + if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) { + return true; + } else if (typeof(navigator.webkitGetUserMedia) !== 'undefined') { + return true; + } + return false; + }); +/* *INDENT-ON* */ /* clang-format on */ + + impl->HasCaptureSupport = capture_available ? SDL_TRUE : SDL_FALSE; + impl->OnlyHasDefaultCaptureDevice = capture_available ? SDL_TRUE : SDL_FALSE; + + return available; +} + +AudioBootStrap EMSCRIPTENAUDIO_bootstrap = { + "emscripten", "SDL emscripten audio driver", EMSCRIPTENAUDIO_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_EMSCRIPTEN */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/emscripten/SDL_emscriptenaudio.h b/third_party/SDL2/src/audio/emscripten/SDL_emscriptenaudio.h new file mode 100644 index 00000000000..62631cf9c74 --- /dev/null +++ b/third_party/SDL2/src/audio/emscripten/SDL_emscriptenaudio.h @@ -0,0 +1,38 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_emscriptenaudio_h_ +#define SDL_emscriptenaudio_h_ + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + int unused; +}; + +#endif /* SDL_emscriptenaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/esd/SDL_esdaudio.c b/third_party/SDL2/src/audio/esd/SDL_esdaudio.c new file mode 100644 index 00000000000..70cdfa26339 --- /dev/null +++ b/third_party/SDL2/src/audio/esd/SDL_esdaudio.c @@ -0,0 +1,322 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_ESD + +/* Allow access to an ESD network stream mixing buffer */ + +#include +#include +#include +#include +#include + +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_esdaudio.h" + +#ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC +#include "SDL_name.h" +#include "SDL_loadso.h" +#else +#define SDL_NAME(X) X +#endif + +#ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC + +static const char *esd_library = SDL_AUDIO_DRIVER_ESD_DYNAMIC; +static void *esd_handle = NULL; + +static int (*SDL_NAME(esd_open_sound)) (const char *host); +static int (*SDL_NAME(esd_close)) (int esd); +static int (*SDL_NAME(esd_play_stream)) (esd_format_t format, int rate, + const char *host, const char *name); + +#define SDL_ESD_SYM(x) { #x, (void **) (char *) &SDL_NAME(x) } +static struct +{ + const char *name; + void **func; +} const esd_functions[] = { + SDL_ESD_SYM(esd_open_sound), + SDL_ESD_SYM(esd_close), SDL_ESD_SYM(esd_play_stream), +}; + +#undef SDL_ESD_SYM + +static void UnloadESDLibrary(void) +{ + if (esd_handle) { + SDL_UnloadObject(esd_handle); + esd_handle = NULL; + } +} + +static int LoadESDLibrary(void) +{ + int i, retval = -1; + + if (!esd_handle) { + esd_handle = SDL_LoadObject(esd_library); + if (esd_handle) { + retval = 0; + for (i = 0; i < SDL_arraysize(esd_functions); ++i) { + *esd_functions[i].func = + SDL_LoadFunction(esd_handle, esd_functions[i].name); + if (!*esd_functions[i].func) { + retval = -1; + UnloadESDLibrary(); + break; + } + } + } + } + return retval; +} + +#else + +static void UnloadESDLibrary(void) +{ + return; +} + +static int LoadESDLibrary(void) +{ + return 0; +} + +#endif /* SDL_AUDIO_DRIVER_ESD_DYNAMIC */ + + +/* This function waits until it is possible to write a full sound buffer */ +static void ESD_WaitDevice(_THIS) +{ + Sint32 ticks; + + /* Check to see if the thread-parent process is still alive */ + { + static int cnt = 0; + /* Note that this only works with thread implementations + that use a different process id for each thread. + */ + /* Check every 10 loops */ + if (this->hidden->parent && (((++cnt) % 10) == 0)) { + if (kill(this->hidden->parent, 0) < 0 && errno == ESRCH) { + SDL_OpenedAudioDeviceDisconnected(this); + } + } + } + + /* Use timer for general audio synchronization */ + ticks = ((Sint32) (this->hidden->next_frame - SDL_GetTicks())) - FUDGE_TICKS; + if (ticks > 0) { + SDL_Delay(ticks); + } +} + +static void ESD_PlayDevice(_THIS) +{ + int written = 0; + + /* Write the audio data, checking for EAGAIN on broken audio drivers */ + do { + written = write(this->hidden->audio_fd, + this->hidden->mixbuf, this->hidden->mixlen); + if ((written < 0) && ((errno == 0) || (errno == EAGAIN))) { + SDL_Delay(1); /* Let a little CPU time go by */ + } + } while ((written < 0) && + ((errno == 0) || (errno == EAGAIN) || (errno == EINTR))); + + /* Set the next write frame */ + this->hidden->next_frame += this->hidden->frame_ticks; + + /* If we couldn't write, assume fatal error for now */ + if (written < 0) { + SDL_OpenedAudioDeviceDisconnected(this); + } +} + +static Uint8 *ESD_GetDeviceBuf(_THIS) +{ + return (this->hidden->mixbuf); +} + +static void ESD_CloseDevice(_THIS) +{ + if (this->hidden->audio_fd >= 0) { + SDL_NAME(esd_close) (this->hidden->audio_fd); + } + SDL_free(this->hidden->mixbuf); + SDL_free(this->hidden); +} + +/* Try to get the name of the program */ +static char *get_progname(void) +{ + char *progname = NULL; +#ifdef __LINUX__ + FILE *fp; + static char temp[BUFSIZ]; + + SDL_snprintf(temp, SDL_arraysize(temp), "/proc/%d/cmdline", getpid()); + fp = fopen(temp, "r"); + if (fp != NULL) { + if (fgets(temp, sizeof(temp) - 1, fp)) { + progname = SDL_strrchr(temp, '/'); + if (!progname) { + progname = temp; + } else { + progname = progname + 1; + } + } + fclose(fp); + } +#endif + return (progname); +} + + +static int ESD_OpenDevice(_THIS, const char *devname) +{ + esd_format_t format = (ESD_STREAM | ESD_PLAY); + SDL_AudioFormat test_format = 0; + int found = 0; + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); + this->hidden->audio_fd = -1; + + /* Convert audio spec to the ESD audio format */ + /* Try for a closest match on audio format */ + for (test_format = SDL_FirstAudioFormat(this->spec.format); + !found && test_format; test_format = SDL_NextAudioFormat()) { +#ifdef DEBUG_AUDIO + fprintf(stderr, "Trying format 0x%4.4x\n", test_format); +#endif + found = 1; + switch (test_format) { + case AUDIO_U8: + format |= ESD_BITS8; + break; + case AUDIO_S16SYS: + format |= ESD_BITS16; + break; + default: + found = 0; + break; + } + } + + if (!found) { + return SDL_SetError("Couldn't find any hardware audio formats"); + } + + if (this->spec.channels == 1) { + format |= ESD_MONO; + } else { + format |= ESD_STEREO; + } +#if 0 + this->spec.samples = ESD_BUF_SIZE; /* Darn, no way to change this yet */ +#endif + + /* Open a connection to the ESD audio server */ + this->hidden->audio_fd = + SDL_NAME(esd_play_stream) (format, this->spec.freq, NULL, + get_progname()); + + if (this->hidden->audio_fd < 0) { + return SDL_SetError("Couldn't open ESD connection"); + } + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&this->spec); + this->hidden->frame_ticks = + (float) (this->spec.samples * 1000) / this->spec.freq; + this->hidden->next_frame = SDL_GetTicks() + this->hidden->frame_ticks; + + /* Allocate mixing buffer */ + this->hidden->mixlen = this->spec.size; + this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); + if (!this->hidden->mixbuf) { + return SDL_OutOfMemory(); + } + SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); + + /* Get the parent process id (we're the parent of the audio thread) */ + this->hidden->parent = getpid(); + + /* We're ready to rock and roll. :-) */ + return 0; +} + +static void ESD_Deinitialize(void) +{ + UnloadESDLibrary(); +} + +static SDL_bool ESD_Init(SDL_AudioDriverImpl * impl) +{ + if (LoadESDLibrary() < 0) { + return SDL_FALSE; + } else { + int connection = 0; + + /* Don't start ESD if it's not running */ + SDL_setenv("ESD_NO_SPAWN", "1", 0); + + connection = SDL_NAME(esd_open_sound) (NULL); + if (connection < 0) { + UnloadESDLibrary(); + SDL_SetError("ESD: esd_open_sound failed (no audio server?)"); + return SDL_FALSE; + } + SDL_NAME(esd_close) (connection); + } + + /* Set the function pointers */ + impl->OpenDevice = ESD_OpenDevice; + impl->PlayDevice = ESD_PlayDevice; + impl->WaitDevice = ESD_WaitDevice; + impl->GetDeviceBuf = ESD_GetDeviceBuf; + impl->CloseDevice = ESD_CloseDevice; + impl->Deinitialize = ESD_Deinitialize; + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + + +AudioBootStrap ESD_bootstrap = { + "esd", "Enlightened Sound Daemon", ESD_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_ESD */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/esd/SDL_esdaudio.h b/third_party/SDL2/src/audio/esd/SDL_esdaudio.h new file mode 100644 index 00000000000..0ec50b06870 --- /dev/null +++ b/third_party/SDL2/src/audio/esd/SDL_esdaudio.h @@ -0,0 +1,51 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_esdaudio_h_ +#define SDL_esdaudio_h_ + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + /* The file descriptor for the audio device */ + int audio_fd; + + /* The parent process id, to detect when application quits */ + pid_t parent; + + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; + + /* Support for audio timing using a timer */ + float frame_ticks; + float next_frame; +}; +#define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ + +#endif /* SDL_esdaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/fusionsound/SDL_fsaudio.c b/third_party/SDL2/src/audio/fusionsound/SDL_fsaudio.c new file mode 100644 index 00000000000..30a429fbf1d --- /dev/null +++ b/third_party/SDL2/src/audio/fusionsound/SDL_fsaudio.c @@ -0,0 +1,305 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_FUSIONSOUND + +/* !!! FIXME: why is this is SDL_FS_* instead of FUSIONSOUND_*? */ + +/* Allow access to a raw mixing buffer */ + +#ifdef HAVE_SIGNAL_H +#include +#endif +#include + +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_fsaudio.h" + +#include + +/* #define SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC "libfusionsound.so" */ + +#ifdef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC +#include "SDL_name.h" +#include "SDL_loadso.h" +#else +#define SDL_NAME(X) X +#endif + +#if (FUSIONSOUND_MAJOR_VERSION == 1) && (FUSIONSOUND_MINOR_VERSION < 1) +typedef DFBResult DirectResult; +#endif + +/* Buffers to use - more than 2 gives a lot of latency */ +#define FUSION_BUFFERS (2) + +#ifdef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC + +static const char *fs_library = SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC; +static void *fs_handle = NULL; + +static DirectResult (*SDL_NAME(FusionSoundInit)) (int *argc, char *(*argv[])); +static DirectResult (*SDL_NAME(FusionSoundCreate)) (IFusionSound ** + ret_interface); + +#define SDL_FS_SYM(x) { #x, (void **) (char *) &SDL_NAME(x) } +static struct +{ + const char *name; + void **func; +} fs_functions[] = { +/* *INDENT-OFF* */ + SDL_FS_SYM(FusionSoundInit), + SDL_FS_SYM(FusionSoundCreate), +/* *INDENT-ON* */ +}; + +#undef SDL_FS_SYM + +static void UnloadFusionSoundLibrary(void) +{ + if (fs_handle) { + SDL_UnloadObject(fs_handle); + fs_handle = NULL; + } +} + +static int LoadFusionSoundLibrary(void) +{ + int i, retval = -1; + + if (!fs_handle) { + fs_handle = SDL_LoadObject(fs_library); + if (fs_handle) { + retval = 0; + for (i = 0; i < SDL_arraysize(fs_functions); ++i) { + *fs_functions[i].func = + SDL_LoadFunction(fs_handle, fs_functions[i].name); + if (!*fs_functions[i].func) { + retval = -1; + UnloadFusionSoundLibrary(); + break; + } + } + } + } + + return retval; +} + +#else + +static void UnloadFusionSoundLibrary(void) +{ + return; +} + +static int LoadFusionSoundLibrary(void) +{ + return 0; +} + +#endif /* SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC */ + +/* This function waits until it is possible to write a full sound buffer */ +static void SDL_FS_WaitDevice(_THIS) +{ + this->hidden->stream->Wait(this->hidden->stream, + this->hidden->mixsamples); +} + +static void SDL_FS_PlayDevice(_THIS) +{ + DirectResult ret; + + ret = this->hidden->stream->Write(this->hidden->stream, + this->hidden->mixbuf, + this->hidden->mixsamples); + /* If we couldn't write, assume fatal error for now */ + if (ret) { + SDL_OpenedAudioDeviceDisconnected(this); + } +#ifdef DEBUG_AUDIO + fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen); +#endif +} + + +static Uint8 *SDL_FS_GetDeviceBuf(_THIS) +{ + return (this->hidden->mixbuf); +} + + +static void SDL_FS_CloseDevice(_THIS) +{ + if (this->hidden->stream) { + this->hidden->stream->Release(this->hidden->stream); + } + if (this->hidden->fs) { + this->hidden->fs->Release(this->hidden->fs); + } + SDL_free(this->hidden->mixbuf); + SDL_free(this->hidden); +} + + +static int SDL_FS_OpenDevice(_THIS, const char *devname) +{ + int bytes; + SDL_AudioFormat test_format; + FSSampleFormat fs_format; + FSStreamDescription desc; + DirectResult ret; + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); + + /* Try for a closest match on audio format */ + for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { +#ifdef DEBUG_AUDIO + fprintf(stderr, "Trying format 0x%4.4x\n", test_format); +#endif + switch (test_format) { + case AUDIO_U8: + fs_format = FSSF_U8; + break; + case AUDIO_S16SYS: + fs_format = FSSF_S16; + break; + case AUDIO_S32SYS: + fs_format = FSSF_S32; + break; + case AUDIO_F32SYS: + fs_format = FSSF_FLOAT; + break; + default: + continue; + } + break; + } + + if (!test_format) { + return SDL_SetError("%s: Unsupported audio format", "fusionsound"); + } + this->spec.format = test_format; + bytes = SDL_AUDIO_BITSIZE(test_format) / 8; + + /* Retrieve the main sound interface. */ + ret = SDL_NAME(FusionSoundCreate) (&this->hidden->fs); + if (ret) { + return SDL_SetError("Unable to initialize FusionSound: %d", ret); + } + + this->hidden->mixsamples = this->spec.size / bytes / this->spec.channels; + + /* Fill stream description. */ + desc.flags = FSSDF_SAMPLERATE | FSSDF_BUFFERSIZE | + FSSDF_CHANNELS | FSSDF_SAMPLEFORMAT | FSSDF_PREBUFFER; + desc.samplerate = this->spec.freq; + desc.buffersize = this->spec.size * FUSION_BUFFERS; + desc.channels = this->spec.channels; + desc.prebuffer = 10; + desc.sampleformat = fs_format; + + ret = + this->hidden->fs->CreateStream(this->hidden->fs, &desc, + &this->hidden->stream); + if (ret) { + return SDL_SetError("Unable to create FusionSoundStream: %d", ret); + } + + /* See what we got */ + desc.flags = FSSDF_SAMPLERATE | FSSDF_BUFFERSIZE | + FSSDF_CHANNELS | FSSDF_SAMPLEFORMAT; + ret = this->hidden->stream->GetDescription(this->hidden->stream, &desc); + + this->spec.freq = desc.samplerate; + this->spec.size = + desc.buffersize / FUSION_BUFFERS * bytes * desc.channels; + this->spec.channels = desc.channels; + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&this->spec); + + /* Allocate mixing buffer */ + this->hidden->mixlen = this->spec.size; + this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); + if (!this->hidden->mixbuf) { + return SDL_OutOfMemory(); + } + SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); + + /* We're ready to rock and roll. :-) */ + return 0; +} + + +static void SDL_FS_Deinitialize(void) +{ + UnloadFusionSoundLibrary(); +} + + +static SDL_bool SDL_FS_Init(SDL_AudioDriverImpl * impl) +{ + if (LoadFusionSoundLibrary() < 0) { + return SDL_FALSE; + } else { + DirectResult ret; + + ret = SDL_NAME(FusionSoundInit) (NULL, NULL); + if (ret) { + UnloadFusionSoundLibrary(); + SDL_SetError + ("FusionSound: SDL_FS_init failed (FusionSoundInit: %d)", + ret); + return SDL_FALSE; + } + } + + /* Set the function pointers */ + impl->OpenDevice = SDL_FS_OpenDevice; + impl->PlayDevice = SDL_FS_PlayDevice; + impl->WaitDevice = SDL_FS_WaitDevice; + impl->GetDeviceBuf = SDL_FS_GetDeviceBuf; + impl->CloseDevice = SDL_FS_CloseDevice; + impl->Deinitialize = SDL_FS_Deinitialize; + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + + +AudioBootStrap FUSIONSOUND_bootstrap = { + "fusionsound", "FusionSound", SDL_FS_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_FUSIONSOUND */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/fusionsound/SDL_fsaudio.h b/third_party/SDL2/src/audio/fusionsound/SDL_fsaudio.h new file mode 100644 index 00000000000..49c2f53469b --- /dev/null +++ b/third_party/SDL2/src/audio/fusionsound/SDL_fsaudio.h @@ -0,0 +1,50 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_fsaudio_h_ +#define SDL_fsaudio_h_ + +#include + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + /* Interface */ + IFusionSound *fs; + + /* The stream interface for the audio device */ + IFusionSoundStream *stream; + + /* Raw mixing buffer */ + Uint8 *mixbuf; + int mixlen; + int mixsamples; + +}; + +#endif /* SDL_fsaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/haiku/SDL_haikuaudio.cc b/third_party/SDL2/src/audio/haiku/SDL_haikuaudio.cc new file mode 100644 index 00000000000..729c0b0dd38 --- /dev/null +++ b/third_party/SDL2/src/audio/haiku/SDL_haikuaudio.cc @@ -0,0 +1,238 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_HAIKU + +/* Allow access to the audio stream on Haiku */ + +#include +#include + +#include "../../main/haiku/SDL_BeApp.h" + +extern "C" +{ + +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "../SDL_sysaudio.h" +#include "SDL_haikuaudio.h" + +} + + +/* !!! FIXME: have the callback call the higher level to avoid code dupe. */ +/* The Haiku callback for handling the audio buffer */ +static void FillSound(void *device, void *stream, size_t len, + const media_raw_audio_format & format) +{ + SDL_AudioDevice *audio = (SDL_AudioDevice *) device; + SDL_AudioCallback callback = audio->callbackspec.callback; + + SDL_LockMutex(audio->mixer_lock); + + /* Only do something if audio is enabled */ + if (!SDL_AtomicGet(&audio->enabled) || SDL_AtomicGet(&audio->paused)) { + if (audio->stream) { + SDL_AudioStreamClear(audio->stream); + } + SDL_memset(stream, audio->spec.silence, len); + } else { + SDL_assert(audio->spec.size == len); + + if (!audio->stream) { /* no conversion necessary. */ + callback(audio->callbackspec.userdata, (Uint8 *) stream, len); + } else { /* streaming/converting */ + const int stream_len = audio->callbackspec.size; + const int ilen = (int) len; + while (SDL_AudioStreamAvailable(audio->stream) < ilen) { + callback(audio->callbackspec.userdata, audio->work_buffer, stream_len); + if (SDL_AudioStreamPut(audio->stream, audio->work_buffer, stream_len) == -1) { + SDL_AudioStreamClear(audio->stream); + SDL_AtomicSet(&audio->enabled, 0); + break; + } + } + + const int got = SDL_AudioStreamGet(audio->stream, stream, ilen); + SDL_assert((got < 0) || (got == ilen)); + if (got != ilen) { + SDL_memset(stream, audio->spec.silence, len); + } + } + } + + SDL_UnlockMutex(audio->mixer_lock); +} + +static void HAIKUAUDIO_CloseDevice(_THIS) +{ + if (_this->hidden->audio_obj) { + _this->hidden->audio_obj->Stop(); + delete _this->hidden->audio_obj; + } + delete _this->hidden; +} + + +static const int sig_list[] = { + SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGWINCH, 0 +}; + +static inline void MaskSignals(sigset_t * omask) +{ + sigset_t mask; + int i; + + sigemptyset(&mask); + for (i = 0; sig_list[i]; ++i) { + sigaddset(&mask, sig_list[i]); + } + sigprocmask(SIG_BLOCK, &mask, omask); +} + +static inline void UnmaskSignals(sigset_t * omask) +{ + sigprocmask(SIG_SETMASK, omask, NULL); +} + + +static int HAIKUAUDIO_OpenDevice(_THIS, const char *devname) +{ + media_raw_audio_format format; + SDL_AudioFormat test_format; + + /* Initialize all variables that we clean on shutdown */ + _this->hidden = new SDL_PrivateAudioData; + if (_this->hidden == NULL) { + return SDL_OutOfMemory(); + } + SDL_zerop(_this->hidden); + + /* Parse the audio format and fill the Be raw audio format */ + SDL_zero(format); + format.byte_order = B_MEDIA_LITTLE_ENDIAN; + format.frame_rate = (float) _this->spec.freq; + format.channel_count = _this->spec.channels; /* !!! FIXME: support > 2? */ + for (test_format = SDL_FirstAudioFormat(_this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { + switch (test_format) { + case AUDIO_S8: + format.format = media_raw_audio_format::B_AUDIO_CHAR; + break; + + case AUDIO_U8: + format.format = media_raw_audio_format::B_AUDIO_UCHAR; + break; + + case AUDIO_S16LSB: + format.format = media_raw_audio_format::B_AUDIO_SHORT; + break; + + case AUDIO_S16MSB: + format.format = media_raw_audio_format::B_AUDIO_SHORT; + format.byte_order = B_MEDIA_BIG_ENDIAN; + break; + + case AUDIO_S32LSB: + format.format = media_raw_audio_format::B_AUDIO_INT; + break; + + case AUDIO_S32MSB: + format.format = media_raw_audio_format::B_AUDIO_INT; + format.byte_order = B_MEDIA_BIG_ENDIAN; + break; + + case AUDIO_F32LSB: + format.format = media_raw_audio_format::B_AUDIO_FLOAT; + break; + + case AUDIO_F32MSB: + format.format = media_raw_audio_format::B_AUDIO_FLOAT; + format.byte_order = B_MEDIA_BIG_ENDIAN; + break; + + default: + continue; + } + break; + } + + if (!test_format) { /* shouldn't happen, but just in case... */ + return SDL_SetError("%s: Unsupported audio format", "haiku"); + } + _this->spec.format = test_format; + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&_this->spec); + + format.buffer_size = _this->spec.size; + + /* Subscribe to the audio stream (creates a new thread) */ + sigset_t omask; + MaskSignals(&omask); + _this->hidden->audio_obj = new BSoundPlayer(&format, "SDL Audio", + FillSound, NULL, _this); + UnmaskSignals(&omask); + + if (_this->hidden->audio_obj->Start() == B_NO_ERROR) { + _this->hidden->audio_obj->SetHasData(true); + } else { + return SDL_SetError("Unable to start Be audio"); + } + + /* We're running! */ + return 0; +} + +static void HAIKUAUDIO_Deinitialize(void) +{ + SDL_QuitBeApp(); +} + +static SDL_bool HAIKUAUDIO_Init(SDL_AudioDriverImpl * impl) +{ + /* Initialize the Be Application, if it's not already started */ + if (SDL_InitBeApp() < 0) { + return SDL_FALSE; + } + + /* Set the function pointers */ + impl->OpenDevice = HAIKUAUDIO_OpenDevice; + impl->CloseDevice = HAIKUAUDIO_CloseDevice; + impl->Deinitialize = HAIKUAUDIO_Deinitialize; + impl->ProvidesOwnCallbackThread = SDL_TRUE; + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +extern "C" +{ + extern AudioBootStrap HAIKUAUDIO_bootstrap; +} +AudioBootStrap HAIKUAUDIO_bootstrap = { + "haiku", "Haiku BSoundPlayer", HAIKUAUDIO_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_HAIKU */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/haiku/SDL_haikuaudio.h b/third_party/SDL2/src/audio/haiku/SDL_haikuaudio.h new file mode 100644 index 00000000000..50008de7b8b --- /dev/null +++ b/third_party/SDL2/src/audio/haiku/SDL_haikuaudio.h @@ -0,0 +1,38 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_haikuaudio_h_ +#define SDL_haikuaudio_h_ + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *_this + +struct SDL_PrivateAudioData +{ + BSoundPlayer *audio_obj; +}; + +#endif /* SDL_haikuaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/jack/SDL_jackaudio.c b/third_party/SDL2/src/audio/jack/SDL_jackaudio.c new file mode 100644 index 00000000000..697cc0afd7b --- /dev/null +++ b/third_party/SDL2/src/audio/jack/SDL_jackaudio.c @@ -0,0 +1,431 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_JACK + +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "../SDL_audio_c.h" +#include "SDL_jackaudio.h" +#include "SDL_loadso.h" +#include "../../thread/SDL_systhread.h" + +static jack_client_t *(*JACK_jack_client_open)(const char *, jack_options_t, jack_status_t *, ...); +static int (*JACK_jack_client_close)(jack_client_t *); +static void (*JACK_jack_on_shutdown)(jack_client_t *, JackShutdownCallback, void *); +static int (*JACK_jack_activate)(jack_client_t *); +static int (*JACK_jack_deactivate)(jack_client_t *); +static void *(*JACK_jack_port_get_buffer)(jack_port_t *, jack_nframes_t); +static int (*JACK_jack_port_unregister)(jack_client_t *, jack_port_t *); +static void (*JACK_jack_free)(void *); +static const char **(*JACK_jack_get_ports)(jack_client_t *, const char *, const char *, unsigned long); +static jack_nframes_t (*JACK_jack_get_sample_rate)(jack_client_t *); +static jack_nframes_t (*JACK_jack_get_buffer_size)(jack_client_t *); +static jack_port_t *(*JACK_jack_port_register)(jack_client_t *, const char *, const char *, unsigned long, unsigned long); +static jack_port_t *(*JACK_jack_port_by_name)(jack_client_t *, const char *); +static const char *(*JACK_jack_port_name)(const jack_port_t *); +static const char *(*JACK_jack_port_type)(const jack_port_t *); +static int (*JACK_jack_connect)(jack_client_t *, const char *, const char *); +static int (*JACK_jack_set_process_callback)(jack_client_t *, JackProcessCallback, void *); + +static int load_jack_syms(void); + +#ifdef SDL_AUDIO_DRIVER_JACK_DYNAMIC + +static const char *jack_library = SDL_AUDIO_DRIVER_JACK_DYNAMIC; +static void *jack_handle = NULL; + +/* !!! FIXME: this is copy/pasted in several places now */ +static int load_jack_sym(const char *fn, void **addr) +{ + *addr = SDL_LoadFunction(jack_handle, fn); + if (!*addr) { + /* Don't call SDL_SetError(): SDL_LoadFunction already did. */ + return 0; + } + + return 1; +} + +/* cast funcs to char* first, to please GCC's strict aliasing rules. */ +#define SDL_JACK_SYM(x) \ + if (!load_jack_sym(#x, (void **)(char *)&JACK_##x)) \ + return -1 + +static void UnloadJackLibrary(void) +{ + if (jack_handle) { + SDL_UnloadObject(jack_handle); + jack_handle = NULL; + } +} + +static int LoadJackLibrary(void) +{ + int retval = 0; + if (!jack_handle) { + jack_handle = SDL_LoadObject(jack_library); + if (!jack_handle) { + retval = -1; + /* Don't call SDL_SetError(): SDL_LoadObject already did. */ + } else { + retval = load_jack_syms(); + if (retval < 0) { + UnloadJackLibrary(); + } + } + } + return retval; +} + +#else + +#define SDL_JACK_SYM(x) JACK_##x = x + +static void UnloadJackLibrary(void) +{ +} + +static int LoadJackLibrary(void) +{ + load_jack_syms(); + return 0; +} + +#endif /* SDL_AUDIO_DRIVER_JACK_DYNAMIC */ + +static int load_jack_syms(void) +{ + SDL_JACK_SYM(jack_client_open); + SDL_JACK_SYM(jack_client_close); + SDL_JACK_SYM(jack_on_shutdown); + SDL_JACK_SYM(jack_activate); + SDL_JACK_SYM(jack_deactivate); + SDL_JACK_SYM(jack_port_get_buffer); + SDL_JACK_SYM(jack_port_unregister); + SDL_JACK_SYM(jack_free); + SDL_JACK_SYM(jack_get_ports); + SDL_JACK_SYM(jack_get_sample_rate); + SDL_JACK_SYM(jack_get_buffer_size); + SDL_JACK_SYM(jack_port_register); + SDL_JACK_SYM(jack_port_by_name); + SDL_JACK_SYM(jack_port_name); + SDL_JACK_SYM(jack_port_type); + SDL_JACK_SYM(jack_connect); + SDL_JACK_SYM(jack_set_process_callback); + + return 0; +} + +static void jackShutdownCallback(void *arg) /* JACK went away; device is lost. */ +{ + SDL_AudioDevice *this = (SDL_AudioDevice *)arg; + SDL_OpenedAudioDeviceDisconnected(this); + SDL_SemPost(this->hidden->iosem); /* unblock the SDL thread. */ +} + +// !!! FIXME: implement and register these! +// typedef int(* JackSampleRateCallback)(jack_nframes_t nframes, void *arg) +// typedef int(* JackBufferSizeCallback)(jack_nframes_t nframes, void *arg) + +static int jackProcessPlaybackCallback(jack_nframes_t nframes, void *arg) +{ + SDL_AudioDevice *this = (SDL_AudioDevice *)arg; + jack_port_t **ports = this->hidden->sdlports; + const int total_channels = this->spec.channels; + const int total_frames = this->spec.samples; + int channelsi; + + if (!SDL_AtomicGet(&this->enabled)) { + /* silence the buffer to avoid repeats and corruption. */ + SDL_memset(this->hidden->iobuffer, '\0', this->spec.size); + } + + for (channelsi = 0; channelsi < total_channels; channelsi++) { + float *dst = (float *)JACK_jack_port_get_buffer(ports[channelsi], nframes); + if (dst) { + const float *src = this->hidden->iobuffer + channelsi; + int framesi; + for (framesi = 0; framesi < total_frames; framesi++) { + *(dst++) = *src; + src += total_channels; + } + } + } + + SDL_SemPost(this->hidden->iosem); /* tell SDL thread we're done; refill the buffer. */ + return 0; +} + +/* This function waits until it is possible to write a full sound buffer */ +static void JACK_WaitDevice(_THIS) +{ + if (SDL_AtomicGet(&this->enabled)) { + if (SDL_SemWait(this->hidden->iosem) == -1) { + SDL_OpenedAudioDeviceDisconnected(this); + } + } +} + +static Uint8 *JACK_GetDeviceBuf(_THIS) +{ + return (Uint8 *)this->hidden->iobuffer; +} + +static int jackProcessCaptureCallback(jack_nframes_t nframes, void *arg) +{ + SDL_AudioDevice *this = (SDL_AudioDevice *)arg; + if (SDL_AtomicGet(&this->enabled)) { + jack_port_t **ports = this->hidden->sdlports; + const int total_channels = this->spec.channels; + const int total_frames = this->spec.samples; + int channelsi; + + for (channelsi = 0; channelsi < total_channels; channelsi++) { + const float *src = (const float *)JACK_jack_port_get_buffer(ports[channelsi], nframes); + if (src) { + float *dst = this->hidden->iobuffer + channelsi; + int framesi; + for (framesi = 0; framesi < total_frames; framesi++) { + *dst = *(src++); + dst += total_channels; + } + } + } + } + + SDL_SemPost(this->hidden->iosem); /* tell SDL thread we're done; new buffer is ready! */ + return 0; +} + +static int JACK_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + SDL_assert(buflen == this->spec.size); /* we always fill a full buffer. */ + + /* Wait for JACK to fill the iobuffer */ + if (SDL_SemWait(this->hidden->iosem) == -1) { + return -1; + } + + SDL_memcpy(buffer, this->hidden->iobuffer, buflen); + return buflen; +} + +static void JACK_FlushCapture(_THIS) +{ + SDL_SemWait(this->hidden->iosem); +} + +static void JACK_CloseDevice(_THIS) +{ + if (this->hidden->client) { + JACK_jack_deactivate(this->hidden->client); + + if (this->hidden->sdlports) { + const int channels = this->spec.channels; + int i; + for (i = 0; i < channels; i++) { + JACK_jack_port_unregister(this->hidden->client, this->hidden->sdlports[i]); + } + SDL_free(this->hidden->sdlports); + } + + JACK_jack_client_close(this->hidden->client); + } + + if (this->hidden->iosem) { + SDL_DestroySemaphore(this->hidden->iosem); + } + + SDL_free(this->hidden->iobuffer); + SDL_free(this->hidden); +} + +static int JACK_OpenDevice(_THIS, const char *devname) +{ + /* Note that JACK uses "output" for capture devices (they output audio + data to us) and "input" for playback (we input audio data to them). + Likewise, SDL's playback port will be "output" (we write data out) + and capture will be "input" (we read data in). */ + SDL_bool iscapture = this->iscapture; + const unsigned long sysportflags = iscapture ? JackPortIsOutput : JackPortIsInput; + const unsigned long sdlportflags = iscapture ? JackPortIsInput : JackPortIsOutput; + const JackProcessCallback callback = iscapture ? jackProcessCaptureCallback : jackProcessPlaybackCallback; + const char *sdlportstr = iscapture ? "input" : "output"; + const char **devports = NULL; + int *audio_ports; + jack_client_t *client = NULL; + jack_status_t status; + int channels = 0; + int ports = 0; + int i; + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, sizeof(*this->hidden)); + if (this->hidden == NULL) { + return SDL_OutOfMemory(); + } + + /* !!! FIXME: we _still_ need an API to specify an app name */ + client = JACK_jack_client_open("SDL", JackNoStartServer, &status, NULL); + this->hidden->client = client; + if (client == NULL) { + return SDL_SetError("Can't open JACK client"); + } + + devports = JACK_jack_get_ports(client, NULL, NULL, JackPortIsPhysical | sysportflags); + if (devports == NULL || !devports[0]) { + return SDL_SetError("No physical JACK ports available"); + } + + while (devports[++ports]) { + /* spin to count devports */ + } + + /* Filter out non-audio ports */ + audio_ports = SDL_calloc(ports, sizeof(*audio_ports)); + for (i = 0; i < ports; i++) { + const jack_port_t *dport = JACK_jack_port_by_name(client, devports[i]); + const char *type = JACK_jack_port_type(dport); + const int len = SDL_strlen(type); + /* See if type ends with "audio" */ + if (len >= 5 && !SDL_memcmp(type + len - 5, "audio", 5)) { + audio_ports[channels++] = i; + } + } + if (channels == 0) { + SDL_free(audio_ports); + return SDL_SetError("No physical JACK ports available"); + } + + /* !!! FIXME: docs say about buffer size: "This size may change, clients that depend on it must register a bufsize_callback so they will be notified if it does." */ + + /* Jack pretty much demands what it wants. */ + this->spec.format = AUDIO_F32SYS; + this->spec.freq = JACK_jack_get_sample_rate(client); + this->spec.channels = channels; + this->spec.samples = JACK_jack_get_buffer_size(client); + + SDL_CalculateAudioSpec(&this->spec); + + this->hidden->iosem = SDL_CreateSemaphore(0); + if (!this->hidden->iosem) { + SDL_free(audio_ports); + return -1; /* error was set by SDL_CreateSemaphore */ + } + + this->hidden->iobuffer = (float *)SDL_calloc(1, this->spec.size); + if (!this->hidden->iobuffer) { + SDL_free(audio_ports); + return SDL_OutOfMemory(); + } + + /* Build SDL's ports, which we will connect to the device ports. */ + this->hidden->sdlports = (jack_port_t **)SDL_calloc(channels, sizeof(jack_port_t *)); + if (!this->hidden->sdlports) { + SDL_free(audio_ports); + return SDL_OutOfMemory(); + } + + for (i = 0; i < channels; i++) { + char portname[32]; + (void)SDL_snprintf(portname, sizeof(portname), "sdl_jack_%s_%d", sdlportstr, i); + this->hidden->sdlports[i] = JACK_jack_port_register(client, portname, JACK_DEFAULT_AUDIO_TYPE, sdlportflags, 0); + if (this->hidden->sdlports[i] == NULL) { + SDL_free(audio_ports); + return SDL_SetError("jack_port_register failed"); + } + } + + if (JACK_jack_set_process_callback(client, callback, this) != 0) { + SDL_free(audio_ports); + return SDL_SetError("JACK: Couldn't set process callback"); + } + + JACK_jack_on_shutdown(client, jackShutdownCallback, this); + + if (JACK_jack_activate(client) != 0) { + SDL_free(audio_ports); + return SDL_SetError("Failed to activate JACK client"); + } + + /* once activated, we can connect all the ports. */ + for (i = 0; i < channels; i++) { + const char *sdlport = JACK_jack_port_name(this->hidden->sdlports[i]); + const char *srcport = iscapture ? devports[audio_ports[i]] : sdlport; + const char *dstport = iscapture ? sdlport : devports[audio_ports[i]]; + if (JACK_jack_connect(client, srcport, dstport) != 0) { + SDL_free(audio_ports); + return SDL_SetError("Couldn't connect JACK ports: %s => %s", srcport, dstport); + } + } + + /* don't need these anymore. */ + JACK_jack_free(devports); + SDL_free(audio_ports); + + /* We're ready to rock and roll. :-) */ + return 0; +} + +static void JACK_Deinitialize(void) +{ + UnloadJackLibrary(); +} + +static SDL_bool JACK_Init(SDL_AudioDriverImpl *impl) +{ + if (LoadJackLibrary() < 0) { + return SDL_FALSE; + } else { + /* Make sure a JACK server is running and available. */ + jack_status_t status; + jack_client_t *client = JACK_jack_client_open("SDL", JackNoStartServer, &status, NULL); + if (!client) { + UnloadJackLibrary(); + return SDL_FALSE; + } + JACK_jack_client_close(client); + } + + /* Set the function pointers */ + impl->OpenDevice = JACK_OpenDevice; + impl->WaitDevice = JACK_WaitDevice; + impl->GetDeviceBuf = JACK_GetDeviceBuf; + impl->CloseDevice = JACK_CloseDevice; + impl->Deinitialize = JACK_Deinitialize; + impl->CaptureFromDevice = JACK_CaptureFromDevice; + impl->FlushCapture = JACK_FlushCapture; + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + impl->OnlyHasDefaultCaptureDevice = SDL_TRUE; + impl->HasCaptureSupport = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap JACK_bootstrap = { + "jack", "JACK Audio Connection Kit", JACK_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_JACK */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/jack/SDL_jackaudio.h b/third_party/SDL2/src/audio/jack/SDL_jackaudio.h new file mode 100644 index 00000000000..5fbac2b2801 --- /dev/null +++ b/third_party/SDL2/src/audio/jack/SDL_jackaudio.h @@ -0,0 +1,41 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#ifndef SDL_jackaudio_h_ +#define SDL_jackaudio_h_ + +#include + +#include "../SDL_sysaudio.h" + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +struct SDL_PrivateAudioData +{ + jack_client_t *client; + SDL_sem *iosem; + float *iobuffer; + jack_port_t **sdlports; +}; + +#endif /* SDL_jackaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/n3ds/SDL_n3dsaudio.c b/third_party/SDL2/src/audio/n3ds/SDL_n3dsaudio.c new file mode 100644 index 00000000000..c577436028a --- /dev/null +++ b/third_party/SDL2/src/audio/n3ds/SDL_n3dsaudio.c @@ -0,0 +1,337 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_N3DS + +#include "SDL_audio.h" + +/* N3DS Audio driver */ + +#include "../SDL_sysaudio.h" +#include "SDL_n3dsaudio.h" +#include "SDL_timer.h" + +#define N3DSAUDIO_DRIVER_NAME "n3ds" + +static dspHookCookie dsp_hook; +static SDL_AudioDevice *audio_device; + +static void FreePrivateData(_THIS); +static int FindAudioFormat(_THIS); + +/* fully local functions related to the wavebufs / DSP, not the same as the SDL-wide mixer lock */ +static SDL_INLINE void contextLock(_THIS) +{ + LightLock_Lock(&this->hidden->lock); +} + +static SDL_INLINE void contextUnlock(_THIS) +{ + LightLock_Unlock(&this->hidden->lock); +} + +static void N3DSAUD_DspHook(DSP_HookType hook) +{ + if (hook == DSPHOOK_ONCANCEL) { + contextLock(audio_device); + audio_device->hidden->isCancelled = SDL_TRUE; + SDL_AtomicSet(&audio_device->enabled, SDL_FALSE); + CondVar_Broadcast(&audio_device->hidden->cv); + contextUnlock(audio_device); + } +} + +static void AudioFrameFinished(void *device) +{ + bool shouldBroadcast = false; + unsigned i; + SDL_AudioDevice *this = (SDL_AudioDevice *)device; + + contextLock(this); + + for (i = 0; i < NUM_BUFFERS; i++) { + if (this->hidden->waveBuf[i].status == NDSP_WBUF_DONE) { + this->hidden->waveBuf[i].status = NDSP_WBUF_FREE; + shouldBroadcast = SDL_TRUE; + } + } + + if (shouldBroadcast) { + CondVar_Broadcast(&this->hidden->cv); + } + + contextUnlock(this); +} + +static int N3DSAUDIO_OpenDevice(_THIS, const char *devname) +{ + Result ndsp_init_res; + Uint8 *data_vaddr; + float mix[12]; + this->hidden = (struct SDL_PrivateAudioData *)SDL_calloc(1, sizeof(*this->hidden)); + + if (!this->hidden) { + return SDL_OutOfMemory(); + } + + /* Initialise the DSP service */ + ndsp_init_res = ndspInit(); + if (R_FAILED(ndsp_init_res)) { + if ((R_SUMMARY(ndsp_init_res) == RS_NOTFOUND) && (R_MODULE(ndsp_init_res) == RM_DSP)) { + SDL_SetError("DSP init failed: dspfirm.cdc missing!"); + } else { + SDL_SetError("DSP init failed. Error code: 0x%lX", ndsp_init_res); + } + return -1; + } + + /* Initialise internal state */ + LightLock_Init(&this->hidden->lock); + CondVar_Init(&this->hidden->cv); + + if (this->spec.channels > 2) { + this->spec.channels = 2; + } + + /* Should not happen but better be safe. */ + if (FindAudioFormat(this) < 0) { + return SDL_SetError("No supported audio format found."); + } + + /* Update the fragment size as size in bytes */ + SDL_CalculateAudioSpec(&this->spec); + + /* Allocate mixing buffer */ + if (this->spec.size >= SDL_MAX_UINT32 / 2) { + return SDL_SetError("Mixing buffer is too large."); + } + + this->hidden->mixlen = this->spec.size; + this->hidden->mixbuf = (Uint8 *)SDL_malloc(this->spec.size); + if (!this->hidden->mixbuf) { + return SDL_OutOfMemory(); + } + + SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); + + data_vaddr = (Uint8 *)linearAlloc(this->hidden->mixlen * NUM_BUFFERS); + if (!data_vaddr) { + return SDL_OutOfMemory(); + } + + SDL_memset(data_vaddr, 0, this->hidden->mixlen * NUM_BUFFERS); + DSP_FlushDataCache(data_vaddr, this->hidden->mixlen * NUM_BUFFERS); + + this->hidden->nextbuf = 0; + this->hidden->channels = this->spec.channels; + this->hidden->samplerate = this->spec.freq; + + ndspChnReset(0); + + ndspChnSetInterp(0, NDSP_INTERP_LINEAR); + ndspChnSetRate(0, this->spec.freq); + ndspChnSetFormat(0, this->hidden->format); + + SDL_memset(mix, 0, sizeof(mix)); + mix[0] = 1.0; + mix[1] = 1.0; + ndspChnSetMix(0, mix); + + SDL_memset(this->hidden->waveBuf, 0, sizeof(ndspWaveBuf) * NUM_BUFFERS); + + for (unsigned i = 0; i < NUM_BUFFERS; i++) { + this->hidden->waveBuf[i].data_vaddr = data_vaddr; + this->hidden->waveBuf[i].nsamples = this->hidden->mixlen / this->hidden->bytePerSample; + data_vaddr += this->hidden->mixlen; + } + + /* Setup callback */ + audio_device = this; + ndspSetCallback(AudioFrameFinished, this); + dspHook(&dsp_hook, N3DSAUD_DspHook); + + return 0; +} + +static int N3DSAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + /* Delay to make this sort of simulate real audio input. */ + SDL_Delay((this->spec.samples * 1000) / this->spec.freq); + + /* always return a full buffer of silence. */ + SDL_memset(buffer, this->spec.silence, buflen); + return buflen; +} + +static void N3DSAUDIO_PlayDevice(_THIS) +{ + size_t nextbuf; + size_t sampleLen; + + contextLock(this); + + nextbuf = this->hidden->nextbuf; + sampleLen = this->hidden->mixlen; + + if (this->hidden->isCancelled || + this->hidden->waveBuf[nextbuf].status != NDSP_WBUF_FREE) { + contextUnlock(this); + return; + } + + this->hidden->nextbuf = (nextbuf + 1) % NUM_BUFFERS; + + contextUnlock(this); + + memcpy((void *)this->hidden->waveBuf[nextbuf].data_vaddr, + this->hidden->mixbuf, sampleLen); + DSP_FlushDataCache(this->hidden->waveBuf[nextbuf].data_vaddr, sampleLen); + + ndspChnWaveBufAdd(0, &this->hidden->waveBuf[nextbuf]); +} + +static void N3DSAUDIO_WaitDevice(_THIS) +{ + contextLock(this); + while (!this->hidden->isCancelled && + this->hidden->waveBuf[this->hidden->nextbuf].status != NDSP_WBUF_FREE) { + CondVar_Wait(&this->hidden->cv, &this->hidden->lock); + } + contextUnlock(this); +} + +static Uint8 *N3DSAUDIO_GetDeviceBuf(_THIS) +{ + return this->hidden->mixbuf; +} + +static void N3DSAUDIO_CloseDevice(_THIS) +{ + contextLock(this); + + dspUnhook(&dsp_hook); + ndspSetCallback(NULL, NULL); + + if (!this->hidden->isCancelled) { + ndspChnReset(0); + memset(this->hidden->waveBuf, 0, sizeof(ndspWaveBuf) * NUM_BUFFERS); + CondVar_Broadcast(&this->hidden->cv); + } + + contextUnlock(this); + + ndspExit(); + + FreePrivateData(this); +} + +static void N3DSAUDIO_ThreadInit(_THIS) +{ + s32 current_priority = 0x30; + svcGetThreadPriority(¤t_priority, CUR_THREAD_HANDLE); + current_priority--; + /* 0x18 is reserved for video, 0x30 is the default for main thread */ + current_priority = SDL_clamp(current_priority, 0x19, 0x2F); + svcSetThreadPriority(CUR_THREAD_HANDLE, current_priority); +} + +static SDL_bool N3DSAUDIO_Init(SDL_AudioDriverImpl *impl) +{ + /* Set the function pointers */ + impl->OpenDevice = N3DSAUDIO_OpenDevice; + impl->PlayDevice = N3DSAUDIO_PlayDevice; + impl->WaitDevice = N3DSAUDIO_WaitDevice; + impl->GetDeviceBuf = N3DSAUDIO_GetDeviceBuf; + impl->CloseDevice = N3DSAUDIO_CloseDevice; + impl->ThreadInit = N3DSAUDIO_ThreadInit; + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + + /* Should be possible, but micInit would fail */ + impl->HasCaptureSupport = SDL_FALSE; + impl->CaptureFromDevice = N3DSAUDIO_CaptureFromDevice; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap N3DSAUDIO_bootstrap = { + N3DSAUDIO_DRIVER_NAME, + "SDL N3DS audio driver", + N3DSAUDIO_Init, + 0 +}; + +/** + * Cleans up all allocated memory, safe to call with null pointers + */ +static void FreePrivateData(_THIS) +{ + if (!this->hidden) { + return; + } + + if (this->hidden->waveBuf[0].data_vaddr) { + linearFree((void *)this->hidden->waveBuf[0].data_vaddr); + } + + if (this->hidden->mixbuf) { + SDL_free(this->hidden->mixbuf); + this->hidden->mixbuf = NULL; + } + + SDL_free(this->hidden); + this->hidden = NULL; +} + +static int FindAudioFormat(_THIS) +{ + SDL_bool found_valid_format = SDL_FALSE; + Uint16 test_format = SDL_FirstAudioFormat(this->spec.format); + + while (!found_valid_format && test_format) { + this->spec.format = test_format; + switch (test_format) { + case AUDIO_S8: + /* Signed 8-bit audio supported */ + this->hidden->format = (this->spec.channels == 2) ? NDSP_FORMAT_STEREO_PCM8 : NDSP_FORMAT_MONO_PCM8; + this->hidden->isSigned = 1; + this->hidden->bytePerSample = this->spec.channels; + found_valid_format = SDL_TRUE; + break; + case AUDIO_S16: + /* Signed 16-bit audio supported */ + this->hidden->format = (this->spec.channels == 2) ? NDSP_FORMAT_STEREO_PCM16 : NDSP_FORMAT_MONO_PCM16; + this->hidden->isSigned = 1; + this->hidden->bytePerSample = this->spec.channels * 2; + found_valid_format = SDL_TRUE; + break; + default: + test_format = SDL_NextAudioFormat(); + break; + } + } + + return found_valid_format ? 0 : -1; +} + +#endif /* SDL_AUDIO_DRIVER_N3DS */ + +/* vi: set sts=4 ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/n3ds/SDL_n3dsaudio.h b/third_party/SDL2/src/audio/n3ds/SDL_n3dsaudio.h new file mode 100644 index 00000000000..dbd9d61b506 --- /dev/null +++ b/third_party/SDL2/src/audio/n3ds/SDL_n3dsaudio.h @@ -0,0 +1,50 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef _SDL_n3dsaudio_h_ +#define _SDL_n3dsaudio_h_ + +#include <3ds.h> + +/* Hidden "this" pointer for the audio functions */ +#define _THIS SDL_AudioDevice *this + +#define NUM_BUFFERS 3 /* -- Minimum 2! */ + +struct SDL_PrivateAudioData +{ + /* Speaker data */ + Uint8 *mixbuf; + Uint32 mixlen; + Uint32 format; + Uint32 samplerate; + Uint32 channels; + Uint8 bytePerSample; + Uint32 isSigned; + Uint32 nextbuf; + ndspWaveBuf waveBuf[NUM_BUFFERS]; + LightLock lock; + CondVar cv; + SDL_bool isCancelled; +}; + +#endif /* _SDL_n3dsaudio_h_ */ +/* vi: set sts=4 ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/nacl/SDL_naclaudio.c b/third_party/SDL2/src/audio/nacl/SDL_naclaudio.c new file mode 100644 index 00000000000..c592aaaa6f3 --- /dev/null +++ b/third_party/SDL2/src/audio/nacl/SDL_naclaudio.c @@ -0,0 +1,161 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_NACL + +#include "SDL_naclaudio.h" + +#include "SDL_audio.h" +#include "SDL_mutex.h" +#include "../SDL_audio_c.h" +#include "../SDL_audiodev_c.h" + +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/pp_instance.h" +#include "ppapi_simple/ps.h" +#include "ppapi_simple/ps_interface.h" +#include "ppapi_simple/ps_event.h" + +/* The tag name used by NACL audio */ +#define NACLAUDIO_DRIVER_NAME "nacl" + +#define SAMPLE_FRAME_COUNT 4096 + +/* Audio driver functions */ +static void nacl_audio_callback(void* samples, uint32_t buffer_size, PP_TimeDelta latency, void* data); + +/* FIXME: Make use of latency if needed */ +static void nacl_audio_callback(void* stream, uint32_t buffer_size, PP_TimeDelta latency, void* data) +{ + const int len = (int) buffer_size; + SDL_AudioDevice* _this = (SDL_AudioDevice*) data; + SDL_AudioCallback callback = _this->callbackspec.callback; + + SDL_LockMutex(_this->mixer_lock); + + /* Only do something if audio is enabled */ + if (!SDL_AtomicGet(&_this->enabled) || SDL_AtomicGet(&_this->paused)) { + if (_this->stream) { + SDL_AudioStreamClear(_this->stream); + } + SDL_memset(stream, _this->spec.silence, len); + } else { + SDL_assert(_this->spec.size == len); + + if (!_this->stream) { /* no conversion necessary. */ + callback(_this->callbackspec.userdata, stream, len); + } else { /* streaming/converting */ + const int stream_len = _this->callbackspec.size; + while (SDL_AudioStreamAvailable(_this->stream) < len) { + callback(_this->callbackspec.userdata, _this->work_buffer, stream_len); + if (SDL_AudioStreamPut(_this->stream, _this->work_buffer, stream_len) == -1) { + SDL_AudioStreamClear(_this->stream); + SDL_AtomicSet(&_this->enabled, 0); + break; + } + } + + const int got = SDL_AudioStreamGet(_this->stream, stream, len); + SDL_assert((got < 0) || (got == len)); + if (got != len) { + SDL_memset(stream, _this->spec.silence, len); + } + } + } + + SDL_UnlockMutex(_this->mixer_lock); +} + +static void NACLAUDIO_CloseDevice(SDL_AudioDevice *device) +{ + const PPB_Core *core = PSInterfaceCore(); + const PPB_Audio *ppb_audio = PSInterfaceAudio(); + SDL_PrivateAudioData *hidden = (SDL_PrivateAudioData *) device->hidden; + + ppb_audio->StopPlayback(hidden->audio); + core->ReleaseResource(hidden->audio); +} + +static int NACLAUDIO_OpenDevice(_THIS, const char *devname) +{ + PP_Instance instance = PSGetInstanceId(); + const PPB_Audio *ppb_audio = PSInterfaceAudio(); + const PPB_AudioConfig *ppb_audiocfg = PSInterfaceAudioConfig(); + + private = (SDL_PrivateAudioData *)SDL_calloc(1, sizeof(*private)); + if (!private) { + return SDL_OutOfMemory(); + } + + _this->spec.freq = 44100; + _this->spec.format = AUDIO_S16LSB; + _this->spec.channels = 2; + _this->spec.samples = ppb_audiocfg->RecommendSampleFrameCount( + instance, + PP_AUDIOSAMPLERATE_44100, + SAMPLE_FRAME_COUNT); + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&_this->spec); + + private->audio = ppb_audio->Create( + instance, + ppb_audiocfg->CreateStereo16Bit(instance, PP_AUDIOSAMPLERATE_44100, _this->spec.samples), + nacl_audio_callback, + _this); + + /* Start audio playback while we are still on the main thread. */ + ppb_audio->StartPlayback(private->audio); + + return 0; +} + +static SDL_bool NACLAUDIO_Init(SDL_AudioDriverImpl * impl) +{ + if (PSGetInstanceId() == 0) { + return SDL_FALSE; + } + + /* Set the function pointers */ + impl->OpenDevice = NACLAUDIO_OpenDevice; + impl->CloseDevice = NACLAUDIO_CloseDevice; + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + impl->ProvidesOwnCallbackThread = SDL_TRUE; + /* + * impl->WaitDevice = NACLAUDIO_WaitDevice; + * impl->GetDeviceBuf = NACLAUDIO_GetDeviceBuf; + * impl->PlayDevice = NACLAUDIO_PlayDevice; + * impl->Deinitialize = NACLAUDIO_Deinitialize; + */ + + return SDL_TRUE; +} + +AudioBootStrap NACLAUDIO_bootstrap = { + NACLAUDIO_DRIVER_NAME, "SDL NaCl Audio Driver", + NACLAUDIO_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_NACL */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/nacl/SDL_naclaudio.h b/third_party/SDL2/src/audio/nacl/SDL_naclaudio.h new file mode 100644 index 00000000000..c47f544d15a --- /dev/null +++ b/third_party/SDL2/src/audio/nacl/SDL_naclaudio.h @@ -0,0 +1,42 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#include "../../SDL_internal.h" + +#ifndef SDL_naclaudio_h_ +#define SDL_naclaudio_h_ + +#include "SDL_audio.h" +#include "../SDL_sysaudio.h" +#include "SDL_mutex.h" + +#include "ppapi/c/ppb_audio.h" + +#define _THIS SDL_AudioDevice *_this +#define private _this->hidden + +typedef struct SDL_PrivateAudioData { + PP_Resource audio; +} SDL_PrivateAudioData; + +#endif /* SDL_naclaudio_h_ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/nas/SDL_nasaudio.c b/third_party/SDL2/src/audio/nas/SDL_nasaudio.c new file mode 100644 index 00000000000..22301e567a6 --- /dev/null +++ b/third_party/SDL2/src/audio/nas/SDL_nasaudio.c @@ -0,0 +1,443 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifdef SDL_AUDIO_DRIVER_NAS + +/* Allow access to a raw mixing buffer */ + +#include +#include + +#include "SDL_timer.h" +#include "SDL_audio.h" +#include "SDL_loadso.h" +#include "../SDL_audio_c.h" +#include "SDL_nasaudio.h" + +static void (*NAS_AuCloseServer) (AuServer *); +static void (*NAS_AuNextEvent) (AuServer *, AuBool, AuEvent *); +static AuBool(*NAS_AuDispatchEvent) (AuServer *, AuEvent *); +static void (*NAS_AuHandleEvents) (AuServer *); +static AuFlowID(*NAS_AuCreateFlow) (AuServer *, AuStatus *); +static void (*NAS_AuStartFlow) (AuServer *, AuFlowID, AuStatus *); +static void (*NAS_AuSetElements) + (AuServer *, AuFlowID, AuBool, int, AuElement *, AuStatus *); +static void (*NAS_AuWriteElement) + (AuServer *, AuFlowID, int, AuUint32, AuPointer, AuBool, AuStatus *); +static AuUint32 (*NAS_AuReadElement) + (AuServer *, AuFlowID, int, AuUint32, AuPointer, AuStatus *); +static AuServer *(*NAS_AuOpenServer) + (_AuConst char *, int, _AuConst char *, int, _AuConst char *, char **); +static AuEventHandlerRec *(*NAS_AuRegisterEventHandler) + (AuServer *, AuMask, int, AuID, AuEventHandlerCallback, AuPointer); + + +#ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC + +static const char *nas_library = SDL_AUDIO_DRIVER_NAS_DYNAMIC; +static void *nas_handle = NULL; + +static int load_nas_sym(const char *fn, void **addr) +{ + *addr = SDL_LoadFunction(nas_handle, fn); + if (!*addr) { + return 0; + } + return 1; +} + +/* cast funcs to char* first, to please GCC's strict aliasing rules. */ +#define SDL_NAS_SYM(x) \ + if (!load_nas_sym(#x, (void **) (char *) &NAS_##x)) return -1 +#else +#define SDL_NAS_SYM(x) NAS_##x = x +#endif + +static int load_nas_syms(void) +{ + SDL_NAS_SYM(AuCloseServer); + SDL_NAS_SYM(AuNextEvent); + SDL_NAS_SYM(AuDispatchEvent); + SDL_NAS_SYM(AuHandleEvents); + SDL_NAS_SYM(AuCreateFlow); + SDL_NAS_SYM(AuStartFlow); + SDL_NAS_SYM(AuSetElements); + SDL_NAS_SYM(AuWriteElement); + SDL_NAS_SYM(AuReadElement); + SDL_NAS_SYM(AuOpenServer); + SDL_NAS_SYM(AuRegisterEventHandler); + return 0; +} + +#undef SDL_NAS_SYM + +#ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC + +static void UnloadNASLibrary(void) +{ + if (nas_handle) { + SDL_UnloadObject(nas_handle); + nas_handle = NULL; + } +} + +static int LoadNASLibrary(void) +{ + int retval = 0; + if (!nas_handle) { + nas_handle = SDL_LoadObject(nas_library); + if (!nas_handle) { + /* Copy error string so we can use it in a new SDL_SetError(). */ + const char *origerr = SDL_GetError(); + const size_t len = SDL_strlen(origerr) + 1; + char *err = SDL_stack_alloc(char, len); + SDL_strlcpy(err, origerr, len); + SDL_SetError("NAS: SDL_LoadObject('%s') failed: %s", nas_library, err); + SDL_stack_free(err); + retval = -1; + } else { + retval = load_nas_syms(); + if (retval < 0) { + UnloadNASLibrary(); + } + } + } + return retval; +} + +#else + +static void UnloadNASLibrary(void) +{ +} + +static int LoadNASLibrary(void) +{ + load_nas_syms(); + return 0; +} + +#endif /* SDL_AUDIO_DRIVER_NAS_DYNAMIC */ + +/* This function waits until it is possible to write a full sound buffer */ +static void NAS_WaitDevice(_THIS) +{ + while (this->hidden->buf_free < this->hidden->mixlen) { + AuEvent ev; + NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev); + NAS_AuDispatchEvent(this->hidden->aud, &ev); + } +} + +static void NAS_PlayDevice(_THIS) +{ + while (this->hidden->mixlen > this->hidden->buf_free) { + /* + * We think the buffer is full? Yikes! Ask the server for events, + * in the hope that some of them is LowWater events telling us more + * of the buffer is free now than what we think. + */ + AuEvent ev; + NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev); + NAS_AuDispatchEvent(this->hidden->aud, &ev); + } + this->hidden->buf_free -= this->hidden->mixlen; + + /* Write the audio data */ + NAS_AuWriteElement(this->hidden->aud, this->hidden->flow, 0, + this->hidden->mixlen, this->hidden->mixbuf, AuFalse, + NULL); + + this->hidden->written += this->hidden->mixlen; + +#ifdef DEBUG_AUDIO + fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen); +#endif +} + +static Uint8 *NAS_GetDeviceBuf(_THIS) +{ + return (this->hidden->mixbuf); +} + +static int NAS_CaptureFromDevice(_THIS, void *buffer, int buflen) +{ + struct SDL_PrivateAudioData *h = this->hidden; + int retval; + + while (SDL_TRUE) { + /* just keep the event queue moving and the server chattering. */ + NAS_AuHandleEvents(h->aud); + + retval = (int) NAS_AuReadElement(h->aud, h->flow, 1, buflen, buffer, NULL); + /*printf("read %d capture bytes\n", (int) retval);*/ + if (retval == 0) { + SDL_Delay(10); /* don't burn the CPU if we're waiting for data. */ + } else { + break; + } + } + + return retval; +} + +static void NAS_FlushCapture(_THIS) +{ + struct SDL_PrivateAudioData *h = this->hidden; + AuUint32 total = 0; + AuUint32 br; + Uint8 buf[512]; + + do { + /* just keep the event queue moving and the server chattering. */ + NAS_AuHandleEvents(h->aud); + br = NAS_AuReadElement(h->aud, h->flow, 1, sizeof(buf), buf, NULL); + /*printf("flushed %d capture bytes\n", (int) br);*/ + total += br; + } while ((br == sizeof(buf)) && (total < this->spec.size)); +} + +static void NAS_CloseDevice(_THIS) +{ + if (this->hidden->aud) { + NAS_AuCloseServer(this->hidden->aud); + } + SDL_free(this->hidden->mixbuf); + SDL_free(this->hidden); +} + +static AuBool event_handler(AuServer * aud, AuEvent * ev, AuEventHandlerRec * hnd) +{ + SDL_AudioDevice *this = (SDL_AudioDevice *) hnd->data; + struct SDL_PrivateAudioData *h = this->hidden; + if (this->iscapture) { + return AuTrue; /* we don't (currently) care about any of this for capture devices */ + } + + switch (ev->type) { + case AuEventTypeElementNotify: + { + AuElementNotifyEvent *event = (AuElementNotifyEvent *) ev; + + switch (event->kind) { + case AuElementNotifyKindLowWater: + if (h->buf_free >= 0) { + h->really += event->num_bytes; + gettimeofday(&h->last_tv, 0); + h->buf_free += event->num_bytes; + } else { + h->buf_free = event->num_bytes; + } + break; + case AuElementNotifyKindState: + switch (event->cur_state) { + case AuStatePause: + if (event->reason != AuReasonUser) { + if (h->buf_free >= 0) { + h->really += event->num_bytes; + gettimeofday(&h->last_tv, 0); + h->buf_free += event->num_bytes; + } else { + h->buf_free = event->num_bytes; + } + } + break; + } + } + } + } + return AuTrue; +} + +static AuDeviceID find_device(_THIS) +{ + /* These "Au" things are all macros, not functions... */ + struct SDL_PrivateAudioData *h = this->hidden; + const unsigned int devicekind = this->iscapture ? AuComponentKindPhysicalInput : AuComponentKindPhysicalOutput; + const int numdevs = AuServerNumDevices(h->aud); + const int nch = this->spec.channels; + int i; + + /* Try to find exact match on channels first... */ + for (i = 0; i < numdevs; i++) { + const AuDeviceAttributes *dev = AuServerDevice(h->aud, i); + if ((AuDeviceKind(dev) == devicekind) && (AuDeviceNumTracks(dev) == nch)) { + return AuDeviceIdentifier(dev); + } + } + + /* Take anything, then... */ + for (i = 0; i < numdevs; i++) { + const AuDeviceAttributes *dev = AuServerDevice(h->aud, i); + if (AuDeviceKind(dev) == devicekind) { + this->spec.channels = AuDeviceNumTracks(dev); + return AuDeviceIdentifier(dev); + } + } + return AuNone; +} + +static int NAS_OpenDevice(_THIS, const char *devname) +{ + AuElement elms[3]; + int buffer_size; + SDL_bool iscapture = this->iscapture; + SDL_AudioFormat test_format, format = 0; + + /* Initialize all variables that we clean on shutdown */ + this->hidden = (struct SDL_PrivateAudioData *)SDL_malloc(sizeof(*this->hidden)); + if (!this->hidden) { + return SDL_OutOfMemory(); + } + SDL_zerop(this->hidden); + + /* Try for a closest match on audio format */ + for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) { + switch (test_format) { + case AUDIO_U8: + format = AuFormatLinearUnsigned8; + break; + case AUDIO_S8: + format = AuFormatLinearSigned8; + break; + case AUDIO_U16LSB: + format = AuFormatLinearUnsigned16LSB; + break; + case AUDIO_U16MSB: + format = AuFormatLinearUnsigned16MSB; + break; + case AUDIO_S16LSB: + format = AuFormatLinearSigned16LSB; + break; + case AUDIO_S16MSB: + format = AuFormatLinearSigned16MSB; + break; + default: + continue; + } + break; + } + if (!test_format) { + return SDL_SetError("%s: Unsupported audio format", "nas"); + } + this->spec.format = test_format; + + this->hidden->aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL); + if (this->hidden->aud == 0) { + return SDL_SetError("NAS: Couldn't open connection to NAS server"); + } + + this->hidden->dev = find_device(this); + if ((this->hidden->dev == AuNone) + || (!(this->hidden->flow = NAS_AuCreateFlow(this->hidden->aud, 0)))) { + return SDL_SetError("NAS: Couldn't find a fitting device on NAS server"); + } + + buffer_size = this->spec.freq; + if (buffer_size < 4096) + buffer_size = 4096; + + if (buffer_size > 32768) + buffer_size = 32768; /* So that the buffer won't get unmanageably big. */ + + /* Calculate the final parameters for this audio specification */ + SDL_CalculateAudioSpec(&this->spec); + + if (iscapture) { + AuMakeElementImportDevice(elms, this->spec.freq, this->hidden->dev, + AuUnlimitedSamples, 0, NULL); + AuMakeElementExportClient(elms + 1, 0, this->spec.freq, format, + this->spec.channels, AuTrue, buffer_size, + buffer_size, 0, NULL); + } else { + AuMakeElementImportClient(elms, this->spec.freq, format, + this->spec.channels, AuTrue, buffer_size, + buffer_size / 4, 0, NULL); + AuMakeElementExportDevice(elms + 1, 0, this->hidden->dev, this->spec.freq, + AuUnlimitedSamples, 0, NULL); + } + + NAS_AuSetElements(this->hidden->aud, this->hidden->flow, AuTrue, + 2, elms, NULL); + + NAS_AuRegisterEventHandler(this->hidden->aud, AuEventHandlerIDMask, 0, + this->hidden->flow, event_handler, + (AuPointer) this); + + NAS_AuStartFlow(this->hidden->aud, this->hidden->flow, NULL); + + /* Allocate mixing buffer */ + if (!iscapture) { + this->hidden->mixlen = this->spec.size; + this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); + if (!this->hidden->mixbuf) { + return SDL_OutOfMemory(); + } + SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); + } + + /* We're ready to rock and roll. :-) */ + return 0; +} + +static void NAS_Deinitialize(void) +{ + UnloadNASLibrary(); +} + +static SDL_bool NAS_Init(SDL_AudioDriverImpl * impl) +{ + if (LoadNASLibrary() < 0) { + return SDL_FALSE; + } else { + AuServer *aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL); + if (!aud) { + SDL_SetError("NAS: AuOpenServer() failed (no audio server?)"); + return SDL_FALSE; + } + NAS_AuCloseServer(aud); + } + + /* Set the function pointers */ + impl->OpenDevice = NAS_OpenDevice; + impl->PlayDevice = NAS_PlayDevice; + impl->WaitDevice = NAS_WaitDevice; + impl->GetDeviceBuf = NAS_GetDeviceBuf; + impl->CaptureFromDevice = NAS_CaptureFromDevice; + impl->FlushCapture = NAS_FlushCapture; + impl->CloseDevice = NAS_CloseDevice; + impl->Deinitialize = NAS_Deinitialize; + + impl->OnlyHasDefaultOutputDevice = SDL_TRUE; + impl->OnlyHasDefaultCaptureDevice = SDL_TRUE; + impl->HasCaptureSupport = SDL_TRUE; + + return SDL_TRUE; /* this audio target is available. */ +} + +AudioBootStrap NAS_bootstrap = { + "nas", "Network Audio System", NAS_Init, SDL_FALSE +}; + +#endif /* SDL_AUDIO_DRIVER_NAS */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/third_party/SDL2/src/audio/nas/SDL_nasaudio.h b/third_party/SDL2/src/audio/nas/SDL_nasaudio.h new file mode 100644 index 00000000000..eaa3b3797b0 --- /dev/null +++ b/third_party/SDL2/src/audio/nas/SDL_nasaudio.h @@ -0,0 +1,56 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2025 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "../../SDL_internal.h" + +#ifndef SDL_nasaudio_h_ +#define SDL_nasaudio_h_ + +#ifdef __sgi +#include +#else +#include