blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
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
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 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
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
24962c6e6c5d46ef7b6c8983bd4a802d96b99147
c50c30e511946ddb660a2e25bfb81376faad6d08
/src/masternode-payments.cpp
282f5e03f7bfc736e977f8bb12a623aa33210fac
[ "MIT" ]
permissive
ultranatum/ultragate
e52fd316761fde9996f52e7e98ddf7475d915a88
b4773b11f358932cbdbd8f738b0648bd4ee5f385
refs/heads/master
2022-07-23T21:26:27.488403
2022-06-21T11:27:42
2022-06-21T11:27:42
175,899,669
4
4
null
null
null
null
UTF-8
C++
false
false
31,404
cpp
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode-payments.h" #include "addrman.h" #include "chainparams.h" #include "masternode-budget.h" #include "masternode-sync.h" #include "masternodeman.h" #include "obfuscation.h" #include "spork.h" #include "sync.h" #include "util.h" #include "utilmoneystr.h" #include <boost/filesystem.hpp> /** Object for who's going to get paid on which blocks */ CMasternodePayments masternodePayments; CCriticalSection cs_vecPayments; CCriticalSection cs_mapMasternodeBlocks; CCriticalSection cs_mapMasternodePayeeVotes; // // CMasternodePaymentDB // CMasternodePaymentDB::CMasternodePaymentDB() { pathDB = GetDataDir() / "mnpayments.dat"; strMagicMessage = "MasternodePayments"; } bool CMasternodePaymentDB::Write(const CMasternodePayments& objToSave) { int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // masternode cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrint("masternode","Written info to mnpayments.dat %dms\n", GetTimeMillis() - nStart); return true; } CMasternodePaymentDB::ReadResult CMasternodePaymentDB::Read(CMasternodePayments& objToLoad, bool fDryRun) { int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; std::vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (masternode cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid masternode payement cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CMasternodePayments object ssObj >> objToLoad; } catch (std::exception& e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrint("masternode","Loaded info from mnpayments.dat %dms\n", GetTimeMillis() - nStart); LogPrint("masternode"," %s\n", objToLoad.ToString()); if (!fDryRun) { LogPrint("masternode","Masternode payments manager - cleaning....\n"); objToLoad.CleanPaymentList(); LogPrint("masternode","Masternode payments manager - result:\n"); LogPrint("masternode"," %s\n", objToLoad.ToString()); } return Ok; } void DumpMasternodePayments() { int64_t nStart = GetTimeMillis(); CMasternodePaymentDB paymentdb; CMasternodePayments tempPayments; LogPrint("masternode","Verifying mnpayments.dat format...\n"); CMasternodePaymentDB::ReadResult readResult = paymentdb.Read(tempPayments, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CMasternodePaymentDB::FileError) LogPrint("masternode","Missing budgets file - mnpayments.dat, will try to recreate\n"); else if (readResult != CMasternodePaymentDB::Ok) { LogPrint("masternode","Error reading mnpayments.dat: "); if (readResult == CMasternodePaymentDB::IncorrectFormat) LogPrint("masternode","magic is ok but data has invalid format, will try to recreate\n"); else { LogPrint("masternode","file format is unknown or invalid, please fix it manually\n"); return; } } LogPrint("masternode","Writting info to mnpayments.dat...\n"); paymentdb.Write(masternodePayments); LogPrint("masternode","Budget dump finished %dms\n", GetTimeMillis() - nStart); } bool IsBlockValueValid(const CBlock& block, CAmount nExpectedValue, CAmount nMinted) { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return true; int nHeight = 0; if (pindexPrev->GetBlockHash() == block.hashPrevBlock) { nHeight = pindexPrev->nHeight + 1; } else { //out of order BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi != mapBlockIndex.end() && (*mi).second) nHeight = (*mi).second->nHeight + 1; } if (nHeight == 0) { LogPrint("masternode","IsBlockValueValid() : WARNING: Couldn't find previous block\n"); } //LogPrintf("XX69----------> IsBlockValueValid(): nMinted: %d, nExpectedValue: %d\n", FormatMoney(nMinted), FormatMoney(nExpectedValue)); if (!masternodeSync.IsSynced()) { //there is no budget data to use to check anything //super blocks will always be on these blocks, max 100 per budgeting if (nHeight % Params().GetBudgetCycleBlocks() < 100) { return true; } else { if (nMinted > nExpectedValue) { return false; } } } else { // we're synced and have data so check the budget schedule //are these blocks even enabled if (!IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS)) { return nMinted <= nExpectedValue; } if (budget.IsBudgetPaymentBlock(nHeight)) { //the value of the block is evaluated in CheckBlock return true; } else { if (nMinted > nExpectedValue) { return false; } } } return true; } bool IsBlockPayeeValid(const CBlock& block, int nBlockHeight) { TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; if (!masternodeSync.IsSynced()) { //there is no budget data to use to check anything -- find the longest chain LogPrint("mnpayments", "Client not synced, skipping block payee checks\n"); return true; } const CTransaction& txNew = (nBlockHeight > Params().LAST_POW_BLOCK() ? block.vtx[1] : block.vtx[0]); //check if it's a budget block if (IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS)) { if (budget.IsBudgetPaymentBlock(nBlockHeight)) { transactionStatus = budget.IsTransactionValid(txNew, nBlockHeight); if (transactionStatus == TrxValidationStatus::Valid) { return true; } if (transactionStatus == TrxValidationStatus::InValid) { LogPrint("masternode","Invalid budget payment detected %s\n", txNew.ToString().c_str()); if (IsSporkActive(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT)) return false; LogPrint("masternode","Budget enforcement is disabled, accepting block\n"); } } } // If we end here the transaction was either TrxValidationStatus::InValid and Budget enforcement is disabled, or // a double budget payment (status = TrxValidationStatus::DoublePayment) was detected, or no/not enough masternode // votes (status = TrxValidationStatus::VoteThreshold) for a finalized budget were found // In all cases a masternode will get the payment for this block //check for masternode payee if (masternodePayments.IsTransactionValid(txNew, nBlockHeight)) return true; LogPrint("masternode","Invalid mn payment detected %s\n", txNew.ToString().c_str()); if (IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) return false; LogPrint("masternode","Masternode payment enforcement is disabled, accepting block\n"); return true; } void FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake, bool fZULGStake) { CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; if (IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS) && budget.IsBudgetPaymentBlock(pindexPrev->nHeight + 1)) { budget.FillBlockPayee(txNew, nFees, fProofOfStake); } else { masternodePayments.FillBlockPayee(txNew, nFees, fProofOfStake, fZULGStake); } } std::string GetRequiredPaymentsString(int nBlockHeight) { if (IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS) && budget.IsBudgetPaymentBlock(nBlockHeight)) { return budget.GetRequiredPaymentsString(nBlockHeight); } else { return masternodePayments.GetRequiredPaymentsString(nBlockHeight); } } void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int64_t nFees, bool fProofOfStake, bool fZULGStake) { CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; bool hasPayment = true; CScript payee; //spork if (!masternodePayments.GetBlockPayee(pindexPrev->nHeight + 1, payee)) { //no masternode detected CMasternode* winningNode = mnodeman.GetCurrentMasterNode(1); if (winningNode) { payee = GetScriptForDestination(winningNode->pubKeyCollateralAddress.GetID()); } else { LogPrint("masternode","CreateNewBlock: Failed to detect masternode to pay\n"); hasPayment = false; } } CAmount blockValue = GetBlockValue(pindexPrev->nHeight); CAmount masternodePayment = GetMasternodePayment(pindexPrev->nHeight, blockValue); if (hasPayment) { if (fProofOfStake) { /**For Proof Of Stake vout[0] must be null * Stake reward can be split into many different outputs, so we must * use vout.size() to align with several different cases. * An additional output is appended as the masternode payment */ unsigned int i = txNew.vout.size(); txNew.vout.resize(i + 1); txNew.vout[i].scriptPubKey = payee; txNew.vout[i].nValue = masternodePayment; //subtract mn payment from the stake reward if (!txNew.vout[1].IsZerocoinMint()) if (i == 2) { // Majority of cases; do it quick and move on txNew.vout[i - 1].nValue -= masternodePayment; } else if (i > 2) { // special case, stake is split between (i-1) outputs unsigned int outputs = i-1; CAmount mnPaymentSplit = masternodePayment / outputs; CAmount mnPaymentRemainder = masternodePayment - (mnPaymentSplit * outputs); for (unsigned int j=1; j<=outputs; j++) { txNew.vout[j].nValue -= mnPaymentSplit; } // in case it's not an even division, take the last bit of dust from the last one txNew.vout[outputs].nValue -= mnPaymentRemainder; } } else { txNew.vout.resize(2); txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = masternodePayment; txNew.vout[0].nValue = blockValue - masternodePayment; } CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("masternode","Masternode payment of %s to %s\n", FormatMoney(masternodePayment).c_str(), address2.ToString().c_str()); } } int CMasternodePayments::GetMinMasternodePaymentsProto() { if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return ActiveProtocol(); // Allow only updated peers else return MIN_PEER_PROTO_VERSION_BEFORE_ENFORCEMENT; // Also allow old peers as long as they are allowed to run } void CMasternodePayments::ProcessMessageMasternodePayments(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (!masternodeSync.IsBlockchainSynced()) return; if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality if (strCommand == "mnget") { //Masternode Payments Request Sync if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality int nCountNeeded; vRecv >> nCountNeeded; if (Params().NetworkID() == CBaseChainParams::MAIN) { if (pfrom->HasFulfilledRequest("mnget")) { LogPrintf("CMasternodePayments::ProcessMessageMasternodePayments() : mnget - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } } pfrom->FulfilledRequest("mnget"); masternodePayments.Sync(pfrom, nCountNeeded); LogPrint("mnpayments", "mnget - Sent Masternode winners to peer %i\n", pfrom->GetId()); } else if (strCommand == "mnw") { //Masternode Payments Declare Winner //this is required in litemodef CMasternodePaymentWinner winner; vRecv >> winner; if (pfrom->nVersion < ActiveProtocol()) return; int nHeight; { TRY_LOCK(cs_main, locked); if (!locked || chainActive.Tip() == NULL) return; nHeight = chainActive.Tip()->nHeight; } if (masternodePayments.mapMasternodePayeeVotes.count(winner.GetHash())) { LogPrint("mnpayments", "mnw - Already seen - %s bestHeight %d\n", winner.GetHash().ToString().c_str(), nHeight); masternodeSync.AddedMasternodeWinner(winner.GetHash()); return; } int nFirstBlock = nHeight - (mnodeman.CountEnabled() * 1.25); if (winner.nBlockHeight < nFirstBlock || winner.nBlockHeight > nHeight + 20) { LogPrint("mnpayments", "mnw - winner out of range - FirstBlock %d Height %d bestHeight %d\n", nFirstBlock, winner.nBlockHeight, nHeight); return; } std::string strError = ""; if (!winner.IsValid(pfrom, strError)) { // if(strError != "") LogPrint("masternode","mnw - invalid message - %s\n", strError); return; } if (!masternodePayments.CanVote(winner.vinMasternode.prevout, winner.nBlockHeight)) { // LogPrint("masternode","mnw - masternode already voted - %s\n", winner.vinMasternode.prevout.ToStringShort()); return; } if (!winner.SignatureValid()) { if (masternodeSync.IsSynced()) { LogPrintf("CMasternodePayments::ProcessMessageMasternodePayments() : mnw - invalid signature\n"); Misbehaving(pfrom->GetId(), 20); } // it could just be a non-synced masternode mnodeman.AskForMN(pfrom, winner.vinMasternode); return; } CTxDestination address1; ExtractDestination(winner.payee, address1); CBitcoinAddress address2(address1); // LogPrint("mnpayments", "mnw - winning vote - Addr %s Height %d bestHeight %d - %s\n", address2.ToString().c_str(), winner.nBlockHeight, nHeight, winner.vinMasternode.prevout.ToStringShort()); if (masternodePayments.AddWinningMasternode(winner)) { winner.Relay(); masternodeSync.AddedMasternodeWinner(winner.GetHash()); } } } bool CMasternodePaymentWinner::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { std::string errorMessage; std::string strMasterNodeSignMessage; std::string strMessage = vinMasternode.prevout.ToStringShort() + std::to_string(nBlockHeight) + payee.ToString(); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage.c_str()); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage.c_str()); return false; } return true; } bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee) { if (mapMasternodeBlocks.count(nBlockHeight)) { return mapMasternodeBlocks[nBlockHeight].GetPayee(payee); } return false; } // Is this masternode scheduled to get paid soon? // -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 winners bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight) { LOCK(cs_mapMasternodeBlocks); int nHeight; { TRY_LOCK(cs_main, locked); if (!locked || chainActive.Tip() == NULL) return false; nHeight = chainActive.Tip()->nHeight; } CScript mnpayee; mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID()); CScript payee; for (int64_t h = nHeight; h <= nHeight + 8; h++) { if (h == nNotBlockHeight) continue; if (mapMasternodeBlocks.count(h)) { if (mapMasternodeBlocks[h].GetPayee(payee)) { if (mnpayee == payee) { return true; } } } } return false; } bool CMasternodePayments::AddWinningMasternode(CMasternodePaymentWinner& winnerIn) { uint256 blockHash = 0; if (!GetBlockHash(blockHash, winnerIn.nBlockHeight - 100)) { return false; } { LOCK2(cs_mapMasternodePayeeVotes, cs_mapMasternodeBlocks); if (mapMasternodePayeeVotes.count(winnerIn.GetHash())) { return false; } mapMasternodePayeeVotes[winnerIn.GetHash()] = winnerIn; if (!mapMasternodeBlocks.count(winnerIn.nBlockHeight)) { CMasternodeBlockPayees blockPayees(winnerIn.nBlockHeight); mapMasternodeBlocks[winnerIn.nBlockHeight] = blockPayees; } } mapMasternodeBlocks[winnerIn.nBlockHeight].AddPayee(winnerIn.payee, 1); return true; } bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) { LOCK(cs_vecPayments); int nMaxSignatures = 0; int nMasternode_Drift_Count = 0; std::string strPayeesPossible = ""; CAmount nReward = GetBlockValue(nBlockHeight); if (IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { // Get a stable number of masternodes by ignoring newly activated (< 8000 sec old) masternodes nMasternode_Drift_Count = mnodeman.stable_size() + Params().MasternodeCountDrift(); } else { //account for the fact that all peers do not see the same masternode count. A allowance of being off our masternode count is given //we only need to look at an increased masternode count because as count increases, the reward decreases. This code only checks //for mnPayment >= required, so it only makes sense to check the max node count allowed. nMasternode_Drift_Count = mnodeman.size() + Params().MasternodeCountDrift(); } CAmount requiredMasternodePayment = GetMasternodePayment(nBlockHeight, nReward); //require at least 6 signatures for (CMasternodePayee& payee : vecPayments) if (payee.nVotes >= nMaxSignatures && payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED) nMaxSignatures = payee.nVotes; // if we don't have at least 6 signatures on a payee, approve whichever is the longest chain if (nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; for (CMasternodePayee& payee : vecPayments) { bool found = false; for (CTxOut out : txNew.vout) { if (payee.scriptPubKey == out.scriptPubKey) { if(out.nValue >= requiredMasternodePayment) found = true; else LogPrint("masternode","Masternode payment is out of drift range. Paid=%s Min=%s\n", FormatMoney(out.nValue).c_str(), FormatMoney(requiredMasternodePayment).c_str()); } } if (payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED) { if (found) return true; CTxDestination address1; ExtractDestination(payee.scriptPubKey, address1); CBitcoinAddress address2(address1); if (strPayeesPossible == "") { strPayeesPossible += address2.ToString(); } else { strPayeesPossible += "," + address2.ToString(); } } } LogPrint("masternode","CMasternodePayments::IsTransactionValid - Missing required payment of %s to %s\n", FormatMoney(requiredMasternodePayment).c_str(), strPayeesPossible.c_str()); return false; } std::string CMasternodeBlockPayees::GetRequiredPaymentsString() { LOCK(cs_vecPayments); std::string ret = "Unknown"; for (CMasternodePayee& payee : vecPayments) { CTxDestination address1; ExtractDestination(payee.scriptPubKey, address1); CBitcoinAddress address2(address1); if (ret != "Unknown") { ret += ", " + address2.ToString() + ":" + std::to_string(payee.nVotes); } else { ret = address2.ToString() + ":" + std::to_string(payee.nVotes); } } return ret; } std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if (mapMasternodeBlocks.count(nBlockHeight)) { return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString(); } return "Unknown"; } bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if (mapMasternodeBlocks.count(nBlockHeight)) { return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew); } return true; } void CMasternodePayments::CleanPaymentList() { LOCK2(cs_mapMasternodePayeeVotes, cs_mapMasternodeBlocks); int nHeight; { TRY_LOCK(cs_main, locked); if (!locked || chainActive.Tip() == NULL) return; nHeight = chainActive.Tip()->nHeight; } //keep up to five cycles for historical sake int nLimit = std::max(int(mnodeman.size() * 1.25), 1000); std::map<uint256, CMasternodePaymentWinner>::iterator it = mapMasternodePayeeVotes.begin(); while (it != mapMasternodePayeeVotes.end()) { CMasternodePaymentWinner winner = (*it).second; if (nHeight - winner.nBlockHeight > nLimit) { LogPrint("mnpayments", "CMasternodePayments::CleanPaymentList - Removing old Masternode payment - block %d\n", winner.nBlockHeight); masternodeSync.mapSeenSyncMNW.erase((*it).first); mapMasternodePayeeVotes.erase(it++); mapMasternodeBlocks.erase(winner.nBlockHeight); } else { ++it; } } } bool CMasternodePaymentWinner::IsValid(CNode* pnode, std::string& strError) { CMasternode* pmn = mnodeman.Find(vinMasternode); if (!pmn) { strError = strprintf("Unknown Masternode %s", vinMasternode.prevout.hash.ToString()); LogPrint("masternode","CMasternodePaymentWinner::IsValid - %s\n", strError); mnodeman.AskForMN(pnode, vinMasternode); return false; } if (pmn->protocolVersion < ActiveProtocol()) { strError = strprintf("Masternode protocol too old %d - req %d", pmn->protocolVersion, ActiveProtocol()); LogPrint("masternode","CMasternodePaymentWinner::IsValid - %s\n", strError); return false; } int n = mnodeman.GetMasternodeRank(vinMasternode, nBlockHeight - 100, ActiveProtocol()); if (n > MNPAYMENTS_SIGNATURES_TOTAL) { //It's common to have masternodes mistakenly think they are in the top 10 // We don't want to print all of these messages, or punish them unless they're way off if (n > MNPAYMENTS_SIGNATURES_TOTAL * 2) { strError = strprintf("Masternode not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL * 2, n); LogPrint("masternode","CMasternodePaymentWinner::IsValid - %s\n", strError); //if (masternodeSync.IsSynced()) Misbehaving(pnode->GetId(), 20); } return false; } return true; } bool CMasternodePayments::ProcessBlock(int nBlockHeight) { if (!fMasterNode) return false; //reference node - hybrid mode int n = mnodeman.GetMasternodeRank(activeMasternode.vin, nBlockHeight - 100, ActiveProtocol()); if (n == -1) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock - Unknown Masternode\n"); return false; } if (n > MNPAYMENTS_SIGNATURES_TOTAL) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock - Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, n); return false; } if (nBlockHeight <= nLastBlockHeight) return false; CMasternodePaymentWinner newWinner(activeMasternode.vin); if (budget.IsBudgetPaymentBlock(nBlockHeight)) { //is budget payment block -- handled by the budgeting software } else { LogPrint("masternode","CMasternodePayments::ProcessBlock() Start nHeight %d - vin %s. \n", nBlockHeight, activeMasternode.vin.prevout.hash.ToString()); // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough int nCount = 0; CMasternode* pmn = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount); if (pmn != NULL) { LogPrint("masternode","CMasternodePayments::ProcessBlock() Found by FindOldestNotInVec \n"); newWinner.nBlockHeight = nBlockHeight; CScript payee = GetScriptForDestination(pmn->pubKeyCollateralAddress.GetID()); newWinner.AddPayee(payee); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("masternode","CMasternodePayments::ProcessBlock() Winner payee %s nHeight %d. \n", address2.ToString().c_str(), newWinner.nBlockHeight); } else { LogPrint("masternode","CMasternodePayments::ProcessBlock() Failed to find masternode to pay\n"); } } std::string errorMessage; CPubKey pubKeyMasternode; CKey keyMasternode; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrint("masternode","CMasternodePayments::ProcessBlock() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } LogPrint("masternode","CMasternodePayments::ProcessBlock() - Signing Winner\n"); if (newWinner.Sign(keyMasternode, pubKeyMasternode)) { LogPrint("masternode","CMasternodePayments::ProcessBlock() - AddWinningMasternode\n"); if (AddWinningMasternode(newWinner)) { newWinner.Relay(); nLastBlockHeight = nBlockHeight; return true; } } return false; } void CMasternodePaymentWinner::Relay() { CInv inv(MSG_MASTERNODE_WINNER, GetHash()); RelayInv(inv); } bool CMasternodePaymentWinner::SignatureValid() { CMasternode* pmn = mnodeman.Find(vinMasternode); if (pmn != NULL) { std::string strMessage = vinMasternode.prevout.ToStringShort() + std::to_string(nBlockHeight) + payee.ToString(); std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { return error("CMasternodePaymentWinner::SignatureValid() - Got bad Masternode address signature %s\n", vinMasternode.prevout.hash.ToString()); } return true; } return false; } void CMasternodePayments::Sync(CNode* node, int nCountNeeded) { LOCK(cs_mapMasternodePayeeVotes); int nHeight; { TRY_LOCK(cs_main, locked); if (!locked || chainActive.Tip() == NULL) return; nHeight = chainActive.Tip()->nHeight; } int nCount = (mnodeman.CountEnabled() * 1.25); if (nCountNeeded > nCount) nCountNeeded = nCount; int nInvCount = 0; std::map<uint256, CMasternodePaymentWinner>::iterator it = mapMasternodePayeeVotes.begin(); while (it != mapMasternodePayeeVotes.end()) { CMasternodePaymentWinner winner = (*it).second; if (winner.nBlockHeight >= nHeight - nCountNeeded && winner.nBlockHeight <= nHeight + 20) { node->PushInventory(CInv(MSG_MASTERNODE_WINNER, winner.GetHash())); nInvCount++; } ++it; } node->PushMessage("ssc", MASTERNODE_SYNC_MNW, nInvCount); } std::string CMasternodePayments::ToString() const { std::ostringstream info; info << "Votes: " << (int)mapMasternodePayeeVotes.size() << ", Blocks: " << (int)mapMasternodeBlocks.size(); return info.str(); } int CMasternodePayments::GetOldestBlock() { LOCK(cs_mapMasternodeBlocks); int nOldestBlock = std::numeric_limits<int>::max(); std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin(); while (it != mapMasternodeBlocks.end()) { if ((*it).first < nOldestBlock) { nOldestBlock = (*it).first; } it++; } return nOldestBlock; } int CMasternodePayments::GetNewestBlock() { LOCK(cs_mapMasternodeBlocks); int nNewestBlock = 0; std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin(); while (it != mapMasternodeBlocks.end()) { if ((*it).first > nNewestBlock) { nNewestBlock = (*it).first; } it++; } return nNewestBlock; }
[ "ultranatum@web.de" ]
ultranatum@web.de
9ef7d6c35b1441ed57d539b17c235089e426f467
59bf36d2e39ecd8ecad2375ed6a8788d0559d7df
/FootSoldier.hpp
72801ec973a8f15989cef1ba2630c05d112601f1
[ "MIT" ]
permissive
YehielSiri/c-assignment-4
e8b1bcd4c694d9a34dffface00688873c61fa7ed
ed967e170c61de8623e14243b06bca2751a4be99
refs/heads/master
2022-08-01T12:28:09.515921
2020-05-20T22:15:41
2020-05-20T22:15:41
266,506,489
0
0
MIT
2020-05-24T09:13:01
2020-05-24T09:13:00
null
UTF-8
C++
false
false
123
hpp
#pragma once #include "Soldier.hpp" class FootSoldier: public Soldier{ public: FootSoldier(int team){} };
[ "Itamarzo0@gmail.com" ]
Itamarzo0@gmail.com
38503bf798270b147e7d94523b890566d9aad272
1817295bb117c18930fa04e2ada5b8a938e2ab2b
/src/Magnum/Renderer.h
dc09ab92ba91a58c86136eab2daf998aab4f5c27
[ "MIT" ]
permissive
torkos/magnum
eedd480ec04e1884dfa74691791eb57e784e4374
e2bd3943003860d7a9819f0e0d99b7f952b50c59
refs/heads/master
2021-01-18T05:38:00.007157
2015-02-08T22:27:01
2015-02-08T22:32:59
30,578,141
0
1
null
2015-02-10T06:18:04
2015-02-10T06:18:04
null
UTF-8
C++
false
false
43,669
h
#ifndef Magnum_Renderer_h #define Magnum_Renderer_h /* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> 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. */ /** @file * @brief Class @ref Magnum::Renderer */ #include <Corrade/Containers/EnumSet.h> #include "Magnum/Magnum.h" #include "Magnum/OpenGL.h" #include "Magnum/visibility.h" namespace Magnum { namespace Implementation { struct RendererState; } /** @nosubgrouping @brief Global renderer configuration. @todo @extension{ARB,viewport_array} @todo `GL_POINT_SIZE_GRANULARITY`, `GL_POINT_SIZE_RANGE` (?) @todo `GL_STEREO`, `GL_DOUBLEBUFFER` (?) @todo `GL_MAX_CLIP_DISTANCES`... */ class MAGNUM_EXPORT Renderer { friend Context; friend Implementation::RendererState; public: Renderer() = delete; /** * @brief Affected polygon facing for culling, stencil operations and masks * * @see @ref setFaceCullingMode(), * @ref setStencilFunction(PolygonFacing, StencilFunction, Int, UnsignedInt), * @ref setStencilOperation(PolygonFacing, StencilOperation, StencilOperation, StencilOperation), * @ref setStencilMask(PolygonFacing, UnsignedInt) */ enum class PolygonFacing: GLenum { Front = GL_FRONT, /**< Front-facing polygons */ Back = GL_BACK, /**< Back-facing polygons */ FrontAndBack = GL_FRONT_AND_BACK /**< Front- and back-facing polygons */ }; /** @{ @name Renderer features */ /** * @brief Features * * All features are disabled by default unless specified otherwise. * @see @ref enable(), @ref disable(), @ref setFeature() */ enum class Feature: GLenum { /** * Blending * @see @ref setBlendEquation(), @ref setBlendFunction(), * @ref setBlendColor() */ Blending = GL_BLEND, /** * Debug output. Disabled by default unless the GL context was * created with debug output enabled. * @see @ref DebugOutput, @ref Feature::DebugOutputSynchronous, * @ref Platform::Sdl2Application::Configuration::Flag::Debug "Platform::*Application::Configuration::Flag::Debug" * @requires_gl43 Extension @extension{KHR,debug} * @requires_es_extension Extension @es_extension{KHR,debug} */ #ifndef MAGNUM_TARGET_GLES DebugOutput = GL_DEBUG_OUTPUT, #else DebugOutput = GL_DEBUG_OUTPUT_KHR, #endif /** * Synchronous debug output. Has effect only if * @ref Feature::DebugOutput is enabled. * @see @ref DebugMessage * @requires_gl43 Extension @extension{KHR,debug} * @requires_es_extension Extension @es_extension{KHR,debug} */ #ifndef MAGNUM_TARGET_GLES DebugOutputSynchronous = GL_DEBUG_OUTPUT_SYNCHRONOUS, #else DebugOutputSynchronous = GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR, #endif #ifndef MAGNUM_TARGET_GLES /** * Depth clamping. If enabled, ignores near and far clipping plane. * @requires_gl32 Extension @extension{ARB,depth_clamp} * @requires_gl Depth clamping is not available in OpenGL ES. */ DepthClamp = GL_DEPTH_CLAMP, #endif /** * Depth test * @see @ref setClearDepth(), @ref setDepthFunction(), * @ref setDepthMask() */ DepthTest = GL_DEPTH_TEST, Dithering = GL_DITHER, /**< Dithering. Enabled by default. */ /** * Back face culling * @see @ref setFrontFace() */ FaceCulling = GL_CULL_FACE, #ifndef MAGNUM_TARGET_GLES /** * sRGB encoding of the default framebuffer * @requires_gl30 Extension @extension{ARB,framebuffer_sRGB} * @requires_gl sRGB encoding of the default framebuffer is * implementation-defined in OpenGL ES. */ FramebufferSRGB = GL_FRAMEBUFFER_SRGB, /** * Logical operation * @see @ref setLogicOperation() * @requires_gl Logical operations on framebuffer are not * available in OpenGL ES. */ LogicOperation = GL_COLOR_LOGIC_OP, #endif #ifndef MAGNUM_TARGET_GLES /** * Multisampling. Enabled by default. Note that the actual presence * of this feature in default framebuffer depends on context * configuration, see for example @ref Platform::Sdl2Application::Configuration::setSampleCount(). * @requires_gl Always enabled in OpenGL ES. */ Multisampling = GL_MULTISAMPLE, #endif /** * Offset filled polygons * @see @ref Magnum::Renderer::Feature "Feature::PolygonOffsetLine", * @ref Magnum::Renderer::Feature "Feature::PolygonOffsetPoint", * @ref setPolygonOffset() */ PolygonOffsetFill = GL_POLYGON_OFFSET_FILL, #ifndef MAGNUM_TARGET_GLES /** * Offset lines * @see @ref Magnum::Renderer::Feature "Feature::PolygonOffsetFill", * @ref Magnum::Renderer::Feature "Feature::PolygonOffsetPoint", * @ref setPolygonOffset() * @requires_gl Only @ref Magnum::Renderer::Feature "Feature::PolygonOffsetFill" * is available in OpenGL ES. */ PolygonOffsetLine = GL_POLYGON_OFFSET_LINE, /** * Offset points * @see @ref Magnum::Renderer::Feature "Feature::PolygonOffsetFill", * @ref Magnum::Renderer::Feature "Feature::PolygonOffsetLine", * @ref setPolygonOffset() * @requires_gl Only @ref Magnum::Renderer::Feature "Feature::PolygonOffsetFill" * is available in OpenGL ES. */ PolygonOffsetPoint = GL_POLYGON_OFFSET_POINT, #endif #ifndef MAGNUM_TARGET_GLES /** * Programmable point size. If enabled, the point size is taken * from vertex/geometry shader builtin `gl_PointSize`. * @see @ref setPointSize() * @requires_gl Always enabled on OpenGL ES. */ ProgramPointSize = GL_PROGRAM_POINT_SIZE, #endif #ifndef MAGNUM_TARGET_GLES2 /** * Discard primitives before rasterization. * @requires_gl30 Extension @extension{EXT,transform_feedback} * @requires_gles30 Transform feedback is not available in OpenGL * ES 2.0. */ RasterizerDiscard = GL_RASTERIZER_DISCARD, #endif /** * Scissor test * @see @ref setScissor() */ ScissorTest = GL_SCISSOR_TEST, #ifndef MAGNUM_TARGET_GLES /** * Seamless cube map texture. * @see @ref CubeMapTexture, @ref CubeMapTextureArray * @requires_gl32 Extension @extension{ARB,seamless_cube_map} * @requires_gl Not available in OpenGL ES 2.0, always enabled in * OpenGL ES 3.0. */ SeamlessCubeMapTexture = GL_TEXTURE_CUBE_MAP_SEAMLESS, #endif /** * Stencil test * @see @ref setClearStencil(), @ref setStencilFunction(), * @ref setStencilOperation(), @ref setStencilMask() */ StencilTest = GL_STENCIL_TEST }; /** * @brief Enable feature * * @see @ref disable(), @ref setFeature(), @fn_gl{Enable} */ static void enable(Feature feature); /** * @brief Disable feature * * @see @ref enable(), @ref setFeature(), @fn_gl{Disable} */ static void disable(Feature feature); /** * @brief Enable or disable feature * * Convenience equivalent to the following: * @code * enabled ? Renderer::enable(feature) : Renderer::disable(feature) * @endcode * Prefer to use @ref enable() and @ref disable() directly to avoid * unnecessary branching. */ static void setFeature(Feature feature, bool enabled); /** * @brief Hint * * @see @ref setHint() * @todo other hints */ enum class Hint: GLenum { /** * Accuracy of derivative calculation in fragment shader. * @requires_gles30 Extension @es_extension{OES,standard_derivatives} * in OpenGL ES 2.0 */ #ifndef MAGNUM_TARGET_GLES2 FragmentShaderDerivative = GL_FRAGMENT_SHADER_DERIVATIVE_HINT #else FragmentShaderDerivative = GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES #endif }; /** * @brief Hint mode * * @see @ref setHint() */ enum class HintMode: GLenum { Fastest = GL_FASTEST, /**< Most efficient option. */ Nicest = GL_NICEST, /**< Most correct or highest quality option. */ DontCare = GL_DONT_CARE /**< No preference. */ }; /** * @brief Set hint * * Initial value is @ref HintMode::DontCare for all targets. * @see @fn_gl{Hint} */ static void setHint(Hint target, HintMode mode); /*@}*/ /** @{ @name Clearing values */ /** * @brief Set clear color * * Initial value is `{0.125f, 0.125f, 0.125f, 1.0f}`. * @see @fn_gl{ClearColor} */ static void setClearColor(const Color4& color); #ifndef MAGNUM_TARGET_GLES /** * @brief Set clear depth * * Initial value is `1.0`. * @see @ref Feature::DepthTest, @fn_gl{ClearDepth} * @requires_gl See @ref Magnum::Renderer::setClearDepth(Float) "setClearDepth(Float)", * which is available in OpenGL ES. */ static void setClearDepth(Double depth); #endif /** * @overload * * If OpenGL ES, OpenGL 4.1 or extension @extension{ARB,ES2_compatibility} * is not available, this function behaves exactly as * @ref setClearDepth(Double). * @see @ref Feature::DepthTest, @fn_gl{ClearDepth} */ static void setClearDepth(Float depth); /** * @brief Set clear stencil * * Initial value is `0`. * @see @ref Feature::StencilTest, @fn_gl{ClearStencil} */ static void setClearStencil(Int stencil); /*@}*/ /** @name Polygon drawing settings */ /** * @brief Front facing polygon winding * * @see @ref setFrontFace() */ enum class FrontFace: GLenum { /** @brief Counterclockwise polygons are front facing (default). */ CounterClockWise = GL_CCW, /** @brief Clockwise polygons are front facing. */ ClockWise = GL_CW }; /** * @brief Set front-facing polygon winding * * Initial value is @ref FrontFace::CounterClockWise. * @see @ref setFaceCullingMode(), @fn_gl{FrontFace} */ static void setFrontFace(FrontFace mode); /** * @brief Which polygon facing to cull * * Initial value is @ref PolygonFacing::Back. If set to both front and * back, only points and lines are drawn. * @see @ref Feature::FaceCulling, @ref setFrontFace(), * @fn_gl{CullFace} */ static void setFaceCullingMode(PolygonFacing mode); #ifndef MAGNUM_TARGET_GLES /** * @brief Provoking vertex * * @see @ref setProvokingVertex() * @requires_gl32 Extension @extension{ARB,provoking_vertex}. Older * versions behave always like * @ref Magnum::Renderer::ProvokingVertex "ProvokingVertex::LastVertexConvention". * @requires_gl OpenGL ES behaves always like * @ref Magnum::Renderer::ProvokingVertex "ProvokingVertex::LastVertexConvention". */ enum class ProvokingVertex: GLenum { /** @brief Use first vertex of each polygon. */ FirstVertexConvention = GL_FIRST_VERTEX_CONVENTION, /** @brief Use last vertex of each polygon (default). */ LastVertexConvention = GL_LAST_VERTEX_CONVENTION }; /** * @brief Set provoking vertex * * Initial value is @ref ProvokingVertex::LastVertexConvention. * @see @fn_gl{ProvokingVertex} * @requires_gl32 Extension @extension{ARB,provoking_vertex}. Older * versions behave always like the default. * @requires_gl OpenGL ES behaves always like the default. */ static void setProvokingVertex(ProvokingVertex mode); /** * @brief Polygon mode * * @see @ref setPolygonMode() * @requires_gl OpenGL ES behaves always like @ref Magnum::Renderer::PolygonMode "PolygonMode::Fill". * See @ref Magnum::Mesh::setPrimitive() "Mesh::setPrimitive()" * for possible workaround. */ enum class PolygonMode: GLenum { /** * Interior of the polygon is filled (default). */ Fill = GL_FILL, /** * Boundary edges are filled. See also @ref setLineWidth(). */ Line = GL_LINE, /** * Starts of boundary edges are drawn as points. See also * @ref setPointSize(). */ Point = GL_POINT }; /** * @brief Set polygon drawing mode * * Initial value is @ref PolygonMode::Fill. * @see @fn_gl{PolygonMode} * @requires_gl OpenGL ES behaves always like the default. See * @ref Magnum::Mesh::setPrimitive() "Mesh::setPrimitive()" for * possible workaround. */ static void setPolygonMode(PolygonMode mode); #endif /** * @brief Set polygon offset * @param factor Scale factor * @param units Offset units * * @see @ref Feature::PolygonOffsetFill, @ref Feature::PolygonOffsetLine, * @ref Feature::PolygonOffsetPoint, @fn_gl{PolygonOffset} */ static void setPolygonOffset(Float factor, Float units); /** * @brief Set line width * * Initial value is `1.0f`. * @see @fn_gl{LineWidth} */ static void setLineWidth(Float width); #ifndef MAGNUM_TARGET_GLES /** * @brief Set point size * * Initial value is `1.0f`. * @see @ref Feature::ProgramPointSize, @fn_gl{PointSize} * @requires_gl Use `gl_PointSize` builtin vertex shader variable in * OpenGL ES instead. */ static void setPointSize(Float size); #endif /*@}*/ /** @{ @name Scissor operations */ /** * @brief Set scissor rectangle * * Initial value is set to cover whole window. * @see @ref Feature::ScissorTest, @fn_gl{Scissor} */ static void setScissor(const Range2Di& rectangle); /*@}*/ /** @{ @name Stencil operations */ /** * @brief Stencil function * * @see @ref setStencilFunction(), @ref DepthFunction */ enum class StencilFunction: GLenum { Never = GL_NEVER, /**< Never pass the test. */ Always = GL_ALWAYS, /**< Always pass the test. */ Less = GL_LESS, /**< Pass when reference value is less than buffer value. */ LessOrEqual = GL_LEQUAL, /**< Pass when reference value is less than or equal to buffer value. */ Equal = GL_EQUAL, /**< Pass when reference value is equal to buffer value. */ NotEqual = GL_NOTEQUAL, /**< Pass when reference value is not equal to buffer value. */ GreaterOrEqual = GL_GEQUAL, /**< Pass when reference value is greater than or equal to buffer value. */ Greater = GL_GREATER /**< Pass when reference value is greater than buffer value. */ }; /** * @brief Stencil operation * * @see @ref setStencilOperation() */ enum class StencilOperation: GLenum { Keep = GL_KEEP, /**< Keep the current value. */ Zero = GL_ZERO, /**< Set the stencil buffer value to `0`. */ /** * Set the stencil value to reference value specified by * @ref setStencilFunction(). */ Replace = GL_REPLACE, /** * Increment the current stencil buffer value, clamp to maximum * possible value on overflow. */ Increment = GL_INCR, /** * Increment the current stencil buffer value, wrap to zero on * overflow. */ IncrementWrap = GL_INCR_WRAP, /** * Increment the current stencil buffer value, clamp to minimum * possible value on underflow. */ Decrement = GL_DECR, /** * Decrement the current stencil buffer value, wrap to maximum * possible value on underflow. */ DecrementWrap = GL_DECR_WRAP, /** * Bitwise invert the current stencil buffer value. */ Invert = GL_INVERT }; /** * @brief Set stencil function * @param facing Affected polygon facing * @param function Stencil function. Initial value is * @ref StencilFunction::Always. * @param referenceValue Reference value. Initial value is `0`. * @param mask Mask for both reference and buffer value. * Initial value is all `1`s. * * @attention In @ref MAGNUM_TARGET_WEBGL "WebGL" the reference value * and mask must be the same for both front and back polygon * facing. * @see @ref Feature::StencilTest, @ref setStencilFunction(StencilFunction, Int, UnsignedInt), * @ref setStencilOperation(), @fn_gl{StencilFuncSeparate} */ static void setStencilFunction(PolygonFacing facing, StencilFunction function, Int referenceValue, UnsignedInt mask); /** * @brief Set stencil function * * The same as @ref setStencilFunction(PolygonFacing, StencilFunction, Int, UnsignedInt) * with @p facing set to @ref PolygonFacing::FrontAndBack. * @see @ref Feature::StencilTest, @ref setStencilOperation(), * @fn_gl{StencilFunc} */ static void setStencilFunction(StencilFunction function, Int referenceValue, UnsignedInt mask); /** * @brief Set stencil operation * @param facing Affected polygon facing * @param stencilFail Action when stencil test fails * @param depthFail Action when stencil test passes, but depth * test fails * @param depthPass Action when both stencil and depth test * pass * * Initial value for all fields is @ref StencilOperation::Keep. * @see @ref Feature::StencilTest, @ref setStencilOperation(StencilOperation, StencilOperation, StencilOperation), * @ref setStencilFunction(), @fn_gl{StencilOpSeparate} */ static void setStencilOperation(PolygonFacing facing, StencilOperation stencilFail, StencilOperation depthFail, StencilOperation depthPass); /** * @brief Set stencil operation * * The same as @ref setStencilOperation(PolygonFacing, StencilOperation, StencilOperation, StencilOperation) * with @p facing set to @ref PolygonFacing::FrontAndBack. * @see @ref Feature::StencilTest, @ref setStencilFunction(), * @fn_gl{StencilOp} */ static void setStencilOperation(StencilOperation stencilFail, StencilOperation depthFail, StencilOperation depthPass); /*@}*/ /** @{ @name Depth testing */ /** * @brief Depth function * * @see @ref setDepthFunction() */ typedef StencilFunction DepthFunction; /** * @brief Set depth function * * Initial value is @ref DepthFunction::Less. * @see @ref Feature::DepthTest, @fn_gl{DepthFunc} */ static void setDepthFunction(DepthFunction function); /*@}*/ /** @{ @name Masking writes */ /** * @brief Mask color writes * * Set to `false` to disallow writing to given color channel. Initial * values are all `true`. * @see @ref setDepthMask(), @ref setStencilMask(), @fn_gl{ColorMask} * @todo Masking only given draw buffer */ static void setColorMask(GLboolean allowRed, GLboolean allowGreen, GLboolean allowBlue, GLboolean allowAlpha); /** * @brief Mask depth writes * * Set to `false` to disallow writing to depth buffer. Initial value * is `true`. * @see @ref setColorMask(), @ref setStencilMask(), @fn_gl{DepthMask} */ static void setDepthMask(GLboolean allow); /** * @brief Mask stencil writes * * Set given bit to `0` to disallow writing stencil value for given * faces to it. Initial value is all `1`s. * * @attention In @ref MAGNUM_TARGET_WEBGL "WebGL" the mask must be the * same for both front and back polygon facing. * @see @ref setStencilMask(UnsignedInt), @ref setColorMask(), * @ref setDepthMask(), @fn_gl{StencilMaskSeparate} */ static void setStencilMask(PolygonFacing facing, UnsignedInt allowBits); /** * @brief Mask stencil writes * * The same as calling @ref setStencilMask(PolygonFacing, UnsignedInt) * with `facing` set to @ref PolygonFacing::FrontAndBack. * @see @fn_gl{StencilMask} */ static void setStencilMask(UnsignedInt allowBits); /*@}*/ /** * @{ @name Blending * * You have to enable blending with @ref enable() first. * @todo Blending for given draw buffer */ /** * @brief Blend equation * * @see @ref setBlendEquation() */ enum class BlendEquation: GLenum { Add = GL_FUNC_ADD, /**< `source + destination` */ Subtract = GL_FUNC_SUBTRACT, /**< `source - destination` */ ReverseSubtract = GL_FUNC_REVERSE_SUBTRACT /**< `destination - source` */ #ifndef MAGNUM_TARGET_GLES2 , /** * `min(source, destination)` * @requires_gles30 Extension @es_extension2{EXT,blend_minmax,blend_minmax} * in OpenGL ES 2.0 */ Min = GL_MIN, /** * `max(source, destination)` * @requires_gles30 Extension @es_extension2{EXT,blend_minmax,blend_minmax} * in OpenGL ES 2.0 */ Max = GL_MAX #endif }; /** * @brief Blend function * * @see @ref setBlendFunction() */ enum class BlendFunction: GLenum { /** Zero (@f$ RGB = (0.0, 0.0, 0.0); A = 0.0 @f$) */ Zero = GL_ZERO, /** One (@f$ RGB = (1.0, 1.0, 1.0); A = 1.0 @f$) */ One = GL_ONE, /** * Constant color (@f$ RGB = (R_c, G_c, B_c); A = A_c @f$) * * @see @ref setBlendColor() */ ConstantColor = GL_CONSTANT_COLOR, /** * One minus constant color (@f$ RGB = (1.0 - R_c, 1.0 - G_c, 1.0 - B_c); A = 1.0 - A_c @f$) * * @see @ref setBlendColor() */ OneMinusConstantColor = GL_ONE_MINUS_CONSTANT_COLOR, /** * Constant alpha (@f$ RGB = (A_c, A_c, A_c); A = A_c @f$) * * @see @ref setBlendColor() */ ConstantAlpha = GL_CONSTANT_ALPHA, /** * One minus constant alpha (@f$ RGB = (1.0 - A_c, 1.0 - A_c, 1.0 - A_c); A = 1.0 - A_c @f$) * * @see @ref setBlendColor() */ OneMinusConstantAlpha = GL_ONE_MINUS_CONSTANT_ALPHA, /** Source color (@f$ RGB = (R_{s0}, G_{s0}, B_{s0}); A = A_{s0} @f$) */ SourceColor = GL_SRC_COLOR, #ifndef MAGNUM_TARGET_GLES /** * Second source color (@f$ RGB = (R_{s1}, G_{s1}, B_{s1}); A = A_{s1} @f$) * * @see @ref AbstractShaderProgram::bindFragmentDataLocationIndexed() * @requires_gl33 Extension @extension{ARB,blend_func_extended} * @requires_gl Multiple blending inputs are not available in * OpenGL ES. */ SecondSourceColor = GL_SRC1_COLOR, #endif /** * One minus source color (@f$ RGB = (1.0 - R_{s0}, 1.0 - G_{s0}, 1.0 - B_{s0}); A = 1.0 - A_{s0} @f$) */ OneMinusSourceColor = GL_ONE_MINUS_SRC_COLOR, #ifndef MAGNUM_TARGET_GLES /** * One minus second source color (@f$ RGB = (1.0 - R_{s1}, 1.0 - G_{s1}, 1.0 - B_{s1}); A = 1.0 - A_{s1} @f$) * * @see @ref AbstractShaderProgram::bindFragmentDataLocationIndexed() * @requires_gl33 Extension @extension{ARB,blend_func_extended} * @requires_gl Multiple blending inputs are not available in * OpenGL ES. */ OneMinusSecondSourceColor = GL_ONE_MINUS_SRC1_COLOR, #endif /** Source alpha (@f$ RGB = (A_{s0}, A_{s0}, A_{s0}); A = A_{s0} @f$) */ SourceAlpha = GL_SRC_ALPHA, /** * Saturate source alpha (@f$ RGB = (f, f, f); A = 1.0; f = min(A_s, 1.0 - A_d) @f$) * * Can be used only in source parameter of @ref setBlendFunction(). */ SourceAlphaSaturate = GL_SRC_ALPHA_SATURATE, #ifndef MAGNUM_TARGET_GLES /** * Second source alpha (@f$ RGB = (A_{s1}, A_{s1}, A_{s1}); A = A_{s1} @f$) * * @see @ref AbstractShaderProgram::bindFragmentDataLocationIndexed() * @requires_gl33 Extension @extension{ARB,blend_func_extended} * @requires_gl Multiple blending inputs are not available in * OpenGL ES. */ SecondSourceAlpha = GL_SRC1_ALPHA, #endif /** * One minus source alpha (@f$ RGB = (1.0 - A_{s0}, 1.0 - A_{s0}, 1.0 - A_{s0}); A = 1.0 - A_{s0} @f$) */ OneMinusSourceAlpha = GL_ONE_MINUS_SRC_ALPHA, #ifndef MAGNUM_TARGET_GLES /** * One minus second source alpha (@f$ RGB = (1.0 - A_{s1}, 1.0 - A_{s1}, 1.0 - A_{s1}); A = 1.0 - A_{s1} @f$) * * @see @ref AbstractShaderProgram::bindFragmentDataLocationIndexed() * @requires_gl33 Extension @extension{ARB,blend_func_extended} * @requires_gl Multiple blending inputs are not available in * OpenGL ES. */ OneMinusSecondSourceAlpha = GL_ONE_MINUS_SRC1_ALPHA, #endif /** Destination color (@f$ RGB = (R_d, G_d, B_d); A = A_d @f$) */ DestinationColor = GL_DST_COLOR, /** * One minus source color (@f$ RGB = (1.0 - R_d, 1.0 - G_d, 1.0 - B_d); A = 1.0 - A_d @f$) */ OneMinusDestinationColor = GL_ONE_MINUS_DST_COLOR, /** Destination alpha (@f$ RGB = (A_d, A_d, A_d); A = A_d @f$) */ DestinationAlpha = GL_DST_ALPHA, /** * One minus source alpha (@f$ RGB = (1.0 - A_d, 1.0 - A_d, 1.0 - A_d); A = 1.0 - A_d @f$) */ OneMinusDestinationAlpha = GL_ONE_MINUS_DST_ALPHA }; /** * @brief Set blend equation * * How to combine source color (pixel value) with destination color * (framebuffer). Initial value is @ref BlendEquation::Add. * @see @ref Feature::Blending, @ref setBlendEquation(BlendEquation, BlendEquation), * @ref setBlendFunction(), @ref setBlendColor(), * @fn_gl{BlendEquation} */ static void setBlendEquation(BlendEquation equation); /** * @brief Set blend equation separately for RGB and alpha components * * See @ref setBlendEquation(BlendEquation) for more information. * @see @ref Feature::Blending, @ref setBlendFunction(), * @ref setBlendColor(), @fn_gl{BlendEquationSeparate} */ static void setBlendEquation(BlendEquation rgb, BlendEquation alpha); /** * @brief Set blend function * @param source How the source blending factor is computed * from pixel value. Initial value is @ref BlendFunction::One. * @param destination How the destination blending factor is * computed from framebuffer. Initial value is @ref BlendFunction::Zero. * * @attention In @ref MAGNUM_TARGET_WEBGL "WebGL", constant color and * constant alpha cannot be used together as source and * destination factors. * @see @ref Feature::Blending, @ref setBlendFunction(BlendFunction, BlendFunction, BlendFunction, BlendFunction), * @ref setBlendEquation(), @ref setBlendColor(), * @fn_gl{BlendFunc} */ static void setBlendFunction(BlendFunction source, BlendFunction destination); /** * @brief Set blend function separately for RGB and alpha components * * See @ref setBlendFunction(BlendFunction, BlendFunction) for more * information. * @see @ref Feature::Blending, @ref setBlendEquation(), * @ref setBlendColor(), @fn_gl{BlendFuncSeparate} */ static void setBlendFunction(BlendFunction sourceRgb, BlendFunction destinationRgb, BlendFunction sourceAlpha, BlendFunction destinationAlpha); /** * @brief Set blend color * * Sets constant color used in @ref setBlendFunction() by * @ref BlendFunction::ConstantColor, @ref BlendFunction::OneMinusConstantColor, * @ref BlendFunction::ConstantAlpha and @ref BlendFunction::OneMinusConstantAlpha. * @see @ref Feature::Blending, @ref setBlendEquation(), * @ref setBlendFunction(), @fn_gl{BlendColor} */ static void setBlendColor(const Color4& color); /*@}*/ #ifndef MAGNUM_TARGET_GLES /** @{ @name Logical operation */ /** * @brief Logical operation * * @see @ref setLogicOperation() * @requires_gl Logical operations on framebuffer are not available in * OpenGL ES. */ enum class LogicOperation: GLenum { Clear = GL_CLEAR, /**< `0` */ Set = GL_SET, /**< `1` */ Copy = GL_COPY, /**< `source` */ CopyInverted = GL_COPY_INVERTED,/**< `~source` */ Noop = GL_NOOP, /**< `destination` */ Invert = GL_INVERT, /**< `~destination` */ And = GL_AND, /**< `source & destination` */ AndReverse = GL_AND_REVERSE, /**< `source & ~destination` */ AndInverted = GL_AND_INVERTED, /**< `~source & destination` */ Nand = GL_NAND, /**< `~(source & destination)` */ Or = GL_OR, /**< `source | destination` */ OrReverse = GL_OR_REVERSE, /**< `source | ~destination` */ OrInverted = GL_OR_INVERTED, /**< `~source | destination` */ Nor = GL_NOR, /**< `~(source | destination)` */ Xor = GL_XOR, /**< `source ^ destination` */ Equivalence = GL_EQUIV /**< `~(source ^ destination)` */ }; /** * @brief Set logical operation * * @see @ref Feature::LogicOperation, @fn_gl{LogicOp} * @requires_gl Logical operations on framebuffer are not available in * OpenGL ES. */ static void setLogicOperation(LogicOperation operation); /*@}*/ #endif /** @{ @name Renderer management */ /** * @brief Flush the pipeline * * @see @ref finish(), @fn_gl{Flush} */ static void flush() { glFlush(); } /** * @brief Finish the pipeline * * Blocks until all commands in the pipeline are finished. * @see @ref flush(), @fn_gl{Finish} */ static void finish() { glFinish(); } /** * @brief Error status * * @see @ref error() */ enum class Error: GLenum { /** No error has been recorded */ NoError = GL_NO_ERROR, /** An unacceptable value specified for enumerated argument */ InvalidEnum = GL_INVALID_ENUM, /** A numeric argument is out of range */ InvalidValue = GL_INVALID_VALUE, /** The specified operation is not allowed in the current state */ InvalidOperation = GL_INVALID_OPERATION, /** * The framebuffer object is not complete. * @see AbstractFramebuffer::checkStatus() * @requires_gl30 Extension @extension{ARB,framebuffer_object} */ InvalidFramebufferOperation = GL_INVALID_FRAMEBUFFER_OPERATION, /** There is not enough memory left to execute the command. */ OutOfMemory = GL_OUT_OF_MEMORY, /** * Given operation would cause an internal stack to underflow. * @see @ref DebugGroup * @requires_gl43 Extension @extension{KHR,debug} * @requires_es_extension Extension @es_extension2{KHR,debug,debug} */ #ifndef MAGNUM_TARGET_GLES StackUnderflow = GL_STACK_UNDERFLOW, #else StackUnderflow = GL_STACK_UNDERFLOW_KHR, #endif /** * Given operation would cause an internal stack to overflow. * @see @ref DebugGroup * @requires_gl43 Extension @extension{KHR,debug} * @requires_es_extension Extension @es_extension2{KHR,debug,debug} */ #ifndef MAGNUM_TARGET_GLES StackOverflow = GL_STACK_OVERFLOW #else StackOverflow = GL_STACK_OVERFLOW_KHR #endif }; /** * @brief Error status * * Returns error flag, if any set. If there aren't any more error * flags, returns @ref Error::NoError. Thus this function should be * always called in a loop until it returns @ref Error::NoError. * @see @fn_gl{GetError} */ static Error error() { return static_cast<Error>(glGetError()); } /** * @brief Graphics reset notification strategy * * @see @ref resetNotificationStrategy() * @requires_extension Extension @extension{ARB,robustness} * @requires_es_extension Extension @es_extension{EXT,robustness} */ enum class ResetNotificationStrategy: GLint { /** * No reset notification, thus @ref graphicsResetStatus() will * always return @ref GraphicsResetStatus::NoError. * However this doesn't mean that the context cannot be lost. */ #ifndef MAGNUM_TARGET_GLES NoResetNotification = GL_NO_RESET_NOTIFICATION_ARB, #else NoResetNotification = GL_NO_RESET_NOTIFICATION_EXT, #endif /** * Graphics reset will result in context loss, cause of the reset * can be queried with @ref graphicsResetStatus(). */ #ifndef MAGNUM_TARGET_GLES LoseContextOnReset = GL_LOSE_CONTEXT_ON_RESET_ARB #else LoseContextOnReset = GL_LOSE_CONTEXT_ON_RESET_EXT #endif }; /** * @brief Graphics reset notification strategy * * The result is cached, repeated queries don't result in repeated * OpenGL calls. If OpenGL extension @extension{ARB,robustness} or ES * extension @es_extension{EXT,robustness} is not available, this * function always returns @ref ResetNotificationStrategy::NoResetNotification. * * For the reset notification to work, additionally to the extension * support the context must be created with * @ref Platform::Sdl2Application::Configuration::Flag::RobustAccess "Platform::*Application::Configuration::Flag::RobustAccess" * flag. * * @see @ref graphicsResetStatus(), @fn_gl{Get} with * @def_gl{RESET_NOTIFICATION_STRATEGY_ARB} */ static ResetNotificationStrategy resetNotificationStrategy(); /** * @brief Graphics reset status * * @see @ref resetNotificationStrategy(), @ref graphicsResetStatus() * @requires_extension Extension @extension{ARB,robustness} * @requires_es_extension Extension @es_extension{EXT,robustness} */ enum class GraphicsResetStatus: GLenum { /** No reset occured since last call. */ NoError = GL_NO_ERROR, /** Reset attributable to the current context has been detected. */ #ifndef MAGNUM_TARGET_GLES GuiltyContextReset = GL_GUILTY_CONTEXT_RESET_ARB, #else GuiltyContextReset = GL_GUILTY_CONTEXT_RESET_EXT, #endif /** Reset not attributable to the current context has been detected. */ #ifndef MAGNUM_TARGET_GLES InnocentContextReset = GL_INNOCENT_CONTEXT_RESET_ARB, #else InnocentContextReset = GL_INNOCENT_CONTEXT_RESET_EXT, #endif /** Reset with unknown cause has been detected. */ #ifndef MAGNUM_TARGET_GLES UnknownContextReset = GL_UNKNOWN_CONTEXT_RESET_ARB #else UnknownContextReset = GL_UNKNOWN_CONTEXT_RESET_EXT #endif }; /** * @brief Check graphics reset status * * Reset causes all context state to be lost. If OpenGL extension * @extension{ARB,robustness} or ES extension @es_extension{EXT,robustness} * is not available, this function always returns @ref GraphicsResetStatus::NoError. * * For the reset notification to work, additionally to the extension * support the context must be created with * @ref Platform::Sdl2Application::Configuration::Flag::RobustAccess "Platform::*Application::Configuration::Flag::RobustAccess" * flag. * * If the reset occurs, @extension{ARB,robustness_isolation} * extension is supported and context is created with * @ref Platform::Sdl2Application::Configuration::Flag::ResetIsolation "Platform::*Application::Configuration::Flag::ResetIsolation", * advertised support for @extension{ARB,robustness_application_isolation} * indicates that no other application on the system will be affected * by the graphics reset. Advertised support for * @extension{ARB,robustness_share_group_isolation} indicates that no * other share group will be affected by the graphics reset. * @see @ref resetNotificationStrategy(), * @fn_gl_extension{GetGraphicsResetStatus,ARB,robustness} */ static GraphicsResetStatus graphicsResetStatus(); /*@}*/ private: static void MAGNUM_LOCAL initializeContextBasedFunctionality(); #ifndef MAGNUM_TARGET_GLES static void MAGNUM_LOCAL clearDepthfImplementationDefault(GLfloat depth); #endif static void MAGNUM_LOCAL clearDepthfImplementationES(GLfloat depth); static GraphicsResetStatus MAGNUM_LOCAL graphicsResetStatusImplementationDefault(); static GraphicsResetStatus MAGNUM_LOCAL graphicsResetStatusImplementationRobustness(); }; /** @debugoperatorclassenum{Magnum::Renderer,Magnum::Renderer::Error} */ Debug MAGNUM_EXPORT operator<<(Debug debug, Renderer::Error value); /** @debugoperatorclassenum{Magnum::Renderer,Magnum::Renderer::ResetNotificationStrategy} */ Debug MAGNUM_EXPORT operator<<(Debug debug, Renderer::ResetNotificationStrategy value); /** @debugoperatorclassenum{Magnum::Renderer,Magnum::Renderer::GraphicsResetStatus} */ Debug MAGNUM_EXPORT operator<<(Debug debug, Renderer::GraphicsResetStatus value); } #endif
[ "mosra@centrum.cz" ]
mosra@centrum.cz
d22272bfd5b128d2a7b9adce7541841a9ff7906a
c47e002922aa40e72f01c035ff23d72c6c07b437
/lintcode2/superuglynumber.cpp
c8e1c8f67d5ad15ede697a8c771e9126adfe0954
[ "Apache-2.0" ]
permissive
WIZARD-CXY/pl
4a8b08900aa1f76adab62696fcfe3560df7d49a9
db212e5bdacb22b8ab51cb2e9089bf60c2b4bfca
refs/heads/master
2023-06-10T00:05:37.576769
2023-05-27T03:32:48
2023-05-27T03:32:48
27,328,872
2
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
class Solution { public: /** * @param n a positive integer * @param primes the given prime list * @return the nth super ugly number */ int nthSuperUglyNumber(int n, vector<int>& primes) { // Write your code here int len=primes.size(); vector<int> ugly(n,INT_MAX); vector<int> idx(len,0); ugly[0]=1; for(int i=1; i<n; i++){ for(int j=0; j<len; j++){ ugly[i]=min(ugly[i],primes[j]*ugly[idx[j]]); } for(int j=0; j<len; j++){ if(ugly[i]==primes[j]*ugly[idx[j]]){ idx[j]++; } } } return ugly[n-1]; } };
[ "wizard_cxy@hotmail.com" ]
wizard_cxy@hotmail.com
a81ec504ae6edc0de962cc52059ff06fc4731648
6b40e9cba1dd06cd31a289adff90e9ea622387ac
/Develop/Server/GameServerOck/main/GNPCStress.cpp
000d4ba3410ad89eccb0f514959c2eecaf70c809
[]
no_license
AmesianX/SHZPublicDev
c70a84f9170438256bc9b2a4d397d22c9c0e1fb9
0f53e3b94a34cef1bc32a06c80730b0d8afaef7d
refs/heads/master
2022-02-09T07:34:44.339038
2014-06-09T09:20:04
2014-06-09T09:20:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
cpp
#include "StdAfx.h" #include "GNPCStress.h" #include "GEntityNPC.h" #include "GModuleAI.h" #include "GColtMgr.h" GNPCStress::GNPCStress(GEntityNPC* pOwner) : m_pOwner(pOwner) , m_nStress(0) , m_bStressChanged(false) { m_pOwner->AttachObserver(this); } GNPCStress::~GNPCStress(void) { m_pOwner->DetachObserver(this); } int GNPCStress::GetStress() const { return m_nStress; } void GNPCStress::AddStress( int val ) { m_nStress += val; m_bStressChanged = true; } void GNPCStress::SetStress( int val ) { m_nStress = val; } void GNPCStress::Clear() { m_bStressChanged = false; m_nStress = 0; } void GNPCStress::Update( float fDelta ) { if (!m_bStressChanged) return; m_bStressChanged = false; m_pOwner->GetModuleAI()->GetColt()->RunColtStress(m_pOwner); } void GNPCStress::OnCombatBegin(GEntityActor* pOwner) { Clear(); } void GNPCStress::OnHitEnemy( GEntityActor* pOwner, uint32 nCombatResultFalg, GEntityActor* pTarget, GTalentInfo* pTalentInfo ) { Clear(); }
[ "shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4" ]
shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4
2b54df722689aa83faf4af10fd149503f7430fc7
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_1694_collectd-5.6.1.cpp
4feda4254a2ff156804947e91ad0cc97beb8071b
[]
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
589
cpp
static void lvm_submit (char const *plugin_instance, char const *type_instance, uint64_t ivalue) { value_t v; value_list_t vl = VALUE_LIST_INIT; v.gauge = (gauge_t) ivalue; vl.values = &v; vl.values_len = 1; sstrncpy(vl.host, hostname_g, sizeof (vl.host)); sstrncpy(vl.plugin, "lvm", sizeof (vl.plugin)); sstrncpy(vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); sstrncpy(vl.type, "df_complex", sizeof (vl.type)); sstrncpy(vl.type_instance, type_instance, sizeof (vl.type_instance)); plugin_dispatch_values (&vl); }
[ "993273596@qq.com" ]
993273596@qq.com
0ec0b36d033fb52200abd5f97aaf50bcd31178d7
c2abb873c8b352d0ec47757031e4a18b9190556e
/src/MyGUIEngine/include/MyGUI_SkinManager.h
0ccce3ab80cf8684c3c93facf95abfe987f380b8
[]
no_license
twktheainur/vortex-ee
70b89ec097cd1c74cde2b75f556448965d0d345d
8b8aef42396cbb4c9ce063dd1ab2f44d95e994c6
refs/heads/master
2021-01-10T02:26:21.913972
2009-01-30T12:53:21
2009-01-30T12:53:21
44,046,528
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,987
h
/*! @file @author Albert Semenov @date 11/2007 @module */ #ifndef __MYGUI_SKIN_MANAGER_H__ #define __MYGUI_SKIN_MANAGER_H__ #include "MyGUI_Prerequest.h" #include "MyGUI_Instance.h" #include "MyGUI_WidgetDefines.h" #include "MyGUI_XmlDocument.h" namespace MyGUI { class _MyGUIExport SkinManager { INSTANCE_HEADER(SkinManager); public: typedef std::map<std::string, Align> MapAlign; public: void initialise(); void shutdown(); /** Parse align string */ static Align parseAlign(const std::string & _value); /** Get skin info */ WidgetSkinInfo * getSkin(const Ogre::String & _name); // для ручного создания скина /** Create new skin (used for creating skin in code), if skin with such name already exist - overwrite it */ WidgetSkinInfo * create(const Ogre::String & _name); /** Load additional MyGUI *.skin file */ bool load(const std::string & _file, const std::string & _group = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); void _load(xml::xmlNodePtr _node, const std::string & _file); /** Get texture size in pixels @param _texture file name */ static IntSize getTextureSize(const std::string & _texture); // конвертирует из пиксельных координат в текстурные, в Rect задано начало и размер /** Convert pixel coordinates to texture UV coordinates */ static FloatRect convertTextureCoord(const FloatRect & _source, const IntSize & _textureSize); /** Check that texture have power of two size */ static bool isPowerOfTwo(IntSize _size); /** Check is skin exist */ inline bool isSkinExist(const std::string& _name) { return mSkins.find(_name) != mSkins.end();} private: void createDefault(); private: MapWidgetSkinInfoPtr mSkins; static MapAlign mMapAlign; }; // class SkinManager } // namespace MyGUI #endif // __MYGUI_SKIN_MANAGER_H__
[ "twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83" ]
twk.theainur@37e2baaa-b253-11dd-9381-bf584fb1fa83
9c9b9762f362ab487da373d8d373f20fdd3d93d7
fdfeb3da025ece547aed387ad9c83b34a28b4662
/Applied/CCore/inc/net/PTPConBase.h
741be9fa3622b8432626fcbf8e03289daaf58cf9
[ "FTL", "BSL-1.0" ]
permissive
SergeyStrukov/CCore-3-xx
815213a9536e9c0094548ad6db469e62ab2ad3f7
820507e78f8aa35ca05761e00e060c8f64c59af5
refs/heads/master
2021-06-04T05:29:50.384520
2020-07-04T20:20:29
2020-07-04T20:20:29
93,891,835
8
1
null
null
null
null
UTF-8
C++
false
false
7,035
h
/* PTPConBase.h */ //---------------------------------------------------------------------------------------- // // Project: CCore 3.01 // // Tag: Applied // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2017 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #ifndef CCore_inc_net_PTPConBase_h #define CCore_inc_net_PTPConBase_h #include <CCore/inc/net/PTPExtra.h> namespace CCore { namespace Net { namespace PTPCon { /* using */ using namespace PTP; /* consts */ inline constexpr ulen MaxNameLen = 128 ; inline constexpr ulen DeltaReadLen = 20 ; inline constexpr ulen MaxReadDataLen = 1420 ; inline constexpr ulen DeltaWriteLen = 36 ; inline constexpr ulen MaxWriteDataLen = 1404 ; inline constexpr ServiceIdType ServiceId = 3 ; inline constexpr FunctionIdType FunctionId_Open = 1 ; inline constexpr FunctionIdType FunctionId_Read = 2 ; inline constexpr FunctionIdType FunctionId_Write = 3 ; inline constexpr FunctionIdType FunctionId_Close = 4 ; enum Trigger { TriggerNone, TriggerDefault, // \r \n \t \b TriggerAll }; /* classes */ struct ConId; struct TriggerMask; struct OpenInput; struct OpenOutput; struct ReadInput; struct ReadOutput; struct WriteInput; using WriteOutput = Empty ; struct CloseInput; using CloseOutput = Empty ; /* struct ConId */ struct ConId { uint32 slot; uint64 number; uint64 clock; // constructors ConId() : slot(),number(),clock() {} // methods friend bool operator == (const ConId &a,const ConId &b) { return a.slot==b.slot && a.number==b.number && a.clock==b.clock ; } friend bool operator != (const ConId &a,const ConId &b) { return !(a==b); } // save/load object enum { SaveLoadLen = SaveLenCounter<uint32,uint64,uint64>::SaveLoadLen }; void save(SaveDevType &dev) const { dev.template use<BeOrder>(slot,number,clock); } void load(LoadDevType &dev) { dev.template use<BeOrder>(slot,number,clock); } }; /* struct TriggerMask */ struct TriggerMask { uint32 mask[8]; static uint32 CharBit(uint8 ch) { return UIntBit<uint32>(ch&31u); } uint32 maskOf(uint8 ch) const { return mask[ch>>5]; } uint32 & maskOf(uint8 ch) { return mask[ch>>5]; } // constructors TriggerMask() : mask() {} explicit TriggerMask(const char *zstr) : mask() { set(zstr); } explicit TriggerMask(Trigger t) { switch( t ) { default: case TriggerNone : setNone(); break; case TriggerDefault : setDefault(); break; case TriggerAll : setAll(); break; } } // methods void setNone() { Range(mask).set_null(); } void setDefault() { setNone(); set("\r\n\t\b"); } void setAll() { Range(mask).set(MaxUInt<uint32>); } void set(uint8 ch) { maskOf(ch) |= CharBit(ch) ; } void set(const char *zstr) { for(; char ch=*zstr ;zstr++) set((uint8)ch); } uint32 test(uint8 ch) const { return maskOf(ch) & CharBit(ch) ; } // save/load object enum { SaveLoadLen = 8*SaveLenCounter<uint32>::SaveLoadLen }; void save(SaveDevType &dev) const { SaveRange_use<BeOrder>(Range(mask),dev); } void load(LoadDevType &dev) { LoadRange_use<BeOrder>(Range(mask),dev); } }; /* struct OpenInput */ struct OpenInput // + uint8 name[len]; { static constexpr ulen MaxLen = MaxNameLen ; uint32 write_timeout_msec; uint32 read_timeout_msec; TriggerMask trigger_mask; LenType len; // constructors OpenInput() : write_timeout_msec(),read_timeout_msec(),trigger_mask(),len() {} OpenInput(uint32 write_timeout_msec_,uint32 read_timeout_msec_,const TriggerMask &trigger_mask_,LenType len_) : write_timeout_msec(write_timeout_msec_), read_timeout_msec(read_timeout_msec_), trigger_mask(trigger_mask_), len(len_) { } // save/load object enum { SaveLoadLen = SaveLenCounter<uint32,uint32,TriggerMask,LenType>::SaveLoadLen }; void save(SaveDevType &dev) const { dev.template use<BeOrder>(write_timeout_msec,read_timeout_msec,trigger_mask,len); } void load(LoadDevType &dev) { dev.template use<BeOrder>(write_timeout_msec,read_timeout_msec,trigger_mask,len); } }; /* struct OpenOutput */ struct OpenOutput { ConId con_id; // constructors OpenOutput() : con_id() {} explicit OpenOutput(const ConId &con_id_) : con_id(con_id_) {} // save/load object enum { SaveLoadLen = SaveLenCounter<ConId>::SaveLoadLen }; void save(SaveDevType &dev) const { dev.template use<BeOrder>(con_id); } void load(LoadDevType &dev) { dev.template use<BeOrder>(con_id); } }; /* struct ReadInput */ struct ReadInput { ConId con_id; uint32 number; LenType len; // constructors ReadInput() : con_id(),number(),len() {} ReadInput(const ConId &con_id_,uint32 number_,LenType len_) : con_id(con_id_),number(number_),len(len_) {} // save/load object enum { SaveLoadLen = SaveLenCounter<ConId,uint32,LenType>::SaveLoadLen }; void save(SaveDevType &dev) const { dev.template use<BeOrder>(con_id,number,len); } void load(LoadDevType &dev) { dev.template use<BeOrder>(con_id,number,len); } }; /* struct ReadOutput */ struct ReadOutput // + uint8 data[len]; { static constexpr ulen MaxLen = MaxReadDataLen ; uint32 number; LenType len; // constructors ReadOutput() : number(),len() {} ReadOutput(uint32 number_,LenType len_) : number(number_),len(len_) {} // save/load object enum { SaveLoadLen = SaveLenCounter<uint32,LenType>::SaveLoadLen }; void save(SaveDevType &dev) const { dev.template use<BeOrder>(number,len); } void load(LoadDevType &dev) { dev.template use<BeOrder>(number,len); } }; /* struct WriteInput */ struct WriteInput // + uint8 data[len]; { static constexpr ulen MaxLen = MaxWriteDataLen ; ConId con_id; uint32 number; LenType len; // constructors WriteInput() : con_id(),number(),len() {} WriteInput(const ConId &con_id_,uint32 number_,LenType len_) : con_id(con_id_),number(number_),len(len_) {} // save/load object enum { SaveLoadLen = SaveLenCounter<ConId,uint32,LenType>::SaveLoadLen }; void save(SaveDevType &dev) const { dev.template use<BeOrder>(con_id,number,len); } void load(LoadDevType &dev) { dev.template use<BeOrder>(con_id,number,len); } }; /* struct CloseInput */ struct CloseInput { ConId con_id; // constructors CloseInput() : con_id() {} explicit CloseInput(const ConId &con_id_) : con_id(con_id_) {} // save/load object enum { SaveLoadLen = SaveLenCounter<ConId>::SaveLoadLen }; void save(SaveDevType &dev) const { dev.template use<BeOrder>(con_id); } void load(LoadDevType &dev) { dev.template use<BeOrder>(con_id); } }; } // namespace PTPCon } // namespace Net } // namespace CCore #endif
[ "sshimnick@hotmail.com" ]
sshimnick@hotmail.com
e8d8e65b416ede5939f0e024532ed5975f4bb30f
b3310d8daefc2bb52c0dc844c7f7399466c60cfc
/cMainGame.cpp
6d70f295800a79d36b2c5dc8752d92093ce2fcb5
[]
no_license
LalDi/SmileGate_Project
b89783c296924bedb33a7aa622f023bdbb8f383c
03d6a115f2143d5dd2dec060fea1c901ea694d1b
refs/heads/master
2022-11-24T13:01:15.986313
2020-07-30T14:34:42
2020-07-30T14:34:42
276,552,771
0
0
null
null
null
null
UHC
C++
false
false
2,294
cpp
#include "Framework.h" cMainGame::cMainGame() { ImageManager = nullptr; SceneManager = nullptr; InputManager = nullptr; SoundManager = nullptr; } cMainGame::~cMainGame() { Release(); } void cMainGame::Init() { srand(time(NULL)); ImageManager = new cImageManager(); SceneManager = new cSceneManager(); InputManager = new cInputManager(); SoundManager = new cSoundManager(); // 선언한 매니저를 cGameManager에 전달 cGameManager::Init(ImageManager, SceneManager, InputManager, SoundManager); // INPUTMANAGER 생성 INPUTMANAGER->Create(DXUTGetHWND()); // SOUNDMANAGER 생성 SOUNDMANAGER->Init(); // 게임 내에 사용될 씬을 미리 추가 SCENEMANAGER->AddScene("Title", new cTitleScene()); SCENEMANAGER->AddScene("Ingame", new cIngameScene()); SCENEMANAGER->AddScene("Option", new cOptionScene()); SCENEMANAGER->AddScene("HowToPlay", new cHowToPlayScene()); SCENEMANAGER->AddScene("Credit", new cCreditScene()); // 게임 내에 사용될 사운드를 미리 추가 SOUNDMANAGER->AddSound("Title", L"./Sounds/BGM/Title.wav"); SOUNDMANAGER->AddSound("Stage1", L"./Sounds/BGM/Stage1.wav"); SOUNDMANAGER->AddSound("Stage2", L"./Sounds/BGM/Stage2.wav"); SOUNDMANAGER->AddSound("Stage3", L"./Sounds/BGM/Stage3.wav"); SOUNDMANAGER->AddSound("Warning", L"./Sounds/SE/Warning.wav"); SOUNDMANAGER->AddSound("ShootP", L"./Sounds/SE/PlayerShoot.wav"); SOUNDMANAGER->AddSound("ShootE", L"./Sounds/SE/EnemyShoot.wav"); SOUNDMANAGER->AddSound("Broken", L"./Sounds/SE/Broken.wav"); SOUNDMANAGER->AddSound("Meteo", L"./Sounds/SE/Meteo.wav"); SOUNDMANAGER->AddSound("PlayerHit", L"./Sounds/SE/PlayerHit.wav"); SCENEMANAGER->ChangeScene("Title"); } void cMainGame::Update() { INPUTMANAGER->Update(); SCENEMANAGER->Update(); SOUNDMANAGER->Update(); } void cMainGame::Render() { IMAGEMANAGER->Begin(); SCENEMANAGER->Render(); IMAGEMANAGER->End(); } void cMainGame::Release() { if (ImageManager) { delete ImageManager; ImageManager = nullptr; } if (SceneManager) { delete SceneManager; SceneManager = nullptr; } if (InputManager) { delete InputManager; InputManager = nullptr; } if (SoundManager) { delete SoundManager; SoundManager = nullptr; } } void cMainGame::LostDevice() { } void cMainGame::ResetDevice() { }
[ "jungjh0513@naver.com" ]
jungjh0513@naver.com
4f4db1b659fc428c00ed4f664868447d10c29ae9
bc8418c96b77a812a1fb8f82d11ac3baeeb12085
/windows/CreateEtwTrace.cpp
cc4aed152a3fa3396bd8a49bb39d552a8334219c
[]
no_license
CaledoniaProject/public-src
f9a62dbd727109b2cec0c991cd47d88575295e75
a8c5aafa8eddbd989cd1412f2d68b95393968dc8
refs/heads/master
2023-08-30T21:29:35.414886
2023-08-27T00:55:42
2023-08-27T00:55:42
218,477,380
14
10
null
null
null
null
UTF-8
C++
false
false
2,839
cpp
// TODO: 没有做Trace的关闭 // // 来自 // https://tttang.com/archive/1612/ #include <windows.h> #include <evntcons.h> #include <stdio.h> #define AssemblyDCStart_V1 155 static GUID ClrRuntimeProviderGuid = { 0xe13c0d23, 0xccbc, 0x4e12, { 0x93, 0x1b, 0xd9, 0xcc, 0x2e, 0xee, 0x27, 0xe4 } }; const char name[] = "dotnet trace1"; #pragma pack(1) typedef struct _AssemblyLoadUnloadRundown_V1 { ULONG64 AssemblyID; ULONG64 AppDomainID; ULONG64 BindingID; ULONG AssemblyFlags; WCHAR FullyQualifiedAssemblyName[1]; } AssemblyLoadUnloadRundown_V1, * PAssemblyLoadUnloadRundown_V1; #pragma pack() static void NTAPI ProcessEvent(PEVENT_RECORD EventRecord) { PEVENT_HEADER eventHeader = &EventRecord->EventHeader; PEVENT_DESCRIPTOR eventDescriptor = &eventHeader->EventDescriptor; AssemblyLoadUnloadRundown_V1* assemblyUserData; switch (eventDescriptor->Id) { case AssemblyDCStart_V1: assemblyUserData = (AssemblyLoadUnloadRundown_V1*)EventRecord->UserData; wprintf(L"[%d] - Assembly: %s\n", eventHeader->ProcessId, assemblyUserData->FullyQualifiedAssemblyName); break; } } int main(void) { TRACEHANDLE hTrace = 0; ULONG result, bufferSize; EVENT_TRACE_LOGFILEA trace; EVENT_TRACE_PROPERTIES* traceProp; printf(".net_ETW_finder\n\n"); memset(&trace, 0, sizeof(EVENT_TRACE_LOGFILEA)); trace.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_EVENT_RECORD; trace.LoggerName = (LPSTR)name; trace.EventRecordCallback = (PEVENT_RECORD_CALLBACK)ProcessEvent; bufferSize = sizeof(EVENT_TRACE_PROPERTIES) + strlen(name) + 1; traceProp = (EVENT_TRACE_PROPERTIES*)LocalAlloc(LPTR, bufferSize); traceProp->Wnode.BufferSize = bufferSize; traceProp->Wnode.ClientContext = 2; traceProp->Wnode.Flags = WNODE_FLAG_TRACED_GUID; traceProp->LogFileMode = EVENT_TRACE_REAL_TIME_MODE | EVENT_TRACE_USE_PAGED_MEMORY; traceProp->LogFileNameOffset = 0; traceProp->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); if ((result = StartTraceA(&hTrace, (LPCSTR)name, traceProp)) != ERROR_SUCCESS) { printf("[!] Error starting trace: %d\n", result); return 1; } if ((result = EnableTraceEx( &ClrRuntimeProviderGuid, NULL, hTrace, 1, TRACE_LEVEL_VERBOSE, 0x8, // LoaderKeyword 0, 0, NULL )) != ERROR_SUCCESS) { printf("[!] Error EnableTraceEx\n"); return 2; } hTrace = OpenTraceA(&trace); if (hTrace == INVALID_PROCESSTRACE_HANDLE) { printf("[!] Error OpenTrace\n"); return 3; } result = ProcessTrace(&hTrace, 1, NULL, NULL); if (result != ERROR_SUCCESS) { printf("[!] Error ProcessTrace\n"); return 4; } return 0; }
[ "commit@github.com" ]
commit@github.com
197c49d1be54c8499cccd30aaee2f63bce5b23b6
dbb74305face6ff163847667798298185f7d68b6
/mimmaxoperations/max_min.cpp
3db307cc207a39a93ac666a16befbf73ff99fefc
[ "BSD-2-Clause" ]
permissive
Sinchiguano/Algorithmic-Toolbox
33afabdce3a7307ed4a4d0f443b006154a9ed0b0
7e9dda588a72356fc43fa276016fc3486be47556
refs/heads/master
2020-03-27T22:32:53.785683
2018-09-15T22:05:11
2018-09-15T22:05:11
147,240,634
0
0
null
null
null
null
UTF-8
C++
false
false
842
cpp
/* * max_min.cpp * Copyright (C) 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es> * * Distributed under terms of the BSD license. */ #include<iostream> #include<algorithm> //g++ -std=c++14 -o temp sort.cpp using namespace std; /*compare function for strings*/ bool myMaxCompare(string a, string b) { return (a.size() < b.size()); } bool myMinCompare(string a, string b) { return (a.size() > b.size()); } int main() { int x=4, y=5; std::cout << std::max(x,y) << '\n'; std::cout << std::max(2.345, 5.23)<<endl; std::cout << std::min(2.312, 7.434); std::cout << "\n/* message */" << '\n'; std::string s = "cesar"; std::string t = "sinchiguano"; std::string s1 = std::max(s, t, myMaxCompare); std::cout << s1 << '\n'; std::string s2 = std::min(s, t, myMaxCompare); std::cout << s2 << '\n'; }
[ "cesarsinchiguano@hotmail.es" ]
cesarsinchiguano@hotmail.es
4e338d0078fe03caf8bc7e4200a9333e8dd6371b
e6837c0ef7be61b0ba42e81cf925159e80be84c9
/pgadmin/schema/pgPolicy.cpp
050f677a35ff5dc7853e5fc5d8be3f30dff874f6
[ "PostgreSQL" ]
permissive
jelitox/pgadmin3
80eb7a19c02e248e24add1692b8dc5c9140c0acd
8ffb338e322d6e54b3ba06687708e5c8072451b3
refs/heads/master
2021-10-19T15:29:35.947903
2019-02-22T04:03:03
2019-02-22T04:03:03
171,987,206
0
0
NOASSERTION
2019-02-22T03:20:37
2019-02-22T03:20:37
null
UTF-8
C++
false
false
6,622
cpp
////////////////////////////////////////////////////////////////////////// // // pgAdmin III - PostgreSQL Tools // // Copyright (C) 2002 - 2016, The pgAdmin Development Team // This software is released under the PostgreSQL Licence // // pgPolicy.cpp - Policy class // ////////////////////////////////////////////////////////////////////////// // wxWindows headers #include <wx/wx.h> #include "wx/arrstr.h" // App headers #include "pgAdmin3.h" #include "frm/frmMain.h" #include "utils/misc.h" #include "schema/pgPolicy.h" pgPolicy::pgPolicy(pgSchema *newSchema, const wxString &newName) : pgSchemaObject(newSchema, policyFactory, newName) { } pgPolicy::~pgPolicy() { } wxString pgPolicy::GetTranslatedMessage(int kindOfMessage) const { wxString message = wxEmptyString; switch (kindOfMessage) { case RETRIEVINGDETAILS: message = _("Retrieving details on policy"); message += wxT(" ") + GetName(); break; case REFRESHINGDETAILS: message = _("Refreshing policy"); message += wxT(" ") + GetName(); break; case DROPTITLE: message = _("Drop policy?"); break; case PROPERTIES: message = _("Policy properties"); break; case DROPEXCLUDINGDEPS: message = wxString::Format(_("Are you sure you wish to drop policy \"%s\"?"), GetName().c_str()); break; } return message; } bool pgPolicy::DropObject(wxFrame *frame, ctlTree *browser, bool cascaded) { wxString sql = wxT("DROP POLICY ") + GetName() + wxT(" ON ") + GetQuotedSchemaPrefix(GetSchemaName()) + qtIdent(GetTableName()); return GetDatabase()->ExecuteVoid(sql); } wxString pgPolicy::GetSql(ctlTree *browser) { if (sql.IsNull()) { sql = wxT("-- Policy: ") + GetQuotedIdentifier() + wxT("\n\n") + wxT("-- DROP POLICY ") + GetQuotedIdentifier() + wxT(" ON ") + GetQuotedSchemaPrefix(GetSchemaName()) + qtIdent(GetTableName()) + wxT(";\n\n"); sql += wxT("CREATE POLICY ") + GetIdentifier() + wxT(" ON ") + GetQuotedSchemaPrefix(GetSchemaName()) + qtIdent(GetTableName()); sql += wxT("\n FOR ") + GetCommand() + wxT("\n TO ") + GetRoles(); if (!GetUsingExpr().IsNull()) sql += wxT("\n USING (") + GetUsingExpr() + wxT(")"); if (!GetCheckExpr().IsNull()) sql += wxT("\n WITH CHECK (") + GetCheckExpr() + wxT(")"); sql += wxT(";\n\n"); if (!GetComment().IsNull()) { sql += wxT("COMMENT ON POLICY ") + GetQuotedIdentifier() + wxT(" ON ") + GetQuotedSchemaPrefix(GetSchemaName()) + qtIdent(GetTableName()) + wxT(" IS ") + qtDbString(GetComment()) + wxT(";\n"); } } return sql; } void pgPolicy::ParseRoles(const wxString &s) { wxString r = s.Mid(1, s.Length() - 2); if (!r.IsEmpty()) FillArray(roles, r); } wxString pgPolicy::GetRoles() const { wxString result = wxEmptyString; for (size_t index = 0; index < roles.GetCount(); index++) { result += roles.Item(index); if (!(index + 1 == roles.GetCount())) result += wxT(", "); } return result; } void pgPolicy::ShowTreeDetail(ctlTree *browser, frmMain *form, ctlListView *properties, ctlSQLBox *sqlPane) { if (properties) { CreateListColumns(properties); properties->AppendItem(_("Name"), GetName()); properties->AppendItem(_("Defined for"), GetTableName()); properties->AppendItem(_("OID"), GetOid()); properties->AppendItem(_("Roles"), GetRoles()); properties->AppendItem(_("Command"), GetCommand()); properties->AppendItem(_("Using expression"), GetUsingExpr()); properties->AppendItem(_("Check expression"), GetCheckExpr()); properties->AppendItem(_("Comment"), GetComment()); } } pgObject *pgPolicy::Refresh(ctlTree *browser, const wxTreeItemId item) { pgObject *policy = 0; pgCollection *coll = browser->GetParentCollection(item); if (coll) policy = policyFactory.CreateObjects(coll, 0, wxT("\n AND p.oid=") + GetOidStr()); return policy; } pgObject *pgPolicyFactory::CreateObjects(pgCollection *coll, ctlTree *browser, const wxString &restriction) { pgSchemaObjCollection *collection = (pgSchemaObjCollection *)coll; pgPolicy *policy = 0; wxString sql = wxT("SELECT p.oid AS oid, p.polname AS polname, ") wxT(" pp.schemaname AS schemaname, pp.tablename AS tablename, pp.roles AS roles, pp.cmd AS cmd, ") wxT(" pp.qual AS using, pp.with_check AS check, d.description AS description ") wxT(" FROM pg_policy p\n") wxT(" JOIN pg_policies pp ON p.polname = policyname\n") wxT(" LEFT JOIN pg_description d ON p.oid = d.objoid\n") wxT(" WHERE p.polrelid = ") + collection->GetOidStr() + wxT(" ORDER BY p.polname"); pgSet *policies = collection->GetDatabase()->ExecuteSet(sql); if (policies) { while (!policies->Eof()) { policy = new pgPolicy(collection->GetSchema()->GetSchema(), policies->GetVal(wxT("polname"))); policy->iSetOid(policies->GetOid(wxT("oid"))); policy->iSetName(policies->GetVal(wxT("polname"))); policy->iSetSchemaName(policies->GetVal(wxT("schemaname"))); policy->iSetTableName(policies->GetVal(wxT("tablename"))); policy->ParseRoles(policies->GetVal(wxT("roles"))); policy->iSetCommand(policies->GetVal(wxT("cmd"))); policy->iSetUsingExpr(policies->GetVal(wxT("using"))); policy->iSetCheckExpr(policies->GetVal(wxT("check"))); policy->iSetComment(policies->GetVal(wxT("description"))); if (browser) { browser->AppendObject(collection, policy); policies->MoveNext(); } else break; } delete policies; } return policy; } ///////////////////////////// pgPolicyCollection::pgPolicyCollection(pgaFactory *factory, pgSchema *sch) : pgSchemaObjCollection(factory, sch) { } wxString pgPolicyCollection::GetTranslatedMessage(int kindOfMessage) const { wxString message = wxEmptyString; switch (kindOfMessage) { case RETRIEVINGDETAILS: message = _("Retrieving details on policies"); break; case REFRESHINGDETAILS: message = _("Refreshing policies"); break; case OBJECTSLISTREPORT: message = _("Check policies list report"); break; } return message; } ///////////////////////////// #include "images/policies.pngc" #include "images/policy.pngc" pgPolicyFactory::pgPolicyFactory() : pgSchemaObjFactory(__("Policy"), __("New Policy..."), __("Create a new Policy."), policy_png_img) { metaType = PGM_POLICY; } pgCollection *pgPolicyFactory::CreateCollection(pgObject *obj) { return new pgPolicyCollection(GetCollectionFactory(), (pgSchema *)obj); } pgPolicyFactory policyFactory; pgaCollectionFactory policyCollectionFactory(&policyFactory, __("Policies"), policies_png_img);
[ "jel1284@gmail.com" ]
jel1284@gmail.com
c5a22be07753693833632cc7a014eedcf53665b6
8e9f67d56cab10affc9ee8912d36435e6cd06245
/Sandbox/src/gui/MainWindow.cpp
019dc17f64bccd2eaee041ee66a9b96d55eba7ee
[]
no_license
Cooble/NiceDay
79d4fd88d5ee40b025790bf3b7a2fd80fa966333
56b507b1f853240493affae82ad792f8054d635a
refs/heads/master
2023-08-18T23:21:44.348957
2023-01-20T18:23:07
2023-01-20T18:23:07
179,539,325
14
0
null
2021-05-12T17:34:09
2019-04-04T16:52:23
JavaScript
UTF-8
C++
false
false
18,164
cpp
#include "MainWindow.h" #include "core/App.h" #include "event/MessageEvent.h" #include "gui/GUIContext.h" #include "GUICustomRenderer.h" #include "Translator.h" #include "world/WorldsProvider.h" #include "window_messeages.h" #include "event/ControlMap.h" #include "event/KeyEvent.h" #include "core/NBT.h" #include "files/FUtil.h" #include "gui/GUIParser.h" using namespace nd; FontMaterial* GameFonts::bigFont; FontMaterial* GameFonts::smallFont; static float logoTransient = -1.3; MainWindow::MainWindow(const MessageConsumer& c) :m_messenger(c) { width = APwin()->getWidth(); height = APwin()->getHeight(); isVisible = false; isMoveable = false; isResizable = false; dimInherit = GUIDimensionInherit::WIDTH_HEIGHT; setCenterPosition(APwin()->getWidth(), APwin()->getHeight()); auto material = GameFonts::bigFont; auto col = new GUIColumn(); col->isAlwaysPacked = true; col->setAlignment(GUIAlign::CENTER); long long micros = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count(); int rand = micros % 6; auto logo = Texture::create(TextureInfo("res/images/logos/" + std::to_string(rand) + ".png").filterMode(TextureFilterMode::LINEAR)); auto res = new SpriteSheetResource(logo, 1, 1); m_logo = new GUIImage(); m_logo->setImage(new Sprite(res)); m_logo->image->setSize({ logo->width(), logo->height() }); m_logo->packDimensions(); m_logo->isAlwaysPacked = true; m_logo->scale = 0; col->appendChild(m_logo); auto dims = new GUIElement(GETYPE::Blank); dims->dim = { 0,25 }; dims->isVisible = false; col->appendChild(dims); //scale japanese auto gengo = App::get().getSettings()["language"]; float maxScale = 1.2 + (gengo.string() == "jp" ? 0.2 : 0); float minScale = 0.7 + (gengo.string() == "jp" ? 0.3 : 0); //auto playBtn = new GUISpecialTextButton(Font::colorizeBorder(Font::BLACK)+"&0P&1l&2a&3y &4P&5l&6a&7y &8P&9l&aa&by &cP&dl&ea&fy!", material); auto playBtn = new GUISpecialTextButton(ND_TRANSLATE("main.btn.play_play"), material); //auto playBtn = new GUISpecialTextButton("Play", material); playBtn->dim = { 200,50 }; playBtn->maxScale = maxScale; playBtn->minScale = minScale; playBtn->onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenWorldSelection)); logoTransient = -1; }; col->appendChild(playBtn); auto playNew = new GUISpecialTextButton(ND_TRANSLATE("main.btn.play"), material); playNew->dim = { 200,50 }; playNew->maxScale = maxScale; playNew->minScale = minScale; playNew->onPressed = [this](GUIElement& e) { logoTransient = -1; m_messenger(MessageEvent(WindowMess::OpenSkin)); }; col->appendChild(playNew); auto setBtn = new GUISpecialTextButton(ND_TRANSLATE("main.btn.settings"), material); setBtn->dim = { 200,50 }; setBtn->maxScale = maxScale; setBtn->minScale = minScale; setBtn->onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenSettings)); }; col->appendChild(setBtn); auto exitBtn = new GUISpecialTextButton(ND_TRANSLATE("main.btn.exit"), material); exitBtn->dim = { 200,50 }; exitBtn->maxScale = maxScale; exitBtn->minScale = minScale; exitBtn->onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenExit)); }; col->appendChild(exitBtn); appendChild(col); } void MainWindow::update() { GUIWindow::update(); {//logo animation static float scaleUp = 0; logoTransient += 0.06; scaleUp += 0.01; m_logo->renderAngle = std::sin((scaleUp + 3.14159 / 2) / 2) / 8; float s = std::clamp(logoTransient, 0.f, 1.5f); if (s > 1.25f) s = 1.25 - (s - 1.25); m_logo->scale = (((1 + std::sin(scaleUp)) / 2) * 0.15 + 1) * s; } } GUIWorldEntry::GUIWorldEntry(MessageConsumer* c) :m_messenger(c) { auto material = GameFonts::smallFont; static SpriteSheetResource* res = new SpriteSheetResource( Texture::create(TextureInfo("res/images/gui_atlas.png").filterMode(TextureFilterMode::NEAREST)), 4, 4); setPadding(10); isAlwaysPacked = false; isVisible = true; dimInherit = GUIDimensionInherit::WIDTH; height = 100; m_world_name = new GUIText(material); m_world_name->setAlignment(GUIAlign::LEFT_UP); color = { 1,0,1,1 }; appendChild(m_world_name); auto playBtn = new GUIImageButton(new Sprite(res)); playBtn->isVisible = false; playBtn->dim = { 22,22 }; playBtn->getImageElement()->image->setSpriteIndex(2, 0); playBtn->getImageElement()->dim = { 32,32 }; playBtn->getImageElement()->setAlignment(GUIAlign::LEFT_DOWN); playBtn->onFocusGain = [playBtn](GUIElement& e) { playBtn->getImageElement()->image->setSpriteIndex(1, 0); }; playBtn->onFocusLost = [playBtn](GUIElement& e) { playBtn->getImageElement()->image->setSpriteIndex(2, 0); }; playBtn->onPressed = [this](GUIElement& e) { auto data = ND_TEMP_EMPLACE(WindowMessageData::World); data->worldName = this->getWorldName(); auto m = MessageEvent(WindowMess::OpenPlayWorld, 0, data); (*m_messenger)(m); /*auto dat = App::get().getBufferedAllocator().emplace<CommonMessages::WorldMessage>(); dat->type = CommonMessages::WorldMessage::PLAY; dat->worldName = m_world_name->getText(); App::get().fireEvent(MessageEvent("Play", 0, dat));*/ }; auto deleteBtn = new GUIImageButton(new Sprite(res)); deleteBtn->isVisible = false; deleteBtn->dim = { 22,22 }; deleteBtn->getImageElement()->image->setSpriteIndex(0, 1); deleteBtn->getImageElement()->dim = { 32,32 }; deleteBtn->getImageElement()->setAlignment(GUIAlign::LEFT_DOWN); deleteBtn->onFocusGain = [deleteBtn](GUIElement& e) { deleteBtn->getImageElement()->image->setSpriteIndex(1, 1); }; deleteBtn->onFocusLost = [deleteBtn](GUIElement& e) { deleteBtn->getImageElement()->image->setSpriteIndex(0, 1); }; deleteBtn->onPressed = [this](GUIElement& e) { auto data = ND_TEMP_EMPLACE(WindowMessageData::World); data->worldName = this->getWorldName(); auto m = MessageEvent(WindowMess::ActionDeleteWorld, 0, data); (*m_messenger)(m); }; deleteBtn->setAlignment(GUIAlign::RIGHT_DOWN); auto row = new GUIRow(); row->isAlwaysPacked = true; row->setAlignment(GUIAlign::LEFT_DOWN); row->appendChild(playBtn); appendChild(row); appendChild(deleteBtn); } void GUIWorldEntry::setWorldName(const std::string& name) { m_world_name->setText(name); } const std::string& GUIWorldEntry::getWorldName() { return m_world_name->getText(); } SelectWorldWindow::SelectWorldWindow(const MessageConsumer& c) :m_messenger(c) { GUIParser::parseWindow(FUtil::readFileString("res/xml_gui/world_select.xml"), *this); auto material = GameFonts::bigFont; auto materialSmall = GameFonts::smallFont; //createbtn auto createNewBtn = get<GUITextButton>("btn.create_world"); //create txtbox auto textBox = get<GUITextBox>("txtBox"); auto onWorldCrea = [textBox, this](GUIElement& e) { if (textBox->getValue().empty()) return; auto data = ND_TEMP_EMPLACE(WindowMessageData::World); data->worldName = textBox->getValue(); auto m = MessageEvent(WindowMess::ActionGenerateWorld, 0, data); m_messenger(m); }; textBox->onValueEntered = onWorldCrea; createNewBtn->onPressed = onWorldCrea; m_world_slider = get<GUIVSlider>("slider"); //view column m_world_column = get<GUIColumn>("keyColumn"); //back btn auto bckBtn = new GUITextButton(ND_TRANSLATE("btn.back"), material); bckBtn->dim = { 700, bckBtn->getTextElement()->height + bckBtn->heightPadding() }; get<GUIButton>("btn.back")->onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenBack)); }; } void SelectWorldWindow::setWorlds(const std::vector<WorldInfoData>& worlds) { m_world_column->clearChildren(); m_world_column->adaptToParent(); for (auto& world : worlds) { auto worlde = new GUIWorldEntry(&m_messenger); worlde->setWorldName(world.name); m_world_column->appendChild(worlde); } m_world_column->adaptToParent(); m_world_slider->setValue(1); } PauseWindow::PauseWindow(const MessageConsumer& c) :m_messenger(c) { width = APwin()->getWidth(); height = APwin()->getHeight(); setCenterPosition(APwin()->getWidth(), APwin()->getHeight()); isVisible = false; isMoveable = false; isResizable = false; setAlignment(GUIAlign::CENTER); dimInherit = GUIDimensionInherit::WIDTH_HEIGHT; auto material = GameFonts::bigFont; auto materialSmall = GameFonts::smallFont; auto mainCol = new GUIColumn(); mainCol->isAlwaysPacked = true; mainCol->dimInherit = GUIDimensionInherit::WIDTH; mainCol->setAlignment(GUIAlign::CENTER); auto centerBox = new GUIBlank(); centerBox->setPadding(10); centerBox->isAlwaysPacked = false; centerBox->dim = { 500,230 }; centerBox->isVisible = true; centerBox->setAlignment(GUIAlign::CENTER); //Column auto col = new GUIColumn(); col->dimInherit = GUIDimensionInherit::WIDTH_HEIGHT; col->space = 15; col->setAlignment(GUIAlign::CENTER); centerBox->appendChild(col); auto spacer = new GUIBlank(); spacer->isAlwaysPacked = false; spacer->height = 50; col->appendChild(spacer); //createbtn auto createNewBtn = new GUITextButton(ND_TRANSLATE("btn.continue"), materialSmall); createNewBtn->setAlignment(GUIAlign::CENTER); createNewBtn->isAlwaysPacked = true; createNewBtn->setPadding(5); createNewBtn->onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenBack)); }; col->appendChild(createNewBtn); //goToMainScreenBtn auto goToMainScreenBtn = new GUITextButton(ND_TRANSLATE("btn.save_go_menu"), materialSmall); goToMainScreenBtn->setAlignment(GUIAlign::CENTER); goToMainScreenBtn->isAlwaysPacked = true; goToMainScreenBtn->setPadding(5); goToMainScreenBtn->onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::ActionWorldQuit)); }; col->appendChild(goToMainScreenBtn); //Title auto title = new GUIText(material); title->setText(ND_TRANSLATE("title.pause")); title->setAlignment(GUIAlign::CENTER); auto blankTitle = new GUIBlank(); blankTitle->setPadding(10); blankTitle->isAlwaysPacked = true; blankTitle->isVisible = true; blankTitle->appendChild(title); blankTitle->y = centerBox->height - blankTitle->height / 2; blankTitle->x = centerBox->width / 2 - blankTitle->width / 2; centerBox->appendChild(blankTitle); mainCol->appendChild(centerBox); appendChild(mainCol); } ControlsWindow::ControlsWindow(const MessageConsumer& c) :m_messenger(c) { auto material = GameFonts::bigFont; auto materialSmall = GameFonts::smallFont; GUIParser::parseWindow(FUtil::readFileString("res/xml_gui/settings_template.xml"), *this); // title get<GUIText>("template.title")->setText(ND_TRANSLATE("title.controls")); //custom column fill auto keyColumn = get<GUIColumn>("keyColumn"); for (auto& pair : ControlMap::getControlsList()) { auto button = new GUISpecialTextButton(pair.first + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName(*pair.second.pointer), materialSmall); button->minScale = 1; button->maxScale = 1; button->setPadding(10); button->packDimensions(); keyColumn->appendChild(button); button->onPressed = [button, titlo = pair.first](GUIElement& e) { if (GUIContext::get().getFocusedElement() != &e) { GUIContext::get().setFocusedElement(&e); button->getTextElement()->setText(Font::BLUE + titlo + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName(*ControlMap::getButtonData(titlo)->pointer)); } else { auto loc = APin().getMouseLocation(); if (!e.contains(loc.x, loc.y)) { GUIContext::get().setFocusedElement(nullptr); e.onMyEventFunc(MouseFocusLost(0, 0), e); } } }; button->onMyEventFunc = [button, titlo = pair.first](Event& eve, GUIElement& e) { if (GUIContext::get().getFocusedElement() == &e) { if (eve.getEventType() == Event::EventType::KeyPress) { auto m = static_cast<KeyPressEvent&>(eve); ControlMap::setValueAtPointer(titlo, (uint64_t)m.getKey()); button->getTextElement()->setText(titlo + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName((uint64_t)m.getKey())); GUIContext::get().setFocusedElement(nullptr); } } else if (eve.getEventType() == Event::EventType::MouseFocusGain) { button->getTextElement()->setText(Font::GREEN + titlo + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName(*ControlMap::getButtonData(titlo)->pointer)); } else if (eve.getEventType() == Event::EventType::MouseFocusLost) { button->getTextElement()->setText(titlo + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName(*ControlMap::getButtonData(titlo)->pointer)); } }; } for (auto& pair : ControlMap::getControlsList()) { auto button = new GUISpecialTextButton(pair.first + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName(*pair.second.pointer), materialSmall); button->minScale = 1; button->maxScale = 1; button->setPadding(10); button->packDimensions(); keyColumn->appendChild(button); button->onPressed = [button, titlo = pair.first](GUIElement& e) { if (GUIContext::get().getFocusedElement() != &e) { GUIContext::get().setFocusedElement(&e); button->getTextElement()->setText(Font::BLUE + titlo + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName(*ControlMap::getButtonData(titlo)->pointer)); } else { auto loc = APin().getMouseLocation(); if (!e.contains(loc.x, loc.y)) { GUIContext::get().setFocusedElement(nullptr); e.onMyEventFunc(MouseFocusLost(0, 0), e); } } }; button->onMyEventFunc = [button, titlo = pair.first](Event& eve, GUIElement& e) { if (GUIContext::get().getFocusedElement() == &e) { if (eve.getEventType() == Event::EventType::KeyPress) { auto m = static_cast<KeyPressEvent&>(eve); ControlMap::setValueAtPointer(titlo, (uint64_t)m.getKey()); button->getTextElement()->setText(titlo + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName((uint64_t)m.getKey())); GUIContext::get().setFocusedElement(nullptr); } } else if (eve.getEventType() == Event::EventType::MouseFocusGain) { button->getTextElement()->setText(Font::GREEN + titlo + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName(*ControlMap::getButtonData(titlo)->pointer)); } else if (eve.getEventType() == Event::EventType::MouseFocusLost) { button->getTextElement()->setText(titlo + ": " + Font::colorize(Font::BLACK, "#013220") + ControlMap::getKeyName(*ControlMap::getButtonData(titlo)->pointer)); } }; } // back buttons auto onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenBack)); }; get<GUIButton>("btn.back")->onPressed = onPressed; get<GUIButton>("btn.save_back")->onPressed = onPressed; } SettingsWindow::SettingsWindow(const MessageConsumer& c) :m_messenger(c) { auto material = GameFonts::bigFont; auto materialSmall = GameFonts::smallFont; GUIParser::parseWindow(FUtil::readFileString("res/xml_gui/settings_template.xml"), *this); // title get<GUIText>("template.title")->setText(ND_TRANSLATE("title.settings")); //custom column fill auto keyColumn = get<GUIColumn>("keyColumn"); //nav controls button auto navCon = new GUITextButton(ND_TRANSLATE("btn.controls"), materialSmall); navCon->onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenControls)); }; navCon->setPadding(5); navCon->isAlwaysPacked = true; keyColumn->appendChild(navCon); auto lang = new GUITextButton(ND_TRANSLATE("btn.lang"), materialSmall); lang->setPadding(5); lang->onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenLanguage)); }; lang->isAlwaysPacked = true; keyColumn->appendChild(lang); // back buttons auto onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenBack)); }; get<GUIButton>("btn.back")->onPressed = onPressed; get<GUIButton>("btn.save_back")->onPressed = onPressed; } LanguageWindow::LanguageWindow(const MessageConsumer& c) :m_messenger(c) { GUIParser::parseWindow(FUtil::readFileString("res/xml_gui/settings_template.xml"), *this); auto material = GameFonts::bigFont; auto materialSmall = GameFonts::smallFont; // title get<GUIText>("template.title")->setText(ND_TRANSLATE("title.language")); // custom column fill auto keyColumn = get<GUIColumn>("keyColumn"); auto& list = AppLanguages::getLanguages(); for (auto& lang : list) { bool selected = lang.abbrev == AppLanguages::getCurrentLanguage(); auto btn = new GUITextButton((selected ? Font::colorizeBorder(Font::BLACK) + Font::GREEN : "") + lang.name, materialSmall); if (!selected) { btn->onPressed = [this, abbrev = lang.abbrev](GUIElement& e) { App::get().fireEvent(MessageEvent("language_change", abbrev)); m_messenger(MessageEvent(WindowMess::OpenBack));//go up m_messenger(MessageEvent(WindowMess::OpenLanguage));//go back again }; } btn->setPadding(5); btn->isAlwaysPacked = true; keyColumn->appendChild(btn); } // back button auto onPressed = [this](GUIElement& e) { m_messenger(MessageEvent(WindowMess::OpenBack)); }; get<GUIButton>("btn.back")->onPressed = onPressed; get<GUIButton>("btn.save_back")->onPressed = onPressed; } SkinWindow::SkinWindow(const MessageConsumer& c) :m_messenger(c) { width = APwin()->getWidth(); height = APwin()->getHeight(); setCenterPosition(APwin()->getWidth(), APwin()->getHeight()); GUIParser::parseWindow(FUtil::readFileString("res/xml_gui/world_select.xml"), *this); } void SkinWindow::onMyEvent(Event& e) { GUIWindow::onMyEvent(e); auto ee = dynamic_cast<MousePressEvent*>(&e); if (ee) { GUIContext::get().setFocusedElement(this); } if (KeyPressEvent::getKeyNumber(e) == KeyCode::R) { clearChildren(); GUIParser::parseWindow(FUtil::readFileString("res/xml_gui/world_select.xml"), *this); } else if (KeyPressEvent::getKeyNumber(e) == KeyCode::B) { GUIContext::get().setFocusedElement(nullptr); m_messenger(MessageEvent(WindowMess::OpenBack)); } }
[ "minekoza@gmail.com" ]
minekoza@gmail.com
5f1e9eb34f109393aebebae6a68bfb7073cee4d6
9f1c4be5e964218d161423f1eebcd43b548a5456
/FirstMFCDlg/FirstMFCDlg.cpp
b66be1d92d8080a23825f2bd0b926c3cc3a7ce8b
[]
no_license
Jeanhwea/WindowsProgramming
914f542b6e1555cb2118a63d1a24154bb52fe133
432545e5b5576d010fbbeb5ceacb310c73668cad
refs/heads/master
2021-01-10T16:34:34.183295
2016-02-24T12:21:25
2016-02-24T12:21:25
48,323,880
2
0
null
null
null
null
GB18030
C++
false
false
2,918
cpp
// FirstMFCDlg.cpp : 定义应用程序的类行为。 // #include "stdafx.h" #include "FirstMFCDlg.h" #include "CFirstMFCDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CFirstMFCDlgApp BEGIN_MESSAGE_MAP(CFirstMFCDlgApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CFirstMFCDlgApp 构造 CFirstMFCDlgApp::CFirstMFCDlgApp() { // 支持重新启动管理器 m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: 在此处添加构造代码, // 将所有重要的初始化放置在 InitInstance 中 } // 唯一的一个 CFirstMFCDlgApp 对象 CFirstMFCDlgApp theApp; // CFirstMFCDlgApp 初始化 BOOL CFirstMFCDlgApp::InitInstance() { // 如果一个运行在 Windows XP 上的应用程序清单指定要 // 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式, //则需要 InitCommonControlsEx()。否则,将无法创建窗口。 INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // 将它设置为包括所有要在应用程序中使用的 // 公共控件类。 InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // 创建 shell 管理器,以防对话框包含 // 任何 shell 树视图控件或 shell 列表视图控件。 CShellManager *pShellManager = new CShellManager; // 激活“Windows Native”视觉管理器,以便在 MFC 控件中启用主题 CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); // 标准初始化 // 如果未使用这些功能并希望减小 // 最终可执行文件的大小,则应移除下列 // 不需要的特定初始化例程 // 更改用于存储设置的注册表项 // TODO: 应适当修改该字符串, // 例如修改为公司或组织名 SetRegistryKey(_T("应用程序向导生成的本地应用程序")); CFirstMFCDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: 在此放置处理何时用 // “确定”来关闭对话框的代码 } else if (nResponse == IDCANCEL) { // TODO: 在此放置处理何时用 // “取消”来关闭对话框的代码 } else if (nResponse == -1) { TRACE(traceAppMsg, 0, "警告: 对话框创建失败,应用程序将意外终止。\n"); TRACE(traceAppMsg, 0, "警告: 如果您在对话框上使用 MFC 控件,则无法 #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS。\n"); } // 删除上面创建的 shell 管理器。 if (pShellManager != NULL) { delete pShellManager; } // 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序, // 而不是启动应用程序的消息泵。 return FALSE; }
[ "hujinghui@buaa.edu.cn" ]
hujinghui@buaa.edu.cn
b24fa173cd21f04aff231fb2e3637eedb81bd999
d38a0692cd1759367b25a65261335a3be9040fb6
/Challenges/C_CPP/0017_dangling_reference/factoryComplex.cpp
4852e454339e8ffd9db901da4c88c1095585b196
[ "MIT" ]
permissive
saucec0de/sifu
8308f43e70e084002233b944ca0c9becbcb91571
7924844e1737c7634016c677237bccd7e7651818
refs/heads/main
2023-01-28T11:22:18.058418
2020-12-02T14:10:01
2020-12-02T14:10:01
317,881,746
5
0
null
null
null
null
UTF-8
C++
false
false
959
cpp
#include <iostream> #include <complex> #include <new> #include "factoryComplex.h" //Constructor allocates the complexContainer array of MAX elements FactoryComplex::FactoryComplex(int _max): max(_max){ position = 0; complexContainer = new std::complex<int>[max]; } //Creates a complex number, stores it in the container and returns a reference to that element std::complex<int>& FactoryComplex::create(int x, int y) { std::complex<int> a = std::complex<int>(x,y); complexContainer[position++] = a; return a; } //Returns a reference to an element stored in the container with an index: index - 1 //If we call .get(1) -> we expect element complexContainer[0] std::complex<int>& FactoryComplex::get(int index){ return complexContainer[index - 1]; } //Frees the allocated array, after calling this method //no further method calls should be allowed //E.g. factoryComplex.get(index); void FactoryComplex::empty(){ delete complexContainer; }
[ "tiago.gasiba@gmail.com" ]
tiago.gasiba@gmail.com
8dcb80809909f813b37994e8f8d58f592d3e176e
43e9ceece978228be0c9859fb43edfd3a4c266a0
/cytosim/src/base/random_inline.h
fe03b63b61c5dfcf4fd762d63134c81277a0efb1
[]
no_license
CyCelsLab/Multi-aster-swaming
ef4eb28d229235ee9887c12bf5792dfe8ea6d3e1
a3fb7241960c3664a245210accd6bd0ffcbfe4f0
refs/heads/master
2022-11-19T22:39:20.914910
2020-07-25T18:06:34
2020-07-25T18:06:34
260,443,252
0
0
null
null
null
null
UTF-8
C++
false
false
13,522
h
//RCS: $Id: random_inline.h,v 2.1 2005/01/10 17:27:47 foethke Exp $ // Modified by F. Nedelec, October 2002 and later for the needs of Cytosim // 29 March 2003: added gaussian random numbers // August 2003: added signed integer arguments to pint_() // Sept 2003: added random integer according to given distribution // END modications by F. nedelec // MersenneTwister.h // Mersenne Twister random number generator -- a C++ class MTRand // Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus // Richard J. Wagner v0.8 24 March 2002 rjwagner@writeme.com // The Mersenne Twister is an algorithm for generating random numbers. It // was designed with consideration of the flaws in various other generators. // The period, 2^19937-1, and the order of equidistribution, 623 dimensions, // are far greater. The generator is also fast; it avoids multiplication and // division, and it benefits from caches and pipelines. For more information // see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html // Reference // M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally // Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on // Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. // Copyright (C) 2002 Richard J. Wagner // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // The original code included the following notice: // // Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura. // When you use this, send an email to: matumoto@math.keio.ac.jp // with an appropriate reference to your work. // // It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu // when you write. #ifndef RANDOM_H #define RANDOM_H // Not thread safe (unless auto-initialization is avoided and each thread has // its own MTRand object) #include <climits> #include <ctime> #include <cstdio> #include "assert_macro.h" #include "smath.h" class Random { //================================= Data ================================= public: typedef unsigned int uint32; // unsigned integer type, min 32 bits typedef signed int int32; enum { N = 624 }; // length of state vector enum { SAVE = N + 1 }; // length of array for save() protected: enum { M = 397 }; // period parameter enum { MAGIC = 0x9908b0dfU }; // magic constant uint32 state[N]; // internal state uint32 *pNext; // next value to get from state int left; // number of values left before reload needed //================================ Methods ================================= public: //---------------------------------reload----------------------------------- void reload() { // Generate N new values in state // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) register uint32 *p = state; register int i; for( i = N - M; i--; ++p ) *p = twist( p[M], p[0], p[1] ); for( i = M; --i; ++p ) *p = twist( p[M-N], p[0], p[1] ); *p = twist( p[M-N], p[0], state[0] ); left = N, pNext = state; } uint32 hash( time_t t, clock_t c ) { // Get a uint32 from t and c // Better than uint32(x) in case x is floating point in [0,1] // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) static uint32 differ = 0; // guarantee time-based seeds will change uint32 h1 = 0; unsigned char *p = (unsigned char *) &t; for( size_t i = 0; i < sizeof(t); ++i ) { h1 *= UCHAR_MAX + 2U; h1 += p[i]; } uint32 h2 = 0; p = (unsigned char *) &c; for( size_t j = 0; j < sizeof(c); ++j ) { h2 *= UCHAR_MAX + 2U; h2 += p[j]; } return ( h1 + differ++ ) ^ h2; } //--------------------------creators------------------------- Random( const uint32 oneSeed ) { seed(oneSeed); } Random( uint32 *const bigSeed ) { seed(bigSeed); } Random() { seed(); } //---------------------------reals---------------------------- double preal() // real number in [0,1) { return double( pint() ) * 2.3283064365386962890625e-10; // 1/2^32 } double preal( const double& n ) // real number in [0,n) { return preal() * n; } double preal_exc() // real number in (0,1) { return (1.0+double(pint())) * 2.328306435996595202945965527e-10; // 1/( 2^32+1 ) } double preal_exc( const double& n ) // real number in (0,n) { return preal_exc() * n; } double sreal() // signed real number in (-1,1) { return double( sint() ) * 4.656612873077392578125e-10; // 1/2^31 } double real_range(const double low, const double high) { return low + preal() * ( high - low ); } double gauss() // signed real number, following a normal law N(0,1) { //a trick from Numerical Recipe static double buffer_value = 0; static int buffer_flag = 0; if ( buffer_flag ) { buffer_flag = 0; return buffer_value; } else { double x, y, normsq, fac; do { x = sreal(); y = sreal(); normsq = x * x + y * y; } while (( normsq >= 1.0 ) || ( normsq == 0.0 )); fac = sqrt( -2.0 * log( normsq ) / normsq ); buffer_value = fac * x; buffer_flag = 1; return fac * y; } } double gauss2() // signed real number, following a normal law N(0,1) { //const double PI = 3.14159265358979323846264338327950288; static double buffer_value = 0; static int buffer_flag = 0; if ( buffer_flag ) { buffer_flag = 0; return buffer_value; } else { double angle = double( pint() ) * 1.46291807926715968105133780430979e-9; //the constant is 2*pi/2^32 double norm = sqrt( -2.0 * log( preal_exc() ) ); buffer_value = norm * cos( angle ); buffer_flag = 1; return norm * sin( angle ); } } //---------------------------integers----------------------------- uint32 pint() // integer in [0,2^32-1] { if( left == 0 ) reload(); --left; register uint32 s1; s1 = *pNext++; s1 ^= (s1 >> 11); s1 ^= (s1 << 7) & 0x9d2c5680U; s1 ^= (s1 << 15) & 0xefc60000U; return ( s1 ^ (s1 >> 18) ); } uint32 pint_exc( const uint32 n ) // unsigned integer in [0,n-1] for n < 2^32 { return uint32( preal() * n ); } int32 pint_exc( const int32 n ) // integer in [0,n-1] for n < 2^31 { assert( n >= 0 ); return int32( preal() * n ); } uint32 pint_inc( const uint32 n ) // unsigned integer in [0,n] for n < 2^32 { return uint32( preal() * (n+1) ); } int32 pint_inc( const int32 n ) // integer in [0,n] for n < 2^32 { assert( n >= 0 ); return int32( preal() * (n+1) ); } uint32 pint_inc_true( const uint32 n ) // integer in [0,n] for n < 2^32 { // Find which bits are used in n uint32 used = ~0; for( uint32 m = n; m; used <<= 1, m >>= 1 ) {} used = ~used; // Draw numbers until one is found in [0,n] uint32 i; do i = pint() & used; // toss unused bits to shorten search while( i > n ); return i; } uint32 pint_exc_true( const uint32 n ) // integer in [0,n) for n < 2^32 { if ( n == 0 ) return 0; // Find which bits are used in n uint32 used = ~0; for( uint32 m = n-1; m; used <<= 1, m >>= 1 ) {} used = ~used; // Draw numbers until one is found in [0,n] uint32 i; do i = pint() & used; // toss unused bits to shorten search while( i >= n ); return i; } int32 sint() // signed integer; { if( left == 0 ) reload(); --left; register uint32 s1; s1 = *pNext++; s1 ^= (s1 >> 11); s1 ^= (s1 << 7) & 0x9d2c5680U; s1 ^= (s1 << 15) & 0xefc60000U; return ( s1 ^ (s1 >> 18) ); } int32 sint_inc(const int32 N) // integer in [-N, N]; { assert( N >= 0 ); return pint_inc( 2 * N ) - N; } int32 sint_exc(const int32 N) // integer in (-N, N); { assert( N >= 0 ); return pint_inc( 2 * ( N - 1 ) ) - N + 1; } bool test( const double & p ) { return ( preal() < p ); } bool flip() // 0 or 1 { return ( pint() % 2 ); } int32 int_range(const int32 low, const int32 high) // in [low, high] { return low + pint_inc( high - low ); } uint32 pint_ratio(const uint32 n, const int ratio[]) //returns an integer in [0 n[, with the ratios given in the array of ints { int sum = 0; uint32 ii; for( ii = 0; ii < n; ++ii ) sum += ratio[ ii ]; // sum==0 denotes a careless use of the function, with wrong arguments. // we return here 0, but in harder times, we should call an MSG.error() if ( sum == 0 ) return 0; sum = (int) floor( sum * preal() ); ii = 0; while ( sum >= ratio[ ii ] ) sum -= ratio[ ii++ ]; return ii; } //-------------------------- uniform choice among the values given: double choose(const double x, const double y) { if ( flip() ) return x; else return y; } double choose(const double x, const double y, const double z) { switch( pint_exc(3) ) { case 0: return x; case 1: return y; default: return z; } } double choose(const double x, const double y, const double z, const double t) { switch( pint_exc(4) ) { case 0: return x; case 1: return y; case 2: return z; default: return t; } } double choose(const double x, const double y, const double z, const double t, const double u) { switch( pint_exc(5) ) { case 0: return x; case 1: return y; case 2: return z; case 3: return t; default: return u; } } double choose(const double x, const double y, const double z, const double t, const double u, const double v) { switch( pint_exc(6) ) { case 0: return x; case 1: return y; case 2: return z; case 3: return t; case 4: return u; default: return v; } } //--------------------------seeding------------------------------------ uint32 seed( uint32 oneSeed ) //included a call to the timer, if argument is zero 2002/Oct/3, FNedelec { // last attempt to get a correct seeding: if ( oneSeed == 0 ) oneSeed = 1; // Seed the generator with a simple uint32 register uint32 *s; register int i; for( i = N, s = state; i--; *s = oneSeed & 0xffff0000, *s++ |= ( (oneSeed *= 69069U)++ & 0xffff0000 ) >> 16, (oneSeed *= 69069U)++ ) {} // hard to read, but fast reload(); return oneSeed; } void seed( uint32 *const bigSeed ) { // Seed the generator with an array of 624 uint32's // There are 2^19937-1 possible initial states. This function allows // any one of those to be chosen by providing 19937 bits. The lower // 31 bits of the first element, bigSeed[0], are discarded. Any bits // above the lower 32 in each element are also discarded. Theoretically, // the rest of the array can contain any values except all zeroes. // Just call seed() if you want to get array from /dev/urandom register uint32 *s = state, *b = bigSeed; register int i = N; for( ; i--; *s++ = *b++ & 0xffffffff ) {} reload(); } void seed() { // Seed the generator with an array from /dev/urandom if available // Otherwise use a hash of time() and clock() values // First try getting an array from /dev/urandom FILE* urandom = fopen( "/dev/urandom", "rb" ); if( urandom ) { register uint32 *s = state; register int i = N; register bool success = true; while( success && i-- ) { success = fread( s, sizeof(uint32), 1, urandom ); *s++ &= 0xffffffff; // filter in case uint32 > 32 bits } fclose(urandom); if( success ) { // There is a 1 in 2^19937 chance that a working urandom gave // 19937 consecutive zeroes and will make the generator fail // Ignore that case and continue with initialization reload(); return; } } // Was not successful, so use time() and clock() instead seed( hash( time(NULL), clock() ) ); } uint32 seedTimer() { uint32 s = hash( time(NULL), clock() ); seed( s ); return s; } //-------------- Saving and loading generator state------------------- void save( uint32* saveArray ) const // to array of size SAVE { register uint32 *sa = saveArray; register const uint32 *s = state; register int i = N; for( ; i--; *sa++ = *s++ ) {} *sa = left; } void load( uint32 *const loadArray ) // from such array { register uint32 *s = state; register uint32 *la = loadArray; register int i = N; for( ; i--; *s++ = *la++ ) {} left = *la; pNext = &state[N-left]; } protected: uint32 hiBit( const uint32& u ) const { return u & 0x80000000U; } uint32 loBit( const uint32& u ) const { return u & 0x00000001U; } uint32 loBits( const uint32& u ) const { return u & 0x7fffffffU; } uint32 mixBits( const uint32& u, const uint32& v ) const { return hiBit(u) | loBits(v); } uint32 twist(const uint32& m, const uint32& s0, const uint32& s1) const { return m ^ (mixBits(s0,s1)>>1) ^ (loBit(s1) ? MAGIC : 0U); } }; extern Random RNG; #endif //MERSENNETWISTER_H
[ "khetanneha@gmail.com" ]
khetanneha@gmail.com
846d56d04eeea0facb5d953a037b69179bfc68d8
492976adfdf031252c85de91a185bfd625738a0c
/src/Game/AI/Action/actionDieAnmDropWeapon.h
56706ba156a4c86be0b6397ecef0cf021d0b7c0a
[]
no_license
zeldaret/botw
50ccb72c6d3969c0b067168f6f9124665a7f7590
fd527f92164b8efdb746cffcf23c4f033fbffa76
refs/heads/master
2023-07-21T13:12:24.107437
2023-07-01T20:29:40
2023-07-01T20:29:40
288,736,599
1,350
117
null
2023-09-03T14:45:38
2020-08-19T13:16:30
C++
UTF-8
C++
false
false
535
h
#pragma once #include "Game/AI/Action/actionDieAnm.h" #include "KingSystem/ActorSystem/actAiAction.h" namespace uking::action { class DieAnmDropWeapon : public DieAnm { SEAD_RTTI_OVERRIDE(DieAnmDropWeapon, DieAnm) public: explicit DieAnmDropWeapon(const InitArg& arg); ~DieAnmDropWeapon() override; void enter_(ksys::act::ai::InlineParamPack* params) override; void loadParams_() override; protected: // static_param at offset 0x40 const float* mWeaponDropSpeedY_s{}; }; } // namespace uking::action
[ "leo@leolam.fr" ]
leo@leolam.fr
e8421ef77349225f849e63a9683d2229a076ad84
cf8594eb75f873cdc769a92b341114cc0591947a
/Programz Other/Concepts/home task 13 dif tasks/home task 13 dif tasks/Source2.cpp
6a504055bed00aa3a075fa1e5255e297b80231b3
[]
no_license
Tayyibah/PF
1bcb2494e23e088f0100fb64f3accf3e1d9b7f54
47417af17c15053c54a16f14ec501084de078ed0
refs/heads/master
2021-06-28T05:23:08.954593
2017-08-14T11:44:55
2017-08-14T11:44:55
100,258,409
0
0
null
null
null
null
UTF-8
C++
false
false
379
cpp
//#include<iostream> //using namespace std; //class base1 //{ //public: // int a,b; //}; //class base2 //{ //public: // int c,d; //}; //class derive:public base1, public base2 {}; //void main() //{ // derive obj; // //Assume: starting address of // //obj is 100 // cout<<sizeof(obj); // base1 *ptrb1=&obj; // base2 *ptrb2=&obj; // cout<<endl<<ptrb1; // cout<<endl<<ptrb2; //}
[ "tayyibahalauddin@gmail.com" ]
tayyibahalauddin@gmail.com
10c033efc8ac871282c189a8d70eaa92fdfb7d7b
dfe192faadd39dfdb821ac503d577ee7010b69d3
/states/TriangleSelector.cpp
736e864b5d34c98449362d259e20f4e19faf962b
[]
no_license
hecrj/simplegl
2b4ff4d6938540447f288708f1fb5b76d85cb93c
c47e22dae55a5ee66ec2ce8bc0d4d02c4c8c9436
refs/heads/master
2016-09-11T11:24:08.263718
2013-11-18T18:01:52
2013-11-18T18:01:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,373
cpp
/** * File: TriangleSelector.cpp * Author: hector */ #include "TriangleSelector.h" #if defined(__APPLE__) #include <OpenGL/OpenGl.h> #include <GLUT/GLUT.h> #else #include <GL/gl.h> #include <GL/freeglut.h> #endif #include <iostream> using namespace std; TriangleSelector::TriangleSelector(Viewport* window, Triangle** triangle) : State("Triangle selector") { this->window = window; this->triangle = triangle; a = b = c = NULL; } TriangleSelector::~TriangleSelector() { } string TriangleSelector::getDescription() const { return "Click to define every vertex of the new triangle."; } void TriangleSelector::enter() { a = b = c = NULL; State::enter(); } void TriangleSelector::leave() { if(a != NULL) delete a; if(b != NULL) delete b; if(c != NULL) delete c; } void TriangleSelector::mousePressed(int buttonId, int state, int x, int y) { if(buttonId != GLUT_LEFT_BUTTON || state == GLUT_DOWN) return; Point* v = window->getViewportVertex(x, y); cout << "New vertex defined at: (" << v->x << ", " << v->y << ", " << v->z << ")" << endl; if(a == NULL) a = v; else if(b == NULL) b = v; else c = v; if(c != NULL) { *triangle = new Triangle(a, b, c); a = b = c = NULL; glutPostRedisplay(); } }
[ "hector0193@gmail.com" ]
hector0193@gmail.com
2ea07a619d0e8afcf063d78994c889d2188805d5
dd2bcd6e829347eef6ab8020bd8e31a18c335acc
/ThisIsASoftRenderer/Editor/XTP/Source/Chart/Diagram/RadarDiagram/XTPChartRadarDiagramView.h
f228602491ab3b9a3ea94b7623d4ea75d35e5ea3
[]
no_license
lai3d/ThisIsASoftRenderer
4dab4cac0e0ee82ac4f7f796aeafae40a4cb478a
a8d65af36f11a079e754c739a37803484df05311
refs/heads/master
2021-01-22T17:14:03.064181
2014-03-24T16:02:16
2014-03-24T16:02:16
56,359,042
1
0
null
2016-04-16T01:19:22
2016-04-16T01:19:20
null
UTF-8
C++
false
false
5,050
h
// XTPChartRadarDiagramView.h // // This file is a part of the XTREME TOOLKIT PRO 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: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTPCHARTRADARDIAGRAMVIEW_H__) #define __XTPCHARTRADARDIAGRAMVIEW_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 class CXTPChartAxis; class CXTPChartDiagram2DAppearance; class CXTPChartRadarAxisView; class CXTPChartSeriesView; class CXTPChartRadarAxisXView; class CXTPChartRadarAxisYView; class CXTPChartLineStyle; class CXTPChartFillStyle; //=========================================================================== // Summary: // This class represents the view of a chart 2D diagram, which is a kind of // CXTPChartDiagramView. // Remarks: //=========================================================================== class _XTP_EXT_CLASS CXTPChartRadarDiagramView :public CXTPChartDiagramView { public: //----------------------------------------------------------------------- // Summary: // Constructs a CXTPChartRadarDiagramView object. // Parameters: // pDiagram - A pointer to the chart diagram object. // pParent - A pointer to the parent view object. // Remarks: //----------------------------------------------------------------------- CXTPChartRadarDiagramView(CXTPChartDiagram* pDiagram, CXTPChartElementView* pParent); //----------------------------------------------------------------------- // Summary: // Call this function to create the view of the 2D diagram. // Parameters: // pDC - A pointer to the chart device context. // Remarks: //----------------------------------------------------------------------- void CreateView(CXTPChartDeviceContext* pDC); //----------------------------------------------------------------------- // Summary: // Call this function to calculate the layout based on a rectangular // boundary. // Parameters: // pDC - A pointer to the chart device context. // rcBounds - The diagram boundary. // Remarks: //----------------------------------------------------------------------- void CalculateView(CXTPChartDeviceContext* pDC, CRect rcBounds); void UpdateRange(CXTPChartDeviceContext* pDC); CXTPChartDeviceCommand* CreateDeviceCommand(CXTPChartDeviceContext* pDC); //----------------------------------------------------------------------- // Summary: // Returns Axis View // Parameters: // pAxis - Axis // Remarks: //----------------------------------------------------------------------- CXTPChartRadarAxisView* GetAxisView(CXTPChartAxis* pAxis) const; public: void CheckLabelBounds(const CXTPChartRectF& rcBounds); CXTPChartPointF GetScreenPoint(const CXTPChartSeriesView* pView, double x, double y) const; CXTPChartRadarAxisXView* GetAxisXView() const; CXTPChartRadarAxisYView* GetAxisYView() const; protected: //----------------------------------------------------------------------- // Summary: // Use this function to add an axis view to the diagram view. // boundary. // Parameters: // pDC - A pointer to the chart device context. // pParentView - The parent view of the axis view. // pAxis - A pointer to the axis object, whose view is to be // added. // Remarks: //----------------------------------------------------------------------- CXTPChartRadarAxisView* AddAxisView(CXTPChartDeviceContext* pDC, CXTPChartElementView* pParentView, CXTPChartAxis* pAxis); public: CXTPChartDeviceCommand* CreatePolygonStripDeviceCommand(CXTPChartDeviceContext* /*pDC*/, double dRadiusFrom, double dRadiusTo, const CXTPChartColor& color1, const CXTPChartColor& color2, CXTPChartFillStyle* pFillStyle); CXTPChartDeviceCommand* CreatePolygonLineDeviceCommand(CXTPChartDeviceContext* /*pDC*/, double dRadius, const CXTPChartColor& color, CXTPChartLineStyle* pLineStyle); protected: CXTPChartElementView* m_pAxisViews; //The axis view. CXTPChartRadarAxisXView* m_pAxisXView; CXTPChartRadarAxisYView* m_pAxisYView; CRect m_rcLabelPadding; CXTPPoint2i m_ptCenter; int m_nRadius; }; AFX_INLINE CXTPChartRadarAxisXView* CXTPChartRadarDiagramView::GetAxisXView() const { return m_pAxisXView; } AFX_INLINE CXTPChartRadarAxisYView* CXTPChartRadarDiagramView::GetAxisYView() const { return m_pAxisYView; } #endif //#if !defined(__XTPCHARTRADARDIAGRAMVIEW_H__)
[ "54639976@qq.com" ]
54639976@qq.com
efcd126f43a52640bd2b81839ba1476b48ed4ecb
801b9f7cd0f7b5c63bca2adb18bb9fbf2d0f5b44
/src/PhoneHighlightAlt2.h
788b9d8f0853bc6b57f6f797077613070429b05d
[ "MIT" ]
permissive
ystanislavyk/phone-highlight
4e58cf02685e246201cfc885f0cf4fe394460121
5509d0780d6e84bae4d908e01bc63157aac0cbca
refs/heads/master
2021-10-25T05:21:12.627369
2019-04-01T21:08:27
2019-04-01T21:08:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
788
h
// Copyright [2019] <Malinovsky Rodion> (rodionmalino@gmail.com) #include "PhoneHighlightUtil.h" #include <string> namespace rms { /** * @brief Get the Phone Highlight object. UTF32 version. Indexes are zero based. Range is [begin, end] where begin and end are first * and the last elements of the match range. * * @param phoneNumber Phone number as UTF32 string in which highlights are searched. List of ignored symbols: space, no-break space, "(",")","/", "#", ".".  * @param searchString UTF32 encoded search pattern to search. * @return std::string formatted string with list of indexes for highlights. Format: "begin1-end1;begin2-end2..." */ HighlightRanges GetPhoneHighlightAlt2(std::u32string const& phoneNumber, std::u32string const& searchString); } // namespace rms
[ "rodionmalino@gmail.com" ]
rodionmalino@gmail.com
05b83902c8a82338d8e95505726f7f6012b61719
e51a99c13169d41094d4ee8440faaa7df668172a
/FPVTransport/hori_xtionrgb/include/socketClass.h
2c5d5cbcac99cc7657953222fa2e0d2ad9d31ee3
[]
no_license
CEfanmin/Pyramid
9f2125b4b328d05516cca59541319440d36666e8
8c5d9c20dbde6b4db94df021a4106bcf49220404
refs/heads/main
2023-03-13T04:45:34.111746
2021-03-04T11:36:10
2021-03-04T11:36:10
320,573,263
0
0
null
null
null
null
UTF-8
C++
false
false
1,403
h
#pragma once #include <iostream> #include <sstream> #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/shm.h> class mySocket{ public: mySocket(); ~mySocket(); private: //common bool paramSetDone; int socketType;//0 NULL , 1 Server , 2 Client int port; int queuelen; //server int server_sockfd; struct sockaddr_in server_sockaddr; int on; int ret; struct sockaddr_in client_addr; socklen_t length; int conn; //client int sock_cli; struct sockaddr_in servaddr; public: void changePort(int Port){ port = Port; } void changeQueuelen(int len){ queuelen = len; } bool serverInit(void); int serverRecv(void *buff,int len); int serverSend(void *buff,int len); bool serverClose(void); int serverAutoReconnect(int Port = 10086); bool clientInit(char *ip); int clientRecv(void *buff,int len); int clientSend(void *buff,int len); bool clientClose(void); int clientAutoReconnect(char *ip,int Port = 10086); int serverReceiveOnce(void *buff,int len); int clientSendOnce(char *ip,void *buff,int len); int Send(void *buff,int len,char *ip = NULL); int Receive(void *buff,int len,char *ip = NULL); };
[ "840831204@qq.com" ]
840831204@qq.com
9d387c8c46541abf2c16173b122e79a45df00a06
043eb9b100070cef1a522ffea1c48f8f8d969ac7
/ios_proj/wwj/Classes/Native/mscorlib_System_Collections_ObjectModel_ReadOnlyCo3038217833.h
54f8767ab9dbe1c778fdb9a0b598125cfc4dd8ad
[]
no_license
spidermandl/wawaji
658076fcac0c0f5975eb332a52310a61a5396c25
209ef57c14f7ddd1b8309fc808501729dda58071
refs/heads/master
2021-01-18T16:38:07.528225
2017-10-19T09:57:00
2017-10-19T09:57:00
100,465,677
1
2
null
null
null
null
UTF-8
C++
false
false
1,206
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object2689449295.h" // System.Collections.Generic.IList`1<MonsterLove.StateMachine.IStateMachine> struct IList_1_t3393372742; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.ObjectModel.ReadOnlyCollection`1<MonsterLove.StateMachine.IStateMachine> struct ReadOnlyCollection_1_t3038217833 : public Il2CppObject { public: // System.Collections.Generic.IList`1<T> System.Collections.ObjectModel.ReadOnlyCollection`1::list Il2CppObject* ___list_0; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(ReadOnlyCollection_1_t3038217833, ___list_0)); } inline Il2CppObject* get_list_0() const { return ___list_0; } inline Il2CppObject** get_address_of_list_0() { return &___list_0; } inline void set_list_0(Il2CppObject* value) { ___list_0 = value; Il2CppCodeGenWriteBarrier(&___list_0, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "Desmond@Desmonds-MacBook-Pro.local" ]
Desmond@Desmonds-MacBook-Pro.local
99b73cd554a5dc6df1ffb498e1e8eaea45d5a35f
eb13824ebccd9e25c2866a6de9745cf835df662f
/LR3/singleattributesearchwindow.cpp
9454dbf5b924699e12b1962e6f298765731f9e0b
[]
no_license
DmitryDankov207/labs
4101c85f1b2b67ff775e34a546f8d9336a51179f
6e9319bd4c02762fa756e1c53fab8677cc1f0e5d
refs/heads/master
2022-01-31T15:41:36.225530
2019-06-24T22:22:14
2019-06-24T22:22:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
435
cpp
#include "singleattributesearchwindow.h" #include "ui_singleattributesearchwindow.h" SingleAttributeSearchWindow::SingleAttributeSearchWindow(QWidget *parent) : QDialog(parent), ui(new Ui::SingleAttributeSearchWindow) { ui->setupUi(this); } SingleAttributeSearchWindow::~SingleAttributeSearchWindow() { delete ui; } void SingleAttributeSearchWindow::on_buttonBox_accepted() { attribute = ui->lineEdit->text(); }
[ "12ddankov12@gmail.com" ]
12ddankov12@gmail.com
818f24bf8a596c3f4b5b20b3b3817b0d54ddb11e
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/git/gumtree/git_repos_function_4475_git-2.5.6.cpp
4b2de501b15d011faf835199ce078b24d01f187a
[]
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
316
cpp
static const char *skip_tree_prefix(const char *line, int llen) { int nslash; int i; if (!p_value) return (llen && line[0] == '/') ? NULL : line; nslash = p_value; for (i = 0; i < llen; i++) { int ch = line[i]; if (ch == '/' && --nslash <= 0) return (i == 0) ? NULL : &line[i + 1]; } return NULL; }
[ "993273596@qq.com" ]
993273596@qq.com
145a62447b73f9cf59418d726d9d4f6b8ba9ab9e
e6c80d747be1496b9c0ebcc8a8bc33bd64eb17dd
/Codes/C++ Programs/Others/Access the elements of a vector through an iterator..cpp
28c217fce8d166f802f5b11e4dc7454c91bd5254
[]
no_license
developersbk/Universal_Code_Snippets
56b25fb43cc2c67113e97e691cc48f8a0b0193f6
0001535476a5743c0557c5ce2c3ffc13c6ee8791
refs/heads/master
2023-02-24T08:16:57.240264
2020-02-29T01:21:46
2020-02-29T01:21:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
825
cpp
Access the elements of a vector through an iterator. #include <iostream> #include <vector> using namespace std; int main() { vector<int> vectorObject(10); vector<int>::iterator p; int i; p = vectorObject.begin(); i = 0; while(p != vectorObject.end()) { *p = i; p++; i++; } cout << "Original contents:\n"; p = vectorObject.begin(); while(p != vectorObject.end()) { cout << *p << " "; p++; } cout << "\n\n"; p = vectorObject.begin(); while(p != vectorObject.end()) { *p = *p * 2; // change contents of vector p++; } cout << "Modified Contents:\n"; p = vectorObject.begin(); while(p != vectorObject.end()) { cout << *p << " "; // display contents of vector p++; } cout << endl; return 0; }
[ "sbkannath1996@gmail.com" ]
sbkannath1996@gmail.com
29ee784726502d4037d46317c73f64c1b09909c8
40bdc1a307583f1ea1783eef84158c05e8826883
/src/nix/queue.hxx
39da92dcb1d8cccb9a28f53dd06945201979c0a0
[]
no_license
mcptr/nixsrv
be722f6fe08ef9b529712921f89a2765c41dda94
83b54ebe5db381493a9776c607cca41f8aa136a1
refs/heads/master
2020-03-07T17:54:35.304114
2018-04-01T11:49:08
2018-04-01T11:49:08
127,624,111
0
0
null
null
null
null
UTF-8
C++
false
false
1,875
hxx
#ifndef NIX_QUEUE_HXX #define NIX_QUEUE_HXX #include <queue> #include <string> #include <mutex> #include <condition_variable> #include <memory> #include <atomic> #include "nix/common.hxx" namespace nix { template<class T> class Queue { public: Queue() = delete; Queue(const Queue& other) = delete; Queue& operator= (Queue& other) = delete; Queue(size_t queue_size) : queue_size_(queue_size ? queue_size : 50), is_closed_(false) { } void pop(std::unique_ptr<T>&& ptr, int timeout = -1) { ptr.reset(); std::unique_lock<std::mutex> lock(mtx_); while(!is_closed_ && !ptr) { if(!q_.empty()) { ptr = std::move(q_.front()); q_.pop(); } if(!ptr) { if(timeout == -1) { cv_.wait(lock);//, [this]() { return this->is_closed(); }); } else { std::cv_status status = cv_.wait_for(lock, std::chrono::milliseconds(timeout)); if(status == std::cv_status::timeout) { break; } } } else { break; } } } void push(std::unique_ptr<T>&& elem, bool& success) { success = false; std::unique_lock<std::mutex> lock(mtx_); if(!is_closed_ && queue_size_ && q_.size() < queue_size_) { q_.push(std::move(elem)); success = true; } lock.unlock(); cv_.notify_one(); } size_t size() const { return q_.size(); } void set_enabled(bool state = true) { is_closed_ = !state; cv_.notify_all(); } void clear() { std::unique_lock<std::mutex> lock(mtx_); bool was_closed = is_closed_; is_closed_ = true; std::queue<std::unique_ptr<T>> new_q; std::swap(q_, new_q); is_closed_ = was_closed; lock.unlock(); cv_.notify_all(); } bool is_closed() const { return is_closed_; } protected: std::queue<std::unique_ptr<T>> q_; size_t queue_size_ = 0; std::atomic<bool> is_closed_; std::mutex mtx_; std::condition_variable cv_; }; } // nix #endif
[ "minus@noise-nation.net" ]
minus@noise-nation.net
da3286d69b083976a53375bc01647f34478038ad
765fdaabaf4ec08896d5857826e55d4e6954e275
/SW/Click Examples mikroC/Examples/HEXIWEAR_AirQ_Click/example/ARM/HEXIWEAR_AirQ_Click.cp
023ed5cf4fdf6a404b04307248a146fe54ba2b75
[]
no_license
addielvega/Hexiware
79a1f42cc07d4d97203051ca3c483329ae9ae442
664beab95999f0c7050da3b22edf5e672eb50ff5
refs/heads/master
2021-01-12T06:23:48.987813
2016-12-26T03:02:22
2016-12-26T03:02:22
77,353,552
1
1
null
null
null
null
UTF-8
C++
false
false
7,459
cp
#line 1 "D:/Marko/tasks/freescale/svn/Hexiwear/MK64/5. Click Demos/1. mikroC/2. Primeri/HEXIWEAR_AirQ_Click/example/ARM/HEXIWEAR_AirQ_Click.c" #line 1 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_driver.h" #line 1 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_types.h" #line 1 "d:/work/mikroc pro for arm/include/stdint.h" typedef signed char int8_t; typedef signed int int16_t; typedef signed long int int32_t; typedef signed long long int64_t; typedef unsigned char uint8_t; typedef unsigned int uint16_t; typedef unsigned long int uint32_t; typedef unsigned long long uint64_t; typedef signed char int_least8_t; typedef signed int int_least16_t; typedef signed long int int_least32_t; typedef signed long long int_least64_t; typedef unsigned char uint_least8_t; typedef unsigned int uint_least16_t; typedef unsigned long int uint_least32_t; typedef unsigned long long uint_least64_t; typedef signed long int int_fast8_t; typedef signed long int int_fast16_t; typedef signed long int int_fast32_t; typedef signed long long int_fast64_t; typedef unsigned long int uint_fast8_t; typedef unsigned long int uint_fast16_t; typedef unsigned long int uint_fast32_t; typedef unsigned long long uint_fast64_t; typedef signed long int intptr_t; typedef unsigned long int uintptr_t; typedef signed long long intmax_t; typedef unsigned long long uintmax_t; #line 13 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_types.h" typedef enum { OLED_TRANSITION_NONE, OLED_TRANSITION_TOP_DOWN, OLED_TRANSITION_DOWN_TOP, OLED_TRANSITION_LEFT_RIGHT, OLED_TRANSITION_RIGHT_LEFT } oled_transition_t; typedef enum { OLED_STATUS_SUCCESS, OLED_STATUS_ERROR, OLED_STATUS_PROTOCOL_ERROR, OLED_STATUS_INIT_ERROR, OLED_STATUS_DEINIT_ERROR } oled_status_t; #line 41 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_types.h" typedef uint16_t* oled_pixel_t; typedef struct { uint32_t DCpin; uint32_t CSpin; uint32_t RSTpin; uint32_t ENpin; } settingsOLED_t; typedef enum { OLED_TEXT_ALIGN_NONE = 0, OLED_TEXT_ALIGN_LEFT = 0x1, OLED_TEXT_ALIGN_RIGHT = 0x2, OLED_TEXT_ALIGN_CENTER = 0x3, OLED_TEXT_VALIGN_TOP = 0x10, OLED_TEXT_VALIGN_BOTTOM = 0x20, OLED_TEXT_VALIGN_CENTER = 0x30 } oled_text_align_t; typedef enum { OLED_COLOR_BLACK = 0x0000, OLED_COLOR_BLUE_1 = 0x06FF, OLED_COLOR_BLUE = 0x001F, OLED_COLOR_RED = 0xF800, OLED_COLOR_GREEN = 0x07E0, OLED_COLOR_CYAN = 0x07FF, OLED_COLOR_MAGENTA = 0xF81F, OLED_COLOR_YELLOW = 0xFFE0, OLED_COLOR_GRAY = 0x528A, OLED_COLOR_WHITE = 0xFFFF } oled_color_t; typedef struct { uint8_t xCrd; uint8_t yCrd; uint8_t width; uint8_t height; oled_pixel_t areaBuffer; } oled_dynamic_area_t; typedef struct { const uint8_t* font; uint16_t fontColor; oled_text_align_t alignParam; const uint8_t* background; } oled_text_properties_t; #line 1 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_resources.h" #line 1 "d:/work/mikroc pro for arm/include/stdint.h" #line 6 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_resources.h" extern const uint8_t guiFont_Tahoma_8_Regular[]; extern const uint8_t airQuality_bmp[18438]; #line 12 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_driver.h" extern const uint8_t FO_HORIZONTAL; extern const uint8_t FO_VERTICAL; extern const uint8_t FO_VERTICAL_COLUMN; #line 26 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_driver.h" oled_status_t OLED_Init(void); #line 41 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_driver.h" oled_status_t OLED_DrawBox ( uint16_t xCrd, uint16_t yCrd, uint16_t width, uint16_t height, uint16_t color ); #line 58 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_driver.h" oled_status_t OLED_FillScreen( uint16_t color ); #line 72 "d:/marko/tasks/freescale/svn/hexiwear/mk64/5. click demos/1. mikroc/2. primeri/hexiwear_airq_click/example/arm/oled_driver.h" oled_status_t OLED_DrawPixel ( int16_t xCrd, int16_t yCrd, uint16_t color ); oled_status_t OLED_AddText( const uint8_t* text ); void OLED_SetTextProperties(oled_text_properties_t *textProperties); uint8_t OLED_GetTextWidth(const uint8_t* text); uint8_t OLED_CharCount(uint8_t width, const uint8_t* font, const uint8_t* text, uint8_t length); void OLED_SetFont(const uint8_t *activeFont, uint16_t font_color, uint8_t font_orientation); void OLED_SetDynamicArea(oled_dynamic_area_t *dynamic_area); void OLED_WriteText(uint8_t *text, uint16_t x, uint16_t y); oled_status_t OLED_DrawImage (const uint8_t* image, uint8_t xCrd, uint8_t yCrd); void OLED_GetImageDimensions(uint8_t *width, uint8_t *height, const uint8_t* image); #line 64 "D:/Marko/tasks/freescale/svn/Hexiwear/MK64/5. Click Demos/1. mikroC/2. Primeri/HEXIWEAR_AirQ_Click/example/ARM/HEXIWEAR_AirQ_Click.c" const float LoadRes = 10470, Vadc_5 = 0.001220703125, Vadc_33 = 0.0008056640625; double Vrl; double SensRes; double ppm; double ratio; double value = 0, value_old = 0; uint16_t adc_rd; uint8_t text[16]; static uint8_t valText[] = "val:"; #line 100 "D:/Marko/tasks/freescale/svn/Hexiwear/MK64/5. Click Demos/1. mikroC/2. Primeri/HEXIWEAR_AirQ_Click/example/ARM/HEXIWEAR_AirQ_Click.c" void CalculatePPM() { double lgPPM; Vrl = (double)adc_rd * Vadc_33; SensRes = LoadRes * (5 - Vrl)/Vrl; ratio = SensRes/LoadRes; lgPPM = (log10(ratio) * -0.8 ) + 0.9; ppm = pow(10,lgPPM); } #line 121 "D:/Marko/tasks/freescale/svn/Hexiwear/MK64/5. Click Demos/1. mikroC/2. Primeri/HEXIWEAR_AirQ_Click/example/ARM/HEXIWEAR_AirQ_Click.c" void DisplayAirQValue( uint16_t value ) { if (value_old != value) { OLED_SetFont( guiFont_Tahoma_8_Regular, OLED_COLOR_WHITE, 0 ); OLED_WriteText( text, 50, 75 ); WordToStr(value, text); OLED_SetFont( guiFont_Tahoma_8_Regular, OLED_COLOR_BLACK, 0 ); OLED_WriteText( text, 50, 75 ); } value_old = value; } #line 148 "D:/Marko/tasks/freescale/svn/Hexiwear/MK64/5. Click Demos/1. mikroC/2. Primeri/HEXIWEAR_AirQ_Click/example/ARM/HEXIWEAR_AirQ_Click.c" void ReadSensor() { adc_rd = ADC0_Get_Sample( 12 ); Delay_ms(10); } #line 165 "D:/Marko/tasks/freescale/svn/Hexiwear/MK64/5. Click Demos/1. mikroC/2. Primeri/HEXIWEAR_AirQ_Click/example/ARM/HEXIWEAR_AirQ_Click.c" void InitModules() { OLED_Init(); OLED_DrawImage( &airQuality_bmp, 0, 0 ); OLED_SetFont( guiFont_Tahoma_8_Regular, OLED_COLOR_BLACK, 0 ); OLED_WriteText( valText, 25, 75 ); ADC0_Init(); Delay_ms(100); } void main() { InitModules(); while(1) { ReadSensor(); CalculatePPM(); DisplayAirQValue( ppm ); Delay_ms(500); } }
[ "viktor.milovanovic@mikroe.com" ]
viktor.milovanovic@mikroe.com
7815481a5a8944fbaabff663b4bf3c9376ac7e18
e4a4242f04e66a33c31ad73e99fd5a9db5663a28
/include/broker/errors.hpp
c7b851c013f1b2028ce60be5e88f714755be3e8d
[]
no_license
Vin5/0broker
e8bea8bc4437f6178e6a50d617f50f6bc359cb3e
a4f0ad295bb1345feb97b089a45b683364701f29
refs/heads/master
2021-01-13T02:27:10.887286
2014-03-08T08:23:54
2014-03-08T08:23:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
685
hpp
#ifndef ERRORS_HPP #define ERRORS_HPP #include <stdexcept> #include <string> #include <cstdio> namespace zbroker { struct runtime_error_t : public std::exception { template<typename... Args> runtime_error_t(const char* format, const Args&... args) { char details[2048]; m_details.reserve(sizeof(details)); if(snprintf(details, sizeof(details), format, args...) < 0) { sprintf(details, "%s", "Couldn't format error message"); } m_details.assign(details, sizeof(details)); } const char* what() const throw() { return m_details.c_str(); } private: std::string m_details; }; } #endif // ERRORS_HPP
[ "vins2008@gmail.com" ]
vins2008@gmail.com
5a7f12508c7e3f23c656ba9b349edfa0b267a32c
3fb7a2780603a2b3b2635c3719e6079fd2c46f05
/CartVector.cpp
ab69ce4e886ada8ee095376f0133e5fe0b9ac774
[]
no_license
standardgalactic/SEAplusplus
e8fc62b964a8d13eb22a87ba8de4adb934ac491b
57100c72790c8028ecfea4a9abd74a8c709b1200
refs/heads/master
2023-07-13T11:36:59.757427
2015-12-11T16:45:29
2015-12-11T16:45:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,072
cpp
/* EC 327 PA3. Implementation of class CartVector used for the Sea++ game. The class represents a 2D cartesian vector represented by its x-component followed by its y-component. Luis Barroso Luque October 2014 */ #include <iostream> #include "CartVector.h" using namespace std; //Default constructor CartVector::CartVector() { this->x = 0.0; this->y = 0.0; } //Constructors CartVector::CartVector(double in_x, double in_y) { this->x = in_x; this->y = in_y; } //Overloaded Operators ostream& operator<<(ostream& out, const CartVector& v1) { out << "<" << v1.x << ", " << v1.y << ">"; } istream& operator>>(istream& in, CartVector& vect) { char par1, com, par2; in >> par1 >> vect.x >> com >> vect.y >> par2; } CartVector operator*(const CartVector& vector, double scalar) { CartVector newVector(vector.x*scalar, vector.y*scalar); return newVector; } CartVector operator/(const CartVector& vector, double scalar) { CartVector newVector(vector.x/scalar, vector.y/scalar); return newVector; }
[ "luisbarrosoluq@gmail.com" ]
luisbarrosoluq@gmail.com
fc62bb415dfad449a9829f2e37cd2d156f66d7ce
e8e3e939ca489e2bac7c590c7a06077f3243c5cb
/Hackerearth/basic Programming/xsquarestring.cpp
3f215c5924dd7b1a8550b92cceaaf7345a03a9ed
[]
no_license
sungkukpark/CompetitiveProgramming
5b55fb88909bc17fe12b094f701a39f453aebad2
9a6713d0512f50bc9c66b711e9be921262137d12
refs/heads/master
2023-03-19T00:48:58.528173
2018-11-09T08:24:32
2018-11-09T08:24:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
#include<bits/stdc++.h> using namespace std; void solve() { string a; string b; cin>>a; cin>>b; sort(a.begin(),a.end()); sort(b.begin(),b.end()); int ok = false; int n = a.length(); int m = b.length(); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(s[i]==s[j]) { ok = true; break; } } } if(ok) { cout<<"Yes"<<'\n'; } else { cout<<"No"<<'\n'; } } int main() { int t; cin>>t; while(t--) { solve(); } }
[ "prasadgujar16@gmail.com" ]
prasadgujar16@gmail.com
130bcc413bdf3016092017e0c9385ee4cc8f9721
2f78e134c5b55c816fa8ee939f54bde4918696a5
/code_ps3/core/loader_buffer_ps3.h
862e28287d35fafbf51fd8ef2ce665f9d5efbc8a
[]
no_license
narayanr7/HeavenlySword
b53afa6a7a6c344e9a139279fbbd74bfbe70350c
a255b26020933e2336f024558fefcdddb48038b2
refs/heads/master
2022-08-23T01:32:46.029376
2020-05-26T04:45:56
2020-05-26T04:45:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,643
h
//---------------------------------------------------------------------------------------- //! //! \filename core/loader_buffer_ps3.h //! //---------------------------------------------------------------------------------------- #ifndef LOADER_BUFFER_PS3_H_ #define LOADER_BUFFER_PS3_H_ #include "core/loader_callback_ps3.h" #include "core/loader_resource_types_ps3.h" #include "core/syncprims.h" namespace Loader { // Forward declare a visitor class. struct MemBlockVisitor { template < typename T > bool Visit( T ); // Implemented in loader_ps3.cpp. }; // The buffer-memory for the loader. class Buffer { public: // // Allocate/Deallocate a block of memory. // typedef uintptr_t MemBlockID; static const MemBlockID InvalidMemBlockID = 0xffffffff; MemBlockID Allocate ( uint32_t size_in_bytes, ResourceType resource_type, const char *filename, void* userdata, Callback callback = NULL, volatile void *callback_arg = NULL ); public: // // Functions associated with memory-block ids. // // Return a pointer to the block associated with this id. void * GetPtr ( MemBlockID mem_id ) const; // Run the callback associated with this memory-block id, if there is one. void RunCallback ( MemBlockID mem_id, CallbackStage stage ) const; enum Tags { NOT_READY = 0, READY_TO_PROCESS = 1 }; void Tag ( MemBlockID mem_id, Tags tag ); void StoreReadSize ( MemBlockID mem_id, uint32_t filesize ); public: // // Visit each memory-block. Although this is public, you can't actually call // it; trust me on this. This is intended behaviour. See the comment above // Loader::Update in loader_ps3.cpp. [ARV]. // void VisitAll ( MemBlockVisitor visitor ); public: // // Ctor, dtor. // Buffer (); ~Buffer (); private: // // Prevent copying and assignment. // Buffer( const Buffer & ) /* NOT_IMPLEMENTED */; Buffer &operator = ( const Buffer & ) /* NOT_IMPLEMENTED */; private: // // Array of allocated blocks. // friend struct MemBlockVisitor; mutable CriticalSection m_Mutex; struct MemBlock { void * m_Memory; uint32_t m_ReadSize; Callback m_Callback; volatile void * m_CallbackArg; Tags m_Tag; const char * m_Filename; void * m_UserData; ResourceType m_ResourceType; }; typedef ntstd::List< ntstd::pair< MemBlockID, MemBlock > > BlockMap; BlockMap m_Blocks; MemBlock * FindBlock( MemBlockID id ); const MemBlock * FindBlock( MemBlockID id ) const; }; } #endif // !LOADER_BUFFER_PS3_H_
[ "hopefullyidontgetbanned735@gmail.com" ]
hopefullyidontgetbanned735@gmail.com
9a39d70a359904e93c0fb2efd3fcf4131328661a
7293db316725af6749666a4e44b062203dc22e49
/VideoEditing/ClosedFormMatting.h
6466cec57913f204061932aef2ffd98085740ee8
[]
no_license
UniLauX/VideoMatting
cc4ca435c9013a22235c38ed1e6d191a3c04b1f0
29be302b6496fe521cbc4caee1b3a163dc902c33
refs/heads/master
2023-03-01T17:43:36.645845
2021-01-28T10:09:43
2021-01-28T10:09:43
333,607,207
1
1
null
null
null
null
UTF-8
C++
false
false
5,298
h
#pragma once #include <vector> #include "ZImage.h" #include "WmlMathLib.h" #include "ZMattingInterface.h" #define REGION_BG 0 #define REGION_BG_EDIT 1 #define REGION_UNINIT 2 #define REGION_UNKNOWN 128 #define REGION_FG 255 class CSparseMatrix; class CSparseMatrix_ListType; namespace MattingAlgorithm{ class CClosedFormMatting : public ZMattingInterface { public: CClosedFormMatting(void); public: ~CClosedFormMatting(void); public: //Input & output Interface: if not available, fill 0 virtual bool ImageSolve(ZFloatImage* pSrcImg, /*Source Input Image*/ ZByteImage* pTriMap,/*Input Trimap*/ ZFloatImage* pBgPrior, /*Input Bg Prior: (r,g,b,w)*/ ZFloatImage* pDataCost, /*Input Data cost Prior: (bg,fg,weight)*/ ZFloatImage* pSmoothCost, /*Input Smoothness Prior: (EAST,SOUTH,WEST,NORTH,weight)*/ ZByteImage* pAlpha, /*Output Alpha*/ ZFloatImage* pBgImg, /*Output Bg Image*/ ZFloatImage* pFgImg /*Output Fg Image*/ ); //Input & output Interface: if not available, fill 0 virtual bool VideoSolve(FloatImgList* pSrcImg, /*Source Input Images*/ ByteImgList* pTriMap,/*Input Trimaps*/ FloatImgList* pBgPrior, /*Input Bg Priors: (r,g,b,w)*/ FloatImgList* pDataCost, /*Input Data cost Priors: (bg,fg,weight)*/ FloatImgList* pSmoothCost, /*Input Smoothness Priors: (EAST,SOUTH,WEST,NORTH,weight)*/ IntImgList* pTMaps, /*Input termproal prior: (x1,y1,x2,y2)*/ bool bStaticCamera, /*Camera is static or not*/ ByteImgList* pAlpha, /*Output Alpha Imgs*/ FloatImgList* pBgImg, /*Output Bg Images*/ FloatImgList* pFgImg /*Output Fg Images*/ ); public: void Test(); void Test2(); ZFloatImage* RunMatting(ZFloatImage& srcImg, ZByteImage& triMap); bool RunMatting(ZFloatImage& srcImg,ZByteImage& triMap,ZFloatImage& bgInfo); ZFloatImage* SolveAlphaC2F(ZFloatImage& img,ZByteImage& triMap,int levels_num, int active_levels_num); ZFloatImage* SolveAlpha(ZFloatImage& srcImg, ZByteImage& triMap); ZFloatImage* SolveAlpha_WithBG(ZFloatImage& srcImg,ZByteImage& triMap,ZFloatImage& bgInfo); ZFloatImage* SolveAlpha_Generic(ZFloatImage& srcImg, ZByteImage& triMap, ZFloatImage* pDataCost, ZFloatImage* pSmoothCost); void SolveFB(ZFloatImage& srcImg, ZFloatImage& alpha, ZFloatImage& F, ZFloatImage& B); CSparseMatrix_ListType* _GetLaplacian(ZFloatImage& srcImg, ZByteImage& triMap, Wml::GVectord& b, ZIntImage& indsM); CSparseMatrix_ListType* _GetLaplacian_WithBG(ZFloatImage& srcImg, ZByteImage& triMap, ZFloatImage& bgImg, Wml::GVectord& b, ZIntImage& indsM); CSparseMatrix_ListType* _CreateSparseMatrix(std::vector<int>& row_inds, std::vector<int>& col_inds, std::vector<double>& vals, int nRows,int nCols); void _imErode(ZByteImage& triMap, ZByteImage& o_constsMap, ZByteImage& constsMap); void _imErode(ZByteImage& img); void _Conv2(ZFloatImage& img, ZFloatVector& filterW, ZFloatVector& filterH); ZByteImage* _DownSmpTrimap(ZByteImage& triMap); void _CalTvals(Wml::GMatrixd& tvals,const Wml::GMatrixd& winI, const Wml::GMatrixd& win_var); void _CalWinVar(Wml::GMatrixd& win_var, const Wml::GMatrixd& winI, const Wml::GMatrixd& win_mu); ZFloatImage* _DownSmpImg(ZFloatImage& img); ZByteImage* _DownSmpImg(ZByteImage& img); ZFloatImage* _UpSampleAlphaUsingImg(ZFloatImage& alphaImg,ZFloatImage& img, ZFloatImage& b_img); ZFloatImage* _GetLinearCoeff(ZFloatImage& alphaImg, ZFloatImage& img); ZFloatImage* _UpSmpImg(ZFloatImage* coeff, int iNewW, int iNewH, int filterS); void _UpdateTrimap(ZByteImage& triMap,ZFloatImage& alphaImg); public: void SolveAlpha_MultiFrames(FloatImgList& srcImgList,ByteImgList& triMapList,IntImgList& csMapList,FloatImgList& wMapList, FloatImgList& alphaImgList); void SolveAlpha_MultiFrames_Fix(FloatImgList& srcImgList,ByteImgList& triMapList,IntImgList& csMapList,FloatImgList& wMapList, FloatImgList& alphaImgList, FloatImgList& fixAlphaImgList, std::vector<int>& fixImgList); void SolveAlpha_MultiFrames_SpatialSmooth(FloatImgList& srcImgList,ByteImgList& triMapList,IntImgList& csMapList,FloatImgList& wMapList, FloatImgList& alphaImgList,FloatImgList& spatialWList); void SolveAlpha_MultiFrames_SoftConstraint(FloatImgList& srcImgList,ByteImgList& triMapList,IntImgList& csMapList,FloatImgList& wMapList, FloatImgList& alphaImgList, ByteImgList& constMapList, FloatImgList& constWList,FloatImgList& spatialWList); void SolveAlphaWithBG_MultiFrames(FloatImgList& srcImgList,ByteImgList& triMapList,IntImgList& csMapList,FloatImgList& wMapList, FloatImgList& bgInfoList,FloatImgList& alphaImgList); CSparseMatrix_ListType* _GetLaplacian_MultiFrames2(FloatImgList& srcImgList, ByteImgList& triMapList, IntImgList& csMapList,FloatImgList& wMapList, Wml::GVectord& b, IntImgList& indsMList); CSparseMatrix_ListType* _GetLaplacianWithBG_MultiFrames(FloatImgList& srcImgList, ByteImgList& triMapList, IntImgList& csMapList,FloatImgList& wMapList, FloatImgList& bgInfoList, Wml::GVectord& b, IntImgList& indsMList); int _CalIndsM(ByteImgList& triMapList,IntImgList& csMapList,IntImgList& indsMList); private: double m_thr_alpha; double epsilon; int win_size; }; }
[ "zhangshuoyan@jd.com" ]
zhangshuoyan@jd.com
cf199c9e018e25931216e39e1bb1c2a2963ecec4
e744609c9c13540d529b74bea0f8989e4bff06c3
/tensorflow/tsl/profiler/utils/xplane_schema.h
95b40a4e750425af927947c5f5cd81a0c182e432
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
josephmjansen/tensorflow
c41d354e5e7fb957e096bbe0f380541ca88e1e73
324e691d27ea011d85b4aba0f9c9be5e45f24df5
refs/heads/master
2023-05-25T09:08:57.167040
2023-05-11T16:17:11
2023-05-11T16:21:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,173
h
/* Copyright 2019 The TensorFlow Authors. 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 TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_SCHEMA_H_ #define TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_SCHEMA_H_ #include <atomic> #include <cstdint> #include <string> #include "absl/hash/hash.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "tensorflow/tsl/platform/logging.h" #include "tensorflow/tsl/platform/macros.h" #include "tensorflow/tsl/platform/types.h" #include "tensorflow/tsl/profiler/lib/context_types.h" namespace tsl { namespace profiler { // Name of XPlane that contains TraceMe events. TF_CONST_INIT extern const absl::string_view kHostThreadsPlaneName; // Name prefix of XPlane that contains GPU events. TF_CONST_INIT extern const absl::string_view kGpuPlanePrefix; // Name prefix of XPlane that contains TPU events. TF_CONST_INIT extern const absl::string_view kTpuPlanePrefix; // Regex for XPlanes that contain TensorCore planes. TF_CONST_INIT extern const char kTpuPlaneRegex[]; // Name prefix of XPlane that contains custom device events. TF_CONST_INIT extern const absl::string_view kCustomPlanePrefix; // Name prefix of XPlane that contains TPU non-core events such as HBM, ICI etc. TF_CONST_INIT extern const absl::string_view kTpuNonCorePlaneNamePrefix; // Name prefix of XPlane that contains TPU runtime events. TF_CONST_INIT extern const absl::string_view kTpuRuntimePlaneName; // Name of XPlane that contains CUPTI driver API generated events. TF_CONST_INIT extern const absl::string_view kCuptiDriverApiPlaneName; // Name of XPlane that contains Roctracer API generated events. TF_CONST_INIT extern const absl::string_view kRoctracerApiPlaneName; // Name of XPlane that contains profile metadata such as XLA debug info. TF_CONST_INIT extern const absl::string_view kMetadataPlaneName; // Name of XPlane that contains kpi related metrics. TF_CONST_INIT extern const absl::string_view kTFStreamzPlaneName; // Name of XPlane that contains events from python tracer. TF_CONST_INIT extern const absl::string_view kPythonTracerPlaneName; // Name of XPlane that contains kTrace thread-switch events TF_CONST_INIT extern const absl::string_view kHostCpusPlaneName; // Name of XPlane that contains kTrace system calls. TF_CONST_INIT extern const absl::string_view kSyscallsPlaneName; // Names of XLines that contain ML-level events. TF_CONST_INIT extern const absl::string_view kStepLineName; TF_CONST_INIT extern const absl::string_view kTensorFlowNameScopeLineName; TF_CONST_INIT extern const absl::string_view kTensorFlowOpLineName; TF_CONST_INIT extern const absl::string_view kXlaModuleLineName; TF_CONST_INIT extern const absl::string_view kXlaOpLineName; TF_CONST_INIT extern const absl::string_view kXlaAsyncOpLineName; TF_CONST_INIT extern const absl::string_view kKernelLaunchLineName; TF_CONST_INIT extern const absl::string_view kSourceLineName; TF_CONST_INIT extern const absl::string_view kCounterEventsLineName; // GPU device vendors. TF_CONST_INIT extern const absl::string_view kDeviceVendorNvidia; TF_CONST_INIT extern const absl::string_view kDeviceVendorAMD; // Interesting event types (i.e., TraceMe names). enum HostEventType { kFirstHostEventType = 0, kUnknownHostEventType = kFirstHostEventType, kTraceContext, kSessionRun, kFunctionRun, kRunGraph, kRunGraphDone, kTfOpRun, kEagerKernelExecute, kExecutorStateProcess, kExecutorDoneCallback, kMemoryAllocation, kMemoryDeallocation, // Performance counter related. kRemotePerf, // tf.data captured function events. kTfDataCapturedFunctionRun, kTfDataCapturedFunctionRunWithBorrowedArgs, kTfDataCapturedFunctionRunInstantiated, kTfDataCapturedFunctionRunAsync, // Loop ops. kParallelForOp, kForeverOp, kWhileOpEvalCond, kWhileOpStartBody, kForOp, // tf.data related. kIteratorGetNextOp, kIteratorGetNextAsOptionalOp, kIterator, kDeviceInputPipelineSecondIterator, kPrefetchProduce, kPrefetchConsume, kParallelInterleaveProduce, kParallelInterleaveConsume, kParallelInterleaveInitializedInput, kParallelMapProduce, kParallelMapConsume, kMapAndBatchProduce, kMapAndBatchConsume, kParseExampleProduce, kParseExampleConsume, kParallelBatchProduce, kParallelBatchConsume, // Batching related. kBatchingSessionRun, kProcessBatch, kConcatInputTensors, kMergeInputTensors, kScheduleWithoutSplit, kScheduleWithSplit, kScheduleWithEagerSplit, kASBSQueueSchedule, // TFRT related. kTfrtModelRun, // GPU related. kKernelLaunch, kKernelExecute, // TPU related kEnqueueRequestLocked, kRunProgramRequest, kHostCallbackRequest, kTransferH2DRequest, kTransferPreprocessedH2DRequest, kTransferD2HRequest, kOnDeviceSendRequest, kOnDeviceRecvRequest, kOnDeviceSendRecvLocalRequest, kCustomWait, kOnDeviceSendRequestMulti, kOnDeviceRecvRequestMulti, kPjrtAsyncWait, kDoEnqueueProgram, kDoEnqueueContinuationProgram, kWriteHbm, kReadHbm, kTpuExecuteOp, kCompleteCallbacks, kTransferToDeviceIssueEvent, kTransferToDeviceDone, kTransferFromDeviceIssueEvent, kTransferFromDeviceDone, kTpuSystemExecute, kTpuPartitionedCallOpInitializeVarOnTpu, kTpuPartitionedCallOpExecuteRemote, kTpuPartitionedCallOpExecuteLocal, kLinearize, kDelinearize, kTransferBufferFromDeviceFastPath, kLastHostEventType = kTransferBufferFromDeviceFastPath, }; enum StatType { kFirstStatType = 0, kUnknownStatType = kFirstStatType, // TraceMe arguments. kStepId, kDeviceOrdinal, kChipOrdinal, kNodeOrdinal, kModelId, kQueueId, kQueueAddr, kRequestId, kRunId, kReplicaId, kGraphType, kStepNum, kIterNum, kIndexOnHost, kAllocatorName, kBytesReserved, kBytesAllocated, kBytesAvailable, kFragmentation, kPeakBytesInUse, kRequestedBytes, kAllocationBytes, kAddress, kRegionType, kDataType, kTensorShapes, kTensorLayout, kKpiName, kKpiValue, kElementId, kParentId, // XPlane semantics related. kProducerType, kConsumerType, kProducerId, kConsumerId, kIsRoot, kIsAsync, // Device trace arguments. kDeviceId, kDeviceTypeString, kContextId, kCorrelationId, // TODO(b/176137043): These "details" should differentiate between activity // and API event sources. kMemcpyDetails, kMemallocDetails, kMemFreeDetails, kMemsetDetails, kMemoryResidencyDetails, kNVTXRange, kKernelDetails, kStream, // Stats added when processing traces. kGroupId, kFlow, kStepName, kTfOp, kHloOp, kHloCategory, kHloModule, kProgramId, kEquation, kIsEager, kIsFunc, kTfFunctionCall, kTfFunctionTracingCount, kFlops, kBytesAccessed, kSourceInfo, kModelName, kModelVersion, kBytesTransferred, kDmaQueue, // Performance counter related. kRawValue, kScaledValue, kThreadId, kMatrixUnitUtilizationPercent, // XLA metadata map related. kHloProto, // Device capability related. kDevCapClockRateKHz, kDevCapCoreCount, kDevCapMemoryBandwidth, kDevCapMemorySize, kDevCapComputeCapMajor, kDevCapComputeCapMinor, kDevCapPeakTeraflopsPerSecond, kDevCapPeakHbmBwGigabytesPerSecond, kDevCapPeakSramRdBwGigabytesPerSecond, kDevCapPeakSramWrBwGigabytesPerSecond, kDevVendor, // Batching related. kBatchSizeAfterPadding, kPaddingAmount, kBatchingInputTaskSize, // GPU occupancy metrics kTheoreticalOccupancyPct, kOccupancyMinGridSize, kOccupancySuggestedBlockSize, // Aggregrated Stats kSelfDurationPs, kMinDurationPs, kTotalProfileDurationPs, kMaxIterationNum, kDeviceType, kUsesMegaCore, kSymbolId, kTfOpName, kDmaStallDurationPs, kKey, kPayloadSizeBytes, kDuration, kBufferSize, kTransfers, kLastStatType = kTransfers, }; inline std::string TpuPlaneName(int32_t device_ordinal) { return absl::StrCat(kTpuPlanePrefix, device_ordinal); } inline std::string GpuPlaneName(int32_t device_ordinal) { return absl::StrCat(kGpuPlanePrefix, device_ordinal); } absl::string_view GetHostEventTypeStr(HostEventType event_type); bool IsHostEventType(HostEventType event_type, absl::string_view event_name); inline bool IsHostEventType(HostEventType event_type, absl::string_view event_name) { return GetHostEventTypeStr(event_type) == event_name; } absl::optional<int64_t> FindHostEventType(absl::string_view event_name); absl::optional<int64_t> FindTfOpEventType(absl::string_view event_name); absl::string_view GetStatTypeStr(StatType stat_type); bool IsStatType(StatType stat_type, absl::string_view stat_name); inline bool IsStatType(StatType stat_type, absl::string_view stat_name) { return GetStatTypeStr(stat_type) == stat_name; } bool IsTensorCorePlaneName(absl::string_view plane_name); absl::optional<int64_t> FindStatType(absl::string_view stat_name); // Returns true if the given event shouldn't be shown in the trace viewer. bool IsInternalEvent(absl::optional<int64_t> event_type); // Returns true if the given stat shouldn't be shown in the trace viewer. bool IsInternalStat(absl::optional<int64_t> stat_type); // Support for flow events: // This class enables encoding/decoding the flow id and direction, stored as // XStat value. The flow id are limited to 56 bits. class XFlow { public: enum FlowDirection { kFlowUnspecified = 0x0, kFlowIn = 0x1, kFlowOut = 0x2, kFlowInOut = 0x3, }; XFlow(uint64_t flow_id, FlowDirection direction, ContextType category = ContextType::kGeneric) { DCHECK_NE(direction, kFlowUnspecified); encoded_.parts.direction = direction; encoded_.parts.flow_id = flow_id; encoded_.parts.category = static_cast<uint64_t>(category); } // Encoding uint64 ToStatValue() const { return encoded_.whole; } // Decoding static XFlow FromStatValue(uint64_t encoded) { return XFlow(encoded); } /* NOTE: absl::HashOf is not consistent across processes (some process level * salt is added), even different executions of the same program. * However we are not tracking cross-host flows, i.e. A single flow's * participating events are from the same XSpace. On the other hand, * events from the same XSpace is always processed in the same profiler * process. Flows from different hosts are unlikely to collide because of * 2^56 hash space. Therefore, we can consider this is good for now. We should * revisit the hash function when cross-hosts flows became more popular. */ template <typename... Args> static uint64_t GetFlowId(Args&&... args) { return absl::HashOf(std::forward<Args>(args)...) & kFlowMask; } uint64_t Id() const { return encoded_.parts.flow_id; } ContextType Category() const { return GetSafeContextType(encoded_.parts.category); } FlowDirection Direction() const { return FlowDirection(encoded_.parts.direction); } static uint64_t GetUniqueId() { // unique in current process. return next_flow_id_.fetch_add(1); } private: explicit XFlow(uint64_t encoded) { encoded_.whole = encoded; } static constexpr uint64_t kFlowMask = (1ULL << 56) - 1; static std::atomic<uint64_t> next_flow_id_; union { // Encoded representation. uint64_t whole; struct { uint64_t direction : 2; uint64_t flow_id : 56; uint64_t category : 6; } parts; } encoded_ ABSL_ATTRIBUTE_PACKED; static_assert(sizeof(encoded_) == sizeof(uint64_t), "Must be 64 bits."); }; // String constants for XProf TraceMes for DCN Messages. TF_CONST_INIT extern const absl::string_view kMegaScaleDcnReceive; TF_CONST_INIT extern const absl::string_view kMegaScaleDcnSend; TF_CONST_INIT extern const absl::string_view kMegaScaleDcnSendFinished; TF_CONST_INIT extern const absl::string_view kMegaScaleTopologyDiscovery; TF_CONST_INIT extern const absl::string_view kMegaScaleBarrier; TF_CONST_INIT extern const absl::string_view kMegaScaleHostCommand; TF_CONST_INIT extern const absl::string_view kMegaScaleD2HTransferStart; TF_CONST_INIT extern const absl::string_view kMegaScaleD2HTransferFinished; TF_CONST_INIT extern const absl::string_view kMegaScaleH2DTransferStart; TF_CONST_INIT extern const absl::string_view kMegaScaleH2DTransferFinished; TF_CONST_INIT extern const char kXProfMetadataKey[]; TF_CONST_INIT extern const char kXProfMetadataFlow[]; TF_CONST_INIT extern const char kXProfMetadataTransfers[]; TF_CONST_INIT extern const char kXProfMetadataBufferSize[]; } // namespace profiler } // namespace tsl #endif // TENSORFLOW_TSL_PROFILER_UTILS_XPLANE_SCHEMA_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
0ae0cd3490df839fa9a95e0e2a058d046af3ed15
ab7d5ec2e40b26c33da957210b5d2da77f9b696d
/repos/iso/contents/PolycodeTemplate/winmain.cpp
86417f7783aca7b443d46bd2f354dd395702a782
[]
no_license
mcclure/bitbucket-backup
e49d280363ff7ef687f03473e463865a7ad8a817
b6a02ca8decf843fa0a765c842c24e7eccf59307
refs/heads/archive
2023-01-24T21:15:14.875131
2020-02-02T20:56:23
2020-02-02T20:56:23
237,833,969
115
6
null
2023-01-07T14:24:14
2020-02-02T20:43:56
C
UTF-8
C++
false
false
547
cpp
#include "windows.h" #include <Polycode.h> #include "PolycodeTemplateApp.h" #include "PolycodeView.h" using namespace Polycode; #define NAME L"LD25" int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { PolycodeView *view = new PolycodeView(hInstance, nCmdShow, NAME); PolycodeTemplateApp *app = new PolycodeTemplateApp(view); MSG Msg; do { if(PeekMessage(&Msg, NULL, 0,0,PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } } while(app->Update()); return Msg.wParam; }
[ "andi.m.mcclure@gmail.com" ]
andi.m.mcclure@gmail.com
5f2dcdfb090d11d9eb811e957a6d919c2aa37e36
bbeffa6612df177a804b29172321d45edce45da0
/Documents/PokemonClone/Move.cpp
0a1ff36770fa34dd34e95318219703c1df5ecd52
[]
no_license
ian9/Game-1
c9830204ca3116c283a06751f5171626e192131b
89594651770ec6782325c9eeb44d006f674cb9e8
refs/heads/master
2021-01-25T03:48:12.162173
2012-09-22T21:53:40
2012-09-22T21:53:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,051
cpp
#include "Move.h" std::vector<Move*> Move::moveDataSet; std::vector<std::string> Move::moveNames; Move::Move() { id = rand() % 36; special = Move::moveDataSet.at(id)->special; multiHit = Move::moveDataSet.at(id)->multiHit; power = Move::moveDataSet.at(id)->power; element = Move::moveDataSet.at(id)->element; priorityLevel = Move::moveDataSet.at(id)->priorityLevel; name = Move::moveNames.at(id); /*element = rand() % 9; if(element == 0) name = "Martial"; else if(element == 1) name = "Mental"; else if(element == 2) name = "Spirit"; else if(element == 3) name = "Fire"; else if(element == 4) name = "Water"; else if(element == 5) name = "Wood"; else if(element == 6) name = "Electric"; else if(element == 7) name = "Ground"; else if(element == 8) name = "Metal"; else name = "None";*/ } Move::Move(std::string nm) { name = nm; int randomNumber = rand() % 9; element = randomNumber; } Move::Move(int theId) { id = theId; special = Move::moveDataSet.at(theId)->special; multiHit = Move::moveDataSet.at(theId)->multiHit; power = Move::moveDataSet.at(theId)->power; element = Move::moveDataSet.at(theId)->element; priorityLevel = Move::moveDataSet.at(theId)->priorityLevel; name = Move::moveNames.at(id); } Move::Move(int tempID, bool tempSpecial, bool tempMulti, int tempPower, int tempElement, int tempPriority) { id = tempID; special = tempSpecial; multiHit = tempMulti; power = tempPower; element = tempElement; priorityLevel = tempPriority; } std::string Move::getName() { return name; } int Move::getID() { return id; } int Move::getElement() { return element; } int Move::getPriorityLevel() { return priorityLevel; } bool Move::isSpecialAttack() { return special; } bool Move::isHitsMultiple() { return multiHit; } double Move::getPower() { return power; }
[ "urafatrodent@gmail.com" ]
urafatrodent@gmail.com
be2443d84c2d04de0d32ffca48664bec3ab1a71b
0edbcda83b7a9542f15f706573a8e21da51f6020
/private/shell/ext/mlang/fechauto.cpp
6c57d4ca55d63a537ed49f77e42dfa3b622efd54
[]
no_license
yair-k/Win2000SRC
fe9f6f62e60e9bece135af15359bb80d3b65dc6a
fd809a81098565b33f52d0f65925159de8f4c337
refs/heads/main
2023-04-12T08:28:31.485426
2021-05-08T22:47:00
2021-05-08T22:47:00
365,623,923
1
3
null
null
null
null
UTF-8
C++
false
false
20,743
cpp
/*---------------------------------------------------------------------------- %%File: fechauto.c %%Unit: fechmap %%Contact: jpick Module that attempts to auto-detect encoding for a given stream. ----------------------------------------------------------------------------*/ #include <stdio.h> #include <stddef.h> #include "private.h" #include "fechmap_.h" #include "lexint_.h" // Code marked by these #defines will be deleted eventually ... // (It prints out useful information and statistics about how // auto-detect is doing and what it's finding in the input). // #define JPDEBUG 0 #define JPDEBUG2 0 #define JPDEBUG3 0 #define NEED_NAMES 0 #if JPDEBUG || JPDEBUG2 || JPDEBUG3 #undef NEED_NAMES #define NEED_NAMES 1 #endif #if NEED_NAMES static char *rgszIcetNames[icetCount] = { "icetEucCn", "icetEucJp", "icetEucKr", "icetEucTw", "icetIso2022Cn", "icetIso2022Jp", "icetIso2022Kr", "icetIso2022Tw", "icetBig5", "icetGbk", "icetHz", "icetShiftJis", "icetWansung", "icetUtf7", "icetUtf8", }; #endif // Characters we care about // #define chSo (UCHAR) 0x0e #define chSi (UCHAR) 0x0f #define chEsc (UCHAR) 0x1b // Minimum Sample Size // #define cchMinSample 64 // High-ASCII character threshold. If this routine is unable // to absolutely determine the encoding of this file, it will // need to guess. Files that are ASCII, but contain high-ASCII // characters (e.g., a file with some Cyrillic characters) may // confuse us. If the number of high-ASCII characters falls // below this threshold, return the encoding we guessed but // also return a special rc that says the file "might be ASCII." // // 5%, for now. // // 40%, for now, of the high-ascii characters must be in high- // ascii pairs. (Pulled down because of Big5 and the other // DBCS encodings that can have trail bytes in the low range). // #define nHighCharThreshold 5 // % #define nHighPairThreshold 40 // % // Used by CceDetermineInputTypeReturnAll() to determine whether any icet has // high enough count to rule out all other icets. // #define CchCountThreshold(icet) (((icet) == icetHz || (icet) == icetUtf7) ? 5 : 10) // Tokens // // Stop tokens (negative) imply special handling and will cause // the processing loop to stop (eof, err, si, so and esc are // stop tokens). // #define xmn 0 #define esc (-1) #define so (-2) #define si (-3) #define eof (-4) #define err (-5) #define _FStopToken(tk) ((tk) < 0) // Masks used in _CBitsOnFromUlong() // #define lMaskBitCount1 (LONG) 0x55555555 #define lMaskBitCount2 (LONG) 0x33333333 #define lMaskBitCount3 (LONG) 0x0F0F0F0F #define lMaskBitCount4 (LONG) 0x00FF00FF #define lMaskBitCount5 (LONG) 0x0000FFFF /* _ C B I T S O N F R O M U L O N G */ /*---------------------------------------------------------------------------- %%Function: _CBitsOnFromUlong %%Contact: jpick (adapted from code in convio.c) ----------------------------------------------------------------------------*/ int __inline _CBitsOnFromUlong(ULONG ulBits) { ulBits = (ulBits & lMaskBitCount1) + ((ulBits & ~lMaskBitCount1) >> 1); ulBits = (ulBits & lMaskBitCount2) + ((ulBits & ~lMaskBitCount2) >> 2); ulBits = (ulBits & lMaskBitCount3) + ((ulBits & ~lMaskBitCount3) >> 4); ulBits = (ulBits & lMaskBitCount4) + ((ulBits & ~lMaskBitCount4) >> 8); ulBits = (ulBits & lMaskBitCount5) + ((ulBits & ~lMaskBitCount5) >> 16); return (int)ulBits; } // Masks for the encodings // #define grfEucCn (ULONG) 0x0001 #define grfEucJp (ULONG) 0x0002 #define grfEucKr (ULONG) 0x0004 #define grfEucTw (ULONG) 0x0008 #define grfIso2022Cn (ULONG) 0x0010 #define grfIso2022Jp (ULONG) 0x0020 #define grfIso2022Kr (ULONG) 0x0040 #define grfIso2022Tw (ULONG) 0x0080 #define grfBig5 (ULONG) 0x0100 #define grfGbk (ULONG) 0x0200 #define grfHz (ULONG) 0x0400 #define grfShiftJis (ULONG) 0x0800 #define grfWansung (ULONG) 0x1000 #define grfUtf7 (ULONG) 0x2000 #define grfUtf8 (ULONG) 0x4000 // grfAll assumes that the tests for Euc-Kr fall within those // for Wansung (as far as I can tell from reading, Euc-Kr is a // strict subset of Wansung). The same for Euc-Cn and Gbk. No // need to test for both the subset and the whole. // #define grfAll (ULONG) 0x7FFA #define grfAllButIso2022 (ULONG) 0x7F0A #define cAll 13 // == number bits set in grfAll #define cAllButIso2022 9 // == number bits set in grfAllButIso2022 // Array that maps an encoding to its mask // static ULONG _mpicetgrf[icetCount] = { grfEucCn, grfEucJp, grfEucKr, grfEucTw, grfIso2022Cn, grfIso2022Jp, grfIso2022Kr, grfIso2022Tw, grfBig5, grfGbk, grfHz, grfShiftJis, grfWansung, grfUtf7, grfUtf8, }; // Prototypes // static int _NGetNextUch(IStream *pstmIn, unsigned char *c, BOOL *lpfIsHigh); static ICET _IcetFromIcetMask(ULONG ulMask); static ICET _IcetDefaultFromIcetMask(ULONG ulMask); static CCE _CceResolveAmbiguity(ULONG grfIcet, ICET *lpicet, int nPrefCp, EFam efPref); static CCE _CceReadEscSeq(IStream *pstmIn, int nPrefCp, ICET *lpicet, BOOL *lpfGuess); /* C C E D E T E R M I N E I N P U T T Y P E */ /*---------------------------------------------------------------------------- %%Function: CceDetermineInputType %%Contact: jpick Attempt to determine the appropriate ICET type for the given stream. Caller-supplied get/unget routines used for data access. ----------------------------------------------------------------------------*/ CCE CceDetermineInputType( IStream *pstmIn, // input stream DWORD dwFlags, // configuration flags EFam efPref, // optional: preferred encoding family int nPrefCp, // optional: preferred code page ICET *lpicet, // set to detected encoding BOOL *lpfGuess // set to fTrue if function "guessed" ) { unsigned char uch; int nToken; CCE cceRet; BOOL fGuess; ICET icet; int cIcetActive; ULONG grfIcetActive; // Bitarray tracks which encodings are still active candidates. ICET icetSeq; int i, nCount, nCountCurr; DWORD dwValFlags; BOOL fIsHigh; int cchHigh = 0; int cchHighPairs = 0; int cchTotal = 0; BOOL fLastHigh = fFalse; #if JPDEBUG3 ULONG grfIcetNoCommonChars; #endif #if JPDEBUG printf("flags: %d\n", dwFlags); #endif // Initialize parsers // dwValFlags = grfCountCommonChars; if (dwFlags & grfDetectUseCharMapping) dwValFlags |= grfValidateCharMapping; ValidateInitAll(dwValFlags); // Initialize locals -- be optimistic // cceRet = cceSuccess; fGuess = fFalse; grfIcetActive = grfAllButIso2022; cIcetActive = cAllButIso2022; #if JPDEBUG3 grfIcetNoCommonChars = grfAllButIso2022; #endif while (fTrue) { nToken = _NGetNextUch(pstmIn, &uch, &fIsHigh); if (_FStopToken(nToken)) break; // Update (admittedly dumb) statistics -- really counts high // ascii characters in runs (not really pairs). But threshold // constants (defined, above) were determined by calculating // exactly these numbers for ~25 files, so it should be ok (?). // ++cchTotal; if (fIsHigh) { ++cchHigh; if (fLastHigh) ++cchHighPairs; } fLastHigh = fIsHigh; for (i = 0; i < icetCount; i++) { if (!(grfIcetActive & _mpicetgrf[i]) || (NValidateUch((ICET)i, uch, fFalse) != 0)) continue; grfIcetActive &= ~_mpicetgrf[i]; --cIcetActive; #if JPDEBUG printf("Log: Lost %s at offset 0x%.4x (%d), char 0x%.2x\n", rgszIcetNames[i], (cchTotal-1), (cchTotal-1), uch); #endif } #if JPDEBUG3 for (i = 0; i < icetCount; i++) { if (!(grfIcetActive & _mpicetgrf[i]) || !(grfIcetNoCommonChars & _mpicetgrf[i])) continue; if (!FValidateCharCount(i, &nCount) || (nCount == 0)) continue; grfIcetNoCommonChars &= ~_mpicetgrf[i]; printf("Log: Found first common seq for %s at offset 0x%.4x (%d)\n", rgszIcetNames[i], (cchTotal-1), (cchTotal-1)); } #endif if ((cIcetActive == 0) || ((cIcetActive == 1) && (cchTotal > cchMinSample))) break; } // Figure out why we exited the loop. // if (nToken == err) { cceRet = cceRead; goto _LRet; } // Process escapes separately. Interpret the escape sequence // to determine for real which ISO7 flavor we have found. // if ((nToken == esc) || (nToken == so) || (nToken == si)) { LARGE_INTEGER li; HRESULT hr; LISet32(li, -1 ); hr = pstmIn->Seek(li,STREAM_SEEK_CUR, NULL); // if (!pfnUnget(uch, lpvPrivate)) // { // cceRet = cceUnget; // goto _LRet; // } cceRet = _CceReadEscSeq(pstmIn, nPrefCp, &icet, &fGuess); #if JPDEBUG if (cceRet == cceSuccess) printf("Log: Found encoding %s at offset 0x%.4x (%d)\n", rgszIcetNames[icet], cchTotal, cchTotal); #endif // ISO is a special case -- no need to check statistics. // goto _LRet; } #if JPDEBUG2 printf("Counts: %d total chars, %d high chars, %d high pairs\n", cchTotal, cchHigh, cchHighPairs); #endif // If the token was eof, and we're not ignoring eof, transition // the remaining active sets on eof. // if ((nToken == eof) && !(dwFlags & grfDetectIgnoreEof)) { for (i = 0; i < icetCount; i++) { if (!(grfIcetActive & _mpicetgrf[i]) || (NValidateUch((ICET)i, 0, fTrue) != 0)) continue; #if JPDEBUG printf("Log: Lost %s at EOF\n", rgszIcetNames[i]); #endif grfIcetActive &= ~_mpicetgrf[i]; --cIcetActive; } } Assert(cIcetActive >= 0); // better *not* be less than 0 // See how we've narrowed our field of choices and set the // return status accordingly. // if (cIcetActive <= 0) { #if JPDEBUG printf("Log: Bailed out entirely at offset 0x%.4x (%d)\n", cchTotal, cchTotal); #endif cceRet = cceUnknownInput; goto _LRet; } else if (cIcetActive == 1) { icet = _IcetFromIcetMask(grfIcetActive); #if JPDEBUG printf("Log: Found encoding %s at offset 0x%.4x (%d)\n", rgszIcetNames[icet], cchTotal, cchTotal); #endif // If we matched an encoding type and also found matching // common character runs, skip statistics (see comment, // below). // if (FValidateCharCount(icet, &nCount) && (nCount > 0)) { #if JPDEBUG3 printf("Log: %d common sequences for %s\n", nCount, rgszIcetNames[icet]); #endif goto _LRet; } else { goto _LStats; } } // Did we learn anything from counting characters? // icetSeq = (ICET)-1; nCountCurr = 0; for (i = 0; i < icetCount; i++) { if (!(grfIcetActive & _mpicetgrf[i]) || !FValidateCharCount((ICET)i, &nCount)) continue; if (nCount > nCountCurr) { icetSeq = (ICET)i; nCountCurr = nCount; } #if JPDEBUG3 printf("Log: %d common sequences for %s\n", nCount, rgszIcetNames[i]); #endif } // Any luck? If so, return. Don't bother checking statistics. // We just proved that we found at least one common run of // characters in this input. The odds against this for just a // plain ASCII file with some high characters seem pretty high. // Ignore the statistics and just return the encoding type we // found. // if (icetSeq != -1) { icet = icetSeq; goto _LRet; } #if JPDEBUG printf("Log: Active Icet Mask 0x%.8x, %d left\n", grfIcetActive, cIcetActive); printf("Log: Icet's left -- "); for (i = 0; i < icetCount; i++) { if (grfIcetActive & _mpicetgrf[i]) printf("%s, ", rgszIcetNames[i]); } printf("\n"); #endif // If caller did not want us to try to guess at the encoding // in the absence of definitive data, bail out. // if (!(dwFlags & grfDetectResolveAmbiguity)) { cceRet = cceAmbiguousInput; goto _LRet; } // We're guessing -- note it. // fGuess = fTrue; // More than one active encoding. Attempt to resolve ambiguity. // cceRet = _CceResolveAmbiguity(grfIcetActive, &icet, nPrefCp, efPref); if (cceRet != cceSuccess) return cceRet; _LStats: // Adjust the return code based on the "statistics" we gathered, // above. // if (cchHigh > 0) { if ((cchTotal < cchMinSample) || (((cchHigh * 100) / cchTotal) < nHighCharThreshold) || (((cchHighPairs * 100) / cchHigh) < nHighPairThreshold)) { cceRet = cceMayBeAscii; } } else { cceRet = cceMayBeAscii; // no high-ascii characters? definitely maybe! } #if JPDEBUG2 if (cchHigh > 0) { int nPercent1 = ((cchHigh * 100) / cchTotal); int nPercent2 = ((cchHighPairs * 100) / cchHigh); printf("Ratios -- high/total: %d%%, runs/high: %d%%\n", nPercent1, nPercent2); } #endif _LRet: // Set the return variables, if successful. // if ((cceRet == cceSuccess) || (cceRet == cceMayBeAscii)) { *lpicet = icet; *lpfGuess = fGuess; } #if JPDEBUG if (cceRet == cceSuccess) { printf("Log: Returning %s, fGuess = %s\n", rgszIcetNames[icet], (fGuess ? "fTrue" : "fFalse")); } else if (cceRet == cceMayBeAscii) { printf("Log: Returning %s, fGuess = %s, may-be-ASCII\n", rgszIcetNames[icet], (fGuess ? "fTrue" : "fFalse")); } #endif return cceRet; } /* _ N G E T N E X T U C H */ /*---------------------------------------------------------------------------- %%Function: _NGetNextUch %%Contact: jpick Get the next character from the input stream. Classify the character. ----------------------------------------------------------------------------*/ static int _NGetNextUch(IStream *pstmIn, unsigned char *c, BOOL *lpfIsHigh) { ULONG rc; unsigned char uch; HRESULT hr; hr = pstmIn->Read(&uch, 1, &rc); if (rc == 0) return eof; else if (hr != S_OK ) return err; *lpfIsHigh = (uch >= 0x80); *c = uch; switch (uch) { case chEsc: return esc; case chSo: return so; case chSi: return si; default: return xmn; } } // Masks for _CceResolveAmbiguity() -- only externally supported character // sets are used in ambiguity resolution. Don't include Euc-Tw here. // #define grfJapan (ULONG) (grfShiftJis | grfEucJp) #define grfChina (ULONG) (grfEucCn | grfGbk) #define grfKorea (ULONG) (grfEucKr | grfWansung) #define grfTaiwan (ULONG) (grfBig5) #define grfDbcs (ULONG) (grfShiftJis | grfGbk | grfWansung | grfBig5) #define grfEuc (ULONG) (grfEucJp | grfEucKr | grfEucCn) /* _ C E F R O M C E M A S K */ /*---------------------------------------------------------------------------- %%Function: _IcetFromIcetMask %%Contact: jpick ----------------------------------------------------------------------------*/ static ICET _IcetFromIcetMask(ULONG ulMask) { switch (ulMask) { case grfEucCn: return icetEucCn; case grfEucJp: return icetEucJp; case grfEucKr: return icetEucKr; case grfEucTw: return icetEucTw; case grfIso2022Cn: return icetIso2022Cn; case grfIso2022Jp: return icetIso2022Jp; case grfIso2022Kr: return icetIso2022Kr; case grfIso2022Tw: return icetIso2022Tw; case grfBig5: return icetBig5; case grfGbk: return icetGbk; case grfHz: return icetHz; case grfShiftJis: return icetShiftJis; case grfWansung: return icetWansung; case grfUtf7: return icetUtf7; case grfUtf8: return icetUtf8; default: break; } // Should never get here ... // // NotReached(); // Can't return a bogus value, here. // return icetShiftJis; } /* _ C E D E F A U L T F R O M C E M A S K */ /*---------------------------------------------------------------------------- %%Function: _IcetDefaultFromIcetMask %%Contact: jpick ----------------------------------------------------------------------------*/ static ICET _IcetDefaultFromIcetMask(ULONG ulMask) { // Priorities -- DBCS, EUC, Japan, Taiwan, China and Korea (???). // if (ulMask & grfDbcs) { if (ulMask & grfJapan) return icetShiftJis; if (ulMask & grfChina) return icetGbk; if (ulMask & grfTaiwan) return icetBig5; if (ulMask & grfKorea) return icetWansung; } else // EUC { if (ulMask & grfJapan) return icetEucJp; if (ulMask & grfChina) return icetEucCn; if (ulMask & grfKorea) return icetEucKr; // may be able to return icetWansung, here } // (Assert); return icetShiftJis; // ??? } /* _ U L C E M A S K F R O M C P E T P */ /*---------------------------------------------------------------------------- %%Function: _UlIcetMaskFromCpEf %%Contact: jpick ----------------------------------------------------------------------------*/ static ULONG _UlIcetMaskFromCpEf(int nCp, EFam ef) { ULONG grf = grfAll; switch (nCp) { case nCpJapan: grf &= grfJapan; break; case nCpChina: grf &= grfChina; break; case nCpKorea: grf &= grfKorea; break; case nCpTaiwan: grf &= grfTaiwan; break; default: break; } switch (ef) { case efDbcs: grf &= grfDbcs; break; case efEuc: grf &= grfEuc; break; default: break; } return grf; } /* _ C C E R E S O L V E A M B I G U I T Y */ /*---------------------------------------------------------------------------- %%Function: _CceResolveAmbiguity %%Contact: jpick Attempt to resolve ambiguous input encoding based on user preferences, if set, and system code page. grfIcet contains a bitmask representing the encodings that are still possible after examining the input sample. ----------------------------------------------------------------------------*/ static CCE _CceResolveAmbiguity(ULONG grfIcet, ICET *lpicet, int nPrefCp, EFam efPref) { ULONG grfIcetOrig = grfIcet; ULONG grfPref; ULONG grfSys; ULONG grfResult; UINT cpSys; int cIcet; // Build "list" of encodings based on user-prefs. // grfPref = _UlIcetMaskFromCpEf(nPrefCp, efPref); // See if the user's preferences make any difference. // grfResult = grfIcet & grfPref; if (grfResult) { cIcet = _CBitsOnFromUlong(grfResult); if (cIcet == 1) { *lpicet = _IcetFromIcetMask(grfResult); return cceSuccess; } else grfIcet = grfResult; // see comment, below } // Now look to the system code page for help. Look at // the set of encodings as modified by the user // preferences (??? do we want to do this ???). // cpSys = GetACP(); if (!FIsFeCp(cpSys) || (grfIcetOrig & grfUtf8)) goto _LDefault; // Build "list" of encodings based on system cp. // grfSys = _UlIcetMaskFromCpEf(cpSys, (EFam) 0); // See if the system cp makes any difference. // grfResult = grfIcet & grfSys; if (grfResult) { cIcet = _CBitsOnFromUlong(grfResult); if (cIcet == 1) { *lpicet = _IcetFromIcetMask(grfResult); return cceSuccess; } } _LDefault: // Special case -- pick UTF-8 if it's legal and the prefs // don't help us. // *lpicet = (grfIcetOrig & grfUtf8) ? icetUtf8 : _IcetDefaultFromIcetMask(grfIcet); return cceSuccess; } /* _ C C E R E A D E S C S E Q */ /*---------------------------------------------------------------------------- %%Function: _CceReadEscSeq %%Contact: jpick We've read (and put back) an escape character. Call the ISO-2022 escape sequence converter to have it map the escape sequence to the appropriate character set. We may be looking at the escape sequence for ASCII, so be prepared to read ahead to the next one. ----------------------------------------------------------------------------*/ static CCE _CceReadEscSeq( IStream *pstmIn, // input stream int nPrefCp, ICET *lpicet, BOOL *lpfGuess ) { unsigned char uch; CCE cceRet; int nToken; BOOL fDummy; do { cceRet = CceReadEscSeq(pstmIn, lpicet); if ((cceRet == cceSuccess) || (cceRet != cceMayBeAscii)) break; while (fTrue) { nToken = _NGetNextUch(pstmIn, &uch, &fDummy); if (_FStopToken(nToken)) break; } // Why did we stop? // if (nToken == err) { cceRet = cceRead; break; } else if (nToken == eof) { // Means this is legal ISO-2022 input, but we've seen nothing // but non-flavor-specific escape sequences (e.g., only ASCII // or shift sequences). Choose the encoding type based on // preferences (only pick from those currently supported // externally). // switch (nPrefCp) { case nCpKorea: *lpicet = icetIso2022Kr; break; case nCpJapan: default: // Right ??? (gotta pick something ...) *lpicet = icetIso2022Jp; break; } *lpfGuess = fTrue; // not *really* guessing, but ... (???) cceRet = cceSuccess; break; } Assert((nToken == esc) || (nToken == so) || (nToken == si)); { LARGE_INTEGER li; HRESULT hr; LISet32(li, -1 ); hr = pstmIn->Seek(li,STREAM_SEEK_CUR, NULL); } // Put it back for CceReadEscSeq() to process. // // if (!pfnUnget(uch, lpvPrivate)) // { // cceRet = cceUnget; // break; // } } while (fTrue); return cceRet; }
[ "ykorokhov@pace.ca" ]
ykorokhov@pace.ca
860a6fe5477af9b4427ae503e77ca6f08570b058
554e606f83e6eaaf048492c78b03aea889729ded
/dualJets3Mesh_LRRTurbulenceOff/2/p
f76b27ec9611f79094ee99dbbf73034cd4ea7ca2
[]
no_license
bshambaugh/openfoam-experiments4
87a211ed00f2de7da31cff548ea9bc9bd3368227
b1751d4d52270a2e7644f09bd6e77237d022ebd7
refs/heads/master
2020-04-17T04:46:57.796961
2019-02-16T00:48:06
2019-02-16T00:48:06
166,245,743
0
0
null
null
null
null
UTF-8
C++
false
false
13,120
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 4.1 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "2"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 1280 ( 0.1189 2.45086 2.27043 1.83213 4.59228 4.39673 3.97295 5.00266 7.23499 7.55268 6.67188 9.73995 10.0688 8.90785 12.1015 12.9195 12.0226 13.4179 17.0215 9.78168 20.9764 32.6388 37.9149 38.7518 42.521 48.2602 46.6258 50.5818 49.0889 48.9542 48.9999 48.3333 48.1371 47.2251 46.7358 45.5837 44.3424 43.7998 40.5067 41.4629 21.0133 25.4829 26.6203 26.9076 26.9235 27.7624 27.6298 27.5856 27.5529 27.6434 27.6397 27.5508 27.5547 27.6203 27.7774 26.7879 26.8378 26.5571 25.4242 20.8827 41.5735 40.5957 43.8793 44.4386 45.6797 46.8412 47.331 48.2464 48.4401 49.111 49.0649 49.1965 50.7175 46.9375 48.4971 42.7419 38.9551 38.115 32.8141 21.1329 9.96086 17.1625 13.5067 12.101 13.0088 12.1646 8.94925 10.1302 9.78612 6.68553 7.59258 7.26507 5.00277 3.96897 4.41429 4.61418 1.81119 2.27571 2.45574 0.0921902 0.0100554 0.0340333 0.0511827 0.0753761 0.102434 0.138309 0.186741 0.255565 0.349134 0.458029 0.531673 0.358251 -0.712297 -1.55296 -6.59618 -3.91818 0.0528844 1.93638 2.24088 0.0232175 0.0850476 0.128943 0.189172 0.253896 0.337564 0.448499 0.605677 0.81914 1.07225 1.30947 1.25145 -0.742152 -4.45248 -9.75815 -5.62511 0.269621 3.71988 3.55226 0.0355209 0.139488 0.214288 0.315827 0.424636 0.564213 0.748642 1.00965 1.36088 1.76115 2.12315 2.08497 -0.847167 -8.29394 -8.70727 -6.70925 0.723981 5.25207 4.50356 0.0445423 0.186751 0.286661 0.422379 0.565547 0.746442 0.982856 1.3146 1.74747 2.19408 2.54382 2.44993 -0.253227 -8.0423 -7.7622 -9.10843 1.39888 7.12047 6.13607 0.0515065 0.231836 0.354092 0.521273 0.694694 0.909858 1.18658 1.5677 2.03293 2.39066 2.43648 1.77888 -0.604574 -5.82777 -8.8822 -9.11177 1.39696 9.06717 6.75619 0.0558169 0.272279 0.411912 0.605154 0.801236 1.03829 1.336 1.73783 2.18948 2.32046 1.80749 0.420299 -1.5168 -3.60315 -9.30964 -7.60295 2.91009 11.9852 9.43197 0.057797 0.308421 0.460995 0.675518 0.887875 1.13644 1.43666 1.81375 2.15677 1.95896 1.23324 0.166235 -0.197399 0.105175 -6.90054 -9.30029 1.65205 12.9594 8.46606 0.0572888 0.338299 0.499018 0.729288 0.951725 1.20189 1.48604 1.84077 2.12977 1.82608 1.32719 1.184 2.28119 3.83658 -0.670218 -4.0555 8.07912 19.4639 12.2743 0.0555853 0.361287 0.526338 0.76685 0.992706 1.2347 1.50176 1.86099 2.12122 1.89401 1.5573 2.06712 3.70021 5.36157 2.48751 3.11534 20.1005 31.0879 24.3225 0.0528507 0.372549 0.53879 0.784862 1.01513 1.25937 1.52547 1.88383 2.14455 2.00015 1.76901 2.71907 4.46166 5.79548 3.37772 5.93089 24.9644 32.2921 25.8639 0.0528538 0.372556 0.538811 0.784921 1.01533 1.26001 1.52709 1.88755 2.15332 2.00745 1.76335 2.68785 4.42212 5.75731 3.36803 5.98856 24.9455 32.3116 26.0125 0.0555951 0.361311 0.526403 0.766984 0.992931 1.23494 1.50173 1.86044 2.12433 1.91293 1.5996 2.10321 3.694 5.28725 2.41685 3.28579 20.2136 30.9701 24.5447 0.0573036 0.338339 0.499126 0.729532 0.952298 1.20336 1.48969 1.84798 2.14434 1.86069 1.39401 1.26177 2.30807 3.71632 -0.911827 -3.76644 8.63759 19.6189 12.3753 0.0578159 0.308475 0.46114 0.675845 0.888595 1.13798 1.4398 1.81995 2.17156 1.99603 1.30453 0.260374 -0.128569 -0.0289042 -7.27508 -9.009 2.24205 13.1998 8.47285 0.0558377 0.272341 0.412077 0.605527 0.802059 1.0401 1.33988 1.74602 2.20768 2.35699 1.87639 0.529263 -1.39939 -3.71858 -9.56308 -7.50066 3.45377 12.1712 9.43476 0.0515267 0.231898 0.35426 0.521654 0.695534 0.911673 1.19038 1.57533 2.04849 2.4202 2.48896 1.86131 -0.532654 -5.99591 -8.9619 -9.11915 1.82091 9.24427 6.8155 0.0445602 0.186807 0.286814 0.422726 0.566306 0.748058 0.98617 1.32111 1.76028 2.21714 2.57866 2.49071 -0.258996 -8.22336 -7.94975 -8.94169 1.70584 7.26511 6.17375 0.0355344 0.139532 0.21441 0.316103 0.425236 0.565477 0.751209 1.01463 1.37039 1.77752 2.14416 2.09787 -0.864901 -8.24804 -8.93829 -6.55106 0.956761 5.36871 4.54955 0.0232261 0.085076 0.129022 0.189349 0.254281 0.33837 0.450123 0.608786 0.824943 1.08211 1.32143 1.252 -0.754255 -4.28688 -9.85818 -5.51957 0.444685 3.81198 3.57933 0.0100577 0.0340414 0.0512076 0.0754342 0.102562 0.138577 0.187275 0.256568 0.350941 0.460962 0.534528 0.352433 -0.730858 -1.47988 -6.54628 -3.82118 0.140388 1.98341 2.24478 122.593 120.449 120.276 118.089 117.223 115.026 113.707 112.088 110.924 109.406 108.487 107.259 106.733 105.674 105.515 104.592 104.665 103.948 104.034 103.647 103.555 103.428 104.247 103.829 104.551 104.221 104.579 104.241 104.348 103.995 103.981 103.548 103.553 103.033 103.115 102.563 102.695 102.223 102.326 102.055 108.533 107.857 108.642 107.708 108.139 107.66 107.75 107.469 107.46 107.211 107.209 106.92 106.98 106.623 106.752 106.357 106.505 106.153 106.232 106.003 105.233 104.852 105.77 105.016 105.576 105.283 105.487 105.378 105.487 105.409 105.514 105.404 105.553 105.389 105.585 105.393 105.593 105.441 105.568 105.539 104.918 104.533 105.5 104.691 105.223 104.977 105.126 105.069 105.144 105.111 105.194 105.14 105.261 105.172 105.328 105.225 105.381 105.316 105.414 105.446 102.417 102.101 103.177 102.402 103.058 102.91 103.15 103.188 103.328 103.388 103.516 103.557 103.699 103.716 103.869 103.879 104.021 104.06 104.15 104.265 100.357 99.932 101.049 100.275 101.085 100.876 101.261 101.299 101.509 101.615 101.774 101.877 102.026 102.113 102.254 102.336 102.456 102.557 102.63 102.781 99.1448 98.5181 99.4979 98.7888 99.7244 99.224 99.8105 99.7124 99.9705 100.059 100.213 100.332 100.464 100.577 100.695 100.806 100.899 101.021 101.074 101.218 99.0846 98.261 99.0436 98.2963 99.4265 98.5602 99.3156 99.044 99.2958 99.3285 99.4373 99.5286 99.6187 99.7159 99.7981 99.8992 99.9642 100.071 100.109 100.216 98.3717 97.544 98.4959 97.506 98.889 97.928 98.6808 98.4277 98.6412 98.6878 98.7808 98.878 98.9676 99.0747 99.1652 99.2811 99.361 99.483 99.5366 99.6512 95.0528 94.7642 96.039 94.9721 96.4267 95.789 96.4055 96.3985 96.6209 96.79 96.9614 97.1502 97.332 97.5306 97.7164 97.9275 98.0991 98.3233 98.4425 98.6742 87.7284 88.1312 89.7321 88.888 90.3371 90.2013 90.8256 91.1696 91.5602 91.9662 92.3564 92.7611 93.1625 93.576 93.9757 94.403 94.7694 95.2227 95.4739 95.9795 75.2517 75.9246 78.1668 77.3473 79.1919 79.3525 80.2659 80.9542 81.6591 82.3942 83.1174 83.8516 84.5852 85.3293 86.0526 86.8098 87.4715 88.2686 88.7334 89.6663 59.0684 59.4209 62.4994 61.176 63.7874 63.7505 65.089 65.9094 66.8667 67.8383 68.8099 69.8014 70.7963 71.806 72.79 73.8131 74.7163 75.7901 76.4546 77.693 41.5633 40.8837 44.5673 42.6039 46.0965 45.5536 47.4896 48.3075 49.5698 50.763 51.9906 53.2433 54.4963 55.7594 56.979 58.2125 59.2942 60.5054 61.2417 62.5246 27.0383 24.7506 28.268 25.1224 28.8466 27.4346 29.4866 29.9661 31.3355 32.5912 34.0617 35.6498 37.343 39.1484 40.9843 42.9036 44.6834 46.491 47.5741 49.3154 28.6246 24.9312 27.9344 22.1639 23.7743 20.1487 19.6372 17.7123 16.7215 15.6682 15.0072 14.5925 14.4578 14.5958 14.8965 15.6439 16.7953 18.8117 20.7095 23.4201 17.4508 10.3669 18.546 11.5672 13.484 10.0981 8.76561 6.18636 3.92151 1.39028 -1.07864 -3.57161 -6.03655 -8.51206 -10.9439 -12.7015 -13.1931 -11.87 -10.6764 -8.19171 40.9447 17.6544 25.3976 13.7226 10.4255 3.21659 -2.29255 -8.08125 -13.1486 -17.6667 -21.4117 -24.3068 -26.2662 -27.2281 -27.1437 -25.9088 -23.4591 -20.8833 -19.1591 -16.6016 740.02 656.594 607.152 550.458 501.097 453.447 409.173 367.375 328.088 291.041 256.095 223.061 191.711 161.962 133.902 106.905 81.922 63.3687 40.4061 2.50846 740.39 656.963 607.522 550.826 501.464 453.813 409.539 367.739 328.451 291.402 256.454 223.419 192.067 162.318 134.259 107.264 82.2857 63.7322 40.7662 2.86467 41.3145 18.0211 25.7641 14.0871 10.7894 3.5792 -1.93061 -7.72017 -12.788 -17.3065 -21.0516 -23.9465 -25.9052 -26.8659 -26.78 -25.5432 -23.0917 -20.5149 -18.7963 -16.248 17.7624 10.6715 18.8468 11.8617 13.7735 10.3813 9.0427 6.4566 4.1845 1.64545 -0.831894 -3.33396 -5.80858 -8.29421 -10.7361 -12.5007 -12.9957 -11.6797 -10.4922 -8.01592 28.823 25.1243 28.1239 22.3472 23.952 20.3199 19.8015 17.8693 16.8708 15.8094 15.14 14.7168 14.5733 14.7027 14.9952 15.736 16.8853 18.9042 20.805 23.5162 27.2248 24.9374 28.4555 25.3096 29.0344 27.6225 29.6755 30.1554 31.5262 32.783 34.2553 35.8455 37.5412 39.3496 41.1889 43.1121 44.8955 46.7074 47.7917 49.5376 41.7752 41.0965 44.7808 42.8178 46.3122 45.7687 47.7069 48.5245 49.788 50.9818 52.2101 53.4635 54.7173 55.9811 57.2015 58.436 59.5181 60.7307 61.4669 62.7504 59.2826 59.6356 62.715 61.391 64.0048 63.9662 65.3066 66.1267 67.0849 68.0571 69.0295 70.022 71.018 72.0289 73.0143 74.0389 74.9433 76.019 76.6847 77.9236 75.4872 76.162 78.4065 77.5876 79.4353 79.5964 80.5121 81.2019 81.9087 82.6459 83.371 84.1074 84.8431 85.5895 86.315 87.0747 87.7385 88.5384 89.0047 89.9415 87.9968 88.4014 90.0054 89.1635 90.6152 90.4818 91.1079 91.4546 91.8474 92.2559 92.6485 93.0556 93.4593 93.8755 94.2776 94.7078 95.0765 95.5331 95.7862 96.2953 95.3541 95.0676 96.3463 95.2798 96.7363 96.1015 96.7178 96.7143 96.9375 97.109 97.282 97.4727 97.6561 97.8566 98.044 98.2572 98.4302 98.6569 98.7772 99.0113 98.6926 97.868 98.8228 97.8297 99.2167 98.2587 99.0088 98.7605 98.9733 99.0223 99.1161 99.2149 99.3055 99.4142 99.5056 99.6232 99.7038 99.8277 99.8819 99.9981 99.423 98.6004 99.3867 98.6344 99.7689 98.9061 99.6576 99.3909 99.6413 99.6762 99.7853 99.8778 99.9685 100.067 100.149 100.252 100.317 100.425 100.463 100.571 99.4952 98.8688 99.8525 99.1396 100.077 99.5796 100.163 100.068 100.325 100.415 100.57 100.689 100.821 100.935 101.053 101.165 101.258 101.38 101.434 101.579 100.722 100.297 101.416 100.641 101.45 101.242 101.626 101.664 101.873 101.979 102.138 102.241 102.39 102.476 102.618 102.7 102.819 102.921 102.993 103.144 102.782 102.466 103.543 102.767 103.423 103.273 103.513 103.551 103.69 103.749 103.877 103.919 104.06 104.076 104.229 104.239 104.38 104.42 104.51 104.625 105.283 104.895 105.865 105.053 105.586 105.338 105.487 105.43 105.504 105.47 105.554 105.499 105.619 105.53 105.685 105.583 105.738 105.674 105.771 105.803 105.583 105.2 106.12 105.363 105.926 105.631 105.836 105.726 105.836 105.757 105.863 105.753 105.901 105.738 105.933 105.742 105.94 105.79 105.917 105.887 108.891 108.211 108.999 108.062 108.495 108.014 108.105 107.822 107.814 107.564 107.562 107.273 107.332 106.976 107.104 106.709 106.855 106.505 106.583 106.353 103.883 103.753 104.574 104.156 104.882 104.55 104.912 104.571 104.682 104.326 104.314 103.88 103.886 103.366 103.447 102.897 103.028 102.557 102.66 102.389 122.963 120.815 120.648 118.458 117.597 115.394 114.08 112.457 111.292 109.77 108.851 107.621 107.097 106.036 105.877 104.952 105.021 104.301 104.385 103.992 ) ; boundaryField { outletWall { type fixedValue; value uniform 0; } fineWalls { type zeroGradient; } fineFrontAndBack { type zeroGradient; } fineplugLeft { type cyclicAMI; value nonuniform List<scalar> 20 ( 91.2101 91.3286 91.9185 92.6002 92.7904 93.7596 93.9841 95.0139 95.4737 96.5892 97.3156 98.557 99.7866 106.079 101.673 102.283 102.222 103.804 102.887 102.269 ) ; } fineplugRight { type cyclicAMI; value nonuniform List<scalar> 20 ( 91.5086 91.6273 92.2169 92.9048 93.0975 94.0701 94.2954 95.3265 95.7851 96.9026 97.6288 98.873 100.109 106.445 102.015 102.626 102.557 104.142 103.215 102.597 ) ; } inletOutletLeft { type cyclicAMI; value nonuniform List<scalar> 20 ( 91.2101 91.3286 91.9185 92.6002 92.7904 93.7596 93.9841 95.0139 95.4737 96.5892 97.3156 98.557 99.7866 106.079 101.673 102.283 102.222 103.804 102.887 102.269 ) ; } inletLeft { type zeroGradient; } inletWallsLeft { type zeroGradient; } inletFacesLeft { type zeroGradient; } inletOutletRight { type cyclicAMI; value nonuniform List<scalar> 20 ( 91.5086 91.6273 92.2169 92.9048 93.0975 94.0701 94.2954 95.3265 95.7851 96.9026 97.6288 98.873 100.109 106.445 102.015 102.626 102.557 104.142 103.215 102.597 ) ; } inletRight { type zeroGradient; } inletWallsRight { type zeroGradient; } inletFacesRight { type zeroGradient; } } // ************************************************************************* //
[ "brent.shambaugh@gmail.com" ]
brent.shambaugh@gmail.com
279a20ca9f0357528dec4aff3a5f0ce1e2c8fd19
e6e28d03510d4a0d38eb66dc52959bacef915068
/server/membermanage.h
97a09da8cacbc4ecec7f9e5179b6a74ec68b1f5d
[]
no_license
Sl-lerlyn/Exams
a031aafd6cb009e422358bd6c66abdc525748a08
31530ba5cf93dd3a16d0f125b7eee2265038a18f
refs/heads/master
2023-01-30T07:13:36.836762
2020-12-02T05:58:45
2020-12-02T05:58:45
226,640,705
0
1
null
null
null
null
UTF-8
C++
false
false
2,674
h
#ifndef MEMBERMANAGEUI_H #define MEMBERMANAGEUI_H #include <QWidget> #include <QFileDialog> #include <QFile> #include <QDir> #include "ui_membermanage.h" #include "data.h" class MemberManageUI : public QWidget,public Ui::MemberManageUI { Q_OBJECT public: explicit MemberManageUI(QWidget *parent = 0); ~MemberManageUI(); signals: void addStudent(Student *); void addTeacher(User *); void addManager(User *); void addType(int, QString); void deleteUserId(QString); void deleteManagerId(int); void deleteType(int); void showStudent(Student *); void updateStudent(Student *); void showTeacher(User *); void showTypeList(QList<QString>); void updateTeacher(User *); void showManager(User *); void updateManager(User *); void showType(int, QString); void updateType(int, QString); void exportStudent(QList<Student *>, QString); void exportTeacher(QList<User *>, QString); void exportManager(QList<User *>, QString); void exportType(QMap<int, QString>, QString); void importStudent(QString); void importTeacher(QString); void importManager(QString); void importType(QString); private slots: void on_pushButton_add_user_clicked(); void on_pushButton_delete_user_clicked(); // void on_pushButton_search_clicked(); // void on_pushButton_all_clicked(); void showManager(QList<User *>); void showStudent(QList<Student *>); void showTeacher(QList<User *>); void showSubject(QList<QString>); void showType(QMap<int, QString>); void textClear(); void studentDialog(QTableWidgetItem *); void teacherDialog(QTableWidgetItem *); void managerDialog(QTableWidgetItem *); void typeDialog(QTableWidgetItem *); void updateStudentList(QList<Student *>); void updateTeacherList(QList<User *>); void updateManagerList(QList<User *>); void updateTypeList(QMap<int, QString>); void on_pushButton_import_clicked(); void on_pushButton_export_clicked(); void on_search_student_clicked(); void on_all_student_clicked(); void on_search_teacher_clicked(); void on_all_teacher_clicked(); void on_search_manager_clicked(); void on_all_manager_clicked(); private: QList<Student *> studentList; QList<User *> teacherList; QList<User *> managerList; QList<Student *> studentSearchList; QList<User *> teacherSearchList; QList<User *> managerSearchList; QMap<int, QString> typeList; QMap<int, QString> typeSearchList; QButtonGroup studentButton; QButtonGroup teacherButton; QButtonGroup managerButton; }; #endif // MEMBERMANAGEUI_H
[ "alan19920626@gmail.com" ]
alan19920626@gmail.com
6306f752e39519f392ddcce4dbc643219008cef2
3bd9310fa97864b824f1779e8e45979099ec917e
/vish-h5-plugin/VScriptUpdates.hpp
10123a85ed40044d691ad2886456cedc17c61dc3
[]
no_license
dimstamat/hdf5-rbdb-vol
04356f24e4d670ac91f25f1f291f175a0f9c36e2
47c6d4ec478cbaba3abc2b51cd102f39be683ab2
refs/heads/master
2021-09-10T05:25:02.190071
2018-03-21T04:48:56
2018-03-21T04:48:56
126,115,055
0
0
null
null
null
null
UTF-8
C++
false
false
1,273
hpp
/* * VScriptUpdates.hpp * * Contains functions for updating the state of the Vish network. * Was taken from the Vish ASCII loader and adopted to work with the HDF5 loader. * * Created on: Oct 31, 2016 * Author: dimos */ #ifndef FISH_V5_VSCRIPTUPDATES_HPP_ #define FISH_V5_VSCRIPTUPDATES_HPP_ using namespace std; namespace Wizt { void setupObject(string& objName); void addConnection(H5Script::MemberID& fromMember, H5Script::MemberID& toMember); void addObjectCreator(string& objectCreator, string& objName); void deleteObject(string& objname); void addParamLocal(H5Script::MemberID& mID, RefPtr<VValueBase> value, H5Script& h5script); void addParamSimple(H5Script::MemberID& mID, RefPtr<VValueBase> value, H5Script& h5script); void addParamContext(string& objName, string& paramName, string& contextName, RefPtr<VValueBase> value, H5Script& h5script); void addParamProperty(H5Script::MemberID& mID, string& parname, string& propertyType, string& propname, RefPtr<VValueBase> value); void addStatementToScriptValue(H5Script& h5script); void addScriptValueToDiscardvalue(H5Script& h5script); void addParam(string& objName, string& param, RefPtr<VValueBase> value, bool isLocal, H5Script& h5script); } #endif /* FISH_V5_VSCRIPTUPDATES_HPP_ */
[ "dimstamat@gmail.com" ]
dimstamat@gmail.com
d4f88ebdb35fc228cc0ab30143fcc81824e63aff
90ce76e9b9312afe7a65fc513e698378d4294d0f
/SRM291/FarFromPrimes_Kaiyang.cpp
71071f2abcb9e9e2912a8498664fda3e86757798
[]
no_license
FighterKing/TopCoder
248946350aa535489d7f6d1eb1936aaf26a0eadc
d3420136cb8d2bbf6a0d0433f8c5736badac8868
refs/heads/master
2016-09-05T22:53:13.869535
2014-12-29T06:59:33
2014-12-29T06:59:33
19,060,759
0
1
null
null
null
null
UTF-8
C++
false
false
3,179
cpp
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class FarFromPrimes { bool isPrime(int n) { if (n == 2) return true; if (n % 2 == 0) return false; for (int i = 3; i <= sqrt(n); i += 2) if (n % i == 0) return false; return true; } bool check(int n) { for (int i = n - 10; i <= n + 10; ++i) { if (isPrime(i)) return false; } return true; } public: int count(int A, int B) { int sum = 0; for (int i = A; i <= B; ++i) { if (check(i)) ++sum; } return sum; } }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof bool KawigiEdit_RunTest(int testNum, int p0, int p1, bool hasAnswer, int p2) { cout << "Test " << testNum << ": [" << p0 << "," << p1; cout << "]" << endl; FarFromPrimes *obj; int answer; obj = new FarFromPrimes(); clock_t startTime = clock(); answer = obj->count(p0, p1); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << p2 << endl; } cout << "Your answer:" << endl; cout << "\t" << answer << endl; if (hasAnswer) { res = answer == p2; } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; int p0; int p1; int p2; { // ----- test 0 ----- p0 = 3328; p1 = 4100; p2 = 4; all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 1 ----- p0 = 10; p1 = 1000; p2 = 0; all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 2 ----- p0 = 19240; p1 = 19710; p2 = 53; all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 3 ----- p0 = 23659; p1 = 24065; p2 = 20; all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 4 ----- p0 = 97001; p1 = 97691; p2 = 89; all_right = KawigiEdit_RunTest(4, p0, p1, true, p2) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
[ "kevinlui598@gmail.com" ]
kevinlui598@gmail.com
cc0b280814eac91da8aaf3464b7dff1159b16b94
8ae887afac7903c6dd3b0ddfec69a100524510d5
/api/api_pool.cpp
a5722f0952f2d7a52f3e45160366a6720cf582d9
[]
no_license
liuyinqi2013/relay_proxy
5787350fe9ece9bb36e42767e8cc86a4e754a9e1
3abb9ad23e19d5f277b901b720dced6759ccafac
refs/heads/master
2020-04-13T13:35:08.474978
2018-12-27T02:17:32
2018-12-27T02:17:32
163,235,191
0
0
null
null
null
null
GB18030
C++
false
false
12,340
cpp
#include "api_pool.h" #include "middle_api.h" #include "relay_api.h" #include "trpc_sys_exception.h" #include "hasite_conf.h" #include "log.h" CApiPool::CApiPool(CHaSiteConf & hasite_conf, CSystemConf& sys_conf, const std::string & server_name, const int conn_num, const int max_conn_num, const int time_out) : _server_name(server_name), _need_switch(false), _conn_num(conn_num), _max_conn_num(max_conn_num), _hasite_conf(hasite_conf), _sys_conf(sys_conf), _time_out(time_out), _pool_size(0), _switch_factor(0), _switch_state(EM_SWITCH_PRIOR) { _api_pool = &_pool[_switch_factor%2]; } CApiPool::~CApiPool() { } void CApiPool::set_switch_on() { CAutoWLock l(_mutex); _need_switch = true; } void CApiPool::set_switch_off() { CAutoWLock l(_mutex); _need_switch = false; } CApiBase * CApiPool::get(const char * user, const char * passwd) { // 先加写锁 CAutoWLock l(_mutex); return _get(user, passwd); } void CApiPool::release(CApiBase * api, bool force_close) { // 先加写锁 CAutoWLock l(_mutex); return _release(api, force_close); } /* CApiBase * CApiPool::_get(const char * user, const char * passwd) { if (_switch_state == EM_SWITCH_ONGOING) { trpc_debug_log("EM_SWITCH_ONGOING, clear some apis"); assert(_switch_factor > 0); bool switch_complete = true; std::vector<CApiBase *> & pool = _pool[(_switch_factor-1)%2]; trpc_debug_log("old pool index:=%d, old pool size=%lu", (_switch_factor-1)%2, pool.size()); for(std::vector<CApiBase *>::iterator it = pool.begin(); it != pool.end(); ++it) { if ((*it) != NULL && (*it)->is_free()) { trpc_debug_log("delete one invalid free api"); delete (*it); *it = NULL; } } for(std::vector<CApiBase *>::iterator it = pool.begin(); it != pool.end(); ++it) { if ((*it) != NULL && !(*it)->is_free()) { trpc_debug_log("find a still used api"); switch_complete = false; break; } } if (switch_complete) { trpc_debug_log("all apis have been cleared, EM_SWITCH_FINISHED"); pool.clear(); _switch_state = EM_SWITCH_FINISHED; } } if (!_need_switch) { // 遍历,查找空闲 //for (std::vector<CApiBase *>::iterator it = _api_pool.begin(); it != _api_pool.end(); ++it) for (std::vector<CApiBase *>::iterator it = _api_pool->begin(); it != _api_pool->end(); ++it) { if ((*it)->is_free()) { (*it)->set_used(); //trpc_debug_log("FIND GET_API_INDEX:%d, IDC:%s\n", (*it)->index(), (*it)->idc()); return (*it); } } } else { std::string next_idc = _sys_conf.next_idc(_cur_idc.c_str()); trpc_debug_log("API_POOL:need switch from %s to next idc:%s", _cur_idc.c_str(), next_idc.c_str()); if (next_idc == CHaSiteConf::default_idc) { trpc_debug_log("already reach the last IDC, do not switch"); trpc_write_statslog("already reach the last IDC, do not switch\n"); _need_switch = false; for (std::vector<CApiBase *>::iterator it = _api_pool->begin(); it != _api_pool->end(); ++it) { if ((*it)->is_free()) { (*it)->set_used(); //trpc_debug_log("FIND GET_API_INDEX:%d, IDC:%s\n", (*it)->index(), (*it)->idc()); return (*it); } } } else { trpc_write_statslog("begin to switch from %s to next idc:%s\n", _cur_idc.c_str(), next_idc.c_str()); if (_switch_state == EM_SWITCH_ONGOING) { trpc_debug_log("switching IDC has not finished, please wait!"); trpc_write_statslog("switching IDC has not finished, please wait!\n"); THROW(CServerException, ERR_SERVER_BUSY, "Last switch has not finished, please wait!"); } else if (_switch_state == EM_SWITCH_PRIOR || _switch_state == EM_SWITCH_FINISHED) { _switch_state = EM_SWITCH_ONGOING; trpc_write_statslog("SWITCH_ONGOING\n"); } int index = (++_switch_factor) % 2; _api_pool = &_pool[index]; _pool_size = _api_pool->size(); trpc_debug_log("new pool index == %d, new pool size == %d", index, _pool_size); std::string last_idc = _cur_idc; _cur_idc = next_idc; _need_switch = false; trpc_debug_log("switch completed, current IDC=%s\n", _cur_idc.c_str()); trpc_write_statslog("switch completed, current IDC=%s\n", _cur_idc.c_str()); } } trpc_debug_log("_need_switch=%d, create an api from :%s\n", _need_switch, _cur_idc.c_str()); // 检查,如果没有超过最大的值,创建一个新的API,并加入_api_pool中 if (_pool_size < _max_conn_num) { return _add_api(user, passwd); } else { // 无可用节点 THROW(CServerException, ERR_SERVER_BUSY, "server_site: %s no free conn max: %d, now: %d", _server_name.c_str(), _max_conn_num, _pool_size); } // never go here return NULL; } */ CApiBase * CApiPool::_get(const char * user, const char * passwd) { if (_switch_state == EM_SWITCH_ONGOING) { trpc_debug_log("EM_SWITCH_ONGOING, clear some apis"); assert(_switch_factor > 0); bool switch_complete = true; std::vector<CApiBase *> & pool = _pool[(_switch_factor-1)%2]; trpc_debug_log("old pool index:=%d, old pool size=%lu", (_switch_factor-1)%2, pool.size()); for(std::vector<CApiBase *>::iterator it = pool.begin(); it != pool.end(); ++it) { if ((*it) != NULL && (*it)->is_free()) { trpc_debug_log("delete one invalid free api"); delete (*it); *it = NULL; } } for(std::vector<CApiBase *>::iterator it = pool.begin(); it != pool.end(); ++it) { if ((*it) != NULL && !(*it)->is_free()) { trpc_debug_log("find a still used api"); switch_complete = false; break; } } if (switch_complete) { trpc_debug_log("all apis have been cleared, EM_SWITCH_FINISHED"); pool.clear(); _switch_state = EM_SWITCH_FINISHED; } } if (!_need_switch) { // 遍历,查找空闲 //for (std::vector<CApiBase *>::iterator it = _api_pool.begin(); it != _api_pool.end(); ++it) for (std::vector<CApiBase *>::iterator it = _api_pool->begin(); it != _api_pool->end(); ++it) { if ((*it)->is_free()) { (*it)->set_used(); //trpc_debug_log("FIND GET_API_INDEX:%d, IDC:%s\n", (*it)->index(), (*it)->idc()); return (*it); } } } else { std::string next_idc = _hasite_conf.get_next_idc(_server_name.c_str()); if (next_idc == "") { trpc_debug_log("already reach the last IDC, do not switch"); trpc_write_statslog("already reach the last IDC, do not switch\n"); _need_switch = false; for (std::vector<CApiBase *>::iterator it = _api_pool->begin(); it != _api_pool->end(); ++it) { if ((*it)->is_free()) { (*it)->set_used(); //trpc_debug_log("FIND GET_API_INDEX:%d, IDC:%s\n", (*it)->index(), (*it)->idc()); return (*it); } } } else { if (_switch_state == EM_SWITCH_ONGOING) { trpc_debug_log("switching IDC has not finished, please wait!"); trpc_write_statslog("switching IDC has not finished, please wait!\n"); THROW(CServerException, ERR_SERVER_BUSY, "Last switch has not finished, please wait!"); } else if (_switch_state == EM_SWITCH_PRIOR || _switch_state == EM_SWITCH_FINISHED) { _switch_state = EM_SWITCH_ONGOING; trpc_write_statslog("SWITCH_ONGOING\n"); } int index = (++_switch_factor) % 2; _api_pool = &_pool[index]; _pool_size = _api_pool->size(); trpc_debug_log("new pool index == %d, new pool size == %d", index, _pool_size); _hasite_conf.set_current_idc(_server_name.c_str()); _need_switch = false; trpc_debug_log("switch completed, current IDC=%s\n", next_idc.c_str()); trpc_write_statslog("switch completed, current IDC=%s\n", next_idc.c_str()); /* if (last_idc != _hasite_conf.default_idc) { _hasite_conf.set_invalid_forever(last_idc.c_str(), _server_name.c_str(), _ip_addr.c_str(), _port); } */ } } // 检查,如果没有超过最大的值,创建一个新的API,并加入_api_pool中 if (_pool_size < _max_conn_num) { return _add_api(user, passwd); } else { // 无可用节点 THROW(CServerException, ERR_SERVER_BUSY, "server_site: %s no free conn max: %d, now: %d", _server_name.c_str(), _max_conn_num, _pool_size); } // never go here return NULL; } CApiBase * CApiPool::_add_api(const char * user, const char * passwd) { // 获取ip和端口 std::string ip; int port; int protocol; CApiBase * api = NULL; std::string idc = _need_switch ? _hasite_conf.get_next_idc(_server_name.c_str()) : _hasite_conf.get_current_idc(_server_name.c_str()); _hasite_conf.get(idc.c_str(), _server_name.c_str(), ip, port, protocol); _ip_addr = ip; _port = port; trpc_debug_log("get ip success, idc:%s, server_name: %s, ip: %s, port: %d, protocol: %d", idc.c_str(), _server_name.c_str(), ip.c_str(), port, protocol); api = _create_api(idc, ip, port, protocol, user, passwd); if (api == NULL) { THROW(CServerException, ERR_SYS_UNKNOWN, "create api error idc:%s, ip: %s, port: %d, protocol: %d", idc.c_str(), ip.c_str(), port, protocol); } // 加入到池中 api->set_used(); _api_pool->push_back(api); ++_pool_size; // test assert if (_pool_size != (int)_api_pool->size()) { THROW(CTrpcException, ERR_SYS_UNKNOWN, "_poolsize: %d != api_pool: %d", _pool_size, (int)_api_pool->size()); } //trpc_debug_log("GET_API_INDEX:%d, IDC:%s\n", api->index(), api->idc()); return api; } void CApiPool::_release(CApiBase * api, bool force_close) { bool auto_close = false; // 如果index大于必须长存的链接数量,自动关闭 if (api->index() >= _conn_num) { auto_close = true; } else { auto_close = force_close; } //(*_api_pool)[api->index()]->set_free(auto_close); api->set_free(auto_close); } CApiBase * CApiPool::_create_api(const std::string& idc, const std::string& ip, int port, int protocol, const char *user, const char *passwd) { CApiBase * api = NULL; if (protocol == EM_ST_RELAY) { api = new CRelayApi(idc.c_str(), ip.c_str(), port, _pool_size, _time_out); } else if (protocol == EM_ST_MIDDLE) { api = new CMiddleApi(idc.c_str(), ip.c_str(), port, user, passwd, _pool_size, _time_out); } else { THROW(CConfigException, ERR_CONF, "idc:%s, server_name: %s, protocol error: %d", idc.c_str(), _server_name.c_str(), protocol); } return api; }
[ "liuyinqi2013@163.com" ]
liuyinqi2013@163.com
172450a08af092db1162c1bb250f9edcacfeb068
a62342d6359a88b0aee911e549a4973fa38de9ea
/0.6.0.3/External/SDK/UI_BuildingMenu_classes.h
f3bf4ce17aefbc9d61e889acc3e40090ca83be89
[]
no_license
zanzo420/Medieval-Dynasty-SDK
d020ad634328ee8ee612ba4bd7e36b36dab740ce
d720e49ae1505e087790b2743506921afb28fc18
refs/heads/main
2023-06-20T03:00:17.986041
2021-07-15T04:51:34
2021-07-15T04:51:34
386,165,085
0
0
null
null
null
null
UTF-8
C++
false
false
35,223
h
#pragma once // Name: Medieval Dynasty, Version: 0.6.0.3 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass UI_BuildingMenu.UI_BuildingMenu_C // 0x0478 (FullSize[0x0710] - InheritedSize[0x0298]) class UUI_BuildingMenu_C : public UUI_MasterRadialMenu_C { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0298(0x0008) (ZeroConstructor, Transient, DuplicateTransient, UObjectWrapper) class UHorizontalBox* AnimalBox; // 0x02A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* Animals; // 0x02A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Animals_Eighth; // 0x02B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Animals_Fifth; // 0x02B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Animals_First; // 0x02C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Animals_Fourth; // 0x02C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Animals_Second; // 0x02D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Animals_Seventh; // 0x02D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Animals_Sixth; // 0x02E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Animals_Third; // 0x02E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Building_Fifth; // 0x02F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Building_First; // 0x02F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Building_Fourth; // 0x0300(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Building_Second; // 0x0308(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Building_Third; // 0x0310(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* BuildTypeDescription; // 0x0318(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* BuildTypeName; // 0x0320(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* BuildTypeName_4; // 0x0328(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* CenterImage_2; // 0x0330(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* Crafting; // 0x0338(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Eighth; // 0x0340(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Eleventh; // 0x0348(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Fifth; // 0x0350(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_First; // 0x0358(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Fourth; // 0x0360(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Nineth; // 0x0368(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Second; // 0x0370(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Seventh; // 0x0378(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Sixth; // 0x0380(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Tenth; // 0x0388(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Third; // 0x0390(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Thirteenth; // 0x0398(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crafting_Twelfth; // 0x03A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* Crops; // 0x03A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crops_Fifth; // 0x03B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crops_First; // 0x03B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crops_Fourth; // 0x03C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crops_Second; // 0x03C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crops_Sixth; // 0x03D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Crops_Third; // 0x03D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* Extraction; // 0x03E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UBorder* FirstItem; // 0x03E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UBorder* FourthItem; // 0x03F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* Houses; // 0x03F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Houses_First; // 0x0400(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Houses_Fourth; // 0x0408(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Houses_Second; // 0x0410(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Houses_Third; // 0x0418(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* Hunting; // 0x0420(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Image; // 0x0428(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Image_11; // 0x0430(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Image_12; // 0x0438(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Image_149; // 0x0440(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item1Cost; // 0x0448(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Item1Img; // 0x0450(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item1Inventory; // 0x0458(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item1Name; // 0x0460(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item2Cost; // 0x0468(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Item2Img; // 0x0470(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item2Inventory; // 0x0478(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item2Name; // 0x0480(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item3Cost; // 0x0488(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Item3Img; // 0x0490(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item3Inventory; // 0x0498(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item3Name; // 0x04A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item4Cost; // 0x04A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Item4Img; // 0x04B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item4Inventory; // 0x04B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Item4Name; // 0x04C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UHorizontalBox* LimitsBox; // 0x04C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Main_Eighth; // 0x04D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Main_Fifth; // 0x04D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Main_First; // 0x04E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Main_Fourth; // 0x04E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Main_Second; // 0x04F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Main_Seventh; // 0x04F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Main_Sixth; // 0x0500(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Main_Third; // 0x0508(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* MainCanvas; // 0x0510(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UVerticalBox* MainInformationBox; // 0x0518(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UBorder* NotEnoughItem; // 0x0520(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* NotEnoughResourcesText; // 0x0528(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UWidgetSwitcher* PageSwitcher; // 0x0530(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UVerticalBox* ResourcesBox; // 0x0538(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class USizeBox* ResourcesTextBox; // 0x0540(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UBorder* SecondItem; // 0x0548(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* Storages; // 0x0550(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Storages_Eighth; // 0x0558(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Storages_Fifth; // 0x0560(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Storages_First; // 0x0568(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Storages_Fourth; // 0x0570(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Storages_Second; // 0x0578(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Storages_Seventh; // 0x0580(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Storages_Sixth; // 0x0588(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Storages_Third; // 0x0590(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Survival_Fifth; // 0x0598(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Survival_First; // 0x05A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Survival_Fourth; // 0x05A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Survival_Second; // 0x05B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UUI_RadialSegment_C* Survival_Third; // 0x05B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UBorder* ThirdItem; // 0x05C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* txt_AnimalLimit; // 0x05C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* txt_WorkerLimit; // 0x05D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* WheelArrow; // 0x05D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UHorizontalBox* WorkerBox; // 0x05E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) struct FScriptMulticastDelegate SegmentChanged; // 0x05E8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable, BlueprintCallable) TArray<class UTextBlock*> ItemsNames; // 0x05F8(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UTextBlock*> ItemsCosts; // 0x0608(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UImage*> ItemsImages; // 0x0618(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UBorder*> ItemsArray; // 0x0628(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UUI_RadialSegment_C*> Main_SegmentsArray; // 0x0638(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UUI_RadialSegment_C*> Crops_SegmentsArray; // 0x0648(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UUI_RadialSegment_C*> Houses_SegmentsArray; // 0x0658(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UUI_RadialSegment_C*> Crafting_SegmentsArray; // 0x0668(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UUI_RadialSegment_C*> Storages_SegmentsArray; // 0x0678(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UUI_RadialSegment_C*> Extraction_SegmentsArray; // 0x0688(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UUI_RadialSegment_C*> Hunting_SegmentsArray; // 0x0698(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UUI_RadialSegment_C*> Animals_SegmentsArray; // 0x06A8(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) TArray<class UTextBlock*> ItemsInventory; // 0x06B8(0x0010) (Edit, BlueprintVisible, DisableEditOnInstance, ContainsInstancedReference) struct FLinearColor InventoryFalseColor; // 0x06C8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FLinearColor InventoryTrueColor; // 0x06D8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FLinearColor InventoryNoTechnologyColor; // 0x06E8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FLinearColor InventoryNoResourcesColor; // 0x06F8(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FVector2D SegmentSize; // 0x0708(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass UI_BuildingMenu.UI_BuildingMenu_C"); return ptr; } void CollapseItemsArray(); void GetFurnitureResources(class UUI_RadialSegment_C* Segment); void GetFenceResources(class UUI_RadialSegment_C* Segment); void GetBuildingResources(const struct FST_Building& ST_Building); void CheckBuildingsAvailability(); void CheckResources(int Index, int Selection); struct FSlateBrush Get_BuildTypeIcon_Brush_1(); struct FText Get_BuildTypeDescription_Text_1(); struct FText Get_BuildTypeName_Text_1(); void GetMouseOver(); void OnSpawned(); void ChangeInformationAboutSegment(); void NextPage(int SwitcherIndex); void PreviousPage(); void PreConstruct(bool IsDesignTime); void UpdateResourcesCheck(); void UpdateBuildingsTechnologyAvailability(); void RemoveMenu(); void ExecuteUbergraph_UI_BuildingMenu(int EntryPoint); void SegmentChanged__DelegateSignature(); void AfterRead(); void BeforeDelete(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
b14fe5014006e6e26f37748a0603f8bd4bed8a10
916b1ccbf41c689b65ffa2c054e26cf295ba2e27
/Loop_Back_AXI_Stream/hls/LoopBack_Productor_Consumer_Structure/loopback_PC.hpp
3193ca505baaebeb54eb6590a20ff7c24dd337f1
[]
no_license
cadriansalazarg/InterfacesZynq
bc6b25cc1f89cad0e805017f6783a401db0e21e8
b0d7f65840ee7db11dbded1c2497beeb83ccd408
refs/heads/master
2023-06-16T21:49:05.777950
2021-07-09T07:32:25
2021-07-09T07:32:25
183,521,914
0
1
null
null
null
null
UTF-8
C++
false
false
247
hpp
#include<hls_stream.h> #include<ap_int.h> #define SIZE 8 #define NUM_OF_TESTS 1000 typedef int data_type; struct AXISTREAM32{ int data; ap_int<1> tlast; }; void loopback(hls::stream<AXISTREAM32> &input, hls::stream<AXISTREAM32> &output);
[ "cadriansalazarg@gmail.com" ]
cadriansalazarg@gmail.com
8535ca28feb536285f1a5bb348faa0bd27249fcf
e837fbb65ae8c1e5e7ca74a845b4d81e3cd9fcc8
/Calendar/zzBak/CalendarTemplates/calBase.h
54aae3ef8a1aa27170aba4c506a9ffe0d3574f67
[ "MIT" ]
permissive
Vidyadhar-Mudkavi/gitApplications
213348dc2d819f48ef739429d08db0d9492bfceb
aca4087f733ac41bd18c558dce6f78b99646309b
refs/heads/master
2020-12-25T18:18:55.629596
2014-10-26T12:56:46
2014-10-26T12:56:46
25,765,788
1
0
null
null
null
null
UTF-8
C++
false
false
3,564
h
#ifndef _CALBASE_ #define _CALBASE_ /** *File: calBase.h *Description: this file declares class calBase. this class forms the base for all the calendars. it will hold the rd date and provide comparator operators which will apply to all the derived classes. *Version: 1.2 "@(#) calBase. header. ver. 1.2. Premalatha, Vidyadhar Mudkavi, CTFD, NAL." *Dependencies: *Authors: Premalatha, Vidyadhar Mudkavi, CTFD, NAL. *Date: */ // system includes // standard template // local includes // const declarations // function prototypes // forward declarations template <typename T> class tCalRataDie; // begin class declaration template <typename T> class tCalBase { public: // constructors tCalBase(long int fixed_date = 1) : pv_fixed(fixed_date) { /* empty */ } // default tCalBase(const tCalBase& tCal_base) : pv_fixed(tCal_base.pv_fixed) { /* empty */ } // assignment operator inline tCalBase& operator=(const tCalBase& tCal_base); // destructor ~tCalBase() { /* empty */ } // other functionality tCalRataDie<T> Fixed() const; inline long int operator-(const tCalBase& tCal_base) const; inline bool operator==(const tCalBase& tCal_base) const; inline bool operator> (const tCalBase& tCal_base) const; inline bool operator< (const tCalBase& tCal_base) const; inline bool operator>=(const tCalBase& tCal_base) const; inline bool operator<=(const tCalBase& tCal_base) const; inline bool operator!=(const tCalBase& tCal_base) const; protected: inline long int _Fixed() const; inline void _Fixed(long int fixed); private: long int pv_fixed; // the corresponding fixed date }; // include any inline code here template <typename T> inline tCalBase<T>& tCalBase<T>::operator=(const tCalBase& tCal_base) { pv_fixed = tCal_base.pv_fixed; return *this; } template <typename T> inline long int tCalBase<T>::_Fixed() const { return pv_fixed; } template <typename T> inline void tCalBase<T>::_Fixed(long int fixed) { pv_fixed = fixed; } template <typename T> inline long int tCalBase<T>::operator-(const tCalBase& tCal_base) const { return pv_fixed - tCal_base.pv_fixed; } template <typename T> inline bool tCalBase<T>::operator==(const tCalBase& tCal_base) const { return (pv_fixed == tCal_base.pv_fixed); } template <typename T> inline bool tCalBase<T>::operator> (const tCalBase& tCal_base) const { return (pv_fixed > tCal_base.pv_fixed); } template <typename T> inline bool tCalBase<T>::operator< (const tCalBase& tCal_base) const { return (pv_fixed < tCal_base.pv_fixed); } template <typename T> inline bool tCalBase<T>::operator>=(const tCalBase& tCal_base) const { return (pv_fixed >= tCal_base.pv_fixed); } template <typename T> inline bool tCalBase<T>::operator<=(const tCalBase& tCal_base) const { return (pv_fixed <= tCal_base.pv_fixed); } template <typename T> inline bool tCalBase<T>::operator!=(const tCalBase& tCal_base) const { return (pv_fixed != tCal_base.pv_fixed); } /** declare any typedef statements here (e.g.: typedef aVortex areVortices;) */ // // \\^// // o(!_!)o // __m__ o __m__ // #endif // _CALBASE_
[ "Vidyadhar.Mudkavi@gmail.com" ]
Vidyadhar.Mudkavi@gmail.com
4128d0d85268b4ef722805f080d3819c37635f85
2e9455464d582a4349dc9ff032fa3eaa402153a9
/非类型模版参数和技巧性知识/非类型模版参数和技巧性知识/main.cpp
696ad8d790e436e5e6035e9f7a783a08d21c3732
[]
no_license
csqnbhk/Templates
10a383f96556ccaf4619a40caebc7030ba73bc6a
8ad524e2c6305a42165c412cc3137700a41691e8
refs/heads/master
2021-07-11T20:27:59.627227
2017-10-13T11:07:07
2017-10-13T11:07:07
106,812,475
0
0
null
null
null
null
GB18030
C++
false
false
1,969
cpp
#include"test.h" int main() { //非类型的类模版参数 Stack<std::string> s_o; s_o.push("北京"); s_o.push("上海"); s_o.push("南京"); s_o.push("杭州"); s_o.push("深圳"); s_o.elems_info(); //非类型的函数模版参数 cout << "::addvalue<int,7>(8)=" << ::addvalue<int, 7>(8) << endl; /* 小结: 1.非类型模版参数是有限制的,通常而言,它们可以是长整数(包括枚举值)或者指向 外部链接对象的指针。 2.浮点数,类对象和内部链接对象(例如string)是不许作为非类型模版参数的。 */ /************************************************************************************************* 编程技巧 **************************************************************************************************/ //Base<float> base; //Derived<int> subclass; ///*subclass.foo();*/ /* 小结: 1.如果要访问依赖于模版参数的类型名称,应该在类型名称前面添加关键字 typename 。 2.嵌套类和成员函数也可以是模版。针对于元素可以进行隐式类型转化的2个栈,可以实现通用的 赋值操作。然而,在这种情况下,类型检查还是存在的。 3.赋值运算符的模版版本并没有取代缺省赋值运算符。 4.类模板也可以作为模版参数,称为模版的模版参数。 5.模版的模版参数必须精确地匹配,匹配是并不会考虑“模版的模版实参”的缺省模版实数。(例如std::queue的allocator) 6.通过显示调用缺省构造函数,可以确保模版的变量和成员函数都已经使用一个缺省值完成初始化,这种方法对内建类型的变量和成员也适用。 7.对于字符串,在实参推导过程中,当且仅当参数不是引用时,才会出现数组到指针(array_to_pointer)的类型转化(称为退化decay)。 */ return 0; }
[ "374405702.qq.com" ]
374405702.qq.com
c77ab4d06d1df32c42924f27c73fc18f12db92e6
ce75b3e54e9d2aa7ed47ea9d3cb1e4496b23f1c0
/AVLTree/AVL_tree.h
43ae5d230ef46804bff4f6b852f6fc60986d15ee
[]
no_license
zcxsythenew/AVLTree
2386fba3c2a4dc87a06197819a5f4146215b4fc3
8ab05d4a4526bf496e9eb26bcc173401f9129632
refs/heads/master
2020-04-14T20:47:24.632143
2019-01-04T12:48:54
2019-01-04T12:48:54
164,106,897
0
0
null
null
null
null
UTF-8
C++
false
false
8,813
h
#pragma once #include "Search_tree.h" #include "AVL_node.h" template <class Key, class Entry> class AVL_tree// : public Search_tree<Key, Entry> { public: AVL_tree() : root(nullptr), _size(0) { } bool empty() const noexcept { return root == nullptr; } void inorder(void(*visit)(Record<Key, Entry> &)) { recursive_inorder(visit, root); } void preorder(void(*visit)(Record<Key, Entry> &)) { recursive_preorder(visit, root); } void postorder(void(*visit)(Record<Key, Entry> &)) { recursive_postorder(visit, root); } int size() const noexcept { return _size; } void clear() { recursive_clear(root); } virtual ~AVL_tree() { clear(); } bool insert(const Record<Key, Entry> &data) { bool taller; return recursive_tree_insert(this->root, data, taller); } bool remove(const Record<Key, Entry> &data) { bool shorter; return recursive_tree_remove(root, data, shorter); } protected: AVL_node<Key, Entry> *root; int _size; AVL_node<Key, Entry> *recursive_tree_search(AVL_node<Key, Entry> *this_root, const Record<Key, Entry> &target) { while (this_root != nullptr) { if ((Key)(this_root->data) < (Key)(target)) { this_root = this_root->right; continue; } if ((Key)(target) < (Key)(this_root->data)) { this_root = this_root->left; continue; } return this_root; } return this_root; } bool remove_node(AVL_node<Key, Entry> *&this_root, bool &shorter) { if (this_root != nullptr) { if (this_root->left == nullptr && this_root->right == nullptr) { delete this_root; this_root = nullptr; shorter = true; } else if (this_root->left == nullptr) { delete this_root; this_root = this_root->right; shorter = true; } else if (this_root->right == nullptr) { delete this_root; this_root = this_root->left; shorter = true; } else { AVL_node<Key, Entry> *i; for (i = this_root->left; i->right != nullptr; i = i->right); this_root->data = i->data; AVL_remove(this_root->left, shorter); } if (shorter) { switch (this_root->balance) { case left_higher: this_root->balance = equal_height; break; case equal_height: this_root->balance = right_higher; shorter = false; break; case right_higher: if (this_root->right->balance == equal_height) { shorter = false; } right_balance(this_root); break; } } this->_size--; return true; } else { return false; } } Record<Key, Entry> AVL_remove(AVL_node<Key, Entry> *&this_root, bool &shorter) { if (this_root->right != nullptr) { Record<Key, Entry> ent = AVL_remove(this_root->right, shorter); if (shorter) { switch (this_root->balance) { case left_higher: left_balance(this_root); if (this_root->left->balance == equal_height) { shorter = false; } break; case equal_height: this_root->balance = left_higher; shorter = false; break; case right_higher: this_root->balance = equal_height; break; } } return ent; } else { shorter = true; Record<Key, Entry> ent = this_root->data; delete this_root; this_root = nullptr; return ent; } } void recursive_inorder(void(*visit)(Record<Key, Entry> &), AVL_node<Key, Entry> *this_root) { if (this_root != nullptr) { recursive_inorder(visit, this_root->left); (*visit)(this_root->data); recursive_inorder(visit, this_root->right); } } void recursive_preorder(void(*visit)(Record<Key, Entry> &), AVL_node<Key, Entry> *this_root) { if (this_root != nullptr) { (*visit)(this_root->data); recursive_preorder(visit, this_root->left); recursive_preorder(visit, this_root->right); } } void recursive_postorder(void(*visit)(Record<Key, Entry> &), AVL_node<Key, Entry> *this_root) { if (this_root != nullptr) { recursive_postorder(visit, this_root->left); recursive_postorder(visit, this_root->right); (*visit)(this_root->data); } } void recursive_clear(AVL_node<Key, Entry> *&this_root) { if (this_root != nullptr) { recursive_clear(this_root->left); recursive_clear(this_root->right); delete this_root; this_root = nullptr; } } bool recursive_tree_remove(AVL_node<Key, Entry> *&this_root, const Record<Key, Entry> &target, bool &shorter) { if (this_root == nullptr) { return false; } else { if ((Key)(this_root->data) < (Key)(target)) { bool result = recursive_tree_remove(this_root->right, target, shorter); if (result && shorter) { switch (this_root->balance) { case left_higher: if (this_root->left->balance == equal_height) { shorter = false; } left_balance(this_root); break; case equal_height: this_root->balance = left_higher; shorter = false; break; case right_higher: this_root->balance = equal_height; break; } } return result; } if ((Key)(target) < (Key)(this_root->data)) { bool result = recursive_tree_remove(this_root->left, target, shorter); if (result && shorter) { switch (this_root->balance) { case left_higher: this_root->balance = equal_height; break; case equal_height: this_root->balance = right_higher; shorter = false; break; case right_higher: if (this_root->right->balance == equal_height) { shorter = false; } right_balance(this_root); break; } } return result; } remove_node(this_root, shorter); return true; } } bool recursive_tree_insert(AVL_node<Key, Entry> *&this_root, const Record<Key, Entry> &data, bool &taller) { if (this_root == nullptr) { this_root = new AVL_node<Key, Entry>(); this_root->data = data; this_root->left = nullptr; this_root->right = nullptr; this_root->balance = equal_height; taller = true; this->_size++; return true; } if ((Key)(this_root->data) < (Key)(data)) { bool result = recursive_tree_insert(this_root->right, data, taller); if (result && taller) { switch (this_root->balance) { case left_higher: this_root->balance = equal_height; taller = false; break; case equal_height: this_root->balance = right_higher; break; case right_higher: right_balance(this_root); taller = false; break; } } return result; } if ((Key)(data) < (Key)(this_root->data)) { bool result = recursive_tree_insert(this_root->left, data, taller); if (result && taller) { switch (this_root->balance) { case left_higher: left_balance(this_root); taller = false; break; case equal_height: this_root->balance = left_higher; break; case right_higher: this_root->balance = equal_height; taller = false; break; } } return result; } taller = false; return false; } void right_balance(AVL_node<Key, Entry> *&this_root) { AVL_node<Key, Entry> *right_tree = this_root->right; AVL_node<Key, Entry> *root = this_root; if (this_root->right->balance != left_higher) { this_root->right = this_root->right->left; right_tree->left = this_root; this_root = right_tree; root->balance = equal_height; right_tree->balance = equal_height; } else { AVL_node<Key, Entry> *sub_tree = this_root->right->left; root->right = sub_tree->left; right_tree->left = sub_tree->right; sub_tree->left = this_root; sub_tree->right = right_tree; this_root = sub_tree; sub_tree->balance = equal_height; if (sub_tree->balance == left_higher) { root->balance = equal_height; right_tree->balance = right_higher; } else { root->balance = left_higher; right_tree->balance = equal_height; } } } void left_balance(AVL_node<Key, Entry> *&this_root) { AVL_node<Key, Entry> *left_tree = this_root->left; AVL_node<Key, Entry> *root = this_root; if (this_root->left->balance != right_higher) { this_root->left = this_root->left->right; left_tree->right = this_root; this_root = left_tree; root->balance = equal_height; left_tree->balance = equal_height; } else { AVL_node<Key, Entry> *sub_tree = this_root->left->right; root->left = sub_tree->right; left_tree->right = sub_tree->left; sub_tree->right = this_root; sub_tree->left = left_tree; this_root = sub_tree; sub_tree->balance = equal_height; if (sub_tree->balance == right_higher) { root->balance = equal_height; left_tree->balance = left_higher; } else { root->balance = right_higher; left_tree->balance = equal_height; } } } };
[ "zcxsythenew@outlook.com" ]
zcxsythenew@outlook.com
b8872e17884151bdbdaacf536b1086841d7d35e7
bf265796bb2bb429ecd3388fc63c86847cacbfd4
/files/diffs/RenderSVGInlineText.cpp
21f8a9f25bd4865d4a7baca98fb4363cda9debc5
[]
no_license
the-elves/TSE-MP1
5d13f7bb665997cdd0d98f4deb8fa37e7a469d32
04fabd388afff0cfb6fc392c12b3c20cead144e9
refs/heads/master
2023-04-19T09:34:05.649942
2021-05-08T09:20:42
2021-05-08T09:20:42
318,176,278
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
--- files/before/RenderSVGInlineText.cpp 2020-12-03 05:32:26.174348109 +0530 +++ files/after/RenderSVGInlineText.cpp 2020-12-03 05:32:27.246519530 +0530 @@ -89,7 +89,7 @@ return; } - if (diff != StyleDifferenceLayout) + if (!diff.needsFullLayout()) return; // The text metrics may be influenced by style changes.
[ "ajinkya@abc.in" ]
ajinkya@abc.in
595aaf836176bc9bb0d1f3439b303613b85bb3cf
306fd4270074eab419dfaaf2a5fbececb47b6a81
/src/SearchMarks.cc
90b42823078d28c3096cd9a8ff0d113ff9f27169
[]
no_license
CosmoQuestTeam/IncidenceAngleAnalysis
24cf9ed6e1db366d1644b9923719fe93591c1512
084a25c3cf03819e78b5086a85ebf627a7689f6f
refs/heads/master
2020-03-18T22:03:56.115604
2018-07-25T19:33:06
2018-07-25T19:33:06
135,322,247
1
0
null
2018-07-25T19:33:08
2018-05-29T16:12:33
C++
UTF-8
C++
false
false
19,904
cc
#include "SearchMarks.h" using namespace std; bool SearchMarks::EqualityComparison(vector <Marks> &marks, int index, string field, void *value) { /********************************/ /* Retrieve field column number */ /********************************/ if(field.compare("id") == 0) { return (marks[index].GetId() == *static_cast<int *>(value)); } if(field.compare("user_id") == 0) { return (marks[index].GetUser_id() == *static_cast<int *>(value)); } if(field.compare("image_id") == 0) { return (marks[index].GetImage_id() == *static_cast<int *>(value)); } if(field.compare("application_id") == 0) { return (marks[index].GetApplication_id() == *static_cast<int *>(value)); } if(field.compare("image_user_id") == 0) { return (marks[index].GetImage_user_id() == *static_cast<int *>(value)); } if(field.compare("machine_mark_id") == 0) { return (marks[index].GetMachine_mark_id() == *static_cast<int *>(value)); } if(field.compare("shared_mark_id") == 0) { return (marks[index].GetShared_mark_id() == *static_cast<int *>(value)); } if(field.compare("x") == 0) { return (marks[index].GetX() == *static_cast<double *>(value)); } if(field.compare("y") == 0) { return (marks[index].GetY() == *static_cast<double *>(value)); } if(field.compare("diameter") == 0) { return (marks[index].GetDiameter() == *static_cast<double *>(value)); } if(field.compare("submit_time") == 0) { return (marks[index].GetSubmit_time() == *static_cast<int *>(value)); } if(field.compare("confirmed") == 0) { return (marks[index].GetConfirmed() == *static_cast<int *>(value)); } if(field.compare("score") == 0) { return (marks[index].GetScore() == *static_cast<double *>(value)); } if(field.compare("type") == 0) { return (marks[index].GetType().compare(*static_cast<string *>(value)) == 0); } if(field.compare("sub_type") == 0) { return (marks[index].GetSub_type().compare(*static_cast<string *>(value)) == 0); } if(field.compare("details") == 0) { return (marks[index].GetDetails().compare(*static_cast<string *>(value)) == 0); } if(field.compare("created_at") == 0) { return (marks[index].GetCreated_at().compare(*static_cast<string *>(value)) == 0); } if(field.compare("updated_at") == 0) { return (marks[index].GetUpdated_at().compare(*static_cast<string *>(value)) == 0); } return false; } bool SearchMarks::GreaterThanComparison(vector <Marks> &marks, int index, string field, void *value) { /********************************/ /* Retrieve field column number */ /********************************/ if(field.compare("id") == 0) { return (marks[index].GetId() > *static_cast<int *>(value)); } if(field.compare("user_id") == 0) { return (marks[index].GetUser_id() > *static_cast<int *>(value)); } if(field.compare("image_id") == 0) { return (marks[index].GetImage_id() > *static_cast<int *>(value)); } if(field.compare("application_id") == 0) { return (marks[index].GetApplication_id() > *static_cast<int *>(value)); } if(field.compare("image_user_id") == 0) { return (marks[index].GetImage_user_id() > *static_cast<int *>(value)); } if(field.compare("machine_mark_id") == 0) { return (marks[index].GetMachine_mark_id() > *static_cast<int *>(value)); } if(field.compare("shared_mark_id") == 0) { return (marks[index].GetShared_mark_id() > *static_cast<int *>(value)); } if(field.compare("x") == 0) { return (marks[index].GetX() > *static_cast<double *>(value)); } if(field.compare("y") == 0) { return (marks[index].GetY() > *static_cast<double *>(value)); } if(field.compare("diameter") == 0) { return (marks[index].GetDiameter() > *static_cast<double *>(value)); } if(field.compare("submit_time") == 0) { return (marks[index].GetSubmit_time() > *static_cast<int *>(value)); } if(field.compare("confirmed") == 0) { return (marks[index].GetConfirmed() > *static_cast<int *>(value)); } if(field.compare("score") == 0) { return (marks[index].GetScore() > *static_cast<double *>(value)); } if(field.compare("type") == 0) { return (marks[index].GetType() > *static_cast<string *>(value)); } if(field.compare("sub_type") == 0) { return (marks[index].GetSub_type() > *static_cast<string *>(value)); } if(field.compare("details") == 0) { return (marks[index].GetDetails() > *static_cast<string *>(value)); } if(field.compare("created_at") == 0) { return (marks[index].GetCreated_at() > *static_cast<string *>(value)); } if(field.compare("updated_at") == 0) { return (marks[index].GetUpdated_at() > *static_cast<string *>(value)); } return false; } bool SearchMarks::LessThanComparison(vector <Marks> &marks, int index, string field, void *value) { /********************************/ /* Retrieve field column number */ /********************************/ if(field.compare("id") == 0) { return (marks[index].GetId() < *static_cast<int *>(value)); } if(field.compare("user_id") == 0) { return (marks[index].GetUser_id() < *static_cast<int *>(value)); } if(field.compare("image_id") == 0) { return (marks[index].GetImage_id() < *static_cast<int *>(value)); } if(field.compare("application_id") == 0) { return (marks[index].GetApplication_id() < *static_cast<int *>(value)); } if(field.compare("image_user_id") == 0) { return (marks[index].GetImage_user_id() < *static_cast<int *>(value)); } if(field.compare("machine_mark_id") == 0) { return (marks[index].GetMachine_mark_id() < *static_cast<int *>(value)); } if(field.compare("shared_mark_id") == 0) { return (marks[index].GetShared_mark_id() < *static_cast<int *>(value)); } if(field.compare("x") == 0) { return (marks[index].GetX() < *static_cast<double *>(value)); } if(field.compare("y") == 0) { return (marks[index].GetY() < *static_cast<double *>(value)); } if(field.compare("diameter") == 0) { return (marks[index].GetDiameter() < *static_cast<double *>(value)); } if(field.compare("submit_time") == 0) { return (marks[index].GetSubmit_time() < *static_cast<int *>(value)); } if(field.compare("confirmed") == 0) { return (marks[index].GetConfirmed() < *static_cast<int *>(value)); } if(field.compare("score") == 0) { return (marks[index].GetScore() < *static_cast<double *>(value)); } if(field.compare("type") == 0) { return (marks[index].GetType() < *static_cast<string *>(value)); } if(field.compare("sub_type") == 0) { return (marks[index].GetSub_type() < *static_cast<string *>(value)); } if(field.compare("details") == 0) { return (marks[index].GetDetails() < *static_cast<string *>(value)); } if(field.compare("created_at") == 0) { return (marks[index].GetCreated_at() < *static_cast<string *>(value)); } if(field.compare("updated_at") == 0) { return (marks[index].GetUpdated_at() < *static_cast<string *>(value)); } return false; } double SearchMarks::Difference(vector <Marks> &marks, int index, string field, void *value) { /********************************/ /* Retrieve field column number */ /********************************/ if(field.compare("id") == 0) { return static_cast<double>(marks[index].GetId() - *static_cast<int *>(value)); } if(field.compare("user_id") == 0) { return static_cast<double>(marks[index].GetUser_id() - *static_cast<int *>(value)); } if(field.compare("image_id") == 0) { return static_cast<double>(marks[index].GetImage_id() - *static_cast<int *>(value)); } if(field.compare("application_id") == 0) { return static_cast<double>(marks[index].GetApplication_id() - *static_cast<int *>(value)); } if(field.compare("image_user_id") == 0) { return static_cast<double>(marks[index].GetImage_user_id() - *static_cast<int *>(value)); } if(field.compare("machine_mark_id") == 0) { return static_cast<double>(marks[index].GetMachine_mark_id() - *static_cast<int *>(value)); } if(field.compare("shared_mark_id") == 0) { return static_cast<double>(marks[index].GetShared_mark_id() - *static_cast<int *>(value)); } if(field.compare("x") == 0) { return static_cast<double>(marks[index].GetX() - *static_cast<double *>(value)); } if(field.compare("y") == 0) { return static_cast<double>(marks[index].GetY() - *static_cast<double *>(value)); } if(field.compare("diameter") == 0) { return static_cast<double>(marks[index].GetDiameter() - *static_cast<double *>(value)); } if(field.compare("submit_time") == 0) { return static_cast<double>(marks[index].GetSubmit_time() - *static_cast<int *>(value)); } if(field.compare("confirmed") == 0) { return static_cast<double>(marks[index].GetConfirmed() - *static_cast<int *>(value)); } if(field.compare("score") == 0) { return static_cast<double>(marks[index].GetScore() - *static_cast<double *>(value)); } if(field.compare("type") == 0) { return static_cast<double>(marks[index].GetType().compare(*static_cast<string *>(value))); } if(field.compare("sub_type") == 0) { return static_cast<double>(marks[index].GetSub_type().compare(*static_cast<string *>(value))); } if(field.compare("details") == 0) { return static_cast<double>(marks[index].GetDetails().compare(*static_cast<string *>(value))); } if(field.compare("created_at") == 0) { return static_cast<double>(marks[index].GetCreated_at().compare(*static_cast<string *>(value))); } if(field.compare("updated_at") == 0) { return static_cast<double>(marks[index].GetUpdated_at().compare(*static_cast<string *>(value))); } return false; } int SearchMarks::BinarySearch(vector <Marks> &marks, int m, int n, string field, void *value) { if(n >= m) { /***********************************/ /* Calculate value of middle index */ /***********************************/ int midpoint = m+(n-m)/2; /****************************************************/ /* Compare wanted value to value of middle element. */ /* If equal, return index of middle element. */ /****************************************************/ if(EqualityComparison(marks, midpoint, field, value)) { return midpoint; } /**************************************************/ /* If value of the middle element is smaller than */ /* the wanted value, then the wanted value must */ /* reside in the right portion of the array. */ /**************************************************/ if(LessThanComparison(marks, midpoint, field, value)) { return BinarySearch(marks, midpoint+1, n, field, value); } /*************************************************/ /* If value of the middle element is larger than */ /* the wanted value, then the wanted value must */ /* reside in the left portion of the array. */ /*************************************************/ if(GreaterThanComparison(marks, midpoint, field, value)) { return BinarySearch(marks, m, midpoint-1, field, value); } } /***********************************************************/ /* If value is not present in array, return negative index */ /***********************************************************/ return -1; } int SearchMarks::FirstNearestValue(vector <Marks> &marks, int m, int n, string field, void *value) { /*************************************************/ /* Declaration/Initialization of class variables */ /*************************************************/ double diff1; double diff2; if((n-m) > 1) { /******************************************************************/ /* Calculate index at boundary between first and second quantile. */ /* Calculate index at boundary between second and third quantile. */ /******************************************************************/ int boundary1 = m+(n-m)/3; int boundary2 = m+2*(n-m)/3; /************************************************************************/ /* Calculate difference between value to value at the index of boundary */ /* one and repeat for the value at the index of boundary two */ /************************************************************************/ diff1 = Difference(marks, boundary1, field, value); diff2 = Difference(marks, boundary2, field, value); /*************************************************/ /* If either differences equal zero, simply find */ /* the first occurence of value in data set */ /*************************************************/ if((diff1 == 0) || (diff2 == 0)) { return FirstOccurence(marks, m, n, field, value); } /**************************************/ /* If the first difference is greater */ /* than zero, examine first quantile */ /**************************************/ if(diff1 > 0) { return FirstNearestValue(marks, 0, boundary1-1, field, value); } /*************************************/ /* If the second difference is less */ /* than zero, examine third quantile */ /**************************************/ if(diff2 < 0) { return FirstNearestValue(marks, boundary2+1, n, field, value); } /*********************************************/ /* If zero lies between the two differences, */ /* then examine second quantile */ /*********************************************/ if((diff1 < 0) && (diff2 > 0)) { return FirstNearestValue(marks, boundary1+1, boundary2-1, field, value); } } /************************************************************/ /* Calculate difference between value to value at the index */ /* of m one and repeat for the value at the index of n */ /************************************************************/ diff1 = Difference(marks, m, field, value); diff2 = Difference(marks, n, field, value); return (diff1 < diff2) ? FirstOccurence(marks, m, n, field, marks[m].GetValue(field)) : FirstOccurence(marks, m, n, field, marks[n].GetValue(field)); } int SearchMarks::FirstOccurence(vector <Marks> &marks, int m, int n, string field, void *value) { if((n-m) > 1) { /***********************************************************/ /* Find midpoint between upper and lower bounding indicies */ /***********************************************************/ int midpoint = m+(n-m)/2; /*********************************************************/ /* Compare value of midpoint element to reference value. */ /* If less than reference value, move lowerbounding */ /* index to midpoint position. If equal to searched */ /* value, move upperbounding index to midpoint position */ /*********************************************************/ if(LessThanComparison(marks, midpoint, field, value)) { return FirstOccurence(marks, midpoint, n, field, value); } else { return FirstOccurence(marks, m, midpoint, field, value); } } /*********************************************************/ /* Check to see if quantities at indicies m or n matches */ /* reference value when indicies are one unit apart */ /*********************************************************/ if(EqualityComparison(marks, m, field, value)) { return m; } if(EqualityComparison(marks, n, field, value)) { return n; } return -1; } int SearchMarks::LastNearestValue(vector <Marks> &marks, int m, int n, string field, void *value) { /*************************************************/ /* Declaration/Initialization of class variables */ /*************************************************/ double diff1; double diff2; if((n-m) > 1) { /******************************************************************/ /* Calculate index at boundary between first and second quantile. */ /* Calculate index at boundary between second and third quantile. */ /******************************************************************/ int boundary1 = m+(n-m)/3; int boundary2 = m+2*(n-m)/3; /************************************************************************/ /* Calculate difference between value to value at the index of boundary */ /* one and repeat for the value at the index of boundary two */ /************************************************************************/ diff1 = Difference(marks, boundary1, field, value); diff2 = Difference(marks, boundary2, field, value); /*************************************************/ /* If either differences equal zero, simply find */ /* the first occurence of value in data set */ /*************************************************/ if((diff1 == 0) || (diff2 == 0)) { return LastOccurence(marks, m, n, field, value); } /**************************************/ /* If the first difference is greater */ /* than zero, examine first quantile */ /**************************************/ if(diff1 > 0) { return LastNearestValue(marks, 0, boundary1-1, field, value); } /*************************************/ /* If the second difference is less */ /* than zero, examine third quantile */ /**************************************/ if(diff2 < 0) { return LastNearestValue(marks, boundary2+1, n, field, value); } /*********************************************/ /* If zero lies between the two differences, */ /* then examine second quantile */ /*********************************************/ if((diff1 < 0) && (diff2 > 0)) { return LastNearestValue(marks, boundary1+1, boundary2-1, field, value); } } /************************************************************/ /* Calculate difference between value to value at the index */ /* of m one and repeat for the value at the index of n */ /************************************************************/ diff1 = Difference(marks, m, field, value); diff2 = Difference(marks, n, field, value); return (diff1 < diff2) ? LastOccurence(marks, m, n, field, marks[m].GetValue(field)) : LastOccurence(marks, m, n, field, marks[n].GetValue(field)); } int SearchMarks::LastOccurence(vector <Marks> &marks, int m, int n, string field, void *value) { if((n-m) > 1) { /***********************************************************/ /* Find midpoint between upper and lower bounding indicies */ /***********************************************************/ int midpoint = m+(n-m)/2; /********************************************************/ /* Compare value of midpoint element to searched value. */ /* If less than searched value, move lowerbounding */ /* index to midpoint position. If equal to searched */ /* value, move upperbounding index to midpoint position */ /********************************************************/ if(GreaterThanComparison(marks, midpoint, field, value)) { return LastOccurence(marks, m, midpoint, field, value); } else { return LastOccurence(marks, midpoint, n, field, value); } } /*********************************************************/ /* Check to see if quantities at indicies m or n matches */ /* reference value when indicies are one unit apart */ /*********************************************************/ if(EqualityComparison(marks, n, field, value)) { return n; } if(EqualityComparison(marks, m, field, value)) { return m; } return -1; }
[ "matthew.d.richardson.1@vanderbilt.edu" ]
matthew.d.richardson.1@vanderbilt.edu
179f69a51be0cfeb07c51ec2387864ceb8f69131
27d4fe457d83a1e63ef572a53c3adf4417a22f14
/stewartplatform.cpp
a17ae4d7b1d26b949c187ac259ae1da1f3ef6593
[]
no_license
Berglid/StewartPlatform
e37d38e037e7865dfd5bb09591f3ba30f7d5c7f6
dc3f30a0dca21e2ebcdef1ab38d42d7634a6f973
refs/heads/master
2022-11-19T20:57:57.477356
2020-07-19T17:29:30
2020-07-19T17:29:30
279,195,099
1
0
null
null
null
null
UTF-8
C++
false
false
22,894
cpp
#include "stewartplatform.h" #include "utilities.h" #include <QtDataVisualization/qscatterdataproxy.h> #include <QtDataVisualization/qvalue3daxis.h> #include <QtDataVisualization/q3dscene.h> #include <QtDataVisualization/q3dcamera.h> #include <QtDataVisualization/qscatter3dseries.h> #include <QtDataVisualization/q3dtheme.h> #include <QtWidgets/QComboBox> #include <QtMath> #include <QMatrix4x4> #include <Qt> #include <QFile> #include <QTextStream> #include <QFileDialog> #include <iostream> #include <QDebug> #include <QTime> using namespace QtDataVisualization; StewartPlatform::StewartPlatform(Q3DScatter *scatter) : m_graph(scatter), m_fontSize(12.0f), m_smooth(true), x(x_home), y(y_home), z(z_home), rx(rx_home), ry(ry_home), rz(rz_home), meshScale(2000.0f, 2000.0f, 2000.0f), itemUpperActuators(actuatorCount), itemLowerActuatorsLight(actuatorCount), itemLowerActuatorsMedium(actuatorCount), itemLowerActuatorsDark(actuatorCount), actuatorLengths(actuatorCount, actuatorMinLength), platformPointsInSFrame(actuatorCount), baseToPlatformInSFrame(actuatorCount), lowerActuatorQuaternion(actuatorCount) { initializeGraph(); setCameraHome(); initializeMeshes(); updateMeshPoses(getPose()); } // deconstructor StewartPlatform::~StewartPlatform() { delete m_graph; } // Initialize and configure graph void StewartPlatform::initializeGraph(){ m_graph->activeTheme()->setType(Q3DTheme::ThemeDigia); QFont font = m_graph->activeTheme()->font(); font.setPointSize(m_fontSize); m_graph->activeTheme()->setFont(font); m_graph->setShadowQuality(QAbstract3DGraph::ShadowQualityNone); m_graph->scene()->activeCamera()->setCameraPreset(Q3DCamera::CameraPresetFront); m_graph->activeTheme()->setBackgroundEnabled(false); m_graph->activeTheme()->setGridEnabled(false); m_graph->activeTheme()->setLabelBorderEnabled(false); setLabelEnabled(false); m_graph->axisX()->setTitle("X"); m_graph->axisY()->setTitle("Y"); m_graph->axisZ()->setTitle("Z"); m_graph->setAspectRatio(1.0); m_graph->setHorizontalAspectRatio(1.0); m_graph->axisZ()->setReversed(true); // Seems like Z axis was flipped by default, creating an "invalid" coordinate frame, thus reverse the axis int plotSize = 840; int radius = plotSize/2; // keep aspect ratio to get correct scaling of meshes int yMin = - 120; int yMax = plotSize + yMin ; m_graph->axisX()->setMax(radius); m_graph->axisX()->setMin(-radius); m_graph->axisY()->setMax(yMax); m_graph->axisY()->setMin(yMin); m_graph->axisZ()->setMax(radius); m_graph->axisZ()->setMin(-radius); } // Adds mesh to graph void StewartPlatform::addItem(QCustom3DItem*& rItem, const QString& rMeshFile, const QString& rTextureFile, const QVector3D& rPosition){ rItem = new QCustom3DItem; rItem->setMeshFile(rMeshFile); rItem->setPosition(rPosition); rItem->setTextureFile(rTextureFile); rItem->setScalingAbsolute(false); rItem->setScaling(meshScale); m_graph->addCustomItem(rItem); } // Initializes meshes and add them to graph void StewartPlatform::initializeMeshes() { // Texture files const QString darkGray(":/textures/gray45.png"); const QString mediumGray(":/textures/grey159.png"); const QString mediumLightGray(":/textures/grey189.png"); const QString lightGray(":/textures/gray210.png"); // Mesh files const QString meshTopPlateLight(":/obj/top_plate_light.obj"); const QString meshTopPlateDark(":/obj/top_plate_dark.obj"); const QString meshBottomPlateLight(":/obj/bottom_plate_light.obj"); const QString meshBottomPlateDark(":/obj/bottom_plate_dark.obj"); const QString meshLowerActuatorLight(":/obj/Lower_actuator_light.obj"); const QString meshLowerActuatorMedium(":/obj/lower_actuator_medium.obj"); const QString meshLowerActuatorDark(":/obj/lower_actuator_dark.obj"); const QString meshUpperActuator(":/obj/upper_actuator.obj"); // Add top plate addItem(itemTopPlateDark, meshTopPlateDark, darkGray, QVector3D(x, y, z)); addItem(itemTopPlateLight, meshTopPlateLight, mediumGray, QVector3D(x, y, z)); // Add bottom plate addItem(itemBottomPlateLight, meshBottomPlateLight, mediumGray, QVector3D(0, 0, 0)); addItem(itemBottomPlateDark, meshBottomPlateDark, darkGray, QVector3D(0, 0, 0)); // Add upper/lower actuators for(int i = 0; i < actuatorCount; i++){ addItem(itemLowerActuatorsLight[i], meshLowerActuatorLight, lightGray, basePoints[i]); addItem(itemLowerActuatorsMedium[i], meshLowerActuatorMedium, mediumLightGray, basePoints[i]); addItem(itemLowerActuatorsDark[i], meshLowerActuatorDark, darkGray, basePoints[i]); addItem(itemUpperActuators[i], meshUpperActuator, lightGray, platformPointsInSFrame[i]); } } // change theme void StewartPlatform::changeTheme(int theme) { Q3DTheme *currentTheme = m_graph->activeTheme(); switch (theme) { case 0: { currentTheme->setType(Q3DTheme::ThemeQt); break; } case 1: { currentTheme->setType(Q3DTheme::ThemeArmyBlue); break; } case 2: { currentTheme->setType(Q3DTheme::ThemeEbony); break; } default: { break; } } currentTheme->setBackgroundEnabled(false); currentTheme->setGridEnabled(false); setLabelEnabled(false); emit backgroundEnabledChanged(currentTheme->isBackgroundEnabled()); emit gridEnabledChanged(currentTheme->isGridEnabled()); } // change camera preset void StewartPlatform::changePresetCamera() { static int preset = Q3DCamera::CameraPresetFrontLow; m_graph->scene()->activeCamera()->setCameraPreset((Q3DCamera::CameraPreset)preset); if (++preset > Q3DCamera::CameraPresetDirectlyBelow){ preset = Q3DCamera::CameraPresetFrontLow; } } // shadow quality changed void StewartPlatform::shadowQualityUpdatedByVisual(QAbstract3DGraph::ShadowQuality sq) { int quality = int(sq); emit shadowQualityChanged(quality); } // change shadow quality void StewartPlatform::changeShadowQuality(int quality) { QAbstract3DGraph::ShadowQuality sq = QAbstract3DGraph::ShadowQuality(quality); m_graph->setShadowQuality(sq); } // enable background void StewartPlatform::setBackgroundEnabled(int enabled) { m_graph->activeTheme()->setBackgroundEnabled((bool)enabled);} // enable grid void StewartPlatform::setGridEnabled(int enabled) { m_graph->activeTheme()->setGridEnabled((bool)enabled); } // TODO: // Very ugly solution // Sets the label color to the background color // Overwrite Q3Dtheme? // enable label void StewartPlatform::setLabelEnabled(int enabled){ isLabelEnabled = enabled; emit(labelEnabledChanged(enabled)); QColor labelColor; Q3DTheme *currentTheme = m_graph->activeTheme(); if(isLabelEnabled == false){ labelColor = currentTheme->backgroundColor(); } else { if(currentTheme->type() == Q3DTheme::ThemeEbony){ labelColor = QColor(170,170,170); // Set to gray } else { labelColor = QColor(0, 0, 0); // set to black } } currentTheme->setLabelTextColor(labelColor); currentTheme->setLabelBackgroundColor(currentTheme->backgroundColor()); QFont arialfont("Arial", m_fontSize); currentTheme->setFont(arialfont); currentTheme->setLabelBorderEnabled(false); } // Move platform to home position void StewartPlatform::setActuatorsHome(){ // updateMeshPoses(QVector<float>{ x_home, y_home, z_home, rx_home, ry_home, rz_home }); // DELETE // updateMeshPoses(getHomePose()); QVector<QVector<float>> homePath = generatePath(getPose(), getHomePose()); for(int i = 0; i < homePath.size(); i++){ move3D(homePath[i]); } /// MOVE TO TIMER IN MAINWINDOW TO UPDATE WITH FPS } // Move platform x direction void StewartPlatform::xMove(double value){ QVector<float> tempPose = getPose(); tempPose[0] = value; updateMeshPoses(tempPose); } // Move platform y direction void StewartPlatform::yMove(double value){ QVector<float> tempPose = getPose(); tempPose[1] = value; updateMeshPoses(tempPose); } // Move platform z direction void StewartPlatform::zMove(double value){ QVector<float> tempPose = getPose(); tempPose[2] = value; updateMeshPoses(tempPose); } // Rotate platform about x axis (roll) void StewartPlatform::xRot(double value){ QVector<float> tempPose = getPose(); tempPose[3] = value; updateMeshPoses(tempPose); } // Rotate platform about y axis (pitch) void StewartPlatform::yRot(double value){ QVector<float> tempPose = getPose(); tempPose[4] = value; updateMeshPoses(tempPose); } // Rotate platform about z axis (yaw) void StewartPlatform::zRot(double value){ QVector<float> tempPose = getPose(); tempPose[5] = value; updateMeshPoses(tempPose); } // get positions double StewartPlatform::getX(){ return x;} double StewartPlatform::getY(){ return y;} double StewartPlatform::getZ(){ return z;} double StewartPlatform::getRX(){ return rx;} double StewartPlatform::getRY(){ return ry;} double StewartPlatform::getRZ(){ return rz; } float StewartPlatform::getMaxRy(){ return ry_max; } QVector<float> StewartPlatform::getPose(){ return QVector<float>{x,y,z,rx,ry,rz}; } QVector<float> StewartPlatform::getHomePose(){ return QVector<float> {x_home, y_home, z_home, rx_home, ry_home, rz_home}; } // Returns pose in string format used for serial communication QVector<int> StewartPlatform::getActuatorData(){ float interScale = 1023.0f/150.0f; QVector<int> actuatorData(actuatorCount); for(int i = 0; i < actuatorCount; i++){ actuatorData[i] = round((actuatorLengths[i] - actuatorMinLength)*interScale); // convert actuatorLengths to value between 0 and 1023 } return actuatorData; } // Returns rotation matrix for platform QMatrix3x3 StewartPlatform::getRotationMatrix(){ float RxValues[] = {1, 0, 0, 0, cosd(this->rx), -sind(this->rx), 0, sind(this->rx), cosd(this->rx)}; float RyValues[] = {cosd(this->ry), 0, sind(this->ry), 0, 1, 0, -sind(this->ry), 0, cosd(this->ry)}; float RzValues[] = {cosd(this->rz), -sind(this->rz), 0, sind(this->rz), cosd(this->rz), 0, 0, 0, 1 }; QMatrix3x3 Rx(RxValues); QMatrix3x3 Ry(RyValues); QMatrix3x3 Rz(RzValues); return Rx*Ry*Rz; } // Overload: Returns the composite rotation matrix of R(roll) R(pitch) R(yaw) QMatrix3x3 StewartPlatform::getRotationMatrix(float roll, float pitch, float yaw){ float RxValues[] = {1, 0, 0, 0, cosd(roll), -sind(roll), 0, sind(roll), cosd(roll)}; float RyValues[] = {cosd(pitch), 0, sind(pitch), 0, 1, 0, -sind(pitch), 0, cosd(pitch)}; float RzValues[] = {cosd(yaw), -sind(yaw), 0, sind(yaw), cosd(yaw), 0, 0, 0, 1 }; QMatrix3x3 Rx(RxValues); QMatrix3x3 Ry(RyValues); QMatrix3x3 Rz(RzValues); return Rx*Ry*Rz; } // Returns transformation matrix for platform QMatrix4x4 StewartPlatform::getTransformationMatrix(){ QMatrix3x3 R = getRotationMatrix(); QMatrix4x4 trans(R(0,0), R(0,1), R(0,2), x, R(1,0), R(1,1), R(1,2), y, R(2,0), R(2,1), R(2,2), z, 0, 0, 0, 1); return trans; } // Returns transformation matrix for given pose QMatrix4x4 StewartPlatform::getTransformationMatrix(QVector<float> pose){ QMatrix3x3 R = getRotationMatrix(pose[3], pose[4], pose[5]); QMatrix4x4 trans(R(0,0), R(0,1), R(0,2), pose[0], R(1,0), R(1,1), R(1,2), pose[1], R(2,0), R(2,1), R(2,2), pose[2], 0, 0, 0, 1); return trans; } // FIX: Set quaternion directly from euler angles // Returns quaternion for platform QQuaternion StewartPlatform::getQuaternion(){ QMatrix3x3 R = getRotationMatrix(); return QQuaternion::fromRotationMatrix(R); } //TODO:: // ADD bool to function Return true if valid pose // RENAME? // calculates platform parameters for given pose. If leg lengths are valid, stewart platforms parameters is updated bool StewartPlatform::updatePlatformParameters(QVector<float> pose){ QMatrix4x4 trans = getTransformationMatrix(pose); QVector<QVector3D> tempPlatformPointsInSFrame(actuatorCount); QVector<QVector3D> tempBaseToPlatformInSFrame(actuatorCount); QVector<float> tempActuatorLengths(actuatorCount); // calculate temporary vectors and actuator lengths for(int i = 0; i < actuatorCount; i++){ QVector4D temp = trans * platformPoints[i]; tempPlatformPointsInSFrame[i] = temp.toVector3D(); tempBaseToPlatformInSFrame[i] = (tempPlatformPointsInSFrame[i] - basePoints[i]); tempActuatorLengths[i] = static_cast<int>((tempPlatformPointsInSFrame[i] - basePoints[i]).length()); // leg lengths total in mm } // if actuator lenghs are valid, then update stewart platform if (isValidLengths(tempActuatorLengths)){ setPose(pose); // actuator lenghts are valid, set coordinates // Points were valid, update parameters platformPointsInSFrame = tempPlatformPointsInSFrame; baseToPlatformInSFrame = tempBaseToPlatformInSFrame; actuatorLengths = tempActuatorLengths; // calculate lower actuators rotation for(int i = 0; i < actuatorCount; i++){ QQuaternion q; QVector3D a; QVector3D v1(0, 1, 0); // Y-unit vector QVector3D v2 = baseToPlatformInSFrame[i]; v1.normalize(); v2.normalize(); a = QVector3D::crossProduct(v1, v2); // qDebug() << "base point" << i; // << ":" << basePoints[i] << "platform point" << "i" << platformPointsInSFrame[i] << "vector" << a.x() << a.y << a.z; q.setVector(a); q.setScalar(qSqrt(qPow(v1.length(), 2)) * qSqrt(qPow(v2.length(), 2)) + QVector3D::dotProduct(v1, v2)); q.normalize(); lowerActuatorQuaternion[i] = q; } return true; } else { // Pose gave invalid leg lengths return false; } } // updates all meshes if given pose for platform is valid void StewartPlatform::updateMeshPoses(QVector<float> pose){ // dont update if roll is not within limits if((pose[4] > ry_max) || (pose[4] < ry_min)){ return; } // Set new pose for meshes if pose result in valid parameters if(updatePlatformParameters(pose)){ itemTopPlateDark->setPosition(QVector3D(x, y, z)); itemTopPlateDark->setRotation(getQuaternion()); itemTopPlateLight->setPosition(QVector3D(x, y, z)); itemTopPlateLight->setRotation(getQuaternion()); // update position and rotation for actuators for(int i = 0; i < actuatorCount; i++){ itemLowerActuatorsLight[i]->setRotation(lowerActuatorQuaternion[i]*lowerActuatorQuaternionInitialRot[i]); // Lower actuator light rotation itemLowerActuatorsMedium[i]->setRotation(lowerActuatorQuaternion[i]*lowerActuatorQuaternionInitialRot[i]); // Lower actuator medium rotation itemLowerActuatorsDark[i]->setRotation(lowerActuatorQuaternion[i]*lowerActuatorQuaternionInitialRot[i]); // Lower actuator dark rotation itemUpperActuators[i]->setPosition(platformPointsInSFrame[i]); // upper actuator position itemUpperActuators[i]->setRotation(lowerActuatorQuaternion[i]); // upper actuator rotation } } // qDebug() << "updatePose finished"; // qDebug() << "(" + QTime::currentTime().toString() + ") i:" << tempCountFPS << " x:" << x << "y:" << y << "z:" << z << "rx:" << roll << "ry:" << pitch << "rz:" << yaw; // tempCountFPS++; // // 63 FPS ? } void StewartPlatform::setPose(QVector<float> pose){ x = pose[0]; y = pose[1]; z = pose[2]; rx = pose[3]; ry = pose[4]; rz = pose[5]; emitValueChanged(); // Emit signals for values changed to update spinboxes } void StewartPlatform::OnMove(QVector<float>& motionData){ if(motionData.size() != 6) { qDebug() << "StewartPLatform::onMove.. motionData.size() != 6"; return; } // Adjust base sensitivity for 3D Mouse float xSens = 0.005f; float ySens = 0.005f; float zSens = 0.005f; float rxSens = 0.0008f; float rySens = 0.0008f; float rzSens = 0.0008f; QVector<float> tempPose { x - (motionData[0]*xSens), // Reversed (-) y + (motionData[1]*ySens), z + (motionData[2]*zSens), rx - (motionData[3]*rxSens), // Reversed (-) ry + (motionData[4]*rySens), rz + (motionData[5]*rzSens) }; // function updates platform position and rotation if tempPose is valid updateMeshPoses(tempPose); // TODO: // ADD IF PRINT ACTUATOR LENGHS printActuatorLengths(); } void StewartPlatform::move3D(QVector<float> motionData){ updateMeshPoses(motionData); } bool StewartPlatform::isValidLengths(QVector<float> lengths){ bool valid = true; for(int i = 0; i < actuatorLengths.size(); i++){ if((lengths[i] < actuatorMinLength) || (lengths[i] > actuatorMaxLength)) { return false; } } return valid; } void StewartPlatform::setCameraHome(){ float xRotationHome = -180.0f; float yRotationHome = 12.0f; float zoomHome = 250.0f; m_graph->scene()->activeCamera()->setTarget(QVector3D(0.0f, -0.25f, 0.0f)); m_graph->scene()->activeCamera()->setXRotation(xRotationHome); m_graph->scene()->activeCamera()->setYRotation(yRotationHome); m_graph->scene()->activeCamera()->setZoomLevel(zoomHome); } void StewartPlatform::emitValueChanged(){ emit(xChanged(x)); emit(yChanged(y)); emit(zChanged(z)); emit(rXChanged(rx)); emit(rYChanged(ry)); emit(rZChanged(rz)); emit(validMove()); } // Temporary //TODO: // Calculate max step based on actuators length at start and end pose, and the actuator speed instead. QVector<QVector<float>> StewartPlatform::generatePath(const QVector<float> startPose, const QVector<float> endPose, int FPS){ QVector<QVector<float>> path; QVector<float> diffPose(6, 0.0f); QVector<float> currenStep(startPose); float maxDiff = 0; float maxDiffIndex; float maxStep = 0.94; int numStep; if((startPose.size() == endPose.size()) && (startPose.size() == 6)){ for(int i = 0; i < diffPose.size(); i++){ diffPose[i] = endPose[i] - startPose[i]; if(abs(diffPose[i]) > maxDiff){ maxDiff = abs(diffPose[i]); maxDiffIndex = i; } } } numStep = round(maxDiff/maxStep); QVector<float> poseStep(6); for(int i = 0; i < poseStep.size(); i++){ if(diffPose[i] == 0 || numStep == 0){ poseStep[i] = 0; }else{ poseStep[i] = diffPose[i]/numStep; } } path.append(startPose); for(int i = 0; i < numStep-1; i++){ for(int j = 0; j < currenStep.size(); j++){ currenStep[j] += poseStep[j]; } path.append(currenStep); } path.append(endPose); return path; // Override +, -, *, / operators of QVector? // maxLengthActuator = 150 // minLengthActuator = 0 // max height platform (yMax) = 522 // min heigh platform (yMin) = 340 // range Y = 505.5-340 = 160.5mm // Max speed actuator 2"/s = 25.4mm*2/s = 50.8mm sec // time from minActLengt to MaxActLength: 150 - s*50.8 = 0 -> s = 150/50.8 = 2.953s // Number of steps s * fps = 2.953*FPS(60) = 177.2 // round down to 170 steps at 60 fps from ymin to ymax // thus maxStep = 160/170 = 0.9411 // but combined movements will give diferent maxsteps // aswell as rotation // so not at all correct speeds } /////////////// //// Debug //// /////////////// //// prints a QMatrix3x3 //void StewartPlatform::printRotationMatrix(const QMatrix3x3& R){ // QDebug deb = qDebug(); // for(int i = 0; i < 3; ++i){ // for(int j = 0; j < 3; ++j){ // deb << R(i, j); // } // deb << "\n"; // } //} //// Print quaternion //void StewartPlatform::printQuaternion(const QQuaternion& q){ // qDebug() << "q.x: " << q.x() << "q.y:" << q.y(); //} //// Print upper joint positions //void StewartPlatform::printUpperJointPositions(){ // QVector3D temp; // qDebug() << "Upper joint positions"; // for(int i = 0; i < NumberOfActuators; i++){ // temp = platformPointsInSFrame[i]; // qDebug() << temp.x() << temp.y() << temp.z(); // } //} // Prints actuator lengths void StewartPlatform::printActuatorLengths(){ QVector<int> convertedLengths = getActuatorData(); qDebug() << "Actuator :" << " 1 " << " 2 " << " 3 " << " 4 " << " 5 " << " 6 "; QDebug deb = qDebug(); for(int i = 0; i < actuatorCount + 1; i++){ if(i == 0){ deb << "Length mm :"; }else { deb << actuatorLengths[i-1]; } } for(int i = 0; i < actuatorCount + 1; i++){ if(i == 0){ deb << "\nLength [0-1023] :"; }else { deb << convertedLengths[i-1]; } } } //// Prints pose (position and rotation) //void StewartPlatform::printPose(){ // qDebug() << "x:" << x << " y:" << y << " z:" << z // << " roll:" << roll << " pitch:" << pitch << " yaw:" << yaw; //} //// prints log //void StewartPlatform::printLog(){ // printPose(); // printActuatorLengths(); //} void StewartPlatform::printQVector(QVector<float> vec){ qDebug() << "x: " << vec[0] << "Y: " << vec[1] << "z: " << vec[2] << "rx:" << vec[3] << "ry:" << vec[4] << "rz" << vec[5]; }
[ "sebastian.grans@gmail.com" ]
sebastian.grans@gmail.com
51f21909be129eb5b8a90af4c8875f852f12eea4
2414652fde0bceae0fef4ad7dbab13b8ca72ece4
/timeseries.cpp
bc3fefd789a961f67fd00cf109b0d0483aff6236
[ "MIT" ]
permissive
ComComServicesLtd/hengeDB
57179fe4861608971185e5e960117b86a0f69b1f
84cee095a7893663fd6e299133a3e8f2633ec892
refs/heads/master
2021-01-01T19:23:31.421300
2015-09-27T05:20:37
2015-09-27T05:20:37
41,757,067
0
0
null
null
null
null
UTF-8
C++
false
false
88
cpp
#include "timeseries.h" timeseries::timeseries() { } timeseries::~timeseries() { }
[ "jonelias@mundall.com" ]
jonelias@mundall.com
6ec4899c74f8df74ed90831f9a1b36cb5d843818
47fb20e1435c9f27aa335f32248f84d370132a46
/src/libs/geometry/gtk/geom_drawer.cpp
34ce50760aed3232f5b706d22af7b4c131e7f5d1
[]
no_license
sanyaade-teachings/fawkes
f7fc08aa18147364a2106ed90b2a18501cfc65a0
bb80e90bc5192f2ff6c6c6b4f0f6be52ea5627cd
refs/heads/master
2020-12-14T17:12:30.790871
2013-07-13T09:54:11
2013-07-13T09:54:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,626
cpp
/*************************************************************************** * geom_drawer.cpp - Drawer base class * * Created: Thu Oct 09 15:38:19 2008 * Copyright 2008 Daniel Beck * ****************************************************************************/ /* This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. A runtime exception applies to * this software (see LICENSE.GPL_WRE file mentioned below for details). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * Read the full text in the LICENSE.GPL_WRE file in the doc directory. */ #include <geometry/gtk/geom_drawer.h> /** @class fawkes::GeomDrawer <geometry/gtk/geom_drawer.h> * Abstract base class for all drawer classes. All objects that have * corresponding drawer classes can easily be drawn on a * GeomDrawingArea. * @author Daniel Beck */ /** @fn void fawkes::GeomDrawer::draw(Cairo::RefPtr<Cairo::Context>& context) * This method is called by the GeomDrawingArea. Here, derived classes * should implement the drawing code. * @param context the drawing context */ namespace fawkes { /** Constructor. */ GeomDrawer::GeomDrawer() { } /** Destructor. */ GeomDrawer::~GeomDrawer() { } } // end namespace fawkes
[ "niemueller@kbsg.rwth-aachen.de" ]
niemueller@kbsg.rwth-aachen.de
437797f56c38a48ae83aaa43a76b99318ca93932
5838cf8f133a62df151ed12a5f928a43c11772ed
/NT/enduser/netmeeting/ui/wb/mwnd.cpp
15141cac435922387fc884dfd6e748f48c417192
[]
no_license
proaholic/Win2K3
e5e17b2262f8a2e9590d3fd7a201da19771eb132
572f0250d5825e7b80920b6610c22c5b9baaa3aa
refs/heads/master
2023-07-09T06:15:54.474432
2021-08-11T09:09:14
2021-08-11T09:09:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
165,780
cpp
// // MWND.CPP // Main WB Window // // Copyright Microsoft 1998- // // PRECOMP #include "precomp.h" #include <dde.h> #include "version.h" #include "nmwbobj.h" static const TCHAR s_cszHtmlHelpFile[] = TEXT("nmwhiteb.chm"); // Class name TCHAR szMainClassName[] = "T126WBMainWindowClass"; extern TCHAR g_PassedFileName[]; void ShiftFocus(HWND hwndTop, BOOL bForward); BOOL IsWindowActive(HWND hwnd); // // Scroll accelerators // typedef struct tagSCROLL { UINT uiMenuId; UINT uiMessage; UINT uiScrollCode; } SCROLL; static const SCROLL s_MenuToScroll[] = { { IDM_PAGEUP, WM_VSCROLL, SB_PAGEUP }, { IDM_PAGEDOWN, WM_VSCROLL, SB_PAGEDOWN }, { IDM_SHIFTPAGEUP, WM_HSCROLL, SB_PAGEUP }, { IDM_SHIFTPAGEDOWN, WM_HSCROLL, SB_PAGEDOWN }, { IDM_HOME, WM_HSCROLL, SB_TOP }, { IDM_HOME, WM_VSCROLL, SB_TOP }, { IDM_END, WM_HSCROLL, SB_BOTTOM }, { IDM_END, WM_VSCROLL, SB_BOTTOM }, { IDM_LINEUP, WM_VSCROLL, SB_LINEUP }, { IDM_LINEDOWN, WM_VSCROLL, SB_LINEDOWN }, { IDM_SHIFTLINEUP, WM_HSCROLL, SB_LINEUP }, { IDM_SHIFTLINEDOWN, WM_HSCROLL, SB_LINEDOWN } }; // tooltip data // check codes #define NA 0 // dont't check checked state #define TB 1 // check toolbar for checked state #define BT 2 // check tipped wnd (a button) for checked state typedef struct { UINT nID; UINT nCheck; UINT nUpTipID; UINT nDownTipID; } TIPIDS; TIPIDS g_tipIDsArray[] = { {IDM_SELECT, TB, IDS_HINT_SELECT, IDS_HINT_SELECT}, {IDM_ERASER, TB, IDS_HINT_ERASER, IDS_HINT_ERASER}, {IDM_TEXT, TB, IDS_HINT_TEXT, IDS_HINT_TEXT}, {IDM_HIGHLIGHT, TB, IDS_HINT_HIGHLIGHT, IDS_HINT_HIGHLIGHT}, {IDM_PEN, TB, IDS_HINT_PEN, IDS_HINT_PEN}, {IDM_LINE, TB, IDS_HINT_LINE, IDS_HINT_LINE}, {IDM_BOX, TB, IDS_HINT_BOX, IDS_HINT_BOX}, {IDM_FILLED_BOX, TB, IDS_HINT_FBOX, IDS_HINT_FBOX}, {IDM_ELLIPSE, TB, IDS_HINT_ELLIPSE, IDS_HINT_ELLIPSE}, {IDM_FILLED_ELLIPSE, TB, IDS_HINT_FELLIPSE, IDS_HINT_FELLIPSE}, {IDM_ZOOM, TB, IDS_HINT_ZOOM_UP, IDS_HINT_ZOOM_DOWN}, {IDM_REMOTE, TB, IDS_HINT_REMOTE_UP, IDS_HINT_REMOTE_DOWN}, {IDM_LOCK, TB, IDS_HINT_LOCK_UP, IDS_HINT_LOCK_DOWN}, {IDM_SYNC, TB, IDS_HINT_SYNC_UP, IDS_HINT_SYNC_DOWN}, {IDM_GRAB_AREA, TB, IDS_HINT_GRAB_AREA, IDS_HINT_GRAB_AREA}, {IDM_GRAB_WINDOW, TB, IDS_HINT_GRAB_WINDOW, IDS_HINT_GRAB_WINDOW}, {IDM_WIDTH_1, NA, IDS_HINT_WIDTH_1, IDS_HINT_WIDTH_1}, {IDM_WIDTH_2, NA, IDS_HINT_WIDTH_2, IDS_HINT_WIDTH_2}, {IDM_WIDTH_3, NA, IDS_HINT_WIDTH_3, IDS_HINT_WIDTH_3}, {IDM_WIDTH_4, NA, IDS_HINT_WIDTH_4, IDS_HINT_WIDTH_4}, {IDM_PAGE_FIRST, BT, IDS_HINT_PAGE_FIRST, IDS_HINT_PAGE_FIRST}, {IDM_PAGE_PREV, BT, IDS_HINT_PAGE_PREVIOUS, IDS_HINT_PAGE_PREVIOUS}, {IDM_PAGE_ANY, NA, IDS_HINT_PAGE_ANY, IDS_HINT_PAGE_ANY}, {IDM_PAGE_NEXT, BT, IDS_HINT_PAGE_NEXT, IDS_HINT_PAGE_NEXT}, {IDM_PAGE_LAST, BT, IDS_HINT_PAGE_LAST, IDS_HINT_PAGE_LAST}, {IDM_PAGE_INSERT_AFTER, BT, IDS_HINT_PAGE_INSERT, IDS_HINT_PAGE_INSERT} }; //////////// HRESULT WbMainWindow::WB_LoadFile(LPCTSTR szFile) { // // If a file name was passed // if (szFile && g_pMain) { int cchLength; BOOL fSkippedQuote; // Skip past first quote if (fSkippedQuote = (*szFile == '"')) szFile++; cchLength = lstrlen(szFile); // // NOTE: // There may be DBCS implications with this. Hence we check to see // if we skipped the first quote; we assume that if the file name // starts with a quote it must end with one also. But we need to check // it out. // // Strip last quote if (fSkippedQuote && (cchLength > 0) && (szFile[cchLength - 1] == '"')) { BYTE * pLastQuote = (BYTE *)&szFile[cchLength - 1]; TRACE_MSG(("Skipping last quote in file name %s", szFile)); *pLastQuote = '\0'; } g_pMain->OnOpen(szFile); } return S_OK; } void WbMainWindow::BringToFront(void) { if (NULL != m_hwnd) { int nCmdShow = SW_SHOW; WINDOWPLACEMENT wp; ::ZeroMemory(&wp, sizeof(wp)); wp.length = sizeof(wp); if (::GetWindowPlacement(m_hwnd, &wp)) { if (SW_MINIMIZE == wp.showCmd || SW_SHOWMINIMIZED == wp.showCmd) { // The window is minimized - restore it: nCmdShow = SW_RESTORE; } } // show the window now ::ShowWindow(m_hwnd, nCmdShow); // bring it to the foreground ::SetForegroundWindow(m_hwnd); } } // // // Function: WbMainWindow constructor // // Purpose: Create the main Whiteboard window. An exception is thrown // if an error occurs during construction. // // WbMainWindow::WbMainWindow(void) { OSVERSIONINFO OsData; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::WbMainWindow"); // // Initialize member vars first! // ZeroMemory(m_ToolArray, sizeof(m_ToolArray)); m_hwnd = NULL; m_hwndToolTip = NULL; ZeroMemory(&m_tiLastHit, sizeof(m_tiLastHit)); m_nLastHit = -1; m_bInitOk = FALSE; m_bDisplayingError = FALSE; m_hwndSB = NULL; m_bStatusBarOn = TRUE; m_bToolBarOn = TRUE; // Load the main accelerator table m_hAccelTable = ::LoadAccelerators(g_hInstance, MAKEINTRESOURCE(MAINACCELTABLE)); m_hwndQuerySaveDlg = NULL; m_hwndWaitForEventDlg = NULL; m_hwndWaitForLockDlg = NULL; m_pCurrentTool = NULL; ZeroMemory(m_strFileName, sizeof(m_strFileName)); m_pTitleFileName = NULL; // Load the alternative accelerator table for the pages edit // field and text editor m_hAccelPagesGroup = ::LoadAccelerators(g_hInstance, MAKEINTRESOURCE(PAGESGROUPACCELTABLE)); m_hAccelTextEdit = ::LoadAccelerators(g_hInstance, MAKEINTRESOURCE(TEXTEDITACCELTABLE)); // Show that we are not yet in a call m_uiSubState = SUBSTATE_IDLE; // We are not currently displaying a menu m_hContextMenuBar = NULL; m_hContextMenu = NULL; m_hGrobjContextMenuBar = NULL; m_hGrobjContextMenu = NULL; m_bInSaveDialog = FALSE; m_bSelectAllInProgress = FALSE; m_bUnlockStateSettled = TRUE; m_bQuerySysShutdown = FALSE; // figure out if we're on Win95 m_bIsWin95 = FALSE; OsData.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if( GetVersionEx( &OsData ) ) { if( OsData.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) m_bIsWin95 = TRUE; } m_cancelModeSent = FALSE; // // We only do this once for the lifetime of the DLL. There is no // way really to clean up registered window messages, and each register // bumps up a ref count. If we registered each time WB was started up // during one session of CONF, we'd overflow the refcount. // if (!g_uConfShutdown) { g_uConfShutdown = ::RegisterWindowMessage( NM_ENDSESSION_MSG_NAME ); } m_pLocalRemotePointer = NULL; m_localRemotePointerPosition.x = -50; m_localRemotePointerPosition.y = -50; } // // Open() // Do Main window initialization (stuff that can fail). After this, // the run code will try to join the current domain and do message loop // stuff. // BOOL WbMainWindow::Open(int iCommand) { WNDCLASSEX wc; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::Open"); // // CREATE OTHER GLOBALS // if (!InitToolArray()) { ERROR_OUT(("Can't create tools; failing to start up")); return(FALSE); } // // Init comon controls // InitCommonControls(); // // CREATE THE MAIN FRAME WINDOW // ASSERT(!m_hwnd); // // Get the class info for it, and change the name. // ZeroMemory(&wc, sizeof(wc)); wc.cbSize = sizeof(wc); wc.style = CS_DBLCLKS; // CS_HREDRAW | CS_VREDRAW? wc.lpfnWndProc = WbMainWindowProc; wc.hInstance = g_hInstance; wc.hIcon = ::LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_APP)); wc.hCursor = ::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW)); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1); wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU_WB_WITHFILE); wc.lpszClassName = szMainClassName; if (!::RegisterClassEx(&wc)) { ERROR_OUT(("Can't register private frame window class")); return(FALSE); } // Create the main drawing window. if (!::CreateWindowEx(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, szMainClassName, NULL, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, g_hInstance, this)) { // Could not create the main window ERROR_OUT(("Failed to create main window")); return(FALSE); } ASSERT(m_hwnd); // // Create the pop-up context menu // if (!CreateContextMenus()) { ERROR_OUT(("Failed to create context menus")); return(FALSE); } // // Register the the main window for Drag/Drop messages. // DragAcceptFiles(m_hwnd, TRUE); // // CREATE THE CHILD WINDOWS // // Create the drawing pane // (the Create call throws an exception on error) RECT clientRect; RECT drawingAreaRect; ::GetClientRect(m_hwnd, &clientRect); drawingAreaRect.top=0; drawingAreaRect.bottom = DRAW_HEIGHT; drawingAreaRect.left = 0; drawingAreaRect.right = DRAW_WIDTH; // Every control in the main window has a border on it, so increase the // client size by 1 to force these borders to be drawn under the inside // black line in the window frame. This prevents a 2 pel wide border // being drawn ::InflateRect(&clientRect, 1, 1); SIZE sizeAG; m_AG.GetNaturalSize(&sizeAG); if (!m_drawingArea.Create(m_hwnd, &drawingAreaRect)) { ERROR_OUT(("Failed to create drawing area")); return(FALSE); } // // Create the toolbar // if (!m_TB.Create(m_hwnd)) { ERROR_OUT(("Failed to create tool window")); return(FALSE); } // // Create the attributes group // The attributes group is on the bottom, underneath the // drawing area, above the status bar. // RECT rectAG; rectAG.left = clientRect.left; rectAG.right = clientRect.right; rectAG.top = drawingAreaRect.bottom; rectAG.bottom = rectAG.top + sizeAG.cy; if (!m_AG.Create(m_hwnd, &rectAG)) { ERROR_OUT(("Failed to create attributes group window")); return(FALSE); } // // Create the widths group. // The widths group is on the left side, underneath the tools group // SIZE sizeWG; RECT rectWG; // The widths group is on the left side, underneath the toolbar m_WG.GetNaturalSize(&sizeWG); rectWG.left = 0; rectWG.right = rectWG.left + sizeWG.cx; rectWG.bottom = rectAG.top; rectWG.top = rectWG.bottom - sizeWG.cy; if (!m_WG.Create(m_hwnd, &rectWG)) { ERROR_OUT(("Failed to create widths group window")); return(FALSE); } // // Create the status bar // m_hwndSB = ::CreateWindowEx(0, STATUSCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | CCS_NOPARENTALIGN | CCS_NOMOVEY | CCS_NORESIZE | SBARS_SIZEGRIP, clientRect.left, clientRect.bottom - STATUSBAR_HEIGHT, (clientRect.right - clientRect.left), STATUSBAR_HEIGHT, m_hwnd, 0, g_hInstance, NULL); if (!m_hwndSB) { ERROR_OUT(("Failed to create status bar window")); return(FALSE); } // Initialize the color, width and tool menus InitializeMenus(); m_currentMenuTool = IDM_SELECT; m_pCurrentTool = m_ToolArray[TOOL_INDEX(IDM_SELECT)]; OnSelectTool(m_currentMenuTool); m_hwndToolTip = ::CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, m_hwnd, NULL, g_hInstance, NULL); if (!m_hwndToolTip) { ERROR_OUT(("Unable to create tooltip window")); return(FALSE); } // Add a dead-area tooltip TOOLINFO ti; ZeroMemory(&ti, sizeof(ti)); ti.cbSize = sizeof(TOOLINFO); ti.uFlags = TTF_IDISHWND; ti.hwnd = m_hwnd; ti.uId = (UINT_PTR)m_hwnd; ::SendMessage(m_hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti); // Ensure the page buttons are disabled while starting UpdatePageButtons(); // If this is the first time we have created a clipboard object, // register the private Whiteboard formats. if (g_ClipboardFormats[CLIPBOARD_PRIVATE] == 0) { g_ClipboardFormats[CLIPBOARD_PRIVATE] = (int) ::RegisterClipboardFormat("NMWT126"); } m_bInitOk = TRUE; BOOL bSuccess = TRUE; // indicates whether window opened successfully // Get the position of the window from options RECT rectWindow; OPT_GetWindowRectOption(&rectWindow); ::MoveWindow(m_hwnd, rectWindow.left, rectWindow.top, rectWindow.right - rectWindow.left, rectWindow.bottom - rectWindow.top, FALSE ); // // Inititalize the fake GCC handle, it will be used when we are not in a conference and need // handles for workspaces/drawings/bitmaps etc... // g_localGCCHandle = 1; // // Create a standard workspace // if(g_pCurrentWorkspace) { m_drawingArea.Attach(g_pCurrentWorkspace); } else { if(g_numberOfWorkspaces < WB_MAX_WORKSPACES) { m_drawingArea.Detach(); WorkspaceObj * pObj; DBG_SAVE_FILE_LINE pObj = new WorkspaceObj(); pObj->AddToWorkspace(); g_pConferenceWorkspace = pObj; } } CheckMenuItem(IDM_STATUS_BAR_TOGGLE); CheckMenuItem(IDM_TOOL_BAR_TOGGLE); // // Start synced // Sync(); if(!OPT_GetBooleanOption(OPT_MAIN_STATUSBARVISIBLE, DFLT_MAIN_STATUSBARVISIBLE)) { OnStatusBarToggle(); } if(!OPT_GetBooleanOption(OPT_MAIN_TOOLBARVISIBLE, DFLT_MAIN_TOOLBARVISIBLE)) { OnToolBarToggle(); } ::ShowWindow(m_hwnd, iCommand); ::UpdateWindow(m_hwnd); // Update the window title with no file name UpdateWindowTitle(); // Return value indicating success or failure return(bSuccess); } // // // Function : OnMenuSelect // // Purpose : Update the text in the help bar // // void WbMainWindow::OnMenuSelect(UINT uiItemID, UINT uiFlags, HMENU hSysMenu) { UINT firstMenuId; UINT statusId; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnMenuSelect"); // // Work out the help ID for the menu item. We have to store this now // because when the user presses F1 from a menu item, we can't tell // which item it was. // if ((uiFlags & MF_POPUP) && (uiFlags & MF_SYSMENU)) { // // System menu selected // statusId = IDS_MENU_SYSTEM; } else if (uiFlags & MF_POPUP) { // get popup menu handle and first item (bug NM4db:463) HMENU hPopup = ::GetSubMenu( hSysMenu, uiItemID ); firstMenuId = ::GetMenuItemID( hPopup, 0 ); // figure out which popup it is so we can display the right help text switch (firstMenuId) { case IDM_NEW: statusId = IDS_MENU_FILE; break; case IDM_DELETE: statusId = IDS_MENU_EDIT; break; case IDM_TOOL_BAR_TOGGLE: statusId = IDS_MENU_VIEW; break; case IDM_EDITCOLOR: case IDM_TOOLS_START: statusId = IDS_MENU_TOOLS; break; case IDM_HELP: statusId = IDS_MENU_HELP; break; case IDM_WIDTH_1: // (added for bug NM4db:463) statusId = IDS_MENU_WIDTH; break; default: statusId = IDS_DEFAULT; break; } } else { // // A normal menu item has been selected // statusId = uiItemID; } // Set the new help text TCHAR szStatus[256]; if (::LoadString(g_hInstance, statusId, szStatus, 256)) { ::SetWindowText(m_hwndSB, szStatus); } } // // WbMainWindowProc() // Frame window message handler // LRESULT WbMainWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { LRESULT lResult = 0; WbMainWindow * pMain; pMain = (WbMainWindow *)::GetWindowLongPtr(hwnd, GWLP_USERDATA); switch (message) { case WM_NCCREATE: pMain = (WbMainWindow *)((LPCREATESTRUCT)lParam)->lpCreateParams; ASSERT(pMain); pMain->m_hwnd = hwnd; ::SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)pMain); goto DefWndProc; break; case WM_DESTROY: ShutDownHelp(); break; case WM_NCDESTROY: pMain->m_hwnd = NULL; break; case WM_SIZE: pMain->OnSize((UINT)wParam, (short)LOWORD(lParam), (short)HIWORD(lParam)); break; case WM_ACTIVATE: if (GET_WM_ACTIVATE_STATE(wParam, lParam) == WA_INACTIVE) { // Cancel the tooltip if it's around if (pMain->m_hwndToolTip) ::SendMessage(pMain->m_hwndToolTip, TTM_ACTIVATE, FALSE, 0); } goto DefWndProc; break; case WM_SETFOCUS: pMain->OnSetFocus(); break; case WM_CANCELMODE: pMain->OnCancelMode(); break; case WM_INITMENUPOPUP: pMain->OnInitMenuPopup((HMENU)wParam, LOWORD(lParam), HIWORD(lParam)); break; case WM_MENUSELECT: pMain->OnMenuSelect(GET_WM_MENUSELECT_CMD(wParam, lParam), GET_WM_MENUSELECT_FLAGS(wParam, lParam), GET_WM_MENUSELECT_HMENU(wParam, lParam)); break; case WM_MEASUREITEM: pMain->OnMeasureItem((UINT)wParam, (LPMEASUREITEMSTRUCT)lParam); break; case WM_DRAWITEM: pMain->OnDrawItem((UINT)wParam, (LPDRAWITEMSTRUCT)lParam); break; case WM_QUERYNEWPALETTE: lResult = pMain->OnQueryNewPalette(); break; case WM_PALETTECHANGED: pMain->OnPaletteChanged((HWND)wParam); break; case WM_HELP: pMain->OnCommand(IDM_HELP, 0, NULL); break; case WM_CLOSE: pMain->OnClose(); break; case WM_QUERYENDSESSION: lResult = pMain->OnQueryEndSession(); break; case WM_ENDSESSION: pMain->OnEndSession((UINT)wParam); break; case WM_SYSCOLORCHANGE: pMain->OnSysColorChange(); break; case WM_USER_PRIVATE_PARENTNOTIFY: pMain->OnParentNotify(GET_WM_PARENTNOTIFY_MSG(wParam, lParam)); break; case WM_GETMINMAXINFO: if (pMain) pMain->OnGetMinMaxInfo((LPMINMAXINFO)lParam); break; case WM_COMMAND: pMain->OnCommand(LOWORD(wParam), HIWORD(wParam), (HWND)lParam); break; case WM_NOTIFY: pMain->OnNotify((UINT)wParam, (NMHDR *)lParam); break; case WM_DROPFILES: pMain->OnDropFiles((HDROP)wParam); break; case WM_USER_DISPLAY_ERROR: pMain->OnDisplayError(wParam, lParam); break; case WM_USER_UPDATE_ATTRIBUTES: pMain->m_AG.DisplayTool(pMain->m_pCurrentTool); break; case WM_USER_LOAD_FILE: pMain->WB_LoadFile(g_PassedFileName); // Fall through. case WM_USER_BRING_TO_FRONT_WINDOW: pMain->BringToFront(); break; default: if (message == g_uConfShutdown) { lResult = pMain->OnConfShutdown(wParam, lParam); } else { DefWndProc: lResult = DefWindowProc(hwnd, message, wParam, lParam); } break; } return(lResult); } // // OnCommand() // Command dispatcher for the main window // void WbMainWindow::OnCommand(UINT cmd, UINT code, HWND hwndCtl) { switch (cmd) { // // FILE MENU // case IDM_NEW: OnNew(); break; case IDM_OPEN: OnOpen(); break; case IDM_SAVE: OnSave(FALSE); break; case IDM_SAVE_AS: OnSave(TRUE); break; case IDM_PRINT: OnPrint(); break; case IDM_EXIT: ::PostMessage(m_hwnd, WM_CLOSE, 0, 0); break; // // EDIT MENU // case IDM_DELETE: OnDelete(); break; case IDM_UNDELETE: OnUndelete(); break; case IDM_CUT: OnCut(); break; case IDM_COPY: OnCopy(); break; case IDM_PASTE: OnPaste(); break; case IDM_SELECTALL: OnSelectAll(); break; case IDM_BRING_TO_TOP: m_drawingArea.BringToTopSelection(TRUE, 0); break; case IDM_SEND_TO_BACK: m_drawingArea.SendToBackSelection(TRUE, 0); break; case IDM_CLEAR_PAGE: OnClearPage(); break; case IDM_DELETE_PAGE: OnDeletePage(); break; case IDM_PAGE_INSERT_AFTER: OnInsertPageAfter(); break; // // VIEW MENU // case IDM_TOOL_BAR_TOGGLE: OnToolBarToggle(); break; case IDM_STATUS_BAR_TOGGLE: OnStatusBarToggle(); break; case IDM_ZOOM: OnZoom(); break; // // TOOLS MENU // case IDM_SELECT: case IDM_PEN: case IDM_HIGHLIGHT: case IDM_TEXT: case IDM_ERASER: case IDM_LINE: case IDM_BOX: case IDM_FILLED_BOX: case IDM_ELLIPSE: case IDM_FILLED_ELLIPSE: OnSelectTool(cmd); break; case IDM_REMOTE: OnRemotePointer(); // // Are we turnig remote pointer on // if(m_pLocalRemotePointer) { //put us in select-tool mode OnSelectTool(IDM_SELECT); } break; case IDM_GRAB_AREA: OnGrabArea(); break; case IDM_GRAB_WINDOW: OnGrabWindow(); break; case IDM_SYNC: OnSync(); break; case IDM_LOCK: OnLock(); break; case IDM_COLOR: OnSelectColor(); break; case IDM_EDITCOLOR: m_AG.OnEditColors(); break; case IDM_FONT: OnChooseFont(); break; case IDM_WIDTH_1: case IDM_WIDTH_2: case IDM_WIDTH_3: case IDM_WIDTH_4: OnSelectWidth(cmd); break; // // HELP MENU // case IDM_ABOUT: OnAbout(); break; case IDM_HELP: ShowHelp(); break; // // PAGE BAR // case IDM_PAGE_FIRST: OnFirstPage(); break; case IDM_PAGE_PREV: OnPrevPage(); break; case IDM_PAGE_GOTO: OnGotoPage(); break; case IDM_PAGE_NEXT: OnNextPage(); break; case IDM_PAGE_LAST: OnLastPage(); break; // // SCROLLING // case IDM_PAGEUP: case IDM_PAGEDOWN: case IDM_SHIFTPAGEUP: case IDM_SHIFTPAGEDOWN: case IDM_HOME: case IDM_END: case IDM_LINEUP: case IDM_LINEDOWN: case IDM_SHIFTLINEUP: case IDM_SHIFTLINEDOWN: OnScrollAccelerator(cmd); break; case ID_NAV_TAB: ShiftFocus(m_hwnd, TRUE); break; case ID_NAV_SHIFT_TAB: ShiftFocus(m_hwnd, FALSE); break; } } // // // Function: OnInitMenuPopup // // Purpose: Process a WM_INITMENUPOPUP event // // void WbMainWindow::OnInitMenuPopup ( HMENU hMenu, UINT uiIndex, BOOL bSystemMenu ) { // Ignore the event if it relates to the system menu if (!bSystemMenu) { if (hMenu) { SetMenuStates(hMenu); m_hInitMenu = hMenu; } else { m_hInitMenu = NULL; } // Save the last menu we handled, so that we can alter its state // if necessary whilst it is still visible } } // // // Function: GetMenuWithItem // // Purpose: Return the menu which contains the specified item. // // HMENU WbMainWindow::GetMenuWithItem(HMENU hMenu, UINT uiID) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::GetMenuWithItem"); ASSERT(hMenu != NULL); HMENU hMenuResult = NULL; // Get the number ofitems in the menu UINT uiNumItems = ::GetMenuItemCount(hMenu); UINT uiPos; UINT uiNextID; // Look for the item through the menu for (uiPos = 0; uiPos < uiNumItems; uiPos++) { // Get the ID of the item at this position uiNextID = ::GetMenuItemID(hMenu, uiPos); if (uiNextID == uiID) { // We have found the item hMenuResult = hMenu; break; } } // If we have not yet found the item if (hMenuResult == NULL) { // Look through each of the submenus of the current menu HMENU hSubMenu; for (uiPos = 0; uiPos < uiNumItems; uiPos++) { // Get the ID of the item at this position uiNextID = ::GetMenuItemID(hMenu, uiPos); // If the item is a submenu if (uiNextID == -1) { // Get the submenu hSubMenu = ::GetSubMenu(hMenu, (int) uiPos); // Search the submenu hMenuResult = GetMenuWithItem(hSubMenu, uiID); if (hMenuResult != NULL) { // We have found the menu with the requested item break; } } } } return hMenuResult; } // // // Function: WbMainWindow::InitializeMenus // // Purpose: Initialise the menus: set up owner-drawn menu items and // those read from options file. // // void WbMainWindow::InitializeMenus(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::InitializeMenus"); // Make the width menu ownerdraw HMENU hMenu = GetMenuWithItem(::GetMenu(m_hwnd), IDM_WIDTH_1); if (hMenu != NULL) { // Change each entry to be ownerdraw (loop until failure) int iIndex; UINT uiId; int iCount = ::GetMenuItemCount(hMenu); for (iIndex = 0; iIndex < iCount; iIndex++) { uiId = ::GetMenuItemID(hMenu, iIndex); ::ModifyMenu(hMenu, iIndex, MF_BYPOSITION | MF_ENABLED | MF_OWNERDRAW, uiId, NULL); } } } // // // Function: CheckMenuItem // // Purpose: Check an item on the application menus (main and context // menu.) // // void WbMainWindow::CheckMenuItem(UINT uiId) { CheckMenuItemRecursive(::GetMenu(m_hwnd), uiId, MF_BYCOMMAND | MF_CHECKED); CheckMenuItemRecursive(m_hContextMenu, uiId, MF_BYCOMMAND | MF_CHECKED); CheckMenuItemRecursive(m_hGrobjContextMenu, uiId, MF_BYCOMMAND | MF_CHECKED); } // // // Function: UncheckMenuItem // // Purpose: Uncheck an item on the application menus (main and context // menus.) // // void WbMainWindow::UncheckMenuItem(UINT uiId) { CheckMenuItemRecursive(::GetMenu(m_hwnd), uiId, MF_BYCOMMAND | MF_UNCHECKED); CheckMenuItemRecursive(m_hContextMenu, uiId, MF_BYCOMMAND | MF_UNCHECKED); CheckMenuItemRecursive(m_hGrobjContextMenu, uiId, MF_BYCOMMAND | MF_UNCHECKED); } // // // Function: CheckMenuItemRecursive // // Purpose: Check or uncheck an item on the any of the Whiteboard menus. // This function recursively searches through the menus until // it finds the specified item. The menu item Ids must be // unique for this function to work. // // BOOL WbMainWindow::CheckMenuItemRecursive(HMENU hMenu, UINT uiId, BOOL bCheck) { UINT uiNumItems = ::GetMenuItemCount(hMenu); // Attempt to check the menu item UINT uiCheck = MF_BYCOMMAND | (bCheck ? MF_CHECKED : MF_UNCHECKED); // A return code of -1 from CheckMenuItem implies that // the menu item was not found BOOL bChecked = ((::CheckMenuItem(hMenu, uiId, uiCheck) == -1) ? FALSE : TRUE); if (bChecked) { // // If this item is on the active menu, ensure it's redrawn now // if (hMenu == m_hInitMenu) { InvalidateActiveMenu(); } } else { UINT uiPos; HMENU hSubMenu; // Recurse through the submenus of the specified menu for (uiPos = 0; uiPos < uiNumItems; uiPos++) { // Assume that the next item is a submenu // and try to get a pointer to it hSubMenu = ::GetSubMenu(hMenu, (int)uiPos); // NULL return implies the item is a not submenu if (hSubMenu != NULL) { // Item is a submenu, make recursive call to search it bChecked = CheckMenuItemRecursive(hSubMenu, uiId, bCheck); if (bChecked) { // We have found the item break; } } } } return bChecked; } // // // Function: InvalidateActiveMenu // // Purpose: If a menu is currently active, gray items according to // the current state, and force it to redraw. // // void WbMainWindow::InvalidateActiveMenu() { if (m_hInitMenu != NULL) { // A menu is displayed, so set the state appropriately and force a // repaint to show the new state SetMenuStates(m_hInitMenu); ::RedrawWindow(::GetTopWindow(::GetDesktopWindow()), NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_ERASE | RDW_ERASENOW | RDW_ALLCHILDREN); } } // // // Function: SetMenuState // // Purpose: Sets menu contents to their correct enabled/disabled state // // void WbMainWindow::SetMenuStates(HMENU hInitMenu) { BOOL bLocked; BOOL bPageOrderLocked; BOOL bPresentationMode; UINT uiEnable; UINT uiCountPages; BOOL bIdle; BOOL bSelected; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::SetMenuStates"); // // Check menu exists // if (hInitMenu == NULL) { WARNING_OUT(("Menu doesn't exist")); return; } HMENU hMainMenu = ::GetMenu(m_hwnd); // Get the window's main menu and check that the menu // now being popped up is one on the top-level. (We do not // seem to be able to associate the index number passed with // sub-menus easily.) if ((hInitMenu != m_hContextMenu) && (hInitMenu != m_hGrobjContextMenu)) { BOOL bTopLevel = FALSE; int nCount = ::GetMenuItemCount(hMainMenu); for (int nNext = 0; nNext < nCount; nNext++) { HMENU hNextMenu = ::GetSubMenu(hMainMenu, nNext); if (hNextMenu != NULL) { if (hNextMenu == hInitMenu) { bTopLevel = TRUE; break; } } } // not a top level, so leave the function now if (!bTopLevel) { TRACE_DEBUG(("Not top-level menu")); return; } } BOOL bImNotLocked = (g_pCurrentWorkspace ? (g_pCurrentWorkspace->GetUpdatesEnabled() ? TRUE : g_pNMWBOBJ->m_LockerID == g_MyMemberID) :FALSE); BOOL bIsThereAnything = IsThereAnythingInAnyWorkspace(); BOOL bIsThereSomethig = bImNotLocked && (g_pCurrentWorkspace && g_pCurrentWorkspace->GetHead() != NULL) ? TRUE : FALSE; BOOL bIsThereTrash = bImNotLocked && (g_pTrash->GetHead() != NULL) && (g_pCurrentWorkspace != NULL); BOOL bIsSomethingSelected = bImNotLocked && g_pDraw->GraphicSelected() && g_pDraw->GetSelectedGraphic()->GraphicTool() != TOOLTYPE_REMOTEPOINTER && g_pCurrentWorkspace != NULL; BOOL bIsSynced = g_pDraw->IsSynced(); BOOL bOnlyOnePage = (g_pListOfWorkspaces->GetHead() == g_pListOfWorkspaces->GetTail()); // // Functions which are disabled when contents is locked // uiEnable = MF_BYCOMMAND | (bImNotLocked && bIsSynced ? MF_ENABLED : MF_GRAYED); // // File menu // ::EnableMenuItem(hInitMenu, IDM_NEW, uiEnable); ::EnableMenuItem(hInitMenu, IDM_OPEN, uiEnable); uiEnable = MF_BYCOMMAND | (bIsThereAnything ? MF_ENABLED : MF_GRAYED); ::EnableMenuItem(hInitMenu, IDM_SAVE, uiEnable); ::EnableMenuItem(hInitMenu, IDM_SAVE_AS, uiEnable); ::EnableMenuItem(hInitMenu, IDM_PRINT, uiEnable); // // Tools menu // uiEnable = MF_BYCOMMAND | (bImNotLocked ? MF_ENABLED : MF_GRAYED); ::EnableMenuItem(hInitMenu, IDM_SELECT, uiEnable); ::EnableMenuItem(hInitMenu, IDM_ERASER, uiEnable); ::EnableMenuItem(hInitMenu, IDM_PEN, uiEnable); ::EnableMenuItem(hInitMenu, IDM_HIGHLIGHT, uiEnable); ::EnableMenuItem(hInitMenu, IDM_GRAB_AREA, uiEnable); ::EnableMenuItem(hInitMenu, IDM_GRAB_WINDOW, uiEnable); ::EnableMenuItem(hInitMenu, IDM_LINE, uiEnable); ::EnableMenuItem(hInitMenu, IDM_BOX, uiEnable); ::EnableMenuItem(hInitMenu, IDM_FILLED_BOX, uiEnable); ::EnableMenuItem(hInitMenu, IDM_ELLIPSE, uiEnable); ::EnableMenuItem(hInitMenu, IDM_FILLED_ELLIPSE, uiEnable); ::EnableMenuItem(hInitMenu, IDM_TEXT, m_drawingArea.Zoomed() ? MF_BYCOMMAND | MF_GRAYED : uiEnable); ::EnableMenuItem(hInitMenu, IDM_ZOOM, uiEnable); ::EnableMenuItem(hInitMenu, IDM_REMOTE, uiEnable); ::EnableMenuItem(hInitMenu, IDM_FONT, MF_BYCOMMAND | bImNotLocked && m_pCurrentTool->HasFont() ? MF_ENABLED : MF_GRAYED); ::EnableMenuItem(hInitMenu, IDM_EDITCOLOR, MF_BYCOMMAND | bImNotLocked && m_pCurrentTool->HasColor() ? MF_ENABLED : MF_GRAYED); HMENU hToolsMenu = ::GetSubMenu(hMainMenu, MENUPOS_TOOLS); uiEnable = (bImNotLocked && m_pCurrentTool->HasWidth()) ? MF_ENABLED : MF_GRAYED; if (hToolsMenu == hInitMenu ) { ::EnableMenuItem(hToolsMenu, TOOLSPOS_WIDTH, MF_BYPOSITION | uiEnable ); } UINT i; UINT uIdmCurWidth = 0; if( uiEnable == MF_ENABLED ) uIdmCurWidth = m_pCurrentTool->GetWidthIndex() + IDM_WIDTH_1; for( i=IDM_WIDTH_1; i<=IDM_WIDTH_4; i++ ) { ::EnableMenuItem(hInitMenu, i, uiEnable ); if( uiEnable == MF_ENABLED ) { if( uIdmCurWidth == i ) ::CheckMenuItem(hInitMenu, i, MF_CHECKED ); else ::CheckMenuItem(hInitMenu, i, MF_UNCHECKED ); } } // // Edit Menu // uiEnable = MF_BYCOMMAND | (bIsSomethingSelected? MF_ENABLED : MF_GRAYED); ::EnableMenuItem(hInitMenu, IDM_DELETE, uiEnable ); ::EnableMenuItem(hInitMenu, IDM_CUT, uiEnable ); ::EnableMenuItem(hInitMenu, IDM_COPY, uiEnable); ::EnableMenuItem(hInitMenu, IDM_BRING_TO_TOP, uiEnable); ::EnableMenuItem(hInitMenu, IDM_SEND_TO_BACK, uiEnable); uiEnable = MF_BYCOMMAND | (bIsThereSomethig ?MF_ENABLED : MF_GRAYED); ::EnableMenuItem(hInitMenu, IDM_CLEAR_PAGE, uiEnable); ::EnableMenuItem(hInitMenu, IDM_SELECTALL, uiEnable); ::EnableMenuItem(hInitMenu, IDM_PASTE, MF_BYCOMMAND | CLP_AcceptableClipboardFormat() && bImNotLocked ? MF_ENABLED : MF_GRAYED); ::EnableMenuItem(hInitMenu, IDM_UNDELETE, MF_BYCOMMAND | (bIsThereTrash? MF_ENABLED : MF_GRAYED) ); ::EnableMenuItem(hInitMenu, IDM_DELETE_PAGE, MF_BYCOMMAND | bIsSynced && bImNotLocked && !bOnlyOnePage ? MF_ENABLED : MF_GRAYED); ::EnableMenuItem(hInitMenu, IDM_PAGE_INSERT_AFTER, MF_BYCOMMAND | bIsSynced && bImNotLocked && g_numberOfWorkspaces < WB_MAX_WORKSPACES ? MF_ENABLED : MF_GRAYED); // // View Menu // ::EnableMenuItem(hInitMenu, IDM_SYNC, MF_BYCOMMAND | (bImNotLocked && !m_drawingArea.IsLocked()? MF_ENABLED : MF_GRAYED)); ::EnableMenuItem(hInitMenu, IDM_LOCK, MF_BYCOMMAND |((bImNotLocked && bIsSynced) ? MF_ENABLED : MF_GRAYED)); // // Enable toolbar // EnableToolbar(bImNotLocked); // // Enable page controls // m_AG.EnablePageCtrls(bImNotLocked); } // // // Function: WbMainWindow destructor // // Purpose: Tidy up main window on destruction. // // WbMainWindow::~WbMainWindow() { // // Destroy the tooltip window // if (m_hwndToolTip) { ::DestroyWindow(m_hwndToolTip); m_hwndToolTip = NULL; } if (m_hGrobjContextMenuBar != NULL) { ::DestroyMenu(m_hGrobjContextMenuBar); m_hGrobjContextMenuBar = NULL; } m_hGrobjContextMenu = NULL; if (m_hContextMenuBar != NULL) { ::DestroyMenu(m_hContextMenuBar); m_hContextMenuBar = NULL; } m_hContextMenu = NULL; POSITION position = m_pageToPosition.GetHeadPosition(); PAGE_POSITION * pPoint; while (position) { pPoint = (PAGE_POSITION*)m_pageToPosition.GetNext(position); delete pPoint; } m_pageToPosition.EmptyList(); // // Free the palette // if (g_hRainbowPaletteDisplay) { if (g_pDraw && g_pDraw->m_hDCCached) { // Select out the rainbow palette so we can delete it ::SelectPalette(g_pDraw->m_hDCCached, (HPALETTE)::GetStockObject(DEFAULT_PALETTE), TRUE); } DeletePalette(g_hRainbowPaletteDisplay); g_hRainbowPaletteDisplay = NULL; } g_bPalettesInitialized = FALSE; g_bUsePalettes = FALSE; if (g_pIcons) { delete g_pIcons; g_pIcons = NULL; } if(m_pTitleFileName) { delete m_pTitleFileName; m_pTitleFileName = NULL; } // // Delete all the objectsb in global lists // DeleteAllWorkspaces(FALSE); ASSERT(g_pListOfWorkspaces); g_pListOfWorkspaces->EmptyList(); ASSERT(g_pListOfObjectsThatRequestedHandles); g_pListOfObjectsThatRequestedHandles->EmptyList(); g_numberOfWorkspaces = 0; // // Delete objects in limbo, sitting in the undelete trash // ASSERT(g_pTrash); T126Obj* pGraphic; // // Burn trash // pGraphic = (T126Obj *)g_pTrash->RemoveTail(); while (pGraphic != NULL) { delete pGraphic; pGraphic = (T126Obj *) g_pTrash->RemoveTail(); } DeleteAllRetryPDUS(); DestroyToolArray(); ::DestroyWindow(m_hwnd); ::UnregisterClass(szMainClassName, g_hInstance); } // // OnToolHitTest() // This handles tooltips for child windows. // int WbMainWindow::OnToolHitTest(POINT pt, TOOLINFO* pTI) const { HWND hwnd; int status; int nHit = -1; ASSERT(!IsBadWritePtr(pTI, sizeof(TOOLINFO))); hwnd = ::ChildWindowFromPointEx(m_hwnd, pt, CWP_SKIPINVISIBLE); if (hwnd == m_AG.m_hwnd) { ::MapWindowPoints(m_hwnd, m_AG.m_hwnd, &pt, 1); hwnd = ::ChildWindowFromPointEx(m_AG.m_hwnd, pt, CWP_SKIPINVISIBLE); if (hwnd != NULL) { nHit = ::GetDlgCtrlID(hwnd); pTI->hwnd = m_hwnd; pTI->uId = (UINT_PTR)hwnd; pTI->uFlags |= TTF_IDISHWND; pTI->lpszText = LPSTR_TEXTCALLBACK; return(nHit); } } else if (hwnd == m_WG.m_hwnd) { int iItem; ::MapWindowPoints(m_hwnd, m_WG.m_hwnd, &pt, 1); iItem = m_WG.ItemFromPoint(pt.x, pt.y); pTI->hwnd = m_WG.m_hwnd; pTI->uId = iItem; // Since the area isn't a window, we must fill in the rect ourself m_WG.GetItemRect(iItem, &pTI->rect); pTI->lpszText = LPSTR_TEXTCALLBACK; return(iItem); } else if (hwnd == m_TB.m_hwnd) { RECT rect; TBBUTTON button; int i; for (i = 0; i < TOOLBAR_MAXBUTTON; i++) { if (::SendMessage(m_TB.m_hwnd, TB_GETITEMRECT, i, (LPARAM)&rect) && ::PtInRect(&rect, pt) && ::SendMessage(m_TB.m_hwnd, TB_GETBUTTON, i, (LPARAM)&button) && !(button.fsStyle & TBSTYLE_SEP)) { nHit = button.idCommand; pTI->hwnd = m_TB.m_hwnd; pTI->uId = nHit; pTI->rect = rect; pTI->lpszText = LPSTR_TEXTCALLBACK; // found matching rect, return the ID of the button return(nHit); } } } return(-1); } // // WinHelp() wrapper // LRESULT WbMainWindow::ShowHelp(void) { HWND hwndCapture; // Get the main window out of any mode ::SendMessage(m_hwnd, WM_CANCELMODE, 0, 0); // Cancel any other tracking if (hwndCapture = ::GetCapture()) ::SendMessage(hwndCapture, WM_CANCELMODE, 0, 0); // finally, run the NetMeeting Help engine ShowNmHelp(s_cszHtmlHelpFile); return S_OK; } // // TimedDlgProc() // This puts up a visible or invisible dialog which only goes away when // an event occurs or a certain amount of time has passed. We store the // DialogBoxParam parameter, a TMDLG pointer, in our user data. That is // from the stack of the DialogBoxParam() caller, so it is valid until that // function returns, which won't be until a bit after the dialog has been // destroyed. // INT_PTR CALLBACK TimedDlgProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam) { BOOL fHandled = FALSE; TMDLG * ptm; switch (uMessage) { case WM_INITDIALOG: ptm = (TMDLG *)lParam; ASSERT(!IsBadWritePtr(ptm, sizeof(TMDLG))); ::SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)ptm); // // Set the WbMainWindow hwnd // if (ptm->bLockNotEvent) { g_pMain->m_hwndWaitForLockDlg = hwnd; } else { g_pMain->m_hwndWaitForEventDlg = hwnd; } // // Set max timer // ::SetTimer(hwnd, TIMERID_MAXDISPLAY, ptm->uiMaxDisplay, NULL); // // Change the cursor if invisible // if (!ptm->bVisible) ::SetCursor(::LoadCursor(NULL, IDC_WAIT)); fHandled = TRUE; break; case WM_TIMER: ASSERT(wParam == TIMERID_MAXDISPLAY); // End the dialog--since we timed out, it acts like cancel ::SendMessage(hwnd, WM_COMMAND, MAKELONG(IDCANCEL, BN_CLICKED), 0); fHandled = TRUE; break; case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: case IDCANCEL: if (GET_WM_COMMAND_CMD(wParam, lParam) == BN_CLICKED) { ptm = (TMDLG *)::GetWindowLongPtr(hwnd, GWLP_USERDATA); ASSERT(!IsBadWritePtr(ptm, sizeof(TMDLG))); // Clear out the HWND variable if (ptm->bLockNotEvent) { g_pMain->m_hwndWaitForLockDlg = NULL; } else { g_pMain->m_hwndWaitForEventDlg = NULL; } // Restore the cursor if (!ptm->bVisible) ::SetCursor(::LoadCursor(NULL, IDC_ARROW)); ::KillTimer(hwnd, TIMERID_MAXDISPLAY); ::EndDialog(hwnd, GET_WM_COMMAND_ID(wParam, lParam)); } break; } fHandled = TRUE; break; // // Don't let these dialogs be killed by any other means than our // getting an event or timing out. // case WM_CLOSE: fHandled = TRUE; break; } return(fHandled); } // // FilterMessage() // // This does tooltip message filtering, then translates accelerators. // BOOL WbMainWindow::FilterMessage(MSG* pMsg) { BOOL bResult = FALSE; if ((pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST) || (pMsg->message == WM_LBUTTONDOWN || pMsg->message == WM_LBUTTONDBLCLK) || (pMsg->message == WM_RBUTTONDOWN || pMsg->message == WM_RBUTTONDBLCLK) || (pMsg->message == WM_MBUTTONDOWN || pMsg->message == WM_MBUTTONDBLCLK) || (pMsg->message == WM_NCLBUTTONDOWN || pMsg->message == WM_NCLBUTTONDBLCLK) || (pMsg->message == WM_NCRBUTTONDOWN || pMsg->message == WM_NCRBUTTONDBLCLK) || (pMsg->message == WM_NCMBUTTONDOWN || pMsg->message == WM_NCMBUTTONDBLCLK)) { // Cancel any tooltip up ::SendMessage(m_hwndToolTip, TTM_ACTIVATE, FALSE, 0); } // handle tooltip messages (some messages cancel, some may cause it to popup) if ((pMsg->message == WM_MOUSEMOVE || pMsg->message == WM_NCMOUSEMOVE || pMsg->message == WM_LBUTTONUP || pMsg->message == WM_RBUTTONUP || pMsg->message == WM_MBUTTONUP) && (GetKeyState(VK_LBUTTON) >= 0 && GetKeyState(VK_RBUTTON) >= 0 && GetKeyState(VK_MBUTTON) >= 0)) { #if 0 // // If this mouse move isn't for a descendant of the main window, skip // it. For example, when the tooltip is shown, it gets a mousemove // to itself, which if we didn't check for it, would cause us to // immediately dismiss this! // HWND hwndTmp = pMsg->hwnd; while (hwndTmp && (::GetWindowLong(hwndTmp, GWL_STYLE) & WS_CHILD)) { hwndTmp = ::GetParent(hwndTmp); } if (hwndTmp != m_hwnd) { // This is not for us, it's for another top level window in // our app. goto DoneToolTipFiltering; } #endif // determine which tool was hit POINT pt; pt = pMsg->pt; ::ScreenToClient(m_hwnd, &pt); TOOLINFO tiHit; ZeroMemory(&tiHit, sizeof(tiHit)); tiHit.cbSize = sizeof(TOOLINFO); int nHit = OnToolHitTest(pt, &tiHit); if (m_nLastHit != nHit) { if (nHit != -1) { // add new tool and activate the tip if (!::SendMessage(m_hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&tiHit)) { ERROR_OUT(("TTM_ADDTOOL failed")); } if (::GetActiveWindow() == m_hwnd) { // allow the tooltip to popup when it should ::SendMessage(m_hwndToolTip, TTM_ACTIVATE, TRUE, 0); // bring the tooltip window above other popup windows ::SetWindowPos(m_hwndToolTip, HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOMOVE); } } // relay mouse event before deleting old tool ::SendMessage(m_hwndToolTip, TTM_RELAYEVENT, 0, (LPARAM)pMsg); // now safe to delete the old tool if (m_tiLastHit.cbSize != 0) ::SendMessage(m_hwndToolTip, TTM_DELTOOL, 0, (LPARAM)&m_tiLastHit); m_nLastHit = nHit; m_tiLastHit = tiHit; } else { // relay mouse events through the tooltip if (nHit != -1) ::SendMessage(m_hwndToolTip, TTM_RELAYEVENT, 0, (LPARAM)pMsg); } } #if 0 DoneToolTipFiltering: #endif // Assume we will use the main accelerator table HACCEL hAccelTable = m_hAccelTable; // If this window has focus, just continue HWND hwndFocus = ::GetFocus(); if (hwndFocus && (hwndFocus != m_hwnd)) { // Check whether an edit field in the pages group has the focus if (m_AG.IsChildEditField(hwndFocus)) { hAccelTable = m_hAccelPagesGroup; } // Check whether text editor has the focus and is active else if ( (hwndFocus == m_drawingArea.m_hwnd) && (m_drawingArea.TextEditActive())) { // Let editbox do its own acceleration. hAccelTable = NULL; } } return ( (hAccelTable != NULL) && ::TranslateAccelerator(m_hwnd, hAccelTable, pMsg)); } // // // Function: OnDisplayError // // Purpose: Display an error message // // void WbMainWindow::OnDisplayError(WPARAM uiFEReturnCode, LPARAM uiDCGReturnCode) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnDisplayError"); // Only continue if we are not currently displaying an error if (!m_bDisplayingError) { // Show that we are currently displaying an error message m_bDisplayingError = TRUE; // Display the error ::ErrorMessage((UINT)uiFEReturnCode, (UINT)uiDCGReturnCode); // Show that we are no longer displaying an error m_bDisplayingError = FALSE; } } // // // Function: OnPaletteChanged // // Purpose: The palette has changed. // // void WbMainWindow::OnPaletteChanged(HWND hwndPalette) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnPaletteChanged"); if ((hwndPalette != m_hwnd) && (hwndPalette != m_drawingArea.m_hwnd)) { // Tell the drawing area to realize its palette m_drawingArea.RealizePalette( TRUE ); } } // // // Function: OnQueryNewPalette // // Purpose: We are getting focus and must realize our palette // // LRESULT WbMainWindow::OnQueryNewPalette(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnQueryNewPalette"); // Tell the drawing area to realize its palette m_drawingArea.RealizePalette( FALSE ); return TRUE; } // // // Function: PopupContextMenu // // Purpose: Popup the context menu for the drawing area. This is called // by the drawing area window on a right mouse click. // // void WbMainWindow::PopupContextMenu(int x, int y) { POINT surfacePos; RECT clientRect; T126Obj * pGraphic; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::PopupContextMenu"); surfacePos.x = x; surfacePos.y = y; m_drawingArea.ClientToSurface(&surfacePos); if( (pGraphic = m_drawingArea.GetHitObject( surfacePos )) != NULL && pGraphic->GraphicTool() != TOOLTYPE_REMOTEPOINTER ) { if(!pGraphic->IsSelected() ) { g_pDraw->SelectGraphic(pGraphic); } // selector tool is active, and one or more objects are selected m_hInitMenu = m_hGrobjContextMenu; } else { // no current selection, show drawing menu m_hInitMenu = m_hContextMenu; } // set up current menu state SetMenuStates(m_hInitMenu); // pop it up ::GetClientRect(m_drawingArea.m_hwnd, &clientRect); ::MapWindowPoints(m_drawingArea.m_hwnd, NULL, (LPPOINT)&clientRect.left, 2); ::TrackPopupMenu(m_hInitMenu, TPM_RIGHTALIGN | TPM_RIGHTBUTTON, x + clientRect.left, y + clientRect.top, 0, m_hwnd, NULL); // reset m_hInitMenu to indicate the popup menu isn't being shown anymore m_hInitMenu = NULL; } // // // Function: OnSize // // Purpose: The window has been resized. // // void WbMainWindow::OnSize(UINT nType, int cx, int cy ) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnSize"); // Only process this message if the window is not minimized if (nType != SIZE_MINIMIZED) { // The user's view has changed PositionUpdated(); if (m_bStatusBarOn) { ::ShowWindow(m_hwndSB, SW_HIDE); } // Resize the subpanes of the window ResizePanes(); // Show it again if (m_bStatusBarOn) { ::ShowWindow(m_hwndSB, SW_SHOW); } // If the status has changed, set the option if (m_uiWindowSize != nType) { m_uiWindowSize = nType; // Write the new option values to file OPT_SetBooleanOption(OPT_MAIN_MAXIMIZED, (m_uiWindowSize == SIZE_MAXIMIZED)); OPT_SetBooleanOption(OPT_MAIN_MINIMIZED, (m_uiWindowSize == SIZE_MINIMIZED)); } } } // // // Function: SaveWindowPosition // // Purpose: Save the current window position to the options file. // // void WbMainWindow::SaveWindowPosition(void) { RECT rectWindow; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::SaveWindowPosition"); // Get the new window rectangle ::GetWindowRect(m_hwnd, &rectWindow); // Write the new option values to file OPT_SetWindowRectOption(&rectWindow); } // // // Function: ResizePanes // // Purpose: Resize the subpanes of the main window. // // void WbMainWindow::ResizePanes(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::ResizePanes"); // // // The client area is organized as follows: // // ------------------------------------- // | | | // | T | | // | o | Drawing Area | // | o | | // | l | | // | s | | // |---| | // | W | | // | i | | // | d | | // | t | | // | h | | // | s | | // |-----------------------------------| // | Attributes (colors) | Pages | // |-----------------------------------| // | Status | // ------------------------------------- // // RECT clientRect; RECT rectStatusBar; RECT rectToolBar; RECT rectWG; RECT rectAG; RECT rectDraw; SIZE size; SIZE sizeAG; // Get the client rectangle ::GetClientRect(m_hwnd, &clientRect); rectStatusBar = clientRect; // Resize the help bar and progress meter if (m_bStatusBarOn) { rectStatusBar.top = rectStatusBar.bottom - STATUSBAR_HEIGHT; ::MoveWindow(m_hwndSB, rectStatusBar.left, rectStatusBar.top, rectStatusBar.right - rectStatusBar.left, rectStatusBar.bottom - rectStatusBar.top, TRUE); } else { // Status bar is off - set it's height to zero rectStatusBar.top = rectStatusBar.bottom; } // Resize the tool and width windows m_TB.GetNaturalSize(&size); rectToolBar.left = 0; rectToolBar.right = rectToolBar.left + size.cx; rectToolBar.top = 0; rectToolBar.bottom = rectToolBar.top + size.cy; m_WG.GetNaturalSize(&size); rectWG.left = rectToolBar.left; rectWG.top = rectToolBar.bottom; rectWG.bottom = rectWG.top + size.cy; if (!m_bToolBarOn) { // Toolbar is either off or floating - set its width to zero rectToolBar.right = rectToolBar.left; } rectWG.right = rectToolBar.right; // Position attribute group m_AG.GetNaturalSize(&sizeAG); ::MoveWindow(m_AG.m_hwnd, rectToolBar.left, rectStatusBar.top - sizeAG.cy, clientRect.right - rectToolBar.left, sizeAG.cy, TRUE); // finish fiddling with tools and widths bars if (m_bToolBarOn) { // // We make the toolbar, which includes the width bar, extend all // down the left side. // rectToolBar.bottom = rectStatusBar.top - sizeAG.cy; rectWG.left += TOOLBAR_MARGINX; rectWG.right -= 2*TOOLBAR_MARGINX; ::MoveWindow(m_TB.m_hwnd, rectToolBar.left, rectToolBar.top, rectToolBar.right - rectToolBar.left, rectToolBar.bottom - rectToolBar.top, TRUE); ::MoveWindow(m_WG.m_hwnd, rectWG.left, rectWG.top, rectWG.right - rectWG.left, rectWG.bottom - rectWG.top, TRUE); ::BringWindowToTop(m_WG.m_hwnd); } // Resize the drawing pane rectDraw = clientRect; rectDraw.bottom = rectStatusBar.top - sizeAG.cy; rectDraw.left = rectToolBar.right; ::MoveWindow(m_drawingArea.m_hwnd, rectDraw.left, rectDraw.top, rectDraw.right - rectDraw.left, rectDraw.bottom - rectDraw.top, TRUE); // Check to see if Width group is overlapping Attributes group. This can happen if // the menu bar has wrapped because the window isn't wide enough (bug 424) RECT crWidthWnd; RECT crAttrWnd; ::GetWindowRect(m_WG.m_hwnd, &crWidthWnd); ::GetWindowRect(m_AG.m_hwnd, &crAttrWnd); if (crAttrWnd.top < crWidthWnd.bottom) { // the menu bar has wrapped and our height placements are wrong. Adjust window // by difference and try again RECT crMainWnd; ::GetWindowRect(m_hwnd, &crMainWnd); crMainWnd.bottom += (crWidthWnd.bottom - crAttrWnd.top + ::GetSystemMetrics(SM_CYFIXEDFRAME)); ::MoveWindow(m_hwnd, crMainWnd.left, crMainWnd.top, crMainWnd.right - crMainWnd.left, crMainWnd.bottom - crMainWnd.top, FALSE); // this is going to recurse but the adjustment will happen only once..... } } // // // Function: WbMainWindow::OnGetMinMaxInfo // // Purpose: Set the minimum and maximum tracking sizes of the window // // void WbMainWindow::OnGetMinMaxInfo(LPMINMAXINFO lpmmi) { if (m_TB.m_hwnd == NULL) return; // not ready to do this yet SIZE csFrame; SIZE csSeparator; SIZE csAG; SIZE csToolBar; SIZE csWidthBar; SIZE csMaxSize; SIZE csScrollBars; csFrame.cx = ::GetSystemMetrics(SM_CXSIZEFRAME); csFrame.cy = ::GetSystemMetrics(SM_CYSIZEFRAME); csSeparator.cx = ::GetSystemMetrics(SM_CXEDGE); csSeparator.cy = ::GetSystemMetrics(SM_CYEDGE); csScrollBars.cx = ::GetSystemMetrics(SM_CXVSCROLL); csScrollBars.cy = ::GetSystemMetrics(SM_CYHSCROLL); m_AG.GetNaturalSize(&csAG); m_TB.GetNaturalSize(&csToolBar); m_WG.GetNaturalSize(&csWidthBar); // Set the minimum width and height of the window lpmmi->ptMinTrackSize.x = csFrame.cx + csAG.cx + csFrame.cx; lpmmi->ptMinTrackSize.y = csFrame.cy + GetSystemMetrics( SM_CYCAPTION ) + GetSystemMetrics( SM_CYMENU ) + csToolBar.cy + csWidthBar.cy + csSeparator.cy + csAG.cy + csSeparator.cy + csFrame.cy + STATUSBAR_HEIGHT; // // Retrieves the size of the work area on the primary display monitor. The work // area is the portion of the screen not obscured by the system taskbar or by // application desktop toolbars // RECT rcWorkArea; ::SystemParametersInfo( SPI_GETWORKAREA, 0, (&rcWorkArea), NULL ); csMaxSize.cx = rcWorkArea.right - rcWorkArea.left; csMaxSize.cy = rcWorkArea.bottom - rcWorkArea.top; lpmmi->ptMaxPosition.x = 0; lpmmi->ptMaxPosition.y = 0; lpmmi->ptMaxSize.x = csMaxSize.cx; lpmmi->ptMaxSize.y = csMaxSize.cy; lpmmi->ptMaxTrackSize.x = csMaxSize.cx; lpmmi->ptMaxTrackSize.y = csMaxSize.cy; } // // // Function: WbMainWindow::CreateContextMenus // // Purpose: Create the pop-up context menus: used within the application // drawing area. // // BOOL WbMainWindow::CreateContextMenus(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::CreateContextMenus"); m_hContextMenuBar = ::LoadMenu(g_hInstance, MAKEINTRESOURCE(CONTEXTMENU)); if (!m_hContextMenuBar) { ERROR_OUT(("Failed to create context menu")); DefaultExceptionHandler(WBFE_RC_WINDOWS, 0); return FALSE; } m_hContextMenu = ::GetSubMenu(m_hContextMenuBar, 0); m_hGrobjContextMenuBar = ::LoadMenu(g_hInstance, MAKEINTRESOURCE(GROBJMENU)); if (!m_hGrobjContextMenuBar) { ERROR_OUT(("Failed to create grobj context menu")); DefaultExceptionHandler(WBFE_RC_WINDOWS, 0); return FALSE; } m_hGrobjContextMenu = ::GetSubMenu(m_hGrobjContextMenuBar, 0); // make parts of m_hGrobjContextMenu be owner draw ::ModifyMenu(m_hGrobjContextMenu, IDM_WIDTH_1, MF_ENABLED | MF_OWNERDRAW, IDM_WIDTH_1, NULL); ::ModifyMenu(m_hGrobjContextMenu, IDM_WIDTH_2, MF_ENABLED | MF_OWNERDRAW, IDM_WIDTH_2, NULL); ::ModifyMenu(m_hGrobjContextMenu, IDM_WIDTH_3, MF_ENABLED | MF_OWNERDRAW, IDM_WIDTH_3, NULL); ::ModifyMenu(m_hGrobjContextMenu, IDM_WIDTH_4, MF_ENABLED | MF_OWNERDRAW, IDM_WIDTH_4, NULL); return TRUE; } // // // Function: WbMainWindow::OnMeasureItem // // Purpose: Return the size of an item in the widths menu // // void WbMainWindow::OnMeasureItem ( int nIDCtl, LPMEASUREITEMSTRUCT measureStruct ) { // Check that this is for a color menu item if ( (measureStruct->itemID >= IDM_WIDTHS_START) && (measureStruct->itemID < IDM_WIDTHS_END)) { measureStruct->itemWidth = ::GetSystemMetrics(SM_CXMENUCHECK) + (2 * CHECKMARK_BORDER_X) + COLOR_MENU_WIDTH; measureStruct->itemHeight = ::GetSystemMetrics(SM_CYMENUCHECK) + (2 * CHECKMARK_BORDER_Y); } } // // // Function: WbMainWindow::OnDrawItem // // Purpose: Draw an item in the color menu // // void WbMainWindow::OnDrawItem ( int nIDCtl, LPDRAWITEMSTRUCT drawStruct ) { COLORREF crMenuBackground; COLORREF crMenuText; HPEN hOldPen; HBRUSH hOldBrush; COLORREF crOldBkgnd; COLORREF crOldText; int nOldBkMode; HBITMAP hbmp = NULL; BITMAP bitmap; UINT uiCheckWidth; UINT uiCheckHeight; RECT rect; RECT rectCheck; RECT rectLine; HDC hMemDC; UINT uiWidthIndex; UINT uiWidth; HPEN hPenMenu; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnDrawItem"); // Check that this is a width menu item if( (drawStruct->itemID < IDM_WIDTHS_START) || (drawStruct->itemID >= IDM_WIDTHS_END) ) { return; } // get menu item colors if( (drawStruct->itemState & ODS_SELECTED) || ((drawStruct->itemState & (ODS_SELECTED |ODS_CHECKED)) == (ODS_SELECTED |ODS_CHECKED)) ) { crMenuBackground = COLOR_HIGHLIGHT; crMenuText = COLOR_HIGHLIGHTTEXT; } else if( drawStruct->itemState & ODS_GRAYED) { crMenuBackground = COLOR_MENU; crMenuText = COLOR_GRAYTEXT; } else { crMenuBackground = COLOR_MENU; crMenuText = COLOR_MENUTEXT; } hPenMenu = ::CreatePen(PS_SOLID, 0, ::GetSysColor(crMenuBackground)); if (!hPenMenu) { TRACE_MSG(("Failed to create penMenu")); ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WINDOWS, 0); goto bail_out; } rect = drawStruct->rcItem; // Fill the whole box with current menu background color hOldPen = SelectPen(drawStruct->hDC, hPenMenu); hOldBrush = SelectBrush(drawStruct->hDC, GetSysColorBrush(crMenuBackground)); ::Rectangle(drawStruct->hDC, rect.left, rect.top, rect.right, rect.bottom); SelectBrush(drawStruct->hDC, hOldBrush); SelectPen(drawStruct->hDC, hOldPen); if( (hbmp = (HBITMAP)LoadImage( NULL, MAKEINTRESOURCE( OBM_CHECK ), IMAGE_BITMAP, 0,0, 0 )) == NULL ) { TRACE_MSG(("Failed to create check image")); ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WINDOWS, 0); goto bail_out; } // Get the width and height of the bitmap (allowing some border) ::GetObject(hbmp, sizeof(BITMAP), &bitmap); uiCheckWidth = bitmap.bmWidth + (2 * CHECKMARK_BORDER_X); uiCheckHeight = bitmap.bmHeight; // Draw in a checkmark (if needed) if (drawStruct->itemState & ODS_CHECKED) { hMemDC = ::CreateCompatibleDC(drawStruct->hDC); if (!hMemDC) { ERROR_OUT(("Failed to create memDC")); ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WINDOWS, 0); goto bail_out; } crOldBkgnd = ::SetBkColor(drawStruct->hDC, GetSysColor( crMenuBackground ) ); crOldText = ::SetTextColor(drawStruct->hDC, GetSysColor( crMenuText ) ); nOldBkMode = ::SetBkMode(drawStruct->hDC, OPAQUE ); HBITMAP hOld = SelectBitmap(hMemDC, hbmp); if (hOld != NULL) { rectCheck = rect; rectCheck.top += ((rectCheck.bottom - rectCheck.top)/2 - uiCheckHeight/2); rectCheck.right = rectCheck.left + uiCheckWidth; rectCheck.bottom = rectCheck.top + uiCheckHeight; ::BitBlt(drawStruct->hDC, rectCheck.left, rectCheck.top, rectCheck.right - rectCheck.left, rectCheck.bottom - rectCheck.top, hMemDC, 0, 0, SRCCOPY); SelectBitmap(hMemDC, hOld); } ::SetBkMode(drawStruct->hDC, nOldBkMode); ::SetTextColor(drawStruct->hDC, crOldText); ::SetBkColor(drawStruct->hDC, crOldBkgnd); ::DeleteDC(hMemDC); } DeleteBitmap(hbmp); // Allow room for the checkmark to the left of the color rect.left += uiCheckWidth; uiWidthIndex = drawStruct->itemID - IDM_WIDTHS_START; uiWidth = g_PenWidths[uiWidthIndex]; // If pens are very wide they can be larger than the allowed rectangle. // So we reduce the clipping rectangle here. We save the DC so that we // can restore it - getting the clip region back. if (::SaveDC(drawStruct->hDC) == 0) { ERROR_OUT(("Failed to save DC")); ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WINDOWS, 0); goto bail_out; } if (::IntersectClipRect(drawStruct->hDC, rect.left, rect.top, rect.right, rect.bottom) == ERROR) { ERROR_OUT(("Failed to set clip rect")); ::RestoreDC(drawStruct->hDC, -1); ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WINDOWS, 0); goto bail_out; } hOldPen = SelectPen(drawStruct->hDC, hPenMenu); hOldBrush = SelectBrush(drawStruct->hDC, GetSysColorBrush(crMenuText)); rectLine.left = rect.left; rectLine.top = rect.top + ((rect.bottom - rect.top) / 2) - uiWidth/2; rectLine.right= rect.right - ((rect.right - rect.left) / 6); rectLine.bottom = rectLine.top + uiWidth + 2; ::Rectangle(drawStruct->hDC, rectLine.left, rectLine.top, rectLine.right, rectLine.bottom); SelectBrush(drawStruct->hDC, hOldBrush); SelectPen(drawStruct->hDC, hOldPen); ::RestoreDC(drawStruct->hDC, -1); bail_out: if (hPenMenu != NULL) { ::DeletePen(hPenMenu); } } // // // Function: OnSetFocus // // Purpose: The window is getting the focus // // void WbMainWindow::OnSetFocus(void) { // We pass the focus on to the main drawing area ::SetFocus(m_drawingArea.m_hwnd); } // // // Function: OnParentNotfiy // // Purpose: Process a message coming from a child window // // void WbMainWindow::OnParentNotify(UINT uiMessage) { switch (uiMessage) { // Scroll message from the drawing area. These are sent when the user // scrolls the area using the scroll bars. We queue an update of the // current sync position. case WM_HSCROLL: case WM_VSCROLL: // The user's view has changed PositionUpdated(); break; } } // // // Function: QuerySaveRequired // // Purpose: Check whether the drawing pane contents are to be saved // before a destructive function is performed. // // int WbMainWindow::QuerySaveRequired(BOOL bCancelBtn) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::QuerySaveRequired"); // If we are not maximized if (!::IsZoomed(m_hwnd) && !::IsIconic(m_hwnd)) { // Save the new position of the window SaveWindowPosition(); } // Default the response to "no save required" int iResult = IDNO; // // If we are already displaying a "Save As" dialog, dismiss it. // if (m_hwndQuerySaveDlg != NULL) { ::SendMessage(m_hwndQuerySaveDlg, WM_COMMAND, MAKELONG(IDCANCEL, BN_CLICKED), 0); ASSERT(m_hwndQuerySaveDlg == NULL); } // If any of the pages has changed - ask the user if they want to // save the contents of the Whiteboard. if (g_bContentsChanged && IsThereAnythingInAnyWorkspace()) { ::SetForegroundWindow(m_hwnd); //bring us to the top first // SetForegroundWindow() does not work properly in Memphis when its called during a // SendMessage handler, specifically, when conf calls me to shutdown. The window activation // state is messed up or something and my window does not pop to the top. So I have to // force my window to the top using SetWindowPos. But even after that the titlebar is not // highlighted properly. I tried combinations of SetActiveWindow, SetFocus, etc but to no // avail. But, at least the dialog is visible so you can clear it thus fixing the // bug (NM4db:2103). SetForegroundWindow() works ok for Win95 and NT here without // having to use SetWindowPos (it doesn't hurt anyting to do it anyway so I didn't // do a platform check). ::SetWindowPos(m_hwnd, HWND_TOPMOST, 0,0, 0,0, SWP_NOMOVE | SWP_NOSIZE ); // force to top ::SetWindowPos(m_hwnd, HWND_NOTOPMOST, 0,0, 0,0, SWP_NOMOVE | SWP_NOSIZE ); // let go of topmost // // Display a dialog box with the relevant question // LOWORD of user data is "cancel command is allowed" // HIWORD of user data is "disable cancel button" // iResult = (int)DialogBoxParam(g_hInstance, bCancelBtn ? MAKEINTRESOURCE(QUERYSAVEDIALOGCANCEL) : MAKEINTRESOURCE(QUERYSAVEDIALOG), m_hwnd, QuerySaveDlgProc, MAKELONG(bCancelBtn, FALSE)); } return iResult; } // // QuerySaveDlgProc() // Handler for query save dialogs. We save some flags in GWL_USER // INT_PTR CALLBACK QuerySaveDlgProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam) { BOOL fHandled = FALSE; switch (uMessage) { case WM_INITDIALOG: // // Save away our HWND so this dialog can be cancelled if necessary // g_pMain->m_hwndQuerySaveDlg = hwnd; // Remember the flags we passed ::SetWindowLongPtr(hwnd, GWLP_USERDATA, lParam); // Should the cancel button be disabled? if (HIWORD(lParam)) ::EnableWindow(::GetDlgItem(hwnd, IDCANCEL), FALSE); // Bring us to the front ::SetForegroundWindow(hwnd); fHandled = TRUE; break; case WM_CLOSE: // Even if the cancel button is disabled, kill the dialog ::PostMessage(hwnd, WM_COMMAND, IDCANCEL, 0); fHandled = TRUE; break; case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDCANCEL: // // If a dialog doesn't have a cancel button or it's // disabled and the user pressed the close btn, we can // get here. // if (!LOWORD(::GetWindowLongPtr(hwnd, GWLP_USERDATA))) wParam = MAKELONG(IDNO, HIWORD(wParam)); // FALL THRU case IDYES: case IDNO: if (GET_WM_COMMAND_CMD(wParam, lParam) == BN_CLICKED) { g_pMain->m_hwndQuerySaveDlg = NULL; ::EndDialog(hwnd, GET_WM_COMMAND_ID(wParam, lParam)); break; } break; } fHandled = TRUE; break; } return(fHandled); } // // // Function: OnNew // // Purpose: Clear the workspace and associated filenames // // LRESULT WbMainWindow::OnNew(void) { int iDoNew; if( UsersMightLoseData( NULL, NULL ) ) // bug NM4db:418 return S_OK; // check state before proceeding - if we're already doing a new, then abort if (m_uiSubState == SUBSTATE_NEW_IN_PROGRESS) { // post an error message indicating the whiteboard is busy ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WB, WB_RC_BUSY); return S_OK; } // if we're currently loading, then cancel the load and proceed (don't // prompt to save). else if (m_uiSubState == SUBSTATE_LOADING) { // cancel load, not releasing the page order lock, because // we need it immediately afterwards CancelLoad(FALSE); iDoNew = IDNO; } // otherwise prompt to save if necessary else { // Get confirmation for the new iDoNew = QuerySaveRequired(TRUE); } if (iDoNew == IDYES) { // Save the changes iDoNew = (int)OnSave(FALSE); } // If the user did not cancel the operation, clear the drawing area if (iDoNew != IDCANCEL) { // // Remember if we had a remote pointer. // In OldWB, the remote pointer is a global thing that clearing // doesn't get rid of. // In T.126WB, it's just an object on a page, so we need to add // it back because we're deleting the old pages and creating // new ones. // BOOL bRemote = FALSE; if (m_pLocalRemotePointer) { // Remove remote pointer from pages bRemote = TRUE; OnRemotePointer(); } ::InvalidateRect(g_pDraw->m_hwnd, NULL, TRUE); DeleteAllWorkspaces(TRUE); WorkspaceObj * pObj; DBG_SAVE_FILE_LINE pObj = new WorkspaceObj(); pObj->AddToWorkspace(); if (bRemote) { // Put it back OnRemotePointer(); } // Clear the associated file name ZeroMemory(m_strFileName, sizeof(m_strFileName)); // Update the window title with no file name UpdateWindowTitle(); } return S_OK; } // // // Function: OnNextPage // // Purpose: Move to the next worksheet in the pages list // // LRESULT WbMainWindow::OnNextPage(void) { // Go to the next page if(g_pCurrentWorkspace) { WBPOSITION pos = g_pCurrentWorkspace->GetMyPosition(); g_pListOfWorkspaces->GetNext(pos); if(pos) { WorkspaceObj* pWorkspace = (WorkspaceObj*)g_pListOfWorkspaces->GetNext(pos); GotoPage(pWorkspace); } } return S_OK; } // // // Function: OnPrevPage // // Purpose: Move to the previous worksheet in the pages list // // LRESULT WbMainWindow::OnPrevPage(void) { if(g_pCurrentWorkspace) { WBPOSITION pos = g_pCurrentWorkspace->GetMyPosition(); g_pListOfWorkspaces->GetPrevious(pos); if(pos) { WorkspaceObj* pWorkspace = (WorkspaceObj*)g_pListOfWorkspaces->GetPrevious(pos); GotoPage(pWorkspace); } } return S_OK; } // // // Function: OnFirstPage // // Purpose: Move to the first worksheet in the pages list // // LRESULT WbMainWindow::OnFirstPage(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnFirstPage"); WorkspaceObj * pWorkspace = (WorkspaceObj *)g_pListOfWorkspaces->GetHead(); GotoPage(pWorkspace); return S_OK; } // // // Function: OnLastPage // // Purpose: Move to the last worksheet in the pages list // // LRESULT WbMainWindow::OnLastPage(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnLastPage"); WorkspaceObj * pWorkspace = (WorkspaceObj *)g_pListOfWorkspaces->GetTail(); GotoPage(pWorkspace); return S_OK; } // // // Function: OnGotoPage // // Purpose: Move to the specified page (if it exists) // // LRESULT WbMainWindow::OnGotoPage(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnGotoPage"); // Get the requested page number from the pages group UINT uiPageNumber = m_AG.GetCurrentPageNumber() - 1; WBPOSITION pos; WorkspaceObj* pWorkspace = NULL; pos = g_pListOfWorkspaces->GetHeadPosition(); while(pos && uiPageNumber != 0) { g_pListOfWorkspaces->GetNext(pos); uiPageNumber--; } if(pos) { pWorkspace = (WorkspaceObj *)g_pListOfWorkspaces->GetNext(pos); GotoPage(pWorkspace); } return S_OK; } // // Check if remote pointer was on before we go to page // void WbMainWindow::GotoPage(WorkspaceObj * pNewWorkspace, BOOL bSend) { // // If we were editing text // if (g_pDraw->TextEditActive()) { g_pDraw->EndTextEntry(TRUE); } // // If we had a remote pointer // BOOL bRemote = FALSE; if(m_pLocalRemotePointer) { bRemote = TRUE; OnRemotePointer(); } // // Undraw remote pointers // T126Obj * pPointer = g_pCurrentWorkspace->GetTail(); WBPOSITION pos = g_pCurrentWorkspace->GetTailPosition(); while(pos && pPointer->GraphicTool() == TOOLTYPE_REMOTEPOINTER) { pPointer->UnDraw(); pPointer = (T126Obj*) g_pCurrentWorkspace->GetPreviousObject(pos); } GoPage(pNewWorkspace, bSend); // // Draw remote pointers back // pPointer = g_pCurrentWorkspace->GetTail(); pos = g_pCurrentWorkspace->GetTailPosition(); while(pos && pPointer->GraphicTool() == TOOLTYPE_REMOTEPOINTER) { pPointer->Draw(); pPointer = (T126Obj*) g_pCurrentWorkspace->GetPreviousObject(pos); } // // If we had a remote pointer // if(bRemote) { OnRemotePointer(); } } // // // Function: GoPage // // Purpose: Move to the specified page // // void WbMainWindow::GoPage(WorkspaceObj * pNewWorkspace, BOOL bSend) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::GotoPage"); // If we are changing pages if (pNewWorkspace != g_pCurrentWorkspace) { m_drawingArea.CancelDrawingMode(); // Attach the new page to the drawing area m_drawingArea.Attach(pNewWorkspace); // set the focus back to the drawing area if (!(m_AG.IsChildEditField(::GetFocus()))) { ::SetFocus(m_drawingArea.m_hwnd); } ::InvalidateRect(m_drawingArea.m_hwnd, NULL, TRUE ); ::UpdateWindow(m_drawingArea.m_hwnd); // // Tell the other nodes we moved to a different page. // if(bSend) { // // Set the view state // pNewWorkspace->SetViewState(focus_chosen); pNewWorkspace->SetViewActionChoice(editView_chosen); pNewWorkspace->OnObjectEdit(); } } UpdatePageButtons(); } // // // Function: GotoPosition // // Purpose: Move to the specified position within the page // // void WbMainWindow::GotoPosition(int x, int y) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::GotoPosition"); // Move the drawing area to the new position m_drawingArea.GotoPosition(x, y); // The user's view has changed PositionUpdated(); } // // // Function: LoadFile // // Purpose: Load a metafile into the application. Errors are reported // to the caller by the return code. // // void WbMainWindow::LoadFile ( LPCSTR szLoadFileName ) { UINT uRes; // Check we're in idle state if (!IsIdle()) { // post an error message indicating the whiteboard is busy ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WB, WB_RC_BUSY); goto UserPointerCleanup; } if (*szLoadFileName) { // Change the cursor to "wait" ::SetCursor(::LoadCursor(NULL, IDC_WAIT)); // Set the state to say that we are loading a file SetSubstate(SUBSTATE_LOADING); // Load the file uRes = ContentsLoad(szLoadFileName); if (uRes != 0) { DefaultExceptionHandler(WBFE_RC_WB, uRes); goto UserPointerCleanup; } // Set the window title to the new file name lstrcpy(m_strFileName, szLoadFileName); // Update the window title with the new file name g_bContentsChanged = FALSE; } UserPointerCleanup: // Set the state to say that we are loading a file SetSubstate(SUBSTATE_IDLE); // Restore the cursor ::SetCursor(::LoadCursor(NULL, IDC_ARROW)); } // // // Function: OnDropFiles // // Purpose: Files have been dropped onto the Whiteboard window // // void WbMainWindow::OnDropFiles(HDROP hDropInfo) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnDropFiles"); UINT uiFilesDropped = 0; UINT eachfile; PT126WB_FILE_HEADER_AND_OBJECTS pHeader = NULL; // Get the total number of files dropped uiFilesDropped = ::DragQueryFile(hDropInfo, (UINT) -1, NULL, (UINT) 0); // release mouse capture in case we report any errors (message boxes // won't repsond to mouse clicks if we don't) ReleaseCapture(); for (eachfile = 0; eachfile < uiFilesDropped; eachfile++) { // Retrieve each file name char szDropFileName[256]; ::DragQueryFile(hDropInfo, eachfile, szDropFileName, 256); TRACE_MSG(("Loading file: %s", szDropFileName)); OnOpen(szDropFileName); } ::DragFinish(hDropInfo); } // // // Function: OnOpen // // Purpose: Load a metafile into the application. // // LRESULT WbMainWindow::OnOpen(LPCSTR szLoadFileName) { int iOnSave; if(g_pDraw->IsLocked() || !g_pDraw->IsSynced()) { DefaultExceptionHandler(WBFE_RC_WB, WB_RC_BAD_STATE); return S_FALSE; } MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnOpen"); if( UsersMightLoseData( NULL, NULL ) ) // bug NM4db:418 return S_OK; // Check we're in idle state if ((m_uiSubState == SUBSTATE_NEW_IN_PROGRESS)) { // post an error message indicating the whiteboard is busy ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WB, WB_RC_BUSY); return S_OK; } // Don't prompt to save file if we're already loading if (m_uiSubState != SUBSTATE_LOADING) { // Check whether there are changes to be saved iOnSave = QuerySaveRequired(TRUE); } else { iOnSave = IDNO; } if (iOnSave == IDYES) { // User wants to save the drawing area contents int iResult = (int)OnSave(TRUE); if (iResult == IDOK) { } else { // cancelled out of Save As, so cancel the open operation iOnSave = IDCANCEL; } } // Only continue if the user has not cancelled the operation if (iOnSave != IDCANCEL) { // // If the filename was passed // if(szLoadFileName) { LoadFile(szLoadFileName); } else { OPENFILENAME ofn; TCHAR szFileName[_MAX_PATH]; TCHAR szFileTitle[64]; TCHAR strLoadFilter[2*_MAX_PATH]; TCHAR strDefaultExt[_MAX_PATH]; TCHAR strDefaultPath[2*_MAX_PATH]; TCHAR * pStr; UINT strSize = 0; UINT totalSize; // Build the filter for loadable files pStr = strLoadFilter; totalSize = 2*_MAX_PATH; // These must be NULL separated, with a double NULL at the end strSize = ::LoadString(g_hInstance, IDS_FILTER_WHT, pStr, totalSize) + 1; pStr += strSize; ASSERT(totalSize > strSize); totalSize -= strSize; strSize = ::LoadString(g_hInstance, IDS_FILTER_WHT_SPEC, pStr, totalSize) + 1; pStr += strSize; ASSERT(totalSize > strSize); totalSize -= strSize; strSize = ::LoadString(g_hInstance, IDS_FILTER_ALL, pStr, totalSize) + 1; pStr += strSize; ASSERT(totalSize > strSize); totalSize -= strSize; strSize = ::LoadString(g_hInstance, IDS_FILTER_ALL_SPEC, pStr, totalSize) + 1; pStr += strSize; ASSERT(totalSize > strSize); totalSize -= strSize; *pStr = 0; // // Setup the OPENFILENAME struct // ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = m_hwnd; // No file name supplied to begin with szFileName[0] = 0; ofn.lpstrFile = szFileName; ofn.nMaxFile = _MAX_PATH; // Default Extension: .NMW ::LoadString(g_hInstance, IDS_EXT_WHT, strDefaultExt, sizeof(strDefaultExt)); ofn.lpstrDefExt = strDefaultExt; // Default file title is empty szFileTitle[0] = 0; ofn.lpstrFileTitle = szFileTitle; ofn.nMaxFileTitle = 64; // Open flags ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_EXPLORER; ofn.hInstance = g_hInstance; // Filter ofn.lpstrFilter = strLoadFilter; // Default path if (GetDefaultPath(strDefaultPath, sizeof(strDefaultPath))) ofn.lpstrInitialDir = strDefaultPath; // Get user input, continue only if the user selects the OK button if (::GetOpenFileName(&ofn)) { // Change the cursor to "wait" ::SetCursor(::LoadCursor(NULL, IDC_WAIT)); // if we're currently loading a file, cancel it, not releasing // the page order lock, because we need it immediately afterwards if (m_uiSubState == SUBSTATE_LOADING) { CancelLoad(FALSE); } // Load the file LoadFile(ofn.lpstrFile); } } } // Update the window title with no file name UpdateWindowTitle(); return S_OK; } // // // Function: GetFileName // // Purpose: Get a file name for saving the contents // // int WbMainWindow::GetFileName(void) { OPENFILENAME ofn; int iResult; TCHAR szFileTitle[64]; TCHAR strSaveFilter[2*_MAX_PATH]; TCHAR strDefaultExt[_MAX_PATH]; TCHAR strDefaultPath[2 * _MAX_PATH]; TCHAR szFileName[2*_MAX_PATH]; TCHAR * pStr; UINT strSize = 0; UINT totalSize; // // If we are already displaying a "Save As" dialog, dismiss it and create // a new one. This can happen if Win95 shuts down whilst WB is // displaying the "Save As" dialog and the use selects "Yes" when asked // whether they want to save the contents - a second "Save As dialog // appears on top of the first. // if (m_bInSaveDialog) { CancelSaveDialog(); } // Build the filter for save files pStr = strSaveFilter; totalSize = 2*_MAX_PATH; // These must be NULL separated, with a double NULL at the end strSize = ::LoadString(g_hInstance, IDS_FILTER_WHT, pStr, totalSize) + 1; pStr += strSize; ASSERT(totalSize > strSize); totalSize -= strSize; strSize = ::LoadString(g_hInstance, IDS_FILTER_WHT_SPEC, pStr, totalSize) + 1; pStr += strSize; ASSERT(totalSize > strSize); totalSize -= strSize; strSize = ::LoadString(g_hInstance, IDS_FILTER_ALL, pStr, totalSize) + 1; pStr += strSize; ASSERT(totalSize > strSize); totalSize -= strSize; strSize = ::LoadString(g_hInstance, IDS_FILTER_ALL_SPEC, pStr, totalSize) + 1; pStr += strSize; ASSERT(totalSize > strSize); totalSize -= strSize; *pStr = 0; // // Setup the OPENFILENAME struct // ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = m_hwnd; lstrcpy(szFileName, m_strFileName); ofn.lpstrFile = szFileName; ofn.nMaxFile = _MAX_PATH; // Build the default extension string ::LoadString(g_hInstance, IDS_EXT_WHT, strDefaultExt, sizeof(strDefaultExt)); ofn.lpstrDefExt = strDefaultExt; szFileTitle[0] = 0; ofn.lpstrFileTitle = szFileTitle; ofn.nMaxFileTitle = 64; // Save flags ofn.Flags = OFN_HIDEREADONLY | OFN_NOREADONLYRETURN | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST; ofn.hInstance = g_hInstance; // Filter ofn.lpstrFilter = strSaveFilter; // Default path if (GetDefaultPath(strDefaultPath, sizeof(strDefaultPath))) ofn.lpstrInitialDir = strDefaultPath; m_bInSaveDialog = TRUE; if (::GetSaveFileName(&ofn)) { // The user selected OK iResult = IDOK; lstrcpy(m_strFileName, szFileName); } else { iResult = IDCANCEL; } m_bInSaveDialog = FALSE; return iResult; } // // // Function: OnSave // // Purpose: Save the contents of the Whiteboard using the current file // name (or prompting for a new name if there is no current). // // LRESULT WbMainWindow::OnSave(BOOL bPrompt) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnSave"); LRESULT iResult = IDOK; // save the old file name in case there's an error TCHAR strOldName[2*MAX_PATH]; UINT fileNameSize = lstrlen(m_strFileName); lstrcpy(strOldName, m_strFileName); BOOL bNewName = FALSE; if (!IsIdle()) { // post an error message indicating the whiteboard is busy ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WB, WB_RC_BUSY); return(iResult); } // Check whether there is a filename available for use if (!fileNameSize || (bPrompt)) { // Get user input, continue only if the user selects the OK button iResult = GetFileName(); if (iResult == IDOK) { // entering a blank file name is treated as cancelling the save if (!lstrlen(m_strFileName)) { lstrcpy(m_strFileName, strOldName); iResult = IDCANCEL; } else { // flag that we've changed the contents file name bNewName = TRUE; } } } // Now save the file if ((iResult == IDOK) && lstrlen(m_strFileName)) { WIN32_FIND_DATA findFileData; HANDLE hFind; // Get attributes hFind = ::FindFirstFile(m_strFileName, &findFileData); if (hFind != INVALID_HANDLE_VALUE) { ::FindClose(hFind); // This is a read-only file; we can't change its contents if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) { WARNING_OUT(("Dest file %s is read only", m_strFileName)); ::Message(NULL, IDS_SAVE, IDS_SAVE_READ_ONLY); // If the file name was changed for this save then undo // the change if (bNewName) { lstrcpy(m_strFileName, strOldName); bNewName = FALSE; } // Change the return code to indicate no save was made iResult = IDCANCEL; return(iResult); } } // Change the cursor to "wait" ::SetCursor(::LoadCursor(NULL,IDC_WAIT)); // Write the file if (ContentsSave(m_strFileName) != 0) { // Show that an error occurred saving the file. WARNING_OUT(("Error saving file")); ::Message(NULL, IDS_SAVE, IDS_SAVE_ERROR); // If the file name was changed for this save then undo // the change if (bNewName) { lstrcpy(m_strFileName, strOldName); bNewName = FALSE; } // Change the return code to indicate no save was made iResult = IDCANCEL; } else { g_bContentsChanged = FALSE; } // Restore the cursor ::SetCursor(::LoadCursor(NULL,IDC_ARROW)); } // if the contents file name has changed as a result of the save then // update the window title if (bNewName) { UpdateWindowTitle(); } return(iResult); } // // CancelSaveDialog() // This cancels the save as dialog if up and we need to kill it to continue. // We walk back up the owner chain in case the save dialog puts up help or // other owned windows. // void WbMainWindow::CancelSaveDialog(void) { WBFINDDIALOG wbf; ASSERT(m_bInSaveDialog); wbf.hwndOwner = m_hwnd; wbf.hwndDialog = NULL; EnumThreadWindows(::GetCurrentThreadId(), WbFindCurrentDialog, (LPARAM)&wbf); if (wbf.hwndDialog) { // Found it! ::SendMessage(wbf.hwndDialog, WM_COMMAND, IDCANCEL, 0); } m_bInSaveDialog = FALSE; } BOOL CALLBACK WbFindCurrentDialog(HWND hwndNext, LPARAM lParam) { WBFINDDIALOG * pwbf = (WBFINDDIALOG *)lParam; // Is this a dialog, owned by the main window? if ((::GetClassLong(hwndNext, GCW_ATOM) == 0x8002) && (::GetWindow(hwndNext, GW_OWNER) == pwbf->hwndOwner)) { pwbf->hwndDialog = hwndNext; return(FALSE); } return(TRUE); } // // // Function: OnClose // // Purpose: Close the Whiteboard // // void WbMainWindow::OnClose() { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnClose"); int iOnSave = IDOK; m_drawingArea.CancelDrawingMode(); m_AG.SaveSettings(); // If we got here, by way of OnDestroy from the DCL cores or // by system shutdown, then assume that user responded already to the // save-changes dialog that would have poped up during conf's global shutdown // message. We don't need to ask 'em again. What tangled webs...... if ((!m_bQuerySysShutdown) && (IsIdle())) { // Check whether there are changes to be saved iOnSave = QuerySaveRequired(TRUE); if (iOnSave == IDYES) { // User wants to save the drawing area contents iOnSave = (int)OnSave(TRUE); } } // If the exit was not cancelled, close the application if (iOnSave != IDCANCEL) { // Close the application ::PostQuitMessage(0); } } // // // Function: OnClearPage // // Purpose: Clear the Whiteboard drawing area. The user is prompted to // choose clearing of foreground, background or both. // // LRESULT WbMainWindow::OnClearPage(BOOL bClearAll) { LRESULT iResult; BOOL bWasPosted; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnClearPage"); if( UsersMightLoseData( &bWasPosted, NULL ) ) // bug NM4db:418 return S_OK; if( bWasPosted ) iResult = IDYES; else iResult = ::Message(NULL, bClearAll == FALSE ? IDS_DELETE_PAGE : IDS_CLEAR_CAPTION, bClearAll == FALSE ? IDS_DELETE_PAGE_MESSAGE : IDS_CLEAR_MESSAGE, MB_YESNO | MB_ICONQUESTION); if ((iResult == IDYES) && bClearAll) { OnSelectAll(); OnDelete(); TRACE_MSG(("User requested clear of page")); } return iResult; } // // // Function: OnDelete // // Purpose: Delete the current selection // // LRESULT WbMainWindow::OnDelete() { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnDelete"); // cleanup select logic in case object context menu called us (bug 426) m_drawingArea.SetLClickIgnore( FALSE ); // Delete the currently selected graphics and add to m_LastDeletedGraphic m_drawingArea.EraseSelectedDrawings(); return S_OK; } // // // Function: OnUndelete // // Purpose: Undo the last delete operation // // LRESULT WbMainWindow::OnUndelete() { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnUndelete"); // If there is a deleted graphic to restore T126Obj * pObj; pObj = (T126Obj *)g_pTrash->RemoveHead(); while (pObj != NULL) { if(!AddT126ObjectToWorkspace(pObj)) { return S_FALSE; } if(pObj->GetMyWorkspace() == g_pCurrentWorkspace) { pObj->Draw(FALSE); } // // Make sure it gets added back as unselected. It was selected // when deleted. // pObj->ClearDeletionFlags(); pObj->SetAllAttribs(); pObj->SetViewState(unselected_chosen); pObj->SendNewObjectToT126Apps(); pObj = (T126Obj *) g_pTrash->RemoveHead(); } return S_OK; } // // // Function: OnSelectAll // // Purpose: Select all the objects in the current page // // LRESULT WbMainWindow::OnSelectAll( void ) { // Unselect every oject first. m_drawingArea.RemoveMarker(); // turn off any selections // cleanup select logic in case object context menu called us (bug 426) m_drawingArea.SetLClickIgnore( FALSE ); // inhibit normal select-tool action m_bSelectAllInProgress = TRUE; //put us in select-tool mode first OnSelectTool(IDM_SELECT); // back to normal m_bSelectAllInProgress = FALSE; // now, select everything m_drawingArea.SelectMarkerFromRect( NULL ); return S_OK; } // // // Function: OnCut // // Purpose: Cut the current selection // // LRESULT WbMainWindow::OnCut() { // Copy all the selected graphics to the clipboard BOOL bResult = CLP_Copy(); // If an error occurred during the copy, report it now if (!bResult) { ::Message(NULL, IDM_CUT, IDS_COPY_ERROR); return S_FALSE; } // // Erase the selected objects // OnDelete(); return S_OK; } // // OnCopy() // Purpose: Copy the current selection to the clipboard // // LRESULT WbMainWindow::OnCopy(void) { // Copy all the selected graphics to the clipboard BOOL bResult = CLP_Copy(); // If an error occurred during the copy, report it now if (!bResult) { ::Message(NULL, IDS_COPY, IDS_COPY_ERROR); return S_FALSE; } return S_OK; } // // // Function: OnPaste // // Purpose: Paste the contents of the clipboard into the drawing pane // // LRESULT WbMainWindow::OnPaste() { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnPaste"); BOOL bResult = CLP_Paste(); // If an error occurred during the copy, report it now if (!bResult) { ::Message(NULL, IDS_PASTE, IDS_PASTE_ERROR); return S_FALSE; } return S_OK; } // // // Function: OnScrollAccelerator // // Purpose: Called when a scroll accelerator is used // // LRESULT WbMainWindow::OnScrollAccelerator(UINT uiMenuId) { int iScroll; // Locate the scroll messages to be sent in the conversion table for (iScroll = 0; iScroll < ARRAYSIZE(s_MenuToScroll); iScroll++) { if (s_MenuToScroll[iScroll].uiMenuId == uiMenuId) { // Found it; break; } } // Send the messages if (iScroll < ARRAYSIZE(s_MenuToScroll)) { while ((s_MenuToScroll[iScroll].uiMenuId == uiMenuId) && (iScroll < ARRAYSIZE(s_MenuToScroll))) { // Tell the drawing pane to scroll ::PostMessage(m_drawingArea.m_hwnd, s_MenuToScroll[iScroll].uiMessage, s_MenuToScroll[iScroll].uiScrollCode, 0); iScroll++; } // Indicate that scrolling has completed (in both directions) ::PostMessage(m_drawingArea.m_hwnd, WM_HSCROLL, SB_ENDSCROLL, 0L); ::PostMessage(m_drawingArea.m_hwnd, WM_VSCROLL, SB_ENDSCROLL, 0L); } return S_OK; } // // // Function: OnZoom // // Purpose: Zoom or unzoom the drawing area // // LRESULT WbMainWindow::OnZoom() { // If the drawing area is currently zoomed if (m_drawingArea.Zoomed()) { // Tell the tool bar of the new selection m_TB.PopUp(IDM_ZOOM); UncheckMenuItem(IDM_ZOOM); } else { // Tell the tool bar of the new selection m_TB.PushDown(IDM_ZOOM); CheckMenuItem(IDM_ZOOM); } // Zoom/unzoom the drawing area m_drawingArea.Zoom(); // Restore the focus to the drawing area ::SetFocus(m_drawingArea.m_hwnd); return S_OK; } LRESULT WbMainWindow::OnLock() { // If the drawing area is currently Locked if (m_drawingArea.IsLocked()) { m_TB.PopUp(IDM_LOCK); UncheckMenuItem(IDM_LOCK); } else { m_TB.PushDown(IDM_LOCK); CheckMenuItem(IDM_LOCK); g_pNMWBOBJ->m_LockerID = g_MyMemberID; } m_drawingArea.SetLock(!m_drawingArea.IsLocked()); TogleLockInAllWorkspaces(m_drawingArea.IsLocked(), TRUE); EnableToolbar( TRUE ); return S_OK; } // // // Function: OnSelectTool // // Purpose: Select the current tool // // LRESULT WbMainWindow::OnSelectTool(UINT uiMenuId) { UncheckMenuItem(m_currentMenuTool); CheckMenuItem( uiMenuId); UINT uiIndex; // Save the new menu Id m_currentMenuTool = uiMenuId; // Tell the tool bar of the new selection m_TB.PushDown(m_currentMenuTool); // Get the new tool m_pCurrentTool = m_ToolArray[TOOL_INDEX(m_currentMenuTool)]; // Set the current attributes if( !m_bSelectAllInProgress ) { m_AG.SetChoiceColor(m_pCurrentTool->GetColor() ); ::SendMessage(m_hwnd, WM_COMMAND, IDM_COLOR, 0L); } // Report the change of tool to the attributes group m_AG.DisplayTool(m_pCurrentTool); // Select the new tool into the drawing area m_drawingArea.SelectTool(m_pCurrentTool); // Restore the focus to the drawing area ::SetFocus(m_drawingArea.m_hwnd); return S_OK; } // // // Function: OnSelectColor // // Purpose: Set the current color // // LRESULT WbMainWindow::OnSelectColor(void) { // Tell the attributes group of the new selection and get the // new color value selected ino the current tool. m_AG.SelectColor(m_pCurrentTool); // Select the changed tool into the drawing area m_drawingArea.SelectTool(m_pCurrentTool); // If there is an object marked for changing if (m_drawingArea.GraphicSelected() || m_drawingArea.TextEditActive()) { // Update the object m_drawingArea.SetSelectionColor(m_pCurrentTool->GetColor()); } // Restore the focus to the drawing area ::SetFocus(m_drawingArea.m_hwnd); return S_OK; } // // // Function: OnSelectWidth // // Purpose: Set the current nib width // // LRESULT WbMainWindow::OnSelectWidth(UINT uiMenuId) { // cleanup select logic in case object context menu called us (bug 426) m_drawingArea.SetLClickIgnore( FALSE ); // Save the new pen width m_currentMenuWidth = uiMenuId; // Tell the attributes display of the new selection m_WG.PushDown(uiMenuId - IDM_WIDTHS_START); if (m_pCurrentTool != NULL) { m_pCurrentTool->SetWidthIndex(uiMenuId - IDM_WIDTHS_START); } // Tell the drawing pane of the new selection m_drawingArea.SelectTool(m_pCurrentTool); // If there is an object marked for changing if (m_drawingArea.GraphicSelected()) { // Update the object m_drawingArea.SetSelectionWidth(uiMenuId - IDM_WIDTHS_START); } // Restore the focus to the drawing area ::SetFocus(m_drawingArea.m_hwnd); return S_OK; } // // // Function: OnChooseFont // // Purpose: Let the user select a font // // LRESULT WbMainWindow::OnChooseFont(void) { HDC hdc; LOGFONT lfont; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnChooseFont"); // cleanup select logic in case object context menu called us (bug 426) m_drawingArea.SetLClickIgnore( FALSE ); // It is only really sensible to be here when a text tool is selected. // This is achieved by graying the Font selection menu entry when // anything other than a text tool is in use. // Get the font details from the current tool ::GetObject(m_pCurrentTool->GetFont(), sizeof(LOGFONT), &lfont); lfont.lfClipPrecision |= CLIP_DFA_OVERRIDE; // // The Font dialog is passed a LOGFONT structure which it uses to // initialize all of its fields (face name, weight etc). // // The face name passed in the LOGFONT structure is checked by the dialog // against the facenames of all available fonts. If the name does not // match one of the available fonts, no name is displayed. // // WB stores the LOGFONT structure specifying the font used for a text // object in the object. This LOGFONT is selected into a DC where the // GDIs font mapper decides which physical font most closely matches the // required logical font. On boxes where the original font is not // supported the font is substituted for the closest matching font // available. // // So, if we pass the LOGFONT structure for a font which is not supported // into the Font dialog, no facename is displayed. To bypass this we // // - select the logical font into a DC // // - determine the textmetrics and get the face name of the physical font // chosen by the Font Mapper // // - use these textmetrics to create a LOGFONT structure which matches // the substituted font! // // The resulting LOGFONT will have the correct weight, dimensions and // facename for the substituted font. // hdc = ::CreateCompatibleDC(NULL); if (hdc != NULL) { TEXTMETRIC tm; HFONT hFont; HFONT hOldFont; hFont = ::CreateFontIndirect(&lfont); // // Get the face name and text metrics of the selected font. // hOldFont = SelectFont(hdc, hFont); if (hOldFont == NULL) { WARNING_OUT(("Failed to select font into DC")); } else { ::GetTextMetrics(hdc, &tm); ::GetTextFace(hdc, LF_FACESIZE, lfont.lfFaceName); // // Restore the old font back into the DC. // SelectFont(hdc, hOldFont); // // Create a LOGFONT structure which matches the Text metrics // of the font used by the DC so that the font dialog manages // to initialise all of its fields properly, even for // substituted fonts... // lfont.lfHeight = tm.tmHeight; lfont.lfWidth = tm.tmAveCharWidth; lfont.lfWeight = tm.tmWeight; lfont.lfItalic = tm.tmItalic; lfont.lfUnderline = tm.tmUnderlined; lfont.lfStrikeOut = tm.tmStruckOut; lfont.lfCharSet = tm.tmCharSet; //ADDED BY RAND - to make lfHeight be a char height. This makes // the font dlg show the same pt size that is // displayed in the sample font toolbar if( lfont.lfHeight > 0 ) { lfont.lfHeight = -(lfont.lfHeight - tm.tmInternalLeading); } } ::DeleteDC(hdc); if (hFont != NULL) { ::DeleteFont(hFont); } } else { WARNING_OUT(("Failed to get DC to select font into")); } CHOOSEFONT cf; TCHAR szStyleName[64]; ZeroMemory(&cf, sizeof(cf)); ZeroMemory(szStyleName, sizeof(szStyleName)); cf.lStructSize = sizeof(cf); cf.lpszStyle = szStyleName; cf.rgbColors = m_pCurrentTool->GetColor() & 0x00ffffff; // blow off palette bits (NM4db:2304) cf.Flags = CF_EFFECTS | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS | CF_NOVERTFONTS; cf.lpLogFont = &lfont; cf.hwndOwner = m_hwnd; // Call up the ChooseFont dialog from COM DLG if (::ChooseFont(&cf)) { lfont.lfClipPrecision |= CLIP_DFA_OVERRIDE; //ADDED BY RAND - set color selected in dialog. m_pCurrentTool->SetColor(cf.rgbColors); m_AG.DisplayTool( m_pCurrentTool ); ::SendMessage(m_hwnd, WM_COMMAND, (WPARAM)MAKELONG( IDM_COLOR, BN_CLICKED ), (LPARAM)0 ); // Inform the drawing pane of the new selection HFONT hNewFont; hNewFont = ::CreateFontIndirect(&lfont); if (!hNewFont) { ERROR_OUT(("Failed to create font")); DefaultExceptionHandler(WBFE_RC_WINDOWS, 0); return S_FALSE; } // // We need to set the text editor font after inserting it in the DC // and querying the metrics, otherwise we may get a font with different // metrics in zoomed mode // HFONT hNewFont2; HDC hDC = m_drawingArea.GetCachedDC(); TEXTMETRIC textMetrics; m_drawingArea.PrimeFont(hDC, hNewFont, &textMetrics); lfont.lfHeight = textMetrics.tmHeight; lfont.lfWidth = textMetrics.tmAveCharWidth; lfont.lfPitchAndFamily = textMetrics.tmPitchAndFamily; ::GetTextFace(hDC, sizeof(lfont.lfFaceName), lfont.lfFaceName); TRACE_MSG(("Font face name %s", lfont.lfFaceName)); // Inform the drawing pane of the new selection hNewFont2 = ::CreateFontIndirect(&lfont); if (!hNewFont2) { ERROR_OUT(("Failed to create font")); DefaultExceptionHandler(WBFE_RC_WINDOWS, 0); return S_FALSE; } m_drawingArea.SetSelectionColor(cf.rgbColors); m_drawingArea.SetSelectionFont(hNewFont2); if (m_pCurrentTool != NULL) { m_pCurrentTool->SetFont(hNewFont2); } m_drawingArea.SelectTool(m_pCurrentTool); // // discard the new font // m_drawingArea.UnPrimeFont( hDC ); // Delete the fonts we created--everybody above makes copies ::DeleteFont(hNewFont2); ::DeleteFont(hNewFont); } // Restore the focus to the drawing area ::SetFocus(m_drawingArea.m_hwnd); return S_OK; } // // // Function: OnToolBarToggle // // Purpose: Let the user toggle the tool bar on/off // // LRESULT WbMainWindow::OnToolBarToggle(void) { RECT rectWnd; // Toggle the flag m_bToolBarOn = !m_bToolBarOn; // Make the necessary updates if (m_bToolBarOn) { // The tool bar was hidden, so show it ::ShowWindow(m_TB.m_hwnd, SW_SHOW); // The tool window is fixed so we must resize the other panes in // the window to make room for it ResizePanes(); // Check the associated menu item CheckMenuItem(IDM_TOOL_BAR_TOGGLE); } else { // The tool bar was visible, so hide it ::ShowWindow(m_TB.m_hwnd, SW_HIDE); ResizePanes(); // Uncheck the associated menu item UncheckMenuItem(IDM_TOOL_BAR_TOGGLE); } // Make sure things reflect current tool m_AG.DisplayTool(m_pCurrentTool); // Write the new option value to the options file OPT_SetBooleanOption(OPT_MAIN_TOOLBARVISIBLE, m_bToolBarOn); ::GetWindowRect(m_hwnd, &rectWnd); ::MoveWindow(m_hwnd, rectWnd.left, rectWnd.top, rectWnd.right - rectWnd.left, rectWnd.bottom - rectWnd.top, TRUE); return S_OK; } // // // Function: OnStatusBarToggle // // Purpose: Let the user toggle the help bar on/off // // void WbMainWindow::OnStatusBarToggle(void) { RECT rectWnd; // Toggle the flag m_bStatusBarOn = !m_bStatusBarOn; // Make the necessary updates if (m_bStatusBarOn) { // Resize the panes to give room for the help bar ResizePanes(); // The help bar was hidden, so show it ::ShowWindow(m_hwndSB, SW_SHOW); // Check the associated menu item CheckMenuItem(IDM_STATUS_BAR_TOGGLE); } else { // The help bar was visible, so hide it ::ShowWindow(m_hwndSB, SW_HIDE); // Uncheck the associated menu item UncheckMenuItem(IDM_STATUS_BAR_TOGGLE); // Resize the panes to take up the help bar space ResizePanes(); } // Write the new option value to the options file OPT_SetBooleanOption(OPT_MAIN_STATUSBARVISIBLE, m_bStatusBarOn); ::GetWindowRect(m_hwnd, &rectWnd); ::MoveWindow(m_hwnd, rectWnd.left, rectWnd.top, rectWnd.right - rectWnd.left, rectWnd.bottom - rectWnd.top, TRUE); } // // // Function: OnAbout // // Purpose: Show the about box for the Whiteboard application. This // method is called whenever a WM_COMMAND with IDM_ABOUT // is issued by Windows. // // LRESULT WbMainWindow::OnAbout() { ::DialogBoxParam(g_hInstance, MAKEINTRESOURCE(ABOUTBOX), m_hwnd, AboutDlgProc, 0); return S_OK; } INT_PTR AboutDlgProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam) { BOOL fHandled = FALSE; switch (uMessage) { case WM_INITDIALOG: { TCHAR szFormat[256]; TCHAR szVersion[512]; ::GetDlgItemText(hwnd, IDC_ABOUTVERSION, szFormat, 256); wsprintf(szVersion, szFormat, VER_PRODUCTRELEASE_STR, VER_PRODUCTVERSION_STR); ::SetDlgItemText(hwnd, IDC_ABOUTVERSION, szVersion); fHandled = TRUE; break; } case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: case IDCANCEL: switch (GET_WM_COMMAND_CMD(wParam, lParam)) { case BN_CLICKED: ::EndDialog(hwnd, IDCANCEL); break; } break; } fHandled = TRUE; break; } return(fHandled); } void WbMainWindow::UpdateWindowTitle(void) { TCHAR szCaption[MAX_PATH * 2]; TCHAR szFileName[MAX_PATH * 2]; UINT captionID; if (! g_pNMWBOBJ->IsInConference()) { captionID = IDS_WB_NOT_IN_CALL_WINDOW_CAPTION; } else { captionID = IDS_WB_IN_CALL_WINDOW_CAPTION; } ::LoadString(g_hInstance, captionID, szFileName, sizeof(szFileName) ); wsprintf(szCaption, szFileName, GetFileNameStr(), g_pNMWBOBJ->m_cOtherMembers); SetWindowText(m_hwnd, szCaption); } // // // Function: SelectWindow // // Purpose: Let the user select a window for grabbing // // HWND WbMainWindow::SelectWindow(void) { POINT mousePos; // Mouse position HWND hwndSelected = NULL; // Window clicked on MSG msg; // Current message // Load the grabbing cursors HCURSOR hGrabCursor = ::LoadCursor(g_hInstance, MAKEINTRESOURCE( GRABCURSOR ) ); // Capture the mouse UT_CaptureMouse(m_hwnd); // Ensure we receive all keyboard messages. ::SetFocus(m_hwnd); // Reset the CancelMode state ResetCancelMode(); // Change to the grab cursor HCURSOR hOldCursor = ::SetCursor(hGrabCursor); // Trap all mouse messages until a WM_LBUTTONUP is received for ( ; ; ) { // Wait for the next message ::WaitMessage(); // Cancel if we have been sent a WM_CANCELMODE message if (CancelModeSent()) { break; } // If it is a mouse message, process it if (::PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE)) { if (msg.message == WM_LBUTTONUP) { // Get mouse position mousePos.x = (short)LOWORD(msg.lParam); mousePos.y = (short)HIWORD(msg.lParam); // Convert to screen coordinates ::ClientToScreen(m_hwnd, &mousePos); // Get the window under the mouse hwndSelected = ::WindowFromPoint(mousePos); // Leave the loop break; } } // Cancel if ESCAPE is pressed. // or if another window receives the focus else if (::PeekMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)) { if (msg.wParam == VK_ESCAPE) { break; } } } // Release the mouse UT_ReleaseMouse(m_hwnd); // Restore the cursor ::SetCursor(hOldCursor); return(hwndSelected); } // // // Function: OnGrabWindow // // Purpose: Allows the user to grab a bitmap of a window // // LRESULT WbMainWindow::OnGrabWindow(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnGrabWindow"); if (::DialogBoxParam(g_hInstance, MAKEINTRESOURCE(WARNSELECTWINDOW), m_hwnd, WarnSelectWindowDlgProc, 0) != IDOK) { // User cancelled; bail out return S_OK;; } // Hide the application windows ::ShowWindow(m_hwnd, SW_HIDE); HWND mainUIhWnd = FindWindow("MPWClass\0" , NULL); if(IsWindowVisible(mainUIhWnd)) { ::UpdateWindow(mainUIhWnd); } // Get window selection from the user HWND hwndSelected = SelectWindow(); if (hwndSelected != NULL) { // Walk back to the find the 'real' window ancestor HWND hwndParent; // The following piece of code attempts to find the frame window // enclosing the selected window. This allows us to bring the // enclosing window to the top, bringing the child window with it. DWORD dwStyle; while ((hwndParent = ::GetParent(hwndSelected)) != NULL) { // If we have reached a stand-alone window, stop the search dwStyle = ::GetWindowLong(hwndSelected, GWL_STYLE); if ( ((dwStyle & WS_POPUP) == WS_POPUP) || ((dwStyle & WS_THICKFRAME) == WS_THICKFRAME) || ((dwStyle & WS_DLGFRAME) == WS_DLGFRAME)) { break; } // Move up to the parent window hwndSelected = hwndParent; } // Bring the selected window to the top ::BringWindowToTop(hwndSelected); ::UpdateWindow(hwndSelected); // Get an image copy of the window RECT areaRect; ::GetWindowRect(hwndSelected, &areaRect); BitmapObj* dib; DBG_SAVE_FILE_LINE dib = new BitmapObj(TOOLTYPE_FILLEDBOX); dib->FromScreenArea(&areaRect); if(dib->m_lpbiImage == NULL) { delete dib; return S_FALSE; } // Add the new grabbed bitmap AddCapturedImage(dib); // Force the selection tool to be selected ::PostMessage(m_hwnd, WM_COMMAND, IDM_TOOLS_START, 0L); } // Show the windows again ::ShowWindow(m_hwnd, SW_SHOW); // Restore the focus to the drawing area ::SetFocus(m_drawingArea.m_hwnd); return S_OK; } // // WarnSelectWindowDlgProc() // This puts up the warning/explanation dialog. We use the default settings // or whatever the user chose last time this dialog was up. // INT_PTR CALLBACK WarnSelectWindowDlgProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam) { BOOL fHandled = FALSE; switch (uMessage) { case WM_INITDIALOG: { if (OPT_GetBooleanOption( OPT_MAIN_SELECTWINDOW_NOTAGAIN, DFLT_MAIN_SELECTWINDOW_NOTAGAIN)) { // End this right away, the user doesn't want a warning ::EndDialog(hwnd, IDOK); } fHandled = TRUE; break; } case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: switch (GET_WM_COMMAND_CMD(wParam, lParam)) { case BN_CLICKED: // // Update settings -- note that we don't have to write out // FALSE--we wouldn't be in the dialog in the first place // if the current setting weren't already FALSE. // if (::IsDlgButtonChecked(hwnd, IDC_SWWARN_NOTAGAIN)) { OPT_SetBooleanOption(OPT_MAIN_SELECTWINDOW_NOTAGAIN, TRUE); } ::EndDialog(hwnd, IDOK); break; } break; case IDCANCEL: switch (GET_WM_COMMAND_CMD(wParam, lParam)) { case BN_CLICKED: ::EndDialog(hwnd, IDCANCEL); break; } break; } fHandled = TRUE; break; } return(fHandled); } // // // Function: ShowAllWindows // // Purpose: Show or hide the main window and associated windows // // void WbMainWindow::ShowAllWindows(int iShow) { // Show/hide the main window ::ShowWindow(m_hwnd, iShow); // Show/hide the tool window if (m_bToolBarOn) { ::ShowWindow(m_TB.m_hwnd, iShow); } } // // // Function: OnGrabArea // // Purpose: Allows the user to grab a bitmap of an area of the screen // // LRESULT WbMainWindow::OnGrabArea(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnGrabArea"); if (::DialogBoxParam(g_hInstance, MAKEINTRESOURCE(WARNSELECTAREA), m_hwnd, WarnSelectAreaDlgProc, 0) != IDOK) { // User cancelled, so bail out return S_OK;; } // Hide the application windows ::ShowWindow(m_hwnd, SW_HIDE); HWND mainUIhWnd = FindWindow("MPWClass\0" , NULL); if(IsWindowVisible(mainUIhWnd)) { ::UpdateWindow(mainUIhWnd); } // Load the grabbing cursors HCURSOR hGrabCursor = ::LoadCursor(g_hInstance, MAKEINTRESOURCE( PENCURSOR ) ); // Capture the mouse UT_CaptureMouse(m_hwnd); // Ensure we receive all keyboard messages. ::SetFocus(m_hwnd); // Reset the CancelMode status ResetCancelMode(); // Change to the grab cursor HCURSOR hOldCursor = ::SetCursor(hGrabCursor); // Let the user select the area to be grabbed RECT rect; int tmp; GetGrabArea(&rect); // Normalize coords if (rect.right < rect.left) { tmp = rect.left; rect.left = rect.right; rect.right = tmp; } if (rect.bottom < rect.top) { tmp = rect.top; rect.top = rect.bottom; rect.bottom = tmp; } BitmapObj* dib; DBG_SAVE_FILE_LINE dib = new BitmapObj(TOOLTYPE_FILLEDBOX); if (!::IsRectEmpty(&rect)) { // Get a bitmap copy of the screen area dib->FromScreenArea(&rect); } // Show the windows again now - if we do it later we get the bitmap to // be added re-drawn twice (once on the window show and once when the // graphic added indication arrives). ::ShowWindow(m_hwnd, SW_SHOW); ::UpdateWindow(m_hwnd); if (!::IsRectEmpty(&rect) && dib->m_lpbiImage) { // Add the bitmap AddCapturedImage(dib); // Force the selection tool to be selected ::PostMessage(m_hwnd, WM_COMMAND, IDM_TOOLS_START, 0L); } else { delete dib; dib = NULL; } // Release the mouse UT_ReleaseMouse(m_hwnd); // Restore the cursor ::SetCursor(hOldCursor); // Restore the focus to the drawing area ::SetFocus(m_drawingArea.m_hwnd); if(dib) { dib->Draw(); } return S_OK; } // // WarnSelectArea dialog handler // INT_PTR CALLBACK WarnSelectAreaDlgProc(HWND hwnd, UINT uMessage, WPARAM wParam, LPARAM lParam) { BOOL fHandled = FALSE; switch (uMessage) { case WM_INITDIALOG: if (OPT_GetBooleanOption(OPT_MAIN_SELECTAREA_NOTAGAIN, DFLT_MAIN_SELECTAREA_NOTAGAIN)) { // End this right away, the user doesn't want a warning ::EndDialog(hwnd, IDOK); } fHandled = TRUE; break; case WM_COMMAND: switch (GET_WM_COMMAND_ID(wParam, lParam)) { case IDOK: switch (GET_WM_COMMAND_CMD(wParam, lParam)) { case BN_CLICKED: // // Update settings -- note that we don't have to write out // FALSE--we wouldn't be in the dialog in the first place // if the current setting weren't already FALSE. // if (::IsDlgButtonChecked(hwnd, IDC_SAWARN_NOTAGAIN)) { OPT_SetBooleanOption(OPT_MAIN_SELECTAREA_NOTAGAIN, TRUE); } ::EndDialog(hwnd, IDOK); break; } break; case IDCANCEL: switch (GET_WM_COMMAND_CMD(wParam, lParam)) { case BN_CLICKED: ::EndDialog(hwnd, IDCANCEL); break; } } fHandled = TRUE; break; } return(fHandled); } // // // Function: GetGrabArea // // Purpose: Allows the user to grab a bitmap of an area of the screen // // void WbMainWindow::GetGrabArea(LPRECT lprect) { POINT mousePos; // Mouse position MSG msg; // Current message BOOL tracking = FALSE; // Flag indicating mouse button is down HDC hDC = NULL; POINT grabStartPoint; // Start point (when mouse button is pressed) POINT grabEndPoint; // End point (when mouse button is released) POINT grabCurrPoint; // Current mouse position MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::GetGrabArea"); // Set the result to an empty rectangle ::SetRectEmpty(lprect); // Create the rectangle to be used for tracking DrawObj* pRectangle = NULL; DBG_SAVE_FILE_LINE pRectangle = new DrawObj(rectangle_chosen, TOOLTYPE_SELECT); if(NULL == pRectangle) { ERROR_OUT(("Failed to allocate DrawObj")); goto GrabAreaCleanup; } pRectangle->SetPenColor(RGB(0,0,0), TRUE); pRectangle->SetFillColor(RGB(255,255,255), FALSE); pRectangle->SetLineStyle(PS_DOT); pRectangle->SetPenThickness(1); // Get the DC for tracking HWND hDesktopWnd = ::GetDesktopWindow(); hDC = ::GetWindowDC(hDesktopWnd); if (hDC == NULL) { WARNING_OUT(("NULL desktop DC")); goto GrabAreaCleanup; } RECT rect; // Trap all mouse messages until a WM_LBUTTONUP is received for ( ; ; ) { // Wait for the next message ::WaitMessage(); // Cancel if we have been sent a WM_CANCELMODE message if (CancelModeSent()) { TRACE_MSG(("canceling grab")); // Erase the last tracking rectangle if (!EqualPoint(grabStartPoint, grabEndPoint)) { rect.top = grabStartPoint.y; rect.left = grabStartPoint.x; rect.bottom = grabEndPoint.y; rect.right = grabEndPoint.x; pRectangle->SetRect(&rect); pRectangle->SetBoundsRect(&rect); pRectangle->Draw(hDC); } break; } // If it is a mouse message, process it if (::PeekMessage(&msg, NULL, WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE)) { // Get mouse position TRACE_MSG( ("msg = %x, lParam = %0x", msg.message, msg.lParam) ); mousePos.x = (short)LOWORD(msg.lParam); mousePos.y = (short)HIWORD(msg.lParam); TRACE_MSG( ("mousePos = %d,%d", mousePos.x, mousePos.y) ); // Convert to screen coordinates ::ClientToScreen(m_hwnd, &mousePos); grabCurrPoint = mousePos; switch (msg.message) { // Starting the grab case WM_LBUTTONDOWN: // Save the starting position TRACE_MSG(("grabbing start position")); grabStartPoint = mousePos; grabEndPoint = mousePos; tracking = TRUE; break; // Completing the rectangle case WM_LBUTTONUP: { tracking = FALSE; // Check that there is an area to capture TRACE_MSG(("grabbing end position")); if (EqualPoint(grabStartPoint, grabCurrPoint)) { TRACE_MSG(("start == end, skipping grab")); goto GrabAreaCleanup; } // Erase the last tracking rectangle if (!EqualPoint(grabStartPoint, grabEndPoint)) { rect.top = grabStartPoint.y; rect.left = grabStartPoint.x; rect.bottom = grabEndPoint.y; rect.right = grabEndPoint.x; pRectangle->SetRect(&rect); pRectangle->SetBoundsRect(&rect); pRectangle->Draw(hDC); } // Update the rectangle object rect.top = grabStartPoint.y; rect.left = grabStartPoint.x; rect.bottom = grabCurrPoint.y; rect.right = grabCurrPoint.x; pRectangle->SetRect(&rect); pRectangle->SetBoundsRect(&rect); pRectangle->GetBoundsRect(lprect); // We are done goto GrabAreaCleanup; } break; // Continuing the rectangle case WM_MOUSEMOVE: if (tracking) { TRACE_MSG(("tracking grab")); // Erase the last tracking rectangle if (!EqualPoint(grabStartPoint, grabEndPoint)) { rect.top = grabStartPoint.y; rect.left = grabStartPoint.x; rect.bottom = grabEndPoint.y; rect.right = grabEndPoint.x; pRectangle->SetRect(&rect); pRectangle->SetBoundsRect(&rect); pRectangle->Draw(hDC); } // Draw the new rectangle if (!EqualPoint(grabStartPoint, grabCurrPoint)) { // Save the new box end point grabEndPoint = grabCurrPoint; // Draw the rectangle TRACE_MSG( ("grabStartPoint = %d,%d", grabStartPoint.x, grabStartPoint.y) ); TRACE_MSG( ("grabEndPoint = %d,%d", grabEndPoint.x, grabEndPoint.y) ); rect.top = grabStartPoint.y; rect.left = grabStartPoint.x; rect.bottom = grabEndPoint.y; rect.right = grabEndPoint.x; pRectangle->SetRect(&rect); pRectangle->SetBoundsRect(&rect); pRectangle->Draw(hDC); } } break; } } // Cancel if ESCAPE is pressed. else if (::PeekMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)) { if( ((msg.message == WM_KEYUP)||(msg.message == WM_SYSKEYUP))&& (msg.wParam == VK_ESCAPE) ) { TRACE_MSG(("grab cancelled by ESC")); // Erase the last tracking rectangle if (!EqualPoint(grabStartPoint, grabEndPoint)) { rect.top = grabStartPoint.y; rect.left = grabStartPoint.x; rect.bottom = grabEndPoint.y; rect.right = grabEndPoint.x; pRectangle->SetRect(&rect); pRectangle->Draw(hDC); } break; } } } GrabAreaCleanup: // Release the device context (if we have it) if (hDC != NULL) { ::ReleaseDC(hDesktopWnd, hDC); } delete pRectangle; } // // // Function: AddCapturedImage // // Purpose: Add a bitmap to the contents (adding a new page for it // if necessary). // // void WbMainWindow::AddCapturedImage(BitmapObj* dib) { // Position the grabbed object at the top left of the currently visible // area. RECT rcVis; m_drawingArea.GetVisibleRect(&rcVis); dib->MoveTo(rcVis.left, rcVis.top); dib->Draw(); // Add the new grabbed bitmap dib->AddToWorkspace(); } // // // Function: OnPrint // // Purpose: Print the contents of the drawing pane // // LRESULT WbMainWindow::OnPrint() { BOOL bPrintError = FALSE; PRINTDLG pd; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnPrint"); if (!IsIdle()) { // post an error message indicating the whiteboard is busy ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_WB, WB_RC_BUSY); return S_FALSE; } // // Initialize the PRINTDLG structure // ZeroMemory(&pd, sizeof(pd)); pd.lStructSize = sizeof(pd); pd.hInstance = g_hInstance; pd.hwndOwner = m_hwnd; pd.Flags = PD_ALLPAGES | PD_RETURNDC | PD_PAGENUMS | PD_HIDEPRINTTOFILE | PD_NOSELECTION; pd.nMinPage = 1; pd.nMaxPage = (WORD)g_numberOfWorkspaces; pd.nFromPage = pd.nMinPage; pd.nToPage = pd.nMaxPage; // Put up the COMMDLG print dialog if (::PrintDlg(&pd)) { int nStartPage, nEndPage; // Get the start and end page numbers to be printed if (pd.Flags & PD_PAGENUMS) { nStartPage = pd.nFromPage; nEndPage = pd.nToPage; } else { nStartPage = pd.nMinPage; nEndPage = pd.nMaxPage; } // Check whether any pages are to be printed if (nStartPage <= pd.nMaxPage) { // Ensure that the start and end pages lie within range. nStartPage = max(nStartPage, pd.nMinPage); nEndPage = min(nEndPage, pd.nMaxPage); // Get the printer and output port names. // These are written to the dialog for the user to see // in the OnInitDialog member. TCHAR szDeviceName[2*_MAX_PATH]; LPDEVNAMES lpDev; // Device name if (pd.hDevNames == NULL) { szDeviceName[0] = 0; } else { lpDev = (LPDEVNAMES)::GlobalLock(pd.hDevNames); wsprintf(szDeviceName, "%s %s", (LPCTSTR)lpDev + lpDev->wDeviceOffset, (LPCTSTR)lpDev + lpDev->wOutputOffset); ::GlobalUnlock(pd.hDevNames); } // // Tell the printer we are starting the print. // Note that the printer object handles the cancellation dialog. WbPrinter printer(szDeviceName); TCHAR szJobName[_MAX_PATH]; ::LoadString(g_hInstance, IDS_PRINT_NAME, szJobName, _MAX_PATH); int nPrintResult = printer.StartDoc(pd.hDC, szJobName, nStartPage); if (nPrintResult < 0) { WARNING_OUT(("Print result %d", nPrintResult)); bPrintError = TRUE; } else { // Find out how many copies to print int copyNum; copyNum = 0; while ((copyNum < pd.nCopies) && !bPrintError) { // Loop through all pages int nPrintPage = 0; WBPOSITION pos; WorkspaceObj * pWorkspace = NULL; pos = g_pListOfWorkspaces->GetHeadPosition(); while(pos) { pWorkspace = (WorkspaceObj*) g_pListOfWorkspaces->GetNext(pos); nPrintPage++; if (nPrintPage >= nStartPage && nPrintPage <= nEndPage // We are in the range && pWorkspace && pWorkspace->GetHead() != NULL) // is there anything in the workspace { // Tell the printer we are starting a new page printer.StartPage(pd.hDC, nPrintPage); if (!printer.Error()) { RECT rectArea; rectArea.left = 0; rectArea.top = 0; rectArea.right = DRAW_WIDTH; rectArea.bottom = DRAW_HEIGHT; // Print the page PG_Print(pWorkspace, pd.hDC, &rectArea); // Inform the printer that the page is complete printer.EndPage(pd.hDC); } else { bPrintError = TRUE; break; } } } copyNum++; } // The print has completed nPrintResult = printer.EndDoc(pd.hDC); if (nPrintResult < 0) { WARNING_OUT(("Print result %d", nPrintResult)); bPrintError = TRUE; } // reset the error if the user cancelled the print if (printer.Aborted()) { WARNING_OUT(("User cancelled print")); bPrintError = FALSE; } } } } // Inform the user if an error occurred if (bPrintError) { // display a message informing the user the job terminated ::PostMessage(m_hwnd, WM_USER_DISPLAY_ERROR, WBFE_RC_PRINTER, 0); } // // Cleanup the hDevMode, hDevNames, and hdc blocks if allocated // if (pd.hDevMode != NULL) { ::GlobalFree(pd.hDevMode); pd.hDevMode = NULL; } if (pd.hDevNames != NULL) { ::GlobalFree(pd.hDevNames); pd.hDevNames = NULL; } if (pd.hDC != NULL) { ::DeleteDC(pd.hDC); pd.hDC = NULL; } return S_OK; } // // // Function: InsertPageAfter // // Purpose: Insert a new page after the specified page. // // void WbMainWindow::InsertPageAfter(WorkspaceObj * pCurrentWorkspace) { // // Create a standard workspace // if(g_numberOfWorkspaces < WB_MAX_WORKSPACES) { // // If we were editing text // if (g_pDraw->TextEditActive()) { g_pDraw->EndTextEntry(TRUE); } BOOL bRemote = FALSE; if(m_pLocalRemotePointer) { bRemote = TRUE; OnRemotePointer(); } WorkspaceObj * pObj; DBG_SAVE_FILE_LINE pObj = new WorkspaceObj(); pObj->AddToWorkspace(); if(bRemote) { OnRemotePointer(); } } } // // // Function: OnInsertPageAfter // // Purpose: Insert a new page after the current page // // LRESULT WbMainWindow::OnInsertPageAfter() { // Insert the new page InsertPageAfter(g_pCurrentWorkspace); return S_OK; } // // // Function: OnDeletePage // // Purpose: Delete the current page // // LRESULT WbMainWindow::OnDeletePage() { // // Clear the page // if(g_pListOfWorkspaces->GetHeadPosition() == g_pListOfWorkspaces->GetTailPosition()) { OnClearPage(TRUE); } else { LRESULT result = OnClearPage(FALSE); // // If we had more pages move to the previous page // if(result == IDYES) { // // Deleted locally // g_pCurrentWorkspace->DeletedLocally(); // // If the text editor is active // if(m_drawingArea.TextEditActive()) { m_drawingArea.DeactivateTextEditor(); } BOOL remotePointerIsOn = FALSE; if(g_pMain->m_pLocalRemotePointer) { g_pMain->OnRemotePointer(); remotePointerIsOn = TRUE; } // // Remove the workspace and point current to the correct one. // WorkspaceObj * pWorkspace = RemoveWorkspace(g_pCurrentWorkspace); g_pMain->GoPage(pWorkspace); if(remotePointerIsOn) { g_pMain->OnRemotePointer(); } } } return S_OK; } // // // Function: OnRemotePointer // // Purpose: Create a remote pointer // // LRESULT WbMainWindow::OnRemotePointer(void) { if(m_pLocalRemotePointer == NULL) { BitmapObj* remotePtr; DBG_SAVE_FILE_LINE m_pLocalRemotePointer = new BitmapObj(TOOLTYPE_REMOTEPOINTER); if(g_pMain->m_localRemotePointerPosition.x < 0 && g_pMain->m_localRemotePointerPosition.y < 0 ) { // Position the remote pointer in center of the drawing area RECT rcVis; m_drawingArea.GetVisibleRect(&rcVis); m_localRemotePointerPosition.x = rcVis.left + (rcVis.right - rcVis.left)/2; m_localRemotePointerPosition.y = rcVis.top + (rcVis.bottom - rcVis.top)/2; } m_pLocalRemotePointer->MoveTo(m_localRemotePointerPosition.x ,m_localRemotePointerPosition.y); COLORREF color; color = g_crDefaultColors[g_MyIndex + 1]; m_pLocalRemotePointer->CreateColoredIcon(color); // // If we couldn't create an image for teh remote pointer bitmap // if(m_pLocalRemotePointer->m_lpbiImage == NULL) { delete m_pLocalRemotePointer; m_pLocalRemotePointer = NULL; return S_FALSE; } m_pLocalRemotePointer->Draw(FALSE); // Add the new grabbed bitmap m_pLocalRemotePointer->AddToWorkspace(); m_TB.PushDown(IDM_REMOTE); CheckMenuItem(IDM_REMOTE); // Start the timer for updating the graphic (this is only for updating // the graphic when the user stops moving the pointer but keeps the // mouse button down). ::SetTimer(g_pDraw->m_hwnd, TIMER_REMOTE_POINTER_UPDATE, DRAW_REMOTEPOINTERDELAY, NULL); } else { ::KillTimer(g_pDraw->m_hwnd, TIMER_REMOTE_POINTER_UPDATE); m_pLocalRemotePointer->DeletedLocally(); g_pCurrentWorkspace->RemoveT126Object(m_pLocalRemotePointer); m_pLocalRemotePointer = NULL; m_TB.PopUp(IDM_REMOTE); UncheckMenuItem(IDM_REMOTE); } return S_OK; } // // // Function: OnSync // // Purpose: Sync or unsync the Whiteboard with other users // // LRESULT WbMainWindow::OnSync(void) { // Determine whether we are currently synced if (m_drawingArea.IsSynced()) { // currently synced, so unsync Unsync(); } else { // currently unsynced, so sync Sync(); } m_drawingArea.SetSync(!m_drawingArea.IsSynced()); EnableToolbar( TRUE ); m_AG.EnablePageCtrls(TRUE); return S_OK; } // // // Function: Sync // // Purpose: Sync the Whiteboard with other users // // void WbMainWindow::Sync(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::Sync"); m_TB.PushDown(IDM_SYNC); CheckMenuItem(IDM_SYNC); GotoPage(g_pConferenceWorkspace); } // Sync // // // Function: Unsync // // Purpose: Unsync the Whiteboard with other users // // void WbMainWindow::Unsync(void) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::Unsync"); m_TB.PopUp(IDM_SYNC); UncheckMenuItem(IDM_SYNC); } // Unsync LRESULT WbMainWindow::OnConfShutdown( WPARAM, LPARAM ) { if (OnQueryEndSession()) { ::SendMessage(m_hwnd, WM_CLOSE, 0, 0); // do close immediately // : // DON'T DO ANYTHING else at this point except for exit. return( 0 );// tell conf ok to shutdown } else return( (LRESULT)g_cuEndSessionAbort ); // don't shutdown } // // // Function: OnQueryEndSession // // Purpose: Ensure user is prompted to save changes when windows is // ended. // // LRESULT WbMainWindow::OnQueryEndSession(void) { HWND hwndPopup; if ((hwndPopup = ::GetLastActivePopup(m_hwnd)) != m_hwnd) { ::Message(NULL, IDS_DEFAULT, IDS_CANTCLOSE ); ::BringWindowToTop(hwndPopup); return( FALSE ); } // If changes are required then prompt the user to save int iDoNew = IDYES; if (IsIdle()) { iDoNew = QuerySaveRequired(TRUE); if (iDoNew == IDYES) { // Save the changes iDoNew = (int)OnSave(FALSE); } } // remember what we did so OnClose can act appropriately m_bQuerySysShutdown = (iDoNew != IDCANCEL); // If the user did not cancel, let windows exit return( m_bQuerySysShutdown ); } // // // Function: UnlockDrawingArea // // Purpose: Unlock the drawing area and enable the appropriate buttons // // // void WbMainWindow::UnlockDrawingArea() { m_drawingArea.Unlock(); { EnableToolbar( TRUE ); m_AG.EnablePageCtrls(TRUE); } // // Show the tool attributes group. // m_AG.DisplayTool(m_pCurrentTool); } // // // Function: LockDrawingArea // // Purpose: Lock the drawing area and enable the appropriate buttons // // // void WbMainWindow::LockDrawingArea() { m_drawingArea.Lock(); if(g_pNMWBOBJ->m_LockerID != g_MyMemberID) { // Disable tool-bar buttons that cannot be used while locked EnableToolbar( FALSE ); m_AG.EnablePageCtrls(FALSE); // // Hide the tool attributes // if (m_WG.m_hwnd != NULL) { ::ShowWindow(m_WG.m_hwnd, SW_HIDE); } m_AG.Hide(); } } void WbMainWindow::EnableToolbar( BOOL bEnable ) { if (bEnable) { m_TB.Enable(IDM_SELECT); // don't allow text editing in zoom mode if( m_drawingArea.Zoomed() ) m_TB.Disable(IDM_TEXT); else m_TB.Enable(IDM_TEXT); m_TB.Enable(IDM_PEN); m_TB.Enable(IDM_HIGHLIGHT); m_TB.Enable(IDM_LINE); m_TB.Enable(IDM_ZOOM); m_TB.Enable(IDM_BOX); m_TB.Enable(IDM_FILLED_BOX); m_TB.Enable(IDM_ELLIPSE); m_TB.Enable(IDM_FILLED_ELLIPSE); m_TB.Enable(IDM_ERASER); m_TB.Enable(IDM_GRAB_AREA); m_TB.Enable(IDM_GRAB_WINDOW); // // If we are not synced we can't lock the other nodes // if(g_pDraw->IsSynced()) { m_TB.PushDown(IDM_SYNC); m_TB.Enable(IDM_LOCK); } else { m_TB.PopUp(IDM_SYNC); m_TB.Disable(IDM_LOCK); } if(m_drawingArea.IsLocked()) { m_TB.Disable(IDM_SYNC); } else { m_TB.Enable(IDM_SYNC); } m_TB.Enable(IDM_REMOTE); } else { m_TB.Disable(IDM_SELECT); m_TB.Disable(IDM_PEN); m_TB.Disable(IDM_HIGHLIGHT); m_TB.Disable(IDM_TEXT); m_TB.Disable(IDM_LINE); m_TB.Disable(IDM_ZOOM); m_TB.Disable(IDM_BOX); m_TB.Disable(IDM_FILLED_BOX); m_TB.Disable(IDM_ELLIPSE); m_TB.Disable(IDM_FILLED_ELLIPSE); m_TB.Disable(IDM_ERASER); m_TB.Disable(IDM_REMOTE); m_TB.Disable(IDM_GRAB_AREA); m_TB.Disable(IDM_GRAB_WINDOW); m_TB.Disable(IDM_LOCK); m_TB.Disable(IDM_SYNC); } } // // // Function: UpdatePageButtons // // Purpose: Enable or disable the page buttons, according to the current // state. // // // void WbMainWindow::UpdatePageButtons() { BOOL bEnable = TRUE; if(!g_pCurrentWorkspace) { g_numberOfWorkspaces = 0; bEnable = FALSE; } else { // // Can we update this workspace // bEnable = g_pCurrentWorkspace->GetUpdatesEnabled(); // // If it is locked, is it locked by us // if(!bEnable) { bEnable |= g_pNMWBOBJ->m_LockerID == g_MyMemberID; } } m_AG.EnablePageCtrls(bEnable); WBPOSITION pos; WorkspaceObj * pWorkspace; UINT pageNumber = 0; pos = g_pListOfWorkspaces->GetHeadPosition(); while(pos) { pageNumber++; pWorkspace = (WorkspaceObj*)g_pListOfWorkspaces->GetNext(pos); if(g_pCurrentWorkspace == pWorkspace) { break; } } m_AG.SetCurrentPageNumber(pageNumber); m_AG.SetLastPageNumber(g_numberOfWorkspaces); EnableToolbar( bEnable ); } // // // Function: CancelLoad // // Purpose: Cancel any load in progress // // void WbMainWindow::CancelLoad(BOOL bReleaseLock) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::CancelLoad"); // reset file name to untitled ZeroMemory(m_strFileName, sizeof(m_strFileName)); // reset the whiteboard substate SetSubstate(SUBSTATE_IDLE); } // // // Function: IsIdle // // Purpose: Returns true if the main window is idle (in a call and not // loading a file/performing a new) // // BOOL WbMainWindow::IsIdle() { return(m_uiSubState == SUBSTATE_IDLE); } // // // Function: SetSubstate // // Purpose: Sets the substate, informing the page sorter dialog of the // change, if necessary. // // void WbMainWindow::SetSubstate(UINT newSubState) { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::SetSubstate"); // substate only valid if in a call if (newSubState != m_uiSubState) { DBG_SAVE_FILE_LINE m_uiSubState = newSubState; // Trace the substate change switch (m_uiSubState) { case SUBSTATE_IDLE: TRACE_DEBUG(("set substate to IDLE")); break; case SUBSTATE_LOADING: TRACE_DEBUG(("set substate to LOADING")); break; case SUBSTATE_SAVING: TRACE_DEBUG(("set substate to SAVING")); break; case SUBSTATE_NEW_IN_PROGRESS: TRACE_DEBUG(("set substate to NEW_IN_PROGRESS")); break; default: ERROR_OUT(("Unknown substate %hd",m_uiSubState)); break; } // update the page buttons (may have become enabled/disabled) UpdatePageButtons(); } } // // // Function: PositionUpdated // // Purpose: Called when the drawing area position has changed. // change, if necessary. // // void WbMainWindow::PositionUpdated() { RECT rectDraw; m_drawingArea.GetVisibleRect(&rectDraw); g_pDraw->InvalidateSurfaceRect(&rectDraw,FALSE); } // // // Function : OnEndSession // // Purpose : Called when Windows is exiting // // void WbMainWindow::OnEndSession(BOOL bEnding) { if (bEnding) { ::PostQuitMessage(0); } else { m_bQuerySysShutdown = FALSE; // never mind, cancel OnClose special handling } } // // Function: OnCancelMode() // // Purpose: Called whenever a WM_CANCELMODE message is sent to the frame // window. // WM_CANCELMODE is sent when another app or dialog receives the // input focus. The frame simply records that a WM_CANCELMODE // message has been sent. This fact is used by the SelectWindow // code to determine if it should cancel the selecting of a // window // // void WbMainWindow::OnCancelMode() { MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::OnCancelMode"); m_cancelModeSent = TRUE; // // Note: Not passed to the default handler as the default action on // WM_CANCELMODE is to release mouse capture - we shall do this // explicitly. // // blow off any dragging that might be in progress (bug 573) POINT pt; ::GetCursorPos( &pt ); ::ScreenToClient(m_drawingArea.m_hwnd, &pt); ::SendMessage(m_drawingArea.m_hwnd, WM_LBUTTONUP, 0, MAKELONG( pt.x, pt.y ) ); } void WbMainWindow::LoadCmdLine(LPCSTR szFilename) { int iOnSave; if (szFilename && *szFilename) { if( UsersMightLoseData( NULL, NULL ) ) // bug NM4db:418 return; // Don't prompt to save file if we're already loading if (m_uiSubState != SUBSTATE_LOADING ) { // Check whether there are changes to be saved iOnSave = QuerySaveRequired(TRUE); } else { return; } if (iOnSave == IDYES) { // User wants to save the drawing area contents int iResult = (int)OnSave(TRUE); if( iResult == IDOK ) { } else { // cancelled out of save, so cancel the open operation return; } } // load filename if( iOnSave != IDCANCEL ) LoadFile(szFilename); } } // // OnNotify() // Handles TTN_NEEDTEXTA and TTN_NEEDTEXTW // void WbMainWindow::OnNotify(UINT id, NMHDR * pNM) { UINT nID; HWND hwnd = NULL; POINT ptCurPos; UINT nTipStringID; if (!pNM) return; if (pNM->code == TTN_NEEDTEXTA) { TOOLTIPTEXTA *pTA = (TOOLTIPTEXTA *)pNM; // get id and hwnd if( pTA->uFlags & TTF_IDISHWND ) { // idFrom is actually the HWND of the tool hwnd = (HWND)pNM->idFrom; nID = ::GetDlgCtrlID(hwnd); } else { nID = (UINT)pNM->idFrom; } // get tip string id nTipStringID = GetTipId(hwnd, nID); if (nTipStringID == 0) return; // give it to em pTA->lpszText = MAKEINTRESOURCE( nTipStringID ); pTA->hinst = g_hInstance; } else if (pNM->code == TTN_NEEDTEXTW) { TOOLTIPTEXTW *pTW = (TOOLTIPTEXTW *)pNM; // get id and hwnd if( pTW->uFlags & TTF_IDISHWND ) { // idFrom is actually the HWND of the tool hwnd = (HWND)pNM->idFrom; nID = ::GetDlgCtrlID(hwnd); } else { nID = (UINT)pNM->idFrom; } // get tip string id nTipStringID = GetTipId(hwnd, nID ); if (nTipStringID == 0) return; // give it to em pTW->lpszText = (LPWSTR) MAKEINTRESOURCE( nTipStringID ); pTW->hinst = g_hInstance; } } // // GetTipId() // Finds the tooltip for a control in Whiteboard // UINT WbMainWindow::GetTipId(HWND hwndTip, UINT nID) { WbTool * pTool; BOOL bCheckedState; int nTipID; int nTipStringID; int i; // find tip stuff relevant for nID nTipID = -1; for( i=0; i<((sizeof g_tipIDsArray)/(sizeof (TIPIDS) )); i++ ) { if( g_tipIDsArray[i].nID == nID ) { nTipID = i; break; } } // valid? if( nTipID < 0 ) return( 0 ); // get checked state switch( g_tipIDsArray[ nTipID ].nCheck ) { case TB: bCheckedState = (::SendMessage(m_TB.m_hwnd, TB_ISBUTTONCHECKED, nID, 0) != 0); break; case BT: if (hwndTip != NULL) { bCheckedState = (::SendMessage(hwndTip, BM_GETSTATE, 0, 0) & 0x0003) == 1; } else bCheckedState = FALSE; break; case NA: default: bCheckedState = FALSE; break; } // get tip string id if( bCheckedState ) nTipStringID = g_tipIDsArray[ nTipID ].nDownTipID; else nTipStringID = g_tipIDsArray[ nTipID ].nUpTipID; // done return( nTipStringID ); } // gets default path if no saves or opens have been done yet // Returns FALSE if last default should be reused BOOL WbMainWindow::GetDefaultPath(LPTSTR csDefaultPath , UINT size) { DWORD dwType; DWORD dwBufLen = size; HKEY hDefaultKey = NULL; BOOL bRet =FALSE; if( !lstrlen(m_strFileName) ) { // a name has not been picked yet in this session, use path // to "My Documents" if( (RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", 0, KEY_READ, &hDefaultKey ) != ERROR_SUCCESS) || (RegQueryValueEx( hDefaultKey, "Personal", NULL, &dwType, (BYTE *)csDefaultPath, &dwBufLen ) != ERROR_SUCCESS)) { // reg failed, use desktop LPITEMIDLIST pidl; if(SUCCEEDED(SHGetSpecialFolderLocation(GetDesktopWindow(),CSIDL_DESKTOPDIRECTORY,&pidl))) { bRet= SHGetPathFromIDList(pidl,csDefaultPath); } if( hDefaultKey != NULL ) RegCloseKey( hDefaultKey ); } else { bRet = TRUE; } } return bRet; } void WbMainWindow::OnSysColorChange( void ) { if (g_pCurrentWorkspace != NULL) { PG_ReinitPalettes(); ::InvalidateRect(m_hwnd, NULL, TRUE ); ::UpdateWindow(m_hwnd); } m_TB.RecolorButtonImages(); m_AG.RecolorButtonImages(); } // // posts a do-you-wana-do-that message if other users are in the conference // BOOL WbMainWindow::UsersMightLoseData( BOOL *pbWasPosted, HWND hwnd ) { if (g_pNMWBOBJ->GetNumberOfMembers() > 0) { if( pbWasPosted != NULL ) *pbWasPosted = TRUE; return( ::Message(hwnd, IDS_DEFAULT, IDS_MSG_USERSMIGHTLOSE, MB_YESNO | MB_ICONEXCLAMATION ) != IDYES ); } if( pbWasPosted != NULL ) *pbWasPosted = FALSE; return( FALSE ); } // // // Name: ContentsSave // // Purpose: Save the contents of the WB. // // Returns: Error code // // UINT WbMainWindow::ContentsSave(LPCSTR pFileName) { UINT result = 0; UINT index; HANDLE hFile; ULONG cbSizeWritten; T126WB_FILE_HEADER t126Header; WB_OBJ endOfFile; MLZ_EntryOut(ZONE_FUNCTION, "WbMainWindow::ContentsSave"); // // Open the file // m_hFile = CreateFile(pFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (m_hFile == INVALID_HANDLE_VALUE) { result = WB_RC_CREATE_FAILED; ERROR_OUT(("Error creating file, win32 err=%d", GetLastError())); goto CleanUp; } // // Create the file header. // memcpy(t126Header.functionProfile, T126WB_FP_NAME,sizeof(T126WB_FP_NAME)); t126Header.length = sizeof(T126WB_FILE_HEADER) + g_numberOfWorkspaces*sizeof(UINT); t126Header.version = T126WB_VERSION; t126Header.numberOfWorkspaces = g_numberOfWorkspaces; // // Save the header // if (!WriteFile(m_hFile, (void *) &t126Header, sizeof(T126WB_FILE_HEADER), &cbSizeWritten, NULL)) { result = WB_RC_WRITE_FAILED; ERROR_OUT(("Error writing length to file, win32 err=%d", GetLastError())); goto CleanUp; } WorkspaceObj* pWorkspace; WBPOSITION pos; index = 0; pos = g_pListOfWorkspaces->GetHeadPosition(); while(pos) { pWorkspace = (WorkspaceObj*)g_pListOfWorkspaces->GetNext(pos); ASSERT(pWorkspace); UINT numberOfObjects = pWorkspace->EnumerateObjectsInWorkspace(); // // Save the number of objects in each page // if (!WriteFile(m_hFile, (void *) &numberOfObjects, sizeof(numberOfObjects), &cbSizeWritten, NULL)) { result = WB_RC_WRITE_FAILED; ERROR_OUT(("Error writing length to file, win32 err=%d", GetLastError())); goto CleanUp; } index++; } ASSERT(index == g_numberOfWorkspaces); // // Loop through the pages, saving each as we go // g_bSavingFile = TRUE; ResendAllObjects(); // // The Last Object to be saved is the current workspace // g_pCurrentWorkspace->OnObjectEdit(); // // If we have successfully written the contents, we write an end-of-page // marker to the file. // ZeroMemory(&endOfFile, sizeof(endOfFile)); endOfFile.length = sizeof(endOfFile); endOfFile.type = TYPE_T126_END_OF_FILE; // // Write the end-of-file object // if (!WriteFile(m_hFile, (void *) &endOfFile, sizeof(endOfFile), &cbSizeWritten, NULL)) { result = WB_RC_WRITE_FAILED; ERROR_OUT(("Error writing length to file, win32 err=%d", GetLastError())); goto CleanUp; } CleanUp: // // Close the file // if (m_hFile != INVALID_HANDLE_VALUE) { CloseHandle(m_hFile); } // // If an error occurred in saving the contents to file, and the file was // opened, then delete it. // if (result != 0) { // // If the file was opened successfully, delete it // if (m_hFile != INVALID_HANDLE_VALUE) { DeleteFile(pFileName); } } g_bSavingFile = FALSE; return(result); } // // // Name: ObjectSave // // Purpose: Save a structure to file // // Returns: Error code // // UINT WbMainWindow::ObjectSave(UINT type, LPBYTE pData, UINT length) { ASSERT(m_hFile != INVALID_HANDLE_VALUE); UINT result = 0; ULONG cbSizeWritten; WB_OBJ objectHeader; objectHeader.length = sizeof(WB_OBJ) + length; objectHeader.type = type; // // Save the Header // if (! WriteFile(m_hFile, (void *) &objectHeader, sizeof(WB_OBJ), &cbSizeWritten, NULL)) { result = WB_RC_WRITE_FAILED; ERROR_OUT(("Error writing length to file, win32 err=%d", GetLastError())); goto bail; } ASSERT(cbSizeWritten == sizeof(WB_OBJ)); // // Save the object data // if (! WriteFile(m_hFile, pData, length, &cbSizeWritten, NULL)) { result = WB_RC_WRITE_FAILED; ERROR_OUT(("Error writing data to file, win32 err=%d", GetLastError())); goto bail; } ASSERT(cbSizeWritten == length); bail: return result; } // // // Function: ContentsLoad // // Purpose: Load a file and delete the current workspaces // // UINT WbMainWindow::ContentsLoad(LPCSTR pFileName) { BOOL bRemote; UINT result = 0; PT126WB_FILE_HEADER_AND_OBJECTS pHeader = NULL; // // Validate the file, and get a handle to it. // If there is an error, then no file handle is returned. // pHeader = ValidateFile(pFileName); if (pHeader == NULL) { result = WB_RC_BAD_FILE_FORMAT; goto bail; } delete pHeader; // // Remember if remote pointer is on // bRemote = FALSE; if (m_pLocalRemotePointer) { // Remove remote pointer from pages bRemote = TRUE; OnRemotePointer(); } // // Just before loading anything delete all the workspaces // ::InvalidateRect(g_pDraw->m_hwnd, NULL, TRUE); DeleteAllWorkspaces(TRUE); result = ObjectLoad(); // // Put remote pointer back if it was on // if (bRemote) { OnRemotePointer(); } // // The workspaces may have being saved as locked // Unlock all workspaces, and make sure the drawing area is unlocked // TogleLockInAllWorkspaces(FALSE, FALSE); // Not locked, don't send updates UnlockDrawingArea(); ResendAllObjects(); bail: if(INVALID_HANDLE_VALUE != m_hFile) { CloseHandle(m_hFile); } return(result); } // // // Function: ObjectLoad // // Purpose: Load t126 ASN1 objects from the file // // UINT WbMainWindow::ObjectLoad(void) { UINT result = 0; LPSTR pData = NULL; UINT length; DWORD cbSizeRead; BOOL readFileOk = TRUE; WB_OBJ objectHeader; while(readFileOk) { // // Read objects header info // readFileOk = ReadFile(m_hFile, (void *) &objectHeader, sizeof(WB_OBJ), &cbSizeRead, NULL); if ( !readFileOk ) { // // Make sure we return a sensible error. // ERROR_OUT(("reading object length, win32 err=%d, length=%d", GetLastError(), sizeof(WB_OBJ))); result = WB_RC_BAD_FILE_FORMAT; goto bail; } ASSERT(cbSizeRead == sizeof(WB_OBJ)); // // Read the object's raw data // length = objectHeader.length - sizeof(WB_OBJ); DBG_SAVE_FILE_LINE pData = (LPSTR)new BYTE[length]; readFileOk = ReadFile(m_hFile, (LPBYTE) pData, length, &cbSizeRead, NULL); if(! readFileOk) { // // Make sure we return a sensible error. // ERROR_OUT(("Reading object from file: win32 err=%d, asked for %d got %d bytes", GetLastError(), length, cbSizeRead)); result = WB_RC_BAD_FILE_FORMAT; goto bail; } ASSERT(cbSizeRead == length); // // It is an ASN1 t126 object // if(objectHeader.type == TYPE_T126_ASN_OBJECT) { // // Try decoding and adding it to the workspace // if(!T126_MCSSendDataIndication(length, (LPBYTE)pData, g_MyMemberID, TRUE)) { result = WB_RC_BAD_FILE_FORMAT; goto bail; } } // // If it is an end of file do a last check // else if(objectHeader.type == TYPE_T126_END_OF_FILE) { if(objectHeader.length != sizeof(WB_OBJ)) { result = WB_RC_BAD_FILE_FORMAT; } goto bail; } else { ERROR_OUT(("Don't know object type =%d , size=%d ; skipping to next object", objectHeader.type, length)); } delete [] pData; pData = NULL; } bail: if(pData) { delete [] pData; } return(result); } // // // Function: ValidateFile // // Purpose: Open a T126 file and check if it is valid, if it is the it will // return a pointer to the header structure // // PT126WB_FILE_HEADER_AND_OBJECTS WbMainWindow::ValidateFile(LPCSTR pFileName) { UINT result = 0; PT126WB_FILE_HEADER pFileHeader = NULL; PT126WB_FILE_HEADER_AND_OBJECTS pCompleteFileHeader = NULL; UINT length; ULONG cbSizeRead; BOOL fileOpen = FALSE; DBG_SAVE_FILE_LINE pFileHeader = new T126WB_FILE_HEADER[1]; if(pFileHeader == NULL) { WARNING_OUT(("Could not allocate memory to read the file header opening file, win32 err=%d", GetLastError())); result = WB_RC_CREATE_FAILED; goto bail; } // // Open the file // m_hFile = CreateFile(pFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (m_hFile == INVALID_HANDLE_VALUE) { WARNING_OUT(("Error opening file, win32 err=%d", GetLastError())); result = WB_RC_CREATE_FAILED; goto bail; } // // Show that we have opened the file successfully // fileOpen = TRUE; // // Read the file header // if (! ReadFile(m_hFile, (void *) pFileHeader, sizeof(T126WB_FILE_HEADER), &cbSizeRead, NULL)) { WARNING_OUT(("Error reading file header, win32 err=%d", GetLastError())); result = WB_RC_READ_FAILED; goto bail; } if (cbSizeRead != sizeof(T126WB_FILE_HEADER)) { WARNING_OUT(("Could not read file header")); result = WB_RC_BAD_FILE_FORMAT; goto bail; } // // Validate the file header // if (memcmp(pFileHeader->functionProfile, T126WB_FP_NAME, sizeof(T126WB_FP_NAME))) { WARNING_OUT(("Bad function profile in file header")); result = WB_RC_BAD_FILE_FORMAT; goto bail; } // // Check for version // if( pFileHeader->version < T126WB_VERSION) { WARNING_OUT(("Bad version number")); result = WB_RC_BAD_FILE_FORMAT; goto bail; } DBG_SAVE_FILE_LINE pCompleteFileHeader = (PT126WB_FILE_HEADER_AND_OBJECTS) new BYTE[sizeof(T126WB_FILE_HEADER) + pFileHeader->numberOfWorkspaces*sizeof(UINT)]; memcpy(pCompleteFileHeader, pFileHeader, sizeof(T126WB_FILE_HEADER)); // // Read the rest of the file header // if(! ReadFile(m_hFile, (void *) &pCompleteFileHeader->numberOfObjects[0], pFileHeader->numberOfWorkspaces*sizeof(UINT), &cbSizeRead, NULL)) { if(cbSizeRead != pFileHeader->numberOfWorkspaces) result = WB_RC_BAD_FILE_FORMAT; goto bail; } TRACE_DEBUG(("Opening file with %d workspaces", pFileHeader->numberOfWorkspaces)); #ifdef _DEBUG INT i; for(i = 0; i < (INT)pFileHeader->numberOfWorkspaces; i++) { TRACE_DEBUG(("Workspace %d contains %d objects", i+1, pCompleteFileHeader->numberOfObjects[i] )); } #endif bail: // // Close the file if there has been an error // if ( (fileOpen) && (result != 0)) { CloseHandle(m_hFile); m_hFile = INVALID_HANDLE_VALUE; } // // Delete allocated file header // if(pFileHeader) { delete [] pFileHeader; } // // if there was an error delete the return header // if(result != 0) { if(pCompleteFileHeader) { delete [] pCompleteFileHeader; pCompleteFileHeader = NULL; } } return pCompleteFileHeader; } // // // Function: GetFileNameStr // // Purpose: Return a plain file name string // // LPSTR WbMainWindow::GetFileNameStr(void) { UINT size = 2*_MAX_FNAME; if(m_pTitleFileName) { delete m_pTitleFileName; m_pTitleFileName = NULL; } DBG_SAVE_FILE_LINE m_pTitleFileName = new TCHAR[size]; if (!m_pTitleFileName) { ERROR_OUT(("GetWindowTitle: failed to allocate TitleFileName")); return(NULL); } // Set title to either the "Untitled" string, or the loaded file name if( (!lstrlen(m_strFileName))|| (GetFileTitle( m_strFileName, m_pTitleFileName, (WORD)size ) != 0) ) { ::LoadString(g_hInstance, IDS_UNTITLED , m_pTitleFileName, 2*_MAX_FNAME); } return (LPSTR)m_pTitleFileName; } 
[ "blindtiger@foxmail.com" ]
blindtiger@foxmail.com
b1f32050cf049d8d9946a9f248ac5cbc7233573c
57a31688cb25da41dd1d2bf1e2c18de4e72d530c
/src/crc.hpp
6352f1d01e6484b18db55ba1c0fc062d5bcd47ae
[]
no_license
Bnaich/Generator_signature
ad2010abf6aad0066e9d067d611ae2505835a2f8
3b8bf19ac02e1c1b07f169a2ce4b27d522a8a56e
refs/heads/master
2020-05-28T00:06:28.007044
2019-05-27T15:51:55
2019-05-27T15:51:55
188,827,732
0
0
null
null
null
null
UTF-8
C++
false
false
138
hpp
#ifndef TASK_CRC_HPP #define TASK_CRC_HPP #include <boost/crc.hpp> uint32_t get_crc(const uint8_t *, std::size_t); #endif //TASK_CRC_HPP
[ "maxim.y.scherbakov@gmail.com" ]
maxim.y.scherbakov@gmail.com
21695ef062ecc7ec5fbdc562cfd205023a312f8e
469573a8c80a5613daff244c1e7ae86478b87dd5
/src/protagonist.h
4fef9108c04806b602bfc13b00cb878558fed1f1
[]
no_license
claytical/Avoid-Squares
8000c1e42b410b37fe4bed2513b2350673de4829
0e73d17d2688385eff0c0734da09c9e9cc5e14c1
refs/heads/master
2016-08-06T11:47:27.330263
2013-07-27T22:38:51
2013-07-27T22:38:51
9,734,979
0
1
null
null
null
null
UTF-8
C++
false
false
663
h
// // protagonist.h // AvoidSquares // // Created by Clay Ewing on 7/9/11. #pragma once #include "ofMain.h" #include "ofxRetinaImage.h" #include "collectable.h" #include "enemy.h" #define HEALTHY 0 #define DEAD 12 #define LINE_ANIMATION_SPEED 1.5 class Protagonist { public: void display(); void create(int x, int y, int radius); void change(int amount); void moveTo(int x, int y); bool collide(Collectable c); bool collide(Enemy e); int collectEdge(); float x, y; int r,g,b; int width, height; int sides; int edgeCounter; bool lineAnimation[4]; ofPoint edges[4]; float animatedLine[4]; };
[ "c.ewing@miami.edu" ]
c.ewing@miami.edu
e296f1a28b34ad5e9f231c2ae81b9fbbe37c9953
3b6054a8c8447ad7b658c3ad98d95aa2d5277008
/start_project/Laghaim_Client/LHFX_Perom_Strike.cpp
9348ba9d6d7410da0ca85afbe4f9ec0167c57eb0
[]
no_license
Topstack-first/20210521_directx_laghaim
80261e1d25ade898ab18c878e46f8f922d62031f
7f92bd76fb5e10af43cd26f6e23ae8781a29632c
refs/heads/main
2023-05-09T14:19:52.082370
2021-05-25T22:22:16
2021-05-25T22:22:16
369,423,057
2
4
null
null
null
null
UTF-8
C++
false
false
2,758
cpp
#include "stdafx.h" #include "main.h" #include "FxSet.h" #include "NkCharacter.h" #include "NkMob.h" #include "LHFX_Perom_Strike.h" const int male_frame = 43; const int fmale_frame = 34; LHFX_Perom_Strike::LHFX_Perom_Strike(void) : m_lolo(NULL) { } LHFX_Perom_Strike::~LHFX_Perom_Strike(void) { SAFE_DELETE_ARRAY(m_lolo); } void LHFX_Perom_Strike::LoadRes() { if (!m_lolo) { m_lolo = new CLolos[2]; m_lolo[0].SetIndexedTexture( g_pCapsyongTexture ); m_lolo[0].Read("data/effect/lolos/pm_skill_wheelwind1.lol"); m_lolo[1].SetIndexedTexture( g_pCapsyongTexture ); m_lolo[1].Read("data/effect/lolos/pw_skill_wheelwind1.lol"); } } void LHFX_Perom_Strike::DeleteRes() { } bool LHFX_Perom_Strike::Render(EffectSort &effect_sort) { if( !GET_D3DDEVICE() || !m_lolo ) return false; int frame = 0; if( effect_sort.pNkChaFrom->m_Sex == 0) frame = male_frame; else frame = fmale_frame; if( effect_sort.nCurFrame > frame ) { effect_sort.nCurFrame = frame; return true; } D3DMATRIX matWorld, matView, matRot; DWORD dwLighting, dwZWrite, dwSrc, dwDest; GET_D3DDEVICE()->GetRenderState( D3DRENDERSTATE_LIGHTING, &dwLighting ); GET_D3DDEVICE()->GetRenderState( D3DRENDERSTATE_ZWRITEENABLE, &dwZWrite ); GET_D3DDEVICE()->GetRenderState( D3DRENDERSTATE_SRCBLEND, &dwSrc ); GET_D3DDEVICE()->GetRenderState( D3DRENDERSTATE_DESTBLEND, &dwDest ); GET_D3DDEVICE()->SetRenderState( D3DRENDERSTATE_ZWRITEENABLE, TRUE ); GET_D3DDEVICE()->SetRenderState( D3DRENDERSTATE_LIGHTING, TRUE ); GET_D3DDEVICE()->SetRenderState( D3DRENDERSTATE_DESTBLEND, D3DBLEND_ONE ); GET_D3DDEVICE()->SetRenderState( D3DRENDERSTATE_SRCBLEND, D3DBLEND_SRCALPHA ); D3DUtil_SetIdentityMatrix( matWorld ); D3DUtil_SetTranslateMatrix( matWorld, effect_sort.pNkChaFrom->m_wx, effect_sort.pNkChaFrom->m_wy, effect_sort.pNkChaFrom->m_wz); D3DUtil_SetIdentityMatrix( matRot ); D3DUtil_SetRotateYMatrix( matRot, -effect_sort.pNkChaFrom->m_dir ); D3DMath_MatrixMultiply( matWorld, matRot, matWorld ); pCMyApp->SetViewMatrix(matView); GET_D3DDEVICE()->SetTransform(D3DTRANSFORMSTATE_WORLD, &matWorld ); GET_D3DDEVICE()->SetTransform(D3DTRANSFORMSTATE_VIEW, &matView); if( effect_sort.pNkChaFrom ) { if( effect_sort.pNkChaFrom->m_Sex == 0 ) m_lolo[0].Render(GET_D3DDEVICE(), effect_sort.nCurFrame, FALSE, FALSE); else if( effect_sort.pNkChaFrom->m_Sex == 1 ) m_lolo[1].Render(GET_D3DDEVICE(), effect_sort.nCurFrame, FALSE, FALSE); } GET_D3DDEVICE()->SetRenderState( D3DRENDERSTATE_LIGHTING, dwLighting ); GET_D3DDEVICE()->SetRenderState( D3DRENDERSTATE_ZWRITEENABLE, dwZWrite ); GET_D3DDEVICE()->SetRenderState( D3DRENDERSTATE_SRCBLEND, dwSrc ); GET_D3DDEVICE()->SetRenderState( D3DRENDERSTATE_DESTBLEND, dwDest ); return false; }
[ "topstack2020+first@gmail.com" ]
topstack2020+first@gmail.com
835cf738ea2def762faa82b00eec7ffe91b7f33e
1e506578383a9c018ccf992340f556090cf5cb87
/IMU/VTK-6.2.0/Interaction/Widgets/Testing/Cxx/TestButtonWidget.cxx
49efee3fb4053ca2996e8a3ef6b4db316e74eb16
[ "MIT", "BSD-3-Clause" ]
permissive
timkrentz/SunTracker
387c69f4080441822c490fdccf5c850e64cb0ea7
9a189cc38f45e5fbc4e4c700d7295a871d022795
refs/heads/master
2020-12-14T09:50:34.216912
2015-07-17T17:06:36
2015-07-17T17:06:36
37,494,691
0
0
null
null
null
null
UTF-8
C++
false
false
31,569
cxx
/*========================================================================= Program: Visualization Toolkit Module: TestButtonWidget.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkActor.h" #include "vtkCommand.h" #include "vtkConeSource.h" #include "vtkGlyph3D.h" #include "vtkAppendPolyData.h" #include "vtkSphereSource.h" #include "vtkButtonWidget.h" #include "vtkTexturedButtonRepresentation.h" #include "vtkTexturedButtonRepresentation2D.h" #include "vtkProp3DButtonRepresentation.h" #include "vtkInteractorEventRecorder.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkLookupTable.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkEllipticalButtonSource.h" #include "vtkTIFFReader.h" #include "vtkPNGReader.h" #include "vtkStructuredPointsReader.h" #include "vtkPiecewiseFunction.h" #include "vtkColorTransferFunction.h" #include "vtkVolumeProperty.h" #include "vtkVolumeRayCastCompositeFunction.h" #include "vtkVolumeRayCastMapper.h" #include "vtkVolumeTextureMapper2D.h" #include "vtkVolume.h" #include "vtkOutlineSource.h" #include "vtkPlatonicSolidSource.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #define VTK_CREATE(type, name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() char ButtonWidgetEventLog[] = "# StreamVersion 1\n" "RenderEvent 0 0 0 0 0 0 0\n" "EnterEvent 125 299 0 0 0 0 0\n" "MouseMoveEvent 125 299 0 0 0 0 0\n" "MouseMoveEvent 125 298 0 0 0 0 0\n" "MouseMoveEvent 125 297 0 0 0 0 0\n" "MouseMoveEvent 124 295 0 0 0 0 0\n" "MouseMoveEvent 123 294 0 0 0 0 0\n" "MouseMoveEvent 122 293 0 0 0 0 0\n" "MouseMoveEvent 121 292 0 0 0 0 0\n" "MouseMoveEvent 120 292 0 0 0 0 0\n" "MouseMoveEvent 120 291 0 0 0 0 0\n" "MouseMoveEvent 119 291 0 0 0 0 0\n" "MouseMoveEvent 119 290 0 0 0 0 0\n" "MouseMoveEvent 119 289 0 0 0 0 0\n" "MouseMoveEvent 119 288 0 0 0 0 0\n" "MouseMoveEvent 119 287 0 0 0 0 0\n" "MouseMoveEvent 119 286 0 0 0 0 0\n" "MouseMoveEvent 119 285 0 0 0 0 0\n" "MouseMoveEvent 119 284 0 0 0 0 0\n" "MouseMoveEvent 119 283 0 0 0 0 0\n" "MouseMoveEvent 119 282 0 0 0 0 0\n" "MouseMoveEvent 119 280 0 0 0 0 0\n" "MouseMoveEvent 119 279 0 0 0 0 0\n" "MouseMoveEvent 119 278 0 0 0 0 0\n" "MouseMoveEvent 118 278 0 0 0 0 0\n" "MouseMoveEvent 118 277 0 0 0 0 0\n" "MouseMoveEvent 118 276 0 0 0 0 0\n" "MouseMoveEvent 118 275 0 0 0 0 0\n" "MouseMoveEvent 118 274 0 0 0 0 0\n" "MouseMoveEvent 117 273 0 0 0 0 0\n" "MouseMoveEvent 116 272 0 0 0 0 0\n" "MouseMoveEvent 116 271 0 0 0 0 0\n" "MouseMoveEvent 116 270 0 0 0 0 0\n" "MouseMoveEvent 116 269 0 0 0 0 0\n" "MouseMoveEvent 116 268 0 0 0 0 0\n" "MouseMoveEvent 116 267 0 0 0 0 0\n" "MouseMoveEvent 115 267 0 0 0 0 0\n" "MouseMoveEvent 115 266 0 0 0 0 0\n" "MouseMoveEvent 115 265 0 0 0 0 0\n" "MouseMoveEvent 115 264 0 0 0 0 0\n" "MouseMoveEvent 115 263 0 0 0 0 0\n" "MouseMoveEvent 115 262 0 0 0 0 0\n" "RenderEvent 115 262 0 0 0 0 0\n" "MouseMoveEvent 115 260 0 0 0 0 0\n" "KeyPressEvent 115 260 0 0 116 1 t\n" "CharEvent 115 260 0 0 116 1 t\n" "MouseMoveEvent 115 259 0 0 0 0 t\n" "KeyReleaseEvent 115 259 0 0 116 1 t\n" "MouseMoveEvent 115 258 0 0 0 0 t\n" "MouseMoveEvent 115 257 0 0 0 0 t\n" "MouseMoveEvent 114 256 0 0 0 0 t\n" "MouseMoveEvent 113 255 0 0 0 0 t\n" "MouseMoveEvent 111 253 0 0 0 0 t\n" "MouseMoveEvent 111 252 0 0 0 0 t\n" "MouseMoveEvent 109 252 0 0 0 0 t\n" "MouseMoveEvent 106 251 0 0 0 0 t\n" "MouseMoveEvent 105 250 0 0 0 0 t\n" "MouseMoveEvent 105 249 0 0 0 0 t\n" "MouseMoveEvent 104 249 0 0 0 0 t\n" "MouseMoveEvent 100 247 0 0 0 0 t\n" "MouseMoveEvent 99 247 0 0 0 0 t\n" "LeftButtonPressEvent 99 247 0 0 0 0 t\n" "RenderEvent 99 247 0 0 0 0 t\n" "LeftButtonReleaseEvent 99 247 0 0 0 0 t\n" "RenderEvent 99 247 0 0 0 0 t\n" "MouseMoveEvent 99 247 0 0 0 0 t\n" "LeftButtonPressEvent 99 247 0 0 0 0 t\n" "RenderEvent 99 247 0 0 0 0 t\n" "LeftButtonReleaseEvent 99 247 0 0 0 0 t\n" "RenderEvent 99 247 0 0 0 0 t\n" "MouseMoveEvent 99 247 0 0 0 0 t\n" "MouseMoveEvent 98 246 0 0 0 0 t\n" "MouseMoveEvent 96 245 0 0 0 0 t\n" "MouseMoveEvent 99 245 0 0 0 0 t\n" "MouseMoveEvent 165 248 0 0 0 0 t\n" "RenderEvent 165 248 0 0 0 0 t\n" "MouseMoveEvent 206 247 0 0 0 0 t\n" "MouseMoveEvent 213 247 0 0 0 0 t\n" "MouseMoveEvent 216 247 0 0 0 0 t\n" "MouseMoveEvent 221 247 0 0 0 0 t\n" "MouseMoveEvent 227 247 0 0 0 0 t\n" "MouseMoveEvent 234 247 0 0 0 0 t\n" "MouseMoveEvent 238 247 0 0 0 0 t\n" "MouseMoveEvent 242 248 0 0 0 0 t\n" "MouseMoveEvent 247 248 0 0 0 0 t\n" "MouseMoveEvent 248 249 0 0 0 0 t\n" "MouseMoveEvent 251 249 0 0 0 0 t\n" "MouseMoveEvent 252 249 0 0 0 0 t\n" "MouseMoveEvent 253 249 0 0 0 0 t\n" "MouseMoveEvent 254 249 0 0 0 0 t\n" "RenderEvent 254 249 0 0 0 0 t\n" "MouseMoveEvent 264 252 0 0 0 0 t\n" "MouseMoveEvent 264 253 0 0 0 0 t\n" "LeftButtonPressEvent 264 253 0 0 0 0 t\n" "RenderEvent 264 253 0 0 0 0 t\n" "LeftButtonReleaseEvent 264 253 0 0 0 0 t\n" "RenderEvent 264 253 0 0 0 0 t\n" "MouseMoveEvent 264 253 0 0 0 0 t\n" "LeftButtonPressEvent 264 253 0 0 0 0 t\n" "RenderEvent 264 253 0 0 0 0 t\n" "LeftButtonReleaseEvent 264 253 0 0 0 0 t\n" "RenderEvent 264 253 0 0 0 0 t\n" "MouseMoveEvent 264 253 0 0 0 0 t\n" "MouseMoveEvent 264 252 0 0 0 0 t\n" "MouseMoveEvent 264 246 0 0 0 0 t\n" "RenderEvent 264 246 0 0 0 0 t\n" "MouseMoveEvent 263 236 0 0 0 0 t\n" "MouseMoveEvent 263 233 0 0 0 0 t\n" "MouseMoveEvent 262 230 0 0 0 0 t\n" "MouseMoveEvent 262 229 0 0 0 0 t\n" "MouseMoveEvent 262 226 0 0 0 0 t\n" "MouseMoveEvent 262 223 0 0 0 0 t\n" "MouseMoveEvent 262 222 0 0 0 0 t\n" "MouseMoveEvent 262 217 0 0 0 0 t\n" "MouseMoveEvent 262 215 0 0 0 0 t\n" "MouseMoveEvent 262 212 0 0 0 0 t\n" "MouseMoveEvent 263 209 0 0 0 0 t\n" "MouseMoveEvent 263 206 0 0 0 0 t\n" "MouseMoveEvent 263 203 0 0 0 0 t\n" "MouseMoveEvent 263 201 0 0 0 0 t\n" "MouseMoveEvent 263 198 0 0 0 0 t\n" "MouseMoveEvent 263 195 0 0 0 0 t\n" "MouseMoveEvent 263 193 0 0 0 0 t\n" "MouseMoveEvent 263 190 0 0 0 0 t\n" "MouseMoveEvent 263 187 0 0 0 0 t\n" "MouseMoveEvent 263 185 0 0 0 0 t\n" "MouseMoveEvent 263 183 0 0 0 0 t\n" "MouseMoveEvent 263 180 0 0 0 0 t\n" "MouseMoveEvent 263 178 0 0 0 0 t\n" "MouseMoveEvent 263 175 0 0 0 0 t\n" "RenderEvent 263 175 0 0 0 0 t\n" "MouseMoveEvent 263 170 0 0 0 0 t\n" "MouseMoveEvent 263 169 0 0 0 0 t\n" "MouseMoveEvent 263 168 0 0 0 0 t\n" "MouseMoveEvent 264 167 0 0 0 0 t\n" "MouseMoveEvent 264 165 0 0 0 0 t\n" "MouseMoveEvent 264 164 0 0 0 0 t\n" "MouseMoveEvent 264 162 0 0 0 0 t\n" "MouseMoveEvent 264 161 0 0 0 0 t\n" "MouseMoveEvent 264 160 0 0 0 0 t\n" "MouseMoveEvent 264 159 0 0 0 0 t\n" "MouseMoveEvent 264 158 0 0 0 0 t\n" "LeftButtonPressEvent 264 158 0 0 0 0 t\n" "RenderEvent 264 158 0 0 0 0 t\n" "LeftButtonReleaseEvent 264 158 0 0 0 0 t\n" "RenderEvent 264 158 0 0 0 0 t\n" "MouseMoveEvent 264 158 0 0 0 0 t\n" "LeftButtonPressEvent 264 158 0 0 0 0 t\n" "RenderEvent 264 158 0 0 0 0 t\n" "LeftButtonReleaseEvent 264 158 0 0 0 0 t\n" "RenderEvent 264 158 0 0 0 0 t\n" "MouseMoveEvent 264 158 0 0 0 0 t\n" "MouseMoveEvent 264 157 0 0 0 0 t\n" "MouseMoveEvent 264 156 0 0 0 0 t\n" "MouseMoveEvent 264 155 0 0 0 0 t\n" "MouseMoveEvent 264 154 0 0 0 0 t\n" "MouseMoveEvent 264 152 0 0 0 0 t\n" "MouseMoveEvent 264 148 0 0 0 0 t\n" "RenderEvent 264 148 0 0 0 0 t\n" "MouseMoveEvent 263 134 0 0 0 0 t\n" "MouseMoveEvent 263 131 0 0 0 0 t\n" "MouseMoveEvent 264 128 0 0 0 0 t\n" "MouseMoveEvent 264 121 0 0 0 0 t\n" "MouseMoveEvent 264 114 0 0 0 0 t\n" "MouseMoveEvent 264 108 0 0 0 0 t\n" "MouseMoveEvent 264 102 0 0 0 0 t\n" "MouseMoveEvent 264 98 0 0 0 0 t\n" "MouseMoveEvent 265 95 0 0 0 0 t\n" "MouseMoveEvent 265 91 0 0 0 0 t\n" "MouseMoveEvent 265 89 0 0 0 0 t\n" "MouseMoveEvent 265 88 0 0 0 0 t\n" "MouseMoveEvent 265 86 0 0 0 0 t\n" "MouseMoveEvent 265 84 0 0 0 0 t\n" "MouseMoveEvent 265 81 0 0 0 0 t\n" "MouseMoveEvent 266 79 0 0 0 0 t\n" "MouseMoveEvent 266 77 0 0 0 0 t\n" "MouseMoveEvent 267 75 0 0 0 0 t\n" "MouseMoveEvent 267 74 0 0 0 0 t\n" "MouseMoveEvent 267 71 0 0 0 0 t\n" "MouseMoveEvent 267 69 0 0 0 0 t\n" "MouseMoveEvent 267 67 0 0 0 0 t\n" "MouseMoveEvent 269 64 0 0 0 0 t\n" "MouseMoveEvent 270 62 0 0 0 0 t\n" "MouseMoveEvent 270 60 0 0 0 0 t\n" "MouseMoveEvent 271 58 0 0 0 0 t\n" "MouseMoveEvent 271 57 0 0 0 0 t\n" "MouseMoveEvent 271 56 0 0 0 0 t\n" "MouseMoveEvent 271 55 0 0 0 0 t\n" "MouseMoveEvent 271 54 0 0 0 0 t\n" "MouseMoveEvent 271 53 0 0 0 0 t\n" "MouseMoveEvent 271 52 0 0 0 0 t\n" "MouseMoveEvent 271 51 0 0 0 0 t\n" "MouseMoveEvent 271 49 0 0 0 0 t\n" "MouseMoveEvent 271 47 0 0 0 0 t\n" "MouseMoveEvent 272 45 0 0 0 0 t\n" "MouseMoveEvent 272 43 0 0 0 0 t\n" "RenderEvent 272 43 0 0 0 0 t\n" "MouseMoveEvent 272 38 0 0 0 0 t\n" "MouseMoveEvent 272 37 0 0 0 0 t\n" "MouseMoveEvent 271 36 0 0 0 0 t\n" "MouseMoveEvent 271 35 0 0 0 0 t\n" "MouseMoveEvent 270 35 0 0 0 0 t\n" "MouseMoveEvent 270 34 0 0 0 0 t\n" "LeftButtonPressEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "LeftButtonReleaseEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "MouseMoveEvent 270 34 0 0 0 0 t\n" "LeftButtonPressEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "LeftButtonReleaseEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "MouseMoveEvent 270 34 0 0 0 0 t\n" "LeftButtonPressEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "LeftButtonReleaseEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "MouseMoveEvent 270 34 0 0 0 0 t\n" "LeftButtonPressEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "LeftButtonReleaseEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "MouseMoveEvent 270 34 0 0 0 0 t\n" "LeftButtonPressEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "LeftButtonReleaseEvent 270 34 0 0 0 0 t\n" "RenderEvent 270 34 0 0 0 0 t\n" "MouseMoveEvent 270 34 0 0 0 0 t\n" "MouseMoveEvent 269 34 0 0 0 0 t\n" "MouseMoveEvent 267 34 0 0 0 0 t\n" "MouseMoveEvent 266 34 0 0 0 0 t\n" "MouseMoveEvent 264 35 0 0 0 0 t\n" "MouseMoveEvent 260 35 0 0 0 0 t\n" "MouseMoveEvent 256 36 0 0 0 0 t\n" "MouseMoveEvent 251 37 0 0 0 0 t\n" "RenderEvent 251 37 0 0 0 0 t\n" "MouseMoveEvent 220 46 0 0 0 0 t\n" "MouseMoveEvent 210 51 0 0 0 0 t\n" "MouseMoveEvent 198 53 0 0 0 0 t\n" "MouseMoveEvent 188 56 0 0 0 0 t\n" "MouseMoveEvent 179 57 0 0 0 0 t\n" "MouseMoveEvent 169 57 0 0 0 0 t\n" "MouseMoveEvent 163 57 0 0 0 0 t\n" "MouseMoveEvent 152 58 0 0 0 0 t\n" "MouseMoveEvent 144 58 0 0 0 0 t\n" "MouseMoveEvent 137 58 0 0 0 0 t\n" "MouseMoveEvent 130 58 0 0 0 0 t\n" "MouseMoveEvent 124 60 0 0 0 0 t\n" "MouseMoveEvent 121 61 0 0 0 0 t\n" "MouseMoveEvent 119 62 0 0 0 0 t\n" "MouseMoveEvent 115 63 0 0 0 0 t\n" "MouseMoveEvent 110 66 0 0 0 0 t\n" "MouseMoveEvent 107 67 0 0 0 0 t\n" "MouseMoveEvent 99 69 0 0 0 0 t\n" "MouseMoveEvent 93 69 0 0 0 0 t\n" "MouseMoveEvent 84 70 0 0 0 0 t\n" "MouseMoveEvent 82 70 0 0 0 0 t\n" "MouseMoveEvent 76 70 0 0 0 0 t\n" "MouseMoveEvent 71 70 0 0 0 0 t\n" "MouseMoveEvent 67 70 0 0 0 0 t\n" "MouseMoveEvent 64 70 0 0 0 0 t\n" "RenderEvent 64 70 0 0 0 0 t\n" "MouseMoveEvent 61 68 0 0 0 0 t\n" "MouseMoveEvent 60 68 0 0 0 0 t\n" "MouseMoveEvent 59 68 0 0 0 0 t\n" "MouseMoveEvent 58 69 0 0 0 0 t\n" "MouseMoveEvent 57 69 0 0 0 0 t\n" "MouseMoveEvent 56 69 0 0 0 0 t\n" "MouseMoveEvent 55 68 0 0 0 0 t\n" "LeftButtonPressEvent 55 68 0 0 0 0 t\n" "RenderEvent 55 68 0 0 0 0 t\n" "LeftButtonReleaseEvent 55 68 0 0 0 0 t\n" "RenderEvent 55 68 0 0 0 0 t\n" "MouseMoveEvent 55 68 0 0 0 0 t\n" "LeftButtonPressEvent 55 68 0 0 0 0 t\n" "RenderEvent 55 68 0 0 0 0 t\n" "LeftButtonReleaseEvent 55 68 0 0 0 0 t\n" "RenderEvent 55 68 0 0 0 0 t\n" "MouseMoveEvent 55 68 0 0 0 0 t\n" "MouseMoveEvent 57 67 0 0 0 0 t\n" "MouseMoveEvent 64 66 0 0 0 0 t\n" "MouseMoveEvent 71 66 0 0 0 0 t\n" "RenderEvent 71 66 0 0 0 0 t\n" "MouseMoveEvent 83 64 0 0 0 0 t\n" "MouseMoveEvent 84 64 0 0 0 0 t\n" "MouseMoveEvent 84 63 0 0 0 0 t\n" "MouseMoveEvent 85 63 0 0 0 0 t\n" "MouseMoveEvent 86 63 0 0 0 0 t\n" "MouseMoveEvent 87 63 0 0 0 0 t\n" "MouseMoveEvent 88 63 0 0 0 0 t\n" "MouseMoveEvent 89 63 0 0 0 0 t\n" "MouseMoveEvent 89 64 0 0 0 0 t\n" "MouseMoveEvent 90 65 0 0 0 0 t\n" "MouseMoveEvent 92 65 0 0 0 0 t\n" "MouseMoveEvent 92 66 0 0 0 0 t\n" "MouseMoveEvent 93 66 0 0 0 0 t\n" "LeftButtonPressEvent 93 66 0 0 0 0 t\n" "StartInteractionEvent 93 66 0 0 0 0 t\n" "MouseMoveEvent 94 66 0 0 0 0 t\n" "RenderEvent 94 66 0 0 0 0 t\n" "MouseMoveEvent 103 63 0 0 0 0 t\n" "RenderEvent 103 63 0 0 0 0 t\n" "MouseMoveEvent 110 62 0 0 0 0 t\n" "RenderEvent 110 62 0 0 0 0 t\n" "MouseMoveEvent 118 61 0 0 0 0 t\n" "RenderEvent 118 61 0 0 0 0 t\n" "MouseMoveEvent 132 60 0 0 0 0 t\n" "RenderEvent 132 60 0 0 0 0 t\n" "MouseMoveEvent 138 60 0 0 0 0 t\n" "RenderEvent 138 60 0 0 0 0 t\n" "MouseMoveEvent 142 60 0 0 0 0 t\n" "RenderEvent 142 60 0 0 0 0 t\n" "MouseMoveEvent 150 60 0 0 0 0 t\n" "RenderEvent 150 60 0 0 0 0 t\n" "MouseMoveEvent 159 63 0 0 0 0 t\n" "RenderEvent 159 63 0 0 0 0 t\n" "MouseMoveEvent 168 63 0 0 0 0 t\n" "RenderEvent 168 63 0 0 0 0 t\n" "MouseMoveEvent 176 63 0 0 0 0 t\n" "RenderEvent 176 63 0 0 0 0 t\n" "MouseMoveEvent 185 65 0 0 0 0 t\n" "RenderEvent 185 65 0 0 0 0 t\n" "MouseMoveEvent 190 65 0 0 0 0 t\n" "RenderEvent 190 65 0 0 0 0 t\n" "MouseMoveEvent 195 65 0 0 0 0 t\n" "RenderEvent 195 65 0 0 0 0 t\n" "MouseMoveEvent 200 65 0 0 0 0 t\n" "RenderEvent 200 65 0 0 0 0 t\n" "MouseMoveEvent 202 65 0 0 0 0 t\n" "RenderEvent 202 65 0 0 0 0 t\n" "MouseMoveEvent 203 67 0 0 0 0 t\n" "RenderEvent 203 67 0 0 0 0 t\n" "MouseMoveEvent 204 67 0 0 0 0 t\n" "RenderEvent 204 67 0 0 0 0 t\n" "MouseMoveEvent 205 67 0 0 0 0 t\n" "RenderEvent 205 67 0 0 0 0 t\n" "MouseMoveEvent 206 68 0 0 0 0 t\n" "RenderEvent 206 68 0 0 0 0 t\n" "LeftButtonReleaseEvent 206 68 0 0 0 0 t\n" "EndInteractionEvent 206 68 0 0 0 0 t\n" "RenderEvent 206 68 0 0 0 0 t\n" "MouseMoveEvent 206 68 0 0 0 0 t\n" "MouseMoveEvent 204 68 0 0 0 0 t\n" "MouseMoveEvent 202 69 0 0 0 0 t\n" "MouseMoveEvent 201 69 0 0 0 0 t\n" "MouseMoveEvent 200 69 0 0 0 0 t\n" "MouseMoveEvent 198 69 0 0 0 0 t\n" "MouseMoveEvent 196 69 0 0 0 0 t\n" "MouseMoveEvent 195 69 0 0 0 0 t\n" "MouseMoveEvent 192 69 0 0 0 0 t\n" "MouseMoveEvent 190 70 0 0 0 0 t\n" "MouseMoveEvent 187 70 0 0 0 0 t\n" "MouseMoveEvent 185 70 0 0 0 0 t\n" "MouseMoveEvent 181 70 0 0 0 0 t\n" "MouseMoveEvent 175 71 0 0 0 0 t\n" "MouseMoveEvent 171 72 0 0 0 0 t\n" "MouseMoveEvent 155 76 0 0 0 0 t\n" "MouseMoveEvent 141 78 0 0 0 0 t\n" "MouseMoveEvent 128 82 0 0 0 0 t\n" "MouseMoveEvent 114 85 0 0 0 0 t\n" "MouseMoveEvent 100 90 0 0 0 0 t\n" "MouseMoveEvent 87 94 0 0 0 0 t\n" "MouseMoveEvent 78 99 0 0 0 0 t\n" "MouseMoveEvent 68 102 0 0 0 0 t\n" "MouseMoveEvent 61 105 0 0 0 0 t\n" "MouseMoveEvent 57 108 0 0 0 0 t\n" "MouseMoveEvent 53 112 0 0 0 0 t\n" "MouseMoveEvent 50 113 0 0 0 0 t\n" "MouseMoveEvent 50 114 0 0 0 0 t\n" "MouseMoveEvent 49 114 0 0 0 0 t\n" "MouseMoveEvent 49 115 0 0 0 0 t\n" "MouseMoveEvent 49 116 0 0 0 0 t\n" "MouseMoveEvent 49 118 0 0 0 0 t\n" "MouseMoveEvent 49 120 0 0 0 0 t\n" "MouseMoveEvent 50 122 0 0 0 0 t\n" "MouseMoveEvent 52 124 0 0 0 0 t\n" "MouseMoveEvent 54 127 0 0 0 0 t\n" "MouseMoveEvent 56 128 0 0 0 0 t\n" "MouseMoveEvent 57 131 0 0 0 0 t\n" "MouseMoveEvent 58 133 0 0 0 0 t\n" "MouseMoveEvent 59 135 0 0 0 0 t\n" "MouseMoveEvent 59 136 0 0 0 0 t\n" "MouseMoveEvent 59 138 0 0 0 0 t\n" "MouseMoveEvent 59 139 0 0 0 0 t\n" "MouseMoveEvent 59 140 0 0 0 0 t\n" "MouseMoveEvent 59 141 0 0 0 0 t\n" "MouseMoveEvent 59 142 0 0 0 0 t\n" "MouseMoveEvent 59 143 0 0 0 0 t\n" "MouseMoveEvent 61 143 0 0 0 0 t\n" "RenderEvent 61 143 0 0 0 0 t\n" "MouseMoveEvent 64 145 0 0 0 0 t\n" "MouseMoveEvent 64 146 0 0 0 0 t\n" "MouseMoveEvent 65 146 0 0 0 0 t\n" "MouseMoveEvent 66 146 0 0 0 0 t\n" "MouseMoveEvent 66 147 0 0 0 0 t\n" "LeftButtonPressEvent 66 147 0 0 0 0 t\n" "RenderEvent 66 147 0 0 0 0 t\n" "LeftButtonReleaseEvent 66 147 0 0 0 0 t\n" "RenderEvent 66 147 0 0 0 0 t\n" "MouseMoveEvent 66 147 0 0 0 0 t\n" "LeftButtonPressEvent 66 147 0 0 0 0 t\n" "RenderEvent 66 147 0 0 0 0 t\n" "LeftButtonReleaseEvent 66 147 0 0 0 0 t\n" "RenderEvent 66 147 0 0 0 0 t\n" "MouseMoveEvent 66 147 0 0 0 0 t\n" "MouseMoveEvent 66 148 0 0 0 0 t\n" "MouseMoveEvent 65 148 0 0 0 0 t\n" ; // This does the actual work: updates the vtkPlane implicit function. // This in turn causes the pipeline to update and clip the object. // Callback for the interaction class vtkButtonCallback : public vtkCommand { public: static vtkButtonCallback *New() { return new vtkButtonCallback; } virtual void Execute(vtkObject *caller, unsigned long, void*) { vtkButtonWidget *buttonWidget = reinterpret_cast<vtkButtonWidget*>(caller); vtkTexturedButtonRepresentation *rep = reinterpret_cast<vtkTexturedButtonRepresentation*> (buttonWidget->GetRepresentation()); int state = rep->GetState(); cout << "State: " << state << "\n"; this->Glyph->SetScaleFactor(0.05*(1+state)); } vtkButtonCallback():Glyph(0) {} vtkGlyph3D *Glyph; }; int TestButtonWidget(int argc, char *argv[] ) { // Create an image for the button char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/beach.tif"); VTK_CREATE(vtkTIFFReader, image1); image1->SetFileName(fname); image1->SetOrientationType( 4 ); image1->Update(); delete [] fname; // Create an image for the button char* fname2 = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/fran_cut.png"); VTK_CREATE(vtkPNGReader, image2); image2->SetFileName(fname2); image2->Update(); delete [] fname2; // Create a mace out of filters. // VTK_CREATE(vtkSphereSource, sphere); VTK_CREATE(vtkConeSource, cone); VTK_CREATE(vtkGlyph3D, glyph); glyph->SetInputConnection(sphere->GetOutputPort()); glyph->SetSourceConnection(cone->GetOutputPort()); glyph->SetVectorModeToUseNormal(); glyph->SetScaleModeToScaleByVector(); glyph->SetScaleFactor(0.25); glyph->Update(); // Appending just makes things simpler to manage. VTK_CREATE(vtkAppendPolyData, apd); apd->AddInputConnection(glyph->GetOutputPort()); apd->AddInputConnection(sphere->GetOutputPort()); VTK_CREATE(vtkPolyDataMapper, maceMapper); maceMapper->SetInputConnection(apd->GetOutputPort()); VTK_CREATE(vtkActor, maceActor); maceActor->SetMapper(maceMapper); maceActor->VisibilityOn(); // Create the RenderWindow, Renderer and both Actors // VTK_CREATE(vtkRenderer, ren1); VTK_CREATE(vtkRenderWindow, renWin); renWin->AddRenderer(ren1); VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(renWin); // The SetInteractor method is how 3D widgets are associated with the render // window interactor. Internally, SetInteractor sets up a bunch of callbacks // using the Command/Observer mechanism (AddObserver()). VTK_CREATE(vtkButtonCallback, myCallback); myCallback->Glyph = glyph; VTK_CREATE(vtkEllipticalButtonSource, button); button->TwoSidedOn(); button->SetCircumferentialResolution(24); button->SetShoulderResolution(24); button->SetTextureResolution(24); VTK_CREATE(vtkTexturedButtonRepresentation, rep); rep->SetNumberOfStates(2); rep->SetButtonTexture(0,image1->GetOutput()); rep->SetButtonTexture(1,image2->GetOutput()); rep->SetButtonGeometryConnection(button->GetOutputPort()); rep->SetPlaceFactor(1); double bds[6]; bds[0] = 0.6; bds[1] = 0.75; bds[2] = 0.6; bds[3] = 0.75; bds[4] = 0.6; bds[5] = 0.75; rep->PlaceWidget(bds); rep->FollowCameraOn(); VTK_CREATE(vtkButtonWidget, buttonWidget); buttonWidget->SetInteractor(iren); buttonWidget->SetRepresentation(rep); buttonWidget->AddObserver(vtkCommand::StateChangedEvent,myCallback); // Another 3D button widget, this time use alternative PlaceWidget() method VTK_CREATE(vtkEllipticalButtonSource, button2); button2->TwoSidedOn(); button2->SetCircumferentialResolution(24); button2->SetShoulderResolution(24); button2->SetTextureResolution(24); button2->SetWidth(0.65); button2->SetHeight(0.45); button2->SetTextureStyleToFitImage(); VTK_CREATE(vtkTexturedButtonRepresentation, rep2); rep2->SetNumberOfStates(2); rep2->SetButtonTexture(0,image1->GetOutput()); rep2->SetButtonTexture(1,image2->GetOutput()); rep2->SetButtonGeometryConnection(button2->GetOutputPort()); rep2->SetPlaceFactor(1); bds[0] = 0.0; bds[1] = 0.0; bds[2] = 0.65; bds[3] = 0.0; bds[4] = 0.0; bds[5] = 1; rep2->PlaceWidget(0.5, bds, bds+3); rep2->FollowCameraOff(); VTK_CREATE(vtkButtonWidget, buttonWidget2); buttonWidget2->SetInteractor(iren); buttonWidget2->SetRepresentation(rep2); buttonWidget2->AddObserver(vtkCommand::StateChangedEvent,myCallback); // Okay now for the 2D version of the widget (in display space) VTK_CREATE(vtkTexturedButtonRepresentation2D, rep3); rep3->SetNumberOfStates(2); rep3->SetButtonTexture(0,image1->GetOutput()); rep3->SetButtonTexture(1,image2->GetOutput()); rep3->SetPlaceFactor(1); bds[0] = 25; bds[1] = 65; bds[2] = 50; bds[3] = 200; rep3->PlaceWidget(bds); VTK_CREATE(vtkButtonWidget, buttonWidget3); buttonWidget3->SetInteractor(iren); buttonWidget3->SetRepresentation(rep3); buttonWidget3->AddObserver(vtkCommand::StateChangedEvent,myCallback); // Okay now for the 2D version of the widget (in world space) VTK_CREATE(vtkTexturedButtonRepresentation2D, rep4); rep4->SetNumberOfStates(2); rep4->SetButtonTexture(0,image1->GetOutput()); rep4->SetButtonTexture(1,image2->GetOutput()); rep4->SetPlaceFactor(1); bds[0] = 0.75; bds[1] = 0; bds[2] = 0; int size[2]; size[0] = 25; size[1] = 45; rep4->PlaceWidget(bds,size); VTK_CREATE(vtkButtonWidget, buttonWidget4); buttonWidget4->SetInteractor(iren); buttonWidget4->SetRepresentation(rep4); buttonWidget4->AddObserver(vtkCommand::StateChangedEvent,myCallback); // Finally now a set of vtkProp3D's to define a vtkProp3DButtonRepresentation VTK_CREATE(vtkLookupTable,lut); lut->SetNumberOfColors(20); lut->Build(); lut->SetTableValue(0, 1, 0, 0, 1); lut->SetTableValue(1, 0, 1, 0, 1); lut->SetTableValue(2, 1, 1, 0, 1); lut->SetTableValue(3, 0, 0, 1, 1); lut->SetTableValue(4, 1, 0, 1, 1); lut->SetTableValue(5, 0, 1, 1, 1); lut->SetTableValue(6, 0.0000, 1.0000, 0.4980, 1.0); lut->SetTableValue(7, 0.9020, 0.9020, 0.9804, 1.0); lut->SetTableValue(8, 0.9608, 1.0000, 0.9804, 1.0); lut->SetTableValue(9, 0.5600, 0.3700, 0.6000, 1.0); lut->SetTableValue(10, 0.1600, 0.1400, 0.1300, 1.0); lut->SetTableValue(11, 1.0000, 0.4980, 0.3137, 1.0); lut->SetTableValue(12, 1.0000, 0.7529, 0.7961, 1.0); lut->SetTableValue(13, 0.9804, 0.5020, 0.4471, 1.0); lut->SetTableValue(14, 0.3700, 0.1500, 0.0700, 1.0); lut->SetTableValue(15, 0.9300, 0.5700, 0.1300, 1.0); lut->SetTableValue(16, 1.0000, 0.8431, 0.0000, 1.0); lut->SetTableValue(17, 0.1333, 0.5451, 0.1333, 1.0); lut->SetTableValue(18, 0.2510, 0.8784, 0.8157, 1.0); lut->SetTableValue(19, 0.8667, 0.6275, 0.8667, 1.0); lut->SetTableRange(0, 19); VTK_CREATE(vtkPlatonicSolidSource,tet); tet->SetSolidTypeToTetrahedron(); VTK_CREATE(vtkPolyDataMapper,tetMapper); tetMapper->SetInputConnection(tet->GetOutputPort()); tetMapper->SetLookupTable(lut); tetMapper->SetScalarRange(0,19); VTK_CREATE(vtkActor,tetActor); tetActor->SetMapper(tetMapper); VTK_CREATE(vtkPlatonicSolidSource,cube); cube->SetSolidTypeToCube(); VTK_CREATE(vtkPolyDataMapper,cubeMapper); cubeMapper->SetInputConnection(cube->GetOutputPort()); cubeMapper->SetLookupTable(lut); cubeMapper->SetScalarRange(0,19); VTK_CREATE(vtkActor,cubeActor); cubeActor->SetMapper(cubeMapper); VTK_CREATE(vtkPlatonicSolidSource,oct); oct->SetSolidTypeToOctahedron(); VTK_CREATE(vtkPolyDataMapper,octMapper); octMapper->SetInputConnection(oct->GetOutputPort()); octMapper->SetLookupTable(lut); octMapper->SetScalarRange(0,19); VTK_CREATE(vtkActor,octActor); octActor->SetMapper(octMapper); VTK_CREATE(vtkPlatonicSolidSource,ico); ico->SetSolidTypeToIcosahedron(); VTK_CREATE(vtkPolyDataMapper,icoMapper); icoMapper->SetInputConnection(ico->GetOutputPort()); icoMapper->SetLookupTable(lut); icoMapper->SetScalarRange(0,19); VTK_CREATE(vtkActor,icoActor); icoActor->SetMapper(icoMapper); VTK_CREATE(vtkPlatonicSolidSource,dode); dode->SetSolidTypeToDodecahedron(); VTK_CREATE(vtkPolyDataMapper,dodeMapper); dodeMapper->SetInputConnection(dode->GetOutputPort()); dodeMapper->SetLookupTable(lut); dodeMapper->SetScalarRange(0,19); VTK_CREATE(vtkActor,dodeActor); dodeActor->SetMapper(dodeMapper); VTK_CREATE(vtkProp3DButtonRepresentation, rep5); rep5->SetNumberOfStates(5); rep5->SetButtonProp(0,tetActor); rep5->SetButtonProp(1,cubeActor); rep5->SetButtonProp(2,octActor); rep5->SetButtonProp(3,icoActor); rep5->SetButtonProp(4,dodeActor); rep5->SetPlaceFactor(1); bds[0] = 0.65; bds[1] = 0.75; bds[2] = -0.75; bds[3] = -0.65; bds[4] = 0.65; bds[5] = 0.75; rep5->PlaceWidget(bds); rep5->FollowCameraOn(); VTK_CREATE(vtkButtonWidget, buttonWidget5); buttonWidget5->SetInteractor(iren); buttonWidget5->SetRepresentation(rep5); buttonWidget5->AddObserver(vtkCommand::StateChangedEvent,myCallback); // A volume rendered button! // Create the reader for the data char* fname3 = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/ironProt.vtk"); VTK_CREATE(vtkStructuredPointsReader, reader); reader->SetFileName(fname3); delete [] fname3; // Create transfer mapping scalar value to opacity VTK_CREATE(vtkPiecewiseFunction, opacityTransferFunction); opacityTransferFunction->AddPoint(20,0); opacityTransferFunction->AddPoint(255,1); // Create transfer mapping scalar value to color VTK_CREATE(vtkColorTransferFunction, colorTransferFunction); colorTransferFunction->AddRGBPoint(0.0, 0.0, 0.0, 0.0); colorTransferFunction->AddRGBPoint(64.0, 1.0, 0.0, 0.0); colorTransferFunction->AddRGBPoint(128.0, 0.0, 0.0, 1.0); colorTransferFunction->AddRGBPoint(192.0, 0.0, 1.0, 0.0); colorTransferFunction->AddRGBPoint(255.0, 0.0, 0.2, 0.0); // The property describes how the data will look VTK_CREATE(vtkVolumeProperty, volumeProperty); volumeProperty->SetColor(colorTransferFunction); volumeProperty->SetScalarOpacity(opacityTransferFunction); volumeProperty->ShadeOn(); volumeProperty->SetInterpolationTypeToLinear(); // The mapper / ray cast function know how to render the data VTK_CREATE(vtkVolumeTextureMapper2D, volumeMapper); volumeMapper->SetInputConnection(reader->GetOutputPort()); // The volume holds the mapper and the property and // can be used to position/orient the volume VTK_CREATE(vtkVolume, volume); volume->SetMapper(volumeMapper); volume->SetProperty(volumeProperty); // Create transfer mapping scalar value to color VTK_CREATE(vtkColorTransferFunction, colorTransferFunction2); colorTransferFunction2->AddRGBPoint(0.0, 0.0, 0.0, 0.0); colorTransferFunction2->AddRGBPoint(64.0, 0.0, 0.0, 1.0); colorTransferFunction2->AddRGBPoint(128.0, 1.0, 0.0, 1.0); colorTransferFunction2->AddRGBPoint(192.0, 0.5, 0.0, 0.5); colorTransferFunction2->AddRGBPoint(255.0, 0.2, 0.0, 0.2); // The property describes how the data will look VTK_CREATE(vtkVolumeProperty, volumeProperty2); volumeProperty2->SetColor(colorTransferFunction2); volumeProperty2->SetScalarOpacity(opacityTransferFunction); volumeProperty2->ShadeOn(); volumeProperty2->SetInterpolationTypeToLinear(); // The mapper / ray cast function know how to render the data VTK_CREATE(vtkVolumeTextureMapper2D, volumeMapper2); volumeMapper2->SetInputConnection(reader->GetOutputPort()); VTK_CREATE(vtkVolume, volume2); volume2->SetMapper(volumeMapper2); volume2->SetProperty(volumeProperty2); VTK_CREATE(vtkProp3DButtonRepresentation, rep6); rep6->SetNumberOfStates(2); rep6->SetButtonProp(0,volume); rep6->SetButtonProp(1,volume2); rep6->SetPlaceFactor(1); bds[0] = -0.75; bds[1] = -0.35; bds[2] = 0.6; bds[3] = 1; bds[4] = -1; bds[5] = -0.6; rep6->PlaceWidget(bds); rep6->FollowCameraOn(); VTK_CREATE(vtkButtonWidget, buttonWidget6); buttonWidget6->SetInteractor(iren); buttonWidget6->SetRepresentation(rep6); buttonWidget6->AddObserver(vtkCommand::StateChangedEvent,myCallback); // Outline is for debugging VTK_CREATE(vtkOutlineSource, outline); outline->SetBounds(bds); VTK_CREATE(vtkPolyDataMapper, outlineMapper); outlineMapper->SetInputConnection(outline->GetOutputPort()); VTK_CREATE(vtkActor, outlineActor); outlineActor->SetMapper(outlineMapper); ren1->AddActor(maceActor); // ren1->AddActor(outlineActor); //used for debugging // Add the actors to the renderer, set the background and size // ren1->SetBackground(0.1, 0.2, 0.4); renWin->SetSize(300, 300); // record events vtkSmartPointer<vtkInteractorEventRecorder> recorder = vtkSmartPointer<vtkInteractorEventRecorder>::New(); recorder->SetInteractor(iren); // recorder->SetFileName("record.log"); // recorder->Record(); recorder->ReadFromInputStringOn(); recorder->SetInputString(ButtonWidgetEventLog); recorder->EnabledOn(); // render the image // iren->Initialize(); renWin->Render(); buttonWidget->EnabledOn(); buttonWidget2->EnabledOn(); buttonWidget3->EnabledOn(); buttonWidget4->EnabledOn(); buttonWidget5->EnabledOn(); buttonWidget6->EnabledOn(); recorder->Play(); // Remove the observers so we can go interactive. Without this the "-I" // testing option fails. recorder->Off(); iren->Start(); return EXIT_SUCCESS; }
[ "tskrentz@gmail.com" ]
tskrentz@gmail.com
db91825fab5fca139076af43400e28d11d49aafb
2f541d9b5b35ca129f533d273c55a6f3f90f3e30
/random_file_access/main.cpp
1523625257164d4244df97fc3a061e50dcc14b73
[]
no_license
GinkgoX/Primer
602ce83fe41363a2e89d5712d8221280355d4ba2
47b0dee18e6ebf311758b53af19b4252e1759311
refs/heads/master
2021-10-25T00:03:22.368417
2019-03-30T12:46:41
2019-03-30T12:46:41
170,057,101
0
0
null
null
null
null
UTF-8
C++
false
false
221
cpp
#include<iostream> #include<fstream> #include<cstring> #include"personal.h" #include"student.h" #include"database.h" using namespace std; int main() { Database<Personal> run(); //Database<Student> run(); return 0; }
[ "1640043928@qq.com" ]
1640043928@qq.com
6e8207ae29de204c15c37f07cac2b6d11dbc2ac0
9afe8785df3afb1b5f061dfb59399f4ad3de870d
/02_DirectX _Sample_Programs/10_3D_Rotation.cpp
9902f0ab053dce087171b78cfdd209c19e0f722d
[]
no_license
a-shinde/RTR
66dee8cfe1bd2de0b4aa60dc34c91ea091543d97
27402dbd519dfb479c1a6c0f7cc831408ecb3f6a
refs/heads/master
2022-04-30T08:12:57.938299
2022-03-03T12:44:50
2022-03-03T12:44:50
93,935,213
0
0
null
null
null
null
UTF-8
C++
false
false
35,660
cpp
//Header files. #include <windows.h> #include <fstream> #include <d3d11.h> #include <d3dcompiler.h> #pragma warning( disable: 4838 ) #include <XNAMath\xnamath.h> #pragma comment (lib,"d3d11.lib") #pragma comment (lib,"D3dcompiler.lib") using namespace std; #define WIN_WIDTH 800 #define WIN_HEIGHT 600 int currentWidth; int currentHeight; HWND gHwnd; HDC gHdc; HGLRC gHglrc; bool gbFullscreen; bool gbEscapeKeyIsPressed; bool gbActiveWindow; bool bDone; WINDOWPLACEMENT wpPrev = { sizeof(WINDOWPLACEMENT) }; DWORD dwStyle; ofstream outputFile; //Fun Declarations LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); HRESULT Initialize(); void FirstResize(); void Uninitialize(); void Display(); void Update(); HRESULT resize(int, int); HRESULT initializeData(); char gszLogFileName[] = "Logs.txt"; float clearColor[4]; // RGBA IDXGISwapChain *gpI_DXGI_SwapChain = NULL; ID3D11Device *gpI_D3D11_Device = NULL; ID3D11DeviceContext *gpI_D3D11_DeviceContext = NULL; ID3D11RenderTargetView *gpI_D3D11_RenderTargetView = NULL; ID3D11RasterizerState *gpI_D3D11_RasterizeState = NULL; ID3D11DepthStencilView *gpI_D3D11_Depth_Stencil_View = NULL; ID3D11VertexShader *gpI_D3D11_VertexShader = NULL; ID3D11PixelShader *gpI_D3D11_PixelShader = NULL; ID3D11Buffer *gpI_D3D11_Buffer_Pyramid_PositionBuffer = NULL; ID3D11Buffer *gpI_D3D11_Buffer_Pyramid_ColorBuffer = NULL; ID3D11Buffer *gpI_D3D11_Buffer_Cube_PositionBuffer = NULL; ID3D11Buffer *gpI_D3D11_Buffer_Cube_ColorBuffer = NULL; ID3D11InputLayout *gpI_D3D11_InputLayout = NULL; ID3D11Buffer *gpI_D3D11_Buffer_ConstantBuffer = NULL; ID3DBlob *gpI_D3DBlob_VertexShaderCode = NULL; struct CBUFFER { XMMATRIX WorldViewProjectionMatrix; }; XMMATRIX perspectiveProjectionMatrix; float angleRotate; //Code int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdArgs, int cmdShow) { TCHAR className[] = TEXT("DirectX_Window"); WNDCLASSEX wndClassEx; HWND hWnd; MSG msg; outputFile.open(gszLogFileName, std::ofstream::out); if (outputFile.is_open()) { outputFile << "------------------------------" << endl; outputFile << "---- Amol Shinde ----" << endl; outputFile << "------------------------------" << endl; outputFile << "Log File Successfully Opened" << endl; } outputFile.close(); wndClassEx.cbSize = sizeof(WNDCLASSEX); wndClassEx.cbClsExtra = 0; wndClassEx.cbWndExtra = 0; wndClassEx.hbrBackground = CreateSolidBrush(RGB(0.0f, 0.0f, 0.0f)); wndClassEx.hCursor = LoadCursor(NULL, IDC_ARROW); wndClassEx.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndClassEx.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wndClassEx.hInstance = hInstance; wndClassEx.lpfnWndProc = WndProc; wndClassEx.lpszMenuName = NULL; wndClassEx.lpszClassName = className; wndClassEx.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; RegisterClassEx(&wndClassEx); int monitorWidth = GetSystemMetrics(SM_CXSCREEN); int monitorHeight = GetSystemMetrics(SM_CYSCREEN); int x = (monitorWidth / 2) - (WIN_WIDTH / 2); int y = (monitorHeight / 2) - (WIN_HEIGHT / 2); hWnd = CreateWindowEx(WS_EX_APPWINDOW, className, TEXT("DirextX 3D"), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE, x, y, WIN_WIDTH, WIN_HEIGHT, NULL, NULL, hInstance, NULL); gHwnd = hWnd; HRESULT hr; hr = Initialize(); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "initialize() Failed. Exitting Now ..." << endl; outputFile.close(); DestroyWindow(hWnd); hWnd = NULL; } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "initialize() Succeeded." << endl; outputFile.close(); } ShowWindow(hWnd, cmdShow); //Game Loop while (bDone == false) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) bDone = TRUE; else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { if (gbActiveWindow == true) { if (gbEscapeKeyIsPressed == true) bDone = true; } Display(); Update(); } } Uninitialize(); return (int)msg.wParam; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { // Functions Declarations void ToggleFullscreen(); switch (message) { case WM_CREATE: break; case WM_ACTIVATE: if (HIWORD(wParam) == 0) gbActiveWindow = true; else gbActiveWindow = false; break; case WM_LBUTTONDOWN: break; case WM_RBUTTONDOWN: break; case WM_SIZE: if (gpI_D3D11_DeviceContext) { HRESULT hr; hr = resize(LOWORD(lParam), HIWORD(lParam)); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "resize() Failed" << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "resize() Successded" << endl; outputFile.close(); } } break; case WM_PAINT: break; case WM_KEYDOWN: switch (wParam) { case VK_ESCAPE: if (gbEscapeKeyIsPressed == false) gbEscapeKeyIsPressed = true; break; case 0x46: //for 'f' if (gbFullscreen == true) { ToggleFullscreen(); gbFullscreen = false; } else { ToggleFullscreen(); gbFullscreen = true; } break; case 0x4C: //for 'l' break; } break; case WM_CHAR: break; case WM_ERASEBKGND: return(0); break; case WM_CLOSE: Uninitialize(); break; case WM_DESTROY: PostQuitMessage(0); break; default: break; } return DefWindowProc(hWnd, message, wParam, lParam); } HRESULT Initialize() { HRESULT hr; D3D_DRIVER_TYPE d3d_DriverType; D3D_DRIVER_TYPE d3d_DriverTypes[] = { D3D_DRIVER_TYPE_HARDWARE,D3D_DRIVER_TYPE_WARP,D3D_DRIVER_TYPE_REFERENCE, }; D3D_FEATURE_LEVEL d3d_FeatureLevel_required = D3D_FEATURE_LEVEL_11_0; D3D_FEATURE_LEVEL d3d_FeatureLevel_acquired = D3D_FEATURE_LEVEL_10_0; UINT createDeviceFlags = 0; UINT num_DriverTypes = 0; UINT num_FeatureLevels = 1; num_DriverTypes = sizeof(d3d_DriverTypes) / sizeof(d3d_DriverTypes[0]); DXGI_SWAP_CHAIN_DESC dxgi_SwapChainDesc; ZeroMemory((void *)&dxgi_SwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); dxgi_SwapChainDesc.BufferCount = 1; dxgi_SwapChainDesc.BufferDesc.Width = WIN_WIDTH; dxgi_SwapChainDesc.BufferDesc.Height = WIN_HEIGHT; dxgi_SwapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; dxgi_SwapChainDesc.BufferDesc.RefreshRate.Numerator = 60; dxgi_SwapChainDesc.BufferDesc.RefreshRate.Denominator = 1; dxgi_SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; dxgi_SwapChainDesc.OutputWindow = gHwnd; dxgi_SwapChainDesc.SampleDesc.Count = 4; dxgi_SwapChainDesc.SampleDesc.Quality = 0.99; dxgi_SwapChainDesc.Windowed = TRUE; for (UINT driverTypeIndex = 0; driverTypeIndex < num_DriverTypes; driverTypeIndex++) { d3d_DriverType = d3d_DriverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain( NULL, // Adapter d3d_DriverType, // Driver Type NULL, // Software createDeviceFlags, // Flags &d3d_FeatureLevel_required, // Feature Levels num_FeatureLevels, // Num Feature Levels D3D11_SDK_VERSION, // SDK Version &dxgi_SwapChainDesc, // Swap Chain Desc &gpI_DXGI_SwapChain, // Swap Chain &gpI_D3D11_Device, // Device &d3d_FeatureLevel_acquired, // Feature Level &gpI_D3D11_DeviceContext); // Device Context if (SUCCEEDED(hr)) break; } if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "D3D11CreateDeviceAndSwapChain() Failed" << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "D3D11CreateDeviceAndSwapChain() Succeeded" << endl; outputFile << "The Chosen Driver Is Of" << endl; if (d3d_DriverType == D3D_DRIVER_TYPE_HARDWARE) { outputFile << "Hardware Type." << endl; } else if (d3d_DriverType == D3D_DRIVER_TYPE_WARP) { outputFile << "Warp Type." << endl; } else if (d3d_DriverType == D3D_DRIVER_TYPE_REFERENCE) { outputFile << "Reference Type." << endl; } else { outputFile << "Unknown Type." << endl; } outputFile << "The Supported Highest Feature Level Is" << endl; if (d3d_FeatureLevel_acquired == D3D_FEATURE_LEVEL_11_0) { outputFile << "11.0" << endl; } else if (d3d_FeatureLevel_acquired == D3D_FEATURE_LEVEL_10_1) { outputFile << "10.1" << endl; } else if (d3d_FeatureLevel_acquired == D3D_FEATURE_LEVEL_10_0) { outputFile << "10.0" << endl; } else { outputFile << "Unknown" << endl; } outputFile.close(); } const char *vertexShaderSourceCode = "struct outputVertex " \ "{ " \ " float4 position : SV_POSITION;" \ " float4 color : COLOR;" \ "}; " \ "cbuffer ConstanatBuffer " \ "{ "\ " float4x4 worldViewProjectionMatrix;" \ "} "\ " "\ "outputVertex main(float4 pos : POSITION, float4 col : COLOR )" \ "{ "\ " outputVertex outVec; " \ " outVec.position = mul(worldViewProjectionMatrix, pos);" \ " outVec.color = col;" \ " return (outVec); "\ "} "; ID3DBlob *pI_D3DBlob_Error = NULL; hr = D3DCompile(vertexShaderSourceCode, lstrlenA(vertexShaderSourceCode) + 1, "VS", NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "vs_5_0", 0, 0, &gpI_D3DBlob_VertexShaderCode, &pI_D3DBlob_Error); if (FAILED(hr)) { if (pI_D3DBlob_Error != NULL) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "D3DCompile() Failed For Vertex Shader : %s." << endl; outputFile.close(); pI_D3DBlob_Error->Release(); pI_D3DBlob_Error = NULL; return(hr); } } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "D3DCompile() Succeeded For Vertex Shader." << endl; outputFile.close(); } hr = gpI_D3D11_Device->CreateVertexShader(gpI_D3DBlob_VertexShaderCode->GetBufferPointer(), gpI_D3DBlob_VertexShaderCode->GetBufferSize(), NULL, &gpI_D3D11_VertexShader); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateVertexShader() Failed." << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateVertexShader() Succeeded." << endl; outputFile.close(); } gpI_D3D11_DeviceContext->VSSetShader(gpI_D3D11_VertexShader, 0, 0); const char *pixelShaderSourceCode = "float4 main( float4 position : POSITION, float4 color : COLOR) : SV_TARGET"\ "{ "\ " float4 outColor = color;" \ " return (outColor);"\ "}"; ID3DBlob *pI_D3DBlob_PixelShaderCode = NULL; pI_D3DBlob_Error = NULL; hr = D3DCompile(pixelShaderSourceCode, lstrlenA(pixelShaderSourceCode) + 1, "PS", NULL, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "ps_5_0", 0, 0, &pI_D3DBlob_PixelShaderCode, &pI_D3DBlob_Error); if (FAILED(hr)) { if (pI_D3DBlob_Error != NULL) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "D3DCompile() Failed For Pixel Shader : %s" << (char *)pI_D3DBlob_Error->GetBufferPointer() << endl; outputFile.close(); pI_D3DBlob_Error->Release(); pI_D3DBlob_Error = NULL; return(hr); } } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "D3DCompile() Succeeded For Pixel Shader." << endl; outputFile.close(); } hr = gpI_D3D11_Device->CreatePixelShader(pI_D3DBlob_PixelShaderCode->GetBufferPointer(), pI_D3DBlob_PixelShaderCode->GetBufferSize(), NULL, &gpI_D3D11_PixelShader); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreatePixelShader() Failed." << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreatePixelShader() Succeeded." << endl; outputFile.close(); } gpI_D3D11_DeviceContext->PSSetShader(gpI_D3D11_PixelShader, 0, 0); pI_D3DBlob_PixelShaderCode->Release(); pI_D3DBlob_PixelShaderCode = NULL; clearColor[0] = 0.0f; clearColor[1] = 0.0f; clearColor[2] = 0.0f; clearColor[3] = 1.0f; hr = initializeData(); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "initializeData() Failed" << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "initializeData() Successded" << endl; outputFile.close(); } D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc)); rasterizerDesc.AntialiasedLineEnable = FALSE; rasterizerDesc.MultisampleEnable = FALSE; rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.SlopeScaledDepthBias = 0.0f; rasterizerDesc.DepthClipEnable = TRUE; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.ScissorEnable = FALSE; rasterizerDesc.CullMode = D3D11_CULL_NONE; gpI_D3D11_Device->CreateRasterizerState(&rasterizerDesc, &gpI_D3D11_RasterizeState); gpI_D3D11_DeviceContext->RSSetState(gpI_D3D11_RasterizeState); hr = resize(WIN_WIDTH, WIN_HEIGHT); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "resize() Failed" << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "resize() Successded" << endl; outputFile.close(); } return(S_OK); } HRESULT initializeData() { HRESULT hr; //-------------------------- // Pyramid Data float pyramid_positions[] = { //front 0.0f,1.0f,0.0f, 1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, //Right face 0.0f,1.0f,0.0f, 1.0f,-1.0f,1.0f, 1.0f,-1.0f,-1.0f, //Back face 0.0f,1.0f,0.0f, -1.0f,-1.0f,1.0f, 1.0f,-1.0f,1.0f, //right face 0.0f,1.0f,0.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,1.0f, }; float pyramid_colors[] = { 1.0f,0.0f,0.0f, 0.0f,0.0f,1.0f, 0.0f,1.0f,0.0f, 1.0f,0.0f,0.0f, 0.0f,1.0f,0.0f, 0.0f,0.0f,1.0f, 1.0f,0.0f,0.0f, 0.0f,0.0f,1.0f, 0.0f,1.0f,0.0f, 1.0f,0.0f,0.0f, 0.0f,1.0f,0.0f, 0.0f,0.0f,1.0f, }; D3D11_BUFFER_DESC bufferDesc; ZeroMemory(&bufferDesc, sizeof(D3D11_BUFFER_DESC)); bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = sizeof(float) * ARRAYSIZE(pyramid_positions); bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; hr = gpI_D3D11_Device->CreateBuffer(&bufferDesc, NULL, &gpI_D3D11_Buffer_Pyramid_PositionBuffer); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Failed For Position Buffer." << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Succeeded For Position Buffer." << endl; outputFile.close(); } // copy vertices into above buffer D3D11_MAPPED_SUBRESOURCE mappedSubresource; ZeroMemory(&mappedSubresource, sizeof(D3D11_MAPPED_SUBRESOURCE)); gpI_D3D11_DeviceContext->Map(gpI_D3D11_Buffer_Pyramid_PositionBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &mappedSubresource); memcpy(mappedSubresource.pData, pyramid_positions, sizeof(pyramid_positions)); gpI_D3D11_DeviceContext->Unmap(gpI_D3D11_Buffer_Pyramid_PositionBuffer, NULL); //Copy Color Data ZeroMemory(&bufferDesc, sizeof(D3D11_BUFFER_DESC)); bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = sizeof(float) * ARRAYSIZE(pyramid_colors); bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; hr = gpI_D3D11_Device->CreateBuffer(&bufferDesc, NULL, &gpI_D3D11_Buffer_Pyramid_ColorBuffer); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Failed For Color Buffer." << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Succeeded For Color Buffer." << endl; outputFile.close(); } // copy vertices into above buffer ZeroMemory(&mappedSubresource, sizeof(D3D11_MAPPED_SUBRESOURCE)); gpI_D3D11_DeviceContext->Map(gpI_D3D11_Buffer_Pyramid_ColorBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &mappedSubresource); memcpy(mappedSubresource.pData, pyramid_colors, sizeof(pyramid_colors)); gpI_D3D11_DeviceContext->Unmap(gpI_D3D11_Buffer_Pyramid_ColorBuffer, NULL); // Cube Data float cube_positions[] = { //Front -1.0f,1.0f,-1.0f, 1.0f,1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, 1.0f,1.0f,-1.0f, 1.0f,-1.0f,-1.0f, //Right 1.0f,1.0f,-1.0f, 1.0f,1.0f,1.0f, 1.0f,-1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f,1.0f,1.0f, 1.0f,-1.0f,1.0f, //Back 1.0f,1.0f,1.0f, -1.0f,1.0f,1.0f, 1.0f,-1.0f,1.0f, 1.0f,-1.0f,1.0f, -1.0f,1.0f,1.0f, -1.0f,-1.0f,1.0f, //Left -1.0f,1.0f,1.0f, -1.0f,1.0f,-1.0f, -1.0f,-1.0f,1.0f, -1.0f,-1.0f,1.0f, -1.0f,1.0f,-1.0f, -1.0f,-1.0f,-1.0f, //Top -1.0f,1.0f,1.0f, 1.0f,1.0f,1.0f, -1.0f,1.0f,-1.0f, -1.0f,1.0f,-1.0f, 1.0f,1.0f,1.0f, 1.0f,1.0f,-1.0f, //Bottom -1.0f,-1.0f,1.0f, 1.0f,-1.0f,1.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, 1.0f,-1.0f,1.0f, 1.0f,-1.0f,-1.0f, }; float cube_colors[] = { //Front Face 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, //Right Face 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, //Back Face 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, //Left Face 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, //Top face 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, //Bottom face 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f }; ZeroMemory(&bufferDesc, sizeof(D3D11_BUFFER_DESC)); bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = sizeof(float) * ARRAYSIZE(cube_positions); bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; hr = gpI_D3D11_Device->CreateBuffer(&bufferDesc, NULL, &gpI_D3D11_Buffer_Cube_PositionBuffer); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Failed For Position Buffer." << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Succeeded For Position Buffer." << endl; outputFile.close(); } // copy vertices into above buffer ZeroMemory(&mappedSubresource, sizeof(D3D11_MAPPED_SUBRESOURCE)); gpI_D3D11_DeviceContext->Map(gpI_D3D11_Buffer_Cube_PositionBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &mappedSubresource); memcpy(mappedSubresource.pData, cube_positions, sizeof(cube_positions)); gpI_D3D11_DeviceContext->Unmap(gpI_D3D11_Buffer_Cube_PositionBuffer, NULL); //Copy Color Data ZeroMemory(&bufferDesc, sizeof(D3D11_BUFFER_DESC)); bufferDesc.Usage = D3D11_USAGE_DYNAMIC; bufferDesc.ByteWidth = sizeof(float) * ARRAYSIZE(cube_colors); bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; hr = gpI_D3D11_Device->CreateBuffer(&bufferDesc, NULL, &gpI_D3D11_Buffer_Cube_ColorBuffer); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Failed For Color Buffer." << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Succeeded For Color Buffer." << endl; outputFile.close(); } // copy vertices into above buffer ZeroMemory(&mappedSubresource, sizeof(D3D11_MAPPED_SUBRESOURCE)); gpI_D3D11_DeviceContext->Map(gpI_D3D11_Buffer_Cube_ColorBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &mappedSubresource); memcpy(mappedSubresource.pData, cube_colors, sizeof(cube_colors)); gpI_D3D11_DeviceContext->Unmap(gpI_D3D11_Buffer_Cube_ColorBuffer, NULL); //---------------------------------- // define and set the constant buffer D3D11_BUFFER_DESC bufferDesc_ConstantBuffer; ZeroMemory(&bufferDesc_ConstantBuffer, sizeof(D3D11_BUFFER_DESC)); bufferDesc_ConstantBuffer.Usage = D3D11_USAGE_DEFAULT; bufferDesc_ConstantBuffer.ByteWidth = sizeof(CBUFFER); bufferDesc_ConstantBuffer.BindFlags = D3D11_BIND_CONSTANT_BUFFER; hr = gpI_D3D11_Device->CreateBuffer(&bufferDesc_ConstantBuffer, nullptr, &gpI_D3D11_Buffer_ConstantBuffer); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Failed For Constant Buffer." << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateBuffer() Succeeded For Constant Buffer." << endl; outputFile.close(); } gpI_D3D11_DeviceContext->VSSetConstantBuffers(0, 1, &gpI_D3D11_Buffer_ConstantBuffer); // create and set input layout D3D11_INPUT_ELEMENT_DESC inputElementDesc[2]; inputElementDesc[0].SemanticName = "POSITION"; inputElementDesc[0].SemanticIndex = 0; inputElementDesc[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; inputElementDesc[0].InputSlot = 0; inputElementDesc[0].AlignedByteOffset = 0; inputElementDesc[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; inputElementDesc[0].InstanceDataStepRate = 0; inputElementDesc[1].SemanticName = "COLOR"; inputElementDesc[1].SemanticIndex = 0; inputElementDesc[1].Format = DXGI_FORMAT_R32G32B32_FLOAT; inputElementDesc[1].InputSlot = 1; inputElementDesc[1].AlignedByteOffset = 0; inputElementDesc[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; inputElementDesc[1].InstanceDataStepRate = 0; hr = gpI_D3D11_Device->CreateInputLayout(inputElementDesc, 2, gpI_D3DBlob_VertexShaderCode->GetBufferPointer(), gpI_D3DBlob_VertexShaderCode->GetBufferSize(), &gpI_D3D11_InputLayout); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateInputLayout() Failed." << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateInputLayout() Succeeded." << endl; outputFile.close(); } gpI_D3D11_DeviceContext->IASetInputLayout(gpI_D3D11_InputLayout); gpI_D3DBlob_VertexShaderCode->Release(); gpI_D3DBlob_VertexShaderCode = NULL; perspectiveProjectionMatrix = XMMatrixIdentity(); } void FirstResize() { currentWidth = WIN_WIDTH - GetSystemMetrics(SM_CXSIZEFRAME) * 4; currentHeight = WIN_HEIGHT - GetSystemMetrics(SM_CYCAPTION) - GetSystemMetrics(SM_CYSIZEFRAME) * 4; resize(currentWidth, currentHeight); } HRESULT resize(int width, int height) { HRESULT hr = S_OK; if (gpI_D3D11_RenderTargetView) { gpI_D3D11_RenderTargetView->Release(); gpI_D3D11_RenderTargetView = NULL; } gpI_DXGI_SwapChain->ResizeBuffers(1, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, 0); // again get back buffer from swap chain ID3D11Texture2D *pI_D3D11_Texture2D_BackBuffer; gpI_DXGI_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pI_D3D11_Texture2D_BackBuffer); hr = gpI_D3D11_Device->CreateRenderTargetView(pI_D3D11_Texture2D_BackBuffer, NULL, &gpI_D3D11_RenderTargetView); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateRenderTargetView() Failed" << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateRenderTargetView() Succeeded" << endl; outputFile.close(); } pI_D3D11_Texture2D_BackBuffer->Release(); pI_D3D11_Texture2D_BackBuffer = NULL; if (gpI_D3D11_Depth_Stencil_View) { gpI_D3D11_Depth_Stencil_View->Release(); gpI_D3D11_Depth_Stencil_View = NULL; } D3D11_TEXTURE2D_DESC textureDesc; ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Height = height; textureDesc.Width = width; textureDesc.ArraySize = 1; textureDesc.MipLevels = 1; textureDesc.SampleDesc.Count = 4; textureDesc.SampleDesc.Quality = 0.99; textureDesc.Format = DXGI_FORMAT_D32_FLOAT; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; ID3D11Texture2D *pI_D3D11_Texture2D = NULL; gpI_D3D11_Device->CreateTexture2D(&textureDesc, NULL, &pI_D3D11_Texture2D); D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc; ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc)); depthStencilViewDesc.Format = DXGI_FORMAT_D32_FLOAT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS; hr = gpI_D3D11_Device->CreateDepthStencilView(pI_D3D11_Texture2D, &depthStencilViewDesc, &gpI_D3D11_Depth_Stencil_View); if (FAILED(hr)) { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateDepthStencilView() Failed" << endl; outputFile.close(); return(hr); } else { outputFile.open(gszLogFileName, std::ofstream::app); outputFile << "ID3D11Device::CreateDepthStencilView() Succeeded" << endl; outputFile.close(); } gpI_D3D11_DeviceContext->OMSetRenderTargets(1, &gpI_D3D11_RenderTargetView, gpI_D3D11_Depth_Stencil_View); D3D11_VIEWPORT d3d_ViewPort; d3d_ViewPort.TopLeftX = 0; d3d_ViewPort.TopLeftY = 0; d3d_ViewPort.Width = (float)width; d3d_ViewPort.Height = (float)height; d3d_ViewPort.MinDepth = 0.0f; d3d_ViewPort.MaxDepth = 1.0f; gpI_D3D11_DeviceContext->RSSetViewports(1, &d3d_ViewPort); // set orthographic matrix perspectiveProjectionMatrix = XMMatrixPerspectiveFovLH(XMConvertToRadians(45.0f), (float)width / (float)height, 0.1f, 100.0f); } void ToggleFullscreen() { MONITORINFO mi = { sizeof(MONITORINFO) }; if (!gbFullscreen) { // Make fullscreen dwStyle = GetWindowLong(gHwnd, GWL_STYLE); if (dwStyle & WS_OVERLAPPEDWINDOW) { if (GetWindowPlacement(gHwnd, &wpPrev) && GetMonitorInfo( MonitorFromWindow(gHwnd, MONITORINFOF_PRIMARY), &mi)) { SetWindowLong(gHwnd, GWL_STYLE, dwStyle & ~WS_OVERLAPPEDWINDOW); SetWindowPos(gHwnd, HWND_TOP, mi.rcMonitor.left, mi.rcMonitor.top, mi.rcMonitor.right - mi.rcMonitor.left, mi.rcMonitor.bottom - mi.rcMonitor.top, SWP_NOZORDER | SWP_FRAMECHANGED); } } ShowCursor(FALSE); } else { SetWindowLong(gHwnd, GWL_STYLE, dwStyle | WS_OVERLAPPEDWINDOW); SetWindowPlacement(gHwnd, &wpPrev); SetWindowPos(gHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_FRAMECHANGED); ShowCursor(TRUE); } } void Uninitialize() { if (gbFullscreen == true) { dwStyle = GetWindowLong(gHwnd, GWL_STYLE); SetWindowLong(gHwnd, GWL_STYLE, dwStyle | WS_OVERLAPPEDWINDOW); SetWindowPlacement(gHwnd, &wpPrev); SetWindowPos(gHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_FRAMECHANGED); ShowCursor(TRUE); } if (gpI_D3D11_Depth_Stencil_View) { gpI_D3D11_Depth_Stencil_View->Release(); gpI_D3D11_Depth_Stencil_View = NULL; } if (gpI_D3D11_RasterizeState) { gpI_D3D11_RasterizeState->Release(); gpI_D3D11_RasterizeState = NULL; } if (gpI_D3D11_RenderTargetView) { gpI_D3D11_RenderTargetView->Release(); gpI_D3D11_RenderTargetView = NULL; } if (gpI_D3D11_Buffer_ConstantBuffer) { gpI_D3D11_Buffer_ConstantBuffer->Release(); gpI_D3D11_Buffer_ConstantBuffer = NULL; } if (gpI_D3D11_InputLayout) { gpI_D3D11_InputLayout->Release(); gpI_D3D11_InputLayout = NULL; } if (gpI_D3D11_Buffer_Pyramid_ColorBuffer) { gpI_D3D11_Buffer_Pyramid_ColorBuffer->Release(); gpI_D3D11_Buffer_Pyramid_ColorBuffer = NULL; } if (gpI_D3D11_Buffer_Pyramid_PositionBuffer) { gpI_D3D11_Buffer_Pyramid_PositionBuffer->Release(); gpI_D3D11_Buffer_Pyramid_PositionBuffer = NULL; } if (gpI_D3D11_PixelShader) { gpI_D3D11_PixelShader->Release(); gpI_D3D11_PixelShader = NULL; } if (gpI_D3D11_VertexShader) { gpI_D3D11_VertexShader->Release(); gpI_D3D11_VertexShader = NULL; } if (gpI_DXGI_SwapChain) { gpI_DXGI_SwapChain->Release(); gpI_DXGI_SwapChain = NULL; } if (gpI_D3D11_DeviceContext) { gpI_D3D11_DeviceContext->Release(); gpI_D3D11_DeviceContext = NULL; } if (gpI_D3D11_Device) { gpI_D3D11_Device->Release(); gpI_D3D11_Device = NULL; } ReleaseDC(gHwnd, gHdc); gHdc = NULL; outputFile.open(gszLogFileName, std::ofstream::app); if (outputFile.is_open()) { outputFile << "Log File Successfully Closed."; outputFile.close(); } DestroyWindow(gHwnd); } void Display() { gpI_D3D11_DeviceContext->ClearRenderTargetView(gpI_D3D11_RenderTargetView, clearColor); gpI_D3D11_DeviceContext->ClearDepthStencilView(gpI_D3D11_Depth_Stencil_View, D3D11_CLEAR_DEPTH, 1.0f, 0); UINT stride = sizeof(float) * 3; UINT offset = 0; //Draw Pyramid gpI_D3D11_DeviceContext->IASetVertexBuffers(0, 1, &gpI_D3D11_Buffer_Pyramid_PositionBuffer, &stride, &offset); gpI_D3D11_DeviceContext->IASetVertexBuffers(1, 1, &gpI_D3D11_Buffer_Pyramid_ColorBuffer, &stride, &offset); gpI_D3D11_DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); XMMATRIX worldMatrix = XMMatrixTranslation(-1.5f, 0.0f, 6.0f); worldMatrix = XMMatrixRotationY(XMConvertToRadians(angleRotate)) * worldMatrix; XMMATRIX viewMatrix = XMMatrixIdentity(); XMMATRIX wvpMatrix = worldMatrix * viewMatrix * perspectiveProjectionMatrix; CBUFFER constantBuffer; constantBuffer.WorldViewProjectionMatrix = wvpMatrix; gpI_D3D11_DeviceContext->UpdateSubresource(gpI_D3D11_Buffer_ConstantBuffer, 0, NULL, &constantBuffer, 0, 0); gpI_D3D11_DeviceContext->Draw(12, 0); // Draw Cube gpI_D3D11_DeviceContext->IASetVertexBuffers(0, 1, &gpI_D3D11_Buffer_Cube_PositionBuffer, &stride, &offset); gpI_D3D11_DeviceContext->IASetVertexBuffers(1, 1, &gpI_D3D11_Buffer_Cube_ColorBuffer, &stride, &offset); XMMATRIX translationMatrix = XMMatrixTranslation(1.5f, 0.0f, 6.0f); XMMATRIX scaleMatrix = XMMatrixScaling(0.75f, 0.75f, 0.75f); XMMATRIX rotationMatrix = XMMatrixRotationX(XMConvertToRadians(angleRotate)); rotationMatrix = XMMatrixRotationY(XMConvertToRadians(angleRotate)) * rotationMatrix; rotationMatrix = XMMatrixRotationZ(XMConvertToRadians(angleRotate)) * rotationMatrix; worldMatrix = scaleMatrix * rotationMatrix * translationMatrix; wvpMatrix = worldMatrix * viewMatrix * perspectiveProjectionMatrix; constantBuffer.WorldViewProjectionMatrix = wvpMatrix; gpI_D3D11_DeviceContext->UpdateSubresource(gpI_D3D11_Buffer_ConstantBuffer, 0, NULL, &constantBuffer, 0, 0); gpI_D3D11_DeviceContext->Draw(6, 0); gpI_D3D11_DeviceContext->Draw(6, 6); gpI_D3D11_DeviceContext->Draw(6, 12); gpI_D3D11_DeviceContext->Draw(6, 18); gpI_D3D11_DeviceContext->Draw(6, 24); gpI_D3D11_DeviceContext->Draw(6, 30); gpI_DXGI_SwapChain->Present(0, 0); } void Update() { if (angleRotate > 360.0f) angleRotate = 0.0f; angleRotate += 0.02f; }
[ "ashinde@nvidia.com" ]
ashinde@nvidia.com
1318c23e675380cd938b5005e7dd3bc51ce78ca4
4b4a423a1fb267364cc1cae22c28482820ef3f9f
/OGLWindow.h
5dc60aee33d7588e2ca2284646c123e5b533443b
[]
no_license
esmitt/Win32OpenGL-OBJ
1761ea353dddc17c8347a4ef7c925648e6b308cd
66632bbb7f7ebf3165083e2b6fb10c352a4652c5
refs/heads/master
2021-08-30T20:28:52.023608
2017-12-19T09:56:46
2017-12-19T09:56:46
114,748,260
0
0
null
null
null
null
UTF-8
C++
false
false
1,050
h
#pragma once #include <Windows.h> #include "OGLRectangle.h" #include "OGLCube.h" #include "TriangleMesh.h" class OGLWindow { private: HWND m_hwnd; //handle to a window HDC m_hdc; //handle to a device context HGLRC m_hglrc; //handle to a gl rendering context int m_width; //width of the OGL drawing surface int m_height; //height of the OGL drawing surface //This is not an ideal place to hold geometry data OGLCube *m_cube; TriangleMesh* m_triangleMesh; float frotationX, frotationY, frotationZ; protected: HGLRC CreateOGLContext (HDC hdc); BOOL DestroyOGLContext(); void InitOGLState(); public: OGLWindow(); OGLWindow(HINSTANCE hInstance, int width, int height); ~OGLWindow(); BOOL InitWindow(HINSTANCE hInstance, int width, int height); void Render(); void Resize( int width, int height ); void SetVisible( BOOL visible ); void DestroyOGLWindow(); BOOL MouseLBDown ( int x, int y ); BOOL MouseLBUp ( int x, int y ); BOOL MouseMove ( int x, int y ); };
[ "esmitt.ramirez@cvc.uab.es" ]
esmitt.ramirez@cvc.uab.es
f59493e0a779446d6684a5719eb325f407300cf7
06a2dab18197a13fc3371debd29b476ae99cb01c
/Flat/interface/L1Analyzer.h
ce17fefca31cfd0d8202d93d365a835ef934f3dd
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
PandaPhysics/PandaAnalysis
397a031f9e8d399be1814ab04dd525d69b41f060
3167d106d41dfce58219c3e07d30e201ee823b55
refs/heads/master
2021-06-18T13:52:57.650900
2019-04-08T17:35:29
2019-04-08T17:35:29
168,376,672
0
0
NOASSERTION
2019-04-08T17:33:55
2019-01-30T16:34:09
C++
UTF-8
C++
false
false
594
h
#ifndef L1Analyzer_h #define L1Analyzer_h #include "AnalyzerUtilities.h" #include "Analyzer.h" #include "L1Tree.h" #include "L1Op.h" #include "PandaAnalysis/Flat/interface/Common.h" namespace pa { class L1Analyzer : public Analyzer<L1Tree> { public : L1Analyzer(Analysis* a, int debug_=0); ~L1Analyzer(); void Reset(); void Run(); void Terminate(); private: ////////////////////////////////////////////////////////////////////////////////////// std::unique_ptr<L1Op> op{nullptr}; L1Event event; }; } #endif
[ "sidn@mit.edu" ]
sidn@mit.edu
8a2ec82ae23d4a8891a57d41364970b9fc660b0b
14ed0ebefcceb32de5296cd3b47629bac248f3a9
/gx6/workspace/gx6/src/ComplexBoard.cpp
d842fc8dbbd40cb8ca26e9da5581b8c04cd0ef2e
[]
no_license
chengouxuan/gx6
24e55caf1a70bae6503c1c9b2e0fb29da61578cc
e4462999fcff9dc8b7fd9535c56f9de29d0ac53b
refs/heads/master
2020-05-15T23:15:12.926941
2013-07-24T13:14:17
2013-07-24T13:14:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,336
cpp
#include "ComplexBoard.h" void ComplexBoard::NewSearchInit(Board board) { FOR_EACH(b, 7) { FOR_EACH(w, 7) { segmentTable._table[b][w].Clear(); } } FOR_EACH_SEG(r, c, d) { SegmentTable::Item &item = (segmentTable._segment[r][c][d] = SegmentTable::Item(r, c, d, 0, 0)); if(item.IsInsideBoard()) { segmentTable._table[0][0].Add(item); } } _hash = 0; _checkSum = 0; _stack.Clear(); std::fill(_data[0], _data[ROW_MAX], CELL_TYPE_EMPTY); FOR_EACH_CELL(r, c) { if(board[r][c] == CELL_TYPE_BLACK) { MakeMove(r, c, true); } else if(board[r][c] == CELL_TYPE_WHITE) { MakeMove(r, c, false); } else { assert(board[r][c] == CELL_TYPE_EMPTY); } } } void ComplexBoard::MakeMove(int row, int col, bool isBlack) { assert(::IsInsideBoard(row, col)); assert(_data[row][col] == CELL_TYPE_EMPTY); _hash ^= ::randTable.Rand32(row, col, _data[row][col]); _checkSum ^= ::randTable.Rand64(row, col, _data[row][col]); _data[row][col] = (isBlack ? CELL_TYPE_BLACK : CELL_TYPE_WHITE); _hash ^= ::randTable.Rand32(row, col, _data[row][col]); _checkSum ^= ::randTable.Rand64(row, col, _data[row][col]); FOR_EACH(i, 4) { UpdateDirection(row, col, i, isBlack, true); } _stack.Push(row, col, isBlack); } void ComplexBoard::UnmakeLastMove() { int row = _stack.Top()._row; int col = _stack.Top()._col; assert(_data[row][col] != CELL_TYPE_EMPTY); _hash ^= ::randTable.Rand32(row, col, _data[row][col]); _checkSum ^= ::randTable.Rand64(row, col, _data[row][col]); _data[row][col] = CELL_TYPE_EMPTY; _hash ^= ::randTable.Rand32(row, col, _data[row][col]); _checkSum ^= ::randTable.Rand64(row, col, _data[row][col]); FOR_EACH(i, 4) { UpdateDirection(row, col, i, _stack.Top()._isBlack, false); } _stack.Pop(); } void ComplexBoard::UpdateDirection(int row, int col, int dir, bool isBlack, bool isIncrease) { FOR_EACH(i, 6) { if(! ::IsInsideBoard(row - dr[dir] * i, col - dc[dir] * i)) { return; } UpdateSegment(row - dr[dir] * i, col - dc[dir] * i, dir, isBlack, isIncrease); } } ComplexBoard complexBoard; // tightly coupled with segmentTable
[ "chengouxuan@21cn.com" ]
chengouxuan@21cn.com
2d7081d1df400118163ca3305322b48d4c86009f
b0e2c079ff69de7ef88f24c6ebab8272646703a4
/mono/Player.h
b588dbbfb1ec0eefd30e66efaa0a37de7ef488ba
[]
no_license
shrenikrajvijay/Monopoly-Empire-without-UI
a9e8cb0518236bf21b76471eac2acacbcc290725
08a7ede7144e41f047d6bff10e6d4e36148e94c8
refs/heads/master
2021-01-10T03:17:39.788808
2015-10-29T22:09:05
2015-10-29T22:09:05
45,138,930
0
0
null
null
null
null
UTF-8
C++
false
false
834
h
#ifndef PLAYER_H_ #define PLAYER_H_ #include <string> #include "Tower.h" #include <vector> // #include "Space.h" using namespace std; class Space; class Player { private: string name; int money; int position; int at_jail; Tower * tower; vector<Player*> * players; int num_player; int my_id; vector<Space*> spaces; public: Player( string input, vector<Player*>* , int, int, vector<Space*> ); virtual ~Player(); string getName(); int getPosition(); void setPostion( int ); int getTowerValue(); void changeMoney( int ); int getMoney(); void setGlobal(int); Tower * getTower(); void sneakySwap(Player&, Player&); void steal( Player& ); vector<Player*> getPlayers(); int getNum(); int getId(); void testPlayers(); int isInJail(); void setJail( int ); vector<Space*> getSpaces(); }; #endif /* PLAYER_H_ */
[ "s.vijay0991@yahoo.com" ]
s.vijay0991@yahoo.com
438e7c6e4455356c964aabfbd09f390098ff4d02
33c3bd541b3d1522e6a424280b50d8e17c00caa1
/AltSign/Certificate.cpp
ba6dce8570916a580a7507e37f6c8e07ae38932b
[]
no_license
WalterHHD/AltServerPlus-Windows
7a9f995a8d149030a4554ebd1a45d14c495ba108
0bdc116efb33acd39f7b59211e5aea6ea8f1f87f
refs/heads/master
2023-01-10T03:43:56.866368
2020-11-02T08:10:08
2020-11-02T08:10:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,901
cpp
// // Certificate.cpp // AltSign-Windows // // Created by Riley Testut on 8/12/19. // Copyright © 2019 Riley Testut. All rights reserved. // #include "Certificate.hpp" #include "Error.hpp" #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <cpprest/http_client.h> extern std::string StringFromWideString(std::wstring wideString); extern std::wstring WideStringFromString(std::string string); std::string kCertificatePEMPrefix = "-----BEGIN CERTIFICATE-----"; std::string kCertificatePEMSuffix = "-----END CERTIFICATE-----"; static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::vector<unsigned char> base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::vector<unsigned char> ret; while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0; i < 4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) { ret.push_back(char_array_3[i]); } i = 0; } } if (i) { for (j = i; j < 4; j++) char_array_4[j] = 0; for (j = 0; j < 4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) { ret.push_back(char_array_3[j]); } } return ret; } Certificate::Certificate() { } Certificate::~Certificate() { } Certificate::Certificate(plist_t plist) { auto dataNode = plist_dict_get_item(plist, "certContent"); if (dataNode != nullptr) { char *bytes = nullptr; uint64_t size = 0; plist_get_data_val(dataNode, &bytes, &size); std::vector<unsigned char> data; data.reserve(size); for (int i = 0; i < size; i++) { data.push_back(bytes[i]); } this->ParseData(data); } else { auto nameNode = plist_dict_get_item(plist, "name"); auto serialNumberNode = plist_dict_get_item(plist, "serialNumber"); if (serialNumberNode == nullptr) { serialNumberNode = plist_dict_get_item(plist, "serialNum"); } if (nameNode == nullptr || serialNumberNode == nullptr) { throw APIError(APIErrorCode::InvalidResponse); } char* name = nullptr; plist_get_string_val(nameNode, &name); char* serialNumber = nullptr; plist_get_string_val(serialNumberNode, &serialNumber); _name = name; _serialNumber = serialNumber; } auto machineNameNode = plist_dict_get_item(plist, "machineName"); auto machineIdentifierNode = plist_dict_get_item(plist, "machineId"); if (machineNameNode != nullptr) { char* machineName = nullptr; plist_get_string_val(machineNameNode, &machineName); _machineName = machineName; } if (machineIdentifierNode != nullptr) { char* machineIdentifier = nullptr; plist_get_string_val(machineIdentifierNode, &machineIdentifier); _machineIdentifier = machineIdentifier; } } Certificate::Certificate(web::json::value json) { auto identifier = json[L"id"].as_string(); auto attributes = json[L"attributes"]; std::vector<unsigned char> data; if (attributes.has_field(L"certificateContent")) { auto encodedData = attributes[L"certificateContent"].as_string(); data = base64_decode(StringFromWideString(encodedData)); } auto machineName = attributes[L"machineName"].as_string(); auto machineIdentifier = attributes[L"machineId"].as_string(); if (data.size() != 0) { this->ParseData(data); } else { auto name = attributes[L"name"].as_string(); auto serialNumber = attributes[L"serialNumber"].as_string(); _name = StringFromWideString(name); _serialNumber = StringFromWideString(serialNumber); } _identifier = std::make_optional(StringFromWideString(identifier)); _machineName = std::make_optional(StringFromWideString(machineName)); _machineIdentifier = std::make_optional(StringFromWideString(machineIdentifier)); } Certificate::Certificate(std::vector<unsigned char>& p12Data, std::string password) { BIO* inputP12Buffer = BIO_new(BIO_s_mem()); BIO_write(inputP12Buffer, p12Data.data(), (int)p12Data.size()); PKCS12* inputP12 = d2i_PKCS12_bio(inputP12Buffer, NULL); // Extract key + certificate from .p12. EVP_PKEY* key; X509* certificate; PKCS12_parse(inputP12, password.c_str(), &key, &certificate, NULL); if (key == nullptr || certificate == nullptr) { throw APIError(APIErrorCode::InvalidResponse); } BIO* pemBuffer = BIO_new(BIO_s_mem()); PEM_write_bio_X509(pemBuffer, certificate); BIO* privateKeyBuffer = BIO_new(BIO_s_mem()); PEM_write_bio_PrivateKey(privateKeyBuffer, key, NULL, NULL, 0, NULL, NULL); char* pemBytes = NULL; int pemSize = BIO_get_mem_data(pemBuffer, &pemBytes); char* privateKeyBytes = NULL; int privateKeySize = BIO_get_mem_data(privateKeyBuffer, &privateKeyBytes); std::vector<unsigned char> pemData; pemData.reserve(pemSize); for (int i = 0; i < pemSize; i++) { p12Data.push_back(pemBytes[i]); } std::vector<unsigned char> privateKey; privateKey.reserve(privateKeySize); for (int i = 0; i < privateKeySize; i++) { privateKey.push_back(privateKeyBytes[i]); } this->ParseData(pemData); } Certificate::Certificate(std::vector<unsigned char>& data) { this->ParseData(data); } void Certificate::ParseData(std::vector<unsigned char>& data) { std::vector<unsigned char> pemData; std::string prefix(data.begin(), data.begin() + std::min(data.size(), kCertificatePEMPrefix.size())); if (prefix != kCertificatePEMPrefix) { // Convert to proper PEM format before storing. utility::string_t base64Data = utility::conversions::to_base64(data); std::stringstream ss; ss << kCertificatePEMPrefix << std::endl << StringFromWideString(base64Data) << std::endl << kCertificatePEMSuffix; auto content = ss.str(); pemData = std::vector<unsigned char>(content.begin(), content.end()); } else { pemData = data; } BIO *certificateBuffer = BIO_new(BIO_s_mem()); BIO_write(certificateBuffer, pemData.data(), (int)pemData.size()); X509 *certificate = nullptr; PEM_read_bio_X509(certificateBuffer, &certificate, 0, 0); if (certificate == nullptr) { throw APIError(APIErrorCode::InvalidResponse); } /* Certificate Common Name */ X509_NAME *subject = X509_get_subject_name(certificate); int index = X509_NAME_get_index_by_NID(subject, NID_commonName, -1); if (index == -1) { throw APIError(APIErrorCode::InvalidResponse); } X509_NAME_ENTRY *nameEntry = X509_NAME_get_entry(subject, index); ASN1_STRING *nameData = X509_NAME_ENTRY_get_data(nameEntry); char *cName = (char *)ASN1_STRING_data(nameData); /* Serial Number */ ASN1_INTEGER *serialNumberData = X509_get_serialNumber(certificate); BIGNUM *number = ASN1_INTEGER_to_BN(serialNumberData, NULL); if (number == nullptr) { throw APIError(APIErrorCode::InvalidResponse); } char *cSerialNumber = BN_bn2hex(number); if (cName == nullptr || cSerialNumber == nullptr) { throw APIError(APIErrorCode::InvalidResponse); } std::string serialNumber(cSerialNumber); serialNumber.erase(0, std::min(serialNumber.find_first_not_of('0'), serialNumber.size() - 1)); // Remove leading zeroes. _name = cName; _serialNumber = serialNumber; _data = pemData; } #pragma mark - Description - std::ostream& operator<<(std::ostream& os, const Certificate& certificate) { os << "Name: " << certificate.name() << " SN: " << certificate.serialNumber(); return os; } #pragma mark - Getters - std::string Certificate::name() const { return _name; } std::string Certificate::serialNumber() const { return _serialNumber; } std::optional<std::string> Certificate::identifier() const { return _identifier; } std::optional<std::string> Certificate::machineName() const { return _machineName; } std::optional<std::string> Certificate::machineIdentifier() const { return _machineIdentifier; } std::optional<std::vector<unsigned char>> Certificate::data() const { return _data; } std::optional<std::vector<unsigned char>> Certificate::privateKey() const { return _privateKey; } void Certificate::setPrivateKey(std::optional<std::vector<unsigned char>> privateKey) { _privateKey = privateKey; } std::optional<std::vector<unsigned char>> Certificate::p12Data() const { return this->encryptedP12Data(""); } std::optional<std::vector<unsigned char>> Certificate::encryptedP12Data(std::string password) const { if (!this->data().has_value()) { return std::nullopt; } BIO* certificateBuffer = BIO_new(BIO_s_mem()); BIO* privateKeyBuffer = BIO_new(BIO_s_mem()); BIO_write(certificateBuffer, this->data()->data(), (int)this->data()->size()); if (this->privateKey().has_value()) { BIO_write(privateKeyBuffer, this->privateKey()->data(), (int)this->privateKey()->size()); } X509* certificate = nullptr; PEM_read_bio_X509(certificateBuffer, &certificate, 0, 0); EVP_PKEY* privateKey = nullptr; PEM_read_bio_PrivateKey(privateKeyBuffer, &privateKey, 0, 0); char emptyString[] = ""; PKCS12* outputP12 = PKCS12_create((char *)password.c_str(), emptyString, privateKey, certificate, NULL, 0, 0, 0, 0, 0); BIO* p12Buffer = BIO_new(BIO_s_mem()); i2d_PKCS12_bio(p12Buffer, outputP12); char* buffer = NULL; int size = (int)BIO_get_mem_data(p12Buffer, &buffer); std::vector<unsigned char> p12Data; p12Data.reserve(size); for (int i = 0; i < size; i++) { p12Data.push_back(buffer[i]); } BIO_free(p12Buffer); PKCS12_free(outputP12); EVP_PKEY_free(privateKey); X509_free(certificate); BIO_free(privateKeyBuffer); BIO_free(certificateBuffer); return p12Data; }
[ "riley@rileytestut.com" ]
riley@rileytestut.com
4a87bc9ab570005c82170589848e59491465f602
7bfcd9d9bc389d8b0a422830dbd3b741a4f7067b
/boj/11722.cpp
81b5f976a2ac74baad61ac6bc8ce9bb6ad13a9e6
[]
no_license
taehyeok-jang/algorithms
d0a762e5b4abc92b77287b11ff01d9591422c7d9
7254984d5b394371c0e96b93912aebc42a45f8cb
refs/heads/master
2023-04-02T23:45:00.740807
2021-03-28T14:35:05
2021-03-28T14:35:05
123,245,936
0
0
null
null
null
null
UTF-8
C++
false
false
401
cpp
#include <stdio.h> using namespace std; int N; int A[1001], dp[1001]; int main() { scanf("%d", &N); for(int i=0; i<N; i++) scanf("%d", &A[i]); int ans = 0; for(int i=0; i<N; i++) { dp[i] = 1; for(int j=0; j<i; j++) if(A[i]<A[j]&&dp[i]<dp[j]+1) dp[i] = dp[j]+1; ans = ans<dp[i]? dp[i]:ans; } printf("%d", ans); return 0; }
[ "jth@jthui-MacBook-Pro.local" ]
jth@jthui-MacBook-Pro.local
f5570063443352a5d3ee37104556a8fd0597bb11
d524146e24cac91a8c49dc1c4916246826b81fa3
/SoundActiveLamp/Libraries/FastLED-master/FastLED.h
7d303234056a6daaf1d5bc1dd37a21c50b1d39b9
[ "MIT" ]
permissive
robbiesm/SoundActiveLamp
dba083a8189a906302328685458dd6148d8b63e3
524d4bbbf9eeddf31f8c1cda7db58b1098d383f2
refs/heads/master
2021-04-15T18:43:53.246187
2018-11-20T08:32:48
2018-11-20T08:32:48
126,400,375
0
0
null
null
null
null
UTF-8
C++
false
false
30,279
h
#ifndef __INC_FASTSPI_LED2_H #define __INC_FASTSPI_LED2_H ///@file FastLED.h /// central include file for FastLED, defines the CFastLED class/object #define xstr(s) str(s) #define str(s) #s #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) #define FASTLED_HAS_PRAGMA_MESSAGE #endif #define FASTLED_VERSION 3001005 #ifndef FASTLED_INTERNAL # ifdef FASTLED_HAS_PRAGMA_MESSAGE # pragma message "FastLED version 3.001.005" # else # warning FastLED version 3.001.005 (Not really a warning, just telling you here.) # endif #endif #ifndef __PROG_TYPES_COMPAT__ #define __PROG_TYPES_COMPAT__ #endif #ifdef SmartMatrix_h #include<SmartMatrix.h> #endif #ifdef DmxSimple_h #include<DmxSimple.h> #endif #ifdef DmxSerial_h #include<DMXSerial.h> #endif #include <stdint.h> /* #include "cpp_compat.h" #include "fastled_config.h" #include "led_sysdefs.h" #include "bitswap.h" #include "controller.h" #include "fastpin.h" #include "fastspi_types.h" #include "./dmx.h" #include "platforms.h" #include "fastled_progmem.h" #include "lib8tion.h" #include "pixeltypes.h" #include "hsv2rgb.h" #include "colorutils.h" #include "pixelset.h" #include "colorpalettes.h" #include "noise.h" #include "power_mgt.h" #include "fastspi.h" #include "chipsets.h" */ FASTLED_NAMESPACE_BEGIN /// definitions for the spi chipset constants enum ESPIChipsets { LPD8806, WS2801, WS2803, SM16716, P9813, APA102, SK9822, DOTSTAR }; enum ESM { SMART_MATRIX }; enum OWS2811 { OCTOWS2811,OCTOWS2811_400, OCTOWS2813}; #ifdef HAS_PIXIE template<uint8_t DATA_PIN, EOrder RGB_ORDER> class PIXIE : public PixieController<DATA_PIN, RGB_ORDER> {}; #endif #ifdef FASTLED_HAS_CLOCKLESS template<uint8_t DATA_PIN> class NEOPIXEL : public WS2812Controller800Khz<DATA_PIN, GRB> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class TM1829 : public TM1829Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class TM1812 : public TM1809Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class TM1809 : public TM1809Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class TM1804 : public TM1809Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class TM1803 : public TM1803Controller400Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class UCS1903 : public UCS1903Controller400Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class UCS1903B : public UCS1903BController800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class UCS1904 : public UCS1904Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class UCS2903 : public UCS2903Controller<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class WS2812 : public WS2812Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class WS2852 : public WS2812Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class WS2812B : public WS2812Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class SK6812 : public SK6812Controller<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class SK6822 : public SK6822Controller<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class APA106 : public SK6822Controller<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class PL9823 : public PL9823Controller<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class WS2811 : public WS2811Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class WS2813 : public WS2813Controller<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class APA104 : public WS2811Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class WS2811_400 : public WS2811Controller400Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class GW6205 : public GW6205Controller800Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class GW6205_400 : public GW6205Controller400Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class LPD1886 : public LPD1886Controller1250Khz<DATA_PIN, RGB_ORDER> {}; template<uint8_t DATA_PIN, EOrder RGB_ORDER> class LPD1886_8BIT : public LPD1886Controller1250Khz_8bit<DATA_PIN, RGB_ORDER> {}; #ifdef DmxSimple_h template<uint8_t DATA_PIN, EOrder RGB_ORDER> class DMXSIMPLE : public DMXSimpleController<DATA_PIN, RGB_ORDER> {}; #endif #ifdef DmxSerial_h template<EOrder RGB_ORDER> class DMXSERIAL : public DMXSerialController<RGB_ORDER> {}; #endif #endif enum EBlockChipsets { #ifdef PORTA_FIRST_PIN WS2811_PORTA, WS2813_PORTA, WS2811_400_PORTA, TM1803_PORTA, UCS1903_PORTA, #endif #ifdef PORTB_FIRST_PIN WS2811_PORTB, WS2813_PORTB, WS2811_400_PORTB, TM1803_PORTB, UCS1903_PORTB, #endif #ifdef PORTC_FIRST_PIN WS2811_PORTC, WS2813_PORTC, WS2811_400_PORTC, TM1803_PORTC, UCS1903_PORTC, #endif #ifdef PORTD_FIRST_PIN WS2811_PORTD, WS2813_PORTD, WS2811_400_PORTD, TM1803_PORTD, UCS1903_PORTD, #endif #ifdef HAS_PORTDC WS2811_PORTDC, WS2813_PORTDC, WS2811_400_PORTDC, TM1803_PORTDC, UCS1903_PORTDC, #endif }; #if defined(LIB8_ATTINY) #define NUM_CONTROLLERS 2 #else #define NUM_CONTROLLERS 8 #endif typedef uint8_t (*power_func)(uint8_t scale, uint32_t data); /// High level controller interface for FastLED. This class manages controllers, global settings and trackings /// such as brightness, and refresh rates, and provides access functions for driving led data to controllers /// via the show/showColor/clear methods. /// @nosubgrouping class CFastLED { // int m_nControllers; uint8_t m_Scale; ///< The current global brightness scale setting uint16_t m_nFPS; ///< Tracking for current FPS value uint32_t m_nMinMicros; ///< minimum µs between frames, used for capping frame rates. uint32_t m_nPowerData; ///< max power use parameter power_func m_pPowerFunc; ///< function for overriding brightness when using FastLED.show(); public: CFastLED(); /// Add a CLEDController instance to the world. Exposed to the public to allow people to implement their own /// CLEDController objects or instances. There are two ways to call this method (as well as the other addLeds) /// variations. The first is with 3 arguments, in which case the arguments are the controller, a pointer to /// led data, and the number of leds used by this controller. The second is with 4 arguments, in which case /// the first two arguments are the same, the third argument is an offset into the CRGB data where this controller's /// CRGB data begins, and the fourth argument is the number of leds for this controller object. /// @param pLed - the led controller being added /// @param data - base point to an array of CRGB data structures /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array /// @param nLedsIfOffset - number of leds (4 argument version) /// @returns a reference to the added controller static CLEDController &addLeds(CLEDController *pLed, struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0); /// @name Adding SPI based controllers //@{ /// Add an SPI based CLEDController instance to the world. /// There are two ways to call this method (as well as the other addLeds) /// variations. The first is with 2 arguments, in which case the arguments are a pointer to /// led data, and the number of leds used by this controller. The second is with 3 arguments, in which case /// the first argument is the same, the second argument is an offset into the CRGB data where this controller's /// CRGB data begins, and the third argument is the number of leds for this controller object. /// /// This method also takes a 1 to 5 template parameters for identifying the specific chipset, data and clock pins, /// RGB ordering, and SPI data rate /// @param data - base point to an array of CRGB data structures /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array /// @param nLedsIfOffset - number of leds (4 argument version) /// @tparam CHIPSET - the chipset type /// @tparam DATA_PIN - the optional data pin for the leds (if omitted, will default to the first hardware SPI MOSI pin) /// @tparam CLOCK_PIN - the optional clock pin for the leds (if omitted, will default to the first hardware SPI clock pin) /// @tparam RGB_ORDER - the rgb ordering for the leds (e.g. what order red, green, and blue data is written out in) /// @tparam SPI_DATA_RATE - the data rate to drive the SPI clock at, defined using DATA_RATE_MHZ or DATA_RATE_KHZ macros /// @returns a reference to the added controller template<ESPIChipsets CHIPSET, uint8_t DATA_PIN, uint8_t CLOCK_PIN, EOrder RGB_ORDER, uint8_t SPI_DATA_RATE > CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { switch(CHIPSET) { case LPD8806: { static LPD8806Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER, SPI_DATA_RATE> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case WS2801: { static WS2801Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER, SPI_DATA_RATE> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case WS2803: { static WS2803Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER, SPI_DATA_RATE> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case SM16716: { static SM16716Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER, SPI_DATA_RATE> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case P9813: { static P9813Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER, SPI_DATA_RATE> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case DOTSTAR: case APA102: { static APA102Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER, SPI_DATA_RATE> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case SK9822: { static SK9822Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER, SPI_DATA_RATE> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } } } template<ESPIChipsets CHIPSET, uint8_t DATA_PIN, uint8_t CLOCK_PIN > static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { switch(CHIPSET) { case LPD8806: { static LPD8806Controller<DATA_PIN, CLOCK_PIN> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case WS2801: { static WS2801Controller<DATA_PIN, CLOCK_PIN> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case WS2803: { static WS2803Controller<DATA_PIN, CLOCK_PIN> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case SM16716: { static SM16716Controller<DATA_PIN, CLOCK_PIN> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case P9813: { static P9813Controller<DATA_PIN, CLOCK_PIN> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case DOTSTAR: case APA102: { static APA102Controller<DATA_PIN, CLOCK_PIN> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case SK9822: { static SK9822Controller<DATA_PIN, CLOCK_PIN> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } } } template<ESPIChipsets CHIPSET, uint8_t DATA_PIN, uint8_t CLOCK_PIN, EOrder RGB_ORDER > static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { switch(CHIPSET) { case LPD8806: { static LPD8806Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case WS2801: { static WS2801Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case WS2803: { static WS2803Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case SM16716: { static SM16716Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case P9813: { static P9813Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case DOTSTAR: case APA102: { static APA102Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } case SK9822: { static SK9822Controller<DATA_PIN, CLOCK_PIN, RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } } } #ifdef SPI_DATA template<ESPIChipsets CHIPSET> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { return addLeds<CHIPSET, SPI_DATA, SPI_CLOCK, RGB>(data, nLedsOrOffset, nLedsIfOffset); } template<ESPIChipsets CHIPSET, EOrder RGB_ORDER> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { return addLeds<CHIPSET, SPI_DATA, SPI_CLOCK, RGB_ORDER>(data, nLedsOrOffset, nLedsIfOffset); } template<ESPIChipsets CHIPSET, EOrder RGB_ORDER, uint8_t SPI_DATA_RATE> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { return addLeds<CHIPSET, SPI_DATA, SPI_CLOCK, RGB_ORDER, SPI_DATA_RATE>(data, nLedsOrOffset, nLedsIfOffset); } #endif //@} #ifdef FASTLED_HAS_CLOCKLESS /// @name Adding 3-wire led controllers //@{ /// Add a clockless (aka 3wire, also DMX) based CLEDController instance to the world. /// There are two ways to call this method (as well as the other addLeds) /// variations. The first is with 2 arguments, in which case the arguments are a pointer to /// led data, and the number of leds used by this controller. The second is with 3 arguments, in which case /// the first argument is the same, the second argument is an offset into the CRGB data where this controller's /// CRGB data begins, and the third argument is the number of leds for this controller object. /// /// This method also takes a 2 to 3 template parameters for identifying the specific chipset, data pin, and rgb ordering /// RGB ordering, and SPI data rate /// @param data - base point to an array of CRGB data structures /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array /// @param nLedsIfOffset - number of leds (4 argument version) /// @tparam CHIPSET - the chipset type (required) /// @tparam DATA_PIN - the optional data pin for the leds (required) /// @tparam RGB_ORDER - the rgb ordering for the leds (e.g. what order red, green, and blue data is written out in) /// @returns a reference to the added controller template<template<uint8_t DATA_PIN, EOrder RGB_ORDER> class CHIPSET, uint8_t DATA_PIN, EOrder RGB_ORDER> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { static CHIPSET<DATA_PIN, RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } template<template<uint8_t DATA_PIN, EOrder RGB_ORDER> class CHIPSET, uint8_t DATA_PIN> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { static CHIPSET<DATA_PIN, RGB> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } template<template<uint8_t DATA_PIN> class CHIPSET, uint8_t DATA_PIN> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { static CHIPSET<DATA_PIN> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } #ifdef FASTSPI_USE_DMX_SIMPLE template<EClocklessChipsets CHIPSET, uint8_t DATA_PIN, EOrder RGB_ORDER=RGB> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { switch(CHIPSET) { case DMX: { static DMXController<DATA_PIN> controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } } } #endif //@} #endif /// @name Adding 3rd party library controllers //@{ /// Add a 3rd party library based CLEDController instance to the world. /// There are two ways to call this method (as well as the other addLeds) /// variations. The first is with 2 arguments, in which case the arguments are a pointer to /// led data, and the number of leds used by this controller. The second is with 3 arguments, in which case /// the first argument is the same, the second argument is an offset into the CRGB data where this controller's /// CRGB data begins, and the third argument is the number of leds for this controller object. This class includes the SmartMatrix /// and OctoWS2811 based controllers /// /// This method also takes a 1 to 2 template parameters for identifying the specific chipset and rgb ordering /// RGB ordering, and SPI data rate /// @param data - base point to an array of CRGB data structures /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array /// @param nLedsIfOffset - number of leds (4 argument version) /// @tparam CHIPSET - the chipset type (required) /// @tparam RGB_ORDER - the rgb ordering for the leds (e.g. what order red, green, and blue data is written out in) /// @returns a reference to the added controller template<template<EOrder RGB_ORDER> class CHIPSET, EOrder RGB_ORDER> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { static CHIPSET<RGB_ORDER> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } template<template<EOrder RGB_ORDER> class CHIPSET> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { static CHIPSET<RGB> c; return addLeds(&c, data, nLedsOrOffset, nLedsIfOffset); } #ifdef USE_OCTOWS2811 template<OWS2811 CHIPSET, EOrder RGB_ORDER> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { switch(CHIPSET) { case OCTOWS2811: { static COctoWS2811Controller<RGB_ORDER,WS2811_800kHz> controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } case OCTOWS2811_400: { static COctoWS2811Controller<RGB_ORDER,WS2811_400kHz> controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } case OCTOWS2813: { static COctoWS2811Controller<RGB_ORDER,WS2813_800kHz> controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } } } template<OWS2811 CHIPSET> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { return addLeds<CHIPSET,GRB>(data,nLedsOrOffset,nLedsIfOffset); } #endif #ifdef SmartMatrix_h template<ESM CHIPSET> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { switch(CHIPSET) { case SMART_MATRIX: { static CSmartMatrixController controller; return addLeds(&controller, data, nLedsOrOffset, nLedsIfOffset); } } } #endif //@} #ifdef FASTLED_HAS_BLOCKLESS /// @name adding parallel output controllers //@{ /// Add a block based CLEDController instance to the world. /// There are two ways to call this method (as well as the other addLeds) /// variations. The first is with 2 arguments, in which case the arguments are a pointer to /// led data, and the number of leds used by this controller. The second is with 3 arguments, in which case /// the first argument is the same, the second argument is an offset into the CRGB data where this controller's /// CRGB data begins, and the third argument is the number of leds for this controller object. /// /// This method also takes a 2 to 3 template parameters for identifying the specific chipset and rgb ordering /// RGB ordering, and SPI data rate /// @param data - base point to an array of CRGB data structures /// @param nLedsOrOffset - number of leds (3 argument version) or offset into the data array /// @param nLedsIfOffset - number of leds (4 argument version) /// @tparam CHIPSET - the chipset/port type (required) /// @tparam NUM_LANES - how many parallel lanes of output to write /// @tparam RGB_ORDER - the rgb ordering for the leds (e.g. what order red, green, and blue data is written out in) /// @returns a reference to the added controller template<EBlockChipsets CHIPSET, int NUM_LANES, EOrder RGB_ORDER> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { switch(CHIPSET) { #ifdef PORTA_FIRST_PIN case WS2811_PORTA: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTA_FIRST_PIN, NS(320), NS(320), NS(640), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2811_400_PORTA: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTA_FIRST_PIN, NS(800), NS(800), NS(900), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2813_PORTA: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTA_FIRST_PIN, NS(320), NS(320), NS(640), RGB_ORDER, 0, false, 300>(), data, nLedsOrOffset, nLedsIfOffset); case TM1803_PORTA: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTA_FIRST_PIN, NS(700), NS(1100), NS(700), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case UCS1903_PORTA: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTA_FIRST_PIN, NS(500), NS(1500), NS(500), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); #endif #ifdef PORTB_FIRST_PIN case WS2811_PORTB: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTB_FIRST_PIN, NS(320), NS(320), NS(640), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2811_400_PORTB: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTB_FIRST_PIN, NS(800), NS(800), NS(900), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2813_PORTB: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTB_FIRST_PIN, NS(320), NS(320), NS(640), RGB_ORDER, 0, false, 300>(), data, nLedsOrOffset, nLedsIfOffset); case TM1803_PORTB: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTB_FIRST_PIN, NS(700), NS(1100), NS(700), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case UCS1903_PORTB: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTB_FIRST_PIN, NS(500), NS(1500), NS(500), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); #endif #ifdef PORTC_FIRST_PIN case WS2811_PORTC: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTC_FIRST_PIN, NS(320), NS(320), NS(640), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2811_400_PORTC: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTC_FIRST_PIN, NS(800), NS(800), NS(900), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2813_PORTC: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTC_FIRST_PIN, NS(320), NS(320), NS(640), RGB_ORDER, 0, false, 300>(), data, nLedsOrOffset, nLedsIfOffset); case TM1803_PORTC: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTC_FIRST_PIN, NS(700), NS(1100), NS(700), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case UCS1903_PORTC: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTC_FIRST_PIN, NS(500), NS(1500), NS(500), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); #endif #ifdef PORTD_FIRST_PIN case WS2811_PORTD: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTD_FIRST_PIN, NS(320), NS(320), NS(640), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2811_400_PORTD: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTD_FIRST_PIN, NS(800), NS(800), NS(900), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2813_PORTD: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTD_FIRST_PIN, NS(320), NS(320), NS(640), RGB_ORDER, 0, false, 300>(), data, nLedsOrOffset, nLedsIfOffset); case TM1803_PORTD: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTD_FIRST_PIN, NS(700), NS(1100), NS(700), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case UCS1903_PORTD: return addLeds(new InlineBlockClocklessController<NUM_LANES, PORTD_FIRST_PIN, NS(500), NS(1500), NS(500), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); #endif #ifdef HAS_PORTDC case WS2811_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController<NUM_LANES,NS(320), NS(320), NS(640), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2811_400_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController<NUM_LANES,NS(800), NS(800), NS(900), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case WS2813_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController<NUM_LANES, NS(320), NS(320), NS(640), RGB_ORDER, 0, false, 300>(), data, nLedsOrOffset, nLedsIfOffset); case TM1803_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController<NUM_LANES, NS(700), NS(1100), NS(700), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); case UCS1903_PORTDC: return addLeds(new SixteenWayInlineBlockClocklessController<NUM_LANES, NS(500), NS(1500), NS(500), RGB_ORDER>(), data, nLedsOrOffset, nLedsIfOffset); #endif } } template<EBlockChipsets CHIPSET, int NUM_LANES> static CLEDController &addLeds(struct CRGB *data, int nLedsOrOffset, int nLedsIfOffset = 0) { return addLeds<CHIPSET,NUM_LANES,GRB>(data,nLedsOrOffset,nLedsIfOffset); } //@} #endif /// Set the global brightness scaling /// @param scale a 0-255 value for how much to scale all leds before writing them out void setBrightness(uint8_t scale) { m_Scale = scale; } /// Get the current global brightness setting /// @returns the current global brightness value uint8_t getBrightness() { return m_Scale; } /// Set the maximum power to be used, given in volts and milliamps. /// @param volts - how many volts the leds are being driven at (usually 5) /// @param milliamps - the maximum milliamps of power draw you want inline void setMaxPowerInVoltsAndMilliamps(uint8_t volts, uint32_t milliamps) { setMaxPowerInMilliWatts(volts * milliamps); } /// Set the maximum power to be used, given in milliwatts /// @param milliwatts - the max power draw desired, in milliwatts inline void setMaxPowerInMilliWatts(uint32_t milliwatts) { m_pPowerFunc = &calculate_max_brightness_for_power_mW; m_nPowerData = milliwatts; } /// Update all our controllers with the current led colors, using the passed in brightness /// @param scale temporarily override the scale void show(uint8_t scale); /// Update all our controllers with the current led colors void show() { show(m_Scale); } /// clear the leds, wiping the local array of data, optionally black out the leds as well /// @param writeData whether or not to write out to the leds as well void clear(boolean writeData = false); /// clear out the local data array void clearData(); /// Set all leds on all controllers to the given color/scale /// @param color what color to set the leds to /// @param scale what brightness scale to show at void showColor(const struct CRGB & color, uint8_t scale); /// Set all leds on all controllers to the given color /// @param color what color to set the leds to void showColor(const struct CRGB & color) { showColor(color, m_Scale); } /// Delay for the given number of milliseconds. Provided to allow the library to be used on platforms /// that don't have a delay function (to allow code to be more portable). Note: this will call show /// constantly to drive the dithering engine (and will call show at least once). /// @param ms the number of milliseconds to pause for void delay(unsigned long ms); /// Set a global color temperature. Sets the color temperature for all added led strips, overriding whatever /// previous color temperature those controllers may have had /// @param temp A CRGB structure describing the color temperature void setTemperature(const struct CRGB & temp); /// Set a global color correction. Sets the color correction for all added led strips, /// overriding whatever previous color correction those controllers may have had. /// @param correction A CRGB structure describin the color correction. void setCorrection(const struct CRGB & correction); /// Set the dithering mode. Sets the dithering mode for all added led strips, overriding /// whatever previous dithering option those controllers may have had. /// @param ditherMode - what type of dithering to use, either BINARY_DITHER or DISABLE_DITHER void setDither(uint8_t ditherMode = BINARY_DITHER); /// Set the maximum refresh rate. This is global for all leds. Attempts to /// call show faster than this rate will simply wait. Note that the refresh rate /// defaults to the slowest refresh rate of all the leds added through addLeds. If /// you wish to set/override this rate, be sure to call setMaxRefreshRate _after_ /// adding all of your leds. /// @param refresh - maximum refresh rate in hz /// @param constrain - constrain refresh rate to the slowest speed yet set void setMaxRefreshRate(uint16_t refresh, bool constrain=false); /// for debugging, will keep track of time between calls to countFPS, and every /// nFrames calls, it will update an internal counter for the current FPS. /// @todo make this a rolling counter /// @param nFrames - how many frames to time for determining FPS void countFPS(int nFrames=25); /// Get the number of frames/second being written out /// @returns the most recently computed FPS value uint16_t getFPS() { return m_nFPS; } /// Get how many controllers have been registered /// @returns the number of controllers (strips) that have been added with addLeds int count(); /// Get a reference to a registered controller /// @returns a reference to the Nth controller CLEDController & operator[](int x); /// Get the number of leds in the first controller /// @returns the number of LEDs in the first controller int size() { return (*this)[0].size(); } /// Get a pointer to led data for the first controller /// @returns pointer to the CRGB buffer for the first controller CRGB *leds() { return (*this)[0].leds(); } }; #define FastSPI_LED FastLED #define FastSPI_LED2 FastLED #ifndef LEDS #define LEDS FastLED #endif extern CFastLED FastLED; // Warnings for undefined things #ifndef HAS_HARDWARE_PIN_SUPPORT #warning "No pin/port mappings found, pin access will be slightly slower. See fastpin.h for info." #define NO_HARDWARE_PIN_SUPPORT #endif FASTLED_NAMESPACE_END #endif
[ "r0614858@student.thomasmore.be" ]
r0614858@student.thomasmore.be
56b57596c775ff6035b3e1acfdc618988e7f2f72
f1c39fcf9f40801a8ae4a317706d1877bfa8fe8b
/itung2an.cpp
cd75a7bd84831e6d5c12ae0fce62b3cf7e31db60
[]
no_license
Imammulh/Belajara-bahasa-C
872587ef17c2d9134fa0eac0b4e06d249aeceb35
13b1eef179b55e6b1cb0dfef43b85a11a6ed7897
refs/heads/master
2021-06-13T03:25:28.859822
2021-05-16T14:42:55
2021-05-16T14:42:55
254,421,249
0
0
null
null
null
null
UTF-8
C++
false
false
95
cpp
#include <iostream> using namespace std; int main() {int A,B,T; A=6; B=8; T=A*B; cout << T; }
[ "imam_chelsea2@apps.ipb.ac.id" ]
imam_chelsea2@apps.ipb.ac.id
9ba0e9a2e50c948ecef829ac711cbc2c397b52db
acc3f19bd25c01b1e8c861ed6f0af09d1861caa6
/dialogs/welcome.h
af9e3cb5e424f0520db29410e0b9126a8a47881e
[]
no_license
nickgammon/mushclient
7da44c02f2ebaedd38273e0c1f67a8a155a1f137
5f1ca253cf6f44b65caeafd9f2ad7a4b87817c8e
refs/heads/master
2022-11-11T14:57:20.924735
2022-10-30T00:32:03
2022-10-30T00:32:03
481,654
152
94
null
2023-09-06T03:35:59
2010-01-21T03:28:51
C
UTF-8
C++
false
false
842
h
// welcome.h : header file // ///////////////////////////////////////////////////////////////////////////// // CWelcomeDlg dialog class CWelcomeDlg : public CDialog { protected: // static controls with hyperlinks CStaticLink m_ChangesLink; // Construction public: CWelcomeDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CWelcomeDlg) enum { IDD = IDD_WELCOME }; CString m_strMessage; CString m_strChangeHistoryAddress; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CWelcomeDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CWelcomeDlg) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() };
[ "nick@gammon.com.au" ]
nick@gammon.com.au
7c3af7604f4b52fb698a90c3b75f48e4fd91ab94
243cf387f0c7191a63f37296a87ed843d5692783
/src/MusicManager.hpp
b49366554ec5ee16e74b2e50bf5f9f18641c0889
[]
no_license
jasetom/audio-visuals-excerpt-from-VinylAR
c94e1462b1f0c8ac671545d4b59ead7514b4bb70
fe75a82f4d58e45c9c864eec85bcac397cfe4086
refs/heads/master
2021-01-19T22:08:39.247619
2017-04-19T15:07:22
2017-04-19T15:07:22
88,758,559
0
0
null
null
null
null
UTF-8
C++
false
false
2,714
hpp
// // MusicManager.hpp // // Created by Tomas on 13/03/2017. // // #ifndef MusicManager_hpp #define MusicManager_hpp #include <stdio.h> #include "ofMain.h" #include "ofxMaxim.h" class MusicManager { public: void setup(); void update(int imgId); void audioOut(float * output, int bufferSize, int nChannels); //audio output function void play(bool play); void analyseSound(); void calculatePitchHistogram(); bool detectBeat(); void nextSong(); void prevSong(); void firstDetect(); void draw(int xPos, int yPos); //Sound feature extraction: //get analysed sound features (single constantly updating values) float getSpecCentroid1(); float getSpecCentroid2(); float getSpecFlatness(); float getPeakFreq(); float getRms(); //multiple values float getFftMagnitudes(int i); float getMfccs(int i); float getOctaveAvg(int i); float getPitchHistogram(int i); float getMelBands(int i); bool getIsBeatDetected(); ofxMaxiFFT * getFFT(); ofxMaxiMFCC * getMFCC(); ofxMaxiFFTOctaveAnalyzer * getFFTOctaveAnalyzer(); string getAlbumSongNames(); string getCurrentSongName(); int getOctaveAvgN(); int getFftSize(); bool isPlay(); private: //Loading and playing music maxiSample samp, samp1,samp2,samp3,samp4,samp5,samp6,samp7,samp8,samp9; int initialBufferSize; //buffer size int sampleRate; //sample rate variable double playingSound; //variable where we store data when sound is playing bool playSound; float * lAudio; //left audio output float * rAudio; //right audio output /* FFT */ ofxMaxiFFT mfft; int fftSize, windowSize, hopSize; int bins, dataSize; //other analysation tools double wave,sample, ifftVal; maxiMix mymix; maxiOsc osc; //spectralFlux for beat detection vector <float> prevFFT; float specFlux; int waitTime; float threshold; bool beatDetected; ofxMaxiFFTOctaveAnalyzer oct; int nAverages; float *ifftOutput; int ifftSize; float peakFreq = 0; float specCentroid1 = 0; float specCentroid2 = 0; float specFlatness = 0; float rms = 0; float pitchHistogram[12]; maxiMFCC mfcc; double *mfccs; //music control int currentSong; //we create a vector of ints(ids for songs) and strings(names of the songs); vector < pair<int, string> > songs; bool nextSound; bool prevSound; bool first; bool swapSong; //we use this variable to store detected image id comming from OrbTracker class. int detectedImgId; }; #endif /* MusicManager_hpp */
[ "Tomasjase@gmail.com" ]
Tomasjase@gmail.com
7d17835f79fba8ca356b04cbad31c2e8fa4e34fc
6f46ecc474c4045b9106b3f6046f0cad4e49f5b2
/GameTest/glowEngine/presets/PlayerEntity.cpp
734cc45c32dff35826052b16f23c056ec11bdedb
[]
no_license
Glowies/Ubisoft-NEXT-2020
29265e50a7355cc3416e6863e2b48d243cd9cd4b
81d087f45f1a032b40fac83b3de1b7e4584f0bbf
refs/heads/master
2023-01-06T15:49:29.194254
2020-10-12T13:29:53
2020-10-12T13:29:53
303,396,538
0
0
null
null
null
null
UTF-8
C++
false
false
327
cpp
#include "stdafx.h" #include "PlayerEntity.h" PlayerEntity::PlayerEntity() : Entity() { TunnelTraveler* trav = AddAttachment<PlayerTraveler>(); AddAttachment<PlayerRenderer>(); AddAttachment<CircleCollider>(); GetAttachment<Transform>()->position = Vector2(512, 200); GetAttachment<Transform>()->scale = Vector2(3, 1); }
[ "oktaycomu@gmail.com" ]
oktaycomu@gmail.com
bc97755a11ff79af13fd19f93b2712a4aafd9874
26f56a9f2d8c842ce3c465ed89ec37f7aef3b53a
/simulation/17281.cpp
24d4818c3bf7cc03aad77d4b7f5271d88fcaf319
[]
no_license
chewin9/algorithm
5fb468bf9861d82b88e35c97946f351c3b4c04c0
e3bfb5ec95038665e9cf6b42db0a828897bb5090
refs/heads/master
2023-02-26T12:01:39.578315
2021-02-02T12:34:13
2021-02-02T12:34:13
283,669,109
0
0
null
null
null
null
UTF-8
C++
false
false
3,662
cpp
#include<iostream> #include<algorithm> #include<string.h> using namespace std; int arr[52][12]; int N; int ans = -1e9; int choose[10]; bool visit[10]; bool home[4]; //0 home 1 1ro 2ro 3ro int get_point(int cnt) { if (home[3] == true) cnt++; for (int i = 3; i > 0; i--) home[i] = home[i - 1]; //home[1] = true; return cnt; } void play_game() { memset(home, false, sizeof(home)); int out = 0; int cnt = 0; int cur = 1; bool check = false; for (int i = 1; i < N + 1; i++) { out = 0; for (int j = 0; j < 4; j++) home[j] = false; while (out < 3) { home[0] = true; if (arr[i][choose[cur]] == 0) { out++; } else { for (int j = 3; j >= 0; j--) { if (home[j] == false) continue; int tmp = j + arr[i][choose[cur]]; if (tmp > 3) cnt++; else home[tmp] = true; home[j] = false; } } cur++; if (cur == 10) cur = 1; } } ans = max(cnt, ans); //while (in <N+1) { // check = false; // for (int i = pre; i < 10; i++) { // switch (arr[in][choose[i]]) { // case 0: // out++; // break; // case 1: // if (home[3] == true) // cnt++; // for (int i = 3; i > 0; i--) // home[i] = home[i - 1]; // home[1] = true; // /*cnt = get_point(cnt); // home[1] = true;*/ // break; // case 2: // if (home[3] == true) // cnt++; // if (home[2] == true) // cnt++; // home[3] = home[1]; // home[1] = false; // home[2] = true; // /*for (int i = 0; i < 2; i++) // cnt = get_point(cnt); // home[2] = true;*/ // break; // case 3: // for (int i = 3; i > 0; i--) // if (home[i] == true) // cnt++; // for (int i = 1; i < 4; i++) // home[i] = false; // home[3] = true; // /* // for (int i = 0; i < 3; i++) // cnt = get_point(cnt); // home[3] = true;*/ // break; // case 4: // for (int i = 1; i < 4; i++) { // if (home[i] == true) { // home[i] = false; // cnt++; // } // } // cnt++; // break; // } // if (out == 3) { // out = 0; // memset(home, false, sizeof(home)); // in++; // pre = i + 1; // check = true; // break; // } // } // if (check == false) // pre = 1; //} ////printf("[%d]\n", cnt); //ans = max(cnt, ans); } //void dfs(int pos, int val) { // //choose[pos] = val; // //visit[val] = true; // if (pos == 4) { // choose[pos] = 1; // visit[1] = true; // for (int i = 2; i < 10; i++) // if (visit[i] == false) { // dfs(pos + 1, i); // visit[i] = false; // } // } // if (pos != 4) { // choose[pos] = val; // visit[val] = true; // } // if (pos == 9) { // /*printf("==================\n"); // for (int i = 1; i < 10; i++) { // printf("%2d", choose[i]); // }*/ // //printf("\n"); // // play_game(); // // // visit[val] = false; // return; // } // for (int i = 2; i < 10; i++) { // if (visit[i] == false) { // dfs(pos + 1, i); // visit[i] = false; // } // } //} void dfs(int pos, int val) { visit[val] = true; choose[pos] = val; if (pos == 9) { if (choose[4] != 1) return; /*printf("==================\n"); for (int i = 1; i < 10; i++) { printf("%2d", choose[i]); }*/ play_game(); visit[val] = false; return; } for (int i = 1; i < 10; i++) { if (visit[i] == false) { dfs(pos + 1, i); visit[i] = false; } } } int main() { scanf("%d", &N); for (int i = 1; i < N + 1; i++) { for (int j = 1; j < 10; j++) { scanf("%d", &arr[i][j]); } } for (int j = 1; j < 10; j++) { memset(choose, 0, sizeof(choose)); memset(visit, false, sizeof(visit)); /*choose[4] = 1; visit[1] = true;*/ dfs(1, j); } printf("%d\n", ans); return 0; }
[ "37531506+chewin9@users.noreply.github.com" ]
37531506+chewin9@users.noreply.github.com
0aea81062d157d998c248885ec1b33d86885c39f
07fb9fd837ef962e2e30c96a776e9e1a95e9d3fb
/ekart_Final_1/build-EkartF1-Desktop-Debug/ui_mainwindow.h
acc5a9f1fdfe1c4a908327dc1abd640811c74074
[]
no_license
LuizAlexandreA86362/eKartFinal1
ec58a17a9ea6466a15260da46b73c7b40f9819ad
1e79ede47aa66708911d88c701a5fc6419a7b4ef
refs/heads/master
2023-06-03T12:38:31.243133
2021-06-21T01:56:43
2021-06-21T01:56:43
378,714,512
0
0
null
null
null
null
UTF-8
C++
false
false
5,634
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.11.3 ** ** 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/QApplication> #include <QtWidgets/QLabel> #include <QtWidgets/QMainWindow> #include <QtWidgets/QMenuBar> #include <QtWidgets/QPushButton> #include <QtWidgets/QStatusBar> #include <QtWidgets/QToolBar> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QLabel *ekart_logo; QLabel *code_label; QPushButton *powerON; QLabel *code_label_2; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(417, 324); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); ekart_logo = new QLabel(centralWidget); ekart_logo->setObjectName(QStringLiteral("ekart_logo")); ekart_logo->setGeometry(QRect(140, 0, 111, 31)); QPalette palette; QBrush brush(QColor(255, 255, 255, 255)); brush.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::WindowText, brush); palette.setBrush(QPalette::Inactive, QPalette::WindowText, brush); QBrush brush1(QColor(143, 146, 147, 255)); brush1.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush1); ekart_logo->setPalette(palette); QFont font; font.setFamily(QStringLiteral("DejaVu Sans Mono")); font.setPointSize(28); font.setBold(true); font.setWeight(75); font.setStyleStrategy(QFont::PreferDefault); ekart_logo->setFont(font); ekart_logo->setStyleSheet(QLatin1String("#ekart_logo\n" "{\n" " background-color: transparent;\n" " background: none;\n" " border: none;\n" " background-repeat: none;\n" "}")); ekart_logo->setAlignment(Qt::AlignCenter); code_label = new QLabel(centralWidget); code_label->setObjectName(QStringLiteral("code_label")); code_label->setGeometry(QRect(140, 70, 131, 31)); QPalette palette1; palette1.setBrush(QPalette::Active, QPalette::WindowText, brush); palette1.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette1.setBrush(QPalette::Disabled, QPalette::WindowText, brush1); code_label->setPalette(palette1); QFont font1; font1.setFamily(QStringLiteral("Sans Serif")); font1.setPointSize(14); code_label->setFont(font1); code_label->setStyleSheet(QLatin1String("#code_label\n" "{\n" " background-color: transparent;\n" " background: none;\n" " border: none;\n" " background-repeat: none;\n" "}")); powerON = new QPushButton(centralWidget); powerON->setObjectName(QStringLiteral("powerON")); powerON->setGeometry(QRect(150, 190, 111, 81)); powerON->setStyleSheet(QLatin1String("#powerON\n" "{\n" "background-color: transparent;\n" "border-image: url(:power.png);\n" "background:none;\n" "border:none;\n" "background-repeat: none;\n" "}")); code_label_2 = new QLabel(centralWidget); code_label_2->setObjectName(QStringLiteral("code_label_2")); code_label_2->setGeometry(QRect(150, 100, 111, 31)); QPalette palette2; palette2.setBrush(QPalette::Active, QPalette::WindowText, brush); palette2.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette2.setBrush(QPalette::Disabled, QPalette::WindowText, brush1); code_label_2->setPalette(palette2); QFont font2; font2.setFamily(QStringLiteral("Serif")); font2.setPointSize(20); code_label_2->setFont(font2); code_label_2->setStyleSheet(QLatin1String("#code_label\n" "{\n" " background-color: transparent;\n" " background: none;\n" " border: none;\n" " background-repeat: none;\n" "}")); MainWindow->setCentralWidget(centralWidget); menuBar = new QMenuBar(MainWindow); menuBar->setObjectName(QStringLiteral("menuBar")); menuBar->setGeometry(QRect(0, 0, 417, 28)); MainWindow->setMenuBar(menuBar); mainToolBar = new QToolBar(MainWindow); mainToolBar->setObjectName(QStringLiteral("mainToolBar")); MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar); statusBar = new QStatusBar(MainWindow); statusBar->setObjectName(QStringLiteral("statusBar")); MainWindow->setStatusBar(statusBar); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "eKart", nullptr)); ekart_logo->setText(QApplication::translate("MainWindow", "eKart", nullptr)); code_label->setText(QApplication::translate("MainWindow", "Your code is:", nullptr)); powerON->setText(QString()); code_label_2->setText(QString()); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
[ "a86362@alunos.uminho.pt" ]
a86362@alunos.uminho.pt
089e59e71b1e77c9e7eb17d186b4e2b73efcd80d
a67c70c6ccd97819adb094cdfb5d272a10fa5284
/hw12_team9/AmericanPut.cpp
fcb0fccfabff72a05e4a43c2cbc12430275415c6
[]
no_license
RancyChepchirchir/MTH9821-Numerical-Methods-for-Finance-1
b488e84613cdcb069601b71c3031c026c7a1f62e
f04890e484d28c18e7a90341f79bfd312ac921b8
refs/heads/master
2021-09-17T19:40:33.412912
2018-07-04T17:04:59
2018-07-04T17:04:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
721
cpp
#include "AmericanPut.hpp" AmericanPut::AmericanPut() {}; AmericanPut::AmericanPut(const AmericanPut & other) : Option(other){}; AmericanPut::AmericanPut(double S0, double T, double K, double r, double sigma, double q) : Option(S0, T, K, r, sigma, q) {}; AmericanPut::AmericanPut(double S0, double T, double K, double r, double sigma, double q, double exact) : Option(S0, T, K, r, sigma, q), V_exact(exact) {}; AmericanPut::~AmericanPut(){}; AmericanPut& AmericanPut::operator = (const AmericanPut & option) { if (this==&option) return *this; Option::operator=(option); return *this; } std::string AmericanPut::OptionType() { return "American Put"; } double AmericanPut::Price() { return V_exact; }
[ "chiongheng.chen@gmail.com" ]
chiongheng.chen@gmail.com
f8645de20d57926c1b8fc8afcc872f9fae382204
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/gin/per_isolate_data.cc
6c2397ba50b0a67ef1bb20a516c1fc1ab6b49f34
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
1,725
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 "gin/per_isolate_data.h" #include "gin/public/gin_embedders.h" using v8::Eternal; using v8::Isolate; using v8::Local; using v8::Object; using v8::FunctionTemplate; using v8::ObjectTemplate; namespace gin { PerIsolateData::PerIsolateData(Isolate* isolate) : isolate_(isolate) { isolate_->SetData(kEmbedderNativeGin, this); } PerIsolateData::~PerIsolateData() { isolate_->SetData(kEmbedderNativeGin, NULL); } PerIsolateData* PerIsolateData::From(Isolate* isolate) { return static_cast<PerIsolateData*>(isolate->GetData(kEmbedderNativeGin)); } void PerIsolateData::SetObjectTemplate(WrapperInfo* info, Local<ObjectTemplate> templ) { object_templates_[info] = Eternal<ObjectTemplate>(isolate_, templ); } void PerIsolateData::SetFunctionTemplate(WrapperInfo* info, Local<FunctionTemplate> templ) { function_templates_[info] = Eternal<FunctionTemplate>(isolate_, templ); } v8::Local<v8::ObjectTemplate> PerIsolateData::GetObjectTemplate( WrapperInfo* info) { ObjectTemplateMap::iterator it = object_templates_.find(info); if (it == object_templates_.end()) return v8::Local<v8::ObjectTemplate>(); return it->second.Get(isolate_); } v8::Local<v8::FunctionTemplate> PerIsolateData::GetFunctionTemplate( WrapperInfo* info) { FunctionTemplateMap::iterator it = function_templates_.find(info); if (it == function_templates_.end()) return v8::Local<v8::FunctionTemplate>(); return it->second.Get(isolate_); } } // namespace gin
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
c7da09c0156d4d40e152d9ebd205a59d01870a72
461619a84c6617ceaf2b7913ef58c99ff32c0fb5
/com/IOleInPlaceObject/IOleInPlaceObject/src/IOleInPlaceObject/IOleInPlaceObject/WebBrowserHost.h
0066607d0b6c560d2681c66f85dcd2189d6de28f
[ "MIT" ]
permissive
bg1bgst333/Sample
cf066e48facac8ecd203c56665251fa1aa103844
298a4253dd8123b29bc90a3569f2117d7f6858f8
refs/heads/master
2023-09-02T00:46:31.139148
2023-09-01T02:41:42
2023-09-01T02:41:42
27,908,184
9
10
MIT
2023-09-06T20:49:55
2014-12-12T06:22:49
Java
SHIFT_JIS
C++
false
false
3,244
h
// 二重インクルード防止 #ifndef __WEB_BROWSER_HOST_H__ #define __WEB_BROWSER_HOST_H__ // ヘッダのインクルード // 既定のヘッダ #include <shlobj.h> // シェルオブジェクト // 独自のヘッダ #include "UserControl.h" // CUserControl // ウェブブラウザホストクラスCWebBrowserHost class CWebBrowserHost : public CUserControl, public IOleClientSite, public IOleInPlaceSite{ // privateメンバ private: // privateメンバ変数 LONG m_lRef; // 参照カウンタm_lRef IWebBrowser2 *m_pWebBrowser2; // IWebBrowser2ポインタm_pWebBrowser2 // publicメンバ public: // publicメンバ関数 // コンストラクタ・デストラクタ CWebBrowserHost(); // コンストラクタCWebBrowserHost virtual ~CWebBrowserHost(); // デストラクタ~CWebBrowserHost // staticメンバ関数 static BOOL RegisterClass(HINSTANCE hInstance); // ウィンドウクラス登録関数RegisterClass.(ウィンドウクラス名省略バージョン.) static BOOL RegisterClass(HINSTANCE hInstance, LPCTSTR lpctszClassName); // ウィンドウクラス登録関数RegisterClass // メンバ関数 virtual BOOL Create(LPCTSTR lpctszWindowName, DWORD dwStyle, int x, int y, int iWidth, int iHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance); // ウィンドウ作成関数Create.(ウィンドウクラス名省略バージョン.) virtual BOOL Create(LPCTSTR lpctszClassName, LPCTSTR lpctszWindowName, DWORD dwStyle, int x, int y, int iWidth, int iHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance); // ウィンドウ作成関数Create. virtual BOOL InitBrowser(); // ブラウザの初期化関数InitBrowser virtual BOOL Navigate(LPCTSTR lpctszUrl); // 指定のURLに遷移する関数Navigate virtual BOOL Destroy(); // ウィンドウ破棄関数Destroy virtual int OnCreate(HWND hwnd, LPCREATESTRUCT lpCreateStruct); // ウィンドウの作成が開始された時. virtual void OnDestroy(); // ウィンドウが破棄された時. virtual void OnSize(UINT nType, int cx, int cy); // ウィンドウのサイズが変更された時. // IUnknown STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // IOleClientSite STDMETHODIMP GetContainer(IOleContainer **ppContainer); STDMETHODIMP GetMoniker(DWORD dwAssign, DWORD dwWhichMoniker, IMoniker **ppmk); STDMETHODIMP OnShowWindow(BOOL fShow); STDMETHODIMP RequestNewObjectLayout(); STDMETHODIMP SaveObject(); STDMETHODIMP ShowObject(); // IOleWindow STDMETHODIMP ContextSensitiveHelp(BOOL fEnterMode); STDMETHODIMP GetWindow(HWND *phwnd); // IOleInPlaceSite STDMETHODIMP CanInPlaceActivate(); STDMETHODIMP DeactivateAndUndo(); STDMETHODIMP DiscardUndoState(); STDMETHODIMP GetWindowContext(IOleInPlaceFrame **ppFrame, IOleInPlaceUIWindow **ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo); STDMETHODIMP OnInPlaceActivate(); STDMETHODIMP OnInPlaceDeactivate(); STDMETHODIMP OnPosRectChange(LPCRECT lprcPosRect); STDMETHODIMP OnUIActivate(); STDMETHODIMP OnUIDeactivate(BOOL fUndoable); STDMETHODIMP Scroll(SIZE scrollExtant); }; #endif
[ "bg1bgst333@gmail.com" ]
bg1bgst333@gmail.com
e8cd38a0a4b5218b19070ffa70c6181967c83bc5
b8af5a6b2f36acf00b3f2ee75b69832c410927c3
/AirHawks/OptionsDialog.cpp
3a9d441261b6a5fbbad2454f92666871ac628366
[]
no_license
vish-chan/AirHawks-CPP
2a4e823f0419e486955803790587e84af56cb818
f81b6037ad21231d5edcbdac711a03ed85671fdf
refs/heads/master
2020-12-03T00:20:40.835182
2017-07-02T11:24:57
2017-07-02T11:24:57
96,018,671
1
0
null
null
null
null
UTF-8
C++
false
false
6,172
cpp
#include "OptionsDialog.h" #include "Res.h" #include "cGame.h" #include "SexyAppFramework/XAppBase.h" #include "SexyAppFramework/WidgetManager.h" #include "SexyAppFramework/Font.h" #include "SexyAppFramework/Image.h" #include "SexyAppFramework/Checkbox.h" #include "SexyAppFramework/Slider.h" using namespace FrameworkX; OptionsDialog::OptionsDialog(std::string theHeader, std::string theBody) :Dialog(IMAGE_DIALOG_BOX, IMAGE_DIALOG_BUTTON, OptionsDialog::DIALOG_ID, true, StringToSexyStringFast(theHeader), StringToSexyStringFast(theBody), _S("CLOSE"), Dialog::BUTTONS_FOOTER) { mWidgetFlagsMod.mAddFlags |= WIDGETFLAGS_MARK_DIRTY; mContentInsets = Insets(20,20,20,20); //set insets mSpaceAfterHeader = 30; //set space after header /* set fonts for various sections */ SetHeaderFont(FONT_DEFAULT); SetLinesFont(FONT_DEFAULT); SetButtonFont(FONT_DEFAULT); /* set colours for various sections */ SetColor(COLOR_HEADER, Color::Black); SetColor(COLOR_LINES, Color::Black); //create musicvolume slider mMusicVolumeSlider = new Slider(IMAGE_SLIDER_TRACK, IMAGE_SLIDER_THUMB, OptionsDialog::MUSIC_SLIDER_ID, this); mMusicVolumeSlider->SetValue(gSexyAppBase->GetMusicVolume()); AddWidget(mMusicVolumeSlider); //create sound effects volume slider mSfxVolumeSlider = new Slider(IMAGE_SLIDER_TRACK, IMAGE_SLIDER_THUMB, OptionsDialog::SFX_SLIDER_ID, this); mSfxVolumeSlider->SetValue(gSexyAppBase->GetSfxVolume()); AddWidget(mSfxVolumeSlider); //create checkboxes for 3d and fullscreen m3DCheckbox = new Checkbox(IMAGE_CHECKBOX, IMAGE_CHECKBOX, OptionsDialog::HARDWARE_CHECKBOX_ID, this); mFSCheckbox = new Checkbox(IMAGE_CHECKBOX, IMAGE_CHECKBOX, OptionsDialog::FS_CHECKBOX_ID, this); int checkWidth = IMAGE_CHECKBOX->GetWidth() / 2; int checkHeight = IMAGE_CHECKBOX->GetHeight(); //define unchecked and checked part of images m3DCheckbox->mUncheckedRect = Rect(0, 0, checkWidth,checkHeight ); m3DCheckbox->mCheckedRect = Rect(checkWidth, 0, checkWidth,checkHeight); mFSCheckbox->mUncheckedRect = Rect(0, 0, checkWidth, checkHeight); mFSCheckbox->mCheckedRect = Rect(checkWidth, 0, checkWidth, checkHeight); //set init values m3DCheckbox->mChecked = gSexyAppBase->Is3DAccelerated(); mFSCheckbox->mChecked = !gSexyAppBase->mIsWindowed; AddWidget(m3DCheckbox); AddWidget(mFSCheckbox); } OptionsDialog::~OptionsDialog() { RemoveAllWidgets(); delete mMusicVolumeSlider; delete mSfxVolumeSlider; delete m3DCheckbox; delete mFSCheckbox; } void OptionsDialog::Draw(Graphics* g) { Dialog::Draw(g); //Draws dialogbox g->SetFont(FONT_DEFAULT); g->SetColor(Color::Black); g->DrawString(_S("Music volume:"), mMusicVolumeSlider->mX, mMusicVolumeSlider->mY - mMusicVolumeSlider->mHeight); g->DrawString(_S("Sound volume:"), mSfxVolumeSlider->mX, mSfxVolumeSlider->mY - mSfxVolumeSlider->mHeight); g->DrawString(_S("3D Mode:"), m3DCheckbox->mX, m3DCheckbox->mY- m3DCheckbox->mHeight + 20); g->DrawString(_S("Full Screen:"), mFSCheckbox->mX, mFSCheckbox->mY - mFSCheckbox->mHeight + 20); } void OptionsDialog::Update() { Dialog::Update(); } void OptionsDialog::Resize(int theX, int theY, int theWidth, int theHeight) { Dialog::Resize(theX, theY, theWidth, theHeight); mMusicVolumeSlider->Resize(mContentInsets.mLeft, 140,mWidth - mContentInsets.mLeft - mContentInsets.mRight, IMAGE_SLIDER_THUMB->GetHeight()); mSfxVolumeSlider->Layout(LAY_SameLeft | LAY_Below | LAY_SameWidth | LAY_SameHeight, mMusicVolumeSlider, 0, 40, 0, 0); m3DCheckbox->Layout(LAY_SameLeft | LAY_Below, mSfxVolumeSlider, 0, 40, 0, 0); m3DCheckbox->Resize(m3DCheckbox->mX, m3DCheckbox->mY, IMAGE_CHECKBOX->mWidth / 2, IMAGE_CHECKBOX->mHeight); mFSCheckbox->Layout(LAY_SameTop | LAY_SameWidth | LAY_SameHeight, m3DCheckbox); mFSCheckbox->Resize(m3DCheckbox->mX + 200, mFSCheckbox->mY, mFSCheckbox->mWidth, mFSCheckbox->mHeight); } void OptionsDialog::SliderVal(int theId, double theVal) { if (theId == OptionsDialog::MUSIC_SLIDER_ID) { // Let's set the music volume to whatever the slider position is gSexyAppBase->SetMusicVolume(theVal); } else if (theId == OptionsDialog::SFX_SLIDER_ID) { // Set the sound value gSexyAppBase->SetSfxVolume(theVal); //play a ding sound when slider is released if (!mSfxVolumeSlider->mDragging) gSexyAppBase->PlaySample(SOUND_TIMER); } } void OptionsDialog::CheckboxChecked(int theId, bool checked) { // We'll wait until the dialog box is closed before actually applying any effects, // since it's rather jarring if as soon as a user clicks the 3d or fullscreen // toggle buttons to change right then and there. if (theId == m3DCheckbox->mId) { if (checked) { if (!gSexyAppBase->Is3DAccelerationSupported()) { m3DCheckbox->SetChecked(false); gSexyAppBase->DoDialog(OptionsDialog::MESSAGE_BOX_ID, true, _S("Not Supported"), _S("Hardware acceleration can not be enabled on this computer. \nYour\ video card does not meet the minimum requirements for this game."), _S("OK"), Dialog::BUTTONS_FOOTER); } else if(!gSexyAppBase->Is3DAccelerationRecommended()) { gSexyAppBase->DoDialog(OptionsDialog::MESSAGE_BOX_ID, true, _S("Warning"), _S("Your video card may not fully support this feature.\n\ If you experience slower performance, please disable Hardware Acceleration."), _S("OK"), Dialog::BUTTONS_FOOTER); } } } else if (theId == mFSCheckbox->mId) { if (gSexyAppBase->mForceFullscreen && !checked) { gSexyAppBase->DoDialog(OptionsDialog::MESSAGE_BOX_ID, true, _S("No Windowed Mode"), _S("Windowed mode is only available if your desktop is running in\n\ either 16 bit or 32 bit color mode, which it is not."), _S("OK"), Dialog::BUTTONS_FOOTER); // re-check the box to indicate that fullscreen is still the selected mode: mFSCheckbox->SetChecked(true); } } }
[ "vish-chan@users.noreply.github.com" ]
vish-chan@users.noreply.github.com
3b1d49ae5955e36ca82c8fb2014ee301730dd73e
b03bb28b95ab56afac6526c5f18c829763492bb6
/core/tensorShape.h
6e230e0187d18e38401e6cf73321eff5f2ad5525
[ "MIT" ]
permissive
adajed/DeepLearningCPP
06da3d679b08dc2cf3691a735d80fef9ce572b31
2fa4d57b75c145e918a8906b7404284628baa116
refs/heads/master
2021-06-07T00:59:45.055274
2021-05-23T16:02:42
2021-05-23T16:02:42
152,218,238
10
2
MIT
2021-05-23T16:02:42
2018-10-09T08:47:47
C++
UTF-8
C++
false
false
1,204
h
#ifndef GRAPHDL_CORE_TENSOR_SHAPE_H_ #define GRAPHDL_CORE_TENSOR_SHAPE_H_ #include "graphdl.h" #include <initializer_list> namespace graphdl { namespace core { class TensorShape { public: using iterator = std::vector<int>::iterator; TensorShape() = default; TensorShape(Shape shape); TensorShape(std::vector<int> vals); TensorShape(const TensorShape& other) = default; TensorShape(std::initializer_list<int> list); TensorShape& operator=(const TensorShape& other) = default; bool operator==(const TensorShape& other) const; bool operator!=(const TensorShape& other) const; int& operator[](std::size_t pos); const int& operator[](std::size_t pos) const; unsigned size() const; size_t getCount() const; operator Shape() const; operator std::vector<int>() const; iterator begin(); iterator end(); //! \fn subshape //! \brief Returns shape cut from this shape. //! Returned shape is [mDims[start], ..., mDims[start + size - 1]]. //! TensorShape subshape(int start, int size); private: std::vector<int> mDims; }; } // namespace core } // namespace graphdl #endif // GRAPHDL_CORE_TENSOR_SHAPE_H_
[ "adam.jedrych25@gmail.com" ]
adam.jedrych25@gmail.com
1263f0432a9f0629929fffcc0820be5d23e33fb2
f4fed014040a5ab4b8365e5c0735d65bddafa230
/SIDPlayPaul/mos6510.cpp
6c136aa6e3ffa78b8b032f8951b3fa1bc2af7681
[]
no_license
SparkyNZ/GeekTunes
f428b9a3ea490b80a15a336958220d1d0c18db41
7d8deec6b6cf29895d9eee6d0eb4e7f83303bb49
refs/heads/master
2020-05-18T01:55:26.993415
2013-10-18T00:28:34
2013-10-18T00:28:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,587
cpp
/*************************************************************************** main.cpp - description ------------------- begin : Thu May 11 06:22:40 BST 2000 copyright : (C) 2000 by Simon White email : s_a_white@email.com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /*************************************************************************** * $Log: mos6510.cpp,v $ * Revision 1.2.2.1 2004/07/26 18:11:17 sid * synced with libsidplay2 from cvs and resid 0.16 * * Revision 1.13 2004/04/23 01:06:24 s_a_white * Display correct cycle instruction starts on via dbgClk. This is set at the * start of every instruction correctly allows for cycle stealing. * * Revision 1.12 2004/02/21 13:20:10 s_a_white * Zero debug cycle count so is from start of instruction rather than after * the last addressing mode cycle. * * Revision 1.11 2004/01/13 22:36:07 s_a_white * Converted some missed printfs to fprintfs * * Revision 1.10 2003/10/28 00:22:52 s_a_white * getTime now returns a time with respect to the clocks desired phase. * * Revision 1.9 2003/10/16 07:46:05 s_a_white * Allow redirection of debug information of file. * * Revision 1.8 2001/08/05 15:46:38 s_a_white * No longer need to check on which cycle to print debug information. * * Revision 1.7 2001/07/14 13:04:34 s_a_white * Accumulator is now unsigned, which improves code readability. * * Revision 1.6 2001/03/09 22:27:46 s_a_white * Speed optimisation update. * * Revision 1.5 2001/02/13 23:01:10 s_a_white * envReadMemDataByte now used for debugging. * * Revision 1.4 2000/12/11 19:03:16 s_a_white * AC99 Update. * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include "sidtypes.h" #include "sidendian.h" #include "sidenv.h" #include "conf6510.h" #include "opcodes.h" #ifdef HAVE_EXCEPTIONS # include <new> #endif #ifdef MOS6510_STATE_6510 # include "state6510.h" # include "state6510.cpp" #else #include "mos6510.h" // Check to see what type of emulation is required #ifdef MOS6510_CYCLE_BASED # include "mos6510c.i" # ifdef MOS6510_SIDPLAY // Compile in sidplay code # include "sid6510c.i" # endif // MOS6510_SIDPLAY #else // Line based emulation code has not been provided #endif // MOS6510_CYCLE_BASED void MOS6510::DumpState (void) { uint8_t opcode, data; uint_least16_t operand, address; fprintf(m_fdbg, " PC I A X Y SP DR PR NV-BDIZC Instruction (%u)\n", m_dbgClk); fprintf(m_fdbg, "%04x ", instrStartPC); fprintf(m_fdbg, "%u ", interrupts.irqs); fprintf(m_fdbg, "%02x ", Register_Accumulator); fprintf(m_fdbg, "%02x ", Register_X); fprintf(m_fdbg, "%02x ", Register_Y); fprintf(m_fdbg, "01%02x ", endian_16lo8 (Register_StackPointer)); fprintf(m_fdbg, "%02x ", envReadMemDataByte (0)); fprintf(m_fdbg, "%02x ", envReadMemDataByte (1)); if (getFlagN()) fprintf(m_fdbg, "1"); else fprintf(m_fdbg, "0"); if (getFlagV()) fprintf(m_fdbg, "1"); else fprintf(m_fdbg, "0"); if (Register_Status & (1 << SR_NOTUSED)) fprintf(m_fdbg, "1"); else fprintf(m_fdbg, "0"); if (Register_Status & (1 << SR_BREAK)) fprintf(m_fdbg, "1"); else fprintf(m_fdbg, "0"); if (getFlagD()) fprintf(m_fdbg, "1"); else fprintf(m_fdbg, "0"); if (getFlagI()) fprintf(m_fdbg, "1"); else fprintf(m_fdbg, "0"); if (getFlagZ()) fprintf(m_fdbg, "1"); else fprintf(m_fdbg, "0"); if (getFlagC()) fprintf(m_fdbg, "1"); else fprintf(m_fdbg, "0"); opcode = instrOpcode; operand = Instr_Operand; data = Cycle_Data; switch (opcode) { case BCCr: case BCSr: case BEQr: case BMIr: case BNEr: case BPLr: case BVCr: case BVSr: address = (uint_least16_t) (Register_ProgramCounter + (int8_t) operand); break; default: address = Cycle_EffectiveAddress; break; } fprintf(m_fdbg, " %02x ", opcode); switch(opcode) { //Accumulator or Implied addressing case ASLn: case LSRn: case ROLn: case RORn: fprintf(m_fdbg, " "); break; //Zero Page Addressing Mode Handler case ADCz: case ANDz: case ASLz: case BITz: case CMPz: case CPXz: case CPYz: case DCPz: case DECz: case EORz: case INCz: case ISBz: case LAXz: case LDAz: case LDXz: case LDYz: case LSRz: case NOPz_: case ORAz: case ROLz: case RORz: case SAXz: case SBCz: case SREz: case STAz: case STXz: case STYz: case SLOz: case RLAz: case RRAz: //ASOz AXSz DCMz INSz LSEz - Optional Opcode Names fprintf(m_fdbg, "%02x ", (uint8_t) operand); break; //Zero Page with X Offset Addressing Mode Handler case ADCzx: case ANDzx: case ASLzx: case CMPzx: case DCPzx: case DECzx: case EORzx: case INCzx: case ISBzx: case LDAzx: case LDYzx: case LSRzx: case NOPzx_: case ORAzx: case RLAzx: case ROLzx: case RORzx: case RRAzx: case SBCzx: case SLOzx: case SREzx: case STAzx: case STYzx: //ASOzx DCMzx INSzx LSEzx - Optional Opcode Names fprintf(m_fdbg, "%02x ", (uint8_t) operand); break; //Zero Page with Y Offset Addressing Mode Handler case LDXzy: case STXzy: case SAXzy: case LAXzy: //AXSzx - Optional Opcode Names fprintf(m_fdbg, "%02x ", endian_16lo8 (operand)); break; //Absolute Addressing Mode Handler case ADCa: case ANDa: case ASLa: case BITa: case CMPa: case CPXa: case CPYa: case DCPa: case DECa: case EORa: case INCa: case ISBa: case JMPw: case JSRw: case LAXa: case LDAa: case LDXa: case LDYa: case LSRa: case NOPa: case ORAa: case ROLa: case RORa: case SAXa: case SBCa: case SLOa: case SREa: case STAa: case STXa: case STYa: case RLAa: case RRAa: //ASOa AXSa DCMa INSa LSEa - Optional Opcode Names fprintf(m_fdbg, "%02x %02x ", endian_16lo8 (operand), endian_16hi8 (operand)); break; //Absolute With X Offset Addresing Mode Handler case ADCax: case ANDax: case ASLax: case CMPax: case DCPax: case DECax: case EORax: case INCax: case ISBax: case LDAax: case LDYax: case LSRax: case NOPax_: case ORAax: case RLAax: case ROLax: case RORax: case RRAax: case SBCax: case SHYax: case SLOax: case SREax: case STAax: //ASOax DCMax INSax LSEax SAYax - Optional Opcode Names fprintf(m_fdbg, "%02x %02x ", endian_16lo8 (operand), endian_16hi8 (operand)); break; //Absolute With Y Offset Addresing Mode Handler case ADCay: case ANDay: case CMPay: case DCPay: case EORay: case ISBay: case LASay: case LAXay: case LDAay: case LDXay: case ORAay: case RLAay: case RRAay: case SBCay: case SHAay: case SHSay: case SHXay: case SLOay: case SREay: case STAay: //ASOay AXAay DCMay INSax LSEay TASay XASay - Optional Opcode Names fprintf(m_fdbg, "%02x %02x ", endian_16lo8 (operand), endian_16hi8 (operand)); break; //Immediate and Relative Addressing Mode Handler case ADCb: case ANDb: case ANCb_: case ANEb: case ASRb: case ARRb: case CMPb: case CPXb: case CPYb: case EORb: case LDAb: case LDXb: case LDYb: case LXAb: case NOPb_: case ORAb: case SBCb_: case SBXb: //OALb ALRb XAAb - Optional Opcode Names fprintf(m_fdbg, "%02x ", endian_16lo8 (operand)); break; case BCCr: case BCSr: case BEQr: case BMIr: case BNEr: case BPLr: case BVCr: case BVSr: fprintf(m_fdbg, "%02x ", endian_16lo8 (operand)); break; //Indirect Addressing Mode Handler case JMPi: fprintf(m_fdbg, "%02x %02x ", endian_16lo8 (operand), endian_16hi8 (operand)); break; //Indexed with X Preinc Addressing Mode Handler case ADCix: case ANDix: case CMPix: case DCPix: case EORix: case ISBix: case LAXix: case LDAix: case ORAix: case SAXix: case SBCix: case SLOix: case SREix: case STAix: case RLAix: case RRAix: //ASOix AXSix DCMix INSix LSEix - Optional Opcode Names fprintf(m_fdbg, "%02x ", endian_16lo8 (operand)); break; //Indexed with Y Postinc Addressing Mode Handler case ADCiy: case ANDiy: case CMPiy: case DCPiy: case EORiy: case ISBiy: case LAXiy: case LDAiy: case ORAiy: case RLAiy: case RRAiy: case SBCiy: case SHAiy: case SLOiy: case SREiy: case STAiy: //AXAiy ASOiy LSEiy DCMiy INSiy - Optional Opcode Names fprintf(m_fdbg, "%02x ", endian_16lo8 (operand)); break; default: fprintf(m_fdbg, " "); break; } switch(opcode) { case ADCb: case ADCz: case ADCzx: case ADCa: case ADCax: case ADCay: case ADCix: case ADCiy: fprintf(m_fdbg, " ADC"); break; case ANCb_: fprintf(m_fdbg, "*ANC"); break; case ANDb: case ANDz: case ANDzx: case ANDa: case ANDax: case ANDay: case ANDix: case ANDiy: fprintf(m_fdbg, " AND"); break; case ANEb: //Also known as XAA fprintf(m_fdbg, "*ANE"); break; case ARRb: fprintf(m_fdbg, "*ARR"); break; case ASLn: case ASLz: case ASLzx: case ASLa: case ASLax: fprintf(m_fdbg, " ASL"); break; case ASRb: //Also known as ALR fprintf(m_fdbg, "*ASR"); break; case BCCr: fprintf(m_fdbg, " BCC"); break; case BCSr: fprintf(m_fdbg, " BCS"); break; case BEQr: fprintf(m_fdbg, " BEQ"); break; case BITz: case BITa: fprintf(m_fdbg, " BIT"); break; case BMIr: fprintf(m_fdbg, " BMI"); break; case BNEr: fprintf(m_fdbg, " BNE"); break; case BPLr: fprintf(m_fdbg, " BPL"); break; case BRKn: fprintf(m_fdbg, " BRK"); break; case BVCr: fprintf(m_fdbg, " BVC"); break; case BVSr: fprintf(m_fdbg, " BVS"); break; case CLCn: fprintf(m_fdbg, " CLC"); break; case CLDn: fprintf(m_fdbg, " CLD"); break; case CLIn: fprintf(m_fdbg, " CLI"); break; case CLVn: fprintf(m_fdbg, " CLV"); break; case CMPb: case CMPz: case CMPzx: case CMPa: case CMPax: case CMPay: case CMPix: case CMPiy: fprintf(m_fdbg, " CMP"); break; case CPXb: case CPXz: case CPXa: fprintf(m_fdbg, " CPX"); break; case CPYb: case CPYz: case CPYa: fprintf(m_fdbg, " CPY"); break; case DCPz: case DCPzx: case DCPa: case DCPax: case DCPay: case DCPix: case DCPiy: //Also known as DCM fprintf(m_fdbg, "*DCP"); break; case DECz: case DECzx: case DECa: case DECax: fprintf(m_fdbg, " DEC"); break; case DEXn: fprintf(m_fdbg, " DEX"); break; case DEYn: fprintf(m_fdbg, " DEY"); break; case EORb: case EORz: case EORzx: case EORa: case EORax: case EORay: case EORix: case EORiy: fprintf(m_fdbg, " EOR"); break; case INCz: case INCzx: case INCa: case INCax: fprintf(m_fdbg, " INC"); break; case INXn: fprintf(m_fdbg, " INX"); break; case INYn: fprintf(m_fdbg, " INY"); break; case ISBz: case ISBzx: case ISBa: case ISBax: case ISBay: case ISBix: case ISBiy: //Also known as INS fprintf(m_fdbg, "*ISB"); break; case JMPw: case JMPi: fprintf(m_fdbg, " JMP"); break; case JSRw: fprintf(m_fdbg, " JSR"); break; case LASay: fprintf(m_fdbg, "*LAS"); break; case LAXz: case LAXzy: case LAXa: case LAXay: case LAXix: case LAXiy: fprintf(m_fdbg, "*LAX"); break; case LDAb: case LDAz: case LDAzx: case LDAa: case LDAax: case LDAay: case LDAix: case LDAiy: fprintf(m_fdbg, " LDA"); break; case LDXb: case LDXz: case LDXzy: case LDXa: case LDXay: fprintf(m_fdbg, " LDX"); break; case LDYb: case LDYz: case LDYzx: case LDYa: case LDYax: fprintf(m_fdbg, " LDY"); break; case LSRz: case LSRzx: case LSRa: case LSRax: case LSRn: fprintf(m_fdbg, " LSR"); break; case NOPn_: case NOPb_: case NOPz_: case NOPzx_: case NOPa: case NOPax_: if(opcode != NOPn) fprintf(m_fdbg, "*"); else fprintf(m_fdbg, " "); fprintf(m_fdbg, "NOP"); break; case LXAb: //Also known as OAL fprintf(m_fdbg, "*LXA"); break; case ORAb: case ORAz: case ORAzx: case ORAa: case ORAax: case ORAay: case ORAix: case ORAiy: fprintf(m_fdbg, " ORA"); break; case PHAn: fprintf(m_fdbg, " PHA"); break; case PHPn: fprintf(m_fdbg, " PHP"); break; case PLAn: fprintf(m_fdbg, " PLA"); break; case PLPn: fprintf(m_fdbg, " PLP"); break; case RLAz: case RLAzx: case RLAix: case RLAa: case RLAax: case RLAay: case RLAiy: fprintf(m_fdbg, "*RLA"); break; case ROLz: case ROLzx: case ROLa: case ROLax: case ROLn: fprintf(m_fdbg, " ROL"); break; case RORz: case RORzx: case RORa: case RORax: case RORn: fprintf(m_fdbg, " ROR"); break; case RRAa: case RRAax: case RRAay: case RRAz: case RRAzx: case RRAix: case RRAiy: fprintf(m_fdbg, "*RRA"); break; case RTIn: fprintf(m_fdbg, " RTI"); break; case RTSn: fprintf(m_fdbg, " RTS"); break; case SAXz: case SAXzy: case SAXa: case SAXix: //Also known as AXS fprintf(m_fdbg, "*SAX"); break; case SBCb_: if(opcode != SBCb) fprintf(m_fdbg, "*"); else fprintf(m_fdbg, " "); fprintf(m_fdbg, "SBC"); break; case SBCz: case SBCzx: case SBCa: case SBCax: case SBCay: case SBCix: case SBCiy: fprintf(m_fdbg, " SBC"); break; case SBXb: fprintf(m_fdbg, "*SBX"); break; case SECn: fprintf(m_fdbg, " SEC"); break; case SEDn: fprintf(m_fdbg, " SED"); break; case SEIn: fprintf(m_fdbg, " SEI"); break; case SHAay: case SHAiy: //Also known as AXA fprintf(m_fdbg, "*SHA"); break; case SHSay: //Also known as TAS fprintf(m_fdbg, "*SHS"); break; case SHXay: //Also known as XAS fprintf(m_fdbg, "*SHX"); break; case SHYax: //Also known as SAY fprintf(m_fdbg, "*SHY"); break; case SLOz: case SLOzx: case SLOa: case SLOax: case SLOay: case SLOix: case SLOiy: //Also known as ASO fprintf(m_fdbg, "*SLO"); break; case SREz: case SREzx: case SREa: case SREax: case SREay: case SREix: case SREiy: //Also known as LSE fprintf(m_fdbg, "*SRE"); break; case STAz: case STAzx: case STAa: case STAax: case STAay: case STAix: case STAiy: fprintf(m_fdbg, " STA"); break; case STXz: case STXzy: case STXa: fprintf(m_fdbg, " STX"); break; case STYz: case STYzx: case STYa: fprintf(m_fdbg, " STY"); break; case TAXn: fprintf(m_fdbg, " TAX"); break; case TAYn: fprintf(m_fdbg, " TAY"); break; case TSXn: fprintf(m_fdbg, " TSX"); break; case TXAn: fprintf(m_fdbg, " TXA"); break; case TXSn: fprintf(m_fdbg, " TXS"); break; case TYAn: fprintf(m_fdbg, " TYA"); break; default: fprintf(m_fdbg, "*HLT"); break; } switch(opcode) { //Accumulator or Implied addressing case ASLn: case LSRn: case ROLn: case RORn: fprintf(m_fdbg, "n A"); break; //Zero Page Addressing Mode Handler case ADCz: case ANDz: case ASLz: case BITz: case CMPz: case CPXz: case CPYz: case DCPz: case DECz: case EORz: case INCz: case ISBz: case LAXz: case LDAz: case LDXz: case LDYz: case LSRz: case ORAz: case ROLz: case RORz: case SBCz: case SREz: case SLOz: case RLAz: case RRAz: //ASOz AXSz DCMz INSz LSEz - Optional Opcode Names fprintf(m_fdbg, "z %02x {%02x}", (uint8_t) operand, data); break; case SAXz: case STAz: case STXz: case STYz: #ifdef MOS6510_DEBUG case NOPz_: #endif fprintf(m_fdbg, "z %02x", endian_16lo8 (operand)); break; //Zero Page with X Offset Addressing Mode Handler case ADCzx: case ANDzx: case ASLzx: case CMPzx: case DCPzx: case DECzx: case EORzx: case INCzx: case ISBzx: case LDAzx: case LDYzx: case LSRzx: case ORAzx: case RLAzx: case ROLzx: case RORzx: case RRAzx: case SBCzx: case SLOzx: case SREzx: //ASOzx DCMzx INSzx LSEzx - Optional Opcode Names fprintf(m_fdbg, "zx %02x,X", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]{%02x}", address, data); break; case STAzx: case STYzx: #ifdef MOS6510_DEBUG case NOPzx_: #endif fprintf(m_fdbg, "zx %02x,X", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]", address); break; //Zero Page with Y Offset Addressing Mode Handler case LAXzy: case LDXzy: //AXSzx - Optional Opcode Names fprintf(m_fdbg, "zy %02x,Y", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]{%02x}", address, data); break; case STXzy: case SAXzy: fprintf(m_fdbg, "zy %02x,Y", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]", address); break; //Absolute Addressing Mode Handler case ADCa: case ANDa: case ASLa: case BITa: case CMPa: case CPXa: case CPYa: case DCPa: case DECa: case EORa: case INCa: case ISBa: case LAXa: case LDAa: case LDXa: case LDYa: case LSRa: case ORAa: case ROLa: case RORa: case SBCa: case SLOa: case SREa: case RLAa: case RRAa: //ASOa AXSa DCMa INSa LSEa - Optional Opcode Names fprintf(m_fdbg, "a %04x {%02x}", operand, data); break; case SAXa: case STAa: case STXa: case STYa: #ifdef MOS6510_DEBUG case NOPa: #endif fprintf(m_fdbg, "a %04x", operand); break; case JMPw: case JSRw: fprintf(m_fdbg, "w %04x", operand); break; //Absolute With X Offset Addresing Mode Handler case ADCax: case ANDax: case ASLax: case CMPax: case DCPax: case DECax: case EORax: case INCax: case ISBax: case LDAax: case LDYax: case LSRax: case ORAax: case RLAax: case ROLax: case RORax: case RRAax: case SBCax: case SLOax: case SREax: //ASOax DCMax INSax LSEax SAYax - Optional Opcode Names fprintf(m_fdbg, "ax %04x,X", operand); fprintf(m_fdbg, " [%04x]{%02x}", address, data); break; case SHYax: case STAax: #ifdef MOS6510_DEBUG case NOPax_: #endif fprintf(m_fdbg, "ax %04x,X", operand); fprintf(m_fdbg, " [%04x]", address); break; //Absolute With Y Offset Addresing Mode Handler case ADCay: case ANDay: case CMPay: case DCPay: case EORay: case ISBay: case LASay: case LAXay: case LDAay: case LDXay: case ORAay: case RLAay: case RRAay: case SBCay: case SHSay: case SLOay: case SREay: //ASOay AXAay DCMay INSax LSEay TASay XASay - Optional Opcode Names fprintf(m_fdbg, "ay %04x,Y", operand); fprintf(m_fdbg, " [%04x]{%02x}", address, data); break; case SHAay: case SHXay: case STAay: fprintf(m_fdbg, "ay %04x,Y", operand); fprintf(m_fdbg, " [%04x]", address); break; //Immediate Addressing Mode Handler case ADCb: case ANDb: case ANCb_: case ANEb: case ASRb: case ARRb: case CMPb: case CPXb: case CPYb: case EORb: case LDAb: case LDXb: case LDYb: case LXAb: case ORAb: case SBCb_: case SBXb: //OALb ALRb XAAb - Optional Opcode Names #ifdef MOS6510_DEBUG case NOPb_: #endif fprintf(m_fdbg, "b #%02x", endian_16lo8 (operand)); break; //Relative Addressing Mode Handler case BCCr: case BCSr: case BEQr: case BMIr: case BNEr: case BPLr: case BVCr: case BVSr: fprintf(m_fdbg, "r #%02x", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]", address); break; //Indirect Addressing Mode Handler case JMPi: fprintf(m_fdbg, "i (%04x)", operand); fprintf(m_fdbg, " [%04x]", address); break; //Indexed with X Preinc Addressing Mode Handler case ADCix: case ANDix: case CMPix: case DCPix: case EORix: case ISBix: case LAXix: case LDAix: case ORAix: case SBCix: case SLOix: case SREix: case RLAix: case RRAix: //ASOix AXSix DCMix INSix LSEix - Optional Opcode Names fprintf(m_fdbg, "ix (%02x,X)", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]{%02x}", address, data); break; case SAXix: case STAix: fprintf(m_fdbg, "ix (%02x,X)", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]", address); break; //Indexed with Y Postinc Addressing Mode Handler case ADCiy: case ANDiy: case CMPiy: case DCPiy: case EORiy: case ISBiy: case LAXiy: case LDAiy: case ORAiy: case RLAiy: case RRAiy: case SBCiy: case SLOiy: case SREiy: //AXAiy ASOiy LSEiy DCMiy INSiy - Optional Opcode Names fprintf(m_fdbg, "iy (%02x),Y", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]{%02x}", address, data); break; case SHAiy: case STAiy: fprintf(m_fdbg, "iy (%02x),Y", endian_16lo8 (operand)); fprintf(m_fdbg, " [%04x]", address); break; default: break; } fprintf (m_fdbg, "\n\n"); fflush (m_fdbg); } #endif // MOS6510_STATE_6510
[ "sparkynz74@gmail.com" ]
sparkynz74@gmail.com
4fdf175774c5569091ba3073ebaa7651b867c985
92e979498ec13e4ef1f9ff140e12865b5082c1dd
/SDK/Rejoin_structs.h
49ea53fe1e37a7713e345316c4dd2561fa2c5243
[]
no_license
ALEHACKsp/BlazingSails-SDK
ac1d98ff67983b9d8e9c527815f17233d045d44d
900cbb934dc85f7325f1fc8845b90def2298dc2d
refs/heads/master
2022-04-08T21:55:32.767942
2020-03-11T11:37:42
2020-03-11T11:37:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
638
h
#pragma once // Name: BlazingSails, Version: 1.481.81 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Enums //--------------------------------------------------------------------------- // Enum Rejoin.ERejoinStatus enum class ERejoinStatus : uint8_t { ERejoinStatus__NoMatchToRejoin = 0, ERejoinStatus__RejoinAvailable = 1, ERejoinStatus__UpdatingStatus = 2, ERejoinStatus__NeedsRecheck = 3, ERejoinStatus__NoMatchToRejoin_MatchEnded = 4, ERejoinStatus__ERejoinStatus_MAX = 5 }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
b427c85db71fb496553640ea575776ec0d525378
82ffbe324536805b25cf01bb068d93fe0f6f26ab
/leetcode C++/number_cal/Add_Two_Number/Add_Two_Number_First.cpp
8b022ef3e29f830e015e393b9c218a3abdb754c8
[]
no_license
caixiaomo/leetcode-ans1
b4e0fab2da42036f8409b9adb6ccf33e22bbac11
d6ba2b76a3cf469abb97b170caa2f99c1564306f
refs/heads/master
2020-03-31T01:23:08.989746
2015-03-02T14:31:13
2015-03-02T14:31:13
31,544,222
1
1
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { // Note: The Solution object is instantiated only once and is reused by each test case. if((!l1)&&(!l2)) return NULL; ListNode* n1 = l1; ListNode* n2 = l2; int addOn = 0; int v1 = 0; int v2 = 0; int value = 0; ListNode* next; ListNode* head = new ListNode(0); next = head; while(n1||n2){ v1 = (n1)?(n1 -> val):0; v2 = (n2)?(n2 -> val):0; value = v1 + v2 + addOn; if(value > 9 ){ value = value - 10; addOn = 1; }else{ addOn = 0; } next -> val = value; if(n1||n2){ next -> next = new ListNode(0); next = next -> next; } n1 = (n1)?(n1 -> next):NULL; n2 = (n2)?(n2 -> next):NULL; } return head; } };
[ "caixiaomo1993@gmail.com" ]
caixiaomo1993@gmail.com
190b09f13c4d0acf73f05a4762aaf8bca92488d1
ed0cc12a537967664016c38a2ba9e6c64efff441
/src/util.h
70e1e7d2bacec58895a86f8db5d5451ac8aaf916
[ "MIT" ]
permissive
AzzureCore/Azzure
113462cbc4e17eb1ec548ac8577190067aaa37bc
2e0e094f3b6807cbdafe0dd6a5de21cf89be2ea3
refs/heads/master
2022-07-07T15:45:05.327901
2020-05-08T16:59:01
2020-05-08T16:59:01
262,760,734
0
0
null
2020-05-10T10:19:24
2020-05-10T10:19:24
null
UTF-8
C++
false
false
8,851
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 LightPayCoin developers // Copyright (c) 2018 The Azzure developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * Server/client environment: argument handling, config file parsing, * logging, thread wrappers */ #ifndef BITCOIN_UTIL_H #define BITCOIN_UTIL_H #if defined(HAVE_CONFIG_H) #include "config/Azzure-config.h" #endif #include "compat.h" #include "tinyformat.h" #include "utiltime.h" #include <exception> #include <map> #include <stdint.h> #include <string> #include <vector> #include <boost/filesystem/path.hpp> #include <boost/thread/exceptions.hpp> //Azzure only features extern bool fMasterNode; extern bool fLiteMode; extern bool fEnableSwiftTX; extern int nSwiftTXDepth; extern int nObfuscationRounds; extern int nAnonymizeAzzureAmount; extern int nLiquidityProvider; extern bool fEnableObfuscation; extern int64_t enforceMasternodePaymentsTime; extern std::string strMasterNodeAddr; extern int keysLoaded; extern bool fSucessfullyLoaded; extern std::vector<int64_t> obfuScationDenominations; extern std::string strBudgetMode; extern std::map<std::string, std::string> mapArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs; extern bool fDebug; extern bool fPrintToConsole; extern bool fPrintToDebugLog; extern bool fServer; extern std::string strMiscWarning; extern bool fLogTimestamps; extern bool fLogIPs; extern volatile bool fReopenDebugLog; void SetupEnvironment(); /** Return true if log accepts specified category */ bool LogAcceptCategory(const char* category); /** Send a string to the log output */ int LogPrintStr(const std::string& str); #define LogPrintf(...) LogPrint(NULL, __VA_ARGS__) /** * When we switch to C++11, this can be switched to variadic templates instead * of this macro-based construction (see tinyformat.h). */ #define MAKE_ERROR_AND_LOG_FUNC(n) \ /** Print to debug.log if -debug=category switch is given OR category is NULL. */ \ template <TINYFORMAT_ARGTYPES(n)> \ static inline int LogPrint(const char* category, const char* format, TINYFORMAT_VARARGS(n)) \ { \ if (!LogAcceptCategory(category)) return 0; \ return LogPrintStr(tfm::format(format, TINYFORMAT_PASSARGS(n))); \ } \ /** Log error and return false */ \ template <TINYFORMAT_ARGTYPES(n)> \ static inline bool error(const char* format, TINYFORMAT_VARARGS(n)) \ { \ LogPrintStr("ERROR: " + tfm::format(format, TINYFORMAT_PASSARGS(n)) + "\n"); \ return false; \ } TINYFORMAT_FOREACH_ARGNUM(MAKE_ERROR_AND_LOG_FUNC) /** * Zero-arg versions of logging and error, these are not covered by * TINYFORMAT_FOREACH_ARGNUM */ static inline int LogPrint(const char* category, const char* format) { if (!LogAcceptCategory(category)) return 0; return LogPrintStr(format); } static inline bool error(const char* format) { LogPrintStr(std::string("ERROR: ") + format + "\n"); return false; } void PrintExceptionContinue(std::exception* pex, const char* pszThread); void ParseParameters(int argc, const char* const argv[]); void FileCommit(FILE* fileout); bool TruncateFile(FILE* file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length); bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest); bool TryCreateDirectory(const boost::filesystem::path& p); boost::filesystem::path GetDefaultDataDir(); const boost::filesystem::path& GetDataDir(bool fNetSpecific = true); boost::filesystem::path GetConfigFile(); boost::filesystem::path GetMasternodeConfigFile(); #ifndef WIN32 boost::filesystem::path GetPidFile(); void CreatePidFile(const boost::filesystem::path& path, pid_t pid); #endif void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif boost::filesystem::path GetTempPath(); void ShrinkDebugFile(); void runCommand(std::string strCommand); inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64_t GetArg(const std::string& strArg, int64_t nDefault); /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault); /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); /** * Format a string to be used as group of options in help messages * * @param message Group name (e.g. "RPC server options:") * @return the formatted string */ std::string HelpMessageGroup(const std::string& message); /** * Format a string to be used as option description in help messages * * @param option Option message (e.g. "-rpcuser=<user>") * @param message Option description (e.g. "Username for JSON-RPC connections") * @return the formatted string */ std::string HelpMessageOpt(const std::string& option, const std::string& message); void SetThreadPriority(int nPriority); void RenameThread(const char* name); /** * Standard wrapper for do-something-forever thread functions. * "Forever" really means until the thread is interrupted. * Use it like: * new boost::thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 900000)); * or maybe: * boost::function<void()> f = boost::bind(&FunctionWithArg, argument); * threadGroup.create_thread(boost::bind(&LoopForever<boost::function<void()> >, "nothing", f, milliseconds)); */ template <typename Callable> void LoopForever(const char* name, Callable func, int64_t msecs) { std::string s = strprintf("Azzure-%s", name); RenameThread(s.c_str()); LogPrintf("%s thread start\n", name); try { while (1) { MilliSleep(msecs); func(); } } catch (boost::thread_interrupted) { LogPrintf("%s thread stop\n", name); throw; } catch (std::exception& e) { PrintExceptionContinue(&e, name); throw; } catch (...) { PrintExceptionContinue(NULL, name); throw; } } /** * .. and a wrapper that just calls func once */ template <typename Callable> void TraceThread(const char* name, Callable func) { std::string s = strprintf("Azzure-%s", name); RenameThread(s.c_str()); try { LogPrintf("%s thread start\n", name); func(); LogPrintf("%s thread exit\n", name); } catch (boost::thread_interrupted) { LogPrintf("%s thread interrupt\n", name); throw; } catch (std::exception& e) { PrintExceptionContinue(&e, name); throw; } catch (...) { PrintExceptionContinue(NULL, name); throw; } } #endif // BITCOIN_UTIL_H
[ "adeeshaa@adastproject.com" ]
adeeshaa@adastproject.com
8aed0e3036a6c4d9f935c9f1b46ded80f6f81d93
8ae7a23f05805fd71d4be13686cf35d8994762ed
/mame150/src/mess/machine/abc99.h
9b85c55a54c7759c812d8c2302317a90932b315e
[]
no_license
cyberkni/276in1JAMMA
fb06ccc6656fb4346808a24beed8977996da91b2
d1a68172d4f3490cf7f6e7db25d5dfd4cde3bb22
refs/heads/master
2021-01-18T09:38:36.974037
2013-10-07T18:30:02
2013-10-07T18:30:02
13,152,960
1
0
null
null
null
null
UTF-8
C++
false
false
2,639
h
/********************************************************************** Luxor ABC-99 keyboard and mouse emulation Copyright MESS Team. Visit http://mamedev.org for licensing and usage restrictions. *********************************************************************/ #pragma once #ifndef __ABC99__ #define __ABC99__ #include "emu.h" #include "cpu/mcs48/mcs48.h" #include "machine/abckb.h" #include "sound/speaker.h" //************************************************************************** // TYPE DEFINITIONS //************************************************************************** // ======================> abc99_device class abc99_device : public device_t, public abc_keyboard_interface { public: // construction/destruction abc99_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock); // optional information overrides virtual const rom_entry *device_rom_region() const; virtual machine_config_constructor device_mconfig_additions() const; virtual ioport_constructor device_input_ports() const; // abc_keyboard_interface overrides virtual int rxd_r(); virtual void txd_w(int state); DECLARE_INPUT_CHANGED_MEMBER( keyboard_reset ); DECLARE_WRITE8_MEMBER( z2_led_w ); DECLARE_WRITE8_MEMBER( z2_p1_w ); DECLARE_READ8_MEMBER( z2_p2_r ); DECLARE_READ8_MEMBER( z2_t0_r ); DECLARE_READ8_MEMBER( z2_t1_r ); DECLARE_READ8_MEMBER( z5_p1_r ); DECLARE_WRITE8_MEMBER( z5_p2_w ); DECLARE_READ8_MEMBER( z5_t1_r ); protected: // device-level overrides virtual void device_start(); virtual void device_reset(); virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr); private: enum { TIMER_SERIAL, TIMER_MOUSE }; enum { LED_1 = 0, LED_2, LED_3, LED_4, LED_5, LED_6, LED_7, LED_8, LED_INS, LED_ALT, LED_CAPS_LOCK }; inline void serial_input(); inline void serial_clock(); inline void key_down(int state); inline void scan_mouse(); devcb_resolved_write_line m_out_clock_func; devcb_resolved_write_line m_out_keydown_func; emu_timer *m_serial_timer; emu_timer *m_mouse_timer; required_device<cpu_device> m_maincpu; required_device<cpu_device> m_mousecpu; required_device<speaker_sound_device> m_speaker; required_ioport m_z14; required_ioport m_mouseb; int m_si; int m_si_en; int m_so_z2; int m_so_z5; int m_keydown; int m_t1_z2; int m_t1_z5; int m_led_en; int m_reset; }; // device type definition extern const device_type ABC99; #endif
[ "dan@van.derveer.com" ]
dan@van.derveer.com
97bb5d2caa39ab60a0fc8e79fcb73845b4017682
86609148aee683f1a2f92f9ab5c073b4c29380e4
/utils/dnp3_src/cpp/libs/src/opendnp3/master/DisableUnsolicitedTask.cpp
f5cddd63ff004dd6feb99d11004ed0157f2e34cc
[ "Apache-2.0" ]
permissive
thiagoralves/OpenPLC_v3
16ba73585ab6b4aff7fb3e0f6388cf31f7aa2fce
cf139121bc15cb960a8fad62c02f34532b36a7c7
refs/heads/master
2023-08-07T06:55:19.533734
2023-07-19T15:33:35
2023-07-19T15:33:35
137,387,519
817
370
null
2023-09-14T03:09:01
2018-06-14T17:15:49
C++
UTF-8
C++
false
false
2,309
cpp
/* * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #include "DisableUnsolicitedTask.h" #include "opendnp3/app/APDUBuilders.h" #include "MasterTasks.h" using namespace openpal; namespace opendnp3 { DisableUnsolicitedTask::DisableUnsolicitedTask(IMasterApplication& application, bool enabled_, TimeDuration retryPeriod_, openpal::Logger logger) : IMasterTask(application, MonotonicTimestamp::Min(), logger, TaskConfig::Default()), enabled(enabled_), retryPeriod(retryPeriod_) { } bool DisableUnsolicitedTask::BuildRequest(APDURequest& request, uint8_t seq) { build::DisableUnsolicited(request, seq); return true; } IMasterTask::ResponseResult DisableUnsolicitedTask::ProcessResponse(const opendnp3::APDUResponseHeader& header, const openpal::RSlice& objects) { return ValidateNullResponse(header, objects) ? ResponseResult::OK_FINAL : ResponseResult::ERROR_BAD_RESPONSE; } IMasterTask::TaskState DisableUnsolicitedTask::OnTaskComplete(TaskCompletion result, openpal::MonotonicTimestamp now) { switch (result) { case(TaskCompletion::FAILURE_BAD_RESPONSE) : return TaskState::Disabled(); case(TaskCompletion::FAILURE_NO_COMMS) : return TaskState::Immediately(); case(TaskCompletion::FAILURE_RESPONSE_TIMEOUT) : return TaskState::Retry(now.Add(retryPeriod)); default: return TaskState::Infinite(); } } } //end ns
[ "thiagoralves@gmail.com" ]
thiagoralves@gmail.com
1bf02335e30258090acc5ac06ef9ec82ae24dfc7
5d6efcd77c8ac61e8ef50050e495a6e340f7180f
/src/lexical/lexicalanalyzer.h
83d9ff5fa44cc29f9cf9a5d8ee785458c5b6f637
[]
no_license
Youw/Compiler
1ba3d675e435bf2cc8abd093d7299a0d85d4a10a
b186cf788b30426acc7d551e2f25b716f079bbb3
refs/heads/master
2020-05-16T21:29:51.419984
2015-06-23T04:40:20
2015-06-23T04:40:20
33,451,123
0
1
null
2015-04-09T12:47:02
2015-04-05T18:47:32
C++
UTF-8
C++
false
false
1,637
h
#ifndef LEXICALANALYZER_H #define LEXICALANALYZER_H #include <deque> #include "config.h" #include "lexem.h" class LexicalException { string message; public: LexicalException(const string& s = STR("LexicalException")):message(STR("LexicalException: ")+s) { } virtual const string& what() const { return message; } }; class LexicalExceptionEndOfStream: public LexicalException { public: LexicalExceptionEndOfStream(): LexicalException(STR("Stream end reached.")) { } }; class LexicalExceptionLexemIndexOutOfRange: public LexicalException { public: LexicalExceptionLexemIndexOutOfRange(unsigned index=unsigned(-1)): LexicalException(index==unsigned(-1)?STR("Lexem index out of range."):STR("Lexem index \"")+to_string(index)+STR("\" out of range.")) { } }; class LexicalAnalyzer { istream& input; std::deque<LexemPtr> lexems; struct { int row, column; } current_read_pos = {1,0}, begin_read_pos; unsigned current_lexem_index = 0; public: LexicalAnalyzer(istream& input); LexemPtr nextLexem(); LexemPtr nextLexemSkipComment(); LexemPtr currentLexem(); unsigned currentLexemIndex(); void setCurrentLexemIndex(unsigned index); const decltype(current_read_pos)& currentReadPos(); private: character getChar(); int getRawChar(); int skipEOL(int &c); LexemPtr readDelimiter(character current_char); LexemPtr readSingleLineComment(); LexemPtr readMultiLineComment(); LexemPtr readQuotedIdentifier(); LexemPtr readNumber(character current_char); LexemPtr readStrLiteral(); LexemPtr readIdentifier(character current_char); }; #endif // LEXICALANALYZER_H
[ "ihor.youw@gmail.com" ]
ihor.youw@gmail.com
f4d43d447b357febea0baa5e4d64986b269a13af
4d9bbd510b0af8778daba54fe2b1809216463fa6
/build/Android/Debug/app/src/main/include/Fuse.Navigation.SwipeNavigate.h
a5a21e9c6cc2368ccf6e2789ff6326029965b215
[]
no_license
Koikka/mood_cal
c80666c4930bd8091e7fbe4869f5bad2f60953c1
9bf73aab2998aa7aa9e830aefb6dd52e25db710a
refs/heads/master
2021-06-23T20:24:14.150644
2020-09-04T09:25:54
2020-09-04T09:25:54
137,458,064
0
0
null
2020-12-13T05:23:20
2018-06-15T07:53:15
C++
UTF-8
C++
false
false
5,622
h
// This file was generated based on node_modules/@fuse-open/fuselibs/Source/build/Fuse.Navigation/1.12.0/SwipeNavigate.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Behavior.h> #include <Fuse.Binding.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.Input.IGesture.h> #include <Fuse.IProperties.h> #include <Fuse.ISourceLocation.h> #include <Fuse.Scripting.IScriptObject.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.Float2.h> namespace g{namespace Fuse{namespace Elements{struct Element;}}} namespace g{namespace Fuse{namespace Input{struct Gesture;}}} namespace g{namespace Fuse{namespace Input{struct GesturePriorityConfig;}}} namespace g{namespace Fuse{namespace Input{struct PointerEventArgs;}}} namespace g{namespace Fuse{namespace Input{struct PointerMovedArgs;}}} namespace g{namespace Fuse{namespace Input{struct PointerPressedArgs;}}} namespace g{namespace Fuse{namespace Input{struct PointerReleasedArgs;}}} namespace g{namespace Fuse{namespace Motion{namespace Simulation{struct PointerVelocity;}}}} namespace g{namespace Fuse{namespace Navigation{struct SwipeNavigate;}}} namespace g{namespace Fuse{namespace Navigation{struct UpdateSeekArgs;}}} namespace g{ namespace Fuse{ namespace Navigation{ // public sealed class SwipeNavigate // { struct SwipeNavigate_type : ::g::Fuse::Node_type { ::g::Fuse::Input::IGesture interface7; }; SwipeNavigate_type* SwipeNavigate_typeof(); void SwipeNavigate__ctor_3_fn(SwipeNavigate* __this); void SwipeNavigate__get_AllowedDirections_fn(SwipeNavigate* __this, int32_t* __retval); void SwipeNavigate__set_AllowedDirections_fn(SwipeNavigate* __this, int32_t* value); void SwipeNavigate__DetermineSnap_fn(SwipeNavigate* __this, int32_t* __retval); void SwipeNavigate__get_Direction_fn(SwipeNavigate* __this, ::g::Uno::Float2* __retval); void SwipeNavigate__get_Distance_fn(SwipeNavigate* __this, ::g::Uno::Float2* __retval); void SwipeNavigate__get_ElapsedTime_fn(SwipeNavigate* __this, double* __retval); void SwipeNavigate__get_ForwardDirection_fn(SwipeNavigate* __this, int32_t* __retval); void SwipeNavigate__set_ForwardDirection_fn(SwipeNavigate* __this, int32_t* value); void SwipeNavigate__FuseInputIGestureOnCaptureChanged_fn(SwipeNavigate* __this, ::g::Fuse::Input::PointerEventArgs* args, int32_t* how, int32_t* prev); void SwipeNavigate__FuseInputIGestureOnLostCapture_fn(SwipeNavigate* __this, bool* forced); void SwipeNavigate__FuseInputIGestureOnPointerMoved_fn(SwipeNavigate* __this, ::g::Fuse::Input::PointerMovedArgs* args, int32_t* __retval); void SwipeNavigate__FuseInputIGestureOnPointerPressed_fn(SwipeNavigate* __this, ::g::Fuse::Input::PointerPressedArgs* args, int32_t* __retval); void SwipeNavigate__FuseInputIGestureOnPointerReleased_fn(SwipeNavigate* __this, ::g::Fuse::Input::PointerReleasedArgs* args, int32_t* __retval); void SwipeNavigate__FuseInputIGestureget_Priority_fn(SwipeNavigate* __this, ::g::Fuse::Input::GesturePriorityConfig* __retval); void SwipeNavigate__GetNavigationArgs_fn(SwipeNavigate* __this, ::g::Fuse::Navigation::UpdateSeekArgs** __retval); void SwipeNavigate__Invert_fn(SwipeNavigate* __this, int32_t* sd, int32_t* __retval); void SwipeNavigate__get_IsHorizontal_fn(SwipeNavigate* __this, bool* __retval); void SwipeNavigate__get_Navigation_fn(SwipeNavigate* __this, uObject** __retval); void SwipeNavigate__New2_fn(SwipeNavigate** __retval); void SwipeNavigate__OnRooted_fn(SwipeNavigate* __this); void SwipeNavigate__OnUnrooted_fn(SwipeNavigate* __this); void SwipeNavigate__get_ProgressVelocity_fn(SwipeNavigate* __this, float* __retval); void SwipeNavigate__get_Scale_fn(SwipeNavigate* __this, ::g::Uno::Float2* __retval); void SwipeNavigate__get_SwipeDirection_fn(SwipeNavigate* __this, int32_t* __retval); void SwipeNavigate__set_SwipeDirection_fn(SwipeNavigate* __this, int32_t* value); void SwipeNavigate__get_VelocityThreshold_fn(SwipeNavigate* __this, float* __retval); void SwipeNavigate__set_VelocityThreshold_fn(SwipeNavigate* __this, float* value); struct SwipeNavigate : ::g::Fuse::Behavior { uStrong< ::g::Fuse::Motion::Simulation::PointerVelocity*> _velocity; uStrong<uObject*> _currentNavigation; uStrong< ::g::Fuse::Input::Gesture*> _gesture; int32_t _forwardDirection; uStrong< ::g::Fuse::Elements::Element*> _lengthNode; bool _hasMaxPages; float _maxPages; ::g::Uno::Float2 _startCoord; ::g::Uno::Float2 _currentCoord; float _prevDistance; double _startTime; bool _startedSeek; int32_t _swipeAllow; static float elasticDecay_; static float& elasticDecay() { return SwipeNavigate_typeof()->Init(), elasticDecay_; } static float elasticScale_; static float& elasticScale() { return SwipeNavigate_typeof()->Init(), elasticScale_; } float _VelocityThreshold; void ctor_3(); int32_t AllowedDirections(); void AllowedDirections(int32_t value); int32_t DetermineSnap(); ::g::Uno::Float2 Direction(); ::g::Uno::Float2 Distance(); double ElapsedTime(); int32_t ForwardDirection(); void ForwardDirection(int32_t value); ::g::Fuse::Navigation::UpdateSeekArgs* GetNavigationArgs(); int32_t Invert(int32_t sd); bool IsHorizontal(); uObject* Navigation(); float ProgressVelocity(); ::g::Uno::Float2 Scale(); int32_t SwipeDirection(); void SwipeDirection(int32_t value); float VelocityThreshold(); void VelocityThreshold(float value); static SwipeNavigate* New2(); }; // } }}} // ::g::Fuse::Navigation
[ "antti.koivisto@samk.fi" ]
antti.koivisto@samk.fi
d0b524bb0bc805e3bb2210535c55a8b16ff50353
674510d1598b29f01d7c82e24ebb21c3468147e2
/src/chatbot.cpp
3939973e252ddb0b8286c6bac4f3656880eb0970
[]
no_license
kforkaran/Memory-Management-Chatbot
7b8297f06058d9de6f5165571212f2e63c3aade4
d8dd8a6ad38b269df3ec70ff203b81320eb88884
refs/heads/master
2022-11-09T00:37:17.233532
2020-06-27T17:39:26
2020-06-27T17:39:26
265,440,525
0
0
null
null
null
null
UTF-8
C++
false
false
5,067
cpp
#include "chatbot.h" #include <algorithm> #include <ctime> #include <iostream> #include <random> #include "chatlogic.h" #include "graphedge.h" #include "graphnode.h" // constructor WITHOUT memory allocation ChatBot::ChatBot() { // invalidate data handles _image = nullptr; _chatLogic = nullptr; _rootNode = nullptr; } // constructor WITH memory allocation ChatBot::ChatBot(std::string filename) { std::cout << "ChatBot Constructor" << std::endl; // invalidate data handles _chatLogic = nullptr; _rootNode = nullptr; // load image into heap memory _image = new wxBitmap(filename, wxBITMAP_TYPE_PNG); } ChatBot::~ChatBot() { std::cout << "ChatBot Destructor" << std::endl; // deallocate heap memory // wxWidgets used NULL and not nullptr if (_image != NULL) { delete _image; _image = NULL; } } ChatBot::ChatBot(const ChatBot &source) { std::cout << "ChatBot Copy Constructor" << std::endl; _image = new wxBitmap(*source._image); _currentNode = source._currentNode; _rootNode = source._rootNode; _chatLogic = source._chatLogic; } ChatBot &ChatBot::operator=(const ChatBot &source) { std::cout << "ChatBot Copy Assignment Operator" << std::endl; if (&source == this) return *this; _image = new wxBitmap(*source._image); _currentNode = source._currentNode; _rootNode = source._rootNode; _chatLogic = source._chatLogic; return *this; } ChatBot::ChatBot(ChatBot &&source) noexcept { std::cout << "ChatBot Move Constructor" << std::endl; _image = source._image; _currentNode = source._currentNode; _rootNode = source._rootNode; _chatLogic = source._chatLogic; source._image = NULL; source._currentNode = nullptr; source._rootNode = nullptr; source._chatLogic = nullptr; } ChatBot &ChatBot::operator=(ChatBot &&source) noexcept { std::cout << "ChatBot Move Assignment Operator" << std::endl; if (&source == this) return *this; _image = source._image; _currentNode = source._currentNode; _rootNode = source._rootNode; _chatLogic = source._chatLogic; source._image = NULL; source._currentNode = nullptr; source._rootNode = nullptr; source._chatLogic = nullptr; return *this; } void ChatBot::ReceiveMessageFromUser(std::string message) { // loop over all edges and keywords and compute Levenshtein distance to query typedef std::pair<GraphEdge *, int> EdgeDist; std::vector<EdgeDist> levDists; // format is <ptr,levDist> for (size_t i = 0; i < _currentNode->GetNumberOfChildEdges(); ++i) { GraphEdge *edge = _currentNode->GetChildEdgeAtIndex(i); for (auto keyword : edge->GetKeywords()) { EdgeDist ed{edge, ComputeLevenshteinDistance(keyword, message)}; levDists.push_back(ed); } } // select best fitting edge to proceed along GraphNode *newNode; if (levDists.size() > 0) { // sort in ascending order of Levenshtein distance (best fit is at the top) std::sort(levDists.begin(), levDists.end(), [](const EdgeDist &a, const EdgeDist &b) { return a.second < b.second; }); newNode = levDists.at(0).first->GetChildNode(); // after sorting the best edge is // at first position } else { // go back to root node newNode = _rootNode; } // tell current node to move chatbot to new node _currentNode->MoveChatbotToNewNode(newNode); } void ChatBot::SetCurrentNode(GraphNode *node) { // update pointer to current node _currentNode = node; // select a random node answer (if several answers should exist) std::vector<std::string> answers = _currentNode->GetAnswers(); std::mt19937 generator(int(std::time(0))); std::uniform_int_distribution<int> dis(0, answers.size() - 1); std::string answer = answers.at(dis(generator)); _chatLogic->SetChatbotHandle(this); // update ChatBot for ChatLogic // send selected node answer to user _chatLogic->SendMessageToUser(answer); } int ChatBot::ComputeLevenshteinDistance(std::string s1, std::string s2) { // convert both strings to upper-case before comparing std::transform(s1.begin(), s1.end(), s1.begin(), ::toupper); std::transform(s2.begin(), s2.end(), s2.begin(), ::toupper); // compute Levenshtein distance measure between both strings const size_t m(s1.size()); const size_t n(s2.size()); if (m == 0) return n; if (n == 0) return m; size_t *costs = new size_t[n + 1]; for (size_t k = 0; k <= n; k++) costs[k] = k; size_t i = 0; for (std::string::const_iterator it1 = s1.begin(); it1 != s1.end(); ++it1, ++i) { costs[0] = i + 1; size_t corner = i; size_t j = 0; for (std::string::const_iterator it2 = s2.begin(); it2 != s2.end(); ++it2, ++j) { size_t upper = costs[j + 1]; if (*it1 == *it2) { costs[j + 1] = corner; } else { size_t t(upper < corner ? upper : corner); costs[j + 1] = (costs[j] < t ? costs[j] : t) + 1; } corner = upper; } } int result = costs[n]; delete[] costs; return result; }
[ "karangupta199920@gmail.com" ]
karangupta199920@gmail.com
3ba37331e69c9c6fc60bf70c15406bc5933fe855
3b23020e27df245916ddf20bb7677deaf69bcb8b
/系统源码/服务器组件/登陆服务器/LogonServerDlg.cpp
5bcf93d296119d94eb5fd30a9edb2e3482b0a65f
[]
no_license
weimingtom/wh2008
dcd0de272b637383cc4077c7afd69f6dc2de2fa0
21fa8806f4bca3f690aec190a6e374ef308c7780
refs/heads/master
2021-01-22T00:13:48.289285
2014-10-23T15:04:45
2014-10-23T15:04:45
null
0
0
null
null
null
null
GB18030
C++
false
false
6,875
cpp
#include "Stdafx.h" #include "LogonServerDlg.h" #include "afxdialogex.h" ////////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CSystemOptionDlg, CDialog) END_MESSAGE_MAP() BEGIN_MESSAGE_MAP(CLogonServerDlg, CDialog) ON_BN_CLICKED(IDC_START_SERVICE, OnBnClickedStartService) ON_BN_CLICKED(IDC_STOP_SERVICE, OnBnClickedStopService) ON_BN_CLICKED(IDC_INIT_SERVICE, OnBnClickedInitService) END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////////// //构造函数 CSystemOptionDlg::CSystemOptionDlg() : CDialog(IDD_SYSTEM_OPTION) { } //析构函数 CSystemOptionDlg::~CSystemOptionDlg() { } //控件子类化 void CSystemOptionDlg::DoDataExchange(CDataExchange * pDX) { __super::DoDataExchange(pDX); } //初始化函数 BOOL CSystemOptionDlg::OnInitDialog() { __super::OnInitDialog(); //限制输入 ((CEdit *)GetDlgItem(IDC_LISTEN_PORT))->LimitText(5); ((CEdit *)GetDlgItem(IDC_MAX_CONNECT))->LimitText(3); ((CEdit *)GetDlgItem(IDC_MAIN_PAGE))->LimitText(31); ((CEdit *)GetDlgItem(IDC_USER_DATABASE_PORT))->LimitText(5); ((CEdit *)GetDlgItem(IDC_USER_DATABASE_USER))->LimitText(31); ((CEdit *)GetDlgItem(IDC_USER_DATABASE_PASS))->LimitText(31); ((CEdit *)GetDlgItem(IDC_USER_DATABASE_NAME))->LimitText(31); //加载参数 CInitParamter InitParamter; InitParamter.LoadInitParamter(); //设置控件 SetDlgItemInt(IDC_LISTEN_PORT,InitParamter.m_wListenPort,FALSE); SetDlgItemInt(IDC_MAX_CONNECT,InitParamter.m_wMaxConnect,FALSE); //登录数据库 SetDlgItemInt(IDC_USER_DATABASE_PORT,InitParamter.m_wUserDataBasePort,FALSE); SetDlgItemText(IDC_USER_DATABASE_USER,InitParamter.m_szUserDataBaseUser); SetDlgItemText(IDC_USER_DATABASE_PASS,InitParamter.m_szUserDataBasePass); SetDlgItemText(IDC_USER_DATABASE_NAME,InitParamter.m_szUserDataBaseName); //登录数据库地址 DWORD dwDataBaseIP=inet_addr(InitParamter.m_szUserDataBaseAddr); if (dwDataBaseIP==INADDR_NONE) { LPHOSTENT lpHost=gethostbyname(InitParamter.m_szUserDataBaseAddr); if (lpHost!=NULL) dwDataBaseIP=((LPIN_ADDR)lpHost->h_addr)->s_addr; } CIPAddressCtrl * pDataBaseIP=(CIPAddressCtrl *)GetDlgItem(IDC_USER_DATABASE_IP); pDataBaseIP->SetAddress(ntohl(dwDataBaseIP)); //主站地址 if (InitParamter.m_szMainPage[0]==0) SetDlgItemText(IDC_MAIN_PAGE,szStationPage); else SetDlgItemText(IDC_MAIN_PAGE,InitParamter.m_szMainPage); //中心服务器 dwDataBaseIP=inet_addr(InitParamter.m_szCenterServerAddr); if (dwDataBaseIP==INADDR_NONE) { LPHOSTENT lpHost=gethostbyname(InitParamter.m_szCenterServerAddr); if (lpHost!=NULL) dwDataBaseIP=((LPIN_ADDR)lpHost->h_addr)->s_addr; } pDataBaseIP=(CIPAddressCtrl *)GetDlgItem(IDC_CENTER_SERVER_IP); pDataBaseIP->SetAddress(dwDataBaseIP); return TRUE; } //确定函数 void CSystemOptionDlg::OnOK() { //获取输入 CInitParamter InitParamter; InitParamter.m_wListenPort=GetDlgItemInt(IDC_LISTEN_PORT); InitParamter.m_wMaxConnect=GetDlgItemInt(IDC_MAX_CONNECT); //登录数据库 InitParamter.m_wUserDataBasePort=GetDlgItemInt(IDC_USER_DATABASE_PORT); GetDlgItemText(IDC_USER_DATABASE_USER,InitParamter.m_szUserDataBaseUser,sizeof(InitParamter.m_szUserDataBaseUser)); GetDlgItemText(IDC_USER_DATABASE_PASS,InitParamter.m_szUserDataBasePass,sizeof(InitParamter.m_szUserDataBasePass)); GetDlgItemText(IDC_USER_DATABASE_NAME,InitParamter.m_szUserDataBaseName,sizeof(InitParamter.m_szUserDataBaseName)); //登录数据库地址 DWORD dwDataBaseIP=INADDR_NONE; BYTE * pAddrByte=(BYTE *)&dwDataBaseIP; ((CIPAddressCtrl *)GetDlgItem(IDC_USER_DATABASE_IP))->GetAddress(dwDataBaseIP); _snprintf(InitParamter.m_szUserDataBaseAddr,sizeof(InitParamter.m_szUserDataBaseAddr),TEXT("%d.%d.%d.%d"), pAddrByte[3],pAddrByte[2],pAddrByte[1],pAddrByte[0]); //主站地址 GetDlgItemText(IDC_MAIN_PAGE,InitParamter.m_szMainPage,sizeof(InitParamter.m_szMainPage)); if (lstrcmp(InitParamter.m_szMainPage,szStationPage)==0) InitParamter.m_szMainPage[0]=0; //中心服务器 dwDataBaseIP=INADDR_NONE; pAddrByte=(BYTE *)&dwDataBaseIP; ((CIPAddressCtrl *)GetDlgItem(IDC_CENTER_SERVER_IP))->GetAddress(dwDataBaseIP); _snprintf(InitParamter.m_szCenterServerAddr,sizeof(InitParamter.m_szCenterServerAddr),TEXT("%d.%d.%d.%d"), pAddrByte[0],pAddrByte[1],pAddrByte[2],pAddrByte[3]); //保存设置 InitParamter.SaveInitParamter(false); __super::OnOK(); } ////////////////////////////////////////////////////////////////////////// //构造函数 CLogonServerDlg::CLogonServerDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CLogonServerDlg::IDD, pParent) { } //控件子类化 void CLogonServerDlg::DoDataExchange(CDataExchange * pDX) { __super::DoDataExchange(pDX); DDX_Control(pDX, IDC_SERVICE_EVENT, m_RichEditTrace); } //初始化函数 BOOL CLogonServerDlg::OnInitDialog() { __super::OnInitDialog(); //设置图标 HICON hIcon=LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAINFRAME)); SetIcon(hIcon,TRUE); SetIcon(hIcon,FALSE); return TRUE; } //确定消息 void CLogonServerDlg::OnOK() { return; } //取消函数 void CLogonServerDlg::OnCancel() { //获取状态 bool bRuning=m_LogonService.IsService(); //询问退出 if (bRuning==true) { CString strMessage=TEXT("登录服务器正在运行中,确实要退出吗?"); int iRetCode=AfxMessageBox(strMessage,MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2); if (iRetCode!=IDYES) return; } //停止服务 if (bRuning==true) { m_LogonService.StopService(); } __super::OnCancel(); } //消息解释 BOOL CLogonServerDlg::PreTranslateMessage(MSG * pMsg) { if ((pMsg->message==WM_KEYDOWN)&&(pMsg->wParam==VK_ESCAPE)) return TRUE; return __super::PreTranslateMessage(pMsg); } //启动服务 void CLogonServerDlg::OnBnClickedStartService() { //启动服务 if (m_LogonService.StartService()==true) { //设置界面 GetDlgItem(IDC_STOP_SERVICE)->EnableWindow(TRUE); GetDlgItem(IDC_START_SERVICE)->EnableWindow(FALSE); //输出事件 CTraceService::TraceString(TEXT("登录服务启动成功"),TraceLevel_Normal); } else { //输出事件 CTraceService::TraceString(TEXT("登录服务启动失败"),TraceLevel_Exception); } return; } //停止服务 void CLogonServerDlg::OnBnClickedStopService() { //停止服务 if (m_LogonService.StopService()==true) { //设置界面 GetDlgItem(IDC_STOP_SERVICE)->EnableWindow(FALSE); GetDlgItem(IDC_START_SERVICE)->EnableWindow(TRUE); //输出事件 CTraceService::TraceString(TEXT("登录服务停止成功"),TraceLevel_Normal); } else { //输出事件 CTraceService::TraceString(TEXT("登录服务停止失败"),TraceLevel_Exception); } return; } //系统配置 void CLogonServerDlg::OnBnClickedInitService() { CSystemOptionDlg SystemOptionDlg; SystemOptionDlg.DoModal(); return; } //////////////////////////////////////////////////////////////////////////
[ "frozen.arthur@gmail.com" ]
frozen.arthur@gmail.com
e60d62abf8514d46b99efb4a2169ba2fc9c92b0c
116894caf8dcccf6f70211e386b943c43485087f
/vendor/Qt5.14.2/msvc2017/include/QtGui/5.14.2/QtGui/qpa/qplatformdialoghelper.h
ba800a696f6aa9c36d9c7a7952fee1f22dff2a59
[ "MIT" ]
permissive
kiseop91/Pomordor
04498276ea73daef37ad50b6f351a2ffd2ed7ab5
5bfbfaa9ceecdf147058ca49dc3c4fa8b442717c
refs/heads/develop
2023-03-25T22:15:59.964938
2021-03-20T07:59:37
2021-03-20T07:59:37
276,431,994
2
2
MIT
2020-12-21T04:31:02
2020-07-01T16:44:31
C++
UTF-8
C++
false
false
15,778
h
/**************************************************************************** ** ** Copyright (C) 2018 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 QPLATFORMDIALOGHELPER_H #define QPLATFORMDIALOGHELPER_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/QtGlobal> #include <QtCore/QObject> #include <QtCore/QList> #include <QtCore/QSharedDataPointer> #include <QtCore/QSharedPointer> #include <QtCore/QDir> #include <QtCore/QUrl> #include <QtGui/QRgb> QT_BEGIN_NAMESPACE class QString; class QColor; class QFont; class QWindow; class QVariant; class QUrl; class QColorDialogOptionsPrivate; class QFontDialogOptionsPrivate; class QFileDialogOptionsPrivate; class QMessageDialogOptionsPrivate; #define QPLATFORMDIALOGHELPERS_HAS_CREATE class Q_GUI_EXPORT QPlatformDialogHelper : public QObject { Q_OBJECT public: enum StyleHint { DialogIsQtWindow }; enum DialogCode { Rejected, Accepted }; enum StandardButton { // keep this in sync with QDialogButtonBox::StandardButton and QMessageBox::StandardButton NoButton = 0x00000000, Ok = 0x00000400, Save = 0x00000800, SaveAll = 0x00001000, Open = 0x00002000, Yes = 0x00004000, YesToAll = 0x00008000, No = 0x00010000, NoToAll = 0x00020000, Abort = 0x00040000, Retry = 0x00080000, Ignore = 0x00100000, Close = 0x00200000, Cancel = 0x00400000, Discard = 0x00800000, Help = 0x01000000, Apply = 0x02000000, Reset = 0x04000000, RestoreDefaults = 0x08000000, FirstButton = Ok, // internal LastButton = RestoreDefaults, // internal LowestBit = 10, // internal: log2(FirstButton) HighestBit = 27 // internal: log2(LastButton) }; Q_DECLARE_FLAGS(StandardButtons, StandardButton) Q_FLAG(StandardButtons) enum ButtonRole { // keep this in sync with QDialogButtonBox::ButtonRole and QMessageBox::ButtonRole // TODO Qt 6: make the enum copies explicit, and make InvalidRole == 0 so that // AcceptRole can be or'ed with flags, and EOL can be the same as InvalidRole (null-termination) InvalidRole = -1, AcceptRole, RejectRole, DestructiveRole, ActionRole, HelpRole, YesRole, NoRole, ResetRole, ApplyRole, NRoles, RoleMask = 0x0FFFFFFF, AlternateRole = 0x10000000, Stretch = 0x20000000, Reverse = 0x40000000, EOL = InvalidRole }; Q_ENUM(ButtonRole) enum ButtonLayout { // keep this in sync with QDialogButtonBox::ButtonLayout UnknownLayout = -1, WinLayout, MacLayout, KdeLayout, GnomeLayout, MacModelessLayout, AndroidLayout }; Q_ENUM(ButtonLayout) QPlatformDialogHelper(); ~QPlatformDialogHelper(); virtual QVariant styleHint(StyleHint hint) const; virtual void exec() = 0; virtual bool show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow *parent) = 0; virtual void hide() = 0; static QVariant defaultStyleHint(QPlatformDialogHelper::StyleHint hint); static const int *buttonLayout(Qt::Orientation orientation = Qt::Horizontal, ButtonLayout policy = UnknownLayout); static ButtonRole buttonRole(StandardButton button); Q_SIGNALS: void accept(); void reject(); }; QT_END_NAMESPACE Q_DECLARE_METATYPE(QPlatformDialogHelper::StandardButton) Q_DECLARE_METATYPE(QPlatformDialogHelper::ButtonRole) QT_BEGIN_NAMESPACE class Q_GUI_EXPORT QColorDialogOptions { Q_GADGET Q_DISABLE_COPY(QColorDialogOptions) protected: explicit QColorDialogOptions(QColorDialogOptionsPrivate *dd); ~QColorDialogOptions(); public: enum ColorDialogOption { ShowAlphaChannel = 0x00000001, NoButtons = 0x00000002, DontUseNativeDialog = 0x00000004 }; Q_DECLARE_FLAGS(ColorDialogOptions, ColorDialogOption) Q_FLAG(ColorDialogOptions) static QSharedPointer<QColorDialogOptions> create(); QSharedPointer<QColorDialogOptions> clone() const; QString windowTitle() const; void setWindowTitle(const QString &); void setOption(ColorDialogOption option, bool on = true); bool testOption(ColorDialogOption option) const; void setOptions(ColorDialogOptions options); ColorDialogOptions options() const; static int customColorCount(); static QRgb customColor(int index); static QRgb *customColors(); static void setCustomColor(int index, QRgb color); static QRgb *standardColors(); static QRgb standardColor(int index); static void setStandardColor(int index, QRgb color); private: QColorDialogOptionsPrivate *d; }; class Q_GUI_EXPORT QPlatformColorDialogHelper : public QPlatformDialogHelper { Q_OBJECT public: const QSharedPointer<QColorDialogOptions> &options() const; void setOptions(const QSharedPointer<QColorDialogOptions> &options); virtual void setCurrentColor(const QColor &) = 0; virtual QColor currentColor() const = 0; Q_SIGNALS: void currentColorChanged(const QColor &color); void colorSelected(const QColor &color); private: QSharedPointer<QColorDialogOptions> m_options; }; class Q_GUI_EXPORT QFontDialogOptions { Q_GADGET Q_DISABLE_COPY(QFontDialogOptions) protected: explicit QFontDialogOptions(QFontDialogOptionsPrivate *dd); ~QFontDialogOptions(); public: enum FontDialogOption { NoButtons = 0x00000001, DontUseNativeDialog = 0x00000002, ScalableFonts = 0x00000004, NonScalableFonts = 0x00000008, MonospacedFonts = 0x00000010, ProportionalFonts = 0x00000020 }; Q_DECLARE_FLAGS(FontDialogOptions, FontDialogOption) Q_FLAG(FontDialogOptions) static QSharedPointer<QFontDialogOptions> create(); QSharedPointer<QFontDialogOptions> clone() const; QString windowTitle() const; void setWindowTitle(const QString &); void setOption(FontDialogOption option, bool on = true); bool testOption(FontDialogOption option) const; void setOptions(FontDialogOptions options); FontDialogOptions options() const; private: QFontDialogOptionsPrivate *d; }; class Q_GUI_EXPORT QPlatformFontDialogHelper : public QPlatformDialogHelper { Q_OBJECT public: virtual void setCurrentFont(const QFont &) = 0; virtual QFont currentFont() const = 0; const QSharedPointer<QFontDialogOptions> &options() const; void setOptions(const QSharedPointer<QFontDialogOptions> &options); Q_SIGNALS: void currentFontChanged(const QFont &font); void fontSelected(const QFont &font); private: QSharedPointer<QFontDialogOptions> m_options; }; class Q_GUI_EXPORT QFileDialogOptions { Q_GADGET Q_DISABLE_COPY(QFileDialogOptions) protected: QFileDialogOptions(QFileDialogOptionsPrivate *dd); ~QFileDialogOptions(); public: enum ViewMode { Detail, List }; Q_ENUM(ViewMode) enum FileMode { AnyFile, ExistingFile, Directory, ExistingFiles, DirectoryOnly }; Q_ENUM(FileMode) enum AcceptMode { AcceptOpen, AcceptSave }; Q_ENUM(AcceptMode) enum DialogLabel { LookIn, FileName, FileType, Accept, Reject, DialogLabelCount }; Q_ENUM(DialogLabel) enum FileDialogOption { ShowDirsOnly = 0x00000001, DontResolveSymlinks = 0x00000002, DontConfirmOverwrite = 0x00000004, #if QT_DEPRECATED_SINCE(5, 14) DontUseSheet Q_DECL_ENUMERATOR_DEPRECATED = 0x00000008, #endif DontUseNativeDialog = 0x00000010, ReadOnly = 0x00000020, HideNameFilterDetails = 0x00000040, DontUseCustomDirectoryIcons = 0x00000080 }; Q_DECLARE_FLAGS(FileDialogOptions, FileDialogOption) Q_FLAG(FileDialogOptions) static QSharedPointer<QFileDialogOptions> create(); QSharedPointer<QFileDialogOptions> clone() const; QString windowTitle() const; void setWindowTitle(const QString &); void setOption(FileDialogOption option, bool on = true); bool testOption(FileDialogOption option) const; void setOptions(FileDialogOptions options); FileDialogOptions options() const; QDir::Filters filter() const; void setFilter(QDir::Filters filters); void setViewMode(ViewMode mode); ViewMode viewMode() const; void setFileMode(FileMode mode); FileMode fileMode() const; void setAcceptMode(AcceptMode mode); AcceptMode acceptMode() const; void setSidebarUrls(const QList<QUrl> &urls); QList<QUrl> sidebarUrls() const; bool useDefaultNameFilters() const; void setUseDefaultNameFilters(bool d); void setNameFilters(const QStringList &filters); QStringList nameFilters() const; void setMimeTypeFilters(const QStringList &filters); QStringList mimeTypeFilters() const; void setDefaultSuffix(const QString &suffix); QString defaultSuffix() const; void setHistory(const QStringList &paths); QStringList history() const; void setLabelText(DialogLabel label, const QString &text); QString labelText(DialogLabel label) const; bool isLabelExplicitlySet(DialogLabel label); QUrl initialDirectory() const; void setInitialDirectory(const QUrl &); QString initiallySelectedMimeTypeFilter() const; void setInitiallySelectedMimeTypeFilter(const QString &); QString initiallySelectedNameFilter() const; void setInitiallySelectedNameFilter(const QString &); QList<QUrl> initiallySelectedFiles() const; void setInitiallySelectedFiles(const QList<QUrl> &); void setSupportedSchemes(const QStringList &schemes); QStringList supportedSchemes() const; static QString defaultNameFilterString(); private: QFileDialogOptionsPrivate *d; }; class Q_GUI_EXPORT QPlatformFileDialogHelper : public QPlatformDialogHelper { Q_OBJECT public: virtual bool defaultNameFilterDisables() const = 0; virtual void setDirectory(const QUrl &directory) = 0; virtual QUrl directory() const = 0; virtual void selectFile(const QUrl &filename) = 0; virtual QList<QUrl> selectedFiles() const = 0; virtual void setFilter() = 0; virtual void selectMimeTypeFilter(const QString &filter); virtual void selectNameFilter(const QString &filter) = 0; virtual QString selectedMimeTypeFilter() const; virtual QString selectedNameFilter() const = 0; virtual bool isSupportedUrl(const QUrl &url) const; const QSharedPointer<QFileDialogOptions> &options() const; void setOptions(const QSharedPointer<QFileDialogOptions> &options); static QStringList cleanFilterList(const QString &filter); static const char filterRegExp[]; Q_SIGNALS: void fileSelected(const QUrl &file); void filesSelected(const QList<QUrl> &files); void currentChanged(const QUrl &path); void directoryEntered(const QUrl &directory); void filterSelected(const QString &filter); private: QSharedPointer<QFileDialogOptions> m_options; }; class Q_GUI_EXPORT QMessageDialogOptions { Q_GADGET Q_DISABLE_COPY(QMessageDialogOptions) protected: QMessageDialogOptions(QMessageDialogOptionsPrivate *dd); ~QMessageDialogOptions(); public: // Keep in sync with QMessageBox::Icon enum Icon { NoIcon, Information, Warning, Critical, Question }; Q_ENUM(Icon) static QSharedPointer<QMessageDialogOptions> create(); QSharedPointer<QMessageDialogOptions> clone() const; QString windowTitle() const; void setWindowTitle(const QString &); void setIcon(Icon icon); Icon icon() const; void setText(const QString &text); QString text() const; void setInformativeText(const QString &text); QString informativeText() const; void setDetailedText(const QString &text); QString detailedText() const; void setStandardButtons(QPlatformDialogHelper::StandardButtons buttons); QPlatformDialogHelper::StandardButtons standardButtons() const; struct CustomButton { explicit CustomButton( int id = -1, const QString &label = QString(), QPlatformDialogHelper::ButtonRole role = QPlatformDialogHelper::InvalidRole, void *button = nullptr) : label(label), role(role), id(id), button(button) {} QString label; QPlatformDialogHelper::ButtonRole role; int id; void *button; // strictly internal use only }; int addButton(const QString &label, QPlatformDialogHelper::ButtonRole role, void *buttonImpl = nullptr); void removeButton(int id); const QVector<CustomButton> &customButtons(); const CustomButton *customButton(int id); private: QMessageDialogOptionsPrivate *d; }; class Q_GUI_EXPORT QPlatformMessageDialogHelper : public QPlatformDialogHelper { Q_OBJECT public: const QSharedPointer<QMessageDialogOptions> &options() const; void setOptions(const QSharedPointer<QMessageDialogOptions> &options); Q_SIGNALS: void clicked(QPlatformDialogHelper::StandardButton button, QPlatformDialogHelper::ButtonRole role); private: QSharedPointer<QMessageDialogOptions> m_options; }; QT_END_NAMESPACE #endif // QPLATFORMDIALOGHELPER_H
[ "kiseop91@naver.com" ]
kiseop91@naver.com
1bae4f837b4026995f65d3f7208387c93297e5a3
ad49ba448efe450cb1ce16966581d39369eee586
/c/physics/morse.cpp
74fc0e7c06cfd7caf387ae08d907b25683cdb965
[]
no_license
onehalfatsquared/CPfold
5bef1ab139bb82c4cb5d5ec580f495f1b706355f
0c4b3d428f69a546159c79a1915681ccb57774c2
refs/heads/master
2021-06-09T14:49:34.991489
2021-05-05T16:39:26
2021-05-05T16:39:26
158,277,864
1
0
null
null
null
null
UTF-8
C++
false
false
3,534
cpp
#include <math.h> #include <algorithm> #include "bDynamics.h" #include "../defines.h" namespace bd { double morseP(double r, double rho, double E){ //evaluate the morse potential derivative double Y = exp(-(rho) * ((r) - 1)); return -2 * (rho) * (E) * ( Y*Y -Y); } double morseEval(double* particles, int rho, double* E, int N, int* P) { //compute total energy of system with pairwise morse potential //not necc? double S = 0; int i, j; int rep = 0.0; for(i=0;i<N;i++){ for(j=i+1;j<N;j++){ if(j!=i){ double* Z = new double[DIMENSION]; double r = euDist(particles, i, j, N, Z); int minimum = std::min(i,j); int maximum = std::max(i,j); if(P[N*maximum+minimum]==1){ double Eeff = E[N*maximum+minimum]; S += morseP(r, rho, Eeff); } else if(r<1){ S -= rep/r; } delete []Z; } } } return S; } void morseGrad(double* particles, int rho, double* E, int N, int* P, double* g) { //compute gradient of energy of system with pairwise morse potential int i, j; int rep = 250.0; double* S = new double[DIMENSION]; for(i=0;i<N;i++){ S[0] = S[1] = 0; #if (DIMENSION == 3) S[2] = 0; #endif for(j=0;j<N;j++){ if(j!=i){ double* Z = new double[DIMENSION]; double r = euDist(particles, i, j, N, Z); int minimum = std::min(i,j); int maximum = std::max(i,j); if(P[N*maximum+minimum]==1){ double Eeff = E[N*maximum+minimum]; for(int k=0; k<DIMENSION;k++) { if (r < 1 || abs(i-j) == 1) { S[k] += 2.0 * rho * rho * Eeff * (r-1.0) * Z[k]; } else { S[k] = S[k] + morseP(r, rho, Eeff) * Z[k]; } } } else if(r<1.1){ //printf("repelling\n"); for(int k=0; k<DIMENSION;k++) S[k] = S[k] - rep * Z[k] / (r*r); } delete []Z; } } for(int k=0; k<DIMENSION;k++) g[DIMENSION*i+k] = S[k]; } delete []S; } void morseGradR(double* particles, int rho, double* E, int N, int* P, double* g) { //compute gradient of energy of system with pairwise morse potential //includes repulsion force to keep particles from binding int i, j; int rep = 45.0; double* S = new double[DIMENSION]; for(i=0;i<N;i++){ S[0] = S[1] = 0; #if (DIMENSION == 3) S[2] = 0; #endif for(j=0;j<N;j++){ if(j!=i){ double* Z = new double[DIMENSION]; double r = euDist(particles, i, j, N, Z); int minimum = std::min(i,j); int maximum = std::max(i,j); if(P[N*maximum+minimum]==1){ double Eeff = E[N*maximum+minimum]; for(int k=0; k<DIMENSION;k++) { if (r < 1 || abs(i-j) == 1 || (i == 4 && j == 6) || (i==6 && j ==4)) { S[k] += 2.0 * rho * rho * Eeff * (r-1.0) * Z[k]; } else { double mult = morseP(r, rho, Eeff); S[k] = S[k] + mult * Z[k]; if (r < 1.2) { //printf("p1 %d, p2 %d, Distance is %f, mult is %f\n", i,j,r, mult); S[k] = S[k] - mult * Z[k]; S[k] = S[k] - rep * Z[k] / (r*r); } } } } delete []Z; } } for(int k=0; k<DIMENSION;k++) g[DIMENSION*i+k] = S[k]; } delete []S; } }
[ "onehalfatsquared@github.com" ]
onehalfatsquared@github.com
bb88d05c5e07e0593ac335f33c1a3763f199ff61
dccc899de920df96e8c41dde4e23af8966c94393
/quickselect/quickselect.cpp
99406e79c32bb8f082c6ffa714b09ddbf4ebb195
[]
no_license
qs8607a/algorithm-32
5da99a5436abc16fd5aa11453c0647f1c33f7407
fea5f2516d13664cf303ee108bd7512fd2c37c6b
refs/heads/master
2016-09-03T07:08:25.374637
2013-03-24T04:31:01
2013-03-24T04:31:01
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,334
cpp
/* quickSelect - 中央値を探索する - 平均的にO(n) - ※バグもち。そのうち直す。 */ #include <cstdio> #include <algorithm> #include <functional> #include <vector> // 中央値を返す int quickSelect( int* elements, int left, int right, int selectNo ) { // 要素が1つしかない場合 if( left == right ) { return elements[left]; } // 要素が二つしかない場合 else if( right - left == 1 ) { if( elements[left] > elements[right] ) { std::swap(elements[left],elements[right]); } if( left == selectNo ) { return elements[left]; } else { return elements[right]; } } // pivotの決定を行う int numSameNumber = left; while( numSameNumber < right && elements[numSameNumber] == elements[numSameNumber+1] ) { ++numSameNumber; } // 同値のみの列なので先頭要素をそのまま返す if( (numSameNumber != left) && numSameNumber + 1 == (right - left + 1) ) { return elements[0]; } // 軸要素の決定(隣あう値が違う値で、その高いほうであれば列中の最低値では確実にない)し、最後尾に移動 if( elements[numSameNumber] < elements[numSameNumber+1] ) { std::swap( elements[numSameNumber+1], elements[right] ); } else { std::swap( elements[numSameNumber], elements[right] ); } int pivotValue = elements[right]; // 二つの要素に分割 int lowArrayIndex = left; for(int i=left;i<right;++i) { if( elements[i] < pivotValue ) { std::swap( elements[lowArrayIndex], elements[i] ); ++lowArrayIndex; } } // 後半の列の先頭とpivot値のある最後尾を交換 std::swap( elements[lowArrayIndex], elements[right] ); // 分割の中心が中心より右だったら左の中でさらに選択動作 if( selectNo < lowArrayIndex ) { return quickSelect( elements, left, lowArrayIndex, selectNo ); } // 分割の中心が中心より左だったら右の中でさらに選択動作 else if( lowArrayIndex < selectNo ) { return quickSelect( elements, lowArrayIndex, right, selectNo ); } else { return elements[lowArrayIndex]; } } // quickSelect int quickSelect( int* elements, int numElements, int selectNo ) { return quickSelect( elements, 0, numElements-1, selectNo ); } // 全体をソートしてから選択 int bruteSelect( int* elements, int numElements, int selectNo ) { // 全体をソートして指定した場所を返す std::sort( elements, elements + numElements ); return elements[selectNo]; } // main関数 void main() { for( int testNo=0;testNo<100;++testNo) { std::vector<int> testValue; testValue.resize( rand() % 100 + 1 ); for( int& i : testValue ){ i = rand(); } const int selectPos = rand() % testValue.size(); std::vector<int> copy0 = testValue; std::vector<int> copy1 = testValue; int selectedNo0 = quickSelect( &copy0[0], copy0.size(), selectPos ); int selectedNo1 = bruteSelect( &copy1[0], copy1.size(), selectPos ); if( selectedNo0 != selectedNo1 ) { printf("%d\n",testNo); printf("testNo%d\n select:%d\n %d-%d\n", testNo, selectPos, selectedNo0, selectedNo1 ); printf(" numElem:%d\n ", testValue.size() ); printf(" "); for( int i:testValue){ printf("%d ", i); } printf("\n"); } } }
[ "q.at.nonoil@gmail.com" ]
q.at.nonoil@gmail.com
443e4be63869d7d2badd4c6793071726669ba036
2d42a50f7f3b4a864ee19a42ea88a79be4320069
/source/graphics/buffers/ibo.h
c5f3f3cb8cdbf9484a57c1182e9995d1835bcfd0
[]
no_license
Mikalai/punk_project_a
8a4f55e49e2ad478fdeefa68293012af4b64f5d4
8829eb077f84d4fd7b476fd951c93377a3073e48
refs/heads/master
2016-09-06T05:58:53.039941
2015-01-24T11:56:49
2015-01-24T11:56:49
14,536,431
1
0
null
2014-06-26T06:40:50
2013-11-19T20:03:46
C
UTF-8
C++
false
false
3,553
h
#ifndef _H_PUNK_OPENGL_INDEX_BUFFER #define _H_PUNK_OPENGL_INDEX_BUFFER #include <graphics/opengl/module.h> #include "ibufffer_object.h" PUNK_ENGINE_BEGIN namespace Graphics { namespace OpenGL { class VideoMemory; template<class T> class PUNK_ENGINE_LOCAL IndexBufferObject : public IBufferObject { public: using CurrentIndex = T; public: // Only VideoMemory can create it virtual ~IndexBufferObject() { try { Destroy(); } catch (...) { } } void QueryInterface(const Core::Guid& type, void** object) { Core::QueryInterface(this, type, object, { Core::IID_IObject, IID_IBufferObject }); } std::uint32_t AddRef() { return m_ref_count.fetch_add(1); } std::uint32_t Release() { auto v = m_ref_count.fetch_sub(1) - 1; if (!v) { delete this; } return v; } IndexBufferObject(){}; IndexBufferObject(const IndexBufferObject&) = delete; IndexBufferObject& operator = (const IndexBufferObject&) = delete; void Create(const T* data, std::uint32_t count) { Create(data, sizeof(T)*count); } void Destroy() override { if (m_index) { GL_CALL(glDeleteBuffers(1, &m_index)); m_index = 0; } } void Bind() const override { if (!IsValid()) throw Error::OpenGLInvalidValueException(L"Buffer is not valid"); GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_index)); } void Unbind() const override { if (!IsValid()) throw Error::OpenGLInvalidValueException(L"Buffer is not valid"); GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); } T* MapIB() { return (T*)Map(); } const T* MapIB() const { return (const T*)Map(); } void Unmap() const override { Bind(); GL_CALL(glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER)); Unbind(); } void CopyData(const T* data, std::uint32_t count) { CopyData((void*)data, count*sizeof(T)); } bool IsValid() const override { return m_index != 0; } std::uint32_t GetCount() { return m_size / sizeof(T); } std::uint32_t GetSize() override { return m_size; } private: void Create(const void* data, std::uint32_t size) { if (IsValid()) Destroy(); GL_CALL(glGenBuffers(1, &m_index)); GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_index)); GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW)); GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); m_size = size; } void* Map() { Bind(); GL_CALL(GLvoid* buffer = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_WRITE)); Unbind(); return buffer; } const void* Map() const { Bind(); GL_CALL(GLvoid* buffer = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_BUFFER)); Unbind(); return buffer; } void CopyData(const void* data, std::uint32_t size) { if (m_index == 0) { Create(data, size); } else { if (m_size < (GLsizei)size) throw Error::OpenGLOutOfMemoryException(L"Index buffer is to small " + Core::String::Convert(m_size) + L" to hold " + Core::String::Convert(size)); Bind(); GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, size, data)); Unbind(); } } private: std::atomic<std::uint32_t> m_ref_count{ 0 }; GLuint m_index{ 0 }; GLsizei m_size{ 0 }; }; template<> class PUNK_ENGINE_LOCAL IndexBufferObject < std::nullptr_t > { public: using CurrentIndex = std::nullptr_t; }; } } PUNK_ENGINE_END #endif // _H_PUNK_OPENGL_INDEX_BUFFER
[ "nickolaib2004@gmail.com" ]
nickolaib2004@gmail.com
55f1fd5218dfb25e23383cf7a6a0f17a4e76f57d
2fa764b33e15edd3b53175456f7df61a594f0bb5
/appseed/aura/net/netserver/netserver_socket.h
7183e7b022dc8cd8201572cc44632241ac1ac355
[]
no_license
PeterAlfonsLoch/app
5f6ac8f92d7f468bc99e0811537380fcbd828f65
268d0c7083d9be366529e4049adedc71d90e516e
refs/heads/master
2021-01-01T17:44:15.914503
2017-07-23T16:58:08
2017-07-23T16:58:08
98,142,329
1
0
null
2017-07-24T02:44:10
2017-07-24T02:44:10
null
UTF-8
C++
false
false
585
h
#pragma once namespace netserver { class CLASS_DECL_AURA socket : virtual public ::sockets::httpd_socket { public: bool m_bSetCookie; socket(::sockets::base_socket_handler & h); ~socket(); virtual void OnExecute(); virtual void OnResponseComplete(); virtual void send_response(); virtual void on_send_response(); virtual void simple_file_server(const char * pszPath); virtual bool http_filter_response_header(id key, stringa & straValue); }; } // namespace netserver
[ "camilo@ca2.email" ]
camilo@ca2.email
9b57619a03d1a81b1992fefb6c525031d4e8317f
04b1803adb6653ecb7cb827c4f4aa616afacf629
/ash/shell/content/shell_with_content_main.cc
b1a6b73adab02d22611546f02dbdf5f2133c2fb5
[ "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,197
cc
// 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. #include "ash/shell/content/client/shell_main_delegate.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "content/public/app/content_main.h" int main(int argc, const char** argv) { base::CommandLine::Init(argc, argv); base::AtExitManager exit_manager; base::FilePath log_filename; base::PathService::Get(base::DIR_EXE, &log_filename); log_filename = log_filename.AppendASCII("ash_shell.log"); logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_ALL; settings.log_file = log_filename.value().c_str(); settings.delete_old = logging::DELETE_OLD_LOG_FILE; logging::InitLogging(settings); logging::SetLogItems(true /* process_id */, true /* thread_id */, true /* timestamp */, false /* tick_count */); ash::shell::ShellMainDelegate delegate; content::ContentMainParams params(&delegate); params.argc = argc; params.argv = argv; return content::ContentMain(params); }
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
1c79e75e5448ba079b0ea1bc63bf4565809fa69d
6bdce03306010b28317815fbaa3e377329742c8b
/CPP/LogicalandRelationalOperators.cpp
e5a42e02691d9d613824c2a59554a647dc8eff53
[]
no_license
kayfour/learn_C_CPP
9ed9a804fa3f4e4bbfc1a1f37cd3b71894074536
43871102ad4e4af75c9332baa1da7e06e1b847e5
refs/heads/master
2023-01-18T17:24:30.595527
2020-12-01T12:45:05
2020-12-01T12:45:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
901
cpp
#include <iostream> using namespace std; int main() { int first = 21; int second = 10; int result ; if( first == second ) { cout << "first is equal to second" << endl ; } else { cout << "first is not equal to second" << endl ; } if( first < second ) { cout << "first is less than second" << endl ; } else { cout << "first is not less than second" << endl ; } if( first > second ) { cout << "first is greater than second" << endl ; } else { cout << "first is not greater than second" << endl ; } /* Let's change the values of first and second */ first = 5; second = 20; if( first <= second ) { cout << "first is either less than \ or equal to second" << endl ; } if( second >= first ) { cout << "second is either greater than \ or equal to second" << endl ; } return 0; }
[ "sanghunoh@sanghuns-MacBook-Air.local" ]
sanghunoh@sanghuns-MacBook-Air.local
9e63fa095ec1cbce18c9ac8a00864279218058e8
fc6507919542a73013cd098d124f9fc26d5125b3
/Sub two numbers.cpp
f4e789c78535ba2a5834b3e87895dbabecc30732
[]
no_license
MonikaLinn/CPlusPlus-Projects
e206819768aa9498ee1f269cd0dbee53c2a7bb31
e094337524a0480e693186ac46d18d254264fd61
refs/heads/main
2023-08-24T08:15:25.884751
2021-10-24T03:49:16
2021-10-24T03:49:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,263
cpp
#include <iostream> using namespace std; //Function prototypes declarations int calculations(int firstInput, int secondInput); int numberOne(); int numberTwo(); //Showing the user answer / skeleton for program int main() { int inputOne = numberOne(); int inputTwo = numberTwo(); int subtraction = calculations(inputOne, inputTwo); cout << "The sum of the two numbers are: " << subtraction << endl; return 0; } //Caluculations for subtracting the two numbers int calculations(int firstInput, int secondInput) { int result = firstInput - secondInput; return result; } //Validating if the first number is positive, if it isn't it reprompts user. int numberOne() { int input; cout << "Enter the first positive number: "; cin >> input; while (input < 0) { cout << "That is an invalid input. Number must be positive\n"; cout << "Enter the first positive number: "; cin >> input; } return input; } //Validating if the second number is positive, if it isn't it reprompts user. int numberTwo() { int input; cout << "Enter the second positive number: "; cin >> input; while (input < 0) { cout << "That is an invalid input. Number must be positive\n"; cout << "Enter the second positive number: "; cin >> input; } return input; }
[ "75878133+MonikaLinn@users.noreply.github.com" ]
75878133+MonikaLinn@users.noreply.github.com
7d62ef1e95f94ee0aedc76148f34452044163a7f
17b6dff759bc6b2348785f6dd5b8f0c9805d9fd9
/IC Imaging Control/samples/vc10/Making Device Settings/MakingDeviceSettingsDlg.cpp
f4acbc41a1702e17b8356a95a7e34e73be050447
[]
no_license
LVROBOT/Stereo-Vision
19d5c43932d2bc98b7e80b75bcf13b155679f7ca
c1910271a7440165aa3d38174c167a135ffdfc62
refs/heads/master
2021-04-06T17:03:03.740281
2018-03-15T15:10:30
2018-03-15T15:10:30
125,384,975
0
0
null
null
null
null
UTF-8
C++
false
false
3,884
cpp
// MakingDeviceSettingsDlg.cpp : implementation file // #include "stdafx.h" #include "MakingDeviceSettings.h" #include "MakingDeviceSettingsDlg.h" #include "DeviceDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMakingDeviceSettingsDlg dialog CMakingDeviceSettingsDlg::CMakingDeviceSettingsDlg(CWnd* pParent /*=NULL*/) : CDialog(CMakingDeviceSettingsDlg::IDD, pParent) { //{{AFX_DATA_INIT(CMakingDeviceSettingsDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMakingDeviceSettingsDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMakingDeviceSettingsDlg) DDX_Control(pDX, IDC_PICTURE, m_staticPicture); DDX_Control(pDX, IDC_BTN_STOPLIVE, m_btnStopLive); DDX_Control(pDX, IDC_BTN_STARTLIVE, m_btnStartLive); DDX_Control(pDX, IDC_BTN_DEVICE, m_btnDevice); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMakingDeviceSettingsDlg, CDialog) //{{AFX_MSG_MAP(CMakingDeviceSettingsDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BTN_STARTLIVE, OnBtnStartlive) ON_BN_CLICKED(IDC_BTN_STOPLIVE, OnBtnStoplive) ON_BN_CLICKED(IDC_BTN_DEVICE, OnBtnDevice) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMakingDeviceSettingsDlg message handlers BOOL CMakingDeviceSettingsDlg::OnInitDialog() { CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon m_Grabber.setHWND( GetDlgItem( IDC_PICTURE )->m_hWnd ); m_btnStartLive.EnableWindow( false ); m_btnStopLive.EnableWindow( false ); return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMakingDeviceSettingsDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CMakingDeviceSettingsDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CMakingDeviceSettingsDlg::OnBtnStartlive() { m_Grabber.startLive( true ); m_btnStartLive.EnableWindow( false ); m_btnStopLive.EnableWindow( true ); } void CMakingDeviceSettingsDlg::OnBtnStoplive() { m_Grabber.stopLive(); m_btnStartLive.EnableWindow( true ); m_btnStopLive.EnableWindow( false ); } void CMakingDeviceSettingsDlg::OnBtnDevice() { CDeviceDlg dlg( &m_Grabber, this ); // Call the dialog if( dlg.DoModal() == -1 ) { AfxMessageBox( TEXT("The dialog could not be created") ); return; } if( m_Grabber.isDevValid() ) { if( !m_Grabber.isLive() ) { m_btnStartLive.EnableWindow( true ); } else { m_btnStartLive.EnableWindow( false ); } } else { m_btnStartLive.EnableWindow( false ); } }
[ "15954028913@163.com" ]
15954028913@163.com
6f671a00d57fa1a2faf28f752974375d7deed60e
345dbd5c369e617da89cbd164b773b71bca91aff
/virtualChassis.cpp
536147745f1cfa9559199d943ed05cf513a71c58
[]
no_license
zhenwk/autonomous_rolling_hump
df11e228687adf3e2620635ec266450ba6ee823b
0e77aa7ff71ba37d4236ab3dbae4f4000afd0b5f
refs/heads/master
2021-01-14T08:59:24.492981
2015-03-31T19:10:11
2015-03-31T19:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,209
cpp
/* * Adapted from David Rollinson's code (unifiedVC_fast.cpp) on 2012/2/2. * * Virtual chassis implementation for use with snake simulator. */ /************************************* * Documentation from MATLAB version * *************************************/ //UNIFIEDVC // [ virtualChassis, chassisMags ] = // unifiedVC( robotFrames, axisPerm ) // // Uses SVD to find the virtual chassis of the snake for any gait. // The function finds the principal moments of inertia of the robot's // shape and uses them to define the axes of the virtual chassis, with the // origin at the center of mass (each transform is treated as a point mass // of equal weight). // // This code is intended for use with the Modsnake robots, but it should // theoretically be general enough to work on any system with a bunch of // rigid bodies described by transformation matrices in a common frame. // // Inputs: // robotFrames - a [4 x 4 x number of modules] array of homogeneous // transform matrices describing the poses of the the centers of // the modules in the robot. The matrices need to be in some common // body frame, not relative to each other. // // axisPerm - a [3 x 3] permutation matrix that allows the user to // re-align the virtual chassis however they want. By default the // 1st, 2nd, and 3rd principal moments of inertia are aligned // respectively with the Z, Y, and X axes of the virtual chassis. // // Outputs: // virtualChassis - [4 x 4] transformation matrix that describes the // pose of the virtual chassis body frame, described in the frame of // the input transformation matrices. // // chassisMags - [3 x 1] vector, diag(S) from SVD, used for reporting // the magnitudes of the principle components of the robot's shape. // // Dave Rollinson // July 2011 /* END MATLAB DOCUMENTATION */ #include <math.h> #include <vector> #include "Eigen/Dense" #include "Eigen/Core" #include "Pose3d.h" using namespace Eigen; /// Returns a 4x4 (12 element, first four elements are first column) transform /// matrix. /// points is void virtualChassis(double* virtualChassis, std::vector<Point3d> modulePos) { /************* * VARIABLES * *************/ int i, j, k; // for-loop counters double signCheck; // for checking for sign-flips in the VC int numModules; // number of modules numModules = modulePos.size(); /********************************************* * Create Eigen Matrices for doing the maths * *********************************************/ // Matrix for the virtual chassis transform Matrix4d VC = Matrix4d::Identity(); // Form the data matrix for doing SVD MatrixXd xyz_pts(numModules,3); for (i = 0; i < numModules; i++) { // Copy the x,y,z coordinates from the input data. xyz_pts(i,0) = modulePos[i].x; xyz_pts(i,1) = modulePos[i].y; xyz_pts(i,2) = modulePos[i].z; } // Get the center of mass of the module positions. // Subtract it from the xyz positions Vector3d CoM = xyz_pts.colwise().mean(); for (j = 0; j < 3; j++) { xyz_pts.col(j).array() -= CoM(j); } /********************************************* * Take the SVD of the zero-meaned positions * *********************************************/ // Take the SVD, use thinSVD since we only need V and S. JacobiSVD<MatrixXd> svd(xyz_pts, ComputeThinU | ComputeThinV); // Get the singular values and V matrix Vector3d S = svd.singularValues(); Matrix3d V = svd.matrixV(); // Make sure the 1st principal moment points toward the // head module. signCheck = V.col(0).dot( xyz_pts.row(0) ); if (signCheck < 0) { V.col(0) = -V.col(0); } // Ensure a right-handed frame, by making the 3rd moment // the cross product of the first two. V.col(2) = V.col(0).cross(V.col(1)); // 4x4 transform for the virtual chassis VC.block<3,3>(0,0) = V; VC.block<3,1>(0,3) = CoM; /******************************************** * Copy the Eigen Matrices to the MexArrays * ********************************************/ // Matrix for the last virtual chassis for (j = 0; j < 4; j++) { for (k = 0; k < 4; k++) { virtualChassis[4*j + k] = VC(k,j); } } }
[ "biorobotics@MambaLin.biorobotics.local" ]
biorobotics@MambaLin.biorobotics.local
3d3ebd1ce16c2ff48bdc0750adc5232ff3fb2668
34ba73cad1026d0edeccdd989ca3b5f7186876f8
/rbdl/tests/CustomJointMultiBodyTests.cc
1c4416c211ccb4f773e02fabf7c7e1195850ce6e
[ "Zlib", "MIT" ]
permissive
bvsk35/Hopping_Bot
36fe3934190c44ac827eb285c08c3d1f59779fee
5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216
refs/heads/master
2022-07-31T20:06:55.814867
2019-11-28T17:54:40
2019-11-28T17:54:40
173,667,400
0
1
MIT
2022-06-21T22:01:27
2019-03-04T03:29:32
C++
UTF-8
C++
false
false
31,389
cc
/* * RBDL - Rigid Body Dynamics Library * Copyright (c) 2016-2018 Matthew Millard <matthew.millard@iwr.uni-heidelberg.de> */ #include <UnitTest++.h> #include <iostream> #include "Fixtures.h" #include "Human36Fixture.h" #include "rbdl/rbdl_mathutils.h" #include "rbdl/Logging.h" #include "rbdl/Model.h" #include "rbdl/Kinematics.h" #include "rbdl/Dynamics.h" #include "rbdl/Constraints.h" #include <vector> using namespace std; using namespace RigidBodyDynamics; using namespace RigidBodyDynamics::Math; const double TEST_PREC = 1.0e-11; const int NUMBER_OF_MODELS = 3; const int NUMBER_OF_BODIES = 3; //============================================================================== /* The purpose of this test is to test that all of the code in RBDL related to a multibody mechanism that includes a custom joint functions. Specifically this test is for the multi-pass algorithms in rbdl ... namely the CompositeRigidBodyAlgorithm. However, because these tests have already been written for CustomJointSingleBodyTests.cc, we'll run them all on the multibody models that we will be testing. We will be testing 3 models to get good coverage of the CompositeRigidBodyAlgorithm: 1. Rx - multidof - custom 2. Rx - custom - multidof 3. custom - multidof - Rx As before, to test that the model works, we will create a model using standard RBDL versions (the reference model), and then we will create a model using a custom joint in the correct location. The following algorithms will be tested in this manner: UpdateKinematicsCustom Jacobians InverseDynamics CompositeRigidBodyAlgorithm ForwardDynamics CalcMInvTimestau ForwardDynamicsContactsKokkevis */ //============================================================================== struct CustomJointTypeRevoluteX : public CustomJoint { CustomJointTypeRevoluteX(){ mDoFCount = 1; S = MatrixNd::Zero(6,1); S(0,0)=1.0; d_u = MatrixNd::Zero(mDoFCount,1); } virtual void jcalc (Model &model, unsigned int joint_id, const Math::VectorNd &q, const Math::VectorNd &qdot) { model.X_J[joint_id] = Xrotx(q[model.mJoints[joint_id].q_index]); model.v_J[joint_id][0] = qdot[model.mJoints[joint_id].q_index]; } virtual void jcalc_X_lambda_S ( Model &model, unsigned int joint_id, const Math::VectorNd &q) { model.X_lambda[joint_id] = Xrotx (q[model.mJoints[joint_id].q_index]) * model.X_T[joint_id]; const Joint &joint = model.mJoints[joint_id]; model.mCustomJoints[joint.custom_joint_index]->S = S; } }; struct CustomEulerZYXJoint : public CustomJoint { CustomEulerZYXJoint () { mDoFCount = 3; S = MatrixNd::Zero (6,3); d_u = MatrixNd::Zero(mDoFCount,1); } virtual void jcalc (Model &model, unsigned int joint_id, const Math::VectorNd &q, const Math::VectorNd &qdot) { double q0 = q[model.mJoints[joint_id].q_index]; double q1 = q[model.mJoints[joint_id].q_index + 1]; double q2 = q[model.mJoints[joint_id].q_index + 2]; double s0 = sin (q0); double c0 = cos (q0); double s1 = sin (q1); double c1 = cos (q1); double s2 = sin (q2); double c2 = cos (q2); model.X_J[joint_id].E = Matrix3d( c0 * c1, s0 * c1, -s1, c0 * s1 * s2 - s0 * c2, s0 * s1 * s2 + c0 * c2, c1 * s2, c0 * s1 * c2 + s0 * s2, s0 * s1 * c2 - c0 * s2, c1 * c2 ); S.setZero(); S(0,0) = -s1; S(0,2) = 1.; S(1,0) = c1 * s2; S(1,1) = c2; S(2,0) = c1 * c2; S(2,1) = - s2; double qdot0 = qdot[model.mJoints[joint_id].q_index]; double qdot1 = qdot[model.mJoints[joint_id].q_index + 1]; double qdot2 = qdot[model.mJoints[joint_id].q_index + 2]; model.v_J[joint_id] = S * Vector3d (qdot0, qdot1, qdot2); model.c_J[joint_id].set( -c1*qdot0*qdot1, -s1*s2*qdot0*qdot1 + c1*c2*qdot0*qdot2 - s2*qdot1*qdot2, -s1*c2*qdot0*qdot1 - c1*s2*qdot0*qdot2 - c2*qdot1*qdot2, 0., 0., 0. ); } virtual void jcalc_X_lambda_S ( Model &model, unsigned int joint_id, const Math::VectorNd &q) { double q0 = q[model.mJoints[joint_id].q_index]; double q1 = q[model.mJoints[joint_id].q_index + 1]; double q2 = q[model.mJoints[joint_id].q_index + 2]; double s0 = sin (q0); double c0 = cos (q0); double s1 = sin (q1); double c1 = cos (q1); double s2 = sin (q2); double c2 = cos (q2); model.X_lambda[joint_id] = SpatialTransform ( Matrix3d( c0 * c1, s0 * c1, -s1, c0 * s1 * s2 - s0 * c2, s0 * s1 * s2 + c0 * c2, c1 * s2, c0 * s1 * c2 + s0 * s2, s0 * s1 * c2 - c0 * s2, c1 * c2 ), Vector3d (0., 0., 0.)) * model.X_T[joint_id]; S.setZero(); S(0,0) = -s1; S(0,2) = 1.; S(1,0) = c1 * s2; S(1,1) = c2; S(2,0) = c1 * c2; S(2,1) = - s2; const Joint &joint = model.mJoints[joint_id]; model.mCustomJoints[joint.custom_joint_index]->S = S; } }; //============================================================================== //Test Fixture //============================================================================== struct CustomJointMultiBodyFixture { CustomJointMultiBodyFixture () { reference_model.resize(NUMBER_OF_MODELS); custom_model.resize(NUMBER_OF_MODELS); body.resize(NUMBER_OF_MODELS); custom_joint.resize(NUMBER_OF_MODELS); reference_body_id.resize(NUMBER_OF_MODELS); custom_body_id.resize(NUMBER_OF_MODELS); for(int i=0; i < NUMBER_OF_MODELS; ++i){ body.at(i).resize(3); custom_joint.at(i).resize(1); reference_body_id.at(i).resize(3); custom_body_id.at(i).resize(3); } q.resize(NUMBER_OF_MODELS); qdot.resize(NUMBER_OF_MODELS); qddot.resize(NUMBER_OF_MODELS); tau.resize(NUMBER_OF_MODELS); //======================================================== //Test Model 1: Rx - multidof3 - custom //======================================================== custom_rx_joint1 = CustomJointTypeRevoluteX(); Matrix3d inertia1 = Matrix3d::Identity(3,3); Body body11 = Body (1., Vector3d (1.1, 1.2, 1.3), inertia1); Body body12 = Body (2., Vector3d (2.1, 2.2, 2.3), inertia1); Body body13 = Body (3., Vector3d (3.1, 3.2, 3.3), inertia1); Model reference1, custom1; Vector3d r1 = Vector3d(0.78,-0.125,0.37); double th1 = M_PI/6.0; double sinTh1 = sin(th1); double cosTh1 = cos(th1); Matrix3d rm1 = Matrix3d( 1.0, 0., 0., 0., cosTh1, -sinTh1, 0., sinTh1, cosTh1); Vector3d r2 = Vector3d(-0.178,0.2125,-0.937); double th2 = M_PI/2.15; double sinTh2 = sin(th2); double cosTh2 = cos(th2); Matrix3d rm2 = Matrix3d( cosTh2, 0., sinTh2, 0., 1., 0., -sinTh2, 0., cosTh2); unsigned int reference_body_id10 = reference1.AddBody (0, SpatialTransform(), Joint(JointTypeRevoluteX), body11); unsigned int reference_body_id11 = reference1.AddBody (reference_body_id10, SpatialTransform(rm1,r1), Joint(JointTypeEulerZYX), body12); unsigned int reference_body_id12 = reference1.AddBody (reference_body_id11, SpatialTransform(rm2,r2), Joint(JointTypeRevoluteX), body13); unsigned int custom_body_id10 = custom1.AddBody ( 0, SpatialTransform(), Joint(JointTypeRevoluteX), body11); unsigned int custom_body_id11 = custom1.AddBody ( custom_body_id10, SpatialTransform(rm1,r1), Joint(JointTypeEulerZYX), body12); unsigned int custom_body_id12 = custom1.AddBodyCustomJoint ( custom_body_id11, SpatialTransform(rm2,r2), &custom_rx_joint1, body13); VectorNd q1 = VectorNd::Zero (reference1.q_size); VectorNd qdot1 = VectorNd::Zero (reference1.qdot_size); VectorNd qddot1 = VectorNd::Zero (reference1.qdot_size); VectorNd tau1 = VectorNd::Zero (reference1.qdot_size); int idx = 0; reference_model.at(idx) = (reference1); custom_model.at(idx) = (custom1); reference_body_id.at(idx).at(0) = (reference_body_id10); reference_body_id.at(idx).at(1) = (reference_body_id11); reference_body_id.at(idx).at(2) = (reference_body_id12); custom_body_id.at(idx).at(0) = (custom_body_id10); custom_body_id.at(idx).at(1) = (custom_body_id11); custom_body_id.at(idx).at(2) = (custom_body_id12); body.at(idx).at(0) = (body11); body.at(idx).at(1) = (body12); body.at(idx).at(2) = (body13); custom_joint.at(idx).at(0) = (&custom_rx_joint1); q.at(idx) = (q1); qdot.at(idx) = (qdot1); qddot.at(idx) = (qddot1); tau.at(idx) = (tau1); //======================================================== //Test Model 2: Rx - custom - multidof3 //======================================================== Model reference2, custom2; unsigned int reference_body_id20 = reference2.AddBody (0, SpatialTransform(), Joint(JointTypeRevoluteX), body11); unsigned int reference_body_id21 = reference2.AddBody (reference_body_id20, SpatialTransform(rm2,r2), Joint(JointTypeRevoluteX), body12); unsigned int reference_body_id22 = reference2.AddBody (reference_body_id21, SpatialTransform(rm1,r1), Joint(JointTypeEulerZYX), body13); unsigned int custom_body_id20 = custom2.AddBody ( 0, SpatialTransform(), Joint(JointTypeRevoluteX), body11); unsigned int custom_body_id21 = custom2.AddBodyCustomJoint ( custom_body_id20, SpatialTransform(rm2,r2), &custom_rx_joint1, body12); unsigned int custom_body_id22 = custom2.AddBody ( custom_body_id21, SpatialTransform(rm1,r1), Joint(JointTypeEulerZYX), body13); VectorNd q2 = VectorNd::Zero (reference2.q_size); VectorNd qdot2 = VectorNd::Zero (reference2.qdot_size); VectorNd qddot2 = VectorNd::Zero (reference2.qdot_size); VectorNd tau2 = VectorNd::Zero (reference2.qdot_size); idx = 1; reference_model.at(idx) = (reference2); custom_model.at(idx) = (custom2); reference_body_id.at(idx).at(0) = (reference_body_id20); reference_body_id.at(idx).at(1) = (reference_body_id21); reference_body_id.at(idx).at(2) = (reference_body_id22); custom_body_id.at(idx).at(0) = (custom_body_id20); custom_body_id.at(idx).at(1) = (custom_body_id21); custom_body_id.at(idx).at(2) = (custom_body_id22); body.at(idx).at(0) = (body11); body.at(idx).at(1) = (body12); body.at(idx).at(2) = (body13); custom_joint.at(idx).at(0) = (&custom_rx_joint1); q.at(idx) = (q2); qdot.at(idx) = (qdot2); qddot.at(idx) = (qddot2); tau.at(idx) = (tau2); //======================================================== //Test Model 3: custom - multidof3 - Rx //======================================================== Model reference3, custom3; unsigned int reference_body_id30 = reference3.AddBody (0, SpatialTransform(), Joint(JointTypeRevoluteX), body11); unsigned int reference_body_id31 = reference3.AddBody (reference_body_id30, SpatialTransform(rm1,r1), Joint(JointTypeEulerZYX), body12); unsigned int reference_body_id32 = reference3.AddBody (reference_body_id31, SpatialTransform(rm2,r2), Joint(JointTypeRevoluteX), body13); unsigned int custom_body_id30 = custom3.AddBodyCustomJoint ( 0, SpatialTransform(), &custom_rx_joint1, body11); unsigned int custom_body_id31 = custom3.AddBody ( custom_body_id30, SpatialTransform(rm1,r1), Joint(JointTypeEulerZYX), body12); unsigned int custom_body_id32 = custom3.AddBody ( custom_body_id31, SpatialTransform(rm2,r2), Joint(JointTypeRevoluteX), body13); VectorNd q3 = VectorNd::Zero (reference3.q_size); VectorNd qdot3 = VectorNd::Zero (reference3.qdot_size); VectorNd qddot3 = VectorNd::Zero (reference3.qdot_size); VectorNd tau3 = VectorNd::Zero (reference3.qdot_size); idx = 2; reference_model.at(idx) = (reference3); custom_model.at(idx) = (custom3); reference_body_id.at(idx).at(0) = (reference_body_id30); reference_body_id.at(idx).at(1) = (reference_body_id31); reference_body_id.at(idx).at(2) = (reference_body_id32); custom_body_id.at(idx).at(0) = (custom_body_id30); custom_body_id.at(idx).at(1) = (custom_body_id31); custom_body_id.at(idx).at(2) = (custom_body_id32); body.at(idx).at(0) = (body11); body.at(idx).at(1) = (body12); body.at(idx).at(2) = (body13); custom_joint.at(idx).at(0) = (&custom_rx_joint1); q.at(idx) = (q3); qdot.at(idx) = (qdot3); qddot.at(idx) = (qddot3); tau.at(idx) = (tau3); } /* ~CustomJointMultiBodyFixture () { }*/ vector < Model > reference_model; vector < Model > custom_model; vector < vector < Body > > body; vector < vector < CustomJoint* > > custom_joint; vector < vector< unsigned int > > reference_body_id; vector < vector< unsigned int > > custom_body_id; vector < VectorNd > q; vector < VectorNd > qdot; vector < VectorNd > qddot; vector < VectorNd > tau; CustomJointTypeRevoluteX custom_rx_joint1; CustomJointTypeRevoluteX custom_rx_joint2; CustomJointTypeRevoluteX custom_rx_joint3; }; //============================================================================== // // Tests // UpdateKinematicsCustom // Jacobians // InverseDynamics // CompositeRigidBodyAlgorithm // ForwardDynamics // CalcMInvTimestau // ForwardDynamicsContactsKokkevis // //============================================================================== TEST_FIXTURE ( CustomJointMultiBodyFixture, UpdateKinematics ) { VectorNd test; for(int idx =0; idx < NUMBER_OF_MODELS; ++idx){ int dof = reference_model.at(idx).dof_count; for (unsigned int i = 0; i < dof ; i++) { q.at(idx)[i] = i * 0.1; qdot.at(idx)[i] = i * 0.15; qddot.at(idx)[i] = i * 0.17; } UpdateKinematics (reference_model.at(idx), q.at(idx), qdot.at(idx), qddot.at(idx)); UpdateKinematics (custom_model.at(idx), q.at(idx), qdot.at(idx), qddot.at(idx)); Matrix3d Eref = reference_model.at(idx).X_base[ reference_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].E; Matrix3d Ecus = custom_model.at(idx).X_base[ custom_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].E; Matrix3d Eerr = Eref-Ecus; CHECK_ARRAY_CLOSE ( reference_model.at(idx).X_base[ reference_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].E.data(), custom_model.at(idx).X_base[ custom_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].E.data(), 9, TEST_PREC); CHECK_ARRAY_CLOSE ( reference_model.at(idx).v[ reference_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].data(), custom_model.at(idx).v[ custom_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].data(), 6, TEST_PREC); CHECK_ARRAY_CLOSE ( reference_model.at(idx).a[ reference_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].data(), custom_model.at(idx).a[ custom_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].data(), 6, TEST_PREC); } } TEST_FIXTURE (CustomJointMultiBodyFixture, UpdateKinematicsCustom) { for(int idx =0; idx < NUMBER_OF_MODELS; ++idx){ int dof = reference_model.at(idx).dof_count; for (unsigned int i = 0; i < dof; i++) { q.at(idx)[i] = i * 9.133758561390194e-01; qdot.at(idx)[i] = i * 6.323592462254095e-01; qddot.at(idx)[i] = i * 9.754040499940952e-02; } UpdateKinematicsCustom (reference_model.at(idx), &q.at(idx), NULL, NULL); UpdateKinematicsCustom (custom_model.at(idx), &q.at(idx), NULL, NULL); CHECK_ARRAY_CLOSE ( reference_model.at(idx).X_base[ reference_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].E.data(), custom_model.at(idx).X_base[ custom_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].E.data(), 9, TEST_PREC); //velocity UpdateKinematicsCustom (reference_model.at(idx), &q.at(idx), &qdot.at(idx), NULL); UpdateKinematicsCustom (custom_model.at(idx), &q.at(idx), &qdot.at(idx), NULL); CHECK_ARRAY_CLOSE ( reference_model.at(idx).v[ reference_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].data(), custom_model.at(idx).v[ custom_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].data(), 6, TEST_PREC); //All UpdateKinematicsCustom (reference_model.at(idx), &q.at(idx), &qdot.at(idx), &qddot.at(idx)); UpdateKinematicsCustom (custom_model.at(idx), &q.at(idx), &qdot.at(idx), &qddot.at(idx)); CHECK_ARRAY_CLOSE ( reference_model.at(idx).a[ reference_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].data(), custom_model.at(idx).a[ custom_body_id.at(idx).at(NUMBER_OF_BODIES-1) ].data(), 6, TEST_PREC); } } TEST_FIXTURE (CustomJointMultiBodyFixture, Jacobians) { for(int idx = 0; idx < NUMBER_OF_MODELS; ++idx){ int dof = reference_model.at(idx).dof_count; for (unsigned int i = 0; i < dof; i++) { q.at(idx)[i] = i * 9.133758561390194e-01; qdot.at(idx)[i] = i * 6.323592462254095e-01; qddot.at(idx)[i] = i * 9.754040499940952e-02; } //position UpdateKinematics (reference_model.at(idx), q.at(idx), qdot.at(idx), qddot.at(idx)); UpdateKinematics (custom_model.at(idx), q.at(idx), qdot.at(idx), qddot.at(idx)); //Check the Spatial Jacobian MatrixNd Gref = MatrixNd( MatrixNd::Zero(6,reference_model.at(idx).dof_count)); MatrixNd Gcus = MatrixNd( MatrixNd::Zero(6,reference_model.at(idx).dof_count)); CalcBodySpatialJacobian ( reference_model.at(idx), q.at(idx), reference_body_id.at(idx).at(NUMBER_OF_BODIES-1), Gref); CalcBodySpatialJacobian ( custom_model.at(idx), q.at(idx), custom_body_id.at(idx).at(NUMBER_OF_BODIES-1), Gcus); for(int i=0; i<6;++i){ for(int j=0; j<dof;++j){ CHECK_CLOSE ( Gref(i,j), Gcus(i,j), TEST_PREC); } } //Check the 6d point Jacobian Vector3d point_position (1.1, 1.2, 2.1); CalcPointJacobian6D (reference_model.at(idx), q.at(idx), reference_body_id.at(idx).at(NUMBER_OF_BODIES-1), point_position, Gref); CalcPointJacobian6D (custom_model.at(idx), q.at(idx), custom_body_id.at(idx).at(NUMBER_OF_BODIES-1), point_position, Gcus); for(int i=0; i<6;++i){ for(int j=0; j<dof;++j){ CHECK_CLOSE ( Gref(i,j), Gcus(i,j), TEST_PREC); } } //Check the 3d point Jacobian MatrixNd GrefPt = MatrixNd::Constant (3, reference_model.at(idx).dof_count, 0.); MatrixNd GcusPt = MatrixNd::Constant (3, reference_model.at(idx).dof_count, 0.); CalcPointJacobian (reference_model.at(idx), q.at(idx), reference_body_id.at(idx).at(NUMBER_OF_BODIES-1), point_position, GrefPt); CalcPointJacobian (custom_model.at(idx), q.at(idx), custom_body_id.at(idx).at(NUMBER_OF_BODIES-1), point_position, GcusPt); for(int i=0; i<3;++i){ for(int j=0; j<dof;++j){ CHECK_CLOSE ( GrefPt(i,j), GcusPt(i,j), TEST_PREC); } } } } TEST_FIXTURE (CustomJointMultiBodyFixture, InverseDynamics) { for(int idx =0; idx < NUMBER_OF_MODELS; ++idx){ int dof = reference_model.at(idx).dof_count; for (unsigned int i = 0; i < dof; i++) { q.at(idx)[i] = i * 9.133758561390194e-01; qdot.at(idx)[i] = i * 6.323592462254095e-01; qddot.at(idx)[i] = i * 9.754040499940952e-02; } //position VectorNd tauRef = VectorNd::Zero (reference_model.at(idx).qdot_size); VectorNd tauCus = VectorNd::Zero (reference_model.at(idx).qdot_size); InverseDynamics(reference_model.at(idx), q.at(idx), qdot.at(idx), qddot.at(idx), tauRef); InverseDynamics(custom_model.at(idx), q.at(idx), qdot.at(idx), qddot.at(idx), tauCus); VectorNd tauErr = tauRef-tauCus; CHECK_ARRAY_CLOSE ( tauRef.data(), tauCus.data(), tauRef.rows(), TEST_PREC); } } TEST_FIXTURE (CustomJointMultiBodyFixture, CompositeRigidBodyAlgorithm) { for(int idx =0; idx < NUMBER_OF_MODELS; ++idx){ int dof = reference_model.at(idx).dof_count; for (unsigned int i = 0; i < dof; i++) { q.at(idx)[i] = (i+0.1) * 9.133758561390194e-01; qdot.at(idx)[i] = (i+0.1) * 6.323592462254095e-01; tau.at(idx)[i] = (i+0.1) * 9.754040499940952e-02; } MatrixNd h_ref = MatrixNd::Constant (dof, dof, 0.); VectorNd c_ref = VectorNd::Constant (dof, 0.); VectorNd qddot_zero_ref = VectorNd::Constant (dof, 0.); VectorNd qddot_crba_ref = VectorNd::Constant (dof, 0.); MatrixNd h_cus = MatrixNd::Constant (dof, dof, 0.); VectorNd c_cus = VectorNd::Constant (dof, 0.); VectorNd qddot_zero_cus = VectorNd::Constant (dof, 0.); VectorNd qddot_crba_cus = VectorNd::Constant (dof, 0.); VectorNd qddotRef = VectorNd::Zero (dof); VectorNd qddotCus = VectorNd::Zero (dof); //Ref ForwardDynamics(reference_model.at(idx), q.at(idx), qdot.at(idx), tau.at(idx), qddotRef); CompositeRigidBodyAlgorithm (reference_model.at(idx), q.at(idx), h_ref); InverseDynamics (reference_model.at(idx), q.at(idx), qdot.at(idx), qddot_zero_ref, c_ref); LinSolveGaussElimPivot (h_ref, c_ref * -1. + tau.at(idx), qddot_crba_ref); //Custom ForwardDynamics(custom_model.at(idx), q.at(idx), qdot.at(idx), tau.at(idx), qddotCus); CompositeRigidBodyAlgorithm (custom_model.at(idx), q.at(idx), h_cus); InverseDynamics (custom_model.at(idx), q.at(idx), qdot.at(idx), qddot_zero_cus, c_cus); LinSolveGaussElimPivot (h_cus, c_cus * -1. + tau.at(idx), qddot_crba_cus); CHECK_ARRAY_CLOSE(qddot_crba_ref.data(), qddot_crba_cus.data(), dof, TEST_PREC); } } TEST_FIXTURE (CustomJointMultiBodyFixture, ForwardDynamics) { for(int idx =0; idx < NUMBER_OF_MODELS; ++idx){ int dof = reference_model.at(idx).dof_count; for (unsigned int i = 0; i < dof; i++) { q.at(idx)[i] = (i+0.1) * 9.133758561390194e-01; qdot.at(idx)[i] = (i+0.1) * 6.323592462254095e-01; qddot.at(idx)[i] = (i+0.1) * 2.323592499940952e-01; tau.at(idx)[i] = (i+0.1) * 9.754040499940952e-02; } VectorNd qddotRef = VectorNd::Zero (reference_model.at(idx).qdot_size); VectorNd qddotCus = VectorNd::Zero (reference_model.at(idx).qdot_size); ForwardDynamics(reference_model.at(idx), q.at(idx), qdot.at(idx), tau.at(idx), qddotRef); ForwardDynamics(custom_model.at(idx), q.at(idx), qdot.at(idx), tau.at(idx), qddotCus); CHECK_ARRAY_CLOSE ( qddotRef.data(), qddotCus.data(), dof, TEST_PREC); } } TEST_FIXTURE (CustomJointMultiBodyFixture, CalcMInvTimestau) { for(int idx =0; idx < NUMBER_OF_MODELS; ++idx){ int dof = reference_model.at(idx).dof_count; for (unsigned int i = 0; i < dof; i++) { q.at(idx)[i] = (i+0.1) * 9.133758561390194e-01; tau.at(idx)[i] = (i+0.1) * 9.754040499940952e-02; } //reference VectorNd qddot_minv_ref = VectorNd::Zero(dof); CalcMInvTimesTau(reference_model.at(idx), q.at(idx), tau.at(idx), qddot_minv_ref, true); //custom VectorNd qddot_minv_cus = VectorNd::Zero(dof); CalcMInvTimesTau(custom_model.at(idx), q.at(idx), tau.at(idx), qddot_minv_cus, true); //check. CHECK_ARRAY_CLOSE(qddot_minv_ref.data(), qddot_minv_cus.data(), dof, TEST_PREC); } } TEST_FIXTURE (CustomJointMultiBodyFixture, ForwardDynamicsContactsKokkevis){ for(int idx =0; idx < NUMBER_OF_MODELS; ++idx){ int dof = reference_model.at(idx).dof_count; //Adding a 1 constraint to a system with 1 dof is //a no-no if(dof > 1){ for (unsigned int i = 0; i < dof; i++) { q.at(idx)[i] = (i+0.1) * 9.133758561390194e-01; qdot.at(idx)[i] = (i+0.1) * 6.323592462254095e-01; tau.at(idx)[i] = (i+0.1) * 9.754040499940952e-02; } VectorNd qddot_ref = VectorNd::Zero(dof); VectorNd qddot_cus = VectorNd::Zero(dof); VectorNd qdot_plus_ref = VectorNd::Zero(dof); VectorNd qdot_plus_cus = VectorNd::Zero(dof); Vector3d contact_point ( 0., 1., 0.); ConstraintSet constraint_set_ref; ConstraintSet constraint_set_cus; //Reference constraint_set_ref.AddContactConstraint( reference_body_id.at(idx).at(NUMBER_OF_BODIES-1), contact_point, Vector3d (1., 0., 0.), "ground_x"); constraint_set_ref.AddContactConstraint( reference_body_id.at(idx).at(NUMBER_OF_BODIES-1), contact_point, Vector3d (0., 1., 0.), "ground_y"); constraint_set_ref.Bind (reference_model.at(idx)); //Custom constraint_set_cus.AddContactConstraint( custom_body_id.at(idx).at(NUMBER_OF_BODIES-1), contact_point, Vector3d (1., 0., 0.), "ground_x"); constraint_set_cus.AddContactConstraint( custom_body_id.at(idx).at(NUMBER_OF_BODIES-1), contact_point, Vector3d (0., 1., 0.), "ground_y"); constraint_set_cus.Bind (custom_model.at(idx)); ComputeConstraintImpulsesDirect(reference_model.at(idx), q.at(idx), qdot.at(idx), constraint_set_ref, qdot_plus_ref); ForwardDynamicsContactsKokkevis (reference_model.at(idx), q.at(idx), qdot_plus_ref, tau.at(idx), constraint_set_ref, qddot_ref); ComputeConstraintImpulsesDirect(custom_model.at(idx), q.at(idx), qdot.at(idx), constraint_set_cus, qdot_plus_cus); ForwardDynamicsContactsKokkevis (custom_model.at(idx), q.at(idx), qdot_plus_cus, tau.at(idx), constraint_set_cus, qddot_cus); VectorNd qdot_plus_error = qdot_plus_ref - qdot_plus_cus; VectorNd qddot_error = qddot_ref - qddot_cus; CHECK_ARRAY_CLOSE (qdot_plus_ref.data(), qdot_plus_cus.data(), dof, TEST_PREC); CHECK_ARRAY_CLOSE (qddot_ref.data(), qddot_cus.data(), dof, TEST_PREC); } } } // //Completed? // x : implement test for UpdateKinematicsCustom // x : implement test for Jacobians // x : implement test for InverseDynamics // x : implement test for CompositeRigidBodyAlgorithm // x : implement test for ForwardDynamics // x : implement test for CalcMInvTimestau // x : implement test for ForwardDynamicsContactsKokkevis
[ "43317325+bvsk35@users.noreply.github.com" ]
43317325+bvsk35@users.noreply.github.com
717f3e6fd5cf0b2ed2859c90d8d32a7249ae0fa6
9b1a0e9ac2c5ffc35f368ca5108cd8953eb2716d
/5/Section6-Networking/6.04-FastRPCforOnlineGames-Bae/RPCDuel/lobby.cpp
91b836a81e961c6ede08cf67e372b49f1f4f2d64
[]
no_license
TomasRejhons/gpg-source-backup
c6993579e96bf5a6d8cba85212f94ec20134df11
bbc8266c6cd7df8a7e2f5ad638cdcd7f6298052e
refs/heads/main
2023-06-05T05:14:00.374344
2021-06-16T15:08:41
2021-06-16T15:08:41
377,536,509
2
2
null
null
null
null
UTF-8
C++
false
false
9,242
cpp
#include "stdafx.h" //----------------------------------------------------------------------------- // File: Lobby.cpp // // Desc: DP lobby related routines // // Copyright (C) 1995-2001 Microsoft Corporation. All Rights Reserved. //----------------------------------------------------------------------------- #include "duel.h" #include "lobby.h" //----------------------------------------------------------------------------- // Definitions //----------------------------------------------------------------------------- #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #define TIMERID 1 // Timer ID to use #define TIMERINTERVAL 250 // Timer interval //----------------------------------------------------------------------------- // Globals //----------------------------------------------------------------------------- extern LPDIRECTPLAY4 g_pDP; // DirectPlay object pointer extern LPDPLCONNECTION g_pDPLConnection; // Connection settings extern LPDIRECTPLAYLOBBY3 g_pDPLobby; // Lobby object pointer extern BOOL g_bHostPlayer; // Flag indicating if we are hosting extern HWND g_hwndMain; // Main application window handle extern HINSTANCE g_hInst; // Application instance handle BOOL g_bLobbyMsgSupported; // Lobby messages are supported GUID g_guidPlayer; // This player in this session //----------------------------------------------------------------------------- // Name: DPLobbyRelease() // Desc: Wrapper for DirectPlayLobby Release API //----------------------------------------------------------------------------- HRESULT DPLobbyRelease() { // Cleanup lobby SAFE_DELETE_ARRAY( g_pDPLConnection ); SAFE_RELEASE( g_pDPLobby ); return S_OK; } //----------------------------------------------------------------------------- // Name: DoingLobbyMessages() // Desc: Return TRUE if connected to a lobby and messages are supported. //----------------------------------------------------------------------------- BOOL DoingLobbyMessages() { return( g_pDPLobby && g_bLobbyMsgSupported ); } //----------------------------------------------------------------------------- // Name: LobbyMessageInit() // Desc: Initialize lobby message processing. Must be done while a lobby // connection is open. //----------------------------------------------------------------------------- HRESULT LobbyMessageInit() { if( NULL ==g_pDPLobby ) // Not connected to a lobby return E_FAIL; g_bLobbyMsgSupported = FALSE; // Until we find out otherwise. // Find out if lobby messages are supported by the lobby DPLMSG_GETPROPERTY msgGetProp; ZeroMemory( &msgGetProp, sizeof(DPLMSG_GETPROPERTY) ); msgGetProp.dwType = DPLSYS_GETPROPERTY; msgGetProp.dwRequestID = 1; // guidPlayer is not used msgGetProp.guidPropertyTag = DPLPROPERTY_MessagesSupported; return g_pDPLobby->SendLobbyMessage( DPLMSG_STANDARD, 0, &msgGetProp, sizeof(DPLMSG_GETPROPERTY) ); } //----------------------------------------------------------------------------- // Name: LobbyMessageReceive() // Desc: Check for any lobby messages and handle them // There are two modes: // LMR_CONNECTIONSETTINGS - Waiting only for settings from a lobby // LMR_PROPERTIES - Handle property message responses //----------------------------------------------------------------------------- HRESULT LobbyMessageReceive( DWORD dwMode ) { HRESULT hr = NOERROR; LPVOID lpMsgBuffer = NULL; DWORD dwBufferSize = 0; DWORD dwRequiredSize; DWORD dwMsgFlags; if( NULL == g_pDPLobby ) // No lobby interface return DPERR_NOINTERFACE; while( SUCCEEDED(hr) ) // Get all queued messages { dwRequiredSize = dwBufferSize; hr = g_pDPLobby->ReceiveLobbyMessage( 0, 0, &dwMsgFlags, lpMsgBuffer, &dwRequiredSize ); if( hr == DPERR_BUFFERTOOSMALL ) // Alloc msg buffer and try again { if( NULL == lpMsgBuffer ) lpMsgBuffer = GlobalAllocPtr( GHND, dwRequiredSize ); else lpMsgBuffer = GlobalReAllocPtr( lpMsgBuffer, dwRequiredSize, 0 ); if( NULL == lpMsgBuffer) return DPERR_NOMEMORY; dwBufferSize = dwRequiredSize; hr = S_OK; } else if( SUCCEEDED(hr) && dwRequiredSize >= sizeof(DPLMSG_GENERIC) ) { // Decode the message // Are we just looking for the CONNECTIONSETTINGS msg? if( dwMode == LMR_CONNECTIONSETTINGS ) { if( (dwMsgFlags & DPLMSG_SYSTEM) && ((DPLMSG_GENERIC*)lpMsgBuffer)->dwType == DPLSYS_NEWCONNECTIONSETTINGS ) break; else TRACE(_T("Non CONNECTIONSETTINGS lobby message ignored\n")); } // Otherwise we handle only GetProperty responses else if( (dwMsgFlags & DPLMSG_STANDARD) && ((DPLMSG_GENERIC*)lpMsgBuffer)->dwType == DPLSYS_GETPROPERTYRESPONSE ) { DPLMSG_GETPROPERTYRESPONSE* lpMsgGPR = (DPLMSG_GETPROPERTYRESPONSE*)lpMsgBuffer; if( IsEqualGUID( lpMsgGPR->guidPropertyTag, DPLPROPERTY_MessagesSupported ) ) { if( (BOOL)lpMsgGPR->dwPropertyData[0] ) // Supported { // So request our player instance guid DPLMSG_GETPROPERTY msgGetProp; ZeroMemory(&msgGetProp, sizeof(DPLMSG_GETPROPERTY)); msgGetProp.dwType = DPLSYS_GETPROPERTY; msgGetProp.dwRequestID = 2; // guidPlayer is left NULL msgGetProp.guidPropertyTag = DPLPROPERTY_PlayerGuid; hr = g_pDPLobby->SendLobbyMessage( DPLMSG_STANDARD, 0, &msgGetProp, sizeof(DPLMSG_GETPROPERTY) ); hr = S_OK; // keep fetching messages } else // not supported so close up shop { TRACE(_T("Lobby Messages not supported\n")); DPLobbyRelease(); break; } } else if( IsEqualGUID( lpMsgGPR->guidPropertyTag, DPLPROPERTY_PlayerGuid ) ) { // Have our player guid, ready to send property msgs g_guidPlayer = ( (DPLDATA_PLAYERGUID*) &lpMsgGPR->dwPropertyData)->guidPlayer; g_bLobbyMsgSupported = TRUE; } } else TRACE(_T("Unrecognized lobby message ignored\n")); } } if( lpMsgBuffer ) GlobalFreePtr( lpMsgBuffer ); return hr; } //----------------------------------------------------------------------------- // Name: LobbyMessageSetProperty() // Desc: Send a SetProperty message //----------------------------------------------------------------------------- HRESULT LobbyMessageSetProperty( const GUID* pPropTagGUID, VOID* pData, DWORD dwDataSize ) { HRESULT hr; LPBYTE lpBuffer; LPDPLMSG_SETPROPERTY lpMsgSP; DWORD dwMsgSize; if( NULL == g_pDPLobby ) return DPERR_NOCONNECTION; if( NULL == g_bLobbyMsgSupported ) return DPERR_UNAVAILABLE; // Allocate and pack up the message // Property data starts at dwPropertyData[0] for the size calculation dwMsgSize = sizeof(DPLMSG_SETPROPERTY) - sizeof(DWORD) + dwDataSize; lpBuffer = (LPBYTE)GlobalAllocPtr(GHND, dwMsgSize); if( NULL == lpBuffer ) return (DPERR_NOMEMORY); lpMsgSP = (LPDPLMSG_SETPROPERTY)lpBuffer; lpMsgSP->dwType = DPLSYS_SETPROPERTY; lpMsgSP->dwRequestID = DPL_NOCONFIRMATION; lpMsgSP->guidPlayer = g_guidPlayer; // player property assumed lpMsgSP->guidPropertyTag = (*pPropTagGUID); lpMsgSP->dwDataSize = dwDataSize; memcpy( lpMsgSP->dwPropertyData, pData, dwDataSize ); hr = g_pDPLobby->SendLobbyMessage( DPLMSG_STANDARD, 0, lpBuffer, dwMsgSize ); GlobalFreePtr( lpBuffer ); return hr; }
[ "t.rejhons@gmail.com" ]
t.rejhons@gmail.com
61e7233b2729ce3a145e3e70c25003f11121c9ff
37b06470bea58c0e17e1e2f8cbfed105f02c09b3
/Grains_autogen/moc_compilation.cpp
4a4f38dda9cd80b5cca24437329b64d92751a800
[]
no_license
edarles/Grain
7e56bc6962380a9dce9b6f17a2eca0f6027a49fc
e197672b637e2de7c14aa188d2abf1b87961454f
refs/heads/master
2020-03-23T13:06:17.628516
2018-07-19T15:33:44
2018-07-19T15:33:44
141,600,131
0
0
null
null
null
null
UTF-8
C++
false
false
82
cpp
/* This file is autogenerated, do not edit*/ #include "U6PKXSNLUA/moc_window.cpp"
[ "emmanuelle.darles@univ-poitiers.fr" ]
emmanuelle.darles@univ-poitiers.fr