blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
769e0f8f620b7908215c1d40f0c5f6b44afd1dd0
4793aa98a5e61b3437ff75767f632cd335e1b01a
/zipreader/zipreader.h
c2bf1258f8e2f950db9381d061c999a3c32ee34f
[]
no_license
pnicolauc/ARMarkerEditor
c13490a7c27a4f8ac2bbdd8d4d43327cb8eacebd
1e9063b572b68eb01dd75b60b308b468543804c0
refs/heads/master
2021-08-12T07:45:50.865924
2017-11-14T14:57:27
2017-11-14T14:57:27
93,961,147
1
0
null
null
null
null
UTF-8
C++
false
false
3,317
h
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef ZipReader_H #define ZipReader_H #include <QtCore/qdatetime.h> #include <QtCore/qfile.h> #include <QtCore/qstring.h> class ZipReaderPrivate; class ZipReader { public: ZipReader(const QString &fileName, QIODevice::OpenMode mode = QIODevice::ReadOnly ); explicit ZipReader(QIODevice *device); ~ZipReader(); QIODevice* device() const; bool isReadable() const; bool exists() const; struct FileInfo { FileInfo(); FileInfo(const FileInfo &other); ~FileInfo(); FileInfo &operator=(const FileInfo &other); bool isValid() const; QString filePath; uint isDir : 1; uint isFile : 1; uint isSymLink : 1; QFile::Permissions permissions; uint crc32; qint64 size; QDateTime lastModified; void *d; }; QList<FileInfo> fileInfoList() const; int count() const; FileInfo entryInfoAt(int index) const; QByteArray fileData(const QString &fileName) const; bool extractAll(const QString &destinationDir) const; enum Status { NoError, FileReadError, FileOpenError, FilePermissionsError, FileError }; Status status() const; void close(); private: ZipReaderPrivate *d; Q_DISABLE_COPY(ZipReader) }; #endif // ZipReader_H
2419730c72135fa3f45df239dacc94ce2c590ab5
dba0d71187521d167770fd4ff5929c6a74927827
/Codechef/August Challenge 2020/Chef and Linear Chess.cpp
a011e4438bda3ee2d7491dde2f76700665aee59e
[]
no_license
Shihabulminhaz/My_Competitive_Programming_Code
6ffb1a51d07a1c11d67aa764703e342af5d37a8c
0bf3ca4b4d685d8a4ab2f11881075ffe446945df
refs/heads/master
2022-12-04T02:39:14.744496
2020-08-18T06:50:42
2020-08-18T06:50:42
274,332,491
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
cpp
/*==============================================*\ Codeforces ID: mdshihab | Name: Md. Shihabul Minhaz | Study: CSE, JKKNIU | Address: Trishal, Mymensingh, Bangladesh | | mail: [email protected] | FB : fb.com/mdshihabul.minhaz.7 | github: Shihabulminhaz | stopstalk : mdshihab | | @uthor Md. Shihabul Minhaz (shihab) | \*===============================================*/ #include<bits/stdc++.h> using namespace std; #define fi(a) scanf("%d",&a); #define fli(a) scanf("%ld",&a); #define fll(a) scanf("%lld",&a); #define pi(a) printf("%d\n",a); #define ppi(i,a) printf("Case %d: %d\n",i,a); #define ll long long #define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int shihab; void FI() { #ifndef ONLINE_JUDGE freopen("C:\\Users\\SHIHAB\\Desktop\\input.in","r",stdin); #endif // ONLINE_JUDGE } int main() { fast // FI(); /// skip this line for compile int t,n,k,mn,a,ans; cin >> t; while(t--) { mn = 2000000000; cin >> n >> k; for(int i=0; i<n; i++) { cin >> a; if(k%a==0) { if(mn>k/a) { mn = k/a; ans=a; } } } if(mn==2000000000) cout << -1 << endl; else cout << ans << endl; } return 0; //code end } //okbye
c5d63b23caec749577edc017b5cd71a7c8a044f4
eccd8caa201e348b0a212f889390d358a03b83f8
/MyProject/Plugins/AppPlugin/Source/AppPlugin/Private/ColorActor.cpp
180c14e9a243a4c9ab17050fd6b9e3d273010f7a
[]
no_license
liupanfengfreedom/wv2
4d84c44b52e1a33a5a16365888ccdce6475fcc44
f7f9eb4a55216c62cb87a953d76d215fccdbbafa
refs/heads/master
2022-12-14T04:59:08.364057
2020-09-15T12:56:53
2020-09-15T12:56:53
291,601,876
0
0
null
null
null
null
UTF-8
C++
false
false
882
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ColorActor.h" #include "MessageManager.h" #include "KeyMap.h" #include "Engine.h" // Sets default values AColorActor::AColorActor() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } void AColorActor::EndPlay(const EEndPlayReason::Type EndPlayReason) { REMOVEMESSAGELISTEN(this) } // Called when the game starts or when spawned void AColorActor::BeginPlay() { Super::BeginPlay(); ADDMESSAGELISTEN(this, key_onalphacontrolvalue, [=](const void* p) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Yellow, TEXT("key_onalphacontrolvalue-----------------------------cpp")); }) } // Called every frame void AColorActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
933eef9764ded7890bd8a7813544a0418ab470ab
9fb229975cc6bd01eb38c3e96849d0c36985fa1e
/src/iPhone/Sound/SoundEngine.cpp
2df43717679619db24254359be5300710a6d8b04
[]
no_license
Danewalker/ahr
3758bf3219f407ed813c2bbed5d1d86291b9237d
2af9fd5a866c98ef1f95f4d1c3d9b192fee785a6
refs/heads/master
2016-09-13T08:03:43.040624
2010-07-21T15:44:41
2010-07-21T15:44:41
56,323,321
0
0
null
null
null
null
UTF-8
C++
false
false
64,157
cpp
/*** Important: This is sample code demonstrating API, technology or techniques in development. Although this sample code has been reviewed for technical accuracy, it is not final. Apple is supplying this information to help you plan for the adoption of the technologies and programming interfaces described herein. This information is subject to change, and software implemented based on this sample code should be tested with final operating system software and final documentation. Newer versions of this sample code may be provided with future seeds of the API or technology. For information about updates to this and other developer documentation, view the New & Updated sidebars in subsequent documentation seeds. ***/ /* File: SoundEngine.cpp Abstract: This C API is a sound engine intended for games and applications that want to do more than casual UI sounds playback e.g. background music track, multiple sound effects, stereo panning... while ensuring low-latency response at the same time. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2008 Apple Inc. All Rights Reserved. */ /*================================================================================================== SoundEngine.cpp ==================================================================================================*/ #if !defined(__SoundEngine_cpp__) #define __SoundEngine_cpp__ //================================================================================================== // Includes //================================================================================================== // System Includes #include <AudioToolbox/AudioToolbox.h> #include <CoreFoundation/CFURL.h> #include <OpenAL/al.h> #include <OpenAL/alc.h> #include <map> #include <vector> #include <pthread.h> #include <mach/mach.h> #include <AudioToolbox/AudioServices.h> // Local Includes #include "SoundEngine.h" #include "config.h" #include "Gapi.h" extern unsigned int g_SystemVersion; #define AssertNoError(inMessage, inHandler) \ if(result != noErr) \ { \ printf("%s: %d\n", inMessage, (int)result); \ } #define AssertNoOALError(inMessage, inHandler) \ if((result = alGetError()) != AL_NO_ERROR) \ { \ printf("%s: %x\n", inMessage, (int)result); \ goto inHandler; \ } #define kNumberBuffers 3 class OpenALObject; class BackgroundTrackMgr; static OpenALObject *sOpenALObject = NULL; static BackgroundTrackMgr *sBackgroundTrackMgr = NULL; static Float32 gMasterVolumeGain = 1.0; int soundError = 0; extern "C" void GamePause(); extern "C" void GameResume(); void interruptionListenerCallback ( void *inUserData, UInt32 interruptionState ) { // This callback, being outside the implementation block, needs a reference // to the AudioViewController object if (interruptionState == kAudioSessionBeginInterruption) { //printf("interruptionListener\n"); //AudioSessionSetActive(false); GamePause(); } else if (interruptionState == kAudioSessionEndInterruption) { // if the interruption was removed, and the app had been playing, resume playback //printf("resumeListener\n"); GameResume(); } } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ typedef ALvoid AL_APIENTRY (*alBufferDataStaticProcPtr) (const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq); ALvoid alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* data, ALsizei size, ALsizei freq) { static alBufferDataStaticProcPtr proc = NULL; if (proc == NULL) { proc = (alBufferDataStaticProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alBufferDataStatic"); } if (proc) proc(bid, format, data, size, freq); return; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ typedef ALvoid AL_APIENTRY (*alcMacOSXMixerOutputRateProcPtr) (const ALdouble value); ALvoid alcMacOSXMixerOutputRateProc(const ALdouble value) { static alcMacOSXMixerOutputRateProcPtr proc = NULL; if (proc == NULL) { proc = (alcMacOSXMixerOutputRateProcPtr) alcGetProcAddress(NULL, (const ALCchar*) "alcMacOSXMixerOutputRate"); } if (proc) proc(value); return; } #pragma mark ***** OpenALThread ***** //================================================================================================== // Threading functions //================================================================================================== class OpenALThread { // returns the thread's priority as it was last set by the API #define OpenALThread_SET_PRIORITY 0 // returns the thread's priority as it was last scheduled by the Kernel #define OpenALThread_SCHEDULED_PRIORITY 1 // Types public: typedef void* (*ThreadRoutine)(void* inParameter); // Constants public: enum { kMinThreadPriority = 1, kMaxThreadPriority = 63, kDefaultThreadPriority = 31 }; // Construction/Destruction public: OpenALThread(ThreadRoutine inThreadRoutine, void* inParameter) : mPThread(0), mSpawningThreadPriority(getScheduledPriority(pthread_self(), OpenALThread_SET_PRIORITY)), mThreadRoutine(inThreadRoutine), mThreadParameter(inParameter), mPriority(kDefaultThreadPriority), mFixedPriority(false), mAutoDelete(true) { } ~OpenALThread() { } // Properties bool IsRunning() const { return 0 != mPThread; } void SetAutoDelete(bool b) { mAutoDelete = b; } void SetPriority(UInt32 inPriority, bool inFixedPriority) { OSStatus result = noErr; mPriority = inPriority; mFixedPriority = inFixedPriority; if(mPThread != 0) { if (mFixedPriority) { thread_extended_policy_data_t theFixedPolicy; theFixedPolicy.timeshare = false; // set to true for a non-fixed thread result = thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT); if (result) printf("OpenALThread::SetPriority: failed to set the fixed-priority policy"); return; } // We keep a reference to the spawning thread's priority around (initialized in the constructor), // and set the importance of the child thread relative to the spawning thread's priority. thread_precedence_policy_data_t thePrecedencePolicy; thePrecedencePolicy.importance = mPriority - mSpawningThreadPriority; result =thread_policy_set(pthread_mach_thread_np(mPThread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT); if (result) printf("OpenALThread::SetPriority: failed to set the precedence policy"); return; } } // Actions void Start() { if(mPThread != 0) { printf("OpenALThread::Start: can't start because the thread is already running\n"); return; } OSStatus result; pthread_attr_t theThreadAttributes; result = pthread_attr_init(&theThreadAttributes); AssertNoError("Error initializing thread", end); result = pthread_attr_setdetachstate(&theThreadAttributes, PTHREAD_CREATE_DETACHED); AssertNoError("Error setting thread detach state", end); result = pthread_create(&mPThread, &theThreadAttributes, (ThreadRoutine)OpenALThread::Entry, this); AssertNoError("Error creating thread", end); pthread_attr_destroy(&theThreadAttributes); AssertNoError("Error destroying thread attributes", end); end: return; } // Implementation protected: static void* Entry(OpenALThread* inOpenALThread) { void* theAnswer = NULL; inOpenALThread->SetPriority(inOpenALThread->mPriority, inOpenALThread->mFixedPriority); if(inOpenALThread->mThreadRoutine != NULL) { theAnswer = inOpenALThread->mThreadRoutine(inOpenALThread->mThreadParameter); } inOpenALThread->mPThread = 0; if (inOpenALThread->mAutoDelete) delete inOpenALThread; return theAnswer; } static UInt32 getScheduledPriority(pthread_t inThread, int inPriorityKind) { thread_basic_info_data_t threadInfo; policy_info_data_t thePolicyInfo; unsigned int count; if (inThread == NULL) return 0; // get basic info count = THREAD_BASIC_INFO_COUNT; thread_info (pthread_mach_thread_np (inThread), THREAD_BASIC_INFO, (thread_info_t)&threadInfo, &count); switch (threadInfo.policy) { case POLICY_TIMESHARE: count = POLICY_TIMESHARE_INFO_COUNT; thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_TIMESHARE_INFO, (thread_info_t)&(thePolicyInfo.ts), &count); if (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) { return thePolicyInfo.ts.cur_priority; } return thePolicyInfo.ts.base_priority; break; case POLICY_FIFO: count = POLICY_FIFO_INFO_COUNT; thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_FIFO_INFO, (thread_info_t)&(thePolicyInfo.fifo), &count); if ( (thePolicyInfo.fifo.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) { return thePolicyInfo.fifo.depress_priority; } return thePolicyInfo.fifo.base_priority; break; case POLICY_RR: count = POLICY_RR_INFO_COUNT; thread_info(pthread_mach_thread_np (inThread), THREAD_SCHED_RR_INFO, (thread_info_t)&(thePolicyInfo.rr), &count); if ( (thePolicyInfo.rr.depressed) && (inPriorityKind == OpenALThread_SCHEDULED_PRIORITY) ) { return thePolicyInfo.rr.depress_priority; } return thePolicyInfo.rr.base_priority; break; } return 0; } pthread_t mPThread; UInt32 mSpawningThreadPriority; ThreadRoutine mThreadRoutine; void* mThreadParameter; SInt32 mPriority; bool mFixedPriority; bool mAutoDelete; // delete self when thread terminates }; //================================================================================================== // Helper functions //================================================================================================== OSStatus OpenFile(const char *inFilePath, AudioFileID &outAFID) { CFURLRef theURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, (UInt8*)inFilePath, strlen(inFilePath), false); if (theURL == NULL) return kSoundEngineErrFileNotFound; OSStatus result = AudioFileOpenURL(theURL, kAudioFileReadPermission, 0, &outAFID); CFRelease(theURL); AssertNoError("Error opening file", end); end: return result; return 0; } OSStatus LoadFileDataInfo(const char *inFilePath, AudioFileID &outAFID, AudioStreamBasicDescription &outFormat, UInt64 &outDataSize) { UInt32 thePropSize = sizeof(outFormat); OSStatus result = OpenFile(inFilePath, outAFID); AssertNoError("Error opening file", end); result = AudioFileGetProperty(outAFID, kAudioFilePropertyDataFormat, &thePropSize, &outFormat); AssertNoError("Error getting file format", end); thePropSize = sizeof(UInt64); result = AudioFileGetProperty(outAFID, kAudioFilePropertyAudioDataByteCount, &thePropSize, &outDataSize); AssertNoError("Error getting file data size", end); end: return result; } void CalculateBytesForTime (AudioStreamBasicDescription & inDesc, UInt32 inMaxPacketSize, Float64 inSeconds, UInt32 *outBufferSize, UInt32 *outNumPackets) { static const UInt32 maxBufferSize = 0x10000; // limit size to 64K static const UInt32 minBufferSize = 0x4000; // limit size to 16K if (inDesc.mFramesPerPacket) { Float64 numPacketsForTime = inDesc.mSampleRate / inDesc.mFramesPerPacket * inSeconds; *outBufferSize = numPacketsForTime * inMaxPacketSize; } else { // if frames per packet is zero, then the codec has no predictable packet == time // so we can't tailor this (we don't know how many Packets represent a time period // we'll just return a default buffer size *outBufferSize = maxBufferSize > inMaxPacketSize ? maxBufferSize : inMaxPacketSize; } // we're going to limit our size to our default if (*outBufferSize > maxBufferSize && *outBufferSize > inMaxPacketSize) *outBufferSize = maxBufferSize; else { // also make sure we're not too small - we don't want to go the disk for too small chunks if (*outBufferSize < minBufferSize) *outBufferSize = minBufferSize; } *outNumPackets = *outBufferSize / inMaxPacketSize; } static Boolean MatchFormatFlags(const AudioStreamBasicDescription& x, const AudioStreamBasicDescription& y) { UInt32 xFlags = x.mFormatFlags; UInt32 yFlags = y.mFormatFlags; // match wildcards if (x.mFormatID == 0 || y.mFormatID == 0 || xFlags == 0 || yFlags == 0) return true; if (x.mFormatID == kAudioFormatLinearPCM) { // knock off the all clear flag xFlags = xFlags & ~kAudioFormatFlagsAreAllClear; yFlags = yFlags & ~kAudioFormatFlagsAreAllClear; // if both kAudioFormatFlagIsPacked bits are set, then we don't care about the kAudioFormatFlagIsAlignedHigh bit. if (xFlags & yFlags & kAudioFormatFlagIsPacked) { xFlags = xFlags & ~kAudioFormatFlagIsAlignedHigh; yFlags = yFlags & ~kAudioFormatFlagIsAlignedHigh; } // if both kAudioFormatFlagIsFloat bits are set, then we don't care about the kAudioFormatFlagIsSignedInteger bit. if (xFlags & yFlags & kAudioFormatFlagIsFloat) { xFlags = xFlags & ~kAudioFormatFlagIsSignedInteger; yFlags = yFlags & ~kAudioFormatFlagIsSignedInteger; } // if the bit depth is 8 bits or less and the format is packed, we don't care about endianness if((x.mBitsPerChannel <= 8) && ((xFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked)) { xFlags = xFlags & ~kAudioFormatFlagIsBigEndian; } if((y.mBitsPerChannel <= 8) && ((yFlags & kAudioFormatFlagIsPacked) == kAudioFormatFlagIsPacked)) { yFlags = yFlags & ~kAudioFormatFlagIsBigEndian; } // if the number of channels is 0 or 1, we don't care about non-interleavedness if (x.mChannelsPerFrame <= 1 && y.mChannelsPerFrame <= 1) { xFlags &= ~kLinearPCMFormatFlagIsNonInterleaved; yFlags &= ~kLinearPCMFormatFlagIsNonInterleaved; } } return xFlags == yFlags; } Boolean FormatIsEqual(AudioStreamBasicDescription x, AudioStreamBasicDescription y) { // the semantics for equality are: // 1) Values must match exactly // 2) wildcard's are ignored in the comparison #define MATCH(name) ((x.name) == 0 || (y.name) == 0 || (x.name) == (y.name)) return ((x.mSampleRate==0.) || (y.mSampleRate==0.) || (x.mSampleRate==y.mSampleRate)) && MATCH(mFormatID) && MatchFormatFlags(x, y) && MATCH(mBytesPerPacket) && MATCH(mFramesPerPacket) && MATCH(mBytesPerFrame) && MATCH(mChannelsPerFrame) && MATCH(mBitsPerChannel) ; } #pragma mark ***** BackgroundTrackMgr ***** static volatile bool s_ignoreQueueCallBack = false; //================================================================================================== // BackgroundTrackMgr class //================================================================================================== class BackgroundTrackMgr { #define CurFileInfo THIS->mBGFileInfo[THIS->mCurrentFileIndex] public: typedef struct BG_FileInfo { const char* mFilePath; AudioFileID mAFID; AudioStreamBasicDescription mFileFormat; UInt64 mFileDataSize; //UInt64 mFileNumPackets; // this is only used if loading file to memory Boolean mLoadAtOnce; Boolean mFileDataInQueue; } BackgroundMusicFileInfo; BackgroundTrackMgr() : mQueue(0), mBufferByteSize(0), mCurrentPacket(0), mNumPacketsToRead(0), mVolume(1.0), mPacketDescs(NULL), mCurrentFileIndex(0), mMakeNewQueueWhenStopped(false), mStopAtEnd(false) { } ~BackgroundTrackMgr() { Teardown(); } void Teardown() { //music will be destroy so ignore refilling buffers form QueueCallBack s_ignoreQueueCallBack = true; AudioSessionSetActive(false); if (mQueue) AudioQueueDispose(mQueue, true); mQueue = 0; for (UInt32 i=0; i < mBGFileInfo.size(); i++) { if (mBGFileInfo[i]->mAFID) AudioFileClose(mBGFileInfo[i]->mAFID); if(mBGFileInfo[i]) delete mBGFileInfo[i]; } mBGFileInfo.clear(); if(mPacketDescs) { delete[] mPacketDescs; mPacketDescs = NULL; } } AudioStreamPacketDescription *GetPacketDescsPtr() { return mPacketDescs; } UInt32 GetNumPacketsToRead(BackgroundTrackMgr::BG_FileInfo *inFileInfo) { return mNumPacketsToRead; } static OSStatus AttachNewCookie(AudioQueueRef inQueue, BackgroundTrackMgr::BG_FileInfo *inFileInfo) { OSStatus result = noErr; UInt32 size = sizeof(UInt32); result = AudioFileGetPropertyInfo (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, NULL); if (!result && size) { char* cookie = new char [size]; result = AudioFileGetProperty (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, cookie); AssertNoError("Error getting cookie data", end); result = AudioQueueSetProperty(inQueue, kAudioQueueProperty_MagicCookie, cookie, size); delete [] cookie; AssertNoError("Error setting cookie data for queue", end); } return noErr; end: return noErr; } static void QueueStoppedProc( void * inUserData, AudioQueueRef inAQ, AudioQueuePropertyID inID) { UInt32 isRunning; UInt32 propSize = sizeof(isRunning); BackgroundTrackMgr *THIS = (BackgroundTrackMgr*)inUserData; OSStatus result = AudioQueueGetProperty(inAQ, kAudioQueueProperty_IsRunning, &isRunning, &propSize); if ((!isRunning) && (THIS->mMakeNewQueueWhenStopped)) { AudioSessionSetActive(false); result = AudioQueueDispose(inAQ, true); AssertNoError("Error disposing queue", end); result = THIS->SetupQueue(CurFileInfo); AssertNoError("Error setting up new queue", end); result = THIS->SetupBuffers(CurFileInfo); AssertNoError("Error setting up new queue buffers", end); result = THIS->Start(); AssertNoError("Error starting queue", end); } end: return; } static Boolean DisposeBuffer(AudioQueueRef inAQ, std::vector<AudioQueueBufferRef> inDisposeBufferList, AudioQueueBufferRef inBufferToDispose) { for (unsigned int i=0; i < inDisposeBufferList.size(); i++) { if (inBufferToDispose == inDisposeBufferList[i]) { OSStatus result = AudioQueueFreeBuffer(inAQ, inBufferToDispose); if (result == noErr) { //inDisposeBufferList.pop_back(); inDisposeBufferList.erase(inDisposeBufferList.begin() + i); } return true; } } return false; } enum { kQueueState_DoNothing = 0, kQueueState_ResizeBuffer = 1, kQueueState_NeedNewCookie = 2, kQueueState_NeedNewBuffers = 3, kQueueState_NeedNewQueue = 4, }; static SInt8 GetQueueStateForNextBuffer(BackgroundTrackMgr::BG_FileInfo *inFileInfo, BackgroundTrackMgr::BG_FileInfo *inNextFileInfo) { inFileInfo->mFileDataInQueue = false; // unless the data formats are the same, we need a new queue if (!FormatIsEqual(inFileInfo->mFileFormat, inNextFileInfo->mFileFormat)) return kQueueState_NeedNewQueue; // if going from a load-at-once file to streaming or vice versa, we need new buffers if (inFileInfo->mLoadAtOnce != inNextFileInfo->mLoadAtOnce) return kQueueState_NeedNewBuffers; // if the next file is smaller than the current, we just need to resize if (inNextFileInfo->mLoadAtOnce) return (inFileInfo->mFileDataSize >= inNextFileInfo->mFileDataSize) ? kQueueState_ResizeBuffer : kQueueState_NeedNewBuffers; return kQueueState_NeedNewCookie; } static void QueueCallback( void * inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inCompleteAQBuffer) { // dispose of the buffer if no longer in use OSStatus result = noErr; BackgroundTrackMgr *THIS = (BackgroundTrackMgr*)inUserData; if (DisposeBuffer(inAQ, THIS->mBuffersToDispose, inCompleteAQBuffer)) return; if(s_ignoreQueueCallBack) return; UInt32 nPackets = 0; // loop the current buffer if the following: // 1. file was loaded into the buffer previously // 2. only one file in the queue // 3. we have not been told to stop at playlist completion if ((CurFileInfo->mFileDataInQueue) && (THIS->mBGFileInfo.size() == 1) && (!THIS->mStopAtEnd)) nPackets = THIS->GetNumPacketsToRead(CurFileInfo); else { UInt32 numBytes; while (nPackets == 0) { // if loadAtOnce, get all packets in the file, otherwise ~.5 seconds of data nPackets = THIS->GetNumPacketsToRead(CurFileInfo); result = AudioFileReadPackets(CurFileInfo->mAFID, false, &numBytes, THIS->mPacketDescs, THIS->mCurrentPacket, &nPackets, inCompleteAQBuffer->mAudioData); AssertNoError("Error reading file data", end); inCompleteAQBuffer->mAudioDataByteSize = numBytes; if (nPackets == 0) // no packets were read, this file has ended. { if (CurFileInfo->mLoadAtOnce) CurFileInfo->mFileDataInQueue = true; THIS->mCurrentPacket = 0; UInt32 theNextFileIndex = (THIS->mCurrentFileIndex < THIS->mBGFileInfo.size()-1) ? THIS->mCurrentFileIndex+1 : 0; // we have gone through the playlist. if mStopAtEnd, stop the queue here if (theNextFileIndex == 0 && THIS->mStopAtEnd) { result = AudioQueueStop(inAQ, false); AssertNoError("Error stopping queue", end); return; } SInt8 theQueueState = GetQueueStateForNextBuffer(CurFileInfo, THIS->mBGFileInfo[theNextFileIndex]); if (theNextFileIndex != THIS->mCurrentFileIndex) { // if were are not looping the same file. Close the old one and open the new result = AudioFileClose(CurFileInfo->mAFID); AssertNoError("Error closing file", end); THIS->mCurrentFileIndex = theNextFileIndex; result = LoadFileDataInfo(CurFileInfo->mFilePath, CurFileInfo->mAFID, CurFileInfo->mFileFormat, CurFileInfo->mFileDataSize); AssertNoError("Error opening file", end); } switch (theQueueState) { // if we need to resize the buffer, set the buffer's audio data size to the new file's size // we will also need to get the new file cookie case kQueueState_ResizeBuffer: inCompleteAQBuffer->mAudioDataByteSize = CurFileInfo->mFileDataSize; // if the data format is the same but we just need a new cookie, attach a new cookie case kQueueState_NeedNewCookie: result = AttachNewCookie(inAQ, CurFileInfo); AssertNoError("Error attaching new file cookie data to queue", end); break; // we can keep the same queue, but not the same buffer(s) case kQueueState_NeedNewBuffers: THIS->mBuffersToDispose.push_back(inCompleteAQBuffer); THIS->SetupBuffers(CurFileInfo); break; // if the data formats are not the same, we need to dispose the current queue and create a new one case kQueueState_NeedNewQueue: THIS->mMakeNewQueueWhenStopped = true; result = AudioQueueStop(inAQ, false); AssertNoError("Error stopping queue", end); return; default: break; } } } } //printf("enqueueing %d bytes\n", inCompleteAQBuffer->mAudioDataByteSize); result = AudioQueueEnqueueBuffer(inAQ, inCompleteAQBuffer, (THIS->mPacketDescs ? nPackets : 0), THIS->mPacketDescs); soundError = result; AssertNoError("Error enqueuing new buffer", end); if (CurFileInfo->mLoadAtOnce) CurFileInfo->mFileDataInQueue = true; THIS->mCurrentPacket += nPackets; end: return; } OSStatus SetupQueue(BG_FileInfo *inFileInfo) { UInt32 size = 0; //free old AudioQueue if (mQueue) AudioQueueDispose(mQueue, true); mQueue = 0; static bool s_bAudioSessionInitialized = false; if(!s_bAudioSessionInitialized) { //intialize a sesion for this queue AudioSessionInitialize(NULL, NULL, interruptionListenerCallback, NULL); // before instantiating the playback audio queue object, // set the audio session category UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; AudioSessionSetProperty ( kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory); s_bAudioSessionInitialized = true; } OSStatus result = AudioQueueNewOutput(&inFileInfo->mFileFormat, QueueCallback, this, NULL/*CFRunLoopGetCurrent()*/, kCFRunLoopCommonModes, 0, &mQueue); AssertNoError("Error creating queue", end); // (2) If the file has a cookie, we should get it and set it on the AQ size = sizeof(UInt32); result = AudioFileGetPropertyInfo (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, NULL); if (!result && size) { char* cookie = new char [size]; result = AudioFileGetProperty (inFileInfo->mAFID, kAudioFilePropertyMagicCookieData, &size, cookie); AssertNoError("Error getting magic cookie", end); result = AudioQueueSetProperty(mQueue, kAudioQueueProperty_MagicCookie, cookie, size); delete [] cookie; AssertNoError("Error setting magic cookie", end); } // channel layout OSStatus err = AudioFileGetPropertyInfo(inFileInfo->mAFID, kAudioFilePropertyChannelLayout, &size, NULL); if (err == noErr && size > 0) { AudioChannelLayout *acl = (AudioChannelLayout *)malloc(size); result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyChannelLayout, &size, acl); AssertNoError("Error getting channel layout from file", end); result = AudioQueueSetProperty(mQueue, kAudioQueueProperty_ChannelLayout, acl, size); free(acl); AssertNoError("Error setting channel layout on queue", end); } // add a notification proc for when the queue stops result = AudioQueueAddPropertyListener(mQueue, kAudioQueueProperty_IsRunning, QueueStoppedProc, this); AssertNoError("Error adding isRunning property listener to queue", end); // we need to reset this variable so that if the queue is stopped mid buffer we don't dispose it mMakeNewQueueWhenStopped = false; // volume result = SetVolume(mVolume); AudioSessionSetActive(true); end: return result; } OSStatus SetupBuffers(BG_FileInfo *inFileInfo) { int numBuffersToQueue = kNumberBuffers; UInt32 maxPacketSize; UInt32 size = sizeof(maxPacketSize); // we need to calculate how many packets we read at a time, and how big a buffer we need // we base this on the size of the packets in the file and an approximate duration for each buffer // first check to see what the max size of a packet is - if it is bigger // than our allocation default size, that needs to become larger OSStatus result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyPacketSizeUpperBound, &size, &maxPacketSize); AssertNoError("Error getting packet upper bound size", end1); bool isFormatVBR = (inFileInfo->mFileFormat.mBytesPerPacket == 0 || inFileInfo->mFileFormat.mFramesPerPacket == 0); CalculateBytesForTime(inFileInfo->mFileFormat, maxPacketSize, 0.5/*seconds*/, &mBufferByteSize, &mNumPacketsToRead); // if the file is smaller than the capacity of all the buffer queues, always load it at once if ((mBufferByteSize * numBuffersToQueue) > inFileInfo->mFileDataSize) inFileInfo->mLoadAtOnce = true; if (inFileInfo->mLoadAtOnce) { UInt64 theFileNumPackets; size = sizeof(UInt64); result = AudioFileGetProperty(inFileInfo->mAFID, kAudioFilePropertyAudioDataPacketCount, &size, &theFileNumPackets); AssertNoError("Error getting packet count for file", end1); mNumPacketsToRead = (UInt32)theFileNumPackets; mBufferByteSize = inFileInfo->mFileDataSize; numBuffersToQueue = 1; } else { mNumPacketsToRead = mBufferByteSize / maxPacketSize; } if(mPacketDescs) { delete[] mPacketDescs; mPacketDescs = NULL; } if (isFormatVBR) mPacketDescs = new AudioStreamPacketDescription [mNumPacketsToRead]; else mPacketDescs = NULL; // we don't provide packet descriptions for constant bit rate formats (like linear PCM) //music will be created ... let QueueCallBack to initialize buffers s_ignoreQueueCallBack = false; // allocate the queue's buffers for (int i = 0; i < numBuffersToQueue; ++i) { result = AudioQueueAllocateBuffer(mQueue, mBufferByteSize, &mBuffers[i]); AssertNoError("Error allocating buffer for queue", end1); QueueCallback (this, mQueue, mBuffers[i]); if (inFileInfo->mLoadAtOnce) inFileInfo->mFileDataInQueue = true; } end1: return result; } OSStatus LoadTrack(const char* inFilePath, Boolean inAddToQueue, Boolean inLoadAtOnce) { // if not adding to the queue, clear the current file vector if (!inAddToQueue) { for (UInt32 i=0; i < mBGFileInfo.size(); i++) { if (mBGFileInfo[i]->mAFID) AudioFileClose(mBGFileInfo[i]->mAFID); if(mBGFileInfo[i]) delete mBGFileInfo[i]; } mBGFileInfo.clear(); } BG_FileInfo *fileInfo = new BG_FileInfo; fileInfo->mFilePath = inFilePath; OSStatus result = LoadFileDataInfo(fileInfo->mFilePath, fileInfo->mAFID, fileInfo->mFileFormat, fileInfo->mFileDataSize); AssertNoError("Error getting file data info", fail); fileInfo->mLoadAtOnce = inLoadAtOnce; fileInfo->mFileDataInQueue = false; mBGFileInfo.push_back(fileInfo); // setup the queue if this is the first (or only) file if (mBGFileInfo.size() == 1) { result = SetupQueue(fileInfo); AssertNoError("Error setting up queue", fail); result = SetupBuffers(fileInfo); AssertNoError("Error setting up queue buffers", fail); } // if this is just part of the playlist, close the file for now else { result = AudioFileClose(fileInfo->mAFID); AssertNoError("Error closing file", fail); } return result; fail: if (fileInfo) delete fileInfo; return result; } OSStatus UpdateGain() { return SetVolume(mVolume); } OSStatus SetVolume(Float32 inVolume) { mVolume = inVolume; return AudioQueueSetParameter(mQueue, kAudioQueueParam_Volume, mVolume * gMasterVolumeGain); } OSStatus Start() { //music will start ... so let the QueueCallBack to refill buffers s_ignoreQueueCallBack = false; OSStatus result = AudioQueuePrime(mQueue, 1, NULL); if (result) { printf("Error priming queue"); return result; } return AudioQueueStart(mQueue, NULL); } OSStatus Stop(Boolean inStopAtEnd) { //music will be stopped so ignore refilling buffers form QueueCallBack s_ignoreQueueCallBack = true; if (inStopAtEnd) { mStopAtEnd = true; return noErr; } else return AudioQueueStop(mQueue, true); } bool IsPlaying() { UInt32 isRunning; UInt32 propSize = sizeof(isRunning); AudioQueueGetProperty(mQueue, kAudioQueueProperty_IsRunning, &isRunning, &propSize); return isRunning!=0; } public: AudioQueueRef mQueue; AudioQueueBufferRef mBuffers[kNumberBuffers]; UInt32 mBufferByteSize; SInt64 mCurrentPacket; UInt32 mNumPacketsToRead; Float32 mVolume; AudioStreamPacketDescription * mPacketDescs; std::vector<BG_FileInfo*> mBGFileInfo; UInt32 mCurrentFileIndex; Boolean mMakeNewQueueWhenStopped; Boolean mStopAtEnd; std::vector<AudioQueueBufferRef> mBuffersToDispose; }; #pragma mark ***** SoundDataParser ***** class SoundDataParser { private: AudioFileStreamID audioStream; AudioStreamBasicDescription audioDataFormat; UInt32 soundDataSize, soundDataOffset; char * soundData; static void Parser_PropertyListener (void *inClientData, AudioFileStreamID inAudioFileStream, AudioFileStreamPropertyID inPropertyID, UInt32 *ioFlags) { SoundDataParser* parser = (SoundDataParser*)inClientData; UInt32 propSize; OSStatus result = noErr; switch (inPropertyID) { case kAudioFileStreamProperty_DataFormat: propSize = sizeof(parser->audioDataFormat); result = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_DataFormat, &propSize, &(parser->audioDataFormat)); break; case kAudioFileStreamProperty_AudioDataByteCount: propSize = sizeof(parser->soundDataSize); result = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_AudioDataByteCount, &propSize, &(parser->soundDataSize)); break; } } static void Parser_PacketsListener (void *inClientData, UInt32 inNumberBytes, UInt32 inNumberPackets, const void *inInputData, AudioStreamPacketDescription *inPacketDescriptions) { SoundDataParser* parser = (SoundDataParser*)inClientData; // allocating memory if needed if (parser->soundData == NULL) { if (parser->soundDataSize == 0) { parser->soundDataSize = inNumberBytes; parser->soundDataOffset = 0; } parser->soundData = (char *) malloc (parser->soundDataSize); } memcpy(parser->soundData + parser->soundDataOffset, inInputData, inNumberBytes); parser->soundDataOffset += inNumberBytes; } public: SoundDataParser() { audioStream = NULL; soundData = NULL; soundDataSize = 0; } ~SoundDataParser() { Close(); } OSStatus Init(const char * data, unsigned long dataLen) { Close(); soundDataOffset = 0; OSStatus result = noErr; result = AudioFileStreamOpen (this, Parser_PropertyListener, Parser_PacketsListener, 0, &audioStream); AssertNoError("Error creating AudioFileStream", end); result = AudioFileStreamParseBytes(audioStream, dataLen, data, 0); AssertNoError("Error parsing bytes", end); end: return result; } void Close() { if (audioStream != NULL) { AudioFileStreamClose(audioStream); audioStream = NULL; } if (soundData != NULL) { free (soundData); soundData = NULL; } } char* GetData(UInt32* dataLen) { if (soundDataSize == 0 || soundDataSize != soundDataOffset) return NULL; char* soundDataTmp = soundData; *dataLen = soundDataSize; soundData = NULL; return soundDataTmp; } AudioStreamBasicDescription* GetDataFormat() { return &audioDataFormat; } }; #pragma mark ***** SoundEngineEffect ***** //================================================================================================== // SoundEngineEffect class //================================================================================================== class SoundEngineEffect { public: // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SoundEngineEffect(const char* inLoopData, int inLoopLength/*, const char* inAttackData, int inAttackLength, const char* inDecayData, int inDecayLength,*//* Boolean inDoLoop*/) : mSourceID(0), // mAttackBufferID(0), mLoopBufferID(0), // mDecayBufferID(0), mLoopFileData(inLoopData), mLoopFileLen(inLoopLength), // mAttackFileData(inAttackData), // mAttackFileLen(inAttackLength), // mDecayFileData(inDecayData), // mDecayFileLen(inDecayLength), mLoopData(NULL), // mAttackData(NULL), // mDecayData(NULL), mLoopDataSize(0) // mAttackDataSize(0), // mDecayDataSize(0), // mIsLoopingEffect(inDoLoop), //mPlayThread(NULL) // mPlayThreadState(kPlayThreadState_Loop) { alGenSources(1, &mSourceID); } ~SoundEngineEffect() { ALenum state; //cdp 001 //alGetSourcei(mSourceID, AL_SOURCE_STATE, &state); //if(state != AL_STOPPED) //{ // alSourceStop(mSourceID); //} //clear the buffers for this source //ClearSourceBuffers(mSourceID); //cdp 002 alSourcei(mSourceID, AL_BUFFER, 0); alDeleteSources(1, &mSourceID); //cdp 001 alDeleteBuffers(1, &mLoopBufferID); if (mLoopData) free(mLoopData); mLoopData = NULL; // if (mAttackData) // free(mAttackData); // if (mDecayData) // free(mDecayData); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Accessors // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UInt32 GetEffectID() { return mSourceID; } // UInt32 GetPlayThreadState() { return mPlayThreadState; } // Boolean HasAttackBuffer() { return mAttackBufferID != 0; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Helper Functions // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ALenum GetALFormat(AudioStreamBasicDescription inFileFormat) { if (inFileFormat.mFormatID != kAudioFormatLinearPCM) return kSoundEngineErrInvalidFileFormat; if ((inFileFormat.mChannelsPerFrame > 2) || (inFileFormat.mChannelsPerFrame < 1)) return kSoundEngineErrInvalidFileFormat; if(inFileFormat.mBitsPerChannel == 8) return (inFileFormat.mChannelsPerFrame == 1) ? AL_FORMAT_MONO8 : AL_FORMAT_STEREO8; else if(inFileFormat.mBitsPerChannel == 16) return (inFileFormat.mChannelsPerFrame == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16; return kSoundEngineErrInvalidFileFormat; } // OSStatus LoadFileData(const char *inFilePath, void* &outData, UInt32 &outDataSize, ALuint &outBufferID) // { // AudioFileID theAFID = 0; // OSStatus result = noErr; // UInt64 theFileSize = 0; // AudioStreamBasicDescription theFileFormat; // // result = LoadFileDataInfo(inFilePath, theAFID, theFileFormat, theFileSize); // outDataSize = (UInt32)theFileSize; // AssertNoError("Error loading file info", fail) // // outData = malloc(outDataSize); // // result = AudioFileReadBytes(theAFID, false, 0, &outDataSize, outData); // AssertNoError("Error reading file data", fail) // // if (!TestAudioFormatNativeEndian(theFileFormat) && (theFileFormat.mBitsPerChannel > 8)) // return kSoundEngineErrInvalidFileFormat; // // alGenBuffers(1, &outBufferID); // AssertNoOALError("Error generating buffer\n", fail); // // alBufferDataStaticProc(outBufferID, GetALFormat(theFileFormat), outData, outDataSize, theFileFormat.mSampleRate); // AssertNoOALError("Error attaching data to buffer\n", fail); // // AudioFileClose(theAFID); // return result; // // fail: // if (theAFID) // AudioFileClose(theAFID); // if (outData) // { // free(outData); // outData = NULL; // } // return result; // } OSStatus LoadAudioData(const char *fileData, unsigned long fileDataLen, void* &outData, UInt32 &outDataSize, ALuint &outBufferID) { SoundDataParser* parser = new SoundDataParser(); OSStatus result = noErr; AudioStreamBasicDescription* theFileFormat; // result = LoadFileDataInfo(inFilePath, theAFID, theFileFormat, theFileSize); // outDataSize = (UInt32)theFileSize; // AssertNoError("Error loading file info", fail) parser->Init(fileData, fileDataLen); outData = parser->GetData(&outDataSize); if (outData == NULL) { printf("%s: %d\n", "Error parsing audio data", (int)result); goto fail; } theFileFormat = parser->GetDataFormat(); if (!TestAudioFormatNativeEndian((*theFileFormat)) && (theFileFormat->mBitsPerChannel > 8)) return kSoundEngineErrInvalidFileFormat; // converting audio data // commented to fix bug # if (g_SystemVersion < SYSTEM_VERSION_SOUND_BUG) { if (theFileFormat->mBitsPerChannel == 8) { char* chData = (char*)outData; for (int i = outDataSize - 1; i >= 0; i--) { chData[i] -= 0x80; } } } alGenBuffers(1, &outBufferID); AssertNoOALError("Error generating buffer", fail); //cdp 001 //~alBufferDataStaticProc(outBufferID, GetALFormat(*theFileFormat), outData, outDataSize, theFileFormat->mSampleRate); //~AssertNoOALError("Error attaching data to buffer", fail); alBufferData(outBufferID, GetALFormat(*theFileFormat), outData, outDataSize, theFileFormat->mSampleRate); AssertNoOALError("Error attaching data to buffer", fail); parser->Close(); delete (parser); return result; fail: if (parser) { parser->Close(); delete (parser); } if (outData) { free(outData); outData = NULL; } return result; } OSStatus AttachFilesToSource() { OSStatus result = AL_NO_ERROR; // first check for the attack file. That will be first in the queue if present // if (mAttackPath) // { // result = LoadFileData(mAttackPath, mAttackData, mAttackDataSize, mAttackBufferID); // AssertNoError("Error loading attack file info", end) // } result = LoadAudioData(mLoopFileData, mLoopFileLen, mLoopData, mLoopDataSize, mLoopBufferID); AssertNoError("Error loading looping file info", end) // if one-shot effect, attach the buffer to the source now // if (!mIsLoopingEffect) // { // alSourcei(mSourceID, AL_BUFFER, mLoopBufferID); // AssertNoOALError("Error attaching file data to effect", end) // } // if (mDecayPath) // { // result = LoadFileData(mDecayPath, mDecayData, mDecayDataSize, mDecayBufferID); // AssertNoError("Error loading decay file info", end) // } //cdp 001 alSourcei(mSourceID, AL_BUFFER, mLoopBufferID); AssertNoOALError("Error attaching file data to effect", end) end: return result; } OSStatus ClearSourceBuffers(ALuint sourceID) { OSStatus result = AL_NO_ERROR; ALint numQueuedBuffers = 0; ALuint *bufferIDs = (ALuint*)malloc(numQueuedBuffers * sizeof(ALint)); alGetSourcei(sourceID, AL_BUFFERS_QUEUED, &numQueuedBuffers); AssertNoOALError("Error getting OpenAL queued buffer size", end) alSourceUnqueueBuffers(sourceID, numQueuedBuffers, bufferIDs); AssertNoOALError("Error unqueueing buffers from source", end) //cdp 001 alDeleteBuffers(numQueuedBuffers, bufferIDs); AssertNoOALError("Error deleting queued buffers from source", end) end: free(bufferIDs); return result; } static void* PlaybackProc(void *args) { OSStatus result = AL_NO_ERROR; SoundEngineEffect *THIS = (SoundEngineEffect*)args; alSourcePlay(THIS->GetEffectID()); AssertNoOALError("Error starting effect playback", end) // // if attack buffer is present, wait until it has completed, then turn looping on // if (THIS->HasAttackBuffer()) // { // ALint numBuffersProcessed = 0; // while (numBuffersProcessed < 1) // { // alGetSourcei(THIS->GetEffectID(), AL_BUFFERS_PROCESSED, &numBuffersProcessed); // AssertNoOALError("Error getting processed buffer number", end) // } // // ALuint tmpBuffer = 0; // alSourceUnqueueBuffers(THIS->GetEffectID(), 1, &tmpBuffer); // AssertNoOALError("Error unqueueing buffers from source", end) // } // now that we have processed the attack buffer, loop the main one THIS->SetLooping(THIS->mIsLoopingEffect); end: return NULL; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Effect management // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OSStatus Start(Boolean loop) { OSStatus result = AL_NO_ERROR; ALenum state; alSourceStop(mSourceID); AssertNoOALError("Error stopping source", end) mIsLoopingEffect = loop; // if (!mIsLoopingEffect) // { // // if we are just playing one-short effects, start playback here // alSourcePlay(mSourceID); // return alGetError(); // } // for loops we need to spawn a new thread //mPlayThread = new OpenALThread(PlaybackProc, (void*)this); // we want this to delete upon thread completion // mPlayThreadState = kPlayThreadState_Loop; // clean up remnants from any previous playback of the source //cdp 001 //~result = ClearSourceBuffers(mSourceID); //~ AssertNoError("Error clearing buffers", end) // if the effect has an attack sample, queue this first // if (HasAttackBuffer()) // { // alSourceQueueBuffers(mSourceID, 1, &mAttackBufferID); // AssertNoOALError("Error queueing buffers for attack", end) // // turn on looping after the attack buffer has been processed // SetLooping(false); // } //cdp 001 //~alSourceQueueBuffers(mSourceID, 1, &mLoopBufferID); //~ AssertNoOALError("Error queueing looping buffer", end) //cdp 002 //mPlayThread->Start(); alSourcePlay(mSourceID); AssertNoOALError("Error start sound", end) SetLooping(mIsLoopingEffect); end: return result; } // OSStatus StartDecay() // { // // turn off looping, and queue the decay buffer // OSStatus result = AL_NO_ERROR; // alSourcei(mSourceID, AL_LOOPING, 0); // AssertNoOALError("Error turning off looping", end) // alSourceQueueBuffers(mSourceID, 1, &mDecayBufferID); // AssertNoOALError("Error queueing decay file", end) // end: // return result; // } OSStatus Pause() { OSStatus result = AL_NO_ERROR; alSourcePause(mSourceID); AssertNoOALError("Error stopping source", end) end: return result; } OSStatus Resume() { OSStatus result = AL_NO_ERROR; alSourcePlay(mSourceID); AssertNoOALError("Error stopping source", end) end: return result; } OSStatus Stop(/*Boolean inDoDecay*/) { OSStatus result = AL_NO_ERROR; // for non looped effects and loops with no decay sample // if ((mDecayBufferID == 0) || !inDoDecay) // { // // if no decay to play, just stop the source alSourceStop(mSourceID); AssertNoOALError("Error stopping source", end) // } // else // return StartDecay(); end: return result; } OSStatus SetPitch(Float32 inValue) { alSourcef(mSourceID, AL_PITCH, inValue); return alGetError(); } OSStatus SetLooping(Boolean inDoLoop) { ALint doLoop = inDoLoop ? 1 : 0; alSourcei(mSourceID, AL_LOOPING, doLoop); return alGetError(); } OSStatus SetPosition(Float32 inX, Float32 inY, Float32 inZ) { alSource3f(mSourceID, AL_POSITION, inX, inY, inZ); return alGetError(); } OSStatus SetMaxDistance(Float32 inValue) { alSourcef(mSourceID, AL_MAX_DISTANCE, inValue); return alGetError(); } OSStatus SetReferenceDistance(Float32 inValue) { alSourcef(mSourceID, AL_REFERENCE_DISTANCE, inValue); return alGetError(); } OSStatus SetLevel(Float32 inValue) { alSourcef(mSourceID, AL_GAIN, inValue * gMasterVolumeGain); return alGetError(); } bool IsPlaying() { ALint state; alGetSourcei(mSourceID, AL_SOURCE_STATE, &state); return state == AL_PLAYING; } // enum { // kPlayThreadState_Loop = 0, // kPlayThreadState_Decay = 1, // kPlayThreadState_End = 2 // }; private: ALuint mSourceID; // ALuint mAttackBufferID; ALuint mLoopBufferID; // ALuint mDecayBufferID; UInt32 mNumberBuffers; const char* mLoopFileData; int mLoopFileLen; // const char* mAttackFileData; // int mAttackFileLen; // const char* mDecayFileData; // int mDecayFileLen; void* mLoopData; // void* mAttackData; // void* mDecayData; UInt32 mLoopDataSize; // UInt32 mAttackDataSize; // UInt32 mDecayDataSize; Boolean mIsLoopingEffect; OpenALThread* mPlayThread; // UInt32 mPlayThreadState; }; #pragma mark ***** SoundEngineEffectMap ***** //================================================================================================== // SoundEngineEffectMap class //================================================================================================== class SoundEngineEffectMap //: std::multimap<UInt32, SoundEngineEffect*, std::less<ALuint> > { #define MAX_ELEMENTS 50 private: SoundEngineEffect* elements[MAX_ELEMENTS]; ALuint effectId[MAX_ELEMENTS]; UInt32 size; public: SoundEngineEffectMap() { for(int i=0;i<MAX_ELEMENTS; i++) { effectId[i] = 0; elements[i] = NULL; } size = 0; } ~SoundEngineEffectMap() { for(int i=0;i<MAX_ELEMENTS; i++) { if(elements[i] != NULL) delete elements[i]; elements[i] = NULL; } size = 0; } // add a new context to the map bool Add (const ALuint inEffectToken, SoundEngineEffect* inEffect) { if(size < MAX_ELEMENTS ) { for(int i=0;i<MAX_ELEMENTS; i++) { if(elements[i] == NULL) { elements[i] = inEffect; effectId[i] = inEffectToken; size++; return true; } } } //TRACE("CAN'T ADD EFFECT\n"); return false; } SoundEngineEffect* Get(ALuint inEffectToken) { for(int i=0; i<MAX_ELEMENTS; i++) { if(effectId[i] == inEffectToken) return elements[i]; } //TRACE("CAN'T GET EFFECT\n"); return (NULL); } void Remove(const ALuint inSourceToken) { for(int i=0; i<MAX_ELEMENTS; i++) { if(effectId[i] == inSourceToken) { delete elements[i]; elements[i] = NULL; effectId[i] = 0; size--; return; } } //TRACE("CAN'T REMOVE EFFECT %d\n", inSourceToken); } SoundEngineEffect* GetEffectByIndex(UInt32 inIndex) { int founds = 0; for(int i=0; i<MAX_ELEMENTS; i++) { if(elements[i] != NULL) { if(founds++ == inIndex) return elements[i]; } } //TRACE("CAN'T GET BY INDEX EFFECT %d\n", inIndex); return (NULL); } UInt32 Size () const { return size; } bool Empty () const { return size == 0; } void RemoveStoppedEffects() { ALenum state; for(int i=0; i<MAX_ELEMENTS; i++) { if(effectId[i] != 0) { alGetSourcei(effectId[i], AL_SOURCE_STATE, &state); if(state == AL_STOPPED) { //TRACE("RemoveStopedEffects\n"); delete elements[i]; elements[i] = NULL; effectId[i] = 0; size--; } } } } void StopAllEffects() { ALenum state; for(int i=0; i<MAX_ELEMENTS; i++) { if(effectId[i] != 0) { alGetSourcei(effectId[i], AL_SOURCE_STATE, &state); if(state != AL_STOPPED) { alSourceStop(effectId[i]); } } } } }; #pragma mark ***** OpenALObject ***** //================================================================================================== // OpenALObject class //================================================================================================== class OpenALObject { public: OpenALObject(Float32 inMixerOutputRate) : mOutputRate(inMixerOutputRate), mGain(1.0), mContext(NULL), mDevice(NULL), mEffectsMap(NULL) { mEffectsMap = new SoundEngineEffectMap(); } ~OpenALObject() { Teardown(); } OSStatus Initialize() { OSStatus result = noErr; mDevice = alcOpenDevice(NULL); AssertNoOALError("Error opening output device", end) if(mDevice == NULL) { return kSoundEngineErrDeviceNotFound; } // if a mixer output rate was specified, set it here // must be done before the alcCreateContext() call if (mOutputRate) alcMacOSXMixerOutputRateProc(mOutputRate); // Create an OpenAL Context mContext = alcCreateContext(mDevice, NULL); AssertNoOALError("Error creating OpenAL context", end) alcMakeContextCurrent(mContext); AssertNoOALError("Error setting current OpenAL context", end) end: return result; } void Teardown() { if (mEffectsMap) { delete mEffectsMap; mEffectsMap = NULL; } //restore context alcMakeContextCurrent(NULL); if(mContext)alcDestroyContext(mContext); mContext = NULL; if (mDevice) alcCloseDevice(mDevice); mDevice = NULL; } OSStatus SetListenerPosition(Float32 inX, Float32 inY, Float32 inZ) { alListener3f(AL_POSITION, inX, inY, inZ); return alGetError(); } OSStatus SetListenerGain(Float32 inValue) { alListenerf(AL_GAIN, inValue); return alGetError(); } OSStatus SetMaxDistance(Float32 inValue) { OSStatus result = 0; for (UInt32 i=0; i < mEffectsMap->Size(); i++) { SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i); if ((result = theEffect->SetMaxDistance(inValue)) != AL_NO_ERROR) return result; } return result; } OSStatus SetReferenceDistance(Float32 inValue) { OSStatus result = 0; for (UInt32 i=0; i < mEffectsMap->Size(); i++) { SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i); if ((result = theEffect->SetReferenceDistance(inValue)) != AL_NO_ERROR) return result; } return result; } OSStatus SetEffectsVolume(Float32 inValue) { OSStatus result = 0; for (UInt32 i=0; i < mEffectsMap->Size(); i++) { SoundEngineEffect *theEffect = mEffectsMap->GetEffectByIndex(i); if ((result = theEffect->SetLevel(inValue)) != AL_NO_ERROR) return result; } return result; } OSStatus UpdateGain() { return SetEffectsVolume(mGain); } OSStatus LoadEffect(char* data, unsigned long length, UInt32 *outEffectID) { SoundEngineEffect *theEffect = new SoundEngineEffect(data, length/*, NULL, NULL, false*/); OSStatus result = theEffect->AttachFilesToSource(); if (result == noErr) { *outEffectID = theEffect->GetEffectID(); mEffectsMap->Add(*outEffectID, theEffect); } return result; } // OSStatus LoadLoopingEffect(const char *inLoopFilePath, const char *inAttackFilePath, const char *inDecayFilePath, UInt32 *outEffectID) // { // SoundEngineEffect *theEffect = new SoundEngineEffect(inLoopFilePath, inAttackFilePath, inDecayFilePath, true); // OSStatus result = theEffect->AttachFilesToSource(); // if (result == noErr) // { // *outEffectID = theEffect->GetEffectID(); // mEffectsMap->Add(*outEffectID, &theEffect); // } // return result; // } OSStatus UnloadEffect(UInt32 inEffectID) { SoundEngineEffect* theEffect = mEffectsMap->Get(inEffectID); mEffectsMap->Remove(inEffectID); if(theEffect) delete theEffect; return 0; } OSStatus StartEffect(UInt32 inEffectID, Boolean loop) { SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID); return (theEffect) ? theEffect->Start(loop) : kSoundEngineErrInvalidID; } OSStatus PauseEffect(UInt32 inEffectID) { SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID); return (theEffect) ? theEffect->Pause() : kSoundEngineErrInvalidID; } OSStatus ResumeEffect(UInt32 inEffectID) { SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID); return (theEffect) ? theEffect->Resume() : kSoundEngineErrInvalidID; } OSStatus StopEffect(UInt32 inEffectID/*, Boolean inDoDecay*/) { SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID); return (theEffect) ? theEffect->Stop(/*inDoDecay*/) : kSoundEngineErrInvalidID; } bool IsEffectPlaying(UInt32 inEffectID) { SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID); return (theEffect) ? theEffect->IsPlaying() : false; } OSStatus SetEffectPitch(UInt32 inEffectID, Float32 inValue) { SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID); return (theEffect) ? theEffect->SetPitch(inValue) : kSoundEngineErrInvalidID; } OSStatus SetEffectVolume(UInt32 inEffectID, Float32 inValue) { SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID); return (theEffect) ? theEffect->SetLevel(inValue) : kSoundEngineErrInvalidID; } OSStatus SetEffectPosition(UInt32 inEffectID, Float32 inX, Float32 inY, Float32 inZ) { SoundEngineEffect *theEffect = mEffectsMap->Get(inEffectID); return (theEffect) ? theEffect->SetPosition(inX, inY, inZ) : kSoundEngineErrInvalidID; } void RemoveStoppedEffects() { if(mEffectsMap) mEffectsMap->RemoveStoppedEffects(); } private: Float32 mOutputRate; Float32 mGain; ALCcontext* mContext; ALCdevice* mDevice; SoundEngineEffectMap* mEffectsMap; }; #pragma mark ***** API ***** //================================================================================================== // Sound Engine //================================================================================================== extern "C" void SoundEngine_RemoveStoppedEffects() { if (sOpenALObject) sOpenALObject->RemoveStoppedEffects(); } extern "C" OSStatus SoundEngine_Initialize(Float32 inMixerOutputRate) { if (sOpenALObject) delete sOpenALObject; if (sBackgroundTrackMgr) delete sBackgroundTrackMgr; sOpenALObject = new OpenALObject(inMixerOutputRate); sBackgroundTrackMgr = new BackgroundTrackMgr(); return sOpenALObject->Initialize(); } extern "C" OSStatus SoundEngine_Teardown() { if (sOpenALObject) { delete sOpenALObject; sOpenALObject = NULL; } if (sBackgroundTrackMgr) { delete sBackgroundTrackMgr; sBackgroundTrackMgr = NULL; } return 0; } extern "C" OSStatus SoundEngine_SetMasterVolume(Float32 inValue) { OSStatus result = noErr; gMasterVolumeGain = inValue; if (sBackgroundTrackMgr) result = sBackgroundTrackMgr->UpdateGain(); if (result) return result; if (sOpenALObject) return sOpenALObject->UpdateGain(); return result; } extern "C" OSStatus SoundEngine_SetListenerPosition(Float32 inX, Float32 inY, Float32 inZ) { return (sOpenALObject) ? sOpenALObject->SetListenerPosition(inX, inY, inZ) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_SetListenerGain(Float32 inValue) { return (sOpenALObject) ? sOpenALObject->SetListenerGain(inValue) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_LoadBackgroundMusicTrack(const char* inPath, Boolean inAddToQueue, Boolean inLoadAtOnce) { if (sBackgroundTrackMgr == NULL) sBackgroundTrackMgr = new BackgroundTrackMgr(); return sBackgroundTrackMgr->LoadTrack(inPath, inAddToQueue, inLoadAtOnce); } extern "C" OSStatus SoundEngine_UnloadBackgroundMusicTrack() { if (sBackgroundTrackMgr) { delete sBackgroundTrackMgr; sBackgroundTrackMgr = NULL; } return 0; } extern "C" OSStatus SoundEngine_StartBackgroundMusic() { return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->Start() : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_StopBackgroundMusic(Boolean stopAtEnd) { return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->Stop(stopAtEnd) : kSoundEngineErrUnitialized; } extern "C" bool SoundEngine_IsMusicPlaying() { return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->IsPlaying() : false; } extern "C" OSStatus SoundEngine_SetBackgroundMusicVolume(Float32 inValue) { return (sBackgroundTrackMgr) ? sBackgroundTrackMgr->SetVolume(inValue) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_LoadEffect(char* data, unsigned long length, UInt32* outEffectID) { OSStatus result = noErr; if (sOpenALObject == NULL) { sOpenALObject = new OpenALObject(0.0); result = sOpenALObject->Initialize(); } return (result) ? result : sOpenALObject->LoadEffect(data, length, outEffectID); } //extern "C" //OSStatus SoundEngine_LoadLoopingEffect(const char* inLoopFilePath, /*const char* inAttackFilePath, const char* inDecayFilePath,*/ UInt32* outEffectID) //{ // OSStatus result = noErr; // if (sOpenALObject == NULL) // { // sOpenALObject = new OpenALObject(0.0); // result = sOpenALObject->Initialize(); // } // return (result) ? result : sOpenALObject->LoadLoopingEffect(inLoopFilePath, /*inAttackFilePath, inDecayFilePath,*/ outEffectID); //} extern "C" OSStatus SoundEngine_UnloadEffect(UInt32 inEffectID) { return (sOpenALObject) ? sOpenALObject->UnloadEffect(inEffectID) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_StartEffect(UInt32 inEffectID, Boolean loop) { return (sOpenALObject) ? sOpenALObject->StartEffect(inEffectID, loop) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_PauseEffect(UInt32 inEffectID) { return (sOpenALObject) ? sOpenALObject->PauseEffect(inEffectID) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_ResumeEffect(UInt32 inEffectID) { return (sOpenALObject) ? sOpenALObject->ResumeEffect(inEffectID) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_StopEffect(UInt32 inEffectID/*, Boolean inDoDecay*/) { return (sOpenALObject) ? sOpenALObject->StopEffect(inEffectID/*, inDoDecay*/) : kSoundEngineErrUnitialized; } extern "C" bool SoundEngine_IsEffectPlaying(UInt32 inEffectID) { return (sOpenALObject) ? sOpenALObject->IsEffectPlaying(inEffectID) : false; } extern "C" OSStatus SoundEngine_SetEffectPitch(UInt32 inEffectID, Float32 inValue) { return (sOpenALObject) ? sOpenALObject->SetEffectPitch(inEffectID, inValue) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_SetEffectLevel(UInt32 inEffectID, Float32 inValue) { return (sOpenALObject) ? sOpenALObject->SetEffectVolume(inEffectID, inValue) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_SetEffectPosition(UInt32 inEffectID, Float32 inX, Float32 inY, Float32 inZ) { return (sOpenALObject) ? sOpenALObject->SetEffectPosition(inEffectID, inX, inY, inZ) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_SetEffectsVolume(Float32 inValue) { return (sOpenALObject) ? sOpenALObject->SetEffectsVolume(inValue) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_SetMaxDistance(Float32 inValue) { return (sOpenALObject) ? sOpenALObject->SetMaxDistance(inValue) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_SetReferenceDistance(Float32 inValue) { return (sOpenALObject) ? sOpenALObject->SetReferenceDistance(inValue) : kSoundEngineErrUnitialized; } extern "C" OSStatus SoundEngine_Vibrate() { #if TARGET_OS_IPHONE AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); #endif } #endif
[ "jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae" ]
jakesoul@c957e3ca-5ece-11de-8832-3f4c773c73ae
680175a4670a5238c02069f83573e91258f24791
6d162c19c9f1dc1d03f330cad63d0dcde1df082d
/qrenderdoc/3rdparty/qt/include/QtGui/5.9.4/QtGui/qpa/qplatformtheme.h
2ba2f8669fff6940fffd2604fc77a5f57128f79e
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-or-later", "LGPL-3.0-only", "GPL-3.0-only", "Python-2.0", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-mit-old-style", "LGPL-2.1-or-later", "LGPL-2.1-only", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "bzip2-1.0.6", "Bison-exception-2.2", "MIT-open-group", "X11", "blessing", "BSD-3-Clause", "BSD-4.3TAHOE", "GPL-2.0-only", "LicenseRef-scancode-free-unknown", "IJG", "xlock", "HPND", "LicenseRef-scancode-xfree86-1.0", "LicenseRef-scancode-pcre", "Libpng", "FTL", "Zlib", "GPL-1.0-or-later", "libtiff", "LicenseRef-scancode-ietf", "LicenseRef-scancode-cavium-malloc", "LicenseRef-scancode-public-domain", "HPND-sell-variant", "ICU", "BSD-2-Clause", "LicenseRef-scancode-lcs-telegraphics", "dtoa", "LicenseRef-scancode-mit-veillard-variant", "LicenseRef-scancode-public-domain-disclaimer", "GFDL-1.1-or-later", "CC-BY-SA-4.0", "CC-BY-SA-3.0", "GFDL-1.3-or-later", "OpenSSL" ]
permissive
baldurk/renderdoc
24efbb84446a9d443bb9350013f3bfab9e9c5923
a214ffcaf38bf5319b2b23d3d014cf3772cda3c6
refs/heads/v1.x
2023-08-16T21:20:43.886587
2023-07-28T22:34:10
2023-08-15T09:09:40
17,253,131
7,729
1,358
MIT
2023-09-13T09:36:53
2014-02-27T15:16:30
C++
UTF-8
C++
false
false
9,392
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPLATFORMTHEME_H #define QPLATFORMTHEME_H // // W A R N I N G // ------------- // // This file is part of the QPA API and is not meant to be used // in applications. Usage of this API may make your code // source and binary incompatible with future versions of Qt. // #include <QtGui/qtguiglobal.h> #include <QtCore/QScopedPointer> #include <QtGui/QKeySequence> QT_BEGIN_NAMESPACE class QIcon; class QIconEngine; class QMenu; class QMenuBar; class QPlatformMenuItem; class QPlatformMenu; class QPlatformMenuBar; class QPlatformDialogHelper; class QPlatformSystemTrayIcon; class QPlatformThemePrivate; class QVariant; class QPalette; class QFont; class QPixmap; class QSizeF; class QFileInfo; class Q_GUI_EXPORT QPlatformTheme { Q_DECLARE_PRIVATE(QPlatformTheme) public: enum ThemeHint { CursorFlashTime, KeyboardInputInterval, MouseDoubleClickInterval, StartDragDistance, StartDragTime, KeyboardAutoRepeatRate, PasswordMaskDelay, StartDragVelocity, TextCursorWidth, DropShadow, MaximumScrollBarDragDistance, ToolButtonStyle, ToolBarIconSize, ItemViewActivateItemOnSingleClick, SystemIconThemeName, SystemIconFallbackThemeName, IconThemeSearchPaths, StyleNames, WindowAutoPlacement, DialogButtonBoxLayout, DialogButtonBoxButtonsHaveIcons, UseFullScreenForPopupMenu, KeyboardScheme, UiEffects, SpellCheckUnderlineStyle, #if QT_VERSION >= QT_VERSION_CHECK(6,0,0) TabFocusBehavior, #else TabAllWidgets, TabFocusBehavior = TabAllWidgets, #endif IconPixmapSizes, PasswordMaskCharacter, DialogSnapToDefaultButton, ContextMenuOnMouseRelease, MousePressAndHoldInterval, MouseDoubleClickDistance, WheelScrollLines, TouchDoubleTapDistance }; enum DialogType { FileDialog, ColorDialog, FontDialog, MessageDialog }; enum Palette { SystemPalette, ToolTipPalette, ToolButtonPalette, ButtonPalette, CheckBoxPalette, RadioButtonPalette, HeaderPalette, ComboBoxPalette, ItemViewPalette, MessageBoxLabelPelette, MessageBoxLabelPalette = MessageBoxLabelPelette, TabBarPalette, LabelPalette, GroupBoxPalette, MenuPalette, MenuBarPalette, TextEditPalette, TextLineEditPalette, NPalettes }; enum Font { SystemFont, MenuFont, MenuBarFont, MenuItemFont, MessageBoxFont, LabelFont, TipLabelFont, StatusBarFont, TitleBarFont, MdiSubWindowTitleFont, DockWidgetTitleFont, PushButtonFont, CheckBoxFont, RadioButtonFont, ToolButtonFont, ItemViewFont, ListViewFont, HeaderViewFont, ListBoxFont, ComboMenuItemFont, ComboLineEditFont, SmallFont, MiniFont, FixedFont, GroupBoxTitleFont, TabButtonFont, EditorFont, NFonts }; enum StandardPixmap { // Keep in sync with QStyle::StandardPixmap TitleBarMenuButton, TitleBarMinButton, TitleBarMaxButton, TitleBarCloseButton, TitleBarNormalButton, TitleBarShadeButton, TitleBarUnshadeButton, TitleBarContextHelpButton, DockWidgetCloseButton, MessageBoxInformation, MessageBoxWarning, MessageBoxCritical, MessageBoxQuestion, DesktopIcon, TrashIcon, ComputerIcon, DriveFDIcon, DriveHDIcon, DriveCDIcon, DriveDVDIcon, DriveNetIcon, DirOpenIcon, DirClosedIcon, DirLinkIcon, DirLinkOpenIcon, FileIcon, FileLinkIcon, ToolBarHorizontalExtensionButton, ToolBarVerticalExtensionButton, FileDialogStart, FileDialogEnd, FileDialogToParent, FileDialogNewFolder, FileDialogDetailedView, FileDialogInfoView, FileDialogContentsView, FileDialogListView, FileDialogBack, DirIcon, DialogOkButton, DialogCancelButton, DialogHelpButton, DialogOpenButton, DialogSaveButton, DialogCloseButton, DialogApplyButton, DialogResetButton, DialogDiscardButton, DialogYesButton, DialogNoButton, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, ArrowBack, ArrowForward, DirHomeIcon, CommandLink, VistaShield, BrowserReload, BrowserStop, MediaPlay, MediaStop, MediaPause, MediaSkipForward, MediaSkipBackward, MediaSeekForward, MediaSeekBackward, MediaVolume, MediaVolumeMuted, LineEditClearButton, // do not add any values below/greater than this CustomBase = 0xf0000000 }; enum KeyboardSchemes { WindowsKeyboardScheme, MacKeyboardScheme, X11KeyboardScheme, KdeKeyboardScheme, GnomeKeyboardScheme, CdeKeyboardScheme }; enum UiEffect { GeneralUiEffect = 0x1, AnimateMenuUiEffect = 0x2, FadeMenuUiEffect = 0x4, AnimateComboUiEffect = 0x8, AnimateTooltipUiEffect = 0x10, FadeTooltipUiEffect = 0x20, AnimateToolBoxUiEffect = 0x40, HoverEffect = 0x80 }; enum IconOption { DontUseCustomDirectoryIcons = 0x01 }; Q_DECLARE_FLAGS(IconOptions, IconOption) explicit QPlatformTheme(); virtual ~QPlatformTheme(); virtual QPlatformMenuItem* createPlatformMenuItem() const; virtual QPlatformMenu* createPlatformMenu() const; virtual QPlatformMenuBar* createPlatformMenuBar() const; virtual void showPlatformMenuBar() {} virtual bool usePlatformNativeDialog(DialogType type) const; virtual QPlatformDialogHelper *createPlatformDialogHelper(DialogType type) const; #ifndef QT_NO_SYSTEMTRAYICON virtual QPlatformSystemTrayIcon *createPlatformSystemTrayIcon() const; #endif virtual const QPalette *palette(Palette type = SystemPalette) const; virtual const QFont *font(Font type = SystemFont) const; virtual QVariant themeHint(ThemeHint hint) const; virtual QPixmap standardPixmap(StandardPixmap sp, const QSizeF &size) const; virtual QIcon fileIcon(const QFileInfo &fileInfo, QPlatformTheme::IconOptions iconOptions = 0) const; virtual QIconEngine *createIconEngine(const QString &iconName) const; #ifndef QT_NO_SHORTCUT virtual QList<QKeySequence> keyBindings(QKeySequence::StandardKey key) const; #endif virtual QString standardButtonText(int button) const; virtual QKeySequence standardButtonShortcut(int button) const; static QVariant defaultThemeHint(ThemeHint hint); static QString defaultStandardButtonText(int button); static QString removeMnemonics(const QString &original); protected: explicit QPlatformTheme(QPlatformThemePrivate *priv); QScopedPointer<QPlatformThemePrivate> d_ptr; private: Q_DISABLE_COPY(QPlatformTheme) }; QT_END_NAMESPACE #endif // QPLATFORMTHEME_H
701e6146f84c86b390aa173d7fb141dd8f0a559d
fe875ac27a841b0366bebbe4689c0cda0b062739
/week4_binary_search_trees/3_is_bst_advanced/try1.cpp
cbb71c0a5d74a17346c2856d7ec7e62b06e8b2af
[]
no_license
siddharth-patel-23/Data-Structures
08ae7a12816e1fc154b1bf28670863a88e2833aa
021d74c06e8daf37f6fddc930a1b1324c2a7a285
refs/heads/master
2022-04-21T10:21:57.490419
2020-04-24T13:32:30
2020-04-24T13:32:30
258,518,500
1
0
null
null
null
null
UTF-8
C++
false
false
1,538
cpp
#include <algorithm> #include <iostream> #include <vector> using std::cin; using std::cout; using std::endl; using std::vector; struct Node { int key; int left; int right; Node() : key(0), left(-1), right(-1) {} Node(int key_, int left_, int right_) : key(key_), left(left_), right(right_) {} }; vector<Node> tree; void inorder_traversal(vector<int> &result, int root) { if (root == -1) return; inorder_traversal(result, tree[root].left); result.push_back(root); inorder_traversal(result, tree[root].right); } vector <int> in_order(const vector<Node>& tree) { vector<int> result; // Finish the implementation // You may need to add a new recursive method to do that inorder_traversal(result, 0); return result; } bool IsBinarySearchTree(const vector<Node>& tree) { // Implement correct algorithm here if (tree.size() > 1) { vector <int> v = in_order(tree); for (int i = 0; i < v.size() - 1; i++) { if (tree[v[i + 1]].key < tree[v[i]].key) return false; if (tree[v[i]].key == tree[v[i + 1]].key && tree[v[i + 1]].left == v[i]) return false; } } return true; } int main() { int nodes; cin >> nodes; for (int i = 0; i < nodes; ++i) { int key, left, right; cin >> key >> left >> right; tree.push_back(Node(key, left, right)); } if (IsBinarySearchTree(tree)) { cout << "CORRECT" << endl; } else { cout << "INCORRECT" << endl; } return 0; }
4325afbf91dd3d87dd63bd75d7b70715e0772998
591b593934fa49b68432fade373eb8f9b50a7fc7
/src/LightedSceneVT.cpp
2af946e86df55d6b27377ba99071d12637877089
[]
no_license
janvybiral32/TiledShading
a5fb4c5ed93389dacecc668b3a83f2f6a7541449
4ce9aeda353028138ea710ebc065745db89ac589
refs/heads/master
2022-04-01T17:52:29.232991
2020-02-07T03:40:13
2020-02-07T03:40:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
189
cpp
#include <LightedSceneVT.h> void ts::LightedSceneVT::setLights(std::shared_ptr<std::vector<ge::sg::PointLight>> pointLights) { m_pointLights = pointLights; m_needToSetupLights = true; }
103881ff72d5d761971375cf82b35761621e648e
be1d17dd19e668f58c591ab229da16a9a1da1e40
/tools/vsimporter/xib2nib/UIRuntimeEventConnection.cpp
7fbb447c98ac4f3928a01904d2b22170224480eb
[ "MIT" ]
permissive
kod3r/WinObjC
35134fba421d3030edafb73ee2707b356f4c3cfa
2f6e6ecbb57e7cb6a065ad01fca09d7601a80c2f
refs/heads/master
2021-01-19T19:17:12.293513
2015-12-03T22:12:45
2015-12-03T22:12:45
47,420,494
1
0
null
2015-12-04T17:57:35
2015-12-04T17:57:35
null
UTF-8
C++
false
false
3,362
cpp
//****************************************************************************** // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //****************************************************************************** #include "UIRuntimeEventConnection.h" #include "UIControl.h" #include <assert.h> UIRuntimeEventConnection::UIRuntimeEventConnection() { _outputClassName = "UIRuntimeEventConnection"; _className = "UIRuntimeEventConnection"; _eventMask = -1; _label = NULL; } void UIRuntimeEventConnection::InitFromXIB(XIBObject *obj) { ObjectConverter::InitFromXIB(obj); _label = obj->GetString("label", NULL); _source = obj->FindMember("source"); _destination = obj->FindMember("destination"); _eventMask = -1; int type = obj->GetInt("IBEventType", -1); if ( type != -1 ) { _eventMask = (1 << (type - 1)); } obj->_outputClassName = "UIRuntimeEventConnection"; } void UIRuntimeEventConnection::InitFromStory(XIBObject *obj) { ObjectConverter::InitFromStory(obj); obj->_outputClassName = "UIRuntimeEventConnection"; // Find the destination we're to plug into const char *destId = getAttrib("destination"); if ( strcmp(obj->_className, "action") == 0 ) { _label = getAttrib("selector"); const char *type = getAttrib("eventType"); if ( type ) { if (strcmp(type, "touchUpInside") == 0) { _eventMask = UIControlEventTouchUpInside; } else if (strcmp(type, "touchDown") == 0) { _eventMask = UIControlEventTouchDown; } else if (strcmp(type, "valueChanged") == 0) { _eventMask = UIControlEventValueChanged; } else { printf("Unknown UIRuntimeEventConnection event type %s\n", type); } } } else { assert(0); } _source = _parent->_parent; ObjectConverter *destObj = (ObjectConverter *) findReference(destId); _destination = destObj; // Check if the destination property is part of our heirarchy XIBObject *curObj = this; while ( curObj ) { if ( curObj == destObj ) { destObj = (ObjectConverter *) _source; break; } curObj = curObj->_parent; } if ( !destObj->_connectedObjects ) destObj->_connectedObjects = new XIBArray(); destObj->_connectedObjects->AddMember(NULL, this); } void UIRuntimeEventConnection::ConvertStaticMappings(NIBWriter *writer, XIBObject *obj) { ObjectConverter::ConvertStaticMappings(writer, obj); if ( _label ) AddString(writer, "UILabel", _label); AddOutputMember(writer, "UISource", _source); AddOutputMember(writer, "UIDestination", _destination); if ( _eventMask != -1 ) AddInt(writer, "UIEventMask", _eventMask); }
d5269b44e72fbc310b996cd4ffeaa64036a09059
c13ddb30df19359185b1257fb076c4c0a1d0b340
/LAB2_EX3.cpp
697024174f5ce5abbd943144968c112990b44e78
[]
no_license
nhphuong2504/nguyenhoangphuong17es_hw
78bfadc44c47460e25e9900121bb7c5d35332439
f29cd70cc7b446ace2c453826fe120a158bf7e8a
refs/heads/master
2020-08-04T03:53:00.651756
2019-10-01T03:38:41
2019-10-01T03:38:41
211,993,567
0
0
null
null
null
null
UTF-8
C++
false
false
2,707
cpp
#include <iostream> #include <conio.h> using namespace std; class Vector { private: int n; float *data; public: Vector(){ cout << "Enter the size of vector: "; cin >> n; data = new float[n]; for (int i=0; i<n; i++){ cout << "Enter the " << i+1 << "element of vector: "; cin >> data[i]; } } Vector(float *a, int n){ this->n = n; data = new float[n]; for(int i=0; i<n; i++){ data[i] = *(a+i); } } ~Vector(){ delete[] data; } int capacity(){ return n; } void clear(){ delete[] data; n=0; } bool contains(float elem){ for (int i=0; i<n; i++){ if (data[i] == elem) return true; else return false; } } int indexOf(float elem){ for(int i=0; i<n; i++) if (data[i] == elem) return i+1; return 0; } int lastIndexOf(float elem){ for (int i = n-1; i >=0; i--) if (data[i] == elem) return i+1; return 0; } float elementAt(int index){ return data[index-1]; } bool isEmpty(){ if(n == 0) return true; else return false; } int toArray(float *d){ for (int i = 0; i < n; i++){ *(d+i) = data[i]; } return n; } void display(){ for (int i = 0; i < n; i++) cout << data[i] << " "; cout << endl; } }; int main() { float a[]={1,4,5,4,1}; float d[]={}; Vector c(a, 5); Vector b; cout << "Capacity of b: " << b.capacity() << endl; cout << "Does b contain 15? : " << b.contains(15) << endl << "Does b contain 3? : " << b.contains(3) << endl; cout << "Index position of 3: " << b.indexOf(3) << endl << "Index position of 15: " << b.indexOf(15) << endl; cout << "Last Index position of 3: " << b.lastIndexOf(3) << endl << "Last Index position of 15: " << b.lastIndexOf(15) << endl; cout << "Element at position 1 is: " << b.elementAt(1) << endl; cout << "Vector b: "; b.display(); cout << "Put elements from vector b to array d." << endl; int n = b.toArray(d); //return the size of vector b cout << "Vector d: "; for (int i = 0; i < n; i++){ cout << d[i] << " "; } cout << endl; b.clear(); cout << "b was cleared." << endl; cout << "Capacity of b: " << b.capacity() << endl; cout << "Is b empty? : " << b.isEmpty() << endl << "Is c empty? : " << c.isEmpty() << endl; }
afb2a36f14a316f940cec0b87e9389bcd6438e05
bcddc28628daa3dd1904077bb3307759e7bc732a
/Number of Islands II.cpp
c49c9d474b5593e515abea0ee3ee432e2fd1bd59
[]
no_license
Funsom/Leetcode
985304fda728cd13a9e16d8d73563f1cacb9a5b0
c613acb1fed2021f03faa74a73bb8df0d1874e60
refs/heads/master
2020-03-19T02:44:32.641984
2017-03-24T19:45:15
2017-03-24T19:45:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,107
cpp
class Solution { public: vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) { vector<int>res; if(!m||!n)return res; vector<int>roots(m*n,-1); vector<vector<int>>dir{{-1,0},{1,0},{0,-1},{0,1}}; int cnt=0; for(pair<int,int> &p:positions){ int x=p.first,y=p.second; int id=x*n+y; roots[id]=id; cnt++; for(int k=0;k<4;k++){ int i=x+dir[k][0],j=y+dir[k][1]; int nid=i*n+j; if(i<0||i>=m||j<0||j>=n||roots[nid]==-1)continue; int rootn=findRoot(roots,nid); if(id!=rootn){ roots[id]=rootn; id=rootn; cnt--; } } res.push_back(cnt); } return res; } int findRoot(vector<int>&roots, int id){ while(roots[id]!=id){ roots[id]=roots[roots[id]]; id=roots[id]; } return id; } };
dff28a790ec6f6057ee38bd1aa42c9382e8bf9cb
a280197e538a92b582a26cd255ed8fe91c791e50
/SPOJ/spoj_20847_STUDID.cpp
f2d4ee99d7ef92082edf5a92a71cb9c2f787b272
[]
no_license
MysticSoul/CCplusplus-Project
908d2a3cbda34658487b8d64b0a3be99cf9323a0
da7936d6686e7d5251b8b6cdfe0fa85502e51f54
refs/heads/master
2020-07-25T21:11:42.324013
2018-07-17T04:02:36
2018-07-17T04:02:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,034
cpp
/* * * Tag: Data Structure * Time: O(n) * Space: O(n) */ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <climits> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <list> #include <unordered_map> #include <unordered_set> #include <map> #include <set> using namespace std; const int N = 210002; const int M = 300; const long long MOD = 495; const double PI = acos(-1.0); const double eps = 1e-10; const int MAX_VAL = 800*1000; char nm[M]; int vcnt, len; int main(){ int T; scanf("%d",&T); while (T --) { vcnt = 0; scanf("%s",nm); for (int i = 0; nm[i]; ++ i) { if (nm[i] == 'a' || nm[i] == 'e' || nm[i] == 'i' || nm[i] == 'o' || nm[i] == 'u') { ++ vcnt; } } puts(nm); len = strlen(nm); if (vcnt > len - vcnt) { puts("1"); } else { puts("0"); } } return 0; }
dfffd6c6f60cc1f96c42123a60d1b8244ad797a8
02bd50b1fa744bb3642fbaa57a84152ff3cbb2b9
/src/fibonacci.h
5838e9b0d4516f71674b91a14399a48120062a8c
[]
no_license
Kalteplatte/Algorithm-Engineering
6ece1a33e1aac971b0a26cba0f777aeadbbf8419
3ce2221b60fa884aeb5b31a2f4f77aa4ccb0433c
refs/heads/master
2016-09-06T13:43:23.211612
2015-02-10T11:17:40
2015-02-10T11:17:40
26,548,117
0
0
null
null
null
null
UTF-8
C++
false
false
396
h
#ifndef FIBONACCI_H #define FIBONACCI_H #include <vector> #include <stdio.h> #include <math.h> #include <iostream> using namespace std; unsigned long Fibonacci1 (int); unsigned long Fibonacci2 (int); unsigned long Fibonacci3 (int); unsigned long Fibonacci4(int); unsigned long Fibonacci41(int); unsigned long Fibonacci5(int); unsigned long Fibonacci6(int); #endif
85f101a3dae6ef5556019c3e4bea3fa03ec59ecf
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_399_collectd-5.6.1.cpp
9d535c7d9bf226c13d76973b1985adbc09358a60
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
483
cpp
static int battery_config (oconfig_item_t *ci) { for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *child = ci->children + i; if (strcasecmp ("ValuesPercentage", child->key) == 0) cf_util_get_boolean (child, &report_percent); else if (strcasecmp ("ReportDegraded", child->key) == 0) cf_util_get_boolean (child, &report_degraded); else WARNING ("battery plugin: Ignoring unknown " "configuration option \"%s\".", child->key); } return (0); }
f0c5c2d1305660f33d7a6d0634d1b88c05bafd73
759c549761cf39736bc071bb8235412b10f91452
/src/RootTreeOutput.cxx
239f5a0e6c0322b356769e5f89de7171e7b182d7
[ "MIT" ]
permissive
williamhbell/LeCroyScopeDAQ
c9b762d36706214cd736cb6018b8fe0c83e3aae5
a4c3a5d75055749fc3e0b0fc85f3e4ba65644fbc
refs/heads/master
2016-09-05T10:05:52.266569
2015-01-01T21:33:55
2015-01-01T21:33:55
28,694,923
0
0
null
null
null
null
UTF-8
C++
false
false
10,363
cxx
#include "RootTreeOutput.h" #include "LeCroyDsoTrace.h" #include <iostream> #include <cstring> RootTreeOutput::RootTreeOutput(): m_outputFile(0), m_tree(0) { } //-------------------------------------------------------------------- RootTreeOutput::~RootTreeOutput() { } //-------------------------------------------------------------------- int RootTreeOutput::initialize(std::string fileName) { // Open the output root file. if (!m_outputFile) { m_outputFile = TFile::Open(fileName.c_str(),"RECREATE"); if (!m_outputFile) { std::cerr << "Error: Output histogram file " << fileName << " could not be opened!" << std::endl; return 1; } } else { std::cerr << "Error: Output root file has already been opened!" << std::endl; return 2; } // Create the TTree objects. m_tree = new TTree("scopeTraces","LeCroy X-Stream Scope Traces"); // Add the trace information m_tree->Branch("triggerNumber",&m_triggerNumber,"triggerNumber/i"); m_tree->Branch("descriptorName",m_descriptorName,"descriptorName[100]/C"); m_tree->Branch("templateName",m_templateName,"templateName[100]/C"); m_tree->Branch("commType",&m_commType,"commType/b"); m_tree->Branch("commOrder",&m_commOrder,"commOrder/b"); m_tree->Branch("waveDescriptorLength",&m_waveDescriptorLength,"waveDescriptorLength/I"); m_tree->Branch("userTextLength",&m_userTextLength,"userTextLength/I"); m_tree->Branch("resDesc1",&m_resDesc1,"resDesc1/I"); m_tree->Branch("triggerTimeArrayLength",&m_triggerTimeArrayLength,"triggerTimeArrayLength/I"); m_tree->Branch("riseTimeArrayLength",&m_riseTimeArrayLength,"riseTimeArrayLength/I"); m_tree->Branch("resArray1Length",&m_resArray1Length,"resArray1Length/I"); m_tree->Branch("waveArray1Length",&m_waveArray1Length,"waveArray1Length/I"); m_tree->Branch("waveArray2Length",&m_waveArray2Length,"waveArray2Length/I"); m_tree->Branch("resArray2Length",&m_resArray2Length,"resArray2Length/I"); m_tree->Branch("resArray3Length",&m_resArray3Length,"resArray3Length/I"); m_tree->Branch("instrumentName",m_instrumentName,"instrumentName[100]/C"); m_tree->Branch("instrumentNumber",&m_instrumentNumber,"instrumentNumber/I"); m_tree->Branch("traceLabel",m_traceLabel,"traceLabel[100]/C"); m_tree->Branch("reserved1",&m_reserved1,"reserved1/S"); m_tree->Branch("reserved2",&m_reserved2,"reserved2/S"); m_tree->Branch("waveArrayCount",&m_waveArrayCount,"waveArrayCount/I"); m_tree->Branch("pointsPerScreen",&m_pointsPerScreen,"pointsPerScreen/I"); m_tree->Branch("firstValidPoint",&m_firstValidPoint,"firstValidPoint/I"); m_tree->Branch("lastValidPoint",&m_lastValidPoint,"lastValidPoint/I"); m_tree->Branch("firstPoint",&m_firstPoint,"firstPoint/I"); m_tree->Branch("sparsingFactor",&m_sparsingFactor,"sparsingFactor/I"); m_tree->Branch("segmentIndex",&m_segmentIndex,"segmentIndex/I"); m_tree->Branch("subArrayCount",&m_subArrayCount,"subArrayCount/I"); m_tree->Branch("sweepsPerAcq",&m_sweepsPerAcq,"sweepsPerAcq/I"); m_tree->Branch("pointsPerPair",&m_pointsPerPair,"pointsPerPair/S"); m_tree->Branch("pairOffset",&m_pairOffset,"pairOffset/S"); m_tree->Branch("verticalGain",&m_verticalGain,"verticalGain/F"); m_tree->Branch("verticalOffset",&m_verticalOffset,"verticalOffset/F"); m_tree->Branch("maxValue",&m_maxValue,"maxValue/F"); m_tree->Branch("minValue",&m_minValue,"minValue/F"); m_tree->Branch("nominalBits",&m_nominalBits,"nominalBits/S"); m_tree->Branch("nominalSubArrayCount",&m_nominalSubArrayCount,"nominalSubArrayCount/S"); m_tree->Branch("horizontalInterval",&m_horizontalInterval,"horizontalInterval/F"); m_tree->Branch("horizontalOffset",&m_horizontalOffset,"horizontalOffset/D"); m_tree->Branch("pixelOffset",&m_pixelOffset,"pixelOffset/D"); m_tree->Branch("verticalUnit",m_verticalUnit,"verticalUnit[100]/C"); m_tree->Branch("horizontalUnit",m_horizontalUnit,"horizontalUnit[100]/C"); m_tree->Branch("horizontalUncertainty",&m_horizontalUncertainty,"horizontalUncertainty/F"); m_tree->Branch("triggerSeconds",&m_triggerSeconds,"triggerSeconds/D"); m_tree->Branch("triggerMinutes",&m_triggerMinutes,"triggerMinutes/s"); m_tree->Branch("triggerHours",&m_triggerHours,"triggerHours/s"); m_tree->Branch("triggerDays",&m_triggerDays,"triggerDays/s"); m_tree->Branch("triggerMonths",&m_triggerMonths,"triggerMonths/s"); m_tree->Branch("triggerYears",&m_triggerYears,"triggerYears/i"); m_tree->Branch("acquisitionDuration",&m_acquisitionDuration,"acquisitionDuration/F"); m_tree->Branch("recordType",&m_recordType,"recordType/b"); m_tree->Branch("processingDone",&m_processingDone,"processingDone/b"); m_tree->Branch("reserved5",&m_reserved5,"reserved5/S"); m_tree->Branch("risSweeps",&m_risSweeps,"risSweeps/S"); m_tree->Branch("timeBase",&m_timeBase,"timeBase/b"); m_tree->Branch("verticalCoupling",&m_verticalCoupling,"verticalCoupling/b"); m_tree->Branch("probeAttenuation",&m_probeAttenuation,"probeAttenuation/F"); m_tree->Branch("fixedVerticalGain",&m_fixedVerticalGain,"fixedVerticalGain/b"); m_tree->Branch("bandwidthLimit",&m_bandwidthLimit,"bandwidthLimit/b"); m_tree->Branch("verticalVernier",&m_verticalVernier,"verticalVernier/F"); m_tree->Branch("acqVerticalOffset",&m_acqVerticalOffset,"acqVerticalOffset/F"); m_tree->Branch("waveSource",&m_waveSource,"waveSource/b"); m_tree->Branch("trigTimeArrayCount", &m_trigTimeArrayCount, "trigTimeArrayCount/I"); m_tree->Branch("trigTimeArray", m_trigTimeArray, "trigTimeArray[trigTimeArrayCount]/D"); m_tree->Branch("trigOffsetArray", m_trigOffsetArray, "trigOffsetArray[trigTimeArrayCount]/D"); m_tree->Branch("rawDataArray", m_rawDataArray, "rawDataArray[waveArrayCount]/I"); return 0; } //-------------------------------------------------------------------- int RootTreeOutput::saveTrace(LeCroyDsoTrace* trace) { int index, max_index; // Check for null pointer if(trace == 0) { std::cerr << "Error null trace pointer found" << std::endl; return 1; } m_triggerNumber = trace->triggerNumber; strcpy(m_descriptorName, trace->descriptorName.c_str()); strcpy(m_templateName, trace->templateName.c_str()); m_commType = trace->commType; m_commOrder = trace->commOrder; m_waveDescriptorLength = trace->waveDescriptorLength; m_userTextLength = trace->userTextLength; m_resDesc1 = trace->resDesc1; m_triggerTimeArrayLength = trace->triggerTimeArrayLength; m_riseTimeArrayLength = trace->riseTimeArrayLength; m_resArray1Length = trace->resArray1Length; m_waveArray1Length = trace->waveArray1Length; m_waveArray2Length = trace->waveArray2Length; m_resArray2Length = trace->resArray2Length; m_resArray3Length = trace->resArray3Length; strcpy(m_instrumentName, trace->instrumentName.c_str()); m_instrumentNumber = trace->instrumentNumber; strcpy(m_traceLabel, trace->traceLabel.c_str()); m_reserved1 = trace->reserved1; m_reserved2 = trace->reserved2; m_waveArrayCount = trace->waveArrayCount; m_pointsPerScreen = trace->pointsPerScreen; m_firstValidPoint = trace->firstValidPoint; m_lastValidPoint = trace->lastValidPoint; m_firstPoint = trace->firstPoint; m_sparsingFactor = trace->sparsingFactor; m_segmentIndex = trace->segmentIndex; m_subArrayCount = trace->subArrayCount; m_sweepsPerAcq = trace->sweepsPerAcq; m_pointsPerPair = trace->pointsPerPair; m_pairOffset = trace->pairOffset; m_verticalGain = trace->verticalGain; m_verticalOffset = trace->verticalOffset; m_maxValue = trace->maxValue; m_minValue = trace->minValue; m_nominalBits = trace->nominalBits; m_nominalSubArrayCount = trace->nominalSubArrayCount; m_horizontalInterval = trace->horizontalInterval; m_horizontalOffset = trace->horizontalOffset; m_pixelOffset = trace->pixelOffset; strcpy(m_verticalUnit, trace->verticalUnit.c_str()); strcpy(m_horizontalUnit, trace->horizontalUnit.c_str()); m_horizontalUncertainty = trace->horizontalUncertainty; // TriggerTime time in Root form. m_triggerSeconds = trace->triggerTime.seconds; m_triggerMinutes = trace->triggerTime.minutes; m_triggerHours = trace->triggerTime.hours; m_triggerDays = trace->triggerTime.days; m_triggerMonths = trace->triggerTime.months; m_triggerYears = trace->triggerTime.years; m_acquisitionDuration = trace->acquisitionDuration; m_recordType = trace->recordType; m_processingDone = trace->processingDone; m_reserved5 = trace->reserved5; m_risSweeps = trace->risSweeps; m_timeBase = trace->timeBase; m_verticalCoupling = trace->verticalCoupling; m_probeAttenuation = trace->probeAttenuation; m_fixedVerticalGain = trace->fixedVerticalGain; m_bandwidthLimit = trace->bandwidthLimit; m_verticalVernier = trace->verticalVernier; m_acqVerticalOffset = trace->acqVerticalOffset; m_waveSource = trace->waveSource; // Trigger Time array // Check the array size. max_index = trace->trigTimeArray.size(); if(m_trigTimeArray_size < max_index) { max_index = m_trigTimeArray_size; std::cerr << "Warning: truncating the trig time array to fit into the Root array" << std::endl; } m_trigTimeArrayCount = max_index; // Copy the values for(index = 0; index < max_index; index++) { m_trigTimeArray[index] = trace->trigTimeArray[index]; } // Fill the rest of the array with 0. for(; index < m_trigTimeArray_size; index++) { m_trigTimeArray[index] = 0; } // Raw data array. // Check the array size. max_index = trace->rawDataArray.size(); if(m_rawDataArray_size < max_index) { max_index = m_rawDataArray_size; std::cerr << "Warning: truncating the data to fit into the Root array" << std::endl; } // Copy the values for(index = 0; index < max_index; index++) { m_rawDataArray[index] = trace->rawDataArray[index]; } // Fill the rest of the array with 0. for(; index < m_rawDataArray_size; index++) { m_rawDataArray[index] = 0; } // Write the data into the TTree m_tree->Fill(); return 0; } //-------------------------------------------------------------------- int RootTreeOutput::finalize() { std::cout << "finalize" << std::endl; m_outputFile->Write(); m_outputFile->Close(); m_outputFile = 0; // delete does not work with Root TFile return 0; } //--------------------------------------------------------------------
44c184a6d536f025827412afa8929998a90ab1c2
8e936649b44c43c9595d668ee29a151a6d8ed7fb
/引擎源程序2.7C/MusicBox.h
5fce23d513ebe4e36cade04696ee862e8d4ecc7e
[]
no_license
flyfei00/GamePainter
78d105f72e31fcf53fb64902ff291be307314b72
a10b2626f323d0bf709953259c5ae43a408822c3
refs/heads/master
2023-06-11T14:37:53.740505
2021-06-10T05:32:05
2021-06-10T05:32:05
null
0
0
null
null
null
null
GB18030
C++
false
false
479
h
/* 程序开源,请勿用于商业开发 怎么去拥有一道彩虹,怎么去拥抱一夏天的风 大夏天2015冬 */ #include "stdafx.h" #pragma once #define MAX_MUSIC 32 class MusicBox { public: MusicBox(void); ~MusicBox(void); private: int m_ID[MAX_MUSIC]; int m_nID; MCI_PLAY_PARMS mciPlay; MCI_OPEN_PARMS mciOpen; public: int addMusic(CString str); void play(int ID); void pause(int ID); void stop(int ID); void resume(int ID); void del(int ID); };
3a7347d5627a6a495b397141975ae422e50ce97e
17872885a8a71ef3d57998437c4155cb7cd36dee
/player/ultraPlayer/DisplayDevicesInfoResponse.cpp
026b7e3753b16b94f7c8d00f8bad48a546555b5f
[]
no_license
odyodyodys/ultraplayer
edcbc1efd83ac5bf53b4caacfd96dbb8027bb086
18b09339045ffa8b316771360e2fab1d22890806
refs/heads/master
2021-01-20T13:55:13.478696
2017-02-21T19:28:46
2017-02-21T19:28:46
82,717,972
0
0
null
null
null
null
UTF-8
C++
false
false
1,245
cpp
#include "DisplayDevicesInfoResponse.h" DisplayDevicesInfoResponse::DisplayDevicesInfoResponse(void):AResponse(MessageType::DisplayDevicesInfo) { } DisplayDevicesInfoResponse::~DisplayDevicesInfoResponse(void) { } std::string DisplayDevicesInfoResponse::ToString() { string response; try { response += AResponse::ToString(); list<DisplayDevice*>::iterator deviceIterator; for (deviceIterator = _devices.begin(); deviceIterator != _devices.end(); deviceIterator++) { response += NumericToStringConverter::Convert<UINT>((*deviceIterator)->MonitorNumber(), std::dec, CommunicationProtocol::Instance()->NumericParameterLength()); response += (*deviceIterator)->MonitorLayout()->ToString(); } } catch (exception& e) { } return response; } void DisplayDevicesInfoResponse::Devices( list<DisplayDevice*> devices ) { try { // clean devices list if not empty if (!_devices.empty()) { list<DisplayDevice*>::iterator deviceIterator; list<DisplayDevice*> tmpList = _devices; for (deviceIterator = tmpList.begin(); deviceIterator != tmpList.end(); deviceIterator++) { if (*deviceIterator) { delete (*deviceIterator); } } } _devices = devices; } catch (exception& e) { } }
cabd2bf484c3d302fe8150b90855bb4acf24f3db
810edea964dbef93cd47fa61f50efbf41528be7e
/university/usc_ee450_computer_networks/cuservermain.cc
c48fccb9b5a0ce8f63db212632a93bdf3c5e2d9b
[ "MIT" ]
permissive
sanjnair/projects
2cee6e3c5f34d348067a34dc4be7535bc3b050df
9d7fce9a9d219b7e63a06bb57d16f23e20eb4dc3
refs/heads/master
2021-01-20T00:09:05.448898
2017-04-27T07:33:06
2017-04-27T07:33:06
89,086,374
0
0
null
null
null
null
UTF-8
C++
false
false
1,115
cc
#include "cexception.h" #include "cutil.h" #include "cuserver.h" void printUsage() { string msg("Usage: userver id\nId must be either 1 or 2"); CUtil::writeOutputLn(msg); } /*! Program's main function. */ int main(int argc, char *argv[]) { int status = 0; if (argc != 2) { printUsage(); status = -1; } int id = 0; if (0 == status) { try { id = CUtil::getUInt(string(argv[1])); } catch (CException &e) { CUtil::writeError(e.toString()); printUsage(); status = -1; } } if (0 == status) { if ((id != 1) && (id != 2)) { CUtil::writeError("Invalid Server Id entered"); printUsage(); status = -1; } } if (0 == status) { CUServer s(id); try { s.start(); } catch (CException &e) { string msg(e.getMessage()); msg += "\n\nExiting the application.\n"; CUtil::writeError(msg); status = -1; } } return status; }
9e97fb89faa800880dd5126333c80c5269d25abb
4537d194684865b0779f5172f0066cca94ba3322
/3rdparty/qt/include/QtCore/5.7.1/QtCore/private/qmetaobject_p.h
7f0beb311cb51b404e2daec669067a58a6b99cdf
[]
no_license
sukai33/AuboDriver
2efeaa8437b4e39c24dacaad71227f6376d85fb4
0f5a652b4df30ff7bfe485c6a388c4d4f0586414
refs/heads/master
2022-12-16T15:06:09.242749
2020-09-26T12:47:57
2020-09-26T12:47:57
298,804,925
1
1
null
null
null
null
UTF-8
C++
false
false
9,571
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Copyright (C) 2014 Olivier Goffart <[email protected]> ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QMETAOBJECT_P_H #define QMETAOBJECT_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists for the convenience // of moc. This header file may change from version to version without notice, // or even be removed. // // We mean it. // #include <QtCore/qglobal.h> #include <QtCore/qobjectdefs.h> #ifndef QT_NO_QOBJECT #include <private/qobject_p.h> // For QObjectPrivate::Connection #endif #include <QtCore/qvarlengtharray.h> QT_BEGIN_NAMESPACE enum PropertyFlags { Invalid = 0x00000000, Readable = 0x00000001, Writable = 0x00000002, Resettable = 0x00000004, EnumOrFlag = 0x00000008, StdCppSet = 0x00000100, // Override = 0x00000200, Constant = 0x00000400, Final = 0x00000800, Designable = 0x00001000, ResolveDesignable = 0x00002000, Scriptable = 0x00004000, ResolveScriptable = 0x00008000, Stored = 0x00010000, ResolveStored = 0x00020000, Editable = 0x00040000, ResolveEditable = 0x00080000, User = 0x00100000, ResolveUser = 0x00200000, Notify = 0x00400000, Revisioned = 0x00800000 }; enum MethodFlags { AccessPrivate = 0x00, AccessProtected = 0x01, AccessPublic = 0x02, AccessMask = 0x03, //mask MethodMethod = 0x00, MethodSignal = 0x04, MethodSlot = 0x08, MethodConstructor = 0x0c, MethodTypeMask = 0x0c, MethodCompatibility = 0x10, MethodCloned = 0x20, MethodScriptable = 0x40, MethodRevisioned = 0x80 }; enum MetaObjectFlags { DynamicMetaObject = 0x01, RequiresVariantMetaObject = 0x02, PropertyAccessInStaticMetaCall = 0x04 // since Qt 5.5, property code is in the static metacall }; enum MetaDataFlags { IsUnresolvedType = 0x80000000, TypeNameIndexMask = 0x7FFFFFFF }; extern int qMetaTypeTypeInternal(const char *); class QArgumentType { public: QArgumentType(int type) : _type(type) {} QArgumentType(const QByteArray &name) : _type(qMetaTypeTypeInternal(name.constData())), _name(name) {} QArgumentType() : _type(0) {} int type() const { return _type; } QByteArray name() const { if (_type && _name.isEmpty()) const_cast<QArgumentType *>(this)->_name = QMetaType::typeName(_type); return _name; } bool operator==(const QArgumentType &other) const { if (_type) return _type == other._type; else if (other._type) return false; else return _name == other._name; } bool operator!=(const QArgumentType &other) const { if (_type) return _type != other._type; else if (other._type) return true; else return _name != other._name; } private: int _type; QByteArray _name; }; Q_DECLARE_TYPEINFO(QArgumentType, Q_MOVABLE_TYPE); typedef QVarLengthArray<QArgumentType, 10> QArgumentTypeArray; class QMetaMethodPrivate; class QMutex; struct QMetaObjectPrivate { enum { OutputRevision = 7 }; // Used by moc, qmetaobjectbuilder and qdbus int revision; int className; int classInfoCount, classInfoData; int methodCount, methodData; int propertyCount, propertyData; int enumeratorCount, enumeratorData; int constructorCount, constructorData; //since revision 2 int flags; //since revision 3 int signalCount; //since revision 4 // revision 5 introduces changes in normalized signatures, no new members // revision 6 added qt_static_metacall as a member of each Q_OBJECT and inside QMetaObject itself // revision 7 is Qt 5 static inline const QMetaObjectPrivate *get(const QMetaObject *metaobject) { return reinterpret_cast<const QMetaObjectPrivate*>(metaobject->d.data); } static int originalClone(const QMetaObject *obj, int local_method_index); static QByteArray decodeMethodSignature(const char *signature, QArgumentTypeArray &types); static int indexOfSignalRelative(const QMetaObject **baseObject, const QByteArray &name, int argc, const QArgumentType *types); static int indexOfSlotRelative(const QMetaObject **m, const QByteArray &name, int argc, const QArgumentType *types); static int indexOfSignal(const QMetaObject *m, const QByteArray &name, int argc, const QArgumentType *types); static int indexOfSlot(const QMetaObject *m, const QByteArray &name, int argc, const QArgumentType *types); static int indexOfMethod(const QMetaObject *m, const QByteArray &name, int argc, const QArgumentType *types); static int indexOfConstructor(const QMetaObject *m, const QByteArray &name, int argc, const QArgumentType *types); Q_CORE_EXPORT static QMetaMethod signal(const QMetaObject *m, int signal_index); Q_CORE_EXPORT static int signalOffset(const QMetaObject *m); Q_CORE_EXPORT static int absoluteSignalCount(const QMetaObject *m); Q_CORE_EXPORT static int signalIndex(const QMetaMethod &m); static bool checkConnectArgs(int signalArgc, const QArgumentType *signalTypes, int methodArgc, const QArgumentType *methodTypes); static bool checkConnectArgs(const QMetaMethodPrivate *signal, const QMetaMethodPrivate *method); static QList<QByteArray> parameterTypeNamesFromSignature(const char *signature); #ifndef QT_NO_QOBJECT //defined in qobject.cpp enum DisconnectType { DisconnectAll, DisconnectOne }; static void memberIndexes(const QObject *obj, const QMetaMethod &member, int *signalIndex, int *methodIndex); static QObjectPrivate::Connection *connect(const QObject *sender, int signal_index, const QMetaObject *smeta, const QObject *receiver, int method_index_relative, const QMetaObject *rmeta = 0, int type = 0, int *types = 0); static bool disconnect(const QObject *sender, int signal_index, const QMetaObject *smeta, const QObject *receiver, int method_index, void **slot, DisconnectType = DisconnectAll); static inline bool disconnectHelper(QObjectPrivate::Connection *c, const QObject *receiver, int method_index, void **slot, QMutex *senderMutex, DisconnectType = DisconnectAll); #endif }; // For meta-object generators enum { MetaObjectPrivateFieldCount = sizeof(QMetaObjectPrivate) / sizeof(int) }; #ifndef UTILS_H // mirrored in moc's aubo.h static inline bool is_ident_char(char s) { return ((s >= 'a' && s <= 'z') || (s >= 'A' && s <= 'Z') || (s >= '0' && s <= '9') || s == '_' ); } static inline bool is_space(char s) { return (s == ' ' || s == '\t'); } #endif /* This function is shared with moc.cpp. The implementation lives in qmetaobject_moc_p.h, which should be included where needed. The declaration here is not used to avoid warnings from the compiler about unused functions. static QByteArray normalizeTypeInternal(const char *t, const char *e, bool fixScope = false, bool adjustConst = true); */ QT_END_NAMESPACE #endif
b2e3bd488c26e9d0c6d62849c6ca95a3fe4fc840
1f8360d8a94869b7074d47458626d8b65509a153
/CodeForces/WeightsDivisionEasy/solution.cpp
a6ea52678a43010fd31b8a1fc7a5139ba0982f13
[]
no_license
Duaard/ProgrammingProblems
954812332632a5932ada310976a7f79d9285d415
baeef97663f85aa184e93b46a26602711d3c3c94
refs/heads/master
2021-08-09T01:48:55.108061
2020-12-21T06:17:34
2020-12-21T06:17:34
233,727,308
0
0
null
null
null
null
UTF-8
C++
false
false
1,552
cpp
#include <bits/stdc++.h> using namespace std; int n; long long S; vector<vector<pair<int, int>>> adj; vector<int> w, cnt; long long getDiff(int i) { return w[i] * 1ll * cnt[i] - w[i] / 2 * 1ll * cnt[i]; } void dfs(int v, int p = -1) { if (adj[v].size() == 1) cnt[p] = 1; for (auto [to, id] : adj[v]) { if (id == p) continue; dfs(to, id); if (p != -1) { cnt[p] += cnt[id]; } } } void solve() { cin >> n >> S; cnt = w = vector<int>(n - 1); adj = vector<vector<pair<int, int>>>(n); for (int i = 0; i < n - 1; i++) { int x, y; cin >> x >> y >> w[i]; x--, y--; adj[x].push_back({y, i}); adj[y].push_back({x, i}); } dfs(0); // Create a set of pairs to keep track of different weight * leaves set<pair<long long, int>> st; long long cur = 0; for (int i = 0; i < n - 1; i++) { st.insert({getDiff(i), i}); cur += w[i] * 1ll * cnt[i]; } int ans = 0; while (cur > S) { // Get the highest diff value int id = st.rbegin()->second; // Delete the last element st.erase(prev(st.end())); // Decrease cur by the diff of this id cur -= getDiff(id); w[id] /= 2; // Insert new value for this id st.insert({getDiff(id), id}); // Increment ans ans++; } cout << ans << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } }
e171a1554ca8839aa5c44787ea5004a18a0ff2c6
ba4db75b9d1f08c6334bf7b621783759cd3209c7
/src_main/Tracker/AdminServer/DialogAddServer.cpp
4a9130423b05c5c6c54485956141844d5fb4e812
[]
no_license
equalent/source-2007
a27326c6eb1e63899e3b77da57f23b79637060c0
d07be8d02519ff5c902e1eb6430e028e1b302c8b
refs/heads/master
2020-03-28T22:46:44.606988
2017-03-27T18:05:57
2017-03-27T18:05:57
149,257,460
2
0
null
2018-09-18T08:52:10
2018-09-18T08:52:09
null
WINDOWS-1252
C++
false
false
3,224
cpp
//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #include "DialogAddServer.h" #include "INetAPI.h" #include "IGameList.h" #include "Server.h" #include <VGUI_MessageBox.h> #include <VGUI_KeyValues.h> using namespace vgui; //----------------------------------------------------------------------------- // Purpose: Constructor // Input : *gameList - game list to add specified server to //----------------------------------------------------------------------------- CDialogAddServer::CDialogAddServer(IGameList *gameList) : Frame(NULL, "DialogAddServer") { MakePopup(); m_pGameList = gameList; SetTitle("Add Server - Servers", true); LoadControlSettings("Admin\\DialogAddServer.res"); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- CDialogAddServer::~CDialogAddServer() { } //----------------------------------------------------------------------------- // Purpose: Activates this dialog //----------------------------------------------------------------------------- void CDialogAddServer::Open() { MoveToFront(); RequestFocus(); } //----------------------------------------------------------------------------- // Purpose: // Input : *command - //----------------------------------------------------------------------------- void CDialogAddServer::OnCommand(const char *command) { if (!stricmp(command, "OK")) { OnOK(); } else { BaseClass::OnCommand(command); } } //----------------------------------------------------------------------------- // Purpose: Handles the OK button being pressed; adds the server to the game list //----------------------------------------------------------------------------- void CDialogAddServer::OnOK() { // try and parse out IP address const char *address = GetControlString("ServerNameText", ""); netadr_t netaddr; if (net->StringToAdr(address, &netaddr)) { // net address successfully parsed, add the server to the game list serveritem_t server; memset(&server, 0, sizeof(server)); for (int i = 0; i < 4; i++) { server.ip[i] = netaddr.ip[i]; } server.port = (netaddr.port & 0xff) << 8 | (netaddr.port & 0xff00) >> 8;; if (!server.port) { // use the default port since it was not entered server.port = 27015; } m_pGameList->AddNewServer(server); m_pGameList->StartRefresh(); } else { // could not parse the ip address, popup an error MessageBox *dlg = new MessageBox("Add Server - Error", "The server IP address you entered is invalid."); dlg->DoModal(); } // mark ourselves to be closed PostMessage(this, new KeyValues("Close")); } //----------------------------------------------------------------------------- // Purpose: Deletes dialog on close //----------------------------------------------------------------------------- void CDialogAddServer::OnClose() { BaseClass::OnClose(); MarkForDeletion(); }
7541e54dd2375ef8a66f8efb5c481cf634303f69
3e7709aad8a8850f5d95f051a70797678b873649
/PP17/Main.cpp
60d4f9bc012ea48bec4c0d26f9239cc4d8f8c258
[]
no_license
OhYouSeok/PP01.HelloSDL.20171200.-
210998e62c0bbf8db70fe3fa42a1bafb5d7760ae
43332bed2d3795848064c885a166be8ee28f8af8
refs/heads/master
2020-03-28T03:24:05.583773
2018-12-04T04:20:35
2018-12-04T04:20:35
147,642,430
0
0
null
null
null
null
UTF-8
C++
false
false
786
cpp
#pragma once #include "Game.h" #include "SDL.h" int main(int argc, char* argv[]) { std::cout << "game init attempt...\n"; if (TheGame::Instance()->init("Chapter 1", 100, 100, 640, 480, false)) { const int FPS = 60; const int DELAY_TIME = 1000.0f / FPS; Uint32 frameStart, frameTime; while (TheGame::Instance()->running()) { frameStart = SDL_GetTicks(); TheGame::Instance()->handleEvents(); TheGame::Instance()->update(); TheGame::Instance()->render(); frameTime = SDL_GetTicks() - frameStart; if (frameTime < DELAY_TIME) { SDL_Delay((int)(DELAY_TIME - frameTime)); } } } else { std::cout << "game init failure - " << SDL_GetError() << "\n"; return -1; } std::cout << "game closing...\n"; TheGame::Instance()->clean(); return 0; }
ca4121635fe2c64bf2ec704c2291b5460a9891f3
83c56aa49e1dae0aae3c4b2ac57948b2922081cf
/AVIWriter/src/create_avi.cpp
713b0b71ce1492ba02ca9fc0b38f8c556088da1d
[ "MIT" ]
permissive
supragya/libfuse-FrameServer
6cb6683396f4c4e15dd7a02787b8866033d5b04b
7a4291b187f54104e6822979dc800b9d8df34d4b
refs/heads/master
2021-04-26T23:51:39.813555
2018-03-22T20:21:40
2018-03-22T20:21:40
123,870,955
1
2
null
null
null
null
UTF-8
C++
false
false
1,171
cpp
/* Copyright (C) 2018 Supragya Raj * You may use, distribute and modify this code under the * terms of the MIT license. * * libfuse-FrameServer - (https://github.com/supragya/libfuse-FrameServer) * */ #include "AviEncode/AviEncode.h" #include "AviEncode/SyntheticFrames.h" void setavisettings(AviEncode::avi_usersettings *settings); int main(int argc, char **argv) { AviEncode::avi_usersettings avisettings; setavisettings(&avisettings); AviEncode::AviContainer aviout("AviFile.avi", avisettings); long framelen = 480 * 270 * 3; char *frame = new char[framelen]; SFrame::GrayScaleGradient(frame, 480, 270); for (int i = 0; i < 50; i++) { aviout.AddFrame(frame); } SFrame::RGBStripes(frame, 480, 270); for (int i = 0; i < 50; i++) { aviout.AddFrame(frame); } SFrame::AbstractFrame1(frame, 480, 270); for (int i = 0; i < 50; i++) { aviout.AddFrame(frame); } return 0; } void setavisettings(AviEncode::avi_usersettings *settings) { settings->height = 480; settings->width = 270; settings->fps = 24; // TODO: MAKE FPS SEEP INTO HEADERS settings->framecnt = 150; }
7209f0025fb7eb90eee814e225eaa994416f55a3
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/protocols/helical_bundle/MakeBundle.fwd.hh
7e9366acb3526bac4df16382b50f592ecdc0bb3e
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
1,348
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: [email protected]. /// @file protocols/helical_bundle/MakeBundle.fwd.hh /// @brief Defines owning pointers for MakeBundle mover class. /// @author Vikram K. Mulligan ([email protected]) #ifndef INCLUDED_protocols_helical_bundle_MakeBundle_fwd_hh #define INCLUDED_protocols_helical_bundle_MakeBundle_fwd_hh #include <utility/pointer/owning_ptr.hh> #include <utility/vector1.hh> namespace protocols { namespace helical_bundle { class MakeBundle; // fwd declaration typedef utility::pointer::shared_ptr< MakeBundle > MakeBundleOP; typedef utility::pointer::shared_ptr< MakeBundle const > MakeBundleCOP; typedef utility::vector1<MakeBundleOP> MakeBundleOPs; typedef utility::vector1<MakeBundleCOP> MakeBundleCOPs; } // namespace helical_bundle } // namespace protocols #endif // INCLUDED_protocols_helical_bundle_MakeBundle_fwd_hh
c7d4032519975a7c4b34cf6cc54d24f8de3e31c1
02242585871ebf9129684541246d0688a447f03e
/UI/ReaderType.h
41907a00169f54138235814ee7f056b928320f86
[]
no_license
zy98/LibraryManagement
6d0ab525b80703913d5ba3f25cd3ddb59e3f0709
ffb27bf346ea95568f584a6493a1ec8e532fa8a1
refs/heads/master
2020-04-10T09:20:25.278992
2018-12-20T06:36:31
2018-12-20T06:36:31
160,933,503
0
0
null
null
null
null
UTF-8
C++
false
false
644
h
#ifndef READERTYPE_H #define READERTYPE_H #include <QContextMenuEvent> #include <QDialog> #include <QMenu> #include <QSqlRelationalTableModel> #include <QWidget> namespace Ui { class ReaderType; } class ReaderType : public QDialog { Q_OBJECT public: explicit ReaderType(QWidget *parent = nullptr); ~ReaderType(); protected: void contextMenuEvent(QContextMenuEvent *event); private slots: void on_actionSubmit_triggered(); void on_actionNew_triggered(); void on_actionRemove_triggered(); private: Ui::ReaderType *ui; QSqlRelationalTableModel* model; QMenu* menu; }; #endif // READERTYPE_H
c98bf16e91743b345a9be1942757201afcbf0572
a8c8256c4f5ea37543a54b98debd6876394ad091
/metrics/vsnr_matlab_source/imdwt_cpp/ginclude/gwavelift.cpp
fa7f44abacdad90427897f9b2e5a24f2d9ad612d
[]
no_license
treammm/DoG_SSIM
a1582f9c02911efe464728b3f40bfb77c8f4c1e9
677846f8baaaaf452cf6a7bdf7bf33a38ed67954
refs/heads/master
2020-05-04T20:03:32.264207
2019-11-20T18:09:22
2019-11-20T18:09:22
179,419,972
13
0
null
null
null
null
UTF-8
C++
false
false
1,843
cpp
//////////////////////////////////////////////////////////////////////////// // // // COPYRIGHT (c) 1998, 2002, VCL // // ------------------------------ // // Permission to use, copy, modify, distribute and sell this software // // and its documentation for any purpose is hereby granted without fee, // // provided that the above copyright notice appear in all copies and // // that both that copyright notice and this permission notice appear // // in supporting documentation. VCL makes no representations about // // the suitability of this software for any purpose. // // // // DISCLAIMER: // // ----------- // // The code provided hereunder is provided as is without warranty // // of any kind, either express or implied, including but not limited // // to the implied warranties of merchantability and fitness for a // // particular purpose. The author(s) shall in no event be liable for // // any damages whatsoever including direct, indirect, incidental, // // consequential, loss of business profits or special damages. // // // //////////////////////////////////////////////////////////////////////////// //========================================================================= #include "gwavelift.h" // template class //=========================================================================
60be79a8f2a19ae63d87ee5e87a3b83d9c6631f5
88a5b32b3cf2588bb6a2a442b417489b72e5bae0
/cores/arduino/HardwareSerial2.cpp
aa1397ce6ab281ff716878065bd2ba85151de0cf
[]
no_license
unimatrix099/arduino-platform-avr
3217ee6d89beebf0822b946faac2d9424a892a30
a33c722357a92d92ef290eed086dd715498206b9
refs/heads/master
2021-05-26T14:53:07.373960
2014-01-27T21:48:17
2014-01-27T21:48:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,600
cpp
#include "Arduino.h" #include "HardwareSerial.h" #include "HardwareSerial_private.h" // Each HardwareSerial is defined in its own file, sine the linker pulls // in the entire file when any element inside is used. --gc-sections can // additionally cause unused symbols to be dropped, but ISRs have the // "used" attribute so are never dropped and they keep the // HardwareSerial instance in as well. Putting each instance in its own // file prevents the linker from pulling in any unused instances in the // first place. #if defined(HAVE_HWSERIAL2) #if defined(USART_RX_vect) ISR(USART_RX_vect) #elif defined(USART2_RX_vect) ISR(USART2_RX_vect) #elif defined(USART_RXC_vect) ISR(USART_RXC_vect) // ATmega8 #else #error "Don't know what the Data Received vector is called for the first UART" #endif { Serial2._rx_complete_irq(); } #if defined(UART2_UDRE_vect) ISR(UART2_UDRE_vect) #elif defined(UART_UDRE_vect) ISR(UART_UDRE_vect) #elif defined(USART2_UDRE_vect) ISR(USART2_UDRE_vect) #elif defined(USART_UDRE_vect) ISR(USART_UDRE_vect) #else #error "Don't know what the Data Register Empty vector is called for the first UART" #endif { Serial2._tx_udr_empty_irq(); } #if defined(UBRRH) && defined(UBRRL) HardwareSerial Serial2(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR); #else HardwareSerial Serial2(&UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UCSR2C, &UDR2); #endif // Function that can be weakly referenced by serialEventRun to prevent // pulling in this file if it's not otherwise used. bool Serial2_available() { return Serial2.available(); } #endif // HAVE_HWSERIAL2
9ebc9626a2014c4374bc4b5f4385f16f2245cdda
a9d08ab9cdde95f699f3a696e1e4a8d4fd07caa9
/01_WinMain/IntersectManager.cpp
bf45a8c51d1e0f3d5d2181a2e834d47ba0ea4035
[]
no_license
rlawhdcjf333/isometricTileMap
3e75a36e517c0dc036869e0ebe528a4578c3f856
71c67ccbdd05b4080e578e9c2dac1d0bc0ca1959
refs/heads/main
2023-03-28T00:03:11.047477
2021-03-28T23:40:05
2021-03-28T23:40:05
345,596,703
0
1
null
null
null
null
UTF-8
C++
false
false
704
cpp
#include "pch.h" #include "IntersectManager.h" IntersectManager::IntersectManager() { // mPlayerBullets = &ObjectManager::GetInstance()->GetObjectList(ObjectLayer::Player_Bullet); // mEnemyBullets = &ObjectManager::GetInstance()->GetObjectList(ObjectLayer::Enemy_Bullet); // mEnemy = &ObjectManager::GetInstance()->GetObjectList(ObjectLayer::Enemy); } //void IntersectManager::IntersectBullet() //{ // for (int a = 0; a < mPlayerBullets->size(); a++) { // for (int b = 0; b < mEnemy->size(); b++) { // RECT PlayerBullet = (*mPlayerBullets)[a]->GetRect(); // RECT Enmey = (*mEnemyBullets)[b]->GetRect(); // RECT temp; // if (IntersectRect(&temp,&PlayerBullet,&Enemy) { // // } // } // } //}
824fc79d524338c45af82f94d6c2a70289d71e78
edc067ec2e759a31b7ac84c51daeb67ed27d63d1
/Kruskal.cpp
05788e0407c08d4b6090245a2c4545bf3074aae0
[]
no_license
Nphox/algorithms
68db0b40ec04f3ebc38b3a0937ad792c5eaacad0
293e79af350e3ca968abdd1ff64a62b89f077fd0
refs/heads/master
2020-06-26T15:25:31.233846
2019-07-30T14:54:39
2019-07-30T14:54:39
199,672,814
0
0
null
null
null
null
UTF-8
C++
false
false
1,709
cpp
#include <iostream> #include <vector> #include <algorithm> #include <math.h> using namespace std; double weight_edge(pair<int, int> p1, pair<int, int> p2){ double dx = p1.first - p2.first; double dy = p1.second - p2.second; return sqrt(dx*dx + dy*dy); } int main() { int count_vertices; cout << "count_vertices: "; cin >> count_vertices; int x, y; vector<pair<int, int>> vertices; for(int i = 0; i < count_vertices; i++){ cout << "input x, y: "; cin >> x; cin >> y; vertices.push_back(make_pair(x, y)); } int count_edges = (count_vertices * count_vertices - count_vertices) / 2; vector<pair<double, pair<int, int>>> edges(count_edges); int index = 0; for(int i = 0; i < count_vertices; i++){ for(int j = i + 1; j < count_vertices; j++){ edges[index].first = weight_edge(vertices[i], vertices[j]); edges[index].second = make_pair(i, j); index++; } } sort(edges.begin(), edges.end()); vector<int> tree_id(count_vertices); for (int i = 0; i < count_vertices; ++i){ tree_id[i] = i; } double cost = 0; for (int i = 0; i < count_edges; ++i){ int index_v1 = edges[i].second.first; int index_v2 = edges[i].second.second; double weight = edges[i].first; if (tree_id[index_v1] != tree_id[index_v2]){ cost += weight; int old_id = tree_id[index_v2], new_id = tree_id[index_v1]; for (int j = 0; j < count_vertices; ++j){ if (tree_id[j] == old_id){ tree_id[j] = new_id; } } } } printf("%.*f", 2, cost); }
c76384e54e56878852ad0eb0eba351087833c966
279932ac2716df741344f6210b5cfe390929e9c6
/week3_imageDrawingAndSound/src/ofApp.cpp
b7243fd47c9f01a4bfb10d2746f61e428a936025
[]
no_license
templeblock/avsysNantes
bf9dec0396c80a99a724a82f7dfcfe4aeaf0b863
196ea116a3b158d426c883099c71467ba426fd28
refs/heads/master
2021-01-23T19:11:31.334781
2016-01-21T13:39:52
2016-01-21T13:39:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,703
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ w = 300; h = 500; img.allocate(w,h,OF_IMAGE_GRAYSCALE); unsigned char * pixels = img.getPixels(); for (int i = 0; i < w; i++){ for (int j = 0; j < h; j++){ pixels[j*w + i] = 0; } } img.update(); ofSoundStreamSetup(2,0,this, 44100,256, 4); ofSetVerticalSync(true); verticalPos = 0; for (int i = 0; i < 30; i++){ oscillators[i].setup(); oscillators[i].setFrequency(30 + i * 100); oscillators[i].setVolume(0); } bDoFade = false; speed = 2; } //-------------------------------------------------------------- void ofApp::update(){ unsigned char * pixels = img.getPixels(); if (bDoFade == true){ for (int i = 0; i < w; i++){ for (int j = 0; j < h; j++){ pixels[j*w + i] = MAX(0, pixels[j*w + i] - 1); } } } ofBackground(255,255,255); verticalPos += speed; if (verticalPos > (h-1)) verticalPos = 0; if (verticalPos < 0) verticalPos = (h-1); // now, for the given line of pixels, calculate how "loud" each oscillator is: int pixWidth = (int)(w / 30.0f); for (int i = 0; i < 30; i++){ float total = 0; for (int j = 0; j < pixWidth; j++){ int ypos = verticalPos; int xpos = i * pixWidth + j; total += pixels[ypos * w + xpos]; } total /= (float)pixWidth; total /= 255; total *= (1/30.0f); oscillators[i].setVolume(total); } img.update(); } //-------------------------------------------------------------- void ofApp::draw(){ ofSetColor(255); img.draw(0,0,w,h); //calculate where the position is: ofSetColor(255, 0, 0); ofLine(0,verticalPos, w, verticalPos); ofSetColor(0,0,0); ofDrawBitmapString("press (f) to toggle fade", 330, 30); ofDrawBitmapString("press (+/-) to adjust speed: " + ofToString(speed, 3), 330, 45); } //-------------------------------------------------------------- void ofApp::keyPressed (int key){ if (key == 'f'){ bDoFade = !bDoFade; } else if (key == '-'){ speed -= 0.15f; } else if (key == '+'){ speed += 0.15f; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ unsigned char * pixels = img.getPixels(); for (int i = 0; i < w; i++){ for (int j = 0; j < h; j++){ float dist = ofDist(mouseX, mouseY, i, j); // calculate the distance between two 2d points (pythogrean) if (dist < 100){ pixels[ j * 300 + i ] = MIN(255, pixels[ j * 300 + i ] + ofMap(dist, 0, 100, 100, 0)); } } } img.update(); } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(){ } //-------------------------------------------------------------- void ofApp::audioRequested(float * output, int bufferSize, int nChannels){ float volume = 0.3f; for (int i = 0; i < bufferSize; i++){ output[i*nChannels ] = 0; output[i*nChannels + 1] = 0; } for (int i = 0; i < 30; i++){ oscillators[i].addToSoundBuffer(output, bufferSize); } /*for (int i = 0; i < bufferSize; i++){ pos ++; pos %= (w*h); output[i*nChannels ] = (pixels[pos]/127.0f - 1) * volume; output[i*nChannels + 1] = (pixels[pos]/127.0f - 1) * volume; }*/ }
d4b21a41b45f796e955947cb5ba91efa1a78c543
2f89eb85c767c7ec0f20c369a46abab72ad1cca1
/hook.cpp
6671d3b404f6d6d23f1e74a56cfbe583e48c17c9
[]
no_license
bbrandt/nssm
f51c496189ad4a65ad3c235b6305ad9b4312f620
9c88bc137c8cdec52c6c1b63c010c0aa3a78fb2b
refs/heads/master
2021-01-10T22:33:43.058823
2016-09-06T12:29:27
2016-09-06T12:29:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,221
cpp
#include "nssm.h" typedef struct { TCHAR *name; HANDLE process_handle; unsigned long pid; unsigned long deadline; FILETIME creation_time; kill_t k; } hook_t; const TCHAR *hook_event_strings[] = { NSSM_HOOK_EVENT_START, NSSM_HOOK_EVENT_STOP, NSSM_HOOK_EVENT_EXIT, NSSM_HOOK_EVENT_POWER, NSSM_HOOK_EVENT_ROTATE, NULL }; const TCHAR *hook_action_strings[] = { NSSM_HOOK_ACTION_PRE, NSSM_HOOK_ACTION_POST, NSSM_HOOK_ACTION_CHANGE, NSSM_HOOK_ACTION_RESUME, NULL }; static unsigned long WINAPI await_hook(void *arg) { hook_t *hook = (hook_t *) arg; if (! hook) return NSSM_HOOK_STATUS_ERROR; int ret = 0; if (WaitForSingleObject(hook->process_handle, hook->deadline) == WAIT_TIMEOUT) ret = NSSM_HOOK_STATUS_TIMEOUT; /* Tidy up hook process tree. */ if (hook->name) hook->k.name = hook->name; else hook->k.name = _T("hook"); hook->k.process_handle = hook->process_handle; hook->k.pid = hook->pid; hook->k.stop_method = ~0; hook->k.kill_console_delay = NSSM_KILL_CONSOLE_GRACE_PERIOD; hook->k.kill_window_delay = NSSM_KILL_WINDOW_GRACE_PERIOD; hook->k.kill_threads_delay = NSSM_KILL_THREADS_GRACE_PERIOD; hook->k.creation_time = hook->creation_time; GetSystemTimeAsFileTime(&hook->k.exit_time); kill_process_tree(&hook->k, hook->pid); if (ret) { CloseHandle(hook->process_handle); if (hook->name) HeapFree(GetProcessHeap(), 0, hook->name); HeapFree(GetProcessHeap(), 0, hook); return ret; } unsigned long exitcode; GetExitCodeProcess(hook->process_handle, &exitcode); CloseHandle(hook->process_handle); if (hook->name) HeapFree(GetProcessHeap(), 0, hook->name); HeapFree(GetProcessHeap(), 0, hook); if (exitcode == NSSM_HOOK_STATUS_ABORT) return NSSM_HOOK_STATUS_ABORT; if (exitcode) return NSSM_HOOK_STATUS_FAILED; return NSSM_HOOK_STATUS_SUCCESS; } static void set_hook_runtime(TCHAR *v, FILETIME *start, FILETIME *now) { if (start && now) { ULARGE_INTEGER s; s.LowPart = start->dwLowDateTime; s.HighPart = start->dwHighDateTime; if (s.QuadPart) { ULARGE_INTEGER t; t.LowPart = now->dwLowDateTime; t.HighPart = now->dwHighDateTime; if (t.QuadPart && t.QuadPart >= s.QuadPart) { t.QuadPart -= s.QuadPart; t.QuadPart /= 10000LL; TCHAR number[16]; _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%llu"), t.QuadPart); SetEnvironmentVariable(v, number); return; } } } SetEnvironmentVariable(v, _T("")); } static void add_thread_handle(hook_thread_t *hook_threads, HANDLE thread_handle, TCHAR *name) { if (! hook_threads) return; int num_threads = hook_threads->num_threads + 1; hook_thread_data_t *data = (hook_thread_data_t *) HeapAlloc(GetProcessHeap(), 0, num_threads * sizeof(hook_thread_data_t)); if (! data) { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("hook_thread_t"), _T("add_thread_handle()"), 0); return; } int i; for (i = 0; i < hook_threads->num_threads; i++) memmove(&data[i], &hook_threads->data[i], sizeof(data[i])); memmove(data[i].name, name, sizeof(data[i].name)); data[i].thread_handle = thread_handle; if (hook_threads->data) HeapFree(GetProcessHeap(), 0, hook_threads->data); hook_threads->data = data; hook_threads->num_threads = num_threads; } bool valid_hook_name(const TCHAR *hook_event, const TCHAR *hook_action, bool quiet) { bool valid_event = false; bool valid_action = false; /* Exit/Post */ if (str_equiv(hook_event, NSSM_HOOK_EVENT_EXIT)) { if (str_equiv(hook_action, NSSM_HOOK_ACTION_POST)) return true; if (quiet) return false; print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_POST); return false; } /* Power/{Change,Resume} */ if (str_equiv(hook_event, NSSM_HOOK_EVENT_POWER)) { if (str_equiv(hook_action, NSSM_HOOK_ACTION_CHANGE)) return true; if (str_equiv(hook_action, NSSM_HOOK_ACTION_RESUME)) return true; if (quiet) return false; print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_CHANGE); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_RESUME); return false; } /* Rotate/{Pre,Post} */ if (str_equiv(hook_event, NSSM_HOOK_EVENT_ROTATE)) { if (str_equiv(hook_action, NSSM_HOOK_ACTION_PRE)) return true; if (str_equiv(hook_action, NSSM_HOOK_ACTION_POST)) return true; if (quiet) return false; print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_PRE); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_POST); return false; } /* Start/{Pre,Post} */ if (str_equiv(hook_event, NSSM_HOOK_EVENT_START)) { if (str_equiv(hook_action, NSSM_HOOK_ACTION_PRE)) return true; if (str_equiv(hook_action, NSSM_HOOK_ACTION_POST)) return true; if (quiet) return false; print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_PRE); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_POST); return false; } /* Stop/Pre */ if (str_equiv(hook_event, NSSM_HOOK_EVENT_STOP)) { if (str_equiv(hook_action, NSSM_HOOK_ACTION_PRE)) return true; if (quiet) return false; print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_ACTION, hook_event); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_ACTION_PRE); return false; } if (quiet) return false; print_message(stderr, NSSM_MESSAGE_INVALID_HOOK_EVENT); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_EXIT); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_POWER); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_ROTATE); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_START); _ftprintf(stderr, _T("%s\n"), NSSM_HOOK_EVENT_STOP); return false; } void await_hook_threads(hook_thread_t *hook_threads, SERVICE_STATUS_HANDLE status_handle, SERVICE_STATUS *status, unsigned long deadline) { if (! hook_threads) return; if (! hook_threads->num_threads) return; int *retain = (int *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, hook_threads->num_threads * sizeof(int)); if (! retain) { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("retain"), _T("await_hook_threads()"), 0); return; } /* We could use WaitForMultipleObjects() but await_single_object() can update the service status as well. */ int num_threads = 0; int i; for (i = 0; i < hook_threads->num_threads; i++) { if (deadline) { if (await_single_handle(status_handle, status, hook_threads->data[i].thread_handle, hook_threads->data[i].name, _T(__FUNCTION__), deadline) != 1) { CloseHandle(hook_threads->data[i].thread_handle); continue; } } else if (WaitForSingleObject(hook_threads->data[i].thread_handle, 0) != WAIT_TIMEOUT) { CloseHandle(hook_threads->data[i].thread_handle); continue; } retain[num_threads++]= i; } if (num_threads) { hook_thread_data_t *data = (hook_thread_data_t *) HeapAlloc(GetProcessHeap(), 0, num_threads * sizeof(hook_thread_data_t)); if (! data) { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("data"), _T("await_hook_threads()"), 0); HeapFree(GetProcessHeap(), 0, retain); return; } for (i = 0; i < num_threads; i++) memmove(&data[i], &hook_threads->data[retain[i]], sizeof(data[i])); HeapFree(GetProcessHeap(), 0, hook_threads->data); hook_threads->data = data; hook_threads->num_threads = num_threads; } else { HeapFree(GetProcessHeap(), 0, hook_threads->data); ZeroMemory(hook_threads, sizeof(*hook_threads)); } HeapFree(GetProcessHeap(), 0, retain); } /* Returns: NSSM_HOOK_STATUS_SUCCESS if the hook ran successfully. NSSM_HOOK_STATUS_NOTFOUND if no hook was found. NSSM_HOOK_STATUS_ABORT if the hook failed and we should cancel service start. NSSM_HOOK_STATUS_ERROR on error. NSSM_HOOK_STATUS_NOTRUN if the hook didn't run. NSSM_HOOK_STATUS_TIMEOUT if the hook timed out. NSSM_HOOK_STATUS_FAILED if the hook failed. */ int nssm_hook(hook_thread_t *hook_threads, nssm_service_t *service, TCHAR *hook_event, TCHAR *hook_action, unsigned long *hook_control, unsigned long deadline, bool async) { int ret = 0; hook_t *hook = (hook_t *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(hook_t)); if (! hook) { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("hook"), _T("nssm_hook()"), 0); return NSSM_HOOK_STATUS_ERROR; } FILETIME now; GetSystemTimeAsFileTime(&now); EnterCriticalSection(&service->hook_section); /* Set the environment. */ set_service_environment(service); /* ABI version. */ TCHAR number[16]; _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), NSSM_HOOK_VERSION); SetEnvironmentVariable(NSSM_HOOK_ENV_VERSION, number); /* Event triggering this action. */ SetEnvironmentVariable(NSSM_HOOK_ENV_EVENT, hook_event); /* Hook action. */ SetEnvironmentVariable(NSSM_HOOK_ENV_ACTION, hook_action); /* Control triggering this action. May be empty. */ if (hook_control) SetEnvironmentVariable(NSSM_HOOK_ENV_TRIGGER, service_control_text(*hook_control)); else SetEnvironmentVariable(NSSM_HOOK_ENV_TRIGGER, _T("")); /* Last control handled. */ SetEnvironmentVariable(NSSM_HOOK_ENV_LAST_CONTROL, service_control_text(service->last_control)); /* Path to NSSM, unquoted for the environment. */ SetEnvironmentVariable(NSSM_HOOK_ENV_IMAGE_PATH, nssm_unquoted_imagepath()); /* NSSM version. */ SetEnvironmentVariable(NSSM_HOOK_ENV_NSSM_CONFIGURATION, NSSM_CONFIGURATION); SetEnvironmentVariable(NSSM_HOOK_ENV_NSSM_VERSION, NSSM_VERSION); SetEnvironmentVariable(NSSM_HOOK_ENV_BUILD_DATE, NSSM_DATE); /* NSSM PID. */ _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), GetCurrentProcessId()); SetEnvironmentVariable(NSSM_HOOK_ENV_PID, number); /* NSSM runtime. */ set_hook_runtime(NSSM_HOOK_ENV_RUNTIME, &service->nssm_creation_time, &now); /* Application PID. */ if (service->pid) { _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->pid); SetEnvironmentVariable(NSSM_HOOK_ENV_APPLICATION_PID, number); /* Application runtime. */ set_hook_runtime(NSSM_HOOK_ENV_APPLICATION_RUNTIME, &service->creation_time, &now); /* Exit code. */ SetEnvironmentVariable(NSSM_HOOK_ENV_EXITCODE, _T("")); } else { SetEnvironmentVariable(NSSM_HOOK_ENV_APPLICATION_PID, _T("")); if (str_equiv(hook_event, NSSM_HOOK_EVENT_START) && str_equiv(hook_action, NSSM_HOOK_ACTION_PRE)) { SetEnvironmentVariable(NSSM_HOOK_ENV_APPLICATION_RUNTIME, _T("")); SetEnvironmentVariable(NSSM_HOOK_ENV_EXITCODE, _T("")); } else { set_hook_runtime(NSSM_HOOK_ENV_APPLICATION_RUNTIME, &service->creation_time, &service->exit_time); /* Exit code. */ _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->exitcode); SetEnvironmentVariable(NSSM_HOOK_ENV_EXITCODE, number); } } /* Deadline for this script. */ _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), deadline); SetEnvironmentVariable(NSSM_HOOK_ENV_DEADLINE, number); /* Service name. */ SetEnvironmentVariable(NSSM_HOOK_ENV_SERVICE_NAME, service->name); SetEnvironmentVariable(NSSM_HOOK_ENV_SERVICE_DISPLAYNAME, service->displayname); /* Times the service was asked to start. */ _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->start_requested_count); SetEnvironmentVariable(NSSM_HOOK_ENV_START_REQUESTED_COUNT, number); /* Times the service actually did start. */ _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->start_count); SetEnvironmentVariable(NSSM_HOOK_ENV_START_COUNT, number); /* Times the service exited. */ _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->exit_count); SetEnvironmentVariable(NSSM_HOOK_ENV_EXIT_COUNT, number); /* Throttled count. */ _sntprintf_s(number, _countof(number), _TRUNCATE, _T("%lu"), service->throttle); SetEnvironmentVariable(NSSM_HOOK_ENV_THROTTLE_COUNT, number); /* Command line. */ TCHAR app[CMD_LENGTH]; _sntprintf_s(app, _countof(app), _TRUNCATE, _T("\"%s\" %s"), service->exe, service->flags); SetEnvironmentVariable(NSSM_HOOK_ENV_COMMAND_LINE, app); TCHAR cmd[CMD_LENGTH]; if (get_hook(service->name, hook_event, hook_action, cmd, sizeof(cmd))) { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_HOOK_FAILED, hook_event, hook_action, service->name, 0); unset_service_environment(service); LeaveCriticalSection(&service->hook_section); HeapFree(GetProcessHeap(), 0, hook); return NSSM_HOOK_STATUS_ERROR; } /* No hook. */ if (! _tcslen(cmd)) { unset_service_environment(service); LeaveCriticalSection(&service->hook_section); HeapFree(GetProcessHeap(), 0, hook); return NSSM_HOOK_STATUS_NOTFOUND; } /* Run the command. */ STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (service->hook_share_output_handles) (void) use_output_handles(service, &si); bool inherit_handles = false; if (si.dwFlags & STARTF_USESTDHANDLES) inherit_handles = true; unsigned long flags = 0; #ifdef UNICODE flags |= CREATE_UNICODE_ENVIRONMENT; #endif ret = NSSM_HOOK_STATUS_NOTRUN; if (CreateProcess(0, cmd, 0, 0, inherit_handles, flags, 0, service->dir, &si, &pi)) { hook->name = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, HOOK_NAME_LENGTH * sizeof(TCHAR)); if (hook->name) _sntprintf_s(hook->name, HOOK_NAME_LENGTH, _TRUNCATE, _T("%s (%s/%s)"), service->name, hook_event, hook_action); hook->process_handle = pi.hProcess; hook->pid = pi.dwProcessId; hook->deadline = deadline; if (get_process_creation_time(hook->process_handle, &hook->creation_time)) GetSystemTimeAsFileTime(&hook->creation_time); unsigned long tid; HANDLE thread_handle = CreateThread(NULL, 0, await_hook, (void *) hook, 0, &tid); if (thread_handle) { if (async) { ret = 0; await_hook_threads(hook_threads, service->status_handle, &service->status, 0); add_thread_handle(hook_threads, thread_handle, hook->name); } else { await_single_handle(service->status_handle, &service->status, thread_handle, hook->name, _T(__FUNCTION__), deadline + NSSM_SERVICE_STATUS_DEADLINE); unsigned long exitcode; GetExitCodeThread(thread_handle, &exitcode); ret = (int) exitcode; CloseHandle(thread_handle); } } else { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETHREAD_FAILED, error_string(GetLastError()), 0); await_hook(hook); if (hook->name) HeapFree(GetProcessHeap(), 0, hook->name); HeapFree(GetProcessHeap(), 0, hook); } } else { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_HOOK_CREATEPROCESS_FAILED, hook_event, hook_action, service->name, cmd, error_string(GetLastError()), 0); HeapFree(GetProcessHeap(), 0, hook); close_output_handles(&si); } /* Restore our environment. */ unset_service_environment(service); LeaveCriticalSection(&service->hook_section); return ret; } int nssm_hook(hook_thread_t *hook_threads, nssm_service_t *service, TCHAR *hook_event, TCHAR *hook_action, unsigned long *hook_control, unsigned long deadline) { return nssm_hook(hook_threads, service, hook_event, hook_action, hook_control, deadline, true); } int nssm_hook(hook_thread_t *hook_threads, nssm_service_t *service, TCHAR *hook_event, TCHAR *hook_action, unsigned long *hook_control) { return nssm_hook(hook_threads, service, hook_event, hook_action, hook_control, NSSM_HOOK_DEADLINE); }
9f64996eb91c9520561e9067e15666372e5acd5f
33b59f7ddb64b9464e68d281a8d2dd6dc1f63d47
/source/octoon-graphics/OpenGL 45/gl45_graphics_data.h
5548c04561dbfea8fa1ac233db4a63f140a3be89
[ "MIT" ]
permissive
superowner/octoon
24913edde75963a1414728c07f679fe024552777
2957132f9b00927a7d177ae21db20c5c7233a56f
refs/heads/master
2020-03-22T15:56:25.741567
2018-06-13T02:26:27
2018-06-13T02:26:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,261
h
#ifndef OCTOON_GL33_CORE_GRAPHICS_DATA_H_ #define OCTOON_GL33_CORE_GRAPHICS_DATA_H_ #include "gl33_types.h" namespace octoon { namespace graphics { class GL45GraphicsData final : public GraphicsData { OctoonDeclareSubClass(GL45GraphicsData, GraphicsData) public: GL45GraphicsData() noexcept; virtual ~GL45GraphicsData() noexcept; bool setup(const GraphicsDataDesc& desc) noexcept; void close() noexcept; std::ptrdiff_t flush() noexcept; std::ptrdiff_t flush(GLintptr offset, GLsizeiptr cnt) noexcept; bool map(std::ptrdiff_t offset, std::ptrdiff_t count, void** data) noexcept; void unmap() noexcept; GLuint getInstanceID() const noexcept; GLuint64 getInstanceAddr() const noexcept; const GraphicsDataDesc& getGraphicsDataDesc() const noexcept override; private: friend class GL33Device; void setDevice(const GraphicsDevicePtr& device) noexcept; GraphicsDevicePtr getDevice() noexcept override; private: GL45GraphicsData(const GL45GraphicsData&) noexcept = delete; GL45GraphicsData& operator=(const GL45GraphicsData&) noexcept = delete; private: GLuint _buffer; GLuint64 _bufferAddr; GLvoid* _data; GraphicsDataDesc _desc; GraphicsDeviceWeakPtr _device; }; } } #endif
2ab3423b394f7113b1e7aec146fd9a3d0f8056a9
ee6f4bb32a3deb57b19e9f159f63ff2735695409
/src/compress.h
68977e1ac6730abe3e38f1e535cd95ecd7903849
[ "LGPL-2.0-or-later", "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "ISC" ]
permissive
LunaMoo/maxcso
cc4876b039e772f47af4225f07be898c38c8806e
e24f55ce6dad3f52ae44a2570fea429d31ce1c06
refs/heads/master
2022-04-27T08:10:38.964273
2020-04-29T04:05:46
2020-04-29T04:07:15
260,652,356
1
0
ISC
2020-05-02T09:18:29
2020-05-02T09:18:29
null
UTF-8
C++
false
false
1,529
h
#pragma once #include <string> #include <vector> #include <functional> #include <cstdint> namespace maxcso { static const char *VERSION = "1.11.0"; static const uint32_t DEFAULT_BLOCK_SIZE = 0xFFFFFFFF; struct Task; enum TaskStatus { TASK_INPROGRESS, TASK_SUCCESS, TASK_BAD_INPUT, TASK_BAD_OUTPUT, TASK_INVALID_DATA, TASK_CANNOT_WRITE, TASK_INVALID_OPTION, }; enum TaskFlags { TASKFLAG_DEFAULT = 0, // Disable certain compression algorithms. TASKFLAG_NO_ZLIB = 0x03, TASKFLAG_NO_ZLIB_DEFAULT = 0x01, TASKFLAG_NO_ZLIB_BRUTE = 0x02, TASKFLAG_NO_ZOPFLI = 0x04, TASKFLAG_NO_7ZIP = 0x08, // Disable heuristics and compress all sectors. TASKFLAG_FORCE_ALL = 0x10, // Flags for new formats. TASKFLAG_FMT_ZSO = 0x20, TASKFLAG_FMT_CSO_2 = 0x40, TASKFLAG_NO_LZ4 = 0x380, TASKFLAG_NO_LZ4_DEFAULT = 0x80, TASKFLAG_NO_LZ4_HC = 0x100, TASKFLAG_NO_LZ4_HC_BRUTE = 0x200, TASKFLAG_NO_ALL = TASKFLAG_NO_ZLIB | TASKFLAG_NO_ZOPFLI | TASKFLAG_NO_7ZIP | TASKFLAG_NO_LZ4, TASKFLAG_DECOMPRESS = 0x400, TASKFLAG_FMT_DAX = 0x800, }; typedef std::function<void (const Task *, TaskStatus status, int64_t pos, int64_t total, int64_t written)> ProgressCallback; typedef std::function<void (const Task *, TaskStatus status, const char *reason)> ErrorCallback; struct Task { std::string input; std::string output; ProgressCallback progress; ErrorCallback error; uint32_t block_size; uint32_t flags; double orig_max_cost_percent; double lz4_max_cost_percent; }; void Compress(const std::vector<Task> &tasks); };
efb2b34279eec437394988ad77c41118664f1b11
bf042df02c05aac248247d2ba0e5ee02924cdb5e
/AbeLauncher/main.cpp
dad3bfce872d5475ff3ff13fcee0b19cacaf9eff
[]
no_license
mlgthatsme/ReliveLauncher
566c6627417e989e443eab09f2966b68cac792e5
1deb0658724f4504d0f2de7a18efe49969c58b65
refs/heads/main
2023-06-24T05:41:16.008456
2021-07-21T09:17:50
2021-07-21T09:17:50
388,041,311
1
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
#include "Launcher.hpp" int main(int ac, char** ap) { Launcher launcher; launcher.Run(); return 0; }
7c0516acae0e22425afe7abf9e1f7926daeb85c3
d77ca9b1ecc17b5117c1aa93de53bfefa97c22b3
/USART-Interrupt-Driven-master/src/V2/main.cpp
dccfc212d1c0d000b352d6e8b0602f45ae8c06b7
[]
no_license
IvanAntunovic/FreeRTOS
edbbbf2ab8ca610ae81eb8daa0eb615af93c62a6
107b1d25a92778755a8914bcd719e2ed457467af
refs/heads/master
2020-03-31T08:22:42.931918
2018-10-08T09:43:36
2018-10-08T09:43:36
152,053,387
0
0
null
null
null
null
UTF-8
C++
false
false
1,059
cpp
/* * LCD_I2C_4bit.cpp * * Created: 5/20/2017 11:51:13 AM * Author : fairenough */ #define PCF8574A_ADDRESS 0x3F #include <avr/io.h> #include <string.h> #include "SerialPort.h" int main(void) { SerialPort serialPort; SerialPort serialPorta; serialPort.open(9600, 0); DDRA = 0xFF; int8_t retVal; uint8_t buffer[] = {'A', 'B', '\n', '\r'}; uint8_t rxBuffer[4]; while (1) { //serialPort.writeString("hello\n\r"); // serialPort.write(0); // serialPort.writeString("\n\r"); if (serialPort.available()) { retVal = serialPort.readBytes(rxBuffer, 10); serialPort.writeString("ReadBytes return value: "); serialPort.write(retVal); serialPort.writeString("\n\r"); serialPort.writeString("Rx Interrupt Status Code: "); serialPort.write(serialPort.getRxInterruptStatusCode()); serialPort.writeString("\n\r"); retVal = serialPort.writeBytes(rxBuffer, 10); serialPort.writeString("\n\r"); serialPort.writeString("WriteBytes return value: "); serialPort.write(retVal); serialPort.writeString("\n\r"); } } }
7cf134666985478b6a5c37d8f7cb50eb4d442b53
5947213fbe7f920a4190cfba78506f97e4651622
/arkhorserver/game/simplegameinteractor.cpp
13591e49801e943f6127cecc05b6a2254ca693d5
[]
no_license
kingnak/arkhor
bf18dc214325545d013946b9182b23bee3ffa4ac
24d550262f933ebfac4b7bad84cd4f7d22dd9420
refs/heads/master
2023-09-04T06:17:13.778915
2015-08-19T23:12:58
2015-08-19T23:12:58
83,339,894
0
0
null
null
null
null
UTF-8
C++
false
false
131
cpp
#include "simplegameinteractor.h" #include <QtGui> #include "gameoption.h" /* SimpleGameInteractor::SimpleGameInteractor() { } */
b5c4ac6854d4060867ff37f79ec83d2e69d823a0
d70745bdead55035c96f7ff5d6f44469b9a14903
/DynamicButton/dynamiicbutton.h
516633bfab4c8c8b7e27c79e28c4bfe917ff23e2
[]
no_license
rust3128/HotlineDesktop
32e1b06e2d4ad2a74c291941d570f08db10eee20
0006e7d28f088fe99c0aa891db219dfcd8eb8cc8
refs/heads/master
2022-03-26T00:54:28.887503
2020-01-11T13:53:32
2020-01-11T13:53:32
105,343,545
0
0
null
null
null
null
UTF-8
C++
false
false
310
h
#ifndef DYNAMIICBUTTON_H #define DYNAMIICBUTTON_H #include <QCommandLinkButton> #include <QPushButton> class DynamiicButton : public QPushButton { public: explicit DynamiicButton(int clientID, QWidget *parent = nullptr); int getButtonID(); private: int buttonID=0; }; #endif // DYNAMIICBUTTON_H
d0b3513fc1d4e0073ea02232299b0a9430ce2ec5
fe1d5d91d880c51cb6850fcad140bb39581c415d
/Array/KeyPair.cpp
9ed63f38982b9da5cbc7e541cb9e77fa76624fa1
[]
no_license
AvichalGupta/NotesAlgorithmsDS.cpp
ba87fd289a6408423c93355e987f3d9af12cd64f
8cd4c8913d6cf6403f8096918e5ff3f4c87dddce
refs/heads/master
2023-03-18T19:28:51.556720
2018-12-03T05:39:49
2018-12-03T05:39:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
429
cpp
#include <bits/stdc++.h> using namespace std; string KeyPair(int *arr,int size,int sum){ sort(arr,arr+size); for(int i=0;i<size;i++){ if(binary_search(arr,arr+size,arr[i]-sum)){ return "Yes"; } } return "No"; } int main(){ int tc; cin>>tc; while(tc--){ int size,sum; cin>>size>>sum; int *arr=new int[size]; for(int i=0;i<size;i++) cin>>arr[i]; cout<<KeyPair(arr,size,sum)<<endl; } return 0;}
3a9dbd6af75afc3478923d242f2afa9d16c59704
27fd300c2c0cb92b5ce70cf203c1ac35e3f44314
/array_challenges/romantoint.cpp
5508e36b7cb58052b4391f30334bb82c885c3167
[]
no_license
kameshkotwani/cpp
33f1b011657f1f702013ce2d1556ed19434f118a
2b0e6a809a4ec3e61c1b6e206eb2c9ac874046c6
refs/heads/master
2023-06-25T16:10:44.461292
2021-07-27T14:07:34
2021-07-27T14:07:34
371,575,399
0
0
null
null
null
null
UTF-8
C++
false
false
370
cpp
#include<bits/stdc++.h> using namespace std; int RomanToInt(const string& s){ unordered_map<char,int> T = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}}; int sum = T[s.back()]; for(int i=s.length()-2;i>=0;i--){ if(T[s[i]]<T[s[i+1]]){ sum-=T[s[i]]; } else{ sum+=T[s[i]]; } } return sum; } int main(){ cout<<RomanToInt("VII"); }
ad8d885df2f1e0ccca5b7ee8ca3e6caaec40aae7
a76f612c38bc3cf94912e6da9eaef1380cee0635
/src/IntegralEvaluator/LibintIntegrals/IntegralEvaluatorSettings.h
2d08c586cc20118600f8f775ff67d2d52c4ee3b4
[ "BSD-3-Clause" ]
permissive
qcscine/integralevaluator
cfdbbf929c635ef63a5082ddf0d8e8b14e4b3ea8
a81d5169e3a270d9dc19e2e074dbd0efb213807c
refs/heads/master
2023-04-09T10:31:00.146644
2023-01-25T18:36:00
2023-01-25T18:36:00
593,176,169
1
0
null
null
null
null
UTF-8
C++
false
false
992
h
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #ifndef INTEGRALEVALUATOR_INTEGRALEVALUATORSETTINGS_H #define INTEGRALEVALUATOR_INTEGRALEVALUATORSETTINGS_H #include <Utils/Settings.h> namespace Scine { namespace Integrals { struct IntegralEvaluatorSettings : public Utils::Settings { IntegralEvaluatorSettings() : Utils::Settings("Settings for the Integral Evaluator.") { Utils::UniversalSettings::BoolDescriptor pure_spherical( "If true, use only solid harmonics (i.e., spherical harmonics), else, use only cartesians. Mixing is not " "possible."); pure_spherical.setDefaultValue(true); _fields.push_back("use_pure_spherical", std::move(pure_spherical)); resetToDefaults(); } }; } // namespace Integrals } // namespace Scine #endif // INTEGRALEVALUATOR_INTEGRALEVALUATORSETTINGS_H
1e0219218d9fc926fc2699e148cda11261d75094
441baf96ad6b2c854fe45bb881012f70a48dff1a
/SPACEDEFENSE/OpenWindow.cpp
b94895902c01e6ac4dbc5a929a6b58821d67064e
[]
no_license
GautierAppert/C-Project-ENSAE
96efb98cc51c26ea528139c20d8a5c6f6511486d
595709f89f6d446dc48ea5bed51ce12b3e7c66a3
refs/heads/master
2020-04-14T12:13:18.710370
2015-11-23T15:34:17
2015-11-23T15:34:17
30,774,238
2
0
null
null
null
null
UTF-8
C++
false
false
2,897
cpp
#include "OpenWindow.h" #include "Game.h" // In order to create the game Game * game; // Constructor OpenWindow::OpenWindow() { // Size of the window setFixedSize(800,700); // Background of the window setStyleSheet("background-image: url(:/images/BG.jpg)"); //----- The PLAY button -----// // Create the button, using the QPushButton class from Qt playButton = new QPushButton("",this); // Characteristics of the button : cursor, image, size, position on the screen playButton->setCursor(Qt::PointingHandCursor); playButton->setIcon(QIcon(":/images/play.jpg")); playButton->setIconSize(QSize(200,100)); playButton->setMinimumWidth(200); playButton->setMinimumHeight(100); playButton->move(300, 400); // Do the function onClickPlay() when we click on the PLAY button QObject::connect(playButton, SIGNAL(clicked()), this , SLOT(onClickPlay())); //----- The INSTRUCTIONS button -----// // Create the button, using the QPushButton class from Qt instruButton = new QPushButton("",this); // Characteristics of the button : cursor, image, size, position on the screen instruButton->setCursor(Qt::PointingHandCursor); instruButton->setIcon(QIcon(":/images/instruction.jpg")); instruButton->setIconSize(QSize(200,100)); instruButton->setMinimumWidth(200); instruButton->setMinimumHeight(100); instruButton->move(300,550); // Do the function onClickInstru() when we click on the INSTRUCTIONS button QObject::connect(instruButton, SIGNAL(clicked()), this , SLOT(onClickInstru())); } // What happens when we click on the PLAY button void OpenWindow::onClickPlay() { // Begin to play : we create a new game, using our Game class game = new Game(); // Delete the opening window delete this; } // What happens when we click on the INSTRUCTIONS button void OpenWindow::onClickInstru() { // Explain the rules of our game QMessageBox::information(0,"INSTRUCTIONS", "<B><FONT COLOR='#000000'>Des \ vaisseaux spatiaux attaquent votre base ! Vous \ devez la protéger ! Utilisez les touches HAUT et BAS \ afin de vous déplacer sur la base, et la touche ESPACE \ pour tirer sur les vaisseaux ennemis. Soyez rapide : chaque \ ennemi parvenant à atteindre votre base vous fera perdre \ une vie ! Chaque vaisseau détruit vous rapportera 1$. Cet \ argent vous permettra d'acheter des vaisseaux alliés qui, \ une fois placés dans l'espace, vont vous aider dans votre \ mission. Chaque type d'allié à un prix, une vitesse et une \ durée de vie différente. </FONT></B>"); }
3e80a236410ad2f01328fa480070101811f68f1f
be58aaf9d72bc4f765db9c665330b2bca951f6cb
/CaptureReplayAutoTest-Robot2019/src/main/include/Auto.h
859906eaeb5c7e7b3a5c46682fa825b25079a17e
[]
no_license
Team3229/Hawktimus19-20
75df9da2bb7a26e7fd5f793baeebca2323d5226f
65584f2803a8f7b6cfd338f7bb274101c5c25874
refs/heads/master
2020-08-19T07:48:10.005278
2020-03-18T00:08:53
2020-03-18T00:08:53
215,895,257
3
0
null
2020-02-25T20:53:33
2019-10-17T22:20:04
C++
UTF-8
C++
false
false
2,403
h
#ifndef AUTO_H #define AUTO_H // includes #include <iostream> #include <string> #include <frc/TimedRobot.h> #include <frc/smartdashboard/SendableChooser.h> #include <frc/XboxController.h> #include <Math.h> #include "frc/Timer.h" #include "DriveSystem.h" #include "Intake.h" #include "Pneumatics.h" #include "Limelight.h" #include "Lift.h" #include "CaptureFile.h" #include "Debug.h" class Auto { private: bool autoDone = false; // Pass in our subsystems DriveSystem *autoChassis; Limelight *autoVisionSystem; Lift *autoLift; Intake *autoIntake; Pneumatics *autoAir; // files stuff // Use .aut file extension std::string defaultFileName = "defaultAutoPath.aut"; std::string inputFileName; const bool WRITE = true; const bool READ = false; CaptureFile cmdFile {}; // Method of storing and replaying drivers inputs struct cmd { // Driver 1 float xbox1_leftY; float xbox1_leftX; float xbox1_rightX; bool xbox1_AButton; bool xbox1_BButton; bool xbox1_XButton; bool xbox1_YButton; bool xbox1_RightBumper; bool xbox1_LeftBumper; float xbox1_RightTriggerAxis; // Driver 2 float xbox2_leftY; float xbox2_rightY; bool xbox2_XButton; bool xbox2_YButton; bool xbox2_RightBumper; bool xbox2_LeftBumper; float xbox2_RightTriggerAxis; float xbox2_LeftTriggerAxis; }; // TeleOp stuff for driving const float DEAD_BAND = 0.1; double d1_leftY, d1_leftX, d1_rightX, d2_leftY, d2_rightY; // Controller variables bool m_driveWithGyro = false; // Update init driver station message bool m_usingVision = false; bool m_lockLift = false; // Locks the 2nd driver from using lift int m_lastUsedSpeed = 2; std::string m_template = "Other"; public: Auto(DriveSystem *c, Pneumatics *a, Lift *l, Limelight *v, Intake *i); ~Auto(); void SetupAuto(); void SetupReading(); void ReadFile(); void SetupRecording(); void Record(); void CloseFile(); void AutoPeriodic(); cmd * autocommand = new cmd; void SwitchDriveMode() { debug("Drive mode switched...\n"); if (m_driveWithGyro == true) { frc::SmartDashboard::PutString("Drive Mode", "Without Gyro"); m_driveWithGyro = false; } else { frc::SmartDashboard::PutString("Drive Mode", "With Gyro"); m_driveWithGyro = true; } frc::Wait(0.5); } }; #endif // AUTO_H
e18603c2eee77bbe5def3a1c370f93d7b22eef06
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/WebKit/Source/core/svg/SVGAngleTearOff.h
8589ab8215f24a75c68c3bfbdefecd84147467d9
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,754
h
/* * Copyright (C) 2014 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SVGAngleTearOff_h #define SVGAngleTearOff_h #include "bindings/core/v8/ScriptWrappable.h" #include "core/svg/SVGAngle.h" #include "core/svg/properties/SVGPropertyTearOff.h" namespace blink { class SVGAngleTearOff final : public SVGPropertyTearOff<SVGAngle>, public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: static SVGAngleTearOff* create( SVGAngle* target, SVGElement* contextElement, PropertyIsAnimValType propertyIsAnimVal, const QualifiedName& attributeName = QualifiedName::null()) { return new SVGAngleTearOff(target, contextElement, propertyIsAnimVal, attributeName); } enum { kSvgAngletypeUnknown = SVGAngle::kSvgAngletypeUnknown, kSvgAngletypeUnspecified = SVGAngle::kSvgAngletypeUnspecified, kSvgAngletypeDeg = SVGAngle::kSvgAngletypeDeg, kSvgAngletypeRad = SVGAngle::kSvgAngletypeRad, kSvgAngletypeGrad = SVGAngle::kSvgAngletypeGrad }; ~SVGAngleTearOff() override; unsigned short unitType() { return hasExposedAngleUnit() ? target()->unitType() : SVGAngle::kSvgAngletypeUnknown; } void setValue(float, ExceptionState&); float value() { return target()->value(); } void setValueInSpecifiedUnits(float, ExceptionState&); float valueInSpecifiedUnits() { return target()->valueInSpecifiedUnits(); } void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits, ExceptionState&); void convertToSpecifiedUnits(unsigned short unitType, ExceptionState&); String valueAsString() { return hasExposedAngleUnit() ? target()->valueAsString() : String::number(0); } void setValueAsString(const String&, ExceptionState&); DECLARE_VIRTUAL_TRACE_WRAPPERS(); private: SVGAngleTearOff(SVGAngle*, SVGElement*, PropertyIsAnimValType, const QualifiedName&); bool hasExposedAngleUnit() { return target()->unitType() <= SVGAngle::kSvgAngletypeGrad; } }; } // namespace blink #endif // SVGAngleTearOff_h
7cf91e5b80c8838a74f8dfaf0d54b3a24122a060
eab9def3b34de394bd38726f89c02cb4d13d5777
/src/inc/Net/Server.h
8b204afe9d7e8fbd50600a282a66c40f2f5b3c72
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Mikulas/pa2sem
36a4d347f28569783cdc30164e8f9ab278c3b6bf
8cc7b3a2e0450fe13567cfcb869437d90a9f2298
refs/heads/master
2021-01-18T08:28:16.025444
2015-05-14T08:48:58
2015-05-14T08:48:58
32,762,743
0
0
null
null
null
null
UTF-8
C++
false
false
1,970
h
#ifndef NET_SERVER_H #define NET_SERVER_H class Server; #include <cctype> #include <cstdio> #include <cstdlib> #include <map> #include <netdb.h> #include <stdexcept> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <vector> #include "../Player/Remote.h" #include "Payload.h" using std::map; using std::vector; /** * \see Server * \ingroup Net */ class ServerException : public runtime_error { public: ServerException(string const& message) : std::runtime_error(message) {} }; /** * Communicates with one or multiple Client instances via Payload. * Listens on one port. Since all communication with user * must be blocking (with the exception of sending output), * all methods are called on the main thread. * * \ingroup Net */ class Server { public: Server() {}; /** * Starts listening on socket, but does not wait for * any connection. * Defaults to loopback interface. * \see waitForConnections * \throws ServerException */ void start(); /** * Starts listening on socket, but does not wait for * any connection. * \see waitForConnections * \throws ServerException */ void start(const char* addr); /** * Silently disconnects all users, if any. */ void stop(); /** * Blocks until there are as many connections * as passed `RemotePlayer*`. * There is no guarantee which player is bound to * which socket, the order is random (depends on * order in which users connect). */ void waitForConnections(vector<RemotePlayer*>); /** * \see Payload * \throws ServerException player disconnected * \throws PayloadException */ Payload send(RemotePlayer*, Payload*); /** * \see Payload * \throws ServerException player disconnected * \throws PayloadException */ void sendAll(Payload*); static uint port; private: /** * \throws ServerException */ int openSrvSocket(const char *name, int port); int fd; map<RemotePlayer*, int> sockets; }; #endif
694c60154ccd06077bd8e6c56803e11969253262
ffc0684e8c913e0299462a6127b6f1676db2a95e
/SOURCE/Server/query/GMHandlers.h
a3a1fc9e560c19df724946472e217a9842386e33
[ "CC-BY-3.0" ]
permissive
EESkox/iceee
4b692068019b24b327cd750c92505e821a656ef3
fa1b30f73ef86bb60fbe09a4bea265ec4f86dcf1
refs/heads/master
2021-07-03T16:02:15.532660
2017-09-26T12:27:18
2017-09-26T12:27:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,793
h
/* *This file is part of TAWD. * * TAWD is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TAWD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with TAWD. If not, see <http://www.gnu.org/licenses/ */ #ifndef GMHANDLERS_H #define GMHANDLERS_H #include "Query.h" class AddFundsHandler : public QueryHandler { public: ~AddFundsHandler() {}; int handleQuery(SimulatorThread *sim, CharacterServerData *pld, SimulatorQuery *query, CreatureInstance *creatureInstance); }; class PVPZoneModeHandler : public QueryHandler { public: ~PVPZoneModeHandler() {}; int handleQuery(SimulatorThread *sim, CharacterServerData *pld, SimulatorQuery *query, CreatureInstance *creatureInstance); }; class GMSpawnHandler : public QueryHandler { public: ~GMSpawnHandler() {}; int handleQuery(SimulatorThread *sim, CharacterServerData *pld, SimulatorQuery *query, CreatureInstance *creatureInstance); }; class StatusEffectSetHandler : public QueryHandler { public: ~StatusEffectSetHandler() {}; int handleQuery(SimulatorThread *sim, CharacterServerData *pld, SimulatorQuery *query, CreatureInstance *creatureInstance); }; class UpdateContentHandler : public QueryHandler { public: ~UpdateContentHandler() {}; int handleQuery(SimulatorThread *sim, CharacterServerData *pld, SimulatorQuery *query, CreatureInstance *creatureInstance); }; #endif
96c1c40d6c4099629324fe9c711484b8c2bb8a38
a0ef3aa1b3118baf54dc186d89c35072b8d96d54
/codeforces/540/C.cpp
cd536698bd392a0d279e7f167dc4cb8515015a2f
[]
no_license
arjunbangari/Problem-Solving
110398129698038660e558509c46c385e7848cc3
9c9760627a3fbdd97ecee8cbc02245a3ea0f7fda
refs/heads/master
2023-02-05T17:09:40.631840
2019-08-10T12:02:00
2020-12-29T11:52:13
324,994,511
4
0
null
null
null
null
UTF-8
C++
false
false
1,744
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int #define fast ios_base::sync_with_stdio(false);cin.tie(NULL); string arr[505]; ll n,m; bool valid(ll x, ll y){ return (x>=0 && x<n && y>=0 && y<m); } void dfs(ll i, ll j){ arr[i][j] = 'X'; if(valid(i-1,j) && arr[i-1][j]!='X') dfs(i-1,j); if(valid(i+1,j) && arr[i+1][j]!='X') dfs(i+1,j); if(valid(i,j-1) && arr[i][j-1]!='X') dfs(i,j-1); if(valid(i,j+1) && arr[i][j+1]!='X') dfs(i,j+1); } int main(){ string s; cin>>n>>m; for(ll i=0;i<n;i++) cin>>arr[i]; ll r1,c1,r2,c2; cin>>r1>>c1; cin>>r2>>c2; r1--; c1--; r2--; c2--; ll count=0; if(valid(r2-1,c2) && arr[r2-1][c2]!='X') count++; if(valid(r2+1,c2) && arr[r2+1][c2]!='X') count++; if(valid(r2,c2-1) && arr[r2][c2-1]!='X') count++; if(valid(r2,c2+1) && arr[r2][c2+1]!='X') count++; //cout<<count<<"\n"; string ans; ll flag=0; if(r1==r2 && c1==c2) { ans = (count>0 ? "YES" : "NO"); } else if((r2==(r1-1) && c2==c1) || (r2==(r1+1) && c1==c2) || (r2==r1 && c2==(c1-1)) || (r2==r1 && c2==(c1+1))){ if(arr[r2][c2]=='X') ans="YES"; else ans = (count>0 ? "YES":"NO"); } else{ if(arr[r2][c2]=='X'){ arr[r2][c2]='.'; flag = 1; } dfs(r1,c1); if(arr[r2][c2]=='X'){ if(flag) ans = "YES"; else{ ans = (count>1 ? "YES" : "NO"); } } else ans="NO"; } //for(ll i=0;i<n;i++) // cout<<arr[i]<<"\n"; cout<<ans<<endl; return 0; }
bbfe8bb395fef666244c4b921e3daccdff2c4d2c
b97f0d918bdce8d1b0a7fa9c4c044af1bc0766b2
/include/xercesc2.5/util/ArrayIndexOutOfBoundsException.hpp
e3ab259677d0781bef46aaefd1cb3459701710e6
[]
no_license
rauls/newscaster
47ade74338c9d7032a275858ebbaa3deb2aa0b6c
2557eee7b146454042e93382d734d7ca4a5ca2df
refs/heads/master
2021-01-01T20:16:34.236163
2014-02-08T09:17:31
2014-02-08T09:17:31
2,427,760
2
1
null
null
null
null
UTF-8
C++
false
false
3,047
hpp
/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id: ArrayIndexOutOfBoundsException.hpp,v 1.3 2002/12/04 02:32:43 knoaman Exp $ */ #if !defined(ARRAYINDEXOUTOFBOUNDSEXCEPTION_HPP) #define ARRAYINDEXOUTOFBOUNDSEXCEPTION_HPP #include <xercesc/util/XMLException.hpp> XERCES_CPP_NAMESPACE_BEGIN MakeXMLException(ArrayIndexOutOfBoundsException, XMLUTIL_EXPORT) XERCES_CPP_NAMESPACE_END #endif
59a465a19a024d6c44122d8674c7945655f035c7
2277375bd4a554d23da334dddd091a36138f5cae
/ThirdParty/Havok/Source/Common/Serialize/UnitTest/dataObjectTest.cpp
e7426a6fbf2f02d874ae8b8531fbb55c2699c0e8
[]
no_license
kevinmore/Project-Nebula
9a0553ccf8bdc1b4bb5e2588fc94516d9e3532bc
f6d284d4879ae1ea1bd30c5775ef8733cfafa71d
refs/heads/master
2022-10-22T03:55:42.596618
2020-06-19T09:07:07
2020-06-19T09:07:07
25,372,691
6
5
null
null
null
null
UTF-8
C++
false
false
12,127
cpp
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2013 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #include <Common/Serialize/hkSerialize.h> #include <Common/Base/UnitTest/hkUnitTest.h> #include <Common/Serialize/Data/Dict/hkDataObjectDict.h> static int dataObject() { { hkDataWorldDict world; hkTypeManager& typeManager = world.getTypeManager(); const char* class1Name = "Foo1"; const char* class2Name = "Foo2"; const char* m_pointer_Foo1 = "pointer_Foo1"; const char* m_int = "int"; const char* m_renamed_int = "renamed_int"; const char* m_array_struct_Foo1 = "array_struct_Foo1"; const char* m_tuple_struct_Foo1 = "tuple_struct_Foo1"; const char* m_tuple_int = "tuple_int"; const char* m_renamed_tuple_int = "renamed_tuple_int"; { // create class Foo1 { hkDataClass::Cinfo cinfo; cinfo.name = class1Name; cinfo.version = 0; cinfo.parent = HK_NULL; HK_TEST(world.findClass(cinfo.name) == HK_NULL); world.newClass(cinfo); HK_TEST(world.findClass(cinfo.name) != HK_NULL); } HK_ASSERT(0x66a67906, world.findClass(class1Name)); hkDataClass foo1class(world.findClass(class1Name)); world.addClassMember(foo1class, m_pointer_Foo1, typeManager.getClassPointer(class1Name), HK_NULL); HK_TEST(foo1class.getDeclaredMemberIndexByName(m_pointer_Foo1) != -1); world.addClassMember(foo1class, m_int, typeManager.getSubType(hkTypeManager::SUB_TYPE_INT), HK_NULL); HK_TEST(foo1class.getDeclaredMemberIndexByName(m_int) != -1); world.addClassMember(foo1class, m_tuple_int, typeManager.parseTypeExpression("{3}i"), HK_NULL); HK_TEST(foo1class.getDeclaredMemberIndexByName(m_tuple_int) != -1); // create class Foo2 { hkDataClass::Cinfo cinfo; cinfo.name = class2Name; cinfo.version = 0; cinfo.parent = HK_NULL; HK_TEST(world.findClass(cinfo.name) == HK_NULL); world.newClass(cinfo); HK_TEST(world.findClass(cinfo.name) != HK_NULL); } HK_ASSERT(0x66a67906, world.findClass(class2Name)); hkDataClass foo2class(world.findClass(class2Name)); world.addClassMember(foo2class, m_array_struct_Foo1, typeManager.makeArray(typeManager.addClass(foo1class.getName())), HK_NULL); HK_TEST(foo2class.getDeclaredMemberIndexByName(m_array_struct_Foo1) != -1); world.addClassMember(foo2class, m_int, typeManager.parseTypeExpression("i"), HK_NULL); HK_TEST(foo2class.getDeclaredMemberIndexByName(m_int) != -1); world.addClassMember(foo2class, m_tuple_int, typeManager.parseTypeExpression("{4}i"), HK_NULL); HK_TEST(foo2class.getDeclaredMemberIndexByName(m_tuple_int) != -1); world.addClassMember(foo2class, m_tuple_struct_Foo1, typeManager.makeTuple(typeManager.addClass(foo1class.getName()), 2), HK_NULL); HK_TEST(foo2class.getDeclaredMemberIndexByName(m_array_struct_Foo1) != -1); hkArray<hkDataObjectImpl*>::Temp objects; { // create objects HK_TEST(world.getContents().isNull()); world.findObjectsByBaseClass(foo1class.getName(), objects); HK_TEST(objects.getSize() == 0); // Foo1 hkDataObject obj1 = world.newObject(foo1class); HK_TEST(!obj1.isNull()); world.findObjectsByBaseClass(foo1class.getName(), objects); HK_TEST(objects.getSize() == 1); hkDataObject obj2 = world.newObject(foo1class); HK_TEST(!obj2.isNull()); world.findObjectsByBaseClass(foo1class.getName(), objects); HK_TEST(objects.getSize() == 2); // obj1 // - object member HK_TEST(!obj1.hasMember(m_pointer_Foo1)); HK_TEST(obj1[m_pointer_Foo1].asObject().isNull()); obj1[m_pointer_Foo1] = obj2; HK_TEST(obj1.hasMember(m_pointer_Foo1)); HK_TEST(!obj1[m_pointer_Foo1].asObject().isNull()); // - int member HK_TEST(!obj1.hasMember(m_int)); obj1[m_int] = 1; HK_TEST(obj1.hasMember(m_int)); // - tuple of ints member HK_TEST(!obj1.hasMember(m_tuple_int)); obj1[m_tuple_int].asArray()[0] = 1; obj1[m_tuple_int].asArray()[2] = -1; HK_TEST(obj1[m_tuple_int].asArray()[0].asInt() == 1); HK_TEST(obj1[m_tuple_int].asArray()[1].asInt() == 0); HK_TEST(obj1[m_tuple_int].asArray()[2].asInt() == -1); // obj2 // - object member HK_TEST(!obj2.hasMember(m_pointer_Foo1)); HK_TEST(obj2[m_pointer_Foo1].asObject().isNull()); obj2[m_pointer_Foo1] = obj1; HK_TEST(obj2.hasMember(m_pointer_Foo1)); HK_TEST(!obj2[m_pointer_Foo1].asObject().isNull()); // - int member HK_TEST(!obj2.hasMember(m_int)); obj2[m_int] = 2; HK_TEST(obj2.hasMember(m_int)); HK_TEST(obj2[m_int].asInt() == 2); // - tuple of ints member HK_TEST(obj1[m_pointer_Foo1].asObject()[m_int].asInt() == 2); HK_TEST(obj2[m_pointer_Foo1].asObject()[m_int].asInt() == 1); // world contents HK_TEST(!world.getContents().isNull()); HK_TEST(world.getContents()[m_int].asInt() == 1); // obj1, first created object // Foo2 hkDataObject obj3 = world.newObject(foo2class); HK_TEST(!obj3.isNull()); world.findObjectsByBaseClass(foo2class.getName(), objects); HK_TEST(objects.getSize() == 1); // obj3 // array of objects member HK_TEST(!obj3.hasMember(m_array_struct_Foo1)); HK_TEST(obj3[m_array_struct_Foo1].asArray().getSize() == 0); HK_TEST(obj3.hasMember(m_array_struct_Foo1)); obj3[m_array_struct_Foo1].asArray().setSize(2); obj3[m_array_struct_Foo1].asArray()[0] = obj1; obj3[m_array_struct_Foo1].asArray()[1] = obj2; obj3[m_array_struct_Foo1].asArray()[0].asObject()[m_int] = 100; HK_TEST(obj3[m_array_struct_Foo1].asArray()[0].asObject()[m_int].asInt() != obj1[m_int].asInt()); obj3[m_array_struct_Foo1].asArray()[0].asObject()[m_tuple_int].asArray()[1] = -2; HK_TEST(obj3[m_array_struct_Foo1].asArray()[0].asObject()[m_tuple_int].asArray()[1].asInt() != obj1[m_tuple_int].asArray()[1].asInt()); // int member HK_TEST(!obj3.hasMember(m_int)); obj3[m_int] = 3; HK_TEST(obj3[m_int].asInt() == 3); HK_TEST(obj3.hasMember(m_int)); // tuple of ints member HK_TEST(!obj3.hasMember(m_tuple_int)); obj3[m_tuple_int].asArray()[0] = 1; obj3[m_tuple_int].asArray()[2] = -1; HK_TEST(obj3.hasMember(m_tuple_int)); HK_TEST(obj3[m_tuple_int].asArray().getSize() == 4); HK_TEST(obj3[m_tuple_int].asArray()[0].asInt() == 1); HK_TEST(obj3[m_tuple_int].asArray()[1].asInt() == 0); HK_TEST(obj3[m_tuple_int].asArray()[2].asInt() == -1); HK_TEST(obj3[m_tuple_int].asArray()[3].asInt() == 0); // tuple of structs member HK_TEST(!obj3.hasMember(m_tuple_struct_Foo1)); obj3[m_tuple_struct_Foo1].asArray()[0] = obj1; obj3[m_tuple_struct_Foo1].asArray()[1] = obj2; HK_TEST(obj3.hasMember(m_tuple_struct_Foo1)); HK_TEST(obj3[m_tuple_struct_Foo1].asArray().getSize() == 2); HK_TEST(obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_int].asInt() == obj1[m_int].asInt()); obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_int] = 5; HK_TEST(obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_int].asInt() != obj1[m_int].asInt()); obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_tuple_int].asArray()[1] = 3; HK_TEST(obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_tuple_int].asArray()[1].asInt() != obj1[m_tuple_int].asArray()[1].asInt()); // rename foo1class class members // - int HK_TEST(foo1class.getDeclaredMemberIndexByName(m_renamed_int) == -1); world.renameClassMember(foo1class, m_int, m_renamed_int); HK_TEST(foo1class.getDeclaredMemberIndexByName(m_renamed_int) != -1); HK_TEST(foo1class.getDeclaredMemberIndexByName(m_int) == -1); HK_TEST(obj1[m_renamed_int].asInt() == 1); HK_TEST(obj2[m_renamed_int].asInt() == 2); HK_TEST(obj3[m_array_struct_Foo1].asArray()[0].asObject()[m_renamed_int].asInt() == 100); // obj1 copy HK_TEST(obj3[m_array_struct_Foo1].asArray()[1].asObject()[m_renamed_int].asInt() == 2); // obj2 copy HK_TEST(obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_renamed_int].asInt() == 5); // obj1 copy HK_TEST(obj3[m_tuple_struct_Foo1].asArray()[1].asObject()[m_renamed_int].asInt() == 2); // obj2 copy // - tuple of ints HK_TEST(foo1class.getDeclaredMemberIndexByName(m_renamed_tuple_int) == -1); world.renameClassMember(foo1class, m_tuple_int, m_renamed_tuple_int); HK_TEST(foo1class.getDeclaredMemberIndexByName(m_renamed_tuple_int) != -1); HK_TEST(foo1class.getDeclaredMemberIndexByName(m_tuple_int) == -1); HK_TEST(obj1[m_renamed_tuple_int].asArray()[0].asInt() == 1); HK_TEST(obj1[m_renamed_tuple_int].asArray()[1].asInt() == 0); HK_TEST(obj1[m_renamed_tuple_int].asArray()[2].asInt() == -1); HK_TEST(obj3[m_array_struct_Foo1].asArray()[0].asObject()[m_renamed_tuple_int].asArray()[0].asInt() == 1); // obj1 copy HK_TEST(obj3[m_array_struct_Foo1].asArray()[0].asObject()[m_renamed_tuple_int].asArray()[1].asInt() == -2); // obj1 copy HK_TEST(obj3[m_array_struct_Foo1].asArray()[0].asObject()[m_renamed_tuple_int].asArray()[2].asInt() == -1); // obj1 copy HK_TEST(obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_renamed_tuple_int].asArray()[0].asInt() == 1); // obj1 copy HK_TEST(obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_renamed_tuple_int].asArray()[1].asInt() == 3); // obj1 copy HK_TEST(obj3[m_tuple_struct_Foo1].asArray()[0].asObject()[m_renamed_tuple_int].asArray()[2].asInt() == -1); // obj1 copy } // // remove the class (should remove all foo1class objects) // // remove members of the foo1class type first world.removeClassMember(foo1class, m_pointer_Foo1); world.removeClassMember(foo2class, m_array_struct_Foo1); world.removeClassMember(foo2class, m_tuple_struct_Foo1); // remove foo1class world.removeClass(foo1class); HK_TEST(world.findClass(class1Name) == HK_NULL); world.findObjectsByBaseClass(class1Name, objects); HK_TEST(objects.getSize() == 0); HK_TEST(world.getContents().isNull()); } } { hkDataWorldDict world2; hkTypeManager& typeManager = world2.getTypeManager(); hkDataClass::Cinfo cinfo; cinfo.name = "Empty"; cinfo.parent = HK_NULL; cinfo.version = 0; hkDataClass emptyClass( world2.newClass(cinfo) ); cinfo.name = "Class0"; cinfo.members.expandOne().set("int0", typeManager.getSubType(hkTypeManager::SUB_TYPE_INT)); cinfo.members.expandOne().set("obj0", typeManager.getClassPointer("Empty")); hkDataClass class0( world2.newClass(cinfo) ); cinfo.name = "Class1"; cinfo.members[0].name = "int1"; cinfo.members[1].name = "obj1"; hkDataClass class1( world2.newClass(cinfo) ); hkDataObject empty = world2.newObject(emptyClass); hkDataObject obj0 = world2.newObject(class0); hkDataObject obj1 = world2.newObject(class1); obj0["int0"] = 10; obj1["int1"] = obj0["int0"]; obj0["obj0"] = empty; obj1["obj1"] = obj0["obj0"]; //obj1["obj1"] = 20; // should assert incompatible types //obj1["int1"] = empty; // should assert incompatible types } return 0; } #if defined(HK_COMPILER_MWERKS) # pragma fullpath_file on #endif HK_TEST_REGISTER(dataObject, "Fast", "Common/Test/UnitTest/Serialize/", __FILE__ ); /* * Havok SDK - Base file, BUILD(#20130912) * * Confidential Information of Havok. (C) Copyright 1999-2013 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available from [email protected]. * */
d051ac322740b783144e9c7f7c065738cbae9e0d
fc874d973d1681a05265c58ca82ada84d516ebcd
/esp32-camera-series.ino
edc854f0b68baef511b3b12ac640303c10547566
[]
no_license
Tsuchiya-Hayato/esp32
1c585d77ba71f78392de823dce8d2d39d524cfab
5057dd7dbda37ccc52cbd061638cdfec62b36296
refs/heads/master
2022-08-17T19:20:43.211363
2020-05-16T06:00:07
2020-05-16T06:00:07
264,365,490
0
0
null
null
null
null
UTF-8
C++
false
false
12,271
ino
#include <WiFi.h> #include <OneButton.h> #include "freertos/event_groups.h" #include <Wire.h> //#include <Adafruit_BME280.h> #include "esp_camera.h" #include "esp_wifi.h" /*************************************** * Board select **************************************/ //! [T_CAMERA_MIC] With SSD1306 with microphone // #define TTGO_T_CAMERA_MIC_V16 //! [T_CAMERA_V05 or TTGO_T_CAMERA_V1_7_2] With SSD1306, with BME280 position //! Different power management, the same pin #define TTGO_T_CAMERA_V05 //! [T_CAMERA_PLUS] With 240*240TFT display, SD card slot // #define TTGO_T_CAMERA_PLUS //! [T_JORNAL] The most simplified version, without PSRAM // #define TTGO_T_JORNAL /*************************************** * Modules **************************************/ #define ENABLE_SSD1306 //#define SOFTAP_MODE //The comment will be connected to the specified ssid //#define ENABLE_BME280 #define ENABLE_SLEEP //#define ENABLE_IP5306 #define ENABLE_AS312 #define ENABLE_BUTTON /*************************************** * WiFi **************************************/ #define WIFI_SSID "Wifi" #define WIFI_PASSWD "pass" /*************************************** * PinOUT **************************************/ #if defined(TTGO_T_CAMERA_MIC_V16) #define PWDN_GPIO_NUM -1 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 4 #define SIOD_GPIO_NUM 18 #define SIOC_GPIO_NUM 23 #define Y9_GPIO_NUM 36 #define Y8_GPIO_NUM 15 #define Y7_GPIO_NUM 12 #define Y6_GPIO_NUM 39 #define Y5_GPIO_NUM 35 #define Y4_GPIO_NUM 14 #define Y3_GPIO_NUM 13 #define Y2_GPIO_NUM 34 #define VSYNC_GPIO_NUM 5 #define HREF_GPIO_NUM 27 #define PCLK_GPIO_NUM 25 #define AS312_PIN 19 #define BUTTON_1 0 #define I2C_SDA 21 #define I2C_SCL 22 #undef ENABLE_BME280 #undef ENABLE_IP5306 #define SSD130_MODLE_TYPE GEOMETRY_128_64 #elif defined(TTGO_T_CAMERA_V05) || defined(TTGO_T_CAMERA_V1_7_2) #define PWDN_GPIO_NUM 26 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 32 #define SIOD_GPIO_NUM 13 #define SIOC_GPIO_NUM 12 #define Y9_GPIO_NUM 39 #define Y8_GPIO_NUM 36 #define Y7_GPIO_NUM 23 #define Y6_GPIO_NUM 18 #define Y5_GPIO_NUM 15 #define Y4_GPIO_NUM 4 #define Y3_GPIO_NUM 14 #define Y2_GPIO_NUM 5 #define VSYNC_GPIO_NUM 27 #define HREF_GPIO_NUM 25 #define PCLK_GPIO_NUM 19 #define AS312_PIN 33 #define BUTTON_1 34 #define I2C_SDA 21 #define I2C_SCL 22 #define SSD130_MODLE_TYPE GEOMETRY_128_64 #elif defined(TTGO_T_JORNAL) #define PWDN_GPIO_NUM -1 #define RESET_GPIO_NUM 15 #define XCLK_GPIO_NUM 27 #define SIOD_GPIO_NUM 25 #define SIOC_GPIO_NUM 23 #define Y9_GPIO_NUM 19 #define Y8_GPIO_NUM 36 #define Y7_GPIO_NUM 18 #define Y6_GPIO_NUM 39 #define Y5_GPIO_NUM 5 #define Y4_GPIO_NUM 34 #define Y3_GPIO_NUM 35 #define Y2_GPIO_NUM 17 #define VSYNC_GPIO_NUM 22 #define HREF_GPIO_NUM 26 #define PCLK_GPIO_NUM 21 #define I2C_SDA 14 #define I2C_SCL 13 #define BUTTON_1 32 #define SSD130_MODLE_TYPE GEOMETRY_128_32 #undef ENABLE_BME280 #undef ENABLE_AS312 #elif defined(TTGO_T_CAMERA_PLUS) #define PWDN_GPIO_NUM -1 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 4 #define SIOD_GPIO_NUM 18 #define SIOC_GPIO_NUM 23 #define Y9_GPIO_NUM 36 #define Y8_GPIO_NUM 37 #define Y7_GPIO_NUM 38 #define Y6_GPIO_NUM 39 #define Y5_GPIO_NUM 35 #define Y4_GPIO_NUM 26 #define Y3_GPIO_NUM 13 #define Y2_GPIO_NUM 34 #define VSYNC_GPIO_NUM 5 #define HREF_GPIO_NUM 27 #define PCLK_GPIO_NUM 25 #define I2C_SDA -1 #define I2C_SCL -1 #undef ENABLE_SSD1306 #undef ENABLE_BME280 #undef ENABLE_SLEEP #undef ENABLE_IP5306 #undef ENABLE_AS312 #undef ENABLE_BUTTON #else #error "Please select board type" #endif #ifdef ENABLE_SSD1306 #include "SSD1306.h" #include "OLEDDisplayUi.h" #define SSD1306_ADDRESS 0x3c SSD1306 oled(SSD1306_ADDRESS, I2C_SDA, I2C_SCL, SSD130_MODLE_TYPE); OLEDDisplayUi ui(&oled); #endif String ip; EventGroupHandle_t evGroup; #ifdef ENABLE_BUTTON OneButton button1(BUTTON_1, true); #endif #ifdef ENABLE_BME280 #define BEM280_ADDRESS 0X77 #define SEALEVELPRESSURE_HPA (1013.25) Adafruit_BME280 bme; #endif #define IP5306_ADDR 0X75 #define IP5306_REG_SYS_CTL0 0x00 void startCameraServer(); char buff[128]; #ifdef ENABLE_IP5306 bool setPowerBoostKeepOn(int en) { Wire.beginTransmission(IP5306_ADDR); Wire.write(IP5306_REG_SYS_CTL0); if (en) Wire.write(0x37); // Set bit1: 1 enable 0 disable boost keep on else Wire.write(0x35); // 0x37 is default reg value return Wire.endTransmission() == 0; } #endif void buttonClick() { static bool en = false; xEventGroupClearBits(evGroup, 1); sensor_t *s = esp_camera_sensor_get(); en = en ? 0 : 1; s->set_vflip(s, en); delay(200); xEventGroupSetBits(evGroup, 1); } void buttonLongPress() { #ifdef ENABLE_SSD1306 int x = oled.getWidth() / 2; int y = oled.getHeight() / 2; ui.disableAutoTransition(); oled.setTextAlignment(TEXT_ALIGN_CENTER); oled.setFont(ArialMT_Plain_10); oled.clear(); #endif #ifdef ENABLE_SLEEP if (PWDN_GPIO_NUM > 0) { pinMode(PWDN_GPIO_NUM, PULLUP); digitalWrite(PWDN_GPIO_NUM, HIGH); } oled.drawString(x, y, "Press again to wake up"); oled.display(); delay(6000); oled.clear(); oled.display(); oled.displayOff(); // esp_sleep_enable_ext0_wakeup((gpio_num_t )BUTTON_1, LOW); esp_sleep_enable_ext1_wakeup(((uint64_t)(((uint64_t)1) << BUTTON_1)), ESP_EXT1_WAKEUP_ALL_LOW); esp_deep_sleep_start(); #endif } #ifdef ENABLE_SSD1306 void drawFrame1(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) { display->setTextAlignment(TEXT_ALIGN_CENTER); int y1 = 25; if (oled.getHeight() == 32) { y1 = 10; } #ifdef SOFTAP_MODE display->setFont(ArialMT_Plain_10); display->drawString(64 + x, y1 + y, buff); #else display->setFont(ArialMT_Plain_16); display->drawString(64 + x, y1 + y, ip); #endif #ifdef ENABLE_AS312 if (digitalRead(AS312_PIN)) { display->drawString(64 + x, 5 + y, "AS312 Trigger"); } #endif } void drawFrame2(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y) { #ifdef ENABLE_BME280 static String temp, pressure, altitude, humidity; static uint64_t lastMs; if (millis() - lastMs > 2000) { lastMs = millis(); temp = "Temp:" + String(bme.readTemperature()) + " *C"; pressure = "Press:" + String(bme.readPressure() / 100.0F) + " hPa"; altitude = "Altitude:" + String(bme.readAltitude(SEALEVELPRESSURE_HPA)) + " m"; humidity = "Humidity:" + String(bme.readHumidity()) + " %"; } display->setFont(ArialMT_Plain_16); display->setTextAlignment(TEXT_ALIGN_LEFT); display->drawString(0 + x, 0 + y, temp); display->drawString(0 + x, 16 + y, pressure); display->drawString(0 + x, 32 + y, altitude); display->drawString(0 + x, 48 + y, humidity); #else display->setTextAlignment(TEXT_ALIGN_CENTER); display->setFont(ArialMT_Plain_10); if (oled.getHeight() == 32) { display->drawString( 64 + x, 0 + y, "Camera Ready! Use"); display->drawString(64 + x, 10 + y, "http://" + ip ); display->drawString(64 + x, 16 + y, "to connect"); } else { display->drawString( 64 + x, 5 + y, "Camera Ready! Use"); display->drawString(64 + x, 25 + y, "http://" + ip ); display->drawString(64 + x, 45 + y, "to connect"); } #endif } FrameCallback frames[] = {drawFrame1, drawFrame2}; #define FRAMES_SIZE (sizeof(frames) / sizeof(frames[0])) #endif void setup() { Serial.begin(115200); Serial.setDebugOutput(true); Serial.println(); #ifdef ENABLE_AS312 pinMode(AS312_PIN, INPUT); #endif if (I2C_SDA > 0) Wire.begin(I2C_SDA, I2C_SCL); #ifdef ENABLE_IP5306 bool isOk = setPowerBoostKeepOn(1); String info = "IP5306 KeepOn " + String((isOk ? "PASS" : "FAIL")); #endif #ifdef ENABLE_SSD1306 int x = oled.getWidth() / 2; int y = oled.getHeight() / 2; oled.init(); // Wire.setClock(100000); //! Reduce the speed and prevent the speed from being too high, causing the screen oled.setFont(ArialMT_Plain_16); oled.setTextAlignment(TEXT_ALIGN_CENTER); delay(50); oled.drawString(x, y - 10, "TTGO Camera"); oled.display(); #endif #ifdef ENABLE_IP5306 delay(1000); oled.setFont(ArialMT_Plain_10); oled.clear(); oled.drawString(x, y - 10, info); oled.display(); oled.setFont(ArialMT_Plain_16); delay(1000); #endif #ifdef ENABLE_BME280 if (!bme.begin(BEM280_ADDRESS)) { Serial.println("Could not find a valid BME280 sensor, check wiring!"); while (1); } #endif if (!(evGroup = xEventGroupCreate())) { Serial.println("evGroup Fail"); while (1); } xEventGroupSetBits(evGroup, 1); #ifdef TTGO_T_CAMERA_MIC_V16 /* IO13, IO14 is designed for JTAG by default, * to use it as generalized input, * firstly declair it as pullup input */ pinMode(13, INPUT_PULLUP); pinMode(14, INPUT_PULLUP); #endif camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.pixel_format = PIXFORMAT_JPEG; //init with high specs to pre-allocate larger buffers if (psramFound()) { config.frame_size = FRAMESIZE_UXGA; config.jpeg_quality = 10; config.fb_count = 2; } else { config.frame_size = FRAMESIZE_SVGA; config.jpeg_quality = 12; config.fb_count = 1; } esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init Fail"); #ifdef ENABLE_SSD1306 oled.clear(); oled.drawString(oled.getWidth() / 2, oled.getHeight() / 2, "Camera init Fail"); oled.display(); #endif while (1); } //drop down frame size for higher initial frame rate sensor_t *s = esp_camera_sensor_get(); s->set_framesize(s, FRAMESIZE_QVGA); #ifdef ENABLE_BUTTON button1.attachLongPressStart(buttonLongPress); button1.attachClick(buttonClick); #endif #ifdef SOFTAP_MODE Serial.println("Configuring access point..."); uint8_t mac[6]; esp_wifi_get_mac(WIFI_IF_AP, mac); sprintf(buff, "TTGO-CAMERA-%02X:%02X", mac[4], mac[5]); WiFi.softAP(buff); ip = WiFi.softAPIP().toString(); #else WiFi.begin(WIFI_SSID, WIFI_PASSWD); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); ip = WiFi.localIP().toString(); #endif startCameraServer(); delay(50); #ifdef ENABLE_SSD1306 ui.setTargetFPS(30); ui.setIndicatorPosition(BOTTOM); ui.setIndicatorDirection(LEFT_RIGHT); ui.setFrameAnimation(SLIDE_LEFT); ui.setFrames(frames, FRAMES_SIZE); ui.setTimePerFrame(6000); #endif Serial.print("Camera Ready! Use 'http://"); Serial.print(ip); Serial.println("' to connect"); } void loop() { #ifdef ENABLE_SSD1306 if (ui.update()) { #endif #ifdef ENABLE_BUTTON button1.tick(); #else delay(500); #endif #ifdef ENABLE_SSD1306 } #endif }
6a334c62de3fa51e448a8e1a46900009d86f28a1
4ccc93c43061a18de9064569020eb50509e75541
/components/autofill/core/browser/webdata/web_data_service_unittest.cc
e56d3f852601f844e4473f894e28c1b322cd2c19
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
SaschaMester/delicium
f2bdab35d51434ac6626db6d0e60ee01911797d7
b7bc83c3b107b30453998daadaeee618e417db5a
refs/heads/master
2021-01-13T02:06:38.740273
2015-07-06T00:22:53
2015-07-06T00:22:53
38,457,128
4
1
null
null
null
null
UTF-8
C++
false
false
19,535
cc
// Copyright 2013 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. #include <string> #include <vector> #include "base/basictypes.h" #include "base/bind.h" #include "base/files/scoped_temp_dir.h" #include "base/location.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/thread_task_runner_handle.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "components/autofill/core/browser/autofill_country.h" #include "components/autofill/core/browser/autofill_profile.h" #include "components/autofill/core/browser/credit_card.h" #include "components/autofill/core/browser/webdata/autofill_change.h" #include "components/autofill/core/browser/webdata/autofill_entry.h" #include "components/autofill/core/browser/webdata/autofill_table.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service_observer.h" #include "components/autofill/core/common/form_field_data.h" #include "components/webdata/common/web_data_results.h" #include "components/webdata/common/web_data_service_base.h" #include "components/webdata/common/web_data_service_consumer.h" #include "components/webdata/common/web_database_service.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::ASCIIToUTF16; using base::Time; using base::TimeDelta; using base::WaitableEvent; using testing::_; using testing::DoDefault; using testing::ElementsAreArray; namespace { template <class T> class AutofillWebDataServiceConsumer: public WebDataServiceConsumer { public: AutofillWebDataServiceConsumer() : handle_(0) {} virtual ~AutofillWebDataServiceConsumer() {} virtual void OnWebDataServiceRequestDone(WebDataServiceBase::Handle handle, const WDTypedResult* result) { handle_ = handle; const WDResult<T>* wrapped_result = static_cast<const WDResult<T>*>(result); result_ = wrapped_result->GetValue(); base::MessageLoop::current()->Quit(); } WebDataServiceBase::Handle handle() { return handle_; } T& result() { return result_; } private: WebDataServiceBase::Handle handle_; T result_; DISALLOW_COPY_AND_ASSIGN(AutofillWebDataServiceConsumer); }; } // namespace namespace autofill { static const int kWebDataServiceTimeoutSeconds = 8; ACTION_P(SignalEvent, event) { event->Signal(); } class MockAutofillWebDataServiceObserver : public AutofillWebDataServiceObserverOnDBThread { public: MOCK_METHOD1(AutofillEntriesChanged, void(const AutofillChangeList& changes)); MOCK_METHOD1(AutofillProfileChanged, void(const AutofillProfileChange& change)); }; class WebDataServiceTest : public testing::Test { public: WebDataServiceTest() : db_thread_("DBThread") {} protected: void SetUp() override { db_thread_.Start(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); base::FilePath path = temp_dir_.path().AppendASCII("TestWebDB"); wdbs_ = new WebDatabaseService(path, base::ThreadTaskRunnerHandle::Get(), db_thread_.task_runner()); wdbs_->AddTable(scoped_ptr<WebDatabaseTable>(new AutofillTable("en-US"))); wdbs_->LoadDatabase(); wds_ = new AutofillWebDataService( wdbs_, base::ThreadTaskRunnerHandle::Get(), db_thread_.task_runner(), WebDataServiceBase::ProfileErrorCallback()); wds_->Init(); } void TearDown() override { wds_->ShutdownOnUIThread(); wdbs_->ShutdownDatabase(); wds_ = NULL; wdbs_ = NULL; WaitForDatabaseThread(); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::MessageLoop::QuitClosure()); base::MessageLoop::current()->Run(); db_thread_.Stop(); } void WaitForDatabaseThread() { base::WaitableEvent done(false, false); db_thread_.task_runner()->PostTask( FROM_HERE, base::Bind(&base::WaitableEvent::Signal, base::Unretained(&done))); done.Wait(); } base::MessageLoopForUI message_loop_; base::Thread db_thread_; base::FilePath profile_dir_; scoped_refptr<AutofillWebDataService> wds_; scoped_refptr<WebDatabaseService> wdbs_; base::ScopedTempDir temp_dir_; }; class WebDataServiceAutofillTest : public WebDataServiceTest { public: WebDataServiceAutofillTest() : WebDataServiceTest(), unique_id1_(1), unique_id2_(2), test_timeout_(TimeDelta::FromSeconds(kWebDataServiceTimeoutSeconds)), done_event_(false, false) {} protected: virtual void SetUp() { WebDataServiceTest::SetUp(); name1_ = ASCIIToUTF16("name1"); name2_ = ASCIIToUTF16("name2"); value1_ = ASCIIToUTF16("value1"); value2_ = ASCIIToUTF16("value2"); void(AutofillWebDataService::*add_observer_func)( AutofillWebDataServiceObserverOnDBThread*) = &AutofillWebDataService::AddObserver; db_thread_.task_runner()->PostTask( FROM_HERE, base::Bind(add_observer_func, wds_, &observer_)); WaitForDatabaseThread(); } virtual void TearDown() { void(AutofillWebDataService::*remove_observer_func)( AutofillWebDataServiceObserverOnDBThread*) = &AutofillWebDataService::RemoveObserver; db_thread_.task_runner()->PostTask( FROM_HERE, base::Bind(remove_observer_func, wds_, &observer_)); WaitForDatabaseThread(); WebDataServiceTest::TearDown(); } void AppendFormField(const base::string16& name, const base::string16& value, std::vector<FormFieldData>* form_fields) { FormFieldData field; field.name = name; field.value = value; form_fields->push_back(field); } base::string16 name1_; base::string16 name2_; base::string16 value1_; base::string16 value2_; int unique_id1_, unique_id2_; const TimeDelta test_timeout_; testing::NiceMock<MockAutofillWebDataServiceObserver> observer_; WaitableEvent done_event_; }; TEST_F(WebDataServiceAutofillTest, FormFillAdd) { const AutofillChange expected_changes[] = { AutofillChange(AutofillChange::ADD, AutofillKey(name1_, value1_)), AutofillChange(AutofillChange::ADD, AutofillKey(name2_, value2_)) }; // This will verify that the correct notification is triggered, // passing the correct list of autofill keys in the details. EXPECT_CALL(observer_, AutofillEntriesChanged(ElementsAreArray(expected_changes))) .WillOnce(SignalEvent(&done_event_)); std::vector<FormFieldData> form_fields; AppendFormField(name1_, value1_, &form_fields); AppendFormField(name2_, value2_, &form_fields); wds_->AddFormFields(form_fields); // The event will be signaled when the mock observer is notified. done_event_.TimedWait(test_timeout_); AutofillWebDataServiceConsumer<std::vector<base::string16> > consumer; WebDataServiceBase::Handle handle; static const int limit = 10; handle = wds_->GetFormValuesForElementName( name1_, base::string16(), limit, &consumer); // The message loop will exit when the consumer is called. base::MessageLoop::current()->Run(); EXPECT_EQ(handle, consumer.handle()); ASSERT_EQ(1U, consumer.result().size()); EXPECT_EQ(value1_, consumer.result()[0]); } TEST_F(WebDataServiceAutofillTest, FormFillRemoveOne) { // First add some values to autofill. EXPECT_CALL(observer_, AutofillEntriesChanged(_)) .WillOnce(SignalEvent(&done_event_)); std::vector<FormFieldData> form_fields; AppendFormField(name1_, value1_, &form_fields); wds_->AddFormFields(form_fields); // The event will be signaled when the mock observer is notified. done_event_.TimedWait(test_timeout_); // This will verify that the correct notification is triggered, // passing the correct list of autofill keys in the details. const AutofillChange expected_changes[] = { AutofillChange(AutofillChange::REMOVE, AutofillKey(name1_, value1_)) }; EXPECT_CALL(observer_, AutofillEntriesChanged(ElementsAreArray(expected_changes))) .WillOnce(SignalEvent(&done_event_)); wds_->RemoveFormValueForElementName(name1_, value1_); // The event will be signaled when the mock observer is notified. done_event_.TimedWait(test_timeout_); } TEST_F(WebDataServiceAutofillTest, FormFillRemoveMany) { TimeDelta one_day(TimeDelta::FromDays(1)); Time t = Time::Now(); EXPECT_CALL(observer_, AutofillEntriesChanged(_)) .WillOnce(SignalEvent(&done_event_)); std::vector<FormFieldData> form_fields; AppendFormField(name1_, value1_, &form_fields); AppendFormField(name2_, value2_, &form_fields); wds_->AddFormFields(form_fields); // The event will be signaled when the mock observer is notified. done_event_.TimedWait(test_timeout_); // This will verify that the correct notification is triggered, // passing the correct list of autofill keys in the details. const AutofillChange expected_changes[] = { AutofillChange(AutofillChange::REMOVE, AutofillKey(name1_, value1_)), AutofillChange(AutofillChange::REMOVE, AutofillKey(name2_, value2_)) }; EXPECT_CALL(observer_, AutofillEntriesChanged(ElementsAreArray(expected_changes))) .WillOnce(SignalEvent(&done_event_)); wds_->RemoveFormElementsAddedBetween(t, t + one_day); // The event will be signaled when the mock observer is notified. done_event_.TimedWait(test_timeout_); } TEST_F(WebDataServiceAutofillTest, ProfileAdd) { AutofillProfile profile; // Check that GUID-based notification was sent. const AutofillProfileChange expected_change( AutofillProfileChange::ADD, profile.guid(), &profile); EXPECT_CALL(observer_, AutofillProfileChanged(expected_change)) .WillOnce(SignalEvent(&done_event_)); wds_->AddAutofillProfile(profile); done_event_.TimedWait(test_timeout_); // Check that it was added. AutofillWebDataServiceConsumer<std::vector<AutofillProfile*> > consumer; WebDataServiceBase::Handle handle = wds_->GetAutofillProfiles(&consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(handle, consumer.handle()); ASSERT_EQ(1U, consumer.result().size()); EXPECT_EQ(profile, *consumer.result()[0]); STLDeleteElements(&consumer.result()); } TEST_F(WebDataServiceAutofillTest, ProfileRemove) { AutofillProfile profile; // Add a profile. EXPECT_CALL(observer_, AutofillProfileChanged(_)) .WillOnce(SignalEvent(&done_event_)); wds_->AddAutofillProfile(profile); done_event_.TimedWait(test_timeout_); // Check that it was added. AutofillWebDataServiceConsumer<std::vector<AutofillProfile*> > consumer; WebDataServiceBase::Handle handle = wds_->GetAutofillProfiles(&consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(handle, consumer.handle()); ASSERT_EQ(1U, consumer.result().size()); EXPECT_EQ(profile, *consumer.result()[0]); STLDeleteElements(&consumer.result()); // Check that GUID-based notification was sent. const AutofillProfileChange expected_change( AutofillProfileChange::REMOVE, profile.guid(), NULL); EXPECT_CALL(observer_, AutofillProfileChanged(expected_change)) .WillOnce(SignalEvent(&done_event_)); // Remove the profile. wds_->RemoveAutofillProfile(profile.guid()); done_event_.TimedWait(test_timeout_); // Check that it was removed. AutofillWebDataServiceConsumer<std::vector<AutofillProfile*> > consumer2; WebDataServiceBase::Handle handle2 = wds_->GetAutofillProfiles(&consumer2); base::MessageLoop::current()->Run(); EXPECT_EQ(handle2, consumer2.handle()); ASSERT_EQ(0U, consumer2.result().size()); } TEST_F(WebDataServiceAutofillTest, ProfileUpdate) { // The GUIDs are alphabetical for easier testing. AutofillProfile profile1("6141084B-72D7-4B73-90CF-3D6AC154673B", "http://example.com"); profile1.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Abe")); AutofillProfile profile2("087151C8-6AB1-487C-9095-28E80BE5DA15", "http://example.com"); profile2.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Alice")); EXPECT_CALL(observer_, AutofillProfileChanged(_)) .WillOnce(DoDefault()) .WillOnce(SignalEvent(&done_event_)); wds_->AddAutofillProfile(profile1); wds_->AddAutofillProfile(profile2); done_event_.TimedWait(test_timeout_); // Check that they were added. AutofillWebDataServiceConsumer<std::vector<AutofillProfile*> > consumer; WebDataServiceBase::Handle handle = wds_->GetAutofillProfiles(&consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(handle, consumer.handle()); ASSERT_EQ(2U, consumer.result().size()); EXPECT_EQ(profile2, *consumer.result()[0]); EXPECT_EQ(profile1, *consumer.result()[1]); STLDeleteElements(&consumer.result()); AutofillProfile profile2_changed(profile2); profile2_changed.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bill")); const AutofillProfileChange expected_change( AutofillProfileChange::UPDATE, profile2.guid(), &profile2_changed); EXPECT_CALL(observer_, AutofillProfileChanged(expected_change)) .WillOnce(SignalEvent(&done_event_)); // Update the profile. wds_->UpdateAutofillProfile(profile2_changed); done_event_.TimedWait(test_timeout_); // Check that the updates were made. AutofillWebDataServiceConsumer<std::vector<AutofillProfile*> > consumer2; WebDataServiceBase::Handle handle2 = wds_->GetAutofillProfiles(&consumer2); base::MessageLoop::current()->Run(); EXPECT_EQ(handle2, consumer2.handle()); ASSERT_EQ(2U, consumer2.result().size()); EXPECT_EQ(profile2_changed, *consumer2.result()[0]); EXPECT_NE(profile2, *consumer2.result()[0]); EXPECT_EQ(profile1, *consumer2.result()[1]); STLDeleteElements(&consumer2.result()); } TEST_F(WebDataServiceAutofillTest, CreditAdd) { CreditCard card; wds_->AddCreditCard(card); WaitForDatabaseThread(); // Check that it was added. AutofillWebDataServiceConsumer<std::vector<CreditCard*> > consumer; WebDataServiceBase::Handle handle = wds_->GetCreditCards(&consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(handle, consumer.handle()); ASSERT_EQ(1U, consumer.result().size()); EXPECT_EQ(card, *consumer.result()[0]); STLDeleteElements(&consumer.result()); } TEST_F(WebDataServiceAutofillTest, CreditCardRemove) { CreditCard credit_card; // Add a credit card. wds_->AddCreditCard(credit_card); WaitForDatabaseThread(); // Check that it was added. AutofillWebDataServiceConsumer<std::vector<CreditCard*> > consumer; WebDataServiceBase::Handle handle = wds_->GetCreditCards(&consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(handle, consumer.handle()); ASSERT_EQ(1U, consumer.result().size()); EXPECT_EQ(credit_card, *consumer.result()[0]); STLDeleteElements(&consumer.result()); // Remove the credit card. wds_->RemoveCreditCard(credit_card.guid()); WaitForDatabaseThread(); // Check that it was removed. AutofillWebDataServiceConsumer<std::vector<CreditCard*> > consumer2; WebDataServiceBase::Handle handle2 = wds_->GetCreditCards(&consumer2); base::MessageLoop::current()->Run(); EXPECT_EQ(handle2, consumer2.handle()); ASSERT_EQ(0U, consumer2.result().size()); } TEST_F(WebDataServiceAutofillTest, CreditUpdate) { CreditCard card1("E4D2662E-5E16-44F3-AF5A-5A77FAE4A6F3", "https://ejemplo.mx"); card1.SetRawInfo(CREDIT_CARD_NAME, ASCIIToUTF16("Abe")); CreditCard card2("B9C52112-BD5F-4080-84E1-C651D2CB90E2", "https://example.com"); card2.SetRawInfo(CREDIT_CARD_NAME, ASCIIToUTF16("Alice")); wds_->AddCreditCard(card1); wds_->AddCreditCard(card2); WaitForDatabaseThread(); // Check that they got added. AutofillWebDataServiceConsumer<std::vector<CreditCard*> > consumer; WebDataServiceBase::Handle handle = wds_->GetCreditCards(&consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(handle, consumer.handle()); ASSERT_EQ(2U, consumer.result().size()); EXPECT_EQ(card2, *consumer.result()[0]); EXPECT_EQ(card1, *consumer.result()[1]); STLDeleteElements(&consumer.result()); CreditCard card2_changed(card2); card2_changed.SetRawInfo(CREDIT_CARD_NAME, ASCIIToUTF16("Bill")); wds_->UpdateCreditCard(card2_changed); WaitForDatabaseThread(); // Check that the updates were made. AutofillWebDataServiceConsumer<std::vector<CreditCard*> > consumer2; WebDataServiceBase::Handle handle2 = wds_->GetCreditCards(&consumer2); base::MessageLoop::current()->Run(); EXPECT_EQ(handle2, consumer2.handle()); ASSERT_EQ(2U, consumer2.result().size()); EXPECT_NE(card2, *consumer2.result()[0]); EXPECT_EQ(card2_changed, *consumer2.result()[0]); EXPECT_EQ(card1, *consumer2.result()[1]); STLDeleteElements(&consumer2.result()); } TEST_F(WebDataServiceAutofillTest, AutofillRemoveModifiedBetween) { // Add a profile. EXPECT_CALL(observer_, AutofillProfileChanged(_)) .WillOnce(SignalEvent(&done_event_)); AutofillProfile profile; wds_->AddAutofillProfile(profile); done_event_.TimedWait(test_timeout_); // Check that it was added. AutofillWebDataServiceConsumer<std::vector<AutofillProfile*> > profile_consumer; WebDataServiceBase::Handle handle = wds_->GetAutofillProfiles(&profile_consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(handle, profile_consumer.handle()); ASSERT_EQ(1U, profile_consumer.result().size()); EXPECT_EQ(profile, *profile_consumer.result()[0]); STLDeleteElements(&profile_consumer.result()); // Add a credit card. CreditCard credit_card; wds_->AddCreditCard(credit_card); WaitForDatabaseThread(); // Check that it was added. AutofillWebDataServiceConsumer<std::vector<CreditCard*> > card_consumer; handle = wds_->GetCreditCards(&card_consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(handle, card_consumer.handle()); ASSERT_EQ(1U, card_consumer.result().size()); EXPECT_EQ(credit_card, *card_consumer.result()[0]); STLDeleteElements(&card_consumer.result()); // Check that GUID-based notification was sent for the profile. const AutofillProfileChange expected_profile_change( AutofillProfileChange::REMOVE, profile.guid(), NULL); EXPECT_CALL(observer_, AutofillProfileChanged(expected_profile_change)) .WillOnce(SignalEvent(&done_event_)); // Remove the profile using time range of "all time". wds_->RemoveAutofillDataModifiedBetween(Time(), Time()); done_event_.TimedWait(test_timeout_); WaitForDatabaseThread(); // Check that the profile was removed. AutofillWebDataServiceConsumer<std::vector<AutofillProfile*> > profile_consumer2; WebDataServiceBase::Handle handle2 = wds_->GetAutofillProfiles(&profile_consumer2); base::MessageLoop::current()->Run(); EXPECT_EQ(handle2, profile_consumer2.handle()); ASSERT_EQ(0U, profile_consumer2.result().size()); // Check that the credit card was removed. AutofillWebDataServiceConsumer<std::vector<CreditCard*> > card_consumer2; handle2 = wds_->GetCreditCards(&card_consumer2); base::MessageLoop::current()->Run(); EXPECT_EQ(handle2, card_consumer2.handle()); ASSERT_EQ(0U, card_consumer2.result().size()); } } // namespace autofill
be52a641e0bf73b3b34adb78e09f0cd995646f69
46c22f946935fb08dc995657c42934d14b1b0f37
/src/core/ssaa.cc
eda5b5bdb5020d0157d5a2f362b4cb2abf8a9e72
[ "MIT" ]
permissive
zhehangd/qjulia2
480ef1fdb5cf025bb98dfb07b9ddaee47b074c93
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
refs/heads/master
2021-06-14T10:30:01.765623
2021-04-10T02:48:44
2021-04-10T02:48:44
166,139,290
0
0
null
null
null
null
UTF-8
C++
false
false
2,370
cc
/* MIT License Copyright (c) 2019 Zhehang Ding Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "ssaa.h" namespace qjulia { std::vector<AAFilter> GenerateSSAAFilters(AAOption opt) { std::vector<AAFilter> filters; if (opt == AAOption::kOff) { filters.emplace_back(0, 0, 1); } else if (opt == AAOption::kSSAA6x) { filters.emplace_back(-0.52f, 0.38f, 0.128f); filters.emplace_back( 0.41f, 0.56f, 0.119f); filters.emplace_back( 0.27f, 0.08f, 0.294f); filters.emplace_back(-0.17f, -0.29f, 0.249f); filters.emplace_back( 0.58f, -0.55f, 0.104f); filters.emplace_back(-0.31f, -0.71f, 0.106f); } else if (opt == AAOption::kSSAA64x) { for (int r = 0; r < 8; ++r) { for (int c = 0; c < 8; ++c) { float fr = r / 8.0f; float fc = c / 8.0f; filters.emplace_back(fr, fc, 1.0 / 64.0); } } } else if (opt == AAOption::kSSAA256x) { for (int r = 0; r < 16; ++r) { for (int c = 0; c < 16; ++c) { float fr = r / 16.0f; float fc = c / 16.0f; filters.emplace_back(fr, fc, 1.0 / 256.0); } } } return filters; } const AAFilter static_aa_samples[6] = { AAFilter(-0.52f, 0.38f, 0.128f), AAFilter( 0.41f, 0.56f, 0.119f), AAFilter( 0.27f, 0.08f, 0.294f), AAFilter(-0.17f, -0.29f, 0.249f), AAFilter( 0.58f, -0.55f, 0.104f), AAFilter(-0.31f, -0.71f, 0.106f), }; }
7e979c6569d4b14036af0b2de0cb3ea51496866d
e204913fed67f1dfac2d338592fd0929359f1577
/components/Common/Slices/NetworkMessage.hpp
24111c93f7d8d1b59ebe3a3118df23bc15c3ee45
[]
no_license
javpicorel/memory_tool
33371dc778b2a1c4351661887444570265808356
f88ea71a26c94a368675740205779d971ae510f5
refs/heads/master
2021-01-11T03:52:40.234629
2017-03-26T23:23:24
2017-03-26T23:23:24
71,281,348
1
0
null
null
null
null
UTF-8
C++
false
false
3,520
hpp
// DO-NOT-REMOVE begin-copyright-block // // Redistributions of any form whatsoever must retain and/or include the // following acknowledgment, notices and disclaimer: // // This product includes software developed by Carnegie Mellon University. // // Copyright 2006 - 2008 by Eric Chung, Michael Ferdman, Brian Gold, Nikos // Hardavellas, Jangwoo Kim, Ippokratis Pandis, Minglong Shao, Jared Smolens, // Stephen Somogyi, Evangelos Vlachos, Tom Wenisch, Anastassia Ailamaki, // Babak Falsafi and James C. Hoe for the SimFlex Project, Computer // Architecture Lab at Carnegie Mellon, Carnegie Mellon University. // // For more information, see the SimFlex project website at: // http://www.ece.cmu.edu/~simflex // // You may not use the name 'Carnegie Mellon University' or derivations // thereof to endorse or promote products derived from this software. // // If you modify the software you must place a notice on or within any // modified version provided or made available to any third party stating // that you have modified the software. The notice shall include at least // your name, address, phone number, email address and the date and purpose // of the modification. // // THE SOFTWARE IS PROVIDED 'AS-IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER // EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO ANY WARRANTY // THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS OR BE ERROR-FREE AND ANY // IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, // TITLE, OR NON-INFRINGEMENT. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY // BE LIABLE FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO DIRECT, INDIRECT, // SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN // ANY WAY CONNECTED WITH THIS SOFTWARE (WHETHER OR NOT BASED UPON WARRANTY, // CONTRACT, TORT OR OTHERWISE). // // DO-NOT-REMOVE end-copyright-block #ifndef FLEXUS_SLICES__NETWORKMESSAGE_HPP_INCLUDED #define FLEXUS_SLICES__NETWORKMESSAGE_HPP_INCLUDED #ifdef FLEXUS_NetworkMessage_TYPE_PROVIDED #error "Only one component may provide the Flexus::SharedTypes::NetworkMessage data type" #endif #define FLEXUS_NetworkMessage_TYPE_PROVIDED #include <core/boost_extensions/intrusive_ptr.hpp> namespace Flexus { namespace SharedTypes { struct NetworkMessage : public boost::counted_base { int src; // source node int dest; // destination node int vc; // virtual channel int size; // message (i.e. payload) size int src_port; int dst_port; NetworkMessage() : src(-1) , dest(-1) , vc(-1) , size(-1) , src_port(-1) , dst_port(-1) {} }; } //End SharedTypes } //End Flexus #endif //FLEXUS_SLICES__NETWORKMESSAGE_HPP_INCLUDED
fc17c293bcb49223ded700d4c36d95de905e1d38
4f752cd1a14daa1a6d18217549738a5616478ea0
/VideoPlayer/stdafx.cpp
9c0478541533124b7f11fefddb4589c7d47f2411
[]
no_license
preferencia/VideoUtility
459a7b02401e4815f206af59c1977148fc386ca2
c20b89e2d97fa901911b568880aa95872ee954ae
refs/heads/master
2021-01-10T04:38:02.190610
2016-04-10T08:54:46
2016-04-10T08:54:46
55,852,186
0
0
null
null
null
null
UHC
C++
false
false
329
cpp
// stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다. // VideoPlayer.pch는 미리 컴파일된 헤더가 됩니다. // stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다. #include "stdafx.h" // TODO: 필요한 추가 헤더는 // 이 파일이 아닌 STDAFX.H에서 참조합니다.
4290b0ab3173a4962081c8406ac88c7c4e3d7965
b6607ecc11e389cc56ee4966293de9e2e0aca491
/acmp.ru/101...200/126/126.cpp
30b08cf9226ba2f3e1e67166b7d52e042447fa1c
[]
no_license
BekzhanKassenov/olymp
ec31cefee36d2afe40eeead5c2c516f9bf92e66d
e3013095a4f88fb614abb8ac9ba532c5e955a32e
refs/heads/master
2022-09-21T10:07:10.232514
2021-11-01T16:40:24
2021-11-01T16:40:24
39,900,971
5
0
null
null
null
null
UTF-8
C++
false
false
555
cpp
#include <iostream> #include <cstdio> #include <vector> using namespace std; const int inf = 1000000000; int main() { freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int n; cin >> n; vector <vector <int> > g(n, vector <int> (n)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> g[i][j]; int val = inf; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) if (i != j && j != k && i!=k) val = min (val, g[i][j] + g[j][k] + g[i][k]); cout << val; return 0; }
067684c72b807fd03c56684dc437f9fa05390b1e
2563b5ee81624c0761b2d6086efcdab0be8bef23
/kernel/kernel/fs/buffer.cpp
6da553572e9cdf331cd2da0ad7ff09f152bbd3c5
[ "MIT" ]
permissive
reymontero/Onyx
095df1b876454fcafdf795df6912b218ce8a5d3d
6f9b1d72c3e2dccb744869f19d10297336f045b1
refs/heads/master
2023-04-18T01:56:02.715716
2021-05-09T14:06:15
2021-05-09T14:06:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,614
cpp
/* * Copyright (c) 2020 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ #include <stdio.h> #include <errno.h> #include <onyx/block.h> #include <onyx/buffer.h> #include <onyx/mm/pool.hpp> #include <onyx/mm/flush.h> #include <onyx/cpu.h> memory_pool<block_buf, 0> block_buf_pool; ssize_t block_buf_flush(flush_object *fo); bool block_buf_is_dirty(flush_object *fo); static void block_buf_set_dirty(bool dirty, flush_object *fo); const struct flush_ops blockbuf_fops = { .flush = block_buf_flush, .is_dirty = block_buf_is_dirty, .set_dirty = block_buf_set_dirty }; #define block_buf_from_flush_obj(fo) container_of(fo, block_buf, flush_obj) ssize_t block_buf_flush(flush_object *fo) { auto buf = block_buf_from_flush_obj(fo); sector_t disk_sect = (buf->block_nr * buf->block_size) / buf->dev->sector_size; struct page_iov vec; vec.length = buf->block_size; vec.page_off = buf->page_off; vec.page = buf->this_page; struct bio_req r{}; r.nr_vecs = 1; r.sector_number = disk_sect; r.flags = BIO_REQ_WRITE_OP; r.vec = &vec; __atomic_fetch_or(&buf->flags, BLOCKBUF_FLAG_UNDER_WB, __ATOMIC_RELAXED); __atomic_fetch_or(&vec.page->flags, PAGE_FLAG_FLUSHING, __ATOMIC_RELAXED); if(bio_submit_request(buf->dev, &r) < 0) return -EIO; #if 0 printk("Flushed #%lu[sector %lu].\n", buf->block_nr, disk_sect); #endif return buf->block_size; } bool block_buf_is_dirty(flush_object *fo) { auto buf = block_buf_from_flush_obj(fo); return buf->flags & BLOCKBUF_FLAG_DIRTY; } block_buf *block_buf_from_page(struct page *p) { return reinterpret_cast<block_buf *>(p->priv); } bool page_has_dirty_bufs(struct page *p) { auto buf = reinterpret_cast<block_buf *>(p->priv); bool has_dirty_buf = false; while(buf) { if(buf->flags & BLOCKBUF_FLAG_DIRTY) { has_dirty_buf = true; break; } buf = buf->next; } return has_dirty_buf; } static void block_buf_set_dirty(bool dirty, flush_object *fo) { auto buf = block_buf_from_flush_obj(fo); auto page = buf->this_page; if(dirty) { while(buf->flags & BLOCKBUF_FLAG_UNDER_WB) cpu_relax(); unsigned long old_flags = __atomic_fetch_or(&buf->flags, BLOCKBUF_FLAG_DIRTY, __ATOMIC_RELAXED); __atomic_fetch_or(&page->flags, PAGE_FLAG_DIRTY, __ATOMIC_RELAXED); if(!(old_flags & BLOCKBUF_FLAG_DIRTY)) { flush_add_buf(fo); } } else { #if 0 printk("unset dirty block #%lu\n", buf->block_nr); #endif __atomic_and_fetch(&buf->flags, ~(BLOCKBUF_FLAG_DIRTY | BLOCKBUF_FLAG_UNDER_WB), __ATOMIC_RELAXED); if(!page_has_dirty_bufs(page)) __atomic_and_fetch(&page->flags, ~(PAGE_FLAG_DIRTY | PAGE_FLAG_FLUSHING), __ATOMIC_RELAXED); } } struct block_buf *page_add_blockbuf(struct page *page, unsigned int page_off) { assert(page->flags & PAGE_FLAG_BUFFER); auto buf = block_buf_pool.allocate(); if(!buf) { return nullptr; } buf->page_off = page_off; buf->this_page = page; buf->next = nullptr; buf->flush_obj.ops = &blockbuf_fops; buf->refc = 1; buf->flags = 0; /* It's better to do this naively using O(n) as to keep memory usage per-struct page low. */ /* We're not likely to hit substancial n's anyway */ block_buf **pp = reinterpret_cast<block_buf **>(&page->priv); while(*pp) pp = &(*pp)->next; *pp = buf; return buf; } void block_buf_remove(struct block_buf *buf) { struct page *page = buf->this_page; block_buf **pp = reinterpret_cast<block_buf **>(&page->priv); while(*pp) { block_buf *b = *pp; if(b == buf) { *pp = buf->next; break; } pp = &(*pp)->next; } } void block_buf_writeback(struct block_buf *buf) { flush_sync_one(&buf->flush_obj); } void block_buf_free(struct block_buf *buf) { if(buf->flags & BLOCKBUF_FLAG_DIRTY) block_buf_writeback(buf); block_buf_remove(buf); block_buf_pool.free(buf); } void page_destroy_block_bufs(struct page *page) { auto b = reinterpret_cast<block_buf *>(page->priv); block_buf *next = nullptr; while(b) { next = b->next; block_buf_free(b); b = next; } } /* Hmmm - I don't like this. Like linux, We're limiting ourselves to * block_size <= page_size here... */ vmo_status_t bbuffer_commit(vm_object *vmo, size_t off, page **ppage) { vmo_status_t st = VMO_STATUS_BUS_ERROR; page *p = alloc_page(PAGE_ALLOC_NO_ZERO); if(!p) return VMO_STATUS_OUT_OF_MEM; p->flags |= PAGE_FLAG_BUFFER; auto blkdev = reinterpret_cast<blockdev*>(vmo->priv); sector_t sec_nr = off / blkdev->sector_size; if(off % blkdev->sector_size) { free_page(p); printf("bbuffer_commit: Cannot read unaligned offset %lu\n", off); return VMO_STATUS_BUS_ERROR; } auto sb = blkdev->sb; assert(sb != nullptr); struct page_iov vec; vec.length = PAGE_SIZE; vec.page = p; vec.page_off = 0; struct bio_req r{}; r.nr_vecs = 1; r.vec = &vec; r.sector_number = sec_nr; r.flags = BIO_REQ_READ_OP; auto block_size = sb->s_block_size; auto nr_blocks = PAGE_SIZE / block_size; size_t starting_block_nr = off / block_size; size_t curr_off = 0; int iost = bio_submit_request(blkdev, &r); if(iost < 0) goto error; for(size_t i = 0; i < nr_blocks; i++) { struct block_buf *b; if(!(b = page_add_blockbuf(p, curr_off))) { page_destroy_block_bufs(p); st = VMO_STATUS_OUT_OF_MEM; goto error; } b->block_nr = starting_block_nr + i; b->block_size = block_size; b->dev = blkdev; curr_off += block_size; } *ppage = p; return VMO_STATUS_OK; error: free_page(p); return st; } struct block_buf *sb_read_block(const struct superblock *sb, unsigned long block) { struct blockdev *dev = sb->s_bdev; size_t real_off = sb->s_block_size * block; size_t aligned_off = real_off & -PAGE_SIZE; struct page *page; auto st = vmo_get(dev->vmo, aligned_off, VMO_GET_MAY_POPULATE, &page); if(st != VMO_STATUS_OK) return nullptr; auto buf = reinterpret_cast<block_buf *>(page->priv); while(buf && buf->block_nr != block) { buf = buf->next; } if(unlikely(!buf)) { size_t page_off = real_off - aligned_off; sector_t aligned_block = aligned_off / sb->s_block_size; #if 0 printk("Aligned block: %lx\n", aligned_block); printk("Aligned off %lx real off %lx\n", aligned_off, real_off); #endif sector_t block_nr = aligned_block + ((real_off - aligned_off) / sb->s_block_size); if(!(buf = page_add_blockbuf(page, page_off))) { page_unref(page); return nullptr; } buf->block_nr = block_nr; buf->block_size = sb->s_block_size; buf->dev = sb->s_bdev; } block_buf_get(buf); page_unref(page); return buf; } struct sb { uint32_t s_inodes_count; uint32_t s_blocks_count; uint32_t s_r_blocks_count; uint32_t s_free_blocks_count; uint32_t s_free_inodes_count; uint32_t s_first_data_block; uint32_t s_log_block_size; uint32_t s_log_frag_size; uint32_t s_blocks_per_group; uint32_t s_frags_per_group; uint32_t s_inodes_per_group; uint32_t s_mtime; uint32_t s_wtime; uint16_t s_mnt_count; uint16_t s_max_mnt_count; uint16_t s_magic; }; void block_buf_dirty(block_buf *buf) { if(buf->block_nr == 0) { sb *s = (sb *) ((char *) block_buf_data(buf) + 1024); assert(s->s_magic == 0xef53); } //printk("Block number %lu dirty!\n", buf->block_nr); block_buf_set_dirty(true, &buf->flush_obj); } void page_remove_block_buf(struct page *page, size_t offset, size_t end) { block_buf **pp = (block_buf **) &page->priv; while(*pp != nullptr) { if((*pp)->page_off >= offset && (*pp)->page_off < end) { auto bbuf = *pp; *pp = (*pp)->next; block_buf_free(bbuf); } else pp = &(*pp)->next; } }
1229f69bd2044fd666344e9ebb14a40abb09af48
b8e52aa88a8c6c97c67c4f971ba9d62c3949b252
/lesson04/Line2.cpp
29933ef356568c93b3d6f2ced8a8702d07b84cbe
[]
no_license
kidcozyboy/2021s-cpp
2cee9d6ac840154a3876fefecb4a29988299ecb0
444c18663e6a53b279e7de823e00c15ab622ea21
refs/heads/master
2023-06-19T14:13:05.709782
2021-07-15T13:59:55
2021-07-15T13:59:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
878
cpp
#include <cmath> #include <sstream> #include "Line2.h" using namespace std; Line2::Line2(Point2 *pp): p0(pp[0]), p1(pp[1]){ } Line2::Line2(const Point2& p0, const Point2& p1): p0(p0), p1(p1){ cout << "Line2コピー" << endl; } Line2::Line2(double x0, double y0, double x1, double y1): p0(Point2(x0, y0)), p1(Point2(x1, y1)){ cout << "Line2引数付き" << endl; } Line2& Line2::operator=(const Line2 &line) { if (this != &line) { p0 = line.p0; p1 = line.p1; } return *this; } double Line2::length() { return sqrt(pow((p1.getX() - p0.getX()), 2) + pow((p1.getY() - p0.getY()), 2)); } string Line2::toString() { stringstream ss; ss << "("; ss << p0.getX(); ss << ", "; ss << p0.getY(); ss << ") - ("; ss << p1.getX(); ss << ", "; ss << p1.getY(); ss << ")"; return ss.str(); }
7ff863c74342c9f426a1c3b80413a38212895502
8e903808a1058669cfaf78a55ec69368c48017fe
/FlameSim/FlameSimMkIII/FlameSimMkIII.ino
fedb46a5212a4426192335e85454918adbc8b4b5
[ "MIT" ]
permissive
GremlinWrangler/TeensyProjects
2ab4f07eea21204ea3e6f741216fd60fdb2932b1
3bca5746dced8e9b21523ae21e707981668e17fe
refs/heads/master
2021-01-21T14:04:58.062708
2016-03-20T08:39:04
2016-03-20T08:39:04
29,943,967
0
0
null
null
null
null
UTF-8
C++
false
false
11,892
ino
// Fire simulation using 8 streams of 12 neo pixels each // running on a Teensy 3 via the 8 channel OCTOWS811 // Library from PJRC // Default code takes serial messages from an Xbee // and parses out the analogue value to use as a // remote intensity control // Battery monitoring will disable display if // batMonPin (17) is low //Fire effect inspired by the Teensy fire example // but extensivly modified to produce fast rising bursts // of white heat against a red flickering glow // intention was to support fire training where existing process // was for people to wave extuingishers in the direction of // the fire and then walk away to ask an umpire if the // fire was out. In this case they can call it as they see it // One unforseen issue is that in thick smoke an IR camera is // used and of course LEDs have no presence at all in IR // Maybe in the MkV version.. #include <OctoWS2811.h> // The display size and color to use const unsigned int width = 12; const unsigned int height = 8; const unsigned int batMonPin = 17; const unsigned int statusLED = 10; // These parameters control the fire appearance unsigned int heat = width / 5; unsigned int focus = 20; unsigned int cool = 500; //low numbers cause minimal reduction, 500 causes rapid cooling going up display unsigned int flickerSpeed =100; unsigned int stageOneGain =0; //at high intensities two seperate noise fields feed heat into the simulation unsigned int stageTwoGain =0; float stageTwoOffset = 0; //noise inputs are sinewave -1<x<1 values, this drives how much the second stage is >1 unsigned int analogueAvBuffer =0; //used for the highly noisey battery monitor unsigned int lowBatLockout =0; //if set to one disables display until reset. unsigned int heartBeat =0; // these two control the indicator LED in it's unsigned int heartBeatDirection =0; //slow heart beat or fast 'I'm flat' indications int intensity = 5; //defines how hot our fire is burning 0-1024 // 0 =0 no fire // 100 flickering // 500 red flames // 700 yellow flames // if remote is operating will be updated each time it transmits // Arrays for fire animation int canvas[width*height]; byte serialBuffer[14]; //captures Xbee data to allow pattern matching #define RGB(r, g, b) (((r) << 16) | ((g) << 8) | (b)) const unsigned int fireColor[100] = { //100 point lookup table from dim red to blended yellows RGB(0,0,0), RGB(2,0,0), RGB(4,0,0), RGB(6,0,0), RGB(9,0,0), RGB(11,0,0), RGB(14,0,0), RGB(16,0,0), RGB(19,0,0), RGB(22,0,0), RGB(25,0,0), RGB(28,0,0), RGB(31,0,0), RGB(35,0,0), RGB(38,0,0), RGB(41,0,0), RGB(45,0,0), RGB(48,0,0), RGB(52,0,0), RGB(56,0,0), RGB(59,0,0), RGB(64,0,0), RGB(68,0,0), RGB(72,0,0), RGB(76,0,0), RGB(79,0,0), RGB(83,0,0), RGB(88,0,0), RGB(92,0,0), RGB(97,0,0), RGB(101,0,0), RGB(105,0,0), RGB(109,0,0), RGB(114,0,0), RGB(118,0,0), RGB(122,0,0), RGB(127,0,0), RGB(131,0,0), RGB(136,0,0), RGB(140,0,0), RGB(145,0,0), RGB(149,0,0), RGB(154,0,0), RGB(159,0,0), RGB(163,0,0), RGB(168,0,0), RGB(174,0,0), RGB(179,0,0), RGB(184,0,0), RGB(188,0,0), RGB(192,0,0), RGB(194,2,0), RGB(197,4,0), RGB(199,6,0), RGB(202,8,0), RGB(204,11,0), RGB(207,13,0), RGB(209,16,0), RGB(212,19,0), RGB(214,22,0), RGB(217,25,0), RGB(219,28,0), RGB(222,31,0), RGB(224,35,0), RGB(227,38,0), RGB(229,41,0), RGB(232,45,0), RGB(234,48,0), RGB(237,52,0), RGB(240,56,0), RGB(242,59,0), RGB(246,64,0), RGB(249,68,0), RGB(251,72,0), RGB(254,76,0), RGB(255,80,0), RGB(255,86,1), RGB(255,93,2), RGB(255,99,2), RGB(255,106,3), RGB(255,113,4), RGB(255,119,5), RGB(255,126,6), RGB(255,132,8), RGB(255,139,9), RGB(255,146,10), RGB(255,153,11), RGB(255,161,12), RGB(255,168,14), RGB(255,175,15), RGB(255,182,16), RGB(255,190,18), RGB(255,197,19), RGB(255,204,21), RGB(255,212,22), RGB(255,219,24), RGB(255,228,26), RGB(255,236,28), RGB(255,243,29), RGB(255,251,31) }; #define LED_LAYOUT = 0; // OctoWS2811 objects const int ledsPerPin = width * height / 8; DMAMEM int displayMemory[ledsPerPin*6]; int drawingMemory[ledsPerPin*6]; const int config = WS2811_GRB | WS2811_800kHz; OctoWS2811 leds(ledsPerPin, displayMemory, drawingMemory, config); // assorted state machine counters int cycleCounter = 0; //heartbeat delay counter int tick = 0; //counter that feeds our noise function to produce flowing heat into the simulation int battMonReadCounter=0; //tracks how many voltage reads we have done. // Run setup once void setup() { // turn on the display leds.begin(); pinMode(13,OUTPUT); pinMode(statusLED,OUTPUT); pinMode(batMonPin ,INPUT); Serial1.begin(9600); for (int y=0; y <height-1; y++) { // loops to load up a graduated arry to confirm LED operation on power up for (int x=0; x < width-1; x++) { canvas[(y) * width + x]= (x*6+y*6)*256; if (y%2==0) leds.setPixel(xy(x, y), 5); else leds.setPixel(xy(11-x, y), 5); // leds.show(); }} // colorWipe(0x009f00, 50); } // A simple xy() function to turn display matrix coordinates // into the index numbers OctoWS2811 requires. If your LEDs // are arranged differently, edit this code... unsigned int xy(unsigned int x, unsigned int y) { if ((y & 1) == 0) { // even numbered rows (0, 2, 4...) are left to right return y * width + x; } else { // odd numbered rows (1, 3, 5...) are right to left return y * width + width - 1 - x; } } elapsedMillis msec; //Macro to track msec from a time void checkSerial() //pulls data in from the Xbee and parses it for values. { byte incomingByte; if (Serial1.available() > 0) { incomingByte = Serial1.read(); for (int count =1;count<14;count++) {serialBuffer[count-1]=serialBuffer[count]; } //slide buffer right serialBuffer[13]=incomingByte; if (serialBuffer[0]==126&serialBuffer[2]==10&serialBuffer[3]==131) //filter to find Xbee default message structure {intensity = serialBuffer[11]*256+ serialBuffer[12]; //Next time I'll use an actual library! intensity = floor(intensity*3/4); //clamping from Jan15 hardware hitting current limits at high intensity focus = 20; flickerSpeed = 50;//floor((intensity)/2); // cool = floor((1024-intensity)/2); //defines how hot our fire is burning 0-1024 // 0 =0 no fire // 100 flickering // 500 red flames // 700 yellow flames stageOneGain =intensity*2; if (stageOneGain>1024) stageOneGain=1204; //so gain winds up twice as fast to midrange, and then caps stageOneGain = stageOneGain*32;//max intensity is 65536 or 256*256, or in this case 1024*64 if (intensity>512) {stageTwoGain = (512+intensity/2)*64;} else {stageTwoGain=0;} //gain winds up from zero below intensity 512 to 32767 (1024*32) at intensity 1024 stageTwoOffset = 0.4*(intensity-512)/512; //adjusts the -1 to +1 noise values with a positive offset, this is why stage one gain only applies up to 32767, rather than 65536 for (int i=0;i<10;i++) {Serial1.write(intensity);} Serial.println(intensity);} } } void loop() { checkSerial(); if ((millis()/1000)%2>0) digitalWrite(13,HIGH);else digitalWrite(13,LOW); //debug LED blink if (msec > 7) {// flame update rate msec=0; if (lowBatLockout==0) animateFire(); else colorWipe(0,10); //low voltage condition, disable light show tick++; analogueAvBuffer = analogueAvBuffer + analogRead(batMonPin ); battMonReadCounter++; if (64<battMonReadCounter) { battMonReadCounter=0; if (analogueAvBuffer>>6<550) lowBatLockout =1;// else lowBatLockout =0; //else removed because of cyclic battery behavior under load Serial.println(analogueAvBuffer>>6); //now latches in state until power cycled. analogueAvBuffer=0; } if (heartBeatDirection==0){ //and the longest chunk of code in the main loop makes a light blink... heartBeat++; if (heartBeat==255) heartBeatDirection =1; } else{ heartBeat--; if (heartBeat==0) heartBeatDirection =0; } if (lowBatLockout==0) analogWrite(statusLED ,heartBeat); else analogWrite(statusLED ,(heartBeat>>2)%2*200); } } void animateFire() { int i, c, n, x, y; float TickNoiseTemp = float(tick/flickerSpeed)-cos(float(tick)/flickerSpeed); // work out this value once, rather than each cycle through the for loop for (y=height-1; y >= 0; y--) { float YnoiseTemp = float(y/2)-sin(float(y/2)); // for ( x=width-1; x >= 0; x--) { int cellheat = 0; if (x>0) {cellheat = canvas[(y) * width + x];} else //we are on the bottom row and need to feed some noise into the system { cellheat = floor(float(pnoise( YnoiseTemp,TickNoiseTemp,5)*stageOneGain)); //pnoise is a perlin noise routine taking three axis and returning floats -1 to +1 if (intensity>512) { //we then multiply those by the gain values to produce numbers 0-65536 int tempheat=floor((float(pnoise( YnoiseTemp,TickNoiseTemp,10)+stageTwoOffset)*stageTwoGain)); if (tempheat>cellheat) cellheat =tempheat; //adds second layer to the hot spots above half scale input } } float tempfloat = cellheat; tempfloat = 10-cellheat/8000; //coupling facter based on having a multiple between 10 and ~2 (cell heat will be between 0 and 65536 int HeatTransfer = ceil(float(cellheat)/tempfloat);//for high heat values we move them up fast taking half each clock cycle. Cooler temps move 1/10th and rounded up canvas[(y) * width + x]=cellheat-HeatTransfer; if(x<width-1) canvas[(y) * width + x+1]=HeatTransfer+canvas[(y) * width + x+1]; //error trap to avoid writing off the top of the array } } // Step 3: interpolate //Averages with the four cells around it, error checking as it goes to avoid leaving array boundries. for (y=0; y < height; y++) { for (x=0; x < width; x++) { c = canvas[y * width + x] * focus; n = focus; if (x > 0) { c = c + canvas[y * width + (x - 1)]; n = n + 1; } if (x < width-1) { c = c + canvas[y * width + (x + 1)]; n = n + 1; } if (y > 0) { c = c + canvas[(y -1) * width + x]; n = n + 1; } if (y < height-1) { c = c + canvas[(y + 1) * width + x]; n = n + 1; } c = (c + (n / 2)) / n; i = (random(1000) * cool)*x / 10000; if (c > i) { c = c - i; } else { c = 0; } canvas[y * width + x] = c; } } // Step 4: render canvas to LEDs for (y=0; y < height; y++) { for (x=0; x < width; x++) { c = floor(canvas[((height - 1) - y) * width + x]>>8); if (c<0) c = 0; if (c>100) c =99; //c = 10; // c = ((x*6)*256*256)+y*0; // leds.setPixel(xy(x, y), 5); if (y%2==0) leds.setPixel(xy(x, y), fireColor[c]); else leds.setPixel(xy(11-x, y), fireColor[c]);//because I missed the way xy() handles even lines } } leds.show(); } //debug routine now used to blank array in low battery condition void colorWipe(int color, int wait) { for (int i=0; i < leds.numPixels(); i++) { leds.setPixel(i, color); leds.show(); delayMicroseconds(wait); } }
aa13f708b43b7a640dcafcb707b5d5a73c952327
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/chromeos/extensions/input_method_event_router.h
9bc951077d185cce15c82a1e61c421270b9c0c8c
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,223
h
// Copyright (c) 2012 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 CHROME_BROWSER_CHROMEOS_EXTENSIONS_INPUT_METHOD_EVENT_ROUTER_H_ #define CHROME_BROWSER_CHROMEOS_EXTENSIONS_INPUT_METHOD_EVENT_ROUTER_H_ #include "base/compiler_specific.h" #include "base/macros.h" #include "ui/base/ime/chromeos/input_method_manager.h" namespace content { class BrowserContext; } namespace chromeos { // Event router class for the input method events. class ExtensionInputMethodEventRouter : public input_method::InputMethodManager::Observer { public: explicit ExtensionInputMethodEventRouter(content::BrowserContext* context); ~ExtensionInputMethodEventRouter() override; // Implements input_method::InputMethodManager::Observer: void InputMethodChanged(input_method::InputMethodManager* manager, Profile* profile, bool show_message) override; private: content::BrowserContext* context_; DISALLOW_COPY_AND_ASSIGN(ExtensionInputMethodEventRouter); }; } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_EXTENSIONS_INPUT_METHOD_EVENT_ROUTER_H_
e1a6ef411bd483afbdcddd34b24dae770b2f25bb
ab772d6c5ee1aa571d5b579356e00eb9090d8a08
/qtlearnings/paramconfig/UiCommon/ibindobj.h
86549883168964bb84eabbb9f7b320ac81614940
[]
no_license
ldhshao/mylearnings
916ecaf67487c12272ab9ba1f22a8c10bcf888d7
d20fc1640a9da379fc946573ce11df1b924a017c
refs/heads/master
2022-03-12T17:59:08.908442
2022-01-05T10:02:05
2022-01-05T10:02:05
234,214,640
0
0
null
2020-09-25T07:59:07
2020-01-16T02:11:03
JavaScript
UTF-8
C++
false
false
955
h
#ifndef IBINDOBJ_H #define IBINDOBJ_H #include "QKeyEvent" enum{ kd_null = -1, kd_check, kd_emit, kd_check_emit, kd_show, kd_show_emit }; class IBindObj { public: IBindObj():_state(BS_INIT){} virtual ~IBindObj(){} // 使用父类指针析构子类对象 enum { BS_INIT = 0, BS_MODIFIED = 1, BS_SOURCEKEY = 0x10 }; virtual int keyEventFilter(QKeyEvent* ev) = 0; virtual QString checkSet() = 0; virtual QString showSet() = 0; virtual void clear() = 0; virtual bool setValue(const QString& strVal) { return false; } uint8_t state() { return _state; } bool isModified() { return (_state & BS_MODIFIED); } bool isFromKeyEvent() { return (_state & BS_SOURCEKEY); } uint8_t setState(uint8_t s) { _state = (s | _state); return _state; } uint8_t clearState() { return _state = BS_INIT; } protected: uint8_t _state; }; #endif // IBINDOBJ_H
dd64e282d6a78fec446da2a6e31de67e8b526108
fa20cb6ba5e7177228aa011a1444e039d2e871b0
/FileEncryption/FileEncryption/PassphraseDlg.cpp
de92a102fec454d0af2f7672c24e779d530fe5cc
[]
no_license
inf-eth/i02-0491-projects
13158b6c3f96fe9adf436b87da7cd171bd4c4369
429d4a4d6084c5f04a556c3dea103a2d319446c2
refs/heads/master
2021-01-10T09:47:39.020246
2015-11-16T13:33:02
2015-11-16T13:33:02
46,210,626
0
0
null
null
null
null
UTF-8
C++
false
false
1,416
cpp
// PassphraseDlg.cpp : implementation file // #include "stdafx.h" #include "FileEncryption.h" #include "PassphraseDlg.h" #include "afxdialogex.h" extern CString Passphrase; // CPassphraseDlg dialog IMPLEMENT_DYNAMIC(CPassphraseDlg, CDialogEx) CPassphraseDlg::CPassphraseDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CPassphraseDlg::IDD, pParent) , m_Passphrase(_T("Enter passphrase")) { m_Passphrase = _T(""); } CPassphraseDlg::~CPassphraseDlg() { } void CPassphraseDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); // DDX_Text(pDX, IDC_EDIT_PASSPHRASE, m_Passphrase); DDX_Text(pDX, IDC_EDIT_PASSPHRASE, m_Passphrase); DDV_MaxChars(pDX, m_Passphrase, 127); } BEGIN_MESSAGE_MAP(CPassphraseDlg, CDialogEx) ON_BN_CLICKED(IDOK, &CPassphraseDlg::OnBnClickedOk) ON_BN_CLICKED(IDCANCEL, &CPassphraseDlg::OnBnClickedCancel) END_MESSAGE_MAP() // CPassphraseDlg message handlers void CPassphraseDlg::OnBnClickedOk() { // TODO: Add your control notification handler code here UpdateData(true); if (m_Passphrase == "") { AfxMessageBox(L"Please enter a valid passphrase.", MB_ICONSTOP); return; } else { Passphrase = m_Passphrase; CDialogEx::OnOK(); } UpdateData(false); } void CPassphraseDlg::OnBnClickedCancel() { // TODO: Add your control notification handler code here CDialogEx::OnCancel(); }
[ "infinity.ethereal@ef33575d-811c-aa3e-9c56-0e3b2be09934" ]
infinity.ethereal@ef33575d-811c-aa3e-9c56-0e3b2be09934
bc2bb229aad9013a192ba3f2d24c45f5a65cff59
f4cfc323df4d6472b36cb74b04e81a7bc550281f
/hphp/runtime/base/type-structure-helpers.h
4532119d3025d72c3f8ba9eec4fe62fc42548480
[ "PHP-3.01", "Zend-2.0", "MIT" ]
permissive
Howie1201/hhvm
87fc22b1bb2d187da7ce1eac962e2e3d3a6bd1ad
4edbd25aa0d7c75b084d9feb4dd8ddea7f375b07
refs/heads/master
2020-03-11T00:24:06.690992
2018-04-15T21:35:32
2018-04-15T21:39:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,402
h
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #ifndef incl_HPHP_TYPE_STRUCTURE_HELPERS_H_ #define incl_HPHP_TYPE_STRUCTURE_HELPERS_H_ #include <string> #include "hphp/runtime/base/array-data.h" #include "hphp/runtime/base/typed-value.h" #include "hphp/runtime/vm/bytecode.h" namespace HPHP { /* * Checks whether the given cell is an instance of the class referred by * given named entity */ bool cellInstanceOf(const Cell* tv, const NamedEntity* ne); /* * Resolves the given array as a type structure * Raises an error if the type structure contains a trait, typevar * or a function type * May throw if the type structure cannot be resolved */ Array resolveAndVerifyTypeStructure(const Array& ts); /* * Checks whether the type of the given cell matches the type structure * Expects a resolved type structure */ bool checkTypeStructureMatchesCell(const Array& ts, Cell c1); /* * In addition to regular checkTypeStructureMatchesCell, also populates the * error paths */ bool checkTypeStructureMatchesCell( const Array& ts, Cell c1, std::string& givenType, std::string& expectedType, std::string& errorKey ); /* * Throws user catchable exception that tells the user what the given type is, * what the expected type is and which key it failed at, if applicable */ [[noreturn]] void throwTypeStructureDoesNotMatchCellException( std::string& givenType, std::string& expectedType, std::string& errorKey ); } #endif
69ad19eae727ba937345410ec2e6ee7b05b5968e
5c5bd3c70d4761b5a15e79da7aa8d97f69744e03
/day03/ex03/NinjaTrap.hpp
b40d8465161220591bf3d0f89747b7d40a425bd5
[]
no_license
arwn/piscine-cpp
ff98f2a1c7b57ba30725b6b45f01eda51e56f8de
29dbef355737057f141bd980e1010e80da307a13
refs/heads/master
2020-05-18T08:38:37.676031
2019-05-03T15:02:26
2019-05-03T15:02:26
184,300,974
0
0
null
null
null
null
UTF-8
C++
false
false
499
hpp
#ifndef NINJATRAP_HPP #define NINJATRAP_HPP #include "ClapTrap.hpp" #include "FragTrap.hpp" #include "ScavTrap.hpp" #include <iostream> #include <string> #include <random> class NinjaTrap: public ClapTrap { public: NinjaTrap(std::string); NinjaTrap(void); ~NinjaTrap(void); NinjaTrap& operator=(const NinjaTrap &ah); void ninjaShoebox(const FragTrap &r); void ninjaShoebox(const ScavTrap &r); void ninjaShoebox(const NinjaTrap &r); private: static std::string _verbs[8]; }; #endif
2441f817b69c50ef1c14a47aaa363acb5ae513fe
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/ash/system/tray/tray_item_more.h
bc7b70d5af78a92d4e90756a799fd8500a834f63
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
2,332
h
// Copyright (c) 2012 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 ASH_SYSTEM_TRAY_TRAY_ITEM_MORE_H_ #define ASH_SYSTEM_TRAY_TRAY_ITEM_MORE_H_ #include <memory> #include "ash/system/tray/actionable_view.h" #include "base/macros.h" #include "ui/views/view.h" namespace views { class ImageView; class Label; class View; } namespace ash { class SystemTrayItem; class TrayPopupItemStyle; class TriView; // A view with a more arrow on the right edge. Clicking on the view brings up // the detailed view of the tray-item that owns it. If the view is disabled, it // will not show the more arrow. class TrayItemMore : public ActionableView { public: explicit TrayItemMore(SystemTrayItem* owner); ~TrayItemMore() override; void SetLabel(const base::string16& label); void SetImage(const gfx::ImageSkia& image_skia); protected: // Returns a style that will be applied to the elements in the UpdateStyle() // method if |this| is enabled; otherwise, we force |this| to use // ColorStyle::DISABLED. std::unique_ptr<TrayPopupItemStyle> CreateStyle() const; // Called by CreateStyle() to give descendants a chance to customize the // style; e.g. to change the style's ColorStyle based on whether Bluetooth is // enabled/disabled. virtual std::unique_ptr<TrayPopupItemStyle> HandleCreateStyle() const; // Applies the style created from CreateStyle(). Should be called whenever any // input state changes that changes the style configuration created by // CreateStyle(). E.g. if Bluetooth is changed between enabled/disabled then // a differently configured style will be returned from CreateStyle() and thus // it will need to be applied. virtual void UpdateStyle(); private: // Overridden from ActionableView. bool PerformAction(const ui::Event& event) override; // Overridden from views::View. void GetAccessibleNodeData(ui::AXNodeData* node_data) override; void OnEnabledChanged() override; void OnNativeThemeChanged(const ui::NativeTheme* theme) override; TriView* tri_view_; views::ImageView* icon_; views::Label* label_; views::ImageView* more_; DISALLOW_COPY_AND_ASSIGN(TrayItemMore); }; } // namespace ash #endif // ASH_SYSTEM_TRAY_TRAY_ITEM_MORE_H_
3ac8682a418e7c48dc1fc702c2983475179261a3
e3faebc25b7a95acc8f52d3139b9a48cd440dae6
/Classes/FightLayer.cpp
3ab683f07302e232e11cf75722d602d637c6c194
[]
no_license
cuongnv-ict/shuihucard
1e124e4e61d8245bc9bad26c4df2b3f3baa31e3f
dfe30041bccb6e6e73c9d57b7cfd1bbef0601251
refs/heads/master
2021-01-22T11:03:27.605389
2014-10-01T06:14:33
2014-10-01T06:14:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,600
cpp
// // FightLayer.cpp // kapai // // Created by qin on 14-4-6. // // #include "FightLayer.h" #include "BattleScene.h" FightLayer::FightLayer(int level) { init(level); } FightLayer::~FightLayer() { } bool FightLayer::init(int level) { if(!CCLayer::init()){ return false; } mlevel=level; setTouchEnabled(true); CCSize winSize =CCDirector::sharedDirector()->getWinSize(); CCSprite* imagehead= CCSprite::create("zhanyi.png"); imagehead->setPosition(ccp(winSize.width/2,winSize.height/2)); addChild(imagehead); readJson(); CCSize visibSize=CCDirector::sharedDirector()->getVisibleSize(); CCTableView *tableView=CCTableView::create(this, CCSizeMake(visibSize.width,600)); tableView->setDirection(kCCScrollViewDirectionVertical); tableView->setPosition(ccp(0,winSize.height/2-360)); tableView->setDelegate(this); tableView->setVerticalFillOrder(kCCTableViewFillTopDown); this->addChild(tableView,1); //tableView->reloadData(); CCMenuItemImage* pHome = CCMenuItemImage::create("close1.png", "close2.png", this, menu_selector(FightLayer::close)); CCMenu *menu=CCMenu::create(pHome,NULL); menu->setPosition(ccp(winSize.width-60,winSize.height/2+300)); addChild(menu,2); // CCScale9Sprite *sprite9 = CCScale9Sprite::create("close1.png"); // CCControlButton* btn= CCControlButton::create(sprite9); // btn->addTargetWithActionForControlEvents(this, cccontrol_selector(FightLayer::close),CCControlEventTouchDown); // btn->setPreferredSize(CCSizeMake(sprite9->getContentSize().width,sprite9->getContentSize().height)); // btn->setPosition(ccp(winSize.width-60, winSize.height/2+350)); // addChild(btn); return true; } void FightLayer::readJson() { CSJson::Reader reader; CSJson::Value root; unsigned long nSize = 0; char str[32]; sprintf(str,"map_%d.json",mlevel); CCSize winSize=CCDirector::sharedDirector()->getWinSize(); string path =CCFileUtils::sharedFileUtils()->fullPathForFilename(str); map_document=(char*)CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "rb",&nSize); if(reader.parse(map_document, root)) { datas=root["data"]; } } unsigned int FightLayer::numberOfCellsInTableView(CCTableView *table) { return datas.size(); } CCTableViewCell* FightLayer::tableCellAtIndex(CCTableView *table, unsigned int idx) { CCSize winSize=CCDirector::sharedDirector()->getWinSize(); CCTableViewCell *cell = table->dequeueCell(); string tile=datas[idx]["name"].asString(); int card=datas[idx]["card"].asInt(); int sword=datas[idx]["sword"].asInt(); int xp=datas[idx]["xp"].asInt(); int money=datas[idx]["coin"].asInt(); if (!cell) { cell = new CCTableViewCell(); cell->autorelease(); CCSprite *bgSprite = CCSprite::create("cellbg.png"); bgSprite->setAnchorPoint(CCPointZero); bgSprite->setPosition(CCPointZero); bgSprite->setTag(789); cell->addChild(bgSprite); CCLabelTTF *pLabel = CCLabelTTF::create(tile.c_str(), "Arial", 32.0); pLabel->setColor(ccRED); pLabel->setPosition(ccp(winSize.width/2,120)); pLabel->setTag(400); cell->addChild(pLabel); char str[32]; sprintf(str,"经验:%d\n银子:%d",xp,money); CCLabelTTF *coinLabel=CCLabelTTF::create(str, "Arial", 24.0); coinLabel->setTag(401); coinLabel->setColor(ccBLACK); coinLabel->setPosition(ccp(120,100)); cell->addChild(coinLabel); CCLabelTTF *cardLabel=CCLabelTTF::create("","Arial", 32.0); cardLabel->setTag(402); cardLabel->setColor(ccBLUE); cardLabel->setPosition(ccp(winSize.width/2,60)); cell->addChild(cardLabel); } else { CCLabelTTF *pLabel = (CCLabelTTF*)cell->getChildByTag(400); pLabel->setString(tile.c_str()); char str[32]; sprintf(str,"经验:%d\n银子:%d",xp,money); CCLabelTTF *pcoinLabel = (CCLabelTTF*)cell->getChildByTag(401); pcoinLabel->setString(str); CCLabelTTF *pcardLabel = (CCLabelTTF*)cell->getChildByTag(402); map<int,HeroType> HeroTypes=Config::sharedConfig()->getHerosType(); HeroType herodata; herodata.type=card; map<int,HeroType>::iterator iterHero = HeroTypes.find(card); if(iterHero!= HeroTypes.end()) { HeroType herotype=iterHero->second; herodata.name=herotype.name; char strname[32]; sprintf(strname,"随机掉落:%s",herotype.name.c_str()); pcardLabel->setString(strname); } if(card==108) { pcardLabel->setString("随机掉落108将之一"); } else if(card==109) { pcardLabel->setString("随机掉落72地煞星之一"); } map<int,ZhuangBeiType> zhuangTypes=Config::sharedConfig()->getZhuangBei(); ZhuangBeiType data; int index=sword/1000; map<int,ZhuangBeiType>::iterator iter=zhuangTypes.find(index); if(iter!= zhuangTypes.end()) { ZhuangBeiType type=iter->second; char strname[32]; sprintf(strname,"随机掉落:%s",type.name.c_str()); CCLabelTTF *pcard = (CCLabelTTF*)cell->getChildByTag(402); pcard->setString(strname); } if(card==-1&&sword==-1) { CCLabelTTF *pcard = (CCLabelTTF*)cell->getChildByTag(402); pcard->setString(""); } } return cell; } CCSize FightLayer::cellSizeForTable(CCTableView *table) { CCSize visibSize=CCDirector::sharedDirector()->getVisibleSize(); return CCSizeMake(visibSize.width, 193); } void FightLayer::tableCellHighlight(CCTableView *table, CCTableViewCell *cell) { } void FightLayer::tableCellUnhighlight(CCTableView *table, CCTableViewCell *cell) { } void FightLayer::scrollViewDidScroll(cocos2d::extension::CCScrollView* view) { } void FightLayer::scrollViewDidZoom(cocos2d::extension::CCScrollView* view) { } void FightLayer::tableCellTouched(CCTableView *table, CCTableViewCell *cell) { int tag=cell->getIdx(); Value data=datas[tag]; //CCScene *pScene =BattleScene::scene(data); CCScene *pScene =CCDirector::sharedDirector()->getRunningScene(); BattleScene *layer=new BattleScene(); layer->init(data); layer->autorelease(); pScene->addChild(layer,10); CCMenu *menu =(CCMenu*)layer->getParent()->getChildByTag(888); menu->setVisible(false); } void FightLayer::onExit() { CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this); } void FightLayer::registerWithTouchDispatcher(void) { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true); } bool FightLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { return true; } void FightLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { } void FightLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { } void FightLayer::close(CCObject *sender) { removeAllChildrenWithCleanup(true); removeFromParentAndCleanup(true); } void FightLayer::menuPauseCallback(CCObject *sender) { CCMenuItemImage* pHome =(CCMenuItemImage*) sender; int tag=pHome->getTag(); Value data=datas[tag]; BattleScene *layer=new BattleScene(); layer->init(data); layer->autorelease(); addChild(layer,10); }
c7e0c2e01a5a8cb9461a7dc5c95fc7134b4ad115
866a1e1b3bce69abfc916ab42bc2e9478e3f675a
/cpp-boost/src/rest/cli.cpp
167a87146a52912b62bcbf6af46bcffa775cfa92
[ "BSD-3-Clause" ]
permissive
geoffroyvergne/crawler
15b368ad5d7589dc835183ffb51d0d7e0442ace1
9ad65ea022931ad9a898390eaa41a6393b53bf6f
refs/heads/main
2023-07-11T05:40:15.735459
2021-08-26T16:32:16
2021-08-26T16:32:16
301,189,714
0
0
null
null
null
null
UTF-8
C++
false
false
2,225
cpp
#include <iostream> #include <boost/program_options.hpp> //#include <boost/log/trivial.hpp> #include <app.h> #include <cli.hpp> #include <config.hpp> Cli::Cli(int argc, char** argv) { boost::program_options::variables_map variableMap; try { boost::program_options::options_description optionsDescription("Allowed options"); optionsDescription.add_options() ("help", "Produce help message") ("version,v", "Get version") ("host,h", boost::program_options::value<std::string>()->default_value("0.0.0.0"), "Host to listen") ("port,p", boost::program_options::value<int>()->default_value(3000), "Port to listen") ("config,c", boost::program_options::value<std::string>(), "Configuration file name") ; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, optionsDescription), variableMap); boost::program_options::notify(variableMap); if (variableMap.count("help")) { this->getVersion(); this->getHelp(&optionsDescription); exit(EXIT_SUCCESS); } if (variableMap.count("version")) { //BOOST_LOG_TRIVIAL(info) << this->getVersion(); std::cout << this->getVersion() << std::endl; exit(EXIT_SUCCESS); } } catch(std::exception& e) { std::cerr << "error: " << e.what() << std::endl; exit(EXIT_FAILURE); } catch(...) { //BOOST_LOG_TRIVIAL(error) << "Exception of unknown type!"; std::cout << "Exception of unknown type!" << std::endl; exit(EXIT_FAILURE); } this->variableMap = variableMap; } std::string Cli::getVersion() { std::string version; version.append(APP_NAME); version.append(" : "); version.append(std::to_string(VERSION_MAJOR)); version.append("."); version.append(std::to_string(VERSION_MINOR)); return version; } void Cli::getHelp(boost::program_options::options_description *optionsDescription) { std::cout << *optionsDescription << std::endl; } boost::program_options::variables_map Cli::getVariableMap() { return this->variableMap;; }
4cdd68a9388b0cf5a6610970705670a40628439d
1c04742f4c8a4bbe20aaec39d64e0732c532f307
/base.h
7fa99ab5dd85b1ad9176ad55b805eab5cbdf2633
[]
no_license
pawhaley/piece-wise
f547917531ceb1bdfa2b691ff0f47e06474cfc9f
02003ccf1239b06501cdba72335c5afe8f5dbaa9
refs/heads/master
2020-12-31T07:43:04.347519
2016-04-30T23:05:26
2016-04-30T23:05:26
57,463,428
0
0
null
null
null
null
UTF-8
C++
false
false
866
h
#ifndef PWF_HEDDER #define PWF_HEDDER //this is the pure virtual class that knows how to evaluate a pecewise function class PWFunc{ public: //setup PWFunc(){ _next=nullptr; } //add our mask after sompthing else void addAfter(PWFunc* prev){ _next=prev->_next; prev->_next=this; } //how to evaluate the masks double evaluate(double position){ double retval; if(internalEval(retval,position)){ return retval; } //assert: we couldn't handel it if(_next==nullptr){ //WE HAVE A BIG PROBLEM!!! return -1; } return _next->evaluate(position); } ~PWFunc(){} protected: //this must be written for each derrived class accepts a place to store the answer and the value to be evaluated, //returns true if it could be handeled virtual bool internalEval(double& toStore,double position)=0; private: //next mask PWFunc* _next; }; #endif
bcf2939817e08279f5e3d4ee80cc961b9a39c34f
9a879c0669bc70facf5dc2fadaca2eff54bb8a53
/alljoyn/services/controlpanel/cpp/src/Widgets/ConstraintList.cc
9ec8f530c97beaba99b94d6563c871d8d8684c44
[ "ISC" ]
permissive
octoblu/alljoyn
d86c4d2bb60f989f52f3a3f9a0ce8d11ef5cd3f9
a74003fa25af1d0790468bf781a4d49347ec05c4
refs/heads/master
2021-01-21T12:47:18.034834
2016-03-15T16:23:31
2016-03-15T16:23:31
21,958,119
37
29
null
2016-03-15T16:12:35
2014-07-17T21:24:28
C++
UTF-8
C++
false
false
7,636
cc
/****************************************************************************** * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include <alljoyn/controlpanel/ConstraintList.h> #include <alljoyn/controlpanel/ControlPanelService.h> #include "../ControlPanelConstants.h" #include <alljoyn/controlpanel/LogModule.h> namespace ajn { namespace services { using namespace cpsConsts; ConstraintList::ConstraintList() : m_PropertyType(UNDEFINED), m_Display(""), m_GetDisplays(0) { } ConstraintList::~ConstraintList() { } void ConstraintList::setConstraintValue(uint16_t value) { m_ConstraintValue.uint16Value = value; m_PropertyType = UINT16_PROPERTY; } void ConstraintList::setConstraintValue(int16_t value) { m_ConstraintValue.int16Value = value; m_PropertyType = INT16_PROPERTY; } void ConstraintList::setConstraintValue(uint32_t value) { m_ConstraintValue.uint32Value = value; m_PropertyType = UINT32_PROPERTY; } void ConstraintList::setConstraintValue(int32_t value) { m_ConstraintValue.int32Value = value; m_PropertyType = INT32_PROPERTY; } void ConstraintList::setConstraintValue(uint64_t value) { m_ConstraintValue.uint64Value = value; m_PropertyType = UINT64_PROPERTY; } void ConstraintList::setConstraintValue(int64_t value) { m_ConstraintValue.int64Value = value; m_PropertyType = INT64_PROPERTY; } void ConstraintList::setConstraintValue(double value) { m_ConstraintValue.doubleValue = value; m_PropertyType = DOUBLE_PROPERTY; } void ConstraintList::setConstraintValue(qcc::String const& value) { m_ConstraintValueString = value; m_ConstraintValue.charValue = m_ConstraintValueString.c_str(); m_PropertyType = STRING_PROPERTY; } ConstraintValue ConstraintList::getConstraintValue() const { return m_ConstraintValue; } PropertyType ConstraintList::getPropertyType() const { return m_PropertyType; } const qcc::String& ConstraintList::getDisplay() const { return m_Display; } const std::vector<qcc::String>& ConstraintList::getDisplays() const { return m_Displays; } void ConstraintList::setDisplays(const std::vector<qcc::String>& displays) { m_Displays = displays; } GetStringFptr ConstraintList::getGetDisplays() const { return m_GetDisplays; } void ConstraintList::setGetDisplays(GetStringFptr getDisplays) { m_GetDisplays = getDisplays; } QStatus ConstraintList::fillConstraintArg(MsgArg& val, uint16_t languageIndx, PropertyType propertyType) { if (m_PropertyType != propertyType) { QCC_DbgHLPrintf(("Could not fill the Constraint Arg. PropertyTypes do not match")); return ER_FAIL; } if (!(m_Displays.size() > languageIndx) && !m_GetDisplays) { QCC_DbgHLPrintf(("Could not fill the Constraint Arg. Display is not set")); return ER_FAIL; } QStatus status; MsgArg* valueArg = new MsgArg(); switch (propertyType) { case UINT16_PROPERTY: status = valueArg->Set(AJPARAM_UINT16.c_str(), m_ConstraintValue.uint16Value); break; case INT16_PROPERTY: status = valueArg->Set(AJPARAM_INT16.c_str(), m_ConstraintValue.int16Value); break; case UINT32_PROPERTY: status = valueArg->Set(AJPARAM_UINT32.c_str(), m_ConstraintValue.uint32Value); break; case INT32_PROPERTY: status = valueArg->Set(AJPARAM_INT32.c_str(), m_ConstraintValue.int32Value); break; case UINT64_PROPERTY: status = valueArg->Set(AJPARAM_UINT64.c_str(), m_ConstraintValue.uint64Value); break; case INT64_PROPERTY: status = valueArg->Set(AJPARAM_INT64.c_str(), m_ConstraintValue.int64Value); break; case DOUBLE_PROPERTY: status = valueArg->Set(AJPARAM_DOUBLE.c_str(), m_ConstraintValue.doubleValue); break; case STRING_PROPERTY: status = valueArg->Set(AJPARAM_STR.c_str(), m_ConstraintValue.charValue); break; default: status = ER_BUS_BAD_SIGNATURE; break; } if (status != ER_OK) { QCC_LogError(status, ("Could not marshal Constraint Value")); delete valueArg; return status; } const char* display = m_GetDisplays ? m_GetDisplays(languageIndx) : m_Displays[languageIndx].c_str(); status = val.Set(AJPARAM_STRUCT_VAR_STR.c_str(), valueArg, display); if (status != ER_OK) { QCC_LogError(status, ("Could not marshal Constraint Value")); delete valueArg; return status; } val.SetOwnershipFlags(MsgArg::OwnsArgs, true); return status; } QStatus ConstraintList::readConstraintArg(MsgArg& val) { QStatus status = ER_OK; MsgArg* valueArg; char* display; CHECK_AND_RETURN(val.Get(AJPARAM_STRUCT_VAR_STR.c_str(), &valueArg, &display)) m_Display = display; switch (valueArg->typeId) { case ALLJOYN_UINT16: { CHECK_AND_RETURN(valueArg->Get(AJPARAM_UINT16.c_str(), &m_ConstraintValue.uint16Value)) m_PropertyType = UINT16_PROPERTY; break; } case ALLJOYN_INT16: { CHECK_AND_RETURN(valueArg->Get(AJPARAM_INT16.c_str(), &m_ConstraintValue.int16Value)) m_PropertyType = INT16_PROPERTY; break; } case ALLJOYN_UINT32: { CHECK_AND_RETURN(valueArg->Get(AJPARAM_UINT32.c_str(), &m_ConstraintValue.uint32Value)) m_PropertyType = UINT32_PROPERTY; break; } case ALLJOYN_INT32: { CHECK_AND_RETURN(valueArg->Get(AJPARAM_INT32.c_str(), &m_ConstraintValue.int32Value)) m_PropertyType = INT32_PROPERTY; break; } case ALLJOYN_UINT64: { CHECK_AND_RETURN(valueArg->Get(AJPARAM_UINT64.c_str(), &m_ConstraintValue.uint64Value)) m_PropertyType = UINT64_PROPERTY; break; } case ALLJOYN_INT64: { CHECK_AND_RETURN(valueArg->Get(AJPARAM_INT64.c_str(), &m_ConstraintValue.int64Value)) m_PropertyType = INT64_PROPERTY; break; } case ALLJOYN_DOUBLE: { CHECK_AND_RETURN(valueArg->Get(AJPARAM_DOUBLE.c_str(), &m_ConstraintValue.doubleValue)) m_PropertyType = DOUBLE_PROPERTY; break; } case ALLJOYN_STRING: { char* constraintValue; CHECK_AND_RETURN(valueArg->Get(AJPARAM_STR.c_str(), &constraintValue)) m_ConstraintValueString = constraintValue; m_ConstraintValue.charValue = m_ConstraintValueString.c_str(); m_PropertyType = STRING_PROPERTY; break; } default: status = ER_BUS_SIGNATURE_MISMATCH; break; } return ER_OK; } } /* namespace services */ } /* namespace ajn */
262e86faa5eee9970f13f9328666841bf584b7a1
d0394270a950fe2c0d50c352669e9f8fb3f9d0d6
/src/console/commands/render/mode/renderModeWireframe.h
beb3437aaa2c624d141777fbcf0ed7330b52bdb0
[ "MIT" ]
permissive
jobtalle/LGen
58cb08999adb5abff0b73c3c80dc8b5a1e25837e
4d6afcb232da4c0798f130aae47dfda5032d71a2
refs/heads/master
2021-06-27T13:34:58.265298
2020-10-23T17:20:14
2020-10-23T17:20:14
169,788,726
29
5
null
null
null
null
UTF-8
C++
false
false
374
h
#pragma once #include "console/commands/render/mode/renderMode.h" namespace LGen { class Command::Render::Mode::Wireframe final : public Command { public: Wireframe(); protected: void application( const std::vector<std::string> &arguments, Console &console) override; private: static const std::string KEYWORD; static const std::string FILE_HELP; }; }
95821fed8789b40d1127148b1cdaa10059e0ac5e
9e3de8931eafea0a2e7a686aef81f1279170457b
/c-cpp/sockets/ChatClientServer-cpprestsdk/Common/ProjectUtilities.cpp
e13f06edd380719542cc5609682a602fe88be666
[ "Apache-2.0" ]
permissive
tomj0311/microservices
61698fcf1cb1184eae0a54592e19dc12efe684bf
bdbd7fb51d51d7ebf7d220627c2d7e089413adb3
refs/heads/master
2020-06-13T04:11:04.884137
2020-05-17T19:07:34
2020-05-17T19:07:34
194,529,174
0
0
null
null
null
null
UTF-8
C++
false
false
2,984
cpp
/*** * ==++== * * Copyright (c) Microsoft Corporation. All rights reserved. * 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. * * ==--== * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ * * ProjectUtilities.cpp * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ****/ #include "ProjectUtilities.h" using namespace Windows::Foundation::Collections; using namespace Windows::Networking; using namespace Windows::Networking::Connectivity; using namespace Platform; utility::string_t ProjectUtilities::generate_guid() { GUID guid; CoCreateGuid(&guid); OLECHAR guid_buff[40]; StringFromGUID2(guid, guid_buff, 40); utility::string_t guid_str(guid_buff); return guid_str; } utility::string_t ProjectUtilities::default_screen_name() { IVectorView<HostName^>^ host_name_list = NetworkInformation::GetHostNames(); String^ screen_name_str_p = "MyScreenName"; for (unsigned int i = 0; i < host_name_list->Size; i++) { if (host_name_list->GetAt(i)->Type == HostNameType::DomainName) { screen_name_str_p = host_name_list->GetAt(i)->DisplayName; break; } } utility::string_t screen_name(screen_name_str_p->Data()); return screen_name.substr(0, screen_name.find_first_of('.')); } void ProjectUtilities::ShowMessage(Platform::String^ message) { // Create the message dialog and set its content Windows::UI::Popups::MessageDialog^ msgDiag = ref new Windows::UI::Popups::MessageDialog(message); // Add OK commands Windows::UI::Popups::UICommand^ continueCommand = ref new Windows::UI::Popups::UICommand("OK"); // Add the commands to the dialog msgDiag->Commands->Append(continueCommand); // Show the message dialog msgDiag->ShowAsync(); } pplx::task<void> ProjectUtilities::async_do_while(std::function<pplx::task<bool>(void)> func) { return _do_while_impl(func).then([](bool){}); } pplx::task<bool> ProjectUtilities::_do_while_iteration(std::function<pplx::task<bool>(void)> func) { pplx::task_completion_event<bool> ev; func().then([=](bool task_completed) { ev.set(task_completed); }); return pplx::create_task(ev); } pplx::task<bool> ProjectUtilities::_do_while_impl(std::function<pplx::task<bool>(void)> func) { return _do_while_iteration(func).then([=](bool continue_next_iteration) -> pplx::task<bool> { return ((continue_next_iteration == true) ? _do_while_impl(func) : pplx::task_from_result(false)); }); }
8d890a3c32849677235f91f3977986b8f820e3ed
0f08d97fb9199d47a245d1fa80de28afed9f8491
/tuts/src/Sprite.h
0d9b6cc0a3653b202616b5880d93f81792d7257c
[]
no_license
stillsnowedin/practice
f29caa7fbb8ff80869113f2b630efca3746f2ac8
d689935717e3173aee8291706e52ba8a45e305ab
refs/heads/master
2021-01-01T06:45:24.484677
2015-02-23T08:35:33
2015-02-23T08:35:33
26,898,185
0
0
null
null
null
null
UTF-8
C++
false
false
665
h
#ifndef __tuts__Sprite__ #define __tuts__Sprite__ //ignore gl.h and gl3.h overlap #ifdef __APPLE__ # define GL_DO_NOT_WARN_IF_MULTI_GL_VERSION_HEADERS_INCLUDED #endif #include <OpenGL/gl3.h> #include "Vertex.h" #include "GLTexture.h" #include "ResourceManager.h" #include <cstddef> #include <iostream> #include <string> class Sprite { public: Sprite(); ~Sprite(); void init(float x, float y, float width, float height, std::string texturePath); void draw(); private: float _x; float _y; float _width; float _height; GLuint _vboID; GLuint _vaoID; GLTexture _texture; }; #endif /* defined(__tuts__Sprite__) */
c4bf371c42cca647b65276836d1fe77a96a8d540
23ace58d05876953cb78ff44f963b8e79070889c
/算法/背包问题/01背包/1203留学申请费(有概率).cpp
72338b7f6bf949277e56829b0d1552048852ae20
[]
no_license
InTheBloodHorse/ACM
ae9d2fccb33efee2d54b530eba0b0640aff5ae43
7a1a5c7d3b5e1ede7c62b484f91e89bcf012bd5d
refs/heads/master
2020-03-28T09:01:59.552044
2019-04-30T13:37:58
2019-04-30T13:37:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
546
cpp
#include<bits/stdc++.h> #define INF 1 using namespace std; double dp[100010]; int main() { int n,m; double weight[100001]; double val[100001]; while(scanf("%d%d",&n,&m)!=EOF) { if(n==0 && m==0) break; for(int i=1;i<=m;i++) { scanf("%lf%lf",&weight[i],&val[i]); } for(int i=0;i<=n;i++) dp[i] = INF; for(int i=1;i<=m;i++) { for(int j=n;j>=weight[i];j--) { dp[j] = min(dp[j],dp[j-(int)weight[i]]*(1-val[i])); } } printf("%.1lf%%\n",(1-dp[n])*100); } }
5d3166e3d9107a8ad38232c1bed7e3f17e204ca4
ba4db75b9d1f08c6334bf7b621783759cd3209c7
/src_main/game/shared/dod/weapon_dodbipodgun.cpp
ec4b7fc1bdb7abaa0aec21f4ae83193fcff2950c
[]
no_license
equalent/source-2007
a27326c6eb1e63899e3b77da57f23b79637060c0
d07be8d02519ff5c902e1eb6430e028e1b302c8b
refs/heads/master
2020-03-28T22:46:44.606988
2017-03-27T18:05:57
2017-03-27T18:05:57
149,257,460
2
0
null
2018-09-18T08:52:10
2018-09-18T08:52:09
null
WINDOWS-1252
C++
false
false
20,232
cpp
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "fx_dod_shared.h" #include "weapon_dodbipodgun.h" #include "dod_gamerules.h" #include "engine/IEngineSound.h" #ifndef CLIENT_DLL #include "ndebugoverlay.h" #endif IMPLEMENT_NETWORKCLASS_ALIASED( DODBipodWeapon, DT_BipodWeapon ) BEGIN_NETWORK_TABLE( CDODBipodWeapon, DT_BipodWeapon ) #ifdef CLIENT_DLL RecvPropBool( RECVINFO( m_bDeployed ) ), RecvPropInt( RECVINFO( m_iDeployedReloadModelIndex) ), #else SendPropBool( SENDINFO( m_bDeployed ) ), SendPropModelIndex( SENDINFO(m_iDeployedReloadModelIndex) ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CDODBipodWeapon ) DEFINE_PRED_FIELD( m_bDeployed, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ) END_PREDICTION_DATA() #endif CDODBipodWeapon::CDODBipodWeapon() { } void CDODBipodWeapon::Spawn() { SetDeployed( false ); m_flNextDeployCheckTime = 0; m_iCurrentWorldModel = 0; m_iAltFireHint = HINT_USE_DEPLOY; BaseClass::Spawn(); } void CDODBipodWeapon::SetDeployed( bool bDeployed ) { if ( bDeployed == false ) { m_hDeployedOnEnt = NULL; m_DeployedEntOrigin = vec3_origin; m_flDeployedHeight = 0; #ifdef GAME_DLL CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); if ( pPlayer ) { pPlayer->HandleDeployedMGKillCount( 0 ); // reset when we undeploy } #endif } m_bDeployed = bDeployed; } void CDODBipodWeapon::Precache( void ) { // precache base first, it loads weapon scripts BaseClass::Precache(); const CDODWeaponInfo &info = GetDODWpnData(); if( Q_strlen(info.m_szDeployedModel) > 0 ) { Assert( info.m_iAltWpnCriteria & ALTWPN_CRITERIA_DEPLOYED ); m_iDeployedModelIndex = CBaseEntity::PrecacheModel( info.m_szDeployedModel ); } if( Q_strlen(info.m_szDeployedReloadModel) > 0 ) { Assert( info.m_iAltWpnCriteria & ALTWPN_CRITERIA_DEPLOYED_RELOAD ); m_iDeployedReloadModelIndex = CBaseEntity::PrecacheModel( info.m_szDeployedReloadModel ); } if( Q_strlen(info.m_szProneDeployedReloadModel) > 0 ) { Assert( info.m_iAltWpnCriteria & ALTWPN_CRITERIA_PRONE_DEPLOYED_RELOAD ); m_iProneDeployedReloadModelIndex = CBaseEntity::PrecacheModel( info.m_szProneDeployedReloadModel ); } m_iCurrentWorldModel = m_iWorldModelIndex; Assert( m_iCurrentWorldModel != 0 ); } bool CDODBipodWeapon::CanDrop( void ) { return ( IsDeployed() == false ); } bool CDODBipodWeapon::CanHolster( void ) { return ( IsDeployed() == false ); } void CDODBipodWeapon::Drop( const Vector &vecVelocity ) { // If a player is killed while deployed, this resets the weapon state SetDeployed( false ); BaseClass::Drop( vecVelocity ); } void CDODBipodWeapon::SecondaryAttack( void ) { // Toggle deployed / undeployed if ( IsDeployed() ) UndeployBipod(); else { if ( CanAttack() ) { bool bSuccess = AttemptToDeploy(); CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); Assert( pPlayer ); if ( !bSuccess ) { pPlayer->HintMessage( HINT_MG_DEPLOY_USAGE ); } else { #ifndef CLIENT_DLL pPlayer->RemoveHintTimer( m_iAltFireHint ); #endif } } } } bool CDODBipodWeapon::Reload( void ) { bool bSuccess = BaseClass::Reload(); if ( bSuccess ) { m_flNextSecondaryAttack = gpGlobals->curtime; } return bSuccess; } #include "in_buttons.h" // check in busy frame too, to catch cancelling reloads void CDODBipodWeapon::ItemBusyFrame( void ) { BipodThink(); CBasePlayer *pPlayer = GetPlayerOwner(); if ( !pPlayer ) return; if ((pPlayer->m_nButtons & IN_ATTACK2) && (m_flNextSecondaryAttack <= gpGlobals->curtime)) { SecondaryAttack(); pPlayer->m_nButtons &= ~IN_ATTACK2; } BaseClass::ItemBusyFrame(); } void CDODBipodWeapon::ItemPostFrame( void ) { BipodThink(); BaseClass::ItemPostFrame(); } // see if we're still deployed on the same entity at the same height // in future can be expanded to check when deploying on other ents that may move / die / break void CDODBipodWeapon::BipodThink( void ) { if ( m_flNextDeployCheckTime < gpGlobals->curtime ) { if ( IsDeployed() ) { if ( CheckDeployEnt() == false ) { UndeployBipod(); // cancel any reload in progress m_bInReload = false; m_flNextPrimaryAttack = gpGlobals->curtime + 0.1; m_flNextSecondaryAttack = gpGlobals->curtime + 0.1; } } m_flNextDeployCheckTime = gpGlobals->curtime + 0.2; } } void CDODBipodWeapon::DoFireEffects() { BaseClass::DoFireEffects(); CBaseEntity *pDeployedOn = m_hDeployedOnEnt.Get(); // in future can be expanded to check when deploying on other ents that may move / die / break if ( pDeployedOn && pDeployedOn->IsPlayer() && IsDeployed() ) { #ifndef CLIENT_DLL CSingleUserRecipientFilter user( (CBasePlayer *)pDeployedOn ); enginesound->SetPlayerDSP( user, 32, false ); #endif } } // Do the work of deploying the gun at the current location and angles void CDODBipodWeapon::DeployBipod( float flHeight, CBaseEntity *pDeployedOn, float flYawLimitLeft, float flYawLimitRight ) { m_flDeployedHeight = flHeight; m_hDeployedOnEnt = pDeployedOn; if ( pDeployedOn ) m_DeployedEntOrigin = pDeployedOn->GetAbsOrigin(); else m_DeployedEntOrigin = vec3_origin; // world ent SendWeaponAnim( GetDeployActivity() ); SetDeployed( true ); CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); pPlayer->m_Shared.SetDeployed( true, flHeight ); pPlayer->m_Shared.SetDeployedYawLimits( flYawLimitLeft, flYawLimitRight ); // Save this off so we do duck checks later, even though we won't be flagged as ducking m_bDuckedWhenDeployed = pPlayer->m_Shared.IsDucking(); // More TODO: // recalc our yaw limits if the item we're deployed on has moved or rotated // if our new limits are outside our current eye angles, undeploy us m_flNextPrimaryAttack = gpGlobals->curtime + SequenceDuration(); m_flNextSecondaryAttack = gpGlobals->curtime + SequenceDuration(); m_flTimeWeaponIdle = gpGlobals->curtime + SequenceDuration(); } // Do the work of undeploying the gun void CDODBipodWeapon::UndeployBipod( void ) { SendWeaponAnim( GetUndeployActivity() ); SetDeployed( false ); CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); pPlayer->m_Shared.SetDeployed( false ); // if we cancelled our reload by undeploying, don't let the reload complete if ( m_bInReload ) m_bInReload = false; m_flNextPrimaryAttack = gpGlobals->curtime + SequenceDuration(); m_flNextSecondaryAttack = gpGlobals->curtime + SequenceDuration(); pPlayer->m_flNextAttack = m_flNextPrimaryAttack; m_flTimeWeaponIdle = gpGlobals->curtime + SequenceDuration(); } #ifndef CLIENT_DLL ConVar dod_debugmgdeploy( "dod_debugmgdeploy", "0", FCVAR_CHEAT|FCVAR_GAMEDLL ); #endif bool CDODBipodWeapon::AttemptToDeploy( void ) { CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); if ( pPlayer->GetGroundEntity() == NULL ) return false; if ( pPlayer->m_Shared.IsGettingUpFromProne() || pPlayer->m_Shared.IsGoingProne() ) return false; CBaseEntity *pDeployedOn = NULL; float flDeployedHeight = 0.0f; float flYawLimitLeft = 0; float flYawLimitRight = 0; if ( TestDeploy( &flDeployedHeight, &pDeployedOn, &flYawLimitLeft, &flYawLimitRight ) ) { if ( pPlayer->m_Shared.IsProne() && !pPlayer->m_Shared.IsGettingUpFromProne() ) { DeployBipod( flDeployedHeight, NULL, flYawLimitLeft, flYawLimitRight ); return true; } else { float flMinDeployHeight = 24.0; if( flDeployedHeight >= flMinDeployHeight ) { DeployBipod( flDeployedHeight, pDeployedOn, flYawLimitLeft, flYawLimitRight ); return true; } } } return false; } bool CDODBipodWeapon::CheckDeployEnt( void ) { CBaseEntity *pDeployedOn = NULL; float flDeployedHeight = 0.0f; if ( TestDeploy( &flDeployedHeight, &pDeployedOn ) == false ) return false; // If the entity we were deployed on has changed, or has moved, the origin // of it will be different. If so, recalc our yaw limits. if ( pDeployedOn ) { if ( m_DeployedEntOrigin != pDeployedOn->GetAbsOrigin() ) { float flYawLimitLeft = 0, flYawLimitRight = 0; TestDeploy( &flDeployedHeight, &pDeployedOn, &flYawLimitLeft, &flYawLimitRight ); CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); if ( pPlayer ) pPlayer->m_Shared.SetDeployedYawLimits( flYawLimitLeft, flYawLimitRight ); m_DeployedEntOrigin = pDeployedOn->GetAbsOrigin(); } } // 20 unit tolerance in height if ( abs( m_flDeployedHeight - flDeployedHeight ) > 20 ) return false; return true; } bool CDODBipodWeapon::TestDeploy( float *flDeployedHeight, CBaseEntity **pDeployedOn, float *flYawLimitLeft /* = NULL */, float *flYawLimitRight /* = NULL */ ) { CDODPlayer *pPlayer = ToDODPlayer( GetPlayerOwner() ); QAngle angles = pPlayer->EyeAngles(); float flPitch = angles[PITCH]; if( flPitch > 180 ) { flPitch -= 360; } if( flPitch > MIN_DEPLOY_PITCH || flPitch < MAX_DEPLOY_PITCH ) { return false; } bool bSuccess = false; // if we're not finding the range, test at the current angles if ( flYawLimitLeft == NULL && flYawLimitRight == NULL ) { // test our current angle only bSuccess = TestDeployAngle( pPlayer, flDeployedHeight, pDeployedOn, angles ); } else { float flSaveYaw = angles[YAW]; const float flAngleDelta = 5; const float flMaxYaw = 45; float flLeft = 0; float flRight = 0; float flTestDeployHeight = 0; CBaseEntity *pTestDeployedOn = NULL; // Sweep Left while ( flLeft <= flMaxYaw ) { angles[YAW] = flSaveYaw + flLeft; if ( TestDeployAngle( pPlayer, &flTestDeployHeight, &pTestDeployedOn, angles ) == true ) { if ( flLeft == 0 ) // first sweep is authoritative on deploy height and entity { *flDeployedHeight = flTestDeployHeight; *pDeployedOn = pTestDeployedOn; } else if ( abs( *flDeployedHeight - flTestDeployHeight ) > 20 ) { // don't allow yaw to a position that is too different in height break; } *flYawLimitLeft = flLeft; } else { break; } flLeft += flAngleDelta; } // can't deploy here, drop out early if ( flLeft <= 0 ) return false; // we already tested directly ahead and it was clear. skip one test flRight += flAngleDelta; // Sweep Right while ( flRight <= flMaxYaw ) { angles[YAW] = flSaveYaw - flRight; if ( TestDeployAngle( pPlayer, &flTestDeployHeight, &pTestDeployedOn, angles ) == true ) { if ( abs( *flDeployedHeight - flTestDeployHeight ) > 20 ) { // don't allow yaw to a position that is too different in height break; } *flYawLimitRight = flRight; } else { break; } flRight += flAngleDelta; } bSuccess = true; } return bSuccess; } //ConVar dod_deploy_box_size( "dod_deploy_box_size", "8", FCVAR_REPLICATED ); #include "util_shared.h" // trace filter that ignores all players except the passed one class CTraceFilterIgnorePlayersExceptFor : public CTraceFilterSimple { public: // It does have a base, but we'll never network anything below here.. DECLARE_CLASS( CTraceFilterIgnorePlayersExceptFor, CTraceFilterSimple ); CTraceFilterIgnorePlayersExceptFor( const IHandleEntity *passentity, int collisionGroup ) : CTraceFilterSimple( passentity, collisionGroup ) { } virtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask ) { CBaseEntity *pEntity = EntityFromEntityHandle( pServerEntity ); if ( pEntity->IsPlayer() ) { if ( pEntity != GetPassEntity() ) { return false; } else return true; } return true; } }; #define DEPLOY_DOWNTRACE_FORWARD_DIST 16 #define DEPLOY_DOWNTRACE_OFFSET 16 // yay for magic numbers bool CDODBipodWeapon::TestDeployAngle( CDODPlayer *pPlayer, float *flDeployedHeight, CBaseEntity **pDeployedOn, QAngle angles ) { // make sure we are deployed on the same entity at the same height trace_t tr; angles[PITCH] = 0; Vector forward, right, up; AngleVectors( angles, &forward, &right, &up ); // start at top of player bbox Vector vecStart = pPlayer->GetAbsOrigin(); float flForwardTraceDist = 32; // check us as ducking if we are ducked, or if were ducked when we were deployed bool bDucking = pPlayer->m_Shared.IsDucking() || ( IsDeployed() && m_bDuckedWhenDeployed ); if ( pPlayer->m_Shared.IsProne() ) { vecStart.z += VEC_PRONE_HULL_MAX[2]; flForwardTraceDist = 16; } else if ( bDucking ) { vecStart.z += VEC_DUCK_HULL_MAX[2]; } else { vecStart.z += 60; } int dim = 1; // dod_deploy_box_size.GetInt(); Vector vecDeployTraceBoxSize( dim, dim, dim ); vecStart.z -= vecDeployTraceBoxSize[2]; vecStart.z -= 4; // sandbags are around 50 units high. Shouldn't be able to deploy on anything a lot higher than that // optimal standing height ( for animation's sake ) is around 42 units // optimal ducking height is around 20 units ( 20 unit high object, plus 8 units of gun ) // Start one half box width away from the edge of the player hull Vector vecForwardStart = vecStart + forward * ( VEC_HULL_MAX[0] + vecDeployTraceBoxSize[0] ); int traceMask = MASK_SOLID; CBaseEntity *pDeployedOnPlayer = NULL; if ( m_hDeployedOnEnt && m_hDeployedOnEnt->IsPlayer() ) { pDeployedOnPlayer = m_hDeployedOnEnt.Get(); } CTraceFilterIgnorePlayersExceptFor deployedFilter( pDeployedOnPlayer, COLLISION_GROUP_NONE ); CTraceFilterSimple undeployedFilter( pPlayer, COLLISION_GROUP_NONE ); // if we're deployed, skip all players except for the deployed on player // if we're not, only skip ourselves ITraceFilter *filter; if ( IsDeployed() ) filter = &deployedFilter; else filter = &undeployedFilter; UTIL_TraceHull( vecForwardStart, vecForwardStart + forward * ( flForwardTraceDist - 2 * vecDeployTraceBoxSize[0] ), -vecDeployTraceBoxSize, vecDeployTraceBoxSize, traceMask, filter, &tr ); #ifndef CLIENT_DLL if ( dod_debugmgdeploy.GetBool() ) { NDebugOverlay::Line( vecForwardStart, vecForwardStart + forward * ( flForwardTraceDist - 2 * vecDeployTraceBoxSize[0] ), 0, 0, 255, true, 0.1 ); NDebugOverlay::Box( vecForwardStart, -vecDeployTraceBoxSize, vecDeployTraceBoxSize, 255, 0, 0, 128, 0.1 ); NDebugOverlay::Box( tr.endpos, -vecDeployTraceBoxSize, vecDeployTraceBoxSize, 0, 0, 255, 128, 0.1 ); } #endif // Test forward, are we trying to deploy into a solid object? if ( tr.fraction < 1.0 ) { return false; } // If we're prone, we can always deploy, don't do the ground test if ( pPlayer->m_Shared.IsProne() && !pPlayer->m_Shared.IsGettingUpFromProne() ) { // MATTTODO: do trace from *front* of player, not from the edge of crouch hull // this is sufficient *flDeployedHeight = PRONE_DEPLOY_HEIGHT; return true; } // fix prediction hitch when coming up from prone. client thinks we aren't // prone, but hull is still prone hull // assumes prone hull is shorter than duck hull! if ( pPlayer->WorldAlignMaxs().z <= VEC_PRONE_HULL_MAX.z ) return false; // Else trace down Vector vecDownTraceStart = vecStart + forward * ( VEC_HULL_MAX[0] + DEPLOY_DOWNTRACE_FORWARD_DIST ); int iTraceHeight = -( pPlayer->WorldAlignMaxs().z ); // search down from the forward trace // use the farthest point first. If that fails, move towards the player a few times // to see if they are trying to deploy on a thin railing bool bFound = false; int maxAttempts = 4; float flHighestTraceEnd = vecDownTraceStart.z + iTraceHeight; CBaseEntity *pBestDeployEnt = NULL; while( maxAttempts > 0 ) { UTIL_TraceHull( vecDownTraceStart, vecDownTraceStart + Vector(0,0,iTraceHeight), // trace forward one box width -vecDeployTraceBoxSize, vecDeployTraceBoxSize, traceMask, filter, &tr ); #ifndef CLIENT_DLL if ( dod_debugmgdeploy.GetBool() ) { NDebugOverlay::Line( vecDownTraceStart, tr.endpos, 255, 0, 0, true, 0.1 ); NDebugOverlay::Box( vecDownTraceStart, -vecDeployTraceBoxSize, vecDeployTraceBoxSize, 255, 0, 0, 128, 0.1 ); NDebugOverlay::Box( tr.endpos, -vecDeployTraceBoxSize, vecDeployTraceBoxSize, 0, 0, 255, 128, 0.1 ); } #endif bool bSuccess = ( tr.fraction < 1.0 ) && !tr.startsolid && !tr.allsolid; // if this is the first one found, set found flag if ( bSuccess && !bFound ) { bFound = true; } else if ( bFound == true && bSuccess == false ) { // it failed and we have some data. break here break; } // if this trace is better ( higher ) use this one if ( tr.endpos.z > flHighestTraceEnd ) { flHighestTraceEnd = tr.endpos.z; pBestDeployEnt = tr.m_pEnt; } --maxAttempts; // move towards the player, looking for a better height to deploy on vecDownTraceStart += forward * -4; } if ( bFound == false || pBestDeployEnt == NULL ) return false; *pDeployedOn = pBestDeployEnt; *flDeployedHeight = flHighestTraceEnd - vecDeployTraceBoxSize[0] + DEPLOY_DOWNTRACE_OFFSET - pPlayer->GetAbsOrigin().z; return true; } Activity CDODBipodWeapon::GetUndeployActivity( void ) { return ACT_VM_UNDEPLOY; } Activity CDODBipodWeapon::GetDeployActivity( void ) { return ACT_VM_DEPLOY; } Activity CDODBipodWeapon::GetPrimaryAttackActivity( void ) { Activity actPrim; if( IsDeployed() ) actPrim = ACT_VM_PRIMARYATTACK_DEPLOYED; else actPrim = ACT_VM_PRIMARYATTACK; return actPrim; } Activity CDODBipodWeapon::GetReloadActivity( void ) { Activity actReload; if( IsDeployed() ) actReload = ACT_VM_RELOAD_DEPLOYED; else actReload = ACT_VM_RELOAD; return actReload; } Activity CDODBipodWeapon::GetIdleActivity( void ) { Activity actIdle; if( IsDeployed() ) actIdle = ACT_VM_IDLE_DEPLOYED; else actIdle = ACT_VM_IDLE; return actIdle; } float CDODBipodWeapon::GetWeaponAccuracy( float flPlayerSpeed ) { float flSpread = BaseClass::GetWeaponAccuracy( flPlayerSpeed ); if( IsDeployed() ) { flSpread = m_pWeaponInfo->m_flSecondaryAccuracy; } return flSpread; } #ifdef CLIENT_DLL int CDODBipodWeapon::GetWorldModelIndex( void ) { if( GetOwner() == NULL ) return m_iWorldModelIndex; else if( m_bUseAltWeaponModel ) return m_iWorldModelIndex; //override for hand signals etc else return m_iCurrentWorldModel; } void CDODBipodWeapon::CheckForAltWeapon( int iCurrentState ) { int iCriteria = GetDODWpnData().m_iAltWpnCriteria; bool bReloading = ( iCurrentState & ALTWPN_CRITERIA_RELOADING ); if( bReloading ) { if( IsDeployed() && iCurrentState & ALTWPN_CRITERIA_PRONE && iCriteria & ALTWPN_CRITERIA_PRONE_DEPLOYED_RELOAD ) { m_iCurrentWorldModel = m_iProneDeployedReloadModelIndex; // prone deployed reload } else if( IsDeployed() && iCriteria & ALTWPN_CRITERIA_DEPLOYED_RELOAD ) { m_iCurrentWorldModel = m_iDeployedReloadModelIndex; // deployed reload } else if( iCriteria & ALTWPN_CRITERIA_RELOADING ) { m_iCurrentWorldModel = m_iReloadModelIndex; // left handed reload } else { m_iCurrentWorldModel = m_iWorldModelIndex; // normal weapon reload } } else if( IsDeployed() && iCriteria & ALTWPN_CRITERIA_DEPLOYED ) { m_iCurrentWorldModel = m_iDeployedModelIndex; // bipod down } else if( (iCurrentState & iCriteria) & ALTWPN_CRITERIA_FIRING ) { // don't think we have any weapons that do this m_iCurrentWorldModel = m_iReloadModelIndex; // left handed shooting? } else { m_iCurrentWorldModel = m_iWorldModelIndex; // normal weapon } } #endif
736028730e6b116e8f4b04049b3a2a123dae02f2
766758b6771a711954b25db9f9683f117758fed6
/chapter2/deleteXinLink.cpp
8a8c5039fe682dd3110a02b29b6367a21ae072e5
[]
no_license
Edddddddddy/data_structure
a8d66ace875ba65ad6599e775a62f608cc99dc53
0f3427c99fc25cb0077e503a5ae3858c448ec074
refs/heads/main
2023-08-17T18:42:34.965683
2021-10-16T15:10:32
2021-10-16T15:10:32
405,097,519
1
0
null
null
null
null
UTF-8
C++
false
false
2,364
cpp
#include <cstdio> #include <stdlib.h> #include <stdio.h> struct Link{ int value; struct Link *next; }; void deleteX(Link *&p, int delNum){ //递归删除 struct Link *pre; //用于释放 if (p == NULL) return; if (p->value == delNum){ pre = p; p = p->next; free(pre); deleteX(p, delNum); } else deleteX(p->next, delNum); } //尾插法 Link *create(){ struct Link *p, *rear, *head; int count = 0; rear = (struct Link *)malloc(sizeof(struct Link)); head = (struct Link *)malloc(sizeof(struct Link)); int value; printf("请输入链表节点value:(9999结束)"); scanf("%d", &value); while(value != 9999){ p = (struct Link *)malloc(sizeof(struct Link)); p->value = value; p->next = NULL; if (count++ == 0){ rear = p; head = p; } else { rear->next = p; rear = p; } scanf("%d", &value); } rear->next = NULL; return head; } //头插法创建单链表 Link *create2(){ struct Link *p , *rear, *head; rear = (struct Link *)malloc(sizeof(struct Link)); head = (struct Link *)malloc(sizeof(struct Link)); head = rear = NULL; int value; printf("请输入链表节点value:(9999结束)"); scanf("%d", &value); int count = 0; while(value != 9999){ p = (struct Link *)malloc(sizeof(struct Link)); p->value = value; if (head == NULL){ head = p; rear = p; } else { p->next = head->next; head->next = p; rear = p; //head 后面是rear if (count++ == 0){ //插入第二个元素 rear->next = NULL; } } scanf("%d", &value); } } int main(){ printf("尾插法创建单链表\n"); struct Link *head, *q; head = create(); q = head; printf("打印链表:"); while (q != NULL){ printf("%d ", q->value); q = q->next; } q = head; printf("输入要删除元素:"); int delNum; scanf("%d", &delNum); deleteX(q, delNum); printf("打印删除后的链表:"); while (q != NULL){ printf("%d ", q->value); q = q->next; } q = head; return 0; }
c5164a5a1f4e796f15a06e80aa1632e0a30a1914
9722e49f01f30cbd9a673e29c2ab7293db068985
/Intermediate/Build/Win64/UE4Editor/Inc/FPSGame/FPSGameProjectile.generated.h
62c4e4952ffa1d9d94b9b98c2a5dbe6ccafed0fe
[]
no_license
banned2054/FPSGame
dd8acb6fc8005da31f612de7e1e373b8d4369495
af9da35d32545be924a2a44f48e0dd24338a7ae1
refs/heads/master
2023-09-02T04:37:12.205073
2021-11-05T19:58:21
2021-11-05T19:58:21
425,064,242
0
0
null
null
null
null
UTF-8
C++
false
false
4,597
h
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS class UPrimitiveComponent; class AActor; struct FVector; struct FHitResult; #ifdef FPSGAME_FPSGameProjectile_generated_h #error "FPSGameProjectile.generated.h already included, missing '#pragma once' in FPSGameProjectile.h" #endif #define FPSGAME_FPSGameProjectile_generated_h #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_SPARSE_DATA #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_RPC_WRAPPERS \ \ DECLARE_FUNCTION(execOnHit); #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_RPC_WRAPPERS_NO_PURE_DECLS \ \ DECLARE_FUNCTION(execOnHit); #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAFPSGameProjectile(); \ friend struct Z_Construct_UClass_AFPSGameProjectile_Statics; \ public: \ DECLARE_CLASS(AFPSGameProjectile, AActor, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/FPSGame"), NO_API) \ DECLARE_SERIALIZER(AFPSGameProjectile) \ static const TCHAR* StaticConfigName() {return TEXT("Game");} \ #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_INCLASS \ private: \ static void StaticRegisterNativesAFPSGameProjectile(); \ friend struct Z_Construct_UClass_AFPSGameProjectile_Statics; \ public: \ DECLARE_CLASS(AFPSGameProjectile, AActor, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/FPSGame"), NO_API) \ DECLARE_SERIALIZER(AFPSGameProjectile) \ static const TCHAR* StaticConfigName() {return TEXT("Game");} \ #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API AFPSGameProjectile(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AFPSGameProjectile) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AFPSGameProjectile); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AFPSGameProjectile); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AFPSGameProjectile(AFPSGameProjectile&&); \ NO_API AFPSGameProjectile(const AFPSGameProjectile&); \ public: #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AFPSGameProjectile(AFPSGameProjectile&&); \ NO_API AFPSGameProjectile(const AFPSGameProjectile&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AFPSGameProjectile); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AFPSGameProjectile); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(AFPSGameProjectile) #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_PRIVATE_PROPERTY_OFFSET \ FORCEINLINE static uint32 __PPO__CollisionComp() { return STRUCT_OFFSET(AFPSGameProjectile, CollisionComp); } \ FORCEINLINE static uint32 __PPO__ProjectileMovement() { return STRUCT_OFFSET(AFPSGameProjectile, ProjectileMovement); } #define FPSGame_Source_FPSGame_FPSGameProjectile_h_12_PROLOG #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_PRIVATE_PROPERTY_OFFSET \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_SPARSE_DATA \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_RPC_WRAPPERS \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_INCLASS \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define FPSGame_Source_FPSGame_FPSGameProjectile_h_15_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_PRIVATE_PROPERTY_OFFSET \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_SPARSE_DATA \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_RPC_WRAPPERS_NO_PURE_DECLS \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_INCLASS_NO_PURE_DECLS \ FPSGame_Source_FPSGame_FPSGameProjectile_h_15_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> FPSGAME_API UClass* StaticClass<class AFPSGameProjectile>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID FPSGame_Source_FPSGame_FPSGameProjectile_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
a08e68adfeb4e1738db65f85c4f2498ff9ef6c0d
c8c3bbf8a1728252d81847661dcacfc7c941cf93
/tests/test_random_lz4.cpp
902239d9ccbcd2dd0645bcb3392510873a1a0af8
[]
permissive
ucasfl/nvcomp
6a66ee4a5e94851cb7bb0f056c04ac75e350173d
ad3615db0320ed1a47d234890206c9fb393208c7
refs/heads/main
2023-06-15T08:50:40.459322
2021-07-18T06:03:08
2021-07-18T06:03:08
387,102,523
0
0
BSD-3-Clause
2021-07-18T06:00:29
2021-07-18T06:00:28
null
UTF-8
C++
false
false
6,201
cpp
/* * Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION 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 ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define CATCH_CONFIG_MAIN #ifndef VERBOSE #define VERBOSE 0 #endif #include "test_common.h" // Test method that takes an input data, compresses it (on the CPU), // decompresses it on the GPU, and verifies it is correct. // Uses LZ4 Compression template <typename T> void test_lz4(const std::vector<T>& data, size_t /*chunk_size*/) { const nvcompType_t type = nvcomp::TypeOf<T>(); size_t chunk_size = 1 << 16; #if VERBOSE > 1 // dump input data std::cout << "Input" << std::endl; for (size_t i = 0; i < data.size(); i++) std::cout << data[i] << " "; std::cout << std::endl; #endif // these two items will be the only forms of communication between // compression and decompression void* d_comp_out = nullptr; size_t comp_out_bytes = 0; { // this block handles compression, and we scope it to ensure only // serialized metadata and compressed data, are the only things passed // between compression and decopmression std::cout << "----------" << std::endl; std::cout << "uncompressed (B): " << data.size() * sizeof(T) << std::endl; // create GPU only input buffer void* d_in_data; const size_t in_bytes = sizeof(T) * data.size(); CUDA_CHECK(cudaMalloc(&d_in_data, in_bytes)); CUDA_CHECK( cudaMemcpy(d_in_data, data.data(), in_bytes, cudaMemcpyHostToDevice)); cudaStream_t stream; cudaStreamCreate(&stream); nvcompError_t status; LZ4Compressor compressor(chunk_size); size_t comp_temp_bytes; compressor.configure(in_bytes, &comp_temp_bytes, &comp_out_bytes); void* d_comp_temp; CUDA_CHECK(cudaMalloc(&d_comp_temp, comp_temp_bytes)); CUDA_CHECK(cudaMalloc(&d_comp_out, comp_out_bytes)); size_t* comp_out_bytes_ptr; CUDA_CHECK(cudaMallocHost( (void**)&comp_out_bytes_ptr, sizeof(*comp_out_bytes_ptr))); compressor.compress_async( d_in_data, in_bytes, d_comp_temp, comp_temp_bytes, d_comp_out, comp_out_bytes_ptr, stream); CUDA_CHECK(cudaStreamSynchronize(stream)); comp_out_bytes = *comp_out_bytes_ptr; cudaFree(d_comp_temp); cudaFree(d_in_data); cudaStreamDestroy(stream); std::cout << "comp_size: " << comp_out_bytes << ", compressed ratio: " << std::fixed << std::setprecision(2) << (double)in_bytes / comp_out_bytes << std::endl; } { // this block handles decompression, and we scope it to ensure only // serialized metadata and compressed data, are the only things passed // between compression and decopmression // cudaStream_t stream; cudaStreamCreate(&stream); LZ4Decompressor decompressor; size_t temp_bytes; size_t decomp_out_bytes; decompressor.configure( d_comp_out, comp_out_bytes, &temp_bytes, &decomp_out_bytes, stream); void* temp_ptr; cudaMalloc(&temp_ptr, temp_bytes); T* out_ptr = NULL; cudaMalloc((void**)&out_ptr, decomp_out_bytes); auto start = std::chrono::steady_clock::now(); decompressor.decompress_async( d_comp_out, comp_out_bytes, temp_ptr, temp_bytes, out_ptr, decomp_out_bytes, stream); CUDA_CHECK(cudaStreamSynchronize(stream)); // stop timing and the profiler auto end = std::chrono::steady_clock::now(); std::cout << "throughput (GB/s): " << gbs(start, end, decomp_out_bytes) << std::endl; cudaStreamDestroy(stream); cudaFree(d_comp_out); cudaFree(temp_ptr); std::vector<T> res(decomp_out_bytes / sizeof(T)); cudaMemcpy(&res[0], out_ptr, decomp_out_bytes, cudaMemcpyDeviceToHost); #if VERBOSE > 1 // dump output data std::cout << "Output" << std::endl; for (size_t i = 0; i < data.size(); i++) std::cout << ((T*)out_ptr)[i] << " "; std::cout << std::endl; #endif REQUIRE(res == data); } } template <typename T> void test_random_lz4( int max_val, int max_run, size_t chunk_size) { // generate random data std::vector<T> data; int seed = (max_val ^ max_run ^ chunk_size); random_runs(data, (T)max_val, (T)max_run, seed); test_lz4<T>(data, chunk_size); } // int TEST_CASE("small-LZ4", "[small]") { test_random_lz4<int>(10, 10, 10000); } TEST_CASE("medium-LZ4", "[small]") { test_random_lz4<int>(10000, 10, 100000); } TEST_CASE("large-LZ4", "[large][bp]") { test_random_lz4<int>(10000, 1000, 10000000); } // long long TEST_CASE("small-LZ4-ll", "[small]") { test_random_lz4<int64_t>(10, 10, 10000); } TEST_CASE("large-LZ4-ll", "[large]") { test_random_lz4<int64_t>(10000, 1000, 10000000); }
99e777c0873a951f0f2b75b5f8b3bb7a3696e5a2
394ab75b729863a4134b9b9123b5ecdade5825d8
/HDOJ1875畅通工程再续(最小生成树,稀疏图,但还是用了kruskal).cpp
ec58611b7512f00a8fa8e59f1d8d8ac5e90dcdfd
[]
no_license
Overstars/Summer-practice-mission
612af592a796e00bd7b3781b62d6ee766dd550ae
76d78e70edb3923173ba069d58fa44eb816d838b
refs/heads/master
2022-02-18T12:09:55.385045
2019-08-29T14:59:48
2019-08-29T14:59:48
197,879,035
2
0
null
null
null
null
GB18030
C++
false
false
1,402
cpp
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath>//这题要尝试所有边嘞,稀疏图啊 using namespace std; const int inf=0x3f3f3f3f,maxn=105; struct Node { int x,y; } node[maxn]; struct edge { int u,v; double w; } e[maxn*maxn]; int father[maxn]; bool cmp(edge x,edge y) { return x.w<y.w; } int findfa(int x) { if(x!=father[x]) father[x]=findfa(father[x]); return father[x]; } int Merge(int a,int b) { int x=findfa(a),y=findfa(b); if(x==y) return 0; if(x<y) father[y]=x; else father[x]=y; return 1; } double kruskal(int n,int m) { double ans=0; for(int i=0;i<m;i++) { if(e[i].w>=10&&e[i].w<=1000&&Merge(e[i].u,e[i].v)) { ans+=e[i].w; n--; if(n==1) return ans; } } return -1; } int main() { int t,c,x,y; cin>>t; while(t--){ cin>>c; for(int i=1;i<=c;i++) cin>>node[i].x>>node[i].y; int cnt=0; for(int i=1;i<=c;i++) for(int j=1;j<i;j++) { double dist=sqrt((node[i].x-node[j].x)*(node[i].x-node[j].x)+(node[i].y-node[j].y)*(node[i].y-node[j].y)); e[cnt].u=i; e[cnt].v=j; e[cnt++].w=(dist<10||dist>1000)?inf:dist; } for(int i=1;i<=c;i++) father[i]=i; sort(e,e+cnt,cmp); double ans=0; if((ans=kruskal(c,cnt))==-1) cout<<"oh!"<<endl; else printf("%.1lf\n",ans*100); } return 0; }
7fc9252d3b8150932959f9eb9e9319d4efe92c04
f03bc4a82f620c336125bff5064a2f747db6802f
/sources/ModelList.hpp
dbaa0f5922ed655bd94fa5c17d192be4d63008be
[]
no_license
ShrademnThill/ogre-construction-set
4a997cd649f9697ef31d9f9983bec4237ad19734
38cb824e71cc4293922aa13fb7ff5e9769709120
refs/heads/master
2021-01-19T17:55:56.249422
2012-04-26T12:35:53
2012-04-26T12:35:53
42,311,556
0
0
null
null
null
null
UTF-8
C++
false
false
1,122
hpp
#ifndef MODELLIST_HPP #define MODELLIST_HPP #include <QAbstractTableModel> #include <QList> #include "Model.hpp" class ModelList : public QAbstractTableModel { public: ModelList(QObject * parent = 0); ModelList(QStringList const & paths, QObject * parent = 0); ~ModelList(void); int rowCount(QModelIndex const & parent) const; int columnCount(QModelIndex const & parent) const; QVariant data(QModelIndex const & index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const; Qt::ItemFlags flags(QModelIndex const & index) const; bool setData(QModelIndex const & index, const QVariant &value, int role = Qt::EditRole); bool insertRows(int row, int count, QModelIndex const & index = QModelIndex()); bool removeRows(int row, int count, QModelIndex const & index = QModelIndex()); QList<Model> const & getList(void) const; void build(QString const & path, bool rec); void clearList(); private: QList<Model> m_list; bool isModel(QString const & path) const; }; #endif // MODELLIST_HPP
8406e7aecb1a18cf9d2994d17a7e6a6c7d07a10d
21599bb66069e266cb8a77014fa86ebcb40e0367
/1248.cpp
671b44c7ed766e84cc413099b4a65fbe92042d29
[]
no_license
Hehe-0/Record
bb34474d523eb4ff80bb1eaaff7c6c316a724c1a
1509185538a8d4064b53f7ad234e7d9c4c5617ba
refs/heads/main
2023-08-31T16:44:44.048016
2021-10-28T12:15:00
2021-10-28T12:15:00
390,011,465
1
0
null
null
null
null
UTF-8
C++
false
false
841
cpp
#include<bits/stdc++.h> using namespace std; int n; int a[10000],t[10000],b[10000],ans[10000]; struct node { int minn,num; }th[10000]; bool cmp(node x,node y) { return x.minn<y.minn; } int main() { ios::sync_with_stdio(false); cin>>n; for(int i=1;i<=n;i++) { th[i].num=i; cin>>a[i]; } for(int i=1;i<=n;i++) { cin>>b[i]; th[i].minn=min(a[i],b[i]); } sort(th+1,th+1+n,cmp); int l=0,r=n+1; for(int i=1;i<=n;i++) { if(th[i].minn==a[th[i].num]) { l++; ans[l]=th[i].num; } else { r--; ans[r]=th[i].num; } } for(int i=1;i<=n;i++) t[i]=t[i-1]+a[ans[i]]; int sum=t[1]+b[ans[1]]; for(int i=2;i<=n;i++) { sum=max(t[i],sum)+b[ans[i]]; } cout<<sum<<endl; for(int i=1;i<=n;i++) cout<<ans[i]<<" "; return 0; }
35ca20017bd3341abebd9e335249bd74a9039499
0fc7efa847037ab123c553e8445785b3bddc462d
/calibration_tool/GL/VertexArray.h
4d7b2ef80fb83055fbaf86dd683232b522864406
[ "MIT" ]
permissive
michalpelka/catoptric_livox
6f0b71460a79e300c9313ec61706f497d38ca8b1
fde4db428840509b6102ac0d2aacee6d4d973ca8
refs/heads/main
2023-07-16T05:35:44.569872
2021-08-14T21:57:24
2021-08-14T21:57:24
395,836,435
9
0
MIT
2022-12-19T10:05:39
2021-08-14T00:13:57
C++
UTF-8
C++
false
false
283
h
#pragma once #include "VertexBuffer.h" class VertexBufferLayout; class VertexArray { public: VertexArray(); ~VertexArray(); void AddBuffer(const VertexBuffer &vb, const VertexBufferLayout& layout); void Bind() const; void Unbind() const; private: unsigned int m_RenderId; };
f31774a485ae310786ef76fcf38883458370d0cc
8e59d28b2df200c2da4820b1bb02f5e45023ab73
/src/blockfile.cpp
20f0c56792a5720ec2ce924285dd308e58eaf096
[ "MIT" ]
permissive
Piradoxlanieve/galaxycash
d35fdc1a84577a59a48acb93ec49b7907a0c74f3
20540b2c4a16d38c0a5e8596dd59380775c98f2d
refs/heads/master
2020-03-12T01:33:18.535565
2018-04-17T18:44:38
2018-04-17T18:44:38
130,379,077
1
0
null
2018-04-20T15:15:30
2018-04-20T15:15:29
null
UTF-8
C++
false
false
3,764
cpp
// Copyright (c) 2017-2018 The GalaxyCash developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/lexical_cast.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/assign/list_of.hpp> #include "main.h" #include "chainparams.h" #include "checkpoints.h" #include "db.h" #include "init.h" #include "net.h" #include "txdb.h" #include "txmempool.h" #include "blockfile.h" #include <zlib.h> #include <sys/fcntl.h> using namespace std; using namespace boost; static filesystem::path BlockFilePath(unsigned int nFile) { string strBlockFn = strprintf("blocks/blk%04u.dat", nFile); return GetDataDir() / strBlockFn; } CBlockFile::CBlockFile() : mode(0) { nType = 0; nVersion = 0; state = 0; exceptmask = std::ios::badbit | std::ios::failbit; } CBlockFile::CBlockFile(const int mode, const std::string &path, int nTypeIn, int nVersionIn) : mode(mode), path(path), nType(nTypeIn), nVersion(nVersionIn) { { if (mode == APPEND) { try { file.open(path, std::ios_base::binary | std::ios_base::out | std::ios_base::app | std::ios_base::ate); } catch (std::exception &e) { error("CBlockFile::CBlockFile() : Open block file to append failed %s", path.c_str()); } } else if (mode == OPEN) { try { file.open(path, std::ios_base::binary | std::ios_base::in); } catch (std::exception &e) { error("CBlockFile::CBlockFile() : Open block file to read failed %s", path.c_str()); } } } nType = nTypeIn; nVersion = nVersionIn; state = 0; exceptmask = std::ios::badbit | std::ios::failbit; } CBlockFile::~CBlockFile() { if (file.is_open()) { if (mode == APPEND) file.flush(); file.close(); } } long CBlockFile::seek(long pos) { return file.seekp (streamsize(pos), file.beg).bad(); } long CBlockFile::skip(long count) { return file.seekp (streamsize(count), file.cur).bad(); } long CBlockFile::readbytes(void *pch, long size) { if (file.read(reinterpret_cast<char*>(pch), streamsize(size)).bad()) return 0; return size; } long CBlockFile::writebytes(const void *pch, long size) { if (file.write(reinterpret_cast<const char*>(pch), streamsize(size)).bad()) return 0; return size; } long CBlockFile::tell() { return file.tellp(); } static unsigned int nCurrentBlockFile = 1; CBlockFile *OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, int nMode) { if ((nFile < 1) || (nFile == (unsigned int) -1)) return NULL; CBlockFile *file = new CBlockFile(nMode, BlockFilePath(nFile).string().c_str()); if (nBlockPos != 0) { if (file->seek(nBlockPos) != 0 && file->mode != CBlockFile::APPEND) { delete file; return NULL; } } return file; } CBlockFile *AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; while (true) { CBlockFile* file = OpenBlockFile(nCurrentBlockFile, 0, CBlockFile::APPEND); if (!file) return NULL; // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (file->tell() < (long)(0x7F000000 - MAX_SIZE)) { nFileRet = nCurrentBlockFile; return file; } delete file; nCurrentBlockFile++; } }
040ee7739bf0453481223a8b759da2b7d53a2537
14d30579f77e2a33b8a777cb8784f36ea36ff996
/Source/loader.cpp
292e40ac5e117a02d6d7cbe2740aae5896f22c6e
[]
no_license
elenoa429/openGLNetWorkGame
b624b3a6bf90e17ff2b9f9a9a245524ada993a6e
d5656562ce74f436b4f37d62537368b021d58e8f
refs/heads/master
2021-01-13T09:27:13.720046
2017-01-30T08:50:01
2017-01-30T08:50:01
72,610,677
0
1
null
2017-01-30T08:50:02
2016-11-02T06:28:54
C++
SHIFT_JIS
C++
false
false
10,724
cpp
//============================================================================== // タイトル : ファイル読み込み用クラス // ファイル名 : loader.cpp // 作成者 : AT13B284 21 数藤凌哉 // 作成日 : 2016/05/02 //============================================================================== //============================================================================== // 更新履歴: -2016/05/02 数藤凌哉 // ・制作開始 //============================================================================== //============================================================================== // WARNING防止 //============================================================================== #define _CRT_SECURE_NO_WARNINGS //============================================================================== // インクルードファイル //============================================================================== #include "loader.h" #include <string.h> /* ===各種ローダーのインクルード=== */ #include "texLoaderBMP.h" #include "texLoaderTGA.h" #include "texLoaderJPG.h" #include "texLoaderPNG.h" #include "ModelLoaderOBJ.h" #include "materialLoaderMTL.h" //============================================================================== // 列挙型宣言 //============================================================================== //============================================================================== // マクロ定義 //============================================================================== #define EXTENSION_LEN_MAX ( 64 ) // 拡張子の最大文字数( ここまで使うかは不明 ) //============================================================================== // 構造体宣言 //============================================================================== //============================================================================== // プロトタイプ宣言 //============================================================================== //============================================================================== // グローバル宣言 //============================================================================== //============================================================================== // 静的変数 //============================================================================== //============================================================================== // 関数名 : bool TextuerLoad( char* path , CTexture** ppTexture ) // 引数 : char* path : ファイルパス( exeからの相対座標が望ましい ) // CTexture** ppTexture : テクスチャ格納先ポインタ // 戻り値 : bool型 : 処理結果 // 説明 : テクスチャ読み込み処理 //============================================================================== bool CLoader::TextuerLoad( char* path , CTexture** ppTexture ) { //-------------------------------------- // [ 拡張子の取得 ] //-------------------------------------- char pathBuff[ MAX_PATH ] = { '\0' }; // ファイルパス用バッファー char* extension = NULL; // 拡張子格納用ポインタ strcpy( pathBuff , path ); // バッファにパスを保存 strtok( pathBuff , "." ); // ファイルパスの拡張子以外の部分を排除( 厳密にはちがうが... ) extension = strtok( NULL , "." ); // 拡張子を取得 /* ===エラーチェック=== */ if( extension == NULL ) { ErrorMsg( "拡張子が見つかりません。\nファイル名 : ", path ); // エラーメッセージ表示 return false; // 拡張子が見つからないor取得失敗 } //-------------------------------------- // [ 拡張子に対応した処理の呼び出し ] //-------------------------------------- bool bResult = false; // 処理結果 if( strcmp( extension , "bmp" ) == 0 ) { CTexLoaderBMP* pTexLoaderBMP = new CTexLoaderBMP; // ローダーの生成 bResult = pTexLoaderBMP->TextuerLoadBMP( path , ppTexture ); // BMP画像読み込み delete pTexLoaderBMP; // ローダー削除 pTexLoaderBMP = NULL; // NULL埋め } else if( strcmp( extension , "tga" ) == 0 ) { CTexLoaderTGA* pTexLoaderTGA = new CTexLoaderTGA; // ローダーの生成 bResult = pTexLoaderTGA->TextuerLoadTGA( path , ppTexture ); // TGA画像読み込み delete pTexLoaderTGA; // ローダー削除 pTexLoaderTGA = NULL; // NULL埋め } else if( strcmp( extension , "png" ) == 0 ) { CTexLoaderPNG* pTexLoaderPNG = new CTexLoaderPNG; // ローダーの生成 bResult = pTexLoaderPNG->TextuerLoadPNG( path , ppTexture ); // PNG画像読み込み delete pTexLoaderPNG; // ローダー削除 pTexLoaderPNG = NULL; // NULL埋め } else if( strcmp( extension , "jpg" ) == 0 ) { CTexLoaderJPG* pTexLoaderJPG = new CTexLoaderJPG; // ローダーの生成 bResult = pTexLoaderJPG->TextuerLoadJPG( path , ppTexture ); // JPG画像読み込み delete pTexLoaderJPG; // ローダー削除 pTexLoaderJPG = NULL; // NULL埋め } else { ErrorMsg( "処理未実装の拡張子です。\nファイル名 : " , path ); // エラーメッセージ表示 } return bResult; // 処理結果の返却 } //============================================================================== // 関数名 : bool ModelLoad( char* pFileName , CMaterialBuffe** ppMaterials , DWORD* pNumMaterials , CModel** ppModelMesh ) // 引数 : char* pFileName : ファイル名 // CMaterialBuffer *ppMaterials : マテリアル用バッファーへのダブルポインタ // DWORD* pNumMaterials : マテリアル数格納先ポインタ // CModel** ppModelMesh : モデルデータへのダブルポインタ // 戻り値 : bool型 : 処理結果 // 説明 : テクスチャ読み込み処理 //============================================================================== bool CLoader::ModelLoad( char* pFileName , CMaterialBuffer** ppMaterials , DWORD* pNumMaterials , CModel** ppModelMesh ) { //-------------------------------------- // [ 拡張子の取得 ] //-------------------------------------- char pathBuff[ MAX_PATH ] = { '\0' }; // ファイルパス用バッファー char* extension = NULL; // 拡張子格納用ポインタ strcpy( pathBuff , pFileName ); // バッファにファイルネームを保存 strtok( pathBuff , "." ); // ファイルパスの拡張子以外の部分を排除( 厳密にはちがうが... ) extension = strtok( NULL , "." ); // 拡張子を取得 /* ===エラーチェック=== */ if( extension == NULL ) { ErrorMsg( "拡張子が見つかりません。\nファイル名 : ", pFileName ); return false; // 拡張子が見つからないor取得失敗 } //-------------------------------------- // [ 拡張子に対応した処理の呼び出し ] //-------------------------------------- bool bResult = false; // 処理結果 if( strcmp( extension , "obj" ) == 0 ) { CModelLoaderOBJ* pModelLoaderOBJ = new CModelLoaderOBJ; // ローダーの生成 bResult = pModelLoaderOBJ->ModelLoadOBJ( pFileName , ppMaterials , pNumMaterials , ppModelMesh ); // OBJファイルからのデータ読み込み delete pModelLoaderOBJ; // ローダー削除 pModelLoaderOBJ = NULL; // NULL埋め } else { ErrorMsg( "処理未実装の拡張子です。\nファイル名 : " , pFileName ); } return bResult; // 処理結果の返却 } //============================================================================== // 関数名 : bool MaterialLoad( char* pFileName , CMaterial** ppMaterial ) // 引数 : char* pFileName : ファイル名 // CMaterial** ppMaterial : マテリアル処理へのダブルポインタ // 戻り値 : bool型 : 処理結果 // 説明 : マテリアルデータ読み込み処理 //============================================================================== bool CLoader::MaterialLoad( char* pFileName , CMaterial** ppMaterial ) { //-------------------------------------- // [ 拡張子の取得 ] //-------------------------------------- char pathBuff[ MAX_PATH ] = { '\0' }; // ファイルパス用バッファー char* extension = NULL; // 拡張子格納用ポインタ strcpy( pathBuff , pFileName ); // バッファにファイルネームを保存 strtok( pathBuff , "." ); // ファイルパスの拡張子以外の部分を排除( 厳密にはちがうが... ) extension = strtok( NULL , "." ); // 拡張子を取得 // エラーチェック if( extension == NULL ) { ErrorMsg( "拡張子が見つかりません。\nファイル名 : " , pFileName ); return false; // 拡張子が見つからないor取得失敗 } //-------------------------------------- // [ 拡張子に対応した処理の呼び出し ] //-------------------------------------- bool bResult = false; // 処理結果 if( strcmp( extension , "mtl" ) == 0 ) { CMaterialLoaderMTL* pMaterialLoaderMTL = new CMaterialLoaderMTL; // ローダーの生成 bResult = pMaterialLoaderMTL->MaterialLoadMTL( pFileName , ppMaterial ); // MTLファイルからのデータ読み込み delete pMaterialLoaderMTL; // ローダー削除 pMaterialLoaderMTL = NULL; // NULL埋め } else { ErrorMsg( "処理未実装の拡張子です。\nファイル名 : " , pFileName ); } return bResult; // 処理結果の返却 } //============================================================================== // 関数名 : void ErrorMsg( char* errorMsg , char* path ) // 引数 : char* errorMsg : エラーメッセージ // char* path : 読み込みに失敗したファイルパス // 戻り値 : void // 説明 : 読み込み失敗時のエラー文表示用 //============================================================================== void CLoader::ErrorMsg( char* errorMsg , char* path ) { char errorMSG[ 1024 ] ={ '\0' }; // エラーメッセージ用バッファー strcpy( errorMSG , errorMsg ); // エラー文の文字列挿入 if( path != NULL ) { char pathBuff[ MAX_PATH ] ={ '\0' }; // ファイルパス用バッファー strcpy( pathBuff , path ); // バッファにパスを保存 strcat( errorMSG , pathBuff ); // ファイルパスを挿入 } MessageBox( NULL , errorMSG , "ERROR!!" , MB_ICONWARNING ); // エラーメッセージ表示 }
2bc16360047ddda0b04389ebf2ee829333d24461
f68ab61b3cd9651b61305b741c13959e8092bd1a
/PPMedia/PPMedia/mediaCore/mediaKernel/MediaAVSync/MediaSync.cpp
1d635df3010a3c07b98cb50750e360f4b0dbc47a
[]
no_license
KaiLuQiu/PPMedia
e97db5b55709545f0e289efd6fafb93083b0f044
5dcab78ed93887356ce33debc867b8050c75ee71
refs/heads/master
2022-04-11T09:04:31.219480
2020-04-05T15:16:20
2020-04-05T15:16:20
237,715,537
2
0
null
null
null
null
UTF-8
C++
false
false
2,115
cpp
// // MediaStream.cpp // PPMedia // // Created by 邱开禄 on 2020/02/09. // Copyright © 2020 邱开禄. All rights reserved. // #include "MediaSync.h" #include "MediaClock.h" NS_MEDIA_BEGIN MediaSync::MediaSync() { } MediaSync::~MediaSync() { } double MediaSync::vp_duration(Frame *vp, Frame *nextvp, MediaContext *mediaContext) { if (vp->serial == nextvp->serial) { double duration = nextvp->pts - vp->pts; if (isnan(duration) || duration <= 0 || duration > mediaContext->max_frame_duration) return vp->duration; else return duration; } else { return 0.0; } } double MediaSync::compute_target_delay(double delay, MediaContext *mediaContext) { double sync_threshold, diff = 0; // 计算video的时钟和audio时钟的差值 diff = MediaClock::get_clock(mediaContext->videoClock) - MediaClock::get_master_clock(mediaContext); /* skip or repeat frame. We take into account the delay to compute the threshold. I still don't know if it is the best guess */ sync_threshold = FFMAX(AV_SYNC_THRESHOLD_MIN, FFMIN(AV_SYNC_THRESHOLD_MAX, delay)); if (!isnan(diff) && fabs(diff) < mediaContext->max_frame_duration) { // 如果当前落后audio 则应该丢帧 if (diff <= -sync_threshold) delay = FFMAX(0, delay + diff); // 如果超前应该等待更久的时间 else if (diff >= sync_threshold && delay > AV_SYNC_FRAMEDUP_THRESHOLD) delay = delay + diff; else if (diff >= sync_threshold) delay = 2 * delay; } printf("avsync: video refresh thread delay=%0.3f A-V=%f\n", delay, -diff); return delay; } void MediaSync::update_video_clock(double pts, int serial, MediaContext *mediaContext) { MediaClock::set_clock(mediaContext->videoClock, pts, serial); } int MediaSync::get_master_sync_type(MediaContext *mediaContext) { // 目前默认采用视频sync音频 return SYNC_AUDIO_CLOCK; } NS_MEDIA_END
03842b4a5036baa7ed1d6ca020f901895daa28e1
e3ceca6a34bf3426b90b3952782d4fd94c54d08a
/c問題/c_ID.cpp
f4c922020d6ee556b9d655a439f763e8b29d6bc3
[]
no_license
THEosusi/atcoder
ede5bffb44d59e266c6c4763a64cddeed8d8101f
0e9a17a82562e469198a6cc81922db5ac13efa6d
refs/heads/master
2023-06-21T06:45:28.128553
2021-07-27T09:02:55
2021-07-27T09:02:55
336,729,745
0
0
null
null
null
null
UTF-8
C++
false
false
887
cpp
#include <bits/stdc++.h> using namespace std; int main() { int N,M; cin>>N>>M; vector<tuple<int,int,int>>vec; vector<string>vec1(M,""); for(int i=0;i<M;i++){ int a,b; cin>>a>>b; vec.push_back(make_tuple(a,b,i)); } sort(vec.begin(),vec.end()); int count=1; int AAA=0; for(int i=0;i<M;i++){ if(AAA !=get <0>(vec.at(i))){ count=1; AAA=get<0>(vec.at(i)); } string a=""; string b=""; string c=""; a +=to_string(get<0>(vec.at(i))); b +=to_string(count); for(int i=0;i<6-a.size();i++){ c+='0'; } c+=a; for(int i=0;i<6-b.size();i++){ c+='0'; } c+=b; count++; vec1.at(get<2>(vec.at(i))) +=c; } for(int i=0;i<M;i++){ cout<<vec1.at(i)<<endl; } }
63c71bc07d75979366de841b0a96043fbac62b76
03157dce660790a94361701ea53436d54b02db55
/proyecto f1 y f2/build-Transact_OLC1-Desktop-Debug/ui_mainwindow.h
123f5a666b83c3238bd4033b1c6540c6514450fa
[]
no_license
PascualDomingo/organizacion-de-lenguajes-y-compiladores-1
4c445271c1d1bd85f02cb597c3d83bf3cd8b3749
07b4c5a0d5685b598ca570cd542b18aea3d982f8
refs/heads/main
2023-03-03T15:46:07.554429
2021-02-17T04:27:45
2021-02-17T04:27:45
339,608,819
0
0
null
null
null
null
UTF-8
C++
false
false
9,381
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.9.5 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenu> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPlainTextEdit> #include <QtWidgets/QStatusBar> #include <QtWidgets/QTabWidget> #include <QtWidgets/QTableWidget> #include <QtWidgets/QToolBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QAction *actioncrear; QAction *actionabrir; QAction *actionguardar; QAction *actionguardar_como; QAction *actioncrear_pesta_a; QAction *actioneliminar_pesta_a; QAction *actionerror_lexico; QAction *actionerror_sintactico; QAction *actionerror_semantico; QAction *actionAST; QAction *actionejecutar; QWidget *centralWidget; QTabWidget *tabla_simbolo; QWidget *tab; QPlainTextEdit *txtConsola; QWidget *tab_2; QTableWidget *tblVariables; QTabWidget *tabWidget_2; QWidget *tab_3; QPlainTextEdit *txtEditor; QWidget *tab_4; QToolBar *mainToolBar; QStatusBar *statusBar; QMenuBar *menuBar; QMenu *menuarchivo; QMenu *menureportes; QMenu *menucompilar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(1157, 836); actioncrear = new QAction(MainWindow); actioncrear->setObjectName(QStringLiteral("actioncrear")); actionabrir = new QAction(MainWindow); actionabrir->setObjectName(QStringLiteral("actionabrir")); actionguardar = new QAction(MainWindow); actionguardar->setObjectName(QStringLiteral("actionguardar")); actionguardar_como = new QAction(MainWindow); actionguardar_como->setObjectName(QStringLiteral("actionguardar_como")); actioncrear_pesta_a = new QAction(MainWindow); actioncrear_pesta_a->setObjectName(QStringLiteral("actioncrear_pesta_a")); actioneliminar_pesta_a = new QAction(MainWindow); actioneliminar_pesta_a->setObjectName(QStringLiteral("actioneliminar_pesta_a")); actionerror_lexico = new QAction(MainWindow); actionerror_lexico->setObjectName(QStringLiteral("actionerror_lexico")); actionerror_sintactico = new QAction(MainWindow); actionerror_sintactico->setObjectName(QStringLiteral("actionerror_sintactico")); actionerror_semantico = new QAction(MainWindow); actionerror_semantico->setObjectName(QStringLiteral("actionerror_semantico")); actionAST = new QAction(MainWindow); actionAST->setObjectName(QStringLiteral("actionAST")); actionejecutar = new QAction(MainWindow); actionejecutar->setObjectName(QStringLiteral("actionejecutar")); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); tabla_simbolo = new QTabWidget(centralWidget); tabla_simbolo->setObjectName(QStringLiteral("tabla_simbolo")); tabla_simbolo->setGeometry(QRect(0, 560, 1161, 211)); tab = new QWidget(); tab->setObjectName(QStringLiteral("tab")); txtConsola = new QPlainTextEdit(tab); txtConsola->setObjectName(QStringLiteral("txtConsola")); txtConsola->setGeometry(QRect(0, 0, 1151, 181)); QFont font; font.setFamily(QStringLiteral("aakar")); font.setPointSize(11); font.setBold(true); font.setItalic(false); font.setWeight(75); txtConsola->setFont(font); tabla_simbolo->addTab(tab, QString()); tab_2 = new QWidget(); tab_2->setObjectName(QStringLiteral("tab_2")); tblVariables = new QTableWidget(tab_2); tblVariables->setObjectName(QStringLiteral("tblVariables")); tblVariables->setGeometry(QRect(0, 0, 1151, 181)); tabla_simbolo->addTab(tab_2, QString()); tabWidget_2 = new QTabWidget(centralWidget); tabWidget_2->setObjectName(QStringLiteral("tabWidget_2")); tabWidget_2->setGeometry(QRect(0, 0, 1161, 561)); tab_3 = new QWidget(); tab_3->setObjectName(QStringLiteral("tab_3")); txtEditor = new QPlainTextEdit(tab_3); txtEditor->setObjectName(QStringLiteral("txtEditor")); txtEditor->setGeometry(QRect(0, 0, 1151, 531)); QFont font1; font1.setFamily(QStringLiteral("aakar")); font1.setPointSize(13); font1.setBold(true); font1.setItalic(false); font1.setWeight(75); txtEditor->setFont(font1); tabWidget_2->addTab(tab_3, QString()); tab_4 = new QWidget(); tab_4->setObjectName(QStringLiteral("tab_4")); tabWidget_2->addTab(tab_4, QString()); MainWindow->setCentralWidget(centralWidget); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QStringLiteral("statusBar")); MainWindow->setStatusBar(statusBar); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 1157, 22)); menuarchivo = new QMenu(menuBar); menuarchivo->setObjectName(QStringLiteral("menuarchivo")); menureportes = new QMenu(menuBar); menureportes->setObjectName(QStringLiteral("menureportes")); menucompilar = new QMenu(menuBar); menucompilar->setObjectName(QStringLiteral("menucompilar")); MainWindow->setMenuBar(menuBar); mainToolBar->addSeparator(); menuBar->addAction(menuarchivo->menuAction()); menuBar->addAction(menureportes->menuAction()); menuBar->addAction(menucompilar->menuAction()); menuarchivo->addAction(actioncrear); menuarchivo->addAction(actionabrir); menuarchivo->addAction(actionguardar); menuarchivo->addAction(actionguardar_como); menuarchivo->addAction(actioncrear_pesta_a); menuarchivo->addAction(actioneliminar_pesta_a); menureportes->addAction(actionerror_lexico); menureportes->addAction(actionerror_sintactico); menureportes->addAction(actionerror_semantico); menureportes->addAction(actionAST); menucompilar->addAction(actionejecutar); retranslateUi(MainWindow); tabla_simbolo->setCurrentIndex(1); tabWidget_2->setCurrentIndex(0); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "Organizacion de Lenguajes y compiladores 1", Q_NULLPTR)); actioncrear->setText(QApplication::translate("MainWindow", "crear", Q_NULLPTR)); actionabrir->setText(QApplication::translate("MainWindow", "abrir", Q_NULLPTR)); actionguardar->setText(QApplication::translate("MainWindow", "guardar", Q_NULLPTR)); actionguardar_como->setText(QApplication::translate("MainWindow", "guardar como", Q_NULLPTR)); actioncrear_pesta_a->setText(QApplication::translate("MainWindow", "crear pesta\303\261a", Q_NULLPTR)); actioneliminar_pesta_a->setText(QApplication::translate("MainWindow", "eliminar pesta\303\261a", Q_NULLPTR)); actionerror_lexico->setText(QApplication::translate("MainWindow", "error lexico", Q_NULLPTR)); actionerror_sintactico->setText(QApplication::translate("MainWindow", "error sintactico", Q_NULLPTR)); actionerror_semantico->setText(QApplication::translate("MainWindow", "error semantico", Q_NULLPTR)); actionAST->setText(QApplication::translate("MainWindow", "AST", Q_NULLPTR)); actionejecutar->setText(QApplication::translate("MainWindow", "ejecutar", Q_NULLPTR)); tabla_simbolo->setTabText(tabla_simbolo->indexOf(tab), QApplication::translate("MainWindow", "consola", Q_NULLPTR)); tabla_simbolo->setTabText(tabla_simbolo->indexOf(tab_2), QApplication::translate("MainWindow", "tabla simbolo", Q_NULLPTR)); tabWidget_2->setTabText(tabWidget_2->indexOf(tab_3), QApplication::translate("MainWindow", "pesta\303\261a", Q_NULLPTR)); tabWidget_2->setTabText(tabWidget_2->indexOf(tab_4), QApplication::translate("MainWindow", "pesta\303\261a", Q_NULLPTR)); menuarchivo->setTitle(QApplication::translate("MainWindow", "archivo", Q_NULLPTR)); menureportes->setTitle(QApplication::translate("MainWindow", "reportes", Q_NULLPTR)); menucompilar->setTitle(QApplication::translate("MainWindow", "compilar", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
1bc9371ccd554f0b65a9ea58dcd1583bbf7bb67e
c26fbdd9eb8097095796eb88d4ffbb7998ad8973
/capi/src/implementation/visibility_graphs/code/visgraph/visgraph_generator.cpp
95cbbee76411c5500d95e0dee447fef70189b323
[ "MIT" ]
permissive
vatula/capi
2782f383dab0d206622ceb551f9078ac51dce672
ee2f4c01bd4458d71893b850aa95051cd8ebda90
refs/heads/main
2023-06-04T18:56:28.055772
2021-06-22T04:25:43
2021-06-22T04:25:43
359,784,335
0
0
MIT
2021-04-20T11:04:11
2021-04-20T11:04:10
null
UTF-8
C++
false
false
2,635
cpp
// // Created by James.Balajan on 31/03/2021. // #include <algorithm> #include <random> #include <stdexcept> #include "coordinate_periodicity/coordinate_periodicity.hpp" #include "visgraph_generator.hpp" #include "vistree_generator.hpp" VisgraphGenerator::VisgraphGenerator() = default; Graph VisgraphGenerator::generate(const std::vector<Polygon> &polygons) { auto polygon_vertices = VisgraphGenerator::polygon_vertices(polygons); auto visgraph = Graph(polygons); auto vistree_gen = VistreeGenerator(make_polygons_periodic(polygons)); #pragma omp parallel for shared(visgraph, polygon_vertices, vistree_gen) default(none) for (size_t i = 0; i < polygon_vertices.size(); ++i) { // NOLINT const auto visible_vertices = vistree_gen.get_visible_vertices(polygon_vertices[i], true); for (const auto &visible_vertex : visible_vertices) { visgraph.add_edge(polygon_vertices[i], visible_vertex.coord, visible_vertex.is_visible_across_meridian); } } return visgraph; } Graph VisgraphGenerator::generate_with_shuffled_range(const std::vector<Polygon> &polygons, size_t range_start, size_t range_end, unsigned int seed) { auto polygon_vertices = VisgraphGenerator::polygon_vertices(polygons); auto visgraph = Graph(polygons); if (polygons.empty()) { return visgraph; } if (range_start < 0 || range_end > polygon_vertices.size() || range_start > range_end) { throw std::runtime_error("Improper range for visgraph generation"); } auto vistree_gen = VistreeGenerator(make_polygons_periodic(polygons)); std::mt19937 gen(seed); std::shuffle(polygon_vertices.begin(), polygon_vertices.end(), gen); #pragma omp parallel for shared(visgraph, vistree_gen, polygon_vertices, range_start, range_end) default(none) for (size_t i = range_start; i < range_end; ++i) { // NOLINT const auto visible_vertices = vistree_gen.get_visible_vertices(polygon_vertices[i], true); for (const auto &visible_vertex : visible_vertices) { visgraph.add_edge(polygon_vertices[i], visible_vertex.coord, visible_vertex.is_visible_across_meridian); } } return visgraph; } std::vector<Coordinate> VisgraphGenerator::polygon_vertices(const std::vector<Polygon> &polygons) { auto vertices = std::vector<Coordinate>(); for (const auto &polygon : polygons) { vertices.reserve(polygon.get_vertices().size()); vertices.insert(vertices.end(), polygon.get_vertices().begin(), polygon.get_vertices().end()); } return vertices; }
a559e5a6e5db834dbc936e6a666fae6c14d7aa06
712b22a50c3c9432d748837cc9926aa152c6c569
/Qt-project/cfgdatastruct.h
a0eec90ec7ac8038a39f8aa587a917dff4af296c
[]
no_license
owenlyn0123/MyGitTest
5c38beadf469101053aeeb6bb20f3319aad665c2
25cb9656dc99431a72c494d239c6af5548d7f34d
refs/heads/master
2020-08-11T13:43:49.699833
2020-05-11T05:11:45
2020-05-11T05:11:45
214,574,281
0
0
null
null
null
null
UTF-8
C++
false
false
12,944
h
#ifndef CFG_DATA_STRUCT_H #define CFG_DATA_STRUCT_H #include "datatype.h" #include "syslog.h" typedef enum { PID_Unknown, PID_Android_V2, // ºËÐÄ°å+°²×¿ÃÅ¿Ú»ú PID_8130_Outdoor,// ºËÐÄ°å+XTM8130ÃÅ¿Ú»ú PID_8130_Indoor, // ºËÐÄ°å+XTM8130ÊÒÄÚ»ú PID_Analog_Louyu,// ºËÐÄ°å+Ä£ÄâÃÅ¿Ú»ú PID_Analog_Villa,// ºËÐÄ°å+Ä£Äâ±ðÊû»ú PID_Phone, // ºËÐÄ°å+µç»°ÃÅ¿Ú»ú PID_Phone_SDK, // ºËÐÄ°å+µç»°ÃÅ¿Ú»ú + µÚÈý·½¼¯³É£¨ÉîÛÚÎ÷ÎÖ£© }ProductType_e; typedef struct { DWORD dwRoomID; DWORD dwCardCrc; BYTE cHasGet; // ÊÇ·ñÒѾ­´ÓGetRoomCardCrcº¯Êý±»È¡×ß¹ý,0±íʾûÓÐÈ¡×ߣ¬1±íʾÒѾ­È¡×ß }RoomCardCrc_t;//CardCheck£¬¼ì²é¿¨ºÅ typedef std::list<RoomCardCrc_t> ListRoomCardCrc; const DWORD COUNT_ROOMID_CARDINDEX = 150; typedef enum { RR_Unknown, RR_Unlock_Mob = 1, // APP¿ªÃÅ RR_Unlock_Card, // Ë¢¿¨¿ªÃÅ RR_Unlock_Wifi, // Wifi¿ªÃÅ RR_Unlock_TmpPwd, // ÁÙʱÃÜÂ뿪ÃÅ RR_Unlock_Pwd = 5, // ס»§ÃÜÂ뿪ÃÅ RR_Unlock_CloudCard, // ²éѯÔÆƽ̨¿¨ºÅ¿ªÃÅ RR_Unlock_Bluetooth, // À¶ÑÀ¿ªÃÅ RR_Unlock_Indoor, // ÊÒÄÚ»ú¿ªÃÅ RR_Unlock_Phone = 10,// µç»°¿ªÃÅ RR_CallTimeout = 21, // Ôƺô½Ð³¬Ê± RR_CloudAnswer, // App½ÓÌý RR_PhoneAnswer, // µç»°½ÓÌý }RecReason_e; typedef enum { UFT_JPG = 1, UFT_MP4 = 11, UFT_AVI = 12 }UploadFileType_e; typedef struct { DWORD dwTime; int nReserveID; // ÓÃÓÚÔ¤¶¨Í¼Æ¬µÄÔ¤¶¨ºÅ¼Ç¼ char cTTL; // ³¬Ê±ÐÄÌø¼Ç¼ DWORD dwRoomID; RecReason_e eReason; UploadFileType_e eType; CSTRING strLocalFile; DWORD dwFileSize; // µ¥Î»£º×Ö½Ú }RecTask_t; //ÈÎÎñ¼Ç¼ typedef std::list<RecTask_t> List_RecTask; typedef struct { DWORD dwTime; DWORD dwDeviceID; DWORD dwStoreID; CSTRING strToken; }UploadToken_t; typedef struct { DWORD dwDeviceID; DWORD dwRoomID; DWORD dwSize; DWORD dwStoreID; UploadFileType_e eType; RecReason_e eReason; DWORD dwTime; }UploadResult_t; typedef struct { CSTRING strUsername; // Ö÷ÕʺŠCSTRING strPassword; // Ö÷ÕʺÅÃÜÂë(des+base64) CSTRING strAppid; // Ó¦ÓÃid }UcpaasInfo_t; // ÔÆ֮ѶÐÅÏ¢ typedef struct { CSTRING strUserID; CSTRING strAccountSID; CSTRING strAuthToken; CSTRING strAppKey; CSTRING strVendorDisplayNumber;//À´µçÏÔʾºÅÂë }YuntxInfo_t; //ÈÝÁªÔÆͨѶ typedef enum { CA_VATTRTYPE_BRIGHTNESS = 0x00000001, CA_VATTRTYPE_CONTRAST = 0x00000002, CA_VATTRTYPE_HUE = 0x00000004, CA_VATTRTYPE_SATURATION = 0x00000008, CA_VATTRTYPE_SHARPNESS = 0x00000010, CA_VATTRTYPE_MIRROR = 0x00000020, CA_VATTRTYPE_REVERSE = 0x00000040, CA_VATTRTYPE_FLICKER = 0x00000080, CA_VATTRTYPE_TARGETY = 0x00000100, }VideoAttrMode_e; //ÊÓƵ²ÎÊýÀàÐÍ typedef enum { CA_VATTRINDEX_BRIGHTNESS = 0, // ͼÏñÁÁ¶È CA_VATTRINDEX_CONTRAST = 1, // ͼÏñ¶Ô±È¶È CA_VATTRINDEX_HUE = 2, // ͼÏñÉ«¶È CA_VATTRINDEX_SATURATION = 3, // ͼÏñ±¥ºÍ¶È CA_VATTRINDEX_SHARPNESS = 4, // ͼÏñÈñÀû¶È CA_VATTRINDEX_MIRROR = 5, // ×óÓÒ¾µÏñ CA_VATTRINDEX_REVERSE = 6, // ÉÏÏ·­×ª CA_VATTRINDEX_FLICKER = 7, // ÉÁ˸ƵÂÊ CA_VATTRINDEX_TARGETY = 8, // ¾µÍ·ÁÁ¶È }VideoAttrIndex_e; //ÊÓƵ²ÎÊýË÷Òý typedef struct { BYTE cIspInit; BYTE cBrightness; //ÁÁ¶È BYTE cContrast; //¶Ô±È¶È BYTE cHue; //É«¶È BYTE cSaturation; //±¥ºÍ¶È BYTE cSharpness; //ÈñÀû¶È BYTE cMirror; //×óÓÒ¾µÏñ BYTE cReverse; //ÉÏÏ·­×ª BYTE cFlicker; //0: 60Hz; 1: 50Hz BYTE cTargetY; //ÉãÏñÍ·ÁÁ¶È targetY [0~255 def:85] }VideoAttr_t; //ÊÓƵ²ÎÊýÊýÖµ const DWORD CA_VATTRTYPE_COUNTVERSION0 = 9; const DWORD CA_VIDEOATTRTYPE_VALUEMIN = 0; // ÊôÐÔ×îСֵ const DWORD CA_VIDEOATTRTYPE_VALUEMAX = 100; // ÊôÐÔ×î´óÖµ typedef enum { CA_REGISTERTYPE_NONE = 0x0000, // ÉãÏñ»ú²»Ïò×¢²á·þÎñÆ÷×¢²á CA_REGISTERTYPE_SCANAC = 0x0001, // ÉãÏñ»úÏò¾ÖÓòÍøÖÐËÑË÷µ½µÄ // ±¨¾¯ÖÐÐÄ×¢²á(ĬÈÏÖµ) CA_REGISTERTYPE_DIRECTAC = 0x0002, // ÉãÏñ»úÏòÓû§É趨µÄ // ±¨¾¯ÖÐÐÄ×¢²á CA_REGISTERTYPE_PLATFORM = 0x0003, // ÉãÏñ»úÏòƽ̨ע²á }RegSvrType_e; //×¢²á·þÎñÆ÷ÀàÐÍ typedef struct { RegSvrType_e eType; DWORD dwSvr1IP; WORD wSvr1Port; WORD wSvr2Port; CSTRING strSvr1Dns; }RegisterInfo_t; typedef struct { CSTRING strDevName; CSTRING strDevPwd; CSTRING strSerialNo; CSTRING strVer; DWORD dwDeviceID; DWORD dwVendorID; short sZone; // ʱÇø£¬GM+8±íʾΪ8*60=480 ÒÔ·ÖÖÓΪµ¥Î»¼Ç¼ int nNet2DialSec; // ÍøÂçºô½Ðת²¦´òµç»°µÄʱ¼ä¼ä¸ô£¨µ¥Î»£ºÃ룩 RegisterInfo_t tRegInfo; BYTE cWorkMode; }SystemInfo_t; //ϵͳÐÅÏ¢ typedef enum { VMT_UNKNOWN, VMT_MOB = 0x01, //ÊÖ»ú¶ËÊÓƵ VMT_PC = 0x02, //pc¶ËÊÓƵ VMT_REC = 0x04 //¼Ïñ }VideoModeType_e; //ÊÓƵÀàÐÍ typedef enum { WLM_UNKNOWN, WLM_SOFTAP, WLM_STATION }WlMode_e; //ÎÞÏßģʽ typedef enum { WLS_UNKNOWN, WLS_WPA, WLS_WEP, WLS_NONE, // δ¼ÓÃÜ, WLS_TOTAL }WLSecurity_e; //ÎÞÏß¼ÓÃÜÀàÐÍ typedef enum { AM_UNKNOWN, AM_DHCP, //×Ô¶¯·ÖÅäIP AM_STATIC //¹Ì¶¨IP }AddrMode_e; //IPµØÖ·ÀàÐÍ typedef enum { NM_UNKNOWN, NM_WIRE, //ÓÐÏß NM_WIFI //ÎÞÏß }NetMode_e; //ÍøÂçÀàÐÍ const DWORD LEN_MAC = 17; typedef struct { NetMode_e eNetMode; //ÍøÂçÀàÐÍ WORD wAppPort; //¶Ë¿ÚºÅ BYTE szMac[LEN_MAC+1]; //ÎïÀíµØÖ· }NetCommon_t; //ÍøÂçÊôÐÔ typedef struct { AddrMode_e eAddrMode; //µØÖ·ÀàÐÍ DWORD dwIP; //IP DWORD dwMask; //ÑÚÂë DWORD dwGateway; //Íø¹Ø }AddrParam_t; //IPµØÖ·²ÎÊý typedef struct { AddrMode_e eDnsMode; DWORD dwDns1; DWORD dwDns2; }DnsParam_t; //ÓòÃû½âÎö²ÎÊý typedef struct { WlMode_e eWLMode; }WLCommon_t; typedef struct { CSTRING strSSID; WLSecurity_e eSecurity; }SoftApParam_t; typedef struct { int nCurrent; CSTRING strPwd; SoftApParam_t tApInfo; }PeerApInfo_t; typedef std::map<CSTRING/*strAddr*/, PeerApInfo_t> MAP_PEERAP; typedef struct { WLCommon_t tWlCom; SoftApParam_t tSAP; MAP_PEERAP mapPeerAP; }WlParam_t; typedef struct { NetCommon_t tNetCom; AddrParam_t tAddr; DnsParam_t tDns; WlParam_t tWireless; }NetworkInfoV2_t; typedef struct { DWORD dwRecMode; DWORD dwPcMode; DWORD dwMobMode; VideoAttr_t tParam; DWORD dwPhotoMode;// bit0:ºô½Ðʧ°Ü(³¬Ê±,δ½ÓÌý) bit1:App½ÓÌýbit2:µç»°½ÓÌýbit3:APP¿ªËøbit4:µç»°¿ªËøbit5:Ë¢¿¨¿ªËøbit6:ÃÜÂ뿪Ëø }VideoInfo_t; typedef struct { BYTE cCapVolume; BYTE cPlayVolume; }AudioInfo_t; typedef struct { CSTRING strName; BYTE cDefVal; //0: À­µÍ; 1: À­¸ß BYTE cMode; //Bit0: DO1; Bit1: DO2 }DiParam_t; typedef struct { CSTRING strName; BYTE cDefVal; //0: À­µÍ; 1: À­¸ß DWORD dwInterval; //ms }DoParam_t; typedef struct { BYTE cBtnMode; // bit0=1 ±íʾ°´¼ü´¥·¢do1£»bit1=1 ±íʾ°´¼ü´¥·¢do2£»bit2=1 ±íʾ°´¼ü´¥·¢Æ½Ì¨±¨¾¯ BYTE cAlarmST; // 1=³··À£»2=²¼·À DiParam_t tDi[3]; DoParam_t tDo[2]; BYTE cVideoLed; // ²¹¹âµÆ¹¦ÄÜ 1:´ò¿ª 0:¹Ø±Õ; BYTE cWav_btn; // °´¼üÁåÉù²¥·ÅÑ­»·´ÎÊý £¨0¡¢1¡¢3¡¢5¡¢8¡¢10£©; BYTE cWav_come; // À´ÈËÌáʾÁåÉù²¥·ÅÑ­»·´ÎÊý£¨0¡¢1¡¢3¡¢5¡¢8¡¢10£©; BYTE cBtnled_work; // °´¼üָʾµÆ¹¤×÷״̬; BYTE cBtnled_abnormal;// °´¼üָʾµÆÒ쳣״̬; BYTE cBtnled_calling; // °´¼üָʾµÆºô½ÐµÈ´ý״̬; BYTE cBtnled_process; // °´¼üָʾµÆºô½Ð´¦Àí״̬; }DioInfo_t; typedef struct { CSTRING strNum; // ·¿ºÅ ListCString listPhone; ListCString listCard; }Uart_RoomInfo_t; #define DEF_BTN_E_TAG "E-BTN"//"Emergency" #define DEF_BTN_C_TAG "C-BTN"//"Consult" #define ALL_ROOM_NUM "ffffffff" typedef enum { // É豸Ö÷ÀàÐÍ CA_DEVICETYPE_MAIN_GM8126 = 0, // GM8126ƽ̨É豸 CA_DEVICETYPE_MAIN_AK3918 = 1, // AK3918ƽ̨É豸 CA_DEVICETYPE_MAIN_GM8136 = 2, // GM8136ƽ̨É豸 CA_DEVICETYPE_MAIN_ANDROID = 3, // °²×¿Æ½Ì¨É豸 // É豸×ÓÀàÐÍ CA_DEVICETYPE_SUB_ALARM = 0, // ±¨¾¯É豸 CA_DEVICETYPE_SUB_LINK = 1, // ±¨¾¯Áª¶¯É豸 CA_DEVICETYPE_SUB_IPC = 2, // Ïû·ÑÀàÒƶ¯ÉãÏñ»ú CA_DEVICETYPE_SUB_OUTDOOR = 3, // Â¥ÓîÃÅ¿Ú»ú CA_DEVICETYPE_SUB_INDOOR = 4, // Â¥ÓîÊÒÄÚ»ú }DeviceType_e; typedef struct { DWORD dwID; DWORD dwNetID; DWORD dwIP; CSTRING strPos; }DSvrInfo_t; typedef std::list<DSvrInfo_t> LIST_DSVR; ////////////////////////////////////////////////////////////////////////// typedef struct { DWORD dwUsrID; DWORD dwVID; DWORD dwLangID; // Lang: 0:China 1=Taiwei 2=English CSTRING strContact; CSTRING strDevAlias; // É豸±ðÃû }UserInfo_t; typedef std::list<UserInfo_t> LIST_USER; typedef struct { DWORD dwUsrID; DWORD dwVID; DWORD dwLangID; // Lang: 0:China 1=Taiwei 2=English DWORD dwPushType; // 1-Ô­ÉúIOS; 2-°Ù¶ÈAndroid ;3-¸öÍÆIOS;4-¸öÍÆAndroid;5-°Ù¶ÈIOS;6-¼«¹âIOS;7-¼«¹âAndroid;8-СÃ×Android;9-»ªÎªAndroid;10-÷È×åAndroid;11-ÊÒÄÚ»ú CSTRING strToken; }PushInfo_t; typedef std::list<PushInfo_t> LIST_PUSH; typedef struct { PushInfo_t tPushInfo; CSTRING strDevAlias; }PushInfoEx_t; typedef std::list<PushInfoEx_t> LIST_PUSH_EX; typedef struct { CSTRING strNum; // ¿¨ºÅ BYTE cType; // ¿¨ÀàÐÍ£¬µ±Ç°Î´¶¨Òå DWORD dwDeadline;//¿¨ºÅ½ØÖ¹ÈÕÆÚ }CardInfo_t; typedef std::list<CardInfo_t> LIST_CARD; //·¿ºÅÊôÐÔÒªÏÞÖƵŦÄÜ typedef enum { RA_CardUnlock = 8,//Ë¢¿¨¿ªËø RA_AppUnlock = 9,//App¿ªËø RA_PhoneUnlock = 10,//µç»°¿ªËø }RoomAttr_e; typedef struct { DWORD dwUserID; DWORD dwIndoorID; BYTE cStatus;//ÊÒÄÚ»úÔÚÏß״̬ } IndoorInfo_t; typedef std::list<IndoorInfo_t> LIST_INDOOR; typedef std::map<DWORD, BYTE> MAP_DEVICE_STATUS;//É豸IDºÍÉ豸״̬ typedef struct { CSTRING strNum; // ·¿ºÅ CSTRING strPwd; // ¿ªÃÅÃÜÂë DWORD dwRoomAttr;//·¿¼äÊôÐÔ DWORD dwUserIndex; // Óû§ÅäÖÃË÷Òý DWORD dwPushIndex; // ÍÆËÍÅäÖÃË÷Òý DWORD dwCardIndex; // ¿¨ºÅÅäÖÃË÷Òý DWORD dwIndoorIndex;// ÊÒÄÚ»úÅäÖÃË÷Òý LIST_USER listUser; //Óû§Áбí LIST_PUSH listPush; //ÍÆËÍÁбí LIST_CARD listCard; //¿¨ºÅÁбí LIST_INDOOR listIndoor; //ÊÒÄÚ»úÁбí }RoomInfo_t; //·¿¼äÐÅÏ¢ typedef std::map<DWORD, RoomInfo_t> MAP_ROOM;//RoomID ¶ÔÓ¦µÄ·¿¼äÕªÒªÐÅÏ¢ typedef struct { DWORD dwRoomID; //·¿ºÅID CSTRING strNum; //·¿ºÅ CSTRING strPwd; //¿ªÃÅÃÜÂë DWORD dwRoomAttr; //·¿¼äÊôÐÔ£¬ÔÝÓÃÓÚ¿ØÖÆ·¿¼ä¿ªÃÅȨÏÞ }RoomNodeInfo_t; //·¿¼ä½ÚµãÐÅÏ¢ typedef std::list<RoomNodeInfo_t> LIST_ROOM_NODE; ////////////////////////////////////////////////////////////////////////// typedef struct { DWORD dwPushIndex; LIST_PUSH_EX listPushEx; }RoomPushEx_t; #endif
98aaa9cfb014500e3afb18064a28a86c204f002e
019119e06e765466fb496f03692858d9cdf6ab4f
/_oe-sdk-20071004091648/usr/local/arm/oe/arm-linux/include/mozilla-minimo/necko/nsIEncodedChannel.h
bffc7795fa71ea392fba8847a51f31f6ecd50e73
[]
no_license
josuehenrique/iliad-hacking
44b2a5cda34511f8976fc4a4c2740edb5afa5312
49cfd0a8f989491a6cc33cf64e8542f695d2e280
refs/heads/master
2020-04-06T06:40:50.174479
2009-08-23T16:56:01
2009-08-23T16:56:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,045
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /data/workareas/matthijs/svn/openembedded/build/tmp/work/minimo-0.0cvs20051025-r9/mozilla/netwerk/base/public/nsIEncodedChannel.idl */ #ifndef __gen_nsIEncodedChannel_h__ #define __gen_nsIEncodedChannel_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIUTF8StringEnumerator; /* forward declaration */ /* starting interface: nsIEncodedChannel */ #define NS_IENCODEDCHANNEL_IID_STR "30d7ec3a-f376-4652-9276-3092ec57abb6" #define NS_IENCODEDCHANNEL_IID \ {0x30d7ec3a, 0xf376, 0x4652, \ { 0x92, 0x76, 0x30, 0x92, 0xec, 0x57, 0xab, 0xb6 }} /** * A channel interface which allows special handling of encoded content */ class NS_NO_VTABLE nsIEncodedChannel : public nsISupports { public: NS_DEFINE_STATIC_IID_ACCESSOR(NS_IENCODEDCHANNEL_IID) /** * This attribute holds the MIME types corresponding to the content * encodings on the channel. The enumerator returns nsISupportsCString * objects. The first one corresponds to the outermost encoding on the * channel and then we work our way inward. "identity" is skipped and not * represented on the list. Unknown encodings make the enumeration stop. * If you want the actual Content-Encoding value, use * getResponseHeader("Content-Encoding"). * * When there is no Content-Encoding header, this property is null. * * Modifying the Content-Encoding header on the channel will cause * this enumerator to have undefined behavior. Don't do it. * * Also note that contentEncodings only exist during or after OnStartRequest. * Calling contentEncodings before OnStartRequest is an error. */ /* readonly attribute nsIUTF8StringEnumerator contentEncodings; */ NS_IMETHOD GetContentEncodings(nsIUTF8StringEnumerator * *aContentEncodings) = 0; /** * This attribute controls whether or not content conversion should be * done per the Content-Encoding response header. applyConversion can only * be set before or during OnStartRequest. Calling this during * OnDataAvailable is an error. * * TRUE by default. */ /* attribute boolean applyConversion; */ NS_IMETHOD GetApplyConversion(PRBool *aApplyConversion) = 0; NS_IMETHOD SetApplyConversion(PRBool aApplyConversion) = 0; }; /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIENCODEDCHANNEL \ NS_IMETHOD GetContentEncodings(nsIUTF8StringEnumerator * *aContentEncodings); \ NS_IMETHOD GetApplyConversion(PRBool *aApplyConversion); \ NS_IMETHOD SetApplyConversion(PRBool aApplyConversion); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIENCODEDCHANNEL(_to) \ NS_IMETHOD GetContentEncodings(nsIUTF8StringEnumerator * *aContentEncodings) { return _to GetContentEncodings(aContentEncodings); } \ NS_IMETHOD GetApplyConversion(PRBool *aApplyConversion) { return _to GetApplyConversion(aApplyConversion); } \ NS_IMETHOD SetApplyConversion(PRBool aApplyConversion) { return _to SetApplyConversion(aApplyConversion); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIENCODEDCHANNEL(_to) \ NS_IMETHOD GetContentEncodings(nsIUTF8StringEnumerator * *aContentEncodings) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetContentEncodings(aContentEncodings); } \ NS_IMETHOD GetApplyConversion(PRBool *aApplyConversion) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetApplyConversion(aApplyConversion); } \ NS_IMETHOD SetApplyConversion(PRBool aApplyConversion) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetApplyConversion(aApplyConversion); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsEncodedChannel : public nsIEncodedChannel { public: NS_DECL_ISUPPORTS NS_DECL_NSIENCODEDCHANNEL nsEncodedChannel(); private: ~nsEncodedChannel(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsEncodedChannel, nsIEncodedChannel) nsEncodedChannel::nsEncodedChannel() { /* member initializers and constructor code */ } nsEncodedChannel::~nsEncodedChannel() { /* destructor code */ } /* readonly attribute nsIUTF8StringEnumerator contentEncodings; */ NS_IMETHODIMP nsEncodedChannel::GetContentEncodings(nsIUTF8StringEnumerator * *aContentEncodings) { return NS_ERROR_NOT_IMPLEMENTED; } /* attribute boolean applyConversion; */ NS_IMETHODIMP nsEncodedChannel::GetApplyConversion(PRBool *aApplyConversion) { return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsEncodedChannel::SetApplyConversion(PRBool aApplyConversion) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIEncodedChannel_h__ */
cb38d232f43440294131501a61bdb66df71e46ec
1bb398a6e5ba6fafd82490c07cba503b894d7a8d
/extern/lib_example/lib_example.cpp
062d29f09b1c980c8011585caf59c3f5d7024703
[]
no_license
askebm/EK-ESD-LAB
55283ec5ac2b8cc0c13842dbbe987a073e33cb90
28d943ce83cf9f6830c27ef3312a42b6cc88b7fe
refs/heads/master
2022-12-29T17:43:31.414450
2020-10-15T12:53:35
2020-10-15T12:53:35
295,687,744
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
cpp
#include <fstream> #include <string> #include <iostream> #include <sstream> #include <unistd.h> #include "GPIO.hpp" int main() { // ------------------------------------------------------------------------------------- // 1. Activate GPIO pin (similar to: echo 902 > /sys/class/gpio/export) GPIO led_pin; // calls the empty constructor led_pin.setPinNumber(984); GPIO button_pin("988"); // calls the constructor taking a string argument led_pin.exportPin(); button_pin.exportPin(); // ------------------------------------------------------------------------------------- // 2. Set directions (similar to: echo "out" > /sys/class/gpio/gpio886/direction) led_pin.setPinDirection("out"); button_pin.setPinDirection("in"); // ------------------------------------------------------------------------------------- // 3. Read the button state (similar to: cat /sys/class/gpio/gpio902/value) std::string button_value; button_pin.getPinValue(button_value); // ------------------------------------------------------------------------------------- // 4. Write to the LED (similar to: echo 1 > /sys/class/gpio/gpio886/value) led_pin.setPinValue("1"); // ------------------------------------------------------------------------------------- // 5. Link the button an LED // Loop forever while(true) { button_pin.getPinValue(button_value); led_pin.setPinValue(button_value); // Wait 10ms usleep(10000); } return 0; }
41509b907c8562ecc28e81081c5181cba2ea56b0
d4c6151c86413dfd0881706a08aff5953a4aa28b
/zircon/system/utest/core/vmo/vmo.cc
a1af507338269b689c5c2b14cccdeeb7e7707b82
[ "BSD-3-Clause", "MIT" ]
permissive
opensource-assist/fuschia
64e0494fe0c299cf19a500925e115a75d6347a10
66646c55b3d0b36aae90a4b6706b87f1a6261935
refs/heads/master
2022-11-02T02:11:41.392221
2019-12-27T00:43:47
2019-12-27T00:43:47
230,425,920
0
1
BSD-3-Clause
2022-10-03T10:28:51
2019-12-27T10:43:28
C++
UTF-8
C++
false
false
50,375
cc
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <ctype.h> #include <inttypes.h> #include <lib/fit/defer.h> #include <lib/fzl/memory-probe.h> #include <lib/zx/bti.h> #include <lib/zx/iommu.h> #include <lib/zx/vmar.h> #include <lib/zx/vmo.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <threads.h> #include <unistd.h> #include <zircon/process.h> #include <zircon/syscalls.h> #include <zircon/syscalls/iommu.h> #include <zircon/syscalls/object.h> #include <algorithm> #include <atomic> #include <thread> #include <fbl/algorithm.h> #include <fbl/function.h> #include <zxtest/zxtest.h> extern "C" __WEAK zx_handle_t get_root_resource(void); namespace { TEST(VmoTestCase, Create) { zx_status_t status; zx_handle_t vmo[16]; // allocate a bunch of vmos then free them for (size_t i = 0; i < fbl::count_of(vmo); i++) { status = zx_vmo_create(i * PAGE_SIZE, 0, &vmo[i]); EXPECT_OK(status, "vm_object_create"); } for (size_t i = 0; i < fbl::count_of(vmo); i++) { status = zx_handle_close(vmo[i]); EXPECT_OK(status, "handle_close"); } } TEST(VmoTestCase, ReadWriteBadLen) { zx_status_t status; zx_handle_t vmo; // allocate an object and attempt read/write from it, with bad length const size_t len = PAGE_SIZE * 4; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); char buf[len]; for (int i = 1; i <= 2; i++) { status = zx_vmo_read(vmo, buf, 0, std::numeric_limits<size_t>::max() - (PAGE_SIZE / i)); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, status); status = zx_vmo_write(vmo, buf, 0, std::numeric_limits<size_t>::max() - (PAGE_SIZE / i)); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, status); } status = zx_vmo_read(vmo, buf, 0, len); EXPECT_OK(status, "vmo_read"); status = zx_vmo_write(vmo, buf, 0, len); EXPECT_OK(status, "vmo_write"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, ReadWrite) { zx_status_t status; zx_handle_t vmo; // allocate an object and read/write from it const size_t len = PAGE_SIZE * 4; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); char buf[len]; status = zx_vmo_read(vmo, buf, 0, sizeof(buf)); EXPECT_OK(status, "vm_object_read"); // make sure it's full of zeros size_t count = 0; for (auto c : buf) { EXPECT_EQ(c, 0, "zero test"); if (c != 0) { printf("char at offset %#zx is bad\n", count); } count++; } memset(buf, 0x99, sizeof(buf)); status = zx_vmo_write(vmo, buf, 0, sizeof(buf)); EXPECT_OK(status, "vm_object_write"); // map it uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(0u, ptr, "vm_map"); // check that it matches what we last wrote into it EXPECT_BYTES_EQ((uint8_t *)buf, (uint8_t *)ptr, sizeof(buf), "mapped buffer"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "vm_unmap"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, ReadWriteRange) { zx_status_t status; zx_handle_t vmo; // allocate an object const size_t len = PAGE_SIZE * 4; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // fail to read past end char buf[len * 2]; status = zx_vmo_read(vmo, buf, 0, sizeof(buf)); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_read past end"); // Successfully read 0 bytes at end status = zx_vmo_read(vmo, buf, len, 0); EXPECT_OK(status, "vm_object_read zero at end"); // Fail to read 0 bytes past end status = zx_vmo_read(vmo, buf, len + 1, 0); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_read zero past end"); // fail to write past end status = zx_vmo_write(vmo, buf, 0, sizeof(buf)); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_write past end"); // Successfully write 0 bytes at end status = zx_vmo_write(vmo, buf, len, 0); EXPECT_OK(status, "vm_object_write zero at end"); // Fail to read 0 bytes past end status = zx_vmo_write(vmo, buf, len + 1, 0); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_write zero past end"); // Test for unsigned wraparound status = zx_vmo_read(vmo, buf, UINT64_MAX - (len / 2), len); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_read offset + len wraparound"); status = zx_vmo_write(vmo, buf, UINT64_MAX - (len / 2), len); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_write offset + len wraparound"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, Map) { zx_status_t status; zx_handle_t vmo; uintptr_t ptr[3] = {}; // allocate a vmo status = zx_vmo_create(4 * PAGE_SIZE, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // do a regular map ptr[0] = 0; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, PAGE_SIZE, &ptr[0]); EXPECT_OK(status, "map"); EXPECT_NE(0u, ptr[0], "map address"); // printf("mapped %#" PRIxPTR "\n", ptr[0]); // try to map something completely out of range without any fixed mapping, should succeed ptr[2] = UINTPTR_MAX; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, PAGE_SIZE, &ptr[2]); EXPECT_OK(status, "map"); EXPECT_NE(0u, ptr[2], "map address"); // try to map something completely out of range fixed, should fail uintptr_t map_addr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_SPECIFIC, UINTPTR_MAX, vmo, 0, PAGE_SIZE, &map_addr); EXPECT_EQ(ZX_ERR_INVALID_ARGS, status, "map"); // cleanup status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); for (auto p : ptr) { if (p) { status = zx_vmar_unmap(zx_vmar_root_self(), p, PAGE_SIZE); EXPECT_OK(status, "unmap"); } } } TEST(VmoTestCase, MapRead) { zx::vmo vmo; EXPECT_OK(zx::vmo::create(PAGE_SIZE * 2, 0, &vmo)); uintptr_t vaddr; // Map in the first page EXPECT_OK( zx::vmar::root_self()->map(0, vmo, 0, PAGE_SIZE, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, &vaddr)); // Read from the second page of the vmo to mapping. // This should succeed and not deadlock in the kernel. EXPECT_OK(vmo.read(reinterpret_cast<void *>(vaddr), PAGE_SIZE, PAGE_SIZE)); } TEST(VmoTestCase, ParallelRead) { constexpr size_t kNumPages = 1024; zx::vmo vmo1, vmo2; EXPECT_OK(zx::vmo::create(PAGE_SIZE * kNumPages, 0, &vmo1)); EXPECT_OK(zx::vmo::create(PAGE_SIZE * kNumPages, 0, &vmo2)); uintptr_t vaddr1, vaddr2; // Map the bottom half of both in. EXPECT_OK(zx::vmar::root_self()->map(0, vmo1, 0, PAGE_SIZE * (kNumPages / 2), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, &vaddr1)); EXPECT_OK(zx::vmar::root_self()->map(0, vmo2, 0, PAGE_SIZE * (kNumPages / 2), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, &vaddr2)); // Spin up a thread to read from one of the vmos, whilst we read from the other auto vmo_read_closure = [&vmo1, &vaddr2] { vmo1.read(reinterpret_cast<void *>(vaddr2), PAGE_SIZE * (kNumPages / 2), PAGE_SIZE * (kNumPages / 2)); }; std::thread thread(vmo_read_closure); // As these two threads read from one vmo into the mapping from another vmo if there are any // scenarios where the kernel would try and hold both vmo locks at the same time (without // attempting to resolve lock ordering) then this should trigger a deadlock to occur. EXPECT_OK(vmo2.read(reinterpret_cast<void *>(vaddr1), PAGE_SIZE * (kNumPages / 2), PAGE_SIZE * (kNumPages / 2))); thread.join(); } TEST(VmoTestCase, ReadOnlyMap) { zx_status_t status; zx_handle_t vmo; // allocate an object and read/write from it const size_t len = PAGE_SIZE; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // map it uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(0u, ptr, "vm_map"); EXPECT_EQ(false, probe_for_write((void *)ptr), "write"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "vm_unmap"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, NoPermMap) { zx_status_t status; zx_handle_t vmo; // allocate an object and read/write from it const size_t len = PAGE_SIZE; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // map it with read permissions uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(0u, ptr, "vm_map"); // protect it to no permissions status = zx_vmar_protect(zx_vmar_root_self(), 0, ptr, len); EXPECT_OK(status, "vm_protect"); // test reading writing to the mapping EXPECT_EQ(false, probe_for_read(reinterpret_cast<void *>(ptr)), "read"); EXPECT_EQ(false, probe_for_write(reinterpret_cast<void *>(ptr)), "write"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "vm_unmap"); // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } TEST(VmoTestCase, NoPermProtect) { zx_status_t status; zx_handle_t vmo; // allocate an object and read/write from it const size_t len = PAGE_SIZE; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // map it with no permissions uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), 0, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(0u, ptr, "vm_map"); // test writing to the mapping EXPECT_EQ(false, probe_for_write(reinterpret_cast<void *>(ptr)), "write"); // test reading to the mapping EXPECT_EQ(false, probe_for_read(reinterpret_cast<void *>(ptr)), "read"); // protect it to read permissions and make sure it works as expected status = zx_vmar_protect(zx_vmar_root_self(), ZX_VM_PERM_READ, ptr, len); EXPECT_OK(status, "vm_protect"); // test writing to the mapping EXPECT_EQ(false, probe_for_write(reinterpret_cast<void *>(ptr)), "write"); // test reading from the mapping EXPECT_EQ(true, probe_for_read(reinterpret_cast<void *>(ptr)), "read"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "vm_unmap"); // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } TEST(VmoTestCase, Resize) { zx_status_t status; zx_handle_t vmo; // allocate an object size_t len = PAGE_SIZE * 4; status = zx_vmo_create(len, ZX_VMO_RESIZABLE, &vmo); EXPECT_OK(status, "vm_object_create"); // get the size that we set it to uint64_t size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(len, size, "vm_object_get_size"); // try to resize it len += PAGE_SIZE; status = zx_vmo_set_size(vmo, len); EXPECT_OK(status, "vm_object_set_size"); // get the size again size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(len, size, "vm_object_get_size"); // try to resize it to a ludicrous size status = zx_vmo_set_size(vmo, UINT64_MAX); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, status, "vm_object_set_size too big"); // resize it to a non aligned size status = zx_vmo_set_size(vmo, len + 1); EXPECT_OK(status, "vm_object_set_size"); // size should be rounded up to the next page boundary size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(fbl::round_up(len + 1u, static_cast<size_t>(PAGE_SIZE)), size, "vm_object_get_size"); len = fbl::round_up(len + 1u, static_cast<size_t>(PAGE_SIZE)); // map it uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(ptr, 0, "vm_map"); // attempt to map expecting an non resizable vmo. uintptr_t ptr2; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_REQUIRE_NON_RESIZABLE, 0, vmo, 0, len, &ptr2); EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, status, "vm_map"); // resize it with it mapped status = zx_vmo_set_size(vmo, size); EXPECT_OK(status, "vm_object_set_size"); // unmap it status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "unmap"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } // Check that non-resizable VMOs cannot get resized. TEST(VmoTestCase, NoResize) { const size_t len = PAGE_SIZE * 4; zx_handle_t vmo = ZX_HANDLE_INVALID; zx_vmo_create(len, 0, &vmo); EXPECT_NE(vmo, ZX_HANDLE_INVALID); zx_status_t status; status = zx_vmo_set_size(vmo, len + PAGE_SIZE); EXPECT_EQ(ZX_ERR_UNAVAILABLE, status, "vm_object_set_size"); status = zx_vmo_set_size(vmo, len - PAGE_SIZE); EXPECT_EQ(ZX_ERR_UNAVAILABLE, status, "vm_object_set_size"); size_t size; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(len, size, "vm_object_get_size"); uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_REQUIRE_NON_RESIZABLE, 0, vmo, 0, len, &ptr); ASSERT_OK(status, "vm_map"); ASSERT_NE(ptr, 0, "vm_map"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "unmap"); status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, Info) { size_t len = PAGE_SIZE * 4; zx::vmo vmo; zx_info_vmo_t info; zx_status_t status; // Create a non-resizeable VMO, query the INFO on it // and dump it. status = zx::vmo::create(len, 0, &vmo); EXPECT_OK(status, "vm_info_test: vmo_create"); status = vmo.get_info(ZX_INFO_VMO, &info, sizeof(info), nullptr, nullptr); EXPECT_OK(status, "vm_info_test: info_vmo"); vmo.reset(); EXPECT_EQ(info.size_bytes, len, "vm_info_test: info_vmo.size_bytes"); EXPECT_EQ(info.flags, ZX_INFO_VMO_TYPE_PAGED | ZX_INFO_VMO_VIA_HANDLE, "vm_info_test: info_vmo.flags"); EXPECT_EQ(info.cache_policy, ZX_CACHE_POLICY_CACHED, "vm_info_test: info_vmo.cache_policy"); // Create a resizeable uncached VMO, query the INFO on it and dump it. len = PAGE_SIZE * 8; zx::vmo::create(len, ZX_VMO_RESIZABLE, &vmo); EXPECT_OK(status, "vm_info_test: vmo_create"); vmo.set_cache_policy(ZX_CACHE_POLICY_UNCACHED); size_t actual, avail; status = vmo.get_info(ZX_INFO_VMO, &info, sizeof(info), &actual, &avail); EXPECT_OK(status, "vm_info_test: info_vmo"); EXPECT_EQ(actual, 1); EXPECT_EQ(avail, 1); vmo.reset(); EXPECT_EQ(info.size_bytes, len, "vm_info_test: info_vmo.size_bytes"); EXPECT_EQ(info.flags, ZX_INFO_VMO_TYPE_PAGED | ZX_INFO_VMO_VIA_HANDLE | ZX_INFO_VMO_RESIZABLE, "vm_info_test: info_vmo.flags"); EXPECT_EQ(info.cache_policy, ZX_CACHE_POLICY_UNCACHED, "vm_info_test: info_vmo.cache_policy"); if (get_root_resource) { zx::iommu iommu; zx::bti bti; // Please do not use get_root_resource() in new code. See ZX-1467. zx::unowned_resource root_res(get_root_resource()); zx_iommu_desc_dummy_t desc; EXPECT_EQ(zx_iommu_create((*root_res).get(), ZX_IOMMU_TYPE_DUMMY, &desc, sizeof(desc), iommu.reset_and_get_address()), ZX_OK); EXPECT_OK(zx::bti::create(iommu, 0, 0xdeadbeef, &bti)); len = PAGE_SIZE * 12; EXPECT_OK(zx::vmo::create_contiguous(bti, len, 0, &vmo)); status = vmo.get_info(ZX_INFO_VMO, &info, sizeof(info), nullptr, nullptr); EXPECT_OK(status, "vm_info_test: info_vmo"); EXPECT_EQ(info.size_bytes, len, "vm_info_test: info_vmo.size_bytes"); EXPECT_EQ(info.flags, ZX_INFO_VMO_TYPE_PAGED | ZX_INFO_VMO_VIA_HANDLE | ZX_INFO_VMO_CONTIGUOUS, "vm_info_test: info_vmo.flags"); EXPECT_EQ(info.cache_policy, ZX_CACHE_POLICY_CACHED, "vm_info_test: info_vmo.cache_policy"); } } TEST(VmoTestCase, SizeAlign) { for (uint64_t s = 0; s < PAGE_SIZE * 4; s++) { zx_handle_t vmo; // create a new object with nonstandard size zx_status_t status = zx_vmo_create(s, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // should be the size rounded up to the nearest page boundary uint64_t size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(fbl::round_up(s, static_cast<size_t>(PAGE_SIZE)), size, "vm_object_get_size"); // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } } TEST(VmoTestCase, ResizeAlign) { // resize a vmo with a particular size and test that the resulting size is aligned on a page // boundary. zx_handle_t vmo; zx_status_t status = zx_vmo_create(0, ZX_VMO_RESIZABLE, &vmo); EXPECT_OK(status, "vm_object_create"); for (uint64_t s = 0; s < PAGE_SIZE * 4; s++) { // set the size of the object zx_status_t status = zx_vmo_set_size(vmo, s); EXPECT_OK(status, "vm_object_create"); // should be the size rounded up to the nearest page boundary uint64_t size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(fbl::round_up(s, static_cast<size_t>(PAGE_SIZE)), size, "vm_object_get_size"); } // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } void RightsTestMapHelper(zx_handle_t vmo, size_t len, uint32_t flags, bool expect_success, zx_status_t fail_err_code) { uintptr_t ptr; zx_status_t r = zx_vmar_map(zx_vmar_root_self(), flags, 0, vmo, 0, len, &ptr); if (expect_success) { EXPECT_OK(r); r = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(r, "unmap"); } else { EXPECT_EQ(fail_err_code, r); } } zx_rights_t GetHandleRights(zx_handle_t h) { zx_info_handle_basic_t info; zx_status_t s = zx_object_get_info(h, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); if (s != ZX_OK) { EXPECT_OK(s); // Poison the test return 0; } return info.rights; } void ChildPermsTestHelper(const zx_handle_t vmo) { // Read out the current rights; const zx_rights_t parent_rights = GetHandleRights(vmo); // Make different kinds of children and ensure we get the correct rights. zx_handle_t child; EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, PAGE_SIZE, &child)); EXPECT_EQ(GetHandleRights(child), (parent_rights | ZX_RIGHT_GET_PROPERTY | ZX_RIGHT_SET_PROPERTY | ZX_RIGHT_WRITE) & ~ZX_RIGHT_EXECUTE); EXPECT_OK(zx_handle_close(child)); EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE | ZX_VMO_CHILD_NO_WRITE, 0, PAGE_SIZE, &child)); EXPECT_EQ(GetHandleRights(child), (parent_rights | ZX_RIGHT_GET_PROPERTY | ZX_RIGHT_SET_PROPERTY) & ~ZX_RIGHT_WRITE); EXPECT_OK(zx_handle_close(child)); EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_SLICE, 0, PAGE_SIZE, &child)); EXPECT_EQ(GetHandleRights(child), parent_rights | ZX_RIGHT_GET_PROPERTY | ZX_RIGHT_SET_PROPERTY); EXPECT_OK(zx_handle_close(child)); EXPECT_OK( zx_vmo_create_child(vmo, ZX_VMO_CHILD_SLICE | ZX_VMO_CHILD_NO_WRITE, 0, PAGE_SIZE, &child)); EXPECT_EQ(GetHandleRights(child), (parent_rights | ZX_RIGHT_GET_PROPERTY | ZX_RIGHT_SET_PROPERTY) & ~ZX_RIGHT_WRITE); EXPECT_OK(zx_handle_close(child)); } TEST(VmoTestCase, Rights) { char buf[4096]; size_t len = PAGE_SIZE * 4; zx_status_t status; zx_handle_t vmo, vmo2; // allocate an object status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // Check that the handle has at least the expected rights. // This list should match the list in docs/syscalls/vmo_create.md. static const zx_rights_t kExpectedRights = ZX_RIGHT_DUPLICATE | ZX_RIGHT_TRANSFER | ZX_RIGHT_WAIT | ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_MAP | ZX_RIGHT_GET_PROPERTY | ZX_RIGHT_SET_PROPERTY; EXPECT_EQ(kExpectedRights, kExpectedRights & GetHandleRights(vmo)); // test that we can read/write it status = zx_vmo_read(vmo, buf, 0, 0); EXPECT_EQ(0, status, "vmo_read"); status = zx_vmo_write(vmo, buf, 0, 0); EXPECT_EQ(0, status, "vmo_write"); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ, &vmo2); status = zx_vmo_read(vmo2, buf, 0, 0); EXPECT_EQ(0, status, "vmo_read"); status = zx_vmo_write(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_ACCESS_DENIED, status, "vmo_write"); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_WRITE, &vmo2); status = zx_vmo_read(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_ACCESS_DENIED, status, "vmo_read"); status = zx_vmo_write(vmo2, buf, 0, 0); EXPECT_EQ(0, status, "vmo_write"); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, 0, &vmo2); status = zx_vmo_read(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_ACCESS_DENIED, status, "vmo_read"); status = zx_vmo_write(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_ACCESS_DENIED, status, "vmo_write"); zx_handle_close(vmo2); status = zx_vmo_replace_as_executable(vmo, ZX_HANDLE_INVALID, &vmo); EXPECT_OK(status, "vmo_replace_as_executable"); EXPECT_EQ(kExpectedRights | ZX_RIGHT_EXECUTE, (kExpectedRights | ZX_RIGHT_EXECUTE) & GetHandleRights(vmo)); // full perm test ASSERT_NO_FATAL_FAILURES(ChildPermsTestHelper(vmo)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper( vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, true, 0)); // try most of the permutations of mapping and clone a vmo with various rights dropped vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_EXECUTE | ZX_RIGHT_DUPLICATE, &vmo2); ASSERT_NO_FATAL_FAILURES(ChildPermsTestHelper(vmo2)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_MAP | ZX_RIGHT_DUPLICATE, &vmo2); ASSERT_NO_FATAL_FAILURES(ChildPermsTestHelper(vmo2)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_WRITE | ZX_RIGHT_MAP | ZX_RIGHT_DUPLICATE, &vmo2); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_MAP | ZX_RIGHT_DUPLICATE, &vmo2); ASSERT_NO_FATAL_FAILURES(ChildPermsTestHelper(vmo2)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_EXECUTE | ZX_RIGHT_MAP | ZX_RIGHT_DUPLICATE, &vmo2); ASSERT_NO_FATAL_FAILURES(ChildPermsTestHelper(vmo2)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, true, 0)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate( vmo, ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_EXECUTE | ZX_RIGHT_MAP | ZX_RIGHT_DUPLICATE, &vmo2); ASSERT_NO_FATAL_FAILURES(ChildPermsTestHelper(vmo2)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper( vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, true, 0)); zx_handle_close(vmo2); // test that we can get/set a property on it const char *set_name = "test vmo"; status = zx_object_set_property(vmo, ZX_PROP_NAME, set_name, sizeof(set_name)); EXPECT_OK(status, "set_property"); char get_name[ZX_MAX_NAME_LEN]; status = zx_object_get_property(vmo, ZX_PROP_NAME, get_name, sizeof(get_name)); EXPECT_OK(status, "get_property"); EXPECT_STR_EQ(set_name, get_name, "vmo name"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); // Use wrong handle with wrong permission, and expect wrong type not // ZX_ERR_ACCESS_DENIED vmo = ZX_HANDLE_INVALID; vmo2 = ZX_HANDLE_INVALID; status = zx_port_create(0, &vmo); EXPECT_OK(status, "zx_port_create"); status = zx_handle_duplicate(vmo, 0, &vmo2); EXPECT_OK(status, "zx_handle_duplicate"); status = zx_vmo_read(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_WRONG_TYPE, status, "vmo_read wrong type"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); status = zx_handle_close(vmo2); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, Commit) { zx_handle_t vmo; zx_status_t status; uintptr_t ptr, ptr2, ptr3; // create a vmo const size_t size = 16384; status = zx_vmo_create(size, 0, &vmo); EXPECT_EQ(0, status, "vm_object_create"); // commit a range of it status = zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0, size, nullptr, 0); EXPECT_EQ(0, status, "vm commit"); // decommit that range status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0, size, nullptr, 0); EXPECT_EQ(0, status, "vm decommit"); // commit a range of it status = zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0, size, nullptr, 0); EXPECT_EQ(0, status, "vm commit"); // map it ptr = 0; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, size, &ptr); EXPECT_OK(status, "map"); EXPECT_NE(ptr, 0, "map address"); // second mapping with an offset ptr2 = 0; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, PAGE_SIZE, size, &ptr2); EXPECT_OK(status, "map2"); EXPECT_NE(ptr2, 0, "map address2"); // third mapping with a totally non-overlapping offset ptr3 = 0; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, size * 2, size, &ptr3); EXPECT_OK(status, "map3"); EXPECT_NE(ptr3, 0, "map address3"); // write into it at offset PAGE_SIZE, read it back volatile uint32_t *u32 = (volatile uint32_t *)(ptr + PAGE_SIZE); *u32 = 99; EXPECT_EQ(99u, (*u32), "written memory"); // check the alias volatile uint32_t *u32a = (volatile uint32_t *)(ptr2); EXPECT_EQ(99u, (*u32a), "written memory"); // decommit page 0 status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0, PAGE_SIZE, nullptr, 0); EXPECT_EQ(0, status, "vm decommit"); // verify that it didn't get unmapped EXPECT_EQ(99u, (*u32), "written memory"); // verify that it didn't get unmapped EXPECT_EQ(99u, (*u32a), "written memory2"); // decommit page 1 status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, PAGE_SIZE, PAGE_SIZE, nullptr, 0); EXPECT_EQ(0, status, "vm decommit"); // verify that it did get unmapped EXPECT_EQ(0u, (*u32), "written memory"); // verify that it did get unmapped EXPECT_EQ(0u, (*u32a), "written memory2"); // unmap our vmos status = zx_vmar_unmap(zx_vmar_root_self(), ptr, size); EXPECT_OK(status, "vm_unmap"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr2, size); EXPECT_OK(status, "vm_unmap"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr3, size); EXPECT_OK(status, "vm_unmap"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, ZeroPage) { zx_handle_t vmo; zx_status_t status; uintptr_t ptr[3]; // create a vmo const size_t size = PAGE_SIZE * 4; EXPECT_OK(zx_vmo_create(size, 0, &vmo), "vm_object_create"); // make a few mappings of the vmo for (auto &p : ptr) { EXPECT_EQ( ZX_OK, zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, size, &p), "map"); EXPECT_NE(0, p, "map address"); } volatile uint32_t *val = (volatile uint32_t *)ptr[0]; volatile uint32_t *val2 = (volatile uint32_t *)ptr[1]; volatile uint32_t *val3 = (volatile uint32_t *)ptr[2]; // read fault in the first mapping EXPECT_EQ(0, *val, "read zero"); // write fault the second mapping *val2 = 99; EXPECT_EQ(99, *val2, "read back 99"); // expect the third mapping to read fault in the new page EXPECT_EQ(99, *val3, "read 99"); // expect the first mapping to have gotten updated with the new mapping // and no longer be mapping the zero page EXPECT_EQ(99, *val, "read 99 from former zero page"); // read fault in zeros on the second page val = (volatile uint32_t *)(ptr[0] + PAGE_SIZE); EXPECT_EQ(0, *val, "read zero"); // write to the page via a vmo_write call uint32_t v = 100; status = zx_vmo_write(vmo, &v, PAGE_SIZE, sizeof(v)); EXPECT_OK(status, "writing to vmo"); // expect it to read back the new value EXPECT_EQ(100, *val, "read 100 from former zero page"); // read fault in zeros on the third page val = (volatile uint32_t *)(ptr[0] + PAGE_SIZE * 2); EXPECT_EQ(0, *val, "read zero"); // commit this range of the vmo via a commit call status = zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, PAGE_SIZE * 2, PAGE_SIZE, nullptr, 0); EXPECT_OK(status, "committing memory"); // write to the third page status = zx_vmo_write(vmo, &v, PAGE_SIZE * 2, sizeof(v)); EXPECT_OK(status, "writing to vmo"); // expect it to read back the new value EXPECT_EQ(100, *val, "read 100 from former zero page"); // unmap for (auto p : ptr) EXPECT_OK(zx_vmar_unmap(zx_vmar_root_self(), p, size), "unmap"); // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } TEST(VmoTestCase, Cache) { zx_handle_t vmo; const size_t size = PAGE_SIZE; EXPECT_OK(zx_vmo_create(size, 0, &vmo), "creation for cache_policy"); // clean vmo can have all valid cache policies set EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_UNCACHED)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_UNCACHED_DEVICE)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_WRITE_COMBINING)); // bad cache policy EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_MASK + 1)); // map the vmo, make sure policy doesn't set uintptr_t ptr; EXPECT_OK(zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, size, &ptr)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmar_unmap(zx_vmar_root_self(), ptr, size)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); // clone the vmo, make sure policy doesn't set zx_handle_t clone; EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, size, &clone)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_handle_close(clone)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); // clone the vmo, try to set policy on the clone EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, size, &clone)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_set_cache_policy(clone, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_handle_close(clone)); // set the policy, make sure future clones do not go through EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_UNCACHED)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, size, &clone)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, size, &clone)); EXPECT_OK(zx_handle_close(clone)); // set the policy, make sure vmo read/write do not work char c; EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_UNCACHED)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_read(vmo, &c, 0, sizeof(c))); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_write(vmo, &c, 0, sizeof(c))); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmo_read(vmo, &c, 0, sizeof(c))); EXPECT_OK(zx_vmo_write(vmo, &c, 0, sizeof(c))); EXPECT_OK(zx_handle_close(vmo), "close handle"); } TEST(VmoTestCase, PhysicalSlice) { if (!get_root_resource) { printf("Root resource not available, skipping\n"); return; } const size_t size = PAGE_SIZE * 2; // To get physical pages in physmap for the physical_vmo, we create a // contiguous vmo. This needs to last until after we're done testing // with the physical_vmo. zx::vmo contig_vmo; zx::pmt pmt; auto unpin_pmt = fit::defer([&pmt] { if (pmt) { EXPECT_OK(pmt.unpin()); } }); zx::unowned_resource root_res(get_root_resource()); zx::iommu iommu; zx::bti bti; zx_iommu_desc_dummy_t desc; EXPECT_OK(zx::iommu::create(*root_res, ZX_IOMMU_TYPE_DUMMY, &desc, sizeof(desc), &iommu)); EXPECT_OK(zx::bti::create(iommu, 0, 0xdeadbeef, &bti)); EXPECT_OK(zx::vmo::create_contiguous(bti, size, 0, &contig_vmo)); zx_paddr_t phys_addr; EXPECT_OK( bti.pin(ZX_BTI_PERM_WRITE | ZX_BTI_CONTIGUOUS, contig_vmo, 0, size, &phys_addr, 1, &pmt)); zx::vmo physical_vmo; EXPECT_OK(zx::vmo::create_physical(*root_res, phys_addr, size, &physical_vmo)); // Switch to a cached policy as we are operating on real memory and do not need to be uncached. EXPECT_OK(physical_vmo.set_cache_policy(ZX_CACHE_POLICY_CACHED)); // Create a slice of the second page. zx::vmo slice_vmo; EXPECT_OK(physical_vmo.create_child(ZX_VMO_CHILD_SLICE, size / 2, size / 2, &slice_vmo)); // Map both VMOs in so we can access them. uintptr_t parent_vaddr; EXPECT_OK(zx::vmar::root_self()->map(0, physical_vmo, 0, size, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, &parent_vaddr)); uintptr_t slice_vaddr; EXPECT_OK(zx::vmar::root_self()->map(0, slice_vmo, 0, size / 2, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, &slice_vaddr)); // Just do some tests using the first byte of each page char *parent_private_test = (char *)parent_vaddr; char *parent_shared_test = (char *)(parent_vaddr + size / 2); char *slice_test = (char *)slice_vaddr; // We expect parent_shared_test and slice_test to be accessing the same physical pages, but we // should have gotten different mappings for them. EXPECT_NE(parent_shared_test, slice_test); *parent_private_test = 0; *parent_shared_test = 1; // This should have set the child. EXPECT_EQ(*slice_test, 1); // Write to the child now and validate parent changed correctly. *slice_test = 42; EXPECT_EQ(*parent_shared_test, 42); EXPECT_EQ(*parent_private_test, 0); } TEST(VmoTestCase, CacheOp) { { // scope unpin_pmt so ~unpin_pmt is before END_TEST const size_t size = 0x8000; zx_handle_t normal_vmo = ZX_HANDLE_INVALID; zx_handle_t physical_vmo = ZX_HANDLE_INVALID; // To get physical pages in physmap for the physical_vmo, we create a // contiguous vmo. This needs to last until after we're done testing // with the physical_vmo. zx::vmo contig_vmo; zx::pmt pmt; auto unpin_pmt = fit::defer([&pmt] { if (pmt) { EXPECT_OK(pmt.unpin()); } }); EXPECT_OK(zx_vmo_create(size, 0, &normal_vmo), "creation for cache op (normal vmo)"); // Create physical_vmo if we can. if (get_root_resource) { // Please do not use get_root_resource() in new code. See ZX-1467. zx::unowned_resource root_res(get_root_resource()); zx::iommu iommu; zx::bti bti; zx_iommu_desc_dummy_t desc; EXPECT_EQ(zx_iommu_create((*root_res).get(), ZX_IOMMU_TYPE_DUMMY, &desc, sizeof(desc), iommu.reset_and_get_address()), ZX_OK); EXPECT_OK(zx::bti::create(iommu, 0, 0xdeadbeef, &bti)); // There's a chance this will flake if we're unable to get size // bytes that are physically contiguous. EXPECT_OK(zx::vmo::create_contiguous(bti, size, 0, &contig_vmo)); zx_paddr_t phys_addr; EXPECT_OK(zx_bti_pin(bti.get(), ZX_BTI_PERM_WRITE | ZX_BTI_CONTIGUOUS, contig_vmo.get(), 0, size, &phys_addr, 1, pmt.reset_and_get_address())); EXPECT_EQ(ZX_OK, zx_vmo_create_physical((*root_res).get(), phys_addr, size, &physical_vmo), "creation for cache op (physical vmo)"); // Go ahead and set the cache policy; we don't want the op_range calls // below to potentially skip running any code. EXPECT_OK(zx_vmo_set_cache_policy(physical_vmo, ZX_CACHE_POLICY_CACHED), "zx_vmo_set_cache_policy"); } auto test_vmo = [](zx_handle_t vmo) { if (vmo == ZX_HANDLE_INVALID) { return; } auto test_op = [vmo](uint32_t op) { EXPECT_OK(zx_vmo_op_range(vmo, op, 0, 1, nullptr, 0), "0 1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0, 1, nullptr, 0), "0 1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 1, 1, nullptr, 0), "1 1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0, size, nullptr, 0), "0 size"); EXPECT_OK(zx_vmo_op_range(vmo, op, 1, size - 1, nullptr, 0), "1 size-1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0x5200, 1, nullptr, 0), "0x5200 1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0x5200, 0x800, nullptr, 0), "0x5200 0x800"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0x5200, 0x1000, nullptr, 0), "0x5200 0x1000"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0x5200, 0x1200, nullptr, 0), "0x5200 0x1200"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_vmo_op_range(vmo, op, 0, 0, nullptr, 0), "0 0"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, 1, size, nullptr, 0), "0 size"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, size, 1, nullptr, 0), "size 1"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, size + 1, 1, nullptr, 0), "size+1 1"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, UINT64_MAX - 1, 1, nullptr, 0), "UINT64_MAX-1 1"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, UINT64_MAX, 1, nullptr, 0), "UINT64_MAX 1"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, UINT64_MAX, UINT64_MAX, nullptr, 0), "UINT64_MAX UINT64_MAX"); }; test_op(ZX_VMO_OP_CACHE_SYNC); test_op(ZX_VMO_OP_CACHE_CLEAN); test_op(ZX_VMO_OP_CACHE_CLEAN_INVALIDATE); test_op(ZX_VMO_OP_CACHE_INVALIDATE); }; ZX_DEBUG_ASSERT(normal_vmo != ZX_HANDLE_INVALID); ZX_DEBUG_ASSERT(physical_vmo != ZX_HANDLE_INVALID || !get_root_resource); test_vmo(normal_vmo); test_vmo(physical_vmo); EXPECT_OK(zx_handle_close(normal_vmo), "close handle (normal vmo)"); // Closing ZX_HANDLE_INVALID is not an error. EXPECT_OK(zx_handle_close(physical_vmo), "close handle (physical vmo)"); } // ~unpin_pmt before END_TEST } TEST(VmoTestCase, CacheFlush) { zx_handle_t vmo; const size_t size = 0x8000; EXPECT_OK(zx_vmo_create(size, 0, &vmo), "creation for cache op"); uintptr_t ptr_ro; EXPECT_EQ(ZX_OK, zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, size, &ptr_ro), "map"); EXPECT_NE(ptr_ro, 0, "map address"); void *pro = (void *)ptr_ro; uintptr_t ptr_rw; EXPECT_EQ(ZX_OK, zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, size, &ptr_rw), "map"); EXPECT_NE(ptr_rw, 0, "map address"); void *prw = (void *)ptr_rw; zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0, size, NULL, 0); EXPECT_OK(zx_cache_flush(prw, size, ZX_CACHE_FLUSH_INSN), "rw flush insn"); EXPECT_OK(zx_cache_flush(prw, size, ZX_CACHE_FLUSH_DATA), "rw clean"); EXPECT_OK(zx_cache_flush(prw, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INSN), "rw clean w/ insn"); EXPECT_OK(zx_cache_flush(prw, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE), "rw clean/invalidate"); EXPECT_EQ(ZX_OK, zx_cache_flush(prw, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE | ZX_CACHE_FLUSH_INSN), "rw all"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_INSN), "ro flush insn"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA), "ro clean"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INSN), "ro clean w/ insn"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE), "ro clean/invalidate"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE), "ro clean/invalidate"); EXPECT_EQ(ZX_OK, zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE | ZX_CACHE_FLUSH_INSN), "ro all"); // Above checks all valid options combinations; check that invalid // combinations are handled correctly here. EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, 0), "no args"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, ZX_CACHE_FLUSH_INVALIDATE), "invalidate requires data"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, ZX_CACHE_FLUSH_INSN | ZX_CACHE_FLUSH_INVALIDATE), "invalidate requires data"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, 1u << 3), "out of range a"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, ~0u), "out of range b"); zx_vmar_unmap(zx_vmar_root_self(), ptr_rw, size); zx_vmar_unmap(zx_vmar_root_self(), ptr_ro, size); EXPECT_OK(zx_handle_close(vmo), "close handle"); } TEST(VmoTestCase, DecommitMisaligned) { zx_handle_t vmo; EXPECT_OK(zx_vmo_create(PAGE_SIZE * 2, 0, &vmo), "creation for decommit test"); // Forbid unaligned decommit, even if there's nothing committed. zx_status_t status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0x10, 0x100, NULL, 0); EXPECT_EQ(ZX_ERR_INVALID_ARGS, status, "decommitting uncommitted memory"); status = zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0x10, 0x100, NULL, 0); EXPECT_OK(status, "committing memory"); status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0x10, 0x100, NULL, 0); EXPECT_EQ(ZX_ERR_INVALID_ARGS, status, "decommitting memory"); EXPECT_OK(zx_handle_close(vmo), "close handle"); } // Resizing a regular mapped VMO causes a fault. TEST(VmoTestCase, ResizeHazard) { const size_t size = PAGE_SIZE * 2; zx_handle_t vmo; ASSERT_OK(zx_vmo_create(size, ZX_VMO_RESIZABLE, &vmo)); uintptr_t ptr_rw; EXPECT_OK(zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, size, &ptr_rw), "map"); auto int_arr = reinterpret_cast<int *>(ptr_rw); EXPECT_EQ(int_arr[1], 0); EXPECT_OK(zx_vmo_set_size(vmo, 0u)); EXPECT_EQ(false, probe_for_read(&int_arr[1]), "read probe"); EXPECT_EQ(false, probe_for_write(&int_arr[1]), "write probe"); EXPECT_OK(zx_handle_close(vmo)); EXPECT_OK(zx_vmar_unmap(zx_vmar_root_self(), ptr_rw, size), "unmap"); } TEST(VmoTestCase, CompressedContiguous) { if (!get_root_resource) { printf("Root resource not available, skipping\n"); return; } zx::unowned_resource root_res(get_root_resource()); zx::iommu iommu; zx::bti bti; zx_iommu_desc_dummy_t desc; EXPECT_OK(zx::iommu::create(*root_res, ZX_IOMMU_TYPE_DUMMY, &desc, sizeof(desc), &iommu)); EXPECT_OK(zx::bti::create(iommu, 0, 0xdeadbeef, &bti)); zx_info_bti_t bti_info; EXPECT_OK(bti.get_info(ZX_INFO_BTI, &bti_info, sizeof(bti_info), nullptr, nullptr)); constexpr uint32_t kMaxAddrs = 2; // If the minimum contiguity is too high this won't be an effective test, but // the code should still work. uint64_t size = std::min(128ul * 1024 * 1024, bti_info.minimum_contiguity * kMaxAddrs); zx::vmo contig_vmo; EXPECT_OK(zx::vmo::create_contiguous(bti, size, 0, &contig_vmo)); zx_paddr_t paddrs[kMaxAddrs]; uint64_t num_addrs = fbl::round_up(size, bti_info.minimum_contiguity) / bti_info.minimum_contiguity; zx::pmt pmt; EXPECT_OK( bti.pin(ZX_BTI_COMPRESS | ZX_BTI_PERM_READ, contig_vmo, 0, size, paddrs, num_addrs, &pmt)); pmt.unpin(); if (num_addrs > 1) { zx::pmt pmt2; EXPECT_EQ(ZX_ERR_INVALID_ARGS, bti.pin(ZX_BTI_COMPRESS | ZX_BTI_PERM_READ, contig_vmo, 0, size, paddrs, 1, &pmt2)); } } TEST(VmoTestCase, UncachedContiguous) { if (!get_root_resource) { printf("Root resource not available, skipping\n"); return; } zx::unowned_resource root_res(get_root_resource()); zx::iommu iommu; zx::bti bti; zx_iommu_desc_dummy_t desc; EXPECT_OK(zx::iommu::create(*root_res, ZX_IOMMU_TYPE_DUMMY, &desc, sizeof(desc), &iommu)); EXPECT_OK(zx::bti::create(iommu, 0, 0xdeadbeef, &bti)); constexpr uint64_t kSize = PAGE_SIZE * 4; zx::vmo contig_vmo; EXPECT_OK(zx::vmo::create_contiguous(bti, kSize, 0, &contig_vmo)); // Attempt to make the vmo uncached. EXPECT_OK(contig_vmo.set_cache_policy(ZX_CACHE_POLICY_UNCACHED)); // Validate that it really is uncached by making sure operations that should fail, do. uint64_t data = 42; EXPECT_EQ(contig_vmo.write(&data, 0, sizeof(data)), ZX_ERR_BAD_STATE); // Pin part of the vmo and validate we cannot change the cache policy whilst pinned. zx_paddr_t paddr; zx::pmt pmt; EXPECT_OK(bti.pin(ZX_BTI_COMPRESS | ZX_BTI_PERM_READ, contig_vmo, 0, PAGE_SIZE, &paddr, 1, &pmt)); EXPECT_EQ(contig_vmo.set_cache_policy(ZX_CACHE_POLICY_CACHED), ZX_ERR_BAD_STATE); // Unpin and then validate that we cannot move committed pages from uncached->cached pmt.unpin(); EXPECT_EQ(contig_vmo.set_cache_policy(ZX_CACHE_POLICY_CACHED), ZX_ERR_BAD_STATE); } } // namespace
9c870f21297475031989011f5744648ffe8581fe
44289ecb892b6f3df043bab40142cf8530ac2ba4
/Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/modules/v8/V8MediaKeyNeededEvent.cpp
dae206274731151e747edfdd3468f498fef7e239
[ "Apache-2.0" ]
permissive
warrenween/Elastos
a6ef68d8fb699fd67234f376b171c1b57235ed02
5618eede26d464bdf739f9244344e3e87118d7fe
refs/heads/master
2021-01-01T04:07:12.833674
2017-06-17T15:34:33
2017-06-17T15:34:33
97,120,576
2
1
null
2017-07-13T12:33:20
2017-07-13T12:33:20
null
UTF-8
C++
false
false
10,183
cpp
// Copyright 2014 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. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8MediaKeyNeededEvent.h" #include "bindings/v8/Dictionary.h" #include "bindings/v8/ExceptionState.h" #include "bindings/v8/V8DOMConfiguration.h" #include "bindings/v8/V8HiddenValue.h" #include "bindings/v8/V8ObjectConstructor.h" #include "bindings/v8/custom/V8Uint8ArrayCustom.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "core/frame/LocalDOMWindow.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace WebCore { static void initializeScriptWrappableForInterface(MediaKeyNeededEvent* object) { if (ScriptWrappable::wrapperCanBeStoredInObject(object)) ScriptWrappable::fromObject(object)->setTypeInfo(&V8MediaKeyNeededEvent::wrapperTypeInfo); else ASSERT_NOT_REACHED(); } } // namespace WebCore void webCoreInitializeScriptWrappableForInterface(WebCore::MediaKeyNeededEvent* object) { WebCore::initializeScriptWrappableForInterface(object); } namespace WebCore { const WrapperTypeInfo V8MediaKeyNeededEvent::wrapperTypeInfo = { gin::kEmbedderBlink, V8MediaKeyNeededEvent::domTemplate, V8MediaKeyNeededEvent::derefObject, 0, 0, 0, V8MediaKeyNeededEvent::installPerContextEnabledMethods, &V8Event::wrapperTypeInfo, WrapperTypeObjectPrototype, WillBeGarbageCollectedObject }; namespace MediaKeyNeededEventV8Internal { template <typename T> void V8_USE(T) { } static void contentTypeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); MediaKeyNeededEvent* impl = V8MediaKeyNeededEvent::toNative(holder); v8SetReturnValueString(info, impl->contentType(), info.GetIsolate()); } static void contentTypeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); MediaKeyNeededEventV8Internal::contentTypeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void initDataAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); MediaKeyNeededEvent* impl = V8MediaKeyNeededEvent::toNative(holder); RefPtr<Uint8Array> result(impl->initData()); if (result && DOMDataStore::setReturnValueFromWrapper<V8Uint8Array>(info.GetReturnValue(), result.get())) return; v8::Handle<v8::Value> wrapper = toV8(result.get(), holder, info.GetIsolate()); if (!wrapper.IsEmpty()) { V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "initData"), wrapper); v8SetReturnValue(info, wrapper); } } static void initDataAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); MediaKeyNeededEventV8Internal::initDataAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ExceptionState exceptionState(ExceptionState::ConstructionContext, "MediaKeyNeededEvent", info.Holder(), isolate); if (info.Length() < 1) { exceptionState.throwTypeError("An event name must be provided."); exceptionState.throwIfNeeded(); return; } TOSTRING_VOID(V8StringResource<>, type, info[0]); MediaKeyNeededEventInit eventInit; if (info.Length() >= 2) { TONATIVE_VOID(Dictionary, options, Dictionary(info[1], isolate)); if (!initializeMediaKeyNeededEvent(eventInit, options, exceptionState, info)) { exceptionState.throwIfNeeded(); return; } } RefPtrWillBeRawPtr<MediaKeyNeededEvent> event = MediaKeyNeededEvent::create(type, eventInit); v8::Handle<v8::Object> wrapper = info.Holder(); V8DOMWrapper::associateObjectWithWrapper<V8MediaKeyNeededEvent>(event.release(), &V8MediaKeyNeededEvent::wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent); v8SetReturnValue(info, wrapper); } } // namespace MediaKeyNeededEventV8Internal static const V8DOMConfiguration::AttributeConfiguration V8MediaKeyNeededEventAttributes[] = { {"contentType", MediaKeyNeededEventV8Internal::contentTypeAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"initData", MediaKeyNeededEventV8Internal::initDataAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; bool initializeMediaKeyNeededEvent(MediaKeyNeededEventInit& eventInit, const Dictionary& options, ExceptionState& exceptionState, const v8::FunctionCallbackInfo<v8::Value>& info, const String& forEventName) { Dictionary::ConversionContext conversionContext(forEventName.isEmpty() ? String("MediaKeyNeededEvent") : forEventName, "", exceptionState); if (!initializeEvent(eventInit, options, exceptionState, info, forEventName.isEmpty() ? String("MediaKeyNeededEvent") : forEventName)) return false; return true; } void V8MediaKeyNeededEvent::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "DOMConstructor"); if (!info.IsConstructCall()) { throwTypeError(ExceptionMessages::constructorNotCallableAsFunction("MediaKeyNeededEvent"), info.GetIsolate()); return; } if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) { v8SetReturnValue(info, info.Holder()); return; } MediaKeyNeededEventV8Internal::constructor(info); } static void configureV8MediaKeyNeededEventTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; if (!RuntimeEnabledFeatures::encryptedMediaEnabled()) defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "", V8Event::domTemplate(isolate), V8MediaKeyNeededEvent::internalFieldCount, 0, 0, 0, 0, 0, 0, isolate); else defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "MediaKeyNeededEvent", V8Event::domTemplate(isolate), V8MediaKeyNeededEvent::internalFieldCount, V8MediaKeyNeededEventAttributes, WTF_ARRAY_LENGTH(V8MediaKeyNeededEventAttributes), 0, 0, 0, 0, isolate); functionTemplate->SetCallHandler(V8MediaKeyNeededEvent::constructorCallback); functionTemplate->SetLength(1); v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate(); v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate(); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Handle<v8::FunctionTemplate> V8MediaKeyNeededEvent::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8MediaKeyNeededEventTemplate); } bool V8MediaKeyNeededEvent::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Handle<v8::Object> V8MediaKeyNeededEvent::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } MediaKeyNeededEvent* V8MediaKeyNeededEvent::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value) { return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0; } v8::Handle<v8::Object> wrap(MediaKeyNeededEvent* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8MediaKeyNeededEvent>(impl, isolate)); return V8MediaKeyNeededEvent::createWrapper(impl, creationContext, isolate); } v8::Handle<v8::Object> V8MediaKeyNeededEvent::createWrapper(PassRefPtrWillBeRawPtr<MediaKeyNeededEvent> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8MediaKeyNeededEvent>(impl.get(), isolate)); if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) { const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo(); // Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have // the same object de-ref functions, though, so use that as the basis of the check. RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction); } v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; installPerContextEnabledProperties(wrapper, impl.get(), isolate); V8DOMWrapper::associateObjectWithWrapper<V8MediaKeyNeededEvent>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent); return wrapper; } void V8MediaKeyNeededEvent::derefObject(void* object) { #if !ENABLE(OILPAN) fromInternalPointer(object)->deref(); #endif // !ENABLE(OILPAN) } template<> v8::Handle<v8::Value> toV8NoInline(MediaKeyNeededEvent* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { return toV8(impl, creationContext, isolate); } } // namespace WebCore
f16bd3c9a63cf2f40eb7d19f45ed0f5698e5239c
49f88ff91aa582e1a9d5ae5a7014f5c07eab7503
/gen/third_party/blink/renderer/core/dom/mutation_observer_init.h
8b678a96e73061d62e8bb81d8b0689bc7ba0a09c
[]
no_license
AoEiuV020/kiwibrowser-arm64
b6c719b5f35d65906ae08503ec32f6775c9bb048
ae7383776e0978b945e85e54242b4e3f7b930284
refs/heads/main
2023-06-01T21:09:33.928929
2021-06-22T15:56:53
2021-06-22T15:56:53
379,186,747
0
1
null
null
null
null
UTF-8
C++
false
false
3,888
h
// Copyright 2014 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. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/dictionary_impl.h.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #ifndef MutationObserverInit_h #define MutationObserverInit_h #include "third_party/blink/renderer/bindings/core/v8/idl_dictionary_base.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { class CORE_EXPORT MutationObserverInit : public IDLDictionaryBase { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); public: MutationObserverInit(); virtual ~MutationObserverInit(); MutationObserverInit(const MutationObserverInit&); MutationObserverInit& operator=(const MutationObserverInit&); bool hasAttributeFilter() const { return has_attribute_filter_; } const Vector<String>& attributeFilter() const { DCHECK(has_attribute_filter_); return attribute_filter_; } void setAttributeFilter(const Vector<String>&); bool hasAttributeOldValue() const { return has_attribute_old_value_; } bool attributeOldValue() const { DCHECK(has_attribute_old_value_); return attribute_old_value_; } inline void setAttributeOldValue(bool); bool hasAttributes() const { return has_attributes_; } bool attributes() const { DCHECK(has_attributes_); return attributes_; } inline void setAttributes(bool); bool hasCharacterData() const { return has_character_data_; } bool characterData() const { DCHECK(has_character_data_); return character_data_; } inline void setCharacterData(bool); bool hasCharacterDataOldValue() const { return has_character_data_old_value_; } bool characterDataOldValue() const { DCHECK(has_character_data_old_value_); return character_data_old_value_; } inline void setCharacterDataOldValue(bool); bool hasChildList() const { return has_child_list_; } bool childList() const { DCHECK(has_child_list_); return child_list_; } inline void setChildList(bool); bool hasSubtree() const { return has_subtree_; } bool subtree() const { DCHECK(has_subtree_); return subtree_; } inline void setSubtree(bool); v8::Local<v8::Value> ToV8Impl(v8::Local<v8::Object>, v8::Isolate*) const override; void Trace(blink::Visitor*) override; private: bool has_attribute_filter_ = false; bool has_attribute_old_value_ = false; bool has_attributes_ = false; bool has_character_data_ = false; bool has_character_data_old_value_ = false; bool has_child_list_ = false; bool has_subtree_ = false; Vector<String> attribute_filter_; bool attribute_old_value_; bool attributes_; bool character_data_; bool character_data_old_value_; bool child_list_; bool subtree_; friend class V8MutationObserverInit; }; void MutationObserverInit::setAttributeOldValue(bool value) { attribute_old_value_ = value; has_attribute_old_value_ = true; } void MutationObserverInit::setAttributes(bool value) { attributes_ = value; has_attributes_ = true; } void MutationObserverInit::setCharacterData(bool value) { character_data_ = value; has_character_data_ = true; } void MutationObserverInit::setCharacterDataOldValue(bool value) { character_data_old_value_ = value; has_character_data_old_value_ = true; } void MutationObserverInit::setChildList(bool value) { child_list_ = value; has_child_list_ = true; } void MutationObserverInit::setSubtree(bool value) { subtree_ = value; has_subtree_ = true; } } // namespace blink #endif // MutationObserverInit_h
8059923fbbbc80f28542054ab88b42fd33768d7c
ae956d4076e4fc03b632a8c0e987e9ea5ca89f56
/SDK/TBP_ScoutingFamiliarPassive_functions.cpp
9cc22a5f9b92d69eb7b856212c133985279617ca
[]
no_license
BrownBison/Bloodhunt-BASE
5c79c00917fcd43c4e1932bee3b94e85c89b6bc7
8ae1104b748dd4b294609717142404066b6bc1e6
refs/heads/main
2023-08-07T12:04:49.234272
2021-10-02T15:13:42
2021-10-02T15:13:42
638,649,990
1
0
null
2023-05-09T20:02:24
2023-05-09T20:02:23
null
UTF-8
C++
false
false
6,278
cpp
// Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function: // Offset -> 0x016C0340 // Name -> Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.OnRep_Replicated Passive Activated // Flags -> (BlueprintCallable, BlueprintEvent) void UTBP_ScoutingFamiliarPassive_C::OnRep_Replicated_Passive_Activated() { static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.OnRep_Replicated Passive Activated"); UTBP_ScoutingFamiliarPassive_C_OnRep_Replicated_Passive_Activated_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function: // Offset -> 0x016C0340 // Name -> Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.CreateOrbitingParticles // Flags -> (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // class UParticleSystemComponent* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) class UParticleSystemComponent* UTBP_ScoutingFamiliarPassive_C::CreateOrbitingParticles() { static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.CreateOrbitingParticles"); UTBP_ScoutingFamiliarPassive_C_CreateOrbitingParticles_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function: // Offset -> 0x016C0340 // Name -> Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.ScoutSpawned // Flags -> (Event, Public, BlueprintEvent) // Parameters: // class ATigerFamiliarScout* SpawnedScout (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void UTBP_ScoutingFamiliarPassive_C::ScoutSpawned(class ATigerFamiliarScout* SpawnedScout) { static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.ScoutSpawned"); UTBP_ScoutingFamiliarPassive_C_ScoutSpawned_Params params; params.SpawnedScout = SpawnedScout; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function: // Offset -> 0x016C0340 // Name -> Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.Scout Destroyed // Flags -> (BlueprintCallable, BlueprintEvent) // Parameters: // class AActor* DestroyedActor (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void UTBP_ScoutingFamiliarPassive_C::Scout_Destroyed(class AActor* DestroyedActor) { static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.Scout Destroyed"); UTBP_ScoutingFamiliarPassive_C_Scout_Destroyed_Params params; params.DestroyedActor = DestroyedActor; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function: // Offset -> 0x016C0340 // Name -> Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.Begin Fade Out // Flags -> (BlueprintCallable, BlueprintEvent) void UTBP_ScoutingFamiliarPassive_C::Begin_Fade_Out() { static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.Begin Fade Out"); UTBP_ScoutingFamiliarPassive_C_Begin_Fade_Out_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function: // Offset -> 0x016C0340 // Name -> Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.Begin Fade In // Flags -> (BlueprintCallable, BlueprintEvent) void UTBP_ScoutingFamiliarPassive_C::Begin_Fade_In() { static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.Begin Fade In"); UTBP_ScoutingFamiliarPassive_C_Begin_Fade_In_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function: // Offset -> 0x016C0340 // Name -> Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.EvaluateVisibility // Flags -> (Event, Protected, BlueprintCallable, BlueprintEvent) void UTBP_ScoutingFamiliarPassive_C::EvaluateVisibility() { static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.EvaluateVisibility"); UTBP_ScoutingFamiliarPassive_C_EvaluateVisibility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function: // Offset -> 0x016C0340 // Name -> Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.ExecuteUbergraph_TBP_ScoutingFamiliarPassive // Flags -> (Final) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void UTBP_ScoutingFamiliarPassive_C::ExecuteUbergraph_TBP_ScoutingFamiliarPassive(int EntryPoint) { static UFunction* fn = UObject::FindObject<UFunction>("Function TBP_ScoutingFamiliarPassive.TBP_ScoutingFamiliarPassive_C.ExecuteUbergraph_TBP_ScoutingFamiliarPassive"); UTBP_ScoutingFamiliarPassive_C_ExecuteUbergraph_TBP_ScoutingFamiliarPassive_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
c9d74a2cd42189f0fce394a05f03e7d4e461b788
dff5780f161834db353ee91466d04c08cd6b2631
/Kojima_lib/Model.cpp
d4a7b2f05f49f540e5a5928587e6302fe9fe063c
[]
no_license
kojima04/Kojima_lib
bcfe4218f1ba67a0f785576718c60bd32627f671
de5e1aebb69c53366cf8f14b3aeabbbc2b2328ab
refs/heads/master
2016-09-02T22:03:19.871835
2015-09-08T03:56:48
2015-09-08T03:56:48
42,042,912
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,634
cpp
#include "Common.h" #include "Model.h" CModel::CModel() { m_pMesh = NULL; m_pMaterial = NULL; m_pTexture = NULL; m_NumMaterial = 0; SetScale(1,1,1); SetPos(0,0,0); SetRot(0,0,0); } CModel::~CModel() { Destroy(); } void CModel::Destroy() { if(m_pMesh) SAFE_RELEASE(m_pMesh); if(m_pTexture) SAFE_DELETEARRAY(m_pTexture); if(m_pMaterial) SAFE_DELETEARRAY(m_pMaterial); } bool CModel::LoadModelFromFile(std::string FileName) { LPD3DXBUFFER lpD3DBuf; if(FAILED(D3DXLoadMeshFromX( FileName.c_str(), //ファイル名 D3DXMESH_SYSTEMMEM, GetDevice(), NULL, &lpD3DBuf, NULL, &m_NumMaterial, //マテリアルの数 &m_pMesh))) //メッシュへのpp { return false; } //各種インスタンス取得 D3DXMATERIAL *d3dxMatrs = (D3DXMATERIAL *)lpD3DBuf->GetBufferPointer(); m_pTexture = new LPDIRECT3DTEXTURE9[m_NumMaterial]; m_pMaterial = new D3DMATERIAL9[m_NumMaterial]; if(m_pTexture == NULL || m_pMaterial == NULL) { SAFE_RELEASE(lpD3DBuf); return false; } for(DWORD i = 0; i < m_NumMaterial; ++i) { m_pMaterial[i] = d3dxMatrs[i].MatD3D; //材質のコピー m_pMaterial[i].Ambient = m_pMaterial[i].Diffuse; D3DXCreateTextureFromFile( GetDevice(), d3dxMatrs[i].pTextureFilename, (&m_pTexture[i])); } SAFE_RELEASE(lpD3DBuf); LPD3DXMESH pMesh = NULL; if(m_pMesh->GetFVF()!=(D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1)) { //メッシュに法線がない場合書き込む m_pMesh->CloneMeshFVF(m_pMesh->GetOptions(), D3DFVF_XYZ|D3DFVF_NORMAL|D3DFVF_TEX1, GetDevice(),&pMesh); SAFE_RELEASE(m_pMesh); m_pMesh = pMesh; } return true; } void CModel::Draw() { Transform(); m_stpD3DDevice->SetTransform(D3DTS_WORLD, &m_World); for(DWORD i = 0; i < m_NumMaterial; ++i) { GetDevice()->SetMaterial(&m_pMaterial[i]); GetDevice()->SetTexture(0, m_pTexture[i]); m_pMesh->DrawSubset(i); } } void CModel::SetpTexture(LPDIRECT3DTEXTURE9 tex) { m_pTexture[0] = tex; } HRESULT CModel::SetpTexturefromFile(int i,std::string FileName) { HRESULT hr = 0; // テクスチャ画像をファイルから読み込む hr = D3DXCreateTextureFromFileEx( (LPDIRECT3DDEVICE9)m_stpD3DDevice, FileName.c_str(), // ファイル名 0, 0, 0, 0, D3DFMT_A8B8G8R8, // 色抜きを可能に D3DPOOL_MANAGED, D3DX_FILTER_LINEAR, D3DX_FILTER_LINEAR, D3DCOLOR_ARGB(255, 0, 255, 255), NULL, NULL, &m_pTexture[i] // テクスチャ名 ); if( FAILED(hr)) { return E_FAIL; } return S_OK; }
98b87730e4e00b9b9b91e2d61bf8d2b62eda8f23
e34ee268547787a0d532a85edb6022f35a7ce84c
/CBase4618.h
85e74ac443983abb9557855a3e607b4614b72ad9
[]
no_license
Max1259/Raspberry-Pi-Serial-Communication
9b06d1e66aa484108959410fb9382a33a76149e1
b2c86aca3aeb5ec86bb6206925d875e1311a0caa
refs/heads/master
2020-05-02T16:05:03.434394
2019-03-27T19:19:08
2019-03-27T19:19:08
178,059,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
h
#pragma once //#include "stdafx.h" #include "CControlPi.h" // OpenCV Include #include <opencv2/opencv.hpp> // OpenCV Library //#pragma comment(lib,".\\opencv\\lib\\opencv_world310d.lib") /** * * @brief Base class for all ELEX4618 labs 4 - 9 * * This class is the parent class for CSketch and allows the Etch-a-sketch to run * * @author Max Horie * */ class CBase4618 { protected: CControlPi ctrl;///< CControl object to allow access to its functions cv::Mat _canvas;///< OpenCV Mat object to create an image float x, y;///< coordinates for the image public: /** * * @brief Virtual function update to allow CSketch to overload and use * * @param none * @return none * */ virtual void update() = 0; /** * * @brief Virtual function draw to allow CSketch to overload and use * * @param none * @return none * */ virtual void draw() = 0; /** * * @brief Allows the etch-a-sketch program to run * * @param none * @return none * */ void run(); };
682da3415d4187681255008875d4b310c5ead900
4f4ddc396fa1dfc874780895ca9b8ee4f7714222
/src/xtp/Source/Calendar/XTPCalendarOptions.h
ed5e9b131c03a82c4800c11819a05cd3947ae984
[]
no_license
UtsavChokshiCNU/GenSym-Test2
3214145186d032a6b5a7486003cef40787786ba0
a48c806df56297019cfcb22862dd64609fdd8711
refs/heads/master
2021-01-23T23:14:03.559378
2017-09-09T14:20:09
2017-09-09T14:20:09
102,960,203
3
5
null
null
null
null
UTF-8
C++
false
false
10,326
h
// XTPCalendarOptions.h: interface for the CXTPCalendarOptions class. // // This file is a part of the XTREME CALENDAR MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // [email protected] // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(_XTPCALENDAROPTIONS_H__) #define _XTPCALENDAROPTIONS_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CXTPCalendarData; class CXTPPropExchange; class CXTPCalendarFlagsSet_imp; class CXTPCalendarTimeZone; XTP_DEFINE_SMART_PTR_INTERNAL(CXTPCalendarTimeZone) //=========================================================================== // Summary: // Enumerates additional calendar options flags. //=========================================================================== enum XTPCalendarAdditionalOptions { xtpCalendarOptMonthViewShowStartTimeAlways = 0x00000001, // define option to always show event start time in the month view. xtpCalendarOptMonthViewShowEndTimeAlways = 0x00000002, // define option to always show event end time in the month view. xtpCalendarOptWeekViewShowStartTimeAlways = 0x00000004, // define option to always show event start time in the week view. xtpCalendarOptWeekViewShowEndTimeAlways = 0x00000008, // define option to always show event end time in the week view. xtpCalendarOptDayViewNoWordBreak = 0x00000010, // define option to draw event text without word break in the day view. xtpCalendarOptWorkWeekViewShowStartTimeAlways = 0x00000020, // define option to always show event start time in the work week view. xtpCalendarOptWorkWeekViewShowEndTimeAlways = 0x00000040, // define option to always show event end time in the work week view. xtpCalendarOptDayViewShowStartTimeAlways = 0x00000080, // define option to always show event start time in the day view. xtpCalendarOptDayViewShowEndTimeAlways = 0x00000100 // define option to always show event end time in the day view. }; //=========================================================================== // Summary: // Structure contains all calendar options. // Remarks: // This structure contains all options which could be changed by the // user for CXTPCalendarControl. // See Also: CXTPCalendarControl, XTPCalendarWeekDay, XTPCalendarWeekDay //=========================================================================== class _XTP_EXT_CLASS CXTPCalendarOptions : public CXTPCmdTarget { //{{AFX_CODEJOCK_PRIVATE DECLARE_DYNAMIC(CXTPCalendarOptions) //}}AFX_CODEJOCK_PRIVATE public: //----------------------------------------------------------------------- // Summary: // Default object constructor. //----------------------------------------------------------------------- CXTPCalendarOptions(); //----------------------------------------------------------------------- // Summary: // Default Destructor. // Remarks: // Handles all deallocation. //----------------------------------------------------------------------- virtual ~CXTPCalendarOptions(); public: //----------------------------------------------------------------------- // Summary: // This method reads or writes data from or to an storage. // Parameters: // pPX - A CXTPPropExchange object to serialize to or from. // Remarks: // For the save case the options data from will be saved to archive. // For the load a new data will be loaded from the specified // archive and set to members. // See Also: // CXTPPropExchange //----------------------------------------------------------------------- void DoPropExchange(CXTPPropExchange* pPX); //----------------------------------------------------------------------- // Summary: // Get full information about current time zone. // Remarks: // Retrieve additional information from the registry. // Returns: // A smart pointer to CXTPCalendarTimeZone object. // See Also: // GetTimeZoneInformation(), CXTPCalendarTimeZone::GetTimeZoneInfo() //----------------------------------------------------------------------- CXTPCalendarTimeZonePtr GetCurrentTimeZoneInfo(); //----------------------------------------------------------------------- // Summary: // This member function is called when option was changed. //----------------------------------------------------------------------- void OnOptionsChanged(); ///////////////////////////////////////////////////////////////////////// // data provider related //----------------------------------------------------------------------- // Summary: // This member function sets the custom data provider for the control. // Parameters: // pDataProvider - Pointer to the custom data provider object. // lpszConnectionString - String containing the name and type of the data provider. // Remarks: // Call this member function to set the custom data provider // that is currently used by this calendar control. Note that // custom data provider must be a descendant of CXTPCalendarData. // See Also: CXTPCalendarData overview, GetDataProvider //----------------------------------------------------------------------- void SetDataProvider(CXTPCalendarData* pDataProvider); public: //## Calendar work week int nWorkWeekMask; // This structure member represents week working days using XTPCalendarWeekDay enumeration. // Each day is represented by the corresponding binary bit. int nFirstDayOfTheWeek; // This member shows the first day of the week using XTPCalendarWeekDay enum. COleDateTime dtWorkDayStartTime; // This member contains work day start time. COleDateTime dtWorkDayEndTime; // This member contains work day end time. COleDateTime dtScaleMinTime; //The scale minimum time. COleDateTime dtScaleMaxTime; //The scale maximum time. BOOL bEnableInPlaceEditEventSubject_ByF2; // Set TRUE to enable in-place edit event subject by F2, FALSE otherwise. BOOL bEnableInPlaceEditEventSubject_ByMouseClick; // Set TRUE to enable in-place edit event subject by Mouse Click, FALSE otherwise. BOOL bEnableInPlaceEditEventSubject_ByTab; // Set TRUE to enable in-place edit event subject by TAB, FALSE otherwise. BOOL bEnableInPlaceEditEventSubject_AfterEventResize;// Set TRUE to enable in-place edit event subject after event resize, FALSE otherwise. BOOL bEnableInPlaceCreateEvent; // Set TRUE to enable in-place event creation, FALSE otherwise. BOOL bUseOutlookFontGlyphs; // Set TRUE to use 'MS Outlook' font to display Glyps, otherwise bitmaps are used. //## Day View BOOL bDayView_AutoResetBusyFlag; // If TRUE - 'Busy' event status will be automatically set to 'Free' when moving event from hours area to all day events area and vice versa. If FALSE - status flag is not changed automatically. int nDayView_ScaleInterval; // DayView scale interval in minutes. CString strDayView_ScaleLabel; // Stores main time scale label (day view) CString strDayView_Scale2Label; // Stores secondary time scale label (day view) BOOL bDayView_Scale2Visible; // TRUE when secondary time scale is visible in day view, FALSE otherwise. TIME_ZONE_INFORMATION tziDayView_Scale2TimeZone; // Stores time zone information for the secondary time scale. int nDayView_CurrentTimeMarkVisible; // A set of flags which define when Current Time Mark on the timescale is visible. See Also XTPCalendarCurrentTimeMarkFlags. By default it is xtpCalendarCurrentTimeMarkVisibleForToday. BOOL bDayView_TimeScaleShowMinutes; // If TRUE - minutes will be shown on time scale. FALSE by default. BOOL bShowAllDayExpandButton; // TRUE to show all day header expand buttons when needed //## Month View BOOL bMonthView_CompressWeekendDays;// TRUE when compressing weekend days in month view, FALSE otherwise. BOOL bMonthView_ShowEndDate; // TRUE when showing event end date in month view, FALSE otherwise. BOOL bMonthView_ShowTimeAsClocks; // TRUE when showing event time as graphical clocks in month view, FALSE otherwise. BOOL bMonthView_HideTimes; // TRUE to suppress drawing time in month view event, FALSE otherwise //## Week View BOOL bWeekView_ShowEndDate; // TRUE when showing event end date in week view, FALSE otherwise. BOOL bWeekView_ShowTimeAsClocks; // TRUE when showing event time as graphical clocks in week view, FALSE otherwise. //## TimeLine View BOOL bTimeLineCompact; // TRUE when showing event compatized // or not (like Entry List in Outlook) //## Common DWORD dwAdditionalOptions; // Additional calendar options. BOOL bHatchAllDayViewEventsBkgnd; // flag to enable\disable all day events cell background color fill or hatch BOOL bShowCategoryIcons; // flag to show\hide additional categories icons in event view for day\multicolumn week views //## "Add new appointment" tooltip BOOL bEnableAddNewTooltip; // TRUE when "add new appointment" tooltips appears, FALSE otherwise CString strTooltipAddNewText; // Text for "add new appointment" tooltip. Default is: "Click to add appointment" //## Office2007 Theme only BOOL bEnablePrevNextEventButtons; // TRUE when "Prev/Next Appointment" buttons are enabled, FALSE otherwise protected: CXTPCalendarData* m_pDataProvider; // A stored pointer to the owner data provider. }; #endif // !defined(_XTPCALENDAROPTIONS_H__)
b3f13409d912840474f46167ebf6a126a32d16f5
d25ea941bc633c7d66641acf41502f6a4f71f627
/4.MFC/ImgLib/ImgLib.h
a3b3f190dd572cd1b53f215425d2670a98e91691
[]
no_license
shepherd44/bitstudy
eb95b5c330897df4c09e7532e2fc5c8061053720
960b562436cb4586ab76450a01485d9a64fc892c
refs/heads/master
2016-09-06T09:05:32.108636
2015-06-09T10:35:59
2015-06-09T10:35:59
34,652,780
0
0
null
2015-04-30T07:59:03
2015-04-27T07:42:32
C++
UHC
C++
false
false
703
h
// ImgLib.h : ImgLib 응용 프로그램에 대한 주 헤더 파일 // #pragma once #ifndef __AFXWIN_H__ #error "PCH에 대해 이 파일을 포함하기 전에 'stdafx.h'를 포함합니다." #endif #include "resource.h" // 주 기호입니다. // CImgLibApp: // 이 클래스의 구현에 대해서는 ImgLib.cpp을 참조하십시오. // class CImgLibApp : public CWinAppEx { public: CImgLibApp(); // 재정의입니다. public: virtual BOOL InitInstance(); // 구현입니다. BOOL m_bHiColorIcons; virtual void PreLoadState(); virtual void LoadCustomState(); virtual void SaveCustomState(); afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() }; extern CImgLibApp theApp;
43b0a5ac670b3ddb44b220c158a8354004c0ea57
d0241a42eefde13949b01f2348ade57b0e40e340
/Constrained_Particle_System/glme.cpp
65a751084957fd6d258eabc6306706254a3fa5ba
[ "BSD-3-Clause" ]
permissive
vishaknag/Simulation-constrainedParticleSystem
edfba02616507502749c1b8e724177926ee93e36
2ea5c367edda0a38e11917c358c80d6aa416bafd
refs/heads/master
2021-01-10T01:00:10.599747
2013-02-18T01:57:45
2013-02-18T01:57:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
101,676
cpp
#include "render.h" #define T(x) (model->triangles[(x)]) int memoryAllocationMode = GLM_TIGHT; int maxNumVertices; int maxNumTriangles; int maxNumNormals; int maxNumTexCoords; static char * glmDuplicateString(char * s) { // strdup sometimes causes problems, so we use this char * p = (char*) malloc (sizeof(char) * (strlen(s) + 1)); memcpy(p, s, sizeof(char) * (strlen(s) + 1)); return p; } /* glmMax: returns the maximum of two floats */ static GLfloat glmMax(GLfloat a, GLfloat b) { if (b > a) return b; return a; } /* glmAbs: returns the absolute value of a float */ static GLfloat glmAbs(GLfloat f) { if (f < 0) return -f; return f; } /* glmCross: compute the cross product of two vectors * * u - array of 3 GLfloats (GLfloat u[3]) * v - array of 3 GLfloats (GLfloat v[3]) * n - array of 3 GLfloats (GLfloat n[3]) to return the cross product in */ static GLvoid glmCross(GLfloat* u, GLfloat* v, GLfloat* n) { assert(u); assert(v); assert(n); n[0] = u[1]*v[2] - u[2]*v[1]; n[1] = u[2]*v[0] - u[0]*v[2]; n[2] = u[0]*v[1] - u[1]*v[0]; } /* glmEqual: compares two vectors and returns GL_TRUE if they are * equal (within a certain threshold) or GL_FALSE if not. An epsilon * that works fairly well is 0.000001. * * u - array of 3 GLfloats (GLfloat u[3]) * v - array of 3 GLfloats (GLfloat v[3]) */ static GLboolean glmEqual(GLfloat* u, GLfloat* v, GLfloat epsilon) { if (glmAbs(u[0] - v[0]) < epsilon && glmAbs(u[1] - v[1]) < epsilon && glmAbs(u[2] - v[2]) < epsilon) { return GL_TRUE; } return GL_FALSE; } /* glmWeldVectors: eliminate (weld) vectors that are within an * epsilon of each other. * * vectors - array of GLfloat[3]'s to be welded * numvectors - number of GLfloat[3]'s in vectors * epsilon - maximum difference between vectors * */ GLfloat* glmWeldVectors(GLfloat* vectors, GLuint* numvectors, GLfloat epsilon) { GLfloat* copies; GLuint copied; GLuint i, j; copies = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (*numvectors + 1)); memcpy(copies, vectors, (sizeof(GLfloat) * 3 * (*numvectors + 1))); copied = 1; for (i = 1; i <= *numvectors; i++) { for (j = 1; j <= copied; j++) { if (glmEqual(&vectors[3 * i], &copies[3 * j], epsilon)) { goto duplicate; } } /* must not be any duplicates -- add to the copies array */ copies[3 * copied + 0] = vectors[3 * i + 0]; copies[3 * copied + 1] = vectors[3 * i + 1]; copies[3 * copied + 2] = vectors[3 * i + 2]; j = copied; /* pass this along for below */ copied++; duplicate: /* set the first component of this vector to point at the correct index into the new copies array */ vectors[3 * i + 0] = (GLfloat)j; } *numvectors = copied-1; return copies; } void glmPrintGroupInfo(GLMmodel * model) { GLMgroup * group; assert(model); group = model->groups; int groupCounter = 0; while(group) { printf("=== Group %d ===\n", groupCounter); printf(" Name: %s\n", group->name); printf(" Num triangles: %d\n", group->numtriangles); printf(" Num edges: %d\n", group->numEdges); printf(" Triangle pointer: %p\n", group->triangles); printf(" Edge pointer: %p\n", group->edges); printf(" Next group pointer: %p\n", group->next); printf(" Material index: %d\n", group->material); printf(" Material name: %s\n", model->materials[group->material].name); group = group->next; groupCounter++; } printf("Total num groups: %d\n", groupCounter); } /* glmFindGroup: Find a group in the model */ GLMgroup* glmFindGroup(GLMmodel* model, char* name) { GLMgroup* group; assert(model); group = model->groups; while(group) { if (!strcmp(name, group->name)) break; group = group->next; } return group; } /* glmAddGroup: Add a group to the model */ GLMgroup* glmAddGroup(GLMmodel* model, char* name) { GLMgroup* group; group = glmFindGroup(model, name); if (!group) { group = (GLMgroup*)malloc(sizeof(GLMgroup)); group->name = glmDuplicateString(name); group->material = 0; group->numtriangles = 0; group->triangles = NULL; group->numEdges = 0; group->edges = NULL; group->next = model->groups; model->groups = group; model->numgroups++; } return group; } /* glmFindGroup: Find a material in the model */ GLuint glmFindMaterial(GLMmodel* model, char* name) { GLuint i; /* doing a linear search on a string key'd list is pretty lame, but it works and is fast enough for now. */ for (i = 0; i < model->nummaterials; i++) { if (!strcmp(model->materials[i].name, name)) goto found; } /* didn't find the name, so print a warning and return the default material (0). */ printf("glmFindMaterial(): can't find material \"%s\".\n", name); i = 0; found: return i; } /* glmDirName: return the directory given a path * * path - filesystem path * * NOTE: the return value should be free'd. */ static char* glmDirName(char* path) { char * lastSeparator = NULL; char * ch = path; int counter=0; int lastSeparatorPos = 0; while (*ch != '\0') { if ((*ch == '\\') || (*ch == '/')) { lastSeparator = ch; lastSeparatorPos = counter; } ch++; counter++; } char * dir; if (lastSeparator != NULL) { dir = (char*) malloc (sizeof(char) * (lastSeparatorPos+1)); dir[lastSeparatorPos] = '\0'; strncpy(dir,path,sizeof(char)*lastSeparatorPos); } else { dir = (char*) malloc (sizeof(char) * 2); strcpy(dir,"."); } return dir; } GLvoid glmDeleteMaterials(GLMmodel * model) { for(unsigned int i=0; i<model->nummaterials; i++) { free(model->materials[i].name); free(model->materials[i].textureFile); free(model->materials[i].textureData); } free(model->materials); } GLvoid glmSetMaterialAlpha(GLMmodel * model, double alpha) { for (unsigned int i = 0; i < model->nummaterials; i++) { model->materials[i].diffuse[3] = alpha; model->materials[i].ambient[3] = alpha; model->materials[i].specular[3] = alpha; } } GLvoid glmMakeDefaultMaterials(GLMmodel * model, int numDefaultMaterials) { if (model->materials) glmDeleteMaterials(model); model->materials = (GLMmaterial*)malloc(sizeof(GLMmaterial) * numDefaultMaterials); model->nummaterials = numDefaultMaterials; // set the default materials for (int i = 0; i < numDefaultMaterials; i++) { model->materials[i].name = NULL; model->materials[i].shininess = 65.0; model->materials[i].diffuse[0] = 0.6; model->materials[i].diffuse[1] = 0.6; model->materials[i].diffuse[2] = 0.6; model->materials[i].diffuse[3] = 1.0; model->materials[i].ambient[0] = 0.2; model->materials[i].ambient[1] = 0.2; model->materials[i].ambient[2] = 0.2; model->materials[i].ambient[3] = 1.0; model->materials[i].specular[0] = 0.0; model->materials[i].specular[1] = 0.0; model->materials[i].specular[2] = 0.0; model->materials[i].specular[3] = 1.0; model->materials[i].textureFile = NULL; model->materials[i].textureData = NULL; model->materials[i].name = (char*) malloc (sizeof(char) * 8); strcpy(model->materials[i].name, "default"); } } /* glmReadMTL: read a wavefront material library file * * model - properly initialized GLMmodel structure * name - name of the material library */ static GLvoid glmReadMTL(GLMmodel* model, char* name) { FILE* file; char* dir; char* filename; char buf[1024]; char buf2[1024]; char buf3[1024]; GLuint nummaterials; dir = glmDirName(model->pathname); filename = (char*)malloc(sizeof(char) * (strlen(dir) + strlen(name) + 2)); strcpy(filename, dir); strcat(filename, "/"); strcat(filename, name); free(dir); file = fopen(filename, "r"); if (!file) { fprintf(stderr, "glmReadMTL() failed: can't open material file %s.\n", filename); exit(1); } free(filename); /* count the number of materials in the file */ nummaterials = 1; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'n': /* newmtl */ fgets(buf, sizeof(buf), file); nummaterials++; sscanf(buf, "%s %s", buf2, buf3); break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } } rewind(file); glmMakeDefaultMaterials(model,nummaterials); /* now, read in the data */ nummaterials = 0; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'n': /* newmtl */ fscanf(file, "%s", buf2); nummaterials++; free(model->materials[nummaterials].name); model->materials[nummaterials].name = glmDuplicateString(buf2); fgets(buf, sizeof(buf), file); break; case 'N': if (buf[1] == 's') { fscanf(file, "%f", &model->materials[nummaterials].shininess); // wavefront shininess is from [0, 1000], so scale for OpenGL model->materials[nummaterials].shininess *= 128.0 / 1000.0; } else fgets(buf, sizeof(buf), file); //eat rest of line break; case 'K': switch(buf[1]) { case 'd': fscanf(file, "%f %f %f", &model->materials[nummaterials].diffuse[0], &model->materials[nummaterials].diffuse[1], &model->materials[nummaterials].diffuse[2]); break; case 's': fscanf(file, "%f %f %f", &model->materials[nummaterials].specular[0], &model->materials[nummaterials].specular[1], &model->materials[nummaterials].specular[2]); break; case 'a': fscanf(file, "%f %f %f", &model->materials[nummaterials].ambient[0], &model->materials[nummaterials].ambient[1], &model->materials[nummaterials].ambient[2]); break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } break; case 'm': // texture file, allow only one texture file, has to be ppm format // different materials can have different textures // however, each single material can have only one texture // if texture file not already assigned it, assign it, // and then load the texture file into main memory and assign texture name to it fgets(buf, sizeof(buf), file); sscanf(buf, "%s %s", buf, buf); free(model->materials[nummaterials].textureFile); model->materials[nummaterials].textureFile = glmDuplicateString(buf); break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } } } /* glmWriteMTL: write a wavefront material library file * * model - properly initialized GLMmodel structure * modelpath - pathname of the model being written * mtllibname - name of the material library to be written */ static GLvoid glmWriteMTL(GLMmodel* model, char* modelpath, char* mtllibname) { FILE* file; char* dir; char* filename; GLMmaterial* material; GLuint i; dir = glmDirName(modelpath); filename = (char*)malloc(sizeof(char) * (strlen(dir)+strlen(mtllibname))); strcpy(filename, dir); strcat(filename, "/"); strcat(filename, mtllibname); free(dir); /* open the file */ file = fopen(filename, "w"); if (!file) { fprintf(stderr, "glmWriteMTL() failed: can't open file \"%s\".\n", filename); exit(1); } free(filename); /* spit out a header */ fprintf(file, "# \n"); fprintf(file, "# Wavefront MTL generated by GLM library\n"); fprintf(file, "# \n"); fprintf(file, "# GLM library\n"); fprintf(file, "# Nate Robins\n"); fprintf(file, "# [email protected]\n"); fprintf(file, "# http://www.pobox.com/~ndr\n"); fprintf(file, "# \n\n"); for (i = 0; i < model->nummaterials; i++) { material = &model->materials[i]; fprintf(file, "newmtl %s\n", material->name); fprintf(file, "Ka %f %f %f\n", material->ambient[0], material->ambient[1], material->ambient[2]); fprintf(file, "Kd %f %f %f\n", material->diffuse[0], material->diffuse[1], material->diffuse[2]); fprintf(file, "Ks %f %f %f\n", material->specular[0],material->specular[1],material->specular[2]); fprintf(file, "Ns %f\n", material->shininess / 128.0 * 1000.0); fprintf(file, "\n"); } } /* glmFirstPass: first pass at a Wavefront OBJ file that gets all the * statistics of the model (such as #vertices, #normals, etc) * * model - properly initialized GLMmodel structure * file - (fopen'd) file descriptor * directory - the directory where the obj file resides (necessary to open the material file) */ static GLvoid glmFirstPass(GLMmodel* model, FILE* file) { GLuint numvertices; /* number of vertices in model */ GLuint numnormals; /* number of normals in model */ GLuint numtexcoords; /* number of texcoords in model */ GLuint numtriangles; /* number of triangles in model */ GLMgroup* group; /* current group */ unsigned v, n, t; char buf[128]; /* make a default group */ group = glmAddGroup(model, "default"); numvertices = numnormals = numtexcoords = numtriangles = 0; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'v': /* v, vn, vt */ switch(buf[1]) { case '\0': /* vertex */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); numvertices++; break; case 'n': /* normal */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); numnormals++; break; case 't': /* texcoord */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); numtexcoords++; break; default: printf("glmFirstPass(): Unknown token \"%s\".\n", buf); exit(1); break; } break; case 'm': fgets(buf, sizeof(buf), file); sscanf(buf, "%s %s", buf, buf); model->mtllibname = glmDuplicateString(buf); glmReadMTL(model, model->mtllibname); break; case 'u': /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'g': /* group */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); #if SINGLE_STRING_GROUP_NAMES sscanf(buf, "%s", buf); #else buf[strlen(buf)-1] = '\0'; /* nuke '\n' */ #endif group = glmAddGroup(model, buf); break; case 'f': /* face */ v = n = t = 0; fscanf(file, "%s", buf); /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */ if (strstr(buf, "//")) { /* v//n */ sscanf(buf, "%d//%d", &v, &n); fscanf(file, "%d//%d", &v, &n); fscanf(file, "%d//%d", &v, &n); numtriangles++; group->numtriangles++; group->numEdges += 3; while(fscanf(file, "%d//%d", &v, &n) > 0) { numtriangles++; group->numtriangles++; group->numEdges++; } } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) { /* v/t/n */ fscanf(file, "%d/%d/%d", &v, &t, &n); fscanf(file, "%d/%d/%d", &v, &t, &n); numtriangles++; group->numtriangles++; group->numEdges += 3; while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { numtriangles++; group->numtriangles++; group->numEdges++; } } else if (sscanf(buf, "%d/%d", &v, &t) == 2) { /* v/t */ fscanf(file, "%d/%d", &v, &t); fscanf(file, "%d/%d", &v, &t); numtriangles++; group->numtriangles++; group->numEdges += 3; while(fscanf(file, "%d/%d", &v, &t) > 0) { numtriangles++; group->numtriangles++; group->numEdges++; } } else { /* v */ fscanf(file, "%d", &v); fscanf(file, "%d", &v); numtriangles++; group->numtriangles++; group->numEdges += 3; while(fscanf(file, "%d", &v) > 0) { numtriangles++; group->numtriangles++; group->numEdges++; } } break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } } /* set the stats in the model structure */ model->numvertices = numvertices; model->numnormals = numnormals; model->numtexcoords = numtexcoords; model->numtriangles = numtriangles; } // internal routine: adds the edges corresponding to the given fan of triangles void AddEdges(GLMmodel * model, GLMgroup * group, int startFanTriangles, int endFanTriangle) { // add first two edges group->edges[2*group->numEdges+0] = T(startFanTriangles).vindices[0]; group->edges[2*group->numEdges+1] = T(startFanTriangles).vindices[1]; group->numEdges++; group->edges[2*group->numEdges+0] = T(startFanTriangles).vindices[1]; group->edges[2*group->numEdges+1] = T(startFanTriangles).vindices[2]; group->numEdges++; // add edges in the middle for(int tri=startFanTriangles+1; tri <= endFanTriangle; tri++) { group->edges[2*group->numEdges+0] = T(tri).vindices[1]; group->edges[2*group->numEdges+1] = T(tri).vindices[2]; group->numEdges++; } // link last point to first point group->edges[2*group->numEdges+0] = T(endFanTriangle).vindices[2]; group->edges[2*group->numEdges+1] = T(startFanTriangles).vindices[0]; group->numEdges++; } /* glmSecondPass: second pass at a Wavefront OBJ file that gets all * the data. * * model - properly initialized GLMmodel structure * file - (fopen'd) file descriptor */ static GLvoid glmSecondPass(GLMmodel* model, FILE* file) { GLuint numvertices; /* number of vertices in model */ GLuint numnormals; /* number of normals in model */ GLuint numtexcoords; /* number of texcoords in model */ GLuint numtriangles; /* number of triangles in model */ GLfloat* vertices; /* array of vertices */ GLfloat* normals; /* array of normals */ GLfloat* texcoords; /* array of texture coordinates */ GLMgroup* group; /* current group pointer */ GLuint material; /* current material */ GLuint v, n, t; char buf[128]; /* set the pointer shortcuts */ vertices = model->vertices; normals = model->normals; texcoords = model->texcoords; group = model->groups; int startTriangle; // for edges /* on the second pass through the file, read all the data into the allocated arrays */ numvertices = numnormals = numtexcoords = 1; numtriangles = 0; material = 0; while(fscanf(file, "%s", buf) != EOF) { switch(buf[0]) { case '#': /* comment */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; case 'v': /* v, vn, vt */ switch(buf[1]) { case '\0': /* vertex */ fscanf(file, "%f %f %f", &vertices[3 * numvertices + 0], &vertices[3 * numvertices + 1], &vertices[3 * numvertices + 2]); numvertices++; break; case 'n': /* normal */ fscanf(file, "%f %f %f", &normals[3 * numnormals + 0], &normals[3 * numnormals + 1], &normals[3 * numnormals + 2]); numnormals++; break; case 't': /* texcoord */ fscanf(file, "%f %f", &texcoords[2 * numtexcoords + 0], &texcoords[2 * numtexcoords + 1]); numtexcoords++; break; } break; case 'u': fgets(buf, sizeof(buf), file); sscanf(buf, "%s %s", buf, buf); group->material = material = glmFindMaterial(model, buf); break; case 'g': /* group */ /* eat up rest of line */ fgets(buf, sizeof(buf), file); #if SINGLE_STRING_GROUP_NAMES sscanf(buf, "%s", buf); #else buf[strlen(buf)-1] = '\0'; /* nuke '\n' */ #endif group = glmFindGroup(model, buf); group->material = material; break; case 'f': /* face */ v = n = t = 0; startTriangle = numtriangles; fscanf(file, "%s", buf); /* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */ if (strstr(buf, "//")) { /* v//n */ sscanf(buf, "%d//%d", &v, &n); T(numtriangles).vindices[0] = v; T(numtriangles).nindices[0] = n; fscanf(file, "%d//%d", &v, &n); T(numtriangles).vindices[1] = v; T(numtriangles).nindices[1] = n; fscanf(file, "%d//%d", &v, &n); T(numtriangles).vindices[2] = v; T(numtriangles).nindices[2] = n; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; while(fscanf(file, "%d//%d", &v, &n) > 0) { // tesselating the polygon on the fly T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0]; T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2]; T(numtriangles).vindices[2] = v; T(numtriangles).nindices[2] = n; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; } AddEdges(model, group, startTriangle, numtriangles-1); } else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3) { /* v/t/n */ T(numtriangles).vindices[0] = v; T(numtriangles).tindices[0] = t; T(numtriangles).nindices[0] = n; fscanf(file, "%d/%d/%d", &v, &t, &n); T(numtriangles).vindices[1] = v; T(numtriangles).tindices[1] = t; T(numtriangles).nindices[1] = n; fscanf(file, "%d/%d/%d", &v, &t, &n); T(numtriangles).vindices[2] = v; T(numtriangles).tindices[2] = t; T(numtriangles).nindices[2] = n; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0]; T(numtriangles).nindices[0] = T(numtriangles-1).nindices[0]; T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2]; T(numtriangles).nindices[1] = T(numtriangles-1).nindices[2]; T(numtriangles).vindices[2] = v; T(numtriangles).tindices[2] = t; T(numtriangles).nindices[2] = n; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; } AddEdges(model, group, startTriangle, numtriangles-1); } else if (sscanf(buf, "%d/%d", &v, &t) == 2) { /* v/t */ T(numtriangles).vindices[0] = v; T(numtriangles).tindices[0] = t; fscanf(file, "%d/%d", &v, &t); T(numtriangles).vindices[1] = v; T(numtriangles).tindices[1] = t; fscanf(file, "%d/%d", &v, &t); T(numtriangles).vindices[2] = v; T(numtriangles).tindices[2] = t; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; while(fscanf(file, "%d/%d", &v, &t) > 0) { T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; T(numtriangles).tindices[0] = T(numtriangles-1).tindices[0]; T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; T(numtriangles).tindices[1] = T(numtriangles-1).tindices[2]; T(numtriangles).vindices[2] = v; T(numtriangles).tindices[2] = t; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; } AddEdges(model, group, startTriangle, numtriangles-1); } else { /* v */ sscanf(buf, "%d", &v); T(numtriangles).vindices[0] = v; fscanf(file, "%d", &v); T(numtriangles).vindices[1] = v; fscanf(file, "%d", &v); T(numtriangles).vindices[2] = v; group->triangles[group->numtriangles++] = numtriangles; // link the new triangle to the group numtriangles++; while(fscanf(file, "%d", &v) > 0) { T(numtriangles).vindices[0] = T(numtriangles-1).vindices[0]; T(numtriangles).vindices[1] = T(numtriangles-1).vindices[2]; T(numtriangles).vindices[2] = v; group->triangles[group->numtriangles++] = numtriangles; numtriangles++; } AddEdges(model, group, startTriangle, numtriangles-1); } break; default: /* eat up rest of line */ fgets(buf, sizeof(buf), file); break; } } #if 0 /* announce the memory requirements */ printf(" Memory: %d bytes\n", numvertices * 3*sizeof(GLfloat) + numnormals * 3*sizeof(GLfloat) * (numnormals ? 1 : 0) + numtexcoords * 3*sizeof(GLfloat) * (numtexcoords ? 1 : 0) + numtriangles * sizeof(GLMtriangle)); #endif } /* public functions */ /* glmUnitize: "unitize" a model by translating it to the origin and * scaling it to fit in a unit cube around the origin. Returns the * scalefactor used. * * model - properly initialized GLMmodel structure */ GLfloat glmUnitize(GLMmodel* model) { GLuint i; GLfloat maxx, minx, maxy, miny, maxz, minz; GLfloat cx, cy, cz, w, h, d; GLfloat scale; assert(model); assert(model->vertices); /* get the max/mins */ maxx = minx = model->vertices[3 + 0]; maxy = miny = model->vertices[3 + 1]; maxz = minz = model->vertices[3 + 2]; for (i = 1; i <= model->numvertices; i++) { if (maxx < model->vertices[3 * i + 0]) maxx = model->vertices[3 * i + 0]; if (minx > model->vertices[3 * i + 0]) minx = model->vertices[3 * i + 0]; if (maxy < model->vertices[3 * i + 1]) maxy = model->vertices[3 * i + 1]; if (miny > model->vertices[3 * i + 1]) miny = model->vertices[3 * i + 1]; if (maxz < model->vertices[3 * i + 2]) maxz = model->vertices[3 * i + 2]; if (minz > model->vertices[3 * i + 2]) minz = model->vertices[3 * i + 2]; } /* calculate model width, height, and depth */ w = glmAbs(maxx) + glmAbs(minx); h = glmAbs(maxy) + glmAbs(miny); d = glmAbs(maxz) + glmAbs(minz); /* calculate center of the model */ cx = (maxx + minx) / 2.0; cy = (maxy + miny) / 2.0; cz = (maxz + minz) / 2.0; /* calculate unitizing scale factor */ scale = 2.0 / glmMax(glmMax(w, h), d); /* translate around center then scale */ for (i = 1; i <= model->numvertices; i++) { model->vertices[3 * i + 0] -= cx; model->vertices[3 * i + 1] -= cy; model->vertices[3 * i + 2] -= cz; model->vertices[3 * i + 0] *= scale; model->vertices[3 * i + 1] *= scale; model->vertices[3 * i + 2] *= scale; } return scale; } /* glmDimensions: Calculates the dimensions (width, height, depth) of * a model. * * model - initialized GLMmodel structure * dimensions - array of 3 GLfloats (GLfloat dimensions[3]) */ GLvoid glmDimensions(GLMmodel* model, GLfloat* dimensions) { GLuint i; GLfloat maxx, minx, maxy, miny, maxz, minz; assert(model); assert(model->vertices); assert(dimensions); /* get the max/mins */ maxx = minx = model->vertices[3 + 0]; maxy = miny = model->vertices[3 + 1]; maxz = minz = model->vertices[3 + 2]; for (i = 1; i <= model->numvertices; i++) { if (maxx < model->vertices[3 * i + 0]) maxx = model->vertices[3 * i + 0]; if (minx > model->vertices[3 * i + 0]) minx = model->vertices[3 * i + 0]; if (maxy < model->vertices[3 * i + 1]) maxy = model->vertices[3 * i + 1]; if (miny > model->vertices[3 * i + 1]) miny = model->vertices[3 * i + 1]; if (maxz < model->vertices[3 * i + 2]) maxz = model->vertices[3 * i + 2]; if (minz > model->vertices[3 * i + 2]) minz = model->vertices[3 * i + 2]; } /* calculate model width, height, and depth */ dimensions[0] = glmAbs(maxx) + glmAbs(minx); dimensions[1] = glmAbs(maxy) + glmAbs(miny); dimensions[2] = glmAbs(maxz) + glmAbs(minz); } /* glmScale: Scales a model by a given amount. * * model - properly initialized GLMmodel structure * scale - scalefactor (0.5 = half as large, 2.0 = twice as large) */ GLvoid glmScale(GLMmodel* model, GLfloat scale) { GLuint i; for (i = 1; i <= model->numvertices; i++) { model->vertices[3 * i + 0] *= scale; model->vertices[3 * i + 1] *= scale; model->vertices[3 * i + 2] *= scale; } } /* glmReverseWinding: Reverse the polygon winding for all polygons in * this model. Default winding is counter-clockwise. Also changes * the direction of the normals. * * model - properly initialized GLMmodel structure */ GLvoid glmReverseWinding(GLMmodel* model) { GLuint i, swap; assert(model); for (i = 0; i < model->numtriangles; i++) { swap = T(i).vindices[0]; T(i).vindices[0] = T(i).vindices[2]; T(i).vindices[2] = swap; if (model->numnormals) { swap = T(i).nindices[0]; T(i).nindices[0] = T(i).nindices[2]; T(i).nindices[2] = swap; } if (model->numtexcoords) { swap = T(i).tindices[0]; T(i).tindices[0] = T(i).tindices[2]; T(i).tindices[2] = swap; } } /* reverse facet normals */ for (i = 1; i <= model->numfacetnorms; i++) { model->facetnorms[3 * i + 0] = -model->facetnorms[3 * i + 0]; model->facetnorms[3 * i + 1] = -model->facetnorms[3 * i + 1]; model->facetnorms[3 * i + 2] = -model->facetnorms[3 * i + 2]; } /* reverse vertex normals */ for (i = 1; i <= model->numnormals; i++) { model->normals[3 * i + 0] = -model->normals[3 * i + 0]; model->normals[3 * i + 1] = -model->normals[3 * i + 1]; model->normals[3 * i + 2] = -model->normals[3 * i + 2]; } } /* glmFacetNormals: Generates facet normals for a model (by taking the * cross product of the two vectors derived from the sides of each * triangle). Assumes a counter-clockwise winding. * * model - initialized GLMmodel structure */ GLvoid glmFacetNormals(GLMmodel* model) { GLuint i; GLfloat u[3]; GLfloat v[3]; assert(model); assert(model->vertices); /* clobber any old facetnormals */ if (model->facetnorms) free(model->facetnorms); /* allocate memory for the new facet normals */ model->numfacetnorms = model->numtriangles; model->facetnorms = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numfacetnorms + 1)); for (i = 0; i < model->numtriangles; i++) { model->triangles[i].findex = i+1; u[0] = model->vertices[3 * T(i).vindices[1] + 0] - model->vertices[3 * T(i).vindices[0] + 0]; u[1] = model->vertices[3 * T(i).vindices[1] + 1] - model->vertices[3 * T(i).vindices[0] + 1]; u[2] = model->vertices[3 * T(i).vindices[1] + 2] - model->vertices[3 * T(i).vindices[0] + 2]; v[0] = model->vertices[3 * T(i).vindices[2] + 0] - model->vertices[3 * T(i).vindices[0] + 0]; v[1] = model->vertices[3 * T(i).vindices[2] + 1] - model->vertices[3 * T(i).vindices[0] + 1]; v[2] = model->vertices[3 * T(i).vindices[2] + 2] - model->vertices[3 * T(i).vindices[0] + 2]; glmCross(u, v, &model->facetnorms[3 * (i+1)]); glmNormalize(&model->facetnorms[3 * (i+1)]); } } GLvoid glmSetNormalsToFaceNormals(GLMmodel* model) { /* nuke any previous normals */ if (model->normals) free(model->normals); /* allocate space for new normals */ model->numnormals = model->numtriangles; /* 1 normal per triangle */ model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3 * (model->numnormals+1)); // 3 floats per each normal for (unsigned int i = 0; i < model->numtriangles; i++) { // get the facet normal float * normal = &(model->facetnorms[3 * (i+1)]); // assign it to the correct slot memcpy(&(model->normals[3*(i+1)]),normal,sizeof(float)*3); // rewire indices of triangle normal T(i).nindices[0] = T(i).nindices[1] = T(i).nindices[2] = i+1; } } GLvoid glmDeleteNeighborStructure(GLMmodel* model, GLMnode ** structure) { for (unsigned int i = 1; i <= model->numvertices; i++) free(structure[i]); free(structure); } GLMnode ** glmBuildNeighborStructure(GLMmodel* model) { GLMnode* node; GLMnode** members; unsigned int i; /* allocate a structure that will hold a linked list of triangle indices for each vertex */ members = (GLMnode**)malloc(sizeof(GLMnode*) * (model->numvertices + 1)); for (i = 1; i <= model->numvertices; i++) members[i] = NULL; /* for every triangle, create a node for each vertex in it */ for (i = 0; i < model->numtriangles; i++) { node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[0]]; members[T(i).vindices[0]] = node; node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[1]]; members[T(i).vindices[1]] = node; node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[2]]; members[T(i).vindices[2]] = node; } return members; } GLvoid glmSetNormalsToFaceNormalsThresholded(GLMmodel* model, GLMnode ** neighborStructure, float thresholdAngle) { // deallocate any previous normals if ((model->numnormals < 3*model->numtriangles) && (model->normals)) { free(model->normals); // allocate space for new normals model->numnormals = 3*model->numtriangles; /* 3 normals per triangle */ model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3 * (model->numnormals+1)); // 3 floats per each normal } float cosThreshold = cos(thresholdAngle * M_PI / 180.0); for (unsigned int i = 0; i < model->numtriangles; i++) { // get the facet normal float * facetNormal = &(model->facetnorms[3 * (i+1)]); // go over all neighbors float normal[3]; for(int vertex=0; vertex<3; vertex++) { int vertexID = T(i).vindices[vertex]; GLMnode * node = neighborStructure[vertexID]; int numNeighbors = 0; normal[0] = 0.0; normal[1] = 0.0; normal[2] = 0.0; while (node) { // node->index is 0-indexed neighboring triangle float * neighborFacetNormal = &(model->facetnorms[3 * (node->index+1)]); if (glmDot(neighborFacetNormal, facetNormal) >= cosThreshold) { // angle is fat, add this normal to the average normal[0] += neighborFacetNormal[0]; normal[1] += neighborFacetNormal[1]; normal[2] += neighborFacetNormal[2]; } node = node->next; numNeighbors++; } if (numNeighbors == 0) { printf("Warning: something is wrong with the neighboring triangle datastructure...\n"); normal[0] = 0.0; normal[1] = 0.0; normal[2] = 1.0; } // normalize normal glmNormalize(normal); // assign it to the correct slot int normalIndex = 3*i+1+vertex; memcpy(&(model->normals[3*normalIndex]),normal,sizeof(float)*3); // rewire index of triangle normal T(i).nindices[vertex] = normalIndex; } } } /* glmVertexNormals: Generates smooth vertex normals for a model. * First builds a list of all the triangles each vertex is in. Then * loops through each vertex in the the list averaging all the facet * normals of the triangles each vertex is in. Finally, sets the * normal index in the triangle for the vertex to the generated smooth * normal. If the dot product of a facet normal and the facet normal * associated with the first triangle in the list of triangles the * current vertex is in is greater than the cosine of the angle * parameter to the function, that facet normal is not added into the * average normal calculation and the corresponding vertex is given * the facet normal. This tends to preserve hard edges. The angle to * use depends on the model, but 90 degrees is usually a good start. * * model - initialized GLMmodel structure * angle - maximum angle (in degrees) to smooth across */ GLvoid glmVertexNormals(GLMmodel* model, GLfloat angle) { GLMnode* node; GLMnode* tail; GLMnode** members; GLfloat* normals; GLuint numnormals; GLfloat average[3]; GLfloat dot, cos_angle; GLuint i, avg; assert(model); assert(model->facetnorms); /* calculate the cosine of the angle (in degrees) */ cos_angle = cos(angle * M_PI / 180.0); /* nuke any previous normals */ if (model->normals) free(model->normals); /* allocate space for new normals */ model->numnormals = model->numtriangles * 3; /* 3 normals per triangle */ model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1)); /* allocate a structure that will hold a linked list of triangle indices for each vertex */ members = (GLMnode**)malloc(sizeof(GLMnode*) * (model->numvertices + 1)); for (i = 1; i <= model->numvertices; i++) members[i] = NULL; /* for every triangle, create a node for each vertex in it */ for (i = 0; i < model->numtriangles; i++) { node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[0]]; members[T(i).vindices[0]] = node; node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[1]]; members[T(i).vindices[1]] = node; node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[2]]; members[T(i).vindices[2]] = node; } /* calculate the average normal for each vertex */ numnormals = 1; for (i = 1; i <= model->numvertices; i++) { /* calculate an average normal for this vertex by averaging the facet normal of every triangle this vertex is in */ node = members[i]; //if (!node) //fprintf(stderr, "glmVertexNormals(): vertex w/o a triangle\n"); average[0] = 0.0; average[1] = 0.0; average[2] = 0.0; avg = 0; while (node) { /* only average if the dot product of the angle between the two facet normals is greater than the cosine of the threshold angle -- or, said another way, the angle between the two facet normals is less than (or equal to) the threshold angle */ dot = glmDot(&model->facetnorms[3 * T(node->index).findex], &model->facetnorms[3 * T(members[i]->index).findex]); if (dot > cos_angle) { node->averaged = GL_TRUE; average[0] += model->facetnorms[3 * T(node->index).findex + 0]; average[1] += model->facetnorms[3 * T(node->index).findex + 1]; average[2] += model->facetnorms[3 * T(node->index).findex + 2]; avg = 1; /* we averaged at least one normal! */ } else { node->averaged = GL_FALSE; } node = node->next; } if (avg) { /* normalize the averaged normal */ glmNormalize(average); /* add the normal to the vertex normals list */ model->normals[3 * numnormals + 0] = average[0]; model->normals[3 * numnormals + 1] = average[1]; model->normals[3 * numnormals + 2] = average[2]; avg = numnormals; numnormals++; } /* set the normal of this vertex in each triangle it is in */ node = members[i]; while (node) { if (node->averaged) { /* if this node was averaged, use the average normal */ if (T(node->index).vindices[0] == i) T(node->index).nindices[0] = avg; else if (T(node->index).vindices[1] == i) T(node->index).nindices[1] = avg; else if (T(node->index).vindices[2] == i) T(node->index).nindices[2] = avg; } else { /* if this node wasn't averaged, use the facet normal */ model->normals[3 * numnormals + 0] = model->facetnorms[3 * T(node->index).findex + 0]; model->normals[3 * numnormals + 1] = model->facetnorms[3 * T(node->index).findex + 1]; model->normals[3 * numnormals + 2] = model->facetnorms[3 * T(node->index).findex + 2]; if (T(node->index).vindices[0] == i) T(node->index).nindices[0] = numnormals; else if (T(node->index).vindices[1] == i) T(node->index).nindices[1] = numnormals; else if (T(node->index).vindices[2] == i) T(node->index).nindices[2] = numnormals; numnormals++; } node = node->next; } } model->numnormals = numnormals - 1; /* free the member information */ for (i = 1; i <= model->numvertices; i++) { node = members[i]; while (node) { tail = node; node = node->next; free(tail); } } free(members); /* pack the normals array (we previously allocated the maximum number of normals that could possibly be created (numtriangles * 3), so get rid of some of them (usually alot unless none of the facet normals were averaged)) */ normals = model->normals; model->normals = (GLfloat*)malloc(sizeof(GLfloat)* 3* (model->numnormals+1)); for (i = 1; i <= model->numnormals; i++) { model->normals[3 * i + 0] = normals[3 * i + 0]; model->normals[3 * i + 1] = normals[3 * i + 1]; model->normals[3 * i + 2] = normals[3 * i + 2]; } free(normals); } /* glmLinearTexture: Generates texture coordinates according to a * linear projection of the texture map. It generates these by * linearly mapping the vertices onto a square. * * model - pointer to initialized GLMmodel structure */ GLvoid glmLinearTexture(GLMmodel* model) { GLMgroup *group; GLfloat dimensions[3]; GLfloat x, y, scalefactor; GLuint i; assert(model); if (model->texcoords) free(model->texcoords); model->numtexcoords = model->numvertices; model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1)); glmDimensions(model, dimensions); scalefactor = 2.0 / glmAbs(glmMax(glmMax(dimensions[0], dimensions[1]), dimensions[2])); /* do the calculations */ for(i = 1; i <= model->numvertices; i++) { x = model->vertices[3 * i + 0] * scalefactor; y = model->vertices[3 * i + 2] * scalefactor; model->texcoords[2 * i + 0] = (x + 1.0) / 2.0; model->texcoords[2 * i + 1] = (y + 1.0) / 2.0; } /* go through and put texture coordinate indices in all the triangles */ group = model->groups; while(group) { for(i = 0; i < group->numtriangles; i++) { T(group->triangles[i]).tindices[0] = T(group->triangles[i]).vindices[0]; T(group->triangles[i]).tindices[1] = T(group->triangles[i]).vindices[1]; T(group->triangles[i]).tindices[2] = T(group->triangles[i]).vindices[2]; } group = group->next; } #if 0 printf("glmLinearTexture(): generated %d linear texture coordinates\n", model->numtexcoords); #endif } /* glmSpheremapTexture: Generates texture coordinates according to a * spherical projection of the texture map. Sometimes referred to as * spheremap, or reflection map texture coordinates. It generates * these by using the normal to calculate where that vertex would map * onto a sphere. Since it is impossible to map something flat * perfectly onto something spherical, there is distortion at the * poles. This particular implementation causes the poles along the X * axis to be distorted. * * model - pointer to initialized GLMmodel structure */ GLvoid glmSpheremapTexture(GLMmodel* model) { GLMgroup* group; GLfloat theta, phi, rho, x, y, z, r; GLuint i; assert(model); assert(model->normals); if (model->texcoords) free(model->texcoords); model->numtexcoords = model->numnormals; model->texcoords=(GLfloat*)malloc(sizeof(GLfloat)*2*(model->numtexcoords+1)); for (i = 1; i <= model->numnormals; i++) { z = model->normals[3 * i + 0]; /* re-arrange for pole distortion */ y = model->normals[3 * i + 1]; x = model->normals[3 * i + 2]; r = sqrt((x * x) + (y * y)); rho = sqrt((r * r) + (z * z)); if(r == 0.0) { theta = 0.0; phi = 0.0; } else { if(z == 0.0) phi = 3.14159265 / 2.0; else phi = acos(z / rho); if(y == 0.0) theta = 3.141592365 / 2.0; else theta = asin(y / r) + (3.14159265 / 2.0); } model->texcoords[2 * i + 0] = theta / 3.14159265; model->texcoords[2 * i + 1] = phi / 3.14159265; } /* go through and put texcoord indices in all the triangles */ group = model->groups; while(group) { for (i = 0; i < group->numtriangles; i++) { T(group->triangles[i]).tindices[0] = T(group->triangles[i]).nindices[0]; T(group->triangles[i]).tindices[1] = T(group->triangles[i]).nindices[1]; T(group->triangles[i]).tindices[2] = T(group->triangles[i]).nindices[2]; } group = group->next; } } /* glmDelete: Deletes a GLMmodel structure. * * model - initialized GLMmodel structure */ GLvoid glmDelete(GLMmodel* model) { GLMgroup* group; //GLuint i; assert(model); if (model->pathname) free(model->pathname); if (model->mtllibname) free(model->mtllibname); if (model->vertices) free(model->vertices); if (model->verticesRest) free(model->verticesRest); if (model->normals) free(model->normals); if (model->texcoords) free(model->texcoords); if (model->facetnorms) free(model->facetnorms); if (model->triangles) free(model->triangles); if (model->materials) glmDeleteMaterials(model); while(model->groups) { group = model->groups; model->groups = model->groups->next; free(group->name); free(group->triangles); free(group->edges); free(group); } if (model->directory) free(model->directory); free(model); } void glmSetMemoryAllocationMode(int mode) { memoryAllocationMode = mode; } void glmSetMemoryAllocationSizes( int maxNumTriangles_g, int maxNumVertices_g, int maxNumNormals_g, int maxNumTexCoords_g) { maxNumTriangles = maxNumTriangles_g; maxNumVertices = maxNumVertices_g; maxNumNormals = maxNumNormals_g; maxNumTexCoords = maxNumTexCoords_g; } /* glmReadOBJ: Reads a model description from a Wavefront .OBJ file. * Returns a pointer to the created object which should be free'd with * glmDelete(). * * filename - name of the file containing the Wavefront .OBJ format data. */ GLMmodel * glmReadOBJ(char* filename) { GLMmodel * model; FILE * file; /* open the file */ file = fopen(filename, "r"); if (!file) { fprintf(stderr, "glmReadOBJ() failed: can't open data file \"%s\".\n", filename); exit(1); } /* allocate a new model */ model = (GLMmodel*) malloc (sizeof(GLMmodel)); model->pathname = glmDuplicateString(filename); model->mtllibname = NULL; model->numvertices = 0; model->vertices = NULL; model->verticesRest = NULL; model->numnormals = 0; model->normals = NULL; model->numtexcoords = 0; model->texcoords = NULL; model->numfacetnorms = 0; model->facetnorms = NULL; model->numtriangles = 0; model->triangles = NULL; model->nummaterials = 0; model->materials = NULL; model->numgroups = 0; model->groups = NULL; model->position[0] = 0.0; model->position[1] = 0.0; model->position[2] = 0.0; // now directory is known // make a copy for possible future use (as in loading textures) model->directory=glmDirName(filename); // make one default material just in case there is no usemtl tag glmMakeDefaultMaterials(model,1); /* make a first pass through the file to get a count of the number of vertices, normals, texcoords & triangles */ glmFirstPass(model, file); GLMgroup * group; if (memoryAllocationMode == GLM_TIGHT) { /* allocate memory for the triangles in each group */ group = model->groups; while(group) { group->triangles = (GLuint*)malloc(sizeof(GLuint) * group->numtriangles); group->numtriangles = 0; group->edges = (GLuint*)malloc(sizeof(GLuint) * group->numEdges * 2); group->numEdges = 0; group = group->next; } //printf("--------- Allocator: num vertices = %d\n", model->numvertices); model->vertices = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numvertices + 1)); model->verticesRest = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numvertices + 1)); model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) * model->numtriangles); if (model->numnormals) { model->normals = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numnormals + 1)); } if (model->numtexcoords) { model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) * 2 * (model->numtexcoords + 1)); } } else { /* allocate memory */ group = model->groups; while(group) { group->triangles = (GLuint*)malloc(sizeof(GLuint) * maxNumTriangles); group->numtriangles = 0; group->edges = (GLuint*)malloc(sizeof(GLuint) * group->numEdges * 2); group->numEdges = 0; group = group->next; } model->vertices = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (maxNumVertices + 1)); model->verticesRest = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (maxNumVertices + 1)); model->triangles = (GLMtriangle*)malloc(sizeof(GLMtriangle) * maxNumTriangles); model->normals = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (maxNumNormals + 1)); model->texcoords = (GLfloat*)malloc(sizeof(GLfloat) * 2 * (maxNumTexCoords + 1)); } /* rewind to beginning of file and read in the data this pass */ rewind(file); glmSecondPass(model, file); /* close the file */ fclose(file); // copy vertices into their rest position for (unsigned int i=1; i <= model->numvertices; i++) { model->verticesRest[3*i+0] = model->vertices[3*i+0]; model->verticesRest[3*i+1] = model->vertices[3*i+1]; model->verticesRest[3*i+2] = model->vertices[3*i+2]; } return model; } /* glmWriteOBJ: Writes a model description in Wavefront .OBJ format to * a file. * * model - initialized GLMmodel structure * filename - name of the file to write the Wavefront .OBJ format data to * mode - a bitwise or of values describing what is written to the file * GLM_NONE - render with only vertices * GLM_FLAT - render with facet normals * GLM_SMOOTH - render with vertex normals * GLM_TEXTURE - render with texture coords * GLM_COLOR - render with colors (color material) * GLM_MATERIAL - render with materials * GLM_COLOR and GLM_MATERIAL should not both be specified. * GLM_FLAT and GLM_SMOOTH should not both be specified. */ GLvoid glmWriteOBJ(GLMmodel* model, char* filename, GLuint mode, int writeMTL) { GLuint i; FILE* file; GLMgroup* group; assert(model); /* do a bit of warning */ if (mode & GLM_FLAT && !model->facetnorms) { printf("glmWriteOBJ() warning: flat normal output requested " "with no facet normals defined.\n"); mode &= ~GLM_FLAT; } if (mode & GLM_SMOOTH && !model->normals) { printf("glmWriteOBJ() warning: smooth normal output requested " "with no normals defined.\n"); mode &= ~GLM_SMOOTH; } if (mode & GLM_TEXTURE && !model->texcoords) { printf("glmWriteOBJ() warning: texture coordinate output requested " "with no texture coordinates defined.\n"); mode &= ~GLM_TEXTURE; } if (mode & GLM_FLAT && mode & GLM_SMOOTH) { printf("glmWriteOBJ() warning: flat normal output requested " "and smooth normal output requested (using smooth).\n"); mode &= ~GLM_FLAT; } if (mode & GLM_COLOR && !model->materials) { printf("glmWriteOBJ() warning: color output requested " "with no colors (materials) defined.\n"); mode &= ~GLM_COLOR; } if (mode & GLM_MATERIAL && !model->materials) { printf("glmWriteOBJ() warning: material output requested " "with no materials defined.\n"); mode &= ~GLM_MATERIAL; } if (mode & GLM_COLOR && mode & GLM_MATERIAL) { printf("glmWriteOBJ() warning: color and material output requested " "outputting only materials.\n"); mode &= ~GLM_COLOR; } /* open the file */ file = fopen(filename, "w"); if (!file) { fprintf(stderr, "glmWriteOBJ() failed: can't open file \"%s\" to write.\n", filename); exit(1); } /* spit out a header */ fprintf(file, "# \n"); fprintf(file, "# Wavefront OBJ generated by GLM library\n"); fprintf(file, "# \n"); fprintf(file, "# GLM library\n"); fprintf(file, "# Nate Robins\n"); fprintf(file, "# [email protected]\n"); fprintf(file, "# http://www.pobox.com/~ndr\n"); fprintf(file, "# \n"); if (writeMTL && (mode & GLM_MATERIAL && model->mtllibname)) { fprintf(file, "\nmtllib %s\n\n", model->mtllibname); glmWriteMTL(model, filename, model->mtllibname); } /* spit out the vertices */ fprintf(file, "\n"); fprintf(file, "# %d vertices\n", model->numvertices); for (i = 1; i <= model->numvertices; i++) { fprintf(file, "v %f %f %f\n", model->vertices[3 * i + 0], model->vertices[3 * i + 1], model->vertices[3 * i + 2]); } fflush(file); /* spit out the smooth/flat normals */ if (mode & GLM_SMOOTH) { fprintf(file, "\n"); fprintf(file, "# %d normals\n", model->numnormals); for (i = 1; i <= model->numnormals; i++) { fprintf(file, "vn %f %f %f\n", model->normals[3 * i + 0], model->normals[3 * i + 1], model->normals[3 * i + 2]); } } else if (mode & GLM_FLAT) { fprintf(file, "\n"); fprintf(file, "# %d normals\n", model->numfacetnorms); for (i = 1; i <= model->numnormals; i++) { fprintf(file, "vn %f %f %f\n", model->facetnorms[3 * i + 0], model->facetnorms[3 * i + 1], model->facetnorms[3 * i + 2]); } } fflush(file); /* spit out the texture coordinates */ if (mode & GLM_TEXTURE) { fprintf(file, "\n"); fprintf(file, "# %d texcoords\n", model->numtexcoords); for (i = 1; i <= model->numtexcoords; i++) { fprintf(file, "vt %f %f\n", model->texcoords[2 * i + 0], model->texcoords[2 * i + 1]); } } fflush(file); fprintf(file, "\n"); fprintf(file, "# %d groups\n", model->numgroups); fprintf(file, "# %d faces (triangles)\n", model->numtriangles); fprintf(file, "\n"); group = model->groups; while(group) { fprintf(file, "g %s\n", group->name); if (mode & GLM_MATERIAL) fprintf(file, "usemtl %s\n", model->materials[group->material].name); for (i = 0; i < group->numtriangles; i++) { if (mode & GLM_SMOOTH && mode & GLM_TEXTURE) { fprintf(file, "f %d/%d/%d %d/%d/%d %d/%d/%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).tindices[0], T(group->triangles[i]).nindices[0], T(group->triangles[i]).vindices[1], T(group->triangles[i]).tindices[1], T(group->triangles[i]).nindices[1], T(group->triangles[i]).vindices[2], T(group->triangles[i]).tindices[2], T(group->triangles[i]).nindices[2]); } else if (mode & GLM_FLAT && mode & GLM_TEXTURE) { fprintf(file, "f %d/%d %d/%d %d/%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).findex, T(group->triangles[i]).vindices[1], T(group->triangles[i]).findex, T(group->triangles[i]).vindices[2], T(group->triangles[i]).findex); } else if (mode & GLM_TEXTURE) { fprintf(file, "f %d/%d %d/%d %d/%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).tindices[0], T(group->triangles[i]).vindices[1], T(group->triangles[i]).tindices[1], T(group->triangles[i]).vindices[2], T(group->triangles[i]).tindices[2]); } else if (mode & GLM_SMOOTH) { fprintf(file, "f %d//%d %d//%d %d//%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).nindices[0], T(group->triangles[i]).vindices[1], T(group->triangles[i]).nindices[1], T(group->triangles[i]).vindices[2], T(group->triangles[i]).nindices[2]); } else if (mode & GLM_FLAT) { fprintf(file, "f %d//%d %d//%d %d//%d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).findex, T(group->triangles[i]).vindices[1], T(group->triangles[i]).findex, T(group->triangles[i]).vindices[2], T(group->triangles[i]).findex); } else { fprintf(file, "f %d %d %d\n", T(group->triangles[i]).vindices[0], T(group->triangles[i]).vindices[1], T(group->triangles[i]).vindices[2]); } } fprintf(file, "\n"); group = group->next; } fclose(file); } int glmSetUpTextures(GLMmodel* model, int mode) { if (!model->texcoords) { printf("glmSetUpTextures() warning: texture setup requested " "with no texture coordinates defined.\n"); } for (unsigned int i=0; i < model->nummaterials; i++) { printf("Initializing material %d: %s\n",i,model->materials[i].name); if (!model->materials[i].textureFile) { printf(" No texture file defined for this material.\n"); continue; // no texture file defined for this material } // set up texture map // make textures int width, height; char textureFile[4096]; sprintf(textureFile,"%s/%s",model->directory,model->materials[i].textureFile); printf(" Loading texture from %s...\n ", textureFile); model->materials[i].textureData = glmReadPPM(textureFile, &width, &height); if (model->materials[i].textureData == NULL) { printf(" Unable to load texture from %s.\n", textureFile); return 1; } /* width=128; height=128; model->materials[i].textureData = (unsigned char*)malloc(sizeof(unsigned char)*width*height*3); for(int ii=0;ii<width; ii++) for(int jj=0;jj<height; jj++) { model->materials[i].textureData[3*(width*jj+ii)+0] = (ii/10 + jj/10) % 2 == 0 ? (int)(1.0*255* ii / width ) : 0; model->materials[i].textureData[3*(width*jj+ii)+1] = 0; model->materials[i].textureData[3*(width*jj+ii)+2] = 0; } if (model->materials[i].textureData == NULL) { printf(" Error: failed to read texture data.\n"); exit (1); } */ GLubyte * data = model->materials[i].textureData; int twidth = width; int theight = height; printf(" Texture bitmap size is %d x %d\n",width, height); /* // resize to power of 2 int pow2 = 1; while ((width > pow2) || (height > pow2)) pow2 *= 2; pow2 = 256; twidth = pow2; theight = pow2; printf(" Resizing to %d x %d .\n" , twidth, theight); data = (GLubyte*) malloc (sizeof(GLubyte) * 3 * twidth * theight); gluScaleImage(GL_RGB, width, height, GL_UNSIGNED_BYTE, model->materials[i].textureData, twidth, theight, GL_UNSIGNED_BYTE, data); */ glEnable(GL_TEXTURE_2D); glGenTextures(1,&(model->materials[i].textureName)); glBindTexture(GL_TEXTURE_2D, model->materials[i].textureName); //printf(" Texture identifier is %d\n",model->materials[i].textureName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //GL_NEAREST,GL_LINEAR,GL_LINEAR_MIPMAP_LINEAR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if ((mode & GLM_MIPMAP) == GLM_NOMIPMAP) { printf("Not using mipmaps.\n"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } else { printf("Using mipmaps.\n"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } model->textureMode = mode & GLM_LIGHTINGMODULATION; if ((mode & GLM_LIGHTINGMODULATION) == GLM_REPLACE) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); else if ((mode & GLM_LIGHTINGMODULATION) == GLM_MODULATE) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); else { printf(" Warning: unknown texture lighting interaction mode specified.\n"); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); } if ((mode & GLM_MIPMAP) == GLM_NOMIPMAP) glTexImage2D(GL_TEXTURE_2D, 0 , GL_RGB, twidth, theight, 0, GL_RGB, GL_UNSIGNED_BYTE, data); else gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, twidth, theight, GL_RGB, GL_UNSIGNED_BYTE, data); /* printf(" Generating mipmaps...\n");fflush(NULL); if (gluBuild2DMipmaps(GL_TEXTURE_2D,3,width,height,GL_RGB,GL_UNSIGNED_BYTE, model->materials[i].textureData) != 0) printf(" Warning: could not create mipmaps for the textures.\n"); */ glEnable(GL_TEXTURE_2D); printf("Texture loaded.\n");fflush(NULL); } return 0; } GLvoid glmDrawEdges(GLMmodel * model, char * groupName) { assert(model); GLMgroup * group = model->groups; glBegin(GL_LINES); while (group) { if (groupName != NULL) { if (strcmp(groupName, group->name) != 0) { group = group->next; continue; } } for (GLuint i = 0; i < group->numEdges; i++) { float * vtx0 = &(model->vertices[3*group->edges[2*i+0]]); glVertex3f(vtx0[0], vtx0[1], vtx0[2]); float * vtx1 = &(model->vertices[3*group->edges[2*i+1]]); glVertex3f(vtx1[0], vtx1[1], vtx1[2]); } group = group->next; } glEnd(); } /* glmDraw: Renders the model to the current OpenGL context using the * mode specified. * * model - initialized GLMmodel structure * mode - a bitwise OR of values describing what is to be rendered. * GLM_NONE - render with only vertices * GLM_FLAT - render with facet normals * GLM_SMOOTH - render with vertex normals * GLM_TEXTURE - render with texture coords * GLM_COLOR - render with colors (color material) * GLM_MATERIAL - render with materials * GLM_COLOR and GLM_MATERIAL should not both be specified. * GLM_FLAT and GLM_SMOOTH should not both be specified. * GLM_TEXTURE to use textures */ GLvoid glmDraw(GLMmodel* model, unsigned int mode) { GLuint i; GLMgroup* group; GLMtriangle* triangle; GLMmaterial* material = NULL; assert(model); assert(model->vertices); // do a bit of warning if (mode & GLM_FLAT && !model->facetnorms) { printf("glmDraw() warning: flat render mode requested " "with no facet normals defined.\n"); mode &= ~GLM_FLAT; } if (mode & GLM_SMOOTH && !model->normals) { printf("glmDraw() warning: smooth render mode requested " "with no normals defined.\n"); mode &= ~GLM_SMOOTH; } if (mode & GLM_TEXTURE && !model->texcoords) { printf("glmDraw() warning: texture render mode requested " "with no texture coordinates defined.\n"); mode &= ~GLM_TEXTURE; } if (mode & GLM_FLAT && mode & GLM_SMOOTH) { printf("glmDraw() warning: flat render mode requested " "and smooth render mode requested (using smooth).\n"); mode &= ~GLM_FLAT; } if (mode & GLM_COLOR && !model->materials) { printf("glmDraw() warning: color render mode requested " "with no materials defined.\n"); mode &= ~GLM_COLOR; } if (mode & GLM_MATERIAL && !model->materials) { printf("glmDraw() warning: material render mode requested " "with no materials defined.\n"); mode &= ~GLM_MATERIAL; } if (mode & GLM_COLOR && mode & GLM_MATERIAL) { printf("glmDraw() warning: color and material render mode requested " "using only material mode.\n"); mode &= ~GLM_COLOR; } if (mode & GLM_COLOR) glEnable(GL_COLOR_MATERIAL); else if (mode & GLM_MATERIAL) glDisable(GL_COLOR_MATERIAL); //glEnableClientState(GL_VERTEX_ARRAY); //glVertexPointer(3,GL_FLOAT,0,model->vertices); //perhaps this loop should be unrolled into material, color, flat, //smooth, etc. loops? since most cpu's have good branch prediction //schemes (and these branches will always go one way), probably //wouldn't gain too much? group = model->groups; while (group != NULL) { if (group->numtriangles == 0) { group = group->next; continue; } glDisable(GL_TEXTURE_2D); if (mode & GLM_MATERIAL) { material = &model->materials[group->material]; //float green[4] = {0,2,0, 1}; //glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, green); //glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, green); //glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, green); //printf("amb: %G %G %G %G\n", material->ambient[0], material->ambient[1], material->ambient[2], material->ambient[3]); //printf("dif: %G %G %G %G\n", material->diffuse[0], material->diffuse[1], material->diffuse[2], material->diffuse[3]); //printf("spe: %G %G %G %G\n", material->specular[0], material->specular[1], material->specular[2], material->specular[3]); //material->ambient[0] = 0; //material->ambient[1] = 0; //material->ambient[2] = 0; //material->diffuse[0] = 0; //material->diffuse[1] = 2; //material->diffuse[2] = 0; glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, material->ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, material->diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, material->specular); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, material->shininess); } if ((mode & GLM_TEXTURE) && (material->textureData != NULL)) { GLuint tname = material->textureName; glBindTexture(GL_TEXTURE_2D,tname); if (model->textureMode == GLM_REPLACE) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); if (model->textureMode == GLM_MODULATE) { glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); } glEnable(GL_TEXTURE_2D); } if (mode & GLM_COLOR) { glColor3fv(material->diffuse); } //for(int j=0;j<9; j++) //printf("%f ", model->vertices[3 * model->numvertices-6+j]); //printf("\n"); //printf("gnum: %u\n", group->numtriangles); glBegin(GL_TRIANGLES); for (i = 0; i < group->numtriangles; i++) { triangle = &T(group->triangles[i]); //glVertex3fv(&model->vertices[3 * triangle->vindices[0]]); //glVertex3fv(&model->vertices[3 * triangle->vindices[1]]); //glVertex3fv(&model->vertices[3 * triangle->vindices[2]]); /* for(int j=0; j<3; j++) { if ((triangle->vindices[j] < 1) || (triangle->vindices[j] > model->numvertices)) printf("****** Error: i:%d j:%d: vindex: %d\n", i,j, triangle->vindices[j]); } */ /* if (triangle->vindices[0] > model->numvertices - 10) continue; if (triangle->vindices[1] > model->numvertices - 10) continue; if (triangle->vindices[2] > model->numvertices - 10) continue; */ //glNormal3f(1,0,0); //glVertex3fv(&model->vertices[3 * model->numvertices-0]); //glVertex3fv(&model->vertices[3 * model->numvertices-3]); //glVertex3fv(&model->vertices[3 * model->numvertices-6]); //glVertex3fv(&model->vertices[3 * model->numvertices-9]); //glVertex3fv(&model->vertices[3 * model->numvertices-12]); //glVertex3fv(&model->vertices[3 * model->numvertices-15]); if (mode & GLM_FLAT) glNormal3fv(&model->facetnorms[3 * triangle->findex]); // vertex 0 if (mode & GLM_SMOOTH) glNormal3fv(&model->normals[3 * triangle->nindices[0]]); if (mode & GLM_TEXTURE) glTexCoord2fv(&model->texcoords[2 * triangle->tindices[0]]); glVertex3fv(&model->vertices[3 * triangle->vindices[0]]); // vertex 1 if (mode & GLM_SMOOTH) glNormal3fv(&model->normals[3 * triangle->nindices[1]]); if (mode & GLM_TEXTURE) glTexCoord2fv(&model->texcoords[2 * triangle->tindices[1]]); glVertex3fv(&model->vertices[3 * triangle->vindices[1]]); // vertex 2 if (mode & GLM_SMOOTH) glNormal3fv(&model->normals[3 * triangle->nindices[2]]); if (mode & GLM_TEXTURE) glTexCoord2fv(&model->texcoords[2 * triangle->tindices[2]]); glVertex3fv(&model->vertices[3 * triangle->vindices[2]]); //glArrayElement(triangle->vindices[0]); //glArrayElement(triangle->vindices[1]); //glArrayElement(triangle->vindices[2]); } glEnd(); group = group->next; } } /* glmList: Generates and returns a display list for the model using * the mode specified. * * model - initialized GLMmodel structure * mode - a bitwise OR of values describing what is to be rendered. * GLM_NONE - render with only vertices * GLM_FLAT - render with facet normals * GLM_SMOOTH - render with vertex normals * GLM_TEXTURE - render with texture coords * GLM_COLOR - render with colors (color material) * GLM_MATERIAL - render with materials * GLM_COLOR and GLM_MATERIAL should not both be specified. * GLM_FLAT and GLM_SMOOTH should not both be specified. */ GLuint glmList(GLMmodel* model, unsigned int mode) { GLuint list; list = glGenLists(1); glNewList(list, GL_COMPILE); glmDraw(model, mode); glEndList(); return list; } GLuint glmListEdges(GLMmodel* model) { GLuint list; list = glGenLists(1); glNewList(list, GL_COMPILE); glmDrawEdges(model); glEndList(); return list; } /* glmWeld: eliminate (weld) vectors that are within an epsilon of * each other. * * model - initialized GLMmodel structure * epsilon - maximum difference between vertices * ( 0.00001 is a good start for a unitized model) * */ GLvoid glmWeld(GLMmodel* model, GLfloat epsilon) { GLfloat* vectors; GLfloat* copies; GLuint numvectors; GLuint i; /* vertices */ numvectors = model->numvertices; vectors = model->vertices; copies = glmWeldVectors(vectors, &numvectors, epsilon); #if 0 printf("glmWeld(): %d redundant vertices.\n", model->numvertices - numvectors - 1); #endif for (i = 0; i < model->numtriangles; i++) { T(i).vindices[0] = (GLuint)vectors[3 * T(i).vindices[0] + 0]; T(i).vindices[1] = (GLuint)vectors[3 * T(i).vindices[1] + 0]; T(i).vindices[2] = (GLuint)vectors[3 * T(i).vindices[2] + 0]; } /* free space for old vertices */ free(vectors); /* allocate space for the new vertices */ model->numvertices = numvectors; model->vertices = (GLfloat*)malloc(sizeof(GLfloat) * 3 * (model->numvertices + 1)); /* copy the optimized vertices into the actual vertex list */ for (i = 1; i <= model->numvertices; i++) { model->vertices[3 * i + 0] = copies[3 * i + 0]; model->vertices[3 * i + 1] = copies[3 * i + 1]; model->vertices[3 * i + 2] = copies[3 * i + 2]; } free(copies); } /* glmReadPPM: read a PPM raw (type P6) file. The PPM file has a header * that should look something like: * * P6 * # comment * width height max_value * rgbrgbrgb... * * where "P6" is the magic cookie which identifies the file type and * should be the only characters on the first line followed by a * carriage return. Any line starting with a # mark will be treated * as a comment and discarded. After the magic cookie, three integer * values are expected: width, height of the image and the maximum * value for a pixel (max_value must be < 256 for PPM raw files). The * data section consists of width*height rgb triplets (one byte each) * in binary format (i.e., such as that written with fwrite() or * equivalent). * * The rgb data is returned as an array of unsigned chars (packed * rgb). The malloc()'d memory should be free()'d by the caller. If * an error occurs, an error message is sent to stderr and NULL is * returned. * * filename - name of the .ppm file. * width - will contain the width of the image on return. * height - will contain the height of the image on return. * */ GLubyte* glmReadPPM(char* filename, int* width, int* height) { FILE* fp; int i, w, h, d; unsigned char* image; char head[70]; /* max line <= 70 in PPM (per spec). */ fp = fopen(filename, "rb"); if (!fp) { perror(filename); return NULL; } /* grab first two chars of the file and make sure that it has the correct magic cookie for a raw PPM file. */ fgets(head, 70, fp); if (strncmp(head, "P6", 2)) { fprintf(stderr, "%s: Not a raw PPM file\n", filename); return NULL; } /* grab the three elements in the header (width, height, maxval). */ i = 0; while(i < 3) { fgets(head, 70, fp); if (head[0] == '#') /* skip comments. */ continue; if (i == 0) i += sscanf(head, "%d %d %d", &w, &h, &d); else if (i == 1) i += sscanf(head, "%d %d", &h, &d); else if (i == 2) i += sscanf(head, "%d", &d); } /* grab all the image data in one fell swoop. */ image = (unsigned char*)malloc(sizeof(unsigned char)*w*h*3); if ((int)fread(image, sizeof(unsigned char), w*h*3, fp) < 3*w*h) { printf("Error accessing PPM file.\n"); exit(1); } fclose(fp); *width = w; *height = h; return image; } GLvoid glmApplyDeformation(GLMmodel* model, float * U, float * q, int n, int r) { for (unsigned int i=0; i < 3*model->numvertices; i++) { model->vertices[i+3] = model->verticesRest[i+3]; for (int j=0; j < r; j++) model->vertices[i+3] += q[j] * U[3*n*j + i]; } } GLvoid glmApplyDeformation(GLMmodel * model, float * u) { for (unsigned int i=0; i < 3*model->numvertices; i++) { model->vertices[i+3] = model->verticesRest[i+3] + u[i]; } } GLvoid glmApplyDeformation(GLMmodel * model, double * u) { for (unsigned int i=0; i < 3*model->numvertices; i++) { model->vertices[i+3] = model->verticesRest[i+3] + u[i]; } } GLvoid glmApplyDeformation(GLMmodel * model, float * u, int * mask) { for (unsigned int i=0; i < model->numvertices; i++) { model->vertices[3*i+3] = model->verticesRest[3*i+3] + u[3*mask[i]+0]; model->vertices[3*i+4] = model->verticesRest[3*i+4] + u[3*mask[i]+1]; model->vertices[3*i+5] = model->verticesRest[3*i+5] + u[3*mask[i]+2]; } } GLvoid glmApplyDeformation(GLMmodel * model, double * u, int * mask) { for (unsigned int i=0; i < model->numvertices; i++) { model->vertices[3*i+3] = model->verticesRest[3*i+3] + u[3*mask[i]+0]; model->vertices[3*i+4] = model->verticesRest[3*i+4] + u[3*mask[i]+1]; model->vertices[3*i+5] = model->verticesRest[3*i+5] + u[3*mask[i]+2]; } } GLvoid glmDrawPoints(GLMmodel * model) { glBegin(GL_POINTS); for (unsigned int i=1; i <= model->numvertices; i++) glVertex3fv(&model->vertices[3*i]); glEnd(); } GLvoid glmDrawPoints(GLMmodel * model, int * selectedVertices, int numSelectedVertices) { glBegin(GL_POINTS); for (int i=0; i < numSelectedVertices; i++) glVertex3fv(&model->vertices[3*selectedVertices[i]+3]); glEnd(); } GLvoid glmDrawSelectedPoints(GLMmodel * model, int * selectedVertices, int numSelectedVertices, int oneIndexed) { glBegin(GL_POINTS); for (int i=0; i < numSelectedVertices; i++) glVertex3fv(&model->vertices[3*selectedVertices[i] + 3 - 3 * oneIndexed]); glEnd(); } GLvoid glmDrawUnselectedPoints(GLMmodel * model, int * selectionArray) { glBegin(GL_POINTS); for (unsigned int i=1; i <= model->numvertices; i++) { if (selectionArray[i] == 0) glVertex3fv(&model->vertices[3*i]); } glEnd(); } GLvoid glmDrawPoints(GLMmodel * model, int start, int end) { glBegin(GL_POINTS); for (int i=start; i < end; i++) glVertex3fv(&model->vertices[3*i]); glEnd(); } GLvoid glmDrawPointsSelection(GLMmodel * model) { for (unsigned int i=1; i <= model->numvertices; i++) { glLoadName(i); glBegin(GL_POINTS); glVertex3fv(&model->vertices[3*i]); glEnd(); } } GLvoid glmDrawNormals(GLMmodel * model) { static GLuint i; static GLMgroup* group; static GLMtriangle* triangle; //static GLMmaterial* material; group = model->groups; while (group) { for (i = 0; i < group->numtriangles; i++) { triangle = &T(group->triangles[i]); glBegin(GL_LINES); for (int i=0; i<3; i++) { int vertexID = triangle->vindices[i]; glVertex3fv(&model->vertices[3 * vertexID]); float nx,ny,nz; int normalID = triangle->nindices[i]; nx = model->normals[3 * normalID + 0]; ny = model->normals[3 * normalID + 1]; nz = model->normals[3 * normalID + 2]; float x,y,z; x = model->vertices[3*vertexID+0] + 0.1 * nx; y = model->vertices[3*vertexID+1] + 0.1 * ny; z = model->vertices[3*vertexID+2] + 0.1 * nz; glVertex3f(x,y,z); } glEnd(); } group = group->next; } } int glmCopyVertex(GLMmodel * model, int i) { model->numvertices++; model->vertices[3 * model->numvertices + 0] = model->vertices[3 * i + 0]; model->vertices[3 * model->numvertices + 1] = model->vertices[3 * i + 1]; model->vertices[3 * model->numvertices + 2] = model->vertices[3 * i + 2]; model->verticesRest[3 * model->numvertices + 0] = model->verticesRest[3 * i + 0]; model->verticesRest[3 * model->numvertices + 1] = model->verticesRest[3 * i + 1]; model->verticesRest[3 * model->numvertices + 2] = model->verticesRest[3 * i + 2]; return model->numvertices; } int glmAddVertex(GLMmodel * model, GLfloat x, GLfloat y, GLfloat z) { model->numvertices++; model->vertices[3 * model->numvertices + 0] = x; model->vertices[3 * model->numvertices + 1] = y; model->vertices[3 * model->numvertices + 2] = z; model->verticesRest[3 * model->numvertices + 0] = x; model->verticesRest[3 * model->numvertices + 1] = y; model->verticesRest[3 * model->numvertices + 2] = z; return model->numvertices; } int glmAddNormal(GLMmodel * model, GLfloat x, GLfloat y, GLfloat z) { model->numnormals++; model->normals[3 * model->numnormals + 0] = x; model->normals[3 * model->numnormals + 1] = y; model->normals[3 * model->numnormals + 2] = z; return model->numnormals; } int glmAddTexCoord(GLMmodel * model, GLfloat u, GLfloat v) { model->numtexcoords++; model->texcoords[2 * model->numtexcoords + 0] = u; model->texcoords[2 * model->numtexcoords + 1] = v; return model->numtexcoords; } // adds a triangle spanned on the given indices/normals/texcoords void glmAddTriangle(GLMmodel * model, GLMgroup * group, int v1, int v2, int v3, int n1, int n2, int n3, int t1, int t2, int t3) { int numtriangles = model->numtriangles; T(numtriangles).vindices[0] = v1; T(numtriangles).tindices[0] = t1; T(numtriangles).nindices[0] = n1; T(numtriangles).vindices[1] = v2; T(numtriangles).tindices[1] = t2; T(numtriangles).nindices[1] = n2; T(numtriangles).vindices[2] = v3; T(numtriangles).tindices[2] = t3; T(numtriangles).nindices[2] = n3; group->triangles[group->numtriangles++] = numtriangles; model->numtriangles++; } void glmAddTriangle(GLMmodel * model, GLMgroup * group, int v1, int v2, int v3, int n1, int n2, int n3) { glmAddTriangle(model, group, v1, v2, v3, n1, n2, n3, -1, -1, -1); } void glmAddTriangle(GLMmodel * model, GLMgroup * group, int v1, int v2, int v3) { glmAddTriangle(model, group, v1, v2, v3, -1, -1, -1, -1, -1, -1); } void glmGetTriangle(GLMmodel * model, int triangleID, int & i1, int & i2, int & i3) { i1 = T(triangleID).vindices[0]; i2 = T(triangleID).vindices[1]; i3 = T(triangleID).vindices[2]; } void glmSetTriangle(GLMmodel * model, int triangleID, int pos, int newValue) { T(triangleID).vindices[pos] = newValue; } void glmGetVertex(GLMmodel * model, int index, float & v1, float & v2, float & v3) { v1 = model->vertices[3 * index + 0]; v2 = model->vertices[3 * index + 1]; v3 = model->vertices[3 * index + 2]; } void glmSetVertex(GLMmodel * model, int index, int pos, float value) { model->vertices[3 * index + pos] = value; } void glmPermuteVertices(GLMmodel * model, int * permutation) { // renumber the vertices unsigned int i; // first, make a copy float * copy = (float*) malloc (sizeof(float) * model->numvertices * 3); for (i=1; i <= model->numvertices; i++) { float x,y,z; glmGetVertex(model,i,x,y,z); copy[3*(i-1)+0] = x; copy[3*(i-1)+1] = y; copy[3*(i-1)+2] = z; } // write vertices in place for (i=1; i <= model->numvertices; i++) { glmSetVertex(model,permutation[i],0,copy[3*(i-1)+0]); glmSetVertex(model,permutation[i],1,copy[3*(i-1)+1]); glmSetVertex(model,permutation[i],2,copy[3*(i-1)+2]); } free(copy); // renumber the faces for(i=0; i < model->numtriangles; i++) { int i1 = T(i).vindices[0]; int i2 = T(i).vindices[1]; int i3 = T(i).vindices[2]; T(i).vindices[0] = permutation[i1]; T(i).vindices[1] = permutation[i2]; T(i).vindices[2] = permutation[i3]; } } /* Jernej Barbic */ // will compute the averaged normals for the model, and store them into normals // assumed normals has been pre-allocated, to the size of 3 * sizeof(float) * model->numvertices GLvoid glmVertexAveragedNormals(GLMmodel* model, float * normals) { GLMnode* node; GLMnode* tail; GLMnode** members; GLuint numnormals; GLfloat average[3]; GLuint i, avg; assert(model); assert(model->facetnorms); /* allocate a structure that will hold a linked list of triangle indices for each vertex */ members = (GLMnode**)malloc(sizeof(GLMnode*) * (model->numvertices + 1)); for (i = 1; i <= model->numvertices; i++) members[i] = NULL; /* for every triangle, create a node for each vertex in it */ for (i = 0; i < model->numtriangles; i++) { node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[0]]; members[T(i).vindices[0]] = node; node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[1]]; members[T(i).vindices[1]] = node; node = (GLMnode*)malloc(sizeof(GLMnode)); node->index = i; node->next = members[T(i).vindices[2]]; members[T(i).vindices[2]] = node; } // for each vertex i: // traverse the list of all faces that contain the vertex i // if angle among any face and the FIRST face on the list is greater than the treshold, do the averaging // traverse all triangles: // if a triangle contains vertex i: // if i was averaged, register the average normal, as the normal for that vertex in that triangle // else, register the triangle (face) normal as the normal for that vertex in that triangle // stores normals in an independent, separate array /* calculate the average normal for each vertex */ numnormals = 0; for (i = 1; i <= model->numvertices; i++) { /* calculate an average normal for this vertex by averaging the facet normal of every triangle this vertex is in */ node = members[i]; // list of triangles containing node i //if (!node) //printf("glmVertexNormals(): vertex w/o a triangle\n"); average[0] = 0.0; average[1] = 0.0; average[2] = 0.0; avg = 0; while (node) { // average the normals node->averaged = GL_TRUE; average[0] += model->facetnorms[3 * T(node->index).findex + 0]; average[1] += model->facetnorms[3 * T(node->index).findex + 1]; average[2] += model->facetnorms[3 * T(node->index).findex + 2]; avg = 1; /* we averaged at least one normal! */ node = node->next; } if (avg) { // vertex had at least one triangle // normalize the averaged normal glmNormalize(average); /* add the normal to the vertex normals list */ normals[3 * numnormals + 0] = average[0]; normals[3 * numnormals + 1] = average[1]; normals[3 * numnormals + 2] = average[2]; avg = numnormals; } else { //printf("glmVertexNormals(): Setting zero normal for a vertex not belonging to any triangle\n"); normals[3 * numnormals + 0] = 0; normals[3 * numnormals + 1] = 0; normals[3 * numnormals + 2] = 0; } numnormals++; } /* free the member information */ for (i = 1; i <= model->numvertices; i++) { node = members[i]; while (node) { tail = node; node = node->next; free(tail); } } free(members); } /* // converts (most of) the geometry data from the model into a binary representation GLvoid binarizeModelData(GLMmodel * model, int & numVertices, int & numTriangles, int & numGroups, ) { // read out num triangles fread(&numTriangles,sizeof(int),1,fin); vertices = (float*) malloc (sizeof(float) * 9 * numTriangles); verticesRest = (float*) malloc (sizeof(float) * 9 * numTriangles); normals = (float*) malloc (sizeof(float) * 9 * numTriangles); // read all vertices, three per triangle fread(vertices,sizeof(float),9 * numTriangles,fin); memcpy(verticesRest,vertices,sizeof(float) * 9 * numTriangles); // read original indices for each vertex originalIndices = (int*) malloc (sizeof(int) * 3 * numTriangles); fread(originalIndices,sizeof(int),3 * numTriangles,fin); // read num groups fread(&numGroups,sizeof(int),1,fin); Ka = (float*) malloc (sizeof(float) * 3 * numGroups); Kd = (float*) malloc (sizeof(float) * 3 * numGroups); Ks = (float*) malloc (sizeof(float) * 3 * numGroups); shininess = (float*) malloc (sizeof(float) * numGroups); groupSize = (int *) malloc (sizeof(int) * numGroups); // read ka, kd, ks material data for each group for(i=0; i < numGroups; i++) { fread(&groupSize[i],sizeof(int),1,fin); fread(&Ka[3*i],sizeof(float),3,fin); fread(&Kd[3*i],sizeof(float),3,fin); fread(&Ks[3*i],sizeof(float),3,fin); fread(&shininess[i],sizeof(float),1,fin); } } */ // saves the model to a "flat" format, to be used for fast ARB vertex rendering GLvoid saveToFlatFormat(GLMmodel* model, char * filename) { unsigned int i; FILE * fout; fout = fopen(filename,"wb"); if (!fout) { printf("Error: couldn't open filename %s .\n",filename); return; } /* if ((int)(fread(&nVertices_,sizeof(int),1,fin)) < 1) return 1; */ // write out num triangles fwrite(&model->numtriangles,sizeof(int),1,fout); fwrite(&model->numvertices,sizeof(int),1,fout); // write out all vertices, three per triangle GLMtriangle * triangle; GLMgroup * group; GLMmaterial * material; group = model->groups; while (group) { for (i = 0; i < group->numtriangles; i++) { triangle = &T(group->triangles[i]); fwrite(&model->vertices[3 * triangle->vindices[0]],sizeof(float),3,fout); fwrite(&model->vertices[3 * triangle->vindices[1]],sizeof(float),3,fout); fwrite(&model->vertices[3 * triangle->vindices[2]],sizeof(float),3,fout); } group = group->next; } // write out original indices for each vertex group = model->groups; while (group) { for (i = 0; i < group->numtriangles; i++) { triangle = &T(group->triangles[i]); int i1 = triangle->vindices[0]-1; fwrite(&i1,sizeof(int),1,fout); int i2 = triangle->vindices[1]-1; fwrite(&i2,sizeof(int),1,fout); int i3 = triangle->vindices[2]-1; fwrite(&i3,sizeof(int),1,fout); } group = group->next; } // write out num groups fwrite(&model->numgroups,sizeof(int),1,fout); // write out ka, kd, ks material data for each group group = model->groups; while (group) { fwrite(&group->numtriangles,sizeof(int),1,fout); material = &model->materials[group->material]; fwrite(&material->ambient,sizeof(float),3,fout); fwrite(&material->diffuse,sizeof(float),3,fout); fwrite(&material->specular,sizeof(float),3,fout); fwrite(&material->shininess,sizeof(float),1,fout); group = group->next; } fclose(fout); } GLvoid glmPrint_bitmap_string(float x,float y, float z, char* s) { glRasterPos3f(x,y,z); if (s && strlen(s)) { while (*s) { glutBitmapCharacter(GLUT_BITMAP_9_BY_15, *s); s++; } } } GLvoid glmPrint_bitmap_integer(float x,float y, float z,long i) { char s[50]; sprintf(s,"%ld",i); glmPrint_bitmap_string(x,y,z,s); } int glmClosestVertex(GLMmodel * model, double queryPosX, double queryPosY, double queryPosZ) { double closestDist2 = DBL_MAX; int closestVertex=0; for (int i=1; i <= (int)model->numvertices; i++) { double posX = model->vertices[3 * i + 0]; double posY = model->vertices[3 * i + 1]; double posZ = model->vertices[3 * i + 2]; double d2 = (queryPosX-posX)*(queryPosX-posX)+ (queryPosY-posY)*(queryPosY-posY)+ (queryPosZ-posZ)*(queryPosZ-posZ); if (d2 < closestDist2) { closestDist2 = d2; closestVertex = i-1; } } return closestVertex; } // shows all point labels, 1-indexing GLvoid glmShowPointLabels(GLMmodel* model) { glmShowPointLabels(model,1,(int)(model->numvertices)); } // shows point labels from [k to l], 1-indexing GLvoid glmShowPointLabels(GLMmodel* model, int k, int l) { glColor3f(0,0,0); // show point labels // labels are printed out in the range 1... , not 0... for (int i=k; i<=l; i++) glmPrint_bitmap_integer(model->vertices[3*i],model->vertices[3*i+1],model->vertices[3*i+2],i); } GLvoid glmMeshGeometricParameters(GLMmodel * mesh, double * centerX, double * centerY, double * centerZ, double * radius) { unsigned int i; *centerX = 0.0; *centerY = 0.0; *centerZ = 0.0; for(i=0; i < mesh->numvertices ; i++) { *centerX += mesh->vertices[3*i+3]; *centerY += mesh->vertices[3*i+4]; *centerZ += mesh->vertices[3*i+5]; } *centerX /= mesh->numvertices; *centerY /= mesh->numvertices; *centerZ /= mesh->numvertices; glmMeshRadius(mesh,*centerX,*centerY,*centerZ,radius); } GLvoid glmMeshRadius(GLMmodel * mesh, double centerX, double centerY,double centerZ, double * radius) { double radius2 = 0.0; unsigned int i; for(i=0; i < mesh->numvertices ; i++) { double dist2 = (centerX-mesh->vertices[3*i+3])*(centerX-mesh->vertices[3*i+3]) + (centerY-mesh->vertices[3*i+4])*(centerY-mesh->vertices[3*i+4]) + (centerZ-mesh->vertices[3*i+5])*(centerZ-mesh->vertices[3*i+5]); if (dist2 > radius2) radius2 = dist2; } *radius = sqrt(radius2); } GLvoid glmMeshData(GLMmodel * mesh, int * numVertices, double ** vertices, int * numTriangles, int ** triangles) { *numVertices = mesh->numvertices; *numTriangles = mesh->numtriangles; *triangles = (int*) malloc (sizeof(int)*3*(*numTriangles)); int pos = 0; GLMgroup * group; group = mesh->groups; while (group) { for (unsigned ii = 0; ii < group->numtriangles; ii++) { GLMtriangle * triangle = &GLM_TRIANGLE(mesh,group->triangles[ii]); (*triangles)[pos] = triangle->vindices[0]-1; pos++; (*triangles)[pos] = triangle->vindices[1]-1; pos++; (*triangles)[pos] = triangle->vindices[2]-1; pos++; } group = group->next; } *vertices = (double*) malloc (sizeof(double) * 3 * (*numVertices)); for(int i=0; i<3*(*numVertices); i++) (*vertices)[i] = mesh->vertices[i+3]; }
2fb54607d90812338c19e4c16596ea00a0627389
b49999cfaf1f8d0b16cae2400d3ab909a57f9d5d
/src/checkqueue.h
e4907dd666f303f5ef0576360e28456258c8ed21
[ "MIT" ]
permissive
Encel-US/Argon2
7f2f27130f091c43e9f35d1ef9c4864ba7eb3a47
6f570adeac4fe61428c5cb795ec3b6b1b440bf4f
refs/heads/master
2021-01-10T17:16:12.857873
2015-12-13T20:07:13
2015-12-13T20:07:13
47,632,573
1
2
null
null
null
null
UTF-8
C++
false
false
6,623
h
// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef CHECKQUEUE_H #define CHECKQUEUE_H #include <boost/thread/mutex.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/condition_variable.hpp> #include <vector> #include <algorithm> template<typename T> class CCheckQueueControl; /** Queue for verifications that have to be performed. * The verifications are represented by a type T, which must provide an * operator(), returning a bool. * * One thread (the master) is assumed to push batches of verifications * onto the queue, where they are processed by N-1 worker threads. When * the master is done adding work, it temporarily joins the worker pool * as an N'th worker, until all jobs are done. */ template<typename T> class CCheckQueue { private: // Mutex to protect the inner state boost::mutex mutex; // Worker threads block on this when out of work boost::condition_variable condWorker; // Master thread blocks on this when out of work boost::condition_variable condMaster; // The queue of elements to be processed. // As the order of booleans doesn't matter, it is used as a LIFO (stack) std::vector<T> queue; // The number of workers (including the master) that are idle. int nIdle; // The total number of workers (including the master). int nTotal; // The temporary evaluation result. bool fAllOk; // Number of verifications that haven't completed yet. // This includes elements that are not anymore in queue, but still in // worker's own batches. unsigned int nTodo; // Whether we're shutting down. bool fQuit; // The maximum number of elements to be processed in one batch unsigned int nBatchSize; // Internal function that does bulk of the verification work. bool Loop(bool fMaster = false) { boost::condition_variable &cond = fMaster ? condMaster : condWorker; std::vector<T> vChecks; vChecks.reserve(nBatchSize); unsigned int nNow = 0; bool fOk = true; do { { boost::unique_lock<boost::mutex> lock(mutex); // first do the clean-up of the previous loop run (allowing us to do it in the same critsect) if (nNow) { fAllOk &= fOk; nTodo -= nNow; if (nTodo == 0 && !fMaster) // We processed the last element; inform the master he can exit and return the result condMaster.notify_one(); } else { // first iteration nTotal++; } // logically, the do loop starts here while (queue.empty()) { if ((fMaster || fQuit) && nTodo == 0) { nTotal--; bool fRet = fAllOk; // reset the status for new work later if (fMaster) fAllOk = true; // return the current status return fRet; } nIdle++; cond.wait(lock); // wait nIdle--; } // Decide how many work units to process now. // * Do not try to do everything at once, but aim for increasingly smaller batches so // all workers finish approximately simultaneously. // * Try to account for idle jobs which will instantly start helping. // * Don't do batches smaller than 1 (duh), or larger than nBatchSize. nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1))); vChecks.resize(nNow); for (unsigned int i = 0; i < nNow; i++) { // We want the lock on the mutex to be as short as possible, so swap jobs from the global // queue to the local batch vector instead of copying. vChecks[i].swap(queue.back()); queue.pop_back(); } // Check whether we need to do work at all fOk = fAllOk; } // execute work BOOST_FOREACH(T &check, vChecks) if (fOk) fOk = check(); vChecks.clear(); } while(true); } public: // Create a new check queue CCheckQueue(unsigned int nBatchSizeIn) : nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {} // Worker thread void Thread() { Loop(); } // Wait until execution finishes, and return whether all evaluations where succesful. bool Wait() { return Loop(true); } // Add a batch of checks to the queue void Add(std::vector<T> &vChecks) { boost::unique_lock<boost::mutex> lock(mutex); BOOST_FOREACH(T &check, vChecks) { queue.push_back(T()); check.swap(queue.back()); } nTodo += vChecks.size(); if (vChecks.size() == 1) condWorker.notify_one(); else if (vChecks.size() > 1) condWorker.notify_all(); } ~CCheckQueue() { } friend class CCheckQueueControl<T>; }; /** RAII-style controller object for a CCheckQueue that guarantees the passed * queue is finished before continuing. */ template<typename T> class CCheckQueueControl { private: CCheckQueue<T> *pqueue; bool fDone; public: CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) { // passed queue is supposed to be unused, or NULL if (pqueue != NULL) { assert(pqueue->nTotal == pqueue->nIdle); assert(pqueue->nTodo == 0); assert(pqueue->fAllOk == true); } } bool Wait() { if (pqueue == NULL) return true; bool fRet = pqueue->Wait(); fDone = true; return fRet; } void Add(std::vector<T> &vChecks) { if (pqueue != NULL) pqueue->Add(vChecks); } ~CCheckQueueControl() { if (!fDone) Wait(); } }; #endif
9e62d0fd9cf6a84a87563cf59e59038cf14ae9a2
33200c9d8b6e2a8f043a0cbb70c0d59bbb9a2583
/A/1049/deprecated.cpp
e82b4d37459a40302461dc91f3d55d5aa437314a
[]
no_license
ParadoxZW/PATexercise
6014cb353f3b88522530388abb0810be4788c6d8
b9c47878edc4e09d1e7e894edc98ece1fda438d4
refs/heads/master
2021-10-11T11:47:17.610599
2021-10-04T12:39:59
2021-10-04T12:39:59
248,163,727
0
0
null
null
null
null
UTF-8
C++
false
false
1,231
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <map> #include <string> #include <vector> #include <algorithm> #include <mat_print.hpp> using namespace std; typedef unsigned int ui; const ui tp[12] = {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; ui basis[12] = {0, 1, 19, 271, 3439, 40951, 468559, 5217031, 56953279, 612579511, 2218248303 }; ui n, l, h, tmp; int calc(int n) { // scanf("%d\n", &n); ui s, h, tmp = n, l = 0; while(tmp > 0){ h = tmp; tmp /= 10; l++; } tmp = basis[l-1]; cout << l << ' ' << h << ' ' << tmp << ' ' << tp[l] << endl; if (h > 1){ s = (h - 1) * tmp + tp[l]; s += calc(n - h*tp[l]); }else{ s = tmp + n - tp[l] + 1; } return s; } int main(void) { for (int i = 1; i < 12; i++) { basis[i] = 10 * basis[i-1] + tp[i]; cout << basis[i] << ' '; } return 0; }
99236aa94d649065e87ce7a66bfe923920388c8c
0d0e78c6262417fb1dff53901c6087b29fe260a0
/vod/include/tencentcloud/vod/v20180717/model/CreateAIRecognitionTemplateResponse.h
7e08552e99fd83786715a2450af628779c51e68e
[ "Apache-2.0" ]
permissive
li5ch/tencentcloud-sdk-cpp
ae35ffb0c36773fd28e1b1a58d11755682ade2ee
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
refs/heads/master
2022-12-04T15:33:08.729850
2020-07-20T00:52:24
2020-07-20T00:52:24
281,135,686
1
0
Apache-2.0
2020-07-20T14:14:47
2020-07-20T14:14:46
null
UTF-8
C++
false
false
2,318
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * 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. */ #ifndef TENCENTCLOUD_VOD_V20180717_MODEL_CREATEAIRECOGNITIONTEMPLATERESPONSE_H_ #define TENCENTCLOUD_VOD_V20180717_MODEL_CREATEAIRECOGNITIONTEMPLATERESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Vod { namespace V20180717 { namespace Model { /** * CreateAIRecognitionTemplate返回参数结构体 */ class CreateAIRecognitionTemplateResponse : public AbstractModel { public: CreateAIRecognitionTemplateResponse(); ~CreateAIRecognitionTemplateResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); /** * 获取视频内容识别模板唯一标识。 * @return Definition 视频内容识别模板唯一标识。 */ int64_t GetDefinition() const; /** * 判断参数 Definition 是否已赋值 * @return Definition 是否已赋值 */ bool DefinitionHasBeenSet() const; private: /** * 视频内容识别模板唯一标识。 */ int64_t m_definition; bool m_definitionHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_VOD_V20180717_MODEL_CREATEAIRECOGNITIONTEMPLATERESPONSE_H_
b821c9ec9f945a06d7c1e4359ffc860344922433
2b74b17112511ce22758bf05b6ec830f83d21a77
/WinReg/WinReg.hpp
0a124d413947244e28542961cbf8e0b6764864f8
[ "MIT" ]
permissive
GiovanniDicanio/WinReg
8399249e24630dba0bc5366d0f039638fed1cdda
a4907f31deaca15ca27cc41e5506f54e9f05d3a4
refs/heads/master
2023-03-22T03:50:59.958785
2022-07-22T17:14:37
2022-07-22T17:14:37
89,014,686
406
108
MIT
2023-03-10T13:38:07
2017-04-21T18:56:18
C++
UTF-8
C++
false
false
85,721
hpp
#ifndef GIOVANNI_DICANIO_WINREG_HPP_INCLUDED #define GIOVANNI_DICANIO_WINREG_HPP_INCLUDED //////////////////////////////////////////////////////////////////////////////// // // *** Modern C++ Wrappers Around Windows Registry C API *** // // Copyright (C) by Giovanni Dicanio // // First version: 2017, January 22nd // Last update: 2022, July 13th // // E-mail: <first name>.<last name> AT REMOVE_THIS gmail.com // // Registry key handles are safely and conveniently wrapped // in the RegKey resource manager C++ class. // // Many methods are available in two forms: // // - One form that signals errors throwing exceptions // of class RegException (e.g. RegKey::Open) // // - Another form that returns RegResult objects (e.g. RegKey::TryOpen) // // In addition, there are also some methods named like TryGet...Value // (e.g. TryGetDwordValue), that _try_ to perform the given query, // and return a RegExpected object. On success, that object contains // the value read from the registry. On failure, the returned RegExpected object // contains a RegResult storing the return code from the Windows Registry API call. // // Unicode UTF-16 strings are represented using the std::wstring class; // ATL's CString is not used, to avoid dependencies from ATL or MFC. // // Compiler: Visual Studio 2019 // C++ Language Standard: C++17 (/std:c++17) // Code compiles cleanly at warning level 4 (/W4) on both 32-bit and 64-bit builds. // // Requires building in Unicode mode (which has been the default since VS2005). // // =========================================================================== // // The MIT License(MIT) // // Copyright(c) 2017-2022 by Giovanni Dicanio // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// #include <Windows.h> // Windows Platform SDK #include <crtdbg.h> // _ASSERTE #include <memory> // std::unique_ptr, std::make_unique #include <string> // std::wstring #include <system_error> // std::system_error #include <utility> // std::swap, std::pair, std::move #include <variant> // std::variant #include <vector> // std::vector namespace winreg { // // Forward Class Declarations // class RegException; class RegResult; template <typename T> class RegExpected; // // Class Declarations // //------------------------------------------------------------------------------ // // Safe, efficient and convenient C++ wrapper around HKEY registry key handles. // // This class is movable but not copyable. // // This class is designed to be very *efficient* and low-overhead, for example: // non-throwing operations are carefully marked as noexcept, so the C++ compiler // can emit optimized code. // // Moreover, this class just wraps a raw HKEY handle, without any // shared-ownership overhead like in std::shared_ptr; you can think of this // class kind of like a std::unique_ptr for HKEYs. // // The class is also swappable (defines a custom non-member swap); // relational operators are properly overloaded as well. // //------------------------------------------------------------------------------ class RegKey { public: // // Construction/Destruction // // Initialize as an empty key handle RegKey() noexcept = default; // Take ownership of the input key handle explicit RegKey(HKEY hKey) noexcept; // Open the given registry key if it exists, else create a new key. // Uses default KEY_READ|KEY_WRITE|KEY_WOW64_64KEY access. // For finer grained control, call the Create() method overloads. // Throw RegException on failure. RegKey(HKEY hKeyParent, const std::wstring& subKey); // Open the given registry key if it exists, else create a new key. // Allow the caller to specify the desired access to the key // (e.g. KEY_READ|KEY_WOW64_64KEY for read-only access). // For finer grained control, call the Create() method overloads. // Throw RegException on failure. RegKey(HKEY hKeyParent, const std::wstring& subKey, REGSAM desiredAccess); // Take ownership of the input key handle. // The input key handle wrapper is reset to an empty state. RegKey(RegKey&& other) noexcept; // Move-assign from the input key handle. // Properly check against self-move-assign (which is safe and does nothing). RegKey& operator=(RegKey&& other) noexcept; // Ban copy RegKey(const RegKey&) = delete; RegKey& operator=(const RegKey&) = delete; // Safely close the wrapped key handle (if any) ~RegKey() noexcept; // // Properties // // Access the wrapped raw HKEY handle [[nodiscard]] HKEY Get() const noexcept; // Is the wrapped HKEY handle valid? [[nodiscard]] bool IsValid() const noexcept; // Same as IsValid(), but allow a short "if (regKey)" syntax [[nodiscard]] explicit operator bool() const noexcept; // Is the wrapped handle a predefined handle (e.g.HKEY_CURRENT_USER) ? [[nodiscard]] bool IsPredefined() const noexcept; // // Operations // // Close current HKEY handle. // If there's no valid handle, do nothing. // This method doesn't close predefined HKEY handles (e.g. HKEY_CURRENT_USER). void Close() noexcept; // Transfer ownership of current HKEY to the caller. // Note that the caller is responsible for closing the key handle! [[nodiscard]] HKEY Detach() noexcept; // Take ownership of the input HKEY handle. // Safely close any previously open handle. // Input key handle can be nullptr. void Attach(HKEY hKey) noexcept; // Non-throwing swap; // Note: There's also a non-member swap overload void SwapWith(RegKey& other) noexcept; // // Wrappers around Windows Registry APIs. // See the official MSDN documentation for these APIs for detailed explanations // of the wrapper method parameters. // // // NOTE on the KEY_WOW64_64KEY flag // ================================ // // By default, a 32-bit application running on 64-bit Windows accesses the 32-bit registry view // and a 64-bit application accesses the 64-bit registry view. // Using this KEY_WOW64_64KEY flag, both 32-bit or 64-bit applications access the 64-bit // registry view. // // MSDN documentation: // https://docs.microsoft.com/en-us/windows/win32/winprog64/accessing-an-alternate-registry-view // // If you want to use the default Windows API behavior, don't OR (|) the KEY_WOW64_64KEY flag // when specifying the desired access (e.g. just pass KEY_READ | KEY_WRITE as the desired // access parameter). // // Wrapper around RegCreateKeyEx, that allows you to specify desired access void Create( HKEY hKeyParent, const std::wstring& subKey, REGSAM desiredAccess = KEY_READ | KEY_WRITE | KEY_WOW64_64KEY ); // Wrapper around RegCreateKeyEx void Create( HKEY hKeyParent, const std::wstring& subKey, REGSAM desiredAccess, DWORD options, SECURITY_ATTRIBUTES* securityAttributes, DWORD* disposition ); // Wrapper around RegOpenKeyEx void Open( HKEY hKeyParent, const std::wstring& subKey, REGSAM desiredAccess = KEY_READ | KEY_WRITE | KEY_WOW64_64KEY ); // Wrapper around RegCreateKeyEx, that allows you to specify desired access [[nodiscard]] RegResult TryCreate( HKEY hKeyParent, const std::wstring& subKey, REGSAM desiredAccess = KEY_READ | KEY_WRITE | KEY_WOW64_64KEY ) noexcept; // Wrapper around RegCreateKeyEx [[nodiscard]] RegResult TryCreate( HKEY hKeyParent, const std::wstring& subKey, REGSAM desiredAccess, DWORD options, SECURITY_ATTRIBUTES* securityAttributes, DWORD* disposition ) noexcept; // Wrapper around RegOpenKeyEx [[nodiscard]] RegResult TryOpen( HKEY hKeyParent, const std::wstring& subKey, REGSAM desiredAccess = KEY_READ | KEY_WRITE | KEY_WOW64_64KEY ) noexcept; // // Registry Value Setters // void SetDwordValue(const std::wstring& valueName, DWORD data); void SetQwordValue(const std::wstring& valueName, const ULONGLONG& data); void SetStringValue(const std::wstring& valueName, const std::wstring& data); void SetExpandStringValue(const std::wstring& valueName, const std::wstring& data); void SetMultiStringValue(const std::wstring& valueName, const std::vector<std::wstring>& data); void SetBinaryValue(const std::wstring& valueName, const std::vector<BYTE>& data); void SetBinaryValue(const std::wstring& valueName, const void* data, DWORD dataSize); // // Registry Value Setters Returning RegResult // (instead of throwing RegException on error) // [[nodiscard]] RegResult TrySetDwordValue(const std::wstring& valueName, DWORD data) noexcept; [[nodiscard]] RegResult TrySetQwordValue(const std::wstring& valueName, const ULONGLONG& data) noexcept; [[nodiscard]] RegResult TrySetStringValue(const std::wstring& valueName, const std::wstring& data) noexcept; [[nodiscard]] RegResult TrySetExpandStringValue(const std::wstring& valueName, const std::wstring& data) noexcept; [[nodiscard]] RegResult TrySetMultiStringValue(const std::wstring& valueName, const std::vector<std::wstring>& data); // Note: The TrySetMultiStringValue method CANNOT be marked noexcept, // because internally the method *dynamically allocates memory* for creating the multi-string // that will be stored in the Registry. [[nodiscard]] RegResult TrySetBinaryValue(const std::wstring& valueName, const std::vector<BYTE>& data) noexcept; [[nodiscard]] RegResult TrySetBinaryValue(const std::wstring& valueName, const void* data, DWORD dataSize) noexcept; // // Registry Value Getters // [[nodiscard]] DWORD GetDwordValue(const std::wstring& valueName) const; [[nodiscard]] ULONGLONG GetQwordValue(const std::wstring& valueName) const; [[nodiscard]] std::wstring GetStringValue(const std::wstring& valueName) const; enum class ExpandStringOption { DontExpand, Expand }; [[nodiscard]] std::wstring GetExpandStringValue( const std::wstring& valueName, ExpandStringOption expandOption = ExpandStringOption::DontExpand ) const; [[nodiscard]] std::vector<std::wstring> GetMultiStringValue(const std::wstring& valueName) const; [[nodiscard]] std::vector<BYTE> GetBinaryValue(const std::wstring& valueName) const; // // Registry Value Getters Returning RegExpected<T> // (instead of throwing RegException on error) // [[nodiscard]] RegExpected<DWORD> TryGetDwordValue(const std::wstring& valueName) const; [[nodiscard]] RegExpected<ULONGLONG> TryGetQwordValue(const std::wstring& valueName) const; [[nodiscard]] RegExpected<std::wstring> TryGetStringValue(const std::wstring& valueName) const; [[nodiscard]] RegExpected<std::wstring> TryGetExpandStringValue( const std::wstring& valueName, ExpandStringOption expandOption = ExpandStringOption::DontExpand ) const; [[nodiscard]] RegExpected<std::vector<std::wstring>> TryGetMultiStringValue(const std::wstring& valueName) const; [[nodiscard]] RegExpected<std::vector<BYTE>> TryGetBinaryValue(const std::wstring& valueName) const; // // Query Operations // // Information about a registry key (retrieved by QueryInfoKey) struct InfoKey { DWORD NumberOfSubKeys; DWORD NumberOfValues; FILETIME LastWriteTime; // Clear the structure fields InfoKey() noexcept : NumberOfSubKeys{0} , NumberOfValues{0} { LastWriteTime.dwHighDateTime = LastWriteTime.dwLowDateTime = 0; } InfoKey(DWORD numberOfSubKeys, DWORD numberOfValues, FILETIME lastWriteTime) noexcept : NumberOfSubKeys{ numberOfSubKeys } , NumberOfValues{ numberOfValues } , LastWriteTime{ lastWriteTime } { } }; // Retrieve information about the registry key [[nodiscard]] InfoKey QueryInfoKey() const; // Return the DWORD type ID for the input registry value [[nodiscard]] DWORD QueryValueType(const std::wstring& valueName) const; enum class KeyReflection { ReflectionEnabled, ReflectionDisabled }; // Determines whether reflection has been disabled or enabled for the specified key [[nodiscard]] KeyReflection QueryReflectionKey() const; // Enumerate the subkeys of the registry key, using RegEnumKeyEx [[nodiscard]] std::vector<std::wstring> EnumSubKeys() const; // Enumerate the values under the registry key, using RegEnumValue. // Returns a vector of pairs: In each pair, the wstring is the value name, // the DWORD is the value type. [[nodiscard]] std::vector<std::pair<std::wstring, DWORD>> EnumValues() const; // // Query Operations Returning RegExpected // (instead of throwing RegException on error) // // Retrieve information about the registry key [[nodiscard]] RegExpected<InfoKey> TryQueryInfoKey() const; // Return the DWORD type ID for the input registry value [[nodiscard]] RegExpected<DWORD> TryQueryValueType(const std::wstring& valueName) const; // Determines whether reflection has been disabled or enabled for the specified key [[nodiscard]] RegExpected<KeyReflection> TryQueryReflectionKey() const; // Enumerate the subkeys of the registry key, using RegEnumKeyEx [[nodiscard]] RegExpected<std::vector<std::wstring>> TryEnumSubKeys() const; // Enumerate the values under the registry key, using RegEnumValue. // Returns a vector of pairs: In each pair, the wstring is the value name, // the DWORD is the value type. [[nodiscard]] RegExpected<std::vector<std::pair<std::wstring, DWORD>>> TryEnumValues() const; // // Misc Registry API Wrappers // void DeleteValue(const std::wstring& valueName); void DeleteKey(const std::wstring& subKey, REGSAM desiredAccess); void DeleteTree(const std::wstring& subKey); void CopyTree(const std::wstring& sourceSubKey, const RegKey& destKey); void FlushKey(); void LoadKey(const std::wstring& subKey, const std::wstring& filename); void SaveKey(const std::wstring& filename, SECURITY_ATTRIBUTES* securityAttributes) const; void EnableReflectionKey(); void DisableReflectionKey(); void ConnectRegistry(const std::wstring& machineName, HKEY hKeyPredefined); // // Misc Registry API Wrappers Returning RegResult Status // (instead of throwing RegException on error) // [[nodiscard]] RegResult TryDeleteValue(const std::wstring& valueName) noexcept; [[nodiscard]] RegResult TryDeleteKey(const std::wstring& subKey, REGSAM desiredAccess) noexcept; [[nodiscard]] RegResult TryDeleteTree(const std::wstring& subKey) noexcept; [[nodiscard]] RegResult TryCopyTree(const std::wstring& sourceSubKey, const RegKey& destKey) noexcept; [[nodiscard]] RegResult TryFlushKey() noexcept; [[nodiscard]] RegResult TryLoadKey(const std::wstring& subKey, const std::wstring& filename) noexcept; [[nodiscard]] RegResult TrySaveKey(const std::wstring& filename, SECURITY_ATTRIBUTES* securityAttributes) const noexcept; [[nodiscard]] RegResult TryEnableReflectionKey() noexcept; [[nodiscard]] RegResult TryDisableReflectionKey() noexcept; [[nodiscard]] RegResult TryConnectRegistry(const std::wstring& machineName, HKEY hKeyPredefined) noexcept; // Return a string representation of Windows registry types [[nodiscard]] static std::wstring RegTypeToString(DWORD regType); // // Relational comparison operators are overloaded as non-members // ==, !=, <, <=, >, >= // // // Private Implementation // private: // The wrapped registry key handle HKEY m_hKey{ nullptr }; }; //------------------------------------------------------------------------------ // An exception representing an error with the registry operations //------------------------------------------------------------------------------ class RegException : public std::system_error { public: RegException(LSTATUS errorCode, const char* message); RegException(LSTATUS errorCode, const std::string& message); }; //------------------------------------------------------------------------------ // A tiny wrapper around LSTATUS return codes used by the Windows Registry API. //------------------------------------------------------------------------------ class RegResult { public: // Initialize to success code (ERROR_SUCCESS) RegResult() noexcept = default; // Initialize with specific Windows Registry API LSTATUS return code explicit RegResult(LSTATUS result) noexcept; // Is the wrapped code a success code? [[nodiscard]] bool IsOk() const noexcept; // Is the wrapped error code a failure code? [[nodiscard]] bool Failed() const noexcept; // Is the wrapped code a success code? [[nodiscard]] explicit operator bool() const noexcept; // Get the wrapped Win32 code [[nodiscard]] LSTATUS Code() const noexcept; // Return the system error message associated to the current error code [[nodiscard]] std::wstring ErrorMessage() const; // Return the system error message associated to the current error code, // using the given input language identifier [[nodiscard]] std::wstring ErrorMessage(DWORD languageId) const; private: // Error code returned by Windows Registry C API; // default initialized to success code. LSTATUS m_result{ ERROR_SUCCESS }; }; //------------------------------------------------------------------------------ // A class template that stores a value of type T (e.g. DWORD, std::wstring) // on success, or a RegResult on error. // // Used as the return value of some Registry RegKey::TryGetXxxValue() methods // as an alternative to exception-throwing methods. //------------------------------------------------------------------------------ template <typename T> class RegExpected { public: // Initialize the object with an error code explicit RegExpected(const RegResult& errorCode) noexcept; // Initialize the object with a value (the success case) explicit RegExpected(const T& value); // Initialize the object with a value (the success case), // optimized for move semantics explicit RegExpected(T&& value); // Does this object contain a valid value? [[nodiscard]] explicit operator bool() const noexcept; // Does this object contain a valid value? [[nodiscard]] bool IsValid() const noexcept; // Access the value (if the object contains a valid value). // Throws an exception if the object is in invalid state. [[nodiscard]] const T& GetValue() const; // Access the error code (if the object contains an error status) // Throws an exception if the object is in valid state. [[nodiscard]] RegResult GetError() const; private: // Stores a value of type T on success, // or RegResult on error std::variant<RegResult, T> m_var; }; //------------------------------------------------------------------------------ // Overloads of relational comparison operators for RegKey //------------------------------------------------------------------------------ inline bool operator==(const RegKey& a, const RegKey& b) noexcept { return a.Get() == b.Get(); } inline bool operator!=(const RegKey& a, const RegKey& b) noexcept { return a.Get() != b.Get(); } inline bool operator<(const RegKey& a, const RegKey& b) noexcept { return a.Get() < b.Get(); } inline bool operator<=(const RegKey& a, const RegKey& b) noexcept { return a.Get() <= b.Get(); } inline bool operator>(const RegKey& a, const RegKey& b) noexcept { return a.Get() > b.Get(); } inline bool operator>=(const RegKey& a, const RegKey& b) noexcept { return a.Get() >= b.Get(); } //------------------------------------------------------------------------------ // Private Helper Classes and Functions //------------------------------------------------------------------------------ namespace detail { //------------------------------------------------------------------------------ // Simple scoped-based RAII wrapper that *automatically* invokes LocalFree() // in its destructor. //------------------------------------------------------------------------------ template <typename T> class ScopedLocalFree { public: typedef T Type; typedef T* TypePtr; // Init wrapped pointer to nullptr ScopedLocalFree() noexcept = default; // Automatically and safely invoke ::LocalFree() ~ScopedLocalFree() noexcept { Free(); } // // Ban copy and move operations // ScopedLocalFree(const ScopedLocalFree&) = delete; ScopedLocalFree(ScopedLocalFree&&) = delete; ScopedLocalFree& operator=(const ScopedLocalFree&) = delete; ScopedLocalFree& operator=(ScopedLocalFree&&) = delete; // Read-only access to the wrapped pointer [[nodiscard]] T* Get() const noexcept { return m_ptr; } // Writable access to the wrapped pointer [[nodiscard]] T** AddressOf() noexcept { return &m_ptr; } // Explicit pointer conversion to bool explicit operator bool() const noexcept { return (m_ptr != nullptr); } // Safely invoke ::LocalFree() on the wrapped pointer void Free() noexcept { if (m_ptr != nullptr) { ::LocalFree(m_ptr); m_ptr = nullptr; } } // // IMPLEMENTATION // private: T* m_ptr{ nullptr }; }; //------------------------------------------------------------------------------ // Helper function to build a multi-string from a vector<wstring>. // // A multi-string is a sequence of contiguous NUL-terminated strings, // that terminates with an additional NUL. // Basically, considered as a whole, the sequence is terminated by two NULs. // E.g.: // Hello\0World\0\0 //------------------------------------------------------------------------------ [[nodiscard]] inline std::vector<wchar_t> BuildMultiString(const std::vector<std::wstring>& data) { // Special case of the empty multi-string if (data.empty()) { // Build a vector containing just two NULs return std::vector<wchar_t>(2, L'\0'); } // Get the total length in wchar_ts of the multi-string size_t totalLen = 0; for (const auto& s : data) { // Add one to current string's length for the terminating NUL totalLen += (s.length() + 1); } // Add one for the last NUL terminator (making the whole structure double-NUL terminated) totalLen++; // Allocate a buffer to store the multi-string std::vector<wchar_t> multiString; // Reserve room in the vector to speed up the following insertion loop multiString.reserve(totalLen); // Copy the single strings into the multi-string for (const auto& s : data) { if (!s.empty()) { // Copy current string's content multiString.insert(multiString.end(), s.begin(), s.end()); } // Don't forget to NUL-terminate the current string // (or just insert L'\0' for empty strings) multiString.emplace_back(L'\0'); } // Add the last NUL-terminator multiString.emplace_back(L'\0'); return multiString; } //------------------------------------------------------------------------------ // Return true if the wchar_t sequence stored in 'data' terminates // with two null (L'\0') wchar_t's //------------------------------------------------------------------------------ [[nodiscard]] inline bool IsDoubleNullTerminated(const std::vector<wchar_t>& data) { // First check that there's enough room for at least two nulls if (data.size() < 2) { return false; } // Check that the sequence terminates with two nulls (L'\0', L'\0') const size_t lastPosition = data.size() - 1; return ((data[lastPosition] == L'\0') && (data[lastPosition - 1] == L'\0')) ? true : false; } //------------------------------------------------------------------------------ // Given a sequence of wchar_ts representing a double-null-terminated string, // returns a vector of wstrings that represent the single strings. // // Also supports embedded empty strings in the sequence. //------------------------------------------------------------------------------ [[nodiscard]] inline std::vector<std::wstring> ParseMultiString(const std::vector<wchar_t>& data) { // Make sure that there are two terminating L'\0's at the end of the sequence if (!IsDoubleNullTerminated(data)) { throw RegException{ ERROR_INVALID_DATA, "Not a double-null terminated string." }; } // Parse the double-NUL-terminated string into a vector<wstring>, // which will be returned to the caller std::vector<std::wstring> result; // // Note on Embedded Empty Strings // ============================== // // Below commented-out there is the previous parsing code, // that assumes that an empty string *terminates* the sequence. // // In fact, according to the official Microsoft MSDN documentation, // an empty string is treated as a sequence terminator, // so you can't have empty strings inside the sequence. // // Source: https://docs.microsoft.com/en-us/windows/win32/sysinfo/registry-value-types // "A REG_MULTI_SZ string ends with a string of length 0. // Therefore, it is not possible to include a zero-length string // in the sequence. An empty sequence would be defined as follows: \0." // // Unfortunately, it seems that Microsoft violates its own rule, for example // in the PendingFileRenameOperations value under the // "SYSTEM\CurrentControlSet\Control\Session Manager" key. // This is a REG_MULTI_SZ value that does contain embedded empty strings. // // So, I changed the previous parsing code to support also embedded empty strings. // // ------------------------------------------------------------------------- //// *** Previous parsing code - Assumes an empty string terminates the sequence *** // //const wchar_t* currStringPtr = data.data(); //while (*currStringPtr != L'\0') //{ // // Current string is NUL-terminated, so get its length calling wcslen // const size_t currStringLength = wcslen(currStringPtr); // // // Add current string to the result vector // result.emplace_back(currStringPtr, currStringLength); // // // Move to the next string // currStringPtr += currStringLength + 1; //} // ------------------------------------------------------------------------- // const wchar_t* currStringPtr = data.data(); const wchar_t* const endPtr = data.data() + data.size() - 1; while (currStringPtr < endPtr) { // Current string is NUL-terminated, so get its length calling wcslen const size_t currStringLength = wcslen(currStringPtr); // Add current string to the result vector if (currStringLength > 0) { result.emplace_back(currStringPtr, currStringLength); } else { // Insert empty strings, as well result.emplace_back(std::wstring{}); } // Move to the next string, skipping the terminating NUL currStringPtr += currStringLength + 1; } return result; } //------------------------------------------------------------------------------ // Builds a RegExpected object that stores an error code //------------------------------------------------------------------------------ template <typename T> [[nodiscard]] inline RegExpected<T> MakeRegExpectedWithError(const LSTATUS retCode) { return RegExpected<T>{ RegResult{ retCode } }; } } // namespace detail //------------------------------------------------------------------------------ // RegKey Inline Methods //------------------------------------------------------------------------------ inline RegKey::RegKey(const HKEY hKey) noexcept : m_hKey{ hKey } { } inline RegKey::RegKey(const HKEY hKeyParent, const std::wstring& subKey) { Create(hKeyParent, subKey); } inline RegKey::RegKey(const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess) { Create(hKeyParent, subKey, desiredAccess); } inline RegKey::RegKey(RegKey&& other) noexcept : m_hKey{ other.m_hKey } { // Other doesn't own the handle anymore other.m_hKey = nullptr; } inline RegKey& RegKey::operator=(RegKey&& other) noexcept { // Prevent self-move-assign if ((this != &other) && (m_hKey != other.m_hKey)) { // Close current Close(); // Move from other (i.e. take ownership of other's raw handle) m_hKey = other.m_hKey; other.m_hKey = nullptr; } return *this; } inline RegKey::~RegKey() noexcept { // Release the owned handle (if any) Close(); } inline HKEY RegKey::Get() const noexcept { return m_hKey; } inline void RegKey::Close() noexcept { if (IsValid()) { // Do not call RegCloseKey on predefined keys if (! IsPredefined()) { ::RegCloseKey(m_hKey); } // Avoid dangling references m_hKey = nullptr; } } inline bool RegKey::IsValid() const noexcept { return m_hKey != nullptr; } inline RegKey::operator bool() const noexcept { return IsValid(); } inline bool RegKey::IsPredefined() const noexcept { // Predefined keys // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724836(v=vs.85).aspx if ( (m_hKey == HKEY_CURRENT_USER) || (m_hKey == HKEY_LOCAL_MACHINE) || (m_hKey == HKEY_CLASSES_ROOT) || (m_hKey == HKEY_CURRENT_CONFIG) || (m_hKey == HKEY_CURRENT_USER_LOCAL_SETTINGS) || (m_hKey == HKEY_PERFORMANCE_DATA) || (m_hKey == HKEY_PERFORMANCE_NLSTEXT) || (m_hKey == HKEY_PERFORMANCE_TEXT) || (m_hKey == HKEY_USERS)) { return true; } return false; } inline HKEY RegKey::Detach() noexcept { HKEY hKey = m_hKey; // We don't own the HKEY handle anymore m_hKey = nullptr; // Transfer ownership to the caller return hKey; } inline void RegKey::Attach(const HKEY hKey) noexcept { // Prevent self-attach if (m_hKey != hKey) { // Close any open registry handle Close(); // Take ownership of the input hKey m_hKey = hKey; } } inline void RegKey::SwapWith(RegKey& other) noexcept { // Enable ADL (not necessary in this case, but good practice) using std::swap; // Swap the raw handle members swap(m_hKey, other.m_hKey); } inline void swap(RegKey& a, RegKey& b) noexcept { a.SwapWith(b); } inline void RegKey::Create( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess ) { constexpr DWORD kDefaultOptions = REG_OPTION_NON_VOLATILE; Create(hKeyParent, subKey, desiredAccess, kDefaultOptions, nullptr, // no security attributes, nullptr // no disposition ); } inline void RegKey::Create( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess, const DWORD options, SECURITY_ATTRIBUTES* const securityAttributes, DWORD* const disposition ) { HKEY hKey = nullptr; LSTATUS retCode = ::RegCreateKeyExW( hKeyParent, subKey.c_str(), 0, // reserved REG_NONE, // user-defined class type parameter not supported options, desiredAccess, securityAttributes, &hKey, disposition ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegCreateKeyExW failed." }; } // Safely close any previously opened key Close(); // Take ownership of the newly created key m_hKey = hKey; } inline void RegKey::Open( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess ) { HKEY hKey = nullptr; LSTATUS retCode = ::RegOpenKeyExW( hKeyParent, subKey.c_str(), REG_NONE, // default options desiredAccess, &hKey ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegOpenKeyExW failed." }; } // Safely close any previously opened key Close(); // Take ownership of the newly created key m_hKey = hKey; } inline RegResult RegKey::TryCreate( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess ) noexcept { constexpr DWORD kDefaultOptions = REG_OPTION_NON_VOLATILE; return TryCreate(hKeyParent, subKey, desiredAccess, kDefaultOptions, nullptr, // no security attributes, nullptr // no disposition ); } inline RegResult RegKey::TryCreate( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess, const DWORD options, SECURITY_ATTRIBUTES* const securityAttributes, DWORD* const disposition ) noexcept { HKEY hKey = nullptr; RegResult retCode{ ::RegCreateKeyExW( hKeyParent, subKey.c_str(), 0, // reserved REG_NONE, // user-defined class type parameter not supported options, desiredAccess, securityAttributes, &hKey, disposition ) }; if (retCode.Failed()) { return retCode; } // Safely close any previously opened key Close(); // Take ownership of the newly created key m_hKey = hKey; _ASSERTE(retCode.IsOk()); return retCode; } inline RegResult RegKey::TryOpen( const HKEY hKeyParent, const std::wstring& subKey, const REGSAM desiredAccess ) noexcept { HKEY hKey = nullptr; RegResult retCode{ ::RegOpenKeyExW( hKeyParent, subKey.c_str(), REG_NONE, // default options desiredAccess, &hKey ) }; if (retCode.Failed()) { return retCode; } // Safely close any previously opened key Close(); // Take ownership of the newly created key m_hKey = hKey; _ASSERTE(retCode.IsOk()); return retCode; } inline void RegKey::SetDwordValue(const std::wstring& valueName, const DWORD data) { _ASSERTE(IsValid()); LSTATUS retCode = ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_DWORD, reinterpret_cast<const BYTE*>(&data), sizeof(data) ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot write DWORD value: RegSetValueExW failed." }; } } inline void RegKey::SetQwordValue(const std::wstring& valueName, const ULONGLONG& data) { _ASSERTE(IsValid()); LSTATUS retCode = ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_QWORD, reinterpret_cast<const BYTE*>(&data), sizeof(data) ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot write QWORD value: RegSetValueExW failed." }; } } inline void RegKey::SetStringValue(const std::wstring& valueName, const std::wstring& data) { _ASSERTE(IsValid()); // String size including the terminating NUL, in bytes const DWORD dataSize = static_cast<DWORD>((data.length() + 1) * sizeof(wchar_t)); LSTATUS retCode = ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_SZ, reinterpret_cast<const BYTE*>(data.c_str()), dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot write string value: RegSetValueExW failed." }; } } inline void RegKey::SetExpandStringValue(const std::wstring& valueName, const std::wstring& data) { _ASSERTE(IsValid()); // String size including the terminating NUL, in bytes const DWORD dataSize = static_cast<DWORD>((data.length() + 1) * sizeof(wchar_t)); LSTATUS retCode = ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_EXPAND_SZ, reinterpret_cast<const BYTE*>(data.c_str()), dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot write expand string value: RegSetValueExW failed." }; } } inline void RegKey::SetMultiStringValue( const std::wstring& valueName, const std::vector<std::wstring>& data ) { _ASSERTE(IsValid()); // First, we have to build a double-NUL-terminated multi-string from the input data const std::vector<wchar_t> multiString = detail::BuildMultiString(data); // Total size, in bytes, of the whole multi-string structure const DWORD dataSize = static_cast<DWORD>(multiString.size() * sizeof(wchar_t)); LSTATUS retCode = ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_MULTI_SZ, reinterpret_cast<const BYTE*>(multiString.data()), dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot write multi-string value: RegSetValueExW failed." }; } } inline void RegKey::SetBinaryValue(const std::wstring& valueName, const std::vector<BYTE>& data) { _ASSERTE(IsValid()); // Total data size, in bytes const DWORD dataSize = static_cast<DWORD>(data.size()); LSTATUS retCode = ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_BINARY, data.data(), dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot write binary data value: RegSetValueExW failed." }; } } inline void RegKey::SetBinaryValue( const std::wstring& valueName, const void* const data, const DWORD dataSize ) { _ASSERTE(IsValid()); LSTATUS retCode = ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_BINARY, static_cast<const BYTE*>(data), dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot write binary data value: RegSetValueExW failed." }; } } inline RegResult RegKey::TrySetDwordValue(const std::wstring& valueName, const DWORD data) noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_DWORD, reinterpret_cast<const BYTE*>(&data), sizeof(data) ) }; } inline RegResult RegKey::TrySetQwordValue(const std::wstring& valueName, const ULONGLONG& data) noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_QWORD, reinterpret_cast<const BYTE*>(&data), sizeof(data) ) }; } inline RegResult RegKey::TrySetStringValue(const std::wstring& valueName, const std::wstring& data) noexcept { _ASSERTE(IsValid()); // String size including the terminating NUL, in bytes const DWORD dataSize = static_cast<DWORD>((data.length() + 1) * sizeof(wchar_t)); return RegResult{ ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_SZ, reinterpret_cast<const BYTE*>(data.c_str()), dataSize ) }; } inline RegResult RegKey::TrySetExpandStringValue(const std::wstring& valueName, const std::wstring& data) noexcept { _ASSERTE(IsValid()); // String size including the terminating NUL, in bytes const DWORD dataSize = static_cast<DWORD>((data.length() + 1) * sizeof(wchar_t)); return RegResult{ ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_EXPAND_SZ, reinterpret_cast<const BYTE*>(data.c_str()), dataSize ) }; } inline RegResult RegKey::TrySetMultiStringValue(const std::wstring& valueName, const std::vector<std::wstring>& data) { _ASSERTE(IsValid()); // First, we have to build a double-NUL-terminated multi-string from the input data. // // NOTE: This is the reason why I *cannot* mark this method noexcept, // since a *dynamic allocation* happens for creating the std::vector in BuildMultiString. // And, if dynamic memory allocations fail, an exception is thrown. // const std::vector<wchar_t> multiString = detail::BuildMultiString(data); // Total size, in bytes, of the whole multi-string structure const DWORD dataSize = static_cast<DWORD>(multiString.size() * sizeof(wchar_t)); return RegResult{ ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_MULTI_SZ, reinterpret_cast<const BYTE*>(multiString.data()), dataSize ) }; } inline RegResult RegKey::TrySetBinaryValue(const std::wstring& valueName, const std::vector<BYTE>& data) noexcept { _ASSERTE(IsValid()); // Total data size, in bytes const DWORD dataSize = static_cast<DWORD>(data.size()); return RegResult{ ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_BINARY, data.data(), dataSize ) }; } inline RegResult RegKey::TrySetBinaryValue(const std::wstring& valueName, const void* const data, const DWORD dataSize) noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegSetValueExW( m_hKey, valueName.c_str(), 0, // reserved REG_BINARY, static_cast<const BYTE*>(data), dataSize ) }; } inline DWORD RegKey::GetDwordValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); DWORD data = 0; // to be read from the registry DWORD dataSize = sizeof(data); // size of data, in bytes constexpr DWORD flags = RRF_RT_REG_DWORD; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &data, &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get DWORD value: RegGetValueW failed." }; } return data; } inline ULONGLONG RegKey::GetQwordValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); ULONGLONG data = 0; // to be read from the registry DWORD dataSize = sizeof(data); // size of data, in bytes constexpr DWORD flags = RRF_RT_REG_QWORD; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &data, &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get QWORD value: RegGetValueW failed." }; } return data; } inline std::wstring RegKey::GetStringValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); // Get the size of the result string DWORD dataSize = 0; // size of data, in bytes constexpr DWORD flags = RRF_RT_REG_SZ; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get size of string value: RegGetValueW failed." }; } // Allocate a string of proper size. // Note that dataSize is in bytes and includes the terminating NUL; // we have to convert the size from bytes to wchar_ts for wstring::resize. std::wstring result(dataSize / sizeof(wchar_t), L' '); // Call RegGetValue for the second time to read the string's content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required result.data(), // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get string value: RegGetValueW failed." }; } // Remove the NUL terminator scribbled by RegGetValue from the wstring result.resize((dataSize / sizeof(wchar_t)) - 1); return result; } inline std::wstring RegKey::GetExpandStringValue( const std::wstring& valueName, const ExpandStringOption expandOption ) const { _ASSERTE(IsValid()); DWORD flags = RRF_RT_REG_EXPAND_SZ; // Adjust the flag for RegGetValue considering the expand string option specified by the caller if (expandOption == ExpandStringOption::DontExpand) { flags |= RRF_NOEXPAND; } // Get the size of the result string DWORD dataSize = 0; // size of data, in bytes LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get size of expand string value: RegGetValueW failed." }; } // Allocate a string of proper size. // Note that dataSize is in bytes and includes the terminating NUL. // We must convert from bytes to wchar_ts for wstring::resize. std::wstring result(dataSize / sizeof(wchar_t), L' '); // Call RegGetValue for the second time to read the string's content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required result.data(), // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get expand string value: RegGetValueW failed." }; } // Remove the NUL terminator scribbled by RegGetValue from the wstring result.resize((dataSize / sizeof(wchar_t)) - 1); return result; } inline std::vector<std::wstring> RegKey::GetMultiStringValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); // Request the size of the multi-string, in bytes DWORD dataSize = 0; constexpr DWORD flags = RRF_RT_REG_MULTI_SZ; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get size of multi-string value: RegGetValueW failed." }; } // Allocate room for the result multi-string. // Note that dataSize is in bytes, but our vector<wchar_t>::resize method requires size // to be expressed in wchar_ts. std::vector<wchar_t> data(dataSize / sizeof(wchar_t), L' '); // Read the multi-string from the registry into the vector object retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // no type required data.data(), // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get multi-string value: RegGetValueW failed." }; } // Resize vector to the actual size returned by GetRegValue. // Note that the vector is a vector of wchar_ts, instead the size returned by GetRegValue // is in bytes, so we have to scale from bytes to wchar_t count. data.resize(dataSize / sizeof(wchar_t)); // Convert the double-null-terminated string structure to a vector<wstring>, // and return that back to the caller return detail::ParseMultiString(data); } inline std::vector<BYTE> RegKey::GetBinaryValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); // Get the size of the binary data DWORD dataSize = 0; // size of data, in bytes constexpr DWORD flags = RRF_RT_REG_BINARY; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get size of binary data: RegGetValueW failed." }; } // Allocate a buffer of proper size to store the binary data std::vector<BYTE> data(dataSize); // Handle the special case of zero-length binary data: // If the binary data value in the registry is empty, just return if (dataSize == 0) { _ASSERTE(data.empty()); return data; } // Call RegGetValue for the second time to read the data content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required data.data(), // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get binary data: RegGetValueW failed." }; } return data; } inline RegExpected<DWORD> RegKey::TryGetDwordValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); using RegValueType = DWORD; DWORD data = 0; // to be read from the registry DWORD dataSize = sizeof(data); // size of data, in bytes constexpr DWORD flags = RRF_RT_REG_DWORD; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &data, &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } return RegExpected<RegValueType>{ data }; } inline RegExpected<ULONGLONG> RegKey::TryGetQwordValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); using RegValueType = ULONGLONG; ULONGLONG data = 0; // to be read from the registry DWORD dataSize = sizeof(data); // size of data, in bytes constexpr DWORD flags = RRF_RT_REG_QWORD; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required &data, &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } return RegExpected<RegValueType>{ data }; } inline RegExpected<std::wstring> RegKey::TryGetStringValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); using RegValueType = std::wstring; // Get the size of the result string DWORD dataSize = 0; // size of data, in bytes constexpr DWORD flags = RRF_RT_REG_SZ; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } // Allocate a string of proper size. // Note that dataSize is in bytes and includes the terminating NUL; // we have to convert the size from bytes to wchar_ts for wstring::resize. std::wstring result(dataSize / sizeof(wchar_t), L' '); // Call RegGetValue for the second time to read the string's content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required result.data(), // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } // Remove the NUL terminator scribbled by RegGetValue from the wstring result.resize((dataSize / sizeof(wchar_t)) - 1); return RegExpected<RegValueType>{ result }; } inline RegExpected<std::wstring> RegKey::TryGetExpandStringValue( const std::wstring& valueName, const ExpandStringOption expandOption ) const { _ASSERTE(IsValid()); using RegValueType = std::wstring; DWORD flags = RRF_RT_REG_EXPAND_SZ; // Adjust the flag for RegGetValue considering the expand string option specified by the caller if (expandOption == ExpandStringOption::DontExpand) { flags |= RRF_NOEXPAND; } // Get the size of the result string DWORD dataSize = 0; // size of data, in bytes LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } // Allocate a string of proper size. // Note that dataSize is in bytes and includes the terminating NUL. // We must convert from bytes to wchar_ts for wstring::resize. std::wstring result(dataSize / sizeof(wchar_t), L' '); // Call RegGetValue for the second time to read the string's content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required result.data(), // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } // Remove the NUL terminator scribbled by RegGetValue from the wstring result.resize((dataSize / sizeof(wchar_t)) - 1); return RegExpected<RegValueType>{ result }; } inline RegExpected<std::vector<std::wstring>> RegKey::TryGetMultiStringValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); using RegValueType = std::vector<std::wstring>; // Request the size of the multi-string, in bytes DWORD dataSize = 0; constexpr DWORD flags = RRF_RT_REG_MULTI_SZ; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } // Allocate room for the result multi-string. // Note that dataSize is in bytes, but our vector<wchar_t>::resize method requires size // to be expressed in wchar_ts. std::vector<wchar_t> data(dataSize / sizeof(wchar_t), L' '); // Read the multi-string from the registry into the vector object retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // no type required data.data(), // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } // Resize vector to the actual size returned by GetRegValue. // Note that the vector is a vector of wchar_ts, instead the size returned by GetRegValue // is in bytes, so we have to scale from bytes to wchar_t count. data.resize(dataSize / sizeof(wchar_t)); // Convert the double-null-terminated string structure to a vector<wstring>, // and return that back to the caller return RegExpected<RegValueType>{ detail::ParseMultiString(data) }; } inline RegExpected<std::vector<BYTE>> RegKey::TryGetBinaryValue(const std::wstring& valueName) const { _ASSERTE(IsValid()); using RegValueType = std::vector<BYTE>; // Get the size of the binary data DWORD dataSize = 0; // size of data, in bytes constexpr DWORD flags = RRF_RT_REG_BINARY; LSTATUS retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required nullptr, // output buffer not needed now &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } // Allocate a buffer of proper size to store the binary data std::vector<BYTE> data(dataSize); // Handle the special case of zero-length binary data: // If the binary data value in the registry is empty, just return if (dataSize == 0) { _ASSERTE(data.empty()); return RegExpected<RegValueType>{ data }; } // Call RegGetValue for the second time to read the data content retCode = ::RegGetValueW( m_hKey, nullptr, // no subkey valueName.c_str(), flags, nullptr, // type not required data.data(), // output buffer &dataSize ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<RegValueType>(retCode); } return RegExpected<RegValueType>{ data }; } inline std::vector<std::wstring> RegKey::EnumSubKeys() const { _ASSERTE(IsValid()); // Get some useful enumeration info, like the total number of subkeys // and the maximum length of the subkey names DWORD subKeyCount = 0; DWORD maxSubKeyNameLen = 0; LSTATUS retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, // no user-defined class nullptr, // no user-defined class size nullptr, // reserved &subKeyCount, &maxSubKeyNameLen, nullptr, // no subkey class length nullptr, // no value count nullptr, // no value name max length nullptr, // no max value length nullptr, // no security descriptor nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegQueryInfoKeyW failed while preparing for subkey enumeration." }; } // NOTE: According to the MSDN documentation, the size returned for subkey name max length // does *not* include the terminating NUL, so let's add +1 to take it into account // when I allocate the buffer for reading subkey names. maxSubKeyNameLen++; // Preallocate a buffer for the subkey names auto nameBuffer = std::make_unique<wchar_t[]>(maxSubKeyNameLen); // The result subkey names will be stored here std::vector<std::wstring> subkeyNames; // Reserve room in the vector to speed up the following insertion loop subkeyNames.reserve(subKeyCount); // Enumerate all the subkeys for (DWORD index = 0; index < subKeyCount; index++) { // Get the name of the current subkey DWORD subKeyNameLen = maxSubKeyNameLen; retCode = ::RegEnumKeyExW( m_hKey, index, nameBuffer.get(), &subKeyNameLen, nullptr, // reserved nullptr, // no class nullptr, // no class nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot enumerate subkeys: RegEnumKeyExW failed." }; } // On success, the ::RegEnumKeyEx API writes the length of the // subkey name in the subKeyNameLen output parameter // (not including the terminating NUL). // So I can build a wstring based on that length. subkeyNames.emplace_back(nameBuffer.get(), subKeyNameLen); } return subkeyNames; } inline std::vector<std::pair<std::wstring, DWORD>> RegKey::EnumValues() const { _ASSERTE(IsValid()); // Get useful enumeration info, like the total number of values // and the maximum length of the value names DWORD valueCount = 0; DWORD maxValueNameLen = 0; LSTATUS retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, // no user-defined class nullptr, // no user-defined class size nullptr, // reserved nullptr, // no subkey count nullptr, // no subkey max length nullptr, // no subkey class length &valueCount, &maxValueNameLen, nullptr, // no max value length nullptr, // no security descriptor nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegQueryInfoKeyW failed while preparing for value enumeration." }; } // NOTE: According to the MSDN documentation, the size returned for value name max length // does *not* include the terminating NUL, so let's add +1 to take it into account // when I allocate the buffer for reading value names. maxValueNameLen++; // Preallocate a buffer for the value names auto nameBuffer = std::make_unique<wchar_t[]>(maxValueNameLen); // The value names and types will be stored here std::vector<std::pair<std::wstring, DWORD>> valueInfo; // Reserve room in the vector to speed up the following insertion loop valueInfo.reserve(valueCount); // Enumerate all the values for (DWORD index = 0; index < valueCount; index++) { // Get the name and the type of the current value DWORD valueNameLen = maxValueNameLen; DWORD valueType = 0; retCode = ::RegEnumValueW( m_hKey, index, nameBuffer.get(), &valueNameLen, nullptr, // reserved &valueType, nullptr, // no data nullptr // no data size ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot enumerate values: RegEnumValueW failed." }; } // On success, the RegEnumValue API writes the length of the // value name in the valueNameLen output parameter // (not including the terminating NUL). // So we can build a wstring based on that. valueInfo.emplace_back( std::wstring{ nameBuffer.get(), valueNameLen }, valueType ); } return valueInfo; } inline RegExpected<std::vector<std::wstring>> RegKey::TryEnumSubKeys() const { _ASSERTE(IsValid()); using ReturnType = std::vector<std::wstring>; // Get some useful enumeration info, like the total number of subkeys // and the maximum length of the subkey names DWORD subKeyCount = 0; DWORD maxSubKeyNameLen = 0; LSTATUS retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, // no user-defined class nullptr, // no user-defined class size nullptr, // reserved &subKeyCount, &maxSubKeyNameLen, nullptr, // no subkey class length nullptr, // no value count nullptr, // no value name max length nullptr, // no max value length nullptr, // no security descriptor nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<ReturnType>(retCode); } // NOTE: According to the MSDN documentation, the size returned for subkey name max length // does *not* include the terminating NUL, so let's add +1 to take it into account // when I allocate the buffer for reading subkey names. maxSubKeyNameLen++; // Preallocate a buffer for the subkey names auto nameBuffer = std::make_unique<wchar_t[]>(maxSubKeyNameLen); // The result subkey names will be stored here std::vector<std::wstring> subkeyNames; // Reserve room in the vector to speed up the following insertion loop subkeyNames.reserve(subKeyCount); // Enumerate all the subkeys for (DWORD index = 0; index < subKeyCount; index++) { // Get the name of the current subkey DWORD subKeyNameLen = maxSubKeyNameLen; retCode = ::RegEnumKeyExW( m_hKey, index, nameBuffer.get(), &subKeyNameLen, nullptr, // reserved nullptr, // no class nullptr, // no class nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<ReturnType>(retCode); } // On success, the ::RegEnumKeyEx API writes the length of the // subkey name in the subKeyNameLen output parameter // (not including the terminating NUL). // So I can build a wstring based on that length. subkeyNames.emplace_back(nameBuffer.get(), subKeyNameLen); } return RegExpected<ReturnType>{ subkeyNames }; } inline RegExpected<std::vector<std::pair<std::wstring, DWORD>>> RegKey::TryEnumValues() const { _ASSERTE(IsValid()); using ReturnType = std::vector<std::pair<std::wstring, DWORD>>; // Get useful enumeration info, like the total number of values // and the maximum length of the value names DWORD valueCount = 0; DWORD maxValueNameLen = 0; LSTATUS retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, // no user-defined class nullptr, // no user-defined class size nullptr, // reserved nullptr, // no subkey count nullptr, // no subkey max length nullptr, // no subkey class length &valueCount, &maxValueNameLen, nullptr, // no max value length nullptr, // no security descriptor nullptr // no last write time ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<ReturnType>(retCode); } // NOTE: According to the MSDN documentation, the size returned for value name max length // does *not* include the terminating NUL, so let's add +1 to take it into account // when I allocate the buffer for reading value names. maxValueNameLen++; // Preallocate a buffer for the value names auto nameBuffer = std::make_unique<wchar_t[]>(maxValueNameLen); // The value names and types will be stored here std::vector<std::pair<std::wstring, DWORD>> valueInfo; // Reserve room in the vector to speed up the following insertion loop valueInfo.reserve(valueCount); // Enumerate all the values for (DWORD index = 0; index < valueCount; index++) { // Get the name and the type of the current value DWORD valueNameLen = maxValueNameLen; DWORD valueType = 0; retCode = ::RegEnumValueW( m_hKey, index, nameBuffer.get(), &valueNameLen, nullptr, // reserved &valueType, nullptr, // no data nullptr // no data size ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<ReturnType>(retCode); } // On success, the RegEnumValue API writes the length of the // value name in the valueNameLen output parameter // (not including the terminating NUL). // So we can build a wstring based on that. valueInfo.emplace_back( std::wstring{ nameBuffer.get(), valueNameLen }, valueType ); } return RegExpected<ReturnType>{ valueInfo }; } inline DWORD RegKey::QueryValueType(const std::wstring& valueName) const { _ASSERTE(IsValid()); DWORD typeId = 0; // will be returned by RegQueryValueEx LSTATUS retCode = ::RegQueryValueExW( m_hKey, valueName.c_str(), nullptr, // reserved &typeId, nullptr, // not interested nullptr // not interested ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "Cannot get the value type: RegQueryValueExW failed." }; } return typeId; } inline RegExpected<DWORD> RegKey::TryQueryValueType(const std::wstring& valueName) const { _ASSERTE(IsValid()); using ReturnType = DWORD; DWORD typeId = 0; // will be returned by RegQueryValueEx LSTATUS retCode = ::RegQueryValueExW( m_hKey, valueName.c_str(), nullptr, // reserved &typeId, nullptr, // not interested nullptr // not interested ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<ReturnType>(retCode); } return RegExpected<ReturnType>{ typeId }; } inline RegKey::InfoKey RegKey::QueryInfoKey() const { _ASSERTE(IsValid()); InfoKey infoKey{}; LSTATUS retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, nullptr, nullptr, &(infoKey.NumberOfSubKeys), nullptr, nullptr, &(infoKey.NumberOfValues), nullptr, nullptr, nullptr, &(infoKey.LastWriteTime) ); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegQueryInfoKeyW failed." }; } return infoKey; } inline RegExpected<RegKey::InfoKey> RegKey::TryQueryInfoKey() const { _ASSERTE(IsValid()); using ReturnType = RegKey::InfoKey; InfoKey infoKey{}; LSTATUS retCode = ::RegQueryInfoKeyW( m_hKey, nullptr, nullptr, nullptr, &(infoKey.NumberOfSubKeys), nullptr, nullptr, &(infoKey.NumberOfValues), nullptr, nullptr, nullptr, &(infoKey.LastWriteTime) ); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<ReturnType>(retCode); } return RegExpected<ReturnType>{ infoKey }; } inline RegKey::KeyReflection RegKey::QueryReflectionKey() const { BOOL isReflectionDisabled = FALSE; LSTATUS retCode = ::RegQueryReflectionKey(m_hKey, &isReflectionDisabled); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegQueryReflectionKey failed." }; } return (isReflectionDisabled ? KeyReflection::ReflectionDisabled : KeyReflection::ReflectionEnabled); } inline RegExpected<RegKey::KeyReflection> RegKey::TryQueryReflectionKey() const { using ReturnType = RegKey::KeyReflection; BOOL isReflectionDisabled = FALSE; LSTATUS retCode = ::RegQueryReflectionKey(m_hKey, &isReflectionDisabled); if (retCode != ERROR_SUCCESS) { return detail::MakeRegExpectedWithError<ReturnType>(retCode); } KeyReflection keyReflection = isReflectionDisabled ? KeyReflection::ReflectionDisabled : KeyReflection::ReflectionEnabled; return RegExpected<ReturnType>{ keyReflection }; } inline void RegKey::DeleteValue(const std::wstring& valueName) { _ASSERTE(IsValid()); LSTATUS retCode = ::RegDeleteValueW(m_hKey, valueName.c_str()); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegDeleteValueW failed." }; } } inline RegResult RegKey::TryDeleteValue(const std::wstring& valueName) noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegDeleteValueW(m_hKey, valueName.c_str()) }; } inline void RegKey::DeleteKey(const std::wstring& subKey, const REGSAM desiredAccess) { _ASSERTE(IsValid()); LSTATUS retCode = ::RegDeleteKeyExW(m_hKey, subKey.c_str(), desiredAccess, 0); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegDeleteKeyExW failed." }; } } inline RegResult RegKey::TryDeleteKey(const std::wstring& subKey, const REGSAM desiredAccess) noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegDeleteKeyExW(m_hKey, subKey.c_str(), desiredAccess, 0) }; } inline void RegKey::DeleteTree(const std::wstring& subKey) { _ASSERTE(IsValid()); LSTATUS retCode = ::RegDeleteTreeW(m_hKey, subKey.c_str()); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegDeleteTreeW failed." }; } } inline RegResult RegKey::TryDeleteTree(const std::wstring& subKey) noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegDeleteTreeW(m_hKey, subKey.c_str()) }; } inline void RegKey::CopyTree(const std::wstring& sourceSubKey, const RegKey& destKey) { _ASSERTE(IsValid()); LSTATUS retCode = ::RegCopyTreeW(m_hKey, sourceSubKey.c_str(), destKey.Get()); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegCopyTreeW failed." }; } } inline RegResult RegKey::TryCopyTree(const std::wstring& sourceSubKey, const RegKey& destKey) noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegCopyTreeW(m_hKey, sourceSubKey.c_str(), destKey.Get()) }; } inline void RegKey::FlushKey() { _ASSERTE(IsValid()); LSTATUS retCode = ::RegFlushKey(m_hKey); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegFlushKey failed." }; } } inline RegResult RegKey::TryFlushKey() noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegFlushKey(m_hKey) }; } inline void RegKey::LoadKey(const std::wstring& subKey, const std::wstring& filename) { Close(); LSTATUS retCode = ::RegLoadKeyW(m_hKey, subKey.c_str(), filename.c_str()); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegLoadKeyW failed." }; } } inline RegResult RegKey::TryLoadKey(const std::wstring& subKey, const std::wstring& filename) noexcept { Close(); return RegResult{ ::RegLoadKeyW(m_hKey, subKey.c_str(), filename.c_str()) }; } inline void RegKey::SaveKey( const std::wstring& filename, SECURITY_ATTRIBUTES* const securityAttributes ) const { _ASSERTE(IsValid()); LSTATUS retCode = ::RegSaveKeyW(m_hKey, filename.c_str(), securityAttributes); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegSaveKeyW failed." }; } } inline RegResult RegKey::TrySaveKey( const std::wstring& filename, SECURITY_ATTRIBUTES* const securityAttributes ) const noexcept { _ASSERTE(IsValid()); return RegResult{ ::RegSaveKeyW(m_hKey, filename.c_str(), securityAttributes) }; } inline void RegKey::EnableReflectionKey() { LSTATUS retCode = ::RegEnableReflectionKey(m_hKey); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegEnableReflectionKey failed." }; } } inline RegResult RegKey::TryEnableReflectionKey() noexcept { return RegResult{ ::RegEnableReflectionKey(m_hKey) }; } inline void RegKey::DisableReflectionKey() { LSTATUS retCode = ::RegDisableReflectionKey(m_hKey); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegDisableReflectionKey failed." }; } } inline RegResult RegKey::TryDisableReflectionKey() noexcept { return RegResult{ ::RegDisableReflectionKey(m_hKey) }; } inline void RegKey::ConnectRegistry(const std::wstring& machineName, const HKEY hKeyPredefined) { // Safely close any previously opened key Close(); HKEY hKeyResult = nullptr; LSTATUS retCode = ::RegConnectRegistryW(machineName.c_str(), hKeyPredefined, &hKeyResult); if (retCode != ERROR_SUCCESS) { throw RegException{ retCode, "RegConnectRegistryW failed." }; } // Take ownership of the result key m_hKey = hKeyResult; } inline RegResult RegKey::TryConnectRegistry(const std::wstring& machineName, const HKEY hKeyPredefined) noexcept { // Safely close any previously opened key Close(); HKEY hKeyResult = nullptr; RegResult retCode{ ::RegConnectRegistryW(machineName.c_str(), hKeyPredefined, &hKeyResult) }; if (retCode.Failed()) { return retCode; } // Take ownership of the result key m_hKey = hKeyResult; _ASSERTE(retCode.IsOk()); return retCode; } inline std::wstring RegKey::RegTypeToString(const DWORD regType) { switch (regType) { case REG_SZ: return L"REG_SZ"; case REG_EXPAND_SZ: return L"REG_EXPAND_SZ"; case REG_MULTI_SZ: return L"REG_MULTI_SZ"; case REG_DWORD: return L"REG_DWORD"; case REG_QWORD: return L"REG_QWORD"; case REG_BINARY: return L"REG_BINARY"; default: return L"Unknown/unsupported registry type"; } } //------------------------------------------------------------------------------ // RegException Inline Methods //------------------------------------------------------------------------------ inline RegException::RegException(const LSTATUS errorCode, const char* const message) : std::system_error{ errorCode, std::system_category(), message } {} inline RegException::RegException(const LSTATUS errorCode, const std::string& message) : std::system_error{ errorCode, std::system_category(), message } {} //------------------------------------------------------------------------------ // RegResult Inline Methods //------------------------------------------------------------------------------ inline RegResult::RegResult(const LSTATUS result) noexcept : m_result{ result } {} inline bool RegResult::IsOk() const noexcept { return m_result == ERROR_SUCCESS; } inline bool RegResult::Failed() const noexcept { return m_result != ERROR_SUCCESS; } inline RegResult::operator bool() const noexcept { return IsOk(); } inline LSTATUS RegResult::Code() const noexcept { return m_result; } inline std::wstring RegResult::ErrorMessage() const { return ErrorMessage(MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)); } inline std::wstring RegResult::ErrorMessage(const DWORD languageId) const { // Invoke FormatMessage() to retrieve the error message from Windows detail::ScopedLocalFree<wchar_t> messagePtr; DWORD retCode = ::FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, m_result, languageId, reinterpret_cast<LPWSTR>(messagePtr.AddressOf()), 0, nullptr ); if (retCode == 0) { // FormatMessage failed: return an empty string return std::wstring{}; } // Safely copy the C-string returned by FormatMessage() into a std::wstring object, // and return it back to the caller. return std::wstring{ messagePtr.Get() }; } //------------------------------------------------------------------------------ // RegExpected Inline Methods //------------------------------------------------------------------------------ template <typename T> inline RegExpected<T>::RegExpected(const RegResult& errorCode) noexcept : m_var{ errorCode } {} template <typename T> inline RegExpected<T>::RegExpected(const T& value) : m_var{ value } {} template <typename T> inline RegExpected<T>::RegExpected(T&& value) : m_var{ std::move(value) } {} template <typename T> inline RegExpected<T>::operator bool() const noexcept { return IsValid(); } template <typename T> inline bool RegExpected<T>::IsValid() const noexcept { return std::holds_alternative<T>(m_var); } template <typename T> inline const T& RegExpected<T>::GetValue() const { // Check that the object stores a valid value _ASSERTE(IsValid()); // If the object is in a valid state, the variant stores an instance of T return std::get<T>(m_var); } template <typename T> inline RegResult RegExpected<T>::GetError() const { // Check that the object is in an invalid state _ASSERTE(!IsValid()); // If the object is in an invalid state, the variant stores a RegResult // that represents an error code from the Windows Registry API return std::get<RegResult>(m_var); } } // namespace winreg #endif // GIOVANNI_DICANIO_WINREG_HPP_INCLUDED