diff --git a/src/Actor.cpp b/src/Actor.cpp index 8d53a33d23..7f50a4f6f6 100644 --- a/src/Actor.cpp +++ b/src/Actor.cpp @@ -1256,7 +1256,7 @@ const apActorCommands *Actor::GetCommand( const RString &sCommandName ) const { map::const_iterator it = m_mapNameToCommands.find( sCommandName ); if( it == m_mapNameToCommands.end() ) - return NULL; + return nullptr; return &it->second; } diff --git a/src/ActorFrame.cpp b/src/ActorFrame.cpp index 778584a3d7..4c555a2d32 100644 --- a/src/ActorFrame.cpp +++ b/src/ActorFrame.cpp @@ -172,7 +172,7 @@ Actor* ActorFrame::GetChild( const RString &sName ) if( a->GetName() == sName ) return a; } - return NULL; + return nullptr; } void ActorFrame::RemoveAllChildren() diff --git a/src/ActorUtil.cpp b/src/ActorUtil.cpp index 2e29d2c280..6d8630e716 100644 --- a/src/ActorUtil.cpp +++ b/src/ActorUtil.cpp @@ -111,7 +111,7 @@ Actor* ActorUtil::LoadFromNode( const XNode* pNode, Actor *pParentActor ) { bool bCond; if( pNode->GetAttrValue("Condition", bCond) && !bCond ) - return NULL; + return nullptr; } RString sClass; @@ -145,7 +145,7 @@ namespace { RString sScript; if( !GetFileContents(sFile, sScript) ) - return NULL; + return nullptr; Lua *L = LUA->Get(); @@ -155,7 +155,7 @@ namespace LUA->Release( L ); sError = ssprintf( "Lua runtime error: %s", sError.c_str() ); Dialog::OK( sError, "LUA_ERROR" ); - return NULL; + return nullptr; } XNode *pRet = NULL; diff --git a/src/AutoActor.cpp b/src/AutoActor.cpp index 04beddecdb..d004755df8 100644 --- a/src/AutoActor.cpp +++ b/src/AutoActor.cpp @@ -40,7 +40,7 @@ void AutoActor::Load( const RString &sPath ) Unload(); m_pActor = ActorUtil::MakeActor( sPath ); - // If a Condition is false, MakeActor will return NULL. + // If a Condition is false, MakeActor will return nullptr. if( m_pActor == nullptr ) m_pActor = new Actor; } diff --git a/src/AutoKeysounds.h b/src/AutoKeysounds.h index 554088aa53..ca6e14647c 100644 --- a/src/AutoKeysounds.h +++ b/src/AutoKeysounds.h @@ -18,7 +18,7 @@ public: void FinishLoading(); RageSound *GetSound() { return &m_sSound; } RageSoundReader *GetSharedSound() { return m_pSharedSound; } - RageSoundReader *GetPlayerSound( PlayerNumber pn ) { if( pn == PLAYER_INVALID ) return NULL; return m_pPlayerSounds[pn]; } + RageSoundReader *GetPlayerSound( PlayerNumber pn ) { if( pn == PLAYER_INVALID ) return nullptr; return m_pPlayerSounds[pn]; } protected: void LoadAutoplaySoundsInto( RageSoundReader_Chain *pChain ); diff --git a/src/CharacterManager.cpp b/src/CharacterManager.cpp index 707189354d..99d45c71c9 100644 --- a/src/CharacterManager.cpp +++ b/src/CharacterManager.cpp @@ -90,7 +90,7 @@ Character* CharacterManager::GetDefaultCharacter() /* We always have the default character. */ FAIL_M("There must be a default character available!"); - return NULL; + return nullptr; } void CharacterManager::DemandGraphics() @@ -113,7 +113,7 @@ Character* CharacterManager::GetCharacterFromID( RString sCharacterID ) return m_pCharacters[i]; } - return NULL; + return nullptr; } diff --git a/src/Course.cpp b/src/Course.cpp index 9cf08d2317..4b0b9a913a 100644 --- a/src/Course.cpp +++ b/src/Course.cpp @@ -313,7 +313,7 @@ Trail* Course::GetTrail( StepsType st, CourseDifficulty cd ) const { CacheData &cache = it->second; if( cache.null ) - return NULL; + return nullptr; return &cache.trail; } } @@ -331,7 +331,7 @@ Trail* Course::GetTrailForceRegenCache( StepsType st, CourseDifficulty cd ) cons { // This course difficulty doesn't exist. cache.null = true; - return NULL; + return nullptr; } // If we have cached RadarValues for this trail, insert them. @@ -738,7 +738,7 @@ const Style *Course::GetCourseStyle( const Game *pGame, int iNumPlayers ) const return pStyle; } } - return NULL; + return nullptr; } void Course::InvalidateTrailCache() diff --git a/src/FontCharmaps.cpp b/src/FontCharmaps.cpp index f7cdd9a743..cee6921e7f 100644 --- a/src/FontCharmaps.cpp +++ b/src/FontCharmaps.cpp @@ -226,7 +226,7 @@ const wchar_t *FontCharmaps::get_char_map(RString name) map::const_iterator i = charmaps.find(name); if(i == charmaps.end()) - return NULL; + return nullptr; return i->second; } diff --git a/src/GameManager.cpp b/src/GameManager.cpp index 9b290343fb..7cc24707bf 100644 --- a/src/GameManager.cpp +++ b/src/GameManager.cpp @@ -2921,7 +2921,7 @@ const Style* GameManager::GetEditorStyleForStepsType( StepsType st ) } ASSERT_M(0, ssprintf("The current game cannot use this Style with the editor!")); - return NULL; + return nullptr; } @@ -3012,7 +3012,7 @@ const Style *GameManager::GetFirstCompatibleStyle( const Game *pGame, int iNumPl return s; FAIL_M( ssprintf("No compatible styles for %s - %s with %d player%s.", pGame->m_szName, GetStepsTypeInfo(st).szName, iNumPlayers, iNumPlayers==1?"":"s") ); - return NULL; + return nullptr; } @@ -3100,7 +3100,7 @@ const Game* GameManager::StringToGame( RString sGame ) if( !sGame.CompareNoCase(g_Games[i]->m_szName) ) return g_Games[i]; - return NULL; + return nullptr; } @@ -3113,7 +3113,7 @@ const Style* GameManager::GameAndStringToStyle( const Game *game, RString sStyle return style; } - return NULL; + return nullptr; } // lua start diff --git a/src/GameState.cpp b/src/GameState.cpp index 3d78e33cd7..e19b2b230e 100644 --- a/src/GameState.cpp +++ b/src/GameState.cpp @@ -2072,7 +2072,7 @@ bool GameState::PlayerIsUsingModifier( PlayerNumber pn, const RString &sModifier Profile* GameState::GetEditLocalProfile() { if( m_sEditLocalProfileID.Get().empty() ) - return NULL; + return nullptr; return PROFILEMAN->GetLocalProfile( m_sEditLocalProfileID ); } diff --git a/src/InputFilter.cpp b/src/InputFilter.cpp index 56e7f6b7ed..5149ac3612 100644 --- a/src/InputFilter.cpp +++ b/src/InputFilter.cpp @@ -336,7 +336,7 @@ const T *FindItemBinarySearch( IT begin, IT end, const T &i ) { IT it = lower_bound( begin, end, i ); if( it == end || *it != i ) - return NULL; + return nullptr; return &*it; } diff --git a/src/LuaBinding.cpp b/src/LuaBinding.cpp index 06b27023ef..584a741aaa 100644 --- a/src/LuaBinding.cpp +++ b/src/LuaBinding.cpp @@ -326,7 +326,7 @@ void *LuaBinding::GetPointerFromStack( Lua *L, const RString &sType, int iArg ) return *pData; } else - return NULL; + return nullptr; } /* Tricky: when an instance table is copied, we want to do a deep diff --git a/src/ModelTypes.cpp b/src/ModelTypes.cpp index dd81ef3d93..5c600141db 100644 --- a/src/ModelTypes.cpp +++ b/src/ModelTypes.cpp @@ -131,7 +131,7 @@ void AnimatedTexture::Update( float fDelta ) RageTexture* AnimatedTexture::GetCurrentTexture() { if( vFrames.empty() ) - return NULL; + return nullptr; ASSERT( m_iCurState < (int)vFrames.size() ); return vFrames[m_iCurState].pTexture; } diff --git a/src/OptionRowHandler.cpp b/src/OptionRowHandler.cpp index 3f138b223c..705d8086bb 100644 --- a/src/OptionRowHandler.cpp +++ b/src/OptionRowHandler.cpp @@ -1323,7 +1323,7 @@ OptionRowHandler* OptionRowHandlerUtil::Make( const Commands &cmds ) OptionRowHandler* pHand = NULL; if( cmds.v.size() == 0 ) - return NULL; + return nullptr; const RString &name = cmds.v[0].GetName(); @@ -1335,7 +1335,7 @@ OptionRowHandler* OptionRowHandlerUtil::Make( const Commands &cmds ) const Command &command = cmds.v[0]; RString sParam = command.GetArg(1).s; if( command.m_vsArgs.size() != 2 || !sParam.size() ) - return NULL; + return nullptr; if( sParam.CompareNoCase("NoteSkins")==0 ) MAKE( OptionRowHandlerListNoteSkins ) else if( sParam.CompareNoCase("Steps")==0 ) MAKE( OptionRowHandlerListSteps ) diff --git a/src/Preference.cpp b/src/Preference.cpp index 19f2dee099..0c68f9b907 100644 --- a/src/Preference.cpp +++ b/src/Preference.cpp @@ -29,7 +29,7 @@ IPreference *IPreference::GetPreferenceByName( const RString &sName ) return p; } - return NULL; + return nullptr; } void IPreference::LoadAllDefaults() diff --git a/src/Profile.cpp b/src/Profile.cpp index 4a1ed90be0..82e436b6d6 100644 --- a/src/Profile.cpp +++ b/src/Profile.cpp @@ -1804,7 +1804,7 @@ const Profile::HighScoresForASong *Profile::GetHighScoresForASong( const SongID& map::const_iterator it; it = m_SongHighScores.find( songID ); if( it == m_SongHighScores.end() ) - return NULL; + return nullptr; return &it->second; } @@ -1813,7 +1813,7 @@ const Profile::HighScoresForACourse *Profile::GetHighScoresForACourse( const Cou map::const_iterator it; it = m_CourseHighScores.find( courseID ); if( it == m_CourseHighScores.end() ) - return NULL; + return nullptr; return &it->second; } diff --git a/src/ProfileManager.cpp b/src/ProfileManager.cpp index c2b4ae0bae..fa155cbad2 100644 --- a/src/ProfileManager.cpp +++ b/src/ProfileManager.cpp @@ -416,7 +416,7 @@ const Profile *ProfileManager::GetLocalProfile( const RString &sProfileID ) cons return &dap.profile; } - return NULL; + return nullptr; } bool ProfileManager::CreateLocalProfile( RString sName, RString &sProfileIDOut ) diff --git a/src/RageDisplay.h b/src/RageDisplay.h index 2dc3c79357..be4a595377 100644 --- a/src/RageDisplay.h +++ b/src/RageDisplay.h @@ -1,439 +1,439 @@ -/* RageDisplay - Renderer base class. */ - -#ifndef RAGEDISPLAY_H -#define RAGEDISPLAY_H - -#include "RageTypes.h" -#include "ModelTypes.h" -#include - -class DisplayResolution; -typedef set DisplayResolutions; - -const int REFRESH_DEFAULT = 0; -struct RageSurface; -enum TextureUnit -{ - TextureUnit_1, - TextureUnit_2, - TextureUnit_3, - TextureUnit_4, - NUM_TextureUnit -}; - -// RageCompiledGeometry holds vertex data in a format that is most efficient -// for the graphics API. -class RageCompiledGeometry -{ -public: - virtual ~RageCompiledGeometry(); - - void Set( const vector &vMeshes, bool bNeedsNormals ); - - virtual void Allocate( const vector &vMeshes ) = 0; // allocate space - virtual void Change( const vector &vMeshes ) = 0; // new data must be the same size as was passed to Set() - virtual void Draw( int iMeshIndex ) const = 0; - -protected: - size_t GetTotalVertices() const { if( m_vMeshInfo.empty() ) return 0; return m_vMeshInfo.back().iVertexStart + m_vMeshInfo.back().iVertexCount; } - size_t GetTotalTriangles() const { if( m_vMeshInfo.empty() ) return 0; return m_vMeshInfo.back().iTriangleStart + m_vMeshInfo.back().iTriangleCount; } - - struct MeshInfo - { - int iVertexStart; - int iVertexCount; - int iTriangleStart; - int iTriangleCount; - bool m_bNeedsTextureMatrixScale; - }; - vector m_vMeshInfo; - bool m_bNeedsNormals; - bool m_bAnyNeedsTextureMatrixScale; -}; - -enum RagePixelFormat -{ - RagePixelFormat_RGBA8, - RagePixelFormat_BGRA8, - RagePixelFormat_RGBA4, - RagePixelFormat_RGB5A1, - RagePixelFormat_RGB5, - RagePixelFormat_RGB8, - RagePixelFormat_PAL, - /* The above formats differ between OpenGL and D3D. These are provided as - * alternatives for OpenGL that match some format in D3D. Don't use them - * directly; they'll be matched automatically by FindPixelFormat. */ - RagePixelFormat_BGR8, - RagePixelFormat_A1BGR5, - RagePixelFormat_X1RGB5, - NUM_RagePixelFormat, - RagePixelFormat_Invalid -}; -const RString& RagePixelFormatToString( RagePixelFormat i ); - -/** @brief The parameters used for the present Video Mode. */ -class VideoModeParams -{ -public: - // Initialize with a constructor so to guarantee all paramters - // are filled (in case new params are added). - VideoModeParams( - bool windowed_, - int width_, - int height_, - int bpp_, - int rate_, - bool vsync_, - bool interlaced_, - bool bSmoothLines_, - bool bTrilinearFiltering_, - bool bAnisotropicFiltering_, - RString sWindowTitle_, - RString sIconFile_, - bool PAL_, - float fDisplayAspectRatio_ - ): - windowed(windowed_), - width(width_), - height(height_), - bpp(bpp_), - rate(rate_), - vsync(vsync_), - interlaced(interlaced_), - bSmoothLines(bSmoothLines_), - bTrilinearFiltering(bTrilinearFiltering_), - bAnisotropicFiltering(bAnisotropicFiltering_), - sWindowTitle(sWindowTitle_), - sIconFile(sIconFile_), - PAL(PAL_), - fDisplayAspectRatio(fDisplayAspectRatio_) {} - - VideoModeParams(): windowed(false), width(0), height(0), - bpp(0), rate(0), vsync(false), interlaced(false), - bSmoothLines(false), bTrilinearFiltering(false), - bAnisotropicFiltering(false), sWindowTitle(RString()), - sIconFile(RString()), PAL(false), fDisplayAspectRatio(0.0f) {} - - bool windowed; - int width; - int height; - int bpp; - int rate; - bool vsync; - bool interlaced; - bool bSmoothLines; - bool bTrilinearFiltering; - bool bAnisotropicFiltering; - RString sWindowTitle; - RString sIconFile; - bool PAL; - float fDisplayAspectRatio; -}; - -struct RenderTargetParam -{ - RenderTargetParam(): - iWidth(0), - iHeight(0), - bWithDepthBuffer(false), - bWithAlpha(false), - bFloat(false) - { - } - - // The dimensions of the actual render target, analogous to a window size: - int iWidth, iHeight; - - bool bWithDepthBuffer; - bool bWithAlpha; - bool bFloat; -}; - -struct RageTextureLock -{ - virtual ~RageTextureLock() { } - - /* Given a surface with a format and no pixel data, lock the texture into the - * surface. The data is write-only. */ - virtual void Lock( unsigned iTexHandle, RageSurface *pSurface ) = 0; - - /* Unlock and update the texture. If bChanged is false, the texture update - * may be omitted. */ - virtual void Unlock( RageSurface *pSurface, bool bChanged = true ) = 0; -}; - -class RageDisplay -{ - friend class RageTexture; - -public: - - struct RagePixelFormatDesc { - int bpp; - unsigned int masks[4]; - }; - - virtual const RagePixelFormatDesc *GetPixelFormatDesc( RagePixelFormat pf ) const = 0; - - RageDisplay(); - virtual ~RageDisplay(); - - virtual RString Init( const VideoModeParams &p, bool bAllowUnacceleratedRenderer ) = 0; - - virtual RString GetApiDescription() const = 0; - virtual void GetDisplayResolutions( DisplayResolutions &out ) const = 0; - - // Don't override this. Override TryVideoMode() instead. - // This will set the video mode to be as close as possible to params. - // Return true if device was re-created and we need to reload textures. - RString SetVideoMode( VideoModeParams p, bool &bNeedReloadTextures ); - - // Call this when the resolution has been changed externally: - virtual void ResolutionChanged(); - - virtual bool BeginFrame(); - virtual void EndFrame(); - virtual VideoModeParams GetActualVideoModeParams() const = 0; - bool IsWindowed() const { return this->GetActualVideoModeParams().windowed; } - - virtual void SetBlendMode( BlendMode mode ) = 0; - - virtual bool SupportsTextureFormat( RagePixelFormat pixfmt, bool realtime=false ) = 0; - virtual bool SupportsThreadedRendering() { return false; } - virtual bool SupportsPerVertexMatrixScale() = 0; - - // If threaded rendering is supported, these will be called from the - // rendering thread before and after rendering. - virtual void BeginConcurrentRenderingMainThread() { } - virtual void EndConcurrentRenderingMainThread() { } - virtual void BeginConcurrentRendering(); - virtual void EndConcurrentRendering() { } - - /* return 0 if failed or internal texture resource handle - * (unsigned in OpenGL, texture pointer in D3D) */ - virtual unsigned CreateTexture( - RagePixelFormat pixfmt, // format of img and of texture in video mem - RageSurface* img, // must be in pixfmt - bool bGenerateMipMaps - ) = 0; - virtual void UpdateTexture( - unsigned iTexHandle, - RageSurface* img, - int xoffset, int yoffset, int width, int height - ) = 0; - virtual void DeleteTexture( unsigned iTexHandle ) = 0; - /* Return an object to lock pixels for streaming. If not supported, returns NULL. - * Delete the object normally. */ - virtual RageTextureLock *CreateTextureLock() { return NULL; } - virtual void ClearAllTextures() = 0; - virtual int GetNumTextureUnits() = 0; - virtual void SetTexture( TextureUnit, unsigned /* iTexture */ ) = 0; - virtual void SetTextureMode( TextureUnit, TextureMode ) = 0; - virtual void SetTextureWrapping( TextureUnit, bool ) = 0; - virtual int GetMaxTextureSize() const = 0; - virtual void SetTextureFiltering( TextureUnit, bool ) = 0; - virtual void SetEffectMode( EffectMode ) { } - virtual bool IsEffectModeSupported( EffectMode effect ) { return effect == EffectMode_Normal; } - - bool SupportsRenderToTexture() const { return false; } - - /* Create a render target, returning a texture handle. In addition to normal - * texture functions, this can be passed to SetRenderTarget. Delete with - * DeleteTexture. (UpdateTexture is not permitted.) Returns 0 if render-to- - * texture is unsupported. - */ - virtual unsigned CreateRenderTarget( const RenderTargetParam &, int & /* iTextureWidthOut */, int & /* iTextureHeightOut */ ) { return 0; } - - /* Set the render target, or 0 to resume rendering to the framebuffer. An active render - * target may not be used as a texture. If bPreserveTexture is true, the contents - * of the texture will be preserved from the previous call; otherwise, cleared. If - * bPreserveTexture is true the first time a render target is used, behave as if - * bPreserveTexture was false. - */ - virtual void SetRenderTarget( unsigned /* iHandle */, bool /* bPreserveTexture */ = true ) { } - - virtual bool IsZTestEnabled() const = 0; - virtual bool IsZWriteEnabled() const = 0; - virtual void SetZWrite( bool ) = 0; - virtual void SetZTestMode( ZTestMode ) = 0; - virtual void SetZBias( float ) = 0; - virtual void ClearZBuffer() = 0; - - virtual void SetCullMode( CullMode mode ) = 0; - - virtual void SetAlphaTest( bool b ) = 0; - - virtual void SetMaterial( - const RageColor &emissive, - const RageColor &ambient, - const RageColor &diffuse, - const RageColor &specular, - float shininess - ) = 0; - - virtual void SetLighting( bool b ) = 0; - virtual void SetLightOff( int index ) = 0; - virtual void SetLightDirectional( - int index, - const RageColor &ambient, - const RageColor &diffuse, - const RageColor &specular, - const RageVector3 &dir ) = 0; - - virtual void SetSphereEnvironmentMapping( TextureUnit tu, bool b ) = 0; - virtual void SetCelShaded( int stage ) = 0; - - virtual RageCompiledGeometry* CreateCompiledGeometry() = 0; - virtual void DeleteCompiledGeometry( RageCompiledGeometry* p ) = 0; - - void DrawQuads( const RageSpriteVertex v[], int iNumVerts ); - void DrawQuadStrip( const RageSpriteVertex v[], int iNumVerts ); - void DrawFan( const RageSpriteVertex v[], int iNumVerts ); - void DrawStrip( const RageSpriteVertex v[], int iNumVerts ); - void DrawTriangles( const RageSpriteVertex v[], int iNumVerts ); - void DrawCompiledGeometry( const RageCompiledGeometry *p, int iMeshIndex, const vector &vMeshes ); - void DrawLineStrip( const RageSpriteVertex v[], int iNumVerts, float LineWidth ); - void DrawSymmetricQuadStrip( const RageSpriteVertex v[], int iNumVerts ); - void DrawCircle( const RageSpriteVertex &v, float radius ); - - void DrawQuad( const RageSpriteVertex v[] ) { DrawQuads(v,4); } /* alias. upper-left, upper-right, lower-left, lower-right */ - - // hacks for cell-shaded models - virtual void SetPolygonMode( PolygonMode ) {} - virtual void SetLineWidth( float ) {} - - enum GraphicsFileFormat - { - SAVE_LOSSLESS, // bmp - SAVE_LOSSLESS_SENSIBLE, // png - SAVE_LOSSY_LOW_QUAL, // jpg - SAVE_LOSSY_HIGH_QUAL // jpg - }; - bool SaveScreenshot( RString sPath, GraphicsFileFormat format ); - - virtual RString GetTextureDiagnostics( unsigned /* id */ ) const { return RString(); } - virtual RageSurface* CreateScreenshot() = 0; // allocates a surface. Caller must delete it. - virtual RageSurface *GetTexture( unsigned /* iTexture */ ) { return NULL; } // allocates a surface. Caller must delete it. - -protected: - virtual void DrawQuadsInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; - virtual void DrawQuadStripInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; - virtual void DrawFanInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; - virtual void DrawStripInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; - virtual void DrawTrianglesInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; - virtual void DrawCompiledGeometryInternal( const RageCompiledGeometry *p, int iMeshIndex ) = 0; - virtual void DrawLineStripInternal( const RageSpriteVertex v[], int iNumVerts, float LineWidth ); - virtual void DrawSymmetricQuadStripInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; - virtual void DrawCircleInternal( const RageSpriteVertex &v, float radius ); - - // return RString() if mode change was successful, an error message otherwise. - // bNewDeviceOut is set true if a new device was created and textures - // need to be reloaded. - virtual RString TryVideoMode( const VideoModeParams &p, bool &bNewDeviceOut ) = 0; - - void DrawPolyLine( const RageSpriteVertex &p1, const RageSpriteVertex &p2, float LineWidth ); - - // Stuff in RageDisplay.cpp - void SetDefaultRenderStates(); - -public: - // Statistics - int GetFPS() const; - int GetVPF() const; - int GetCumFPS() const; // average FPS since last reset - virtual void ResetStats(); - virtual void ProcessStatsOnFlip(); - virtual RString GetStats() const; - void StatsAddVerts( int iNumVertsRendered ); - - // World matrix stack functions. - void PushMatrix(); - void PopMatrix(); - void Translate( float x, float y, float z ); - void TranslateWorld( float x, float y, float z ); - void Scale( float x, float y, float z ); - void RotateX( float deg ); - void RotateY( float deg ); - void RotateZ( float deg ); - void SkewX( float fAmount ); - void SkewY( float fAmount ); - void MultMatrix( const RageMatrix &f ) { this->PostMultMatrix(f); } /* alias */ - void PostMultMatrix( const RageMatrix &f ); - void PreMultMatrix( const RageMatrix &f ); - void LoadIdentity(); - - // Texture matrix functions - void TexturePushMatrix(); - void TexturePopMatrix(); - void TextureTranslate( float x, float y ); - void TextureTranslate( const RageVector2 &v ) { this->TextureTranslate( v.x, v.y ); } - - // Projection and View matrix stack functions. - void CameraPushMatrix(); - void CameraPopMatrix(); - void LoadMenuPerspective( float fFOVDegrees, float fWidth, float fHeight, float fVanishPointX, float fVanishPointY ); - void LoadLookAt( float fov, const RageVector3 &Eye, const RageVector3 &At, const RageVector3 &Up ); - - // Centering matrix - void CenteringPushMatrix(); - void CenteringPopMatrix(); - void ChangeCentering( int trans_x, int trans_y, int add_width, int add_height ); - - RageSurface *CreateSurfaceFromPixfmt( RagePixelFormat pixfmt, void *pixels, int width, int height, int pitch ); - RagePixelFormat FindPixelFormat( int bpp, unsigned Rmask, unsigned Gmask, unsigned Bmask, unsigned Amask, bool realtime=false ); - - // Lua - void PushSelf( lua_State *L ); - -protected: - RageMatrix GetPerspectiveMatrix( float fovy, float aspect, float zNear, float zFar ); - - // Different for D3D and OpenGL. Not sure why they're not compatible. -Chris - virtual RageMatrix GetOrthoMatrix( float l, float r, float b, float t, float zn, float zf ); - virtual RageMatrix GetFrustumMatrix( float l, float r, float b, float t, float zn, float zf ); - - // Matrix that adjusts position and scale of image on the screen - RageMatrix GetCenteringMatrix( float fTranslateX, float fTranslateY, float fAddWidth, float fAddHeight ) const; - void UpdateCentering(); - - // Called by the RageDisplay derivitives - const RageMatrix* GetCentering() const; - const RageMatrix* GetProjectionTop() const; - const RageMatrix* GetViewTop() const; - const RageMatrix* GetWorldTop() const; - const RageMatrix* GetTextureTop() const; - - // To limit the framerate, call FrameLimitBeforeVsync before waiting - // for vsync and FrameLimitAfterVsync after. - void FrameLimitBeforeVsync( int iFPS ); - void FrameLimitAfterVsync(); -}; - - -extern RageDisplay* DISPLAY; // global and accessable from anywhere in our program - -#endif -/* - * Copyright (c) 2001-2004 Chris Danford, Glenn Maynard - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* RageDisplay - Renderer base class. */ + +#ifndef RAGEDISPLAY_H +#define RAGEDISPLAY_H + +#include "RageTypes.h" +#include "ModelTypes.h" +#include + +class DisplayResolution; +typedef set DisplayResolutions; + +const int REFRESH_DEFAULT = 0; +struct RageSurface; +enum TextureUnit +{ + TextureUnit_1, + TextureUnit_2, + TextureUnit_3, + TextureUnit_4, + NUM_TextureUnit +}; + +// RageCompiledGeometry holds vertex data in a format that is most efficient +// for the graphics API. +class RageCompiledGeometry +{ +public: + virtual ~RageCompiledGeometry(); + + void Set( const vector &vMeshes, bool bNeedsNormals ); + + virtual void Allocate( const vector &vMeshes ) = 0; // allocate space + virtual void Change( const vector &vMeshes ) = 0; // new data must be the same size as was passed to Set() + virtual void Draw( int iMeshIndex ) const = 0; + +protected: + size_t GetTotalVertices() const { if( m_vMeshInfo.empty() ) return 0; return m_vMeshInfo.back().iVertexStart + m_vMeshInfo.back().iVertexCount; } + size_t GetTotalTriangles() const { if( m_vMeshInfo.empty() ) return 0; return m_vMeshInfo.back().iTriangleStart + m_vMeshInfo.back().iTriangleCount; } + + struct MeshInfo + { + int iVertexStart; + int iVertexCount; + int iTriangleStart; + int iTriangleCount; + bool m_bNeedsTextureMatrixScale; + }; + vector m_vMeshInfo; + bool m_bNeedsNormals; + bool m_bAnyNeedsTextureMatrixScale; +}; + +enum RagePixelFormat +{ + RagePixelFormat_RGBA8, + RagePixelFormat_BGRA8, + RagePixelFormat_RGBA4, + RagePixelFormat_RGB5A1, + RagePixelFormat_RGB5, + RagePixelFormat_RGB8, + RagePixelFormat_PAL, + /* The above formats differ between OpenGL and D3D. These are provided as + * alternatives for OpenGL that match some format in D3D. Don't use them + * directly; they'll be matched automatically by FindPixelFormat. */ + RagePixelFormat_BGR8, + RagePixelFormat_A1BGR5, + RagePixelFormat_X1RGB5, + NUM_RagePixelFormat, + RagePixelFormat_Invalid +}; +const RString& RagePixelFormatToString( RagePixelFormat i ); + +/** @brief The parameters used for the present Video Mode. */ +class VideoModeParams +{ +public: + // Initialize with a constructor so to guarantee all paramters + // are filled (in case new params are added). + VideoModeParams( + bool windowed_, + int width_, + int height_, + int bpp_, + int rate_, + bool vsync_, + bool interlaced_, + bool bSmoothLines_, + bool bTrilinearFiltering_, + bool bAnisotropicFiltering_, + RString sWindowTitle_, + RString sIconFile_, + bool PAL_, + float fDisplayAspectRatio_ + ): + windowed(windowed_), + width(width_), + height(height_), + bpp(bpp_), + rate(rate_), + vsync(vsync_), + interlaced(interlaced_), + bSmoothLines(bSmoothLines_), + bTrilinearFiltering(bTrilinearFiltering_), + bAnisotropicFiltering(bAnisotropicFiltering_), + sWindowTitle(sWindowTitle_), + sIconFile(sIconFile_), + PAL(PAL_), + fDisplayAspectRatio(fDisplayAspectRatio_) {} + + VideoModeParams(): windowed(false), width(0), height(0), + bpp(0), rate(0), vsync(false), interlaced(false), + bSmoothLines(false), bTrilinearFiltering(false), + bAnisotropicFiltering(false), sWindowTitle(RString()), + sIconFile(RString()), PAL(false), fDisplayAspectRatio(0.0f) {} + + bool windowed; + int width; + int height; + int bpp; + int rate; + bool vsync; + bool interlaced; + bool bSmoothLines; + bool bTrilinearFiltering; + bool bAnisotropicFiltering; + RString sWindowTitle; + RString sIconFile; + bool PAL; + float fDisplayAspectRatio; +}; + +struct RenderTargetParam +{ + RenderTargetParam(): + iWidth(0), + iHeight(0), + bWithDepthBuffer(false), + bWithAlpha(false), + bFloat(false) + { + } + + // The dimensions of the actual render target, analogous to a window size: + int iWidth, iHeight; + + bool bWithDepthBuffer; + bool bWithAlpha; + bool bFloat; +}; + +struct RageTextureLock +{ + virtual ~RageTextureLock() { } + + /* Given a surface with a format and no pixel data, lock the texture into the + * surface. The data is write-only. */ + virtual void Lock( unsigned iTexHandle, RageSurface *pSurface ) = 0; + + /* Unlock and update the texture. If bChanged is false, the texture update + * may be omitted. */ + virtual void Unlock( RageSurface *pSurface, bool bChanged = true ) = 0; +}; + +class RageDisplay +{ + friend class RageTexture; + +public: + + struct RagePixelFormatDesc { + int bpp; + unsigned int masks[4]; + }; + + virtual const RagePixelFormatDesc *GetPixelFormatDesc( RagePixelFormat pf ) const = 0; + + RageDisplay(); + virtual ~RageDisplay(); + + virtual RString Init( const VideoModeParams &p, bool bAllowUnacceleratedRenderer ) = 0; + + virtual RString GetApiDescription() const = 0; + virtual void GetDisplayResolutions( DisplayResolutions &out ) const = 0; + + // Don't override this. Override TryVideoMode() instead. + // This will set the video mode to be as close as possible to params. + // Return true if device was re-created and we need to reload textures. + RString SetVideoMode( VideoModeParams p, bool &bNeedReloadTextures ); + + // Call this when the resolution has been changed externally: + virtual void ResolutionChanged(); + + virtual bool BeginFrame(); + virtual void EndFrame(); + virtual VideoModeParams GetActualVideoModeParams() const = 0; + bool IsWindowed() const { return this->GetActualVideoModeParams().windowed; } + + virtual void SetBlendMode( BlendMode mode ) = 0; + + virtual bool SupportsTextureFormat( RagePixelFormat pixfmt, bool realtime=false ) = 0; + virtual bool SupportsThreadedRendering() { return false; } + virtual bool SupportsPerVertexMatrixScale() = 0; + + // If threaded rendering is supported, these will be called from the + // rendering thread before and after rendering. + virtual void BeginConcurrentRenderingMainThread() { } + virtual void EndConcurrentRenderingMainThread() { } + virtual void BeginConcurrentRendering(); + virtual void EndConcurrentRendering() { } + + /* return 0 if failed or internal texture resource handle + * (unsigned in OpenGL, texture pointer in D3D) */ + virtual unsigned CreateTexture( + RagePixelFormat pixfmt, // format of img and of texture in video mem + RageSurface* img, // must be in pixfmt + bool bGenerateMipMaps + ) = 0; + virtual void UpdateTexture( + unsigned iTexHandle, + RageSurface* img, + int xoffset, int yoffset, int width, int height + ) = 0; + virtual void DeleteTexture( unsigned iTexHandle ) = 0; + /* Return an object to lock pixels for streaming. If not supported, returns NULL. + * Delete the object normally. */ + virtual RageTextureLock *CreateTextureLock() { return nullptr; } + virtual void ClearAllTextures() = 0; + virtual int GetNumTextureUnits() = 0; + virtual void SetTexture( TextureUnit, unsigned /* iTexture */ ) = 0; + virtual void SetTextureMode( TextureUnit, TextureMode ) = 0; + virtual void SetTextureWrapping( TextureUnit, bool ) = 0; + virtual int GetMaxTextureSize() const = 0; + virtual void SetTextureFiltering( TextureUnit, bool ) = 0; + virtual void SetEffectMode( EffectMode ) { } + virtual bool IsEffectModeSupported( EffectMode effect ) { return effect == EffectMode_Normal; } + + bool SupportsRenderToTexture() const { return false; } + + /* Create a render target, returning a texture handle. In addition to normal + * texture functions, this can be passed to SetRenderTarget. Delete with + * DeleteTexture. (UpdateTexture is not permitted.) Returns 0 if render-to- + * texture is unsupported. + */ + virtual unsigned CreateRenderTarget( const RenderTargetParam &, int & /* iTextureWidthOut */, int & /* iTextureHeightOut */ ) { return 0; } + + /* Set the render target, or 0 to resume rendering to the framebuffer. An active render + * target may not be used as a texture. If bPreserveTexture is true, the contents + * of the texture will be preserved from the previous call; otherwise, cleared. If + * bPreserveTexture is true the first time a render target is used, behave as if + * bPreserveTexture was false. + */ + virtual void SetRenderTarget( unsigned /* iHandle */, bool /* bPreserveTexture */ = true ) { } + + virtual bool IsZTestEnabled() const = 0; + virtual bool IsZWriteEnabled() const = 0; + virtual void SetZWrite( bool ) = 0; + virtual void SetZTestMode( ZTestMode ) = 0; + virtual void SetZBias( float ) = 0; + virtual void ClearZBuffer() = 0; + + virtual void SetCullMode( CullMode mode ) = 0; + + virtual void SetAlphaTest( bool b ) = 0; + + virtual void SetMaterial( + const RageColor &emissive, + const RageColor &ambient, + const RageColor &diffuse, + const RageColor &specular, + float shininess + ) = 0; + + virtual void SetLighting( bool b ) = 0; + virtual void SetLightOff( int index ) = 0; + virtual void SetLightDirectional( + int index, + const RageColor &ambient, + const RageColor &diffuse, + const RageColor &specular, + const RageVector3 &dir ) = 0; + + virtual void SetSphereEnvironmentMapping( TextureUnit tu, bool b ) = 0; + virtual void SetCelShaded( int stage ) = 0; + + virtual RageCompiledGeometry* CreateCompiledGeometry() = 0; + virtual void DeleteCompiledGeometry( RageCompiledGeometry* p ) = 0; + + void DrawQuads( const RageSpriteVertex v[], int iNumVerts ); + void DrawQuadStrip( const RageSpriteVertex v[], int iNumVerts ); + void DrawFan( const RageSpriteVertex v[], int iNumVerts ); + void DrawStrip( const RageSpriteVertex v[], int iNumVerts ); + void DrawTriangles( const RageSpriteVertex v[], int iNumVerts ); + void DrawCompiledGeometry( const RageCompiledGeometry *p, int iMeshIndex, const vector &vMeshes ); + void DrawLineStrip( const RageSpriteVertex v[], int iNumVerts, float LineWidth ); + void DrawSymmetricQuadStrip( const RageSpriteVertex v[], int iNumVerts ); + void DrawCircle( const RageSpriteVertex &v, float radius ); + + void DrawQuad( const RageSpriteVertex v[] ) { DrawQuads(v,4); } /* alias. upper-left, upper-right, lower-left, lower-right */ + + // hacks for cell-shaded models + virtual void SetPolygonMode( PolygonMode ) {} + virtual void SetLineWidth( float ) {} + + enum GraphicsFileFormat + { + SAVE_LOSSLESS, // bmp + SAVE_LOSSLESS_SENSIBLE, // png + SAVE_LOSSY_LOW_QUAL, // jpg + SAVE_LOSSY_HIGH_QUAL // jpg + }; + bool SaveScreenshot( RString sPath, GraphicsFileFormat format ); + + virtual RString GetTextureDiagnostics( unsigned /* id */ ) const { return RString(); } + virtual RageSurface* CreateScreenshot() = 0; // allocates a surface. Caller must delete it. + virtual RageSurface *GetTexture( unsigned /* iTexture */ ) { return nullptr; } // allocates a surface. Caller must delete it. + +protected: + virtual void DrawQuadsInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; + virtual void DrawQuadStripInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; + virtual void DrawFanInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; + virtual void DrawStripInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; + virtual void DrawTrianglesInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; + virtual void DrawCompiledGeometryInternal( const RageCompiledGeometry *p, int iMeshIndex ) = 0; + virtual void DrawLineStripInternal( const RageSpriteVertex v[], int iNumVerts, float LineWidth ); + virtual void DrawSymmetricQuadStripInternal( const RageSpriteVertex v[], int iNumVerts ) = 0; + virtual void DrawCircleInternal( const RageSpriteVertex &v, float radius ); + + // return RString() if mode change was successful, an error message otherwise. + // bNewDeviceOut is set true if a new device was created and textures + // need to be reloaded. + virtual RString TryVideoMode( const VideoModeParams &p, bool &bNewDeviceOut ) = 0; + + void DrawPolyLine( const RageSpriteVertex &p1, const RageSpriteVertex &p2, float LineWidth ); + + // Stuff in RageDisplay.cpp + void SetDefaultRenderStates(); + +public: + // Statistics + int GetFPS() const; + int GetVPF() const; + int GetCumFPS() const; // average FPS since last reset + virtual void ResetStats(); + virtual void ProcessStatsOnFlip(); + virtual RString GetStats() const; + void StatsAddVerts( int iNumVertsRendered ); + + // World matrix stack functions. + void PushMatrix(); + void PopMatrix(); + void Translate( float x, float y, float z ); + void TranslateWorld( float x, float y, float z ); + void Scale( float x, float y, float z ); + void RotateX( float deg ); + void RotateY( float deg ); + void RotateZ( float deg ); + void SkewX( float fAmount ); + void SkewY( float fAmount ); + void MultMatrix( const RageMatrix &f ) { this->PostMultMatrix(f); } /* alias */ + void PostMultMatrix( const RageMatrix &f ); + void PreMultMatrix( const RageMatrix &f ); + void LoadIdentity(); + + // Texture matrix functions + void TexturePushMatrix(); + void TexturePopMatrix(); + void TextureTranslate( float x, float y ); + void TextureTranslate( const RageVector2 &v ) { this->TextureTranslate( v.x, v.y ); } + + // Projection and View matrix stack functions. + void CameraPushMatrix(); + void CameraPopMatrix(); + void LoadMenuPerspective( float fFOVDegrees, float fWidth, float fHeight, float fVanishPointX, float fVanishPointY ); + void LoadLookAt( float fov, const RageVector3 &Eye, const RageVector3 &At, const RageVector3 &Up ); + + // Centering matrix + void CenteringPushMatrix(); + void CenteringPopMatrix(); + void ChangeCentering( int trans_x, int trans_y, int add_width, int add_height ); + + RageSurface *CreateSurfaceFromPixfmt( RagePixelFormat pixfmt, void *pixels, int width, int height, int pitch ); + RagePixelFormat FindPixelFormat( int bpp, unsigned Rmask, unsigned Gmask, unsigned Bmask, unsigned Amask, bool realtime=false ); + + // Lua + void PushSelf( lua_State *L ); + +protected: + RageMatrix GetPerspectiveMatrix( float fovy, float aspect, float zNear, float zFar ); + + // Different for D3D and OpenGL. Not sure why they're not compatible. -Chris + virtual RageMatrix GetOrthoMatrix( float l, float r, float b, float t, float zn, float zf ); + virtual RageMatrix GetFrustumMatrix( float l, float r, float b, float t, float zn, float zf ); + + // Matrix that adjusts position and scale of image on the screen + RageMatrix GetCenteringMatrix( float fTranslateX, float fTranslateY, float fAddWidth, float fAddHeight ) const; + void UpdateCentering(); + + // Called by the RageDisplay derivitives + const RageMatrix* GetCentering() const; + const RageMatrix* GetProjectionTop() const; + const RageMatrix* GetViewTop() const; + const RageMatrix* GetWorldTop() const; + const RageMatrix* GetTextureTop() const; + + // To limit the framerate, call FrameLimitBeforeVsync before waiting + // for vsync and FrameLimitAfterVsync after. + void FrameLimitBeforeVsync( int iFPS ); + void FrameLimitAfterVsync(); +}; + + +extern RageDisplay* DISPLAY; // global and accessable from anywhere in our program + +#endif +/* + * Copyright (c) 2001-2004 Chris Danford, Glenn Maynard + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RageDisplay_OGL.cpp b/src/RageDisplay_OGL.cpp index 2a33601749..5f11fe43c4 100644 --- a/src/RageDisplay_OGL.cpp +++ b/src/RageDisplay_OGL.cpp @@ -835,7 +835,7 @@ RageSurface* RageDisplay_Legacy::CreateScreenshot() RageSurface *RageDisplay_Legacy::GetTexture( unsigned iTexture ) { if (iTexture == 0) - return NULL; // XXX + return nullptr; // XXX FlushGLErrors(); @@ -2277,7 +2277,7 @@ private: RageTextureLock *RageDisplay_Legacy::CreateTextureLock() { if (!GLEW_ARB_pixel_buffer_object) - return NULL; + return nullptr; return new RageTextureLock_OGL; } diff --git a/src/RageFileDriver.cpp b/src/RageFileDriver.cpp index 84d5e8efb3..7bdf64668d 100644 --- a/src/RageFileDriver.cpp +++ b/src/RageFileDriver.cpp @@ -87,7 +87,7 @@ RageFileDriver *MakeFileDriver( const RString &sType, const RString &sRoot ) for( const FileDriverEntry *p = g_pFileDriverList; p; p = p->m_pLink ) if( !p->m_sType.CompareNoCase(sType) ) return p->Create( sRoot ); - return NULL; + return nullptr; } /* diff --git a/src/RageFileDriverDeflate.cpp b/src/RageFileDriverDeflate.cpp index d738949e4a..9931bbc0ff 100644 --- a/src/RageFileDriverDeflate.cpp +++ b/src/RageFileDriverDeflate.cpp @@ -314,12 +314,12 @@ RageFileObjInflate *GunzipFile( RageFileBasic *pFile_, RString &sError, uint32_t char magic[2]; FileReading::ReadBytes( *pFile, magic, 2, sError ); if( sError != "" ) - return NULL; + return nullptr; if( magic[0] != '\x1f' || magic[1] != '\x8b' ) { sError = "Not a gzipped file"; - return NULL; + return nullptr; } } @@ -329,7 +329,7 @@ RageFileObjInflate *GunzipFile( RageFileBasic *pFile_, RString &sError, uint32_t FileReading::read_8( *pFile, sError ); /* xfl */ FileReading::read_8( *pFile, sError ); /* os */ if( sError != "" ) - return NULL; + return nullptr; #define FTEXT 1<<0 #define FHCRC 1<<1 @@ -340,7 +340,7 @@ RageFileObjInflate *GunzipFile( RageFileBasic *pFile_, RString &sError, uint32_t if( iCompressionMethod != 8 ) { sError = ssprintf( "Unsupported compression: %i", iCompressionMethod ); - return NULL; + return nullptr; } /* Warning: flags other than FNAME are untested, since gzip doesn't @@ -348,7 +348,7 @@ RageFileObjInflate *GunzipFile( RageFileBasic *pFile_, RString &sError, uint32_t if( iFlags & UNSUPPORTED_MASK ) { sError = ssprintf( "Unsupported flags: %x", iFlags ); - return NULL; + return nullptr; } if( iFlags & FEXTRA ) @@ -375,12 +375,12 @@ RageFileObjInflate *GunzipFile( RageFileBasic *pFile_, RString &sError, uint32_t uint16_t iExpectedCRC16 = FileReading::read_u16_le( *pFile, sError ); uint16_t iActualCRC16 = int16_t( iActualCRC32 & 0xFFFF ); if( sError != "" ) - return NULL; + return nullptr; if( iActualCRC16 != iExpectedCRC16 ) { sError = "Header CRC error"; - return NULL; + return nullptr; } } @@ -389,7 +389,7 @@ RageFileObjInflate *GunzipFile( RageFileBasic *pFile_, RString &sError, uint32_t pFile->EnableCRC32( false ); if( sError != "" ) - return NULL; + return nullptr; int iDataPos = pFile->Tell(); @@ -406,7 +406,7 @@ RageFileObjInflate *GunzipFile( RageFileBasic *pFile_, RString &sError, uint32_t FileReading::Seek( *pFile, iDataPos, sError ); if( sError != "" ) - return NULL; + return nullptr; RageFileDriverSlice *pSliceFile = new RageFileDriverSlice( pFile.release(), iDataPos, iFooterPos-iDataPos ); pSliceFile->DeleteFileWhenFinished(); diff --git a/src/RageFileDriverDirect.cpp b/src/RageFileDriverDirect.cpp index 02f57fbbd8..c900f05b28 100644 --- a/src/RageFileDriverDirect.cpp +++ b/src/RageFileDriverDirect.cpp @@ -76,7 +76,7 @@ static RageFileObjDirect *MakeFileObjDirect( RString sPath, int iMode, int &iErr if( iFD == -1 ) { iError = errno; - return NULL; + return nullptr; } #if defined(UNIX) @@ -85,7 +85,7 @@ static RageFileObjDirect *MakeFileObjDirect( RString sPath, int iMode, int &iErr { iError = EISDIR; close( iFD ); - return NULL; + return nullptr; } #endif @@ -207,7 +207,7 @@ RageFileBasic *RageFileDriverDirectReadOnly::Open( const RString &sPath, int iMo if( iMode & RageFile::WRITE ) { iError = EROFS; - return NULL; + return nullptr; } return RageFileDriverDirect::Open( sPath, iMode, iError ); diff --git a/src/RageFileDriverMemory.cpp b/src/RageFileDriverMemory.cpp index f400b1482f..477be38a3e 100644 --- a/src/RageFileDriverMemory.cpp +++ b/src/RageFileDriverMemory.cpp @@ -150,7 +150,7 @@ RageFileBasic *RageFileDriverMem::Open( const RString &sPath, int mode, int &err if( pFile == nullptr ) { err = ENOENT; - return NULL; + return nullptr; } return new RageFileObjMem( pFile ); diff --git a/src/RageFileDriverTimeout.cpp b/src/RageFileDriverTimeout.cpp index e47deda529..22689e4a9a 100644 --- a/src/RageFileDriverTimeout.cpp +++ b/src/RageFileDriverTimeout.cpp @@ -299,14 +299,14 @@ RageFileBasic *ThreadedFileWorker::Open( const RString &sPath, int iMode, int &i if( m_pChildDriver == nullptr ) { iErr = ENODEV; - return NULL; + return nullptr; } /* If we're currently in a timed-out state, fail. */ if( IsTimedOut() ) { iErr = EFAULT; /* Win32 has no ETIMEDOUT */ - return NULL; + return nullptr; } m_sRequestPath = sPath; @@ -316,7 +316,7 @@ RageFileBasic *ThreadedFileWorker::Open( const RString &sPath, int iMode, int &i { LOG->Trace( "Open(%s) timed out", sPath.c_str() ); iErr = EFAULT; /* Win32 has no ETIMEDOUT */ - return NULL; + return nullptr; } iErr = m_iResultRequest; @@ -574,7 +574,7 @@ RageFileBasic *ThreadedFileWorker::Copy( RageFileBasic *&pFile, RString &sError if( pFile == nullptr ) { sError = "Operation timed out"; - return NULL; + return nullptr; } m_pRequestFile = pFile; @@ -583,7 +583,7 @@ RageFileBasic *ThreadedFileWorker::Copy( RageFileBasic *&pFile, RString &sError /* If we time out, we can no longer access pFile. */ sError = "Operation timed out"; pFile = NULL; - return NULL; + return nullptr; } RageFileBasic *pRet = m_pResultFile; @@ -747,13 +747,13 @@ public: if( m_pFile == nullptr ) { // SetError( "Operation timed out" ); - return NULL; + return nullptr; } if( pCopy == nullptr ) { // SetError( sError ); - return NULL; + return nullptr; } return new RageFileObjTimeout( m_pWorker, pCopy, m_iFileSize, m_iMode ); @@ -879,7 +879,7 @@ RageFileBasic *RageFileDriverTimeout::Open( const RString &sPath, int iMode, int { RageFileBasic *pChildFile = m_pWorker->Open( sPath, iMode, iErr ); if( pChildFile == nullptr ) - return NULL; + return nullptr; /* RageBasicFile::GetFileSize isn't allowed to fail, but we are; grab the file * size now and store it. */ @@ -892,7 +892,7 @@ RageFileBasic *RageFileDriverTimeout::Open( const RString &sPath, int iMode, int /* When m_pWorker->GetFileSize fails, it takes ownership of pChildFile. */ ASSERT( pChildFile == nullptr ); iErr = EFAULT; - return NULL; + return nullptr; } } diff --git a/src/RageFileDriverZip.cpp b/src/RageFileDriverZip.cpp index 74d5cee731..46a4a79388 100644 --- a/src/RageFileDriverZip.cpp +++ b/src/RageFileDriverZip.cpp @@ -296,14 +296,14 @@ RageFileBasic *RageFileDriverZip::Open( const RString &sPath, int iMode, int &iE if( iMode & RageFile::WRITE ) { iErr = ERROR_WRITING_NOT_SUPPORTED; - return NULL; + return nullptr; } FileInfo *info = (FileInfo *) FDB->GetFilePriv( sPath ); if( info == nullptr ) { iErr = ENOENT; - return NULL; + return nullptr; } m_Mutex.Lock(); @@ -314,7 +314,7 @@ RageFileBasic *RageFileDriverZip::Open( const RString &sPath, int iMode, int &iE if( !ReadLocalFileHeader(*info) ) { m_Mutex.Unlock(); - return NULL; + return nullptr; } } @@ -338,7 +338,7 @@ RageFileBasic *RageFileDriverZip::Open( const RString &sPath, int iMode, int &iE default: /* unknown compression method */ iErr = ENOSYS; - return NULL; + return nullptr; } } diff --git a/src/RageFileManager.cpp b/src/RageFileManager.cpp index 2b51434658..2a0a196811 100644 --- a/src/RageFileManager.cpp +++ b/src/RageFileManager.cpp @@ -154,7 +154,7 @@ public: RageFileBasic *Open( const RString &sPath, int iMode, int &iError ) { iError = (iMode == RageFile::WRITE)? ERROR_WRITING_NOT_SUPPORTED:ENOENT; - return NULL; + return nullptr; } /* Never flush FDB, except in LoadFromDrivers. */ void FlushDirCache( const RString &sPath ) { } @@ -855,7 +855,7 @@ RageFileBasic *RageFileManager::OpenForReading( const RString &sPath, int mode, } UnreferenceAllDrivers( apDriverList ); - return NULL; + return nullptr; } RageFileBasic *RageFileManager::OpenForWriting( const RString &sPath, int mode, int &iError ) @@ -936,7 +936,7 @@ RageFileBasic *RageFileManager::OpenForWriting( const RString &sPath, int mode, UnreferenceAllDrivers( apDriverList ); - return NULL; + return nullptr; } bool RageFileManager::IsAFile( const RString &sPath ) { return GetFileType(sPath) == TYPE_FILE; } diff --git a/src/RageInput.cpp b/src/RageInput.cpp index 837c95ba44..a59e451c72 100644 --- a/src/RageInput.cpp +++ b/src/RageInput.cpp @@ -118,7 +118,7 @@ InputHandler *RageInput::GetHandlerForDevice( const InputDevice id ) { map::iterator it = g_mapDeviceToHandler.find(id); if( it == g_mapDeviceToHandler.end() ) - return NULL; + return nullptr; return it->second; } diff --git a/src/RageLog.cpp b/src/RageLog.cpp index 50d6479399..b6472edc08 100644 --- a/src/RageLog.cpp +++ b/src/RageLog.cpp @@ -353,7 +353,7 @@ void RageLog::AddToRecentLogs( const RString &str ) const char *RageLog::GetRecentLog( int n ) { if( n >= BACKLOG_LINES || n >= backlog_cnt ) - return NULL; + return nullptr; if( backlog_cnt == BACKLOG_LINES ) { diff --git a/src/RageSoundManager.cpp b/src/RageSoundManager.cpp index 280d46c067..90c9872f91 100644 --- a/src/RageSoundManager.cpp +++ b/src/RageSoundManager.cpp @@ -138,7 +138,7 @@ int RageSoundManager::GetDriverSampleRate() const return m_pDriver->GetSampleRate(); } -/* If the given path is loaded, return a copy; otherwise return NULL. +/* If the given path is loaded, return a copy; otherwise return nullptr. * It's the caller's responsibility to delete the result. */ RageSoundReader *RageSoundManager::GetLoadedSound( const RString &sPath_ ) { @@ -149,7 +149,7 @@ RageSoundReader *RageSoundManager::GetLoadedSound( const RString &sPath_ ) map::const_iterator it; it = m_mapPreloadedSounds.find( sPath ); if( it == m_mapPreloadedSounds.end() ) - return NULL; + return nullptr; return it->second->Copy(); } diff --git a/src/RageSoundReader.h b/src/RageSoundReader.h index 635f4fefc0..f7f51f850a 100644 --- a/src/RageSoundReader.h +++ b/src/RageSoundReader.h @@ -1,71 +1,71 @@ -/* RageSoundReader - Data source for a RageSound. */ - -#ifndef RAGE_SOUND_READER_H -#define RAGE_SOUND_READER_H - -class RageSoundReader -{ -public: - virtual int GetLength() const = 0; /* ms */ - virtual int GetLength_Fast() const { return GetLength(); } /* ms */ - virtual int SetPosition( int iFrame ) = 0; - virtual int Read( float *pBuf, int iFrames ) = 0; - virtual ~RageSoundReader() { } - virtual RageSoundReader *Copy() const = 0; - virtual int GetSampleRate() const = 0; - virtual unsigned GetNumChannels() const = 0; - virtual bool SetProperty( const RString & /* sProperty */, float /* fValue */ ) { return false; } - virtual RageSoundReader *GetSource() { return NULL; } - - /* Return values for Read(). */ - enum { - /* An error occurred; GetError() will return a description of the error. */ - ERROR = -1, - END_OF_FILE = -2, - - /* A nonblocking buffer in the filter chain has underrun, and no data is - * currently available. */ - WOULD_BLOCK = -3, - - /* The source position has changed in an expected way, such as looping. - * Seeking manually will not cause this. */ - STREAM_LOOPED = -4, - }; - - /* GetNextSourceFrame() provides the source frame associated with the next frame - * that will be read via Read(). GetStreamToSourceRatio() returns the ratio - * for extrapolating the source frames of the remainder of the block. These - * values are valid so long as no parameters are changed before the next Read(). */ - virtual int GetNextSourceFrame() const = 0; - virtual float GetStreamToSourceRatio() const = 0; - - virtual RString GetError() const = 0; - int RetriedRead( float *pBuffer, int iFrames, int *iSourceFrame = NULL, float *fRate = NULL ); -}; - -#endif - -/* - * Copyright (c) 2002-2003 Glenn Maynard - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* RageSoundReader - Data source for a RageSound. */ + +#ifndef RAGE_SOUND_READER_H +#define RAGE_SOUND_READER_H + +class RageSoundReader +{ +public: + virtual int GetLength() const = 0; /* ms */ + virtual int GetLength_Fast() const { return GetLength(); } /* ms */ + virtual int SetPosition( int iFrame ) = 0; + virtual int Read( float *pBuf, int iFrames ) = 0; + virtual ~RageSoundReader() { } + virtual RageSoundReader *Copy() const = 0; + virtual int GetSampleRate() const = 0; + virtual unsigned GetNumChannels() const = 0; + virtual bool SetProperty( const RString & /* sProperty */, float /* fValue */ ) { return false; } + virtual RageSoundReader *GetSource() { return nullptr; } + + /* Return values for Read(). */ + enum { + /* An error occurred; GetError() will return a description of the error. */ + ERROR = -1, + END_OF_FILE = -2, + + /* A nonblocking buffer in the filter chain has underrun, and no data is + * currently available. */ + WOULD_BLOCK = -3, + + /* The source position has changed in an expected way, such as looping. + * Seeking manually will not cause this. */ + STREAM_LOOPED = -4, + }; + + /* GetNextSourceFrame() provides the source frame associated with the next frame + * that will be read via Read(). GetStreamToSourceRatio() returns the ratio + * for extrapolating the source frames of the remainder of the block. These + * values are valid so long as no parameters are changed before the next Read(). */ + virtual int GetNextSourceFrame() const = 0; + virtual float GetStreamToSourceRatio() const = 0; + + virtual RString GetError() const = 0; + int RetriedRead( float *pBuffer, int iFrames, int *iSourceFrame = NULL, float *fRate = NULL ); +}; + +#endif + +/* + * Copyright (c) 2002-2003 Glenn Maynard + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RageSoundReader_FileReader.cpp b/src/RageSoundReader_FileReader.cpp index 5c43fc080b..caa333e0b1 100644 --- a/src/RageSoundReader_FileReader.cpp +++ b/src/RageSoundReader_FileReader.cpp @@ -1,182 +1,182 @@ -#include "global.h" -#include "RageSoundReader_FileReader.h" -#include "RageUtil.h" -#include "RageLog.h" - -#include -#ifndef NO_WAV_SUPPORT -#include "RageSoundReader_WAV.h" -#endif - -#ifndef NO_MP3_SUPPORT -#include "RageSoundReader_MP3.h" -#endif - -#ifndef NO_VORBIS_SUPPORT -#include "RageSoundReader_Vorbisfile.h" -#endif - -RageSoundReader_FileReader *RageSoundReader_FileReader::TryOpenFile( RageFileBasic *pFile, RString &error, RString format, bool &bKeepTrying ) -{ - RageSoundReader_FileReader *Sample = NULL; - -#ifndef NO_WAV_SUPPORT - if( !format.CompareNoCase("wav") ) - Sample = new RageSoundReader_WAV; -#endif -#ifndef NO_MP3_SUPPORT - if( !format.CompareNoCase("mp3") ) - Sample = new RageSoundReader_MP3; -#endif - -#ifndef NO_VORBIS_SUPPORT - if( !format.CompareNoCase("oga") || !format.CompareNoCase("ogg") ) - Sample = new RageSoundReader_Vorbisfile; -#endif - - if( !Sample ) - return NULL; - - OpenResult ret = Sample->Open( pFile ); - pFile = NULL; // Sample owns it now - if( ret == OPEN_OK ) - return Sample; - - RString err = Sample->GetError(); - delete Sample; - - LOG->Trace( "Format %s failed: %s", format.c_str(), err.c_str() ); - - /* - * The file failed to open, or failed to read. This indicates a problem that will - * affect all readers, so don't waste time trying more readers. (OPEN_IO_ERROR) - * - * Errors fall in two categories: - * OPEN_UNKNOWN_FILE_FORMAT: Data was successfully read from the file, but it's the - * wrong file format. The error message always looks like "unknown file format" or - * "Not Vorbis data"; ignore it so we always give a consistent error message, and - * continue trying other file formats. - * - * OPEN_FATAL_ERROR: Either the file was opened successfully and appears to be the - * correct format, but a fatal format-specific error was encountered that will probably - * not be fixed by using a different reader (for example, an Ogg file that doesn't - * actually contain any audio streams); or the file failed to open or read ("I/O - * error", "permission denied"), in which case all other readers will probably fail, - * too. The returned error is used, and no other formats will be tried. - */ - bKeepTrying = (ret != OPEN_FATAL_ERROR); - switch( ret ) - { - case OPEN_UNKNOWN_FILE_FORMAT: - bKeepTrying = true; - error = "Unknown file format"; - break; - - case OPEN_FATAL_ERROR: - /* The file matched, but failed to load. We know it's this type of data; - * don't bother trying the other file types. */ - bKeepTrying = false; - error = err; - break; - default: break; - } - - return NULL; -} - -#include "RageFileDriverMemory.h" - -RageSoundReader_FileReader *RageSoundReader_FileReader::OpenFile( RString filename, RString &error, bool *pPrebuffer ) -{ - HiddenPtr pFile; - { - RageFile *pFileOpen = new RageFile; - if( !pFileOpen->Open(filename) ) - { - error = pFileOpen->GetError(); - delete pFileOpen; - return NULL; - } - pFile = pFileOpen; - } - - if( pPrebuffer ) - { - if( pFile->GetFileSize() < 1024*50 ) - { - RageFileObjMem *pMem = new RageFileObjMem; - bool bRet = FileCopy( *pFile, *pMem, error, NULL ); - if( !bRet ) - { - delete pMem; - return NULL; - } - - pFile = pMem; - pFile->Seek( 0 ); - *pPrebuffer = true; - } - else - { - *pPrebuffer = false; - } - } - set FileTypes; - FileTypes.insert("oga"); - FileTypes.insert("ogg"); - FileTypes.insert("mp3"); - FileTypes.insert("wav"); - - RString format = GetExtension( filename ); - format.MakeLower(); - - error = ""; - - bool bKeepTrying = true; - - /* If the extension matches a format, try that first. */ - if( FileTypes.find(format) != FileTypes.end() ) - { - RageSoundReader_FileReader *NewSample = TryOpenFile( pFile->Copy(), error, format, bKeepTrying ); - if( NewSample ) - return NewSample; - FileTypes.erase( format ); - } - - for( set::iterator it = FileTypes.begin(); bKeepTrying && it != FileTypes.end(); ++it ) - { - RageSoundReader_FileReader *NewSample = TryOpenFile( pFile->Copy(), error, *it, bKeepTrying ); - if( NewSample ) - { - LOG->UserLog( "Sound file", pFile->GetDisplayPath(), "is really %s.", it->c_str() ); - return NewSample; - } - } - - return NULL; -} - -/* - * Copyright (c) 2003-2004 Glenn Maynard - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#include "global.h" +#include "RageSoundReader_FileReader.h" +#include "RageUtil.h" +#include "RageLog.h" + +#include +#ifndef NO_WAV_SUPPORT +#include "RageSoundReader_WAV.h" +#endif + +#ifndef NO_MP3_SUPPORT +#include "RageSoundReader_MP3.h" +#endif + +#ifndef NO_VORBIS_SUPPORT +#include "RageSoundReader_Vorbisfile.h" +#endif + +RageSoundReader_FileReader *RageSoundReader_FileReader::TryOpenFile( RageFileBasic *pFile, RString &error, RString format, bool &bKeepTrying ) +{ + RageSoundReader_FileReader *Sample = NULL; + +#ifndef NO_WAV_SUPPORT + if( !format.CompareNoCase("wav") ) + Sample = new RageSoundReader_WAV; +#endif +#ifndef NO_MP3_SUPPORT + if( !format.CompareNoCase("mp3") ) + Sample = new RageSoundReader_MP3; +#endif + +#ifndef NO_VORBIS_SUPPORT + if( !format.CompareNoCase("oga") || !format.CompareNoCase("ogg") ) + Sample = new RageSoundReader_Vorbisfile; +#endif + + if( !Sample ) + return nullptr; + + OpenResult ret = Sample->Open( pFile ); + pFile = NULL; // Sample owns it now + if( ret == OPEN_OK ) + return Sample; + + RString err = Sample->GetError(); + delete Sample; + + LOG->Trace( "Format %s failed: %s", format.c_str(), err.c_str() ); + + /* + * The file failed to open, or failed to read. This indicates a problem that will + * affect all readers, so don't waste time trying more readers. (OPEN_IO_ERROR) + * + * Errors fall in two categories: + * OPEN_UNKNOWN_FILE_FORMAT: Data was successfully read from the file, but it's the + * wrong file format. The error message always looks like "unknown file format" or + * "Not Vorbis data"; ignore it so we always give a consistent error message, and + * continue trying other file formats. + * + * OPEN_FATAL_ERROR: Either the file was opened successfully and appears to be the + * correct format, but a fatal format-specific error was encountered that will probably + * not be fixed by using a different reader (for example, an Ogg file that doesn't + * actually contain any audio streams); or the file failed to open or read ("I/O + * error", "permission denied"), in which case all other readers will probably fail, + * too. The returned error is used, and no other formats will be tried. + */ + bKeepTrying = (ret != OPEN_FATAL_ERROR); + switch( ret ) + { + case OPEN_UNKNOWN_FILE_FORMAT: + bKeepTrying = true; + error = "Unknown file format"; + break; + + case OPEN_FATAL_ERROR: + /* The file matched, but failed to load. We know it's this type of data; + * don't bother trying the other file types. */ + bKeepTrying = false; + error = err; + break; + default: break; + } + + return nullptr; +} + +#include "RageFileDriverMemory.h" + +RageSoundReader_FileReader *RageSoundReader_FileReader::OpenFile( RString filename, RString &error, bool *pPrebuffer ) +{ + HiddenPtr pFile; + { + RageFile *pFileOpen = new RageFile; + if( !pFileOpen->Open(filename) ) + { + error = pFileOpen->GetError(); + delete pFileOpen; + return nullptr; + } + pFile = pFileOpen; + } + + if( pPrebuffer ) + { + if( pFile->GetFileSize() < 1024*50 ) + { + RageFileObjMem *pMem = new RageFileObjMem; + bool bRet = FileCopy( *pFile, *pMem, error, NULL ); + if( !bRet ) + { + delete pMem; + return nullptr; + } + + pFile = pMem; + pFile->Seek( 0 ); + *pPrebuffer = true; + } + else + { + *pPrebuffer = false; + } + } + set FileTypes; + FileTypes.insert("oga"); + FileTypes.insert("ogg"); + FileTypes.insert("mp3"); + FileTypes.insert("wav"); + + RString format = GetExtension( filename ); + format.MakeLower(); + + error = ""; + + bool bKeepTrying = true; + + /* If the extension matches a format, try that first. */ + if( FileTypes.find(format) != FileTypes.end() ) + { + RageSoundReader_FileReader *NewSample = TryOpenFile( pFile->Copy(), error, format, bKeepTrying ); + if( NewSample ) + return NewSample; + FileTypes.erase( format ); + } + + for( set::iterator it = FileTypes.begin(); bKeepTrying && it != FileTypes.end(); ++it ) + { + RageSoundReader_FileReader *NewSample = TryOpenFile( pFile->Copy(), error, *it, bKeepTrying ); + if( NewSample ) + { + LOG->UserLog( "Sound file", pFile->GetDisplayPath(), "is really %s.", it->c_str() ); + return NewSample; + } + } + + return nullptr; +} + +/* + * Copyright (c) 2003-2004 Glenn Maynard + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RageSoundReader_ThreadedBuffer.h b/src/RageSoundReader_ThreadedBuffer.h index f440c35ac7..4b22cc4e67 100644 --- a/src/RageSoundReader_ThreadedBuffer.h +++ b/src/RageSoundReader_ThreadedBuffer.h @@ -1,102 +1,102 @@ -/* RageSoundReader_ThreadedBuffer - Buffer sounds into memory. */ - -#ifndef RAGE_SOUND_READER_THREADED_BUFFER -#define RAGE_SOUND_READER_THREADED_BUFFER - -#include "RageSoundReader_Filter.h" -#include "RageUtil_CircularBuffer.h" -#include "RageThreads.h" -#include - -class RageThread; -class RageSoundReader_ThreadedBuffer: public RageSoundReader_Filter -{ -public: - RageSoundReader_ThreadedBuffer( RageSoundReader *pSource ); - RageSoundReader_ThreadedBuffer( const RageSoundReader_ThreadedBuffer &cpy ); - ~RageSoundReader_ThreadedBuffer(); - RageSoundReader_ThreadedBuffer *Copy() const { return new RageSoundReader_ThreadedBuffer(*this); } - - virtual int SetPosition( int iFrame ); - virtual int Read( float *pBuffer, int iLength ); - virtual int GetNextSourceFrame() const; - - virtual int GetLength() const; - virtual int GetLength_Fast() const; - virtual int GetSampleRate() const { return m_iSampleRate; } - virtual unsigned GetNumChannels() const { return m_iChannels; } - virtual bool SetProperty( const RString &sProperty, float fValue ); - virtual float GetStreamToSourceRatio() const; - virtual RageSoundReader *GetSource() { return NULL; } - - /* Enable and disable threaded buffering. Disable buffering before accessing - * the underlying sound. DisableBuffering returns true if buffering was enabled. */ - void EnableBuffering(); - void EnableBuffering() const { const_cast(this)->EnableBuffering(); } - bool DisableBuffering(); - bool DisableBuffering() const { return const_cast(this)->DisableBuffering(); } - -private: - int FillFrames( int iBytes ); - int FillBlock(); - int GetFilledFrames() const; - int GetEmptyFrames() const; - void WaitUntilFrames( int iWaitUntilFrames ); - - int m_iSampleRate; - int m_iChannels; - - CircBuf m_DataBuffer; - - struct Mapping - { - int iFramesBuffered; - int iPositionOfFirstFrame; - float fRate; - Mapping(): iFramesBuffered(0), iPositionOfFirstFrame(0), - fRate(1.0f) {} - }; - list m_StreamPosition; - - bool m_bEOF; - - bool m_bEnabled; - - /* If this is true, the buffering thread owns m_pSource, even - * if m_Event is unlocked. */ - bool m_bFilling; - - mutable RageEvent m_Event; - - RageThread m_Thread; - bool m_bShutdownThread; - static int StartBufferingThread( void *p ) { ((RageSoundReader_ThreadedBuffer *) p)->BufferingThread(); return 0; } - void BufferingThread(); -}; - -#endif - -/* - * Copyright (c) 2006 Glenn Maynard - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/* RageSoundReader_ThreadedBuffer - Buffer sounds into memory. */ + +#ifndef RAGE_SOUND_READER_THREADED_BUFFER +#define RAGE_SOUND_READER_THREADED_BUFFER + +#include "RageSoundReader_Filter.h" +#include "RageUtil_CircularBuffer.h" +#include "RageThreads.h" +#include + +class RageThread; +class RageSoundReader_ThreadedBuffer: public RageSoundReader_Filter +{ +public: + RageSoundReader_ThreadedBuffer( RageSoundReader *pSource ); + RageSoundReader_ThreadedBuffer( const RageSoundReader_ThreadedBuffer &cpy ); + ~RageSoundReader_ThreadedBuffer(); + RageSoundReader_ThreadedBuffer *Copy() const { return new RageSoundReader_ThreadedBuffer(*this); } + + virtual int SetPosition( int iFrame ); + virtual int Read( float *pBuffer, int iLength ); + virtual int GetNextSourceFrame() const; + + virtual int GetLength() const; + virtual int GetLength_Fast() const; + virtual int GetSampleRate() const { return m_iSampleRate; } + virtual unsigned GetNumChannels() const { return m_iChannels; } + virtual bool SetProperty( const RString &sProperty, float fValue ); + virtual float GetStreamToSourceRatio() const; + virtual RageSoundReader *GetSource() { return nullptr; } + + /* Enable and disable threaded buffering. Disable buffering before accessing + * the underlying sound. DisableBuffering returns true if buffering was enabled. */ + void EnableBuffering(); + void EnableBuffering() const { const_cast(this)->EnableBuffering(); } + bool DisableBuffering(); + bool DisableBuffering() const { return const_cast(this)->DisableBuffering(); } + +private: + int FillFrames( int iBytes ); + int FillBlock(); + int GetFilledFrames() const; + int GetEmptyFrames() const; + void WaitUntilFrames( int iWaitUntilFrames ); + + int m_iSampleRate; + int m_iChannels; + + CircBuf m_DataBuffer; + + struct Mapping + { + int iFramesBuffered; + int iPositionOfFirstFrame; + float fRate; + Mapping(): iFramesBuffered(0), iPositionOfFirstFrame(0), + fRate(1.0f) {} + }; + list m_StreamPosition; + + bool m_bEOF; + + bool m_bEnabled; + + /* If this is true, the buffering thread owns m_pSource, even + * if m_Event is unlocked. */ + bool m_bFilling; + + mutable RageEvent m_Event; + + RageThread m_Thread; + bool m_bShutdownThread; + static int StartBufferingThread( void *p ) { ((RageSoundReader_ThreadedBuffer *) p)->BufferingThread(); return 0; } + void BufferingThread(); +}; + +#endif + +/* + * Copyright (c) 2006 Glenn Maynard + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RageSurfaceUtils.cpp b/src/RageSurfaceUtils.cpp index 83bb1cbfdb..5296926205 100644 --- a/src/RageSurfaceUtils.cpp +++ b/src/RageSurfaceUtils.cpp @@ -772,20 +772,20 @@ RageSurface *RageSurfaceUtils::LoadSurface( RString file ) { RageFile f; if( !f.Open( file ) ) - return NULL; + return nullptr; SurfaceHeader h; if( f.Read( &h, sizeof(h) ) != sizeof(h) ) - return NULL; + return nullptr; RageSurfacePalette palette; if( h.bpp == 8 ) { if( f.Read( &palette.ncolors, sizeof(palette.ncolors) ) != sizeof(palette.ncolors) ) - return NULL; + return nullptr; ASSERT_M( palette.ncolors <= 256, ssprintf("%i", palette.ncolors) ); if( f.Read( palette.colors, palette.ncolors * sizeof(RageSurfaceColor) ) != int(palette.ncolors * sizeof(RageSurfaceColor)) ) - return NULL; + return nullptr; } // Create the surface. @@ -801,13 +801,13 @@ RageSurface *RageSurfaceUtils::LoadSurface( RString file ) LOG->Trace( "Error loading \"%s\": expected pitch %i, got %i (%ibpp, %i width)", file.c_str(), h.pitch, img->pitch, h.bpp, h.width ); delete img; - return NULL; + return nullptr; } if( f.Read( img->pixels, h.height * h.pitch ) != h.height * h.pitch ) { delete img; - return NULL; + return nullptr; } // Set the palette. diff --git a/src/RageSurfaceUtils_Palettize.cpp b/src/RageSurfaceUtils_Palettize.cpp index 411fc13e97..72eb1d150b 100644 --- a/src/RageSurfaceUtils_Palettize.cpp +++ b/src/RageSurfaceUtils_Palettize.cpp @@ -565,7 +565,7 @@ static acolorhist_item *pam_computeacolorhist( const RageSurface *src, int maxac { acolorhash_hash acht; if ( !pam_computeacolorhash( src, maxacolors, acolorsP, acht ) ) - return NULL; + return nullptr; acolorhist_item *achv = pam_acolorhashtoacolorhist( acht, *acolorsP ); return achv; diff --git a/src/RageSurface_Load.cpp b/src/RageSurface_Load.cpp index c740a76cb9..050f2a1c82 100644 --- a/src/RageSurface_Load.cpp +++ b/src/RageSurface_Load.cpp @@ -26,7 +26,7 @@ static RageSurface *TryOpenFile( RString sPath, bool bHeaderOnly, RString &error { error = "Unsupported format"; bKeepTrying = true; - return NULL; + return nullptr; } if( result == RageSurfaceUtils::OPEN_OK ) @@ -70,7 +70,7 @@ static RageSurface *TryOpenFile( RString sPath, bool bHeaderOnly, RString &error default: break; } - return NULL; + return nullptr; } RageSurface *RageSurfaceUtils::LoadFile( const RString &sPath, RString &error, bool bHeaderOnly ) @@ -80,7 +80,7 @@ RageSurface *RageSurfaceUtils::LoadFile( const RString &sPath, RString &error, b if( !TestOpen.Open( sPath ) ) { error = TestOpen.GetError(); - return NULL; + return nullptr; } } @@ -115,7 +115,7 @@ RageSurface *RageSurfaceUtils::LoadFile( const RString &sPath, RString &error, b } } - return NULL; + return nullptr; } /* diff --git a/src/RageSurface_Load_GIF.cpp b/src/RageSurface_Load_GIF.cpp index 499e9d22c3..28e7cf5838 100644 --- a/src/RageSurface_Load_GIF.cpp +++ b/src/RageSurface_Load_GIF.cpp @@ -399,14 +399,14 @@ static RageSurface *ReadImage( RageFile &f, int len, int height, if( !state.Init(f) ) { // RWSetMsg("error reading image"); - return NULL; + return nullptr; } /* If this is an "uninteresting picture" ignore it. */ if( ignore ) { while( state.ReadByte(f) >= 0 ) ; - return NULL; + return nullptr; } RageSurface *image = CreateSurface( len, height, 8, 0, 0, 0, 0 ); diff --git a/src/RageSurface_Load_JPEG.cpp b/src/RageSurface_Load_JPEG.cpp index 28a3d35645..c7f9e4842f 100644 --- a/src/RageSurface_Load_JPEG.cpp +++ b/src/RageSurface_Load_JPEG.cpp @@ -132,7 +132,7 @@ static RageSurface *RageSurface_Load_JPEG( RageFile *f, const char *fn, char err jpeg_destroy_decompress( &cinfo ); delete img; - return NULL; + return nullptr; } /* Now we can initialize the JPEG decompression object. */ @@ -161,7 +161,7 @@ static RageSurface *RageSurface_Load_JPEG( RageFile *f, const char *fn, char err case JCS_CMYK: sprintf( errorbuf, "Color format \"%s\" not supported", cinfo.jpeg_color_space == JCS_YCCK? "YCCK":"CMYK" ); jpeg_destroy_decompress( &cinfo ); - return NULL; + return nullptr; default: cinfo.out_color_space = JCS_RGB; diff --git a/src/RageSurface_Load_PNG.cpp b/src/RageSurface_Load_PNG.cpp index 78de06d5eb..1bdc4195f2 100644 --- a/src/RageSurface_Load_PNG.cpp +++ b/src/RageSurface_Load_PNG.cpp @@ -74,7 +74,7 @@ static RageSurface *RageSurface_Load_PNG( RageFile *f, const char *fn, char erro if( png == nullptr ) { sprintf( errorbuf, "creating png_create_read_struct failed"); - return NULL; + return nullptr; } png_info *info_ptr = png_create_info_struct(png); @@ -82,7 +82,7 @@ static RageSurface *RageSurface_Load_PNG( RageFile *f, const char *fn, char erro { png_destroy_read_struct( &png, NULL, NULL ); sprintf( errorbuf, "creating png_create_info_struct failed"); - return NULL; + return nullptr; } RageSurface *volatile img = NULL; @@ -91,7 +91,7 @@ static RageSurface *RageSurface_Load_PNG( RageFile *f, const char *fn, char erro { png_destroy_read_struct( &png, &info_ptr, NULL ); delete img; - return NULL; + return nullptr; } CHECKPOINT; diff --git a/src/RageSurface_Load_XPM.cpp b/src/RageSurface_Load_XPM.cpp index 417977ef75..ed6e6731a1 100644 --- a/src/RageSurface_Load_XPM.cpp +++ b/src/RageSurface_Load_XPM.cpp @@ -11,7 +11,7 @@ #define CheckLine() \ if( xpm[line] == nullptr ) { \ error = "short file"; \ - return NULL; \ + return nullptr; \ } RageSurface *RageSurface_Load_XPM( char * const *xpm, RString &error ) @@ -24,13 +24,13 @@ RageSurface *RageSurface_Load_XPM( char * const *xpm, RString &error ) if( sscanf( xpm[line++], "%i %i %i %i", &width, &height, &num_colors, &color_length ) != 4 ) { error = "parse error reading specs"; - return NULL; + return nullptr; } if( width > 2048 || height > 2048 || num_colors > 1024*16 || color_length > 4 ) { error = "spec error"; - return NULL; + return nullptr; } vector colors; @@ -85,7 +85,7 @@ RageSurface *RageSurface_Load_XPM( char * const *xpm, RString &error ) { error = ssprintf( "row %i is not expected length (%i != %i)", y, int(row.size()), width*color_length ); delete img; - return NULL; + return nullptr; } int8_t *p = (int8_t *) img->pixels; @@ -100,7 +100,7 @@ RageSurface *RageSurface_Load_XPM( char * const *xpm, RString &error ) { error = ssprintf( "%ix%i is unknown color \"%s\"", x, y, color_name.c_str() ); delete img; - return NULL; + return nullptr; } if( colors.size() <= 256 ) diff --git a/src/RageThreads.cpp b/src/RageThreads.cpp index f0653e502c..67007c5b6c 100644 --- a/src/RageThreads.cpp +++ b/src/RageThreads.cpp @@ -109,7 +109,7 @@ void ThreadSlot::ThreadCheckpoint::Set( const char *szFile, int iLine, const cha const char *ThreadSlot::ThreadCheckpoint::GetFormattedCheckpoint() { if( m_szFile == nullptr ) - return NULL; + return nullptr; /* Make sure it's terminated: */ m_szFormattedBuf[ sizeof(m_szFormattedBuf)-1 ] = 0; @@ -120,7 +120,7 @@ const char *ThreadSlot::ThreadCheckpoint::GetFormattedCheckpoint() const char *ThreadSlot::GetFormattedCheckpoint( int lineno ) { if( lineno >= CHECKPOINT_COUNT || lineno >= m_iNumCheckpoints ) - return NULL; + return nullptr; if( m_iNumCheckpoints == CHECKPOINT_COUNT ) { @@ -194,7 +194,7 @@ static ThreadSlot *GetThreadSlotFromID( uint64_t iID ) if( g_ThreadSlots[entry].m_iID == iID ) return &g_ThreadSlots[entry]; } - return NULL; + return nullptr; } static ThreadSlot *GetCurThreadSlot() @@ -406,11 +406,11 @@ static const char *GetCheckpointLog( int slotno, int lineno ) { ThreadSlot &slot = g_ThreadSlots[slotno]; if( !slot.m_bUsed ) - return NULL; + return nullptr; /* Only show the "Unknown thread" entry if it has at least one checkpoint. */ if( &slot == g_pUnknownThreadSlot && slot.GetFormattedCheckpoint(0) == nullptr ) - return NULL; + return nullptr; if( lineno != 0 ) return slot.GetFormattedCheckpoint( lineno-1 ); diff --git a/src/RageUtil.cpp b/src/RageUtil.cpp index 2ebd787c3c..af287a284d 100644 --- a/src/RageUtil.cpp +++ b/src/RageUtil.cpp @@ -658,7 +658,7 @@ const LanguageInfo *GetLanguageInfo( const RString &sIsoCode ) return &g_langs[i]; } - return NULL; + return nullptr; } RString join( const RString &sDeliminator, const vector &sSource) diff --git a/src/RageUtil.h b/src/RageUtil.h index e3a83e576f..366f3905e6 100644 --- a/src/RageUtil.h +++ b/src/RageUtil.h @@ -1,696 +1,696 @@ -/** @brief RageUtil - Miscellaneous helper macros and functions. */ - -#ifndef RAGE_UTIL_H -#define RAGE_UTIL_H - -#include -#include -class RageFileDriver; - -/** @brief Safely delete pointers. */ -#define SAFE_DELETE(p) do { delete (p); (p)=NULL; } while( false ) -/** @brief Safely delete array pointers. */ -#define SAFE_DELETE_ARRAY(p) do { delete[] (p); (p)=NULL; } while( false ) - -/** @brief Zero out the memory. */ -#define ZERO(x) memset(&(x), 0, sizeof(x)) -/** @brief Copy from a to b. */ -#define COPY(a,b) do { ASSERT(sizeof(a)==sizeof(b)); memcpy(&(a), &(b), sizeof(a)); } while( false ) -/** @brief Get the length of the array. */ -#define ARRAYLEN(a) (sizeof(a) / sizeof((a)[0])) - -/* Common harmless mismatches. All min(T,T) and max(T,T) cases are handled - * by the generic template we get from . */ -inline float min( float a, int b ) { return a < b? a:b; } -inline float min( int a, float b ) { return a < b? a:b; } -inline float max( float a, int b ) { return a > b? a:b; } -inline float max( int a, float b ) { return a > b? a:b; } -inline unsigned long min( unsigned int a, unsigned long b ) { return a < b? a:b; } -inline unsigned long min( unsigned long a, unsigned int b ) { return a < b? a:b; } -inline unsigned long max( unsigned int a, unsigned long b ) { return a > b? a:b; } -inline unsigned long max( unsigned long a, unsigned int b ) { return a > b? a:b; } - -/** @brief If outside the range from low to high, bring it within range. */ -#define clamp(val,low,high) ( max( (low), min((val),(high)) ) ) - -/** - * @brief Scales x so that l1 corresponds to l2 and h1 corresponds to h2. - * - * This does not modify x, so it MUST assign the result to something! - * Do the multiply before the divide to that integer scales have more precision. - * - * One such example: SCALE(x, 0, 1, L, H); interpolate between L and H. - */ -#define SCALE(x, l1, h1, l2, h2) (((x) - (l1)) * ((h2) - (l2)) / ((h1) - (l1)) + (l2)) - -template -inline U lerp( T x, U l, U h ) -{ - return U(x * (h - l) + l); -} - -inline bool CLAMP( int &x, int l, int h ) -{ - if (x > h) { x = h; return true; } - else if (x < l) { x = l; return true; } - return false; -} -inline bool CLAMP( unsigned &x, unsigned l, unsigned h ) -{ - if (x > h) { x = h; return true; } - else if (x < l) { x = l; return true; } - return false; -} -inline bool CLAMP( float &x, float l, float h ) -{ - if (x > h) { x = h; return true; } - else if (x < l) { x = l; return true; } - return false; -} -template -inline bool ENUM_CLAMP( T &x, T l, T h ) -{ - if (x > h) { x = h; return true; } - else if (x < l) { x = l; return true; } - return false; -} - -inline void wrap( int &x, int n ) -{ - if (x<0) - x += ((-x/n)+1)*n; - x %= n; -} -inline void wrap( unsigned &x, unsigned n ) -{ - x %= n; -} -inline void wrap( float &x, float n ) -{ - if (x<0) - x += truncf(((-x/n)+1))*n; - x = fmodf(x,n); -} - -inline float fracf( float f ) { return f - truncf(f); } - -template -void CircularShift( vector &v, int dist ) -{ - for( int i = abs(dist); i>0; i-- ) - { - if( dist > 0 ) - { - T t = v[0]; - v.erase( v.begin() ); - v.push_back( t ); - } - else - { - T t = v.back(); - v.erase( v.end()-1 ); - v.insert( v.begin(), t ); - } - } -} - -template -static Ret *CreateClass() { return new Type; } - -/* - * Helper function to remove all objects from an STL container for which the - * Predicate pred is true. If you want to remove all objects for which the predicate - * returns false, wrap the predicate with not1(). - */ -template -inline void RemoveIf( Container& c, Predicate p ) -{ - c.erase( remove_if(c.begin(), c.end(), p), c.end() ); -} -template -inline void RemoveIfEqual( Container &c, const Value &v ) -{ - c.erase( remove(c.begin(), c.end(), v), c.end() ); -} - -/* Helper for ConvertValue(). */ -template -struct ConvertValueHelper -{ - explicit ConvertValueHelper( FROM *pVal ): m_pFromValue(pVal) - { - m_ToValue = static_cast( *m_pFromValue ); - } - - ~ConvertValueHelper() - { - *m_pFromValue = static_cast( m_ToValue ); - } - - TO &operator *() { return m_ToValue; } - operator TO *() { return &m_ToValue; } - -private: - FROM *m_pFromValue; - TO m_ToValue; -}; - -/* Safely temporarily convert between types. For example, - * - * float f = 10.5; - * *ConvertValue(&f) = 12; - */ -template -ConvertValueHelper ConvertValue( FROM *pValue ) -{ - return ConvertValueHelper( pValue ); -} - -/* Safely add an integer to an enum. - * - * This is illegal: - * - * ((int&)val) += iAmt; - * - * It breaks aliasing rules; the compiler is allowed to assume that "val" doesn't - * change (unless it's declared volatile), and in some cases, you'll end up getting - * old values for "val" following the add. (What's probably really happening is - * that the memory location is being added to, but the value is stored in a register, - * and breaking aliasing rules means the compiler doesn't know that the register - * value is invalid.) - */ -template -static inline void enum_add( T &val, int iAmt ) -{ - val = static_cast( val + iAmt ); -} - -template -static inline T enum_add2( T val, int iAmt ) -{ - return static_cast( val + iAmt ); -} - -template -static inline T enum_cycle( T val, int iMax, int iAmt = 1 ) -{ - int iVal = val + iAmt; - iVal %= iMax; - return static_cast( iVal ); -} - - -/* We only have unsigned swaps; byte swapping a signed value doesn't make sense. - * - * Platform-specific, optimized versions are defined in arch_setup, with the names - * ArchSwap32, ArchSwap24, and ArchSwap16; we define them to their real names here, - * to force inclusion of this file when swaps are in use (to prevent different dependencies - * on different systems). - */ -#ifdef HAVE_BYTE_SWAPS -#define Swap32 ArchSwap32 -#define Swap24 ArchSwap24 -#define Swap16 ArchSwap16 -#else -inline uint32_t Swap32( uint32_t n ) -{ - return (n >> 24) | - ((n >> 8) & 0x0000FF00) | - ((n << 8) & 0x00FF0000) | - (n << 24); -} - -inline uint32_t Swap24( uint32_t n ) -{ - return Swap32( n ) >> 8; // xx223344 -> 443322xx -> 00443322 -} - -inline uint16_t Swap16( uint16_t n ) -{ - return (n >> 8) | (n << 8); -} -#endif - -#if defined(ENDIAN_LITTLE) -inline uint32_t Swap32LE( uint32_t n ) { return n; } -inline uint32_t Swap24LE( uint32_t n ) { return n; } -inline uint16_t Swap16LE( uint16_t n ) { return n; } -inline uint32_t Swap32BE( uint32_t n ) { return Swap32( n ); } -inline uint32_t Swap24BE( uint32_t n ) { return Swap24( n ); } -inline uint16_t Swap16BE( uint16_t n ) { return Swap16( n ); } -#else -inline uint32_t Swap32BE( uint32_t n ) { return n; } -inline uint32_t Swap24BE( uint32_t n ) { return n; } -inline uint16_t Swap16BE( uint16_t n ) { return n; } -inline uint32_t Swap32LE( uint32_t n ) { return Swap32( n ); } -inline uint32_t Swap24LE( uint32_t n ) { return Swap24( n ); } -inline uint16_t Swap16LE( uint16_t n ) { return Swap16( n ); } -#endif - -struct MersenneTwister -{ - MersenneTwister( int iSeed = 0 ); // 0 = time() - int operator()(); // returns [0,2^31-1] - int operator()( int n ) // returns [0,n) - { - return (*this)() % n; - } - - void Reset( int iSeed ); - -private: - static int Temper( int iValue ); - void GenerateValues(); - - int m_Values[624]; - int m_iNext; -}; -typedef MersenneTwister RandomGen; - -extern RandomGen g_RandomNumberGenerator; - -/** - * @brief Generate a random float between 0 inclusive and 1 exclusive. - * @return the random float. - */ -inline float RandomFloat() -{ - return g_RandomNumberGenerator() / 2147483648.0f; -} - -/** - * @brief Return a float between the low and high values. - * @param fLow the low value, inclusive. - * @param fHigh the high value, inclusive. - * @return the random float. - */ -inline float RandomFloat( float fLow, float fHigh ) -{ - return SCALE( RandomFloat(), 0.0f, 1.0f, fLow, fHigh ); -} - -// Returns an integer between nLow and nHigh inclusive -inline int RandomInt( int nLow, int nHigh ) -{ - return int( g_RandomNumberGenerator(nHigh - nLow + 1) + nLow ); -} - -// Returns an integer between 0 and n-1 inclusive (replacement for rand() % n). -inline int RandomInt( int n ) -{ - return int( g_RandomNumberGenerator(n) ); -} - - -// Simple function for generating random numbers -inline float randomf( const float low=-1.0f, const float high=1.0f ) -{ - return RandomFloat( low, high ); -} - -/* return f rounded to the nearest multiple of fRoundInterval */ -inline float Quantize( const float f, const float fRoundInterval ) -{ - return int( (f + fRoundInterval/2)/fRoundInterval ) * fRoundInterval; -} - -inline int Quantize( const int i, const int iRoundInterval ) -{ - return int( (i + iRoundInterval/2)/iRoundInterval ) * iRoundInterval; -} - -/* return f truncated to the nearest multiple of fTruncInterval */ -inline float ftruncf( const float f, const float fTruncInterval ) -{ - return int( (f)/fTruncInterval ) * fTruncInterval; -} - -/* Return i rounded up to the nearest multiple of iInterval. */ -inline int QuantizeUp( int i, int iInterval ) -{ - return int( (i+iInterval-1)/iInterval ) * iInterval; -} - -inline float QuantizeUp( float i, float iInterval ) -{ - return ceilf( i/iInterval ) * iInterval; -} - -/* Return i rounded down to the nearest multiple of iInterval. */ -inline int QuantizeDown( int i, int iInterval ) -{ - return int( (i-iInterval+1)/iInterval ) * iInterval; -} - -inline float QuantizeDown( float i, float iInterval ) -{ - return floorf( i/iInterval ) * iInterval; -} - -// Move val toward other_val by to_move. -void fapproach( float& val, float other_val, float to_move ); - -/* Return a positive x mod y. */ -float fmodfp( float x, float y ); - -int power_of_two( int input ); -bool IsAnInt( const RString &s ); -bool IsHexVal( const RString &s ); -RString BinaryToHex( const void *pData_, int iNumBytes ); -RString BinaryToHex( const RString &sString ); -bool HexToBinary( const RString &s, unsigned char *stringOut ); -bool HexToBinary( const RString &s, RString *sOut ); -float HHMMSSToSeconds( const RString &sHMS ); -RString SecondsToHHMMSS( float fSecs ); -RString SecondsToMSSMsMs( float fSecs ); -RString SecondsToMMSSMsMs( float fSecs ); -RString SecondsToMMSSMsMsMs( float fSecs ); -RString SecondsToMSS( float fSecs ); -RString SecondsToMMSS( float fSecs ); -RString PrettyPercent( float fNumerator, float fDenominator ); -inline RString PrettyPercent( int fNumerator, int fDenominator ) { return PrettyPercent( float(fNumerator), float(fDenominator) ); } -RString Commify( int iNum ); -RString Commify( RString sNum, RString sSeperator = "," ); -RString FormatNumberAndSuffix( int i ); - - -struct tm GetLocalTime(); - -RString ssprintf( const char *fmt, ...) PRINTF(1,2); -RString vssprintf( const char *fmt, va_list argList ); -RString ConvertI64FormatString( const RString &sStr ); - -/* - * Splits a Path into 4 parts (Directory, Drive, Filename, Extention). Supports UNC path names. - * If Path is a directory (eg. c:\games\stepmania"), append a slash so the last - * element will end up in Dir, not FName: "c:\games\stepmania\". - * */ -void splitpath( const RString &Path, RString &Dir, RString &Filename, RString &Ext ); - -RString SetExtension( const RString &path, const RString &ext ); -RString GetExtension( const RString &sPath ); -RString GetFileNameWithoutExtension( const RString &sPath ); -void MakeValidFilename( RString &sName ); - -extern const wchar_t INVALID_CHAR; - -int utf8_get_char_len( char p ); -bool utf8_to_wchar( const char *s, size_t iLength, unsigned &start, wchar_t &ch ); -bool utf8_to_wchar_ec( const RString &s, unsigned &start, wchar_t &ch ); -void wchar_to_utf8( wchar_t ch, RString &out ); -wchar_t utf8_get_char( const RString &s ); -bool utf8_is_valid( const RString &s ); -void utf8_remove_bom( RString &s ); -void MakeUpper( char *p, size_t iLen ); -void MakeLower( char *p, size_t iLen ); -void MakeUpper( wchar_t *p, size_t iLen ); -void MakeLower( wchar_t *p, size_t iLen ); -/** - * @brief Have a standard way of converting Strings to integers. - * @param sString the string to convert. - * @return the integer we are after. */ -int StringToInt( const RString &sString ); -/** - * @brief Have a standard way of converting integers to Strings. - * @param iNum the integer to convert. - * @return the string we are after. */ -RString IntToString( const int &iNum ); -float StringToFloat( const RString &sString ); -RString FloatToString( const float &num ); -bool StringToFloat( const RString &sString, float &fOut ); - -RString WStringToRString( const wstring &sString ); -RString WcharToUTF8( wchar_t c ); -wstring RStringToWstring( const RString &sString ); - -struct LanguageInfo -{ - const char *szIsoCode; - const char *szEnglishName; -}; -void GetLanguageInfos( vector &vAddTo ); -const LanguageInfo *GetLanguageInfo( const RString &sIsoCode ); -RString GetLanguageNameFromISO639Code( RString sName ); - -// Splits a RString into an vector according the Delimitor. -void split( const RString &sSource, const RString &sDelimitor, vector& asAddIt, const bool bIgnoreEmpty = true ); -void split( const wstring &sSource, const wstring &sDelimitor, vector &asAddIt, const bool bIgnoreEmpty = true ); - -/* In-place split. */ -void split( const RString &sSource, const RString &sDelimitor, int &iBegin, int &iSize, const bool bIgnoreEmpty = true ); -void split( const wstring &sSource, const wstring &sDelimitor, int &iBegin, int &iSize, const bool bIgnoreEmpty = true ); - -/* In-place split of partial string. */ -void split( const RString &sSource, const RString &sDelimitor, int &iBegin, int &iSize, int iLen, const bool bIgnoreEmpty ); /* no default to avoid ambiguity */ -void split( const wstring &sSource, const wstring &sDelimitor, int &iBegin, int &iSize, int iLen, const bool bIgnoreEmpty ); - -// Joins a vector to create a RString according the Deliminator. -RString join( const RString &sDelimitor, const vector& sSource ); -RString join( const RString &sDelimitor, vector::const_iterator begin, vector::const_iterator end ); - -// These methods escapes a string for saving in a .sm or .crs file -RString SmEscape( const RString &sUnescaped ); -RString SmEscape( const char *cUnescaped, int len ); - -// These methods "escape" a string for .dwi by turning = into -, ] into I, etc. That is "lossy". -RString DwiEscape( const RString &sUnescaped ); -RString DwiEscape( const char *cUnescaped, int len ); - -RString GetCwd(); - -void SetCommandlineArguments( int argc, char **argv ); -void GetCommandLineArguments( int &argc, char **&argv ); -bool GetCommandlineArgument( const RString &option, RString *argument=NULL, int iIndex=0 ); -extern int g_argc; -extern char **g_argv; - -void CRC32( unsigned int &iCRC, const void *pBuffer, size_t iSize ); -unsigned int GetHashForString( const RString &s ); -unsigned int GetHashForFile( const RString &sPath ); -unsigned int GetHashForDirectory( const RString &sDir ); // a hash value that remains the same as long as nothing in the directory has changed -bool DirectoryIsEmpty( const RString &sPath ); - -bool CompareRStringsAsc( const RString &sStr1, const RString &sStr2 ); -bool CompareRStringsDesc( const RString &sStr1, const RString &sStr2 ); -void SortRStringArray( vector &asAddTo, const bool bSortAscending = true ); - -/* Find the mean and standard deviation of all numbers in [start,end). */ -float calc_mean( const float *pStart, const float *pEnd ); -/* When bSample is true, it calculates the square root of an unbiased estimator for the population - * variance. Note that this is not an unbiased estimator for the population standard deviation but - * it is close and an unbiased estimator is complicated (apparently). - * When the entire population is known, bSample should be false to calculate the exact standard - * deviation. */ -float calc_stddev( const float *pStart, const float *pEnd, bool bSample = false ); - -/* - * Find the slope, intercept, and error of a linear least squares regression - * of the points given. Error is returned as the sqrt of the average squared - * Y distance from the chosen line. - * Returns true on success, false on failure. - */ -bool CalcLeastSquares( const vector< pair > &vCoordinates, - float &fSlope, float &fIntercept, float &fError ); - -/* - * This method throws away any points that are more than fCutoff away from - * the line defined by fSlope and fIntercept. - */ -void FilterHighErrorPoints( vector< pair > &vCoordinates, - float fSlope, float fIntercept, float fCutoff ); - -template -int FindIndex( T1 begin, T1 end, const T2 *p ) -{ - T1 iter = find( begin, end, p ); - if( iter == end ) - return -1; - return iter - begin; -} - -/* Useful for objects with no operator-, eg. map::iterator (more convenient than advance). */ -template -inline T Increment( T a ) { ++a; return a; } -template -inline T Decrement( T a ) { --a; return a; } - -void TrimLeft( RString &sStr, const char *szTrim = "\r\n\t " ); -void TrimRight( RString &sStr, const char *szTrim = "\r\n\t " ); -void Trim( RString &sStr, const char *szTrim = "\r\n\t " ); -void StripCrnl( RString &sStr ); -bool BeginsWith( const RString &sTestThis, const RString &sBeginning ); -bool EndsWith( const RString &sTestThis, const RString &sEnding ); -RString URLEncode( const RString &sStr ); - -void StripCvsAndSvn( vector &vs ); // Removes various versioning system metafolders. -void StripMacResourceForks( vector &vs ); // Removes files starting with "._" - -RString DerefRedir( const RString &sPath ); -bool GetFileContents( const RString &sPath, RString &sOut, bool bOneLine = false ); -bool GetFileContents( const RString &sFile, vector &asOut ); - -class Regex -{ -public: - Regex( const RString &sPat = "" ); - Regex( const Regex &rhs ); - Regex &operator=( const Regex &rhs ); - ~Regex(); - bool IsSet() const { return !m_sPattern.empty(); } - void Set( const RString &str ); - bool Compare( const RString &sStr ); - bool Compare( const RString &sStr, vector &asMatches ); - bool Replace( const RString &sReplacement, const RString &sSubject, RString &sOut ); - -private: - void Compile(); - void Release(); - - void *m_pReg; - unsigned m_iBackrefs; - RString m_sPattern; -}; - - -void ReplaceEntityText( RString &sText, const map &m ); -void ReplaceEntityText( RString &sText, const map &m ); -void Replace_Unicode_Markers( RString &Text ); -RString WcharDisplayText( wchar_t c ); - -RString Basename( const RString &dir ); -RString Dirname( const RString &dir ); -RString Capitalize( const RString &s ); - -#ifndef WIN32 -#include /* correct place with correct definitions */ -#endif - -extern unsigned char g_UpperCase[256]; -extern unsigned char g_LowerCase[256]; - -/* ASCII-only case insensitivity. */ -struct char_traits_char_nocase: public char_traits -{ - static inline bool eq( char c1, char c2 ) - { return g_UpperCase[(unsigned char)c1] == g_UpperCase[(unsigned char)c2]; } - - static inline bool ne( char c1, char c2 ) - { return g_UpperCase[(unsigned char)c1] != g_UpperCase[(unsigned char)c2]; } - - static inline bool lt( char c1, char c2 ) - { return g_UpperCase[(unsigned char)c1] < g_UpperCase[(unsigned char)c2]; } - - static int compare( const char* s1, const char* s2, size_t n ) - { - int ret = 0; - while( n-- ) - { - ret = fasttoupper(*s1++) - fasttoupper(*s2++); - if( ret != 0 ) - break; - } - return ret; - } - - static inline char fasttoupper(char a) - { - return g_UpperCase[(unsigned char)a]; - } - - static const char *find( const char* s, int n, char a ) - { - a = fasttoupper(a); - while( n-- > 0 && fasttoupper(*s) != a ) - ++s; - - if(fasttoupper(*s) == a) - return s; - return NULL; - } -}; -typedef basic_string istring; - -/* Compatibility/convenience shortcuts. These are actually defined in RageFileManager.h, but - * declared here since they're used in many places. */ -void GetDirListing( const RString &sPath, vector &AddTo, bool bOnlyDirs=false, bool bReturnPathToo=false ); -void GetDirListingRecursive( const RString &sDir, const RString &sMatch, vector &AddTo ); /* returns path too */ -void GetDirListingRecursive( RageFileDriver *prfd, const RString &sDir, const RString &sMatch, vector &AddTo ); /* returns path too */ -bool DeleteRecursive( const RString &sDir ); /* delete the dir and all files/subdirs inside it */ -bool DeleteRecursive( RageFileDriver *prfd, const RString &sDir ); /* delete the dir and all files/subdirs inside it */ -bool DoesFileExist( const RString &sPath ); -bool IsAFile( const RString &sPath ); -bool IsADirectory( const RString &sPath ); -int GetFileSizeInBytes( const RString &sFilePath ); - -// call FixSlashesInPlace on any path that came from the user -void FixSlashesInPlace( RString &sPath ); -void CollapsePath( RString &sPath, bool bRemoveLeadingDot=false ); - -/** @brief Utilities for converting the RStrings. */ -namespace StringConversion -{ - template - bool FromString( const RString &sValue, T &out ); - - template - RString ToString( const T &value ); - - template<> inline bool FromString( const RString &sValue, RString &out ) { out = sValue; return true; } - template<> inline RString ToString( const RString &value ) { return value; } -} - -class RageFileBasic; -bool FileCopy( const RString &sSrcFile, const RString &sDstFile ); -bool FileCopy( RageFileBasic &in, RageFileBasic &out, RString &sError, bool *bReadError = NULL ); - -template -void GetAsNotInBs( const vector &as, const vector &bs, vector &difference ) -{ - vector bsUnmatched = bs; - // Cannot use FOREACH_CONST here because vector::const_iterator is an implicit type. - for( typename vector::const_iterator a = as.begin(); a != as.end(); ++a ) - { - typename vector::iterator iter = find( bsUnmatched.begin(), bsUnmatched.end(), *a ); - if( iter != bsUnmatched.end() ) - bsUnmatched.erase( iter ); - else - difference.push_back( *a ); - } -} - -template -void GetConnectsDisconnects( const vector &before, const vector &after, vector &disconnects, vector &connects ) -{ - GetAsNotInBs( before, after, disconnects ); - GetAsNotInBs( after, before, connects ); -} - - -#endif - -/** - * @file - * @author Chris Danford, Glenn Maynard (c) 2001-2005 - * @section LICENSE - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +/** @brief RageUtil - Miscellaneous helper macros and functions. */ + +#ifndef RAGE_UTIL_H +#define RAGE_UTIL_H + +#include +#include +class RageFileDriver; + +/** @brief Safely delete pointers. */ +#define SAFE_DELETE(p) do { delete (p); (p)=NULL; } while( false ) +/** @brief Safely delete array pointers. */ +#define SAFE_DELETE_ARRAY(p) do { delete[] (p); (p)=NULL; } while( false ) + +/** @brief Zero out the memory. */ +#define ZERO(x) memset(&(x), 0, sizeof(x)) +/** @brief Copy from a to b. */ +#define COPY(a,b) do { ASSERT(sizeof(a)==sizeof(b)); memcpy(&(a), &(b), sizeof(a)); } while( false ) +/** @brief Get the length of the array. */ +#define ARRAYLEN(a) (sizeof(a) / sizeof((a)[0])) + +/* Common harmless mismatches. All min(T,T) and max(T,T) cases are handled + * by the generic template we get from . */ +inline float min( float a, int b ) { return a < b? a:b; } +inline float min( int a, float b ) { return a < b? a:b; } +inline float max( float a, int b ) { return a > b? a:b; } +inline float max( int a, float b ) { return a > b? a:b; } +inline unsigned long min( unsigned int a, unsigned long b ) { return a < b? a:b; } +inline unsigned long min( unsigned long a, unsigned int b ) { return a < b? a:b; } +inline unsigned long max( unsigned int a, unsigned long b ) { return a > b? a:b; } +inline unsigned long max( unsigned long a, unsigned int b ) { return a > b? a:b; } + +/** @brief If outside the range from low to high, bring it within range. */ +#define clamp(val,low,high) ( max( (low), min((val),(high)) ) ) + +/** + * @brief Scales x so that l1 corresponds to l2 and h1 corresponds to h2. + * + * This does not modify x, so it MUST assign the result to something! + * Do the multiply before the divide to that integer scales have more precision. + * + * One such example: SCALE(x, 0, 1, L, H); interpolate between L and H. + */ +#define SCALE(x, l1, h1, l2, h2) (((x) - (l1)) * ((h2) - (l2)) / ((h1) - (l1)) + (l2)) + +template +inline U lerp( T x, U l, U h ) +{ + return U(x * (h - l) + l); +} + +inline bool CLAMP( int &x, int l, int h ) +{ + if (x > h) { x = h; return true; } + else if (x < l) { x = l; return true; } + return false; +} +inline bool CLAMP( unsigned &x, unsigned l, unsigned h ) +{ + if (x > h) { x = h; return true; } + else if (x < l) { x = l; return true; } + return false; +} +inline bool CLAMP( float &x, float l, float h ) +{ + if (x > h) { x = h; return true; } + else if (x < l) { x = l; return true; } + return false; +} +template +inline bool ENUM_CLAMP( T &x, T l, T h ) +{ + if (x > h) { x = h; return true; } + else if (x < l) { x = l; return true; } + return false; +} + +inline void wrap( int &x, int n ) +{ + if (x<0) + x += ((-x/n)+1)*n; + x %= n; +} +inline void wrap( unsigned &x, unsigned n ) +{ + x %= n; +} +inline void wrap( float &x, float n ) +{ + if (x<0) + x += truncf(((-x/n)+1))*n; + x = fmodf(x,n); +} + +inline float fracf( float f ) { return f - truncf(f); } + +template +void CircularShift( vector &v, int dist ) +{ + for( int i = abs(dist); i>0; i-- ) + { + if( dist > 0 ) + { + T t = v[0]; + v.erase( v.begin() ); + v.push_back( t ); + } + else + { + T t = v.back(); + v.erase( v.end()-1 ); + v.insert( v.begin(), t ); + } + } +} + +template +static Ret *CreateClass() { return new Type; } + +/* + * Helper function to remove all objects from an STL container for which the + * Predicate pred is true. If you want to remove all objects for which the predicate + * returns false, wrap the predicate with not1(). + */ +template +inline void RemoveIf( Container& c, Predicate p ) +{ + c.erase( remove_if(c.begin(), c.end(), p), c.end() ); +} +template +inline void RemoveIfEqual( Container &c, const Value &v ) +{ + c.erase( remove(c.begin(), c.end(), v), c.end() ); +} + +/* Helper for ConvertValue(). */ +template +struct ConvertValueHelper +{ + explicit ConvertValueHelper( FROM *pVal ): m_pFromValue(pVal) + { + m_ToValue = static_cast( *m_pFromValue ); + } + + ~ConvertValueHelper() + { + *m_pFromValue = static_cast( m_ToValue ); + } + + TO &operator *() { return m_ToValue; } + operator TO *() { return &m_ToValue; } + +private: + FROM *m_pFromValue; + TO m_ToValue; +}; + +/* Safely temporarily convert between types. For example, + * + * float f = 10.5; + * *ConvertValue(&f) = 12; + */ +template +ConvertValueHelper ConvertValue( FROM *pValue ) +{ + return ConvertValueHelper( pValue ); +} + +/* Safely add an integer to an enum. + * + * This is illegal: + * + * ((int&)val) += iAmt; + * + * It breaks aliasing rules; the compiler is allowed to assume that "val" doesn't + * change (unless it's declared volatile), and in some cases, you'll end up getting + * old values for "val" following the add. (What's probably really happening is + * that the memory location is being added to, but the value is stored in a register, + * and breaking aliasing rules means the compiler doesn't know that the register + * value is invalid.) + */ +template +static inline void enum_add( T &val, int iAmt ) +{ + val = static_cast( val + iAmt ); +} + +template +static inline T enum_add2( T val, int iAmt ) +{ + return static_cast( val + iAmt ); +} + +template +static inline T enum_cycle( T val, int iMax, int iAmt = 1 ) +{ + int iVal = val + iAmt; + iVal %= iMax; + return static_cast( iVal ); +} + + +/* We only have unsigned swaps; byte swapping a signed value doesn't make sense. + * + * Platform-specific, optimized versions are defined in arch_setup, with the names + * ArchSwap32, ArchSwap24, and ArchSwap16; we define them to their real names here, + * to force inclusion of this file when swaps are in use (to prevent different dependencies + * on different systems). + */ +#ifdef HAVE_BYTE_SWAPS +#define Swap32 ArchSwap32 +#define Swap24 ArchSwap24 +#define Swap16 ArchSwap16 +#else +inline uint32_t Swap32( uint32_t n ) +{ + return (n >> 24) | + ((n >> 8) & 0x0000FF00) | + ((n << 8) & 0x00FF0000) | + (n << 24); +} + +inline uint32_t Swap24( uint32_t n ) +{ + return Swap32( n ) >> 8; // xx223344 -> 443322xx -> 00443322 +} + +inline uint16_t Swap16( uint16_t n ) +{ + return (n >> 8) | (n << 8); +} +#endif + +#if defined(ENDIAN_LITTLE) +inline uint32_t Swap32LE( uint32_t n ) { return n; } +inline uint32_t Swap24LE( uint32_t n ) { return n; } +inline uint16_t Swap16LE( uint16_t n ) { return n; } +inline uint32_t Swap32BE( uint32_t n ) { return Swap32( n ); } +inline uint32_t Swap24BE( uint32_t n ) { return Swap24( n ); } +inline uint16_t Swap16BE( uint16_t n ) { return Swap16( n ); } +#else +inline uint32_t Swap32BE( uint32_t n ) { return n; } +inline uint32_t Swap24BE( uint32_t n ) { return n; } +inline uint16_t Swap16BE( uint16_t n ) { return n; } +inline uint32_t Swap32LE( uint32_t n ) { return Swap32( n ); } +inline uint32_t Swap24LE( uint32_t n ) { return Swap24( n ); } +inline uint16_t Swap16LE( uint16_t n ) { return Swap16( n ); } +#endif + +struct MersenneTwister +{ + MersenneTwister( int iSeed = 0 ); // 0 = time() + int operator()(); // returns [0,2^31-1] + int operator()( int n ) // returns [0,n) + { + return (*this)() % n; + } + + void Reset( int iSeed ); + +private: + static int Temper( int iValue ); + void GenerateValues(); + + int m_Values[624]; + int m_iNext; +}; +typedef MersenneTwister RandomGen; + +extern RandomGen g_RandomNumberGenerator; + +/** + * @brief Generate a random float between 0 inclusive and 1 exclusive. + * @return the random float. + */ +inline float RandomFloat() +{ + return g_RandomNumberGenerator() / 2147483648.0f; +} + +/** + * @brief Return a float between the low and high values. + * @param fLow the low value, inclusive. + * @param fHigh the high value, inclusive. + * @return the random float. + */ +inline float RandomFloat( float fLow, float fHigh ) +{ + return SCALE( RandomFloat(), 0.0f, 1.0f, fLow, fHigh ); +} + +// Returns an integer between nLow and nHigh inclusive +inline int RandomInt( int nLow, int nHigh ) +{ + return int( g_RandomNumberGenerator(nHigh - nLow + 1) + nLow ); +} + +// Returns an integer between 0 and n-1 inclusive (replacement for rand() % n). +inline int RandomInt( int n ) +{ + return int( g_RandomNumberGenerator(n) ); +} + + +// Simple function for generating random numbers +inline float randomf( const float low=-1.0f, const float high=1.0f ) +{ + return RandomFloat( low, high ); +} + +/* return f rounded to the nearest multiple of fRoundInterval */ +inline float Quantize( const float f, const float fRoundInterval ) +{ + return int( (f + fRoundInterval/2)/fRoundInterval ) * fRoundInterval; +} + +inline int Quantize( const int i, const int iRoundInterval ) +{ + return int( (i + iRoundInterval/2)/iRoundInterval ) * iRoundInterval; +} + +/* return f truncated to the nearest multiple of fTruncInterval */ +inline float ftruncf( const float f, const float fTruncInterval ) +{ + return int( (f)/fTruncInterval ) * fTruncInterval; +} + +/* Return i rounded up to the nearest multiple of iInterval. */ +inline int QuantizeUp( int i, int iInterval ) +{ + return int( (i+iInterval-1)/iInterval ) * iInterval; +} + +inline float QuantizeUp( float i, float iInterval ) +{ + return ceilf( i/iInterval ) * iInterval; +} + +/* Return i rounded down to the nearest multiple of iInterval. */ +inline int QuantizeDown( int i, int iInterval ) +{ + return int( (i-iInterval+1)/iInterval ) * iInterval; +} + +inline float QuantizeDown( float i, float iInterval ) +{ + return floorf( i/iInterval ) * iInterval; +} + +// Move val toward other_val by to_move. +void fapproach( float& val, float other_val, float to_move ); + +/* Return a positive x mod y. */ +float fmodfp( float x, float y ); + +int power_of_two( int input ); +bool IsAnInt( const RString &s ); +bool IsHexVal( const RString &s ); +RString BinaryToHex( const void *pData_, int iNumBytes ); +RString BinaryToHex( const RString &sString ); +bool HexToBinary( const RString &s, unsigned char *stringOut ); +bool HexToBinary( const RString &s, RString *sOut ); +float HHMMSSToSeconds( const RString &sHMS ); +RString SecondsToHHMMSS( float fSecs ); +RString SecondsToMSSMsMs( float fSecs ); +RString SecondsToMMSSMsMs( float fSecs ); +RString SecondsToMMSSMsMsMs( float fSecs ); +RString SecondsToMSS( float fSecs ); +RString SecondsToMMSS( float fSecs ); +RString PrettyPercent( float fNumerator, float fDenominator ); +inline RString PrettyPercent( int fNumerator, int fDenominator ) { return PrettyPercent( float(fNumerator), float(fDenominator) ); } +RString Commify( int iNum ); +RString Commify( RString sNum, RString sSeperator = "," ); +RString FormatNumberAndSuffix( int i ); + + +struct tm GetLocalTime(); + +RString ssprintf( const char *fmt, ...) PRINTF(1,2); +RString vssprintf( const char *fmt, va_list argList ); +RString ConvertI64FormatString( const RString &sStr ); + +/* + * Splits a Path into 4 parts (Directory, Drive, Filename, Extention). Supports UNC path names. + * If Path is a directory (eg. c:\games\stepmania"), append a slash so the last + * element will end up in Dir, not FName: "c:\games\stepmania\". + * */ +void splitpath( const RString &Path, RString &Dir, RString &Filename, RString &Ext ); + +RString SetExtension( const RString &path, const RString &ext ); +RString GetExtension( const RString &sPath ); +RString GetFileNameWithoutExtension( const RString &sPath ); +void MakeValidFilename( RString &sName ); + +extern const wchar_t INVALID_CHAR; + +int utf8_get_char_len( char p ); +bool utf8_to_wchar( const char *s, size_t iLength, unsigned &start, wchar_t &ch ); +bool utf8_to_wchar_ec( const RString &s, unsigned &start, wchar_t &ch ); +void wchar_to_utf8( wchar_t ch, RString &out ); +wchar_t utf8_get_char( const RString &s ); +bool utf8_is_valid( const RString &s ); +void utf8_remove_bom( RString &s ); +void MakeUpper( char *p, size_t iLen ); +void MakeLower( char *p, size_t iLen ); +void MakeUpper( wchar_t *p, size_t iLen ); +void MakeLower( wchar_t *p, size_t iLen ); +/** + * @brief Have a standard way of converting Strings to integers. + * @param sString the string to convert. + * @return the integer we are after. */ +int StringToInt( const RString &sString ); +/** + * @brief Have a standard way of converting integers to Strings. + * @param iNum the integer to convert. + * @return the string we are after. */ +RString IntToString( const int &iNum ); +float StringToFloat( const RString &sString ); +RString FloatToString( const float &num ); +bool StringToFloat( const RString &sString, float &fOut ); + +RString WStringToRString( const wstring &sString ); +RString WcharToUTF8( wchar_t c ); +wstring RStringToWstring( const RString &sString ); + +struct LanguageInfo +{ + const char *szIsoCode; + const char *szEnglishName; +}; +void GetLanguageInfos( vector &vAddTo ); +const LanguageInfo *GetLanguageInfo( const RString &sIsoCode ); +RString GetLanguageNameFromISO639Code( RString sName ); + +// Splits a RString into an vector according the Delimitor. +void split( const RString &sSource, const RString &sDelimitor, vector& asAddIt, const bool bIgnoreEmpty = true ); +void split( const wstring &sSource, const wstring &sDelimitor, vector &asAddIt, const bool bIgnoreEmpty = true ); + +/* In-place split. */ +void split( const RString &sSource, const RString &sDelimitor, int &iBegin, int &iSize, const bool bIgnoreEmpty = true ); +void split( const wstring &sSource, const wstring &sDelimitor, int &iBegin, int &iSize, const bool bIgnoreEmpty = true ); + +/* In-place split of partial string. */ +void split( const RString &sSource, const RString &sDelimitor, int &iBegin, int &iSize, int iLen, const bool bIgnoreEmpty ); /* no default to avoid ambiguity */ +void split( const wstring &sSource, const wstring &sDelimitor, int &iBegin, int &iSize, int iLen, const bool bIgnoreEmpty ); + +// Joins a vector to create a RString according the Deliminator. +RString join( const RString &sDelimitor, const vector& sSource ); +RString join( const RString &sDelimitor, vector::const_iterator begin, vector::const_iterator end ); + +// These methods escapes a string for saving in a .sm or .crs file +RString SmEscape( const RString &sUnescaped ); +RString SmEscape( const char *cUnescaped, int len ); + +// These methods "escape" a string for .dwi by turning = into -, ] into I, etc. That is "lossy". +RString DwiEscape( const RString &sUnescaped ); +RString DwiEscape( const char *cUnescaped, int len ); + +RString GetCwd(); + +void SetCommandlineArguments( int argc, char **argv ); +void GetCommandLineArguments( int &argc, char **&argv ); +bool GetCommandlineArgument( const RString &option, RString *argument=NULL, int iIndex=0 ); +extern int g_argc; +extern char **g_argv; + +void CRC32( unsigned int &iCRC, const void *pBuffer, size_t iSize ); +unsigned int GetHashForString( const RString &s ); +unsigned int GetHashForFile( const RString &sPath ); +unsigned int GetHashForDirectory( const RString &sDir ); // a hash value that remains the same as long as nothing in the directory has changed +bool DirectoryIsEmpty( const RString &sPath ); + +bool CompareRStringsAsc( const RString &sStr1, const RString &sStr2 ); +bool CompareRStringsDesc( const RString &sStr1, const RString &sStr2 ); +void SortRStringArray( vector &asAddTo, const bool bSortAscending = true ); + +/* Find the mean and standard deviation of all numbers in [start,end). */ +float calc_mean( const float *pStart, const float *pEnd ); +/* When bSample is true, it calculates the square root of an unbiased estimator for the population + * variance. Note that this is not an unbiased estimator for the population standard deviation but + * it is close and an unbiased estimator is complicated (apparently). + * When the entire population is known, bSample should be false to calculate the exact standard + * deviation. */ +float calc_stddev( const float *pStart, const float *pEnd, bool bSample = false ); + +/* + * Find the slope, intercept, and error of a linear least squares regression + * of the points given. Error is returned as the sqrt of the average squared + * Y distance from the chosen line. + * Returns true on success, false on failure. + */ +bool CalcLeastSquares( const vector< pair > &vCoordinates, + float &fSlope, float &fIntercept, float &fError ); + +/* + * This method throws away any points that are more than fCutoff away from + * the line defined by fSlope and fIntercept. + */ +void FilterHighErrorPoints( vector< pair > &vCoordinates, + float fSlope, float fIntercept, float fCutoff ); + +template +int FindIndex( T1 begin, T1 end, const T2 *p ) +{ + T1 iter = find( begin, end, p ); + if( iter == end ) + return -1; + return iter - begin; +} + +/* Useful for objects with no operator-, eg. map::iterator (more convenient than advance). */ +template +inline T Increment( T a ) { ++a; return a; } +template +inline T Decrement( T a ) { --a; return a; } + +void TrimLeft( RString &sStr, const char *szTrim = "\r\n\t " ); +void TrimRight( RString &sStr, const char *szTrim = "\r\n\t " ); +void Trim( RString &sStr, const char *szTrim = "\r\n\t " ); +void StripCrnl( RString &sStr ); +bool BeginsWith( const RString &sTestThis, const RString &sBeginning ); +bool EndsWith( const RString &sTestThis, const RString &sEnding ); +RString URLEncode( const RString &sStr ); + +void StripCvsAndSvn( vector &vs ); // Removes various versioning system metafolders. +void StripMacResourceForks( vector &vs ); // Removes files starting with "._" + +RString DerefRedir( const RString &sPath ); +bool GetFileContents( const RString &sPath, RString &sOut, bool bOneLine = false ); +bool GetFileContents( const RString &sFile, vector &asOut ); + +class Regex +{ +public: + Regex( const RString &sPat = "" ); + Regex( const Regex &rhs ); + Regex &operator=( const Regex &rhs ); + ~Regex(); + bool IsSet() const { return !m_sPattern.empty(); } + void Set( const RString &str ); + bool Compare( const RString &sStr ); + bool Compare( const RString &sStr, vector &asMatches ); + bool Replace( const RString &sReplacement, const RString &sSubject, RString &sOut ); + +private: + void Compile(); + void Release(); + + void *m_pReg; + unsigned m_iBackrefs; + RString m_sPattern; +}; + + +void ReplaceEntityText( RString &sText, const map &m ); +void ReplaceEntityText( RString &sText, const map &m ); +void Replace_Unicode_Markers( RString &Text ); +RString WcharDisplayText( wchar_t c ); + +RString Basename( const RString &dir ); +RString Dirname( const RString &dir ); +RString Capitalize( const RString &s ); + +#ifndef WIN32 +#include /* correct place with correct definitions */ +#endif + +extern unsigned char g_UpperCase[256]; +extern unsigned char g_LowerCase[256]; + +/* ASCII-only case insensitivity. */ +struct char_traits_char_nocase: public char_traits +{ + static inline bool eq( char c1, char c2 ) + { return g_UpperCase[(unsigned char)c1] == g_UpperCase[(unsigned char)c2]; } + + static inline bool ne( char c1, char c2 ) + { return g_UpperCase[(unsigned char)c1] != g_UpperCase[(unsigned char)c2]; } + + static inline bool lt( char c1, char c2 ) + { return g_UpperCase[(unsigned char)c1] < g_UpperCase[(unsigned char)c2]; } + + static int compare( const char* s1, const char* s2, size_t n ) + { + int ret = 0; + while( n-- ) + { + ret = fasttoupper(*s1++) - fasttoupper(*s2++); + if( ret != 0 ) + break; + } + return ret; + } + + static inline char fasttoupper(char a) + { + return g_UpperCase[(unsigned char)a]; + } + + static const char *find( const char* s, int n, char a ) + { + a = fasttoupper(a); + while( n-- > 0 && fasttoupper(*s) != a ) + ++s; + + if(fasttoupper(*s) == a) + return s; + return nullptr; + } +}; +typedef basic_string istring; + +/* Compatibility/convenience shortcuts. These are actually defined in RageFileManager.h, but + * declared here since they're used in many places. */ +void GetDirListing( const RString &sPath, vector &AddTo, bool bOnlyDirs=false, bool bReturnPathToo=false ); +void GetDirListingRecursive( const RString &sDir, const RString &sMatch, vector &AddTo ); /* returns path too */ +void GetDirListingRecursive( RageFileDriver *prfd, const RString &sDir, const RString &sMatch, vector &AddTo ); /* returns path too */ +bool DeleteRecursive( const RString &sDir ); /* delete the dir and all files/subdirs inside it */ +bool DeleteRecursive( RageFileDriver *prfd, const RString &sDir ); /* delete the dir and all files/subdirs inside it */ +bool DoesFileExist( const RString &sPath ); +bool IsAFile( const RString &sPath ); +bool IsADirectory( const RString &sPath ); +int GetFileSizeInBytes( const RString &sFilePath ); + +// call FixSlashesInPlace on any path that came from the user +void FixSlashesInPlace( RString &sPath ); +void CollapsePath( RString &sPath, bool bRemoveLeadingDot=false ); + +/** @brief Utilities for converting the RStrings. */ +namespace StringConversion +{ + template + bool FromString( const RString &sValue, T &out ); + + template + RString ToString( const T &value ); + + template<> inline bool FromString( const RString &sValue, RString &out ) { out = sValue; return true; } + template<> inline RString ToString( const RString &value ) { return value; } +} + +class RageFileBasic; +bool FileCopy( const RString &sSrcFile, const RString &sDstFile ); +bool FileCopy( RageFileBasic &in, RageFileBasic &out, RString &sError, bool *bReadError = NULL ); + +template +void GetAsNotInBs( const vector &as, const vector &bs, vector &difference ) +{ + vector bsUnmatched = bs; + // Cannot use FOREACH_CONST here because vector::const_iterator is an implicit type. + for( typename vector::const_iterator a = as.begin(); a != as.end(); ++a ) + { + typename vector::iterator iter = find( bsUnmatched.begin(), bsUnmatched.end(), *a ); + if( iter != bsUnmatched.end() ) + bsUnmatched.erase( iter ); + else + difference.push_back( *a ); + } +} + +template +void GetConnectsDisconnects( const vector &before, const vector &after, vector &disconnects, vector &connects ) +{ + GetAsNotInBs( before, after, disconnects ); + GetAsNotInBs( after, before, connects ); +} + + +#endif + +/** + * @file + * @author Chris Danford, Glenn Maynard (c) 2001-2005 + * @section LICENSE + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/RageUtil_FileDB.cpp b/src/RageUtil_FileDB.cpp index 1a92683f5a..709a110808 100644 --- a/src/RageUtil_FileDB.cpp +++ b/src/RageUtil_FileDB.cpp @@ -291,7 +291,7 @@ FileSet *FilenameDB::GetFileSet( const RString &sDir_, bool bCreate ) if( !bCreate ) { if( i == dirs.end() ) - return NULL; + return nullptr; return i->second; } @@ -548,7 +548,7 @@ const File *FilenameDB::GetFile( const RString &sPath ) set::iterator it; it = fs->files.find( File(Name) ); if( it == fs->files.end() ) - return NULL; + return nullptr; return &*it; } diff --git a/src/ScreenGameplay.cpp b/src/ScreenGameplay.cpp index 7708b613f0..1252b148cf 100644 --- a/src/ScreenGameplay.cpp +++ b/src/ScreenGameplay.cpp @@ -2727,7 +2727,7 @@ PlayerInfo *ScreenGameplay::GetPlayerInfo( PlayerNumber pn ) if( pi->m_pn == pn ) return &*pi; } - return NULL; + return nullptr; } PlayerInfo *ScreenGameplay::GetDummyPlayerInfo( int iDummyIndex ) @@ -2737,7 +2737,7 @@ PlayerInfo *ScreenGameplay::GetDummyPlayerInfo( int iDummyIndex ) if( pi->m_bIsDummy && pi->m_iDummyIndex == iDummyIndex ) return &*pi; } - return NULL; + return nullptr; } void ScreenGameplay::SaveReplay() diff --git a/src/ScreenManager.cpp b/src/ScreenManager.cpp index 0ab4554bb2..d41adfbba6 100644 --- a/src/ScreenManager.cpp +++ b/src/ScreenManager.cpp @@ -332,14 +332,14 @@ void ScreenManager::ReloadOverlayScreens() Screen *ScreenManager::GetTopScreen() { if( g_ScreenStack.empty() ) - return NULL; + return nullptr; return g_ScreenStack[g_ScreenStack.size()-1].m_pScreen; } Screen *ScreenManager::GetScreen( int iPosition ) { if( iPosition >= (int) g_ScreenStack.size() ) - return NULL; + return nullptr; return g_ScreenStack[iPosition].m_pScreen; } diff --git a/src/ScreenOptionsEditCourse.cpp b/src/ScreenOptionsEditCourse.cpp index 601a44d54c..5ae02f9232 100644 --- a/src/ScreenOptionsEditCourse.cpp +++ b/src/ScreenOptionsEditCourse.cpp @@ -429,7 +429,7 @@ Song *ScreenOptionsEditCourse::GetSongForEntry( int iEntryIndex ) int index = row.GetOneSharedSelection(); if( index == 0 ) - return NULL; + return nullptr; return m_vpSongs[ index - 1 ]; } diff --git a/src/ScreenOptionsManageCourses.cpp b/src/ScreenOptionsManageCourses.cpp index 7100d50bb9..9ae0021ea3 100644 --- a/src/ScreenOptionsManageCourses.cpp +++ b/src/ScreenOptionsManageCourses.cpp @@ -262,9 +262,9 @@ Course *ScreenOptionsManageCourses::GetCourseWithFocus() const { int iCurRow = m_iCurrentRow[GAMESTATE->GetMasterPlayerNumber()]; if( iCurRow == 0 ) - return NULL; + return nullptr; else if( m_pRows[iCurRow]->GetRowType() == OptionRow::RowType_Exit ) - return NULL; + return nullptr; // a course int index = iCurRow - 1; diff --git a/src/ScreenOptionsManageEditSteps.cpp b/src/ScreenOptionsManageEditSteps.cpp index 2c2a7ecbe6..2797c11084 100644 --- a/src/ScreenOptionsManageEditSteps.cpp +++ b/src/ScreenOptionsManageEditSteps.cpp @@ -294,9 +294,9 @@ Steps *ScreenOptionsManageEditSteps::GetStepsWithFocus() const { int iCurRow = m_iCurrentRow[GAMESTATE->GetMasterPlayerNumber()]; if( iCurRow == 0 ) - return NULL; + return nullptr; else if( m_pRows[iCurRow]->GetRowType() == OptionRow::RowType_Exit ) - return NULL; + return nullptr; // a Steps int iStepsIndex = iCurRow - 1; diff --git a/src/ScreenOptionsMasterPrefs.cpp b/src/ScreenOptionsMasterPrefs.cpp index 4fe1b1fd74..b6e1c733a3 100644 --- a/src/ScreenOptionsMasterPrefs.cpp +++ b/src/ScreenOptionsMasterPrefs.cpp @@ -785,7 +785,7 @@ ConfOption *ConfOption::Find( RString name ) return opt; } - return NULL; + return nullptr; } void ConfOption::UpdateAvailableOptions() diff --git a/src/SongManager.cpp b/src/SongManager.cpp index c54023021f..6a76c022c7 100644 --- a/src/SongManager.cpp +++ b/src/SongManager.cpp @@ -1242,7 +1242,7 @@ void SongManager::GetExtraStageInfo( bool bExtra2, const Style *sd, Song*& pSong Song* SongManager::GetRandomSong() { if( m_pShuffledSongs.empty() ) - return NULL; + return nullptr; static int i = 0; @@ -1258,13 +1258,13 @@ Song* SongManager::GetRandomSong() return pSong; } - return NULL; + return nullptr; } Course* SongManager::GetRandomCourse() { if( m_pShuffledCourses.empty() ) - return NULL; + return nullptr; static int i = 0; @@ -1282,7 +1282,7 @@ Course* SongManager::GetRandomCourse() return pCourse; } - return NULL; + return nullptr; } Song* SongManager::GetSongFromDir( RString sDir ) const @@ -1296,13 +1296,13 @@ Song* SongManager::GetSongFromDir( RString sDir ) const if( sDir.EqualsNoCase(s->GetSongDir()) ) return s; - return NULL; + return nullptr; } Course* SongManager::GetCourseFromPath( RString sPath ) const { if( sPath == "" ) - return NULL; + return nullptr; for (Course *c : m_pCourses) { @@ -1310,19 +1310,19 @@ Course* SongManager::GetCourseFromPath( RString sPath ) const return c; } - return NULL; + return nullptr; } Course* SongManager::GetCourseFromName( RString sName ) const { if( sName == "" ) - return NULL; + return nullptr; for (Course *c : m_pCourses) if( sName.CompareNoCase(c->GetDisplayFullTitle()) == 0 ) return c; - return NULL; + return nullptr; } @@ -1350,7 +1350,7 @@ Song *SongManager::FindSong( RString sPath ) const else if( bits.size() == 2 ) return FindSong( bits[0], bits[1] ); - return NULL; + return nullptr; } Song *SongManager::FindSong( RString sGroup, RString sSong ) const @@ -1363,7 +1363,7 @@ Song *SongManager::FindSong( RString sGroup, RString sSong ) const return s; } - return NULL; + return nullptr; } Course *SongManager::FindCourse( RString sPath ) const @@ -1377,7 +1377,7 @@ Course *SongManager::FindCourse( RString sPath ) const else if( bits.size() == 2 ) return FindCourse( bits[0], bits[1] ); - return NULL; + return nullptr; } Course *SongManager::FindCourse( RString sGroup, RString sName ) const @@ -1388,7 +1388,7 @@ Course *SongManager::FindCourse( RString sGroup, RString sName ) const return c; } - return NULL; + return nullptr; } void SongManager::UpdatePopular() diff --git a/src/SongUtil.cpp b/src/SongUtil.cpp index 9097ede420..d50d316cb4 100644 --- a/src/SongUtil.cpp +++ b/src/SongUtil.cpp @@ -158,7 +158,7 @@ Steps* SongUtil::GetOneSteps( vector vpSteps; GetSteps( pSong, vpSteps, st, dc, iMeterLow, iMeterHigh, sDescription, sCredit, bIncludeAutoGen, uHash, 1 ); // get max 1 if( vpSteps.empty() ) - return NULL; + return nullptr; else return vpSteps[0]; } @@ -178,7 +178,7 @@ Steps* SongUtil::GetStepsByDifficulty( const Song *pSong, StepsType st, Difficul return pSteps; } - return NULL; + return nullptr; } Steps* SongUtil::GetStepsByMeter( const Song *pSong, StepsType st, int iMeterLow, int iMeterHigh ) @@ -196,7 +196,7 @@ Steps* SongUtil::GetStepsByMeter( const Song *pSong, StepsType st, int iMeterLow return pSteps; } - return NULL; + return nullptr; } Steps* SongUtil::GetStepsByDescription( const Song *pSong, StepsType st, RString sDescription ) @@ -204,7 +204,7 @@ Steps* SongUtil::GetStepsByDescription( const Song *pSong, StepsType st, RString vector vNotes; GetSteps( pSong, vNotes, st, Difficulty_Invalid, -1, -1, sDescription, "" ); if( vNotes.size() == 0 ) - return NULL; + return nullptr; else return vNotes[0]; } @@ -214,7 +214,7 @@ Steps* SongUtil::GetStepsByCredit( const Song *pSong, StepsType st, RString sCre vector vNotes; GetSteps(pSong, vNotes, st, Difficulty_Invalid, -1, -1, "", sCredit ); if( vNotes.size() == 0 ) - return NULL; + return nullptr; else return vNotes[0]; } diff --git a/src/StepsUtil.cpp b/src/StepsUtil.cpp index 38c03252f8..3a8b87ed70 100644 --- a/src/StepsUtil.cpp +++ b/src/StepsUtil.cpp @@ -243,7 +243,7 @@ void StepsID::FromSteps( const Steps *p ) Steps *StepsID::ToSteps( const Song *p, bool bAllowNull ) const { if( st == StepsType_Invalid || dc == Difficulty_Invalid ) - return NULL; + return nullptr; SongID songID; songID.FromSong( p ); diff --git a/src/StyleUtil.cpp b/src/StyleUtil.cpp index 79ecc6ff4e..d96ddce726 100644 --- a/src/StyleUtil.cpp +++ b/src/StyleUtil.cpp @@ -24,7 +24,7 @@ const Style *StyleID::ToStyle() const { const Game* pGame = GAMEMAN->StringToGame( sGame ); if( pGame == nullptr ) - return NULL; + return nullptr; return GAMEMAN->GameAndStringToStyle( pGame, sStyle ); } diff --git a/src/UnlockManager.cpp b/src/UnlockManager.cpp index 79a28eb331..d7411ca9a7 100644 --- a/src/UnlockManager.cpp +++ b/src/UnlockManager.cpp @@ -203,7 +203,7 @@ const UnlockEntry *UnlockManager::FindSong( const Song *pSong ) const for (UnlockEntry const &e : m_UnlockEntries) if( e.m_Song.ToSong() == pSong && e.m_dc == Difficulty_Invalid ) return &e; - return NULL; + return nullptr; } const UnlockEntry *UnlockManager::FindSteps( const Song *pSong, const Steps *pSteps ) const @@ -212,7 +212,7 @@ const UnlockEntry *UnlockManager::FindSteps( const Song *pSong, const Steps *pSt for (UnlockEntry const &e : m_UnlockEntries) if( e.m_Song.ToSong() == pSong && e.m_dc == pSteps->GetDifficulty() ) return &e; - return NULL; + return nullptr; } const UnlockEntry *UnlockManager::FindStepsType(const Song *pSong, @@ -225,7 +225,7 @@ const UnlockEntry *UnlockManager::FindStepsType(const Song *pSong, e.m_dc == pSteps->GetDifficulty() && e.m_StepsType == pSteps->m_StepsType) return &e; - return NULL; + return nullptr; } const UnlockEntry *UnlockManager::FindCourse( const Course *pCourse ) const @@ -233,7 +233,7 @@ const UnlockEntry *UnlockManager::FindCourse( const Course *pCourse ) const for (UnlockEntry const &e : m_UnlockEntries) if( e.m_Course.ToCourse() == pCourse ) return &e; - return NULL; + return nullptr; } const UnlockEntry *UnlockManager::FindModifier( const RString &sOneMod ) const @@ -241,7 +241,7 @@ const UnlockEntry *UnlockManager::FindModifier( const RString &sOneMod ) const for (UnlockEntry const &e : m_UnlockEntries) if( e.GetModifier().CompareNoCase(sOneMod) == 0 ) return &e; - return NULL; + return nullptr; } static float GetArcadePoints( const Profile *pProfile ) diff --git a/src/WheelBase.cpp b/src/WheelBase.cpp index 3f19afd5de..b22f5edd15 100644 --- a/src/WheelBase.cpp +++ b/src/WheelBase.cpp @@ -320,7 +320,7 @@ WheelItemBaseData* WheelBase::GetItem( unsigned int iIndex ) if( !m_bEmpty && iIndex < m_CurWheelItemData.size() ) return m_CurWheelItemData[iIndex]; - return NULL; + return nullptr; } int WheelBase::IsMoving() const @@ -502,7 +502,7 @@ void WheelBase::RebuildWheelItems( int iDist ) WheelItemBaseData* WheelBase::LastSelected() { if( m_bEmpty ) - return NULL; + return nullptr; else return m_LastSelection; } diff --git a/src/WheelBase.h b/src/WheelBase.h index 67cf598d49..b1d6a44803 100644 --- a/src/WheelBase.h +++ b/src/WheelBase.h @@ -1,148 +1,148 @@ -#ifndef WHEELBASE_H -#define WHEELBASE_H - -#include "AutoActor.h" -#include "ActorFrame.h" -#include "RageSound.h" -#include "GameConstantsAndTypes.h" -#include "ScreenMessage.h" -#include "ScrollBar.h" -#include "RageTimer.h" -#include "WheelItemBase.h" -#include "ThemeMetric.h" -#include "LuaExpressionTransform.h" - -#define NUM_WHEEL_ITEMS ((int)ceil(NUM_WHEEL_ITEMS_TO_DRAW+2)) - -enum WheelState { - STATE_SELECTING, - STATE_FLYING_OFF_BEFORE_NEXT_SORT, - STATE_FLYING_ON_AFTER_NEXT_SORT, - STATE_ROULETTE_SPINNING, - STATE_ROULETTE_SLOWING_DOWN, - STATE_RANDOM_SPINNING, - STATE_LOCKED, - NUM_WheelState, - WheelState_Invalid, -}; -const RString& WheelStateToString( WheelState ws ); -WheelState StringToWheelState( const RString& sDC ); -LuaDeclareType( WheelState ); - -/** @brief A wheel with data elements. */ -class WheelBase : public ActorFrame -{ -public: - virtual ~WheelBase(); - virtual void Load( RString sType ); - void BeginScreen(); - - virtual void Update( float fDeltaTime ); - - virtual void Move(int n); - void ChangeMusicUnlessLocked( int n ); /* +1 or -1 */ - virtual void ChangeMusic(int dist); /* +1 or -1 */ - virtual void SetOpenSection( RString group ) { } - - // Return true if we're moving fast automatically. - int IsMoving() const; - bool IsSettled() const; - - void GetItemPosition( float fPosOffsetsFromMiddle, float& fX_out, float& fY_out, float& fZ_out, float& fRotationX_out ); - void SetItemPosition( Actor &item, float fPosOffsetsFromMiddle ); - - virtual bool Select(); // return true if this selection can end the screen - - WheelState GetWheelState() { return m_WheelState; } - bool WheelIsLocked() { return (m_WheelState == STATE_LOCKED ? true : false); } - void RebuildWheelItems( int dist = INT_MAX ); // INT_MAX = refresh all - - virtual unsigned int GetNumItems() const { return m_CurWheelItemData.size(); } - bool IsEmpty() { return m_bEmpty; } - WheelItemBaseData* GetItem(unsigned int index); - WheelItemBaseData* LastSelected(); - WheelItemBase *GetWheelItem( int i ) { if( i < 0 || i >= (int) m_WheelBaseItems.size() ) return NULL; return m_WheelBaseItems[i]; } - RString GetExpandedSectionName() { return m_sExpandedSectionName; } - int GetCurrentIndex() { return m_iSelection; } - - WheelItemDataType GetSelectedType() { return m_CurWheelItemData[m_iSelection]->m_Type; } - - // Lua - void PushSelf( lua_State *L ); - -protected: - void TweenOnScreenForSort(); - void TweenOffScreenForSort(); - - virtual WheelItemBase *MakeItem() = 0; - virtual void UpdateSwitch(); - virtual bool MoveSpecific(int n); - void SetPositions(); - - int FirstVisibleIndex(); - - ScrollBar m_ScrollBar; - AutoActor m_sprHighlight; - - vector m_CurWheelItemData; - vector m_WheelBaseItems; - WheelItemBaseData* m_LastSelection; - - bool m_bEmpty; - int m_iSelection; // index into m_CurWheelItemBaseData - RString m_sExpandedSectionName; - - int m_iSwitchesLeftInSpinDown; - float m_fLockedWheelVelocity; - // 0 = none; -1 or 1 = up/down - int m_Moving; - RageTimer m_MovingSoundTimer; - float m_TimeBeforeMovingBegins; - float m_SpinSpeed; - - WheelState m_WheelState; - float m_fTimeLeftInState; - float m_fPositionOffsetFromSelection; - - RageSound m_soundChangeMusic; - RageSound m_soundExpand; - RageSound m_soundCollapse; - RageSound m_soundLocked; - -// bool WheelItemIsVisible(int n); - void UpdateScrollbar(); - - ThemeMetric SWITCH_SECONDS; - ThemeMetric LOCKED_INITIAL_VELOCITY; - ThemeMetric SCROLL_BAR_HEIGHT; - LuaExpressionTransform m_exprItemTransformFunction; - ThemeMetric NUM_WHEEL_ITEMS_TO_DRAW; - ThemeMetric WHEEL_ITEM_LOCKED_COLOR; -}; - -#endif - -/* - * (c) 2001-2004 Chris Danford, Chris Gomez, Glenn Maynard, Josh Allen - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef WHEELBASE_H +#define WHEELBASE_H + +#include "AutoActor.h" +#include "ActorFrame.h" +#include "RageSound.h" +#include "GameConstantsAndTypes.h" +#include "ScreenMessage.h" +#include "ScrollBar.h" +#include "RageTimer.h" +#include "WheelItemBase.h" +#include "ThemeMetric.h" +#include "LuaExpressionTransform.h" + +#define NUM_WHEEL_ITEMS ((int)ceil(NUM_WHEEL_ITEMS_TO_DRAW+2)) + +enum WheelState { + STATE_SELECTING, + STATE_FLYING_OFF_BEFORE_NEXT_SORT, + STATE_FLYING_ON_AFTER_NEXT_SORT, + STATE_ROULETTE_SPINNING, + STATE_ROULETTE_SLOWING_DOWN, + STATE_RANDOM_SPINNING, + STATE_LOCKED, + NUM_WheelState, + WheelState_Invalid, +}; +const RString& WheelStateToString( WheelState ws ); +WheelState StringToWheelState( const RString& sDC ); +LuaDeclareType( WheelState ); + +/** @brief A wheel with data elements. */ +class WheelBase : public ActorFrame +{ +public: + virtual ~WheelBase(); + virtual void Load( RString sType ); + void BeginScreen(); + + virtual void Update( float fDeltaTime ); + + virtual void Move(int n); + void ChangeMusicUnlessLocked( int n ); /* +1 or -1 */ + virtual void ChangeMusic(int dist); /* +1 or -1 */ + virtual void SetOpenSection( RString group ) { } + + // Return true if we're moving fast automatically. + int IsMoving() const; + bool IsSettled() const; + + void GetItemPosition( float fPosOffsetsFromMiddle, float& fX_out, float& fY_out, float& fZ_out, float& fRotationX_out ); + void SetItemPosition( Actor &item, float fPosOffsetsFromMiddle ); + + virtual bool Select(); // return true if this selection can end the screen + + WheelState GetWheelState() { return m_WheelState; } + bool WheelIsLocked() { return (m_WheelState == STATE_LOCKED ? true : false); } + void RebuildWheelItems( int dist = INT_MAX ); // INT_MAX = refresh all + + virtual unsigned int GetNumItems() const { return m_CurWheelItemData.size(); } + bool IsEmpty() { return m_bEmpty; } + WheelItemBaseData* GetItem(unsigned int index); + WheelItemBaseData* LastSelected(); + WheelItemBase *GetWheelItem( int i ) { if( i < 0 || i >= (int) m_WheelBaseItems.size() ) return nullptr; return m_WheelBaseItems[i]; } + RString GetExpandedSectionName() { return m_sExpandedSectionName; } + int GetCurrentIndex() { return m_iSelection; } + + WheelItemDataType GetSelectedType() { return m_CurWheelItemData[m_iSelection]->m_Type; } + + // Lua + void PushSelf( lua_State *L ); + +protected: + void TweenOnScreenForSort(); + void TweenOffScreenForSort(); + + virtual WheelItemBase *MakeItem() = 0; + virtual void UpdateSwitch(); + virtual bool MoveSpecific(int n); + void SetPositions(); + + int FirstVisibleIndex(); + + ScrollBar m_ScrollBar; + AutoActor m_sprHighlight; + + vector m_CurWheelItemData; + vector m_WheelBaseItems; + WheelItemBaseData* m_LastSelection; + + bool m_bEmpty; + int m_iSelection; // index into m_CurWheelItemBaseData + RString m_sExpandedSectionName; + + int m_iSwitchesLeftInSpinDown; + float m_fLockedWheelVelocity; + // 0 = none; -1 or 1 = up/down + int m_Moving; + RageTimer m_MovingSoundTimer; + float m_TimeBeforeMovingBegins; + float m_SpinSpeed; + + WheelState m_WheelState; + float m_fTimeLeftInState; + float m_fPositionOffsetFromSelection; + + RageSound m_soundChangeMusic; + RageSound m_soundExpand; + RageSound m_soundCollapse; + RageSound m_soundLocked; + +// bool WheelItemIsVisible(int n); + void UpdateScrollbar(); + + ThemeMetric SWITCH_SECONDS; + ThemeMetric LOCKED_INITIAL_VELOCITY; + ThemeMetric SCROLL_BAR_HEIGHT; + LuaExpressionTransform m_exprItemTransformFunction; + ThemeMetric NUM_WHEEL_ITEMS_TO_DRAW; + ThemeMetric WHEEL_ITEM_LOCKED_COLOR; +}; + +#endif + +/* + * (c) 2001-2004 Chris Danford, Chris Gomez, Glenn Maynard, Josh Allen + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/XmlFile.cpp b/src/XmlFile.cpp index ea0ac1e4f3..2e3eb09e96 100644 --- a/src/XmlFile.cpp +++ b/src/XmlFile.cpp @@ -73,7 +73,7 @@ const XNodeValue *XNode::GetAttr( const RString &attrname ) const XAttrs::const_iterator it = m_attrs.find( attrname ); if( it != m_attrs.end() ) return it->second; - return NULL; + return nullptr; } bool XNode::PushAttrValue( lua_State *L, const RString &sName ) const @@ -93,7 +93,7 @@ XNodeValue *XNode::GetAttr( const RString &attrname ) XAttrs::iterator it = m_attrs.find( attrname ); if( it != m_attrs.end() ) return it->second; - return NULL; + return nullptr; } XNode *XNode::GetChild( const RString &sName ) @@ -103,7 +103,7 @@ XNode *XNode::GetChild( const RString &sName ) if( it->GetName() == sName ) return it; } - return NULL; + return nullptr; } bool XNode::PushChildValue( lua_State *L, const RString &sName ) const @@ -125,7 +125,7 @@ const XNode *XNode::GetChild( const RString &sName ) const if( it->GetName() == sName ) return it; } - return NULL; + return nullptr; } XNode *XNode::AppendChild( XNode *node ) diff --git a/src/arch/Dialog/DialogDriver.cpp b/src/arch/Dialog/DialogDriver.cpp index 7a2cfeaa41..e4fdd11866 100644 --- a/src/arch/Dialog/DialogDriver.cpp +++ b/src/arch/Dialog/DialogDriver.cpp @@ -40,7 +40,7 @@ DialogDriver *DialogDriver::Create() LOG->Info( "Couldn't load driver %s: %s", Driver.c_str(), sError.c_str() ); SAFE_DELETE( pRet ); } - return NULL; + return nullptr; } diff --git a/src/arch/InputHandler/InputHandler_MacOSX_HID.cpp b/src/arch/InputHandler/InputHandler_MacOSX_HID.cpp index 35f052ade0..bc9849fb4f 100644 --- a/src/arch/InputHandler/InputHandler_MacOSX_HID.cpp +++ b/src/arch/InputHandler/InputHandler_MacOSX_HID.cpp @@ -180,7 +180,7 @@ static HIDDevice *MakeDevice( InputDevice id ) return new JoystickDevice; if( IsPump(id) ) return new PumpDevice; - return NULL; + return nullptr; } void InputHandler_MacOSX_HID::AddDevices( int usagePage, int usage, InputDevice &id ) diff --git a/src/arch/LoadingWindow/LoadingWindow_GtkModule.cpp b/src/arch/LoadingWindow/LoadingWindow_GtkModule.cpp index 0bb0a87cf5..fcaab8c0a1 100644 --- a/src/arch/LoadingWindow/LoadingWindow_GtkModule.cpp +++ b/src/arch/LoadingWindow/LoadingWindow_GtkModule.cpp @@ -49,7 +49,7 @@ extern "C" const char *Init( int *argc, char ***argv ) gtk_widget_show_all(window); gtk_main_iteration_do(FALSE); - return NULL; + return nullptr; } extern "C" void Shutdown() diff --git a/src/arch/LoadingWindow/LoadingWindow_Win32.cpp b/src/arch/LoadingWindow/LoadingWindow_Win32.cpp index c9bce78ac8..d4183f5876 100644 --- a/src/arch/LoadingWindow/LoadingWindow_Win32.cpp +++ b/src/arch/LoadingWindow/LoadingWindow_Win32.cpp @@ -74,7 +74,7 @@ static HBITMAP LoadWin32Surface( RString sFile, HWND hWnd ) RString error; RageSurface *pSurface = RageSurfaceUtils::LoadFile( sFile, error ); if( pSurface == nullptr ) - return NULL; + return nullptr; HBITMAP ret = LoadWin32Surface( pSurface, hWnd ); delete pSurface; diff --git a/src/arch/LowLevelWindow/LowLevelWindow.h b/src/arch/LowLevelWindow/LowLevelWindow.h index ad31aab327..89e844d106 100644 --- a/src/arch/LowLevelWindow/LowLevelWindow.h +++ b/src/arch/LowLevelWindow/LowLevelWindow.h @@ -1,72 +1,72 @@ -#ifndef LOW_LEVEL_WINDOW_H -#define LOW_LEVEL_WINDOW_H - -#include - -class DisplayResolution; -typedef set DisplayResolutions; -class VideoModeParams; -class RenderTarget; -struct RenderTargetParam; -/** @brief Handle low-level operations that OGL 1.x doesn't give us. */ -class LowLevelWindow -{ -public: - static LowLevelWindow *Create(); - - virtual ~LowLevelWindow() { } - - virtual void *GetProcAddress( RString s ) = 0; - - // Return "" if mode change was successful, otherwise an error message. - // bNewDeviceOut is set true if a new device was created and textures - // need to be reloaded. - virtual RString TryVideoMode( const VideoModeParams &p, bool &bNewDeviceOut ) = 0; - virtual void GetDisplayResolutions( DisplayResolutions &out ) const = 0; - - virtual void LogDebugInformation() const { } - virtual bool IsSoftwareRenderer( RString & /* sError */ ) { return false; } - - virtual void SwapBuffers() = 0; - virtual void Update() { } - - virtual const VideoModeParams &GetActualVideoModeParams() const = 0; - - virtual bool SupportsRenderToTexture() const { return false; } - virtual RenderTarget *CreateRenderTarget() { return NULL; } - - virtual bool SupportsThreadedRendering() { return false; } - virtual void BeginConcurrentRenderingMainThread() { } - virtual void EndConcurrentRenderingMainThread() { } - virtual void BeginConcurrentRendering() { } - virtual void EndConcurrentRendering() { } -}; - -#endif - -/** - * @file - * @author Glenn Maynard (c) 2003-2004 - * @section LICENSE - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons to - * whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF - * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS - * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT - * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS - * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - * PERFORMANCE OF THIS SOFTWARE. - */ +#ifndef LOW_LEVEL_WINDOW_H +#define LOW_LEVEL_WINDOW_H + +#include + +class DisplayResolution; +typedef set DisplayResolutions; +class VideoModeParams; +class RenderTarget; +struct RenderTargetParam; +/** @brief Handle low-level operations that OGL 1.x doesn't give us. */ +class LowLevelWindow +{ +public: + static LowLevelWindow *Create(); + + virtual ~LowLevelWindow() { } + + virtual void *GetProcAddress( RString s ) = 0; + + // Return "" if mode change was successful, otherwise an error message. + // bNewDeviceOut is set true if a new device was created and textures + // need to be reloaded. + virtual RString TryVideoMode( const VideoModeParams &p, bool &bNewDeviceOut ) = 0; + virtual void GetDisplayResolutions( DisplayResolutions &out ) const = 0; + + virtual void LogDebugInformation() const { } + virtual bool IsSoftwareRenderer( RString & /* sError */ ) { return false; } + + virtual void SwapBuffers() = 0; + virtual void Update() { } + + virtual const VideoModeParams &GetActualVideoModeParams() const = 0; + + virtual bool SupportsRenderToTexture() const { return false; } + virtual RenderTarget *CreateRenderTarget() { return nullptr; } + + virtual bool SupportsThreadedRendering() { return false; } + virtual void BeginConcurrentRenderingMainThread() { } + virtual void EndConcurrentRenderingMainThread() { } + virtual void BeginConcurrentRendering() { } + virtual void EndConcurrentRendering() { } +}; + +#endif + +/** + * @file + * @author Glenn Maynard (c) 2003-2004 + * @section LICENSE + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, and/or sell copies of the Software, and to permit persons to + * whom the Software is furnished to do so, provided that the above + * copyright notice(s) and this permission notice appear in all copies of + * the Software and that both the above copyright notice(s) and this + * permission notice appear in supporting documentation. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS + * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ diff --git a/src/arch/RageDriver.cpp b/src/arch/RageDriver.cpp index 206f4212fb..d996e23553 100644 --- a/src/arch/RageDriver.cpp +++ b/src/arch/RageDriver.cpp @@ -13,11 +13,11 @@ void DriverList::Add( const istring &sName, CreateRageDriverFn pfn ) RageDriver *DriverList::Create( const RString &sDriverName ) { if( m_pRegistrees == nullptr ) - return NULL; + return nullptr; map::const_iterator iter = m_pRegistrees->find( istring(sDriverName) ); if( iter == m_pRegistrees->end() ) - return NULL; + return nullptr; return (iter->second)(); } diff --git a/src/arch/Sound/RageSoundDriver.cpp b/src/arch/Sound/RageSoundDriver.cpp index d616840abf..aea3d1b2c0 100644 --- a/src/arch/Sound/RageSoundDriver.cpp +++ b/src/arch/Sound/RageSoundDriver.cpp @@ -34,7 +34,7 @@ RageSoundDriver *RageSoundDriver::Create( const RString& sDrivers ) LOG->Info( "Couldn't load driver %s: %s", driverString, sError.c_str() ); SAFE_DELETE( pRet ); } - return NULL; + return nullptr; } /* diff --git a/src/arch/Sound/RageSoundDriver_WDMKS.cpp b/src/arch/Sound/RageSoundDriver_WDMKS.cpp index 77386e90e8..4745d7ef4c 100644 --- a/src/arch/Sound/RageSoundDriver_WDMKS.cpp +++ b/src/arch/Sound/RageSoundDriver_WDMKS.cpp @@ -284,13 +284,13 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) &communication, sizeof(KSPIN_COMMUNICATION), sError) ) { sError = "KSPROPERTY_PIN_COMMUNICATION: " + sError; - return NULL; + return nullptr; } if( communication != KSPIN_COMMUNICATION_SINK && communication != KSPIN_COMMUNICATION_BOTH ) { sError = "Not an audio output device"; - return NULL; + return nullptr; } } @@ -301,13 +301,13 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) &dataFlow, sizeof(KSPIN_DATAFLOW), sError) ) { sError = "KSPROPERTY_PIN_DATAFLOW: " + sError; - return NULL; + return nullptr; } if( dataFlow != KSPIN_DATAFLOW_IN ) { sError = "Not KSPIN_DATAFLOW_IN"; - return NULL; + return nullptr; } } @@ -317,7 +317,7 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) if( !WdmGetPinPropertyMulti(m_hHandle, iPinId, &KSPROPSETID_Pin, KSPROPERTY_PIN_INTERFACES, &pItem, sError) ) { sError = "KSPROPERTY_PIN_INTERFACES: " + sError; - return NULL; + return nullptr; } KSIDENTIFIER *identifier = (KSIDENTIFIER *) &pItem[1]; @@ -337,7 +337,7 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) free( pItem ); if( sError != "" ) - return NULL; + return nullptr; } /* Get the MEDIUM properties list */ @@ -346,7 +346,7 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) if( !WdmGetPinPropertyMulti( m_hHandle, iPinId, &KSPROPSETID_Pin, KSPROPERTY_PIN_MEDIUMS, &pItem, sError) ) { sError = "KSPROPERTY_PIN_MEDIUMS: " + sError; - return NULL; + return nullptr; } const KSIDENTIFIER *identifier = (KSIDENTIFIER *) &pItem[1]; @@ -366,7 +366,7 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) free( pItem ); if( sError != "" ) - return NULL; + return nullptr; } /* Allocate the new PIN object */ @@ -421,7 +421,7 @@ WinWdmPin *WinWdmFilter::CreatePin( unsigned long iPinId, RString &sError ) error: /* Error cleanup */ delete pPin; - return NULL; + return nullptr; } /* If the pin handle is open, close it */ @@ -575,7 +575,7 @@ WinWdmFilter *WinWdmFilter::Create( const RString &sFilterName, const RString &s error: /* Error cleanup */ delete pFilter; - return NULL; + return nullptr; } /* @@ -634,7 +634,7 @@ WinWdmPin *WinWdmFilter::InstantiateRenderPin( const WAVEFORMATEX *wfex, RString } sError = "No pin supports format"; - return NULL; + return nullptr; } template @@ -790,7 +790,7 @@ WinWdmPin *WinWdmFilter::InstantiateRenderPin( } sError = "No compatible format found"; - return NULL; + return nullptr; } static bool GetDevicePath( HANDLE hHandle, SP_DEVICE_INTERFACE_DATA *pInterfaceData, RString &sPath ) diff --git a/src/arch/Threads/Threads_Win32.cpp b/src/arch/Threads/Threads_Win32.cpp index a1392604e1..ecc154e583 100644 --- a/src/arch/Threads/Threads_Win32.cpp +++ b/src/arch/Threads/Threads_Win32.cpp @@ -26,7 +26,7 @@ HANDLE Win32ThreadIdToHandle( uint64_t iID ) return g_ThreadHandles[i]; } - return NULL; + return nullptr; } void ThreadImpl_Win32::Halt( bool Kill ) diff --git a/src/archutils/Unix/BacktraceNames.cpp b/src/archutils/Unix/BacktraceNames.cpp index 2a1e27335d..8bb9298742 100644 --- a/src/archutils/Unix/BacktraceNames.cpp +++ b/src/archutils/Unix/BacktraceNames.cpp @@ -217,7 +217,7 @@ static const char *osx_find_link_edit( const struct mach_header *header ) return (char *) ( scmd->vmaddr - scmd->fileoff ); } - return NULL; + return nullptr; } void BacktraceNames::FromAddr( const void *p ) diff --git a/src/archutils/Unix/SignalHandler.cpp b/src/archutils/Unix/SignalHandler.cpp index e969db03ff..4e30c229c5 100644 --- a/src/archutils/Unix/SignalHandler.cpp +++ b/src/archutils/Unix/SignalHandler.cpp @@ -119,9 +119,9 @@ static void *CreateStack( int size ) p = (char *) mmap( NULL, size+PageSize, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0 ); if( p == (void *) -1 ) - return NULL; + return nullptr; // if( posix_memalign( (void**) &p, PageSize, RealSize ) != 0 ) - // return NULL; + // return nullptr; if( find_stack_direction() < 0 ) { diff --git a/src/archutils/Win32/Crash.cpp b/src/archutils/Win32/Crash.cpp index 3dc019efeb..a0cf183004 100644 --- a/src/archutils/Win32/Crash.cpp +++ b/src/archutils/Win32/Crash.cpp @@ -58,7 +58,7 @@ static const char *LookupException( DWORD code ) if( exceptions[i].code == code ) return exceptions[i].name; - return NULL; + return nullptr; } static CrashInfo g_CrashInfo; @@ -154,13 +154,13 @@ static const char *CrashGetModuleBaseName(HMODULE hmod, char *pszBaseName) __try { if( !GetModuleFileName(hmod, szPath1, sizeof(szPath1)) ) - return NULL; + return nullptr; char *pszFile; DWORD dw = GetFullPathName( szPath1, sizeof(szPath2), szPath2, &pszFile ); if( !dw || dw > sizeof(szPath2) ) - return NULL; + return nullptr; strcpy( pszBaseName, pszFile ); @@ -174,7 +174,7 @@ static const char *CrashGetModuleBaseName(HMODULE hmod, char *pszBaseName) if( period ) *period = 0; } __except(1) { - return NULL; + return nullptr; } return pszBaseName; diff --git a/src/archutils/Win32/CrashHandlerChild.cpp b/src/archutils/Win32/CrashHandlerChild.cpp index 5bc26f6381..63272a3713 100644 --- a/src/archutils/Win32/CrashHandlerChild.cpp +++ b/src/archutils/Win32/CrashHandlerChild.cpp @@ -286,7 +286,7 @@ namespace SymbolLookup pSymbol->MaxNameLen = sizeof(buffer) - sizeof(SYMBOL_INFO) + 1; if( !SymFromAddr(g_hParent, ptr, &disp, pSymbol) ) - return NULL; + return nullptr; return pSymbol; } diff --git a/src/archutils/Win32/CrashHandlerNetworking.cpp b/src/archutils/Win32/CrashHandlerNetworking.cpp index 75bf7692f4..f83ca962f9 100644 --- a/src/archutils/Win32/CrashHandlerNetworking.cpp +++ b/src/archutils/Win32/CrashHandlerNetworking.cpp @@ -158,7 +158,7 @@ NetworkStream *CreateNetworkStream() WSADATA WSAData; WORD iVersionRequested = MAKEWORD(2,0); if( WSAStartup(iVersionRequested, &WSAData) != 0 ) - return NULL; + return nullptr; } return new NetworkStream_Win32; diff --git a/src/archutils/Win32/RegistryAccess.cpp b/src/archutils/Win32/RegistryAccess.cpp index e9c3f2e121..2a689e0e93 100644 --- a/src/archutils/Win32/RegistryAccess.cpp +++ b/src/archutils/Win32/RegistryAccess.cpp @@ -36,14 +36,14 @@ static bool GetRegKeyType( const RString &sIn, RString &sOut, HKEY &key ) } /* Given a full key, eg. "HKEY_LOCAL_MACHINE\hardware\foo", open it and return it. - * On error, return NULL. */ + * On error, return nullptr. */ enum RegKeyMode { READ, WRITE }; static HKEY OpenRegKey( const RString &sKey, RegKeyMode mode, bool bWarnOnError = true ) { RString sSubkey; HKEY hType; if( !GetRegKeyType(sKey, sSubkey, hType) ) - return NULL; + return nullptr; HKEY hRetKey; LONG retval = RegOpenKeyEx( hType, sSubkey, 0, (mode==READ) ? KEY_READ:KEY_WRITE, &hRetKey ); @@ -51,7 +51,7 @@ static HKEY OpenRegKey( const RString &sKey, RegKeyMode mode, bool bWarnOnError { if( bWarnOnError ) LOG->Warn( werr_ssprintf(retval, "RegOpenKeyEx(%x,%s) error", hType, sSubkey.c_str()) ); - return NULL; + return nullptr; } return hRetKey; @@ -196,7 +196,7 @@ bool RegistryAccess::CreateKey( const RString &sKey ) RString sSubkey; HKEY hType; if( !GetRegKeyType(sKey, sSubkey, hType) ) - return NULL; + return nullptr; HKEY hKey; DWORD dwDisposition = 0; diff --git a/src/archutils/Win32/WindowIcon.cpp b/src/archutils/Win32/WindowIcon.cpp index 94657acc08..cd52b87bb0 100644 --- a/src/archutils/Win32/WindowIcon.cpp +++ b/src/archutils/Win32/WindowIcon.cpp @@ -83,7 +83,7 @@ HICON IconFromSurface( const RageSurface *pSrcImg ) if( icon == nullptr ) { LOG->Trace( "%s", werr_ssprintf( GetLastError(), "CreateIconFromResourceEx" ).c_str() ); - return NULL; + return nullptr; } return icon; @@ -96,7 +96,7 @@ HICON IconFromFile( const RString &sIconFile ) if( pImg == nullptr ) { LOG->Warn( "Couldn't open icon \"%s\": %s", sIconFile.c_str(), sError.c_str() ); - return NULL; + return nullptr; } HICON icon = IconFromSurface( pImg );