blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
ea99827e0598c214ddaff0c3f26c36fe0847c8e4
ad2d392f73f6e26b4f082fb0251b241a7ebf85a8
/abc/heisei/064/b.cpp
51ce0c27f6d85467f45587e7910935e0d083b7cf
[]
no_license
miyamotononno/atcoder
b293ac3b25397567aa93a179d1af34add492518b
cf29d48c7448464d33a9d7ad69affd771319fe3c
refs/heads/master
2022-01-09T23:03:07.022772
2022-01-08T14:12:13
2022-01-08T14:12:13
187,175,157
0
0
null
2019-06-12T16:03:24
2019-05-17T08:11:58
Python
UTF-8
C++
false
false
689
cpp
#include <algorithm> #include <iostream> #include <iomanip> #include <cassert> #include <cstring> #include <string> #include <vector> #include <random> #include <bitset> #include <queue> #include <cmath> #include <unordered_map> #include <set> #include <map> #define INCANT cin.tie(0), cout.tie(0), ios::sync_with_stdio(0), cout << fixed << setprecision(20); #define rep(i,n) for (int i=0; i<n;++i) #define ALL(a) (a).begin(),(a).end() #define PI 3.14159265358979 typedef long long ll; using namespace std; const ll MOD = 1e9+7LL; const int INF = 2e9; int N, A[101]; int main() { INCANT; cin >> N; rep(i, N) cin >> A[i]; sort(A, A+N); cout << A[N-1]-A[0] << "\n"; return 0; }
[ "miyamoto-nozomu@g.ecc.u-tokyo.ac.jp" ]
miyamoto-nozomu@g.ecc.u-tokyo.ac.jp
cbe3f82f48123be3e51dd93d1320fcae7557154b
bfa40191bb6837f635d383d9cd7520160d0b03ac
/LightNote/Source/Core/Graphics/Device/OpenGL/GLGraphicsDevice.cpp
7f7156c888b3fde511c393b9892b2abbe4334ca0
[]
no_license
lriki/LightNote
87ec6969c16f2919d04fdaac9d0e7ed389f403ad
a38542691d0c7453dd108bcf1d653a08bb1b6b6b
refs/heads/master
2021-01-10T19:16:33.199071
2015-02-01T08:41:06
2015-02-01T08:41:06
25,684,431
0
0
null
null
null
null
UTF-8
C++
false
false
28,765
cpp
//============================================================================== // GLGraphicsDevice //============================================================================== #include "stdafx.h" #ifdef LNOTE_FOR_200 #include "../../../System/Manager.h" #include "../../../FileIO/Manager.h" //#include "LNGL/LNGL.h" //#include "GLPlatformContext.h" #include "GLRenderer.h" #include "GLCanvas.h" #include "GLVertexBuffer.h" #include "GLIndexBuffer.h" #include "GLShader.h" #include "GLGraphicsDevice.h" namespace LNote { namespace Core { namespace Graphics { //============================================================================== // ■ GLGraphicsDevice //============================================================================== //---------------------------------------------------------------------- // //---------------------------------------------------------------------- GLGraphicsDevice::GLGraphicsDevice() : mPlatformContext ( NULL ) , mRenderer ( NULL ) , mDefaultCanvas ( NULL ) { } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- GLGraphicsDevice::~GLGraphicsDevice() { //LNGL::finalize(); if ( mPlatformContext ) { mPlatformContext->finalize(); } SAFE_DELETE( mPlatformContext ); } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- void GLGraphicsDevice::initialize( const ConfigData& configData ) { GraphicsDeviceBase::initialize( configData ); //LNGL::InitData lngl_data; // lngl_data.LogFile = NULL; // lngl_data.SystemManager = configData.SystemManager; // LNGL::initialize( lngl_data ); mPlatformContext = LN_NEW GLPlatformContext(); mPlatformContext->initialize( configData.SystemManager ); mDefaultCanvas = LN_NEW GLCanvas(); mDefaultCanvas->create(this, configData.SystemManager->getMainWindow(), configData.BackbufferSize, BackbufferResizeMode_Scaling); // TODO: ResizeMode mRenderer = LN_NEW GLRenderer(); mRenderer->initialize( this ); } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- void GLGraphicsDevice::finalize() { LN_SAFE_RELEASE( mRenderer ); LN_SAFE_RELEASE( mDefaultCanvas ); GraphicsDeviceBase::finalize(); } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- IRenderer* GLGraphicsDevice::getRenderer() { return mRenderer; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- ICanvas* GLGraphicsDevice::getDefaultCanvas() { return mDefaultCanvas; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- IVertexBuffer* GLGraphicsDevice::createVertexBuffer( LNVertexElemenst* elements, lnU32 vertexCount, const void* data, bool isDynamic ) { LRefPtr<GLVertexBuffer> vb( LN_NEW GLVertexBuffer() ); vb->create( this, elements, vertexCount, data, isDynamic ); vb->addRef(); return vb; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- IIndexBuffer* GLGraphicsDevice::createIndexBuffer( lnU32 indexCount, const void* data, bool isDynamic, bool is16bit ) { LRefPtr<GLIndexBuffer> ib( LN_NEW GLIndexBuffer() ); ib->create( this, indexCount, data, isDynamic, is16bit ); ib->addRef(); return ib; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- ITexture* GLGraphicsDevice::createTexture( lnU32 width, lnU32 height, lnU32 levels, Graphics::SurfaceFormat format ) { return NULL; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- ITexture* GLGraphicsDevice::createTexture( FileIO::Stream* stream, lnU32 colorKey, lnU32 levels, Graphics::SurfaceFormat format, lnSharingKey key ) { return NULL; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- ITexture* GLGraphicsDevice::createTexture( const lnChar* filePath, lnU32 colorKey, lnU32 levels, Graphics::SurfaceFormat format, lnSharingKey key ) { return NULL; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- ITexture* GLGraphicsDevice::createRenderTarget( lnU32 width, lnU32 height, lnU32 mipLevels, Graphics::SurfaceFormat format ) { return NULL; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- ITexture* GLGraphicsDevice::createDepthBuffer( lnU32 width, lnU32 height, Graphics::SurfaceFormat format ) { return NULL; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- IShader* GLGraphicsDevice::createShader( FileIO::Stream* stream, lnSharingKey registerKey ) { // キャッシュ検索 IShader* ts = static_cast<GLShader*>( findShaderCache( registerKey ) ); if ( ts ) { return ts; } // Shader 作成 LRefPtr<GLShader> shader( LN_NEW GLShader() ); shader->create( this, stream ); // エラーでなければキャッシュ管理に追加 if ( shader->getCompileResult() != LN_SHADERRESULT_ERROR ) { if ( !registerKey.isEmpty() ) { mShaderCache.registerCachedObject( registerKey, shader ); } } shader.addRef(); return shader; } ////--------------------------------------------------------------------- //// // //--------------------------------------------------------------------- // IShader* GLGraphicsDevice::createShader( const void* data, lnU32 size, lnSharingKey registerKey ) // { // return NULL; // } ////--------------------------------------------------------------------- //// // //--------------------------------------------------------------------- //IShader* GLGraphicsDevice::createShader( const lnChar* filePath, lnSharingKey registerKey ) // { // // キャッシュ検索 // IShader* ts = static_cast<GLShader*>( findShaderCache( registerKey ) ); // if ( ts ) { // return ts; // } // // Shader 作成 // LRefPtr<GLShader> shader( LN_NEW GLShader() ); // shader->create( this, filePath ); // // エラーでなければキャッシュ管理に追加 // if ( shader->getCompileResult() != LN_SHADERRESULT_ERROR ) { // if ( !registerKey.isEmpty() ) { // mShaderCache.registerCachedObject( registerKey, shader ); // } // } // shader->addRef(); // return shader; // } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- void GLGraphicsDevice::pauseDevice() { } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- void GLGraphicsDevice::resumeDevice() { } ////---------------------------------------------------------------------- //// ////---------------------------------------------------------------------- //void GLGraphicsDevice::testDeviceLost() //{ //} //---------------------------------------------------------------------- // //---------------------------------------------------------------------- void GLGraphicsDevice::attachCurrentThread() { } } // namespace Graphics } // namespace Core } // namespace LNote #else //------------------------------------------------------------------------- // //------------------------------------------------------------------------- #include "stdafx.h" #include "../../../System/Manager.h" #include "../../../FileIO/Manager.h" #include "LNGL/LNGL.h" #include "GLRenderer.h" #include "GLCanvas.h" #include "GLVertexBuffer.h" #include "GLIndexBuffer.h" #include "GLTexture.h" #include "GLShaderManager.h" #include "GLShader.h" #include "GLGraphicsDevice.h" //------------------------------------------------------------------------- // //------------------------------------------------------------------------- namespace LNote { namespace Core { namespace Graphics { namespace OpenGL { //============================================================================== // ■ GraphicsDevice クラス //============================================================================== //---------------------------------------------------------------------- // ● コンストラクタ //---------------------------------------------------------------------- GraphicsDevice::GraphicsDevice() : mLogFile ( NULL ) , mSystemManager ( NULL ) , mFileManager ( NULL ) , mRenderer ( NULL ) , mShaderManager ( NULL ) //, mPlatformContext ( NULL ) , mDefaultCanvas ( NULL ) , mCurrentShaderrPass ( NULL ) , mIsDeviceLost ( false ) { } //---------------------------------------------------------------------- // ● デストラクタ //---------------------------------------------------------------------- GraphicsDevice::~GraphicsDevice() { /*SAFE_DELETE( mPlatformContext );*/ LNGL::finalize(); } //---------------------------------------------------------------------- // ● 初期化 //---------------------------------------------------------------------- void GraphicsDevice::initialize( const InitData& init_data_ ) { LN_LOG_INIT_BEGIN; LNGL::InitData lngl_data; lngl_data.LogFile = mLogFile; lngl_data.SystemManager = init_data_.SystemManager; LNGL::initialize(lngl_data); mManager = init_data_.Manager; mFileManager = init_data_.FileManager; //----------------------------------------------------- // // キャッシュサイズを設定 TextureCache::initialize( init_data_.TextureCacheSize ); // デフォルトのキャンバス (コンストラクタでリストに入れられる) DefaultCanvas::InitData c_data; //c_data.PlatformContext = mPlatformContext; c_data.Window = init_data_.SystemManager->getMainWindow(); c_data.CanvasSize = init_data_.CanvasSize; mDefaultCanvas = LN_NEW DefaultCanvas( this ); mDefaultCanvas->initialize( c_data ); // 描画クラスの作成 Renderer::InitData rend_data; rend_data.LogFile = mLogFile; rend_data.GraphicsDevice = this; //rend_data.PlatformContext = mPlatformContext; mRenderer = LN_NEW Renderer(); mRenderer->initialize( rend_data ); // シェーダ管理クラス ShaderManager::InitData sm_data; sm_data.LogFile = mLogFile; sm_data.GraphicsDevice = this; sm_data.ShaderCacheSize = init_data_.ShaderCacheSize; mShaderManager = LN_NEW ShaderManager(); mShaderManager->initialize( sm_data ); //mIsDeviceLost = true; // リセットを実行させるため、一度 true にする //onResetDevice(); LN_LOG_INIT_END; } //---------------------------------------------------------------------- // ● 終了処理 //---------------------------------------------------------------------- void GraphicsDevice::finalize() { LN_LOG_FIN_BEGIN; pauseDevice(); LN_SAFE_RELEASE( mCurrentShaderrPass ); LN_SAFE_RELEASE( mRenderer ); // ~Renderer() → onLostDevice() で使用しているのでRenderer の後で開放する LN_SAFE_RELEASE( mDefaultCanvas ); if ( mShaderManager ) { mShaderManager->finalize(); LN_SAFE_RELEASE( mShaderManager ); } TextureCache::finalize(); LN_LOG_FIN_END; } //---------------------------------------------------------------------- // ● 描画クラスの取得 //---------------------------------------------------------------------- IRenderer* GraphicsDevice::getRenderer() { return mRenderer; } //---------------------------------------------------------------------- // ● デフォルトのバックバッファを示すキャンバスの取得 //---------------------------------------------------------------------- ICanvas* GraphicsDevice::getDefaultCanvas() { return mDefaultCanvas; } //---------------------------------------------------------------------- // ● 頂点バッファの作成 //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createVertexBuffer( IVertexBuffer** obj_, LNVertexElemenst* elements_, lnU32 vertex_num_, const void* data_, bool is_dynamic_ ) { *obj_ = NULL; VertexBuffer* vb = LN_NEW VertexBuffer(); vb->initialize( this, elements_, vertex_num_, data_, is_dynamic_ ); mVertexBufferList.push_back(vb); *obj_ = vb; return LN_OK; } //---------------------------------------------------------------------- // ● インデックスバッファの作成 //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createIndexBuffer( IIndexBuffer** obj_, lnU32 index_num_, const lnU16* data_, bool is_dynamic_, bool is_16bit_ ) { *obj_ = NULL; IndexBuffer* ib = LN_NEW IndexBuffer(); ib->initialize( this, index_num_, data_, is_dynamic_, is_16bit_ ); mIndexBufferList.push_back(ib); *obj_ = ib; return LN_OK; } //---------------------------------------------------------------------- // ● テクスチャの作成 //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createTexture( ITexture** obj_, lnU32 width_, lnU32 height_, lnU32 levels_, LNSurfaceFormat format_ ) { *obj_ = NULL; Texture* tex = LN_NEW Texture( this ); tex->initialize( width_, height_, levels_, format_ ); *obj_ = tex; return LN_OK; } //---------------------------------------------------------------------- // ● テクスチャの作成 ( メモリに展開された画像データから ) //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createTexture( ITexture** obj_, const void* data_, lnU32 size_, lnU32 color_key_, lnU32 levels_, LNSurfaceFormat format_, lnSharingKey key_ ) { #if 0 LNRESULT lr; *obj_ = NULL; // キャッシュを検索 *obj_ = TextureCache::findCacheAddRef( key_ ); if ( *obj_ ) { return LN_OK; } // 新しく作る Texture* texture = LN_NEW Texture( this ); LN_CALL_R( texture->initialize( data_, size_, color_key_, levels_, format_ ) ); // キャッシュ管理クラスに追加 TextureCache::registerCachedObject( key_, texture ); *obj_ = texture; return LN_OK; #endif LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; } //---------------------------------------------------------------------- // ● テクスチャの作成 (入力ストリームから) //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createTexture( ITexture** obj_, FileIO::IInStream* stream_, lnU32 color_key_, lnU32 levels_, LNSurfaceFormat format_, lnSharingKey key_ ) { #if 0 lnU32 size = stream_->getSize(); *obj_ = NULL; lnByte* buf = mTempBuffer.lock( size ); stream_->read( buf, size ); LNRESULT lr = createTexture( obj_, buf, size, color_key_, levels_, format_, key_ ); mTempBuffer.unlock(); return lr; #endif LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; } //---------------------------------------------------------------------- // ● テクスチャの作成 (ファイルから) //---------------------------------------------------------------------- void GraphicsDevice::createTexture( ITexture** obj_, const lnChar* filename_, lnU32 color_key_, lnU32 levels_, LNSurfaceFormat format_, lnSharingKey key_ ) { *obj_ = NULL; Texture* tex = LN_NEW Texture( this ); tex->initialize( filename_, color_key_, levels_, format_ ); *obj_ = tex; mTextureList.push_back(tex); } //---------------------------------------------------------------------- // ● レンダーターゲットテクスチャの作成 //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createRenderTarget( ITexture** obj_, lnU32 width_, lnU32 height_, lnU32 levels_, LNSurfaceFormat format_ ) { *obj_ = NULL; RenderTargetTexture* tex = LN_NEW RenderTargetTexture( this ); tex->initialize( width_, height_, levels_, format_ ); mRenderTargetList.push_back( tex ); *obj_ = tex; return LN_OK; } //---------------------------------------------------------------------- // ● 深度バッファの作成 //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createDepthBuffer( ITexture** obj_, lnU32 width_, lnU32 height_, LNSurfaceFormat format_ ) { *obj_ = NULL; DepthBuffer* tex = LN_NEW DepthBuffer( this ); tex->initialize( width_, height_, format_ ); mDepthBufferList.push_back( tex ); *obj_ = tex; return LN_OK; } //---------------------------------------------------------------------- // ● シェーダの作成 //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createShader( IShader** obj_, const void* data_, lnU32 size_, lnSharingKey key_ ) { #if 0 LNRESULT lr; *obj_ = NULL; // キャッシュを検索 *obj_ = ShaderCache::findCacheAddRef( key_ ); if ( *obj_ ) { return LN_OK; } // 新しく作る Shader* shader = LN_NEW Shader( this ); LN_CALL_R( shader->initialize( static_cast< const char* >( data_ ) ) ); // キャッシュ管理クラスに追加 ShaderCache::registerCachedObject( key_, shader ); mShaderList.push_back( shader ); *obj_ = shader; return LN_OK; #endif LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; } //---------------------------------------------------------------------- // ● シェーダの作成 ( 入力ストリームから ) //---------------------------------------------------------------------- LNRESULT GraphicsDevice::createShader( IShader** obj_, FileIO::IInStream* stream_, lnSharingKey key_ ) { #if 0 lnU32 size = stream_->getSize(); *obj_ = NULL; lnByte* buf = mTempBuffer.lock( size + 1 ); // mTempBuffer に全部読み込む stream_->read( buf, size ); // Cg に渡すときは終端 NULL が必要 buf[ size ] = '\0'; LNRESULT lr = createShader( obj_, buf, size, key_ ); mTempBuffer.unlock(); return lr; #endif LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- void GraphicsDevice::createShader( IShader** obj_, const lnChar* filename_, lnSharingKey key_ ) { *obj_ = mShaderManager->createShader( filename_, key_ ); } //---------------------------------------------------------------------- // ● キャッシュのクリア //---------------------------------------------------------------------- void GraphicsDevice::clearCache( bool texture_, bool shader_ ) { if ( texture_ ) TextureCache::clear(); if ( shader_ ) mShaderManager->clearCache(); } //---------------------------------------------------------------------- // ● デバイスリセット前処理 //---------------------------------------------------------------------- void GraphicsDevice::pauseDevice() { if (!mIsDeviceLost) { LN_LOG_WRITE(_T("GraphicsDevice::onLostDevice() begin")); ln_foreach(VertexBuffer* t, mVertexBufferList) { t->onLostDevice(); } ln_foreach(IndexBuffer* t, mIndexBufferList) { t->onLostDevice(); } ln_foreach(Texture* t, mTextureList) { t->onLostDevice(); } ln_foreach(RenderTargetTexture* t, mRenderTargetList) { t->onLostDevice(); } ln_foreach(DepthBuffer* t, mDepthBufferList) { t->onLostDevice(); } if (mShaderManager) mShaderManager->onLostDevice(); if (mRenderer) mRenderer->onLostDevice(); if (mDefaultCanvas) mDefaultCanvas->onLostDevice(); mIsDeviceLost = true; LN_LOG_WRITE(_T("GraphicsDevice::onLostDevice() end")); } } //---------------------------------------------------------------------- // ● デバイスリセット後処理 //---------------------------------------------------------------------- void GraphicsDevice::resumeDevice() { if (mIsDeviceLost) { LN_LOG_WRITE(_T("GraphicsDevice::onResetDevice() begin")); mDefaultCanvas->onResetDevice(); mRenderer->onResetDevice(); mShaderManager->onResetDevice(); ln_foreach(DepthBuffer* t, mDepthBufferList) { t->onResetDevice(); } ln_foreach(RenderTargetTexture* t, mRenderTargetList) { t->onResetDevice(); } ln_foreach(Texture* t, mTextureList) { t->onResetDevice(); } ln_foreach(IndexBuffer* t, mIndexBufferList) { t->onResetDevice(); } ln_foreach(VertexBuffer* t, mVertexBufferList) { t->onResetDevice(); } // Renderer::setRenderTarget() で mDefaultCanvas を使ってるとかの都合で、 // mDefaultCanvas、mRenderer の初期化が終わった後に設定しておく必要がある //mDefaultCanvas->activate(); mIsDeviceLost = true; LN_LOG_WRITE(_T("GraphicsDevice::onResetDevice() end")); } } //---------------------------------------------------------------------- // ● デバイスのリセット //---------------------------------------------------------------------- LNRESULT GraphicsDevice::resetDevice( bool fullscreen_, const Geometry::Size& window_bb_size_ ) { #if 0 HRESULT hr; LNRESULT lr; // プレゼンテーションパラメータ設定 mIsFullScreen = ( canFullScreen() ) ? fullscreen_ : false; _setPresentParameters( window_bb_size_ ); // まだデバイスが作成されていなければ新規作成 if ( !mDxDevice ) { // D3Dデバイスの生成 DWORD fpu_precision = ( mEnableFPUPreserve ) ? D3DCREATE_FPU_PRESERVE : 0; LN_DXCALL_R( mDirect3D->CreateDevice( D3DADAPTER_DEFAULT, mDeviceType, mPresentParameters.hDeviceWindow, fpu_precision | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,//D3DCREATE_SOFTWARE_VERTEXPROCESSING, | D3DCREATE_MULTITHREADED &mPresentParameters, &mDxDevice ) ); } // 既に作成されている場合はリセット else { LN_DXCALL_R( _onLostDevice() ); // デバイスのリセット LN_DXCALL_R( mDxDevice->Reset( &mPresentParameters ) ); LN_DXCALL_R( _onResetDevice() ); } return LN_OK; #endif LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- void GraphicsDevice::commitChangesGLResource() { ln_foreach(VertexBuffer* t, mVertexBufferList) { t->commitChanges(); } ln_foreach(IndexBuffer* t, mIndexBufferList) { t->commitChanges(); } ln_foreach(Texture* t, mTextureList) { t->commitChanges(); } ln_foreach(RenderTargetTexture* t, mRenderTargetList) { t->commitChanges(); } ln_foreach(DepthBuffer* t, mDepthBufferList) { t->commitChanges(); } mShaderManager->commitChangesGLResource(); } //---------------------------------------------------------------------- // ● デバイスの性能チェック //---------------------------------------------------------------------- LNRESULT GraphicsDevice::_checkDeviceInformation() { LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; } //---------------------------------------------------------------------- // ● デバイスリセット前処理 //---------------------------------------------------------------------- LNRESULT GraphicsDevice::_onLostDevice() { LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; } //---------------------------------------------------------------------- // ● デバイスリセット後処理 //---------------------------------------------------------------------- LNRESULT GraphicsDevice::_onResetDevice() { #if 0 LNRESULT lr; ln_foreach( Shader* t, mShaderList ) { LN_CALL_R( t->onResetDevice() ); } ln_foreach( DepthBuffer* t, mDepthBufferList ) { LN_CALL_R( t->onResetDevice() ); } ln_foreach( RenderTargetTexture* t, mRenderTargetList ) { LN_CALL_R( t->onResetDevice() ); } ln_foreach( CanvasBase* t, mCanvasList ) { LN_CALL_R( t->onResetDevice() ); } // ビューポートサイズのリセットにバックバッファサイズを使っているため、 // デフォルトキャンバスの onResetDevice() の後でないと // バックバッファサイズが古いままになってしまう LN_CALL_R( mRenderer->onResetDevice() ); // TODO リセット後コールバック呼び出し LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; #endif LN_PRINT_NOT_IMPL_FUNCTION; return LN_OK; } //---------------------------------------------------------------------- // //---------------------------------------------------------------------- void GraphicsDevice::setCurrentShaderrPass( ShaderPass* pass_ ) { if ( pass_ != mCurrentShaderrPass ) { LN_SAFE_RELEASE( mCurrentShaderrPass ); mCurrentShaderrPass = pass_; LN_SAFE_ADDREF( mCurrentShaderrPass ); } } //------------------------------------------------------------------------- // //------------------------------------------------------------------------- } // namespace OpenGL } // namespace Graphics } // namespace Core } // namespace LNote #endif //============================================================================== // //==============================================================================
[ "ilys.vianote@gmail.com" ]
ilys.vianote@gmail.com
b63740369b35ceb0ba100be594e7cc91082b4a7e
c45640ae914bbd5cdf3fa9cb5ade63220504166d
/プログラム/超字言 コトバトル v0.02/tutorial.cpp
16f722de9423363103d26b695f29b0be192d6b05
[]
no_license
MikiyaMeguro/TEAM_B_OPEN
59d014869129b83a0d3bf16e36dbbfc94299421e
1da9614dbe2d3f25d6ea371fe92ebffb33138f13
refs/heads/master
2020-08-09T16:53:22.002796
2020-02-06T01:13:48
2020-02-06T01:13:48
214,123,538
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,846
cpp
//============================================================================= // // チュートリアル処理 [tutorial.cpp] // Author : 目黒 未来也 // //============================================================================= #include "tutorial.h" #include "manager.h" #include "light.h" #include "camera.h" #include "scene3D.h" #include "game.h" #include "debugProc.h" #include "scene.h" #include "fade.h" #include "input.h" #include "InputKeyboard.h" #include <time.h> //============================================================================ // マクロ定義 //============================================================================ #define SIZE_X (SCREEN_WIDTH) #define SIZE_Y (SCREEN_HEIGHT) #define COLISIONSIZE (20.0f) #define TIME_INI (60) //============================================================================ //静的メンバ変数宣言 //============================================================================ //============================================================================= // コンストラクタ //============================================================================= CTutorial::CTutorial() { } //============================================================================= //デストラクタ //============================================================================= CTutorial::~CTutorial() { } //============================================================================= // ポリゴンの初期化処理 //============================================================================= void CTutorial::Init(void) { //インスタンス CManager *pManager = NULL; } //============================================================================= // ポリゴンの終了処理 //============================================================================= void CTutorial::Uninit(void) { //全ての終了処理 CScene::ReleseAll(); } //============================================================================= // ポリゴンの更新処理 //============================================================================= void CTutorial::Update(void) { CManager *pManager = NULL; CFade *pFade = pManager->GetFade(); // 入力情報を取得 CInputKeyboard *pInputKeyboard; pInputKeyboard = CManager::GetInputKeyboard(); // ランダムな値を更新 srand((unsigned int)time(NULL)); //任意のキーENTER if (pInputKeyboard->GetTrigger(DIK_RETURN) == true) { pFade->SetFade(pManager->MODE_CHARASELECT, pFade->FADE_OUT); } #ifdef _DEBUG CDebugProc::Print("c", "チュートリアル"); #endif } //============================================================================= // ポリゴンの描画処理 //============================================================================= void CTutorial::Draw(void) { }
[ "jb2017013@stu.yoshida-g.ac.jp" ]
jb2017013@stu.yoshida-g.ac.jp
a362dc7ae5b051998b24fdae07c27dcafabd6a7e
7c0102503b74c335d6c1550d72c55911bc9c42fe
/GreekVocab/shifts.h
30fdb236b19053f339a1adea2aff5087cf4cabf1
[]
no_license
barkis/GreekStudy
b4daec8332bf5c19a8eebcdb1b59ecaba8a0f3e6
e7ff8bfebb65bdabfa36ad5427ab98441915fa57
refs/heads/master
2021-09-16T03:29:00.718761
2021-08-30T12:01:18
2021-08-30T12:01:18
172,256,179
0
0
null
null
null
null
UTF-8
C++
false
false
770
h
#ifndef SHIFTS #define SHIFTS class Shifts { public: enum enumShifts{NONE=0,SHIFT=1,IOTA=2,SMOOTH=4,ROUGH=8,ALT=16}; <<<<<<< HEAD Shifts(enumShifts publicVal){value = publicVal;} ======= Shifts(enumShifts publicVal) : value(publicVal) {} >>>>>>> 5d9b66c7416741a99b4502d6239cf43436640dd0 short operator()(){return value;} Shifts operator +(Shifts right){value += right.value;return *this;} Shifts operator +=(Shifts right){value += right.value;return *this;} Shifts operator +(enumShifts right){value += right;return *this;} Shifts operator +=(enumShifts right){value += right;return *this;} bool operator ==(Shifts right){return (value == right.value);} bool operator ==(enumShifts right){return (value == right);} private: short value; Shifts(){} }; #endif
[ "mleddy18a@yahoo.co.uk" ]
mleddy18a@yahoo.co.uk
2375cf7c22f544565ed4c61b60252ac541337a9b
ab1712d65f8510a705a1f28064e4d3fc5a48cf64
/SDK/SoT_BP_gmp_pocket_watch_hwm_01_a_ItemDesc_classes.hpp
80c8f6356ad450dd75f09919931ed8c90af03b29
[]
no_license
zk2013/SoT-SDK
577f4e26ba969c3fa21a9191a210afc116a11dba
04eb22c1c31aaa4d5cf822b0a816786c99e3ea2f
refs/heads/master
2020-05-29T20:06:57.165354
2019-05-29T16:46:51
2019-05-29T16:46:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
813
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_gmp_pocket_watch_hwm_01_a_ItemDesc_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_gmp_pocket_watch_hwm_01_a_ItemDesc.BP_gmp_pocket_watch_hwm_01_a_ItemDesc_C // 0x0000 (0x0120 - 0x0120) class UBP_gmp_pocket_watch_hwm_01_a_ItemDesc_C : public UItemDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_gmp_pocket_watch_hwm_01_a_ItemDesc.BP_gmp_pocket_watch_hwm_01_a_ItemDesc_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "igromanru@yahoo.de" ]
igromanru@yahoo.de
db2ef8d9d2f013d9ed540b2bfb01bd2a312fb0dc
d04cea555772a36e492c1cce5ff7fcedaa9c6af6
/src/remotedebug/bee/rdebug_thread.cpp
dcdb8da5c478b2c41c20619441f4710be452268f
[ "MIT" ]
permissive
sumneko/lua-debug
dc9b063f2da4603578d9058c688962fc5ef8b96f
d3c8f8d74ea5142daf27428a5cd07f9886d3fbf7
refs/heads/master
2021-05-18T13:02:12.588751
2020-03-25T03:03:47
2020-03-25T03:03:47
251,253,148
0
0
MIT
2020-03-30T09:02:42
2020-03-30T09:02:41
null
UTF-8
C++
false
false
171
cpp
#define RLUA_REPLACE #include "../rlua.h" #include <binding/lua_thread.cpp> RLUA_FUNC int luaopen_remotedebug_thread(rlua_State* L) { return luaopen_bee_thread(L); }
[ "actboy168@gmail.com" ]
actboy168@gmail.com
56af8fc99639ca2a5fc96e2eb528040acbbb86a6
41dc3e18de7d1f31e1ccbbe676d6326210045588
/cpp_primer/chap3/ex3.41.cc
ecad202a1a6c375463cb51ac7453800239d86962
[]
no_license
axiomiety/crashburn
372dcfad57a078e4caf7b22d7ae6038162cf4ffb
eff78ed020c1ce309b7cf6e53dd613e7d9f259ef
refs/heads/master
2023-09-01T00:53:08.969794
2023-08-30T11:23:32
2023-08-30T11:23:32
7,456,861
3
1
null
2023-02-11T10:44:01
2013-01-05T15:39:22
Jupyter Notebook
UTF-8
C++
false
false
321
cc
#include <iostream> #include <string> #include <vector> using std::cin; using std::cout; using std::endl; using std::begin; using std::end; using std::vector; int main() { int arr[] = {1,2,3,4,5,6,7,8,9,0}; vector<int> ivec(begin(arr),end(arr)); for (auto i : ivec) cout << i << endl; return 0; }
[ "axiomiety@gmail.com" ]
axiomiety@gmail.com
c17c738f0a52c5f936c034f1f755cb22eee7d692
7a3caf3cfe6f3dbda6e1233c9299bb47df783c07
/Testing/Source/Common/Cxx/TestByteSwap.cxx
3594be993e4e543c8d1a995190af7fb11998158a
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
jordiromera/GDCM
b12bdf1068a011426a07fa4171300c2b07422269
f301a3d22097c82e70afe404e92a7d29d1e454ca
refs/heads/master
2021-01-18T09:45:50.359590
2011-10-12T14:09:45
2011-10-12T14:09:45
1,603,333
2
0
null
null
null
null
UTF-8
C++
false
false
3,589
cxx
/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "gdcmTypes.h" #include "gdcmSwapCode.h" #include "gdcmByteSwap.h" #include <string.h> // memcpy int myfunc() { char vl_str[4]; const char raw[] = "\000\000\000\004"; memcpy(vl_str, raw, 4); uint32_t vl; gdcm::ByteSwap<uint32_t>::SwapRangeFromSwapCodeIntoSystem((uint32_t*)(&vl_str), gdcm::SwapCode::BigEndian, 1); memcpy(&vl, vl_str, 4); if( vl != 0x00000004 ) { std::cerr << std::hex << "vl: " << vl << std::endl; return 1; } gdcm::ByteSwap<uint32_t>::SwapFromSwapCodeIntoSystem(vl, gdcm::SwapCode::LittleEndian); if( vl != 0x00000004 ) { std::cerr << std::hex << "vl: " << vl << std::endl; return 1; } gdcm::ByteSwap<uint32_t>::SwapFromSwapCodeIntoSystem(vl, gdcm::SwapCode::BigEndian); std::cout << std::hex << "vl: " << vl << std::endl; if( vl != 0x4000000 ) { return 1; } return 0; } int TestByteSwap(int , char *[]) { gdcm::SwapCode sc = gdcm::SwapCode::Unknown; if ( gdcm::ByteSwap<uint16_t>::SystemIsBigEndian() ) { sc = gdcm::SwapCode::BigEndian; } else if ( gdcm::ByteSwap<uint16_t>::SystemIsLittleEndian() ) { sc = gdcm::SwapCode::LittleEndian; } if( sc == gdcm::SwapCode::Unknown ) { return 1; } std::cout << "sc: " << sc << std::endl; uint16_t t = 0x1234; gdcm::ByteSwap<uint16_t>::SwapFromSwapCodeIntoSystem(t, sc); if( sc == gdcm::SwapCode::BigEndian ) { if( t != 0x3412 ) { std::cerr << std::hex << "t: " << t << std::endl; return 1; } // ok test pass rest value to old one t = 0x1234; } else if ( sc == gdcm::SwapCode::LittleEndian ) { if( t != 0x1234 ) { std::cerr << std::hex << "t: " << t << std::endl; return 1; } } char n[2]; memcpy(n, &t, 2 ); gdcm::ByteSwap<uint16_t>::SwapRangeFromSwapCodeIntoSystem((uint16_t*)n, sc, 1); uint16_t tn = *((uint16_t*)n); if( sc == gdcm::SwapCode::BigEndian ) { if( tn != 0x3412 ) { std::cerr << std::hex << "tn: " << tn << std::endl; return 1; } // ok test pass rest value to old one t = 0x1234; } else if ( sc == gdcm::SwapCode::LittleEndian ) { if( tn != 0x1234 ) { std::cerr << std::hex << "tn: " << tn << std::endl; return 1; } } gdcm::ByteSwap<uint16_t>::SwapRangeFromSwapCodeIntoSystem((uint16_t*)n, gdcm::SwapCode::BigEndian, 1); tn = *((uint16_t*)n); if( sc == gdcm::SwapCode::LittleEndian ) { if( tn != 0x3412 ) { std::cerr << std::hex << "tn: " << tn << std::endl; return 1; } } else if ( sc == gdcm::SwapCode::BigEndian ) { if( tn != 0x1234 ) { std::cerr << std::hex << "tn: " << tn << std::endl; return 1; } } if( myfunc() ) { return 1; } uint16_t array[] = { 0x1234 }; gdcm::ByteSwap<uint16_t>::SwapRangeFromSwapCodeIntoSystem(array, gdcm::SwapCode::BigEndian,2); if ( array[0] != 0x3412 ) { return 1; } return 0; }
[ "mathieu.malaterre@gmail.com" ]
mathieu.malaterre@gmail.com
dfc4ef7039a5dc5402d6cf12de2348234a973dff
153c8aae78729e81b83b3e9dca1b8a91253cfd3c
/abc/a/064_RGBCards.cpp
6a02005bc0a52e52b085c96bf95b38f8b462c8f2
[]
no_license
High-Hill/atcoder_past
d1b985a91ff7fe1318ed69ac10e0999c318b77b8
d41a54cf80d4c30699417241394e51a837fb4ae7
refs/heads/master
2020-04-24T19:13:44.085060
2019-06-02T15:20:38
2019-06-02T15:20:38
172,205,302
2
0
null
null
null
null
UTF-8
C++
false
false
229
cpp
#include<iostream> using namespace std; int main(){ int r, g, b; cin >> r >> g >> b; int judge = (r * 100) + (g * 10) + b; if(judge % 4 == 0) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
[ "k196336@kansai-u.ac.jp" ]
k196336@kansai-u.ac.jp
2c400727547e4e397522b00d2011a8db88f5a8d8
cf16911bc92458e31c8accb95f2062dcdea75ff2
/SoC-Validation/firmware/AV417/standalone_codecs/MPEG-4_ENCODER/ARCEncoder/MPEG4/MP4OffsetTables.cpp
76b427d23a10be4c8ea5952b4ec77de8b934d7ed
[]
no_license
alexvatti/embedded-documents
b4f7a789f66dad592a655677788da4003df29082
5bcf34328a4f19c514c1bca12ad52dcc06e60f09
refs/heads/master
2023-08-14T20:23:00.180050
2019-11-29T10:48:05
2019-11-29T10:48:05
224,813,397
0
0
null
null
null
null
UTF-8
C++
false
false
4,899
cpp
/* CONFIDENTIAL AND PROPRIETARY INFORMATION */ /* Copyright 2007 ARC International (Unpublished) */ /* All Rights Reserved. */ /* */ /* This document, material and/or software contains confidential */ /* and proprietary information of ARC International and is */ /* protected by copyright, trade secret and other state, federal, */ /* and international laws, and may be embodied in patents issued */ /* or pending. Its receipt or possession does not convey any */ /* rights to use, reproduce, disclose its contents, or to */ /* manufacture, or sell anything it may describe. Reverse */ /* engineering is prohibited, and reproduction, disclosure or use */ /* without specific written authorization of ARC International is */ /* strictly forbidden. ARC and the ARC logotype are trademarks of */ /* ARC International. */ /* */ /* May contain code (c) British Telecommunications plc 2005 */ #include "ArcEEOffsetTables.h" // JRMM all these arrays are not relevant to mpeg4/h263, but are needed to compile the ArcEntropyEncoderModel.cpp /* ------------------------------------------------------------------------ */ /* NAME: top_left_of_luma_4x4_block_bitstream_order_table */ /* DESCRIPTION: The table for converting a luma block number into an offset into a 16x16 block giving the position of the top left pel of the 4x4 block when blocks are numbered in the order of residual coding: 0 1 4 5 2 3 6 7 8 9 12 13 10 11 14 15 */ /* ------------------------------------------------------------------------ */ const unsigned char top_left_of_luma_4x4_block_bitstream_order_table[16] = { 0, 4, 64, 68, 8, 12, 72, 76, 128, 132, 192, 196, 136, 140, 200, 204}; /* ------------------------------------------------------------------------ */ /* NAME: top_left_of_luma_4x4_block_raster_order_table */ /* DESCRIPTION: The table for converting a luma block number into an offset into a 16x16 block giving the position of the top left pel of the 4x4 block. */ /* ------------------------------------------------------------------------ */ const unsigned char top_left_of_luma_4x4_block_raster_order_table[16] = { 0, 4, 8, 12, 64, 68, 72, 76, 128, 132, 136, 140, 192, 196, 200, 204}; /* ------------------------------------------------------------------------ */ /* NAME: top_left_of_chroma_4x4_block_table */ /* DESCRIPTION: The table for converting a cheoma block number into an offset into a 8x8 block giving the position of the top left pel of the 4x4 block. */ /* ------------------------------------------------------------------------ */ const UNSIGNED_SEPTET top_left_of_chroma_4x4_block_table[4] = { 0, 4, 32, 36}; /* ------------------------------------------------------------------------ */ /* NAME: frame_mb_zig_zag_luma_dc_table */ /* DESCRIPTION: The scan table for converting total run into pel position for a 4x4 block within a 4x4 (dc luma) frame block. */ /*- ------------------------------------------------------------------------ */ const UNSIGNED_SEPTET frame_mb_zig_zag_luma_dc_table[16] = { 0 + 0, 0 + 1, 4 + 0, 8 + 0, 4 + 1, 0 + 2, 0 + 3, 4 + 2, 8 + 1, 12 + 0, 12 + 1, 8 + 2, 4 + 3, 8 + 3, 12 + 2, 12 + 3 }; /* ------------------------------------------------------------------------ */ /* NAME: frame_mb_zig_zag_luma_table */ /* DESCRIPTION: The scan table for converting total run into pel position for a 4x4 block within a 16x16 (luma) field macroblock. */ /* ------------------------------------------------------------------------ */ const UNSIGNED_SEPTET frame_mb_zig_zag_luma_table[16] = { 0 + 0, 0 + 1, 16 + 0, 32 + 0, 16 + 1, 0 + 2, 0 + 3, 16 + 2, 32 + 1, 48 + 0, 48 + 1, 32 + 2, 16 + 3, 32 + 3, 48 + 2, 48 + 3 }; /* ------------------------------------------------------------------------ */ /* NAME: frame_mb_zig_zag_chroma_table */ /* DESCRIPTION: The scan table for converting total run into pel position for a 4x4 block within an 8x8 (chroma) frame macroblock. */ /* ------------------------------------------------------------------------ */ const UNSIGNED_SEPTET frame_mb_zig_zag_chroma_table[16] = { 0 + 0, 0 + 1, 8 + 0, 16 + 0, 8 + 1, 0 + 2, 0 + 3, 8 + 2, 16 + 1, 24 + 0, 24 + 1, 16 + 2, 8 + 3, 16 + 3, 24 + 2, 24 + 3 }; /* ------------------------------------------------------------------------ */ /* END OF FILE */ /* ------------------------------------------------------------------------ */
[ "alexvatti@gmail.com" ]
alexvatti@gmail.com
b22e857b16e432d7213dadc981882b280dc60c90
bf4258ce48c2b04c8709c7cc5508782fc73dcca2
/Brick.cpp
0fa871b37f2dee88c5269084ffeef240bbf79081
[]
no_license
ioanamoraru14/brick_game
74232e6dab76a0f27e289426cfb3b5c763798aa2
1e8de0aba9951dd7e2ae16df0b8a976319348dc6
refs/heads/master
2020-04-04T12:31:28.584544
2018-11-06T13:20:51
2018-11-06T13:20:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
266
cpp
#include "Brick.h" const float Brick::WIDTH = 0.2f; const float Brick::HEIGHT = 0.15f; Brick::Brick() { } Brick::Brick(float pos_x, float pos_y) { x = pos_x; y = pos_y; visible = 10; } void Brick::DecreaseVisibility() { visible -= 1; } Brick::~Brick() { }
[ "ioanamoraru14@gmail.com" ]
ioanamoraru14@gmail.com
e61bfc314f320ea6dc4d9d81964f06a6904a0ace
0a1b9a852cd9f8b15699214cd59b2ea4d9ef229d
/R/BayesianBInomialExample/mcmc_standalone.cpp
be6ba671dd192ed022699442097b9a7f76d3b5e8
[]
no_license
LizContreras/estadisticaComputacional2016
b7a2a1fb471279198696b01be1fc08cfc10d34a3
570f0d30f22ad8a810f01e177a4d75274db24cdf
refs/heads/master
2021-01-13T09:37:37.613900
2016-11-10T03:00:23
2016-11-10T03:00:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,182
cpp
#include <Rcpp.h> using namespace Rcpp; #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] double loglikelihood(double theta, NumericVector toss) { double sumx = sum(toss); int n = toss.size(); return sumx*log(theta) + (n-sumx)*log(1-theta); } // [[Rcpp::export]] double logprior(double theta, double shape1, double shape2) { return (shape1-1)*log(theta) + (shape2-1)*log(1-theta); } double logposterior(double theta, NumericVector toss, double shape1, double shape2) { return loglikelihood(theta, toss) + logprior(theta, shape1, shape2); } // [[Rcpp::export]] NumericVector run_mcmc( NumericVector toss, int n_sim, double theta_0, double jump_size = .5, double shape1=-.5, double shape2=-.5) { // NumericVector sim(n_sim); double U, eta; bool test; // sim[0] = theta_0; for (int i=0; i < n_sim; i++) { U = (runif(1))[0]; do { eta = (rnorm(sim[i], jump_size))[0]; test = log(U) > logposterior(eta, toss, shape1, shape2) - logposterior(sim[i], toss, shape1, shape2); } while (test); sim[i + 1] = eta; } return sim; } /*** R timesTwo(42) */
[ "mauriciogtec@gmail.com" ]
mauriciogtec@gmail.com
2fa86323743e7c76f5aae285bd8ad771b1858a74
ace933c48d2c58f22d0de09b6caec600d31c4631
/Engine/src/core/comp/PhysicsComponent.cpp
49078489b67855d031e503c83ba2e28c97366e47
[]
no_license
Richard-Murray/Engine
d144229a2210ba03cfd5c82a7e9ac54ee40d0a48
104ba5ef61c8e7e936f83b65dfba999ae0d4ee8b
refs/heads/master
2021-01-19T07:37:26.587624
2015-08-13T02:16:06
2015-08-13T02:16:06
37,700,895
0
0
null
null
null
null
UTF-8
C++
false
false
2,025
cpp
#include "PhysicsComponent.h" PhysicsComponent::~PhysicsComponent() { } void PhysicsComponent::Initialise() { SetComponentType("Physics"); m_physicsTransform = m_parent->GetWorldTransform(); m_position = m_parent->GetWorldTransform()[3].xyz; m_velocity = glm::vec3(0); m_rotation = glm::vec3(0, 1, 0); m_drag = 0.99f; } void PhysicsComponent::SetStatic(bool boolStatic) { m_static = boolStatic; } void PhysicsComponent::Update(float deltaTime) { if (!m_static) { m_velocity += glm::vec3(0, -10, 0) * deltaTime; m_velocity *= m_drag; m_position += m_velocity * deltaTime; } else { m_velocity = glm::vec3(0); } m_physicsTransform[3].xyz = m_position; //m_physicsTransform = glm::rotate(m_physicsTransform, ); m_parent->SetWorldTransform(m_physicsTransform); //glm::mat4 rotMatrix = <calculate rotation matrix based on angular velocity> //m_parent->SetWorldTransform(m_physicsTransform); //m_parent->SetWorldTranslation(m_parent->GetWorldTransform()[3].xyz + glm::vec3(0, -0.1f, 0)); } void PhysicsComponent::SetSphere(float mass, float radius) { m_objectType = PHYSICSOBJECT::SPHERE; m_mass = mass; m_radius = radius; m_rotation = glm::vec3(0, 1, 0); } void PhysicsComponent::SetPlane(glm::vec3 normal, float distance) { m_objectType = PHYSICSOBJECT::PLANE; m_normal = normal; m_distance = distance; } void PhysicsComponent::SetAABB(float mass, glm::vec3 boxGeometry) { m_objectType = PHYSICSOBJECT::AABB; m_mass = mass; m_boxGeometry = boxGeometry; } void PhysicsComponent::SetBox(float mass, glm::vec3 boxGeometry, glm::vec3 rotation) { m_objectType = PHYSICSOBJECT::BOX; m_mass = mass; m_boxGeometry = boxGeometry; m_rotation = rotation; } PHYSICSOBJECT PhysicsComponent::GetObjectType() { return m_objectType; } void PhysicsComponent::ApplyForce(glm::vec3 force) { m_velocity += force / m_mass; } void PhysicsComponent::SetPosition(glm::vec3 position) { m_position = position; } void PhysicsComponent::SetVelocity(glm::vec3 velocity) { m_velocity = velocity; }
[ "arraygear2@gmail.com" ]
arraygear2@gmail.com
88c125c19f073168d8765f4d387321dd7ef6bf12
0e07bab87fb927c5a619559c5f82380ee6e2a16c
/Pairs.cpp
2078435f42f4e356ef648074b1b5ed983d62af52
[]
no_license
abuba8/Algorithms
1addf26f41e0f4fadb5a100b31e1d1251fedd403
7a8171cce9bf157c90259c81b320ac2b20f0dbd1
refs/heads/master
2021-07-02T05:48:28.596135
2020-10-12T18:32:03
2020-10-12T18:32:03
182,567,600
0
0
null
null
null
null
UTF-8
C++
false
false
398
cpp
#include <bits/stdc++.h> using namespace std; int main(){ int n,k; cin>>n>>k; int *arr; arr=new int [n]; for(int i=0;i<n;i++){ cin>>arr[i]; } int i=0,j=1,count=0,diff; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if((arr[j]-arr[i])==k ) count++; } } cout<<count; return 0; }
[ "abuba8@gmail.com" ]
abuba8@gmail.com
bac3a202b11276ff11c14a7478529e7f39122af6
00dbe4fd5f00fab51f959fdf32ddb185daa8de30
/P902.cpp
e5cd9c3f42c472d695b728d1dc409ca8f3c3f3cc
[]
no_license
LasseD/uva
c02b21c37700bd6f43ec91e788b2787152bfb09b
14b62742d3dfd8fb55948b2682458aae676e7c14
refs/heads/master
2023-01-29T14:51:42.426459
2023-01-15T09:29:47
2023-01-15T09:29:47
17,707,082
3
4
null
null
null
null
UTF-8
C++
false
false
1,083
cpp
/* 26 characters => 5 bit. */ string tos(int N, ULL best) { char cc[11]; FORI(N) { cc[N-i-1] = (char)('a'+(best & 31)); best >>= 5; } cc[N] = '\0'; return string(cc); } int main() { string s; int N; while(cin >> N >> s) { if(N > (int)s.size()) die(); // Not possible. Doesn't make sense. map<ULL,int> m; ULL curr = 0; ULL mask = 0; FORI(N) { curr = (curr << 5) + (s[i]-'a'); mask = (mask << 5) + 31; // Fill with 1's. } m.insert(make_pair(curr, 1)); ULL best = curr; int bestCnt = 1; //cerr << "Init: " << tos(N, curr) << ": " << curr << endl; for(int i = N; i < (int)s.size(); ++i) { curr = mask & ((curr << 5) + (s[i]-'a')); //cerr << " " << i << ": " << tos(N, curr) << ": " << curr << endl; map<ULL,int>::iterator it = m.find(curr); if(it == m.end()) { m.insert(make_pair(curr, 1)); } else { ++it->second; if(it->second > bestCnt) { bestCnt = it->second; best = curr; } } } cout << tos(N, best) << endl; } return 0; }
[ "lassedeleuran@gmail.com" ]
lassedeleuran@gmail.com
c287057c3d1b95f02a017f8ef4d906e305c04e87
3bfcaa96616785fcd1f44770a41d0b1b3617514e
/lab4_oop/lab4_oop_brovdiy/Book.cpp
f0b86d716f0f2be79f999565589cf80cc4e9276f
[]
no_license
ievgeniibrovdii/oop_labs
5125b410534fe621fe306ee662b3ecea9e2ac095
f29787d89d7f09465a67c13c7e3c04b6dc30b15a
refs/heads/master
2020-05-26T22:53:33.940378
2019-05-24T10:45:14
2019-05-24T10:45:14
188,404,769
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
cpp
#include <iostream> #include <conio.h> #include "BinTreeBook.h" using namespace std; int main() { CBinTree book; CTreeNode* rs; int available; cout << " Read from csv to the tree: \n"; printf("|-----------------------------------------------------|\n"); book.read_csv("Book.csv"); book.Print_the_Tree(UP); cout << endl << " Delete book: \n"; printf("|-----------------------------------------------------|\n"); book.DelNode(7); book.Print_the_Tree(UP); cout << "\n Add book :\n"; printf("|-----------------------------------------------------|\n"); book.add_book("12;Consuello;GeorgeSand;1842;19"); book.Print_the_Tree(UP); cout << "\n Availability book: \n"; printf("|-----------------------------------------------------|\n"); available = book.availability_book("Consuello"); printf("Books available: %d \n", available); cout << "\n\n Get Author's books :\n"; printf("|-----------------------------------------------------|\n"); rs = book.get_authors_books("Bulgakov"); book.print_author_books_set(rs); free(rs); _getch(); return 0; }
[ "ievgeniibrovdii@gmail.com" ]
ievgeniibrovdii@gmail.com
52843a68404bf7690fb4e9f424be817c1665f5fa
485c3c27c834d93abbb5b8c840a2a03092d30f8a
/GUI/ConfigParser.h
4ff7617b8d0261550e30ebd244e4ba9eb2cb042a
[]
no_license
Teanan/GameBase
79958e031eb5ae74a4b35d2dfbac6c7a78681da0
9ac2e7951e9e8291dfd7296a92300dcd5accc1c3
refs/heads/master
2020-05-20T07:20:36.999649
2013-08-23T16:05:43
2013-08-23T16:05:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
824
h
#ifndef GUICONFIGPARSER_H_INCLUDED #define GUICONFIGPARSER_H_INCLUDED #include "../../libs/yaml-cpp/include/yaml-cpp/yaml.h" class GraphicsManager; class Widget; class TextWidget; class Button; class ImageWidget; class Label; class Textbox; class GuiConfigParser { public: static void import(Button*, const YAML::Node&, GraphicsManager* graphics); static void import(ImageWidget*, const YAML::Node&, GraphicsManager* graphics); static void import(Label*, const YAML::Node&, GraphicsManager* graphics); static void import(Textbox*, const YAML::Node&, GraphicsManager* graphics); private: static void importGlobal(Widget*, const YAML::Node&, GraphicsManager* graphics); static void importTextWidget(TextWidget*, const YAML::Node&, GraphicsManager* graphics); }; #endif // GUICONFIGPARSER_H_INCLUDED
[ "gamer.toms@gmail.com" ]
gamer.toms@gmail.com
6b75c71b3aeb423a5b4571351aa41f2650a84d8c
639f7fe78a2f685ac1b20cf237ecf97a5065207f
/ParticleSystem.h
20bf789494cde72ed757f3b90f13bc4cb2ce4048
[]
no_license
fransicko/GraphicsFP
3ae59b5912d10df3dbd4d2d3a2bb82f168e4e65a
242765c4331b9d2d334746b1c91b45be32750011
refs/heads/master
2021-08-29T11:51:48.289263
2017-12-13T21:51:25
2017-12-13T21:51:25
113,475,587
0
0
null
null
null
null
UTF-8
C++
false
false
504
h
#pragma once #include "Particle.h" #include <cstdlib> #include <vector> class ParticleSystem { public: std::vector<Particle> particles; Vertex startingLoc; float minLife; float maxLife; float spawn; float minV; float maxV; float coneAngle; double start; double updateStart; void draw(glm::vec3 lookAtPoint, glm::vec3 suzPoint, Vertex points[], GLint bbsize, GLint particleHandle, GLuint pointsVAO, GLuint pointsVBO); void update(); void add(); };
[ "kduong@mymail.mines.edu" ]
kduong@mymail.mines.edu
70f901f5a567e790e07e57d351a7d7282eb093af
cf9d7a083b91378aee2c54ef63011536108d6552
/chapter_03/04_TicTacToeBoard/TicTacToeBoard.cpp
84454ec503d06bd1313a2ffb407a62127bcc4237
[]
no_license
AselK/Beginning-cpp-through-game-programming
3a86f70c8cb99480dafce68c2b7865d9e68e652d
adb9f762a942be66ba58607f93478f5da9d5441f
refs/heads/master
2021-05-05T13:10:45.143894
2018-05-29T21:02:02
2018-05-29T21:02:02
118,325,807
0
0
null
null
null
null
UTF-8
C++
false
false
672
cpp
#include <iostream> int main() { const int ROWS = 3; const int COLUMNS = 3; char board[ROWS][COLUMNS] = { {'0', 'X', '0'}, {' ', 'X', 'X'}, {'X', '0', '0'} }; std::cout << "Here's the tic - tac - toe board:\n"; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; ++j) { std::cout << board[i][j]; } std::cout << std::endl; } std::cout << "\n'X' moves to the empty location.\n\n"; board[1][0] = 'X'; std::cout << "Now the tic - tac - toe board is:\n"; for (int i = 0; i < ROWS; ++i) { for (int j = 0; j < COLUMNS; ++j) { std::cout << board[i][j]; } std::cout << std::endl; } std::cout << "\n'X' wins!"; }
[ "asel.nurmuhanbetova@gmail.com" ]
asel.nurmuhanbetova@gmail.com
076721f8add1d124636ec9c8b61458ab08532df2
fbdc3d93c4e888843f35c86fcbd0080491da83bb
/loadgen/logging.h
87802dbe7c081d32a0f170551c64ede4b15904ac
[ "Apache-2.0" ]
permissive
srivera1/inference
508a8f20c9c53dcae247b9d237fc6cb9a2f54587
c50ded815949b66ae6b31de27dc82426a294a06e
refs/heads/master
2020-05-16T20:45:30.646686
2019-04-24T17:15:04
2019-04-24T17:15:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,262
h
#ifndef MLPERF_LOADGEN_LOGGING_H_ #define MLPERF_LOADGEN_LOGGING_H_ #include <algorithm> #include <atomic> #include <cassert> #include <condition_variable> #include <chrono> #include <functional> #include <future> #include <list> #include <ostream> #include <mutex> #include <thread> #include <set> #include <vector> #include <unordered_set> namespace mlperf { class AsyncLog; class Logger; class TlsLogger; using AsyncLogEntry = std::function<void(AsyncLog&)>; using PerfClock = std::chrono::high_resolution_clock; // AsyncTrace is passed as an argument to the custom log lambda on the // recording thread to serialize the data captured by the lambda and // forward it to the output stream. class AsyncLog { public: AsyncLog(std::ostream *out_stream) : out_stream_(*out_stream) {} template <typename ...Args> void FullEvent(const std::string& trace_name, uint64_t ts, uint64_t dur, const Args... args) { out_stream_ << "{ \"name\": \"" << trace_name << "\", "; out_stream_ << "\"ph\": \"X\", "; out_stream_ << "\"pid\": 0, "; // TODO out_stream_ << "\"tid\": 0, "; // TODO out_stream_ << "\"ts\": " << ts << ", "; out_stream_ << "\"dur\": " << dur << ", "; out_stream_ << "\"args\": { "; LogArgs(args...); out_stream_ << " }},\n"; out_stream_.flush(); } template <typename ...Args> void AsyncEvent(const std::string& trace_name, uint64_t id, uint64_t ts, uint64_t dur, const Args... args) { out_stream_ << "{\"name\": \"" << trace_name << "\", "; out_stream_ << "\"cat\": \"default\", "; out_stream_ << "\"ph\": \"b\", "; out_stream_ << "\"id\": " << id << ", "; out_stream_ << "\"pid\": 0, "; // TODO out_stream_ << "\"tid\": 0, "; // TODO //out_stream_ << "\"ts\": " << ts << " },\n"; out_stream_ << "\"ts\": " << ts << ", "; out_stream_ << "\"args\": { "; LogArgs(args...); out_stream_ << " }},\n"; out_stream_ << "{ \"name\": \"" << trace_name << "\", "; out_stream_ << "\"cat\": \"default\", "; out_stream_ << "\"ph\": \"e\", "; out_stream_ << "\"id\": " << id << ", "; out_stream_ << "\"pid\": 0, "; // TODO out_stream_ << "\"tid\": 0, "; // TODO out_stream_ << "\"ts\": " << ts + dur << " },\n"; out_stream_.flush(); // The trace duration currently corresponds to response latency. // Trace id corresponds to the sample sequence id. std::unique_lock<std::mutex> lock(latencies_mutex_); if (latencies_.size() < id + 1) { latencies_.resize(id + 1, std::chrono::nanoseconds(0)); } latencies_[id] = std::chrono::nanoseconds(dur); latencies_recorded_++; if (AllLatenciesRecorded()) { all_latencies_recorded_.notify_all(); } } void RestartLatencyRecording() { std::unique_lock<std::mutex> lock(latencies_mutex_); assert(latencies_.empty()); assert(latencies_recorded_ == latencies_expected_); latencies_recorded_ = 0; latencies_expected_ = 0; } std::vector<std::chrono::nanoseconds> GetLatenciesBlocking( size_t expected_count) { std::vector<std::chrono::nanoseconds> latencies; std::unique_lock<std::mutex> lock(latencies_mutex_); latencies_expected_ = expected_count; all_latencies_recorded_.wait(lock, [&]{ return AllLatenciesRecorded(); }); latencies.swap(latencies_); return latencies; } private: void LogArgs() {} template <typename T> void LogArgs(const std::string& arg_name, const T &arg_value) { out_stream_ << "\"" << arg_name << "\" : " << arg_value; } template <typename T, typename ...Args> void LogArgs(const std::string& arg_name, const T& arg_value, const Args... args) { out_stream_ << "\"" << arg_name << "\" : " << arg_value << ", "; LogArgs(args...); } std::ostream &out_stream_; std::mutex latencies_mutex_; std::condition_variable all_latencies_recorded_; std::vector<std::chrono::nanoseconds> latencies_; size_t latencies_recorded_ = 0; size_t latencies_expected_ = 0; bool AllLatenciesRecorded() { return latencies_recorded_ == latencies_expected_; } }; // Logs all threads belonging to a run. class Logger { public: Logger(std::ostream *out_stream, std::chrono::duration<double> poll_period, size_t max_threads_to_log); ~Logger(); void RequestSwapBuffers(TlsLogger* tls_logger); PerfClock::time_point origin_time() { return origin_time_; } void RegisterTlsLogger(TlsLogger* tls_logger); void UnRegisterTlsLogger(TlsLogger* tls_logger); void RestartLatencyRecording(); std::vector<std::chrono::nanoseconds> GetLatenciesBlocking( size_t expected_count); private: TlsLogger* GetTlsLoggerThatRequestedSwap(size_t slot, size_t next_id); void GatherRetrySwapRequests(std::vector<TlsLogger*>* threads_to_swap); void GatherNewSwapRequests(std::vector<TlsLogger*>* threads_to_swap); // The main logging thread function that handles the serialization // and I/O to the stream or file. void IOThread(); std::ostream &out_stream_; const size_t max_threads_to_log_; std::thread io_thread_; const PerfClock::time_point origin_time_; // Accessed by IOThead only. const std::chrono::duration<double> poll_period_; AsyncLog async_logger_; // Accessed by producers and IOThead during thread registration and // destruction. Protected by io_thread_mutex_. std::mutex io_thread_mutex_; std::condition_variable io_thread_cv_; bool keep_io_thread_alive_ = true; std::mutex tls_loggers_registerd_mutex_; std::unordered_set<TlsLogger*> tls_loggers_registerd_; // Accessed by producers and IOThead atomically. std::atomic<size_t> swap_request_id_ { 0 }; std::vector<std::atomic<uintptr_t>> thread_swap_request_slots_; // Accessed by IOThead only. size_t swap_request_id_read_ { 0 }; struct SlotRetry { size_t slot; uintptr_t next_id; }; std::vector<SlotRetry> swap_request_slots_to_retry_; std::vector<TlsLogger*> threads_to_swap_deferred_; std::vector<TlsLogger*> threads_to_read_; std::vector<std::function<void()>> thread_cleanup_tasks_; }; void Log(Logger *logger, AsyncLogEntry &&entry); } // namespace mlperf #endif // MLPERF_LOADGEN_LOGGING_H_
[ "brianderson@google.com" ]
brianderson@google.com
e5e3d9b8a6dae8ac5bcc0791c8ddd46fb66e7a4f
08193cc7866b5411298f55a49093a482d8e1f992
/Lesson4/katamari/katamari/Mono_Static.cpp
b63f83ac307ca049938b8f072931b6acb8b4f14c
[]
no_license
nezumimusume/c_purapura_3
85fbd330c8f7fe9ec9fe79c8c6f9f46a47e36ab8
800cfa7c0715e7cd09f6bb052db79ee973289369
refs/heads/master
2023-07-19T17:22:21.711313
2017-07-12T03:18:50
2017-07-12T03:18:50
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
603
cpp
#include "stdafx.h" #include "Mono_Static.h" Mono_Static::Mono_Static() { } Mono_Static::~Mono_Static() { } //初期化。 void Mono_Static::Init(const CVector3& pos, const CQuaternion& rot) { //モデルデータのロード。 modelData.LoadModelData("Assets/modelData/mono.x", NULL); //モデルにモデルデータをセット。 model.Init(&modelData); light.SetAmbinetLight(CVector3(0.7f, 0.7f, 0.7f)); model.SetLight(&light); position = pos; localPosition = pos; rotation = rot; localRotation = rot; model.UpdateWorldMatrix(position, rotation, CVector3(10.0f, 1.0f, 10.0f)); }
[ "nezumimusume30@gmail.com" ]
nezumimusume30@gmail.com
4e1298ede5b2527478350e5d9a2cc2fdd7cf2126
96feb31b215645ec438c09588e1c9dc5691f283b
/dali-toolkit/internal/text/glyph-metrics-helper.cpp
ef9098c11faa5d2d11a6cced7a38923acfc2b779
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
nui-dali/dali-toolkit
28a99e6f117023e95920ee8eda35b6346485e074
b514a4671789bee2f03b0177393b9a21f62ac2c3
refs/heads/master
2020-05-26T23:44:18.106253
2019-05-17T10:06:27
2019-05-17T10:06:27
188,398,539
0
0
null
null
null
null
UTF-8
C++
false
false
3,081
cpp
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // FILE HEADER #include <dali-toolkit/internal/text/glyph-metrics-helper.h> namespace Dali { namespace Toolkit { namespace Text { Length GetNumberOfGlyphsOfGroup( GlyphIndex glyphIndex, GlyphIndex lastGlyphPlusOne, const Length* const charactersPerGlyphBuffer ) { Length numberOfGLyphsInGroup = 1u; for( GlyphIndex index = glyphIndex; index < lastGlyphPlusOne; ++index ) { if( 0u == *( charactersPerGlyphBuffer + index ) ) { ++numberOfGLyphsInGroup; } else { break; } } return numberOfGLyphsInGroup; } void GetGlyphsMetrics( GlyphIndex glyphIndex, Length numberOfGlyphs, GlyphMetrics& glyphMetrics, const GlyphInfo* const glyphsBuffer, MetricsPtr& metrics ) { const GlyphInfo& firstGlyph = *( glyphsBuffer + glyphIndex ); Text::FontMetrics fontMetrics; if( 0u != firstGlyph.fontId ) { metrics->GetFontMetrics( firstGlyph.fontId, fontMetrics ); } else if( 0u != firstGlyph.index ) { // It may be an embedded image. fontMetrics.ascender = firstGlyph.height; fontMetrics.descender = 0.f; fontMetrics.height = fontMetrics.ascender; } const bool isItalicFont = metrics->HasItalicStyle( firstGlyph.fontId ); glyphMetrics.fontId = firstGlyph.fontId; glyphMetrics.fontHeight = fontMetrics.height; glyphMetrics.width = firstGlyph.width + ( ( firstGlyph.isItalicRequired && !isItalicFont ) ? static_cast<unsigned int>( TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE * static_cast<float>( firstGlyph.height ) ) : 0u ); glyphMetrics.advance = firstGlyph.advance; glyphMetrics.ascender = fontMetrics.ascender; glyphMetrics.xBearing = firstGlyph.xBearing; if( 1u < numberOfGlyphs ) { const float widthInit = firstGlyph.xBearing; for( unsigned int i = 1u; i < numberOfGlyphs; ++i ) { const GlyphInfo& glyphInfo = *( glyphsBuffer + glyphIndex + i ); glyphMetrics.width = glyphMetrics.advance + glyphInfo.xBearing + glyphInfo.width + ( ( firstGlyph.isItalicRequired && !isItalicFont ) ? static_cast<unsigned int>( TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE * static_cast<float>( firstGlyph.height ) ) : 0u ); glyphMetrics.advance += glyphInfo.advance; } glyphMetrics.width -= widthInit; } } } // namespace Text } // namespace Toolkit } // namespace Dali
[ "v.cebollada@samsung.com" ]
v.cebollada@samsung.com
a4ef5856a5bd15fec12321e046c800d31743698c
0f6b3b103bb1bf44b0bbb93f9fee59129b0efd0d
/libs/minui/deps/string_view_lite.hpp
a04033cd89bbc98687d204498b634c5559812af0
[ "Apache-2.0" ]
permissive
Compelson/libaroma
bbde6fa5fd5168b83cf6d8573d4cccdbe2dd7517
0c458a9ee66fd78e00e7b1766ab0be6413d3bf90
refs/heads/master
2023-04-20T23:45:52.272533
2021-04-29T13:51:06
2021-04-29T13:51:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
48,828
hpp
// Copyright 2017-2020 by Martin Moene // // string-view lite, a C++17-like string_view for C++98 and later. // For more information see https://github.com/martinmoene/string-view-lite // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Downloaded from https://github.com/martinmoene/string-view-lite #pragma once #ifndef NONSTD_SV_LITE_H_INCLUDED #define NONSTD_SV_LITE_H_INCLUDED #define string_view_lite_MAJOR 1 #define string_view_lite_MINOR 6 #define string_view_lite_PATCH 0 #define string_view_lite_VERSION nssv_STRINGIFY(string_view_lite_MAJOR) "." nssv_STRINGIFY(string_view_lite_MINOR) "." nssv_STRINGIFY(string_view_lite_PATCH) #define nssv_STRINGIFY( x ) nssv_STRINGIFY_( x ) #define nssv_STRINGIFY_( x ) #x // string-view lite configuration: #define nssv_STRING_VIEW_DEFAULT 0 #define nssv_STRING_VIEW_NONSTD 1 #define nssv_STRING_VIEW_STD 2 // tweak header support: #ifdef __has_include # if __has_include(<nonstd/string_view.tweak.hpp>) # include <nonstd/string_view.tweak.hpp> # endif #define nssv_HAVE_TWEAK_HEADER 1 #else #define nssv_HAVE_TWEAK_HEADER 0 //# pragma message("string_view.hpp: Note: Tweak header not supported.") #endif // string_view selection and configuration: #if !defined( nssv_CONFIG_SELECT_STRING_VIEW ) # define nssv_CONFIG_SELECT_STRING_VIEW ( nssv_HAVE_STD_STRING_VIEW ? nssv_STRING_VIEW_STD : nssv_STRING_VIEW_NONSTD ) #endif #if defined( nssv_CONFIG_SELECT_STD_STRING_VIEW ) || defined( nssv_CONFIG_SELECT_NONSTD_STRING_VIEW ) # error nssv_CONFIG_SELECT_STD_STRING_VIEW and nssv_CONFIG_SELECT_NONSTD_STRING_VIEW are deprecated and removed, please use nssv_CONFIG_SELECT_STRING_VIEW=nssv_STRING_VIEW_... #endif #ifndef nssv_CONFIG_STD_SV_OPERATOR # define nssv_CONFIG_STD_SV_OPERATOR 0 #endif #ifndef nssv_CONFIG_USR_SV_OPERATOR # define nssv_CONFIG_USR_SV_OPERATOR 1 #endif #ifdef nssv_CONFIG_CONVERSION_STD_STRING # define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS nssv_CONFIG_CONVERSION_STD_STRING # define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS nssv_CONFIG_CONVERSION_STD_STRING #endif #ifndef nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS # define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS 1 #endif #ifndef nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS # define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS 1 #endif // Control presence of exception handling (try and auto discover): #ifndef nssv_CONFIG_NO_EXCEPTIONS # if _MSC_VER # include <cstddef> // for _HAS_EXCEPTIONS # endif # if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (_HAS_EXCEPTIONS) # define nssv_CONFIG_NO_EXCEPTIONS 0 # else # define nssv_CONFIG_NO_EXCEPTIONS 1 # endif #endif // C++ language version detection (C++20 is speculative): // Note: VC14.0/1900 (VS2015) lacks too much from C++14. #ifndef nssv_CPLUSPLUS # if defined(_MSVC_LANG ) && !defined(__clang__) # define nssv_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) # else # define nssv_CPLUSPLUS __cplusplus # endif #endif #define nssv_CPP98_OR_GREATER ( nssv_CPLUSPLUS >= 199711L ) #define nssv_CPP11_OR_GREATER ( nssv_CPLUSPLUS >= 201103L ) #define nssv_CPP11_OR_GREATER_ ( nssv_CPLUSPLUS >= 201103L ) #define nssv_CPP14_OR_GREATER ( nssv_CPLUSPLUS >= 201402L ) #define nssv_CPP17_OR_GREATER ( nssv_CPLUSPLUS >= 201703L ) #define nssv_CPP20_OR_GREATER ( nssv_CPLUSPLUS >= 202000L ) // use C++17 std::string_view if available and requested: #if nssv_CPP17_OR_GREATER && defined(__has_include ) # if __has_include( <string_view> ) # define nssv_HAVE_STD_STRING_VIEW 1 # else # define nssv_HAVE_STD_STRING_VIEW 0 # endif #else # define nssv_HAVE_STD_STRING_VIEW 0 #endif #define nssv_USES_STD_STRING_VIEW ( (nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_STD) || ((nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_DEFAULT) && nssv_HAVE_STD_STRING_VIEW) ) #define nssv_HAVE_STARTS_WITH ( nssv_CPP20_OR_GREATER || !nssv_USES_STD_STRING_VIEW ) #define nssv_HAVE_ENDS_WITH nssv_HAVE_STARTS_WITH // // Use C++17 std::string_view: // #if nssv_USES_STD_STRING_VIEW #include <string_view> // Extensions for std::string: #if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS namespace nonstd { template< class CharT, class Traits, class Allocator = std::allocator<CharT> > std::basic_string<CharT, Traits, Allocator> to_string( std::basic_string_view<CharT, Traits> v, Allocator const & a = Allocator() ) { return std::basic_string<CharT,Traits, Allocator>( v.begin(), v.end(), a ); } template< class CharT, class Traits, class Allocator > std::basic_string_view<CharT, Traits> to_string_view( std::basic_string<CharT, Traits, Allocator> const & s ) { return std::basic_string_view<CharT, Traits>( s.data(), s.size() ); } // Literal operators sv and _sv: #if nssv_CONFIG_STD_SV_OPERATOR using namespace std::literals::string_view_literals; #endif #if nssv_CONFIG_USR_SV_OPERATOR inline namespace literals { inline namespace string_view_literals { constexpr std::string_view operator "" _sv( const char* str, size_t len ) noexcept // (1) { return std::string_view{ str, len }; } constexpr std::u16string_view operator "" _sv( const char16_t* str, size_t len ) noexcept // (2) { return std::u16string_view{ str, len }; } constexpr std::u32string_view operator "" _sv( const char32_t* str, size_t len ) noexcept // (3) { return std::u32string_view{ str, len }; } constexpr std::wstring_view operator "" _sv( const wchar_t* str, size_t len ) noexcept // (4) { return std::wstring_view{ str, len }; } }} // namespace literals::string_view_literals #endif // nssv_CONFIG_USR_SV_OPERATOR } // namespace nonstd #endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS namespace nonstd { using std::string_view; using std::wstring_view; using std::u16string_view; using std::u32string_view; using std::basic_string_view; // literal "sv" and "_sv", see above using std::operator==; using std::operator!=; using std::operator<; using std::operator<=; using std::operator>; using std::operator>=; using std::operator<<; } // namespace nonstd #else // nssv_HAVE_STD_STRING_VIEW // // Before C++17: use string_view lite: // // Compiler versions: // // MSVC++ 6.0 _MSC_VER == 1200 nssv_COMPILER_MSVC_VERSION == 60 (Visual Studio 6.0) // MSVC++ 7.0 _MSC_VER == 1300 nssv_COMPILER_MSVC_VERSION == 70 (Visual Studio .NET 2002) // MSVC++ 7.1 _MSC_VER == 1310 nssv_COMPILER_MSVC_VERSION == 71 (Visual Studio .NET 2003) // MSVC++ 8.0 _MSC_VER == 1400 nssv_COMPILER_MSVC_VERSION == 80 (Visual Studio 2005) // MSVC++ 9.0 _MSC_VER == 1500 nssv_COMPILER_MSVC_VERSION == 90 (Visual Studio 2008) // MSVC++ 10.0 _MSC_VER == 1600 nssv_COMPILER_MSVC_VERSION == 100 (Visual Studio 2010) // MSVC++ 11.0 _MSC_VER == 1700 nssv_COMPILER_MSVC_VERSION == 110 (Visual Studio 2012) // MSVC++ 12.0 _MSC_VER == 1800 nssv_COMPILER_MSVC_VERSION == 120 (Visual Studio 2013) // MSVC++ 14.0 _MSC_VER == 1900 nssv_COMPILER_MSVC_VERSION == 140 (Visual Studio 2015) // MSVC++ 14.1 _MSC_VER >= 1910 nssv_COMPILER_MSVC_VERSION == 141 (Visual Studio 2017) // MSVC++ 14.2 _MSC_VER >= 1920 nssv_COMPILER_MSVC_VERSION == 142 (Visual Studio 2019) #if defined(_MSC_VER ) && !defined(__clang__) # define nssv_COMPILER_MSVC_VER (_MSC_VER ) # define nssv_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) #else # define nssv_COMPILER_MSVC_VER 0 # define nssv_COMPILER_MSVC_VERSION 0 #endif #define nssv_COMPILER_VERSION( major, minor, patch ) ( 10 * ( 10 * (major) + (minor) ) + (patch) ) #if defined( __apple_build_version__ ) # define nssv_COMPILER_APPLECLANG_VERSION nssv_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) # define nssv_COMPILER_CLANG_VERSION 0 #elif defined( __clang__ ) # define nssv_COMPILER_APPLECLANG_VERSION 0 # define nssv_COMPILER_CLANG_VERSION nssv_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) #else # define nssv_COMPILER_APPLECLANG_VERSION 0 # define nssv_COMPILER_CLANG_VERSION 0 #endif #if defined(__GNUC__) && !defined(__clang__) # define nssv_COMPILER_GNUC_VERSION nssv_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #else # define nssv_COMPILER_GNUC_VERSION 0 #endif // half-open range [lo..hi): #define nssv_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) // Presence of language and library features: #ifdef _HAS_CPP0X # define nssv_HAS_CPP0X _HAS_CPP0X #else # define nssv_HAS_CPP0X 0 #endif // Unless defined otherwise below, consider VC14 as C++11 for variant-lite: #if nssv_COMPILER_MSVC_VER >= 1900 # undef nssv_CPP11_OR_GREATER # define nssv_CPP11_OR_GREATER 1 #endif #define nssv_CPP11_90 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1500) #define nssv_CPP11_100 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1600) #define nssv_CPP11_110 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1700) #define nssv_CPP11_120 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1800) #define nssv_CPP11_140 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1900) #define nssv_CPP11_141 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1910) #define nssv_CPP14_000 (nssv_CPP14_OR_GREATER) #define nssv_CPP17_000 (nssv_CPP17_OR_GREATER) // Presence of C++11 language features: #define nssv_HAVE_CONSTEXPR_11 nssv_CPP11_140 #define nssv_HAVE_EXPLICIT_CONVERSION nssv_CPP11_140 #define nssv_HAVE_INLINE_NAMESPACE nssv_CPP11_140 #define nssv_HAVE_NOEXCEPT nssv_CPP11_140 #define nssv_HAVE_NULLPTR nssv_CPP11_100 #define nssv_HAVE_REF_QUALIFIER nssv_CPP11_140 #define nssv_HAVE_UNICODE_LITERALS nssv_CPP11_140 #define nssv_HAVE_USER_DEFINED_LITERALS nssv_CPP11_140 #define nssv_HAVE_WCHAR16_T nssv_CPP11_100 #define nssv_HAVE_WCHAR32_T nssv_CPP11_100 #if ! ( ( nssv_CPP11_OR_GREATER && nssv_COMPILER_CLANG_VERSION ) || nssv_BETWEEN( nssv_COMPILER_CLANG_VERSION, 300, 400 ) ) # define nssv_HAVE_STD_DEFINED_LITERALS nssv_CPP11_140 #else # define nssv_HAVE_STD_DEFINED_LITERALS 0 #endif // Presence of C++14 language features: #define nssv_HAVE_CONSTEXPR_14 nssv_CPP14_000 // Presence of C++17 language features: #define nssv_HAVE_NODISCARD nssv_CPP17_000 // Presence of C++ library features: #define nssv_HAVE_STD_HASH nssv_CPP11_120 // Presence of compiler intrinsics: // Providing char-type specializations for compare() and length() that // use compiler intrinsics can improve compile- and run-time performance. // // The challenge is in using the right combinations of builtin availablity // and its constexpr-ness. // // | compiler | __builtin_memcmp (constexpr) | memcmp (constexpr) | // |----------|------------------------------|---------------------| // | clang | 4.0 (>= 4.0 ) | any (? ) | // | clang-a | 9.0 (>= 9.0 ) | any (? ) | // | gcc | any (constexpr) | any (? ) | // | msvc | >= 14.2 C++17 (>= 14.2 ) | any (? ) | #define nssv_HAVE_BUILTIN_VER ( (nssv_CPP17_000 && nssv_COMPILER_MSVC_VERSION >= 142) || nssv_COMPILER_GNUC_VERSION > 0 || nssv_COMPILER_CLANG_VERSION >= 400 || nssv_COMPILER_APPLECLANG_VERSION >= 900 ) #define nssv_HAVE_BUILTIN_CE ( nssv_HAVE_BUILTIN_VER ) #define nssv_HAVE_BUILTIN_MEMCMP ( (nssv_HAVE_CONSTEXPR_14 && nssv_HAVE_BUILTIN_CE) || !nssv_HAVE_CONSTEXPR_14 ) #define nssv_HAVE_BUILTIN_STRLEN ( (nssv_HAVE_CONSTEXPR_11 && nssv_HAVE_BUILTIN_CE) || !nssv_HAVE_CONSTEXPR_11 ) #ifdef __has_builtin # define nssv_HAVE_BUILTIN( x ) __has_builtin( x ) #else # define nssv_HAVE_BUILTIN( x ) 0 #endif #if nssv_HAVE_BUILTIN(__builtin_memcmp) || nssv_HAVE_BUILTIN_VER # define nssv_BUILTIN_MEMCMP __builtin_memcmp #else # define nssv_BUILTIN_MEMCMP memcmp #endif #if nssv_HAVE_BUILTIN(__builtin_strlen) || nssv_HAVE_BUILTIN_VER # define nssv_BUILTIN_STRLEN __builtin_strlen #else # define nssv_BUILTIN_STRLEN strlen #endif // C++ feature usage: #if nssv_HAVE_CONSTEXPR_11 # define nssv_constexpr constexpr #else # define nssv_constexpr /*constexpr*/ #endif #if nssv_HAVE_CONSTEXPR_14 # define nssv_constexpr14 constexpr #else # define nssv_constexpr14 /*constexpr*/ #endif #if nssv_HAVE_EXPLICIT_CONVERSION # define nssv_explicit explicit #else # define nssv_explicit /*explicit*/ #endif #if nssv_HAVE_INLINE_NAMESPACE # define nssv_inline_ns inline #else # define nssv_inline_ns /*inline*/ #endif #if nssv_HAVE_NOEXCEPT # define nssv_noexcept noexcept #else # define nssv_noexcept /*noexcept*/ #endif //#if nssv_HAVE_REF_QUALIFIER //# define nssv_ref_qual & //# define nssv_refref_qual && //#else //# define nssv_ref_qual /*&*/ //# define nssv_refref_qual /*&&*/ //#endif #if nssv_HAVE_NULLPTR # define nssv_nullptr nullptr #else # define nssv_nullptr NULL #endif #if nssv_HAVE_NODISCARD # define nssv_nodiscard [[nodiscard]] #else # define nssv_nodiscard /*[[nodiscard]]*/ #endif // Additional includes: #include <algorithm> #include <cassert> #include <iterator> #include <limits> #include <ostream> #include <string> // std::char_traits<> #if ! nssv_CONFIG_NO_EXCEPTIONS # include <stdexcept> #endif #if nssv_CPP11_OR_GREATER # include <type_traits> #endif // Clang, GNUC, MSVC warning suppression macros: #if defined(__clang__) # pragma clang diagnostic ignored "-Wreserved-user-defined-literal" # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wuser-defined-literals" #elif defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wliteral-suffix" #endif // __clang__ #if nssv_COMPILER_MSVC_VERSION >= 140 # define nssv_SUPPRESS_MSGSL_WARNING(expr) [[gsl::suppress(expr)]] # define nssv_SUPPRESS_MSVC_WARNING(code, descr) __pragma(warning(suppress: code) ) # define nssv_DISABLE_MSVC_WARNINGS(codes) __pragma(warning(push)) __pragma(warning(disable: codes)) #else # define nssv_SUPPRESS_MSGSL_WARNING(expr) # define nssv_SUPPRESS_MSVC_WARNING(code, descr) # define nssv_DISABLE_MSVC_WARNINGS(codes) #endif #if defined(__clang__) # define nssv_RESTORE_WARNINGS() _Pragma("clang diagnostic pop") #elif defined(__GNUC__) # define nssv_RESTORE_WARNINGS() _Pragma("GCC diagnostic pop") #elif nssv_COMPILER_MSVC_VERSION >= 140 # define nssv_RESTORE_WARNINGS() __pragma(warning(pop )) #else # define nssv_RESTORE_WARNINGS() #endif // Suppress the following MSVC (GSL) warnings: // - C4455, non-gsl : 'operator ""sv': literal suffix identifiers that do not // start with an underscore are reserved // - C26472, gsl::t.1 : don't use a static_cast for arithmetic conversions; // use brace initialization, gsl::narrow_cast or gsl::narow // - C26481: gsl::b.1 : don't use pointer arithmetic. Use span instead nssv_DISABLE_MSVC_WARNINGS( 4455 26481 26472 ) //nssv_DISABLE_CLANG_WARNINGS( "-Wuser-defined-literals" ) //nssv_DISABLE_GNUC_WARNINGS( -Wliteral-suffix ) namespace nonstd { namespace sv_lite { namespace detail { // support constexpr comparison in C++14; // for C++17 and later, use provided traits: template< typename CharT > inline nssv_constexpr14 int compare( CharT const * s1, CharT const * s2, std::size_t count ) { while ( count-- != 0 ) { if ( *s1 < *s2 ) return -1; if ( *s1 > *s2 ) return +1; ++s1; ++s2; } return 0; } #if nssv_HAVE_BUILTIN_MEMCMP // specialization of compare() for char, see also generic compare() above: inline nssv_constexpr14 int compare( char const * s1, char const * s2, std::size_t count ) { return nssv_BUILTIN_MEMCMP( s1, s2, count ); } #endif #if nssv_HAVE_BUILTIN_STRLEN // specialization of length() for char, see also generic length() further below: inline nssv_constexpr std::size_t length( char const * s ) { return nssv_BUILTIN_STRLEN( s ); } #endif #if defined(__OPTIMIZE__) // gcc, clang provide __OPTIMIZE__ // Expect tail call optimization to make length() non-recursive: template< typename CharT > inline nssv_constexpr std::size_t length( CharT * s, std::size_t result = 0 ) { return *s == '\0' ? result : length( s + 1, result + 1 ); } #else // OPTIMIZE // non-recursive: template< typename CharT > inline nssv_constexpr14 std::size_t length( CharT * s ) { std::size_t result = 0; while ( *s++ != '\0' ) { ++result; } return result; } #endif // OPTIMIZE } // namespace detail template < class CharT, class Traits = std::char_traits<CharT> > class basic_string_view; // // basic_string_view: // template < class CharT, class Traits /* = std::char_traits<CharT> */ > class basic_string_view { public: // Member types: typedef Traits traits_type; typedef CharT value_type; typedef CharT * pointer; typedef CharT const * const_pointer; typedef CharT & reference; typedef CharT const & const_reference; typedef const_pointer iterator; typedef const_pointer const_iterator; typedef std::reverse_iterator< const_iterator > reverse_iterator; typedef std::reverse_iterator< const_iterator > const_reverse_iterator; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; // 24.4.2.1 Construction and assignment: nssv_constexpr basic_string_view() nssv_noexcept : data_( nssv_nullptr ) , size_( 0 ) {} #if nssv_CPP11_OR_GREATER nssv_constexpr basic_string_view( basic_string_view const & other ) nssv_noexcept = default; #else nssv_constexpr basic_string_view( basic_string_view const & other ) nssv_noexcept : data_( other.data_) , size_( other.size_) {} #endif nssv_constexpr basic_string_view( CharT const * s, size_type count ) nssv_noexcept // non-standard noexcept : data_( s ) , size_( count ) {} nssv_constexpr basic_string_view( CharT const * s) nssv_noexcept // non-standard noexcept : data_( s ) #if nssv_CPP17_OR_GREATER , size_( Traits::length(s) ) #elif nssv_CPP11_OR_GREATER , size_( detail::length(s) ) #else , size_( Traits::length(s) ) #endif {} // Assignment: #if nssv_CPP11_OR_GREATER nssv_constexpr14 basic_string_view & operator=( basic_string_view const & other ) nssv_noexcept = default; #else nssv_constexpr14 basic_string_view & operator=( basic_string_view const & other ) nssv_noexcept { data_ = other.data_; size_ = other.size_; return *this; } #endif // 24.4.2.2 Iterator support: nssv_constexpr const_iterator begin() const nssv_noexcept { return data_; } nssv_constexpr const_iterator end() const nssv_noexcept { return data_ + size_; } nssv_constexpr const_iterator cbegin() const nssv_noexcept { return begin(); } nssv_constexpr const_iterator cend() const nssv_noexcept { return end(); } nssv_constexpr const_reverse_iterator rbegin() const nssv_noexcept { return const_reverse_iterator( end() ); } nssv_constexpr const_reverse_iterator rend() const nssv_noexcept { return const_reverse_iterator( begin() ); } nssv_constexpr const_reverse_iterator crbegin() const nssv_noexcept { return rbegin(); } nssv_constexpr const_reverse_iterator crend() const nssv_noexcept { return rend(); } // 24.4.2.3 Capacity: nssv_constexpr size_type size() const nssv_noexcept { return size_; } nssv_constexpr size_type length() const nssv_noexcept { return size_; } nssv_constexpr size_type max_size() const nssv_noexcept { return (std::numeric_limits< size_type >::max)(); } // since C++20 nssv_nodiscard nssv_constexpr bool empty() const nssv_noexcept { return 0 == size_; } // 24.4.2.4 Element access: nssv_constexpr const_reference operator[]( size_type pos ) const { return data_at( pos ); } nssv_constexpr14 const_reference at( size_type pos ) const { #if nssv_CONFIG_NO_EXCEPTIONS assert( pos < size() ); #else if ( pos >= size() ) { throw std::out_of_range("nonstd::string_view::at()"); } #endif return data_at( pos ); } nssv_constexpr const_reference front() const { return data_at( 0 ); } nssv_constexpr const_reference back() const { return data_at( size() - 1 ); } nssv_constexpr const_pointer data() const nssv_noexcept { return data_; } // 24.4.2.5 Modifiers: nssv_constexpr14 void remove_prefix( size_type n ) { assert( n <= size() ); data_ += n; size_ -= n; } nssv_constexpr14 void remove_suffix( size_type n ) { assert( n <= size() ); size_ -= n; } nssv_constexpr14 void swap( basic_string_view & other ) nssv_noexcept { using std::swap; swap( data_, other.data_ ); swap( size_, other.size_ ); } // 24.4.2.6 String operations: size_type copy( CharT * dest, size_type n, size_type pos = 0 ) const { #if nssv_CONFIG_NO_EXCEPTIONS assert( pos <= size() ); #else if ( pos > size() ) { throw std::out_of_range("nonstd::string_view::copy()"); } #endif const size_type rlen = (std::min)( n, size() - pos ); (void) Traits::copy( dest, data() + pos, rlen ); return rlen; } nssv_constexpr14 basic_string_view substr( size_type pos = 0, size_type n = npos ) const { #if nssv_CONFIG_NO_EXCEPTIONS assert( pos <= size() ); #else if ( pos > size() ) { throw std::out_of_range("nonstd::string_view::substr()"); } #endif return basic_string_view( data() + pos, (std::min)( n, size() - pos ) ); } // compare(), 6x: nssv_constexpr14 int compare( basic_string_view other ) const nssv_noexcept // (1) { #if nssv_CPP17_OR_GREATER if ( const int result = Traits::compare( data(), other.data(), (std::min)( size(), other.size() ) ) ) #else if ( const int result = detail::compare( data(), other.data(), (std::min)( size(), other.size() ) ) ) #endif { return result; } return size() == other.size() ? 0 : size() < other.size() ? -1 : 1; } nssv_constexpr int compare( size_type pos1, size_type n1, basic_string_view other ) const // (2) { return substr( pos1, n1 ).compare( other ); } nssv_constexpr int compare( size_type pos1, size_type n1, basic_string_view other, size_type pos2, size_type n2 ) const // (3) { return substr( pos1, n1 ).compare( other.substr( pos2, n2 ) ); } nssv_constexpr int compare( CharT const * s ) const // (4) { return compare( basic_string_view( s ) ); } nssv_constexpr int compare( size_type pos1, size_type n1, CharT const * s ) const // (5) { return substr( pos1, n1 ).compare( basic_string_view( s ) ); } nssv_constexpr int compare( size_type pos1, size_type n1, CharT const * s, size_type n2 ) const // (6) { return substr( pos1, n1 ).compare( basic_string_view( s, n2 ) ); } // 24.4.2.7 Searching: // starts_with(), 3x, since C++20: nssv_constexpr bool starts_with( basic_string_view v ) const nssv_noexcept // (1) { return size() >= v.size() && compare( 0, v.size(), v ) == 0; } nssv_constexpr bool starts_with( CharT c ) const nssv_noexcept // (2) { return starts_with( basic_string_view( &c, 1 ) ); } nssv_constexpr bool starts_with( CharT const * s ) const // (3) { return starts_with( basic_string_view( s ) ); } // ends_with(), 3x, since C++20: nssv_constexpr bool ends_with( basic_string_view v ) const nssv_noexcept // (1) { return size() >= v.size() && compare( size() - v.size(), npos, v ) == 0; } nssv_constexpr bool ends_with( CharT c ) const nssv_noexcept // (2) { return ends_with( basic_string_view( &c, 1 ) ); } nssv_constexpr bool ends_with( CharT const * s ) const // (3) { return ends_with( basic_string_view( s ) ); } // find(), 4x: nssv_constexpr14 size_type find( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) { return assert( v.size() == 0 || v.data() != nssv_nullptr ) , pos >= size() ? npos : to_pos( std::search( cbegin() + pos, cend(), v.cbegin(), v.cend(), Traits::eq ) ); } nssv_constexpr14 size_type find( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) { return find( basic_string_view( &c, 1 ), pos ); } nssv_constexpr14 size_type find( CharT const * s, size_type pos, size_type n ) const // (3) { return find( basic_string_view( s, n ), pos ); } nssv_constexpr14 size_type find( CharT const * s, size_type pos = 0 ) const // (4) { return find( basic_string_view( s ), pos ); } // rfind(), 4x: nssv_constexpr14 size_type rfind( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) { if ( size() < v.size() ) { return npos; } if ( v.empty() ) { return (std::min)( size(), pos ); } const_iterator last = cbegin() + (std::min)( size() - v.size(), pos ) + v.size(); const_iterator result = std::find_end( cbegin(), last, v.cbegin(), v.cend(), Traits::eq ); return result != last ? size_type( result - cbegin() ) : npos; } nssv_constexpr14 size_type rfind( CharT c, size_type pos = npos ) const nssv_noexcept // (2) { return rfind( basic_string_view( &c, 1 ), pos ); } nssv_constexpr14 size_type rfind( CharT const * s, size_type pos, size_type n ) const // (3) { return rfind( basic_string_view( s, n ), pos ); } nssv_constexpr14 size_type rfind( CharT const * s, size_type pos = npos ) const // (4) { return rfind( basic_string_view( s ), pos ); } // find_first_of(), 4x: nssv_constexpr size_type find_first_of( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) { return pos >= size() ? npos : to_pos( std::find_first_of( cbegin() + pos, cend(), v.cbegin(), v.cend(), Traits::eq ) ); } nssv_constexpr size_type find_first_of( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) { return find_first_of( basic_string_view( &c, 1 ), pos ); } nssv_constexpr size_type find_first_of( CharT const * s, size_type pos, size_type n ) const // (3) { return find_first_of( basic_string_view( s, n ), pos ); } nssv_constexpr size_type find_first_of( CharT const * s, size_type pos = 0 ) const // (4) { return find_first_of( basic_string_view( s ), pos ); } // find_last_of(), 4x: nssv_constexpr size_type find_last_of( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) { return empty() ? npos : pos >= size() ? find_last_of( v, size() - 1 ) : to_pos( std::find_first_of( const_reverse_iterator( cbegin() + pos + 1 ), crend(), v.cbegin(), v.cend(), Traits::eq ) ); } nssv_constexpr size_type find_last_of( CharT c, size_type pos = npos ) const nssv_noexcept // (2) { return find_last_of( basic_string_view( &c, 1 ), pos ); } nssv_constexpr size_type find_last_of( CharT const * s, size_type pos, size_type count ) const // (3) { return find_last_of( basic_string_view( s, count ), pos ); } nssv_constexpr size_type find_last_of( CharT const * s, size_type pos = npos ) const // (4) { return find_last_of( basic_string_view( s ), pos ); } // find_first_not_of(), 4x: nssv_constexpr size_type find_first_not_of( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) { return pos >= size() ? npos : to_pos( std::find_if( cbegin() + pos, cend(), not_in_view( v ) ) ); } nssv_constexpr size_type find_first_not_of( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) { return find_first_not_of( basic_string_view( &c, 1 ), pos ); } nssv_constexpr size_type find_first_not_of( CharT const * s, size_type pos, size_type count ) const // (3) { return find_first_not_of( basic_string_view( s, count ), pos ); } nssv_constexpr size_type find_first_not_of( CharT const * s, size_type pos = 0 ) const // (4) { return find_first_not_of( basic_string_view( s ), pos ); } // find_last_not_of(), 4x: nssv_constexpr size_type find_last_not_of( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) { return empty() ? npos : pos >= size() ? find_last_not_of( v, size() - 1 ) : to_pos( std::find_if( const_reverse_iterator( cbegin() + pos + 1 ), crend(), not_in_view( v ) ) ); } nssv_constexpr size_type find_last_not_of( CharT c, size_type pos = npos ) const nssv_noexcept // (2) { return find_last_not_of( basic_string_view( &c, 1 ), pos ); } nssv_constexpr size_type find_last_not_of( CharT const * s, size_type pos, size_type count ) const // (3) { return find_last_not_of( basic_string_view( s, count ), pos ); } nssv_constexpr size_type find_last_not_of( CharT const * s, size_type pos = npos ) const // (4) { return find_last_not_of( basic_string_view( s ), pos ); } // Constants: #if nssv_CPP17_OR_GREATER static nssv_constexpr size_type npos = size_type(-1); #elif nssv_CPP11_OR_GREATER enum : size_type { npos = size_type(-1) }; #else enum { npos = size_type(-1) }; #endif private: struct not_in_view { const basic_string_view v; nssv_constexpr explicit not_in_view( basic_string_view v_ ) : v( v_ ) {} nssv_constexpr bool operator()( CharT c ) const { return npos == v.find_first_of( c ); } }; nssv_constexpr size_type to_pos( const_iterator it ) const { return it == cend() ? npos : size_type( it - cbegin() ); } nssv_constexpr size_type to_pos( const_reverse_iterator it ) const { return it == crend() ? npos : size_type( crend() - it - 1 ); } nssv_constexpr const_reference data_at( size_type pos ) const { #if nssv_BETWEEN( nssv_COMPILER_GNUC_VERSION, 1, 500 ) return data_[pos]; #else return assert( pos < size() ), data_[pos]; #endif } private: const_pointer data_; size_type size_; public: #if nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS template< class Allocator > basic_string_view( std::basic_string<CharT, Traits, Allocator> const & s ) nssv_noexcept : data_( s.data() ) , size_( s.size() ) {} #if nssv_HAVE_EXPLICIT_CONVERSION template< class Allocator > explicit operator std::basic_string<CharT, Traits, Allocator>() const { return to_string( Allocator() ); } #endif // nssv_HAVE_EXPLICIT_CONVERSION #if nssv_CPP11_OR_GREATER template< class Allocator = std::allocator<CharT> > std::basic_string<CharT, Traits, Allocator> to_string( Allocator const & a = Allocator() ) const { return std::basic_string<CharT, Traits, Allocator>( begin(), end(), a ); } #else std::basic_string<CharT, Traits> to_string() const { return std::basic_string<CharT, Traits>( begin(), end() ); } template< class Allocator > std::basic_string<CharT, Traits, Allocator> to_string( Allocator const & a ) const { return std::basic_string<CharT, Traits, Allocator>( begin(), end(), a ); } #endif // nssv_CPP11_OR_GREATER #endif // nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS }; // // Non-member functions: // // 24.4.3 Non-member comparison functions: // lexicographically compare two string views (function template): template< class CharT, class Traits > nssv_constexpr bool operator== ( basic_string_view <CharT, Traits> lhs, basic_string_view <CharT, Traits> rhs ) nssv_noexcept { return lhs.size() == rhs.size() && lhs.compare( rhs ) == 0; } template< class CharT, class Traits > nssv_constexpr bool operator!= ( basic_string_view <CharT, Traits> lhs, basic_string_view <CharT, Traits> rhs ) nssv_noexcept { return !( lhs == rhs ); } template< class CharT, class Traits > nssv_constexpr bool operator< ( basic_string_view <CharT, Traits> lhs, basic_string_view <CharT, Traits> rhs ) nssv_noexcept { return lhs.compare( rhs ) < 0; } template< class CharT, class Traits > nssv_constexpr bool operator<= ( basic_string_view <CharT, Traits> lhs, basic_string_view <CharT, Traits> rhs ) nssv_noexcept { return lhs.compare( rhs ) <= 0; } template< class CharT, class Traits > nssv_constexpr bool operator> ( basic_string_view <CharT, Traits> lhs, basic_string_view <CharT, Traits> rhs ) nssv_noexcept { return lhs.compare( rhs ) > 0; } template< class CharT, class Traits > nssv_constexpr bool operator>= ( basic_string_view <CharT, Traits> lhs, basic_string_view <CharT, Traits> rhs ) nssv_noexcept { return lhs.compare( rhs ) >= 0; } // Let S be basic_string_view<CharT, Traits>, and sv be an instance of S. // Implementations shall provide sufficient additional overloads marked // constexpr and noexcept so that an object t with an implicit conversion // to S can be compared according to Table 67. #if ! nssv_CPP11_OR_GREATER || nssv_BETWEEN( nssv_COMPILER_MSVC_VERSION, 100, 141 ) // accomodate for older compilers: // == template< class CharT, class Traits> nssv_constexpr bool operator==( basic_string_view<CharT, Traits> lhs, CharT const * rhs ) nssv_noexcept { return lhs.size() == detail::length( rhs ) && lhs.compare( rhs ) == 0; } template< class CharT, class Traits> nssv_constexpr bool operator==( CharT const * lhs, basic_string_view<CharT, Traits> rhs ) nssv_noexcept { return detail::length( lhs ) == rhs.size() && rhs.compare( lhs ) == 0; } template< class CharT, class Traits> nssv_constexpr bool operator==( basic_string_view<CharT, Traits> lhs, std::basic_string<CharT, Traits> rhs ) nssv_noexcept { return lhs.size() == rhs.size() && lhs.compare( rhs ) == 0; } template< class CharT, class Traits> nssv_constexpr bool operator==( std::basic_string<CharT, Traits> rhs, basic_string_view<CharT, Traits> lhs ) nssv_noexcept { return lhs.size() == rhs.size() && lhs.compare( rhs ) == 0; } // != template< class CharT, class Traits> nssv_constexpr bool operator!=( basic_string_view<CharT, Traits> lhs, char const * rhs ) nssv_noexcept { return !( lhs == rhs ); } template< class CharT, class Traits> nssv_constexpr bool operator!=( char const * lhs, basic_string_view<CharT, Traits> rhs ) nssv_noexcept { return !( lhs == rhs ); } template< class CharT, class Traits> nssv_constexpr bool operator!=( basic_string_view<CharT, Traits> lhs, std::basic_string<CharT, Traits> rhs ) nssv_noexcept { return !( lhs == rhs ); } template< class CharT, class Traits> nssv_constexpr bool operator!=( std::basic_string<CharT, Traits> rhs, basic_string_view<CharT, Traits> lhs ) nssv_noexcept { return !( lhs == rhs ); } // < template< class CharT, class Traits> nssv_constexpr bool operator<( basic_string_view<CharT, Traits> lhs, char const * rhs ) nssv_noexcept { return lhs.compare( rhs ) < 0; } template< class CharT, class Traits> nssv_constexpr bool operator<( char const * lhs, basic_string_view<CharT, Traits> rhs ) nssv_noexcept { return rhs.compare( lhs ) > 0; } template< class CharT, class Traits> nssv_constexpr bool operator<( basic_string_view<CharT, Traits> lhs, std::basic_string<CharT, Traits> rhs ) nssv_noexcept { return lhs.compare( rhs ) < 0; } template< class CharT, class Traits> nssv_constexpr bool operator<( std::basic_string<CharT, Traits> rhs, basic_string_view<CharT, Traits> lhs ) nssv_noexcept { return rhs.compare( lhs ) > 0; } // <= template< class CharT, class Traits> nssv_constexpr bool operator<=( basic_string_view<CharT, Traits> lhs, char const * rhs ) nssv_noexcept { return lhs.compare( rhs ) <= 0; } template< class CharT, class Traits> nssv_constexpr bool operator<=( char const * lhs, basic_string_view<CharT, Traits> rhs ) nssv_noexcept { return rhs.compare( lhs ) >= 0; } template< class CharT, class Traits> nssv_constexpr bool operator<=( basic_string_view<CharT, Traits> lhs, std::basic_string<CharT, Traits> rhs ) nssv_noexcept { return lhs.compare( rhs ) <= 0; } template< class CharT, class Traits> nssv_constexpr bool operator<=( std::basic_string<CharT, Traits> rhs, basic_string_view<CharT, Traits> lhs ) nssv_noexcept { return rhs.compare( lhs ) >= 0; } // > template< class CharT, class Traits> nssv_constexpr bool operator>( basic_string_view<CharT, Traits> lhs, char const * rhs ) nssv_noexcept { return lhs.compare( rhs ) > 0; } template< class CharT, class Traits> nssv_constexpr bool operator>( char const * lhs, basic_string_view<CharT, Traits> rhs ) nssv_noexcept { return rhs.compare( lhs ) < 0; } template< class CharT, class Traits> nssv_constexpr bool operator>( basic_string_view<CharT, Traits> lhs, std::basic_string<CharT, Traits> rhs ) nssv_noexcept { return lhs.compare( rhs ) > 0; } template< class CharT, class Traits> nssv_constexpr bool operator>( std::basic_string<CharT, Traits> rhs, basic_string_view<CharT, Traits> lhs ) nssv_noexcept { return rhs.compare( lhs ) < 0; } // >= template< class CharT, class Traits> nssv_constexpr bool operator>=( basic_string_view<CharT, Traits> lhs, char const * rhs ) nssv_noexcept { return lhs.compare( rhs ) >= 0; } template< class CharT, class Traits> nssv_constexpr bool operator>=( char const * lhs, basic_string_view<CharT, Traits> rhs ) nssv_noexcept { return rhs.compare( lhs ) <= 0; } template< class CharT, class Traits> nssv_constexpr bool operator>=( basic_string_view<CharT, Traits> lhs, std::basic_string<CharT, Traits> rhs ) nssv_noexcept { return lhs.compare( rhs ) >= 0; } template< class CharT, class Traits> nssv_constexpr bool operator>=( std::basic_string<CharT, Traits> rhs, basic_string_view<CharT, Traits> lhs ) nssv_noexcept { return rhs.compare( lhs ) <= 0; } #else // newer compilers: #define nssv_BASIC_STRING_VIEW_I(T,U) typename std::decay< basic_string_view<T,U> >::type #if defined(_MSC_VER) // issue 40 # define nssv_MSVC_ORDER(x) , int=x #else # define nssv_MSVC_ORDER(x) /*, int=x*/ #endif // == template< class CharT, class Traits nssv_MSVC_ORDER(1) > nssv_constexpr bool operator==( basic_string_view <CharT, Traits> lhs, nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs ) nssv_noexcept { return lhs.size() == rhs.size() && lhs.compare( rhs ) == 0; } template< class CharT, class Traits nssv_MSVC_ORDER(2) > nssv_constexpr bool operator==( nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, basic_string_view <CharT, Traits> rhs ) nssv_noexcept { return lhs.size() == rhs.size() && lhs.compare( rhs ) == 0; } // != template< class CharT, class Traits nssv_MSVC_ORDER(1) > nssv_constexpr bool operator!= ( basic_string_view < CharT, Traits > lhs, nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept { return !( lhs == rhs ); } template< class CharT, class Traits nssv_MSVC_ORDER(2) > nssv_constexpr bool operator!= ( nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, basic_string_view < CharT, Traits > rhs ) nssv_noexcept { return !( lhs == rhs ); } // < template< class CharT, class Traits nssv_MSVC_ORDER(1) > nssv_constexpr bool operator< ( basic_string_view < CharT, Traits > lhs, nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept { return lhs.compare( rhs ) < 0; } template< class CharT, class Traits nssv_MSVC_ORDER(2) > nssv_constexpr bool operator< ( nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, basic_string_view < CharT, Traits > rhs ) nssv_noexcept { return lhs.compare( rhs ) < 0; } // <= template< class CharT, class Traits nssv_MSVC_ORDER(1) > nssv_constexpr bool operator<= ( basic_string_view < CharT, Traits > lhs, nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept { return lhs.compare( rhs ) <= 0; } template< class CharT, class Traits nssv_MSVC_ORDER(2) > nssv_constexpr bool operator<= ( nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, basic_string_view < CharT, Traits > rhs ) nssv_noexcept { return lhs.compare( rhs ) <= 0; } // > template< class CharT, class Traits nssv_MSVC_ORDER(1) > nssv_constexpr bool operator> ( basic_string_view < CharT, Traits > lhs, nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept { return lhs.compare( rhs ) > 0; } template< class CharT, class Traits nssv_MSVC_ORDER(2) > nssv_constexpr bool operator> ( nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, basic_string_view < CharT, Traits > rhs ) nssv_noexcept { return lhs.compare( rhs ) > 0; } // >= template< class CharT, class Traits nssv_MSVC_ORDER(1) > nssv_constexpr bool operator>= ( basic_string_view < CharT, Traits > lhs, nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept { return lhs.compare( rhs ) >= 0; } template< class CharT, class Traits nssv_MSVC_ORDER(2) > nssv_constexpr bool operator>= ( nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, basic_string_view < CharT, Traits > rhs ) nssv_noexcept { return lhs.compare( rhs ) >= 0; } #undef nssv_MSVC_ORDER #undef nssv_BASIC_STRING_VIEW_I #endif // compiler-dependent approach to comparisons // 24.4.4 Inserters and extractors: namespace detail { template< class Stream > void write_padding( Stream & os, std::streamsize n ) { for ( std::streamsize i = 0; i < n; ++i ) os.rdbuf()->sputc( os.fill() ); } template< class Stream, class View > Stream & write_to_stream( Stream & os, View const & sv ) { typename Stream::sentry sentry( os ); if ( !os ) return os; const std::streamsize length = static_cast<std::streamsize>( sv.length() ); // Whether, and how, to pad: const bool pad = ( length < os.width() ); const bool left_pad = pad && ( os.flags() & std::ios_base::adjustfield ) == std::ios_base::right; if ( left_pad ) write_padding( os, os.width() - length ); // Write span characters: os.rdbuf()->sputn( sv.begin(), length ); if ( pad && !left_pad ) write_padding( os, os.width() - length ); // Reset output stream width: os.width( 0 ); return os; } } // namespace detail template< class CharT, class Traits > std::basic_ostream<CharT, Traits> & operator<<( std::basic_ostream<CharT, Traits>& os, basic_string_view <CharT, Traits> sv ) { return detail::write_to_stream( os, sv ); } // Several typedefs for common character types are provided: typedef basic_string_view<char> string_view; typedef basic_string_view<wchar_t> wstring_view; #if nssv_HAVE_WCHAR16_T typedef basic_string_view<char16_t> u16string_view; typedef basic_string_view<char32_t> u32string_view; #endif }} // namespace nonstd::sv_lite // // 24.4.6 Suffix for basic_string_view literals: // #if nssv_HAVE_USER_DEFINED_LITERALS namespace nonstd { nssv_inline_ns namespace literals { nssv_inline_ns namespace string_view_literals { #if nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS nssv_constexpr nonstd::sv_lite::string_view operator "" sv( const char* str, size_t len ) nssv_noexcept // (1) { return nonstd::sv_lite::string_view{ str, len }; } nssv_constexpr nonstd::sv_lite::u16string_view operator "" sv( const char16_t* str, size_t len ) nssv_noexcept // (2) { return nonstd::sv_lite::u16string_view{ str, len }; } nssv_constexpr nonstd::sv_lite::u32string_view operator "" sv( const char32_t* str, size_t len ) nssv_noexcept // (3) { return nonstd::sv_lite::u32string_view{ str, len }; } nssv_constexpr nonstd::sv_lite::wstring_view operator "" sv( const wchar_t* str, size_t len ) nssv_noexcept // (4) { return nonstd::sv_lite::wstring_view{ str, len }; } #endif // nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS #if nssv_CONFIG_USR_SV_OPERATOR nssv_constexpr nonstd::sv_lite::string_view operator "" _sv( const char* str, size_t len ) nssv_noexcept // (1) { return nonstd::sv_lite::string_view{ str, len }; } nssv_constexpr nonstd::sv_lite::u16string_view operator "" _sv( const char16_t* str, size_t len ) nssv_noexcept // (2) { return nonstd::sv_lite::u16string_view{ str, len }; } nssv_constexpr nonstd::sv_lite::u32string_view operator "" _sv( const char32_t* str, size_t len ) nssv_noexcept // (3) { return nonstd::sv_lite::u32string_view{ str, len }; } nssv_constexpr nonstd::sv_lite::wstring_view operator "" _sv( const wchar_t* str, size_t len ) nssv_noexcept // (4) { return nonstd::sv_lite::wstring_view{ str, len }; } #endif // nssv_CONFIG_USR_SV_OPERATOR }}} // namespace nonstd::literals::string_view_literals #endif // // Extensions for std::string: // #if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS namespace nonstd { namespace sv_lite { // Exclude MSVC 14 (19.00): it yields ambiguous to_string(): #if nssv_CPP11_OR_GREATER && nssv_COMPILER_MSVC_VERSION != 140 template< class CharT, class Traits, class Allocator = std::allocator<CharT> > std::basic_string<CharT, Traits, Allocator> to_string( basic_string_view<CharT, Traits> v, Allocator const & a = Allocator() ) { return std::basic_string<CharT,Traits, Allocator>( v.begin(), v.end(), a ); } #else template< class CharT, class Traits > std::basic_string<CharT, Traits> to_string( basic_string_view<CharT, Traits> v ) { return std::basic_string<CharT, Traits>( v.begin(), v.end() ); } template< class CharT, class Traits, class Allocator > std::basic_string<CharT, Traits, Allocator> to_string( basic_string_view<CharT, Traits> v, Allocator const & a ) { return std::basic_string<CharT, Traits, Allocator>( v.begin(), v.end(), a ); } #endif // nssv_CPP11_OR_GREATER template< class CharT, class Traits, class Allocator > basic_string_view<CharT, Traits> to_string_view( std::basic_string<CharT, Traits, Allocator> const & s ) { return basic_string_view<CharT, Traits>( s.data(), s.size() ); } }} // namespace nonstd::sv_lite #endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS // // make types and algorithms available in namespace nonstd: // namespace nonstd { using sv_lite::basic_string_view; using sv_lite::string_view; using sv_lite::wstring_view; #if nssv_HAVE_WCHAR16_T using sv_lite::u16string_view; #endif #if nssv_HAVE_WCHAR32_T using sv_lite::u32string_view; #endif // literal "sv" using sv_lite::operator==; using sv_lite::operator!=; using sv_lite::operator<; using sv_lite::operator<=; using sv_lite::operator>; using sv_lite::operator>=; using sv_lite::operator<<; #if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS using sv_lite::to_string; using sv_lite::to_string_view; #endif } // namespace nonstd // 24.4.5 Hash support (C++11): // Note: The hash value of a string view object is equal to the hash value of // the corresponding string object. #if nssv_HAVE_STD_HASH #include <functional> namespace std { template<> struct hash< nonstd::string_view > { public: std::size_t operator()( nonstd::string_view v ) const nssv_noexcept { return std::hash<std::string>()( std::string( v.data(), v.size() ) ); } }; template<> struct hash< nonstd::wstring_view > { public: std::size_t operator()( nonstd::wstring_view v ) const nssv_noexcept { return std::hash<std::wstring>()( std::wstring( v.data(), v.size() ) ); } }; template<> struct hash< nonstd::u16string_view > { public: std::size_t operator()( nonstd::u16string_view v ) const nssv_noexcept { return std::hash<std::u16string>()( std::u16string( v.data(), v.size() ) ); } }; template<> struct hash< nonstd::u32string_view > { public: std::size_t operator()( nonstd::u32string_view v ) const nssv_noexcept { return std::hash<std::u32string>()( std::u32string( v.data(), v.size() ) ); } }; } // namespace std #endif // nssv_HAVE_STD_HASH nssv_RESTORE_WARNINGS() #endif // nssv_HAVE_STD_STRING_VIEW #endif // NONSTD_SV_LITE_H_INCLUDED
[ "maicolinux4@gmail.com" ]
maicolinux4@gmail.com
975c8b753a97d8b6d5e99bdf526bff1328388c0b
ae7e342049c7cdd7b33733eed9f3541a3cbf53aa
/meta-buffer/probs.cpp
7f18ac950a7f13804410189f294d018a0babf785
[]
no_license
Bored66/meta-buff
69fde144a6bc89fbaa39982f9aa965d2a5203667
512ea5b3774330b662c1805990426287c7593592
refs/heads/master
2020-05-17T10:08:20.632350
2019-06-07T15:19:41
2019-06-07T15:19:41
183,650,659
0
0
null
null
null
null
UTF-8
C++
false
false
7,046
cpp
#include "field_types.h" #include "field_type_utils.h" #include "extract_cmd_params_types.h" #include "cmd_field_info.h" #include "forward_cmd_params.h" #include "field_test.h" #include "field_helpers.h" #include "string_utils.h" #include "byte_stream.h" void basic_test(); void string_utils_test(); void cmd_prepare_test(); void crc_test(); void cmd_tests(); void find_field_test(); void probs() { //basic_test(); //cmd_tests(); crc_test(); cmd_prepare_test(); string_utils_test(); //byte_stream_test(); } void cmd_tests() { using test_cmd = Cmd1st; constexpr auto firstCmdInfo = get_cmd_field_info<test_cmd>(); size_t arr[firstCmdInfo.const_vals[0]];(void)arr; static_assert(firstCmdInfo.const_vals[0] == 170, "firstCmdInfo.const_vals[0] != 10"); static_assert(firstCmdInfo.const_vals[1] == 1, "firstCmdInfo.const_vals[0] != 1"); static_assert(firstCmdInfo.const_vals[2] == 0, "firstCmdInfo.const_vals[0] != 0"); for (uint32_t i = 0; i < firstCmdInfo.size(); i++) { std::cout << std::hex << std::uppercase << "0x" << uint32_t(firstCmdInfo.const_vals[i]) << ":" << std::dec << firstCmdInfo.field_size[i] << "="; } } void crc_test() { std::tuple_element<4, Cmd1st>::type::proc_crc(nullptr, 1); std::tuple_element<4, Cmd1st>::type::proc_type tt = std::tuple_element<4, Cmd1st>::type::proc_crc; tt(nullptr,3); } using src = std::tuple<byte_i_c<0x0>, uint8_t, int16_t, byte_i_c<0x01>, int64_t, byte_i_c<0x02>, float, byte_i_c<0x03>>; class Cmd1class : public tuple_holder<src> { //Cmd1class(tuple_holder<src>::TypeHolder & tuple):tuple_holder<src>(tuple){} }; using cmd1args = command_call<//uint8_t, uint32_t>;// decltype(get_cmd_field_types(Cmd1st{}))>; using cmd2args = command_call<//command_call<uint16_t, uint32_t>; decltype(get_cmd_field_types(Cmd2nd{}))>; using cmd3args = command_call<decltype(get_cmd_field_types(Cmd3rd{}))>; void cmd_prepare_test() { std::make_tuple<byte_i_c<170>, byte_i_c<1>, uint8_t, uint16_t,uint8_t> (byte_i_c<170>{},byte_i_c<1>{}, uint8_t(7), uint16_t(32), uint8_t(12)); std::cout << std::endl; using target = std::tuple<uint8_t, int16_t, int64_t, float>; constexpr auto tupleCmd1st = forward_params<Cmd1st>(75,'3'); //print_item_value(std::get<0>(tupleCmd1st)); print_flat_tuple(tupleCmd1st); auto datagram = tuple_to_datagram<datagram_size<Cmd1st>()>(tupleCmd1st); std::cout << std::endl; datagram.print_seq(); std::cout << std::endl; std::cout << "total_size(): " << datagram_size<Cmd1st>(); std::cout << std::endl; using res = extract_cmd_params_types_result<src>; using srcNoParams = std::tuple<byte_i_c<0x0>, byte_i_c<0x01>, byte_i_c<0x02>, byte_i_c<0x03>>; using target0 = void; using res2 = extract_cmd_params_types_result<srcNoParams>; static_assert(std::is_same<target0,res2>::value,""); static_assert(std::is_same<target,res>::value,""); static_assert(std::is_same<select_type_t<byte_i_c<0x01>::value,uint8_t,int8_t>, uint8_t>::value, ""); static_assert(std::is_same<select_type_t<not byte_i_c<0x01>::value,uint8_t,int8_t>, int8_t>::value, ""); src src1; Cmd1class cmd1; constexpr auto tupleCmd4 = forward_params<Cmd5th>(75,pod{115,'3',345}); print_flat_tuple(tupleCmd4); std::cout << "total_size(): " << datagram_size<Cmd5th>() ; /*{ auto datagram = tuple_to_datagram<datagram_size<Cmd5th>()>(tupleCmd4); datagram.print_seq(); }*/ std::cout << std::endl; } void basic_test() { constexpr MarkerField mf; constexpr bool f = field_type<typename std::tuple_element<4, Cmd1st>::type>::is_function; static_assert (f == false, "T"); static_assert (mf.name == markerFldName, "mf.name == marker"); static_assert (std::is_same<CrcField::type, uint8_t>::value, "is_same<CrcField::type"); static_assert (std::is_same<CrcField, std::tuple_element<4, Cmd1st>::type >::value, "is_same Crcfield"); static_assert(is_integral_const<std::integral_constant<uint8_t, 11>>::is_const, "not integral const"); static_assert(not is_integral_const<CrcField>::is_const, "integral const?"); using t1 = MarkerField::type; static_assert(is_integral_const<t1>::is_const, "not integral const"); auto val = t1::value; val++; using t2 = CrcField; static_assert(not is_integral_const<t2>::is_const, "integral const?"); //print_field_typeinfo<tuple_element_t<0, Cmd1st>>(); //print_field_typeinfo<CrcField>(); using t3 = tuple_element_t<0, Cmd1st>; t3 t3v;(void)t3v; static_assert(is_integral_const<t3::type>::is_const, "not integral const"); print_cmd_field_types(Cmd1st{}); print_cmd_field_types(Cmd2nd{}); print_cmd_field_types(Cmd5th{}); std::cout << std::endl; print_type_name<decltype(get_cmd_field_types(Cmd1st{}))>(); std::cout << std::endl; print_type_name<decltype(get_cmd_field_types(Cmd2nd{}))>(); std::cout << std::endl; print_type_name<decltype(get_cmd_field_types(Cmd5th{}))>(); std::cout << std::endl; print_field_typeinfo<tuple_element_t<4, Cmd5th>>(); } void string_utils_test() { using namespace str_utils_ce; print_type_name<cmd2args>();//test for str_copy_ce static_assert(str_equal_ce(DataField16().name, DataField16().name), "Not Equal"); static_assert(not str_equal_ce(DataField().name, DataField16().name), "Equal"); static_assert(not str_equal_ce(MarkerField().name, DataField16().name), "Equal"); static_assert(find_char_offset(" [][][][][]",'[')==2, "["); static_assert(find_char_offset("[][][][][]",'{')==-1, "{"); find_field_test(); static_assert(str_utils_ce::strlen_ce("aaaa"), "aaaa!=4"); } void find_field_test() { print_field_names(Cmd1st{}); static_assert(find_field_name_offset(Cmd1st{}, DataField16{}.name) == 3, "3"); static_assert(find_field_name_offset(Cmd1st{}, DataField16{}.name) != 2, "Not 2"); static_assert(find_field_name_offset(Cmd1st{}, DataField{}.name) == 2, "2"); static_assert(find_field_name_offset(Cmd1st{}, DataField32{}.name) == -1, "-1"); print_field_names(Cmd4th{}); std::cout << NobField{}.name << " offset: " << find_field_name_offset(Cmd4th{}, VarField_uint16().refFieldName) << " " << find_field_name_offset(Cmd4th{}, VarField_uint16().name) << " " << VarField_uint16().refFieldName; } extern inline uint8_t crc8(uint8_t*seq, size_t size) { (void)seq; std::cout << __PRETTY_FUNCTION__ << ":" << size << std::endl; return uint8_t(size); }
[ "edborovitski@gmail.com" ]
edborovitski@gmail.com
48d53a2f83954545ba490a6e7c68baf893108a50
708532ac7b556779b2d5c1cbdf973f9c4a9d66fd
/cyril/Selection.cc
83f3c3bd9de0a34e69551a503f5fff9c918d22d8
[]
no_license
EthericStd/projectcpp
37f575888042c303782d76a3972e14b06fd90f64
40c9da72b422521a416f266c2db08c94ab371745
refs/heads/master
2021-01-18T18:05:13.713327
2017-05-07T19:05:04
2017-05-07T19:05:04
86,841,798
0
0
null
null
null
null
UTF-8
C++
false
false
2,494
cc
#include<ctime> #include<cstdlib> #include<iostream> #include"Selection.h" Selection::Selection(int pN) { mN = pN; } float* get_sums(float* fitness, int N) { // retourne un tableau dont l'indice i est égal // à la somme des valeurs des indices précédants i // dans la tableau en paramètre // par exemple si fitness = [1, 2, 3] // la tableau retourné sera [1, 1+2, 1+2+3] float* tab = new float[N]; tab[0] = fitness[0]; for(int i=1;i<N;i++) { tab[i] = tab[i-1] + fitness[i]; } return tab; } float get_sum(float* tab, int N) { // retourne le dernier indice du tableau en paramètre float sum = tab[N-1]; return sum; } CPopulation< CChemin<CVille> > Selection::roulette(CPopulation< CChemin<CVille> >& Pop) { //récupère la fitness de chaque chemins dans la tableau fitness int N = Pop.get_lenght(); float fitness[N]; for(int i=0;i<N;i++) { fitness[i] = Pop[i].Fitness(); } // cette partie effectue une boucle en mN = le nombre de chemins sélectionnés // pour créer le tableau des chemins sélectionnés // le principe est la suivant : // - on crée un tableau tab qui est la somme des "indices précédants" // du tableau fitness (voir fonction get_sums) // - on choisi un nombre aléatoire entre 0 et la la dernière valeur de tab // - on regarde chaque valeur de tab dans l'odre croissant des indices // - on retient l'indice de la première valeur trouvée // qui est supérieure au nombre aléatoire choisit // - cet indice sera l'indice du chemin dans la population choisit par la sélection // - on recommence les opérations jusqu'à avoir le nombre de chemins voulu // ( on pense égalament à ne pas choisir 2 fois le même chemin) CChemin<CVille> tC[mN]; float* tab = get_sums(fitness, N); float sum = get_sum(tab, N); float ran = (((float) rand()) / ((float) RAND_MAX)) * sum; for(int j=0;j<mN;j++) { for(int k=0;k<N;k++) { if(ran < tab[k]) { tC[j] = Pop[k]; fitness[k] = 0; tab = get_sums(fitness, N); sum = get_sum(tab, N); ran = (((float) rand()) / ((float) RAND_MAX)) * sum; k = N; } } } CPopulation< CChemin<CVille> > Pop1(tC ,mN); return Pop1; }
[ "cysou3@laposte.net" ]
cysou3@laposte.net
22ccfa5c383876469963bf0ef832431caa540936
fbb03f0345a0ac574a1696449ec756c308b4c5c7
/Source/ProjectFPSTest/FPSGameModeBase.cpp
1c2af378e707194437bf5663d4c214391c5146be
[]
no_license
BlancLohan/GALandProject
bccdb4712c57b01505afb39b55a9d41054fc3a0b
6501545c5fa7c32f6863112ce5c37374ea28b909
refs/heads/main
2023-03-29T10:46:57.006496
2021-04-06T19:43:58
2021-04-06T19:43:58
355,117,700
0
0
null
null
null
null
UTF-8
C++
false
false
111
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "FPSGameModeBase.h"
[ "45771234+RhadamanthysGH@users.noreply.github.com" ]
45771234+RhadamanthysGH@users.noreply.github.com
857d9858b2320b7310c4c049a6db1e5d8961fa54
ffd02605bdd357feae1d81a30b875debee43ee82
/src/Model/Bone.cpp
e9ea6251ed59dfac1813cfeafb5fe11baa803626
[]
no_license
janhsimon/AmbientOcclusion
45c4c26e1215419c4dad7df4bab21224e248f5b4
8c44d6f783fa1b4fa416049d7400b8b6d530c4f7
refs/heads/master
2021-06-04T20:12:17.912798
2016-08-21T14:57:13
2016-08-21T14:57:13
63,185,305
2
0
null
null
null
null
UTF-8
C++
false
false
576
cpp
#include "Bone.hpp" #include "MathHelper.hpp" Bone::Bone(const std::string &name, glm::mat4 &inverseBindPoseMatrix) { this->name = name; this->inverseBindPoseMatrix = inverseBindPoseMatrix; } glm::mat4 Bone::getFinalMatrix() const { // TODO: boneMatrix used to be an aiMatrix4x4 which is transposed, check if this code needs to be flipped! glm::mat4 boneMatrix = flatMatrix; Bone *currentBone = parent; while (currentBone) { boneMatrix = currentBone->flatMatrix * boneMatrix; currentBone = currentBone->parent; } return boneMatrix * inverseBindPoseMatrix; }
[ "checker_at_work@web.de" ]
checker_at_work@web.de
c7bc6a2fac7d46e951c82403322ff12544c518e5
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/06112002/Include/arch/Win32/OpenGL/WGLGraphics.h
3939153d7c55622420c237e2b443db2e938d3b1f
[]
no_license
christhomas/fusionengine
286b33f2c6a7df785398ffbe7eea1c367e512b8d
95422685027bb19986ba64c612049faa5899690e
refs/heads/master
2020-04-05T22:52:07.491706
2006-10-24T11:21:28
2006-10-24T11:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
499
h
#ifndef _WGLGRAPHICS_H_ #define _WGLGRAPHICS_H_ #include <OpenGL/OGLGraphics.h> #include <Fusion.h> /** @ingroup OGL_Graphics_Group * @brief Derived OGLGraphics class for the Win32 Platform */ class WGLGraphics: public OGLGraphics{ public: WGLGraphics (); virtual ~WGLGraphics (); virtual bool SetMode (int w, int h, bool f); virtual bool RestoreMode (void); virtual void * GetExtension (char *extension); }; #endif // #ifndef _WGLGRAPHICS_H_
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7
507dffe03562ca7358735389c67c8f8241932403
b725653e3d882f761e63cc3cd0a081e2fcbab091
/include/ozo/impl/transaction.h
e5b5f5da016bf655cad844eae6a03f3a14026b53
[]
no_license
nuertey/ozo
2d01806d201c5e63b8a8c8b3ac761734c0e3d026
58da2a6f5a14c7d6c071fcd82321ecfcb1aafe34
refs/heads/master
2020-04-14T17:20:12.294883
2018-12-27T13:55:35
2018-12-29T17:17:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,658
h
#pragma once #include <ozo/connection.h> namespace ozo::impl { template <typename T> class transaction { friend unwrap_connection_impl<transaction>; public: static_assert(Connection<T>, "T is not a Connection"); transaction() = default; transaction(T connection) : impl(std::make_shared<impl_type>(std::move(connection))) {} ~transaction() { const auto c = std::move(impl); if (c.use_count() == 1 && c->connection) { close_connection(*c->connection); } } void take_connection(T& out) { out = std::move(*impl->connection); impl->connection = __OZO_STD_OPTIONAL<T>{}; impl.reset(); } bool has_connection() const { return impl != nullptr && impl->has_connection(); } operator bool() const { return has_connection(); } private: struct impl_type { __OZO_STD_OPTIONAL<T> connection; impl_type(T&& connection) : connection(std::move(connection)) {} bool has_connection() const { return connection.has_value() && static_cast<bool>(connection); } }; std::shared_ptr<impl_type> impl; }; template <typename T, typename = Require<Connection<T>>> auto make_transaction(T&& conn) { return transaction<std::decay_t<T>> {std::forward<T>(conn)}; } } // namespace ozo::impl namespace ozo { template <typename T> struct unwrap_connection_impl<impl::transaction<T>> { template <typename Transaction> static constexpr decltype(auto) apply(Transaction&& self) noexcept { return unwrap_connection(*self.impl->connection); } }; } // namespace ozo
[ "orionstation@yandex.ru" ]
orionstation@yandex.ru
cf7189f0581e1709699fcb60525933a4dc466299
75ca48995317737de384d68e6c31c62e1f8cc977
/RPG v5.0/Itemshop.h
3f3bba304021b80c27d535682837271f773c06dc
[]
no_license
mister9819/RPG-v5.0
38b1f6dcf0a9fc9163f342bab7e705658e2afd0b
6b5463bf0ed8b0f341b2f50e1d09436c743883b8
refs/heads/master
2020-04-17T03:57:08.438854
2019-01-17T10:38:38
2019-01-17T10:38:38
166,207,045
0
0
null
null
null
null
UTF-8
C++
false
false
440
h
#ifndef ITEMSHOP_H #define ITEMSHOP_H #include <iostream> #include <string> #include <stdlib.h> #include <cstdlib> #include <limits> #include <list> #include "Shop.h" #include "Player.h" #include "Item.h" class Itemshop { public: Itemshop(); void initShops(list<Shop> &shops); void enterShop(Player &player, Shop &shops); int getInt(); void callShop(Player &player, list<Shop> &shops); }; #endif // ITEMSHOP_H
[ "noreply@github.com" ]
noreply@github.com
86737d5a94267fc79e90de03f0b4f31de8553fd5
abff3f461cd7d740cfc1e675b23616ee638e3f1e
/opencascade/AIS_KindOfUnit.hxx
835bfa24dec6c1c0194d230c43a84b67481e0cb7
[ "Apache-2.0" ]
permissive
CadQuery/pywrap
4f93a4191d3f033f67e1fc209038fc7f89d53a15
f3bcde70fd66a2d884fa60a7a9d9f6aa7c3b6e16
refs/heads/master
2023-04-27T04:49:58.222609
2023-02-10T07:56:06
2023-02-10T07:56:06
146,502,084
22
25
Apache-2.0
2023-05-01T12:14:52
2018-08-28T20:18:59
C++
UTF-8
C++
false
false
1,060
hxx
// Created on: 1996-12-11 // Created by: Robert COUBLANC // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _AIS_KindOfUnit_HeaderFile #define _AIS_KindOfUnit_HeaderFile //! Declares the type of Interactive Object unit. enum AIS_KindOfUnit { AIS_TOU_LENGTH, AIS_TOU_SURFACE, AIS_TOU_VOLUME, AIS_TOU_PLANE_ANGLE, AIS_TOU_SOLID_ANGLE, AIS_TOU_MASS, AIS_TOU_FORCE, AIS_TOU_TIME }; #endif // _AIS_KindOfUnit_HeaderFile
[ "adam.jan.urbanczyk@gmail.com" ]
adam.jan.urbanczyk@gmail.com
d7cab885daa774df502e1b3891b50fbafd9d7c3d
8ab889aefd7c5ba862aaf4819ae9f0f4ecb3b05d
/exercise system/sinh_hoan vi/bai1.cpp
06523e07861d7af260c243c163c88a4997fa24c1
[]
no_license
hoangngo2k/CTDL
5bf1b4f70e70365d81ea3d896dd1c1243aad01d5
f09b440cc7c3023a671c2892a7b997f5547e0f4d
refs/heads/master
2023-08-28T12:31:39.114825
2021-10-24T14:57:16
2021-10-24T14:57:16
284,079,401
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
#include<bits/stdc++.h> using namespace std; string s; int main() { int t; cin>>t; while(t--){ cin>>s; int n=s.length()-1; while(s[n]=='1'){ s[n]='0'; n--; } if(n>=0){ s[n]='1'; } cout<<s<<endl; } }
[ "hoangngo2k0@gmail.com" ]
hoangngo2k0@gmail.com
c8fa2efaed929aaa31e56db1f82b2c4403f4dbae
2710157eabaa334c9582152d5e5087ba87876638
/src/InputManager.cpp
ee712c7a744b298d0ddad0ccd935e77b81e41028
[]
no_license
GNGenesis/Lucity
f4fed328fb2b65f18a68ac6cc2528220fb1d97d8
03fa5cf930ba0ad9157250477f4072d5f6868c33
refs/heads/master
2020-03-18T07:24:06.006109
2018-07-10T21:07:11
2018-07-10T21:07:11
134,450,080
1
2
null
null
null
null
UTF-8
C++
false
false
4,256
cpp
#include "InputManager.h" #include "Camera.h" #include "GameData.h" std::unordered_map<int, bool> InputManager::keyState; std::unordered_map<int, int> InputManager::keyUpdate; bool InputManager::toggleMouse = false; bool InputManager::mouseState [6]; int InputManager::mouseUpdate [6]; int InputManager::mouseWheel; int InputManager::mouseX; int InputManager::mouseY; int InputManager::lastKey; int InputManager::updateCounter; bool InputManager::quitRequested = false; //Joystick Related std::vector<SDL_Joystick*> InputManager::joysticks; void InputManager::Update() { SDL_Event event; SDL_GetMouseState(&mouseX, &mouseY); mouseWheel = 0; mouseX += Camera::pos.x; mouseY += Camera::pos.y; updateCounter++; while(SDL_PollEvent(&event)) { if(event.key.repeat != 1) { if(event.type == SDL_QUIT) quitRequested = true; if(event.type == SDL_MOUSEMOTION) { toggleMouse = true; } if(event.type == SDL_MOUSEBUTTONDOWN) { mouseState[event.button.button] = true; mouseUpdate[event.button.button] = updateCounter; } if(event.type == SDL_MOUSEBUTTONUP) { mouseState[event.button.button] = false; mouseUpdate[event.button.button] = updateCounter; } if(event.type == SDL_MOUSEWHEEL) { mouseWheel = event.wheel.y; if(event.wheel.y > 0) { } else if(event.wheel.y < 0) { } } if(event.type == SDL_KEYDOWN) { toggleMouse = false; lastKey = event.key.keysym.sym; keyState[event.key.keysym.sym] = true; keyUpdate[event.key.keysym.sym] = updateCounter; } if(event.type == SDL_KEYUP) { keyState[event.key.keysym.sym] = false; keyUpdate[event.key.keysym.sym] = updateCounter; } } } } bool InputManager::KeyPress(int key) { return (keyUpdate[key] == updateCounter) ? (keyState[key]) : false; } bool InputManager::KeyRelease(int key) { return (keyUpdate[key] == updateCounter) ? (!keyState[key]) : false; } bool InputManager::IsKeyDown(int key) { return keyState[key]; } bool InputManager::MousePress(int button) { return (mouseUpdate[button] == updateCounter) ? (mouseState[button]) : false; } bool InputManager::MouseRelease(int button) { return (mouseUpdate[button] == updateCounter) ? (!mouseState[button]) : false; } bool InputManager::IsMouseDown(int button) { return mouseState[button]; } int InputManager::GetLastKey() { GameData::key = lastKey; return lastKey; } void InputManager::ResetLastKey() { lastKey = NULL; } int InputManager::GetMouseWheel() { return mouseWheel; } int InputManager::GetMouseX() { return mouseX; } int InputManager::GetMouseY() { return mouseY; } Vec2 InputManager::GetMousePos() { return Vec2(mouseX, mouseY); } bool InputManager::GetToggle() { return toggleMouse; } bool InputManager::QuitRequested() { return quitRequested; } //Joystick Related void InputManager::LoadJoysticks() { for(int i = 0; i < SDL_NumJoysticks(); i++) { AddJoystick(SDL_JoystickOpen(i)); if(!GetJoystick(i)) printf("Warning: Unable to open game controller! SDL Error: %s\n", SDL_GetError()); } } void InputManager::CloseJoysticks() { for(unsigned int i = 0; i < joysticks.size(); i++) SDL_JoystickClose(joysticks[i]); joysticks.clear(); } void InputManager::AddJoystick(SDL_Joystick* joystick) { joysticks.emplace_back(joystick); } SDL_Joystick* InputManager::GetJoystick(unsigned int nJoy) { if(nJoy < joysticks.size()) return joysticks[nJoy]; else return nullptr; } Vec2 InputManager::GetJoyAxis(unsigned int nJoy) { if(nJoy < joysticks.size()) return Vec2(SDL_JoystickGetAxis(joysticks[nJoy], 0), SDL_JoystickGetAxis(joysticks[nJoy], 1)); else return Vec2(); } int InputManager::JoyAxisAngle(unsigned int nJoy) { if(nJoy < joysticks.size()) return Vec2().GetAngle(GetJoyAxis(nJoy)/32768); else return 0; } bool InputManager::JoyAxisEvent(unsigned int nJoy) { if(nJoy < joysticks.size()) return (GetJoyAxis(nJoy).x != 0 || GetJoyAxis(nJoy).y != 0); else return false; } bool InputManager::IsJButtonDown(unsigned int nJoy, int jbutton) { return SDL_JoystickGetButton(joysticks[nJoy], jbutton); }
[ "gabriel_halabi@hotmail.com" ]
gabriel_halabi@hotmail.com
47c1cc9d664b84dc307506417072064f77d8bcfb
303d0481fa05bcfd1a004ee4eae0f96f17ba0796
/cpp_practices/memory_ordering_examples/relaxed_ordering.cpp
12f815807f5432d633f0f5a25939ee09161279ae
[ "BSD-3-Clause" ]
permissive
Maverobot/cpp_playground
8be37116ae163562119b32d837e4bc416cbfe87e
394082cffd9a0d4099fce709ef90d5c37054496a
refs/heads/master
2023-08-17T07:27:48.700768
2023-08-16T07:11:04
2023-08-16T07:11:04
188,075,524
10
3
null
2019-09-08T14:29:58
2019-05-22T16:26:28
C++
UTF-8
C++
false
false
1,844
cpp
// Listing 5.6 in "C++ Concurrency in Action, Second Edition" #include <atomic> #include <iostream> #include <thread> std::atomic<int> x; std::atomic<int> y; std::atomic<int> z; std::atomic<bool> go; unsigned const loop_count = 10; struct ReadValues { int x; int y; int z; }; ReadValues values1[loop_count]; ReadValues values2[loop_count]; ReadValues values3[loop_count]; ReadValues values4[loop_count]; ReadValues values5[loop_count]; void increment(std::atomic<int>* var_to_inc, ReadValues* values) { while (!go) { std::this_thread::yield(); } for (unsigned i = 0; i < loop_count; i++) { values[i].x = x.load(std::memory_order_relaxed); values[i].y = y.load(std::memory_order_relaxed); values[i].z = z.load(std::memory_order_relaxed); var_to_inc->store(i + 1, std::memory_order_relaxed); std::this_thread::yield(); } } void readValues(ReadValues* values) { while (!go) { std::this_thread::yield(); } for (unsigned i = 0; i < loop_count; i++) { values[i].x = x.load(std::memory_order_relaxed); values[i].y = y.load(std::memory_order_relaxed); values[i].z = z.load(std::memory_order_relaxed); std::this_thread::yield(); } } void print(ReadValues* v) { for (unsigned i = 0; i < loop_count; i++) { if (i) { std::cout << ", "; } std::cout << "(" << v[i].x << ", " << v[i].y << ", " << v[i].z << ")"; } std::cout << "\n"; } int main(int argc, char* argv[]) { std::thread t1(increment, &x, values1); std::thread t2(increment, &y, values2); std::thread t3(increment, &z, values3); std::thread t4(readValues, values4); std::thread t5(readValues, values5); go = true; t5.join(); t4.join(); t3.join(); t2.join(); t1.join(); print(values1); print(values2); print(values3); print(values4); print(values5); return 0; }
[ "quzhengrobot@gmail.com" ]
quzhengrobot@gmail.com
b6082680370943add1504d6968512d08cdc335fd
b145f1ab6884f55d240c733f7de08fdc80b624d1
/raspi_main.cpp
9e09b4699b2b222d79098610152a2f76c1614797
[]
no_license
Astronutmers/Object_Tracking_Sekolah
d9a576f7fef6a8522bfcb2e788cc02b7eae3c647
bf31bc879fab4fe80eec1c39431419ba1ec9a096
refs/heads/master
2021-01-20T14:29:07.551423
2017-05-08T11:03:17
2017-05-08T11:03:17
90,616,546
0
0
null
null
null
null
UTF-8
C++
false
false
22,461
cpp
#include "CMT.h" #include "gui.h" #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <fstream> #include <sstream> #include <cstdio> #include <string> #include <stdio.h> #include <vector> #ifdef __GNUC__ #include <getopt.h> #else #include "getopt/getopt.h" #endif using cmt::CMT; using cv::imread; using cv::namedWindow; using cv::Scalar; using cv::VideoCapture; using cv::waitKey; using std::cerr; using std::istream; using std::ifstream; using std::stringstream; using std::ofstream; using std::cout; using std::min_element; using std::max_element; using std::endl; using ::atof; using namespace cv; using namespace std; static string WIN_NAME = "CMT"; static string WIN_NAME2 = "CMT2"; static string OUT_FILE_COL_HEADERS = "Frame,Timestamp (ms),Active points,"\ "Bounding box centre X (px),Bounding box centre Y (px),"\ "Bounding box width (px),Bounding box height (px),"\ "Bounding box rotation (degrees),"\ "Bounding box vertex 1 X (px),Bounding box vertex 1 Y (px),"\ "Bounding box vertex 2 X (px),Bounding box vertex 2 Y (px),"\ "Bounding box vertex 3 X (px),Bounding box vertex 3 Y (px),"\ "Bounding box vertex 4 X (px),Bounding box vertex 4 Y (px)"; //initial min and max HSV filter values. //these will be changed using trackbars int H_MIN = 0; int H_MAX = 256; int S_MIN = 0; int S_MAX = 256; int V_MIN = 0; int V_MAX = 256; //default capture width and height const int FRAME_WIDTH = 320; const int FRAME_HEIGHT = 240; //max number of objects to be detected in frame const int MAX_NUM_OBJECTS = 50; //minimum and maximum object area const int MIN_OBJECT_AREA = 20 * 20; const int MAX_OBJECT_AREA = FRAME_HEIGHT*FRAME_WIDTH / 1.5; //names that will appear at the top of each window const string windowName = "Original Image"; const string windowName1 = "HSV Image"; const string windowName2 = "Thresholded Image"; const string windowName3 = "After Morphological Operations"; const string trackbarWindowName = "Trackbars"; void on_trackbar(int, void*) {//This function gets called whenever a // trackbar position is changed } string intToString(int number) { std::stringstream ss; ss << number; return ss.str(); } /**void createTrackbars() { //create window for trackbars namedWindow(trackbarWindowName, 0); //create memory to store trackbar name on window char TrackbarName[50]; sprintf_s(TrackbarName, "H_MIN", H_MIN); sprintf_s(TrackbarName, "H_MAX", H_MAX); sprintf_s(TrackbarName, "S_MIN", S_MIN); sprintf_s(TrackbarName, "S_MAX", S_MAX); sprintf_s(TrackbarName, "V_MIN", V_MIN); sprintf_s(TrackbarName, "V_MAX", V_MAX); //create trackbars and insert them into window //3 parameters are: the address of the variable that is changing when the trackbar is moved(eg.H_LOW), //the max value the trackbar can move (eg. H_HIGH), //and the function that is called whenever the trackbar is moved(eg. on_trackbar) // ----> ----> ----> createTrackbar("H_MIN", trackbarWindowName, &H_MIN, H_MAX, on_trackbar); createTrackbar("H_MAX", trackbarWindowName, &H_MAX, H_MAX, on_trackbar); createTrackbar("S_MIN", trackbarWindowName, &S_MIN, S_MAX, on_trackbar); createTrackbar("S_MAX", trackbarWindowName, &S_MAX, S_MAX, on_trackbar); createTrackbar("V_MIN", trackbarWindowName, &V_MIN, V_MAX, on_trackbar); createTrackbar("V_MAX", trackbarWindowName, &V_MAX, V_MAX, on_trackbar); }**/ void drawObject(int x, int y, Mat &frame) { //use some of the openCV drawing functions to draw crosshairs //on your tracked image! //UPDATE:JUNE 18TH, 2013 //added 'if' and 'else' statements to prevent //memory errors from writing off the screen (ie. (-25,-25) is not within the window!) circle(frame, Point(x, y), 20, Scalar(0, 255, 0), 2); if (y - 25>0) line(frame, Point(x, y), Point(x, y - 25), Scalar(0, 255, 0), 2); else line(frame, Point(x, y), Point(x, 0), Scalar(0, 255, 0), 2); if (y + 25<FRAME_HEIGHT) line(frame, Point(x, y), Point(x, y + 25), Scalar(0, 255, 0), 2); else line(frame, Point(x, y), Point(x, FRAME_HEIGHT), Scalar(0, 255, 0), 2); if (x - 25>0) line(frame, Point(x, y), Point(x - 25, y), Scalar(0, 255, 0), 2); else line(frame, Point(x, y), Point(0, y), Scalar(0, 255, 0), 2); if (x + 25<FRAME_WIDTH) line(frame, Point(x, y), Point(x + 25, y), Scalar(0, 255, 0), 2); else line(frame, Point(x, y), Point(FRAME_WIDTH, y), Scalar(0, 255, 0), 2); putText(frame, intToString(x) + "," + intToString(y), Point(x, y + 30), 1, 1, Scalar(0, 255, 0), 2); } void morphOps(Mat &thresh) { //create structuring element that will be used to "dilate" and "erode" image. //the element chosen here is a 3px by 3px rectangle Mat erodeElement = getStructuringElement(MORPH_RECT, Size(3, 3)); //dilate with larger element so make sure object is nicely visible Mat dilateElement = getStructuringElement(MORPH_RECT, Size(8, 8)); erode(thresh, thresh, erodeElement); erode(thresh, thresh, erodeElement); dilate(thresh, thresh, dilateElement); dilate(thresh, thresh, dilateElement); } void trackFilteredObject(int &x, int &y, Mat threshold, Mat &cameraFeed) { Mat temp; threshold.copyTo(temp); //these two vectors needed for output of findContours vector< vector<Point> > contours; vector<Vec4i> hierarchy; //find contours of filtered image using openCV findContours function findContours(temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); //use moments method to find our filtered object double refArea = 0; bool objectFound = false; if (hierarchy.size() > 0) { int numObjects = hierarchy.size(); //if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter if (numObjects<MAX_NUM_OBJECTS) { for (int index = 0; index >= 0; index = hierarchy[index][0]) { Moments moment = moments((cv::Mat)contours[index]); double area = moment.m00; //if the area is less than 20 px by 20px then it is probably just noise //if the area is the same as the 3/2 of the image size, probably just a bad filter //we only want the object with the largest area so we safe a reference area each //iteration and compare it to the area in the next iteration. if (area>MIN_OBJECT_AREA && area<MAX_OBJECT_AREA && area>refArea) { x = moment.m10 / area; y = moment.m01 / area; objectFound = true; } else objectFound = false; } //let user know you found an object if (objectFound == true) { putText(cameraFeed, "Tracking Object", Point(0, 50), 2, 1, Scalar(0, 255, 0), 2); //draw object location on screen drawObject(x, y, cameraFeed); } } else putText(cameraFeed, "TOO MUCH NOISE! ADJUST FILTER", Point(0, 50), 1, 2, Scalar(0, 0, 255), 2); } } int color(int argc, char* argv[]) { //some boolean variables for different functionality within this //program bool trackObjects = true; bool useMorphOps = true; //Matrix to store each frame of the webcam feed Mat cameraFeed; //matrix storage for HSV image Mat HSV; //matrix storage for binary threshold image Mat threshold; //x and y values for the location of the object int x = 0, y = 0; //create slider bars for HSV filtering //RcreateTrackbars(); //video capture object to acquire webcam feed VideoCapture capture; //open capture object at location zero (default location for webcam) capture.open(0); //set height and width of capture frame capture.set(CV_CAP_PROP_FRAME_WIDTH, FRAME_WIDTH); capture.set(CV_CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT); //start an infinite loop where webcam feed is copied to cameraFeed matrix //all of our operations will be performed within this loop while (1) { //store image to matrix capture.read(cameraFeed); //convert frame from BGR to HSV colorspace cvtColor(cameraFeed, HSV, COLOR_BGR2HSV); //filter HSV image between values and store filtered image to //threshold matrix inRange(HSV, Scalar(123, 77, 0), Scalar(217, 256, 256), threshold); //perform morphological operations on thresholded image to eliminate noise //and emphasize the filtered object(s) if (useMorphOps) morphOps(threshold); //pass in thresholded frame to our object tracking function //this function will return the x and y coordinates of the //filtered object if (trackObjects) trackFilteredObject(x, y, threshold, cameraFeed); //show frames imshow(windowName2, threshold); imshow(windowName, cameraFeed); //Rimshow(windowName1, HSV); //delay 30ms so that screen can refresh. //image will not appear without this waitKey() command waitKey(30); } return 0; } vector<float> getNextLineAndSplitIntoFloats(istream& str) { vector<float> result; string line; getline(str,line); stringstream lineStream(line); string cell; while(getline(lineStream,cell,',')) { result.push_back(atof(cell.c_str())); } return result; } int display(Mat im, CMT & cmt) { //Visualize the output //It is ok to draw on im itself, as CMT only uses the grayscale image for(size_t i = 0; i < cmt.points_active.size(); i++) { circle(im, cmt.points_active[i], 2, Scalar(255,0,0)); } Point2f vertices[4]; cmt.bb_rot.points(vertices); for (int i = 0; i < 4; i++) { line(im, vertices[i], vertices[(i+1)%4], Scalar(255,0,0)); } imshow(WIN_NAME, im); return waitKey(5); } int display2(Mat im, CMT & cmt) { //Visualize the output //It is ok to draw on im itself, as CMT only uses the grayscale image for(size_t i = 0; i < cmt.points_active.size(); i++) { circle(im, cmt.points_active[i], 2, Scalar(255,0,0)); } Point2f vertices[4]; cmt.bb_rot.points(vertices); for (int i = 0; i < 4; i++) { line(im, vertices[i], vertices[(i+1)%4], Scalar(255,0,0)); } imshow(WIN_NAME2, im); return waitKey(5); } string write_rotated_rect(RotatedRect rect) { Point2f verts[4]; rect.points(verts); stringstream coords; coords << rect.center.x << "," << rect.center.y << ","; coords << rect.size.width << "," << rect.size.height << ","; coords << rect.angle << ","; for (int i = 0; i < 4; i++) { coords << verts[i].x << "," << verts[i].y; if (i != 3) coords << ","; } return coords.str(); } int facetracker1 (int argc, char **argv) { //Create a CMT object CMT cmt, cmt2; //Initialization bounding box Rect rect,rect2; //Parse args int challenge_flag = 0; int loop_flag = 0; int verbose_flag = 0; int bbox_flag = 0; int skip_frames = 0; int skip_msecs = 0; int output_flag = 0; string input_path; string output_path; const int FRAME_WIDTH = 640; const int FRAME_HEIGHT = 480; const int detector_cmd = 1000; const int descriptor_cmd = 1001; const int bbox_cmd = 1002; const int no_scale_cmd = 1003; const int with_rotation_cmd = 1004; const int skip_cmd = 1005; const int skip_msecs_cmd = 1006; const int output_file_cmd = 1007; struct option longopts[] = { //No-argument options {"challenge", no_argument, &challenge_flag, 1}, {"loop", no_argument, &loop_flag, 1}, {"verbose", no_argument, &verbose_flag, 1}, {"no-scale", no_argument, 0, no_scale_cmd}, {"with-rotation", no_argument, 0, with_rotation_cmd}, //Argument options {"bbox", required_argument, 0, bbox_cmd}, {"detector", required_argument, 0, detector_cmd}, {"descriptor", required_argument, 0, descriptor_cmd}, {"output-file", required_argument, 0, output_file_cmd}, {"skip", required_argument, 0, skip_cmd}, {"skip-msecs", required_argument, 0, skip_msecs_cmd}, {0, 0, 0, 0} }; int index = 0; int c; while((c = getopt_long(argc, argv, "v", longopts, &index)) != -1) { switch (c) { case 'v': verbose_flag = true; break; case bbox_cmd: { //TODO: The following also accepts strings of the form %f,%f,%f,%fxyz... string bbox_format = "%f,%f,%f,%f"; float x,y,w,h; int ret = sscanf(optarg, bbox_format.c_str(), &x, &y, &w, &h); if (ret != 4) { cerr << "bounding box must be given in format " << bbox_format << endl; return 1; } bbox_flag = 1; rect = Rect(x,y,w,h); } break; case detector_cmd: cmt.str_detector = optarg; break; case descriptor_cmd: cmt.str_descriptor = optarg; break; case output_file_cmd: output_path = optarg; output_flag = 1; break; case skip_cmd: { int ret = sscanf(optarg, "%d", &skip_frames); if (ret != 1) { skip_frames = 0; } } break; case skip_msecs_cmd: { int ret = sscanf(optarg, "%d", &skip_msecs); if (ret != 1) { skip_msecs = 0; } } break; case no_scale_cmd: cmt.consensus.estimate_scale = false; break; case with_rotation_cmd: cmt.consensus.estimate_rotation = true; break; case '?': return 1; } } // Can only skip frames or milliseconds, not both. if (skip_frames > 0 && skip_msecs > 0) { cerr << "You can only skip frames, or milliseconds, not both." << endl; return 1; } //One argument remains if (optind == argc - 1) { input_path = argv[optind]; } else if (optind < argc - 1) { cerr << "Only one argument is allowed." << endl; return 1; } //Set up logging FILELog::ReportingLevel() = verbose_flag ? logDEBUG : logINFO; Output2FILE::Stream() = stdout; //Log to stdout //Challenge mode if (challenge_flag) { //Read list of images ifstream im_file("images.txt"); vector<string> files; string line; while(getline(im_file, line )) { files.push_back(line); } //Read region ifstream region_file("region.txt"); vector<float> coords = getNextLineAndSplitIntoFloats(region_file); if (coords.size() == 4) { rect = Rect(coords[0], coords[1], coords[2], coords[3]); } else if (coords.size() == 8) { //Split into x and y coordinates vector<float> xcoords; vector<float> ycoords; for (size_t i = 0; i < coords.size(); i++) { if (i % 2 == 0) xcoords.push_back(coords[i]); else ycoords.push_back(coords[i]); } float xmin = *min_element(xcoords.begin(), xcoords.end()); float xmax = *max_element(xcoords.begin(), xcoords.end()); float ymin = *min_element(ycoords.begin(), ycoords.end()); float ymax = *max_element(ycoords.begin(), ycoords.end()); rect = Rect(xmin, ymin, xmax-xmin, ymax-ymin); cout << "Found bounding box" << xmin << " " << ymin << " " << xmax-xmin << " " << ymax-ymin << endl; } else { cerr << "Invalid Bounding box format" << endl; return 0; } //Read first image Mat im0 = imread(files[0]); Mat im0_gray; cvtColor(im0, im0_gray, CV_BGR2GRAY); //Initialize cmt cmt.initialize(im0_gray, rect); //Write init region to output file ofstream output_file("output.txt"); output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl; //Process images, write output to file for (size_t i = 1; i < files.size(); i++) { FILE_LOG(logINFO) << "Processing frame " << i << "/" << files.size(); Mat im = imread(files[i]); Mat im_gray; cvtColor(im, im_gray, CV_BGR2GRAY); cmt.processFrame(im_gray); if (verbose_flag) { display(im, cmt); } rect = cmt.bb_rot.boundingRect(); output_file << rect.x << ',' << rect.y << ',' << rect.width << ',' << rect.height << std::endl; } output_file.close(); return 0; } //Normal mode //Create window namedWindow(WIN_NAME); waitKey(30); //namedWindow(WIN_NAME2); VideoCapture cap; waitKey(30); bool show_preview = true; //If no input was specified if (input_path.length() == 0) { cap.open(0); //Open default camera device waitKey(30); cap.set(CV_CAP_PROP_FRAME_WIDTH,180); cap.set(CV_CAP_PROP_FRAME_HEIGHT,135); cap.set(CV_CAP_PROP_FPS,10); waitKey(30); //cap2.open(2); } //Else open the video specified by input_path else { cap.open(input_path); if (skip_frames > 0) { cap.set(CV_CAP_PROP_POS_FRAMES, skip_frames); } if (skip_msecs > 0) { cap.set(CV_CAP_PROP_POS_MSEC, skip_msecs); // Now which frame are we on? skip_frames = (int) cap.get(CV_CAP_PROP_POS_FRAMES); } show_preview = false; } //If it doesn't work, stop if(!cap.isOpened()) { cerr << "Unable to open video capture." << endl; return -1; } //Show preview until key is pressed while (show_preview) { Mat preview; //preview2; cap >> preview; waitKey(30); //cap2 >> preview2; screenLog(preview, "Press a key to start selecting an object."); imshow(WIN_NAME, preview); waitKey(30); //imshow(WIN_NAME2, preview2); char k = waitKey(10); if (k != -1) { show_preview = false; } } //Get initial image Mat im0;//im02; waitKey(30); cap >> im0; waitKey(30); //cap2 >> im02; //If no bounding was specified, get it from user if (!bbox_flag) { rect = getRect(im0, WIN_NAME); waitKey(30); //rect2 = getRect(im02, WIN_NAME2); } FILE_LOG(logINFO) << "Using " << rect.x << "," << rect.y << "," << rect.width << "," << rect.height << " as initial bounding box."; //Convert im0 to grayscale Mat im0_gray; //im0_gray2; if (im0.channels() > 1 ) { //|| im02.channels() cvtColor(im0, im0_gray, CV_BGR2GRAY); //cvtColor(im02, im0_gray2, CV_BGR2GRAY); } else { im0_gray = im0; //im0_gray2 = im02; } //Initialize CMT cmt.initialize(im0_gray, rect); //cmt2.initialize(im0_gray2, rect2); int frame = skip_frames; //Open output file. ofstream output_file; if (output_flag) { int msecs = (int) cap.get(CV_CAP_PROP_POS_MSEC); output_file.open(output_path.c_str()); output_file << OUT_FILE_COL_HEADERS << endl; output_file << frame << "," << msecs << ","; output_file << cmt.points_active.size() << ","; output_file << write_rotated_rect(cmt.bb_rot) << endl; } int penghitung = 0; float awal = 0.00; //float awal2 = 0.00; float per1 = 1.00; //float per2 = 1.00; double a = cap.get(CV_CAP_PROP_FPS); cout << a << endl; //Main loop while (true) { frame++; Mat im; //im2; //If loop flag is set, reuse initial image (for debugging purposes) if (loop_flag) im0.copyTo(im); else cap >> im; //cap2 >> im2;//Else use next image in stream if (im.empty() ) break; //Exit at end of video stream & || im2.empty() Mat im_gray; //im_gray2; if (im.channels() > 1) { // || im2.channels() > 1 cvtColor(im, im_gray, CV_BGR2GRAY); //cvtColor(im2, im_gray2, CV_BGR2GRAY); } else { im_gray = im; //im_gray2 = im2; } //Let CMT process the frame cmt.processFrame(im_gray); //cmt2.processFrame(im_gray2); //Output. if (output_flag) { int msecs = (int) cap.get(CV_CAP_PROP_POS_MSEC); output_file << frame << "," << msecs << ","; output_file << cmt.points_active.size() << ","; output_file << write_rotated_rect(cmt.bb_rot) << endl; } else { //TODO: Provide meaningful output //FILE_LOG(logINFO) << "#" << frame << " active: " << cmt.points_active.size(); //FILE_LOG(logINFO) << "#" << frame << " active: " << cmt2.points_active.size(); //cout << cmt.points_active.size() <<endl; //cout << cmt2.points_active.size() <<endl; if (penghitung == 0){ awal = (float)cmt.points_active.size(); //awal2 = (float)cmt2.points_active.size(); penghitung++; } per1 = 100*(cmt.points_active.size()/awal) + 50.00 ; //per2 = 100*(cmt2.points_active.size()/awal2); char key = display(im, cmt); } //if (per1 >= per2){ //} //else { //char key2 = display2(im2, cmt2); //} //cout << per1 <<endl; //cout << per2 <<endl; //cout << cmt.consensus <<endl; //Display image and then quit if requested. //if(key == 'q') break; } //Close output file. if (output_flag) output_file.close(); return 0; } int main(){ int facetracker1(int argc, char **argv) ; //int facetracker2(int argc, char **argv) ; int color(int argc, char* argv[]); char ** a; int b; int c; //cin >> c; facetracker1(b,a); //facetracker2(b,a); /**if(c == 1){ tracker1(b,a); } else { warna(b,a);} **/ return 0; }
[ "astronutmers@gmail.com" ]
astronutmers@gmail.com
50b7c0effc2b987e18c2b4c91553c6f6fec63d38
c8ccefd05798f00fb9fd884b56a1ecca73ca28cb
/src/alert.h
87d0dd3e073a33b89e322b81a8bd556539f60747
[ "MIT" ]
permissive
mybitcoinbucks/bitcoinbuck
111279569ae567924983180c3c4754a9181f1e73
f1e705503c1274759eb1f5aee935f13841e96ee0
refs/heads/master
2023-07-02T15:32:59.366893
2021-08-06T06:25:17
2021-08-06T06:25:17
392,881,043
0
1
MIT
2021-08-06T02:02:28
2021-08-05T02:37:57
C++
UTF-8
C++
false
false
3,000
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoinbuck developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _BITCOINBUCKALERT_H_ #define _BITCOINBUCKALERT_H_ 1 #include <set> #include <string> #include "uint256.h" #include "util.h" static const char* pszMainKey = "043fa441fd4203d03f5df2b75ea14e36f20d39f43e7a61aa7552ab9bcd7ecb0e77a3be4585b13fcdaa22ef6e51f1ff6f2929bec2494385b086fb86610e33193195"; // TestNet alerts pubKey static const char* pszTestKey = "0471dc165db490094d35cde15b1f5d755fa6ad6f2b5ed0f340e3f17f57389c3c2af113a8cbcc885bde73305a553b5640c83021128008ddf882e856336269080496"; class CNode; /** Alerts are for notifying old versions if they become too obsolete and * need to upgrade. The message is displayed in the status bar. * Alert messages are broadcast as a vector of signed data. Unserializing may * not read the entire buffer if the alert is for a newer version, but older * versions can still relay the original data. */ class CUnsignedAlert { public: int nVersion; int64 nRelayUntil; // when newer nodes stop relaying to newer nodes int64 nExpiration; int nID; int nCancel; std::set<int> setCancel; int nMinVer; // lowest version inclusive int nMaxVer; // highest version inclusive std::set<std::string> setSubVer; // empty matches all int nPriority; // Actions std::string strComment; std::string strStatusBar; std::string strReserved; IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(nRelayUntil); READWRITE(nExpiration); READWRITE(nID); READWRITE(nCancel); READWRITE(setCancel); READWRITE(nMinVer); READWRITE(nMaxVer); READWRITE(setSubVer); READWRITE(nPriority); READWRITE(strComment); READWRITE(strStatusBar); READWRITE(strReserved); ) void SetNull(); std::string ToString() const; void print() const; }; /** An alert is a combination of a serialized CUnsignedAlert and a signature. */ class CAlert : public CUnsignedAlert { public: std::vector<unsigned char> vchMsg; std::vector<unsigned char> vchSig; CAlert() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(vchMsg); READWRITE(vchSig); ) void SetNull(); bool IsNull() const; uint256 GetHash() const; bool IsInEffect() const; bool Cancels(const CAlert& alert) const; bool AppliesTo(int nVersion, std::string strSubVerIn) const; bool AppliesToMe() const; bool RelayTo(CNode* pnode) const; bool CheckSignature() const; bool ProcessAlert(); /* * Get copy of (active) alert object by hash. Returns a null alert if it is not found. */ static CAlert getAlertByHash(const uint256 &hash); }; #endif
[ "quentin.neveu@hotmail.ca" ]
quentin.neveu@hotmail.ca
3840122084d54701e1073a9057ca2e203af8e9f4
ae07cf722a78d26b47d4e5a9343106ce530bf5c5
/src/cliquesampler.cpp
75f75d498015ba919f8db5a746a850fc1a09afc9
[]
no_license
ehebrard/ChromSAT
78d4aa49ef17bcf790e3e4d1522e04660053bbd1
060732477763bbbf2c1914221721d7a2bd79c46f
refs/heads/master
2023-01-21T21:35:03.158909
2023-01-18T10:55:13
2023-01-18T10:55:13
194,651,765
3
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
#include "cliquesampler.hpp" unsigned long gc::xorshf96(void) { // period 2^96-1 unsigned long t; x ^= x << 16; x ^= x >> 5; x ^= x << 1; t = x; x = y; y = z; z = t ^ x ^ y; return z; }
[ "ehebrard@poulidor.laas.fr" ]
ehebrard@poulidor.laas.fr
e9ab3ba809cfadaca5f1dca6146e19a101f0e1c6
72ee8d1a1795d237a745963534db5977d35b2a4a
/src/third_party/cppcodec/test/catch/include/internal/catch_enforce.h
513dcf1c633f163bc7f6c4bc4221133fdf466d04
[ "Apache-2.0", "MIT", "BSL-1.0" ]
permissive
aggrand/genny
35e1af6ffc36fe643b13dd38d22dad201f1489d7
3da82fd0acb99799caec2ab13047520405833f72
refs/heads/master
2022-09-08T03:06:52.301801
2022-07-19T18:30:41
2022-07-19T18:30:41
226,109,741
0
0
Apache-2.0
2019-12-05T13:34:19
2019-12-05T13:34:18
null
UTF-8
C++
false
false
872
h
/* * Created by Martin on 01/08/2017. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef TWOBLUECUBES_CATCH_ENFORCE_H_INCLUDED #define TWOBLUECUBES_CATCH_ENFORCE_H_INCLUDED #include "catch_common.h" #include "catch_stream.h" #include <stdexcept> #define CATCH_PREPARE_EXCEPTION( type, msg ) \ type( ( Catch::ReusableStringStream() << msg ).str() ) #define CATCH_INTERNAL_ERROR( msg ) \ throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg); #define CATCH_ERROR( msg ) \ throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg ) #define CATCH_ENFORCE( condition, msg ) \ do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false) #endif // TWOBLUECUBES_CATCH_ENFORCE_H_INCLUDED
[ "noreply@github.com" ]
noreply@github.com
8b5b7529954d57116a8a157a5c19e588081c5db0
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/Handle_StepRepr_QuantifiedAssemblyComponentUsage.hxx
8d28f1d4dbe329ffd363d6b351a54a2a8bbf7865
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
961
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Handle_StepRepr_QuantifiedAssemblyComponentUsage_HeaderFile #define _Handle_StepRepr_QuantifiedAssemblyComponentUsage_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_StepRepr_AssemblyComponentUsage_HeaderFile #include <Handle_StepRepr_AssemblyComponentUsage.hxx> #endif class Standard_Transient; class Handle(Standard_Type); class Handle(StepRepr_AssemblyComponentUsage); class StepRepr_QuantifiedAssemblyComponentUsage; DEFINE_STANDARD_HANDLE(StepRepr_QuantifiedAssemblyComponentUsage,StepRepr_AssemblyComponentUsage) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
96a466e7d5ba2c7fe9904cf7ce57f6a029d9b43b
18b69b1fc11c00ac1bfc6cc267dea5c7adfe20a7
/d04/ex01/RadScorpion.hpp
39e7b70b278bada211c46eb91debddf5373c22a1
[]
no_license
ArtemisKS/Piscine_CPP
e6344a3c386b431e5c6eb2fedc9ed16b8f9530ca
83881e01fb391ef70e58858e9716923ae75ebaac
refs/heads/master
2020-04-09T07:09:48.963450
2018-12-03T06:33:42
2018-12-03T06:33:42
160,142,993
0
0
null
null
null
null
UTF-8
C++
false
false
1,169
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* RadScorpion.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akupriia <akupriia@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/22 22:09:46 by akupriia #+# #+# */ /* Updated: 2018/06/22 22:09:47 by akupriia ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef RADSCORPION_HPP # define RADSCORPION_HPP # include "Enemy.hpp" class RadScorpion : public Enemy { public: RadScorpion( void ); RadScorpion( RadScorpion const & enemy ); virtual ~RadScorpion( void ); RadScorpion&operator=( RadScorpion const & enemy ); }; #endif
[ "Artemkupriyanets@yahoo.com" ]
Artemkupriyanets@yahoo.com
1f94dbbe254d755f73fbd2df3dacc52f2b04a2d6
4ce51a62efc99888f6979bf7cbe6d09d7c7b440b
/Matrix.hpp
d008d48e663843f7f984f118fac3227118f28a93
[]
no_license
LandoSama/Matrix
984041bac4f4fda512e12b9c63c91e426f73f3f3
415c8f06f4a8ae299aa85b1e733e92b5754a393c
refs/heads/master
2021-01-22T02:04:50.152567
2014-05-21T23:49:47
2014-05-21T23:49:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,041
hpp
#include <assert.h> #include <iostream> #include <math.h> using namespace std; template<typename T> class Matrix; template<typename T> ostream &operator << (ostream &out, const Matrix<T> &m); template<typename T> Matrix<T> operator* (const Matrix<T> & m1, const Matrix<T> & m2); template<typename T> Matrix<T> operator* (T c, const Matrix<T> & m2); template<typename T> Matrix<T> operator* (const Matrix<T> & m1, T c); template <typename T> T det(T **b, int m); template<typename T> class Matrix { public: Matrix(int sizeX = 1, int sizeY = 1); Matrix(); ~Matrix(); Matrix(const Matrix<T>& m); Matrix& operator=(const Matrix<T>& rhs); Matrix operator+(const Matrix<T> & m); Matrix& operator+=(const Matrix<T> & m); Matrix operator-(const Matrix<T>& m); Matrix& operator-=(const Matrix<T>& m); friend ostream &operator<< <T> (ostream &out, const Matrix<T> &m); T &operator()(T x, T y); bool is_square(); void detmnt(); friend Matrix operator* <T> (const Matrix<T> & m1, const Matrix<T> & m2); friend Matrix operator* <T> (T c, const Matrix<T> & m2); friend Matrix operator* <T> (const Matrix<T> & m1, T c); private: int dx, dy; // dimensions, dx by dy and determinant T determ; T **p; // pointer to a pointer to a long integer void allocArrays() { assert(dx>0); assert(dy>0); p = new T*[dx]; for (int i = 0; i < dx; i++) { p[i] = new T[dy]; } } }; template <typename T> Matrix<T>::Matrix(int sizeX, int sizeY) : dx(sizeX),dy(sizeY) { allocArrays(); for (int i = 0; i < dx; i++) { for (int j = 0; j < dy; j++) { p[i][j] = 0; } } } template <typename T> bool Matrix<T>::is_square(){ if(dx == dy){ cout << "is square" << endl; return true; } else{ cout << "not square" << endl; return false; } } template <typename T> Matrix<T>::Matrix(const Matrix<T>& m) : dx(m.dx), dy(m.dy) { allocArrays(); for (int i=0; i<dx; ++i) { for (int j=0; j<dy; ++j) { p[i][j] = m.p[i][j]; } } } template <typename T> Matrix<T>::~Matrix() { for (int i = 0; i < dx; i++) { delete [] p[i]; } delete [] p; p = 0; } template <typename T> Matrix<T> &Matrix<T>::operator=(const Matrix<T>& m) { if (this == &m) { // avoid self-assignment return *this; } else { if (dx != m.dx || dy != m.dy) { this->~Matrix(); dx = m.dx; dy = m.dy; allocArrays(); } for (int i = 0; i < dx; i++) { for (int j = 0; j < dy; j++) { p[i][j] = m.p[i][j]; } } return *this; } } template <typename T> Matrix<T> &Matrix<T>::operator+=(const Matrix<T> &m) { assert(dx==m.dx); assert(dy==m.dy); // x+=y adds the y-entries into the x-entries for (int i=0; i<dx; ++i) { for (int j=0; j<dy; ++j) { p[i][j] += m.p[i][j]; } } return *this; } template <typename T> Matrix<T> Matrix<T>::operator+(const Matrix<T> &m) { Matrix<T> temp(*this); //copy constructor return (temp += m); } template <typename T> Matrix<T> &Matrix<T>::operator-=(const Matrix<T> &m){ assert(dx==m.dx); assert(dy==m.dy); // x+=y adds the y-entries into the x-entires for(int i=0; i<dx; ++i){ for(int j=0; j<dy; ++j){ p[i][j] -= m.p[i][j]; } } return *this; } template <typename T> Matrix<T> Matrix<T>::operator-(const Matrix<T> &m){ Matrix<T> temp(*this); //copy constructor return(temp -= m); } template <typename T> ostream &operator<< (ostream &out, const Matrix<T> &m) { for (int i = 0; i < m.dx; ++i) { for (int j = 0; j < m.dy; ++j) out << m.p[i][j] << " "; out << endl; } return out; } template <typename T> T &Matrix<T>::operator()(T i, T j) { assert(i>=0 && i<dx); assert(j>=0 && j<dy); return p[i][j]; } template <typename T> Matrix<T> operator* (const Matrix<T>& m1, const Matrix<T>& m2) { Matrix<T> prod(m1.dx, m2.dy); for (int i=0; i<prod.dx; ++i) { for (int j=0; j<prod.dy; ++j) { for (int k=0; k<m1.dy; ++k) { prod.p[i][j] += m1.p[i][k] * m2.p[k][j]; } } }; return prod; } template <typename T> Matrix<T> operator* (T c, const Matrix<T>& m2) { Matrix<T> prod(m2); for (int i=0; i<prod.dx; ++i) { for (int j=0; j<prod.dy; ++j) { prod.p[i][j] = c * m2.p[i][j]; } } return prod; } template <typename T> Matrix<T> operator* (const Matrix<T>& m2, T c) { return c*m2; } template <typename T> void Matrix<T>::detmnt() { determ = det(p, dx); cout<<"det is "<< determ << endl; } template <typename T> T det(T **b,int m) { cout << "this is something" << endl; int sum=0,x=0,y=0,i=0,j,aa,bb; T **c; c = new T*[m]; cout << "this is something 2" << endl; for (int i = 0; i < m; i++) { c[i] = new T[m]; } cout << "this is something 3" << endl; if(m==2) return(b[0][0]*b[1][1]-b[0][1]*b[1][0]); else{ for(j=0;j<m;j++){ cout << "this is something 4" << endl; for(aa=0,y=0;aa<m;aa++){ for(bb=0;bb<m;bb++){ if((aa!=i)&&(bb!=j)){ c[x][y++]=b[aa][bb]; } if(y>0)x++; y=0; } sum=sum+b[i][j]*pow(-1,i+j)*det(c,m-1); } } } return sum; }
[ "lando_lakes@rocketmail.com" ]
lando_lakes@rocketmail.com
aac78ed56eb3cd1c540cf5f65b5be9e8928fa4cf
7bcc51362468098bbb9ddd241230e02cdbeea6e4
/standard/src/dxutil.cpp
3524f0458bf7966fd84ca8b252f26ae92d756805
[ "ISC" ]
permissive
Marko10-000/clonk-rage
af4ac62b7227c00874ecd49431a29a984a417fbb
230e715f2abe65966d5e5467cb18382062d1dec6
refs/heads/master
2021-01-18T07:29:38.108084
2015-09-07T01:34:56
2015-09-07T01:34:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,449
cpp
//----------------------------------------------------------------------------- // File: DXUtil.cpp // // Desc: Shortcut macros and functions for using DX objects // // // Copyright (c) 1997-2000 Microsoft Corporation. All rights reserved //----------------------------------------------------------------------------- #ifdef _WIN32 #define STRICT #if defined(_WIN32) && !defined(POINTER_64) #define POINTER_64 __ptr64 #endif #include <windows.h> #include <mmsystem.h> #include <tchar.h> #include <stdio.h> #include <stdarg.h> #include "dxutil.h" //----------------------------------------------------------------------------- // Name: DXUtil_GetDXSDKMediaPath() // Desc: Returns the DirectX SDK media path //----------------------------------------------------------------------------- const TCHAR* DXUtil_GetDXSDKMediaPath() { static TCHAR strNull[2] = _T(""); static TCHAR strPath[MAX_PATH]; DWORD dwType; DWORD dwSize = MAX_PATH; HKEY hKey; // Open the appropriate registry key LONG lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\DirectX"), 0, KEY_READ, &hKey ); if( ERROR_SUCCESS != lResult ) return strNull; lResult = RegQueryValueEx( hKey, _T("DX8SDK Samples Path"), NULL, &dwType, (BYTE*)strPath, &dwSize ); RegCloseKey( hKey ); if( ERROR_SUCCESS != lResult ) return strNull; _tcscat( strPath, _T("\\Media\\") ); return strPath; } //----------------------------------------------------------------------------- // Name: DXUtil_FindMediaFile() // Desc: Returns a valid path to a DXSDK media file //----------------------------------------------------------------------------- HRESULT DXUtil_FindMediaFile( TCHAR* strPath, TCHAR* strFilename ) { HANDLE file; if( NULL==strFilename || NULL==strPath ) return E_INVALIDARG; // Check if the file exists in the current directory _tcscpy( strPath, strFilename ); file = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if( INVALID_HANDLE_VALUE != file ) { CloseHandle( file ); return S_OK; } // Check if the file exists in the current directory _stprintf( strPath, _T("%s%s"), DXUtil_GetDXSDKMediaPath(), strFilename ); file = CreateFile( strPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if( INVALID_HANDLE_VALUE != file ) { CloseHandle( file ); return S_OK; } // On failure, just return the file as the path _tcscpy( strPath, strFilename ); return E_FAIL; } //----------------------------------------------------------------------------- // Name: DXUtil_ReadStringRegKey() // Desc: Helper function to read a registry key string //----------------------------------------------------------------------------- HRESULT DXUtil_ReadStringRegKey( HKEY hKey, TCHAR* strRegName, TCHAR* strValue, DWORD dwLength, TCHAR* strDefault ) { DWORD dwType; if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType, (BYTE*)strValue, &dwLength ) ) { _tcscpy( strValue, strDefault ); } return S_OK; } //----------------------------------------------------------------------------- // Name: DXUtil_WriteStringRegKey() // Desc: Helper function to write a registry key string //----------------------------------------------------------------------------- HRESULT DXUtil_WriteStringRegKey( HKEY hKey, TCHAR* strRegName, TCHAR* strValue ) { if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_SZ, (BYTE*)strValue, (_tcslen(strValue)+1)*sizeof(TCHAR) ) ) return E_FAIL; return S_OK; } //----------------------------------------------------------------------------- // Name: DXUtil_ReadIntRegKey() // Desc: Helper function to read a registry key int //----------------------------------------------------------------------------- HRESULT DXUtil_ReadIntRegKey( HKEY hKey, TCHAR* strRegName, DWORD* pdwValue, DWORD dwDefault ) { DWORD dwType; DWORD dwLength = sizeof(DWORD); if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType, (BYTE*)pdwValue, &dwLength ) ) { *pdwValue = dwDefault; } return S_OK; } //----------------------------------------------------------------------------- // Name: DXUtil_WriteIntRegKey() // Desc: Helper function to write a registry key int //----------------------------------------------------------------------------- HRESULT DXUtil_WriteIntRegKey( HKEY hKey, TCHAR* strRegName, DWORD dwValue ) { if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_DWORD, (BYTE*)&dwValue, sizeof(DWORD) ) ) return E_FAIL; return S_OK; } //----------------------------------------------------------------------------- // Name: DXUtil_ReadBoolRegKey() // Desc: Helper function to read a registry key BOOL //----------------------------------------------------------------------------- HRESULT DXUtil_ReadBoolRegKey( HKEY hKey, TCHAR* strRegName, BOOL* pbValue, BOOL bDefault ) { DWORD dwType; DWORD dwLength = sizeof(BOOL); if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType, (BYTE*)pbValue, &dwLength ) ) { *pbValue = bDefault; } return S_OK; } //----------------------------------------------------------------------------- // Name: DXUtil_WriteBoolRegKey() // Desc: Helper function to write a registry key BOOL //----------------------------------------------------------------------------- HRESULT DXUtil_WriteBoolRegKey( HKEY hKey, TCHAR* strRegName, BOOL bValue ) { if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_DWORD, (BYTE*)&bValue, sizeof(BOOL) ) ) return E_FAIL; return S_OK; } //----------------------------------------------------------------------------- // Name: DXUtil_ReadGuidRegKey() // Desc: Helper function to read a registry key guid //----------------------------------------------------------------------------- HRESULT DXUtil_ReadGuidRegKey( HKEY hKey, TCHAR* strRegName, GUID* pGuidValue, GUID& guidDefault ) { DWORD dwType; DWORD dwLength = sizeof(GUID); if( ERROR_SUCCESS != RegQueryValueEx( hKey, strRegName, 0, &dwType, (LPBYTE) pGuidValue, &dwLength ) ) { *pGuidValue = guidDefault; } return S_OK; } //----------------------------------------------------------------------------- // Name: DXUtil_WriteGuidRegKey() // Desc: Helper function to write a registry key guid //----------------------------------------------------------------------------- HRESULT DXUtil_WriteGuidRegKey( HKEY hKey, TCHAR* strRegName, GUID guidValue ) { if( ERROR_SUCCESS != RegSetValueEx( hKey, strRegName, 0, REG_BINARY, (BYTE*)&guidValue, sizeof(GUID) ) ) return E_FAIL; return S_OK; } //----------------------------------------------------------------------------- // Name: DXUtil_Timer() // Desc: Performs timer opertations. Use the following commands: // TIMER_RESET - to reset the timer // TIMER_START - to start the timer // TIMER_STOP - to stop (or pause) the timer // TIMER_ADVANCE - to advance the timer by 0.1 seconds // TIMER_GETABSOLUTETIME - to get the absolute system time // TIMER_GETAPPTIME - to get the current time // TIMER_GETELAPSEDTIME - to get the time that elapsed between // TIMER_GETELAPSEDTIME calls //----------------------------------------------------------------------------- FLOAT __stdcall DXUtil_Timer( TIMER_COMMAND command ) { static BOOL m_bTimerInitialized = FALSE; static BOOL m_bUsingQPF = FALSE; static LONGLONG m_llQPFTicksPerSec = 0; // Initialize the timer if( FALSE == m_bTimerInitialized ) { m_bTimerInitialized = TRUE; // Use QueryPerformanceFrequency() to get frequency of timer. If QPF is // not supported, we will timeGetTime() which returns milliseconds. LARGE_INTEGER qwTicksPerSec; m_bUsingQPF = QueryPerformanceFrequency( &qwTicksPerSec ); if( m_bUsingQPF ) m_llQPFTicksPerSec = qwTicksPerSec.QuadPart; } if( m_bUsingQPF ) { static LONGLONG m_llStopTime = 0; static LONGLONG m_llLastElapsedTime = 0; static LONGLONG m_llBaseTime = 0; double fTime; double fElapsedTime; LARGE_INTEGER qwTime; // Get either the current time or the stop time, depending // on whether we're stopped and what command was sent if( m_llStopTime != 0 && command != TIMER_START && command != TIMER_GETABSOLUTETIME) qwTime.QuadPart = m_llStopTime; else QueryPerformanceCounter( &qwTime ); // Return the elapsed time if( command == TIMER_GETELAPSEDTIME ) { fElapsedTime = (double) ( qwTime.QuadPart - m_llLastElapsedTime ) / (double) m_llQPFTicksPerSec; m_llLastElapsedTime = qwTime.QuadPart; return (FLOAT) fElapsedTime; } // Return the current time if( command == TIMER_GETAPPTIME ) { double fAppTime = (double) ( qwTime.QuadPart - m_llBaseTime ) / (double) m_llQPFTicksPerSec; return (FLOAT) fAppTime; } // Reset the timer if( command == TIMER_RESET ) { m_llBaseTime = qwTime.QuadPart; m_llLastElapsedTime = qwTime.QuadPart; return 0.0f; } // Start the timer if( command == TIMER_START ) { m_llBaseTime += qwTime.QuadPart - m_llStopTime; m_llStopTime = 0; m_llLastElapsedTime = qwTime.QuadPart; return 0.0f; } // Stop the timer if( command == TIMER_STOP ) { m_llStopTime = qwTime.QuadPart; m_llLastElapsedTime = qwTime.QuadPart; return 0.0f; } // Advance the timer by 1/10th second if( command == TIMER_ADVANCE ) { m_llStopTime += m_llQPFTicksPerSec/10; return 0.0f; } if( command == TIMER_GETABSOLUTETIME ) { fTime = qwTime.QuadPart / (double) m_llQPFTicksPerSec; return (FLOAT) fTime; } return -1.0f; // Invalid command specified } else { // Get the time using timeGetTime() static double m_fLastElapsedTime = 0.0; static double m_fBaseTime = 0.0; static double m_fStopTime = 0.0; double fTime; double fElapsedTime; // Get either the current time or the stop time, depending // on whether we're stopped and what command was sent if( m_fStopTime != 0.0 && command != TIMER_START && command != TIMER_GETABSOLUTETIME) fTime = m_fStopTime; else fTime = timeGetTime() * 0.001; // Return the elapsed time if( command == TIMER_GETELAPSEDTIME ) { fElapsedTime = (double) (fTime - m_fLastElapsedTime); m_fLastElapsedTime = fTime; return (FLOAT) fElapsedTime; } // Return the current time if( command == TIMER_GETAPPTIME ) { return (FLOAT) (fTime - m_fBaseTime); } // Reset the timer if( command == TIMER_RESET ) { m_fBaseTime = fTime; m_fLastElapsedTime = fTime; return 0.0f; } // Start the timer if( command == TIMER_START ) { m_fBaseTime += fTime - m_fStopTime; m_fStopTime = 0.0f; m_fLastElapsedTime = fTime; return 0.0f; } // Stop the timer if( command == TIMER_STOP ) { m_fStopTime = fTime; return 0.0f; } // Advance the timer by 1/10th second if( command == TIMER_ADVANCE ) { m_fStopTime += 0.1f; return 0.0f; } if( command == TIMER_GETABSOLUTETIME ) { return (FLOAT) fTime; } return -1.0f; // Invalid command specified } } //----------------------------------------------------------------------------- // Name: DXUtil_ConvertAnsiStringToWide() // Desc: This is a UNICODE conversion utility to convert a CHAR string into a // WCHAR string. cchDestChar defaults -1 which means it // assumes strDest is large enough to store strSource //----------------------------------------------------------------------------- VOID DXUtil_ConvertAnsiStringToWide( WCHAR* wstrDestination, const CHAR* strSource, int cchDestChar ) { if( wstrDestination==NULL || strSource==NULL ) return; if( cchDestChar == -1 ) cchDestChar = strlen(strSource)+1; MultiByteToWideChar( CP_ACP, 0, strSource, -1, wstrDestination, cchDestChar-1 ); wstrDestination[cchDestChar-1] = 0; } //----------------------------------------------------------------------------- // Name: DXUtil_ConvertWideStringToAnsi() // Desc: This is a UNICODE conversion utility to convert a WCHAR string into a // CHAR string. cchDestChar defaults -1 which means it // assumes strDest is large enough to store strSource //----------------------------------------------------------------------------- VOID DXUtil_ConvertWideStringToAnsi( CHAR* strDestination, const WCHAR* wstrSource, int cchDestChar ) { if( strDestination==NULL || wstrSource==NULL ) return; if( cchDestChar == -1 ) cchDestChar = wcslen(wstrSource)+1; WideCharToMultiByte( CP_ACP, 0, wstrSource, -1, strDestination, cchDestChar-1, NULL, NULL ); strDestination[cchDestChar-1] = 0; } //----------------------------------------------------------------------------- // Name: DXUtil_ConvertGenericStringToAnsi() // Desc: This is a UNICODE conversion utility to convert a TCHAR string into a // CHAR string. cchDestChar defaults -1 which means it // assumes strDest is large enough to store strSource //----------------------------------------------------------------------------- VOID DXUtil_ConvertGenericStringToAnsi( CHAR* strDestination, const TCHAR* tstrSource, int cchDestChar ) { if( strDestination==NULL || tstrSource==NULL ) return; #ifdef _UNICODE DXUtil_ConvertWideStringToAnsi( strDestination, tstrSource, cchDestChar ); #else if( cchDestChar == -1 ) strcpy( strDestination, tstrSource ); else strncpy( strDestination, tstrSource, cchDestChar ); #endif } //----------------------------------------------------------------------------- // Name: DXUtil_ConvertGenericStringToWide() // Desc: This is a UNICODE conversion utility to convert a TCHAR string into a // WCHAR string. cchDestChar defaults -1 which means it // assumes strDest is large enough to store strSource //----------------------------------------------------------------------------- VOID DXUtil_ConvertGenericStringToWide( WCHAR* wstrDestination, const TCHAR* tstrSource, int cchDestChar ) { if( wstrDestination==NULL || tstrSource==NULL ) return; #ifdef _UNICODE if( cchDestChar == -1 ) wcscpy( wstrDestination, tstrSource ); else wcsncpy( wstrDestination, tstrSource, cchDestChar ); #else DXUtil_ConvertAnsiStringToWide( wstrDestination, tstrSource, cchDestChar ); #endif } //----------------------------------------------------------------------------- // Name: DXUtil_ConvertAnsiStringToGeneric() // Desc: This is a UNICODE conversion utility to convert a CHAR string into a // TCHAR string. cchDestChar defaults -1 which means it // assumes strDest is large enough to store strSource //----------------------------------------------------------------------------- VOID DXUtil_ConvertAnsiStringToGeneric( TCHAR* tstrDestination, const CHAR* strSource, int cchDestChar ) { if( tstrDestination==NULL || strSource==NULL ) return; #ifdef _UNICODE DXUtil_ConvertAnsiStringToWide( tstrDestination, strSource, cchDestChar ); #else if( cchDestChar == -1 ) strcpy( tstrDestination, strSource ); else strncpy( tstrDestination, strSource, cchDestChar ); #endif } //----------------------------------------------------------------------------- // Name: DXUtil_ConvertAnsiStringToGeneric() // Desc: This is a UNICODE conversion utility to convert a WCHAR string into a // TCHAR string. cchDestChar defaults -1 which means it // assumes strDest is large enough to store strSource //----------------------------------------------------------------------------- VOID DXUtil_ConvertWideStringToGeneric( TCHAR* tstrDestination, const WCHAR* wstrSource, int cchDestChar ) { if( tstrDestination==NULL || wstrSource==NULL ) return; #ifdef _UNICODE if( cchDestChar == -1 ) wcscpy( tstrDestination, wstrSource ); else wcsncpy( tstrDestination, wstrSource, cchDestChar ); #else DXUtil_ConvertWideStringToAnsi( tstrDestination, wstrSource, cchDestChar ); #endif } //----------------------------------------------------------------------------- // Name: _DbgOut() // Desc: Outputs a message to the debug stream //----------------------------------------------------------------------------- HRESULT _DbgOut( TCHAR* strFile, DWORD dwLine, HRESULT hr, TCHAR* strMsg ) { TCHAR buffer[256]; wsprintf( buffer, _T("%s(%ld): "), strFile, dwLine ); OutputDebugString( buffer ); OutputDebugString( strMsg ); if( hr ) { wsprintf( buffer, _T("(hr=%08lx)\n"), hr ); OutputDebugString( buffer ); } OutputDebugString( _T("\n") ); return hr; } //----------------------------------------------------------------------------- // Name: DXUtil_Trace() // Desc: Outputs to the debug stream a formatted string with a variable- // argument list. //----------------------------------------------------------------------------- VOID DXUtil_Trace( TCHAR* strMsg, ... ) { #if defined(DEBUG) | defined(_DEBUG) TCHAR strBuffer[512]; va_list args; va_start(args, strMsg); _vsntprintf( strBuffer, 512, strMsg, args ); va_end(args); OutputDebugString( strBuffer ); #endif } #endif //_WIN32
[ "kanibalclonk@freenet.de" ]
kanibalclonk@freenet.de
0390ea42b2374185098410d63a7d61cf5fdfd461
12732dc8a5dd518f35c8af3f2a805806f5e91e28
/trunk/sdk/wxscintilla/src/scintilla/src/LexHTML.cxx
6ae65e8a99519ec95e0379e85e49fc1fa2979efc
[ "LicenseRef-scancode-scintilla" ]
permissive
BackupTheBerlios/codelite-svn
5acd9ac51fdd0663742f69084fc91a213b24ae5c
c9efd7873960706a8ce23cde31a701520bad8861
refs/heads/master
2020-05-20T13:22:34.635394
2007-08-02T21:35:35
2007-08-02T21:35:35
40,669,327
0
0
null
null
null
null
UTF-8
C++
false
false
64,586
cxx
// Scintilla source code edit control /** @file LexHTML.cxx ** Lexer for HTML. **/ // Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" #define SCE_HA_JS (SCE_HJA_START - SCE_HJ_START) #define SCE_HA_VBS (SCE_HBA_START - SCE_HB_START) #define SCE_HA_PYTHON (SCE_HPA_START - SCE_HP_START) enum script_type { eScriptNone = 0, eScriptJS, eScriptVBS, eScriptPython, eScriptPHP, eScriptXML, eScriptSGML, eScriptSGMLblock }; enum script_mode { eHtml = 0, eNonHtmlScript, eNonHtmlPreProc, eNonHtmlScriptPreProc }; static inline bool IsAWordChar(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); } static inline bool IsAWordStart(const int ch) { return (ch < 0x80) && (isalnum(ch) || ch == '_'); } static inline int MakeLowerCase(int ch) { if (ch < 'A' || ch > 'Z') return ch; else return ch - 'A' + 'a'; } static void GetTextSegment(Accessor &styler, unsigned int start, unsigned int end, char *s, size_t len) { size_t i = 0; for (; (i < end - start + 1) && (i < len-1); i++) { s[i] = static_cast<char>(MakeLowerCase(styler[start + i])); } s[i] = '\0'; } static script_type segIsScriptingIndicator(Accessor &styler, unsigned int start, unsigned int end, script_type prevValue) { char s[100]; GetTextSegment(styler, start, end, s, sizeof(s)); //Platform::DebugPrintf("Scripting indicator [%s]\n", s); if (strstr(s, "src")) // External script return eScriptNone; if (strstr(s, "vbs")) return eScriptVBS; if (strstr(s, "pyth")) return eScriptPython; if (strstr(s, "javas")) return eScriptJS; if (strstr(s, "jscr")) return eScriptJS; if (strstr(s, "php")) return eScriptPHP; if (strstr(s, "xml")) return eScriptXML; return prevValue; } static int PrintScriptingIndicatorOffset(Accessor &styler, unsigned int start, unsigned int end) { int iResult = 0; char s[100]; GetTextSegment(styler, start, end, s, sizeof(s)); if (0 == strncmp(s, "php", 3)) { iResult = 3; } return iResult; } static script_type ScriptOfState(int state) { if ((state >= SCE_HP_START) && (state <= SCE_HP_IDENTIFIER)) { return eScriptPython; } else if ((state >= SCE_HB_START) && (state <= SCE_HB_STRINGEOL)) { return eScriptVBS; } else if ((state >= SCE_HJ_START) && (state <= SCE_HJ_REGEX)) { return eScriptJS; } else if ((state >= SCE_HPHP_DEFAULT) && (state <= SCE_HPHP_COMMENTLINE)) { return eScriptPHP; } else if ((state >= SCE_H_SGML_DEFAULT) && (state < SCE_H_SGML_BLOCK_DEFAULT)) { return eScriptSGML; } else if (state == SCE_H_SGML_BLOCK_DEFAULT) { return eScriptSGMLblock; } else { return eScriptNone; } } static int statePrintForState(int state, script_mode inScriptType) { int StateToPrint; if ((state >= SCE_HP_START) && (state <= SCE_HP_IDENTIFIER)) { StateToPrint = state + ((inScriptType == eNonHtmlScript) ? 0 : SCE_HA_PYTHON); } else if ((state >= SCE_HB_START) && (state <= SCE_HB_STRINGEOL)) { StateToPrint = state + ((inScriptType == eNonHtmlScript) ? 0 : SCE_HA_VBS); } else if ((state >= SCE_HJ_START) && (state <= SCE_HJ_REGEX)) { StateToPrint = state + ((inScriptType == eNonHtmlScript) ? 0 : SCE_HA_JS); } else { StateToPrint = state; } return StateToPrint; } static int stateForPrintState(int StateToPrint) { int state; if ((StateToPrint >= SCE_HPA_START) && (StateToPrint <= SCE_HPA_IDENTIFIER)) { state = StateToPrint - SCE_HA_PYTHON; } else if ((StateToPrint >= SCE_HBA_START) && (StateToPrint <= SCE_HBA_STRINGEOL)) { state = StateToPrint - SCE_HA_VBS; } else if ((StateToPrint >= SCE_HJA_START) && (StateToPrint <= SCE_HJA_REGEX)) { state = StateToPrint - SCE_HA_JS; } else { state = StateToPrint; } return state; } static inline bool IsNumber(unsigned int start, Accessor &styler) { return IsADigit(styler[start]) || (styler[start] == '.') || (styler[start] == '-') || (styler[start] == '#'); } static inline bool isStringState(int state) { bool bResult; switch (state) { case SCE_HJ_DOUBLESTRING: case SCE_HJ_SINGLESTRING: case SCE_HJA_DOUBLESTRING: case SCE_HJA_SINGLESTRING: case SCE_HB_STRING: case SCE_HBA_STRING: case SCE_HP_STRING: case SCE_HP_CHARACTER: case SCE_HP_TRIPLE: case SCE_HP_TRIPLEDOUBLE: case SCE_HPA_STRING: case SCE_HPA_CHARACTER: case SCE_HPA_TRIPLE: case SCE_HPA_TRIPLEDOUBLE: case SCE_HPHP_HSTRING: case SCE_HPHP_SIMPLESTRING: case SCE_HPHP_HSTRING_VARIABLE: case SCE_HPHP_COMPLEX_VARIABLE: bResult = true; break; default : bResult = false; break; } return bResult; } static inline bool stateAllowsTermination(int state) { bool allowTermination = !isStringState(state); if (allowTermination) { switch (state) { case SCE_HB_COMMENTLINE: case SCE_HPHP_COMMENT: case SCE_HP_COMMENTLINE: case SCE_HPA_COMMENTLINE: allowTermination = false; } } return allowTermination; } // not really well done, since it's only comments that should lex the %> and <% static inline bool isCommentASPState(int state) { bool bResult; switch (state) { case SCE_HJ_COMMENT: case SCE_HJ_COMMENTLINE: case SCE_HJ_COMMENTDOC: case SCE_HB_COMMENTLINE: case SCE_HP_COMMENTLINE: case SCE_HPHP_COMMENT: case SCE_HPHP_COMMENTLINE: bResult = true; break; default : bResult = false; break; } return bResult; } static void classifyAttribHTML(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { bool wordIsNumber = IsNumber(start, styler); char chAttr = SCE_H_ATTRIBUTEUNKNOWN; if (wordIsNumber) { chAttr = SCE_H_NUMBER; } else { char s[100]; GetTextSegment(styler, start, end, s, sizeof(s)); if (keywords.InList(s)) chAttr = SCE_H_ATTRIBUTE; } if ((chAttr == SCE_H_ATTRIBUTEUNKNOWN) && !keywords) // No keywords -> all are known chAttr = SCE_H_ATTRIBUTE; styler.ColourTo(end, chAttr); } static int classifyTagHTML(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, bool &tagDontFold, bool caseSensitive) { char s[30 + 2]; // Copy after the '<' unsigned int i = 0; for (unsigned int cPos = start; cPos <= end && i < 30; cPos++) { char ch = styler[cPos]; if ((ch != '<') && (ch != '/')) { s[i++] = caseSensitive ? ch : static_cast<char>(MakeLowerCase(ch)); } } //The following is only a quick hack, to see if this whole thing would work //we first need the tagname with a trailing space... s[i] = ' '; s[i+1] = '\0'; //...to find it in the list of no-container-tags // (There are many more. We will need a keywordlist in the property file for this) tagDontFold = (NULL != strstr("meta link img area br hr input ",s)); //now we can remove the trailing space s[i] = '\0'; bool isScript = false; char chAttr = SCE_H_TAGUNKNOWN; if (s[0] == '!') { chAttr = SCE_H_SGML_DEFAULT; } else if (s[0] == '/') { // Closing tag if (keywords.InList(s + 1)) chAttr = SCE_H_TAG; } else { if (keywords.InList(s)) { chAttr = SCE_H_TAG; isScript = 0 == strcmp(s, "script"); } } if ((chAttr == SCE_H_TAGUNKNOWN) && !keywords) { // No keywords -> all are known chAttr = SCE_H_TAG; isScript = 0 == strcmp(s, "script"); } styler.ColourTo(end, chAttr); return isScript ? SCE_H_SCRIPT : chAttr; } static void classifyWordHTJS(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, script_mode inScriptType) { char chAttr = SCE_HJ_WORD; bool wordIsNumber = IsADigit(styler[start]) || (styler[start] == '.'); if (wordIsNumber) chAttr = SCE_HJ_NUMBER; else { char s[30 + 1]; unsigned int i = 0; for (; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; } s[i] = '\0'; if (keywords.InList(s)) chAttr = SCE_HJ_KEYWORD; } styler.ColourTo(end, statePrintForState(chAttr, inScriptType)); } static int classifyWordHTVB(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, script_mode inScriptType) { char chAttr = SCE_HB_IDENTIFIER; bool wordIsNumber = IsADigit(styler[start]) || (styler[start] == '.'); if (wordIsNumber) chAttr = SCE_HB_NUMBER; else { char s[100]; GetTextSegment(styler, start, end, s, sizeof(s)); if (keywords.InList(s)) { chAttr = SCE_HB_WORD; if (strcmp(s, "rem") == 0) chAttr = SCE_HB_COMMENTLINE; } } styler.ColourTo(end, statePrintForState(chAttr, inScriptType)); if (chAttr == SCE_HB_COMMENTLINE) return SCE_HB_COMMENTLINE; else return SCE_HB_DEFAULT; } static void classifyWordHTPy(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord, script_mode inScriptType) { bool wordIsNumber = IsADigit(styler[start]); char s[30 + 1]; unsigned int i = 0; for (; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; } s[i] = '\0'; char chAttr = SCE_HP_IDENTIFIER; if (0 == strcmp(prevWord, "class")) chAttr = SCE_HP_CLASSNAME; else if (0 == strcmp(prevWord, "def")) chAttr = SCE_HP_DEFNAME; else if (wordIsNumber) chAttr = SCE_HP_NUMBER; else if (keywords.InList(s)) chAttr = SCE_HP_WORD; styler.ColourTo(end, statePrintForState(chAttr, inScriptType)); strcpy(prevWord, s); } // Update the word colour to default or keyword // Called when in a PHP word static void classifyWordHTPHP(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char chAttr = SCE_HPHP_DEFAULT; bool wordIsNumber = IsADigit(styler[start]) || (styler[start] == '.' && start+1 <= end && IsADigit(styler[start+1])); if (wordIsNumber) chAttr = SCE_HPHP_NUMBER; else { char s[100]; GetTextSegment(styler, start, end, s, sizeof(s)); if (keywords.InList(s)) chAttr = SCE_HPHP_WORD; } styler.ColourTo(end, chAttr); } static bool isWordHSGML(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char s[30 + 1]; unsigned int i = 0; for (; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; } s[i] = '\0'; return keywords.InList(s); } static bool isWordCdata(unsigned int start, unsigned int end, Accessor &styler) { char s[30 + 1]; unsigned int i = 0; for (; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; } s[i] = '\0'; return (0 == strcmp(s, "[CDATA[")); } // Return the first state to reach when entering a scripting language static int StateForScript(script_type scriptLanguage) { int Result; switch (scriptLanguage) { case eScriptVBS: Result = SCE_HB_START; break; case eScriptPython: Result = SCE_HP_START; break; case eScriptPHP: Result = SCE_HPHP_DEFAULT; break; case eScriptXML: Result = SCE_H_TAGUNKNOWN; break; case eScriptSGML: Result = SCE_H_SGML_DEFAULT; break; default : Result = SCE_HJ_START; break; } return Result; } static inline bool ishtmlwordchar(char ch) { return !isascii(ch) || (isalnum(ch) || ch == '.' || ch == '-' || ch == '_' || ch == ':' || ch == '!' || ch == '#'); } static inline bool issgmlwordchar(char ch) { return !isascii(ch) || (isalnum(ch) || ch == '.' || ch == '_' || ch == ':' || ch == '!' || ch == '#' || ch == '['); } static inline bool IsPhpWordStart(const unsigned char ch) { return (isascii(ch) && (isalpha(ch) || (ch == '_'))) || (ch >= 0x7f); } static inline bool IsPhpWordChar(char ch) { return IsADigit(ch) || IsPhpWordStart(ch); } static bool InTagState(int state) { return state == SCE_H_TAG || state == SCE_H_TAGUNKNOWN || state == SCE_H_SCRIPT || state == SCE_H_ATTRIBUTE || state == SCE_H_ATTRIBUTEUNKNOWN || state == SCE_H_NUMBER || state == SCE_H_OTHER || state == SCE_H_DOUBLESTRING || state == SCE_H_SINGLESTRING; } static bool IsCommentState(const int state) { return state == SCE_H_COMMENT || state == SCE_H_SGML_COMMENT; } static bool IsScriptCommentState(const int state) { return state == SCE_HJ_COMMENT || state == SCE_HJ_COMMENTLINE || state == SCE_HJA_COMMENT || state == SCE_HJA_COMMENTLINE || state == SCE_HB_COMMENTLINE || state == SCE_HBA_COMMENTLINE; } static bool isLineEnd(char ch) { return ch == '\r' || ch == '\n'; } static bool isOKBeforeRE(char ch) { return (ch == '(') || (ch == '=') || (ch == ','); } static bool isPHPStringState(int state) { return (state == SCE_HPHP_HSTRING) || (state == SCE_HPHP_SIMPLESTRING) || (state == SCE_HPHP_HSTRING_VARIABLE) || (state == SCE_HPHP_COMPLEX_VARIABLE); } static int FindPhpStringDelimiter(char *phpStringDelimiter, const int phpStringDelimiterSize, int i, const int lengthDoc, Accessor &styler) { int j; while (i < lengthDoc && (styler[i] == ' ' || styler[i] == '\t')) i++; phpStringDelimiter[0] = '\n'; for (j = i; j < lengthDoc && styler[j] != '\n' && styler[j] != '\r'; j++) { if (j - i < phpStringDelimiterSize - 2) phpStringDelimiter[j-i+1] = styler[j]; else i++; } phpStringDelimiter[j-i+1] = '\0'; return j; } static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; // SGML (DTD) keywords // Lexer for HTML requires more lexical states (7 bits worth) than most lexers styler.StartAt(startPos, STYLE_MAX); char prevWord[200]; prevWord[0] = '\0'; char phpStringDelimiter[200]; // PHP is not limited in length, we are phpStringDelimiter[0] = '\0'; int StateToPrint = initStyle; int state = stateForPrintState(StateToPrint); // If inside a tag, it may be a script tag, so reread from the start to ensure any language tags are seen if (InTagState(state)) { while ((startPos > 0) && (InTagState(styler.StyleAt(startPos - 1)))) { startPos--; length++; } state = SCE_H_DEFAULT; } // String can be heredoc, must find a delimiter first while (startPos > 0 && isPHPStringState(state) && state != SCE_HPHP_SIMPLESTRING) { startPos--; length++; state = styler.StyleAt(startPos); } styler.StartAt(startPos, STYLE_MAX); int lineCurrent = styler.GetLine(startPos); int lineState; if (lineCurrent > 0) { lineState = styler.GetLineState(lineCurrent); } else { // Default client and ASP scripting language is JavaScript lineState = eScriptJS << 8; lineState |= styler.GetPropertyInt("asp.default.language", eScriptJS) << 4; } script_mode inScriptType = script_mode((lineState >> 0) & 0x03); // 2 bits of scripting mode bool tagOpened = (lineState >> 2) & 0x01; // 1 bit to know if we are in an opened tag bool tagClosing = (lineState >> 3) & 0x01; // 1 bit to know if we are in a closing tag bool tagDontFold = false; //some HTML tags should not be folded script_type aspScript = script_type((lineState >> 4) & 0x0F); // 4 bits of script name script_type clientScript = script_type((lineState >> 8) & 0x0F); // 4 bits of script name int beforePreProc = (lineState >> 12) & 0xFF; // 8 bits of state script_type scriptLanguage = ScriptOfState(state); const bool foldHTML = styler.GetPropertyInt("fold.html", 0) != 0; const bool fold = foldHTML && styler.GetPropertyInt("fold", 0); const bool foldHTMLPreprocessor = foldHTML && styler.GetPropertyInt("fold.html.preprocessor", 1); const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; const bool caseSensitive = styler.GetPropertyInt("html.tags.case.sensitive", 0) != 0; int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; int visibleChars = 0; char chPrev = ' '; char ch = ' '; char chPrevNonWhite = ' '; // look back to set chPrevNonWhite properly for better regex colouring if (scriptLanguage == eScriptJS && startPos > 0) { int back = startPos; int style = 0; while (--back) { style = styler.StyleAt(back); if (style < SCE_HJ_DEFAULT || style > SCE_HJ_COMMENTDOC) // includes SCE_HJ_COMMENT & SCE_HJ_COMMENTLINE break; } if (style == SCE_HJ_SYMBOLS) { chPrevNonWhite = styler.SafeGetCharAt(back); } } styler.StartSegment(startPos); const int lengthDoc = startPos + length; for (int i = startPos; i < lengthDoc; i++) { const char chPrev2 = chPrev; chPrev = ch; if (!isspacechar(ch) && state != SCE_HJ_COMMENT && state != SCE_HJ_COMMENTLINE && state != SCE_HJ_COMMENTDOC) chPrevNonWhite = ch; ch = styler[i]; char chNext = styler.SafeGetCharAt(i + 1); const char chNext2 = styler.SafeGetCharAt(i + 2); // Handle DBCS codepages if (styler.IsLeadByte(ch)) { chPrev = ' '; i += 1; continue; } if ((!isspacechar(ch) || !foldCompact) && fold) visibleChars++; // decide what is the current state to print (depending of the script tag) StateToPrint = statePrintForState(state, inScriptType); // handle script folding if (fold) { switch (scriptLanguage) { case eScriptJS: case eScriptPHP: //not currently supported case eScriptVBS: if ((state != SCE_HPHP_COMMENT) && (state != SCE_HPHP_COMMENTLINE) && (state != SCE_HJ_COMMENT) && (state != SCE_HJ_COMMENTLINE) && (state != SCE_HJ_COMMENTDOC) && (!isStringState(state))) { //Platform::DebugPrintf("state=%d, StateToPrint=%d, initStyle=%d\n", state, StateToPrint, initStyle); //if ((state == SCE_HPHP_OPERATOR) || (state == SCE_HPHP_DEFAULT) || (state == SCE_HJ_SYMBOLS) || (state == SCE_HJ_START) || (state == SCE_HJ_DEFAULT)) { if ((ch == '{') || (ch == '}')) { levelCurrent += (ch == '{') ? 1 : -1; } } break; case eScriptPython: if (state != SCE_HP_COMMENTLINE) { if ((ch == ':') && ((chNext == '\n') || (chNext == '\r' && chNext2 == '\n'))) { levelCurrent++; } else if ((ch == '\n') && !((chNext == '\r') && (chNext2 == '\n')) && (chNext != '\n')) { // check if the number of tabs is lower than the level int Findlevel = (levelCurrent & ~SC_FOLDLEVELBASE) * 8; for (int j = 0; Findlevel > 0; j++) { char chTmp = styler.SafeGetCharAt(i + j + 1); if (chTmp == '\t') { Findlevel -= 8; } else if (chTmp == ' ') { Findlevel--; } else { break; } } if (Findlevel > 0) { levelCurrent -= Findlevel / 8; if (Findlevel % 8) levelCurrent--; } } } break; default: break; } } if ((ch == '\r' && chNext != '\n') || (ch == '\n')) { // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) // Avoid triggering two times on Dos/Win // New line -> record any line state onto /next/ line if (fold) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; styler.SetLevel(lineCurrent, lev); visibleChars = 0; levelPrev = levelCurrent; } lineCurrent++; styler.SetLineState(lineCurrent, ((inScriptType & 0x03) << 0) | ((tagOpened & 0x01) << 2) | ((tagClosing & 0x01) << 3) | ((aspScript & 0x0F) << 4) | ((clientScript & 0x0F) << 8) | ((beforePreProc & 0xFF) << 12)); } // generic end of script processing else if ((inScriptType == eNonHtmlScript) && (ch == '<') && (chNext == '/')) { // Check if it's the end of the script tag (or any other HTML tag) switch (state) { // in these cases, you can embed HTML tags (to confirm !!!!!!!!!!!!!!!!!!!!!!) case SCE_H_DOUBLESTRING: case SCE_H_SINGLESTRING: case SCE_HJ_COMMENT: case SCE_HJ_COMMENTDOC: //case SCE_HJ_COMMENTLINE: // removed as this is a common thing done to hide // the end of script marker from some JS interpreters. case SCE_HJ_DOUBLESTRING: case SCE_HJ_SINGLESTRING: case SCE_HJ_REGEX: case SCE_HB_STRING: case SCE_HP_STRING: case SCE_HP_TRIPLE: case SCE_HP_TRIPLEDOUBLE: break; default : // check if the closing tag is a script tag if (state == SCE_HJ_COMMENTLINE) { char tag[7]; // room for the <script> tag char chr; // current char int j=0; chr = styler.SafeGetCharAt(i+2); while (j < 6 && !isspacechar(chr)) { tag[j++] = static_cast<char>(MakeLowerCase(chr)); chr = styler.SafeGetCharAt(i+2+j); } tag[j] = '\0'; if (strcmp(tag, "script") != 0) break; } // closing tag of the script (it's a closing HTML tag anyway) styler.ColourTo(i - 1, StateToPrint); state = SCE_H_TAGUNKNOWN; inScriptType = eHtml; scriptLanguage = eScriptNone; clientScript = eScriptJS; i += 2; visibleChars += 2; tagClosing = true; continue; } } ///////////////////////////////////// // handle the start of PHP pre-processor = Non-HTML else if ((state != SCE_H_ASPAT) && !isPHPStringState(state) && (state != SCE_HPHP_COMMENT) && (ch == '<') && (chNext == '?') && !IsScriptCommentState(state) ) { scriptLanguage = segIsScriptingIndicator(styler, i + 2, i + 10, eScriptPHP); if (scriptLanguage != eScriptPHP && isStringState(state)) continue; styler.ColourTo(i - 1, StateToPrint); beforePreProc = state; i++; visibleChars++; i += PrintScriptingIndicatorOffset(styler, styler.GetStartSegment() + 2, i + 10); if (scriptLanguage == eScriptXML) styler.ColourTo(i, SCE_H_XMLSTART); else styler.ColourTo(i, SCE_H_QUESTION); state = StateForScript(scriptLanguage); if (inScriptType == eNonHtmlScript) inScriptType = eNonHtmlScriptPreProc; else inScriptType = eNonHtmlPreProc; // Fold whole script, but not if the XML first tag (all XML-like tags in this case) if (foldHTMLPreprocessor && (scriptLanguage != eScriptXML)) { levelCurrent++; } // should be better ch = styler.SafeGetCharAt(i); continue; } // handle the start of ASP pre-processor = Non-HTML else if (!isCommentASPState(state) && (ch == '<') && (chNext == '%') && !isPHPStringState(state)) { styler.ColourTo(i - 1, StateToPrint); beforePreProc = state; if (inScriptType == eNonHtmlScript) inScriptType = eNonHtmlScriptPreProc; else inScriptType = eNonHtmlPreProc; if (chNext2 == '@') { i += 2; // place as if it was the second next char treated visibleChars += 2; state = SCE_H_ASPAT; } else if ((chNext2 == '-') && (styler.SafeGetCharAt(i + 3) == '-')) { styler.ColourTo(i + 3, SCE_H_ASP); state = SCE_H_XCCOMMENT; scriptLanguage = eScriptVBS; continue; } else { if (chNext2 == '=') { i += 2; // place as if it was the second next char treated visibleChars += 2; } else { i++; // place as if it was the next char treated visibleChars++; } state = StateForScript(aspScript); } scriptLanguage = eScriptVBS; styler.ColourTo(i, SCE_H_ASP); // fold whole script if (foldHTMLPreprocessor) levelCurrent++; // should be better ch = styler.SafeGetCharAt(i); continue; } ///////////////////////////////////// // handle the start of SGML language (DTD) else if (((scriptLanguage == eScriptNone) || (scriptLanguage == eScriptXML)) && (chPrev == '<') && (ch == '!') && (StateToPrint != SCE_H_CDATA) && (!IsCommentState(StateToPrint)) && (!IsScriptCommentState(StateToPrint)) ) { beforePreProc = state; styler.ColourTo(i - 2, StateToPrint); if ((chNext == '-') && (chNext2 == '-')) { state = SCE_H_COMMENT; // wait for a pending command styler.ColourTo(i + 2, SCE_H_COMMENT); i += 2; // follow styling after the -- } else if (isWordCdata(i + 1, i + 7, styler)) { state = SCE_H_CDATA; } else { styler.ColourTo(i, SCE_H_SGML_DEFAULT); // <! is default scriptLanguage = eScriptSGML; state = SCE_H_SGML_COMMAND; // wait for a pending command } // fold whole tag (-- when closing the tag) if (foldHTMLPreprocessor) levelCurrent++; continue; } // handle the end of a pre-processor = Non-HTML else if (( ((inScriptType == eNonHtmlPreProc) || (inScriptType == eNonHtmlScriptPreProc)) && ( ((scriptLanguage != eScriptNone) && stateAllowsTermination(state) && ((ch == '%') || (ch == '?'))) ) && (chNext == '>')) || ((scriptLanguage == eScriptSGML) && (ch == '>') && (state != SCE_H_SGML_COMMENT))) { if (state == SCE_H_ASPAT) { aspScript = segIsScriptingIndicator(styler, styler.GetStartSegment(), i - 1, aspScript); } // Bounce out of any ASP mode switch (state) { case SCE_HJ_WORD: classifyWordHTJS(styler.GetStartSegment(), i - 1, keywords2, styler, inScriptType); break; case SCE_HB_WORD: classifyWordHTVB(styler.GetStartSegment(), i - 1, keywords3, styler, inScriptType); break; case SCE_HP_WORD: classifyWordHTPy(styler.GetStartSegment(), i - 1, keywords4, styler, prevWord, inScriptType); break; case SCE_HPHP_WORD: classifyWordHTPHP(styler.GetStartSegment(), i - 1, keywords5, styler); break; case SCE_H_XCCOMMENT: styler.ColourTo(i - 1, state); break; default : styler.ColourTo(i - 1, StateToPrint); break; } if (scriptLanguage != eScriptSGML) { i++; visibleChars++; } if (ch == '%') styler.ColourTo(i, SCE_H_ASP); else if (scriptLanguage == eScriptXML) styler.ColourTo(i, SCE_H_XMLEND); else if (scriptLanguage == eScriptSGML) styler.ColourTo(i, SCE_H_SGML_DEFAULT); else styler.ColourTo(i, SCE_H_QUESTION); state = beforePreProc; if (inScriptType == eNonHtmlScriptPreProc) inScriptType = eNonHtmlScript; else inScriptType = eHtml; // Unfold all scripting languages, except for XML tag if (foldHTMLPreprocessor && (scriptLanguage != eScriptXML)) { levelCurrent--; } scriptLanguage = eScriptNone; continue; } ///////////////////////////////////// switch (state) { case SCE_H_DEFAULT: if (ch == '<') { // in HTML, fold on tag open and unfold on tag close tagOpened = true; tagClosing = (chNext == '/'); styler.ColourTo(i - 1, StateToPrint); if (chNext != '!') state = SCE_H_TAGUNKNOWN; } else if (ch == '&') { styler.ColourTo(i - 1, SCE_H_DEFAULT); state = SCE_H_ENTITY; } break; case SCE_H_SGML_DEFAULT: case SCE_H_SGML_BLOCK_DEFAULT: // if (scriptLanguage == eScriptSGMLblock) // StateToPrint = SCE_H_SGML_BLOCK_DEFAULT; if (ch == '\"') { styler.ColourTo(i - 1, StateToPrint); state = SCE_H_SGML_DOUBLESTRING; } else if (ch == '\'') { styler.ColourTo(i - 1, StateToPrint); state = SCE_H_SGML_SIMPLESTRING; } else if ((ch == '-') && (chPrev == '-')) { if (static_cast<int>(styler.GetStartSegment()) <= (i - 2)) { styler.ColourTo(i - 2, StateToPrint); } state = SCE_H_SGML_COMMENT; } else if (isascii(ch) && isalpha(ch) && (chPrev == '%')) { styler.ColourTo(i - 2, StateToPrint); state = SCE_H_SGML_ENTITY; } else if (ch == '#') { styler.ColourTo(i - 1, StateToPrint); state = SCE_H_SGML_SPECIAL; } else if (ch == '[') { styler.ColourTo(i - 1, StateToPrint); scriptLanguage = eScriptSGMLblock; state = SCE_H_SGML_BLOCK_DEFAULT; } else if (ch == ']') { if (scriptLanguage == eScriptSGMLblock) { styler.ColourTo(i, StateToPrint); scriptLanguage = eScriptSGML; } else { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i, SCE_H_SGML_ERROR); } state = SCE_H_SGML_DEFAULT; } else if (scriptLanguage == eScriptSGMLblock) { if ((ch == '!') && (chPrev == '<')) { styler.ColourTo(i - 2, StateToPrint); styler.ColourTo(i, SCE_H_SGML_DEFAULT); state = SCE_H_SGML_COMMAND; } else if (ch == '>') { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i, SCE_H_SGML_DEFAULT); } } break; case SCE_H_SGML_COMMAND: if ((ch == '-') && (chPrev == '-')) { styler.ColourTo(i - 2, StateToPrint); state = SCE_H_SGML_COMMENT; } else if (!issgmlwordchar(ch)) { if (isWordHSGML(styler.GetStartSegment(), i - 1, keywords6, styler)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_H_SGML_1ST_PARAM; } else { state = SCE_H_SGML_ERROR; } } break; case SCE_H_SGML_1ST_PARAM: // wait for the beginning of the word if ((ch == '-') && (chPrev == '-')) { if (scriptLanguage == eScriptSGMLblock) { styler.ColourTo(i - 2, SCE_H_SGML_BLOCK_DEFAULT); } else { styler.ColourTo(i - 2, SCE_H_SGML_DEFAULT); } state = SCE_H_SGML_1ST_PARAM_COMMENT; } else if (issgmlwordchar(ch)) { if (scriptLanguage == eScriptSGMLblock) { styler.ColourTo(i - 1, SCE_H_SGML_BLOCK_DEFAULT); } else { styler.ColourTo(i - 1, SCE_H_SGML_DEFAULT); } // find the length of the word int size = 1; while (ishtmlwordchar(styler.SafeGetCharAt(i + size))) size++; styler.ColourTo(i + size - 1, StateToPrint); i += size - 1; visibleChars += size - 1; ch = styler.SafeGetCharAt(i); if (scriptLanguage == eScriptSGMLblock) { state = SCE_H_SGML_BLOCK_DEFAULT; } else { state = SCE_H_SGML_DEFAULT; } continue; } break; case SCE_H_SGML_ERROR: if ((ch == '-') && (chPrev == '-')) { styler.ColourTo(i - 2, StateToPrint); state = SCE_H_SGML_COMMENT; } case SCE_H_SGML_DOUBLESTRING: if (ch == '\"') { styler.ColourTo(i, StateToPrint); state = SCE_H_SGML_DEFAULT; } break; case SCE_H_SGML_SIMPLESTRING: if (ch == '\'') { styler.ColourTo(i, StateToPrint); state = SCE_H_SGML_DEFAULT; } break; case SCE_H_SGML_COMMENT: if ((ch == '-') && (chPrev == '-')) { styler.ColourTo(i, StateToPrint); state = SCE_H_SGML_DEFAULT; } break; case SCE_H_CDATA: if ((chPrev2 == ']') && (chPrev == ']') && (ch == '>')) { styler.ColourTo(i, StateToPrint); state = SCE_H_DEFAULT; levelCurrent--; } break; case SCE_H_COMMENT: if ((chPrev2 == '-') && (chPrev == '-') && (ch == '>')) { styler.ColourTo(i, StateToPrint); state = SCE_H_DEFAULT; levelCurrent--; } break; case SCE_H_SGML_1ST_PARAM_COMMENT: if ((ch == '-') && (chPrev == '-')) { styler.ColourTo(i, SCE_H_SGML_COMMENT); state = SCE_H_SGML_1ST_PARAM; } break; case SCE_H_SGML_SPECIAL: if (!(isascii(ch) && isupper(ch))) { styler.ColourTo(i - 1, StateToPrint); if (isalnum(ch)) { state = SCE_H_SGML_ERROR; } else { state = SCE_H_SGML_DEFAULT; } } break; case SCE_H_SGML_ENTITY: if (ch == ';') { styler.ColourTo(i, StateToPrint); state = SCE_H_SGML_DEFAULT; } else if (!(isascii(ch) && isalnum(ch)) && ch != '-' && ch != '.') { styler.ColourTo(i, SCE_H_SGML_ERROR); state = SCE_H_SGML_DEFAULT; } break; case SCE_H_ENTITY: if (ch == ';') { styler.ColourTo(i, StateToPrint); state = SCE_H_DEFAULT; } if (ch != '#' && !(isascii(ch) && isalnum(ch)) // Should check that '#' follows '&', but it is unlikely anyway... && ch != '.' && ch != '-' && ch != '_' && ch != ':') { // valid in XML styler.ColourTo(i, SCE_H_TAGUNKNOWN); state = SCE_H_DEFAULT; } break; case SCE_H_TAGUNKNOWN: if (!ishtmlwordchar(ch) && !((ch == '/') && (chPrev == '<')) && ch != '[') { int eClass = classifyTagHTML(styler.GetStartSegment(), i - 1, keywords, styler, tagDontFold, caseSensitive); if (eClass == SCE_H_SCRIPT) { if (!tagClosing) { inScriptType = eNonHtmlScript; scriptLanguage = clientScript; eClass = SCE_H_TAG; } else { scriptLanguage = eScriptNone; eClass = SCE_H_TAG; } } if (ch == '>') { styler.ColourTo(i, eClass); if (inScriptType == eNonHtmlScript) { state = StateForScript(scriptLanguage); } else { state = SCE_H_DEFAULT; } tagOpened = false; if (!tagDontFold){ if (tagClosing) { levelCurrent--; } else { levelCurrent++; } } tagClosing = false; } else if (ch == '/' && chNext == '>') { if (eClass == SCE_H_TAGUNKNOWN) { styler.ColourTo(i + 1, SCE_H_TAGUNKNOWN); } else { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i + 1, SCE_H_TAGEND); } i++; ch = chNext; state = SCE_H_DEFAULT; tagOpened = false; } else { if (eClass != SCE_H_TAGUNKNOWN) { if (eClass == SCE_H_SGML_DEFAULT) { state = SCE_H_SGML_DEFAULT; } else { state = SCE_H_OTHER; } } } } break; case SCE_H_ATTRIBUTE: if (!ishtmlwordchar(ch) && ch != '/' && ch != '-') { if (inScriptType == eNonHtmlScript) { int scriptLanguagePrev = scriptLanguage; clientScript = segIsScriptingIndicator(styler, styler.GetStartSegment(), i - 1, scriptLanguage); scriptLanguage = clientScript; if ((scriptLanguagePrev != scriptLanguage) && (scriptLanguage == eScriptNone)) inScriptType = eHtml; } classifyAttribHTML(styler.GetStartSegment(), i - 1, keywords, styler); if (ch == '>') { styler.ColourTo(i, SCE_H_TAG); if (inScriptType == eNonHtmlScript) { state = StateForScript(scriptLanguage); } else { state = SCE_H_DEFAULT; } tagOpened = false; if (!tagDontFold){ if (tagClosing){ levelCurrent--; } else { levelCurrent++; } } tagClosing = false; } else if (ch == '=') { styler.ColourTo(i, SCE_H_OTHER); state = SCE_H_VALUE; } else { state = SCE_H_OTHER; } } break; case SCE_H_OTHER: if (ch == '>') { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i, SCE_H_TAG); if (inScriptType == eNonHtmlScript) { state = StateForScript(scriptLanguage); } else { state = SCE_H_DEFAULT; } tagOpened = false; if (!tagDontFold){ if (tagClosing){ levelCurrent--; } else { levelCurrent++; } } tagClosing = false; } else if (ch == '\"') { styler.ColourTo(i - 1, StateToPrint); state = SCE_H_DOUBLESTRING; } else if (ch == '\'') { styler.ColourTo(i - 1, StateToPrint); state = SCE_H_SINGLESTRING; } else if (ch == '=') { styler.ColourTo(i, StateToPrint); state = SCE_H_VALUE; } else if (ch == '/' && chNext == '>') { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i + 1, SCE_H_TAGEND); i++; ch = chNext; state = SCE_H_DEFAULT; tagOpened = false; } else if (ch == '?' && chNext == '>') { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i + 1, SCE_H_XMLEND); i++; ch = chNext; state = SCE_H_DEFAULT; } else if (ishtmlwordchar(ch)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_H_ATTRIBUTE; } break; case SCE_H_DOUBLESTRING: if (ch == '\"') { if (inScriptType == eNonHtmlScript) { scriptLanguage = segIsScriptingIndicator(styler, styler.GetStartSegment(), i, scriptLanguage); } styler.ColourTo(i, SCE_H_DOUBLESTRING); state = SCE_H_OTHER; } break; case SCE_H_SINGLESTRING: if (ch == '\'') { if (inScriptType == eNonHtmlScript) { scriptLanguage = segIsScriptingIndicator(styler, styler.GetStartSegment(), i, scriptLanguage); } styler.ColourTo(i, SCE_H_SINGLESTRING); state = SCE_H_OTHER; } break; case SCE_H_VALUE: if (!ishtmlwordchar(ch)) { if (ch == '\"' && chPrev == '=') { // Should really test for being first character state = SCE_H_DOUBLESTRING; } else if (ch == '\'' && chPrev == '=') { state = SCE_H_SINGLESTRING; } else { if (IsNumber(styler.GetStartSegment(), styler)) { styler.ColourTo(i - 1, SCE_H_NUMBER); } else { styler.ColourTo(i - 1, StateToPrint); } if (ch == '>') { styler.ColourTo(i, SCE_H_TAG); if (inScriptType == eNonHtmlScript) { state = StateForScript(scriptLanguage); } else { state = SCE_H_DEFAULT; } tagOpened = false; if (!tagDontFold){ if (tagClosing){ levelCurrent--; } else { levelCurrent++; } } tagClosing = false; } else { state = SCE_H_OTHER; } } } break; case SCE_HJ_DEFAULT: case SCE_HJ_START: case SCE_HJ_SYMBOLS: if (iswordstart(ch)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_WORD; } else if (ch == '/' && chNext == '*') { styler.ColourTo(i - 1, StateToPrint); if (chNext2 == '*') state = SCE_HJ_COMMENTDOC; else state = SCE_HJ_COMMENT; } else if (ch == '/' && chNext == '/') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_COMMENTLINE; } else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_REGEX; } else if (ch == '\"') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_DOUBLESTRING; } else if (ch == '\'') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_SINGLESTRING; } else if ((ch == '<') && (chNext == '!') && (chNext2 == '-') && styler.SafeGetCharAt(i + 3) == '-') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_COMMENTLINE; } else if ((ch == '-') && (chNext == '-') && (chNext2 == '>')) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_COMMENTLINE; i += 2; } else if (isoperator(ch)) { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i, statePrintForState(SCE_HJ_SYMBOLS, inScriptType)); state = SCE_HJ_DEFAULT; } else if ((ch == ' ') || (ch == '\t')) { if (state == SCE_HJ_START) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_DEFAULT; } } break; case SCE_HJ_WORD: if (!iswordchar(ch)) { classifyWordHTJS(styler.GetStartSegment(), i - 1, keywords2, styler, inScriptType); //styler.ColourTo(i - 1, eHTJSKeyword); state = SCE_HJ_DEFAULT; if (ch == '/' && chNext == '*') { if (chNext2 == '*') state = SCE_HJ_COMMENTDOC; else state = SCE_HJ_COMMENT; } else if (ch == '/' && chNext == '/') { state = SCE_HJ_COMMENTLINE; } else if (ch == '\"') { state = SCE_HJ_DOUBLESTRING; } else if (ch == '\'') { state = SCE_HJ_SINGLESTRING; } else if ((ch == '-') && (chNext == '-') && (chNext2 == '>')) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_COMMENTLINE; i += 2; } else if (isoperator(ch)) { styler.ColourTo(i, statePrintForState(SCE_HJ_SYMBOLS, inScriptType)); state = SCE_HJ_DEFAULT; } } break; case SCE_HJ_COMMENT: case SCE_HJ_COMMENTDOC: if (ch == '/' && chPrev == '*') { styler.ColourTo(i, StateToPrint); state = SCE_HJ_DEFAULT; ch = ' '; } break; case SCE_HJ_COMMENTLINE: if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, statePrintForState(SCE_HJ_COMMENTLINE, inScriptType)); state = SCE_HJ_DEFAULT; ch = ' '; } break; case SCE_HJ_DOUBLESTRING: if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; } } else if (ch == '\"') { styler.ColourTo(i, statePrintForState(SCE_HJ_DOUBLESTRING, inScriptType)); state = SCE_HJ_DEFAULT; } else if ((inScriptType == eNonHtmlScript) && (ch == '-') && (chNext == '-') && (chNext2 == '>')) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_COMMENTLINE; i += 2; } else if (isLineEnd(ch)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_STRINGEOL; } break; case SCE_HJ_SINGLESTRING: if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; } } else if (ch == '\'') { styler.ColourTo(i, statePrintForState(SCE_HJ_SINGLESTRING, inScriptType)); state = SCE_HJ_DEFAULT; } else if ((inScriptType == eNonHtmlScript) && (ch == '-') && (chNext == '-') && (chNext2 == '>')) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_COMMENTLINE; i += 2; } else if (isLineEnd(ch)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_STRINGEOL; } break; case SCE_HJ_STRINGEOL: if (!isLineEnd(ch)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HJ_DEFAULT; } else if (!isLineEnd(chNext)) { styler.ColourTo(i, StateToPrint); state = SCE_HJ_DEFAULT; } break; case SCE_HJ_REGEX: if (ch == '\r' || ch == '\n' || ch == '/') { if (ch == '/') { while (isascii(chNext) && islower(chNext)) { // gobble regex flags i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } styler.ColourTo(i, StateToPrint); state = SCE_HJ_DEFAULT; } else if (ch == '\\') { // Gobble up the quoted character if (chNext == '\\' || chNext == '/') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } break; case SCE_HB_DEFAULT: case SCE_HB_START: if (iswordstart(ch)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HB_WORD; } else if (ch == '\'') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HB_COMMENTLINE; } else if (ch == '\"') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HB_STRING; } else if ((ch == '<') && (chNext == '!') && (chNext2 == '-') && styler.SafeGetCharAt(i + 3) == '-') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HB_COMMENTLINE; } else if (isoperator(ch)) { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i, statePrintForState(SCE_HB_DEFAULT, inScriptType)); state = SCE_HB_DEFAULT; } else if ((ch == ' ') || (ch == '\t')) { if (state == SCE_HB_START) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HB_DEFAULT; } } break; case SCE_HB_WORD: if (!iswordchar(ch)) { state = classifyWordHTVB(styler.GetStartSegment(), i - 1, keywords3, styler, inScriptType); if (state == SCE_HB_DEFAULT) { if (ch == '\"') { state = SCE_HB_STRING; } else if (ch == '\'') { state = SCE_HB_COMMENTLINE; } else if (isoperator(ch)) { styler.ColourTo(i, statePrintForState(SCE_HB_DEFAULT, inScriptType)); state = SCE_HB_DEFAULT; } } } break; case SCE_HB_STRING: if (ch == '\"') { styler.ColourTo(i, StateToPrint); state = SCE_HB_DEFAULT; } else if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HB_STRINGEOL; } break; case SCE_HB_COMMENTLINE: if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HB_DEFAULT; } break; case SCE_HB_STRINGEOL: if (!isLineEnd(ch)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HB_DEFAULT; } else if (!isLineEnd(chNext)) { styler.ColourTo(i, StateToPrint); state = SCE_HB_DEFAULT; } break; case SCE_HP_DEFAULT: case SCE_HP_START: if (iswordstart(ch)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HP_WORD; } else if ((ch == '<') && (chNext == '!') && (chNext2 == '-') && styler.SafeGetCharAt(i + 3) == '-') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HP_COMMENTLINE; } else if (ch == '#') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HP_COMMENTLINE; } else if (ch == '\"') { styler.ColourTo(i - 1, StateToPrint); if (chNext == '\"' && chNext2 == '\"') { i += 2; state = SCE_HP_TRIPLEDOUBLE; ch = ' '; chPrev = ' '; chNext = styler.SafeGetCharAt(i + 1); } else { // state = statePrintForState(SCE_HP_STRING,inScriptType); state = SCE_HP_STRING; } } else if (ch == '\'') { styler.ColourTo(i - 1, StateToPrint); if (chNext == '\'' && chNext2 == '\'') { i += 2; state = SCE_HP_TRIPLE; ch = ' '; chPrev = ' '; chNext = styler.SafeGetCharAt(i + 1); } else { state = SCE_HP_CHARACTER; } } else if (isoperator(ch)) { styler.ColourTo(i - 1, StateToPrint); styler.ColourTo(i, statePrintForState(SCE_HP_OPERATOR, inScriptType)); } else if ((ch == ' ') || (ch == '\t')) { if (state == SCE_HP_START) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HP_DEFAULT; } } break; case SCE_HP_WORD: if (!iswordchar(ch)) { classifyWordHTPy(styler.GetStartSegment(), i - 1, keywords4, styler, prevWord, inScriptType); state = SCE_HP_DEFAULT; if (ch == '#') { state = SCE_HP_COMMENTLINE; } else if (ch == '\"') { if (chNext == '\"' && chNext2 == '\"') { i += 2; state = SCE_HP_TRIPLEDOUBLE; ch = ' '; chPrev = ' '; chNext = styler.SafeGetCharAt(i + 1); } else { state = SCE_HP_STRING; } } else if (ch == '\'') { if (chNext == '\'' && chNext2 == '\'') { i += 2; state = SCE_HP_TRIPLE; ch = ' '; chPrev = ' '; chNext = styler.SafeGetCharAt(i + 1); } else { state = SCE_HP_CHARACTER; } } else if (isoperator(ch)) { styler.ColourTo(i, statePrintForState(SCE_HP_OPERATOR, inScriptType)); } } break; case SCE_HP_COMMENTLINE: if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HP_DEFAULT; } break; case SCE_HP_STRING: if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, StateToPrint); state = SCE_HP_DEFAULT; } break; case SCE_HP_CHARACTER: if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, StateToPrint); state = SCE_HP_DEFAULT; } break; case SCE_HP_TRIPLE: if (ch == '\'' && chPrev == '\'' && chPrev2 == '\'') { styler.ColourTo(i, StateToPrint); state = SCE_HP_DEFAULT; } break; case SCE_HP_TRIPLEDOUBLE: if (ch == '\"' && chPrev == '\"' && chPrev2 == '\"') { styler.ColourTo(i, StateToPrint); state = SCE_HP_DEFAULT; } break; ///////////// start - PHP state handling case SCE_HPHP_WORD: if (!iswordchar(ch)) { classifyWordHTPHP(styler.GetStartSegment(), i - 1, keywords5, styler); if (ch == '/' && chNext == '*') { i++; state = SCE_HPHP_COMMENT; } else if (ch == '/' && chNext == '/') { i++; state = SCE_HPHP_COMMENTLINE; } else if (ch == '#') { state = SCE_HPHP_COMMENTLINE; } else if (ch == '\"') { state = SCE_HPHP_HSTRING; strcpy(phpStringDelimiter, "\""); } else if (styler.Match(i, "<<<")) { state = SCE_HPHP_HSTRING; i = FindPhpStringDelimiter(phpStringDelimiter, sizeof(phpStringDelimiter), i + 3, lengthDoc, styler); } else if (ch == '\'') { state = SCE_HPHP_SIMPLESTRING; } else if (ch == '$' && IsPhpWordStart(chNext)) { state = SCE_HPHP_VARIABLE; } else if (isoperator(ch)) { state = SCE_HPHP_OPERATOR; } else { state = SCE_HPHP_DEFAULT; } } break; case SCE_HPHP_NUMBER: // recognize bases 8,10 or 16 integers OR floating-point numbers if (!IsADigit(ch) && strchr(".xXabcdefABCDEF", ch) == NULL && ((ch != '-' && ch != '+') || (chPrev != 'e' && chPrev != 'E'))) { styler.ColourTo(i - 1, SCE_HPHP_NUMBER); if (isoperator(ch)) state = SCE_HPHP_OPERATOR; else state = SCE_HPHP_DEFAULT; } break; case SCE_HPHP_VARIABLE: if (!IsPhpWordChar(ch)) { styler.ColourTo(i - 1, SCE_HPHP_VARIABLE); if (isoperator(ch)) state = SCE_HPHP_OPERATOR; else state = SCE_HPHP_DEFAULT; } break; case SCE_HPHP_COMMENT: if (ch == '/' && chPrev == '*') { styler.ColourTo(i, StateToPrint); state = SCE_HPHP_DEFAULT; } break; case SCE_HPHP_COMMENTLINE: if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, StateToPrint); state = SCE_HPHP_DEFAULT; } break; case SCE_HPHP_HSTRING: if (ch == '\\' && (phpStringDelimiter[0] == '\"' || chNext == '$' || chNext == '{')) { // skip the next char i++; } else if (((ch == '{' && chNext == '$') || (ch == '$' && chNext == '{')) && IsPhpWordStart(chNext2)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HPHP_COMPLEX_VARIABLE; } else if (ch == '$' && IsPhpWordStart(chNext)) { styler.ColourTo(i - 1, StateToPrint); state = SCE_HPHP_HSTRING_VARIABLE; } else if (styler.Match(i, phpStringDelimiter)) { const int psdLength = strlen(phpStringDelimiter); if ((psdLength > 1) && ((i + psdLength) < lengthDoc)) i += psdLength - 1; styler.ColourTo(i, StateToPrint); state = SCE_HPHP_DEFAULT; } break; case SCE_HPHP_SIMPLESTRING: if (ch == '\\') { // skip the next char i++; } else if (ch == '\'') { styler.ColourTo(i, StateToPrint); state = SCE_HPHP_DEFAULT; } break; case SCE_HPHP_HSTRING_VARIABLE: if (!IsPhpWordChar(ch)) { styler.ColourTo(i - 1, StateToPrint); i--; // strange but it works state = SCE_HPHP_HSTRING; } break; case SCE_HPHP_COMPLEX_VARIABLE: if (ch == '}') { styler.ColourTo(i, StateToPrint); state = SCE_HPHP_HSTRING; } break; case SCE_HPHP_OPERATOR: case SCE_HPHP_DEFAULT: styler.ColourTo(i - 1, StateToPrint); if (IsADigit(ch) || (ch == '.' && IsADigit(chNext))) { state = SCE_HPHP_NUMBER; } else if (iswordstart(ch)) { state = SCE_HPHP_WORD; } else if (ch == '/' && chNext == '*') { i++; state = SCE_HPHP_COMMENT; } else if (ch == '/' && chNext == '/') { i++; state = SCE_HPHP_COMMENTLINE; } else if (ch == '#') { state = SCE_HPHP_COMMENTLINE; } else if (ch == '\"') { state = SCE_HPHP_HSTRING; strcpy(phpStringDelimiter, "\""); } else if (styler.Match(i, "<<<")) { state = SCE_HPHP_HSTRING; i = FindPhpStringDelimiter(phpStringDelimiter, sizeof(phpStringDelimiter), i + 3, lengthDoc, styler); } else if (ch == '\'') { state = SCE_HPHP_SIMPLESTRING; } else if (ch == '$' && IsPhpWordStart(chNext)) { state = SCE_HPHP_VARIABLE; } else if (isoperator(ch)) { state = SCE_HPHP_OPERATOR; } else if ((state == SCE_HPHP_OPERATOR) && (isspacechar(ch))) { state = SCE_HPHP_DEFAULT; } break; ///////////// end - PHP state handling } // Some of the above terminated their lexeme but since the same character starts // the same class again, only reenter if non empty segment. bool nonEmptySegment = i >= static_cast<int>(styler.GetStartSegment()); if (state == SCE_HB_DEFAULT) { // One of the above succeeded if ((ch == '\"') && (nonEmptySegment)) { state = SCE_HB_STRING; } else if (ch == '\'') { state = SCE_HB_COMMENTLINE; } else if (iswordstart(ch)) { state = SCE_HB_WORD; } else if (isoperator(ch)) { styler.ColourTo(i, SCE_HB_DEFAULT); } } else if (state == SCE_HBA_DEFAULT) { // One of the above succeeded if ((ch == '\"') && (nonEmptySegment)) { state = SCE_HBA_STRING; } else if (ch == '\'') { state = SCE_HBA_COMMENTLINE; } else if (iswordstart(ch)) { state = SCE_HBA_WORD; } else if (isoperator(ch)) { styler.ColourTo(i, SCE_HBA_DEFAULT); } } else if (state == SCE_HJ_DEFAULT) { // One of the above succeeded if (ch == '/' && chNext == '*') { if (styler.SafeGetCharAt(i + 2) == '*') state = SCE_HJ_COMMENTDOC; else state = SCE_HJ_COMMENT; } else if (ch == '/' && chNext == '/') { state = SCE_HJ_COMMENTLINE; } else if ((ch == '\"') && (nonEmptySegment)) { state = SCE_HJ_DOUBLESTRING; } else if ((ch == '\'') && (nonEmptySegment)) { state = SCE_HJ_SINGLESTRING; } else if (iswordstart(ch)) { state = SCE_HJ_WORD; } else if (isoperator(ch)) { styler.ColourTo(i, statePrintForState(SCE_HJ_SYMBOLS, inScriptType)); } } } StateToPrint = statePrintForState(state, inScriptType); styler.ColourTo(lengthDoc - 1, StateToPrint); // Fill in the real level of the next line, keeping the current flags as they will be filled in later if (fold) { int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } } static bool isASPScript(int state) { return (state >= SCE_HJA_START && state <= SCE_HJA_REGEX) || (state >= SCE_HBA_START && state <= SCE_HBA_STRINGEOL) || (state >= SCE_HPA_DEFAULT && state <= SCE_HPA_IDENTIFIER); } static void ColouriseHBAPiece(StyleContext &sc, WordList *keywordlists[]) { WordList &keywordsVBS = *keywordlists[2]; if (sc.state == SCE_HBA_WORD) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywordsVBS.InList(s)) { if (strcmp(s, "rem") == 0) { sc.ChangeState(SCE_HBA_COMMENTLINE); if (sc.atLineEnd) { sc.SetState(SCE_HBA_DEFAULT); } } else { sc.SetState(SCE_HBA_DEFAULT); } } else { sc.ChangeState(SCE_HBA_IDENTIFIER); sc.SetState(SCE_HBA_DEFAULT); } } } else if (sc.state == SCE_HBA_NUMBER) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_HBA_DEFAULT); } } else if (sc.state == SCE_HBA_STRING) { if (sc.ch == '\"') { sc.ForwardSetState(SCE_HBA_DEFAULT); } else if (sc.ch == '\r' || sc.ch == '\n') { sc.ChangeState(SCE_HBA_STRINGEOL); sc.ForwardSetState(SCE_HBA_DEFAULT); } } else if (sc.state == SCE_HBA_COMMENTLINE) { if (sc.ch == '\r' || sc.ch == '\n') { sc.SetState(SCE_HBA_DEFAULT); } } if (sc.state == SCE_HBA_DEFAULT) { if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_HBA_NUMBER); } else if (IsAWordStart(sc.ch)) { sc.SetState(SCE_HBA_WORD); } else if (sc.ch == '\'') { sc.SetState(SCE_HBA_COMMENTLINE); } else if (sc.ch == '\"') { sc.SetState(SCE_HBA_STRING); } } } static void ColouriseHTMLPiece(StyleContext &sc, WordList *keywordlists[]) { WordList &keywordsTags = *keywordlists[0]; if (sc.state == SCE_H_COMMENT) { if (sc.Match("-->")) { sc.Forward(); sc.Forward(); sc.ForwardSetState(SCE_H_DEFAULT); } } else if (sc.state == SCE_H_ENTITY) { if (sc.ch == ';') { sc.ForwardSetState(SCE_H_DEFAULT); } else if (sc.ch != '#' && (sc.ch < 0x80) && !isalnum(sc.ch) // Should check that '#' follows '&', but it is unlikely anyway... && sc.ch != '.' && sc.ch != '-' && sc.ch != '_' && sc.ch != ':') { // valid in XML sc.ChangeState(SCE_H_TAGUNKNOWN); sc.SetState(SCE_H_DEFAULT); } } else if (sc.state == SCE_H_TAGUNKNOWN) { if (!ishtmlwordchar(static_cast<char>(sc.ch)) && !((sc.ch == '/') && (sc.chPrev == '<')) && sc.ch != '[') { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (s[1] == '/') { if (keywordsTags.InList(s + 2)) { sc.ChangeState(SCE_H_TAG); } } else { if (keywordsTags.InList(s + 1)) { sc.ChangeState(SCE_H_TAG); } } if (sc.ch == '>') { sc.ForwardSetState(SCE_H_DEFAULT); } else if (sc.Match('/', '>')) { sc.SetState(SCE_H_TAGEND); sc.Forward(); sc.ForwardSetState(SCE_H_DEFAULT); } else { sc.SetState(SCE_H_OTHER); } } } else if (sc.state == SCE_H_ATTRIBUTE) { if (!ishtmlwordchar(static_cast<char>(sc.ch))) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (!keywordsTags.InList(s)) { sc.ChangeState(SCE_H_ATTRIBUTEUNKNOWN); } sc.SetState(SCE_H_OTHER); } } else if (sc.state == SCE_H_OTHER) { if (sc.ch == '>') { sc.SetState(SCE_H_TAG); sc.ForwardSetState(SCE_H_DEFAULT); } else if (sc.Match('/', '>')) { sc.SetState(SCE_H_TAG); sc.Forward(); sc.ForwardSetState(SCE_H_DEFAULT); } else if (sc.chPrev == '=') { sc.SetState(SCE_H_VALUE); } } else if (sc.state == SCE_H_DOUBLESTRING) { if (sc.ch == '\"') { sc.ForwardSetState(SCE_H_OTHER); } } else if (sc.state == SCE_H_SINGLESTRING) { if (sc.ch == '\'') { sc.ForwardSetState(SCE_H_OTHER); } } else if (sc.state == SCE_H_NUMBER) { if (!IsADigit(sc.ch)) { sc.SetState(SCE_H_OTHER); } } if (sc.state == SCE_H_DEFAULT) { if (sc.ch == '<') { if (sc.Match("<!--")) sc.SetState(SCE_H_COMMENT); else sc.SetState(SCE_H_TAGUNKNOWN); } else if (sc.ch == '&') { sc.SetState(SCE_H_ENTITY); } } else if ((sc.state == SCE_H_OTHER) || (sc.state == SCE_H_VALUE)) { if (sc.ch == '\"' && sc.chPrev == '=') { sc.SetState(SCE_H_DOUBLESTRING); } else if (sc.ch == '\'' && sc.chPrev == '=') { sc.SetState(SCE_H_SINGLESTRING); } else if (IsADigit(sc.ch)) { sc.SetState(SCE_H_NUMBER); } else if (sc.ch == '>') { sc.SetState(SCE_H_TAG); sc.ForwardSetState(SCE_H_DEFAULT); } else if (ishtmlwordchar(static_cast<char>(sc.ch))) { sc.SetState(SCE_H_ATTRIBUTE); } } } static void ColouriseASPPiece(StyleContext &sc, WordList *keywordlists[]) { // Possibly exit current state to either SCE_H_DEFAULT or SCE_HBA_DEFAULT if ((sc.state == SCE_H_ASPAT || isASPScript(sc.state)) && sc.Match('%', '>')) { sc.SetState(SCE_H_ASP); sc.Forward(); sc.ForwardSetState(SCE_H_DEFAULT); } // Handle some ASP script if (sc.state >= SCE_HBA_START && sc.state <= SCE_HBA_STRINGEOL) { ColouriseHBAPiece(sc, keywordlists); } else if (sc.state >= SCE_H_DEFAULT && sc.state <= SCE_H_SGML_BLOCK_DEFAULT) { ColouriseHTMLPiece(sc, keywordlists); } // Enter new sc.state if ((sc.state == SCE_H_DEFAULT) || (sc.state == SCE_H_TAGUNKNOWN)) { if (sc.Match('<', '%')) { if (sc.state == SCE_H_TAGUNKNOWN) sc.ChangeState(SCE_H_ASP); else sc.SetState(SCE_H_ASP); sc.Forward(); sc.Forward(); if (sc.ch == '@') { sc.ForwardSetState(SCE_H_ASPAT); } else { if (sc.ch == '=') { sc.Forward(); } sc.SetState(SCE_HBA_DEFAULT); } } } } static void ColouriseASPDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { // Lexer for HTML requires more lexical states (7 bits worth) than most lexers StyleContext sc(startPos, length, initStyle, styler, 0x7f); for (; sc.More(); sc.Forward()) { ColouriseASPPiece(sc, keywordlists); } sc.Complete(); } static void ColourisePHPPiece(StyleContext &sc, WordList *keywordlists[]) { // Possibly exit current state to either SCE_H_DEFAULT or SCE_HBA_DEFAULT if (sc.state >= SCE_HPHP_DEFAULT && sc.state <= SCE_HPHP_OPERATOR) { if (!isPHPStringState(sc.state) && (sc.state != SCE_HPHP_COMMENT) && (sc.Match('?', '>'))) { sc.SetState(SCE_H_QUESTION); sc.Forward(); sc.ForwardSetState(SCE_H_DEFAULT); } } if (sc.state >= SCE_H_DEFAULT && sc.state <= SCE_H_SGML_BLOCK_DEFAULT) { ColouriseHTMLPiece(sc, keywordlists); } // Handle some PHP script if (sc.state == SCE_HPHP_WORD) { if (!IsPhpWordChar(static_cast<char>(sc.ch))) { sc.SetState(SCE_HPHP_DEFAULT); } } else if (sc.state == SCE_HPHP_COMMENTLINE) { if (sc.ch == '\r' || sc.ch == '\n') { sc.SetState(SCE_HPHP_DEFAULT); } } else if (sc.state == SCE_HPHP_COMMENT) { if (sc.Match('*', '/')) { sc.Forward(); sc.Forward(); sc.SetState(SCE_HPHP_DEFAULT); } } else if (sc.state == SCE_HPHP_HSTRING) { if (sc.ch == '\"') { sc.ForwardSetState(SCE_HPHP_DEFAULT); } } else if (sc.state == SCE_HPHP_SIMPLESTRING) { if (sc.ch == '\'') { sc.ForwardSetState(SCE_HPHP_DEFAULT); } } else if (sc.state == SCE_HPHP_VARIABLE) { if (!IsPhpWordChar(static_cast<char>(sc.ch))) { sc.SetState(SCE_HPHP_DEFAULT); } } else if (sc.state == SCE_HPHP_OPERATOR) { sc.SetState(SCE_HPHP_DEFAULT); } // Enter new sc.state if ((sc.state == SCE_H_DEFAULT) || (sc.state == SCE_H_TAGUNKNOWN)) { if (sc.Match("<?php")) { sc.SetState(SCE_H_QUESTION); sc.Forward(); sc.Forward(); sc.Forward(); sc.Forward(); sc.Forward(); sc.SetState(SCE_HPHP_DEFAULT); } } if (sc.state == SCE_HPHP_DEFAULT) { if (IsPhpWordStart(static_cast<char>(sc.ch))) { sc.SetState(SCE_HPHP_WORD); } else if (sc.ch == '#') { sc.SetState(SCE_HPHP_COMMENTLINE); } else if (sc.Match("<!--")) { sc.SetState(SCE_HPHP_COMMENTLINE); } else if (sc.Match('/', '/')) { sc.SetState(SCE_HPHP_COMMENTLINE); } else if (sc.Match('/', '*')) { sc.SetState(SCE_HPHP_COMMENT); } else if (sc.ch == '\"') { sc.SetState(SCE_HPHP_HSTRING); } else if (sc.ch == '\'') { sc.SetState(SCE_HPHP_SIMPLESTRING); } else if (sc.ch == '$' && IsPhpWordStart(static_cast<char>(sc.chNext))) { sc.SetState(SCE_HPHP_VARIABLE); } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_HPHP_OPERATOR); } } } static void ColourisePHPDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { // Lexer for HTML requires more lexical states (7 bits worth) than most lexers StyleContext sc(startPos, length, initStyle, styler, 0x7f); for (; sc.More(); sc.Forward()) { ColourisePHPPiece(sc, keywordlists); } sc.Complete(); } static void ColourisePHPScriptDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { if(startPos == 0) initStyle = SCE_HPHP_DEFAULT; ColouriseHyperTextDoc(startPos,length,initStyle,keywordlists,styler); } static const char * const htmlWordListDesc[] = { "HTML elements and attributes", "JavaScript keywords", "VBScript keywords", "Python keywords", "PHP keywords", "SGML and DTD keywords", 0, }; static const char * const phpscriptWordListDesc[] = { "", //Unused "", //Unused "", //Unused "", //Unused "PHP keywords", "", //Unused 0, }; LexerModule lmHTML(SCLEX_HTML, ColouriseHyperTextDoc, "hypertext", 0, htmlWordListDesc, 7); LexerModule lmXML(SCLEX_XML, ColouriseHyperTextDoc, "xml", 0, htmlWordListDesc, 7); // SCLEX_ASP and SCLEX_PHP should not be used in new code: use SCLEX_HTML instead. LexerModule lmASP(SCLEX_ASP, ColouriseASPDoc, "asp", 0, htmlWordListDesc, 7); LexerModule lmPHP(SCLEX_PHP, ColourisePHPDoc, "php", 0, htmlWordListDesc, 7); LexerModule lmPHPSCRIPT(SCLEX_PHPSCRIPT, ColourisePHPScriptDoc, "phpscript", 0, phpscriptWordListDesc, 7);
[ "eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b" ]
eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b
9edfd680363d4e0f137f150088be1d2de3a9def0
f39eb77a730a80f9219ca66e053dbc1bc5003e19
/SDK/PUBG_WeaponEquipmentWidget_Gamepad_functions.cpp
61373040e647cde1d95e2687ed109ea3faef581b
[]
no_license
yuaom/PUBG-SDK
5546e6ecf8ddd9c7576ab0eb3205c1c9bb8637e7
d48746de1151c54cffc5018f24df13e112561e37
refs/heads/master
2023-06-08T19:46:50.084991
2018-01-11T20:43:18
2018-01-11T20:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
48,831
cpp
// PlayerUnknown's Battlegrounds (3.5.7.7) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_WeaponEquipmentWidget_Gamepad_parameters.hpp" namespace Classes { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.IsFocusable // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::IsFocusable() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60439); UWeaponEquipmentWidget_Gamepad_C_IsFocusable_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.Down // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::Down() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60425); UWeaponEquipmentWidget_Gamepad_C_Down_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetDownWidget // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // class UUserWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UUserWidget* UWeaponEquipmentWidget_Gamepad_C::GetDownWidget() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60423); UWeaponEquipmentWidget_Gamepad_C_GetDownWidget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetFocusingChildWidget // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // class UUserWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UUserWidget* UWeaponEquipmentWidget_Gamepad_C::GetFocusingChildWidget() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60420); UWeaponEquipmentWidget_Gamepad_C_GetFocusingChildWidget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetLeftWidget // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // class UUserWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UUserWidget* UWeaponEquipmentWidget_Gamepad_C::GetLeftWidget() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60418); UWeaponEquipmentWidget_Gamepad_C_GetLeftWidget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetRightWidget // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // class UUserWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UUserWidget* UWeaponEquipmentWidget_Gamepad_C::GetRightWidget() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60416); UWeaponEquipmentWidget_Gamepad_C_GetRightWidget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetUpWidget // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // class UUserWidget* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) class UUserWidget* UWeaponEquipmentWidget_Gamepad_C::GetUpWidget() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60414); UWeaponEquipmentWidget_Gamepad_C_GetUpWidget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InputA // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::InputA() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60407); UWeaponEquipmentWidget_Gamepad_C_InputA_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InputB // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::InputB() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60400); UWeaponEquipmentWidget_Gamepad_C_InputB_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InputLB // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::InputLB() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60398); UWeaponEquipmentWidget_Gamepad_C_InputLB_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InputLT // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::InputLT() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60396); UWeaponEquipmentWidget_Gamepad_C_InputLT_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InputRB // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::InputRB() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60394); UWeaponEquipmentWidget_Gamepad_C_InputRB_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InputRT // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::InputRT() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60392); UWeaponEquipmentWidget_Gamepad_C_InputRT_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InputX // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::InputX() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60390); UWeaponEquipmentWidget_Gamepad_C_InputX_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InputY // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::InputY() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60388); UWeaponEquipmentWidget_Gamepad_C_InputY_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.IsFocus // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::IsFocus() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60386); UWeaponEquipmentWidget_Gamepad_C_IsFocus_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.Left // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::Left() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60367); UWeaponEquipmentWidget_Gamepad_C_Left_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.Right // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::Right() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60348); UWeaponEquipmentWidget_Gamepad_C_Right_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.SetFocus // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool NewFocus (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::SetFocus(bool NewFocus) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60329); UWeaponEquipmentWidget_Gamepad_C_SetFocus_Params params; params.NewFocus = NewFocus; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.Up // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::Up() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60314); UWeaponEquipmentWidget_Gamepad_C_Up_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetInventoryGamePad // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // class UInventoryWidget_Gamepad_C* Gamepad (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::GetInventoryGamePad(class UInventoryWidget_Gamepad_C** Gamepad) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60307); UWeaponEquipmentWidget_Gamepad_C_GetInventoryGamePad_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Gamepad != nullptr) *Gamepad = params.Gamepad; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.IsSelfPutMode // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // bool IsSelfPutMode (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::IsSelfPutMode(bool* IsSelfPutMode) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60299); UWeaponEquipmentWidget_Gamepad_C_IsSelfPutMode_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (IsSelfPutMode != nullptr) *IsSelfPutMode = params.IsSelfPutMode; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.OnMoveDownPressed // (Public, BlueprintCallable, BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::OnMoveDownPressed() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60293); UWeaponEquipmentWidget_Gamepad_C_OnMoveDownPressed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.OnMoveUpPressed // (Public, BlueprintCallable, BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::OnMoveUpPressed() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60287); UWeaponEquipmentWidget_Gamepad_C_OnMoveUpPressed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.SelfUpAttachmentIndexUp // (Public, BlueprintCallable, BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::SelfUpAttachmentIndexUp() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60273); UWeaponEquipmentWidget_Gamepad_C_SelfUpAttachmentIndexUp_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.PutAttachment // (Public, BlueprintCallable, BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::PutAttachment() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60260); UWeaponEquipmentWidget_Gamepad_C_PutAttachment_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.StopSelftattachmentPut // (Public, BlueprintCallable, BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::StopSelftattachmentPut() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60251); UWeaponEquipmentWidget_Gamepad_C_StopSelftattachmentPut_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.StartSelfAttachmentPut // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // bool bResult (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::StartSelfAttachmentPut(bool* bResult) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60235); UWeaponEquipmentWidget_Gamepad_C_StartSelfAttachmentPut_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (bResult != nullptr) *bResult = params.bResult; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.OnChildSlotRefreshFocus // (Public, BlueprintCallable, BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::OnChildSlotRefreshFocus() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60217); UWeaponEquipmentWidget_Gamepad_C_OnChildSlotRefreshFocus_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.FindFirtFocusableWidgetIndex // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // int Index (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::FindFirtFocusableWidgetIndex(int* Index) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60208); UWeaponEquipmentWidget_Gamepad_C_FindFirtFocusableWidgetIndex_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Index != nullptr) *Index = params.Index; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetFocusableDownChildIndex // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // int Index (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::GetFocusableDownChildIndex(int* Index) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60196); UWeaponEquipmentWidget_Gamepad_C_GetFocusableDownChildIndex_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Index != nullptr) *Index = params.Index; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetFocusableUpChildIndex // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // int Index (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::GetFocusableUpChildIndex(int* Index) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60181); UWeaponEquipmentWidget_Gamepad_C_GetFocusableUpChildIndex_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Index != nullptr) *Index = params.Index; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetFocusableRightChildIndex // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // int Index (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::GetFocusableRightChildIndex(int* Index) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60176); UWeaponEquipmentWidget_Gamepad_C_GetFocusableRightChildIndex_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Index != nullptr) *Index = params.Index; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetFocusableLeftChildIdnex // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // int Index (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::GetFocusableLeftChildIdnex(int* Index) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60171); UWeaponEquipmentWidget_Gamepad_C_GetFocusableLeftChildIdnex_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Index != nullptr) *Index = params.Index; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetEquipment // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // class AEquipment* Equipment (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::GetEquipment(class AEquipment** Equipment) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60165); UWeaponEquipmentWidget_Gamepad_C_GetEquipment_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Equipment != nullptr) *Equipment = params.Equipment; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.MainPrepass // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UWidget* BoundWidget (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::MainPrepass(class UWidget* BoundWidget) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60161); UWeaponEquipmentWidget_Gamepad_C_MainPrepass_Params params; params.BoundWidget = BoundWidget; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.InitializeWeaponEquipment // (Public, BlueprintCallable, BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::InitializeWeaponEquipment() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60152); UWeaponEquipmentWidget_Gamepad_C_InitializeWeaponEquipment_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.OnDrop // (BlueprintCosmetic, Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // struct FPointerEvent* PointerEvent (Parm) // class UDragDropOperation** Operation (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool UWeaponEquipmentWidget_Gamepad_C::OnDrop(struct FGeometry* MyGeometry, struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60135); UWeaponEquipmentWidget_Gamepad_C_OnDrop_Params params; params.MyGeometry = MyGeometry; params.PointerEvent = PointerEvent; params.Operation = Operation; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.GetWeaponItemByTabIndex // (Private, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // int Index (Parm, ZeroConstructor, IsPlainOldData) // class UWeaponItem* WeaponItem (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::GetWeaponItemByTabIndex(int Index, class UWeaponItem** WeaponItem) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60125); UWeaponEquipmentWidget_Gamepad_C_GetWeaponItemByTabIndex_Params params; params.Index = Index; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (WeaponItem != nullptr) *WeaponItem = params.WeaponItem; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.Construct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::Construct() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60124); UWeaponEquipmentWidget_Gamepad_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.OnDragEnter // (BlueprintCosmetic, Event, Public, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // struct FPointerEvent* PointerEvent (Parm) // class UDragDropOperation** Operation (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::OnDragEnter(struct FGeometry* MyGeometry, struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60120); UWeaponEquipmentWidget_Gamepad_C_OnDragEnter_Params params; params.MyGeometry = MyGeometry; params.PointerEvent = PointerEvent; params.Operation = Operation; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.OnDragLeave // (BlueprintCosmetic, Event, Public, BlueprintEvent) // Parameters: // struct FPointerEvent* PointerEvent (Parm) // class UDragDropOperation** Operation (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::OnDragLeave(struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60117); UWeaponEquipmentWidget_Gamepad_C_OnDragLeave_Params params; params.PointerEvent = PointerEvent; params.Operation = Operation; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.Tick // (BlueprintCosmetic, Event, Public, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // float* InDeltaTime (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::Tick(struct FGeometry* MyGeometry, float* InDeltaTime) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60114); UWeaponEquipmentWidget_Gamepad_C_Tick_Params params; params.MyGeometry = MyGeometry; params.InDeltaTime = InDeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.SetInventoryWidget // (BlueprintCallable, BlueprintEvent) // Parameters: // class UInventoryWidget_C** Inventory (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::SetInventoryWidget(class UInventoryWidget_C** Inventory) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60112); UWeaponEquipmentWidget_Gamepad_C_SetInventoryWidget_Params params; params.Inventory = Inventory; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_01_K2Node_ComponentBoundEvent_19_RefreshFocus__DelegateSignature // (BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_01_K2Node_ComponentBoundEvent_19_RefreshFocus__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60111); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_01_K2Node_ComponentBoundEvent_19_RefreshFocus__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_02_K2Node_ComponentBoundEvent_75_RefreshFocus__DelegateSignature // (BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_02_K2Node_ComponentBoundEvent_75_RefreshFocus__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60110); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_02_K2Node_ComponentBoundEvent_75_RefreshFocus__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_03_K2Node_ComponentBoundEvent_90_RefreshFocus__DelegateSignature // (BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_03_K2Node_ComponentBoundEvent_90_RefreshFocus__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60109); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_03_K2Node_ComponentBoundEvent_90_RefreshFocus__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_04_K2Node_ComponentBoundEvent_106_RefreshFocus__DelegateSignature // (BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_04_K2Node_ComponentBoundEvent_106_RefreshFocus__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60108); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_04_K2Node_ComponentBoundEvent_106_RefreshFocus__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_05_K2Node_ComponentBoundEvent_123_RefreshFocus__DelegateSignature // (BlueprintEvent) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_05_K2Node_ComponentBoundEvent_123_RefreshFocus__DelegateSignature() { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60107); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_05_K2Node_ComponentBoundEvent_123_RefreshFocus__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_01_K2Node_ComponentBoundEvent_56_OnAttachmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EWeaponAttachmentSlotID AttachmentSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_01_K2Node_ComponentBoundEvent_56_OnAttachmentFocused__DelegateSignature(EWeaponAttachmentSlotID AttachmentSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60102); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_01_K2Node_ComponentBoundEvent_56_OnAttachmentFocused__DelegateSignature_Params params; params.AttachmentSlotID = AttachmentSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_02_K2Node_ComponentBoundEvent_77_OnAttachmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EWeaponAttachmentSlotID AttachmentSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_02_K2Node_ComponentBoundEvent_77_OnAttachmentFocused__DelegateSignature(EWeaponAttachmentSlotID AttachmentSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60097); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_02_K2Node_ComponentBoundEvent_77_OnAttachmentFocused__DelegateSignature_Params params; params.AttachmentSlotID = AttachmentSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_03_K2Node_ComponentBoundEvent_104_OnAttachmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EWeaponAttachmentSlotID AttachmentSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_03_K2Node_ComponentBoundEvent_104_OnAttachmentFocused__DelegateSignature(EWeaponAttachmentSlotID AttachmentSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60092); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_03_K2Node_ComponentBoundEvent_104_OnAttachmentFocused__DelegateSignature_Params params; params.AttachmentSlotID = AttachmentSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_04_K2Node_ComponentBoundEvent_133_OnAttachmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EWeaponAttachmentSlotID AttachmentSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_04_K2Node_ComponentBoundEvent_133_OnAttachmentFocused__DelegateSignature(EWeaponAttachmentSlotID AttachmentSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60087); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_04_K2Node_ComponentBoundEvent_133_OnAttachmentFocused__DelegateSignature_Params params; params.AttachmentSlotID = AttachmentSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_05_K2Node_ComponentBoundEvent_162_OnAttachmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EWeaponAttachmentSlotID AttachmentSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_05_K2Node_ComponentBoundEvent_162_OnAttachmentFocused__DelegateSignature(EWeaponAttachmentSlotID AttachmentSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60082); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_05_K2Node_ComponentBoundEvent_162_OnAttachmentFocused__DelegateSignature_Params params; params.AttachmentSlotID = AttachmentSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_01_K2Node_ComponentBoundEvent_412_OnWeaponEquipmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EEquipSlotID EquipSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_01_K2Node_ComponentBoundEvent_412_OnWeaponEquipmentFocused__DelegateSignature(EEquipSlotID EquipSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60077); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_01_K2Node_ComponentBoundEvent_412_OnWeaponEquipmentFocused__DelegateSignature_Params params; params.EquipSlotID = EquipSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_02_K2Node_ComponentBoundEvent_433_OnWeaponEquipmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EEquipSlotID EquipSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_02_K2Node_ComponentBoundEvent_433_OnWeaponEquipmentFocused__DelegateSignature(EEquipSlotID EquipSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60072); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_02_K2Node_ComponentBoundEvent_433_OnWeaponEquipmentFocused__DelegateSignature_Params params; params.EquipSlotID = EquipSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_03_K2Node_ComponentBoundEvent_465_OnWeaponEquipmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EEquipSlotID EquipSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_03_K2Node_ComponentBoundEvent_465_OnWeaponEquipmentFocused__DelegateSignature(EEquipSlotID EquipSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60067); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_03_K2Node_ComponentBoundEvent_465_OnWeaponEquipmentFocused__DelegateSignature_Params params; params.EquipSlotID = EquipSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_04_K2Node_ComponentBoundEvent_498_OnWeaponEquipmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EEquipSlotID EquipSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_04_K2Node_ComponentBoundEvent_498_OnWeaponEquipmentFocused__DelegateSignature(EEquipSlotID EquipSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60062); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_04_K2Node_ComponentBoundEvent_498_OnWeaponEquipmentFocused__DelegateSignature_Params params; params.EquipSlotID = EquipSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.BndEvt__Weapon_05_K2Node_ComponentBoundEvent_532_OnWeaponEquipmentFocused__DelegateSignature // (BlueprintEvent) // Parameters: // EEquipSlotID EquipSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::BndEvt__Weapon_05_K2Node_ComponentBoundEvent_532_OnWeaponEquipmentFocused__DelegateSignature(EEquipSlotID EquipSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(60057); UWeaponEquipmentWidget_Gamepad_C_BndEvt__Weapon_05_K2Node_ComponentBoundEvent_532_OnWeaponEquipmentFocused__DelegateSignature_Params params; params.EquipSlotID = EquipSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.ExecuteUbergraph_WeaponEquipmentWidget_Gamepad // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::ExecuteUbergraph_WeaponEquipmentWidget_Gamepad(int EntryPoint) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(59993); UWeaponEquipmentWidget_Gamepad_C_ExecuteUbergraph_WeaponEquipmentWidget_Gamepad_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.OnWeaponEquipmentFocused__DelegateSignature // (Public, Delegate, BlueprintCallable, BlueprintEvent) // Parameters: // EEquipSlotID EquipSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::OnWeaponEquipmentFocused__DelegateSignature(EEquipSlotID EquipSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(59988); UWeaponEquipmentWidget_Gamepad_C_OnWeaponEquipmentFocused__DelegateSignature_Params params; params.EquipSlotID = EquipSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WeaponEquipmentWidget_Gamepad.WeaponEquipmentWidget_Gamepad_C.OnAttachmentFocused__DelegateSignature // (Public, Delegate, BlueprintCallable, BlueprintEvent) // Parameters: // EWeaponAttachmentSlotID AttachmentSlotID (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotInterface> SlotInterface (Parm, ZeroConstructor, IsPlainOldData) // TScriptInterface<class USlotContainerInterface> SlotContainerInterface (Parm, ZeroConstructor, IsPlainOldData) void UWeaponEquipmentWidget_Gamepad_C::OnAttachmentFocused__DelegateSignature(EWeaponAttachmentSlotID AttachmentSlotID, const TScriptInterface<class USlotInterface>& SlotInterface, const TScriptInterface<class USlotContainerInterface>& SlotContainerInterface) { static UFunction* fn = nullptr; if (!fn) fn = UObject::GetObjectCasted<UFunction>(59983); UWeaponEquipmentWidget_Gamepad_C_OnAttachmentFocused__DelegateSignature_Params params; params.AttachmentSlotID = AttachmentSlotID; params.SlotInterface = SlotInterface; params.SlotContainerInterface = SlotContainerInterface; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "collin.mcqueen@yahoo.com" ]
collin.mcqueen@yahoo.com
d5e05e1502f5bc2dd4cc3a7ece25ddb7035c1795
d701f59582f7845507ba9d9ed73d05d9e4b8186a
/tests/miscellaneous/version.cpp
b2c5294e371733346d819a783a8fb16e5b5a1db2
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
STEllAR-GROUP/hpxpi
eb1c326e529722bdf7fef6e633d0108f58b0ff87
14cd88a37850bd909a3052c3fc3f4c31c9ab858d
refs/heads/master
2021-01-16T19:34:30.239529
2015-03-26T22:29:01
2015-03-26T22:29:01
9,718,451
2
0
null
null
null
null
UTF-8
C++
false
false
1,812
cpp
// Copyright (c) 2013 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <hpxpi/xpi.h> #include <hpx/util/lightweight_test.hpp> /////////////////////////////////////////////////////////////////////////////// bool executed_XPI_main = false; void test_XPI_version() { size_t major = 0; size_t minor = 0; size_t release = 0; XPI_version(&major, &minor, &release); HPX_TEST_EQ(major, XPI_VERSION_MAJOR); HPX_TEST_EQ(minor, XPI_VERSION_MINOR); HPX_TEST_EQ(release, XPI_VERSION_RELEASE); executed_XPI_main = true; } #if !defined(HPXPI_NO_EXTENSIONS) bool executed_HPXPI_main = false; void test_HPXPI_version() { size_t major = 0; size_t minor = 0; size_t release = 0; HPXPI_version(&major, &minor, &release); HPX_TEST_EQ(major, HPXPI_VERSION_MAJOR); HPX_TEST_EQ(minor, HPXPI_VERSION_MINOR); HPX_TEST_EQ(release, HPXPI_VERSION_SUBMINOR); executed_HPXPI_main = true; } #endif /////////////////////////////////////////////////////////////////////////////// XPI_Err XPI_main(size_t nargs, void* args[]) { test_XPI_version(); #if !defined(HPXPI_NO_EXTENSIONS) test_HPXPI_version(); #endif return XPI_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { int result = 0; HPX_TEST_EQ(XPI_init(&argc, &argv, 0), XPI_SUCCESS); HPX_TEST_EQ(XPI_run(argc, argv, &result), XPI_SUCCESS); HPX_TEST_EQ(result, XPI_SUCCESS); HPX_TEST_EQ(XPI_finalize(), XPI_SUCCESS); HPX_TEST(executed_XPI_main); #if !defined(HPXPI_NO_EXTENSIONS) HPX_TEST(executed_HPXPI_main); #endif return hpx::util::report_errors(); }
[ "hartmut.kaiser@gmail.com" ]
hartmut.kaiser@gmail.com
74d422764f33c4724893c2b2be08fea244f09d66
ee300b6528fa6c644ddd236ad8267a85a3e4ee9f
/jni/ImgFun.cpp
26e12c02906ea761b129f1303440f72e68d104ba
[]
no_license
hyperchris/CarDetection-Android
8472d2ecb71970392408f95257678005a0ee7237
5c45e6bbfbb59f7d6d7950b4722d290e0a2518a5
refs/heads/master
2021-01-22T21:28:00.788406
2015-05-15T07:08:16
2015-05-15T07:08:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,049
cpp
#include <jni.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <opencv2/opencv.hpp> #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <iterator> #include <android/log.h> #define mod_w 300 #define mod_h 150 using namespace cv; class cars //main class { public: //variables kept public but precaution taken all over the code Mat image_input; //main input image Mat image_main_result; //the final result Mat storage; //introduced to stop detection of same car more than once CascadeClassifier cascade; //the main cascade classifier CascadeClassifier checkcascade; //a test classifier,car detected by both main and test is stated as car int num; void getimage(Mat src) //getting the input image { if(! src.data ){} else{ image_input = src.clone(); storage = src.clone(); //initialising storage image_main_result = src.clone(); //initialising result } } void cascade_load(string cascade_string) //loading the main cascade { cascade.load(cascade_string); if( !cascade.load(cascade_string) ){} else{} } void checkcascade_load(string checkcascade_string) //loading the test/check cascade { checkcascade.load(checkcascade_string); if( !checkcascade.load(checkcascade_string) ){ __android_log_print(ANDROID_LOG_INFO, "JNIMsg", "Could not load classifier cascade"); } else{} } void setnum(){ num = 0; } void findcars() //main function { int i = 0; Mat img = storage.clone(); Mat temp; //for region of interest.If a car is detected(after testing) by one classifier,then it will not be available for other one if(img.empty() ){} int cen_x; int cen_y; vector<Rect> cars; const static Scalar colors[] = { CV_RGB(0,0,255),CV_RGB(0,255,0),CV_RGB(255,0,0),CV_RGB(255,255,0),CV_RGB(255,0,255),CV_RGB(0,255,255),CV_RGB(255,255,255),CV_RGB(128,0,0),CV_RGB(0,128,0),CV_RGB(0,0,128),CV_RGB(128,128,128),CV_RGB(0,0,0)}; Mat gray; cvtColor( img, gray, CV_BGR2GRAY ); Mat resize_image(cvRound (img.rows), cvRound(img.cols), CV_8UC1 ); resize( gray, resize_image, resize_image.size(), 0, 0, INTER_LINEAR ); equalizeHist( resize_image, resize_image ); cascade.detectMultiScale( resize_image, cars,1.1,2,0,Size(10,10)); //detection using main classifier for( vector<Rect>::const_iterator main = cars.begin(); main != cars.end(); main++, i++ ){ Mat resize_image_reg_of_interest; vector<Rect> nestedcars; Point center; Scalar color = colors[i%8]; //getting points for bouding a rectangle over the car detected by main int x0 = cvRound(main->x); int y0 = cvRound(main->y); int x1 = cvRound((main->x + main->width-1)); int y1 = cvRound((main->y + main->height-1)); if( checkcascade.empty() ) continue; resize_image_reg_of_interest = resize_image(*main); checkcascade.detectMultiScale( resize_image_reg_of_interest, nestedcars,1.1,2,0,Size(30,30)); for( vector<Rect>::const_iterator sub = nestedcars.begin(); sub != nestedcars.end(); sub++ ) //testing the detected car by main using checkcascade { center.x = cvRound((main->x + sub->x + sub->width*0.5)); //getting center points for bouding a circle over the car detected by checkcascade cen_x = center.x; center.y = cvRound((main->y + sub->y + sub->height*0.5)); cen_y = center.y; if(cen_x>(x0+15) && cen_x<(x1-15) && cen_y>(y0+15) && cen_y<(y1-15)) //if centre of bounding circle is inside the rectangle boundary over a threshold the the car is certified { rectangle( image_main_result, cvPoint(x0,y0), cvPoint(x1,y1), color, 3, 8, 0); //detecting boundary rectangle over the final result //masking the detected car to detect second car if present Rect region_of_interest = Rect(x0, y0, x1-x0, y1-y0); temp = storage(region_of_interest); temp = Scalar(255,255,255); num = num+1; //num if number of cars detected } } } if(image_main_result.empty()){ __android_log_print(ANDROID_LOG_INFO, "JNIMsg", "res image is empty!"); } return; } }; extern "C" { JNIEXPORT int JNICALL Java_com_testopencv_haveimgfun_LibImgFun_ImgFun( JNIEnv* env, jobject obj, jintArray buf, int w, int h); JNIEXPORT int JNICALL Java_com_testopencv_haveimgfun_LibImgFun_ImgFun( JNIEnv* env, jobject obj, jintArray buf, int w, int h){ jint *cbuf; cbuf = env->GetIntArrayElements(buf, false); // read in picture if (cbuf == NULL) { return 0; } __android_log_print(ANDROID_LOG_INFO, "JNIMsg", "native started"); Mat myimg(h, w, CV_8UC4, (unsigned char*) cbuf); Mat image1 = myimg; Mat image; resize(image1,image,Size(mod_w,mod_h),0,0,INTER_LINEAR); //resizing image to get best experimental results cars detectcars; // //creating car object detectcars.getimage(image); //get the image detectcars.setnum(); //set number of cars detected as 0 // init the path of needed files in the phone storage const char * checkcas = "/storage/emulated/0/carDetection/checkcas.xml"; const char * cas1 = "/storage/emulated/0/carDetection/cas1.xml"; const char * cas2 = "/storage/emulated/0/carDetection/cas2.xml"; const char * cas3 = "/storage/emulated/0/carDetection/cas3.xml"; const char * cas4 = "/storage/emulated/0/carDetection/cas4.xml"; detectcars.checkcascade_load(checkcas); //load the test cascade __android_log_print(ANDROID_LOG_INFO, "JNIMsg", "processing"); // load cascade files and do matching for(int i = 1;i< 5;i++){ string cas; switch (i){ case 1: cas = cas1; break; case 2: cas = cas2; break; case 3: cas = cas3; break; case 4: cas = cas4; break; default: break; } detectcars.cascade_load(cas); // do car recognition detectcars.findcars(); } // print number of cars __android_log_print(ANDROID_LOG_INFO, "JNIMsg", "there are %d cars in this photo",detectcars.num); // generate output image IplImage resImg = IplImage(detectcars.image_main_result); cvSaveImage("/storage/emulated/0/carDetection/resImg.jpg",&resImg); __android_log_print(ANDROID_LOG_INFO, "JNIMsg", "res img stored"); return detectcars.num; } } /* extern "C" { JNIEXPORT jintArray JNICALL Java_com_testopencv_haveimgfun_LibImgFun_ImgFun( JNIEnv* env, jobject obj, jintArray buf, int w, int h); JNIEXPORT jintArray JNICALL Java_com_testopencv_haveimgfun_LibImgFun_ImgFun( JNIEnv* env, jobject obj, jintArray buf, int w, int h) { jint *cbuf; cbuf = env->GetIntArrayElements(buf, false); if (cbuf == NULL) { return 0; } Mat myimg(h, w, CV_8UC4, (unsigned char*) cbuf); IplImage image=IplImage(myimg); IplImage* image3channel = change4channelTo3InIplImage(&image); IplImage* pCannyImage=cvCreateImage(cvGetSize(image3channel),IPL_DEPTH_8U,1); cvCanny(image3channel,pCannyImage,50,150,3); int* outImage=new int[w*h]; for(int i=0;i<w*h;i++) { outImage[i]=(int)pCannyImage->imageData[i]; } int size = w * h; jintArray result = env->NewIntArray(size); env->SetIntArrayRegion(result, 0, size, outImage); env->ReleaseIntArrayElements(buf, cbuf, 0); return result; } } IplImage * change4channelTo3InIplImage(IplImage * src) { if (src->nChannels != 4) { return NULL; } IplImage * destImg = cvCreateImage(cvGetSize(src), IPL_DEPTH_8U, 3); for (int row = 0; row < src->height; row++) { for (int col = 0; col < src->width; col++) { CvScalar s = cvGet2D(src, row, col); cvSet2D(destImg, row, col, s); } } return destImg; } */
[ "Chris@Chriss-MacBook-Pro.local" ]
Chris@Chriss-MacBook-Pro.local
4229985e8868e5464ea15a2b75d6a786504c604a
786f9c3604d5baf9daa4dfa165bfe792682c5d77
/2.0-vs2013/PluginProj/Common/shapefactory.h
44dcc5ec07ed049813465d3db889303c5ff79d56
[]
no_license
l-iberty/MyDrawboard
70977a756f60fc91dd091fdf2f5827ebe361d006
4a6f5d54391960fd56f34ae30f802aec7d4c5897
refs/heads/master
2021-06-03T01:36:19.947609
2021-04-23T08:08:06
2021-04-23T08:08:06
85,384,282
2
0
null
null
null
null
UTF-8
C++
false
false
278
h
#ifndef SHAPE_FACTORY_H #define SHAPE_FACTORY_H #include "shape.h" #include <Windows.h> class ShapeFactory { public: ShapeFactory(); virtual ~ShapeFactory(); virtual Shape *createShape() = 0; virtual Shape *createShape(Shape *shape) = 0; }; #endif // SHAPE_FACTORY_H
[ "2593093242@qq.com" ]
2593093242@qq.com
14b416a32969212161cab8b6d850ebf429eb4af4
7db238a2bf84e448975c6ac0d3af95bc93506be7
/lab2/Circle.h
7824a8bc607e30109a3eeb2838635e42f10f2cca
[]
no_license
MorganBergen/EECS268-Lab2
d989d514d4603630fdb34cc291afd5222c98b421
87907a3d4c933628a19ca10b3f841f148b250f81
refs/heads/main
2023-08-25T03:54:35.993638
2021-10-10T18:54:18
2021-10-10T18:54:18
413,678,167
1
0
null
null
null
null
UTF-8
C++
false
false
2,271
h
/** * @file Circle.h * @author Morgan Bergen * @date October 08/2021 * @brief This is the header file for the Circle Class that derives from the Shape Class. It has methods that, can return area, can return the name of the object (always Circle in this case), can change the radius, does have a constructor, and has a destructor. This class will used for inheriting from the Shape Interface. */ #ifndef Circle_h #define Circle_h #include <string> #include <stdio.h> #include "Shape.h" class Circle : public Shape { private: double m_radius; public: /** * @pre must have an object be declared from the stack to call this default constructor * @post will only construct the object * @paramnone * @throwsnone * @returnsnone */ Circle(); /** * @pre must have an object be declared from the heap to call this constructor * @post will initialize m_radius to be of the same value to that of radius * @paramradius * @throwsnone * @returnsnone */ Circle(double radius); /** * @pre object must have been previously declared and constructed * @post will initialize m_radius to be of the same value to that of radius * @paramradius * @throwsnone * @returnsnone */ void setRadius(double radius); /** * @pre object must have been previously declared and constructed and have values of radius initialized * @post none * @paramnone * @throwsnone * @returnsarea of the circle, based on the size of m_radius */ virtual double area() const; /** * @pre object must have been previously declared and constructed and have values of radius initialized * @post none * @paramnone * @throwsnone * @returnsname of the circle, which in this case is always "Circle" */ virtual std::string shapeName() const; /** * @pre Circle must no longer be needed by the program * @post will be the destructor of the circle class object, inherited by the Shape Interface * @paramnone * @throwsnone * @returnsnone */ virtual ~Circle(); }; #endif /* Circle_h */
[ "morganmahabergen@icloud.com" ]
morganmahabergen@icloud.com
f1d5e7ce903d4433b7e8b3ae5cb86127e145e158
d47c341d59ed8ba577463ccf100a51efb669599c
/libs/geometry/test/multi/algorithms/multi_reverse.cpp
78334928df93c6e9027bf9fd049f5aba2a913f0a
[ "BSL-1.0" ]
permissive
cms-externals/boost
5980d39d50b7441536eb3b10822f56495fdf3635
9615b17aa7196c42a741e99b4003a0c26f092f4c
refs/heads/master
2023-08-29T09:15:33.137896
2020-08-04T16:50:18
2020-08-04T16:50:18
30,637,301
0
4
BSL-1.0
2023-08-09T23:00:37
2015-02-11T08:07:04
C++
UTF-8
C++
false
false
1,893
cpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <geometry_test_common.hpp> #include <boost/geometry/algorithms/reverse.hpp> #include <boost/geometry/multi/algorithms/reverse.hpp> #include <boost/geometry/io/wkt/wkt.hpp> #include <boost/geometry/multi/io/wkt/wkt.hpp> #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/multi/geometries/multi_point.hpp> #include <boost/geometry/multi/geometries/multi_linestring.hpp> #include <boost/geometry/multi/geometries/multi_polygon.hpp> #include <algorithms/test_reverse.hpp> template <typename P> void test_all() { // Multi point, should happen nothing. test_geometry<bg::model::multi_point<P> >( "MULTIPOINT((0 0),(1 1))", "MULTIPOINT((0 0),(1 1))"); test_geometry<bg::model::multi_linestring<bg::model::linestring<P> > >( "MULTILINESTRING((0 0,1 1),(3 3,4 4))", "MULTILINESTRING((1 1,0 0),(4 4,3 3))"); typedef bg::model::multi_polygon<bg::model::polygon<P> > mp; test_geometry<mp>( "MULTIPOLYGON(((4 0,8 2,8 7,4 9,0 7,0 2,2 1,4 0)))", "MULTIPOLYGON(((4 0,2 1,0 2,0 7,4 9,8 7,8 2,4 0)))"); test_geometry<mp>( "MULTIPOLYGON(((4 0,8 2,8 7,4 9,0 7,0 2,2 1,4 0),(7 3,7 6,1 6,1 3,4 3,7 3)))", "MULTIPOLYGON(((4 0,2 1,0 2,0 7,4 9,8 7,8 2,4 0),(7 3,4 3,1 3,1 6,7 6,7 3)))"); } int test_main( int , char* [] ) { test_all<bg::model::d2::point_xy<int> >(); test_all<bg::model::d2::point_xy<double> >(); #ifdef HAVE_TTMATH test_all<bg::model::d2::point_xy<ttmath_big> >(); #endif return 0; }
[ "giulio.eulisse@cern.ch" ]
giulio.eulisse@cern.ch
59fd0f6609275d6f53a56d4269cf9a79dd91596c
dcd7f028f6800afb4b6b80ffb51b0f1af31176ef
/src/fast_multinom.cpp
c9e7f714174b8e8c610567217d07b6d533bf0db7
[]
no_license
aametwally/metaMix
5853172a4987667b811698a75c11b2e5b026738f
87b510a4346df9a7833398fd5229128d72724626
refs/heads/master
2021-01-16T19:57:51.164263
2014-07-21T20:07:16
2014-07-21T20:07:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,167
cpp
#include<iostream> #include<vector> #include<string> #include <cmath> #include <Rinternals.h> #include <cstdlib> #include <sstream> using namespace std; extern "C" { SEXP C_rmultinom (const SEXP proba_matrix, const SEXP z_matrix, const SEXP seed); } SEXP C_rmultinom (const SEXP proba_matrix, const SEXP z_matrix, const SEXP seed) { const unsigned int Seed = INTEGER(seed)[0]; srand((unsigned)Seed); const double * pmatrix = REAL(proba_matrix); double * zmatrix = REAL(z_matrix); const int * dims = INTEGER(getAttrib(proba_matrix, R_DimSymbol)); int nrow = dims[0]; int ncol = dims[1]; //cout<<"Number of rows "<<nrow<<" and nb of columns "<<ncol<<endl; for (int i = 0; i != nrow; i++) { double sum = 0.; for (int j = 0; j != ncol; j++) sum += pmatrix[ j*nrow + i ]; double randN = rand() / double(RAND_MAX); int k = 0; double current = pmatrix[ k*nrow + i ] / sum; while (current < randN) {k++;current += pmatrix[ k*nrow + i ]/sum;} for (int j = 0; j != ncol; j++) { if (j == k) {zmatrix[ j*nrow + i ] = 1;} else zmatrix[ j*nrow + i ] = 0; } } return z_matrix; }
[ "sofia.morfopoulou@gmail.com" ]
sofia.morfopoulou@gmail.com
d59e44624bfdc05ac3aaa6546c58c96966ccfedd
fe7c6ccb491b4203a42f956a67a43c236dc75f11
/mbgl-core/src/mbgl/layermanager/symbol_layer_factory.cpp
c3ce7515d1925d09879a02316966bf1af87ff6f0
[]
no_license
luyufanzhi/win_mapbox
f571fef859bb39927b6590df606ea37f3eef9d73
4e024cbd35237e4994b65adb61b265bebed41ea9
refs/heads/master
2023-04-14T20:45:09.734962
2020-05-19T11:18:27
2020-05-19T11:18:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,865
cpp
#include <mbgl/layermanager/symbol_layer_factory.hpp> #include <mbgl/layout/symbol_layout.hpp> #include <mbgl/renderer/layers/render_symbol_layer.hpp> #include <mbgl/style/layers/symbol_layer.hpp> #include <mbgl/style/layers/symbol_layer_impl.hpp> namespace mbgl { const style::LayerTypeInfo* SymbolLayerFactory::getTypeInfo() const noexcept { return style::SymbolLayer::Impl::staticTypeInfo(); } std::unique_ptr<style::Layer> SymbolLayerFactory::createLayer(const std::string& id, const style::conversion::Convertible& value) noexcept { optional<std::string> source = getSource(value); if (!source) { return nullptr; } std::unique_ptr<style::Layer> layer = std::unique_ptr<style::Layer>(new style::SymbolLayer(id, *source)); if (!initSourceLayerAndFilter(layer.get(), value)) { return nullptr; } return layer; } std::unique_ptr<Layout> SymbolLayerFactory::createLayout(const LayoutParameters& parameters, std::unique_ptr<GeometryTileLayer> tileLayer, const std::vector<Immutable<style::LayerProperties>>& group) noexcept { return std::make_unique<SymbolLayout>(parameters.bucketParameters, group, std::move(tileLayer), parameters.imageDependencies, parameters.glyphDependencies); } std::unique_ptr<RenderLayer> SymbolLayerFactory::createRenderLayer(Immutable<style::Layer::Impl> impl) noexcept { assert(impl->getTypeInfo() == getTypeInfo()); return std::make_unique<RenderSymbolLayer>(staticImmutableCast<style::SymbolLayer::Impl>(std::move(impl))); } } // namespace mbgl
[ "machfe@126.com" ]
machfe@126.com
c098a2884ca4a33a33a36e1a1c6ab063e8275a37
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/monotonic/boost/monotonic/monotonic.hpp
28c87ca3eab63c0dd70ce03468266522271aa213
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
1,011
hpp
// Copyright (C) 2009 Christian Schladetsch // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_MONOTONIC_MONOTONIC_HPP #define BOOST_MONOTONIC_MONOTONIC_HPP #include <boost/monotonic/detail/prefix.hpp> #ifdef BOOST_MONOTONIC_THREADS # include <boost/monotonic/shared_allocator.hpp> //TODO # include <boost/monotonic/thread_local_allocator.hpp> #endif #include <boost/monotonic/containers/string.hpp> #include <boost/monotonic/containers/vector.hpp> #include <boost/monotonic/containers/list.hpp> #include <boost/monotonic/containers/set.hpp> #include <boost/monotonic/containers/map.hpp> #include <boost/monotonic/containers/deque.hpp> #include <boost/monotonic/containers/chain.hpp> namespace boost { namespace monotonic { } // namespace monotonic } // namespace boost #include <boost/monotonic/detail/postfix.hpp> #endif // BOOST_MONOTONIC_MONOTONIC_HPP //EOF
[ "christian.schladetsch@gmail.com" ]
christian.schladetsch@gmail.com
ef694e44d6d58f0e48a9500cfeb2155af9868506
b9cd547056a8b6cbbeb74737ec75bf6b5769790a
/software Render/main.cpp
d11375e54d3bdfd113732986a48ea746a3efd59d
[]
no_license
enghqii/Software-Rendering
0b2e676b3282ec5a67e6dc8358d2dd8964e8c970
611ab1a65b108223ff692ac2f43141502a380be1
refs/heads/master
2021-01-22T03:53:51.980201
2014-10-04T08:23:43
2014-10-04T08:23:43
24,759,811
1
0
null
null
null
null
UHC
C++
false
false
4,743
cpp
#include <windows.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "matrix.h" #include "vector.h" #include "Render.h" #include "Camera.h" LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM); HINSTANCE g_hInst; LPCWSTR lpszClass=L"Software Rendering"; CRender Renderer; Vector v[12]; Vector v2[8]; int indices[36]; //3각형이 2개 int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance ,LPSTR lpszCmdParam,int nCmdShow) { HWND hWnd; WNDCLASS WndClass; g_hInst=hInstance; WndClass.cbClsExtra=0; WndClass.cbWndExtra=0; WndClass.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH); WndClass.hCursor=LoadCursor(NULL,IDC_ARROW); WndClass.hIcon=LoadIcon(NULL,IDI_APPLICATION); WndClass.hInstance=hInstance; WndClass.lpfnWndProc=(WNDPROC)WndProc; WndClass.lpszClassName=lpszClass; WndClass.lpszMenuName=NULL; WndClass.style=CS_HREDRAW | CS_VREDRAW; RegisterClass(&WndClass); hWnd=CreateWindow(lpszClass,lpszClass,WS_POPUP,//WS_SYSMENU|WS_CAPTION|WS_OVERLAPPED , CW_USEDEFAULT,CW_USEDEFAULT,800,600, NULL,(HMENU)NULL,hInstance,NULL); ShowWindow(hWnd,nCmdShow); return 0; } LRESULT CALLBACK WndProc(HWND hWnd,UINT iMessage,WPARAM wParam,LPARAM lParam) { switch(iMessage) { case WM_CREATE: srand(time(NULL)); Renderer.Init(hWnd); return 0; case WM_DESTROY: Renderer.Release(); PostQuitMessage(0); return 0; } return(DefWindowProc(hWnd,iMessage,wParam,lParam)); } void Setup(){ v[0].init(-0.1f,-0.1f,0.1f); v[1].init(-0.1f, 0.1f,0.1f); v[2].init( 0.1f,-0.1f,0.1f); v[3].init(-0.1f, 0.1f,0.1f); v[4].init( 0.1f, 0.1f,0.1f); v[5].init( 0.1f,-0.1f,0.1f); v[6].init(-0.1f,-0.1f,-0.1f); v[7].init(-0.1f, 0.1f,-0.1f); v[8].init( 0.1f,-0.1f,-0.1f); v[9].init(-0.1f, 0.1f,-0.1f); v[10].init( 0.1f, 0.1f,-0.1f); v[11].init( 0.1f,-0.1f,-0.1f); v2[0].init(-0.1f,-0.1f,-0.1f); v2[1].init(-0.1f, 0.1f,-0.1f); v2[2].init( 0.1f, 0.1f,-0.1f); v2[3].init( 0.1f,-0.1f,-0.1f); v2[4].init(-0.1f,-0.1f, 0.1f); v2[5].init(-0.1f, 0.1f, 0.1f); v2[6].init( 0.1f, 0.1f, 0.1f); v2[7].init( 0.1f,-0.1f, 0.1f); // 앞면 indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 2; indices[5] = 3; // 뒷면 indices[6] = 5; indices[7] = 7; indices[8] = 4; indices[9] = 5; indices[10] = 6; indices[11] = 7; // 왼쪽 indices[12] = 4; indices[13] = 5; indices[14] = 1; indices[15] = 4; indices[16] = 1; indices[17] = 0; // 오른쪽 indices[18] = 3; indices[19] = 2; indices[20] = 6; indices[21] = 3; indices[22] = 6; indices[23] = 7; // 윗면 indices[24] = 1; indices[25] = 5; indices[26] = 6; indices[27] = 1; indices[28] = 6; indices[29] = 2; // 아랫면 indices[30] = 4; indices[31] = 0; indices[32] = 3; indices[33] = 4; indices[34] = 3; indices[35] = 7; /*Matrix View; View.Identity(); View.LookAt(Vector(-0.5f,0.5,0),Vector(0,0,1),Vector(0,1,0)); Renderer.SetTransForm(VIEW,View);*/ Matrix Proj; Proj.Identity(); Proj.PerspectiveFov(3.14f/2.0f, 800.0f/600.0f , 10.0f, 100.0f); Renderer.SetTransForm(PROJECTION,Proj); Matrix vPort; vPort.Identity(); vPort.ViewPort(0 , 0 , 800 , 600 , 0.0f , 1.0f); Renderer.SetTransForm(VIEW_PORT,vPort); } void FrameMove(float timeDelta){ Matrix dy; Matrix dx; Matrix dz; dy.Identity(); dx.Identity(); dz.Identity(); static float Angle = 0.0f; dy.RotationY(Angle); //dx.RotationX(Angle); //dz.RotationZ(Angle); Angle+=0.05; Renderer.SetTransForm(WORLD,dz*dy*dx); static Camera TheCamera(Camera::AIRCRAFT); if( ::GetAsyncKeyState(VK_UP) & 0x8000f ){ TheCamera.pitch(0.00625f * timeDelta); } if( ::GetAsyncKeyState(VK_DOWN) & 0x8000f ){ TheCamera.pitch(-0.00625f * timeDelta); } if( ::GetAsyncKeyState(VK_LEFT) & 0x8000f ){ TheCamera.roll(0.000625 * timeDelta); } if( ::GetAsyncKeyState(VK_RIGHT) & 0x8000f ){ TheCamera.roll(-0.000625 * timeDelta); } if( ::GetAsyncKeyState('Q') & 0x8000f ){ TheCamera.yaw(-0.000625 * timeDelta); } if( ::GetAsyncKeyState('E') & 0x8000f ){ TheCamera.yaw(0.000625 * timeDelta); } if( ::GetAsyncKeyState('W') & 0x8000f ){ TheCamera.walk(0.00625f * timeDelta); } if( ::GetAsyncKeyState('S') & 0x8000f ){ TheCamera.walk(-0.00625f * timeDelta); } Renderer.SetTransForm(VIEW,TheCamera.GetViewMatrix()); } void Render(){ Renderer.Clear(); Renderer.DrawLine(v2,indices,36); Renderer.Present(); } void main(){ WinMain(GetModuleHandle(NULL),NULL,"",SW_SHOW); Setup(); float Start = GetTickCount(); MSG msg = {0,}; while( msg.message != WM_QUIT ){ float End = GetTickCount(); if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ){ TranslateMessage( &msg ); DispatchMessage( &msg ); } else{ FrameMove(End - Start); Render(); Start = End; } } }
[ "enghqii@gmail.com" ]
enghqii@gmail.com
4c0759daedf003352cbb99ef14282bb116325a0f
6d2d6c928e623ab13df7ee44ce122a95c96f87a2
/section1/combo.cpp
5e3ffe9d71de67b0788c58abd9a00d68a4ac551d
[]
no_license
kevinkwl/usaco
180f354273a3bd02add1964b595c3f2d931ed4dc
98d3a4e926ca335ad21656766ce3696f64fe718e
refs/heads/master
2021-05-31T11:38:58.745734
2016-02-13T13:54:56
2016-02-13T13:54:56
46,347,983
1
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
/* ID: kevinli7 PROG: combo LANG: C++11 */ #include <iostream> #include <fstream> #include <vector> #define for(i,N,x) for(i = x; i < N; ++i) using namespace std; int farmer[3], master[3], ans = 0, N; // brute force int distance(int i, int j) { int dis = i - j; if (dis < 0) dis = -dis; if (dis > N/2) dis = N - dis; return dis; } bool valid(int i, int j, int k) { if (distance(i,farmer[0]) < 3) if (distance(j, farmer[1]) < 3) if (distance(k, farmer[2]) < 3) return true; if (distance(i,master[0]) < 3) if (distance(j, master[1]) < 3) if (distance(k, master[2]) < 3) return true; return false; } int main() { ifstream fin("combo.in"); ofstream fout("combo.out"); fin >> N; int p,i,j,k; for(i,3,0) { fin >> p; farmer[i] = p; } for(i,3,0) { fin >>p; master[i] = p; } for(i,N+1,1) for(j,N+1,1) for(k,N+1,1) { if (valid(i,j,k)) { ++ans; } } fout << ans << endl; }
[ "lingkangwei.kevin@gmail.com" ]
lingkangwei.kevin@gmail.com
cd18c20efeb200733c5f5c118b609842c539b42b
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/242/287/CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_realloc_61b.cpp
3a1ee19339bdb999487533cef9a91c2268ac254b
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,703
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_realloc_61b.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-61b.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 61 Data flow: data returned from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_realloc_61 { #ifndef OMITBAD twoIntsStruct * badSource(twoIntsStruct * data) { data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct)); if (data == NULL) {exit(-1);} return data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ twoIntsStruct * goodG2BSource(twoIntsStruct * data) { /* FIX: Allocate memory using new [] */ data = new twoIntsStruct[100]; return data; } /* goodB2G() uses the BadSource with the GoodSink */ twoIntsStruct * goodB2GSource(twoIntsStruct * data) { data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct)); if (data == NULL) {exit(-1);} return data; } #endif /* OMITGOOD */ } /* close namespace */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
ab2a2a3b2c0fe50f5efbde3f814695defa2aed80
d2190cbb5ea5463410eb84ec8b4c6a660e4b3d0e
/old_hydra/hydra/tags/aug04/pidutil/hpiddilepfilter.h
2f35493284622593f988939be4148d5a0f822c21
[]
no_license
wesmail/hydra
6c681572ff6db2c60c9e36ec864a3c0e83e6aa6a
ab934d4c7eff335cc2d25f212034121f050aadf1
refs/heads/master
2021-07-05T17:04:53.402387
2020-08-12T08:54:11
2020-08-12T08:54:11
149,625,232
0
0
null
null
null
null
UTF-8
C++
false
false
1,520
h
#ifndef HPIDDILEPFILTER_H #define HPIDDILEPFILTER_H #include "hreconstructor.h" #include "hpiddileptonfilter.h" class HPidDilepton; class HCategory; class HLinearCategory; class TArrayI; class HIterator; class HPidDiLeptonFilter; class HPidDiLepFilter: public HReconstructor { protected: HCategory *fPidDilepton; HIterator *fPidDileptonIter; HCategory *fClusInfCat; HCategory *fMdcHitCat; Bool_t check_common_hits; Bool_t check_cpr_rej; Bool_t check_open_angle; Bool_t skip_no_pairs; Option_t *singleSelectCond;// OR or AND possible (OR is default) Int_t mode_data; // if mode_data=0 data are REAL if mode_data=1 data are SIM (default REAL) Option_t *cutParams; Float_t open_angle_cut; Float_t prob_single_cut; Char_t *fCpPidParName; TArrayI * double_ids; //array of Id of particles to be removed HPidDiLeptonFilter diLepFilter; public: HPidDiLepFilter(void); HPidDiLepFilter(Text_t *name,Text_t *title); ~HPidDiLepFilter(void); Bool_t init(void); Bool_t finalize(void); Int_t execute(void); void setOptions(Option_t *pParams=""); void setCpPidParamName(Char_t * cp_pid_par_name){fCpPidParName=cp_pid_par_name;} void setOpeningAngleCut(Float_t angle){open_angle_cut=angle;} //angle in deg void setProbSingleCut(Float_t prob){prob_single_cut=prob;} void setProbSingleCondition(Option_t *cond="OR"){singleSelectCond=cond;} void fillRM_array(); ClassDef(HPidDiLepFilter,0) }; #endif /* !HPIDDILEPFILTER */
[ "waleed.physics@gmail.com" ]
waleed.physics@gmail.com
3811a17717371af7681b73be06d868f45b2b89d0
8590b7928fdcff351a6e347c4b04a085f29b7895
/CS_suite/simulation/CS_simulation_unit.h
4e154112d5adbbdc7f9d85a4e21847b835a10c07
[]
no_license
liao007/VIC-CropSyst-Package
07fd0f29634cf28b96a299dc07156e4f98a63878
63a626250ccbf9020717b7e69b6c70e40a264bc2
refs/heads/master
2023-05-23T07:15:29.023973
2021-05-29T02:17:32
2021-05-29T02:17:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,907
h
#ifndef CS_simulation_unitH #define CS_simulation_unitH #ifndef simulation_elementH # include "CS_suite/simulation/CS_simulation_element.h" #endif #ifndef parameters_datarecH # include "corn/parameters/parameters_datarec.h" #endif #ifndef event_schedulerH # include "CS_suite/simulation/CS_event_scheduler.h" #endif #ifndef CS_simulation_controlH # include "CS_suite/simulation/CS_simulation_control.h" #endif # include "corn/OS/directory_entry_name.h" #ifndef BALANCER_H # include "common/simulation/balancer.h" #endif #define LABEL_scenario "scenario" #include "common/simulation/log.h" namespace CS { //______________________________________________________________________________ class Simulation_unit : public extends_ Simulation_element_composite { // Each simulation unit can have its own start and stop date // the Simulation engine will only process units // when the current date falls in between the start date and stop date public: CORN::Unidirectional_list performable_operations; // These are operations that have been scheduled for today. // They are shared will all simulation_elements // which will contribute to this list of operations. // Derived class(s) which perform operations should scan this // list (during process_day) and perform operations they are responsible // and set the event status for operations that were performed. protected: modifiable_ Simulation_control &simulation_control; //140714 protected: std::ofstream *balance_file_daily; //090409 std::ofstream *balance_file_annual; //090409 Unidirectional_list &balancers; // List of Balancer //070227 /**<\fn This is a list of balancers simulation components may relinquish their accumulation responsability to the master simulation to optimally perform accumulations, this ensures the accumulation is performed after all daily processing settles. For CropSyst, season accumulation is performed by the Land_unit_simulation. Because Simulation_engine does not have the concept of season. Although Cropping_system_simulation has the concept of season each LBU will have its own season (since it has its own rotation). Balancers are owned by this Simulation_engine list and will be deleted when the simulation ends. simulation elements may keep pointers (or references) to the balancers they create and/or use but must not delete them. **/ Common_simulation_log *CS_event_log; //160713 nat32 event_count; //160713 // The log should be temporary until I have explainations 160713 public: Simulation_unit (modifiable_ Simulation_control &simulation_control ,const CORN::date32 &today); virtual ~Simulation_unit(); virtual const OS::Directory_name &get_output_directory_name() const=0; /**<\fn The default output directory is the current working directory. However, typically (as in CropSyst), there should be a directory specifically for output, so this method should be overloaded. **/ public: // Simulation_element overrides virtual bool initialize() initialization_; // provides default event scheduler if not already provided virtual bool start() modification_; /** This specialization would open the optional balances files (NYI. **/ virtual bool process_day() modification_; //150611RLN virtual bool end_day() modification_; /**<\fn This is called each day after process_day(). Derived classes can use this to setup for the current day. Normally clearing daily state and or accumlators. **/ virtual bool end_year() modification_; public: // Introduced methods inline virtual Event_status_indicator perform_operation (Common_operation &/*op*/) modification_ { /*UNUSED(op);*/ return ES_COMPLETE;} inline virtual Event_status_indicator terminate_operation (Common_operation &/*op*/) modification_ { /*UNUSED(op);*/ return ES_COMPLETE;} public: nat32 take_balancer(Simulation::Balancer *balancer); //070227 /**<\fn This gives the balancer to the simulation to maintain accumulators. Balancers are optional. \return handle of balance. 070227 **/ }; //_2003-02-03___________________________________________________________________ } // namespace CS #endif
[ "mingliang.liu@wsu.edu" ]
mingliang.liu@wsu.edu
942e292ef01b38214999909419ca9c1240650a27
fd5b501d032156bd468271e01ee9da20265645df
/re2c/src/conf/help.cc
caf0f8f7b0cab05b49ee6de68b9038b29fd5fe34
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
YenForYang/debian-re2c
32e41bf2fd7712596ecc13449d936863bd35d09e
201e30509e886a3a0433b1c81caf93f599112de6
refs/heads/master
2020-04-10T11:55:50.071228
2018-12-24T08:43:02
2018-12-24T08:43:02
161,006,640
0
0
null
null
null
null
UTF-8
C++
false
false
12,675
cc
extern const char *help; const char *help = "\n" " -? -h --help\n" " Show help message.\n" "\n" " -b --bit-vectors\n" " Optimize conditional jumps using bit masks. Implies -s.\n" "\n" " -c --conditions --start-conditions\n" " Enable support of Flex-like \"conditions\": multiple interrelated\n" " lexers within one block. Option --start-conditions is a legacy\n" " alias; use --conditions instead.\n" "\n" " -d --debug-output\n" " Emit YYDEBUG in the generated code. YYDEBUG should be defined\n" " by the user in the form of a void function with two parameters:\n" " state (lexer state or -1) and symbol (current input symbol of\n" " type YYCTYPE).\n" "\n" " -D --emit-dot\n" " Instead of normal output generate lexer graph in DOT format.\n" " The output can be converted to PNG with the help of Graphviz\n" " (something like dot -Tpng -odfa.png dfa.dot). Note that large\n" " graphs may crash Graphviz.\n" "\n" " -e --ecb\n" " Generate a lexer that reads input in EBCDIC encoding. re2c\n" " assumes that character range is 0 -- 0xFF an character size is 1\n" " byte.\n" "\n" " -f --storable-state\n" " Generate a lexer which can store its inner state. This is use‐\n" " ful in push-model lexers which are stopped by an outer program\n" " when there is not enough input, and then resumed when more input\n" " becomes available. In this mode users should additionally\n" " define YYGETSTATE () and YYSETSTATE (state) macros and variables\n" " yych, yyaccept and the state as part of the lexer state.\n" "\n" " -F --flex-syntax\n" " Partial support for Flex syntax: in this mode named definitions\n" " don't need the equal sign and the terminating semicolon, and\n" " when used they must be surrounded by curly braces. Names with‐\n" " out curly braces are treated as double-quoted strings.\n" "\n" " -g --computed-gotos\n" " Optimize conditional jumps using non-standard \"computed goto\"\n" " extension (must be supported by C/C++ compiler). re2c generates\n" " jump tables only in complex cases with a lot of conditional\n" " branches. Complexity threshold can be configured with\n" " cgoto:threshold configuration. This option implies -b.\n" "\n" " -i --no-debug-info\n" " Do not output #line information. This is useful when the gener‐\n" " ated code is tracked by some version control system.\n" "\n" " -o OUTPUT --output=OUTPUT\n" " Specify the OUTPUT file.\n" "\n" " -r --reusable\n" " Allows reuse of re2c rules with /*!rules:re2c */ and /*!use:re2c\n" " */ blocks. In this mode simple /*!re2c */ blocks are not\n" " allowed and exactly one /*!rules:re2c */ block must be present.\n" " The rules are saved and used by every /*!use:re2c */ block that\n" " follows (which may add rules of their own). This option allows\n" " one to reuse the same set of rules with different configurations.\n" "\n" " -s --nested-ifs\n" " Use nested if statements instead of switch statements in condi‐\n" " tional jumps. This usually results in more efficient code with\n" " non-optimizing C/C++ compilers.\n" "\n" " -t HEADER --type-header=HEADER\n" " Generate a HEADER file that contains enum with condition names.\n" " Requires -c option.\n" "\n" " -T --tags\n" " Enable submatch extraction with tags.\n" "\n" " -P --posix-captures\n" " Enable submatch extraction with POSIX-style capturing groups.\n" "\n" " -u --unicode\n" " Generate a lexer that reads input in UTF-32 encoding. re2c\n" " assumes that character range is 0 -- 0x10FFFF and character size\n" " is 4 bytes. Implies -s.\n" "\n" " -v --version\n" " Show version information.\n" "\n" " -V --vernum\n" " Show version information in MMmmpp format (major, minor, patch).\n" "\n" " -w --wide-chars\n" " Generate a lexer that reads input in UCS-2 encoding. re2c\n" " assumes that character range is 0 -- 0xFFFF and character size\n" " is 2 bytes. Implies -s.\n" "\n" " -x --utf-16\n" " Generate a lexer that reads input in UTF-16 encoding. re2c\n" " assumes that character range is 0 -- 0x10FFFF and character size\n" " is 2 bytes. Implies -s.\n" "\n" " -8 --utf-8\n" " Generate a lexer that reads input in UTF-8 encoding. re2c\n" " assumes that character range is 0 -- 0x10FFFF and character size\n" " is 1 byte.\n" "\n" " --case-insensitive\n" " Treat single-quoted and double-quoted strings as case-insensi‐\n" " tive.\n" "\n" " --case-inverted\n" " Invert the meaning of single-quoted and double-quoted strings:\n" " treat single-quoted strings as case-sensitive and double-quoted\n" " strings as case-insensitive.\n" "\n" " --no-generation-date\n" " Suppress date output in the generated file.\n" "\n" " --no-lookahead\n" " Use TDFA(0) instead of TDFA(1). This option only has effect\n" " with --tags or --posix-captures options.\n" "\n" " --no-optimize-tags\n" " Suppress optimization of tag variables (useful for debugging or\n" " benchmarking).\n" "\n" " --no-version\n" " Suppress version output in the generated file.\n" "\n" " --encoding-policy POLICY\n" " Define the way re2c treats Unicode surrogates. POLICY can be\n" " one of the following: fail (abort with an error when a surrogate\n" " is encountered), substitute (silently replace surrogates with\n" " the error code point 0xFFFD), ignore (default, treat surrogates\n" " as normal code points). The Unicode standard says that stand‐\n" " alone surrogates are invalid, but real-world libraries and pro‐\n" " grams behave in different ways.\n" "\n" " --input INPUT\n" " Specify re2c input API. INPUT can be either default or custom\n" " (enables the use of generic API).\n" "\n" " -S --skeleton\n" " Ignore user-defined interface code and generate a self-contained\n" " \"skeleton\" program. Additionally, generate input files with\n" " strings derived from the regular grammar and compressed match\n" " results that are used to verify \"skeleton\" behavior on all\n" " inputs. This option is useful for finding bugs in optimizations\n" " and code generation.\n" "\n" " --empty-class POLICY\n" " Define the way re2c treats empty character classes. POLICY can\n" " be one of the following: match-empty (match empty input: illogi‐\n" " cal, but default behavior for backwards compatibility reasons),\n" " match-none (fail to match on any input), error (compilation\n" " error).\n" "\n" " --dfa-minimization ALGORITHM\n" " The internal algorithm used by re2c to minimize the DFA. ALGO‐\n" " RITHM can be either moore (Moore algorithm, the default) or ta‐\n" " ble (table filling algorithm). Both algorithms should produce\n" " the same DFA up to states relabeling; table filling is much\n" " slower and serves as a reference implementation.\n" "\n" " --eager-skip\n" " Make the generated lexer advance the input position \"eagerly\":\n" " immediately after reading input symbol. By default this happens\n" " after transition to the next state. Implied by --no-lookahead.\n" "\n" " --dump-nfa\n" " Generate representation of NFA in DOT format and dump it on\n" " stderr.\n" "\n" " --dump-dfa-raw\n" " Generate representation of DFA in DOT format under construction\n" " and dump it on stderr.\n" "\n" " --dump-dfa-det\n" " Generate representation of DFA in DOT format immediately after\n" " determinization and dump it on stderr.\n" "\n" " --dump-dfa-tagopt\n" " Generate representation of DFA in DOT format after tag optimiza‐\n" " tions and dump it on stderr.\n" "\n" " --dump-dfa-min\n" " Generate representation of DFA in DOT format after minimization\n" " and dump it on stderr.\n" "\n" " --dump-adfa\n" " Generate representation of DFA in DOT format after tunneling and\n" " dump it on stderr.\n" "\n" " -1 --single-pass\n" " Deprecated. Does nothing (single pass is the default now).\n" "\n" " -W Turn on all warnings.\n" "\n" " -Werror\n" " Turn warnings into errors. Note that this option alone doesn't\n" " turn on any warnings; it only affects those warnings that have\n" " been turned on so far or will be turned on later.\n" "\n" " -W<warning>\n" " Turn on warning.\n" "\n" " -Wno-<warning>\n" " Turn off warning.\n" "\n" " -Werror-<warning>\n" " Turn on warning and treat it as an error (this implies -W<warn‐\n" " ing>).\n" "\n" " -Wno-error-<warning>\n" " Don't treat this particular warning as an error. This doesn't\n" " turn off the warning itself.\n" "\n" " -Wcondition-order\n" " Warn if the generated program makes implicit assumptions about\n" " condition numbering. One should use either the -t, --type-header\n" " option or the /*!types:re2c*/ directive to generate a mapping of\n" " condition names to numbers and then use the autogenerated condi‐\n" " tion names.\n" "\n" " -Wempty-character-class\n" " Warn if a regular expression contains an empty character class.\n" " Trying to match an empty character class makes no sense: it\n" " should always fail. However, for backwards compatibility rea‐\n" " sons re2c allows empty character classes and treats them as\n" " empty strings. Use the --empty-class option to change the\n" " default behavior.\n" "\n" " -Wmatch-empty-string\n" " Warn if a rule is nullable (matches an empty string). If the\n" " lexer runs in a loop and the empty match is unintentional, the\n" " lexer may unexpectedly hang in an infinite loop.\n" "\n" " -Wswapped-range\n" " Warn if the lower bound of a range is greater than its upper\n" " bound. The default behavior is to silently swap the range\n" " bounds.\n" "\n" " -Wundefined-control-flow\n" " Warn if some input strings cause undefined control flow in the\n" " lexer (the faulty patterns are reported). This is the most dan‐\n" " gerous and most common mistake. It can be easily fixed by adding\n" " the default rule * which has the lowest priority, matches any\n" " code unit, and consumes exactly one code unit.\n" "\n" " -Wunreachable-rules\n" " Warn about rules that are shadowed by other rules and will never\n" " match.\n" "\n" " -Wuseless-escape\n" " Warn if a symbol is escaped when it shouldn't be. By default,\n" " re2c silently ignores such escapes, but this may as well indi‐\n" " cate a typo or an error in the escape sequence.\n" "\n" " -Wnondeterministic-tags\n" " Warn if a tag has n-th degree of nondeterminism, where n is\n" " greater than 1.\n" "\n" ;
[ "richard@yenforyang.com" ]
richard@yenforyang.com
2d95c613037f85a52d6c4b26c06d8574270ee64f
6b40e9cba1dd06cd31a289adff90e9ea622387ac
/Develop/Game/XSystemMsgHandler.h
68656b7c5ae79a31dbf64a885831fc108f316f1b
[]
no_license
AmesianX/SHZPublicDev
c70a84f9170438256bc9b2a4d397d22c9c0e1fb9
0f53e3b94a34cef1bc32a06c80730b0d8afaef7d
refs/heads/master
2022-02-09T07:34:44.339038
2014-06-09T09:20:04
2014-06-09T09:20:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
281
h
#pragma once #include "XMsgHandler.h" class XSystemMsgHandler: public XMsgHandler { public: XSystemMsgHandler(); virtual ~XSystemMsgHandler(); virtual bool OnResponse(const minet::MCommand* pCmd); virtual CSMsgType GetHandlerType(void) { return MT_SYSTEM; } };
[ "shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4" ]
shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4
cf5a11522bc96ca8a4b7db030116d529d110ae7a
1a4f8c01b142be5646cbde9355ca1116c7d1e47f
/Board.h
7d18492ae9e5192e7f145584fd47f7ae9b3b2378
[]
no_license
Lmq2002/roguelike
15343de6ef3f0370a8507ae5d3d9f92f90467e16
ec3c7e1b41d4f780e202890e191fc0a79fabe260
refs/heads/main
2023-06-03T12:31:07.676775
2021-06-22T11:48:05
2021-06-22T11:48:05
363,574,777
0
0
null
null
null
null
UTF-8
C++
false
false
192
h
#pragma once #ifndef _BOARD_H_ #define _BOARD_H_ #include "Characters.h" class Board : public Characters { public: CREATE_FUNC(Board); virtual bool init(); void act(); }; #endif _BOARD_H_
[ "2316961613@qq.com" ]
2316961613@qq.com
0872c466356d3cee219a2e30ec51348e7acdbe0b
0b92fdfb42dd0faf31ce446060c281f532b81755
/build-Manager-Desktop_Qt_5_5_1_MinGW_32bit-Debug/ui_loginform.h
679064f3cd5d4b4345228f0d7058267b9f5c8afb
[]
no_license
chrisyeung333/Proyecto-Final
86979e6a92f31f37644371ce56fcfc6202cb0617
62d7cadb7168407d7f1008dab467270fd415986e
refs/heads/master
2021-01-10T13:38:45.241845
2015-12-08T17:19:08
2015-12-08T17:19:08
47,516,912
0
0
null
null
null
null
UTF-8
C++
false
false
3,875
h
/******************************************************************************** ** Form generated from reading UI file 'loginform.ui' ** ** Created by: Qt User Interface Compiler version 5.5.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_LOGINFORM_H #define UI_LOGINFORM_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_LoginForm { public: QGroupBox *groupBox; QVBoxLayout *verticalLayout_2; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label; QLineEdit *lineEdit_User; QHBoxLayout *horizontalLayout_2; QLabel *label_2; QLineEdit *lineEdit_Pass; QPushButton *pushButton; QLabel *label_Status; void setupUi(QDialog *LoginForm) { if (LoginForm->objectName().isEmpty()) LoginForm->setObjectName(QStringLiteral("LoginForm")); LoginForm->resize(400, 300); groupBox = new QGroupBox(LoginForm); groupBox->setObjectName(QStringLiteral("groupBox")); groupBox->setGeometry(QRect(40, 40, 291, 201)); verticalLayout_2 = new QVBoxLayout(groupBox); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); label = new QLabel(groupBox); label->setObjectName(QStringLiteral("label")); horizontalLayout->addWidget(label); lineEdit_User = new QLineEdit(groupBox); lineEdit_User->setObjectName(QStringLiteral("lineEdit_User")); horizontalLayout->addWidget(lineEdit_User); verticalLayout->addLayout(horizontalLayout); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2")); label_2 = new QLabel(groupBox); label_2->setObjectName(QStringLiteral("label_2")); horizontalLayout_2->addWidget(label_2); lineEdit_Pass = new QLineEdit(groupBox); lineEdit_Pass->setObjectName(QStringLiteral("lineEdit_Pass")); horizontalLayout_2->addWidget(lineEdit_Pass); verticalLayout->addLayout(horizontalLayout_2); verticalLayout_2->addLayout(verticalLayout); pushButton = new QPushButton(groupBox); pushButton->setObjectName(QStringLiteral("pushButton")); verticalLayout_2->addWidget(pushButton); label_Status = new QLabel(LoginForm); label_Status->setObjectName(QStringLiteral("label_Status")); label_Status->setGeometry(QRect(66, 260, 251, 20)); retranslateUi(LoginForm); QMetaObject::connectSlotsByName(LoginForm); } // setupUi void retranslateUi(QDialog *LoginForm) { LoginForm->setWindowTitle(QApplication::translate("LoginForm", "Profesor", 0)); groupBox->setTitle(QString()); label->setText(QApplication::translate("LoginForm", "Usuario", 0)); label_2->setText(QApplication::translate("LoginForm", "Contrase\303\261a", 0)); pushButton->setText(QApplication::translate("LoginForm", "Ingresar", 0)); label_Status->setText(QString()); } // retranslateUi }; namespace Ui { class LoginForm: public Ui_LoginForm {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_LOGINFORM_H
[ "kevin.wang.9408@gmail.com" ]
kevin.wang.9408@gmail.com
feb133a6fc42a98dba1cbd77a21730144a2e40c3
62ba00726a94e7dab156397b85d6331c46ea878f
/array_stack.cpp
8740d5cc76fc2b1960d594a41fed1ba720ea3fa4
[]
no_license
harsimran01099/Data-structure
53f0868fa1a1724900a96507a8267c4eb47e62a7
beba1841e6e198e5100dacf9488fbdcab6e1d446
refs/heads/master
2020-05-31T17:01:24.401422
2019-09-02T15:12:00
2019-09-02T15:12:00
190,396,273
0
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
#include<iostream> #define Max_size 101 using namespace std; int A[Max_size],top=-1; void push(int x) { if(top==Max_size-1) { cout<<"stack over flow"; return; } A[++top]=x; } void pop() { if(top==-1) { cout<<"stack is under flow"; return; } top--; } int Top() { if(top==-1) { cout<<"stack is empty"; return 0; } return A[top]; } bool isEmpty() { if(top==-1) { return true; } return false; } int main() { push(2); push(3); push(4); pop(); isEmpty(); push(2); Top(); push(6); }
[ "harsimran01099@gmail.com" ]
harsimran01099@gmail.com
86908260cfb1d1e7a44daa1d14157cb380c78f84
76c1d6679768213f64a07473f32579afdb8c6941
/Clock.h
d677f07a84290c395ca24f54fa62ef56b436a1f8
[]
no_license
sanhuhai/Clock
b4b38e2813005befdeb688629f8b05387bf7742c
496c440a1e0a0ede2302521d72a42c305da9d0f9
refs/heads/master
2022-10-08T00:11:14.405687
2020-06-12T07:34:21
2020-06-12T07:34:21
271,737,962
0
0
null
null
null
null
UTF-8
C++
false
false
597
h
#pragma once #include <QtWidgets/QDialog> #include <QLCDNumber> #include <QPalette> #include <QTimer> #include <Qtime> #include <QMouseEvent> #include <QDebug> #include <QPoint> //#include "ui_Clock.h" #ifdef WIN32 #pragma execution_character_set("utf-8") #endif // WIN32 class Clock : public QLCDNumber { Q_OBJECT public: Clock(QWidget *parent = Q_NULLPTR); void mousePressEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); void showT(); private slots: void showTime(); private: //Ui::ClockClass ui; bool showColon; QPoint dragPosition; };
[ "yqz2309761996@outlook.com" ]
yqz2309761996@outlook.com
fbf915e0b4f1d9e93b63ab7cc892ec16a237321f
d06856e6c22e37bb86856daa47cb7b51da78d698
/Source/WebKit/chromium/src/WebExternalTextureLayerImpl.h
4f9a98727c97d9b5c958744c269b884d1853e76f
[ "BSD-2-Clause" ]
permissive
sfarbotka/py3webkit
8ddd2288e72a08deefc18a2ddf661a06185ad924
4492fc82c67189931141ee64e1cc5df7e5331bf9
refs/heads/master
2016-09-05T17:32:02.639162
2012-02-08T15:14:28
2012-02-08T15:14:28
3,235,299
6
0
null
null
null
null
UTF-8
C++
false
false
2,093
h
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef WebExternalTextureLayerImpl_h #define WebExternalTextureLayerImpl_h #include "PluginLayerChromium.h" #include <wtf/PassRefPtr.h> namespace WebKit { class WebLayerClient; class WebExternalTextureLayerImpl : public WebCore::PluginLayerChromium, public WebCore::CCLayerDelegate { public: static PassRefPtr<WebExternalTextureLayerImpl> create(WebLayerClient*); protected: WebExternalTextureLayerImpl(WebLayerClient*); virtual ~WebExternalTextureLayerImpl(); virtual void paintContents(WebCore::GraphicsContext&, const WebCore::IntRect& clip); virtual void notifySyncRequired(); virtual bool drawsContent() const; WebLayerClient* m_client; }; } // namespace WebKit #endif // WebExternalTextureLayerImpl_h
[ "z8sergey8z@gmail.com" ]
z8sergey8z@gmail.com
e5edc6a730a3f7242c48e6e909aa1321b07c33da
ac9fd76c91a8de1e32cd99d30c3374bb48be3a0d
/dialogs/optionsdialog.h
27955e59ec380839ca69cbf6dcc37579c16c6fc8
[ "BSD-3-Clause" ]
permissive
bendalab/NixView
89d1c1dbf8246c218c221779031d07d433f38e54
62d45409d9ee9bd7612b5f3e7742a35e3202bbda
refs/heads/master
2020-04-09T07:32:30.207858
2019-12-21T15:32:43
2019-12-21T15:32:43
41,813,337
9
6
null
2018-04-10T19:00:39
2015-09-02T16:39:48
C++
UTF-8
C++
false
false
492
h
#ifndef OPTIONSDIALOG_H #define OPTIONSDIALOG_H #include <QDialog> namespace Ui { class OptionsDialog; } class OptionsDialog : public QDialog { Q_OBJECT public: explicit OptionsDialog(QWidget *parent = 0); ~OptionsDialog(); public slots: void file_opened(QString filename); signals: void column_visibility_changed(QString who, QString column, bool state); void recent_file_changed(QStringList); private: Ui::OptionsDialog *ui; }; #endif // OPTIONSDIALOG_H
[ "jan.grewe@g-node.org" ]
jan.grewe@g-node.org
d3f6db7b4f71db1ffb6aa2cb16d65f33b10eed54
01d1d17b920718fb25489edb6f56c4e3e271b112
/olcRoguEngine/roguSrc/olcPixelGameEngine.h
16089059cd73bb510f3218b47ed1caeef81fc6a7
[ "MIT" ]
permissive
Momonyaro/RoguEngine
708d4bb6df13a6284ea186fcfcc0dd31b9182651
fc8b7b86e6b624690b055863af7e966df7bc6a1a
refs/heads/master
2023-04-15T13:22:26.191702
2021-04-28T15:57:01
2021-04-28T15:57:01
335,334,847
0
0
null
null
null
null
ISO-8859-2
C++
false
false
201,244
h
#pragma region license_and_help /* olcPixelGameEngine.h +-------------------------------------------------------------+ | OneLoneCoder Pixel Game Engine v2.15 | | "What do you need? Pixels... Lots of Pixels..." - javidx9 | +-------------------------------------------------------------+ What is this? ~~~~~~~~~~~~~ olc::PixelGameEngine is a single file, cross platform graphics and userinput framework used for games, visualisations, algorithm exploration and learning. It was developed by YouTuber "javidx9" as an assistive tool for many of his videos. The goal of this project is to provide high speed graphics with minimal project setup complexity, to encourage new programmers, younger people, and anyone else that wants to make fun things. However, olc::PixelGameEngine is not a toy! It is a powerful and fast utility capable of delivering high resolution, high speed, high quality applications which behave the same way regardless of the operating system or platform. This file provides the core utility set of the olc::PixelGameEngine, including window creation, keyboard/mouse input, main game thread, timing, pixel drawing routines, image/sprite loading and drawing routines, and a bunch of utility types to make rapid development of games/visualisations possible. License (OLC-3) ~~~~~~~~~~~~~~~ Copyright 2018 - 2021 OneLoneCoder.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions or derivations of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions or derivative works in binary form must reproduce the above copyright notice. This list of conditions and the following disclaimer must be reproduced in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Links ~~~~~ YouTube: https://www.youtube.com/javidx9 https://www.youtube.com/javidx9extra Discord: https://discord.gg/WhwHUMV Twitter: https://www.twitter.com/javidx9 Twitch: https://www.twitch.tv/javidx9 GitHub: https://www.github.com/onelonecoder Homepage: https://www.onelonecoder.com Patreon: https://www.patreon.com/javidx9 Community: https://community.onelonecoder.com Compiling in Linux ~~~~~~~~~~~~~~~~~~ You will need a modern C++ compiler, so update yours! To compile use the command: g++ -o YourProgName YourSource.cpp -lX11 -lGL -lpthread -lpng -lstdc++fs -std=c++17 On some Linux configurations, the frame rate is locked to the refresh rate of the monitor. This engine tries to unlock it but may not be able to, in which case try launching your program like this: vblank_mode=0 ./YourProgName Compiling in Code::Blocks on Windows ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Well I wont judge you, but make sure your Code::Blocks installation is really up to date - you may even consider updating your C++ toolchain to use MinGW32-W64. Guide for installing recent GCC for Windows: https://www.msys2.org/ Guide for configuring code::blocks: https://solarianprogrammer.com/2019/11/05/install-gcc-windows/ https://solarianprogrammer.com/2019/11/16/install-codeblocks-gcc-windows-build-c-cpp-fortran-programs/ Add these libraries to "Linker Options": user32 gdi32 opengl32 gdiplus Shlwapi dwmapi stdc++fs Set these compiler options: -std=c++17 Compiling on Mac - EXPERIMENTAL! PROBABLY HAS BUGS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Yes yes, people use Macs for C++ programming! Who knew? Anyway, enough arguing, thanks to Mumflr the PGE is now supported on Mac. Now I know nothing about Mac, so if you need support, I suggest checking out the instructions here: https://github.com/MumflrFumperdink/olcPGEMac clang++ -arch x86_64 -std=c++17 -mmacosx-version-min=10.15 -Wall -framework OpenGL -framework GLUT -lpng YourSource.cpp -o YourProgName Compiling with Emscripten (New & Experimental) ~~~~~~~~~~~~~~~~~~~~~~~~~ Emscripten compiler will turn your awesome C++ PixelGameEngine project into WASM! This means you can run your application in teh browser, great for distributing and submission in to jams and things! It's a bit new at the moment. em++ -std=c++17 -O2 -s ALLOW_MEMORY_GROWTH=1 -s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2 -s USE_LIBPNG=1 ./YourSource.cpp -o pge.html Using stb_image.h ~~~~~~~~~~~~~~~~~ The PGE will load png images by default (with help from libpng on non-windows systems). However, the excellent "stb_image.h" can be used instead, supporting a variety of image formats, and has no library dependence - something we like at OLC studios ;) To use stb_image.h, make sure it's in your code base, and simply: #define OLC_IMAGE_STB Before including the olcPixelGameEngine.h header file. stb_image.h works on many systems and can be downloaded here: https://github.com/nothings/stb/blob/master/stb_image.h Multiple cpp file projects? ~~~~~~~~~~~~~~~~~~~~~~~~~~~ As a single header solution, the OLC_PGE_APPLICATION definition is used to insert the engine implementation at a project location of your choosing. The simplest way to setup multifile projects is to create a file called "olcPixelGameEngine.cpp" which includes the following: #define OLC_PGE_APPLICATION #include "olcPixelGameEngine.h" That's all it should include. You can also include PGEX includes and defines in here too. With this in place, you dont need to #define OLC_PGE_APPLICATION anywhere, and can simply include this header file as an when you need to. Ports ~~~~~ olc::PixelGameEngine has been ported and tested with varying degrees of success to: WinXP, Win7, Win8, Win10, Various Linux, Raspberry Pi, Chromebook, Playstation Portable (PSP) and Nintendo Switch. If you are interested in the details of these ports, come and visit the Discord! Thanks ~~~~~~ I'd like to extend thanks to Ian McKay, Bispoo, Eremiell, slavka, gurkanctn, Phantim, IProgramInCPP, JackOJC, KrossX, Huhlig, Dragoneye, Appa, JustinRichardsMusic, SliceNDice, dandistine, Ralakus, Gorbit99, raoul, joshinils, benedani, Moros1138, Alexio, SaladinAkara & MagetzUb for advice, ideas and testing, and I'd like to extend my appreciation to the 230K YouTube followers, 80+ Patreons and 10K Discord server members who give me the motivation to keep going with all this :D Significant Contributors: @Moros1138, @SaladinAkara, @MaGetzUb, @slavka, @Dragoneye, @Gorbit99, @dandistine & @Mumflr Special thanks to those who bring gifts! GnarGnarHead.......Domina Gorbit99...........Bastion, Ori & The Blind Forest, Terraria, Spelunky 2 Marti Morta........Gris Danicron...........Terraria SaladinAkara.......Aseprite, Inside AlterEgo...........Final Fantasy XII - The Zodiac Age SlicEnDicE.........Noita, Inside Special thanks to my Patreons too - I wont name you on here, but I've certainly enjoyed my tea and flapjacks :D Author ~~~~~~ David Barr, aka javidx9, ŠOneLoneCoder 2018, 2019, 2020, 2021 */ #pragma endregion #pragma region version_history /* 2.01: Made renderer and platform static for multifile projects 2.02: Added Decal destructor, optimised Pixel constructor 2.03: Added FreeBSD flags, Added DrawStringDecal() 2.04: Windows Full-Screen bug fixed 2.05: +DrawPartialWarpedDecal() - draws a warped decal from a subset image +DrawPartialRotatedDecal() - draws a rotated decal from a subset image 2.06: +GetTextSize() - returns area occupied by multiline string +GetWindowSize() - returns actual window size +GetElapsedTime() - returns last calculated fElapsedTime +GetWindowMouse() - returns actual mouse location in window +DrawExplicitDecal() - bow-chikka-bow-bow +DrawPartialDecal(pos, size) - draws a partial decal to specified area +FillRectDecal() - draws a flat shaded rectangle as a decal +GradientFillRectDecal() - draws a rectangle, with unique colour corners +Modified DrawCircle() & FillCircle() - Thanks IanM-Matrix1 (#PR121) +Gone someway to appeasing pedants 2.07: +GetPixelSize() - returns user specified pixel size +GetScreenPixelSize() - returns actual size in monitor pixels +Pixel Cohesion Mode (flag in Construct()) - disallows arbitrary window scaling +Working VSYNC in Windows windowed application - now much smoother +Added string conversion for olc::vectors +Added comparator operators for olc::vectors +Added DestroyWindow() on windows platforms for serial PGE launches +Added GetMousePos() to stop TarriestPython whinging 2.08: Fix SetScreenSize() aspect ratio pre-calculation Fix DrawExplicitDecal() - stupid oversight with multiple decals Disabled olc::Sprite copy constructor +olc::Sprite Duplicate() - produces a new clone of the sprite +olc::Sprite Duplicate(pos, size) - produces a new sprite from the region defined +Unary operators for vectors +More pedant mollification - Thanks TheLandfill +ImageLoader modules - user selectable image handling core, gdi+, libpng, stb_image +Mac Support via GLUT - thanks Mumflr! 2.09: Fix olc::Renderable Image load error - Thanks MaGetzUb & Zij-IT for finding and moaning about it Fix file rejection in image loaders when using resource packs Tidied Compiler defines per platform - Thanks slavka +Pedant fixes, const correctness in parts +DecalModes - Normal, Additive, Multiplicative blend modes +Pixel Operators & Lerping +Filtered Decals - If you hate pixels, then erase this file +DrawStringProp(), GetTextSizeProp(), DrawStringPropDecal() - Draws non-monospaced font 2.10: Fix PixelLerp() - oops my bad, lerped the wrong way :P Fix "Shader" support for strings - thanks Megarev for crying about it Fix GetTextSizeProp() - Height was just plain wrong... +vec2d operator overloads (element wise *=, /=) +vec2d comparison operators... :| yup... hmmmm... +vec2d ceil(), floor(), min(), max() functions - surprising how often I do it manually +DrawExplicitDecal(... uint32_t elements) - complete control over convex polygons and lines +DrawPolygonDecal() - to keep Bispoo happy, required significant rewrite of EVERYTHING, but hey ho +Complete rewrite of decal renderer +OpenGL 3.3 Renderer (also supports Raspberry Pi) +PGEX Break-In Hooks - with a push from Dandistine +Wireframe Decal Mode - For debug overlays 2.11: Made PGEX hooks optional - (provide true to super constructor) 2.12: Fix for MinGW compiler non-compliance :( - why is its sdk structure different?? why??? 2.13: +GetFontSprite() - allows access to font data 2.14: Fix WIN32 Definition reshuffle Fix DrawPartialDecal() - messed up dimension during renderer experiment, didnt remove junk code, thanks Alexio Fix? Strange error regarding GDI+ Image Loader not knowing about COM, SDK change? 2.15: Big Reformat +WASM Platform (via Emscripten) - Big Thanks to OLC Community - See Platform for details +Sample Mode for Decals +Made olc_ConfigureSystem() accessible +Added OLC_----_CUSTOM_EX for externalised platforms, renderers and image loaders =Refactored olc::Sprite pixel data store -Deprecating LoadFromPGESprFile() -Deprecating SaveToPGESprFile() Fix Pixel -= operator (thanks Au Lit) !! Apple Platforms will not see these updates immediately - Sorry, I dont have a mac to test... !! !! Volunteers willing to help appreciated, though PRs are manually integrated with credit !! */ #pragma endregion #pragma region hello_world_example // O------------------------------------------------------------------------------O // | Example "Hello World" Program (main.cpp) | // O------------------------------------------------------------------------------O /* #define OLC_PGE_APPLICATION #include "olcPixelGameEngine.h" // Override base class with your custom functionality class Example : public olc::PixelGameEngine { public: Example() { // Name your application sAppName = "Example"; } public: bool OnUserCreate() override { // Called once at the start, so create things here return true; } bool OnUserUpdate(float fElapsedTime) override { // Called once per frame, draws random coloured pixels for (int x = 0; x < ScreenWidth(); x++) for (int y = 0; y < ScreenHeight(); y++) Draw(x, y, olc::Pixel(rand() % 256, rand() % 256, rand() % 256)); return true; } }; int main() { Example demo; if (demo.Construct(256, 240, 4, 4)) demo.Start(); return 0; } */ #pragma endregion #ifndef OLC_PGE_DEF #define OLC_PGE_DEF #pragma region std_includes // O------------------------------------------------------------------------------O // | STANDARD INCLUDES | // O------------------------------------------------------------------------------O #include <cmath> #include <cstdint> #include <string> #include <iostream> #include <streambuf> #include <sstream> #include <chrono> #include <vector> #include <list> #include <thread> #include <atomic> #include <fstream> #include <map> #include <functional> #include <algorithm> #include <array> #include <cstring> #pragma endregion #define PGE_VER 215 // O------------------------------------------------------------------------------O // | COMPILER CONFIGURATION ODDITIES | // O------------------------------------------------------------------------------O #pragma region compiler_config #define USE_EXPERIMENTAL_FS #if defined(_WIN32) #if _MSC_VER >= 1920 && _MSVC_LANG >= 201703L #undef USE_EXPERIMENTAL_FS #endif #endif #if defined(__linux__) || defined(__MINGW32__) || defined(__EMSCRIPTEN__) || defined(__FreeBSD__) || defined(__APPLE__) #if __cplusplus >= 201703L #undef USE_EXPERIMENTAL_FS #endif #endif #if defined(USE_EXPERIMENTAL_FS) || defined(FORCE_EXPERIMENTAL_FS) // C++14 #define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING #include <experimental/filesystem> namespace _gfs = std::experimental::filesystem::v1; #else // C++17 #include <filesystem> namespace _gfs = std::filesystem; #endif #if defined(UNICODE) || defined(_UNICODE) #define olcT(s) L##s #else #define olcT(s) s #endif #define UNUSED(x) (void)(x) // O------------------------------------------------------------------------------O // | PLATFORM SELECTION CODE, Thanks slavka! | // O------------------------------------------------------------------------------O // Platform #if !defined(OLC_PLATFORM_WINAPI) && !defined(OLC_PLATFORM_X11) && !defined(OLC_PLATFORM_GLUT) && !defined(OLC_PLATFORM_EMSCRIPTEN) #if !defined(OLC_PLATFORM_CUSTOM_EX) #if defined(_WIN32) #define OLC_PLATFORM_WINAPI #endif #if defined(__linux__) || defined(__FreeBSD__) #define OLC_PLATFORM_X11 #endif #if defined(__APPLE__) #define GL_SILENCE_DEPRECATION #define OLC_PLATFORM_GLUT #endif #if defined(__EMSCRIPTEN__) #define OLC_PLATFORM_EMSCRIPTEN #endif #endif #endif // Start Situation #if defined(OLC_PLATFORM_GLUT) || defined(OLC_PLATFORM_EMSCRIPTEN) #define PGE_USE_CUSTOM_START #endif // Renderer #if !defined(OLC_GFX_OPENGL10) && !defined(OLC_GFX_OPENGL33) && !defined(OLC_GFX_DIRECTX10) #if !defined(OLC_GFX_CUSTOM_EX) #if defined(OLC_PLATFORM_EMSCRIPTEN) #define OLC_GFX_OPENGL33 #else #define OLC_GFX_OPENGL10 #endif #endif #endif // Image loader #if !defined(OLC_IMAGE_STB) && !defined(OLC_IMAGE_GDI) && !defined(OLC_IMAGE_LIBPNG) #if !defined(OLC_IMAGE_CUSTOM_EX) #if defined(_WIN32) #define OLC_IMAGE_GDI #endif #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__EMSCRIPTEN__) #define OLC_IMAGE_LIBPNG #endif #endif #endif // O------------------------------------------------------------------------------O // | PLATFORM-SPECIFIC DEPENDENCIES | // O------------------------------------------------------------------------------O #if defined(OLC_PLATFORM_WINAPI) #define _WINSOCKAPI_ // Thanks Cornchipss #if !defined(VC_EXTRALEAN) #define VC_EXTRALEAN #endif #if !defined(NOMINMAX) #define NOMINMAX #endif // In Code::Blocks #if !defined(_WIN32_WINNT) #ifdef HAVE_MSMF #define _WIN32_WINNT 0x0600 // Windows Vista #else #define _WIN32_WINNT 0x0500 // Windows 2000 #endif #endif #include <windows.h> #undef _WINSOCKAPI_ #endif #if defined(OLC_PLATFORM_X11) namespace X11 { #include <X11/X.h> #include <X11/Xlib.h> } #endif #if defined(OLC_PLATFORM_GLUT) #if defined(__linux__) #include <GL/glut.h> #include <GL/freeglut_ext.h> #endif #if defined(__APPLE__) #include <GLUT/glut.h> #endif #endif #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine INTERFACE DECLARATION | // O------------------------------------------------------------------------------O #pragma region pge_declaration namespace olc { class PixelGameEngine; class Sprite; // Pixel Game Engine Advanced Configuration constexpr uint8_t nMouseButtons = 5; constexpr uint8_t nDefaultAlpha = 0xFF; constexpr uint32_t nDefaultPixel = (nDefaultAlpha << 24); enum rcode { FAIL = 0, OK = 1, NO_FILE = -1 }; // O------------------------------------------------------------------------------O // | olc::Pixel - Represents a 32-Bit RGBA colour | // O------------------------------------------------------------------------------O struct Pixel { union { uint32_t n = nDefaultPixel; struct { uint8_t r; uint8_t g; uint8_t b; uint8_t a; }; }; enum Mode { NORMAL, MASK, ALPHA, CUSTOM }; Pixel(); Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = nDefaultAlpha); Pixel(uint32_t p); Pixel& operator = (const Pixel& v) = default; bool operator ==(const Pixel& p) const; bool operator !=(const Pixel& p) const; Pixel operator * (const float i) const; Pixel operator / (const float i) const; Pixel& operator *=(const float i); Pixel& operator /=(const float i); Pixel operator + (const Pixel& p) const; Pixel operator - (const Pixel& p) const; Pixel& operator +=(const Pixel& p); Pixel& operator -=(const Pixel& p); Pixel inv() const; }; Pixel PixelF(float red, float green, float blue, float alpha = 1.0f); Pixel PixelLerp(const olc::Pixel& p1, const olc::Pixel& p2, float t); // O------------------------------------------------------------------------------O // | USEFUL CONSTANTS | // O------------------------------------------------------------------------------O static const Pixel GREY(192, 192, 192), DARK_GREY(128, 128, 128), VERY_DARK_GREY(64, 64, 64), RED(255, 0, 0), DARK_RED(128, 0, 0), VERY_DARK_RED(64, 0, 0), YELLOW(255, 255, 0), DARK_YELLOW(128, 128, 0), VERY_DARK_YELLOW(64, 64, 0), GREEN(0, 255, 0), DARK_GREEN(0, 128, 0), VERY_DARK_GREEN(0, 64, 0), CYAN(0, 255, 255), DARK_CYAN(0, 128, 128), VERY_DARK_CYAN(0, 64, 64), BLUE(0, 0, 255), DARK_BLUE(0, 0, 128), VERY_DARK_BLUE(0, 0, 64), MAGENTA(255, 0, 255), DARK_MAGENTA(128, 0, 128), VERY_DARK_MAGENTA(64, 0, 64), WHITE(255, 255, 255), BLACK(0, 0, 0), BLANK(0, 0, 0, 0); // Thanks to scripticuk and others for updating the key maps // NOTE: The GLUT platform will need updating, open to contributions ;) enum Key { NONE, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, K0, K1, K2, K3, K4, K5, K6, K7, K8, K9, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, UP, DOWN, LEFT, RIGHT, SPACE, TAB, SHIFT, CTRL, INS, DEL, HOME, END, PGUP, PGDN, BACK, ESCAPE, RETURN, ENTER, PAUSE, SCROLL, NP0, NP1, NP2, NP3, NP4, NP5, NP6, NP7, NP8, NP9, NP_MUL, NP_DIV, NP_ADD, NP_SUB, NP_DECIMAL, PERIOD, EQUALS, COMMA, MINUS, OEM_1, OEM_2, OEM_3, OEM_4, OEM_5, OEM_6, OEM_7, OEM_8, CAPS_LOCK, ENUM_END }; // O------------------------------------------------------------------------------O // | olc::HWButton - Represents the state of a hardware button (mouse/key/joy) | // O------------------------------------------------------------------------------O struct HWButton { bool bPressed = false; // Set once during the frame the event occurs bool bReleased = false; // Set once during the frame the event occurs bool bHeld = false; // Set true for all frames between pressed and released events }; // O------------------------------------------------------------------------------O // | olc::vX2d - A generic 2D vector type | // O------------------------------------------------------------------------------O #if !defined(OLC_IGNORE_VEC2D) template <class T> struct v2d_generic { T x = 0; T y = 0; v2d_generic() : x(0), y(0) {} v2d_generic(T _x, T _y) : x(_x), y(_y) {} v2d_generic(const v2d_generic& v) : x(v.x), y(v.y) {} v2d_generic& operator=(const v2d_generic& v) = default; T mag() const { return T(std::sqrt(x * x + y * y)); } T mag2() const { return x * x + y * y; } v2d_generic norm() const { T r = 1 / mag(); return v2d_generic(x * r, y * r); } v2d_generic perp() const { return v2d_generic(-y, x); } v2d_generic floor() const { return v2d_generic(std::floor(x), std::floor(y)); } v2d_generic ceil() const { return v2d_generic(std::ceil(x), std::ceil(y)); } v2d_generic max(const v2d_generic& v) const { return v2d_generic(std::max(x, v.x), std::max(y, v.y)); } v2d_generic min(const v2d_generic& v) const { return v2d_generic(std::min(x, v.x), std::min(y, v.y)); } T dot(const v2d_generic& rhs) const { return this->x * rhs.x + this->y * rhs.y; } T cross(const v2d_generic& rhs) const { return this->x * rhs.y - this->y * rhs.x; } v2d_generic operator + (const v2d_generic& rhs) const { return v2d_generic(this->x + rhs.x, this->y + rhs.y); } v2d_generic operator - (const v2d_generic& rhs) const { return v2d_generic(this->x - rhs.x, this->y - rhs.y); } v2d_generic operator * (const T& rhs) const { return v2d_generic(this->x * rhs, this->y * rhs); } v2d_generic operator * (const v2d_generic& rhs) const { return v2d_generic(this->x * rhs.x, this->y * rhs.y); } v2d_generic operator / (const T& rhs) const { return v2d_generic(this->x / rhs, this->y / rhs); } v2d_generic operator / (const v2d_generic& rhs) const { return v2d_generic(this->x / rhs.x, this->y / rhs.y); } v2d_generic& operator += (const v2d_generic& rhs) { this->x += rhs.x; this->y += rhs.y; return *this; } v2d_generic& operator -= (const v2d_generic& rhs) { this->x -= rhs.x; this->y -= rhs.y; return *this; } v2d_generic& operator *= (const T& rhs) { this->x *= rhs; this->y *= rhs; return *this; } v2d_generic& operator /= (const T& rhs) { this->x /= rhs; this->y /= rhs; return *this; } v2d_generic& operator *= (const v2d_generic& rhs) { this->x *= rhs.x; this->y *= rhs.y; return *this; } v2d_generic& operator /= (const v2d_generic& rhs) { this->x /= rhs.x; this->y /= rhs.y; return *this; } v2d_generic operator + () const { return { +x, +y }; } v2d_generic operator - () const { return { -x, -y }; } bool operator == (const v2d_generic& rhs) const { return (this->x == rhs.x && this->y == rhs.y); } bool operator != (const v2d_generic& rhs) const { return (this->x != rhs.x || this->y != rhs.y); } const std::string str() const { return std::string("(") + std::to_string(this->x) + "," + std::to_string(this->y) + ")"; } friend std::ostream& operator << (std::ostream& os, const v2d_generic& rhs) { os << rhs.str(); return os; } operator v2d_generic<int32_t>() const { return { static_cast<int32_t>(this->x), static_cast<int32_t>(this->y) }; } operator v2d_generic<float>() const { return { static_cast<float>(this->x), static_cast<float>(this->y) }; } operator v2d_generic<double>() const { return { static_cast<double>(this->x), static_cast<double>(this->y) }; } }; // Note: joshinils has some good suggestions here, but they are complicated to implement at this moment, // however they will appear in a future version of PGE template<class T> inline v2d_generic<T> operator * (const float& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs * (float)rhs.x), (T)(lhs * (float)rhs.y)); } template<class T> inline v2d_generic<T> operator * (const double& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs * (double)rhs.x), (T)(lhs * (double)rhs.y)); } template<class T> inline v2d_generic<T> operator * (const int& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs * (int)rhs.x), (T)(lhs * (int)rhs.y)); } template<class T> inline v2d_generic<T> operator / (const float& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs / (float)rhs.x), (T)(lhs / (float)rhs.y)); } template<class T> inline v2d_generic<T> operator / (const double& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs / (double)rhs.x), (T)(lhs / (double)rhs.y)); } template<class T> inline v2d_generic<T> operator / (const int& lhs, const v2d_generic<T>& rhs) { return v2d_generic<T>((T)(lhs / (int)rhs.x), (T)(lhs / (int)rhs.y)); } // To stop dandistine crying... template<class T, class U> inline bool operator < (const v2d_generic<T>& lhs, const v2d_generic<U>& rhs) { return lhs.y < rhs.y || (lhs.y == rhs.y && lhs.x < rhs.x); } template<class T, class U> inline bool operator > (const v2d_generic<T>& lhs, const v2d_generic<U>& rhs) { return lhs.y > rhs.y || (lhs.y == rhs.y && lhs.x > rhs.x); } typedef v2d_generic<int32_t> vi2d; typedef v2d_generic<uint32_t> vu2d; typedef v2d_generic<float> vf2d; typedef v2d_generic<double> vd2d; #endif // O------------------------------------------------------------------------------O // | olc::ResourcePack - A virtual scrambled filesystem to pack your assets into | // O------------------------------------------------------------------------------O struct ResourceBuffer : public std::streambuf { ResourceBuffer(std::ifstream& ifs, uint32_t offset, uint32_t size); std::vector<char> vMemory; }; class ResourcePack : public std::streambuf { public: ResourcePack(); ~ResourcePack(); bool AddFile(const std::string& sFile); bool LoadPack(const std::string& sFile, const std::string& sKey); bool SavePack(const std::string& sFile, const std::string& sKey); ResourceBuffer GetFileBuffer(const std::string& sFile); bool Loaded(); private: struct sResourceFile { uint32_t nSize; uint32_t nOffset; }; std::map<std::string, sResourceFile> mapFiles; std::ifstream baseFile; std::vector<char> scramble(const std::vector<char>& data, const std::string& key); std::string makeposix(const std::string& path); }; class ImageLoader { public: ImageLoader() = default; virtual ~ImageLoader() = default; virtual olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) = 0; virtual olc::rcode SaveImageResource(olc::Sprite* spr, const std::string& sImageFile) = 0; }; // O------------------------------------------------------------------------------O // | olc::Sprite - An image represented by a 2D array of olc::Pixel | // O------------------------------------------------------------------------------O class Sprite { public: Sprite(); Sprite(const std::string& sImageFile, olc::ResourcePack* pack = nullptr); Sprite(int32_t w, int32_t h); Sprite(const olc::Sprite&) = delete; ~Sprite(); public: olc::rcode LoadFromFile(const std::string& sImageFile, olc::ResourcePack* pack = nullptr); olc::rcode LoadFromPGESprFile(const std::string& sImageFile, olc::ResourcePack* pack = nullptr); olc::rcode SaveToPGESprFile(const std::string& sImageFile); public: int32_t width = 0; int32_t height = 0; enum Mode { NORMAL, PERIODIC }; enum Flip { NONE = 0, HORIZ = 1, VERT = 2 }; public: void SetSampleMode(olc::Sprite::Mode mode = olc::Sprite::Mode::NORMAL); Pixel GetPixel(int32_t x, int32_t y) const; bool SetPixel(int32_t x, int32_t y, Pixel p); Pixel GetPixel(const olc::vi2d& a) const; bool SetPixel(const olc::vi2d& a, Pixel p); Pixel Sample(float x, float y) const; Pixel SampleBL(float u, float v) const; Pixel* GetData(); olc::Sprite* Duplicate(); olc::Sprite* Duplicate(const olc::vi2d& vPos, const olc::vi2d& vSize); std::vector<olc::Pixel> pColData; Mode modeSample = Mode::NORMAL; static std::unique_ptr<olc::ImageLoader> loader; }; // O------------------------------------------------------------------------------O // | olc::Decal - A GPU resident storage of an olc::Sprite | // O------------------------------------------------------------------------------O class Decal { public: Decal(olc::Sprite* spr, bool filter = false, bool clamp = true); Decal(const uint32_t nExistingTextureResource, olc::Sprite* spr); virtual ~Decal(); void Update(); void UpdateSprite(); public: // But dont touch int32_t id = -1; olc::Sprite* sprite = nullptr; olc::vf2d vUVScale = { 1.0f, 1.0f }; }; enum class DecalMode { NORMAL, ADDITIVE, MULTIPLICATIVE, STENCIL, ILLUMINATE, WIREFRAME, }; // O------------------------------------------------------------------------------O // | olc::Renderable - Convenience class to keep a sprite and decal together | // O------------------------------------------------------------------------------O class Renderable { public: Renderable() = default; olc::rcode Load(const std::string& sFile, ResourcePack* pack = nullptr, bool filter = false, bool clamp = true); void Create(uint32_t width, uint32_t height, bool filter = false, bool clamp = true); olc::Decal* Decal() const; olc::Sprite* Sprite() const; private: std::unique_ptr<olc::Sprite> pSprite = nullptr; std::unique_ptr<olc::Decal> pDecal = nullptr; }; // O------------------------------------------------------------------------------O // | Auxilliary components internal to engine | // O------------------------------------------------------------------------------O struct DecalInstance { olc::Decal* decal = nullptr; std::vector<olc::vf2d> pos; std::vector<olc::vf2d> uv; std::vector<float> w; std::vector<olc::Pixel> tint; olc::DecalMode mode = olc::DecalMode::NORMAL; uint32_t points = 0; }; struct LayerDesc { olc::vf2d vOffset = { 0, 0 }; olc::vf2d vScale = { 1, 1 }; bool bShow = false; bool bUpdate = false; olc::Sprite* pDrawTarget = nullptr; uint32_t nResID = 0; std::vector<DecalInstance> vecDecalInstance; olc::Pixel tint = olc::WHITE; std::function<void()> funcHook = nullptr; }; class Renderer { public: virtual ~Renderer() = default; virtual void PrepareDevice() = 0; virtual olc::rcode CreateDevice(std::vector<void*> params, bool bFullScreen, bool bVSYNC) = 0; virtual olc::rcode DestroyDevice() = 0; virtual void DisplayFrame() = 0; virtual void PrepareDrawing() = 0; virtual void SetDecalMode(const olc::DecalMode& mode) = 0; virtual void DrawLayerQuad(const olc::vf2d& offset, const olc::vf2d& scale, const olc::Pixel tint) = 0; virtual void DrawDecal(const olc::DecalInstance& decal) = 0; virtual uint32_t CreateTexture(const uint32_t width, const uint32_t height, const bool filtered = false, const bool clamp = true) = 0; virtual void UpdateTexture(uint32_t id, olc::Sprite* spr) = 0; virtual void ReadTexture(uint32_t id, olc::Sprite* spr) = 0; virtual uint32_t DeleteTexture(const uint32_t id) = 0; virtual void ApplyTexture(uint32_t id) = 0; virtual void UpdateViewport(const olc::vi2d& pos, const olc::vi2d& size) = 0; virtual void ClearBuffer(olc::Pixel p, bool bDepth) = 0; static olc::PixelGameEngine* ptrPGE; }; class Platform { public: virtual ~Platform() = default; virtual olc::rcode ApplicationStartUp() = 0; virtual olc::rcode ApplicationCleanUp() = 0; virtual olc::rcode ThreadStartUp() = 0; virtual olc::rcode ThreadCleanUp() = 0; virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) = 0; virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) = 0; virtual olc::rcode SetWindowTitle(const std::string& s) = 0; virtual olc::rcode StartSystemEventLoop() = 0; virtual olc::rcode HandleSystemEvent() = 0; static olc::PixelGameEngine* ptrPGE; }; class PGEX; // The Static Twins (plus one) static std::unique_ptr<Renderer> renderer; static std::unique_ptr<Platform> platform; static std::map<size_t, uint8_t> mapKeys; // O------------------------------------------------------------------------------O // | olc::PixelGameEngine - The main BASE class for your application | // O------------------------------------------------------------------------------O class PixelGameEngine { public: PixelGameEngine(); virtual ~PixelGameEngine(); public: olc::rcode Construct(int32_t screen_w, int32_t screen_h, int32_t pixel_w, int32_t pixel_h, bool full_screen = false, bool vsync = false, bool cohesion = false); olc::rcode Start(); public: // User Override Interfaces // Called once on application startup, use to load your resources virtual bool OnUserCreate(); // Called every frame, and provides you with a time per frame value virtual bool OnUserUpdate(float fElapsedTime); // Called once on application termination, so you can be one clean coder virtual bool OnUserDestroy(); public: // Hardware Interfaces // Returns true if window is currently in focus bool IsFocused() const; // Get the state of a specific keyboard button HWButton GetKey(Key k) const; // Get the state of a specific mouse button HWButton GetMouse(uint32_t b) const; // Get Mouse X coordinate in "pixel" space int32_t GetMouseX() const; // Get Mouse Y coordinate in "pixel" space int32_t GetMouseY() const; // Get Mouse Wheel Delta int32_t GetMouseWheel() const; // Get the mouse in window space const olc::vi2d& GetWindowMouse() const; // Gets the mouse as a vector to keep Tarriest happy const olc::vi2d& GetMousePos() const; public: // Utility // Returns the width of the screen in "pixels" int32_t ScreenWidth() const; // Returns the height of the screen in "pixels" int32_t ScreenHeight() const; // Returns the width of the currently selected drawing target in "pixels" int32_t GetDrawTargetWidth() const; // Returns the height of the currently selected drawing target in "pixels" int32_t GetDrawTargetHeight() const; // Returns the currently active draw target olc::Sprite* GetDrawTarget() const; // Resize the primary screen sprite void SetScreenSize(int w, int h); // Specify which Sprite should be the target of drawing functions, use nullptr // to specify the primary screen void SetDrawTarget(Sprite* target); // Gets the current Frames Per Second uint32_t GetFPS() const; // Gets last update of elapsed time float GetElapsedTime() const; // Gets Actual Window size const olc::vi2d& GetWindowSize() const; // Gets pixel scale const olc::vi2d& GetPixelSize() const; // Gets actual pixel scale const olc::vi2d& GetScreenPixelSize() const; public: // CONFIGURATION ROUTINES // Layer targeting functions void SetDrawTarget(uint8_t layer); void EnableLayer(uint8_t layer, bool b); void SetLayerOffset(uint8_t layer, const olc::vf2d& offset); void SetLayerOffset(uint8_t layer, float x, float y); void SetLayerScale(uint8_t layer, const olc::vf2d& scale); void SetLayerScale(uint8_t layer, float x, float y); void SetLayerTint(uint8_t layer, const olc::Pixel& tint); void SetLayerCustomRenderFunction(uint8_t layer, std::function<void()> f); std::vector<LayerDesc>& GetLayers(); uint32_t CreateLayer(); // Change the pixel mode for different optimisations // olc::Pixel::NORMAL = No transparency // olc::Pixel::MASK = Transparent if alpha is < 255 // olc::Pixel::ALPHA = Full transparency void SetPixelMode(Pixel::Mode m); Pixel::Mode GetPixelMode(); // Use a custom blend function void SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel& pSource, const olc::Pixel& pDest)> pixelMode); // Change the blend factor from between 0.0f to 1.0f; void SetPixelBlend(float fBlend); public: // DRAWING ROUTINES // Draws a single Pixel virtual bool Draw(int32_t x, int32_t y, Pixel p = olc::WHITE); bool Draw(const olc::vi2d& pos, Pixel p = olc::WHITE); // Draws a line from (x1,y1) to (x2,y2) void DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF); void DrawLine(const olc::vi2d& pos1, const olc::vi2d& pos2, Pixel p = olc::WHITE, uint32_t pattern = 0xFFFFFFFF); // Draws a circle located at (x,y) with radius void DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF); void DrawCircle(const olc::vi2d& pos, int32_t radius, Pixel p = olc::WHITE, uint8_t mask = 0xFF); // Fills a circle located at (x,y) with radius void FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p = olc::WHITE); void FillCircle(const olc::vi2d& pos, int32_t radius, Pixel p = olc::WHITE); // Draws a rectangle at (x,y) to (x+w,y+h) void DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE); void DrawRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p = olc::WHITE); // Fills a rectangle at (x,y) to (x+w,y+h) void FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p = olc::WHITE); void FillRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p = olc::WHITE); // Draws a triangle between points (x1,y1), (x2,y2) and (x3,y3) void DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE); void DrawTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p = olc::WHITE); // Flat fills a triangle between points (x1,y1), (x2,y2) and (x3,y3) void FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p = olc::WHITE); void FillTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p = olc::WHITE); // Draws an entire sprite at location (x,y) void DrawSprite(int32_t x, int32_t y, Sprite* sprite, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE); void DrawSprite(const olc::vi2d& pos, Sprite* sprite, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE); // Draws an area of a sprite at location (x,y), where the // selected area is (ox,oy) to (ox+w,oy+h) void DrawPartialSprite(int32_t x, int32_t y, Sprite* sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE); void DrawPartialSprite(const olc::vi2d& pos, Sprite* sprite, const olc::vi2d& sourcepos, const olc::vi2d& size, uint32_t scale = 1, uint8_t flip = olc::Sprite::NONE); // Draws a single line of text - traditional monospaced void DrawString(int32_t x, int32_t y, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1); void DrawString(const olc::vi2d& pos, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1); olc::vi2d GetTextSize(const std::string& s); // Draws a single line of text - non-monospaced void DrawStringProp(int32_t x, int32_t y, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1); void DrawStringProp(const olc::vi2d& pos, const std::string& sText, Pixel col = olc::WHITE, uint32_t scale = 1); olc::vi2d GetTextSizeProp(const std::string& s); // Decal Quad functions void SetDecalMode(const olc::DecalMode& mode); // Draws a whole decal, with optional scale and tinting void DrawDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE); // Draws a region of a decal, with optional scale and tinting void DrawPartialDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE); void DrawPartialDecal(const olc::vf2d& pos, const olc::vf2d& size, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE); // Draws fully user controlled 4 vertices, pos(pixels), uv(pixels), colours void DrawExplicitDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d* uv, const olc::Pixel* col, uint32_t elements = 4); // Draws a decal with 4 arbitrary points, warping the texture to look "correct" void DrawWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::Pixel& tint = olc::WHITE); void DrawWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::Pixel& tint = olc::WHITE); void DrawWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::Pixel& tint = olc::WHITE); // As above, but you can specify a region of a decal source sprite void DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE); void DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE); void DrawPartialWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint = olc::WHITE); // Draws a decal rotated to specified angle, wit point of rotation offset void DrawRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center = { 0.0f, 0.0f }, const olc::vf2d& scale = { 1.0f,1.0f }, const olc::Pixel& tint = olc::WHITE); void DrawPartialRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale = { 1.0f, 1.0f }, const olc::Pixel& tint = olc::WHITE); // Draws a multiline string as a decal, with tiniting and scaling void DrawStringDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col = olc::WHITE, const olc::vf2d& scale = { 1.0f, 1.0f }); void DrawStringPropDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col = olc::WHITE, const olc::vf2d& scale = { 1.0f, 1.0f }); // Draws a single shaded filled rectangle as a decal void FillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel col = olc::WHITE); // Draws a corner shaded rectangle as a decal void GradientFillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel colTL, const olc::Pixel colBL, const olc::Pixel colBR, const olc::Pixel colTR); // Draws an arbitrary convex textured polygon using GPU void DrawPolygonDecal(olc::Decal* decal, const std::vector<olc::vf2d>& pos, const std::vector<olc::vf2d>& uv, const olc::Pixel tint = olc::WHITE); // Clears entire draw target to Pixel void Clear(Pixel p); // Clears the rendering back buffer void ClearBuffer(Pixel p, bool bDepth = true); // Returns the font image olc::Sprite* GetFontSprite(); public: // Branding std::string sAppName; private: // Inner mysterious workings Sprite* pDrawTarget = nullptr; Pixel::Mode nPixelMode = Pixel::NORMAL; float fBlendFactor = 1.0f; olc::vi2d vScreenSize = { 256, 240 }; olc::vf2d vInvScreenSize = { 1.0f / 256.0f, 1.0f / 240.0f }; olc::vi2d vPixelSize = { 4, 4 }; olc::vi2d vScreenPixelSize = { 4, 4 }; olc::vi2d vMousePos = { 0, 0 }; int32_t nMouseWheelDelta = 0; olc::vi2d vMousePosCache = { 0, 0 }; olc::vi2d vMouseWindowPos = { 0, 0 }; int32_t nMouseWheelDeltaCache = 0; olc::vi2d vWindowSize = { 0, 0 }; olc::vi2d vViewPos = { 0, 0 }; olc::vi2d vViewSize = { 0,0 }; bool bFullScreen = false; olc::vf2d vPixel = { 1.0f, 1.0f }; bool bHasInputFocus = false; bool bHasMouseFocus = false; bool bEnableVSYNC = false; float fFrameTimer = 1.0f; float fLastElapsed = 0.0f; int nFrameCount = 0; Sprite* fontSprite = nullptr; Decal* fontDecal = nullptr; Sprite* pDefaultDrawTarget = nullptr; std::vector<LayerDesc> vLayers; uint8_t nTargetLayer = 0; uint32_t nLastFPS = 0; bool bPixelCohesion = false; DecalMode nDecalMode = DecalMode::NORMAL; std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> funcPixelMode; std::chrono::time_point<std::chrono::system_clock> m_tp1, m_tp2; std::vector<olc::vi2d> vFontSpacing; // State of keyboard bool pKeyNewState[256] = { 0 }; bool pKeyOldState[256] = { 0 }; HWButton pKeyboardState[256] = { 0 }; // State of mouse bool pMouseNewState[nMouseButtons] = { 0 }; bool pMouseOldState[nMouseButtons] = { 0 }; HWButton pMouseState[nMouseButtons] = { 0 }; // The main engine thread void EngineThread(); // If anything sets this flag to false, the engine // "should" shut down gracefully static std::atomic<bool> bAtomActive; public: // "Break In" Functions void olc_UpdateMouse(int32_t x, int32_t y); void olc_UpdateMouseWheel(int32_t delta); void olc_UpdateWindowSize(int32_t x, int32_t y); void olc_UpdateViewport(); void olc_ConstructFontSheet(); void olc_CoreUpdate(); void olc_PrepareEngine(); void olc_UpdateMouseState(int32_t button, bool state); void olc_UpdateKeyState(int32_t key, bool state); void olc_UpdateMouseFocus(bool state); void olc_UpdateKeyFocus(bool state); void olc_Terminate(); void olc_Reanimate(); bool olc_IsRunning(); // At the very end of this file, chooses which // components to compile virtual void olc_ConfigureSystem(); // NOTE: Items Here are to be deprecated, I have left them in for now // in case you are using them, but they will be removed. // olc::vf2d vSubPixelOffset = { 0.0f, 0.0f }; public: // PGEX Stuff friend class PGEX; void pgex_Register(olc::PGEX* pgex); private: std::vector<olc::PGEX*> vExtensions; }; // O------------------------------------------------------------------------------O // | PGE EXTENSION BASE CLASS - Permits access to PGE functions from extension | // O------------------------------------------------------------------------------O class PGEX { friend class olc::PixelGameEngine; public: PGEX(bool bHook = false); protected: virtual void OnBeforeUserCreate(); virtual void OnAfterUserCreate(); virtual void OnBeforeUserUpdate(float &fElapsedTime); virtual void OnAfterUserUpdate(float fElapsedTime); protected: static PixelGameEngine* pge; }; } #pragma endregion #endif // OLC_PGE_DEF // O------------------------------------------------------------------------------O // | START OF OLC_PGE_APPLICATION | // O------------------------------------------------------------------------------O #ifdef OLC_PGE_APPLICATION #undef OLC_PGE_APPLICATION // O------------------------------------------------------------------------------O // | olcPixelGameEngine INTERFACE IMPLEMENTATION (CORE) | // | Note: The core implementation is platform independent | // O------------------------------------------------------------------------------O #pragma region pge_implementation namespace olc { // O------------------------------------------------------------------------------O // | olc::Pixel IMPLEMENTATION | // O------------------------------------------------------------------------------O Pixel::Pixel() { r = 0; g = 0; b = 0; a = nDefaultAlpha; } Pixel::Pixel(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) { n = red | (green << 8) | (blue << 16) | (alpha << 24); } // Thanks jarekpelczar Pixel::Pixel(uint32_t p) { n = p; } bool Pixel::operator==(const Pixel& p) const { return n == p.n; } bool Pixel::operator!=(const Pixel& p) const { return n != p.n; } Pixel Pixel::operator * (const float i) const { float fR = std::min(255.0f, std::max(0.0f, float(r) * i)); float fG = std::min(255.0f, std::max(0.0f, float(g) * i)); float fB = std::min(255.0f, std::max(0.0f, float(b) * i)); return Pixel(uint8_t(fR), uint8_t(fG), uint8_t(fB), a); } Pixel Pixel::operator / (const float i) const { float fR = std::min(255.0f, std::max(0.0f, float(r) / i)); float fG = std::min(255.0f, std::max(0.0f, float(g) / i)); float fB = std::min(255.0f, std::max(0.0f, float(b) / i)); return Pixel(uint8_t(fR), uint8_t(fG), uint8_t(fB), a); } Pixel& Pixel::operator *=(const float i) { this->r = uint8_t(std::min(255.0f, std::max(0.0f, float(r) * i))); this->g = uint8_t(std::min(255.0f, std::max(0.0f, float(g) * i))); this->b = uint8_t(std::min(255.0f, std::max(0.0f, float(b) * i))); return *this; } Pixel& Pixel::operator /=(const float i) { this->r = uint8_t(std::min(255.0f, std::max(0.0f, float(r) / i))); this->g = uint8_t(std::min(255.0f, std::max(0.0f, float(g) / i))); this->b = uint8_t(std::min(255.0f, std::max(0.0f, float(b) / i))); return *this; } Pixel Pixel::operator + (const Pixel& p) const { uint8_t nR = uint8_t(std::min(255, std::max(0, int(r) + int(p.r)))); uint8_t nG = uint8_t(std::min(255, std::max(0, int(g) + int(p.g)))); uint8_t nB = uint8_t(std::min(255, std::max(0, int(b) + int(p.b)))); return Pixel(nR, nG, nB, a); } Pixel Pixel::operator - (const Pixel& p) const { uint8_t nR = uint8_t(std::min(255, std::max(0, int(r) - int(p.r)))); uint8_t nG = uint8_t(std::min(255, std::max(0, int(g) - int(p.g)))); uint8_t nB = uint8_t(std::min(255, std::max(0, int(b) - int(p.b)))); return Pixel(nR, nG, nB, a); } Pixel& Pixel::operator += (const Pixel& p) { this->r = uint8_t(std::min(255, std::max(0, int(r) + int(p.r)))); this->g = uint8_t(std::min(255, std::max(0, int(g) + int(p.g)))); this->b = uint8_t(std::min(255, std::max(0, int(b) + int(p.b)))); return *this; } Pixel& Pixel::operator -= (const Pixel& p) // Thanks Au Lit { this->r = uint8_t(std::min(255, std::max(0, int(r) - int(p.r)))); this->g = uint8_t(std::min(255, std::max(0, int(g) - int(p.g)))); this->b = uint8_t(std::min(255, std::max(0, int(b) - int(p.b)))); return *this; } Pixel Pixel::inv() const { uint8_t nR = uint8_t(std::min(255, std::max(0, 255 - int(r)))); uint8_t nG = uint8_t(std::min(255, std::max(0, 255 - int(g)))); uint8_t nB = uint8_t(std::min(255, std::max(0, 255 - int(b)))); return Pixel(nR, nG, nB, a); } Pixel PixelF(float red, float green, float blue, float alpha) { return Pixel(uint8_t(red * 255.0f), uint8_t(green * 255.0f), uint8_t(blue * 255.0f), uint8_t(alpha * 255.0f)); } Pixel PixelLerp(const olc::Pixel& p1, const olc::Pixel& p2, float t) { return (p2 * t) + p1 * (1.0f - t); } // O------------------------------------------------------------------------------O // | olc::Sprite IMPLEMENTATION | // O------------------------------------------------------------------------------O Sprite::Sprite() { width = 0; height = 0; } Sprite::Sprite(const std::string& sImageFile, olc::ResourcePack* pack) { LoadFromFile(sImageFile, pack); } Sprite::Sprite(int32_t w, int32_t h) { width = w; height = h; pColData.resize(width * height); pColData.resize(width * height, nDefaultPixel); } Sprite::~Sprite() { pColData.clear(); } // To Be Deprecated //olc::rcode Sprite::LoadFromPGESprFile(const std::string& sImageFile, olc::ResourcePack* pack) //{ // if (pColData) delete[] pColData; // auto ReadData = [&](std::istream& is) // { // is.read((char*)&width, sizeof(int32_t)); // is.read((char*)&height, sizeof(int32_t)); // pColData = new Pixel[width * height]; // is.read((char*)pColData, (size_t)width * (size_t)height * sizeof(uint32_t)); // }; // // These are essentially Memory Surfaces represented by olc::Sprite // // which load very fast, but are completely uncompressed // if (pack == nullptr) // { // std::ifstream ifs; // ifs.open(sImageFile, std::ifstream::binary); // if (ifs.is_open()) // { // ReadData(ifs); // return olc::OK; // } // else // return olc::FAIL; // } // else // { // ResourceBuffer rb = pack->GetFileBuffer(sImageFile); // std::istream is(&rb); // ReadData(is); // return olc::OK; // } // return olc::FAIL; //} //olc::rcode Sprite::SaveToPGESprFile(const std::string& sImageFile) //{ // if (pColData == nullptr) return olc::FAIL; // std::ofstream ofs; // ofs.open(sImageFile, std::ifstream::binary); // if (ofs.is_open()) // { // ofs.write((char*)&width, sizeof(int32_t)); // ofs.write((char*)&height, sizeof(int32_t)); // ofs.write((char*)pColData, std::streamsize(width) * std::streamsize(height) * sizeof(uint32_t)); // ofs.close(); // return olc::OK; // } // return olc::FAIL; //} void Sprite::SetSampleMode(olc::Sprite::Mode mode) { modeSample = mode; } Pixel Sprite::GetPixel(const olc::vi2d& a) const { return GetPixel(a.x, a.y); } bool Sprite::SetPixel(const olc::vi2d& a, Pixel p) { return SetPixel(a.x, a.y, p); } Pixel Sprite::GetPixel(int32_t x, int32_t y) const { if (modeSample == olc::Sprite::Mode::NORMAL) { if (x >= 0 && x < width && y >= 0 && y < height) return pColData[y * width + x]; else return Pixel(0, 0, 0, 0); } else { return pColData[abs(y % height) * width + abs(x % width)]; } } bool Sprite::SetPixel(int32_t x, int32_t y, Pixel p) { if (x >= 0 && x < width && y >= 0 && y < height) { pColData[y * width + x] = p; return true; } else return false; } Pixel Sprite::Sample(float x, float y) const { int32_t sx = std::min((int32_t)((x * (float)width)), width - 1); int32_t sy = std::min((int32_t)((y * (float)height)), height - 1); return GetPixel(sx, sy); } Pixel Sprite::SampleBL(float u, float v) const { u = u * width - 0.5f; v = v * height - 0.5f; int x = (int)floor(u); // cast to int rounds toward zero, not downward int y = (int)floor(v); // Thanks @joshinils float u_ratio = u - x; float v_ratio = v - y; float u_opposite = 1 - u_ratio; float v_opposite = 1 - v_ratio; olc::Pixel p1 = GetPixel(std::max(x, 0), std::max(y, 0)); olc::Pixel p2 = GetPixel(std::min(x + 1, (int)width - 1), std::max(y, 0)); olc::Pixel p3 = GetPixel(std::max(x, 0), std::min(y + 1, (int)height - 1)); olc::Pixel p4 = GetPixel(std::min(x + 1, (int)width - 1), std::min(y + 1, (int)height - 1)); return olc::Pixel( (uint8_t)((p1.r * u_opposite + p2.r * u_ratio) * v_opposite + (p3.r * u_opposite + p4.r * u_ratio) * v_ratio), (uint8_t)((p1.g * u_opposite + p2.g * u_ratio) * v_opposite + (p3.g * u_opposite + p4.g * u_ratio) * v_ratio), (uint8_t)((p1.b * u_opposite + p2.b * u_ratio) * v_opposite + (p3.b * u_opposite + p4.b * u_ratio) * v_ratio)); } Pixel* Sprite::GetData() { return pColData.data(); } olc::rcode Sprite::LoadFromFile(const std::string& sImageFile, olc::ResourcePack* pack) { UNUSED(pack); return loader->LoadImageResource(this, sImageFile, pack); } olc::Sprite* Sprite::Duplicate() { olc::Sprite* spr = new olc::Sprite(width, height); std::memcpy(spr->GetData(), GetData(), width * height * sizeof(olc::Pixel)); spr->modeSample = modeSample; return spr; } olc::Sprite* Sprite::Duplicate(const olc::vi2d& vPos, const olc::vi2d& vSize) { olc::Sprite* spr = new olc::Sprite(vSize.x, vSize.y); for (int y = 0; y < vSize.y; y++) for (int x = 0; x < vSize.x; x++) spr->SetPixel(x, y, GetPixel(vPos.x + x, vPos.y + y)); return spr; } // O------------------------------------------------------------------------------O // | olc::Decal IMPLEMENTATION | // O------------------------------------------------------------------------------O Decal::Decal(olc::Sprite* spr, bool filter, bool clamp) { id = -1; if (spr == nullptr) return; sprite = spr; id = renderer->CreateTexture(sprite->width, sprite->height, filter, clamp); Update(); } Decal::Decal(const uint32_t nExistingTextureResource, olc::Sprite* spr) { if (spr == nullptr) return; id = nExistingTextureResource; } void Decal::Update() { if (sprite == nullptr) return; vUVScale = { 1.0f / float(sprite->width), 1.0f / float(sprite->height) }; renderer->ApplyTexture(id); renderer->UpdateTexture(id, sprite); } void Decal::UpdateSprite() { if (sprite == nullptr) return; renderer->ApplyTexture(id); renderer->ReadTexture(id, sprite); } Decal::~Decal() { if (id != -1) { renderer->DeleteTexture(id); id = -1; } } void Renderable::Create(uint32_t width, uint32_t height, bool filter, bool clamp) { pSprite = std::make_unique<olc::Sprite>(width, height); pDecal = std::make_unique<olc::Decal>(pSprite.get(), filter, clamp); } olc::rcode Renderable::Load(const std::string& sFile, ResourcePack* pack, bool filter, bool clamp) { pSprite = std::make_unique<olc::Sprite>(); if (pSprite->LoadFromFile(sFile, pack) == olc::rcode::OK) { pDecal = std::make_unique<olc::Decal>(pSprite.get(), filter, clamp); return olc::rcode::OK; } else { pSprite.release(); pSprite = nullptr; return olc::rcode::NO_FILE; } } olc::Decal* Renderable::Decal() const { return pDecal.get(); } olc::Sprite* Renderable::Sprite() const { return pSprite.get(); } // O------------------------------------------------------------------------------O // | olc::ResourcePack IMPLEMENTATION | // O------------------------------------------------------------------------------O //============================================================= // Resource Packs - Allows you to store files in one large // scrambled file - Thanks MaGetzUb for debugging a null char in std::stringstream bug ResourceBuffer::ResourceBuffer(std::ifstream& ifs, uint32_t offset, uint32_t size) { vMemory.resize(size); ifs.seekg(offset); ifs.read(vMemory.data(), vMemory.size()); setg(vMemory.data(), vMemory.data(), vMemory.data() + size); } ResourcePack::ResourcePack() { } ResourcePack::~ResourcePack() { baseFile.close(); } bool ResourcePack::AddFile(const std::string& sFile) { const std::string file = makeposix(sFile); if (_gfs::exists(file)) { sResourceFile e; e.nSize = (uint32_t)_gfs::file_size(file); e.nOffset = 0; // Unknown at this stage mapFiles[file] = e; return true; } return false; } bool ResourcePack::LoadPack(const std::string& sFile, const std::string& sKey) { // Open the resource file baseFile.open(sFile, std::ifstream::binary); if (!baseFile.is_open()) return false; // 1) Read Scrambled index uint32_t nIndexSize = 0; baseFile.read((char*)&nIndexSize, sizeof(uint32_t)); std::vector<char> buffer(nIndexSize); for (uint32_t j = 0; j < nIndexSize; j++) buffer[j] = baseFile.get(); std::vector<char> decoded = scramble(buffer, sKey); size_t pos = 0; auto read = [&decoded, &pos](char* dst, size_t size) { memcpy((void*)dst, (const void*)(decoded.data() + pos), size); pos += size; }; auto get = [&read]() -> int { char c; read(&c, 1); return c; }; // 2) Read Map uint32_t nMapEntries = 0; read((char*)&nMapEntries, sizeof(uint32_t)); for (uint32_t i = 0; i < nMapEntries; i++) { uint32_t nFilePathSize = 0; read((char*)&nFilePathSize, sizeof(uint32_t)); std::string sFileName(nFilePathSize, ' '); for (uint32_t j = 0; j < nFilePathSize; j++) sFileName[j] = get(); sResourceFile e; read((char*)&e.nSize, sizeof(uint32_t)); read((char*)&e.nOffset, sizeof(uint32_t)); mapFiles[sFileName] = e; } // Don't close base file! we will provide a stream // pointer when the file is requested return true; } bool ResourcePack::SavePack(const std::string& sFile, const std::string& sKey) { // Create/Overwrite the resource file std::ofstream ofs(sFile, std::ofstream::binary); if (!ofs.is_open()) return false; // Iterate through map uint32_t nIndexSize = 0; // Unknown for now ofs.write((char*)&nIndexSize, sizeof(uint32_t)); uint32_t nMapSize = uint32_t(mapFiles.size()); ofs.write((char*)&nMapSize, sizeof(uint32_t)); for (auto& e : mapFiles) { // Write the path of the file size_t nPathSize = e.first.size(); ofs.write((char*)&nPathSize, sizeof(uint32_t)); ofs.write(e.first.c_str(), nPathSize); // Write the file entry properties ofs.write((char*)&e.second.nSize, sizeof(uint32_t)); ofs.write((char*)&e.second.nOffset, sizeof(uint32_t)); } // 2) Write the individual Data std::streampos offset = ofs.tellp(); nIndexSize = (uint32_t)offset; for (auto& e : mapFiles) { // Store beginning of file offset within resource pack file e.second.nOffset = (uint32_t)offset; // Load the file to be added std::vector<uint8_t> vBuffer(e.second.nSize); std::ifstream i(e.first, std::ifstream::binary); i.read((char*)vBuffer.data(), e.second.nSize); i.close(); // Write the loaded file into resource pack file ofs.write((char*)vBuffer.data(), e.second.nSize); offset += e.second.nSize; } // 3) Scramble Index std::vector<char> stream; auto write = [&stream](const char* data, size_t size) { size_t sizeNow = stream.size(); stream.resize(sizeNow + size); memcpy(stream.data() + sizeNow, data, size); }; // Iterate through map write((char*)&nMapSize, sizeof(uint32_t)); for (auto& e : mapFiles) { // Write the path of the file size_t nPathSize = e.first.size(); write((char*)&nPathSize, sizeof(uint32_t)); write(e.first.c_str(), nPathSize); // Write the file entry properties write((char*)&e.second.nSize, sizeof(uint32_t)); write((char*)&e.second.nOffset, sizeof(uint32_t)); } std::vector<char> sIndexString = scramble(stream, sKey); uint32_t nIndexStringLen = uint32_t(sIndexString.size()); // 4) Rewrite Map (it has been updated with offsets now) // at start of file ofs.seekp(0, std::ios::beg); ofs.write((char*)&nIndexStringLen, sizeof(uint32_t)); ofs.write(sIndexString.data(), nIndexStringLen); ofs.close(); return true; } ResourceBuffer ResourcePack::GetFileBuffer(const std::string& sFile) { return ResourceBuffer(baseFile, mapFiles[sFile].nOffset, mapFiles[sFile].nSize); } bool ResourcePack::Loaded() { return baseFile.is_open(); } std::vector<char> ResourcePack::scramble(const std::vector<char>& data, const std::string& key) { if (key.empty()) return data; std::vector<char> o; size_t c = 0; for (auto s : data) o.push_back(s ^ key[(c++) % key.size()]); return o; }; std::string ResourcePack::makeposix(const std::string& path) { std::string o; for (auto s : path) o += std::string(1, s == '\\' ? '/' : s); return o; }; // O------------------------------------------------------------------------------O // | olc::PixelGameEngine IMPLEMENTATION | // O------------------------------------------------------------------------------O PixelGameEngine::PixelGameEngine() { sAppName = "Undefined"; olc::PGEX::pge = this; // Bring in relevant Platform & Rendering systems depending // on compiler parameters olc_ConfigureSystem(); } PixelGameEngine::~PixelGameEngine() {} olc::rcode PixelGameEngine::Construct(int32_t screen_w, int32_t screen_h, int32_t pixel_w, int32_t pixel_h, bool full_screen, bool vsync, bool cohesion) { bPixelCohesion = cohesion; vScreenSize = { screen_w, screen_h }; vInvScreenSize = { 1.0f / float(screen_w), 1.0f / float(screen_h) }; vPixelSize = { pixel_w, pixel_h }; vWindowSize = vScreenSize * vPixelSize; bFullScreen = full_screen; bEnableVSYNC = vsync; vPixel = 2.0f / vScreenSize; if (vPixelSize.x <= 0 || vPixelSize.y <= 0 || vScreenSize.x <= 0 || vScreenSize.y <= 0) return olc::FAIL; return olc::OK; } void PixelGameEngine::SetScreenSize(int w, int h) { vScreenSize = { w, h }; vInvScreenSize = { 1.0f / float(w), 1.0f / float(h) }; for (auto& layer : vLayers) { delete layer.pDrawTarget; // Erase existing layer sprites layer.pDrawTarget = new Sprite(vScreenSize.x, vScreenSize.y); layer.bUpdate = true; } SetDrawTarget(nullptr); renderer->ClearBuffer(olc::BLACK, true); renderer->DisplayFrame(); renderer->ClearBuffer(olc::BLACK, true); renderer->UpdateViewport(vViewPos, vViewSize); } #if !defined(PGE_USE_CUSTOM_START) olc::rcode PixelGameEngine::Start() { if (platform->ApplicationStartUp() != olc::OK) return olc::FAIL; // Construct the window if (platform->CreateWindowPane({ 30,30 }, vWindowSize, bFullScreen) != olc::OK) return olc::FAIL; olc_UpdateWindowSize(vWindowSize.x, vWindowSize.y); // Start the thread bAtomActive = true; std::thread t = std::thread(&PixelGameEngine::EngineThread, this); // Some implementations may form an event loop here platform->StartSystemEventLoop(); // Wait for thread to be exited t.join(); if (platform->ApplicationCleanUp() != olc::OK) return olc::FAIL; return olc::OK; } #endif void PixelGameEngine::SetDrawTarget(Sprite* target) { if (target) { pDrawTarget = target; } else { nTargetLayer = 0; pDrawTarget = vLayers[0].pDrawTarget; } } void PixelGameEngine::SetDrawTarget(uint8_t layer) { if (layer < vLayers.size()) { pDrawTarget = vLayers[layer].pDrawTarget; vLayers[layer].bUpdate = true; nTargetLayer = layer; } } void PixelGameEngine::EnableLayer(uint8_t layer, bool b) { if (layer < vLayers.size()) vLayers[layer].bShow = b; } void PixelGameEngine::SetLayerOffset(uint8_t layer, const olc::vf2d& offset) { SetLayerOffset(layer, offset.x, offset.y); } void PixelGameEngine::SetLayerOffset(uint8_t layer, float x, float y) { if (layer < vLayers.size()) vLayers[layer].vOffset = { x, y }; } void PixelGameEngine::SetLayerScale(uint8_t layer, const olc::vf2d& scale) { SetLayerScale(layer, scale.x, scale.y); } void PixelGameEngine::SetLayerScale(uint8_t layer, float x, float y) { if (layer < vLayers.size()) vLayers[layer].vScale = { x, y }; } void PixelGameEngine::SetLayerTint(uint8_t layer, const olc::Pixel& tint) { if (layer < vLayers.size()) vLayers[layer].tint = tint; } void PixelGameEngine::SetLayerCustomRenderFunction(uint8_t layer, std::function<void()> f) { if (layer < vLayers.size()) vLayers[layer].funcHook = f; } std::vector<LayerDesc>& PixelGameEngine::GetLayers() { return vLayers; } uint32_t PixelGameEngine::CreateLayer() { LayerDesc ld; ld.pDrawTarget = new olc::Sprite(vScreenSize.x, vScreenSize.y); ld.nResID = renderer->CreateTexture(vScreenSize.x, vScreenSize.y); renderer->UpdateTexture(ld.nResID, ld.pDrawTarget); vLayers.push_back(ld); return uint32_t(vLayers.size()) - 1; } Sprite* PixelGameEngine::GetDrawTarget() const { return pDrawTarget; } int32_t PixelGameEngine::GetDrawTargetWidth() const { if (pDrawTarget) return pDrawTarget->width; else return 0; } int32_t PixelGameEngine::GetDrawTargetHeight() const { if (pDrawTarget) return pDrawTarget->height; else return 0; } uint32_t PixelGameEngine::GetFPS() const { return nLastFPS; } bool PixelGameEngine::IsFocused() const { return bHasInputFocus; } HWButton PixelGameEngine::GetKey(Key k) const { return pKeyboardState[k]; } HWButton PixelGameEngine::GetMouse(uint32_t b) const { return pMouseState[b]; } int32_t PixelGameEngine::GetMouseX() const { return vMousePos.x; } int32_t PixelGameEngine::GetMouseY() const { return vMousePos.y; } const olc::vi2d& PixelGameEngine::GetMousePos() const { return vMousePos; } int32_t PixelGameEngine::GetMouseWheel() const { return nMouseWheelDelta; } int32_t PixelGameEngine::ScreenWidth() const { return vScreenSize.x; } int32_t PixelGameEngine::ScreenHeight() const { return vScreenSize.y; } float PixelGameEngine::GetElapsedTime() const { return fLastElapsed; } const olc::vi2d& PixelGameEngine::GetWindowSize() const { return vWindowSize; } const olc::vi2d& PixelGameEngine::GetPixelSize() const { return vPixelSize; } const olc::vi2d& PixelGameEngine::GetScreenPixelSize() const { return vScreenPixelSize; } const olc::vi2d& PixelGameEngine::GetWindowMouse() const { return vMouseWindowPos; } bool PixelGameEngine::Draw(const olc::vi2d& pos, Pixel p) { return Draw(pos.x, pos.y, p); } // This is it, the critical function that plots a pixel bool PixelGameEngine::Draw(int32_t x, int32_t y, Pixel p) { if (!pDrawTarget) return false; if (nPixelMode == Pixel::NORMAL) { return pDrawTarget->SetPixel(x, y, p); } if (nPixelMode == Pixel::MASK) { if (p.a == 255) return pDrawTarget->SetPixel(x, y, p); } if (nPixelMode == Pixel::ALPHA) { Pixel d = pDrawTarget->GetPixel(x, y); float a = (float)(p.a / 255.0f) * fBlendFactor; float c = 1.0f - a; float r = a * (float)p.r + c * (float)d.r; float g = a * (float)p.g + c * (float)d.g; float b = a * (float)p.b + c * (float)d.b; return pDrawTarget->SetPixel(x, y, Pixel((uint8_t)r, (uint8_t)g, (uint8_t)b/*, (uint8_t)(p.a * fBlendFactor)*/)); } if (nPixelMode == Pixel::CUSTOM) { return pDrawTarget->SetPixel(x, y, funcPixelMode(x, y, p, pDrawTarget->GetPixel(x, y))); } return false; } void PixelGameEngine::DrawLine(const olc::vi2d& pos1, const olc::vi2d& pos2, Pixel p, uint32_t pattern) { DrawLine(pos1.x, pos1.y, pos2.x, pos2.y, p, pattern); } void PixelGameEngine::DrawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2, Pixel p, uint32_t pattern) { int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i; dx = x2 - x1; dy = y2 - y1; auto rol = [&](void) { pattern = (pattern << 1) | (pattern >> 31); return pattern & 1; }; // straight lines idea by gurkanctn if (dx == 0) // Line is vertical { if (y2 < y1) std::swap(y1, y2); for (y = y1; y <= y2; y++) if (rol()) Draw(x1, y, p); return; } if (dy == 0) // Line is horizontal { if (x2 < x1) std::swap(x1, x2); for (x = x1; x <= x2; x++) if (rol()) Draw(x, y1, p); return; } // Line is Funk-aye dx1 = abs(dx); dy1 = abs(dy); px = 2 * dy1 - dx1; py = 2 * dx1 - dy1; if (dy1 <= dx1) { if (dx >= 0) { x = x1; y = y1; xe = x2; } else { x = x2; y = y2; xe = x1; } if (rol()) Draw(x, y, p); for (i = 0; x < xe; i++) { x = x + 1; if (px < 0) px = px + 2 * dy1; else { if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) y = y + 1; else y = y - 1; px = px + 2 * (dy1 - dx1); } if (rol()) Draw(x, y, p); } } else { if (dy >= 0) { x = x1; y = y1; ye = y2; } else { x = x2; y = y2; ye = y1; } if (rol()) Draw(x, y, p); for (i = 0; y < ye; i++) { y = y + 1; if (py <= 0) py = py + 2 * dx1; else { if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) x = x + 1; else x = x - 1; py = py + 2 * (dx1 - dy1); } if (rol()) Draw(x, y, p); } } } void PixelGameEngine::DrawCircle(const olc::vi2d& pos, int32_t radius, Pixel p, uint8_t mask) { DrawCircle(pos.x, pos.y, radius, p, mask); } void PixelGameEngine::DrawCircle(int32_t x, int32_t y, int32_t radius, Pixel p, uint8_t mask) { // Thanks to IanM-Matrix1 #PR121 if (radius < 0 || x < -radius || y < -radius || x - GetDrawTargetWidth() > radius || y - GetDrawTargetHeight() > radius) return; if (radius > 0) { int x0 = 0; int y0 = radius; int d = 3 - 2 * radius; while (y0 >= x0) // only formulate 1/8 of circle { // Draw even octants if (mask & 0x01) Draw(x + x0, y - y0, p);// Q6 - upper right right if (mask & 0x04) Draw(x + y0, y + x0, p);// Q4 - lower lower right if (mask & 0x10) Draw(x - x0, y + y0, p);// Q2 - lower left left if (mask & 0x40) Draw(x - y0, y - x0, p);// Q0 - upper upper left if (x0 != 0 && x0 != y0) { if (mask & 0x02) Draw(x + y0, y - x0, p);// Q7 - upper upper right if (mask & 0x08) Draw(x + x0, y + y0, p);// Q5 - lower right right if (mask & 0x20) Draw(x - y0, y + x0, p);// Q3 - lower lower left if (mask & 0x80) Draw(x - x0, y - y0, p);// Q1 - upper left left } if (d < 0) d += 4 * x0++ + 6; else d += 4 * (x0++ - y0--) + 10; } } else Draw(x, y, p); } void PixelGameEngine::FillCircle(const olc::vi2d& pos, int32_t radius, Pixel p) { FillCircle(pos.x, pos.y, radius, p); } void PixelGameEngine::FillCircle(int32_t x, int32_t y, int32_t radius, Pixel p) { // Thanks to IanM-Matrix1 #PR121 if (radius < 0 || x < -radius || y < -radius || x - GetDrawTargetWidth() > radius || y - GetDrawTargetHeight() > radius) return; if (radius > 0) { int x0 = 0; int y0 = radius; int d = 3 - 2 * radius; auto drawline = [&](int sx, int ex, int y) { for (int x = sx; x <= ex; x++) Draw(x, y, p); }; while (y0 >= x0) { drawline(x - y0, x + y0, y - x0); if (x0 > 0) drawline(x - y0, x + y0, y + x0); if (d < 0) d += 4 * x0++ + 6; else { if (x0 != y0) { drawline(x - x0, x + x0, y - y0); drawline(x - x0, x + x0, y + y0); } d += 4 * (x0++ - y0--) + 10; } } } else Draw(x, y, p); } void PixelGameEngine::DrawRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p) { DrawRect(pos.x, pos.y, size.x, size.y, p); } void PixelGameEngine::DrawRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p) { DrawLine(x, y, x + w, y, p); DrawLine(x + w, y, x + w, y + h, p); DrawLine(x + w, y + h, x, y + h, p); DrawLine(x, y + h, x, y, p); } void PixelGameEngine::Clear(Pixel p) { int pixels = GetDrawTargetWidth() * GetDrawTargetHeight(); Pixel* m = GetDrawTarget()->GetData(); for (int i = 0; i < pixels; i++) m[i] = p; } void PixelGameEngine::ClearBuffer(Pixel p, bool bDepth) { renderer->ClearBuffer(p, bDepth); } olc::Sprite* PixelGameEngine::GetFontSprite() { return fontSprite; } void PixelGameEngine::FillRect(const olc::vi2d& pos, const olc::vi2d& size, Pixel p) { FillRect(pos.x, pos.y, size.x, size.y, p); } void PixelGameEngine::FillRect(int32_t x, int32_t y, int32_t w, int32_t h, Pixel p) { int32_t x2 = x + w; int32_t y2 = y + h; if (x < 0) x = 0; if (x >= (int32_t)GetDrawTargetWidth()) x = (int32_t)GetDrawTargetWidth(); if (y < 0) y = 0; if (y >= (int32_t)GetDrawTargetHeight()) y = (int32_t)GetDrawTargetHeight(); if (x2 < 0) x2 = 0; if (x2 >= (int32_t)GetDrawTargetWidth()) x2 = (int32_t)GetDrawTargetWidth(); if (y2 < 0) y2 = 0; if (y2 >= (int32_t)GetDrawTargetHeight()) y2 = (int32_t)GetDrawTargetHeight(); for (int i = x; i < x2; i++) for (int j = y; j < y2; j++) Draw(i, j, p); } void PixelGameEngine::DrawTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p) { DrawTriangle(pos1.x, pos1.y, pos2.x, pos2.y, pos3.x, pos3.y, p); } void PixelGameEngine::DrawTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p) { DrawLine(x1, y1, x2, y2, p); DrawLine(x2, y2, x3, y3, p); DrawLine(x3, y3, x1, y1, p); } void PixelGameEngine::FillTriangle(const olc::vi2d& pos1, const olc::vi2d& pos2, const olc::vi2d& pos3, Pixel p) { FillTriangle(pos1.x, pos1.y, pos2.x, pos2.y, pos3.x, pos3.y, p); } // https://www.avrfreaks.net/sites/default/files/triangles.c void PixelGameEngine::FillTriangle(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x3, int32_t y3, Pixel p) { auto drawline = [&](int sx, int ex, int ny) { for (int i = sx; i <= ex; i++) Draw(i, ny, p); }; int t1x, t2x, y, minx, maxx, t1xp, t2xp; bool changed1 = false; bool changed2 = false; int signx1, signx2, dx1, dy1, dx2, dy2; int e1, e2; // Sort vertices if (y1 > y2) { std::swap(y1, y2); std::swap(x1, x2); } if (y1 > y3) { std::swap(y1, y3); std::swap(x1, x3); } if (y2 > y3) { std::swap(y2, y3); std::swap(x2, x3); } t1x = t2x = x1; y = y1; // Starting points dx1 = (int)(x2 - x1); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; } else signx1 = 1; dy1 = (int)(y2 - y1); dx2 = (int)(x3 - x1); if (dx2 < 0) { dx2 = -dx2; signx2 = -1; } else signx2 = 1; dy2 = (int)(y3 - y1); if (dy1 > dx1) { std::swap(dx1, dy1); changed1 = true; } if (dy2 > dx2) { std::swap(dy2, dx2); changed2 = true; } e2 = (int)(dx2 >> 1); // Flat top, just process the second half if (y1 == y2) goto next; e1 = (int)(dx1 >> 1); for (int i = 0; i < dx1;) { t1xp = 0; t2xp = 0; if (t1x < t2x) { minx = t1x; maxx = t2x; } else { minx = t2x; maxx = t1x; } // process first line until y value is about to change while (i < dx1) { i++; e1 += dy1; while (e1 >= dx1) { e1 -= dx1; if (changed1) t1xp = signx1;//t1x += signx1; else goto next1; } if (changed1) break; else t1x += signx1; } // Move line next1: // process second line until y value is about to change while (1) { e2 += dy2; while (e2 >= dx2) { e2 -= dx2; if (changed2) t2xp = signx2;//t2x += signx2; else goto next2; } if (changed2) break; else t2x += signx2; } next2: if (minx > t1x) minx = t1x; if (minx > t2x) minx = t2x; if (maxx < t1x) maxx = t1x; if (maxx < t2x) maxx = t2x; drawline(minx, maxx, y); // Draw line from min to max points found on the y // Now increase y if (!changed1) t1x += signx1; t1x += t1xp; if (!changed2) t2x += signx2; t2x += t2xp; y += 1; if (y == y2) break; } next: // Second half dx1 = (int)(x3 - x2); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; } else signx1 = 1; dy1 = (int)(y3 - y2); t1x = x2; if (dy1 > dx1) { // swap values std::swap(dy1, dx1); changed1 = true; } else changed1 = false; e1 = (int)(dx1 >> 1); for (int i = 0; i <= dx1; i++) { t1xp = 0; t2xp = 0; if (t1x < t2x) { minx = t1x; maxx = t2x; } else { minx = t2x; maxx = t1x; } // process first line until y value is about to change while (i < dx1) { e1 += dy1; while (e1 >= dx1) { e1 -= dx1; if (changed1) { t1xp = signx1; break; }//t1x += signx1; else goto next3; } if (changed1) break; else t1x += signx1; if (i < dx1) i++; } next3: // process second line until y value is about to change while (t2x != x3) { e2 += dy2; while (e2 >= dx2) { e2 -= dx2; if (changed2) t2xp = signx2; else goto next4; } if (changed2) break; else t2x += signx2; } next4: if (minx > t1x) minx = t1x; if (minx > t2x) minx = t2x; if (maxx < t1x) maxx = t1x; if (maxx < t2x) maxx = t2x; drawline(minx, maxx, y); if (!changed1) t1x += signx1; t1x += t1xp; if (!changed2) t2x += signx2; t2x += t2xp; y += 1; if (y > y3) return; } } void PixelGameEngine::DrawSprite(const olc::vi2d& pos, Sprite* sprite, uint32_t scale, uint8_t flip) { DrawSprite(pos.x, pos.y, sprite, scale, flip); } void PixelGameEngine::DrawSprite(int32_t x, int32_t y, Sprite* sprite, uint32_t scale, uint8_t flip) { if (sprite == nullptr) return; int32_t fxs = 0, fxm = 1, fx = 0; int32_t fys = 0, fym = 1, fy = 0; if (flip & olc::Sprite::Flip::HORIZ) { fxs = sprite->width - 1; fxm = -1; } if (flip & olc::Sprite::Flip::VERT) { fys = sprite->height - 1; fym = -1; } if (scale > 1) { fx = fxs; for (int32_t i = 0; i < sprite->width; i++, fx += fxm) { fy = fys; for (int32_t j = 0; j < sprite->height; j++, fy += fym) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + (i * scale) + is, y + (j * scale) + js, sprite->GetPixel(fx, fy)); } } else { fx = fxs; for (int32_t i = 0; i < sprite->width; i++, fx += fxm) { fy = fys; for (int32_t j = 0; j < sprite->height; j++, fy += fym) Draw(x + i, y + j, sprite->GetPixel(fx, fy)); } } } void PixelGameEngine::DrawPartialSprite(const olc::vi2d& pos, Sprite* sprite, const olc::vi2d& sourcepos, const olc::vi2d& size, uint32_t scale, uint8_t flip) { DrawPartialSprite(pos.x, pos.y, sprite, sourcepos.x, sourcepos.y, size.x, size.y, scale, flip); } void PixelGameEngine::DrawPartialSprite(int32_t x, int32_t y, Sprite* sprite, int32_t ox, int32_t oy, int32_t w, int32_t h, uint32_t scale, uint8_t flip) { if (sprite == nullptr) return; int32_t fxs = 0, fxm = 1, fx = 0; int32_t fys = 0, fym = 1, fy = 0; if (flip & olc::Sprite::Flip::HORIZ) { fxs = w - 1; fxm = -1; } if (flip & olc::Sprite::Flip::VERT) { fys = h - 1; fym = -1; } if (scale > 1) { fx = fxs; for (int32_t i = 0; i < w; i++, fx += fxm) { fy = fys; for (int32_t j = 0; j < h; j++, fy += fym) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + (i * scale) + is, y + (j * scale) + js, sprite->GetPixel(fx + ox, fy + oy)); } } else { fx = fxs; for (int32_t i = 0; i < w; i++, fx += fxm) { fy = fys; for (int32_t j = 0; j < h; j++, fy += fym) Draw(x + i, y + j, sprite->GetPixel(fx + ox, fy + oy)); } } } void PixelGameEngine::SetDecalMode(const olc::DecalMode& mode) { nDecalMode = mode; } void PixelGameEngine::DrawPartialDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale, const olc::Pixel& tint) { olc::vf2d vScreenSpacePos = { (std::floor(pos.x) * vInvScreenSize.x) * 2.0f - 1.0f, ((std::floor(pos.y) * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; olc::vf2d vScreenSpaceDim = { vScreenSpacePos.x + (2.0f * source_size.x * vInvScreenSize.x) * scale.x, vScreenSpacePos.y - (2.0f * source_size.y * vInvScreenSize.y) * scale.y }; DecalInstance di; di.points = 4; di.decal = decal; di.tint = { tint, tint, tint, tint }; di.pos = { { vScreenSpacePos.x, vScreenSpacePos.y }, { vScreenSpacePos.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpacePos.y } }; olc::vf2d uvtl = source_pos * decal->vUVScale; olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale); di.uv = { { uvtl.x, uvtl.y }, { uvtl.x, uvbr.y }, { uvbr.x, uvbr.y }, { uvbr.x, uvtl.y } }; di.w = { 1,1,1,1 }; di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawPartialDecal(const olc::vf2d& pos, const olc::vf2d& size, olc::Decal* decal, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint) { olc::vf2d vScreenSpacePos = { (std::floor(pos.x) * vInvScreenSize.x) * 2.0f - 1.0f, ((std::floor(pos.y) * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; olc::vf2d vScreenSpaceDim = { vScreenSpacePos.x + (2.0f * size.x * vInvScreenSize.x), vScreenSpacePos.y - (2.0f * size.y * vInvScreenSize.y) }; DecalInstance di; di.points = 4; di.decal = decal; di.tint = { tint, tint, tint, tint }; di.pos = { { vScreenSpacePos.x, vScreenSpacePos.y }, { vScreenSpacePos.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpacePos.y } }; olc::vf2d uvtl = (source_pos) * decal->vUVScale; olc::vf2d uvbr = uvtl + ((source_size) * decal->vUVScale); di.uv = { { uvtl.x, uvtl.y }, { uvtl.x, uvbr.y }, { uvbr.x, uvbr.y }, { uvbr.x, uvtl.y } }; di.w = { 1,1,1,1 }; di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawDecal(const olc::vf2d& pos, olc::Decal* decal, const olc::vf2d& scale, const olc::Pixel& tint) { olc::vf2d vScreenSpacePos = { (std::floor(pos.x) * vInvScreenSize.x) * 2.0f - 1.0f, ((std::floor(pos.y) * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; olc::vf2d vScreenSpaceDim = { vScreenSpacePos.x + (2.0f * (float(decal->sprite->width) * vInvScreenSize.x)) * scale.x, vScreenSpacePos.y - (2.0f * (float(decal->sprite->height) * vInvScreenSize.y)) * scale.y }; DecalInstance di; di.decal = decal; di.points = 4; di.tint = { tint, tint, tint, tint }; di.pos = { { vScreenSpacePos.x, vScreenSpacePos.y }, { vScreenSpacePos.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpaceDim.y }, { vScreenSpaceDim.x, vScreenSpacePos.y } }; di.uv = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} }; di.w = { 1, 1, 1, 1 }; di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawExplicitDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d* uv, const olc::Pixel* col, uint32_t elements) { DecalInstance di; di.decal = decal; di.pos.resize(elements); di.uv.resize(elements); di.w.resize(elements); di.tint.resize(elements); di.points = elements; for (uint32_t i = 0; i < elements; i++) { di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; di.uv[i] = uv[i]; di.tint[i] = col[i]; di.w[i] = 1.0f; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawPolygonDecal(olc::Decal* decal, const std::vector<olc::vf2d>& pos, const std::vector<olc::vf2d>& uv, const olc::Pixel tint) { DecalInstance di; di.decal = decal; di.points = uint32_t(pos.size()); di.pos.resize(di.points); di.uv.resize(di.points); di.w.resize(di.points); di.tint.resize(di.points); for (uint32_t i = 0; i < di.points; i++) { di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; di.uv[i] = uv[i]; di.tint[i] = tint; di.w[i] = 1.0f; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::FillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel col) { std::array<olc::vf2d, 4> points = { { {pos}, {pos.x, pos.y + size.y}, {pos + size}, {pos.x + size.x, pos.y} } }; std::array<olc::vf2d, 4> uvs = { {{0,0},{0,0},{0,0},{0,0}} }; std::array<olc::Pixel, 4> cols = { {col, col, col, col} }; DrawExplicitDecal(nullptr, points.data(), uvs.data(), cols.data(), 4); } void PixelGameEngine::GradientFillRectDecal(const olc::vf2d& pos, const olc::vf2d& size, const olc::Pixel colTL, const olc::Pixel colBL, const olc::Pixel colBR, const olc::Pixel colTR) { std::array<olc::vf2d, 4> points = { { {pos}, {pos.x, pos.y + size.y}, {pos + size}, {pos.x + size.x, pos.y} } }; std::array<olc::vf2d, 4> uvs = { {{0,0},{0,0},{0,0},{0,0}} }; std::array<olc::Pixel, 4> cols = { {colTL, colBL, colBR, colTR} }; DrawExplicitDecal(nullptr, points.data(), uvs.data(), cols.data(), 4); } void PixelGameEngine::DrawRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& scale, const olc::Pixel& tint) { DecalInstance di; di.decal = decal; di.pos.resize(4); di.uv = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} }; di.w = { 1, 1, 1, 1 }; di.tint = { tint, tint, tint, tint }; di.points = 4; di.pos[0] = (olc::vf2d(0.0f, 0.0f) - center) * scale; di.pos[1] = (olc::vf2d(0.0f, float(decal->sprite->height)) - center) * scale; di.pos[2] = (olc::vf2d(float(decal->sprite->width), float(decal->sprite->height)) - center) * scale; di.pos[3] = (olc::vf2d(float(decal->sprite->width), 0.0f) - center) * scale; float c = cos(fAngle), s = sin(fAngle); for (int i = 0; i < 4; i++) { di.pos[i] = pos + olc::vf2d(di.pos[i].x * c - di.pos[i].y * s, di.pos[i].x * s + di.pos[i].y * c); di.pos[i] = di.pos[i] * vInvScreenSize * 2.0f - olc::vf2d(1.0f, 1.0f); di.pos[i].y *= -1.0f; di.w[i] = 1; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawPartialRotatedDecal(const olc::vf2d& pos, olc::Decal* decal, const float fAngle, const olc::vf2d& center, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::vf2d& scale, const olc::Pixel& tint) { DecalInstance di; di.decal = decal; di.points = 4; di.tint = { tint, tint, tint, tint }; di.w = { 1, 1, 1, 1 }; di.pos.resize(4); di.pos[0] = (olc::vf2d(0.0f, 0.0f) - center) * scale; di.pos[1] = (olc::vf2d(0.0f, source_size.y) - center) * scale; di.pos[2] = (olc::vf2d(source_size.x, source_size.y) - center) * scale; di.pos[3] = (olc::vf2d(source_size.x, 0.0f) - center) * scale; float c = cos(fAngle), s = sin(fAngle); for (int i = 0; i < 4; i++) { di.pos[i] = pos + olc::vf2d(di.pos[i].x * c - di.pos[i].y * s, di.pos[i].x * s + di.pos[i].y * c); di.pos[i] = di.pos[i] * vInvScreenSize * 2.0f - olc::vf2d(1.0f, 1.0f); di.pos[i].y *= -1.0f; } olc::vf2d uvtl = source_pos * decal->vUVScale; olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale); di.uv = { { uvtl.x, uvtl.y }, { uvtl.x, uvbr.y }, { uvbr.x, uvbr.y }, { uvbr.x, uvtl.y } }; di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint) { DecalInstance di; di.points = 4; di.decal = decal; di.tint = { tint, tint, tint, tint }; di.w = { 1, 1, 1, 1 }; di.pos.resize(4); di.uv = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} }; olc::vf2d center; float rd = ((pos[2].x - pos[0].x) * (pos[3].y - pos[1].y) - (pos[3].x - pos[1].x) * (pos[2].y - pos[0].y)); if (rd != 0) { olc::vf2d uvtl = source_pos * decal->vUVScale; olc::vf2d uvbr = uvtl + (source_size * decal->vUVScale); di.uv = { { uvtl.x, uvtl.y }, { uvtl.x, uvbr.y }, { uvbr.x, uvbr.y }, { uvbr.x, uvtl.y } }; rd = 1.0f / rd; float rn = ((pos[3].x - pos[1].x) * (pos[0].y - pos[1].y) - (pos[3].y - pos[1].y) * (pos[0].x - pos[1].x)) * rd; float sn = ((pos[2].x - pos[0].x) * (pos[0].y - pos[1].y) - (pos[2].y - pos[0].y) * (pos[0].x - pos[1].x)) * rd; if (!(rn < 0.f || rn > 1.f || sn < 0.f || sn > 1.f)) center = pos[0] + rn * (pos[2] - pos[0]); float d[4]; for (int i = 0; i < 4; i++) d[i] = (pos[i] - center).mag(); for (int i = 0; i < 4; i++) { float q = d[i] == 0.0f ? 1.0f : (d[i] + d[(i + 2) & 3]) / d[(i + 2) & 3]; di.uv[i] *= q; di.w[i] *= q; di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } } void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const olc::vf2d* pos, const olc::Pixel& tint) { // Thanks Nathan Reed, a brilliant article explaining whats going on here // http://www.reedbeta.com/blog/quadrilateral-interpolation-part-1/ DecalInstance di; di.points = 4; di.decal = decal; di.tint = { tint, tint, tint, tint }; di.w = { 1, 1, 1, 1 }; di.pos.resize(4); di.uv = { { 0.0f, 0.0f}, {0.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, 0.0f} }; olc::vf2d center; float rd = ((pos[2].x - pos[0].x) * (pos[3].y - pos[1].y) - (pos[3].x - pos[1].x) * (pos[2].y - pos[0].y)); if (rd != 0) { rd = 1.0f / rd; float rn = ((pos[3].x - pos[1].x) * (pos[0].y - pos[1].y) - (pos[3].y - pos[1].y) * (pos[0].x - pos[1].x)) * rd; float sn = ((pos[2].x - pos[0].x) * (pos[0].y - pos[1].y) - (pos[2].y - pos[0].y) * (pos[0].x - pos[1].x)) * rd; if (!(rn < 0.f || rn > 1.f || sn < 0.f || sn > 1.f)) center = pos[0] + rn * (pos[2] - pos[0]); float d[4]; for (int i = 0; i < 4; i++) d[i] = (pos[i] - center).mag(); for (int i = 0; i < 4; i++) { float q = d[i] == 0.0f ? 1.0f : (d[i] + d[(i + 2) & 3]) / d[(i + 2) & 3]; di.uv[i] *= q; di.w[i] *= q; di.pos[i] = { (pos[i].x * vInvScreenSize.x) * 2.0f - 1.0f, ((pos[i].y * vInvScreenSize.y) * 2.0f - 1.0f) * -1.0f }; } di.mode = nDecalMode; vLayers[nTargetLayer].vecDecalInstance.push_back(di); } } void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::Pixel& tint) { DrawWarpedDecal(decal, pos.data(), tint); } void PixelGameEngine::DrawWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::Pixel& tint) { DrawWarpedDecal(decal, &pos[0], tint); } void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const std::array<olc::vf2d, 4>& pos, const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint) { DrawPartialWarpedDecal(decal, pos.data(), source_pos, source_size, tint); } void PixelGameEngine::DrawPartialWarpedDecal(olc::Decal* decal, const olc::vf2d(&pos)[4], const olc::vf2d& source_pos, const olc::vf2d& source_size, const olc::Pixel& tint) { DrawPartialWarpedDecal(decal, &pos[0], source_pos, source_size, tint); } void PixelGameEngine::DrawStringDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col, const olc::vf2d& scale) { olc::vf2d spos = { 0.0f, 0.0f }; for (auto c : sText) { if (c == '\n') { spos.x = 0; spos.y += 8.0f * scale.y; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; DrawPartialDecal(pos + spos, fontDecal, { float(ox) * 8.0f, float(oy) * 8.0f }, { 8.0f, 8.0f }, scale, col); spos.x += 8.0f * scale.x; } } } void PixelGameEngine::DrawStringPropDecal(const olc::vf2d& pos, const std::string& sText, const Pixel col, const olc::vf2d& scale) { olc::vf2d spos = { 0.0f, 0.0f }; for (auto c : sText) { if (c == '\n') { spos.x = 0; spos.y += 8.0f * scale.y; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; DrawPartialDecal(pos + spos, fontDecal, { float(ox) * 8.0f + float(vFontSpacing[c - 32].x), float(oy) * 8.0f }, { float(vFontSpacing[c - 32].y), 8.0f }, scale, col); spos.x += float(vFontSpacing[c - 32].y) * scale.x; } } } olc::vi2d PixelGameEngine::GetTextSize(const std::string& s) { olc::vi2d size = { 0,1 }; olc::vi2d pos = { 0,1 }; for (auto c : s) { if (c == '\n') { pos.y++; pos.x = 0; } else pos.x++; size.x = std::max(size.x, pos.x); size.y = std::max(size.y, pos.y); } return size * 8; } void PixelGameEngine::DrawString(const olc::vi2d& pos, const std::string& sText, Pixel col, uint32_t scale) { DrawString(pos.x, pos.y, sText, col, scale); } void PixelGameEngine::DrawString(int32_t x, int32_t y, const std::string& sText, Pixel col, uint32_t scale) { int32_t sx = 0; int32_t sy = 0; Pixel::Mode m = nPixelMode; // Thanks @tucna, spotted bug with col.ALPHA :P if (m != Pixel::CUSTOM) // Thanks @Megarev, required for "shaders" { if (col.a != 255) SetPixelMode(Pixel::ALPHA); else SetPixelMode(Pixel::MASK); } for (auto c : sText) { if (c == '\n') { sx = 0; sy += 8 * scale; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; if (scale > 1) { for (uint32_t i = 0; i < 8; i++) for (uint32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + sx + (i * scale) + is, y + sy + (j * scale) + js, col); } else { for (uint32_t i = 0; i < 8; i++) for (uint32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8, j + oy * 8).r > 0) Draw(x + sx + i, y + sy + j, col); } sx += 8 * scale; } } SetPixelMode(m); } olc::vi2d PixelGameEngine::GetTextSizeProp(const std::string& s) { olc::vi2d size = { 0,1 }; olc::vi2d pos = { 0,1 }; for (auto c : s) { if (c == '\n') { pos.y += 1; pos.x = 0; } else pos.x += vFontSpacing[c - 32].y; size.x = std::max(size.x, pos.x); size.y = std::max(size.y, pos.y); } size.y *= 8; return size; } void PixelGameEngine::DrawStringProp(const olc::vi2d& pos, const std::string& sText, Pixel col, uint32_t scale) { DrawStringProp(pos.x, pos.y, sText, col, scale); } void PixelGameEngine::DrawStringProp(int32_t x, int32_t y, const std::string& sText, Pixel col, uint32_t scale) { int32_t sx = 0; int32_t sy = 0; Pixel::Mode m = nPixelMode; if (m != Pixel::CUSTOM) { if (col.a != 255) SetPixelMode(Pixel::ALPHA); else SetPixelMode(Pixel::MASK); } for (auto c : sText) { if (c == '\n') { sx = 0; sy += 8 * scale; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; if (scale > 1) { for (int32_t i = 0; i < vFontSpacing[c - 32].y; i++) for (int32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8 + vFontSpacing[c - 32].x, j + oy * 8).r > 0) for (int32_t is = 0; is < int(scale); is++) for (int32_t js = 0; js < int(scale); js++) Draw(x + sx + (i * scale) + is, y + sy + (j * scale) + js, col); } else { for (int32_t i = 0; i < vFontSpacing[c - 32].y; i++) for (int32_t j = 0; j < 8; j++) if (fontSprite->GetPixel(i + ox * 8 + vFontSpacing[c - 32].x, j + oy * 8).r > 0) Draw(x + sx + i, y + sy + j, col); } sx += vFontSpacing[c - 32].y * scale; } } SetPixelMode(m); } void PixelGameEngine::SetPixelMode(Pixel::Mode m) { nPixelMode = m; } Pixel::Mode PixelGameEngine::GetPixelMode() { return nPixelMode; } void PixelGameEngine::SetPixelMode(std::function<olc::Pixel(const int x, const int y, const olc::Pixel&, const olc::Pixel&)> pixelMode) { funcPixelMode = pixelMode; nPixelMode = Pixel::Mode::CUSTOM; } void PixelGameEngine::SetPixelBlend(float fBlend) { fBlendFactor = fBlend; if (fBlendFactor < 0.0f) fBlendFactor = 0.0f; if (fBlendFactor > 1.0f) fBlendFactor = 1.0f; } // User must override these functions as required. I have not made // them abstract because I do need a default behaviour to occur if // they are not overwritten bool PixelGameEngine::OnUserCreate() { return false; } bool PixelGameEngine::OnUserUpdate(float fElapsedTime) { UNUSED(fElapsedTime); return false; } bool PixelGameEngine::OnUserDestroy() { return true; } void PixelGameEngine::olc_UpdateViewport() { int32_t ww = vScreenSize.x * vPixelSize.x; int32_t wh = vScreenSize.y * vPixelSize.y; float wasp = (float)ww / (float)wh; if (bPixelCohesion) { vScreenPixelSize = (vWindowSize / vScreenSize); vViewSize = (vWindowSize / vScreenSize) * vScreenSize; } else { vViewSize.x = (int32_t)vWindowSize.x; vViewSize.y = (int32_t)((float)vViewSize.x / wasp); if (vViewSize.y > vWindowSize.y) { vViewSize.y = vWindowSize.y; vViewSize.x = (int32_t)((float)vViewSize.y * wasp); } } vViewPos = (vWindowSize - vViewSize) / 2; } void PixelGameEngine::olc_UpdateWindowSize(int32_t x, int32_t y) { vWindowSize = { x, y }; olc_UpdateViewport(); } void PixelGameEngine::olc_UpdateMouseWheel(int32_t delta) { nMouseWheelDeltaCache += delta; } void PixelGameEngine::olc_UpdateMouse(int32_t x, int32_t y) { // Mouse coords come in screen space // But leave in pixel space bHasMouseFocus = true; vMouseWindowPos = { x, y }; // Full Screen mode may have a weird viewport we must clamp to x -= vViewPos.x; y -= vViewPos.y; vMousePosCache.x = (int32_t)(((float)x / (float)(vWindowSize.x - (vViewPos.x * 2)) * (float)vScreenSize.x)); vMousePosCache.y = (int32_t)(((float)y / (float)(vWindowSize.y - (vViewPos.y * 2)) * (float)vScreenSize.y)); if (vMousePosCache.x >= (int32_t)vScreenSize.x) vMousePosCache.x = vScreenSize.x - 1; if (vMousePosCache.y >= (int32_t)vScreenSize.y) vMousePosCache.y = vScreenSize.y - 1; if (vMousePosCache.x < 0) vMousePosCache.x = 0; if (vMousePosCache.y < 0) vMousePosCache.y = 0; } void PixelGameEngine::olc_UpdateMouseState(int32_t button, bool state) { pMouseNewState[button] = state; } void PixelGameEngine::olc_UpdateKeyState(int32_t key, bool state) { pKeyNewState[key] = state; } void PixelGameEngine::olc_UpdateMouseFocus(bool state) { bHasMouseFocus = state; } void PixelGameEngine::olc_UpdateKeyFocus(bool state) { bHasInputFocus = state; } void PixelGameEngine::olc_Reanimate() { bAtomActive = true; } bool PixelGameEngine::olc_IsRunning() { return bAtomActive; } void PixelGameEngine::olc_Terminate() { bAtomActive = false; } void PixelGameEngine::EngineThread() { // Allow platform to do stuff here if needed, since its now in the // context of this thread if (platform->ThreadStartUp() == olc::FAIL) return; // Do engine context specific initialisation olc_PrepareEngine(); // Create user resources as part of this thread for (auto& ext : vExtensions) ext->OnBeforeUserCreate(); if (!OnUserCreate()) bAtomActive = false; for (auto& ext : vExtensions) ext->OnAfterUserCreate(); while (bAtomActive) { // Run as fast as possible while (bAtomActive) { olc_CoreUpdate(); } // Allow the user to free resources if they have overrided the destroy function if (!OnUserDestroy()) { // User denied destroy for some reason, so continue running bAtomActive = true; } } platform->ThreadCleanUp(); } void PixelGameEngine::olc_PrepareEngine() { // Start OpenGL, the context is owned by the game thread if (platform->CreateGraphics(bFullScreen, bEnableVSYNC, vViewPos, vViewSize) == olc::FAIL) return; // Construct default font sheet olc_ConstructFontSheet(); // Create Primary Layer "0" CreateLayer(); vLayers[0].bUpdate = true; vLayers[0].bShow = true; SetDrawTarget(nullptr); m_tp1 = std::chrono::system_clock::now(); m_tp2 = std::chrono::system_clock::now(); } void PixelGameEngine::olc_CoreUpdate() { // Handle Timing m_tp2 = std::chrono::system_clock::now(); std::chrono::duration<float> elapsedTime = m_tp2 - m_tp1; m_tp1 = m_tp2; // Our time per frame coefficient float fElapsedTime = elapsedTime.count(); fLastElapsed = fElapsedTime; // Some platforms will need to check for events platform->HandleSystemEvent(); // Compare hardware input states from previous frame auto ScanHardware = [&](HWButton* pKeys, bool* pStateOld, bool* pStateNew, uint32_t nKeyCount) { for (uint32_t i = 0; i < nKeyCount; i++) { pKeys[i].bPressed = false; pKeys[i].bReleased = false; if (pStateNew[i] != pStateOld[i]) { if (pStateNew[i]) { pKeys[i].bPressed = !pKeys[i].bHeld; pKeys[i].bHeld = true; } else { pKeys[i].bReleased = true; pKeys[i].bHeld = false; } } pStateOld[i] = pStateNew[i]; } }; ScanHardware(pKeyboardState, pKeyOldState, pKeyNewState, 256); ScanHardware(pMouseState, pMouseOldState, pMouseNewState, nMouseButtons); // Cache mouse coordinates so they remain consistent during frame vMousePos = vMousePosCache; nMouseWheelDelta = nMouseWheelDeltaCache; nMouseWheelDeltaCache = 0; // renderer->ClearBuffer(olc::BLACK, true); // Handle Frame Update for (auto& ext : vExtensions) ext->OnBeforeUserUpdate(fElapsedTime); if (!OnUserUpdate(fElapsedTime)) bAtomActive = false; for (auto& ext : vExtensions) ext->OnAfterUserUpdate(fElapsedTime); // Display Frame renderer->UpdateViewport(vViewPos, vViewSize); renderer->ClearBuffer(olc::BLACK, true); // Layer 0 must always exist vLayers[0].bUpdate = true; vLayers[0].bShow = true; SetDecalMode(DecalMode::NORMAL); renderer->PrepareDrawing(); for (auto layer = vLayers.rbegin(); layer != vLayers.rend(); ++layer) { if (layer->bShow) { if (layer->funcHook == nullptr) { renderer->ApplyTexture(layer->nResID); if (layer->bUpdate) { renderer->UpdateTexture(layer->nResID, layer->pDrawTarget); layer->bUpdate = false; } renderer->DrawLayerQuad(layer->vOffset, layer->vScale, layer->tint); // Display Decals in order for this layer for (auto& decal : layer->vecDecalInstance) renderer->DrawDecal(decal); layer->vecDecalInstance.clear(); } else { // Mwa ha ha.... Have Fun!!! layer->funcHook(); } } } // Present Graphics to screen renderer->DisplayFrame(); // Update Title Bar fFrameTimer += fElapsedTime; nFrameCount++; if (fFrameTimer >= 1.0f) { nLastFPS = nFrameCount; fFrameTimer -= 1.0f; std::string sTitle = "ROGU Engine | " + sAppName + " | FPS: " + std::to_string(nFrameCount); platform->SetWindowTitle(sTitle); nFrameCount = 0; } } void PixelGameEngine::olc_ConstructFontSheet() { std::string data; data += "?Q`0001oOch0o01o@F40o0<AGD4090LAGD<090@A7ch0?00O7Q`0600>00000000"; data += "O000000nOT0063Qo4d8>?7a14Gno94AA4gno94AaOT0>o3`oO400o7QN00000400"; data += "Of80001oOg<7O7moBGT7O7lABET024@aBEd714AiOdl717a_=TH013Q>00000000"; data += "720D000V?V5oB3Q_HdUoE7a9@DdDE4A9@DmoE4A;Hg]oM4Aj8S4D84@`00000000"; data += "OaPT1000Oa`^13P1@AI[?g`1@A=[OdAoHgljA4Ao?WlBA7l1710007l100000000"; data += "ObM6000oOfMV?3QoBDD`O7a0BDDH@5A0BDD<@5A0BGeVO5ao@CQR?5Po00000000"; data += "Oc``000?Ogij70PO2D]??0Ph2DUM@7i`2DTg@7lh2GUj?0TO0C1870T?00000000"; data += "70<4001o?P<7?1QoHg43O;`h@GT0@:@LB@d0>:@hN@L0@?aoN@<0O7ao0000?000"; data += "OcH0001SOglLA7mg24TnK7ln24US>0PL24U140PnOgl0>7QgOcH0K71S0000A000"; data += "00H00000@Dm1S007@DUSg00?OdTnH7YhOfTL<7Yh@Cl0700?@Ah0300700000000"; data += "<008001QL00ZA41a@6HnI<1i@FHLM81M@@0LG81?O`0nC?Y7?`0ZA7Y300080000"; data += "O`082000Oh0827mo6>Hn?Wmo?6HnMb11MP08@C11H`08@FP0@@0004@000000000"; data += "00P00001Oab00003OcKP0006@6=PMgl<@440MglH@000000`@000001P00000000"; data += "Ob@8@@00Ob@8@Ga13R@8Mga172@8?PAo3R@827QoOb@820@0O`0007`0000007P0"; data += "O`000P08Od400g`<3V=P0G`673IP0`@3>1`00P@6O`P00g`<O`000GP800000000"; data += "?P9PL020O`<`N3R0@E4HC7b0@ET<ATB0@@l6C4B0O`H3N7b0?P01L3R000000020"; fontSprite = new olc::Sprite(128, 48); int px = 0, py = 0; for (size_t b = 0; b < 1024; b += 4) { uint32_t sym1 = (uint32_t)data[b + 0] - 48; uint32_t sym2 = (uint32_t)data[b + 1] - 48; uint32_t sym3 = (uint32_t)data[b + 2] - 48; uint32_t sym4 = (uint32_t)data[b + 3] - 48; uint32_t r = sym1 << 18 | sym2 << 12 | sym3 << 6 | sym4; for (int i = 0; i < 24; i++) { int k = r & (1 << i) ? 255 : 0; fontSprite->SetPixel(px, py, olc::Pixel(k, k, k, k)); if (++py == 48) { px++; py = 0; } } } fontDecal = new olc::Decal(fontSprite); constexpr std::array<uint8_t, 96> vSpacing = { { 0x03,0x25,0x16,0x08,0x07,0x08,0x08,0x04,0x15,0x15,0x08,0x07,0x15,0x07,0x24,0x08, 0x08,0x17,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x24,0x15,0x06,0x07,0x16,0x17, 0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x17,0x08,0x08,0x17,0x08,0x08,0x08, 0x08,0x08,0x08,0x08,0x17,0x08,0x08,0x08,0x08,0x17,0x08,0x15,0x08,0x15,0x08,0x08, 0x24,0x18,0x17,0x17,0x17,0x17,0x17,0x17,0x17,0x33,0x17,0x17,0x33,0x18,0x17,0x17, 0x17,0x17,0x17,0x17,0x07,0x17,0x17,0x18,0x18,0x17,0x17,0x07,0x33,0x07,0x08,0x00, } }; for (auto c : vSpacing) vFontSpacing.push_back({ c >> 4, c & 15 }); } void PixelGameEngine::pgex_Register(olc::PGEX* pgex) { if (std::find(vExtensions.begin(), vExtensions.end(), pgex) == vExtensions.end()) vExtensions.push_back(pgex); } PGEX::PGEX(bool bHook) { if(bHook) pge->pgex_Register(this); } void PGEX::OnBeforeUserCreate() {} void PGEX::OnAfterUserCreate() {} void PGEX::OnBeforeUserUpdate(float& fElapsedTime) {} void PGEX::OnAfterUserUpdate(float fElapsedTime) {} // Need a couple of statics as these are singleton instances // read from multiple locations std::atomic<bool> PixelGameEngine::bAtomActive{ false }; olc::PixelGameEngine* olc::PGEX::pge = nullptr; olc::PixelGameEngine* olc::Platform::ptrPGE = nullptr; olc::PixelGameEngine* olc::Renderer::ptrPGE = nullptr; std::unique_ptr<ImageLoader> olc::Sprite::loader = nullptr; }; #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine Renderers - the draw-y bits | // O------------------------------------------------------------------------------O #pragma region renderer_ogl10 // O------------------------------------------------------------------------------O // | START RENDERER: OpenGL 1.0 (the original, the best...) | // O------------------------------------------------------------------------------O #if defined(OLC_GFX_OPENGL10) #if defined(OLC_PLATFORM_WINAPI) #include <dwmapi.h> #include <GL/gl.h> #if !defined(__MINGW32__) #pragma comment(lib, "Dwmapi.lib") #endif typedef BOOL(WINAPI wglSwapInterval_t) (int interval); static wglSwapInterval_t* wglSwapInterval = nullptr; typedef HDC glDeviceContext_t; typedef HGLRC glRenderContext_t; #endif #if defined(__linux__) || defined(__FreeBSD__) #include <GL/gl.h> #endif #if defined(OLC_PLATFORM_X11) namespace X11 { #include <GL/glx.h> } typedef int(glSwapInterval_t)(X11::Display* dpy, X11::GLXDrawable drawable, int interval); static glSwapInterval_t* glSwapIntervalEXT; typedef X11::GLXContext glDeviceContext_t; typedef X11::GLXContext glRenderContext_t; #endif #if defined(__APPLE__) #define GL_SILENCE_DEPRECATION #include <OpenGL/OpenGL.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #endif namespace olc { class Renderer_OGL10 : public olc::Renderer { private: #if defined(OLC_PLATFORM_GLUT) bool mFullScreen = false; #else glDeviceContext_t glDeviceContext = 0; glRenderContext_t glRenderContext = 0; #endif bool bSync = false; olc::DecalMode nDecalMode = olc::DecalMode(-1); // Thanks Gusgo & Bispoo #if defined(OLC_PLATFORM_X11) X11::Display* olc_Display = nullptr; X11::Window* olc_Window = nullptr; X11::XVisualInfo* olc_VisualInfo = nullptr; #endif public: void PrepareDevice() override { #if defined(OLC_PLATFORM_GLUT) //glutInit has to be called with main() arguments, make fake ones int argc = 0; char* argv[1] = { (char*)"" }; glutInit(&argc, argv); glutInitWindowPosition(0, 0); glutInitWindowSize(512, 512); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA); // Creates the window and the OpenGL context for it glutCreateWindow("OneLoneCoder.com - Pixel Game Engine"); glEnable(GL_TEXTURE_2D); // Turn on texturing glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); #endif } olc::rcode CreateDevice(std::vector<void*> params, bool bFullScreen, bool bVSYNC) override { #if defined(OLC_PLATFORM_WINAPI) // Create Device Context glDeviceContext = GetDC((HWND)(params[0])); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pf = 0; if (!(pf = ChoosePixelFormat(glDeviceContext, &pfd))) return olc::FAIL; SetPixelFormat(glDeviceContext, pf, &pfd); if (!(glRenderContext = wglCreateContext(glDeviceContext))) return olc::FAIL; wglMakeCurrent(glDeviceContext, glRenderContext); // Remove Frame cap wglSwapInterval = (wglSwapInterval_t*)wglGetProcAddress("wglSwapIntervalEXT"); if (wglSwapInterval && !bVSYNC) wglSwapInterval(0); bSync = bVSYNC; #endif #if defined(OLC_PLATFORM_X11) using namespace X11; // Linux has tighter coupling between OpenGL and X11, so we store // various "platform" handles in the renderer olc_Display = (X11::Display*)(params[0]); olc_Window = (X11::Window*)(params[1]); olc_VisualInfo = (X11::XVisualInfo*)(params[2]); glDeviceContext = glXCreateContext(olc_Display, olc_VisualInfo, nullptr, GL_TRUE); glXMakeCurrent(olc_Display, *olc_Window, glDeviceContext); XWindowAttributes gwa; XGetWindowAttributes(olc_Display, *olc_Window, &gwa); glViewport(0, 0, gwa.width, gwa.height); glSwapIntervalEXT = nullptr; glSwapIntervalEXT = (glSwapInterval_t*)glXGetProcAddress((unsigned char*)"glXSwapIntervalEXT"); if (glSwapIntervalEXT == nullptr && !bVSYNC) { printf("NOTE: Could not disable VSYNC, glXSwapIntervalEXT() was not found!\n"); printf(" Don't worry though, things will still work, it's just the\n"); printf(" frame rate will be capped to your monitors refresh rate - javidx9\n"); } if (glSwapIntervalEXT != nullptr && !bVSYNC) glSwapIntervalEXT(olc_Display, *olc_Window, 0); #endif #if defined(OLC_PLATFORM_GLUT) mFullScreen = bFullScreen; if (!bVSYNC) { #if defined(__APPLE__) GLint sync = 0; CGLContextObj ctx = CGLGetCurrentContext(); if (ctx) CGLSetParameter(ctx, kCGLCPSwapInterval, &sync); #endif } #else glEnable(GL_TEXTURE_2D); // Turn on texturing glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); #endif return olc::rcode::OK; } olc::rcode DestroyDevice() override { #if defined(OLC_PLATFORM_WINAPI) wglDeleteContext(glRenderContext); #endif #if defined(OLC_PLATFORM_X11) glXMakeCurrent(olc_Display, None, NULL); glXDestroyContext(olc_Display, glDeviceContext); #endif #if defined(OLC_PLATFORM_GLUT) glutDestroyWindow(glutGetWindow()); #endif return olc::rcode::OK; } void DisplayFrame() override { #if defined(OLC_PLATFORM_WINAPI) SwapBuffers(glDeviceContext); if (bSync) DwmFlush(); // Woooohooooooo!!!! SMOOOOOOOTH! #endif #if defined(OLC_PLATFORM_X11) X11::glXSwapBuffers(olc_Display, *olc_Window); #endif #if defined(OLC_PLATFORM_GLUT) glutSwapBuffers(); #endif } void PrepareDrawing() override { glEnable(GL_BLEND); nDecalMode = DecalMode::NORMAL; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void SetDecalMode(const olc::DecalMode& mode) { if (mode != nDecalMode) { switch (mode) { case olc::DecalMode::NORMAL: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case olc::DecalMode::ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; case olc::DecalMode::MULTIPLICATIVE: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); break; case olc::DecalMode::STENCIL: glBlendFunc(GL_ZERO, GL_SRC_ALPHA); break; case olc::DecalMode::ILLUMINATE: glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA); break; case olc::DecalMode::WIREFRAME: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } nDecalMode = mode; } } void DrawLayerQuad(const olc::vf2d& offset, const olc::vf2d& scale, const olc::Pixel tint) override { glBegin(GL_QUADS); glColor4ub(tint.r, tint.g, tint.b, tint.a); glTexCoord2f(0.0f * scale.x + offset.x, 1.0f * scale.y + offset.y); glVertex3f(-1.0f /*+ vSubPixelOffset.x*/, -1.0f /*+ vSubPixelOffset.y*/, 0.0f); glTexCoord2f(0.0f * scale.x + offset.x, 0.0f * scale.y + offset.y); glVertex3f(-1.0f /*+ vSubPixelOffset.x*/, 1.0f /*+ vSubPixelOffset.y*/, 0.0f); glTexCoord2f(1.0f * scale.x + offset.x, 0.0f * scale.y + offset.y); glVertex3f(1.0f /*+ vSubPixelOffset.x*/, 1.0f /*+ vSubPixelOffset.y*/, 0.0f); glTexCoord2f(1.0f * scale.x + offset.x, 1.0f * scale.y + offset.y); glVertex3f(1.0f /*+ vSubPixelOffset.x*/, -1.0f /*+ vSubPixelOffset.y*/, 0.0f); glEnd(); } void DrawDecal(const olc::DecalInstance& decal) override { SetDecalMode(decal.mode); if (decal.decal == nullptr) glBindTexture(GL_TEXTURE_2D, 0); else glBindTexture(GL_TEXTURE_2D, decal.decal->id); if (nDecalMode == DecalMode::WIREFRAME) glBegin(GL_LINE_LOOP); else glBegin(GL_TRIANGLE_FAN); for (uint32_t n = 0; n < decal.points; n++) { glColor4ub(decal.tint[n].r, decal.tint[n].g, decal.tint[n].b, decal.tint[n].a); glTexCoord4f(decal.uv[n].x, decal.uv[n].y, 0.0f, decal.w[n]); glVertex2f(decal.pos[n].x, decal.pos[n].y); } glEnd(); } uint32_t CreateTexture(const uint32_t width, const uint32_t height, const bool filtered, const bool clamp) override { UNUSED(width); UNUSED(height); uint32_t id = 0; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); if (filtered) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } if (clamp) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); return id; } uint32_t DeleteTexture(const uint32_t id) override { glDeleteTextures(1, &id); return id; } void UpdateTexture(uint32_t id, olc::Sprite* spr) override { UNUSED(id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, spr->width, spr->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData()); } void ReadTexture(uint32_t id, olc::Sprite* spr) override { glReadPixels(0, 0, spr->width, spr->height, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData()); } void ApplyTexture(uint32_t id) override { glBindTexture(GL_TEXTURE_2D, id); } void ClearBuffer(olc::Pixel p, bool bDepth) override { glClearColor(float(p.r) / 255.0f, float(p.g) / 255.0f, float(p.b) / 255.0f, float(p.a) / 255.0f); glClear(GL_COLOR_BUFFER_BIT); if (bDepth) glClear(GL_DEPTH_BUFFER_BIT); } void UpdateViewport(const olc::vi2d& pos, const olc::vi2d& size) override { #if defined(OLC_PLATFORM_GLUT) if (!mFullScreen) glutReshapeWindow(size.x, size.y); #else glViewport(pos.x, pos.y, size.x, size.y); #endif } }; } #endif // O------------------------------------------------------------------------------O // | END RENDERER: OpenGL 1.0 (the original, the best...) | // O------------------------------------------------------------------------------O #pragma endregion #pragma region renderer_ogl33 // O------------------------------------------------------------------------------O // | START RENDERER: OpenGL 3.3 (3.0 es) (sh-sh-sh-shaders....) | // O------------------------------------------------------------------------------O #if defined(OLC_GFX_OPENGL33) #if defined(OLC_PLATFORM_WINAPI) #include <dwmapi.h> #include <gl/GL.h> #if !defined(__MINGW32__) #pragma comment(lib, "Dwmapi.lib") #endif typedef void __stdcall locSwapInterval_t(GLsizei n); typedef HDC glDeviceContext_t; typedef HGLRC glRenderContext_t; #define CALLSTYLE __stdcall #define OGL_LOAD(t, n) (t*)wglGetProcAddress(#n) #endif #if defined(__linux__) || defined(__FreeBSD__) #include <GL/gl.h> #endif #if defined(OLC_PLATFORM_X11) namespace X11 { #include <GL/glx.h> } typedef int(locSwapInterval_t)(X11::Display* dpy, X11::GLXDrawable drawable, int interval); typedef X11::GLXContext glDeviceContext_t; typedef X11::GLXContext glRenderContext_t; #define CALLSTYLE #define OGL_LOAD(t, n) (t*)glXGetProcAddress((unsigned char*)#n); #endif #if defined(__APPLE__) #define GL_SILENCE_DEPRECATION #include <OpenGL/OpenGL.h> #include <OpenGL/gl.h> #include <OpenGL/glu.h> #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) #include <EGL/egl.h> #include <GLES2/gl2.h> #define GL_GLEXT_PROTOTYPES #include <GLES2/gl2ext.h> #include <emscripten/emscripten.h> #define CALLSTYLE typedef EGLBoolean(locSwapInterval_t)(EGLDisplay display, EGLint interval); #define GL_CLAMP GL_CLAMP_TO_EDGE #define OGL_LOAD(t, n) n; #endif namespace olc { typedef char GLchar; typedef ptrdiff_t GLsizeiptr; typedef GLuint CALLSTYLE locCreateShader_t(GLenum type); typedef GLuint CALLSTYLE locCreateProgram_t(void); typedef void CALLSTYLE locDeleteShader_t(GLuint shader); #if defined(OLC_PLATFORM_EMSCRIPTEN) typedef void CALLSTYLE locShaderSource_t(GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length); #else typedef void CALLSTYLE locShaderSource_t(GLuint shader, GLsizei count, const GLchar** string, const GLint* length); #endif typedef void CALLSTYLE locCompileShader_t(GLuint shader); typedef void CALLSTYLE locLinkProgram_t(GLuint program); typedef void CALLSTYLE locDeleteProgram_t(GLuint program); typedef void CALLSTYLE locAttachShader_t(GLuint program, GLuint shader); typedef void CALLSTYLE locBindBuffer_t(GLenum target, GLuint buffer); typedef void CALLSTYLE locBufferData_t(GLenum target, GLsizeiptr size, const void* data, GLenum usage); typedef void CALLSTYLE locGenBuffers_t(GLsizei n, GLuint* buffers); typedef void CALLSTYLE locVertexAttribPointer_t(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void* pointer); typedef void CALLSTYLE locEnableVertexAttribArray_t(GLuint index); typedef void CALLSTYLE locUseProgram_t(GLuint program); typedef void CALLSTYLE locBindVertexArray_t(GLuint array); typedef void CALLSTYLE locGenVertexArrays_t(GLsizei n, GLuint* arrays); typedef void CALLSTYLE locGetShaderInfoLog_t(GLuint shader, GLsizei bufSize, GLsizei* length, GLchar* infoLog); constexpr size_t OLC_MAX_VERTS = 128; class Renderer_OGL33 : public olc::Renderer { private: #if defined(OLC_PLATFORM_EMSCRIPTEN) EGLDisplay olc_Display; EGLConfig olc_Config; EGLContext olc_Context; EGLSurface olc_Surface; #endif #if defined(OLC_PLATFORM_GLUT) bool mFullScreen = false; #else #if !defined(OLC_PLATFORM_EMSCRIPTEN) glDeviceContext_t glDeviceContext = 0; glRenderContext_t glRenderContext = 0; #endif #endif bool bSync = false; olc::DecalMode nDecalMode = olc::DecalMode(-1); // Thanks Gusgo & Bispoo #if defined(OLC_PLATFORM_X11) X11::Display* olc_Display = nullptr; X11::Window* olc_Window = nullptr; X11::XVisualInfo* olc_VisualInfo = nullptr; #endif private: locCreateShader_t* locCreateShader = nullptr; locShaderSource_t* locShaderSource = nullptr; locCompileShader_t* locCompileShader = nullptr; locDeleteShader_t* locDeleteShader = nullptr; locCreateProgram_t* locCreateProgram = nullptr; locDeleteProgram_t* locDeleteProgram = nullptr; locLinkProgram_t* locLinkProgram = nullptr; locAttachShader_t* locAttachShader = nullptr; locBindBuffer_t* locBindBuffer = nullptr; locBufferData_t* locBufferData = nullptr; locGenBuffers_t* locGenBuffers = nullptr; locVertexAttribPointer_t* locVertexAttribPointer = nullptr; locEnableVertexAttribArray_t* locEnableVertexAttribArray = nullptr; locUseProgram_t* locUseProgram = nullptr; locBindVertexArray_t* locBindVertexArray = nullptr; locGenVertexArrays_t* locGenVertexArrays = nullptr; locSwapInterval_t* locSwapInterval = nullptr; locGetShaderInfoLog_t* locGetShaderInfoLog = nullptr; uint32_t m_nFS = 0; uint32_t m_nVS = 0; uint32_t m_nQuadShader = 0; uint32_t m_vbQuad = 0; uint32_t m_vaQuad = 0; struct locVertex { float pos[3]; olc::vf2d tex; olc::Pixel col; }; locVertex pVertexMem[OLC_MAX_VERTS]; olc::Renderable rendBlankQuad; public: void PrepareDevice() override { #if defined(OLC_PLATFORM_GLUT) //glutInit has to be called with main() arguments, make fake ones int argc = 0; char* argv[1] = { (char*)"" }; glutInit(&argc, argv); glutInitWindowPosition(0, 0); glutInitWindowSize(512, 512); glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA); // Creates the window and the OpenGL context for it glutCreateWindow("OneLoneCoder.com - Pixel Game Engine"); glEnable(GL_TEXTURE_2D); // Turn on texturing glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); #endif } olc::rcode CreateDevice(std::vector<void*> params, bool bFullScreen, bool bVSYNC) override { // Create OpenGL Context #if defined(OLC_PLATFORM_WINAPI) // Create Device Context glDeviceContext = GetDC((HWND)(params[0])); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pf = 0; if (!(pf = ChoosePixelFormat(glDeviceContext, &pfd))) return olc::FAIL; SetPixelFormat(glDeviceContext, pf, &pfd); if (!(glRenderContext = wglCreateContext(glDeviceContext))) return olc::FAIL; wglMakeCurrent(glDeviceContext, glRenderContext); // Set Vertical Sync locSwapInterval = OGL_LOAD(locSwapInterval_t, "wglSwapIntervalEXT"); if (locSwapInterval && !bVSYNC) locSwapInterval(0); bSync = bVSYNC; #endif #if defined(OLC_PLATFORM_X11) using namespace X11; // Linux has tighter coupling between OpenGL and X11, so we store // various "platform" handles in the renderer olc_Display = (X11::Display*)(params[0]); olc_Window = (X11::Window*)(params[1]); olc_VisualInfo = (X11::XVisualInfo*)(params[2]); glDeviceContext = glXCreateContext(olc_Display, olc_VisualInfo, nullptr, GL_TRUE); glXMakeCurrent(olc_Display, *olc_Window, glDeviceContext); XWindowAttributes gwa; XGetWindowAttributes(olc_Display, *olc_Window, &gwa); glViewport(0, 0, gwa.width, gwa.height); locSwapInterval = OGL_LOAD(locSwapInterval_t, "glXSwapIntervalEXT"); if (locSwapInterval == nullptr && !bVSYNC) { printf("NOTE: Could not disable VSYNC, glXSwapIntervalEXT() was not found!\n"); printf(" Don't worry though, things will still work, it's just the\n"); printf(" frame rate will be capped to your monitors refresh rate - javidx9\n"); } if (locSwapInterval != nullptr && !bVSYNC) locSwapInterval(olc_Display, *olc_Window, 0); #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) EGLint const attribute_list[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; EGLint const context_config[] = { EGL_CONTEXT_CLIENT_VERSION , 2, EGL_NONE }; EGLint num_config; olc_Display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(olc_Display, nullptr, nullptr); eglChooseConfig(olc_Display, attribute_list, &olc_Config, 1, &num_config); /* create an EGL rendering context */ olc_Context = eglCreateContext(olc_Display, olc_Config, EGL_NO_CONTEXT, context_config); olc_Surface = eglCreateWindowSurface(olc_Display, olc_Config, NULL, nullptr); eglMakeCurrent(olc_Display, olc_Surface, olc_Surface, olc_Context); //eglSwapInterval is currently a NOP, plement anyways in case it becomes supported locSwapInterval = &eglSwapInterval; locSwapInterval(olc_Display, bVSYNC ? 1 : 0); #endif #if defined(OLC_PLATFORM_GLUT) mFullScreen = bFullScreen; if (!bVSYNC) { #if defined(__APPLE__) GLint sync = 0; CGLContextObj ctx = CGLGetCurrentContext(); if (ctx) CGLSetParameter(ctx, kCGLCPSwapInterval, &sync); #endif } #else #if !defined(OLC_PLATFORM_EMSCRIPTEN) glEnable(GL_TEXTURE_2D); // Turn on texturing glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); #endif #endif // Load External OpenGL Functions locCreateShader = OGL_LOAD(locCreateShader_t, glCreateShader); locCompileShader = OGL_LOAD(locCompileShader_t, glCompileShader); locShaderSource = OGL_LOAD(locShaderSource_t, glShaderSource); locDeleteShader = OGL_LOAD(locDeleteShader_t, glDeleteShader); locCreateProgram = OGL_LOAD(locCreateProgram_t, glCreateProgram); locDeleteProgram = OGL_LOAD(locDeleteProgram_t, glDeleteProgram); locLinkProgram = OGL_LOAD(locLinkProgram_t, glLinkProgram); locAttachShader = OGL_LOAD(locAttachShader_t, glAttachShader); locBindBuffer = OGL_LOAD(locBindBuffer_t, glBindBuffer); locBufferData = OGL_LOAD(locBufferData_t, glBufferData); locGenBuffers = OGL_LOAD(locGenBuffers_t, glGenBuffers); locVertexAttribPointer = OGL_LOAD(locVertexAttribPointer_t, glVertexAttribPointer); locEnableVertexAttribArray = OGL_LOAD(locEnableVertexAttribArray_t, glEnableVertexAttribArray); locUseProgram = OGL_LOAD(locUseProgram_t, glUseProgram); locGetShaderInfoLog = OGL_LOAD(locGetShaderInfoLog_t, glGetShaderInfoLog); #if !defined(OLC_PLATFORM_EMSCRIPTEN) locBindVertexArray = OGL_LOAD(locBindVertexArray_t, glBindVertexArray); locGenVertexArrays = OGL_LOAD(locGenVertexArrays_t, glGenVertexArrays); #else locBindVertexArray = glBindVertexArrayOES; locGenVertexArrays = glGenVertexArraysOES; #endif // Load & Compile Quad Shader - assumes no errors m_nFS = locCreateShader(0x8B30); const GLchar* strFS = #if defined(__arm__) || defined(OLC_PLATFORM_EMSCRIPTEN) "#version 300 es\n" "precision mediump float;" #else "#version 330 core\n" #endif "out vec4 pixel;\n""in vec2 oTex;\n" "in vec4 oCol;\n""uniform sampler2D sprTex;\n""void main(){pixel = texture(sprTex, oTex) * oCol;}"; locShaderSource(m_nFS, 1, &strFS, NULL); locCompileShader(m_nFS); m_nVS = locCreateShader(0x8B31); const GLchar* strVS = #if defined(__arm__) || defined(OLC_PLATFORM_EMSCRIPTEN) "#version 300 es\n" "precision mediump float;" #else "#version 330 core\n" #endif "layout(location = 0) in vec3 aPos;\n""layout(location = 1) in vec2 aTex;\n" "layout(location = 2) in vec4 aCol;\n""out vec2 oTex;\n""out vec4 oCol;\n" "void main(){ float p = 1.0 / aPos.z; gl_Position = p * vec4(aPos.x, aPos.y, 0.0, 1.0); oTex = p * aTex; oCol = aCol;}"; locShaderSource(m_nVS, 1, &strVS, NULL); locCompileShader(m_nVS); m_nQuadShader = locCreateProgram(); locAttachShader(m_nQuadShader, m_nFS); locAttachShader(m_nQuadShader, m_nVS); locLinkProgram(m_nQuadShader); // Create Quad locGenBuffers(1, &m_vbQuad); locGenVertexArrays(1, &m_vaQuad); locBindVertexArray(m_vaQuad); locBindBuffer(0x8892, m_vbQuad); locVertex verts[OLC_MAX_VERTS]; locBufferData(0x8892, sizeof(locVertex) * OLC_MAX_VERTS, verts, 0x88E0); locVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(locVertex), 0); locEnableVertexAttribArray(0); locVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(locVertex), (void*)(3 * sizeof(float))); locEnableVertexAttribArray(1); locVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(locVertex), (void*)(5 * sizeof(float))); locEnableVertexAttribArray(2); locBindBuffer(0x8892, 0); locBindVertexArray(0); // Create blank texture for spriteless decals rendBlankQuad.Create(1, 1); rendBlankQuad.Sprite()->GetData()[0] = olc::WHITE; rendBlankQuad.Decal()->Update(); return olc::rcode::OK; } olc::rcode DestroyDevice() override { #if defined(OLC_PLATFORM_WINAPI) wglDeleteContext(glRenderContext); #endif #if defined(OLC_PLATFORM_X11) glXMakeCurrent(olc_Display, None, NULL); glXDestroyContext(olc_Display, glDeviceContext); #endif #if defined(OLC_PLATFORM_GLUT) glutDestroyWindow(glutGetWindow()); #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) eglMakeCurrent(olc_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(olc_Display, olc_Context); eglDestroySurface(olc_Display, olc_Surface); eglTerminate(olc_Display); olc_Display = EGL_NO_DISPLAY; olc_Surface = EGL_NO_SURFACE; olc_Context = EGL_NO_CONTEXT; #endif return olc::rcode::OK; } void DisplayFrame() override { #if defined(OLC_PLATFORM_WINAPI) SwapBuffers(glDeviceContext); if (bSync) DwmFlush(); // Woooohooooooo!!!! SMOOOOOOOTH! #endif #if defined(OLC_PLATFORM_X11) X11::glXSwapBuffers(olc_Display, *olc_Window); #endif #if defined(OLC_PLATFORM_GLUT) glutSwapBuffers(); #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) eglSwapBuffers(olc_Display, olc_Surface); #endif } void PrepareDrawing() override { glEnable(GL_BLEND); nDecalMode = DecalMode::NORMAL; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); locUseProgram(m_nQuadShader); locBindVertexArray(m_vaQuad); #if defined(OLC_PLATFORM_EMSCRIPTEN) locVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(locVertex), 0); locEnableVertexAttribArray(0); locVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(locVertex), (void*)(3 * sizeof(float))); locEnableVertexAttribArray(1); locVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(locVertex), (void*)(5 * sizeof(float))); locEnableVertexAttribArray(2); #endif } void SetDecalMode(const olc::DecalMode& mode) override { if (mode != nDecalMode) { switch (mode) { case olc::DecalMode::NORMAL: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case olc::DecalMode::ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; case olc::DecalMode::MULTIPLICATIVE: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); break; case olc::DecalMode::STENCIL: glBlendFunc(GL_ZERO, GL_SRC_ALPHA); break; case olc::DecalMode::ILLUMINATE: glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA); break; case olc::DecalMode::WIREFRAME: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } nDecalMode = mode; } } void DrawLayerQuad(const olc::vf2d& offset, const olc::vf2d& scale, const olc::Pixel tint) override { locBindBuffer(0x8892, m_vbQuad); locVertex verts[4] = { {{-1.0f, -1.0f, 1.0}, {0.0f * scale.x + offset.x, 1.0f * scale.y + offset.y}, tint}, {{+1.0f, -1.0f, 1.0}, {1.0f * scale.x + offset.x, 1.0f * scale.y + offset.y}, tint}, {{-1.0f, +1.0f, 1.0}, {0.0f * scale.x + offset.x, 0.0f * scale.y + offset.y}, tint}, {{+1.0f, +1.0f, 1.0}, {1.0f * scale.x + offset.x, 0.0f * scale.y + offset.y}, tint}, }; locBufferData(0x8892, sizeof(locVertex) * 4, verts, 0x88E0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } void DrawDecal(const olc::DecalInstance& decal) override { SetDecalMode(decal.mode); if (decal.decal == nullptr) glBindTexture(GL_TEXTURE_2D, rendBlankQuad.Decal()->id); else glBindTexture(GL_TEXTURE_2D, decal.decal->id); locBindBuffer(0x8892, m_vbQuad); for (uint32_t i = 0; i < decal.points; i++) pVertexMem[i] = { { decal.pos[i].x, decal.pos[i].y, decal.w[i] }, { decal.uv[i].x, decal.uv[i].y }, decal.tint[i] }; locBufferData(0x8892, sizeof(locVertex) * decal.points, pVertexMem, 0x88E0); if (nDecalMode == DecalMode::WIREFRAME) glDrawArrays(GL_LINE_LOOP, 0, decal.points); else glDrawArrays(GL_TRIANGLE_FAN, 0, decal.points); } uint32_t CreateTexture(const uint32_t width, const uint32_t height, const bool filtered, const bool clamp) override { UNUSED(width); UNUSED(height); uint32_t id = 0; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); if (filtered) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } if (clamp) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } #if !defined(OLC_PLATFORM_EMSCRIPTEN) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); #endif return id; } uint32_t DeleteTexture(const uint32_t id) override { glDeleteTextures(1, &id); return id; } void UpdateTexture(uint32_t id, olc::Sprite* spr) override { UNUSED(id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, spr->width, spr->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData()); } void ReadTexture(uint32_t id, olc::Sprite* spr) override { glReadPixels(0, 0, spr->width, spr->height, GL_RGBA, GL_UNSIGNED_BYTE, spr->GetData()); } void ApplyTexture(uint32_t id) override { glBindTexture(GL_TEXTURE_2D, id); } void ClearBuffer(olc::Pixel p, bool bDepth) override { glClearColor(float(p.r) / 255.0f, float(p.g) / 255.0f, float(p.b) / 255.0f, float(p.a) / 255.0f); glClear(GL_COLOR_BUFFER_BIT); if (bDepth) glClear(GL_DEPTH_BUFFER_BIT); } void UpdateViewport(const olc::vi2d& pos, const olc::vi2d& size) override { #if defined(OLC_PLATFORM_GLUT) if (!mFullScreen) glutReshapeWindow(size.x, size.y); #else glViewport(pos.x, pos.y, size.x, size.y); #endif } }; } #endif // O------------------------------------------------------------------------------O // | END RENDERER: OpenGL 3.3 (3.0 es) (sh-sh-sh-shaders....) | // O------------------------------------------------------------------------------O #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine Image loaders | // O------------------------------------------------------------------------------O #pragma region image_gdi // O------------------------------------------------------------------------------O // | START IMAGE LOADER: GDI+, Windows Only, always exists, a little slow | // O------------------------------------------------------------------------------O #if defined(OLC_IMAGE_GDI) #define min(a, b) ((a < b) ? a : b) #define max(a, b) ((a > b) ? a : b) #include <objidl.h> #include <gdiplus.h> #if defined(__MINGW32__) // Thanks Gusgo & Dandistine, but c'mon mingw!! wtf?! #include <gdiplus/gdiplusinit.h> #else #include <gdiplusinit.h> #endif #include <shlwapi.h> #undef min #undef max #if !defined(__MINGW32__) #pragma comment(lib, "gdiplus.lib") #pragma comment(lib, "Shlwapi.lib") #endif namespace olc { // Thanks @MaGetzUb for this, which allows sprites to be defined // at construction, by initialising the GDI subsystem static class GDIPlusStartup { public: GDIPlusStartup() { Gdiplus::GdiplusStartupInput startupInput; GdiplusStartup(&token, &startupInput, NULL); } ULONG_PTR token; ~GDIPlusStartup() { // Well, MarcusTU thought this was important :D Gdiplus::GdiplusShutdown(token); } } gdistartup; class ImageLoader_GDIPlus : public olc::ImageLoader { private: std::wstring ConvertS2W(std::string s) { #ifdef __MINGW32__ wchar_t* buffer = new wchar_t[s.length() + 1]; mbstowcs(buffer, s.c_str(), s.length()); buffer[s.length()] = L'\0'; #else int count = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); wchar_t* buffer = new wchar_t[count]; MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, count); #endif std::wstring w(buffer); delete[] buffer; return w; } public: ImageLoader_GDIPlus() : ImageLoader() {} olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) override { // clear out existing sprite spr->pColData.clear(); // Open file UNUSED(pack); Gdiplus::Bitmap* bmp = nullptr; if (pack != nullptr) { // Load sprite from input stream ResourceBuffer rb = pack->GetFileBuffer(sImageFile); bmp = Gdiplus::Bitmap::FromStream(SHCreateMemStream((BYTE*)rb.vMemory.data(), UINT(rb.vMemory.size()))); } else { // Check file exists if (!_gfs::exists(sImageFile)) return olc::rcode::NO_FILE; // Load sprite from file bmp = Gdiplus::Bitmap::FromFile(ConvertS2W(sImageFile).c_str()); } if (bmp->GetLastStatus() != Gdiplus::Ok) return olc::rcode::FAIL; spr->width = bmp->GetWidth(); spr->height = bmp->GetHeight(); spr->pColData.resize(spr->width * spr->height); for (int y = 0; y < spr->height; y++) for (int x = 0; x < spr->width; x++) { Gdiplus::Color c; bmp->GetPixel(x, y, &c); spr->SetPixel(x, y, olc::Pixel(c.GetRed(), c.GetGreen(), c.GetBlue(), c.GetAlpha())); } delete bmp; return olc::rcode::OK; } olc::rcode SaveImageResource(olc::Sprite* spr, const std::string& sImageFile) override { return olc::rcode::OK; } }; } #endif // O------------------------------------------------------------------------------O // | END IMAGE LOADER: GDI+ | // O------------------------------------------------------------------------------O #pragma endregion #pragma region image_libpng // O------------------------------------------------------------------------------O // | START IMAGE LOADER: libpng, default on linux, requires -lpng (libpng-dev) | // O------------------------------------------------------------------------------O #if defined(OLC_IMAGE_LIBPNG) #include <png.h> namespace olc { void pngReadStream(png_structp pngPtr, png_bytep data, png_size_t length) { png_voidp a = png_get_io_ptr(pngPtr); ((std::istream*)a)->read((char*)data, length); } class ImageLoader_LibPNG : public olc::ImageLoader { public: ImageLoader_LibPNG() : ImageLoader() {} olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) override { UNUSED(pack); // clear out existing sprite spr->pColData.clear(); //////////////////////////////////////////////////////////////////////////// // Use libpng, Thanks to Guillaume Cottenceau // https://gist.github.com/niw/5963798 // Also reading png from streams // http://www.piko3d.net/tutorials/libpng-tutorial-loading-png-files-from-streams/ png_structp png; png_infop info; auto loadPNG = [&]() { png_read_info(png, info); png_byte color_type; png_byte bit_depth; png_bytep* row_pointers; spr->width = png_get_image_width(png, info); spr->height = png_get_image_height(png, info); color_type = png_get_color_type(png, info); bit_depth = png_get_bit_depth(png, info); if (bit_depth == 16) png_set_strip_16(png); if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png); if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_expand_gray_1_2_4_to_8(png); if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png); if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE) png_set_filler(png, 0xFF, PNG_FILLER_AFTER); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png); png_read_update_info(png, info); row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * spr->height); for (int y = 0; y < spr->height; y++) { row_pointers[y] = (png_byte*)malloc(png_get_rowbytes(png, info)); } png_read_image(png, row_pointers); //////////////////////////////////////////////////////////////////////////// // Create sprite array spr->pColData.resize(spr->width * spr->height); // Iterate through image rows, converting into sprite format for (int y = 0; y < spr->height; y++) { png_bytep row = row_pointers[y]; for (int x = 0; x < spr->width; x++) { png_bytep px = &(row[x * 4]); spr->SetPixel(x, y, Pixel(px[0], px[1], px[2], px[3])); } } for (int y = 0; y < spr->height; y++) // Thanks maksym33 free(row_pointers[y]); free(row_pointers); png_destroy_read_struct(&png, &info, nullptr); }; png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png) goto fail_load; info = png_create_info_struct(png); if (!info) goto fail_load; if (setjmp(png_jmpbuf(png))) goto fail_load; if (pack == nullptr) { FILE* f = fopen(sImageFile.c_str(), "rb"); if (!f) return olc::rcode::NO_FILE; png_init_io(png, f); loadPNG(); fclose(f); } else { ResourceBuffer rb = pack->GetFileBuffer(sImageFile); std::istream is(&rb); png_set_read_fn(png, (png_voidp)&is, pngReadStream); loadPNG(); } return olc::rcode::OK; fail_load: spr->width = 0; spr->height = 0; spr->pColData.clear(); return olc::rcode::FAIL; } olc::rcode SaveImageResource(olc::Sprite* spr, const std::string& sImageFile) override { return olc::rcode::OK; } }; } #endif // O------------------------------------------------------------------------------O // | END IMAGE LOADER: | // O------------------------------------------------------------------------------O #pragma endregion #pragma region image_stb // O------------------------------------------------------------------------------O // | START IMAGE LOADER: stb_image.h, all systems, very fast | // O------------------------------------------------------------------------------O // Thanks to Sean Barrett - https://github.com/nothings/stb/blob/master/stb_image.h // MIT License - Copyright(c) 2017 Sean Barrett // Note you need to download the above file into your project folder, and // #define OLC_IMAGE_STB // #define OLC_PGE_APPLICATION // #include "olcPixelGameEngine.h" #if defined(OLC_IMAGE_STB) #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" namespace olc { class ImageLoader_STB : public olc::ImageLoader { public: ImageLoader_STB() : ImageLoader() {} olc::rcode LoadImageResource(olc::Sprite* spr, const std::string& sImageFile, olc::ResourcePack* pack) override { UNUSED(pack); // clear out existing sprite spr->pColData.clear(); // Open file stbi_uc* bytes = nullptr; int w = 0, h = 0, cmp = 0; if (pack != nullptr) { ResourceBuffer rb = pack->GetFileBuffer(sImageFile); bytes = stbi_load_from_memory((unsigned char*)rb.vMemory.data(), rb.vMemory.size(), &w, &h, &cmp, 4); } else { // Check file exists if (!_gfs::exists(sImageFile)) return olc::rcode::NO_FILE; bytes = stbi_load(sImageFile.c_str(), &w, &h, &cmp, 4); } if (!bytes) return olc::rcode::FAIL; spr->width = w; spr->height = h; spr->pColData.resize(spr->width * spr->height); std::memcpy(spr->pColData.data(), bytes, spr->width * spr->height * 4); delete[] bytes; return olc::rcode::OK; } olc::rcode SaveImageResource(olc::Sprite* spr, const std::string& sImageFile) override { return olc::rcode::OK; } }; } #endif // O------------------------------------------------------------------------------O // | START IMAGE LOADER: stb_image.h | // O------------------------------------------------------------------------------O #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine Platforms | // O------------------------------------------------------------------------------O #pragma region platform_windows // O------------------------------------------------------------------------------O // | START PLATFORM: MICROSOFT WINDOWS XP, VISTA, 7, 8, 10 | // O------------------------------------------------------------------------------O #if defined(OLC_PLATFORM_WINAPI) #if defined(_WIN32) && !defined(__MINGW32__) #pragma comment(lib, "user32.lib") // Visual Studio Only #pragma comment(lib, "gdi32.lib") // For other Windows Compilers please add #pragma comment(lib, "opengl32.lib") // these libs to your linker input #endif namespace olc { class Platform_Windows : public olc::Platform { private: HWND olc_hWnd = nullptr; std::wstring wsAppName; std::wstring ConvertS2W(std::string s) { #ifdef __MINGW32__ wchar_t* buffer = new wchar_t[s.length() + 1]; mbstowcs(buffer, s.c_str(), s.length()); buffer[s.length()] = L'\0'; #else int count = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, NULL, 0); wchar_t* buffer = new wchar_t[count]; MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, buffer, count); #endif std::wstring w(buffer); delete[] buffer; return w; } public: virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; } virtual olc::rcode ApplicationCleanUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadCleanUp() override { renderer->DestroyDevice(); PostMessage(olc_hWnd, WM_DESTROY, 0, 0); return olc::OK; } virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override { if (renderer->CreateDevice({ olc_hWnd }, bFullScreen, bEnableVSYNC) == olc::rcode::OK) { renderer->UpdateViewport(vViewPos, vViewSize); return olc::rcode::OK; } else return olc::rcode::FAIL; } virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override { WNDCLASS wc; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.hInstance = GetModuleHandle(nullptr); wc.lpfnWndProc = olc_WindowEvent; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.lpszMenuName = nullptr; wc.hbrBackground = nullptr; wc.lpszClassName = olcT("OLC_PIXEL_GAME_ENGINE"); RegisterClass(&wc); // Define window furniture DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; DWORD dwStyle = WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_THICKFRAME; olc::vi2d vTopLeft = vWindowPos; // Handle Fullscreen if (bFullScreen) { dwExStyle = 0; dwStyle = WS_VISIBLE | WS_POPUP; HMONITOR hmon = MonitorFromWindow(olc_hWnd, MONITOR_DEFAULTTONEAREST); MONITORINFO mi = { sizeof(mi) }; if (!GetMonitorInfo(hmon, &mi)) return olc::rcode::FAIL; vWindowSize = { mi.rcMonitor.right, mi.rcMonitor.bottom }; vTopLeft.x = 0; vTopLeft.y = 0; } // Keep client size as requested RECT rWndRect = { 0, 0, vWindowSize.x, vWindowSize.y }; AdjustWindowRectEx(&rWndRect, dwStyle, FALSE, dwExStyle); int width = rWndRect.right - rWndRect.left; int height = rWndRect.bottom - rWndRect.top; olc_hWnd = CreateWindowEx(dwExStyle, olcT("OLC_PIXEL_GAME_ENGINE"), olcT(""), dwStyle, vTopLeft.x, vTopLeft.y, width, height, NULL, NULL, GetModuleHandle(nullptr), this); // Create Keyboard Mapping mapKeys[0x00] = Key::NONE; mapKeys[0x41] = Key::A; mapKeys[0x42] = Key::B; mapKeys[0x43] = Key::C; mapKeys[0x44] = Key::D; mapKeys[0x45] = Key::E; mapKeys[0x46] = Key::F; mapKeys[0x47] = Key::G; mapKeys[0x48] = Key::H; mapKeys[0x49] = Key::I; mapKeys[0x4A] = Key::J; mapKeys[0x4B] = Key::K; mapKeys[0x4C] = Key::L; mapKeys[0x4D] = Key::M; mapKeys[0x4E] = Key::N; mapKeys[0x4F] = Key::O; mapKeys[0x50] = Key::P; mapKeys[0x51] = Key::Q; mapKeys[0x52] = Key::R; mapKeys[0x53] = Key::S; mapKeys[0x54] = Key::T; mapKeys[0x55] = Key::U; mapKeys[0x56] = Key::V; mapKeys[0x57] = Key::W; mapKeys[0x58] = Key::X; mapKeys[0x59] = Key::Y; mapKeys[0x5A] = Key::Z; mapKeys[VK_F1] = Key::F1; mapKeys[VK_F2] = Key::F2; mapKeys[VK_F3] = Key::F3; mapKeys[VK_F4] = Key::F4; mapKeys[VK_F5] = Key::F5; mapKeys[VK_F6] = Key::F6; mapKeys[VK_F7] = Key::F7; mapKeys[VK_F8] = Key::F8; mapKeys[VK_F9] = Key::F9; mapKeys[VK_F10] = Key::F10; mapKeys[VK_F11] = Key::F11; mapKeys[VK_F12] = Key::F12; mapKeys[VK_DOWN] = Key::DOWN; mapKeys[VK_LEFT] = Key::LEFT; mapKeys[VK_RIGHT] = Key::RIGHT; mapKeys[VK_UP] = Key::UP; mapKeys[VK_RETURN] = Key::ENTER; //mapKeys[VK_RETURN] = Key::RETURN; mapKeys[VK_BACK] = Key::BACK; mapKeys[VK_ESCAPE] = Key::ESCAPE; mapKeys[VK_RETURN] = Key::ENTER; mapKeys[VK_PAUSE] = Key::PAUSE; mapKeys[VK_SCROLL] = Key::SCROLL; mapKeys[VK_TAB] = Key::TAB; mapKeys[VK_DELETE] = Key::DEL; mapKeys[VK_HOME] = Key::HOME; mapKeys[VK_END] = Key::END; mapKeys[VK_PRIOR] = Key::PGUP; mapKeys[VK_NEXT] = Key::PGDN; mapKeys[VK_INSERT] = Key::INS; mapKeys[VK_SHIFT] = Key::SHIFT; mapKeys[VK_CONTROL] = Key::CTRL; mapKeys[VK_SPACE] = Key::SPACE; mapKeys[0x30] = Key::K0; mapKeys[0x31] = Key::K1; mapKeys[0x32] = Key::K2; mapKeys[0x33] = Key::K3; mapKeys[0x34] = Key::K4; mapKeys[0x35] = Key::K5; mapKeys[0x36] = Key::K6; mapKeys[0x37] = Key::K7; mapKeys[0x38] = Key::K8; mapKeys[0x39] = Key::K9; mapKeys[VK_NUMPAD0] = Key::NP0; mapKeys[VK_NUMPAD1] = Key::NP1; mapKeys[VK_NUMPAD2] = Key::NP2; mapKeys[VK_NUMPAD3] = Key::NP3; mapKeys[VK_NUMPAD4] = Key::NP4; mapKeys[VK_NUMPAD5] = Key::NP5; mapKeys[VK_NUMPAD6] = Key::NP6; mapKeys[VK_NUMPAD7] = Key::NP7; mapKeys[VK_NUMPAD8] = Key::NP8; mapKeys[VK_NUMPAD9] = Key::NP9; mapKeys[VK_MULTIPLY] = Key::NP_MUL; mapKeys[VK_ADD] = Key::NP_ADD; mapKeys[VK_DIVIDE] = Key::NP_DIV; mapKeys[VK_SUBTRACT] = Key::NP_SUB; mapKeys[VK_DECIMAL] = Key::NP_DECIMAL; // Thanks scripticuk mapKeys[VK_OEM_1] = Key::OEM_1; // On US and UK keyboards this is the ';:' key mapKeys[VK_OEM_2] = Key::OEM_2; // On US and UK keyboards this is the '/?' key mapKeys[VK_OEM_3] = Key::OEM_3; // On US keyboard this is the '~' key mapKeys[VK_OEM_4] = Key::OEM_4; // On US and UK keyboards this is the '[{' key mapKeys[VK_OEM_5] = Key::OEM_5; // On US keyboard this is '\|' key. mapKeys[VK_OEM_6] = Key::OEM_6; // On US and UK keyboards this is the ']}' key mapKeys[VK_OEM_7] = Key::OEM_7; // On US keyboard this is the single/double quote key. On UK, this is the single quote/@ symbol key mapKeys[VK_OEM_8] = Key::OEM_8; // miscellaneous characters. Varies by keyboard mapKeys[VK_OEM_PLUS] = Key::EQUALS; // the '+' key on any keyboard mapKeys[VK_OEM_COMMA] = Key::COMMA; // the comma key on any keyboard mapKeys[VK_OEM_MINUS] = Key::MINUS; // the minus key on any keyboard mapKeys[VK_OEM_PERIOD] = Key::PERIOD; // the period key on any keyboard mapKeys[VK_CAPITAL] = Key::CAPS_LOCK; return olc::OK; } virtual olc::rcode SetWindowTitle(const std::string& s) override { #ifdef UNICODE SetWindowText(olc_hWnd, ConvertS2W(s).c_str()); #else SetWindowText(olc_hWnd, s.c_str()); #endif return olc::OK; } virtual olc::rcode StartSystemEventLoop() override { MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return olc::OK; } virtual olc::rcode HandleSystemEvent() override { return olc::rcode::FAIL; } // Windows Event Handler - this is statically connected to the windows event system static LRESULT CALLBACK olc_WindowEvent(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_MOUSEMOVE: { // Thanks @ForAbby (Discord) uint16_t x = lParam & 0xFFFF; uint16_t y = (lParam >> 16) & 0xFFFF; int16_t ix = *(int16_t*)&x; int16_t iy = *(int16_t*)&y; ptrPGE->olc_UpdateMouse(ix, iy); return 0; } case WM_SIZE: ptrPGE->olc_UpdateWindowSize(lParam & 0xFFFF, (lParam >> 16) & 0xFFFF); return 0; case WM_MOUSEWHEEL: ptrPGE->olc_UpdateMouseWheel(GET_WHEEL_DELTA_WPARAM(wParam)); return 0; case WM_MOUSELEAVE: ptrPGE->olc_UpdateMouseFocus(false); return 0; case WM_SETFOCUS: ptrPGE->olc_UpdateKeyFocus(true); return 0; case WM_KILLFOCUS: ptrPGE->olc_UpdateKeyFocus(false); return 0; case WM_KEYDOWN: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], true); return 0; case WM_KEYUP: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], false); return 0; case WM_SYSKEYDOWN: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], true); return 0; case WM_SYSKEYUP: ptrPGE->olc_UpdateKeyState(mapKeys[wParam], false); return 0; case WM_LBUTTONDOWN:ptrPGE->olc_UpdateMouseState(0, true); return 0; case WM_LBUTTONUP: ptrPGE->olc_UpdateMouseState(0, false); return 0; case WM_RBUTTONDOWN:ptrPGE->olc_UpdateMouseState(1, true); return 0; case WM_RBUTTONUP: ptrPGE->olc_UpdateMouseState(1, false); return 0; case WM_MBUTTONDOWN:ptrPGE->olc_UpdateMouseState(2, true); return 0; case WM_MBUTTONUP: ptrPGE->olc_UpdateMouseState(2, false); return 0; case WM_CLOSE: ptrPGE->olc_Terminate(); return 0; case WM_DESTROY: PostQuitMessage(0); DestroyWindow(hWnd); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } }; } #endif // O------------------------------------------------------------------------------O // | END PLATFORM: MICROSOFT WINDOWS XP, VISTA, 7, 8, 10 | // O------------------------------------------------------------------------------O #pragma endregion #pragma region platform_linux // O------------------------------------------------------------------------------O // | START PLATFORM: LINUX | // O------------------------------------------------------------------------------O #if defined(OLC_PLATFORM_X11) namespace olc { class Platform_Linux : public olc::Platform { private: X11::Display* olc_Display = nullptr; X11::Window olc_WindowRoot; X11::Window olc_Window; X11::XVisualInfo* olc_VisualInfo; X11::Colormap olc_ColourMap; X11::XSetWindowAttributes olc_SetWindowAttribs; public: virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; } virtual olc::rcode ApplicationCleanUp() override { XDestroyWindow(olc_Display, olc_Window); return olc::rcode::OK; } virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadCleanUp() override { renderer->DestroyDevice(); return olc::OK; } virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override { if (renderer->CreateDevice({ olc_Display, &olc_Window, olc_VisualInfo }, bFullScreen, bEnableVSYNC) == olc::rcode::OK) { renderer->UpdateViewport(vViewPos, vViewSize); return olc::rcode::OK; } else return olc::rcode::FAIL; } virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override { using namespace X11; XInitThreads(); // Grab the deafult display and window olc_Display = XOpenDisplay(NULL); olc_WindowRoot = DefaultRootWindow(olc_Display); // Based on the display capabilities, configure the appearance of the window GLint olc_GLAttribs[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; olc_VisualInfo = glXChooseVisual(olc_Display, 0, olc_GLAttribs); olc_ColourMap = XCreateColormap(olc_Display, olc_WindowRoot, olc_VisualInfo->visual, AllocNone); olc_SetWindowAttribs.colormap = olc_ColourMap; // Register which events we are interested in receiving olc_SetWindowAttribs.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | FocusChangeMask | StructureNotifyMask; // Create the window olc_Window = XCreateWindow(olc_Display, olc_WindowRoot, vWindowPos.x, vWindowPos.y, vWindowSize.x, vWindowSize.y, 0, olc_VisualInfo->depth, InputOutput, olc_VisualInfo->visual, CWColormap | CWEventMask, &olc_SetWindowAttribs); Atom wmDelete = XInternAtom(olc_Display, "WM_DELETE_WINDOW", true); XSetWMProtocols(olc_Display, olc_Window, &wmDelete, 1); XMapWindow(olc_Display, olc_Window); XStoreName(olc_Display, olc_Window, "OneLoneCoder.com - Pixel Game Engine"); if (bFullScreen) // Thanks DragonEye, again :D { Atom wm_state; Atom fullscreen; wm_state = XInternAtom(olc_Display, "_NET_WM_STATE", False); fullscreen = XInternAtom(olc_Display, "_NET_WM_STATE_FULLSCREEN", False); XEvent xev{ 0 }; xev.type = ClientMessage; xev.xclient.window = olc_Window; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = (bFullScreen ? 1 : 0); // the action (0: off, 1: on, 2: toggle) xev.xclient.data.l[1] = fullscreen; // first property to alter xev.xclient.data.l[2] = 0; // second property to alter xev.xclient.data.l[3] = 0; // source indication XMapWindow(olc_Display, olc_Window); XSendEvent(olc_Display, DefaultRootWindow(olc_Display), False, SubstructureRedirectMask | SubstructureNotifyMask, &xev); XFlush(olc_Display); XWindowAttributes gwa; XGetWindowAttributes(olc_Display, olc_Window, &gwa); vWindowSize.x = gwa.width; vWindowSize.y = gwa.height; } // Create Keyboard Mapping mapKeys[0x00] = Key::NONE; mapKeys[0x61] = Key::A; mapKeys[0x62] = Key::B; mapKeys[0x63] = Key::C; mapKeys[0x64] = Key::D; mapKeys[0x65] = Key::E; mapKeys[0x66] = Key::F; mapKeys[0x67] = Key::G; mapKeys[0x68] = Key::H; mapKeys[0x69] = Key::I; mapKeys[0x6A] = Key::J; mapKeys[0x6B] = Key::K; mapKeys[0x6C] = Key::L; mapKeys[0x6D] = Key::M; mapKeys[0x6E] = Key::N; mapKeys[0x6F] = Key::O; mapKeys[0x70] = Key::P; mapKeys[0x71] = Key::Q; mapKeys[0x72] = Key::R; mapKeys[0x73] = Key::S; mapKeys[0x74] = Key::T; mapKeys[0x75] = Key::U; mapKeys[0x76] = Key::V; mapKeys[0x77] = Key::W; mapKeys[0x78] = Key::X; mapKeys[0x79] = Key::Y; mapKeys[0x7A] = Key::Z; mapKeys[XK_F1] = Key::F1; mapKeys[XK_F2] = Key::F2; mapKeys[XK_F3] = Key::F3; mapKeys[XK_F4] = Key::F4; mapKeys[XK_F5] = Key::F5; mapKeys[XK_F6] = Key::F6; mapKeys[XK_F7] = Key::F7; mapKeys[XK_F8] = Key::F8; mapKeys[XK_F9] = Key::F9; mapKeys[XK_F10] = Key::F10; mapKeys[XK_F11] = Key::F11; mapKeys[XK_F12] = Key::F12; mapKeys[XK_Down] = Key::DOWN; mapKeys[XK_Left] = Key::LEFT; mapKeys[XK_Right] = Key::RIGHT; mapKeys[XK_Up] = Key::UP; mapKeys[XK_KP_Enter] = Key::ENTER; mapKeys[XK_Return] = Key::ENTER; mapKeys[XK_BackSpace] = Key::BACK; mapKeys[XK_Escape] = Key::ESCAPE; mapKeys[XK_Linefeed] = Key::ENTER; mapKeys[XK_Pause] = Key::PAUSE; mapKeys[XK_Scroll_Lock] = Key::SCROLL; mapKeys[XK_Tab] = Key::TAB; mapKeys[XK_Delete] = Key::DEL; mapKeys[XK_Home] = Key::HOME; mapKeys[XK_End] = Key::END; mapKeys[XK_Page_Up] = Key::PGUP; mapKeys[XK_Page_Down] = Key::PGDN; mapKeys[XK_Insert] = Key::INS; mapKeys[XK_Shift_L] = Key::SHIFT; mapKeys[XK_Shift_R] = Key::SHIFT; mapKeys[XK_Control_L] = Key::CTRL; mapKeys[XK_Control_R] = Key::CTRL; mapKeys[XK_space] = Key::SPACE; mapKeys[XK_period] = Key::PERIOD; mapKeys[XK_0] = Key::K0; mapKeys[XK_1] = Key::K1; mapKeys[XK_2] = Key::K2; mapKeys[XK_3] = Key::K3; mapKeys[XK_4] = Key::K4; mapKeys[XK_5] = Key::K5; mapKeys[XK_6] = Key::K6; mapKeys[XK_7] = Key::K7; mapKeys[XK_8] = Key::K8; mapKeys[XK_9] = Key::K9; mapKeys[XK_KP_0] = Key::NP0; mapKeys[XK_KP_1] = Key::NP1; mapKeys[XK_KP_2] = Key::NP2; mapKeys[XK_KP_3] = Key::NP3; mapKeys[XK_KP_4] = Key::NP4; mapKeys[XK_KP_5] = Key::NP5; mapKeys[XK_KP_6] = Key::NP6; mapKeys[XK_KP_7] = Key::NP7; mapKeys[XK_KP_8] = Key::NP8; mapKeys[XK_KP_9] = Key::NP9; mapKeys[XK_KP_Multiply] = Key::NP_MUL; mapKeys[XK_KP_Add] = Key::NP_ADD; mapKeys[XK_KP_Divide] = Key::NP_DIV; mapKeys[XK_KP_Subtract] = Key::NP_SUB; mapKeys[XK_KP_Decimal] = Key::NP_DECIMAL; // These keys vary depending on the keyboard. I've included comments for US and UK keyboard layouts mapKeys[XK_semicolon] = Key::OEM_1; // On US and UK keyboards this is the ';:' key mapKeys[XK_slash] = Key::OEM_2; // On US and UK keyboards this is the '/?' key mapKeys[XK_asciitilde] = Key::OEM_3; // On US keyboard this is the '~' key mapKeys[XK_bracketleft] = Key::OEM_4; // On US and UK keyboards this is the '[{' key mapKeys[XK_backslash] = Key::OEM_5; // On US keyboard this is '\|' key. mapKeys[XK_bracketright] = Key::OEM_6; // On US and UK keyboards this is the ']}' key mapKeys[XK_apostrophe] = Key::OEM_7; // On US keyboard this is the single/double quote key. On UK, this is the single quote/@ symbol key mapKeys[XK_numbersign] = Key::OEM_8; // miscellaneous characters. Varies by keyboard. I believe this to be the '#~' key on UK keyboards mapKeys[XK_equal] = Key::EQUALS; // the '+' key on any keyboard mapKeys[XK_comma] = Key::COMMA; // the comma key on any keyboard mapKeys[XK_minus] = Key::MINUS; // the minus key on any keyboard mapKeys[XK_Caps_Lock] = Key::CAPS_LOCK; return olc::OK; } virtual olc::rcode SetWindowTitle(const std::string& s) override { X11::XStoreName(olc_Display, olc_Window, s.c_str()); return olc::OK; } virtual olc::rcode StartSystemEventLoop() override { return olc::OK; } virtual olc::rcode HandleSystemEvent() override { using namespace X11; // Handle Xlib Message Loop - we do this in the // same thread that OpenGL was created so we dont // need to worry too much about multithreading with X11 XEvent xev; while (XPending(olc_Display)) { XNextEvent(olc_Display, &xev); if (xev.type == Expose) { XWindowAttributes gwa; XGetWindowAttributes(olc_Display, olc_Window, &gwa); ptrPGE->olc_UpdateWindowSize(gwa.width, gwa.height); } else if (xev.type == ConfigureNotify) { XConfigureEvent xce = xev.xconfigure; ptrPGE->olc_UpdateWindowSize(xce.width, xce.height); } else if (xev.type == KeyPress) { KeySym sym = XLookupKeysym(&xev.xkey, 0); ptrPGE->olc_UpdateKeyState(mapKeys[sym], true); XKeyEvent* e = (XKeyEvent*)&xev; // Because DragonEye loves numpads XLookupString(e, NULL, 0, &sym, NULL); ptrPGE->olc_UpdateKeyState(mapKeys[sym], true); } else if (xev.type == KeyRelease) { KeySym sym = XLookupKeysym(&xev.xkey, 0); ptrPGE->olc_UpdateKeyState(mapKeys[sym], false); XKeyEvent* e = (XKeyEvent*)&xev; XLookupString(e, NULL, 0, &sym, NULL); ptrPGE->olc_UpdateKeyState(mapKeys[sym], false); } else if (xev.type == ButtonPress) { switch (xev.xbutton.button) { case 1: ptrPGE->olc_UpdateMouseState(0, true); break; case 2: ptrPGE->olc_UpdateMouseState(2, true); break; case 3: ptrPGE->olc_UpdateMouseState(1, true); break; case 4: ptrPGE->olc_UpdateMouseWheel(120); break; case 5: ptrPGE->olc_UpdateMouseWheel(-120); break; default: break; } } else if (xev.type == ButtonRelease) { switch (xev.xbutton.button) { case 1: ptrPGE->olc_UpdateMouseState(0, false); break; case 2: ptrPGE->olc_UpdateMouseState(2, false); break; case 3: ptrPGE->olc_UpdateMouseState(1, false); break; default: break; } } else if (xev.type == MotionNotify) { ptrPGE->olc_UpdateMouse(xev.xmotion.x, xev.xmotion.y); } else if (xev.type == FocusIn) { ptrPGE->olc_UpdateKeyFocus(true); } else if (xev.type == FocusOut) { ptrPGE->olc_UpdateKeyFocus(false); } else if (xev.type == ClientMessage) { ptrPGE->olc_Terminate(); } } return olc::OK; } }; } #endif // O------------------------------------------------------------------------------O // | END PLATFORM: LINUX | // O------------------------------------------------------------------------------O #pragma endregion #pragma region platform_glut // O------------------------------------------------------------------------------O // | START PLATFORM: GLUT (used to make it simple for Apple) | // O------------------------------------------------------------------------------O // // VERY IMPORTANT!!! The Apple port was originally created by @Mumflr (discord) // and the repo for the development of this project can be found here: // https://github.com/MumflrFumperdink/olcPGEMac which contains maccy goodness // and support on how to setup your build environment. // // "MASSIVE MASSIVE THANKS TO MUMFLR" - Javidx9 #if defined(OLC_PLATFORM_GLUT) namespace olc { class Platform_GLUT : public olc::Platform { public: static std::atomic<bool>* bActiveRef; virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; } virtual olc::rcode ApplicationCleanUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadCleanUp() override { renderer->DestroyDevice(); return olc::OK; } virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override { if (renderer->CreateDevice({}, bFullScreen, bEnableVSYNC) == olc::rcode::OK) { renderer->UpdateViewport(vViewPos, vViewSize); return olc::rcode::OK; } else return olc::rcode::FAIL; } static void ExitMainLoop() { if (!ptrPGE->OnUserDestroy()) { *bActiveRef = true; return; } platform->ThreadCleanUp(); platform->ApplicationCleanUp(); exit(0); } static void ThreadFunct() { if (!*bActiveRef) { ExitMainLoop(); return; } glutPostRedisplay(); } static void DrawFunct() { ptrPGE->olc_CoreUpdate(); } virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override { renderer->PrepareDevice(); if (bFullScreen) { vWindowSize.x = glutGet(GLUT_SCREEN_WIDTH); vWindowSize.y = glutGet(GLUT_SCREEN_HEIGHT); glutFullScreen(); } if (vWindowSize.x > glutGet(GLUT_SCREEN_WIDTH) || vWindowSize.y > glutGet(GLUT_SCREEN_HEIGHT)) { perror("ERROR: The specified window dimensions do not fit on your screen\n"); return olc::FAIL; } // Create Keyboard Mapping mapKeys[0x00] = Key::NONE; mapKeys['A'] = Key::A; mapKeys['B'] = Key::B; mapKeys['C'] = Key::C; mapKeys['D'] = Key::D; mapKeys['E'] = Key::E; mapKeys['F'] = Key::F; mapKeys['G'] = Key::G; mapKeys['H'] = Key::H; mapKeys['I'] = Key::I; mapKeys['J'] = Key::J; mapKeys['K'] = Key::K; mapKeys['L'] = Key::L; mapKeys['M'] = Key::M; mapKeys['N'] = Key::N; mapKeys['O'] = Key::O; mapKeys['P'] = Key::P; mapKeys['Q'] = Key::Q; mapKeys['R'] = Key::R; mapKeys['S'] = Key::S; mapKeys['T'] = Key::T; mapKeys['U'] = Key::U; mapKeys['V'] = Key::V; mapKeys['W'] = Key::W; mapKeys['X'] = Key::X; mapKeys['Y'] = Key::Y; mapKeys['Z'] = Key::Z; mapKeys[GLUT_KEY_F1] = Key::F1; mapKeys[GLUT_KEY_F2] = Key::F2; mapKeys[GLUT_KEY_F3] = Key::F3; mapKeys[GLUT_KEY_F4] = Key::F4; mapKeys[GLUT_KEY_F5] = Key::F5; mapKeys[GLUT_KEY_F6] = Key::F6; mapKeys[GLUT_KEY_F7] = Key::F7; mapKeys[GLUT_KEY_F8] = Key::F8; mapKeys[GLUT_KEY_F9] = Key::F9; mapKeys[GLUT_KEY_F10] = Key::F10; mapKeys[GLUT_KEY_F11] = Key::F11; mapKeys[GLUT_KEY_F12] = Key::F12; mapKeys[GLUT_KEY_DOWN] = Key::DOWN; mapKeys[GLUT_KEY_LEFT] = Key::LEFT; mapKeys[GLUT_KEY_RIGHT] = Key::RIGHT; mapKeys[GLUT_KEY_UP] = Key::UP; mapKeys[13] = Key::ENTER; mapKeys[127] = Key::BACK; mapKeys[27] = Key::ESCAPE; mapKeys[9] = Key::TAB; mapKeys[GLUT_KEY_HOME] = Key::HOME; mapKeys[GLUT_KEY_END] = Key::END; mapKeys[GLUT_KEY_PAGE_UP] = Key::PGUP; mapKeys[GLUT_KEY_PAGE_DOWN] = Key::PGDN; mapKeys[GLUT_KEY_INSERT] = Key::INS; mapKeys[32] = Key::SPACE; mapKeys[46] = Key::PERIOD; mapKeys[48] = Key::K0; mapKeys[49] = Key::K1; mapKeys[50] = Key::K2; mapKeys[51] = Key::K3; mapKeys[52] = Key::K4; mapKeys[53] = Key::K5; mapKeys[54] = Key::K6; mapKeys[55] = Key::K7; mapKeys[56] = Key::K8; mapKeys[57] = Key::K9; // NOTE: MISSING KEYS :O glutKeyboardFunc([](unsigned char key, int x, int y) -> void { switch (glutGetModifiers()) { case 0: //This is when there are no modifiers if ('a' <= key && key <= 'z') key -= 32; break; case GLUT_ACTIVE_SHIFT: ptrPGE->olc_UpdateKeyState(Key::SHIFT, true); break; case GLUT_ACTIVE_CTRL: if ('a' <= key && key <= 'z') key -= 32; ptrPGE->olc_UpdateKeyState(Key::CTRL, true); break; case GLUT_ACTIVE_ALT: if ('a' <= key && key <= 'z') key -= 32; break; } if (mapKeys[key]) ptrPGE->olc_UpdateKeyState(mapKeys[key], true); }); glutKeyboardUpFunc([](unsigned char key, int x, int y) -> void { switch (glutGetModifiers()) { case 0: //This is when there are no modifiers if ('a' <= key && key <= 'z') key -= 32; break; case GLUT_ACTIVE_SHIFT: ptrPGE->olc_UpdateKeyState(Key::SHIFT, false); break; case GLUT_ACTIVE_CTRL: if ('a' <= key && key <= 'z') key -= 32; ptrPGE->olc_UpdateKeyState(Key::CTRL, false); break; case GLUT_ACTIVE_ALT: if ('a' <= key && key <= 'z') key -= 32; //No ALT in PGE break; } if (mapKeys[key]) ptrPGE->olc_UpdateKeyState(mapKeys[key], false); }); //Special keys glutSpecialFunc([](int key, int x, int y) -> void { if (mapKeys[key]) ptrPGE->olc_UpdateKeyState(mapKeys[key], true); }); glutSpecialUpFunc([](int key, int x, int y) -> void { if (mapKeys[key]) ptrPGE->olc_UpdateKeyState(mapKeys[key], false); }); glutMouseFunc([](int button, int state, int x, int y) -> void { switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_UP) ptrPGE->olc_UpdateMouseState(0, false); else if (state == GLUT_DOWN) ptrPGE->olc_UpdateMouseState(0, true); break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_UP) ptrPGE->olc_UpdateMouseState(2, false); else if (state == GLUT_DOWN) ptrPGE->olc_UpdateMouseState(2, true); break; case GLUT_RIGHT_BUTTON: if (state == GLUT_UP) ptrPGE->olc_UpdateMouseState(1, false); else if (state == GLUT_DOWN) ptrPGE->olc_UpdateMouseState(1, true); break; } }); auto mouseMoveCall = [](int x, int y) -> void { ptrPGE->olc_UpdateMouse(x, y); }; glutMotionFunc(mouseMoveCall); glutPassiveMotionFunc(mouseMoveCall); glutEntryFunc([](int state) -> void { if (state == GLUT_ENTERED) ptrPGE->olc_UpdateKeyFocus(true); else if (state == GLUT_LEFT) ptrPGE->olc_UpdateKeyFocus(false); }); glutDisplayFunc(DrawFunct); glutIdleFunc(ThreadFunct); return olc::OK; } virtual olc::rcode SetWindowTitle(const std::string& s) override { glutSetWindowTitle(s.c_str()); return olc::OK; } virtual olc::rcode StartSystemEventLoop() override { glutMainLoop(); return olc::OK; } virtual olc::rcode HandleSystemEvent() override { return olc::OK; } }; std::atomic<bool>* Platform_GLUT::bActiveRef{ nullptr }; //Custom Start olc::rcode PixelGameEngine::Start() { if (platform->ApplicationStartUp() != olc::OK) return olc::FAIL; // Construct the window if (platform->CreateWindowPane({ 30,30 }, vWindowSize, bFullScreen) != olc::OK) return olc::FAIL; olc_UpdateWindowSize(vWindowSize.x, vWindowSize.y); if (platform->ThreadStartUp() == olc::FAIL) return olc::FAIL; olc_PrepareEngine(); if (!OnUserCreate()) return olc::FAIL; Platform_GLUT::bActiveRef = &bAtomActive; glutWMCloseFunc(Platform_GLUT::ExitMainLoop); bAtomActive = true; platform->StartSystemEventLoop(); //This code will not even be run but why not if (platform->ApplicationCleanUp() != olc::OK) return olc::FAIL; return olc::OK; } } #endif // O------------------------------------------------------------------------------O // | END PLATFORM: GLUT | // O------------------------------------------------------------------------------O #pragma endregion #pragma region platform_emscripten // O------------------------------------------------------------------------------O // | START PLATFORM: Emscripten - Totally Game Changing... | // O------------------------------------------------------------------------------O // // Firstly a big mega thank you to members of the OLC Community for sorting this // out. Making a browser compatible version has been a priority for quite some // time, but I lacked the expertise to do it. This awesome feature is possible // because a group of former strangers got together and formed friendships over // their shared passion for code. If anything demonstrates how powerful helping // each other can be, it's this. - Javidx9 // Emscripten Platform: MaGetzUb, Moros1138, Slavka, Dandistine, Gorbit99, Bispoo // also: Ishidex, Gusgo99, SlicEnDicE, Alexio #if defined(OLC_PLATFORM_EMSCRIPTEN) #include <emscripten/html5.h> #include <emscripten/key_codes.h> extern "C" { EMSCRIPTEN_KEEPALIVE inline int olc_OnPageUnload() { olc::platform->ApplicationCleanUp(); return 0; } } namespace olc { class Platform_Emscripten : public olc::Platform { public: virtual olc::rcode ApplicationStartUp() override { return olc::rcode::OK; } virtual olc::rcode ApplicationCleanUp() override { ThreadCleanUp(); return olc::rcode::OK; } virtual olc::rcode ThreadStartUp() override { return olc::rcode::OK; } virtual olc::rcode ThreadCleanUp() override { renderer->DestroyDevice(); return olc::OK; } virtual olc::rcode CreateGraphics(bool bFullScreen, bool bEnableVSYNC, const olc::vi2d& vViewPos, const olc::vi2d& vViewSize) override { if (renderer->CreateDevice({}, bFullScreen, bEnableVSYNC) == olc::rcode::OK) { renderer->UpdateViewport(vViewPos, vViewSize); return olc::rcode::OK; } else return olc::rcode::FAIL; } virtual olc::rcode CreateWindowPane(const olc::vi2d& vWindowPos, olc::vi2d& vWindowSize, bool bFullScreen) override { emscripten_set_canvas_element_size("#canvas", vWindowSize.x, vWindowSize.y); mapKeys[DOM_PK_UNKNOWN] = Key::NONE; mapKeys[DOM_PK_A] = Key::A; mapKeys[DOM_PK_B] = Key::B; mapKeys[DOM_PK_C] = Key::C; mapKeys[DOM_PK_D] = Key::D; mapKeys[DOM_PK_E] = Key::E; mapKeys[DOM_PK_F] = Key::F; mapKeys[DOM_PK_G] = Key::G; mapKeys[DOM_PK_H] = Key::H; mapKeys[DOM_PK_I] = Key::I; mapKeys[DOM_PK_J] = Key::J; mapKeys[DOM_PK_K] = Key::K; mapKeys[DOM_PK_L] = Key::L; mapKeys[DOM_PK_M] = Key::M; mapKeys[DOM_PK_N] = Key::N; mapKeys[DOM_PK_O] = Key::O; mapKeys[DOM_PK_P] = Key::P; mapKeys[DOM_PK_Q] = Key::Q; mapKeys[DOM_PK_R] = Key::R; mapKeys[DOM_PK_S] = Key::S; mapKeys[DOM_PK_T] = Key::T; mapKeys[DOM_PK_U] = Key::U; mapKeys[DOM_PK_V] = Key::V; mapKeys[DOM_PK_W] = Key::W; mapKeys[DOM_PK_X] = Key::X; mapKeys[DOM_PK_Y] = Key::Y; mapKeys[DOM_PK_Z] = Key::Z; mapKeys[DOM_PK_0] = Key::K0; mapKeys[DOM_PK_1] = Key::K1; mapKeys[DOM_PK_2] = Key::K2; mapKeys[DOM_PK_3] = Key::K3; mapKeys[DOM_PK_4] = Key::K4; mapKeys[DOM_PK_5] = Key::K5; mapKeys[DOM_PK_6] = Key::K6; mapKeys[DOM_PK_7] = Key::K7; mapKeys[DOM_PK_8] = Key::K8; mapKeys[DOM_PK_9] = Key::K9; mapKeys[DOM_PK_F1] = Key::F1; mapKeys[DOM_PK_F2] = Key::F2; mapKeys[DOM_PK_F3] = Key::F3; mapKeys[DOM_PK_F4] = Key::F4; mapKeys[DOM_PK_F5] = Key::F5; mapKeys[DOM_PK_F6] = Key::F6; mapKeys[DOM_PK_F7] = Key::F7; mapKeys[DOM_PK_F8] = Key::F8; mapKeys[DOM_PK_F9] = Key::F9; mapKeys[DOM_PK_F10] = Key::F10; mapKeys[DOM_PK_F11] = Key::F11; mapKeys[DOM_PK_F12] = Key::F12; mapKeys[DOM_PK_ARROW_UP] = Key::UP; mapKeys[DOM_PK_ARROW_DOWN] = Key::DOWN; mapKeys[DOM_PK_ARROW_LEFT] = Key::LEFT; mapKeys[DOM_PK_ARROW_RIGHT] = Key::RIGHT; mapKeys[DOM_PK_SPACE] = Key::SPACE; mapKeys[DOM_PK_TAB] = Key::TAB; mapKeys[DOM_PK_SHIFT_LEFT] = Key::SHIFT; mapKeys[DOM_PK_SHIFT_RIGHT] = Key::SHIFT; mapKeys[DOM_PK_CONTROL_LEFT] = Key::CTRL; mapKeys[DOM_PK_CONTROL_RIGHT] = Key::CTRL; mapKeys[DOM_PK_INSERT] = Key::INS; mapKeys[DOM_PK_DELETE] = Key::DEL; mapKeys[DOM_PK_HOME] = Key::HOME; mapKeys[DOM_PK_END] = Key::END; mapKeys[DOM_PK_PAGE_UP] = Key::PGUP; mapKeys[DOM_PK_PAGE_DOWN] = Key::PGDN; mapKeys[DOM_PK_BACKSPACE] = Key::BACK; mapKeys[DOM_PK_ESCAPE] = Key::ESCAPE; mapKeys[DOM_PK_ENTER] = Key::ENTER; mapKeys[DOM_PK_NUMPAD_EQUAL] = Key::EQUALS; mapKeys[DOM_PK_NUMPAD_ENTER] = Key::ENTER; mapKeys[DOM_PK_PAUSE] = Key::PAUSE; mapKeys[DOM_PK_SCROLL_LOCK] = Key::SCROLL; mapKeys[DOM_PK_NUMPAD_0] = Key::NP0; mapKeys[DOM_PK_NUMPAD_1] = Key::NP1; mapKeys[DOM_PK_NUMPAD_2] = Key::NP2; mapKeys[DOM_PK_NUMPAD_3] = Key::NP3; mapKeys[DOM_PK_NUMPAD_4] = Key::NP4; mapKeys[DOM_PK_NUMPAD_5] = Key::NP5; mapKeys[DOM_PK_NUMPAD_6] = Key::NP6; mapKeys[DOM_PK_NUMPAD_7] = Key::NP7; mapKeys[DOM_PK_NUMPAD_8] = Key::NP8; mapKeys[DOM_PK_NUMPAD_9] = Key::NP9; mapKeys[DOM_PK_NUMPAD_MULTIPLY] = Key::NP_MUL; mapKeys[DOM_PK_NUMPAD_DIVIDE] = Key::NP_DIV; mapKeys[DOM_PK_NUMPAD_ADD] = Key::NP_ADD; mapKeys[DOM_PK_NUMPAD_SUBTRACT] = Key::NP_SUB; mapKeys[DOM_PK_NUMPAD_DECIMAL] = Key::NP_DECIMAL; mapKeys[DOM_PK_PERIOD] = Key::PERIOD; mapKeys[DOM_PK_EQUAL] = Key::EQUALS; mapKeys[DOM_PK_COMMA] = Key::COMMA; mapKeys[DOM_PK_MINUS] = Key::MINUS; mapKeys[DOM_PK_CAPS_LOCK] = Key::CAPS_LOCK; mapKeys[DOM_PK_SEMICOLON] = Key::OEM_1; mapKeys[DOM_PK_SLASH] = Key::OEM_2; mapKeys[DOM_PK_BACKQUOTE] = Key::OEM_3; mapKeys[DOM_PK_BRACKET_LEFT] = Key::OEM_4; mapKeys[DOM_PK_BACKSLASH] = Key::OEM_5; mapKeys[DOM_PK_BRACKET_RIGHT] = Key::OEM_6; mapKeys[DOM_PK_QUOTE] = Key::OEM_7; mapKeys[DOM_PK_BACKSLASH] = Key::OEM_8; // Keyboard Callbacks emscripten_set_keydown_callback("#canvas", 0, 1, keyboard_callback); emscripten_set_keyup_callback("#canvas", 0, 1, keyboard_callback); // Mouse Callbacks emscripten_set_wheel_callback("#canvas", 0, 1, wheel_callback); emscripten_set_mousedown_callback("#canvas", 0, 1, mouse_callback); emscripten_set_mouseup_callback("#canvas", 0, 1, mouse_callback); emscripten_set_mousemove_callback("#canvas", 0, 1, mouse_callback); // Touch Callbacks emscripten_set_touchstart_callback("#canvas", 0, 1, touch_callback); emscripten_set_touchmove_callback("#canvas", 0, 1, touch_callback); emscripten_set_touchend_callback("#canvas", 0, 1, touch_callback); // Canvas Focus Callbacks emscripten_set_blur_callback("#canvas", 0, 1, focus_callback); emscripten_set_focus_callback("#canvas", 0, 1, focus_callback); #pragma warning disable format EM_ASM( window.onunload = Module._olc_OnPageUnload; ); // IMPORTANT! - Sorry About This... // // In order to handle certain browser based events, such as resizing and // going to full screen, we have to effectively inject code into the container // running the PGE. Yes, I vomited about 11 times too when the others were // convincing me this is the future. Well, this isnt the future, and if it // were to be, I want no part of what must be a miserable distopian free // for all of anarchic code injection to get rudimentary events like "Resize()". // // Wake up people! Of course theres a spoon. There has to be to keep feeding // the giant web baby. // Fullscreen and Resize Observers EM_ASM({ // cache for reuse Module._olc_EmscriptenShellCss = "width: 100%; height: 70vh; margin-left: auto; margin-right: auto;"; // width / height = aspect ratio Module._olc_WindowAspectRatio = $0 / $1; Module.canvas.parentNode.addEventListener("resize", (e) => { if (e.defaultPrevented) { e.stopPropagation(); return; } var viewWidth = e.detail.width; var viewHeight = e.detail.width / Module._olc_WindowAspectRatio; if (viewHeight > e.detail.height) { viewHeight = e.detail.height; viewWidth = e.detail.height * Module._olc_WindowAspectRatio; } if (Module.canvas.parentNode.className == 'emscripten_border') Module.canvas.parentNode.style.cssText = Module._olc_EmscriptenShellCss + " width: " + viewWidth.toString() + "px; height: " + viewHeight.toString() + "px;"; Module.canvas.setAttribute("width", viewWidth); Module.canvas.setAttribute("height", viewHeight); if (document.fullscreenElement != null) { var top = (e.detail.height - viewHeight) / 2; var left = (e.detail.width - viewWidth) / 2; Module.canvas.style.position = "fixed"; Module.canvas.style.top = top.toString() + "px"; Module.canvas.style.left = left.toString() + "px"; Module.canvas.style.width = ""; Module.canvas.style.height = ""; } // trigger PGE update Module._olc_PGE_UpdateWindowSize(viewWidth, viewHeight); // this is really only needed when enter/exiting fullscreen Module.canvas.focus(); // prevent this event from ever affecting the document beyond this element e.stopPropagation(); }); // helper function to prevent repeating the same code everywhere Module._olc_ResizeCanvas = () => { // yes, we still have to wait, sigh.. setTimeout(() => { // if default template, stretch width as well if (Module.canvas.parentNode.className == 'emscripten_border') Module.canvas.parentNode.style.cssText = Module._olc_EmscriptenShellCss; // override it's styling so we can get it's stretched size Module.canvas.style.cssText = "width: 100%; height: 100%; outline: none;"; // setup custom resize event var resizeEvent = new CustomEvent('resize', { detail: { width: Module.canvas.clientWidth, height : Module.canvas.clientHeight }, bubbles : true, cancelable : true }); // trigger custom resize event on canvas element Module.canvas.dispatchEvent(resizeEvent); }, 50); }; // Disable Refresh Gesture on mobile document.body.style.cssText += " overscroll-behavior-y: contain;"; if (Module.canvas.parentNode.className == 'emscripten_border') { // force body to have no margin in emscripten's minimal shell document.body.style.margin = "0"; Module.canvas.parentNode.style.cssText = Module._olc_EmscriptenShellCss; } Module._olc_ResizeCanvas(); // observe and react to resizing of the container element var resizeObserver = new ResizeObserver((entries) => {Module._olc_ResizeCanvas();}).observe(Module.canvas.parentNode); // observe and react to changes that occur when entering/exiting fullscreen var mutationObserver = new MutationObserver((mutationsList, observer) => { // a change has occurred, let's check them out! for (var i = 0; i < mutationsList.length; i++) { // cycle through all of the newly added elements for (var j = 0; j < mutationsList[i].addedNodes.length; j++) { // if this element is a our canvas, trigger resize if (mutationsList[i].addedNodes[j].id == 'canvas') Module._olc_ResizeCanvas(); } } }).observe(Module.canvas.parentNode, { attributes: false, childList : true, subtree : false }); // add resize listener on window window.addEventListener("resize", (e) => { Module._olc_ResizeCanvas(); }); }, vWindowSize.x, vWindowSize.y); // Fullscreen and Resize Observers #pragma warning restore format return olc::rcode::OK; } // Interface PGE's UpdateWindowSize, for use in Javascript void UpdateWindowSize(int width, int height) { ptrPGE->olc_UpdateWindowSize(width, height); } //TY Gorbit static EM_BOOL focus_callback(int eventType, const EmscriptenFocusEvent* focusEvent, void* userData) { if (eventType == EMSCRIPTEN_EVENT_BLUR) { ptrPGE->olc_UpdateKeyFocus(false); ptrPGE->olc_UpdateMouseFocus(false); } else if (eventType == EMSCRIPTEN_EVENT_FOCUS) { ptrPGE->olc_UpdateKeyFocus(true); ptrPGE->olc_UpdateMouseFocus(true); } return 0; } //TY Moros static EM_BOOL keyboard_callback(int eventType, const EmscriptenKeyboardEvent* e, void* userData) { if (eventType == EMSCRIPTEN_EVENT_KEYDOWN) ptrPGE->olc_UpdateKeyState(mapKeys[emscripten_compute_dom_pk_code(e->code)], true); // THANK GOD!! for this compute function. And thanks Dandistine for pointing it out! if (eventType == EMSCRIPTEN_EVENT_KEYUP) ptrPGE->olc_UpdateKeyState(mapKeys[emscripten_compute_dom_pk_code(e->code)], false); //Consume keyboard events so that keys like F1 and F5 don't do weird things return EM_TRUE; } //TY Moros static EM_BOOL wheel_callback(int eventType, const EmscriptenWheelEvent* e, void* userData) { if (eventType == EMSCRIPTEN_EVENT_WHEEL) ptrPGE->olc_UpdateMouseWheel(-1 * e->deltaY); return EM_TRUE; } //TY Bispoo static EM_BOOL touch_callback(int eventType, const EmscriptenTouchEvent* e, void* userData) { // Move if (eventType == EMSCRIPTEN_EVENT_TOUCHMOVE) { ptrPGE->olc_UpdateMouse(e->touches->targetX, e->touches->targetY); } // Start if (eventType == EMSCRIPTEN_EVENT_TOUCHSTART) { ptrPGE->olc_UpdateMouse(e->touches->targetX, e->touches->targetY); ptrPGE->olc_UpdateMouseState(0, true); } // End if (eventType == EMSCRIPTEN_EVENT_TOUCHEND) { ptrPGE->olc_UpdateMouseState(0, false); } return EM_TRUE; } //TY Moros static EM_BOOL mouse_callback(int eventType, const EmscriptenMouseEvent* e, void* userData) { //Mouse Movement if (eventType == EMSCRIPTEN_EVENT_MOUSEMOVE) ptrPGE->olc_UpdateMouse(e->targetX, e->targetY); //Mouse button press if (e->button == 0) // left click { if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN) ptrPGE->olc_UpdateMouseState(0, true); else if (eventType == EMSCRIPTEN_EVENT_MOUSEUP) ptrPGE->olc_UpdateMouseState(0, false); } if (e->button == 2) // right click { if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN) ptrPGE->olc_UpdateMouseState(1, true); else if (eventType == EMSCRIPTEN_EVENT_MOUSEUP) ptrPGE->olc_UpdateMouseState(1, false); } if (e->button == 1) // middle click { if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN) ptrPGE->olc_UpdateMouseState(2, true); else if (eventType == EMSCRIPTEN_EVENT_MOUSEUP) ptrPGE->olc_UpdateMouseState(2, false); //at the moment only middle mouse needs to consume events. return EM_TRUE; } return EM_FALSE; } virtual olc::rcode SetWindowTitle(const std::string& s) override { emscripten_set_window_title(s.c_str()); return olc::OK; } virtual olc::rcode StartSystemEventLoop() override { return olc::OK; } virtual olc::rcode HandleSystemEvent() override { return olc::OK; } static void MainLoop() { olc::Platform::ptrPGE->olc_CoreUpdate(); if (!ptrPGE->olc_IsRunning()) { if (ptrPGE->OnUserDestroy()) { emscripten_cancel_main_loop(); platform->ApplicationCleanUp(); } else { ptrPGE->olc_Reanimate(); } } } }; //Emscripten needs a special Start function //Much of this is usually done in EngineThread, but that isn't used here olc::rcode PixelGameEngine::Start() { if (platform->ApplicationStartUp() != olc::OK) return olc::FAIL; // Construct the window if (platform->CreateWindowPane({ 30,30 }, vWindowSize, bFullScreen) != olc::OK) return olc::FAIL; olc_UpdateWindowSize(vWindowSize.x, vWindowSize.y); // Some implementations may form an event loop here if (platform->ThreadStartUp() == olc::FAIL) return olc::FAIL; // Do engine context specific initialisation olc_PrepareEngine(); // Consider the "thread" started bAtomActive = true; // Create user resources as part of this thread for (auto& ext : vExtensions) ext->OnBeforeUserCreate(); if (!OnUserCreate()) bAtomActive = false; for (auto& ext : vExtensions) ext->OnAfterUserCreate(); platform->StartSystemEventLoop(); //This causes a heap memory corruption in Emscripten for some reason //Platform_Emscripten::bActiveRef = &bAtomActive; emscripten_set_main_loop(&Platform_Emscripten::MainLoop, 0, 1); // Wait for thread to be exited if (platform->ApplicationCleanUp() != olc::OK) return olc::FAIL; return olc::OK; } } extern "C" { EMSCRIPTEN_KEEPALIVE inline void olc_PGE_UpdateWindowSize(int width, int height) { emscripten_set_canvas_element_size("#canvas", width, height); // Thanks slavka ((olc::Platform_Emscripten*)olc::platform.get())->UpdateWindowSize(width, height); } } #endif // O------------------------------------------------------------------------------O // | END PLATFORM: Emscripten | // O------------------------------------------------------------------------------O #pragma endregion // O------------------------------------------------------------------------------O // | olcPixelGameEngine Auto-Configuration | // O------------------------------------------------------------------------------O #pragma region pge_config namespace olc { void PixelGameEngine::olc_ConfigureSystem() { #if defined(OLC_IMAGE_GDI) olc::Sprite::loader = std::make_unique<olc::ImageLoader_GDIPlus>(); #endif #if defined(OLC_IMAGE_LIBPNG) olc::Sprite::loader = std::make_unique<olc::ImageLoader_LibPNG>(); #endif #if defined(OLC_IMAGE_STB) olc::Sprite::loader = std::make_unique<olc::ImageLoader_STB>(); #endif #if defined(OLC_IMAGE_CUSTOM_EX) olc::Sprite::loader = std::make_unique<OLC_IMAGE_CUSTOM_EX>(); #endif #if defined(OLC_PLATFORM_WINAPI) platform = std::make_unique<olc::Platform_Windows>(); #endif #if defined(OLC_PLATFORM_X11) platform = std::make_unique<olc::Platform_Linux>(); #endif #if defined(OLC_PLATFORM_GLUT) platform = std::make_unique<olc::Platform_GLUT>(); #endif #if defined(OLC_PLATFORM_EMSCRIPTEN) platform = std::make_unique<olc::Platform_Emscripten>(); #endif #if defined(OLC_PLATFORM_CUSTOM_EX) platform = std::make_unique<OLC_PLATFORM_CUSTOM_EX>(); #endif #if defined(OLC_GFX_OPENGL10) renderer = std::make_unique<olc::Renderer_OGL10>(); #endif #if defined(OLC_GFX_OPENGL33) renderer = std::make_unique<olc::Renderer_OGL33>(); #endif #if defined(OLC_GFX_OPENGLES2) renderer = std::make_unique<olc::Renderer_OGLES2>(); #endif #if defined(OLC_GFX_DIRECTX10) renderer = std::make_unique<olc::Renderer_DX10>(); #endif #if defined(OLC_GFX_DIRECTX11) renderer = std::make_unique<olc::Renderer_DX11>(); #endif #if defined(OLC_GFX_CUSTOM_EX) renderer = std::make_unique<OLC_RENDERER_CUSTOM_EX>(); #endif // Associate components with PGE instance platform->ptrPGE = this; renderer->ptrPGE = this; } } #pragma endregion #endif // End OLC_PGE_APPLICATION // O------------------------------------------------------------------------------O // | END OF OLC_PGE_APPLICATION | // O------------------------------------------------------------------------------O
[ "sebastian.alkstrand@gmail.com" ]
sebastian.alkstrand@gmail.com
b0321247ee3418b8d19598400d23e448655a6102
b51df35c7d975faba96466167d405f71545271b5
/server/src/main/c++/nativeMap/NativeMap.h
85060d6ea3c9767bbaf55411796f99dc83bec7d6
[ "Apache-2.0", "LicenseRef-scancode-unknown", "BSD-3-Clause", "MIT" ]
permissive
phrocker/accumulo
1cf0771a49f305db446a36595f4a9c6946320693
8b79dbffa3886ebc0419657d0fa0fbc997cd7929
refs/heads/ACCUMULO-3709
2023-08-31T14:34:50.746638
2015-04-12T20:03:15
2015-04-12T20:03:15
33,831,900
0
0
Apache-2.0
2022-07-01T17:39:01
2015-04-12T20:08:34
Java
UTF-8
C++
false
false
5,638
h
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __NATIVE_MAP_A12__ #define __NATIVE_MAP_A12__ #include "SubKey.h" #include "Field.h" #include "BlockAllocator.h" #include <map> #include <vector> #include <iostream> using namespace std; typedef map<SubKey, Field, std::less<SubKey>, BlockAllocator<std::pair<const SubKey, Field> > > ColumnMap; typedef map<Field, ColumnMap, std::less<Field>, BlockAllocator<std::pair<const Field, ColumnMap> > > RowMap; struct NativeMapData { LinkedBlockAllocator *lba; RowMap rowmap; int count; NativeMapData(int blockSize, int bigBlockSize):lba(new LinkedBlockAllocator(blockSize, bigBlockSize)), rowmap(RowMap(std::less<Field>(), BlockAllocator<std::pair<Field, ColumnMap> >(lba))){ this->lba = lba; } ~NativeMapData(){ rowmap.clear(); //if row map is not cleared here, it will be deconstructed after lba is deleted delete(lba); } }; struct Iterator { NativeMapData &nativeMap; RowMap::iterator rowIter; ColumnMap::iterator colIter; Iterator(NativeMapData &nm, int32_t *ia):nativeMap(nm){ rowIter = nativeMap.rowmap.begin(); if(rowIter == nativeMap.rowmap.end()){ return; } colIter = rowIter->second.begin(); skipAndFillIn(ia, true); } Iterator(NativeMapData &nm, Field &row, SubKey &sk, int32_t *ia):nativeMap(nm){ rowIter = nativeMap.rowmap.lower_bound(row); if(rowIter == nativeMap.rowmap.end()){ return; } //TODO use equals instead of compare if(rowIter->first.compare(row) == 0){ colIter = rowIter->second.lower_bound(sk); }else{ colIter = rowIter->second.begin(); } skipAndFillIn(ia, true); } bool skipAndFillIn(int32_t *ia, bool firstCall) { bool rowChanged = false; while(colIter == rowIter->second.end()){ rowIter++; rowChanged = true; if(rowIter == nativeMap.rowmap.end()){ return false; } colIter = rowIter->second.begin(); } ia[0] = (firstCall || rowChanged) ? rowIter->first.length() : -1; ia[1] = colIter->first.getCFLen(); ia[2] = colIter->first.getCQLen(); ia[3] = colIter->first.getCVLen(); ia[4] = colIter->first.isDeleted() ? 1 : 0; ia[5] = colIter->second.length(); ia[6] = colIter->first.getMC(); return true; } bool atEnd(){ return rowIter == nativeMap.rowmap.end(); } void advance(int32_t *ia){ colIter++; skipAndFillIn(ia, false); } }; struct NativeMap : public NativeMapData { NativeMap(int blockSize, int bigBlockSize):NativeMapData(blockSize, bigBlockSize){ count = 0; } ~NativeMap(){ } ColumnMap *startUpdate(JNIEnv * env, jbyteArray r){ Field row(lba, env, r); return startUpdate(row); } ColumnMap *startUpdate(const char *r){ Field row(lba, r); return startUpdate(row); } ColumnMap *startUpdate(Field &row){ //cout << "Starting update "<<row.toString()<<endl; pair<RowMap::iterator, bool> insertResult = rowmap.insert(pair<Field, ColumnMap>(row, ColumnMap(std::less<SubKey>(), BlockAllocator<std::pair<SubKey, Field> >(lba)))); if(!insertResult.second) row.clear(lba); return &(insertResult.first->second); } void update(ColumnMap *cm, JNIEnv *env, jbyteArray cf, jbyteArray cq, jbyteArray cv, jlong ts, jboolean del, jbyteArray val, jint mutationCount){ SubKey sk(lba, env, cf, cq, cv, ts, del, mutationCount); //cout << "Updating " << sk.toString() << " " << sk.getTimestamp() << " " << sk.isDeleted() << endl; //do not bother allocating value if not needed Field value(NULL, 0); pair<ColumnMap::iterator, bool> insertResult = cm->insert(pair<SubKey, Field>(sk, value)); if(insertResult.second){ insertResult.first->second = Field(lba, env, val); count++; }else{ sk.clear(lba); int valLen = env->GetArrayLength(val); if(valLen <= insertResult.first->second.length()){ insertResult.first->second.set(env, val, valLen); }else{ insertResult.first->second.clear(); insertResult.first->second = Field(lba, env, val, valLen); } } } void update(ColumnMap *cm, const char *cf, const char *cq, const char *cv, long ts, bool del, const char *val, int valLen, int mutationCount){ SubKey sk(lba, cf, cq, cv, ts, del, mutationCount); //do not bother allocating value if not needed Field value(NULL, 0); pair<ColumnMap::iterator, bool> insertResult = cm->insert(pair<SubKey, Field>(sk, value)); if(insertResult.second){ insertResult.first->second = Field(lba, val); count++; }else{ sk.clear(lba); if(insertResult.first->second.length() <= valLen){ insertResult.first->second.set(val, valLen); }else{ insertResult.first->second.clear(); insertResult.first->second = Field(lba, val); } } } Iterator *iterator(int32_t *ia){ return new Iterator(*this, ia); } Iterator *iterator(Field &row, SubKey &sk, int32_t *ia){ return new Iterator(*this, row, sk, ia); } int64_t getMemoryUsed(){ return lba->getMemoryUsed(); } }; #endif
[ "kturner@apache.org" ]
kturner@apache.org
f706677c9d57232bdf2af74dbfd513ecc23fff35
b7f81e00f68734cc35e53166a88b14c46ea61025
/src/any_callable.h
426ff5a1d157a9e5f59c5eda3622629630c3ff9e
[]
no_license
icepic/bass
ebfdd044db3ff5b4f193db53aa01ca363a950f60
44fc365528236fcf59b82ac4c2391eb23b433338
refs/heads/master
2022-11-22T03:57:29.140583
2020-07-24T08:00:39
2020-07-24T08:00:39
282,978,750
0
0
null
2020-07-27T18:12:24
2020-07-27T18:12:23
null
UTF-8
C++
false
false
2,626
h
#pragma once #include "defines.h" #include <any> #include <cstdint> #include <vector> template <int A, typename ARG> ARG get_arg(std::vector<std::any> const& vec, std::false_type) { static ARG empty{}; return A < vec.size() ? std::any_cast<ARG>(vec[A]) : empty; } template <int A, typename ARG> ARG get_arg(std::vector<std::any> const& vec, std::true_type) { return static_cast<ARG>(A < vec.size() ? std::any_cast<double>(vec[A]) : 0.0); } template <int A, typename ARG> ARG get_arg(std::vector<std::any> const& vec) { return get_arg<A, ARG>(vec, std::is_arithmetic<ARG>()); } template <typename T> std::any make_res(T&& v, std::true_type) { return std::any(static_cast<double>(v)); } template <typename T> std::any make_res(T&& v, std::false_type) { return std::any(v); } template <typename T> std::any make_res(T&& v) { return make_res(std::forward<T>(v), std::is_arithmetic<T>()); } struct FunctionCaller { virtual ~FunctionCaller() = default; virtual std::any call(std::vector<std::any> const&) const = 0; }; template <typename... X> struct FunctionCallerImpl; template <class FX, class R> struct FunctionCallerImpl<FX, R (FX::*)(std::vector<std::any> const&) const> : public FunctionCaller { explicit FunctionCallerImpl(FX const& f) : fn(f) {} FX fn; std::any call(std::vector<std::any> const& args) const override { return make_res(fn(args)); } }; template <class FX, class R, class... ARGS> struct FunctionCallerImpl<FX, R (FX::*)(ARGS...) const> : public FunctionCaller { explicit FunctionCallerImpl(FX const& f) : fn(f) {} FX fn; template <size_t... A> std::any apply(std::vector<std::any> const& vec, std::index_sequence<A...>) const { return make_res(fn(get_arg<A, ARGS>(vec)...)); } std::any call(std::vector<std::any> const& args) const override { return apply(args, std::make_index_sequence<sizeof...(ARGS)>()); } }; struct AnyCallable { std::unique_ptr<FunctionCaller> fc; std::any operator()(std::vector<std::any> const& args) const { return fc->call(args); } AnyCallable() = default; template <typename FX> void init(FX const& f) { fc = std::make_unique<FunctionCallerImpl<FX, decltype(&FX::operator())>>( f); } template <typename FX> explicit AnyCallable(FX const& f) { init(f); } template <typename FX> AnyCallable& operator=(FX const& f) { init(f); return *this; } };
[ "jonas@minnberg.se" ]
jonas@minnberg.se
1a3b59cc5aab6318192c10d76800856820c5bb7f
d26a306d0dc07a6a239e0f1e87e83e8d96712681
/GIFTSRC/main.cpp
83489823a93c7dcc606ae6cba68dd9d4ffc2351e
[]
no_license
umar-07/Competitive-Programming-questions-with-solutions
e08f8dbbebed7ab48c658c3f0ead19baf966f140
39353b923638dff2021923a8ea2f426cd94d2204
refs/heads/main
2023-05-19T03:05:48.669470
2021-06-16T18:36:22
2021-06-16T18:36:22
377,588,251
0
0
null
null
null
null
UTF-8
C++
false
false
1,812
cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int n; cin >> n; string s; cin >> s; int x=0, y=0; vector <char> arr; for(int i=0; i<n; i++) { if(s[i]=='U' || s[i]=='D') { arr.push_back(s[i]); for(int j=i+1; j<n; j++) { if(s[j]=='U' || s[j]=='D') { if(j==n-1) { i=n-1; break; } continue; } else { i=j; i--; break; } } } else { arr.push_back(s[i]); for(int j=i+1; j<n; j++) { if(s[j]=='L' || s[j]=='R') { if(j==n-1) { i=n-1; break; } continue; } else { i=j; i--; break; } } } } for(int i=0; i<arr.size(); i++) { if(arr[i]=='L') x--; else if(arr[i]=='R') x++; else if(arr[i]=='U') y++; else y--; } cout << x << " " << y << endl; } return 0; }
[ "mdu07100@gmail.com" ]
mdu07100@gmail.com
e1dfe14104e7b8280db08cf0ec69c0c09d530910
a6a4ac51edef099f81d101bcb50b339a87bc4946
/preproceso/src/matrix.h
d4e9d2320954c5712dbae901cef6ef0c6f65ffb0
[]
no_license
ne555/ocr
41efff60b0cf00f305ec46d365e5db6d4901df93
982371c27a6bfb8f9f95b14fd21db07f0118cb95
refs/heads/master
2021-01-10T21:44:18.778528
2011-11-15T00:57:34
2011-11-15T00:57:34
2,746,610
0
1
null
null
null
null
UTF-8
C++
false
false
1,392
h
#ifndef MATRIX_H #define MATRIX_H #include <vector> template<class T> struct matrix3d{ typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; //value_type *buffer; std::vector<value_type> buffer; size_t row, column, depth; matrix3d(size_t row, size_t column, size_t depth): row(row), column(column), depth(depth) { buffer.resize( row*column*depth ); } pointer data(){ return &buffer[0]; } reference operator()(size_t x, size_t y, size_t z){ return buffer[ x*column*depth + y*column + z ]; } size_t size() const{ return buffer.size(); } const_reference operator()(size_t x, size_t y, size_t z) const{ return buffer[ x*column*depth + y*column + z ]; } }; template<class T> struct matrix2d{ typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; //value_type *buffer; std::vector<value_type> buffer; size_t row, column; matrix2d(size_t row, size_t column): row(row), column(column) { buffer.resize( row*column ); } pointer data(){ return &buffer[0]; } reference operator()(size_t x, size_t y){ return buffer[ x*column + y ]; } size_t size() const{ return buffer.size(); } const_reference operator()(size_t x, size_t y) const{ return buffer[ x*column + y ]; } }; #endif
[ "wbedrij@gmail.com" ]
wbedrij@gmail.com
14bf52a6423b30f3054c812a784bc463f3d3ac4f
171cf4182089576641226d6b314de5420a4db3ce
/src/decoder16timeschar64.cpp
2694451014cb1924e51a4b3d6ae7c3777d26dc07
[ "MIT" ]
permissive
leroythelegend/pcars_nn
a8df81184f8401334bd095f5910b33794a137fb2
bf6cd55b41741ebec59cd72a82aef9906e816bc8
refs/heads/master
2022-12-16T06:55:32.430221
2020-09-19T07:32:14
2020-09-19T07:32:14
296,807,099
0
0
MIT
2020-09-19T07:32:15
2020-09-19T07:05:12
C++
UTF-8
C++
false
false
1,047
cpp
#include "decoder16timeschar64.h" namespace pcars { Decoder16Times64Char::Decoder16Times64Char() { add(&first_); add(&second_); add(&third_); add(&forth_); add(&fith_); add(&sixth_); add(&seventh_); add(&eightth_); add(&nineth_); add(&tenth_); add(&eleventh_); add(&twelve_); add(&thirteen_); add(&forteen_); add(&fithteen_); add(&sixteen_); } Vector_String Decoder16Times64Char::times16_64Char() const { Vector_String value; value.push_back(first_.char64()); value.push_back(second_.char64()); value.push_back(third_.char64()); value.push_back(forth_.char64()); value.push_back(fith_.char64()); value.push_back(sixth_.char64()); value.push_back(seventh_.char64()); value.push_back(eightth_.char64()); value.push_back(nineth_.char64()); value.push_back(tenth_.char64()); value.push_back(eleventh_.char64()); value.push_back(twelve_.char64()); value.push_back(thirteen_.char64()); value.push_back(forteen_.char64()); value.push_back(fithteen_.char64()); value.push_back(sixteen_.char64()); return value; } }
[ "leroythelegend@gmail.com" ]
leroythelegend@gmail.com
6a7f7f651016abdbc8cdcf59cdfe1867dc81cbf4
a9aa074f0d0bbbd75bc5ea72c4a60c3985407762
/Xspec/src/XSFit/FitMethod/Minuit/minuit2/test/MnSim/ReneTest.cxx
7a0c6d29bc2a1d45d73e5047606067a854ed6b22
[]
no_license
Areustle/heasoft-6.20
d54e5d5b8769a2544472d98b1ac738a1280da6c1
1162716527d9d275cdca064a82bf4d678fbafa15
refs/heads/master
2021-01-21T10:29:55.195578
2017-02-28T14:26:43
2017-02-28T14:26:43
83,440,883
0
1
null
null
null
null
UTF-8
C++
false
false
6,907
cxx
// @(#)root/minuit2:$Id: ReneTest.cxx,v 1.1 2013/06/14 15:34:14 kaa Exp $ // Authors: M. Winkler, F. James, L. Moneta, A. Zsenei 2003-2005 /********************************************************************** * * * Copyright (c) 2005 LCG ROOT Math team, CERN/PH-SFT * * * **********************************************************************/ // $Id: ReneTest.cxx,v 1.1 2013/06/14 15:34:14 kaa Exp $ #ifdef _WIN32 #define _USE_MATH_DEFINES #endif #include "Minuit2/FunctionMinimum.h" #include "Minuit2/MnMigrad.h" #include "Minuit2/MnMinos.h" #include "Minuit2/MnUserParameters.h" #include "Minuit2/MnPrint.h" #include "Minuit2/FCNBase.h" #include "Minuit2/MnScan.h" #include "Minuit2/MnPlot.h" using namespace ROOT::Minuit2; class ReneFcn : public FCNBase { public: ReneFcn(const std::vector<double>& meas) : fMeasurements(meas) {} virtual ~ReneFcn() {} virtual double operator()(const std::vector<double>& par) const { double a = par[2]; double b = par[1]; double c = par[0]; double p0 = par[3]; double p1 = par[4]; double p2 = par[5]; double fval = 0.; // double nbin = 3./double(fMeasurements.size()); for(unsigned int i = 0; i < fMeasurements.size(); i++) { double ni = fMeasurements[i]; if(ni < 1.e-10) continue; // double xi = (i + 0.5)*nbin; //xi=0-3 // double xi = (i+0.5)/20.; //xi=0-3 // double xi = (i+0.5)/40.; //xi=0-3 double xi = (i+1.)/40. - 1./80.; //xi=0-3 double ei = ni; // double nexp1 = a*xi*xi + b*xi + c; // double nexp2 = 0.5*p0*p1/M_PI; // double nexp3 = std::max(1.e-10, (xi-p2)*(xi-p2) + 0.25*p1*p1); // double nexp = nexp1 + nexp2/nexp3; double nexp = a*xi*xi + b*xi + c + (0.5*p0*p1/M_PI)/std::max(1.e-10, (xi-p2)*(xi-p2) + 0.25*p1*p1); fval += (ni-nexp)*(ni-nexp)/ei; } return fval; } virtual double Up() const {return 1.;} private: std::vector<double> fMeasurements; }; /* extern "C" void fcnr_(int&, double[], double&, double[], int&); extern "C" void stand_() {} class ReneFcn : public FCNBase { public: ReneFcn(const std::vector<double>& meas) : fMeasurements(meas) {} virtual ~ReneFcn() {} virtual double operator()(const std::vector<double>& par) const { double mypar[6]; for(std::vector<double>::const_iterator ipar = par.begin(); ipar != par.end(); ipar++) mypar[ipar-par.begin()] = par[ipar-par.begin()]; double fval = 0.; int iflag = 4; int npar = par.size(); fcnr_(npar, 0, fval, mypar, iflag); return fval; } virtual double Up() const {return 1.;} private: std::vector<double> fMeasurements; }; */ int main() { /* double tmp[60] = {6., 1.,10.,12., 6.,13.,23.,22.,15.,21., 23.,26.,36.,25.,27.,35.,40.,44.,66.,81., 75.,57.,48.,45.,46.,41.,35.,36.,53.,32., 40.,37.,38.,31.,36.,44.,42.,37.,32.,32., 43.,44.,35.,33.,33.,39.,29.,41.,32.,44., 26.,39.,29.,35.,32.,21.,21.,15.,25.,15.}; std::vector<double> measurements(tmp, tmp+60); */ /* double tmp[120] = {2.,1.,1.,0.,1.,1.,0.,1.,3.,0.,0.,1.,0., 1.,1.,0.,0.,1.,0.,0.,0.,0.,2.,1.,1.,2., 2.,0.,2.,4.,2.,6.,2.,1.,4.,0.,3.,6.,16., 30.,34.,18.,8.,2.,3.,4.,4.,5.,6.,3.,5., 0.,1.,1.,7.,3.,2.,5.,1.,3.,5.,3.,2.,3., 2.,2.,1.,1.,5.,2.,3.,7.,2.,7.,6.,5.,1., 4.,5.,0.,6.,3.,4.,3.,3.,6.,8.,8.,3.,4., 4.,8.,9.,7.,3.,4.,6.,2.,5.,10.,7.,6.,4., 4.,7.,7.,5.,4.,12.,4.,6.,3.,7.,4.,3.,4., 3,10.,8.,7.}; */ double tmp[120] = {38.,36.,46.,52.,54.,52.,61.,52.,64.,77., 60.,56.,78.,71.,81.,83.,89.,96.,118.,96., 109.,111.,107.,107.,135.,156.,196.,137., 160.,153.,185.,222.,251.,270.,329.,422., 543.,832.,1390.,2835.,3462.,2030.,1130., 657.,469.,411.,375.,295.,281.,281.,289., 273.,297.,256.,274.,287.,280.,274.,286., 279.,293.,314.,285.,322.,307.,313.,324., 351.,314.,314.,301.,361.,332.,342.,338., 396.,356.,344.,395.,416.,406.,411.,422., 393.,393.,409.,455.,427.,448.,459.,403., 441.,510.,501.,502.,482.,487.,506.,506., 526.,517.,534.,509.,482.,591.,569.,518., 609.,569.,598.,627.,617.,610.,662.,666., 652.,671.,647.,650.,701.}; std::vector<double> measurements(tmp, tmp+120); ReneFcn fFCN(measurements); MnUserParameters upar; upar.Add("p0", 100., 10.); upar.Add("p1", 100., 10.); upar.Add("p2", 100., 10.); upar.Add("p3", 100., 10.); upar.Add("p4", 1., 0.3); upar.Add("p5", 1., 0.3); /* # ext. || Name || type || Value || Error +/- 0 || p0 || free || 32.04 || 9.611 1 || p1 || free || 98.11 || 29.43 2 || p2 || free || 39.15 || 11.75 3 || p3 || free || 362.4 || 108.7 4 || p4 || free || 0.06707 || 0.02012 5 || p5 || free || 1.006 || 0.3019 upar.Add(0, "p0", 32.04, 9.611); upar.Add(1, "p1", 98.11, 29.43); upar.Add(2, "p2", 39.15, 11.75); upar.Add(3, "p3", 362.4, 108.7); upar.Add(4, "p4", 0.06707, 0.02012); upar.Add(5, "p5", 1.006, 0.3019); */ std::cout<<"initial parameters: "<<upar<<std::endl; std::cout<<"start migrad "<<std::endl; MnMigrad migrad(fFCN, upar); FunctionMinimum min = migrad(); if(!min.IsValid()) { //try with higher strategy std::cout<<"FM is invalid, try with strategy = 2."<<std::endl; MnMigrad migrad2(fFCN, min.UserState(), MnStrategy(2)); min = migrad2(); } std::cout<<"minimum: "<<min<<std::endl; /* std::cout<<"start Minos"<<std::endl; MnMinos Minos(migrad, min); AsymmetricError e0 = Minos(0); AsymmetricError e1 = Minos(1); AsymmetricError e2 = Minos(2); std::cout<<"par0: "<<e0.Value()<<" + "<<e0.Upper()<<e0.Lower()<<std::endl; std::cout<<"par1: "<<e1.Value()<<" + "<<e1.Upper()<<e1.Lower()<<std::endl; std::cout<<"par2: "<<e2.Value()<<" + "<<e2.Upper()<<e2.Lower()<<std::endl; */ { std::vector<double> params(6, 1.); std::vector<double> Error(6, 1.); MnScan scan(fFCN, params, Error); std::cout<<"scan parameters: "<<scan.Parameters()<<std::endl; MnPlot plot; for(unsigned int i = 0; i < upar.VariableParameters(); i++) { std::vector<std::pair<double, double> > xy = scan.Scan(i); // std::vector<std::pair<double, double> > xy = scan.scan(0); plot(xy); } std::cout<<scan.Parameters()<<std::endl; } { std::vector<double> params(6, 1.); std::vector<double> Error(6, 1.); MnScan scan(fFCN, params, Error); std::cout<<"scan parameters: "<<scan.Parameters()<<std::endl; FunctionMinimum min = scan(); // std::cout<<min<<std::endl; std::cout<<scan.Parameters()<<std::endl; } return 0; }
[ "alexander.w.reustle@nasa.gov" ]
alexander.w.reustle@nasa.gov
04fc7ed51796e4e85ce42ae62ec6d7df82468206
003c2eda472215c07a42ddb84c10cfaafbf9b858
/EasyFramework3d/base/xml/XmlPrimitivesForMath.cpp
4f3e9cd75c27355c00b02c4d16e0cdb98a8ca8bf
[ "MIT" ]
permissive
sizilium/FlexChess
6abd8a596438875e719201049c0b28db957d85f4
f12b94e800ddcb00535067eca3b560519c9122e0
refs/heads/master
2021-01-22T02:48:59.709851
2017-02-06T11:11:31
2017-02-06T11:11:31
80,826,446
0
0
null
null
null
null
UTF-8
C++
false
false
1,772
cpp
#include <vs/base/xml/XmlPrimitivesForMath.h> namespace vs { namespace base { namespace xml { DoubleVectorTag::DoubleVectorTag(const string &name, const DoubleVector vector3d) { this->name = name; this->vector3d = vector3d; } DoubleVectorTag::DoubleVectorTag(const string &name, double x, double y, double z) { this->name = name; vector3d = DoubleVector(x, y, z); } const string DoubleVectorTag::getName() const { return this->name; } void DoubleVectorTag::cout(ofstream &os) const { os << "<" << name << "> " << "<x>" << vector3d.x() << "</x>" << "<y>" << vector3d.y() << "</y>" << "<z>" << vector3d.z() << "</z>" << " </" << name << ">"; } void DoubleVectorTag::cout(ostream &os) const { os << "<" << name << "> " << "<x>" << vector3d.x() << "</x>" << "<y>" << vector3d.y() << "</y>" << "<z>" << vector3d.z() << "</z>" << " </" << name << ">"; } bool getDoubleVector (const string &name, const Tree<XmlTag*> *tree, DoubleVector &vec) { Tree<XmlTag*>::Const_Iterator it (tree); while (it.hasNext()) { // search for DoubleVector's name if (it.current()->getName() == name) { it.goChild(); // read x y z bool x = false; bool y = false; bool z = false; while (it.hasNextSibling()) { if (it.current()->getName() == "x") { vec.x(atof(it.current()->getValue().c_str())); x = true; } else if (it.current()->getName() == "y") { vec.y(atof(it.current()->getValue().c_str())); y = true; } else if (it.current()->getName() == "z") { vec.z(atof(it.current()->getValue().c_str())); z = true; } it.nextSibling(); } if (x && y && z) return true; else return false; } it.next(); } return false; } } // xml } // base } // vs
[ "sizilium@outlook.com" ]
sizilium@outlook.com
54d11230ca6e13838c994a126159273f8edecd82
decefb13f8a603c1f5cc7eb00634b4649915204f
/packages/node-mobile/deps/v8/src/codegen/source-position.h
ad0132b827e8a5005c0a927fbe2acd87ec31fffd
[ "BSD-3-Clause", "Apache-2.0", "bzip2-1.0.6", "SunPro", "LicenseRef-scancode-free-unknown", "Zlib", "CC0-1.0", "ISC", "LicenseRef-scancode-public-domain", "ICU", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "Artistic-2.0", "NTP", "LicenseRef-scancode-unknown-license-reference", ...
permissive
open-pwa/open-pwa
f092b377dc6cb04123a16ef96811ad09a9956c26
4c88c8520b4f6e7af8701393fd2cedbe1b209e8f
refs/heads/master
2022-05-28T22:05:19.514921
2022-05-20T07:27:10
2022-05-20T07:27:10
247,925,596
24
1
Apache-2.0
2021-08-10T07:38:42
2020-03-17T09:13:00
C++
UTF-8
C++
false
false
6,089
h
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_CODEGEN_SOURCE_POSITION_H_ #define V8_CODEGEN_SOURCE_POSITION_H_ #include <ostream> #include "src/common/globals.h" #include "src/flags/flags.h" #include "src/handles/handles.h" #include "src/utils/utils.h" namespace v8 { namespace internal { class Code; class OptimizedCompilationInfo; class Script; class SharedFunctionInfo; struct SourcePositionInfo; // SourcePosition stores // - is_external (1 bit true/false) // // - if is_external is true: // - external_line (20 bits, non-negative int) // - external_file_id (10 bits, non-negative int) // // - if is_external is false: // - script_offset (30 bit non-negative int or kNoSourcePosition) // // - In both cases, there is an inlining_id. // - inlining_id (16 bit non-negative int or kNotInlined). // // An "external" SourcePosition is one given by a file_id and a line, // suitable for embedding references to .cc or .tq files. // Otherwise, a SourcePosition contains an offset into a JavaScript // file. // // A defined inlining_id refers to positions in // OptimizedCompilationInfo::inlined_functions or // DeoptimizationData::InliningPositions, depending on the compilation stage. class SourcePosition final { public: explicit SourcePosition(int script_offset, int inlining_id = kNotInlined) : value_(0) { SetIsExternal(false); SetScriptOffset(script_offset); SetInliningId(inlining_id); } // External SourcePositions should use the following method to construct // SourcePositions to avoid confusion. static SourcePosition External(int line, int file_id) { return SourcePosition(line, file_id, kNotInlined); } static SourcePosition Unknown() { return SourcePosition(kNoSourcePosition); } bool IsKnown() const { if (IsExternal()) return true; return ScriptOffset() != kNoSourcePosition || InliningId() != kNotInlined; } bool isInlined() const { if (IsExternal()) return false; return InliningId() != kNotInlined; } bool IsExternal() const { return IsExternalField::decode(value_); } bool IsJavaScript() const { return !IsExternal(); } int ExternalLine() const { DCHECK(IsExternal()); return ExternalLineField::decode(value_); } int ExternalFileId() const { DCHECK(IsExternal()); return ExternalFileIdField::decode(value_); } // Assumes that the code object is optimized std::vector<SourcePositionInfo> InliningStack(Handle<Code> code) const; std::vector<SourcePositionInfo> InliningStack( OptimizedCompilationInfo* cinfo) const; void Print(std::ostream& out, Code code) const; void PrintJson(std::ostream& out) const; int ScriptOffset() const { DCHECK(IsJavaScript()); return ScriptOffsetField::decode(value_) - 1; } int InliningId() const { return InliningIdField::decode(value_) - 1; } void SetIsExternal(bool external) { value_ = IsExternalField::update(value_, external); } void SetExternalLine(int line) { DCHECK(IsExternal()); DCHECK(line <= ExternalLineField::kMax - 1); value_ = ExternalLineField::update(value_, line); } void SetExternalFileId(int file_id) { DCHECK(IsExternal()); DCHECK(file_id <= ExternalFileIdField::kMax - 1); value_ = ExternalFileIdField::update(value_, file_id); } void SetScriptOffset(int script_offset) { DCHECK(IsJavaScript()); DCHECK(script_offset <= ScriptOffsetField::kMax - 2); DCHECK_GE(script_offset, kNoSourcePosition); value_ = ScriptOffsetField::update(value_, script_offset + 1); } void SetInliningId(int inlining_id) { DCHECK(inlining_id <= InliningIdField::kMax - 2); DCHECK_GE(inlining_id, kNotInlined); value_ = InliningIdField::update(value_, inlining_id + 1); } static const int kNotInlined = -1; STATIC_ASSERT(kNoSourcePosition == -1); int64_t raw() const { return static_cast<int64_t>(value_); } static SourcePosition FromRaw(int64_t raw) { SourcePosition position = Unknown(); DCHECK_GE(raw, 0); position.value_ = static_cast<uint64_t>(raw); return position; } private: // Used by SourcePosition::External(line, file_id). SourcePosition(int line, int file_id, int inlining_id) : value_(0) { SetIsExternal(true); SetExternalLine(line); SetExternalFileId(file_id); SetInliningId(inlining_id); } void Print(std::ostream& out, SharedFunctionInfo function) const; using IsExternalField = BitField64<bool, 0, 1>; // The two below are only used if IsExternal() is true. using ExternalLineField = BitField64<int, 1, 20>; using ExternalFileIdField = BitField64<int, 21, 10>; // ScriptOffsetField is only used if IsExternal() is false. using ScriptOffsetField = BitField64<int, 1, 30>; // InliningId is in the high bits for better compression in // SourcePositionTable. using InliningIdField = BitField64<int, 31, 16>; // Leaving the highest bit untouched to allow for signed conversion. uint64_t value_; }; inline bool operator==(const SourcePosition& lhs, const SourcePosition& rhs) { return lhs.raw() == rhs.raw(); } inline bool operator!=(const SourcePosition& lhs, const SourcePosition& rhs) { return !(lhs == rhs); } struct InliningPosition { // position of the inlined call SourcePosition position = SourcePosition::Unknown(); // references position in DeoptimizationData::literals() int inlined_function_id; }; struct SourcePositionInfo { SourcePositionInfo(SourcePosition pos, Handle<SharedFunctionInfo> f); SourcePosition position; Handle<SharedFunctionInfo> shared; Handle<Script> script; int line = -1; int column = -1; }; std::ostream& operator<<(std::ostream& out, const SourcePosition& pos); std::ostream& operator<<(std::ostream& out, const SourcePositionInfo& pos); std::ostream& operator<<(std::ostream& out, const std::vector<SourcePositionInfo>& stack); } // namespace internal } // namespace v8 #endif // V8_CODEGEN_SOURCE_POSITION_H_
[ "frank@lemanschik.com" ]
frank@lemanschik.com
7649be3701fc7b5478edcb32c609bdc3cfae1dc7
1497386b0fe450e6c3881c8c6d52d9e6ad9117ab
/trunk/CrypTool/DlgPlayfairAnalysis.cpp
fac5691fe19207419c6af720bfb3d8f498911d9f
[ "Apache-2.0" ]
permissive
flomar/CrypTool-VS2015
403f538d6cad9b2f16fbf8846d94456c0944569b
6468257af2e1002418882f22a9ed9fabddde096d
refs/heads/master
2021-01-21T14:39:58.113648
2017-02-22T14:10:19
2017-02-22T14:10:19
57,972,666
0
5
null
null
null
null
ISO-8859-1
C++
false
false
36,926
cpp
/************************************************************************** Copyright [2009] [CrypTool Team] This file is part of CrypTool. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **************************************************************************/ ////////////////////////////////////////////////////////////////// // DialogPlayfair.cpp: Implementierungsdatei // // Menüfolge: Analyse -> manuelle Analyse / Algorithmen -> Playfair... // #include "stdafx.h" #include "CrypToolApp.h" #include "DlgPlayfairAnalysis.h" #include "PlayfairAnalysis.h" #include "assert.h" #include "DialogeMessage.h" ///////////////////////////////////////////////////////////////////////////// // // Dialogfeld CDlgPlayfairAnalysis // CDlgPlayfairAnalysis::CDlgPlayfairAnalysis(const char *infile,const char *outfile,int r,int c,CWnd* pParent /*=NULL*/) : CDialog(CDlgPlayfairAnalysis::IDD, pParent) { int i,j; m_Alg = new CPlayfairAnalysis("",0,infile,outfile,r,c,1); m_Alg->getMatrix()->clear(m_Alg->getAlphabet()->getNullElement()); for (i=0;i<6;i++) { for (j=0;j<6;j++) { char p[2]; p[1]=0; p[0]=m_Alg->getCharOfMatrix(i,j); m_einfeld[i][j].SetAlg(m_Alg,this); if (i<5&&j<5) m_mat[i][j]=p; } } m_Alg->UpdateDigrams(1); //{{AFX_DATA_INIT(CDlgPlayfairAnalysis) m_use = 1; m_Dec = 1; m_sechs = 0; m_iScroll = 0; m_ActualiseExpectedPlaintext = 1; m_txtfeld.SetAlg(m_Alg); //}}AFX_DATA_INIT } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgPlayfairAnalysis) DDX_Control(pDX, IDC_EDIT_1_1, m_einfeld[0][0]); DDX_Control(pDX, IDC_EDIT_1_2, m_einfeld[0][1]); DDX_Control(pDX, IDC_EDIT_1_3, m_einfeld[0][2]); DDX_Control(pDX, IDC_EDIT_1_4, m_einfeld[0][3]); DDX_Control(pDX, IDC_EDIT_1_5, m_einfeld[0][4]); DDX_Control(pDX, IDC_EDIT_1_6, m_einfeld[0][5]); DDX_Control(pDX, IDC_EDIT_2_1, m_einfeld[1][0]); DDX_Control(pDX, IDC_EDIT_2_2, m_einfeld[1][1]); DDX_Control(pDX, IDC_EDIT_2_3, m_einfeld[1][2]); DDX_Control(pDX, IDC_EDIT_2_4, m_einfeld[1][3]); DDX_Control(pDX, IDC_EDIT_2_5, m_einfeld[1][4]); DDX_Control(pDX, IDC_EDIT_2_6, m_einfeld[1][5]); DDX_Control(pDX, IDC_EDIT_3_1, m_einfeld[2][0]); DDX_Control(pDX, IDC_EDIT_3_2, m_einfeld[2][1]); DDX_Control(pDX, IDC_EDIT_3_3, m_einfeld[2][2]); DDX_Control(pDX, IDC_EDIT_3_4, m_einfeld[2][3]); DDX_Control(pDX, IDC_EDIT_3_5, m_einfeld[2][4]); DDX_Control(pDX, IDC_EDIT_3_6, m_einfeld[2][5]); DDX_Control(pDX, IDC_EDIT_4_1, m_einfeld[3][0]); DDX_Control(pDX, IDC_EDIT_4_2, m_einfeld[3][1]); DDX_Control(pDX, IDC_EDIT_4_3, m_einfeld[3][2]); DDX_Control(pDX, IDC_EDIT_4_4, m_einfeld[3][3]); DDX_Control(pDX, IDC_EDIT_4_5, m_einfeld[3][4]); DDX_Control(pDX, IDC_EDIT_4_6, m_einfeld[3][5]); DDX_Control(pDX, IDC_EDIT_5_1, m_einfeld[4][0]); DDX_Control(pDX, IDC_EDIT_5_2, m_einfeld[4][1]); DDX_Control(pDX, IDC_EDIT_5_3, m_einfeld[4][2]); DDX_Control(pDX, IDC_EDIT_5_4, m_einfeld[4][3]); DDX_Control(pDX, IDC_EDIT_5_5, m_einfeld[4][4]); DDX_Control(pDX, IDC_EDIT_5_6, m_einfeld[4][5]); DDX_Control(pDX, IDC_EDIT_6_1, m_einfeld[5][0]); DDX_Control(pDX, IDC_EDIT_6_2, m_einfeld[5][1]); DDX_Control(pDX, IDC_EDIT_6_3, m_einfeld[5][2]); DDX_Control(pDX, IDC_EDIT_6_4, m_einfeld[5][3]); DDX_Control(pDX, IDC_EDIT_6_5, m_einfeld[5][4]); DDX_Control(pDX, IDC_EDIT_6_6, m_einfeld[5][5]); DDX_Text(pDX, IDC_EDIT_1_1, m_mat[0][0]); DDV_MaxChars(pDX, m_mat[0][0], 1); DDX_Text(pDX, IDC_EDIT_1_2, m_mat[0][1]); DDV_MaxChars(pDX, m_mat[0][1], 1); DDX_Text(pDX, IDC_EDIT_1_3, m_mat[0][2]); DDV_MaxChars(pDX, m_mat[0][2], 1); DDX_Text(pDX, IDC_EDIT_1_4, m_mat[0][3]); DDV_MaxChars(pDX, m_mat[0][3], 1); DDX_Text(pDX, IDC_EDIT_1_5, m_mat[0][4]); DDV_MaxChars(pDX, m_mat[0][4], 1); DDX_Text(pDX, IDC_EDIT_1_6, m_mat[0][5]); DDV_MaxChars(pDX, m_mat[0][5], 1); DDX_Text(pDX, IDC_EDIT_2_1, m_mat[1][0]); DDV_MaxChars(pDX, m_mat[1][0], 1); DDX_Text(pDX, IDC_EDIT_2_2, m_mat[1][1]); DDV_MaxChars(pDX, m_mat[1][1], 1); DDX_Text(pDX, IDC_EDIT_2_3, m_mat[1][2]); DDV_MaxChars(pDX, m_mat[1][2], 1); DDX_Text(pDX, IDC_EDIT_2_4, m_mat[1][3]); DDV_MaxChars(pDX, m_mat[1][3], 1); DDX_Text(pDX, IDC_EDIT_2_5, m_mat[1][4]); DDV_MaxChars(pDX, m_mat[1][4], 1); DDX_Text(pDX, IDC_EDIT_2_6, m_mat[1][5]); DDV_MaxChars(pDX, m_mat[1][5], 1); DDX_Text(pDX, IDC_EDIT_3_1, m_mat[2][0]); DDV_MaxChars(pDX, m_mat[2][0], 1); DDX_Text(pDX, IDC_EDIT_3_2, m_mat[2][1]); DDV_MaxChars(pDX, m_mat[2][1], 1); DDX_Text(pDX, IDC_EDIT_3_3, m_mat[2][2]); DDV_MaxChars(pDX, m_mat[2][2], 1); DDX_Text(pDX, IDC_EDIT_3_4, m_mat[2][3]); DDV_MaxChars(pDX, m_mat[2][3], 1); DDX_Text(pDX, IDC_EDIT_3_5, m_mat[2][4]); DDV_MaxChars(pDX, m_mat[2][4], 1); DDX_Text(pDX, IDC_EDIT_3_6, m_mat[2][5]); DDV_MaxChars(pDX, m_mat[2][5], 1); DDX_Text(pDX, IDC_EDIT_4_1, m_mat[3][0]); DDV_MaxChars(pDX, m_mat[3][0], 1); DDX_Text(pDX, IDC_EDIT_4_2, m_mat[3][1]); DDV_MaxChars(pDX, m_mat[3][1], 1); DDX_Text(pDX, IDC_EDIT_4_3, m_mat[3][2]); DDV_MaxChars(pDX, m_mat[3][2], 1); DDX_Text(pDX, IDC_EDIT_4_4, m_mat[3][3]); DDV_MaxChars(pDX, m_mat[3][3], 1); DDX_Text(pDX, IDC_EDIT_4_5, m_mat[3][4]); DDV_MaxChars(pDX, m_mat[3][4], 1); DDX_Text(pDX, IDC_EDIT_4_6, m_mat[3][5]); DDV_MaxChars(pDX, m_mat[3][5], 1); DDX_Text(pDX, IDC_EDIT_5_1, m_mat[4][0]); DDV_MaxChars(pDX, m_mat[4][0], 1); DDX_Text(pDX, IDC_EDIT_5_2, m_mat[4][1]); DDV_MaxChars(pDX, m_mat[4][1], 1); DDX_Text(pDX, IDC_EDIT_5_3, m_mat[4][2]); DDV_MaxChars(pDX, m_mat[4][2], 1); DDX_Text(pDX, IDC_EDIT_5_4, m_mat[4][3]); DDV_MaxChars(pDX, m_mat[4][3], 1); DDX_Text(pDX, IDC_EDIT_5_5, m_mat[4][4]); DDV_MaxChars(pDX, m_mat[4][4], 1); DDX_Text(pDX, IDC_EDIT_5_6, m_mat[4][5]); DDV_MaxChars(pDX, m_mat[4][5], 1); DDX_Text(pDX, IDC_EDIT_6_1, m_mat[5][0]); DDV_MaxChars(pDX, m_mat[5][0], 1); DDX_Text(pDX, IDC_EDIT_6_2, m_mat[5][1]); DDV_MaxChars(pDX, m_mat[5][1], 1); DDX_Text(pDX, IDC_EDIT_6_3, m_mat[5][2]); DDV_MaxChars(pDX, m_mat[5][2], 1); DDX_Text(pDX, IDC_EDIT_6_4, m_mat[5][3]); DDV_MaxChars(pDX, m_mat[5][3], 1); DDX_Text(pDX, IDC_EDIT_6_5, m_mat[5][4]); DDV_MaxChars(pDX, m_mat[5][4], 1); DDX_Text(pDX, IDC_EDIT_6_6, m_mat[5][5]); DDV_MaxChars(pDX, m_mat[5][5], 1); DDX_Radio(pDX, IDC_RAD6, m_sechs); DDX_Control(pDX, IDC_PLAYFAIR_LIST, m_listview); DDX_Control(pDX, IDC_PASSWORD, m_pwfeld); DDX_Control(pDX, IDC_MYTXT, m_txtfeld); DDX_Check(pDX, IDC_CHECK4, m_ActualiseExpectedPlaintext); // DDV_MaxChars(pDX, m_mytxt, MAXSHOWLETTER); m_mytxt ersetzt durch lokale Variable DDX_Text(pDX, IDC_PASSWORD, m_password); DDV_MaxChars(pDX, m_password, 36); DDX_Control(pDX, IDC_LIST, m_ciphfeld); DDX_Text(pDX, IDC_LIST, m_cipher); DDV_MaxChars(pDX, m_cipher, MAXSHOWLETTER*10); DDX_Check(pDX, IDC_CHECK1, m_use); // DDX_Text(pDX, IDC_MYTXT, m_mytxt); DDX_Control(pDX, IDC_SCROLLBAR1, m_ctrlScroll); DDX_Scroll(pDX, IDC_SCROLLBAR1, m_iScroll); //}}AFX_DATA_MAP } ///////////////////////////////////////////////////////////////////////////// // // // BEGIN_MESSAGE_MAP(CDlgPlayfairAnalysis, CDialog) //{{AFX_MSG_MAP(CDlgPlayfairAnalysis) ON_BN_CLICKED(IDC_CHECK1, OnCheck) ON_BN_CLICKED(IDC_RAD5, OnSechs) ON_BN_CLICKED(IDC_RAD6, OnSechs) ON_BN_CLICKED(IDC_BUTTON5, OnAnalyse) ON_BN_CLICKED(IDC_BUTTON6, OnSynchronise) ON_EN_UPDATE(IDC_MYTXT, OnManAnalyse) ON_EN_UPDATE(IDC_PASSWORD, OnUpdate) ON_WM_HSCROLL() ON_EN_CHANGE(IDC_MYTXT, OnChangeEditPlaintext) ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // Behandlungsroutinen für Nachrichten CDlgPlayfairAnalysis char *CDlgPlayfairAnalysis::GetData() { return m_password.GetBuffer(25); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::OnManAnalyse() { char buf[MAXSHOWLETTER+2], line[256]; int i,j, n, k; int maxchars=MAXSHOWLETTER; playfair_digrammlist* diglist; UpdateData(); i=0; j=0; CString m_plaintext; m_txtfeld.GetWindowText(m_plaintext); while ((i<maxchars)&&(j<m_plaintext.GetLength())) { char nChar = m_plaintext[j]; if (m_Alg->myisalpha2(nChar)) buf[i] = nChar; else { if ((nChar=='j')||(nChar=='J')||(('0'<=nChar)&&(nChar<='9'))) { Message(IDS_STRING_PLAYFAIR_WARNMSG003, MB_ICONEXCLAMATION); } buf[i] = NULLELEMENT; } i++; j++; } buf[i]='\0'; digbuf[0]='\0'; m_Alg->initDigrams(); diglist = new playfair_digrammlist(m_Alg->getAlphabet(), m_Alg->getDigrams(), buf, m_Alg->inbuf, min (maxchars, m_Alg->inbuflen)); // in der Initialisierung läuft die eigentliche Arbeit ab: // für jedes Pärchen des Klartextes, wird das passende Digramm gesucht, das durch das Chiffrat festgelegt ist. n = 2*diglist->getLen(); m_txtfeld.SetLimitText (n); // limitiere Ausgabe diglist->getPlainString(digbuf, n); // lege Ausgabe des Klartextes fest (2.Zeile) try { if (true || (i%2==0)) { m_Alg->DeleteLetterGraph(); m_Alg->AnalyseDigramme(diglist); //untersuchen der Digramme und erstellen des Lettergraphen } } catch (playfair_error e) { switch (e.getCode()) { case 1: LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_ERRMSG001,pc_str,STR_LAENGE_STRING_TABLE); break; case 101: case 102: case 103: case 104: case 105: case 106: case 107: LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_ERRMSG100,pc_str,STR_LAENGE_STRING_TABLE); break; case 113: case 114: LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_ERRMSG110,pc_str,STR_LAENGE_STRING_TABLE); break; case 201: case 202: case 203: case 204: LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_ERRMSG200,pc_str,STR_LAENGE_STRING_TABLE); break; default: LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_ERRMSGALLG,pc_str,STR_LAENGE_STRING_TABLE); break; } sprintf(line,pc_str,e.getPosition()+1,(e.getLetter())?e.getLetter()->getValue():m_Alg->getAlphabet()->getNullElement()->getValue()); AfxMessageBox (line); } if ((false) && (i%2==0) && (i>0)) { //automatische Generierung der Matrix aktiv if (!m_Alg->CreateMatrixStandalone (buf, i)) { // Analyse Peer Wichmann // keine gültige Matrix gefunden LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_NOMATRIX,pc_str,STR_LAENGE_STRING_TABLE); sprintf(line,pc_str); AfxMessageBox (line); } m_password = m_Alg->CreatePassfromMatrix(); } delete (diglist); // Matrix neu schreiben for (i=0;i<m_Alg->getSize();i++) { for (k=0;k<m_Alg->getSize();k++) { m_mat[i][k]=m_Alg->getCharOfMatrix(i,k); } } UpdateData(FALSE); UpdateListBox(); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::OnAnalyse() // Schalter "erzeuge Matrix", war "Häufigkeitsanalyse" { int i, k; char buf[MAXSHOWLETTER+2], line[256]; int maxchars=MAXSHOWLETTER; BOOL flagSuccess; UpdateData(TRUE); CString m_plaintext; m_txtfeld.GetWindowText(m_plaintext); i=0; while ((i<maxchars)&&(i<m_plaintext.GetLength())) { buf[i] = m_plaintext[i]; i++; } buf[i]='\0'; if (!(flagSuccess = m_Alg->CreateMatrixStandalone(buf, i))) { // Analyse Peer Wichmann // keine gültige Matrix gefunden LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_NOMATRIX,pc_str,STR_LAENGE_STRING_TABLE); sprintf(line,pc_str); AfxMessageBox (line); } m_password = m_Alg->CreatePassfromMatrix(); // Matrix neu schreiben for (i=0;i<m_Alg->getSize();i++) { for (k=0;k<m_Alg->getSize();k++) { m_mat[i][k]=m_Alg->getCharOfMatrix(i,k); } } UpdateData(FALSE); UpdateListBox(); if ( m_ActualiseExpectedPlaintext && flagSuccess ) { char obuf[MAXSHOWLETTER+2]; int i,j,k; i=j=k=0; while(i<MAXSHOWLETTER&&j<m_Alg->inbuflen) { char c=m_Alg->inbuf[j++]; if(!m_Alg->myisalpha2(c) && !isinvalidoccured) c = m_Alg->getAlphabet()->replaceInvalidLetter(true, c); if(m_Alg->myisalpha2(c)) { obuf[i] = m_Alg->outbuf[k]; k++; } else { obuf[i] = '.'; } i++; } obuf[i] = '\0'; CString tmp = obuf; int ps, pe; m_txtfeld.GetSel(ps, pe); m_txtfeld.SetSel(0,-1); m_txtfeld.ReplaceSel(tmp, TRUE); m_txtfeld.SetSel(ps,ps); } m_txtfeld.SetFocus(); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::OnCheck() // Doppelte ignorieren oder nicht { m_Alg->PassUse(!m_use); OnUpdate(); m_Alg->SetPass(""); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::OnSechs() // auf 5x5 oder 6x6 Matrix einstellen { int i,j; UpdateData(TRUE); // TODO: Code für die Behandlungsroutine der Steuerelement-Benachrichtigung hier einfügen if (m_sechs == 1) { m_Alg->SetSize(true); for (i=0;i<6;i++) m_einfeld[i][5].EnableWindow(TRUE); for (i=0;i<5;i++) m_einfeld[5][i].EnableWindow(TRUE); } else { m_Alg->SetSize(false); for (i=0;i<6;i++) { m_einfeld[i][5].EnableWindow(FALSE); m_mat[i][5]=""; } for (i=0;i<5;i++) { m_einfeld[5][i].EnableWindow(FALSE); m_mat[5][i]=""; } } m_password=""; m_Alg->SetPass(""); m_Alg->UpdateDigrams(true); m_Alg->getMatrix()->clear(m_Alg->getAlphabet()->getNullElement()); for (i=0;i<m_Alg->getSize();i++) { for (j=0;j<m_Alg->getSize();j++) { m_mat[i][j]=m_Alg->getCharOfMatrix(i,j); } } UpdateData(FALSE); OnManAnalyse(); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::InitListBox() { is6x6possible = false; isinvalidoccured = false; int i; char c, s[245]; m_Alg->DoCipher(false, true,MAXSHOWLETTER); UpdateData(TRUE); m_cipher=m_Alg->outbuf; UpdateData(FALSE); // Gauweiler 30.1.01, statt eine einzelne Zeile, sollten gleich alle drei Zeilen angezeigt werden. // da die Update-Fkt das richtig macht, soll sie gleich mal zum ersten Mal ihre Arbeit machen. strcpy(digbuf,""); // ist vielleicht mit 6x6 Matrix verschlüsselt worden? i=0; while(i<MAXSHOWLETTER&&i<m_Alg->inbuflen) { c=m_Alg->inbuf[i++]; if(!m_Alg->myisalpha2(c)) // TG, Umlaute oder französische Zeichen zu etwas ähnlichem ersetzen. if (('J'==MyToUpper(c)) || (('0'<=c) && (c<='9'))) is6x6possible = true; else isinvalidoccured = true; } if (is6x6possible || isinvalidoccured) { if (is6x6possible) LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_WARNMSG001,pc_str,STR_LAENGE_STRING_TABLE); if (isinvalidoccured) { LoadString(AfxGetInstanceHandle(),IDS_STRING_PLAYFAIR_WARNMSG002,pc_str,STR_LAENGE_STRING_TABLE); UpdateData(); UpdateData(FALSE); } sprintf(s,pc_str); AfxMessageBox (s); UpdateData(TRUE); m_sechs = (is6x6possible && !isinvalidoccured)?1:0; UpdateData(FALSE); OnSechs(); } } //////////////////////////////////////////////////////////////////////////////////////// // // ON INIT DIALOG // BOOL CDlgPlayfairAnalysis::OnInitDialog() { CDialog::OnInitDialog(); // m_listview in Report-Mode initialisieren m_Font.CreateFont(0,0,0,0,0,0,0,0,DEFAULT_CHARSET,OUT_RASTER_PRECIS,0,DEFAULT_QUALITY,FIXED_PITCH|FF_DONTCARE,NULL); m_ciphfeld.SetFont(&m_Font); m_txtfeld.SetFont(&m_Font); int colWidth = 55; // Spaltenbreite in Pixel m_listview.InsertColumn( 0, " ", LVCFMT_LEFT, colWidth-30 , 0); // Buchstabe m_listview.InsertColumn( 1, "LROU", LVCFMT_LEFT, colWidth , 3); // m_listview.InsertColumn( 2, "Nb?", LVCFMT_LEFT, colWidth , 3); // LoadString(AfxGetInstanceHandle(),IDS_STRING_HORIZ,pc_str,STR_LAENGE_STRING_TABLE); m_listview.InsertColumn( 3, pc_str, LVCFMT_LEFT, colWidth+30 , 1); // LoadString(AfxGetInstanceHandle(),IDS_STRING_VERT,pc_str,STR_LAENGE_STRING_TABLE); m_listview.InsertColumn( 4, pc_str, LVCFMT_LEFT, colWidth+30 , 2); // m_listview.InsertColumn( 5, "row or col?", LVCFMT_LEFT, colWidth+60 , 3); // m_listview.InsertColumn( 6, "Metrik", LVCFMT_LEFT, colWidth , 3); // m_bHScroll = FALSE; m_iPos = 0; InitListBox(); SetupListBox(); SetupAnalysisWindow(); // read window rects at dialog initialization GetWindowRect(&initialRectDialog); GetDlgItem(IDC_PLAYFAIR_LIST)->GetWindowRect(&initialRectListLetterInformation); GetDlgItem(IDC_LIST)->GetWindowRect(&initialRectFieldResult); GetDlgItem(IDC_MYTXT)->GetWindowRect(&initialRectFieldPlaintext); GetDlgItem(IDCANCEL)->GetWindowRect(&initialRectButtonCancel); GetDlgItem(IDC_SCROLLBAR1)->GetWindowRect(&initialRectScrollbar); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX-Eigenschaftenseiten sollten FALSE zurückgeben } /****** Mark Santiago, Henrik Koy *******/ const int iEditSize=69; void CDlgPlayfairAnalysis::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { m_bHScroll = !m_bHScroll; int iMin, iMax, iPos, iPrev; pScrollBar->GetScrollRange(&iMin, &iMax); iPos = pScrollBar->GetScrollPos(); if(m_bHScroll) { switch(nSBCode) { case SB_LINELEFT: iPos = iPos-1; break; //Scroll left. case SB_LINERIGHT: iPos = iPos+1; break; //Scroll right. case SB_PAGELEFT: iPos = iPos-iEditSize/2; break; //Scroll one page left. case SB_PAGERIGHT: iPos = iPos+iEditSize/2; break; //Scroll one page right. case SB_THUMBTRACK: iPos = (int)nPos; break; //Drag scroll box to specified position. The current position is specified by the nPos parameter. } m_iPos = iPos = min(max(0, iPos), iMax); iPrev = m_ctrlScroll.SetScrollPos(iPos); m_ciphfeld.LineScroll(0, iPos-iPrev); // m_txtfeld.LineScroll(0, iPos-iPrev); } CDialog::OnHScroll(nSBCode, nPos, pScrollBar); m_bHScroll = FALSE; } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::ScrollRange(int length_in_characters) { if ( length_in_characters ) { m_iSMax = length_in_characters - iEditSize; if ( m_iSMax < 0 ) m_iSMax = 0; } m_ctrlScroll.SetScrollRange(0, m_iSMax); m_iPos = m_ctrlScroll.GetScrollPos(); m_ciphfeld.SetScrollRange(SB_HORZ, 0, m_iSMax); m_ciphfeld.LineScroll(0, m_iPos); m_ciphfeld.ShowScrollBar(SB_HORZ, FALSE); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::OnChangeEditPlaintext() { ScrollRange(); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::OnSynchronise() { int iMin, iPos; m_txtfeld.GetSel(iMin, iPos); CPoint cur = m_txtfeld.GetCaretPos(); iPos = max((int) 0, (int) (iPos-(cur.x+1)/9)); m_ctrlScroll.ShowWindow(SW_HIDE); m_ctrlScroll.SetScrollPos(0); m_ctrlScroll.SetScrollPos(iPos); m_ctrlScroll.ShowWindow(SW_SHOW); m_ciphfeld.ShowWindow(SW_HIDE); m_ciphfeld.LineScroll(0, -MAXSHOWLETTER); m_ciphfeld.LineScroll(0, iPos); m_ciphfeld.ShowWindow(SW_SHOW); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::SetupListBox() { int i,j; playfair_letter *let; char s[MAXSHOWLETTER+2]; m_listview.DeleteAllItems(); for (j=i=0; i < m_Alg->getLetterlist()->getLen(); i++) { let = (m_Alg->getLetterlist()->getLetter(i)); assert (let); assert (let->getValue()<='Z'); assert (let->getValue()>=NULLELEMENT); s[0] = let->getValue(); s[1] = '\0'; j = m_listview.InsertItem(i,s); assert (let); assert (let->getValue()<='Z'); assert (let->getValue()>=NULLELEMENT); let->getNeighboursString (s, 10); // Neighbours m_listview.SetItemText( j, 1, s); assert (let); assert (let->getValue()<='Z'); assert (let->getValue()>=NULLELEMENT); let->getUndefinedNeighboursString (s, 10); // poss. Neighbours m_listview.SetItemText( j, 2, s); assert (let); assert (let->getValue()<='Z'); assert (let->getValue()>=NULLELEMENT); let->getRowString (s, 20); // Rows m_listview.SetItemText( j, 3, s); assert (let); assert (let->getValue()<='Z'); assert (let->getValue()>=NULLELEMENT); let->getColString (s, 20); // Col m_listview.SetItemText( j, 4, s); assert (let); assert (let->getValue()<='Z'); assert (let->getValue()>=NULLELEMENT); let->getRoworcolString (s, 25); // RoworCol m_listview.SetItemText( j, 5, s); sprintf(s,"%d", let->getWeight()); // Metrik m_listview.SetItemText( j, 6, s); } } int CDlgPlayfairAnalysis::SetupAnalysisWindow() { int i,j,k; char ibuf[MAXSHOWLETTER+2],dbuf[MAXSHOWLETTER+2],obuf[MAXSHOWLETTER+2],c; m_Alg->DoCipher(false, true, MAXSHOWLETTER); UpdateData(TRUE); i=j=k=0; while(i<MAXSHOWLETTER&&j<m_Alg->inbuflen) { c=m_Alg->inbuf[j++]; if(!m_Alg->myisalpha2(c) && !isinvalidoccured) // TG, Umlaute oder französische Zeichen zu etwas ähnlichem ersetzen. c = m_Alg->getAlphabet()->replaceInvalidLetter(true, c); if(m_Alg->myisalpha2(c)) { ibuf[i] = MyToUpper(c); dbuf[i] = digbuf[k]; obuf[i] = m_Alg->outbuf[k]; k++; } else { ibuf[i] = '.'; dbuf[i] = '.'; obuf[i] = '.'; } i++; } ibuf[i]=0; dbuf[i]=0; obuf[i]=0; m_cipher.Format("%s\r\n%s\r\n%s\r\n",ibuf,dbuf,obuf); UpdateData(FALSE); return i; } void CDlgPlayfairAnalysis::UpdateListBox() { m_listview.ShowWindow(SW_HIDE); SetupListBox(); m_listview.ShowWindow(SW_SHOW); int i = SetupAnalysisWindow(); ScrollRange( i ); } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::UpdatePassword() { int i,j; char p[37]; if (m_sechs) { for (j=0;j<36;j++) p[j]=m_mat[j/6][j%6][0]; } else { for (i=0,j=0;i<30;i++) { if ( (i+1)%6) p[j++]=m_mat[i/6][i%6][0]; } } p[j--]=0; UpdateData(TRUE); m_password=p; // m_password=m_Alg->CreatePassfromMatrix(); UpdateData(FALSE); } ///////////////////////////////////////////////////////////////////////////// // // // int CDlgPlayfairAnalysis::Display() { int res; res=DoModal(); return res; } ///////////////////////////////////////////////////////////////////////////// // // // void CDlgPlayfairAnalysis::OnUpdate() // sobald ein neues Zeichen im Passwort eingegeben wurde { int sels, sele, i, k; char c; CString res; UpdateData(TRUE); //erstmal wieder die Daten aus dem Formular holen m_pwfeld.GetSel(sels, sele); res.Empty(); m_password.MakeUpper(); //abprüfen, ob ein ungültiges Zeichen in der Paßwortzeile eingegeben wurde for(k=i=0;i<m_password.GetLength();i++) { c = m_password[i]; if(!m_Alg->myisalpha2(c)) // TG, Umlaute oder französische Zeichen zu etwas ähnlichem ersetzen. c = m_Alg->getAlphabet()->replaceInvalidLetter(true, c); if(m_Alg->myisalpha2(c)) { // valid character res += c; k++; } else { // invalid character MessageBeep(MB_OK); if(k<sels) sels--; if(k<sele) sele--; } } m_password = res; m_Alg->SetPass(m_password.GetBuffer(36)); // GetBuffer(25) auf GetBuffer(36) ??? for (i=0;i<m_Alg->getSize();i++) { for (k=0;k<m_Alg->getSize();k++) { m_mat[i][k]=m_Alg->getCharOfMatrix(i,k); } } UpdateData(FALSE); UpdateListBox(); m_pwfeld.SetSel(sels,sele); } // flomar, 01/07/09 // this function is a quick hack (compare ListResults.cpp) // to make the dialog window scalable along the x-axis void CDlgPlayfairAnalysis::OnSize(UINT nType, int cx, int cy) { CWnd *windowListLetterInformation = GetDlgItem(IDC_PLAYFAIR_LIST); CWnd *windowFieldResult = GetDlgItem(IDC_LIST); CWnd *windowFieldPlaintext = GetDlgItem(IDC_MYTXT); CWnd *windowButtonCancel = GetDlgItem(IDCANCEL); CWnd *windowScrollbar = GetDlgItem(IDC_SCROLLBAR1); // make sure we have valid pointers; if not, return if(!windowListLetterInformation || !windowFieldResult || !windowFieldPlaintext || !windowButtonCancel || !windowScrollbar) return; // read the new dialog rect RECT newRectDialog; this->GetWindowRect(&newRectDialog); // return if the new dialog rect is smaller then the initial one, int widthOld = initialRectDialog.right - initialRectDialog.left; int widthNew = newRectDialog.right - newRectDialog.left; int heightOld = initialRectDialog.bottom - initialRectDialog.top; int heightNew = newRectDialog.bottom - newRectDialog.top; if(widthNew < widthOld || heightNew != heightOld) { this->MoveWindow(newRectDialog.left, newRectDialog.top, widthOld, heightOld); return; } // compute how much wider the dialog is compared to its original state int widthIncrement = widthNew - widthOld; // in order to deal with Microsoft's weird behaviour here, we need some // correctional parameters to make the dialog look less weird (WTF?) int correctionX = -4; int correctionY = +7; // compute new list letter information rect int widthListLetterInformation = initialRectListLetterInformation.right - initialRectListLetterInformation.left + widthIncrement; int heightListLetterInformation = initialRectListLetterInformation.bottom - initialRectListLetterInformation.top; int marginRightListLetterInformation = initialRectDialog.right - initialRectListLetterInformation.right; int marginBottomListLetterInformation = initialRectDialog.bottom - initialRectListLetterInformation.bottom; int xListLetterInformation = cx - widthListLetterInformation - marginRightListLetterInformation + correctionX; int yListLetterInformation = cy - heightListLetterInformation - marginBottomListLetterInformation + correctionY; // compute new field result rect int widthFieldResult = initialRectFieldResult.right - initialRectFieldResult.left + widthIncrement; int heightFieldResult = initialRectFieldResult.bottom - initialRectFieldResult.top; int marginRightFieldResult = initialRectDialog.right - initialRectFieldResult.right; int marginBottomFieldResult = initialRectDialog.bottom - initialRectFieldResult.bottom; int xFieldResult = cx - widthFieldResult - marginRightFieldResult + correctionX; int yFieldResult = cy - heightFieldResult - marginBottomFieldResult + correctionY; // compute new field plaintext rect int widthFieldPlaintext = initialRectFieldPlaintext.right - initialRectFieldPlaintext.left + widthIncrement; int heightFieldPlaintext = initialRectFieldPlaintext.bottom - initialRectFieldPlaintext.top; int marginRightFieldPlaintext = initialRectDialog.right - initialRectFieldPlaintext.right; int marginBottomFieldPlaintext = initialRectDialog.bottom - initialRectFieldPlaintext.bottom; int xFieldPlaintext = cx - widthFieldPlaintext - marginRightFieldPlaintext + correctionX; int yFieldPlaintext = cy - heightFieldPlaintext - marginBottomFieldPlaintext + correctionY; // compute new CANCEL button rect int widthButtonCancel = initialRectButtonCancel.right - initialRectButtonCancel.left; int heightButtonCancel = initialRectButtonCancel.bottom - initialRectButtonCancel.top; int marginRightButtonCancel = initialRectDialog.right - initialRectButtonCancel.right; int marginBottomButtonCancel = initialRectDialog.bottom - initialRectButtonCancel.bottom; int xButtonCancel = cx - widthButtonCancel - marginRightButtonCancel; int yButtonCancel = cy - heightButtonCancel - marginBottomButtonCancel; // compute new SCROLLBAR rect int marginRightScrollbar = initialRectDialog.right - initialRectScrollbar.right; int marginBottomScrollbar = initialRectDialog.bottom - initialRectScrollbar.bottom; int widthScrollbar = cx - marginRightScrollbar; int heightScrollbar = initialRectScrollbar.bottom - initialRectScrollbar.top; int xScrollbar = cx - widthScrollbar - marginRightScrollbar; int yScrollbar = cy - heightScrollbar - marginBottomScrollbar; // align dialog components windowListLetterInformation->MoveWindow(xListLetterInformation, yListLetterInformation, widthListLetterInformation, heightListLetterInformation); windowFieldResult->MoveWindow(xFieldResult, yFieldResult, widthFieldResult, heightFieldResult); windowFieldPlaintext->MoveWindow(xFieldPlaintext, yFieldPlaintext, widthFieldPlaintext, heightFieldPlaintext); windowButtonCancel->MoveWindow(xButtonCancel, yButtonCancel, widthButtonCancel, heightButtonCancel); windowScrollbar->MoveWindow(xScrollbar, yScrollbar, widthScrollbar, heightScrollbar); Invalidate(); } PlayfairOptions CDlgPlayfairAnalysis::getPlayfairOptions() { // create a PlayfairOptions structure that is to be returned PlayfairOptions playfairOptions; playfairOptions.decryption = this->m_Dec; playfairOptions.fileNameCleartext = ""; playfairOptions.fileNameCiphertext = ""; // TODO playfairOptions.separateDoubleCharacters = true; // TODO playfairOptions.separator1 = "X"; // TODO playfairOptions.separator2 = "Y"; // TODO playfairOptions.separateDoubleCharactersOnlyWithinPairs = true; playfairOptions.ignoreDoubleCharactersInKey = this->m_use; playfairOptions.matrixSize = m_sechs ? 6 : 5; return playfairOptions; } ///////////////////////////////////////////////////////////////////////////// // // // CChEdit::CChEdit() { } ///////////////////////////////////////////////////////////////////////////// // // // CChEdit::~CChEdit() { } ///////////////////////////////////////////////////////////////////////////// // // // BEGIN_MESSAGE_MAP(CChEdit, CEdit) //{{AFX_MSG_MAP(CChEdit) ON_WM_CHAR() ON_WM_LBUTTONUP() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // // // void CChEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { #if 1 // flomar, 03/28/2013: after hours of debugging I finally located the source of // the problem; obviously the user's key strokes weren't correctly processed, in // other words a character inserted at a specific location would get assigned to an // incorrect matrix cell-- before digging in any deeper I completely re-wrote this // function; it *should* work as intended now; I left the old code in here on purpose // (see the '#if' blocks above and below) in case someone has to deal with this in // another 10 or so years, and I'm not 100% sure I didn't introduce some bugs myself // the character the user tried to insert-- in case the character is invalid with regards // to the analysis alphabet, it gets replaced implicitly; if the replacement fails (i.e. // the character is still invalid), we return right away and notify the user with a beep const char newCharacter = MyToUpper(m_Alg->getAlphabet()->replaceInvalidLetter(true, nChar)); if(!m_Alg->myisalpha2(newCharacter)) { MessageBeep(MB_OK); } // the character that was replaced by the new character; the way this is handled // is pretty ugly with all that SetSel/GetLine stuff, but I'm certainly not gonna // touch any other parts of this dialog for the meantime (note: a better solution // would be to have member variables for each and every cell of the GUI matrix); // in case the character is not part of the analysis alphabet, we're trying to // convert it just like we did with the new character above char tempCharacter[2]; memset(tempCharacter, 0, sizeof(char) * 2); SetSel(0, 1); GetLine(0, tempCharacter, 1); ReplaceSel(CString(newCharacter)); SetSel(0, 1); // try to replace the temp character with something valid, if necessary tempCharacter[0] = MyToUpper(m_Alg->getAlphabet()->replaceInvalidLetter(true, tempCharacter[0])); // if the character is still invalid after the conversion, we proceed with a // null element which, as of today, is denoted by the '*' character if(!tempCharacter[0]) { tempCharacter[0] = m_Alg->getAlphabet()->getNullElement()->getValue(); } // at this point all conversion work is done, we can now assign the old character const char oldCharacter = tempCharacter[0]; // if old a new character are identical, return without doing anything else if(newCharacter == oldCharacter) { return; } // if the new character is invalid (not part of the alphabet), return as well if(!m_Alg->myisalpha2(newCharacter)) { return; } // we're gonna need those in a minute... int newCharacterIndexColumn = -1; int newCharacterIndexRow = -1; // get the size of the current maxtrix (either 5x5 or 6x6) const int matrixSize = m_Alg->getSize(); // go through all cells of the matrix and find the newly inserted character for(int indexRow=0; indexRow<matrixSize; indexRow++) { for(int indexColumn=0; indexColumn<matrixSize; indexColumn++) { // get the current character char currentCharacter = m_Alg->getCharOfMatrix(indexColumn, indexRow); // ignore null elements if(currentCharacter != m_Alg->getAlphabet()->getNullElement()->getValue()) { // assign indices for new character if(newCharacter == currentCharacter) { newCharacterIndexColumn = indexColumn; newCharacterIndexRow = indexRow; } } } } // this variable tells us if the new character did already exist in the matrix const bool newCharacterAlreadyExisted = newCharacterIndexColumn != -1 && newCharacterIndexRow != -1; // if the new character did NOT exist in the matrix, determine its indices (column/row) if(!newCharacterAlreadyExisted) { for(int indexRow=0; indexRow<matrixSize && newCharacterIndexRow<0; indexRow++) { for(int indexColumn=0; indexColumn<matrixSize && newCharacterIndexColumn<0; indexColumn++) { // get the content of the current matrix cell CString stringCurrentMatrixCell; m_Dia->getEinfeld(indexColumn, indexRow)->GetWindowText(stringCurrentMatrixCell); // check if we've arrived at the new character if(newCharacter == stringCurrentMatrixCell[0]) { // update indices for the new character newCharacterIndexColumn = indexColumn; newCharacterIndexRow = indexRow; // now update the matrix (actually insert the new character at its appropriate position) m_Alg->setElMatrix(newCharacter, newCharacterIndexColumn, newCharacterIndexRow); } } } } // in case the new character was already inserted, switch back to the old character if(newCharacterAlreadyExisted) { // update the dialog m_Dia->getEinfeld(newCharacterIndexColumn, newCharacterIndexRow)->SetWindowText(CString(oldCharacter)); // update the analysis m_Alg->setElMatrix(oldCharacter, newCharacterIndexColumn, newCharacterIndexRow); } // some clean-up work m_Alg->UpdateDigrams(m_Dia->getDec()); m_Alg->DoCipher(false, m_Dia->getDec(),MAXSHOWLETTER); m_Dia->UpdateListBox(); m_Dia->UpdatePassword(); #else char b1[2],b2[2]; if(!m_Alg->myisalpha2(nChar)) // TG, Umlaute oder französische Zeichen zu etwas ähnlichem ersetzen. nChar = m_Alg->getAlphabet()->replaceInvalidLetter(true, MyToUpper(nChar)); if (m_Alg->myisalpha2(nChar)) { int i,j,s,a,b,c,d; a=-1; c =-1; b2[1]=0; b2[0]=MyToUpper(nChar); SetSel(0, 1); GetLine(0,b1,2); ReplaceSel(b2); SetSel(0, 1); if(!m_Alg->myisalpha2(b1[0])){ // TG, Umlaute oder französische Zeichen zu etwas ähnlichem ersetzen. b1[0] = m_Alg->getAlphabet()->replaceInvalidLetter(true, b1[0]); if (b1[0] == '\0') b1[0] = m_Alg->getAlphabet()->getNullElement()->getValue(); } if (b1[0]==b2[0]||!m_Alg->myisalpha2(b2[0])) return; s=m_Alg->getSize(); for (i=0;i<s;i++) { for (j=0;j<s;j++) { if (b1[0] == m_Alg->getCharOfMatrix (i,j)) { // hole Indices vom alten Buchstaben a=i; b=j; } if (b2[0] == m_Alg->getCharOfMatrix (i,j)) { // hole Indices vom eingetippten Buchstaben c=i; d=j; } } } if (a>=0) { // zu ersetzender Buchstabe gefunden i=i; } else { // wie erfahre ich meine Koordinaten? for (i=0;(i<s)&&(a<0);i++) for (j=0;(j<s)&&(a<0);j++) { CString tmpstr; m_Dia->getEinfeld(i,j)->GetWindowText(tmpstr); if (b2[0] == tmpstr[0]) { a=i; b=j; } } i=i; } m_Alg->setElMatrix (b2[0], a, b); if (c>=0) { // eingetippter Buchstabe war schon vorhanden m_Dia->getEinfeld(c,d)->SetWindowText(b1); m_Alg->setElMatrix (b1[0], c, d); } else { i=i; } m_Alg->UpdateDigrams(m_Dia->getDec()); m_Alg->DoCipher(false, m_Dia->getDec(),MAXSHOWLETTER); m_Dia->UpdateListBox(); m_Dia->UpdatePassword(); } else // invalid character MessageBeep(MB_OK); #endif } // void CChEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) ///////////////////////////////////////////////////////////////////////////// // // // void CChEdit::OnLButtonUp(UINT nFlags, CPoint point ) { CEdit::OnLButtonUp(nFlags,point); SetSel(0, 1); // funktioniert nicht !!! }
[ "florian@marchal.de" ]
florian@marchal.de
1b7bc13bba02d2d686aa5ce22501e0ae111bd24b
0bd856ab632f9277456a11e42cc6339f6721fcde
/util/options.cc
8d94a4310033dc5cccce2fa4f3b225bbc1e4ff39
[ "BSD-3-Clause" ]
permissive
Meggie4/hotnvmdb
15e80b401481774fdc42246c2bee3217e452f2b8
8b65419d41a62ea275ffd7458dc0ee783311a4ea
refs/heads/master
2020-05-17T02:32:23.381835
2019-05-02T10:56:52
2019-05-02T10:56:52
183,454,851
0
0
null
null
null
null
UTF-8
C++
false
false
992
cc
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "leveldb/options.h" #include "leveldb/comparator.h" #include "leveldb/env.h" namespace leveldb { Options::Options() : comparator(BytewiseComparator()), create_if_missing(false), error_if_exists(false), paranoid_checks(false), env(Env::Default()), info_log(nullptr), write_buffer_size(4<<20), /////////////meggie chunk_size(64<<20), /////////////meggie max_open_files(1000), block_cache(nullptr), block_size(4096), block_restart_interval(16), max_file_size(2<<20), /////////////meggie //compression(kSnappyCompression), compression(kNoCompression), /////////////meggie reuse_logs(false), filter_policy(nullptr) { } } // namespace leveldb
[ "1224642332@qq.com" ]
1224642332@qq.com
717662992540698f4277be9eceb3e4bc26104fdf
9af4396a0b08edb5402b770c1d7d6b0552342018
/network/thread_mutex.h
d857c7d9584957124e49687bc8a5a7a3ca858255
[]
no_license
saicom/network
e63e474bc838e1da7cd05cbf135580ae5a168815
992410f8ea9edba2b51cab4fe68e52530829b952
refs/heads/master
2020-03-17T17:42:04.456510
2018-05-17T11:12:23
2018-05-17T11:12:23
133,798,776
0
0
null
null
null
null
UTF-8
C++
false
false
892
h
//! @file thread_mutex.h //! @brief 线程锁 #pragma once #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <pthread.h> #endif namespace utils { //! @class Thread_Mutex //! @brief 线程锁 class Thread_Mutex { public: Thread_Mutex(); ~Thread_Mutex(); //! 加锁 //! @return 0:成功, <0:失败 int acquire(); //! 解锁 //! @return 0:成功, <0:失败 int release(); private: //! 线程锁 #ifdef WIN32 CRITICAL_SECTION m_thread_section; #else pthread_mutex_t m_thread_mutex; #endif }; //! @class Thread_Mutex_Guard //! @brief 线程锁工具类 //! //! 此类在构造函数加锁, 析构函数解锁 class Thread_Mutex_Guard { public: //! 构造函数 //! @param mutex 用到的线程锁 Thread_Mutex_Guard(Thread_Mutex& mutex); //! 析构函数 ~Thread_Mutex_Guard(); private: Thread_Mutex& m_mutex; }; } // namepsace utils
[ "saicom@163.com" ]
saicom@163.com
a3fd50dce229e38ab7aab14e9767d507268dc5f8
bc997f47b4cffef395f0ce85d72f113ceb1466e6
/ICPC/CERC/cerc2013_l.cpp
ca5d217855a8d5b5cba2a40f6c65ede5adf44912
[ "LicenseRef-scancode-public-domain" ]
permissive
koosaga/olympiad
1f069dd480004c9df033b73d87004b765d77d622
fcb87b58dc8b5715b3ae2fac788bd1b7cac9bffe
refs/heads/master
2023-09-01T07:37:45.168803
2023-08-31T14:18:03
2023-08-31T14:18:03
45,691,895
246
49
null
2020-10-20T16:52:45
2015-11-06T16:01:57
C++
UTF-8
C++
false
false
228
cpp
#include <bits/stdc++.h> using namespace std; typedef long long lint; typedef long double llf; typedef pair<int, int> pi; int main(){ int t; cin >> t; while(t--){ int x; scanf("%d",&x); printf("%d\n", (1<<x) - 1); } }
[ "koosaga@gmail.com" ]
koosaga@gmail.com
9c6908e7825fa091c4e9d8cfcdd46d5a9eebf76b
a9fa300486c390308131a368b2f0b2758c552c1e
/others/Google_Code_Jam/2020/round1_a/C.cpp
ec8bf4cb2a585a3debd6b02b6a2ba3018466d4ee
[]
no_license
sekiya9311/Programming-Contest
630a426c022254ba8929096495bb09333a493fa0
3b3eb796b222122c22054e9d8111f484c8fa20f1
refs/heads/master
2023-03-16T11:02:46.598628
2023-03-04T06:34:59
2023-03-04T06:34:59
61,473,645
0
0
null
null
null
null
UTF-8
C++
false
false
4,645
cpp
#include <iostream> #include <string> #include <queue> #include <stack> #include <algorithm> #include <list> #include <vector> #include <complex> #include <utility> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <bitset> #include <ctime> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <cassert> #include <cstddef> #include <iomanip> #include <numeric> #include <tuple> #include <sstream> #include <fstream> #include <functional> using namespace std; #define REP(i, n) for (int (i) = 0; (i) < (n); (i)++) #define FOR(i, a, b) for (int (i) = (a); (i) < (b); (i)++) #define RREP(i, a) for(int (i) = (a) - 1; (i) >= 0; (i)--) #define FORR(i, a, b) for(int (i) = (a) - 1; (i) >= (b); (i)--) #define DEBUG(C) cerr << #C << " = " << C << endl; using LL = long long; using VI = vector<int>; using VVI = vector<VI>; using VL = vector<LL>; using VVL = vector<VL>; using VD = vector<double>; using VVD = vector<VD>; using PII = pair<int, int>; using PDD = pair<double, double>; using PLL = pair<LL, LL>; using VPII = vector<PII>; template<typename T> using VT = vector<T>; #define ALL(a) begin((a)), end((a)) #define RALL(a) rbegin((a)), rend((a)) #define SORT(a) sort(ALL((a))) #define RSORT(a) sort(RALL((a))) #define REVERSE(a) reverse(ALL((a))) #define MP make_pair #define FORE(a, b) for (auto &&a : (b)) #define EB emplace_back #define GREATER(T) T, VT<T> greater<T> template<typename T>inline bool chmax(T &a,T b){if(a<b){a=b;return true;}return false;} template<typename T>inline bool chmin(T &a,T b){if(a>b){a=b;return true;}return false;} const int INF = 1e9; const int MOD = INF + 7; const LL LLINF = 1e18; const int dx4[] = {0, 0, -1, 1}; const int dy4[] = {1, -1, 0, 0}; void solve(stringstream &out) { int R, C; scanf("%d%d", &R, &C); LL sum = 0; VPII cand; VT<VT<array<PII, 4>>> dirs(R, VT<array<PII, 4>>(C)); VVI memo(R, VI(C, -1)); VVI P(R, VI(C)); REP(i, R) REP(j, C) { scanf("%d", &P[i][j]); sum += P[i][j]; cand.EB(i, j); REP(k, 4) { const int ii = i + dx4[k]; const int jj = j + dy4[k]; dirs[i][j][k] = { ii, jj }; } } const auto in_range = [R, C](const int r, const int c) { return 0 <= r && r < R && 0 <= c && c < C; }; const auto in_range_p = [in_range](const PII &p) { return in_range(p.first, p.second); }; LL ans = sum; for (int dance_cnt = 0; ; dance_cnt++) { VPII rem; FORE(p, cand) { const int r = p.first; const int c = p.second; if (P[r][c] == 0) continue; int neighbor_cnt = 0, neighbor_sum = 0; REP(d, 4) { int dcnt = 0; while (true) { const int cur_r = dirs[r][c][d].first + dx4[d] * dcnt; const int cur_c = dirs[r][c][d].second + dy4[d] * dcnt; dcnt++; if (!in_range(cur_r, cur_c)) { dirs[r][c][d] = { cur_r, cur_c }; break; } if (P[cur_r][cur_c] == 0) continue; neighbor_cnt++; neighbor_sum += P[cur_r][cur_c]; dirs[r][c][d] = { cur_r, cur_c }; break; } } if (P[r][c] * neighbor_cnt < neighbor_sum) { rem.EB(r, c); } } if (rem.empty()) break; cand.clear(); FORE(e, rem) { sum -= P[e.first][e.second]; P[e.first][e.second] = 0; REP(d, 4) if (in_range_p(dirs[e.first][e.second][d])) { const auto nxt_r = dirs[e.first][e.second][d].first; const auto nxt_c = dirs[e.first][e.second][d].second; if (memo[nxt_r][nxt_c] == dance_cnt) { continue; } cand.EB(nxt_r, nxt_c); memo[nxt_r][nxt_c] = dance_cnt; } } ans += sum; } out << ans << '\n'; } int main(void) { // if (freopen("out.txt", "w", stdout) == NULL) { // cerr << "file open failed" << endl; // exit(1); // } int problem_count; scanf("%d", &problem_count); //string s;getline(cin, s); for (int test_no = 1; test_no <= problem_count; test_no++) { stringstream out; solve(out); printf("Case #%d: %s", test_no, out.str().c_str()); cerr << "Case #" << test_no << ": solved" << endl; } }
[ "sekiya9311@gmail.com" ]
sekiya9311@gmail.com
eb9a1b1c49673c655a9b78e52c680a8656405591
9793113b59a3fb69b9005304145f9553c79f75c4
/time.h
0ee0a2985f89f9e360d1af1ed8ae81cd1b7f7b56
[]
no_license
nkdhny/pq-richquery
f5c9117bfd2618dda6a446afa2a587a253723909
d63da33862b110721394ca2fdfa2c0455ad8e353
refs/heads/master
2020-04-13T04:17:04.704144
2014-03-17T09:15:02
2014-03-17T09:15:02
17,822,018
0
1
null
null
null
null
UTF-8
C++
false
false
114
h
#ifndef TIME_H #define TIME_H #include <sys/time.h> namespace nkdhny { long gettime_ms(); } #endif // TIME_H
[ "a.golomedov@robocv.ru" ]
a.golomedov@robocv.ru
c9b6e9919d8ed677065b01f2573ffbf889ed6baa
5d44c4dbbeccf48a4b789bca37fce483abe5cf16
/src/parsing/MICG_parser.h
0181f299744cb1e424f584e4fc05b5db33403052
[]
no_license
pbiggar/phc
13ec82817db6854e8541758a1f7e57da292ff1f1
96adc7bef3e222532196846c1f11ea4b2bc7930e
refs/heads/master
2023-03-10T18:06:00.905163
2021-07-08T14:55:32
2021-07-08T14:55:32
2,450,161
121
41
null
2021-07-08T14:55:33
2011-09-24T14:54:32
C++
UTF-8
C++
false
false
407
h
/* * phc -- the open source PHP compiler * See doc/license/README.license for licensing information * * Parser for the Macro inline code generator. */ #ifndef PHC_MICG_PARSER #define PHC_MICG_PARSER #include "lib/String.h" #include "MICG.h" class MICG_parser : virtual public GC_obj { public: MICG_parser (); MICG::Macro_list* parse (string str, string filename); }; #endif // PHC_MICG_PARSER
[ "paul.biggar@gmail.com" ]
paul.biggar@gmail.com
83818f103b8cb54b75102955f2e9909023aee085
fae551eb54ab3a907ba13cf38aba1db288708d92
/components/services/app_service/public/cpp/capability_access_update.h
313ad499e45952901342975741fe8b114ed2a7fe
[ "BSD-3-Clause" ]
permissive
xtblock/chromium
d4506722fc6e4c9bc04b54921a4382165d875f9a
5fe0705b86e692c65684cdb067d9b452cc5f063f
refs/heads/main
2023-04-26T18:34:42.207215
2021-05-27T04:45:24
2021-05-27T04:45:24
371,258,442
2
1
BSD-3-Clause
2021-05-27T05:36:28
2021-05-27T05:36:28
null
UTF-8
C++
false
false
3,039
h
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SERVICES_APP_SERVICE_PUBLIC_CPP_CAPABILITY_ACCESS_UPDATE_H_ #define COMPONENTS_SERVICES_APP_SERVICE_PUBLIC_CPP_CAPABILITY_ACCESS_UPDATE_H_ #include <string> #include "base/component_export.h" #include "base/macros.h" #include "components/account_id/account_id.h" #include "components/services/app_service/public/mojom/types.mojom.h" namespace apps { // Wraps two apps::mojom::CapabilityAccessPtr's, a prior state and a delta on // top of that state. The state is conceptually the "sum" of all of the previous // deltas, with "addition" or "merging" simply being that the most recent // version of each field "wins". // // The state may be nullptr, meaning that there are no previous deltas. // Alternatively, the delta may be nullptr, meaning that there is no change in // state. At least one of state and delta must be non-nullptr. // // The combination of the two (state and delta) can answer questions such as: // - Whether the app is accessing the camera? If the delta knows, that's the // answer. Otherwise, ask the state. // - Whether the app is accessing the microphone? If the delta knows, that's // the answer. Otherwise, ask the state. // // An CapabilityAccessUpdate is read-only once constructed. All of its fields // and methods are const. The constructor caller must guarantee that the // CapabilityAccessPtr references remain valid for the lifetime of the // CapabilityAccessUpdate. // // See components/services/app_service/README.md for more details. class COMPONENT_EXPORT(APP_UPDATE) CapabilityAccessUpdate { public: // Modifies |state| by copying over all of |delta|'s known fields: those // fields whose values aren't "unknown". The |state| may not be nullptr. static void Merge(apps::mojom::CapabilityAccess* state, const apps::mojom::CapabilityAccess* delta); // At most one of |state| or |delta| may be nullptr. CapabilityAccessUpdate(const apps::mojom::CapabilityAccess* state, const apps::mojom::CapabilityAccess* delta, const AccountId& account_id); CapabilityAccessUpdate(const CapabilityAccessUpdate&) = delete; CapabilityAccessUpdate& operator=(const CapabilityAccessUpdate&) = delete; // Returns whether this is the first update for the given AppId. // Equivalently, there are no previous deltas for the AppId. bool StateIsNull() const; const std::string& AppId() const; apps::mojom::OptionalBool Camera() const; bool CameraChanged() const; apps::mojom::OptionalBool Microphone() const; bool MicrophoneChanged() const; const ::AccountId& AccountId() const; private: const apps::mojom::CapabilityAccess* state_; const apps::mojom::CapabilityAccess* delta_; const ::AccountId& account_id_; }; } // namespace apps #endif // COMPONENTS_SERVICES_APP_SERVICE_PUBLIC_CPP_CAPABILITY_ACCESS_UPDATE_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
de1af059ec9c62e92b15ef4323d09c0d79a7e20c
c4fe6870c29dfd244e45d88f134d2bfcf226a522
/code_blank/Companion.h
9d2023e79eb5b05735b50083eaabb3054d9f26bd
[]
no_license
Neevan09/NNSample
c4a907c4b01cbe96fb374570dfb3832ce3b865df
2390372f7d7f968b84960d4aa1d93a57dc8f7d37
refs/heads/master
2020-03-14T06:57:50.362708
2018-04-29T13:54:06
2018-04-29T13:54:06
131,493,241
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
h
#pragma once #include <AnimationComponent.h> #include <TransformComponent.h> #include<TofuMath.h> // Player Companion Class // Sword/Gun for the player to use in combat // Also may act as the map displayer, among other possible features class Companion { public: Companion(CodeEngine::math::float3); ~Companion(); void Update(float, CodeEngine::math::float3, CodeEngine::math::float3); void FixedUpdate(float, CodeEngine::math::float3, CodeEngine::math::float3); void SetInUse(bool); void SetActive(bool); void SetTarget(CodeEngine::math::float3); bool ActiveSelf(); CodeEngine::math::float3 GetPosition(); private: CodeEngine::TransformComponent tComp; CodeEngine::AnimationComponent aComp; bool inUse; bool targetSet; bool isActive; CodeEngine::math::float3 target; CodeEngine::math::float3 targetLastPos; CodeEngine::math::float3 targetFwd; float distance = 50.0f; float height = 1.7f; float heightDamping = 1.0f; float positionDamping = 2.0f; float rotationDamping = 1.0f; };
[ "Naveen@DESKTOP-794QGAI" ]
Naveen@DESKTOP-794QGAI
2335b7b308b7a3ab60801949e2ac7968660a392e
2e57bd599c3f95ddc1a312f059962735895fc0cf
/grader/d64_q3b_heap_level/student.h
fb7a1759b7b4ca9a1b5e892b9a4d37cf52f387af
[]
no_license
noppakorn/2110211
37b14752783b414bf1846e44308fdf0fbc279636
61bca645cbe9b922282a54134c47b439f2be9a2e
refs/heads/main
2023-09-05T23:34:31.913629
2021-11-24T15:24:27
2021-11-24T15:24:27
394,025,766
2
1
null
null
null
null
UTF-8
C++
false
false
513
h
#include <algorithm> #include <vector> #include "priority_queue.h" template <typename T,typename Comp> std::vector<T> CP::priority_queue<T,Comp>::at_level(size_t k) const { std::vector<T> r; r.reserve(1 << k); size_t ind = 0; for (size_t i = 0; i < k; ++i) { ind += 1 << i; } for (size_t i = ind; i < std::min(ind + (1 << k), mSize); ++i) { std::cout << i << std::endl; r.emplace_back(mData[ind+i]); } std::sort(r.rbegin(), r.rend(), mLess); return r; }
[ "noppakorn@noppakorn.com" ]
noppakorn@noppakorn.com
7317ff3536d7c6cf6c945b7fddb34f0538c354c6
4491a810f77d635620442c6ef5e70ade50eecbe8
/file/BZOJ1066.cpp
d65a9b70dfccc1790fffe3d628c65c4a8b169d00
[]
no_license
cooook/OI_Code
15473a3b7deafa365d20ae36820f3281884209bf
45d46b69f2d02b31dcc42d1cd5a5593a343d89af
refs/heads/master
2023-04-03T21:35:57.365441
2021-04-15T14:36:02
2021-04-15T14:36:02
358,290,530
2
1
null
null
null
null
UTF-8
C++
false
false
2,863
cpp
# include <bits/stdc++.h> const int inf = 0x3f3f3f3f, MAXN = 1e6+5; int n, m, d[MAXN], first[MAXN], e = 2, S, T, D, map[50][50], id[50][50][2], cnt; char s[50][50]; inline int read() { int x = 0, f = 1; char ch = getchar(); for (; ch < '0' | ch > '9'; ch = getchar()) if (ch == '-') f = -f; for (; ch >= '0' & ch <= '9'; ch = getchar()) x = x * 10 + (ch ^ 48); return x * f; } struct edge{ int u, v, w, next; }a[2000000]; inline void push(int u, int v, int w) { a[e] = (edge){u, v, w, first[u]}; first[u] = e++; a[e] = (edge){v, u, 0, first[v]}; first[v] = e++; } inline bool bfs() { std::queue<int> Q; Q.push(S); memset(d, -1, sizeof d); d[S] = 1; while (!Q.empty()) { register int u = Q.front(); Q.pop(); if (u == T) return true; for (int i = first[u]; i; i = a[i].next) if (a[i].w && d[a[i].v] == -1) d[a[i].v] = d[u] + 1, Q.push(a[i].v); } return false; } inline int dfs(int u, int cap) { if (u == T || !cap) return cap; int Ans = 0, w; for (int i = first[u]; i; i = a[i].next) { register int v = a[i].v; if (d[v] == d[u] + 1 && a[i].w) { w = dfs(v, std::min(cap, a[i].w)); Ans += w; a[i].w -= w; a[i ^ 1].w += w; cap -= w; if (!cap) break; } } if (!Ans) d[u] = -1; return Ans; } inline int dinic() { int Ans = 0; while (bfs()) Ans += dfs(S, inf); return Ans; } inline bool dis(int a, int b, int c, int d) { return abs(a - c) + abs(b - d) <= D; } inline void Link(int x, int y) { for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (dis(i, j, x, y) && map[i][j]) { if (x == i && y == j) continue; push(id[x][y][1], id[i][j][0], inf); } } inline int read_char() { char ch = getchar(); for (; !isdigit(ch); ch = getchar()); return ch - '0'; } int main() { n = read(), m = read(), D = read(); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) { map[i][j] = read_char(); id[i][j][0] = ++ cnt; id[i][j][1] = ++ cnt; if (map[i][j]) push(id[i][j][0], id[i][j][1], map[i][j]); } for (int i = 1; i <= n; ++i) scanf("%s", s[i] + 1); for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) if (map[i][j]) Link(i, j); int Ans = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (s[i][j] == 'L') push(S, id[i][j][0], 1), ++ Ans; T = ++ cnt; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (std::min(std::min(i, n - i + 1), std::min(j, m - j + 1)) <= D && map[i][j]) push(id[i][j][1], T, inf); printf("%d\n", Ans - dinic()); return 0; }
[ "zyfan020305@gmail.com" ]
zyfan020305@gmail.com
740766824d91b3561b7bdffadbfb97f65f746b08
45e728f592f503e8e3689d3c31aa81b15ba17af0
/code/src/obstacle.h
115159dc03f5bd83944a997efe565f055a9b118b
[]
no_license
gloriahwang/FlockSimulator
ea62399b42b05197599804e50c12299c97997f94
3b24bc672cb864dd47f5ae98d2fb65f8f1e93c74
refs/heads/master
2021-08-16T14:48:20.820149
2017-11-20T02:18:16
2017-11-20T02:18:16
105,466,468
1
0
null
null
null
null
UTF-8
C++
false
false
598
h
#ifndef CLOTHSIM_OBSTACLE_H #define CLOTHSIM_OBSTACLE_H #include "clothMesh.h" #include "CGL/CGL.h" using namespace CGL; using namespace std; struct Obstacle { enum e_obstacle_type {AVOID_TYPE = 1, STATIC_SEEK_TYPE = 2, FOOD_TYPE = 3}; Obstacle(const Vector3D &position, double size, double detection_radius, e_obstacle_type obstacle_type) : position(position), size(size), detection_radius(detection_radius), obstacle_type(obstacle_type) {} Vector3D position; double size; double detection_radius; e_obstacle_type obstacle_type; }; #endif //CLOTHSIM_OBSTACLE_H
[ "gloria.hwang@berkeley.edu" ]
gloria.hwang@berkeley.edu
3d8541a6124e37cea81c214ba1c13a8cdcaebf4b
6627d27fc69922f179b14b612b366bbf0bc4eff9
/xerolibs/xerobase/motorencodersubsystem/MotorEncoderPowerAction.cpp
d388359a8b990a1fda035e7e84aafac2edb8c929
[]
no_license
errorcodexero/newarch
1a4773377197174ae58b6e4ef6d670bf197c643b
e69a864012e09548014ad208affeb8901835a654
refs/heads/master
2021-06-03T16:28:41.840622
2020-03-15T18:15:08
2020-03-15T18:15:08
139,747,384
9
6
null
2020-01-31T05:35:34
2018-07-04T16:54:36
C++
UTF-8
C++
false
false
2,635
cpp
#include "MotorEncoderPowerAction.h" #include "MotorEncoderSubsystem.h" #include "Robot.h" using namespace xero::misc ; namespace xero { namespace base { std::vector<std::string> MotorEncoderPowerAction::columns_ = { "time", "pos", "vel", "accel", "out" } ; MotorEncoderPowerAction::MotorEncoderPowerAction(MotorEncoderSubsystem &subsystem, double v) : SingleMotorPowerAction(subsystem, v) { plot_id_ = -1; } MotorEncoderPowerAction::MotorEncoderPowerAction(MotorEncoderSubsystem &subsystem, const std::string &name) : SingleMotorPowerAction(subsystem, name) { plot_id_ = -1; } MotorEncoderPowerAction::MotorEncoderPowerAction(MotorEncoderSubsystem &subsystem, double v, double d) : SingleMotorPowerAction(subsystem, v, d) { plot_id_ = subsystem.initPlot(subsystem.getName() + "-power"); } MotorEncoderPowerAction::MotorEncoderPowerAction(MotorEncoderSubsystem &subsystem, const std::string &name, const std::string &durname) : SingleMotorPowerAction(subsystem, name, durname) { plot_id_ = subsystem.initPlot(subsystem.getName() + "-power"); } MotorEncoderPowerAction::~MotorEncoderPowerAction() { } void MotorEncoderPowerAction::start() { SingleMotorPowerAction::start(); if (plot_id_ != -1) { getSubsystem().startPlot(plot_id_, columns_); } } void MotorEncoderPowerAction::run() { SingleMotorPowerAction::run(); if (plot_id_ != -1) { MotorEncoderSubsystem &sub = dynamic_cast<MotorEncoderSubsystem &>(getSubsystem()); std::vector<double> data; data.push_back(getElapsed()); data.push_back(sub.getPosition()); data.push_back(sub.getSpeedometer().getVelocity()); data.push_back(sub.getSpeedometer().getAcceleration()); data.push_back(getPower()); sub.addPlotData(plot_id_, data); } if (isDone() && plot_id_ != -1) { getSubsystem().endPlot(plot_id_); plot_id_ = -1; } } void MotorEncoderPowerAction::cancel() { SingleMotorPowerAction::cancel(); } } }
[ "butchg@comcast.net" ]
butchg@comcast.net
f2326e4f11c5e3927c11a8c1e8289df3bf15d0f2
40ed901896c236441a3c0692e2a8379f5ff85297
/ESP32Remote/CMainApplication.h
856be629e8b7b8d31d15ed562d2948d69de20e3e
[]
no_license
lgg-smart-house/universal-IR-remote
3c00082b3086584a986bf7cb352b323d8532be6e
d59ee1e319216625966e3400053174027dc759b2
refs/heads/master
2021-06-19T09:51:19.809040
2017-07-18T19:54:54
2017-07-18T19:54:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,342
h
#pragma once #include <vector> #include <driver/adc.h> #include "FS.h" #include "SD.h" #include "SPI.h" #include "CEventManager.h" #include "CWifiManager.h" #include "CLcdManager.h" #include "CIRControl.h" #include "IRStatus.h" #define BATTERY_ADC_CHANNEL ADC1_CHANNEL_3 #define PL(msg) Serial.println(msg); using namespace std; class CMainApplication : CEventManager { public: CMainApplication(); ~CMainApplication(); void init(); void loop() override; private: CIRControl irControl; CLcdManager lcdManager; CWifiManager wifiManager; IRStatus getIRSignalNameList(vector<String> * _signalNameList); IRStatus saveIRSignal(String _name, CIRControl * _irControl, bool _bOverwrite = false); IRStatus loadIRSignal(String _name, CIRControl * _irControl); int16_t getBatteryCharge(); String saveIRSignalEvent(String _eventData); String loadIRSignalEvent(String _eventData); String sendIRSignalEvent(String _eventData); String receiveIRSignalEvent(String _eventData); String getBatteryChargeEvent(String _eventData); String getIRSignalNameListEvent(String _eventData); String removeIRSignalEvent(String _eventData); String renameIRSignalEvent(String _eventData); String deepSleep(uint64_t _time, bool _bSeconds); String deepSleepEvent(String _eventData); void updateLoadMenu(); };
[ "lucaschuttler@gmail.com" ]
lucaschuttler@gmail.com
2836f3df09510e597728f3dc6096b1e330a625c2
3f65d15d837c92956a4399202a753af6d001a257
/attempt/122-1.cpp
04ef56aa0571940224040f604213e4bc8d542678
[]
no_license
yjl9903/XLor-UVa
e1f8c35bc41043a926666b3645519a65795d6238
46fb80f179f22321b9af00edafcc3fa698e82bcd
refs/heads/master
2020-03-18T06:25:49.162647
2018-08-27T02:35:29
2018-08-27T02:35:29
134,395,093
0
0
null
null
null
null
UTF-8
C++
false
false
2,479
cpp
#include <cstdio> #include <queue> #include <vector> using namespace std; char x[300], cmd[300]; int flag; struct node{ int data = 0; bool check = false; node* left = NULL; node* right = NULL; }; node* newNode() { return new node(); } node* root = NULL; queue<node*> que; vector<int> out; int addNode(int num) { //printf("%d %s\n", num, cmd); //if (cmd[0] == ')') // root -> data = num, root -> check = true; int i = 0; node* p = root; while (cmd[i] != ')') { if (cmd[i] == 'L') { if(p -> left == NULL) p -> left = newNode(); p = p-> left; } else { if (p -> right == NULL) p -> right = newNode(); p = p -> right; } i++; } p -> data = num; if (p -> check) return 0; p -> check = true; //printf("%d %s\n", num, cmd); return 1; } void remove(node* p) { if (p == NULL) return; remove(p -> left); remove(p -> right); delete p; } int read() { remove(root); flag = 0; root = new node(); int num; while (scanf("%s", x) != EOF) { if (x[1] == ')') return 1; sscanf(x, "(%d,%s)", &num, cmd); flag = addNode(num); } return 0; } int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); while (read()) { out.clear(); if (flag == 0) { printf("not complete\n"); } else { node* p = root; que.push(root); while (!que.empty()) { p = que.front(); que.pop(); if (p -> check) { out.push_back(p -> data); //printf("%d\n", p -> data); } else { printf("not complete\n"); flag = 0; break; } if (p -> left != NULL) que.push(p -> left); if (p -> right != NULL) que.push(p -> right); } if (flag) { printf("%d", out[0]); for (int i = 1; i < out.size(); i++) printf(" %d", out[i]); printf("\n"); } } } return 0; }
[ "yjl9903@vip.qq.com" ]
yjl9903@vip.qq.com
15e7ffdd1a45551347dcc6a7b9559be94621778c
c5ae06867a1af8e55e854e6be4c3079cad076d4a
/server/third_party/Box2D/Collision/b2TimeOfImpact.cpp
b44cd66113590c40b4983ba17cdda3bd53f14189
[ "Zlib" ]
permissive
xiaol-luo/lxl_cpp
54dbef02e551e52e54700a94de34b095f45bdcfc
3b283e9d6d0623f49715ccf7d5eeb837fe3ab61f
refs/heads/master
2021-06-16T01:29:42.909728
2021-03-03T06:34:24
2021-03-03T06:34:24
134,434,723
3
3
null
null
null
null
UTF-8
C++
false
false
11,704
cpp
/* * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "Box2D/Collision/b2Collision.h" #include "Box2D/Collision/b2Distance.h" #include "Box2D/Collision/b2TimeOfImpact.h" #include "Box2D/Collision/Shapes/b2CircleShape.h" #include "Box2D/Collision/Shapes/b2PolygonShape.h" #include "Box2D/Common/b2Timer.h" #include <stdio.h> float32 b2_toiTime, b2_toiMaxTime; int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; int32 b2_toiRootIters, b2_toiMaxRootIters; // struct b2SeparationFunction { enum Type { e_points, e_faceA, e_faceB }; // TODO_ERIN might not need to return the separation float32 Initialize(const b2SimplexCache* cache, const b2DistanceProxy* proxyA, const b2Sweep& sweepA, const b2DistanceProxy* proxyB, const b2Sweep& sweepB, float32 t1) { m_proxyA = proxyA; m_proxyB = proxyB; int32 count = cache->count; //b2Assert(0 < count && count < 3); m_sweepA = sweepA; m_sweepB = sweepB; b2Transform xfA, xfB; m_sweepA.GetTransform(&xfA, t1); m_sweepB.GetTransform(&xfB, t1); if (count == 1) { m_type = e_points; b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); b2Vec2 pointA = b2Mul(xfA, localPointA); b2Vec2 pointB = b2Mul(xfB, localPointB); m_axis = pointB - pointA; float32 s = m_axis.Normalize(); return s; } else if (cache->indexA[0] == cache->indexA[1]) { // Two points on B and one on A. m_type = e_faceB; b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); m_axis = b2Cross(localPointB2 - localPointB1, 1_fx); m_axis.Normalize(); b2Vec2 normal = b2Mul(xfB.q, m_axis); m_localPoint = "0.5"_fx * (localPointB1 + localPointB2); b2Vec2 pointB = b2Mul(xfB, m_localPoint); b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); b2Vec2 pointA = b2Mul(xfA, localPointA); float32 s = b2Dot(pointA - pointB, normal); if (s < 0_fx) { m_axis = -m_axis; s = -s; } return s; } else { // Two points on A and one or two points on B. m_type = e_faceA; b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); m_axis = b2Cross(localPointA2 - localPointA1, 1_fx); m_axis.Normalize(); b2Vec2 normal = b2Mul(xfA.q, m_axis); m_localPoint = "0.5"_fx * (localPointA1 + localPointA2); b2Vec2 pointA = b2Mul(xfA, m_localPoint); b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); b2Vec2 pointB = b2Mul(xfB, localPointB); float32 s = b2Dot(pointB - pointA, normal); if (s < 0_fx) { m_axis = -m_axis; s = -s; } return s; } } // float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const { b2Transform xfA, xfB; m_sweepA.GetTransform(&xfA, t); m_sweepB.GetTransform(&xfB, t); switch (m_type) { case e_points: { b2Vec2 axisA = b2MulT(xfA.q, m_axis); b2Vec2 axisB = b2MulT(xfB.q, -m_axis); *indexA = m_proxyA->GetSupport(axisA); *indexB = m_proxyB->GetSupport(axisB); b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); b2Vec2 pointA = b2Mul(xfA, localPointA); b2Vec2 pointB = b2Mul(xfB, localPointB); float32 separation = b2Dot(pointB - pointA, m_axis); return separation; } case e_faceA: { b2Vec2 normal = b2Mul(xfA.q, m_axis); b2Vec2 pointA = b2Mul(xfA, m_localPoint); b2Vec2 axisB = b2MulT(xfB.q, -normal); *indexA = -1; *indexB = m_proxyB->GetSupport(axisB); b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); b2Vec2 pointB = b2Mul(xfB, localPointB); float32 separation = b2Dot(pointB - pointA, normal); return separation; } case e_faceB: { b2Vec2 normal = b2Mul(xfB.q, m_axis); b2Vec2 pointB = b2Mul(xfB, m_localPoint); b2Vec2 axisA = b2MulT(xfA.q, -normal); *indexB = -1; *indexA = m_proxyA->GetSupport(axisA); b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); b2Vec2 pointA = b2Mul(xfA, localPointA); float32 separation = b2Dot(pointA - pointB, normal); return separation; } default: b2Assert(false); *indexA = -1; *indexB = -1; return 0_fx; } } // float32 Evaluate(int32 indexA, int32 indexB, float32 t) const { b2Transform xfA, xfB; m_sweepA.GetTransform(&xfA, t); m_sweepB.GetTransform(&xfB, t); switch (m_type) { case e_points: { b2Vec2 localPointA = m_proxyA->GetVertex(indexA); b2Vec2 localPointB = m_proxyB->GetVertex(indexB); b2Vec2 pointA = b2Mul(xfA, localPointA); b2Vec2 pointB = b2Mul(xfB, localPointB); float32 separation = b2Dot(pointB - pointA, m_axis); return separation; } case e_faceA: { b2Vec2 normal = b2Mul(xfA.q, m_axis); b2Vec2 pointA = b2Mul(xfA, m_localPoint); b2Vec2 localPointB = m_proxyB->GetVertex(indexB); b2Vec2 pointB = b2Mul(xfB, localPointB); float32 separation = b2Dot(pointB - pointA, normal); return separation; } case e_faceB: { b2Vec2 normal = b2Mul(xfB.q, m_axis); b2Vec2 pointB = b2Mul(xfB, m_localPoint); b2Vec2 localPointA = m_proxyA->GetVertex(indexA); b2Vec2 pointA = b2Mul(xfA, localPointA); float32 separation = b2Dot(pointA - pointB, normal); return separation; } default: b2Assert(false); return 0_fx; } } const b2DistanceProxy* m_proxyA; const b2DistanceProxy* m_proxyB; b2Sweep m_sweepA, m_sweepB; Type m_type; b2Vec2 m_localPoint; b2Vec2 m_axis; }; // CCD via the local separating axis method. This seeks progression // by computing the largest time at which separation is maintained. void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) { b2Timer timer; ++b2_toiCalls; output->state = b2TOIOutput::e_unknown; output->t = input->tMax; const b2DistanceProxy* proxyA = &input->proxyA; const b2DistanceProxy* proxyB = &input->proxyB; b2Sweep sweepA = input->sweepA; b2Sweep sweepB = input->sweepB; // Large rotations can make the root finder fail, so we normalize the // sweep angles. sweepA.Normalize(); sweepB.Normalize(); float32 tMax = input->tMax; float32 totalRadius = proxyA->m_radius + proxyB->m_radius; float32 target = b2Max(b2_linearSlop, totalRadius - 3_fx * b2_linearSlop); float32 tolerance = "0.25"_fx * b2_linearSlop; b2Assert(target > tolerance); float32 t1 = 0_fx; const int32 k_maxIterations = 20; // TODO_ERIN b2Settings int32 iter = 0; // Prepare input for distance query. b2SimplexCache cache; cache.count = 0; b2DistanceInput distanceInput; distanceInput.proxyA = input->proxyA; distanceInput.proxyB = input->proxyB; distanceInput.useRadii = false; // The outer loop progressively attempts to compute new separating axes. // This loop terminates when an axis is repeated (no progress is made). for(;;) { b2Transform xfA, xfB; sweepA.GetTransform(&xfA, t1); sweepB.GetTransform(&xfB, t1); // Get the distance between shapes. We can also use the results // to get a separating axis. distanceInput.transformA = xfA; distanceInput.transformB = xfB; b2DistanceOutput distanceOutput; b2Distance(&distanceOutput, &cache, &distanceInput); // If the shapes are overlapped, we give up on continuous collision. if (distanceOutput.distance <= 0_fx) { // Failure! output->state = b2TOIOutput::e_overlapped; output->t = 0_fx; break; } if (distanceOutput.distance < target + tolerance) { // Victory! output->state = b2TOIOutput::e_touching; output->t = t1; break; } // Initialize the separating axis. b2SeparationFunction fcn; fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); #if 0 // Dump the curve seen by the root finder { const int32 N = 100; float32 dx = 1_fx / N; float32 xs[N+1]; float32 fs[N+1]; float32 x = 0_fx; for (int32 i = 0; i <= N; ++i) { sweepA.GetTransform(&xfA, x); sweepB.GetTransform(&xfB, x); float32 f = fcn.Evaluate(xfA, xfB) - target; printf("%g %g\n", x, f); xs[i] = x; fs[i] = f; x += dx; } } #endif // Compute the TOI on the separating axis. We do this by successively // resolving the deepest point. This loop is bounded by the number of vertices. bool done = false; float32 t2 = tMax; int32 pushBackIter = 0; for (;;) { // Find the deepest point at t2. Store the witness point indices. int32 indexA, indexB; float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); // Is the final configuration separated? if (s2 > target + tolerance) { // Victory! output->state = b2TOIOutput::e_separated; output->t = tMax; done = true; break; } // Has the separation reached tolerance? if (s2 > target - tolerance) { // Advance the sweeps t1 = t2; break; } // Compute the initial separation of the witness points. float32 s1 = fcn.Evaluate(indexA, indexB, t1); // Check for initial overlap. This might happen if the root finder // runs out of iterations. if (s1 < target - tolerance) { output->state = b2TOIOutput::e_failed; output->t = t1; done = true; break; } // Check for touching if (s1 <= target + tolerance) { // Victory! t1 should hold the TOI (could be 0.0). output->state = b2TOIOutput::e_touching; output->t = t1; done = true; break; } // Compute 1D root of: f(x) - target = 0 int32 rootIterCount = 0; float32 a1 = t1, a2 = t2; for (;;) { // Use a mix of the secant rule and bisection. float32 t; if (rootIterCount & 1) { // Secant rule to improve convergence. t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); } else { // Bisection to guarantee progress. t = "0.5"_fx * (a1 + a2); } ++rootIterCount; ++b2_toiRootIters; float32 s = fcn.Evaluate(indexA, indexB, t); if (b2Abs(s - target) < tolerance) { // t2 holds a tentative value for t1 t2 = t; break; } // Ensure we continue to bracket the root. if (s > target) { a1 = t; s1 = s; } else { a2 = t; s2 = s; } if (rootIterCount == 50) { break; } } b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); ++pushBackIter; if (pushBackIter == b2_maxPolygonVertices) { break; } } ++iter; ++b2_toiIters; if (done) { break; } if (iter == k_maxIterations) { // Root finder got stuck. Semi-victory. output->state = b2TOIOutput::e_failed; output->t = t1; break; } } b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); float32 time = timer.GetMilliseconds(); b2_toiMaxTime = b2Max(b2_toiMaxTime, time); b2_toiTime += time; }
[ "xiaol.luo@163.com" ]
xiaol.luo@163.com
51f808220c8dc2088b899bacca0d0532121510a8
c1f3cf1bb6e2a0be181630ea2a992d971b37b278
/subtitle/main.cc
b0a3860ca82a3849ef11a1e6e3dab76f68f08eeb
[]
no_license
leeonky/clayer
1f00b7ccafec6450b6672f714dd4e9c39bf962e9
26216dac5c1979118f207a502a662afd04a8b353
refs/heads/master
2023-08-24T08:45:01.410961
2021-10-07T14:43:34
2021-10-07T14:43:34
107,023,342
1
0
null
null
null
null
UTF-8
C++
false
false
4,785
cc
#include "stdexd/stdexd.h" #include "mem/circular_shm.h" #include "iobus/iobus.h" #include "media/media.h" #include "media/sub_srt.h" #include "media/sub_ass.h" #include <sstream> #include <iostream> #include <vector> namespace { int w=-1, h=-1; int subtitle_buffer_key = 2; int subtitle_buffer_count = 4; int layer_id = 0; char font_file[512] = {}; circular_shm *shms[MAX_LAYER_COUNT]; int subtitle_bottom_pos = -5; int font_size_k = 50; const char *file_name; SDL_Color srt_subtitle_color = {255, 255, 255, 0}; void process_args(int argc, char **argv) { file_name = command_argument().require_full_argument("size", 's', [&](const char *arg){ sscanf(arg, "%dx%d", &w, &h); }).require_full_argument("font", 'f', [&](const char *arg){ sscanf(arg, "%s", font_file); }).parse(argc, argv); if(!file_name) { fprintf(app_stderr, "Error[subtitle]: require subtitle file\n"); exit(-1); } if(!strlen(font_file)) { fprintf(app_stderr, "Error[subtitle]: require font file\n"); exit(-1); } } size_t render_lines(iobus &iob, std::istringstream &lines, uint8_t *buffer, TTF_Font *font, const SDL_Color &color, int &h) { std::string line; if(!std::getline(lines, line)) return 0; size_t offset = render_lines(iob, lines, buffer, font, color, h); TTF_RenderUTF8_Blended(font, line.c_str(), color, [&](SDL_Surface *surface) { SDL_LockSurface(surface); size_t size = surface->pitch*surface->h; memcpy(buffer+offset, surface->pixels, size); h -= surface->h; iob.post_some(" %d=>%d,%d,%d,%d,%d", offset, (w-surface->w)/2, h, surface->w, surface->h, surface->pitch); offset += size; SDL_UnlockSurface(surface); return 0; }); return offset; } inline std::function<void(const std::string &)> subtitle_action(iobus &iob, circular_shm &shm, TTF_Font *font, const SDL_Color &color) { return [&, font](const std::string &title) { if(!title.empty()) { std::istringstream f(title); uint8_t *buffer = (uint8_t *)shm.allocate(); iob.post_some("LAYER buffer:%d index:%d id:%d width:%d height:%d", subtitle_buffer_key, shm.index, layer_id, w, h); int title_h = ((100+subtitle_bottom_pos)%100)*h/100; render_lines(iob, f, buffer, font, color, title_h); iob.post(""); } else iob.post("NOLAYER id:%d", layer_id); }; } inline std::function<int(FILE *)> process_srt(iobus &iob, circular_shm &shm) { return [&](FILE *sub_file){ subtitle_srt srt(sub_file); return TTF_OpenFont(font_file, w/font_size_k, [&](TTF_Font *font) { return main_transform(iob, shms, frame_event, [&](int, int, int64_t pts) { iob.recaption_and_post(); srt.query_item(pts, subtitle_action(iob, shm, font, srt_subtitle_color)); return 0; }); }); }; } inline size_t pixel_copy(uint8_t *buffer, ASS_Image *image) { uint32_t *colors = (uint32_t *)buffer; uint32_t color = ((image->color>>8) & 0xffffff); uint8_t *bitmap = image->bitmap; for(int y=0; y<image->h; ++y) { for(int x=0; x<image->w; ++x) colors[x] = ((bitmap[x] << 24) & 0xff000000) + color; colors += image->stride; bitmap += image->stride; } return image->stride*4 * image->h; } inline int process_ass(iobus &iob, circular_shm &shm) { return subtitle_ass(file_name, w, h, font_file, [&](ASS_Renderer *renderer, ASS_Track *track){ return main_transform(iob, shms, frame_event, [&](int, int, int64_t pts) { iob.recaption_and_post(); ass_render_frame(renderer, track, pts, [&](ASS_Image *image) { if(image) { uint8_t *buffer = (uint8_t *)shm.allocate(); iob.post_some("LAYER buffer:%d index:%d id:%d width:%d height:%d", subtitle_buffer_key, shm.index, layer_id, w, h); for(int offset=0; image; image = image->next) { size_t size = pixel_copy(buffer+offset, image); iob.post_some(" %d=>%d,%d,%d,%d,%d", offset, image->dst_x, image->dst_y, image->w, image->h, image->stride*4); offset += size; } iob.post(""); } else iob.post("NOLAYER id:%d", layer_id); }); return 0; }); }); } } int main(int argc, char **argv) { process_args(argc, argv); iobus iob(stdin, stdout, stderr); const char *file_ext = strrchr(file_name, '.'); return forward_untill(iob, video_event, [&](int fw, int fh, enum AVPixelFormat /*av_format*/){ w = w==-1 ? fw : w; h = h==-1 ? fh : h; iob.recaption_and_post(); return circular_shm::create(w*h*4, subtitle_buffer_count, [&](circular_shm &shm){ iob.post("%s", shm.serialize_to_string(subtitle_buffer_key)); return !strcmp(file_ext, ".ass") ? process_ass(iob, shm) : fopen(file_name, "rb", process_srt(iob, shm)); }); }); }
[ "leeonky@gmail.com" ]
leeonky@gmail.com
fe934d89fab8466d29a8951796b83a016053dbf9
cde27c00d54aeb700b3dfed9ba284c6118c16363
/TheUnbeatableBoss/Tile.cpp
bdc4f4298f100c4d8df3e224b4ad35154bcbee0a
[]
no_license
ash9991win/NeuralNetworksProject
0acfd02b248607c7e505640d2f739e624b462883
0e221ee0194c9d799c91f734ff1b12c5a3a5479e
refs/heads/master
2021-01-20T19:57:04.915524
2016-07-14T18:40:36
2016-07-14T18:40:36
61,472,084
0
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
#include"pch.h" #include "Tile.h" void Tile::SetIndex(int r, int c) { mRowIndex = r; mColIndex = c; mPosition.x = r * TILE_WIDTH; mPosition.y = c * TILE_HEIGHT; } bool Tile::IsTileInPosition(const sf::Vector2f & position) const { return ((position.x >= mPosition.x) && (position.x <= (mPosition.x + TILE_WIDTH)) && (position.y >= mPosition.y) && (position.y <= (mPosition.y + TILE_HEIGHT))); }
[ "ash9991win@gmail.com" ]
ash9991win@gmail.com
10e05e40bc7f69ff500fcf5eb1231f100813304a
2dba1dc8e5c62631ad9801222d8a34b72b8a5635
/UVa Online Judge/volume114/11487 Gathering Food/program.cpp
4f5f9afe855e25f9d84393232697851ced5003ab
[]
no_license
dingswork/Code
f9e875417238efd04294b86c0b4261b4da867923
669139b70d0dbc8eae238d52aa7b8c0782fb9003
refs/heads/master
2021-01-24T16:52:10.703835
2018-02-27T14:07:25
2018-02-27T14:07:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,256
cpp
// Gathering cell // UVa ID: 11487 // Verdict: Accepted // Submission Date: 2018-02-24 // UVa Run Time: 0.000s // // 版权所有(C)2018,邱秋。metaphysis # yeah dot net #include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <cstring> #include <iomanip> #include <iostream> #include <limits> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; const int MAXV = 12, INF = 0x3f3f3f3f, MOD = 20437; struct cell { int i, j; cell (int i = 0, int j = 0): i(i), j(j) {} }; int n, dist[MAXV][MAXV], path[MAXV][MAXV]; int offset[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; cell cells[32]; char grid[MAXV][MAXV]; int main(int argc, char *argv[]) { cin.tie(0), cout.tie(0), ios::sync_with_stdio(false); int cases = 0; while (cin >> n, n > 0) { int cnt = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { cin >> grid[i][j]; if (isalpha(grid[i][j])) { cells[grid[i][j] - 'A'] = cell(i, j); cnt = max(cnt, grid[i][j] - 'A' + 1); } } bool impossible = false; int sumOfDist = 0, cntOfPath = 1; for (int i = 1; i < cnt; i++) { memset(dist, 0x3f, sizeof(dist)); memset(path, 0, sizeof(path)); cell c = cells[i - 1]; queue<cell> q; q.push(c); dist[c.i][c.j] = 0; path[c.i][c.j] = 1; // BFS. while (!q.empty()) { c = q.front(); q.pop(); for (int k = 0; k < 4; k++) { int nexti = c.i + offset[k][0], nextj = c.j + offset[k][1]; if (nexti >= 0 && nexti < n && nextj >= 0 && nextj < n) { if (dist[nexti][nextj] > dist[c.i][c.j] + 1) { dist[nexti][nextj] = dist[c.i][c.j] + 1; path[nexti][nextj] = path[c.i][c.j]; if (grid[nexti][nextj] == '.') q.push(cell(nexti, nextj)); } else if (dist[nexti][nextj] == (dist[c.i][c.j] + 1)) { path[nexti][nextj] += path[c.i][c.j]; path[nexti][nextj] %= MOD; } } } } // Food picked. grid[cells[i - 1].i][cells[i - 1].j] = '.'; if (dist[cells[i].i][cells[i].j] == INF) { impossible = true; break; } sumOfDist += dist[cells[i].i][cells[i].j]; cntOfPath *= path[cells[i].i][cells[i].j]; cntOfPath %= MOD; } cout << "Case " << ++cases << ": "; if (impossible) cout << "Impossible\n"; else cout << sumOfDist << ' ' << cntOfPath << '\n'; } return 0; }
[ "metaphysis@yeah.net" ]
metaphysis@yeah.net
52ba98a6a97fc71a3da1dd8d1215d6c7ced24091
f234b70d2b883065a34d7948dc3c5a2b0daed019
/3D/Model.cpp
a55f5e0ece7e6c9f59126ffc131afd003ee74e72
[]
no_license
ByoubuSiki/Beginner
8b607c0fc82db6236dfd9c54213225cbb1f52eee
dfd62eca8d815e0a582dcc1dba8ca5ea691ce989
refs/heads/master
2023-03-05T05:31:52.439088
2021-02-20T15:21:59
2021-02-20T15:21:59
268,213,451
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,967
cpp
#include"Model.h" namespace Beginner { std::list<Model> modelList;//作製したModelクラスの実態を記録 //モデル作成 Model* Model::CreateModel(const char* filename) { Assimp::Importer importer; //Assimpで読み取り const auto scene = importer.ReadFile(filename, MODEL_LOAD_MEDIUM); if (!scene) { DebugLogOnConsole("モデル読み取り失敗\n"); return nullptr; } //実体を配列に追加 modelList.push_back({}); auto itr = --modelList.end(); itr->LoadModelData(scene->mRootNode, scene); if (!itr->SetUpObject() || !itr->SetUpModel()) { DebugLogOnConsole("ModelクラスのSetUpが失敗\n"); modelList.erase(itr); return nullptr; } outputObject.push_back(&(*itr)); return &(*itr); } // 描画時に呼び出し void Model::DrawCall() { ApplyTransform();//座標変換 //パイプラインとルートシグネチャを設定 commandList->SetPipelineState(pipeline.GetPipelineState().Get()); commandList->SetGraphicsRootSignature(pipeline.GetRootSignature().Get()); //三角形で描画 頂点情報と頂点インデックスを設定 commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); commandList->IASetVertexBuffers(0, 1, &vertexView); commandList->IASetIndexBuffer(&indexView); //CBV・SRVを設定 const auto handle = cbvHeap.GetHeap()->GetGPUDescriptorHandleForHeapStart(); commandList->SetDescriptorHeaps(1, cbvHeap.GetHeap().GetAddressOf()); commandList->SetGraphicsRootDescriptorTable(0, handle); //描画 commandList->DrawIndexedInstanced((UINT)vertexIndex.size(), 1, 0, 0, 0); } //再帰でAssimpのNodeを読み取り void Model::LoadModelData(aiNode* node, const aiScene* scene) { for (unsigned i = 0; i < node->mNumMeshes; i++)//Node内のMeshを読み取り { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; LoadModelMesh(mesh);//Meshの情報を読み取り } for (unsigned i = 0; i < node->mNumChildren; i++) //子Nodeを探索 { LoadModelData(node->mChildren[i], scene); } } //AssimpのMesh情報を読み取り void Model::LoadModelMesh(aiMesh* mesh) { const auto offset = vertex.size();//頂点インデックスの位置を調整 for (unsigned i = 0; i < mesh->mNumVertices; i++)//頂点情報を一つずつ読み取り { LoadModelVertex(mesh, i);//頂点情報を読み取り } for (unsigned i = 0; i < mesh->mNumFaces; i++)//Mesh内の面を調べる { for (unsigned j = 0; j < mesh->mFaces[i].mNumIndices; j++)//面内の頂点番号を調べる { vertexIndex.push_back(mesh->mFaces[i].mIndices[j] + offset);//頂点番号を追加 } } } //頂点の情報を読み取り void Model::LoadModelVertex(aiMesh* mesh, const unsigned vertexIndex) { //配列に頂点情報の入れ物を追加 vertex.push_back(Vertex()); auto itr = --vertex.end(); if (mesh->HasPositions())//座標情報 { itr->position = { mesh->mVertices[vertexIndex].x,mesh->mVertices[vertexIndex].y, mesh->mVertices[vertexIndex].z }; } if (mesh->HasNormals())//法線情報 { itr->normal = { mesh->mNormals[vertexIndex].x,mesh->mNormals[vertexIndex].y,mesh->mNormals[vertexIndex].z }; } /*for (unsigned i = 0; i < mesh->HasTextureCoords(i); i++) { itr->texcoord.push_back({ mesh->mTextureCoords[i][vertexIndex].x, mesh->mTextureCoords[i][vertexIndex].y, mesh->mTextureCoords[i][vertexIndex].z }); } for (unsigned i = 0; mesh->HasVertexColors(i); i++)//頂点カラー { itr->color.push_back( { mesh->mColors[i]->r, mesh->mColors[i]->g, mesh->mColors[i]->b, mesh->mColors[i]->a } ); } if (mesh->HasTangentsAndBitangents())//接戦 { itr->tangent = {//texture x axis mesh->mTangents[vertexIndex].x,mesh->mTangents[vertexIndex].y,mesh->mTangents[vertexIndex].z }; itr->bitangent = {//texture y axis mesh->mBitangents[vertexIndex].x,mesh->mBitangents[vertexIndex].y,mesh->mBitangents[vertexIndex].z }; } */ } //ModelクラスのSetUp動作 bool Model::SetUpModel() { //Model用のバッファ作製 && CBV用ディスクリプタヒープ作製 && グラフィックパイプラインを作製 if (CreateModelBuffer() && cbvHeap.CreateCBV_SRV_UAV(1) && pipeline.CreateGraphicsPipeline(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, MODEL_TYPE, vertexShader->GetShaderBlob(), pixelShader->GetShaderBlob())) { auto heap = cbvHeap.GetHeap(); CreateConstantView(constBuffer, heap);//CBV用のViewを作製 return true; } return false; } //Modelクラス用のバッファを作製・マップ処理 bool Model::CreateModelBuffer() { //頂点情報・頂点インデックス用のバッファを作製 if (!CreateBuffer(vertexBuffer, sizeof(vertex[0]) * vertex.size()) || !CreateBuffer(indexBuffer, sizeof(vertexIndex[0]) * vertexIndex.size())) { return false; } //頂点情報・頂点インデックスのバッファをマップ if (BufferMap(vertexBuffer, vertex.begin(), vertex.end(), true) == nullptr || BufferMap(indexBuffer, vertexIndex.begin(), vertexIndex.end(), true) == nullptr) { return false; } //頂点情報・頂点インデックス用のビューを設定 SetVertexView(vertex.size(), sizeof(vertex[0]), vertexBuffer->GetGPUVirtualAddress()); SetIndexView(vertexIndex.size() * sizeof(vertexIndex[0]), indexBuffer->GetGPUVirtualAddress()); return true; } //頂点ビューの設定 void Model::SetVertexView(const size_t byte, const UINT typeSize, const D3D12_GPU_VIRTUAL_ADDRESS gpuAddress) { vertexView.BufferLocation = gpuAddress; vertexView.SizeInBytes = (UINT)byte * typeSize; vertexView.StrideInBytes = typeSize; } //インデックスビューの設定 void Model::SetIndexView(const size_t indexSize, const D3D12_GPU_VIRTUAL_ADDRESS gpuAddress) { indexView.BufferLocation = gpuAddress; indexView.Format = DXGI_FORMAT_R32_UINT; indexView.SizeInBytes = (UINT)indexSize; } }
[ "kzk.peanut@outlook.jp" ]
kzk.peanut@outlook.jp
05ca2aef1d356ab1ad2e46c824608173cef39018
4bce2f32e15537f87ae0c3b4d37339bd433b2051
/104IO/include/color_code.h
ecc71c97faeec6bf4fc56cd5b4e037d5b55bc8c8
[ "BSD-2-Clause" ]
permissive
Coderik/104P
b3e4cb1d3108a359ae9a51f2d2822f38e6d5d8ef
37435ff3709fbce9fcc87b59acc46212f484daad
refs/heads/master
2020-12-13T22:34:56.915092
2016-07-12T18:35:39
2016-07-12T18:35:39
15,802,145
0
0
null
null
null
null
UTF-8
C++
false
false
976
h
/** * Copyright (C) 2016, Vadim Fedorov <coderiks@gmail.com> * * This program is free software: you can use, modify and/or * redistribute it under the terms of the simplified BSD * License. You should have received a copy of this license along * this program. If not, see * <http://www.opensource.org/licenses/bsd-license.html>. */ /// Created on: Feb 8, 2013 #ifndef COLOR_CODE_H_ #define COLOR_CODE_H_ #include <vector> #include <math.h> #include "i_optical_flow_code.h" using namespace std; /** * Color encoding of flow vectors * adapted from the color circle idea described at * http://members.shaw.ca/quadibloc/other/colint.htm */ class ColorCode : public IOptivalFlowCode { public: ColorCode(); virtual ~ColorCode(); virtual void get_color(float fx, float fy, char *color); private: int _colors_count; vector<vector<int> > _color_wheel; void set_color(int r, int g, int b, int index); void make_color_wheel(); }; #endif /* COLOR_CODE_H_ */
[ "coderiks@gmail.com" ]
coderiks@gmail.com
e4b8fd961a13eebbc1befa2b5025a675cd232ddb
62869fe5152bbe07fbe9f0b61166be32e4f5016c
/3rdparty/CGAL/include/CGAL/Partition_2/Partition_vertex_map.h
06fa04ae0d111f48acb48415b08d9f5fe4ec395a
[ "LicenseRef-scancode-warranty-disclaimer", "LGPL-3.0-or-later", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-commercial-license", "MIT" ]
permissive
daergoth/SubdivisionSandbox
aef65eab0e1ab3dfecb2f9254c36d26c71ecd4fd
d67386980eb978a552e5a98ba1c4b25cf5a9a328
refs/heads/master
2020-03-30T09:19:07.121847
2019-01-08T16:42:53
2019-01-08T16:42:53
151,070,972
0
0
MIT
2018-12-03T11:10:03
2018-10-01T10:26:28
C++
UTF-8
C++
false
false
15,599
h
// Copyright (c) 2000 Max-Planck-Institute Saarbruecken (Germany). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // You can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Susan Hert <hert@mpi-sb.mpg.de> #ifndef CGAL_PARTITION_VERTEX_MAP_H #define CGAL_PARTITION_VERTEX_MAP_H #include <CGAL/license/Partition_2.h> #include <map> #include <iostream> #include <CGAL/circulator.h> #include <CGAL/assertions.h> #include <sstream> namespace CGAL { const int PARTITION_VMAP_UNSHARED_EDGE = -1; template<class Traits_> class Vertex_info { public: typedef Traits_ Traits; typedef typename Traits::Polygon_2 Polygon_2 ; typedef typename Traits::Polygon_2::Vertex_const_iterator Vertex_const_iterator; typedef typename Traits::Less_xy_2 Less_xy_2; Vertex_info ( Vertex_const_iterator const& vx_it, Polygon_2 const* poly_ptr ) : m_vx_it(vx_it) ,m_poly_ptr(poly_ptr) {} Vertex_const_iterator vertex_it() const { return m_vx_it ; } Polygon_2 const* poly_ptr () const { return m_poly_ptr ; } friend bool operator == ( Vertex_info const& a, Vertex_info const& b ) { return a.poly_ptr() == b.poly_ptr() && a.vertex_it() == b.vertex_it() ; } friend bool operator != ( Vertex_info const& a, Vertex_info const& b ) { return !(a==b); } friend bool operator < ( Vertex_info const& a, Vertex_info const& b ) { return Traits().less_xy_2_object()(*a.vertex_it(), *b.vertex_it()); } private: Vertex_const_iterator m_vx_it ; Polygon_2 const* m_poly_ptr ; } ; template <class Traits_> class Edge_info { public: typedef Traits_ Traits; typedef CGAL::Vertex_info<Traits> Vertex_info; public: Edge_info(Vertex_info e_ref, int p_num1) : _endpoint_ref(e_ref), _poly_num1(p_num1), _poly_num2(PARTITION_VMAP_UNSHARED_EDGE) { } void set_poly_num2(int p_num) { _poly_num2 = p_num; } Vertex_info endpoint() const { return _endpoint_ref; } int poly_num1() const { return _poly_num1; } int poly_num2() const { return _poly_num2; } private: Vertex_info _endpoint_ref; int _poly_num1; int _poly_num2; }; template <class Traits> class CW_indirect_edge_info_compare { public: typedef CGAL::Vertex_info<Traits> Vertex_info ; typedef CGAL::Edge_info<Traits> Edge_info; typedef typename Vertex_info::Vertex_const_iterator Vertex_const_iterator ; typedef typename Traits::Left_turn_2 Left_turn_2; typedef typename Traits::Less_xy_2 Less_xy_2; typedef typename Traits::Point_2 Point_2; CW_indirect_edge_info_compare (Vertex_const_iterator v_info) : vertex_it(v_info), left_turn(Traits().left_turn_2_object()), less_xy(Traits().less_xy_2_object()) {} bool operator()(Edge_info e1, Edge_info e2) { bool e1_less = less_xy((*e1.endpoint().vertex_it()), *vertex_it); bool e2_less = less_xy((*e2.endpoint().vertex_it()), *vertex_it); bool e1_to_e2_left_turn = left_turn((*e1.endpoint().vertex_it()), *vertex_it, (*e2.endpoint().vertex_it())); // if both edges are on the same side of the vertical line through // _vertex then e1 comes before e2 (in CW order from the vertical line) // if one makes a left turn going from e1 to e2 if (e1_less == e2_less) return e1_to_e2_left_turn; else // e1 comes first if it is to the right of the vertical line return !e1_less; } private: Vertex_const_iterator vertex_it; Left_turn_2 left_turn; Less_xy_2 less_xy; }; namespace Partition_2 { template <class Traits_> class Edge_list { public: typedef Traits_ Traits; typedef Edge_list<Traits> Self; typedef typename Traits::Point_2 Point_2; typedef typename Traits::Orientation_2 Orientation_pred; typedef typename Traits::Polygon_2 Polygon_2 ; typedef typename Traits::Polygon_2::Vertex_const_iterator Vertex_const_iterator; typedef CGAL::Vertex_info<Traits> Vertex_info; typedef CGAL::Edge_info<Traits> Edge_info; typedef std::list<Edge_info> List ; typedef typename List::iterator Self_iterator; typedef typename List::const_iterator Self_const_iterator; typedef typename List::size_type size_type ; typedef Circulator_from_iterator<Self_const_iterator> Self_const_circulator; Self_const_iterator begin() const { return m_list.begin() ; } Self_iterator begin() { return m_list.begin() ; } Self_const_iterator end () const { return m_list.end () ; } Self_iterator end () { return m_list.end () ; } size_type size() const { return m_list.size() ; } Edge_info const& front() const { return m_list.front() ; } Edge_info & front() { return m_list.front() ; } Edge_info const& back() const { return m_list.back() ; } Edge_info & back() { return m_list.back() ; } template<class Compare> void sort ( Compare c ) { m_list.sort(c); } void insert_next(Vertex_info endpoint_ref, int num) { Self_iterator e_it; for (e_it = m_list.begin(); e_it != m_list.end() && e_it->endpoint() != endpoint_ref ; e_it++) { } if (e_it != m_list.end()) { (*e_it).set_poly_num2(num); } else { m_list.push_back(Edge_info(endpoint_ref, num)); } } void insert_prev(Vertex_info endpoint_ref, int num) { Self_iterator e_it; for (e_it = m_list.begin(); e_it != m_list.end() && e_it->endpoint() != endpoint_ref ; e_it++) { } if (e_it != m_list.end()) { (*e_it).set_poly_num2(num); } else { m_list.push_front(Edge_info(endpoint_ref, num)); } } // PRE: polygons must be simple bool edges_overlap(Vertex_const_iterator vertex_it) { #ifdef CGAL_PARTITION_CHECK_DEBUG std::cout << "before sort: edges for " << *vertex_it << std::endl; std::cout << *this << std::endl; #endif int num_unshared = 0; // Don't want to sort the edges for vertices of degree 2 because they // are already in CCW order (since the partition polygons were in CCW // order), and this is what you need when you construct the union // polygon. if (m_list.size() > 2) { m_list.sort(CW_indirect_edge_info_compare<Traits>(vertex_it)); } #ifdef CGAL_PARTITION_CHECK_DEBUG std::cout << "after sort: edges for " << *vertex_it << std::endl; std::cout << *this << std::endl; #endif Self_const_iterator prev_e_it = m_list.begin(); Self_const_iterator e_it; for (e_it = m_list.begin(); e_it != m_list.end(); e_it++) { if ((*e_it).poly_num1() == PARTITION_VMAP_UNSHARED_EDGE) num_unshared++; if ((*e_it).poly_num2() == PARTITION_VMAP_UNSHARED_EDGE) num_unshared++; if ((*prev_e_it).poly_num1() != (*e_it).poly_num1() && (*prev_e_it).poly_num1() != (*e_it).poly_num2() && (*prev_e_it).poly_num2() != (*e_it).poly_num1() && (*prev_e_it).poly_num2() != (*e_it).poly_num2()) { return true; } prev_e_it = e_it; } if ((*prev_e_it).poly_num1() != (*m_list.begin()).poly_num1() && (*prev_e_it).poly_num1() != (*m_list.begin()).poly_num2() && (*prev_e_it).poly_num2() != (*m_list.begin()).poly_num1() && (*prev_e_it).poly_num2() != (*m_list.begin()).poly_num2()) { return true; } return (num_unshared > 2); } // NOTE: the edges here are sorted in CW order so the next CCW edge // comes BEFORE the edge with endpoint v_info in the sorted list Edge_info next_ccw_edge_info(Vertex_info v_info) const { Self_const_circulator first_e(m_list.begin(), m_list.end(), m_list.begin()); Self_const_circulator e_circ = first_e; do { if ((*e_circ).endpoint() == v_info) { e_circ--; // go to the previous endpoint return *e_circ; } } while (++e_circ != first_e); return *first_e; // shouldn't get here unless v_info is not in list } private : List m_list ; }; template <class Traits> std::ostream& operator<<(std::ostream& os, const Edge_list<Traits>& edges) { typename Edge_list<Traits>::const_iterator e_it; for (e_it = edges.begin(); e_it != edges.end(); e_it++) { os << "edge with endpoint (" << (*(*e_it).endpoint().vertex_it()) << ") from poly #" << (*e_it).poly_num1() << " and poly #" << (*e_it).poly_num2() << std::endl; } return os; } } // namesapce Partition_2 template <class Traits_> class Partition_vertex_map { public: typedef Traits_ Traits; typedef CGAL::Vertex_info<Traits> Vertex_info; typedef CGAL::Edge_info<Traits> Edge_info; typedef Partition_2::Edge_list<Traits> Edge_list; typedef Partition_vertex_map<Traits> Self; typedef std::map<Vertex_info, Edge_list> Map ; typedef typename Map::const_iterator Self_const_iterator; typedef typename Map::iterator Self_iterator; typedef typename Traits::Point_2 Point_2; typedef typename Traits::Polygon_2 Polygon_2 ; typedef typename Polygon_2::Vertex_const_iterator Vertex_const_iterator; Partition_vertex_map() {} template <class InputIterator> Partition_vertex_map(InputIterator first_poly, InputIterator last_poly) { _build(first_poly, last_poly); } Self_const_iterator begin() const { return m_map.begin() ; } Self_iterator begin() { return m_map.begin() ; } Self_const_iterator end () const { return m_map.end () ; } Self_iterator end () { return m_map.end () ; } bool polygons_overlap() { Self_iterator v_info; for (v_info = m_map.begin(); v_info != m_map.end(); v_info++) { if ((*v_info).second.edges_overlap((*v_info).first.vertex_it())) return true; } return false; } template <class OutputIterator> OutputIterator union_vertices(OutputIterator result) { if (m_map.empty()) return result; Self_iterator m_it = m_map.begin(); // find a vertex with degree 2 (there must be at least one) while (m_it != m_map.end() && (*m_it).second.size() != 2) m_it++; CGAL_assertion (m_it != m_map.end()); // insert this vertex and the two around it Vertex_info first_v_info = (*m_it).second.front().endpoint(); Vertex_info prev_v_info = first_v_info ; #ifdef CGAL_PARTITION_CHECK_DEBUG std::cout << "union_vertices: inserting " << (*prev_v_info.vertex_it()) << std::endl; #endif *result = *prev_v_info.vertex_it(); result++; #ifdef CGAL_PARTITION_CHECK_DEBUG std::cout << "union_vertices: inserting "<< *(*m_it).first.vertex_it() << std::endl; #endif *result = *(*m_it).first.vertex_it(); result++; Vertex_info next_v_info = (*m_it).second.back().endpoint(); #ifdef CGAL_PARTITION_CHECK_DEBUG std::cout << "union_vertices: inserting " << *next_v_info.vertex_it() << std::endl; #endif *result = *next_v_info.vertex_it(); result++; // find the map iterator corresponding to the next vertex prev_v_info = (*m_it).first; Vertex_info v_info = next_v_info; m_it = m_map.find(v_info); while (v_info != first_v_info && m_it != m_map.end()) { #ifdef CGAL_PARTITION_CHECK_DEBUG std::cout << "union_vertices: prev_v_info " << (*prev_v_info.vertex_it()) << " v_info " << (*v_info.vertex_it()) << " next_v_info " << (*next_v_info.vertex_it()) << std::endl; #endif // Don't want to sort the edges for vertices of degree 2 because they // are already in CCW order (since the partition polygons were in CCW // order), and this is what you need to begin the construction // of the union polygon. if ((*m_it).second.size() > 2) { (*m_it).second.sort( CW_indirect_edge_info_compare<Traits>((*m_it).first.vertex_it())); } // find the previous vertex in this vertex's list next_v_info=(*m_it).second.next_ccw_edge_info(prev_v_info).endpoint(); if (next_v_info != first_v_info) { #ifdef CGAL_PARTITION_CHECK_DEBUG std::cout << "union_vertices: inserting " << *next_v_info.vertex_it() << std::endl; #endif *result = *next_v_info.vertex_it(); result++; } prev_v_info = v_info; v_info = next_v_info; m_it = m_map.find(v_info); CGAL_assertion (m_it == m_map.end() || (*m_it).first == v_info); } #ifdef CGAL_PARTITION_CHECK_DEBUG if (v_info == first_v_info) std::cout << "union_vertices: stopped because first was reached " << std::endl; else std::cout << "union_vertices: stopped because end was reached " << std::endl; #endif return result; } private : template <class InputIterator> void _build(InputIterator poly_first, InputIterator poly_last) { typedef std::pair<Self_iterator, bool> Location_pair; typedef std::pair<Vertex_info, Edge_list> P_Vertex; Location_pair v_loc_pair; Location_pair begin_v_loc_pair; Location_pair prev_v_loc_pair; Vertex_const_iterator vtx_begin; Vertex_const_iterator vtx_end; Vertex_const_iterator v_it; int poly_num = 0; for (; poly_first != poly_last; poly_first++, poly_num++) { Polygon_2 const* poly_ptr = &(*poly_first); vtx_begin = (*poly_first).vertices_begin(); vtx_end = (*poly_first).vertices_end(); begin_v_loc_pair = m_map.insert(P_Vertex( Vertex_info(vtx_begin,poly_ptr), Edge_list())); prev_v_loc_pair = begin_v_loc_pair; v_it = vtx_begin; for (v_it++; v_it != vtx_end; v_it++) { v_loc_pair = m_map.insert(P_Vertex( Vertex_info(v_it,poly_ptr), Edge_list())); insert_next_edge(prev_v_loc_pair.first, v_loc_pair.first, poly_num); insert_prev_edge(v_loc_pair.first, prev_v_loc_pair.first, poly_num); prev_v_loc_pair = v_loc_pair; } insert_next_edge(prev_v_loc_pair.first, begin_v_loc_pair.first, poly_num); insert_prev_edge(begin_v_loc_pair.first, prev_v_loc_pair.first, poly_num); } } void insert_next_edge(Self_iterator& v1_ref, Self_iterator& v2_ref, int num) { (*v1_ref).second.insert_next((*v2_ref).first, num); } void insert_prev_edge(Self_iterator& v1_ref, Self_iterator& v2_ref, int num) { (*v1_ref).second.insert_prev((*v2_ref).first, num); } private : Map m_map ; }; } #endif // CGAL_PARTITION_VERTEX_MAP_H
[ "bodonyiandi94@gmail.com" ]
bodonyiandi94@gmail.com
0803bc0572fa432f2fbf9b3e26a1e2ce969739d2
de7e771699065ec21a340ada1060a3cf0bec3091
/analysis/icu/src/test/org/apache/lucene/analysis/icu/segmentation/TestWithCJKBigramFilter.h
e9874cb4211c28b5a7092db865a262beb317d099
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
4,163
h
#pragma once #include "../../../../../../../../../../core/src/java/org/apache/lucene/analysis/Analyzer.h" #include "../../../../../../../../../../test-framework/src/java/org/apache/lucene/analysis/BaseTokenStreamTestCase.h" #include "stringhelper.h" #include <memory> #include <stdexcept> #include <string> #include <deque> // C++ NOTE: Forward class declarations: #include "core/src/java/org/apache/lucene/analysis/Analyzer.h" #include "core/src/java/org/apache/lucene/analysis/TokenStreamComponents.h" /* * Licensed to the Syed Mamun Raihan (sraihan.com) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * sraihan.com licenses this file to You under GPLv3 License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * https://www.gnu.org/licenses/gpl-3.0.en.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace org::apache::lucene::analysis::icu::segmentation { using Analyzer = org::apache::lucene::analysis::Analyzer; using BaseTokenStreamTestCase = org::apache::lucene::analysis::BaseTokenStreamTestCase; /** * Tests ICUTokenizer's ability to work with CJKBigramFilter. * Most tests adopted from TestCJKTokenizer */ class TestWithCJKBigramFilter : public BaseTokenStreamTestCase { GET_CLASS_NAME(TestWithCJKBigramFilter) public: std::shared_ptr<Analyzer> analyzer, analyzer2; void setUp() override; private: class AnalyzerAnonymousInnerClass : public Analyzer { GET_CLASS_NAME(AnalyzerAnonymousInnerClass) private: std::shared_ptr<TestWithCJKBigramFilter> outerInstance; public: AnalyzerAnonymousInnerClass( std::shared_ptr<TestWithCJKBigramFilter> outerInstance); protected: std::shared_ptr<Analyzer::TokenStreamComponents> createComponents(const std::wstring &fieldName) override; protected: std::shared_ptr<AnalyzerAnonymousInnerClass> shared_from_this() { return std::static_pointer_cast<AnalyzerAnonymousInnerClass>( org.apache.lucene.analysis.Analyzer::shared_from_this()); } }; private: class AnalyzerAnonymousInnerClass2 : public Analyzer { GET_CLASS_NAME(AnalyzerAnonymousInnerClass2) private: std::shared_ptr<TestWithCJKBigramFilter> outerInstance; public: AnalyzerAnonymousInnerClass2( std::shared_ptr<TestWithCJKBigramFilter> outerInstance); protected: std::shared_ptr<Analyzer::TokenStreamComponents> createComponents(const std::wstring &fieldName) override; protected: std::shared_ptr<AnalyzerAnonymousInnerClass2> shared_from_this() { return std::static_pointer_cast<AnalyzerAnonymousInnerClass2>( org.apache.lucene.analysis.Analyzer::shared_from_this()); } }; public: void tearDown() override; virtual void testJa1() ; virtual void testJa2() ; virtual void testC() ; /** * LUCENE-2207: wrong offset calculated by end() */ virtual void testFinalOffset() ; virtual void testMix() ; virtual void testMix2() ; /** * Non-english text (outside of CJK) is treated normally, according to unicode * rules */ virtual void testNonIdeographic() ; /** * Same as the above, except with a nonspacing mark to show correctness. */ virtual void testNonIdeographicNonLetter() ; virtual void testSurrogates() ; virtual void testReusableTokenStream() ; virtual void testSingleChar() ; virtual void testTokenStream() ; protected: std::shared_ptr<TestWithCJKBigramFilter> shared_from_this() { return std::static_pointer_cast<TestWithCJKBigramFilter>( org.apache.lucene.analysis.BaseTokenStreamTestCase::shared_from_this()); } }; } // #include "core/src/java/org/apache/lucene/analysis/icu/segmentation/
[ "smamunr@fedora.localdomain" ]
smamunr@fedora.localdomain
61fbc9d75fc66d23d2dc6f6c805bbaa421762a24
fec81bfe0453c5646e00c5d69874a71c579a103d
/blazetest/src/mathtest/adaptors/diagonalmatrix/RowTest.cpp
a88d4d35fd42281ade57815311108ed53290ef4c
[ "BSD-3-Clause" ]
permissive
parsa/blaze
801b0f619a53f8c07454b80d0a665ac0a3cf561d
6ce2d5d8951e9b367aad87cc55ac835b054b5964
refs/heads/master
2022-09-19T15:46:44.108364
2022-07-30T04:47:03
2022-07-30T04:47:03
105,918,096
52
7
null
null
null
null
UTF-8
C++
false
false
4,410
cpp
//================================================================================================= /*! // \file src/mathtest/adaptors/diagonalmatrix/RowTest.cpp // \brief Source file for the DiagonalMatrix row test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blazetest/mathtest/adaptors/diagonalmatrix/RowTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif namespace blazetest { namespace mathtest { namespace adaptors { namespace diagonalmatrix { //================================================================================================= // // CONSTRUCTORS // //================================================================================================= //************************************************************************************************* /*!\brief Constructor for the DiagonalMatrix row test. // // \exception std::runtime_error Operation error detected. */ RowTest::RowTest() { testAssignment<DDT>(); testAddAssign<DDT>(); testSubAssign<DDT>(); testMultAssign<DDT>(); testAssignment<DODT>(); testAddAssign<DODT>(); testSubAssign<DODT>(); testMultAssign<DODT>(); testAssignment<SDT>(); testAddAssign<SDT>(); testSubAssign<SDT>(); testMultAssign<SDT>(); testAssignment<SODT>(); testAddAssign<SODT>(); testSubAssign<SODT>(); testMultAssign<SODT>(); } //************************************************************************************************* } // namespace diagonalmatrix } // namespace adaptors } // namespace mathtest } // namespace blazetest //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running DiagonalMatrix row test..." << std::endl; try { RUN_DIAGONALMATRIX_ROW_TEST; } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during DiagonalMatrix row test:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
1fc6be4365d4812d5e60f66300d6ceb5918cbeb8
7137be01fc7f00ddd5b1a408d5de81f6c1db9fa2
/wifi_state.ino
fc5ead18dbaf63ba80bb91831047ae37c2a18eb8
[]
no_license
chazcheadle/WakameGPS
5577f5981701a6cc737b3a8bc06520d697734a24
8e5cc354a6518997390bcc070cbcd6441b7cc116
refs/heads/master
2022-05-15T12:52:19.883059
2020-02-14T07:33:22
2020-02-14T07:33:22
240,452,311
0
0
null
null
null
null
UTF-8
C++
false
false
6,051
ino
/** * WiFi state machine and display functions */ static void displayWifi() { unsigned long current_millis = millis(); if (currentScreen != lastScreen) { // if (current_millis - last_millis >= 1000) { // Display title bar. tft.fillRect(0, 1, 112, 10, ST7735_WHITE); tft.setTextColor(ST7735_BLACK, ST7735_WHITE); tft.setCursor(2, 2); tft.print(F("WiFi Info")); tft.setTextColor(ST7735_WHITE, ST7735_BLACK); lastScreen = currentScreen; last_millis = 0; } if (configPage[WIFI_INFO_SCREEN] == true) { // tft.fillRect(0, 11, 127, 116, ST7735_BLACK); wifiInfoOptions(); } else { if (current_millis - last_millis >= 1000) { tft.setCursor(2, 12); tft.print(F("STATUS: ")); if ( WiFi.status() != WL_CONNECTED ) { tft.print(F("Not connected")); tft.setCursor(2, 21); tft.print(F("Press CMD to connect")); } else { tft.print(F("Connected")); tft.setCursor(2, 21); tft.print(F("SSID: ")); tft.print(ssid); tft.setCursor(2, 30); tft.print(F("IP: ")); tft.print(hostIP); tft.setCursor(2, 39); tft.print(F("DNS: ")); tft.print(hostString); tft.print(F(".local")); } last_millis = current_millis; } } } // displayWifi void wifiInfoOptions() { if (lastOption != currentOption) { // tft.fillRect(0, 11, 127, 116, ST7735_BLACK); } // Set option marker currentOption = currentOption % NUM_WIFI_INFO_SCREEN_OPTIONS; for (int i= 0; i < NUM_WIFI_INFO_SCREEN_OPTIONS; i++) { tft.setCursor(1, 12 + 9 * i); if (currentOption == i) { tft.print(F("*")); } else { tft.print(F(" ")); } } if (menuCMD == true) { switch (currentOption) { case 0: // Connect (last saved) tft.setCursor(1, 120); tft.print("Starting WiFi..."); digitalWrite(LED, LOW); delay(2000); // Router_SSID = ESP_wifiManager.WiFi_SSID(); // Router_Pass = ESP_wifiManager.WiFi_Pass(); // WiFi.mode(WIFI_STA); // WiFi.begin(Router_SSID, Router_Pass); // delay(5000); // if (WiFi.waitForConnectResult() != WL_CONNECTED) { // // DEBUG_PORT.println("Connection Failed! Rebooting..."); // tft.setCursor(1, 112); // tft.print("Cannot connect to WiFi"); // tft.setCursor(1, 120); // tft.print("Start WiFi Manager"); // tft.setCursor(114, 120); // tft.print(" "); // // ESP.restart(); // } // else { // tft.fillRect(0, 120, 127, 7, ST7735_BLACK); // tft.setTextColor(ST7735_BLACK, ST7735_WHITE); // tft.setCursor(114, 2); // tft.print("W"); // tft.setTextColor(ST7735_WHITE, ST7735_BLACK); // } // // Set mDNS hostname // sprintf(hostString, "ESP-%06X", ESP.getChipId()); // if (!MDNS.begin(hostString)) { // tft.setCursor(1, 119); // tft.print(F("mDNS failed")); // } // sprintf(hostIP, "%d.%d.%d.%d", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3] ); // digitalWrite(LED, LOW); // delay(20); // digitalWrite(LED, HIGH); // delay(20); // digitalWrite(LED, LOW); // delay(20); // digitalWrite(LED, HIGH); // delay(20); // ArduinoOTA.onStart([]() { // // DEBUG_PORT.println("Start"); // digitalWrite(LED, LOW); // tft.setTextColor(ST7735_WHITE, ST7735_BLACK); // tft.setCursor(2, 120); // tft.print(F("Updating firmware: ")); // }); // ArduinoOTA.onEnd([]() { // // DEBUG_PORT.println("\nEnd"); // tft.fillRect(0, 120, 127, 7, ST7735_BLACK); // tft.setTextColor(ST7735_WHITE, ST7735_BLACK); // tft.setCursor(2, 120); // tft.print(F("Firmware updated.")); // digitalWrite(LED, HIGH); // }); // ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { // // DEBUG_PORT.printf("Progress: %u%%\r", (progress / (total / 100))); // tft.setCursor(104, 120); // tft.print(progress / (total / 100)); // tft.print(F("% ")); // }); // ArduinoOTA.onError([](ota_error_t error) { // // DEBUG_PORT.printf("Error[%u]: ", error); // if (error == OTA_AUTH_ERROR) DEBUG_PORT.println("Auth Failed"); // else if (error == OTA_BEGIN_ERROR) DEBUG_PORT.println("Begin Failed"); // else if (error == OTA_CONNECT_ERROR) DEBUG_PORT.println("Connect Failed"); // else if (error == OTA_RECEIVE_ERROR) DEBUG_PORT.println("Receive Failed"); // else if (error == OTA_END_ERROR) DEBUG_PORT.println("End Failed"); // }); // ArduinoOTA.begin(); configPage[WIFI_INFO_SCREEN] = false; currentOption = 0; break; case 1: // Config Portal // ESP_wifiManager.startConfigPortal(); break; case 2: // Turn WiFi On/Off // Put modem to sleep // WiFi.mode( WIFI_OFF ); // WiFi.forceSleepBegin(); // delay(1); // tft.setTextColor(ST7735_BLACK, ST7735_WHITE); // tft.setCursor(114, 2); // tft.print(" "); // tft.setTextColor(ST7735_WHITE, ST7735_BLACK); configPage[WIFI_INFO_SCREEN] = false; currentOption = 0; break; case 3: // Exit tft.fillRect(0, 11, 128, 107, ST7735_BLACK); delay(1); configPage[WIFI_INFO_SCREEN] = false; currentOption = 0; break; } menuCMD = false; } lastOption = currentOption; if (configPage[WIFI_INFO_SCREEN]) { tft.setTextColor(ST7735_WHITE, ST7735_BLACK); tft.setCursor(8, 12); tft.print(F("Connect to Wifi")); tft.setCursor(8, 21); tft.print(F("WiFi manager")); tft.setCursor(8, 30); tft.print(F("Turn WiFi Off")); tft.setCursor(8, 39); tft.print(F("Exit")); } }
[ "charles.cheadle@nbcuni.com" ]
charles.cheadle@nbcuni.com
ed88f9d72a88771443180d4e0914c42ec7968579
d88b4eecb35a84c03f234488938fc23975210628
/cpp_test/smart_ptr/shared_ptr_get.cpp
e658b5ccae42b4c6fe163797646fe6a2a279e60d
[]
no_license
shaofeichang/daily_test
4de567075d37d9c3cbfc0945f395cf756ebfa2a6
f65305e80fa77e4ae13f8b802e4a7dc3c6493ce5
refs/heads/master
2021-06-19T14:43:56.584023
2021-03-29T01:09:18
2021-03-29T01:09:18
195,053,762
0
0
null
2021-03-29T01:10:20
2019-07-03T12:57:47
C++
UTF-8
C++
false
false
792
cpp
// shared_ptr::get example #include <iostream> #include <memory> struct C { int num1; void printnum() { std::cout << "num1: " << num1 << std::endl; } C(int n):num1(n) { std::cout << "C" << std::endl; } ~C() { std::cout << "~C" << std::endl; } }; int main() { int *p = new int(10); std::shared_ptr<int> a(p); if (a.get() == p) std::cout << "a and p point to the same location\n"; // three ways of accessing the same address: std::cout << *a.get() << "\n"; std::cout << *a << "\n"; std::cout << *p << "\n"; std::shared_ptr<C> ssp(new C(100)); C *cp = new C(1234); std::shared_ptr<C> ptrc(cp); cp->printnum(); ptrc->printnum(); ptrc.get()->printnum(); (*ptrc).printnum(); (*cp).printnum(); return 0; }
[ "chang1151230815@outlook.com" ]
chang1151230815@outlook.com