diff --git a/.gitignore b/.gitignore index 67907ad2..8edc843c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ Bonzomatic .obj +.aps tmp build build.* diff --git a/src/Capture.h b/src/Capture.h index fdfbce00..a4544e77 100644 --- a/src/Capture.h +++ b/src/Capture.h @@ -1,7 +1,11 @@ namespace Capture { - void LoadSettings(jsonxx::Object & o); - bool Open(RENDERER_SETTINGS & settings); - void CaptureFrame(); - void Close(); +////////////////////////////////////////////////////////////////////////// + +void LoadSettings( jsonxx::Object & o ); +bool Open( Renderer::Settings & settings ); +void CaptureFrame(); +void Close(); + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/Clipboard.h b/src/Clipboard.h index 7ebe5f6d..06e6c71e 100644 --- a/src/Clipboard.h +++ b/src/Clipboard.h @@ -1,6 +1,10 @@ namespace Clipboard { - void Copy( const char * data, int len ); - int GetContentsLength(); - void GetContents( char * data, int len ); +////////////////////////////////////////////////////////////////////////// + +void Copy( const char * data, int len ); +int GetContentsLength(); +void GetContents( char * data, int len ); + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/FFT.h b/src/FFT.h index 82e424f5..41a01231 100644 --- a/src/FFT.h +++ b/src/FFT.h @@ -1,22 +1,26 @@ #define FFT_SIZE 1024 -typedef struct +namespace FFT +{ +////////////////////////////////////////////////////////////////////////// + +struct Settings { bool bUseRecordingDevice; void * pDeviceID; -} FFT_SETTINGS; +}; -namespace FFT -{ - typedef void (*FFT_ENUMERATE_FUNC)( const bool bIsCaptureDevice, const char * szDeviceName, void * pDeviceID, void * pUserContext ); +typedef void ( *FFT_ENUMERATE_FUNC )( const bool bIsCaptureDevice, const char * szDeviceName, void * pDeviceID, void * pUserContext ); + +extern float fAmplification; - extern float fAmplification; +void EnumerateDevices( FFT_ENUMERATE_FUNC pEnumerationFunction, void * pUserContext ); - void EnumerateDevices( FFT_ENUMERATE_FUNC pEnumerationFunction, void * pUserContext ); +bool Create(); +bool Destroy(); +bool Open( Settings * pSettings ); +bool GetFFT( float * _samples ); +void Close(); - bool Create(); - bool Destroy(); - bool Open( FFT_SETTINGS * pSettings ); - bool GetFFT( float * _samples ); - void Close(); +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/MIDI.h b/src/MIDI.h index 109cf4cf..68cea303 100644 --- a/src/MIDI.h +++ b/src/MIDI.h @@ -1,18 +1,22 @@ namespace MIDI { - enum - { - MIDIMSG_NOTE_OFF = 8, - MIDIMSG_NOTE_ON = 9, - MIDIMSG_POLYPHONIC_KEY = 10, - MIDIMSG_CONTROL_CHANGE = 11, - MIDIMSG_PROGRAM_CHANGE = 12, - MIDIMSG_CHANNEL_PRESSURE = 13, - MIDIMSG_PITCH_BEND = 14, - MIDIMSG_SYSTEM = 15, - } MIDI_MESSAGE_TYPE; +////////////////////////////////////////////////////////////////////////// - bool Open(); - bool Close(); - float GetCCValue( unsigned char cc ); +enum +{ + MIDIMSG_NOTE_OFF = 8, + MIDIMSG_NOTE_ON = 9, + MIDIMSG_POLYPHONIC_KEY = 10, + MIDIMSG_CONTROL_CHANGE = 11, + MIDIMSG_PROGRAM_CHANGE = 12, + MIDIMSG_CHANNEL_PRESSURE = 13, + MIDIMSG_PITCH_BEND = 14, + MIDIMSG_SYSTEM = 15, +} MIDI_MESSAGE_TYPE; + +bool Open(); +bool Close(); +float GetCCValue( unsigned char cc ); + +////////////////////////////////////////////////////////////////////////// }; \ No newline at end of file diff --git a/src/Misc.h b/src/Misc.h index f98f4324..f5829205 100644 --- a/src/Misc.h +++ b/src/Misc.h @@ -2,13 +2,17 @@ namespace Misc { - void PlatformStartup(); - void PlatformShutdown(); +////////////////////////////////////////////////////////////////////////// - void InitKeymaps(); - void GetKeymapName( char * sz ); - bool ExecuteCommand( const char * cmd, const char * param ); +void PlatformStartup(); +void PlatformShutdown(); - bool FileExists(const char * path); - const char * GetDefaultFontPath(); +void InitKeymaps(); +void GetKeymapName( char * sz ); +bool ExecuteCommand( const char * cmd, const char * param ); + +bool FileExists( const char * path ); +const char * GetDefaultFontPath(); + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/Platform.cpp b/src/Platform.cpp index 42b38811..9b4d814a 100644 --- a/src/Platform.cpp +++ b/src/Platform.cpp @@ -27,29 +27,29 @@ using namespace Scintilla; ////////////////////////////////////////////////////////////////////////// // this is only used if we support loading external lexers, which we don't -DynamicLibrary *DynamicLibrary::Load(const char *modulePath) +DynamicLibrary * DynamicLibrary::Load( const char * modulePath ) { return NULL; } ////////////////////////////////////////////////////////////////////////// -ColourDesired MakeRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a=0xFF) +ColourDesired MakeRGBA( unsigned char r, unsigned char g, unsigned char b, unsigned char a = 0xFF ) { - return a<<24 | b<<16 | g<<8 | r; + return a << 24 | b << 16 | g << 8 | r; } ColourDesired Platform::Chrome() { - return MakeRGBA(0xe0, 0xe0, 0xe0); + return MakeRGBA( 0xe0, 0xe0, 0xe0 ); } ColourDesired Platform::ChromeHighlight() { - return MakeRGBA(0xff, 0xff, 0xff); + return MakeRGBA( 0xff, 0xff, 0xff ); } -const char *Platform::DefaultFont() +const char * Platform::DefaultFont() { return "Lucida Console"; } @@ -69,29 +69,29 @@ bool Platform::MouseButtonBounce() return true; } -void Platform::Assert(const char *c, const char *file, int line) +void Platform::Assert( const char * c, const char * file, int line ) { - char buffer[2000]; - sprintf(buffer, "Assertion [%s] failed at %s %d", c, file, line); - strcat(buffer, "\r\n"); - assert(false); + char buffer[ 2000 ]; + sprintf( buffer, "Assertion [%s] failed at %s %d", c, file, line ); + strcat( buffer, "\r\n" ); + assert( false ); } -int Platform::Minimum(int a, int b) { return ab ? a : b; } -int Platform::Clamp(int val, int minVal, int maxVal) { return Minimum( maxVal, Maximum( val, minVal ) ); } +int Platform::Minimum( int a, int b ) { return a < b ? a : b; } +int Platform::Maximum( int a, int b ) { return a > b ? a : b; } +int Platform::Clamp( int val, int minVal, int maxVal ) { return Minimum( maxVal, Maximum( val, minVal ) ); } #ifdef TRACE -void Platform::DebugPrintf(const char *format, ...) +void Platform::DebugPrintf( const char * format, ... ) { - char buffer[2000]; + char buffer[ 2000 ]; va_list pArguments; - va_start(pArguments, format); - vsprintf(buffer,format,pArguments); - va_end(pArguments); - Platform::DebugDisplay(buffer); + va_start( pArguments, format ); + vsprintf( buffer, format, pArguments ); + va_end( pArguments ); + Platform::DebugDisplay( buffer ); } #else -void Platform::DebugPrintf(const char *, ...) +void Platform::DebugPrintf( const char *, ... ) { } #endif @@ -104,12 +104,12 @@ void Platform::DebugPrintf(const char *, ...) struct stbtt_Font { stbtt_fontinfo fontinfo; - stbtt_bakedchar cdata[CHARACTER_COUNT]; + stbtt_bakedchar cdata[ CHARACTER_COUNT ]; float scale; Renderer::Texture * texture; }; -Font::Font() : fid(0) +Font::Font() : fid( 0 ) { } @@ -117,51 +117,51 @@ Font::~Font() { } -void Font::Create(const FontParameters &fp) +void Font::Create( const FontParameters & fp ) { - stbtt_Font* newFont = new stbtt_Font; + stbtt_Font * newFont = new stbtt_Font; - FILE* f = fopen(fp.faceName, "rb"); + FILE * f = fopen( fp.faceName, "rb" ); - assert(f); + assert( f ); - fseek(f, 0, SEEK_END); - size_t len = ftell(f); - fseek(f, 0, SEEK_SET); + fseek( f, 0, SEEK_END ); + size_t len = ftell( f ); + fseek( f, 0, SEEK_SET ); int texSize = 512; - unsigned char* buf = (unsigned char*)malloc(len); - fread(buf, 1, len, f); - fclose(f); + unsigned char * buf = (unsigned char *) malloc( len ); + fread( buf, 1, len, f ); + fclose( f ); - unsigned char* bmp = new unsigned char[texSize*texSize]; + unsigned char * bmp = new unsigned char[ texSize * texSize ]; - stbtt_BakeFontBitmap(buf, 0, fp.size, bmp, texSize, texSize, 0, CHARACTER_COUNT, newFont->cdata); // no guarantee this fits! + stbtt_BakeFontBitmap( buf, 0, fp.size, bmp, texSize, texSize, 0, CHARACTER_COUNT, newFont->cdata ); // no guarantee this fits! #ifdef _DEBUG - FILE* dump = fopen("font.raw", "wb"); - fwrite(bmp,texSize,texSize,dump); - fclose(dump); + FILE * dump = fopen( "font.raw", "wb" ); + fwrite( bmp, texSize, texSize, dump ); + fclose( dump ); #endif // _DEBUG newFont->texture = Renderer::CreateA8TextureFromData( texSize, texSize, bmp ); - stbtt_InitFont(&newFont->fontinfo, buf, 0); + stbtt_InitFont( &newFont->fontinfo, buf, 0 ); - newFont->scale = stbtt_ScaleForPixelHeight(&newFont->fontinfo, fp.size); + newFont->scale = stbtt_ScaleForPixelHeight( &newFont->fontinfo, fp.size ); - delete [] bmp; + delete[] bmp; fid = newFont; } void Font::Release() { - if (fid) + if ( fid ) { - free(((stbtt_Font*)fid)->fontinfo.data); - Renderer::ReleaseTexture( ((stbtt_Font*)fid)->texture ); - delete (stbtt_Font*)fid; + free( ( (stbtt_Font *) fid )->fontinfo.data ); + Renderer::ReleaseTexture( ( (stbtt_Font *) fid )->texture ); + delete (stbtt_Font *) fid; } } @@ -183,60 +183,60 @@ class SurfaceImpl : public Surface { SurfaceImpl(); virtual ~SurfaceImpl(); - void Init(WindowID wid); - void Init(SurfaceID sid, WindowID wid); - void InitPixMap(int width, int height, Surface *surface, WindowID wid); + void Init( WindowID wid ); + void Init( SurfaceID sid, WindowID wid ); + void InitPixMap( int width, int height, Surface * surface, WindowID wid ); void Release(); bool Initialised(); - void PenColour(ColourDesired fore); + void PenColour( ColourDesired fore ); int LogPixelsY(); - int DeviceHeightFont(int points); - void MoveTo(float x, float y); - void LineTo(float x, float y); - void Polygon(Point *pts, int npts, ColourDesired fore, ColourDesired back); - void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back); - void FillRectangle(PRectangle rc, ColourDesired back); - void FillRectangle(PRectangle rc, Surface &surfacePattern); - void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back); - void AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill, - ColourDesired outline, int alphaOutline, int flags); - void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back); - void Copy(PRectangle rc, Point from, Surface &surfaceSource); + int DeviceHeightFont( int points ); + void MoveTo( float x, float y ); + void LineTo( float x, float y ); + void Polygon( Point * pts, int npts, ColourDesired fore, ColourDesired back ); + void RectangleDraw( PRectangle rc, ColourDesired fore, ColourDesired back ); + void FillRectangle( PRectangle rc, ColourDesired back ); + void FillRectangle( PRectangle rc, Surface & surfacePattern ); + void RoundedRectangle( PRectangle rc, ColourDesired fore, ColourDesired back ); + void AlphaRectangle( PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill, + ColourDesired outline, int alphaOutline, int flags ); + void Ellipse( PRectangle rc, ColourDesired fore, ColourDesired back ); + void Copy( PRectangle rc, Point from, Surface & surfaceSource ); //virtual void DrawPixmap(PRectangle rc, Point from, Pixmap pixmap); - virtual void DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage); - - void DrawTextBase(PRectangle rc, Font &font, float ybase, const char *s, int len, ColourDesired fore); - void DrawTextNoClip(PRectangle rc, Font &font, float ybase, const char *s, int len, ColourDesired fore, ColourDesired back); - void DrawTextClipped(PRectangle rc, Font &font, float ybase, const char *s, int len, ColourDesired fore, ColourDesired back); - void DrawTextTransparent(PRectangle rc, Font &font, float ybase, const char *s, int len, ColourDesired fore); - void MeasureWidths(Font &font, const char *s, int len, float *positions); - float WidthText(Font &font, const char *s, int len); - float WidthChar(Font &font, char ch); - float Ascent(Font &font); - float Descent(Font &font); - float InternalLeading(Font &font); - float ExternalLeading(Font &font); - float Height(Font &font); - float AverageCharWidth(Font &font); - - void MoveTo(int x, int y); - void LineTo(int x, int y); - - void SetClip(PRectangle rc); + virtual void DrawRGBAImage( PRectangle rc, int width, int height, const unsigned char * pixelsImage ); + + void DrawTextBase( PRectangle rc, Font & font, float ybase, const char * s, int len, ColourDesired fore ); + void DrawTextNoClip( PRectangle rc, Font & font, float ybase, const char * s, int len, ColourDesired fore, ColourDesired back ); + void DrawTextClipped( PRectangle rc, Font & font, float ybase, const char * s, int len, ColourDesired fore, ColourDesired back ); + void DrawTextTransparent( PRectangle rc, Font & font, float ybase, const char * s, int len, ColourDesired fore ); + void MeasureWidths( Font & font, const char * s, int len, float * positions ); + float WidthText( Font & font, const char * s, int len ); + float WidthChar( Font & font, char ch ); + float Ascent( Font & font ); + float Descent( Font & font ); + float InternalLeading( Font & font ); + float ExternalLeading( Font & font ); + float Height( Font & font ); + float AverageCharWidth( Font & font ); + + void MoveTo( int x, int y ); + void LineTo( int x, int y ); + + void SetClip( PRectangle rc ); void FlushCachedState(); - void SetUnicodeMode(bool unicodeMode_); - void SetDBCSMode(int codePage); + void SetUnicodeMode( bool unicodeMode_ ); + void SetDBCSMode( int codePage ); }; #ifdef SCI_NAMESPACE } #endif -SurfaceImpl::SurfaceImpl() - : currentX(0), currentY(0) +SurfaceImpl::SurfaceImpl() + : currentX( 0 ), currentY( 0 ) { unicodeMode = false; codePage = 0; @@ -257,12 +257,12 @@ void SurfaceImpl::Init( SurfaceID sid, WindowID wid ) initialised = true; } -void SurfaceImpl::InitPixMap( int width, int height, Surface *surface, WindowID wid ) +void SurfaceImpl::InitPixMap( int width, int height, Surface * surface, WindowID wid ) { initialised = true; } -void SurfaceImpl::Release() +void SurfaceImpl::Release() { } @@ -271,33 +271,33 @@ bool SurfaceImpl::Initialised() return initialised; } -void SurfaceImpl::PenColour(ColourDesired fore) +void SurfaceImpl::PenColour( ColourDesired fore ) { penColour = fore; } -int SurfaceImpl::LogPixelsY() +int SurfaceImpl::LogPixelsY() { return 72; } -int SurfaceImpl::DeviceHeightFont(int points) +int SurfaceImpl::DeviceHeightFont( int points ) { int logPix = LogPixelsY(); - return (points * logPix + logPix / 2) / 72; + return ( points * logPix + logPix / 2 ) / 72; } -void SurfaceImpl::MoveTo(float x, float y) +void SurfaceImpl::MoveTo( float x, float y ) { currentX = x; currentY = y; } -void SurfaceImpl::LineTo(float targetX, float targetY) +void SurfaceImpl::LineTo( float targetX, float targetY ) { Renderer::RenderLine( - Renderer::Vertex( currentX+0.5f, currentY+0.5f, (unsigned int)penColour.AsLong() ), - Renderer::Vertex( targetX+0.5f, targetY+0.5f, (unsigned int)penColour.AsLong() ) + Renderer::Vertex( currentX + 0.5f, currentY + 0.5f, (unsigned int) penColour.AsLong() ), + Renderer::Vertex( targetX + 0.5f, targetY + 0.5f, (unsigned int) penColour.AsLong() ) ); currentX = targetX; currentY = targetY; @@ -305,175 +305,175 @@ void SurfaceImpl::LineTo(float targetX, float targetY) void SurfaceImpl::MoveTo( int x, int y ) { - MoveTo( (float)x, (float)y ); + MoveTo( (float) x, (float) y ); } void SurfaceImpl::LineTo( int x, int y ) { - LineTo( (float)x, (float)y ); + LineTo( (float) x, (float) y ); } -void SurfaceImpl::Polygon(Point* /*pts*/, int /*npts*/, ColourDesired /*fore*/, ColourDesired /*back*/) +void SurfaceImpl::Polygon( Point * /*pts*/, int /*npts*/, ColourDesired /*fore*/, ColourDesired /*back*/ ) { - assert(!"Implemented"); + assert( !"Implemented" ); } -void SurfaceImpl::RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back) +void SurfaceImpl::RectangleDraw( PRectangle rc, ColourDesired fore, ColourDesired back ) { - FillRectangle(rc, back); - PenColour(fore); - MoveTo( rc.left , rc.top ); + FillRectangle( rc, back ); + PenColour( fore ); + MoveTo( rc.left, rc.top ); LineTo( rc.right, rc.top ); LineTo( rc.right, rc.bottom ); - LineTo( rc.left, rc.bottom); - LineTo( rc.left, rc.top ); + LineTo( rc.left, rc.bottom ); + LineTo( rc.left, rc.top ); } -void SurfaceImpl::FillRectangle(PRectangle rc, ColourDesired back) +void SurfaceImpl::FillRectangle( PRectangle rc, ColourDesired back ) { - Renderer::BindTexture(NULL); - + Renderer::BindTexture( NULL ); + Renderer::RenderQuad( - Renderer::Vertex( rc.left , rc.top, (unsigned int)back.AsLong() ), - Renderer::Vertex( rc.right, rc.top, (unsigned int)back.AsLong() ), - Renderer::Vertex( rc.right, rc.bottom, (unsigned int)back.AsLong() ), - Renderer::Vertex( rc.left , rc.bottom, (unsigned int)back.AsLong() ) - ); + Renderer::Vertex( rc.left, rc.top, (unsigned int) back.AsLong() ), + Renderer::Vertex( rc.right, rc.top, (unsigned int) back.AsLong() ), + Renderer::Vertex( rc.right, rc.bottom, (unsigned int) back.AsLong() ), + Renderer::Vertex( rc.left, rc.bottom, (unsigned int) back.AsLong() ) + ); } -void SurfaceImpl::FillRectangle(PRectangle rc, Surface & surfacePattern) +void SurfaceImpl::FillRectangle( PRectangle rc, Surface & surfacePattern ) { - FillRectangle( rc, 0xd0000000 ); + FillRectangle( rc, 0xd0000000 ); } -void SurfaceImpl::RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back) +void SurfaceImpl::RoundedRectangle( PRectangle rc, ColourDesired fore, ColourDesired back ) { - RectangleDraw( rc, fore, back ); + RectangleDraw( rc, fore, back ); } -void SurfaceImpl::AlphaRectangle(PRectangle rc, int /*cornerSize*/, ColourDesired fill, int alphaFill, - ColourDesired /*outline*/, int /*alphaOutline*/, int /*flags*/) +void SurfaceImpl::AlphaRectangle( PRectangle rc, int /*cornerSize*/, ColourDesired fill, int alphaFill, + ColourDesired /*outline*/, int /*alphaOutline*/, int /*flags*/ ) { - unsigned int back = (fill.AsLong() & 0xFFFFFF) | ((alphaFill & 0xFF) << 24); - FillRectangle(rc, back); + unsigned int back = ( fill.AsLong() & 0xFFFFFF ) | ( ( alphaFill & 0xFF ) << 24 ); + FillRectangle( rc, back ); } -void SurfaceImpl::DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) +void SurfaceImpl::DrawRGBAImage( PRectangle rc, int width, int height, const unsigned char * pixelsImage ) { - assert(!"Implemented"); + assert( !"Implemented" ); } -void SurfaceImpl::Ellipse(PRectangle /*rc*/, ColourDesired /*fore*/, ColourDesired /*back*/) +void SurfaceImpl::Ellipse( PRectangle /*rc*/, ColourDesired /*fore*/, ColourDesired /*back*/ ) { - assert(!"Implemented"); + assert( !"Implemented" ); } -void SurfaceImpl::Copy( PRectangle rc, Point from, Surface &surfaceSource ) +void SurfaceImpl::Copy( PRectangle rc, Point from, Surface & surfaceSource ) { // we don't assert here because this is often used // however, we don't support it right now } -void SurfaceImpl::DrawTextBase(PRectangle rc, Font &font, float ybase, const char *str, int len, ColourDesired fore) +void SurfaceImpl::DrawTextBase( PRectangle rc, Font & font, float ybase, const char * str, int len, ColourDesired fore ) { - stbtt_Font* realFont = (stbtt_Font*)font.GetID(); + stbtt_Font * realFont = (stbtt_Font *) font.GetID(); Renderer::BindTexture( realFont->texture ); float x = rc.left, y = ybase; - while (len-- > 0) + while ( len-- > 0 ) { unsigned int c = *str; - unsigned int charLength = UTF8CharLength(c); - if (charLength > 1) + unsigned int charLength = UTF8CharLength( c ); + if ( charLength > 1 ) { c = 0; - UTF16FromUTF8( str, charLength, (wchar_t*)&c, sizeof(unsigned int) ); + UTF16FromUTF8( str, charLength, (wchar_t *) &c, sizeof( unsigned int ) ); } - if (c >= CHARACTER_COUNT) + if ( c >= CHARACTER_COUNT ) c = '?'; stbtt_aligned_quad quad; stbtt_GetBakedQuad( realFont->cdata, realFont->texture->width, realFont->texture->height, c, &x, &y, &quad, 1 ); - + Renderer::RenderQuad( - Renderer::Vertex( quad.x0, quad.y0, (unsigned int)fore.AsLong(), quad.s0, quad.t0 ), - Renderer::Vertex( quad.x1, quad.y0, (unsigned int)fore.AsLong(), quad.s1, quad.t0 ), - Renderer::Vertex( quad.x1, quad.y1, (unsigned int)fore.AsLong(), quad.s1, quad.t1 ), - Renderer::Vertex( quad.x0, quad.y1, (unsigned int)fore.AsLong(), quad.s0, quad.t1 ) + Renderer::Vertex( quad.x0, quad.y0, (unsigned int) fore.AsLong(), quad.s0, quad.t0 ), + Renderer::Vertex( quad.x1, quad.y0, (unsigned int) fore.AsLong(), quad.s1, quad.t0 ), + Renderer::Vertex( quad.x1, quad.y1, (unsigned int) fore.AsLong(), quad.s1, quad.t1 ), + Renderer::Vertex( quad.x0, quad.y1, (unsigned int) fore.AsLong(), quad.s0, quad.t1 ) ); str += charLength; len -= charLength - 1; } } -void SurfaceImpl::DrawTextNoClip(PRectangle rc, Font &font, float ybase, const char *s, int len, - ColourDesired fore, ColourDesired /*back*/) +void SurfaceImpl::DrawTextNoClip( PRectangle rc, Font & font, float ybase, const char * s, int len, + ColourDesired fore, ColourDesired /*back*/ ) { - DrawTextBase(rc, font, ybase, s, len, fore); + DrawTextBase( rc, font, ybase, s, len, fore ); } -void SurfaceImpl::DrawTextClipped(PRectangle rc, Font &font, float ybase, const char *s, int len, - ColourDesired fore, ColourDesired /*back*/) +void SurfaceImpl::DrawTextClipped( PRectangle rc, Font & font, float ybase, const char * s, int len, + ColourDesired fore, ColourDesired /*back*/ ) { - DrawTextBase(rc, font, ybase, s, len, fore); + DrawTextBase( rc, font, ybase, s, len, fore ); } -void SurfaceImpl::DrawTextTransparent(PRectangle rc, Font &font, float ybase, const char *s, int len, - ColourDesired fore) +void SurfaceImpl::DrawTextTransparent( PRectangle rc, Font & font, float ybase, const char * s, int len, + ColourDesired fore ) { - DrawTextBase(rc, font, ybase, s, len, fore); + DrawTextBase( rc, font, ybase, s, len, fore ); } -void SurfaceImpl::MeasureWidths(Font & font, const char *str, int len, float *positions) +void SurfaceImpl::MeasureWidths( Font & font, const char * str, int len, float * positions ) { - stbtt_Font* realFont = (stbtt_Font*)font.GetID(); - + stbtt_Font * realFont = (stbtt_Font *) font.GetID(); + float position = 0; const char * p = str; - while (len-- > 0) + while ( len-- > 0 ) { unsigned int c = *p; - unsigned int charLength = UTF8CharLength(c); - if (charLength > 1) + unsigned int charLength = UTF8CharLength( c ); + if ( charLength > 1 ) { c = 0; - UTF16FromUTF8( str, charLength, (wchar_t*)&c, sizeof(unsigned int) ); + UTF16FromUTF8( str, charLength, (wchar_t *) &c, sizeof( unsigned int ) ); } - if (c >= CHARACTER_COUNT) + if ( c >= CHARACTER_COUNT ) c = '?'; int advance = 0, leftBearing = 0; - - stbtt_GetCodepointHMetrics(&realFont->fontinfo, c, &advance, &leftBearing); - - position += advance; - for (unsigned int i=0; iscale; + + stbtt_GetCodepointHMetrics( &realFont->fontinfo, c, &advance, &leftBearing ); + + position += advance; + for ( unsigned int i = 0; i < charLength; i++ ) // we need to loop here because UTF8 characters count as multiple unless their position is the same + *positions++ = position * realFont->scale; p += charLength; len -= charLength - 1; } } -float SurfaceImpl::WidthText(Font & font, const char *str, int len) +float SurfaceImpl::WidthText( Font & font, const char * str, int len ) { - stbtt_Font* realFont = (stbtt_Font*)font.GetID(); - + stbtt_Font * realFont = (stbtt_Font *) font.GetID(); + float position = 0; - while (len-- > 0) + while ( len-- > 0 ) { unsigned int c = *str; - unsigned int charLength = UTF8CharLength(c); - if (charLength > 1) + unsigned int charLength = UTF8CharLength( c ); + if ( charLength > 1 ) { c = 0; - UTF16FromUTF8( str, charLength, (wchar_t*)&c, sizeof(unsigned int) ); + UTF16FromUTF8( str, charLength, (wchar_t *) &c, sizeof( unsigned int ) ); } - if (c >= CHARACTER_COUNT) + if ( c >= CHARACTER_COUNT ) c = '?'; int advance = 0, leftBearing = 0; - stbtt_GetCodepointHMetrics(&realFont->fontinfo, c, &advance, &leftBearing); - position += advance*realFont->scale;//TODO: +Kerning + stbtt_GetCodepointHMetrics( &realFont->fontinfo, c, &advance, &leftBearing ); + position += advance * realFont->scale;//TODO: +Kerning str += charLength; len -= charLength - 1; @@ -481,56 +481,56 @@ float SurfaceImpl::WidthText(Font & font, const char *str, int len) return position; } -float SurfaceImpl::WidthChar(Font &font, char ch) +float SurfaceImpl::WidthChar( Font & font, char ch ) { - stbtt_Font* realFont = (stbtt_Font*)font.GetID(); + stbtt_Font * realFont = (stbtt_Font *) font.GetID(); int advance, leftBearing; - stbtt_GetCodepointHMetrics(&realFont->fontinfo, ch, &advance, &leftBearing); + stbtt_GetCodepointHMetrics( &realFont->fontinfo, ch, &advance, &leftBearing ); return advance * realFont->scale; } -float SurfaceImpl::Ascent(Font &font) +float SurfaceImpl::Ascent( Font & font ) { - stbtt_Font* realFont = (stbtt_Font*)font.GetID(); + stbtt_Font * realFont = (stbtt_Font *) font.GetID(); int ascent, descent, lineGap; - stbtt_GetFontVMetrics(&realFont->fontinfo, &ascent, &descent, &lineGap); + stbtt_GetFontVMetrics( &realFont->fontinfo, &ascent, &descent, &lineGap ); return ascent * realFont->scale; } -float SurfaceImpl::Descent(Font &font) +float SurfaceImpl::Descent( Font & font ) { - stbtt_Font* realFont = (stbtt_Font*)font.GetID(); + stbtt_Font * realFont = (stbtt_Font *) font.GetID(); int ascent, descent, lineGap; - stbtt_GetFontVMetrics(&realFont->fontinfo, &ascent, &descent, &lineGap); + stbtt_GetFontVMetrics( &realFont->fontinfo, &ascent, &descent, &lineGap ); return -descent * realFont->scale; } -float SurfaceImpl::InternalLeading(Font &) +float SurfaceImpl::InternalLeading( Font & ) { //WTF is this????? return 0; } -float SurfaceImpl::ExternalLeading(Font& font) +float SurfaceImpl::ExternalLeading( Font & font ) { //WTF is this????? - stbtt_Font* realFont = (stbtt_Font*)font.GetID(); + stbtt_Font * realFont = (stbtt_Font *) font.GetID(); int ascent, descent, lineGap; - stbtt_GetFontVMetrics(&realFont->fontinfo, &ascent, &descent, &lineGap); + stbtt_GetFontVMetrics( &realFont->fontinfo, &ascent, &descent, &lineGap ); return lineGap * realFont->scale; } -float SurfaceImpl::Height(Font &font) +float SurfaceImpl::Height( Font & font ) { - return Ascent(font) + Descent(font); + return Ascent( font ) + Descent( font ); } -float SurfaceImpl::AverageCharWidth(Font &font) +float SurfaceImpl::AverageCharWidth( Font & font ) { - return WidthChar(font, 'n'); + return WidthChar( font, 'n' ); } -void SurfaceImpl::SetClip(PRectangle rc) +void SurfaceImpl::SetClip( PRectangle rc ) { // we deal with this in the renderer } @@ -548,7 +548,7 @@ void SurfaceImpl::SetDBCSMode( int cp ) codePage = cp; } -Surface *Surface::Allocate(int technology) +Surface * Surface::Allocate( int technology ) { return new SurfaceImpl; } @@ -569,27 +569,27 @@ bool Window::HasFocus() return false; } -std::map rects; -PRectangle Window::GetPosition() +std::map rects; +PRectangle Window::GetPosition() { - return rects[wid]; + return rects[ wid ]; } -void Window::SetPosition(PRectangle rc) +void Window::SetPosition( PRectangle rc ) { - rects[wid] = rc; + rects[ wid ] = rc; } -void Window::SetPositionRelative(PRectangle rc, Window w) +void Window::SetPositionRelative( PRectangle rc, Window w ) { } -PRectangle Window::GetClientPosition() +PRectangle Window::GetClientPosition() { - return PRectangle( 0, 0, rects[wid].Width(), rects[wid].Height() ); + return PRectangle( 0, 0, rects[ wid ].Width(), rects[ wid ].Height() ); } -void Window::Show(bool show) +void Window::Show( bool show ) { } @@ -597,19 +597,19 @@ void Window::InvalidateAll() { } -void Window::InvalidateRectangle(PRectangle rc) +void Window::InvalidateRectangle( PRectangle rc ) { } -void Window::SetFont(Font &font) +void Window::SetFont( Font & font ) { } -void Window::SetCursor(Cursor curs) +void Window::SetCursor( Cursor curs ) { } -PRectangle Window::GetMonitorRect(Point pt) +PRectangle Window::GetMonitorRect( Point pt ) { return PRectangle( 0, 0, Renderer::nWidth, Renderer::nHeight ); } @@ -617,30 +617,30 @@ PRectangle Window::GetMonitorRect(Point pt) ////////////////////////////////////////////////////////////////////////// // Menus -Menu::Menu() : mid(0) +Menu::Menu() : mid( 0 ) { - assert(!"Implemented"); + assert( !"Implemented" ); } void Menu::CreatePopUp() { - assert(!"Implemented"); + assert( !"Implemented" ); } void Menu::Destroy() { - assert(!"Implemented"); + assert( !"Implemented" ); } -void Menu::Show(Point pt, Window &w) +void Menu::Show( Point pt, Window & w ) { - assert(!"Implemented"); + assert( !"Implemented" ); } ////////////////////////////////////////////////////////////////////////// // ListBox implementation -ListBox *ListBox::Allocate() +ListBox * ListBox::Allocate() { return NULL; } diff --git a/src/Renderer.h b/src/Renderer.h index f77aa88f..626bb01d 100644 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -1,114 +1,128 @@ #include -typedef enum { - RENDERER_WINDOWMODE_WINDOWED = 0, - RENDERER_WINDOWMODE_FULLSCREEN, - RENDERER_WINDOWMODE_BORDERLESS -} RENDERER_WINDOWMODE; +namespace Renderer +{ +////////////////////////////////////////////////////////////////////////// + +enum WINDOWMODE +{ + WINDOWMODE_WINDOWED = 0, + WINDOWMODE_FULLSCREEN, + WINDOWMODE_BORDERLESS +}; -typedef struct +struct Settings { int nWidth; int nHeight; - RENDERER_WINDOWMODE windowMode; + WINDOWMODE windowMode; bool bVsync; -} RENDERER_SETTINGS; +}; -namespace Renderer +struct KeyEvent +{ + int character; + int scanCode; + bool ctrl; + bool shift; + bool alt; +}; + +enum MOUSEEVENTTYPE +{ + MOUSEEVENTTYPE_DOWN = 0, + MOUSEEVENTTYPE_MOVE, + MOUSEEVENTTYPE_UP, + MOUSEEVENTTYPE_SCROLL +}; + +enum MOUSEBUTTON +{ + MOUSEBUTTON_LEFT = 0, + MOUSEBUTTON_RIGHT, + MOUSEBUTTON_MIDDLE, +}; + +struct MouseEvent +{ + MOUSEEVENTTYPE eventType; + float x; + float y; + MOUSEBUTTON button; +}; + +enum TEXTURETYPE +{ + TEXTURETYPE_1D = 1, + TEXTURETYPE_2D = 2, +}; + +struct Texture +{ + int width; + int height; + TEXTURETYPE type; +}; + +struct Vertex { - extern const char * defaultShaderFilename; - extern const char defaultShader[65536]; - - extern int nWidth; - extern int nHeight; - - bool OpenSetupDialog( RENDERER_SETTINGS * settings ); - bool Open( RENDERER_SETTINGS * settings ); - - void StartFrame(); - void EndFrame(); - bool WantsToQuit(); - - void RenderFullscreenQuad(); - - bool ReloadShader( const char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize ); - void SetShaderConstant( const char * szConstName, float x ); - void SetShaderConstant( const char * szConstName, float x, float y ); - - void StartTextRendering(); - void SetTextRenderingViewport( Scintilla::PRectangle rect ); - void EndTextRendering(); - - bool GrabFrame( void * pPixelBuffer ); // input buffer must be able to hold w * h * 4 bytes of 0xAABBGGRR data - - void Close(); - - enum TEXTURETYPE - { - TEXTURETYPE_1D = 1, - TEXTURETYPE_2D = 2, - }; - - struct Texture - { - int width; - int height; - TEXTURETYPE type; - }; - - Texture * CreateRGBA8Texture(); - Texture * CreateRGBA8TextureFromFile( const char * szFilename ); - Texture * CreateA8TextureFromData( int w, int h, const unsigned char * data ); - Texture * Create1DR32Texture( int w ); - bool UpdateR32Texture( Texture * tex, float * data ); - void SetShaderTexture( const char * szTextureName, Texture * tex ); - void BindTexture( Texture * tex ); // temporary function until all the quad rendering is moved to the renderer - void ReleaseTexture( Texture * tex ); - - void CopyBackbufferToTexture( Texture * tex ); - - struct Vertex - { - Vertex( float _x, float _y, unsigned int _c = 0xFFFFFFFF, float _u = 0.0, float _v = 0.0) : - x(_x), y(_y), c(_c), u(_u), v(_v) {} - float x, y; - unsigned int c; - float u, v; - }; - void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d ); - void RenderLine( const Vertex & a, const Vertex & b ); - - struct KeyEvent - { - int character; - int scanCode; - bool ctrl; - bool shift; - bool alt; - }; - extern KeyEvent keyEventBuffer[512]; - extern int keyEventBufferCount; - - enum MOUSEEVENTTYPE - { - MOUSEEVENTTYPE_DOWN = 0, - MOUSEEVENTTYPE_MOVE, - MOUSEEVENTTYPE_UP, - MOUSEEVENTTYPE_SCROLL - }; - enum MOUSEBUTTON - { - MOUSEBUTTON_LEFT = 0, - MOUSEBUTTON_RIGHT, - MOUSEBUTTON_MIDDLE, - }; - struct MouseEvent - { - MOUSEEVENTTYPE eventType; - float x; - float y; - MOUSEBUTTON button; - }; - extern MouseEvent mouseEventBuffer[512]; - extern int mouseEventBufferCount; + Vertex( float _x, float _y, unsigned int _c = 0xFFFFFFFF, float _u = 0.0, float _v = 0.0 ) : + x( _x ), y( _y ), c( _c ), u( _u ), v( _v ) {} + float x, y; + unsigned int c; + float u, v; +}; + +extern const char * szDefaultShaderFilename; +extern const char szDefaultShader[ 65536 ]; + +extern const char * shaderKeyword; +extern const char * shaderType; +extern const char * shaderBuiltin; + +extern int nWidth; +extern int nHeight; + +bool OpenSetupDialog( Settings * settings ); +bool Open( Settings * settings ); + +void StartFrame(); +void EndFrame(); +bool WantsToQuit(); + +void RenderFullscreenQuad(); + +bool ReloadShader( const char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize ); +void SetShaderConstant( const char * szConstName, float x ); +void SetShaderConstant( const char * szConstName, float x, float y ); + +void StartTextRendering(); +void SetTextRenderingViewport( Scintilla::PRectangle rect ); +void EndTextRendering(); + +bool GrabFrame( void * pPixelBuffer ); // input buffer must be able to hold w * h * 4 bytes of 0xAABBGGRR data + +void Close(); + +Texture * CreateRGBA8Texture(); +Texture * CreateRGBA8TextureFromFile( const char * szFilename ); +Texture * CreateA8TextureFromData( int w, int h, const unsigned char * data ); +Texture * Create1DR32Texture( int w ); +bool UpdateR32Texture( Texture * tex, float * data ); +void SetShaderTexture( const char * szTextureName, Texture * tex ); +void BindTexture( Texture * tex ); // temporary function until all the quad rendering is moved to the renderer +void ReleaseTexture( Texture * tex ); + +void CopyBackbufferToTexture( Texture * tex ); + +void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d ); +void RenderLine( const Vertex & a, const Vertex & b ); + +extern KeyEvent keyEventBuffer[ 512 ]; +extern int keyEventBufferCount; + +extern MouseEvent mouseEventBuffer[ 512 ]; +extern int mouseEventBufferCount; + +////////////////////////////////////////////////////////////////////////// } diff --git a/src/SetupDialog.h b/src/SetupDialog.h index b0534f2a..185a8a09 100644 --- a/src/SetupDialog.h +++ b/src/SetupDialog.h @@ -1,10 +1,14 @@ namespace SetupDialog { - typedef struct - { - RENDERER_SETTINGS sRenderer; - FFT_SETTINGS sFFT; - } SETTINGS; +////////////////////////////////////////////////////////////////////////// - bool Open( SETTINGS * pSettings ); +typedef struct +{ + Renderer::Settings sRenderer; + FFT::Settings sFFT; +} SETTINGS; + +bool Open( SETTINGS * pSettings ); + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/ShaderEditor.cpp b/src/ShaderEditor.cpp index 0ccef733..1cd760c9 100644 --- a/src/ShaderEditor.cpp +++ b/src/ShaderEditor.cpp @@ -1,630 +1,692 @@ -#include -#include "ShaderEditor.h" -#include "Renderer.h" -#include "PropSetSimple.h" -#include "Clipboard.h" - -const int statementLookback = 20; -const int statementIndentStyleNumber = 5; -const int blockAndStatementEndStyleNumber = 10; -std::string statementIndent[] = { "case", "default", "do", "else", "for", "if", "while" }; -const char statementEnd = ';'; -const char blockStart = '{'; -const char blockEnd = '}'; - -ShaderEditor::ShaderEditor( Scintilla::Surface *s ) -{ - bReadOnly = false; - surfaceWindow = s; - sFontFile = ""; - nFontSize = 16; - bHasMouseCapture = false; - nOpacity = 0xC0; -} - -void ShaderEditor::SetAStyle(int style, Scintilla::ColourDesired fore, Scintilla::ColourDesired back, int size, const char *face) -{ - WndProc(SCI_STYLESETFORE, style, (sptr_t)fore.AsLong()); - WndProc(SCI_STYLESETBACK, style, (sptr_t)back.AsLong()); - if (size >= 1) - WndProc(SCI_STYLESETSIZE, style, size); - if (face) - WndProc(SCI_STYLESETFONT, style, reinterpret_cast(face)); -} - -#define BACKGROUND(x) ( (x) | (nOpacity << 24) ) - -const size_t NB_FOLDER_STATE = 7; -const size_t FOLDER_TYPE = 0; - -const int markersArray[][NB_FOLDER_STATE] = { - {SC_MARKNUM_FOLDEROPEN, SC_MARKNUM_FOLDER, SC_MARKNUM_FOLDERSUB, SC_MARKNUM_FOLDERTAIL, SC_MARKNUM_FOLDEREND, SC_MARKNUM_FOLDEROPENMID, SC_MARKNUM_FOLDERMIDTAIL}, - {SC_MARK_MINUS, SC_MARK_PLUS, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY}, - {SC_MARK_ARROWDOWN, SC_MARK_ARROW, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY}, - {SC_MARK_CIRCLEMINUS, SC_MARK_CIRCLEPLUS,SC_MARK_VLINE, SC_MARK_LCORNERCURVE, SC_MARK_CIRCLEPLUSCONNECTED, SC_MARK_CIRCLEMINUSCONNECTED, SC_MARK_TCORNERCURVE}, - {SC_MARK_BOXMINUS, SC_MARK_BOXPLUS, SC_MARK_VLINE, SC_MARK_LCORNER, SC_MARK_BOXPLUSCONNECTED, SC_MARK_BOXMINUSCONNECTED, SC_MARK_TCORNER} -}; -extern const char * shaderKeyword; -extern const char * shaderType; -extern const char * shaderBuiltin; - -using namespace Scintilla; -class Scintilla::LexState : public LexInterface { - const LexerModule *lexCurrent; - void SetLexerModule(const LexerModule *lex); - PropSetSimple props; - int interfaceVersion; -public: - int lexLanguage; - - explicit LexState(Document *pdoc_); - virtual ~LexState(); - void SetLexer(uptr_t wParam); - void SetLexerLanguage(const char *languageName); - const char *DescribeWordListSets(); - void SetWordList(int n, const char *wl); - const char *GetName() const; - void *PrivateCall(int operation, void *pointer); - const char *PropertyNames(); - int PropertyType(const char *name); - const char *DescribeProperty(const char *name); - void PropSet(const char *key, const char *val); - const char *PropGet(const char *key) const; - int PropGetInt(const char *key, int defaultValue=0) const; - int PropGetExpanded(const char *key, char *result) const; - - int LineEndTypesSupported(); - int AllocateSubStyles(int styleBase, int numberStyles); - int SubStylesStart(int styleBase); - int SubStylesLength(int styleBase); - int StyleFromSubStyle(int subStyle); - int PrimaryStyleFromStyle(int style); - void FreeSubStyles(); - void SetIdentifiers(int style, const char *identifiers); - int DistanceToSecondaryStyles(); - const char *GetSubStyleBases(); -}; - -static unsigned int wndID = 1; -void ShaderEditor::Initialise() -{ - wMain = (Scintilla::WindowID)(unsigned long)(wndID++); - - lexState = new Scintilla::LexState( pdoc ); - +#include +#include "ShaderEditor.h" +#include "Renderer.h" +#include "PropSetSimple.h" +#include "Clipboard.h" + +const int statementLookback = 20; +const int statementIndentStyleNumber = 5; +const int blockAndStatementEndStyleNumber = 10; +std::string statementIndent[] = { "case", "default", "do", "else", "for", "if", "while" }; +const char statementEnd = ';'; +const char blockStart = '{'; +const char blockEnd = '}'; + +ShaderEditor::ShaderEditor( Scintilla::Surface * s ) +{ + bReadOnly = false; + surfaceWindow = s; + sFontFile = ""; + nFontSize = 16; + bHasMouseCapture = false; + nOpacity = 0xC0; +} + +void ShaderEditor::SetAStyle( int style, Scintilla::ColourDesired fore, Scintilla::ColourDesired back, int size, const char * face ) +{ + WndProc( SCI_STYLESETFORE, style, (sptr_t) fore.AsLong() ); + WndProc( SCI_STYLESETBACK, style, (sptr_t) back.AsLong() ); + if ( size >= 1 ) + WndProc( SCI_STYLESETSIZE, style, size ); + if ( face ) + WndProc( SCI_STYLESETFONT, style, reinterpret_cast( face ) ); +} + +#define BACKGROUND(x) ( (x) | (nOpacity << 24) ) + +const size_t NB_FOLDER_STATE = 7; +const size_t FOLDER_TYPE = 0; + +const int markersArray[][ NB_FOLDER_STATE ] = { + {SC_MARKNUM_FOLDEROPEN, SC_MARKNUM_FOLDER, SC_MARKNUM_FOLDERSUB, SC_MARKNUM_FOLDERTAIL, SC_MARKNUM_FOLDEREND, SC_MARKNUM_FOLDEROPENMID, SC_MARKNUM_FOLDERMIDTAIL}, + {SC_MARK_MINUS, SC_MARK_PLUS, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY}, + {SC_MARK_ARROWDOWN, SC_MARK_ARROW, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY, SC_MARK_EMPTY}, + {SC_MARK_CIRCLEMINUS, SC_MARK_CIRCLEPLUS,SC_MARK_VLINE, SC_MARK_LCORNERCURVE, SC_MARK_CIRCLEPLUSCONNECTED, SC_MARK_CIRCLEMINUSCONNECTED, SC_MARK_TCORNERCURVE}, + {SC_MARK_BOXMINUS, SC_MARK_BOXPLUS, SC_MARK_VLINE, SC_MARK_LCORNER, SC_MARK_BOXPLUSCONNECTED, SC_MARK_BOXMINUSCONNECTED, SC_MARK_TCORNER} +}; + +using namespace Scintilla; +class Scintilla::LexState : public LexInterface +{ + const LexerModule * lexCurrent; + void SetLexerModule( const LexerModule * lex ); + PropSetSimple props; + int interfaceVersion; +public: + int lexLanguage; + + explicit LexState( Document * pdoc_ ); + virtual ~LexState(); + void SetLexer( uptr_t wParam ); + void SetLexerLanguage( const char * languageName ); + const char * DescribeWordListSets(); + void SetWordList( int n, const char * wl ); + const char * GetName() const; + void * PrivateCall( int operation, void * pointer ); + const char * PropertyNames(); + int PropertyType( const char * name ); + const char * DescribeProperty( const char * name ); + void PropSet( const char * key, const char * val ); + const char * PropGet( const char * key ) const; + int PropGetInt( const char * key, int defaultValue = 0 ) const; + int PropGetExpanded( const char * key, char * result ) const; + + int LineEndTypesSupported(); + int AllocateSubStyles( int styleBase, int numberStyles ); + int SubStylesStart( int styleBase ); + int SubStylesLength( int styleBase ); + int StyleFromSubStyle( int subStyle ); + int PrimaryStyleFromStyle( int style ); + void FreeSubStyles(); + void SetIdentifiers( int style, const char * identifiers ); + int DistanceToSecondaryStyles(); + const char * GetSubStyleBases(); +}; + +static unsigned int wndID = 1; +void ShaderEditor::Initialise() +{ + wMain = (Scintilla::WindowID) (unsigned long) ( wndID++ ); + + lexState = new Scintilla::LexState( pdoc ); + WndProc( SCI_SETBUFFEREDDRAW, 0, 0 ); WndProc( SCI_SETCODEPAGE, SC_CP_UTF8, 0 ); - + WndProc( SCI_SETWRAPMODE, SC_WRAP_WORD, 0 ); - + //WndProc( SCI_SETLEXERLANGUAGE, SCLEX_CPP, 0 ); - - SetAStyle( STYLE_DEFAULT, 0xFFFFFFFF, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); + + SetAStyle( STYLE_DEFAULT, 0xFFFFFFFF, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); WndProc( SCI_STYLECLEARALL, 0, 0 ); - SetAStyle( STYLE_LINENUMBER, 0xFFC0C0C0, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); - SetAStyle( STYLE_BRACELIGHT, 0xFF00FF00, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); - SetAStyle( STYLE_BRACEBAD, 0xFF0000FF, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); - SetAStyle( STYLE_INDENTGUIDE, 0xFFC0C0C0, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); - - WndProc(SCI_SETFOLDMARGINCOLOUR, 1, BACKGROUND( 0x1A1A1A )); - WndProc(SCI_SETFOLDMARGINHICOLOUR, 1, BACKGROUND( 0x1A1A1A )); - WndProc(SCI_SETSELBACK, 1, theme.selection); - - SetReadOnly(false); - - for (int i = 0 ; i < NB_FOLDER_STATE ; i++) - { - WndProc(SCI_MARKERDEFINE, markersArray[FOLDER_TYPE][i], markersArray[4][i]); - WndProc(SCI_MARKERSETBACK, markersArray[FOLDER_TYPE][i], 0xFF6A6A6A); - WndProc(SCI_MARKERSETFORE, markersArray[FOLDER_TYPE][i], 0xFF333333); - } - WndProc(SCI_SETUSETABS, bUseSpacesForTabs ? 0 : 1, 0); - WndProc(SCI_SETTABWIDTH, nTabSize, 0); - WndProc(SCI_SETINDENT, nTabSize, 0); - WndProc(SCI_SETINDENTATIONGUIDES, SC_IV_REAL, 0); - - if (bVisibleWhitespace) - { - WndProc(SCI_SETVIEWWS, SCWS_VISIBLEALWAYS, 0); - WndProc(SCI_SETWHITESPACEFORE, 1, 0x30FFFFFF); - WndProc(SCI_SETWHITESPACESIZE, 2, 0 ); - } - - lexState->SetLexer( SCLEX_CPP ); - lexState->SetWordList(0, shaderKeyword); - lexState->SetWordList(1, shaderType); - lexState->SetWordList(3, shaderBuiltin); - // Do not grey out code inside #if #else #endif (when set to 1 it causes problems with fully transparent background) - lexState->PropSet("lexer.cpp.track.preprocessor", "0"); - // Colorize the content of the #defines (thx @blackle for finding it) - lexState->PropSet("styling.within.preprocessor", "1"); - - SetAStyle(SCE_C_DEFAULT, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000), nFontSize, sFontFile.c_str() ); - SetAStyle(SCE_C_WORD, theme.keyword, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_WORD2, theme.type, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_GLOBALCLASS, theme.builtin, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_PREPROCESSOR, theme.preprocessor, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_NUMBER, theme.number, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_OPERATOR, theme.op, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_COMMENT, theme.comment, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_COMMENTLINE, theme.comment, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - - // Misc chars to cover for standard text - SetAStyle(SCE_C_COMMENTDOC, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_STRING, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_CHARACTER, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_UUID, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_IDENTIFIER, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_STRINGEOL, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_VERBATIM, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_REGEX, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_COMMENTLINEDOC, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_COMMENTDOCKEYWORD, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_COMMENTDOCKEYWORDERROR, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_STRINGRAW, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_TRIPLEVERBATIM, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_HASHQUOTEDSTRING, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_PREPROCESSORCOMMENT, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_PREPROCESSORCOMMENTDOC, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_USERLITERAL, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_TASKMARKER, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - SetAStyle(SCE_C_ESCAPESEQUENCE, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND(0x000000)); - - lexState->Colourise( 0, -1 ); - + SetAStyle( STYLE_LINENUMBER, 0xFFC0C0C0, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); + SetAStyle( STYLE_BRACELIGHT, 0xFF00FF00, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); + SetAStyle( STYLE_BRACEBAD, 0xFF0000FF, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); + SetAStyle( STYLE_INDENTGUIDE, 0xFFC0C0C0, BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); + + WndProc( SCI_SETFOLDMARGINCOLOUR, 1, BACKGROUND( 0x1A1A1A ) ); + WndProc( SCI_SETFOLDMARGINHICOLOUR, 1, BACKGROUND( 0x1A1A1A ) ); + WndProc( SCI_SETSELBACK, 1, theme.selection ); + + SetReadOnly( false ); + + for ( int i = 0; i < NB_FOLDER_STATE; i++ ) + { + WndProc( SCI_MARKERDEFINE, markersArray[ FOLDER_TYPE ][ i ], markersArray[ 4 ][ i ] ); + WndProc( SCI_MARKERSETBACK, markersArray[ FOLDER_TYPE ][ i ], 0xFF6A6A6A ); + WndProc( SCI_MARKERSETFORE, markersArray[ FOLDER_TYPE ][ i ], 0xFF333333 ); + } + WndProc( SCI_SETUSETABS, bUseSpacesForTabs ? 0 : 1, 0 ); + WndProc( SCI_SETTABWIDTH, nTabSize, 0 ); + WndProc( SCI_SETINDENT, nTabSize, 0 ); + WndProc( SCI_SETINDENTATIONGUIDES, SC_IV_REAL, 0 ); + + if ( bVisibleWhitespace ) + { + WndProc( SCI_SETVIEWWS, SCWS_VISIBLEALWAYS, 0 ); + WndProc( SCI_SETWHITESPACEFORE, 1, 0x30FFFFFF ); + WndProc( SCI_SETWHITESPACESIZE, 2, 0 ); + } + + lexState->SetLexer( SCLEX_CPP ); + lexState->SetWordList( 0, Renderer::shaderKeyword ); + lexState->SetWordList( 1, Renderer::shaderType ); + lexState->SetWordList( 3, Renderer::shaderBuiltin ); + // Do not grey out code inside #if #else #endif (when set to 1 it causes problems with fully transparent background) + lexState->PropSet( "lexer.cpp.track.preprocessor", "0" ); + // Colorize the content of the #defines (thx @blackle for finding it) + lexState->PropSet( "styling.within.preprocessor", "1" ); + + SetAStyle( SCE_C_DEFAULT, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ), nFontSize, sFontFile.c_str() ); + SetAStyle( SCE_C_WORD, theme.keyword, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_WORD2, theme.type, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_GLOBALCLASS, theme.builtin, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_PREPROCESSOR, theme.preprocessor, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_NUMBER, theme.number, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_OPERATOR, theme.op, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_COMMENT, theme.comment, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_COMMENTLINE, theme.comment, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + + // Misc chars to cover for standard text + SetAStyle( SCE_C_COMMENTDOC, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_STRING, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_CHARACTER, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_UUID, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_IDENTIFIER, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_STRINGEOL, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_VERBATIM, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_REGEX, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_COMMENTLINEDOC, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_COMMENTDOCKEYWORD, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_COMMENTDOCKEYWORDERROR, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_STRINGRAW, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_TRIPLEVERBATIM, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_HASHQUOTEDSTRING, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_PREPROCESSORCOMMENT, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_PREPROCESSORCOMMENTDOC, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_USERLITERAL, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_TASKMARKER, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + SetAStyle( SCE_C_ESCAPESEQUENCE, theme.text, theme.bUseCharBackground ? theme.charBackground : BACKGROUND( 0x000000 ) ); + + lexState->Colourise( 0, -1 ); + //WndProc( SCI_COLOURISE, 0, 0 ); - - vs.Refresh( *surfaceWindow, 4 ); -} - -void ShaderEditor::Initialise( SHADEREDITOR_OPTIONS &options ) -{ - nFontSize = options.nFontSize; - sFontFile = options.sFontPath; - nOpacity = options.nOpacity; - bUseSpacesForTabs = options.bUseSpacesForTabs; - nTabSize = options.nTabSize; - bVisibleWhitespace = options.bVisibleWhitespace; - eAutoIndent = options.eAutoIndent; - theme = options.theme; - - Initialise(); - SetPosition( options.rect ); -} - -void ShaderEditor::SetVerticalScrollPos() -{ - -} - -void ShaderEditor::SetHorizontalScrollPos() -{ - -} - -bool ShaderEditor::ModifyScrollBars( int nMax, int nPage ) -{ - return true; -} - -void ShaderEditor::Copy() -{ - if (!sel.Empty()) { - SelectionText selectedText; - CopySelectionRange(&selectedText); - CopyToClipboard(selectedText); - } -} - -void ShaderEditor::Paste() -{ - int n = Clipboard::GetContentsLength(); - if (n == 0) return; - - char * p = new char[n + 1]; - memset(p,0,n+1); - Clipboard::GetContents( p, n ); - - ClearSelection(); - InsertPaste(p, n); - - delete[] p; -} - -void ShaderEditor::ClaimSelection() -{ - -} - -void ShaderEditor::NotifyChange() -{ - -} - -void ShaderEditor::NotifyParent( Scintilla::SCNotification scn ) -{ - switch (scn.nmhdr.code) { - case SCN_CHARADDED: - char ch = static_cast(scn.ch); - if(eAutoIndent == aitPreserve) { - PreserveIndentation(ch); - } else if (eAutoIndent == aitSmart) { - AutomaticIndentation(ch); - } - break; - } -} - -void ShaderEditor::CopyToClipboard( const Scintilla::SelectionText &selectedText ) -{ - Clipboard::Copy( selectedText.Data(), (int)selectedText.Length() ); -} - -void ShaderEditor::SetMouseCapture( bool on ) -{ - bHasMouseCapture = on; -} - -bool ShaderEditor::HaveMouseCapture() -{ - return bHasMouseCapture; -} - -sptr_t ShaderEditor::DefWndProc( unsigned int iMessage, uptr_t wParam, sptr_t lParam ) -{ - return 0; -} - -void ShaderEditor::Paint() -{ - Renderer::SetTextRenderingViewport( wMain.GetPosition() ); - Scintilla::Editor::Paint( surfaceWindow, GetClientRectangle() ); -} - -void ShaderEditor::SetText( const char * buf ) -{ + + vs.Refresh( *surfaceWindow, 4 ); +} + +void ShaderEditor::Initialise( SHADEREDITOR_OPTIONS & options ) +{ + nFontSize = options.nFontSize; + sFontFile = options.sFontPath; + nOpacity = options.nOpacity; + bUseSpacesForTabs = options.bUseSpacesForTabs; + nTabSize = options.nTabSize; + bVisibleWhitespace = options.bVisibleWhitespace; + eAutoIndent = options.eAutoIndent; + theme = options.theme; + + Initialise(); + SetPosition( options.rect ); +} + +void ShaderEditor::SetVerticalScrollPos() +{ + +} + +void ShaderEditor::SetHorizontalScrollPos() +{ + +} + +bool ShaderEditor::ModifyScrollBars( int nMax, int nPage ) +{ + return true; +} + +void ShaderEditor::Copy() +{ + if ( !sel.Empty() ) + { + SelectionText selectedText; + CopySelectionRange( &selectedText ); + CopyToClipboard( selectedText ); + } +} + +void ShaderEditor::Paste() +{ + int n = Clipboard::GetContentsLength(); + if ( n == 0 ) return; + + char * p = new char[ n + 1 ]; + memset( p, 0, n + 1 ); + Clipboard::GetContents( p, n ); + + ClearSelection(); + InsertPaste( p, n ); + + delete[] p; +} + +void ShaderEditor::ClaimSelection() +{ + +} + +void ShaderEditor::NotifyChange() +{ + +} + +void ShaderEditor::NotifyParent( Scintilla::SCNotification scn ) +{ + switch ( scn.nmhdr.code ) + { + case SCN_CHARADDED: + char ch = static_cast( scn.ch ); + if ( eAutoIndent == aitPreserve ) + { + PreserveIndentation( ch ); + } + else if ( eAutoIndent == aitSmart ) + { + AutomaticIndentation( ch ); + } + break; + } +} + +void ShaderEditor::CopyToClipboard( const Scintilla::SelectionText & selectedText ) +{ + Clipboard::Copy( selectedText.Data(), (int) selectedText.Length() ); +} + +void ShaderEditor::SetMouseCapture( bool on ) +{ + bHasMouseCapture = on; +} + +bool ShaderEditor::HaveMouseCapture() +{ + return bHasMouseCapture; +} + +sptr_t ShaderEditor::DefWndProc( unsigned int iMessage, uptr_t wParam, sptr_t lParam ) +{ + return 0; +} + +void ShaderEditor::Paint() +{ + Renderer::SetTextRenderingViewport( wMain.GetPosition() ); + Scintilla::Editor::Paint( surfaceWindow, GetClientRectangle() ); +} + +void ShaderEditor::SetText( const char * buf ) +{ WndProc( SCI_SETREADONLY, false, 0 ); WndProc( SCI_CLEARALL, false, 0 ); - WndProc( SCI_SETUNDOCOLLECTION, 0, 0); - WndProc( SCI_ADDTEXT, strlen(buf), (sptr_t)buf ); - WndProc( SCI_SETUNDOCOLLECTION, 1, 0); + WndProc( SCI_SETUNDOCOLLECTION, 0, 0 ); + WndProc( SCI_ADDTEXT, strlen( buf ), (sptr_t) buf ); + WndProc( SCI_SETUNDOCOLLECTION, 1, 0 ); WndProc( SCI_SETREADONLY, bReadOnly, 0 ); WndProc( SCI_GOTOPOS, 0, 0 ); - if (!bReadOnly) - SetFocusState( true ); -} - -void ShaderEditor::Tick() -{ - Scintilla::Editor::Tick(); -} - -void ShaderEditor::SetTicking( bool on ) -{ - -} - -int ShaderEditor::KeyDown( int key, bool shift, bool ctrl, bool alt, bool *consumed ) -{ - return Scintilla::Editor::KeyDown( key, shift, ctrl, alt, consumed ); -} - -void ShaderEditor::AddCharUTF( const char *s, unsigned int len, bool treatAsDBCS ) -{ - Scintilla::Editor::AddCharUTF( s, len, treatAsDBCS ); -} - -void ShaderEditor::GetText( char * buf, int len ) -{ - memset( buf, 0, len ); - - int lengthDoc = (int)WndProc( SCI_GETLENGTH, 0, 0 ); - - Scintilla::TextRange tr; - tr.chrg.cpMin = 0; - tr.chrg.cpMax = Scintilla::Platform::Minimum( len - 1, lengthDoc ); - tr.lpstrText = buf; - - WndProc(SCI_GETTEXTRANGE, 0, reinterpret_cast(&tr)); -} - -void ShaderEditor::NotifyStyleToNeeded(int endStyleNeeded) { -#ifdef SCI_LEXER - if (lexState->lexLanguage != SCLEX_CONTAINER) { - int lineEndStyled = pdoc->LineFromPosition(pdoc->GetEndStyled()); - int endStyled = pdoc->LineStart(lineEndStyled); - lexState->Colourise(endStyled, endStyleNeeded); - return; - } -#endif - Scintilla::Editor::NotifyStyleToNeeded(endStyleNeeded); -} - -void ShaderEditor::SetReadOnly( bool b ) -{ - bReadOnly = b; + if ( !bReadOnly ) + SetFocusState( true ); +} + +void ShaderEditor::Tick() +{ + Scintilla::Editor::Tick(); +} + +void ShaderEditor::SetTicking( bool on ) +{ + +} + +int ShaderEditor::KeyDown( int key, bool shift, bool ctrl, bool alt, bool * consumed ) +{ + return Scintilla::Editor::KeyDown( key, shift, ctrl, alt, consumed ); +} + +void ShaderEditor::AddCharUTF( const char * s, unsigned int len, bool treatAsDBCS ) +{ + Scintilla::Editor::AddCharUTF( s, len, treatAsDBCS ); +} + +void ShaderEditor::GetText( char * buf, int len ) +{ + memset( buf, 0, len ); + + int lengthDoc = (int) WndProc( SCI_GETLENGTH, 0, 0 ); + + Scintilla::TextRange tr; + tr.chrg.cpMin = 0; + tr.chrg.cpMax = Scintilla::Platform::Minimum( len - 1, lengthDoc ); + tr.lpstrText = buf; + + WndProc( SCI_GETTEXTRANGE, 0, reinterpret_cast( &tr ) ); +} + +void ShaderEditor::NotifyStyleToNeeded( int endStyleNeeded ) +{ +#ifdef SCI_LEXER + if ( lexState->lexLanguage != SCLEX_CONTAINER ) + { + int lineEndStyled = pdoc->LineFromPosition( pdoc->GetEndStyled() ); + int endStyled = pdoc->LineStart( lineEndStyled ); + lexState->Colourise( endStyled, endStyleNeeded ); + return; + } +#endif + Scintilla::Editor::NotifyStyleToNeeded( endStyleNeeded ); +} + +void ShaderEditor::SetReadOnly( bool b ) +{ + bReadOnly = b; WndProc( SCI_SETREADONLY, bReadOnly, 0 ); - if (bReadOnly) - { - WndProc(SCI_SETVIEWWS, SCWS_INVISIBLE, 0); - WndProc(SCI_SETMARGINWIDTHN, 0, 0); - WndProc(SCI_SETMARGINWIDTHN, 1, 0); - WndProc( SCI_SETCARETLINEVISIBLE, 0, 0); - WndProc( SCI_SETCARETFORE, 0, 0); - } - else - { - WndProc(SCI_SETMARGINWIDTHN, 0, 44);//Calculate correct width - WndProc(SCI_SETMARGINWIDTHN, 1, 20);//Calculate correct width - WndProc(SCI_SETMARGINMASKN, 1, SC_MASK_FOLDERS);//Calculate correct width - - WndProc( SCI_SETCARETFORE, 0xFFFFFFFF, 0); - WndProc( SCI_SETCARETLINEVISIBLE, 1, 0); - WndProc( SCI_SETCARETLINEBACK, 0xFFFFFFFF, 0); - WndProc( SCI_SETCARETLINEBACKALPHA, 0x20, 0); - } -} - -void ShaderEditor::ButtonDown( Scintilla::Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt ) -{ - Scintilla::PRectangle rect = wMain.GetPosition(); - pt.x -= rect.left; - pt.y -= rect.top; - Scintilla::Editor::ButtonDown( pt, curTime, shift, ctrl, alt ); -} - -void ShaderEditor::ButtonMovePublic( Scintilla::Point pt ) -{ - Scintilla::PRectangle rect = wMain.GetPosition(); - pt.x -= rect.left; - pt.y -= rect.top; - ButtonMove(pt); -} - -void ShaderEditor::ButtonUp( Scintilla::Point pt, unsigned int curTime, bool ctrl ) -{ - Scintilla::PRectangle rect = wMain.GetPosition(); - pt.x -= rect.left; - pt.y -= rect.top; - Scintilla::Editor::ButtonUp( pt, curTime, ctrl ); -} - -Font * ShaderEditor::GetTextFont() -{ - return &vs.styles[ STYLE_DEFAULT ].font; -} - -void ShaderEditor::SetPosition( Scintilla::PRectangle rect ) -{ - wMain.SetPosition(rect); -} - -bool ShaderEditor::FineTickerRunning( TickReason ) -{ - return false; -} - -void ShaderEditor::FineTickerStart( TickReason, int, int ) -{ - -} - -void ShaderEditor::FineTickerCancel( TickReason ) -{ - -} - - -///////////////////////////////////////////////////////////////////////////////////////////// -// Indentation handling - -int ShaderEditor::GetLineLength(int line) { - return WndProc(SCI_GETLINEENDPOSITION, line, 0) - WndProc(SCI_POSITIONFROMLINE, line, 0); -} - -int ShaderEditor::GetCurrentLineNumber() { - return WndProc(SCI_LINEFROMPOSITION, WndProc(SCI_GETCURRENTPOS, 0, 0), 0); -} - -Sci_CharacterRange ShaderEditor::GetSelection() { - Sci_CharacterRange chrange; - chrange.cpMin = WndProc(SCI_GETSELECTIONSTART, 0, 0); - chrange.cpMax = WndProc(SCI_GETSELECTIONEND, 0, 0); - return chrange; -} - -int ShaderEditor::GetLineIndentation(int line) { - return WndProc(SCI_GETLINEINDENTATION, line, 0); -} - -int ShaderEditor::GetLineIndentPosition(int line) { - return WndProc(SCI_GETLINEINDENTPOSITION, line, 0); -} - -void ShaderEditor::SetLineIndentation(int line, int indent) { - if (indent < 0) - return; - Sci_CharacterRange crange = GetSelection(); - int posBefore = GetLineIndentPosition(line); - WndProc(SCI_SETLINEINDENTATION, line, indent); - int posAfter = GetLineIndentPosition(line); - int posDifference = posAfter - posBefore; - if (posAfter > posBefore) { - // Move selection on - if (crange.cpMin >= posBefore) { - crange.cpMin += posDifference; - } - if (crange.cpMax >= posBefore) { - crange.cpMax += posDifference; - } - } else if (posAfter < posBefore) { - // Move selection back - if (crange.cpMin >= posAfter) { - if (crange.cpMin >= posBefore) { - crange.cpMin += posDifference; - } else { - crange.cpMin = posAfter; - } - } - if (crange.cpMax >= posAfter) { - if (crange.cpMax >= posBefore) { - crange.cpMax += posDifference; - } else { - crange.cpMax = posAfter; - } - } - } - SetSelection(static_cast(crange.cpMin), static_cast(crange.cpMax)); -} - -void ShaderEditor::PreserveIndentation(char ch) { - int eolMode = WndProc(SCI_GETEOLMODE, 0, 0); - int curLine = GetCurrentLineNumber(); - int lastLine = curLine - 1; - - if (((eolMode == SC_EOL_CRLF || eolMode == SC_EOL_LF) && ch == '\n') || (eolMode == SC_EOL_CR && ch == '\r')) { - while (lastLine >= 0 && GetLineLength(lastLine) == 0) { - lastLine--; - } - int indentAmount = 0; - if (lastLine >= 0) { - indentAmount = GetLineIndentation(lastLine); - } - if (indentAmount > 0) { - SetLineIndentation(curLine, indentAmount); - } - } -} - -std::vector ShaderEditor::GetLinePartsInStyle(int line, int style) { - std::vector out; - std::string s; - int thisLineStart = WndProc(SCI_POSITIONFROMLINE, line, 0); - int nextLineStart = WndProc(SCI_POSITIONFROMLINE, line + 1, 0); - for (int pos = thisLineStart; pos < nextLineStart; pos++) { - if (static_cast(WndProc(SCI_GETSTYLEAT, pos, 0)) == style) { - char c = WndProc(SCI_GETCHARAT, pos, 0); - // special handling for statements and blocks characters as they should be dissociated to other strings - if (c == statementEnd || c == blockStart || c == blockEnd) { - out.push_back(std::string(1, c)); - s = ""; - } else { - s += c; - } - } else if (s.size() > 0) { - out.push_back(s); - s = ""; - } - } - if (s.size() > 0) { - out.push_back(s); - } - - return out; -} - -bool ShaderEditor::isAStatementIndent(std::string &word) { - for (size_t i=0; i<(sizeof(statementIndent)/sizeof(statementIndent[0])); i++) { - std::string &statementElem = statementIndent[i]; - if (statementElem == word) { - return true; - } - } - return false; -} - -ShaderEditor::IndentationStatus ShaderEditor::GetIndentState(int line) { - size_t i; - IndentationStatus indentState = isNone; - std::vector controlWords = GetLinePartsInStyle(line, statementIndentStyleNumber); - for (i=0; i= lineLimit) && (indentState == isNone)) { - indentState = GetIndentState(backLine); - if (indentState != isNone) { - indentBlock = GetLineIndentation(backLine); - if (indentState == isBlockStart) { - indentBlock += indentSize; - } - if (indentState == isBlockEnd) { - if (indentBlock < 0) - indentBlock = 0; - } - if ((indentState == isKeyWordStart) && (backLine == line)) - indentBlock += indentSize; - } - backLine--; - } - - return indentBlock; -} - -bool ShaderEditor::RangeIsAllWhitespace(int start, int end) { - for (int i = start; i < end; i++) { - if ((WndProc(SCI_GETCHARAT, i, 0) != ' ') && (WndProc(SCI_GETCHARAT, i, 0) != '\t')) - return false; - } - return true; -} - -void ShaderEditor::AutomaticIndentation(char ch) { - Sci_CharacterRange crange = GetSelection(); - int selStart = static_cast(crange.cpMin); - int curLine = GetCurrentLineNumber(); - int thisLineStart = WndProc(SCI_POSITIONFROMLINE, curLine, 0); - int indentSize = WndProc(SCI_GETINDENT, 0, 0); - int indentBlock = IndentOfBlock(curLine - 1); - - if (ch == blockEnd) { - if (RangeIsAllWhitespace(thisLineStart, selStart - 1)) { - SetLineIndentation(curLine, indentBlock - indentSize); - } - } else if (ch == blockStart) { - if (GetIndentState(curLine - 1) == isKeyWordStart) { - if (RangeIsAllWhitespace(thisLineStart, selStart - 1)) { - SetLineIndentation(curLine, indentBlock - indentSize); - } - } - } else if ((ch == '\r' || ch == '\n') && (selStart == thisLineStart)) { - SetLineIndentation(curLine, indentBlock); - } -} + if ( bReadOnly ) + { + WndProc( SCI_SETVIEWWS, SCWS_INVISIBLE, 0 ); + WndProc( SCI_SETMARGINWIDTHN, 0, 0 ); + WndProc( SCI_SETMARGINWIDTHN, 1, 0 ); + WndProc( SCI_SETCARETLINEVISIBLE, 0, 0 ); + WndProc( SCI_SETCARETFORE, 0, 0 ); + } + else + { + WndProc( SCI_SETMARGINWIDTHN, 0, 44 );//Calculate correct width + WndProc( SCI_SETMARGINWIDTHN, 1, 20 );//Calculate correct width + WndProc( SCI_SETMARGINMASKN, 1, SC_MASK_FOLDERS );//Calculate correct width + + WndProc( SCI_SETCARETFORE, 0xFFFFFFFF, 0 ); + WndProc( SCI_SETCARETLINEVISIBLE, 1, 0 ); + WndProc( SCI_SETCARETLINEBACK, 0xFFFFFFFF, 0 ); + WndProc( SCI_SETCARETLINEBACKALPHA, 0x20, 0 ); + } +} + +void ShaderEditor::ButtonDown( Scintilla::Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt ) +{ + Scintilla::PRectangle rect = wMain.GetPosition(); + pt.x -= rect.left; + pt.y -= rect.top; + Scintilla::Editor::ButtonDown( pt, curTime, shift, ctrl, alt ); +} + +void ShaderEditor::ButtonMovePublic( Scintilla::Point pt ) +{ + Scintilla::PRectangle rect = wMain.GetPosition(); + pt.x -= rect.left; + pt.y -= rect.top; + ButtonMove( pt ); +} + +void ShaderEditor::ButtonUp( Scintilla::Point pt, unsigned int curTime, bool ctrl ) +{ + Scintilla::PRectangle rect = wMain.GetPosition(); + pt.x -= rect.left; + pt.y -= rect.top; + Scintilla::Editor::ButtonUp( pt, curTime, ctrl ); +} + +Font * ShaderEditor::GetTextFont() +{ + return &vs.styles[ STYLE_DEFAULT ].font; +} + +void ShaderEditor::SetPosition( Scintilla::PRectangle rect ) +{ + wMain.SetPosition( rect ); +} + +bool ShaderEditor::FineTickerRunning( TickReason ) +{ + return false; +} + +void ShaderEditor::FineTickerStart( TickReason, int, int ) +{ + +} + +void ShaderEditor::FineTickerCancel( TickReason ) +{ + +} + + +///////////////////////////////////////////////////////////////////////////////////////////// +// Indentation handling + +int ShaderEditor::GetLineLength( int line ) +{ + return WndProc( SCI_GETLINEENDPOSITION, line, 0 ) - WndProc( SCI_POSITIONFROMLINE, line, 0 ); +} + +int ShaderEditor::GetCurrentLineNumber() +{ + return WndProc( SCI_LINEFROMPOSITION, WndProc( SCI_GETCURRENTPOS, 0, 0 ), 0 ); +} + +Sci_CharacterRange ShaderEditor::GetSelection() +{ + Sci_CharacterRange chrange; + chrange.cpMin = WndProc( SCI_GETSELECTIONSTART, 0, 0 ); + chrange.cpMax = WndProc( SCI_GETSELECTIONEND, 0, 0 ); + return chrange; +} + +int ShaderEditor::GetLineIndentation( int line ) +{ + return WndProc( SCI_GETLINEINDENTATION, line, 0 ); +} + +int ShaderEditor::GetLineIndentPosition( int line ) +{ + return WndProc( SCI_GETLINEINDENTPOSITION, line, 0 ); +} + +void ShaderEditor::SetLineIndentation( int line, int indent ) +{ + if ( indent < 0 ) + return; + Sci_CharacterRange crange = GetSelection(); + int posBefore = GetLineIndentPosition( line ); + WndProc( SCI_SETLINEINDENTATION, line, indent ); + int posAfter = GetLineIndentPosition( line ); + int posDifference = posAfter - posBefore; + if ( posAfter > posBefore ) + { + // Move selection on + if ( crange.cpMin >= posBefore ) + { + crange.cpMin += posDifference; + } + if ( crange.cpMax >= posBefore ) + { + crange.cpMax += posDifference; + } + } + else if ( posAfter < posBefore ) + { + // Move selection back + if ( crange.cpMin >= posAfter ) + { + if ( crange.cpMin >= posBefore ) + { + crange.cpMin += posDifference; + } + else { + crange.cpMin = posAfter; + } + } + if ( crange.cpMax >= posAfter ) + { + if ( crange.cpMax >= posBefore ) + { + crange.cpMax += posDifference; + } + else { + crange.cpMax = posAfter; + } + } + } + SetSelection( static_cast( crange.cpMin ), static_cast( crange.cpMax ) ); +} + +void ShaderEditor::PreserveIndentation( char ch ) +{ + int eolMode = WndProc( SCI_GETEOLMODE, 0, 0 ); + int curLine = GetCurrentLineNumber(); + int lastLine = curLine - 1; + + if ( ( ( eolMode == SC_EOL_CRLF || eolMode == SC_EOL_LF ) && ch == '\n' ) || ( eolMode == SC_EOL_CR && ch == '\r' ) ) + { + while ( lastLine >= 0 && GetLineLength( lastLine ) == 0 ) + { + lastLine--; + } + int indentAmount = 0; + if ( lastLine >= 0 ) + { + indentAmount = GetLineIndentation( lastLine ); + } + if ( indentAmount > 0 ) + { + SetLineIndentation( curLine, indentAmount ); + } + } +} + +std::vector ShaderEditor::GetLinePartsInStyle( int line, int style ) +{ + std::vector out; + std::string s; + int thisLineStart = WndProc( SCI_POSITIONFROMLINE, line, 0 ); + int nextLineStart = WndProc( SCI_POSITIONFROMLINE, line + 1, 0 ); + for ( int pos = thisLineStart; pos < nextLineStart; pos++ ) + { + if ( static_cast( WndProc( SCI_GETSTYLEAT, pos, 0 ) ) == style ) + { + char c = WndProc( SCI_GETCHARAT, pos, 0 ); + // special handling for statements and blocks characters as they should be dissociated to other strings + if ( c == statementEnd || c == blockStart || c == blockEnd ) + { + out.push_back( std::string( 1, c ) ); + s = ""; + } + else { + s += c; + } + } + else if ( s.size() > 0 ) + { + out.push_back( s ); + s = ""; + } + } + if ( s.size() > 0 ) + { + out.push_back( s ); + } + + return out; +} + +bool ShaderEditor::isAStatementIndent( std::string & word ) +{ + for ( size_t i = 0; i < ( sizeof( statementIndent ) / sizeof( statementIndent[ 0 ] ) ); i++ ) + { + std::string & statementElem = statementIndent[ i ]; + if ( statementElem == word ) + { + return true; + } + } + return false; +} + +ShaderEditor::IndentationStatus ShaderEditor::GetIndentState( int line ) +{ + size_t i; + IndentationStatus indentState = isNone; + std::vector controlWords = GetLinePartsInStyle( line, statementIndentStyleNumber ); + for ( i = 0; i < controlWords.size(); i++ ) + { + std::string & controlWord = controlWords[ i ]; + if ( isAStatementIndent( controlWord ) ) + { + indentState = isKeyWordStart; + } + } + + controlWords = GetLinePartsInStyle( line, blockAndStatementEndStyleNumber ); + for ( i = 0; i < controlWords.size(); i++ ) + { + std::string & controlWord = controlWords[ i ]; + if ( controlWord.size() < 1 ) continue; + if ( statementEnd == controlWord[ 0 ] ) + { + indentState = isNone; + } + } + + for ( i = 0; i < controlWords.size(); i++ ) + { + std::string & controlWord = controlWords[ i ]; + if ( controlWord.size() < 1 ) continue; + if ( blockEnd == controlWord[ 0 ] ) + { + indentState = isBlockEnd; + } + if ( blockStart == controlWord[ 0 ] ) + { + indentState = isBlockStart; + } + } + + return indentState; +} + +int ShaderEditor::IndentOfBlock( int line ) +{ + if ( line < 0 ) + return 0; + int indentSize = WndProc( SCI_GETINDENT, 0, 0 ); + int indentBlock = GetLineIndentation( line ); + int backLine = line; + IndentationStatus indentState = isNone; + + int lineLimit = line - statementLookback; + if ( lineLimit < 0 ) lineLimit = 0; + + while ( ( backLine >= lineLimit ) && ( indentState == isNone ) ) + { + indentState = GetIndentState( backLine ); + if ( indentState != isNone ) + { + indentBlock = GetLineIndentation( backLine ); + if ( indentState == isBlockStart ) + { + indentBlock += indentSize; + } + if ( indentState == isBlockEnd ) + { + if ( indentBlock < 0 ) + indentBlock = 0; + } + if ( ( indentState == isKeyWordStart ) && ( backLine == line ) ) + indentBlock += indentSize; + } + backLine--; + } + + return indentBlock; +} + +bool ShaderEditor::RangeIsAllWhitespace( int start, int end ) +{ + for ( int i = start; i < end; i++ ) + { + if ( ( WndProc( SCI_GETCHARAT, i, 0 ) != ' ' ) && ( WndProc( SCI_GETCHARAT, i, 0 ) != '\t' ) ) + return false; + } + return true; +} + +void ShaderEditor::AutomaticIndentation( char ch ) +{ + Sci_CharacterRange crange = GetSelection(); + int selStart = static_cast( crange.cpMin ); + int curLine = GetCurrentLineNumber(); + int thisLineStart = WndProc( SCI_POSITIONFROMLINE, curLine, 0 ); + int indentSize = WndProc( SCI_GETINDENT, 0, 0 ); + int indentBlock = IndentOfBlock( curLine - 1 ); + + if ( ch == blockEnd ) + { + if ( RangeIsAllWhitespace( thisLineStart, selStart - 1 ) ) + { + SetLineIndentation( curLine, indentBlock - indentSize ); + } + } + else if ( ch == blockStart ) + { + if ( GetIndentState( curLine - 1 ) == isKeyWordStart ) + { + if ( RangeIsAllWhitespace( thisLineStart, selStart - 1 ) ) + { + SetLineIndentation( curLine, indentBlock - indentSize ); + } + } + } + else if ( ( ch == '\r' || ch == '\n' ) && ( selStart == thisLineStart ) ) + { + SetLineIndentation( curLine, indentBlock ); + } +} diff --git a/src/ShaderEditor.h b/src/ShaderEditor.h index 4b46b017..b482a236 100644 --- a/src/ShaderEditor.h +++ b/src/ShaderEditor.h @@ -48,13 +48,15 @@ #include #endif -enum AutoIndentationType { +enum AutoIndentationType +{ aitNone, aitPreserve, aitSmart }; -struct SHADEREDITOR_THEME { +struct SHADEREDITOR_THEME +{ unsigned int text; unsigned int comment; unsigned int number; @@ -68,22 +70,23 @@ struct SHADEREDITOR_THEME { bool bUseCharBackground; SHADEREDITOR_THEME() - : text( 0xFFFFFFFF ) - , comment( 0xFF00FF00 ) - , number( 0xFF0080FF ) - , op( 0xFF00CCFF ) - , keyword( 0xFF0066FF ) - , type( 0xFFFFFF00 ) - , builtin( 0xFF88FF44 ) - , preprocessor( 0xFFC0C0C0 ) - , selection( 0xC0CC9966 ) - , charBackground( 0xC0000000 ) - , bUseCharBackground( false ) + : text( 0xFFFFFFFF ) + , comment( 0xFF00FF00 ) + , number( 0xFF0080FF ) + , op( 0xFF00CCFF ) + , keyword( 0xFF0066FF ) + , type( 0xFFFFFF00 ) + , builtin( 0xFF88FF44 ) + , preprocessor( 0xFFC0C0C0 ) + , selection( 0xC0CC9966 ) + , charBackground( 0xC0000000 ) + , bUseCharBackground( false ) { } }; -struct SHADEREDITOR_OPTIONS { +struct SHADEREDITOR_OPTIONS +{ std::string sFontPath; int nFontSize; Scintilla::PRectangle rect; @@ -97,7 +100,7 @@ struct SHADEREDITOR_OPTIONS { class ShaderEditor : public Scintilla::Editor { - Scintilla::Surface *surfaceWindow; + Scintilla::Surface * surfaceWindow; Scintilla::LexState * lexState; bool bReadOnly; bool bHasMouseCapture; @@ -112,66 +115,67 @@ class ShaderEditor : public Scintilla::Editor SHADEREDITOR_THEME theme; public: - ShaderEditor(Scintilla::Surface *surfaceWindow); + ShaderEditor( Scintilla::Surface * surfaceWindow ); void Initialise(); - void Initialise(SHADEREDITOR_OPTIONS &options); + void Initialise( SHADEREDITOR_OPTIONS & options ); void SetPosition( Scintilla::PRectangle rect ); void SetVerticalScrollPos(); void SetHorizontalScrollPos(); - bool ModifyScrollBars(int nMax, int nPage); + bool ModifyScrollBars( int nMax, int nPage ); void Copy(); void Paste(); void ClaimSelection(); void NotifyChange(); - void NotifyParent(Scintilla::SCNotification scn); - void CopyToClipboard(const Scintilla::SelectionText &selectedText); - void SetMouseCapture(bool on); + void NotifyParent( Scintilla::SCNotification scn ); + void CopyToClipboard( const Scintilla::SelectionText & selectedText ); + void SetMouseCapture( bool on ); bool HaveMouseCapture(); - sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam); + sptr_t DefWndProc( unsigned int iMessage, uptr_t wParam, sptr_t lParam ); - void SetTicking(bool on); - bool FineTickerRunning(TickReason); - void FineTickerStart(TickReason, int, int); - void FineTickerCancel(TickReason); + void SetTicking( bool on ); + bool FineTickerRunning( TickReason ); + void FineTickerStart( TickReason, int, int ); + void FineTickerCancel( TickReason ); void SetText( const char * buf ); void GetText( char * buf, int len ); void Paint(); - void SetAStyle(int style, Scintilla::ColourDesired fore, Scintilla::ColourDesired back=0xFFFFFFFF, int size=-1, const char *face=0); + void SetAStyle( int style, Scintilla::ColourDesired fore, Scintilla::ColourDesired back = 0xFFFFFFFF, int size = -1, const char * face = 0 ); void Tick(); - int KeyDown(int key, bool shift, bool ctrl, bool alt, bool *consumed); + int KeyDown( int key, bool shift, bool ctrl, bool alt, bool * consumed ); void ButtonDown( Scintilla::Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt ); void ButtonMovePublic( Scintilla::Point pt ); void ButtonUp( Scintilla::Point pt, unsigned int curTime, bool ctrl ); - void AddCharUTF( const char *s, unsigned int len, bool treatAsDBCS=false ); - void NotifyStyleToNeeded(int endStyleNeeded); + void AddCharUTF( const char * s, unsigned int len, bool treatAsDBCS = false ); + void NotifyStyleToNeeded( int endStyleNeeded ); void SetReadOnly( bool ); Scintilla::Font * GetTextFont(); - + private: - enum IndentationStatus { + enum IndentationStatus + { isNone, // no effect on indentation isBlockStart, // indentation block begin such as "{" or VB "function" isBlockEnd, // indentation end indicator such as "}" or VB "end" isKeyWordStart // Keywords that cause indentation }; - - int GetLineLength(int line); + + int GetLineLength( int line ); int GetCurrentLineNumber(); Scintilla::Sci_CharacterRange GetSelection(); - int GetLineIndentation(int line); - int GetLineIndentPosition(int line); - void SetLineIndentation(int line, int indent); - void PreserveIndentation(char ch); - std::vector GetLinePartsInStyle(int line, int style); - bool isAStatementIndent(std::string &word); - IndentationStatus GetIndentState(int line); - int IndentOfBlock(int line); - bool RangeIsAllWhitespace(int start, int end); - void AutomaticIndentation(char ch); + int GetLineIndentation( int line ); + int GetLineIndentPosition( int line ); + void SetLineIndentation( int line, int indent ); + void PreserveIndentation( char ch ); + std::vector GetLinePartsInStyle( int line, int style ); + bool isAStatementIndent( std::string & word ); + IndentationStatus GetIndentState( int line ); + int IndentOfBlock( int line ); + bool RangeIsAllWhitespace( int start, int end ); + void AutomaticIndentation( char ch ); }; diff --git a/src/Timer.h b/src/Timer.h index 85cdaca1..004683e8 100644 --- a/src/Timer.h +++ b/src/Timer.h @@ -1,5 +1,9 @@ namespace Timer { - void Start(); - float GetTime(); +////////////////////////////////////////////////////////////////////////// + +void Start(); +float GetTime(); + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/capturing/Capture_Dummy.cpp b/src/capturing/Capture_Dummy.cpp index b0ca4f28..07c97dc2 100644 --- a/src/capturing/Capture_Dummy.cpp +++ b/src/capturing/Capture_Dummy.cpp @@ -3,17 +3,21 @@ namespace Capture { - void LoadSettings(jsonxx::Object & o) - { - } - bool Open(RENDERER_SETTINGS & settings) - { - return true; - } - void CaptureFrame() - { - } - void Close() - { - } +////////////////////////////////////////////////////////////////////////// + +void LoadSettings( jsonxx::Object & o ) +{ +} +bool Open( Renderer::Settings & settings ) +{ + return true; +} +void CaptureFrame() +{ +} +void Close() +{ +} + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/capturing/Capture_NDI.cpp b/src/capturing/Capture_NDI.cpp index 1d7609ef..157d7adc 100644 --- a/src/capturing/Capture_NDI.cpp +++ b/src/capturing/Capture_NDI.cpp @@ -6,103 +6,107 @@ namespace Capture { - std::string sNDIConnectionString; - float fNDIFrameRate = 60.0; - std::string sNDIIdentifier; - bool bNDIProgressive = true; - bool bNDIEnabled = true; - unsigned int * pBuffer[2] = { NULL, NULL }; - unsigned int nBufferIndex = 0; - NDIlib_video_frame_v2_t pNDIFrame; - NDIlib_send_instance_t pNDI_send; +////////////////////////////////////////////////////////////////////////// - void LoadSettings(jsonxx::Object & o) +std::string sNDIConnectionString; +float fNDIFrameRate = 60.0; +std::string sNDIIdentifier; +bool bNDIProgressive = true; +bool bNDIEnabled = true; +unsigned int * pBuffer[ 2 ] = { NULL, NULL }; +unsigned int nBufferIndex = 0; +NDIlib_video_frame_v2_t pNDIFrame; +NDIlib_send_instance_t pNDI_send; + +void LoadSettings( jsonxx::Object & o ) +{ + if ( o.has( "ndi" ) ) { - if (o.has("ndi")) - { - if (o.get("ndi").has("enabled")) - bNDIEnabled = o.get("ndi").get("enabled"); - if (o.get("ndi").has("connectionString")) - sNDIConnectionString = o.get("ndi").get("connectionString"); - if (o.get("ndi").has("identifier")) - sNDIIdentifier = o.get("ndi").get("identifier"); - if (o.get("ndi").has("frameRate")) - fNDIFrameRate = (float)o.get("ndi").get("frameRate"); - if (o.get("ndi").has("progressive")) - bNDIProgressive = o.get("ndi").get("progressive"); - } + if ( o.get( "ndi" ).has( "enabled" ) ) + bNDIEnabled = o.get( "ndi" ).get( "enabled" ); + if ( o.get( "ndi" ).has( "connectionString" ) ) + sNDIConnectionString = o.get( "ndi" ).get( "connectionString" ); + if ( o.get( "ndi" ).has( "identifier" ) ) + sNDIIdentifier = o.get( "ndi" ).get( "identifier" ); + if ( o.get( "ndi" ).has( "frameRate" ) ) + fNDIFrameRate = (float) o.get( "ndi" ).get( "frameRate" ); + if ( o.get( "ndi" ).has( "progressive" ) ) + bNDIProgressive = o.get( "ndi" ).get( "progressive" ); } - bool Open(RENDERER_SETTINGS & settings) +} +bool Open( Renderer::Settings & settings ) +{ + if ( bNDIEnabled ) { - if (bNDIEnabled) + if ( !NDIlib_initialize() ) { - if (!NDIlib_initialize()) - { - printf("[Capture] Cannot initialize NDI"); - return false; - } + printf( "[Capture] Cannot initialize NDI" ); + return false; + } - NDIlib_send_create_t pNDICreateDesc; - sNDIIdentifier = "BONZOMATIC" + (sNDIIdentifier.length() ? (" - " + sNDIIdentifier) : ""); - pNDICreateDesc.p_ndi_name = sNDIIdentifier.c_str(); - pNDICreateDesc.p_groups = NULL; - pNDICreateDesc.clock_video = true; - pNDICreateDesc.clock_audio = false; + NDIlib_send_create_t pNDICreateDesc; + sNDIIdentifier = "BONZOMATIC" + ( sNDIIdentifier.length() ? ( " - " + sNDIIdentifier ) : "" ); + pNDICreateDesc.p_ndi_name = sNDIIdentifier.c_str(); + pNDICreateDesc.p_groups = NULL; + pNDICreateDesc.clock_video = true; + pNDICreateDesc.clock_audio = false; - pNDI_send = NDIlib_send_create(&pNDICreateDesc); - if (!pNDI_send) - { - printf("[Capture] Cannot create NDI source"); - return false; - } + pNDI_send = NDIlib_send_create( &pNDICreateDesc ); + if ( !pNDI_send ) + { + printf( "[Capture] Cannot create NDI source" ); + return false; + } - NDIlib_metadata_frame_t pNDIConnType; - pNDIConnType.length = (int)sNDIConnectionString.length(); - pNDIConnType.timecode = NDIlib_send_timecode_synthesize; - pNDIConnType.p_data = (char*)sNDIConnectionString.c_str(); + NDIlib_metadata_frame_t pNDIConnType; + pNDIConnType.length = (int) sNDIConnectionString.length(); + pNDIConnType.timecode = NDIlib_send_timecode_synthesize; + pNDIConnType.p_data = (char *) sNDIConnectionString.c_str(); - NDIlib_send_add_connection_metadata(pNDI_send, &pNDIConnType); + NDIlib_send_add_connection_metadata( pNDI_send, &pNDIConnType ); - pNDIFrame.xres = settings.nWidth; - pNDIFrame.yres = settings.nHeight; - pNDIFrame.FourCC = NDIlib_FourCC_type_BGRX; - pNDIFrame.frame_rate_N = (int)(fNDIFrameRate * 100); - pNDIFrame.frame_rate_D = 100; - pNDIFrame.picture_aspect_ratio = settings.nWidth / (float)settings.nHeight; - pNDIFrame.frame_format_type = bNDIProgressive ? NDIlib_frame_format_type_progressive : NDIlib_frame_format_type_interleaved; - pNDIFrame.timecode = NDIlib_send_timecode_synthesize; - pBuffer[0] = new unsigned int[settings.nWidth * settings.nHeight * 4]; - pBuffer[1] = new unsigned int[settings.nWidth * settings.nHeight * 4]; - pNDIFrame.p_data = NULL; - pNDIFrame.line_stride_in_bytes = settings.nWidth * 4; - } - return true; + pNDIFrame.xres = settings.nWidth; + pNDIFrame.yres = settings.nHeight; + pNDIFrame.FourCC = NDIlib_FourCC_type_BGRX; + pNDIFrame.frame_rate_N = (int) ( fNDIFrameRate * 100 ); + pNDIFrame.frame_rate_D = 100; + pNDIFrame.picture_aspect_ratio = settings.nWidth / (float) settings.nHeight; + pNDIFrame.frame_format_type = bNDIProgressive ? NDIlib_frame_format_type_progressive : NDIlib_frame_format_type_interleaved; + pNDIFrame.timecode = NDIlib_send_timecode_synthesize; + pBuffer[ 0 ] = new unsigned int[ settings.nWidth * settings.nHeight * 4 ]; + pBuffer[ 1 ] = new unsigned int[ settings.nWidth * settings.nHeight * 4 ]; + pNDIFrame.p_data = NULL; + pNDIFrame.line_stride_in_bytes = settings.nWidth * 4; } - void CaptureFrame() + return true; +} +void CaptureFrame() +{ + if ( pBuffer[ 0 ] && pBuffer[ 1 ] ) { - if (pBuffer[0] && pBuffer[1]) + pNDIFrame.p_data = (unsigned char *) pBuffer[ nBufferIndex ]; + nBufferIndex = ( nBufferIndex + 1 ) & 1; + if ( Renderer::GrabFrame( pNDIFrame.p_data ) ) { - pNDIFrame.p_data = (unsigned char*)pBuffer[ nBufferIndex ]; - nBufferIndex = (nBufferIndex + 1) & 1; - if (Renderer::GrabFrame( pNDIFrame.p_data )) - { - unsigned int * p = (unsigned int *)pNDIFrame.p_data; - for(int i=0; i < pNDIFrame.xres * pNDIFrame.yres; i++) - p[i] = (p[i] & 0x00FF00) | ((p[i] >> 16) & 0xFF) | ((p[i] & 0xFF) << 16) | 0xFF000000; - NDIlib_send_send_video_async_v2(pNDI_send, &pNDIFrame); - } + unsigned int * p = (unsigned int *) pNDIFrame.p_data; + for ( int i = 0; i < pNDIFrame.xres * pNDIFrame.yres; i++ ) + p[ i ] = ( p[ i ] & 0x00FF00 ) | ( ( p[ i ] >> 16 ) & 0xFF ) | ( ( p[ i ] & 0xFF ) << 16 ) | 0xFF000000; + NDIlib_send_send_video_async_v2( pNDI_send, &pNDIFrame ); } } - void Close() +} +void Close() +{ + if ( pBuffer[ 0 ] && pBuffer[ 1 ] ) { - if (pBuffer[0] && pBuffer[1]) - { - NDIlib_send_send_video_async_v2(pNDI_send, NULL); // stop async thread + NDIlib_send_send_video_async_v2( pNDI_send, NULL ); // stop async thread - delete[] pBuffer[0]; - delete[] pBuffer[1]; - NDIlib_send_destroy(pNDI_send); - NDIlib_destroy(); - } + delete[] pBuffer[ 0 ]; + delete[] pBuffer[ 1 ]; + NDIlib_send_destroy( pNDI_send ); + NDIlib_destroy(); } +} + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index b8493ef7..ba59552c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -20,52 +20,53 @@ #include "Capture.h" #include "SetupDialog.h" -unsigned int ParseColor(const std::string& color) { - if (color.size() < 6 || color.size() > 8) return 0xFFFFFFFF; - if (color.size() == 6) +unsigned int ParseColor( const std::string & color ) +{ + if ( color.size() < 6 || color.size() > 8 ) return 0xFFFFFFFF; + if ( color.size() == 6 ) { std::string text = "0x" + color; - unsigned int v = std::stoul(text, 0, 16); - return (0xFF000000 | ((v & 0xFF0000) >> 16) | (v & 0x00FF00) | ((v & 0x0000FF) << 16)); + unsigned int v = std::stoul( text, 0, 16 ); + return ( 0xFF000000 | ( ( v & 0xFF0000 ) >> 16 ) | ( v & 0x00FF00 ) | ( ( v & 0x0000FF ) << 16 ) ); } else { std::string text = "0x" + color; - unsigned int v = std::stoul(text, 0, 16); - return ((v & 0xFF000000) | ((v & 0x00FF0000) >> 16) | (v & 0x0000FF00) | ((v & 0x000000FF) << 16)); + unsigned int v = std::stoul( text, 0, 16 ); + return ( ( v & 0xFF000000 ) | ( ( v & 0x00FF0000 ) >> 16 ) | ( v & 0x0000FF00 ) | ( ( v & 0x000000FF ) << 16 ) ); } } -void ReplaceTokens( std::string &sDefShader, const char * sTokenBegin, const char * sTokenName, const char * sTokenEnd, std::vector &tokens ) +void ReplaceTokens( std::string & sDefShader, const char * sTokenBegin, const char * sTokenName, const char * sTokenEnd, std::vector & tokens ) { - if (sDefShader.find(sTokenBegin) != std::string::npos - && sDefShader.find(sTokenName) != std::string::npos - && sDefShader.find(sTokenEnd) != std::string::npos - && sDefShader.find(sTokenBegin) < sDefShader.find(sTokenName) - && sDefShader.find(sTokenName) < sDefShader.find(sTokenEnd)) + if ( sDefShader.find( sTokenBegin ) != std::string::npos + && sDefShader.find( sTokenName ) != std::string::npos + && sDefShader.find( sTokenEnd ) != std::string::npos + && sDefShader.find( sTokenBegin ) < sDefShader.find( sTokenName ) + && sDefShader.find( sTokenName ) < sDefShader.find( sTokenEnd ) ) { - int nTokenStart = (int)(sDefShader.find(sTokenBegin) + strlen(sTokenBegin)); - std::string sTextureToken = sDefShader.substr( nTokenStart, sDefShader.find(sTokenEnd) - nTokenStart ); + int nTokenStart = (int) ( sDefShader.find( sTokenBegin ) + strlen( sTokenBegin ) ); + std::string sTextureToken = sDefShader.substr( nTokenStart, sDefShader.find( sTokenEnd ) - nTokenStart ); std::string sFinalShader; - sFinalShader = sDefShader.substr( 0, sDefShader.find(sTokenBegin) ); + sFinalShader = sDefShader.substr( 0, sDefShader.find( sTokenBegin ) ); //for (std::map::iterator it = tokens.begin(); it != tokens.end(); it++) - for (int i=0; i < tokens.size(); i++) + for ( int i = 0; i < tokens.size(); i++ ) { std::string s = sTextureToken; - while (s.find(sTokenName) != std::string::npos) + while ( s.find( sTokenName ) != std::string::npos ) { - s.replace( s.find(sTokenName), strlen(sTokenName), tokens[i], 0, std::string::npos ); + s.replace( s.find( sTokenName ), strlen( sTokenName ), tokens[ i ], 0, std::string::npos ); } sFinalShader += s; } - sFinalShader += sDefShader.substr( sDefShader.find(sTokenEnd) + strlen(sTokenEnd), std::string::npos ); + sFinalShader += sDefShader.substr( sDefShader.find( sTokenEnd ) + strlen( sTokenEnd ), std::string::npos ); sDefShader = sFinalShader; } } -int main( int argc, const char *argv[] ) +int main( int argc, const char * argv[] ) { Misc::PlatformStartup(); @@ -117,11 +118,11 @@ int main( int argc, const char *argv[] ) #ifdef _DEBUG settings.sRenderer.nWidth = 1280; settings.sRenderer.nHeight = 720; - settings.sRenderer.windowMode = RENDERER_WINDOWMODE_WINDOWED; + settings.sRenderer.windowMode = Renderer::WINDOWMODE_WINDOWED; #else settings.sRenderer.nWidth = 1920; settings.sRenderer.nHeight = 1080; - settings.sRenderer.windowMode = RENDERER_WINDOWMODE_FULLSCREEN; + settings.sRenderer.windowMode = Renderer::WINDOWMODE_FULLSCREEN; if ( options.has( "window" ) ) { @@ -130,7 +131,7 @@ int main( int argc, const char *argv[] ) if ( options.get( "window" ).has( "height" ) ) settings.sRenderer.nHeight = options.get( "window" ).get( "height" ); if ( options.get( "window" ).has( "fullscreen" ) ) - settings.sRenderer.windowMode = options.get( "window" ).get( "fullscreen" ) ? RENDERER_WINDOWMODE_FULLSCREEN : RENDERER_WINDOWMODE_WINDOWED; + settings.sRenderer.windowMode = options.get( "window" ).get( "fullscreen" ) ? Renderer::WINDOWMODE_FULLSCREEN : Renderer::WINDOWMODE_WINDOWED; } if ( !skipSetupDialog ) { @@ -141,26 +142,26 @@ int main( int argc, const char *argv[] ) } #endif - if (!Renderer::Open( &settings.sRenderer )) + if ( !Renderer::Open( &settings.sRenderer ) ) { - printf("Renderer::Open failed\n"); + printf( "Renderer::Open failed\n" ); return -1; } - if (!FFT::Open( &settings.sFFT )) + if ( !FFT::Open( &settings.sFFT ) ) { - printf("FFT::Open() failed, continuing anyway...\n"); + printf( "FFT::Open() failed, continuing anyway...\n" ); //return -1; } - if (!MIDI::Open()) + if ( !MIDI::Open() ) { - printf("MIDI::Open() failed, continuing anyway...\n"); + printf( "MIDI::Open() failed, continuing anyway...\n" ); //return -1; } - std::map textures; - std::map midiRoutes; + std::map textures; + std::map midiRoutes; const char * szDefaultFontPath = Misc::GetDefaultFontPath(); @@ -189,126 +190,131 @@ int main( int argc, const char *argv[] ) std::string sPostExitCmd; - if (!options.empty()) + if ( !options.empty() ) { - if (options.has("rendering")) + if ( options.has( "rendering" ) ) { - if (options.get("rendering").has("fftSmoothFactor")) - fFFTSmoothingFactor = options.get("rendering").get("fftSmoothFactor"); - if (options.get("rendering").has("fftAmplification")) - FFT::fAmplification = options.get("rendering").get("fftAmplification"); + if ( options.get( "rendering" ).has( "fftSmoothFactor" ) ) + fFFTSmoothingFactor = options.get( "rendering" ).get( "fftSmoothFactor" ); + if ( options.get( "rendering" ).has( "fftAmplification" ) ) + FFT::fAmplification = options.get( "rendering" ).get( "fftAmplification" ); } - if (options.has("textures")) + if ( options.has( "textures" ) ) { - printf("Loading textures...\n"); - std::map tex = options.get("textures").kv_map(); - for (std::map::iterator it = tex.begin(); it != tex.end(); it++) + printf( "Loading textures...\n" ); + std::map tex = options.get( "textures" ).kv_map(); + for ( std::map::iterator it = tex.begin(); it != tex.end(); it++ ) { const char * fn = it->second->string_value_->c_str(); - printf("* %s...\n",fn); + printf( "* %s...\n", fn ); Renderer::Texture * tex = Renderer::CreateRGBA8TextureFromFile( fn ); - if (!tex) + if ( !tex ) { - printf("Renderer::CreateRGBA8TextureFromFile(%s) failed\n",fn); + printf( "Renderer::CreateRGBA8TextureFromFile(%s) failed\n", fn ); return -1; } - textures[it->first] = tex; + textures[ it->first ] = tex; } } - if (options.has("font")) + if ( options.has( "font" ) ) { - if (options.get("font").has("size")) - editorOptions.nFontSize = options.get("font").get("size"); - if (options.get("font").has("file")) + if ( options.get( "font" ).has( "size" ) ) + editorOptions.nFontSize = options.get( "font" ).get( "size" ); + if ( options.get( "font" ).has( "file" ) ) { - std::string fontpath = options.get("font").get("file"); - if (!Misc::FileExists(fontpath.c_str())) + std::string fontpath = options.get( "font" ).get( "file" ); + if ( !Misc::FileExists( fontpath.c_str() ) ) { - printf("Font path (%s) is invalid!\n", fontpath.c_str()); + printf( "Font path (%s) is invalid!\n", fontpath.c_str() ); return -1; } editorOptions.sFontPath = fontpath; } } - if (options.has("gui")) + if ( options.has( "gui" ) ) { - if (options.get("gui").has("outputHeight")) - nDebugOutputHeight = options.get("gui").get("outputHeight"); - if (options.get("gui").has("texturePreviewWidth")) - nTexPreviewWidth = options.get("gui").get("texturePreviewWidth"); - if (options.get("gui").has("opacity")) - editorOptions.nOpacity = options.get("gui").get("opacity"); - if (options.get("gui").has("spacesForTabs")) - editorOptions.bUseSpacesForTabs = options.get("gui").get("spacesForTabs"); - if (options.get("gui").has("tabSize")) - editorOptions.nTabSize = options.get("gui").get("tabSize"); - if (options.get("gui").has("visibleWhitespace")) - editorOptions.bVisibleWhitespace = options.get("gui").get("visibleWhitespace"); - if (options.get("gui").has("autoIndent")) + if ( options.get( "gui" ).has( "outputHeight" ) ) + nDebugOutputHeight = options.get( "gui" ).get( "outputHeight" ); + if ( options.get( "gui" ).has( "texturePreviewWidth" ) ) + nTexPreviewWidth = options.get( "gui" ).get( "texturePreviewWidth" ); + if ( options.get( "gui" ).has( "opacity" ) ) + editorOptions.nOpacity = options.get( "gui" ).get( "opacity" ); + if ( options.get( "gui" ).has( "spacesForTabs" ) ) + editorOptions.bUseSpacesForTabs = options.get( "gui" ).get( "spacesForTabs" ); + if ( options.get( "gui" ).has( "tabSize" ) ) + editorOptions.nTabSize = options.get( "gui" ).get( "tabSize" ); + if ( options.get( "gui" ).has( "visibleWhitespace" ) ) + editorOptions.bVisibleWhitespace = options.get( "gui" ).get( "visibleWhitespace" ); + if ( options.get( "gui" ).has( "autoIndent" ) ) { - std::string autoIndent = options.get("gui").get("autoIndent"); - if (autoIndent == "smart") { + std::string autoIndent = options.get( "gui" ).get( "autoIndent" ); + if ( autoIndent == "smart" ) + { editorOptions.eAutoIndent = aitSmart; - } else if (autoIndent == "preserve") { + } + else if ( autoIndent == "preserve" ) + { editorOptions.eAutoIndent = aitPreserve; - } else { + } + else { editorOptions.eAutoIndent = aitNone; } } - if (options.get("gui").has("scrollXFactor")) - fScrollXFactor = options.get("gui").get("scrollXFactor"); - if (options.get("gui").has("scrollYFactor")) - fScrollYFactor = options.get("gui").get("scrollYFactor"); + if ( options.get( "gui" ).has( "scrollXFactor" ) ) + fScrollXFactor = options.get( "gui" ).get( "scrollXFactor" ); + if ( options.get( "gui" ).has( "scrollYFactor" ) ) + fScrollYFactor = options.get( "gui" ).get( "scrollYFactor" ); } - if (options.has("theme")) + if ( options.has( "theme" ) ) { - const auto& theme = options.get("theme"); - if (theme.has("text")) - editorOptions.theme.text = ParseColor(theme.get("text")); - if (theme.has("comment")) - editorOptions.theme.comment = ParseColor(theme.get("comment")); - if (theme.has("number")) - editorOptions.theme.number = ParseColor(theme.get("number")); - if (theme.has("op")) - editorOptions.theme.op = ParseColor(theme.get("op")); - if (theme.has("keyword")) - editorOptions.theme.keyword = ParseColor(theme.get("keyword")); - if (theme.has("type")) - editorOptions.theme.type = ParseColor(theme.get("type")); - if (theme.has("builtin")) - editorOptions.theme.builtin = ParseColor(theme.get("builtin")); - if (theme.has("preprocessor")) - editorOptions.theme.preprocessor = ParseColor(theme.get("preprocessor")); - if (theme.has("selection")) - editorOptions.theme.selection = ParseColor(theme.get("selection")); - if (theme.has("charBackground")) { + const auto & theme = options.get( "theme" ); + if ( theme.has( "text" ) ) + editorOptions.theme.text = ParseColor( theme.get( "text" ) ); + if ( theme.has( "comment" ) ) + editorOptions.theme.comment = ParseColor( theme.get( "comment" ) ); + if ( theme.has( "number" ) ) + editorOptions.theme.number = ParseColor( theme.get( "number" ) ); + if ( theme.has( "op" ) ) + editorOptions.theme.op = ParseColor( theme.get( "op" ) ); + if ( theme.has( "keyword" ) ) + editorOptions.theme.keyword = ParseColor( theme.get( "keyword" ) ); + if ( theme.has( "type" ) ) + editorOptions.theme.type = ParseColor( theme.get( "type" ) ); + if ( theme.has( "builtin" ) ) + editorOptions.theme.builtin = ParseColor( theme.get( "builtin" ) ); + if ( theme.has( "preprocessor" ) ) + editorOptions.theme.preprocessor = ParseColor( theme.get( "preprocessor" ) ); + if ( theme.has( "selection" ) ) + editorOptions.theme.selection = ParseColor( theme.get( "selection" ) ); + if ( theme.has( "charBackground" ) ) + { editorOptions.theme.bUseCharBackground = true; - editorOptions.theme.charBackground = ParseColor(theme.get("charBackground")); + editorOptions.theme.charBackground = ParseColor( theme.get( "charBackground" ) ); } } - if (options.has("midi")) + if ( options.has( "midi" ) ) { - std::map tex = options.get("midi").kv_map(); - for (std::map::iterator it = tex.begin(); it != tex.end(); it++) + std::map tex = options.get( "midi" ).kv_map(); + for ( std::map::iterator it = tex.begin(); it != tex.end(); it++ ) { - midiRoutes[it->second->number_value_] = it->first; + midiRoutes[ it->second->number_value_ ] = it->first; } } - if (options.has("postExitCmd")) + if ( options.has( "postExitCmd" ) ) { - sPostExitCmd = options.get("postExitCmd"); + sPostExitCmd = options.get( "postExitCmd" ); } Capture::LoadSettings( options ); } - if (!editorOptions.sFontPath.size()) + if ( !editorOptions.sFontPath.size() ) { - printf("Couldn't find any of the default fonts. Please specify one in config.json\n"); + printf( "Couldn't find any of the default fonts. Please specify one in config.json\n" ); return -1; } - if (!Capture::Open(settings.sRenderer)) + if ( !Capture::Open( settings.sRenderer ) ) { - printf("Initializing capture system failed!\n"); + printf( "Initializing capture system failed!\n" ); return 0; } @@ -318,47 +324,47 @@ int main( int argc, const char *argv[] ) Renderer::Texture * texFFTIntegrated = Renderer::Create1DR32Texture( FFT_SIZE ); bool shaderInitSuccessful = false; - char szShader[65535]; - char szError[4096]; - FILE * f = fopen(Renderer::defaultShaderFilename,"rb"); - if (f) + char szShader[ 65535 ]; + char szError[ 4096 ]; + FILE * f = fopen( Renderer::szDefaultShaderFilename, "rb" ); + if ( f ) { - printf("Loading last shader...\n"); + printf( "Loading last shader...\n" ); memset( szShader, 0, 65535 ); fread( szShader, 1, 65535, f ); - fclose(f); - if (Renderer::ReloadShader( szShader, (int)strlen(szShader), szError, 4096 )) + fclose( f ); + if ( Renderer::ReloadShader( szShader, (int) strlen( szShader ), szError, 4096 ) ) { - printf("Last shader works fine.\n"); + printf( "Last shader works fine.\n" ); shaderInitSuccessful = true; } else { - printf("Shader error:\n%s\n", szError); + printf( "Shader error:\n%s\n", szError ); } } - if (!shaderInitSuccessful) + if ( !shaderInitSuccessful ) { - printf("No valid last shader found, falling back to default...\n"); + printf( "No valid last shader found, falling back to default...\n" ); - std::string sDefShader = Renderer::defaultShader; + std::string sDefShader = Renderer::szDefaultShader; std::vector tokens; - for (std::map::iterator it = textures.begin(); it != textures.end(); it++) - tokens.push_back(it->first); - ReplaceTokens(sDefShader, "{%textures:begin%}", "{%textures:name%}", "{%textures:end%}", tokens); + for ( std::map::iterator it = textures.begin(); it != textures.end(); it++ ) + tokens.push_back( it->first ); + ReplaceTokens( sDefShader, "{%textures:begin%}", "{%textures:name%}", "{%textures:end%}", tokens ); tokens.clear(); - for (std::map::iterator it = midiRoutes.begin(); it != midiRoutes.end(); it++) - tokens.push_back(it->second); - ReplaceTokens(sDefShader, "{%midi:begin%}", "{%midi:name%}", "{%midi:end%}", tokens); + for ( std::map::iterator it = midiRoutes.begin(); it != midiRoutes.end(); it++ ) + tokens.push_back( it->second ); + ReplaceTokens( sDefShader, "{%midi:begin%}", "{%midi:name%}", "{%midi:end%}", tokens ); strncpy( szShader, sDefShader.c_str(), 65535 ); - if (!Renderer::ReloadShader( szShader, (int)strlen(szShader), szError, 4096 )) + if ( !Renderer::ReloadShader( szShader, (int) strlen( szShader ), szError, 4096 ) ) { - printf("Default shader compile failed:\n"); - puts(szError); - assert(0); + printf( "Default shader compile failed:\n" ); + puts( szError ); + assert( 0 ); } } @@ -383,73 +389,72 @@ int main( int argc, const char *argv[] ) ShaderEditor mDebugOutput( surface ); mDebugOutput.Initialise( editorOptions ); mDebugOutput.SetText( "" ); - mDebugOutput.SetReadOnly(true); + mDebugOutput.SetReadOnly( true ); - static float fftData[FFT_SIZE]; - memset(fftData, 0, sizeof(float) * FFT_SIZE); - static float fftDataSmoothed[FFT_SIZE]; - memset(fftDataSmoothed, 0, sizeof(float) * FFT_SIZE); + static float fftData[ FFT_SIZE ]; + memset( fftData, 0, sizeof( float ) * FFT_SIZE ); + static float fftDataSmoothed[ FFT_SIZE ]; + memset( fftDataSmoothed, 0, sizeof( float ) * FFT_SIZE ); - - static float fftDataSlightlySmoothed[FFT_SIZE]; - memset(fftDataSlightlySmoothed, 0, sizeof(float) * FFT_SIZE); - static float fftDataIntegrated[FFT_SIZE]; - memset(fftDataIntegrated, 0, sizeof(float) * FFT_SIZE); + static float fftDataSlightlySmoothed[ FFT_SIZE ]; + memset( fftDataSlightlySmoothed, 0, sizeof( float ) * FFT_SIZE ); + static float fftDataIntegrated[ FFT_SIZE ]; + memset( fftDataIntegrated, 0, sizeof( float ) * FFT_SIZE ); bool bShowGui = true; Timer::Start(); float fNextTick = 0.1f; float fLastTimeMS = Timer::GetTime(); - while (!Renderer::WantsToQuit()) + while ( !Renderer::WantsToQuit() ) { bool newShader = false; float time = Timer::GetTime() / 1000.0; // seconds Renderer::StartFrame(); - for(int i=0; i::iterator it = midiRoutes.begin(); it != midiRoutes.end(); it++) + for ( std::map::iterator it = midiRoutes.begin(); it != midiRoutes.end(); it++ ) { Renderer::SetShaderConstant( it->second.c_str(), MIDI::GetCCValue( it->first ) ); } - if (FFT::GetFFT(fftData)) + if ( FFT::GetFFT( fftData ) ) { Renderer::UpdateR32Texture( texFFT, fftData ); const static float maxIntegralValue = 1024.0f; for ( int i = 0; i < FFT_SIZE; i++ ) { - fftDataSmoothed[i] = fftDataSmoothed[i] * fFFTSmoothingFactor + (1 - fFFTSmoothingFactor) * fftData[i]; + fftDataSmoothed[ i ] = fftDataSmoothed[ i ] * fFFTSmoothingFactor + ( 1 - fFFTSmoothingFactor ) * fftData[ i ]; - fftDataSlightlySmoothed[i] = fftDataSlightlySmoothed[i] * fFFTSlightSmoothingFactor + (1 - fFFTSlightSmoothingFactor) * fftData[i]; - fftDataIntegrated[i] = fftDataIntegrated[i] + fftDataSlightlySmoothed[i]; - if (fftDataIntegrated[i] > maxIntegralValue) { - fftDataIntegrated[i] -= maxIntegralValue; + fftDataSlightlySmoothed[ i ] = fftDataSlightlySmoothed[ i ] * fFFTSlightSmoothingFactor + ( 1 - fFFTSlightSmoothingFactor ) * fftData[ i ]; + fftDataIntegrated[ i ] = fftDataIntegrated[ i ] + fftDataSlightlySmoothed[ i ]; + if ( fftDataIntegrated[ i ] > maxIntegralValue ) + { + fftDataIntegrated[ i ] -= maxIntegralValue; } } @@ -526,7 +532,7 @@ int main( int argc, const char *argv[] ) Renderer::SetShaderTexture( "texFFTIntegrated", texFFTIntegrated ); Renderer::SetShaderTexture( "texPreviousFrame", texPreviousFrame ); - for (std::map::iterator it = textures.begin(); it != textures.end(); it++) + for ( std::map::iterator it = textures.begin(); it != textures.end(); it++ ) { Renderer::SetShaderTexture( it->first.c_str(), it->second ); } @@ -537,9 +543,9 @@ int main( int argc, const char *argv[] ) Renderer::StartTextRendering(); - if (bShowGui) + if ( bShowGui ) { - if (time > fNextTick) + if ( time > fNextTick ) { mShaderEditor.Tick(); mDebugOutput.Tick(); @@ -549,16 +555,16 @@ int main( int argc, const char *argv[] ) mShaderEditor.Paint(); mDebugOutput.Paint(); - Renderer::SetTextRenderingViewport( Scintilla::PRectangle(0,0,Renderer::nWidth,Renderer::nHeight) ); + Renderer::SetTextRenderingViewport( Scintilla::PRectangle( 0, 0, Renderer::nWidth, Renderer::nHeight ) ); - if (bTexPreviewVisible) + if ( bTexPreviewVisible ) { int y1 = nMargin; int x1 = settings.sRenderer.nWidth - nMargin - nTexPreviewWidth; int x2 = settings.sRenderer.nWidth - nMargin; - for (std::map::iterator it = textures.begin(); it != textures.end(); it++) + for ( std::map::iterator it = textures.begin(); it != textures.end(); it++ ) { - int y2 = y1 + nTexPreviewWidth * (it->second->height / (float)it->second->width); + int y2 = y1 + nTexPreviewWidth * ( it->second->height / (float) it->second->width ); Renderer::BindTexture( it->second ); Renderer::RenderQuad( Renderer::Vertex( x1, y1, 0xccFFFFFF, 0.0, 0.0 ), @@ -566,16 +572,16 @@ int main( int argc, const char *argv[] ) Renderer::Vertex( x2, y2, 0xccFFFFFF, 1.0, 1.0 ), Renderer::Vertex( x1, y2, 0xccFFFFFF, 0.0, 1.0 ) ); - surface->DrawTextNoClip( Scintilla::PRectangle(x1,y1,x2,y2), *mShaderEditor.GetTextFont(), y2 - 5.0, it->first.c_str(), (int)it->first.length(), 0xffFFFFFF, 0x00000000); + surface->DrawTextNoClip( Scintilla::PRectangle( x1, y1, x2, y2 ), *mShaderEditor.GetTextFont(), y2 - 5.0, it->first.c_str(), (int) it->first.length(), 0xffFFFFFF, 0x00000000 ); y1 = y2 + nMargin; } } - char szLayout[255]; - Misc::GetKeymapName(szLayout); + char szLayout[ 255 ]; + Misc::GetKeymapName( szLayout ); std::string sHelp = "F2 - toggle texture preview F5 or Ctrl-R - recompile shader F11 - hide GUI Current keymap: "; sHelp += szLayout; - surface->DrawTextNoClip( Scintilla::PRectangle(20,Renderer::nHeight - 20,100,Renderer::nHeight), *mShaderEditor.GetTextFont(), Renderer::nHeight - 5.0, sHelp.c_str(), (int)sHelp.length(), 0x80FFFFFF, 0x00000000); + surface->DrawTextNoClip( Scintilla::PRectangle( 20, Renderer::nHeight - 20, 100, Renderer::nHeight ), *mShaderEditor.GetTextFont(), Renderer::nHeight - 5.0, sHelp.c_str(), (int) sHelp.length(), 0x80FFFFFF, 0x00000000 ); } @@ -585,14 +591,14 @@ int main( int argc, const char *argv[] ) Capture::CaptureFrame(); - if (newShader) + if ( newShader ) { // Frame render successful, save shader - FILE * f = fopen(Renderer::defaultShaderFilename,"wb"); - if (f) + FILE * f = fopen( Renderer::szDefaultShaderFilename, "wb" ); + if ( f ) { - fwrite( szShader, strlen(szShader), 1, f ); - fclose(f); + fwrite( szShader, strlen( szShader ), 1, f ); + fclose( f ); mDebugOutput.SetText( "" ); } else @@ -611,7 +617,7 @@ int main( int argc, const char *argv[] ) Renderer::ReleaseTexture( texPreviousFrame ); Renderer::ReleaseTexture( texFFT ); Renderer::ReleaseTexture( texFFTSmoothed ); - for (std::map::iterator it = textures.begin(); it != textures.end(); it++) + for ( std::map::iterator it = textures.begin(); it != textures.end(); it++ ) { Renderer::ReleaseTexture( it->second ); } @@ -620,7 +626,7 @@ int main( int argc, const char *argv[] ) if ( !sPostExitCmd.empty() ) { - Misc::ExecuteCommand( sPostExitCmd.c_str(), Renderer::defaultShaderFilename ); + Misc::ExecuteCommand( sPostExitCmd.c_str(), Renderer::szDefaultShaderFilename ); } FFT::Destroy(); diff --git a/src/platform_common/FFT.cpp b/src/platform_common/FFT.cpp index 095a0e43..e7888c53 100644 --- a/src/platform_common/FFT.cpp +++ b/src/platform_common/FFT.cpp @@ -9,166 +9,171 @@ namespace FFT { - kiss_fftr_cfg fftcfg; - ma_context context; - ma_device captureDevice; - float sampleBuf[ FFT_SIZE * 2 ]; - float fAmplification = 1.0f; - bool bCreated = false; - - void OnLog( ma_context* pContext, ma_device* pDevice, ma_uint32 logLevel, const char* message ) +////////////////////////////////////////////////////////////////////////// + +kiss_fftr_cfg fftcfg; +ma_context context; +ma_device captureDevice; +float sampleBuf[ FFT_SIZE * 2 ]; +float fAmplification = 1.0f; +bool bCreated = false; + +void OnLog( ma_context * pContext, ma_device * pDevice, ma_uint32 logLevel, const char * message ) +{ + printf( "[FFT] [mal:%p:%p]\n %s", pContext, pDevice, message ); +} + +void OnReceiveFrames( ma_device * pDevice, void * pOutput, const void * pInput, ma_uint32 frameCount ) +{ + frameCount = frameCount < FFT_SIZE * 2 ? frameCount : FFT_SIZE * 2; + + // Just rotate the buffer; copy existing, append new + const float * samples = (const float *) pInput; + float * p = sampleBuf; + for ( int i = 0; i < FFT_SIZE * 2 - frameCount; i++ ) { - printf( "[FFT] [mal:%p:%p]\n %s", pContext, pDevice, message ); + *( p++ ) = sampleBuf[ i + frameCount ]; } - - void OnReceiveFrames( ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount ) + for ( int i = 0; i < frameCount; i++ ) { - frameCount = frameCount < FFT_SIZE * 2 ? frameCount : FFT_SIZE * 2; - - // Just rotate the buffer; copy existing, append new - const float * samples = (const float *)pInput; - float * p = sampleBuf; - for ( int i = 0; i < FFT_SIZE * 2 - frameCount; i++ ) - { - *( p++ ) = sampleBuf[ i + frameCount ]; - } - for ( int i = 0; i < frameCount; i++ ) - { - *( p++ ) = ( samples[ i * 2 ] + samples[ i * 2 + 1 ] ) / 2.0f * fAmplification; - } + *( p++ ) = ( samples[ i * 2 ] + samples[ i * 2 + 1 ] ) / 2.0f * fAmplification; } +} - void EnumerateDevices( FFT_ENUMERATE_FUNC pEnumerationFunction, void * pUserContext ) +void EnumerateDevices( FFT_ENUMERATE_FUNC pEnumerationFunction, void * pUserContext ) +{ + if ( !bCreated ) { - if (!bCreated) - { - return; - } - - ma_device_info * pPlaybackDevices = NULL; - ma_device_info * pCaptureDevices = NULL; - ma_uint32 nPlaybackDeviceCount = 0; - ma_uint32 nCaptureDeviceCount = 0; - ma_result result = ma_context_get_devices(&context, &pPlaybackDevices, &nPlaybackDeviceCount, &pCaptureDevices, &nCaptureDeviceCount); - if (result != MA_SUCCESS) { - printf("[FFT] Failed to enumerate audio devices: %d\n", result); - return; - } - - pEnumerationFunction( true, "", NULL, pUserContext ); - for (ma_uint32 i = 0; i < nCaptureDeviceCount; i++) - { - pEnumerationFunction( true, pCaptureDevices[i].name, &pCaptureDevices[i].id, pUserContext ); - } - if (ma_is_loopback_supported(context.backend)) - { - pEnumerationFunction( false, "", NULL, pUserContext ); - for (ma_uint32 i = 0; i < nPlaybackDeviceCount; i++) - { - pEnumerationFunction( false, pPlaybackDevices[i].name, &pPlaybackDevices[i].id, pUserContext ); - } - } + return; } - bool Create() + ma_device_info * pPlaybackDevices = NULL; + ma_device_info * pCaptureDevices = NULL; + ma_uint32 nPlaybackDeviceCount = 0; + ma_uint32 nCaptureDeviceCount = 0; + ma_result result = ma_context_get_devices( &context, &pPlaybackDevices, &nPlaybackDeviceCount, &pCaptureDevices, &nCaptureDeviceCount ); + if ( result != MA_SUCCESS ) { - bCreated = false; - ma_context_config context_config = ma_context_config_init(); - context_config.logCallback = OnLog; - ma_result result = ma_context_init( NULL, 0, &context_config, &context ); - if ( result != MA_SUCCESS ) - { - printf( "[FFT] Failed to initialize context: %d", result ); - return false; - } - - printf( "[FFT] MAL context initialized, backend is '%s'\n", ma_get_backend_name( context.backend ) ); - bCreated = true; - return true; + printf( "[FFT] Failed to enumerate audio devices: %d\n", result ); + return; } - bool Destroy() + pEnumerationFunction( true, "", NULL, pUserContext ); + for ( ma_uint32 i = 0; i < nCaptureDeviceCount; i++ ) { - if (!bCreated) + pEnumerationFunction( true, pCaptureDevices[ i ].name, &pCaptureDevices[ i ].id, pUserContext ); + } + if ( ma_is_loopback_supported( context.backend ) ) + { + pEnumerationFunction( false, "", NULL, pUserContext ); + for ( ma_uint32 i = 0; i < nPlaybackDeviceCount; i++ ) { - return false; + pEnumerationFunction( false, pPlaybackDevices[ i ].name, &pPlaybackDevices[ i ].id, pUserContext ); } + } +} - ma_context_uninit( &context ); +bool Create() +{ + bCreated = false; + ma_context_config context_config = ma_context_config_init(); + context_config.logCallback = OnLog; + ma_result result = ma_context_init( NULL, 0, &context_config, &context ); + if ( result != MA_SUCCESS ) + { + printf( "[FFT] Failed to initialize context: %d", result ); + return false; + } - bCreated = false; + printf( "[FFT] MAL context initialized, backend is '%s'\n", ma_get_backend_name( context.backend ) ); + bCreated = true; + return true; +} - return true; +bool Destroy() +{ + if ( !bCreated ) + { + return false; } - bool Open( FFT_SETTINGS * pSettings ) - { - if (!bCreated) - { - return false; - } + ma_context_uninit( &context ); - memset( sampleBuf, 0, sizeof( float ) * FFT_SIZE * 2 ); + bCreated = false; - fftcfg = kiss_fftr_alloc( FFT_SIZE * 2, false, NULL, NULL ); + return true; +} - bool useLoopback = ma_is_loopback_supported( context.backend ) && !pSettings->bUseRecordingDevice; - ma_device_config config = ma_device_config_init( useLoopback ? ma_device_type_loopback : ma_device_type_capture ); - config.capture.pDeviceID = (ma_device_id*)pSettings->pDeviceID; - config.capture.format = ma_format_f32; - config.capture.channels = 2; - config.sampleRate = 44100; - config.dataCallback = OnReceiveFrames; - config.pUserData = NULL; +bool Open( FFT::Settings * pSettings ) +{ + if ( !bCreated ) + { + return false; + } - ma_result result = ma_device_init( &context, &config, &captureDevice ); - if ( result != MA_SUCCESS ) - { - printf( "[FFT] Failed to initialize capture device: %d\n", result ); - return false; - } + memset( sampleBuf, 0, sizeof( float ) * FFT_SIZE * 2 ); - printf( "[FFT] Selected capture device: %s\n", captureDevice.capture.name ); + fftcfg = kiss_fftr_alloc( FFT_SIZE * 2, false, NULL, NULL ); - result = ma_device_start( &captureDevice ); - if ( result != MA_SUCCESS ) - { - ma_device_uninit( &captureDevice ); - printf( "[FFT] Failed to start capture device: %d\n", result ); - return false; - } + bool useLoopback = ma_is_loopback_supported( context.backend ) && !pSettings->bUseRecordingDevice; + ma_device_config config = ma_device_config_init( useLoopback ? ma_device_type_loopback : ma_device_type_capture ); + config.capture.pDeviceID = (ma_device_id *) pSettings->pDeviceID; + config.capture.format = ma_format_f32; + config.capture.channels = 2; + config.sampleRate = 44100; + config.dataCallback = OnReceiveFrames; + config.pUserData = NULL; - return true; + ma_result result = ma_device_init( &context, &config, &captureDevice ); + if ( result != MA_SUCCESS ) + { + printf( "[FFT] Failed to initialize capture device: %d\n", result ); + return false; } - bool GetFFT( float * _samples ) + + printf( "[FFT] Selected capture device: %s\n", captureDevice.capture.name ); + + result = ma_device_start( &captureDevice ); + if ( result != MA_SUCCESS ) { - if (!bCreated) - { - return false; - } + ma_device_uninit( &captureDevice ); + printf( "[FFT] Failed to start capture device: %d\n", result ); + return false; + } - kiss_fft_cpx out[ FFT_SIZE + 1 ]; - kiss_fftr( fftcfg, sampleBuf, out ); + return true; +} +bool GetFFT( float * _samples ) +{ + if ( !bCreated ) + { + return false; + } - for ( int i = 0; i < FFT_SIZE; i++ ) - { - static const float scaling = 1.0f / (float)FFT_SIZE; - _samples[ i ] = 2.0 * sqrtf( out[ i ].r * out[ i ].r + out[ i ].i * out[ i ].i ) * scaling; - } + kiss_fft_cpx out[ FFT_SIZE + 1 ]; + kiss_fftr( fftcfg, sampleBuf, out ); - return true; + for ( int i = 0; i < FFT_SIZE; i++ ) + { + static const float scaling = 1.0f / (float) FFT_SIZE; + _samples[ i ] = 2.0 * sqrtf( out[ i ].r * out[ i ].r + out[ i ].i * out[ i ].i ) * scaling; } - void Close() + + return true; +} +void Close() +{ + if ( !bCreated ) { - if (!bCreated) - { - return; - } + return; + } - ma_device_stop( &captureDevice ); + ma_device_stop( &captureDevice ); - ma_device_uninit( &captureDevice ); + ma_device_uninit( &captureDevice ); - kiss_fft_free( fftcfg ); - } + kiss_fft_free( fftcfg ); } + +////////////////////////////////////////////////////////////////////////// +} \ No newline at end of file diff --git a/src/platform_glfw/Renderer.cpp b/src/platform_glfw/Renderer.cpp index b5477a51..e6865db8 100644 --- a/src/platform_glfw/Renderer.cpp +++ b/src/platform_glfw/Renderer.cpp @@ -26,1021 +26,1034 @@ #ifdef __APPLE__ #include "../TouchBar.h" #endif +namespace Renderer +{ +////////////////////////////////////////////////////////////////////////// const char * shaderKeyword = - "discard struct if else switch case default break goto return for while do continue"; +"discard struct if else switch case default break goto return for while do continue"; const char * shaderType = - "attribute const in inout out uniform varying invariant " - "centroid flat smooth noperspective layout patch sample " - "subroutine lowp mediump highp precision " - "void float vec2 vec3 vec4 bvec2 bvec3 bvec4 ivec2 ivec3 ivec4 " - "mat2 mat3 mat4 int bool " - "uvec2 uvec3 uvec4 dvec2 dvec3 dvec4 " - "sampler1D sampler2D sampler3D isampler2D isampler1D isampler3D " - "usampler1D usampler2D usampler3D " - "sampler1DShadow sampler2DShadow sampler1DArray sampler2DArray " - "sampler1DArrayShadow sampler2DArrayShadow " - "samplerCube samplerCubeShadow samplerCubeArrayShadow "; +"attribute const in inout out uniform varying invariant " +"centroid flat smooth noperspective layout patch sample " +"subroutine lowp mediump highp precision " +"void float vec2 vec3 vec4 bvec2 bvec3 bvec4 ivec2 ivec3 ivec4 " +"mat2 mat3 mat4 int bool " +"uvec2 uvec3 uvec4 dvec2 dvec3 dvec4 " +"sampler1D sampler2D sampler3D isampler2D isampler1D isampler3D " +"usampler1D usampler2D usampler3D " +"sampler1DShadow sampler2DShadow sampler1DArray sampler2DArray " +"sampler1DArrayShadow sampler2DArrayShadow " +"samplerCube samplerCubeShadow samplerCubeArrayShadow "; const char * shaderBuiltin = - "radians degrees sin cos tan asin acos atan sinh " - "cosh tanh asinh acosh atanh pow exp log exp2 " - "log2 sqrt inversesqrt abs sign floor trunc round " - "roundEven ceil fract mod modf min max clamp mix " - "step smoothstep isnan isinf floatBitsToInt floatBitsToUint " - "intBitsToFloat uintBitsToFloat fma frexp ldexp packUnorm2x16 " - "packUnorm4x8 packSnorm4x8 unpackUnorm2x16 unpackUnorm4x8 " - "unpackSnorm4x8 packDouble2x32 unpackDouble2x32 length distance " - "dot cross normalize ftransform faceforward reflect " - "refract matrixCompMult outerProduct transpose determinant " - "inverse lessThan lessThanEqual greaterThan greaterThanEqual " - "equal notEqual any all not uaddCarry usubBorrow " - "umulExtended imulExtended bitfieldExtract bitfildInsert " - "bitfieldReverse bitCount findLSB findMSB textureSize " - "textureQueryLOD texture textureProj textureLod textureOffset " - "texelFetch texelFetchOffset textureProjOffset textureLodOffset " - "textureProjLod textureProjLodOffset textureGrad textureGradOffset " - "textureProjGrad textureProjGradOffset textureGather " - "textureGatherOffset texture1D texture2D texture3D texture1DProj " - "texture2DProj texture3DProj texture1DLod texture2DLod " - "texture3DLod texture1DProjLod texture2DProjLod texture3DProjLod " - "textureCube textureCubeLod shadow1D shadow2D shadow1DProj " - "shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod " - "shadow2DProjLod dFdx dFdy fwidth interpolateAtCentroid " - "interpolateAtSample interpolateAtOffset noise1 noise2 noise3 " - "noise4 EmitStreamVertex EndStreamPrimitive EmitVertex " - "EndPrimitive barrier " - "gl_VertexID gl_InstanceID gl_Position gl_PointSize " - "gl_ClipDistance gl_PrimitiveIDIn gl_InvocationID gl_PrimitiveID " - "gl_Layer gl_PatchVerticesIn gl_TessLevelOuter gl_TessLevelInner " - "gl_TessCoord gl_FragCoord gl_FrontFacing gl_PointCoord " - "gl_SampleID gl_SamplePosition gl_FragColor gl_FragData " - "gl_FragDepth gl_SampleMask gl_ClipVertex gl_FrontColor " - "gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " - "gl_TexCoord gl_FogFragCoord gl_Color gl_SecondaryColor " - "gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 " - "gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 " - "gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord " - "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " - "gl_MaxVaryingComponents gl_MaxVertexOutputComponents " - "gl_MaxGeometryInputComponents gl_MaxGeometryOutputComponents " - "gl_MaxFragmentInputComponents gl_MaxVertexTextureImageUnits " - "gl_MaxCombinedTextureImageUnits gl_MaxTextureImageUnits " - "gl_MaxFragmentUniformComponents gl_MaxDrawBuffers gl_MaxClipDistances " - "gl_MaxGeometryTextureImageUnits gl_MaxGeometryOutputVertices " - "gl_MaxGeometryTotalOutputComponents gl_MaxGeometryUniformComponents " - "gl_MaxGeometryVaryingComponents gl_MaxTessControlInputComponents " - "gl_MaxTessControlOutputComponents gl_MaxTessControlTextureImageUnits " - "gl_MaxTessControlUniformComponents " - "gl_MaxTessControlTotalOutputComponents " - "gl_MaxTessEvaluationInputComponents gl_MaxTessEvaluationOutputComponents " - "gl_MaxTessEvaluationTextureImageUnits " - "gl_MaxTessEvaluationUniformComponents gl_MaxTessPatchComponents " - "gl_MaxPatchVertices gl_MaxTessGenLevel gl_MaxTextureUnits " - "gl_MaxTextureCoords gl_MaxClipPlanes " - "gl_DepthRange gl_ModelViewMatrix gl_ProjectionMatrix " - "gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix " - "gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse " - "gl_ModelViewProjectionMatrixInverse gl_TextureMatrixInverse " - "gl_ModelViewMatrixTranspose gl_ProjectionMatrixTranspose " - "gl_ModelViewProjectionMatrixTranspose gl_TextureMatrixTranspose " - "gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose " - "gl_ModelViewProjectionMatrixInverseTranspose " - "gl_TextureMatrixInverseTranspose gl_NormalScale gl_ClipPlane " - "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource " - "gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct " - "gl_FrontLightProduct gl_BackLightProduct gl_TextureEnvColor " - "gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " - "gl_ObjectPlaneS gl_ObjectPlaneT gl_ObjectPlaneR gl_ObjectPlaneQ " - "gl_Fog"; - -namespace Renderer +"radians degrees sin cos tan asin acos atan sinh " +"cosh tanh asinh acosh atanh pow exp log exp2 " +"log2 sqrt inversesqrt abs sign floor trunc round " +"roundEven ceil fract mod modf min max clamp mix " +"step smoothstep isnan isinf floatBitsToInt floatBitsToUint " +"intBitsToFloat uintBitsToFloat fma frexp ldexp packUnorm2x16 " +"packUnorm4x8 packSnorm4x8 unpackUnorm2x16 unpackUnorm4x8 " +"unpackSnorm4x8 packDouble2x32 unpackDouble2x32 length distance " +"dot cross normalize ftransform faceforward reflect " +"refract matrixCompMult outerProduct transpose determinant " +"inverse lessThan lessThanEqual greaterThan greaterThanEqual " +"equal notEqual any all not uaddCarry usubBorrow " +"umulExtended imulExtended bitfieldExtract bitfildInsert " +"bitfieldReverse bitCount findLSB findMSB textureSize " +"textureQueryLOD texture textureProj textureLod textureOffset " +"texelFetch texelFetchOffset textureProjOffset textureLodOffset " +"textureProjLod textureProjLodOffset textureGrad textureGradOffset " +"textureProjGrad textureProjGradOffset textureGather " +"textureGatherOffset texture1D texture2D texture3D texture1DProj " +"texture2DProj texture3DProj texture1DLod texture2DLod " +"texture3DLod texture1DProjLod texture2DProjLod texture3DProjLod " +"textureCube textureCubeLod shadow1D shadow2D shadow1DProj " +"shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod " +"shadow2DProjLod dFdx dFdy fwidth interpolateAtCentroid " +"interpolateAtSample interpolateAtOffset noise1 noise2 noise3 " +"noise4 EmitStreamVertex EndStreamPrimitive EmitVertex " +"EndPrimitive barrier " +"gl_VertexID gl_InstanceID gl_Position gl_PointSize " +"gl_ClipDistance gl_PrimitiveIDIn gl_InvocationID gl_PrimitiveID " +"gl_Layer gl_PatchVerticesIn gl_TessLevelOuter gl_TessLevelInner " +"gl_TessCoord gl_FragCoord gl_FrontFacing gl_PointCoord " +"gl_SampleID gl_SamplePosition gl_FragColor gl_FragData " +"gl_FragDepth gl_SampleMask gl_ClipVertex gl_FrontColor " +"gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +"gl_TexCoord gl_FogFragCoord gl_Color gl_SecondaryColor " +"gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 " +"gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 " +"gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord " +"gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +"gl_MaxVaryingComponents gl_MaxVertexOutputComponents " +"gl_MaxGeometryInputComponents gl_MaxGeometryOutputComponents " +"gl_MaxFragmentInputComponents gl_MaxVertexTextureImageUnits " +"gl_MaxCombinedTextureImageUnits gl_MaxTextureImageUnits " +"gl_MaxFragmentUniformComponents gl_MaxDrawBuffers gl_MaxClipDistances " +"gl_MaxGeometryTextureImageUnits gl_MaxGeometryOutputVertices " +"gl_MaxGeometryTotalOutputComponents gl_MaxGeometryUniformComponents " +"gl_MaxGeometryVaryingComponents gl_MaxTessControlInputComponents " +"gl_MaxTessControlOutputComponents gl_MaxTessControlTextureImageUnits " +"gl_MaxTessControlUniformComponents " +"gl_MaxTessControlTotalOutputComponents " +"gl_MaxTessEvaluationInputComponents gl_MaxTessEvaluationOutputComponents " +"gl_MaxTessEvaluationTextureImageUnits " +"gl_MaxTessEvaluationUniformComponents gl_MaxTessPatchComponents " +"gl_MaxPatchVertices gl_MaxTessGenLevel gl_MaxTextureUnits " +"gl_MaxTextureCoords gl_MaxClipPlanes " +"gl_DepthRange gl_ModelViewMatrix gl_ProjectionMatrix " +"gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix " +"gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse " +"gl_ModelViewProjectionMatrixInverse gl_TextureMatrixInverse " +"gl_ModelViewMatrixTranspose gl_ProjectionMatrixTranspose " +"gl_ModelViewProjectionMatrixTranspose gl_TextureMatrixTranspose " +"gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose " +"gl_ModelViewProjectionMatrixInverseTranspose " +"gl_TextureMatrixInverseTranspose gl_NormalScale gl_ClipPlane " +"gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource " +"gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct " +"gl_FrontLightProduct gl_BackLightProduct gl_TextureEnvColor " +"gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +"gl_ObjectPlaneS gl_ObjectPlaneT gl_ObjectPlaneR gl_ObjectPlaneQ " +"gl_Fog"; + +const char * szDefaultShaderFilename = "shader.glsl"; +const char szDefaultShader[ 65536 ] = +"#version 410 core\n" +"\n" +"uniform float fGlobalTime; // in seconds\n" +"uniform vec2 v2Resolution; // viewport resolution (in pixels)\n" +"uniform float fFrameTime; // duration of the last frame, in seconds\n" +"\n" +"uniform sampler1D texFFT; // towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq\n" +"uniform sampler1D texFFTSmoothed; // this one has longer falloff and less harsh transients\n" +"uniform sampler1D texFFTIntegrated; // this is continually increasing\n" +"uniform sampler2D texPreviousFrame; // screenshot of the previous frame\n" +"{%textures:begin%}" // leave off \n here +"uniform sampler2D {%textures:name%};\n" +"{%textures:end%}" // leave off \n here +"{%midi:begin%}" // leave off \n here +"uniform float {%midi:name%};\n" +"{%midi:end%}" // leave off \n here +"\n" +"in vec2 out_texcoord;\n" +"layout(location = 0) out vec4 out_color; // out_color must be written in order to see anything\n" +"\n" +"vec4 plas( vec2 v, float time )\n" +"{\n" +"\tfloat c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );\n" +"\treturn vec4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );\n" +"}\n" +"\n" +"void main(void)\n" +"{\n" +"\tvec2 uv = out_texcoord;\n" +"\tuv -= 0.5;\n" +"\tuv /= vec2(v2Resolution.y / v2Resolution.x, 1);\n" +"\n" +"\tvec2 m;\n" +"\tm.x = atan(uv.x / uv.y) / 3.14;\n" +"\tm.y = 1 / length(uv) * .2;\n" +"\tfloat d = m.y;\n" +"\n" +"\tfloat f = texture( texFFT, d ).r * 100;\n" +"\tm.x += sin( fGlobalTime ) * 0.1;\n" +"\tm.y += fGlobalTime * 0.25;\n" +"\n" +"\tvec4 t = plas( m * 3.14, fGlobalTime ) / d;\n" +"\tt = clamp( t, 0.0, 1.0 );\n" +"\tout_color = f + t;\n" +"}"; + +GLFWwindow * mWindow = NULL; +bool run = true; + +GLuint theShader = 0; +GLuint glhVertexShader = 0; +GLuint glhFullscreenQuadVB = 0; +GLuint glhFullscreenQuadVA = 0; +GLuint glhGUIVB = 0; +GLuint glhGUIVA = 0; +GLuint glhGUIProgram = 0; + +int nWidth = 0; +int nHeight = 0; + +void MatrixOrthoOffCenterLH( float * pout, float l, float r, float b, float t, float zn, float zf ) { - const char * defaultShaderFilename = "shader.glsl"; - const char defaultShader[65536] = - "#version 410 core\n" - "\n" - "uniform float fGlobalTime; // in seconds\n" - "uniform vec2 v2Resolution; // viewport resolution (in pixels)\n" - "uniform float fFrameTime; // duration of the last frame, in seconds\n" - "\n" - "uniform sampler1D texFFT; // towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq\n" - "uniform sampler1D texFFTSmoothed; // this one has longer falloff and less harsh transients\n" - "uniform sampler1D texFFTIntegrated; // this is continually increasing\n" - "uniform sampler2D texPreviousFrame; // screenshot of the previous frame\n" - "{%textures:begin%}" // leave off \n here - "uniform sampler2D {%textures:name%};\n" - "{%textures:end%}" // leave off \n here - "{%midi:begin%}" // leave off \n here - "uniform float {%midi:name%};\n" - "{%midi:end%}" // leave off \n here - "\n" - "in vec2 out_texcoord;\n" - "layout(location = 0) out vec4 out_color; // out_color must be written in order to see anything\n" - "\n" - "vec4 plas( vec2 v, float time )\n" - "{\n" - "\tfloat c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );\n" - "\treturn vec4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );\n" - "}\n" - "\n" - "void main(void)\n" - "{\n" - "\tvec2 uv = out_texcoord;\n" - "\tuv -= 0.5;\n" - "\tuv /= vec2(v2Resolution.y / v2Resolution.x, 1);\n" - "\n" - "\tvec2 m;\n" - "\tm.x = atan(uv.x / uv.y) / 3.14;\n" - "\tm.y = 1 / length(uv) * .2;\n" - "\tfloat d = m.y;\n" - "\n" - "\tfloat f = texture( texFFT, d ).r * 100;\n" - "\tm.x += sin( fGlobalTime ) * 0.1;\n" - "\tm.y += fGlobalTime * 0.25;\n" - "\n" - "\tvec4 t = plas( m * 3.14, fGlobalTime ) / d;\n" - "\tt = clamp( t, 0.0, 1.0 );\n" - "\tout_color = f + t;\n" - "}"; - - GLFWwindow * mWindow = NULL; - bool run = true; - - GLuint theShader = 0; - GLuint glhVertexShader = 0; - GLuint glhFullscreenQuadVB = 0; - GLuint glhFullscreenQuadVA = 0; - GLuint glhGUIVB = 0; - GLuint glhGUIVA = 0; - GLuint glhGUIProgram = 0; + memset( pout, 0, sizeof( float ) * 4 * 4 ); + pout[ 0 + 0 * 4 ] = 2.0f / ( r - l ); + pout[ 1 + 1 * 4 ] = 2.0f / ( t - b ); + pout[ 2 + 2 * 4 ] = 1.0f / ( zf - zn ); + pout[ 3 + 0 * 4 ] = -1.0f - 2.0f * l / ( r - l ); + pout[ 3 + 1 * 4 ] = 1.0f + 2.0f * t / ( b - t ); + pout[ 3 + 2 * 4 ] = zn / ( zn - zf ); + pout[ 3 + 3 * 4 ] = 1.0; +} - int nWidth = 0; - int nHeight = 0; +int readIndex = 0; +int writeIndex = 1; +GLuint pbo[ 2 ]; - void MatrixOrthoOffCenterLH(float * pout, float l, float r, float b, float t, float zn, float zf) +static void error_callback( int error, const char * description ) +{ + switch ( error ) { - memset( pout, 0, sizeof(float) * 4 * 4 ); - pout[0 + 0 * 4] = 2.0f / (r - l); - pout[1 + 1 * 4] = 2.0f / (t - b); - pout[2 + 2 * 4] = 1.0f / (zf -zn); - pout[3 + 0 * 4] = -1.0f -2.0f *l / (r - l); - pout[3 + 1 * 4] = 1.0f + 2.0f * t / (b - t); - pout[3 + 2 * 4] = zn / (zn -zf); - pout[3 + 3 * 4] = 1.0; - } - - int readIndex = 0; - int writeIndex = 1; - GLuint pbo[2]; - - static void error_callback(int error, const char *description) { - switch (error) { case GLFW_API_UNAVAILABLE: - printf("OpenGL is unavailable: "); + printf( "OpenGL is unavailable: " ); break; case GLFW_VERSION_UNAVAILABLE: - printf("OpenGL 4.1 (the minimum requirement) is not available: "); + printf( "OpenGL 4.1 (the minimum requirement) is not available: " ); break; - } - printf("%s\n", description); } - void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); - void character_callback(GLFWwindow* window, unsigned int codepoint); - void cursor_position_callback(GLFWwindow* window, double xpos, double ypos); - void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); - void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); + printf( "%s\n", description ); +} +void key_callback( GLFWwindow * window, int key, int scancode, int action, int mods ); +void character_callback( GLFWwindow * window, unsigned int codepoint ); +void cursor_position_callback( GLFWwindow * window, double xpos, double ypos ); +void mouse_button_callback( GLFWwindow * window, int button, int action, int mods ); +void scroll_callback( GLFWwindow * window, double xoffset, double yoffset ); + +bool Open( Renderer::Settings * settings ) +{ + glfwSetErrorCallback( error_callback ); + theShader = 0; - bool Open( RENDERER_SETTINGS * settings ) - { - glfwSetErrorCallback(error_callback); - theShader = 0; - #ifdef __APPLE__ - glfwInitHint(GLFW_COCOA_CHDIR_RESOURCES, GLFW_FALSE); + glfwInitHint( GLFW_COCOA_CHDIR_RESOURCES, GLFW_FALSE ); #endif - if(!glfwInit()) - { - printf("[Renderer] GLFW init failed\n"); - return false; - } - printf("[GLFW] Version String: %s\n", glfwGetVersionString()); + if ( !glfwInit() ) + { + printf( "[Renderer] GLFW init failed\n" ); + return false; + } + printf( "[GLFW] Version String: %s\n", glfwGetVersionString() ); - nWidth = settings->nWidth; - nHeight = settings->nHeight; + nWidth = settings->nWidth; + nHeight = settings->nHeight; - glfwWindowHint(GLFW_RED_BITS, 8); - glfwWindowHint(GLFW_GREEN_BITS, 8); - glfwWindowHint(GLFW_BLUE_BITS, 8); - glfwWindowHint(GLFW_ALPHA_BITS, 8); - glfwWindowHint(GLFW_DEPTH_BITS, 24); - glfwWindowHint(GLFW_STENCIL_BITS, 8); + glfwWindowHint( GLFW_RED_BITS, 8 ); + glfwWindowHint( GLFW_GREEN_BITS, 8 ); + glfwWindowHint( GLFW_BLUE_BITS, 8 ); + glfwWindowHint( GLFW_ALPHA_BITS, 8 ); + glfwWindowHint( GLFW_DEPTH_BITS, 24 ); + glfwWindowHint( GLFW_STENCIL_BITS, 8 ); - glfwWindowHint(GLFW_DOUBLEBUFFER, GLFW_TRUE); + glfwWindowHint( GLFW_DOUBLEBUFFER, GLFW_TRUE ); - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 ); + glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 1 ); + glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE ); + glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); #ifdef __APPLE__ - glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE); - glfwWindowHint(GLFW_COCOA_GRAPHICS_SWITCHING, GLFW_FALSE); + glfwWindowHint( GLFW_COCOA_RETINA_FRAMEBUFFER, GLFW_FALSE ); + glfwWindowHint( GLFW_COCOA_GRAPHICS_SWITCHING, GLFW_FALSE ); #endif - // TODO: change in case of resize support - glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); + // TODO: change in case of resize support + glfwWindowHint( GLFW_RESIZABLE, GLFW_FALSE ); - // Prevent fullscreen window minimize on focus loss - glfwWindowHint(GLFW_AUTO_ICONIFY, GL_FALSE); + // Prevent fullscreen window minimize on focus loss + glfwWindowHint( GLFW_AUTO_ICONIFY, GL_FALSE ); - GLFWmonitor *monitor = settings->windowMode == RENDERER_WINDOWMODE_FULLSCREEN ? glfwGetPrimaryMonitor() : NULL; + GLFWmonitor * monitor = settings->windowMode == WINDOWMODE_FULLSCREEN ? glfwGetPrimaryMonitor() : NULL; - mWindow = glfwCreateWindow(nWidth, nHeight, "BONZOMATIC - GLFW edition", monitor, NULL); - if (!mWindow) - { - printf("[GLFW] Window creation failed\n"); - glfwTerminate(); - return false; - } + mWindow = glfwCreateWindow( nWidth, nHeight, "BONZOMATIC - GLFW edition", monitor, NULL ); + if ( !mWindow ) + { + printf( "[GLFW] Window creation failed\n" ); + glfwTerminate(); + return false; + } #ifdef __APPLE__ #ifdef BONZOMATIC_ENABLE_TOUCHBAR - ShowTouchBar(mWindow); + ShowTouchBar( mWindow ); #endif #endif - - glfwMakeContextCurrent(mWindow); - - // TODO: here add text callbacks - glfwSetKeyCallback(mWindow, key_callback); - glfwSetCharCallback(mWindow, character_callback); - glfwSetCursorPosCallback(mWindow, cursor_position_callback); - glfwSetMouseButtonCallback(mWindow, mouse_button_callback); - glfwSetScrollCallback(mWindow, scroll_callback); - - glewExperimental = GL_TRUE; - GLenum err = glewInit(); - if (GLEW_OK != err) - { - printf("[GLFW] glewInit failed: %s\n", glewGetErrorString(err)); - glfwTerminate(); - return false; - } - printf("[GLFW] Using GLEW %s\n", glewGetString(GLEW_VERSION)); - glGetError(); // reset glew error - glfwSwapInterval(1); + glfwMakeContextCurrent( mWindow ); + + // TODO: here add text callbacks + glfwSetKeyCallback( mWindow, key_callback ); + glfwSetCharCallback( mWindow, character_callback ); + glfwSetCursorPosCallback( mWindow, cursor_position_callback ); + glfwSetMouseButtonCallback( mWindow, mouse_button_callback ); + glfwSetScrollCallback( mWindow, scroll_callback ); + + glewExperimental = GL_TRUE; + GLenum err = glewInit(); + if ( GLEW_OK != err ) + { + printf( "[GLFW] glewInit failed: %s\n", glewGetErrorString( err ) ); + glfwTerminate(); + return false; + } + printf( "[GLFW] Using GLEW %s\n", glewGetString( GLEW_VERSION ) ); + glGetError(); // reset glew error + + glfwSwapInterval( 1 ); #ifdef _WIN32 - if (settings->bVsync) - wglSwapIntervalEXT(1); + if ( settings->bVsync ) + wglSwapIntervalEXT( 1 ); #endif - printf("[GLFW] OpenGL Version %s, GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); - - // Now, since OpenGL is behaving a lot in fullscreen modes, lets collect the real obtained size! - printf("[GLFW] Requested framebuffer size: %d x %d\n", nWidth, nHeight); - int fbWidth = 1; - int fbHeight = 1; - glfwGetFramebufferSize(mWindow, &fbWidth, &fbHeight); - nWidth = settings->nWidth = fbWidth; - nHeight = settings->nHeight = fbHeight; - printf("[GLFW] Obtained framebuffer size: %d x %d\n", fbWidth, fbHeight); - - static float pFullscreenQuadVertices[] = - { - -1.0, -1.0, 0.5, 0.0, 0.0, - -1.0, 1.0, 0.5, 0.0, 1.0, - 1.0, -1.0, 0.5, 1.0, 0.0, - 1.0, 1.0, 0.5, 1.0, 1.0, - }; - - glGenBuffers( 1, &glhFullscreenQuadVB ); - glBindBuffer( GL_ARRAY_BUFFER, glhFullscreenQuadVB ); - glBufferData( GL_ARRAY_BUFFER, sizeof(float) * 5 * 4, pFullscreenQuadVertices, GL_STATIC_DRAW ); - glBindBuffer( GL_ARRAY_BUFFER, 0 ); - - glGenVertexArrays(1, &glhFullscreenQuadVA); - - glhVertexShader = glCreateShader( GL_VERTEX_SHADER ); - - const char * szVertexShader = - "#version 410 core\n" - "in vec3 in_pos;\n" - "in vec2 in_texcoord;\n" - "out vec2 out_texcoord;\n" - "void main()\n" - "{\n" - " gl_Position = vec4( in_pos.x, in_pos.y, in_pos.z, 1.0 );\n" - " out_texcoord = in_texcoord;\n" - "}"; - GLint nShaderSize = (GLint)strlen(szVertexShader); - - glShaderSource(glhVertexShader, 1, (const GLchar**)&szVertexShader, &nShaderSize); - glCompileShader(glhVertexShader); - - GLint size = 0; - GLint result = 0; - char szErrorBuffer[5000]; - glGetShaderInfoLog(glhVertexShader, 4000, &size, szErrorBuffer); - glGetShaderiv(glhVertexShader, GL_COMPILE_STATUS, &result); - if (!result) - { - printf("[Renderer] Vertex shader compilation failed\n%s\n", szErrorBuffer); - return false; - } + printf( "[GLFW] OpenGL Version %s, GLSL %s\n", glGetString( GL_VERSION ), glGetString( GL_SHADING_LANGUAGE_VERSION ) ); -#define GUIQUADVB_SIZE (1024 * 6) + // Now, since OpenGL is behaving a lot in fullscreen modes, lets collect the real obtained size! + printf( "[GLFW] Requested framebuffer size: %d x %d\n", nWidth, nHeight ); + int fbWidth = 1; + int fbHeight = 1; + glfwGetFramebufferSize( mWindow, &fbWidth, &fbHeight ); + nWidth = settings->nWidth = fbWidth; + nHeight = settings->nHeight = fbHeight; + printf( "[GLFW] Obtained framebuffer size: %d x %d\n", fbWidth, fbHeight ); - const char * defaultGUIVertexShader = - "#version 410 core\n" - "in vec3 in_pos;\n" - "in vec4 in_color;\n" - "in vec2 in_texcoord;\n" - "in float in_factor;\n" - "out vec4 out_color;\n" - "out vec2 out_texcoord;\n" - "out float out_factor;\n" - "uniform vec2 v2Offset;\n" - "uniform mat4 matProj;\n" - "void main()\n" - "{\n" - " vec4 pos = vec4( in_pos + vec3(v2Offset,0), 1.0 );\n" - " gl_Position = pos * matProj;\n" - " out_color = in_color;\n" - " out_texcoord = in_texcoord;\n" - " out_factor = in_factor;\n" - "}\n"; - const char * defaultGUIPixelShader = - "#version 410 core\n" - "uniform sampler2D tex;\n" - "in vec4 out_color;\n" - "in vec2 out_texcoord;\n" - "in float out_factor;\n" - "out vec4 frag_color;\n" - "void main()\n" - "{\n" - " vec4 v4Texture = out_color * texture( tex, out_texcoord );\n" - " vec4 v4Color = out_color;\n" - " frag_color = mix( v4Texture, v4Color, out_factor );\n" - "}\n"; - - glhGUIProgram = glCreateProgram(); - - GLuint vshd = glCreateShader(GL_VERTEX_SHADER); - nShaderSize = (GLint)strlen(defaultGUIVertexShader); - - glShaderSource(vshd, 1, (const GLchar**)&defaultGUIVertexShader, &nShaderSize); - glCompileShader(vshd); - glGetShaderInfoLog(vshd, 4000, &size, szErrorBuffer); - glGetShaderiv(vshd, GL_COMPILE_STATUS, &result); - if (!result) - { - printf("[Renderer] Default GUI vertex shader compilation failed\n"); - return false; - } + static float pFullscreenQuadVertices[] = + { + -1.0, -1.0, 0.5, 0.0, 0.0, + -1.0, 1.0, 0.5, 0.0, 1.0, + 1.0, -1.0, 0.5, 1.0, 0.0, + 1.0, 1.0, 0.5, 1.0, 1.0, + }; - GLuint fshd = glCreateShader(GL_FRAGMENT_SHADER); - nShaderSize = (GLint)strlen(defaultGUIPixelShader); + glGenBuffers( 1, &glhFullscreenQuadVB ); + glBindBuffer( GL_ARRAY_BUFFER, glhFullscreenQuadVB ); + glBufferData( GL_ARRAY_BUFFER, sizeof( float ) * 5 * 4, pFullscreenQuadVertices, GL_STATIC_DRAW ); + glBindBuffer( GL_ARRAY_BUFFER, 0 ); - glShaderSource(fshd, 1, (const GLchar**)&defaultGUIPixelShader, &nShaderSize); - glCompileShader(fshd); - glGetShaderInfoLog(fshd, 4000, &size, szErrorBuffer); - glGetShaderiv(fshd, GL_COMPILE_STATUS, &result); - if (!result) - { - printf("[Renderer] Default GUI pixel shader compilation failed\n"); - return false; - } + glGenVertexArrays( 1, &glhFullscreenQuadVA ); - glAttachShader(glhGUIProgram, vshd); - glAttachShader(glhGUIProgram, fshd); - glLinkProgram(glhGUIProgram); - glGetProgramiv(glhGUIProgram, GL_LINK_STATUS, &result); - if (!result) - { - return false; - } + glhVertexShader = glCreateShader( GL_VERTEX_SHADER ); - glGenBuffers( 1, &glhGUIVB ); - glBindBuffer( GL_ARRAY_BUFFER, glhGUIVB ); + const char * szVertexShader = + "#version 410 core\n" + "in vec3 in_pos;\n" + "in vec2 in_texcoord;\n" + "out vec2 out_texcoord;\n" + "void main()\n" + "{\n" + " gl_Position = vec4( in_pos.x, in_pos.y, in_pos.z, 1.0 );\n" + " out_texcoord = in_texcoord;\n" + "}"; + GLint nShaderSize = (GLint) strlen( szVertexShader ); - glGenVertexArrays(1, &glhGUIVA); + glShaderSource( glhVertexShader, 1, (const GLchar **) &szVertexShader, &nShaderSize ); + glCompileShader( glhVertexShader ); - //create PBOs to hold the data. this allocates memory for them too - glGenBuffers(2, pbo); - glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[0]); - glBufferData(GL_PIXEL_PACK_BUFFER, nWidth * nHeight * sizeof(unsigned int), NULL, GL_STREAM_READ); - glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[1]); - glBufferData(GL_PIXEL_PACK_BUFFER, nWidth * nHeight * sizeof(unsigned int), NULL, GL_STREAM_READ); - //unbind buffers for now - glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); + GLint size = 0; + GLint result = 0; + char szErrorBuffer[ 5000 ]; + glGetShaderInfoLog( glhVertexShader, 4000, &size, szErrorBuffer ); + glGetShaderiv( glhVertexShader, GL_COMPILE_STATUS, &result ); + if ( !result ) + { + printf( "[Renderer] Vertex shader compilation failed\n%s\n", szErrorBuffer ); + return false; + } - glViewport(0, 0, nWidth, nHeight); - - run = true; +#define GUIQUADVB_SIZE (1024 * 6) - return true; - } + const char * defaultGUIVertexShader = + "#version 410 core\n" + "in vec3 in_pos;\n" + "in vec4 in_color;\n" + "in vec2 in_texcoord;\n" + "in float in_factor;\n" + "out vec4 out_color;\n" + "out vec2 out_texcoord;\n" + "out float out_factor;\n" + "uniform vec2 v2Offset;\n" + "uniform mat4 matProj;\n" + "void main()\n" + "{\n" + " vec4 pos = vec4( in_pos + vec3(v2Offset,0), 1.0 );\n" + " gl_Position = pos * matProj;\n" + " out_color = in_color;\n" + " out_texcoord = in_texcoord;\n" + " out_factor = in_factor;\n" + "}\n"; + const char * defaultGUIPixelShader = + "#version 410 core\n" + "uniform sampler2D tex;\n" + "in vec4 out_color;\n" + "in vec2 out_texcoord;\n" + "in float out_factor;\n" + "out vec4 frag_color;\n" + "void main()\n" + "{\n" + " vec4 v4Texture = out_color * texture( tex, out_texcoord );\n" + " vec4 v4Color = out_color;\n" + " frag_color = mix( v4Texture, v4Color, out_factor );\n" + "}\n"; + + glhGUIProgram = glCreateProgram(); - KeyEvent keyEventBuffer[512]; - int keyEventBufferCount = 0; - MouseEvent mouseEventBuffer[512]; - int mouseEventBufferCount = 0; - void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) + GLuint vshd = glCreateShader( GL_VERTEX_SHADER ); + nShaderSize = (GLint) strlen( defaultGUIVertexShader ); + + glShaderSource( vshd, 1, (const GLchar **) &defaultGUIVertexShader, &nShaderSize ); + glCompileShader( vshd ); + glGetShaderInfoLog( vshd, 4000, &size, szErrorBuffer ); + glGetShaderiv( vshd, GL_COMPILE_STATUS, &result ); + if ( !result ) { - if (action == GLFW_PRESS || action == GLFW_REPEAT) { - if ((key==GLFW_KEY_F4 && (mods&GLFW_MOD_ALT)) || (key==GLFW_KEY_ESCAPE&&(mods&GLFW_MOD_SHIFT))) { - run = false; - } - int sciKey = 0; - bool bNormalKey = false; - switch (key) { - case GLFW_KEY_DOWN: sciKey = SCK_DOWN; break; - case GLFW_KEY_UP: sciKey = SCK_UP; break; - case GLFW_KEY_LEFT: sciKey = SCK_LEFT; break; - case GLFW_KEY_RIGHT: sciKey = SCK_RIGHT; break; - case GLFW_KEY_HOME: sciKey = SCK_HOME; break; - case GLFW_KEY_END: sciKey = SCK_END; break; - case GLFW_KEY_PAGE_UP: sciKey = SCK_PRIOR; break; - case GLFW_KEY_PAGE_DOWN: sciKey = SCK_NEXT; break; - case GLFW_KEY_DELETE: sciKey = SCK_DELETE; break; - case GLFW_KEY_INSERT: sciKey = SCK_INSERT; break; - case GLFW_KEY_ESCAPE: sciKey = SCK_ESCAPE; break; - case GLFW_KEY_BACKSPACE: sciKey = SCK_BACK; break; - case GLFW_KEY_TAB: sciKey = SCK_TAB; break; - case GLFW_KEY_ENTER: sciKey = SCK_RETURN; break; - case GLFW_KEY_KP_ADD: sciKey = SCK_ADD; break; - case GLFW_KEY_KP_SUBTRACT: sciKey = SCK_SUBTRACT; break; - case GLFW_KEY_KP_DIVIDE: sciKey = SCK_DIVIDE; break; -// case GLFW_KEY_LSUPER: sciKey = SCK_WIN; break; -// case GLFW_KEY_RSUPER: sciKey = SCK_RWIN; break; - case GLFW_KEY_MENU: sciKey = SCK_MENU; break; -// case GLFW_KEY_SLASH: sciKey = '/'; break; -// case GLFW_KEY_ASTERISK: sciKey = '`'; break; -// case GLFW_KEY_LEFTBRACKET: sciKey = '['; break; -// case GLFW_KEY_BACKSLASH: sciKey = '\\'; break; -// case GLFW_KEY_RIGHTBRACKET: sciKey = ']'; break; - case GLFW_KEY_F1: sciKey = 282; break; - case GLFW_KEY_F2: sciKey = 283; break; - case GLFW_KEY_F3: sciKey = 284; break; - case GLFW_KEY_F4: sciKey = 285; break; - case GLFW_KEY_F5: sciKey = 286; break; - case GLFW_KEY_F6: sciKey = 287; break; - case GLFW_KEY_F7: sciKey = 288; break; - case GLFW_KEY_F8: sciKey = 289; break; - case GLFW_KEY_F9: sciKey = 290; break; - case GLFW_KEY_F10: sciKey = 291; break; - case GLFW_KEY_F11: sciKey = 292; break; - case GLFW_KEY_F12: sciKey = 293; break; - case GLFW_KEY_LEFT_SHIFT: - case GLFW_KEY_RIGHT_SHIFT: - case GLFW_KEY_LEFT_ALT: - case GLFW_KEY_RIGHT_ALT: - case GLFW_KEY_LEFT_CONTROL: - case GLFW_KEY_RIGHT_CONTROL: - case GLFW_KEY_LEFT_SUPER: - case GLFW_KEY_RIGHT_SUPER: - sciKey = 0; - break; - default: - bNormalKey = true; - // TODO: Horrible hack to migrate from GLFW (that uses ascii maj for keys) to scintilla min keys - if ( (key >= GLFW_KEY_A) && (key <= GLFW_KEY_Z) ) { - sciKey = key+32; - } - else { - sciKey = 0; - } - } - if ((bNormalKey && mods) || !bNormalKey) - { - keyEventBuffer[keyEventBufferCount].ctrl = (mods & GLFW_MOD_CONTROL) || (mods & GLFW_MOD_SUPER); - keyEventBuffer[keyEventBufferCount].alt = mods & GLFW_MOD_ALT; - keyEventBuffer[keyEventBufferCount].shift = mods & GLFW_MOD_SHIFT; - keyEventBuffer[keyEventBufferCount].scanCode = sciKey; - keyEventBuffer[keyEventBufferCount].character = 0; - keyEventBufferCount++; - } - } + printf( "[Renderer] Default GUI vertex shader compilation failed\n" ); + return false; } - void character_callback(GLFWwindow* window, unsigned int codepoint) + + GLuint fshd = glCreateShader( GL_FRAGMENT_SHADER ); + nShaderSize = (GLint) strlen( defaultGUIPixelShader ); + + glShaderSource( fshd, 1, (const GLchar **) &defaultGUIPixelShader, &nShaderSize ); + glCompileShader( fshd ); + glGetShaderInfoLog( fshd, 4000, &size, szErrorBuffer ); + glGetShaderiv( fshd, GL_COMPILE_STATUS, &result ); + if ( !result ) { - keyEventBuffer[keyEventBufferCount].ctrl = false; - keyEventBuffer[keyEventBufferCount].alt = false; - keyEventBuffer[keyEventBufferCount].shift = false; - keyEventBuffer[keyEventBufferCount].scanCode = 0; - // TODO: handle special things with Scintilla for UFT8 codepoints? - keyEventBuffer[keyEventBufferCount].character = codepoint; - keyEventBufferCount++; + printf( "[Renderer] Default GUI pixel shader compilation failed\n" ); + return false; } - void cursor_position_callback(GLFWwindow* window, double xpos, double ypos) + + glAttachShader( glhGUIProgram, vshd ); + glAttachShader( glhGUIProgram, fshd ); + glLinkProgram( glhGUIProgram ); + glGetProgramiv( glhGUIProgram, GL_LINK_STATUS, &result ); + if ( !result ) { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_MOVE; - mouseEventBuffer[mouseEventBufferCount].x = xpos; - mouseEventBuffer[mouseEventBufferCount].y = ypos; - if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT; - mouseEventBufferCount++; + return false; } - void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) + + glGenBuffers( 1, &glhGUIVB ); + glBindBuffer( GL_ARRAY_BUFFER, glhGUIVB ); + + glGenVertexArrays( 1, &glhGUIVA ); + + //create PBOs to hold the data. this allocates memory for them too + glGenBuffers( 2, pbo ); + glBindBuffer( GL_PIXEL_PACK_BUFFER, pbo[ 0 ] ); + glBufferData( GL_PIXEL_PACK_BUFFER, nWidth * nHeight * sizeof( unsigned int ), NULL, GL_STREAM_READ ); + glBindBuffer( GL_PIXEL_PACK_BUFFER, pbo[ 1 ] ); + glBufferData( GL_PIXEL_PACK_BUFFER, nWidth * nHeight * sizeof( unsigned int ), NULL, GL_STREAM_READ ); + //unbind buffers for now + glBindBuffer( GL_PIXEL_PACK_BUFFER, 0 ); + + glViewport( 0, 0, nWidth, nHeight ); + + run = true; + + return true; +} + +KeyEvent keyEventBuffer[ 512 ]; +int keyEventBufferCount = 0; +MouseEvent mouseEventBuffer[ 512 ]; +int mouseEventBufferCount = 0; +void key_callback( GLFWwindow * window, int key, int scancode, int action, int mods ) +{ + if ( action == GLFW_PRESS || action == GLFW_REPEAT ) { - if (action == GLFW_PRESS) { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_DOWN; + if ( ( key == GLFW_KEY_F4 && ( mods & GLFW_MOD_ALT ) ) || ( key == GLFW_KEY_ESCAPE && ( mods & GLFW_MOD_SHIFT ) ) ) + { + run = false; } - else if (action == GLFW_RELEASE) { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_UP; + int sciKey = 0; + bool bNormalKey = false; + switch ( key ) + { + case GLFW_KEY_DOWN: sciKey = SCK_DOWN; break; + case GLFW_KEY_UP: sciKey = SCK_UP; break; + case GLFW_KEY_LEFT: sciKey = SCK_LEFT; break; + case GLFW_KEY_RIGHT: sciKey = SCK_RIGHT; break; + case GLFW_KEY_HOME: sciKey = SCK_HOME; break; + case GLFW_KEY_END: sciKey = SCK_END; break; + case GLFW_KEY_PAGE_UP: sciKey = SCK_PRIOR; break; + case GLFW_KEY_PAGE_DOWN: sciKey = SCK_NEXT; break; + case GLFW_KEY_DELETE: sciKey = SCK_DELETE; break; + case GLFW_KEY_INSERT: sciKey = SCK_INSERT; break; + case GLFW_KEY_ESCAPE: sciKey = SCK_ESCAPE; break; + case GLFW_KEY_BACKSPACE: sciKey = SCK_BACK; break; + case GLFW_KEY_TAB: sciKey = SCK_TAB; break; + case GLFW_KEY_ENTER: sciKey = SCK_RETURN; break; + case GLFW_KEY_KP_ADD: sciKey = SCK_ADD; break; + case GLFW_KEY_KP_SUBTRACT: sciKey = SCK_SUBTRACT; break; + case GLFW_KEY_KP_DIVIDE: sciKey = SCK_DIVIDE; break; + // case GLFW_KEY_LSUPER: sciKey = SCK_WIN; break; + // case GLFW_KEY_RSUPER: sciKey = SCK_RWIN; break; + case GLFW_KEY_MENU: sciKey = SCK_MENU; break; + // case GLFW_KEY_SLASH: sciKey = '/'; break; + // case GLFW_KEY_ASTERISK: sciKey = '`'; break; + // case GLFW_KEY_LEFTBRACKET: sciKey = '['; break; + // case GLFW_KEY_BACKSLASH: sciKey = '\\'; break; + // case GLFW_KEY_RIGHTBRACKET: sciKey = ']'; break; + case GLFW_KEY_F1: sciKey = 282; break; + case GLFW_KEY_F2: sciKey = 283; break; + case GLFW_KEY_F3: sciKey = 284; break; + case GLFW_KEY_F4: sciKey = 285; break; + case GLFW_KEY_F5: sciKey = 286; break; + case GLFW_KEY_F6: sciKey = 287; break; + case GLFW_KEY_F7: sciKey = 288; break; + case GLFW_KEY_F8: sciKey = 289; break; + case GLFW_KEY_F9: sciKey = 290; break; + case GLFW_KEY_F10: sciKey = 291; break; + case GLFW_KEY_F11: sciKey = 292; break; + case GLFW_KEY_F12: sciKey = 293; break; + case GLFW_KEY_LEFT_SHIFT: + case GLFW_KEY_RIGHT_SHIFT: + case GLFW_KEY_LEFT_ALT: + case GLFW_KEY_RIGHT_ALT: + case GLFW_KEY_LEFT_CONTROL: + case GLFW_KEY_RIGHT_CONTROL: + case GLFW_KEY_LEFT_SUPER: + case GLFW_KEY_RIGHT_SUPER: + sciKey = 0; + break; + default: + bNormalKey = true; + // TODO: Horrible hack to migrate from GLFW (that uses ascii maj for keys) to scintilla min keys + if ( ( key >= GLFW_KEY_A ) && ( key <= GLFW_KEY_Z ) ) + { + sciKey = key + 32; + } + else { + sciKey = 0; + } } - double xpos, ypos; - glfwGetCursorPos(window, &xpos, &ypos); - mouseEventBuffer[mouseEventBufferCount].x = xpos; - mouseEventBuffer[mouseEventBufferCount].y = ypos; - switch(button) + if ( ( bNormalKey && mods ) || !bNormalKey ) { - case GLFW_MOUSE_BUTTON_MIDDLE: mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_MIDDLE; break; - case GLFW_MOUSE_BUTTON_RIGHT: mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_RIGHT; break; - case GLFW_MOUSE_BUTTON_LEFT: - default: mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT; break; + keyEventBuffer[ keyEventBufferCount ].ctrl = ( mods & GLFW_MOD_CONTROL ) || ( mods & GLFW_MOD_SUPER ); + keyEventBuffer[ keyEventBufferCount ].alt = mods & GLFW_MOD_ALT; + keyEventBuffer[ keyEventBufferCount ].shift = mods & GLFW_MOD_SHIFT; + keyEventBuffer[ keyEventBufferCount ].scanCode = sciKey; + keyEventBuffer[ keyEventBufferCount ].character = 0; + keyEventBufferCount++; } - mouseEventBufferCount++; - } - void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) - { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_SCROLL; - mouseEventBuffer[mouseEventBufferCount].x = xoffset; - mouseEventBuffer[mouseEventBufferCount].y = yoffset; - mouseEventBufferCount++; } +} - void StartFrame() - { - glClearColor(0.08f, 0.18f, 0.18f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - } - void EndFrame() +void character_callback( GLFWwindow * window, unsigned int codepoint ) +{ + keyEventBuffer[ keyEventBufferCount ].ctrl = false; + keyEventBuffer[ keyEventBufferCount ].alt = false; + keyEventBuffer[ keyEventBufferCount ].shift = false; + keyEventBuffer[ keyEventBufferCount ].scanCode = 0; + // TODO: handle special things with Scintilla for UFT8 codepoints? + keyEventBuffer[ keyEventBufferCount ].character = codepoint; + keyEventBufferCount++; +} + +void cursor_position_callback( GLFWwindow * window, double xpos, double ypos ) +{ + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_MOVE; + mouseEventBuffer[ mouseEventBufferCount ].x = (float)xpos; + mouseEventBuffer[ mouseEventBufferCount ].y = (float)ypos; + if ( glfwGetMouseButton( window, GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS ) mouseEventBuffer[ mouseEventBufferCount ].button = MOUSEBUTTON_LEFT; + mouseEventBufferCount++; +} + +void mouse_button_callback( GLFWwindow * window, int button, int action, int mods ) +{ + if ( action == GLFW_PRESS ) { - keyEventBufferCount = 0; - mouseEventBufferCount = 0; - glfwSwapBuffers(mWindow); - glfwPollEvents(); + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_DOWN; } - bool WantsToQuit() + else if ( action == GLFW_RELEASE ) { - return glfwWindowShouldClose(mWindow) || !run; + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_UP; } - void Close() + double xpos, ypos; + glfwGetCursorPos( window, &xpos, &ypos ); + mouseEventBuffer[ mouseEventBufferCount ].x = (float)xpos; + mouseEventBuffer[ mouseEventBufferCount ].y = (float)ypos; + switch ( button ) { - glfwDestroyWindow(mWindow); - glfwTerminate(); + case GLFW_MOUSE_BUTTON_MIDDLE: mouseEventBuffer[ mouseEventBufferCount ].button = MOUSEBUTTON_MIDDLE; break; + case GLFW_MOUSE_BUTTON_RIGHT: mouseEventBuffer[ mouseEventBufferCount ].button = MOUSEBUTTON_RIGHT; break; + case GLFW_MOUSE_BUTTON_LEFT: + default: mouseEventBuffer[ mouseEventBufferCount ].button = MOUSEBUTTON_LEFT; break; } + mouseEventBufferCount++; +} +void scroll_callback( GLFWwindow * window, double xoffset, double yoffset ) +{ + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_SCROLL; + mouseEventBuffer[ mouseEventBufferCount ].x = (float)xoffset; + mouseEventBuffer[ mouseEventBufferCount ].y = (float)yoffset; + mouseEventBufferCount++; +} - void RenderFullscreenQuad() - { - glBindVertexArray(glhFullscreenQuadVA); +void StartFrame() +{ + glClearColor( 0.08f, 0.18f, 0.18f, 1.0f ); + glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT ); +} +void EndFrame() +{ + keyEventBufferCount = 0; + mouseEventBufferCount = 0; + glfwSwapBuffers( mWindow ); + glfwPollEvents(); +} +bool WantsToQuit() +{ + return glfwWindowShouldClose( mWindow ) || !run; +} +void Close() +{ + glfwDestroyWindow( mWindow ); + glfwTerminate(); +} - glUseProgram(theShader); +void RenderFullscreenQuad() +{ + glBindVertexArray( glhFullscreenQuadVA ); - glBindBuffer( GL_ARRAY_BUFFER, glhFullscreenQuadVB ); + glUseProgram( theShader ); - const GLint position = glGetAttribLocation( theShader, "in_pos" ); - if (position >= 0) - { - glVertexAttribPointer( position, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (GLvoid*)(0 * sizeof(GLfloat)) ); - glEnableVertexAttribArray( position ); - } + glBindBuffer( GL_ARRAY_BUFFER, glhFullscreenQuadVB ); - const GLint texcoord = glGetAttribLocation( theShader, "in_texcoord" ); - if (texcoord >= 0) - { - glVertexAttribPointer( texcoord, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (GLvoid*)(3 * sizeof(GLfloat)) ); - glEnableVertexAttribArray( texcoord ); - } + const GLint position = glGetAttribLocation( theShader, "in_pos" ); + if ( position >= 0 ) + { + glVertexAttribPointer( position, 3, GL_FLOAT, GL_FALSE, sizeof( float ) * 5, (GLvoid *) ( 0 * sizeof( GLfloat ) ) ); + glEnableVertexAttribArray( position ); + } - glBindBuffer( GL_ARRAY_BUFFER, glhFullscreenQuadVB ); - glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); + const GLint texcoord = glGetAttribLocation( theShader, "in_texcoord" ); + if ( texcoord >= 0 ) + { + glVertexAttribPointer( texcoord, 2, GL_FLOAT, GL_FALSE, sizeof( float ) * 5, (GLvoid *) ( 3 * sizeof( GLfloat ) ) ); + glEnableVertexAttribArray( texcoord ); + } + + glBindBuffer( GL_ARRAY_BUFFER, glhFullscreenQuadVB ); + glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); - if (texcoord >= 0) - glDisableVertexAttribArray( texcoord ); + if ( texcoord >= 0 ) + glDisableVertexAttribArray( texcoord ); - if (position >= 0) - glDisableVertexAttribArray( position ); + if ( position >= 0 ) + glDisableVertexAttribArray( position ); - glUseProgram(0); - } + glUseProgram( 0 ); +} - bool ReloadShader( const char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize ) +bool ReloadShader( const char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize ) +{ + GLuint prg = glCreateProgram(); + GLuint shd = glCreateShader( GL_FRAGMENT_SHADER ); + GLint size = 0; + GLint result = 0; + + glShaderSource( shd, 1, (const GLchar **) &szShaderCode, &nShaderCodeSize ); + glCompileShader( shd ); + glGetShaderInfoLog( shd, nErrorBufferSize, &size, szErrorBuffer ); + glGetShaderiv( shd, GL_COMPILE_STATUS, &result ); + if ( !result ) { - GLuint prg = glCreateProgram(); - GLuint shd = glCreateShader(GL_FRAGMENT_SHADER); - GLint size = 0; - GLint result = 0; - - glShaderSource(shd, 1, (const GLchar**)&szShaderCode, &nShaderCodeSize); - glCompileShader(shd); - glGetShaderInfoLog(shd, nErrorBufferSize, &size, szErrorBuffer); - glGetShaderiv(shd, GL_COMPILE_STATUS, &result); - if (!result) - { - glDeleteProgram(prg); - glDeleteShader(shd); - return false; - } + glDeleteProgram( prg ); + glDeleteShader( shd ); + return false; + } - glAttachShader(prg, glhVertexShader); - glAttachShader(prg, shd); - glLinkProgram(prg); - glGetProgramInfoLog(prg, nErrorBufferSize - size, &size, szErrorBuffer + size); - glGetProgramiv(prg, GL_LINK_STATUS, &result); - if (!result) - { - glDeleteProgram(prg); - glDeleteShader(shd); - return false; - } + glAttachShader( prg, glhVertexShader ); + glAttachShader( prg, shd ); + glLinkProgram( prg ); + glGetProgramInfoLog( prg, nErrorBufferSize - size, &size, szErrorBuffer + size ); + glGetProgramiv( prg, GL_LINK_STATUS, &result ); + if ( !result ) + { + glDeleteProgram( prg ); + glDeleteShader( shd ); + return false; + } - if (theShader) - glDeleteProgram(theShader); + if ( theShader ) + glDeleteProgram( theShader ); - theShader = prg; + theShader = prg; - return true; - } + return true; +} - void SetShaderConstant( const char * szConstName, float x ) +void SetShaderConstant( const char * szConstName, float x ) +{ + GLint location = glGetUniformLocation( theShader, szConstName ); + if ( location != -1 ) { - GLint location = glGetUniformLocation( theShader, szConstName ); - if ( location != -1 ) - { - glProgramUniform1f( theShader, location, x ); - } + glProgramUniform1f( theShader, location, x ); } +} - void SetShaderConstant( const char * szConstName, float x, float y ) +void SetShaderConstant( const char * szConstName, float x, float y ) +{ + GLint location = glGetUniformLocation( theShader, szConstName ); + if ( location != -1 ) { - GLint location = glGetUniformLocation( theShader, szConstName ); - if ( location != -1 ) - { - glProgramUniform2f( theShader, location, x, y ); - } + glProgramUniform2f( theShader, location, x, y ); } +} - struct GLTexture : public Texture - { - GLuint ID; - int unit; - }; +struct GLTexture : public Texture +{ + GLuint ID; + int unit; +}; + +int textureUnit = 0; - int textureUnit = 0; +Texture * CreateRGBA8Texture() +{ + void * data = NULL; + GLenum internalFormat = GL_SRGB8_ALPHA8; + GLenum srcFormat = GL_FLOAT; + GLenum format = GL_UNSIGNED_BYTE; + + GLuint glTexId = 0; + glGenTextures( 1, &glTexId ); + glBindTexture( GL_TEXTURE_2D, glTexId ); + + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + + GLTexture * tex = new GLTexture(); + tex->width = nWidth; + tex->height = nHeight; + tex->ID = glTexId; + tex->type = TEXTURETYPE_2D; + tex->unit = textureUnit++; + return tex; +} - Texture * CreateRGBA8Texture() +Texture * CreateRGBA8TextureFromFile( const char * szFilename ) +{ + int comp = 0; + int width = 0; + int height = 0; + void * data = NULL; + GLenum internalFormat = GL_SRGB8_ALPHA8; + GLenum srcFormat = GL_RGBA; + GLenum format = GL_UNSIGNED_BYTE; + if ( stbi_is_hdr( szFilename ) ) { - void * data = NULL; - GLenum internalFormat = GL_SRGB8_ALPHA8; - GLenum srcFormat = GL_FLOAT; - GLenum format = GL_UNSIGNED_BYTE; - - GLuint glTexId = 0; - glGenTextures( 1, &glTexId ); - glBindTexture( GL_TEXTURE_2D, glTexId ); - - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - - GLTexture * tex = new GLTexture(); - tex->width = nWidth; - tex->height = nHeight; - tex->ID = glTexId; - tex->type = TEXTURETYPE_2D; - tex->unit = textureUnit++; - return tex; + internalFormat = GL_RGBA32F; + format = GL_FLOAT; + data = stbi_loadf( szFilename, &width, &height, &comp, STBI_rgb_alpha ); } - - Texture * CreateRGBA8TextureFromFile( const char * szFilename ) + else { - int comp = 0; - int width = 0; - int height = 0; - void * data = NULL; - GLenum internalFormat = GL_SRGB8_ALPHA8; - GLenum srcFormat = GL_RGBA; - GLenum format = GL_UNSIGNED_BYTE; - if ( stbi_is_hdr( szFilename ) ) - { - internalFormat = GL_RGBA32F; - format = GL_FLOAT; - data = stbi_loadf( szFilename, &width, &height, &comp, STBI_rgb_alpha ); - } - else - { - data = stbi_load( szFilename, &width, &height, &comp, STBI_rgb_alpha ); - } - if (!data) return NULL; + data = stbi_load( szFilename, &width, &height, &comp, STBI_rgb_alpha ); + } + if ( !data ) return NULL; - GLuint glTexId = 0; - glGenTextures( 1, &glTexId ); - glBindTexture( GL_TEXTURE_2D, glTexId ); + GLuint glTexId = 0; + glGenTextures( 1, &glTexId ); + glBindTexture( GL_TEXTURE_2D, glTexId ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - glTexImage2D( GL_TEXTURE_2D, 0, internalFormat, width, height, 0, srcFormat, format, data ); + glTexImage2D( GL_TEXTURE_2D, 0, internalFormat, width, height, 0, srcFormat, format, data ); - stbi_image_free(data); + stbi_image_free( data ); - GLTexture * tex = new GLTexture(); - tex->width = width; - tex->height = height; - tex->ID = glTexId; - tex->type = TEXTURETYPE_2D; - tex->unit = textureUnit++; - return tex; - } + GLTexture * tex = new GLTexture(); + tex->width = width; + tex->height = height; + tex->ID = glTexId; + tex->type = TEXTURETYPE_2D; + tex->unit = textureUnit++; + return tex; +} - Texture * Create1DR32Texture( int w ) - { - GLuint glTexId = 0; - glGenTextures( 1, &glTexId ); - glBindTexture( GL_TEXTURE_1D, glTexId ); +Texture * Create1DR32Texture( int w ) +{ + GLuint glTexId = 0; + glGenTextures( 1, &glTexId ); + glBindTexture( GL_TEXTURE_1D, glTexId ); - glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT ); - glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT ); + glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - float * data = new float[w]; - for ( int i = 0; i < w; ++i ) - data[i] = 0.0f; + float * data = new float[ w ]; + for ( int i = 0; i < w; ++i ) + data[ i ] = 0.0f; - glTexImage1D( GL_TEXTURE_1D, 0, GL_R32F, w, 0, GL_RED, GL_FLOAT, data ); + glTexImage1D( GL_TEXTURE_1D, 0, GL_R32F, w, 0, GL_RED, GL_FLOAT, data ); - delete[] data; + delete[] data; - glBindTexture( GL_TEXTURE_1D, 0 ); + glBindTexture( GL_TEXTURE_1D, 0 ); - GLTexture * tex = new GLTexture(); - tex->width = w; - tex->height = 1; - tex->ID = glTexId; - tex->type = TEXTURETYPE_1D; - tex->unit = textureUnit++; - return tex; - } + GLTexture * tex = new GLTexture(); + tex->width = w; + tex->height = 1; + tex->ID = glTexId; + tex->type = TEXTURETYPE_1D; + tex->unit = textureUnit++; + return tex; +} - void SetShaderTexture( const char * szTextureName, Texture * tex ) - { - if (!tex) - return; +void SetShaderTexture( const char * szTextureName, Texture * tex ) +{ + if ( !tex ) + return; - GLint location = glGetUniformLocation( theShader, szTextureName ); - if ( location != -1 ) + GLint location = glGetUniformLocation( theShader, szTextureName ); + if ( location != -1 ) + { + glProgramUniform1i( theShader, location, ( (GLTexture *) tex )->unit ); + glActiveTexture( GL_TEXTURE0 + ( (GLTexture *) tex )->unit ); + switch ( tex->type ) { - glProgramUniform1i( theShader, location, ((GLTexture*)tex)->unit ); - glActiveTexture( GL_TEXTURE0 + ((GLTexture*)tex)->unit ); - switch( tex->type) - { - case TEXTURETYPE_1D: glBindTexture( GL_TEXTURE_1D, ((GLTexture*)tex)->ID ); break; - case TEXTURETYPE_2D: glBindTexture( GL_TEXTURE_2D, ((GLTexture*)tex)->ID ); break; - } + case TEXTURETYPE_1D: glBindTexture( GL_TEXTURE_1D, ( (GLTexture *) tex )->ID ); break; + case TEXTURETYPE_2D: glBindTexture( GL_TEXTURE_2D, ( (GLTexture *) tex )->ID ); break; } } +} - bool UpdateR32Texture( Texture * tex, float * data ) - { - glActiveTexture( GL_TEXTURE0 + ((GLTexture*)tex)->unit ); - glBindTexture( GL_TEXTURE_1D, ((GLTexture*)tex)->ID ); - glTexSubImage1D( GL_TEXTURE_1D, 0, 0, tex->width, GL_RED, GL_FLOAT, data ); - - return true; - } +bool UpdateR32Texture( Texture * tex, float * data ) +{ + glActiveTexture( GL_TEXTURE0 + ( (GLTexture *) tex )->unit ); + glBindTexture( GL_TEXTURE_1D, ( (GLTexture *) tex )->ID ); + glTexSubImage1D( GL_TEXTURE_1D, 0, 0, tex->width, GL_RED, GL_FLOAT, data ); - Texture * CreateA8TextureFromData( int w, int h, const unsigned char * data ) - { - GLuint glTexId = 0; - glGenTextures(1, &glTexId); - glBindTexture(GL_TEXTURE_2D, glTexId); - unsigned int * p32bitData = new unsigned int[ w * h ]; - for(int i=0; iwidth = w; - tex->height = h; - tex->ID = glTexId; - tex->type = TEXTURETYPE_2D; - tex->unit = 0; // this is always 0 cos we're not using shaders here - return tex; - } + return true; +} - void ReleaseTexture( Texture * tex ) - { - glDeleteTextures(1, &((GLTexture*)tex)->ID ); - } +Texture * CreateA8TextureFromData( int w, int h, const unsigned char * data ) +{ + GLuint glTexId = 0; + glGenTextures( 1, &glTexId ); + glBindTexture( GL_TEXTURE_2D, glTexId ); + unsigned int * p32bitData = new unsigned int[ w * h ]; + for ( int i = 0; i < w * h; i++ ) p32bitData[ i ] = ( data[ i ] << 24 ) | 0xFFFFFF; + glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, p32bitData ); + delete[] p32bitData; + + glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + + GLTexture * tex = new GLTexture(); + tex->width = w; + tex->height = h; + tex->ID = glTexId; + tex->type = TEXTURETYPE_2D; + tex->unit = 0; // this is always 0 cos we're not using shaders here + return tex; +} - void CopyBackbufferToTexture( Texture * tex ) - { - glActiveTexture( GL_TEXTURE0 + ( (GLTexture *) tex )->unit ); - glBindTexture( GL_TEXTURE_2D, ( (GLTexture *) tex )->ID ); - glCopyTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, 0, 0, nWidth, nHeight, 0 ); - } +void ReleaseTexture( Texture * tex ) +{ + glDeleteTextures( 1, &( (GLTexture *) tex )->ID ); +} - ////////////////////////////////////////////////////////////////////////// - // text rendering +void CopyBackbufferToTexture( Texture * tex ) +{ + glActiveTexture( GL_TEXTURE0 + ( (GLTexture *) tex )->unit ); + glBindTexture( GL_TEXTURE_2D, ( (GLTexture *) tex )->ID ); + glCopyTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, 0, 0, nWidth, nHeight, 0 ); +} - int nDrawCallCount = 0; - Texture * lastTexture = NULL; - void StartTextRendering() - { - glUseProgram(glhGUIProgram); - glBindVertexArray(glhGUIVA); +////////////////////////////////////////////////////////////////////////// +// text rendering - glEnable( GL_BLEND ); - glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); - } +int nDrawCallCount = 0; +Texture * lastTexture = NULL; +void StartTextRendering() +{ + glUseProgram( glhGUIProgram ); + glBindVertexArray( glhGUIVA ); - int bufferPointer = 0; - unsigned char buffer[GUIQUADVB_SIZE * sizeof(float) * 7]; - bool lastModeIsQuad = true; - void __FlushRenderCache() - { - if (!bufferPointer) return; + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); +} - glBindBuffer( GL_ARRAY_BUFFER, glhGUIVB ); - glBufferData( GL_ARRAY_BUFFER, sizeof(float) * 7 * bufferPointer, buffer, GL_DYNAMIC_DRAW ); +int bufferPointer = 0; +unsigned char buffer[ GUIQUADVB_SIZE * sizeof( float ) * 7 ]; +bool lastModeIsQuad = true; +void __FlushRenderCache() +{ + if ( !bufferPointer ) return; - GLuint position = glGetAttribLocation( glhGUIProgram, "in_pos" ); - glVertexAttribPointer( position, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (GLvoid*)(0 * sizeof(GLfloat)) ); - glEnableVertexAttribArray( position ); + glBindBuffer( GL_ARRAY_BUFFER, glhGUIVB ); + glBufferData( GL_ARRAY_BUFFER, sizeof( float ) * 7 * bufferPointer, buffer, GL_DYNAMIC_DRAW ); - GLuint color = glGetAttribLocation( glhGUIProgram, "in_color" ); - glVertexAttribPointer( color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(float) * 7, (GLvoid*)(3 * sizeof(GLfloat)) ); - glEnableVertexAttribArray( color ); + GLuint position = glGetAttribLocation( glhGUIProgram, "in_pos" ); + glVertexAttribPointer( position, 3, GL_FLOAT, GL_FALSE, sizeof( float ) * 7, (GLvoid *) ( 0 * sizeof( GLfloat ) ) ); + glEnableVertexAttribArray( position ); - GLuint texcoord = glGetAttribLocation( glhGUIProgram, "in_texcoord" ); - glVertexAttribPointer( texcoord, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (GLvoid*)(4 * sizeof(GLfloat)) ); - glEnableVertexAttribArray( texcoord ); + GLuint color = glGetAttribLocation( glhGUIProgram, "in_color" ); + glVertexAttribPointer( color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof( float ) * 7, (GLvoid *) ( 3 * sizeof( GLfloat ) ) ); + glEnableVertexAttribArray( color ); - GLuint factor = glGetAttribLocation( glhGUIProgram, "in_factor" ); - glVertexAttribPointer( factor, 1, GL_FLOAT, GL_FALSE, sizeof(float) * 7, (GLvoid*)(6 * sizeof(GLfloat)) ); - glEnableVertexAttribArray( factor ); + GLuint texcoord = glGetAttribLocation( glhGUIProgram, "in_texcoord" ); + glVertexAttribPointer( texcoord, 2, GL_FLOAT, GL_FALSE, sizeof( float ) * 7, (GLvoid *) ( 4 * sizeof( GLfloat ) ) ); + glEnableVertexAttribArray( texcoord ); - if (lastModeIsQuad) - { - glDrawArrays( GL_TRIANGLES, 0, bufferPointer ); - } - else - { - glDrawArrays( GL_LINES, 0, bufferPointer ); - } + GLuint factor = glGetAttribLocation( glhGUIProgram, "in_factor" ); + glVertexAttribPointer( factor, 1, GL_FLOAT, GL_FALSE, sizeof( float ) * 7, (GLvoid *) ( 6 * sizeof( GLfloat ) ) ); + glEnableVertexAttribArray( factor ); - bufferPointer = 0; + if ( lastModeIsQuad ) + { + glDrawArrays( GL_TRIANGLES, 0, bufferPointer ); } - void __WriteVertexToBuffer( const Vertex & v ) + else { - if (bufferPointer >= GUIQUADVB_SIZE) - { - __FlushRenderCache(); - } + glDrawArrays( GL_LINES, 0, bufferPointer ); + } - float * f = (float*)(buffer + bufferPointer * sizeof(float) * 7); - *(f++) = v.x; - *(f++) = v.y; - *(f++) = 0.0; - *(unsigned int *)(f++) = v.c; - *(f++) = v.u; - *(f++) = v.v; - *(f++) = lastTexture ? 0.0f : 1.0f; - bufferPointer++; + bufferPointer = 0; +} +void __WriteVertexToBuffer( const Vertex & v ) +{ + if ( bufferPointer >= GUIQUADVB_SIZE ) + { + __FlushRenderCache(); } - void BindTexture( Texture * tex ) + + float * f = (float *) ( buffer + bufferPointer * sizeof( float ) * 7 ); + *( f++ ) = v.x; + *( f++ ) = v.y; + *( f++ ) = 0.0; + *(unsigned int *) ( f++ ) = v.c; + *( f++ ) = v.u; + *( f++ ) = v.v; + *( f++ ) = lastTexture ? 0.0f : 1.0f; + bufferPointer++; +} +void BindTexture( Texture * tex ) +{ + if ( lastTexture != tex ) { - if (lastTexture != tex) + lastTexture = tex; + if ( tex ) { - lastTexture = tex; - if (tex) - { - __FlushRenderCache(); + __FlushRenderCache(); - GLint location = glGetUniformLocation( glhGUIProgram, "tex" ); - if ( location != -1 ) + GLint location = glGetUniformLocation( glhGUIProgram, "tex" ); + if ( location != -1 ) + { + glProgramUniform1i( glhGUIProgram, location, ( (GLTexture *) tex )->unit ); + glActiveTexture( GL_TEXTURE0 + ( (GLTexture *) tex )->unit ); + switch ( tex->type ) { - glProgramUniform1i( glhGUIProgram, location, ((GLTexture*)tex)->unit ); - glActiveTexture( GL_TEXTURE0 + ((GLTexture*)tex)->unit ); - switch( tex->type) - { - case TEXTURETYPE_1D: glBindTexture( GL_TEXTURE_1D, ((GLTexture*)tex)->ID ); break; - case TEXTURETYPE_2D: glBindTexture( GL_TEXTURE_2D, ((GLTexture*)tex)->ID ); break; - } + case TEXTURETYPE_1D: glBindTexture( GL_TEXTURE_1D, ( (GLTexture *) tex )->ID ); break; + case TEXTURETYPE_2D: glBindTexture( GL_TEXTURE_2D, ( (GLTexture *) tex )->ID ); break; } - } - } - } - void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d ) - { - if (!lastModeIsQuad) - { - __FlushRenderCache(); - lastModeIsQuad = true; } - __WriteVertexToBuffer(a); - __WriteVertexToBuffer(b); - __WriteVertexToBuffer(d); - __WriteVertexToBuffer(b); - __WriteVertexToBuffer(c); - __WriteVertexToBuffer(d); } +} - void RenderLine( const Vertex & a, const Vertex & b ) +void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d ) +{ + if ( !lastModeIsQuad ) { - if (lastModeIsQuad) - { - __FlushRenderCache(); - lastModeIsQuad = false; - } - __WriteVertexToBuffer(a); - __WriteVertexToBuffer(b); + __FlushRenderCache(); + lastModeIsQuad = true; } + __WriteVertexToBuffer( a ); + __WriteVertexToBuffer( b ); + __WriteVertexToBuffer( d ); + __WriteVertexToBuffer( b ); + __WriteVertexToBuffer( c ); + __WriteVertexToBuffer( d ); +} - void SetTextRenderingViewport( Scintilla::PRectangle rect ) +void RenderLine( const Vertex & a, const Vertex & b ) +{ + if ( lastModeIsQuad ) { __FlushRenderCache(); + lastModeIsQuad = false; + } + __WriteVertexToBuffer( a ); + __WriteVertexToBuffer( b ); +} - float pGUIMatrix[16]; - MatrixOrthoOffCenterLH( pGUIMatrix, 0.0f, (float)nWidth, (float)nHeight, 0.0f, -1.0f, 1.0f ); - - GLint location = glGetUniformLocation( glhGUIProgram, "matProj" ); - if ( location != -1 ) - { - glProgramUniformMatrix4fv( glhGUIProgram, location, 1, GL_FALSE, pGUIMatrix ); - } +void SetTextRenderingViewport( Scintilla::PRectangle rect ) +{ + __FlushRenderCache(); - location = glGetUniformLocation( glhGUIProgram, "v2Offset" ); - if ( location != -1 ) - { - glProgramUniform2f( glhGUIProgram, location, rect.left, rect.top ); - } + float pGUIMatrix[ 16 ]; + MatrixOrthoOffCenterLH( pGUIMatrix, 0.0f, (float) nWidth, (float) nHeight, 0.0f, -1.0f, 1.0f ); - glEnable(GL_SCISSOR_TEST); - glScissor(rect.left, nHeight - rect.bottom, rect.right - rect.left, rect.bottom - rect.top); + GLint location = glGetUniformLocation( glhGUIProgram, "matProj" ); + if ( location != -1 ) + { + glProgramUniformMatrix4fv( glhGUIProgram, location, 1, GL_FALSE, pGUIMatrix ); } - void EndTextRendering() + + location = glGetUniformLocation( glhGUIProgram, "v2Offset" ); + if ( location != -1 ) { - __FlushRenderCache(); + glProgramUniform2f( glhGUIProgram, location, rect.left, rect.top ); + } - glBindBuffer( GL_ARRAY_BUFFER, glhFullscreenQuadVB ); - glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); + glEnable( GL_SCISSOR_TEST ); + glScissor( rect.left, nHeight - rect.bottom, rect.right - rect.left, rect.bottom - rect.top ); +} +void EndTextRendering() +{ + __FlushRenderCache(); - GLuint position = glGetAttribLocation( glhGUIProgram, "in_pos" ); - GLuint color = glGetAttribLocation( glhGUIProgram, "in_color" ); - GLuint texcoord = glGetAttribLocation( glhGUIProgram, "in_texcoord" ); - GLuint factor = glGetAttribLocation( glhGUIProgram, "in_factor" ); + glBindBuffer( GL_ARRAY_BUFFER, glhFullscreenQuadVB ); + glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); - glDisableVertexAttribArray( factor ); - glDisableVertexAttribArray( texcoord ); - glDisableVertexAttribArray( color ); - glDisableVertexAttribArray( position ); + GLuint position = glGetAttribLocation( glhGUIProgram, "in_pos" ); + GLuint color = glGetAttribLocation( glhGUIProgram, "in_color" ); + GLuint texcoord = glGetAttribLocation( glhGUIProgram, "in_texcoord" ); + GLuint factor = glGetAttribLocation( glhGUIProgram, "in_factor" ); - glUseProgram(0); + glDisableVertexAttribArray( factor ); + glDisableVertexAttribArray( texcoord ); + glDisableVertexAttribArray( color ); + glDisableVertexAttribArray( position ); - glDisable(GL_BLEND); - glDisable(GL_SCISSOR_TEST); - } + glUseProgram( 0 ); - ////////////////////////////////////////////////////////////////////////// + glDisable( GL_BLEND ); + glDisable( GL_SCISSOR_TEST ); +} + +////////////////////////////////////////////////////////////////////////// - bool GrabFrame( void * pPixelBuffer ) +bool GrabFrame( void * pPixelBuffer ) +{ + writeIndex = ( writeIndex + 1 ) % 2; + readIndex = ( readIndex + 1 ) % 2; + + glBindBuffer( GL_PIXEL_PACK_BUFFER, pbo[ writeIndex ] ); + glReadPixels( 0, 0, nWidth, nHeight, GL_RGBA, GL_UNSIGNED_BYTE, NULL ); + glBindBuffer( GL_PIXEL_PACK_BUFFER, pbo[ readIndex ] ); + unsigned char * downsampleData = (unsigned char *) glMapBuffer( GL_PIXEL_PACK_BUFFER, GL_READ_ONLY ); + if ( downsampleData ) { - writeIndex = (writeIndex + 1) % 2; - readIndex = (readIndex + 1) % 2; - - glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[writeIndex]); - glReadPixels(0, 0, nWidth, nHeight, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[readIndex]); - unsigned char * downsampleData = (unsigned char *)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY); - if (downsampleData) + unsigned char * src = downsampleData; + unsigned char * dst = (unsigned char *) pPixelBuffer + nWidth * ( nHeight - 1 ) * sizeof( unsigned int ); + for ( int i = 0; i < nHeight; i++ ) { - unsigned char * src = downsampleData; - unsigned char * dst = (unsigned char*)pPixelBuffer + nWidth * (nHeight - 1) * sizeof(unsigned int); - for (int i=0; isRenderer.windowMode == RENDERER_WINDOWMODE_FULLSCREEN) { + if (settings->sRenderer.windowMode == Renderer::WINDOWMODE_FULLSCREEN) { settingsFlags |= CFUserNotificationCheckBoxChecked(0); } int idx=0; @@ -95,9 +95,9 @@ bool Open( SetupDialog::SETTINGS * settings ) // Collect the user selection and feed the settings if (responseFlags & CFUserNotificationCheckBoxChecked(0)) { - settings->sRenderer.windowMode = RENDERER_WINDOWMODE_FULLSCREEN; + settings->sRenderer.windowMode = Renderer::WINDOWMODE_FULLSCREEN; } else { - settings->sRenderer.windowMode = RENDERER_WINDOWMODE_WINDOWED; + settings->sRenderer.windowMode = Renderer::WINDOWMODE_WINDOWED; } idx = (int)responseFlags >> 24; if ((idx >= 0) && (idx < resolutions.size())) { diff --git a/src/platform_w32_common/Clipboard.cpp b/src/platform_w32_common/Clipboard.cpp index f3d3b739..cab730c9 100644 --- a/src/platform_w32_common/Clipboard.cpp +++ b/src/platform_w32_common/Clipboard.cpp @@ -2,87 +2,96 @@ namespace Clipboard { - void Copy( const char * data, int len ) +////////////////////////////////////////////////////////////////////////// + +void Copy( const char * data, int len ) +{ + HWND hWnd = GetForegroundWindow(); + if ( !::OpenClipboard( hWnd ) ) + return; + + HGLOBAL hData = GlobalAlloc( GMEM_MOVEABLE, ( len + 1 ) * sizeof( char ) ); + if ( !hData ) { - HWND hWnd = GetForegroundWindow(); - if ( !::OpenClipboard( hWnd ) ) - return; + CloseClipboard(); + return; + } - HGLOBAL hData = GlobalAlloc( GMEM_MOVEABLE, ( len + 1 ) * sizeof( char ) ); - if ( !hData ) { - CloseClipboard(); - return; - } + WCHAR * pMem = (WCHAR *) GlobalLock( hData ); + if ( !pMem ) + { + GlobalFree( hData ); + CloseClipboard(); + return; + } + + ZeroMemory( pMem, ( len + 1 ) * sizeof( char ) ); + CopyMemory( pMem, data, ( len + 1 ) * sizeof( char ) ); - WCHAR * pMem = (WCHAR*) GlobalLock( hData ); - if ( !pMem ) { - GlobalFree( hData ); - CloseClipboard(); - return; - } + GlobalUnlock( hData ); - ZeroMemory( pMem, ( len + 1 ) * sizeof( char ) ); - CopyMemory( pMem, data, ( len + 1 ) * sizeof( char ) ); + EmptyClipboard(); - GlobalUnlock( hData ); + SetClipboardData( CF_TEXT, hData ); - EmptyClipboard(); + CloseClipboard(); +} - SetClipboardData( CF_TEXT, hData ); +int GetContentsLength() +{ + HWND hWnd = GetForegroundWindow(); + if ( !::OpenClipboard( hWnd ) ) + return 0; + HANDLE hData = GetClipboardData( CF_TEXT ); + if ( !hData ) + { CloseClipboard(); + return 0; } - int GetContentsLength() + const char * buffer = (const char *) GlobalLock( hData ); + if ( !buffer ) { - HWND hWnd = GetForegroundWindow(); - if ( !::OpenClipboard( hWnd ) ) - return 0; + CloseClipboard(); + return 0; + } - HANDLE hData = GetClipboardData( CF_TEXT ); - if ( !hData ) { - CloseClipboard(); - return 0; - } + int n = strlen( buffer ); - const char * buffer = (const char*) GlobalLock( hData ); - if ( !buffer ) { - CloseClipboard(); - return 0; - } + GlobalUnlock( hData ); - int n = strlen( buffer ); + CloseClipboard(); - GlobalUnlock( hData ); + return n; +} - CloseClipboard(); +void GetContents( char * data, int len ) +{ + HWND hWnd = GetForegroundWindow(); + if ( !::OpenClipboard( hWnd ) ) + return; - return n; + HANDLE hData = GetClipboardData( CF_TEXT ); + if ( !hData ) + { + CloseClipboard(); + return; } - void GetContents( char * data, int len ) + const char * buffer = (const char *) GlobalLock( hData ); + if ( !buffer ) { - HWND hWnd = GetForegroundWindow(); - if ( !::OpenClipboard( hWnd ) ) - return; - - HANDLE hData = GetClipboardData( CF_TEXT ); - if ( !hData ) { - CloseClipboard(); - return; - } - - const char * buffer = (const char*) GlobalLock( hData ); - if ( !buffer ) { - CloseClipboard(); - return; - } + CloseClipboard(); + return; + } - strncpy( data, buffer, len ); + strncpy( data, buffer, len ); - GlobalUnlock( hData ); + GlobalUnlock( hData ); - CloseClipboard(); - } + CloseClipboard(); +} +////////////////////////////////////////////////////////////////////////// } diff --git a/src/platform_w32_common/MIDI.cpp b/src/platform_w32_common/MIDI.cpp index 05791598..4504ce67 100644 --- a/src/platform_w32_common/MIDI.cpp +++ b/src/platform_w32_common/MIDI.cpp @@ -5,10 +5,13 @@ namespace MIDI { - int nCCValues[256]; - void CALLBACK MyMidiInProc( HMIDIIN hMidiIn, UINT wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2) +////////////////////////////////////////////////////////////////////////// + +int nCCValues[ 256 ]; +void CALLBACK MyMidiInProc( HMIDIIN hMidiIn, UINT wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2 ) +{ + switch ( wMsg ) { - switch (wMsg) { case MM_MIM_OPEN: { // unused @@ -22,47 +25,49 @@ namespace MIDI unsigned char nMIDIMessage = dwParam1 & 0xFF; unsigned char nMIDIMessageType = nMIDIMessage >> 4; unsigned char nMIDIChannel = nMIDIMessage & 0x0F; - unsigned char nMIDIControl = (dwParam1 >> 8) & 0xFF; - unsigned char nMIDIValue = (dwParam1 >> 16) & 0xFF; + unsigned char nMIDIControl = ( dwParam1 >> 8 ) & 0xFF; + unsigned char nMIDIValue = ( dwParam1 >> 16 ) & 0xFF; //printf("[%08X] MM_MIM_DATA - TYPE: %X CHAN: %3d CTRL: %3d VAL: %3d\n",hMidiIn,nMIDIMessageType,nMIDIChannel,nMIDIControl,nMIDIValue); nCCValues[ nMIDIControl ] = nMIDIValue; } break; - } } +} - HMIDIIN hMIDIInput[32]; - int nMIDIDeviceCount = 0; - bool Open() - { - ZeroMemory( &nCCValues, sizeof(int) * 256 ); - nMIDIDeviceCount = midiInGetNumDevs(); - - for (int i = 0; i < nMIDIDeviceCount; i++) - { - MIDIINCAPS caps; - midiInGetDevCaps(i,&caps,sizeof(MIDIINCAPS)); - //_tprintf(_T("%d - %d - %d - %08X - %s\n"),i,caps.wMid,caps.wPid,caps.vDriverVersion,caps.szPname); +HMIDIIN hMIDIInput[ 32 ]; +int nMIDIDeviceCount = 0; +bool Open() +{ + ZeroMemory( &nCCValues, sizeof( int ) * 256 ); + nMIDIDeviceCount = midiInGetNumDevs(); - midiInOpen(&hMIDIInput[i],i,(DWORD_PTR)MyMidiInProc,NULL,CALLBACK_FUNCTION); + for ( int i = 0; i < nMIDIDeviceCount; i++ ) + { + MIDIINCAPS caps; + midiInGetDevCaps( i, &caps, sizeof( MIDIINCAPS ) ); + //_tprintf(_T("%d - %d - %d - %08X - %s\n"),i,caps.wMid,caps.wPid,caps.vDriverVersion,caps.szPname); - midiInStart(hMIDIInput[i]); - } + midiInOpen( &hMIDIInput[ i ], i, (DWORD_PTR) MyMidiInProc, NULL, CALLBACK_FUNCTION ); - return true; - } - bool Close() - { - for (int i = 0; i < nMIDIDeviceCount; i++) { - midiInStop(hMIDIInput[i]); - midiInClose(hMIDIInput[i]); - } - return true; + midiInStart( hMIDIInput[ i ] ); } - float GetCCValue( unsigned char cc ) + return true; +} +bool Close() +{ + for ( int i = 0; i < nMIDIDeviceCount; i++ ) { - return nCCValues[cc] / 127.0f; + midiInStop( hMIDIInput[ i ] ); + midiInClose( hMIDIInput[ i ] ); } + return true; +} + +float GetCCValue( unsigned char cc ) +{ + return nCCValues[ cc ] / 127.0f; +} +////////////////////////////////////////////////////////////////////////// }; \ No newline at end of file diff --git a/src/platform_w32_common/Misc.cpp b/src/platform_w32_common/Misc.cpp index f74a5b0f..10c2533d 100644 --- a/src/platform_w32_common/Misc.cpp +++ b/src/platform_w32_common/Misc.cpp @@ -8,86 +8,90 @@ namespace Misc { - void PlatformStartup() - { - } +////////////////////////////////////////////////////////////////////////// - void PlatformShutdown() - { - } +void PlatformStartup() +{ +} - std::map keymaps; - void InitKeymaps() - { - HKEY hk = NULL; - RegOpenKeyExA( HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts", NULL, KEY_READ, &hk ); +void PlatformShutdown() +{ +} - LONG result = NULL; - int idx = 0; - while ( result != ERROR_NO_MORE_ITEMS ) +std::map keymaps; +void InitKeymaps() +{ + HKEY hk = NULL; + RegOpenKeyExA( HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts", NULL, KEY_READ, &hk ); + + LONG result = NULL; + int idx = 0; + while ( result != ERROR_NO_MORE_ITEMS ) + { + char szKeyName[ 255 ]; + ZeroMemory( szKeyName, 255 ); + DWORD nKeyName = 255; + result = RegEnumKeyExA( hk, idx, szKeyName, &nKeyName, NULL, NULL, NULL, NULL ); + if ( result == ERROR_SUCCESS ) { - char szKeyName[255]; - ZeroMemory(szKeyName,255); - DWORD nKeyName = 255; - result = RegEnumKeyExA( hk, idx, szKeyName, &nKeyName, NULL, NULL, NULL, NULL); - if (result == ERROR_SUCCESS) - { - HKEY hkSub = NULL; - RegOpenKeyExA( hk, szKeyName, NULL, KEY_READ, &hkSub ); + HKEY hkSub = NULL; + RegOpenKeyExA( hk, szKeyName, NULL, KEY_READ, &hkSub ); - BYTE szValue[255]; - ZeroMemory(szValue,255); - DWORD nValue = 255; - DWORD type = REG_SZ; - LONG resultKey = RegQueryValueExA( hkSub, "Layout Text", NULL, &type, szValue, &nValue ); + BYTE szValue[ 255 ]; + ZeroMemory( szValue, 255 ); + DWORD nValue = 255; + DWORD type = REG_SZ; + LONG resultKey = RegQueryValueExA( hkSub, "Layout Text", NULL, &type, szValue, &nValue ); - CharLowerA( szKeyName ); - keymaps[szKeyName] = (const char*)szValue; - } - idx++; + CharLowerA( szKeyName ); + keymaps[ szKeyName ] = (const char *) szValue; } + idx++; } +} - void GetKeymapName( char * sz ) - { - char szCode[KL_NAMELENGTH]; - ::GetKeyboardLayoutNameA(szCode); - CharLowerA( szCode ); - strncpy( sz, keymaps.count(szCode) ? keymaps[szCode].c_str() : "" ,255); - } +void GetKeymapName( char * sz ) +{ + char szCode[ KL_NAMELENGTH ]; + ::GetKeyboardLayoutNameA( szCode ); + CharLowerA( szCode ); + strncpy( sz, keymaps.count( szCode ) ? keymaps[ szCode ].c_str() : "", 255 ); +} - bool ExecuteCommand( const char * cmd, const char * param ) - { - HINSTANCE hI = ShellExecute( NULL, NULL, cmd, param, NULL, SW_SHOW ); - return (int)hI >= 32; - } +bool ExecuteCommand( const char * cmd, const char * param ) +{ + HINSTANCE hI = ShellExecute( NULL, NULL, cmd, param, NULL, SW_SHOW ); + return (int) hI >= 32; +} + +bool FileExists( const char * path ) +{ + return GetFileAttributesA( path ) != INVALID_FILE_ATTRIBUTES; +} - bool FileExists(const char * path) +const char * GetDefaultFontPath() +{ + char windowsPath[ MAX_PATH ]; + if ( SHGetFolderPath( NULL, CSIDL_WINDOWS, NULL, 0, windowsPath ) != S_OK ) { - return GetFileAttributesA(path) != INVALID_FILE_ATTRIBUTES; + return NULL; } - - const char * GetDefaultFontPath() + const char * fontPaths[] = { - char windowsPath[ MAX_PATH ]; - if ( SHGetFolderPath( NULL, CSIDL_WINDOWS, NULL, 0, windowsPath ) != S_OK ) - { - return NULL; - } - const char* fontPaths[] = - { - "Fonts\\cour.ttf", - NULL - }; - for (int i = 0; fontPaths[i]; ++i) + "Fonts\\cour.ttf", + NULL + }; + for ( int i = 0; fontPaths[ i ]; ++i ) + { + static char fullPath[ MAX_PATH ] = { 0 }; + PathCombineA( fullPath, windowsPath, fontPaths[ i ] ); + if ( FileExists( fullPath ) ) { - static char fullPath[ MAX_PATH ] = { 0 }; - PathCombineA( fullPath, windowsPath, fontPaths[ i ] ); - if (FileExists( fullPath )) - { - return fullPath; - } + return fullPath; } - return NULL; } + return NULL; +} + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/platform_w32_common/SetupDialog.cpp b/src/platform_w32_common/SetupDialog.cpp index 7a9ee504..f5e6ed8b 100644 --- a/src/platform_w32_common/SetupDialog.cpp +++ b/src/platform_w32_common/SetupDialog.cpp @@ -13,21 +13,25 @@ namespace SetupDialog { +////////////////////////////////////////////////////////////////////////// + class CSetupDialog; CSetupDialog * pGlobal = NULL; -INT_PTR CALLBACK DlgFunc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); +INT_PTR CALLBACK DlgFunc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); class CSetupDialog { public: - typedef struct { + typedef struct + { int nWidth; int nHeight; } RESOLUTION; - typedef struct { + typedef struct + { bool bIsCapture; void * pDeviceID; } AUDIODEVICE; @@ -36,153 +40,160 @@ class CSetupDialog std::vector gaAudioDevices; HWND hWndSetupDialog; - CSetupDialog(void) + CSetupDialog( void ) { hWndSetupDialog = NULL; } - ~CSetupDialog(void) + ~CSetupDialog( void ) { } SETTINGS * setup; - int __cdecl ResolutionSort(const void * a, const void * b) + int __cdecl ResolutionSort( const void * a, const void * b ) { - RESOLUTION * aa = (RESOLUTION *)a; - RESOLUTION * bb = (RESOLUTION *)b; - if (aa->nWidth < bb->nWidth) return -1; - if (aa->nWidth > bb->nWidth) return 1; - if (aa->nHeight < bb->nHeight) return -1; - if (aa->nHeight > bb->nHeight) return 1; + RESOLUTION * aa = (RESOLUTION *) a; + RESOLUTION * bb = (RESOLUTION *) b; + if ( aa->nWidth < bb->nWidth ) return -1; + if ( aa->nWidth > bb->nWidth ) return 1; + if ( aa->nHeight < bb->nHeight ) return -1; + if ( aa->nHeight > bb->nHeight ) return 1; return 0; } - void FFTDeviceEnum( const bool bIsCaptureDevice, const char * szDeviceName, void * pDeviceID) + void FFTDeviceEnum( const bool bIsCaptureDevice, const char * szDeviceName, void * pDeviceID ) { - TCHAR sz[512]; - _sntprintf( sz, 512, _T("[%hs] %hs"), bIsCaptureDevice ? "in" : "out", szDeviceName ); - SendDlgItemMessage(hWndSetupDialog, IDC_AUDIOSOURCE, CB_ADDSTRING, 0, (LPARAM)sz); + TCHAR sz[ 512 ]; + _sntprintf( sz, 512, _T( "[%hs] %hs" ), bIsCaptureDevice ? "in" : "out", szDeviceName ); + SendDlgItemMessage( hWndSetupDialog, IDC_AUDIOSOURCE, CB_ADDSTRING, 0, (LPARAM) sz ); - if ( !pDeviceID) + if ( !pDeviceID ) { - if (setup->sFFT.bUseRecordingDevice == bIsCaptureDevice) + if ( setup->sFFT.bUseRecordingDevice == bIsCaptureDevice ) { - SendDlgItemMessage(hWndSetupDialog, IDC_AUDIOSOURCE, CB_SETCURSEL, gaAudioDevices.size(), 0); + SendDlgItemMessage( hWndSetupDialog, IDC_AUDIOSOURCE, CB_SETCURSEL, gaAudioDevices.size(), 0 ); } } AUDIODEVICE audioDevice; audioDevice.bIsCapture = bIsCaptureDevice; audioDevice.pDeviceID = pDeviceID; - gaAudioDevices.push_back(audioDevice); + gaAudioDevices.push_back( audioDevice ); } static void FFTDeviceEnum( const bool bIsCaptureDevice, const char * szDeviceName, void * pDeviceID, void * pUserContext ) { - ((CSetupDialog*)pUserContext)->FFTDeviceEnum(bIsCaptureDevice, szDeviceName, pDeviceID); + ( (CSetupDialog *) pUserContext )->FFTDeviceEnum( bIsCaptureDevice, szDeviceName, pDeviceID ); } - bool DialogProcedure( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) + bool DialogProcedure( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - switch (uMsg) { - case WM_INITDIALOG: - { - hWndSetupDialog = hWnd; - - int i = 0; - while(1) { - DEVMODE d; - BOOL h = EnumDisplaySettings(NULL,i++,&d); - if (!h) break; - - //if ((d.dmPelsWidth * 9) / 16 != d.dmPelsHeight) continue; - if (d.dmBitsPerPel != 32) continue; - if (d.dmDisplayOrientation != DMDO_DEFAULT) continue; + switch ( uMsg ) + { + case WM_INITDIALOG: + { + hWndSetupDialog = hWnd; - if (!gaResolutions.size() - || gaResolutions[ gaResolutions.size() - 1 ].nWidth != d.dmPelsWidth - || gaResolutions[ gaResolutions.size() - 1 ].nHeight != d.dmPelsHeight) + int i = 0; + while ( 1 ) { - RESOLUTION res; - res.nWidth = d.dmPelsWidth; - res.nHeight = d.dmPelsHeight; - gaResolutions.push_back(res); - + DEVMODE d; + BOOL h = EnumDisplaySettings( NULL, i++, &d ); + if ( !h ) break; + + //if ((d.dmPelsWidth * 9) / 16 != d.dmPelsHeight) continue; + if ( d.dmBitsPerPel != 32 ) continue; + if ( d.dmDisplayOrientation != DMDO_DEFAULT ) continue; + + if ( !gaResolutions.size() + || gaResolutions[ gaResolutions.size() - 1 ].nWidth != d.dmPelsWidth + || gaResolutions[ gaResolutions.size() - 1 ].nHeight != d.dmPelsHeight ) + { + RESOLUTION res; + res.nWidth = d.dmPelsWidth; + res.nHeight = d.dmPelsHeight; + gaResolutions.push_back( res ); + + } } - } - //std::sort(gaResolutions.begin(),gaResolutions.end(),&CSetupDialog::ResolutionSort); + //std::sort(gaResolutions.begin(),gaResolutions.end(),&CSetupDialog::ResolutionSort); - bool bFoundBest = false; - for (i=0; isRenderer.nWidth && gaResolutions[ i ].nHeight == setup->sRenderer.nHeight ) + { + SendDlgItemMessage( hWnd, IDC_RESOLUTION, CB_SETCURSEL, i, 0 ); + bFoundBest = true; + } + if ( !bFoundBest && gaResolutions[ i ].nWidth == GetSystemMetrics( SM_CXSCREEN ) && gaResolutions[ i ].nHeight == GetSystemMetrics( SM_CYSCREEN ) ) + { + SendDlgItemMessage( hWnd, IDC_RESOLUTION, CB_SETCURSEL, i, 0 ); + } + } - if (gaResolutions[i].nWidth == setup->sRenderer.nWidth && gaResolutions[i].nHeight == setup->sRenderer.nHeight) + if ( setup->sRenderer.windowMode == Renderer::WINDOWMODE_FULLSCREEN ) { - SendDlgItemMessage(hWnd, IDC_RESOLUTION, CB_SETCURSEL, i, 0); - bFoundBest = true; + SendDlgItemMessage( hWnd, IDC_FULLSCREEN, BM_SETCHECK, 1, 1 ); } - if (!bFoundBest && gaResolutions[i].nWidth == GetSystemMetrics(SM_CXSCREEN) && gaResolutions[i].nHeight == GetSystemMetrics(SM_CYSCREEN)) + if ( setup->sRenderer.bVsync ) { - SendDlgItemMessage(hWnd, IDC_RESOLUTION, CB_SETCURSEL, i, 0); + SendDlgItemMessage( hWnd, IDC_VSYNC, BM_SETCHECK, 1, 1 ); } - } - if (setup->sRenderer.windowMode == RENDERER_WINDOWMODE_FULLSCREEN) { - SendDlgItemMessage(hWnd, IDC_FULLSCREEN, BM_SETCHECK, 1, 1); - } - if (setup->sRenderer.bVsync) { - SendDlgItemMessage(hWnd, IDC_VSYNC, BM_SETCHECK, 1, 1); - } + FFT::EnumerateDevices( FFTDeviceEnum, this ); - FFT::EnumerateDevices( FFTDeviceEnum, this ); + return true; + } break; - return true; - } break; - - case WM_COMMAND: - { - switch( LOWORD(wParam) ) + case WM_COMMAND: { - case IDOK: + switch ( LOWORD( wParam ) ) { - setup->sRenderer.nWidth = gaResolutions[ SendDlgItemMessage(hWnd, IDC_RESOLUTION, CB_GETCURSEL, 0, 0) ].nWidth; - setup->sRenderer.nHeight = gaResolutions[ SendDlgItemMessage(hWnd, IDC_RESOLUTION, CB_GETCURSEL, 0, 0) ].nHeight; - setup->sRenderer.windowMode = SendDlgItemMessage(hWnd, IDC_FULLSCREEN, BM_GETCHECK , 0, 0) ? RENDERER_WINDOWMODE_FULLSCREEN : RENDERER_WINDOWMODE_WINDOWED; - setup->sRenderer.bVsync = SendDlgItemMessage(hWnd, IDC_VSYNC, BM_GETCHECK , 0, 0) > 0; - - setup->sFFT.bUseRecordingDevice = gaAudioDevices[ SendDlgItemMessage(hWnd, IDC_AUDIOSOURCE, CB_GETCURSEL, 0, 0) ].bIsCapture; - setup->sFFT.pDeviceID = gaAudioDevices[ SendDlgItemMessage(hWnd, IDC_AUDIOSOURCE, CB_GETCURSEL, 0, 0) ].pDeviceID; - EndDialog (hWnd, TRUE); - } break; - case IDCANCEL: - { - EndDialog (hWnd, FALSE); - } break; - } - } break; + case IDOK: + { + setup->sRenderer.nWidth = gaResolutions[ SendDlgItemMessage( hWnd, IDC_RESOLUTION, CB_GETCURSEL, 0, 0 ) ].nWidth; + setup->sRenderer.nHeight = gaResolutions[ SendDlgItemMessage( hWnd, IDC_RESOLUTION, CB_GETCURSEL, 0, 0 ) ].nHeight; + setup->sRenderer.windowMode = SendDlgItemMessage( hWnd, IDC_FULLSCREEN, BM_GETCHECK, 0, 0 ) ? Renderer::WINDOWMODE_FULLSCREEN : Renderer::WINDOWMODE_WINDOWED; + setup->sRenderer.bVsync = SendDlgItemMessage( hWnd, IDC_VSYNC, BM_GETCHECK, 0, 0 ) > 0; + + setup->sFFT.bUseRecordingDevice = gaAudioDevices[ SendDlgItemMessage( hWnd, IDC_AUDIOSOURCE, CB_GETCURSEL, 0, 0 ) ].bIsCapture; + setup->sFFT.pDeviceID = gaAudioDevices[ SendDlgItemMessage( hWnd, IDC_AUDIOSOURCE, CB_GETCURSEL, 0, 0 ) ].pDeviceID; + EndDialog( hWnd, TRUE ); + } break; + case IDCANCEL: + { + EndDialog( hWnd, FALSE ); + } break; + } + } break; } return false; } - bool Open(HINSTANCE hInstance, HWND hWnd) { - return DialogBoxParam(hInstance,MAKEINTRESOURCE(IDD_SETUP),hWnd,DlgFunc,(LPARAM)this) != NULL; + bool Open( HINSTANCE hInstance, HWND hWnd ) + { + return DialogBoxParam( hInstance, MAKEINTRESOURCE( IDD_SETUP ), hWnd, DlgFunc, (LPARAM) this ) != NULL; } }; -INT_PTR CALLBACK DlgFunc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +INT_PTR CALLBACK DlgFunc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - if (uMsg == WM_INITDIALOG) { - pGlobal = (CSetupDialog *)lParam; // todo: split to multiple hWnd-s! (if needed) + if ( uMsg == WM_INITDIALOG ) + { + pGlobal = (CSetupDialog *) lParam; // todo: split to multiple hWnd-s! (if needed) } - return pGlobal->DialogProcedure(hWnd,uMsg,wParam,lParam); + return pGlobal->DialogProcedure( hWnd, uMsg, wParam, lParam ); } bool Open( SetupDialog::SETTINGS * settings ) { CSetupDialog dlg; dlg.setup = settings; - return dlg.Open( GetModuleHandle(NULL), NULL ); + return dlg.Open( GetModuleHandle( NULL ), NULL ); } +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/platform_w32_common/Timer.cpp b/src/platform_w32_common/Timer.cpp index 97aacc9b..febc1b5a 100644 --- a/src/platform_w32_common/Timer.cpp +++ b/src/platform_w32_common/Timer.cpp @@ -2,33 +2,38 @@ namespace Timer { - LARGE_INTEGER LastPCV = { 0 } ; - double currentTime = 0.0; - double startTime = 0.0; +////////////////////////////////////////////////////////////////////////// - double _Time() +LARGE_INTEGER LastPCV = { 0 }; +double currentTime = 0.0; +double startTime = 0.0; + +double _Time() +{ + LARGE_INTEGER count, freq; + if ( !LastPCV.QuadPart ) { - LARGE_INTEGER count, freq; - if (!LastPCV.QuadPart) { - QueryPerformanceCounter(&LastPCV); - } - QueryPerformanceCounter(&count); - QueryPerformanceFrequency(&freq); + QueryPerformanceCounter( &LastPCV ); + } + QueryPerformanceCounter( &count ); + QueryPerformanceFrequency( &freq ); - currentTime += (double)(count.QuadPart - LastPCV.QuadPart) / (double)(freq.QuadPart); + currentTime += (double) ( count.QuadPart - LastPCV.QuadPart ) / (double) ( freq.QuadPart ); - LastPCV=count; + LastPCV = count; - return currentTime * 1000.0f; - } + return currentTime * 1000.0f; +} - void Start() - { - startTime = (float)_Time(); - } +void Start() +{ + startTime = (float) _Time(); +} - float GetTime() - { - return (float) ( _Time() - startTime ); - } +float GetTime() +{ + return (float) ( _Time() - startTime ); +} + +////////////////////////////////////////////////////////////////////////// } \ No newline at end of file diff --git a/src/platform_w32_dx11/Renderer.cpp b/src/platform_w32_dx11/Renderer.cpp index d571cfa3..c5c00d63 100644 --- a/src/platform_w32_dx11/Renderer.cpp +++ b/src/platform_w32_dx11/Renderer.cpp @@ -16,1242 +16,1245 @@ #include #include "Scintilla.h" +namespace Renderer +{ +////////////////////////////////////////////////////////////////////////// + const char * shaderKeyword = - " register packoffset static const" - " break continue discard do for if else switch while case default return true false" - " BINORMAL BINORMAL0 BINORMAL1 BINORMAL2 BINORMAL3 BINORMAL4 BINORMAL5 BINORMAL6 BINORMAL7" - " BLENDINDICES BLENDINDICES0 BLENDINDICES1 BLENDINDICES2 BLENDINDICES3 BLENDINDICES4 BLENDINDICES5 BLENDINDICES6 BLENDINDICES7" - " BLENDWEIGHT BLENDWEIGHT0 BLENDWEIGHT1 BLENDWEIGHT2 BLENDWEIGHT3 BLENDWEIGHT4 BLENDWEIGHT5 BLENDWEIGHT6 BLENDWEIGHT7" - " COLOR COLOR0 COLOR1 COLOR2 COLOR3 COLOR4 COLOR5 COLOR6 COLOR7" - " NORMAL NORMAL0 NORMAL1 NORMAL2 NORMAL3 NORMAL4 NORMAL5 NORMAL6 NORMAL7" - " POSITION POSITION0 POSITION1 POSITION2 POSITION3 POSITION4 POSITION5 POSITION6 POSITION7" - " POSITIONT" - " PSIZE PSIZE0 PSIZE1 PSIZE2 PSIZE3 PSIZE4 PSIZE5 PSIZE6 PSIZE7" - " TANGENT TANGENT0 TANGENT1 TANGENT2 TANGENT3 TANGENT4 TANGENT5 TANGENT6 TANGENT7" - " TEXCOORD TEXCOORD0 TEXCOORD1 TEXCOORD2 TEXCOORD3 TEXCOORD4 TEXCOORD5 TEXCOORD6 TEXCOORD7 TEXCOORD8 TEXCOORD9" - " TEXCOORD0 TEXCOORD1 TEXCOORD2 TEXCOORD3 TEXCOORD4 TEXCOORD5 TEXCOORD6 TEXCOORD7 TEXCOORD8 TEXCOORD9" - " SV_Coverage SV_Depth SV_DispatchThreadID SV_DomainLocation SV_GroupID SV_GroupIndex SV_GroupThreadID SV_GSInstanceID SV_InsideTessFactor SV_IsFrontFace SV_OutputControlPointID SV_POSITION SV_Position SV_RenderTargetArrayIndex SV_SampleIndex SV_TessFactor SV_ViewportArrayIndex SV_InstanceID SV_PrimitiveID SV_VertexID SV_TargetID" - " SV_TARGET SV_Target SV_Target0 SV_Target1 SV_Target2 SV_Target3 SV_Target4 SV_Target5 SV_Target6 SV_Target7" - " SV_ClipDistance0 SV_ClipDistance1 SV_ClipDistance2 SV_ClipDistance3 SV_ClipDistance4 SV_ClipDistance5 SV_ClipDistance6 SV_ClipDistance7" - " SV_CullDistance0 SV_CullDistance1 SV_CullDistance2 SV_CullDistance3 SV_CullDistance4 SV_CullDistance5 SV_CullDistance6 SV_CullDistance7"; - -const char * shaderType = - "bool bool1 bool2 bool3 bool4" - " bool1x1 bool1x2 bool1x3 bool1x4" - " bool2x1 bool2x2 bool2x3 bool2x4" - " bool3x1 bool3x2 bool3x3 bool3x4" - " bool4x1 bool4x2 bool4x3 bool4x4" - " int int1 int2 int3 int4" - " int1x1 int1x2 int1x3 int1x4" - " int2x1 int2x2 int2x3 int2x4" - " int3x1 int3x2 int3x3 int3x4" - " int4x1 int4x2 int4x3 int4x4" - " uint uint1 uint2 uint3 uint4" - " uint1x1 uint1x2 uint1x3 uint1x4" - " uint2x1 uint2x2 uint2x3 uint2x4" - " uint3x1 uint3x2 uint3x3 uint3x4" - " uint4x1 uint4x2 uint4x3 uint4x4" - " UINT UINT2 UINT3 UINT4" - " dword dword1 dword2 dword3 dword4" - " dword1x1 dword1x2 dword1x3 dword1x4" - " dword2x1 dword2x2 dword2x3 dword2x4" - " dword3x1 dword3x2 dword3x3 dword3x4" - " dword4x1 dword4x2 dword4x3 dword4x4" - " half half1 half2 half3 half4" - " half1x1 half1x2 half1x3 half1x4" - " half2x1 half2x2 half2x3 half2x4" - " half3x1 half3x2 half3x3 half3x4" - " half4x1 half4x2 half4x3 half4x4" - " float float1 float2 float3 float4" - " float1x1 float1x2 float1x3 float1x4" - " float2x1 float2x2 float2x3 float2x4" - " float3x1 float3x2 float3x3 float3x4" - " float4x1 float4x2 float4x3 float4x4" - " double double1 double2 double3 double4" - " double1x1 double1x2 double1x3 double1x4" - " double2x1 double2x2 double2x3 double2x4" - " double3x1 double3x2 double3x3 double3x4" - " double4x1 double4x2 double4x3 double4x4" - " snorm unorm string void cbuffer struct" - " Buffer AppendStructuredBfufer ByteAddressBuffer ConsumeStructuredBuffer StructuredBuffer" - " RWBuffer RWByteAddressBuffer RWStructuredBuffer RWTexture1D RWTexture1DArray RWTexture2D RWTexture2DArray RWTexture3D" - " InputPatch OutputPatch" - " linear centroid nointerpolation noperspective sample" - " sampler sampler1D sampler2D sampler3D samplerCUBE SamplerComparisonState SamplerState sampler_state" - " AddressU AddressV AddressW BorderColor Filter MaxAnisotropy MaxLOD MinLOD MipLODBias ComparisonFunc ComparisonFilter" - " texture Texture1D Texture1DArray Texture2D Texture2DArray Texture2DMS Texture2DMSArray Texture3D TextureCube"; +" register packoffset static const" +" break continue discard do for if else switch while case default return true false" +" BINORMAL BINORMAL0 BINORMAL1 BINORMAL2 BINORMAL3 BINORMAL4 BINORMAL5 BINORMAL6 BINORMAL7" +" BLENDINDICES BLENDINDICES0 BLENDINDICES1 BLENDINDICES2 BLENDINDICES3 BLENDINDICES4 BLENDINDICES5 BLENDINDICES6 BLENDINDICES7" +" BLENDWEIGHT BLENDWEIGHT0 BLENDWEIGHT1 BLENDWEIGHT2 BLENDWEIGHT3 BLENDWEIGHT4 BLENDWEIGHT5 BLENDWEIGHT6 BLENDWEIGHT7" +" COLOR COLOR0 COLOR1 COLOR2 COLOR3 COLOR4 COLOR5 COLOR6 COLOR7" +" NORMAL NORMAL0 NORMAL1 NORMAL2 NORMAL3 NORMAL4 NORMAL5 NORMAL6 NORMAL7" +" POSITION POSITION0 POSITION1 POSITION2 POSITION3 POSITION4 POSITION5 POSITION6 POSITION7" +" POSITIONT" +" PSIZE PSIZE0 PSIZE1 PSIZE2 PSIZE3 PSIZE4 PSIZE5 PSIZE6 PSIZE7" +" TANGENT TANGENT0 TANGENT1 TANGENT2 TANGENT3 TANGENT4 TANGENT5 TANGENT6 TANGENT7" +" TEXCOORD TEXCOORD0 TEXCOORD1 TEXCOORD2 TEXCOORD3 TEXCOORD4 TEXCOORD5 TEXCOORD6 TEXCOORD7 TEXCOORD8 TEXCOORD9" +" TEXCOORD0 TEXCOORD1 TEXCOORD2 TEXCOORD3 TEXCOORD4 TEXCOORD5 TEXCOORD6 TEXCOORD7 TEXCOORD8 TEXCOORD9" +" SV_Coverage SV_Depth SV_DispatchThreadID SV_DomainLocation SV_GroupID SV_GroupIndex SV_GroupThreadID SV_GSInstanceID SV_InsideTessFactor SV_IsFrontFace SV_OutputControlPointID SV_POSITION SV_Position SV_RenderTargetArrayIndex SV_SampleIndex SV_TessFactor SV_ViewportArrayIndex SV_InstanceID SV_PrimitiveID SV_VertexID SV_TargetID" +" SV_TARGET SV_Target SV_Target0 SV_Target1 SV_Target2 SV_Target3 SV_Target4 SV_Target5 SV_Target6 SV_Target7" +" SV_ClipDistance0 SV_ClipDistance1 SV_ClipDistance2 SV_ClipDistance3 SV_ClipDistance4 SV_ClipDistance5 SV_ClipDistance6 SV_ClipDistance7" +" SV_CullDistance0 SV_CullDistance1 SV_CullDistance2 SV_CullDistance3 SV_CullDistance4 SV_CullDistance5 SV_CullDistance6 SV_CullDistance7"; + +const char * shaderType = +"bool bool1 bool2 bool3 bool4" +" bool1x1 bool1x2 bool1x3 bool1x4" +" bool2x1 bool2x2 bool2x3 bool2x4" +" bool3x1 bool3x2 bool3x3 bool3x4" +" bool4x1 bool4x2 bool4x3 bool4x4" +" int int1 int2 int3 int4" +" int1x1 int1x2 int1x3 int1x4" +" int2x1 int2x2 int2x3 int2x4" +" int3x1 int3x2 int3x3 int3x4" +" int4x1 int4x2 int4x3 int4x4" +" uint uint1 uint2 uint3 uint4" +" uint1x1 uint1x2 uint1x3 uint1x4" +" uint2x1 uint2x2 uint2x3 uint2x4" +" uint3x1 uint3x2 uint3x3 uint3x4" +" uint4x1 uint4x2 uint4x3 uint4x4" +" UINT UINT2 UINT3 UINT4" +" dword dword1 dword2 dword3 dword4" +" dword1x1 dword1x2 dword1x3 dword1x4" +" dword2x1 dword2x2 dword2x3 dword2x4" +" dword3x1 dword3x2 dword3x3 dword3x4" +" dword4x1 dword4x2 dword4x3 dword4x4" +" half half1 half2 half3 half4" +" half1x1 half1x2 half1x3 half1x4" +" half2x1 half2x2 half2x3 half2x4" +" half3x1 half3x2 half3x3 half3x4" +" half4x1 half4x2 half4x3 half4x4" +" float float1 float2 float3 float4" +" float1x1 float1x2 float1x3 float1x4" +" float2x1 float2x2 float2x3 float2x4" +" float3x1 float3x2 float3x3 float3x4" +" float4x1 float4x2 float4x3 float4x4" +" double double1 double2 double3 double4" +" double1x1 double1x2 double1x3 double1x4" +" double2x1 double2x2 double2x3 double2x4" +" double3x1 double3x2 double3x3 double3x4" +" double4x1 double4x2 double4x3 double4x4" +" snorm unorm string void cbuffer struct" +" Buffer AppendStructuredBfufer ByteAddressBuffer ConsumeStructuredBuffer StructuredBuffer" +" RWBuffer RWByteAddressBuffer RWStructuredBuffer RWTexture1D RWTexture1DArray RWTexture2D RWTexture2DArray RWTexture3D" +" InputPatch OutputPatch" +" linear centroid nointerpolation noperspective sample" +" sampler sampler1D sampler2D sampler3D samplerCUBE SamplerComparisonState SamplerState sampler_state" +" AddressU AddressV AddressW BorderColor Filter MaxAnisotropy MaxLOD MinLOD MipLODBias ComparisonFunc ComparisonFilter" +" texture Texture1D Texture1DArray Texture2D Texture2DArray Texture2DMS Texture2DMSArray Texture3D TextureCube"; const char * shaderBuiltin = - "abs acos all AllMemoryBarrier AllMemoryBarrierWithGroupSync any asdouble" - " asfloat asin asint asuint atan atan2 ceil clamp clip cos cosh countbits" - " cross D3DCOLORtoUBYTE4 ddx ddx_coarse ddx_fine ddy ddy_coarse ddy_fine" - " degrees determinant DeviceMemoryBarrier DeviceMemoryBarrierWithGroupSync" - " distance dot dst EvaluateAttributeAtCentroid EvaluateAttributeAtSample" - " EvaluateAttributeSnapped exp exp2 f16tof32 f32tof16 faceforward firstbithigh" - " firstbitlow floor fmod frac frexp fwidth GetRenderTargetSampleCount" - " GetRenderTargetSamplePosition GroupMemoryBarrier GroupMemoryBarrierWithGroupSync" - " InterlockedAdd InterlockedAnd InterlockedCompareExchange InterlockedCompareStore" - " InterlockedExchange InterlockedMax InterlockedMin InterlockedOr InterlockedXor" - " isfinite isinf isnan ldexp length lerp lit log log10 log2 mad max min modf mul" - " noise normalize pow Process2DQuadTessFactorsAvg Process2DQuadTessFactorsMax" - " Process2DQuadTessFactorsMin ProcessIsolineTessFactors ProcessQuadTessFactorsAvg" - " ProcessQuadTessFactorsMax ProcessQuadTessFactorsMin ProcessTriTessFactorsAvg" - " ProcessTriTessFactorsMax ProcessTriTessFactorsMin radians rcp reflect refract" - " reversebits round rsqrt saturate sign sin sincos sinh smoothstep sqrt step" - " tan tanh tex1D tex1Dbias tex1Dgrad tex1Dlod tex1Dproj tex2D tex2Dbias" - " tex2Dgrad tex2Dlod tex2Dproj tex3D tex3Dbias tex3Dgrad tex3Dlod tex3Dproj" - " texCUBE texCUBEbias texCUBEgrad texCUBElod texCUBEproj transpose trunc"; - -namespace Renderer +"abs acos all AllMemoryBarrier AllMemoryBarrierWithGroupSync any asdouble" +" asfloat asin asint asuint atan atan2 ceil clamp clip cos cosh countbits" +" cross D3DCOLORtoUBYTE4 ddx ddx_coarse ddx_fine ddy ddy_coarse ddy_fine" +" degrees determinant DeviceMemoryBarrier DeviceMemoryBarrierWithGroupSync" +" distance dot dst EvaluateAttributeAtCentroid EvaluateAttributeAtSample" +" EvaluateAttributeSnapped exp exp2 f16tof32 f32tof16 faceforward firstbithigh" +" firstbitlow floor fmod frac frexp fwidth GetRenderTargetSampleCount" +" GetRenderTargetSamplePosition GroupMemoryBarrier GroupMemoryBarrierWithGroupSync" +" InterlockedAdd InterlockedAnd InterlockedCompareExchange InterlockedCompareStore" +" InterlockedExchange InterlockedMax InterlockedMin InterlockedOr InterlockedXor" +" isfinite isinf isnan ldexp length lerp lit log log10 log2 mad max min modf mul" +" noise normalize pow Process2DQuadTessFactorsAvg Process2DQuadTessFactorsMax" +" Process2DQuadTessFactorsMin ProcessIsolineTessFactors ProcessQuadTessFactorsAvg" +" ProcessQuadTessFactorsMax ProcessQuadTessFactorsMin ProcessTriTessFactorsAvg" +" ProcessTriTessFactorsMax ProcessTriTessFactorsMin radians rcp reflect refract" +" reversebits round rsqrt saturate sign sin sincos sinh smoothstep sqrt step" +" tan tanh tex1D tex1Dbias tex1Dgrad tex1Dlod tex1Dproj tex2D tex2Dbias" +" tex2Dgrad tex2Dlod tex2Dproj tex3D tex3Dbias tex3Dgrad tex3Dlod tex3Dproj" +" texCUBE texCUBEbias texCUBEgrad texCUBElod texCUBEproj transpose trunc"; + +const char * szDefaultShaderFilename = "shader.dx11.hlsl"; +const char szDefaultShader[ 65536 ] = +"{%textures:begin%}" // leave off \n here +"Texture2D {%textures:name%};\n" +"{%textures:end%}" // leave off \n here +"Texture1D texFFT; // towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq\n" +"Texture1D texFFTSmoothed; // this one has longer falloff and less harsh transients\n" +"Texture1D texFFTIntegrated; // this is continually increasing\n" +"Texture2D texPreviousFrame; // screenshot of the previous frame\n" +"SamplerState smp;\n" +"\n" +"cbuffer constants\n" +"{\n" +"\tfloat fGlobalTime; // in seconds\n" +"\tfloat2 v2Resolution; // viewport resolution (in pixels)\n" +"\tfloat fFrameTime; // duration of the last frame, in seconds\n" +"{%midi:begin%}" +"\tfloat {%midi:name%};\n" +"{%midi:end%}" +"}\n" +"\n" +"float4 plas( float2 v, float time )\n" +"{\n" +"\tfloat c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );\n" +"\treturn float4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );\n" +"}\n" +"\n" +"float4 main( float4 position : SV_POSITION, float2 TexCoord : TEXCOORD ) : SV_TARGET\n" +"{\n" +"\tfloat2 uv = TexCoord;\n" +"\tuv -= 0.5;\n" +"\tuv /= float2(v2Resolution.y / v2Resolution.x, 1);" +"\n" +"\tfloat2 m;\n" +"\tm.x = atan(uv.x / uv.y) / 3.14;\n" +"\tm.y = 1 / length(uv) * .2;\n" +"\tfloat d = m.y;\n" +"\n" +"\tfloat f = texFFT.Sample( smp, d ).r * 100;\n" +"\tm.x += sin( fGlobalTime ) * 0.1;\n" +"\tm.y += fGlobalTime * 0.25;\n" +"\n" +"\tfloat4 t = plas( m * 3.14, fGlobalTime ) / d;\n" +"\tt = saturate( t );\n" +"\treturn f + t;\n" +"}"; + +char defaultVertexShader[ 65536 ] = +"struct VS_INPUT_PP { float3 Pos : POSITION; float2 TexCoord : TEXCOORD; };\n" +"struct VS_OUTPUT_PP { float4 Pos : SV_POSITION; float2 TexCoord : TEXCOORD; };\n" +"\n" +"VS_OUTPUT_PP main( VS_INPUT_PP In )\n" +"{\n" +"\tVS_OUTPUT_PP Out;\n" +"\tOut.Pos = float4( In.Pos, 1.0 );\n" +"\tOut.TexCoord = In.TexCoord;\n" +"\treturn Out;\n" +"}\n"; + +bool run = true; + +IDXGISwapChain * pSwapChain = NULL; +ID3D11Device * pDevice = NULL; +ID3D11DeviceContext * pContext = NULL; +ID3D11RenderTargetView * pRenderTarget = NULL; +ID3D11VertexShader * pVertexShader = NULL; +ID3D11PixelShader * theShader = NULL; +ID3D11ShaderReflection * pShaderReflection = NULL; +ID3D11Texture2D * pBackBuffer = NULL; +ID3D11Texture2D * pFrameGrabTexture = NULL; + +int nWidth = 0; +int nHeight = 0; +HWND hWnd = NULL; + +KeyEvent keyEventBuffer[ 512 ]; +int keyEventBufferCount = 0; +MouseEvent mouseEventBuffer[ 512 ]; +int mouseEventBufferCount = 0; + +LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - const char * defaultShaderFilename = "shader.dx11.hlsl"; - const char defaultShader[65536] = - "{%textures:begin%}" // leave off \n here - "Texture2D {%textures:name%};\n" - "{%textures:end%}" // leave off \n here - "Texture1D texFFT; // towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq\n" - "Texture1D texFFTSmoothed; // this one has longer falloff and less harsh transients\n" - "Texture1D texFFTIntegrated; // this is continually increasing\n" - "Texture2D texPreviousFrame; // screenshot of the previous frame\n" - "SamplerState smp;\n" - "\n" - "cbuffer constants\n" - "{\n" - "\tfloat fGlobalTime; // in seconds\n" - "\tfloat2 v2Resolution; // viewport resolution (in pixels)\n" - "\tfloat fFrameTime; // duration of the last frame, in seconds\n" - "{%midi:begin%}" - "\tfloat {%midi:name%};\n" - "{%midi:end%}" - "}\n" - "\n" - "float4 plas( float2 v, float time )\n" - "{\n" - "\tfloat c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );\n" - "\treturn float4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );\n" - "}\n" - "\n" - "float4 main( float4 position : SV_POSITION, float2 TexCoord : TEXCOORD ) : SV_TARGET\n" - "{\n" - "\tfloat2 uv = TexCoord;\n" - "\tuv -= 0.5;\n" - "\tuv /= float2(v2Resolution.y / v2Resolution.x, 1);" - "\n" - "\tfloat2 m;\n" - "\tm.x = atan(uv.x / uv.y) / 3.14;\n" - "\tm.y = 1 / length(uv) * .2;\n" - "\tfloat d = m.y;\n" - "\n" - "\tfloat f = texFFT.Sample( smp, d ).r * 100;\n" - "\tm.x += sin( fGlobalTime ) * 0.1;\n" - "\tm.y += fGlobalTime * 0.25;\n" - "\n" - "\tfloat4 t = plas( m * 3.14, fGlobalTime ) / d;\n" - "\tt = saturate( t );\n" - "\treturn f + t;\n" - "}"; - - char defaultVertexShader[65536] = - "struct VS_INPUT_PP { float3 Pos : POSITION; float2 TexCoord : TEXCOORD; };\n" - "struct VS_OUTPUT_PP { float4 Pos : SV_POSITION; float2 TexCoord : TEXCOORD; };\n" - "\n" - "VS_OUTPUT_PP main( VS_INPUT_PP In )\n" - "{\n" - "\tVS_OUTPUT_PP Out;\n" - "\tOut.Pos = float4( In.Pos, 1.0 );\n" - "\tOut.TexCoord = In.TexCoord;\n" - "\treturn Out;\n" - "}\n"; - - bool run = true; - - IDXGISwapChain * pSwapChain = NULL; - ID3D11Device * pDevice = NULL; - ID3D11DeviceContext * pContext = NULL; - ID3D11RenderTargetView * pRenderTarget = NULL; - ID3D11VertexShader * pVertexShader = NULL; - ID3D11PixelShader * theShader = NULL; - ID3D11ShaderReflection * pShaderReflection = NULL; - ID3D11Texture2D * pBackBuffer = NULL; - ID3D11Texture2D * pFrameGrabTexture = NULL; - - int nWidth = 0; - int nHeight = 0; - HWND hWnd = NULL; - - KeyEvent keyEventBuffer[512]; - int keyEventBufferCount = 0; - MouseEvent mouseEventBuffer[512]; - int mouseEventBufferCount = 0; - - LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) + switch ( uMsg ) { - switch (uMsg) - { - case WM_KEYDOWN: + case WM_KEYDOWN: { int sciKey = 0; - switch(wParam) + switch ( wParam ) { - case VK_DOWN: sciKey = SCK_DOWN; break; - case VK_UP: sciKey = SCK_UP; break; - case VK_LEFT: sciKey = SCK_LEFT; break; - case VK_RIGHT: sciKey = SCK_RIGHT; break; - case VK_HOME: sciKey = SCK_HOME; break; - case VK_END: sciKey = SCK_END; break; - case VK_PRIOR: sciKey = SCK_PRIOR; break; - case VK_NEXT: sciKey = SCK_NEXT; break; - case VK_DELETE: sciKey = SCK_DELETE; break; - case VK_INSERT: sciKey = SCK_INSERT; break; - case VK_ESCAPE: sciKey = SCK_ESCAPE; break; - case VK_BACK: sciKey = SCK_BACK; break; - case VK_TAB: sciKey = SCK_TAB; break; - case VK_RETURN: sciKey = SCK_RETURN; break; -// case VK_KP_PLUS: sciKey = SCK_ADD; break; -// case VK_KP_MINUS: sciKey = SCK_SUBTRACT; break; -// case VK_KP_DIVIDE: sciKey = SCK_DIVIDE; break; -// case VK_LSUPER: sciKey = SCK_WIN; break; -// case VK_RSUPER: sciKey = SCK_RWIN; break; - case VK_MENU: sciKey = SCK_MENU; break; -// case VK_SLASH: sciKey = '/'; break; -// case VK_ASTERISK: sciKey = '`'; break; -// case VK_LEFTBRACKET: sciKey = '['; break; -// case VK_BACKSLASH: sciKey = '\\'; break; -// case VK_RIGHTBRACKET: sciKey = ']'; break; - case VK_F2: sciKey = 283; break; - case VK_F5: sciKey = 286; break; - case VK_F11: sciKey = 292; break; - case VK_SHIFT: - case VK_LSHIFT: - case VK_RSHIFT: - case VK_LMENU: - case VK_RMENU: - case VK_CONTROL: - case VK_LCONTROL: - case VK_RCONTROL: - sciKey = 0; - break; - default: - sciKey = wParam; + case VK_DOWN: sciKey = SCK_DOWN; break; + case VK_UP: sciKey = SCK_UP; break; + case VK_LEFT: sciKey = SCK_LEFT; break; + case VK_RIGHT: sciKey = SCK_RIGHT; break; + case VK_HOME: sciKey = SCK_HOME; break; + case VK_END: sciKey = SCK_END; break; + case VK_PRIOR: sciKey = SCK_PRIOR; break; + case VK_NEXT: sciKey = SCK_NEXT; break; + case VK_DELETE: sciKey = SCK_DELETE; break; + case VK_INSERT: sciKey = SCK_INSERT; break; + case VK_ESCAPE: sciKey = SCK_ESCAPE; break; + case VK_BACK: sciKey = SCK_BACK; break; + case VK_TAB: sciKey = SCK_TAB; break; + case VK_RETURN: sciKey = SCK_RETURN; break; + // case VK_KP_PLUS: sciKey = SCK_ADD; break; + // case VK_KP_MINUS: sciKey = SCK_SUBTRACT; break; + // case VK_KP_DIVIDE: sciKey = SCK_DIVIDE; break; + // case VK_LSUPER: sciKey = SCK_WIN; break; + // case VK_RSUPER: sciKey = SCK_RWIN; break; + case VK_MENU: sciKey = SCK_MENU; break; + // case VK_SLASH: sciKey = '/'; break; + // case VK_ASTERISK: sciKey = '`'; break; + // case VK_LEFTBRACKET: sciKey = '['; break; + // case VK_BACKSLASH: sciKey = '\\'; break; + // case VK_RIGHTBRACKET: sciKey = ']'; break; + case VK_F2: sciKey = 283; break; + case VK_F5: sciKey = 286; break; + case VK_F11: sciKey = 292; break; + case VK_SHIFT: + case VK_LSHIFT: + case VK_RSHIFT: + case VK_LMENU: + case VK_RMENU: + case VK_CONTROL: + case VK_LCONTROL: + case VK_RCONTROL: + sciKey = 0; + break; + default: + sciKey = wParam; } - if (sciKey) + if ( sciKey ) { - keyEventBuffer[keyEventBufferCount].ctrl = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL ); - keyEventBuffer[keyEventBufferCount].alt = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU ); - keyEventBuffer[keyEventBufferCount].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT ); - keyEventBuffer[keyEventBufferCount].scanCode = sciKey; - keyEventBuffer[keyEventBufferCount].character = 0; + keyEventBuffer[ keyEventBufferCount ].ctrl = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL ); + keyEventBuffer[ keyEventBufferCount ].alt = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU ); + keyEventBuffer[ keyEventBufferCount ].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT ); + keyEventBuffer[ keyEventBufferCount ].scanCode = sciKey; + keyEventBuffer[ keyEventBufferCount ].character = 0; keyEventBufferCount++; } //pKeys[wParam] = 1; } break; - case WM_CHAR: + case WM_CHAR: { - if (wParam >= 32) + if ( wParam >= 32 ) { - keyEventBuffer[keyEventBufferCount].ctrl = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL ); - keyEventBuffer[keyEventBufferCount].alt = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU ); - keyEventBuffer[keyEventBufferCount].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT ); - keyEventBuffer[keyEventBufferCount].scanCode = 0; - keyEventBuffer[keyEventBufferCount].character = wParam; + keyEventBuffer[ keyEventBufferCount ].ctrl = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL ); + keyEventBuffer[ keyEventBufferCount ].alt = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU ); + keyEventBuffer[ keyEventBufferCount ].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT ); + keyEventBuffer[ keyEventBufferCount ].scanCode = 0; + keyEventBuffer[ keyEventBufferCount ].character = wParam; keyEventBufferCount++; } //pKeys[wParam] = 1; } break; - case WM_KEYUP: + case WM_KEYUP: { //pKeys[wParam] = 0; } break; - case WM_LBUTTONDOWN: + case WM_LBUTTONDOWN: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_DOWN; - mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT; - mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam); - mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam); + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_DOWN; + mouseEventBuffer[ mouseEventBufferCount ].button = MOUSEBUTTON_LEFT; + mouseEventBuffer[ mouseEventBufferCount ].x = (float)GET_X_LPARAM( lParam ); + mouseEventBuffer[ mouseEventBufferCount ].y = (float)GET_Y_LPARAM( lParam ); mouseEventBufferCount++; } break; - case WM_MOUSEMOVE: + case WM_MOUSEMOVE: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_MOVE; - mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam); - mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam); + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_MOVE; + mouseEventBuffer[ mouseEventBufferCount ].x = (float)GET_X_LPARAM( lParam ); + mouseEventBuffer[ mouseEventBufferCount ].y = (float)GET_Y_LPARAM( lParam ); mouseEventBufferCount++; } break; - case WM_LBUTTONUP: + case WM_LBUTTONUP: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_UP; - mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT; - mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam); - mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam); + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_UP; + mouseEventBuffer[ mouseEventBufferCount ].button = MOUSEBUTTON_LEFT; + mouseEventBuffer[ mouseEventBufferCount ].x = (float)GET_X_LPARAM( lParam ); + mouseEventBuffer[ mouseEventBufferCount ].y = (float)GET_Y_LPARAM( lParam ); mouseEventBufferCount++; } break; case WM_MOUSEWHEEL: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_SCROLL; - mouseEventBuffer[mouseEventBufferCount].x = 0; - mouseEventBuffer[mouseEventBufferCount].y = GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA; + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_SCROLL; + mouseEventBuffer[ mouseEventBufferCount ].x = 0.0f; + mouseEventBuffer[ mouseEventBufferCount ].y = GET_WHEEL_DELTA_WPARAM( wParam ) / (float) WHEEL_DELTA; mouseEventBufferCount++; } break; case WM_MOUSEHWHEEL: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_SCROLL; - mouseEventBuffer[mouseEventBufferCount].x = -GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA; - mouseEventBuffer[mouseEventBufferCount].y = 0; + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_SCROLL; + mouseEventBuffer[ mouseEventBufferCount ].x = -GET_WHEEL_DELTA_WPARAM( wParam ) / (float) WHEEL_DELTA; + mouseEventBuffer[ mouseEventBufferCount ].y = 0.0f; mouseEventBufferCount++; } break; - case WM_SYSCOMMAND: + case WM_SYSCOMMAND: { - switch (wParam) + switch ( wParam ) { - case SC_SCREENSAVE: - case SC_MONITORPOWER: - { - return 0; - } + case SC_SCREENSAVE: + case SC_MONITORPOWER: + { + return 0; + } } } break; - case WM_CLOSE: + case WM_CLOSE: { run = false; } break; - } - - return DefWindowProc(hWnd, uMsg, wParam, lParam); } - bool InitWindow(RENDERER_SETTINGS * pSetup) - { - WNDCLASS WC; - - WC.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; - WC.lpfnWndProc = &WndProc; - WC.cbClsExtra = 0; - WC.cbWndExtra = 0; - WC.hInstance = GetModuleHandle(NULL); - //WC.hIcon = LoadIcon(setup->hInstance,MAKEINTRESOURCE(IDI_ICON1)); - WC.hIcon = NULL; - WC.hCursor = LoadCursor(NULL, IDC_ARROW); - WC.hbrBackground = NULL; - WC.lpszMenuName = NULL; - WC.lpszClassName = _T("fwzwnd"); - if(!RegisterClass(&WC)) return 0; - - DWORD wExStyle = WS_EX_APPWINDOW; - DWORD wStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; - if (pSetup->windowMode == RENDERER_WINDOWMODE_WINDOWED) wStyle |= WS_OVERLAPPED | WS_CAPTION; - - RECT wr={0,0,pSetup->nWidth,pSetup->nHeight}; - AdjustWindowRectEx(&wr, wStyle, FALSE, wExStyle); - - hWnd = CreateWindowEx(wExStyle,_T("fwzwnd"),_T("BONZOMATIC - Direct3D 11.0 edition"),wStyle, - (GetSystemMetrics(SM_CXSCREEN) - pSetup->nWidth )/2, - (GetSystemMetrics(SM_CYSCREEN) - pSetup->nHeight)/2, - wr.right-wr.left, wr.bottom-wr.top, - NULL, NULL, WC.hInstance, NULL); - - if (!hWnd) - return false; - - ShowWindow(hWnd, SW_SHOW); - SetForegroundWindow(hWnd); - SetFocus(hWnd); - - return true; - } + return DefWindowProc( hWnd, uMsg, wParam, lParam ); +} + +bool InitWindow( Renderer::Settings * pSetup ) +{ + WNDCLASS WC; + + WC.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; + WC.lpfnWndProc = &WndProc; + WC.cbClsExtra = 0; + WC.cbWndExtra = 0; + WC.hInstance = GetModuleHandle( NULL ); + //WC.hIcon = LoadIcon(setup->hInstance,MAKEINTRESOURCE(IDI_ICON1)); + WC.hIcon = NULL; + WC.hCursor = LoadCursor( NULL, IDC_ARROW ); + WC.hbrBackground = NULL; + WC.lpszMenuName = NULL; + WC.lpszClassName = _T( "fwzwnd" ); + if ( !RegisterClass( &WC ) ) return 0; + + DWORD wExStyle = WS_EX_APPWINDOW; + DWORD wStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; + if ( pSetup->windowMode == WINDOWMODE_WINDOWED ) wStyle |= WS_OVERLAPPED | WS_CAPTION; + + RECT wr = { 0,0,pSetup->nWidth,pSetup->nHeight }; + AdjustWindowRectEx( &wr, wStyle, FALSE, wExStyle ); + + hWnd = CreateWindowEx( wExStyle, _T( "fwzwnd" ), _T( "BONZOMATIC - Direct3D 11.0 edition" ), wStyle, + ( GetSystemMetrics( SM_CXSCREEN ) - pSetup->nWidth ) / 2, + ( GetSystemMetrics( SM_CYSCREEN ) - pSetup->nHeight ) / 2, + wr.right - wr.left, wr.bottom - wr.top, + NULL, NULL, WC.hInstance, NULL ); + + if ( !hWnd ) + return false; + + ShowWindow( hWnd, SW_SHOW ); + SetForegroundWindow( hWnd ); + SetFocus( hWnd ); + + return true; +} - bool bVsync = false; - bool InitDirect3D(RENDERER_SETTINGS * pSetup) +bool bVsync = false; +bool InitDirect3D( Renderer::Settings * pSetup ) +{ + DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; + + DXGI_SWAP_CHAIN_DESC desc; + ZeroMemory( &desc, sizeof( DXGI_SWAP_CHAIN_DESC ) ); + desc.BufferCount = 1; + desc.BufferDesc.Width = pSetup->nWidth; + desc.BufferDesc.Height = pSetup->nHeight; + desc.BufferDesc.Format = format; + if ( pSetup->bVsync ) { - DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; - - DXGI_SWAP_CHAIN_DESC desc; - ZeroMemory(&desc, sizeof(DXGI_SWAP_CHAIN_DESC)); - desc.BufferCount = 1; - desc.BufferDesc.Width = pSetup->nWidth; - desc.BufferDesc.Height = pSetup->nHeight; - desc.BufferDesc.Format = format; - if (pSetup->bVsync) + bVsync = true; + IDXGIFactory1 * pFactory = NULL; + HRESULT hr = CreateDXGIFactory1( __uuidof( IDXGIFactory1 ), (void **) &pFactory ); + if ( pFactory ) { - bVsync = true; - IDXGIFactory1 * pFactory = NULL; - HRESULT hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&pFactory); - if (pFactory) + IDXGIAdapter1 * pAdapter = NULL; + pFactory->EnumAdapters1( 0, &pAdapter ); + if ( pAdapter ) { - IDXGIAdapter1 * pAdapter = NULL; - pFactory->EnumAdapters1( 0, &pAdapter ); - if (pAdapter) + IDXGIOutput * pOutput = NULL; + pAdapter->EnumOutputs( 0, &pOutput ); + if ( pOutput ) { - IDXGIOutput * pOutput = NULL; - pAdapter->EnumOutputs( 0, &pOutput ); - if (pOutput) - { - unsigned int nModeCount = 0; - pOutput->GetDisplayModeList( format, DXGI_ENUM_MODES_INTERLACED | DXGI_ENUM_MODES_SCALING, &nModeCount, NULL); + unsigned int nModeCount = 0; + pOutput->GetDisplayModeList( format, DXGI_ENUM_MODES_INTERLACED | DXGI_ENUM_MODES_SCALING, &nModeCount, NULL ); - DXGI_MODE_DESC * pModes = new DXGI_MODE_DESC[ nModeCount ]; - pOutput->GetDisplayModeList( format, DXGI_ENUM_MODES_INTERLACED | DXGI_ENUM_MODES_SCALING, &nModeCount, pModes); + DXGI_MODE_DESC * pModes = new DXGI_MODE_DESC[ nModeCount ]; + pOutput->GetDisplayModeList( format, DXGI_ENUM_MODES_INTERLACED | DXGI_ENUM_MODES_SCALING, &nModeCount, pModes ); - for (unsigned int i=0; inWidth && pModes[ i ].Height == pSetup->nHeight ) { - if (pModes[i].Width == pSetup->nWidth && pModes[i].Height == pSetup->nHeight) - { - desc.BufferDesc = pModes[i]; - break; - } + desc.BufferDesc = pModes[ i ]; + break; } - delete[] pModes; - - pOutput->Release(); } + delete[] pModes; - pAdapter->Release(); + pOutput->Release(); } - pFactory->Release(); + pAdapter->Release(); } + + pFactory->Release(); } - desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - desc.OutputWindow = hWnd; - desc.SampleDesc.Count = 1; - desc.Windowed = pSetup->windowMode != RENDERER_WINDOWMODE_FULLSCREEN; + } + desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + desc.OutputWindow = hWnd; + desc.SampleDesc.Count = 1; + desc.Windowed = pSetup->windowMode != WINDOWMODE_FULLSCREEN; - DWORD deviceCreationFlags = 0; + DWORD deviceCreationFlags = 0; #ifdef _DEBUG - deviceCreationFlags |= D3D11_CREATE_DEVICE_DEBUG; + deviceCreationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif - if (D3D11CreateDeviceAndSwapChain( - NULL, - D3D_DRIVER_TYPE_HARDWARE, - NULL, - deviceCreationFlags, - NULL, - NULL, - D3D11_SDK_VERSION, - &desc, - &pSwapChain, - &pDevice, - NULL, - &pContext) != S_OK) - { - printf("[Renderer] D3D11CreateDeviceAndSwapChain failed\n"); - return false; - } + if ( D3D11CreateDeviceAndSwapChain( + NULL, + D3D_DRIVER_TYPE_HARDWARE, + NULL, + deviceCreationFlags, + NULL, + NULL, + D3D11_SDK_VERSION, + &desc, + &pSwapChain, + &pDevice, + NULL, + &pContext ) != S_OK ) + { + printf( "[Renderer] D3D11CreateDeviceAndSwapChain failed\n" ); + return false; + } - pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer); + pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), (void **) &pBackBuffer ); - pDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRenderTarget); - pBackBuffer->Release(); + pDevice->CreateRenderTargetView( pBackBuffer, NULL, &pRenderTarget ); + pBackBuffer->Release(); - pContext->OMSetRenderTargets(1, &pRenderTarget, NULL); + pContext->OMSetRenderTargets( 1, &pRenderTarget, NULL ); - // create staging texture for frame grabbing + // create staging texture for frame grabbing - D3D11_TEXTURE2D_DESC description; - pBackBuffer->GetDesc( &description ); - description.BindFlags = 0; - description.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE; - description.Usage = D3D11_USAGE_STAGING; + D3D11_TEXTURE2D_DESC description; + pBackBuffer->GetDesc( &description ); + description.BindFlags = 0; + description.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE; + description.Usage = D3D11_USAGE_STAGING; - HRESULT hr = pDevice->CreateTexture2D( &description, NULL, &pFrameGrabTexture ); + HRESULT hr = pDevice->CreateTexture2D( &description, NULL, &pFrameGrabTexture ); - return true; - } + return true; +} - ID3D11Buffer * pFullscreenQuadVB = NULL; - ID3D11InputLayout * pFullscreenQuadLayout = NULL; - ID3D11SamplerState * pFullscreenQuadSamplerState = NULL; - ID3D11Buffer * pFullscreenQuadConstantBuffer = NULL; +ID3D11Buffer * pFullscreenQuadVB = NULL; +ID3D11InputLayout * pFullscreenQuadLayout = NULL; +ID3D11SamplerState * pFullscreenQuadSamplerState = NULL; +ID3D11Buffer * pFullscreenQuadConstantBuffer = NULL; #define FULLSCREENQUADCONSTANTS_SIZE 512 - unsigned char pFullscreenQuadConstants[FULLSCREENQUADCONSTANTS_SIZE]; - ID3D11BlendState* pFullscreenQuadBlendState = NULL; - ID3D11RasterizerState * pFullscreenQuadRasterizerState = NULL; +unsigned char pFullscreenQuadConstants[ FULLSCREENQUADCONSTANTS_SIZE ]; +ID3D11BlendState * pFullscreenQuadBlendState = NULL; +ID3D11RasterizerState * pFullscreenQuadRasterizerState = NULL; - bool InitD3D11QuadRendering( RENDERER_SETTINGS * settings ) +bool InitD3D11QuadRendering( Renderer::Settings * settings ) +{ + ID3DBlob * pCode = NULL; + ID3DBlob * pErrors = NULL; + if ( D3DCompile( defaultVertexShader, strlen( defaultVertexShader ), NULL, NULL, NULL, "main", "vs_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK ) { - ID3DBlob * pCode = NULL; - ID3DBlob * pErrors = NULL; - if (D3DCompile( defaultVertexShader, strlen(defaultVertexShader), NULL, NULL, NULL, "main", "vs_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK) - { - printf("[Renderer] D3DCompile failed\n"); - return false; - } + printf( "[Renderer] D3DCompile failed\n" ); + return false; + } - if (pDevice->CreateVertexShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pVertexShader ) != S_OK) - { - printf("[Renderer] CreateVertexShader failed\n"); - return false; - } + if ( pDevice->CreateVertexShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pVertexShader ) != S_OK ) + { + printf( "[Renderer] CreateVertexShader failed\n" ); + return false; + } - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// - static float pQuad[] = { - -1.0, -1.0, 0.5, 0.0, 0.0, - -1.0, 1.0, 0.5, 0.0, 1.0, - 1.0, -1.0, 0.5, 1.0, 0.0, - 1.0, 1.0, 0.5, 1.0, 1.0, - }; + static float pQuad[] = { + -1.0, -1.0, 0.5, 0.0, 0.0, + -1.0, 1.0, 0.5, 0.0, 1.0, + 1.0, -1.0, 0.5, 1.0, 0.0, + 1.0, 1.0, 0.5, 1.0, 1.0, + }; - D3D11_BUFFER_DESC desc; - ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC)); + D3D11_BUFFER_DESC desc; + ZeroMemory( &desc, sizeof( D3D11_BUFFER_DESC ) ); - desc.ByteWidth = sizeof(float) * 5 * 4; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.ByteWidth = sizeof( float ) * 5 * 4; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - D3D11_SUBRESOURCE_DATA subData; - ZeroMemory(&subData, sizeof(D3D11_SUBRESOURCE_DATA)); - subData.pSysMem = pQuad; + D3D11_SUBRESOURCE_DATA subData; + ZeroMemory( &subData, sizeof( D3D11_SUBRESOURCE_DATA ) ); + subData.pSysMem = pQuad; - if (pDevice->CreateBuffer(&desc, &subData, &pFullscreenQuadVB) != S_OK) - { - printf("[Renderer] CreateBuffer failed\n"); - return false; - } + if ( pDevice->CreateBuffer( &desc, &subData, &pFullscreenQuadVB ) != S_OK ) + { + printf( "[Renderer] CreateBuffer failed\n" ); + return false; + } - static D3D11_INPUT_ELEMENT_DESC pQuadDesc[] = - { - {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT , 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, - }; + static D3D11_INPUT_ELEMENT_DESC pQuadDesc[] = + { + {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0 * sizeof( float ), D3D11_INPUT_PER_VERTEX_DATA, 0}, + {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT , 0, 3 * sizeof( float ), D3D11_INPUT_PER_VERTEX_DATA, 0}, + }; - if (pDevice->CreateInputLayout( pQuadDesc, 2, pCode->GetBufferPointer(), pCode->GetBufferSize(), &pFullscreenQuadLayout) != S_OK) - { - printf("[Renderer] CreateInputLayout failed\n"); - return false; - } + if ( pDevice->CreateInputLayout( pQuadDesc, 2, pCode->GetBufferPointer(), pCode->GetBufferSize(), &pFullscreenQuadLayout ) != S_OK ) + { + printf( "[Renderer] CreateInputLayout failed\n" ); + return false; + } - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// - D3D11_VIEWPORT viewport; - ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT)); + D3D11_VIEWPORT viewport; + ZeroMemory( &viewport, sizeof( D3D11_VIEWPORT ) ); - viewport.TopLeftX = 0; - viewport.TopLeftY = 0; - viewport.Width = settings->nWidth; - viewport.Height = settings->nHeight; + viewport.TopLeftX = 0; + viewport.TopLeftY = 0; + viewport.Width = settings->nWidth; + viewport.Height = settings->nHeight; - pContext->RSSetViewports(1, &viewport); + pContext->RSSetViewports( 1, &viewport ); - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// - D3D11_SAMPLER_DESC sampDesc = CD3D11_SAMPLER_DESC( CD3D11_DEFAULT() ); - sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; - sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; - sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; - sampDesc.Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; - if (pDevice->CreateSamplerState( &sampDesc, &pFullscreenQuadSamplerState ) != S_OK) - return false; + D3D11_SAMPLER_DESC sampDesc = CD3D11_SAMPLER_DESC( CD3D11_DEFAULT() ); + sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; + sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; + sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; + sampDesc.Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; + if ( pDevice->CreateSamplerState( &sampDesc, &pFullscreenQuadSamplerState ) != S_OK ) + return false; - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// - D3D11_BUFFER_DESC cbDesc; - ZeroMemory( &cbDesc, sizeof(D3D11_BUFFER_DESC) ); - cbDesc.ByteWidth = sizeof( pFullscreenQuadConstants ); - cbDesc.Usage = D3D11_USAGE_DYNAMIC; - cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; - cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + D3D11_BUFFER_DESC cbDesc; + ZeroMemory( &cbDesc, sizeof( D3D11_BUFFER_DESC ) ); + cbDesc.ByteWidth = sizeof( pFullscreenQuadConstants ); + cbDesc.Usage = D3D11_USAGE_DYNAMIC; + cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - ZeroMemory( &subData, sizeof(D3D11_SUBRESOURCE_DATA) ); - subData.pSysMem = &pFullscreenQuadConstants; + ZeroMemory( &subData, sizeof( D3D11_SUBRESOURCE_DATA ) ); + subData.pSysMem = &pFullscreenQuadConstants; - if (pDevice->CreateBuffer( &cbDesc, &subData, &pFullscreenQuadConstantBuffer ) != S_OK) - return false; + if ( pDevice->CreateBuffer( &cbDesc, &subData, &pFullscreenQuadConstantBuffer ) != S_OK ) + return false; - ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// - D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC( CD3D11_DEFAULT() ); - if (pDevice->CreateBlendState( &blendDesc, &pFullscreenQuadBlendState ) != S_OK) - return false; + D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC( CD3D11_DEFAULT() ); + if ( pDevice->CreateBlendState( &blendDesc, &pFullscreenQuadBlendState ) != S_OK ) + return false; - D3D11_RASTERIZER_DESC rastDesc = CD3D11_RASTERIZER_DESC( CD3D11_DEFAULT() ); - if (pDevice->CreateRasterizerState( &rastDesc, &pFullscreenQuadRasterizerState ) != S_OK) - return false; + D3D11_RASTERIZER_DESC rastDesc = CD3D11_RASTERIZER_DESC( CD3D11_DEFAULT() ); + if ( pDevice->CreateRasterizerState( &rastDesc, &pFullscreenQuadRasterizerState ) != S_OK ) + return false; - return true; - } + return true; +} #define GUIQUADVB_SIZE (1024 * 6) - char defaultGUIPixelShader[65536] = - "Texture2D tex;\n" - "SamplerState smp;\n" - "float4 main( float4 position : SV_POSITION, float4 Color: COLOR, float2 TexCoord : TEXCOORD0, float Factor : TEXCOORD1 ) : SV_TARGET\n" - "{\n" - " float4 v4Texture = Color * tex.Sample(smp,TexCoord);//float4( Color.rgb, Color.a * .a );\n" - " float4 v4Color = Color;\n" - " return lerp( v4Texture, v4Color, Factor );\n" - "}\n"; - char defaultGUIVertexShader[65536] = - "struct VS_INPUT_PP { float3 Pos : POSITION; float4 Color: COLOR; float2 TexCoord : TEXCOORD0; float Factor : TEXCOORD1; };\n" - "struct VS_OUTPUT_PP { float4 Pos : SV_POSITION; float4 Color: COLOR; float2 TexCoord : TEXCOORD0; float Factor : TEXCOORD1; };\n" - "\n" - "cbuffer c { float4x4 matProj; float2 v2Offset; }\n" - "\n" - "VS_OUTPUT_PP main( VS_INPUT_PP In )\n" - "{\n" - " VS_OUTPUT_PP Out;\n" - " Out.Pos = float4( In.Pos + float3(v2Offset,0), 1.0 );\n" - " Out.Pos = mul( Out.Pos, matProj );\n" - " Out.Color = In.Color;\n" - " Out.TexCoord = In.TexCoord;\n" - " Out.Factor = In.Factor;\n" - " return Out;\n" - "}\n"; - - ID3D11VertexShader * pGUIVertexShader = NULL; - ID3D11PixelShader * pGUIPixelShader = NULL; - ID3D11Buffer * pGUIQuadVB = NULL; - ID3D11InputLayout * pGUIQuadLayout = NULL; - ID3D11Buffer * pGUIConstantBuffer = NULL; - ID3D11BlendState* pGUIBlendState = NULL; - ID3D11RasterizerState * pGUIRasterizerState = NULL; - float pGUIMatrix[ 4 * 4 + 16 ]; - - void MatrixOrthoOffCenterLH(float * pout, FLOAT l, FLOAT r, FLOAT b, FLOAT t, FLOAT zn, FLOAT zf) +char defaultGUIPixelShader[ 65536 ] = +"Texture2D tex;\n" +"SamplerState smp;\n" +"float4 main( float4 position : SV_POSITION, float4 Color: COLOR, float2 TexCoord : TEXCOORD0, float Factor : TEXCOORD1 ) : SV_TARGET\n" +"{\n" +" float4 v4Texture = Color * tex.Sample(smp,TexCoord);//float4( Color.rgb, Color.a * .a );\n" +" float4 v4Color = Color;\n" +" return lerp( v4Texture, v4Color, Factor );\n" +"}\n"; +char defaultGUIVertexShader[ 65536 ] = +"struct VS_INPUT_PP { float3 Pos : POSITION; float4 Color: COLOR; float2 TexCoord : TEXCOORD0; float Factor : TEXCOORD1; };\n" +"struct VS_OUTPUT_PP { float4 Pos : SV_POSITION; float4 Color: COLOR; float2 TexCoord : TEXCOORD0; float Factor : TEXCOORD1; };\n" +"\n" +"cbuffer c { float4x4 matProj; float2 v2Offset; }\n" +"\n" +"VS_OUTPUT_PP main( VS_INPUT_PP In )\n" +"{\n" +" VS_OUTPUT_PP Out;\n" +" Out.Pos = float4( In.Pos + float3(v2Offset,0), 1.0 );\n" +" Out.Pos = mul( Out.Pos, matProj );\n" +" Out.Color = In.Color;\n" +" Out.TexCoord = In.TexCoord;\n" +" Out.Factor = In.Factor;\n" +" return Out;\n" +"}\n"; + +ID3D11VertexShader * pGUIVertexShader = NULL; +ID3D11PixelShader * pGUIPixelShader = NULL; +ID3D11Buffer * pGUIQuadVB = NULL; +ID3D11InputLayout * pGUIQuadLayout = NULL; +ID3D11Buffer * pGUIConstantBuffer = NULL; +ID3D11BlendState * pGUIBlendState = NULL; +ID3D11RasterizerState * pGUIRasterizerState = NULL; +float pGUIMatrix[ 4 * 4 + 16 ]; + +void MatrixOrthoOffCenterLH( float * pout, FLOAT l, FLOAT r, FLOAT b, FLOAT t, FLOAT zn, FLOAT zf ) +{ + ZeroMemory( pout, sizeof( float ) * 4 * 4 ); + pout[ 0 + 0 * 4 ] = 2.0f / ( r - l ); + pout[ 1 + 1 * 4 ] = 2.0f / ( t - b ); + pout[ 2 + 2 * 4 ] = 1.0f / ( zf - zn ); + pout[ 3 + 0 * 4 ] = -1.0f - 2.0f * l / ( r - l ); + pout[ 3 + 1 * 4 ] = 1.0f + 2.0f * t / ( b - t ); + pout[ 3 + 2 * 4 ] = zn / ( zn - zf ); + pout[ 3 + 3 * 4 ] = 1.0; +} + +bool InitD3D11GUIRendering( Renderer::Settings * settings ) +{ + ID3DBlob * pCode = NULL; + ID3DBlob * pErrors = NULL; + if ( D3DCompile( defaultGUIPixelShader, strlen( defaultGUIPixelShader ), NULL, NULL, NULL, "main", "ps_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK ) { - ZeroMemory( pout, sizeof(float) * 4 * 4 ); - pout[0 + 0 * 4] = 2.0f / (r - l); - pout[1 + 1 * 4] = 2.0f / (t - b); - pout[2 + 2 * 4] = 1.0f / (zf -zn); - pout[3 + 0 * 4] = -1.0f -2.0f *l / (r - l); - pout[3 + 1 * 4] = 1.0f + 2.0f * t / (b - t); - pout[3 + 2 * 4] = zn / (zn -zf); - pout[3 + 3 * 4] = 1.0; + printf( "[Renderer] D3DCompile (PS) failed\n" ); + return false; } - bool InitD3D11GUIRendering( RENDERER_SETTINGS * settings ) + if ( pDevice->CreatePixelShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pGUIPixelShader ) != S_OK ) { - ID3DBlob * pCode = NULL; - ID3DBlob * pErrors = NULL; - if (D3DCompile( defaultGUIPixelShader, strlen(defaultGUIPixelShader), NULL, NULL, NULL, "main", "ps_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK) - { - printf("[Renderer] D3DCompile (PS) failed\n"); - return false; - } - - if (pDevice->CreatePixelShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pGUIPixelShader ) != S_OK) - { - printf("[Renderer] CreatePixelShader failed\n"); - return false; - } - - if (D3DCompile( defaultGUIVertexShader, strlen(defaultGUIVertexShader), NULL, NULL, NULL, "main", "vs_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK) - { - printf("[Renderer] D3DCompile (VS) failed\n"); - return false; - } - - if (pDevice->CreateVertexShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pGUIVertexShader ) != S_OK) - { - printf("[Renderer] CreateVertexShader failed\n"); - return false; - } - - D3D11_BUFFER_DESC desc; - ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC)); + printf( "[Renderer] CreatePixelShader failed\n" ); + return false; + } - desc.ByteWidth = sizeof(float) * 7 * GUIQUADVB_SIZE; - desc.Usage = D3D11_USAGE_DYNAMIC; - desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; - desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if ( D3DCompile( defaultGUIVertexShader, strlen( defaultGUIVertexShader ), NULL, NULL, NULL, "main", "vs_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK ) + { + printf( "[Renderer] D3DCompile (VS) failed\n" ); + return false; + } - if (pDevice->CreateBuffer(&desc, NULL, &pGUIQuadVB) != S_OK) - { - printf("[Renderer] CreateBuffer (VB) failed\n"); - return false; - } + if ( pDevice->CreateVertexShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pGUIVertexShader ) != S_OK ) + { + printf( "[Renderer] CreateVertexShader failed\n" ); + return false; + } - static D3D11_INPUT_ELEMENT_DESC pGUIDesc[] = - { - {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"COLOR" , 0, DXGI_FORMAT_R8G8B8A8_UNORM , 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT , 0, 4 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"TEXCOORD", 1, DXGI_FORMAT_R32_FLOAT , 0, 6 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0}, - }; + D3D11_BUFFER_DESC desc; + ZeroMemory( &desc, sizeof( D3D11_BUFFER_DESC ) ); - if (pDevice->CreateInputLayout( pGUIDesc, 4, pCode->GetBufferPointer(), pCode->GetBufferSize(), &pGUIQuadLayout) != S_OK) - { - printf("[Renderer] CreateInputLayout failed\n"); - return false; - } + desc.ByteWidth = sizeof( float ) * 7 * GUIQUADVB_SIZE; + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - D3D11_BUFFER_DESC cbDesc; - ZeroMemory( &cbDesc, sizeof(D3D11_BUFFER_DESC) ); - cbDesc.ByteWidth = sizeof( float ) * 4 * 4 * 2; - cbDesc.Usage = D3D11_USAGE_DYNAMIC; - cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; - cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if ( pDevice->CreateBuffer( &desc, NULL, &pGUIQuadVB ) != S_OK ) + { + printf( "[Renderer] CreateBuffer (VB) failed\n" ); + return false; + } - MatrixOrthoOffCenterLH( pGUIMatrix, 0, nWidth, nHeight, 0, -1.0f, 1.0f ); - - D3D11_SUBRESOURCE_DATA subData; - ZeroMemory( &subData, sizeof(D3D11_SUBRESOURCE_DATA) ); - subData.pSysMem = &pGUIMatrix; + static D3D11_INPUT_ELEMENT_DESC pGUIDesc[] = + { + {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0 * sizeof( float ), D3D11_INPUT_PER_VERTEX_DATA, 0}, + {"COLOR" , 0, DXGI_FORMAT_R8G8B8A8_UNORM , 0, 3 * sizeof( float ), D3D11_INPUT_PER_VERTEX_DATA, 0}, + {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT , 0, 4 * sizeof( float ), D3D11_INPUT_PER_VERTEX_DATA, 0}, + {"TEXCOORD", 1, DXGI_FORMAT_R32_FLOAT , 0, 6 * sizeof( float ), D3D11_INPUT_PER_VERTEX_DATA, 0}, + }; - if (pDevice->CreateBuffer( &cbDesc, &subData, &pGUIConstantBuffer ) != S_OK) - { - printf("[Renderer] CreateBuffer (CB) failed\n"); - return false; - } + if ( pDevice->CreateInputLayout( pGUIDesc, 4, pCode->GetBufferPointer(), pCode->GetBufferSize(), &pGUIQuadLayout ) != S_OK ) + { + printf( "[Renderer] CreateInputLayout failed\n" ); + return false; + } - D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC( CD3D11_DEFAULT() ); - blendDesc.RenderTarget[0].BlendEnable = true; - blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; - blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; - if (pDevice->CreateBlendState( &blendDesc, &pGUIBlendState ) != S_OK) - return false; + D3D11_BUFFER_DESC cbDesc; + ZeroMemory( &cbDesc, sizeof( D3D11_BUFFER_DESC ) ); + cbDesc.ByteWidth = sizeof( float ) * 4 * 4 * 2; + cbDesc.Usage = D3D11_USAGE_DYNAMIC; + cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - D3D11_RASTERIZER_DESC rastDesc = CD3D11_RASTERIZER_DESC( CD3D11_DEFAULT() ); - rastDesc.ScissorEnable = true; - if (pDevice->CreateRasterizerState( &rastDesc, &pGUIRasterizerState ) != S_OK) - return false; + MatrixOrthoOffCenterLH( pGUIMatrix, 0, nWidth, nHeight, 0, -1.0f, 1.0f ); - return true; - } + D3D11_SUBRESOURCE_DATA subData; + ZeroMemory( &subData, sizeof( D3D11_SUBRESOURCE_DATA ) ); + subData.pSysMem = &pGUIMatrix; - bool Open( RENDERER_SETTINGS * settings ) + if ( pDevice->CreateBuffer( &cbDesc, &subData, &pGUIConstantBuffer ) != S_OK ) { - nWidth = settings->nWidth; - nHeight = settings->nHeight; - - if (!InitWindow(settings)) - { - printf("[Renderer] InitWindow failed\n"); - return false; - } + printf( "[Renderer] CreateBuffer (CB) failed\n" ); + return false; + } - if (!InitDirect3D(settings)) - { - printf("[Renderer] InitDirect3D failed\n"); - return false; - } + D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC( CD3D11_DEFAULT() ); + blendDesc.RenderTarget[ 0 ].BlendEnable = true; + blendDesc.RenderTarget[ 0 ].SrcBlend = D3D11_BLEND_SRC_ALPHA; + blendDesc.RenderTarget[ 0 ].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + if ( pDevice->CreateBlendState( &blendDesc, &pGUIBlendState ) != S_OK ) + return false; - if (!InitD3D11QuadRendering(settings)) - { - printf("[Renderer] InitD3D11QuadRendering failed\n"); - return false; - } + D3D11_RASTERIZER_DESC rastDesc = CD3D11_RASTERIZER_DESC( CD3D11_DEFAULT() ); + rastDesc.ScissorEnable = true; + if ( pDevice->CreateRasterizerState( &rastDesc, &pGUIRasterizerState ) != S_OK ) + return false; - if (!InitD3D11GUIRendering(settings)) - { - printf("[Renderer] InitD3D11GUIRendering failed\n"); - return false; - } + return true; +} - return true; - } +bool Open( Renderer::Settings * settings ) +{ + nWidth = settings->nWidth; + nHeight = settings->nHeight; - void StartFrame() + if ( !InitWindow( settings ) ) { - MSG msg; - if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) - { - TranslateMessage( &msg ); - DispatchMessage( &msg ); - } - - float f[4] = { 0.08f, 0.18f, 0.18f, 1.0f }; - pContext->ClearRenderTargetView(pRenderTarget, f); + printf( "[Renderer] InitWindow failed\n" ); + return false; } - void EndFrame() + + if ( !InitDirect3D( settings ) ) { - pSwapChain->Present( bVsync ? 1 : 0, NULL ); + printf( "[Renderer] InitDirect3D failed\n" ); + return false; } - bool WantsToQuit() + + if ( !InitD3D11QuadRendering( settings ) ) { - return !run; + printf( "[Renderer] InitD3D11QuadRendering failed\n" ); + return false; } - void Close() + + if ( !InitD3D11GUIRendering( settings ) ) { - // TODO: a bunch of other crap needs to be deallocated here but i cant be arsed - - if (theShader) theShader->Release(); - if (pShaderReflection) pShaderReflection->Release(); - if (pVertexShader) pVertexShader->Release(); - - if (pFullscreenQuadLayout) pFullscreenQuadLayout->Release(); - if (pFullscreenQuadVB) pFullscreenQuadVB->Release(); - if (pFullscreenQuadSamplerState) pFullscreenQuadSamplerState->Release(); - if (pFullscreenQuadConstantBuffer) pFullscreenQuadConstantBuffer->Release(); - if (pFullscreenQuadBlendState) pFullscreenQuadBlendState->Release(); - if (pFullscreenQuadRasterizerState) pFullscreenQuadRasterizerState->Release(); - - if (pGUIRasterizerState) pGUIRasterizerState->Release(); - if (pGUIBlendState) pGUIBlendState->Release(); - if (pGUIConstantBuffer) pGUIConstantBuffer->Release(); - if (pGUIPixelShader) pGUIPixelShader->Release(); - if (pGUIVertexShader) pGUIVertexShader->Release(); - if (pGUIQuadLayout) pGUIQuadLayout->Release(); - if (pGUIQuadVB) pGUIQuadVB->Release(); - - if (pRenderTarget) pRenderTarget->Release(); - if (pContext) pContext->Release(); - if (pSwapChain) pSwapChain->Release(); - if (pDevice) pDevice->Release(); - if (hWnd) - { - DestroyWindow(hWnd); - UnregisterClass(_T("fwzwnd"),GetModuleHandle(NULL)); - } + printf( "[Renderer] InitD3D11GUIRendering failed\n" ); + return false; } - void RenderFullscreenQuad() + return true; +} + +void StartFrame() +{ + MSG msg; + if ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { - float factor[4] = { 1.0f, 1.0f, 1.0f, 1.0f, }; - pContext->VSSetShader( pVertexShader, NULL, NULL ); - pContext->PSSetShader( theShader, NULL, NULL ); - pContext->IASetInputLayout( pFullscreenQuadLayout ); - pContext->PSSetSamplers( 0, 1, &pFullscreenQuadSamplerState ); - pContext->PSSetConstantBuffers( 0, 1, &pFullscreenQuadConstantBuffer ); - pContext->OMSetBlendState( pFullscreenQuadBlendState, factor, 0xFFFFFFFF ); - pContext->RSSetState( pFullscreenQuadRasterizerState ); - - ID3D11Buffer * buffers[] = { pFullscreenQuadVB }; - UINT stride[] = { sizeof(float) * 5 }; - UINT offset[] = { 0 }; - - pContext->IASetVertexBuffers( 0, 1, buffers, stride, offset ); - pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); - - pContext->Draw( 4, 0 ); + TranslateMessage( &msg ); + DispatchMessage( &msg ); } - ID3D11ShaderReflectionConstantBuffer * pCBuf = NULL; - bool ReloadShader( const char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize ) + float f[ 4 ] = { 0.08f, 0.18f, 0.18f, 1.0f }; + pContext->ClearRenderTargetView( pRenderTarget, f ); +} +void EndFrame() +{ + pSwapChain->Present( bVsync ? 1 : 0, NULL ); +} +bool WantsToQuit() +{ + return !run; +} +void Close() +{ + // TODO: a bunch of other crap needs to be deallocated here but i cant be arsed + + if ( theShader ) theShader->Release(); + if ( pShaderReflection ) pShaderReflection->Release(); + if ( pVertexShader ) pVertexShader->Release(); + + if ( pFullscreenQuadLayout ) pFullscreenQuadLayout->Release(); + if ( pFullscreenQuadVB ) pFullscreenQuadVB->Release(); + if ( pFullscreenQuadSamplerState ) pFullscreenQuadSamplerState->Release(); + if ( pFullscreenQuadConstantBuffer ) pFullscreenQuadConstantBuffer->Release(); + if ( pFullscreenQuadBlendState ) pFullscreenQuadBlendState->Release(); + if ( pFullscreenQuadRasterizerState ) pFullscreenQuadRasterizerState->Release(); + + if ( pGUIRasterizerState ) pGUIRasterizerState->Release(); + if ( pGUIBlendState ) pGUIBlendState->Release(); + if ( pGUIConstantBuffer ) pGUIConstantBuffer->Release(); + if ( pGUIPixelShader ) pGUIPixelShader->Release(); + if ( pGUIVertexShader ) pGUIVertexShader->Release(); + if ( pGUIQuadLayout ) pGUIQuadLayout->Release(); + if ( pGUIQuadVB ) pGUIQuadVB->Release(); + + if ( pRenderTarget ) pRenderTarget->Release(); + if ( pContext ) pContext->Release(); + if ( pSwapChain ) pSwapChain->Release(); + if ( pDevice ) pDevice->Release(); + if ( hWnd ) { - ID3DBlob * pCode = NULL; - ID3DBlob * pErrors = NULL; - if (D3DCompile( szShaderCode, nShaderCodeSize, NULL, NULL, NULL, "main", "ps_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK) - { - memset( szErrorBuffer, 0, nErrorBufferSize ); - strncpy( szErrorBuffer, (const char*)pErrors->GetBufferPointer(), nErrorBufferSize - 1 ); - return false; - } - - if (theShader) - { - theShader->Release(); - theShader = NULL; - } - - if (pDevice->CreatePixelShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &theShader ) != S_OK) - { - return false; - } - D3DReflect( pCode->GetBufferPointer(), pCode->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pShaderReflection ); - pCBuf = pShaderReflection->GetConstantBufferByIndex(0); - - return true; + DestroyWindow( hWnd ); + UnregisterClass( _T( "fwzwnd" ), GetModuleHandle( NULL ) ); } +} + +void RenderFullscreenQuad() +{ + float factor[ 4 ] = { 1.0f, 1.0f, 1.0f, 1.0f, }; + pContext->VSSetShader( pVertexShader, NULL, NULL ); + pContext->PSSetShader( theShader, NULL, NULL ); + pContext->IASetInputLayout( pFullscreenQuadLayout ); + pContext->PSSetSamplers( 0, 1, &pFullscreenQuadSamplerState ); + pContext->PSSetConstantBuffers( 0, 1, &pFullscreenQuadConstantBuffer ); + pContext->OMSetBlendState( pFullscreenQuadBlendState, factor, 0xFFFFFFFF ); + pContext->RSSetState( pFullscreenQuadRasterizerState ); + + ID3D11Buffer * buffers[] = { pFullscreenQuadVB }; + UINT stride[] = { sizeof( float ) * 5 }; + UINT offset[] = { 0 }; + + pContext->IASetVertexBuffers( 0, 1, buffers, stride, offset ); + pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP ); + + pContext->Draw( 4, 0 ); +} - void __UpdateConstants() +ID3D11ShaderReflectionConstantBuffer * pCBuf = NULL; +bool ReloadShader( const char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize ) +{ + ID3DBlob * pCode = NULL; + ID3DBlob * pErrors = NULL; + if ( D3DCompile( szShaderCode, nShaderCodeSize, NULL, NULL, NULL, "main", "ps_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK ) { - D3D11_MAPPED_SUBRESOURCE subRes; - pContext->Map( pFullscreenQuadConstantBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes ); - CopyMemory( subRes.pData, &pFullscreenQuadConstants, sizeof(pFullscreenQuadConstants) ); - pContext->Unmap( pFullscreenQuadConstantBuffer, NULL ); + memset( szErrorBuffer, 0, nErrorBufferSize ); + strncpy( szErrorBuffer, (const char *) pErrors->GetBufferPointer(), nErrorBufferSize - 1 ); + return false; } - void SetShaderConstant( const char * szConstName, float x ) + if ( theShader ) { - ID3D11ShaderReflectionVariable * pCVar = pCBuf->GetVariableByName( szConstName ); - D3D11_SHADER_VARIABLE_DESC pDesc; - if (pCVar->GetDesc( &pDesc ) != S_OK) - return; - - ((float*)(((unsigned char*)&pFullscreenQuadConstants) + pDesc.StartOffset))[0] = x; - - __UpdateConstants(); + theShader->Release(); + theShader = NULL; } - void SetShaderConstant( const char * szConstName, float x, float y ) + if ( pDevice->CreatePixelShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &theShader ) != S_OK ) { - ID3D11ShaderReflectionVariable * pCVar = pCBuf->GetVariableByName(szConstName); - D3D11_SHADER_VARIABLE_DESC pDesc; - if (pCVar->GetDesc( &pDesc ) != S_OK) - return; + return false; + } + D3DReflect( pCode->GetBufferPointer(), pCode->GetBufferSize(), IID_ID3D11ShaderReflection, (void **) &pShaderReflection ); + pCBuf = pShaderReflection->GetConstantBufferByIndex( 0 ); - ((float*)(((unsigned char*)&pFullscreenQuadConstants) + pDesc.StartOffset))[0] = x; - ((float*)(((unsigned char*)&pFullscreenQuadConstants) + pDesc.StartOffset))[1] = y; + return true; +} - __UpdateConstants(); - } +void __UpdateConstants() +{ + D3D11_MAPPED_SUBRESOURCE subRes; + pContext->Map( pFullscreenQuadConstantBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes ); + CopyMemory( subRes.pData, &pFullscreenQuadConstants, sizeof( pFullscreenQuadConstants ) ); + pContext->Unmap( pFullscreenQuadConstantBuffer, NULL ); +} - struct DX11Texture : public Texture - { - ID3D11Resource * pTexture; - DXGI_FORMAT format; - ID3D11ShaderResourceView * pResourceView; - }; +void SetShaderConstant( const char * szConstName, float x ) +{ + ID3D11ShaderReflectionVariable * pCVar = pCBuf->GetVariableByName( szConstName ); + D3D11_SHADER_VARIABLE_DESC pDesc; + if ( pCVar->GetDesc( &pDesc ) != S_OK ) + return; - void CreateResourceView( DX11Texture * tex ) - { - D3D11_SHADER_RESOURCE_VIEW_DESC desc; - ZeroMemory( &desc, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC) ); - desc.Format = tex->format; - if (tex->type == TEXTURETYPE_1D) - { - desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; - desc.Texture1D.MostDetailedMip = 0; - desc.Texture1D.MipLevels = 1; - } - else if (tex->type == TEXTURETYPE_2D) - { - desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - desc.Texture2D.MostDetailedMip = 0; - desc.Texture2D.MipLevels = 1; - } - pDevice->CreateShaderResourceView( tex->pTexture, &desc, &tex->pResourceView ); - } + ( (float *) ( ( (unsigned char *) &pFullscreenQuadConstants ) + pDesc.StartOffset ) )[ 0 ] = x; - int textureUnit = 0; + __UpdateConstants(); +} - Renderer::Texture * CreateRGBA8Texture() - { - D3D11_TEXTURE2D_DESC desc; - ZeroMemory( &desc, sizeof( D3D11_TEXTURE2D_DESC ) ); - desc.Width = nWidth; - desc.Height = nHeight; - desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - desc.MipLevels = 1; - desc.ArraySize = 1; - desc.SampleDesc.Count = 1; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - - ID3D11Texture2D * pTex = NULL; - - if ( pDevice->CreateTexture2D( &desc, NULL, &pTex ) != S_OK ) - return NULL; - - DX11Texture * tex = new DX11Texture(); - tex->width = nWidth; - tex->height = nHeight; - tex->pTexture = pTex; - tex->type = TEXTURETYPE_2D; - tex->format = desc.Format; - CreateResourceView( tex ); - return tex; +void SetShaderConstant( const char * szConstName, float x, float y ) +{ + ID3D11ShaderReflectionVariable * pCVar = pCBuf->GetVariableByName( szConstName ); + D3D11_SHADER_VARIABLE_DESC pDesc; + if ( pCVar->GetDesc( &pDesc ) != S_OK ) + return; - } + ( (float *) ( ( (unsigned char *) &pFullscreenQuadConstants ) + pDesc.StartOffset ) )[ 0 ] = x; + ( (float *) ( ( (unsigned char *) &pFullscreenQuadConstants ) + pDesc.StartOffset ) )[ 1 ] = y; - Texture * CreateRGBA8TextureFromFile( const char * szFilename ) - { - int comp = 0; - int width = 0; - int height = 0; - - DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - void * data = NULL; - unsigned int pitch = 0; - if ( stbi_is_hdr( szFilename ) ) - { - data = stbi_loadf( szFilename, &width, &height, &comp, STBI_rgb_alpha ); - format = DXGI_FORMAT_R32G32B32A32_FLOAT; - pitch = width * sizeof( float ) * 4; - } - else - { - data = stbi_load( szFilename, &width, &height, &comp, STBI_rgb_alpha ); - pitch = width * sizeof( unsigned char ) * 4; - } + __UpdateConstants(); +} - D3D11_TEXTURE2D_DESC desc; - ZeroMemory(&desc,sizeof(D3D11_TEXTURE2D_DESC)); - desc.Width = width; - desc.Height = height; - desc.Format = format; - desc.MipLevels = 1; - desc.ArraySize = 1; - desc.SampleDesc.Count = 1; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - - D3D11_SUBRESOURCE_DATA subData; - ZeroMemory(&subData,sizeof(D3D11_SUBRESOURCE_DATA)); - subData.pSysMem = data; - subData.SysMemPitch = pitch; - - ID3D11Texture2D * pTex = NULL; - - if (pDevice->CreateTexture2D( &desc, &subData, &pTex ) != S_OK) - return NULL; - - stbi_image_free(data); - - DX11Texture * tex = new DX11Texture(); - tex->width = width; - tex->height = height; - tex->pTexture = pTex; - tex->type = TEXTURETYPE_2D; - tex->format = desc.Format; - CreateResourceView(tex); - return tex; - } +struct DX11Texture : public Texture +{ + ID3D11Resource * pTexture; + DXGI_FORMAT format; + ID3D11ShaderResourceView * pResourceView; +}; - Texture * Create1DR32Texture( int w ) +void CreateResourceView( DX11Texture * tex ) +{ + D3D11_SHADER_RESOURCE_VIEW_DESC desc; + ZeroMemory( &desc, sizeof( D3D11_SHADER_RESOURCE_VIEW_DESC ) ); + desc.Format = tex->format; + if ( tex->type == TEXTURETYPE_1D ) { - D3D11_TEXTURE1D_DESC desc; - ZeroMemory(&desc,sizeof(D3D11_TEXTURE1D_DESC)); - desc.Width = w; - desc.Format = DXGI_FORMAT_R32_FLOAT; - desc.MipLevels = 1; - desc.ArraySize = 1; - desc.Usage = D3D11_USAGE_DYNAMIC; - desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - - ID3D11Texture1D * pTex = NULL; - - if (pDevice->CreateTexture1D( &desc, NULL, &pTex ) != S_OK) - return NULL; - - DX11Texture * tex = new DX11Texture(); - tex->width = w; - tex->height = 1; - tex->pTexture = pTex; - tex->type = TEXTURETYPE_1D; - tex->format = desc.Format; - CreateResourceView(tex); - return tex; + desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; + desc.Texture1D.MostDetailedMip = 0; + desc.Texture1D.MipLevels = 1; } - - void SetShaderTexture( const char * szTextureName, Texture * tex ) + else if ( tex->type == TEXTURETYPE_2D ) { - D3D11_SHADER_INPUT_BIND_DESC desc; - if (pShaderReflection->GetResourceBindingDescByName( szTextureName, &desc ) == S_OK) - { - DX11Texture * pTex = (DX11Texture *) tex; - pContext->PSSetShaderResources( desc.BindPoint, 1, &pTex->pResourceView ); - } + desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + desc.Texture2D.MostDetailedMip = 0; + desc.Texture2D.MipLevels = 1; } + pDevice->CreateShaderResourceView( tex->pTexture, &desc, &tex->pResourceView ); +} - bool UpdateR32Texture( Texture * tex, float * data ) - { - ID3D11Texture1D * pTex = (ID3D11Texture1D *) ((DX11Texture *) tex)->pTexture; +int textureUnit = 0; - D3D11_MAPPED_SUBRESOURCE subRes; - pContext->Map( pTex, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes ); - CopyMemory( subRes.pData, data, sizeof(float) * tex->width ); - pContext->Unmap( pTex, NULL ); - return true; - } +Renderer::Texture * CreateRGBA8Texture() +{ + D3D11_TEXTURE2D_DESC desc; + ZeroMemory( &desc, sizeof( D3D11_TEXTURE2D_DESC ) ); + desc.Width = nWidth; + desc.Height = nHeight; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.SampleDesc.Count = 1; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + + ID3D11Texture2D * pTex = NULL; + + if ( pDevice->CreateTexture2D( &desc, NULL, &pTex ) != S_OK ) + return NULL; + + DX11Texture * tex = new DX11Texture(); + tex->width = nWidth; + tex->height = nHeight; + tex->pTexture = pTex; + tex->type = TEXTURETYPE_2D; + tex->format = desc.Format; + CreateResourceView( tex ); + return tex; - Texture * CreateA8TextureFromData( int w, int h, const unsigned char * data ) - { - D3D11_TEXTURE2D_DESC desc; - ZeroMemory(&desc,sizeof(D3D11_TEXTURE2D_DESC)); - desc.Width = w; - desc.Height = h; - desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - desc.MipLevels = 1; - desc.ArraySize = 1; - desc.SampleDesc.Count = 1; - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - - unsigned int * p = new unsigned int[ w * h ]; - for (int i=0; i < w * h; i++) - p[i] = (data[i] << 24) | 0xFFFFFF; - D3D11_SUBRESOURCE_DATA subData; - ZeroMemory(&subData,sizeof(D3D11_SUBRESOURCE_DATA)); - subData.pSysMem = p; - subData.SysMemPitch = w * sizeof(unsigned int); - - ID3D11Texture2D * pTex = NULL; - - if (pDevice->CreateTexture2D( &desc, &subData, &pTex ) != S_OK) - return NULL; - - delete[] p; - - DX11Texture * tex = new DX11Texture(); - tex->width = w; - tex->height = h; - tex->pTexture = pTex; - tex->type = TEXTURETYPE_2D; - tex->format = desc.Format; - CreateResourceView(tex); - return tex; - } +} - void ReleaseTexture( Texture * tex ) +Texture * CreateRGBA8TextureFromFile( const char * szFilename ) +{ + int comp = 0; + int width = 0; + int height = 0; + + DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + void * data = NULL; + unsigned int pitch = 0; + if ( stbi_is_hdr( szFilename ) ) { - ((DX11Texture *)tex)->pResourceView->Release(); - ((DX11Texture *)tex)->pTexture->Release(); - delete tex; + data = stbi_loadf( szFilename, &width, &height, &comp, STBI_rgb_alpha ); + format = DXGI_FORMAT_R32G32B32A32_FLOAT; + pitch = width * sizeof( float ) * 4; } - - void CopyBackbufferToTexture( Texture * tex ) + else { - ID3D11Resource * pTex = ( (DX11Texture *) tex )->pTexture; - - pContext->CopySubresourceRegion( pTex, 0, 0, 0, 0, pBackBuffer, 0, NULL ); + data = stbi_load( szFilename, &width, &height, &comp, STBI_rgb_alpha ); + pitch = width * sizeof( unsigned char ) * 4; } - ////////////////////////////////////////////////////////////////////////// - // text rendering + D3D11_TEXTURE2D_DESC desc; + ZeroMemory( &desc, sizeof( D3D11_TEXTURE2D_DESC ) ); + desc.Width = width; + desc.Height = height; + desc.Format = format; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.SampleDesc.Count = 1; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + + D3D11_SUBRESOURCE_DATA subData; + ZeroMemory( &subData, sizeof( D3D11_SUBRESOURCE_DATA ) ); + subData.pSysMem = data; + subData.SysMemPitch = pitch; + + ID3D11Texture2D * pTex = NULL; + + if ( pDevice->CreateTexture2D( &desc, &subData, &pTex ) != S_OK ) + return NULL; + + stbi_image_free( data ); + + DX11Texture * tex = new DX11Texture(); + tex->width = width; + tex->height = height; + tex->pTexture = pTex; + tex->type = TEXTURETYPE_2D; + tex->format = desc.Format; + CreateResourceView( tex ); + return tex; +} + +Texture * Create1DR32Texture( int w ) +{ + D3D11_TEXTURE1D_DESC desc; + ZeroMemory( &desc, sizeof( D3D11_TEXTURE1D_DESC ) ); + desc.Width = w; + desc.Format = DXGI_FORMAT_R32_FLOAT; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + + ID3D11Texture1D * pTex = NULL; + + if ( pDevice->CreateTexture1D( &desc, NULL, &pTex ) != S_OK ) + return NULL; + + DX11Texture * tex = new DX11Texture(); + tex->width = w; + tex->height = 1; + tex->pTexture = pTex; + tex->type = TEXTURETYPE_1D; + tex->format = desc.Format; + CreateResourceView( tex ); + return tex; +} - int nDrawCallCount = 0; - Texture * lastTexture = NULL; - void StartTextRendering() +void SetShaderTexture( const char * szTextureName, Texture * tex ) +{ + D3D11_SHADER_INPUT_BIND_DESC desc; + if ( pShaderReflection->GetResourceBindingDescByName( szTextureName, &desc ) == S_OK ) { - float factor[4] = { 1.0, 1.0, 1.0, 1.0 }; - pContext->VSSetShader( pGUIVertexShader, NULL, NULL ); - pContext->PSSetShader( pGUIPixelShader, NULL, NULL ); - pContext->IASetInputLayout( pGUIQuadLayout ); - pContext->VSSetConstantBuffers( 0, 1, &pGUIConstantBuffer ); - pContext->OMSetBlendState( pGUIBlendState, factor, 0xFFFFFFFF ); - pContext->RSSetState( pGUIRasterizerState ); - - // Disable previous texture - ID3D11ShaderResourceView * dummy[1] = { NULL }; - pContext->PSSetShaderResources( 0, 1, dummy ); - - ID3D11Buffer * buffers[] = { pGUIQuadVB }; - UINT stride[] = { sizeof(float) * 7 }; - UINT offset[] = { 0 }; - - pContext->IASetVertexBuffers( 0, 1, buffers, stride, offset ); - lastTexture = NULL; - - nDrawCallCount = 0; + DX11Texture * pTex = (DX11Texture *) tex; + pContext->PSSetShaderResources( desc.BindPoint, 1, &pTex->pResourceView ); } +} - int bufferPointer = 0; - unsigned char buffer[GUIQUADVB_SIZE * sizeof(float) * 7]; - bool lastModeIsQuad = true; - void __FlushRenderCache() - { - if (!bufferPointer) return; +bool UpdateR32Texture( Texture * tex, float * data ) +{ + ID3D11Texture1D * pTex = (ID3D11Texture1D *) ( (DX11Texture *) tex )->pTexture; - D3D11_MAPPED_SUBRESOURCE subRes; - pContext->Map( pGUIQuadVB, 0, D3D11_MAP_WRITE_DISCARD, NULL, &subRes ); - CopyMemory( subRes.pData, buffer, bufferPointer * sizeof(float) * 7 ); - pContext->Unmap( pGUIQuadVB, 0 ); + D3D11_MAPPED_SUBRESOURCE subRes; + pContext->Map( pTex, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes ); + CopyMemory( subRes.pData, data, sizeof( float ) * tex->width ); + pContext->Unmap( pTex, NULL ); + return true; +} - if (lastModeIsQuad) - { - pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); - } - else - { - pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST ); - } - pContext->Draw( bufferPointer, 0 ); - nDrawCallCount++; +Texture * CreateA8TextureFromData( int w, int h, const unsigned char * data ) +{ + D3D11_TEXTURE2D_DESC desc; + ZeroMemory( &desc, sizeof( D3D11_TEXTURE2D_DESC ) ); + desc.Width = w; + desc.Height = h; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.SampleDesc.Count = 1; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + + unsigned int * p = new unsigned int[ w * h ]; + for ( int i = 0; i < w * h; i++ ) + p[ i ] = ( data[ i ] << 24 ) | 0xFFFFFF; + D3D11_SUBRESOURCE_DATA subData; + ZeroMemory( &subData, sizeof( D3D11_SUBRESOURCE_DATA ) ); + subData.pSysMem = p; + subData.SysMemPitch = w * sizeof( unsigned int ); + + ID3D11Texture2D * pTex = NULL; + + if ( pDevice->CreateTexture2D( &desc, &subData, &pTex ) != S_OK ) + return NULL; + + delete[] p; + + DX11Texture * tex = new DX11Texture(); + tex->width = w; + tex->height = h; + tex->pTexture = pTex; + tex->type = TEXTURETYPE_2D; + tex->format = desc.Format; + CreateResourceView( tex ); + return tex; +} - bufferPointer = 0; - } - void __WriteVertexToBuffer( const Vertex & v ) - { - if (bufferPointer >= GUIQUADVB_SIZE) - { - __FlushRenderCache(); - } +void ReleaseTexture( Texture * tex ) +{ + ( (DX11Texture *) tex )->pResourceView->Release(); + ( (DX11Texture *) tex )->pTexture->Release(); + delete tex; +} + +void CopyBackbufferToTexture( Texture * tex ) +{ + ID3D11Resource * pTex = ( (DX11Texture *) tex )->pTexture; + + pContext->CopySubresourceRegion( pTex, 0, 0, 0, 0, pBackBuffer, 0, NULL ); +} + +////////////////////////////////////////////////////////////////////////// +// text rendering - float * f = (float*)(buffer + bufferPointer * sizeof(float) * 7); - *(f++) = v.x; - *(f++) = v.y; - *(f++) = 0.0; - *(unsigned int *)(f++) = v.c; - *(f++) = v.u; - *(f++) = v.v; - *(f++) = lastTexture ? 0.0f : 1.0f; - bufferPointer++; +int nDrawCallCount = 0; +Texture * lastTexture = NULL; +void StartTextRendering() +{ + float factor[ 4 ] = { 1.0, 1.0, 1.0, 1.0 }; + pContext->VSSetShader( pGUIVertexShader, NULL, NULL ); + pContext->PSSetShader( pGUIPixelShader, NULL, NULL ); + pContext->IASetInputLayout( pGUIQuadLayout ); + pContext->VSSetConstantBuffers( 0, 1, &pGUIConstantBuffer ); + pContext->OMSetBlendState( pGUIBlendState, factor, 0xFFFFFFFF ); + pContext->RSSetState( pGUIRasterizerState ); + + // Disable previous texture + ID3D11ShaderResourceView * dummy[ 1 ] = { NULL }; + pContext->PSSetShaderResources( 0, 1, dummy ); + + ID3D11Buffer * buffers[] = { pGUIQuadVB }; + UINT stride[] = { sizeof( float ) * 7 }; + UINT offset[] = { 0 }; + + pContext->IASetVertexBuffers( 0, 1, buffers, stride, offset ); + lastTexture = NULL; + + nDrawCallCount = 0; +} + +int bufferPointer = 0; +unsigned char buffer[ GUIQUADVB_SIZE * sizeof( float ) * 7 ]; +bool lastModeIsQuad = true; +void __FlushRenderCache() +{ + if ( !bufferPointer ) return; + + D3D11_MAPPED_SUBRESOURCE subRes; + pContext->Map( pGUIQuadVB, 0, D3D11_MAP_WRITE_DISCARD, NULL, &subRes ); + CopyMemory( subRes.pData, buffer, bufferPointer * sizeof( float ) * 7 ); + pContext->Unmap( pGUIQuadVB, 0 ); + + if ( lastModeIsQuad ) + { + pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); } - void BindTexture( Texture * tex ) + else { - if (lastTexture != tex) - { - lastTexture = tex; - if (tex) - { - __FlushRenderCache(); - DX11Texture * pTex = (DX11Texture *) tex; - pContext->PSSetShaderResources( 0, 1, &pTex->pResourceView ); - } - } + pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST ); } + pContext->Draw( bufferPointer, 0 ); + nDrawCallCount++; - void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d ) + bufferPointer = 0; +} +void __WriteVertexToBuffer( const Vertex & v ) +{ + if ( bufferPointer >= GUIQUADVB_SIZE ) { - if (!lastModeIsQuad) - { - __FlushRenderCache(); - lastModeIsQuad = true; - } - __WriteVertexToBuffer(a); - __WriteVertexToBuffer(b); - __WriteVertexToBuffer(d); - __WriteVertexToBuffer(b); - __WriteVertexToBuffer(c); - __WriteVertexToBuffer(d); + __FlushRenderCache(); } - void RenderLine( const Vertex & a, const Vertex & b ) + float * f = (float *) ( buffer + bufferPointer * sizeof( float ) * 7 ); + *( f++ ) = v.x; + *( f++ ) = v.y; + *( f++ ) = 0.0; + *(unsigned int *) ( f++ ) = v.c; + *( f++ ) = v.u; + *( f++ ) = v.v; + *( f++ ) = lastTexture ? 0.0f : 1.0f; + bufferPointer++; +} +void BindTexture( Texture * tex ) +{ + if ( lastTexture != tex ) { - if (lastModeIsQuad) + lastTexture = tex; + if ( tex ) { __FlushRenderCache(); - lastModeIsQuad = false; + DX11Texture * pTex = (DX11Texture *) tex; + pContext->PSSetShaderResources( 0, 1, &pTex->pResourceView ); } - __WriteVertexToBuffer(a); - __WriteVertexToBuffer(b); } +} - void SetTextRenderingViewport( Scintilla::PRectangle rect ) +void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d ) +{ + if ( !lastModeIsQuad ) { __FlushRenderCache(); - - pGUIMatrix[ 16 + 0 ] = rect.left; - pGUIMatrix[ 16 + 1 ] = rect.top; - - D3D11_MAPPED_SUBRESOURCE subRes; - pContext->Map( pGUIConstantBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes ); - CopyMemory( subRes.pData, &pGUIMatrix, sizeof(float) * 16 * 2 ); - pContext->Unmap( pGUIConstantBuffer, NULL ); - - D3D11_RECT rc = { rect.left, rect.top, rect.right, rect.bottom }; - pContext->RSSetScissorRects( 1, &rc ); + lastModeIsQuad = true; } - void EndTextRendering() + __WriteVertexToBuffer( a ); + __WriteVertexToBuffer( b ); + __WriteVertexToBuffer( d ); + __WriteVertexToBuffer( b ); + __WriteVertexToBuffer( c ); + __WriteVertexToBuffer( d ); +} + +void RenderLine( const Vertex & a, const Vertex & b ) +{ + if ( lastModeIsQuad ) { __FlushRenderCache(); + lastModeIsQuad = false; } + __WriteVertexToBuffer( a ); + __WriteVertexToBuffer( b ); +} - ////////////////////////////////////////////////////////////////////////// +void SetTextRenderingViewport( Scintilla::PRectangle rect ) +{ + __FlushRenderCache(); - bool GrabFrame( void * pPixelBuffer ) - { - if (!pFrameGrabTexture) - return false; - - pContext->CopyResource( pFrameGrabTexture, pBackBuffer ); - - D3D11_MAPPED_SUBRESOURCE resource; - unsigned int nSubresource = D3D11CalcSubresource( 0, 0, 0 ); - if (pContext->Map( pFrameGrabTexture, nSubresource, D3D11_MAP_READ, 0, &resource ) != S_OK) - return false; - - unsigned char* pSrc = (unsigned char*)resource.pData; - unsigned char* pDst = (unsigned char*)pPixelBuffer; - for( int i = 0; i < nHeight; i++ ) - { - memcpy( pDst, pSrc, nWidth * 4 ); - pSrc += resource.RowPitch; - pDst += nWidth * 4; - } + pGUIMatrix[ 16 + 0 ] = rect.left; + pGUIMatrix[ 16 + 1 ] = rect.top; + + D3D11_MAPPED_SUBRESOURCE subRes; + pContext->Map( pGUIConstantBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes ); + CopyMemory( subRes.pData, &pGUIMatrix, sizeof( float ) * 16 * 2 ); + pContext->Unmap( pGUIConstantBuffer, NULL ); + + D3D11_RECT rc = { rect.left, rect.top, rect.right, rect.bottom }; + pContext->RSSetScissorRects( 1, &rc ); +} +void EndTextRendering() +{ + __FlushRenderCache(); +} - pContext->Unmap( pFrameGrabTexture, nSubresource ); +////////////////////////////////////////////////////////////////////////// - return true; +bool GrabFrame( void * pPixelBuffer ) +{ + if ( !pFrameGrabTexture ) + return false; + + pContext->CopyResource( pFrameGrabTexture, pBackBuffer ); + + D3D11_MAPPED_SUBRESOURCE resource; + unsigned int nSubresource = D3D11CalcSubresource( 0, 0, 0 ); + if ( pContext->Map( pFrameGrabTexture, nSubresource, D3D11_MAP_READ, 0, &resource ) != S_OK ) + return false; + + unsigned char * pSrc = (unsigned char *) resource.pData; + unsigned char * pDst = (unsigned char *) pPixelBuffer; + for ( int i = 0; i < nHeight; i++ ) + { + memcpy( pDst, pSrc, nWidth * 4 ); + pSrc += resource.RowPitch; + pDst += nWidth * 4; } + pContext->Unmap( pFrameGrabTexture, nSubresource ); + + return true; +} + +////////////////////////////////////////////////////////////////////////// } diff --git a/src/platform_w32_dx9/Renderer.cpp b/src/platform_w32_dx9/Renderer.cpp index 5215a630..217406c7 100644 --- a/src/platform_w32_dx9/Renderer.cpp +++ b/src/platform_w32_dx9/Renderer.cpp @@ -13,922 +13,926 @@ #if defined(__MINGW32__) && !defined(D3D9b_SDK_VERSION) #define D3D9b_SDK_VERSION 31 - // From https://docs.rs/winapi/0.2.8/i686-pc-windows-gnu/winapi/d3d9/constant.D3D9b_SDK_VERSION.html +// From https://docs.rs/winapi/0.2.8/i686-pc-windows-gnu/winapi/d3d9/constant.D3D9b_SDK_VERSION.html #endif #ifndef WM_MOUSEHWHEEL #define WM_MOUSEHWHEEL (0x020E) #endif +namespace Renderer +{ +////////////////////////////////////////////////////////////////////////// + const char * shaderKeyword = - " register packoffset static const" - " break continue discard do for if else switch while case default return true false" - " BINORMAL BINORMAL0 BINORMAL1 BINORMAL2 BINORMAL3 BINORMAL4 BINORMAL5 BINORMAL6 BINORMAL7" - " BLENDINDICES BLENDINDICES0 BLENDINDICES1 BLENDINDICES2 BLENDINDICES3 BLENDINDICES4 BLENDINDICES5 BLENDINDICES6 BLENDINDICES7" - " BLENDWEIGHT BLENDWEIGHT0 BLENDWEIGHT1 BLENDWEIGHT2 BLENDWEIGHT3 BLENDWEIGHT4 BLENDWEIGHT5 BLENDWEIGHT6 BLENDWEIGHT7" - " COLOR COLOR0 COLOR1 COLOR2 COLOR3 COLOR4 COLOR5 COLOR6 COLOR7" - " NORMAL NORMAL0 NORMAL1 NORMAL2 NORMAL3 NORMAL4 NORMAL5 NORMAL6 NORMAL7" - " POSITION POSITION0 POSITION1 POSITION2 POSITION3 POSITION4 POSITION5 POSITION6 POSITION7" - " POSITIONT" - " PSIZE PSIZE0 PSIZE1 PSIZE2 PSIZE3 PSIZE4 PSIZE5 PSIZE6 PSIZE7" - " TANGENT TANGENT0 TANGENT1 TANGENT2 TANGENT3 TANGENT4 TANGENT5 TANGENT6 TANGENT7" - " TEXCOORD TEXCOORD0 TEXCOORD1 TEXCOORD2 TEXCOORD3 TEXCOORD4 TEXCOORD5 TEXCOORD6 TEXCOORD7 TEXCOORD8 TEXCOORD9" - " TEXCOORD0 TEXCOORD1 TEXCOORD2 TEXCOORD3 TEXCOORD4 TEXCOORD5 TEXCOORD6 TEXCOORD7 TEXCOORD8 TEXCOORD9" - " SV_Coverage SV_Depth SV_DispatchThreadID SV_DomainLocation SV_GroupID SV_GroupIndex SV_GroupThreadID SV_GSInstanceID SV_InsideTessFactor SV_IsFrontFace SV_OutputControlPointID SV_POSITION SV_Position SV_RenderTargetArrayIndex SV_SampleIndex SV_TessFactor SV_ViewportArrayIndex SV_InstanceID SV_PrimitiveID SV_VertexID SV_TargetID" - " SV_TARGET SV_Target SV_Target0 SV_Target1 SV_Target2 SV_Target3 SV_Target4 SV_Target5 SV_Target6 SV_Target7" - " SV_ClipDistance0 SV_ClipDistance1 SV_ClipDistance2 SV_ClipDistance3 SV_ClipDistance4 SV_ClipDistance5 SV_ClipDistance6 SV_ClipDistance7" - " SV_CullDistance0 SV_CullDistance1 SV_CullDistance2 SV_CullDistance3 SV_CullDistance4 SV_CullDistance5 SV_CullDistance6 SV_CullDistance7"; - -const char * shaderType = - "bool bool1 bool2 bool3 bool4" - " bool1x1 bool1x2 bool1x3 bool1x4" - " bool2x1 bool2x2 bool2x3 bool2x4" - " bool3x1 bool3x2 bool3x3 bool3x4" - " bool4x1 bool4x2 bool4x3 bool4x4" - " int int1 int2 int3 int4" - " int1x1 int1x2 int1x3 int1x4" - " int2x1 int2x2 int2x3 int2x4" - " int3x1 int3x2 int3x3 int3x4" - " int4x1 int4x2 int4x3 int4x4" - " uint uint1 uint2 uint3 uint4" - " uint1x1 uint1x2 uint1x3 uint1x4" - " uint2x1 uint2x2 uint2x3 uint2x4" - " uint3x1 uint3x2 uint3x3 uint3x4" - " uint4x1 uint4x2 uint4x3 uint4x4" - " UINT UINT2 UINT3 UINT4" - " dword dword1 dword2 dword3 dword4" - " dword1x1 dword1x2 dword1x3 dword1x4" - " dword2x1 dword2x2 dword2x3 dword2x4" - " dword3x1 dword3x2 dword3x3 dword3x4" - " dword4x1 dword4x2 dword4x3 dword4x4" - " half half1 half2 half3 half4" - " half1x1 half1x2 half1x3 half1x4" - " half2x1 half2x2 half2x3 half2x4" - " half3x1 half3x2 half3x3 half3x4" - " half4x1 half4x2 half4x3 half4x4" - " float float1 float2 float3 float4" - " float1x1 float1x2 float1x3 float1x4" - " float2x1 float2x2 float2x3 float2x4" - " float3x1 float3x2 float3x3 float3x4" - " float4x1 float4x2 float4x3 float4x4" - " double double1 double2 double3 double4" - " double1x1 double1x2 double1x3 double1x4" - " double2x1 double2x2 double2x3 double2x4" - " double3x1 double3x2 double3x3 double3x4" - " double4x1 double4x2 double4x3 double4x4" - " snorm unorm string void cbuffer struct" - " Buffer AppendStructuredBfufer ByteAddressBuffer ConsumeStructuredBuffer StructuredBuffer" - " RWBuffer RWByteAddressBuffer RWStructuredBuffer RWTexture1D RWTexture1DArray RWTexture2D RWTexture2DArray RWTexture3D" - " InputPatch OutputPatch" - " linear centroid nointerpolation noperspective sample" - " sampler sampler1D sampler2D sampler3D samplerCUBE SamplerComparisonState SamplerState sampler_state" - " AddressU AddressV AddressW BorderColor Filter MaxAnisotropy MaxLOD MinLOD MipLODBias ComparisonFunc ComparisonFilter" - " texture Texture1D Texture1DArray Texture2D Texture2DArray Texture2DMS Texture2DMSArray Texture3D TextureCube"; +" register packoffset static const" +" break continue discard do for if else switch while case default return true false" +" BINORMAL BINORMAL0 BINORMAL1 BINORMAL2 BINORMAL3 BINORMAL4 BINORMAL5 BINORMAL6 BINORMAL7" +" BLENDINDICES BLENDINDICES0 BLENDINDICES1 BLENDINDICES2 BLENDINDICES3 BLENDINDICES4 BLENDINDICES5 BLENDINDICES6 BLENDINDICES7" +" BLENDWEIGHT BLENDWEIGHT0 BLENDWEIGHT1 BLENDWEIGHT2 BLENDWEIGHT3 BLENDWEIGHT4 BLENDWEIGHT5 BLENDWEIGHT6 BLENDWEIGHT7" +" COLOR COLOR0 COLOR1 COLOR2 COLOR3 COLOR4 COLOR5 COLOR6 COLOR7" +" NORMAL NORMAL0 NORMAL1 NORMAL2 NORMAL3 NORMAL4 NORMAL5 NORMAL6 NORMAL7" +" POSITION POSITION0 POSITION1 POSITION2 POSITION3 POSITION4 POSITION5 POSITION6 POSITION7" +" POSITIONT" +" PSIZE PSIZE0 PSIZE1 PSIZE2 PSIZE3 PSIZE4 PSIZE5 PSIZE6 PSIZE7" +" TANGENT TANGENT0 TANGENT1 TANGENT2 TANGENT3 TANGENT4 TANGENT5 TANGENT6 TANGENT7" +" TEXCOORD TEXCOORD0 TEXCOORD1 TEXCOORD2 TEXCOORD3 TEXCOORD4 TEXCOORD5 TEXCOORD6 TEXCOORD7 TEXCOORD8 TEXCOORD9" +" TEXCOORD0 TEXCOORD1 TEXCOORD2 TEXCOORD3 TEXCOORD4 TEXCOORD5 TEXCOORD6 TEXCOORD7 TEXCOORD8 TEXCOORD9" +" SV_Coverage SV_Depth SV_DispatchThreadID SV_DomainLocation SV_GroupID SV_GroupIndex SV_GroupThreadID SV_GSInstanceID SV_InsideTessFactor SV_IsFrontFace SV_OutputControlPointID SV_POSITION SV_Position SV_RenderTargetArrayIndex SV_SampleIndex SV_TessFactor SV_ViewportArrayIndex SV_InstanceID SV_PrimitiveID SV_VertexID SV_TargetID" +" SV_TARGET SV_Target SV_Target0 SV_Target1 SV_Target2 SV_Target3 SV_Target4 SV_Target5 SV_Target6 SV_Target7" +" SV_ClipDistance0 SV_ClipDistance1 SV_ClipDistance2 SV_ClipDistance3 SV_ClipDistance4 SV_ClipDistance5 SV_ClipDistance6 SV_ClipDistance7" +" SV_CullDistance0 SV_CullDistance1 SV_CullDistance2 SV_CullDistance3 SV_CullDistance4 SV_CullDistance5 SV_CullDistance6 SV_CullDistance7"; + +const char * shaderType = +"bool bool1 bool2 bool3 bool4" +" bool1x1 bool1x2 bool1x3 bool1x4" +" bool2x1 bool2x2 bool2x3 bool2x4" +" bool3x1 bool3x2 bool3x3 bool3x4" +" bool4x1 bool4x2 bool4x3 bool4x4" +" int int1 int2 int3 int4" +" int1x1 int1x2 int1x3 int1x4" +" int2x1 int2x2 int2x3 int2x4" +" int3x1 int3x2 int3x3 int3x4" +" int4x1 int4x2 int4x3 int4x4" +" uint uint1 uint2 uint3 uint4" +" uint1x1 uint1x2 uint1x3 uint1x4" +" uint2x1 uint2x2 uint2x3 uint2x4" +" uint3x1 uint3x2 uint3x3 uint3x4" +" uint4x1 uint4x2 uint4x3 uint4x4" +" UINT UINT2 UINT3 UINT4" +" dword dword1 dword2 dword3 dword4" +" dword1x1 dword1x2 dword1x3 dword1x4" +" dword2x1 dword2x2 dword2x3 dword2x4" +" dword3x1 dword3x2 dword3x3 dword3x4" +" dword4x1 dword4x2 dword4x3 dword4x4" +" half half1 half2 half3 half4" +" half1x1 half1x2 half1x3 half1x4" +" half2x1 half2x2 half2x3 half2x4" +" half3x1 half3x2 half3x3 half3x4" +" half4x1 half4x2 half4x3 half4x4" +" float float1 float2 float3 float4" +" float1x1 float1x2 float1x3 float1x4" +" float2x1 float2x2 float2x3 float2x4" +" float3x1 float3x2 float3x3 float3x4" +" float4x1 float4x2 float4x3 float4x4" +" double double1 double2 double3 double4" +" double1x1 double1x2 double1x3 double1x4" +" double2x1 double2x2 double2x3 double2x4" +" double3x1 double3x2 double3x3 double3x4" +" double4x1 double4x2 double4x3 double4x4" +" snorm unorm string void cbuffer struct" +" Buffer AppendStructuredBfufer ByteAddressBuffer ConsumeStructuredBuffer StructuredBuffer" +" RWBuffer RWByteAddressBuffer RWStructuredBuffer RWTexture1D RWTexture1DArray RWTexture2D RWTexture2DArray RWTexture3D" +" InputPatch OutputPatch" +" linear centroid nointerpolation noperspective sample" +" sampler sampler1D sampler2D sampler3D samplerCUBE SamplerComparisonState SamplerState sampler_state" +" AddressU AddressV AddressW BorderColor Filter MaxAnisotropy MaxLOD MinLOD MipLODBias ComparisonFunc ComparisonFilter" +" texture Texture1D Texture1DArray Texture2D Texture2DArray Texture2DMS Texture2DMSArray Texture3D TextureCube"; const char * shaderBuiltin = - "abs acos all AllMemoryBarrier AllMemoryBarrierWithGroupSync any asdouble" - " asfloat asin asint asuint atan atan2 ceil clamp clip cos cosh countbits" - " cross D3DCOLORtoUBYTE4 ddx ddx_coarse ddx_fine ddy ddy_coarse ddy_fine" - " degrees determinant DeviceMemoryBarrier DeviceMemoryBarrierWithGroupSync" - " distance dot dst EvaluateAttributeAtCentroid EvaluateAttributeAtSample" - " EvaluateAttributeSnapped exp exp2 f16tof32 f32tof16 faceforward firstbithigh" - " firstbitlow floor fmod frac frexp fwidth GetRenderTargetSampleCount" - " GetRenderTargetSamplePosition GroupMemoryBarrier GroupMemoryBarrierWithGroupSync" - " InterlockedAdd InterlockedAnd InterlockedCompareExchange InterlockedCompareStore" - " InterlockedExchange InterlockedMax InterlockedMin InterlockedOr InterlockedXor" - " isfinite isinf isnan ldexp length lerp lit log log10 log2 mad max min modf mul" - " noise normalize pow Process2DQuadTessFactorsAvg Process2DQuadTessFactorsMax" - " Process2DQuadTessFactorsMin ProcessIsolineTessFactors ProcessQuadTessFactorsAvg" - " ProcessQuadTessFactorsMax ProcessQuadTessFactorsMin ProcessTriTessFactorsAvg" - " ProcessTriTessFactorsMax ProcessTriTessFactorsMin radians rcp reflect refract" - " reversebits round rsqrt saturate sign sin sincos sinh smoothstep sqrt step" - " tan tanh tex1D tex1Dbias tex1Dgrad tex1Dlod tex1Dproj tex2D tex2Dbias" - " tex2Dgrad tex2Dlod tex2Dproj tex3D tex3Dbias tex3Dgrad tex3Dlod tex3Dproj" - " texCUBE texCUBEbias texCUBEgrad texCUBElod texCUBEproj transpose trunc"; - -namespace Renderer +"abs acos all AllMemoryBarrier AllMemoryBarrierWithGroupSync any asdouble" +" asfloat asin asint asuint atan atan2 ceil clamp clip cos cosh countbits" +" cross D3DCOLORtoUBYTE4 ddx ddx_coarse ddx_fine ddy ddy_coarse ddy_fine" +" degrees determinant DeviceMemoryBarrier DeviceMemoryBarrierWithGroupSync" +" distance dot dst EvaluateAttributeAtCentroid EvaluateAttributeAtSample" +" EvaluateAttributeSnapped exp exp2 f16tof32 f32tof16 faceforward firstbithigh" +" firstbitlow floor fmod frac frexp fwidth GetRenderTargetSampleCount" +" GetRenderTargetSamplePosition GroupMemoryBarrier GroupMemoryBarrierWithGroupSync" +" InterlockedAdd InterlockedAnd InterlockedCompareExchange InterlockedCompareStore" +" InterlockedExchange InterlockedMax InterlockedMin InterlockedOr InterlockedXor" +" isfinite isinf isnan ldexp length lerp lit log log10 log2 mad max min modf mul" +" noise normalize pow Process2DQuadTessFactorsAvg Process2DQuadTessFactorsMax" +" Process2DQuadTessFactorsMin ProcessIsolineTessFactors ProcessQuadTessFactorsAvg" +" ProcessQuadTessFactorsMax ProcessQuadTessFactorsMin ProcessTriTessFactorsAvg" +" ProcessTriTessFactorsMax ProcessTriTessFactorsMin radians rcp reflect refract" +" reversebits round rsqrt saturate sign sin sincos sinh smoothstep sqrt step" +" tan tanh tex1D tex1Dbias tex1Dgrad tex1Dlod tex1Dproj tex2D tex2Dbias" +" tex2Dgrad tex2Dlod tex2Dproj tex3D tex3Dbias tex3Dgrad tex3Dlod tex3Dproj" +" texCUBE texCUBEbias texCUBEgrad texCUBElod texCUBEproj transpose trunc"; + +const char * szDefaultShaderFilename = "shader.dx9.hlsl"; +const char szDefaultShader[ 65536 ] = +"texture texTFFT; sampler1D texFFT = sampler_state { Texture = ; }; \n" +"// towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq\n" +"texture texFFTSmoothedT; sampler1D texFFTSmoothed = sampler_state { Texture = ; }; \n" +"// this one has longer falloff and less harsh transients\n" +"texture texFFTIntegratedT; sampler1D texFFTIntegrated = sampler_state { Texture = ; }; \n" +"// this is continually increasing\n" +"texture texPreviousFrameT; sampler2D texPreviousFrame = sampler_state { Texture = ; }; \n" +"// screenshot of the previous frame\n" +"\n" +"{%textures:begin%}" // leave off \n here +"texture raw{%textures:name%}; sampler2D {%textures:name%} = sampler_state { Texture = ; };\n" +"{%textures:end%}" +"\n" +"{%midi:begin%}" // leave off \n here +"float {%midi:name%};\n" +"{%midi:end%}" +"float fGlobalTime; // in seconds\n" +"float fFrameTime; // duration of the last frame, in seconds\n" +"float2 v2Resolution; // viewport resolution (in pixels)\n" +"\n" +"float4 plas( float2 v, float time )\n" +"{\n" +"\tfloat c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );\n" +"\treturn float4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );\n" +"}\n" +"\n" +"float4 main( float2 TexCoord : TEXCOORD0 ) : COLOR0\n" +"{\n" +"\tfloat2 uv = TexCoord;\n" +"\tuv -= 0.5;\n" +"\tuv /= float2(v2Resolution.y / v2Resolution.x, 1);" +"\n" +"\tfloat2 m;\n" +"\tm.x = atan(uv.x / uv.y) / 3.14;\n" +"\tm.y = 1 / length(uv) * .2;\n" +"\tfloat d = m.y;\n" +"\n" +"\tfloat f = tex1D( texFFT, d ).r * 100;\n" +"\tm.x += sin( fGlobalTime ) * 0.1;\n" +"\tm.y += fGlobalTime * 0.25;\n" +"\n" +"\tfloat4 t = plas( m * 3.14, fGlobalTime ) / d;\n" +"\tt = saturate( t );\n" +"\treturn f + t;\n" +"}"; +char defaultVertexShader[ 65536 ] = +"struct VS_INPUT_PP { float3 Pos : POSITION0; float2 TexCoord : TEXCOORD0; };\n" +"struct VS_OUTPUT_PP { float4 Pos : POSITION0; float2 TexCoord : TEXCOORD0; };\n" +"\n" +"VS_OUTPUT_PP main( VS_INPUT_PP In )\n" +"{\n" +"\tVS_OUTPUT_PP Out;\n" +"\tOut.Pos = float4( In.Pos, 1.0 );\n" +"\tOut.TexCoord = In.TexCoord;\n" +"\treturn Out;\n" +"}\n"; + +bool run = true; + +LPDIRECT3D9 pD3D = NULL; +LPDIRECT3DDEVICE9 pDevice = NULL; +LPD3DXCONSTANTTABLE pConstantTable = NULL; +LPDIRECT3DVERTEXSHADER9 pVertexShader = NULL; +LPDIRECT3DPIXELSHADER9 theShader = NULL; +LPDIRECT3DSURFACE9 pBackBuffer = NULL; +LPDIRECT3DSURFACE9 pFrameGrabTexture = NULL; + +int nWidth = 0; +int nHeight = 0; +HWND hWnd = NULL; + +KeyEvent keyEventBuffer[ 512 ]; +int keyEventBufferCount = 0; +MouseEvent mouseEventBuffer[ 512 ]; +int mouseEventBufferCount = 0; + +LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - const char * defaultShaderFilename = "shader.dx9.hlsl"; - const char defaultShader[65536] = - "texture texTFFT; sampler1D texFFT = sampler_state { Texture = ; }; \n" - "// towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq\n" - "texture texFFTSmoothedT; sampler1D texFFTSmoothed = sampler_state { Texture = ; }; \n" - "// this one has longer falloff and less harsh transients\n" - "texture texFFTIntegratedT; sampler1D texFFTIntegrated = sampler_state { Texture = ; }; \n" - "// this is continually increasing\n" - "texture texPreviousFrameT; sampler2D texPreviousFrame = sampler_state { Texture = ; }; \n" - "// screenshot of the previous frame\n" - "\n" - "{%textures:begin%}" // leave off \n here - "texture raw{%textures:name%}; sampler2D {%textures:name%} = sampler_state { Texture = ; };\n" - "{%textures:end%}" - "\n" - "{%midi:begin%}" // leave off \n here - "float {%midi:name%};\n" - "{%midi:end%}" - "float fGlobalTime; // in seconds\n" - "float fFrameTime; // duration of the last frame, in seconds\n" - "float2 v2Resolution; // viewport resolution (in pixels)\n" - "\n" - "float4 plas( float2 v, float time )\n" - "{\n" - "\tfloat c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );\n" - "\treturn float4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );\n" - "}\n" - "\n" - "float4 main( float2 TexCoord : TEXCOORD0 ) : COLOR0\n" - "{\n" - "\tfloat2 uv = TexCoord;\n" - "\tuv -= 0.5;\n" - "\tuv /= float2(v2Resolution.y / v2Resolution.x, 1);" - "\n" - "\tfloat2 m;\n" - "\tm.x = atan(uv.x / uv.y) / 3.14;\n" - "\tm.y = 1 / length(uv) * .2;\n" - "\tfloat d = m.y;\n" - "\n" - "\tfloat f = tex1D( texFFT, d ).r * 100;\n" - "\tm.x += sin( fGlobalTime ) * 0.1;\n" - "\tm.y += fGlobalTime * 0.25;\n" - "\n" - "\tfloat4 t = plas( m * 3.14, fGlobalTime ) / d;\n" - "\tt = saturate( t );\n" - "\treturn f + t;\n" - "}"; - char defaultVertexShader[65536] = - "struct VS_INPUT_PP { float3 Pos : POSITION0; float2 TexCoord : TEXCOORD0; };\n" - "struct VS_OUTPUT_PP { float4 Pos : POSITION0; float2 TexCoord : TEXCOORD0; };\n" - "\n" - "VS_OUTPUT_PP main( VS_INPUT_PP In )\n" - "{\n" - "\tVS_OUTPUT_PP Out;\n" - "\tOut.Pos = float4( In.Pos, 1.0 );\n" - "\tOut.TexCoord = In.TexCoord;\n" - "\treturn Out;\n" - "}\n"; - - bool run = true; - - LPDIRECT3D9 pD3D = NULL; - LPDIRECT3DDEVICE9 pDevice = NULL; - LPD3DXCONSTANTTABLE pConstantTable = NULL; - LPDIRECT3DVERTEXSHADER9 pVertexShader = NULL; - LPDIRECT3DPIXELSHADER9 theShader = NULL; - LPDIRECT3DSURFACE9 pBackBuffer = NULL; - LPDIRECT3DSURFACE9 pFrameGrabTexture = NULL; - - int nWidth = 0; - int nHeight = 0; - HWND hWnd = NULL; - - KeyEvent keyEventBuffer[512]; - int keyEventBufferCount = 0; - MouseEvent mouseEventBuffer[512]; - int mouseEventBufferCount = 0; - - LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) + switch ( uMsg ) { - switch (uMsg) - { - case WM_KEYDOWN: + case WM_KEYDOWN: { int sciKey = 0; - switch(wParam) + switch ( wParam ) { - case VK_DOWN: sciKey = SCK_DOWN; break; - case VK_UP: sciKey = SCK_UP; break; - case VK_LEFT: sciKey = SCK_LEFT; break; - case VK_RIGHT: sciKey = SCK_RIGHT; break; - case VK_HOME: sciKey = SCK_HOME; break; - case VK_END: sciKey = SCK_END; break; - case VK_PRIOR: sciKey = SCK_PRIOR; break; - case VK_NEXT: sciKey = SCK_NEXT; break; - case VK_DELETE: sciKey = SCK_DELETE; break; - case VK_INSERT: sciKey = SCK_INSERT; break; - case VK_ESCAPE: sciKey = SCK_ESCAPE; break; - case VK_BACK: sciKey = SCK_BACK; break; - case VK_TAB: sciKey = SCK_TAB; break; - case VK_RETURN: sciKey = SCK_RETURN; break; -// case VK_KP_PLUS: sciKey = SCK_ADD; break; -// case VK_KP_MINUS: sciKey = SCK_SUBTRACT; break; -// case VK_KP_DIVIDE: sciKey = SCK_DIVIDE; break; -// case VK_LSUPER: sciKey = SCK_WIN; break; -// case VK_RSUPER: sciKey = SCK_RWIN; break; - case VK_MENU: sciKey = SCK_MENU; break; -// case VK_SLASH: sciKey = '/'; break; -// case VK_ASTERISK: sciKey = '`'; break; -// case VK_LEFTBRACKET: sciKey = '['; break; -// case VK_BACKSLASH: sciKey = '\\'; break; -// case VK_RIGHTBRACKET: sciKey = ']'; break; - case VK_F2: sciKey = 283; break; - case VK_F5: sciKey = 286; break; - case VK_F11: sciKey = 292; break; - case VK_SHIFT: - case VK_LSHIFT: - case VK_RSHIFT: - case VK_LMENU: - case VK_RMENU: - case VK_CONTROL: - case VK_LCONTROL: - case VK_RCONTROL: - sciKey = 0; - break; - default: - sciKey = wParam; + case VK_DOWN: sciKey = SCK_DOWN; break; + case VK_UP: sciKey = SCK_UP; break; + case VK_LEFT: sciKey = SCK_LEFT; break; + case VK_RIGHT: sciKey = SCK_RIGHT; break; + case VK_HOME: sciKey = SCK_HOME; break; + case VK_END: sciKey = SCK_END; break; + case VK_PRIOR: sciKey = SCK_PRIOR; break; + case VK_NEXT: sciKey = SCK_NEXT; break; + case VK_DELETE: sciKey = SCK_DELETE; break; + case VK_INSERT: sciKey = SCK_INSERT; break; + case VK_ESCAPE: sciKey = SCK_ESCAPE; break; + case VK_BACK: sciKey = SCK_BACK; break; + case VK_TAB: sciKey = SCK_TAB; break; + case VK_RETURN: sciKey = SCK_RETURN; break; + // case VK_KP_PLUS: sciKey = SCK_ADD; break; + // case VK_KP_MINUS: sciKey = SCK_SUBTRACT; break; + // case VK_KP_DIVIDE: sciKey = SCK_DIVIDE; break; + // case VK_LSUPER: sciKey = SCK_WIN; break; + // case VK_RSUPER: sciKey = SCK_RWIN; break; + case VK_MENU: sciKey = SCK_MENU; break; + // case VK_SLASH: sciKey = '/'; break; + // case VK_ASTERISK: sciKey = '`'; break; + // case VK_LEFTBRACKET: sciKey = '['; break; + // case VK_BACKSLASH: sciKey = '\\'; break; + // case VK_RIGHTBRACKET: sciKey = ']'; break; + case VK_F2: sciKey = 283; break; + case VK_F5: sciKey = 286; break; + case VK_F11: sciKey = 292; break; + case VK_SHIFT: + case VK_LSHIFT: + case VK_RSHIFT: + case VK_LMENU: + case VK_RMENU: + case VK_CONTROL: + case VK_LCONTROL: + case VK_RCONTROL: + sciKey = 0; + break; + default: + sciKey = wParam; } - if (sciKey) + if ( sciKey ) { - keyEventBuffer[keyEventBufferCount].ctrl = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL ); - keyEventBuffer[keyEventBufferCount].alt = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU ); - keyEventBuffer[keyEventBufferCount].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT ); - keyEventBuffer[keyEventBufferCount].scanCode = sciKey; - keyEventBuffer[keyEventBufferCount].character = 0; + keyEventBuffer[ keyEventBufferCount ].ctrl = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL ); + keyEventBuffer[ keyEventBufferCount ].alt = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU ); + keyEventBuffer[ keyEventBufferCount ].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT ); + keyEventBuffer[ keyEventBufferCount ].scanCode = sciKey; + keyEventBuffer[ keyEventBufferCount ].character = 0; keyEventBufferCount++; } //pKeys[wParam] = 1; } break; - case WM_CHAR: + case WM_CHAR: { - if (wParam >= 32) + if ( wParam >= 32 ) { - keyEventBuffer[keyEventBufferCount].ctrl = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL ); - keyEventBuffer[keyEventBufferCount].alt = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU ); - keyEventBuffer[keyEventBufferCount].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT ); - keyEventBuffer[keyEventBufferCount].scanCode = 0; - keyEventBuffer[keyEventBufferCount].character = wParam; + keyEventBuffer[ keyEventBufferCount ].ctrl = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL ); + keyEventBuffer[ keyEventBufferCount ].alt = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU ); + keyEventBuffer[ keyEventBufferCount ].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT ); + keyEventBuffer[ keyEventBufferCount ].scanCode = 0; + keyEventBuffer[ keyEventBufferCount ].character = wParam; keyEventBufferCount++; } //pKeys[wParam] = 1; } break; - case WM_KEYUP: + case WM_KEYUP: { //pKeys[wParam] = 0; } break; - case WM_LBUTTONDOWN: + case WM_LBUTTONDOWN: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_DOWN; - mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT; - mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam); - mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam); + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_DOWN; + mouseEventBuffer[ mouseEventBufferCount ].button = MOUSEBUTTON_LEFT; + mouseEventBuffer[ mouseEventBufferCount ].x = (float)GET_X_LPARAM( lParam ); + mouseEventBuffer[ mouseEventBufferCount ].y = (float)GET_Y_LPARAM( lParam ); mouseEventBufferCount++; } break; - case WM_MOUSEMOVE: + case WM_MOUSEMOVE: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_MOVE; - mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam); - mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam); + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_MOVE; + mouseEventBuffer[ mouseEventBufferCount ].x = (float)GET_X_LPARAM( lParam ); + mouseEventBuffer[ mouseEventBufferCount ].y = (float)GET_Y_LPARAM( lParam ); mouseEventBufferCount++; } break; - case WM_LBUTTONUP: + case WM_LBUTTONUP: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_UP; - mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT; - mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam); - mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam); + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_UP; + mouseEventBuffer[ mouseEventBufferCount ].button = MOUSEBUTTON_LEFT; + mouseEventBuffer[ mouseEventBufferCount ].x = (float)GET_X_LPARAM( lParam ); + mouseEventBuffer[ mouseEventBufferCount ].y = (float)GET_Y_LPARAM( lParam ); mouseEventBufferCount++; } break; case WM_MOUSEWHEEL: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_SCROLL; - mouseEventBuffer[mouseEventBufferCount].x = 0; - mouseEventBuffer[mouseEventBufferCount].y = GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA; + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_SCROLL; + mouseEventBuffer[ mouseEventBufferCount ].x = 0.0f; + mouseEventBuffer[ mouseEventBufferCount ].y = GET_WHEEL_DELTA_WPARAM( wParam ) / (float) WHEEL_DELTA; mouseEventBufferCount++; } break; case WM_MOUSEHWHEEL: { - mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_SCROLL; - mouseEventBuffer[mouseEventBufferCount].x = -GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA; - mouseEventBuffer[mouseEventBufferCount].y = 0; + mouseEventBuffer[ mouseEventBufferCount ].eventType = MOUSEEVENTTYPE_SCROLL; + mouseEventBuffer[ mouseEventBufferCount ].x = -GET_WHEEL_DELTA_WPARAM( wParam ) / (float) WHEEL_DELTA; + mouseEventBuffer[ mouseEventBufferCount ].y = 0.0f; mouseEventBufferCount++; } break; - case WM_SYSCOMMAND: + case WM_SYSCOMMAND: { - switch (wParam) + switch ( wParam ) { - case SC_SCREENSAVE: - case SC_MONITORPOWER: - { - return 0; - } + case SC_SCREENSAVE: + case SC_MONITORPOWER: + { + return 0; + } } } break; - case WM_CLOSE: + case WM_CLOSE: { run = false; } break; - } - - return DefWindowProc(hWnd, uMsg, wParam, lParam); } - bool InitWindow(RENDERER_SETTINGS * pSetup) - { - WNDCLASS WC; - - WC.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; - WC.lpfnWndProc = &WndProc; - WC.cbClsExtra = 0; - WC.cbWndExtra = 0; - WC.hInstance = GetModuleHandle(NULL); - //WC.hIcon = LoadIcon(setup->hInstance,MAKEINTRESOURCE(IDI_ICON1)); - WC.hIcon = NULL; - WC.hCursor = LoadCursor(NULL, IDC_ARROW); - WC.hbrBackground = NULL; - WC.lpszMenuName = NULL; - WC.lpszClassName = _T("fwzwnd"); - if(!RegisterClass(&WC)) return 0; - - DWORD wExStyle = WS_EX_APPWINDOW; - DWORD wStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; - if (pSetup->windowMode == RENDERER_WINDOWMODE_WINDOWED) wStyle |= WS_OVERLAPPED | WS_CAPTION; - - RECT wr={0,0,pSetup->nWidth,pSetup->nHeight}; - AdjustWindowRectEx(&wr, wStyle, FALSE, wExStyle); - - hWnd = CreateWindowEx(wExStyle,_T("fwzwnd"),_T("BONZOMATIC - Direct3D 9.0c edition"),wStyle, - (GetSystemMetrics(SM_CXSCREEN) - pSetup->nWidth )/2, - (GetSystemMetrics(SM_CYSCREEN) - pSetup->nHeight)/2, - wr.right-wr.left, wr.bottom-wr.top, - NULL, NULL, WC.hInstance, NULL); - - if (!hWnd) - return false; + return DefWindowProc( hWnd, uMsg, wParam, lParam ); +} - ShowWindow(hWnd, SW_SHOW); - SetForegroundWindow(hWnd); - SetFocus(hWnd); +bool InitWindow( Renderer::Settings * pSetup ) +{ + WNDCLASS WC; + + WC.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; + WC.lpfnWndProc = &WndProc; + WC.cbClsExtra = 0; + WC.cbWndExtra = 0; + WC.hInstance = GetModuleHandle( NULL ); + //WC.hIcon = LoadIcon(setup->hInstance,MAKEINTRESOURCE(IDI_ICON1)); + WC.hIcon = NULL; + WC.hCursor = LoadCursor( NULL, IDC_ARROW ); + WC.hbrBackground = NULL; + WC.lpszMenuName = NULL; + WC.lpszClassName = _T( "fwzwnd" ); + if ( !RegisterClass( &WC ) ) return 0; + + DWORD wExStyle = WS_EX_APPWINDOW; + DWORD wStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; + if ( pSetup->windowMode == WINDOWMODE_WINDOWED ) wStyle |= WS_OVERLAPPED | WS_CAPTION; + + RECT wr = { 0,0,pSetup->nWidth,pSetup->nHeight }; + AdjustWindowRectEx( &wr, wStyle, FALSE, wExStyle ); + + hWnd = CreateWindowEx( wExStyle, _T( "fwzwnd" ), _T( "BONZOMATIC - Direct3D 9.0c edition" ), wStyle, + ( GetSystemMetrics( SM_CXSCREEN ) - pSetup->nWidth ) / 2, + ( GetSystemMetrics( SM_CYSCREEN ) - pSetup->nHeight ) / 2, + wr.right - wr.left, wr.bottom - wr.top, + NULL, NULL, WC.hInstance, NULL ); + + if ( !hWnd ) + return false; + + ShowWindow( hWnd, SW_SHOW ); + SetForegroundWindow( hWnd ); + SetFocus( hWnd ); + + return true; +} - return true; +D3DPRESENT_PARAMETERS d3dpp; +bool InitDirect3D( Renderer::Settings * pSetup ) +{ + pD3D = Direct3DCreate9( D3D9b_SDK_VERSION ); + if ( !pD3D ) + { + printf( "[Renderer] Direct3DCreate9 failed\n" ); + return false; } - D3DPRESENT_PARAMETERS d3dpp; - bool InitDirect3D(RENDERER_SETTINGS * pSetup) - { - pD3D = Direct3DCreate9(D3D9b_SDK_VERSION); - if (!pD3D) - { - printf("[Renderer] Direct3DCreate9 failed\n"); - return false; - } + nWidth = pSetup->nWidth; + nHeight = pSetup->nHeight; - nWidth = pSetup->nWidth; - nHeight = pSetup->nHeight; + ZeroMemory( &d3dpp, sizeof( d3dpp ) ); - ZeroMemory(&d3dpp,sizeof(d3dpp)); + d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; + d3dpp.hDeviceWindow = hWnd; + d3dpp.Windowed = pSetup->windowMode != WINDOWMODE_FULLSCREEN; + d3dpp.PresentationInterval = pSetup->bVsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE; - d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; - d3dpp.hDeviceWindow = hWnd; - d3dpp.Windowed = pSetup->windowMode != RENDERER_WINDOWMODE_FULLSCREEN; - d3dpp.PresentationInterval = pSetup->bVsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE; + d3dpp.BackBufferCount = 1; - d3dpp.BackBufferCount = 1; + d3dpp.BackBufferWidth = pSetup->nWidth; + d3dpp.BackBufferHeight = pSetup->nHeight; - d3dpp.BackBufferWidth = pSetup->nWidth; - d3dpp.BackBufferHeight = pSetup->nHeight; + D3DDISPLAYMODE d3ddm; + if ( FAILED( pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) ) + { + printf( "[Renderer] GetAdapterDisplayMode failed\n" ); + return false; + } - D3DDISPLAYMODE d3ddm; - if( FAILED( pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) ) - { - printf("[Renderer] GetAdapterDisplayMode failed\n"); - return false; - } + static D3DFORMAT pBackbufferFormats32[] = { + D3DFMT_X8R8G8B8, + D3DFMT_A8R8G8B8, + D3DFMT_UNKNOWN + }; + D3DFORMAT * pFormats = pBackbufferFormats32; + for ( int i = 0; pFormats[ i ] != D3DFMT_UNKNOWN; i++ ) + if ( SUCCEEDED( pD3D->CheckDeviceType( D3DADAPTER_DEFAULT, DEVTYPE, d3ddm.Format, pFormats[ i ], d3dpp.Windowed ) ) ) + d3dpp.BackBufferFormat = pFormats[ i ]; - static D3DFORMAT pBackbufferFormats32[] = { - D3DFMT_X8R8G8B8, - D3DFMT_A8R8G8B8, - D3DFMT_UNKNOWN - }; - D3DFORMAT * pFormats = pBackbufferFormats32; - for (int i=0; pFormats[i] != D3DFMT_UNKNOWN; i++) - if ( SUCCEEDED(pD3D->CheckDeviceType( D3DADAPTER_DEFAULT, DEVTYPE, d3ddm.Format, pFormats[i], d3dpp.Windowed )) ) - d3dpp.BackBufferFormat = pFormats[i]; - - if (d3dpp.BackBufferFormat == D3DFMT_UNKNOWN) - { - printf("[Renderer] No suitable backbuffer format found\n"); - return false; - } + if ( d3dpp.BackBufferFormat == D3DFMT_UNKNOWN ) + { + printf( "[Renderer] No suitable backbuffer format found\n" ); + return false; + } - d3dpp.EnableAutoDepthStencil = FALSE; + d3dpp.EnableAutoDepthStencil = FALSE; - static D3DMULTISAMPLE_TYPE pMultisampleTypes[]= - { - D3DMULTISAMPLE_2_SAMPLES, - D3DMULTISAMPLE_4_SAMPLES, - D3DMULTISAMPLE_6_SAMPLES, - D3DMULTISAMPLE_8_SAMPLES, - D3DMULTISAMPLE_NONE - }; - - d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; - - HRESULT h; - h = pD3D->CreateDevice( D3DADAPTER_DEFAULT, DEVTYPE, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &pDevice); - if (h != D3D_OK) - { - h = pD3D->CreateDevice( D3DADAPTER_DEFAULT, DEVTYPE, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &pDevice); - if(h != D3D_OK) - { - printf("[Renderer] CreateDevice failed: %08X\n",h); - return false; - } - } + static D3DMULTISAMPLE_TYPE pMultisampleTypes[] = + { + D3DMULTISAMPLE_2_SAMPLES, + D3DMULTISAMPLE_4_SAMPLES, + D3DMULTISAMPLE_6_SAMPLES, + D3DMULTISAMPLE_8_SAMPLES, + D3DMULTISAMPLE_NONE + }; - pDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); + d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; - for (int x=0; x<4; x++) + HRESULT h; + h = pD3D->CreateDevice( D3DADAPTER_DEFAULT, DEVTYPE, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &pDevice ); + if ( h != D3D_OK ) + { + h = pD3D->CreateDevice( D3DADAPTER_DEFAULT, DEVTYPE, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &pDevice ); + if ( h != D3D_OK ) { - pDevice->SetSamplerState( x, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); - pDevice->SetSamplerState( x, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); - pDevice->SetSamplerState( x, D3DSAMP_MIPFILTER, D3DTEXF_NONE); + printf( "[Renderer] CreateDevice failed: %08X\n", h ); + return false; } - - pDevice->GetRenderTarget( 0, &pBackBuffer ); - - return 1; } - LPDIRECT3DVERTEXBUFFER9 pFullscreenQuadVB = NULL; - LPDIRECT3DVERTEXBUFFER9 pGUIQuadVB = NULL; - LPDIRECT3DVERTEXDECLARATION9 pFullscreenQuadVertexDecl = NULL; - -#define GUIQUADVB_SIZE (128*6) + pDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); - bool Open( RENDERER_SETTINGS * settings ) + for ( int x = 0; x < 4; x++ ) { - if (!InitWindow(settings)) - { - printf("[Renderer] InitWindow failed\n"); - return false; - } + pDevice->SetSamplerState( x, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); + pDevice->SetSamplerState( x, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); + pDevice->SetSamplerState( x, D3DSAMP_MIPFILTER, D3DTEXF_NONE ); + } - if (!InitDirect3D(settings)) - { - printf("[Renderer] InitDirect3D failed\n"); - return false; - } + pDevice->GetRenderTarget( 0, &pBackBuffer ); - static D3DVERTEXELEMENT9 pFullscreenQuadElements[] = - { - { 0, 0*sizeof(float), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, - { 0, 3*sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, - D3DDECL_END() - }; + return 1; +} - static float pQuad[] = - { - -1.0, -1.0, 0.0, 0.0 + 0.5 / (float)nWidth, 0.0 + 0.5 / (float)nHeight, - -1.0, 1.0, 0.0, 0.0 + 0.5 / (float)nWidth, 1.0 + 0.5 / (float)nHeight, - 1.0, -1.0, 0.0, 1.0 + 0.5 / (float)nWidth, 0.0 + 0.5 / (float)nHeight, - 1.0, 1.0, 0.0, 1.0 + 0.5 / (float)nWidth, 1.0 + 0.5 / (float)nHeight, - }; +LPDIRECT3DVERTEXBUFFER9 pFullscreenQuadVB = NULL; +LPDIRECT3DVERTEXBUFFER9 pGUIQuadVB = NULL; +LPDIRECT3DVERTEXDECLARATION9 pFullscreenQuadVertexDecl = NULL; - pDevice->CreateVertexBuffer( 4 * 5 * sizeof(float), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_TEX1, D3DPOOL_DEFAULT, &pFullscreenQuadVB, NULL); - void * v; - pFullscreenQuadVB->Lock( 0, 4 * 5 * sizeof(float), &v, NULL ); - CopyMemory( v, pQuad, 4 * 5 * sizeof(float) ); - pFullscreenQuadVB->Unlock(); +#define GUIQUADVB_SIZE (128*6) - pDevice->CreateVertexDeclaration( pFullscreenQuadElements, &pFullscreenQuadVertexDecl ); +bool Open( Renderer::Settings * settings ) +{ + if ( !InitWindow( settings ) ) + { + printf( "[Renderer] InitWindow failed\n" ); + return false; + } - ////////////////////////////////////////////////////////////////////////// + if ( !InitDirect3D( settings ) ) + { + printf( "[Renderer] InitDirect3D failed\n" ); + return false; + } - pDevice->CreateVertexBuffer( GUIQUADVB_SIZE * 6 * sizeof(float), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1, D3DPOOL_DEFAULT, &pGUIQuadVB, NULL); + static D3DVERTEXELEMENT9 pFullscreenQuadElements[] = + { + { 0, 0 * sizeof( float ), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, + { 0, 3 * sizeof( float ), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, + D3DDECL_END() + }; - ////////////////////////////////////////////////////////////////////////// + static float pQuad[] = + { + -1.0, -1.0, 0.0, 0.0 + 0.5 / (float) nWidth, 0.0 + 0.5 / (float) nHeight, + -1.0, 1.0, 0.0, 0.0 + 0.5 / (float) nWidth, 1.0 + 0.5 / (float) nHeight, + 1.0, -1.0, 0.0, 1.0 + 0.5 / (float) nWidth, 0.0 + 0.5 / (float) nHeight, + 1.0, 1.0, 0.0, 1.0 + 0.5 / (float) nWidth, 1.0 + 0.5 / (float) nHeight, + }; - LPD3DXBUFFER pShader = NULL; - LPD3DXBUFFER pErrors = NULL; + pDevice->CreateVertexBuffer( 4 * 5 * sizeof( float ), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_TEX1, D3DPOOL_DEFAULT, &pFullscreenQuadVB, NULL ); + void * v; + pFullscreenQuadVB->Lock( 0, 4 * 5 * sizeof( float ), &v, NULL ); + CopyMemory( v, pQuad, 4 * 5 * sizeof( float ) ); + pFullscreenQuadVB->Unlock(); - if (D3DXCompileShader( defaultVertexShader, strlen(defaultVertexShader), NULL, NULL, "main", "vs_3_0", NULL, &pShader, &pErrors, NULL ) != D3D_OK) - { - printf("[Renderer] D3DXCompileShader failed\n"); - return false; - } + pDevice->CreateVertexDeclaration( pFullscreenQuadElements, &pFullscreenQuadVertexDecl ); - if (pDevice->CreateVertexShader( (DWORD*)pShader->GetBufferPointer(), &pVertexShader ) != D3D_OK) - { - printf("[Renderer] CreateVertexShader failed\n"); - return false; - } + ////////////////////////////////////////////////////////////////////////// - if (pDevice->CreateOffscreenPlainSurface( settings->nWidth, settings->nHeight, d3dpp.BackBufferFormat, D3DPOOL_SYSTEMMEM, &pFrameGrabTexture, NULL) != D3D_OK) - { - printf("[Renderer] CreateOffscreenPlainSurface failed\n"); - return false; - } + pDevice->CreateVertexBuffer( GUIQUADVB_SIZE * 6 * sizeof( float ), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1, D3DPOOL_DEFAULT, &pGUIQuadVB, NULL ); - return true; - } + ////////////////////////////////////////////////////////////////////////// - unsigned int nCacheFlushCount = 0; - void StartFrame() - { - nCacheFlushCount = 0; - MSG msg; - if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) - { - TranslateMessage( &msg ); - DispatchMessage( &msg ); - } + LPD3DXBUFFER pShader = NULL; + LPD3DXBUFFER pErrors = NULL; - pDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0xFF808080, 1.0f, 0 ); - pDevice->BeginScene(); - } - void EndFrame() + if ( D3DXCompileShader( defaultVertexShader, strlen( defaultVertexShader ), NULL, NULL, "main", "vs_3_0", NULL, &pShader, &pErrors, NULL ) != D3D_OK ) { - pDevice->EndScene(); - pDevice->Present( NULL, NULL, NULL, NULL ); + printf( "[Renderer] D3DXCompileShader failed\n" ); + return false; } - bool WantsToQuit() + + if ( pDevice->CreateVertexShader( (DWORD *) pShader->GetBufferPointer(), &pVertexShader ) != D3D_OK ) { - return !run; + printf( "[Renderer] CreateVertexShader failed\n" ); + return false; } - void Close() + + if ( pDevice->CreateOffscreenPlainSurface( settings->nWidth, settings->nHeight, d3dpp.BackBufferFormat, D3DPOOL_SYSTEMMEM, &pFrameGrabTexture, NULL ) != D3D_OK ) { - if (pFullscreenQuadVB) pFullscreenQuadVB->Release(); - if (pFullscreenQuadVertexDecl) pFullscreenQuadVertexDecl->Release(); - if (pGUIQuadVB) pGUIQuadVB->Release(); - if (pVertexShader) pVertexShader->Release(); - if (theShader) theShader->Release(); - if (pDevice) pDevice->Release(); - if (pD3D) pD3D->Release(); - if (hWnd) - { - DestroyWindow(hWnd); - UnregisterClass(_T("fwzwnd"),GetModuleHandle(NULL)); - } + printf( "[Renderer] CreateOffscreenPlainSurface failed\n" ); + return false; } - void RenderFullscreenQuad() + return true; +} + +unsigned int nCacheFlushCount = 0; +void StartFrame() +{ + nCacheFlushCount = 0; + MSG msg; + if ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { - pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, false ); - - pDevice->SetVertexShader( pVertexShader ); - pDevice->SetPixelShader( theShader ); - - pDevice->SetVertexDeclaration( pFullscreenQuadVertexDecl ); - pDevice->SetStreamSource( 0, pFullscreenQuadVB, 0, sizeof(float) * 5 ); - pDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 ); + TranslateMessage( &msg ); + DispatchMessage( &msg ); } - bool ReloadShader( const char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize ) + pDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0xFF808080, 1.0f, 0 ); + pDevice->BeginScene(); +} +void EndFrame() +{ + pDevice->EndScene(); + pDevice->Present( NULL, NULL, NULL, NULL ); +} +bool WantsToQuit() +{ + return !run; +} +void Close() +{ + if ( pFullscreenQuadVB ) pFullscreenQuadVB->Release(); + if ( pFullscreenQuadVertexDecl ) pFullscreenQuadVertexDecl->Release(); + if ( pGUIQuadVB ) pGUIQuadVB->Release(); + if ( pVertexShader ) pVertexShader->Release(); + if ( theShader ) theShader->Release(); + if ( pDevice ) pDevice->Release(); + if ( pD3D ) pD3D->Release(); + if ( hWnd ) { - LPD3DXBUFFER pShader = NULL; - LPD3DXBUFFER pErrors = NULL; + DestroyWindow( hWnd ); + UnregisterClass( _T( "fwzwnd" ), GetModuleHandle( NULL ) ); + } +} - if (D3DXCompileShader( szShaderCode, nShaderCodeSize, NULL, NULL, "main", "ps_3_0", NULL, &pShader, &pErrors, &pConstantTable ) != D3D_OK) - { - memset( szErrorBuffer, 0, nErrorBufferSize ); - strncpy( szErrorBuffer, (const char*)pErrors->GetBufferPointer(), nErrorBufferSize - 1 ); - return false; - } +void RenderFullscreenQuad() +{ + pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, false ); - if (theShader) - { - theShader->Release(); - theShader = NULL; - } + pDevice->SetVertexShader( pVertexShader ); + pDevice->SetPixelShader( theShader ); - if (pDevice->CreatePixelShader( (DWORD*)pShader->GetBufferPointer(), &theShader ) != D3D_OK) - { - return false; - } + pDevice->SetVertexDeclaration( pFullscreenQuadVertexDecl ); + pDevice->SetStreamSource( 0, pFullscreenQuadVB, 0, sizeof( float ) * 5 ); + pDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 ); +} - return true; - } +bool ReloadShader( const char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize ) +{ + LPD3DXBUFFER pShader = NULL; + LPD3DXBUFFER pErrors = NULL; - void SetShaderConstant( const char * szConstName, float x ) + if ( D3DXCompileShader( szShaderCode, nShaderCodeSize, NULL, NULL, "main", "ps_3_0", NULL, &pShader, &pErrors, &pConstantTable ) != D3D_OK ) { - pConstantTable->SetFloat( pDevice, szConstName, x ); + memset( szErrorBuffer, 0, nErrorBufferSize ); + strncpy( szErrorBuffer, (const char *) pErrors->GetBufferPointer(), nErrorBufferSize - 1 ); + return false; } - static D3DXVECTOR4 SetShaderConstant_VEC4; - void SetShaderConstant( const char * szConstName, float x, float y ) + if ( theShader ) { - SetShaderConstant_VEC4.x = x; - SetShaderConstant_VEC4.y = y; - SetShaderConstant_VEC4.z = 0; - SetShaderConstant_VEC4.w = 0; - pConstantTable->SetVector( pDevice, szConstName, &SetShaderConstant_VEC4 ); + theShader->Release(); + theShader = NULL; } - struct DX9Texture : public Texture + if ( pDevice->CreatePixelShader( (DWORD *) pShader->GetBufferPointer(), &theShader ) != D3D_OK ) { - LPDIRECT3DTEXTURE9 pTexture; - }; + return false; + } - int textureUnit = 0; + return true; +} - Renderer::Texture * CreateRGBA8Texture() - { - LPDIRECT3DTEXTURE9 pTex = NULL; - pDevice->CreateTexture( nWidth, nHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &pTex, NULL ); +void SetShaderConstant( const char * szConstName, float x ) +{ + pConstantTable->SetFloat( pDevice, szConstName, x ); +} - if ( !pTex ) - return NULL; +static D3DXVECTOR4 SetShaderConstant_VEC4; +void SetShaderConstant( const char * szConstName, float x, float y ) +{ + SetShaderConstant_VEC4.x = x; + SetShaderConstant_VEC4.y = y; + SetShaderConstant_VEC4.z = 0; + SetShaderConstant_VEC4.w = 0; + pConstantTable->SetVector( pDevice, szConstName, &SetShaderConstant_VEC4 ); +} - DX9Texture * tex = new DX9Texture(); - tex->pTexture = pTex; - tex->width = nWidth; - tex->height = nHeight; - tex->type = TEXTURETYPE_2D; - return tex; +struct DX9Texture : public Texture +{ + LPDIRECT3DTEXTURE9 pTexture; +}; - } +int textureUnit = 0; - Texture * CreateRGBA8TextureFromFile( const char * szFilename ) - { - LPDIRECT3DTEXTURE9 pTex = NULL; - D3DXIMAGE_INFO info; - HRESULT h = D3DXCreateTextureFromFileExA( - pDevice, - szFilename, - D3DX_DEFAULT_NONPOW2, - D3DX_DEFAULT_NONPOW2, - 0, - NULL, - D3DFMT_FROM_FILE, - D3DPOOL_DEFAULT, - D3DX_DEFAULT, - D3DX_DEFAULT, - NULL, - &info, - NULL, - &pTex); - - if (!pTex) - return NULL; - - DX9Texture * tex = new DX9Texture(); - tex->pTexture = pTex; - tex->width = info.Width; - tex->height = info.Height; - tex->type = TEXTURETYPE_2D; - return tex; - } +Renderer::Texture * CreateRGBA8Texture() +{ + LPDIRECT3DTEXTURE9 pTex = NULL; + pDevice->CreateTexture( nWidth, nHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &pTex, NULL ); - Texture * Create1DR32Texture( int w ) - { - LPDIRECT3DTEXTURE9 pTex = NULL; - pDevice->CreateTexture( w, 1, 0, D3DUSAGE_DYNAMIC, D3DFMT_R32F, D3DPOOL_DEFAULT, &pTex, NULL ); - - if (!pTex) - return NULL; - - D3DLOCKED_RECT rect; - pTex->LockRect( 0, &rect, NULL, NULL ); - memset( rect.pBits, 0, w * sizeof(float) ); - pTex->UnlockRect(0); - - DX9Texture * tex = new DX9Texture(); - tex->pTexture = pTex; - tex->width = w; - tex->height = 1; - tex->type = TEXTURETYPE_1D; - return tex; - } + if ( !pTex ) + return NULL; - void SetShaderTexture( const char * szTextureName, Texture * tex ) - { - int idx = pConstantTable->GetSamplerIndex( szTextureName ); - if (idx >= 0) - { - pDevice->SetSamplerState( idx, D3DSAMP_SRGBTEXTURE, TRUE ); - pDevice->SetSamplerState( idx, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP ); - pDevice->SetSamplerState( idx, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP ); - pDevice->SetTexture( idx, ((DX9Texture *)tex)->pTexture ); - } - } + DX9Texture * tex = new DX9Texture(); + tex->pTexture = pTex; + tex->width = nWidth; + tex->height = nHeight; + tex->type = TEXTURETYPE_2D; + return tex; + +} - bool UpdateR32Texture( Texture * tex, float * data ) +Texture * CreateRGBA8TextureFromFile( const char * szFilename ) +{ + LPDIRECT3DTEXTURE9 pTex = NULL; + D3DXIMAGE_INFO info; + HRESULT h = D3DXCreateTextureFromFileExA( + pDevice, + szFilename, + D3DX_DEFAULT_NONPOW2, + D3DX_DEFAULT_NONPOW2, + 0, + NULL, + D3DFMT_FROM_FILE, + D3DPOOL_DEFAULT, + D3DX_DEFAULT, + D3DX_DEFAULT, + NULL, + &info, + NULL, + &pTex ); + + if ( !pTex ) + return NULL; + + DX9Texture * tex = new DX9Texture(); + tex->pTexture = pTex; + tex->width = info.Width; + tex->height = info.Height; + tex->type = TEXTURETYPE_2D; + return tex; +} + +Texture * Create1DR32Texture( int w ) +{ + LPDIRECT3DTEXTURE9 pTex = NULL; + pDevice->CreateTexture( w, 1, 0, D3DUSAGE_DYNAMIC, D3DFMT_R32F, D3DPOOL_DEFAULT, &pTex, NULL ); + + if ( !pTex ) + return NULL; + + D3DLOCKED_RECT rect; + pTex->LockRect( 0, &rect, NULL, NULL ); + memset( rect.pBits, 0, w * sizeof( float ) ); + pTex->UnlockRect( 0 ); + + DX9Texture * tex = new DX9Texture(); + tex->pTexture = pTex; + tex->width = w; + tex->height = 1; + tex->type = TEXTURETYPE_1D; + return tex; +} + +void SetShaderTexture( const char * szTextureName, Texture * tex ) +{ + int idx = pConstantTable->GetSamplerIndex( szTextureName ); + if ( idx >= 0 ) { - LPDIRECT3DTEXTURE9 pTex = ((DX9Texture *)tex)->pTexture; - - D3DLOCKED_RECT rect; - pTex->LockRect( 0, &rect, NULL, D3DLOCK_DISCARD ); - memcpy( rect.pBits, data, tex->width * sizeof(float) ); - pTex->UnlockRect(0); - - return true; + pDevice->SetSamplerState( idx, D3DSAMP_SRGBTEXTURE, TRUE ); + pDevice->SetSamplerState( idx, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP ); + pDevice->SetSamplerState( idx, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP ); + pDevice->SetTexture( idx, ( (DX9Texture *) tex )->pTexture ); } +} - Texture * CreateA8TextureFromData( int w, int h, const unsigned char * data ) - { - LPDIRECT3DTEXTURE9 pTex = NULL; - pDevice->CreateTexture( w, h, 0, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &pTex, NULL ); +bool UpdateR32Texture( Texture * tex, float * data ) +{ + LPDIRECT3DTEXTURE9 pTex = ( (DX9Texture *) tex )->pTexture; - if (!pTex) - return NULL; + D3DLOCKED_RECT rect; + pTex->LockRect( 0, &rect, NULL, D3DLOCK_DISCARD ); + memcpy( rect.pBits, data, tex->width * sizeof( float ) ); + pTex->UnlockRect( 0 ); - D3DLOCKED_RECT rect; - pTex->LockRect( 0, &rect, NULL, NULL ); - const unsigned char * src = data; - unsigned char * dst = (unsigned char *)rect.pBits; - for (int i=0; iUnlockRect(0); - - DX9Texture * tex = new DX9Texture(); - tex->pTexture = pTex; - tex->width = w; - tex->height = h; - tex->type = TEXTURETYPE_1D; - return tex; - } + return true; +} - void ReleaseTexture( Texture * tex ) - { - ( (DX9Texture *) tex )->pTexture->Release(); - delete tex; - } +Texture * CreateA8TextureFromData( int w, int h, const unsigned char * data ) +{ + LPDIRECT3DTEXTURE9 pTex = NULL; + pDevice->CreateTexture( w, h, 0, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &pTex, NULL ); + + if ( !pTex ) + return NULL; - void CopyBackbufferToTexture( Texture * tex ) + D3DLOCKED_RECT rect; + pTex->LockRect( 0, &rect, NULL, NULL ); + const unsigned char * src = data; + unsigned char * dst = (unsigned char *) rect.pBits; + for ( int i = 0; i < h; i++ ) { - LPDIRECT3DTEXTURE9 pTex = ( (DX9Texture *) tex )->pTexture; - LPDIRECT3DSURFACE9 pSurf = NULL; - pTex->GetSurfaceLevel( 0, &pSurf ); - if ( pSurf ) + const unsigned char * srcLine = src; + unsigned int * dstLine = (unsigned int *) dst; + for ( int j = 0; j < w; j++ ) { - HRESULT res = pDevice->StretchRect( pBackBuffer, NULL, pSurf, NULL, D3DTEXF_LINEAR ); - pSurf->Release(); + *dstLine = ( *srcLine << 24 ) | 0xFFFFFF; + srcLine++; + dstLine++; } + src += w * sizeof( unsigned char ); + dst += rect.Pitch; } + pTex->UnlockRect( 0 ); + + DX9Texture * tex = new DX9Texture(); + tex->pTexture = pTex; + tex->width = w; + tex->height = h; + tex->type = TEXTURETYPE_1D; + return tex; +} - ////////////////////////////////////////////////////////////////////////// - // text rendering +void ReleaseTexture( Texture * tex ) +{ + ( (DX9Texture *) tex )->pTexture->Release(); + delete tex; +} - void StartTextRendering() +void CopyBackbufferToTexture( Texture * tex ) +{ + LPDIRECT3DTEXTURE9 pTex = ( (DX9Texture *) tex )->pTexture; + LPDIRECT3DSURFACE9 pSurf = NULL; + pTex->GetSurfaceLevel( 0, &pSurf ); + if ( pSurf ) { - pDevice->SetVertexShader( NULL ); - pDevice->SetPixelShader( NULL ); - pDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, TRUE ); - //pDevice->SetVertexDeclaration( pGUIVertexDecl ); - pDevice->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); - pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); - pDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); - pDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); - - D3DXMATRIX mat; - D3DXMatrixIdentity( &mat ); - pDevice->SetTransform( D3DTS_VIEW, &mat ); - pDevice->SetTransform( D3DTS_WORLD, &mat ); - D3DXMatrixOrthoOffCenterLH( (D3DXMATRIX*)&mat, 0, nWidth, nHeight, 0, -1.0f, 1.0f ); - pDevice->SetTransform( D3DTS_PROJECTION, &mat ); - - pDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); - pDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE ); - pDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_TEXTURE ); - pDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); - pDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE ); - pDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_TEXTURE ); + HRESULT res = pDevice->StretchRect( pBackBuffer, NULL, pSurf, NULL, D3DTEXF_LINEAR ); + pSurf->Release(); } +} - int bufferPointer = 0; - unsigned char buffer[GUIQUADVB_SIZE * sizeof(float) * 6]; - bool lastModeIsQuad = true; - void __FlushRenderCache() - { - if (!bufferPointer) return; +////////////////////////////////////////////////////////////////////////// +// text rendering - nCacheFlushCount++; - void * v = NULL; - pGUIQuadVB->Lock( 0, bufferPointer * sizeof(float) * 6, &v, NULL ); - CopyMemory( v, buffer, bufferPointer * sizeof(float) * 6 ); - pGUIQuadVB->Unlock(); +void StartTextRendering() +{ + pDevice->SetVertexShader( NULL ); + pDevice->SetPixelShader( NULL ); + pDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, TRUE ); + //pDevice->SetVertexDeclaration( pGUIVertexDecl ); + pDevice->SetFVF( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ); + pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); + pDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); + pDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); + + D3DXMATRIX mat; + D3DXMatrixIdentity( &mat ); + pDevice->SetTransform( D3DTS_VIEW, &mat ); + pDevice->SetTransform( D3DTS_WORLD, &mat ); + D3DXMatrixOrthoOffCenterLH( (D3DXMATRIX *) &mat, 0, nWidth, nHeight, 0, -1.0f, 1.0f ); + pDevice->SetTransform( D3DTS_PROJECTION, &mat ); + + pDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); + pDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE ); + pDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_TEXTURE ); + pDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); + pDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE ); + pDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_TEXTURE ); +} - pDevice->SetStreamSource( 0, pGUIQuadVB, 0, sizeof(float) * 6 ); - if (lastModeIsQuad) - pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, bufferPointer / 3 ); - else - pDevice->DrawPrimitive( D3DPT_LINELIST, 0, bufferPointer / 2 ); +int bufferPointer = 0; +unsigned char buffer[ GUIQUADVB_SIZE * sizeof( float ) * 6 ]; +bool lastModeIsQuad = true; +void __FlushRenderCache() +{ + if ( !bufferPointer ) return; - bufferPointer = 0; - } - inline unsigned int _dxARGBtoABGR(unsigned int abgr) - { - return (abgr&0xff00ff00)+((abgr<<16)&0x00ff0000)+((abgr>>16)&0x000000ff); - } - Texture * lastTexture = NULL; - void __WriteVertexToBuffer( const Vertex & v ) - { - if (bufferPointer >= GUIQUADVB_SIZE) - { - __FlushRenderCache(); - } + nCacheFlushCount++; + void * v = NULL; + pGUIQuadVB->Lock( 0, bufferPointer * sizeof( float ) * 6, &v, NULL ); + CopyMemory( v, buffer, bufferPointer * sizeof( float ) * 6 ); + pGUIQuadVB->Unlock(); - float * f = (float*)(buffer + bufferPointer * sizeof(float) * 6); - *(f++) = v.x; - *(f++) = v.y; - *(f++) = 0.0; - *(unsigned int *)(f++) = _dxARGBtoABGR( v.c ); - *(f++) = v.u + (lastTexture ? (0.5 / (float)lastTexture->width ) : 0.0); - *(f++) = v.v + (lastTexture ? (0.5 / (float)lastTexture->height) : 0.0); - bufferPointer++; - } - void BindTexture( Texture * tex ) - { - if (lastTexture != tex) - { - __FlushRenderCache(); - lastTexture = tex; - pDevice->SetTexture( 0, tex ? ((DX9Texture *)tex)->pTexture : NULL ); - } - } + pDevice->SetStreamSource( 0, pGUIQuadVB, 0, sizeof( float ) * 6 ); + if ( lastModeIsQuad ) + pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, bufferPointer / 3 ); + else + pDevice->DrawPrimitive( D3DPT_LINELIST, 0, bufferPointer / 2 ); - void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d ) + bufferPointer = 0; +} +inline unsigned int _dxARGBtoABGR( unsigned int abgr ) +{ + return ( abgr & 0xff00ff00 ) + ( ( abgr << 16 ) & 0x00ff0000 ) + ( ( abgr >> 16 ) & 0x000000ff ); +} +Texture * lastTexture = NULL; +void __WriteVertexToBuffer( const Vertex & v ) +{ + if ( bufferPointer >= GUIQUADVB_SIZE ) { - if (!lastModeIsQuad) - { - __FlushRenderCache(); - lastModeIsQuad = true; - } - __WriteVertexToBuffer(a); - __WriteVertexToBuffer(b); - __WriteVertexToBuffer(d); - __WriteVertexToBuffer(b); - __WriteVertexToBuffer(c); - __WriteVertexToBuffer(d); + __FlushRenderCache(); } - void RenderLine( const Vertex & a, const Vertex & b ) + float * f = (float *) ( buffer + bufferPointer * sizeof( float ) * 6 ); + *( f++ ) = v.x; + *( f++ ) = v.y; + *( f++ ) = 0.0; + *(unsigned int *) ( f++ ) = _dxARGBtoABGR( v.c ); + *( f++ ) = v.u + ( lastTexture ? ( 0.5 / (float) lastTexture->width ) : 0.0 ); + *( f++ ) = v.v + ( lastTexture ? ( 0.5 / (float) lastTexture->height ) : 0.0 ); + bufferPointer++; +} +void BindTexture( Texture * tex ) +{ + if ( lastTexture != tex ) { - if (lastModeIsQuad) - { - __FlushRenderCache(); - lastModeIsQuad = false; - } - __WriteVertexToBuffer(a); - __WriteVertexToBuffer(b); + __FlushRenderCache(); + lastTexture = tex; + pDevice->SetTexture( 0, tex ? ( (DX9Texture *) tex )->pTexture : NULL ); } +} - void SetTextRenderingViewport( Scintilla::PRectangle rect ) +void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d ) +{ + if ( !lastModeIsQuad ) { __FlushRenderCache(); - D3DXMATRIX mat; - D3DXMatrixIdentity( &mat ); - mat._41 = rect.left; - mat._42 = rect.top; - pDevice->SetTransform( D3DTS_WORLD, &mat ); - - RECT rc = { rect.left, rect.top, rect.right, rect.bottom }; - pDevice->SetScissorRect( &rc ); + lastModeIsQuad = true; } - void EndTextRendering() + __WriteVertexToBuffer( a ); + __WriteVertexToBuffer( b ); + __WriteVertexToBuffer( d ); + __WriteVertexToBuffer( b ); + __WriteVertexToBuffer( c ); + __WriteVertexToBuffer( d ); +} + +void RenderLine( const Vertex & a, const Vertex & b ) +{ + if ( lastModeIsQuad ) { __FlushRenderCache(); - pDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, false ); - pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, false ); + lastModeIsQuad = false; } + __WriteVertexToBuffer( a ); + __WriteVertexToBuffer( b ); +} - ////////////////////////////////////////////////////////////////////////// +void SetTextRenderingViewport( Scintilla::PRectangle rect ) +{ + __FlushRenderCache(); + D3DXMATRIX mat; + D3DXMatrixIdentity( &mat ); + mat._41 = rect.left; + mat._42 = rect.top; + pDevice->SetTransform( D3DTS_WORLD, &mat ); + + RECT rc = { rect.left, rect.top, rect.right, rect.bottom }; + pDevice->SetScissorRect( &rc ); +} +void EndTextRendering() +{ + __FlushRenderCache(); + pDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, false ); + pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, false ); +} - bool GrabFrame( void * pPixelBuffer ) - { - if (!pFrameGrabTexture) - return false; +////////////////////////////////////////////////////////////////////////// - if (pDevice->GetRenderTargetData( pBackBuffer, pFrameGrabTexture ) != D3D_OK) - return false; +bool GrabFrame( void * pPixelBuffer ) +{ + if ( !pFrameGrabTexture ) + return false; - D3DLOCKED_RECT rect; - if (pFrameGrabTexture->LockRect( &rect, NULL, NULL ) != D3D_OK) - return false; - - unsigned char* pSrc = (unsigned char*)rect.pBits; - unsigned char* pDst = (unsigned char*)pPixelBuffer; - for( int i = 0; i < nHeight; i++ ) - { - unsigned int* pSrc32 = (unsigned int*)pSrc; - unsigned int* pDst32 = (unsigned int*)pDst; - for(int j=0; j < nWidth; j++) - pDst32[j] = (pSrc32[j] & 0x00FF00) | ((pSrc32[j] >> 16) & 0xFF) | ((pSrc32[j] & 0xFF) << 16) | 0xFF000000; + if ( pDevice->GetRenderTargetData( pBackBuffer, pFrameGrabTexture ) != D3D_OK ) + return false; - pSrc += rect.Pitch; - pDst += nWidth * 4; - } + D3DLOCKED_RECT rect; + if ( pFrameGrabTexture->LockRect( &rect, NULL, NULL ) != D3D_OK ) + return false; - pFrameGrabTexture->UnlockRect(); + unsigned char * pSrc = (unsigned char *) rect.pBits; + unsigned char * pDst = (unsigned char *) pPixelBuffer; + for ( int i = 0; i < nHeight; i++ ) + { + unsigned int * pSrc32 = (unsigned int *) pSrc; + unsigned int * pDst32 = (unsigned int *) pDst; + for ( int j = 0; j < nWidth; j++ ) + pDst32[ j ] = ( pSrc32[ j ] & 0x00FF00 ) | ( ( pSrc32[ j ] >> 16 ) & 0xFF ) | ( ( pSrc32[ j ] & 0xFF ) << 16 ) | 0xFF000000; - return true; + pSrc += rect.Pitch; + pDst += nWidth * 4; } + + pFrameGrabTexture->UnlockRect(); + + return true; +} + +////////////////////////////////////////////////////////////////////////// }