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
a26827b2ff207984dcec412d67bd7db20d3aa01d
244ec5370d56748826d672ee50fd2056feaf5f29
/Patient.hpp
4657b1d94038dd57b7acf94bb1d758c2977e7e93
[]
no_license
werd0n4/hospital-simulation
100d1bcc421ed2706b6876da66609472d19c8e73
0766f91f8444d0036094a61111144df302c8e826
refs/heads/master
2022-12-03T23:53:19.543835
2020-08-20T19:38:42
2020-08-20T19:38:42
277,548,092
0
0
null
null
null
null
UTF-8
C++
false
false
1,010
hpp
#pragma once #include "Rehabilitation.hpp" #include "Examination.hpp" #include "Reception.hpp" #include "OperatingRoom.hpp" extern std::mutex refresh_mtx; extern bool running; class Rehabilitation; class Reception; class Patient{ private: int time; const int y_max = getmaxy(stdscr); const int x_max = getmaxx(stdscr); const int win_height = 3; const int win_width = x_max/4; std::string status; WINDOW* status_window; std::vector<Examination>& exams; OperatingRoom& operating_room; Rehabilitation& rehab_room; Reception& reception; public: int id; int bed_id; Patient(int _id, std::vector<Examination>&, OperatingRoom&, Rehabilitation&, Reception&); void draw(); void clear_status_window(); void change_status(const std::string&); void registration(); void go_for_exam(); void undergo_surgery(); void rehabilitation(); void discharge(); void treatment(); bool operator==(const Patient&); };
[ "filipgajewski4@gmail.com" ]
filipgajewski4@gmail.com
395c4ec946fb09eff53dec58593cb0a0cb74e86d
d31aed88f751ec8f9dd0a51ea215dba4577b5a9b
/plugins/core/landscape_model/sources/ai/ai_goals/lm_defend_goal.hpp
f36cc4879b428b572316d1834f33b1e3875398d9
[]
no_license
valeriyr/Hedgehog
56a4f186286608140f0e4ce5ef962e9a10b123a8
c045f262ca036570416c793f589ba1650223edd9
refs/heads/master
2016-09-05T20:00:51.747169
2015-09-04T05:21:38
2015-09-04T05:21:38
3,336,071
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
hpp
#ifndef __LM_DEFEND_GOAL_HPP__ #define __LM_DEFEND_GOAL_HPP__ /*---------------------------------------------------------------------------*/ #include "landscape_model/sources/ai/ai_goals/lm_igoal.hpp" /*---------------------------------------------------------------------------*/ namespace Plugins { namespace Core { namespace LandscapeModel { /*---------------------------------------------------------------------------*/ class DefendGoal : public Tools::Core::BaseWrapper< IGoal > { /*---------------------------------------------------------------------------*/ public: /*---------------------------------------------------------------------------*/ DefendGoal(); ~DefendGoal(); /*---------------------------------------------------------------------------*/ /*virtual*/ bool process(); /*---------------------------------------------------------------------------*/ private: /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ }; /*---------------------------------------------------------------------------*/ } // namespace LandscapeModel } // namespace Core } // namespace Plugins /*---------------------------------------------------------------------------*/ #endif // __LM_DEFEND_GOAL_HPP__
[ "valeriy.reutov@gmail.com" ]
valeriy.reutov@gmail.com
f750ef4e312cd8c53290339c5604a483531c56f7
fac3afeeb7be731a3c968b466bd69ae01e19606b
/zpar-0.7/src/chinese/segmentor/agendachart.cpp
fdccd858d2d5c673b8dfdca1057d05263e5af14b
[]
no_license
aminorex/nlp
3a03b280efa20f828bd13eabbcf4097e3daf29b9
e93eb2896213834c99cd1f4861ecff19c996382f
refs/heads/master
2021-01-19T19:35:05.786046
2015-07-18T00:34:00
2015-07-18T00:34:00
30,219,876
1
2
null
null
null
null
UTF-8
C++
false
false
15,037
cpp
// Copyright (C) University of Oxford 2010 /**************************************************************** * * * segmentor.cpp - the chinese segmentor * * * * This implementation uses beam search ageanda+chart * * * * Author: Yue Zhang * * * * Computing Laboratory, Oxford. 2006.10 * * * ****************************************************************/ #include "segmentor.h" using namespace chinese; using namespace chinese::segmentor; CWord g_emptyWord(""); /*=============================================================== * * CFeatureHandle - handles the features for the segmentor * *==============================================================*/ /*--------------------------------------------------------------- * * getGlobalScore - get the global score for sentence * *--------------------------------------------------------------*/ int CFeatureHandle::getGlobalScore(const CStringVector* sentence, const CStateItem* item){ int nReturn = 0; for (int i=0; i<item->m_nLength; ++i) nReturn += getLocalScore(sentence, item, i); return nReturn; } /*--------------------------------------------------------------- * * getLocalScore - get the local score for a word in sentence * * When bigram is needed from the beginning of sentence, the empty word are used. * * This implies that empty words should not be used in other * situations. * *--------------------------------------------------------------*/ int CFeatureHandle::getLocalScore(const CStringVector* sentence, const CStateItem* item, int index){ static int nReturn; static int score_index; static int tmp_i, tmp_j; static int length, last_length, word_length; static int start, end, last_start, last_end; score_index = m_bTrain ? CScore<SCORE_TYPE>::eNonAverage : CScore<SCORE_TYPE>::eAverage ; start = item->getWordStart(index); end = item->getWordEnd(index); length = item->getWordLength(index); last_start = index>0 ? item->getWordStart(index-1) : 0; // make sure that this is only used when index>0 last_end = index>0 ? item->getWordEnd(index-1) : 0; // make sure that this is only used when index>0 last_length = index>0 ? item->getWordLength(index-1) : 0; // similar to the above word_length = length ; // abstd::cout the words const CWord &word=m_parent->findWordFromCache(start, length, sentence); const CWord &last_word = index>0 ? m_parent->findWordFromCache(last_start, last_length, sentence) : g_emptyWord; // use empty word for sentence beginners. static CTwoWords two_word; two_word.refer(&word, &last_word); // abstd::cout the chars const CWord &first_char=m_parent->findWordFromCache(start, 1, sentence); const CWord &last_char=m_parent->findWordFromCache(end, 1, sentence); const CWord &first_char_last_word = index>0 ? m_parent->findWordFromCache(last_start, 1, sentence) : g_emptyWord; const CWord &last_char_last_word = index>0 ? m_parent->findWordFromCache(last_end, 1, sentence) : g_emptyWord; static CTwoWords first_and_last_char, lastword_firstchar, currentword_lastchar, firstcharlastword_word, lastword_lastchar; first_and_last_char.refer(&first_char, &last_char); const CWord &two_char = index>0 ? m_parent->findWordFromCache(last_end, 2, sentence) : g_emptyWord; if (index>0) { lastword_firstchar.refer(&last_word, &first_char); currentword_lastchar.refer(&word, &last_char_last_word); firstcharlastword_word.refer(&first_char_last_word, &first_char); lastword_lastchar.refer(&last_char_last_word, &last_char); } // abstd::cout the length if(length>LENGTH_MAX-1)length=LENGTH_MAX-1; if(last_length>LENGTH_MAX-1)last_length=LENGTH_MAX-1; // // adding scores with features // nReturn = m_weights.m_mapSeenWords.getScore(word, score_index); nReturn += m_weights.m_mapLastWordByWord.getScore(two_word, score_index); if (length==1) nReturn += m_weights.m_mapOneCharWord.getScore(word, score_index); else { nReturn += m_weights.m_mapFirstAndLastChars.getScore(first_and_last_char, score_index); for (int j=0; j<word_length-1; j++) nReturn += m_weights.m_mapConsecutiveChars.getScore(m_parent->findWordFromCache(start+j, 2, sentence), score_index); nReturn += m_weights.m_mapLengthByFirstChar.getScore(std::make_pair(first_char, length), score_index); nReturn += m_weights.m_mapLengthByLastChar.getScore(std::make_pair(last_char, length), score_index); } if (index>0) { nReturn += m_weights.m_mapSeparateChars.getScore(two_char, score_index); nReturn += m_weights.m_mapLastWordFirstChar.getScore(lastword_firstchar, score_index); nReturn += m_weights.m_mapCurrentWordLastChar.getScore(currentword_lastchar, score_index); nReturn += m_weights.m_mapFirstCharLastWordByWord.getScore(firstcharlastword_word, score_index); nReturn += m_weights.m_mapLastWordByLastChar.getScore(lastword_lastchar, score_index); nReturn += m_weights.m_mapLengthByLastWord.getScore(std::make_pair(last_word, length), score_index); nReturn += m_weights.m_mapLastLengthByWord.getScore(std::make_pair(word, last_length), score_index); } return nReturn; } /*--------------------------------------------------------------- * * updateScoreVector - update the score std::vector by input * this is used in training to adjust params * * Inputs: the outout and the correct examples * * Affects: m_bScoreModified, which leads to saveScores on destructor * *--------------------------------------------------------------*/ void CFeatureHandle::updateScoreVector(const CStringVector* outout, const CStringVector* correct, int round) { if ( *outout == *correct ) return; for (int i=0; i<outout->size(); ++i) updateLocalFeatureVector(eSubtract, outout, i, round); for (int j=0; j<correct->size(); ++j) updateLocalFeatureVector(eAdd, correct, j, round); m_bScoreModified = true; } /*--------------------------------------------------------------- * * updateLocalFeatureVector - update the given feature vector with * the local feature vector for a given * sentence. This is a private member only * used by updateGlobalFeatureVector and is * only used for training. * *--------------------------------------------------------------*/ void CFeatureHandle::updateLocalFeatureVector(SCORE_UPDATE method, const CStringVector* outout, int index, int round) { // abstd::cout words CWord word = outout->at(index); CWord last_word = index>0 ? outout->at(index-1) : g_emptyWord; CTwoWords two_word; two_word.allocate(word.str(), last_word.str()); CStringVector chars; chars.clear(); getCharactersFromUTF8String(word.str(), &chars); // abstd::cout length int length = getUTF8StringLength(word.str()); if (length > LENGTH_MAX-1) length = LENGTH_MAX-1; int last_length = getUTF8StringLength(last_word.str()); if (last_length > LENGTH_MAX-1) last_length = LENGTH_MAX-1; // abstd::cout chars CWord first_char = getFirstCharFromUTF8String(word.str()); CWord last_char = getLastCharFromUTF8String(word.str()); CWord first_char_last_word = index>0 ? getFirstCharFromUTF8String(last_word.str()) : g_emptyWord; CWord last_char_last_word = index>0 ? getLastCharFromUTF8String(last_word.str()) : g_emptyWord; CWord two_char = index>0 ? last_char_last_word.str() + first_char.str() : g_emptyWord; CTwoWords first_and_last_char, lastword_firstchar, currentword_lastchar, firstcharlastword_word, lastword_lastchar; first_and_last_char.allocate(first_char.str(), last_char.str()); if (index>0) { lastword_firstchar.allocate(last_word.str(), first_char.str()); currentword_lastchar.allocate(word.str(), last_char_last_word.str()); firstcharlastword_word.allocate(first_char_last_word.str(), first_char.str()); lastword_lastchar.allocate(last_char_last_word.str(), last_char.str()); } SCORE_TYPE amount = ( (method==eAdd) ? 1 : -1 ) ; m_weights.m_mapSeenWords.updateScore(word, amount, round); m_weights.m_mapLastWordByWord.updateScore(two_word, amount, round); if (length==1) m_weights.m_mapOneCharWord.updateScore(first_char, amount, round); else { m_weights.m_mapFirstAndLastChars.updateScore(first_and_last_char, amount, round); for (int j=0; j<chars.size()-1; j++) { m_weights.m_mapConsecutiveChars.updateScore(chars[j]+chars[j+1], amount, round); } m_weights.m_mapLengthByFirstChar.updateScore(std::make_pair(first_char, length), amount, round); m_weights.m_mapLengthByLastChar.updateScore(std::make_pair(last_char, length), amount, round); } if (index>0) { m_weights.m_mapSeparateChars.updateScore(two_char, amount, round); m_weights.m_mapLastWordFirstChar.updateScore(lastword_firstchar, amount, round); m_weights.m_mapCurrentWordLastChar.updateScore(currentword_lastchar, amount, round); m_weights.m_mapFirstCharLastWordByWord.updateScore(firstcharlastword_word, amount, round); m_weights.m_mapLastWordByLastChar.updateScore(lastword_lastchar, amount, round); m_weights.m_mapLengthByLastWord.updateScore(std::make_pair(last_word, length), amount, round); m_weights.m_mapLastLengthByWord.updateScore(std::make_pair(word, last_length), amount, round); } } /*=============================================================== * * CSegmentor - the segmentor for Chinese * *==============================================================*/ /*--------------------------------------------------------------- * * train - do automatic training process * [NOT USED] * *--------------------------------------------------------------*/ void CSegmentor::train(const CStringVector* sentence, const CStringVector* correct, int & round) { assert(1==0); // train by the configurable training algorithm } /*--------------------------------------------------------------- * * segment - do word segmentation on a sentence * *--------------------------------------------------------------*/ void CSegmentor::segment(const CStringVector* sentence_input, CStringVector *vReturn, double *out_scores, int nBest) { clock_t total_start_time = clock();; const CStateItem *pGenerator, *pCandidate; CStateItem tempState; unsigned index; // the index of the current char unsigned j, k; // temporary index int subtract_score; // the score to be subtracted (previous item) static CStateItem best_bigram; int start_index; int word_length; int generator_index; static CStringVector sentence; static CRule rules(m_Feature->m_bRule); rules.segment(sentence_input, &sentence); const unsigned length = sentence.size(); assert(length<MAX_SENTENCE_SIZE); assert(vReturn!=NULL); //clock_t start_time = clock(); TRACE("Initialising the segmentation process..."); vReturn->clear(); clearWordCache(); m_Chart.clear(); tempState.clear(); m_Chart[0]->insertItem(&tempState); TRACE("Segmenting started"); for (index=0; index<length; index++) { // m_Chart index 1 correspond to the first char m_Chart[index+1]; // control for the ending character of the candidate if ( index < length-1 && rules.canSeparate(index+1)==false ) continue ; start_index = index-1 ; // the end index of last word word_length = 1 ; // current word length // enumerating the start index // =========================== // the start index of the word is actually start_index + 1 while( start_index >= -1 && word_length <= MAX_WORD_SIZE ) { // control for the starting character of the candidate // --------------------------------------------------- while ( start_index >= 0 && rules.canSeparate(start_index+1)==false ) start_index-- ; // start the search process // ------------------------ for ( generator_index = 0 ; generator_index < m_Chart[ start_index+1 ]->size() ; ++ generator_index ) { pGenerator = m_Chart[ start_index+1 ]->item( generator_index ) ; tempState.copy( pGenerator ) ; tempState.append( index ) ; tempState.m_nScore += m_Feature->getLocalScore( &sentence, &tempState, tempState.m_nLength-1 ) ; if (nBest==1) { if ( generator_index == 0 || tempState.m_nScore > best_bigram.m_nScore ) { best_bigram.copy(&tempState); //@@@ } } else { m_Chart[ index+1 ]->insertItem( &tempState ); } } if (nBest==1) { m_Chart[ index+1 ]->insertItem( &best_bigram ); //@@@ } //@@@ // control the first character of the candidate if ( rules.canAppend(start_index+1)==false ) break ; // update start index and word len --start_index ; ++word_length ; }//start_index } // now generate outout sentence // n-best list will be stored in array // from the addr vReturn TRACE("Outputing sentence"); for (k=0; k<nBest; ++k) { // clear vReturn[k].clear(); if (out_scores!=NULL) out_scores[k] = 0; // assign retval if (k<m_Chart[length]->size()) { pGenerator = m_Chart[length]->bestItem(k); for (j=0; j<pGenerator->m_nLength; j++) { std::string temp = ""; for (unsigned l = pGenerator->getWordStart(j); l <= pGenerator->getWordEnd(j); ++l) { assert(sentence.at(l)!=" "); // [SPACE] temp += sentence.at(l); } vReturn[k].push_back(temp); } if (out_scores!=NULL) out_scores[k] = pGenerator->m_nScore; } } TRACE("Done, the best score: " << pGenerator->m_nScore); TRACE("total time spent: " << double(clock() - total_start_time)/CLOCKS_PER_SEC); }
[ "agit@southoftheclouds.net" ]
agit@southoftheclouds.net
828513e14e1a79c7d306549a5d0c6aa9d69b6763
196fc6d52f1aece28818b85daefed7777b999099
/GUI/Ape/mainwindow.h
facd647757da272e0ea556e4a508a6a9c51411fa
[]
no_license
sehwan72/Ape
f29b11f8b29c6280f97a02889d84bb86c1abd1d0
0429daffed2d58665e064033373ea56ffa270cf7
refs/heads/master
2021-01-10T04:57:09.319444
2013-04-17T06:35:50
2013-04-17T06:35:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,975
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../../src/Ape.h" #include "../../src/Process.h" #include "../../src/Sys.h" #include <QTimer> #include <QMenu> #include <QMessageBox> #include <QTableWidget> #include <QString> #include <condition_variable> #include <filesinusedialog.h> #include <aboutdialog.h> #include <math.h> #include <time.h> #include <asm/param.h> #include <QPropertyAnimation> #include <QShortcut> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); int addLine(Process *, int); Ape *ape; void clearTable(); private: Ui::MainWindow *ui; const char* itoa(int); QTimer *timer; SortBy sortSetting; bool sortReverse; void myUIInit(); void colorRows(); int getParentRow(int); Process *getProcessAtRow(int); Process *currentProcess; unsigned int currentPID; void setCurrentProcess(Process *); void resetCurrentProcess(); void showFilesInUse(); FilesInUseDialog filesInUseList; AboutDialog aboutApe; void showSysInfo(); void updateInfoTab(); void updateMemoryMap(); QPropertyAnimation *cmdFrame; QShortcut *cmdShortcut; void updateStatusBar(char* message = "No process selected"); protected: void closeEvent(QCloseEvent *); private slots: void updateUI(); void showProcessContextMenu(const QPoint&); void sortTable(int); void doubleClicked(QTableWidgetItem *); void toggleCmd(); void handleMenuBar(QAction*); void on_sigkillButton_clicked(); void on_memmapButton_clicked(); void on_sigintButton_clicked(); void on_sigtermButton_clicked(); void on_sigstopButton_clicked(); void on_sendsigButton_clicked(); void on_coredumpButton_clicked(); }; #endif // MAINWINDOW_H
[ "sehwan@2112-Ubuntu.(none)" ]
sehwan@2112-Ubuntu.(none)
9e43893d4a513c77ea6e089a4015839a201416a3
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/clang/include/clang/Basic/OpenMPKinds.h
5b4573124f21fe153d0f2c53b2bc433e86ececbe
[ "MIT", "NCSA" ]
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,809
h
//===--- OpenMPKinds.h - OpenMP enums ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines some OpenMP-specific enums and functions. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_BASIC_OPENMPKINDS_H #define LLVM_CLANG_BASIC_OPENMPKINDS_H #include "llvm/ADT/StringRef.h" namespace clang { /// \brief OpenMP directives. enum OpenMPDirectiveKind { OMPD_unknown = 0, #define OPENMP_DIRECTIVE(Name) \ OMPD_##Name, #include "clang/Basic/OpenMPKinds.def" NUM_OPENMP_DIRECTIVES }; /// \brief OpenMP clauses. enum OpenMPClauseKind { OMPC_unknown = 0, #define OPENMP_CLAUSE(Name, Class) \ OMPC_##Name, #include "clang/Basic/OpenMPKinds.def" OMPC_threadprivate, NUM_OPENMP_CLAUSES }; /// \brief OpenMP attributes for 'default' clause. enum OpenMPDefaultClauseKind { OMPC_DEFAULT_unknown = 0, #define OPENMP_DEFAULT_KIND(Name) \ OMPC_DEFAULT_##Name, #include "clang/Basic/OpenMPKinds.def" NUM_OPENMP_DEFAULT_KINDS }; OpenMPDirectiveKind getOpenMPDirectiveKind(llvm::StringRef Str); const char *getOpenMPDirectiveName(OpenMPDirectiveKind Kind); OpenMPClauseKind getOpenMPClauseKind(llvm::StringRef Str); const char *getOpenMPClauseName(OpenMPClauseKind Kind); unsigned getOpenMPSimpleClauseType(OpenMPClauseKind Kind, llvm::StringRef Str); const char *getOpenMPSimpleClauseTypeName(OpenMPClauseKind Kind, unsigned Type); bool isAllowedClauseForDirective(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind); } #endif
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
e30d5bc4774ed18ef3fbf8c935eae8cf4214f29b
da5c9b96d42cc280e3866c6fc242c7f85bc891f7
/Source/Alimer/Base/HashMap.h
57c3ca6c30f39ca5efd57cf34e80ee077d3fd3fd
[ "MIT", "Zlib" ]
permissive
parhelia512/alimer
641699a65f07f5810527b1ae3785ea5d43b751bf
b46c8b7bdbf11f2f6305a10d5372dbc61b595ab1
refs/heads/master
2020-03-15T04:22:04.540043
2018-05-02T18:46:15
2018-05-02T18:46:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,454
h
// // Alimer is based on the Turso3D codebase. // Copyright (c) 2018 Amer Koleci and contributors. // // 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. // #pragma once #include "../PlatformDef.h" #include <memory> #include <unordered_map> namespace Alimer { using Hash = uint64_t; struct UnityHasher { inline size_t operator()(uint64_t hash) const { return hash; } }; template <typename T> using HashMap = std::unordered_map<Hash, T, UnityHasher>; class Hasher { public: template <typename T> inline void Data(const T *data, size_t size) { size /= sizeof(*data); for (size_t i = 0; i < size; i++) { _value = (_value * 0x100000001b3ull) ^ data[i]; } } inline void UInt32(uint32_t value) { _value = (_value * 0x100000001b3ull) ^ value; } inline void SInt32(int32_t value) { UInt32(uint32_t(value)); } inline void Float(float value) { union { float f32; uint32_t u32; } u; u.f32 = value; UInt32(u.u32); } inline void UInt64(uint64_t value) { UInt32(value & 0xffffffffu); UInt32(value >> 32); } inline void Pointer(const void *ptr) { UInt64(reinterpret_cast<uintptr_t>(ptr)); } inline void String(const char *str) { char c; while ((c = *str++) != '\0') { UInt32(uint8_t(c)); } } inline Hash GetValue() const { return _value; } private: Hash _value = 0xcbf29ce484222325ull; }; }
[ "amerkoleci@gmail.com" ]
amerkoleci@gmail.com
d9fd14fd1f3d3a8331b79f8371ee316ee839a341
7e762e9dda12e72f96718ef7bec81bca85f3937a
/TowerOfBabylon.cpp
e436d0aa5da179a93018846bb44a64aa602a12f7
[]
no_license
ShravanCool/spoj-classical
b9bd563a28523ad8d626c867f54646d839302ce9
448bf7745c65f6552fb00b32a827044bd1528925
refs/heads/master
2020-05-31T06:48:59.737307
2019-03-30T16:46:07
2019-03-30T16:46:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,673
cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; struct Box { int L, B, H; }; int findMaxStackHt(vector<Box>& arr); bool myComp(Box a, Box b) { return a.L*a.B > b.L*b.B; } int main() { while(true) { int N; cin >> N; if(N == 0) break; vector<Box> arr(N); for(int i = 0; i < N; i++) cin >> arr[i].H >> arr[i].B >> arr[i].L; int ans = findMaxStackHt(arr); cout << ans << endl; } return 0; } int findMaxStackHt(vector<Box>& arr) { vector<Box> possibleRotations; for(int i = 0; i < arr.size(); i++) { Box aBox = arr[i]; possibleRotations.push_back(aBox); aBox.H = arr[i].B; aBox.L = std::max(arr[i].H, arr[i].L); aBox.B = std::min(arr[i].H, arr[i].L); possibleRotations.push_back(aBox); aBox.H = arr[i].L; aBox.L = std::max(arr[i].B, arr[i].H); aBox.B = std::min(arr[i].B, arr[i].H); possibleRotations.push_back(aBox); } std::sort(possibleRotations.begin(), possibleRotations.end(), myComp); vector<int> msh(possibleRotations.size()); for(int i = 0; i < msh.size(); i++) msh[i] = possibleRotations[i].H; for(int i = 1; i < msh.size(); i++) { for(int j = 0; j < i; j++) { if(((possibleRotations[i].B < possibleRotations[j].B && possibleRotations[i].L < possibleRotations[j].L)|| (possibleRotations[j].L > possibleRotations[i].B && possibleRotations[j].B > possibleRotations[i].L)) && msh[i] < msh[j] + possibleRotations[i].H) msh[i] = msh[j] + possibleRotations[i].H; } } int ans = -1; for(int i = 0; i < msh.size(); i++) ans = std::max(msh[i], ans); return ans; }
[ "rohankanojia420@gmail.com" ]
rohankanojia420@gmail.com
863a3fd852c268a5811896ecccc206d5e47b4c15
2ad7f978210e0a4b090dd5bbb7739069d39c59bd
/RM6623-arduino-library/RM6623.h
b97bf153c914153b8c3e8b369314f4ac9e17dd27
[]
no_license
BGD-Libraries/RM-Libraries
780450897c9ff8214fb96ac9f7d86d61ee2df92c
b3a78094ae5773316e1864a6de7c6c180bcae986
refs/heads/master
2021-07-04T11:13:20.936077
2017-09-27T01:20:41
2017-09-27T01:20:41
104,956,070
0
0
null
null
null
null
UTF-8
C++
false
false
955
h
#ifndef _RM6623_H_ #define _RM6623_H_ #include <stdint.h> #if defined(ARDUINO)&&ARDUINO>=100 #include "Arduino.h" #else #include "WProgram.h" #endif class RM6623_ { public: RM6623_(); void pack(uint8_t *tx_data,int16_t yaw,int16_t pitch,int16_t roll); bool unpack(uint32_t ID,uint8_t len,uint8_t *rx_data); uint16_t encoder (uint32_t ID); double angle (uint32_t ID); int16_t real_current(uint32_t ID); int16_t set_current (uint32_t ID); uint8_t hall (uint32_t ID); const uint32_t yaw_ID =0x205; const uint32_t pitch_ID =0x206; const uint32_t roll_ID =0x207; const uint32_t tx_ID =0x1ff; private: typedef union { struct { unsigned encoder:16; int real_current:16; int set_current:16; unsigned hall:8; }; unsigned char buf[8]; }RM6623_rx_data; RM6623_rx_data _Pitch; RM6623_rx_data _Roll; RM6623_rx_data _Yaw; }; extern RM6623_ RM6623; #endif
[ "158964215@qq.com" ]
158964215@qq.com
efbeb3fae3b2bcc119f504d79c7e1d0692a32c46
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14552/function14552_schedule_45/function14552_schedule_45.cpp
f79ca16a477f7cd1d0f048ba702fafc65e89cead
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,687
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14552_schedule_45"); constant c0("c0", 128), c1("c1", 64), c2("c2", 128), c3("c3", 64); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06"); input input00("input00", {i3}, p_int32); input input01("input01", {i0, i1}, p_int32); input input02("input02", {i0, i1, i2}, p_int32); input input03("input03", {i1}, p_int32); input input04("input04", {i3}, p_int32); input input05("input05", {i3}, p_int32); computation comp0("comp0", {i0, i1, i2, i3}, input00(i3) * input01(i0, i1) * input02(i0, i1, i2) + input03(i1) * input04(i3) + input05(i3)); comp0.tile(i0, i1, i2, 128, 64, 32, i01, i02, i03, i04, i05, i06); comp0.parallelize(i01); buffer buf00("buf00", {64}, p_int32, a_input); buffer buf01("buf01", {128, 64}, p_int32, a_input); buffer buf02("buf02", {128, 64, 128}, p_int32, a_input); buffer buf03("buf03", {64}, p_int32, a_input); buffer buf04("buf04", {64}, p_int32, a_input); buffer buf05("buf05", {64}, p_int32, a_input); buffer buf0("buf0", {128, 64, 128, 64}, p_int32, a_output); input00.store_in(&buf00); input01.store_in(&buf01); input02.store_in(&buf02); input03.store_in(&buf03); input04.store_in(&buf04); input05.store_in(&buf05); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf0}, "../data/programs/function14552/function14552_schedule_45/function14552_schedule_45.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
a0774aa386e6292733b3dff6c3a6fbf3bfcb6768
2367e774d643dce26de46053dca007af49a518b3
/7-b28-2/source/100384-7772232/6-b6.cpp
cc7d0471f18af72d674b8cdc3abed20dd4b157c7
[]
no_license
yzy2018YZY/CppCourse2
820cde4c1ba575a3499a4caa6687402b9b51d8a6
e2c61e0281f3ae768505766a1e9d3a495599897c
refs/heads/master
2020-05-18T12:36:19.282539
2019-06-30T13:27:35
2019-06-30T13:27:35
184,412,681
1
0
null
null
null
null
GB18030
C++
false
false
34,098
cpp
/*7772232 数据科学与大数据技术 梅超风 7772256 托雷 */ #include <iostream> using namespace std; /* 函数的原型定义不准变 */ int tj_strlen(const char *str); char *tj_strcat(char *s1, const char *s2); char *tj_strcpy(char *s1, const char *s2); char *tj_strncpy(char *s1, const char *s2, const int len); int tj_strcmp(const char *s1, const char *s2); int tj_strcasecmp(const char *s1, const char *s2); int tj_strncmp(const char *s1, const char *s2, const int len); int tj_strcasencmp(const char *s1, const char *s2, const int len); char *tj_strupr(char *str); char *tj_strlwr(char *str); int tj_strchr(const char *str, const char ch); int tj_strstr(const char *str, const char *substr); int tj_strrchr(const char *str, const char ch); int tj_strrstr(const char *str, const char *substr); char *tj_strrev(char *str); /* ----- 不允许定义任何形式的全局数组!!!!! ----- */ /* 函数实现部分,{ }内的东西可以任意调整,目前的return只是一个示例,可改变 */ int tj_strlen(const char *str) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int num=0; if (str==0) return num; for (;*str!=0;str++) num++; return num; } char *tj_strcat(char *s1, const char *s2) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ char *head=s1; if (s1==0) return 0; if (s2==0) return s1; for (;*s1!=0;s1++) ; for (;*s2!=0;s1++,s2++) *s1=*s2; *s1=0; s1=head; return s1; } char *tj_strcpy(char *s1, const char *s2) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ char *head=s1; if (s1==0) return 0; if (s2==0){ *s1=0; return s1; } for (;*s2!=0;s1++,s2++) *s1=*s2; *s1=0; s1=head; return s1; } char *tj_strncpy(char *s1, const char *s2, const int len) { char *head=s1; int n=0; if (s1==0) return 0; if (s2==0){ return s1; } for (;*s2!=0;s1++,s2++){ *s1=*s2; n++; if (n==len) break; } s1=head; return s1; } int tj_strcmp(const char *s1, const char *s2) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int ASC1=0,ASC2=0,flag=0; if (s1==0 && s2==0) return 0; if (s1==0) return -1; if (s2==0) return 1; for (;*s1!=0 || *s2!=0;s1++,s2++){ if (*s1!=*s2) return (*s1-*s2); else if (*s1==0 && *s2!=0) return *s2; else if (*s1!=0 && *s2==0) return *s1; else continue; } return 0; } int tj_strcasecmp(const char *s1, const char *s2) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int ASC1=0,ASC2=0,flag=0; if (s1==0 && s2==0) return 0; if (s1==0) return -1; if (s2==0) return 1; for (;*s1!=0 || *s2!=0;s1++,s2++){ if (*s1!=*s2){ if (*s1==*s2+32 || *s1==*s2-32) continue; else return (*s1-*s2); } else if (*s1==0 && *s2!=0) return *s2; else if (*s1!=0 && *s2==0) return *s1; else continue; } return 0; } int tj_strncmp(const char *s1, const char *s2, const int len) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int ASC1=0,ASC2=0,flag=0,n=0; if (s1==0 && s2==0) return 0; if (s1==0) return -1; if (s2==0) return 1; for (;*s1!=0 || *s2!=0;s1++,s2++){ if (*s1!=*s2) return (*s1-*s2); if (*s1==0 && *s2!=0) return *s2; if (*s1!=0 && *s2==0) return *s1; n++; if (n==len) break; } return flag; return 0; } int tj_strcasencmp(const char *s1, const char *s2, const int len) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int ASC1=0,ASC2=0,flag=0,n=0; if (s1==0 && s2==0) return 0; if (s1==0) return -1; if (s2==0) return 1; for (;*s1!=0 || *s2!=0;s1++,s2++){ if (*s1!=*s2){ if (*s1==*s2+32 || *s1==*s2-32) flag=0; else return (*s1-*s2); } if (*s1==0 && *s2!=0) return *s2; if (*s1!=0 && *s2==0) return *s1; n++; if (n==len) break; } return flag; } char *tj_strupr(char *str) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ char *head=str; if (str==0) return 0; for (;*str!=0;str++){ if (*str>='a' && *str<='z') *str=*str-32; } return head; } char *tj_strlwr(char *str) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ char *head=str; if (str==0) return 0; for (;*str!=0;str++){ if (*str>='A' && *str<='Z') *str=*str+32; } return head; } int tj_strchr(const char *str, const char ch) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int n=0; if (str==0) return 0; for (;*str!=0;str++){ n++; if (*str==ch) return n; } return 0; } int tj_strstr(const char *str, const char *substr) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int n=0,len=0; if (str==0 || substr==0) return 0; len=tj_strlen(substr); for (;*str!=0;str++){ n++; if (*str==*substr){ if (tj_strncmp(str,substr,len)==0) return n; } } return 0; } int tj_strrchr(const char *str, const char ch) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int len; if (str==0) return 0; len=tj_strlen(str); str=str+len-1; for (;len>0;str--,len--){ if (*str==ch) return len; } return 0; } int tj_strrstr(const char *str, const char *substr) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ int len1=0,len2=0; if (str==0 || substr==0) return 0; len1=tj_strlen(str); len2=tj_strlen(substr); str=str+len1-1; for (;len1>0;str--,len1--){ if (*str==*substr){ if (tj_strncmp(str,substr,len2)==0) return len1; } } return 0; } char *tj_strrev(char *str) { /* 注意:函数内不允许定义任何形式的数组(包括静态数组) */ char temp; char *head=str,*last; int len=0,n=1; if (str==0) return 0; len=strlen(str); last=str+len-1; for (;n<=(len/2);head++,last--,n++){ temp=*head; *head=*last; *last=temp; } return str; } /* ==The End==(函数实现部分) */ void press_key(char *prompt="") { cout << endl << prompt << ",按回车键继续" << endl; getchar(); cin.clear(); cin.sync(); } /* main函数(细节可能有错,若发现,请及时反映) */ int main() { if (1) { char s1[]="abcdefghijklmnopqrstuvwxyz"; char s2[]="abcdefghijklmnopqrstuvwxyz\0UVWXYZ"; char s3[]=""; char *p4 =NULL; cout << "tj_strlen()测试部分:" << endl; cout << "1.s1 的长度应该是26,实际是:" << tj_strlen(s1) << endl; cout << "2.s2 的长度应该是26,实际是:" << tj_strlen(s2) << endl; cout << "3.&s2[27] 的长度应该是6, 实际是:" << tj_strlen(&s2[27]) << endl; cout << "4.s3 的长度应该是0, 实际是:" << tj_strlen(s3) << endl; cout << "5.p4 的长度认为是0, 实际是:" << tj_strlen(p4) << endl; press_key("tj_strlen() 测试完成"); } if (1) { char s1[80]="abcdefghij"; char s2[]="abcde"; char s3[]="hello\0UVWXYZ"; char s4[]=""; char *p5=NULL; cout << "tj_strcat()测试部分:" << endl; cout << "1.s1的输出应该是abcdefghij, 实际是:" << s1 << endl; cout << " s1的长度应该是10, 实际是:" << tj_strlen(s1) << endl; cout << "2.s1的输出应该是abcdefghijabcde, 实际是:" << tj_strcat(s1, s2) << endl; cout << " s1的长度应该是15, 实际是:" << tj_strlen(s1) << endl; cout << "3.s1的输出应该是abcdefghijabcdehello, 实际是:" << tj_strcat(s1, s3) << endl; cout << " s1的长度应该是20, 实际是:" << tj_strlen(s1) << endl; cout << "4.s1的输出应该是abcdefghijabcdehelloUVWXYZ,实际是:" << tj_strcat(s1, &s3[6]) << endl; cout << " s1的长度应该是26, 实际是:" << tj_strlen(s1) << endl; cout << "5.s1的输出应该是abcdefghijabcdehelloUVWXYZ,实际是:" << tj_strcat(s1, s4) << endl; cout << " s1的长度应该是26, 实际是:" << tj_strlen(s1) << endl; cout << "6.s1的输出应该是abcdefghijabcdehelloUVWXYZ,实际是:" << tj_strcat(s1, p5) << endl; cout << " s1的长度应该是26, 实际是:" << tj_strlen(s1) << endl; cout << "7.p5的输出应该是<NULL>, 实际是:" << (tj_strcat(p5, s1)==NULL ? "<NULL>":tj_strcat(p5, s1)) << endl; cout << " p5的长度应该是0, 实际是:" << tj_strlen(p5) << endl; cout << "8.p5的输出应该是<NULL>, 实际是:" << (tj_strcat(p5, NULL)==NULL ? "<NULL>":tj_strcat(p5, NULL)) << endl; cout << " p5的长度应该是0, 实际是:" << tj_strlen(p5) << endl; press_key("tj_strcat() 测试完成"); } if (1) { char s0[80]; char s1[80]="abcdefghijklm"; char s2[]="abcde"; char s3[]="hello\0UVWXYZ"; char s4[]=""; char *p5=NULL; char *p6=NULL; cout << "tj_strcpy()测试部分:" << endl; cout << "1.s1的输出应该是abcdefghijklm, 实际是:" << s1 << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; cout << "2.s1的输出应该是abcde, 实际是:" << tj_strcpy(s1, s2) << endl; cout << " s1的长度应该是5, 实际是:" << tj_strlen(s1) << endl; cout << "3.s1的输出应该是UVWXYZ, 实际是:" << tj_strcpy(s1, &s3[6]) << endl; cout << " s1的长度应该是6, 实际是:" << tj_strlen(s1) << endl; cout << "4.s1的输出应该是hello, 实际是:" << tj_strcpy(s1, s3) << endl; cout << " s1的长度应该是5, 实际是:" << tj_strlen(s1) << endl; cout << "5.s1的输出应该是--, 实际是:-" << tj_strcpy(s1, s4) << '-' << endl; cout << " s1的长度应该是0, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s0, s2); tj_strcat(s0, s3); cout << "6.s0的输出应该是abcdehelloUVWXYZ,实际是:" << tj_strcat(s0, &s3[6]) << endl; cout << " s0的长度应该是16, 实际是:" << tj_strlen(s0) << endl; cout << "7.s0的输出应该是--, 实际是:-" << tj_strcpy(s0, p5) << '-' << endl; cout << " s0的长度应该是0, 实际是:" << tj_strlen(s0) << endl; cout << "8.p5的输出应该是<NULL>, 实际是:" << (tj_strcpy(p5, s0)==NULL ? "<NULL>" : tj_strcpy(p5, s0)) << endl; cout << " p5的长度应该是0, 实际是:" << tj_strlen(p5) << endl; cout << "9.p5的输出应该是<NULL>, 实际是:" << (tj_strcpy(p5, p6)==NULL ? "<NULL>" : tj_strcpy(p5, p6)) << endl; cout << " p5的长度应该是0, 实际是:" << tj_strlen(p5) << endl; press_key("tj_strcpy() 测试完成"); } if (1) { char s0[80]; char s1[80]="abcdefghijklm"; char s2[]="abcde"; char s3[]="hello\0UVWXYZ"; char s4[]=""; char *p5=NULL; char *p6=NULL; cout << "tj_strncpy()测试部分:" << endl; cout << "1. s1的输出应该是abcdefghijklm, 实际是:" << s1 << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; cout << "2. s1的输出应该是hellofghijklm, 实际是:" << tj_strncpy(s1, s3, 10) << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s1, "abcdefghijklm"); cout << "3. s1的输出应该是hellofghijklm, 实际是:" << tj_strncpy(s1, s3, 5) << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s1, "abcdefghijklm"); cout << "4. s1的输出应该是heldefghijklm, 实际是:" << tj_strncpy(s1, s3, 3) << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s1, "abcdefghijklm"); cout << "5. s1的输出应该是abcdefghijklm, 实际是:" << tj_strncpy(s1, s4, 2) << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s1, "abcdefghijklm"); tj_strncpy(&s1[4], s3, 10); cout << "6. s1的输出应该是abcdhellojklm, 实际是:" << s1 << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s1, "abcdefghijklm"); tj_strncpy(&s1[4], s3, 5); cout << "7. s1的输出应该是abcdhellojklm, 实际是:" << s1 << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s1, "abcdefghijklm"); tj_strncpy(&s1[4], s3, 3); cout << "8. s1的输出应该是abcdhelhijklm, 实际是:" << s1 << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s1, "abcdefghijklm"); tj_strncpy(&s1[4], &s3[6], 10); cout << "9. s1的输出应该是abcdUVWXYZklm, 实际是:" << s1 << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; press_key("tj_strncpy() 测试暂停"); tj_strcpy(s1, "abcdefghijklm"); tj_strncpy(&s1[4], &s3[6], 6); cout << "10.s1的输出应该是abcdUVWXYZklm, 实际是:" << s1 << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strcpy(s1, "abcdefghijklm"); tj_strncpy(&s1[4], &s3[6], 3); cout << "11.s1的输出应该是abcdUVWhijklm, 实际是:" << s1 << endl; cout << " s1的长度应该是13, 实际是:" << tj_strlen(s1) << endl; tj_strncpy(s0, s2, tj_strlen(s2)); s0[tj_strlen(s2)] = 0; cout << "12.s0的输出应该是abcde, 实际是:" << s0 << endl; cout << " s0的长度应该是5, 实际是:" << tj_strlen(s0) << endl; cout << "13.s0的输出应该是abcdehello, 实际是:" << tj_strcat(s0, s3) << endl; cout << " s0的长度应该是10, 实际是:" << tj_strlen(s0) << endl; int old_len = tj_strlen(s0); tj_strncpy(&s0[10], &s3[6], tj_strlen(&s3[6])); s0[old_len + tj_strlen(&s3[6]) ] = 0; cout << "14.s0的输出应该是abcdehelloUVWXYZ,实际是:" << s0 << endl; cout << " s0的长度应该是16, 实际是:" << tj_strlen(s0) << endl; cout << "15.s0的输出应该是abcdehelloUVWXYZ,实际是:" << tj_strncpy(s0, p5, 2) << endl; cout << " s0的长度应该是16, 实际是:" << tj_strlen(s0) << endl; cout << "16.p5的输出应该是<NULL>, 实际是:" << (tj_strncpy(p5, s0, 2)==NULL ? "<NULL>" : tj_strncpy(p5, s0, 2)) << endl; cout << " p5的长度应该是0, 实际是:" << tj_strlen(p5) << endl; cout << "17.p5的输出应该是<NULL>, 实际是:" << (tj_strncpy(p5, p6, 2)==NULL ? "<NULL>" : tj_strncpy(p5, p6, 2)) << endl; cout << " p5的长度应该是0, 实际是:" << tj_strlen(p5) << endl; press_key("tj_strncpy() 测试完成"); } if (1) { char s1[]="horse"; char s2[]="house"; char s3[]="hell"; char s4[]="hello"; char s5[]="hello"; char s6[]="hell"; char s7[]="hello"; char s8[]="hello"; char s9[]="hello"; char s10[]="hello\0UVWXYZ"; char s11[]="HELLO"; char s12[]="hello"; char s13[]="HeLlO"; char s14[]="hElLo"; char *p15 = NULL; char *p16 = NULL; cout << "tj_strcmp()测试部分:" << endl; cout << "1.s1 和s2 的输出应该是-3, 实际是:" << tj_strcmp(s1, s2) << endl; cout << "2.s3 和s4 的输出应该是-111,实际是:" << tj_strcmp(s3, s4) << endl; cout << "3.s5 和s6 的输出应该是111, 实际是:" << tj_strcmp(s5, s6) << endl; cout << "4.s7 和s8 的输出应该是0, 实际是:" << tj_strcmp(s7, s8) << endl; cout << "5.s9 和s10的输出应该是0, 实际是:" << tj_strcmp(s9, s10) << endl; cout << "6.s11和s12的输出应该是-32, 实际是:" << tj_strcmp(s11, s12) << endl; cout << "7.s13和s14的输出应该是-32, 实际是:" << tj_strcmp(s13, s14) << endl; cout << "8.p15和s1 的输出应该是-1, 实际是:" << tj_strcmp(p15, s1) << endl; cout << " s1 和p15的输出应该是1, 实际是:" << tj_strcmp(s1, p15) << endl; cout << " p15和p16的输出应该是0, 实际是:" << tj_strcmp(p15, p16) << endl; press_key("tj_strcmp() 测试完成"); } if (1) { char s1[]="horse"; char s2[]="house"; char s3[]="hell"; char s4[]="hello"; char s5[]="hello"; char s6[]="hell"; char s7[]="hello"; char s8[]="hello"; char s9[]="hello"; char s10[]="hello\0UVWXYZ"; char s11[]="HELLO"; char s12[]="hello"; char s13[]="HeLlO"; char s14[]="hElLo"; char *p15 = NULL; char *p16 = NULL; cout << "tj_strcasecmp()测试部分:" << endl; cout << "1.s1 和s2 的输出应该是-3, 实际是:" << tj_strcasecmp(s1, s2) << endl; cout << "2.s3 和s4 的输出应该是-111,实际是:" << tj_strcasecmp(s3, s4) << endl; cout << "3.s5 和s6 的输出应该是111, 实际是:" << tj_strcasecmp(s5, s6) << endl; cout << "4.s7 和s8 的输出应该是0, 实际是:" << tj_strcasecmp(s7, s8) << endl; cout << "5.s9 和s10的输出应该是0, 实际是:" << tj_strcasecmp(s9, s10) << endl; cout << "6.s11和s12的输出应该是0, 实际是:" << tj_strcasecmp(s11, s12) << endl; cout << "7.s13和s14的输出应该是0, 实际是:" << tj_strcasecmp(s13, s14) << endl; cout << "8.p15和s1 的输出应该是-1, 实际是:" << tj_strcasecmp(p15, s1) << endl; cout << " s1 和p15的输出应该是1, 实际是:" << tj_strcasecmp(s1, p15) << endl; cout << " p15和p16的输出应该是0, 实际是:" << tj_strcasecmp(p15, p16) << endl; press_key("tj_strcasecmp() 测试完成"); } if (1) { char s1[]="horse"; char s2[]="house"; char s3[]="hell"; char s4[]="hello"; char s5[]="hello"; char s6[]="hell"; char s7[]="hello"; char s8[]="hello"; char s9[]="hello"; char s10[]="hello\0UVWXYZ"; char s11[]="HELLO"; char s12[]="hello"; char s13[]="HeLlO"; char s14[]="hElLo"; char *p15 = NULL; char *p16 = NULL; cout << "tj_strncmp()测试部分:" << endl; cout << "1.s1 和s2 比较前10个字符的输出应该是-3, 实际是:" << tj_strncmp(s1, s2, 10) << endl; cout << " s1 和s2 比较前5 个字符的输出应该是-3, 实际是:" << tj_strncmp(s1, s2, 5) << endl; cout << " s1 和s2 比较前3 个字符的输出应该是-3, 实际是:" << tj_strncmp(s1, s2, 3) << endl; cout << " s1 和s2 比较前2 个字符的输出应该是0, 实际是:" << tj_strncmp(s1, s2, 2) << endl; cout << "2.s3 和s4 比较前10个字符的输出应该是-111,实际是:" << tj_strncmp(s3, s4, 10) << endl; cout << " s3 和s4 比较前5 个字符的输出应该是-111,实际是:" << tj_strncmp(s3, s4, 5) << endl; cout << " s3 和s4 比较前4 个字符的输出应该是0, 实际是:" << tj_strncmp(s3, s4, 4) << endl; cout << "3.s5 和s6 比较前10个字符的输出应该是111 ,实际是:" << tj_strncmp(s5, s6, 10) << endl; cout << " s5 和s6 比较前5 个字符的输出应该是111, 实际是:" << tj_strncmp(s5, s6, 5) << endl; cout << " s5 和s6 比较前4 个字符的输出应该是0, 实际是:" << tj_strncmp(s5, s6, 4) << endl; cout << "4.s7 和s8 比较前10个字符的输出应该是0 , 实际是:" << tj_strncmp(s7, s8, 10) << endl; cout << " s7 和s8 比较前5 个字符的输出应该是0, 实际是:" << tj_strncmp(s7, s8, 5) << endl; cout << " s7 和s8 比较前4 个字符的输出应该是0, 实际是:" << tj_strncmp(s7, s8, 4) << endl; cout << "5.s9 和s10比较前10个字符的输出应该是0 , 实际是:" << tj_strncmp(s9, s10, 10) << endl; cout << " s9 和s10比较前5 个字符的输出应该是0, 实际是:" << tj_strncmp(s9, s10, 5) << endl; cout << " s9 和s10比较前4 个字符的输出应该是0, 实际是:" << tj_strncmp(s9, s10, 4) << endl; press_key("tj_strncmp() 测试暂停"); cout << "6.s11和s12比较前10个字符的输出应该是-32, 实际是:" << tj_strncmp(s11, s12, 10) << endl; cout << " s11和s12比较前5 个字符的输出应该是-32, 实际是:" << tj_strncmp(s11, s12, 5) << endl; cout << " s11和s12比较前2 个字符的输出应该是-32, 实际是:" << tj_strncmp(s11, s12, 2) << endl; cout << "7.s13和s14比较前10个字符的输出应该是-32, 实际是:" << tj_strncmp(s13, s14, 10) << endl; cout << " s13和s14比较前5 个字符的输出应该是-32, 实际是:" << tj_strncmp(s13, s14, 5) << endl; cout << " s13和s14比较前2 个字符的输出应该是-32, 实际是:" << tj_strncmp(s13, s14, 2) << endl; cout << "8.p15和s1 比较前2 个字符的输出应该是-1, 实际是:" << tj_strncmp(p15, s1, 2) << endl; cout << " s1 和p15比较前2 个字符的输出应该是1, 实际是:" << tj_strncmp(s1, p15, 5) << endl; cout << " p15和p16比较前2 个字符的输出应该是0, 实际是:" << tj_strncmp(p15, p16, 2) << endl; press_key("tj_strncmp() 测试结束"); } if (1) { char s1[]="horse"; char s2[]="house"; char s3[]="hell"; char s4[]="hello"; char s5[]="hello"; char s6[]="hell"; char s7[]="hello"; char s8[]="hello"; char s9[]="hello"; char s10[]="hello\0UVWXYZ"; char s11[]="HELLO"; char s12[]="hello"; char s13[]="HeLlO"; char s14[]="hElLo"; char *p15 = NULL; char *p16 = NULL; cout << "tj_strcasencmp()测试部分:" << endl; cout << "1.s1 和s2 比较前10个字符的输出应该是-3, 实际是:" << tj_strcasencmp(s1, s2, 10) << endl; cout << " s1 和s2 比较前5 个字符的输出应该是-3, 实际是:" << tj_strcasencmp(s1, s2, 5) << endl; cout << " s1 和s2 比较前3 个字符的输出应该是-3, 实际是:" << tj_strcasencmp(s1, s2, 3) << endl; cout << " s1 和s2 比较前2 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s1, s2, 2) << endl; cout << "2.s3 和s4 比较前10个字符的输出应该是-111,实际是:" << tj_strcasencmp(s3, s4, 10) << endl; cout << " s3 和s4 比较前5 个字符的输出应该是-111,实际是:" << tj_strcasencmp(s3, s4, 5) << endl; cout << " s3 和s4 比较前4 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s3, s4, 4) << endl; cout << "3.s5 和s6 比较前10个字符的输出应该是111 ,实际是:" << tj_strcasencmp(s5, s6, 10) << endl; cout << " s5 和s6 比较前5 个字符的输出应该是111, 实际是:" << tj_strcasencmp(s5, s6, 5) << endl; cout << " s5 和s6 比较前4 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s5, s6, 4) << endl; cout << "4.s7 和s8 比较前10个字符的输出应该是0 , 实际是:" << tj_strcasencmp(s7, s8, 10) << endl; cout << " s7 和s8 比较前5 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s7, s8, 5) << endl; cout << " s7 和s8 比较前4 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s7, s8, 4) << endl; cout << "5.s9 和s10比较前10个字符的输出应该是0 , 实际是:" << tj_strcasencmp(s9, s10, 10) << endl; cout << " s9 和s10比较前5 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s9, s10, 5) << endl; cout << " s9 和s10比较前4 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s9, s10, 4) << endl; press_key("tj_strcasencmp() 测试暂停"); cout << "6.s11和s12比较前10个字符的输出应该是0, 实际是:" << tj_strcasencmp(s11, s12, 10) << endl; cout << " s11和s12比较前5 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s11, s12, 5) << endl; cout << " s11和s12比较前2 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s11, s12, 2) << endl; cout << "7.s13和s14比较前10个字符的输出应该是0, 实际是:" << tj_strcasencmp(s13, s14, 10) << endl; cout << " s13和s14比较前5 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s13, s14, 5) << endl; cout << " s13和s14比较前2 个字符的输出应该是0, 实际是:" << tj_strcasencmp(s13, s14, 2) << endl; cout << "8.p15和s1 比较前2 个字符的输出应该是-1, 实际是:" << tj_strcasencmp(p15, s1, 2) << endl; cout << " s1 和p15比较前2 个字符的输出应该是1, 实际是:" << tj_strcasencmp(s1, p15, 5) << endl; cout << " p15和p16比较前2 个字符的输出应该是0, 实际是:" << tj_strcasencmp(p15, p16, 2) << endl; press_key("tj_strcasencmp() 测试完成"); } if (1) { char s1[]="123horseHELLO*#@"; char s2[]="1A2b3C*d#E@f"; char *p3 = NULL; cout << "tj_strupr()测试部分:" << endl; cout << "1.s1 的输出应该是123HORSEHELLO*#@,实际是:" << tj_strupr(s1) << endl; cout << "2.s2 的输出应该是1A2B3C*D#E@F, 实际是:" << tj_strupr(s2) << endl; cout << "3.p3 的输出应该是<NULL>, 实际是:" << (tj_strupr(p3)==NULL ? "<NULL>":tj_strupr(p3)) << endl; press_key("tj_strupr() 测试完成"); } if (1) { char s1[]="123horseHELLO*#@"; char s2[]="1A2b3C*d#E@f"; char *p3 = NULL; cout << "tj_strlwr()测试部分:" << endl; cout << "1.s1 的输出应该是123horsehello*#@,实际是:" << tj_strlwr(s1) << endl; cout << "2.s2 的输出应该是1a2b3c*d#e@f, 实际是:" << tj_strlwr(s2) << endl; cout << "3.p3 的输出应该是<NULL>, 实际是:" << (tj_strlwr(p3)==NULL ? "<NULL>":tj_strlwr(p3)) << endl; press_key("tj_strlwr() 测试完成"); } if (1) { char s1[]="This is a pencil."; char *p2 = NULL; cout << "tj_strchr()测试部分:" << endl; cout << "1.s1 的输出应该是1,实际是:" << tj_strchr(s1, 'T') << endl; cout << "2.s1 的输出应该是3,实际是:" << tj_strchr(s1, 'i') << endl; cout << "3.s1 的输出应该是5,实际是:" << tj_strchr(s1, ' ') << endl; cout << "4.s1 的输出应该是0,实际是:" << tj_strchr(s1, 'x') << endl; cout << "5.p2 的输出应该是0,实际是:" << tj_strchr(p2, 'a') << endl; press_key("tj_strchr() 测试完成"); } if (1) { char s1[]="This is a pencil."; char s2[]="aabbbceddbbbceeeff"; char s3[]="abcde"; char *p4 = NULL; cout << "tj_strstr()测试部分:" << endl; cout << "1.s1 的输出应该是1, 实际是:" << tj_strstr(s1, "T") << endl; cout << " s1 的输出应该是3, 实际是:" << tj_strstr(s1, "is") << endl; cout << " s1 的输出应该是11,实际是:" << tj_strstr(s1, "pencil") << endl; cout << " s1 的输出应该是0, 实际是:" << tj_strstr(s1, "Pencil") << endl; cout << "2.s2 的输出应该是3, 实际是:" << tj_strstr(s2, "bb") << endl; cout << " s2 的输出应该是3, 实际是:" << tj_strstr(s2, "bbb") << endl; cout << " s2 的输出应该是4, 实际是:" << tj_strstr(s2, "bbc") << endl; cout << " s2 的输出应该是0, 实际是:" << tj_strstr(s2, "bbbb") << endl; cout << " s2 的输出应该是6, 实际是:" << tj_strstr(s2, "ce") << endl; cout << " s2 的输出应该是13,实际是:" << tj_strstr(s2, "cee") << endl; cout << "3.s3 的输出应该是1, 实际是:" << tj_strstr(s3, "abcde") << endl; cout << " s3 的输出应该是0, 实际是:" << tj_strstr(s3, "abcdef") << endl; cout << " s3 的输出应该是0, 实际是:" << tj_strstr(s3, NULL) << endl; cout << "4.p4 的输出应该是0, 实际是:" << tj_strstr(p4, "abc") << endl; cout << " p4 的输出应该是0, 实际是:" << tj_strstr(p4, NULL) << endl; press_key("tj_strstr() 测试完成"); } if (1) { char s1[]="This is a pencil."; char *p2 = NULL; cout << "tj_strrchr()测试部分:" << endl; cout << "1.s1 的输出应该是1, 实际是:" << tj_strrchr(s1, 'T') << endl; cout << "2.s1 的输出应该是15,实际是:" << tj_strrchr(s1, 'i') << endl; cout << "3.s1 的输出应该是10,实际是:" << tj_strrchr(s1, ' ') << endl; cout << "4.s1 的输出应该是0, 实际是:" << tj_strrchr(s1, 'x') << endl; cout << "5.p2 的输出应该是0, 实际是:" << tj_strrchr(p2, 'a') << endl; press_key("tj_strrchr() 测试完成"); } if (1) { char s1[]="This is a pencil."; char s2[]="aabbbceddbbbceeeff"; char s3[]="abcde"; char *p4 = NULL; cout << "tj_strrstr()测试部分:" << endl; cout << "1.s1 的输出应该是1, 实际是:" << tj_strrstr(s1, "T") << endl; cout << " s1 的输出应该是6, 实际是:" << tj_strrstr(s1, "is") << endl; cout << " s1 的输出应该是11,实际是:" << tj_strrstr(s1, "pencil") << endl; cout << " s1 的输出应该是0, 实际是:" << tj_strrstr(s1, "Pencil") << endl; cout << "2.s2 的输出应该是11,实际是:" << tj_strrstr(s2, "bb") << endl; cout << " s2 的输出应该是10,实际是:" << tj_strrstr(s2, "bbb") << endl; cout << " s2 的输出应该是11,实际是:" << tj_strrstr(s2, "bbc") << endl; cout << " s2 的输出应该是0, 实际是:" << tj_strrstr(s2, "bbbb") << endl; cout << " s2 的输出应该是13,实际是:" << tj_strrstr(s2, "ce") << endl; cout << " s2 的输出应该是13,实际是:" << tj_strrstr(s2, "cee") << endl; cout << "3.s3 的输出应该是1, 实际是:" << tj_strrstr(s3, "abcde") << endl; cout << " s3 的输出应该是0, 实际是:" << tj_strrstr(s3, "abcdef") << endl; cout << " s3 的输出应该是0, 实际是:" << tj_strrstr(s3, NULL) << endl; cout << "4.p4 的输出应该是0, 实际是:" << tj_strrstr(p4, "abc") << endl; cout << " p4 的输出应该是0, 实际是:" << tj_strrstr(p4, NULL) << endl; press_key("tj_strrstr() 测试完成"); } if (1) { char s1[]="This is a pencil."; char s2[]="aabbbceddbbbceeeff"; char s3[]=""; char *p4 = NULL; cout << "tj_strrev()测试部分:" << endl; cout << "1.s1 的输出应该是This is a pencil., 实际是:" << s1 << endl; cout << " s1 的输出应该是.licnep a si sihT, 实际是:" << tj_strrev(s1) << endl; cout << "2.s2 的输出应该是aabbbceddbbbceeeff, 实际是:" << s2 << endl; cout << " s2 的输出应该是ffeeecbbbddecbbbaa, 实际是:" << tj_strrev(s2) << endl; cout << "3.s3 的输出应该是--, 实际是:-" << s3 << "-" << endl; cout << " s3 的输出应该是--, 实际是:-" << tj_strrev(s3) << "-" << endl; cout << "4.p4 的输出应该是<NULL>, 实际是:" << (p4==NULL ? "<NULL>" : p4) << endl; cout << " p4 的输出应该是<NULL>, 实际是:" << (tj_strrev(p4)==NULL ? "<NULL>" : tj_strrev(s3)) << endl; press_key("tj_strrev() 测试完成"); } return 0; }
[ "yzy_2012_YZY_2012@163.com" ]
yzy_2012_YZY_2012@163.com
f67ac8d44ac127dd3694d3e394eefa98e0e63086
1b006ab86f764f8b13c1a63bb4e04eac28271f7b
/Peasant/PeasantHolder.h
ea7bd5c6f31fa8e60e03a9e7b2300d8af6b22555
[ "MIT" ]
permissive
RodrigoHolztrattner/Peasant
f710a57729e46d0619641d83cde563a4c95ea9f7
b614aa94ed94bfaa6fbec6d81f64ba105ca9324d
refs/heads/master
2020-03-07T15:02:56.169688
2018-09-06T14:38:03
2018-09-06T14:38:03
127,543,406
0
0
null
null
null
null
UTF-8
C++
false
false
1,302
h
//////////////////////////////////////////////////////////////////////////////// // Filename: PeasantHolder.h //////////////////////////////////////////////////////////////////////////////// #pragma once ////////////// // INCLUDES // ////////////// #include "PeasantConfig.h" #include "PeasantObject.h" #include <cstdint> #include <vector> #include <atomic> /////////////// // NAMESPACE // /////////////// ///////////// // DEFINES // ///////////// //////////// // GLOBAL // //////////// /////////////// // NAMESPACE // /////////////// // Peasant PeasantDevelopmentNamespaceBegin(Peasant) ////////////// // TYPEDEFS // ////////////// //////////////// // FORWARDING // //////////////// //////////////////////////////////////////////////////////////////////////////// // Class name: PeasantHolder //////////////////////////////////////////////////////////////////////////////// class PeasantHolder { public: ////////////////// // CONSTRUCTORS // public: ////////// // Constructor / destructor PeasantHolder(PeasantObject* _object); virtual ~PeasantHolder(); ////////////////// // MAIN METHODS // public: ////////// /////////////// // VARIABLES // private: ////// // The object we are referencing PeasantObject* m_ReferenceObject; }; // Peasant PeasantDevelopmentNamespaceEnd(Peasant)
[ "rodrigoholztrattner@gmail.com" ]
rodrigoholztrattner@gmail.com
ab03109ad818ed7693430df157023d06e99d99bb
bc2a6e1f41ced330c04c199d0e13f7f8b82bd6ef
/src/halibs/include/avr-halib/regmaps/local/at90can128/twi.h
7d2a7ad5554347df68c8a931c8d4d6fb4282d4a3
[]
no_license
SoCXin/MEGA328P
372187c044c402ae90c3c3192b4d90f8ea996f3e
321166c6f287e441d0ae906ecfddc5d3cff706f2
refs/heads/master
2023-04-27T02:10:27.492148
2021-05-18T07:51:01
2021-05-18T07:51:01
157,304,433
0
0
null
null
null
null
UTF-8
C++
false
false
2,769
h
#pragma once #include <avr-halib/regmaps/base/localRegMap.h> namespace avr_halib { namespace regmaps { namespace local { namespace at90can128 { struct TWI : public base::LocalRegMap { public: union { struct { uint8_t __base [0xb8]; uint8_t twbr; union { uint8_t twsr; struct { uint8_t twps :2; uint8_t :1; uint8_t tws :5; }; }; union { uint8_t twar; struct { bool twgce :1; uint8_t twa :7; }; }; uint8_t twdr; union { uint8_t twcr; struct { bool twie :1; bool :1; bool twen :1; bool twwc :1; bool twsto :1; bool twsta :1; bool twea :1; bool twint :1; }; }; }; }; enum {ps1 = 0, ps4 = 1, ps16 = 2, ps64 = 3}; enum {read = 1 , write = 0}; enum status { st_start = 1, repeat_start = 2, sla_write_ack = 3, sla_write_noack = 4, m_data_tx_ack = 5, m_data_tx_noack = 6, sla_w_buslost = 7, sla_read_ack = 8, sla_read_noack = 9, m_data_rx_ack = 10, m_data_rx_noack = 11, sla_w_recived = 12, buslost_sla_w_recived = 13, gc_w_recived = 14, buslost_gc_w_recived = 15, sl_data_rx_ack = 16, sl_data_rx_noack = 17, gc_data_rx_ack = 18, gc_data_rx_noack = 19, stop_recived = 20, sla_r_recived = 21, buslost_sla_r_recived = 22, sl_data_tx_ack = 23, sl_data_tx_noack = 24, sl_data_tx_ack_last = 25, no_status = 31, bus_error = 0 }; } __attribute__((packed)); } } } }
[ "qitas@qitas.cn" ]
qitas@qitas.cn
69f7268ac934dfe5cd8efdbe910a8b1267281d3f
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium/net/base/net_test_suite.h
98c5bd511e49c49d721e1b5d89d8e892307b10b1
[ "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,244
h
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_BASE_NET_TEST_SUITE_H_ #define NET_BASE_NET_TEST_SUITE_H_ #pragma once #include "base/memory/ref_counted.h" #include "base/test/test_suite.h" #include "build/build_config.h" #include "net/base/mock_host_resolver.h" class MessageLoop; namespace net { class NetworkChangeNotifier; } class NetTestSuite : public base::TestSuite { public: NetTestSuite(int argc, char** argv); virtual ~NetTestSuite(); virtual void Initialize(); virtual void Shutdown(); protected: // Called from within Initialize(), but separate so that derived classes // can initialize the NetTestSuite instance only and not // TestSuite::Initialize(). TestSuite::Initialize() performs some global // initialization that can only be done once. void InitializeTestThread(); private: scoped_ptr<net::NetworkChangeNotifier> network_change_notifier_; scoped_ptr<MessageLoop> message_loop_; scoped_refptr<net::RuleBasedHostResolverProc> host_resolver_proc_; net::ScopedDefaultHostResolverProc scoped_host_resolver_proc_; }; #endif // NET_BASE_NET_TEST_SUITE_H_
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
35e9edfd72c52c8d0b764e4671173e01e16e1663
8bfe95d68a3527854faa64a7a954b9b8a9948624
/assignment-4/include/global/promise.h
f6bb1438286d3fd808c68e4993323c0e1ae4c9f9
[ "Apache-2.0" ]
permissive
lherman-cs/cs4160
9b670a76e70510ebf9bfdcd40aca987e7cbbf3e0
abcc582e59f139ba8d8e74600ee028f321b308fd
refs/heads/master
2020-04-16T12:30:50.710928
2019-05-01T05:53:19
2019-05-01T05:53:19
165,582,495
2
0
null
null
null
null
UTF-8
C++
false
false
986
h
#pragma once #include <cstdint> #include <functional> #include <list> #include <memory> #include <queue> #include "core/interface.h" class Engine; class Global; class Promise : public std::enable_shared_from_this<Promise> { private: friend class PromiseScheduler; // return true if resolved using Action = std::function<bool()>; std::queue<Action> actions; Uint32 elapsed = 0; // return false if there's no more actions bool next(Uint32 ticks); Promise() : actions() {} public: Promise(const Promise&) = delete; Promise& operator=(const Promise&) = delete; Promise& then(Action); Promise& sleep(uint32_t ms); }; class PromiseScheduler { private: friend class Engine; friend class Global; std::list<std::shared_ptr<Promise>> promises; PromiseScheduler() : promises() {} void update(Uint32 ticks); public: PromiseScheduler(const PromiseScheduler&) = delete; PromiseScheduler& operator=(const PromiseScheduler&) = delete; Promise& add(); };
[ "lherman.cs@gmail.com" ]
lherman.cs@gmail.com
9f1aa514517a4d397f2038ec3a7d8f9c439cc1b8
24f26275ffcd9324998d7570ea9fda82578eeb9e
/third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.cc
c970967893109cc7d5df0219c785c1545211e437
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
5,883
cc
// Copyright 2019 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 "third_party/blink/renderer/controller/user_level_memory_pressure_signal_generator.h" #include <limits> #include "base/memory/memory_pressure_listener.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" #include "base/system/sys_info.h" #include "base/time/default_tick_clock.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" #include "third_party/blink/renderer/platform/wtf/allocator/partitions.h" namespace blink { namespace { constexpr double kDefaultMemoryThresholdMB = std::numeric_limits<double>::infinity(); constexpr base::FeatureParam<double> k512MBDeviceMemoryThresholdParam{ &blink::features::kUserLevelMemoryPressureSignal, "param_512mb_device_memory_threshold_mb", kDefaultMemoryThresholdMB}; constexpr base::FeatureParam<double> k1GBDeviceMemoryThresholdParam{ &blink::features::kUserLevelMemoryPressureSignal, "param_1gb_device_memory_threshold_mb", kDefaultMemoryThresholdMB}; constexpr base::FeatureParam<double> k2GBDeviceMemoryThresholdParam{ &blink::features::kUserLevelMemoryPressureSignal, "param_2gb_device_memory_threshold_mb", kDefaultMemoryThresholdMB}; constexpr base::FeatureParam<double> k3GBDeviceMemoryThresholdParam{ &blink::features::kUserLevelMemoryPressureSignal, "param_3gb_device_memory_threshold_mb", kDefaultMemoryThresholdMB}; constexpr base::FeatureParam<double> k4GBDeviceMemoryThresholdParam{ &blink::features::kUserLevelMemoryPressureSignal, "param_4gb_device_memory_threshold_mb", kDefaultMemoryThresholdMB}; // Minimum time interval between generated memory pressure signals. constexpr double kDefaultMinimumIntervalSeconds = 10 * 60; constexpr base::FeatureParam<double> kMinimumIntervalSeconds{ &blink::features::kUserLevelMemoryPressureSignal, "minimum_interval_s", kDefaultMinimumIntervalSeconds}; } // namespace // static UserLevelMemoryPressureSignalGenerator& UserLevelMemoryPressureSignalGenerator::Instance() { DEFINE_STATIC_LOCAL(UserLevelMemoryPressureSignalGenerator, generator, ()); return generator; } UserLevelMemoryPressureSignalGenerator::UserLevelMemoryPressureSignalGenerator() : delayed_report_timer_( Thread::MainThread()->GetTaskRunner(), this, &UserLevelMemoryPressureSignalGenerator::OnTimerFired), clock_(base::DefaultTickClock::GetInstance()) { int64_t physical_memory = base::SysInfo::AmountOfPhysicalMemory(); if (physical_memory > 3.1 * 1024 * 1024 * 1024) memory_threshold_mb_ = k4GBDeviceMemoryThresholdParam.Get(); else if (physical_memory > 2.1 * 1024 * 1024 * 1024) memory_threshold_mb_ = k3GBDeviceMemoryThresholdParam.Get(); else if (physical_memory > 1.1 * 1024 * 1024 * 1024) memory_threshold_mb_ = k2GBDeviceMemoryThresholdParam.Get(); else if (physical_memory > 600 * 1024 * 1024) memory_threshold_mb_ = k1GBDeviceMemoryThresholdParam.Get(); else memory_threshold_mb_ = k512MBDeviceMemoryThresholdParam.Get(); minimum_interval_ = base::TimeDelta::FromSeconds(kMinimumIntervalSeconds.Get()); // Can be disabled for certain device classes by setting the field param to an // empty string. bool enabled = base::FeatureList::IsEnabled( blink::features::kUserLevelMemoryPressureSignal) && !std::isinf(memory_threshold_mb_); if (enabled) { monitoring_ = true; MemoryUsageMonitor::Instance().AddObserver(this); ThreadScheduler::Current()->AddRAILModeObserver(this); } } UserLevelMemoryPressureSignalGenerator:: ~UserLevelMemoryPressureSignalGenerator() { MemoryUsageMonitor::Instance().RemoveObserver(this); ThreadScheduler::Current()->RemoveRAILModeObserver(this); } void UserLevelMemoryPressureSignalGenerator::SetTickClockForTesting( const base::TickClock* clock) { clock_ = clock; } void UserLevelMemoryPressureSignalGenerator::OnRAILModeChanged( RAILMode rail_mode) { is_loading_ = rail_mode == RAILMode::kLoad; } void UserLevelMemoryPressureSignalGenerator::OnMemoryPing(MemoryUsage usage) { // Disabled during loading as we don't want to purge caches that has just been // created. if (is_loading_) return; if (usage.private_footprint_bytes / 1024 / 1024 < memory_threshold_mb_) return; base::TimeDelta elapsed = clock_->NowTicks() - last_generated_; if (elapsed >= base::TimeDelta::FromSeconds(kMinimumIntervalSeconds.Get())) Generate(usage); } void UserLevelMemoryPressureSignalGenerator::Generate(MemoryUsage usage) { UMA_HISTOGRAM_MEMORY_LARGE_MB( "Memory.Experimental.UserLevelMemoryPressureSignal." "RendererPrivateMemoryFootprintBefore", base::saturated_cast<base::Histogram::Sample>( usage.private_footprint_bytes / 1024 / 1024)); base::MemoryPressureListener::NotifyMemoryPressure( base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL); last_generated_ = clock_->NowTicks(); delayed_report_timer_.StartOneShot(base::TimeDelta::FromSeconds(10), FROM_HERE); } void UserLevelMemoryPressureSignalGenerator::OnTimerFired(TimerBase*) { MemoryUsage usage = MemoryUsageMonitor::Instance().GetCurrentMemoryUsage(); UMA_HISTOGRAM_MEMORY_LARGE_MB( "Memory.Experimental.UserLevelMemoryPressureSignal." "RendererPrivateMemoryFootprintAfter", base::saturated_cast<base::Histogram::Sample>( usage.private_footprint_bytes / 1024 / 1024)); } } // namespace blink
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
a3aea96e98dd1637e3d3b1566cf20ecf88f3313a
62331e1c4760fd204665e1e0f772eab97e88cfbb
/Code/include/eventScaler.h
589ed22df0e8af2fddc15cd2f7a96613ba86374b
[]
no_license
systrauss/Dissertation
180941d56418acbc1c313c4ada5483ed373ba221
3e1713cd3d51239900e6700102dab6ad78726b7d
refs/heads/master
2020-04-29T18:27:04.025699
2020-04-15T14:04:37
2020-04-15T14:04:37
176,324,565
0
0
null
null
null
null
UTF-8
C++
false
false
433
h
#ifndef EVENTSCALER_H #define EVENTSCALER_H #define NUM_OF_SCALER_CH 26 #include "TObject.h" class eventScaler : public TObject { public: UShort_t scalerStartTime; UShort_t scalerEndTime; UShort_t scalers[NUM_OF_SCALER_CH]; eventScaler(); void Reset(); void SetEndTime(unsigned int time); void SetStartTime(unsigned int time); void SetValue(int channel, unsigned int value); ClassDef(eventScaler,1) }; #endif
[ "sstrauss@nd.edu" ]
sstrauss@nd.edu
a9faec894b50b6cba7d803b1ab635477a6e5da22
91294c517b797706c33672b161514fe64c139fe4
/Source/NetEx/Private/NEChar.cpp
ef051a20628097faaa7ae92c8bf5bdbb3b2e0492
[]
no_license
danmanakhov/UE4_NetExample
ec1e3661e9a66e95f2a39f16f172c6f15292aeb2
7634682d6bb821914860a6f0df74c5e592bded4e
refs/heads/master
2020-03-09T01:32:23.693436
2018-04-12T11:53:29
2018-04-12T11:53:29
128,517,328
0
0
null
null
null
null
UTF-8
C++
false
false
735
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "NEChar.h" #include "NEGameMode.h" // Sets default values ANEChar::ANEChar() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; team = ETeamC::red_server; } // Called when the game starts or when spawned void ANEChar::BeginPlay() { Super::BeginPlay(); } // Called every frame void ANEChar::Tick(float DeltaTime) { Super::Tick(DeltaTime); } // Called to bind functionality to input void ANEChar::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); }
[ "muhahambr@gmail.com" ]
muhahambr@gmail.com
f77a1717b2c99d7ef316b85ca741c1a9d8d836c7
cf6e89cbb246fe4135f12a7ee8392008c3c03510
/roomFilter.cpp
4bded30383ee3be6bd314e36e26f4f1a66710a3e
[]
no_license
Behyna/UT-Trip
58252ac5a0d3a97cdd0ef295dd8c80d8eef112a0
bedbe1c819fdca42793f92e33bb6e2c592cf56ee
refs/heads/main
2023-08-08T04:10:38.041765
2021-09-20T12:34:38
2021-09-20T12:34:38
408,417,216
0
0
null
null
null
null
UTF-8
C++
false
false
657
cpp
#include "roomFilter.hpp" #include <iostream> using namespace std; RoomFilter::RoomFilter(string _type, int _quantity, int _checkIn, int _checkOut) { type = _type; quantity = _quantity; checkIn = _checkIn; checkOut = _checkOut; } vector<Hotel*> RoomFilter::doFilter(vector<Hotel*> hotels) { vector<Hotel*> filteredHotels; for(int i = 0; i < hotels.size(); i++) { try { hotels[i]->reserveRooms(type, quantity, checkIn, checkOut); filteredHotels.push_back(hotels[i]); } catch(const char* msg) { msg; } } return filteredHotels; }
[ "behyna@Behynas-MacBook-Pro.local" ]
behyna@Behynas-MacBook-Pro.local
d33307fae3a2d12dfd1f3b91cd57e8b31cf9bede
34a3a975a3a3c2e0c096d1dc948b0b7fa32d0c8b
/sorting algorithms/merge_sort.cpp
c5e54ee833ab2dc0f66f927eda6d2112d4e435e1
[]
no_license
andreox/algds
bac4fb97a577b130d9a782ad4c6ca6af1c2c9261
70c3ba46c0a1aeb29237a5a8a90842e9eea14d49
refs/heads/master
2022-02-07T22:15:43.456450
2022-02-05T17:27:17
2022-02-05T17:27:17
80,754,983
1
0
null
2022-01-23T22:39:43
2017-02-02T18:23:17
C++
UTF-8
C++
false
false
1,201
cpp
#include <iostream> #include <vector> using namespace std ; void merge( vector<int> &A , int p, int q, int r ) { int i,j ; int n1 = q - p + 1 ; int n2 = r - q ; vector<int> L ; vector<int> R ; for ( i = 0 ; i < n1 ; i++ ) { L.push_back(A[p+i]) ; } for ( j = 0 ; j < n2 ; j++ ) { R.push_back(A[q+j+1]) ; } i = 0 ; j = 0 ; int k ; for ( k = p ; k < r && i < n1 && j < n2 ; k++ ) { if ( L[i] <= R[j] ) { A[k] = L[i] ; i++ ; } else { A[k] = R[j] ; j++ ; } } //sentinella while (i < n1) { A[k] = L[i]; i++; k++; } while (j < n2) { A[k] = R[j]; j++; k++; } } void merge_sort( vector<int> &A, int p, int r) { if ( p < r ) { int q = (p+(r-1))/2 ; merge_sort( A, p, q) ; merge_sort( A, q+1, r) ; merge( A, p, q, r) ; } } int main( int argc, char** argv ) { vector<int> A ; A.push_back(7); A.push_back(5); A.push_back(4); A.push_back(2); A.push_back(6); A.push_back(3); A.push_back(2); A.push_back(1); int p = 0 ; int r = A.size() ; merge_sort( A, p, r-1 ) ; for ( int i = 0 ; i < A.size() ; i++ ) cout << A[i] << " " ; cout << endl ; return 0 ; }
[ "andreozzi.alessio@gmail.com" ]
andreozzi.alessio@gmail.com
b798be61ddb49955434da1bf182051f5099bc559
a964826c7d71c0b417157c3f56fced2936a17082
/Attic/ClockworkEditorReference/Source/UI/Modal/UINewProject.cpp
8e8d4096e9ffa66a962e347b8c98e9b43a17aca1
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-openssl", "BSD-3-Clause", "NTP", "BSL-1.0", "LicenseRef-scancode-khronos", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "Zlib" ]
permissive
gitter-badger/Clockwork
c95bcfc2066a11e2fcad0329a79cb69f0e7da4b5
ec489a090697fc8b0dc692c3466df352ee722a6b
refs/heads/master
2020-12-28T07:46:24.514590
2016-04-11T00:51:14
2016-04-11T00:51:14
55,931,507
0
0
null
2016-04-11T01:09:48
2016-04-11T01:09:48
null
UTF-8
C++
false
false
4,863
cpp
// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved // Please see LICENSE.md in repository root for license information // https://github.com/ClockworkGameEngine/ClockworkGameEngine #include "ClockworkEditor.h" #include <TurboBadger/tb_window.h> #include <TurboBadger/tb_select.h> #include <TurboBadger/tb_editfield.h> #include <Clockwork/Core/Context.h> #include <Clockwork/UI/UI.h> #include "License/CELicenseSystem.h" #include "Resources/CEResourceOps.h" #include "CEPreferences.h" #include "CEEditor.h" #include "CEEvents.h" #include "Project/CEProject.h" #include "Project/ProjectUtils.h" #include "UINewProject.h" namespace ClockworkEditor { UINewProject::UINewProject(Context* context): UIModalOpWindow(context) { Editor* editor = GetSubsystem<Editor>(); Project* project = editor->GetProject(); UI* tbui = GetSubsystem<UI>(); window_->SetText("Project Type"); tbui->LoadResourceFile(window_->GetContentRoot(), "ClockworkEditor/editor/ui/newproject.tb.txt"); window_->ResizeToFitContent(); Center(); } UINewProject::~UINewProject() { } bool UINewProject::Create2DProject(const String& projectPath, const String& filename) { FileSystem* fileSystem = GetSubsystem<FileSystem>(); #ifdef CLOCKWORK_PLATFORM_OSX String templateSourceDir = fileSystem->GetAppBundleResourceFolder(); #else String templateSourceDir = fileSystem->GetProgramDir(); #endif templateSourceDir += "/ProjectTemplates/Project2D"; fileSystem->CopyDir(templateSourceDir + "/Resources", projectPath + "/Resources"); File file(context_, projectPath + "/" + filename + ".clockwork", FILE_WRITE); file.Close(); return true; } bool UINewProject::CreateEmptyProject(const String& projectPath, const String &filename) { FileSystem* fileSystem = GetSubsystem<FileSystem>(); #ifdef CLOCKWORK_PLATFORM_OSX String templateSourceDir = fileSystem->GetAppBundleResourceFolder(); #else String templateSourceDir = fileSystem->GetProgramDir(); #endif templateSourceDir += "/ProjectTemplates/EmptyProject"; fileSystem->CopyDir(templateSourceDir + "/Resources", projectPath + "/Resources"); File file(context_, projectPath + "/" + filename + ".clockwork", FILE_WRITE); file.Close(); return true; } bool UINewProject::Create3DProject(const String& projectPath, const String &filename) { FileSystem* fileSystem = GetSubsystem<FileSystem>(); #ifdef CLOCKWORK_PLATFORM_OSX String templateSourceDir = fileSystem->GetAppBundleResourceFolder(); #else String templateSourceDir = fileSystem->GetProgramDir(); #endif templateSourceDir += "/ProjectTemplates/Project3D"; fileSystem->CopyDir(templateSourceDir + "/Resources", projectPath + "/Resources"); File file(context_, projectPath + "/" + filename + ".clockwork", FILE_WRITE); file.Close(); return true; } bool UINewProject::OnEvent(const TBWidgetEvent &ev) { Editor* editor = GetSubsystem<Editor>(); UIModalOps* ops = GetSubsystem<UIModalOps>(); if (ev.type == EVENT_TYPE_CLICK) { if (ev.target->GetID() == TBIDC("cancel")) { ops->Hide(); return true; } int projectType = -1; if (ev.target->GetID() == TBIDC("project_empty")) { projectType = 0; } else if (ev.target->GetID() == TBIDC("project_2d")) { projectType = 1; } else if (ev.target->GetID() == TBIDC("project_3d")) { // BEGIN LICENSE MANAGEMENT LicenseSystem* licenseSystem = GetSubsystem<LicenseSystem>(); if (licenseSystem->IsStandardLicense()) { SharedPtr<UINewProject> keepAlive(this); UIModalOps* ops = GetSubsystem<UIModalOps>(); ops->Hide(); ops->ShowInfoModule3D(); return true; } // END LICENSE MANAGEMENT projectType = 2; } if (projectType != -1) { FileSystem* fileSystem = GetSubsystem<FileSystem>(); #ifdef CLOCKWORK_PLATFORM_OSX String templateSourceDir = fileSystem->GetAppBundleResourceFolder(); #else String templateSourceDir = fileSystem->GetProgramDir(); #endif if (projectType == 0) templateSourceDir += "/ProjectTemplates/EmptyProject"; else if (projectType == 1) templateSourceDir += "/ProjectTemplates/Project2D"; else templateSourceDir += "/ProjectTemplates/Project3D"; SharedPtr<UINewProject> keepAlive(this); UIModalOps* ops = GetSubsystem<UIModalOps>(); ops->Hide(); ops->ShowCreateProject(templateSourceDir); return true; } } return false; } }
[ "dragonCASTjosh@gmail.com" ]
dragonCASTjosh@gmail.com
08b4b9139afbbd8ac595493ba055d8bb15ddc9c0
d2de04d67eb9523d7e8412239371bae27b57a546
/build/Android/Debug/app/src/main/include/Fuse.Animations.RangeAdapter-1.h
9ac79c289f53429deb9abab8c489dcaa7f7770c1
[]
no_license
alloywheels/exploring
e103d6d4924dae117f019558018c1e48cd643e01
75d49914df0563d1956f998199724bc4e9c71a87
refs/heads/master
2021-09-01T21:12:12.052577
2017-12-28T16:10:20
2017-12-28T16:10:20
115,637,649
0
0
null
null
null
null
UTF-8
C++
false
false
1,680
h
// This file was generated based on '../../../AppData/Local/Fusetools/Packages/Fuse.Animations/1.4.2/RangeAdapter.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.IProperties.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.UX.IPropertyListener.h> namespace g{namespace Fuse{namespace Animations{struct RangeAdapter;}}} namespace g{namespace Uno{namespace UX{struct Property1;}}} namespace g{namespace Uno{namespace UX{struct PropertyObject;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{ namespace Fuse{ namespace Animations{ // public sealed class RangeAdapter<T> :36 // { struct RangeAdapter_type : ::g::Fuse::Node_type { ::g::Uno::UX::IPropertyListener interface6; }; RangeAdapter_type* RangeAdapter_typeof(); void RangeAdapter__OnRooted_fn(RangeAdapter* __this); void RangeAdapter__OnUnrooted_fn(RangeAdapter* __this); void RangeAdapter__get_Source_fn(RangeAdapter* __this, ::g::Uno::UX::Property1** __retval); void RangeAdapter__set_Source_fn(RangeAdapter* __this, ::g::Uno::UX::Property1* value); void RangeAdapter__UnoUXIPropertyListenerOnPropertyChanged_fn(RangeAdapter* __this, ::g::Uno::UX::PropertyObject* obj, ::g::Uno::UX::Selector* sel); struct RangeAdapter : ::g::Fuse::Behavior { uStrong< ::g::Uno::UX::Property1*> _Source; ::g::Uno::UX::Property1* Source(); void Source(::g::Uno::UX::Property1* value); }; // } }}} // ::g::Fuse::Animations
[ "turrifftyresandalloys@gmail.com" ]
turrifftyresandalloys@gmail.com
25975d8aebd927c5ec2b13d325d11ce20eeb9850
439d28f761c1774f759fdf720c14ab2108bb93b8
/Programming.in.th/11/1154.cpp
36dcb5e6719720007bbc2017867e835d5de785ee
[]
no_license
Chomtana/cptraining
19fec94cd489c6117f49bd6d80642d60079276f1
df380badd952dceb335525f03373738c35aa0b3a
refs/heads/master
2021-01-09T20:53:24.758998
2020-04-11T04:10:48
2020-04-11T04:10:48
56,289,132
0
0
null
null
null
null
UTF-8
C++
false
false
1,372
cpp
#include <bits/stdc++.h> #define for1(a,b,c) for(int (a)=(b);(a)<(c);(a)++) #define for2(i,a,b) for(int (i)=(a);((a)<=(b)?(i)<=(b):(i)>=(b));(i)+=((a)<=(b)?1:-1)) #define until(x) while(!(x)) #define all(x) x.begin(),x.end() #define mp make_pair #define subfunc(ret,name,args) function<ret args> name; name = [&] args #define hk 53 using namespace std; typedef long long ll; typedef long double ld; typedef pair<int,int> pii; typedef vector<int> vi; int n,m; char data[15005]; bool check(int k) { if (k==0) return true; unordered_map<ll,int> c(1000000); ll h = 0; ll powmax = 1; for1(i,0,k) { h *= hk; h += data[i]-'a'; if (i>0) powmax *= hk; } c[h]++; //cerr<<h<<endl; //cerr<<"bbb "<<n<<endl; for1(i,1,n-k+1) { //cerr<<"aaa "<<i<<endl; h -= (data[i-1]-'a')*powmax; h *= hk; h += data[i+k-1]-'a'; c[h]++; //cerr<<h<<endl; } for(auto p:c) { if (p.second>=m) return true; } return false; } int main() { //ios::sync_with_stdio(false); cout<<fixed; cin>>n>>m; cin.ignore(); gets(data); int l = 0;int r = n; while (l<=r) { int mid = (l+r)/2; if (check(mid)) { l = mid+1; } else { r = mid-1; } } //cerr<<check(0)<<endl; cout<<l-1; return 0; }
[ "Chomtana001@gmail.com" ]
Chomtana001@gmail.com
c922a23f1ad6c7c11ff3dbbcc248e4a96ae86e08
3c3605c6217d6680fb7c5276cfdaf9488d1d5d38
/TestWinRT/ItemsPage.xaml.h
67edfdd3a1f19f3b9d004842261f66ddb2b6739a
[]
no_license
rfog/WinRTvsWin32
f592d9ac0bba90f9171bbfe28105d5de8805768c
7f14197905eec12765ebab3168d0039e0c2d97b0
refs/heads/master
2021-01-22T06:58:55.524333
2013-03-21T21:24:11
2013-03-21T21:24:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
749
h
// // ItemsPage.xaml.h // Declaration of the ItemsPage class // #pragma once #include "Common\LayoutAwarePage.h" // Required by generated header #include "ItemsPage.g.h" namespace TestWinRT { /// <summary> /// A page that displays a collection of item previews. In the Split Application this page /// is used to display and select one of the available groups. /// </summary> public ref class ItemsPage sealed { public: ItemsPage(); protected: virtual void LoadState(Platform::Object^ navigationParameter, Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override; private: void ItemView_ItemClick(Platform::Object^ sender, Windows::UI::Xaml::Controls::ItemClickEventArgs^ e); }; }
[ "rafael.ontivero@gmail.com" ]
rafael.ontivero@gmail.com
74ec23a735894883419edc3ecbc58e205043a1b9
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1484496_0/C++/Konjac/c.cc
c4ad8a122999920c482ab27d2d943f3f0261e0f2
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,334
cc
#include<stdio.h> #include<string.h> #include<algorithm> #include<map> using namespace std; const int N = 22; int a[N], status[1<<N]; int q[1<<N]; int n; void output ( int t ) { for ( int i = 0, tag = 0;i < n;++i ) { if ( t & ( 1 << i ) ) { if ( tag ) printf ( " " ); printf ( "%d", a[i] ); tag = 1; } } printf ( "\n" ); } int hash[2000010]; void solve() { scanf ( "%d", &n ); for ( int i = 0;i < n;++i ) scanf ( "%d", a + i ); int l = 0, r = 0; memset ( status, -1, sizeof ( status ) ); memset ( hash, -1, sizeof ( hash ) ); q[r++] = 0, status[0] = 0; while ( l < r ) { int s = q[l++]; for ( int i = 0;i < n;++i ) { if ( s& ( 1 << i ) ) continue; int t = ( s | ( 1 << i ) ); if ( status[t] != -1 ) continue; status[t] = status[s] + a[i]; if ( hash[status[t]] != -1 ) { output ( t ); output ( hash[status[t]] ); return; } hash[status[t]] = t; q[r++] = t; } } printf ( "Impossible\n" ); return; } int main() { int T; scanf ( "%d", &T ); for ( int t = 1;t <= T;++t ) { printf ( "Case #%d:\n", t ); solve(); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
fcd01b24d357a2fac5dc4f6bad657e5ebb1f8c3a
3e5bda41c14806ff2e459acb15e63022ba5eeb47
/OnlineJudge/LeetCode/第1个进度/387.字符串中的第一个唯一字符.cpp
3424d2cf53b0209cfc5dc12d20910b10829a7610
[]
no_license
CrazyIEEE/algorithm
d3ab6e50b3e54a99d86924c6e4a86b8c491b2a40
89755fc95c2bace7e644af189ec29df9a2ffb277
refs/heads/master
2022-12-31T11:13:03.868343
2020-10-14T13:18:49
2020-10-14T13:18:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,473
cpp
/* * @lc app=leetcode.cn id=387 lang=cpp * * [387] 字符串中的第一个唯一字符 * * https://leetcode-cn.com/problems/first-unique-character-in-a-string/description/ * * algorithms * Easy (37.03%) * Likes: 181 * Dislikes: 0 * Total Accepted: 61.3K * Total Submissions: 141.5K * Testcase Example: '"leetcode"' * * 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 * * 案例: * * * s = "leetcode" * 返回 0. * * s = "loveleetcode", * 返回 2. * * * * * 注意事项:您可以假定该字符串只包含小写字母。 * */ #include "string" #include "vector" #include "algorithm" using namespace std; // @lc code=start class Solution { public: int firstUniqChar(string s) { vector<pair<char, int>> vec; for (int i = 0; i < s.size(); i++) { auto it = find_if(vec.begin(), vec.end(), [&](const pair<char, int> &p) { return p.first == s[i]; }); if (it == vec.end()) { vec.push_back({s[i], i}); } else { it->second = -1; } } int index = -1; for (int i = 0; i < vec.size(); i++) { if (vec[i].second != -1) { index = vec[i].second; break; } } return index; } }; // @lc code=end
[ "228117330@qq.com" ]
228117330@qq.com
ee9afae15833a55a1aa6e5addf050efde14a81cd
1653acd0b8a476b55128b9af60c74366cc730568
/2017-2/msgs/msgsupp.cc
59752ac0fad253623191133913afb2b708c5d304
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
sgtest/p4test
5c6ab62098e99413af8ee12b5911ad9cf7fc081e
0b065a1f4aad902f5860d03fa44d14e00ee980a4
refs/heads/master
2020-04-27T16:46:05.018649
2019-02-07T10:04:05
2019-02-07T10:04:05
174,492,667
1
0
null
null
null
null
UTF-8
C++
false
false
51,847
cc
/* * Copyright 1995, 2000 Perforce Software. All rights reserved. * * This file is part of Perforce - the FAST SCM System. */ /* * msgsupp - definitions of errors for zlib C++ interface * * Note: * * Never re-use an error code value, these may have already been * translated, so using it for a different error is not OK. * * ErrorIds which are no longer used should be moved to the bottom * of the list, with a trailing comment like this: // DEPRECATED. * We keep these to maintain compatibility between newer api clients * and older servers which send old ErrorIds. * * Its okay to add a message in the middle of the file. * * When adding a new error make sure its greater than the current high * value and update the following number: * * Current high value for a MsgSupp error code is: 318 */ # include <error.h> # include <errornum.h> # include <msgsupp.h> ErrorId MsgSupp::NoTransVar = { ErrorOf( ES_SUPP, 1, E_WARN, EV_ILLEGAL, 2 ), "No Translation for parameter '%arg%' value '%value%'!" } ; ErrorId MsgSupp::InvalidDate = { ErrorOf( ES_SUPP, 2, E_FAILED, EV_USAGE, 1 ), "Invalid date '%date%'." } ; ErrorId MsgSupp::InvalidCharset = { ErrorOf( ES_SUPP, 244, E_FAILED, EV_USAGE, 1 ), "Invalid charset '%charset%'." } ; ErrorId MsgSupp::TooMany = { ErrorOf( ES_SUPP, 3, E_FATAL, EV_FAULT, 0 ), "Too many options on command!" } ; ErrorId MsgSupp::Invalid = { ErrorOf( ES_SUPP, 4, E_FAILED, EV_USAGE, 1 ), "Invalid option: -%option%." } ; ErrorId MsgSupp::NeedsArg = { ErrorOf( ES_SUPP, 5, E_FAILED, EV_USAGE, 1 ), "Option: -%option% needs argument." } ; ErrorId MsgSupp::NeedsNonNegArg = { ErrorOf( ES_SUPP, 33, E_FAILED, EV_USAGE, 1 ), "Option: -%option% needs a non-negative integer argument." } ; ErrorId MsgSupp::Needs2Arg = { ErrorOf( ES_SUPP, 23, E_FAILED, EV_USAGE, 1 ), "Option: -%option% needs a flag and an argument." } ; ErrorId MsgSupp::ExtraArg = { ErrorOf( ES_SUPP, 6, E_FAILED, EV_USAGE, 0 ), "Unexpected arguments." } ; ErrorId MsgSupp::WrongArg = { ErrorOf( ES_SUPP, 7, E_FAILED, EV_USAGE, 0 ), "Missing/wrong number of arguments." } ; ErrorId MsgSupp::Usage = { ErrorOf( ES_SUPP, 8, E_FAILED, EV_USAGE, 1 ), "Usage: %text%" } ; ErrorId MsgSupp::OptionData = { ErrorOf( ES_SUPP, 31, E_INFO, EV_NONE, 3 ), "-%flag%%flag2%='%value%'" } ; ErrorId MsgSupp::NoParm = { ErrorOf( ES_SUPP, 9, E_FATAL, EV_FAULT, 1 ), "Required parameter '%arg%' not set!" } ; //NOTRANS ErrorId MsgSupp::NoUnixReg = { ErrorOf( ES_SUPP, 10, E_WARN, EV_NONE, 0 ), "Can't set registry on UNIX." } ; ErrorId MsgSupp::NoSuchVariable = { ErrorOf( ES_SUPP, 34, E_WARN, EV_NONE, 1 ), "Unrecognized variable name %varName%. Comment lines should contain '#' in column 1." } ; ErrorId MsgSupp::HidesVar = { ErrorOf( ES_SUPP, 11, E_WARN, EV_NONE, 1 ), "Warning: environment variable hides registry definition of %name%." } ; ErrorId MsgSupp::NoP4Config = { ErrorOf( ES_SUPP, 12, E_WARN, EV_NONE, 0 ), "Can't save in config if %'P4CONFIG'% not set." } ; ErrorId MsgSupp::VariableData = { ErrorOf( ES_SUPP, 32, E_INFO, EV_NONE, 3 ), "%name%=%value% %source%" } ; ErrorId MsgSupp::PartialChar = { ErrorOf( ES_SUPP, 13, E_INFO, EV_ILLEGAL, 0 ), "Partial character in translation" } ; ErrorId MsgSupp::NoTrans = { ErrorOf( ES_SUPP, 14, E_WARN, EV_ILLEGAL, 2 ), "Translation of file content failed near line %arg%[ file %name%]" } ; ErrorId MsgSupp::ConvertFailed = { ErrorOf( ES_SUPP, 36, E_WARN, EV_ILLEGAL, 3 ), "Translation of %path% from %charset1% to %charset2% failed -- correct before proceeding." } ; ErrorId MsgSupp::BadMangleParams = { ErrorOf( ES_SUPP, 22, E_FATAL, EV_FAULT, 0 ), "Bad parameters passed to mangler!"} ; //NOTRANS ErrorId MsgSupp::BadOS = { ErrorOf( ES_SUPP, 15, E_FATAL, EV_FAULT, 1 ), "Don't know how to translate paths for OS '%arg%'!" } ; //NOTRANS ErrorId MsgSupp::Deflate = { ErrorOf( ES_SUPP, 16, E_FATAL, EV_FAULT, 0 ), "Deflate failed!" } ; //NOTRANS ErrorId MsgSupp::DeflateEnd = { ErrorOf( ES_SUPP, 17, E_FATAL, EV_FAULT, 0 ), "DeflateEnd failed!" } ; //NOTRANS ErrorId MsgSupp::DeflateInit = { ErrorOf( ES_SUPP, 18, E_FATAL, EV_FAULT, 0 ), "DeflateInit failed!" } ; //NOTRANS ErrorId MsgSupp::Inflate = { ErrorOf( ES_SUPP, 19, E_FATAL, EV_FAULT, 0 ), "Inflate failed!" } ; //NOTRANS ErrorId MsgSupp::InflateInit = { ErrorOf( ES_SUPP, 20, E_FATAL, EV_FAULT, 0 ), "InflateInit failed!" } ; //NOTRANS ErrorId MsgSupp::MagicHeader = { ErrorOf( ES_SUPP, 21, E_FATAL, EV_FAULT, 0 ), "Gzip magic header wrong!" } ; //NOTRANS ErrorId MsgSupp::RegexError = { ErrorOf( ES_SUPP, 30, E_FAILED, EV_USAGE, 1 ), "Regular expression error: %text%" } ; ErrorId MsgSupp::OptionChange = { ErrorOf( ES_SUPP, 37, E_INFO, EV_NONE, 0 ), "%'--change (-c)'%: specifies the changelist to use for the command." } ; ErrorId MsgSupp::OptionPort = { ErrorOf( ES_SUPP, 38, E_INFO, EV_NONE, 0 ), "%'--port (-p)'%: specifies the network address of the server." } ; ErrorId MsgSupp::OptionUser = { ErrorOf( ES_SUPP, 39, E_INFO, EV_NONE, 0 ), "%'--user (-u)'%: specifies the user name." } ; ErrorId MsgSupp::OptionClient = { ErrorOf( ES_SUPP, 40, E_INFO, EV_NONE, 0 ), "%'--client (-c)'%: specifies the client workspace name." } ; ErrorId MsgSupp::OptionPreview = { ErrorOf( ES_SUPP, 41, E_INFO, EV_NONE, 0 ), "%'--preview (-n)'%: specifies that the command should display a preview of the results, but not execute them." } ; ErrorId MsgSupp::OptionDelete = { ErrorOf( ES_SUPP, 42, E_INFO, EV_NONE, 0 ), "%'--delete (-d)'%: specifies that the object should be deleted." } ; ErrorId MsgSupp::OptionForce = { ErrorOf( ES_SUPP, 43, E_INFO, EV_NONE, 0 ), "%'--force (-f)'%: overrides the normal safety checks." } ; ErrorId MsgSupp::OptionInput = { ErrorOf( ES_SUPP, 44, E_INFO, EV_NONE, 0 ), "%'--input (-i)'%: specifies that the data should be read from standard input." } ; ErrorId MsgSupp::OptionOutput = { ErrorOf( ES_SUPP, 45, E_INFO, EV_NONE, 0 ), "%'--output (-o)'%: specifies that the data should be written to standard output." } ; ErrorId MsgSupp::OptionMax = { ErrorOf( ES_SUPP, 46, E_INFO, EV_NONE, 0 ), "%'--max (-m)'%: specifies the maximum number of objects." } ; ErrorId MsgSupp::OptionQuiet = { ErrorOf( ES_SUPP, 47, E_INFO, EV_NONE, 0 ), "%'--quiet (-q)'%: suppresses normal information output." } ; ErrorId MsgSupp::OptionShort = { ErrorOf( ES_SUPP, 48, E_INFO, EV_NONE, 0 ), "%'--short (-s)'%: displays a brief version of the results." } ; ErrorId MsgSupp::OptionLong = { ErrorOf( ES_SUPP, 49, E_INFO, EV_NONE, 0 ), "%'--long (-l)'%: displays a complete version of the results." } ; ErrorId MsgSupp::OptionAll = { ErrorOf( ES_SUPP, 50, E_INFO, EV_NONE, 0 ), "%'--all (-a)'%: specifies that the command should include all objects." } ; ErrorId MsgSupp::OptionFiletype = { ErrorOf( ES_SUPP, 51, E_INFO, EV_NONE, 0 ), "%'--filetype (-t)'%: specifies the filetype to be used." } ; ErrorId MsgSupp::OptionStream = { ErrorOf( ES_SUPP, 52, E_INFO, EV_NONE, 0 ), "%'--stream (-S)'%: specifies the stream to be used." } ; ErrorId MsgSupp::OptionParent = { ErrorOf( ES_SUPP, 53, E_INFO, EV_NONE, 0 ), "%'--parent (-P)'%: specifies the stream to be used as the parent." } ; ErrorId MsgSupp::OptionClientName = { ErrorOf( ES_SUPP, 54, E_INFO, EV_NONE, 0 ), "%'--client (-C)'%: specifies the client workspace name." } ; ErrorId MsgSupp::OptionHost = { ErrorOf( ES_SUPP, 55, E_INFO, EV_NONE, 0 ), "%'--host (-H)'%: specifies the host name, overriding the value from the network configuration." } ; ErrorId MsgSupp::OptionPassword = { ErrorOf( ES_SUPP, 56, E_INFO, EV_NONE, 0 ), "%'--password (-P)'%: specifies the password to be used." } ; ErrorId MsgSupp::OptionCharset = { ErrorOf( ES_SUPP, 57, E_INFO, EV_NONE, 0 ), "%'--charset (-C)'%: specifies the client's character set." } ; ErrorId MsgSupp::OptionCmdCharset = { ErrorOf( ES_SUPP, 58, E_INFO, EV_NONE, 0 ), "%'--cmd-charset (-Q)'%: specifies the client's command character set." } ; ErrorId MsgSupp::OptionVariable = { ErrorOf( ES_SUPP, 59, E_INFO, EV_NONE, 0 ), "%'--variable (-v)'%: specifies the value of a configurable variable." } ; ErrorId MsgSupp::OptionHelp = { ErrorOf( ES_SUPP, 60, E_INFO, EV_NONE, 0 ), "%'--help (-h)'%: provides help." } ; ErrorId MsgSupp::OptionVersion = { ErrorOf( ES_SUPP, 61, E_INFO, EV_NONE, 0 ), "%'--version (-V)'%: displays version information." } ; ErrorId MsgSupp::OptionBatchsize = { ErrorOf( ES_SUPP, 62, E_INFO, EV_NONE, 0 ), "%'--batchsize (-b)'%: specifies the number of objects in a single batch." } ; ErrorId MsgSupp::OptionMessageType = { ErrorOf( ES_SUPP, 63, E_INFO, EV_NONE, 0 ), "%'--message-type (-s)'%: includes message type information in the output." } ; ErrorId MsgSupp::OptionXargs = { ErrorOf( ES_SUPP, 64, E_INFO, EV_NONE, 0 ), "%'--xargs (-x)'%: reads input arguments from the specified file." } ; ErrorId MsgSupp::OptionExclusive = { ErrorOf( ES_SUPP, 65, E_INFO, EV_NONE, 0 ), "%'--exclusive (-x)'%: indicates that the command should process files of type +l." } ; ErrorId MsgSupp::OptionProgress = { ErrorOf( ES_SUPP, 66, E_INFO, EV_NONE, 0 ), "%'--progress (-I)'%: indicates that the command should display progress information." } ; ErrorId MsgSupp::OptionDowngrade = { ErrorOf( ES_SUPP, 67, E_INFO, EV_NONE, 0 ), "%'--downgrade (-d)'%: indicates that the operation should be downgraded." } ; ErrorId MsgSupp::OptionDirectory = { ErrorOf( ES_SUPP, 68, E_INFO, EV_NONE, 0 ), "%'--directory (-d)'%: specifies the directory to be used as the current directory." } ; ErrorId MsgSupp::OptionRetries = { ErrorOf( ES_SUPP, 69, E_INFO, EV_NONE, 0 ), "%'--retries (-r)'%: specifies the number of times the command may be retried." } ; ErrorId MsgSupp::OptionNoIgnore = { ErrorOf( ES_SUPP, 70, E_INFO, EV_NONE, 0 ), "%'--no-ignore (-I)'%: specifies that the command should ignore the %'P4IGNORE'% settings." } ; ErrorId MsgSupp::OptionCentralUsers = { ErrorOf( ES_SUPP, 71, E_INFO, EV_NONE, 0 ), "%'--central-only (-c)'%: include user information from the central server only." } ; ErrorId MsgSupp::OptionReplicaUsers = { ErrorOf( ES_SUPP, 72, E_INFO, EV_NONE, 0 ), "%'--replica-only (-r)'%: include user information from the replica server only." } ; ErrorId MsgSupp::OptionFullBranch = { ErrorOf( ES_SUPP, 73, E_INFO, EV_NONE, 0 ), "%'--full-branch (-F)'%: include the full generated branch spec in the output." } ; ErrorId MsgSupp::OptionSpecFixStatus = { ErrorOf( ES_SUPP, 74, E_INFO, EV_NONE, 0 ), "%'--status (-s)'%: include the fix status for each job in the spec." } ; ErrorId MsgSupp::OptionChangeType = { ErrorOf( ES_SUPP, 75, E_INFO, EV_NONE, 0 ), "%'--type (-t)'%: specify the type of this change (public or restricted)." } ; ErrorId MsgSupp::OptionChangeUpdate = { ErrorOf( ES_SUPP, 76, E_INFO, EV_NONE, 0 ), "%'--update (-u)'%: allows the owner of a submitted change to update it." } ; ErrorId MsgSupp::OptionOriginal = { ErrorOf( ES_SUPP, 77, E_INFO, EV_NONE, 0 ), "%'--original (-O)'%: specifies the original change number of a renumbered change." } ; ErrorId MsgSupp::OptionChangeUser = { ErrorOf( ES_SUPP, 78, E_INFO, EV_NONE, 0 ), "%'--new-user (-U)'%: specifies the new user of an empty pending change." } ; ErrorId MsgSupp::OptionTemplate = { ErrorOf( ES_SUPP, 79, E_INFO, EV_NONE, 0 ), "%'--template (-t)'%: specifies the template for a client or label." } ; ErrorId MsgSupp::OptionSwitch = { ErrorOf( ES_SUPP, 80, E_INFO, EV_NONE, 0 ), "%'--switch (-s)'%: specifies to switch this client to a different stream." } ; ErrorId MsgSupp::OptionTemporary = { ErrorOf( ES_SUPP, 81, E_INFO, EV_NONE, 0 ), "%'--temporary (-x)'%: specifies to create a temporary client." } ; ErrorId MsgSupp::OptionOwner = { ErrorOf( ES_SUPP, 82, E_INFO, EV_NONE, 0 ), "%'--owner (-a)'%: enables an owner of the group to update it." } ; ErrorId MsgSupp::OptionAdministrator = { ErrorOf( ES_SUPP, 83, E_INFO, EV_NONE, 0 ), "%'--administrator (-A)'%: enables an administrator to create a new group." } ; ErrorId MsgSupp::OptionGlobal = { ErrorOf( ES_SUPP, 84, E_INFO, EV_NONE, 0 ), "%'--global (-g)'%: enables modifying a global label from an Edge Server." } ; ErrorId MsgSupp::OptionStreamType = { ErrorOf( ES_SUPP, 85, E_INFO, EV_NONE, 0 ), "%'--type (-t)'%: specifies the type of stream" } ; ErrorId MsgSupp::OptionVirtualStream = { ErrorOf( ES_SUPP, 86, E_INFO, EV_NONE, 0 ), "%'--virtual (-v)'%: specifies this is a virtual stream." } ; ErrorId MsgSupp::OptionBrief = { ErrorOf( ES_SUPP, 87, E_INFO, EV_NONE, 0 ), "%'--brief (-L)'%: displays truncated changelist description." } ; ErrorId MsgSupp::OptionInherited = { ErrorOf( ES_SUPP, 88, E_INFO, EV_NONE, 0 ), "%'--inherited (-i)'%: includes changes integrated into the files." } ; ErrorId MsgSupp::OptionShowTime = { ErrorOf( ES_SUPP, 89, E_INFO, EV_NONE, 0 ), "%'--show-time (-t)'%: includes the time in the output."} ; ErrorId MsgSupp::OptionChangeStatus = { ErrorOf( ES_SUPP, 90, E_INFO, EV_NONE, 0 ), "%'--status (-s)'%: specifies the change status." } ; ErrorId MsgSupp::OptionLimitClient = { ErrorOf( ES_SUPP, 91, E_INFO, EV_NONE, 0 ), "%'--client (-C)'%: limit the results to this client workspace." } ; ErrorId MsgSupp::OptionLabelName = { ErrorOf( ES_SUPP, 92, E_INFO, EV_NONE, 0 ), "%'--label (-l)'%: specifies the name of the label." } ; ErrorId MsgSupp::OptionRunOnMaster = { ErrorOf( ES_SUPP, 93, E_INFO, EV_NONE, 0 ), "%'--global (-M)'%: create this list on the master server." } ; ErrorId MsgSupp::OptionArchive = { ErrorOf( ES_SUPP, 94, E_INFO, EV_NONE, 0 ), "%'--archive (-A)'%: enables access to the archive depot" } ; ErrorId MsgSupp::OptionBlocksize = { ErrorOf( ES_SUPP, 95, E_INFO, EV_NONE, 0 ), "%'--blocksize (-b)'%: specifies the blocksize to be used for calculations." } ; ErrorId MsgSupp::OptionHuman1024 = { ErrorOf( ES_SUPP, 96, E_INFO, EV_NONE, 0 ), "%'--human (-h)'%: displays output using human-friendly abbreviations." } ; ErrorId MsgSupp::OptionHuman1000 = { ErrorOf( ES_SUPP, 97, E_INFO, EV_NONE, 0 ), "%'--human-1000 (-H)'%: displays human-friendly output using units of 1000." } ; ErrorId MsgSupp::OptionSummary = { ErrorOf( ES_SUPP, 98, E_INFO, EV_NONE, 0 ), "%'--summary (-s)'%: displays summary information." } ; ErrorId MsgSupp::OptionShelved = { ErrorOf( ES_SUPP, 99, E_INFO, EV_NONE, 0 ), "%'--shelved (-S)'%: specifies to access shelved files." } ; ErrorId MsgSupp::OptionUnload = { ErrorOf( ES_SUPP, 100, E_INFO, EV_NONE, 0 ), "%'--unload (-U)'%: enables access to unloaded objects." } ; ErrorId MsgSupp::OptionUnloadLimit = { ErrorOf( ES_SUPP, 264, E_INFO, EV_NONE, 0 ), "%'--unload-limit (-u)'%: threshold number of days after which an unused client will be unloaded." } ; ErrorId MsgSupp::OptionOmitLazy = { ErrorOf( ES_SUPP, 101, E_INFO, EV_NONE, 0 ), "%'--omit-lazy (-z)'%: omits lazy copies from the results." } ; ErrorId MsgSupp::OptionLeaveKeywords = { ErrorOf( ES_SUPP, 102, E_INFO, EV_NONE, 0 ), "%'--leave-keywords (-k)'%: specifies that RCS keywords are not to be expanded in the output." } ; ErrorId MsgSupp::OptionOutputFile = { ErrorOf( ES_SUPP, 103, E_INFO, EV_NONE, 0 ), "%'--file (-o)'%: specifies the name of the output file." } ; ErrorId MsgSupp::OptionExists = { ErrorOf( ES_SUPP, 104, E_INFO, EV_NONE, 0 ), "%'--exists (-e)'%: includes only files which are not deleted." } ; ErrorId MsgSupp::OptionContent = { ErrorOf( ES_SUPP, 105, E_INFO, EV_NONE, 0 ), "%'--content (-h)'%: display file content history instead of file name history." } ; ErrorId MsgSupp::OptionOmitPromoted = { ErrorOf( ES_SUPP, 106, E_INFO, EV_NONE, 0 ), "%'--omit-promoted (-p)'%: disables following content of promoted task streams." } ; ErrorId MsgSupp::OptionOmitMoved = { ErrorOf( ES_SUPP, 107, E_INFO, EV_NONE, 0 ), "%'--omit-moved (-1)'%: disables following renames resulting from '%'p4 move'%'." } ; ErrorId MsgSupp::OptionKeepClient = { ErrorOf( ES_SUPP, 108, E_INFO, EV_NONE, 0 ), "%'--keep-client (-k)'%: leaves the client's copy of the files untouched." } ; ErrorId MsgSupp::OptionFileCharset = { ErrorOf( ES_SUPP, 109, E_INFO, EV_NONE, 0 ), "%'--file-charset (-Q)'%: specifies a character set override for this file." } ; ErrorId MsgSupp::OptionVirtual = { ErrorOf( ES_SUPP, 110, E_INFO, EV_NONE, 0 ), "%'--virtual (-v)'%: performs the action on the server without updating client data." } ; ErrorId MsgSupp::OptionGenerate = { ErrorOf( ES_SUPP, 111, E_INFO, EV_NONE, 0 ), "%'--generate (-g)'%: generate a new unique value." } ; ErrorId MsgSupp::OptionConfigure = { ErrorOf( ES_SUPP, 276, E_INFO, EV_NONE, 0 ), "%'--configure (-c)'%: configure edge or commit server." } ; ErrorId MsgSupp::OptionUsage = { ErrorOf( ES_SUPP, 112, E_INFO, EV_NONE, 0 ), "%'--usage (-u)'%: display the current usage levels." } ; ErrorId MsgSupp::OptionTags = { ErrorOf( ES_SUPP, 113, E_INFO, EV_NONE, 0 ), "%'--tags (-T)'%: specify which tags to include in the results." } ; ErrorId MsgSupp::OptionFilter = { ErrorOf( ES_SUPP, 114, E_INFO, EV_NONE, 0 ), "%'--filter (-F)'%: specify filters which limit the results." } ; ErrorId MsgSupp::OptionJob = { ErrorOf( ES_SUPP, 115, E_INFO, EV_NONE, 0 ), "%'--job (-j)'%: specifies the job name." } ; ErrorId MsgSupp::OptionExpression = { ErrorOf( ES_SUPP, 116, E_INFO, EV_NONE, 0 ), "%'--expression (-e)'%: specifies the expression to filter the results." } ; ErrorId MsgSupp::OptionNoCaseExpr = { ErrorOf( ES_SUPP, 117, E_INFO, EV_NONE, 0 ), "%'--no-case-expression (-E)'%: specifies the case-insensitive expression to filter the results." } ; ErrorId MsgSupp::OptionIncrement = { ErrorOf( ES_SUPP, 118, E_INFO, EV_NONE, 0 ), "%'--increment (-i)'%: specifies that the value is to be incremented by 1." } ; ErrorId MsgSupp::OptionDiffFlags = { ErrorOf( ES_SUPP, 119, E_INFO, EV_NONE, 0 ), "%'--diff-flags (-d)'%: specifies flags for diff behavior." } ; ErrorId MsgSupp::OptionFixStatus = { ErrorOf( ES_SUPP, 120, E_INFO, EV_NONE, 0 ), "%'--fix-status (-s)'%: specifies the status for this fix." } ; ErrorId MsgSupp::OptionShelf = { ErrorOf( ES_SUPP, 121, E_INFO, EV_NONE, 0 ), "%'--shelf (-s)'%: specifies the shelved changelist number to use." } ; ErrorId MsgSupp::OptionReplace = { ErrorOf( ES_SUPP, 122, E_INFO, EV_NONE, 0 ), "%'--replace (-r)'%: specifies to replace all shelved files in the changelist." } ; ErrorId MsgSupp::OptionShelveOpts = { ErrorOf( ES_SUPP, 123, E_INFO, EV_NONE, 0 ), "%'--shelve-options (-a)'%: specifies options for handling unchanged files." } ; ErrorId MsgSupp::OptionBranch = { ErrorOf( ES_SUPP, 124, E_INFO, EV_NONE, 0 ), "%'--branch (-b)'%: specifies the branch name to use." } ; ErrorId MsgSupp::OptionSubmitShelf = { ErrorOf( ES_SUPP, 125, E_INFO, EV_NONE, 0 ), "%'--shelf (-e)'%: specifies the shelved changelist to submit." } ; ErrorId MsgSupp::OptionSubmitOpts = { ErrorOf( ES_SUPP, 126, E_INFO, EV_NONE, 0 ), "%'--submit-options (-f)'%: specifies options for handling unchanged files." } ; ErrorId MsgSupp::OptionReopen = { ErrorOf( ES_SUPP, 127, E_INFO, EV_NONE, 0 ), "%'--reopen (-r)'%: specifies that the files should be reopened after submit." } ; ErrorId MsgSupp::OptionDescription = { ErrorOf( ES_SUPP, 128, E_INFO, EV_NONE, 0 ), "%'--description (-d)'%: specifies the description of the change." } ; ErrorId MsgSupp::OptionTamper = { ErrorOf( ES_SUPP, 129, E_INFO, EV_NONE, 0 ), "%'--tamper-check (-t)'%: specifies that file digests should be used to detect tampering." } ; ErrorId MsgSupp::OptionCompress = { ErrorOf( ES_SUPP, 130, E_INFO, EV_NONE, 0 ), "%'--compress (-z)'%: specifies that the output should be compressed." } ; ErrorId MsgSupp::OptionDate = { ErrorOf( ES_SUPP, 131, E_INFO, EV_NONE, 0 ), "%'--date (-d)'%: specifies to unload all objects older than that date." } ; ErrorId MsgSupp::OptionStreamName = { ErrorOf( ES_SUPP, 132, E_INFO, EV_NONE, 0 ), "%'--stream (-s)'%: specifies the stream name." } ; ErrorId MsgSupp::OptionReverse = { ErrorOf( ES_SUPP, 133, E_INFO, EV_NONE, 0 ), "%'--reverse (-r)'%: specifies to reverse the direction of the branch view." } ; ErrorId MsgSupp::OptionWipe = { ErrorOf( ES_SUPP, 134, E_INFO, EV_NONE, 0 ), "%'--erase (-w)'%: removes the object from the client machine." } ; ErrorId MsgSupp::OptionUnchanged = { ErrorOf( ES_SUPP, 135, E_INFO, EV_NONE, 0 ), "%'--unchanged (-a)'%: specifies that only unchanged files are affected." } ; ErrorId MsgSupp::OptionDepot = { ErrorOf( ES_SUPP, 136, E_INFO, EV_NONE, 0 ), "%'--depot (-D)'%: specifies the depot name." } ; ErrorId MsgSupp::OptionKeepHead = { ErrorOf( ES_SUPP, 137, E_INFO, EV_NONE, 0 ), "%'--keep-head (-h)'%: specifies the head revision is not to be processed." } ; ErrorId MsgSupp::OptionPurge = { ErrorOf( ES_SUPP, 138, E_INFO, EV_NONE, 0 ), "%'--purge (-p)'%: specifies that the revisions are to be purged." } ; ErrorId MsgSupp::OptionForceText = { ErrorOf( ES_SUPP, 139, E_INFO, EV_NONE, 0 ), "%'--force-text (-t)'%: specifies that text revisions are to be processed." } ; ErrorId MsgSupp::OptionBinaryAsText = { ErrorOf( ES_SUPP, 140, E_INFO, EV_NONE, 0 ), "%'--binary-as-text (-t)'%: specifies that binary files are to be processed." } ; ErrorId MsgSupp::OptionBypassFlow = { ErrorOf( ES_SUPP, 141, E_INFO, EV_NONE, 0 ), "%'--bypass-flow (-F)'%: forces the command to process against a stream's expected flow." } ; ErrorId MsgSupp::OptionShowChange = { ErrorOf( ES_SUPP, 142, E_INFO, EV_NONE, 0 ), "%'--show-change (-c)'%: show changelist numbers rather than revision numbers." } ; ErrorId MsgSupp::OptionFollowBranch = { ErrorOf( ES_SUPP, 143, E_INFO, EV_NONE, 0 ), "%'--follow-branch (-i)'%: include the revisions of the source file up to the branch point." } ; ErrorId MsgSupp::OptionFollowInteg = { ErrorOf( ES_SUPP, 144, E_INFO, EV_NONE, 0 ), "%'--follow-integ (-I)'%: include all integrations into the file." } ; ErrorId MsgSupp::OptionSourceFile = { ErrorOf( ES_SUPP, 145, E_INFO, EV_NONE, 0 ), "%'--source-file (-s)'%: treat fromFile as the source and both sides of the branch view as the target." } ; ErrorId MsgSupp::OptionOutputFlags = { ErrorOf( ES_SUPP, 146, E_INFO, EV_NONE, 0 ), "%'--output-flags (-O)'%: specifies codes controlling the command output." } ; ErrorId MsgSupp::OptionResolveFlags = { ErrorOf( ES_SUPP, 148, E_INFO, EV_NONE, 0 ), "%'--resolve-flags (-A)'%: controls which types of resolves are performed." } ; ErrorId MsgSupp::OptionAcceptFlags = { ErrorOf( ES_SUPP, 149, E_INFO, EV_NONE, 0 ), "%'--accept-flags (-a)'%: specifies the level of automatic resolves accepted." } ; ErrorId MsgSupp::OptionIntegFlags = { ErrorOf( ES_SUPP, 150, E_INFO, EV_NONE, 0 ), "%'--integ-flags (-R)'%: specifies how integrate should schedule resolves." } ; ErrorId MsgSupp::OptionDeleteFlags = { ErrorOf( ES_SUPP, 151, E_INFO, EV_NONE, 0 ), "%'--delete-flags (-D)'%: specifies how integration should handle deleted files." } ; ErrorId MsgSupp::OptionRestrictFlags = { ErrorOf( ES_SUPP, 152, E_INFO, EV_NONE, 0 ), "%'--restrict-flags (-R)'%: limits the output to specific files." } ; ErrorId MsgSupp::OptionSortFlags = { ErrorOf( ES_SUPP, 153, E_INFO, EV_NONE, 0 ), "%'--sort-flags (-S)'%: changes the order of output." } ; ErrorId MsgSupp::OptionForceFlag = { ErrorOf( ES_SUPP, 175, E_INFO, EV_NONE, 0 ), "%'--force-flag (-F)'%: optional force behavior when deleting clients." } ; ErrorId MsgSupp::OptionUseList = { ErrorOf( ES_SUPP, 154, E_INFO, EV_NONE, 0 ), "%'--use-list (-L)'%: collects multiple file arguments into an in-memory list." } ; ErrorId MsgSupp::OptionPublish = { ErrorOf( ES_SUPP, 155, E_INFO, EV_NONE, 0 ), "%'--publish (-p)'%: populates the client workspace but does not update the server." } ; ErrorId MsgSupp::OptionSafe = { ErrorOf( ES_SUPP, 156, E_INFO, EV_NONE, 0 ), "%'--safe (-s)'%: performs a safety check before sending the file." } ; ErrorId MsgSupp::OptionIsGroup = { ErrorOf( ES_SUPP, 157, E_INFO, EV_NONE, 0 ), "%'--group (-g)'%: indicates that the argument is a group name." } ; ErrorId MsgSupp::OptionIsUser = { ErrorOf( ES_SUPP, 158, E_INFO, EV_NONE, 0 ), "%'--user (-u)'%: indicates that the argument is a user name." } ; ErrorId MsgSupp::OptionIsOwner = { ErrorOf( ES_SUPP, 159, E_INFO, EV_NONE, 0 ), "%'--owner (-o)'%: indicates that the argument is an owner." } ; ErrorId MsgSupp::OptionVerbose = { ErrorOf( ES_SUPP, 160, E_INFO, EV_NONE, 0 ), "%'--verbose (-v)'%: includes additional information in the output." } ; ErrorId MsgSupp::OptionLineNumber = { ErrorOf( ES_SUPP, 161, E_INFO, EV_NONE, 0 ), "%'--line-number (-n)'%: print line number with output lines." } ; ErrorId MsgSupp::OptionInvertMatch = { ErrorOf( ES_SUPP, 162, E_INFO, EV_NONE, 0 ), "%'--invert-match (-v)'%: select non-matching lines." } ; ErrorId MsgSupp::OptionFilesWithMatches = { ErrorOf( ES_SUPP, 163, E_INFO, EV_NONE, 0 ), "%'--files-with-matches (-l)'%: only print files containing matches." } ; ErrorId MsgSupp::OptionFilesWithoutMatch = { ErrorOf( ES_SUPP, 164, E_INFO, EV_NONE, 0 ), "%'--files-without-match (-L)'%: only print files containing no match." } ; ErrorId MsgSupp::OptionNoMessages = { ErrorOf( ES_SUPP, 165, E_INFO, EV_NONE, 0 ), "%'--no-messages (-s)'%: specifies no line-too-long messages." } ; ErrorId MsgSupp::OptionFixedStrings = { ErrorOf( ES_SUPP, 166, E_INFO, EV_NONE, 0 ), "%'--fixed-strings (-F)'%: specifies a fixed string." } ; ErrorId MsgSupp::OptionBasicRegexp = { ErrorOf( ES_SUPP, 167, E_INFO, EV_NONE, 0 ), "%'--basic-regexp (-G)'%: specifies a basic regular expression." } ; ErrorId MsgSupp::OptionExtendedRegexp = { ErrorOf( ES_SUPP, 168, E_INFO, EV_NONE, 0 ), "%'--extended-regexp (-E)'%: specifies an extended regular expression." } ; ErrorId MsgSupp::OptionPerlRegexp = { ErrorOf( ES_SUPP, 169, E_INFO, EV_NONE, 0 ), "%'--perl-regexp (-P)'%: specifies a Perl regular expression" } ; ErrorId MsgSupp::OptionRegexp = { ErrorOf( ES_SUPP, 170, E_INFO, EV_NONE, 0 ), "%'--regexp (-e)'%: specifies the regular expression" } ; ErrorId MsgSupp::OptionAfterContext = { ErrorOf( ES_SUPP, 171, E_INFO, EV_NONE, 0 ), "%'--after-context (-A)'%: specifies the number of lines after the match." } ; ErrorId MsgSupp::OptionBeforeContext = { ErrorOf( ES_SUPP, 172, E_INFO, EV_NONE, 0 ), "%'--before-context (-B)'%: specifies the number of lines before the match." } ; ErrorId MsgSupp::OptionContext = { ErrorOf( ES_SUPP, 173, E_INFO, EV_NONE, 0 ), "%'--context (-C)'%: specifies the number of lines of context." } ; ErrorId MsgSupp::OptionIgnoreCase = { ErrorOf( ES_SUPP, 174, E_INFO, EV_NONE, 0 ), "%'--ignore-case (-i)'%: causes the pattern-matching to be case-insensitive." } ; ErrorId MsgSupp::OptionJournalPrefix = { ErrorOf( ES_SUPP, 176, E_INFO, EV_NONE, 0 ), "%'--journal-prefix (-J)'%: specifies the journal file name prefix." } ; ErrorId MsgSupp::OptionRepeat = { ErrorOf( ES_SUPP, 177, E_INFO, EV_NONE, 0 ), "%'--repeat (-i)'%: specifies the repeat interval in seconds." } ; ErrorId MsgSupp::OptionBackoff = { ErrorOf( ES_SUPP, 178, E_INFO, EV_NONE, 0 ), "%'--backoff (-b)'%: specifies the error backoff period in seconds." } ; ErrorId MsgSupp::OptionArchiveData = { ErrorOf( ES_SUPP, 179, E_INFO, EV_NONE, 0 ), "%'--archive-data (-u)'%: specifies to retrieve file content." } ; ErrorId MsgSupp::OptionStatus = { ErrorOf( ES_SUPP, 180, E_INFO, EV_NONE, 0 ), "%'--status (-l)'%: specifies that status information should be displayed" } ; ErrorId MsgSupp::OptionJournalPosition = { ErrorOf( ES_SUPP, 181, E_INFO, EV_NONE, 0 ), "%'--journal-position (-j)'%: specifies to display journal position status." } ; ErrorId MsgSupp::OptionPullServerid = { ErrorOf( ES_SUPP, 182, E_INFO, EV_NONE, 0 ), "%'--serverid (-P)'%: specifies to use filtering specifications of this server." } ; ErrorId MsgSupp::OptionExcludeTables = { ErrorOf( ES_SUPP, 183, E_INFO, EV_NONE, 0 ), "%'--exclude-tables (-T)'%: specifies tables to exclude." } ; ErrorId MsgSupp::OptionFile = { ErrorOf( ES_SUPP, 184, E_INFO, EV_NONE, 0 ), "%'--file (-f)'%: specifies the file." } ; ErrorId MsgSupp::OptionRevision = { ErrorOf( ES_SUPP, 185, E_INFO, EV_NONE, 0 ), "%'--revision (-r)'%: specifies the revision." } ; ErrorId MsgSupp::OptionNoRejournal = { ErrorOf( ES_SUPP, 186, E_INFO, EV_NONE, 0 ), "%'--no-rejournal'%: specifies that the pull command should not re-journal records which are replicated from the target server." } ; ErrorId MsgSupp::OptionAppend = { ErrorOf( ES_SUPP, 187, E_INFO, EV_NONE, 0 ), "%'--append (-a)'%: specifies that information is to be appended." } ; ErrorId MsgSupp::OptionSequence = { ErrorOf( ES_SUPP, 188, E_INFO, EV_NONE, 0 ), "%'--sequence (-c)'%: specifies the sequence value." } ; ErrorId MsgSupp::OptionCounter = { ErrorOf( ES_SUPP, 189, E_INFO, EV_NONE, 0 ), "%'--counter (-t)'%: specifies the counter name." } ; ErrorId MsgSupp::OptionHostName = { ErrorOf( ES_SUPP, 190, E_INFO, EV_NONE, 0 ), "%'--host (-h)'%: specifies the host name to use." } ; ErrorId MsgSupp::OptionPrint = { ErrorOf( ES_SUPP, 191, E_INFO, EV_NONE, 0 ), "%'--print (-p)'%: specifies that the result is to be displayed." } ; ErrorId MsgSupp::OptionStartPosition = { ErrorOf( ES_SUPP, 192, E_INFO, EV_NONE, 0 ), "%'--start (-s)'%: specifies the starting position." } ; ErrorId MsgSupp::OptionEncoded = { ErrorOf( ES_SUPP, 193, E_INFO, EV_NONE, 0 ), "%'--encoded (-e)'%: specifies that the value is to be encoded." } ; ErrorId MsgSupp::OptionLogName = { ErrorOf( ES_SUPP, 194, E_INFO, EV_NONE, 0 ), "%'--log (-l)'%: specifies the name of the log." } ; ErrorId MsgSupp::OptionLoginStatus = { ErrorOf( ES_SUPP, 195, E_INFO, EV_NONE, 0 ), "%'--status (-s)'%: displays the current status." } ; ErrorId MsgSupp::OptionCompressCkp = { ErrorOf( ES_SUPP, 196, E_INFO, EV_NONE, 0 ), "%'--compress-ckp (-Z)'%: compress the checkpoint, but not the journal." } ; ErrorId MsgSupp::OptionSpecType = { ErrorOf( ES_SUPP, 197, E_INFO, EV_NONE, 0 ), "%'--spec (-s)'%: specifies the type of spec to be processed." } ; ErrorId MsgSupp::OptionMaxAccess = { ErrorOf( ES_SUPP, 198, E_INFO, EV_NONE, 0 ), "%'--max-access (-m)'%: displays a single word summary of the maximum access level." } ; ErrorId MsgSupp::OptionGroupName = { ErrorOf( ES_SUPP, 199, E_INFO, EV_NONE, 0 ), "%'--group (-g)'%: specifies the group name." } ; ErrorId MsgSupp::OptionShowFiles = { ErrorOf( ES_SUPP, 200, E_INFO, EV_NONE, 0 ), "%'--show-files (-f)'%: specifies to display the individual files." } ; ErrorId MsgSupp::OptionName = { ErrorOf( ES_SUPP, 201, E_INFO, EV_NONE, 0 ), "%'--name (-n)'%: specifies the object name." } ; ErrorId MsgSupp::OptionValue = { ErrorOf( ES_SUPP, 202, E_INFO, EV_NONE, 0 ), "%'--value (-v)'%: specifies the object value." } ; ErrorId MsgSupp::OptionPropagating = { ErrorOf( ES_SUPP, 203, E_INFO, EV_NONE, 0 ), "%'--propagating (-p)'%: specifies the attribute is propagating." } ; ErrorId MsgSupp::OptionOpenAdd = { ErrorOf( ES_SUPP, 204, E_INFO, EV_NONE, 0 ), "%'--add (-a)'%: specifies files should be opened for add." } ; ErrorId MsgSupp::OptionOpenEdit = { ErrorOf( ES_SUPP, 205, E_INFO, EV_NONE, 0 ), "%'--edit (-e)'%: specifies files should be opened for edit." } ; ErrorId MsgSupp::OptionOpenDelete = { ErrorOf( ES_SUPP, 206, E_INFO, EV_NONE, 0 ), "%'--delete (-d)'%: specifies files should be opened for delete." } ; ErrorId MsgSupp::OptionUseModTime = { ErrorOf( ES_SUPP, 207, E_INFO, EV_NONE, 0 ), "%'--modtime (-m)'%: specifies the file modification time should be checked." } ; ErrorId MsgSupp::OptionLocal = { ErrorOf( ES_SUPP, 208, E_INFO, EV_NONE, 0 ), "%'--local (-l)'%: specifies local syntax for filenames." } ; ErrorId MsgSupp::OptionOutputBase = { ErrorOf( ES_SUPP, 209, E_INFO, EV_NONE, 0 ), "%'--output-base (-o)'%: specifies to display the revision used as the base." } ; ErrorId MsgSupp::OptionSystem = { ErrorOf( ES_SUPP, 210, E_INFO, EV_NONE, 0 ), "%'--system (-s)'%: specifies the value should apply to all users on the system." } ; ErrorId MsgSupp::OptionService = { ErrorOf( ES_SUPP, 211, E_INFO, EV_NONE, 0 ), "%'--service (-S)'%: specifies the value applies to the named service." } ; ErrorId MsgSupp::OptionHistogram = { ErrorOf( ES_SUPP, 212, E_INFO, EV_NONE, 0 ), "%'--histogram (-h)'%: specifies to display a histogram." } ; ErrorId MsgSupp::OptionTableNotUnlocked = { ErrorOf( ES_SUPP, 213, E_INFO, EV_NONE, 0 ), "%'--table-not-unlocked (-U)'%: runs only the table-not-unlocked check." } ; ErrorId MsgSupp::OptionTableName = { ErrorOf( ES_SUPP, 214, E_INFO, EV_NONE, 0 ), "%'--table (-t)'%: specifies the table." } ; ErrorId MsgSupp::OptionAllClients = { ErrorOf( ES_SUPP, 215, E_INFO, EV_NONE, 0 ), "%'--all-clients (-C)'%: specifies to process all client workspaces." } ; ErrorId MsgSupp::OptionCheckSize = { ErrorOf( ES_SUPP, 216, E_INFO, EV_NONE, 0 ), "%'--size (-s)'%: specifies that file size should be checked." } ; ErrorId MsgSupp::OptionTransfer = { ErrorOf( ES_SUPP, 217, E_INFO, EV_NONE, 0 ), "%'--transfer (-t)'%: specifies damaged or missing files should be retransferred." } ; ErrorId MsgSupp::OptionUpdate = { ErrorOf( ES_SUPP, 218, E_INFO, EV_NONE, 0 ), "%'--update (-u)'%: specifies to process only files that have no saved digest." } ; ErrorId MsgSupp::OptionVerify = { ErrorOf( ES_SUPP, 219, E_INFO, EV_NONE, 0 ), "%'--verify (-v)'%: specifies to recompute digests for all files." } ; ErrorId MsgSupp::OptionNoArchive = { ErrorOf( ES_SUPP, 220, E_INFO, EV_NONE, 0 ), "%'--no-archive (-X)'%: specifies to skip files with the +X filetype." } ; ErrorId MsgSupp::OptionServerid = { ErrorOf( ES_SUPP, 221, E_INFO, EV_NONE, 0 ), "%'--serverid (-s)'%: specifies the serverid." } ; ErrorId MsgSupp::OptionUnified = { ErrorOf( ES_SUPP, 222, E_INFO, EV_NONE, 0 ), "%'--unified (-u)'%: specifies to display the diff in unified format." } ; ErrorId MsgSupp::OptionPreviewNC = { ErrorOf( ES_SUPP, 223, E_INFO, EV_NONE, 0 ), "%'--preview-noncontent (-N)'%: previews the operation, including non-content." } ; ErrorId MsgSupp::OptionEstimates = { ErrorOf( ES_SUPP, 224, E_INFO, EV_NONE, 0 ), "%'--estimates (-N)'%: specifies to display estimates about the work required." } ; ErrorId MsgSupp::OptionLocked = { ErrorOf( ES_SUPP, 225, E_INFO, EV_NONE, 0 ), "%'--locked (-L)'%: specifies that locked objects are to be included." } ; ErrorId MsgSupp::OptionUnloadAll = { ErrorOf( ES_SUPP, 226, E_INFO, EV_NONE, 0 ), "%'--unload-all (-a)'%: specifies that multiple objects are to be unloaded." } ; ErrorId MsgSupp::OptionKeepHave = { ErrorOf( ES_SUPP, 227, E_INFO, EV_NONE, 0 ), "%'--keep-have (-h)'%: specifies to leave target files at the currently synced revision." } ; ErrorId MsgSupp::OptionYes = { ErrorOf( ES_SUPP, 228, E_INFO, EV_NONE, 0 ), "%'--yes (-y)'%: causes prompts to be automatically accepted." } ; ErrorId MsgSupp::OptionNo = { ErrorOf( ES_SUPP, 229, E_INFO, EV_NONE, 0 ), "%'--no (-n)'%: causes prompts to be automatically refused." } ; ErrorId MsgSupp::OptionInputValue = { ErrorOf( ES_SUPP, 230, E_INFO, EV_NONE, 0 ), "%'--value (-i)'%: specifies the value." } ; ErrorId MsgSupp::OptionReplacement = { ErrorOf( ES_SUPP, 231, E_INFO, EV_NONE, 0 ), "%'--replacement (-r)'%: specifies that a replacement is affected." } ; ErrorId MsgSupp::OptionFrom = { ErrorOf( ES_SUPP, 232, E_INFO, EV_NONE, 0 ), "%'--from'%: specifies the old value." } ; ErrorId MsgSupp::OptionTo = { ErrorOf( ES_SUPP, 233, E_INFO, EV_NONE, 0 ), "%'--to'%: specifies the new value." } ; ErrorId MsgSupp::OptionRebuild = { ErrorOf( ES_SUPP, 234, E_INFO, EV_NONE, 0 ), "%'--rebuild (-R)'%: rebuild the database." } ; ErrorId MsgSupp::OptionEqual = { ErrorOf( ES_SUPP, 235, E_INFO, EV_NONE, 0 ), "%'--equal (-e)'%: specifies the exact changelist." } ; ErrorId MsgSupp::OptionAttrPattern = { ErrorOf( ES_SUPP, 236, E_INFO, EV_NONE, 0 ), "%'--attribute-pattern (-A)'%: displays only attributes that match the pattern." } ; ErrorId MsgSupp::OptionDiffListFlag = { ErrorOf( ES_SUPP, 237, E_INFO, EV_NONE, 0 ), "%'--diff-list-flag (-s)'%: lists files that satisfy the flag value." } ; ErrorId MsgSupp::OptionArguments = { ErrorOf( ES_SUPP, 238, E_INFO, EV_NONE, 0 ), "%'--arguments (-a)'%: displays the arguments." } ; ErrorId MsgSupp::OptionEnvironment = { ErrorOf( ES_SUPP, 239, E_INFO, EV_NONE, 0 ), "%'--environment (-e)'%: displays the environment." } ; ErrorId MsgSupp::OptionTaskStatus = { ErrorOf( ES_SUPP, 240, E_INFO, EV_NONE, 0 ), "%'--status (-s)'%: displays only commands that match the status." } ; ErrorId MsgSupp::OptionAllUsers = { ErrorOf( ES_SUPP, 241, E_INFO, EV_NONE, 0 ), "%'--all-users (-A)'%: specifies the command applies to all users." } ; ErrorId MsgSupp::OptionParallel = { ErrorOf( ES_SUPP, 242, E_INFO, EV_NONE, 0 ), "%'--parallel=threads=N,batch=N,batchsize=N,min=N,minsize=N'%: specify file transfer parallelism." } ; ErrorId MsgSupp::OptionParallelSubmit = { ErrorOf( ES_SUPP, 35, E_INFO, EV_NONE, 0 ), "%'--parallel=threads=N,batch=N,min=N'%: specify file transfer parallelism." } ; ErrorId MsgSupp::OptionPromote = { ErrorOf( ES_SUPP, 243, E_INFO, EV_NONE, 0 ), "%'--promote (-p)'%: specifies to promote the shelf to the Commit Server." } ; ErrorId MsgSupp::OptionInputFile = { ErrorOf( ES_SUPP, 245, E_INFO, EV_NONE, 0 ), "%'--input-file'%: specifies the name of the input file." } ; ErrorId MsgSupp::OptionPidFile = { ErrorOf( ES_SUPP, 246, E_INFO, EV_NONE, 0 ), "%'--pid-file'%: specifies the name of the PID file." } ; ErrorId MsgSupp::OptionLocalJournal = { ErrorOf( ES_SUPP, 247, E_INFO, EV_NONE, 0 ), "%'--local-journal'%: specifies that the pull command should read journal records from a local journal file rather than from the target server." } ; ErrorId MsgSupp::OptionTest = { ErrorOf( ES_SUPP, 248, E_INFO, EV_NONE, 0 ), "%'--test (-t)'%: specifies a user to test against the LDAP configuration." } ; ErrorId MsgSupp::OptionActive = { ErrorOf( ES_SUPP, 249, E_INFO, EV_NONE, 0 ), "%'--active (-A)'%: only list the active LDAP configurations." } ; ErrorId MsgSupp::OptionNoRetransfer = { ErrorOf( ES_SUPP, 250, E_INFO, EV_NONE, 0 ), "%'--noretransfer'%: override submit.noretransfer configurable behavior." } ; ErrorId MsgSupp::OptionForceNoRetransfer = { ErrorOf( ES_SUPP, 251, E_INFO, EV_NONE, 0 ), "%'--forcenoretransfer'%: skip file transfer if archive files are found (undoc and not recommended)." } ; ErrorId MsgSupp::OptionDurableOnly = { ErrorOf( ES_SUPP, 252, E_INFO, EV_NONE, 0 ), "%'--durable-only'%: deliver only durable journal records." } ; ErrorId MsgSupp::OptionNonAcknowledging = { ErrorOf( ES_SUPP, 253, E_INFO, EV_NONE, 0 ), "%'--non-acknowledging'%: this request does not acknowledge previous journal records." } ; ErrorId MsgSupp::OptionReplicationStatus = { ErrorOf( ES_SUPP, 254, E_INFO, EV_NONE, 0 ), "%'--replication-status (-J)'%: show the replication status of the server and of its replicas." } ; ErrorId MsgSupp::OptionGroupMode = { ErrorOf( ES_SUPP, 255, E_INFO, EV_NONE, 0 ), "%'--groups (-g)'%: updates Perforce group users with LDAP group members." } ; ErrorId MsgSupp::OptionUserMode = { ErrorOf( ES_SUPP, 285, E_INFO, EV_NONE, 0 ), "%'--users (-u)'%: updates Perforce users from LDAP user." } ; ErrorId MsgSupp::OptionUserModeCreate = { ErrorOf( ES_SUPP, 286, E_INFO, EV_NONE, 0 ), "%'--create (-c)'%: creates new users found in LDAP." } ; ErrorId MsgSupp::OptionUserModeUpdate = { ErrorOf( ES_SUPP, 287, E_INFO, EV_NONE, 0 ), "%'--update (-U)'%: updates existing users found in LDAP." } ; ErrorId MsgSupp::OptionUserModeDelete = { ErrorOf( ES_SUPP, 288, E_INFO, EV_NONE, 0 ), "%'--delete (-d)'%: deletes users not found in LDAP." } ; ErrorId MsgSupp::OptionBypassExlusiveLock = { ErrorOf( ES_SUPP, 256, E_INFO, EV_NONE, 0 ), "%'--bypass-exclusive-lock'%: allow command on (+l) filetype even if already exclusively opened." } ; ErrorId MsgSupp::OptionRetainLbrRevisions = { ErrorOf( ES_SUPP, 261, E_INFO, EV_NONE, 0 ), "%'--retain-lbr-revisions'%: don't rename library archive files with the renamed changelist number." } ; ErrorId MsgSupp::OptionCreate = { ErrorOf( ES_SUPP, 257, E_INFO, EV_NONE, 0 ), "%'--create (-c)'%: Create a new stream and populate it with files from the current stream. (dvcs only)" } ; ErrorId MsgSupp::OptionList = { ErrorOf( ES_SUPP, 258, E_INFO, EV_NONE, 0 ), "%'--list (-l)'%: list all the streams available to your client." } ; ErrorId MsgSupp::OptionMainline = { ErrorOf( ES_SUPP, 259, E_INFO, EV_NONE, 0 ), "%'--mainline (-m)'%: Create this stream as an empty mainline (no parent)." } ; ErrorId MsgSupp::OptionMoveChanges = { ErrorOf( ES_SUPP, 260, E_INFO, EV_NONE, 0 ), "%'--movechanges (-r)'%: Move open files to the stream you are switching to, instead of shelving and reverting them." } ; ErrorId MsgSupp::OptionJavaProtocol = { ErrorOf( ES_SUPP, 262, E_INFO, EV_NONE, 0 ), "%'--java'%: enable Java support via the rsh protocol." } ; ErrorId MsgSupp::OptionPullBatch = { ErrorOf( ES_SUPP, 263, E_INFO, EV_NONE, 0 ), "%'--batch'%: pull N archives in a single request to master." } ; ErrorId MsgSupp::OptionDepotType = { ErrorOf( ES_SUPP, 265, E_INFO, EV_NONE, 0 ), "%'--depot-type (-t)'%: specifies the type of depot" } ; ErrorId MsgSupp::OptionClientType = { ErrorOf( ES_SUPP, 280, E_INFO, EV_NONE, 0 ), "%'--client-type'%: specifies the type of client." } ; ErrorId MsgSupp::OptionGlobalLock = { ErrorOf( ES_SUPP, 266, E_INFO, EV_NONE, 0 ), "%'--global (-g)'%: reports or changes global locks from Edge Server" } ; ErrorId MsgSupp::OptionEnableDVCSTriggers = { ErrorOf( ES_SUPP, 267, E_INFO, EV_NONE, 0 ), "%'--enable-dvcs-triggers'%: fires any push-* triggers for changelists imported by this unzip command." } ; ErrorId MsgSupp::OptionUsers = { ErrorOf( ES_SUPP, 269, E_INFO, EV_NONE, 0 ), "%'--users (-u)'%: show the user who modifed the line." } ; ErrorId MsgSupp::OptionConvertAdminComments = { ErrorOf( ES_SUPP, 270, E_INFO, EV_NONE, 0 ), "%'--convert-p4admin-comments'%: When used with -o option converts P4Admin style comments into new ## native spec comments." } ; ErrorId MsgSupp::OptionRemoteSpec = { ErrorOf( ES_SUPP, 271, E_INFO, EV_NONE, 0 ), "%'--remote'%: Specifies the remote spec to be used." } ; ErrorId MsgSupp::OptionP4UserUser = { ErrorOf( ES_SUPP, 272, E_INFO, EV_NONE, 0 ), "%'--me'%: Shorthand for -u $P4USER" } ; ErrorId MsgSupp::OptionAliases = { ErrorOf( ES_SUPP, 273, E_INFO, EV_NONE, 0 ), "%'--aliases'%: specifies alias-handling behavior." } ; ErrorId MsgSupp::OptionField = { ErrorOf( ES_SUPP, 274, E_INFO, EV_NONE, 0 ), "%'--field'%: Modify spec fields from the command line." } ; ErrorId MsgSupp::OptionTab = { ErrorOf( ES_SUPP, 275, E_INFO, EV_NONE, 0 ), "%'--tab[=N] (-T)'%: Align output to tab stops." } ; ErrorId MsgSupp::OptionForceDelete = { ErrorOf( ES_SUPP, 277, E_INFO, EV_NONE, 0 ), "%'--force-delete'%: delete entity from protects and groups." } ; ErrorId MsgSupp::OptionStorageType = { ErrorOf( ES_SUPP, 278, E_INFO, EV_NONE, 0 ), "%'--type'% (-T): specifies the type of client (writeable/readonly/graph)." } ; ErrorId MsgSupp::OptionAtomicPush = { ErrorOf( ES_SUPP, 279, E_INFO, EV_NONE, 0 ), "%'--atomic'%: specifies that all references must pass their checks in order for any reference updates to occur." } ; ErrorId MsgSupp::OptionColor = { ErrorOf( ES_SUPP, 281, E_INFO, EV_NONE, 0 ), "%'--color'%: Force color output on the command line." } ; ErrorId MsgSupp::OptionChangeFiles = { ErrorOf( ES_SUPP, 282, E_INFO, EV_NONE, 0 ), "%'--show-files'%: specifies to display the individual files." } ; ErrorId MsgSupp::OptionDiscardArchives = { ErrorOf( ES_SUPP, 283, E_INFO, EV_NONE, 0 ), "%'--discard-archives=N'%: specifies to discard any packfiles received more than N days ago. Specifying N=0 discards all packfiles except the one(s) just received by this command." } ; ErrorId MsgSupp::OptionLicenseInfo = { ErrorOf( ES_SUPP, 284, E_INFO, EV_NONE, 0 ), "%'--license-info'%: report license status information." } ; ErrorId MsgSupp::OptionRename = { ErrorOf( ES_SUPP, 290, E_INFO, EV_NONE, 0 ), "%'--rename (-r)'%: rename existing files without changing content." } ; ErrorId MsgSupp::TooManyLockTrys = { ErrorOf( ES_SUPP, 268, E_FATAL, EV_FAULT, 1 ), "Too many trys to get lock %file%." } ; ErrorId MsgSupp::OptionRemoteUser = { ErrorOf( ES_SUPP, 289, E_INFO, EV_NONE, 0 ), "%'--remote-user=name'%: specifies the name of the remote user to connect as. This option, if specificed, overrides the RemoteUser: field, if present, in the remote spec." } ; ErrorId MsgSupp::OptionIgnoreCMap = { ErrorOf( ES_SUPP, 291, E_INFO, EV_NONE, 0 ), "%'--ignore-changeview'%: Ignore the limits imposed by the changview." } ; ErrorId MsgSupp::OptionMirror = { ErrorOf( ES_SUPP, 292, E_INFO, EV_NONE, 0 ), "%'--mirror'%: specifies that this update is for a mirrored repo." } ; ErrorId MsgSupp::OptionDaemonSafe = { ErrorOf( ES_SUPP, 293, E_INFO, EV_NONE, 0 ), "%'--daemonsafe'%: Start server as daemon with stdio closed." } ; ErrorId MsgSupp::OptionTrigger = { ErrorOf( ES_SUPP, 294, E_INFO, EV_NONE, 0 ), "%'--trigger'%: Pull archive content using an external trigger." } ; ErrorId MsgSupp::OptionIgnoreHave = { ErrorOf( ES_SUPP, 295, E_INFO, EV_NONE, 0 ), "%'--ignore-have'%: specifies that the publish option (-p) ignore any have records." } ; ErrorId MsgSupp::OptionGraphOnly = { ErrorOf( ES_SUPP, 296, E_INFO, EV_NONE, 0 ), "%'--graph-only'%: skip any non-graph results." } ; ErrorId MsgSupp::OptionMinSize = { ErrorOf( ES_SUPP, 297, E_INFO, EV_NONE, 0 ), "%'--min-size'%: Pull archive trigger min file size." } ; ErrorId MsgSupp::OptionMaxSize = { ErrorOf( ES_SUPP, 298, E_INFO, EV_NONE, 0 ), "%'--max-size'%: Pull archive trigger max file size." } ; ErrorId MsgSupp::OptionNameOnly = { ErrorOf( ES_SUPP, 299, E_INFO, EV_NONE, 0 ), "%'--name-only'%: List only filenames." } ; ErrorId MsgSupp::OptionNoFastForward = { ErrorOf( ES_SUPP, 300, E_INFO, EV_NONE, 0 ), "%'--no-ff'%: Create a merge commit even when the merge resolves as a fast-forward." } ; ErrorId MsgSupp::OptionFastForwardOnly = { ErrorOf( ES_SUPP, 301, E_INFO, EV_NONE, 0 ), "%'--ff-only'%: Refuse to merge unless the current HEAD is already up-to-date or merge can be resolved as a fast-forward." } ; ErrorId MsgSupp::OptionMustExist = { ErrorOf( ES_SUPP, 302, E_INFO, EV_NONE, 0 ), "%'--exists'%: Only output spec if it exists." } ; ErrorId MsgSupp::OptionRepoName = { ErrorOf( ES_SUPP, 303, E_INFO, EV_NONE, 0 ), "%'--repo'%: specifies the repo for a non-interactive merge." } ; ErrorId MsgSupp::OptionTargetBranch = { ErrorOf( ES_SUPP, 304, E_INFO, EV_NONE, 0 ), "%'--target'%: specifies the target branch for a non-interactive merge." } ; ErrorId MsgSupp::OptionByUser = { ErrorOf( ES_SUPP, 305, E_INFO, EV_NONE, 0 ), "%'--user (-u)'%: limit output to repos readable by specified user or group." } ; ErrorId MsgSupp::OptionByOwner = { ErrorOf( ES_SUPP, 306, E_INFO, EV_NONE, 0 ), "%'--owner (-O)'%: limit output to repos owned by specified user or group." } ; ErrorId MsgSupp::OptionSquash = { ErrorOf( ES_SUPP, 307, E_INFO, EV_NONE, 0 ), "%'--squash'%: Create a single commit on top of the specified branch, with content from the merge." } ; ErrorId MsgSupp::OptionAllowEmpty = { ErrorOf( ES_SUPP, 308, E_INFO, EV_NONE, 0 ), "%'--allow-empty'%: allows submitting empty repo commit." } ; ErrorId MsgSupp::OptionAdded = { ErrorOf( ES_SUPP, 309, E_INFO, EV_NONE, 0 ), "%'--added (-a)'%: display content of added files." } ; ErrorId MsgSupp::OptionCreateIndex = { ErrorOf( ES_SUPP, 310, E_INFO, EV_NONE, 0 ), "%'--create-index'%: create repo index for direct file history access." } ; ErrorId MsgSupp::OptionDropIndex = { ErrorOf( ES_SUPP, 311, E_INFO, EV_NONE, 0 ), "%'--drop-index'%: drop repo index." } ; ErrorId MsgSupp::JsmnBadType = { ErrorOf( ES_SUPP, 312, E_FAILED, EV_CONFIG, 3 ), "JSON error: token not expected type. Token number %index% Expected type %expected% Observed type %observed%." } ; ErrorId MsgSupp::JsmnBadParent = { ErrorOf( ES_SUPP, 313, E_FAILED, EV_CONFIG, 3 ), "JSON error: token does not have the expected parent. Token number %index% Expected parent index %expected% Observed parent index %observed%." } ; ErrorId MsgSupp::JsmnBadMem = { ErrorOf( ES_SUPP, 314, E_FAILED, EV_CONFIG, 1 ), "JSON error: parse failed, input has too many tokens. Limit is %limit%." } ; ErrorId MsgSupp::JsmnBadSyn = { ErrorOf( ES_SUPP, 315, E_FAILED, EV_CONFIG, 0 ), "JSON error: parse failed, bad syntax." } ; ErrorId MsgSupp::JsmnTooFew = { ErrorOf( ES_SUPP, 316, E_FAILED, EV_CONFIG, 0 ), "JSON error: parse failed, missing tokens." } ; ErrorId MsgSupp::JsmnKeyNotFound = { ErrorOf( ES_SUPP, 317, E_FAILED, EV_CONFIG, 2 ), "JSON error: not found key name \"%tname%\" in token at index %index%." } ; ErrorId MsgSupp::OptionRetry = { ErrorOf( ES_SUPP, 318, E_INFO, EV_NONE, 0 ), "%'--retry (-R)'%: retry transfer of files that failed to transfer." } ; // ErrorId graveyard'%: retired/deprecated ErrorIds. ErrorId MsgSupp::ZCLoadLibFailed = { ErrorOf( ES_SUPP, 24, E_WARN, EV_ADMIN, 0 ), "Perforce failed to load zeroconf dynamic libraries." } ; // DEPRECATED ZeroConf NOTRANS ErrorId MsgSupp::ZCInvalidName = { ErrorOf( ES_SUPP, 25, E_FAILED, EV_USAGE, 1 ), "Invalid name '%name%'." } ; // DEPRECATED ZeroConf NOTRANS ErrorId MsgSupp::ZCRequireName = { ErrorOf( ES_SUPP, 26, E_FAILED, EV_USAGE, 0 ), "Perforce requires IDname '-In' to register with zeroconf." } ; // DEPRECATED ZeroConf NOTRANS ErrorId MsgSupp::ZCNameConflict = { ErrorOf( ES_SUPP, 27, E_FATAL, EV_ADMIN, 3 ), "*** WARNING duplicate of '%name%' at '%host%:%port%' ***" } ; // DEPRECATED ZeroConf NOTRANS ErrorId MsgSupp::ZCRegistryFailed = { ErrorOf( ES_SUPP, 28, E_WARN, EV_ADMIN, 1 ), "Perforce could not register with zeroconf: error is %err%" } ; // DEPRECATED ZeroConf NOTRANS ErrorId MsgSupp::ZCBrowseFailed = { ErrorOf( ES_SUPP, 29, E_WARN, EV_ADMIN, 2 ), "Perforce could not browse zeroconf/%implementation%: error is %err%" } ; // DEPRECATED ZeroConf NOTRANS ErrorId MsgSupp::OptionShowFlags = { ErrorOf( ES_SUPP, 147, E_INFO, EV_NONE, 0 ), "%'--show-flags (-s)'%: lists the files that satisfy the condition." } ; // NEVER USED NOTRANS
[ "nickpoole@black-sphere.co.uk" ]
nickpoole@black-sphere.co.uk
d407732f954ff2f56ee6f39ee125c8b0a95a80f9
60a15a584b00895e47628c5a485bd1f14cfeebbe
/comps/misc/input/NewDoc/VT5Profile.h
f4a1f3f2fcea7c4b165b6d88673da5fcccade76d
[]
no_license
fcccode/vt5
ce4c1d8fe819715f2580586c8113cfedf2ab44ac
c88049949ebb999304f0fc7648f3d03f6501c65b
refs/heads/master
2020-09-27T22:56:55.348501
2019-06-17T20:39:46
2019-06-17T20:39:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,857
h
#if !defined(__VT5Profile_H__) #define __VT5Profile_H__ #include "StdProfile.h" class CVT5ProfileManager : public CStdProfileManager { CString m_sDriverName; public: bool IsVT5Profile(); CVT5ProfileManager(LPCTSTR lpDrvName = NULL, bool bSingleProfile = true); // Additional functions : get or set values in unknown format virtual VARIANT _GetProfileValue(LPCTSTR lpSection, LPCTSTR lpEntry, bool bIgnoreMethodic = false); virtual VARIANT GetProfileValue(LPCTSTR lpSection, LPCTSTR lpEntry, bool bIgnoreMethodic = false); virtual VARIANT GetDefaultProfileValue(LPCTSTR lpSection, LPCTSTR lpEntry); virtual void WriteProfileValue(LPCTSTR lpSection, LPCTSTR lpEntry, VARIANT varValue, bool bIgnoreMethodic = false); // Overwriten methods: works with VT5 ini file virtual int _GetProfileInt(LPCTSTR lpSection, LPCTSTR lpEntry, int nDef, bool bIgnoreMethodic = false); virtual double _GetProfileDouble(LPCTSTR lpSection, LPCTSTR lpEntry, double dDef, bool *pbDefValueUsed = NULL, bool bIgnoreMethodic = false); virtual CString _GetProfileString(LPCTSTR lpSection, LPCTSTR lpEntry, LPCTSTR lpDefault, bool bIgnoreMethodic = false); virtual void WriteProfileInt(LPCTSTR lpSection, LPCTSTR lpEntry, int nValue, bool bIgnoreMethodic = false); virtual void WriteProfileDouble(LPCTSTR lpSection, LPCTSTR lpEntry, double dValue, bool bIgnoreMethodic = false); virtual void WriteProfileString(LPCTSTR lpSection, LPCTSTR lpEntry, LPCTSTR lpValue, bool bIgnoreMethodic = false); virtual void InitSettings(); virtual void ResetSettings(); virtual int GetDefaultProfileInt(LPCTSTR lpSection, LPCTSTR lpEntry, int nDef); virtual double GetDefaultProfileDouble(LPCTSTR lpSection, LPCTSTR lpEntry, double nDef, bool *pbDefValueUsed = NULL); virtual CString GetDefaultProfileString(LPCTSTR lpSection, LPCTSTR lpEntry, LPCTSTR lpDefault); }; #endif
[ "videotestc@gmail.com" ]
videotestc@gmail.com
8173960cc631dc498868bc642f219805f1cf11e5
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/align/aligned_allocator.hpp
cdee5daee35e3a64a557d51fa3a40b814da96b33
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
129
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:9bb6cd103d0a924e8ad77bcdb9b730e25e842f55edebe4ab58c9eb2cb5abada9 size 3971
[ "YLiLarry@gmail.com" ]
YLiLarry@gmail.com
6e9d36de54420deee282e4494f1160837bb09b64
7e72687dc9a00d63aeacdff3dafcc2dc55349083
/gamecontroller/GameController2006/sample/GameController/sound/WAV.cc
2818162d42c2472b9888d37029cae3037c15e7fd
[]
no_license
burst/burst
1b38082d68bf06e836fc4c5ae5015956c1646942
495a86712a37a145b61a3c5bfdeafe6d0c1e9e61
refs/heads/master
2020-05-17T19:04:49.538528
2010-05-20T20:13:03
2010-05-20T20:13:03
245,141
3
0
null
null
null
null
UTF-8
C++
false
false
8,210
cc
// // Modified from the Sony SoundPlay demo program. // // This Object is used to store the data of a tone or wav file in memory ready to play. // // // Most of this was written by Robin. // //#include <OPENR/OPENR.h> #include <OPENR/OPENRAPI.h> #include <OPENR/OSyslog.h> #include "WAV.h" #include <math.h> WAV::WAV() : soundInfo(), dataStart(0), dataEnd(0), dataCurrent(0) { ThisWavIs = Wav_Failed; } WAV::WAV(byte* addr) : dataStart(0), dataEnd(0), dataCurrent(0) { Set(addr); } WAV::~WAV(){ if (ThisWavIs == Wav_Failed){ return; }else if (ThisWavIs == WAV_File){ OPENR::DeleteDesignData(wavID); }else { delete [] dataStart; } } WAVError WAV::Make(int Mlength, int MFreq){ // Fake the WAV details... soundUnitSize = MONO16K16B_UNIT_SIZE; soundInfo.format = osoundformatPCM; soundInfo.channel = osoundchannelMONO; soundInfo.samplingRate = 16000; soundInfo.bitsPerSample = 16; // 32 samples about one ms.. soundInfo.dataSize = Mlength * 32; //Allocate the amount of memory needed for the wav.. dataCurrent = dataStart = new byte[soundInfo.dataSize]; dataEnd = dataStart + soundInfo.dataSize; //Remember what kind of a wave this is so we will destroy fake ones, and not have them being a memory leak. ThisWavIs = WAV_Tone; //Now fill the memory with the required SIN wave. if (MFreq < 300 || MFreq > 8000) MFreq = 2000; //Cal the number of samples needed.. int Samples = (int) 16000/MFreq; //Work out what that relates to for a full sign wav. double Increments = PI2/Samples; //Because each sample is two bytes, we need double the values. Samples *= 2; int Value; //Now fill the memory array.. for (unsigned int i=0; i < soundInfo.dataSize; i++){ Value = (int) ((sin(( ((int)(i/2)) % Samples )*Increments)*26214)+ 32767); //Wav files are little endin, so swap the bytes around... *(dataStart + i) = (byte) Value; *(dataStart + ++i) = (byte) (Value>>8); } return WAV_SUCCESS; } WAVError WAV::LoadWav(char *FileName) { byte* addr; size_t size; //Load the wav file by the name givin in the DesignDB OStatus result = OPENR::FindDesignData(FileName, &wavID, &addr, &size); if (result != oSUCCESS) { OSYSLOG1((osyslogERROR, "%s : %s %d [%s]", "Wav::LoadWAV()", "OPENR::FindDesignData() FAILED", result, FileName)); return WAV_FAIL; } ThisWavIs = WAV_File; return Set(addr); } WAVError WAV::Set(byte *addr) { // // Check Wav Header // if (strncmp((char *)addr, "RIFF", 4)) return WAV_NOT_RIFF; addr += 4; longword length = get_longword(addr); addr += sizeof(longword); OSYSDEBUG(( "length = %x\n", length)); if (strncmp((char *)addr, "WAVE", 4)) return WAV_NOT_WAV; length -= 4; addr += 4; // // Check Chunk // while (length > 8) { size_t chunksize; char *buf = (char *)addr; addr += 4; chunksize = get_longword(addr); addr += sizeof(longword); length -= chunksize + 8; if (!strncmp(buf, "fmt ", 4)) { // // Format Chunk // // // Check WAV Type // soundInfo.format = (OSoundFormat)get_word(addr); addr += sizeof(word); if (soundInfo.format != osoundformatPCM) { OSYSDEBUG(("WAV_FORMAT_NOT_SUPPORTED\n")); return WAV_FORMAT_NOT_SUPPORTED; } // // Channel // soundInfo.channel = (OSoundChannel)get_word(addr); addr += sizeof(word); if (soundInfo.channel != osoundchannelMONO) { OSYSDEBUG(("WAV_CHANNEL_NOT_SUPPORTED\n")); return WAV_CHANNEL_NOT_SUPPORTED; } // // Sampling Rate // longword frq = get_longword(addr); addr += sizeof(longword); soundInfo.samplingRate = (word)frq; if (soundInfo.samplingRate != 16000) { OSYSDEBUG(("WAV_SAMPLINGRATE_NOT_SUPPORTED\n")); return WAV_SAMPLINGRATE_NOT_SUPPORTED; } // // DataSize Per sec // addr += sizeof(longword); // // Block Size // addr += sizeof(word); // // Bits Of Sample // soundInfo.bitsPerSample = get_word(addr); addr += sizeof(word); soundInfo.bitsPerSample *= soundInfo.channel; if (soundInfo.bitsPerSample != 16) { OSYSDEBUG(("WAV_BITSPERSAMPLE_NOT_SUPPORTED\n")); return WAV_BITSPERSAMPLE_NOT_SUPPORTED; } // // Skip Extentded Infomation // addr += chunksize - FMTSIZE_WITHOUT_EXTINFO; OSYSDEBUG(( "fmt chunksize = %d\n", chunksize)); OSYSDEBUG(( "samplingRate = %d\n", soundInfo.samplingRate)); OSYSDEBUG(( "bitsPerSample = %d\n", soundInfo.bitsPerSample)); } else if (!strncmp(buf, "data", 4)) { // // Data Chunk // OSYSDEBUG(( "data chunksize = %d\n", chunksize)); soundInfo.dataSize = chunksize; dataStart = dataCurrent = addr; dataEnd = dataStart + soundInfo.dataSize; break; } else { // // Fact Chunk // addr += chunksize; } } int rate = soundInfo.samplingRate; int bits = soundInfo.bitsPerSample; if (rate == 16000 & bits == 16) { soundUnitSize = MONO16K16B_UNIT_SIZE; } return WAV_SUCCESS; } WAVError WAV::CopyTo(OSoundVectorData* data) { //If we've reached the end of the wav, don't try and copy any more.. if (dataCurrent >= dataEnd) return WAV_FAIL; //Get the details of the wav and make sure they are what the speaker is expecting.. OSoundInfo* sinfo = data->GetInfo(0); if (soundUnitSize > sinfo->maxDataSize) { OSYSDEBUG(("WAV_SIZE_NOT_ENOUGH ")); return WAV_SIZE_NOT_ENOUGH; } sinfo->dataSize = soundUnitSize; sinfo->format = soundInfo.format; sinfo->channel = soundInfo.channel; sinfo->samplingRate = soundInfo.samplingRate; sinfo->bitsPerSample = soundInfo.bitsPerSample; //dest is the shared mem that the speaker will play. //src is the non shared memory section where the wav is. byte* src = dataCurrent; byte* dest = data->GetData(0); byte* end; //See how much of the wav is left to play. //note: result must be +ve as we check !(dataCurrent >= dataEnd) above unsigned int num = (unsigned int)(dataEnd - dataCurrent); //If there's more then a standard soundunitsize (normally 1024 bytes..) // copy only as much as is the standard soundunitsize. if (soundUnitSize <= num) { end = dest + soundUnitSize; while (dest < end) { *dest++ = *src++; } dataCurrent += soundUnitSize; } else { //Otherwise copy was much of the wav is left. end = dest + num; while (dest < end) { *dest++ = *src++; } //Let the speaker know there isn't a full block of data memset(dest, 0x0, soundUnitSize - num); dataCurrent = dataEnd; } return WAV_SUCCESS; } WAVError WAV::Rewind() { dataCurrent = dataStart; return WAV_SUCCESS; } longword WAV::get_longword(byte* ptr) { longword lw0 = (longword)ptr[0]; longword lw1 = (longword)ptr[1] << 8; longword lw2 = (longword)ptr[2] << 16; longword lw3 = (longword)ptr[3] << 24; return lw0 + lw1 + lw2 + lw3; } word WAV::get_word(byte* ptr) { word w0 = (word)ptr[0]; word w1 = (word)ptr[1] << 8; return w0 + w1; }
[ "alonlevy1@gmail.com" ]
alonlevy1@gmail.com
917a842bc98f34e16874a1ddd8ab91a53a439d08
e96669666c4f5b1f098bc52f71a4bc58b8d7d4bc
/XGine/Vegetation.cpp
81b98bd063f68b92de1084da91942a5e6295046e
[]
no_license
adasm/xgine
e924073e0d7fbc61c2e0bfea6118613c1db2e7bc
1cbcf13cc4af67d8c3b2894cbd300859febc2080
refs/heads/master
2020-05-20T17:01:41.293287
2015-04-18T11:31:39
2015-04-18T11:31:39
34,119,980
1
0
null
null
null
null
UTF-8
C++
false
false
7,747
cpp
#include "Particle.h" struct XGINE_API VertexBillboard { Vec3 pos; Vec2 expandStart; }; static D3DXMATRIX matWorldViewProj, matWorldInv; static UINT Passes, i; static LPD3DXEFFECT lpEffect; static D3DXVECTOR4 tmp; Vegetation::Vegetation(const char* textureName, Vec3 *positions, u32 num, u32 size, BillboardRotation rot) : m_num(num), m_rot(rot) { mesh = 0; position = Vec3(0,0,0); const D3DXVECTOR2 expandDirs[4] = { D3DXVECTOR2(-1,-1), D3DXVECTOR2(1,-1), D3DXVECTOR2(-1,1), D3DXVECTOR2(1,1) }; size /= 2.0f; gEngine.device->getDev()->CreateVertexBuffer(sizeof(VertexBillboard) * m_num * 4, D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &m_vb, 0); gEngine.device->getDev()->CreateIndexBuffer(m_num*6*sizeof(WORD), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &m_ib, 0); VertexBillboard* data; WORD* idata; m_vb->Lock(0, 0, (void**)&data, 0); m_ib->Lock(0, 0, (void**)&idata, 0); Vec3 min = Vec3(9999999,999999,9999999), max = Vec3(-9999999,-999999,-9999999); for(i32 i = 0, p = 0; i < m_num * 4; ++i) { if(!(i%4)) { data[i].pos = positions[p++]; if(data[i].pos.x < min.x)min.x = data[i].pos.x; if(data[i].pos.y < min.y)min.y = data[i].pos.y; if(data[i].pos.z < min.z)min.z = data[i].pos.z; if(data[i].pos.x > max.x)max.x = data[i].pos.x; if(data[i].pos.y > max.y)max.y = data[i].pos.y; if(data[i].pos.z > max.z)max.z = data[i].pos.z; idata[6*(i/4)] = 4*(i/4)+1; idata[6*(i/4)+1] = 4*(i/4); idata[6*(i/4)+2] = 4*(i/4)+3; idata[6*(i/4)+3] = 4*(i/4); idata[6*(i/4)+4] = 4*(i/4)+2; idata[6*(i/4)+5] = 4*(i/4)+3; } else data[i] = data[i-1]; data[i].expandStart = expandDirs[i%4] * size; } m_vb->Unlock(); m_ib->Unlock(); worldInvMat(&world, &invWorld, position); m_texture = gEngine.resMgr->load<Texture>(textureName); shader = gEngine.shaderMgr->load("Billboards.fx"); // Calculate estimated bounding box boundingBox.reset(min - Vec3(size,size,size), max + Vec3(size,size,size)); boundingBox.setTransform(position); } Vegetation::~Vegetation() { DXRELEASE(m_vb); DXRELEASE(m_ib); gEngine.resMgr->release(m_texture); } void Vegetation::update(ICamera* cam) { } void Vegetation::updateOrigin() { worldInvMat(&world, &invWorld, position); boundingBox.setTransform(position); } REND_TYPE Vegetation::getRendType() { return REND_DEFERRED; } u32 Vegetation::renderForward(Light* light) { if(shader && m_vb && m_ib && m_texture) { LPDIRECT3DDEVICE9 dev = gEngine.device->getDev(); ICamera *currCam = gEngine.renderer->get().camera; gEngine.renderer->setShader(shader->setTech("Billboards")); // settings: update(currCam); static Mat worldViewProj; worldViewProj = world * (*currCam->getViewProjectionMat()); shader->setMat("g_matWorldViewProj", &worldViewProj); if(m_rot == BILLBOARDROT_ALL) { D3DXVec4Transform(&tmp, currCam->getViewUp(), &invWorld); shader->setVec4("g_viewUp", &tmp); D3DXVec4Transform(&tmp, currCam->getViewLeft(), &invWorld); shader->setVec4("g_viewLeft", &tmp); } else if(m_rot == BILLBOARDROT_LEFT) { shader->setVec4("g_viewUp", &Vec4(0,1,0,1)); D3DXVec4Transform(&tmp, currCam->getViewLeft(), &invWorld); shader->setVec4("g_viewLeft", &tmp); } else if(m_rot == BILLBOARDROT_UP) { D3DXVec4Transform(&tmp, currCam->getViewUp(), &invWorld); shader->setVec4("g_viewUp", &tmp); shader->setVec4("g_viewLeft", &Vec4(1,0,0,1)); } else { shader->setVec4("g_viewUp", &Vec4(0,1,0,1)); shader->setVec4("g_viewLeft", &Vec4(1,0,0,1)); } shader->setTex("ColorMap", m_texture); {// rendering: gEngine.renderer->state.setAlphaBlendEnable(FALSE); gEngine.renderer->commitChanges(); dev->SetVertexDeclaration(gEngine.renderer->m_vd[VD_VEGETATION]); dev->SetStreamSource(0, m_vb, 0, sizeof(VertexBillboard)); dev->SetIndices(m_ib); dev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_num*4, 0, m_num*2); gEngine.renderer->addRenderedCounts(m_num*4, m_num*2); } return 1; } return 0; } u32 Vegetation::renderDeferred() { if(shader && m_vb && m_ib && m_texture) { LPDIRECT3DDEVICE9 dev = gEngine.device->getDev(); ICamera *currCam = gEngine.renderer->get().camera; gEngine.renderer->setShader(shader->setTech("BillboardsDeferred")); // settings: update(currCam); static Mat worldViewProj; worldViewProj = world * (*currCam->getViewProjectionMat()); shader->setMat("g_matWorldViewProj", &worldViewProj); if(m_rot == BILLBOARDROT_ALL) { D3DXVec4Transform(&tmp, currCam->getViewUp(), &invWorld); shader->setVec4("g_viewUp", &tmp); D3DXVec4Transform(&tmp, currCam->getViewLeft(), &invWorld); shader->setVec4("g_viewLeft", &tmp); } else if(m_rot == BILLBOARDROT_LEFT) { shader->setVec4("g_viewUp", &Vec4(0,1,0,1)); D3DXVec4Transform(&tmp, currCam->getViewLeft(), &invWorld); shader->setVec4("g_viewLeft", &tmp); } else if(m_rot == BILLBOARDROT_UP) { D3DXVec4Transform(&tmp, currCam->getViewUp(), &invWorld); shader->setVec4("g_viewUp", &tmp); shader->setVec4("g_viewLeft", &Vec4(1,0,0,1)); } else { shader->setVec4("g_viewUp", &Vec4(0,1,0,1)); shader->setVec4("g_viewLeft", &Vec4(1,0,0,1)); } shader->setTex("ColorMap", m_texture); {// rendering: gEngine.renderer->state.setAlphaBlendEnable(FALSE); gEngine.renderer->commitChanges(); dev->SetVertexDeclaration(gEngine.renderer->m_vd[VD_VEGETATION]); dev->SetStreamSource(0, m_vb, 0, sizeof(VertexBillboard)); dev->SetIndices(m_ib); dev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_num*4, 0, m_num*2); gEngine.renderer->addRenderedCounts(m_num*4, m_num*2); } return 1; } return 0; } u32 Vegetation::renderRaw() { if(gEngine.renderer->get().pass == REND_SM) { return 0; } else if(gEngine.renderer->get().pass == REND_UNLIT) { return 0; } if(shader && m_vb && m_ib && m_texture) { LPDIRECT3DDEVICE9 dev = gEngine.device->getDev(); ICamera *currCam = gEngine.renderer->get().camera; gEngine.renderer->setShader(shader->setTech("BillboardsRaw")); // settings: update(currCam); static Mat worldViewProj; worldViewProj = world * (*currCam->getViewProjectionMat()); shader->setMat("g_matWorldViewProj", &worldViewProj); if(m_rot == BILLBOARDROT_ALL) { D3DXVec4Transform(&tmp, currCam->getViewUp(), &invWorld); shader->setVec4("g_viewUp", &tmp); D3DXVec4Transform(&tmp, currCam->getViewLeft(), &invWorld); shader->setVec4("g_viewLeft", &tmp); } else if(m_rot == BILLBOARDROT_LEFT) { shader->setVec4("g_viewUp", &Vec4(0,1,0,1)); D3DXVec4Transform(&tmp, currCam->getViewLeft(), &invWorld); shader->setVec4("g_viewLeft", &tmp); } else if(m_rot == BILLBOARDROT_UP) { D3DXVec4Transform(&tmp, currCam->getViewUp(), &invWorld); shader->setVec4("g_viewUp", &tmp); shader->setVec4("g_viewLeft", &Vec4(1,0,0,1)); } else { shader->setVec4("g_viewUp", &Vec4(0,1,0,1)); shader->setVec4("g_viewLeft", &Vec4(1,0,0,1)); } shader->setTex("ColorMap", m_texture); {// rendering: gEngine.renderer->state.setAlphaBlendEnable(FALSE); gEngine.renderer->commitChanges(); dev->SetVertexDeclaration(gEngine.renderer->m_vd[VD_VEGETATION]); dev->SetStreamSource(0, m_vb, 0, sizeof(VertexBillboard)); dev->SetIndices(m_ib); dev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_num*4, 0, m_num*2); gEngine.renderer->addRenderedCounts(m_num*4, m_num*2); } return 1; } return 0; }
[ "adasm@live.com" ]
adasm@live.com
b947d1459165d7fa60f17856f4c57b1bd046b13d
b3c7e13c639f6f71dd828431d3b1b09c7362e25f
/game/server/baseentity.cpp
dc03aa16927e69ca0aa0f91157ee4c65ae00d606
[]
no_license
emcniece/fps-moba
d4a47e6c5decf24e2ff87e337d71f75d86deb810
7b06932f18d54f5b2a336f9d955e2925a9cbe33b
refs/heads/master
2021-01-01T20:40:49.087556
2013-07-09T04:10:44
2013-07-09T04:10:44
10,415,654
1
1
null
null
null
null
UTF-8
C++
false
false
225,480
cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: The base class from which all game entities are derived. // //===========================================================================// #include "cbase.h" #include "globalstate.h" #include "isaverestore.h" #include "client.h" #include "decals.h" #include "gamerules.h" #include "entityapi.h" #include "entitylist.h" #include "eventqueue.h" #include "hierarchy.h" #include "basecombatweapon.h" #include "const.h" #include "player.h" // For debug draw sending #include "ndebugoverlay.h" #include "physics.h" #include "model_types.h" #include "team.h" #include "sendproxy.h" #include "IEffects.h" #include "vstdlib/random.h" #include "baseentity.h" #include "collisionutils.h" #include "coordsize.h" #include "animation.h" #include "tier1/strtools.h" #include "engine/IEngineSound.h" #include "physics_saverestore.h" #include "saverestore_utlvector.h" #include "bone_setup.h" #include "vcollide_parse.h" #include "filters.h" #include "te_effect_dispatch.h" #include "AI_Criteria.h" #include "AI_ResponseSystem.h" #include "world.h" #include "globals.h" #include "saverestoretypes.h" #include "SkyCamera.h" #include "sceneentity.h" #include "game.h" #include "tier0/vprof.h" #include "ai_basenpc.h" #include "iservervehicle.h" #include "eventlist.h" #include "scriptevent.h" #include "SoundEmitterSystem/isoundemittersystembase.h" #include "UtlCachedFileData.h" #include "utlbuffer.h" #include "positionwatcher.h" #include "movetype_push.h" #include "tier0/icommandline.h" #include "vphysics/friction.h" #include <ctype.h> #include "datacache/imdlcache.h" #include "ModelSoundsCache.h" #include "env_debughistory.h" #include "tier1/utlstring.h" #include "utlhashtable.h" #if defined( TF_DLL ) #include "tf_gamerules.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern bool g_bTestMoveTypeStepSimulation; extern ConVar sv_vehicle_autoaim_scale; // Init static class variables bool CBaseEntity::m_bInDebugSelect = false; // Used for selection in debug overlays int CBaseEntity::m_nDebugPlayer = -1; // Player doing the selection // This can be set before creating an entity to force it to use a particular edict. edict_t *g_pForceAttachEdict = NULL; bool CBaseEntity::m_bDebugPause = false; // Whether entity i/o is paused. int CBaseEntity::m_nDebugSteps = 1; // Number of entity outputs to fire before pausing again. bool CBaseEntity::sm_bDisableTouchFuncs = false; // Disables PhysicsTouch and PhysicsStartTouch function calls bool CBaseEntity::sm_bAccurateTriggerBboxChecks = true; // set to false for legacy behavior in ep1 int CBaseEntity::m_nPredictionRandomSeed = -1; CBasePlayer *CBaseEntity::m_pPredictionPlayer = NULL; // Used to make sure nobody calls UpdateTransmitState directly. int g_nInsideDispatchUpdateTransmitState = 0; // When this is false, throw an assert in debug when GetAbsAnything is called. Used when hierachy is incomplete/invalid. bool CBaseEntity::s_bAbsQueriesValid = true; ConVar sv_netvisdist( "sv_netvisdist", "10000", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "Test networking visibility distance" ); // This table encodes edict data. void SendProxy_AnimTime( const SendProp *pProp, const void *pStruct, const void *pVarData, DVariant *pOut, int iElement, int objectID ) { CBaseEntity *pEntity = (CBaseEntity *)pStruct; #if defined( _DEBUG ) CBaseAnimating *pAnimating = pEntity->GetBaseAnimating(); Assert( pAnimating ); if ( pAnimating ) { Assert( !pAnimating->IsUsingClientSideAnimation() ); } #endif int ticknumber = TIME_TO_TICKS( pEntity->m_flAnimTime ); // Tickbase is current tick rounded down to closes 100 ticks int tickbase = gpGlobals->GetNetworkBase( gpGlobals->tickcount, pEntity->entindex() ); int addt = 0; // If it's within the last tick interval through the current one, then we can encode it if ( ticknumber >= ( tickbase - 100 ) ) { addt = ( ticknumber - tickbase ) & 0xFF; } pOut->m_Int = addt; } // This table encodes edict data. void SendProxy_SimulationTime( const SendProp *pProp, const void *pStruct, const void *pVarData, DVariant *pOut, int iElement, int objectID ) { CBaseEntity *pEntity = (CBaseEntity *)pStruct; int ticknumber = TIME_TO_TICKS( pEntity->m_flSimulationTime ); // tickbase is current tick rounded down to closest 100 ticks int tickbase = gpGlobals->GetNetworkBase( gpGlobals->tickcount, pEntity->entindex() ); int addt = 0; if ( ticknumber >= tickbase ) { addt = ( ticknumber - tickbase ) & 0xff; } pOut->m_Int = addt; } void* SendProxy_ClientSideAnimation( const SendProp *pProp, const void *pStruct, const void *pVarData, CSendProxyRecipients *pRecipients, int objectID ) { CBaseEntity *pEntity = (CBaseEntity *)pStruct; CBaseAnimating *pAnimating = pEntity->GetBaseAnimating(); if ( pAnimating && !pAnimating->IsUsingClientSideAnimation() ) return (void*)pVarData; else return NULL; // Don't send animtime unless the client needs it. } REGISTER_SEND_PROXY_NON_MODIFIED_POINTER( SendProxy_ClientSideAnimation ); BEGIN_SEND_TABLE_NOBASE( CBaseEntity, DT_AnimTimeMustBeFirst ) // NOTE: Animtime must be sent before origin and angles ( from pev ) because it has a // proxy on the client that stores off the old values before writing in the new values and // if it is sent after the new values, then it will only have the new origin and studio model, etc. // interpolation will be busted SendPropInt (SENDINFO(m_flAnimTime), 8, SPROP_UNSIGNED|SPROP_CHANGES_OFTEN|SPROP_ENCODED_AGAINST_TICKCOUNT, SendProxy_AnimTime), END_SEND_TABLE() #if !defined( NO_ENTITY_PREDICTION ) BEGIN_SEND_TABLE_NOBASE( CBaseEntity, DT_PredictableId ) SendPropPredictableId( SENDINFO( m_PredictableID ) ), SendPropInt( SENDINFO( m_bIsPlayerSimulated ), 1, SPROP_UNSIGNED ), END_SEND_TABLE() static void* SendProxy_SendPredictableId( const SendProp *pProp, const void *pStruct, const void *pVarData, CSendProxyRecipients *pRecipients, int objectID ) { CBaseEntity *pEntity = (CBaseEntity *)pStruct; if ( !pEntity || !pEntity->m_PredictableID->IsActive() ) return NULL; int id_player_index = pEntity->m_PredictableID->GetPlayer(); pRecipients->SetOnly( id_player_index ); return ( void * )pVarData; } REGISTER_SEND_PROXY_NON_MODIFIED_POINTER( SendProxy_SendPredictableId ); #endif void SendProxy_Origin( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ) { CBaseEntity *entity = (CBaseEntity*)pStruct; Assert( entity ); const Vector *v; if ( !entity->UseStepSimulationNetworkOrigin( &v ) ) { v = &entity->GetLocalOrigin(); } pOut->m_Vector[ 0 ] = v->x; pOut->m_Vector[ 1 ] = v->y; pOut->m_Vector[ 2 ] = v->z; } //-------------------------------------------------------------------------------------------------------- // Used when breaking up origin, note we still have to deal with StepSimulation //-------------------------------------------------------------------------------------------------------- void SendProxy_OriginXY( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ) { CBaseEntity *entity = (CBaseEntity*)pStruct; Assert( entity ); const Vector *v; if ( !entity->UseStepSimulationNetworkOrigin( &v ) ) { v = &entity->GetLocalOrigin(); } pOut->m_Vector[ 0 ] = v->x; pOut->m_Vector[ 1 ] = v->y; } //-------------------------------------------------------------------------------------------------------- // Used when breaking up origin, note we still have to deal with StepSimulation //-------------------------------------------------------------------------------------------------------- void SendProxy_OriginZ( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ) { CBaseEntity *entity = (CBaseEntity*)pStruct; Assert( entity ); const Vector *v; if ( !entity->UseStepSimulationNetworkOrigin( &v ) ) { v = &entity->GetLocalOrigin(); } pOut->m_Float = v->z; } void SendProxy_Angles( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ) { CBaseEntity *entity = (CBaseEntity*)pStruct; Assert( entity ); const QAngle *a; if ( !entity->UseStepSimulationNetworkAngles( &a ) ) { a = &entity->GetLocalAngles(); } pOut->m_Vector[ 0 ] = anglemod( a->x ); pOut->m_Vector[ 1 ] = anglemod( a->y ); pOut->m_Vector[ 2 ] = anglemod( a->z ); } // This table encodes the CBaseEntity data. IMPLEMENT_SERVERCLASS_ST_NOBASE( CBaseEntity, DT_BaseEntity ) SendPropDataTable( "AnimTimeMustBeFirst", 0, &REFERENCE_SEND_TABLE(DT_AnimTimeMustBeFirst), SendProxy_ClientSideAnimation ), SendPropInt (SENDINFO(m_flSimulationTime), SIMULATION_TIME_WINDOW_BITS, SPROP_UNSIGNED|SPROP_CHANGES_OFTEN|SPROP_ENCODED_AGAINST_TICKCOUNT, SendProxy_SimulationTime), #if PREDICTION_ERROR_CHECK_LEVEL > 1 SendPropVector (SENDINFO(m_vecOrigin), -1, SPROP_NOSCALE|SPROP_CHANGES_OFTEN, 0.0f, HIGH_DEFAULT, SendProxy_Origin ), #else SendPropVector (SENDINFO(m_vecOrigin), -1, SPROP_COORD|SPROP_CHANGES_OFTEN, 0.0f, HIGH_DEFAULT, SendProxy_Origin ), #endif SendPropInt (SENDINFO( m_ubInterpolationFrame ), NOINTERP_PARITY_MAX_BITS, SPROP_UNSIGNED ), SendPropModelIndex(SENDINFO(m_nModelIndex)), SendPropDataTable( SENDINFO_DT( m_Collision ), &REFERENCE_SEND_TABLE(DT_CollisionProperty) ), SendPropInt (SENDINFO(m_nRenderFX), 8, SPROP_UNSIGNED ), SendPropInt (SENDINFO(m_nRenderMode), 8, SPROP_UNSIGNED ), SendPropInt (SENDINFO(m_fEffects), EF_MAX_BITS, SPROP_UNSIGNED), SendPropInt (SENDINFO(m_clrRender), 32, SPROP_UNSIGNED), SendPropInt (SENDINFO(m_iTeamNum), TEAMNUM_NUM_BITS, 0), SendPropInt (SENDINFO(m_CollisionGroup), 5, SPROP_UNSIGNED), SendPropFloat (SENDINFO(m_flElasticity), 0, SPROP_COORD), SendPropFloat (SENDINFO(m_flShadowCastDistance), 12, SPROP_UNSIGNED ), SendPropEHandle (SENDINFO(m_hOwnerEntity)), SendPropEHandle (SENDINFO(m_hEffectEntity)), SendPropEHandle (SENDINFO_NAME(m_hMoveParent, moveparent)), SendPropInt (SENDINFO(m_iParentAttachment), NUM_PARENTATTACHMENT_BITS, SPROP_UNSIGNED), SendPropInt (SENDINFO_NAME( m_MoveType, movetype ), MOVETYPE_MAX_BITS, SPROP_UNSIGNED ), SendPropInt (SENDINFO_NAME( m_MoveCollide, movecollide ), MOVECOLLIDE_MAX_BITS, SPROP_UNSIGNED ), #if PREDICTION_ERROR_CHECK_LEVEL > 1 SendPropVector (SENDINFO(m_angRotation), -1, SPROP_NOSCALE|SPROP_CHANGES_OFTEN, 0, HIGH_DEFAULT, SendProxy_Angles ), #else SendPropQAngles (SENDINFO(m_angRotation), 13, SPROP_CHANGES_OFTEN, SendProxy_Angles ), #endif SendPropInt ( SENDINFO( m_iTextureFrameIndex ), 8, SPROP_UNSIGNED ), #if !defined( NO_ENTITY_PREDICTION ) SendPropDataTable( "predictable_id", 0, &REFERENCE_SEND_TABLE( DT_PredictableId ), SendProxy_SendPredictableId ), #endif // FIXME: Collapse into another flag field? SendPropInt (SENDINFO(m_bSimulatedEveryTick), 1, SPROP_UNSIGNED ), SendPropInt (SENDINFO(m_bAnimatedEveryTick), 1, SPROP_UNSIGNED ), SendPropBool( SENDINFO( m_bAlternateSorting )), #ifdef TF_DLL SendPropArray3( SENDINFO_ARRAY3(m_nModelIndexOverrides), SendPropInt( SENDINFO_ARRAY(m_nModelIndexOverrides), SP_MODEL_INDEX_BITS, SPROP_UNSIGNED ) ), #endif END_SEND_TABLE() // dynamic models class CBaseEntityModelLoadProxy { protected: class Handler : public IModelLoadCallback { public: explicit Handler( CBaseEntity *pEntity ) : m_pEntity(pEntity) { } virtual void OnModelLoadComplete( const model_t *pModel ); CBaseEntity* m_pEntity; }; Handler* m_pHandler; public: explicit CBaseEntityModelLoadProxy( CBaseEntity *pEntity ) : m_pHandler( new Handler( pEntity ) ) { } ~CBaseEntityModelLoadProxy() { delete m_pHandler; } void Register( int nModelIndex ) const { modelinfo->RegisterModelLoadCallback( nModelIndex, m_pHandler ); } operator CBaseEntity * () const { return m_pHandler->m_pEntity; } private: CBaseEntityModelLoadProxy( const CBaseEntityModelLoadProxy& ); CBaseEntityModelLoadProxy& operator=( const CBaseEntityModelLoadProxy& ); }; static CUtlHashtable< CBaseEntityModelLoadProxy, empty_t, PointerHashFunctor, PointerEqualFunctor, CBaseEntity * > sg_DynamicLoadHandlers; void CBaseEntityModelLoadProxy::Handler::OnModelLoadComplete( const model_t *pModel ) { m_pEntity->OnModelLoadComplete( pModel ); sg_DynamicLoadHandlers.Remove( m_pEntity ); // NOTE: destroys *this! } CBaseEntity::CBaseEntity( bool bServerOnly ) { COMPILE_TIME_ASSERT( MOVETYPE_LAST < (1 << MOVETYPE_MAX_BITS) ); COMPILE_TIME_ASSERT( MOVECOLLIDE_COUNT < (1 << MOVECOLLIDE_MAX_BITS) ); #ifdef _DEBUG // necessary since in debug, we initialize vectors to NAN for debugging m_vecAngVelocity.Init(); // m_vecAbsAngVelocity.Init(); m_vecViewOffset.Init(); m_vecBaseVelocity.GetForModify().Init(); m_vecVelocity.Init(); m_vecAbsVelocity.Init(); #endif m_bAlternateSorting = false; m_CollisionGroup = COLLISION_GROUP_NONE; m_iParentAttachment = 0; CollisionProp()->Init( this ); NetworkProp()->Init( this ); // NOTE: THIS MUST APPEAR BEFORE ANY SetMoveType() or SetNextThink() calls AddEFlags( EFL_NO_THINK_FUNCTION | EFL_NO_GAME_PHYSICS_SIMULATION | EFL_USE_PARTITION_WHEN_NOT_SOLID ); // clear debug overlays m_debugOverlays = 0; m_pTimedOverlay = NULL; m_pPhysicsObject = NULL; m_flElasticity = 1.0f; m_flShadowCastDistance = m_flDesiredShadowCastDistance = 0; SetRenderColor( 255, 255, 255, 255 ); m_iTeamNum = m_iInitialTeamNum = TEAM_UNASSIGNED; m_nLastThinkTick = gpGlobals->tickcount; m_nSimulationTick = -1; SetIdentityMatrix( m_rgflCoordinateFrame ); m_pBlocker = NULL; #if _DEBUG m_iCurrentThinkContext = NO_THINK_CONTEXT; #endif m_nWaterTouch = m_nSlimeTouch = 0; SetSolid( SOLID_NONE ); ClearSolidFlags(); m_nModelIndex = 0; m_bDynamicModelAllowed = false; m_bDynamicModelPending = false; m_bDynamicModelSetBounds = false; SetMoveType( MOVETYPE_NONE ); SetOwnerEntity( NULL ); SetCheckUntouch( false ); SetModelIndex( 0 ); SetModelName( NULL_STRING ); m_nTransmitStateOwnedCounter = 0; SetCollisionBounds( vec3_origin, vec3_origin ); ClearFlags(); SetFriction( 1.0f ); if ( bServerOnly ) { AddEFlags( EFL_SERVER_ONLY ); } NetworkProp()->MarkPVSInformationDirty(); #ifndef _XBOX AddEFlags( EFL_USE_PARTITION_WHEN_NOT_SOLID ); #endif } //----------------------------------------------------------------------------- // Purpose: Scale up our physics hull and test against the new one // Input : *pNewCollide - New collision hull //----------------------------------------------------------------------------- void CBaseEntity::SetScaledPhysics( IPhysicsObject *pNewObject ) { if ( pNewObject ) { AddSolidFlags( FSOLID_CUSTOMBOXTEST | FSOLID_CUSTOMRAYTEST ); } else { RemoveSolidFlags( FSOLID_CUSTOMBOXTEST | FSOLID_CUSTOMRAYTEST ); } } extern bool g_bDisableEhandleAccess; //----------------------------------------------------------------------------- // Purpose: See note below //----------------------------------------------------------------------------- CBaseEntity::~CBaseEntity( ) { // FIXME: This can't be called from UpdateOnRemove! There's at least one // case where friction sounds are added between the call to UpdateOnRemove + ~CBaseEntity PhysCleanupFrictionSounds( this ); Assert( !IsDynamicModelIndex( m_nModelIndex ) ); Verify( !sg_DynamicLoadHandlers.Remove( this ) ); // In debug make sure that we don't call delete on an entity without setting // the disable flag first! // EHANDLE accessors will check, in debug, for access to entities during destruction of // another entity. // That kind of operation should only occur in UpdateOnRemove calls // Deletion should only occur via UTIL_Remove(Immediate) calls, not via naked delete calls Assert( g_bDisableEhandleAccess ); VPhysicsDestroyObject(); // Need to remove references to this entity before EHANDLES go null { g_bDisableEhandleAccess = false; CBaseEntity::PhysicsRemoveTouchedList( this ); CBaseEntity::PhysicsRemoveGroundList( this ); SetGroundEntity( NULL ); // remove us from the ground entity if we are on it DestroyAllDataObjects(); g_bDisableEhandleAccess = true; // Remove this entity from the ent list (NOTE: This Makes EHANDLES go NULL) gEntList.RemoveEntity( GetRefEHandle() ); } } void CBaseEntity::PostConstructor( const char *szClassname ) { if ( szClassname ) { SetClassname(szClassname); } Assert( m_iClassname != NULL_STRING && STRING(m_iClassname) != NULL ); // Possibly get an edict, and add self to global list of entites. if ( IsEFlagSet( EFL_SERVER_ONLY ) ) { gEntList.AddNonNetworkableEntity( this ); } else { // Certain entities set up their edicts in the constructor if ( !IsEFlagSet( EFL_NO_AUTO_EDICT_ATTACH ) ) { NetworkProp()->AttachEdict( g_pForceAttachEdict ); g_pForceAttachEdict = NULL; } // Some ents like the player override the AttachEdict function and do it at a different time. // While precaching, they don't ever have an edict, so we don't need to add them to // the entity list in that case. if ( edict() ) { gEntList.AddNetworkableEntity( this, entindex() ); // Cache our IServerNetworkable pointer for the engine for fast access. if ( edict() ) edict()->m_pNetworkable = NetworkProp(); } } CheckHasThinkFunction( false ); CheckHasGamePhysicsSimulation(); } //----------------------------------------------------------------------------- // Purpose: Called after player becomes active in the game //----------------------------------------------------------------------------- void CBaseEntity::PostClientActive( void ) { } //----------------------------------------------------------------------------- // Purpose: Verifies that this entity's data description is valid in debug builds. //----------------------------------------------------------------------------- #ifdef _DEBUG typedef CUtlVector< const char * > KeyValueNameList_t; static void AddDataMapFieldNamesToList( KeyValueNameList_t &list, datamap_t *pDataMap ) { while (pDataMap != NULL) { for (int i = 0; i < pDataMap->dataNumFields; i++) { typedescription_t *pField = &pDataMap->dataDesc[i]; if (pField->fieldType == FIELD_EMBEDDED) { AddDataMapFieldNamesToList( list, pField->td ); continue; } if (pField->flags & FTYPEDESC_KEY) { list.AddToTail( pField->externalName ); } } pDataMap = pDataMap->baseMap; } } void CBaseEntity::ValidateDataDescription(void) { // Multiple key fields that have the same name are not allowed - it creates an // ambiguity when trying to parse keyvalues and outputs. datamap_t *pDataMap = GetDataDescMap(); if ((pDataMap == NULL) || pDataMap->bValidityChecked) return; pDataMap->bValidityChecked = true; // Let's generate a list of all keyvalue strings in the entire hierarchy... KeyValueNameList_t names(128); AddDataMapFieldNamesToList( names, pDataMap ); for (int i = names.Count(); --i > 0; ) { for (int j = i - 1; --j >= 0; ) { if (!Q_stricmp(names[i], names[j])) { DevMsg( "%s has multiple data description entries for \"%s\"\n", STRING(m_iClassname), names[i]); break; } } } } #endif // _DEBUG //----------------------------------------------------------------------------- // Sets the collision bounds + the size //----------------------------------------------------------------------------- void CBaseEntity::SetCollisionBounds( const Vector& mins, const Vector &maxs ) { m_Collision.SetCollisionBounds( mins, maxs ); } void CBaseEntity::StopFollowingEntity( ) { if( !IsFollowingEntity() ) { // Assert( IsEffectActive( EF_BONEMERGE ) == 0 ); return; } SetParent( NULL ); RemoveEffects( EF_BONEMERGE ); RemoveSolidFlags( FSOLID_NOT_SOLID ); SetMoveType( MOVETYPE_NONE ); CollisionRulesChanged(); } bool CBaseEntity::IsFollowingEntity() { return IsEffectActive( EF_BONEMERGE ) && (GetMoveType() == MOVETYPE_NONE) && GetMoveParent(); } CBaseEntity *CBaseEntity::GetFollowedEntity() { if (!IsFollowingEntity()) return NULL; return GetMoveParent(); } void CBaseEntity::SetClassname( const char *className ) { m_iClassname = AllocPooledString( className ); } void CBaseEntity::SetModelIndex( int index ) { if ( IsDynamicModelIndex( index ) && !(GetBaseAnimating() && m_bDynamicModelAllowed) ) { AssertMsg( false, "dynamic model support not enabled on server entity" ); index = -1; } if ( index != m_nModelIndex ) { if ( m_bDynamicModelPending ) { sg_DynamicLoadHandlers.Remove( this ); } modelinfo->ReleaseDynamicModel( m_nModelIndex ); modelinfo->AddRefDynamicModel( index ); m_nModelIndex = index; m_bDynamicModelSetBounds = false; if ( IsDynamicModelIndex( index ) ) { m_bDynamicModelPending = true; sg_DynamicLoadHandlers[ sg_DynamicLoadHandlers.Insert( this ) ].Register( index ); } else { m_bDynamicModelPending = false; OnNewModel(); } } DispatchUpdateTransmitState(); } void CBaseEntity::ClearModelIndexOverrides( void ) { #ifdef TF_DLL for ( int index = 0 ; index < MAX_MODEL_INDEX_OVERRIDES ; index++ ) { m_nModelIndexOverrides.Set( index, 0 ); } #endif } void CBaseEntity::SetModelIndexOverride( int index, int nValue ) { #ifdef TF_DLL if ( ( index >= MODEL_INDEX_OVERRIDE_DEFAULT ) && ( index < MAX_MODEL_INDEX_OVERRIDES ) ) { if ( nValue != m_nModelIndexOverrides[index] ) { m_nModelIndexOverrides.Set( index, nValue ); } } #endif } // position to shoot at Vector CBaseEntity::BodyTarget( const Vector &posSrc, bool bNoisy) { return WorldSpaceCenter( ); } // return the position of my head. someone's trying to attack it. Vector CBaseEntity::HeadTarget( const Vector &posSrc ) { return EyePosition(); } struct TimedOverlay_t { char *msg; int msgEndTime; int msgStartTime; TimedOverlay_t *pNextTimedOverlay; }; //----------------------------------------------------------------------------- // Purpose: Display an error message on the entity // Input : // Output : //----------------------------------------------------------------------------- void CBaseEntity::AddTimedOverlay( const char *msg, int endTime ) { TimedOverlay_t *pNewTO = new TimedOverlay_t; int len = strlen(msg); pNewTO->msg = new char[len + 1]; Q_strncpy(pNewTO->msg,msg, len+1); pNewTO->msgEndTime = gpGlobals->curtime + endTime; pNewTO->msgStartTime = gpGlobals->curtime; pNewTO->pNextTimedOverlay = m_pTimedOverlay; m_pTimedOverlay = pNewTO; } //----------------------------------------------------------------------------- // Purpose: Send debug overlay box to the client // Input : // Output : //----------------------------------------------------------------------------- void CBaseEntity::DrawBBoxOverlay( float flDuration ) { if (edict()) { NDebugOverlay::EntityBounds(this, 255, 100, 0, 0, flDuration ); if ( CollisionProp()->IsSolidFlagSet( FSOLID_USE_TRIGGER_BOUNDS ) ) { Vector vecTriggerMins, vecTriggerMaxs; CollisionProp()->WorldSpaceTriggerBounds( &vecTriggerMins, &vecTriggerMaxs ); Vector center = 0.5f * (vecTriggerMins + vecTriggerMaxs); Vector extents = vecTriggerMaxs - center; NDebugOverlay::Box(center, -extents, extents, 0, 255, 255, 0, flDuration ); } } } void CBaseEntity::DrawAbsBoxOverlay() { int red = 0; int green = 200; if ( VPhysicsGetObject() && VPhysicsGetObject()->IsAsleep() ) { red = 90; green = 120; } if (edict()) { // Surrounding boxes are axially aligned, so ignore angles Vector vecSurroundMins, vecSurroundMaxs; CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs ); Vector center = 0.5f * (vecSurroundMins + vecSurroundMaxs); Vector extents = vecSurroundMaxs - center; NDebugOverlay::Box(center, -extents, extents, red, green, 0, 0 ,0); } } void CBaseEntity::DrawRBoxOverlay() { } //----------------------------------------------------------------------------- // Purpose: Draws an axis overlay at the origin and angles of the entity //----------------------------------------------------------------------------- void CBaseEntity::SendDebugPivotOverlay( void ) { if ( edict() ) { NDebugOverlay::Axis( GetAbsOrigin(), GetAbsAngles(), 20, true, 0 ); } } //------------------------------------------------------------------------------ // Purpose : Add new entity positioned overlay text // Input : How many lines to offset text from origin // The text to print // How long to display text // The color of the text // Output : //------------------------------------------------------------------------------ void CBaseEntity::EntityText( int text_offset, const char *text, float duration, int r, int g, int b, int a ) { Vector origin; Vector vecLocalCenter; VectorAdd( m_Collision.OBBMins(), m_Collision.OBBMaxs(), vecLocalCenter ); vecLocalCenter *= 0.5f; if ( ( m_Collision.GetCollisionAngles() == vec3_angle ) || ( vecLocalCenter == vec3_origin ) ) { VectorAdd( vecLocalCenter, m_Collision.GetCollisionOrigin(), origin ); } else { VectorTransform( vecLocalCenter, m_Collision.CollisionToWorldTransform(), origin ); } NDebugOverlay::EntityTextAtPosition( origin, text_offset, text, duration, r, g, b, a ); } //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CBaseEntity::DrawTimedOverlays(void) { // Draw name first if I have an overlay or am in message mode if ((m_debugOverlays & OVERLAY_MESSAGE_BIT)) { char tempstr[512]; Q_snprintf( tempstr, sizeof( tempstr ), "[%s]", GetDebugName() ); EntityText(0,tempstr, 0); } // Now draw overlays TimedOverlay_t* pTO = m_pTimedOverlay; TimedOverlay_t* pNextTO = NULL; TimedOverlay_t* pLastTO = NULL; int nCount = 1; // Offset by one while (pTO) { pNextTO = pTO->pNextTimedOverlay; // Remove old messages unless messages are paused if ((!CBaseEntity::Debug_IsPaused() && gpGlobals->curtime > pTO->msgEndTime) || (nCount > 10)) { if (pLastTO) { pLastTO->pNextTimedOverlay = pNextTO; } else { m_pTimedOverlay = pNextTO; } delete pTO->msg; delete pTO; } else { int nAlpha = 0; // If messages aren't paused fade out if (!CBaseEntity::Debug_IsPaused()) { nAlpha = 255*((gpGlobals->curtime - pTO->msgStartTime)/(pTO->msgEndTime - pTO->msgStartTime)); } int r = 185; int g = 145; int b = 145; // Brighter when new message if (nAlpha < 50) { r = 255; g = 205; b = 205; } if (nAlpha < 0) nAlpha = 0; EntityText(nCount,pTO->msg, 0.0, r, g, b, 255-nAlpha); nCount++; pLastTO = pTO; } pTO = pNextTO; } } //----------------------------------------------------------------------------- // Purpose: Draw all overlays (should be implemented by subclass to add // any additional non-text overlays) // Input : // Output : Current text offset from the top //----------------------------------------------------------------------------- void CBaseEntity::DrawDebugGeometryOverlays(void) { DrawTimedOverlays(); DrawDebugTextOverlays(); if (m_debugOverlays & OVERLAY_NAME_BIT) { EntityText(0,GetDebugName(), 0); } if (m_debugOverlays & OVERLAY_BBOX_BIT) { DrawBBoxOverlay(); } if (m_debugOverlays & OVERLAY_ABSBOX_BIT ) { DrawAbsBoxOverlay(); } if (m_debugOverlays & OVERLAY_PIVOT_BIT) { SendDebugPivotOverlay(); } if( m_debugOverlays & OVERLAY_RBOX_BIT ) { DrawRBoxOverlay(); } if ( m_debugOverlays & (OVERLAY_BBOX_BIT|OVERLAY_PIVOT_BIT) ) { // draw mass center if ( VPhysicsGetObject() ) { Vector massCenter = VPhysicsGetObject()->GetMassCenterLocalSpace(); Vector worldPos; VPhysicsGetObject()->LocalToWorld( &worldPos, massCenter ); NDebugOverlay::Cross3D( worldPos, 12, 255, 0, 0, false, 0 ); DebugDrawContactPoints(VPhysicsGetObject()); if ( GetMoveType() != MOVETYPE_VPHYSICS ) { Vector pos; QAngle angles; VPhysicsGetObject()->GetPosition( &pos, &angles ); float dist = (pos - GetAbsOrigin()).Length(); Vector axis; float deltaAngle; RotationDeltaAxisAngle( angles, GetAbsAngles(), axis, deltaAngle ); if ( dist > 2 || fabsf(deltaAngle) > 2 ) { Vector mins, maxs; physcollision->CollideGetAABB( &mins, &maxs, VPhysicsGetObject()->GetCollide(), vec3_origin, vec3_angle ); NDebugOverlay::BoxAngles( pos, mins, maxs, angles, 255, 255, 0, 16, 0 ); } } } } if ( m_debugOverlays & OVERLAY_SHOW_BLOCKSLOS ) { if ( BlocksLOS() ) { NDebugOverlay::EntityBounds(this, 255, 255, 255, 0, 0 ); } } if ( m_debugOverlays & OVERLAY_AUTOAIM_BIT && (GetFlags()&FL_AIMTARGET) && AI_GetSinglePlayer() != NULL ) { // Crude, but it gets the point across. Vector vecCenter = GetAutoAimCenter(); Vector vecRight, vecUp, vecDiag; CBasePlayer *pPlayer = AI_GetSinglePlayer(); float radius = GetAutoAimRadius(); QAngle angles = pPlayer->EyeAngles(); AngleVectors( angles, NULL, &vecRight, &vecUp ); int r,g,b; if( ((int)gpGlobals->curtime) % 2 == 1 ) { r = 255; g = 255; b = 255; if( pPlayer->GetActiveWeapon() != NULL ) radius *= pPlayer->GetActiveWeapon()->WeaponAutoAimScale(); } else { r = 255;g=0;b=0; if( !ShouldAttractAutoAim(pPlayer) ) { g = 255; } } if( pPlayer->IsInAVehicle() ) { radius *= sv_vehicle_autoaim_scale.GetFloat(); } NDebugOverlay::Line( vecCenter, vecCenter + vecRight * radius, r, g, b, true, 0.1 ); NDebugOverlay::Line( vecCenter, vecCenter - vecRight * radius, r, g, b, true, 0.1 ); NDebugOverlay::Line( vecCenter, vecCenter + vecUp * radius, r, g, b, true, 0.1 ); NDebugOverlay::Line( vecCenter, vecCenter - vecUp * radius, r, g, b, true, 0.1 ); vecDiag = vecRight + vecUp; VectorNormalize( vecDiag ); NDebugOverlay::Line( vecCenter - vecDiag * radius, vecCenter + vecDiag * radius, r, g, b, true, 0.1 ); vecDiag = vecRight - vecUp; VectorNormalize( vecDiag ); NDebugOverlay::Line( vecCenter - vecDiag * radius, vecCenter + vecDiag * radius, r, g, b, true, 0.1 ); } } //----------------------------------------------------------------------------- // Purpose: Draw any text overlays (override in subclass to add additional text) // Output : Current text offset from the top //----------------------------------------------------------------------------- int CBaseEntity::DrawDebugTextOverlays(void) { int offset = 1; if (m_debugOverlays & OVERLAY_TEXT_BIT) { char tempstr[512]; Q_snprintf( tempstr, sizeof(tempstr), "(%d) Name: %s (%s)", entindex(), GetDebugName(), GetClassname() ); EntityText(offset,tempstr, 0); offset++; if( m_iGlobalname != NULL_STRING ) { Q_snprintf( tempstr, sizeof(tempstr), "GLOBALNAME: %s", STRING(m_iGlobalname) ); EntityText(offset,tempstr, 0); offset++; } Vector vecOrigin = GetAbsOrigin(); Q_snprintf( tempstr, sizeof(tempstr), "Position: %0.1f, %0.1f, %0.1f\n", vecOrigin.x, vecOrigin.y, vecOrigin.z ); EntityText( offset, tempstr, 0 ); offset++; if( GetModelName() != NULL_STRING || GetBaseAnimating() ) { Q_snprintf(tempstr, sizeof(tempstr), "Model:%s", STRING(GetModelName()) ); EntityText(offset,tempstr,0); offset++; } if( m_hDamageFilter.Get() != NULL ) { Q_snprintf( tempstr, sizeof(tempstr), "DAMAGE FILTER:%s", m_hDamageFilter->GetDebugName() ); EntityText( offset,tempstr,0 ); offset++; } } if (m_debugOverlays & OVERLAY_VIEWOFFSET) { NDebugOverlay::Cross3D( EyePosition(), 16, 255, 0, 0, true, 0.05f ); } return offset; } void CBaseEntity::SetParent( string_t newParent, CBaseEntity *pActivator, int iAttachment ) { // find and notify the new parent CBaseEntity *pParent = gEntList.FindEntityByName( NULL, newParent, NULL, pActivator ); // debug check if ( newParent != NULL_STRING && pParent == NULL ) { Msg( "Entity %s(%s) has bad parent %s\n", STRING(m_iClassname), GetDebugName(), STRING(newParent) ); } else { // make sure there isn't any ambiguity if ( gEntList.FindEntityByName( pParent, newParent, NULL, pActivator ) ) { Msg( "Entity %s(%s) has ambigious parent %s\n", STRING(m_iClassname), GetDebugName(), STRING(newParent) ); } SetParent( pParent, iAttachment ); } } //----------------------------------------------------------------------------- // Purpose: Move our points from parent to worldspace // Input : *pParent - Parent to use as reference //----------------------------------------------------------------------------- void CBaseEntity::TransformStepData_ParentToWorld( CBaseEntity *pParent ) { // Fix up our step simulation points to be in the proper local space StepSimulationData *step = (StepSimulationData *) GetDataObject( STEPSIMULATION ); if ( step != NULL ) { // Convert our positions UTIL_ParentToWorldSpace( pParent, step->m_Previous2.vecOrigin, step->m_Previous2.qRotation ); UTIL_ParentToWorldSpace( pParent, step->m_Previous.vecOrigin, step->m_Previous.qRotation ); } } //----------------------------------------------------------------------------- // Purpose: Move step data between two parent-spaces // Input : *pOldParent - parent we were attached to // *pNewParent - parent we're now attached to //----------------------------------------------------------------------------- void CBaseEntity::TransformStepData_ParentToParent( CBaseEntity *pOldParent, CBaseEntity *pNewParent ) { // Fix up our step simulation points to be in the proper local space StepSimulationData *step = (StepSimulationData *) GetDataObject( STEPSIMULATION ); if ( step != NULL ) { // Convert our positions UTIL_ParentToWorldSpace( pOldParent, step->m_Previous2.vecOrigin, step->m_Previous2.qRotation ); UTIL_WorldToParentSpace( pNewParent, step->m_Previous2.vecOrigin, step->m_Previous2.qRotation ); UTIL_ParentToWorldSpace( pOldParent, step->m_Previous.vecOrigin, step->m_Previous.qRotation ); UTIL_WorldToParentSpace( pNewParent, step->m_Previous.vecOrigin, step->m_Previous.qRotation ); } } //----------------------------------------------------------------------------- // Purpose: After parenting to an object, we need to also correctly translate our // step stimulation positions and angles into that parent space. Otherwise // we end up splining between two different world spaces. //----------------------------------------------------------------------------- void CBaseEntity::TransformStepData_WorldToParent( CBaseEntity *pParent ) { // Fix up our step simulation points to be in the proper local space StepSimulationData *step = (StepSimulationData *) GetDataObject( STEPSIMULATION ); if ( step != NULL ) { // Convert our positions UTIL_WorldToParentSpace( pParent, step->m_Previous2.vecOrigin, step->m_Previous2.qRotation ); UTIL_WorldToParentSpace( pParent, step->m_Previous.vecOrigin, step->m_Previous.qRotation ); } } //----------------------------------------------------------------------------- // Purpose: Sets the movement parent of this entity. This entity will be moved // to a local coordinate calculated from its current absolute offset // from the parent entity and will then follow the parent entity. // Input : pParentEntity - This entity's new parent in the movement hierarchy. //----------------------------------------------------------------------------- void CBaseEntity::SetParent( CBaseEntity *pParentEntity, int iAttachment ) { // If they didn't specify an attachment, use our current if ( iAttachment == -1 ) { iAttachment = m_iParentAttachment; } bool bWasNotParented = ( GetParent() == NULL ); CBaseEntity *pOldParent = m_pParent; // notify the old parent of the loss UnlinkFromParent( this ); // set the new name m_pParent = pParentEntity; if ( m_pParent == this ) { // should never set parent to 'this' - makes no sense Assert(0); m_pParent = NULL; } if ( m_pParent == NULL ) { m_iParent = NULL_STRING; // Transform step data from parent to worldspace TransformStepData_ParentToWorld( pOldParent ); return; } m_iParent = m_pParent->m_iName; RemoveSolidFlags( FSOLID_ROOT_PARENT_ALIGNED ); if ( pParentEntity ) { if ( const_cast<CBaseEntity *>(pParentEntity)->GetRootMoveParent()->GetSolid() == SOLID_BSP ) { AddSolidFlags( FSOLID_ROOT_PARENT_ALIGNED ); } else { if ( GetSolid() == SOLID_BSP ) { // Must be SOLID_VPHYSICS because parent might rotate SetSolid( SOLID_VPHYSICS ); } } } // set the move parent if we have one if ( edict() ) { // add ourselves to the list LinkChild( m_pParent, this ); m_iParentAttachment = (char)iAttachment; EntityMatrix matrix, childMatrix; matrix.InitFromEntity( const_cast<CBaseEntity *>(pParentEntity), m_iParentAttachment ); // parent->world childMatrix.InitFromEntityLocal( this ); // child->world Vector localOrigin = matrix.WorldToLocal( GetLocalOrigin() ); // I have the axes of local space in world space. (childMatrix) // I want to compute those world space axes in the parent's local space // and set that transform (as angles) on the child's object so the net // result is that the child is now in parent space, but still oriented the same way VMatrix tmp = matrix.Transpose(); // world->parent tmp.MatrixMul( childMatrix, matrix ); // child->parent QAngle angles; MatrixToAngles( matrix, angles ); SetLocalAngles( angles ); UTIL_SetOrigin( this, localOrigin ); // Move our step data into the correct space if ( bWasNotParented ) { // Transform step data from world to parent-space TransformStepData_WorldToParent( this ); } else { // Transform step data between parent-spaces TransformStepData_ParentToParent( pOldParent, this ); } } if ( VPhysicsGetObject() ) { if ( VPhysicsGetObject()->IsStatic()) { if ( VPhysicsGetObject()->IsAttachedToConstraint(false) ) { Warning("SetParent on static object, all constraints attached to %s (%s)will now be broken!\n", GetDebugName(), GetClassname() ); } VPhysicsDestroyObject(); VPhysicsInitShadow(false, false); } } CollisionRulesChanged(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseEntity::ValidateEntityConnections() { if ( m_target == NULL_STRING ) return; if ( ClassMatches( "scripted_*" ) || ClassMatches( "trigger_relay" ) || ClassMatches( "trigger_auto" ) || ClassMatches( "path_*" ) || ClassMatches( "monster_*" ) || ClassMatches( "trigger_teleport" ) || ClassMatches( "func_train" ) || ClassMatches( "func_tracktrain" ) || ClassMatches( "func_plat*" ) || ClassMatches( "npc_*" ) || ClassMatches( "info_big*" ) || ClassMatches( "env_texturetoggle" ) || ClassMatches( "env_render" ) || ClassMatches( "func_areaportalwindow") || ClassMatches( "point_view*") || ClassMatches( "func_traincontrols" ) || ClassMatches( "multisource" ) || ClassMatches( "xen_plant*" ) ) return; datamap_t *dmap = GetDataDescMap(); while ( dmap ) { int fields = dmap->dataNumFields; for ( int i = 0; i < fields; i++ ) { typedescription_t *dataDesc = &dmap->dataDesc[i]; if ( ( dataDesc->fieldType == FIELD_CUSTOM ) && ( dataDesc->flags & FTYPEDESC_OUTPUT ) ) { CBaseEntityOutput *pOutput = (CBaseEntityOutput *)((int)this + (int)dataDesc->fieldOffset[0]); if ( pOutput->NumberOfElements() ) return; } } dmap = dmap->baseMap; } Vector vecLoc = WorldSpaceCenter(); Warning("---------------------------------\n"); Warning( "Entity %s - (%s) has a target and NO OUTPUTS\n", GetDebugName(), GetClassname() ); Warning( "Location %f %f %f\n", vecLoc.x, vecLoc.y, vecLoc.z ); Warning("---------------------------------\n"); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseEntity::FireNamedOutput( const char *pszOutput, variant_t variant, CBaseEntity *pActivator, CBaseEntity *pCaller, float flDelay ) { if ( pszOutput == NULL ) return; datamap_t *dmap = GetDataDescMap(); while ( dmap ) { int fields = dmap->dataNumFields; for ( int i = 0; i < fields; i++ ) { typedescription_t *dataDesc = &dmap->dataDesc[i]; if ( ( dataDesc->fieldType == FIELD_CUSTOM ) && ( dataDesc->flags & FTYPEDESC_OUTPUT ) ) { CBaseEntityOutput *pOutput = ( CBaseEntityOutput * )( ( int )this + ( int )dataDesc->fieldOffset[0] ); if ( !Q_stricmp( dataDesc->externalName, pszOutput ) ) { pOutput->FireOutput( variant, pActivator, pCaller, flDelay ); return; } } } dmap = dmap->baseMap; } } void CBaseEntity::Activate( void ) { #ifdef DEBUG extern bool g_bCheckForChainedActivate; extern bool g_bReceivedChainedActivate; if ( g_bCheckForChainedActivate && g_bReceivedChainedActivate ) { Assert( !"Multiple calls to base class Activate()\n" ); } g_bReceivedChainedActivate = true; #endif // NOTE: This forces a team change so that stuff in the level // that starts out on a team correctly changes team if (m_iInitialTeamNum) { ChangeTeam( m_iInitialTeamNum ); } // Get a handle to my damage filter entity if there is one. if ( m_iszDamageFilterName != NULL_STRING ) { m_hDamageFilter = gEntList.FindEntityByName( NULL, m_iszDamageFilterName ); } // Add any non-null context strings to our context vector if ( m_iszResponseContext != NULL_STRING ) { AddContext( m_iszResponseContext.ToCStr() ); } #ifdef HL1_DLL ValidateEntityConnections(); #endif //HL1_DLL } //////////////////////////// old CBaseEntity stuff /////////////////////////////////// // give health. // Returns the amount of health actually taken. int CBaseEntity::TakeHealth( float flHealth, int bitsDamageType ) { if ( !edict() || m_takedamage < DAMAGE_YES ) return 0; int iMax = GetMaxHealth(); // heal if ( m_iHealth >= iMax ) return 0; const int oldHealth = m_iHealth; m_iHealth += flHealth; if (m_iHealth > iMax) m_iHealth = iMax; return m_iHealth - oldHealth; } // inflict damage on this entity. bitsDamageType indicates type of damage inflicted, ie: DMG_CRUSH int CBaseEntity::OnTakeDamage( const CTakeDamageInfo &info ) { Vector vecTemp; if ( !edict() || !m_takedamage ) return 0; if ( info.GetInflictor() ) { vecTemp = info.GetInflictor()->WorldSpaceCenter() - ( WorldSpaceCenter() ); } else { vecTemp.Init( 1, 0, 0 ); } // this global is still used for glass and other non-NPC killables, along with decals. g_vecAttackDir = vecTemp; VectorNormalize(g_vecAttackDir); // save damage based on the target's armor level // figure momentum add (don't let hurt brushes or other triggers move player) // physics objects have their own calcs for this: (don't let fire move things around!) if ( !IsEFlagSet( EFL_NO_DAMAGE_FORCES ) ) { if ( ( GetMoveType() == MOVETYPE_VPHYSICS ) ) { VPhysicsTakeDamage( info ); } else { if ( info.GetInflictor() && (GetMoveType() == MOVETYPE_WALK || GetMoveType() == MOVETYPE_STEP) && !info.GetAttacker()->IsSolidFlagSet(FSOLID_TRIGGER) ) { Vector vecDir, vecInflictorCentroid; vecDir = WorldSpaceCenter( ); vecInflictorCentroid = info.GetInflictor()->WorldSpaceCenter( ); vecDir -= vecInflictorCentroid; VectorNormalize( vecDir ); float flForce = info.GetDamage() * ((32 * 32 * 72.0) / (WorldAlignSize().x * WorldAlignSize().y * WorldAlignSize().z)) * 5; if (flForce > 1000.0) flForce = 1000.0; ApplyAbsVelocityImpulse( vecDir * flForce ); } } } if ( m_takedamage != DAMAGE_EVENTS_ONLY ) { // do the damage m_iHealth -= info.GetDamage(); if (m_iHealth <= 0) { Event_Killed( info ); return 0; } } return 1; } //----------------------------------------------------------------------------- // Purpose: Scale damage done and call OnTakeDamage //----------------------------------------------------------------------------- void CBaseEntity::TakeDamage( const CTakeDamageInfo &inputInfo ) { if ( !g_pGameRules ) return; bool bHasPhysicsForceDamage = !g_pGameRules->Damage_NoPhysicsForce( inputInfo.GetDamageType() ); if ( bHasPhysicsForceDamage && inputInfo.GetDamageType() != DMG_GENERIC ) { // If you hit this assert, you've called TakeDamage with a damage type that requires a physics damage // force & position without specifying one or both of them. Decide whether your damage that's causing // this is something you believe should impart physics force on the receiver. If it is, you need to // setup the damage force & position inside the CTakeDamageInfo (Utility functions for this are in // takedamageinfo.cpp. If you think the damage shouldn't cause force (unlikely!) then you can set the // damage type to DMG_GENERIC, or | DMG_CRUSH if you need to preserve the damage type for purposes of HUD display. if ( inputInfo.GetDamageForce() == vec3_origin || inputInfo.GetDamagePosition() == vec3_origin ) { static int warningCount = 0; if ( ++warningCount < 10 ) { if ( inputInfo.GetDamageForce() == vec3_origin ) { DevWarning( "CBaseEntity::TakeDamage: with inputInfo.GetDamageForce() == vec3_origin\n" ); } if ( inputInfo.GetDamagePosition() == vec3_origin ) { DevWarning( "CBaseEntity::TakeDamage: with inputInfo.GetDamagePosition() == vec3_origin\n" ); } } } } // Make sure our damage filter allows the damage. if ( !PassesDamageFilter( inputInfo )) { return; } if( !g_pGameRules->AllowDamage(this, inputInfo) ) { return; } if ( PhysIsInCallback() ) { PhysCallbackDamage( this, inputInfo ); } else { CTakeDamageInfo info = inputInfo; // Scale the damage by the attacker's modifier. if ( info.GetAttacker() ) { info.ScaleDamage( info.GetAttacker()->GetAttackDamageScale( this ) ); } // Scale the damage by my own modifiers info.ScaleDamage( GetReceivedDamageScale( info.GetAttacker() ) ); //Msg("%s took %.2f Damage, at %.2f\n", GetClassname(), info.GetDamage(), gpGlobals->curtime ); OnTakeDamage( info ); } } //----------------------------------------------------------------------------- // Purpose: Returns a value that scales all damage done by this entity. //----------------------------------------------------------------------------- float CBaseEntity::GetAttackDamageScale( CBaseEntity *pVictim ) { float flScale = 1; FOR_EACH_LL( m_DamageModifiers, i ) { if ( !m_DamageModifiers[i]->IsDamageDoneToMe() ) { flScale *= m_DamageModifiers[i]->GetModifier(); } } return flScale; } //----------------------------------------------------------------------------- // Purpose: Returns a value that scales all damage done to this entity //----------------------------------------------------------------------------- float CBaseEntity::GetReceivedDamageScale( CBaseEntity *pAttacker ) { float flScale = 1; FOR_EACH_LL( m_DamageModifiers, i ) { if ( m_DamageModifiers[i]->IsDamageDoneToMe() ) { flScale *= m_DamageModifiers[i]->GetModifier(); } } return flScale; } //----------------------------------------------------------------------------- // Purpose: Applies forces to our physics object in response to damage. //----------------------------------------------------------------------------- int CBaseEntity::VPhysicsTakeDamage( const CTakeDamageInfo &info ) { // don't let physics impacts or fire cause objects to move (again) bool bNoPhysicsForceDamage = g_pGameRules->Damage_NoPhysicsForce( info.GetDamageType() ); if ( bNoPhysicsForceDamage || info.GetDamageType() == DMG_GENERIC ) return 1; Assert(VPhysicsGetObject() != NULL); if ( VPhysicsGetObject() ) { Vector force = info.GetDamageForce(); Vector offset = info.GetDamagePosition(); // If you hit this assert, you've called TakeDamage with a damage type that requires a physics damage // force & position without specifying one or both of them. Decide whether your damage that's causing // this is something you believe should impart physics force on the receiver. If it is, you need to // setup the damage force & position inside the CTakeDamageInfo (Utility functions for this are in // takedamageinfo.cpp. If you think the damage shouldn't cause force (unlikely!) then you can set the // damage type to DMG_GENERIC, or | DMG_CRUSH if you need to preserve the damage type for purposes of HUD display. #if !defined( TF_DLL ) Assert( force != vec3_origin && offset != vec3_origin ); #else // this was spamming the console for Payload maps in TF (trigger_hurt entity on the front of the cart) if ( !TFGameRules() || TFGameRules()->GetGameType() != TF_GAMETYPE_ESCORT ) { Assert( force != vec3_origin && offset != vec3_origin ); } #endif unsigned short gameFlags = VPhysicsGetObject()->GetGameFlags(); if ( gameFlags & FVPHYSICS_PLAYER_HELD ) { // if the player is holding the object, use it's real mass (player holding reduced the mass) CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer ) { float mass = pPlayer->GetHeldObjectMass( VPhysicsGetObject() ); if ( mass != 0.0f ) { float ratio = VPhysicsGetObject()->GetMass() / mass; force *= ratio; } } } else if ( (gameFlags & FVPHYSICS_PART_OF_RAGDOLL) && (gameFlags & FVPHYSICS_CONSTRAINT_STATIC) ) { IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT]; int count = VPhysicsGetObjectList( pList, ARRAYSIZE(pList) ); for ( int i = 0; i < count; i++ ) { if ( !(pList[i]->GetGameFlags() & FVPHYSICS_CONSTRAINT_STATIC) ) { pList[i]->ApplyForceOffset( force, offset ); return 1; } } } VPhysicsGetObject()->ApplyForceOffset( force, offset ); } return 1; } // Character killed (only fired once) void CBaseEntity::Event_Killed( const CTakeDamageInfo &info ) { if( info.GetAttacker() ) { info.GetAttacker()->Event_KilledOther(this, info); } m_takedamage = DAMAGE_NO; m_lifeState = LIFE_DEAD; UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: helper method to send a game event when this entity is killed. Note: // gets called specifically for particular entities (mostly NPC), this // does not get called for every entity //----------------------------------------------------------------------------- void CBaseEntity::SendOnKilledGameEvent( const CTakeDamageInfo &info ) { IGameEvent *event = gameeventmanager->CreateEvent( "entity_killed" ); if ( event ) { event->SetInt( "entindex_killed", entindex() ); if ( info.GetAttacker()) { event->SetInt( "entindex_attacker", info.GetAttacker()->entindex() ); } if ( info.GetInflictor()) { event->SetInt( "entindex_inflictor", info.GetInflictor()->entindex() ); } event->SetInt( "damagebits", info.GetDamageType() ); gameeventmanager->FireEvent( event ); } } bool CBaseEntity::HasTarget( string_t targetname ) { if( targetname != NULL_STRING && m_target != NULL_STRING ) return FStrEq(STRING(targetname), STRING(m_target) ); else return false; } CBaseEntity *CBaseEntity::GetNextTarget( void ) { if ( !m_target ) return NULL; return gEntList.FindEntityByName( NULL, m_target ); } class CThinkContextsSaveDataOps : public CDefSaveRestoreOps { virtual void Save( const SaveRestoreFieldInfo_t &fieldInfo, ISave *pSave ) { AssertMsg( fieldInfo.pTypeDesc->fieldSize == 1, "CThinkContextsSaveDataOps does not support arrays"); // Write out the vector CUtlVector< thinkfunc_t > *pUtlVector = (CUtlVector< thinkfunc_t > *)fieldInfo.pField; SaveUtlVector( pSave, pUtlVector, FIELD_EMBEDDED ); // Get our owner CBaseEntity *pOwner = (CBaseEntity*)fieldInfo.pOwner; pSave->StartBlock(); // Now write out all the functions for ( int i = 0; i < pUtlVector->Size(); i++ ) { #ifdef WIN32 void **ppV = (void**)&((*pUtlVector)[i].m_pfnThink); #else BASEPTR *ppV = &((*pUtlVector)[i].m_pfnThink); #endif bool bHasFunc = (*ppV != NULL); pSave->WriteBool( &bHasFunc, 1 ); if ( bHasFunc ) { pSave->WriteFunction( pOwner->GetDataDescMap(), "m_pfnThink", (inputfunc_t **)ppV, 1 ); } } pSave->EndBlock(); } virtual void Restore( const SaveRestoreFieldInfo_t &fieldInfo, IRestore *pRestore ) { AssertMsg( fieldInfo.pTypeDesc->fieldSize == 1, "CThinkContextsSaveDataOps does not support arrays"); // Read in the vector CUtlVector< thinkfunc_t > *pUtlVector = (CUtlVector< thinkfunc_t > *)fieldInfo.pField; RestoreUtlVector( pRestore, pUtlVector, FIELD_EMBEDDED ); // Get our owner CBaseEntity *pOwner = (CBaseEntity*)fieldInfo.pOwner; pRestore->StartBlock(); // Now read in all the functions for ( int i = 0; i < pUtlVector->Size(); i++ ) { bool bHasFunc; pRestore->ReadBool( &bHasFunc, 1 ); #ifdef WIN32 void **ppV = (void**)&((*pUtlVector)[i].m_pfnThink); #else BASEPTR *ppV = &((*pUtlVector)[i].m_pfnThink); Q_memset( (void *)ppV, 0x0, sizeof(inputfunc_t) ); #endif if ( bHasFunc ) { SaveRestoreRecordHeader_t header; pRestore->ReadHeader( &header ); pRestore->ReadFunction( pOwner->GetDataDescMap(), (inputfunc_t **)ppV, 1, header.size ); } else { *ppV = NULL; } } pRestore->EndBlock(); } virtual bool IsEmpty( const SaveRestoreFieldInfo_t &fieldInfo ) { CUtlVector< thinkfunc_t > *pUtlVector = (CUtlVector< thinkfunc_t > *)fieldInfo.pField; return ( pUtlVector->Count() == 0 ); } virtual void MakeEmpty( const SaveRestoreFieldInfo_t &fieldInfo ) { BASEPTR pFunc = *((BASEPTR*)fieldInfo.pField); pFunc = NULL; } }; CThinkContextsSaveDataOps g_ThinkContextsSaveDataOps; ISaveRestoreOps *thinkcontextFuncs = &g_ThinkContextsSaveDataOps; BEGIN_SIMPLE_DATADESC( thinkfunc_t ) DEFINE_FIELD( m_iszContext, FIELD_STRING ), // DEFINE_FIELD( m_pfnThink, FIELD_FUNCTION ), // Manually written DEFINE_FIELD( m_nNextThinkTick, FIELD_TICK ), DEFINE_FIELD( m_nLastThinkTick, FIELD_TICK ), END_DATADESC() BEGIN_SIMPLE_DATADESC( ResponseContext_t ) DEFINE_FIELD( m_iszName, FIELD_STRING ), DEFINE_FIELD( m_iszValue, FIELD_STRING ), DEFINE_FIELD( m_fExpirationTime, FIELD_TIME ), END_DATADESC() BEGIN_DATADESC_NO_BASE( CBaseEntity ) DEFINE_KEYFIELD( m_iClassname, FIELD_STRING, "classname" ), DEFINE_GLOBAL_KEYFIELD( m_iGlobalname, FIELD_STRING, "globalname" ), DEFINE_KEYFIELD( m_iParent, FIELD_STRING, "parentname" ), DEFINE_KEYFIELD( m_iHammerID, FIELD_INTEGER, "hammerid" ), // save ID numbers so that entities can be tracked between save/restore and vmf DEFINE_KEYFIELD( m_flSpeed, FIELD_FLOAT, "speed" ), DEFINE_KEYFIELD( m_nRenderFX, FIELD_CHARACTER, "renderfx" ), DEFINE_KEYFIELD( m_nRenderMode, FIELD_CHARACTER, "rendermode" ), // Consider moving to CBaseAnimating? DEFINE_FIELD( m_flPrevAnimTime, FIELD_TIME ), DEFINE_FIELD( m_flAnimTime, FIELD_TIME ), DEFINE_FIELD( m_flSimulationTime, FIELD_TIME ), DEFINE_FIELD( m_nLastThinkTick, FIELD_TICK ), DEFINE_KEYFIELD( m_nNextThinkTick, FIELD_TICK, "nextthink" ), DEFINE_KEYFIELD( m_fEffects, FIELD_INTEGER, "effects" ), DEFINE_KEYFIELD( m_clrRender, FIELD_COLOR32, "rendercolor" ), DEFINE_GLOBAL_KEYFIELD( m_nModelIndex, FIELD_SHORT, "modelindex" ), #if !defined( NO_ENTITY_PREDICTION ) // DEFINE_FIELD( m_PredictableID, CPredictableId ), #endif DEFINE_FIELD( touchStamp, FIELD_INTEGER ), DEFINE_CUSTOM_FIELD( m_aThinkFunctions, thinkcontextFuncs ), // m_iCurrentThinkContext (not saved, debug field only, and think transient to boot) DEFINE_UTLVECTOR(m_ResponseContexts, FIELD_EMBEDDED), DEFINE_KEYFIELD( m_iszResponseContext, FIELD_STRING, "ResponseContext" ), DEFINE_FIELD( m_pfnThink, FIELD_FUNCTION ), DEFINE_FIELD( m_pfnTouch, FIELD_FUNCTION ), DEFINE_FIELD( m_pfnUse, FIELD_FUNCTION ), DEFINE_FIELD( m_pfnBlocked, FIELD_FUNCTION ), DEFINE_FIELD( m_pfnMoveDone, FIELD_FUNCTION ), DEFINE_FIELD( m_lifeState, FIELD_CHARACTER ), DEFINE_FIELD( m_takedamage, FIELD_CHARACTER ), DEFINE_KEYFIELD( m_iMaxHealth, FIELD_INTEGER, "max_health" ), DEFINE_KEYFIELD( m_iHealth, FIELD_INTEGER, "health" ), // DEFINE_FIELD( m_pLink, FIELD_CLASSPTR ), DEFINE_KEYFIELD( m_target, FIELD_STRING, "target" ), DEFINE_KEYFIELD( m_iszDamageFilterName, FIELD_STRING, "damagefilter" ), DEFINE_FIELD( m_hDamageFilter, FIELD_EHANDLE ), DEFINE_FIELD( m_debugOverlays, FIELD_INTEGER ), DEFINE_GLOBAL_FIELD( m_pParent, FIELD_EHANDLE ), DEFINE_FIELD( m_iParentAttachment, FIELD_CHARACTER ), DEFINE_GLOBAL_FIELD( m_hMoveParent, FIELD_EHANDLE ), DEFINE_GLOBAL_FIELD( m_hMoveChild, FIELD_EHANDLE ), DEFINE_GLOBAL_FIELD( m_hMovePeer, FIELD_EHANDLE ), DEFINE_FIELD( m_iEFlags, FIELD_INTEGER ), DEFINE_FIELD( m_iName, FIELD_STRING ), DEFINE_EMBEDDED( m_Collision ), DEFINE_EMBEDDED( m_Network ), DEFINE_FIELD( m_MoveType, FIELD_CHARACTER ), DEFINE_FIELD( m_MoveCollide, FIELD_CHARACTER ), DEFINE_FIELD( m_hOwnerEntity, FIELD_EHANDLE ), DEFINE_FIELD( m_CollisionGroup, FIELD_INTEGER ), DEFINE_PHYSPTR( m_pPhysicsObject), DEFINE_FIELD( m_flElasticity, FIELD_FLOAT ), DEFINE_KEYFIELD( m_flShadowCastDistance, FIELD_FLOAT, "shadowcastdist" ), DEFINE_FIELD( m_flDesiredShadowCastDistance, FIELD_FLOAT ), DEFINE_INPUT( m_iInitialTeamNum, FIELD_INTEGER, "TeamNum" ), DEFINE_FIELD( m_iTeamNum, FIELD_INTEGER ), // DEFINE_FIELD( m_bSentLastFrame, FIELD_INTEGER ), DEFINE_FIELD( m_hGroundEntity, FIELD_EHANDLE ), DEFINE_FIELD( m_flGroundChangeTime, FIELD_TIME ), DEFINE_GLOBAL_KEYFIELD( m_ModelName, FIELD_MODELNAME, "model" ), DEFINE_KEYFIELD( m_vecBaseVelocity, FIELD_VECTOR, "basevelocity" ), DEFINE_FIELD( m_vecAbsVelocity, FIELD_VECTOR ), DEFINE_KEYFIELD( m_vecAngVelocity, FIELD_VECTOR, "avelocity" ), // DEFINE_FIELD( m_vecAbsAngVelocity, FIELD_VECTOR ), DEFINE_ARRAY( m_rgflCoordinateFrame, FIELD_FLOAT, 12 ), // NOTE: MUST BE IN LOCAL SPACE, NOT POSITION_VECTOR!!! (see CBaseEntity::Restore) DEFINE_KEYFIELD( m_nWaterLevel, FIELD_CHARACTER, "waterlevel" ), DEFINE_FIELD( m_nWaterType, FIELD_CHARACTER ), DEFINE_FIELD( m_pBlocker, FIELD_EHANDLE ), DEFINE_KEYFIELD( m_flGravity, FIELD_FLOAT, "gravity" ), DEFINE_KEYFIELD( m_flFriction, FIELD_FLOAT, "friction" ), // Local time is local to each object. It doesn't need to be re-based if the clock // changes. Therefore it is saved as a FIELD_FLOAT, not a FIELD_TIME DEFINE_KEYFIELD( m_flLocalTime, FIELD_FLOAT, "ltime" ), DEFINE_FIELD( m_flVPhysicsUpdateLocalTime, FIELD_FLOAT ), DEFINE_FIELD( m_flMoveDoneTime, FIELD_FLOAT ), // DEFINE_FIELD( m_nPushEnumCount, FIELD_INTEGER ), DEFINE_FIELD( m_vecAbsOrigin, FIELD_POSITION_VECTOR ), DEFINE_KEYFIELD( m_vecVelocity, FIELD_VECTOR, "velocity" ), DEFINE_KEYFIELD( m_iTextureFrameIndex, FIELD_CHARACTER, "texframeindex" ), DEFINE_FIELD( m_bSimulatedEveryTick, FIELD_BOOLEAN ), DEFINE_FIELD( m_bAnimatedEveryTick, FIELD_BOOLEAN ), DEFINE_FIELD( m_bAlternateSorting, FIELD_BOOLEAN ), DEFINE_KEYFIELD( m_spawnflags, FIELD_INTEGER, "spawnflags" ), DEFINE_FIELD( m_nTransmitStateOwnedCounter, FIELD_CHARACTER ), DEFINE_FIELD( m_angAbsRotation, FIELD_VECTOR ), DEFINE_FIELD( m_vecOrigin, FIELD_VECTOR ), // NOTE: MUST BE IN LOCAL SPACE, NOT POSITION_VECTOR!!! (see CBaseEntity::Restore) DEFINE_FIELD( m_angRotation, FIELD_VECTOR ), DEFINE_KEYFIELD( m_vecViewOffset, FIELD_VECTOR, "view_ofs" ), DEFINE_FIELD( m_fFlags, FIELD_INTEGER ), #if !defined( NO_ENTITY_PREDICTION ) // DEFINE_FIELD( m_bIsPlayerSimulated, FIELD_INTEGER ), // DEFINE_FIELD( m_hPlayerSimulationOwner, FIELD_EHANDLE ), #endif // DEFINE_FIELD( m_pTimedOverlay, TimedOverlay_t* ), DEFINE_FIELD( m_nSimulationTick, FIELD_TICK ), // DEFINE_FIELD( m_RefEHandle, CBaseHandle ), // DEFINE_FIELD( m_nWaterTouch, FIELD_INTEGER ), // DEFINE_FIELD( m_nSlimeTouch, FIELD_INTEGER ), DEFINE_FIELD( m_flNavIgnoreUntilTime, FIELD_TIME ), // DEFINE_FIELD( m_bToolRecording, FIELD_BOOLEAN ), // DEFINE_FIELD( m_ToolHandle, FIELD_INTEGER ), // NOTE: This is tricky. TeamNum must be saved, but we can't directly // read it in, because we can only set it after the team entity has been read in, // which may or may not actually occur before the entity is parsed. // Therefore, we set the TeamNum from the InitialTeamNum in Activate DEFINE_INPUTFUNC( FIELD_INTEGER, "SetTeam", InputSetTeam ), DEFINE_INPUTFUNC( FIELD_VOID, "Kill", InputKill ), DEFINE_INPUTFUNC( FIELD_VOID, "KillHierarchy", InputKillHierarchy ), DEFINE_INPUTFUNC( FIELD_VOID, "Use", InputUse ), DEFINE_INPUTFUNC( FIELD_INTEGER, "Alpha", InputAlpha ), DEFINE_INPUTFUNC( FIELD_BOOLEAN, "AlternativeSorting", InputAlternativeSorting ), DEFINE_INPUTFUNC( FIELD_COLOR32, "Color", InputColor ), DEFINE_INPUTFUNC( FIELD_STRING, "SetParent", InputSetParent ), DEFINE_INPUTFUNC( FIELD_STRING, "SetParentAttachment", InputSetParentAttachment ), DEFINE_INPUTFUNC( FIELD_STRING, "SetParentAttachmentMaintainOffset", InputSetParentAttachmentMaintainOffset ), DEFINE_INPUTFUNC( FIELD_VOID, "ClearParent", InputClearParent ), DEFINE_INPUTFUNC( FIELD_STRING, "SetDamageFilter", InputSetDamageFilter ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableDamageForces", InputEnableDamageForces ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableDamageForces", InputDisableDamageForces ), DEFINE_INPUTFUNC( FIELD_STRING, "DispatchEffect", InputDispatchEffect ), DEFINE_INPUTFUNC( FIELD_STRING, "DispatchResponse", InputDispatchResponse ), // Entity I/O methods to alter context DEFINE_INPUTFUNC( FIELD_STRING, "AddContext", InputAddContext ), DEFINE_INPUTFUNC( FIELD_STRING, "RemoveContext", InputRemoveContext ), DEFINE_INPUTFUNC( FIELD_STRING, "ClearContext", InputClearContext ), DEFINE_INPUTFUNC( FIELD_VOID, "DisableShadow", InputDisableShadow ), DEFINE_INPUTFUNC( FIELD_VOID, "EnableShadow", InputEnableShadow ), DEFINE_INPUTFUNC( FIELD_STRING, "AddOutput", InputAddOutput ), DEFINE_INPUTFUNC( FIELD_STRING, "FireUser1", InputFireUser1 ), DEFINE_INPUTFUNC( FIELD_STRING, "FireUser2", InputFireUser2 ), DEFINE_INPUTFUNC( FIELD_STRING, "FireUser3", InputFireUser3 ), DEFINE_INPUTFUNC( FIELD_STRING, "FireUser4", InputFireUser4 ), DEFINE_OUTPUT( m_OnUser1, "OnUser1" ), DEFINE_OUTPUT( m_OnUser2, "OnUser2" ), DEFINE_OUTPUT( m_OnUser3, "OnUser3" ), DEFINE_OUTPUT( m_OnUser4, "OnUser4" ), // Function Pointers DEFINE_FUNCTION( SUB_Remove ), DEFINE_FUNCTION( SUB_DoNothing ), DEFINE_FUNCTION( SUB_StartFadeOut ), DEFINE_FUNCTION( SUB_StartFadeOutInstant ), DEFINE_FUNCTION( SUB_FadeOut ), DEFINE_FUNCTION( SUB_Vanish ), DEFINE_FUNCTION( SUB_CallUseToggle ), DEFINE_THINKFUNC( ShadowCastDistThink ), DEFINE_FIELD( m_hEffectEntity, FIELD_EHANDLE ), //DEFINE_FIELD( m_DamageModifiers, FIELD_?? ), // can't save? // DEFINE_FIELD( m_fDataObjectTypes, FIELD_INTEGER ), #ifdef TF_DLL DEFINE_ARRAY( m_nModelIndexOverrides, FIELD_INTEGER, MAX_MODEL_INDEX_OVERRIDES ), #endif END_DATADESC() // For code error checking extern bool g_bReceivedChainedUpdateOnRemove; //----------------------------------------------------------------------------- // Purpose: Called just prior to object destruction // Entities that need to unlink themselves from other entities should do the unlinking // here rather than in their destructor. The reason why is that when the global entity list // is told to Clear(), it first takes a pass through all active entities and calls UTIL_Remove // on each such entity. Then it calls the delete function on each deleted entity in the list. // In the old code, the objects were simply destroyed in order and there was no guarantee that the // destructor of one object would not try to access another object that might already have been // destructed (especially since the entity list order is more or less random!). // NOTE: You should never call delete directly on an entity (there's an assert now), see note // at CBaseEntity::~CBaseEntity for more information. // // NOTE: You should chain to BaseClass::UpdateOnRemove after doing your own cleanup code, e.g.: // // void CDerived::UpdateOnRemove( void ) // { // ... cleanup code // ... // // BaseClass::UpdateOnRemove(); // } // // In general, this function updates global tables that need to know about entities being removed //----------------------------------------------------------------------------- void CBaseEntity::UpdateOnRemove( void ) { g_bReceivedChainedUpdateOnRemove = true; // Virtual call to shut down any looping sounds. StopLoopingSounds(); // Notifies entity listeners, etc gEntList.NotifyRemoveEntity( GetRefEHandle() ); if ( edict() ) { AddFlag( FL_KILLME ); if ( GetFlags() & FL_GRAPHED ) { /* <<TODO>> // this entity was a LinkEnt in the world node graph, so we must remove it from // the graph since we are removing it from the world. for ( int i = 0 ; i < WorldGraph.m_cLinks ; i++ ) { if ( WorldGraph.m_pLinkPool [ i ].m_pLinkEnt == pev ) { // if this link has a link ent which is the same ent that is removing itself, remove it! WorldGraph.m_pLinkPool [ i ].m_pLinkEnt = NULL; } } */ } } if ( m_iGlobalname != NULL_STRING ) { // NOTE: During level shutdown the global list will suppress this // it assumes your changing levels or the game will end // causing the whole list to be flushed GlobalEntity_SetState( m_iGlobalname, GLOBAL_DEAD ); } VPhysicsDestroyObject(); // This is only here to allow the MOVETYPE_NONE to be set without the // assertion triggering. Why do we bother setting the MOVETYPE to none here? RemoveEffects( EF_BONEMERGE ); SetMoveType(MOVETYPE_NONE); // If we have a parent, unlink from it. UnlinkFromParent( this ); // Any children still connected are orphans, mark all for delete CUtlVector<CBaseEntity *> childrenList; GetAllChildren( this, childrenList ); if ( childrenList.Count() ) { DevMsg( 2, "Warning: Deleting orphaned children of %s\n", GetClassname() ); for ( int i = childrenList.Count()-1; i >= 0; --i ) { UTIL_Remove( childrenList[i] ); } } SetGroundEntity( NULL ); if ( m_bDynamicModelPending ) { sg_DynamicLoadHandlers.Remove( this ); } if ( IsDynamicModelIndex( m_nModelIndex ) ) { modelinfo->ReleaseDynamicModel( m_nModelIndex ); // no-op if not dynamic m_nModelIndex = -1; } } //----------------------------------------------------------------------------- // capabilities //----------------------------------------------------------------------------- int CBaseEntity::ObjectCaps( void ) { #if 1 model_t *pModel = GetModel(); bool bIsBrush = ( pModel && modelinfo->GetModelType( pModel ) == mod_brush ); // We inherit our parent's use capabilities so that we can forward use commands // to our parent. CBaseEntity *pParent = GetParent(); if ( pParent ) { int caps = pParent->ObjectCaps(); if ( !bIsBrush ) caps &= ( FCAP_ACROSS_TRANSITION | FCAP_IMPULSE_USE | FCAP_CONTINUOUS_USE | FCAP_ONOFF_USE | FCAP_DIRECTIONAL_USE ); else caps &= ( FCAP_IMPULSE_USE | FCAP_CONTINUOUS_USE | FCAP_ONOFF_USE | FCAP_DIRECTIONAL_USE ); if ( pParent->IsPlayer() ) caps |= FCAP_ACROSS_TRANSITION; return caps; } else if ( !bIsBrush ) { return FCAP_ACROSS_TRANSITION; } return 0; #else // We inherit our parent's use capabilities so that we can forward use commands // to our parent. int parentCaps = 0; if (GetParent()) { parentCaps = GetParent()->ObjectCaps(); parentCaps &= ( FCAP_IMPULSE_USE | FCAP_CONTINUOUS_USE | FCAP_ONOFF_USE | FCAP_DIRECTIONAL_USE ); } model_t *pModel = GetModel(); if ( pModel && modelinfo->GetModelType( pModel ) == mod_brush ) return parentCaps; return FCAP_ACROSS_TRANSITION | parentCaps; #endif } void CBaseEntity::StartTouch( CBaseEntity *pOther ) { // notify parent if ( m_pParent != NULL ) m_pParent->StartTouch( pOther ); } void CBaseEntity::Touch( CBaseEntity *pOther ) { if ( m_pfnTouch ) (this->*m_pfnTouch)( pOther ); // notify parent of touch if ( m_pParent != NULL ) m_pParent->Touch( pOther ); } void CBaseEntity::EndTouch( CBaseEntity *pOther ) { // notify parent if ( m_pParent != NULL ) { m_pParent->EndTouch( pOther ); } } //----------------------------------------------------------------------------- // Purpose: Dispatches blocked events to this entity's blocked handler, set via SetBlocked. // Input : pOther - The entity that is blocking us. //----------------------------------------------------------------------------- void CBaseEntity::Blocked( CBaseEntity *pOther ) { if ( m_pfnBlocked ) { (this->*m_pfnBlocked)( pOther ); } // // Forward the blocked event to our parent, if any. // if ( m_pParent != NULL ) { m_pParent->Blocked( pOther ); } } //----------------------------------------------------------------------------- // Purpose: Dispatches use events to this entity's use handler, set via SetUse. // Input : pActivator - // pCaller - // useType - // value - //----------------------------------------------------------------------------- void CBaseEntity::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { if ( m_pfnUse != NULL ) { (this->*m_pfnUse)( pActivator, pCaller, useType, value ); } else { // // We don't handle use events. Forward to our parent, if any. // if ( m_pParent != NULL ) { m_pParent->Use( pActivator, pCaller, useType, value ); } } } static CBaseEntity *FindPhysicsBlocker( IPhysicsObject *pPhysics, physicspushlist_t &list, const Vector &pushVel ) { IPhysicsFrictionSnapshot *pSnapshot = pPhysics->CreateFrictionSnapshot(); CBaseEntity *pBlocker = NULL; float maxForce = 0; while ( pSnapshot->IsValid() ) { IPhysicsObject *pOther = pSnapshot->GetObject(1); CBaseEntity *pOtherEntity = static_cast<CBaseEntity *>(pOther->GetGameData()); bool inList = false; for ( int i = 0; i < list.pushedCount; i++ ) { if ( pOtherEntity == list.pushedEnts[i] ) { inList = true; break; } } Vector normal; pSnapshot->GetSurfaceNormal(normal); float dot = DotProduct( pushVel, pSnapshot->GetNormalForce() * normal ); if ( !pBlocker || (!inList && dot > maxForce) ) { pBlocker = pOtherEntity; if ( !inList ) { maxForce = dot; } } pSnapshot->NextFrictionData(); } pPhysics->DestroyFrictionSnapshot( pSnapshot ); return pBlocker; } struct pushblock_t { physicspushlist_t *pList; CBaseEntity *pRootParent; CBaseEntity *pBlockedEntity; float moveBackFraction; float movetime; }; static void ComputePushStartMatrix( matrix3x4_t &start, CBaseEntity *pEntity, const pushblock_t &params ) { Vector localOrigin; QAngle localAngles; if ( params.pList ) { localOrigin = params.pList->localOrigin; localAngles = params.pList->localAngles; } else { localOrigin = params.pRootParent->GetAbsOrigin() - params.pRootParent->GetAbsVelocity() * params.movetime; localAngles = params.pRootParent->GetAbsAngles() - params.pRootParent->GetLocalAngularVelocity() * params.movetime; } matrix3x4_t xform, delta; AngleMatrix( localAngles, localOrigin, xform ); matrix3x4_t srcInv; // xform = src(-1) * dest MatrixInvert( params.pRootParent->EntityToWorldTransform(), srcInv ); ConcatTransforms( xform, srcInv, delta ); ConcatTransforms( delta, pEntity->EntityToWorldTransform(), start ); } #define DEBUG_PUSH_MESSAGES 0 static void CheckPushedEntity( CBaseEntity *pEntity, pushblock_t &params ) { IPhysicsObject *pPhysics = pEntity->VPhysicsGetObject(); if ( !pPhysics ) return; // somehow we've got a static or motion disabled physics object in hierarchy! // This is not allowed! Don't test blocking in that case. Assert(pPhysics->IsMoveable()); if ( !pPhysics->IsMoveable() || !pPhysics->GetShadowController() ) { #if DEBUG_PUSH_MESSAGES Msg("Blocking %s, not moveable!\n", pEntity->GetClassname()); #endif return; } bool checkrot = true; bool checkmove = true; Vector origin; QAngle angles; pPhysics->GetShadowPosition( &origin, &angles ); float fraction = -1.0f; matrix3x4_t parentDelta; if ( pEntity == params.pRootParent ) { if ( pEntity->GetLocalAngularVelocity() == vec3_angle ) checkrot = false; if ( pEntity->GetLocalVelocity() == vec3_origin) checkmove = false; } else { #if DEBUG_PUSH_MESSAGES if ( pPhysics->IsAttachedToConstraint(false)) { Msg("Warning, hierarchical entity is attached to a constraint %s\n", pEntity->GetClassname()); } #endif } if ( checkmove ) { // project error onto the axis of movement Vector dir = pEntity->GetAbsVelocity(); float speed = VectorNormalize(dir); Vector targetPos; pPhysics->GetShadowController()->GetTargetPosition( &targetPos, NULL ); float targetAmount = DotProduct(targetPos, dir); float currentAmount = DotProduct(origin, dir); float entityAmount = DotProduct(pEntity->GetAbsOrigin(), dir); // if target and entity origin are not in sync, then the position of the entity was updated // by something outside of push physics if ( (targetAmount - entityAmount) > 1 ) { pEntity->UpdatePhysicsShadowToCurrentPosition(0); #if DEBUG_PUSH_MESSAGES Warning("Someone slammed the position of a %s\n", pEntity->GetClassname() ); #endif } else { float dist = targetAmount - currentAmount; if ( dist > 1 ) { #if DEBUG_PUSH_MESSAGES const char *pName = pEntity->GetClassname(); Msg( "%s blocked by %.2f units\n", pName, dist ); #endif float movementAmount = targetAmount - (speed * params.movetime); if ( pEntity == params.pRootParent ) { if ( params.pList ) { Vector localVel = pEntity->GetLocalVelocity(); VectorNormalize(localVel); float localTargetAmt = DotProduct(pEntity->GetLocalOrigin(), localVel); movementAmount = targetAmount + DotProduct(params.pList->localOrigin, localVel) - localTargetAmt; } } else { matrix3x4_t start; ComputePushStartMatrix( start, pEntity, params ); Vector startPos; MatrixPosition( start, startPos ); movementAmount = DotProduct(startPos, dir); } float expectedDist = targetAmount - movementAmount; // compute the fraction to move back the AI to match the physics if ( expectedDist <= 0 ) { fraction = 1; } else { fraction = dist / expectedDist; fraction = clamp(fraction, 0.f, 1.f); } } } } if ( checkrot ) { Vector axis; float deltaAngle; RotationDeltaAxisAngle( angles, pEntity->GetAbsAngles(), axis, deltaAngle ); if ( fabsf(deltaAngle) > 0.5f ) { Vector targetAxis; QAngle targetRot; float deltaTargetAngle; pPhysics->GetShadowController()->GetTargetPosition( NULL, &targetRot ); RotationDeltaAxisAngle( angles, targetRot, targetAxis, deltaTargetAngle ); if ( fabsf(deltaTargetAngle) > 0.01f ) { float expectedDist = deltaAngle; #if DEBUG_PUSH_MESSAGES const char *pName = pEntity->GetClassname(); Msg( "%s blocked by %.2f degrees\n", pName, deltaAngle ); if ( pPhysics->IsAsleep() ) { Msg("Asleep while blocked?\n"); } if ( pPhysics->GetGameFlags() & FVPHYSICS_PENETRATING ) { Msg("Blocking for penetration!\n"); } #endif if ( pEntity == params.pRootParent ) { expectedDist = pEntity->GetLocalAngularVelocity().Length() * params.movetime; } else { matrix3x4_t start; ComputePushStartMatrix( start, pEntity, params ); Vector startAxis; float startAngle; Vector startPos; QAngle startAngles; MatrixAngles( start, startAngles, startPos ); RotationDeltaAxisAngle( startAngles, pEntity->GetAbsAngles(), startAxis, startAngle ); expectedDist = startAngle * DotProduct( startAxis, axis ); } float t = expectedDist != 0.0f ? fabsf(deltaAngle / expectedDist) : 1.0f; t = clamp(t,0.f,1.f); fraction = MAX(fraction, t); } else { pEntity->UpdatePhysicsShadowToCurrentPosition(0); #if DEBUG_PUSH_MESSAGES Warning("Someone slammed the position of a %s\n", pEntity->GetClassname() ); #endif } } } if ( fraction >= params.moveBackFraction ) { params.moveBackFraction = fraction; params.pBlockedEntity = pEntity; } } void CBaseEntity::VPhysicsUpdatePusher( IPhysicsObject *pPhysics ) { float movetime = m_flLocalTime - m_flVPhysicsUpdateLocalTime; if (movetime <= 0) return; // only reconcile pushers on the final vphysics tick if ( !PhysIsFinalTick() ) return; Vector origin; QAngle angles; // physics updated the shadow, so check to see if I got blocked // NOTE: SOLID_BSP cannont compute consistent collisions wrt vphysics, so // don't allow vphysics to block. Assume game physics has handled it. if ( GetSolid() != SOLID_BSP && pPhysics->GetShadowPosition( &origin, &angles ) ) { CUtlVector<CBaseEntity *> list; GetAllInHierarchy( this, list ); //NDebugOverlay::BoxAngles( origin, CollisionProp()->OBBMins(), CollisionProp()->OBBMaxs(), angles, 255,0,0,0, gpGlobals->frametime); physicspushlist_t *pList = NULL; if ( HasDataObjectType(PHYSICSPUSHLIST) ) { pList = (physicspushlist_t *)GetDataObject( PHYSICSPUSHLIST ); Assert(pList); } bool checkrot = (GetLocalAngularVelocity() != vec3_angle) ? true : false; bool checkmove = (GetLocalVelocity() != vec3_origin) ? true : false; pushblock_t params; params.pRootParent = this; params.pList = pList; params.pBlockedEntity = NULL; params.moveBackFraction = 0.0f; params.movetime = movetime; for ( int i = 0; i < list.Count(); i++ ) { if ( list[i]->IsSolid() ) { CheckPushedEntity( list[i], params ); } } float physLocalTime = m_flLocalTime; if ( params.pBlockedEntity ) { float moveback = movetime * params.moveBackFraction; if ( moveback > 0 ) { physLocalTime = m_flLocalTime - moveback; // add 1% noise for bouncing in collision. if ( physLocalTime <= (m_flVPhysicsUpdateLocalTime + movetime * 0.99f) ) { CBaseEntity *pBlocked = NULL; IPhysicsObject *pOther; if ( params.pBlockedEntity->VPhysicsGetObject()->GetContactPoint( NULL, &pOther ) ) { pBlocked = static_cast<CBaseEntity *>(pOther->GetGameData()); } // UNDONE: Need to traverse hierarchy here? Shouldn't. if ( pList ) { SetLocalOrigin( pList->localOrigin ); SetLocalAngles( pList->localAngles ); physLocalTime = pList->localMoveTime; for ( int i = 0; i < pList->pushedCount; i++ ) { CBaseEntity *pEntity = pList->pushedEnts[i]; if ( !pEntity ) continue; pEntity->SetAbsOrigin( pEntity->GetAbsOrigin() - pList->pushVec[i] ); } CBaseEntity *pPhysicsBlocker = FindPhysicsBlocker( VPhysicsGetObject(), *pList, pList->pushVec[0] ); if ( pPhysicsBlocker ) { pBlocked = pPhysicsBlocker; } } else { Vector origin = GetLocalOrigin(); QAngle angles = GetLocalAngles(); if ( checkmove ) { origin -= GetLocalVelocity() * moveback; } if ( checkrot ) { // BUGBUG: This is pretty hack-tastic! angles -= GetLocalAngularVelocity() * moveback; } SetLocalOrigin( origin ); SetLocalAngles( angles ); } if ( pBlocked ) { Blocked( pBlocked ); } m_flLocalTime = physLocalTime; } } } } // this data is no longer useful, free the memory if ( HasDataObjectType(PHYSICSPUSHLIST) ) { DestroyDataObject( PHYSICSPUSHLIST ); } m_flVPhysicsUpdateLocalTime = m_flLocalTime; if ( m_flMoveDoneTime <= m_flLocalTime && m_flMoveDoneTime > 0 ) { SetMoveDoneTime( -1 ); MoveDone(); } } void CBaseEntity::SetMoveDoneTime( float flDelay ) { if (flDelay >= 0) { m_flMoveDoneTime = GetLocalTime() + flDelay; } else { m_flMoveDoneTime = -1; } CheckHasGamePhysicsSimulation(); } //----------------------------------------------------------------------------- // Purpose: Relinks all of a parents children into the collision tree //----------------------------------------------------------------------------- void CBaseEntity::PhysicsRelinkChildren( float dt ) { CBaseEntity *child; // iterate through all children for ( child = FirstMoveChild(); child != NULL; child = child->NextMovePeer() ) { if ( child->IsSolid() || child->IsSolidFlagSet(FSOLID_TRIGGER) ) { child->PhysicsTouchTriggers(); } // // Update their physics shadows. We should never have any children of // movetype VPHYSICS. // if ( child->GetMoveType() != MOVETYPE_VPHYSICS ) { child->UpdatePhysicsShadowToCurrentPosition( dt ); } else if ( child->GetOwnerEntity() != this ) { // the only case where this is valid is if this entity is an attached ragdoll. // So assert here to catch the non-ragdoll case. Assert( 0 ); } if ( child->FirstMoveChild() ) { child->PhysicsRelinkChildren(dt); } } } void CBaseEntity::PhysicsTouchTriggers( const Vector *pPrevAbsOrigin ) { edict_t *pEdict = edict(); if ( pEdict && !IsWorld() ) { Assert(CollisionProp()); bool isTriggerCheckSolids = IsSolidFlagSet( FSOLID_TRIGGER ); bool isSolidCheckTriggers = IsSolid() && !isTriggerCheckSolids; // NOTE: Moving triggers (items, ammo etc) are not // checked against other triggers to reduce the number of touchlinks created if ( !(isSolidCheckTriggers || isTriggerCheckSolids) ) return; if ( GetSolid() == SOLID_BSP ) { if ( !GetModel() && Q_strlen( STRING( GetModelName() ) ) == 0 ) { Warning( "Inserted %s with no model\n", GetClassname() ); return; } } SetCheckUntouch( true ); if ( isSolidCheckTriggers ) { engine->SolidMoved( pEdict, CollisionProp(), pPrevAbsOrigin, sm_bAccurateTriggerBboxChecks ); } if ( isTriggerCheckSolids ) { engine->TriggerMoved( pEdict, sm_bAccurateTriggerBboxChecks ); } } } void CBaseEntity::VPhysicsShadowCollision( int index, gamevcollisionevent_t *pEvent ) { } void CBaseEntity::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent ) { // filter out ragdoll props hitting other parts of itself too often // UNDONE: Store a sound time for this entity (not just this pair of objects) // and filter repeats on that? int otherIndex = !index; CBaseEntity *pHitEntity = pEvent->pEntities[otherIndex]; // Don't make sounds / effects if neither entity is MOVETYPE_VPHYSICS. The game // physics should have done so. if ( GetMoveType() != MOVETYPE_VPHYSICS && pHitEntity->GetMoveType() != MOVETYPE_VPHYSICS ) return; if ( pEvent->deltaCollisionTime < 0.5 && (pHitEntity == this) ) return; // don't make noise for hidden/invisible/sky materials surfacedata_t *phit = physprops->GetSurfaceData( pEvent->surfaceProps[otherIndex] ); const surfacedata_t *pprops = physprops->GetSurfaceData( pEvent->surfaceProps[index] ); if ( phit->game.material == 'X' || pprops->game.material == 'X' ) return; if ( pHitEntity == this ) { PhysCollisionSound( this, pEvent->pObjects[index], CHAN_BODY, pEvent->surfaceProps[index], pEvent->surfaceProps[otherIndex], pEvent->deltaCollisionTime, pEvent->collisionSpeed ); } else { PhysCollisionSound( this, pEvent->pObjects[index], CHAN_STATIC, pEvent->surfaceProps[index], pEvent->surfaceProps[otherIndex], pEvent->deltaCollisionTime, pEvent->collisionSpeed ); } PhysCollisionScreenShake( pEvent, index ); #if HL2_EPISODIC // episodic does something different for when advisor shields are struck if ( phit->game.material == 'Z' || pprops->game.material == 'Z') { PhysCollisionWarpEffect( pEvent, phit ); } else { PhysCollisionDust( pEvent, phit ); } #else PhysCollisionDust( pEvent, phit ); #endif } void CBaseEntity::VPhysicsFriction( IPhysicsObject *pObject, float energy, int surfaceProps, int surfacePropsHit ) { PhysFrictionSound( this, pObject, energy, surfaceProps, surfacePropsHit ); } void CBaseEntity::VPhysicsSwapObject( IPhysicsObject *pSwap ) { if ( !pSwap ) { PhysRemoveShadow(this); } if ( !m_pPhysicsObject ) { Warning( "Bad vphysics swap for %s\n", STRING(m_iClassname) ); } m_pPhysicsObject = pSwap; } // Tells the physics shadow to update it's target to the current position void CBaseEntity::UpdatePhysicsShadowToCurrentPosition( float deltaTime ) { if ( GetMoveType() != MOVETYPE_VPHYSICS ) { IPhysicsObject *pPhys = VPhysicsGetObject(); if ( pPhys ) { pPhys->UpdateShadow( GetAbsOrigin(), GetAbsAngles(), false, deltaTime ); } } } int CBaseEntity::VPhysicsGetObjectList( IPhysicsObject **pList, int listMax ) { IPhysicsObject *pPhys = VPhysicsGetObject(); if ( pPhys ) { // multi-object entities must implement this function Assert( !(pPhys->GetGameFlags() & FVPHYSICS_MULTIOBJECT_ENTITY) ); if ( listMax > 0 ) { pList[0] = pPhys; return 1; } } return 0; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- bool CBaseEntity::VPhysicsIsFlesh( void ) { IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT]; int count = VPhysicsGetObjectList( pList, ARRAYSIZE(pList) ); for ( int i = 0; i < count; i++ ) { int material = pList[i]->GetMaterialIndex(); const surfacedata_t *pSurfaceData = physprops->GetSurfaceData( material ); // Is flesh ?, don't allow pickup if ( pSurfaceData->game.material == CHAR_TEX_ANTLION || pSurfaceData->game.material == CHAR_TEX_FLESH || pSurfaceData->game.material == CHAR_TEX_BLOODYFLESH || pSurfaceData->game.material == CHAR_TEX_ALIENFLESH ) return true; } return false; } bool CBaseEntity::Intersects( CBaseEntity *pOther ) { if ( !edict() || !pOther->edict() ) return false; CCollisionProperty *pMyProp = CollisionProp(); CCollisionProperty *pOtherProp = pOther->CollisionProp(); return IsOBBIntersectingOBB( pMyProp->GetCollisionOrigin(), pMyProp->GetCollisionAngles(), pMyProp->OBBMins(), pMyProp->OBBMaxs(), pOtherProp->GetCollisionOrigin(), pOtherProp->GetCollisionAngles(), pOtherProp->OBBMins(), pOtherProp->OBBMaxs() ); } extern ConVar ai_LOS_mode; //========================================================= // FVisible - returns true if a line can be traced from // the caller's eyes to the target //========================================================= bool CBaseEntity::FVisible( CBaseEntity *pEntity, int traceMask, CBaseEntity **ppBlocker ) { VPROF( "CBaseEntity::FVisible" ); if ( pEntity->GetFlags() & FL_NOTARGET ) return false; #if HL1_DLL // FIXME: only block LOS through opaque water // don't look through water if ((m_nWaterLevel != 3 && pEntity->m_nWaterLevel == 3) || (m_nWaterLevel == 3 && pEntity->m_nWaterLevel == 0)) return false; #endif Vector vecLookerOrigin = EyePosition();//look through the caller's 'eyes' Vector vecTargetOrigin = pEntity->EyePosition(); trace_t tr; if ( !IsXbox() && ai_LOS_mode.GetBool() ) { UTIL_TraceLine(vecLookerOrigin, vecTargetOrigin, traceMask, this, COLLISION_GROUP_NONE, &tr); } else { // If we're doing an LOS search, include NPCs. if ( traceMask == MASK_BLOCKLOS ) { traceMask = MASK_BLOCKLOS_AND_NPCS; } // Player sees through nodraw if ( IsPlayer() ) { traceMask &= ~CONTENTS_BLOCKLOS; } // Use the custom LOS trace filter CTraceFilterLOS traceFilter( this, COLLISION_GROUP_NONE, pEntity ); UTIL_TraceLine( vecLookerOrigin, vecTargetOrigin, traceMask, &traceFilter, &tr ); } if (tr.fraction != 1.0 || tr.startsolid ) { // If we hit the entity we're looking for, it's visible if ( tr.m_pEnt == pEntity ) return true; // Got line of sight on the vehicle the player is driving! if ( pEntity && pEntity->IsPlayer() ) { CBasePlayer *pPlayer = assert_cast<CBasePlayer*>( pEntity ); if ( tr.m_pEnt == pPlayer->GetVehicleEntity() ) return true; } if (ppBlocker) { *ppBlocker = tr.m_pEnt; } return false;// Line of sight is not established } return true;// line of sight is valid. } //========================================================= // FVisible - returns true if a line can be traced from // the caller's eyes to the wished position. //========================================================= bool CBaseEntity::FVisible( const Vector &vecTarget, int traceMask, CBaseEntity **ppBlocker ) { #if HL1_DLL // don't look through water // FIXME: only block LOS through opaque water bool inWater = ( UTIL_PointContents( vecTarget ) & (CONTENTS_SLIME|CONTENTS_WATER) ) ? true : false; // Don't allow it if we're straddling two areas if ( ( m_nWaterLevel == 3 && !inWater ) || ( m_nWaterLevel != 3 && inWater ) ) return false; #endif trace_t tr; Vector vecLookerOrigin = EyePosition();// look through the caller's 'eyes' if ( ai_LOS_mode.GetBool() ) { UTIL_TraceLine( vecLookerOrigin, vecTarget, traceMask, this, COLLISION_GROUP_NONE, &tr); } else { // If we're doing an LOS search, include NPCs. if ( traceMask == MASK_BLOCKLOS ) { traceMask = MASK_BLOCKLOS_AND_NPCS; } // Player sees through nodraw and blocklos if ( IsPlayer() ) { traceMask |= CONTENTS_IGNORE_NODRAW_OPAQUE; traceMask &= ~CONTENTS_BLOCKLOS; } // Use the custom LOS trace filter CTraceFilterLOS traceFilter( this, COLLISION_GROUP_NONE ); UTIL_TraceLine( vecLookerOrigin, vecTarget, traceMask, &traceFilter, &tr ); } if (tr.fraction != 1.0) { if (ppBlocker) { *ppBlocker = tr.m_pEnt; } return false;// Line of sight is not established } return true;// line of sight is valid. } extern ConVar ai_debug_los; //----------------------------------------------------------------------------- // Purpose: Turn on prop LOS debugging mode //----------------------------------------------------------------------------- void CC_AI_LOS_Debug( IConVar *var, const char *pOldString, float flOldValue ) { int iLOSMode = ai_debug_los.GetInt(); for ( CBaseEntity *pEntity = gEntList.FirstEnt(); pEntity != NULL; pEntity = gEntList.NextEnt(pEntity) ) { if ( iLOSMode == 1 && pEntity->IsSolid() ) { pEntity->m_debugOverlays |= OVERLAY_SHOW_BLOCKSLOS; } else if ( iLOSMode == 2 ) { pEntity->m_debugOverlays |= OVERLAY_SHOW_BLOCKSLOS; } else { pEntity->m_debugOverlays &= ~OVERLAY_SHOW_BLOCKSLOS; } } } ConVar ai_debug_los("ai_debug_los", "0", FCVAR_CHEAT, "NPC Line-Of-Sight debug mode. If 1, solid entities that block NPC LOC will be highlighted with white bounding boxes. If 2, it'll show non-solid entities that would do it if they were solid.", CC_AI_LOS_Debug ); Class_T CBaseEntity::Classify ( void ) { return CLASS_NONE; } float CBaseEntity::GetAutoAimRadius() { if( g_pGameRules->GetAutoAimMode() == AUTOAIM_ON_CONSOLE ) return 48.0f; else return 24.0f; } //----------------------------------------------------------------------------- // Changes the shadow cast distance over time //----------------------------------------------------------------------------- void CBaseEntity::ShadowCastDistThink( ) { SetShadowCastDistance( m_flDesiredShadowCastDistance ); SetContextThink( NULL, gpGlobals->curtime, "ShadowCastDistThink" ); } void CBaseEntity::SetShadowCastDistance( float flDesiredDistance, float flDelay ) { m_flDesiredShadowCastDistance = flDesiredDistance; if ( m_flDesiredShadowCastDistance != m_flShadowCastDistance ) { SetContextThink( &CBaseEntity::ShadowCastDistThink, gpGlobals->curtime + flDelay, "ShadowCastDistThink" ); } } /* ================ TraceAttack ================ */ //----------------------------------------------------------------------------- // Purpose: Returns whether a damage info can damage this entity. //----------------------------------------------------------------------------- bool CBaseEntity::PassesDamageFilter( const CTakeDamageInfo &info ) { if (m_hDamageFilter) { CBaseFilter *pFilter = (CBaseFilter *)(m_hDamageFilter.Get()); return pFilter->PassesDamageFilter(info); } return true; } FORCEINLINE bool NamesMatch( const char *pszQuery, string_t nameToMatch ) { if ( nameToMatch == NULL_STRING ) return (!pszQuery || *pszQuery == 0 || *pszQuery == '*'); const char *pszNameToMatch = STRING(nameToMatch); // If the pointers are identical, we're identical if ( pszNameToMatch == pszQuery ) return true; while ( *pszNameToMatch && *pszQuery ) { unsigned char cName = *pszNameToMatch; unsigned char cQuery = *pszQuery; // simple ascii case conversion if ( cName == cQuery ) ; else if ( cName - 'A' <= (unsigned char)'Z' - 'A' && cName - 'A' + 'a' == cQuery ) ; else if ( cName - 'a' <= (unsigned char)'z' - 'a' && cName - 'a' + 'A' == cQuery ) ; else break; ++pszNameToMatch; ++pszQuery; } if ( *pszQuery == 0 && *pszNameToMatch == 0 ) return true; // @TODO (toml 03-18-03): Perhaps support real wildcards. Right now, only thing supported is trailing * if ( *pszQuery == '*' ) return true; return false; } bool CBaseEntity::NameMatchesComplex( const char *pszNameOrWildcard ) { if ( !Q_stricmp( "!player", pszNameOrWildcard) ) return IsPlayer(); return NamesMatch( pszNameOrWildcard, m_iName ); } bool CBaseEntity::ClassMatchesComplex( const char *pszClassOrWildcard ) { return NamesMatch( pszClassOrWildcard, m_iClassname ); } void CBaseEntity::MakeDormant( void ) { AddEFlags( EFL_DORMANT ); // disable thinking for dormant entities SetThink( NULL ); if ( !edict() ) return; SETBITS( m_iEFlags, EFL_DORMANT ); // Don't touch AddSolidFlags( FSOLID_NOT_SOLID ); // Don't move SetMoveType( MOVETYPE_NONE ); // Don't draw AddEffects( EF_NODRAW ); // Don't think SetNextThink( TICK_NEVER_THINK ); } int CBaseEntity::IsDormant( void ) { return IsEFlagSet( EFL_DORMANT ); } bool CBaseEntity::IsInWorld( void ) const { if ( !edict() ) return true; // position if (GetAbsOrigin().x >= MAX_COORD_INTEGER) return false; if (GetAbsOrigin().y >= MAX_COORD_INTEGER) return false; if (GetAbsOrigin().z >= MAX_COORD_INTEGER) return false; if (GetAbsOrigin().x <= MIN_COORD_INTEGER) return false; if (GetAbsOrigin().y <= MIN_COORD_INTEGER) return false; if (GetAbsOrigin().z <= MIN_COORD_INTEGER) return false; // speed if (GetAbsVelocity().x >= 2000) return false; if (GetAbsVelocity().y >= 2000) return false; if (GetAbsVelocity().z >= 2000) return false; if (GetAbsVelocity().x <= -2000) return false; if (GetAbsVelocity().y <= -2000) return false; if (GetAbsVelocity().z <= -2000) return false; return true; } bool CBaseEntity::IsViewable( void ) { if ( IsEffectActive( EF_NODRAW ) ) { return false; } if (IsBSPModel()) { if (GetMoveType() != MOVETYPE_NONE) { return true; } } else if (GetModelIndex() != 0) { // check for total transparency??? return true; } return false; } int CBaseEntity::ShouldToggle( USE_TYPE useType, int currentState ) { if ( useType != USE_TOGGLE && useType != USE_SET ) { if ( (currentState && useType == USE_ON) || (!currentState && useType == USE_OFF) ) return 0; } return 1; } // NOTE: szName must be a pointer to constant memory, e.g. "NPC_class" because the entity // will keep a pointer to it after this call. CBaseEntity *CBaseEntity::Create( const char *szName, const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner ) { CBaseEntity *pEntity = CreateNoSpawn( szName, vecOrigin, vecAngles, pOwner ); DispatchSpawn( pEntity ); return pEntity; } // NOTE: szName must be a pointer to constant memory, e.g. "NPC_class" because the entity // will keep a pointer to it after this call. CBaseEntity * CBaseEntity::CreateNoSpawn( const char *szName, const Vector &vecOrigin, const QAngle &vecAngles, CBaseEntity *pOwner ) { CBaseEntity *pEntity = CreateEntityByName( szName ); if ( !pEntity ) { Assert( !"CreateNoSpawn: only works for CBaseEntities" ); return NULL; } pEntity->SetLocalOrigin( vecOrigin ); pEntity->SetLocalAngles( vecAngles ); pEntity->SetOwnerEntity( pOwner ); gEntList.NotifyCreateEntity( pEntity ); return pEntity; } Vector CBaseEntity::GetSoundEmissionOrigin() const { return WorldSpaceCenter(); } //----------------------------------------------------------------------------- // Purpose: Saves the current object out to disk, by iterating through the objects // data description hierarchy // Input : &save - save buffer which the class data is written to // Output : int - 0 if the save failed, 1 on success //----------------------------------------------------------------------------- int CBaseEntity::Save( ISave &save ) { // loop through the data description list, saving each data desc block int status = SaveDataDescBlock( save, GetDataDescMap() ); return status; } //----------------------------------------------------------------------------- // Purpose: Recursively saves all the classes in an object, in reverse order (top down) // Output : int 0 on failure, 1 on success //----------------------------------------------------------------------------- int CBaseEntity::SaveDataDescBlock( ISave &save, datamap_t *dmap ) { return save.WriteAll( this, dmap ); } //----------------------------------------------------------------------------- // Purpose: Restores the current object from disk, by iterating through the objects // data description hierarchy // Input : &restore - restore buffer which the class data is read from // Output : int - 0 if the restore failed, 1 on success //----------------------------------------------------------------------------- int CBaseEntity::Restore( IRestore &restore ) { // This is essential to getting the spatial partition info correct CollisionProp()->DestroyPartitionHandle(); // loops through the data description list, restoring each data desc block in order int status = RestoreDataDescBlock( restore, GetDataDescMap() ); // --------------------------------------------------------------- // HACKHACK: We don't know the space of these vectors until now // if they are worldspace, fix them up. // --------------------------------------------------------------- { CGameSaveRestoreInfo *pGameInfo = restore.GetGameSaveRestoreInfo(); Vector parentSpaceOffset = pGameInfo->modelSpaceOffset; if ( !GetParent() ) { // parent is the world, so parent space is worldspace // so update with the worldspace leveltransition transform parentSpaceOffset += pGameInfo->GetLandmark(); } // NOTE: Do *not* use GetAbsOrigin() here because it will // try to recompute m_rgflCoordinateFrame! MatrixSetColumn( m_vecAbsOrigin, 3, m_rgflCoordinateFrame ); m_vecOrigin += parentSpaceOffset; } // Gotta do this after the coordframe is set up as it depends on it. // By definition, the surrounding bounds are dirty // Also, twiddling with the flags here ensures it gets added to the KD tree dirty list // (We don't want to use the saved version of this flag) RemoveEFlags( EFL_DIRTY_SPATIAL_PARTITION ); CollisionProp()->MarkSurroundingBoundsDirty(); if ( edict() && GetModelIndex() != 0 && GetModelName() != NULL_STRING && restore.GetPrecacheMode() ) { PrecacheModel( STRING( GetModelName() ) ); //Adrian: We should only need to do this after we precache. No point in setting the model again. SetModelIndex( modelinfo->GetModelIndex( STRING(GetModelName() ) ) ); } // Restablish ground entity if ( m_hGroundEntity != NULL ) { m_hGroundEntity->AddEntityToGroundList( this ); } return status; } //----------------------------------------------------------------------------- // handler to do stuff before you are saved //----------------------------------------------------------------------------- void CBaseEntity::OnSave( IEntitySaveUtils *pUtils ) { // Here, we must force recomputation of all abs data so it gets saved correctly // We can't leave the dirty bits set because the loader can't cope with it. CalcAbsolutePosition(); CalcAbsoluteVelocity(); } //----------------------------------------------------------------------------- // handler to do stuff after you are restored //----------------------------------------------------------------------------- void CBaseEntity::OnRestore() { #if defined( PORTAL ) || defined( HL2_EPISODIC ) || defined ( HL2_DLL ) || defined( HL2_LOSTCOAST ) // We had a short period during the 2013 beta where the FL_* flags had a bogus value near the top, so detect // these bad saves and just give up. Only saves from the short beta period should have been effected. if ( GetFlags() & FL_FAKECLIENT ) { char szMsg[256]; V_snprintf( szMsg, sizeof(szMsg), "\nInvalid save, unable to load. Please run \"map %s\" to restart this level manually\n\n", gpGlobals->mapname.ToCStr() ); Msg( "%s", szMsg ); engine->ServerCommand("wait;wait;disconnect;showconsole\n"); } #endif SimThink_EntityChanged( this ); // touchlinks get recomputed if ( IsEFlagSet( EFL_CHECK_UNTOUCH ) ) { RemoveEFlags( EFL_CHECK_UNTOUCH ); SetCheckUntouch( true ); } // disable touch functions while we recreate the touch links between entities // NOTE: We don't do this on transitions, because we'd miss the OnStartTouch call! #if !defined(HL2_DLL) || ( defined(HL2_DLL) && defined(HL2_EPISODIC) ) CBaseEntity::sm_bDisableTouchFuncs = ( gpGlobals->eLoadType != MapLoad_Transition ); PhysicsTouchTriggers(); CBaseEntity::sm_bDisableTouchFuncs = false; #endif // HL2_EPISODIC //Adrian: If I'm restoring with these fields it means I've become a client side ragdoll. //Don't create another one, just wait until is my time of being removed. if ( GetFlags() & FL_TRANSRAGDOLL ) { m_nRenderFX = kRenderFxNone; AddEffects( EF_NODRAW ); RemoveFlag( FL_DISSOLVING | FL_ONFIRE ); } if ( m_pParent ) { CBaseEntity *pChild = m_pParent->FirstMoveChild(); while ( pChild ) { if ( pChild == this ) break; pChild = pChild->NextMovePeer(); } if ( pChild != this ) { #if _DEBUG // generally this means you've got something marked FCAP_DONT_SAVE // in a hierarchy. That's probably ok given this fixup, but the hierarhcy // linked list is just saved/loaded in-place Warning("Fixing up parent on %s\n", GetClassname() ); #endif // We only need to be back in the parent's list because we're already in the right place and with the right data LinkChild( m_pParent, this ); } } // We're not save/loading the PVS dirty state. Assume everything is dirty after a restore NetworkProp()->MarkPVSInformationDirty(); } //----------------------------------------------------------------------------- // Purpose: Recursively restores all the classes in an object, in reverse order (top down) // Output : int 0 on failure, 1 on success //----------------------------------------------------------------------------- int CBaseEntity::RestoreDataDescBlock( IRestore &restore, datamap_t *dmap ) { return restore.ReadAll( this, dmap ); } //----------------------------------------------------------------------------- bool CBaseEntity::ShouldSavePhysics() { return true; } //----------------------------------------------------------------------------- #include "tier0/memdbgoff.h" //----------------------------------------------------------------------------- // CBaseEntity new/delete // allocates and frees memory for itself from the engine-> // All fields in the object are all initialized to 0. //----------------------------------------------------------------------------- void *CBaseEntity::operator new( size_t stAllocateBlock ) { // call into engine to get memory Assert( stAllocateBlock != 0 ); return engine->PvAllocEntPrivateData(stAllocateBlock); }; void *CBaseEntity::operator new( size_t stAllocateBlock, int nBlockUse, const char *pFileName, int nLine ) { // call into engine to get memory Assert( stAllocateBlock != 0 ); return engine->PvAllocEntPrivateData(stAllocateBlock); } void CBaseEntity::operator delete( void *pMem ) { // get the engine to free the memory engine->FreeEntPrivateData( pMem ); } #include "tier0/memdbgon.h" #ifdef _DEBUG void CBaseEntity::FunctionCheck( void *pFunction, const char *name ) { #ifdef USES_SAVERESTORE // Note, if you crash here and your class is using multiple inheritance, it is // probably the case that CBaseEntity (or a descendant) is not the first // class in your list of ancestors, which it must be. if (pFunction && !UTIL_FunctionToName( GetDataDescMap(), (inputfunc_t *)pFunction ) ) { Warning( "FUNCTION NOT IN TABLE!: %s:%s (%08lx)\n", STRING(m_iClassname), name, (unsigned long)pFunction ); Assert(0); } #endif } #endif bool CBaseEntity::TestCollision( const Ray_t &ray, unsigned int mask, trace_t& trace ) { return false; } //----------------------------------------------------------------------------- // Perform hitbox test, returns true *if hitboxes were tested at all*!! //----------------------------------------------------------------------------- bool CBaseEntity::TestHitboxes( const Ray_t &ray, unsigned int fContentsMask, trace_t& tr ) { return false; } void CBaseEntity::SetOwnerEntity( CBaseEntity* pOwner ) { if ( m_hOwnerEntity.Get() != pOwner ) { m_hOwnerEntity = pOwner; CollisionRulesChanged(); } } void CBaseEntity::SetMoveType( MoveType_t val, MoveCollide_t moveCollide ) { #ifdef _DEBUG // Make sure the move type + move collide are compatible... if ((val != MOVETYPE_FLY) && (val != MOVETYPE_FLYGRAVITY)) { Assert( moveCollide == MOVECOLLIDE_DEFAULT ); } if ( m_MoveType == MOVETYPE_VPHYSICS && val != m_MoveType ) { if ( VPhysicsGetObject() && val != MOVETYPE_NONE ) { // What am I supposed to do with the physics object if // you're changing away from MOVETYPE_VPHYSICS without making the object // shadow? This isn't likely to work, assert. // You probably meant to call VPhysicsInitShadow() instead of VPhysicsInitNormal()! Assert( VPhysicsGetObject()->GetShadowController() ); } } #endif if ( m_MoveType == val ) { m_MoveCollide = moveCollide; return; } // This is needed to the removal of MOVETYPE_FOLLOW: // We can't transition from follow to a different movetype directly // or the leaf code will break. Assert( !IsEffectActive( EF_BONEMERGE ) ); m_MoveType = val; m_MoveCollide = moveCollide; CollisionRulesChanged(); switch( m_MoveType ) { case MOVETYPE_WALK: { SetSimulatedEveryTick( true ); SetAnimatedEveryTick( true ); } break; case MOVETYPE_STEP: { // This will probably go away once I remove the cvar that controls the test code SetSimulatedEveryTick( g_bTestMoveTypeStepSimulation ? true : false ); SetAnimatedEveryTick( false ); } break; case MOVETYPE_FLY: case MOVETYPE_FLYGRAVITY: { // Initialize our water state, because these movetypes care about transitions in/out of water UpdateWaterState(); } break; default: { SetSimulatedEveryTick( true ); SetAnimatedEveryTick( false ); } } // This will probably go away or be handled in a better way once I remove the cvar that controls the test code CheckStepSimulationChanged(); CheckHasGamePhysicsSimulation(); } void CBaseEntity::Spawn( void ) { } CBaseEntity* CBaseEntity::Instance( const CBaseHandle &hEnt ) { return gEntList.GetBaseEntity( hEnt ); } int CBaseEntity::GetTransmitState( void ) { edict_t *ed = edict(); if ( !ed ) return 0; return ed->m_fStateFlags; } int CBaseEntity::SetTransmitState( int nFlag) { edict_t *ed = edict(); if ( !ed ) return 0; // clear current flags = check ShouldTransmit() ed->ClearTransmitState(); int oldFlags = ed->m_fStateFlags; ed->m_fStateFlags |= nFlag; // Tell the engine (used for a network backdoor optimization). if ( (oldFlags & FL_EDICT_DONTSEND) != (ed->m_fStateFlags & FL_EDICT_DONTSEND) ) engine->NotifyEdictFlagsChange( entindex() ); return ed->m_fStateFlags; } int CBaseEntity::UpdateTransmitState() { // If you get this assert, you should be calling DispatchUpdateTransmitState // instead of UpdateTransmitState. Assert( g_nInsideDispatchUpdateTransmitState > 0 ); // If an object is the moveparent of something else, don't skip it just because it's marked EF_NODRAW or else // the client won't have a proper origin for the child since the hierarchy won't be correctly transmitted down if ( IsEffectActive( EF_NODRAW ) && !m_hMoveChild.Get() ) { return SetTransmitState( FL_EDICT_DONTSEND ); } if ( !IsEFlagSet( EFL_FORCE_CHECK_TRANSMIT ) ) { if ( !GetModelIndex() || !GetModelName() ) { return SetTransmitState( FL_EDICT_DONTSEND ); } } // Always send the world if ( GetModelIndex() == 1 ) { return SetTransmitState( FL_EDICT_ALWAYS ); } if ( IsEFlagSet( EFL_IN_SKYBOX ) ) { return SetTransmitState( FL_EDICT_ALWAYS ); } // by default cull against PVS return SetTransmitState( FL_EDICT_PVSCHECK ); } int CBaseEntity::DispatchUpdateTransmitState() { edict_t *ed = edict(); if ( m_nTransmitStateOwnedCounter != 0 ) return ed ? ed->m_fStateFlags : 0; g_nInsideDispatchUpdateTransmitState++; int ret = UpdateTransmitState(); g_nInsideDispatchUpdateTransmitState--; return ret; } //----------------------------------------------------------------------------- // Purpose: Note, an entity can override the send table ( e.g., to send less data or to send minimal data for // objects ( prob. players ) that are not in the pvs. // Input : **ppSendTable - // *recipient - // *pvs - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- int CBaseEntity::ShouldTransmit( const CCheckTransmitInfo *pInfo ) { int fFlags = DispatchUpdateTransmitState(); if ( fFlags & FL_EDICT_PVSCHECK ) { return FL_EDICT_PVSCHECK; } else if ( fFlags & FL_EDICT_ALWAYS ) { return FL_EDICT_ALWAYS; } else if ( fFlags & FL_EDICT_DONTSEND ) { return FL_EDICT_DONTSEND; } // if ( IsToolRecording() ) // { // return FL_EDICT_ALWAYS; // } CBaseEntity *pRecipientEntity = CBaseEntity::Instance( pInfo->m_pClientEnt ); Assert( pRecipientEntity->IsPlayer() ); CBasePlayer *pRecipientPlayer = static_cast<CBasePlayer*>( pRecipientEntity ); // FIXME: Refactor once notion of "team" is moved into HL2 code // Team rules may tell us that we should if ( pRecipientPlayer->GetTeam() ) { if ( pRecipientPlayer->GetTeam()->ShouldTransmitToPlayer( pRecipientPlayer, this )) return FL_EDICT_ALWAYS; } /*#ifdef INVASION_DLL // Check test network vis distance stuff. Eventually network LOD will do this. float flTestDistSqr = pRecipientEntity->GetAbsOrigin().DistToSqr( WorldSpaceCenter() ); if ( flTestDistSqr > sv_netvisdist.GetFloat() * sv_netvisdist.GetFloat() ) return TRANSMIT_NO; // TODO doesn't work with HLTV #endif*/ // by default do a PVS check return FL_EDICT_PVSCHECK; } //----------------------------------------------------------------------------- // Rules about which entities need to transmit along with me //----------------------------------------------------------------------------- void CBaseEntity::SetTransmit( CCheckTransmitInfo *pInfo, bool bAlways ) { int index = entindex(); // Are we already marked for transmission? if ( pInfo->m_pTransmitEdict->Get( index ) ) return; CServerNetworkProperty *pNetworkParent = NetworkProp()->GetNetworkParent(); pInfo->m_pTransmitEdict->Set( index ); // HLTV/Replay need to know if this entity is culled by PVS limits if ( pInfo->m_pTransmitAlways ) { // in HLTV/Replay mode always transmit entitys with move-parents // HLTV/Replay can't resolve the mode-parents relationships if ( bAlways || pNetworkParent ) { // tell HLTV/Replay that this entity is always transmitted pInfo->m_pTransmitAlways->Set( index ); } else { // HLTV/Replay will PVS cull this entity, so update the // node/cluster infos if necessary m_Network.RecomputePVSInformation(); } } // Force our aiment and move parent to be sent. if ( pNetworkParent ) { CBaseEntity *pMoveParent = pNetworkParent->GetBaseEntity(); pMoveParent->SetTransmit( pInfo, bAlways ); } } //----------------------------------------------------------------------------- // Returns which skybox the entity is in //----------------------------------------------------------------------------- CSkyCamera *CBaseEntity::GetEntitySkybox() { int area = engine->GetArea( WorldSpaceCenter() ); CSkyCamera *pCur = GetSkyCameraList(); while ( pCur ) { if ( engine->CheckAreasConnected( area, pCur->m_skyboxData.area ) ) return pCur; pCur = pCur->m_pNext; } return NULL; } bool CBaseEntity::DetectInSkybox() { if ( GetEntitySkybox() != NULL ) { AddEFlags( EFL_IN_SKYBOX ); return true; } RemoveEFlags( EFL_IN_SKYBOX ); return false; } //------------------------------------------------------------------------------ // Computes a world-aligned bounding box that surrounds everything in the entity //------------------------------------------------------------------------------ void CBaseEntity::ComputeWorldSpaceSurroundingBox( Vector *pMins, Vector *pMaxs ) { // Should never get here.. only use USE_GAME_CODE with bounding boxes // if you have an implementation for this method Assert( 0 ); } //------------------------------------------------------------------------------ // Purpose : If name exists returns name, otherwise returns classname // Input : // Output : //------------------------------------------------------------------------------ const char *CBaseEntity::GetDebugName(void) { if ( this == NULL ) return "<<null>>"; if ( m_iName != NULL_STRING ) { return STRING(m_iName); } else { return STRING(m_iClassname); } } //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CBaseEntity::DrawInputOverlay(const char *szInputName, CBaseEntity *pCaller, variant_t Value) { char bigstring[1024]; if ( Value.FieldType() == FIELD_INTEGER ) { Q_snprintf( bigstring,sizeof(bigstring), "%3.1f (%s,%d) <-- (%s)\n", gpGlobals->curtime, szInputName, Value.Int(), pCaller ? pCaller->GetDebugName() : NULL); } else if ( Value.FieldType() == FIELD_STRING ) { Q_snprintf( bigstring,sizeof(bigstring), "%3.1f (%s,%s) <-- (%s)\n", gpGlobals->curtime, szInputName, Value.String(), pCaller ? pCaller->GetDebugName() : NULL); } else { Q_snprintf( bigstring,sizeof(bigstring), "%3.1f (%s) <-- (%s)\n", gpGlobals->curtime, szInputName, pCaller ? pCaller->GetDebugName() : NULL); } AddTimedOverlay(bigstring, 10.0); if ( Value.FieldType() == FIELD_INTEGER ) { DevMsg( 2, "input: (%s,%d) -> (%s,%s), from (%s)\n", szInputName, Value.Int(), STRING(m_iClassname), GetDebugName(), pCaller ? pCaller->GetDebugName() : NULL); } else if ( Value.FieldType() == FIELD_STRING ) { DevMsg( 2, "input: (%s,%s) -> (%s,%s), from (%s)\n", szInputName, Value.String(), STRING(m_iClassname), GetDebugName(), pCaller ? pCaller->GetDebugName() : NULL); } else DevMsg( 2, "input: (%s) -> (%s,%s), from (%s)\n", szInputName, STRING(m_iClassname), GetDebugName(), pCaller ? pCaller->GetDebugName() : NULL); } //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CBaseEntity::DrawOutputOverlay(CEventAction *ev) { // Print to entity char bigstring[1024]; if ( ev->m_flDelay ) { Q_snprintf( bigstring,sizeof(bigstring), "%3.1f (%s) --> (%s),%.1f) \n", gpGlobals->curtime, STRING(ev->m_iTargetInput), STRING(ev->m_iTarget), ev->m_flDelay); } else { Q_snprintf( bigstring,sizeof(bigstring), "%3.1f (%s) --> (%s)\n", gpGlobals->curtime, STRING(ev->m_iTargetInput), STRING(ev->m_iTarget)); } AddTimedOverlay(bigstring, 10.0); // Now print to the console if ( ev->m_flDelay ) { DevMsg( 2, "output: (%s,%s) -> (%s,%s,%.1f)\n", STRING(m_iClassname), GetDebugName(), STRING(ev->m_iTarget), STRING(ev->m_iTargetInput), ev->m_flDelay ); } else { DevMsg( 2, "output: (%s,%s) -> (%s,%s)\n", STRING(m_iClassname), GetDebugName(), STRING(ev->m_iTarget), STRING(ev->m_iTargetInput) ); } } //----------------------------------------------------------------------------- // Entity events... these are events targetted to a particular entity // Each event defines its own well-defined event data structure //----------------------------------------------------------------------------- void CBaseEntity::OnEntityEvent( EntityEvent_t event, void *pEventData ) { switch( event ) { case ENTITY_EVENT_WATER_TOUCH: { int nContents = (int)pEventData; if ( !nContents || (nContents & CONTENTS_WATER) ) { ++m_nWaterTouch; } if ( nContents & CONTENTS_SLIME ) { ++m_nSlimeTouch; } } break; case ENTITY_EVENT_WATER_UNTOUCH: { int nContents = (int)pEventData; if ( !nContents || (nContents & CONTENTS_WATER) ) { --m_nWaterTouch; } if ( nContents & CONTENTS_SLIME ) { --m_nSlimeTouch; } } break; default: return; } // Only do this for vphysics objects if ( GetMoveType() != MOVETYPE_VPHYSICS ) return; int nNewContents = 0; if ( m_nWaterTouch > 0 ) { nNewContents |= CONTENTS_WATER; } if ( m_nSlimeTouch > 0 ) { nNewContents |= CONTENTS_SLIME; } if (( nNewContents & MASK_WATER ) == 0) { SetWaterLevel( 0 ); SetWaterType( CONTENTS_EMPTY ); return; } SetWaterLevel( 1 ); SetWaterType( nNewContents ); } ConVar ent_messages_draw( "ent_messages_draw", "0", FCVAR_CHEAT, "Visualizes all entity input/output activity." ); //----------------------------------------------------------------------------- // Purpose: calls the appropriate message mapped function in the entity according // to the fired action. // Input : char *szInputName - input destination // *pActivator - entity which initiated this sequence of actions // *pCaller - entity from which this event is sent // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBaseEntity::AcceptInput( const char *szInputName, CBaseEntity *pActivator, CBaseEntity *pCaller, variant_t Value, int outputID ) { if ( ent_messages_draw.GetBool() ) { if ( pCaller != NULL ) { NDebugOverlay::Line( pCaller->GetAbsOrigin(), GetAbsOrigin(), 255, 255, 255, false, 3 ); NDebugOverlay::Box( pCaller->GetAbsOrigin(), Vector(-4, -4, -4), Vector(4, 4, 4), 255, 0, 0, 0, 3 ); } NDebugOverlay::Text( GetAbsOrigin(), szInputName, false, 3 ); NDebugOverlay::Box( GetAbsOrigin(), Vector(-4, -4, -4), Vector(4, 4, 4), 0, 255, 0, 0, 3 ); } // loop through the data description list, restoring each data desc block for ( datamap_t *dmap = GetDataDescMap(); dmap != NULL; dmap = dmap->baseMap ) { // search through all the actions in the data description, looking for a match for ( int i = 0; i < dmap->dataNumFields; i++ ) { if ( dmap->dataDesc[i].flags & FTYPEDESC_INPUT ) { if ( !Q_stricmp(dmap->dataDesc[i].externalName, szInputName) ) { // found a match char szBuffer[256]; // mapper debug message if (pCaller != NULL) { Q_snprintf( szBuffer, sizeof(szBuffer), "(%0.2f) input %s: %s.%s(%s)\n", gpGlobals->curtime, STRING(pCaller->m_iName), GetDebugName(), szInputName, Value.String() ); } else { Q_snprintf( szBuffer, sizeof(szBuffer), "(%0.2f) input <NULL>: %s.%s(%s)\n", gpGlobals->curtime, GetDebugName(), szInputName, Value.String() ); } DevMsg( 2, "%s", szBuffer ); ADD_DEBUG_HISTORY( HISTORY_ENTITY_IO, szBuffer ); if (m_debugOverlays & OVERLAY_MESSAGE_BIT) { DrawInputOverlay(szInputName,pCaller,Value); } // convert the value if necessary if ( Value.FieldType() != dmap->dataDesc[i].fieldType ) { if ( !(Value.FieldType() == FIELD_VOID && dmap->dataDesc[i].fieldType == FIELD_STRING) ) // allow empty strings { if ( !Value.Convert( (fieldtype_t)dmap->dataDesc[i].fieldType ) ) { // bad conversion Warning( "!! ERROR: bad input/output link:\n!! %s(%s,%s) doesn't match type from %s(%s)\n", STRING(m_iClassname), GetDebugName(), szInputName, ( pCaller != NULL ) ? STRING(pCaller->m_iClassname) : "<null>", ( pCaller != NULL ) ? STRING(pCaller->m_iName) : "<null>" ); return false; } } } // call the input handler, or if there is none just set the value inputfunc_t pfnInput = dmap->dataDesc[i].inputFunc; if ( pfnInput ) { // Package the data into a struct for passing to the input handler. inputdata_t data; data.pActivator = pActivator; data.pCaller = pCaller; data.value = Value; data.nOutputID = outputID; (this->*pfnInput)( data ); } else if ( dmap->dataDesc[i].flags & FTYPEDESC_KEY ) { // set the value directly Value.SetOther( ((char*)this) + dmap->dataDesc[i].fieldOffset[ TD_OFFSET_NORMAL ]); // TODO: if this becomes evil and causes too many full entity updates, then we should make // a macro like this: // // define MAKE_INPUTVAR(x) void Note##x##Modified() { x.GetForModify(); } // // Then the datadesc points at that function and we call it here. The only pain is to add // that function for all the DEFINE_INPUT calls. NetworkStateChanged(); } return true; } } } } DevMsg( 2, "unhandled input: (%s) -> (%s,%s)\n", szInputName, STRING(m_iClassname), GetDebugName()/*,", from (%s,%s)" STRING(pCaller->m_iClassname), STRING(pCaller->m_iName)*/ ); return false; } //----------------------------------------------------------------------------- // Purpose: Input handler for the entity alpha. // Input : nAlpha - Alpha value (0 - 255). //----------------------------------------------------------------------------- void CBaseEntity::InputAlpha( inputdata_t &inputdata ) { SetRenderColorA( clamp( inputdata.value.Int(), 0, 255 ) ); } //----------------------------------------------------------------------------- // Activate alternative sorting //----------------------------------------------------------------------------- void CBaseEntity::InputAlternativeSorting( inputdata_t &inputdata ) { m_bAlternateSorting = inputdata.value.Bool(); } //----------------------------------------------------------------------------- // Purpose: Input handler for the entity color. Ignores alpha since that is handled // by a separate input handler. // Input : Color32 new value for color (alpha is ignored). //----------------------------------------------------------------------------- void CBaseEntity::InputColor( inputdata_t &inputdata ) { color32 clr = inputdata.value.Color32(); SetRenderColor( clr.r, clr.g, clr.b ); } //----------------------------------------------------------------------------- // Purpose: Called whenever the entity is 'Used'. This can be when a player hits // use, or when an entity targets it without an output name (legacy entities) //----------------------------------------------------------------------------- void CBaseEntity::InputUse( inputdata_t &inputdata ) { Use( inputdata.pActivator, inputdata.pCaller, (USE_TYPE)inputdata.nOutputID, 0 ); } //----------------------------------------------------------------------------- // Purpose: Reads an output variable, by string name, from an entity // Input : char *varName - the string name of the variable // variant_t *var - the value is stored here // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CBaseEntity::ReadKeyField( const char *varName, variant_t *var ) { if ( !varName ) return false; // loop through the data description list, restoring each data desc block for ( datamap_t *dmap = GetDataDescMap(); dmap != NULL; dmap = dmap->baseMap ) { // search through all the readable fields in the data description, looking for a match for ( int i = 0; i < dmap->dataNumFields; i++ ) { if ( dmap->dataDesc[i].flags & (FTYPEDESC_OUTPUT | FTYPEDESC_KEY) ) { if ( !Q_stricmp(dmap->dataDesc[i].externalName, varName) ) { var->Set( dmap->dataDesc[i].fieldType, ((char*)this) + dmap->dataDesc[i].fieldOffset[ TD_OFFSET_NORMAL ] ); return true; } } } } return false; } //----------------------------------------------------------------------------- // Purpose: Sets the damage filter on the object //----------------------------------------------------------------------------- void CBaseEntity::InputEnableDamageForces( inputdata_t &inputdata ) { RemoveEFlags( EFL_NO_DAMAGE_FORCES ); } void CBaseEntity::InputDisableDamageForces( inputdata_t &inputdata ) { AddEFlags( EFL_NO_DAMAGE_FORCES ); } //----------------------------------------------------------------------------- // Purpose: Sets the damage filter on the object //----------------------------------------------------------------------------- void CBaseEntity::InputSetDamageFilter( inputdata_t &inputdata ) { // Get a handle to my damage filter entity if there is one. m_iszDamageFilterName = inputdata.value.StringID(); if ( m_iszDamageFilterName != NULL_STRING ) { m_hDamageFilter = gEntList.FindEntityByName( NULL, m_iszDamageFilterName ); } else { m_hDamageFilter = NULL; } } //----------------------------------------------------------------------------- // Purpose: Dispatch effects on this entity //----------------------------------------------------------------------------- void CBaseEntity::InputDispatchEffect( inputdata_t &inputdata ) { const char *sEffect = inputdata.value.String(); if ( sEffect && sEffect[0] ) { CEffectData data; GetInputDispatchEffectPosition( sEffect, data.m_vOrigin, data.m_vAngles ); AngleVectors( data.m_vAngles, &data.m_vNormal ); data.m_vStart = data.m_vOrigin; data.m_nEntIndex = entindex(); // Clip off leading attachment point numbers while ( sEffect[0] >= '0' && sEffect[0] <= '9' ) { sEffect++; } DispatchEffect( sEffect, data ); } } //----------------------------------------------------------------------------- // Purpose: Returns the origin at which to play an inputted dispatcheffect //----------------------------------------------------------------------------- void CBaseEntity::GetInputDispatchEffectPosition( const char *sInputString, Vector &pOrigin, QAngle &pAngles ) { pOrigin = GetAbsOrigin(); pAngles = GetAbsAngles(); } //----------------------------------------------------------------------------- // Purpose: Marks the entity for deletion //----------------------------------------------------------------------------- void CBaseEntity::InputKill( inputdata_t &inputdata ) { // tell owner ( if any ) that we're dead.This is mostly for NPCMaker functionality. CBaseEntity *pOwner = GetOwnerEntity(); if ( pOwner ) { pOwner->DeathNotice( this ); SetOwnerEntity( NULL ); } UTIL_Remove( this ); } void CBaseEntity::InputKillHierarchy( inputdata_t &inputdata ) { CBaseEntity *pChild, *pNext; for ( pChild = FirstMoveChild(); pChild; pChild = pNext ) { pNext = pChild->NextMovePeer(); pChild->InputKillHierarchy( inputdata ); } // tell owner ( if any ) that we're dead. This is mostly for NPCMaker functionality. CBaseEntity *pOwner = GetOwnerEntity(); if ( pOwner ) { pOwner->DeathNotice( this ); SetOwnerEntity( NULL ); } UTIL_Remove( this ); } //------------------------------------------------------------------------------ // Purpose: Input handler for changing this entity's movement parent. //------------------------------------------------------------------------------ void CBaseEntity::InputSetParent( inputdata_t &inputdata ) { // If we had a parent attachment, clear it, because it's no longer valid. if ( m_iParentAttachment ) { m_iParentAttachment = 0; } SetParent( inputdata.value.StringID(), inputdata.pActivator ); } //------------------------------------------------------------------------------ // Purpose: //------------------------------------------------------------------------------ void CBaseEntity::SetParentAttachment( const char *szInputName, const char *szAttachment, bool bMaintainOffset ) { // Must have a parent if ( !m_pParent ) { Warning("ERROR: Tried to %s for entity %s (%s), but it has no parent.\n", szInputName, GetClassname(), GetDebugName() ); return; } // Valid only on CBaseAnimating CBaseAnimating *pAnimating = m_pParent->GetBaseAnimating(); if ( !pAnimating ) { Warning("ERROR: Tried to %s for entity %s (%s), but its parent has no model.\n", szInputName, GetClassname(), GetDebugName() ); return; } // Lookup the attachment int iAttachment = pAnimating->LookupAttachment( szAttachment ); if ( iAttachment <= 0 ) { Warning("ERROR: Tried to %s for entity %s (%s), but it has no attachment named %s.\n", szInputName, GetClassname(), GetDebugName(), szAttachment ); return; } m_iParentAttachment = iAttachment; SetParent( m_pParent, m_iParentAttachment ); // Now move myself directly onto the attachment point SetMoveType( MOVETYPE_NONE ); if ( !bMaintainOffset ) { SetLocalOrigin( vec3_origin ); SetLocalAngles( vec3_angle ); } } //----------------------------------------------------------------------------- // Purpose: Input handler for changing this entity's movement parent's attachment point //----------------------------------------------------------------------------- void CBaseEntity::InputSetParentAttachment( inputdata_t &inputdata ) { SetParentAttachment( "SetParentAttachment", inputdata.value.String(), false ); } //----------------------------------------------------------------------------- // Purpose: Input handler for changing this entity's movement parent's attachment point //----------------------------------------------------------------------------- void CBaseEntity::InputSetParentAttachmentMaintainOffset( inputdata_t &inputdata ) { SetParentAttachment( "SetParentAttachmentMaintainOffset", inputdata.value.String(), true ); } //------------------------------------------------------------------------------ // Purpose: Input handler for clearing this entity's movement parent. //------------------------------------------------------------------------------ void CBaseEntity::InputClearParent( inputdata_t &inputdata ) { SetParent( NULL ); } //------------------------------------------------------------------------------ // Purpose : Returns velcocity of base entity. If physically simulated gets // velocity from physics object // Input : // Output : //------------------------------------------------------------------------------ void CBaseEntity::GetVelocity(Vector *vVelocity, AngularImpulse *vAngVelocity) { if (GetMoveType()==MOVETYPE_VPHYSICS && m_pPhysicsObject) { m_pPhysicsObject->GetVelocity(vVelocity,vAngVelocity); } else { if (vVelocity != NULL) { *vVelocity = GetAbsVelocity(); } if (vAngVelocity != NULL) { QAngle tmp = GetLocalAngularVelocity(); QAngleToAngularImpulse( tmp, *vAngVelocity ); } } } bool CBaseEntity::IsMoving() { Vector velocity; GetVelocity( &velocity, NULL ); return velocity != vec3_origin; } //----------------------------------------------------------------------------- // Purpose: Retrieves the coordinate frame for this entity. // Input : forward - Receives the entity's forward vector. // right - Receives the entity's right vector. // up - Receives the entity's up vector. //----------------------------------------------------------------------------- void CBaseEntity::GetVectors(Vector* pForward, Vector* pRight, Vector* pUp) const { // This call is necessary to cause m_rgflCoordinateFrame to be recomputed const matrix3x4_t &entityToWorld = EntityToWorldTransform(); if (pForward != NULL) { MatrixGetColumn( entityToWorld, 0, *pForward ); } if (pRight != NULL) { MatrixGetColumn( entityToWorld, 1, *pRight ); *pRight *= -1.0f; } if (pUp != NULL) { MatrixGetColumn( entityToWorld, 2, *pUp ); } } //----------------------------------------------------------------------------- // Purpose: Sets the model, validates that it's of the appropriate type // Input : *szModelName - //----------------------------------------------------------------------------- void CBaseEntity::SetModel( const char *szModelName ) { int modelIndex = modelinfo->GetModelIndex( szModelName ); const model_t *model = modelinfo->GetModel( modelIndex ); if ( model && modelinfo->GetModelType( model ) != mod_brush ) { Msg( "Setting CBaseEntity to non-brush model %s\n", szModelName ); } UTIL_SetModel( this, szModelName ); } //------------------------------------------------------------------------------ CStudioHdr *CBaseEntity::OnNewModel() { // Do nothing. return NULL; } //================================================================================ // TEAM HANDLING //================================================================================ void CBaseEntity::InputSetTeam( inputdata_t &inputdata ) { ChangeTeam( inputdata.value.Int() ); } //----------------------------------------------------------------------------- // Purpose: Put the entity in the specified team //----------------------------------------------------------------------------- void CBaseEntity::ChangeTeam( int iTeamNum ) { m_iTeamNum = iTeamNum; } //----------------------------------------------------------------------------- // Get the Team this entity is on //----------------------------------------------------------------------------- CTeam *CBaseEntity::GetTeam( void ) const { return GetGlobalTeam( m_iTeamNum ); } //----------------------------------------------------------------------------- // Purpose: Returns true if these players are both in at least one team together //----------------------------------------------------------------------------- bool CBaseEntity::InSameTeam( CBaseEntity *pEntity ) const { if ( !pEntity ) return false; return ( pEntity->GetTeam() == GetTeam() ); } //----------------------------------------------------------------------------- // Purpose: Returns the string name of the players team //----------------------------------------------------------------------------- const char *CBaseEntity::TeamID( void ) const { if ( GetTeam() == NULL ) return ""; return GetTeam()->GetName(); } //----------------------------------------------------------------------------- // Purpose: Returns true if the player is on the same team //----------------------------------------------------------------------------- bool CBaseEntity::IsInTeam( CTeam *pTeam ) const { return ( GetTeam() == pTeam ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CBaseEntity::GetTeamNumber( void ) const { return m_iTeamNum; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CBaseEntity::IsInAnyTeam( void ) const { return ( GetTeam() != NULL ); } //----------------------------------------------------------------------------- // Purpose: Returns the type of damage that this entity inflicts. //----------------------------------------------------------------------------- int CBaseEntity::GetDamageType() const { return DMG_GENERIC; } //----------------------------------------------------------------------------- // process notification //----------------------------------------------------------------------------- void CBaseEntity::NotifySystemEvent( CBaseEntity *pNotify, notify_system_event_t eventType, const notify_system_event_params_t &params ) { } //----------------------------------------------------------------------------- // Purpose: Holds an entity's previous abs origin and angles at the time of // teleportation. Used for child & constrained entity fixup to prevent // lazy updates of abs origins and angles from messing things up. //----------------------------------------------------------------------------- struct TeleportListEntry_t { CBaseEntity *pEntity; Vector prevAbsOrigin; QAngle prevAbsAngles; }; static void TeleportEntity( CBaseEntity *pSourceEntity, TeleportListEntry_t &entry, const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ) { CBaseEntity *pTeleport = entry.pEntity; Vector prevOrigin = entry.prevAbsOrigin; QAngle prevAngles = entry.prevAbsAngles; int nSolidFlags = pTeleport->GetSolidFlags(); pTeleport->AddSolidFlags( FSOLID_NOT_SOLID ); // I'm teleporting myself if ( pSourceEntity == pTeleport ) { if ( newAngles ) { pTeleport->SetLocalAngles( *newAngles ); if ( pTeleport->IsPlayer() ) { CBasePlayer *pPlayer = (CBasePlayer *)pTeleport; pPlayer->SnapEyeAngles( *newAngles ); } } if ( newVelocity ) { pTeleport->SetAbsVelocity( *newVelocity ); pTeleport->SetBaseVelocity( vec3_origin ); } if ( newPosition ) { pTeleport->IncrementInterpolationFrame(); UTIL_SetOrigin( pTeleport, *newPosition ); } } else { // My parent is teleporting, just update my position & physics pTeleport->CalcAbsolutePosition(); } IPhysicsObject *pPhys = pTeleport->VPhysicsGetObject(); bool rotatePhysics = false; // handle physics objects / shadows if ( pPhys ) { if ( newVelocity ) { pPhys->SetVelocity( newVelocity, NULL ); } const QAngle *rotAngles = &pTeleport->GetAbsAngles(); // don't rotate physics on players or bbox entities if (pTeleport->IsPlayer() || pTeleport->GetSolid() == SOLID_BBOX ) { rotAngles = &vec3_angle; } else { rotatePhysics = true; } pPhys->SetPosition( pTeleport->GetAbsOrigin(), *rotAngles, true ); } g_pNotify->ReportTeleportEvent( pTeleport, prevOrigin, prevAngles, rotatePhysics ); pTeleport->SetSolidFlags( nSolidFlags ); } //----------------------------------------------------------------------------- // Purpose: Recurses an entity hierarchy and fills out a list of all entities // in the hierarchy with their current origins and angles. // // This list is necessary to keep lazy updates of abs origins and angles // from messing up our child/constrained entity fixup. //----------------------------------------------------------------------------- static void BuildTeleportList_r( CBaseEntity *pTeleport, CUtlVector<TeleportListEntry_t> &teleportList ) { TeleportListEntry_t entry; entry.pEntity = pTeleport; entry.prevAbsOrigin = pTeleport->GetAbsOrigin(); entry.prevAbsAngles = pTeleport->GetAbsAngles(); teleportList.AddToTail( entry ); CBaseEntity *pList = pTeleport->FirstMoveChild(); while ( pList ) { BuildTeleportList_r( pList, teleportList ); pList = pList->NextMovePeer(); } } static CUtlVector<CBaseEntity *> g_TeleportStack; void CBaseEntity::Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity ) { if ( g_TeleportStack.Find( this ) >= 0 ) return; int index = g_TeleportStack.AddToTail( this ); CUtlVector<TeleportListEntry_t> teleportList; BuildTeleportList_r( this, teleportList ); int i; for ( i = 0; i < teleportList.Count(); i++) { TeleportEntity( this, teleportList[i], newPosition, newAngles, newVelocity ); } for (i = 0; i < teleportList.Count(); i++) { teleportList[i].pEntity->CollisionRulesChanged(); } Assert( g_TeleportStack[index] == this ); g_TeleportStack.FastRemove( index ); // FIXME: add an initializer function to StepSimulationData StepSimulationData *step = ( StepSimulationData * )GetDataObject( STEPSIMULATION ); if (step) { Q_memset( step, 0, sizeof( *step ) ); } } // Stuff implemented for weapon prediction code void CBaseEntity::SetSize( const Vector &vecMin, const Vector &vecMax ) { UTIL_SetSize( this, vecMin, vecMax ); } CStudioHdr *ModelSoundsCache_LoadModel( const char *filename ) { // Load the file int idx = engine->PrecacheModel( filename, true ); if ( idx != -1 ) { model_t *mdl = (model_t *)modelinfo->GetModel( idx ); if ( mdl ) { CStudioHdr *studioHdr = new CStudioHdr( modelinfo->GetStudiomodel( mdl ), mdlcache ); if ( studioHdr->IsValid() ) { return studioHdr; } } } return NULL; } void ModelSoundsCache_FinishModel( CStudioHdr *hdr ) { Assert( hdr ); delete hdr; } void ModelSoundsCache_PrecacheScriptSound( const char *soundname ) { CBaseEntity::PrecacheScriptSound( soundname ); } static CUtlCachedFileData< CModelSoundsCache > g_ModelSoundsCache( "modelsounds.cache", MODELSOUNDSCACHE_VERSION, 0, UTL_CACHED_FILE_USE_FILESIZE, false ); void ClearModelSoundsCache() { if ( IsX360() ) { return; } g_ModelSoundsCache.Reload(); } //----------------------------------------------------------------------------- // Purpose: // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool ModelSoundsCacheInit() { if ( IsX360() ) { return true; } return g_ModelSoundsCache.Init(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void ModelSoundsCacheShutdown() { if ( IsX360() ) { return; } g_ModelSoundsCache.Shutdown(); } static CUtlSymbolTable g_ModelSoundsSymbolHelper( 0, 32, true ); class CModelSoundsCacheSaver: public CAutoGameSystem { public: CModelSoundsCacheSaver( const char *name ) : CAutoGameSystem( name ) { } virtual void LevelInitPostEntity() { if ( IsX360() ) { return; } if ( g_ModelSoundsCache.IsDirty() ) { g_ModelSoundsCache.Save(); } } virtual void LevelShutdownPostEntity() { if ( IsX360() ) { // Unforunate that this table must persist through duration of level. // It is the common case that PrecacheModel() still gets called (and needs this table), // after LevelInitPostEntity, as PrecacheModel() redundantly precaches. g_ModelSoundsSymbolHelper.RemoveAll(); return; } if ( g_ModelSoundsCache.IsDirty() ) { g_ModelSoundsCache.Save(); } } }; static CModelSoundsCacheSaver g_ModelSoundsCacheSaver( "CModelSoundsCacheSaver" ); //#define WATCHACCESS #if defined( WATCHACCESS ) static bool g_bWatching = true; void ModelLogFunc( const char *fileName, const char *accessType ) { if ( g_bWatching && !CBaseEntity::IsPrecacheAllowed() ) { if ( Q_stristr( fileName, ".vcd" ) ) { Msg( "%s\n", fileName ); } } } class CWatchForModelAccess: public CAutoGameSystem { public: virtual bool Init() { filesystem->AddLoggingFunc(&ModelLogFunc); return true; } virtual void Shutdown() { filesystem->RemoveLoggingFunc(&ModelLogFunc); } }; static CWatchForModelAccess g_WatchForModels; #endif // HACK: This must match the #define in cl_animevent.h in the client .dll code!!! #define CL_EVENT_SOUND 5004 #define CL_EVENT_FOOTSTEP_LEFT 6004 #define CL_EVENT_FOOTSTEP_RIGHT 6005 #define CL_EVENT_MFOOTSTEP_LEFT 6006 #define CL_EVENT_MFOOTSTEP_RIGHT 6007 //----------------------------------------------------------------------------- // Precache model sound. Requires a local symbol table to prevent // a very expensive call to PrecacheScriptSound(). //----------------------------------------------------------------------------- void CBaseEntity::PrecacheSoundHelper( const char *pName ) { if ( !IsX360() ) { // 360 only Assert( 0 ); return; } if ( !pName || !pName[0] ) { return; } if ( UTL_INVAL_SYMBOL == g_ModelSoundsSymbolHelper.Find( pName ) ) { g_ModelSoundsSymbolHelper.AddString( pName ); // very expensive, only call when required PrecacheScriptSound( pName ); } } //----------------------------------------------------------------------------- // Precache model components //----------------------------------------------------------------------------- void CBaseEntity::PrecacheModelComponents( int nModelIndex ) { model_t *pModel = (model_t *)modelinfo->GetModel( nModelIndex ); if ( !pModel || modelinfo->GetModelType( pModel ) != mod_studio ) { return; } // sounds if ( IsPC() ) { const char *name = modelinfo->GetModelName( pModel ); if ( !g_ModelSoundsCache.EntryExists( name ) ) { char extension[ 8 ]; Q_ExtractFileExtension( name, extension, sizeof( extension ) ); if ( Q_stristr( extension, "mdl" ) ) { DevMsg( 2, "Late precache of %s, need to rebuild modelsounds.cache\n", name ); } else { if ( !extension[ 0 ] ) { Warning( "Precache of %s ambigious (no extension specified)\n", name ); } else { Warning( "Late precache of %s (file missing?)\n", name ); } return; } } CModelSoundsCache *entry = g_ModelSoundsCache.Get( name ); Assert( entry ); if ( entry ) { entry->PrecacheSoundList(); } } // particles { // Check keyvalues for auto-emitting particles KeyValues *pModelKeyValues = new KeyValues(""); KeyValues::AutoDelete autodelete_pModelKeyValues( pModelKeyValues ); if ( pModelKeyValues->LoadFromBuffer( modelinfo->GetModelName( pModel ), modelinfo->GetModelKeyValueText( pModel ) ) ) { KeyValues *pParticleEffects = pModelKeyValues->FindKey("Particles"); if ( pParticleEffects ) { // Start grabbing the sounds and slotting them in for ( KeyValues *pSingleEffect = pParticleEffects->GetFirstSubKey(); pSingleEffect; pSingleEffect = pSingleEffect->GetNextKey() ) { const char *pParticleEffectName = pSingleEffect->GetString( "name", "" ); PrecacheParticleSystem( pParticleEffectName ); } } } } // model anim event owned components { // Check animevents for particle events CStudioHdr studioHdr( modelinfo->GetStudiomodel( pModel ), mdlcache ); if ( studioHdr.IsValid() ) { // force animation event resolution!!! VerifySequenceIndex( &studioHdr ); int nSeqCount = studioHdr.GetNumSeq(); for ( int i = 0; i < nSeqCount; ++i ) { mstudioseqdesc_t &seq = studioHdr.pSeqdesc( i ); int nEventCount = seq.numevents; for ( int j = 0; j < nEventCount; ++j ) { mstudioevent_t *pEvent = seq.pEvent( j ); if ( !( pEvent->type & AE_TYPE_NEWEVENTSYSTEM ) || ( pEvent->type & AE_TYPE_CLIENT ) ) { if ( pEvent->event == AE_CL_CREATE_PARTICLE_EFFECT ) { char token[256]; const char *pOptions = pEvent->pszOptions(); nexttoken( token, pOptions, ' ' ); if ( token ) { PrecacheParticleSystem( token ); } continue; } } // 360 precaches the model sounds now at init time, the cost is now ~250 msecs worst case. // The disk based solution was not needed. Now at runtime partly due to already crawling the sequences // for the particles and the expensive part was redundant PrecacheScriptSound(), which is now prevented // by a local symbol table. if ( IsX360() ) { switch ( pEvent->event ) { default: { if ( ( pEvent->type & AE_TYPE_NEWEVENTSYSTEM ) && ( pEvent->event == AE_SV_PLAYSOUND ) ) { PrecacheSoundHelper( pEvent->pszOptions() ); } } break; case CL_EVENT_FOOTSTEP_LEFT: case CL_EVENT_FOOTSTEP_RIGHT: { char soundname[256]; char const *options = pEvent->pszOptions(); if ( !options || !options[0] ) { options = "NPC_CombineS"; } Q_snprintf( soundname, sizeof( soundname ), "%s.RunFootstepLeft", options ); PrecacheSoundHelper( soundname ); Q_snprintf( soundname, sizeof( soundname ), "%s.RunFootstepRight", options ); PrecacheSoundHelper( soundname ); Q_snprintf( soundname, sizeof( soundname ), "%s.FootstepLeft", options ); PrecacheSoundHelper( soundname ); Q_snprintf( soundname, sizeof( soundname ), "%s.FootstepRight", options ); PrecacheSoundHelper( soundname ); } break; case AE_CL_PLAYSOUND: { if ( !( pEvent->type & AE_TYPE_CLIENT ) ) break; if ( pEvent->pszOptions()[0] ) { PrecacheSoundHelper( pEvent->pszOptions() ); } else { Warning( "-- Error --: empty soundname, .qc error on AE_CL_PLAYSOUND in model %s, sequence %s, animevent # %i\n", studioHdr.GetRenderHdr()->pszName(), seq.pszLabel(), j+1 ); } } break; case CL_EVENT_SOUND: case SCRIPT_EVENT_SOUND: case SCRIPT_EVENT_SOUND_VOICE: { PrecacheSoundHelper( pEvent->pszOptions() ); } break; } } } } } } } //----------------------------------------------------------------------------- // Purpose: Add model to level precache list // Input : *name - model name // Output : int -- model index for model //----------------------------------------------------------------------------- int CBaseEntity::PrecacheModel( const char *name, bool bPreload ) { if ( !name || !*name ) { Msg( "Attempting to precache model, but model name is NULL\n"); return -1; } // Warn on out of order precache if ( !CBaseEntity::IsPrecacheAllowed() ) { if ( !engine->IsModelPrecached( name ) ) { Assert( !"CBaseEntity::PrecacheModel: too late" ); Warning( "Late precache of %s\n", name ); } } #if defined( WATCHACCESS ) else { g_bWatching = false; } #endif int idx = engine->PrecacheModel( name, bPreload ); if ( idx != -1 ) { PrecacheModelComponents( idx ); } #if defined( WATCHACCESS ) g_bWatching = true; #endif return idx; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseEntity::Remove( ) { UTIL_Remove( this ); } // Entity degugging console commands extern CBaseEntity *FindPickerEntity( CBasePlayer *pPlayer ); extern void SetDebugBits( CBasePlayer* pPlayer, const char *name, int bit ); extern CBaseEntity *GetNextCommandEntity( CBasePlayer *pPlayer, const char *name, CBaseEntity *ent ); //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void ConsoleFireTargets( CBasePlayer *pPlayer, const char *name) { // If no name was given use the picker if (FStrEq(name,"")) { CBaseEntity *pEntity = FindPickerEntity( pPlayer ); if ( pEntity && !pEntity->IsMarkedForDeletion()) { Msg( "[%03d] Found: %s, firing\n", gpGlobals->tickcount%1000, pEntity->GetDebugName()); pEntity->Use( pPlayer, pPlayer, USE_TOGGLE, 0 ); return; } } // Otherwise use name or classname FireTargets( name, pPlayer, pPlayer, USE_TOGGLE, 0 ); } //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CC_Ent_Name( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_NAME_BIT); } static ConCommand ent_name("ent_name", CC_Ent_Name, 0, FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_Text( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_TEXT_BIT); } static ConCommand ent_text("ent_text", CC_Ent_Text, "Displays text debugging information about the given entity(ies) on top of the entity (See Overlay Text)\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_BBox( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_BBOX_BIT); } static ConCommand ent_bbox("ent_bbox", CC_Ent_BBox, "Displays the movement bounding box for the given entity(ies) in orange. Some entites will also display entity specific overlays.\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_AbsBox( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_ABSBOX_BIT); } static ConCommand ent_absbox("ent_absbox", CC_Ent_AbsBox, "Displays the total bounding box for the given entity(s) in green. Some entites will also display entity specific overlays.\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_RBox( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_RBOX_BIT); } static ConCommand ent_rbox("ent_rbox", CC_Ent_RBox, "Displays the total bounding box for the given entity(s) in green. Some entites will also display entity specific overlays.\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_AttachmentPoints( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_ATTACHMENTS_BIT); } static ConCommand ent_attachments("ent_attachments", CC_Ent_AttachmentPoints, "Displays the attachment points on an entity.\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_ViewOffset( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_VIEWOFFSET); } static ConCommand ent_viewoffset("ent_viewoffset", CC_Ent_ViewOffset, "Displays the eye position for the given entity(ies) in red.\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_Remove( const CCommand& args ) { CBaseEntity *pEntity = NULL; // If no name was given set bits based on the picked if ( FStrEq( args[1],"") ) { pEntity = FindPickerEntity( UTIL_GetCommandClient() ); } else { int index = atoi( args[1] ); if ( index ) { pEntity = CBaseEntity::Instance( index ); } else { // Otherwise set bits based on name or classname CBaseEntity *ent = NULL; while ( (ent = gEntList.NextEnt(ent)) != NULL ) { if ( (ent->GetEntityName() != NULL_STRING && FStrEq(args[1], STRING(ent->GetEntityName()))) || (ent->m_iClassname != NULL_STRING && FStrEq(args[1], STRING(ent->m_iClassname))) || (ent->GetClassname()!=NULL && FStrEq(args[1], ent->GetClassname()))) { pEntity = ent; break; } } } } // Found one? if ( pEntity ) { Msg( "Removed %s(%s)\n", STRING(pEntity->m_iClassname), pEntity->GetDebugName() ); UTIL_Remove( pEntity ); } } static ConCommand ent_remove("ent_remove", CC_Ent_Remove, "Removes the given entity(s)\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_RemoveAll( const CCommand& args ) { // If no name was given remove based on the picked if ( args.ArgC() < 2 ) { Msg( "Removes all entities of the specified type\n\tArguments: {entity_name} / {class_name}\n" ); } else { // Otherwise remove based on name or classname int iCount = 0; CBaseEntity *ent = NULL; while ( (ent = gEntList.NextEnt(ent)) != NULL ) { if ( (ent->GetEntityName() != NULL_STRING && FStrEq(args[1], STRING(ent->GetEntityName()))) || (ent->m_iClassname != NULL_STRING && FStrEq(args[1], STRING(ent->m_iClassname))) || (ent->GetClassname()!=NULL && FStrEq(args[1], ent->GetClassname()))) { UTIL_Remove( ent ); iCount++; } } if ( iCount ) { Msg( "Removed %d %s's\n", iCount, args[1] ); } else { Msg( "No %s found.\n", args[1] ); } } } static ConCommand ent_remove_all("ent_remove_all", CC_Ent_RemoveAll, "Removes all entities of the specified type\n\tArguments: {entity_name} / {class_name} ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Ent_SetName( const CCommand& args ) { CBaseEntity *pEntity = NULL; if ( args.ArgC() < 1 ) { CBasePlayer *pPlayer = ToBasePlayer( UTIL_GetCommandClient() ); if (!pPlayer) return; ClientPrint( pPlayer, HUD_PRINTCONSOLE, "Usage:\n ent_setname <new name> <entity name>\n" ); } else { // If no name was given set bits based on the picked if ( FStrEq( args[2],"") ) { pEntity = FindPickerEntity( UTIL_GetCommandClient() ); } else { // Otherwise set bits based on name or classname CBaseEntity *ent = NULL; while ( (ent = gEntList.NextEnt(ent)) != NULL ) { if ( (ent->GetEntityName() != NULL_STRING && FStrEq(args[1], STRING(ent->GetEntityName()))) || (ent->m_iClassname != NULL_STRING && FStrEq(args[1], STRING(ent->m_iClassname))) || (ent->GetClassname()!=NULL && FStrEq(args[1], ent->GetClassname()))) { pEntity = ent; break; } } } // Found one? if ( pEntity ) { Msg( "Set the name of %s to %s\n", STRING(pEntity->m_iClassname), args[1] ); pEntity->SetName( AllocPooledString( args[1] ) ); } } } static ConCommand ent_setname("ent_setname", CC_Ent_SetName, "Sets the targetname of the given entity(s)\n\tArguments: {new entity name} {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Find_Ent( const CCommand& args ) { if ( args.ArgC() < 2 ) { Msg( "Total entities: %d (%d edicts)\n", gEntList.NumberOfEntities(), gEntList.NumberOfEdicts() ); Msg( "Format: find_ent <substring>\n" ); return; } int iCount = 0; const char *pszSubString = args[1]; Msg("Searching for entities with class/target name containing substring: '%s'\n", pszSubString ); CBaseEntity *ent = NULL; while ( (ent = gEntList.NextEnt(ent)) != NULL ) { const char *pszClassname = ent->GetClassname(); const char *pszTargetname = STRING(ent->GetEntityName()); bool bMatches = false; if ( pszClassname && pszClassname[0] ) { if ( Q_stristr( pszClassname, pszSubString ) ) { bMatches = true; } } if ( !bMatches && pszTargetname && pszTargetname[0] ) { if ( Q_stristr( pszTargetname, pszSubString ) ) { bMatches = true; } } if ( bMatches ) { iCount++; Msg(" '%s' : '%s' (entindex %d) \n", ent->GetClassname(), ent->GetEntityName().ToCStr(), ent->entindex() ); } } Msg("Found %d matches.\n", iCount); } static ConCommand find_ent("find_ent", CC_Find_Ent, "Find and list all entities with classnames or targetnames that contain the specified substring.\nFormat: find_ent <substring>\n", FCVAR_CHEAT); //------------------------------------------------------------------------------ void CC_Find_Ent_Index( const CCommand& args ) { if ( args.ArgC() < 2 ) { Msg( "Format: find_ent_index <index>\n" ); return; } int iIndex = atoi(args[1]); CBaseEntity *pEnt = UTIL_EntityByIndex( iIndex ); if ( pEnt ) { Msg(" '%s' : '%s' (entindex %d) \n", pEnt->GetClassname(), pEnt->GetEntityName().ToCStr(), iIndex ); } else { Msg("Found no entity at %d.\n", iIndex); } } static ConCommand find_ent_index("find_ent_index", CC_Find_Ent_Index, "Display data for entity matching specified index.\nFormat: find_ent_index <index>\n", FCVAR_CHEAT); // Purpose : //------------------------------------------------------------------------------ void CC_Ent_Dump( const CCommand& args ) { CBasePlayer *pPlayer = ToBasePlayer( UTIL_GetCommandClient() ); if (!pPlayer) { return; } if ( args.ArgC() < 2 ) { ClientPrint( pPlayer, HUD_PRINTCONSOLE, "Usage:\n ent_dump <entity name>\n" ); } else { // iterate through all the ents of this name, printing out their details CBaseEntity *ent = NULL; bool bFound = false; while ( ( ent = gEntList.FindEntityByName(ent, args[1] ) ) != NULL ) { bFound = true; for ( datamap_t *dmap = ent->GetDataDescMap(); dmap != NULL; dmap = dmap->baseMap ) { // search through all the actions in the data description, printing out details for ( int i = 0; i < dmap->dataNumFields; i++ ) { variant_t var; if ( ent->ReadKeyField( dmap->dataDesc[i].externalName, &var) ) { char buf[256]; buf[0] = 0; switch( var.FieldType() ) { case FIELD_STRING: Q_strncpy( buf, var.String() ,sizeof(buf)); break; case FIELD_INTEGER: if ( var.Int() ) Q_snprintf( buf,sizeof(buf), "%d", var.Int() ); break; case FIELD_FLOAT: if ( var.Float() ) Q_snprintf( buf,sizeof(buf), "%.2f", var.Float() ); break; case FIELD_EHANDLE: { // get the entities name if ( var.Entity() ) { Q_snprintf( buf,sizeof(buf), "%s", STRING(var.Entity()->GetEntityName()) ); } } break; } // don't print out the duplicate keys if ( !Q_stricmp("parentname",dmap->dataDesc[i].externalName) || !Q_stricmp("targetname",dmap->dataDesc[i].externalName) ) continue; // don't print out empty keys if ( buf[0] ) { ClientPrint( pPlayer, HUD_PRINTCONSOLE, UTIL_VarArgs(" %s: %s\n", dmap->dataDesc[i].externalName, buf) ); } } } } } if ( !bFound ) { ClientPrint( pPlayer, HUD_PRINTCONSOLE, "ent_dump: no such entity" ); } } } static ConCommand ent_dump("ent_dump", CC_Ent_Dump, "Usage:\n ent_dump <entity name>\n", FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CC_Ent_FireTarget( const CCommand& args ) { ConsoleFireTargets(UTIL_GetCommandClient(),args[1]); } static ConCommand firetarget("firetarget", CC_Ent_FireTarget, 0, FCVAR_CHEAT); static bool UtlStringLessFunc( const CUtlString &lhs, const CUtlString &rhs ) { return Q_stricmp( lhs.String(), rhs.String() ) < 0; } class CEntFireAutoCompletionFunctor : public ICommandCallback, public ICommandCompletionCallback { public: virtual void CommandCallback( const CCommand &command ) { CBasePlayer *pPlayer = ToBasePlayer( UTIL_GetCommandClient() ); if (!pPlayer) { return; } // fires a command from the console if ( command.ArgC() < 2 ) { ClientPrint( pPlayer, HUD_PRINTCONSOLE, "Usage:\n ent_fire <target> [action] [value] [delay]\n" ); } else { const char *target = "", *action = "Use"; variant_t value; int delay = 0; target = STRING( AllocPooledString(command.Arg( 1 ) ) ); // Don't allow them to run anything on a point_servercommand unless they're the host player. Otherwise they can ent_fire // and run any command on the server. Admittedly, they can only do the ent_fire if sv_cheats is on, but // people complained about users resetting the rcon password if the server briefly turned on cheats like this: // give point_servercommand // ent_fire point_servercommand command "rcon_password mynewpassword" // // Robin: Unfortunately, they get around point_servercommand checks with this: // ent_create point_servercommand; ent_setname mine; ent_fire mine command "rcon_password mynewpassword" // So, I'm removing the ability for anyone to execute ent_fires on dedicated servers (we can't check to see if // this command is going to connect with a point_servercommand entity here, because they could delay the event and create it later). if ( engine->IsDedicatedServer() ) { // We allow people with disabled autokick to do it, because they already have rcon. if ( pPlayer->IsAutoKickDisabled() == false ) return; } else if ( gpGlobals->maxClients > 1 ) { // On listen servers with more than 1 player, only allow the host to issue ent_fires. CBasePlayer *pHostPlayer = UTIL_GetListenServerHost(); if ( pPlayer != pHostPlayer ) return; } if ( command.ArgC() >= 3 ) { action = STRING( AllocPooledString(command.Arg( 2 )) ); } if ( command.ArgC() >= 4 ) { value.SetString( AllocPooledString(command.Arg( 3 )) ); } if ( command.ArgC() >= 5 ) { delay = atoi( command.Arg( 4 ) ); } g_EventQueue.AddEvent( target, action, value, delay, pPlayer, pPlayer ); } } virtual int CommandCompletionCallback( const char *partial, CUtlVector< CUtlString > &commands ) { if ( !g_pGameRules ) { return 0; } const char *cmdname = "ent_fire"; char *substring = (char *)partial; if ( Q_strstr( partial, cmdname ) ) { substring = (char *)partial + strlen( cmdname ) + 1; } int checklen = 0; char *space = Q_strstr( substring, " " ); if ( space ) { return EntFire_AutoCompleteInput( partial, commands );; } else { checklen = Q_strlen( substring ); } CUtlRBTree< CUtlString > symbols( 0, 0, UtlStringLessFunc ); CBaseEntity *pos = NULL; while ( ( pos = gEntList.NextEnt( pos ) ) != NULL ) { // Check target name against partial string if ( pos->GetEntityName() == NULL_STRING ) continue; if ( Q_strnicmp( STRING( pos->GetEntityName() ), substring, checklen ) ) continue; CUtlString sym = STRING( pos->GetEntityName() ); int idx = symbols.Find( sym ); if ( idx == symbols.InvalidIndex() ) { symbols.Insert( sym ); } // Too many if ( symbols.Count() >= COMMAND_COMPLETION_MAXITEMS ) break; } // Now fill in the results for ( int i = symbols.FirstInorder(); i != symbols.InvalidIndex(); i = symbols.NextInorder( i ) ) { const char *name = symbols[ i ].String(); char buf[ 512 ]; Q_strncpy( buf, name, sizeof( buf ) ); Q_strlower( buf ); CUtlString command; command = CFmtStr( "%s %s", cmdname, buf ); commands.AddToTail( command ); } return symbols.Count(); } private: int EntFire_AutoCompleteInput( const char *partial, CUtlVector< CUtlString > &commands ) { const char *cmdname = "ent_fire"; char *substring = (char *)partial; if ( Q_strstr( partial, cmdname ) ) { substring = (char *)partial + strlen( cmdname ) + 1; } int checklen = 0; char *space = Q_strstr( substring, " " ); if ( !space ) { Assert( !"CC_EntFireAutoCompleteInputFunc is broken\n" ); return 0; } checklen = Q_strlen( substring ); char targetEntity[ 256 ]; targetEntity[0] = 0; int nEntityNameLength = (space-substring); Q_strncat( targetEntity, substring, sizeof( targetEntity ), nEntityNameLength ); // Find the target entity by name CBaseEntity *target = gEntList.FindEntityByName( NULL, targetEntity ); if ( target == NULL ) return 0; CUtlRBTree< CUtlString > symbols( 0, 0, UtlStringLessFunc ); // Find the next portion of the text chain, if any (removing space) int nInputNameLength = (checklen-nEntityNameLength-1); // Starting past the last space, this is the remainder of the string char *inputPartial = ( checklen > nEntityNameLength ) ? (space+1) : NULL; for ( datamap_t *dmap = target->GetDataDescMap(); dmap != NULL; dmap = dmap->baseMap ) { // Make sure we don't keep adding things in if the satisfied the limit if ( symbols.Count() >= COMMAND_COMPLETION_MAXITEMS ) break; int c = dmap->dataNumFields; for ( int i = 0; i < c; i++ ) { typedescription_t *field = &dmap->dataDesc[ i ]; // Only want inputs if ( !( field->flags & FTYPEDESC_INPUT ) ) continue; // Only want input functions if ( field->flags & FTYPEDESC_SAVE ) continue; // See if we've got a partial string for the input name already if ( inputPartial != NULL ) { if ( Q_strnicmp( inputPartial, field->externalName, nInputNameLength ) ) continue; } CUtlString sym = field->externalName; int idx = symbols.Find( sym ); if ( idx == symbols.InvalidIndex() ) { symbols.Insert( sym ); } // Too many items have been added if ( symbols.Count() >= COMMAND_COMPLETION_MAXITEMS ) break; } } // Now fill in the results for ( int i = symbols.FirstInorder(); i != symbols.InvalidIndex(); i = symbols.NextInorder( i ) ) { const char *name = symbols[ i ].String(); char buf[ 512 ]; Q_strncpy( buf, name, sizeof( buf ) ); Q_strlower( buf ); CUtlString command; command = CFmtStr( "%s %s %s", cmdname, targetEntity, buf ); commands.AddToTail( command ); } return symbols.Count(); } }; static CEntFireAutoCompletionFunctor g_EntFireAutoComplete; static ConCommand ent_fire("ent_fire", &g_EntFireAutoComplete, "Usage:\n ent_fire <target> [action] [value] [delay]\n", FCVAR_CHEAT, &g_EntFireAutoComplete ); void CC_Ent_CancelPendingEntFires( const CCommand& args ) { if ( !UTIL_IsCommandIssuedByServerAdmin() ) return; CBasePlayer *pPlayer = ToBasePlayer( UTIL_GetCommandClient() ); if (!pPlayer) return; g_EventQueue.CancelEvents( pPlayer ); } static ConCommand ent_cancelpendingentfires("ent_cancelpendingentfires", CC_Ent_CancelPendingEntFires, "Cancels all ent_fire created outputs that are currently waiting for their delay to expire." ); //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CC_Ent_Info( const CCommand& args ) { CBasePlayer *pPlayer = ToBasePlayer( UTIL_GetCommandClient() ); if (!pPlayer) { return; } if ( args.ArgC() < 2 ) { ClientPrint( pPlayer, HUD_PRINTCONSOLE, "Usage:\n ent_info <class name>\n" ); } else { // iterate through all the ents printing out their details CBaseEntity *ent = CreateEntityByName( args[1] ); if ( ent ) { datamap_t *dmap; for ( dmap = ent->GetDataDescMap(); dmap != NULL; dmap = dmap->baseMap ) { // search through all the actions in the data description, printing out details for ( int i = 0; i < dmap->dataNumFields; i++ ) { if ( dmap->dataDesc[i].flags & FTYPEDESC_OUTPUT ) { ClientPrint( pPlayer, HUD_PRINTCONSOLE, UTIL_VarArgs(" output: %s\n", dmap->dataDesc[i].externalName) ); } } } for ( dmap = ent->GetDataDescMap(); dmap != NULL; dmap = dmap->baseMap ) { // search through all the actions in the data description, printing out details for ( int i = 0; i < dmap->dataNumFields; i++ ) { if ( dmap->dataDesc[i].flags & FTYPEDESC_INPUT ) { ClientPrint( pPlayer, HUD_PRINTCONSOLE, UTIL_VarArgs(" input: %s\n", dmap->dataDesc[i].externalName) ); } } } delete ent; } else { ClientPrint( pPlayer, HUD_PRINTCONSOLE, UTIL_VarArgs("no such entity %s\n", args[1]) ); } } } static ConCommand ent_info("ent_info", CC_Ent_Info, "Usage:\n ent_info <class name>\n", FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CC_Ent_Messages( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_MESSAGE_BIT); } static ConCommand ent_messages("ent_messages", CC_Ent_Messages ,"Toggles input/output message display for the selected entity(ies). The name of the entity will be displayed as well as any messages that it sends or receives.\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at", FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CC_Ent_Pause( void ) { if (CBaseEntity::Debug_IsPaused()) { Msg( "Resuming entity I/O events\n" ); CBaseEntity::Debug_Pause(false); } else { Msg( "Pausing entity I/O events\n" ); CBaseEntity::Debug_Pause(true); } } static ConCommand ent_pause("ent_pause", CC_Ent_Pause, "Toggles pausing of input/output message processing for entities. When turned on processing of all message will stop. Any messages displayed with 'ent_messages' will stop fading and be displayed indefinitely. To step through the messages one by one use 'ent_step'.", FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose : Enables the entity picker, revelaing debug information about the // entity under the crosshair. // Input : an optional command line argument "full" enables all debug info. // Output : //------------------------------------------------------------------------------ void CC_Ent_Picker( void ) { CBaseEntity::m_bInDebugSelect = CBaseEntity::m_bInDebugSelect ? false : true; // Remember the player that's making this request CBaseEntity::m_nDebugPlayer = UTIL_GetCommandClientIndex(); } static ConCommand picker("picker", CC_Ent_Picker, "Toggles 'picker' mode. When picker is on, the bounding box, pivot and debugging text is displayed for whatever entity the player is looking at.\n\tArguments: full - enables all debug information", FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CC_Ent_Pivot( const CCommand& args ) { SetDebugBits(UTIL_GetCommandClient(),args[1],OVERLAY_PIVOT_BIT); } static ConCommand ent_pivot("ent_pivot", CC_Ent_Pivot, "Displays the pivot for the given entity(ies).\n\t(y=up=green, z=forward=blue, x=left=red). \n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void CC_Ent_Step( const CCommand& args ) { int nSteps = atoi(args[1]); if (nSteps <= 0) { nSteps = 1; } CBaseEntity::Debug_SetSteps(nSteps); } static ConCommand ent_step("ent_step", CC_Ent_Step, "When 'ent_pause' is set this will step through one waiting input / output message at a time.", FCVAR_CHEAT); void CBaseEntity::SetCheckUntouch( bool check ) { // Invalidate touchstamp if ( check ) { touchStamp++; if ( !IsEFlagSet( EFL_CHECK_UNTOUCH ) ) { AddEFlags( EFL_CHECK_UNTOUCH ); EntityTouch_Add( this ); } } else { RemoveEFlags( EFL_CHECK_UNTOUCH ); } } model_t *CBaseEntity::GetModel( void ) { return (model_t *)modelinfo->GetModel( GetModelIndex() ); } //----------------------------------------------------------------------------- // Purpose: Calculates the absolute position of an edict in the world // assumes the parent's absolute origin has already been calculated //----------------------------------------------------------------------------- void CBaseEntity::CalcAbsolutePosition( void ) { if (!IsEFlagSet( EFL_DIRTY_ABSTRANSFORM )) return; RemoveEFlags( EFL_DIRTY_ABSTRANSFORM ); // Plop the entity->parent matrix into m_rgflCoordinateFrame AngleMatrix( m_angRotation, m_vecOrigin, m_rgflCoordinateFrame ); CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { // no move parent, so just copy existing values m_vecAbsOrigin = m_vecOrigin; m_angAbsRotation = m_angRotation; if ( HasDataObjectType( POSITIONWATCHER ) ) { ReportPositionChanged( this ); } return; } // concatenate with our parent's transform matrix3x4_t tmpMatrix, scratchSpace; ConcatTransforms( GetParentToWorldTransform( scratchSpace ), m_rgflCoordinateFrame, tmpMatrix ); MatrixCopy( tmpMatrix, m_rgflCoordinateFrame ); // pull our absolute position out of the matrix MatrixGetColumn( m_rgflCoordinateFrame, 3, m_vecAbsOrigin ); // if we have any angles, we have to extract our absolute angles from our matrix if (( m_angRotation == vec3_angle ) && ( m_iParentAttachment == 0 )) { // just copy our parent's absolute angles VectorCopy( pMoveParent->GetAbsAngles(), m_angAbsRotation ); } else { MatrixAngles( m_rgflCoordinateFrame, m_angAbsRotation ); } if ( HasDataObjectType( POSITIONWATCHER ) ) { ReportPositionChanged( this ); } } void CBaseEntity::CalcAbsoluteVelocity() { if (!IsEFlagSet( EFL_DIRTY_ABSVELOCITY )) return; RemoveEFlags( EFL_DIRTY_ABSVELOCITY ); CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { m_vecAbsVelocity = m_vecVelocity; return; } // This transforms the local velocity into world space VectorRotate( m_vecVelocity, pMoveParent->EntityToWorldTransform(), m_vecAbsVelocity ); // Now add in the parent abs velocity m_vecAbsVelocity += pMoveParent->GetAbsVelocity(); } // FIXME: While we're using (dPitch, dYaw, dRoll) as our local angular velocity // representation, we can't actually solve this problem /* void CBaseEntity::CalcAbsoluteAngularVelocity() { if (!IsEFlagSet( EFL_DIRTY_ABSANGVELOCITY )) return; RemoveEFlags( EFL_DIRTY_ABSANGVELOCITY ); CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { m_vecAbsAngVelocity = m_vecAngVelocity; return; } // This transforms the local ang velocity into world space matrix3x4_t angVelToParent, angVelToWorld; AngleMatrix( m_vecAngVelocity, angVelToParent ); ConcatTransforms( pMoveParent->EntityToWorldTransform(), angVelToParent, angVelToWorld ); MatrixAngles( angVelToWorld, m_vecAbsAngVelocity ); } */ //----------------------------------------------------------------------------- // Computes the abs position of a point specified in local space //----------------------------------------------------------------------------- void CBaseEntity::ComputeAbsPosition( const Vector &vecLocalPosition, Vector *pAbsPosition ) { CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { *pAbsPosition = vecLocalPosition; } else { VectorTransform( vecLocalPosition, pMoveParent->EntityToWorldTransform(), *pAbsPosition ); } } //----------------------------------------------------------------------------- // Computes the abs position of a point specified in local space //----------------------------------------------------------------------------- void CBaseEntity::ComputeAbsDirection( const Vector &vecLocalDirection, Vector *pAbsDirection ) { CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { *pAbsDirection = vecLocalDirection; } else { VectorRotate( vecLocalDirection, pMoveParent->EntityToWorldTransform(), *pAbsDirection ); } } matrix3x4_t& CBaseEntity::GetParentToWorldTransform( matrix3x4_t &tempMatrix ) { CBaseEntity *pMoveParent = GetMoveParent(); if ( !pMoveParent ) { Assert( false ); SetIdentityMatrix( tempMatrix ); return tempMatrix; } if ( m_iParentAttachment != 0 ) { MDLCACHE_CRITICAL_SECTION(); CBaseAnimating *pAnimating = pMoveParent->GetBaseAnimating(); if ( pAnimating && pAnimating->GetAttachment( m_iParentAttachment, tempMatrix ) ) { return tempMatrix; } } // If we fall through to here, then just use the move parent's abs origin and angles. return pMoveParent->EntityToWorldTransform(); } //----------------------------------------------------------------------------- // These methods recompute local versions as well as set abs versions //----------------------------------------------------------------------------- void CBaseEntity::SetAbsOrigin( const Vector& absOrigin ) { AssertMsg( absOrigin.IsValid(), "Invalid origin set" ); // This is necessary to get the other fields of m_rgflCoordinateFrame ok CalcAbsolutePosition(); if ( m_vecAbsOrigin == absOrigin ) return; // All children are invalid, but we are not InvalidatePhysicsRecursive( POSITION_CHANGED ); RemoveEFlags( EFL_DIRTY_ABSTRANSFORM ); m_vecAbsOrigin = absOrigin; MatrixSetColumn( absOrigin, 3, m_rgflCoordinateFrame ); Vector vecNewOrigin; CBaseEntity *pMoveParent = GetMoveParent(); if (!pMoveParent) { vecNewOrigin = absOrigin; } else { matrix3x4_t tempMat; matrix3x4_t &parentTransform = GetParentToWorldTransform( tempMat ); // Moveparent case: transform the abs position into local space VectorITransform( absOrigin, parentTransform, vecNewOrigin ); } if (m_vecOrigin != vecNewOrigin) { m_vecOrigin = vecNewOrigin; SetSimulationTime( gpGlobals->curtime ); } } void CBaseEntity::SetAbsAngles( const QAngle& absAngles ) { // This is necessary to get the other fields of m_rgflCoordinateFrame ok CalcAbsolutePosition(); // FIXME: The normalize caused problems in server code like momentary_rot_button that isn't // handling things like +/-180 degrees properly. This should be revisited. //QAngle angleNormalize( AngleNormalize( absAngles.x ), AngleNormalize( absAngles.y ), AngleNormalize( absAngles.z ) ); if ( m_angAbsRotation == absAngles ) return; // All children are invalid, but we are not InvalidatePhysicsRecursive( ANGLES_CHANGED ); RemoveEFlags( EFL_DIRTY_ABSTRANSFORM ); m_angAbsRotation = absAngles; AngleMatrix( absAngles, m_rgflCoordinateFrame ); MatrixSetColumn( m_vecAbsOrigin, 3, m_rgflCoordinateFrame ); QAngle angNewRotation; CBaseEntity *pMoveParent = GetMoveParent(); if (!pMoveParent) { angNewRotation = absAngles; } else { if ( m_angAbsRotation == pMoveParent->GetAbsAngles() ) { angNewRotation.Init( ); } else { // Moveparent case: transform the abs transform into local space matrix3x4_t worldToParent, localMatrix; MatrixInvert( pMoveParent->EntityToWorldTransform(), worldToParent ); ConcatTransforms( worldToParent, m_rgflCoordinateFrame, localMatrix ); MatrixAngles( localMatrix, angNewRotation ); } } if (m_angRotation != angNewRotation) { m_angRotation = angNewRotation; SetSimulationTime( gpGlobals->curtime ); } } void CBaseEntity::SetAbsVelocity( const Vector &vecAbsVelocity ) { if ( m_vecAbsVelocity == vecAbsVelocity ) return; // The abs velocity won't be dirty since we're setting it here // All children are invalid, but we are not InvalidatePhysicsRecursive( VELOCITY_CHANGED ); RemoveEFlags( EFL_DIRTY_ABSVELOCITY ); m_vecAbsVelocity = vecAbsVelocity; // NOTE: Do *not* do a network state change in this case. // m_vecVelocity is only networked for the player, which is not manual mode CBaseEntity *pMoveParent = GetMoveParent(); if (!pMoveParent) { m_vecVelocity = vecAbsVelocity; return; } // First subtract out the parent's abs velocity to get a relative // velocity measured in world space Vector relVelocity; VectorSubtract( vecAbsVelocity, pMoveParent->GetAbsVelocity(), relVelocity ); // Transform relative velocity into parent space Vector vNew; VectorIRotate( relVelocity, pMoveParent->EntityToWorldTransform(), vNew ); m_vecVelocity = vNew; } // FIXME: While we're using (dPitch, dYaw, dRoll) as our local angular velocity // representation, we can't actually solve this problem /* void CBaseEntity::SetAbsAngularVelocity( const QAngle &vecAbsAngVelocity ) { // The abs velocity won't be dirty since we're setting it here // All children are invalid, but we are not InvalidatePhysicsRecursive( EFL_DIRTY_ABSANGVELOCITY ); RemoveEFlags( EFL_DIRTY_ABSANGVELOCITY ); m_vecAbsAngVelocity = vecAbsAngVelocity; CBaseEntity *pMoveParent = GetMoveParent(); if (!pMoveParent) { m_vecAngVelocity = vecAbsAngVelocity; return; } // NOTE: We *can't* subtract out parent ang velocity, it's nonsensical matrix3x4_t entityToWorld; AngleMatrix( vecAbsAngVelocity, entityToWorld ); // Moveparent case: transform the abs relative angular vel into local space matrix3x4_t worldToParent, localMatrix; MatrixInvert( pMoveParent->EntityToWorldTransform(), worldToParent ); ConcatTransforms( worldToParent, entityToWorld, localMatrix ); MatrixAngles( localMatrix, m_vecAngVelocity ); } */ //----------------------------------------------------------------------------- // Methods that modify local physics state, and let us know to compute abs state later //----------------------------------------------------------------------------- void CBaseEntity::SetLocalOrigin( const Vector& origin ) { // Safety check against NaN's or really huge numbers if ( !IsEntityPositionReasonable( origin ) ) { if ( CheckEmitReasonablePhysicsSpew() ) { Warning( "Bad SetLocalOrigin(%f,%f,%f) on %s\n", origin.x, origin.y, origin.z, GetDebugName() ); } Assert( false ); return; } // if ( !origin.IsValid() ) // { // AssertMsg( 0, "Bad origin set" ); // return; // } if (m_vecOrigin != origin) { // Sanity check to make sure the origin is valid. #ifdef _DEBUG float largeVal = 1024 * 128; Assert( origin.x >= -largeVal && origin.x <= largeVal ); Assert( origin.y >= -largeVal && origin.y <= largeVal ); Assert( origin.z >= -largeVal && origin.z <= largeVal ); #endif InvalidatePhysicsRecursive( POSITION_CHANGED ); m_vecOrigin = origin; SetSimulationTime( gpGlobals->curtime ); } } void CBaseEntity::SetLocalAngles( const QAngle& angles ) { // NOTE: The angle normalize is a little expensive, but we can save // a bunch of time in interpolation if we don't have to invalidate everything // and sometimes it's off by a normalization amount // FIXME: The normalize caused problems in server code like momentary_rot_button that isn't // handling things like +/-180 degrees properly. This should be revisited. //QAngle angleNormalize( AngleNormalize( angles.x ), AngleNormalize( angles.y ), AngleNormalize( angles.z ) ); // Safety check against NaN's or really huge numbers if ( !IsEntityQAngleReasonable( angles ) ) { if ( CheckEmitReasonablePhysicsSpew() ) { Warning( "Bad SetLocalAngles(%f,%f,%f) on %s\n", angles.x, angles.y, angles.z, GetDebugName() ); } Assert( false ); return; } if (m_angRotation != angles) { InvalidatePhysicsRecursive( ANGLES_CHANGED ); m_angRotation = angles; SetSimulationTime( gpGlobals->curtime ); } } void CBaseEntity::SetLocalVelocity( const Vector &inVecVelocity ) { Vector vecVelocity = inVecVelocity; // Safety check against receive a huge impulse, which can explode physics switch ( CheckEntityVelocity( vecVelocity ) ) { case -1: Warning( "Discarding SetLocalVelocity(%f,%f,%f) on %s\n", vecVelocity.x, vecVelocity.y, vecVelocity.z, GetDebugName() ); Assert( false ); return; case 0: if ( CheckEmitReasonablePhysicsSpew() ) { Warning( "Clamping SetLocalVelocity(%f,%f,%f) on %s\n", inVecVelocity.x, inVecVelocity.y, inVecVelocity.z, GetDebugName() ); } break; } if (m_vecVelocity != vecVelocity) { InvalidatePhysicsRecursive( VELOCITY_CHANGED ); m_vecVelocity = vecVelocity; } } void CBaseEntity::SetLocalAngularVelocity( const QAngle &vecAngVelocity ) { // Safety check against NaN's or really huge numbers if ( !IsEntityQAngleVelReasonable( vecAngVelocity ) ) { if ( CheckEmitReasonablePhysicsSpew() ) { Warning( "Bad SetLocalAngularVelocity(%f,%f,%f) on %s\n", vecAngVelocity.x, vecAngVelocity.y, vecAngVelocity.z, GetDebugName() ); } Assert( false ); return; } if (m_vecAngVelocity != vecAngVelocity) { // InvalidatePhysicsRecursive( EFL_DIRTY_ABSANGVELOCITY ); m_vecAngVelocity = vecAngVelocity; } } //----------------------------------------------------------------------------- // Sets the local position from a transform //----------------------------------------------------------------------------- void CBaseEntity::SetLocalTransform( const matrix3x4_t &localTransform ) { // FIXME: Should angles go away? Should we just use transforms? Vector vecLocalOrigin; QAngle vecLocalAngles; MatrixGetColumn( localTransform, 3, vecLocalOrigin ); MatrixAngles( localTransform, vecLocalAngles ); SetLocalOrigin( vecLocalOrigin ); SetLocalAngles( vecLocalAngles ); } //----------------------------------------------------------------------------- // Is the entity floating? //----------------------------------------------------------------------------- bool CBaseEntity::IsFloating() { if ( !IsEFlagSet(EFL_TOUCHING_FLUID) ) return false; IPhysicsObject *pObject = VPhysicsGetObject(); if ( !pObject ) return false; int nMaterialIndex = pObject->GetMaterialIndex(); float flDensity; float flThickness; float flFriction; float flElasticity; physprops->GetPhysicsProperties( nMaterialIndex, &flDensity, &flThickness, &flFriction, &flElasticity ); // FIXME: This really only works for water at the moment.. // Owing the check for density == 1000 return (flDensity < 1000.0f); } //----------------------------------------------------------------------------- // Purpose: Created predictable and sets up Id. Note that persist is ignored on the server. // Input : *classname - // *module - // line - // persist - // Output : CBaseEntity //----------------------------------------------------------------------------- CBaseEntity *CBaseEntity::CreatePredictedEntityByName( const char *classname, const char *module, int line, bool persist /* = false */ ) { #if !defined( NO_ENTITY_PREDICTION ) CBasePlayer *player = CBaseEntity::GetPredictionPlayer(); Assert( player ); CBaseEntity *ent = NULL; int command_number = player->CurrentCommandNumber(); int player_index = player->entindex() - 1; CPredictableId testId; testId.Init( player_index, command_number, classname, module, line ); ent = CreateEntityByName( classname ); // No factory??? if ( !ent ) return NULL; ent->SetPredictionEligible( true ); // Set up "shared" id number ent->m_PredictableID.GetForModify().SetRaw( testId.GetRaw() ); return ent; #else return NULL; #endif } void CBaseEntity::SetPredictionEligible( bool canpredict ) { // Nothing in game code m_bPredictionEligible = canpredict; } //----------------------------------------------------------------------------- // These could be virtual, but only the player is overriding them // NOTE: If you make any of these virtual, remove this implementation!!! //----------------------------------------------------------------------------- void CBaseEntity::AddPoints( int score, bool bAllowNegativeScore ) { CBasePlayer *pPlayer = ToBasePlayer(this); if ( pPlayer ) { pPlayer->CBasePlayer::AddPoints( score, bAllowNegativeScore ); } } void CBaseEntity::AddPointsToTeam( int score, bool bAllowNegativeScore ) { CBasePlayer *pPlayer = ToBasePlayer(this); if ( pPlayer ) { pPlayer->CBasePlayer::AddPointsToTeam( score, bAllowNegativeScore ); } } void CBaseEntity::ViewPunch( const QAngle &angleOffset ) { CBasePlayer *pPlayer = ToBasePlayer(this); if ( pPlayer ) { pPlayer->CBasePlayer::ViewPunch( angleOffset ); } } void CBaseEntity::VelocityPunch( const Vector &vecForce ) { CBasePlayer *pPlayer = ToBasePlayer(this); if ( pPlayer ) { pPlayer->CBasePlayer::VelocityPunch( vecForce ); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Purpose: Tell clients to remove all decals from this entity //----------------------------------------------------------------------------- void CBaseEntity::RemoveAllDecals( void ) { EntityMessageBegin( this ); WRITE_BYTE( BASEENTITY_MSG_REMOVE_DECALS ); MessageEnd(); } //----------------------------------------------------------------------------- // Purpose: // Input : set - //----------------------------------------------------------------------------- void CBaseEntity::ModifyOrAppendCriteria( AI_CriteriaSet& set ) { // TODO // Append chapter/day? set.AppendCriteria( "randomnum", UTIL_VarArgs("%d", RandomInt(0,100)) ); // Append map name set.AppendCriteria( "map", gpGlobals->mapname.ToCStr() ); // Append our classname and game name set.AppendCriteria( "classname", GetClassname() ); set.AppendCriteria( "name", GetEntityName().ToCStr() ); // Append our health set.AppendCriteria( "health", UTIL_VarArgs( "%i", GetHealth() ) ); float healthfrac = 0.0f; if ( GetMaxHealth() > 0 ) { healthfrac = (float)GetHealth() / (float)GetMaxHealth(); } set.AppendCriteria( "healthfrac", UTIL_VarArgs( "%.3f", healthfrac ) ); // Go through all the global states and append them for ( int i = 0; i < GlobalEntity_GetNumGlobals(); i++ ) { const char *szGlobalName = GlobalEntity_GetName(i); int iGlobalState = (int)GlobalEntity_GetStateByIndex(i); set.AppendCriteria( szGlobalName, UTIL_VarArgs( "%i", iGlobalState ) ); } // Append anything from I/O or keyvalues pairs AppendContextToCriteria( set ); if( hl2_episodic.GetBool() ) { set.AppendCriteria( "episodic", "1" ); } // Append anything from world I/O/keyvalues with "world" as prefix CWorld *world = dynamic_cast< CWorld * >( CBaseEntity::Instance( engine->PEntityOfEntIndex( 0 ) ) ); if ( world ) { world->AppendContextToCriteria( set, "world" ); } } //----------------------------------------------------------------------------- // Purpose: // Input : set - // "" - //----------------------------------------------------------------------------- void CBaseEntity::AppendContextToCriteria( AI_CriteriaSet& set, const char *prefix /*= ""*/ ) { RemoveExpiredConcepts(); int c = GetContextCount(); int i; char sz[ 128 ]; for ( i = 0; i < c; i++ ) { const char *name = GetContextName( i ); const char *value = GetContextValue( i ); Q_snprintf( sz, sizeof( sz ), "%s%s", prefix, name ); set.AppendCriteria( sz, value ); } } //----------------------------------------------------------------------------- // Purpose: Removes expired concepts from list // Output : //----------------------------------------------------------------------------- void CBaseEntity::RemoveExpiredConcepts( void ) { int c = GetContextCount(); int i; for ( i = 0; i < c; i++ ) { if ( ContextExpired( i ) ) { m_ResponseContexts.Remove( i ); c--; i--; continue; } } } //----------------------------------------------------------------------------- // Purpose: Get current context count // Output : int //----------------------------------------------------------------------------- int CBaseEntity::GetContextCount() const { return m_ResponseContexts.Count(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : const char //----------------------------------------------------------------------------- const char *CBaseEntity::GetContextName( int index ) const { if ( index < 0 || index >= m_ResponseContexts.Count() ) { Assert( 0 ); return ""; } return m_ResponseContexts[ index ].m_iszName.ToCStr(); } //----------------------------------------------------------------------------- // Purpose: // Input : index - // Output : const char //----------------------------------------------------------------------------- const char *CBaseEntity::GetContextValue( int index ) const { if ( index < 0 || index >= m_ResponseContexts.Count() ) { Assert( 0 ); return ""; } return m_ResponseContexts[ index ].m_iszValue.ToCStr(); } //----------------------------------------------------------------------------- // Purpose: Check if context has expired // Input : index - // Output : bool //----------------------------------------------------------------------------- bool CBaseEntity::ContextExpired( int index ) const { if ( index < 0 || index >= m_ResponseContexts.Count() ) { Assert( 0 ); return true; } if ( !m_ResponseContexts[ index ].m_fExpirationTime ) { return false; } return ( m_ResponseContexts[ index ].m_fExpirationTime <= gpGlobals->curtime ); } //----------------------------------------------------------------------------- // Purpose: Search for index of named context string // Input : *name - // Output : int //----------------------------------------------------------------------------- int CBaseEntity::FindContextByName( const char *name ) const { int c = m_ResponseContexts.Count(); for ( int i = 0; i < c; i++ ) { if ( FStrEq( name, GetContextName( i ) ) ) return i; } return -1; } //----------------------------------------------------------------------------- // Purpose: // Input : inputdata - //----------------------------------------------------------------------------- void CBaseEntity::InputAddContext( inputdata_t& inputdata ) { const char *contextName = inputdata.value.String(); AddContext( contextName ); } //----------------------------------------------------------------------------- // Purpose: User inputs. These fire the corresponding user outputs, and are // a means of forwarding messages through !activator to a target known // known by !activator but not by the targetting entity. // // For example, say you have three identical trains, following the same // path. Each train has a sprite in hierarchy with it that needs to // toggle on/off as it passes each path_track. You would hook each train's // OnUser1 output to it's sprite's Toggle input, then connect each path_track's // OnPass output to !activator's FireUser1 input. //----------------------------------------------------------------------------- void CBaseEntity::InputFireUser1( inputdata_t& inputdata ) { m_OnUser1.FireOutput( inputdata.pActivator, this ); } void CBaseEntity::InputFireUser2( inputdata_t& inputdata ) { m_OnUser2.FireOutput( inputdata.pActivator, this ); } void CBaseEntity::InputFireUser3( inputdata_t& inputdata ) { m_OnUser3.FireOutput( inputdata.pActivator, this ); } void CBaseEntity::InputFireUser4( inputdata_t& inputdata ) { m_OnUser4.FireOutput( inputdata.pActivator, this ); } //----------------------------------------------------------------------------- // Purpose: // Input : *contextName - //----------------------------------------------------------------------------- void CBaseEntity::AddContext( const char *contextName ) { char key[ 128 ]; char value[ 128 ]; float duration; const char *p = contextName; while ( p ) { duration = 0.0f; p = SplitContext( p, key, sizeof( key ), value, sizeof( value ), &duration ); if ( duration ) { duration += gpGlobals->curtime; } int iIndex = FindContextByName( key ); if ( iIndex != -1 ) { // Set the existing context to the new value m_ResponseContexts[iIndex].m_iszValue = AllocPooledString( value ); m_ResponseContexts[iIndex].m_fExpirationTime = duration; continue; } ResponseContext_t newContext; newContext.m_iszName = AllocPooledString( key ); newContext.m_iszValue = AllocPooledString( value ); newContext.m_fExpirationTime = duration; m_ResponseContexts.AddToTail( newContext ); } } //----------------------------------------------------------------------------- // Purpose: // Input : inputdata - //----------------------------------------------------------------------------- void CBaseEntity::InputRemoveContext( inputdata_t& inputdata ) { const char *contextName = inputdata.value.String(); int idx = FindContextByName( contextName ); if ( idx == -1 ) return; m_ResponseContexts.Remove( idx ); } //----------------------------------------------------------------------------- // Purpose: // Input : inputdata - //----------------------------------------------------------------------------- void CBaseEntity::InputClearContext( inputdata_t& inputdata ) { m_ResponseContexts.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: // Output : IResponseSystem //----------------------------------------------------------------------------- IResponseSystem *CBaseEntity::GetResponseSystem() { return NULL; } //----------------------------------------------------------------------------- // Purpose: // Input : inputdata - //----------------------------------------------------------------------------- void CBaseEntity::InputDispatchResponse( inputdata_t& inputdata ) { DispatchResponse( inputdata.value.String() ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CBaseEntity::InputDisableShadow( inputdata_t &inputdata ) { AddEffects( EF_NOSHADOW ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CBaseEntity::InputEnableShadow( inputdata_t &inputdata ) { RemoveEffects( EF_NOSHADOW ); } //----------------------------------------------------------------------------- // Purpose: An input to add a new connection from this entity // Input : &inputdata - //----------------------------------------------------------------------------- void CBaseEntity::InputAddOutput( inputdata_t &inputdata ) { char sOutputName[MAX_PATH]; Q_strncpy( sOutputName, inputdata.value.String(), sizeof(sOutputName) ); char *sChar = strchr( sOutputName, ' ' ); if ( sChar ) { *sChar = '\0'; // Now replace all the :'s in the string with ,'s. // Has to be done this way because Hammer doesn't allow ,'s inside parameters. char *sColon = strchr( sChar+1, ':' ); while ( sColon ) { *sColon = ','; sColon = strchr( sChar+1, ':' ); } KeyValue( sOutputName, sChar+1 ); } else { Warning("AddOutput input fired with bad string. Format: <output name> <targetname>,<inputname>,<parameter>,<delay>,<max times to fire (-1 == infinite)>\n"); } } //----------------------------------------------------------------------------- // Purpose: // Input : *conceptName - //----------------------------------------------------------------------------- void CBaseEntity::DispatchResponse( const char *conceptName ) { IResponseSystem *rs = GetResponseSystem(); if ( !rs ) return; AI_CriteriaSet set; // Always include the concept name set.AppendCriteria( "concept", conceptName, CONCEPT_WEIGHT ); // Let NPC fill in most match criteria ModifyOrAppendCriteria( set ); // Append local player criteria to set,too CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if( pPlayer ) pPlayer->ModifyOrAppendPlayerCriteria( set ); // Now that we have a criteria set, ask for a suitable response AI_Response result; bool found = rs->FindBestResponse( set, result ); if ( !found ) { return; } // Handle the response here... char response[ 256 ]; result.GetResponse( response, sizeof( response ) ); switch ( result.GetType() ) { case RESPONSE_SPEAK: { EmitSound( response ); } break; case RESPONSE_SENTENCE: { int sentenceIndex = SENTENCEG_Lookup( response ); if( sentenceIndex == -1 ) { // sentence not found break; } // FIXME: Get pitch from npc? CPASAttenuationFilter filter( this ); CBaseEntity::EmitSentenceByIndex( filter, entindex(), CHAN_VOICE, sentenceIndex, 1, result.GetSoundLevel(), 0, PITCH_NORM ); } break; case RESPONSE_SCENE: { // Try to fire scene w/o an actor InstancedScriptedScene( NULL, response ); } break; case RESPONSE_PRINT: { } break; default: // Don't know how to handle .vcds!!! break; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseEntity::DumpResponseCriteria( void ) { Msg("----------------------------------------------\n"); Msg("RESPONSE CRITERIA FOR: %s (%s)\n", GetClassname(), GetDebugName() ); AI_CriteriaSet set; // Let NPC fill in most match criteria ModifyOrAppendCriteria( set ); // Append local player criteria to set,too CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer ) { pPlayer->ModifyOrAppendPlayerCriteria( set ); } // Now dump it all to console set.Describe(); } //------------------------------------------------------------------------------ void CC_Ent_Show_Response_Criteria( const CCommand& args ) { CBaseEntity *pEntity = NULL; while ( (pEntity = GetNextCommandEntity( UTIL_GetCommandClient(), args[1], pEntity )) != NULL ) { pEntity->DumpResponseCriteria(); } } static ConCommand ent_show_response_criteria("ent_show_response_criteria", CC_Ent_Show_Response_Criteria, "Print, to the console, an entity's current criteria set used to select responses.\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at ", FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose: Show an entity's autoaim radius //------------------------------------------------------------------------------ void CC_Ent_Autoaim( const CCommand& args ) { SetDebugBits( UTIL_GetCommandClient(),args[1], OVERLAY_AUTOAIM_BIT ); } static ConCommand ent_autoaim("ent_autoaim", CC_Ent_Autoaim, "Displays the entity's autoaim radius.\n\tArguments: {entity_name} / {class_name} / no argument picks what player is looking at", FCVAR_CHEAT ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CAI_BaseNPC *CBaseEntity::MyNPCPointer( void ) { if ( IsNPC() ) return assert_cast<CAI_BaseNPC *>(this); return NULL; } ConVar step_spline( "step_spline", "0" ); //----------------------------------------------------------------------------- // Purpose: Run one tick's worth of faked simulation // Input : *step - //----------------------------------------------------------------------------- void CBaseEntity::ComputeStepSimulationNetwork( StepSimulationData *step ) { if ( !step ) { Assert( !"ComputeStepSimulationNetworkOriginAndAngles with NULL step\n" ); return; } // Don't run again if we've already calculated this tick if ( step->m_nLastProcessTickCount == gpGlobals->tickcount ) { return; } step->m_nLastProcessTickCount = gpGlobals->tickcount; // Origin // It's inactive if ( step->m_bOriginActive ) { // First see if any external code moved the entity if ( GetStepOrigin() != step->m_Next.vecOrigin ) { step->m_bOriginActive = false; } else { // Compute interpolated info based on tick interval float frac = 1.0f; int tickdelta = step->m_Next.nTickCount - step->m_Previous.nTickCount; if ( tickdelta > 0 ) { frac = (float)( gpGlobals->tickcount - step->m_Previous.nTickCount ) / (float) tickdelta; frac = clamp( frac, 0.0f, 1.0f ); } if (step->m_Previous2.nTickCount == 0 || step->m_Previous2.nTickCount >= step->m_Previous.nTickCount) { Vector delta = step->m_Next.vecOrigin - step->m_Previous.vecOrigin; VectorMA( step->m_Previous.vecOrigin, frac, delta, step->m_vecNetworkOrigin ); } else if (!step_spline.GetBool()) { StepSimulationStep *pOlder = &step->m_Previous; StepSimulationStep *pNewer = &step->m_Next; if (step->m_Discontinuity.nTickCount > step->m_Previous.nTickCount) { if (gpGlobals->tickcount > step->m_Discontinuity.nTickCount) { pOlder = &step->m_Discontinuity; } else { pNewer = &step->m_Discontinuity; } tickdelta = pNewer->nTickCount - pOlder->nTickCount; if ( tickdelta > 0 ) { frac = (float)( gpGlobals->tickcount - pOlder->nTickCount ) / (float) tickdelta; frac = clamp( frac, 0.0f, 1.0f ); } } Vector delta = pNewer->vecOrigin - pOlder->vecOrigin; VectorMA( pOlder->vecOrigin, frac, delta, step->m_vecNetworkOrigin ); } else { Hermite_Spline( step->m_Previous2.vecOrigin, step->m_Previous.vecOrigin, step->m_Next.vecOrigin, frac, step->m_vecNetworkOrigin ); } } } // Angles if ( step->m_bAnglesActive ) { // See if external code changed the orientation of the entity if ( GetStepAngles() != step->m_angNextRotation ) { step->m_bAnglesActive = false; } else { // Compute interpolated info based on tick interval float frac = 1.0f; int tickdelta = step->m_Next.nTickCount - step->m_Previous.nTickCount; if ( tickdelta > 0 ) { frac = (float)( gpGlobals->tickcount - step->m_Previous.nTickCount ) / (float) tickdelta; frac = clamp( frac, 0.0f, 1.0f ); } if (step->m_Previous2.nTickCount == 0 || step->m_Previous2.nTickCount >= step->m_Previous.nTickCount) { // Pure blend between start/end orientations Quaternion outangles; QuaternionBlend( step->m_Previous.qRotation, step->m_Next.qRotation, frac, outangles ); QuaternionAngles( outangles, step->m_angNetworkAngles ); } else if (!step_spline.GetBool()) { StepSimulationStep *pOlder = &step->m_Previous; StepSimulationStep *pNewer = &step->m_Next; if (step->m_Discontinuity.nTickCount > step->m_Previous.nTickCount) { if (gpGlobals->tickcount > step->m_Discontinuity.nTickCount) { pOlder = &step->m_Discontinuity; } else { pNewer = &step->m_Discontinuity; } tickdelta = pNewer->nTickCount - pOlder->nTickCount; if ( tickdelta > 0 ) { frac = (float)( gpGlobals->tickcount - pOlder->nTickCount ) / (float) tickdelta; frac = clamp( frac, 0.0f, 1.0f ); } } // Pure blend between start/end orientations Quaternion outangles; QuaternionBlend( pOlder->qRotation, pNewer->qRotation, frac, outangles ); QuaternionAngles( outangles, step->m_angNetworkAngles ); } else { // FIXME: enable spline interpolation when turning is debounced. Quaternion outangles; Hermite_Spline( step->m_Previous2.qRotation, step->m_Previous.qRotation, step->m_Next.qRotation, frac, outangles ); QuaternionAngles( outangles, step->m_angNetworkAngles ); } } } } //----------------------------------------------------------------------------- bool CBaseEntity::UseStepSimulationNetworkOrigin( const Vector **out_v ) { Assert( out_v ); if ( g_bTestMoveTypeStepSimulation && GetMoveType() == MOVETYPE_STEP && HasDataObjectType( STEPSIMULATION ) ) { StepSimulationData *step = ( StepSimulationData * )GetDataObject( STEPSIMULATION ); ComputeStepSimulationNetwork( step ); *out_v = &step->m_vecNetworkOrigin; return step->m_bOriginActive; } return false; } //----------------------------------------------------------------------------- bool CBaseEntity::UseStepSimulationNetworkAngles( const QAngle **out_a ) { Assert( out_a ); if ( g_bTestMoveTypeStepSimulation && GetMoveType() == MOVETYPE_STEP && HasDataObjectType( STEPSIMULATION ) ) { StepSimulationData *step = ( StepSimulationData * )GetDataObject( STEPSIMULATION ); ComputeStepSimulationNetwork( step ); *out_a = &step->m_angNetworkAngles; return step->m_bAnglesActive; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CBaseEntity::AddStepDiscontinuity( float flTime, const Vector &vecOrigin, const QAngle &vecAngles ) { if ((GetMoveType() != MOVETYPE_STEP ) || !HasDataObjectType( STEPSIMULATION ) ) { return false; } StepSimulationData *step = ( StepSimulationData * )GetDataObject( STEPSIMULATION ); if (!step) { Assert( 0 ); return false; } step->m_Discontinuity.nTickCount = TIME_TO_TICKS( flTime ); step->m_Discontinuity.vecOrigin = vecOrigin; AngleQuaternion( vecAngles, step->m_Discontinuity.qRotation ); return true; } Vector CBaseEntity::GetStepOrigin( void ) const { return GetLocalOrigin(); } QAngle CBaseEntity::GetStepAngles( void ) const { return GetLocalAngles(); } //----------------------------------------------------------------------------- // Purpose: For each client who appears to be a valid recipient, checks the client has disabled CC and if so, removes them from // the recipient list. // Input : filter - //----------------------------------------------------------------------------- void CBaseEntity::RemoveRecipientsIfNotCloseCaptioning( CRecipientFilter& filter ) { int c = filter.GetRecipientCount(); for ( int i = c - 1; i >= 0; --i ) { int playerIndex = filter.GetRecipientIndex( i ); CBasePlayer *player = static_cast< CBasePlayer * >( CBaseEntity::Instance( playerIndex ) ); if ( !player ) continue; #if !defined( _XBOX ) const char *cvarvalue = engine->GetClientConVarValue( playerIndex, "closecaption" ); Assert( cvarvalue ); if ( !cvarvalue[ 0 ] ) continue; int value = atoi( cvarvalue ); #else static ConVar *s_pCloseCaption = NULL; if ( !s_pCloseCaption ) { s_pCloseCaption = cvar->FindVar( "closecaption" ); if ( !s_pCloseCaption ) { Error( "XBOX couldn't find closecaption convar!!!" ); } } int value = s_pCloseCaption->GetInt(); #endif // No close captions? if ( value == 0 ) { filter.RemoveRecipient( player ); } } } //----------------------------------------------------------------------------- // Purpose: Wrapper to emit a sentence and also a close caption token for the sentence as appropriate. // Input : filter - // iEntIndex - // iChannel - // iSentenceIndex - // flVolume - // iSoundlevel - // iFlags - // iPitch - // bUpdatePositions - // soundtime - //----------------------------------------------------------------------------- void CBaseEntity::EmitSentenceByIndex( IRecipientFilter& filter, int iEntIndex, int iChannel, int iSentenceIndex, float flVolume, soundlevel_t iSoundlevel, int iFlags /*= 0*/, int iPitch /*=PITCH_NORM*/, const Vector *pOrigin /*=NULL*/, const Vector *pDirection /*=NULL*/, bool bUpdatePositions /*=true*/, float soundtime /*=0.0f*/ ) { CUtlVector< Vector > dummy; enginesound->EmitSentenceByIndex( filter, iEntIndex, iChannel, iSentenceIndex, flVolume, iSoundlevel, iFlags, iPitch, 0, pOrigin, pDirection, &dummy, bUpdatePositions, soundtime ); } void CBaseEntity::SetRefEHandle( const CBaseHandle &handle ) { m_RefEHandle = handle; if ( edict() ) { COMPILE_TIME_ASSERT( NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS <= 8*sizeof( edict()->m_NetworkSerialNumber ) ); edict()->m_NetworkSerialNumber = (m_RefEHandle.GetSerialNumber() & (1 << NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS) - 1); } } bool CPointEntity::KeyValue( const char *szKeyName, const char *szValue ) { if ( FStrEq( szKeyName, "mins" ) || FStrEq( szKeyName, "maxs" ) ) { Warning("Warning! Can't specify mins/maxs for point entities! (%s)\n", GetClassname() ); return true; } return BaseClass::KeyValue( szKeyName, szValue ); } bool CServerOnlyPointEntity::KeyValue( const char *szKeyName, const char *szValue ) { if ( FStrEq( szKeyName, "mins" ) || FStrEq( szKeyName, "maxs" ) ) { Warning("Warning! Can't specify mins/maxs for point entities! (%s)\n", GetClassname() ); return true; } return BaseClass::KeyValue( szKeyName, szValue ); } bool CLogicalEntity::KeyValue( const char *szKeyName, const char *szValue ) { if ( FStrEq( szKeyName, "mins" ) || FStrEq( szKeyName, "maxs" ) ) { Warning("Warning! Can't specify mins/maxs for point entities! (%s)\n", GetClassname() ); return true; } return BaseClass::KeyValue( szKeyName, szValue ); } //----------------------------------------------------------------------------- // Purpose: Sets the entity invisible, and makes it remove itself on the next frame //----------------------------------------------------------------------------- void CBaseEntity::RemoveDeferred( void ) { // Set our next think to remove us SetThink( &CBaseEntity::SUB_Remove ); SetNextThink( gpGlobals->curtime + 0.1f ); // Hide us completely AddEffects( EF_NODRAW ); AddSolidFlags( FSOLID_NOT_SOLID ); SetMoveType( MOVETYPE_NONE ); } #define MIN_CORPSE_FADE_TIME 10.0 #define MIN_CORPSE_FADE_DIST 256.0 #define MAX_CORPSE_FADE_DIST 1500.0 // // fade out - slowly fades a entity out, then removes it. // // DON'T USE ME FOR GIBS AND STUFF IN MULTIPLAYER! // SET A FUTURE THINK AND A RENDERMODE!! void CBaseEntity::SUB_StartFadeOut( float delay, bool notSolid ) { SetThink( &CBaseEntity::SUB_FadeOut ); SetNextThink( gpGlobals->curtime + delay ); SetRenderColorA( 255 ); m_nRenderMode = kRenderNormal; if ( notSolid ) { AddSolidFlags( FSOLID_NOT_SOLID ); SetLocalAngularVelocity( vec3_angle ); } } void CBaseEntity::SUB_StartFadeOutInstant() { SUB_StartFadeOut( 0, true ); } //----------------------------------------------------------------------------- // Purpose: Vanish when players aren't looking //----------------------------------------------------------------------------- void CBaseEntity::SUB_Vanish( void ) { //Always think again next frame SetNextThink( gpGlobals->curtime + 0.1f ); CBasePlayer *pPlayer; //Get all players for ( int i = 1; i <= gpGlobals->maxClients; i++ ) { //Get the next client if ( ( pPlayer = UTIL_PlayerByIndex( i ) ) != NULL ) { Vector corpseDir = (GetAbsOrigin() - pPlayer->WorldSpaceCenter() ); float flDistSqr = corpseDir.LengthSqr(); //If the player is close enough, don't fade out if ( flDistSqr < (MIN_CORPSE_FADE_DIST*MIN_CORPSE_FADE_DIST) ) return; // If the player's far enough away, we don't care about looking at it if ( flDistSqr < (MAX_CORPSE_FADE_DIST*MAX_CORPSE_FADE_DIST) ) { VectorNormalize( corpseDir ); Vector plForward; pPlayer->EyeVectors( &plForward ); float dot = plForward.Dot( corpseDir ); if ( dot > 0.0f ) return; } } } //If we're here, then we can vanish safely m_iHealth = 0; SetThink( &CBaseEntity::SUB_Remove ); } void CBaseEntity::SUB_PerformFadeOut( void ) { float dt = gpGlobals->frametime; if ( dt > 0.1f ) { dt = 0.1f; } m_nRenderMode = kRenderTransTexture; int speed = MAX(1,256*dt); // fade out over 1 second SetRenderColorA( UTIL_Approach( 0, m_clrRender->a, speed ) ); } bool CBaseEntity::SUB_AllowedToFade( void ) { if( VPhysicsGetObject() ) { if( VPhysicsGetObject()->GetGameFlags() & FVPHYSICS_PLAYER_HELD || GetEFlags() & EFL_IS_BEING_LIFTED_BY_BARNACLE ) return false; } // on Xbox, allow these to fade out #ifndef _XBOX CBasePlayer *pPlayer = ( AI_IsSinglePlayer() ) ? UTIL_GetLocalPlayer() : NULL; if ( pPlayer && pPlayer->FInViewCone( this ) ) return false; #endif return true; } //----------------------------------------------------------------------------- // Purpose: Fade out slowly //----------------------------------------------------------------------------- void CBaseEntity::SUB_FadeOut( void ) { if ( SUB_AllowedToFade() == false ) { SetNextThink( gpGlobals->curtime + 1 ); SetRenderColorA( 255 ); return; } SUB_PerformFadeOut(); if ( m_clrRender->a == 0 ) { UTIL_Remove(this); } else { SetNextThink( gpGlobals->curtime ); } } inline bool AnyPlayersInHierarchy_R( CBaseEntity *pEnt ) { if ( pEnt->IsPlayer() ) return true; for ( CBaseEntity *pCur = pEnt->FirstMoveChild(); pCur; pCur=pCur->NextMovePeer() ) { if ( AnyPlayersInHierarchy_R( pCur ) ) return true; } return false; } void CBaseEntity::RecalcHasPlayerChildBit() { if ( AnyPlayersInHierarchy_R( this ) ) AddEFlags( EFL_HAS_PLAYER_CHILD ); else RemoveEFlags( EFL_HAS_PLAYER_CHILD ); } bool CBaseEntity::DoesHavePlayerChild() { return IsEFlagSet( EFL_HAS_PLAYER_CHILD ); } //------------------------------------------------------------------------------ void CBaseEntity::IncrementInterpolationFrame() { m_ubInterpolationFrame = (m_ubInterpolationFrame + 1) % NOINTERP_PARITY_MAX; } //------------------------------------------------------------------------------ void CBaseEntity::OnModelLoadComplete( const model_t* model ) { Assert( m_bDynamicModelPending && IsDynamicModelIndex( m_nModelIndex ) ); Assert( model == modelinfo->GetModel( m_nModelIndex ) ); m_bDynamicModelPending = false; if ( m_bDynamicModelSetBounds ) { m_bDynamicModelSetBounds = false; SetCollisionBoundsFromModel(); } OnNewModel(); } //------------------------------------------------------------------------------ void CBaseEntity::SetCollisionBoundsFromModel() { if ( IsDynamicModelLoading() ) { m_bDynamicModelSetBounds = true; return; } if ( const model_t *pModel = GetModel() ) { Vector mns, mxs; modelinfo->GetModelBounds( pModel, mns, mxs ); UTIL_SetSize( this, mns, mxs ); } } //------------------------------------------------------------------------------ // Purpose: Create an NPC of the given type //------------------------------------------------------------------------------ void CC_Ent_Create( const CCommand& args ) { MDLCACHE_CRITICAL_SECTION(); bool allowPrecache = CBaseEntity::IsPrecacheAllowed(); CBaseEntity::SetAllowPrecache( true ); // Try to create entity CBaseEntity *entity = dynamic_cast< CBaseEntity * >( CreateEntityByName(args[1]) ); if (entity) { entity->Precache(); // Pass in any additional parameters. for ( int i = 2; i + 1 < args.ArgC(); i += 2 ) { const char *pKeyName = args[i]; const char *pValue = args[i+1]; entity->KeyValue( pKeyName, pValue ); } DispatchSpawn(entity); // Now attempt to drop into the world CBasePlayer* pPlayer = UTIL_GetCommandClient(); trace_t tr; Vector forward; pPlayer->EyeVectors( &forward ); UTIL_TraceLine(pPlayer->EyePosition(), pPlayer->EyePosition() + forward * MAX_TRACE_LENGTH,MASK_SOLID, pPlayer, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction != 1.0 ) { // Raise the end position a little up off the floor, place the npc and drop him down tr.endpos.z += 12; entity->Teleport( &tr.endpos, NULL, NULL ); UTIL_DropToFloor( entity, MASK_SOLID ); } entity->Activate(); } CBaseEntity::SetAllowPrecache( allowPrecache ); } static ConCommand ent_create("ent_create", CC_Ent_Create, "Creates an entity of the given type where the player is looking. Additional parameters can be passed in in the form: ent_create <entity name> <param 1 name> <param 1> <param 2 name> <param 2>...<param N name> <param N>", FCVAR_GAMEDLL | FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose: Teleport a specified entity to where the player is looking //------------------------------------------------------------------------------ bool CC_GetCommandEnt( const CCommand& args, CBaseEntity **ent, Vector *vecTargetPoint, QAngle *vecPlayerAngle ) { // Find the entity *ent = NULL; // First try using it as an entindex int iEntIndex = atoi( args[1] ); if ( iEntIndex ) { *ent = CBaseEntity::Instance( iEntIndex ); } else { // Try finding it by name *ent = gEntList.FindEntityByName( NULL, args[1] ); if ( !*ent ) { // Finally, try finding it by classname *ent = gEntList.FindEntityByClassname( NULL, args[1] ); } } if ( !*ent ) { Msg( "Couldn't find any entity named '%s'\n", args[1] ); return false; } CBasePlayer *pPlayer = UTIL_GetCommandClient(); if ( vecTargetPoint ) { trace_t tr; Vector forward; pPlayer->EyeVectors( &forward ); UTIL_TraceLine(pPlayer->EyePosition(), pPlayer->EyePosition() + forward * MAX_TRACE_LENGTH,MASK_NPCSOLID, pPlayer, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction != 1.0 ) { *vecTargetPoint = tr.endpos; } } if ( vecPlayerAngle ) { *vecPlayerAngle = pPlayer->EyeAngles(); } return true; } //------------------------------------------------------------------------------ // Purpose: Teleport a specified entity to where the player is looking //------------------------------------------------------------------------------ void CC_Ent_Teleport( const CCommand& args ) { if ( args.ArgC() < 2 ) { Msg( "Format: ent_teleport <entity name>\n" ); return; } CBaseEntity *pEnt; Vector vecTargetPoint; if ( CC_GetCommandEnt( args, &pEnt, &vecTargetPoint, NULL ) ) { pEnt->Teleport( &vecTargetPoint, NULL, NULL ); } } static ConCommand ent_teleport("ent_teleport", CC_Ent_Teleport, "Teleport the specified entity to where the player is looking.\n\tFormat: ent_teleport <entity name>", FCVAR_CHEAT); //------------------------------------------------------------------------------ // Purpose: Orient a specified entity to match the player's angles //------------------------------------------------------------------------------ void CC_Ent_Orient( const CCommand& args ) { if ( args.ArgC() < 2 ) { Msg( "Format: ent_orient <entity name> <optional: allangles>\n" ); return; } CBaseEntity *pEnt; QAngle vecPlayerAngles; if ( CC_GetCommandEnt( args, &pEnt, NULL, &vecPlayerAngles ) ) { QAngle vecEntAngles = pEnt->GetAbsAngles(); if ( args.ArgC() == 3 && !Q_strncmp( args[2], "allangles", 9 ) ) { vecEntAngles = vecPlayerAngles; } else { vecEntAngles[YAW] = vecPlayerAngles[YAW]; } pEnt->SetAbsAngles( vecEntAngles ); } } static ConCommand ent_orient("ent_orient", CC_Ent_Orient, "Orient the specified entity to match the player's angles. By default, only orients target entity's YAW. Use the 'allangles' option to orient on all axis.\n\tFormat: ent_orient <entity name> <optional: allangles>", FCVAR_CHEAT);
[ "maxdumonceaux@gmail.com" ]
maxdumonceaux@gmail.com
4eb87e352325934a0e548bcf3a23d8044e903505
5e020627cbd61548054b29a5d16f1c9b5337c312
/src/draco/metadata/geometry_metadata.h
9f668f7fa1587e915fb2f117b970acf9e233b6cf
[ "Apache-2.0" ]
permissive
jeromeetienne/draco
a78001b9a2da991643ce24beed33f1a52e9feb06
eee8bf5d8634e6f70100e22b2693b5437c8037c7
refs/heads/master
2023-08-19T07:33:36.066746
2018-08-20T23:04:59
2018-08-20T23:04:59
147,519,303
2
0
Apache-2.0
2018-09-05T13:07:25
2018-09-05T13:07:25
null
UTF-8
C++
false
false
4,258
h
// Copyright 2017 The Draco Authors. // // 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 DRACO_METADATA_GEOMETRY_METADATA_H_ #define DRACO_METADATA_GEOMETRY_METADATA_H_ #include "draco/metadata/metadata.h" namespace draco { // Class for representing specifically metadata of attributes. It must have an // attribute id which should be identical to it's counterpart attribute in // the point cloud it belongs to. class AttributeMetadata : public Metadata { public: AttributeMetadata() : att_unique_id_(0) {} explicit AttributeMetadata(const Metadata &metadata) : Metadata(metadata), att_unique_id_(0) {} void set_att_unique_id(uint32_t att_unique_id) { att_unique_id_ = att_unique_id; } // The unique id of the attribute that this metadata belongs to. uint32_t att_unique_id() const { return att_unique_id_; } private: uint32_t att_unique_id_; friend struct AttributeMetadataHasher; friend class PointCloud; }; // Functor for computing a hash from data stored in a AttributeMetadata class. struct AttributeMetadataHasher { size_t operator()(const AttributeMetadata &metadata) const { size_t hash = metadata.att_unique_id_; MetadataHasher metadata_hasher; hash = HashCombine(metadata_hasher(static_cast<const Metadata &>(metadata)), hash); return hash; } }; // Class for representing the metadata for a point cloud. It could have a list // of attribute metadata. class GeometryMetadata : public Metadata { public: GeometryMetadata(){}; explicit GeometryMetadata(const Metadata &metadata) : Metadata(metadata) {} const AttributeMetadata *GetAttributeMetadataByStringEntry( const std::string &entry_name, const std::string &entry_value) const; bool AddAttributeMetadata(std::unique_ptr<AttributeMetadata> att_metadata); void DeleteAttributeMetadataByUniqueId(int32_t att_unique_id) { for (auto itr = att_metadatas_.begin(); itr != att_metadatas_.end(); ++itr) { if (itr->get()->att_unique_id() == att_unique_id) { att_metadatas_.erase(itr); return; } } } const AttributeMetadata *GetAttributeMetadataByUniqueId( int32_t att_unique_id) const { // TODO(draco-eng): Consider using unordered_map instead of vector to store // attribute metadata. for (auto &&att_metadata : att_metadatas_) { if (att_metadata->att_unique_id() == att_unique_id) { return att_metadata.get(); } } return nullptr; } AttributeMetadata *attribute_metadata(int32_t att_unique_id) { // TODO(draco-eng): Consider use unordered_map instead of vector to store // attribute metadata. for (auto &&att_metadata : att_metadatas_) { if (att_metadata->att_unique_id() == att_unique_id) { return att_metadata.get(); } } return nullptr; } const std::vector<std::unique_ptr<AttributeMetadata>> &attribute_metadatas() const { return att_metadatas_; } private: std::vector<std::unique_ptr<AttributeMetadata>> att_metadatas_; friend struct GeometryMetadataHasher; }; // Functor for computing a hash from data stored in a GeometryMetadata class. struct GeometryMetadataHasher { size_t operator()(const GeometryMetadata &metadata) const { size_t hash = metadata.att_metadatas_.size(); AttributeMetadataHasher att_metadata_hasher; for (auto &&att_metadata : metadata.att_metadatas_) { hash = HashCombine(att_metadata_hasher(*att_metadata), hash); } MetadataHasher metadata_hasher; hash = HashCombine(metadata_hasher(static_cast<const Metadata &>(metadata)), hash); return hash; } }; } // namespace draco #endif // THIRD_PARTY_DRACO_METADATA_GEOMETRY_METADATA_H_
[ "ondrej.stava@gmail.com" ]
ondrej.stava@gmail.com
084f8a2d1fa66e45f270badd19842f421174271c
c1b65b3ee4db1938e9bd6ee457594d2a3174b925
/EV3DF/SJC/SJCSTLExtensions.h
180d6e5f50195af8ded7eaff2da24a3bac020c4e
[]
no_license
damody/geology
f4b204700d9d710d148f360f7998fb20d4a029c1
6c1f2cb7772dae7f4370317b26159c9bab52406f
refs/heads/master
2021-01-01T04:12:50.726678
2013-05-10T08:37:08
2013-05-10T08:37:08
56,484,969
0
1
null
null
null
null
UTF-8
C++
false
false
597
h
/************************************************************************ Main File: File: STLExtensions.h Author: Eric McDaniel, chat@cs.wisc.edu Comment: The extension of standard container Compiler: g++ Platform: Linux *************************************************************************/ #ifndef _STL_EXTENSIONS_H_ #define _STL_EXTENSIONS_H_ #include <functional> #include <vector> #include <map> // definition of stl extension templates #include "SJCSTLExtensions.cpp" #endif
[ "t1238142000@15cd899a-37be-affb-661b-94829f8fb904" ]
t1238142000@15cd899a-37be-affb-661b-94829f8fb904
7a2469011bbb0610568ff8d1cb6488c02a5cbf00
3a4651255b75dd82e201deda268e0b1d80c867c2
/product-subseq-cnt.cpp
d9279148633b8c7c0eb31abe395f5a9a863ca2cd
[]
no_license
Shikhar21121999/ds-algo-busted
7b5f46ec88cd6d64e70ac422c5ae0d6bcc0cb0cc
2b102313a55147e14bf890f4184509b74e928842
refs/heads/main
2023-08-10T05:04:16.434039
2021-06-03T05:23:48
2021-06-03T05:23:48
312,954,116
0
0
null
null
null
null
UTF-8
C++
false
false
883
cpp
// program to count number of subsequences // such that the product of elements in subsequence is less than k #include<bits/stdc++.h> using namespace std; #define vi vector<int> #define vvi vector<vi> int productCountSubseq(vi &a,int k){ int n=a.size(); vvi dp(k+1,vi(n+1,0)); // dp[i][j] represent number of subsequences possible // including j which have product less than or equal to i for(int i=1;i<=k;i++){ for(int j=1;j<=n;j++){ // subsequences without including current element dp[i][j]=dp[i][j-1]; // see if its possible to include this element to get product // less than i if(a[j-1]<=i and a[j-1]>0){ dp[i][j]+=dp[i/a[j-1]][j-1]+1; } } } return dp[k][n]; } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; vi a(n); for(int i=0;i<n;i++){ cin>>a[i]; } int k; cin>>k; cout<<productCountSubseq(a,k)<<endl; } }
[ "shikhar21121999@gmail.com" ]
shikhar21121999@gmail.com
cf6d8011457a73fda725c77b54e911c5eb66fb7c
17d766a296cc6c72499bba01b82d58f7df747b64
/GcdQuery.cpp
0dacf082b0c6ea08cd5bd28767dedad6fff5252d
[]
no_license
Kullsno2/C-Cpp-Programs
1dd7a57cf7e4c70831c5b36566605dc35abdeb67
2b81ddc67f22ada291e85bfc377e59e6833e48fb
refs/heads/master
2021-01-22T21:45:41.214882
2015-11-15T11:15:46
2015-11-15T11:15:46
85,473,174
0
1
null
2017-03-19T12:12:00
2017-03-19T12:11:59
null
UTF-8
C++
false
false
1,546
cpp
#include<iostream> #include<vector> #include<stdio.h> #include<stack> #include<vector> #include<queue> #include<string.h> #include<stdlib.h> #include<math.h> #include<limits.h> #include<map> #include<algorithm> #include<utility> #define ll long long #define p(a) printf("%d\n",a) #define s(a) scanf("%d",&a) #define sll(a) scanf("%lld",&a) #define sl(a) scanf("%ld",&a) #define FOR(a,b) for(int i=a ; i<=b ; ++i) #define pi pair<int,int> using namespace std ; int gcd(int a,int b){ //cout<<a<<" " <<b; if(a<b) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } int findModulus(int a,string b){ if(a==0) return atoi(b.c_str()); int m = b[0]-'0'; int i=0,d; while(b[i]){ d = m % a; // cout<<"d: "<<d<<end if(b[i+1]) m = (10*d) + (b[i+1]-'0'); i++; // cout<<d<<endl; } return d; } int calc_gcd(int a,int b){ a = min(a,b); b = max(a,b); // string s; char ar[100] ; itoa(b,ar,10); string st(ar); //cout<<st<<" "; return gcd(a,findModulus(a,st)); } int gcd(int arr[],int l,int r,int n,map<pi , int> &m){ int res = 0; for(int i=1 ; i<=n ; i++){ // cout<<res<<" "<<arr[i]<<endl; if(i==l) i = r; else{ pi p = make_pair(res,arr[i]); if(m[p]==0){ res = calc_gcd(res,arr[i]); m[p] = res; } else{ res = m[p]; } } } return res; } int main() { int t; s(t); while(t--){ int n,q; s(n); s(q); map<pi , int> m; int arr[n+1]; FOR(1,n) s(arr[i]); FOR(1,q){ int l,r; s(l); s(r); p(gcd(arr,l,r,n,m)); } } return 0 ; }
[ "nanduvinodan2@gmail.com" ]
nanduvinodan2@gmail.com
a8787997c7d0ac6b7f65c109356c8421301f32e5
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5634947029139456_1/C++/MagiMaster/main.cpp
80ac9b2aae34eceb1b0ecf8f3f79d81f25478b99
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
187
cpp
#include <fstream> using namespace std; #include "Chaos.cpp" int main() { ifstream infile("A-large.in"); ofstream outfile("results.out"); Chaos c; c.go(infile, outfile); }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
70d392246ea109c95d9efb8b3cc3017356c74752
9c5d73ebee96e39f7311f8a29eb46f3aa82c9c34
/source/discovery/carla-discovery.cpp
f062b775ddeacfedc8745201f6ae3b024043b2af
[]
no_license
bagnz0r/Carla
4dcdb22e10e8ae0a620fb5b556fa17ef6d788b56
6347381f84dea5c0fda0d299f3786aae58a3d86b
refs/heads/master
2021-01-22T15:22:17.591706
2015-01-23T07:02:13
2015-01-23T07:02:13
29,738,354
1
0
null
2015-01-23T15:19:50
2015-01-23T15:19:50
null
UTF-8
C++
false
false
55,979
cpp
/* * Carla Plugin discovery * Copyright (C) 2011-2014 Filipe Coelho <falktx@falktx.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 any later version. * * 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 General Public License for more details. * * For a full copy of the GNU General Public License see the doc/GPL.txt file. */ #include "CarlaBackendUtils.hpp" #include "CarlaLibUtils.hpp" #include "CarlaMathUtils.hpp" #include "CarlaMIDI.h" #if defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN) # define USE_JUCE_PROCESSORS # include "juce_audio_processors.h" #endif #ifdef BUILD_BRIDGE # undef HAVE_FLUIDSYNTH # undef HAVE_LINUXSAMPLER #endif #include "CarlaLadspaUtils.hpp" #include "CarlaDssiUtils.cpp" #include "CarlaLv2Utils.hpp" #include "CarlaVstUtils.hpp" #ifdef HAVE_FLUIDSYNTH # include <fluidsynth.h> #endif #ifdef HAVE_LINUXSAMPLER # include "linuxsampler/EngineFactory.h" #endif #include <iostream> #include "juce_core.h" using juce::CharPointer_UTF8; using juce::File; using juce::String; using juce::StringArray; #define DISCOVERY_OUT(x, y) std::cout << "\ncarla-discovery::" << x << "::" << y << std::endl; CARLA_BACKEND_USE_NAMESPACE // -------------------------------------------------------------------------- // Dummy values to test plugins with static const uint32_t kBufferSize = 512; static const double kSampleRate = 44100.0; static const int32_t kSampleRatei = 44100; static const float kSampleRatef = 44100.0f; // -------------------------------------------------------------------------- // Don't print ELF/EXE related errors since discovery can find multi-architecture binaries static void print_lib_error(const char* const filename) { const char* const error(lib_error(filename)); if (error != nullptr && std::strstr(error, "wrong ELF class") == nullptr && std::strstr(error, "Bad EXE format") == nullptr) DISCOVERY_OUT("error", error); } #ifndef CARLA_OS_MAC // -------------------------------------------------------------------------- // VST stuff // Check if plugin is currently processing static bool gVstIsProcessing = false; // Check if plugin needs idle static bool gVstNeedsIdle = false; // Check if plugin wants midi static bool gVstWantsMidi = false; // Check if plugin wants time static bool gVstWantsTime = false; // Current uniqueId for VST shell plugins static intptr_t gVstCurrentUniqueId = 0; // Supported Carla features static intptr_t vstHostCanDo(const char* const feature) { carla_debug("vstHostCanDo(\"%s\")", feature); if (std::strcmp(feature, "supplyIdle") == 0) return 1; if (std::strcmp(feature, "sendVstEvents") == 0) return 1; if (std::strcmp(feature, "sendVstMidiEvent") == 0) return 1; if (std::strcmp(feature, "sendVstMidiEventFlagIsRealtime") == 0) return 1; if (std::strcmp(feature, "sendVstTimeInfo") == 0) { gVstWantsTime = true; return 1; } if (std::strcmp(feature, "receiveVstEvents") == 0) return 1; if (std::strcmp(feature, "receiveVstMidiEvent") == 0) return 1; if (std::strcmp(feature, "receiveVstTimeInfo") == 0) return -1; if (std::strcmp(feature, "reportConnectionChanges") == 0) return -1; if (std::strcmp(feature, "acceptIOChanges") == 0) return 1; if (std::strcmp(feature, "sizeWindow") == 0) return 1; if (std::strcmp(feature, "offline") == 0) return -1; if (std::strcmp(feature, "openFileSelector") == 0) return -1; if (std::strcmp(feature, "closeFileSelector") == 0) return -1; if (std::strcmp(feature, "startStopProcess") == 0) return 1; if (std::strcmp(feature, "supportShell") == 0) return 1; if (std::strcmp(feature, "shellCategory") == 0) return 1; // non-official features found in some plugins: // "asyncProcessing" // "editFile" // unimplemented carla_stderr("vstHostCanDo(\"%s\") - unknown feature", feature); return 0; } // Host-side callback static intptr_t VSTCALLBACK vstHostCallback(AEffect* const effect, const int32_t opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt) { carla_debug("vstHostCallback(%p, %i:%s, %i, " P_INTPTR ", %p, %f)", effect, opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt); static VstTimeInfo timeInfo; intptr_t ret = 0; switch (opcode) { case audioMasterAutomate: ret = 1; break; case audioMasterVersion: ret = kVstVersion; break; case audioMasterCurrentId: if (gVstCurrentUniqueId == 0) DISCOVERY_OUT("warning", "Plugin asked for uniqueId, but it's currently 0"); ret = gVstCurrentUniqueId; break; case DECLARE_VST_DEPRECATED(audioMasterWantMidi): if (gVstWantsMidi) DISCOVERY_OUT("warning", "Plugin requested MIDI more than once"); gVstWantsMidi = true; ret = 1; break; case audioMasterGetTime: if (! gVstIsProcessing) DISCOVERY_OUT("warning", "Plugin requested timeInfo out of process"); if (! gVstWantsTime) DISCOVERY_OUT("warning", "Plugin requested timeInfo but didn't ask if host could do \"sendVstTimeInfo\""); carla_zeroStruct<VstTimeInfo>(timeInfo); timeInfo.sampleRate = kSampleRate; // Tempo timeInfo.tempo = 120.0; timeInfo.flags |= kVstTempoValid; // Time Signature timeInfo.timeSigNumerator = 4; timeInfo.timeSigDenominator = 4; timeInfo.flags |= kVstTimeSigValid; ret = (intptr_t)&timeInfo; break; case DECLARE_VST_DEPRECATED(audioMasterTempoAt): ret = 120 * 10000; break; case DECLARE_VST_DEPRECATED(audioMasterGetNumAutomatableParameters): ret = carla_minPositive(effect->numParams, static_cast<int>(MAX_DEFAULT_PARAMETERS)); break; case DECLARE_VST_DEPRECATED(audioMasterGetParameterQuantization): ret = 1; // full single float precision break; case DECLARE_VST_DEPRECATED(audioMasterNeedIdle): if (gVstNeedsIdle) DISCOVERY_OUT("warning", "Plugin requested idle more than once"); gVstNeedsIdle = true; ret = 1; break; case audioMasterGetSampleRate: ret = kSampleRatei; break; case audioMasterGetBlockSize: ret = kBufferSize; break; case DECLARE_VST_DEPRECATED(audioMasterWillReplaceOrAccumulate): ret = 1; // replace break; case audioMasterGetCurrentProcessLevel: ret = gVstIsProcessing ? kVstProcessLevelRealtime : kVstProcessLevelUser; break; case audioMasterGetAutomationState: ret = kVstAutomationOff; break; case audioMasterGetVendorString: CARLA_SAFE_ASSERT_BREAK(ptr != nullptr); std::strcpy((char*)ptr, "falkTX"); ret = 1; break; case audioMasterGetProductString: CARLA_SAFE_ASSERT_BREAK(ptr != nullptr); std::strcpy((char*)ptr, "Carla-Discovery"); ret = 1; break; case audioMasterGetVendorVersion: ret = CARLA_VERSION_HEX; break; case audioMasterCanDo: CARLA_SAFE_ASSERT_BREAK(ptr != nullptr); ret = vstHostCanDo((const char*)ptr); break; case audioMasterGetLanguage: ret = kVstLangEnglish; break; default: carla_stdout("vstHostCallback(%p, %i:%s, %i, " P_INTPTR ", %p, %f)", effect, opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt); break; } return ret; } #endif // ! CARLA_OS_MAC #ifdef HAVE_LINUXSAMPLER // -------------------------------------------------------------------------- // LinuxSampler stuff class LinuxSamplerScopedEngine { public: LinuxSamplerScopedEngine(const char* const filename, const char* const stype) : fEngine(nullptr) { using namespace LinuxSampler; try { fEngine = EngineFactory::Create(stype); } catch (const Exception& e) { DISCOVERY_OUT("error", e.what()); return; } if (fEngine == nullptr) return; InstrumentManager* const insMan(fEngine->GetInstrumentManager()); if (insMan == nullptr) { DISCOVERY_OUT("error", "Failed to get LinuxSampler instrument manager"); return; } std::vector<InstrumentManager::instrument_id_t> ids; try { ids = insMan->GetInstrumentFileContent(filename); } catch (const InstrumentManagerException& e) { DISCOVERY_OUT("error", e.what()); return; } if (ids.size() == 0) { DISCOVERY_OUT("error", "Failed to find any instruments"); return; } InstrumentManager::instrument_info_t info; try { info = insMan->GetInstrumentInfo(ids[0]); } catch (const InstrumentManagerException& e) { DISCOVERY_OUT("error", e.what()); return; } outputInfo(&info, nullptr, ids.size() > 1); } ~LinuxSamplerScopedEngine() { if (fEngine != nullptr) { LinuxSampler::EngineFactory::Destroy(fEngine); fEngine = nullptr; } } static void outputInfo(const LinuxSampler::InstrumentManager::instrument_info_t* const info, const char* const basename, const bool has16Outs) { CarlaString name; const char* label; if (info != nullptr) { name = info->InstrumentName.c_str(); label = info->Product.c_str(); } else { name = basename; label = basename; } // 2 channels DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", PLUGIN_IS_SYNTH); DISCOVERY_OUT("name", name.buffer()); DISCOVERY_OUT("label", label); if (info != nullptr) DISCOVERY_OUT("maker", info->Artists); DISCOVERY_OUT("audio.outs", 2); DISCOVERY_OUT("midi.ins", 1); DISCOVERY_OUT("end", "------------"); // 16 channels if (name.isEmpty() || ! has16Outs) return; name += " (16 outputs)"; DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", PLUGIN_IS_SYNTH); DISCOVERY_OUT("name", name.buffer()); DISCOVERY_OUT("label", label); if (info != nullptr) DISCOVERY_OUT("maker", info->Artists); DISCOVERY_OUT("audio.outs", 32); DISCOVERY_OUT("midi.ins", 1); DISCOVERY_OUT("end", "------------"); } private: LinuxSampler::Engine* fEngine; CARLA_PREVENT_HEAP_ALLOCATION CARLA_DECLARE_NON_COPY_CLASS(LinuxSamplerScopedEngine) }; #endif // HAVE_LINUXSAMPLER // ------------------------------ Plugin Checks ----------------------------- static void do_ladspa_check(lib_t& libHandle, const char* const filename, const bool doInit) { LADSPA_Descriptor_Function descFn = lib_symbol<LADSPA_Descriptor_Function>(libHandle, "ladspa_descriptor"); if (descFn == nullptr) { DISCOVERY_OUT("error", "Not a LADSPA plugin"); return; } const LADSPA_Descriptor* descriptor; { descriptor = descFn(0); if (descriptor == nullptr) { DISCOVERY_OUT("error", "Binary doesn't contain any plugins"); return; } if (doInit && descriptor->instantiate != nullptr && descriptor->cleanup != nullptr) { LADSPA_Handle handle = descriptor->instantiate(descriptor, kSampleRatei); if (handle == nullptr) { DISCOVERY_OUT("error", "Failed to init first LADSPA plugin"); return; } descriptor->cleanup(handle); lib_close(libHandle); libHandle = lib_open(filename); if (libHandle == nullptr) { print_lib_error(filename); return; } descFn = lib_symbol<LADSPA_Descriptor_Function>(libHandle, "ladspa_descriptor"); if (descFn == nullptr) { DISCOVERY_OUT("error", "Not a LADSPA plugin (#2)"); return; } } } unsigned long i = 0; while ((descriptor = descFn(i++)) != nullptr) { if (descriptor->instantiate == nullptr) { DISCOVERY_OUT("error", "Plugin '" << descriptor->Name << "' has no instantiate()"); continue; } if (descriptor->cleanup == nullptr) { DISCOVERY_OUT("error", "Plugin '" << descriptor->Name << "' has no cleanup()"); continue; } if (descriptor->run == nullptr) { DISCOVERY_OUT("error", "Plugin '" << descriptor->Name << "' has no run()"); continue; } if (! LADSPA_IS_HARD_RT_CAPABLE(descriptor->Properties)) { DISCOVERY_OUT("warning", "Plugin '" << descriptor->Name << "' is not hard real-time capable"); } uint hints = 0x0; int audioIns = 0; int audioOuts = 0; int audioTotal = 0; int parametersIns = 0; int parametersOuts = 0; int parametersTotal = 0; if (LADSPA_IS_HARD_RT_CAPABLE(descriptor->Properties)) hints |= PLUGIN_IS_RTSAFE; for (unsigned long j=0; j < descriptor->PortCount; ++j) { CARLA_ASSERT(descriptor->PortNames[j] != nullptr); const LADSPA_PortDescriptor portDescriptor = descriptor->PortDescriptors[j]; if (LADSPA_IS_PORT_AUDIO(portDescriptor)) { if (LADSPA_IS_PORT_INPUT(portDescriptor)) audioIns += 1; else if (LADSPA_IS_PORT_OUTPUT(portDescriptor)) audioOuts += 1; audioTotal += 1; } else if (LADSPA_IS_PORT_CONTROL(portDescriptor)) { if (LADSPA_IS_PORT_INPUT(portDescriptor)) parametersIns += 1; else if (LADSPA_IS_PORT_OUTPUT(portDescriptor) && std::strcmp(descriptor->PortNames[j], "latency") != 0 && std::strcmp(descriptor->PortNames[j], "_latency") != 0) parametersOuts += 1; parametersTotal += 1; } } if (doInit) { // ----------------------------------------------------------------------- // start crash-free plugin test LADSPA_Handle handle = descriptor->instantiate(descriptor, kSampleRatei); if (handle == nullptr) { DISCOVERY_OUT("error", "Failed to init LADSPA plugin"); continue; } // Test quick init and cleanup descriptor->cleanup(handle); handle = descriptor->instantiate(descriptor, kSampleRatei); if (handle == nullptr) { DISCOVERY_OUT("error", "Failed to init LADSPA plugin (#2)"); continue; } LADSPA_Data bufferAudio[kBufferSize][audioTotal]; LADSPA_Data bufferParams[parametersTotal]; LADSPA_Data min, max, def; for (unsigned long j=0, iA=0, iC=0; j < descriptor->PortCount; ++j) { const LADSPA_PortDescriptor portDescriptor = descriptor->PortDescriptors[j]; const LADSPA_PortRangeHint portRangeHints = descriptor->PortRangeHints[j]; const char* const portName = descriptor->PortNames[j]; if (LADSPA_IS_PORT_AUDIO(portDescriptor)) { carla_zeroFloat(bufferAudio[iA], kBufferSize); descriptor->connect_port(handle, j, bufferAudio[iA++]); } else if (LADSPA_IS_PORT_CONTROL(portDescriptor)) { // min value if (LADSPA_IS_HINT_BOUNDED_BELOW(portRangeHints.HintDescriptor)) min = portRangeHints.LowerBound; else min = 0.0f; // max value if (LADSPA_IS_HINT_BOUNDED_ABOVE(portRangeHints.HintDescriptor)) max = portRangeHints.UpperBound; else max = 1.0f; if (min > max) { DISCOVERY_OUT("warning", "Parameter '" << portName << "' is broken: min > max"); max = min + 0.1f; } else if (carla_compareFloats(min, max)) { DISCOVERY_OUT("warning", "Parameter '" << portName << "' is broken: max == min"); max = min + 0.1f; } // default value def = get_default_ladspa_port_value(portRangeHints.HintDescriptor, min, max); if (LADSPA_IS_HINT_SAMPLE_RATE(portRangeHints.HintDescriptor)) { min *= kSampleRatef; max *= kSampleRatef; def *= kSampleRatef; } if (LADSPA_IS_PORT_OUTPUT(portDescriptor) && (std::strcmp(portName, "latency") == 0 || std::strcmp(portName, "_latency") == 0)) { // latency parameter def = 0.0f; } else { if (def < min) def = min; else if (def > max) def = max; } bufferParams[iC] = def; descriptor->connect_port(handle, j, &bufferParams[iC++]); } } if (descriptor->activate != nullptr) descriptor->activate(handle); descriptor->run(handle, kBufferSize); if (descriptor->deactivate != nullptr) descriptor->deactivate(handle); descriptor->cleanup(handle); // end crash-free plugin test // ----------------------------------------------------------------------- } DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", hints); DISCOVERY_OUT("name", descriptor->Name); DISCOVERY_OUT("label", descriptor->Label); DISCOVERY_OUT("maker", descriptor->Maker); DISCOVERY_OUT("uniqueId", descriptor->UniqueID); DISCOVERY_OUT("audio.ins", audioIns); DISCOVERY_OUT("audio.outs", audioOuts); DISCOVERY_OUT("parameters.ins", parametersIns); DISCOVERY_OUT("parameters.outs", parametersOuts); DISCOVERY_OUT("end", "------------"); } } static void do_dssi_check(lib_t& libHandle, const char* const filename, const bool doInit) { DSSI_Descriptor_Function descFn = lib_symbol<DSSI_Descriptor_Function>(libHandle, "dssi_descriptor"); if (descFn == nullptr) { DISCOVERY_OUT("error", "Not a DSSI plugin"); return; } const DSSI_Descriptor* descriptor; { descriptor = descFn(0); if (descriptor == nullptr) { DISCOVERY_OUT("error", "Binary doesn't contain any plugins"); return; } const LADSPA_Descriptor* const ldescriptor(descriptor->LADSPA_Plugin); if (ldescriptor == nullptr) { DISCOVERY_OUT("error", "DSSI plugin doesn't provide the LADSPA interface"); return; } if (doInit && ldescriptor->instantiate != nullptr && ldescriptor->cleanup != nullptr) { LADSPA_Handle handle = ldescriptor->instantiate(ldescriptor, kSampleRatei); if (handle == nullptr) { DISCOVERY_OUT("error", "Failed to init first LADSPA plugin"); return; } ldescriptor->cleanup(handle); lib_close(libHandle); libHandle = lib_open(filename); if (libHandle == nullptr) { print_lib_error(filename); return; } descFn = lib_symbol<DSSI_Descriptor_Function>(libHandle, "dssi_descriptor"); if (descFn == nullptr) { DISCOVERY_OUT("error", "Not a DSSI plugin (#2)"); return; } } } unsigned long i = 0; while ((descriptor = descFn(i++)) != nullptr) { const LADSPA_Descriptor* const ldescriptor(descriptor->LADSPA_Plugin); if (ldescriptor == nullptr) { DISCOVERY_OUT("error", "Plugin '" << ldescriptor->Name << "' has no LADSPA interface"); continue; } if (descriptor->DSSI_API_Version != DSSI_VERSION_MAJOR) { DISCOVERY_OUT("error", "Plugin '" << ldescriptor->Name << "' uses an unsupported DSSI spec version " << descriptor->DSSI_API_Version); continue; } if (ldescriptor->instantiate == nullptr) { DISCOVERY_OUT("error", "Plugin '" << ldescriptor->Name << "' has no instantiate()"); continue; } if (ldescriptor->cleanup == nullptr) { DISCOVERY_OUT("error", "Plugin '" << ldescriptor->Name << "' has no cleanup()"); continue; } if (ldescriptor->run == nullptr && descriptor->run_synth == nullptr && descriptor->run_multiple_synths == nullptr) { DISCOVERY_OUT("error", "Plugin '" << ldescriptor->Name << "' has no run(), run_synth() or run_multiple_synths()"); continue; } if (! LADSPA_IS_HARD_RT_CAPABLE(ldescriptor->Properties)) { DISCOVERY_OUT("warning", "Plugin '" << ldescriptor->Name << "' is not hard real-time capable"); } uint hints = 0x0; int audioIns = 0; int audioOuts = 0; int audioTotal = 0; int midiIns = 0; int parametersIns = 0; int parametersOuts = 0; int parametersTotal = 0; if (LADSPA_IS_HARD_RT_CAPABLE(ldescriptor->Properties)) hints |= PLUGIN_IS_RTSAFE; for (unsigned long j=0; j < ldescriptor->PortCount; ++j) { CARLA_ASSERT(ldescriptor->PortNames[j] != nullptr); const LADSPA_PortDescriptor portDescriptor = ldescriptor->PortDescriptors[j]; if (LADSPA_IS_PORT_AUDIO(portDescriptor)) { if (LADSPA_IS_PORT_INPUT(portDescriptor)) audioIns += 1; else if (LADSPA_IS_PORT_OUTPUT(portDescriptor)) audioOuts += 1; audioTotal += 1; } else if (LADSPA_IS_PORT_CONTROL(portDescriptor)) { if (LADSPA_IS_PORT_INPUT(portDescriptor)) parametersIns += 1; else if (LADSPA_IS_PORT_OUTPUT(portDescriptor) && std::strcmp(ldescriptor->PortNames[j], "latency") != 0 && std::strcmp(ldescriptor->PortNames[j], "_latency") != 0) parametersOuts += 1; parametersTotal += 1; } } if (descriptor->run_synth != nullptr || descriptor->run_multiple_synths != nullptr) midiIns = 1; if (midiIns > 0 && audioIns == 0 && audioOuts > 0) hints |= PLUGIN_IS_SYNTH; if (const char* const ui = find_dssi_ui(filename, ldescriptor->Label)) { hints |= PLUGIN_HAS_CUSTOM_UI; delete[] ui; } if (doInit) { // ----------------------------------------------------------------------- // start crash-free plugin test LADSPA_Handle handle = ldescriptor->instantiate(ldescriptor, kSampleRatei); if (handle == nullptr) { DISCOVERY_OUT("error", "Failed to init DSSI plugin"); continue; } // Test quick init and cleanup ldescriptor->cleanup(handle); handle = ldescriptor->instantiate(ldescriptor, kSampleRatei); if (handle == nullptr) { DISCOVERY_OUT("error", "Failed to init DSSI plugin (#2)"); continue; } LADSPA_Data bufferAudio[kBufferSize][audioTotal]; LADSPA_Data bufferParams[parametersTotal]; LADSPA_Data min, max, def; for (unsigned long j=0, iA=0, iC=0; j < ldescriptor->PortCount; ++j) { const LADSPA_PortDescriptor portDescriptor = ldescriptor->PortDescriptors[j]; const LADSPA_PortRangeHint portRangeHints = ldescriptor->PortRangeHints[j]; const char* const portName = ldescriptor->PortNames[j]; if (LADSPA_IS_PORT_AUDIO(portDescriptor)) { carla_zeroFloat(bufferAudio[iA], kBufferSize); ldescriptor->connect_port(handle, j, bufferAudio[iA++]); } else if (LADSPA_IS_PORT_CONTROL(portDescriptor)) { // min value if (LADSPA_IS_HINT_BOUNDED_BELOW(portRangeHints.HintDescriptor)) min = portRangeHints.LowerBound; else min = 0.0f; // max value if (LADSPA_IS_HINT_BOUNDED_ABOVE(portRangeHints.HintDescriptor)) max = portRangeHints.UpperBound; else max = 1.0f; if (min > max) { DISCOVERY_OUT("warning", "Parameter '" << portName << "' is broken: min > max"); max = min + 0.1f; } else if (carla_compareFloats(min, max)) { DISCOVERY_OUT("warning", "Parameter '" << portName << "' is broken: max == min"); max = min + 0.1f; } // default value def = get_default_ladspa_port_value(portRangeHints.HintDescriptor, min, max); if (LADSPA_IS_HINT_SAMPLE_RATE(portRangeHints.HintDescriptor)) { min *= kSampleRatef; max *= kSampleRatef; def *= kSampleRatef; } if (LADSPA_IS_PORT_OUTPUT(portDescriptor) && (std::strcmp(portName, "latency") == 0 || std::strcmp(portName, "_latency") == 0)) { // latency parameter def = 0.0f; } else { if (def < min) def = min; else if (def > max) def = max; } bufferParams[iC] = def; ldescriptor->connect_port(handle, j, &bufferParams[iC++]); } } // select first midi-program if available if (descriptor->get_program != nullptr && descriptor->select_program != nullptr) { if (const DSSI_Program_Descriptor* const pDesc = descriptor->get_program(handle, 0)) descriptor->select_program(handle, pDesc->Bank, pDesc->Program); } if (ldescriptor->activate != nullptr) ldescriptor->activate(handle); if (descriptor->run_synth != nullptr || descriptor->run_multiple_synths != nullptr) { snd_seq_event_t midiEvents[2]; carla_zeroStruct<snd_seq_event_t>(midiEvents, 2); const unsigned long midiEventCount = 2; midiEvents[0].type = SND_SEQ_EVENT_NOTEON; midiEvents[0].data.note.note = 64; midiEvents[0].data.note.velocity = 100; midiEvents[1].type = SND_SEQ_EVENT_NOTEOFF; midiEvents[1].data.note.note = 64; midiEvents[1].data.note.velocity = 0; midiEvents[1].time.tick = kBufferSize/2; if (descriptor->run_multiple_synths != nullptr && descriptor->run_synth == nullptr) { LADSPA_Handle handlePtr[1] = { handle }; snd_seq_event_t* midiEventsPtr[1] = { midiEvents }; unsigned long midiEventCountPtr[1] = { midiEventCount }; descriptor->run_multiple_synths(1, handlePtr, kBufferSize, midiEventsPtr, midiEventCountPtr); } else descriptor->run_synth(handle, kBufferSize, midiEvents, midiEventCount); } else ldescriptor->run(handle, kBufferSize); if (ldescriptor->deactivate != nullptr) ldescriptor->deactivate(handle); ldescriptor->cleanup(handle); // end crash-free plugin test // ----------------------------------------------------------------------- } DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", hints); DISCOVERY_OUT("name", ldescriptor->Name); DISCOVERY_OUT("label", ldescriptor->Label); DISCOVERY_OUT("maker", ldescriptor->Maker); DISCOVERY_OUT("uniqueId", ldescriptor->UniqueID); DISCOVERY_OUT("audio.ins", audioIns); DISCOVERY_OUT("audio.outs", audioOuts); DISCOVERY_OUT("midi.ins", midiIns); DISCOVERY_OUT("parameters.ins", parametersIns); DISCOVERY_OUT("parameters.outs", parametersOuts); DISCOVERY_OUT("end", "------------"); } } static void do_lv2_check(const char* const bundle, const bool doInit) { Lv2WorldClass& lv2World(Lv2WorldClass::getInstance()); Lilv::Node bundleNode(lv2World.new_file_uri(nullptr, bundle)); CARLA_SAFE_ASSERT_RETURN(bundleNode.is_uri(),); CarlaString sBundle(bundleNode.as_uri()); if (! sBundle.endsWith("/")) sBundle += "/"; // Load bundle lv2World.load_bundle(sBundle); // Load plugins in this bundle const Lilv::Plugins lilvPlugins(lv2World.get_all_plugins()); // Get all plugin URIs in this bundle StringArray URIs; LILV_FOREACH(plugins, it, lilvPlugins) { Lilv::Plugin lilvPlugin(lilv_plugins_get(lilvPlugins, it)); if (const char* const uri = lilvPlugin.get_uri().as_string()) URIs.addIfNotAlreadyThere(String(uri)); } if (URIs.size() == 0) { DISCOVERY_OUT("warning", "LV2 Bundle doesn't provide any plugins"); return; } // Get & check every plugin-instance for (int i=0, count=URIs.size(); i < count; ++i) { const LV2_RDF_Descriptor* const rdfDescriptor(lv2_rdf_new(URIs[i].toRawUTF8(), false)); if (rdfDescriptor == nullptr || rdfDescriptor->URI == nullptr) { DISCOVERY_OUT("error", "Failed to find LV2 plugin '" << URIs[i].toRawUTF8() << "'"); continue; } if (doInit) { // test if DLL is loadable, twice const lib_t libHandle1 = lib_open(rdfDescriptor->Binary); if (libHandle1 == nullptr) { print_lib_error(rdfDescriptor->Binary); delete rdfDescriptor; continue; } lib_close(libHandle1); const lib_t libHandle2 = lib_open(rdfDescriptor->Binary); if (libHandle2 == nullptr) { print_lib_error(rdfDescriptor->Binary); delete rdfDescriptor; continue; } lib_close(libHandle2); } // test if we support all required ports and features { bool supported = true; for (uint32_t j=0; j < rdfDescriptor->PortCount && supported; ++j) { const LV2_RDF_Port* const rdfPort(&rdfDescriptor->Ports[j]); if (is_lv2_port_supported(rdfPort->Types)) { pass(); } else if (! LV2_IS_PORT_OPTIONAL(rdfPort->Properties)) { DISCOVERY_OUT("error", "Plugin '" << rdfDescriptor->URI << "' requires a non-supported port type (portName: '" << rdfPort->Name << "')"); supported = false; break; } } for (uint32_t j=0; j < rdfDescriptor->FeatureCount && supported; ++j) { const LV2_RDF_Feature& feature(rdfDescriptor->Features[j]); if (std::strcmp(feature.URI, LV2_DATA_ACCESS_URI) == 0 || std::strcmp(feature.URI, LV2_INSTANCE_ACCESS_URI) == 0) { DISCOVERY_OUT("warning", "Plugin '" << rdfDescriptor->URI << "' DSP wants UI feature '" << feature.URI << "', ignoring this"); } else if (LV2_IS_FEATURE_REQUIRED(feature.Type) && ! is_lv2_feature_supported(feature.URI)) { DISCOVERY_OUT("error", "Plugin '" << rdfDescriptor->URI << "' requires a non-supported feature '" << feature.URI << "'"); supported = false; break; } } if (! supported) { delete rdfDescriptor; continue; } } uint hints = 0x0; int audioIns = 0; int audioOuts = 0; int midiIns = 0; int midiOuts = 0; int parametersIns = 0; int parametersOuts = 0; for (uint32_t j=0; j < rdfDescriptor->FeatureCount; ++j) { const LV2_RDF_Feature* const rdfFeature(&rdfDescriptor->Features[j]); if (std::strcmp(rdfFeature->URI, LV2_CORE__hardRTCapable) == 0) hints |= PLUGIN_IS_RTSAFE; } for (uint32_t j=0; j < rdfDescriptor->PortCount; ++j) { const LV2_RDF_Port* const rdfPort(&rdfDescriptor->Ports[j]); if (LV2_IS_PORT_AUDIO(rdfPort->Types)) { if (LV2_IS_PORT_INPUT(rdfPort->Types)) audioIns += 1; else if (LV2_IS_PORT_OUTPUT(rdfPort->Types)) audioOuts += 1; } else if (LV2_IS_PORT_CONTROL(rdfPort->Types)) { if (LV2_IS_PORT_DESIGNATION_LATENCY(rdfPort->Designation)) { pass(); } else if (LV2_IS_PORT_DESIGNATION_SAMPLE_RATE(rdfPort->Designation)) { pass(); } else if (LV2_IS_PORT_DESIGNATION_FREEWHEELING(rdfPort->Designation)) { pass(); } else if (LV2_IS_PORT_DESIGNATION_TIME(rdfPort->Designation)) { pass(); } else { if (LV2_IS_PORT_INPUT(rdfPort->Types)) parametersIns += 1; else if (LV2_IS_PORT_OUTPUT(rdfPort->Types)) parametersOuts += 1; } } else if (LV2_PORT_SUPPORTS_MIDI_EVENT(rdfPort->Types)) { if (LV2_IS_PORT_INPUT(rdfPort->Types)) midiIns += 1; else if (LV2_IS_PORT_OUTPUT(rdfPort->Types)) midiOuts += 1; } } if (LV2_IS_INSTRUMENT(rdfDescriptor->Type[0], rdfDescriptor->Type[1])) hints |= PLUGIN_IS_SYNTH; if (rdfDescriptor->UICount > 0) hints |= PLUGIN_HAS_CUSTOM_UI; DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", hints); if (rdfDescriptor->Name != nullptr) DISCOVERY_OUT("name", rdfDescriptor->Name); if (rdfDescriptor->Author != nullptr) DISCOVERY_OUT("maker", rdfDescriptor->Author); DISCOVERY_OUT("uri", rdfDescriptor->URI); DISCOVERY_OUT("uniqueId", rdfDescriptor->UniqueID); DISCOVERY_OUT("audio.ins", audioIns); DISCOVERY_OUT("audio.outs", audioOuts); DISCOVERY_OUT("midi.ins", midiIns); DISCOVERY_OUT("midi.outs", midiOuts); DISCOVERY_OUT("parameters.ins", parametersIns); DISCOVERY_OUT("parameters.outs", parametersOuts); DISCOVERY_OUT("end", "------------"); delete rdfDescriptor; } } #ifndef CARLA_OS_MAC static void do_vst_check(lib_t& libHandle, const bool doInit) { VST_Function vstFn = lib_symbol<VST_Function>(libHandle, "VSTPluginMain"); if (vstFn == nullptr) { vstFn = lib_symbol<VST_Function>(libHandle, "main"); if (vstFn == nullptr) { DISCOVERY_OUT("error", "Not a VST plugin"); return; } } AEffect* const effect = vstFn(vstHostCallback); if (effect == nullptr || effect->magic != kEffectMagic) { DISCOVERY_OUT("error", "Failed to init VST plugin, or VST magic failed"); return; } if (effect->uniqueID == 0) { DISCOVERY_OUT("error", "Plugin doesn't have an Unique ID"); effect->dispatcher(effect, effClose, 0, 0, nullptr, 0.0f); return; } gVstCurrentUniqueId = effect->uniqueID; effect->dispatcher(effect, DECLARE_VST_DEPRECATED(effIdentify), 0, 0, nullptr, 0.0f); effect->dispatcher(effect, DECLARE_VST_DEPRECATED(effSetBlockSizeAndSampleRate), 0, kBufferSize, nullptr, kSampleRate); effect->dispatcher(effect, effSetSampleRate, 0, 0, nullptr, kSampleRate); effect->dispatcher(effect, effSetBlockSize, 0, kBufferSize, nullptr, 0.0f); effect->dispatcher(effect, effSetProcessPrecision, 0, kVstProcessPrecision32, nullptr, 0.0f); effect->dispatcher(effect, effOpen, 0, 0, nullptr, 0.0f); effect->dispatcher(effect, effSetProgram, 0, 0, nullptr, 0.0f); char strBuf[STR_MAX+1]; CarlaString cName; CarlaString cProduct; CarlaString cVendor; const intptr_t vstCategory = effect->dispatcher(effect, effGetPlugCategory, 0, 0, nullptr, 0.0f); //for (int32_t i = effect->numInputs; --i >= 0;) effect->dispatcher(effect, DECLARE_VST_DEPRECATED(effConnectInput), i, 1, 0, 0); //for (int32_t i = effect->numOutputs; --i >= 0;) effect->dispatcher(effect, DECLARE_VST_DEPRECATED(effConnectOutput), i, 1, 0, 0); carla_zeroChar(strBuf, STR_MAX+1); if (effect->dispatcher(effect, effGetVendorString, 0, 0, strBuf, 0.0f) == 1) cVendor = strBuf; carla_zeroChar(strBuf, STR_MAX+1); if (vstCategory == kPlugCategShell) { gVstCurrentUniqueId = effect->dispatcher(effect, effShellGetNextPlugin, 0, 0, strBuf, 0.0f); CARLA_SAFE_ASSERT_RETURN(gVstCurrentUniqueId != 0,); cName = strBuf; } else { if (effect->dispatcher(effect, effGetEffectName, 0, 0, strBuf, 0.0f) == 1) cName = strBuf; } for (;;) { carla_zeroChar(strBuf, STR_MAX+1); if (effect->dispatcher(effect, effGetProductString, 0, 0, strBuf, 0.0f) == 1) cProduct = strBuf; else cProduct.clear(); uint hints = 0x0; int audioIns = effect->numInputs; int audioOuts = effect->numOutputs; int midiIns = 0; int midiOuts = 0; int parameters = effect->numParams; if (effect->flags & effFlagsHasEditor) hints |= PLUGIN_HAS_CUSTOM_UI; if (effect->flags & effFlagsIsSynth) hints |= PLUGIN_IS_SYNTH; if (vstPluginCanDo(effect, "receiveVstEvents") || vstPluginCanDo(effect, "receiveVstMidiEvent") || (effect->flags & effFlagsIsSynth) != 0) midiIns = 1; if (vstPluginCanDo(effect, "sendVstEvents") || vstPluginCanDo(effect, "sendVstMidiEvent")) midiOuts = 1; // ----------------------------------------------------------------------- // start crash-free plugin test if (doInit) { if (gVstNeedsIdle) effect->dispatcher(effect, DECLARE_VST_DEPRECATED(effIdle), 0, 0, nullptr, 0.0f); effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f); effect->dispatcher(effect, effStartProcess, 0, 0, nullptr, 0.0f); if (gVstNeedsIdle) effect->dispatcher(effect, DECLARE_VST_DEPRECATED(effIdle), 0, 0, nullptr, 0.0f); // Plugin might call wantMidi() during resume if (midiIns == 0 && gVstWantsMidi) { midiIns = 1; } float* bufferAudioIn[audioIns]; for (int j=0; j < audioIns; ++j) { bufferAudioIn[j] = new float[kBufferSize]; carla_zeroFloat(bufferAudioIn[j], kBufferSize); } float* bufferAudioOut[audioOuts]; for (int j=0; j < audioOuts; ++j) { bufferAudioOut[j] = new float[kBufferSize]; carla_zeroFloat(bufferAudioOut[j], kBufferSize); } struct VstEventsFixed { int32_t numEvents; intptr_t reserved; VstEvent* data[2]; VstEventsFixed() : numEvents(0), reserved(0) { data[0] = data[1] = nullptr; } } events; VstMidiEvent midiEvents[2]; carla_zeroStruct<VstMidiEvent>(midiEvents, 2); midiEvents[0].type = kVstMidiType; midiEvents[0].byteSize = sizeof(VstMidiEvent); midiEvents[0].midiData[0] = char(MIDI_STATUS_NOTE_ON); midiEvents[0].midiData[1] = 64; midiEvents[0].midiData[2] = 100; midiEvents[1].type = kVstMidiType; midiEvents[1].byteSize = sizeof(VstMidiEvent); midiEvents[1].midiData[0] = char(MIDI_STATUS_NOTE_OFF); midiEvents[1].midiData[1] = 64; midiEvents[1].deltaFrames = kBufferSize/2; events.numEvents = 2; events.data[0] = (VstEvent*)&midiEvents[0]; events.data[1] = (VstEvent*)&midiEvents[1]; // processing gVstIsProcessing = true; if (midiIns > 0) effect->dispatcher(effect, effProcessEvents, 0, 0, &events, 0.0f); if ((effect->flags & effFlagsCanReplacing) > 0 && effect->processReplacing != nullptr && effect->processReplacing != effect->DECLARE_VST_DEPRECATED(process)) effect->processReplacing(effect, bufferAudioIn, bufferAudioOut, kBufferSize); else if (effect->DECLARE_VST_DEPRECATED(process) != nullptr) effect->DECLARE_VST_DEPRECATED(process)(effect, bufferAudioIn, bufferAudioOut, kBufferSize); else DISCOVERY_OUT("error", "Plugin doesn't have a process function"); gVstIsProcessing = false; effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f); effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0.0f); if (gVstNeedsIdle) effect->dispatcher(effect, DECLARE_VST_DEPRECATED(effIdle), 0, 0, nullptr, 0.0f); for (int j=0; j < audioIns; ++j) delete[] bufferAudioIn[j]; for (int j=0; j < audioOuts; ++j) delete[] bufferAudioOut[j]; } // end crash-free plugin test // ----------------------------------------------------------------------- DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", hints); DISCOVERY_OUT("name", cName.buffer()); DISCOVERY_OUT("label", cProduct.buffer()); DISCOVERY_OUT("maker", cVendor.buffer()); DISCOVERY_OUT("uniqueId", gVstCurrentUniqueId); DISCOVERY_OUT("audio.ins", audioIns); DISCOVERY_OUT("audio.outs", audioOuts); DISCOVERY_OUT("midi.ins", midiIns); DISCOVERY_OUT("midi.outs", midiOuts); DISCOVERY_OUT("parameters.ins", parameters); DISCOVERY_OUT("end", "------------"); if (vstCategory != kPlugCategShell) break; gVstWantsMidi = false; gVstWantsTime = false; carla_zeroChar(strBuf, STR_MAX+1); gVstCurrentUniqueId = effect->dispatcher(effect, effShellGetNextPlugin, 0, 0, strBuf, 0.0f); if (gVstCurrentUniqueId != 0) cName = strBuf; else break; } if (gVstNeedsIdle) effect->dispatcher(effect, DECLARE_VST_DEPRECATED(effIdle), 0, 0, nullptr, 0.0f); effect->dispatcher(effect, effClose, 0, 0, nullptr, 0.0f); } #endif // ! CARLA_OS_MAC #ifdef USE_JUCE_PROCESSORS static void do_juce_check(const char* const filename_, const char* const stype, const bool doInit) { CARLA_SAFE_ASSERT_RETURN(stype != nullptr && stype[0] != 0,) // FIXME carla_debug("do_juce_check(%s, %s, %s)", filename_, stype, bool2str(doInit)); using namespace juce; juce::String filename; #ifdef CARLA_OS_WIN // Fix for wine usage if (juce_isRunningInWine() && filename_[0] == '/') { filename = filename_; filename.replace("/", "\\"); filename = "Z:" + filename; } else #endif filename = File(filename_).getFullPathName(); juce::ScopedPointer<AudioPluginFormat> pluginFormat; /* */ if (std::strcmp(stype, "VST2") == 0) { #if JUCE_PLUGINHOST_VST pluginFormat = new VSTPluginFormat(); #else DISCOVERY_OUT("error", "VST support not available"); #endif } else if (std::strcmp(stype, "VST3") == 0) { #if JUCE_PLUGINHOST_VST3 pluginFormat = new VST3PluginFormat(); #else DISCOVERY_OUT("error", "VST3 support not available"); #endif } else if (std::strcmp(stype, "AU") == 0) { #if JUCE_PLUGINHOST_AU pluginFormat = new AudioUnitPluginFormat(); #else DISCOVERY_OUT("error", "AU support not available"); #endif } if (pluginFormat == nullptr) { DISCOVERY_OUT("error", stype << " support not available"); return; } #ifdef CARLA_OS_WIN CARLA_SAFE_ASSERT_RETURN(File(filename).existsAsFile(),); #endif CARLA_SAFE_ASSERT_RETURN(pluginFormat->fileMightContainThisPluginType(filename),); OwnedArray<PluginDescription> results; pluginFormat->findAllTypesForFile(results, filename); if (results.size() == 0) { DISCOVERY_OUT("error", "No plugins found"); return; } for (PluginDescription **it = results.begin(), **end = results.end(); it != end; ++it) { PluginDescription* const desc(*it); uint hints = 0x0; int audioIns = desc->numInputChannels; int audioOuts = desc->numOutputChannels; int midiIns = 0; int midiOuts = 0; int parameters = 0; if (desc->isInstrument) hints |= PLUGIN_IS_SYNTH; if (doInit) { if (AudioPluginInstance* const instance = pluginFormat->createInstanceFromDescription(*desc, kSampleRate, kBufferSize)) { instance->refreshParameterList(); parameters = instance->getNumParameters(); if (instance->hasEditor()) hints |= PLUGIN_HAS_CUSTOM_UI; if (instance->acceptsMidi()) midiIns = 1; if (instance->producesMidi()) midiOuts = 1; delete instance; } } DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", hints); DISCOVERY_OUT("name", desc->descriptiveName); DISCOVERY_OUT("label", desc->name); DISCOVERY_OUT("maker", desc->manufacturerName); DISCOVERY_OUT("uniqueId", desc->uid); DISCOVERY_OUT("audio.ins", audioIns); DISCOVERY_OUT("audio.outs", audioOuts); DISCOVERY_OUT("midi.ins", midiIns); DISCOVERY_OUT("midi.outs", midiOuts); DISCOVERY_OUT("parameters.ins", parameters); DISCOVERY_OUT("end", "------------"); } } #endif static void do_fluidsynth_check(const char* const filename, const bool doInit) { #ifdef HAVE_FLUIDSYNTH const String jfilename = String(CharPointer_UTF8(filename)); const File file(jfilename); if (! file.existsAsFile()) { DISCOVERY_OUT("error", "Requested file is not valid or does not exist"); return; } if (! fluid_is_soundfont(filename)) { DISCOVERY_OUT("error", "Not a SF2 file"); return; } int programs = 0; if (doInit) { fluid_settings_t* const f_settings = new_fluid_settings(); CARLA_SAFE_ASSERT_RETURN(f_settings != nullptr,); fluid_synth_t* const f_synth = new_fluid_synth(f_settings); CARLA_SAFE_ASSERT_RETURN(f_synth != nullptr,); const int f_id = fluid_synth_sfload(f_synth, filename, 0); if (f_id < 0) { DISCOVERY_OUT("error", "Failed to load SF2 file"); return; } if (fluid_sfont_t* const f_sfont = fluid_synth_get_sfont_by_id(f_synth, static_cast<uint>(f_id))) { fluid_preset_t f_preset; f_sfont->iteration_start(f_sfont); for (; f_sfont->iteration_next(f_sfont, &f_preset);) ++programs; } delete_fluid_synth(f_synth); delete_fluid_settings(f_settings); } CarlaString name(file.getFileNameWithoutExtension().toRawUTF8()); CarlaString label(name); // 2 channels DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", PLUGIN_IS_SYNTH); DISCOVERY_OUT("name", name.buffer()); DISCOVERY_OUT("label", label.buffer()); DISCOVERY_OUT("audio.outs", 2); DISCOVERY_OUT("midi.ins", 1); DISCOVERY_OUT("parameters.ins", 13); // defined in Carla DISCOVERY_OUT("parameters.outs", 1); DISCOVERY_OUT("end", "------------"); // 16 channels if (doInit && (name.isEmpty() || programs <= 1)) return; name += " (16 outputs)"; DISCOVERY_OUT("init", "-----------"); DISCOVERY_OUT("build", BINARY_NATIVE); DISCOVERY_OUT("hints", PLUGIN_IS_SYNTH); DISCOVERY_OUT("name", name.buffer()); DISCOVERY_OUT("label", label.buffer()); DISCOVERY_OUT("audio.outs", 32); DISCOVERY_OUT("midi.ins", 1); DISCOVERY_OUT("parameters.ins", 13); // defined in Carla DISCOVERY_OUT("parameters.outs", 1); DISCOVERY_OUT("end", "------------"); #else // HAVE_FLUIDSYNTH DISCOVERY_OUT("error", "SF2 support not available"); return; // unused (void)filename; (void)doInit; #endif } static void do_linuxsampler_check(const char* const filename, const char* const stype, const bool doInit) { #ifdef HAVE_LINUXSAMPLER const String jfilename = String(CharPointer_UTF8(filename)); const File file(jfilename); if (! file.existsAsFile()) { DISCOVERY_OUT("error", "Requested file is not valid or does not exist"); return; } if (doInit) const LinuxSamplerScopedEngine engine(filename, stype); else LinuxSamplerScopedEngine::outputInfo(nullptr, file.getFileNameWithoutExtension().toRawUTF8(), std::strcmp(stype, "gig") == 0); #else // HAVE_LINUXSAMPLER DISCOVERY_OUT("error", stype << " support not available"); return; // unused (void)filename; (void)doInit; #endif } // ------------------------------ main entry point ------------------------------ int main(int argc, char* argv[]) { if (argc != 3) { carla_stdout("usage: %s <type> </path/to/plugin>", argv[0]); return 1; } const char* const stype = argv[1]; const char* const filename = argv[2]; const PluginType type = getPluginTypeFromString(stype); CarlaString filenameCheck(filename); filenameCheck.toLower(); if (type != PLUGIN_GIG && type != PLUGIN_SF2 && type != PLUGIN_SFZ) { if (filenameCheck.contains("fluidsynth", true)) { DISCOVERY_OUT("info", "skipping fluidsynth based plugin"); return 0; } if (filenameCheck.contains("linuxsampler", true) || filenameCheck.endsWith("ls16.so")) { DISCOVERY_OUT("info", "skipping linuxsampler based plugin"); return 0; } } bool openLib = false; lib_t handle = nullptr; switch (type) { case PLUGIN_LADSPA: case PLUGIN_DSSI: #ifndef CARLA_OS_MAC case PLUGIN_VST2: openLib = true; #endif default: break; } if (openLib) { handle = lib_open(filename); if (handle == nullptr) { print_lib_error(filename); return 1; } } // never do init for dssi-vst, takes too long and it's crashy bool doInit = ! filenameCheck.contains("dssi-vst", true); if (doInit && getenv("CARLA_DISCOVERY_NO_PROCESSING_CHECKS") != nullptr) doInit = false; if (doInit && handle != nullptr) { // test fast loading & unloading DLL without initializing the plugin(s) if (! lib_close(handle)) { print_lib_error(filename); return 1; } handle = lib_open(filename); if (handle == nullptr) { print_lib_error(filename); return 1; } } switch (type) { case PLUGIN_LADSPA: do_ladspa_check(handle, filename, doInit); break; case PLUGIN_DSSI: do_dssi_check(handle, filename, doInit); break; case PLUGIN_LV2: do_lv2_check(filename, doInit); break; case PLUGIN_VST2: #ifdef CARLA_OS_MAC do_juce_check(filename, "VST2", doInit); #else do_vst_check(handle, doInit); #endif break; case PLUGIN_VST3: #ifdef USE_JUCE_PROCESSORS do_juce_check(filename, "VST3", doInit); #else DISCOVERY_OUT("error", "VST3 support not available"); #endif break; case PLUGIN_AU: #ifdef USE_JUCE_PROCESSORS do_juce_check(filename, "AU", doInit); #else DISCOVERY_OUT("error", "AU support not available"); #endif break; case PLUGIN_GIG: do_linuxsampler_check(filename, "gig", doInit); break; case PLUGIN_SF2: do_fluidsynth_check(filename, doInit); break; case PLUGIN_SFZ: do_linuxsampler_check(filename, "sfz", doInit); break; default: break; } if (openLib && handle != nullptr) lib_close(handle); return 0; } // --------------------------------------------------------------------------
[ "falktx@gmail.com" ]
falktx@gmail.com
6e642ce1f9bc3f186d9ab21c7e04204d0f68f859
3df49f2a3d4da202760e6a516a1b561349251c73
/src/IGDSIIFileReader.h
5282f31534345e258f1952857a83096a59eae7b2
[]
no_license
valerpenko/ONUGDSIIViewer
c7944ea3be5d2029a2c3b9bd59ece1ea779835db
8e222e08c469b2ce4ba84aeba7376bfeb09eba73
refs/heads/master
2021-01-11T21:09:26.234506
2017-01-17T19:12:17
2017-01-17T19:12:17
79,260,757
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: IGDSIIFileReader.h * Author: Val * * Created on 2 января 2017 г., 14:56 */ #ifndef IGDSIIFILEREADER_H #define IGDSIIFILEREADER_H #include "GDSIIRecord.h" class IGDSIIFileReader { public: virtual GDSIIRecord NextRecord() = 0; virtual bool HasNextRecord() = 0; }; #endif /* IGDSIIFILEREADER_H */
[ "valerpenko@mail.ru" ]
valerpenko@mail.ru
6c21a2a679926634a3a120a38c37230166c9b0d3
97ca6b5f3ea1b51a3cc6834285a43d15e815413f
/triangle.cpp
16a27f994a3e06f19a6be33ac61f7d159f332178
[ "MIT" ]
permissive
iRaySpace/college-days
beade3a0baff15165118b5d9ad1dd2b25a890741
955ac9b5e3107af484ee31891068ea453247d05e
refs/heads/master
2016-09-06T08:11:42.395420
2015-03-10T15:45:22
2015-03-10T15:45:22
23,756,246
1
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
#include <iostream> #include <cmath> #define MAX 10 // offset paramaters #define FC_OFFSET 0 #define SC_OFFSET 1 using namespace std; int main() { int x = 0; while(x < MAX * 2) { int y = x < MAX ? x : (MAX * 2 - x) - 1; // zero-based be like int z = (MAX - y) - 1; // zero-based // printing wonders while(y > 0 - FC_OFFSET && y-- < MAX) cout << "- "; while(z > 0 - SC_OFFSET && z-- < MAX) cout << "* "; cout << endl; x = (x == MAX - 1 || x ==(MAX * 2 / 2) - 1) ? x += 2 : x += 1; // escapes unnecessary parts } return 0; }
[ "irayspacii@gmail.com" ]
irayspacii@gmail.com
da23e696dbd2cb1d03c1bce9dca8363bfa7efcdc
cc7643ff887a76a5cacd344993f5812281db8b2d
/src/WebCoreSupport/Stubs/HTMLPluginElement.cpp
28f89f5a108888dc0555e6e405bbf64949316b9c
[ "BSD-3-Clause" ]
permissive
ahixon/webkit.js
e1497345aee2ec81c9895bebf8d705e112c42005
7ed1480d73de11cb25f02e89f11ecf71dfa6e0c2
refs/heads/master
2020-06-18T13:13:54.933869
2016-12-01T10:06:08
2016-12-01T10:06:08
75,136,170
2
0
null
2016-11-30T00:51:10
2016-11-30T00:51:09
null
UTF-8
C++
false
false
6,288
cpp
// #pragma GCC diagnostic ignored "-Wreturn-type" #include "config.h" #include <wtf/Forward.h> #include <wtf/HashMap.h> #include <wtf/PassRefPtr.h> #include <wtf/RefCounted.h> #include <wtf/RefPtr.h> #include "ScriptValue.h" #include "ScriptCallFrame.h" #include "ScriptCallStack.h" #include "DebuggerJS.h" #include "Cursor.h" #include "APICast.h" #include "InspectorValues.h" #include "JSLock.h" #include "bridge/runtime_root.h" #include "File.h" #include "FileList.h" #include "DOMWrapperWorld.h" #include "Icon.h" #include "JSDOMWindowBase.h" #include "DocumentLoader.h" #include "ScriptCachedFrameData.h" #include "PlatformKeyboardEvent.h" #include "ApplicationCacheHost.h" #include "EventHandler.h" #include "BitmapImage.h" #include "Editor.h" #include "GCController.h" #include "HTMLObjectElement.h" #include "Image.h" #include "RenderEmbeddedObject.h" #include "bindings/js/JSLazyEventListener.h" #include "ResourceHandle.h" #include "RuntimeEnabledFeatures.h" #include "MIMETypeRegistry.h" #include "ScrollbarTheme.h" #include "RenderTheme.h" #include "ScriptCallStack.h" #include "HTMLImageLoader.h" #include "MouseEvent.h" #include "SerializedScriptValue.h" #include "HTMLFrameOwnerElement.h" void errorOutIfUsed() { fprintf(stderr, "Call to unused method\n"); abort(); } namespace WebCore { RenderPtr<RenderElement> HTMLPlugInElement::createElementRenderer(PassRef<RenderStyle> style) { errorOutIfUsed(); return nullptr; } void HTMLPlugInElement::defaultEventHandler(Event* event) { errorOutIfUsed(); } void HTMLPlugInElement::didAddUserAgentShadowRoot(ShadowRoot* root) { errorOutIfUsed(); } bool HTMLPlugInElement::requestObject(const String& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues) { errorOutIfUsed(); return false; } void HTMLPlugInElement::setDisplayState(DisplayState state) { errorOutIfUsed(); } void HTMLPlugInElement::swapRendererTimerFired(Timer<HTMLPlugInElement>*) { errorOutIfUsed(); } void HTMLPlugInElement::willDetachRenderers() { errorOutIfUsed(); } WebCore::HTMLPlugInElement::HTMLPlugInElement(WebCore::QualifiedName const& a, WebCore::Document& b) : HTMLFrameOwnerElement(a, b) , m_inBeforeLoadEventHandler(false) , m_swapRendererTimer(this, &HTMLPlugInElement::swapRendererTimerFired) , m_isCapturingMouseEvents(false) , m_displayState(Playing) { errorOutIfUsed(); } WebCore::HTMLPlugInElement::~HTMLPlugInElement() { errorOutIfUsed(); } void HTMLPlugInElement::collectStyleForPresentationAttribute(WebCore::QualifiedName const& a, WTF::AtomicString const& b, WebCore::MutableStyleProperties& c) { errorOutIfUsed(); } bool HTMLPlugInElement::guardedDispatchBeforeLoadEvent(WTF::String const&) { errorOutIfUsed(); return false; } bool HTMLPlugInElement::isKeyboardFocusable(WebCore::KeyboardEvent*) const { errorOutIfUsed(); return false; } bool HTMLPlugInElement::isPluginElement() const { errorOutIfUsed(); return false; } bool HTMLPlugInElement::isPresentationAttribute(WebCore::QualifiedName const&) const { errorOutIfUsed(); return false; } bool HTMLPlugInElement::supportsFocus() const { errorOutIfUsed(); return false; } bool HTMLPlugInElement::willRespondToMouseClickEvents() { errorOutIfUsed(); return false;} HTMLPlugInImageElement::HTMLPlugInImageElement(const QualifiedName& tagName, Document& document, bool createdByParser, PreferPlugInsForImagesOption preferPlugInsForImagesOption) : HTMLPlugInElement(tagName, document) , m_needsWidgetUpdate(!createdByParser) , m_shouldPreferPlugInsForImages(preferPlugInsForImagesOption == ShouldPreferPlugInsForImages) , m_needsDocumentActivationCallbacks(false) , m_simulatedMouseClickTimer(this, &HTMLPlugInImageElement::simulatedMouseClickTimerFired, 0.75) , m_removeSnapshotTimer(this, &HTMLPlugInImageElement::removeSnapshotTimerFired) , m_createdDuringUserGesture(false) , m_isRestartedPlugin(false) , m_needsCheckForSizeChange(false) , m_plugInWasCreated(false) , m_deferredPromotionToPrimaryPlugIn(false) , m_snapshotDecision(SnapshotNotYetDecided) { errorOutIfUsed(); } void HTMLPlugInImageElement::removeSnapshotTimerFired(Timer<HTMLPlugInImageElement>*) { errorOutIfUsed(); } void HTMLPlugInImageElement::simulatedMouseClickTimerFired(DeferrableOneShotTimer<HTMLPlugInImageElement>*) { errorOutIfUsed(); } bool HTMLPlugInImageElement::allowedToLoadFrameURL(WTF::String const&) { errorOutIfUsed(); return false; } void HTMLPlugInImageElement::checkSnapshotStatus() { errorOutIfUsed(); } RenderPtr<RenderElement> HTMLPlugInImageElement::createElementRenderer(WTF::PassRef<WebCore::RenderStyle>) { errorOutIfUsed(); return nullptr; } void HTMLPlugInImageElement::defaultEventHandler(WebCore::Event*) { errorOutIfUsed(); } void HTMLPlugInImageElement::didAddUserAgentShadowRoot(WebCore::ShadowRoot*) { errorOutIfUsed(); } void HTMLPlugInImageElement::didAttachRenderers() { errorOutIfUsed(); } void HTMLPlugInImageElement::didMoveToNewDocument(WebCore::Document*) { errorOutIfUsed(); } void HTMLPlugInImageElement::dispatchPendingMouseClick() { errorOutIfUsed(); } void HTMLPlugInImageElement::documentDidResumeFromPageCache() { errorOutIfUsed(); } void HTMLPlugInImageElement::documentWillSuspendForPageCache() { errorOutIfUsed(); } void HTMLPlugInImageElement::finishParsingChildren() { errorOutIfUsed(); } bool HTMLPlugInImageElement::isImageType() { errorOutIfUsed(); return false; } RenderEmbeddedObject* HTMLPlugInImageElement::renderEmbeddedObject() const { errorOutIfUsed(); return NULL; } bool HTMLPlugInImageElement::requestObject(WTF::String const&, WTF::String const&, WTF::Vector<WTF::String, 0u, WTF::CrashOnOverflow> const&, WTF::Vector<WTF::String, 0u, WTF::CrashOnOverflow> const&) { errorOutIfUsed(); return false; } void HTMLPlugInImageElement::setDisplayState(HTMLPlugInElement::DisplayState) { errorOutIfUsed(); } void HTMLPlugInImageElement::updateSnapshot(WTF::PassRefPtr<WebCore::Image>) { errorOutIfUsed(); } void HTMLPlugInImageElement::willDetachRenderers() { errorOutIfUsed(); } bool HTMLPlugInImageElement::willRecalcStyle(WebCore::Style::Change) { errorOutIfUsed(); return false; } bool HTMLPlugInImageElement::wouldLoadAsNetscapePlugin(WTF::String const&, WTF::String const&) { errorOutIfUsed(); return false; } HTMLPlugInImageElement::~HTMLPlugInImageElement() { errorOutIfUsed(); } }
[ "trevor.linton@gmail.com" ]
trevor.linton@gmail.com
da86e353f18d2ad50d7197ad5e9f8a8920804d93
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/ash/display/unified_mouse_warp_controller_unittest.cc
6aacdf74ac6a26789d2ea9874e38fd16272b1430
[ "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
9,825
cc
// Copyright 2015 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/display/unified_mouse_warp_controller.h" #include "ash/display/display_util.h" #include "ash/display/mirror_window_controller.h" #include "ash/display/mouse_cursor_event_filter.h" #include "ash/host/ash_window_tree_host.h" #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ui/aura/env.h" #include "ui/aura/window_tree_host.h" #include "ui/display/display.h" #include "ui/display/manager/display_manager.h" #include "ui/display/manager/display_manager_utilities.h" #include "ui/display/screen.h" #include "ui/events/test/event_generator.h" #include "ui/wm/core/coordinate_conversion.h" namespace ash { class UnifiedMouseWarpControllerTest : public test::AshTestBase { public: UnifiedMouseWarpControllerTest() {} ~UnifiedMouseWarpControllerTest() override {} void SetUp() override { test::AshTestBase::SetUp(); display_manager()->SetUnifiedDesktopEnabled(true); } protected: bool FindMirrroingDisplayIdContainingNativePoint( const gfx::Point& point_in_native, int64_t* display_id, gfx::Point* point_in_mirroring_host, gfx::Point* point_in_unified_host) { for (auto display : display_manager()->software_mirroring_display_list()) { display::ManagedDisplayInfo info = display_manager()->GetDisplayInfo(display.id()); if (info.bounds_in_native().Contains(point_in_native)) { *display_id = info.id(); *point_in_unified_host = point_in_native; const gfx::Point& origin = info.bounds_in_native().origin(); // Convert to mirroring host. point_in_unified_host->Offset(-origin.x(), -origin.y()); *point_in_mirroring_host = *point_in_unified_host; // Convert from mirroring host to unified host. AshWindowTreeHost* ash_host = Shell::GetInstance() ->window_tree_host_manager() ->mirror_window_controller() ->GetAshWindowTreeHostForDisplayId(info.id()); ash_host->AsWindowTreeHost()->ConvertPointFromHost( point_in_unified_host); return true; } } return false; } bool TestIfMouseWarpsAt(const gfx::Point& point_in_native) { static_cast<UnifiedMouseWarpController*>( Shell::GetInstance() ->mouse_cursor_filter() ->mouse_warp_controller_for_test()) ->update_location_for_test(); int64_t orig_mirroring_display_id; gfx::Point point_in_unified_host; gfx::Point point_in_mirroring_host; if (!FindMirrroingDisplayIdContainingNativePoint( point_in_native, &orig_mirroring_display_id, &point_in_mirroring_host, &point_in_unified_host)) { return false; } #if defined(USE_OZONE) // The location of the ozone's native event is relative to the host. GetEventGenerator().MoveMouseToWithNative(point_in_unified_host, point_in_mirroring_host); #else GetEventGenerator().MoveMouseToWithNative(point_in_unified_host, point_in_native); #endif aura::Window* root = Shell::GetPrimaryRootWindow(); gfx::Point new_location_in_unified_host = aura::Env::GetInstance()->last_mouse_location(); // Convert screen to the host. root->GetHost()->ConvertPointToHost(&new_location_in_unified_host); int new_index = display::FindDisplayIndexContainingPoint( display_manager()->software_mirroring_display_list(), new_location_in_unified_host); if (new_index < 0) return false; return orig_mirroring_display_id != display_manager()->software_mirroring_display_list()[new_index].id(); } MouseCursorEventFilter* event_filter() { return Shell::GetInstance()->mouse_cursor_filter(); } UnifiedMouseWarpController* mouse_warp_controller() { return static_cast<UnifiedMouseWarpController*>( event_filter()->mouse_warp_controller_for_test()); } void BoundaryTestBody(const std::string& displays_with_same_height, const std::string& displays_with_different_heights) { UpdateDisplay(displays_with_same_height); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); // Let the UnifiedMouseWarpController compute the bounds by // generating a mouse move event. GetEventGenerator().MoveMouseTo(gfx::Point(0, 0)); EXPECT_EQ("399,0 1x400", mouse_warp_controller()->first_edge_bounds_in_native_.ToString()); EXPECT_EQ( "0,450 1x400", mouse_warp_controller()->second_edge_bounds_in_native_.ToString()); // Scaled. UpdateDisplay(displays_with_different_heights); root_windows = Shell::GetAllRootWindows(); // Let the UnifiedMouseWarpController compute the bounds by // generating a mouse move event. GetEventGenerator().MoveMouseTo(gfx::Point(1, 1)); EXPECT_EQ("399,0 1x400", mouse_warp_controller()->first_edge_bounds_in_native_.ToString()); EXPECT_EQ( "0,450 1x600", mouse_warp_controller()->second_edge_bounds_in_native_.ToString()); } void NoWarpTestBody() { // Touch the left edge of the first display. EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(0, 10))); // Touch the top edge of the first display. EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(10, 0))); // Touch the bottom edge of the first display. EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(10, 499))); // Touch the right edge of the second display. EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(1099, 10))); // Touch the top edge of the second display. EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(610, 0))); // Touch the bottom edge of the second display. EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(610, 499))); } private: DISALLOW_COPY_AND_ASSIGN(UnifiedMouseWarpControllerTest); }; // Verifies if MouseCursorEventFilter's bounds calculation works correctly. TEST_F(UnifiedMouseWarpControllerTest, BoundaryTest) { if (!SupportsMultipleDisplays()) return; { SCOPED_TRACE("1x1"); BoundaryTestBody("400x400,0+450-700x400", "400x400,0+450-700x600"); } { SCOPED_TRACE("2x1"); BoundaryTestBody("400x400*2,0+450-700x400", "400x400*2,0+450-700x600"); } { SCOPED_TRACE("1x2"); BoundaryTestBody("400x400,0+450-700x400*2", "400x400,0+450-700x600*2"); } { SCOPED_TRACE("2x2"); BoundaryTestBody("400x400*2,0+450-700x400*2", "400x400*2,0+450-700x600*2"); } } // Verifies if the mouse pointer correctly moves to another display in // unified desktop mode. TEST_F(UnifiedMouseWarpControllerTest, WarpMouse) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("500x500,600+0-500x500"); ASSERT_EQ(1, display::Screen::GetScreen()->GetNumDisplays()); EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(10, 10))); // Touch the right edge of the first display. Pointer should warp. EXPECT_TRUE(TestIfMouseWarpsAt(gfx::Point(499, 10))); EXPECT_EQ("501,10", // by 2px. aura::Env::GetInstance()->last_mouse_location().ToString()); // Touch the left edge of the second display. Pointer should warp. EXPECT_TRUE(TestIfMouseWarpsAt(gfx::Point(600, 10))); EXPECT_EQ("498,10", // by 2px. aura::Env::GetInstance()->last_mouse_location().ToString()); { SCOPED_TRACE("1x1 NO WARP"); NoWarpTestBody(); } // With 2X and 1X displays UpdateDisplay("500x500*2,600+0-500x500"); ASSERT_EQ(1, display::Screen::GetScreen()->GetNumDisplays()); EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(10, 10))); // Touch the right edge of the first display. Pointer should warp. EXPECT_TRUE(TestIfMouseWarpsAt(gfx::Point(499, 10))); EXPECT_EQ("250,5", // moved to 501 by 2px, devided by 2 (dsf). aura::Env::GetInstance()->last_mouse_location().ToString()); // Touch the left edge of the second display. Pointer should warp. EXPECT_TRUE(TestIfMouseWarpsAt(gfx::Point(600, 10))); EXPECT_EQ("249,5", // moved to 498 by 2px, divided by 2 (dsf). aura::Env::GetInstance()->last_mouse_location().ToString()); { SCOPED_TRACE("2x1 NO WARP"); NoWarpTestBody(); } // With 1X and 2X displays UpdateDisplay("500x500,600+0-500x500*2"); ASSERT_EQ(1, display::Screen::GetScreen()->GetNumDisplays()); EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(10, 10))); // Touch the right edge of the first display. Pointer should warp. EXPECT_TRUE(TestIfMouseWarpsAt(gfx::Point(499, 10))); EXPECT_EQ("501,10", // by 2px. aura::Env::GetInstance()->last_mouse_location().ToString()); // Touch the left edge of the second display. Pointer should warp. EXPECT_TRUE(TestIfMouseWarpsAt(gfx::Point(600, 10))); EXPECT_EQ("498,10", // by 2px. aura::Env::GetInstance()->last_mouse_location().ToString()); { SCOPED_TRACE("1x2 NO WARP"); NoWarpTestBody(); } // With two 2X displays UpdateDisplay("500x500*2,600+0-500x500*2"); ASSERT_EQ(1, display::Screen::GetScreen()->GetNumDisplays()); EXPECT_FALSE(TestIfMouseWarpsAt(gfx::Point(10, 10))); // Touch the right edge of the first display. Pointer should warp. EXPECT_TRUE(TestIfMouseWarpsAt(gfx::Point(499, 10))); EXPECT_EQ("250,5", // by 2px. aura::Env::GetInstance()->last_mouse_location().ToString()); // Touch the left edge of the second display. Pointer should warp. EXPECT_TRUE(TestIfMouseWarpsAt(gfx::Point(600, 10))); EXPECT_EQ("249,5", // moved to 498 by 2px, divided by 2 (dsf). aura::Env::GetInstance()->last_mouse_location().ToString()); { SCOPED_TRACE("1x2 NO WARP"); NoWarpTestBody(); } } } // namespace aura
[ "xElvis89x@gmail.com" ]
xElvis89x@gmail.com
f23998116c33563e32919e542cc67f5a4b383c28
7fb7d37a183fae068dfd78de293d4487977c241e
/chrome/browser/chromeos/enrollment_dialog_view.h
0e54c8611d371d76c9530c7f9d9acb2add383b84
[ "BSD-3-Clause" ]
permissive
robclark/chromium
f643a51bb759ac682341e3bb82cc153ab928cd34
f097b6ea775c27e5352c94ddddd264dd2af21479
refs/heads/master
2021-01-20T00:56:40.515459
2012-05-20T16:04:38
2012-05-20T18:56:07
4,587,416
1
0
null
null
null
null
UTF-8
C++
false
false
855
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_ENROLLMENT_DIALOG_VIEW_H_ #define CHROME_BROWSER_CHROMEOS_ENROLLMENT_DIALOG_VIEW_H_ #pragma once #include "base/callback.h" #include "googleurl/src/gurl.h" #include "net/base/cert_database.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/window/dialog_delegate.h" class Profile; namespace chromeos { class EnrollmentDelegate; EnrollmentDelegate* CreateEnrollmentDelegate(gfx::NativeWindow owning_window, const std::string& network_name, Profile* profile); } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_ENROLLMENT_DIALOG_VIEW_H_
[ "gspencer@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98" ]
gspencer@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98
191f7b0c29277df4ccb24b15433a029c70f09749
10b56e44ff7a3d65c4515bc9d3429f9d065db749
/Hmwrk/Gaddis_8th_8.7/main.cpp
902664b3b6d5763bfeeffc0d9f0090f695abede9
[]
no_license
Rbarayuga/BarayugaRaphael_CSC17a_48096
5c0c38b443328c9610f9ce0d2ffceda76cceb43c
00f347d04d5b0e1157710054909a9428db9ff5f3
refs/heads/master
2020-04-05T22:57:33.579150
2016-12-09T22:06:34
2016-12-09T22:06:34
68,042,757
0
1
null
null
null
null
UTF-8
C++
false
false
2,242
cpp
/* * File: main.cpp * Author: Raphael M.B. Barayuga * Purpose: Review Homework * Created on September 21, 2016, 7:49 PM */ //system libraries #include <iostream> #include <string> using namespace std; //Function Prototype int binaryS(string[], int, string); //BinarySearch void sortArray(string[], int); // Sort the array int main(int argc, char** argv) { //Declare const int SIZE = 20; string person; int results; //8-8 Skeleton string names[SIZE] = {"Bill", "Bart", "Allen", "Griffin ", " Marty", "Rose", "Taylor ", "Johnson ", "Allison", " Joe", "Wolfe", "Jean", "Weaver", "Pore ", "Greg", "Javens", "Harrison", "Cathy", "Gordon", "Holland"}; //Sort sortArray(names, SIZE); //Input //Can Only Pick from name list cout << " Who would you like to search for? " << person << endl; cin>>person; results = binaryS(names, SIZE, person); cout << "The name " << names[results] << " is located in the cell number " << results << " in the array" << endl; //Does not display any other names except for names inside return 0; } //From Chapter's binarySearch int binaryS(string a[], int n, string i) { int first = 0, last = n - 1, middle, position = -1; bool found = false; while (!found && first <= last) { middle = (first + last) / 2; if (a[middle] == i) { found = true; position = middle; } else if (a[middle] > i) last = middle - 1; else first = middle + 1; } return position; } //Sort void sortArray(string array[], int names) { bool swap = false; string y; do { swap = false; for (int count = 0; count < (names - 1); count++) { if (array[count] > array[count + 1]) { y = array[count]; array[count] = array[count + 1]; array[count + 1] = y; swap = true; } } } while (swap); }
[ "Raphael.barayuga@gmail.com" ]
Raphael.barayuga@gmail.com
339498b3fffb6ebf449fdf91101da020f1cfc5a5
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/libtorrent/2017/8/test_threads.cpp
0baa059181782e86d40495f64170b188c3a073a4
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
3,357
cpp
/* Copyright (c) 2010, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <functional> #include <atomic> #include <list> #include <thread> #include <mutex> #include <condition_variable> #include "test.hpp" #include "libtorrent/time.hpp" using namespace lt; void fun(std::condition_variable* s, std::mutex* m, int* waiting, int i) { std::printf("thread %d waiting\n", i); std::unique_lock<std::mutex> l(*m); *waiting += 1; s->wait(l); std::printf("thread %d done\n", i); } void increment(std::condition_variable* s, std::mutex* m, int* waiting, std::atomic<int>* c) { std::unique_lock<std::mutex> l(*m); *waiting += 1; s->wait(l); l.unlock(); for (int i = 0; i < 1000000; ++i) ++*c; } void decrement(std::condition_variable* s, std::mutex* m, int* waiting, std::atomic<int>* c) { std::unique_lock<std::mutex> l(*m); *waiting += 1; s->wait(l); l.unlock(); for (int i = 0; i < 1000000; ++i) --*c; } TORRENT_TEST(threads) { std::condition_variable cond; std::mutex m; std::vector<std::thread> threads; int waiting = 0; for (int i = 0; i < 20; ++i) { threads.emplace_back(&fun, &cond, &m, &waiting, i); } // make sure all threads are waiting on the condition_variable std::unique_lock<std::mutex> l(m); while (waiting < 20) { l.unlock(); std::this_thread::sleep_for(lt::milliseconds(10)); l.lock(); } cond.notify_all(); l.unlock(); for (auto& t : threads) t.join(); threads.clear(); waiting = 0; std::atomic<int> c(0); for (int i = 0; i < 3; ++i) { threads.emplace_back(&increment, &cond, &m, &waiting, &c); threads.emplace_back(&decrement, &cond, &m, &waiting, &c); } // make sure all threads are waiting on the condition_variable l.lock(); while (waiting < 6) { l.unlock(); std::this_thread::sleep_for(lt::milliseconds(10)); l.lock(); } cond.notify_all(); l.unlock(); for (auto& t : threads) t.join(); TEST_CHECK(c == 0); }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
fce8dff5867db1722b448b654555575bd6363bd4
c6ad16a29e3e318870864227f7dea02ac9a448fa
/URI Online Judge/Graph/1148.cpp
1c3cd8c4cf19ccd7e35c1dd9ab353ea7fd45cf48
[]
no_license
anasrasyid/Competitive-Programming
625c7081f270cc6bf8867952c57cb5ac847ae0f3
aef6453abecd655fa83d64056907babd8433938d
refs/heads/master
2020-05-25T08:41:20.365941
2019-06-02T12:15:40
2019-06-02T12:15:40
187,717,871
0
0
null
null
null
null
UTF-8
C++
false
false
1,719
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long typedef pair<ll, ll> pii; ll findSame(vector<pii> g, ll x){ for(ll i = 0; i < g.size(); i++) if(g[i].first == x) return i; return -1; } ll route(vector<pii> g[], ll v, ll x, ll y){ vector<ll> dist(v, LONG_MAX); set<pii> cek; cek.insert(make_pair(0,x)); dist[x] = 0; while(!cek.empty()){ pii tmp = *cek.begin(); cek.erase(cek.begin()); ll u = tmp.second; for(auto i : g[u]){ int z = i.first; int w = i.second; if(dist[z] > dist[u] + w){ if(dist[z] != LONG_MAX) cek.erase(cek.find(make_pair(dist[z],z))); dist[z] = dist[u] + w; cek.insert(make_pair(dist[z], z)); } } } if(dist[y] == LONG_MAX) return -1; return dist[y]; } int main(){ ll v, e; cin >> v >> e; while(v != 0 || e != 0){ vector<pii> g[v]; ll s, d, w; for(ll i = 0; i < e; i++){ cin >> s >> d >> w; ll x = findSame(g[--d],--s); if(s == d){ w = 0; }else if(x != -1){ g[d][x].second = 0; w = 0; } g[s].push_back(make_pair(d,w)); } ll n; cin >> n; for (ll i = 0; i < n; i++){ cin >> s >> d; int x = route(g, v, --s, --d); if(x != -1) cout << x << endl; else cout << "Nao e possivel entregar a carta" << endl; } cout << endl; cin >> v >> e; } return 0; }
[ "anasrasyid333@gmail.com" ]
anasrasyid333@gmail.com
9ecebdafc7b639c9473fd5fde32b2925929547cf
2f6b71cedb07cadc9db9ffa5c27180ba8291708a
/include/HostCoordinator.hpp
5e1ddbaaf8e60f56efc8327ec8392c4ebd9ea235
[]
no_license
w-klijn/vector
9c01b7856d024782fc6595a5830ac2e1ce103626
892219db107ba951ebf9150238fad3c204543ae1
refs/heads/master
2021-01-17T21:47:49.747732
2016-06-10T12:57:22
2016-06-10T12:57:22
60,853,939
0
0
null
2016-06-10T14:29:18
2016-06-10T14:29:18
null
UTF-8
C++
false
false
7,093
hpp
#pragma once #include <algorithm> #include <memory> #include <string> #include "definitions.hpp" #include "Array.hpp" #include "Allocator.hpp" namespace memory { // forward declare for type printers template <typename T, class Allocator> class HostCoordinator; #ifdef WITH_CUDA template <typename T, class Allocator> class DeviceCoordinator; #endif namespace util { template <typename T, typename Allocator> struct type_printer<HostCoordinator<T,Allocator>>{ static std::string print() { #if VERBOSE>1 return util::white("HostCoordinator") + "<" + type_printer<T>::print() + ", " + type_printer<Allocator>::print() + ">"; #else return util::white("HostCoordinator") + "<" + type_printer<T>::print() + ">"; #endif } }; template <typename T, typename Allocator> struct pretty_printer<HostCoordinator<T,Allocator>>{ static std::string print(const HostCoordinator<T,Allocator>& val) { return type_printer<HostCoordinator<T,Allocator>>::print();; } }; } // namespace util template <typename T, class Allocator=AlignedAllocator<T> > class HostCoordinator { public: using value_type = T; using pointer = value_type*; using const_pointer = const value_type*; using reference = value_type&; using const_reference = value_type const&; using view_type = ArrayView<value_type, HostCoordinator>; using size_type = types::size_type; using difference_type = types::difference_type; // rebind host_coordinator with another type template <typename Tother> using rebind = HostCoordinator<Tother, Allocator>; view_type allocate(size_type n) { typename Allocator::template rebind<value_type> allocator; pointer ptr = n>0 ? allocator.allocate(n) : nullptr; #ifdef VERBOSE std::cerr << util::type_printer<HostCoordinator>::print() << "::" + util::blue("alocate") << "(" << n << " [" << n*sizeof(value_type) << " bytes]) @ " << ptr << std::endl; #endif return view_type(ptr, n); } void free(view_type& rng) { typename Allocator::template rebind<value_type> allocator; if(rng.data()) { #ifdef VERBOSE std::cerr << util::type_printer<HostCoordinator>::print() << "::" + util::blue("free") << "(" << rng.size() << " [" << rng.size()*sizeof(value_type) << " bytes])" << " @ " << rng.data() << std::endl; #endif allocator.deallocate(rng.data(), rng.size()); } impl::reset(rng); } // copy memory between host memory ranges template <typename Allocator1, typename Allocator2> // requires Allocator1 = Allocator // requires Allocator2 = Allocator void copy(const ArrayView<value_type, HostCoordinator<value_type, Allocator1>>& from, ArrayView<value_type, HostCoordinator<value_type, Allocator2>>& to) { assert(from.size()==to.size()); assert(!from.overlaps(to)); #ifdef VERBOSE using c1 = HostCoordinator<value_type, Allocator1>; std::cerr << util::type_printer<c1>::print() << "::" + util::blue("copy") << "(" << from.size() << " [" << from.size()*sizeof(value_type) << " bytes])" << " " << from.data() << util::yellow(" -> ") << to.data() << std::endl; #endif std::copy(from.begin(), from.end(), to.begin()); } // copy memory between host memory ranges template <typename Allocator1, typename Allocator2> // requires Allocator1 = Allocator // requires Allocator2 = Allocator void copy(const ConstArrayView<value_type, HostCoordinator<value_type, Allocator1>>& from, ArrayView<value_type, HostCoordinator<value_type, Allocator2>>& to) { assert(from.size()==to.size()); assert(!from.overlaps(to)); #ifdef VERBOSE using c1 = HostCoordinator<value_type, Allocator1>; std::cerr << util::type_printer<c1>::print() << "::" + util::blue("copy") << "(" << from.size() << " [" << from.size()*sizeof(value_type) << " bytes])" << " " << from.data() << util::yellow(" -> ") << to.data() << std::endl; #endif std::copy(from.begin(), from.end(), to.begin()); } /* void copy(const view_type &from, view_type &to) { assert(from.size()==to.size()); assert(!from.overlaps(to)); #ifdef VERBOSE std::cerr << util::type_printer<HostCoordinator>::print() << "::" + util::blue("copy") << "(" << from.size() << " [" << from.size()*sizeof(value_type) << " bytes])" << " " << from.data() << util::yellow(" -> ") << to.data() << std::endl; #endif std::copy(from.begin(), from.end(), to.begin()); } */ #ifdef WITH_CUDA // copy memory from device to host template <class Alloc> void copy(const ArrayView<value_type, DeviceCoordinator<value_type, Alloc>> &from, view_type &to) { assert(from.size()==to.size()); #ifdef VERBOSE std::cerr << util::type_printer<HostCoordinator>::print() << "::" + util::blue("copy") << "(device2host, " << from.size() << " [" << from.size()*sizeof(value_type) << " bytes])" << " " << from.data() << util::yellow(" -> ") << to.data() << std::endl; #endif auto status = cudaMemcpy( reinterpret_cast<void*>(to.begin()), reinterpret_cast<const void*>(from.begin()), from.size()*sizeof(value_type), cudaMemcpyDeviceToHost ); if(status != cudaSuccess) { std::cerr << util::red("error") << " bad CUDA memcopy, unable to copy " << sizeof(T)*from.size() << " bytes from host to device"; exit(-1); } } #endif // set all values in a range to val void set(view_type &rng, value_type val) { #ifdef VERBOSE std::cerr << util::type_printer<HostCoordinator>::print() << "::" + util::blue("fill") << "(" << rng.size() << " * " << val << ")" << " @ " << rng.data() << std::endl; #endif std::fill(rng.begin(), rng.end(), val); } reference make_reference(value_type* p) { return *p; } const_reference make_reference(value_type const* p) const { return *p; } static constexpr auto alignment() -> decltype(Allocator::alignment()) { return Allocator::alignment(); } static constexpr bool is_malloc_compatible() { return Allocator::is_malloc_compatible(); } }; } //namespace memory
[ "bcumming@cscs.ch" ]
bcumming@cscs.ch
8e3fc20b30a99072be2db445785eea55108b1189
f8df0470893e10f25f4362b84feecb9011293f43
/build/iOS/Preview/include/Fuse.Reactive.WhileCount.Range.h
3981677942e9c16a15aba91b4c281fd1a1ef1288
[]
no_license
cekrem/PlateNumber
0593a84a5ff56ebd9663382905dc39ae4e939b08
3a4e40f710bb0db109a36d65000dca50e79a22eb
refs/heads/master
2021-08-23T02:06:58.388256
2017-12-02T11:01:03
2017-12-02T11:01:03
112,779,024
0
0
null
null
null
null
UTF-8
C++
false
false
368
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Reactive.Bindings/1.4.0/WhileCount.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Int.h> namespace g{ namespace Fuse{ namespace Reactive{ // private enum WhileCount.Range :145 uEnumType* WhileCount__Range_typeof(); }}} // ::g::Fuse::Reactive
[ "cekrem@Christians-MacBook-Pro.local" ]
cekrem@Christians-MacBook-Pro.local
ffe8bdfe8a78628739dcb71ef8e8d06d2d0c0d18
bdbf58c973e87c2632680fc1bd79c6a750ceabc9
/src/rpcmining.cpp
6cc9bb822768e19709df5dd16d58c70792902006
[ "MIT" ]
permissive
Givecoin/givecoin
073caf46c0b3cf61e08be9957fb86cf6381bd18c
10b15858b9e05ba1b310841cb450f778e1574522
refs/heads/master
2020-05-17T20:15:56.830475
2014-05-20T12:00:58
2014-05-20T12:00:58
19,966,906
1
0
null
null
null
null
UTF-8
C++
false
false
21,099
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; // Return average network hashes per second based on the last 'lookup' blocks, // or from the last difficulty change if 'lookup' is nonpositive. // If 'height' is nonnegative, compute the estimate at the time when a given block was found. Value GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = pindexBest; if (height >= 0 && height < nBestHeight) pb = FindBlockByHeight(height); if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64 minTime = pb0->GetBlockTime(); int64 maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64 time = pb0->GetBlockTime(); minTime = std::min(time, minTime); maxTime = std::max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64 timeDiff = maxTime - minTime; return (boost::int64_t)(workDiff.getdouble() / timeDiff); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getnetworkhashps [blocks] [height]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); } // Key used by getwork/getblocktemplate miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining static CReserveKey* pMiningKey = NULL; void InitRPCMining() { if (!pwalletMain) return; // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); } void ShutdownRPCMining() { if (!pMiningKey) return; delete pMiningKey; pMiningKey = NULL; } Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); if (!pMiningKey) return false; return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); assert(pwalletMain != NULL); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Givecoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Givecoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Givecoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Givecoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); assert(pwalletMain != NULL); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Givecoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Givecoin is downloading blocks..."); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int index_in_template = i - 1; entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template])); entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template])); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); if (!fAccepted) return "rejected"; // TODO: report validation state return Value::null; }
[ "Dan@Daniels-MacBook-Pro.local" ]
Dan@Daniels-MacBook-Pro.local
e53337845b9534000a484eb43a2875f0f7b51d80
e090a7a4de62bef5cb2a4a272ea768abeee1ba9d
/Graduation/Client/Mouse.cpp
b33803fce233a8e0cf61bd5de029a153c7b8f6f5
[]
no_license
ParkJWoo/graduationProject
280e0a6b75a439e926073bdf21bbf874cc91a640
f29766b2c34622a2d73397d258306f4aa390638d
refs/heads/main
2023-01-08T11:36:03.018859
2020-11-19T13:01:10
2020-11-19T13:01:10
314,222,736
0
0
null
null
null
null
UHC
C++
false
false
2,270
cpp
#include "stdafx.h" #include "Mouse.h" CMouse::CMouse() { } CMouse::~CMouse() { Release(); } D3DXVECTOR3 CMouse::GetMouse() { POINT pt = {}; GetCursorPos(&pt); ScreenToClient(g_hWnd, &pt); return D3DXVECTOR3((float)pt.x, (float)pt.y, 0.f); } HRESULT CMouse::Initialize() { if (FAILED(CTextureMgr::GetInstance()->InsertTexture(L"../Texture/Mouse/Cursor%d.png", L"Mouse", TEX_MULTI, L"Cursor", 3))) { ERR_MSG(L"Mouse Cursor Image Insert Failed!!!"); return E_FAIL; } return S_OK; } int CMouse::Update() { return NO_EVENT; } void CMouse::LateUpdate() { /*if (CKeyMgr::GetInstance()->KeyPress(KEY_RIGHT)) { m_tInfo.vPos.x += 0.2f; } if (CKeyMgr::GetInstance()->KeyPress(KEY_LEFT)) { m_tInfo.vPos.x -= 0.2f; }*/ } void CMouse::Render() { POINT pt = {}; GetCursorPos(&pt); ScreenToClient(g_hWnd, &pt); RECT rcWnd = { }; ::GetClientRect(g_hWnd, &rcWnd); float fRatioX = WINCX / float(rcWnd.right - rcWnd.left); float fRatioY = WINCY / float(rcWnd.bottom - rcWnd.top); D3DXMATRIX matScale, matTrans, matWorld; D3DXMatrixScaling(&matScale, fRatioX, fRatioY, 1.f); D3DXMatrixTranslation(&matTrans, pt.x - CScrollMgr::GetScroll().x, pt.y - CScrollMgr::GetScroll().y, 0.f); matWorld = matScale * matTrans; // SetTransform: 행렬을 반영하는 함수. CDevice::GetInstance()->GetSprite()->SetTransform(&matWorld); const TEXINFO* pTexInfo = CTextureMgr::GetInstance()->GetTexture(L"Mouse", L"Cursor", 0); // 이미지의 중점 구하기. int iCenterX = pTexInfo->tImgInfo.Width / 2; int iCenterY = pTexInfo->tImgInfo.Height / 2; // 앞으로 모든 오브젝트의 렌더링은 이 사이에서 진행. CDevice::GetInstance()->GetSprite()->Draw(pTexInfo->pTexture, nullptr /*출력할 이미지 영역의 RECT*/, &D3DXVECTOR3((float)iCenterX, (float)iCenterY, 0.f) /*출력할 이미지의 중심 좌표 D3DXVECTOR3*/, nullptr /*출력할 위치 좌표 D3DXVECTOR3*/, D3DCOLOR_ARGB(255, 255, 255, 255)); } void CMouse::Release() { } HRESULT CMouse::CursorChange(MOUSE_STANCE eCursor) { m_eCursor = eCursor; switch (m_eCursor) { case CMouse::NORMAL: break; case CMouse::CLICK: break; case CMouse::ATTACK: break; case CMouse::MOUSE_END: break; default: break; } return E_NOTIMPL; }
[ "character453@naver.com" ]
character453@naver.com
8f6ecb20b6b66c2bd08571220385f9fc04dc8866
ecf61aab2bde91c0b94dcf5cb7b3842e71aac141
/src/app/CaisseEpargneTransactionReader.cpp
b2eda20d7eee0a8c0f500fc8d8f2bc128f8eb9b8
[ "MIT" ]
permissive
Wardleth/AccountManager
0c04260680e281d10703093328c74e142965a100
21a0e3a59f009c66cdccce5cbd6045f20b323952
refs/heads/master
2023-03-22T18:35:06.180948
2021-03-13T12:21:02
2021-03-13T12:21:02
112,400,967
0
0
null
null
null
null
ISO-8859-2
C++
false
false
5,473
cpp
#include "CaisseEpargneTransactionReader.h" #include "MalformedTransactionListException.h" #include "UnexpectedCurrencyException.h" #include "Utils.h" #include <iomanip> #include <list> #include <regex> #include <sstream> static constexpr int STATEMENT_COLUMNS_COUNT = 6; static constexpr int BALANCE_COLUMNS_COUNT = 5; TransactionData CaisseEpargneTransactionReader::readTransaction(std::istream& is) { std::string line; std::getline(is, line); auto statementData = StringUtils::split(line, ';'); if (statementData.size() < STATEMENT_COLUMNS_COUNT) { throw MalformedTransactionListException(); } std::regex date_time_regex("([0-9]{2})\\s*/\\s*([0-9]{2})\\s*/\\s*([0-9]{2})"); std::smatch result; if (!std::regex_search(statementData[0], result, date_time_regex)) { throw MalformedTransactionListException(); } std::istringstream iss(statementData[0]); std::tm date = {}; iss >> std::get_time(&date, "%d/%m/%y"); date.tm_mday = std::stoi(result[1]); date.tm_mon = std::stoi(result[2]) - 1; // tm_mon is 0-based date.tm_year = std::stoi(result[3]) + 100; // result[3] is year since 2000, but tm_year expect year since 1900 if (!statementData[3].empty() && !statementData[4].empty()) { throw MalformedTransactionListException(); } double amount = 0.0; if (!statementData[3].empty()) { amount = extractDouble(statementData[3]); if (amount > 0.0) { throw MalformedTransactionListException(); } } else if (!statementData[4].empty()) { amount = extractDouble(statementData[4]); if (amount < 0.0) { throw MalformedTransactionListException(); } } else { throw MalformedTransactionListException(); } return TransactionData{ date, amount, StringUtils::trim(statementData[2]), StringUtils::trim(statementData[5]) }; } TransactionList CaisseEpargneTransactionReader::readTransactionList(std::istream& is) { auto metadata = readMetadata(is); auto bankCodeData = metadata.find("Code de la banque"); if (bankCodeData == metadata.end() || bankCodeData->second.size() != 5) { throw MalformedTransactionListException(); } auto agencyCodeData = metadata.find("Code de l'agence"); if (agencyCodeData == metadata.end() || agencyCodeData->second.size() != 5) { throw MalformedTransactionListException(); } auto accountNumberData = metadata.find("Numéro de compte"); if (accountNumberData == metadata.end() || accountNumberData->second.size() != 11) { throw MalformedTransactionListException(); } auto currencyData = metadata.find("Devise"); if (currencyData == metadata.end()) { throw MalformedTransactionListException(); } if (auto currency = expectedCurrency_.lock()) { if (currencyData->second != currency->code()) { throw UnexpectedCurrencyException(currencyData->second); } } std::string tmp; while (std::getline(is, tmp) && !StringUtils::startsWith("Solde en fin de période", tmp)) {} double endBalance = extractBalance(tmp); std::getline(is, tmp); // Skip headers std::list<TransactionData> statements; while (std::getline(is, tmp) && !StringUtils::startsWith("Solde en début de période", tmp)) { std::istringstream iis(tmp); statements.push_front(readTransaction(iis)); } double startBalance = extractBalance(tmp); ensureValidity(endBalance - startBalance, statements); return { bankCodeData->second, agencyCodeData->second, accountNumberData->second, startBalance, endBalance, std::vector<TransactionData>(statements.begin(), statements.end()) }; } std::map<std::string, std::string> CaisseEpargneTransactionReader::readMetadata(std::istream& is) { std::map<std::string, std::string> metadata; std::string firstLine, secondLine; std::getline(is, firstLine); std::getline(is, secondLine); for (auto& token : StringUtils::split(firstLine + secondLine, ';')) { auto data = StringUtils::split(token, ':'); if (data.size() < 2) { throw MalformedTransactionListException(); } metadata.insert(std::make_pair(StringUtils::trim(data[0]), StringUtils::trim(data[1]))); } return metadata; } double CaisseEpargneTransactionReader::extractDouble(const std::string& valueStr) const { std::istringstream iss(valueStr); iss.imbue(std::locale("fr_FR.UTF8")); double value; iss >> value; if (iss.fail()) { throw MalformedTransactionListException(); } return value; } double CaisseEpargneTransactionReader::extractBalance(const std::string& line) const { auto endBalanceData = StringUtils::split(line, ';'); if (endBalanceData.size() < BALANCE_COLUMNS_COUNT) { throw MalformedTransactionListException(); } return extractDouble(endBalanceData.back()); } void CaisseEpargneTransactionReader::ensureValidity(double balanceDelta, const std::list<TransactionData>& statements) const { double sum = 0.0; for (auto& s : statements) { sum += s.amount; } if (sum != balanceDelta) { throw MalformedTransactionListException(); } } CaisseEpargneTransactionReader::CaisseEpargneTransactionReader(std::weak_ptr<Currency> expectedCurrency) : expectedCurrency_(expectedCurrency) {}
[ "hebus_le_barbare@hotmail.com" ]
hebus_le_barbare@hotmail.com
4325a19454d009b528136c9667c98d584201ffb2
a55e43b9c9563965b745815564c17b6c5512c690
/tests/test-decl-string1.cp
d8efa1decdf5458da4c7e048817887a240f8191e
[]
no_license
cammiller1/plt-parser
4e543f21d34d77fa45ba4ff5e01fe16674ac302e
a5a712bc9cf432941cb9d4b24121af01f3683ca5
refs/heads/main
2023-04-05T20:04:10.555635
2021-04-27T04:01:48
2021-04-27T04:01:48
340,517,579
0
0
null
2021-04-27T00:35:48
2021-02-19T23:50:42
OCaml
UTF-8
C++
false
false
9
cp
string x;
[ "george.j.dinicola@gmail.com" ]
george.j.dinicola@gmail.com
e0800e8b3b4738b763fdb88c8d3126a9098f4d5a
431a1a905847dde998e9fe3ed2eeb184b1482d83
/src/Demo_combineClassAndProperty_temp.cpp
870fae677c83c83175b952fe2644837e86f2829c
[]
no_license
bicelove/txtFileParse
359aefc698dfc382c2433f940451f080a1dfc030
24a2665d0b1acc1301afc4ca6a53e98fa9e88baf
refs/heads/master
2020-04-02T04:32:47.296627
2017-06-27T09:59:46
2017-06-27T09:59:46
95,542,483
0
0
null
null
null
null
UTF-8
C++
false
false
7,917
cpp
#include <stdio.h> // for snprintf #include <string> #include <vector> #include <iostream> #include <sstream> // stringstream #include <fstream> // NOLINT (readability /streams) #include <utility> // Create key-value pair (there could be not used) #include <stdlib.h> #include <sys/stat.h> #include <time.h> #include <opencv/cv.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; using namespace cv; struct imgClassQueryList{ vector<string> srcImgIDList; vector<string> imgIDList; vector<int> label; }; struct imgClassQueryList classTagDataList; struct imgMultiQueryList{ vector<string> imgIDList; vector<vector<int>> labels; }; struct imgMultiQueryList multiTagDataList; // int getStringID( const string imageString, string &srcImgID, string &imageID) { int sour_pos, postfix_pos; string sour_name; // sour_pos = imageString.find_last_of('/'); sour_name = imageString.substr(sour_pos + 1); srcImgID = sour_name; //cout<<"nameTemp1: "<<nameTemp1<<endl; int strLen = srcImgID.length(); postfix_pos = srcImgID.find_first_of('_'); if(postfix_pos < 0 || postfix_pos >= strLen - 8){ imageID = srcImgID; }else{ imageID = srcImgID.substr(postfix_pos + 1, strLen - postfix_pos); } //cout<<"imageID: "<<imageID<<endl; return 0; } // int getClassTagDataList( const string szQueryList) { cout<<"------------------getAllDataQueryList------------------"<<endl; FILE* fpQueryList = fopen(szQueryList.c_str(), "r"); if(NULL == fpQueryList) { cout<<"cannot open "<<szQueryList<<endl; return -1; } int i; int nRet = 0; char buff[2000]; int numLines; string srcImgID, imageID; int label; bool ifImgID, ifImgLabel, ifSingleTagImg, ifExistImg; classTagDataList.srcImgIDList.clear(); classTagDataList.imgIDList.clear(); classTagDataList.label.clear(); while(fgets(buff, 2000 ,fpQueryList) != NULL) { char *pstr = strtok(buff, "\n"); //cout<<pstr<<endl; char *qstr = NULL; if(pstr != NULL){ qstr = strtok(pstr, "\t "); }else{ continue; } numLines = 0; ifImgID = false; ifImgLabel = false; ifSingleTagImg = true; while(qstr != NULL) { numLines++; if(numLines == 1){ //cout<<qstr<<endl; /* nRet = getStringID(qstr, srcImgID, imageID); if(nRet != 0){ continue; } */ srcImgID = qstr; imageID = qstr; //cout<<"srcImgID: "<<srcImgID<<endl; ifImgID = true; }else if(numLines == 2){ //cout<<qstr<<endl; label = atoi(qstr); ifImgLabel = true; }else if(numLines > 2){ ifSingleTagImg = false; break; } qstr = strtok(NULL, " "); } if(ifSingleTagImg && ifImgID && ifImgLabel) { ifExistImg = false; for(i = 0; i < classTagDataList.imgIDList.size(); i++){ if(imageID == classTagDataList.imgIDList[i]){ ifExistImg = true; //cout<<"repeat: "<<srcImgID<<" & "<<classTagDataList.srcImgIDList[i]<<endl; break; } } if(ifExistImg)continue; classTagDataList.srcImgIDList.push_back(srcImgID); classTagDataList.imgIDList.push_back(imageID); classTagDataList.label.push_back(label); } } fclose(fpQueryList); return 0; } // int tagCombine( const string dataList) { FILE* fpDataList = fopen(dataList.c_str(), "r"); if(NULL == fpDataList) { cout<<"cannot open "<<dataList<<endl; return -1; } int i; int nRet = 0; char buff[2000]; string imgPath; string srcImgID; string imageID; int label; int index; int numIMg; int numLines; bool ifImgID, ifImgLabel, ifHaveWrite; vector<pair<int, bool>> ifwrite(classTagDataList.srcImgIDList.size(), make_pair(-1, false)); vector<int> labels; multiTagDataList.imgIDList.clear(); multiTagDataList.labels.resize(classTagDataList.label.size()); numIMg = 0; ifwrite.clear(); while(fgets(buff, 2000 ,fpDataList) != NULL) { char *pstr = strtok(buff, "\n"); //cout<<pstr<<endl; char *qstr = NULL; if(pstr != NULL){ qstr = strtok(pstr, ","); }else{ continue; } numLines = 0; ifImgID = false; ifImgLabel = false; labels.clear(); while(qstr != NULL) { numLines++; if(numLines == 1){ //cout<<qstr<<endl; imgPath = qstr; nRet = getStringID(qstr, srcImgID, imageID); if(nRet != 0){ continue; } //cout<<"imageID: "<<imageID<<endl; ifImgID = true; }else if(numLines >= 2){ //cout<<qstr<<endl; label = atoi(qstr); labels.push_back(label); ifImgLabel = true; } qstr = strtok(NULL, ","); } if(ifImgID && ifImgLabel) { //cout<<"imageID: "<<imageID<<endl; vector<string>::iterator iElement = find(classTagDataList.srcImgIDList.begin(), classTagDataList.srcImgIDList.end(), imgPath); index = distance(classTagDataList.srcImgIDList.begin(), iElement); if(index > -1 && index < classTagDataList.srcImgIDList.size()){ if(!ifwrite[index].second){ multiTagDataList.imgIDList.push_back(classTagDataList.srcImgIDList[index]); numIMg++; multiTagDataList.labels[numIMg - 1].push_back(classTagDataList.label[index]); multiTagDataList.labels[numIMg - 1].push_back(label); ifwrite[index].first = numIMg - 1; ifwrite[index].second = true; }else{ ifHaveWrite = false; for(i = 0; i < multiTagDataList.labels[ifwrite[index].first].size(); i++){ if(multiTagDataList.labels[ifwrite[index].first][i] == label){ ifHaveWrite = true; break; } } if(!ifHaveWrite)multiTagDataList.labels[ifwrite[index].first].push_back(label); } } } if(numIMg % 100 == 0){ cout<<"the "<<numIMg<<"th image deal!"<<endl; } } cout<<"numIMg = "<<numIMg<<endl; fclose(fpDataList); return 0; } // int outputMatchList( const string outputList) { if(multiTagDataList.imgIDList.size() < 1 || multiTagDataList.labels.size() < 1){ cout<<"image information error!"<<endl; return -1; } FILE* fpOutputList = fopen(outputList.c_str(), "w"); if(NULL == fpOutputList) { cout<<"cannot open "<<outputList<<endl; return -1; } int i, j; int nRet = 0; int numIMg; numIMg = 0; for(i = 0; i < multiTagDataList.imgIDList.size(); i++) { numIMg++; fprintf(fpOutputList, "%s,", multiTagDataList.imgIDList[i].c_str()); for(j = 0; j < multiTagDataList.labels[i].size(); j++){ fprintf(fpOutputList, "%d,", multiTagDataList.labels[i][j]); } fprintf(fpOutputList, "\n"); } cout<<"numIMg = "<<numIMg<<endl; fclose(fpOutputList); return 0; } // int main(int argc, char** argv) { const int num_required_args = 3; if( argc < num_required_args ){ cout<< "This program extracts features of an image and predict its label and score.\n" "Usage: Demo_mainboby szQueryList outputList\n"; return 1; } /***********************************Init**********************************/ string szQueryList = argv[1]; string dataList = argv[2]; string outputList = argv[3]; int nRet = 0; /**************************** getAllDataQueryList *************************/ nRet = getClassTagDataList(szQueryList); if(nRet != 0){ cout<<"fail to getQueryList!"<<endl; return -1; } cout<<"classTagDataList.size = "<<classTagDataList.srcImgIDList.size()<<endl; nRet = tagCombine(dataList); if(nRet != 0){ cout<<"fail to combine tags!"<<endl; return -1; } nRet = outputMatchList(outputList); if(nRet != 0){ cout<<"fail to output match list!"<<endl; return -1; } cout<<"deal end!"<<endl; return 0; }
[ "tutu@in66.com" ]
tutu@in66.com
30dfc4cf3921fd7965c506994aff777186a80faa
b85d28cdd5ae653e6122b913e06fe0ed41d73b6e
/xdoj/1081.cpp
96a59eeba50a2f4febf60986e5c237c2654bec6b
[]
no_license
a62625536/ACM
46b19d8b43dad857629d5420cafb1d82bd8c3fa8
9dcc28a9d96e27f6aa50aeeb4e03324b240ec142
refs/heads/master
2021-09-18T15:55:02.765547
2018-07-17T01:46:30
2018-07-17T01:46:30
120,172,970
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> using namespace std; int main() { long long a1,a2,b1,b2,c1,c2,d1,d2; while(~scanf("%lld%lld%lld%lld%lld%lld%lld%lld",&a1,&a2,&b1,&b2,&c1,&c2,&d1,&d2)) { long long x1 = a1*d1,x2 = a2*d2,y1 = b1*c1,y2 = b2*c2; if(x1 > y2 || x2 < y1) printf("NO\n"); else printf("YES\n"); } return 0; }
[ "540911979@qq.com" ]
540911979@qq.com
87f5acfde73f1331ef1cf836b1dbe92214bfaf67
3d1d25af664fbcebbb209416b44964af623c1322
/src/vlCore/plugins/ioDAT.cpp
502fe9d5294e2e8a7e229427aea64f956ae4be49
[ "BSD-2-Clause" ]
permissive
torkos/visualizationlibrary
e83400c69cb32ad7b9e19a579d2db606f03de78f
27e359aa348a8f182f90ecd68058d1b1ef924999
refs/heads/master
2021-01-20T19:05:00.133429
2016-02-01T12:34:43
2016-02-01T12:34:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,400
cpp
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include "ioDAT.hpp" #include <vlCore/LoadWriterManager.hpp> #include <vlCore/VisualizationLibrary.hpp> #include <vlCore/VisualizationLibrary.hpp> #include <vlCore/FileSystem.hpp> #include <vlCore/VirtualFile.hpp> #include <vlCore/Image.hpp> #include <vlCore/TextStream.hpp> #include <stdio.h> using namespace vl; #include <vlCore/ImageTools.hpp> //----------------------------------------------------------------------------- ref<Image> vl::loadDAT( const String& path ) { ref<VirtualFile> file = defFileSystem()->locateFile(path); if ( !file ) { Log::error( Say("File '%s' not found.\n") << path ); return NULL; } return loadDAT(file.get()); } //----------------------------------------------------------------------------- ref<Image> vl::loadDAT(VirtualFile* file) { if (!file->open(OM_ReadOnly)) { Log::error( Say("loadDAT: could not find DAT file '%s'.\n") << file->path() ); return NULL; } #define BUFFER_SIZE 1024 ref<TextStream> stream = new TextStream(file); std::string line; char buffer[BUFFER_SIZE ]; char filename[BUFFER_SIZE ]; char typ[BUFFER_SIZE ]; char fmt[BUFFER_SIZE ]; float a=0,b=0,c=0; int width=0, height=0, depth=0, bytealign=1; EImageFormat format; EImageType type; // safe way, get a line first then sscanf the string stream->readLine(line); if ( sscanf(line.c_str(), "%s %s", buffer, filename) != 2 ) return NULL; // make sure it is zero terminated filename[BUFFER_SIZE-1] = 0; stream->readLine(line); if ( sscanf(line.c_str(), "%s %d %d %d", buffer, &width, &height, &depth) != 4 ) return NULL; stream->readLine(line); if ( sscanf(line.c_str(), "%s %f %f %f", buffer, &a,&b,&c) != 4 ) return NULL; stream->readLine(line); if ( sscanf(line.c_str(), "%s %s", buffer, typ) != 2 ) return NULL; // make sure it is zero terminated typ[BUFFER_SIZE-1] = 0; stream->readLine(line); if ( sscanf(line.c_str(), "%s %s", buffer, fmt) != 2 ) return NULL; // make sure it is zero terminated fmt[BUFFER_SIZE-1] = 0; file->close(); // strip quotes int len = strlen(filename); if (len > 2) { if (filename[0] == '\'' || filename[0] == '"') memmove(filename, filename + 1, len); len = (int)strlen(filename); if (filename[len-1] == '\'' || filename[len-1] == '"') filename[len-1] = 0; } // extract path String raw_file = file->path().extractPath() + filename; if (String(typ) == "UCHAR") type = IT_UNSIGNED_BYTE; else { Log::error( Say("loadDAT('%s'): type '%s' not supported.\n") << file->path() << typ ); return NULL; } if (String(fmt) == "LUMINANCE") format = IF_LUMINANCE; else if (String(fmt) == "LUMINANCE_ALPHA") format = IF_LUMINANCE_ALPHA; else if (String(fmt) == "RGB") format = IF_RGB; else if (String(fmt) == "RGBA") format = IF_RGBA; else { Log::error( Say("loadDAT('%s'): format '%s' not supported.\n") << file->path() << fmt ); return NULL; } ref<VirtualFile> rawf = defFileSystem()->locateFile(raw_file); if (rawf) { return loadRAW( rawf.get(), -1, width, height, depth, bytealign, format, type ); } else { Log::error( Say("loadDAT('%s'): could not find RAW file '%s'.\n") << file->path() << raw_file ); return NULL; } } //----------------------------------------------------------------------------- bool vl::isDAT(VirtualFile* file) { #define BUFFER_SIZE 1024 if (!file->open(OM_ReadOnly)) return false; ref<TextStream> stream = new TextStream(file); std::string line; char buffer[BUFFER_SIZE]; char filename[BUFFER_SIZE]; char typ[BUFFER_SIZE]; char fmt[BUFFER_SIZE]; float a=0,b=0,c=0; int width=0, height=0, depth=0; EImageFormat format; EImageType type; // safe way, get a line first then sscanf the string stream->readLine(line); if ( sscanf(line.c_str(), "%s %s", buffer, filename) != 2 ) return false; // make sure it is zero terminated filename[BUFFER_SIZE-1] = 0; stream->readLine(line); if ( sscanf(line.c_str(), "%s %d %d %d", buffer, &width, &height, &depth) != 4 ) return false; stream->readLine(line); if ( sscanf(line.c_str(), "%s %f %f %f", buffer, &a,&b,&c) != 4 ) return false; stream->readLine(line); if ( sscanf(line.c_str(), "%s %s", buffer, typ) != 2 ) return false; // make sure it is zero terminated typ[BUFFER_SIZE-1] = 0; stream->readLine(line); if ( sscanf(line.c_str(), "%s %s", buffer, fmt) != 2 ) return false; // make sure it is zero terminated fmt[BUFFER_SIZE-1] = 0; file->close(); // strip quotes int len = strlen(filename); if (len > 2) { if (filename[0] == '\'' || filename[0] == '"') memmove(filename,filename + 1, len); len = (int)strlen(filename); if (filename[len-1] == '\'' || filename[len-1] == '"') filename[len-1] = 0; } // extract path String raw_file = file->path().extractPath() + filename; // check type if (String(typ) == "UCHAR") type = IT_UNSIGNED_BYTE; else return false; if (String(fmt) == "LUMINANCE") format = IF_LUMINANCE; else if (String(fmt) == "LUMINANCE_ALPHA") format = IF_LUMINANCE_ALPHA; else if (String(fmt) == "RGB") format = IF_RGB; else if (String(fmt) == "RGBA") format = IF_RGBA; else return false; if (defFileSystem()->locateFile(raw_file)) return true; else return false; } //-----------------------------------------------------------------------------
[ "hello@michelebosi.com" ]
hello@michelebosi.com
2109a19b22cd549e793f4205754db5da06c6b5ac
12168f3e2f6a45ff95a54f4a6d6ee0229161e4d1
/sparky-core/src/graphics/buffers/buffer.h
15058be887f8ca8a447857ae58a3ac1404e602a2
[]
no_license
cymes1/mySparkyEngine
ccd3d4fb8c1d23811d8138e54b5891629b3694fe
f8357488d68db6f3a2245b4fa78dc6138c149589
refs/heads/master
2021-11-23T10:10:29.169471
2021-11-01T19:48:10
2021-11-01T19:48:10
119,690,504
0
0
null
null
null
null
UTF-8
C++
false
false
374
h
#ifndef BUFFER_H #define BUFFER_H #include <GL/glew.h> #include <iostream> namespace Sparky { namespace Graphics { class Buffer { private: GLuint m_bufferID; GLuint m_componentCount; public: Buffer(GLfloat* data, GLsizei count, GLuint componenetCount); ~Buffer(); void bind() const; void unbind() const; GLuint componentCount() const; }; }} #endif
[ "mateusz.winiarczyk@outlook.com" ]
mateusz.winiarczyk@outlook.com
2feab9515fd80aa23c08ee6147cf441ff83b3d5a
68e950337e96123bc25506c0284920a03292ab7c
/extensions/model/ndn-interpacket-strain-estimator.hpp
b99caaa3288089098da432af95c24d90ab245e4c
[]
no_license
goodluckz/ndn-mrbart
7220b2fa480e16496985c613c83a36c959370223
376af267ee0533ffbbb2daff8e2b75f82960e92e
refs/heads/master
2022-11-08T15:11:33.612580
2018-01-21T08:46:40
2018-01-21T08:46:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,630
hpp
#ifndef NDN_INTERPACKET_STRAIN_ESTIMATOR_H #define NDN_INTERPACKET_STRAIN_ESTIMATOR_H // #include "ns3/ndnSIM/utils/ndn-rtt-estimator.hpp" #include <deque> #include "ns3/sequence-number.h" #include "ns3/nstime.h" #include "ns3/object.h" #include <memory> #include "parameter.hpp" #include <map> namespace ns3 { namespace ndn { class IpsHistory : public Object{ public: IpsHistory(SequenceNumber32 s, uint32_t c, Time t); IpsHistory(const IpsHistory& h); // Copy constructor public: SequenceNumber32 seq; // First sequence number in packet sent uint32_t count; // Number of bytes sent Time time; // Time this one was sent bool retx; // True if this has been retransmitted }; typedef std::deque<IpsHistory> IpsHistory_t; class InterpacketStrainEstimator : public Object { public: static TypeId GetTypeId(void); InterpacketStrainEstimator(); // InterpacketStrainEstimator(const InterpacketStrainEstimator&); virtual TypeId GetInstanceTypeId(void) const; void SentSeq(SequenceNumber32 seq, uint32_t size); double AckSeq(SequenceNumber32 ackSeq, uint32_t size); double GetIpsEstimation(); double GetU(); // Ptr<RttEstimator> // Copy() const; void Reset(); // void // Gain(double g); private: Time m_variance; // Current variance // IpsHistory_t m_history; std::map<SequenceNumber32, Time> m_history; IpsHistory_t m_arrival; Time m_window; // Ptr<IpsHistory> m_previousAckSeq; double m_lastu; }; } // namespace ndn } // namespace ns3 #endif
[ "zl.iafag@gmail.com" ]
zl.iafag@gmail.com
d6a377575330140a97db1eac0ee39f5ad9282e9e
d8d765351bea8d0cd066d9dcd37875dd6527985f
/DA4_Four_In_a_Row_Eclipse/DA4_Four_In_a_Row/ComputerPlayer.h
447759b1f4bca745f923b00b23feb46557a0b219
[]
no_license
Caresilabs/MAH_CPP_OODA
5626f13231a2368ea8dc741d7a19dae3d60a03a3
ed8634c60fc0ce2319a31d61284126bc6f62bfb8
refs/heads/master
2021-01-01T05:36:25.958165
2016-03-15T19:12:01
2016-03-15T19:12:01
42,531,432
0
0
null
null
null
null
UTF-8
C++
false
false
786
h
#pragma once #include "Player.h" #include "Board.h" /* Simulates a real player using artificial intelligence. */ class ComputerPlayer : public Player { public: ComputerPlayer(PlayerManager* manager, std::string name, const Board* board); /* Disable copy constructor and assignment operator*/ ComputerPlayer(const ComputerPlayer& rhs) = delete; ComputerPlayer& operator=(const ComputerPlayer& rhs) = delete; /* Get the opposite player's move. @param position the x position that is recieved. */ virtual void notify( int position ) override; private: /* The board to lookup * @directed true */ const Board* board; /* Calculate the best move for the AI @return position of the best move. */ int calculateBestMove(); /* Run the AI simulation. */ void doAI(); };
[ "caresilabs@gmail.com" ]
caresilabs@gmail.com
76919f65f3d741eaf6bf5e41d296ad3391d6630c
258e3b68fcd88f30b28142bf8b9d4d7f06114243
/src/parser/events/IncludeEvent.cpp
055d9d7cf089333c7117f48810c3b934ab0706d3
[]
no_license
Kracav4ik/cxx_creed
e3c46925d65ee3ba1085aff90759029c139e227e
a771d52d0c3e9196eb5baa697c82a93e282d1416
refs/heads/master
2020-09-23T06:51:39.922549
2019-12-15T10:03:13
2019-12-15T10:04:41
225,431,644
0
0
null
null
null
null
UTF-8
C++
false
false
227
cpp
#include "IncludeEvent.h" #include "parser/EventVisitor.h" IncludeEvent::IncludeEvent(std::string include) : include(std::move(include)) {} void IncludeEvent::visit(EventVisitor& visitor) { visitor.visitInclude(*this); }
[ "dikama2013@yandex.ru" ]
dikama2013@yandex.ru
d4b42062da2b3619aa43bbcb9e5803fdf6f06cd3
d457c8df6e4e1a104fcf9e44d655c3e563b7d131
/src/main.cpp
c8ed28c69006ac3f32f2bac4c9225edf66a21a16
[]
no_license
xd-hbj/webserver
20c7da49c2c6eb12c7cf51a10af26b6ad28ca808
51d08cab1bc8ef1179be56d700f365fb56d18fe4
refs/heads/master
2023-06-01T16:13:55.497280
2021-06-22T10:53:32
2021-06-22T10:53:32
342,847,293
1
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
#include<sys/epoll.h> #include<assert.h> #include"webserver.h" #include"http_conn.h" int main(int argc,char** argv){ if(argc>1){ cout<<" wrong parameters "<<endl; exit(1); } Webserver webserver; webserver.run(); return 0; }
[ "945600831@qq.com" ]
945600831@qq.com
b4f4417fbffd198b4e47b37201f37031542f0e75
5bc6d0d5dc493e018ce1c5f2660b74ae15bd8399
/valid_palindrome.cpp
dfd4becf17c358dab53587fb0f21ee7bead6494a
[]
no_license
MagicSen/leetcode
2681f42626907c66fdb5f25047d510106b652513
2de9ffda3f73bee8af916bbf2e78e7fcaf892f6b
refs/heads/master
2021-01-02T09:09:36.797490
2015-09-25T01:50:59
2015-09-25T01:50:59
25,122,552
0
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; class Solution { public: void tolower(string &s){ for(int i = 0; i < s.size(); ++i) { if(s[i] >= 'A' && s[i] <= 'Z'){ s[i] = s[i] - 'A' + 'a'; } } } bool isvalid(char ch) { if((ch < 'a' || ch > 'z') && (ch < '0' || ch > '9')) return false; else return true; } bool isPalindrome(string s) { if(s.size() == 0) return true; tolower(s); int i = 0; int j = s.size()-1; while(i <= j){ if(!isvalid(s[i])){ ++i; continue; } if(!isvalid(s[j])){ --j; continue; } if(s[i] == s[j]){ ++i; --j; }else{ return false; } } return true; } }; int main() { // string s = "A B C C b a "; string s = "1a2"; Solution sol; cout << sol.isPalindrome(s) << endl; return 0; }
[ "magicys@qq.com" ]
magicys@qq.com
b058aa6ca0def8f37d9181dead3e62334c3615d2
f6a9522a67f7c12b553667efbf9bee8a4e8b0470
/Udemy_C++/5_impl_method2/Account.cpp
5477ed7260ba1da95400ee2785d4030febcfe8ba
[]
no_license
krishnausjs/cpp_programs
956fa9d16743e1c4426abd16c39d8cead0602b5d
b3807fff3d7c39a8058814c0996374d343d7b1c8
refs/heads/master
2021-10-19T18:10:42.412519
2019-02-22T23:49:26
2019-02-22T23:49:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
360
cpp
#include "Account.h" void Account::set_name(std::string n) { name = n; } std::string Account::get_name() { return name; } bool Account::deposit(double amount) { //if verify amount balance += amount; return true; } bool Account::withdraw(double amount) { if(balance-amount >= 0) { balance-=amount; return true; } else { return false; } }
[ "murali.marimekala@gmail.com" ]
murali.marimekala@gmail.com
7ad0123a22450f7dea39ca7bcd73eee53e66f87c
efc3acac48c5a44fe347290c2b72b7fc552c572e
/include/dcps/C++/isocpp/dds/core/cond/StatusCondition.hpp
c93d6538613636a6fdf0ac8bdddbe30ed8b7b1cb
[]
no_license
NaiveSolution/PubSub
3635316fcaadd62b67dbdb8861cc21042e822204
1fa6c0a3cd27a0b1a2bbf1b7f878fdd96ef5daf7
refs/heads/main
2023-01-23T12:43:00.865389
2020-12-03T05:19:00
2020-12-03T05:19:00
318,079,990
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
hpp
/* * Vortex OpenSplice * * This software and documentation are Copyright 2006 to ADLINK * Technology Limited, its affiliated companies and licensors. 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 OSPL_DDS_CORE_COND_STATUSCONDITION_HPP_ #define OSPL_DDS_CORE_COND_STATUSCONDITION_HPP_ /** * @file */ /* * OMG PSM class declaration */ #include <spec/dds/core/cond/StatusCondition.hpp> // Implementation // End of implementation #endif /* OSPL_DDS_CORE_COND_STATUSCONDITION_HPP_ */
[ "tariq@localhost.localdomain" ]
tariq@localhost.localdomain
1a597863f74aa33411a21e97db5230875db23c5d
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/framework/XMLAttDef.cpp
533a48828a27e1f929042899622394b44ba848ac
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
6,781
cpp
/* * Copyright 1999-2004 The Apache Software Foundation. * * 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. */ /** * $Id: XMLAttDef.cpp,v 1.9 2004/09/08 13:55:58 peiyongz Exp $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/framework/XMLAttDef.hpp> #include <xercesc/util/ArrayIndexOutOfBoundsException.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/OutOfMemoryException.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local const data // // gAttTypeStrings // A list of strings which are used to map attribute type numbers to // attribute type names. // // gDefAttTypesStrings // A list of strings which are used to map default attribute type // numbers to default attribute type names. // --------------------------------------------------------------------------- const XMLCh* const gAttTypeStrings[XMLAttDef::AttTypes_Count] = { XMLUni::fgCDATAString , XMLUni::fgIDString , XMLUni::fgIDRefString , XMLUni::fgIDRefsString , XMLUni::fgEntityString , XMLUni::fgEntitiesString , XMLUni::fgNmTokenString , XMLUni::fgNmTokensString , XMLUni::fgNotationString , XMLUni::fgEnumerationString , XMLUni::fgCDATAString , XMLUni::fgCDATAString , XMLUni::fgCDATAString , XMLUni::fgCDATAString }; const XMLCh* const gDefAttTypeStrings[XMLAttDef::DefAttTypes_Count] = { XMLUni::fgDefaultString , XMLUni::fgFixedString , XMLUni::fgRequiredString , XMLUni::fgImpliedString , XMLUni::fgImpliedString , XMLUni::fgImpliedString , XMLUni::fgImpliedString , XMLUni::fgImpliedString , XMLUni::fgImpliedString }; // --------------------------------------------------------------------------- // XMLAttDef: Public, static data members // --------------------------------------------------------------------------- const unsigned int XMLAttDef::fgInvalidAttrId = 0xFFFFFFFE; // --------------------------------------------------------------------------- // XMLAttDef: Public, static methods // --------------------------------------------------------------------------- const XMLCh* XMLAttDef::getAttTypeString(const XMLAttDef::AttTypes attrType , MemoryManager* const manager) { // Check for an invalid attribute type and return a null if ((attrType < AttTypes_Min) || (attrType > AttTypes_Max)) ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::AttDef_BadAttType, manager); return gAttTypeStrings[attrType]; } const XMLCh* XMLAttDef::getDefAttTypeString(const XMLAttDef::DefAttTypes attrType , MemoryManager* const manager) { // Check for an invalid attribute type and return a null if ((attrType < DefAttTypes_Min) || (attrType > DefAttTypes_Max)) ThrowXMLwithMemMgr(ArrayIndexOutOfBoundsException, XMLExcepts::AttDef_BadDefAttType, manager); return gDefAttTypeStrings[attrType]; } // --------------------------------------------------------------------------- // XMLAttDef: Destructor // --------------------------------------------------------------------------- XMLAttDef::~XMLAttDef() { cleanUp(); } // --------------------------------------------------------------------------- // XMLAttDef: Hidden constructors // --------------------------------------------------------------------------- XMLAttDef::XMLAttDef( const XMLAttDef::AttTypes type , const XMLAttDef::DefAttTypes defType , MemoryManager* const manager) : fDefaultType(defType) , fType(type) , fCreateReason(XMLAttDef::NoReason) , fProvided(false) , fExternalAttribute(false) , fId(XMLAttDef::fgInvalidAttrId) , fValue(0) , fEnumeration(0) , fMemoryManager(manager) { } XMLAttDef::XMLAttDef( const XMLCh* const attrValue , const XMLAttDef::AttTypes type , const XMLAttDef::DefAttTypes defType , const XMLCh* const enumValues , MemoryManager* const manager) : fDefaultType(defType) , fType(type) , fCreateReason(XMLAttDef::NoReason) , fProvided(false) , fExternalAttribute(false) , fId(XMLAttDef::fgInvalidAttrId) , fValue(0) , fEnumeration(0) , fMemoryManager(manager) { try { fValue = XMLString::replicate(attrValue, fMemoryManager); fEnumeration = XMLString::replicate(enumValues, fMemoryManager); } catch(const OutOfMemoryException&) { throw; } catch(...) { cleanUp(); } } // --------------------------------------------------------------------------- // XMLAttDef: Private helper methods // --------------------------------------------------------------------------- void XMLAttDef::cleanUp() { if (fEnumeration) fMemoryManager->deallocate(fEnumeration); if (fValue) fMemoryManager->deallocate(fValue); } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_NOCREATE(XMLAttDef) void XMLAttDef::serialize(XSerializeEngine& serEng) { if (serEng.isStoring()) { serEng<<(int)fDefaultType; serEng<<(int)fType; serEng<<(int)fCreateReason; serEng<<fProvided; serEng<<fExternalAttribute; serEng<<fId; serEng.writeString(fValue); serEng.writeString(fEnumeration); } else { int i; serEng>>i; fDefaultType = (DefAttTypes) i; serEng>>i; fType = (AttTypes)i; serEng>>i; fCreateReason = (CreateReasons)i; serEng>>fProvided; serEng>>fExternalAttribute; serEng>>fId; serEng.readString(fValue); serEng.readString(fEnumeration); } } XERCES_CPP_NAMESPACE_END
[ "aburke@bitflood.org" ]
aburke@bitflood.org
a5757bb0d59e269b977bd6f40d871ba62557f277
6732d1042a9152b96905a5f51c052b5e00da2c39
/include/Actors/Enemies/Melee/Melee.h
0faac8ae48b9f663bc3c2bfb5c6334746d53eb9c
[]
no_license
Oyuret/spelet
0c096538a143b1be8adaf954b09014f51472f0fd
96dc20fe3253789662d0b9778ac42016e06583dc
refs/heads/master
2020-05-18T01:16:22.823206
2014-06-04T22:29:06
2014-06-04T22:29:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
265
h
#ifndef MELEE_H_INCLUDED #define MELEE_H_INCLUDED #include "../Enemy.h" namespace lab3 { using namespace std; class Melee : public Enemy { public: Melee() {} virtual ~Melee() {} private: protected: }; } #endif // MELEE_H_INCLUDED
[ "yuris@kth.se" ]
yuris@kth.se
97a596f5e78555e38122991854954975deb41f6f
f3a9174535cd7e76d1c1e0f0fa1a3929751fb48d
/SDK/PVR_Item_Escape_RepairTool_classes.hpp
800cf748f2e37e3d85d0c9a63fd4807dc3fd60ae
[]
no_license
hinnie123/PavlovVRSDK
9fcdf97e7ed2ad6c5cb485af16652a4c83266a2b
503f8d9a6770046cc23f935f2df1f1dede4022a8
refs/heads/master
2020-03-31T05:30:40.125042
2020-01-28T20:16:11
2020-01-28T20:16:11
151,949,019
5
2
null
null
null
null
UTF-8
C++
false
false
5,726
hpp
#pragma once // PavlovVR (Dumped by Hinnie) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Item_Escape_RepairTool.Item_Escape_RepairTool_C // 0x007C (0x0578 - 0x04FC) class AItem_Escape_RepairTool_C : public AItem_Escape_C { public: unsigned char UnknownData00[0x4]; // 0x04FC(0x0004) MISSED OFFSET struct FPointerToUberGraphFrame UberGraphFrame; // 0x0500(0x0008) (ZeroConstructor, Transient, DuplicateTransient) class UVRHandleComponent* VRHandle; // 0x0508(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData) float HandleRotation; // 0x0510(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x4]; // 0x0514(0x0004) MISSED OFFSET class USoundBase* FlintStrikeSound; // 0x0518(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) class UAudioComponent* FlintStrikeSoundCmp; // 0x0520(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) class USoundBase* TorchSound; // 0x0528(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) class UAudioComponent* TorchSoundCmp; // 0x0530(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) class UAudioComponent* GasSoundCmp; // 0x0538(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) class USoundBase* GasSound; // 0x0540(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) class USoundBase* RepairSound; // 0x0548(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) struct FTimerHandle RepairTimer; // 0x0550(0x0008) (Edit, BlueprintVisible, DisableEditOnInstance) int RepairTicks; // 0x0558(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData02[0x4]; // 0x055C(0x0004) MISSED OFFSET class UAudioComponent* RepairSoundCMP; // 0x0560(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) class UParticleSystem* TorchFX; // 0x0568(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) class UParticleSystemComponent* TorchFXCMP; // 0x0570(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Item_Escape_RepairTool.Item_Escape_RepairTool_C"); return ptr; } void SetHandleRotation(float HandleRotation, bool TurnOff, float* Alpha); void SetTriggerDown(bool TriggerDown); void StopTorchFX(); void PlayTorchFX(); void PlayRepairingSound(); void TryUseItem(class UObject** Object, bool* PlayError); void TryRepair_Client(); void OnRep_RepairTicks(); void TickRepair(); void StopGasSound(); void StopTorchSound(); void PlayGasSound(); void SetGasVolume(float VolumeMultiplier); void PlayTorchSound(); void PlayFlintStrikeSound(); bool CanGetPickedBy(class AVRItemController** ByController); void UserConstructionScript(); void Repair_Objective(class ABP_EscapeObjective_C* EscapeObjective); void Use(); void RepairLock(class ABP_Escape_Lock_C* Escape_Lock); void BndEvt__VRHandle_K2Node_ComponentBoundEvent_4_VRHandleOnRotationInputReceivedSignature__DelegateSignature(float InputValueDegrees); void Used(bool* bJustPicked); void OnPick(class AVRItemController** ByController); void OnDrop(); void BndEvt__SkeletalMesh_K2Node_ComponentBoundEvent_6_ComponentBeginOverlapSignature__DelegateSignature(class UPrimitiveComponent* OverlappedComponent, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int OtherBodyIndex, bool bFromSweep, const struct FHitResult& SweepResult); void BndEvt__VRHandle_K2Node_ComponentBoundEvent_0_VRHandleOnUngrabSignature__DelegateSignature(); void RepairObjective(); void Start_RepairingObjective(); void ReceiveDestroyed(); void ExecuteUbergraph_Item_Escape_RepairTool(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "hsibma02@gmail.com" ]
hsibma02@gmail.com
e4690bd45b49474acdf860c548a4924da0e67e0d
c2fc0bc1bcc05469e859c999324479e521f34077
/猜數字(XAXB).cpp
4e75be08b9eb22af325e484eb744f82d9dd871fd
[]
no_license
lf2netr0/code
bcc01397d362307128358679134f92d09066ef64
5c14f1d412661ae92bd61c5aa7607f57f80dfd82
refs/heads/master
2021-01-10T08:43:04.019634
2016-04-23T14:32:02
2016-04-23T14:32:02
52,195,239
0
0
null
null
null
null
BIG5
C++
false
false
3,007
cpp
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> int q[5]; int a,a1=10000,a2=100000,t,v,ans[5],A,B,C,times=0,control; void question(); int main(void){ question(); do{ control = 0; printf("Enter a integer between 12345 to 98765:\n"); scanf("%d",&a); ans[0]=a/10000; ans[1]=(a/1000)%10; ans[2]=(a/100)%10; ans[3]=(a/10)%10; ans[4]=a%10; if (a==0) { printf("Answer is %d%d%d%d%d.\n",q[0],q[1],q[2],q[3],q[4]); break; } if(a>a1) { if(a<a2) { for(t=0;t<=4;t++){ for(v=t+1;v<=4;v++){ if(ans[t]==ans[v]){ printf("Every number can't repeat.\n"); control = 1; break; } } } if(control==0) { while(1) { times+=1; printf("The %d times\n",times); A=0; B=0; C=0; for(t=0;t<=4;t++){ if(q[t]==ans[t]){ A=A+1; } else{ for(v=0;v<=4;v++){ if(q[t]==ans[v]){ B=B+1; } } } } C=5-B-A; printf("%dA%dC\n",A,C); if(A==5){ printf("You win the Game!\n"); printf("Answer is %d%d%d%d%d.\n",q[0],q[1],q[2],q[3],q[4]); break; } else{ control=1; break; } } } } else if(a>a2) { printf("Please enter integer between 12345 to 98765.\n"); control=1; } } else { printf("Please enter integer between 12345 to 98765.\n"); control=1; } }while(control == 1); system("pause\n"); return 0; } void question(){//產生問題(利用時間種子產生亂數) int i,j; int repeat; srand(time(NULL)); q[0]=rand()%9+1; do{ repeat=0; for(i=1;i<=4;i++){ q[i]=rand()%10; for(j=0;j<i;j++){ if(q[i]==q[j]){ repeat=1; break; } } } }while(repeat==1); }
[ "zxc82990@gmail.com" ]
zxc82990@gmail.com
7f21256fa934b584b68337cbcc3877375ce1d359
53faa0f941ff1fa653e66f43fd68679a8042c895
/core/monitor/TimeBuffer.cc
4e8c15c42713d793e0d1cbd12c4c2d6d97ec6c72
[ "LicenseRef-scancode-cecill-b-en", "CECILL-B" ]
permissive
bdepardo/libdadiCORBA
edf0ac67730267f58ea187d42460f8886bda1ec7
3fec099e0d7aaec54d59542ce2074c7fd74c1d90
refs/heads/master
2021-01-18T00:26:03.750557
2012-09-11T11:54:15
2012-09-11T11:54:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,948
cc
/** * @file TimeBuffer.cc * * @brief Implementation of the TimeBuffer class * * @author - Kevin Coulomb (kevin.coulomb@sysfera.com) * - Georg Hoesch (hoesch@in.tum.de) * - Cyrille Pontvieux (cyrille.pontvieux@edu.univ-fcomte.fr) * * @section Licence * |LICENSE| */ #include "TimeBuffer.hh" #include <iostream> using namespace std; TimeBuffer::TimeBuffer() { this->msgList = new MsgLinkedList(); this->lastTime.sec = 0; this->lastTime.msec = 0; } TimeBuffer::~TimeBuffer() { delete this->msgList; } void TimeBuffer::put(log_msg_t* msg) { msg->warning = false; // To get an read/write iterator for the messages list MsgLinkedList::Iterator* it = this->msgList->getIterator(); // find the good place to insert the message (according to its timestamp) // Messages are order from older messages to newer messages (e.g. newer // messages are on the top of the list) it->resetToLast(); // go at the end of the list while (it->hasCurrent()) { if (!isOlder(it->getCurrentRef()->time, msg->time)) { break; } it->previousRef(); } if (it->hasCurrent()) { it->insertAfter(msg); } else { // must insert in the first position if (this->isOlder(msg->time, this->lastTime)) { msg->warning = true; } it->reset(); it->insertBefore(msg); } delete it; } log_msg_t* TimeBuffer::get(log_time_t minAge) { log_msg_t* msg = NULL; MsgLinkedList::Iterator* it = this->msgList->getIterator(); if (it->hasCurrent()) { // check the age limit if (this->isOlder(minAge, it->getCurrentRef()->time)) { msg = it->removeAndGetCurrent(); // get and delete the current element this->lastTime = msg->time; } } delete it; return msg; } // true if t2 older than t1 bool TimeBuffer::isOlder(log_time_t t1, log_time_t t2) const { // important not to use <= return ((t2.sec < t1.sec) || ((t2.sec == t1.sec) && (t2.msec < t1.msec))); }
[ "kevin.coulomb@sysfera.com" ]
kevin.coulomb@sysfera.com
0a4839a0a6d701686159ef506d02df5a6a577807
7672579040743945f50e696c8cdca1e0acd38bb1
/valobj.h
faa8b899ef3e55b12a8322e52afbceb11d16aca9
[]
no_license
bix191/buby
97ebb656db94026dd6d885a80397823e51ed3632
40141ec53794a1965612250ce4afbbe208cfa7de
refs/heads/master
2021-04-30T14:34:50.227520
2018-02-12T08:42:20
2018-02-12T08:42:20
121,220,600
0
0
null
null
null
null
UTF-8
C++
false
false
488
h
#ifndef VALOBJ #define VALOBJ typedef enum { VALTYPE_INTEGER, VALTYPE_STRING } VALTYPE; class ValObj { VALTYPE valType; public: ValObj(VALTYPE _valtype); VALTYPE getValType(void); }; class ValObjInteger public ValObj { int val; public: ValObjInteger(int _val); int getVal(void); void setVal(int _val); } class ValObjString public ValObj { int val; public: ValObjString(std::string _val); std::string getVal(void); void setVal(std::string _val); } #endif
[ "bix@sting.toybox" ]
bix@sting.toybox
702624697ab09be871f7e5c4322f42ec8b4bd4a7
3aa9a68026ab10ced85dec559b6b4dfcb74ae251
/leetCode/sqrtx/Accepted/8-15-2021, 6_10_07 PM/Solution.cpp
2076080bf0cfc6149c664f736703d85f5a5f902d
[]
no_license
kushuu/competitive_programming_all
10eee29c3ca0656a2ffa37b142df680c3a022f1b
5edaec66d2179a012832698035bdfb0957dbd806
refs/heads/master
2023-08-17T15:09:48.492816
2021-10-04T20:09:37
2021-10-04T20:09:37
334,891,360
3
2
null
null
null
null
UTF-8
C++
false
false
177
cpp
// https://leetcode.com/problems/sqrtx class Solution { public: int mySqrt(int x) { long long int i; for(i = 0; i*i <= x; i++); return i-1; } };
[ "sonikushu007@gmail.com" ]
sonikushu007@gmail.com
e21fa4209a70e15827ba668093359b3068203c83
a642a2969dd2a3728afe1604d6a00e19415e6bbe
/SampleFromGTestRepo/Sample2/sample2.h
3b5542269bb3a6cd0c46edeccf95d214486700b4
[]
no_license
mgkrishnan1/GTest_Bazel_KT
005a238a69fde55d26bf7d0128ce3cba241d7a64
77f5a9543c7e41803d1c349659ca73f8f945da03
refs/heads/master
2023-05-25T18:06:26.792301
2021-06-11T04:28:28
2021-06-11T04:28:28
375,900,255
0
0
null
null
null
null
UTF-8
C++
false
false
2,981
h
// Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // A sample program demonstrating using Google C++ testing framework. #ifndef GOOGLETEST_SAMPLES_SAMPLE2_H_ #define GOOGLETEST_SAMPLES_SAMPLE2_H_ #include <string.h> // A simple string class. class MyString { private: const char* c_string_; const MyString& operator=(const MyString& rhs); public: // Clones a 0-terminated C string, allocating memory using new. static const char* CloneCString(const char* a_c_string); //////////////////////////////////////////////////////////// // // C'tors // The default c'tor constructs a NULL string. MyString() : c_string_(nullptr) {} // Constructs a MyString by cloning a 0-terminated C string. explicit MyString(const char* a_c_string) : c_string_(nullptr) { Set(a_c_string); } // Copy c'tor MyString(const MyString& string) : c_string_(nullptr) { Set(string.c_string_); } //////////////////////////////////////////////////////////// // // D'tor. MyString is intended to be a final class, so the d'tor // doesn't need to be virtual. ~MyString() { delete[] c_string_; } // Gets the 0-terminated C string this MyString object represents. const char* c_string() const { return c_string_; } size_t Length() const { return c_string_ == nullptr ? 0 : strlen(c_string_); } // Sets the 0-terminated C string this MyString object represents. void Set(const char* c_string); }; #endif // GOOGLETEST_SAMPLES_SAMPLE2_H_
[ "muralikrishna1997@gmail.com" ]
muralikrishna1997@gmail.com
c728a8bfc50baf910138c41d1c1220c2308a28e2
7f50a48f089b15c40eeef5647a614b8906f4cc76
/pureVirtualFunctionInterface/pureVirtualFunctionInterface/main.cpp
8ed3a58256a7b99f3e0ab98cc97f1714d5c9b573
[]
no_license
himanchal/UnderstandingCPP
a24a72feb295d24d521bca27bc85ccee0e02e8b4
92a3883ccc6edd772022d011d6cb48b761f1ff38
refs/heads/master
2022-03-21T01:24:02.451255
2019-11-13T15:51:12
2019-11-13T15:51:12
216,514,076
0
0
null
null
null
null
UTF-8
C++
false
false
1,071
cpp
#include <iostream> //this class will behave like an interface as having a pure virtual function //there is no interface keyword in c++ like other languages C#, Java class Printable{ public: virtual std:: string GetClassName() = 0; }; class Entity : public Printable{ public: //pure virtual function //virtual std::string GetName()= 0; //will force the subclasses to implement this function std::string GetClassName() { return "Entity"; } }; class Player : public Entity{ private: std::string _name; public: Player(const std::string& name) : _name(name){} std::string GetName() { return _name; } std::string GetClassName() { return "Player"; } }; //same way we can have more classes class A : public Printable{ public: std::string GetClassName() override{ return "A";} }; void Print(Printable* obj){ std::cout << obj->GetClassName() << std::endl; } int main(int argc, const char * argv[]) { Entity* e = new Entity(); Player* p = new Player("Ronaldhino"); Print(e); Print(p); Print(new A()); return 0; }
[ "himanchalsingh93@gmail.com" ]
himanchalsingh93@gmail.com
daf27a9595cd1e8417c12fba870370f184d05fe5
59f28f769de518183d38dfca04434e363c195cfb
/src/Kernel.hpp
a05ab28a08be5672349f0b44d41e82d061afb222
[]
no_license
IFeelBloated/minsrp
cb6c02004eeee0d6b96335e98673bfa59834e80d
f90c5a78f4c9f4f91d089b5a7a6368e32b98fb08
refs/heads/master
2021-01-18T22:42:39.265579
2016-05-21T07:36:49
2016-05-21T07:36:49
54,386,773
3
2
null
2016-03-21T22:57:32
2016-03-21T12:27:01
C++
UTF-8
C++
false
false
6,911
hpp
#ifndef KERNEL_HPP #define KERNEL_HPP #define _JUMP \ dstp += dst_stride; \ srcp += src_stride #define _PERFORM_GAUSS \ _process_plane_3x3(srcp, src_stride, dstp_a, dst_stride, h, w, true) #define _PERFORM_MEDIAN \ _process_plane_3x3(srcp, src_stride, dstp_b, dst_stride, h, w, false) #define _AMPLIFY_DIF \ _reverse_dif(srcp, dstp, x, _amp, _linear) #define _PERFORM_PAD \ _pad<T1, T2>(srcp, src_stride, padp, pad_stride, h, w) #define _SECURE_SCL 0 #include <algorithm> #include <cmath> #include "VapourSynth.h" #include "VSHelper.h" using namespace std; static volatile uint64_t _ptr_sucker = 0xFFFFFFFFFFFFFFFF; static long val = 0; template<typename T> static inline T _abs(T num) { return (num > 0) ? num : -num; } static inline void _clamp(int bits) { val = max(min(val, (1l << bits) - 1l), 0l); } template<typename T1, typename T2> static void _pad(const T1 *&srcp, int &src_stride, T1 *&padp, int pad_stride, int h, int w) { T1 *padtmp = padp; for (int y = 1; y < h + 1; ++y) { padp += pad_stride; for (int x = 1; x < w + 1; ++x) padp[x] = srcp[x - 1]; srcp += src_stride; } srcp = padtmp + pad_stride + 1; src_stride = pad_stride; padp += pad_stride; for (int x = 1; x < w + 1; ++x) padp[x] = padp[x - pad_stride]; padp = padtmp; for (int x = 1; x < w + 1; ++x) padp[x] = padp[x + pad_stride]; for (int y = 1; y < h + 1; ++y) padp[y*pad_stride] = padp[y*pad_stride + 1]; padp = padp + pad_stride - 1; for (int y = 1; y < h + 1; ++y) padp[y*pad_stride] = padp[y*pad_stride - 1]; padp = padtmp; *padp = static_cast<T1>((static_cast<T2>(padp[1]) + padp[pad_stride]) / 2); padp = padp + pad_stride - 1; *padp = static_cast<T1>((static_cast<T2>(*(padp - 1)) + padp[pad_stride]) / 2); padp += (h + 1)*pad_stride; *padp = static_cast<T1>((static_cast<T2>(*(padp - 1)) + *(padp - pad_stride)) / 2); padp = padtmp + (h + 1)*pad_stride; *padp = static_cast<T1>((static_cast<T2>(padp[1]) + *(padp - pad_stride)) / 2); padp = nullptr; } static void _gauss_3x3(float *dstp, int x) { static float * const a = reinterpret_cast<float *>(_ptr_sucker); dstp[x] = static_cast<float>( (4. * a[0] + 2. * (static_cast<double>(a[2]) + a[4] + a[5] + a[7]) + a[1] + a[3] + a[6] + a[8]) / 16.); } static void _gauss_3x3(uint16_t *dstp, int x) { static uint16_t * const a = reinterpret_cast<uint16_t *>(_ptr_sucker); val = ((a[0] << 2l) + ((static_cast<uint32_t>(a[2]) + a[4] + a[5] + a[7]) << 1l) + a[1] + a[3] + a[6] + a[8] + 8l) >> 4l; _clamp(16); dstp[x] = static_cast<uint16_t>(val); } static void _gauss_3x3(uint8_t *dstp, int x) { static uint8_t * const a = reinterpret_cast<uint8_t *>(_ptr_sucker); val = ((a[0] << 2l) + ((static_cast<uint32_t>(a[2]) + a[4] + a[5] + a[7]) << 1l) + a[1] + a[3] + a[6] + a[8] + 8l) >> 4l; _clamp(8); dstp[x] = static_cast<uint8_t>(val); } template<typename T> static void _median_3x3(T *dstp, int x) { static T * const a = reinterpret_cast<T *>(_ptr_sucker); nth_element(a, a + 4, a + 9); dstp[x] = a[4]; } template<typename T> static void _process_plane_3x3(const T *srcp, int src_stride, T *dstp, int dst_stride, int h, int w, bool gauss) { void(*_func)(T *, int) = nullptr; alignas(16) static T a[9]; _ptr_sucker = reinterpret_cast<uint64_t>(a); if (gauss) _func = _gauss_3x3; else _func = _median_3x3<T>; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { a[0] = *(srcp + x); a[1] = *(srcp + x - src_stride - 1); a[2] = *(srcp + x - src_stride); a[3] = *(srcp + x - src_stride + 1); a[4] = *(srcp + x - 1); a[5] = *(srcp + x + 1); a[6] = *(srcp + x + src_stride - 1); a[7] = *(srcp + x + src_stride); a[8] = *(srcp + x + src_stride + 1); _func(dstp, x); } _JUMP; } } static void _reverse_dif(const float *srcp, float *dstp, int x, double _amp, bool _linear) { if (_linear) dstp[x] = static_cast<float>((1. + _amp) * srcp[x] - dstp[x] * _amp); else dstp[x] = static_cast<float>(srcp[x] + (_amp * 4. * pow(_abs(srcp[x] * 256. - dstp[x] * 256.) / 4., 0.25)) * ((srcp[x] * 256. - dstp[x] * 256.) / (_abs(srcp[x] * 256. - dstp[x] * 256.) + 1.001)) / 256.); } static void _reverse_dif(const uint16_t *srcp, uint16_t *dstp, int x, double _amp, bool _linear) { if (_linear) val = static_cast<long>((1. + _amp) * srcp[x] - dstp[x] * _amp); else val = static_cast<long>(srcp[x] + (_amp * 4. * pow(_abs(srcp[x] / 256. - dstp[x] / 256.) / 4., 0.25)) * ((srcp[x] / 256. - dstp[x] / 256.) / (_abs(srcp[x] / 256. - dstp[x] / 256.) + 1.001)) * 256.); _clamp(16); dstp[x] = static_cast<uint16_t>(val); } static void _reverse_dif(const uint8_t *srcp, uint8_t *dstp, int x, double _amp, bool _linear) { if (_linear) val = static_cast<long>((1. + _amp) * srcp[x] - dstp[x] * _amp); else val = static_cast<long>(srcp[x] + (_amp * 4. * pow(_abs(static_cast<double>(srcp[x]) - dstp[x]) / 4., 0.25)) * ((static_cast<double>(srcp[x]) - dstp[x]) / (_abs(static_cast<double>(srcp[x]) - dstp[x]) + 1.001))); _clamp(8); dstp[x] = static_cast<uint8_t>(val); } template<typename T1, typename T2> static void _do_it_(const VSAPI *vsapi, const VSFrameRef *src, int src_stride, VSFrameRef *dst, int dst_stride, VSFrameRef *pad, int pad_stride, int h, int w, VSFrameRef *dst_a, VSFrameRef *dst_b, int plane, double _amp, int mode, bool _linear) { const T1 *srcp = reinterpret_cast<const T1 *>(vsapi->getReadPtr(src, plane)); T1 *padp = reinterpret_cast<T1 *>(vsapi->getWritePtr(pad, plane)); T1 *dstp = reinterpret_cast<T1 *>(vsapi->getWritePtr(dst, plane)); T1 *dstp_a = reinterpret_cast<T1 *>(vsapi->getWritePtr(dst_a, plane)); T1 *dstp_b = reinterpret_cast<T1 *>(vsapi->getWritePtr(dst_b, plane)); if (!mode) for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) dstp[x] = srcp[x]; _JUMP; } else if (mode == 1) { _PERFORM_PAD; _PERFORM_GAUSS; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { dstp[x] = dstp_a[x]; _AMPLIFY_DIF; } _JUMP; dstp_a += dst_stride; } } else if (mode == 2) { _PERFORM_PAD; _PERFORM_MEDIAN; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { dstp[x] = dstp_b[x]; _AMPLIFY_DIF; } _JUMP; dstp_b += dst_stride; } } else { _PERFORM_PAD; _PERFORM_GAUSS; _PERFORM_MEDIAN; T2 _dif_a = 0; T2 _dif_b = 0; for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { _dif_a = _abs(static_cast<T2>(dstp_a[x]) - srcp[x]); _dif_b = _abs(static_cast<T2>(dstp_b[x]) - srcp[x]); dstp[x] = (_dif_a > _dif_b) ? dstp_b[x] : dstp_a[x]; _AMPLIFY_DIF; } _JUMP; dstp_a += dst_stride; dstp_b += dst_stride; } } } #endif
[ "nickgray0@gmail.com" ]
nickgray0@gmail.com
91337debf998b9732b86f1016a19074ac1e88661
183e4126b2fdb9c4276a504ff3ace42f4fbcdb16
/V семестр/Системне програмування - 2/Кочетов/лабы/lab7/lab7/syntaxP.cpp
2f752f06e90769904e9b50b0a0081921e59187e4
[]
no_license
Computer-engineering-FICT/Computer-engineering-FICT
ab625e2ca421af8bcaff74f0d37ac1f7d363f203
80b64b43d2254e15338060aa4a6d946e8bd43424
refs/heads/master
2023-08-10T08:02:34.873229
2019-06-22T22:06:19
2019-06-22T22:06:19
193,206,403
3
0
null
2023-07-22T09:01:05
2019-06-22T07:41:22
HTML
WINDOWS-1251
C++
false
false
4,001
cpp
#include "stdafx.h" #include "token.h" #include "syntaxP.h" extern enum tokPrec opPrFC[256]; extern enum tokPrec opPrGC[256]; extern enum tokPrec opPrFP[256]; extern enum tokPrec opPrGP[256]; enum tokPrec *opPrF,*opPrG; extern char *oprtrC[], *oprtrP[], *oprtrV[], *cprC[], *cprP[], *cprV[]; extern char **oprtr, **cpr, modeP, // тип роздільника операторних дужок для Паскаля modeC, // тип роздільника операторних дужок для С modeL; void SxAnInit(char nl) {char i=0; switch (nl) {case 'P': opPrF=opPrFP; opPrG=opPrGP; modeC=0; modeL=modeP; modeP=1; oprtr=oprtrP; cpr=cprP; break; case 'V': default: case 'C':opPrF=opPrFC; opPrG=opPrGC; modeP=0; modeL=modeC; modeC=1; oprtr=oprtrC; cpr=cprC; } } int nxtProd(struct lxNode*nd, // вказівник на початок масиву вузлів int nR, // номер кореневого вузла int nC) // номер поточного вузла {int n=nC-1; // номер попереднього вузла enum tokPrec pC = opPrF[nd[nC].ndOp],// передування поточного вузла *opPr=opPrG;//F;// nd[nC].prvNd = nd+n; while(n!=-1) // цикл просування від попереднього вузла до кореню {if(opPr[nd[n].ndOp]<pC//)// порівняння функцій передувань &&nd[n].ndOp</*_ctbz*/_frkz) {if(n!=nC-1&&nd[n].pstNd!=0) // перевірка необхідності вставки {nd[nC].prvNd = nd[n].pstNd; // підготовка зв’язків nd[nC].prvNd->prnNd=/*nd+*/nC;} // для вставки вузла if(opPrF[nd[n].ndOp]==pskw&&nd[n].prvNd==0)nd[n].prvNd = nd+nC; else nd[n].pstNd = nd+nC; nd[nC].prnNd=/*nd+*/n; // додавання піддерева return nR;} if(opPrG[nd[n].ndOp]==pC&& (nd[n].ndOp==_brkt||nd[n].ndOp==_ixbr||nd[n].ndOp==_opbr||nd[n].ndOp==_tdbr)) {nd[n].ndOp=(enum tokType)((nd[n].ndOp-_fork)/2+_frkz);//09.04.07 nd[nC]=nd[n]; if(nd[nC].prnNd==-1){nR=nC; nd[nR].prnNd=-1;} else if(opPrF[nd[nd[nC].prnNd].ndOp]==pskw&&nd[nC].ndOp<_frkz) nd[nd[nC].prnNd].prvNd = nd+nC; else if(opPrF[nd[nd[nC].prnNd].ndOp]==pekw&&nd[nC].ndOp==_opbz) {nd[nd[nC].prnNd].prvNd =nd+nC;nd[nd[nC].prnNd].pstNd=0;} return nR;} /* if(nd[n].ndOp==_brkt||nd[n].ndOp==_ixbr||nd[n].ndOp==_opbr||nd[n].ndOp==_tdbr) {nd[nC].prnNd=n; nd[nC].prvNd=nd[n].pstNd; nd[n].pstNd->prnNd=nC; nd[n].pstNd= nd+nC; return nR;}*/ n=nd[n].prnNd; opPr=opPrG;} // просування до кореню // if(n<=) else nd[nC].prvNd = nd+nR; nd[nR].prnNd=/*nd+*/nC; nR = nC; nd[nR].prnNd=-1; return nR;} int prCmpr(struct lxNode*nd, int nn, int nr) //компресія для скорочення графа {int nR, nN=0, nC=0; do{ if((nd+nN)->ndOp==_remL||(nd+nN)->ndOp==_rem) {if(nd[nN].pstNd>&nd[nN]&&nd[nN].prnNd!=-1) {if(nC-nN>1)nd[nN]=nd[nC]; // nN++; nC++; continue;} } // if(nR<-1){nC++; continue;} if(nr==nC)nr=nN; if(nd[nC].ndOp==_brkz&&nd[nC].prvNd==0) {if(nd[nd[nC].prnNd].prvNd==&nd[nC]) {nd[nC].pstNd->prnNd=nd[nC].prnNd; nd[nd[nC].prnNd].prvNd=nd[nC].pstNd;} if(nd[nd[nC].prnNd].pstNd==&nd[nC]) // b 02/06/07 {nd[nC].pstNd->prnNd=nd[nC].prnNd; nd[nd[nC].prnNd].pstNd=nd[nC].pstNd;}// e 02/06/07 nC++; } if(nN!=nC) {nR=nd[nC].prnNd; nd[nN]=nd[nC]; //зв'язок з батьківським вузлом if(nd[nR].prvNd==&nd[nC]) nd[nR].prvNd=&nd[nN]; if(nd[nR].pstNd==&nd[nC]) nd[nR].pstNd=&nd[nN]; if(nd[nN].ndOp>_cnst){ //зв'язок з лівим наступником if(nd[nN].prvNd) nd[nN].prvNd->prnNd=nN; //зв'язок з правим наступником if(nd[nN].pstNd) nd[nN].pstNd->prnNd=nN; } // if(nR<nN)nd[nN].prnNd=nR; // nd[nR].prvNd } // else nC //}else nN++; nC++; }while(nC<nn); return nr; }
[ "mazanyan027@gmail.com" ]
mazanyan027@gmail.com
9ceb00263021ae9b4317417730464be9b6cbecd3
57c831409ef85f47c1da4dcdf50160216e815acc
/src/ofApp.h
e278e25ea2f9205708ce2b518d75f8a524f6d060
[]
no_license
jfarman/deeply
8a27af75840c9aaa6492b06509a7f40823a35e43
5bf30c3718cf2facf0af91a77940967acfba14a6
refs/heads/master
2021-01-10T09:06:09.770525
2015-12-11T01:02:34
2015-12-11T01:02:34
47,796,191
0
0
null
null
null
null
UTF-8
C++
false
false
2,897
h
#pragma once #include "ofMain.h" #include "ofxStk.h" #include "ofxGui.h" #include "ofxVboParticles.h" #include "Granulate.h" #include "Goom.h" #include <sstream> #include <algorithm> using namespace std; #define expand 7.0 #define GROWTH_CONST 70.0f #define NUM_COMPONENTS 6 #define NUM_VOICES 4 #define NUM_CHORDS 4 #define RGB 3 #define R_INDEX 0 #define G_INDEX 1 #define B_INDEX 2 #define NUM_COLORS 5 // Constants that define the phases // of the breathing cycle (ints) #define CYCLE_TOTAL 12 #define CYCLE_INHALE_PHASE 4 #define CYCLE_HOLD_BREATH 6 #define CYCLE_EXHALE_PHASE 10 // Constants that define the phases // of the breathing cycle (floats) #define CYCLE_TOTAL_F 12.0f #define CYCLE_INHALE_PHASE_F 4.0f #define CYCLE_HOLD_BREATH_F 6.0f #define CYCLE_EXHALE_PHASE_F 10.0f struct MusicalNote { stk::StkFloat noteNumber; long voiceTag; }; class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofEasyCam camera; ofIcoSpherePrimitive centerSphere; ofIcoSpherePrimitive icospheres[NUM_COMPONENTS]; int colors[NUM_COLORS][RGB]; std::vector<int> colorOrder; void adjustNotes(int i); void initColors(); float time; // keeps track of the elapsed time float timer; // timer that starts after the into int currentStep; // current step of the breathing cycle int numSpheres; // number of spheres to be rendered float width; // keeps track of the largest sphere's width float defaultWidth; // the default width for the spheres void audioOut(float *output,int bufferSize,int nChannels); stk::Voicer *voicer; stk::Granulate granulater; MusicalNote c,d,e,f,g,a,b,c2,d2,e2; MusicalNote x1,x2,x3,x4; void initChords(int offset, bool update); int newRandom(int n, int length); MusicalNote base; bool baseOn; MusicalNote chords[4][4]; MusicalNote newChords[4][4]; bool notesOn[4]; bool isIntro; bool scaleChanged; stk::FreeVerb reverb; stk::OnePole filter; void reverbParametersChanged(float &value); void filterCutoffChanged(float &value); float reverbValue; float mod_f; int mod_i; int currScale; int currCycle; int currChord; ofTrueTypeFont header; ofTrueTypeFont headerLG; ofTrueTypeFont instructions; ofxVboParticles *vboParticles; ofVec3f particlePosition; };
[ "jfarman@stanford.edu" ]
jfarman@stanford.edu
f1281d0704e8a5b521516bed218475a6a81bd9e5
6eaab6b260d2b750c074d7b569ff19c930a3059f
/c++_primer_plus/第八章/8.14temptempover.cpp
96bd8255429f0f2e992db312602c824077eb5b73
[]
no_license
kapuni/box
9b95505b2f00d7ad00e20cfe540d883dcbbb27b1
6187368e2bbcba2148c48b82a4979dae3cc9756a
refs/heads/master
2023-05-05T01:21:08.092428
2021-05-10T14:36:39
2021-05-10T14:36:39
164,998,826
1
0
null
null
null
null
UTF-8
C++
false
false
1,216
cpp
//temptemoover.cpp -- template overloading #include<iostream> //template A template <typename T> void ShowArray(T arr[] , int m); //template B template <typename T> void ShowArray(T * arr[], int n); struct debts { char name[50]; double amount; }; int main() { using namespace std; int things[6] = {13, 21, 103, 301, 310, 130}; struct debts mr_E[3] = { { "Ima Wolfe", 2400.0 }, { "Ura Foxe", 1300.0 }, { "Iby Stout", 1800.0 } }; double * pd[3]; for (int i = 0; i< 3; i++) pd[i] = &mr_E[i].amount; cout << "Listing Mr.R's counts of thongs:\n"; //use template A ShowArray(things, 6); cout << "Listing Mr.E's debts: \n"; //use template B ShowArray(pd, 3); return 0; } template <typename T> void ShowArray (T arr[], int n) { using namespace std; cout << "template A\n"; for (int i = 0; i< n; i++) cout << arr[i] << " "; cout << endl; } template <typename T> void ShowArray (T *arr[], int n) { using namespace std; cout << "template B\n"; for (int i = 0; i< n; i++) cout << *arr[i] << " "; cout << endl; }
[ "910048757@qq.com" ]
910048757@qq.com
ecc467095839ef6e34d67b3fa8c4a36a16f09344
499f4b46c5745bf8ea155551712b4c401861b0eb
/NoSqlDb/XmlDocument/XmlDocument/XmlDocument.h
ec43f5ba39fec3e0b2123a4215e371d6cb6dbef8
[]
no_license
acmer29/RemoteCodeRepository
c2619b0d011f3547e87a0e412ecd3cd76839f740
943804560f13ac112ec24e012824e0fe57a339e5
refs/heads/master
2021-09-26T10:28:35.180250
2018-05-01T22:12:50
2018-05-01T22:12:50
155,156,270
0
0
null
null
null
null
UTF-8
C++
false
false
6,643
h
#ifndef XMLDOCUMENT_H #define XMLDOCUMENT_H /////////////////////////////////////////////////////////////////// // XmlDocument.h - a container of XmlElement nodes // // Ver 2.5 // // Application: Help for CSE687 Pr#2, Spring 2015 // // Platform: Dell XPS 2720, Win 8.1 Pro, Visual Studio 2013 // // Author: Jim Fawcett, CST 4-187, 443-3948 // // jfawcett@twcny.rr.com // /////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * This package is intended to help students in CSE687 - Object Oriented Design * get started with Project #2 - XML Document Model. It uses C++11 constructs, * most noteably std::shared_ptr. The XML Document Model is essentially * a program-friendly wrapper around an Abstract Syntax Tree (AST) used to * contain the results of parsing XML markup. * * Abstract Syntax Trees, defined in this package, are unordered trees with * two types of nodes: * Terminal nodes - nodes with no children * Non-Terminal nodes - nodes which may have a finite number of children * They are often used to contain the results of parsing some language. * * The elements defined in the companion package, XmlElement, will be used in * the AST defined in this package. They are: * AbstractXmlElement - base for all the XML Element types * DocElement - XML element with children designed to hold prologue, Xml root, and epilogue * TaggedElement - XML element with tag, attributes, child elements * TextElement - XML element with only text, no markup * CommentElement - XML element with comment markup and text * ProcInstrElement - XML element with markup and attributes but no children * XmlDeclarElement - XML declaration element with attributes but no children * * Required Files: * --------------- * - XmlDocument.h, XmlDocument.cpp, * XmlElement.h, XmlElement.cpp * * Build Process: * -------------- * devenv AST.sln /debug rebuild * * Maintenance History: * -------------------- * ver 2.5 : 02 Feb 2018 * - completed attribute handling by adding two new methods to AbstractXmlElement * and overrides of those methods in TaggedElement. * ver 2.4 : 30 Jan 2018 * - added trimming of text end in XmlParser::CreateTextElement() * ver 2.3 : 18 Feb 2017 * - now create docElement in XmlDocument constructor even if there is * no argument. * ver 2.2 : 01 Jun 2015 * - added building document from XML file using XmlParser in constructor * - added test to teststub * ver 2.1 : 07 Mar 2015 * - added an XmlDocument method DFS(...) to implement Depth First Search. * This isn't really needed, but was added to illustrate the answer to * a Midterm question. * ver 2.0 : 04 Mar 2015 * This version can programmatically create, edit, and save an XML document. * It is not yet able to parse an XML string or file. * - deleted copy constructor and assignment operator * - defined move constructor and move assignment * - defined search methods element, elements, descendents, select, find * - defined access methods docElement() and xmlRoot() * - defined toString() * ver 1.2 : 21 Feb 2015 * - modified these comments * ver 1.1 : 14 Feb 2015 * - minor changes to comments, method arguments * Ver 1.0 : 11 Feb 2015 * - first release * * ToDo: * ----- * This is the beginning of an XmlDocument class for Project #2. * It lays out a suggested design, which you are not compelled to follow. * If it helps then use it. If not you don't have to. * * Note that I've simply roughed in a design that is similar to that * used in the .Net Framework XDocument class. */ #include <memory> #include <string> #include "../XmlElement/XmlElement.h" namespace XmlProcessing { /////////////////////////////////////////////////////////////////////////// // XmlDocument class class XmlDocument { public: using sPtr = std::shared_ptr < AbstractXmlElement >; enum sourceType { file, str }; // construction and assignment XmlDocument(sPtr pRoot = nullptr) : pDocElement_(pRoot) { if (!pRoot) pDocElement_ = makeDocElement(); } XmlDocument(const std::string& src, sourceType srcType = str); XmlDocument(const XmlDocument& doc) = delete; XmlDocument(XmlDocument&& doc); XmlDocument& operator=(const XmlDocument& doc) = delete; XmlDocument& operator=(XmlDocument&& doc); // access to docElement and XML root std::shared_ptr<AbstractXmlElement>& docElement() { return pDocElement_; } std::shared_ptr<AbstractXmlElement> xmlRoot(); bool xmlRoot(sPtr pRoot); // queries return XmlDocument references so they can be chained, e.g., doc.element("foobar").descendents(); XmlDocument& element(const std::string& tag); // found_[0] contains first element (DFS order) with tag XmlDocument& elements(const std::string& tag); // found_ contains all children of first element with tag XmlDocument& descendents(const std::string& tag = ""); // found_ contains descendents of prior found_[0] std::vector<sPtr> select(); // returns found_. Uses std::move(found_) to clear found_ bool find(const std::string& tag, sPtr pElem, bool findall = true); size_t size(); std::string toString(); template<typename CallObj> void DFS(sPtr pElem, CallObj& co); private: sPtr pDocElement_; // AST that holds procInstr, comments, XML root, and more comments std::vector<sPtr> found_; // query results }; //----< search subtree of XmlDocument >------------------------------------ template<typename CallObj> void XmlDocument::DFS(sPtr pElem, CallObj& co) { co(*pElem); for (auto pChild : pElem->children()) DFS(pChild, co); } /////////////////////////////////////////////////////////////////////////// // Global Functions for Depth First Search // // These functions take a callable object to define processing on each // element encountered on search traversal. They may be functions, // functors, or lambdas - see XmlDocument.cpp for examples. //----< search subtree of XmlDocument >------------------------------------ template<typename CallObj> void DFS(XmlDocument::sPtr pElem, CallObj& co) { using sPtr = XmlDocument::sPtr; co(*pElem); for (auto pChild : pElem->children()) DFS(pChild, co); } //----< search entire XmlDocument >---------------------------------------- template<typename CallObj> void DFS(XmlDocument& doc, CallObj& co) { using sPtr = XmlDocument::sPtr; sPtr pDocElem = doc.docElement(); DFS(pDocElem, co); } } #endif
[ "tqi100@syr.edu" ]
tqi100@syr.edu
bb01e24c13d17fa2cb2c0996f957556df0286790
27c02d8a5c819307ea736b7e2968171ff25f607b
/AZ3166/tests/UnitTest/UnitTest.ino
4ef7aaff0e838eabc1fcadcefeed25be41baaed5
[ "MIT" ]
permissive
vnn0804/devkit-sdk
11ffc949650abbf79196aa1550ca4cbfbb1e7de1
33f1a450fd138d932561d707acdcebeb1d7de05b
refs/heads/master
2020-03-07T03:43:16.075978
2018-03-27T02:52:47
2018-03-27T02:52:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
256
ino
#include "ArduinoUnit.h" #include "HTS221Sensor.h" #include "lis2mdlSensor.h" #include "LSM6DSLSensor.h" #include "RGB_LED.h" #include "AZ3166WiFi.h" #include "SystemWiFi.h" #include "config.h" void setup() { I2CInit(); } void loop() { Test::run(); }
[ "arthma@microsoft.com" ]
arthma@microsoft.com
621eb22bbb8d36a1ebbe51af78be37207cbc26f1
b78ce7249140f3b8e26d7a0b3c4cd6fc02918095
/DuiLib/Core/UIRender.cpp
342f9ccbe9a3e97629642aa078b06a5adbd319d0
[]
no_license
miketwais/DuiLib_Ultimate
2f9e57cc4057bd780999b3f26194689a2ddc0a8b
4cc23de4606fb047df8edfd4ebe3552c838b9907
refs/heads/master
2021-01-11T12:28:18.445740
2016-12-13T02:19:14
2016-12-13T02:19:14
null
0
0
null
null
null
null
GB18030
C++
false
false
92,184
cpp
#include "StdAfx.h" #define STB_IMAGE_IMPLEMENTATION #include "..\Utils\stb_image.h" #ifdef USE_XIMAGE_EFFECT # include "../../3rd/CxImage/ximage.h" # include "../../3rd/CxImage/ximage.cpp" # include "../../3rd/CxImage/ximaenc.cpp" # include "../../3rd/CxImage/ximagif.cpp" # include "../../3rd/CxImage/ximainfo.cpp" # include "../../3rd/CxImage/ximalpha.cpp" # include "../../3rd/CxImage/ximapal.cpp" # include "../../3rd/CxImage/ximatran.cpp" # include "../../3rd/CxImage/ximawnd.cpp" # include "../../3rd/CxImage/xmemfile.cpp" #endif /////////////////////////////////////////////////////////////////////////////////////// DECLARE_HANDLE(HZIP); // An HZIP identifies a zip file that has been opened typedef DWORD ZRESULT; typedef struct { int index; // index of this file within the zip char name[MAX_PATH]; // filename within the zip DWORD attr; // attributes, as in GetFileAttributes. FILETIME atime,ctime,mtime;// access, create, modify filetimes long comp_size; // sizes of item, compressed and uncompressed. These long unc_size; // may be -1 if not yet known (e.g. being streamed in) } ZIPENTRY; typedef struct { int index; // index of this file within the zip TCHAR name[MAX_PATH]; // filename within the zip DWORD attr; // attributes, as in GetFileAttributes. FILETIME atime,ctime,mtime;// access, create, modify filetimes long comp_size; // sizes of item, compressed and uncompressed. These long unc_size; // may be -1 if not yet known (e.g. being streamed in) } ZIPENTRYW; #define OpenZip OpenZipU #define CloseZip(hz) CloseZipU(hz) extern HZIP OpenZipU(void *z,unsigned int len,DWORD flags); extern ZRESULT CloseZipU(HZIP hz); #ifdef _UNICODE #define ZIPENTRY ZIPENTRYW #define GetZipItem GetZipItemW #define FindZipItem FindZipItemW #else #define GetZipItem GetZipItemA #define FindZipItem FindZipItemA #endif extern ZRESULT GetZipItemA(HZIP hz, int index, ZIPENTRY *ze); extern ZRESULT GetZipItemW(HZIP hz, int index, ZIPENTRYW *ze); extern ZRESULT FindZipItemA(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze); extern ZRESULT FindZipItemW(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRYW *ze); extern ZRESULT UnzipItem(HZIP hz, int index, void *dst, unsigned int len, DWORD flags); /////////////////////////////////////////////////////////////////////////////////////// namespace DuiLib { static int g_iFontID = MAX_FONT_ID; ///////////////////////////////////////////////////////////////////////////////////// // // CRenderClip::~CRenderClip() { ASSERT(::GetObjectType(hDC)==OBJ_DC || ::GetObjectType(hDC)==OBJ_MEMDC); ASSERT(::GetObjectType(hRgn)==OBJ_REGION); ASSERT(::GetObjectType(hOldRgn)==OBJ_REGION); ::SelectClipRgn(hDC, hOldRgn); ::DeleteObject(hOldRgn); ::DeleteObject(hRgn); } void CRenderClip::GenerateClip(HDC hDC, RECT rc, CRenderClip& clip) { RECT rcClip = { 0 }; ::GetClipBox(hDC, &rcClip); clip.hOldRgn = ::CreateRectRgnIndirect(&rcClip); clip.hRgn = ::CreateRectRgnIndirect(&rc); ::ExtSelectClipRgn(hDC, clip.hRgn, RGN_AND); clip.hDC = hDC; clip.rcItem = rc; } void CRenderClip::GenerateRoundClip(HDC hDC, RECT rc, RECT rcItem, int width, int height, CRenderClip& clip) { RECT rcClip = { 0 }; ::GetClipBox(hDC, &rcClip); clip.hOldRgn = ::CreateRectRgnIndirect(&rcClip); clip.hRgn = ::CreateRectRgnIndirect(&rc); HRGN hRgnItem = ::CreateRoundRectRgn(rcItem.left, rcItem.top, rcItem.right + 1, rcItem.bottom + 1, width, height); ::CombineRgn(clip.hRgn, clip.hRgn, hRgnItem, RGN_AND); ::ExtSelectClipRgn(hDC, clip.hRgn, RGN_AND); clip.hDC = hDC; clip.rcItem = rc; ::DeleteObject(hRgnItem); } void CRenderClip::UseOldClipBegin(HDC hDC, CRenderClip& clip) { ::SelectClipRgn(hDC, clip.hOldRgn); } void CRenderClip::UseOldClipEnd(HDC hDC, CRenderClip& clip) { ::SelectClipRgn(hDC, clip.hRgn); } ///////////////////////////////////////////////////////////////////////////////////// // // static const float OneThird = 1.0f / 3; static void RGBtoHSL(DWORD ARGB, float* H, float* S, float* L) { const float R = (float)GetRValue(ARGB), G = (float)GetGValue(ARGB), B = (float)GetBValue(ARGB), nR = (R<0?0:(R>255?255:R))/255, nG = (G<0?0:(G>255?255:G))/255, nB = (B<0?0:(B>255?255:B))/255, m = min(min(nR,nG),nB), M = max(max(nR,nG),nB); *L = (m + M)/2; if (M==m) *H = *S = 0; else { const float f = (nR==m)?(nG-nB):((nG==m)?(nB-nR):(nR-nG)), i = (nR==m)?3.0f:((nG==m)?5.0f:1.0f); *H = (i-f/(M-m)); if (*H>=6) *H-=6; *H*=60; *S = (2*(*L)<=1)?((M-m)/(M+m)):((M-m)/(2-M-m)); } } static void HSLtoRGB(DWORD* ARGB, float H, float S, float L) { const float q = 2*L<1?L*(1+S):(L+S-L*S), p = 2*L-q, h = H/360, tr = h + OneThird, tg = h, tb = h - OneThird, ntr = tr<0?tr+1:(tr>1?tr-1:tr), ntg = tg<0?tg+1:(tg>1?tg-1:tg), ntb = tb<0?tb+1:(tb>1?tb-1:tb), B = 255*(6*ntr<1?p+(q-p)*6*ntr:(2*ntr<1?q:(3*ntr<2?p+(q-p)*6*(2.0f*OneThird-ntr):p))), G = 255*(6*ntg<1?p+(q-p)*6*ntg:(2*ntg<1?q:(3*ntg<2?p+(q-p)*6*(2.0f*OneThird-ntg):p))), R = 255*(6*ntb<1?p+(q-p)*6*ntb:(2*ntb<1?q:(3*ntb<2?p+(q-p)*6*(2.0f*OneThird-ntb):p))); *ARGB &= 0xFF000000; *ARGB |= RGB( (BYTE)(R<0?0:(R>255?255:R)), (BYTE)(G<0?0:(G>255?255:G)), (BYTE)(B<0?0:(B>255?255:B)) ); } static COLORREF PixelAlpha(COLORREF clrSrc, double src_darken, COLORREF clrDest, double dest_darken) { return RGB (GetRValue (clrSrc) * src_darken + GetRValue (clrDest) * dest_darken, GetGValue (clrSrc) * src_darken + GetGValue (clrDest) * dest_darken, GetBValue (clrSrc) * src_darken + GetBValue (clrDest) * dest_darken); } static BOOL WINAPI AlphaBitBlt(HDC hDC, int nDestX, int nDestY, int dwWidth, int dwHeight, HDC hSrcDC, \ int nSrcX, int nSrcY, int wSrc, int hSrc, BLENDFUNCTION ftn) { HDC hTempDC = ::CreateCompatibleDC(hDC); if (NULL == hTempDC) return FALSE; //Creates Source DIB LPBITMAPINFO lpbiSrc = NULL; // Fill in the BITMAPINFOHEADER lpbiSrc = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; if (lpbiSrc == NULL) { ::DeleteDC(hTempDC); return FALSE; } lpbiSrc->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); lpbiSrc->bmiHeader.biWidth = dwWidth; lpbiSrc->bmiHeader.biHeight = dwHeight; lpbiSrc->bmiHeader.biPlanes = 1; lpbiSrc->bmiHeader.biBitCount = 32; lpbiSrc->bmiHeader.biCompression = BI_RGB; lpbiSrc->bmiHeader.biSizeImage = dwWidth * dwHeight; lpbiSrc->bmiHeader.biXPelsPerMeter = 0; lpbiSrc->bmiHeader.biYPelsPerMeter = 0; lpbiSrc->bmiHeader.biClrUsed = 0; lpbiSrc->bmiHeader.biClrImportant = 0; COLORREF* pSrcBits = NULL; HBITMAP hSrcDib = CreateDIBSection ( hSrcDC, lpbiSrc, DIB_RGB_COLORS, (void **)&pSrcBits, NULL, NULL); if ((NULL == hSrcDib) || (NULL == pSrcBits)) { delete [] lpbiSrc; ::DeleteDC(hTempDC); return FALSE; } HBITMAP hOldTempBmp = (HBITMAP)::SelectObject (hTempDC, hSrcDib); ::StretchBlt(hTempDC, 0, 0, dwWidth, dwHeight, hSrcDC, nSrcX, nSrcY, wSrc, hSrc, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); //Creates Destination DIB LPBITMAPINFO lpbiDest = NULL; // Fill in the BITMAPINFOHEADER lpbiDest = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; if (lpbiDest == NULL) { delete [] lpbiSrc; ::DeleteObject(hSrcDib); ::DeleteDC(hTempDC); return FALSE; } lpbiDest->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); lpbiDest->bmiHeader.biWidth = dwWidth; lpbiDest->bmiHeader.biHeight = dwHeight; lpbiDest->bmiHeader.biPlanes = 1; lpbiDest->bmiHeader.biBitCount = 32; lpbiDest->bmiHeader.biCompression = BI_RGB; lpbiDest->bmiHeader.biSizeImage = dwWidth * dwHeight; lpbiDest->bmiHeader.biXPelsPerMeter = 0; lpbiDest->bmiHeader.biYPelsPerMeter = 0; lpbiDest->bmiHeader.biClrUsed = 0; lpbiDest->bmiHeader.biClrImportant = 0; COLORREF* pDestBits = NULL; HBITMAP hDestDib = CreateDIBSection ( hDC, lpbiDest, DIB_RGB_COLORS, (void **)&pDestBits, NULL, NULL); if ((NULL == hDestDib) || (NULL == pDestBits)) { delete [] lpbiSrc; ::DeleteObject(hSrcDib); ::DeleteDC(hTempDC); return FALSE; } ::SelectObject (hTempDC, hDestDib); ::BitBlt (hTempDC, 0, 0, dwWidth, dwHeight, hDC, nDestX, nDestY, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); double src_darken; BYTE nAlpha; for (int pixel = 0; pixel < dwWidth * dwHeight; pixel++, pSrcBits++, pDestBits++) { nAlpha = LOBYTE(*pSrcBits >> 24); src_darken = (double) (nAlpha * ftn.SourceConstantAlpha) / 255.0 / 255.0; if( src_darken < 0.0 ) src_darken = 0.0; *pDestBits = PixelAlpha(*pSrcBits, src_darken, *pDestBits, 1.0 - src_darken); } //for ::SelectObject (hTempDC, hDestDib); ::BitBlt (hDC, nDestX, nDestY, dwWidth, dwHeight, hTempDC, 0, 0, SRCCOPY); ::SelectObject (hTempDC, hOldTempBmp); delete [] lpbiDest; ::DeleteObject(hDestDib); delete [] lpbiSrc; ::DeleteObject(hSrcDib); ::DeleteDC(hTempDC); return TRUE; } ///////////////////////////////////////////////////////////////////////////////////// // // bool DrawImage(HDC hDC, CPaintManagerUI* pManager, const RECT& rc, const RECT& rcPaint, const CDuiString& sImageName, \ const CDuiString& sImageResType, RECT rcItem, RECT rcBmpPart, RECT rcCorner, DWORD dwMask, BYTE bFade, \ bool bHole, bool bTiledX, bool bTiledY, HINSTANCE instance = NULL) { if (sImageName.IsEmpty()) { return false; } const TImageInfo* data = NULL; if( sImageResType.IsEmpty() ) { data = pManager->GetImageEx((LPCTSTR)sImageName, NULL, dwMask, false, instance); } else { data = pManager->GetImageEx((LPCTSTR)sImageName, (LPCTSTR)sImageResType, dwMask, false, instance); } if( !data ) return false; if( rcBmpPart.left == 0 && rcBmpPart.right == 0 && rcBmpPart.top == 0 && rcBmpPart.bottom == 0 ) { rcBmpPart.right = data->nX; rcBmpPart.bottom = data->nY; } if (rcBmpPart.right > data->nX) rcBmpPart.right = data->nX; if (rcBmpPart.bottom > data->nY) rcBmpPart.bottom = data->nY; RECT rcTemp; if( !::IntersectRect(&rcTemp, &rcItem, &rc) ) return true; if( !::IntersectRect(&rcTemp, &rcItem, &rcPaint) ) return true; CRenderEngine::DrawImage(hDC, data->hBitmap, rcItem, rcPaint, rcBmpPart, rcCorner, pManager->IsLayered() ? true : data->bAlpha, bFade, bHole, bTiledX, bTiledY); return true; } DWORD CRenderEngine::AdjustColor(DWORD dwColor, short H, short S, short L) { if( H == 180 && S == 100 && L == 100 ) return dwColor; float fH, fS, fL; float S1 = S / 100.0f; float L1 = L / 100.0f; RGBtoHSL(dwColor, &fH, &fS, &fL); fH += (H - 180); fH = fH > 0 ? fH : fH + 360; fS *= S1; fL *= L1; HSLtoRGB(&dwColor, fH, fS, fL); return dwColor; } TImageInfo* CRenderEngine::LoadImage(STRINGorID bitmap, LPCTSTR type, DWORD mask, HINSTANCE instance) { LPBYTE pData = NULL; DWORD dwSize = 0; do { if( type == NULL ) { CDuiString sFile = CPaintManagerUI::GetResourcePath(); if( CPaintManagerUI::GetResourceZip().IsEmpty() ) { sFile += bitmap.m_lpstr; HANDLE hFile = ::CreateFile(sFile.GetData(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, \ FILE_ATTRIBUTE_NORMAL, NULL); if( hFile == INVALID_HANDLE_VALUE ) break; dwSize = ::GetFileSize(hFile, NULL); if( dwSize == 0 ) break; DWORD dwRead = 0; pData = new BYTE[ dwSize ]; ::ReadFile( hFile, pData, dwSize, &dwRead, NULL ); ::CloseHandle( hFile ); if( dwRead != dwSize ) { delete[] pData; pData = NULL; break; } } else { sFile += CPaintManagerUI::GetResourceZip(); HZIP hz = NULL; if( CPaintManagerUI::IsCachedResourceZip() ) hz = (HZIP)CPaintManagerUI::GetResourceZipHandle(); else hz = OpenZip((void*)sFile.GetData(), 0, 2); if( hz == NULL ) break; ZIPENTRY ze; int i; if( FindZipItem(hz, bitmap.m_lpstr, true, &i, &ze) != 0 ) break; dwSize = ze.unc_size; if( dwSize == 0 ) break; pData = new BYTE[ dwSize ]; int res = UnzipItem(hz, i, pData, dwSize, 3); if( res != 0x00000000 && res != 0x00000600) { delete[] pData; pData = NULL; if( !CPaintManagerUI::IsCachedResourceZip() ) CloseZip(hz); break; } if( !CPaintManagerUI::IsCachedResourceZip() ) CloseZip(hz); } } else { HINSTANCE dllinstance = NULL; if (instance) { dllinstance = instance; } else { dllinstance = CPaintManagerUI::GetResourceDll(); } HRSRC hResource = ::FindResource(dllinstance, bitmap.m_lpstr, type); if( hResource == NULL ) break; HGLOBAL hGlobal = ::LoadResource(dllinstance, hResource); if( hGlobal == NULL ) { FreeResource(hResource); break; } dwSize = ::SizeofResource(dllinstance, hResource); if( dwSize == 0 ) break; pData = new BYTE[ dwSize ]; ::CopyMemory(pData, (LPBYTE)::LockResource(hGlobal), dwSize); ::FreeResource(hResource); } } while (0); while (!pData) { //读不到图片, 则直接去读取bitmap.m_lpstr指向的路径 HANDLE hFile = ::CreateFile(bitmap.m_lpstr, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, \ FILE_ATTRIBUTE_NORMAL, NULL); if( hFile == INVALID_HANDLE_VALUE ) break; dwSize = ::GetFileSize(hFile, NULL); if( dwSize == 0 ) break; DWORD dwRead = 0; pData = new BYTE[ dwSize ]; ::ReadFile( hFile, pData, dwSize, &dwRead, NULL ); ::CloseHandle( hFile ); if( dwRead != dwSize ) { delete[] pData; pData = NULL; } break; } if (!pData) { //::MessageBox(0, _T("读取图片数据失败!"), _T("抓BUG"), MB_OK); return NULL; } LPBYTE pImage = NULL; int x,y,n; pImage = stbi_load_from_memory(pData, dwSize, &x, &y, &n, 4); delete[] pData; if( !pImage ) { //::MessageBox(0, _T("解析图片失败"), _T("抓BUG"), MB_OK); return NULL; } BITMAPINFO bmi; ::ZeroMemory(&bmi, sizeof(BITMAPINFO)); bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = x; bmi.bmiHeader.biHeight = -y; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = x * y * 4; bool bAlphaChannel = false; LPBYTE pDest = NULL; HBITMAP hBitmap = ::CreateDIBSection(NULL, &bmi, DIB_RGB_COLORS, (void**)&pDest, NULL, 0); if( !hBitmap ) { //::MessageBox(0, _T("CreateDIBSection失败"), _T("抓BUG"), MB_OK); return NULL; } for( int i = 0; i < x * y; i++ ) { pDest[i*4 + 3] = pImage[i*4 + 3]; if( pDest[i*4 + 3] < 255 ) { pDest[i*4] = (BYTE)(DWORD(pImage[i*4 + 2])*pImage[i*4 + 3]/255); pDest[i*4 + 1] = (BYTE)(DWORD(pImage[i*4 + 1])*pImage[i*4 + 3]/255); pDest[i*4 + 2] = (BYTE)(DWORD(pImage[i*4])*pImage[i*4 + 3]/255); bAlphaChannel = true; } else { pDest[i*4] = pImage[i*4 + 2]; pDest[i*4 + 1] = pImage[i*4 + 1]; pDest[i*4 + 2] = pImage[i*4]; } if( *(DWORD*)(&pDest[i*4]) == mask ) { pDest[i*4] = (BYTE)0; pDest[i*4 + 1] = (BYTE)0; pDest[i*4 + 2] = (BYTE)0; pDest[i*4 + 3] = (BYTE)0; bAlphaChannel = true; } } stbi_image_free(pImage); TImageInfo* data = new TImageInfo; data->pBits = NULL; data->pSrcBits = NULL; data->hBitmap = hBitmap; data->nX = x; data->nY = y; data->bAlpha = bAlphaChannel; return data; } #ifdef USE_XIMAGE_EFFECT static DWORD LoadImage2Memory(const STRINGorID &bitmap, LPCTSTR type,LPBYTE &pData) { assert(pData == NULL); pData = NULL; DWORD dwSize(0U); do { if( type == NULL ) { CDuiString sFile = CPaintManagerUI::GetResourcePath(); if( CPaintManagerUI::GetResourceZip().IsEmpty() ) { sFile += bitmap.m_lpstr; HANDLE hFile = ::CreateFile(sFile.GetData(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, \ FILE_ATTRIBUTE_NORMAL, NULL); if( hFile == INVALID_HANDLE_VALUE ) break; dwSize = ::GetFileSize(hFile, NULL); if( dwSize == 0 ) break; DWORD dwRead = 0; pData = new BYTE[ dwSize + 1 ]; memset(pData,0,dwSize+1); ::ReadFile( hFile, pData, dwSize, &dwRead, NULL ); ::CloseHandle( hFile ); if( dwRead != dwSize ) { delete[] pData; pData = NULL; dwSize = 0U; break; } } else { sFile += CPaintManagerUI::GetResourceZip(); HZIP hz = NULL; if( CPaintManagerUI::IsCachedResourceZip() ) hz = (HZIP)CPaintManagerUI::GetResourceZipHandle(); else hz = OpenZip((void*)sFile.GetData(), 0, 2); if( hz == NULL ) break; ZIPENTRY ze; int i; if( FindZipItem(hz, bitmap.m_lpstr, true, &i, &ze) != 0 ) break; dwSize = ze.unc_size; if( dwSize == 0 ) break; pData = new BYTE[ dwSize ]; int res = UnzipItem(hz, i, pData, dwSize, 3); if( res != 0x00000000 && res != 0x00000600) { delete[] pData; pData = NULL; dwSize = 0U; if( !CPaintManagerUI::IsCachedResourceZip() ) CloseZip(hz); break; } if( !CPaintManagerUI::IsCachedResourceZip() ) CloseZip(hz); } } else { HINSTANCE hDll = CPaintManagerUI::GetResourceDll(); HRSRC hResource = ::FindResource(hDll, bitmap.m_lpstr, type); if( hResource == NULL ) break; HGLOBAL hGlobal = ::LoadResource(hDll, hResource); if( hGlobal == NULL ) { FreeResource(hResource); break; } dwSize = ::SizeofResource(hDll, hResource); if( dwSize == 0 ) break; pData = new BYTE[ dwSize ]; ::CopyMemory(pData, (LPBYTE)::LockResource(hGlobal), dwSize); ::FreeResource(hResource); } } while (0); while (!pData) { //读不到图片, 则直接去读取bitmap.m_lpstr指向的路径 HANDLE hFile = ::CreateFile(bitmap.m_lpstr, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, \ FILE_ATTRIBUTE_NORMAL, NULL); if( hFile == INVALID_HANDLE_VALUE ) break; dwSize = ::GetFileSize(hFile, NULL); if( dwSize == 0 ) break; DWORD dwRead = 0; pData = new BYTE[ dwSize ]; ::ReadFile( hFile, pData, dwSize, &dwRead, NULL ); ::CloseHandle( hFile ); if( dwRead != dwSize ) { delete[] pData; pData = NULL; dwSize = 0U; } break; } return dwSize; } CxImage* CRenderEngine::LoadGifImageX(STRINGorID bitmap, LPCTSTR type , DWORD mask) { //write by wangji LPBYTE pData = NULL; DWORD dwSize = LoadImage2Memory(bitmap,type,pData); if(dwSize == 0U || !pData) return NULL; CxImage * pImg = NULL; if(pImg = new CxImage()) { pImg->SetRetreiveAllFrames(TRUE); if(!pImg->Decode(pData,dwSize,CXIMAGE_FORMAT_GIF)) { delete pImg; pImg = nullptr; } } delete[] pData; pData = NULL; return pImg; } #endif//USE_XIMAGE_EFFECT void CRenderEngine::FreeImage(TImageInfo* bitmap, bool bDelete) { if (bitmap == NULL) return; if (bitmap->hBitmap) { ::DeleteObject(bitmap->hBitmap); } bitmap->hBitmap = NULL; if (bitmap->pBits) { delete[] bitmap->pBits; } bitmap->pBits = NULL; if (bitmap->pSrcBits) { delete[] bitmap->pSrcBits; } bitmap->pSrcBits = NULL; if (bDelete) { delete bitmap; bitmap = NULL; } } bool CRenderEngine::DrawIconImageString(HDC hDC, CPaintManagerUI* pManager, const RECT& rc, const RECT& rcPaint, LPCTSTR pStrImage, LPCTSTR pStrModify) { if ((pManager == NULL) || (hDC == NULL)) return false; // 1、aaa.jpg // 2、file='aaa.jpg' res='' restype='0' dest='0,0,0,0' source='0,0,0,0' corner='0,0,0,0' // mask='#FF0000' fade='255' hole='FALSE' xtiled='FALSE' ytiled='FALSE' CDuiString sImageName = pStrImage; CDuiString sImageResType; RECT rcItem = rc; RECT rcBmpPart = {0}; RECT rcCorner = {0}; DWORD dwMask = 0; BYTE bFade = 0xFF; bool bHole = false; bool bTiledX = true; bool bTiledY = true; CDuiSize szIcon(0,0); int image_count = 0; CDuiString sItem; CDuiString sValue; LPTSTR pstr = NULL; for( int i = 0; i < 2; ++i,image_count = 0 ) { if( i == 1) pStrImage = pStrModify; if( !pStrImage ) continue; while( *pStrImage != _T('\0') ) { sItem.Empty(); sValue.Empty(); while( *pStrImage > _T('\0') && *pStrImage <= _T(' ') ) pStrImage = ::CharNext(pStrImage); while( *pStrImage != _T('\0') && *pStrImage != _T('=') && *pStrImage > _T(' ') ) { LPTSTR pstrTemp = ::CharNext(pStrImage); while( pStrImage < pstrTemp) { sItem += *pStrImage++; } } while( *pStrImage > _T('\0') && *pStrImage <= _T(' ') ) pStrImage = ::CharNext(pStrImage); if( *pStrImage++ != _T('=') ) break; while( *pStrImage > _T('\0') && *pStrImage <= _T(' ') ) pStrImage = ::CharNext(pStrImage); if( *pStrImage++ != _T('\'') ) break; while( *pStrImage != _T('\0') && *pStrImage != _T('\'') ) { LPTSTR pstrTemp = ::CharNext(pStrImage); while( pStrImage < pstrTemp) { sValue += *pStrImage++; } } if( *pStrImage++ != _T('\'') ) break; if( !sValue.IsEmpty() ) { if( sItem == _T("file") || sItem == _T("res") ) { if( image_count > 0 ) DuiLib::DrawImage(hDC, pManager, rc, rcPaint, sImageName, sImageResType, rcItem, rcBmpPart, rcCorner, dwMask, bFade, bHole, bTiledX, bTiledY); sImageName = sValue; ++image_count; } else if( sItem == _T("restype") ) { if( image_count > 0 ) DuiLib::DrawImage(hDC, pManager, rc, rcPaint, sImageName, sImageResType, rcItem, rcBmpPart, rcCorner, dwMask, bFade, bHole, bTiledX, bTiledY); sImageResType = sValue; ++image_count; } else if( sItem == _T("dest") ) { rcItem.left = rc.left + _tcstol(sValue.GetData(), &pstr, 10); ASSERT(pstr); rcItem.top = rc.top + _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcItem.right = rc.left + _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); if (rcItem.right > rc.right) rcItem.right = rc.right; rcItem.bottom = rc.top + _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); if (rcItem.bottom > rc.bottom) rcItem.bottom = rc.bottom; } else if( sItem == _T("source") ) { rcBmpPart.left = _tcstol(sValue.GetData(), &pstr, 10); ASSERT(pstr); rcBmpPart.top = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcBmpPart.right = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcBmpPart.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); } else if( sItem == _T("corner") ) { rcCorner.left = _tcstol(sValue.GetData(), &pstr, 10); ASSERT(pstr); rcCorner.top = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcCorner.right = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcCorner.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); } else if( sItem == _T("mask") ) { if( sValue[0] == _T('#')) dwMask = _tcstoul(sValue.GetData() + 1, &pstr, 16); else dwMask = _tcstoul(sValue.GetData(), &pstr, 16); } else if( sItem == _T("fade") ) { bFade = (BYTE)_tcstoul(sValue.GetData(), &pstr, 10); } else if( sItem == _T("hole") ) { bHole = (_tcsicmp(sValue.GetData(), _T("TRUE")) == 0); } else if( sItem == _T("xtiled") ) { bTiledX = (_tcsicmp(sValue.GetData(), _T("TRUE")) == 0); } else if( sItem == _T("ytiled") ) { bTiledY = (_tcsicmp(sValue.GetData(), _T("TRUE")) == 0); } else if( sItem == _T("iconsize") ) { szIcon.cx = _tcstol(sValue.GetData(), &pstr, 10); ASSERT(pstr); szIcon.cy = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); } else if( sItem == _T("iconalign") ) { MakeFitIconDest(rcItem, szIcon, sValue, rcItem); } } if( *pStrImage++ != _T(' ') ) break; } } DuiLib::DrawImage(hDC, pManager, rc, rcPaint, sImageName, sImageResType, rcItem, rcBmpPart, rcCorner, dwMask, bFade, bHole, bTiledX, bTiledY); return true; } bool CRenderEngine::MakeFitIconDest(const RECT& rcControl,const CDuiSize& szIcon, const CDuiString& sAlign, RECT& rcDest) { ASSERT(!sAlign.IsEmpty()); if(sAlign == _T("left")) { rcDest.left = rcControl.left; rcDest.top = rcControl.top; rcDest.right = rcDest.left + szIcon.cx; rcDest.bottom = rcDest.top + szIcon.cy; } else if( sAlign == _T("center") ) { rcDest.left = rcControl.left + ((rcControl.right - rcControl.left) - szIcon.cx)/2; rcDest.top = rcControl.top + ((rcControl.bottom - rcControl.top) - szIcon.cy)/2; rcDest.right = rcDest.left + szIcon.cx; rcDest.bottom = rcDest.top + szIcon.cy; } else if( sAlign == _T("vcenter") ) { rcDest.left = rcControl.left; rcDest.top = rcControl.top + ((rcControl.bottom - rcControl.top) - szIcon.cy)/2; rcDest.right = rcDest.left + szIcon.cx; rcDest.bottom = rcDest.top + szIcon.cy; } else if( sAlign == _T("hcenter") ) { rcDest.left = rcControl.left + ((rcControl.right - rcControl.left) - szIcon.cx)/2; rcDest.top = rcControl.top; rcDest.right = rcDest.left + szIcon.cx; rcDest.bottom = rcDest.top + szIcon.cy; } if (rcDest.right > rcControl.right) rcDest.right = rcControl.right; if (rcDest.bottom > rcControl.bottom) rcDest.bottom = rcControl.bottom; return true; } TImageInfo* CRenderEngine::LoadImage(LPCTSTR pStrImage, LPCTSTR type, DWORD mask, HINSTANCE instance) { if(pStrImage == NULL) return NULL; CDuiString sStrPath = pStrImage; if( type == NULL ) { sStrPath = CResourceManager::GetInstance()->GetImagePath(pStrImage); if (sStrPath.IsEmpty()) sStrPath = pStrImage; else { /*if (CResourceManager::GetInstance()->GetScale() != 100) { CDuiString sScale; sScale.Format(_T("@%d."), CResourceManager::GetInstance()->GetScale()); sStrPath.Replace(_T("."), sScale); }*/ } } return LoadImage(STRINGorID(sStrPath.GetData()), type, mask, instance); } TImageInfo* CRenderEngine::LoadImage(UINT nID, LPCTSTR type, DWORD mask, HINSTANCE instance) { return LoadImage(STRINGorID(nID), type, mask, instance); } void CRenderEngine::DrawText(HDC hDC, CPaintManagerUI* pManager, RECT& rc, LPCTSTR pstrText,DWORD dwTextColor, \ int iFont, UINT uStyle, DWORD dwTextBKColor, BOOL bTransparent) { if( pstrText == NULL || pManager == NULL ) return; if(bTransparent) ::SetBkMode(hDC, TRANSPARENT); else ::SetBkMode(hDC, OPAQUE); ::SetBkColor(hDC, RGB(GetBValue(dwTextBKColor), GetGValue(dwTextBKColor), GetRValue(dwTextBKColor))); ::SetTextColor(hDC, RGB(GetBValue(dwTextColor), GetGValue(dwTextColor), GetRValue(dwTextColor))); HFONT hOldFont = (HFONT)::SelectObject(hDC, pManager->GetFont(iFont)); ::DrawText(hDC, pstrText, -1, &rc, uStyle | DT_NOPREFIX); ::SelectObject(hDC, hOldFont); } void CRenderEngine::DrawImage(HDC hDC, HBITMAP hBitmap, const RECT& rc, const RECT& rcPaint, const RECT& rcBmpPart, const RECT& rcCorners, bool bAlpha, BYTE uFade, bool hole, bool xtiled, bool ytiled) { ASSERT(::GetObjectType(hDC)==OBJ_DC || ::GetObjectType(hDC)==OBJ_MEMDC); typedef BOOL (WINAPI *LPALPHABLEND)(HDC, int, int, int, int,HDC, int, int, int, int, BLENDFUNCTION); static LPALPHABLEND lpAlphaBlend = (LPALPHABLEND) ::GetProcAddress(::GetModuleHandle(_T("msimg32.dll")), "AlphaBlend"); if( lpAlphaBlend == NULL ) lpAlphaBlend = AlphaBitBlt; if( hBitmap == NULL ) return; HDC hCloneDC = ::CreateCompatibleDC(hDC); HBITMAP hOldBitmap = (HBITMAP) ::SelectObject(hCloneDC, hBitmap); ::SetStretchBltMode(hDC, HALFTONE); RECT rcTemp = {0}; RECT rcDest = {0}; if( lpAlphaBlend && (bAlpha || uFade < 255) ) { BLENDFUNCTION bf = { AC_SRC_OVER, 0, uFade, AC_SRC_ALPHA }; // middle if( !hole ) { rcDest.left = rc.left + rcCorners.left; rcDest.top = rc.top + rcCorners.top; rcDest.right = rc.right - rc.left - rcCorners.left - rcCorners.right; rcDest.bottom = rc.bottom - rc.top - rcCorners.top - rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { if( !xtiled && !ytiled ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left + rcCorners.left, rcBmpPart.top + rcCorners.top, \ rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right, \ rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom, bf); } else if( xtiled && ytiled ) { LONG lWidth = rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right; LONG lHeight = rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom; int iTimesX = (rcDest.right - rcDest.left + lWidth - 1) / lWidth; int iTimesY = (rcDest.bottom - rcDest.top + lHeight - 1) / lHeight; for( int j = 0; j < iTimesY; ++j ) { LONG lDestTop = rcDest.top + lHeight * j; LONG lDestBottom = rcDest.top + lHeight * (j + 1); LONG lDrawHeight = lHeight; if( lDestBottom > rcDest.bottom ) { lDrawHeight -= lDestBottom - rcDest.bottom; lDestBottom = rcDest.bottom; } for( int i = 0; i < iTimesX; ++i ) { LONG lDestLeft = rcDest.left + lWidth * i; LONG lDestRight = rcDest.left + lWidth * (i + 1); LONG lDrawWidth = lWidth; if( lDestRight > rcDest.right ) { lDrawWidth -= lDestRight - rcDest.right; lDestRight = rcDest.right; } lpAlphaBlend(hDC, rcDest.left + lWidth * i, rcDest.top + lHeight * j, lDestRight - lDestLeft, lDestBottom - lDestTop, hCloneDC, rcBmpPart.left + rcCorners.left, rcBmpPart.top + rcCorners.top, lDrawWidth, lDrawHeight, bf); } } } else if( xtiled ) { LONG lWidth = rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right; int iTimes = (rcDest.right - rcDest.left + lWidth - 1) / lWidth; for( int i = 0; i < iTimes; ++i ) { LONG lDestLeft = rcDest.left + lWidth * i; LONG lDestRight = rcDest.left + lWidth * (i + 1); LONG lDrawWidth = lWidth; if( lDestRight > rcDest.right ) { lDrawWidth -= lDestRight - rcDest.right; lDestRight = rcDest.right; } lpAlphaBlend(hDC, lDestLeft, rcDest.top, lDestRight - lDestLeft, rcDest.bottom, hCloneDC, rcBmpPart.left + rcCorners.left, rcBmpPart.top + rcCorners.top, \ lDrawWidth, rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom, bf); } } else { // ytiled LONG lHeight = rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom; int iTimes = (rcDest.bottom - rcDest.top + lHeight - 1) / lHeight; for( int i = 0; i < iTimes; ++i ) { LONG lDestTop = rcDest.top + lHeight * i; LONG lDestBottom = rcDest.top + lHeight * (i + 1); LONG lDrawHeight = lHeight; if( lDestBottom > rcDest.bottom ) { lDrawHeight -= lDestBottom - rcDest.bottom; lDestBottom = rcDest.bottom; } lpAlphaBlend(hDC, rcDest.left, rcDest.top + lHeight * i, rcDest.right, lDestBottom - lDestTop, hCloneDC, rcBmpPart.left + rcCorners.left, rcBmpPart.top + rcCorners.top, \ rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right, lDrawHeight, bf); } } } } // left-top if( rcCorners.left > 0 && rcCorners.top > 0 ) { rcDest.left = rc.left; rcDest.top = rc.top; rcDest.right = rcCorners.left; rcDest.bottom = rcCorners.top; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left, rcBmpPart.top, rcCorners.left, rcCorners.top, bf); } } // top if( rcCorners.top > 0 ) { rcDest.left = rc.left + rcCorners.left; rcDest.top = rc.top; rcDest.right = rc.right - rc.left - rcCorners.left - rcCorners.right; rcDest.bottom = rcCorners.top; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left + rcCorners.left, rcBmpPart.top, rcBmpPart.right - rcBmpPart.left - \ rcCorners.left - rcCorners.right, rcCorners.top, bf); } } // right-top if( rcCorners.right > 0 && rcCorners.top > 0 ) { rcDest.left = rc.right - rcCorners.right; rcDest.top = rc.top; rcDest.right = rcCorners.right; rcDest.bottom = rcCorners.top; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.right - rcCorners.right, rcBmpPart.top, rcCorners.right, rcCorners.top, bf); } } // left if( rcCorners.left > 0 ) { rcDest.left = rc.left; rcDest.top = rc.top + rcCorners.top; rcDest.right = rcCorners.left; rcDest.bottom = rc.bottom - rc.top - rcCorners.top - rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left, rcBmpPart.top + rcCorners.top, rcCorners.left, rcBmpPart.bottom - \ rcBmpPart.top - rcCorners.top - rcCorners.bottom, bf); } } // right if( rcCorners.right > 0 ) { rcDest.left = rc.right - rcCorners.right; rcDest.top = rc.top + rcCorners.top; rcDest.right = rcCorners.right; rcDest.bottom = rc.bottom - rc.top - rcCorners.top - rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.right - rcCorners.right, rcBmpPart.top + rcCorners.top, rcCorners.right, \ rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom, bf); } } // left-bottom if( rcCorners.left > 0 && rcCorners.bottom > 0 ) { rcDest.left = rc.left; rcDest.top = rc.bottom - rcCorners.bottom; rcDest.right = rcCorners.left; rcDest.bottom = rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left, rcBmpPart.bottom - rcCorners.bottom, rcCorners.left, rcCorners.bottom, bf); } } // bottom if( rcCorners.bottom > 0 ) { rcDest.left = rc.left + rcCorners.left; rcDest.top = rc.bottom - rcCorners.bottom; rcDest.right = rc.right - rc.left - rcCorners.left - rcCorners.right; rcDest.bottom = rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left + rcCorners.left, rcBmpPart.bottom - rcCorners.bottom, \ rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right, rcCorners.bottom, bf); } } // right-bottom if( rcCorners.right > 0 && rcCorners.bottom > 0 ) { rcDest.left = rc.right - rcCorners.right; rcDest.top = rc.bottom - rcCorners.bottom; rcDest.right = rcCorners.right; rcDest.bottom = rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; lpAlphaBlend(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.right - rcCorners.right, rcBmpPart.bottom - rcCorners.bottom, rcCorners.right, \ rcCorners.bottom, bf); } } } else { if (rc.right - rc.left == rcBmpPart.right - rcBmpPart.left \ && rc.bottom - rc.top == rcBmpPart.bottom - rcBmpPart.top \ && rcCorners.left == 0 && rcCorners.right == 0 && rcCorners.top == 0 && rcCorners.bottom == 0) { if( ::IntersectRect(&rcTemp, &rcPaint, &rc) ) { ::BitBlt(hDC, rcTemp.left, rcTemp.top, rcTemp.right - rcTemp.left, rcTemp.bottom - rcTemp.top, \ hCloneDC, rcBmpPart.left + rcTemp.left - rc.left, rcBmpPart.top + rcTemp.top - rc.top, SRCCOPY); } } else { // middle if( !hole ) { rcDest.left = rc.left + rcCorners.left; rcDest.top = rc.top + rcCorners.top; rcDest.right = rc.right - rc.left - rcCorners.left - rcCorners.right; rcDest.bottom = rc.bottom - rc.top - rcCorners.top - rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { if( !xtiled && !ytiled ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left + rcCorners.left, rcBmpPart.top + rcCorners.top, \ rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right, \ rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom, SRCCOPY); } else if( xtiled && ytiled ) { LONG lWidth = rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right; LONG lHeight = rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom; int iTimesX = (rcDest.right - rcDest.left + lWidth - 1) / lWidth; int iTimesY = (rcDest.bottom - rcDest.top + lHeight - 1) / lHeight; for( int j = 0; j < iTimesY; ++j ) { LONG lDestTop = rcDest.top + lHeight * j; LONG lDestBottom = rcDest.top + lHeight * (j + 1); LONG lDrawHeight = lHeight; if( lDestBottom > rcDest.bottom ) { lDrawHeight -= lDestBottom - rcDest.bottom; lDestBottom = rcDest.bottom; } for( int i = 0; i < iTimesX; ++i ) { LONG lDestLeft = rcDest.left + lWidth * i; LONG lDestRight = rcDest.left + lWidth * (i + 1); LONG lDrawWidth = lWidth; if( lDestRight > rcDest.right ) { lDrawWidth -= lDestRight - rcDest.right; lDestRight = rcDest.right; } ::BitBlt(hDC, rcDest.left + lWidth * i, rcDest.top + lHeight * j, \ lDestRight - lDestLeft, lDestBottom - lDestTop, hCloneDC, \ rcBmpPart.left + rcCorners.left, rcBmpPart.top + rcCorners.top, SRCCOPY); } } } else if( xtiled ) { LONG lWidth = rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right; int iTimes = (rcDest.right - rcDest.left + lWidth - 1) / lWidth; for( int i = 0; i < iTimes; ++i ) { LONG lDestLeft = rcDest.left + lWidth * i; LONG lDestRight = rcDest.left + lWidth * (i + 1); LONG lDrawWidth = lWidth; if( lDestRight > rcDest.right ) { lDrawWidth -= lDestRight - rcDest.right; lDestRight = rcDest.right; } ::StretchBlt(hDC, lDestLeft, rcDest.top, lDestRight - lDestLeft, rcDest.bottom, hCloneDC, rcBmpPart.left + rcCorners.left, rcBmpPart.top + rcCorners.top, \ lDrawWidth, rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom, SRCCOPY); } } else { // ytiled LONG lHeight = rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom; int iTimes = (rcDest.bottom - rcDest.top + lHeight - 1) / lHeight; for( int i = 0; i < iTimes; ++i ) { LONG lDestTop = rcDest.top + lHeight * i; LONG lDestBottom = rcDest.top + lHeight * (i + 1); LONG lDrawHeight = lHeight; if( lDestBottom > rcDest.bottom ) { lDrawHeight -= lDestBottom - rcDest.bottom; lDestBottom = rcDest.bottom; } ::StretchBlt(hDC, rcDest.left, rcDest.top + lHeight * i, rcDest.right, lDestBottom - lDestTop, hCloneDC, rcBmpPart.left + rcCorners.left, rcBmpPart.top + rcCorners.top, \ rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right, lDrawHeight, SRCCOPY); } } } } // left-top if( rcCorners.left > 0 && rcCorners.top > 0 ) { rcDest.left = rc.left; rcDest.top = rc.top; rcDest.right = rcCorners.left; rcDest.bottom = rcCorners.top; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left, rcBmpPart.top, rcCorners.left, rcCorners.top, SRCCOPY); } } // top if( rcCorners.top > 0 ) { rcDest.left = rc.left + rcCorners.left; rcDest.top = rc.top; rcDest.right = rc.right - rc.left - rcCorners.left - rcCorners.right; rcDest.bottom = rcCorners.top; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left + rcCorners.left, rcBmpPart.top, rcBmpPart.right - rcBmpPart.left - \ rcCorners.left - rcCorners.right, rcCorners.top, SRCCOPY); } } // right-top if( rcCorners.right > 0 && rcCorners.top > 0 ) { rcDest.left = rc.right - rcCorners.right; rcDest.top = rc.top; rcDest.right = rcCorners.right; rcDest.bottom = rcCorners.top; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.right - rcCorners.right, rcBmpPart.top, rcCorners.right, rcCorners.top, SRCCOPY); } } // left if( rcCorners.left > 0 ) { rcDest.left = rc.left; rcDest.top = rc.top + rcCorners.top; rcDest.right = rcCorners.left; rcDest.bottom = rc.bottom - rc.top - rcCorners.top - rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left, rcBmpPart.top + rcCorners.top, rcCorners.left, rcBmpPart.bottom - \ rcBmpPart.top - rcCorners.top - rcCorners.bottom, SRCCOPY); } } // right if( rcCorners.right > 0 ) { rcDest.left = rc.right - rcCorners.right; rcDest.top = rc.top + rcCorners.top; rcDest.right = rcCorners.right; rcDest.bottom = rc.bottom - rc.top - rcCorners.top - rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.right - rcCorners.right, rcBmpPart.top + rcCorners.top, rcCorners.right, \ rcBmpPart.bottom - rcBmpPart.top - rcCorners.top - rcCorners.bottom, SRCCOPY); } } // left-bottom if( rcCorners.left > 0 && rcCorners.bottom > 0 ) { rcDest.left = rc.left; rcDest.top = rc.bottom - rcCorners.bottom; rcDest.right = rcCorners.left; rcDest.bottom = rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left, rcBmpPart.bottom - rcCorners.bottom, rcCorners.left, rcCorners.bottom, SRCCOPY); } } // bottom if( rcCorners.bottom > 0 ) { rcDest.left = rc.left + rcCorners.left; rcDest.top = rc.bottom - rcCorners.bottom; rcDest.right = rc.right - rc.left - rcCorners.left - rcCorners.right; rcDest.bottom = rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.left + rcCorners.left, rcBmpPart.bottom - rcCorners.bottom, \ rcBmpPart.right - rcBmpPart.left - rcCorners.left - rcCorners.right, rcCorners.bottom, SRCCOPY); } } // right-bottom if( rcCorners.right > 0 && rcCorners.bottom > 0 ) { rcDest.left = rc.right - rcCorners.right; rcDest.top = rc.bottom - rcCorners.bottom; rcDest.right = rcCorners.right; rcDest.bottom = rcCorners.bottom; rcDest.right += rcDest.left; rcDest.bottom += rcDest.top; if( ::IntersectRect(&rcTemp, &rcPaint, &rcDest) ) { rcDest.right -= rcDest.left; rcDest.bottom -= rcDest.top; ::StretchBlt(hDC, rcDest.left, rcDest.top, rcDest.right, rcDest.bottom, hCloneDC, \ rcBmpPart.right - rcCorners.right, rcBmpPart.bottom - rcCorners.bottom, rcCorners.right, \ rcCorners.bottom, SRCCOPY); } } } } ::SelectObject(hCloneDC, hOldBitmap); ::DeleteDC(hCloneDC); } bool CRenderEngine::DrawImageInfo(HDC hDC, CPaintManagerUI* pManager, const RECT& rcItem, const RECT& rcPaint, const TDrawInfo* pDrawInfo, HINSTANCE instance) { if( pManager == NULL || hDC == NULL || pDrawInfo == NULL ) return false; RECT rcDest = rcItem; if( pDrawInfo->rcDest.left != 0 || pDrawInfo->rcDest.top != 0 || pDrawInfo->rcDest.right != 0 || pDrawInfo->rcDest.bottom != 0 ) { rcDest.left = rcItem.left + pDrawInfo->rcDest.left; rcDest.top = rcItem.top + pDrawInfo->rcDest.top; rcDest.right = rcItem.left + pDrawInfo->rcDest.right; if( rcDest.right > rcItem.right ) rcDest.right = rcItem.right; rcDest.bottom = rcItem.top + pDrawInfo->rcDest.bottom; if( rcDest.bottom > rcItem.bottom ) rcDest.bottom = rcItem.bottom; } return DuiLib::DrawImage(hDC, pManager, rcItem, rcPaint, pDrawInfo->sImageName, pDrawInfo->sResType, rcDest,\ pDrawInfo->rcSource, pDrawInfo->rcCorner, pDrawInfo->dwMask, pDrawInfo->uFade, pDrawInfo->bHole, pDrawInfo->bTiledX, pDrawInfo->bTiledY, instance); } bool CRenderEngine::DrawImageString(HDC hDC, CPaintManagerUI* pManager, const RECT& rcItem, const RECT& rcPaint, LPCTSTR pStrImage, LPCTSTR pStrModify, HINSTANCE instance) { if ((pManager == NULL) || (hDC == NULL)) return false; const TDrawInfo* pDrawInfo = pManager->GetDrawInfo(pStrImage, pStrModify); return DrawImageInfo(hDC, pManager, rcItem, rcPaint, pDrawInfo, instance); } void CRenderEngine::DrawColor(HDC hDC, const RECT& rc, DWORD color) { if( color <= 0x00FFFFFF ) return; Gdiplus::Graphics graphics( hDC ); Gdiplus::SolidBrush brush(Gdiplus::Color((LOBYTE((color)>>24)), GetBValue(color), GetGValue(color), GetRValue(color))); graphics.FillRectangle(&brush, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top); } void CRenderEngine::DrawGradient(HDC hDC, const RECT& rc, DWORD dwFirst, DWORD dwSecond, bool bVertical, int nSteps) { typedef BOOL (WINAPI *LPALPHABLEND)(HDC, int, int, int, int,HDC, int, int, int, int, BLENDFUNCTION); static LPALPHABLEND lpAlphaBlend = (LPALPHABLEND) ::GetProcAddress(::GetModuleHandle(_T("msimg32.dll")), "AlphaBlend"); if( lpAlphaBlend == NULL ) lpAlphaBlend = AlphaBitBlt; typedef BOOL (WINAPI *PGradientFill)(HDC, PTRIVERTEX, ULONG, PVOID, ULONG, ULONG); static PGradientFill lpGradientFill = (PGradientFill) ::GetProcAddress(::GetModuleHandle(_T("msimg32.dll")), "GradientFill"); BYTE bAlpha = (BYTE)(((dwFirst >> 24) + (dwSecond >> 24)) >> 1); if( bAlpha == 0 ) return; int cx = rc.right - rc.left; int cy = rc.bottom - rc.top; RECT rcPaint = rc; HDC hPaintDC = hDC; HBITMAP hPaintBitmap = NULL; HBITMAP hOldPaintBitmap = NULL; if( bAlpha < 255 ) { rcPaint.left = rcPaint.top = 0; rcPaint.right = cx; rcPaint.bottom = cy; hPaintDC = ::CreateCompatibleDC(hDC); hPaintBitmap = ::CreateCompatibleBitmap(hDC, cx, cy); ASSERT(hPaintDC); ASSERT(hPaintBitmap); hOldPaintBitmap = (HBITMAP) ::SelectObject(hPaintDC, hPaintBitmap); } if( lpGradientFill != NULL ) { TRIVERTEX triv[2] = { { rcPaint.left, rcPaint.top, GetBValue(dwFirst) << 8, GetGValue(dwFirst) << 8, GetRValue(dwFirst) << 8, 0xFF00 }, { rcPaint.right, rcPaint.bottom, GetBValue(dwSecond) << 8, GetGValue(dwSecond) << 8, GetRValue(dwSecond) << 8, 0xFF00 } }; GRADIENT_RECT grc = { 0, 1 }; lpGradientFill(hPaintDC, triv, 2, &grc, 1, bVertical ? GRADIENT_FILL_RECT_V : GRADIENT_FILL_RECT_H); } else { // Determine how many shades int nShift = 1; if( nSteps >= 64 ) nShift = 6; else if( nSteps >= 32 ) nShift = 5; else if( nSteps >= 16 ) nShift = 4; else if( nSteps >= 8 ) nShift = 3; else if( nSteps >= 4 ) nShift = 2; int nLines = 1 << nShift; for( int i = 0; i < nLines; i++ ) { // Do a little alpha blending BYTE bR = (BYTE) ((GetBValue(dwSecond) * (nLines - i) + GetBValue(dwFirst) * i) >> nShift); BYTE bG = (BYTE) ((GetGValue(dwSecond) * (nLines - i) + GetGValue(dwFirst) * i) >> nShift); BYTE bB = (BYTE) ((GetRValue(dwSecond) * (nLines - i) + GetRValue(dwFirst) * i) >> nShift); // ... then paint with the resulting color HBRUSH hBrush = ::CreateSolidBrush(RGB(bR,bG,bB)); RECT r2 = rcPaint; if( bVertical ) { r2.bottom = rc.bottom - ((i * (rc.bottom - rc.top)) >> nShift); r2.top = rc.bottom - (((i + 1) * (rc.bottom - rc.top)) >> nShift); if( (r2.bottom - r2.top) > 0 ) ::FillRect(hDC, &r2, hBrush); } else { r2.left = rc.right - (((i + 1) * (rc.right - rc.left)) >> nShift); r2.right = rc.right - ((i * (rc.right - rc.left)) >> nShift); if( (r2.right - r2.left) > 0 ) ::FillRect(hPaintDC, &r2, hBrush); } ::DeleteObject(hBrush); } } if( bAlpha < 255 ) { BLENDFUNCTION bf = { AC_SRC_OVER, 0, bAlpha, AC_SRC_ALPHA }; lpAlphaBlend(hDC, rc.left, rc.top, cx, cy, hPaintDC, 0, 0, cx, cy, bf); ::SelectObject(hPaintDC, hOldPaintBitmap); ::DeleteObject(hPaintBitmap); ::DeleteDC(hPaintDC); } } void CRenderEngine::DrawLine( HDC hDC, const RECT& rc, int nSize, DWORD dwPenColor,int nStyle /*= PS_SOLID*/ ) { ASSERT(::GetObjectType(hDC)==OBJ_DC || ::GetObjectType(hDC)==OBJ_MEMDC); LOGPEN lg; lg.lopnColor = RGB(GetBValue(dwPenColor), GetGValue(dwPenColor), GetRValue(dwPenColor)); lg.lopnStyle = nStyle; lg.lopnWidth.x = nSize; HPEN hPen = CreatePenIndirect(&lg); HPEN hOldPen = (HPEN)::SelectObject(hDC, hPen); POINT ptTemp = { 0 }; ::MoveToEx(hDC, rc.left, rc.top, &ptTemp); ::LineTo(hDC, rc.right, rc.bottom); ::SelectObject(hDC, hOldPen); ::DeleteObject(hPen); } void CRenderEngine::DrawRect(HDC hDC, const RECT& rc, int nSize, DWORD dwPenColor,int nStyle /*= PS_SOLID*/) { #if USE_GDI_RENDER ASSERT(::GetObjectType(hDC) == OBJ_DC || ::GetObjectType(hDC) == OBJ_MEMDC); HPEN hPen = ::CreatePen(PS_SOLID | PS_INSIDEFRAME, nSize, RGB(GetBValue(dwPenColor), GetGValue(dwPenColor), GetRValue(dwPenColor))); HPEN hOldPen = (HPEN)::SelectObject(hDC, hPen); ::SelectObject(hDC, ::GetStockObject(HOLLOW_BRUSH)); ::Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom); ::SelectObject(hDC, hOldPen); ::DeleteObject(hPen); #else ASSERT(::GetObjectType(hDC) == OBJ_DC || ::GetObjectType(hDC) == OBJ_MEMDC); Gdiplus::Graphics graphics(hDC); Gdiplus::Pen pen(Gdiplus::Color(dwPenColor), (Gdiplus::REAL)nSize); pen.SetAlignment(Gdiplus::PenAlignmentInset); graphics.DrawRectangle(&pen, rc.left, rc.top, rc.right - rc.left - 1, rc.bottom - rc.top - 1); #endif } void CRenderEngine::DrawRoundRect(HDC hDC, const RECT& rc, int nSize, int width, int height, DWORD dwPenColor,int nStyle /*= PS_SOLID*/) { ASSERT(::GetObjectType(hDC)==OBJ_DC || ::GetObjectType(hDC)==OBJ_MEMDC); HPEN hPen = ::CreatePen(nStyle, nSize, RGB(GetBValue(dwPenColor), GetGValue(dwPenColor), GetRValue(dwPenColor))); HPEN hOldPen = (HPEN)::SelectObject(hDC, hPen); ::SelectObject(hDC, ::GetStockObject(HOLLOW_BRUSH)); ::RoundRect(hDC, rc.left, rc.top, rc.right, rc.bottom, width, height); ::SelectObject(hDC, hOldPen); ::DeleteObject(hPen); } void CRenderEngine::DrawText(HDC hDC, CPaintManagerUI* pManager, RECT& rc, LPCTSTR pstrText, DWORD dwTextColor, int iFont, UINT uStyle) { ASSERT(::GetObjectType(hDC)==OBJ_DC || ::GetObjectType(hDC)==OBJ_MEMDC); if( pstrText == NULL || pManager == NULL ) return; if ( pManager->IsLayered() || pManager->IsUseGdiplusText()) { HFONT hOldFont = (HFONT)::SelectObject(hDC, pManager->GetFont(iFont)); Gdiplus::Graphics graphics( hDC ); Gdiplus::Font font(hDC, pManager->GetFont(iFont)); Gdiplus::TextRenderingHint trh = Gdiplus::TextRenderingHintSystemDefault; switch(pManager->GetGdiplusTextRenderingHint()) { case 0: {trh = Gdiplus::TextRenderingHintSystemDefault; break;} case 1: {trh = Gdiplus::TextRenderingHintSingleBitPerPixelGridFit; break;} case 2: {trh = Gdiplus::TextRenderingHintSingleBitPerPixel; break;} case 3: {trh = Gdiplus::TextRenderingHintAntiAliasGridFit; break;} case 4: {trh = Gdiplus::TextRenderingHintAntiAlias; break;} case 5: {trh = Gdiplus::TextRenderingHintClearTypeGridFit; break;} } graphics.SetTextRenderingHint(trh); graphics.SetSmoothingMode(Gdiplus::SmoothingModeHighQuality); graphics.SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic); Gdiplus::RectF rectF((Gdiplus::REAL)rc.left, (Gdiplus::REAL)rc.top, (Gdiplus::REAL)(rc.right - rc.left), (Gdiplus::REAL)(rc.bottom - rc.top)); Gdiplus::SolidBrush brush(Gdiplus::Color(254, GetBValue(dwTextColor), GetGValue(dwTextColor), GetRValue(dwTextColor))); Gdiplus::StringFormat stringFormat = Gdiplus::StringFormat::GenericTypographic(); if ((uStyle & DT_END_ELLIPSIS) != 0) { stringFormat.SetTrimming(Gdiplus::StringTrimmingEllipsisCharacter); } int formatFlags = 0; if ((uStyle & DT_NOCLIP) != 0) { formatFlags |= Gdiplus::StringFormatFlagsNoClip; } if ((uStyle & DT_SINGLELINE) != 0) { formatFlags |= Gdiplus::StringFormatFlagsNoWrap; } stringFormat.SetFormatFlags(formatFlags); if ((uStyle & DT_LEFT) != 0) { stringFormat.SetAlignment(Gdiplus::StringAlignmentNear); } else if ((uStyle & DT_CENTER) != 0) { stringFormat.SetAlignment(Gdiplus::StringAlignmentCenter); } else if ((uStyle & DT_RIGHT) != 0) { stringFormat.SetAlignment(Gdiplus::StringAlignmentFar); } else { stringFormat.SetAlignment(Gdiplus::StringAlignmentNear); } stringFormat.GenericTypographic(); if ((uStyle & DT_TOP) != 0) { stringFormat.SetLineAlignment(Gdiplus::StringAlignmentNear); } else if ((uStyle & DT_VCENTER) != 0) { stringFormat.SetLineAlignment(Gdiplus::StringAlignmentCenter); } else if ((uStyle & DT_BOTTOM) != 0) { stringFormat.SetLineAlignment(Gdiplus::StringAlignmentFar); } else { stringFormat.SetLineAlignment(Gdiplus::StringAlignmentNear); } #ifdef UNICODE if ((uStyle & DT_CALCRECT) != 0) { Gdiplus::RectF bounds; graphics.MeasureString(pstrText, -1, &font, rectF, &stringFormat, &bounds); // MeasureString存在计算误差,这里加一像素 rc.bottom = rc.top + (long)bounds.Height + 1; rc.right = rc.left + (long)bounds.Width + 1; } else { graphics.DrawString(pstrText, -1, &font, rectF, &stringFormat, &brush); } #else DWORD dwSize = MultiByteToWideChar(CP_ACP, 0, pstrText, -1, NULL, 0); WCHAR * pcwszDest = new WCHAR[dwSize + 1]; memset(pcwszDest, 0, (dwSize + 1) * sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, NULL, pstrText, -1, pcwszDest, dwSize); if(pcwszDest != NULL) { if ((uStyle & DT_CALCRECT) != 0) { Gdiplus::RectF bounds; graphics.MeasureString(pcwszDest, -1, &font, rectF, &stringFormat, &bounds); rc.bottom = rc.top + (long)(bounds.Height * 1.06); rc.right = rc.left + (long)(bounds.Width * 1.06); } else { graphics.DrawString(pcwszDest, -1, &font, rectF, &stringFormat, &brush); } delete []pcwszDest; } #endif ::SelectObject(hDC, hOldFont); } else { ::SetBkMode(hDC, TRANSPARENT); ::SetTextColor(hDC, RGB(GetBValue(dwTextColor), GetGValue(dwTextColor), GetRValue(dwTextColor))); HFONT hOldFont = (HFONT)::SelectObject(hDC, pManager->GetFont(iFont)); ::DrawText(hDC, pstrText, -1, &rc, uStyle); ::SelectObject(hDC, hOldFont); } } void CRenderEngine::DrawHtmlText(HDC hDC, CPaintManagerUI* pManager, RECT& rc, LPCTSTR pstrText, DWORD dwTextColor, RECT* prcLinks, CDuiString* sLinks, int& nLinkRects, UINT uStyle) { // 考虑到在xml编辑器中使用<>符号不方便,可以使用{}符号代替 // 支持标签嵌套(如<l><b>text</b></l>),但是交叉嵌套是应该避免的(如<l><b>text</l></b>) // The string formatter supports a kind of "mini-html" that consists of various short tags: // // Bold: <b>text</b> // Color: <c #xxxxxx>text</c> where x = RGB in hex // Font: <f x>text</f> where x = font id // Italic: <i>text</i> // Image: <i x y z> where x = image name and y = imagelist num and z(optional) = imagelist id // Link: <a x>text</a> where x(optional) = link content, normal like app:notepad or http:www.xxx.com // NewLine <n> // Paragraph: <p x>text</p> where x = extra pixels indent in p // Raw Text: <r>text</r> // Selected: <s>text</s> // Underline: <u>text</u> // X Indent: <x i> where i = hor indent in pixels // Y Indent: <y i> where i = ver indent in pixels ASSERT(::GetObjectType(hDC)==OBJ_DC || ::GetObjectType(hDC)==OBJ_MEMDC); if( pstrText == NULL || pManager == NULL ) return; if( ::IsRectEmpty(&rc) ) return; bool bDraw = (uStyle & DT_CALCRECT) == 0; CStdPtrArray aFontArray(10); CStdPtrArray aColorArray(10); CStdPtrArray aPIndentArray(10); RECT rcClip = { 0 }; ::GetClipBox(hDC, &rcClip); HRGN hOldRgn = ::CreateRectRgnIndirect(&rcClip); HRGN hRgn = ::CreateRectRgnIndirect(&rc); if( bDraw ) ::ExtSelectClipRgn(hDC, hRgn, RGN_AND); TEXTMETRIC* pTm = &pManager->GetDefaultFontInfo()->tm; HFONT hOldFont = (HFONT) ::SelectObject(hDC, pManager->GetDefaultFontInfo()->hFont); ::SetBkMode(hDC, TRANSPARENT); ::SetTextColor(hDC, RGB(GetBValue(dwTextColor), GetGValue(dwTextColor), GetRValue(dwTextColor))); DWORD dwBkColor = pManager->GetDefaultSelectedBkColor(); ::SetBkColor(hDC, RGB(GetBValue(dwBkColor), GetGValue(dwBkColor), GetRValue(dwBkColor))); // If the drawstyle include a alignment, we'll need to first determine the text-size so // we can draw it at the correct position... if( ((uStyle & DT_CENTER) != 0 || (uStyle & DT_RIGHT) != 0 || (uStyle & DT_VCENTER) != 0 || (uStyle & DT_BOTTOM) != 0) && (uStyle & DT_CALCRECT) == 0 ) { RECT rcText = { 0, 0, 9999, 100 }; int nLinks = 0; DrawHtmlText(hDC, pManager, rcText, pstrText, dwTextColor, NULL, NULL, nLinks, uStyle | DT_CALCRECT); if( (uStyle & DT_SINGLELINE) != 0 ){ if( (uStyle & DT_CENTER) != 0 ) { rc.left = rc.left + ((rc.right - rc.left) / 2) - ((rcText.right - rcText.left) / 2); rc.right = rc.left + (rcText.right - rcText.left); } if( (uStyle & DT_RIGHT) != 0 ) { rc.left = rc.right - (rcText.right - rcText.left); } } if( (uStyle & DT_VCENTER) != 0 ) { rc.top = rc.top + ((rc.bottom - rc.top) / 2) - ((rcText.bottom - rcText.top) / 2); rc.bottom = rc.top + (rcText.bottom - rcText.top); } if( (uStyle & DT_BOTTOM) != 0 ) { rc.top = rc.bottom - (rcText.bottom - rcText.top); } } bool bHoverLink = false; CDuiString sHoverLink; POINT ptMouse = pManager->GetMousePos(); for( int i = 0; !bHoverLink && i < nLinkRects; i++ ) { if( ::PtInRect(prcLinks + i, ptMouse) ) { sHoverLink = *(CDuiString*)(sLinks + i); bHoverLink = true; } } POINT pt = { rc.left, rc.top }; int iLinkIndex = 0; int cyLine = pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1); int cyMinHeight = 0; int cxMaxWidth = 0; POINT ptLinkStart = { 0 }; bool bLineEnd = false; bool bInRaw = false; bool bInLink = false; bool bInSelected = false; int iLineLinkIndex = 0; // 排版习惯是图文底部对齐,所以每行绘制都要分两步,先计算高度,再绘制 CStdPtrArray aLineFontArray; CStdPtrArray aLineColorArray; CStdPtrArray aLinePIndentArray; LPCTSTR pstrLineBegin = pstrText; bool bLineInRaw = false; bool bLineInLink = false; bool bLineInSelected = false; int cyLineHeight = 0; bool bLineDraw = false; // 行的第二阶段:绘制 while( *pstrText != _T('\0') ) { if( pt.x >= rc.right || *pstrText == _T('\n') || bLineEnd ) { if( *pstrText == _T('\n') ) pstrText++; if( bLineEnd ) bLineEnd = false; if( !bLineDraw ) { if( bInLink && iLinkIndex < nLinkRects ) { ::SetRect(&prcLinks[iLinkIndex++], ptLinkStart.x, ptLinkStart.y, MIN(pt.x, rc.right), pt.y + cyLine); CDuiString *pStr1 = (CDuiString*)(sLinks + iLinkIndex - 1); CDuiString *pStr2 = (CDuiString*)(sLinks + iLinkIndex); *pStr2 = *pStr1; } for( int i = iLineLinkIndex; i < iLinkIndex; i++ ) { prcLinks[i].bottom = pt.y + cyLine; } if( bDraw ) { bInLink = bLineInLink; iLinkIndex = iLineLinkIndex; } } else { if( bInLink && iLinkIndex < nLinkRects ) iLinkIndex++; bLineInLink = bInLink; iLineLinkIndex = iLinkIndex; } if( (uStyle & DT_SINGLELINE) != 0 && (!bDraw || bLineDraw) ) break; if( bDraw ) bLineDraw = !bLineDraw; // ! pt.x = rc.left; if( !bLineDraw ) pt.y += cyLine; if( pt.y > rc.bottom && bDraw ) break; ptLinkStart = pt; cyLine = pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1); if( pt.x >= rc.right ) break; } else if( !bInRaw && ( *pstrText == _T('<') || *pstrText == _T('{') ) && ( pstrText[1] >= _T('a') && pstrText[1] <= _T('z') ) && ( pstrText[2] == _T(' ') || pstrText[2] == _T('>') || pstrText[2] == _T('}') ) ) { pstrText++; LPCTSTR pstrNextStart = NULL; switch( *pstrText ) { case _T('a'): // Link { pstrText++; while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); if( iLinkIndex < nLinkRects && !bLineDraw ) { CDuiString *pStr = (CDuiString*)(sLinks + iLinkIndex); pStr->Empty(); while( *pstrText != _T('\0') && *pstrText != _T('>') && *pstrText != _T('}') ) { LPCTSTR pstrTemp = ::CharNext(pstrText); while( pstrText < pstrTemp) { *pStr += *pstrText++; } } } DWORD clrColor = dwTextColor; if(clrColor == 0) pManager->GetDefaultLinkFontColor(); if( bHoverLink && iLinkIndex < nLinkRects ) { CDuiString *pStr = (CDuiString*)(sLinks + iLinkIndex); if( sHoverLink == *pStr ) clrColor = pManager->GetDefaultLinkHoverFontColor(); } //else if( prcLinks == NULL ) { // if( ::PtInRect(&rc, ptMouse) ) // clrColor = pManager->GetDefaultLinkHoverFontColor(); //} aColorArray.Add((LPVOID)clrColor); ::SetTextColor(hDC, RGB(GetBValue(clrColor), GetGValue(clrColor), GetRValue(clrColor))); TFontInfo* pFontInfo = pManager->GetDefaultFontInfo(); if( aFontArray.GetSize() > 0 ) pFontInfo = (TFontInfo*)aFontArray.GetAt(aFontArray.GetSize() - 1); if( pFontInfo->bUnderline == false ) { HFONT hFont = pManager->GetFont(pFontInfo->sFontName, pFontInfo->iSize, pFontInfo->bBold, true, pFontInfo->bItalic); if( hFont == NULL ) hFont = pManager->AddFont(g_iFontID, pFontInfo->sFontName, pFontInfo->iSize, pFontInfo->bBold, true, pFontInfo->bItalic); pFontInfo = pManager->GetFontInfo(hFont); aFontArray.Add(pFontInfo); pTm = &pFontInfo->tm; ::SelectObject(hDC, pFontInfo->hFont); cyLine = MAX(cyLine, pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1)); } ptLinkStart = pt; bInLink = true; } break; case _T('b'): // Bold { pstrText++; TFontInfo* pFontInfo = pManager->GetDefaultFontInfo(); if( aFontArray.GetSize() > 0 ) pFontInfo = (TFontInfo*)aFontArray.GetAt(aFontArray.GetSize() - 1); if( pFontInfo->bBold == false ) { HFONT hFont = pManager->GetFont(pFontInfo->sFontName, pFontInfo->iSize, true, pFontInfo->bUnderline, pFontInfo->bItalic); if( hFont == NULL ) hFont = pManager->AddFont(g_iFontID, pFontInfo->sFontName, pFontInfo->iSize, true, pFontInfo->bUnderline, pFontInfo->bItalic); pFontInfo = pManager->GetFontInfo(hFont); aFontArray.Add(pFontInfo); pTm = &pFontInfo->tm; ::SelectObject(hDC, pFontInfo->hFont); cyLine = MAX(cyLine, pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1)); } } break; case _T('c'): // Color { pstrText++; while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); if( *pstrText == _T('#')) pstrText++; DWORD clrColor = _tcstol(pstrText, const_cast<LPTSTR*>(&pstrText), 16); aColorArray.Add((LPVOID)clrColor); ::SetTextColor(hDC, RGB(GetBValue(clrColor), GetGValue(clrColor), GetRValue(clrColor))); } break; case _T('f'): // Font { pstrText++; while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); LPCTSTR pstrTemp = pstrText; int iFont = (int) _tcstol(pstrText, const_cast<LPTSTR*>(&pstrText), 10); //if( isdigit(*pstrText) ) { // debug版本会引起异常 if( pstrTemp != pstrText ) { TFontInfo* pFontInfo = pManager->GetFontInfo(iFont); aFontArray.Add(pFontInfo); pTm = &pFontInfo->tm; ::SelectObject(hDC, pFontInfo->hFont); } else { CDuiString sFontName; int iFontSize = 10; CDuiString sFontAttr; bool bBold = false; bool bUnderline = false; bool bItalic = false; while( *pstrText != _T('\0') && *pstrText != _T('>') && *pstrText != _T('}') && *pstrText != _T(' ') ) { pstrTemp = ::CharNext(pstrText); while( pstrText < pstrTemp) { sFontName += *pstrText++; } } while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); if( isdigit(*pstrText) ) { iFontSize = (int) _tcstol(pstrText, const_cast<LPTSTR*>(&pstrText), 10); } while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); while( *pstrText != _T('\0') && *pstrText != _T('>') && *pstrText != _T('}') ) { pstrTemp = ::CharNext(pstrText); while( pstrText < pstrTemp) { sFontAttr += *pstrText++; } } sFontAttr.MakeLower(); if( sFontAttr.Find(_T("bold")) >= 0 ) bBold = true; if( sFontAttr.Find(_T("underline")) >= 0 ) bUnderline = true; if( sFontAttr.Find(_T("italic")) >= 0 ) bItalic = true; HFONT hFont = pManager->GetFont(sFontName, iFontSize, bBold, bUnderline, bItalic); if( hFont == NULL ) hFont = pManager->AddFont(g_iFontID, sFontName, iFontSize, bBold, bUnderline, bItalic); TFontInfo* pFontInfo = pManager->GetFontInfo(hFont); aFontArray.Add(pFontInfo); pTm = &pFontInfo->tm; ::SelectObject(hDC, pFontInfo->hFont); } cyLine = MAX(cyLine, pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1)); } break; case _T('i'): // Italic or Image { pstrNextStart = pstrText - 1; pstrText++; CDuiString sImageString = pstrText; int iWidth = 0; int iHeight = 0; while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); const TImageInfo* pImageInfo = NULL; CDuiString sName; while( *pstrText != _T('\0') && *pstrText != _T('>') && *pstrText != _T('}') && *pstrText != _T(' ') ) { LPCTSTR pstrTemp = ::CharNext(pstrText); while( pstrText < pstrTemp) { sName += *pstrText++; } } if( sName.IsEmpty() ) { // Italic pstrNextStart = NULL; TFontInfo* pFontInfo = pManager->GetDefaultFontInfo(); if( aFontArray.GetSize() > 0 ) pFontInfo = (TFontInfo*)aFontArray.GetAt(aFontArray.GetSize() - 1); if( pFontInfo->bItalic == false ) { HFONT hFont = pManager->GetFont(pFontInfo->sFontName, pFontInfo->iSize, pFontInfo->bBold, pFontInfo->bUnderline, true); if( hFont == NULL ) hFont = pManager->AddFont(g_iFontID, pFontInfo->sFontName, pFontInfo->iSize, pFontInfo->bBold, pFontInfo->bUnderline, true); pFontInfo = pManager->GetFontInfo(hFont); aFontArray.Add(pFontInfo); pTm = &pFontInfo->tm; ::SelectObject(hDC, pFontInfo->hFont); cyLine = MAX(cyLine, pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1)); } } else { while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); int iImageListNum = (int) _tcstol(pstrText, const_cast<LPTSTR*>(&pstrText), 10); if( iImageListNum <= 0 ) iImageListNum = 1; while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); int iImageListIndex = (int) _tcstol(pstrText, const_cast<LPTSTR*>(&pstrText), 10); if( iImageListIndex < 0 || iImageListIndex >= iImageListNum ) iImageListIndex = 0; if( _tcsstr(sImageString.GetData(), _T("file=\'")) != NULL || _tcsstr(sImageString.GetData(), _T("res=\'")) != NULL ) { CDuiString sImageResType; CDuiString sImageName; LPCTSTR pStrImage = sImageString.GetData(); CDuiString sItem; CDuiString sValue; while( *pStrImage != _T('\0') ) { sItem.Empty(); sValue.Empty(); while( *pStrImage > _T('\0') && *pStrImage <= _T(' ') ) pStrImage = ::CharNext(pStrImage); while( *pStrImage != _T('\0') && *pStrImage != _T('=') && *pStrImage > _T(' ') ) { LPTSTR pstrTemp = ::CharNext(pStrImage); while( pStrImage < pstrTemp) { sItem += *pStrImage++; } } while( *pStrImage > _T('\0') && *pStrImage <= _T(' ') ) pStrImage = ::CharNext(pStrImage); if( *pStrImage++ != _T('=') ) break; while( *pStrImage > _T('\0') && *pStrImage <= _T(' ') ) pStrImage = ::CharNext(pStrImage); if( *pStrImage++ != _T('\'') ) break; while( *pStrImage != _T('\0') && *pStrImage != _T('\'') ) { LPTSTR pstrTemp = ::CharNext(pStrImage); while( pStrImage < pstrTemp) { sValue += *pStrImage++; } } if( *pStrImage++ != _T('\'') ) break; if( !sValue.IsEmpty() ) { if( sItem == _T("file") || sItem == _T("res") ) { sImageName = sValue; } else if( sItem == _T("restype") ) { sImageResType = sValue; } } if( *pStrImage++ != _T(' ') ) break; } pImageInfo = pManager->GetImageEx((LPCTSTR)sImageName, sImageResType); } else pImageInfo = pManager->GetImageEx((LPCTSTR)sName); if( pImageInfo ) { iWidth = pImageInfo->nX; iHeight = pImageInfo->nY; if( iImageListNum > 1 ) iWidth /= iImageListNum; if( pt.x + iWidth > rc.right && pt.x > rc.left && (uStyle & DT_SINGLELINE) == 0 ) { bLineEnd = true; } else { pstrNextStart = NULL; if( bDraw && bLineDraw ) { CDuiRect rcImage(pt.x, pt.y + cyLineHeight - iHeight, pt.x + iWidth, pt.y + cyLineHeight); if( iHeight < cyLineHeight ) { rcImage.bottom -= (cyLineHeight - iHeight) / 2; rcImage.top = rcImage.bottom - iHeight; } CDuiRect rcBmpPart(0, 0, iWidth, iHeight); rcBmpPart.left = iWidth * iImageListIndex; rcBmpPart.right = iWidth * (iImageListIndex + 1); CDuiRect rcCorner(0, 0, 0, 0); DrawImage(hDC, pImageInfo->hBitmap, rcImage, rcImage, rcBmpPart, rcCorner, \ pImageInfo->bAlpha, 255); } cyLine = MAX(iHeight, cyLine); pt.x += iWidth; cyMinHeight = pt.y + iHeight; cxMaxWidth = MAX(cxMaxWidth, pt.x); } } else pstrNextStart = NULL; } } break; case _T('n'): // Newline { pstrText++; if( (uStyle & DT_SINGLELINE) != 0 ) break; bLineEnd = true; } break; case _T('p'): // Paragraph { pstrText++; if( pt.x > rc.left ) bLineEnd = true; while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); int cyLineExtra = (int)_tcstol(pstrText, const_cast<LPTSTR*>(&pstrText), 10); aPIndentArray.Add((LPVOID)cyLineExtra); cyLine = MAX(cyLine, pTm->tmHeight + pTm->tmExternalLeading + cyLineExtra); } break; case _T('r'): // Raw Text { pstrText++; bInRaw = true; } break; case _T('s'): // Selected text background color { pstrText++; bInSelected = !bInSelected; if( bDraw && bLineDraw ) { if( bInSelected ) ::SetBkMode(hDC, OPAQUE); else ::SetBkMode(hDC, TRANSPARENT); } } break; case _T('u'): // Underline text { pstrText++; TFontInfo* pFontInfo = pManager->GetDefaultFontInfo(); if( aFontArray.GetSize() > 0 ) pFontInfo = (TFontInfo*)aFontArray.GetAt(aFontArray.GetSize() - 1); if( pFontInfo->bUnderline == false ) { HFONT hFont = pManager->GetFont(pFontInfo->sFontName, pFontInfo->iSize, pFontInfo->bBold, true, pFontInfo->bItalic); if( hFont == NULL ) hFont = pManager->AddFont(g_iFontID, pFontInfo->sFontName, pFontInfo->iSize, pFontInfo->bBold, true, pFontInfo->bItalic); pFontInfo = pManager->GetFontInfo(hFont); aFontArray.Add(pFontInfo); pTm = &pFontInfo->tm; ::SelectObject(hDC, pFontInfo->hFont); cyLine = MAX(cyLine, pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1)); } } break; case _T('x'): // X Indent { pstrText++; while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); int iWidth = (int) _tcstol(pstrText, const_cast<LPTSTR*>(&pstrText), 10); pt.x += iWidth; cxMaxWidth = MAX(cxMaxWidth, pt.x); } break; case _T('y'): // Y Indent { pstrText++; while( *pstrText > _T('\0') && *pstrText <= _T(' ') ) pstrText = ::CharNext(pstrText); cyLine = (int) _tcstol(pstrText, const_cast<LPTSTR*>(&pstrText), 10); } break; } if( pstrNextStart != NULL ) pstrText = pstrNextStart; else { while( *pstrText != _T('\0') && *pstrText != _T('>') && *pstrText != _T('}') ) pstrText = ::CharNext(pstrText); pstrText = ::CharNext(pstrText); } } else if( !bInRaw && ( *pstrText == _T('<') || *pstrText == _T('{') ) && pstrText[1] == _T('/') ) { pstrText++; pstrText++; switch( *pstrText ) { case _T('c'): { pstrText++; aColorArray.Remove(aColorArray.GetSize() - 1); DWORD clrColor = dwTextColor; if( aColorArray.GetSize() > 0 ) clrColor = (int)aColorArray.GetAt(aColorArray.GetSize() - 1); ::SetTextColor(hDC, RGB(GetBValue(clrColor), GetGValue(clrColor), GetRValue(clrColor))); } break; case _T('p'): pstrText++; if( pt.x > rc.left ) bLineEnd = true; aPIndentArray.Remove(aPIndentArray.GetSize() - 1); cyLine = MAX(cyLine, pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1)); break; case _T('s'): { pstrText++; bInSelected = !bInSelected; if( bDraw && bLineDraw ) { if( bInSelected ) ::SetBkMode(hDC, OPAQUE); else ::SetBkMode(hDC, TRANSPARENT); } } break; case _T('a'): { if( iLinkIndex < nLinkRects ) { if( !bLineDraw ) ::SetRect(&prcLinks[iLinkIndex], ptLinkStart.x, ptLinkStart.y, MIN(pt.x, rc.right), pt.y + pTm->tmHeight + pTm->tmExternalLeading); iLinkIndex++; } aColorArray.Remove(aColorArray.GetSize() - 1); DWORD clrColor = dwTextColor; if( aColorArray.GetSize() > 0 ) clrColor = (int)aColorArray.GetAt(aColorArray.GetSize() - 1); ::SetTextColor(hDC, RGB(GetBValue(clrColor), GetGValue(clrColor), GetRValue(clrColor))); bInLink = false; } case _T('b'): case _T('f'): case _T('i'): case _T('u'): { pstrText++; aFontArray.Remove(aFontArray.GetSize() - 1); TFontInfo* pFontInfo = (TFontInfo*)aFontArray.GetAt(aFontArray.GetSize() - 1); if( pFontInfo == NULL ) pFontInfo = pManager->GetDefaultFontInfo(); if( pTm->tmItalic && pFontInfo->bItalic == false ) { ABC abc; ::GetCharABCWidths(hDC, _T(' '), _T(' '), &abc); pt.x += abc.abcC / 2; // 简单修正一下斜体混排的问题, 正确做法应该是http://support.microsoft.com/kb/244798/en-us } pTm = &pFontInfo->tm; ::SelectObject(hDC, pFontInfo->hFont); cyLine = MAX(cyLine, pTm->tmHeight + pTm->tmExternalLeading + (int)aPIndentArray.GetAt(aPIndentArray.GetSize() - 1)); } break; } while( *pstrText != _T('\0') && *pstrText != _T('>') && *pstrText != _T('}') ) pstrText = ::CharNext(pstrText); pstrText = ::CharNext(pstrText); } else if( !bInRaw && *pstrText == _T('<') && pstrText[2] == _T('>') && (pstrText[1] == _T('{') || pstrText[1] == _T('}')) ) { SIZE szSpace = { 0 }; ::GetTextExtentPoint32(hDC, &pstrText[1], 1, &szSpace); if( bDraw && bLineDraw ) ::TextOut(hDC, pt.x, pt.y + cyLineHeight - pTm->tmHeight - pTm->tmExternalLeading, &pstrText[1], 1); pt.x += szSpace.cx; cxMaxWidth = MAX(cxMaxWidth, pt.x); pstrText++;pstrText++;pstrText++; } else if( !bInRaw && *pstrText == _T('{') && pstrText[2] == _T('}') && (pstrText[1] == _T('<') || pstrText[1] == _T('>')) ) { SIZE szSpace = { 0 }; ::GetTextExtentPoint32(hDC, &pstrText[1], 1, &szSpace); if( bDraw && bLineDraw ) ::TextOut(hDC, pt.x, pt.y + cyLineHeight - pTm->tmHeight - pTm->tmExternalLeading, &pstrText[1], 1); pt.x += szSpace.cx; cxMaxWidth = MAX(cxMaxWidth, pt.x); pstrText++;pstrText++;pstrText++; } else if( !bInRaw && *pstrText == _T(' ') ) { SIZE szSpace = { 0 }; ::GetTextExtentPoint32(hDC, _T(" "), 1, &szSpace); // Still need to paint the space because the font might have // underline formatting. if( bDraw && bLineDraw ) ::TextOut(hDC, pt.x, pt.y + cyLineHeight - pTm->tmHeight - pTm->tmExternalLeading, _T(" "), 1); pt.x += szSpace.cx; cxMaxWidth = MAX(cxMaxWidth, pt.x); pstrText++; } else { POINT ptPos = pt; int cchChars = 0; int cchSize = 0; int cchLastGoodWord = 0; int cchLastGoodSize = 0; LPCTSTR p = pstrText; LPCTSTR pstrNext; SIZE szText = { 0 }; if( !bInRaw && *p == _T('<') || *p == _T('{') ) p++, cchChars++, cchSize++; while( *p != _T('\0') && *p != _T('\n') ) { // This part makes sure that we're word-wrapping if needed or providing support // for DT_END_ELLIPSIS. Unfortunately the GetTextExtentPoint32() call is pretty // slow when repeated so often. // TODO: Rewrite and use GetTextExtentExPoint() instead! if( bInRaw ) { if( ( *p == _T('<') || *p == _T('{') ) && p[1] == _T('/') && p[2] == _T('r') && ( p[3] == _T('>') || p[3] == _T('}') ) ) { p += 4; bInRaw = false; break; } } else { if( *p == _T('<') || *p == _T('{') ) break; } pstrNext = ::CharNext(p); cchChars++; cchSize += (int)(pstrNext - p); szText.cx = cchChars * pTm->tmMaxCharWidth; if( pt.x + szText.cx >= rc.right ) { ::GetTextExtentPoint32(hDC, pstrText, cchSize, &szText); } if( pt.x + szText.cx > rc.right ) { if( pt.x + szText.cx > rc.right && pt.x != rc.left) { cchChars--; cchSize -= (int)(pstrNext - p); } if( (uStyle & DT_WORDBREAK) != 0 && cchLastGoodWord > 0 ) { cchChars = cchLastGoodWord; cchSize = cchLastGoodSize; } if( (uStyle & DT_END_ELLIPSIS) != 0 && cchChars > 0 ) { cchChars -= 1; LPCTSTR pstrPrev = ::CharPrev(pstrText, p); if( cchChars > 0 ) { cchChars -= 1; pstrPrev = ::CharPrev(pstrText, pstrPrev); cchSize -= (int)(p - pstrPrev); } else cchSize -= (int)(p - pstrPrev); pt.x = rc.right; } bLineEnd = true; cxMaxWidth = MAX(cxMaxWidth, pt.x); break; } if (!( ( p[0] >= _T('a') && p[0] <= _T('z') ) || ( p[0] >= _T('A') && p[0] <= _T('Z') ) )) { cchLastGoodWord = cchChars; cchLastGoodSize = cchSize; } if( *p == _T(' ') ) { cchLastGoodWord = cchChars; cchLastGoodSize = cchSize; } p = ::CharNext(p); } ::GetTextExtentPoint32(hDC, pstrText, cchSize, &szText); if( bDraw && bLineDraw ) { if( (uStyle & DT_SINGLELINE) == 0 && (uStyle & DT_CENTER) != 0 ) { ptPos.x += (rc.right - rc.left - szText.cx)/2; } else if( (uStyle & DT_SINGLELINE) == 0 && (uStyle & DT_RIGHT) != 0) { ptPos.x += (rc.right - rc.left - szText.cx); } ::TextOut(hDC, ptPos.x, ptPos.y + cyLineHeight - pTm->tmHeight - pTm->tmExternalLeading, pstrText, cchSize); if( pt.x >= rc.right && (uStyle & DT_END_ELLIPSIS) != 0 ) ::TextOut(hDC, ptPos.x + szText.cx, ptPos.y, _T("..."), 3); } pt.x += szText.cx; cxMaxWidth = MAX(cxMaxWidth, pt.x); pstrText += cchSize; } if( pt.x >= rc.right || *pstrText == _T('\n') || *pstrText == _T('\0') ) bLineEnd = true; if( bDraw && bLineEnd ) { if( !bLineDraw ) { aFontArray.Resize(aLineFontArray.GetSize()); ::CopyMemory(aFontArray.GetData(), aLineFontArray.GetData(), aLineFontArray.GetSize() * sizeof(LPVOID)); aColorArray.Resize(aLineColorArray.GetSize()); ::CopyMemory(aColorArray.GetData(), aLineColorArray.GetData(), aLineColorArray.GetSize() * sizeof(LPVOID)); aPIndentArray.Resize(aLinePIndentArray.GetSize()); ::CopyMemory(aPIndentArray.GetData(), aLinePIndentArray.GetData(), aLinePIndentArray.GetSize() * sizeof(LPVOID)); cyLineHeight = cyLine; pstrText = pstrLineBegin; bInRaw = bLineInRaw; bInSelected = bLineInSelected; DWORD clrColor = dwTextColor; if( aColorArray.GetSize() > 0 ) clrColor = (int)aColorArray.GetAt(aColorArray.GetSize() - 1); ::SetTextColor(hDC, RGB(GetBValue(clrColor), GetGValue(clrColor), GetRValue(clrColor))); TFontInfo* pFontInfo = (TFontInfo*)aFontArray.GetAt(aFontArray.GetSize() - 1); if( pFontInfo == NULL ) pFontInfo = pManager->GetDefaultFontInfo(); pTm = &pFontInfo->tm; ::SelectObject(hDC, pFontInfo->hFont); if( bInSelected ) ::SetBkMode(hDC, OPAQUE); } else { aLineFontArray.Resize(aFontArray.GetSize()); ::CopyMemory(aLineFontArray.GetData(), aFontArray.GetData(), aFontArray.GetSize() * sizeof(LPVOID)); aLineColorArray.Resize(aColorArray.GetSize()); ::CopyMemory(aLineColorArray.GetData(), aColorArray.GetData(), aColorArray.GetSize() * sizeof(LPVOID)); aLinePIndentArray.Resize(aPIndentArray.GetSize()); ::CopyMemory(aLinePIndentArray.GetData(), aPIndentArray.GetData(), aPIndentArray.GetSize() * sizeof(LPVOID)); pstrLineBegin = pstrText; bLineInSelected = bInSelected; bLineInRaw = bInRaw; } } ASSERT(iLinkIndex<=nLinkRects); } nLinkRects = iLinkIndex; // Return size of text when requested if( (uStyle & DT_CALCRECT) != 0 ) { rc.bottom = MAX(cyMinHeight, pt.y + cyLine); rc.right = MIN(rc.right, cxMaxWidth); } if( bDraw ) ::SelectClipRgn(hDC, hOldRgn); ::DeleteObject(hOldRgn); ::DeleteObject(hRgn); ::SelectObject(hDC, hOldFont); } HBITMAP CRenderEngine::GenerateBitmap(CPaintManagerUI* pManager, CControlUI* pControl, RECT rc) { int cx = rc.right - rc.left; int cy = rc.bottom - rc.top; HDC hPaintDC = ::CreateCompatibleDC(pManager->GetPaintDC()); HBITMAP hPaintBitmap = ::CreateCompatibleBitmap(pManager->GetPaintDC(), rc.right, rc.bottom); ASSERT(hPaintDC); ASSERT(hPaintBitmap); HBITMAP hOldPaintBitmap = (HBITMAP) ::SelectObject(hPaintDC, hPaintBitmap); pControl->DoPaint(hPaintDC, rc); BITMAPINFO bmi = { 0 }; bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = cx; bmi.bmiHeader.biHeight = cy; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = cx * cy * sizeof(DWORD); LPDWORD pDest = NULL; HDC hCloneDC = ::CreateCompatibleDC(pManager->GetPaintDC()); HBITMAP hBitmap = ::CreateDIBSection(pManager->GetPaintDC(), &bmi, DIB_RGB_COLORS, (LPVOID*) &pDest, NULL, 0); ASSERT(hCloneDC); ASSERT(hBitmap); if( hBitmap != NULL ) { HBITMAP hOldBitmap = (HBITMAP) ::SelectObject(hCloneDC, hBitmap); ::BitBlt(hCloneDC, 0, 0, cx, cy, hPaintDC, rc.left, rc.top, SRCCOPY); ::SelectObject(hCloneDC, hOldBitmap); ::DeleteDC(hCloneDC); ::GdiFlush(); } // Cleanup ::SelectObject(hPaintDC, hOldPaintBitmap); ::DeleteObject(hPaintBitmap); ::DeleteDC(hPaintDC); return hBitmap; } SIZE CRenderEngine::GetTextSize( HDC hDC, CPaintManagerUI* pManager , LPCTSTR pstrText, int iFont, UINT uStyle ) { SIZE size = {0,0}; ASSERT(::GetObjectType(hDC)==OBJ_DC || ::GetObjectType(hDC)==OBJ_MEMDC); if( pstrText == NULL || pManager == NULL ) return size; ::SetBkMode(hDC, TRANSPARENT); HFONT hOldFont = (HFONT)::SelectObject(hDC, pManager->GetFont(iFont)); GetTextExtentPoint32(hDC, pstrText, _tcslen(pstrText) , &size); ::SelectObject(hDC, hOldFont); return size; } void CRenderEngine::CheckAlphaColor(DWORD& dwColor) { //RestoreAlphaColor认为0x00000000是真正的透明,其它都是GDI绘制导致的 //所以在GDI绘制中不能用0xFF000000这个颜色值,现在处理是让它变成RGB(0,0,1) //RGB(0,0,1)与RGB(0,0,0)很难分出来 if((0x00FFFFFF & dwColor) == 0) { dwColor += 1; } } HBITMAP CRenderEngine::CreateARGB32Bitmap(HDC hDC, int cx, int cy, BYTE** pBits) { LPBITMAPINFO lpbiSrc = NULL; lpbiSrc = (LPBITMAPINFO) new BYTE[sizeof(BITMAPINFOHEADER)]; if (lpbiSrc == NULL) return NULL; lpbiSrc->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); lpbiSrc->bmiHeader.biWidth = cx; lpbiSrc->bmiHeader.biHeight = cy; lpbiSrc->bmiHeader.biPlanes = 1; lpbiSrc->bmiHeader.biBitCount = 32; lpbiSrc->bmiHeader.biCompression = BI_RGB; lpbiSrc->bmiHeader.biSizeImage = cx * cy; lpbiSrc->bmiHeader.biXPelsPerMeter = 0; lpbiSrc->bmiHeader.biYPelsPerMeter = 0; lpbiSrc->bmiHeader.biClrUsed = 0; lpbiSrc->bmiHeader.biClrImportant = 0; HBITMAP hBitmap = CreateDIBSection (hDC, lpbiSrc, DIB_RGB_COLORS, (void **)pBits, NULL, NULL); delete [] lpbiSrc; return hBitmap; } void CRenderEngine::AdjustImage(bool bUseHSL, TImageInfo* imageInfo, short H, short S, short L) { if( imageInfo == NULL || imageInfo->bUseHSL == false || imageInfo->hBitmap == NULL || imageInfo->pBits == NULL || imageInfo->pSrcBits == NULL ) return; if( bUseHSL == false || (H == 180 && S == 100 && L == 100)) { ::CopyMemory(imageInfo->pBits, imageInfo->pSrcBits, imageInfo->nX * imageInfo->nY * 4); return; } float fH, fS, fL; float S1 = S / 100.0f; float L1 = L / 100.0f; for( int i = 0; i < imageInfo->nX * imageInfo->nY; i++ ) { RGBtoHSL(*(DWORD*)(imageInfo->pSrcBits + i*4), &fH, &fS, &fL); fH += (H - 180); fH = fH > 0 ? fH : fH + 360; fS *= S1; fL *= L1; HSLtoRGB((DWORD*)(imageInfo->pBits + i*4), fH, fS, fL); } } } // namespace DuiLib
[ "qdtroy@qq.com" ]
qdtroy@qq.com
9b8ea3de2d84c63b549873d9f8df3cfdfb8af38f
5a2349399fa9d57c6e8cc6e0f7226d683391a362
/src/qt/qtwebkit/Source/WebKit/qt/WebCoreSupport/GeolocationClientQt.cpp
b4c5189f685e77bc4d78ea55463806287b47012e
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
aharthcock/phantomjs
e70f3c379dcada720ec8abde3f7c09a24808154c
7d7f2c862347fbc7215c849e790290b2e07bab7c
refs/heads/master
2023-03-18T04:58:32.428562
2023-03-14T05:52:52
2023-03-14T05:52:52
24,828,890
0
0
BSD-3-Clause
2023-03-14T05:52:53
2014-10-05T23:38:56
C++
UTF-8
C++
false
false
5,076
cpp
/* * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "GeolocationClientQt.h" #include "Geolocation.h" #include "GeolocationController.h" #include "GeolocationError.h" #include "GeolocationPermissionClientQt.h" #include "GeolocationPosition.h" #include "HTMLFormElement.h" #include "Page.h" #include "QWebFrameAdapter.h" #include "QWebPageAdapter.h" #include <QtPositioning/QGeoPositionInfoSource> namespace WebCore { static const char failedToStartServiceErrorMessage[] = "Failed to start Geolocation service"; GeolocationClientQt::GeolocationClientQt(const QWebPageAdapter* page) : m_webPage(page) , m_lastPosition(0) , m_location(0) { } GeolocationClientQt::~GeolocationClientQt() { delete m_location; } void GeolocationClientQt::geolocationDestroyed() { delete this; } void GeolocationClientQt::positionUpdated(const QGeoPositionInfo& geoPosition) { if (!geoPosition.isValid()) return; QGeoCoordinate coord = geoPosition.coordinate(); double latitude = coord.latitude(); double longitude = coord.longitude(); bool providesAltitude = (geoPosition.coordinate().type() == QGeoCoordinate::Coordinate3D); double altitude = coord.altitude(); double accuracy = geoPosition.attribute(QGeoPositionInfo::HorizontalAccuracy); bool providesAltitudeAccuracy = geoPosition.hasAttribute(QGeoPositionInfo::VerticalAccuracy); double altitudeAccuracy = geoPosition.attribute(QGeoPositionInfo::VerticalAccuracy); bool providesHeading = geoPosition.hasAttribute(QGeoPositionInfo::Direction); double heading = geoPosition.attribute(QGeoPositionInfo::Direction); bool providesSpeed = geoPosition.hasAttribute(QGeoPositionInfo::GroundSpeed); double speed = geoPosition.attribute(QGeoPositionInfo::GroundSpeed); double timeStampInSeconds = geoPosition.timestamp().toMSecsSinceEpoch() / 1000; m_lastPosition = GeolocationPosition::create(timeStampInSeconds, latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed); WebCore::Page* page = m_webPage->page; GeolocationController::from(page)->positionChanged(m_lastPosition.get()); } void GeolocationClientQt::startUpdating() { if (!m_location && (m_location = QGeoPositionInfoSource::createDefaultSource(this))) connect(m_location, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo))); if (!m_location) { WebCore::Page* page = m_webPage->page; RefPtr<WebCore::GeolocationError> error = GeolocationError::create(GeolocationError::PositionUnavailable, failedToStartServiceErrorMessage); GeolocationController::from(page)->errorOccurred(error.get()); return; } m_location->startUpdates(); } void GeolocationClientQt::stopUpdating() { if (m_location) m_location->stopUpdates(); } void GeolocationClientQt::setEnableHighAccuracy(bool) { // qtmobility 1.0 supports only GPS as of now so high accuracy is enabled by default } void GeolocationClientQt::requestPermission(Geolocation* geolocation) { ASSERT(geolocation); QWebFrameAdapter* webFrame = QWebFrameAdapter::kit(geolocation->frame()); GeolocationPermissionClientQt::geolocationPermissionClient()->requestGeolocationPermissionForFrame(webFrame, geolocation); } void GeolocationClientQt::cancelPermissionRequest(Geolocation* geolocation) { ASSERT(geolocation); QWebFrameAdapter* webFrame = QWebFrameAdapter::kit(geolocation->frame()); GeolocationPermissionClientQt::geolocationPermissionClient()->cancelGeolocationPermissionRequestForFrame(webFrame, geolocation); } } // namespace WebCore #include "moc_GeolocationClientQt.cpp"
[ "ariya.hidayat@gmail.com" ]
ariya.hidayat@gmail.com
8a6fdf263d740e64c3ce4467012dc9df2a64bd2a
98ee63ddbd737ed29569d08d588732a4b3a086e6
/core/AbstractPlaces.h
715ba8ef686ab80befec7a768eb2a742992a3029
[ "MIT" ]
permissive
vitalissius/iweather
883e975a37186d9db53ab06e69d8f2bcbbdf2dbd
13b6469b729a627335a2d629e5a62f6726058dc0
refs/heads/master
2021-01-22T08:09:37.491218
2017-03-21T11:26:31
2017-03-21T11:26:31
81,877,415
1
0
null
null
null
null
UTF-8
C++
false
false
881
h
#pragma once #include "LanguagePack.h" #include <algorithm> #include <string> #include <vector> class AbstractPlaces { protected: struct Place { std::string key; std::string place; Place(std::string key, std::string place); }; protected: AbstractPlaces() = default; public: AbstractPlaces(AbstractPlaces&&) = default; virtual ~AbstractPlaces() = default; AbstractPlaces& operator=(AbstractPlaces&&) = default; std::vector<Place>::const_iterator begin() const; std::vector<Place>::const_iterator end() const; std::vector<Place>::size_type size() const; const Place& at(size_t pos) const; std::string GetKey(const std::string& place) const; public: virtual void Update(const std::string& place) = 0; private: virtual void parse(std::string page) = 0; protected: std::vector<Place> m_places; };
[ "vitaliy.sklyarov@gmail.com" ]
vitaliy.sklyarov@gmail.com
a10a3dcf8ea4c4497fe7a1e9ae1a57e689bea831
42c64672a2a640646a2b66197da2e5134486a1bc
/mixExcel/ExcelWrite_noOLE/ExcelFile.h
4c5329d89b238a332aff9ebe0b7398a84ef22766
[]
no_license
15831944/C_plus_plus
898de0abd44898060460c9adcabade9f4849fece
50a3d1e72718c6d577a49180ce29e8c81108cdfd
refs/heads/master
2022-10-01T15:30:13.837718
2020-06-08T20:08:09
2020-06-08T20:08:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
393
h
#include <stdio.h> class ExcelFile { public: ExcelFile(); ExcelFile(char *fname); ~ExcelFile(); bool open(char *fname); void writeCell(unsigned short col, unsigned short row, int value); void writeCell(unsigned short col, unsigned short row, double value); void writeCell(unsigned short col, unsigned short row, char *value); void close(); protected: FILE *f; };
[ "logovopost@yandex.ru" ]
logovopost@yandex.ru
588ad13d9d670567e107c82b7ae3b72c728f714c
941c21954bcedc96fddf41a09bc71fb1e44e226f
/contest-1181-567/a.cpp
a75f5d383424d8e50e03f916cdabb18bc509a375
[ "MIT" ]
permissive
easimonenko/codeforces-problems-solutions
9cbf5f73bede40c48915b26d6303e36b11398655
36e4ecd7fcdfe1d6a4d2b439f952c5aefa9c0bf4
refs/heads/master
2023-08-05T05:06:40.376155
2023-07-27T09:10:51
2023-07-27T09:10:51
69,059,791
1
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#include <iostream> using namespace std; int main() { long long x, y, z; cin >> x >> y >> z; long long r1 = x % z, r2 = y % z; long long r = r1 + r2; long long delta = r % z; cout << x / z + y / z + r / z << " " << max(min(r1, r2) - delta, 0LL) << endl; return 0; }
[ "easimonenko@mail.ru" ]
easimonenko@mail.ru
46d9dc390b95b38af7aaf9817e2e457cdce4c41d
edd67c7e9a8996b002f2a58c3f1baa2cfd1b8bed
/leetcode/QtcreatorProjects/untitled11/main.cpp
e4575513e5c3b151264a5e121cbb90a0910a9e15
[]
no_license
glennychen/cp3
ebfbc023a7005d7a1871d91fb51def0ce715af56
baaccc92a34bb775919b8448e5dc5c58db24e839
refs/heads/master
2023-06-10T00:39:20.642981
2023-06-04T00:55:14
2023-06-04T00:55:14
131,664,164
0
0
null
null
null
null
UTF-8
C++
false
false
1,171
cpp
// https://leetcode.com/problems/delete-n-nodes-after-m-nodes-of-a-linked-list/ #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode* deleteNodes(ListNode* head, int m, int n) { ListNode* current = head; ListNode* before_delete = head; while (current != nullptr) { int keep = m; int remove = n; while(keep-- > 0){ //remember keep--, is keep, then keep = keep -1, need to reset keep or infinite loop if (current->next == nullptr) return head; before_delete = current; current = current->next; } while(remove-- > 0 && current != nullptr){ ListNode* to_be_deleted = current; current = current->next; delete to_be_deleted; } before_delete->next = current; } return head; } }; int main() { return 0; }
[ "glenn.chen01@gmail.com" ]
glenn.chen01@gmail.com
94709722b4bfbd13bbe496ca284db5e33af44aa0
4ed584410ce88f7adea994d56a95df0b24c1ccf3
/LibreOJ/2317BFS.cpp
268ea3bf6b4c22b3d73502d746d5d9668c6f602c
[]
no_license
L-Trump/OI-code
0750e88ee9ecb75287eb5e6a7a9a09dae39f8bd6
9d3de89c94c998425b54c45218ead958c38bcc19
refs/heads/master
2020-04-21T21:00:50.826208
2019-08-15T15:35:09
2019-08-15T15:35:09
169,865,046
0
0
null
null
null
null
UTF-8
C++
false
false
3,043
cpp
#include <cstdio> #include <iostream> #include <queue> #include <cmath> #include <cstring> #include <algorithm> #define rep(i, l, r) for (int i = (l); i <= (r); ++i) #define per(i, l, r) for (int i = (l); i >= (r); --i) using std::cin; using std::cout; using std::cerr; using std::endl; using std::string; typedef long long ll; struct circle{ circle *head, *next; bool final, visited; int x,y,z; circle(){ next=head=NULL; z=x=y=0; final=false; visited=false; } }; circle *e[1005]; circle *down[1005]; circle* create(){ return new circle; } double dis(circle* a, circle* b){ double x1=(double)a->x,x2=(double)b->x,y1=(double)a->y,y2=(double)b->y; double z1=(double)a->z,z2=(double)b->z; return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2)); } void newEdge(circle* a, circle* b){ if(a->head!=NULL){ b->next=a->head; } a->head=b; //printf("%d %d %d -> %d %d %d\n", a->x,a->y,a->z,b->x,b->y,b->z); } bool bfs(circle *root){ std::queue<circle*> q; if(root->visited) return false; q.push(root); while(!q.empty()){ root=q.front(); q.pop(); if(root->visited) continue; root->visited=true; if(root->final) return true; for(circle* p=root->head;p!=NULL;p=p->next){ q.push(p); } } return false; } int main(){ int T,n,h,r,x,y,z; int cntd; bool found; //freopen("triangle.in", "r", stdin); //freopen("triangle.out", "w", stdout); std::ios::sync_with_stdio(false); cout.tie(0); cin>>T; rep(i,0,1005) e[i]=down[i]=NULL; rep(k,1,T){ cntd=0;found=false; cin>>n>>h>>r; rep(i,1,n){ e[i]=create(); cin>>x>>y>>z; e[i]->x=x;e[i]->y=y;e[i]->z=z; if (z<=r) down[++cntd]=e[i]; if (h-z<=r) e[i]->final=true; rep(j,1,i-1){ // cerr<<"distance of "<<j<<" and "<<i<<" is "<<dis(e[1],e[i])<<endl; if(dis(e[j],e[i])<=2*r){ //z低位指向高位,同位互指 if(e[i]->z>e[j]->z) { newEdge(e[j],e[i]); // cerr<<"connect: "<<j<<"->"<<i<<endl; } if(e[i]->z<e[j]->z) { newEdge(e[i],e[j]); // cerr<<"connect: "<<i<<"->"<<j<<endl; } if(e[i]->z==e[j]->z){ newEdge(e[i],e[j]); newEdge(e[j],e[i]); // cerr<<"connect: "<<i<<" and "<<j<<endl; } } } } //建图 //cerr<<"down count="<<cntd<<endl; //cerr<<"e[2]'s final is "<<e[2]->final<<endl; //cerr<<down[1]->x<<" "<<down[1]->y<<" "<<down[1]->z<<endl; rep(i,1,cntd){ //广搜 if(bfs(down[i])){ found=true; cout<<"Yes"<<endl; break; } } if(!found) cout<<"No"<<endl; rep(i,1,n){ delete e[i]; down[i]=e[i]=NULL; } } return 0; }
[ "yinghaochi@163.com" ]
yinghaochi@163.com
cf0a4579fb901bf94ac0c464c50b4bf5d99a8511
d9d08bf67fceb7fffa51501462ff1b3e71984c9f
/release/v0.2.2_rss/src/Linux_Gateway/udpclt/CmdControlLightHandler.cpp
4218ebe516d8c235f0ada72a9429186d0c41437e
[]
no_license
Clariones/job_deltadore_linux
0e9138a7fa7636ec58f943bfca0c22347f161778
2971d64b2cd1806dcd59cc296a807aae76ef5647
refs/heads/master
2021-01-13T03:06:51.164085
2018-05-24T03:13:20
2018-05-24T03:13:20
77,445,612
0
0
null
null
null
null
UTF-8
C++
false
false
3,612
cpp
/** * File name: CmdControlLightHandler.cpp * Author: Clariones Wang * * All rights reserved. */ #include "CmdControlLightHandler.h" #define CMD_NAME "controlLight" #define MAX_OPTION_LENTH 14 CmdControlLightHandler::CmdControlLightHandler(){ } CmdControlLightHandler::~CmdControlLightHandler(){ } const char* CmdControlLightHandler::handle(const char* pCmd, DeltaDoreX2Driver* pDriver){ int network; int node; // first string always the command, so just skip it const char* pCurrentParam = pCmd; // process paramter: network pCurrentParam = getNextParamStartPosition(pCurrentParam);; if (pCurrentParam == NULL){ return newMissingRequiredParametersResponse(); } getParamInt(pCurrentParam, &network); if (!isValidNetwork(network)){ return newWrongIntParamResponse("Invalid network number %d", network); } // process parameter: node pCurrentParam = getNextParamStartPosition(pCurrentParam); if (pCurrentParam == NULL){ return newMissingRequiredParametersResponse(); } getParamInt(pCurrentParam, &node); if (!isValidNode(node)){ return newWrongIntParamResponse("Invalid node number %d", node); } // process parameter: option pCurrentParam = getNextParamStartPosition(pCurrentParam); if (pCurrentParam == NULL){ return newMissingRequiredParametersResponse(); } char* option = new char[strlen(pCurrentParam) + 1]; cJSON* pResponse = NULL; getParamString(pCurrentParam, option); if (strlen(option) >= MAX_OPTION_LENTH){ const char* pResult = newWrongStringParamResponse("invalid option %s", option); delete option; return pResult; } else if (strcmp("off", option) == 0 ) { pResponse = pDriver->switchOffLight(network, node ); } else if (strcmp("on", option) == 0 ) { pResponse = pDriver->switchOnLight(network, node ); } else if (strcmp("ram-up", option) == 0 ) { pResponse = pDriver->rampUpLight(network, node ); } else if (strcmp("ram-down", option) == 0 ) { pResponse = pDriver->ramDownLight(network, node ); } else if (strcmp("stop", option) == 0 ) { pResponse = pDriver->stopLight(network, node ); } else if (strcmp("stand-out", option) == 0 ) { pResponse = pDriver->standOutLight(network, node ); } else if (strcmp("alarm-pairing", option) == 0 ) { pResponse = pDriver->alarmPairingLight(network, node ); } else if (strcmp("toggle", option) == 0 ) { pResponse = pDriver->toggleLight(network, node ); } else if (strcmp("preset-1", option) == 0 ) { pResponse = pDriver->preset1Light(network, node ); } else if (strcmp("preset-2", option) == 0 ) { pResponse = pDriver->preset2Light(network, node ); } else { const char* pResult = newWrongStringParamResponse("invalid option %s", option); delete option; return pResult; } delete option; return newResponse(pResponse); } const char * CmdControlLightHandler::getCommandName(){ return CMD_NAME; } const char * CmdControlLightHandler::getUsage(){ return "Control light devices\n" \ "Usage:\n" \ " controlLight <network> <node> option\n" \ "Params:\n" \ " network: the network number of target device, 0~11\n" \ " node: the node number of target device, 0~15\n" \ " option: the valid action options. Can be:\n" \ " off on ram-up ram-down stop stand-out alarm-pairing toggle preset-1 preset-2"; } #undef MAX_OPTION_LENTH #undef CMD_NAME
[ "clariones@163.com" ]
clariones@163.com
b921b9d9ac0813ec5a116cd93335d85a5cf1322a
5be190b7f68ebcbddcee06a2e2c3ea2ea6144add
/include/common/snippets/telnet.cpp
f1713aa4990dd675549894a0faf4469b5af2c82f
[]
no_license
sheldonrobinson/codesuppository
e03d60c1098a90a8dab99a4c703bf342b22b9a65
3577f70e2dbe04f1996151b209d448dc7c0e28d2
refs/heads/master
2020-05-17T13:36:53.048159
2014-02-24T20:26:24
2014-02-24T20:26:24
42,025,259
1
0
null
null
null
null
UTF-8
C++
false
false
61,204
cpp
#ifndef __CELLOS_LV2__ #include <assert.h> #include <ctype.h> #pragma warning(disable:4211) #pragma warning(disable:4244) #pragma warning(disable:4189) #pragma warning(disable:4100) #pragma warning(disable:4706) #pragma warning(disable:4702) #pragma warning(disable:4267) #include "UserMemAlloc.h" #include <list> #include <queue> #include <map> /*! ** ** Copyright (c) 2009 by John W. Ratcliff mailto:jratcliffscarab@gmail.com ** ** Portions of this source has been released with the PhysXViewer application, as well as ** Rocket, CreateDynamics, ODF, and as a number of sample code snippets. ** ** If you find this code useful or you are feeling particularily generous I would ** ask that you please go to http://www.amillionpixels.us and make a donation ** to Troy DeMolay. ** ** DeMolay is a youth group for young men between the ages of 12 and 21. ** It teaches strong moral principles, as well as leadership skills and ** public speaking. The donations page uses the 'pay for pixels' paradigm ** where, in this case, a pixel is only a single penny. Donations can be ** made for as small as $4 or as high as a $100 block. Each person who donates ** will get a link to their own site as well as acknowledgement on the ** donations blog located here http://www.amillionpixels.blogspot.com/ ** ** If you wish to contact me you can use the following methods: ** ** Skype ID: jratcliff63367 ** Yahoo: jratcliff63367 ** AOL: jratcliff1961 ** email: jratcliffscarab@gmail.com ** Personal website: http://jratcliffscarab.blogspot.com ** Coding Website: http://codesuppository.blogspot.com ** FundRaising Blog: http://amillionpixels.blogspot.com ** Fundraising site: http://www.amillionpixels.us ** New Temple Site: http://newtemple.blogspot.com ** ** ** The MIT license: ** ** Permission is hereby granted, freeof 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. */ //*********************************************************************************** //*** This code snippet allows you to embed a telnet client or server easily into any //*** of your applications. Currently this code only builds for Windows and the XBOX //*** It is very desirable to me to have this code build for APPLE, Linux, and Iphone //*** If you wish to contribute to this cause, please let me know and I will add you //*** as a developer to the google code page. http://code.google.com/p/telnet //*** //*** To test the program simply run 'telnet.exe'. //*** //*** The first time you run it, it will be set up as a telnet server. You can //*** connect to it by runing a telnet client and typing 'open localhost 23' //*** If you run the program a second time, it will detect that a server is already //*** using Port 23 and will instead start up as a client. You can now send messages //*** between the two instances of the application. //*** You can keep launching as many of them as you wish. //*********************************************************************************** #if defined(_XBOX) #include "NxXBOX.h" #include <winsockx.h> #endif #if defined(WIN32) #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x400 #endif #include <windows.h> #endif #if defined(_XBOX) #include "NxXBOX.h" #endif #if defined(__APPLE__) || defined(LINUX) #include <pthread.h> #endif #include "telnet.h" // Common Telnet Functionality. #ifdef WIN32 #pragma warning(disable:4786 4996) #pragma comment(lib,"wsock32.lib") #endif namespace NVSHARE { Telnet *gTelnet=0; // optional global variable representing the TELNET singleton for the application. }; #define TELNET_NVSHARE TELNET_##NVSHARE namespace TELNET_NVSHARE { ///*************** The FastXML code snippet class FastXmlInterface { public: // return true to continue processing the XML document, false to skip. virtual bool processElement(const char *elementName, // name of the element NxI32 argc, // number of attributes const char **argv, // list of attributes. const char *elementData, // element data, null if none NxI32 lineno) = 0; // line number in the source XML file }; class FastXml { public: virtual bool processXml(const char *inputData,NxU32 dataLen,FastXmlInterface *iface) = 0; virtual const char * getError(NxI32 &lineno) = 0; // report the reason for a parsing error, and the line number where it occurred. }; FastXml * createFastXml(void); void releaseFastXml(FastXml *f); class MyFastXml : public FastXml, public NVSHARE::Memalloc { public: enum CharType { CT_DATA, CT_EOF, CT_SOFT, CT_END_OF_ELEMENT, // either a forward slash or a greater than symbol CT_END_OF_LINE, }; MyFastXml(void) { mInputData = 0; memset(mTypes,CT_DATA,256); mTypes[0] = CT_EOF; mTypes[32] = CT_SOFT; mTypes[9] = CT_SOFT; mTypes['/'] = CT_END_OF_ELEMENT; mTypes['>'] = CT_END_OF_ELEMENT; mTypes['?'] = CT_END_OF_ELEMENT; mTypes[10] = CT_END_OF_LINE; mTypes[13] = CT_END_OF_LINE; mError = 0; } virtual ~MyFastXml(void) { release(); } void release(void) { if ( mInputData ) { free(mInputData); mInputData = 0; } mError = 0; } inline char *nextSoft(char *scan) { while ( *scan && mTypes[*scan] != CT_SOFT ) scan++; return scan; } inline char *nextSoftOrClose(char *scan,bool &close) { while ( *scan && mTypes[*scan] != CT_SOFT && *scan != '>' ) scan++; close = *scan == '>'; return scan; } inline char *nextSep(char *scan) { while ( *scan && mTypes[*scan] != CT_SOFT && *scan != '=' ) scan++; return scan; } inline char * skipNextData(char *scan) { // while we have data, and we encounter soft seperators or line feeds... while ( *scan && mTypes[*scan] == CT_SOFT || mTypes[*scan] == CT_END_OF_LINE ) { if ( *scan == 13 ) mLineNo++; scan++; } return scan; } char * processClose(char c,const char *element,char *scan,NxI32 argc,const char **argv,FastXmlInterface *iface) { if ( c == '/' || c == '?' ) { if ( *scan != '>' ) // unexepected character! { mError = "Expected an element close character immediately after the '/' or '?' character."; return 0; } scan++; bool ok = iface->processElement(element,argc,argv,0,mLineNo); if ( !ok ) { mError = "User aborted the parsing process"; return 0; } } else { scan = skipNextData(scan); char *data = scan; // this is the data portion of the element, only copies memory if we encounter line feeds char *dest_data = 0; while ( *scan && *scan != '<' ) { if ( mTypes[*scan] == CT_END_OF_LINE ) { if ( *scan == 13 ) mLineNo++; dest_data = scan; *dest_data++ = 32; // replace the linefeed with a space... scan = skipNextData(scan); while ( *scan && *scan != '<' ) { if ( mTypes[*scan] == CT_END_OF_LINE ) { if ( *scan == 13 ) mLineNo++; *dest_data++ = 32; // replace the linefeed with a space... scan = skipNextData(scan); } else { *dest_data++ = *scan++; } } break; } else scan++; } if ( *scan == '<' ) { if ( dest_data ) { *dest_data = 0; } else { *scan = 0; } scan++; // skip it.. if ( *data == 0 ) data = 0; bool ok = iface->processElement(element,argc,argv,data,mLineNo); if ( !ok ) { mError = "User aborted the parsing process"; return 0; } if ( *scan == '/' ) { while ( *scan && *scan != '>' ) scan++; scan++; } } else { mError = "Data portion of an element wasn't terminated properly"; return 0; } } return scan; } virtual bool processXml(const char *inputData,NxU32 dataLen,FastXmlInterface *iface) { bool ret = true; #define MAX_ATTRIBUTE 2048 // can't imagine having more than 2,048 attributes in a single element right? release(); mInputData = (char *)malloc(dataLen+1); memcpy(mInputData,inputData,dataLen); mInputData[dataLen] = 0; mLineNo = 1; char *element; char *scan = mInputData; if ( *scan == '<' ) { scan++; while ( *scan ) { scan = skipNextData(scan); if ( *scan == 0 ) return ret; if ( *scan == '<' ) { scan++; } if ( *scan == '/' || *scan == '?' ) { while ( *scan && *scan != '>' ) scan++; scan++; } else { element = scan; NxI32 argc = 0; const char *argv[MAX_ATTRIBUTE]; bool close; scan = nextSoftOrClose(scan,close); if ( close ) { char c = *(scan-1); if ( c != '?' && c != '/' ) { c = '>'; } *scan = 0; scan++; scan = processClose(c,element,scan,argc,argv,iface); if ( !scan ) return false; } else { if ( *scan == 0 ) return ret; *scan = 0; // place a zero byte to indicate the end of the element name... scan++; while ( *scan ) { scan = skipNextData(scan); // advance past any soft seperators (tab or space) if ( mTypes[*scan] == CT_END_OF_ELEMENT ) { char c = *scan++; scan = processClose(c,element,scan,argc,argv,iface); if ( !scan ) return false; break; } else { if ( argc >= MAX_ATTRIBUTE ) { mError = "encountered too many attributes"; return false; } argv[argc] = scan; scan = nextSep(scan); // scan up to a space, or an equal if ( *scan ) { if ( *scan != '=' ) { *scan = 0; scan++; while ( *scan && *scan != '=' ) scan++; if ( *scan == '=' ) scan++; } else { *scan=0; scan++; } if ( *scan ) // if not eof... { scan = skipNextData(scan); if ( *scan == 34 ) { scan++; argc++; argv[argc] = scan; argc++; while ( *scan && *scan != 34 ) scan++; if ( *scan == 34 ) { *scan = 0; scan++; } else { mError = "Failed to find closing quote for attribute"; return false; } } else { mError = "Expected quote to begin attribute"; return false; } } } } } } } } } else { mError = "Expected the start of an element '<' at this location."; ret = false; // unexpected character!? } return ret; } const char * getError(NxI32 &lineno) { const char *ret = mError; lineno = mLineNo; mError = 0; return ret; } private: char mTypes[256]; char *mInputData; NxI32 mLineNo; const char *mError; }; FastXml * createFastXml(void) { MyFastXml *f = MEMALLOC_NEW(MyFastXml); return static_cast< FastXml *>(f); } void releaseFastXml(FastXml *f) { MyFastXml *m = static_cast< MyFastXml *>(f); delete m; } //**** The BlobIO code snippet class BlobIOInterface { public: virtual void sendBlobText(NxU32 client,const char *fmt,...) = 0; }; class BlobIO { public: virtual bool sendBlob(NxU32 client,const char *blobType,const void *blobData,NxU32 blobLen) = 0; virtual const char * receiveBlob(NxU32 &client,const void *&data,NxU32 &dlen) = 0; virtual bool processIncomingBlobText(NxU32 client,const char *text) = 0; protected: BlobIO(void) { }; }; BlobIO * createBlobIO(BlobIOInterface *iface); void releaseBlobIO(BlobIO *b); #define BLOB_LINE 256 static char gHexTable[16] = { '0', '1', '2', '3','4','5','6','7','8','9','A','B','C','D','E','F' }; static inline char getHex(NxU8 c) { return gHexTable[c]; } #pragma warning(disable:4100) static inline bool getHex(char c,NxU8 &v) { bool ret = true; if ( c >= '0' && c <= '9' ) { v = c-'0'; } else if ( c >= 'A' && c <= 'F' ) { v = (c-'A')+10; } else { ret = false; } return ret; } static inline bool getHexValue(char c1,char c2,NxU8 &v) { bool ret = false; NxU8 v1,v2; if ( getHex(c1,v1) && getHex(c2,v2) ) { v = v1<<4 | v2; ret = true; } return ret; } class Blob : public NVSHARE::Memalloc { public: Blob(const char *blobType,NxU32 client,NxU32 blobId,NxU32 olen,const char *data) { NxU32 slen = strlen(blobType); mClient = client; mFinished = false; mError = false; mBlobType = (char *)MEMALLOC_MALLOC(slen+1); strcpy(mBlobType,blobType); mBlobId = blobId; mBlobLen = olen; mBlobData = (NxU8 *)MEMALLOC_MALLOC(olen); mBlobIndex = 0; addData(data); } ~Blob(void) { MEMALLOC_FREE(mBlobType); MEMALLOC_FREE(mBlobData); } void addData(const char *data) { while ( mBlobIndex < mBlobLen && *data ) { char c1 = data[0]; char c2 = data[1]; if ( getHexValue(c1,c2,mBlobData[mBlobIndex]) ) { mBlobIndex++; } else { break; } data+=2; } if ( mBlobIndex == mBlobLen ) { mFinished = true; } } void addDataEnd(const char *data) { addData(data); assert( mFinished ); } NxU32 getId(void) const { return mBlobId; }; bool mFinished; bool mError; char *mBlobType; NxU32 mBlobId; NxU32 mBlobLen; NxU8 *mBlobData; NxU32 mBlobIndex; NxU32 mClient; }; typedef std::list< Blob * > BlobList; class MyBlobIO : public BlobIO, public FastXmlInterface, public NVSHARE::Memalloc { public: MyBlobIO(BlobIOInterface *iface) { mCallback = iface; mBlobId = 0; mLastBlob = 0; mFastXml = createFastXml(); } virtual ~MyBlobIO(void) { releaseFastXml(mFastXml); BlobList::iterator i; for (i=mBlobs.begin(); i!=mBlobs.end(); ++i) { Blob *b = (*i); delete b; } delete mLastBlob; } // convert a blob of binary data into multiple lines of ascii data virtual bool sendBlob(NxU32 client,const char *blobType,const void *blobData,NxU32 blobLen) { bool ret = false; if ( mCallback && blobLen > 0 ) { assert(blobType); assert(blobData); if ( blobLen <= BLOB_LINE ) { char blobText[BLOB_LINE*2+1]; const NxU8 *scan = (const NxU8 *)blobData; char *dest = blobText; for (NxU32 i=0; i<blobLen; i++) { NxU8 c = *scan++; dest[0] = getHex(c>>4); dest[1] = getHex(c&0xF); dest+=2; } *dest = 0; mCallback->sendBlobText(client,"<telnetBlob blob=\"%s\" len=\"%d\">%s</telnetBlob>\r\n", blobType, blobLen, blobText ); } else { mBlobId++; char blobText[BLOB_LINE*2+1]; const NxU8 *scan = (const NxU8 *)blobData; char *dest = blobText; for (NxU32 i=0; i<BLOB_LINE; i++) { NxU8 c = *scan++; dest[0] = getHex(c>>4); dest[1] = getHex(c&0xF); dest+=2; } *dest = 0; mCallback->sendBlobText(client,"<telnetBlob blob=\"%s\" blobId=\"%d\" len=\"%d\">%s</telnetBlob>\r\n", blobType, mBlobId, blobLen, blobText ); blobLen-=BLOB_LINE; while ( blobLen > BLOB_LINE ) { char *dest = blobText; for (NxU32 i=0; i<BLOB_LINE; i++) { NxU8 c = *scan++; dest[0] = getHex(c>>4); dest[1] = getHex(c&0xF); dest+=2; } *dest = 0; blobLen-=BLOB_LINE; mCallback->sendBlobText(client,"<telnetBlobData blobId=\"%d\">%s</telnetBlobData>\r\n", mBlobId, blobText ); } dest = blobText; for (NxU32 i=0; i<blobLen; i++) { NxU8 c = *scan++; dest[0] = getHex(c>>4); dest[1] = getHex(c&0xF); dest+=2; } *dest = 0; mCallback->sendBlobText(client,"<telnetBlobEnd blobId=\"%d\">%s</telnetBlobEnd>\r\n", mBlobId, blobText ); } } return ret; } virtual const char * receiveBlob(NxU32 &client,const void *&data,NxU32 &dlen) { const char *ret = 0; client = 0; data = 0; dlen = 0; delete mLastBlob; mLastBlob = 0; if ( !mBlobs.empty() ) { BlobList::iterator i; for (i=mBlobs.begin(); i!=mBlobs.end(); ++i) { Blob *b = (*i); if ( b->mFinished ) { mLastBlob = b; client = b->mClient; data = b->mBlobData; dlen = b->mBlobLen; ret = b->mBlobType; mBlobs.erase(i); break; } } } return ret; } virtual bool processIncomingBlobText(NxU32 client,const char *text) { bool ret = false; if ( strncmp(text,"<telnetBlob",11) == 0 ) { size_t len = strlen(text); mClient = client; ret = mFastXml->processXml(text,len,this); if ( !ret ) { NxI32 lineno; const char *error = mFastXml->getError(lineno); printf("Error: %s at line %d\r\n", error, lineno ); } } return ret; } virtual bool processElement(const char *elementName, // name of the element NxI32 argc, // number of attributes const char **argv, // list of attributes. const char *elementData, // element data, null if none NxI32 lineno) // line number in the source XML file { bool ret = true; if ( elementData ) { NxI32 len = 0; NxI32 blobId = 0; const char *blobName=0; NxI32 acount = argc/2; for (NxI32 i=0; i<acount; i++) { const char * atr = argv[i*2]; const char * value = argv[i*2+1]; if ( strcmp(atr,"blob") == 0 ) { blobName = value; } else if ( strcmp(atr,"blobId") == 0 ) { blobId = atoi(value); } else if ( strcmp(atr,"len") == 0 ) { len = atoi(value); } } { if ( strcmp(elementName,"telnetBlob") == 0 ) { Blob *check = locateBlob(blobId,mClient); assert(check==0); assert(blobName); // assert(len > 0 ); if ( len > 0 && check == 0 && blobName ) { Blob *b = MEMALLOC_NEW(Blob)(blobName,mClient,blobId,len,elementData); mBlobs.push_back(b); } } else if ( strcmp(elementName,"telnetBlobData") == 0 ) { Blob *b = locateBlob(blobId,mClient); if ( b ) { b->addData(elementData); } } else if ( strcmp(elementName,"telnetBlobEnd") == 0 ) { Blob *b = locateBlob(blobId,mClient); if ( b ) { b->addDataEnd(elementData); } } } } return ret; } Blob * locateBlob(NxU32 id,NxU32 client) const { Blob *ret = 0; if ( id != 0 ) { BlobList::const_iterator i; for (i=mBlobs.begin(); i!=mBlobs.end(); i++) { Blob *b = (*i); if ( b->getId() == id && b->mClient == client ) { ret = b; break; } } } return ret; } private: NxU32 mClient; NxU32 mBlobId; BlobIOInterface *mCallback; FastXml *mFastXml; Blob *mLastBlob; BlobList mBlobs; }; BlobIO * createBlobIO(BlobIOInterface *iface) { MyBlobIO * m = MEMALLOC_NEW(MyBlobIO)(iface); return static_cast< BlobIO *>(m); } void releaseBlobIO(BlobIO *b) { MyBlobIO *m = static_cast< MyBlobIO *>(b); delete m; } //****************************************************** //*** Mutex layer //****************************************************** class OdfMutex { public: OdfMutex(void); ~OdfMutex(void); public: // Blocking Lock. void Lock(void); // Non-blocking Lock. Return's false if already locked. bool TryLock(void); // Unlock. void Unlock(void); private: #if defined(WIN32) || defined(_XBOX) CRITICAL_SECTION m_Mutex; #elif defined(__APPLE__) || defined(LINUX) pthread_mutex_t m_Mutex; #endif }; OdfMutex::OdfMutex(void) { #if defined(WIN32) || defined(_XBOX) InitializeCriticalSection(&m_Mutex); #elif defined(__APPLE__) || defined(LINUX) pthread_mutex_init(&m_Mutex, 0); #endif } OdfMutex::~OdfMutex(void) { #if defined(WIN32) || defined(_XBOX) DeleteCriticalSection(&m_Mutex); #elif defined(__APPLE__) || defined(LINUX) pthread_mutex_destroy(&m_Mutex); #endif } // Blocking Lock. void OdfMutex::Lock(void) { #if defined(WIN32) || defined(_XBOX) EnterCriticalSection(&m_Mutex); #elif defined(__APPLE__) || defined(LINUX) pthread_mutex_lock(&m_Mutex); #endif } // Non-blocking Lock. Return's false if already locked. bool OdfMutex::TryLock(void) { bool bRet = false; #if defined(WIN32) || defined(_XBOX) //assert(("TryEnterCriticalSection seems to not work on XP???", 0)); bRet = TryEnterCriticalSection(&m_Mutex) ? true : false; #elif defined(__APPLE__) || defined(LINUX) pthread_mutex_trylock(&m_Mutex) #endif return bRet; } // Unlock. void OdfMutex::Unlock(void) { #if defined(WIN32) || defined(_XBOX) LeaveCriticalSection(&m_Mutex); #elif defined(__APPLE__) || defined(LINUX) pthread_mutex_unlock(&m_Mutex) #endif } //****************************************************** //*** End Of Mutex layer //****************************************************** //****************************************************** //*** Threading layer //****************************************************** class OdfThread { protected: // Called when the thread is started. This method runs on the Thread. virtual void OnThreadExecute(void)=0; public: OdfThread(void); virtual ~OdfThread(void); public: // Start execution of the thread. void ThreadExecute(void); // Wait for the Thread to terminate. void ThreadWait(void); // Stop the thread's execution (not safe). void ThreadKill(void); protected: // Safely Quit the thread. void ThreadQuit(void); private: HANDLE m_hThread; friend static DWORD WINAPI _ODFThreadFunc(LPVOID arg); }; static DWORD WINAPI _ODFThreadFunc(LPVOID arg) { ((OdfThread *)arg)->OnThreadExecute(); return 0; } OdfThread::OdfThread(void) { m_hThread = 0; } OdfThread::~OdfThread(void) { assert(!m_hThread); } // Start execution of the thread. void OdfThread::ThreadExecute(void) { if(!m_hThread) { m_hThread = CreateThread(0, 0, _ODFThreadFunc, this, 0, 0); } } // Wait for the Thread to terminate. void OdfThread::ThreadWait(void) { if(m_hThread) { WaitForSingleObject(m_hThread, INFINITE); } } // Safely Quit the thread. void OdfThread::ThreadQuit(void) { if(m_hThread) { m_hThread = 0; ExitThread(0); } } // Stop the thread's execution (not safe). void OdfThread::ThreadKill(void) { if(m_hThread) { #if defined(WIN32) TerminateThread(m_hThread, 0); #endif #if defined(_XBOX) //-- TODO: Please figure out the equivalent of TerminateThread assert(false); #endif CloseHandle(m_hThread); m_hThread = 0; } } //****************************************************** //*** End of Threading layer //****************************************************** //****************************************************** //** The Telnet header file //****************************************************** class TelnetLineNode; typedef std::queue<TelnetLineNode*> TelnetLineNodeQueue; #ifdef WIN32 #pragma warning(push) #pragma warning(disable:4996) #endif // Common Telnet Functionality. class TelnetInterface { public: // Called when a connection has been established. virtual void OnConnect(NxU32 uiClient) { PushLine("NewConnection", uiClient ); } // Sends text across the telnet connection. // returns false on failure. virtual bool SendText(NxU32 uiClient, const char *pcLine, ...)=0; // Waits until there is a block ready to be read. bool WaitForBlock(void); // Pops the last line off the local queue. // returns 0 if no lines available. const char *GetLine(NxU32 &uiClient); protected: // Add a Line to the Local Queue. void PushLine(const char *pcLine, NxU32 uiClient); protected: TelnetInterface(void); TelnetInterface(const TelnetInterface&){} virtual ~TelnetInterface(void); private: OdfMutex m_LineMutex; TelnetLineNodeQueue m_Lines; char *m_pcLineBuffer; OdfMutex m_BlockMutex; OdfMutex m_HaveBlock; }; #ifdef WIN32 #pragma warning(pop) #endif //****************************************************** //** The Telnet header file //****************************************************** class TelnetLineNode : public NVSHARE::Memalloc { public: char *pcLine; NxU32 uiClient; }; // Pops the last line off the local queue. // returns 0 if no lines available. const char *TelnetInterface::GetLine(NxU32 &uiClient) { const char *pRet = 0; m_LineMutex.Lock(); if(!m_Lines.empty()) { TelnetLineNode *node = m_Lines.front(); m_Lines.pop(); if(m_pcLineBuffer) { ::free(m_pcLineBuffer); m_pcLineBuffer = 0; } m_pcLineBuffer = node->pcLine; uiClient = node->uiClient; delete node; pRet = m_pcLineBuffer; } m_LineMutex.Unlock(); return pRet; } // Add a Line to the Local Queue. void TelnetInterface::PushLine(const char *pcLine, NxU32 uiClient) { m_LineMutex.Lock(); TelnetLineNode *node = MEMALLOC_NEW(TelnetLineNode); node->pcLine = (char*)::malloc(sizeof(char)*(strlen(pcLine)+1)); strcpy(node->pcLine, pcLine); node->uiClient = uiClient; m_Lines.push(node); m_LineMutex.Unlock(); } TelnetInterface::TelnetInterface(void) { m_pcLineBuffer = 0; m_HaveBlock.Lock(); } TelnetInterface::~TelnetInterface(void) { if(m_pcLineBuffer) { ::free(m_pcLineBuffer); } while(!m_Lines.empty()) { TelnetLineNode *pLine = m_Lines.front(); ::free(pLine->pcLine); delete pLine; m_Lines.pop(); } m_HaveBlock.TryLock(); m_HaveBlock.Unlock(); } //************************************************************************************ //** The Telnet Parser header file. //************************************************************************************ typedef std::queue<char*> StringQueue; class _Block { public: void *m_pData; NxU32 m_uiDataSize; }; typedef std::queue<_Block> BlockQueue; class TelnetParser { public: TelnetParser(void) { m_uiBufferSize = 1024; m_uiBufferUsed = 0; m_pBuffer = (char *)::malloc(sizeof(char)*m_uiBufferSize); m_pcLastLine = 0; m_uiCurrBlockSize = 1024; m_uiCurrBlockUsed = 0; m_pCurrBlock = (char *)::malloc(sizeof(char)*m_uiCurrBlockSize); m_bBlockMode = false; } ~TelnetParser(void) { if(m_pBuffer) { ::free(m_pBuffer); } if(m_pcLastLine) { ::free(m_pcLastLine); } if(m_pCurrBlock) { ::free(m_pCurrBlock); } while(!m_Lines.empty()) { char *pTemp = m_Lines.front(); m_Lines.pop(); if(pTemp) { ::free(pTemp); } } while(!m_Blocks.empty()) { _Block &block = m_Blocks.front(); if(block.m_pData) { ::free(block.m_pData); } m_Blocks.pop(); } } public: void AddBuffer(const char *pcBuffer, NxU32 uiLen) { NxU32 uiNewSize = uiLen + m_uiBufferUsed; if(uiNewSize >= m_uiBufferSize) Resize(uiNewSize); for(NxU32 i=0; i<uiLen; i++) { if(m_bBlockMode) BlockChar(pcBuffer[i]); else ParseChar(pcBuffer[i]); } } const char *GetLine(void) { const char *pRet = 0; if(!m_Lines.empty()) { if(m_pcLastLine) { ::free(m_pcLastLine); } m_pcLastLine = m_Lines.front(); m_Lines.pop(); pRet = m_pcLastLine; } return pRet; } const void *GetBlock(NxU32 &uiSize) { void *pRet = 0; if(!m_Blocks.empty()) { _Block &block = m_Blocks.front(); pRet = block.m_pData; uiSize = block.m_uiDataSize; m_Blocks.pop(); } return pRet; } private: void ParseChar(char c) { if(c >= 32 && c < 128) { // simply add the character. m_pBuffer[m_uiBufferUsed++] = c; } else if(c == '\n' && m_uiBufferUsed) { // Add a line to the queue. char *pcLine = (char*)::malloc(sizeof(char)*(m_uiBufferUsed+1)); memcpy(pcLine, m_pBuffer, m_uiBufferUsed); pcLine[m_uiBufferUsed] = 0; m_Lines.push(pcLine); m_uiBufferUsed = 0; } else if(c == 8 && m_uiBufferUsed) { // if backspace then remove the last character. m_uiBufferUsed--; } else { // ??? } m_pBuffer[m_uiBufferUsed] = 0; char *pBlockStart = strstr(m_pBuffer, "<NxBlock"); if(pBlockStart) { char *equals = strchr(pBlockStart, '='); char *end = strchr(pBlockStart, '>'); if(end) { if(equals && equals < end) { char *name = equals+1; NxU32 len = (NxU32)(end - name) + 1; } m_bBlockMode = true; } } } void BlockChar(char c) { if(m_uiCurrBlockUsed+1 >= m_uiCurrBlockSize) { NxU32 uiNewSize = m_uiCurrBlockSize * 2; char *pBlock = (char*)::malloc(sizeof(char)*uiNewSize); memcpy(pBlock, m_pCurrBlock, m_uiCurrBlockUsed); if(m_pCurrBlock) { ::free(m_pCurrBlock); } m_pCurrBlock = pBlock; m_uiCurrBlockSize = uiNewSize; } m_pCurrBlock[m_uiCurrBlockUsed++] = c; m_pCurrBlock[m_uiCurrBlockUsed] = 0; char *pcEnd = strstr(m_pCurrBlock, "</NxBlock>"); if(pcEnd) { m_bBlockMode = false; NxU32 uiSize = (NxU32)(pcEnd - m_pCurrBlock); _Block block; block.m_uiDataSize = uiSize; block.m_pData = (char*)::malloc(sizeof(char)*uiSize); memcpy(block.m_pData, m_pCurrBlock, uiSize); m_Blocks.push(block); for(NxU32 i=uiSize+9; i<m_uiCurrBlockUsed; i++) { ParseChar(m_pCurrBlock[i]); } m_uiCurrBlockUsed = 0; } } void Resize(NxU32 uiNewSize) { char *pNewBuffer = (char*)::malloc(sizeof(char)*uiNewSize); if(m_uiBufferUsed) { memcpy(pNewBuffer, m_pBuffer, m_uiBufferUsed); } if(m_pBuffer) { ::free(m_pBuffer); } m_pBuffer = pNewBuffer; m_uiBufferSize = uiNewSize; } private: char *m_pBuffer; NxU32 m_uiBufferSize; NxU32 m_uiBufferUsed; char *m_pcLastLine; StringQueue m_Lines; bool m_bBlockMode; char *m_pCurrBlock; NxU32 m_uiCurrBlockSize; NxU32 m_uiCurrBlockUsed; BlockQueue m_Blocks; }; //**************************************************************************************** //** Telnet Client header file //**************************************************************************************** // Simple Telnet Client. class TelnetClient : public TelnetInterface, public NVSHARE::Memalloc { public: TelnetClient(void); virtual ~TelnetClient(void); public: // Connect to a remote Telnet server. // returns false on failure. bool Connect(const char *pcAddress, unsigned short uiPort); // Closes the current connection. void Close(void); public: // Sends text across the telnet connection. // returns false on failure. virtual bool SendText(NxU32 uiClient, const char *pcLine, ...); private: void ThreadFunc(void); friend DWORD WINAPI _TelnetClientFunc(LPVOID arg); private: TelnetClient(const TelnetClient &){} private: OdfMutex m_Mutex; SOCKET m_Socket; HANDLE m_Thread; }; //************************************************************************************* //** The Telnet Client source code //************************************************************************************* static DWORD WINAPI _TelnetClientFunc(LPVOID arg) { ((TelnetClient *)arg)->ThreadFunc(); ExitThread(0); return 0; } void TelnetClient::ThreadFunc(void) { bool bDone = false; m_Mutex.Lock(); SOCKET clientSocket = m_Socket; bDone = clientSocket == INVALID_SOCKET ? true : false; m_Mutex.Unlock(); #define BUFFER_SIZE 8192 char vcBuffer[BUFFER_SIZE+1]; TelnetParser parser; while(!bDone) { NxI32 iBytesRead = 0; iBytesRead = recv(clientSocket, vcBuffer, BUFFER_SIZE, 0); if(iBytesRead <= 0) { bDone = true; m_Mutex.Lock(); closesocket(clientSocket); clientSocket = INVALID_SOCKET; m_Socket = clientSocket; m_Mutex.Unlock(); } else { parser.AddBuffer(vcBuffer, iBytesRead); } const char *pcLine = 0; while((pcLine = parser.GetLine())) { PushLine(pcLine, 0); } m_Mutex.Lock(); clientSocket = m_Socket; bDone = clientSocket == INVALID_SOCKET ? true : false; m_Mutex.Unlock(); } } /***************** ** TelnetClient ** *****************/ TelnetClient::TelnetClient(void) { m_Socket = INVALID_SOCKET; m_Thread = 0; WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); } TelnetClient::~TelnetClient(void) { Close(); } // Connect to a remote Telnet server. // returns false on failure. bool TelnetClient::Connect(const char *pcAddress, unsigned short uiPort) { bool bRet = false; Close(); m_Thread = 0; #if defined(WIN32) m_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(m_Socket != INVALID_SOCKET) { sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_port = htons(uiPort); addr.sin_addr.s_addr = inet_addr(pcAddress); if(addr.sin_addr.s_addr == INADDR_NONE) { hostent *pHost = gethostbyname(pcAddress); memcpy(&addr.sin_addr, pHost->h_addr, pHost->h_length); addr.sin_family = pHost->h_addrtype; } if(connect(m_Socket, (sockaddr *)&addr, sizeof(addr)) == 0) { OnConnect(0); m_Thread = CreateThread(0, 0, _TelnetClientFunc, this, 0, 0); bRet = true; } if(!m_Thread) { NxI32 error = WSAGetLastError(); closesocket(m_Socket); m_Socket = INVALID_SOCKET; } } else { assert(0); } #endif return bRet; } // Closes the current connection. void TelnetClient::Close(void) { if(m_Socket != INVALID_SOCKET) { // Close the Socket. m_Mutex.Lock(); closesocket(m_Socket); m_Socket = INVALID_SOCKET; m_Mutex.Unlock(); // Wait for the Listen Thread to stop. WaitForSingleObject(m_Thread, INFINITE); m_Thread = 0; } } // Sends text across the telnet connection. // returns false on failure. bool TelnetClient::SendText(NxU32 uiClient, const char *pcLine, ...) { char vcBuffer[8192]; _vsnprintf(vcBuffer,8191, pcLine, (va_list)(&pcLine+1)); NxU32 uiLen = (NxU32)strlen(vcBuffer); send(m_Socket, vcBuffer, uiLen, 0); return true; } //**************************************************************************** //** Telnet server header file //*************************************************************************** class TelnetServer_Client; typedef std::map<NxU32, TelnetServer_Client*> TelnetServer_ClientMap; // Simple Telnet Server. class TelnetServer : public TelnetInterface, public NVSHARE::Memalloc { friend class TelnetServer_Client; public: TelnetServer(void); ~TelnetServer(void); public: // Starts the Telnet server listening on // the specified port. // returns false if failure. bool Listen(unsigned short uiPort); // Closes all connections. void Close(void); public: // Sends text across the telnet connection. // returns false on failure. virtual bool SendText(NxU32 uiClient, const char *pcLine, ...); private: void ThreadFunc(void); friend DWORD WINAPI _TelnetServerFunc(LPVOID arg); private: TelnetServer(const TelnetServer &){} private: NxU32 m_uiLastClient; OdfMutex m_ListenMutex; SOCKET m_ListenSocket; HANDLE m_ListenThread; TelnetServer_ClientMap m_Clients; }; //**************************************************************************** //** Telnet server source //**************************************************************************** class TelnetServer_Client : public NVSHARE::Memalloc { public: TelnetServer *m_pParent; NxU32 m_uiClient; OdfMutex m_Mutex; SOCKET m_Socket; HANDLE m_Thread; public: ~TelnetServer_Client(void) { TelnetServer_ClientMap::iterator iter; iter = m_pParent->m_Clients.find(m_uiClient); if(iter != m_pParent->m_Clients.end()) { m_pParent->m_Clients[m_uiClient] = 0; //m_pParent->m_Clients.erase(iter); } } private: void ThreadFunc(void); friend DWORD WINAPI _TelnetServerClientFunc(LPVOID arg); }; /********************** ** Threading Support ** **********************/ static DWORD WINAPI _TelnetServerClientFunc(LPVOID arg) { TelnetServer_Client *pClient = (TelnetServer_Client *)arg; pClient->ThreadFunc(); delete pClient; ExitThread(0); return 0; } static DWORD WINAPI _TelnetServerFunc(LPVOID arg) { ((TelnetServer *)arg)->ThreadFunc(); ExitThread(0); return 0; } void TelnetServer_Client::ThreadFunc(void) { bool bDone = false; OdfMutex &mutex = m_Mutex; #define BUFFER_SIZE 8192 char vcBuffer[BUFFER_SIZE]; TelnetParser parser; mutex.Lock(); SOCKET clientSocket = m_Socket; bDone = clientSocket == INVALID_SOCKET ? true : false; mutex.Unlock(); while(!bDone) { NxI32 iBytesRead=0; #if !defined(_XBOX) iBytesRead = recv(clientSocket, vcBuffer, BUFFER_SIZE, 0); #endif if(iBytesRead > 0) { parser.AddBuffer(vcBuffer, iBytesRead); } const char *pcLine = 0; while((pcLine = parser.GetLine())) { m_pParent->PushLine(pcLine, m_uiClient); } mutex.Lock(); clientSocket = m_Socket; bDone = clientSocket == INVALID_SOCKET ? true : false; mutex.Unlock(); } } void TelnetServer::ThreadFunc(void) { bool bDone = false; m_ListenMutex.Lock(); SOCKET listenSocket = m_ListenSocket; bDone = listenSocket == INVALID_SOCKET ? true : false; m_ListenMutex.Unlock(); while(!bDone) { SOCKET clientSocket= INVALID_SOCKET; #if !defined(_XBOX) clientSocket = accept(listenSocket, 0, 0); #endif if(clientSocket != INVALID_SOCKET) { TelnetServer_Client *pClient = MEMALLOC_NEW(TelnetServer_Client); pClient->m_pParent = this; pClient->m_uiClient = ++m_uiLastClient; pClient->m_Socket = clientSocket; m_Clients[pClient->m_uiClient] = pClient; pClient->m_Thread = CreateThread(0, 0, _TelnetServerClientFunc, pClient, 0, 0); OnConnect(pClient->m_uiClient); } m_ListenMutex.Lock(); listenSocket = m_ListenSocket; bDone = listenSocket == INVALID_SOCKET ? true : false; m_ListenMutex.Unlock(); } TelnetServer_ClientMap::iterator iter; for(iter=m_Clients.begin(); iter!=m_Clients.end(); iter++) { TelnetServer_Client *pClient = (*iter).second; if(pClient) { OdfMutex &mutex = pClient->m_Mutex; // Signal the socket. mutex.Lock(); #if !defined(_XBOX) closesocket(pClient->m_Socket); #endif pClient->m_Socket = INVALID_SOCKET; mutex.Unlock(); // Wait for the thread to stop. WaitForSingleObject(pClient->m_Thread, INFINITE); } } m_Clients.clear(); } /***************** ** TelnetServer ** *****************/ TelnetServer::TelnetServer(void) { m_uiLastClient = 1; m_ListenSocket = INVALID_SOCKET; m_ListenThread = 0; #if !defined(_XBOX) WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); #endif } TelnetServer::~TelnetServer(void) { Close(); } // Starts the Telnet server listening on // the specified port. // returns false if failure. bool TelnetServer::Listen(unsigned short uiPort) { bool bRet = false; Close(); m_ListenThread = 0; #if !defined(_XBOX) m_ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(m_ListenSocket != INVALID_SOCKET) { sockaddr_in addr = {0}; addr.sin_family = AF_INET; addr.sin_port = htons(uiPort); addr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(m_ListenSocket, (sockaddr*)&addr, sizeof(addr)) == 0) { if(listen(m_ListenSocket, SOMAXCONN) == 0) { m_ListenThread = CreateThread(0, 0, _TelnetServerFunc, this, 0, 0); bRet = true; } else { NxI32 error = WSAGetLastError(); assert(0); } } else // if(bind(m_ListenSocket, (sockaddr*)&addr, sizeof(addr)) == 0) { NxI32 error = WSAGetLastError(); // assert(0); } if(!m_ListenThread) { NxI32 error = WSAGetLastError(); closesocket(m_ListenSocket); m_ListenSocket = INVALID_SOCKET; } } else // if(m_ListenSocket != INVALID_SOCKET) { NxI32 error = WSAGetLastError(); assert(0); } // assert(m_ListenSocket != INVALID_SOCKET); #endif return bRet; } // Closes all connections. void TelnetServer::Close(void) { if(m_ListenSocket != INVALID_SOCKET) { // Close the Socket. m_ListenMutex.Lock(); #if !defined(_XBOX) closesocket(m_ListenSocket); #endif m_ListenSocket = INVALID_SOCKET; m_ListenMutex.Unlock(); // Wait for the Listen Thread to stop. WaitForSingleObject(m_ListenThread, INFINITE); m_ListenThread = 0; } } // Sends text across the telnet connection. // returns false on failure. bool TelnetServer::SendText(NxU32 uiClient, const char *pcLine, ...) { bool bRet = false; TelnetServer_ClientMap::iterator iter; char vcBuffer[8192]; _vsnprintf(vcBuffer, 8191, pcLine, (va_list)(&pcLine+1)); NxU32 uiLen = (NxU32)strlen(vcBuffer); if(!uiClient) { for(iter=m_Clients.begin(); iter!=m_Clients.end(); iter++) { TelnetServer_Client *pClient = (*iter).second; pClient->m_Mutex.Lock(); #if !defined(_XBOX) send(pClient->m_Socket, vcBuffer, uiLen, 0); #endif pClient->m_Mutex.Unlock(); bRet = true; } } else { iter = m_Clients.find(uiClient); if(iter != m_Clients.end()) { TelnetServer_Client *pClient = (*iter).second; pClient->m_Mutex.Lock(); #if !defined(_XBOX) send(pClient->m_Socket, vcBuffer, uiLen, 0); #endif pClient->m_Mutex.Unlock(); bRet = true; } } return bRet; } #if defined(__APPLE__) || defined(__CELLOS_LV2__) || defined(LINUX) #define stricmp(a, b) strcasecmp((a), (b)) #endif /*******************************************************************/ /******************** InParser.h ********************************/ /*******************************************************************/ class InPlaceParserInterface { public: virtual NxI32 ParseLine(NxI32 lineno,NxI32 argc,const char **argv) =0; // return TRUE to continue parsing, return FALSE to abort parsing process }; enum SeparatorType { ST_DATA, // is data ST_HARD, // is a hard separator ST_SOFT, // is a soft separator ST_EOS // is a comment symbol, and everything past this character should be ignored }; class InPlaceParser { public: InPlaceParser(void) { Init(); } InPlaceParser(char *data,NxI32 len) { Init(); SetSourceData(data,len); } InPlaceParser(const char *fname) { Init(); SetFile(fname); } ~InPlaceParser(void); void Init(void) { mQuoteChar = 34; mData = 0; mLen = 0; mMyAlloc = false; for (NxI32 i=0; i<256; i++) { mHard[i] = ST_DATA; mHardString[i*2] = (char)i; mHardString[i*2+1] = 0; } mHard[0] = ST_EOS; mHard[32] = ST_SOFT; mHard[9] = ST_SOFT; mHard[13] = ST_SOFT; mHard[10] = ST_SOFT; } void SetFile(const char *fname); // use this file as source data to parse. void SetSourceData(char *data,NxI32 len) { mData = data; mLen = len; mMyAlloc = false; }; NxI32 Parse(InPlaceParserInterface *callback); // returns true if entire file was parsed, false if it aborted for some reason NxI32 ProcessLine(NxI32 lineno,char *line,InPlaceParserInterface *callback); const char ** GetArglist(char *source,NxI32 &count); // convert source string into an arg list, this is a destructive parse. void SetHardSeparator(char c) // add a hard separator { mHard[c] = ST_HARD; } void SetHard(char c) // add a hard separator { mHard[c] = ST_HARD; } void SetCommentSymbol(char c) // comment character, treated as 'end of string' { mHard[c] = ST_EOS; } void ClearHardSeparator(char c) { mHard[c] = ST_DATA; } void DefaultSymbols(void); // set up default symbols for hard seperator and comment symbol of the '#' character. bool EOS(char c) { if ( mHard[c] == ST_EOS ) { return true; } return false; } void SetQuoteChar(char c) { mQuoteChar = c; } private: inline char * AddHard(NxI32 &argc,const char **argv,char *foo); inline bool IsHard(char c); inline char * SkipSpaces(char *foo); inline bool IsWhiteSpace(char c); inline bool IsNonSeparator(char c); // non seperator,neither hard nor soft bool mMyAlloc; // whether or not *I* allocated the buffer and am responsible for deleting it. char *mData; // ascii data to parse. NxI32 mLen; // length of data SeparatorType mHard[256]; char mHardString[256*2]; char mQuoteChar; }; /*******************************************************************/ /******************** InParser.cpp ********************************/ /*******************************************************************/ void InPlaceParser::SetFile(const char *fname) { if ( mMyAlloc ) { ::free(mData); } mData = 0; mLen = 0; mMyAlloc = false; FILE *fph = fopen(fname,"rb"); if ( fph ) { fseek(fph,0L,SEEK_END); mLen = ftell(fph); fseek(fph,0L,SEEK_SET); if ( mLen ) { mData = (char *) ::malloc(sizeof(char)*(mLen+1)); NxI32 ok = (NxI32)fread(mData, mLen, 1, fph); if ( !ok ) { ::free(mData); mData = 0; } else { mData[mLen] = 0; // zero byte terminate end of file marker. mMyAlloc = true; } } fclose(fph); } } InPlaceParser::~InPlaceParser(void) { if ( mMyAlloc ) { ::free(mData); } } #define MAXARGS 512 bool InPlaceParser::IsHard(char c) { return mHard[c] == ST_HARD; } char * InPlaceParser::AddHard(NxI32 &argc,const char **argv,char *foo) { while ( IsHard(*foo) ) { const char *hard = &mHardString[*foo*2]; if ( argc < MAXARGS ) { argv[argc++] = hard; } foo++; } return foo; } bool InPlaceParser::IsWhiteSpace(char c) { return mHard[c] == ST_SOFT; } char * InPlaceParser::SkipSpaces(char *foo) { while ( !EOS(*foo) && IsWhiteSpace(*foo) ) foo++; return foo; } bool InPlaceParser::IsNonSeparator(char c) { if ( !IsHard(c) && !IsWhiteSpace(c) && c != 0 ) return true; return false; } NxI32 InPlaceParser::ProcessLine(NxI32 lineno,char *line,InPlaceParserInterface *callback) { NxI32 ret = 0; const char *argv[MAXARGS]; NxI32 argc = 0; char *foo = line; while ( !EOS(*foo) && argc < MAXARGS ) { foo = SkipSpaces(foo); // skip any leading spaces if ( EOS(*foo) ) break; if ( *foo == mQuoteChar ) // if it is an open quote { foo++; if ( argc < MAXARGS ) { argv[argc++] = foo; } while ( !EOS(*foo) && *foo != mQuoteChar ) foo++; if ( !EOS(*foo) ) { *foo = 0; // replace close quote with zero byte EOS foo++; } } else { foo = AddHard(argc,argv,foo); // add any hard separators, skip any spaces if ( IsNonSeparator(*foo) ) // add non-hard argument. { bool quote = false; if ( *foo == mQuoteChar ) { foo++; quote = true; } if ( argc < MAXARGS ) { argv[argc++] = foo; } if ( quote ) { while (*foo && *foo != mQuoteChar ) foo++; if ( *foo ) *foo = 32; } // continue..until we hit an eos .. while ( !EOS(*foo) ) // until we hit EOS { if ( IsWhiteSpace(*foo) ) // if we hit a space, stomp a zero byte, and exit { *foo = 0; foo++; break; } else if ( IsHard(*foo) ) // if we hit a hard separator, stomp a zero byte and store the hard separator argument { const char *hard = &mHardString[*foo*2]; *foo = 0; if ( argc < MAXARGS ) { argv[argc++] = hard; } foo++; break; } foo++; } // end of while loop... } } } if ( argc ) { ret = callback->ParseLine(lineno, argc, argv ); } return ret; } NxI32 InPlaceParser::Parse(InPlaceParserInterface *callback) // returns true if entire file was parsed, false if it aborted for some reason { assert( callback ); if ( !mData ) return 0; NxI32 ret = 0; NxI32 lineno = 0; char *foo = mData; char *begin = foo; while ( *foo ) { if ( *foo == 10 || *foo == 13 ) { lineno++; *foo = 0; if ( *begin ) // if there is any data to parse at all... { NxI32 v = ProcessLine(lineno,begin,callback); if ( v ) ret = v; } foo++; if ( *foo == 10 ) foo++; // skip line feed, if it is in the carraige-return line-feed format... begin = foo; } else { foo++; } } lineno++; // lasst line. NxI32 v = ProcessLine(lineno,begin,callback); if ( v ) ret = v; return ret; } void InPlaceParser::DefaultSymbols(void) { SetHardSeparator(','); SetHardSeparator('('); SetHardSeparator(')'); SetHardSeparator('<'); SetHardSeparator('>'); SetHardSeparator(':'); SetHardSeparator('='); SetHardSeparator('['); SetHardSeparator(']'); SetHardSeparator('{'); SetHardSeparator('}'); SetCommentSymbol('#'); } const char ** InPlaceParser::GetArglist(char *line,NxI32 &count) // convert source string into an arg list, this is a destructive parse. { const char **ret = 0; static const char *argv[MAXARGS]; NxI32 argc = 0; char *foo = line; while ( !EOS(*foo) && argc < MAXARGS ) { foo = SkipSpaces(foo); // skip any leading spaces if ( EOS(*foo) ) break; if ( *foo == mQuoteChar ) // if it is an open quote { foo++; if ( argc < MAXARGS ) { argv[argc++] = foo; } while ( !EOS(*foo) && *foo != mQuoteChar ) foo++; if ( !EOS(*foo) ) { *foo = 0; // replace close quote with zero byte EOS foo++; } } else { foo = AddHard(argc,argv,foo); // add any hard separators, skip any spaces if ( IsNonSeparator(*foo) ) // add non-hard argument. { bool quote = false; if ( *foo == mQuoteChar ) { foo++; quote = true; } if ( argc < MAXARGS ) { argv[argc++] = foo; } if ( quote ) { while (*foo && *foo != mQuoteChar ) foo++; if ( *foo ) *foo = 32; } // continue..until we hit an eos .. while ( !EOS(*foo) ) // until we hit EOS { if ( IsWhiteSpace(*foo) ) // if we hit a space, stomp a zero byte, and exit { *foo = 0; foo++; break; } else if ( IsHard(*foo) ) // if we hit a hard separator, stomp a zero byte and store the hard separator argument { const char *hard = &mHardString[*foo*2]; *foo = 0; if ( argc < MAXARGS ) { argv[argc++] = hard; } foo++; break; } foo++; } // end of while loop... } } } count = argc; if ( argc ) { ret = argv; } return ret; } #define MAXPARSEBUFFER 2048 class BlobLine { public: BlobLine(NxU32 client,const char *msg) { mClient = client; size_t l = strlen(msg); mBlobText = (char *)MEMALLOC_MALLOC(l+1); memcpy(mBlobText,msg,l+1); } ~BlobLine(void) { MEMALLOC_FREE(mBlobText); } BlobLine(const BlobLine &b) { mClient = b.mClient; size_t l = strlen(b.mBlobText); mBlobText = (char *)MEMALLOC_MALLOC(l+1); memcpy(mBlobText,b.mBlobText,l+1); } NxU32 mClient; char *mBlobText; }; typedef std::queue< BlobLine > BlobLineQueue; class MyTelnet : public NVSHARE::Telnet, public BlobIOInterface, public NVSHARE::Memalloc { public: MyTelnet(NVSHARE::TelnetType type,const char *address,NxU32 port) { mBlobIO = createBlobIO(this); mParser.DefaultSymbols(); mClient = 0; mInterface = 0; mServer = 0; mIsServer = false; mHaveConnection = false; if ( type == NVSHARE::TT_SERVER_ONLY || type == NVSHARE::TT_CLIENT_OR_SERVER ) { mServer = MEMALLOC_NEW(TelnetServer); mIsServer = mServer->Listen(port); mHaveConnection = true; } if ( mIsServer ) { mInterface = static_cast< TelnetInterface *>(mServer); } else if ( type == NVSHARE::TT_CLIENT_ONLY || type == NVSHARE::TT_CLIENT_OR_SERVER ) { delete mServer; mServer = 0; mClient = MEMALLOC_NEW(TelnetClient); mHaveConnection = mClient->Connect(address,port); if ( !mHaveConnection ) { delete mClient; mClient = 0; } else { mInterface = static_cast< TelnetInterface *>(mClient); } } } virtual bool isServer(void) // returns true if we are a server or a client. First one created on a machine is a server, additional copies are clients. { return mIsServer; } virtual bool haveConnection(void) { return mHaveConnection; } virtual bool sendMessage(NxU32 client,const char *fmt,...) { bool ret = false; if ( mInterface ) { char wbuff[MAXPARSEBUFFER]; wbuff[MAXPARSEBUFFER-1] = 0; _vsnprintf(wbuff,MAXPARSEBUFFER-1, fmt, (char *)(&fmt+1)); ret = mInterface->SendText(client,"%s",wbuff); } return ret; } virtual const char * receiveMessage(NxU32 &client) { const char *ret = 0; client = 0; if ( !mBlobLines.empty() ) { BlobLine &bl = mBlobLines.front(); mInterface->SendText(bl.mClient,"%s", bl.mBlobText ); mBlobLines.pop(); } if ( mInterface ) { ret = mInterface->GetLine(client); if ( ret && mBlobIO ) { bool snarfed = mBlobIO->processIncomingBlobText(client,ret); if ( snarfed ) { ret = 0; } } } return ret; } virtual const char ** getArgs(const char *input,NxU32 &argc) // parse string into a series of arguments. { strncpy(mParseBuffer,input,MAXPARSEBUFFER); mParseBuffer[MAXPARSEBUFFER-1] = 0; NxI32 ac; const char **ret = mParser.GetArglist(mParseBuffer,ac); argc = (NxU32)ac; return ret; } virtual ~MyTelnet(void) { delete mClient; delete mServer; releaseBlobIO(mBlobIO); } virtual bool sendBlob(NxU32 client,const char *blobType,const void *data,NxU32 dlen) { bool ret = false; if ( mBlobIO ) { ret = mBlobIO->sendBlob(client,blobType,data,dlen); } return ret; } virtual const char * receiveBlob(NxU32 &client,const void *&data,NxU32 &dlen) { const char *ret = 0; client = 0; dlen = 0; data = 0; if ( mBlobIO ) { ret = mBlobIO->receiveBlob(client,data,dlen); } return ret; } virtual void sendBlobText(NxU32 client,const char *fmt,...) { if ( mInterface ) { char wbuff[MAXPARSEBUFFER]; wbuff[MAXPARSEBUFFER-1] = 0; _vsnprintf(wbuff,MAXPARSEBUFFER-1, fmt, (char *)(&fmt+1)); BlobLine bl(client,wbuff); mBlobLines.push(bl); if ( mBlobIO ) { mBlobIO->processIncomingBlobText(client,wbuff); } } } private: bool mIsServer; bool mHaveConnection; TelnetInterface *mInterface; TelnetClient *mClient; TelnetServer *mServer; char mParseBuffer[MAXPARSEBUFFER]; InPlaceParser mParser; BlobIO *mBlobIO; BlobLineQueue mBlobLines; }; }; // end of namespace namespace NVSHARE { Telnet * createTelnet(TelnetType type,const char *address,NxU32 port) { TELNET_NVSHARE::MyTelnet *m = MEMALLOC_NEW(TELNET_NVSHARE::MyTelnet)(type,address,port); return static_cast< Telnet *>(m); } void releaseTelnet(Telnet *t) { TELNET_NVSHARE::MyTelnet *m = static_cast< TELNET_NVSHARE::MyTelnet *>(t); delete m; } }; // end of namespace #endif
[ "jratcliffscarab@f10ad84c-df75-11dd-bd7b-b12b6590754f" ]
jratcliffscarab@f10ad84c-df75-11dd-bd7b-b12b6590754f
4b54ac3694b9303753d2877c795eb3c285b77e53
c0c44b30d6a9fd5896fd3dce703c98764c0c447f
/cpp/Targets/MapLibNG/Shared/src/MemoryDBufRequester.cpp
1b04deff6df3fb50f7d692ff566816f449a2407c
[ "BSD-3-Clause" ]
permissive
wayfinder/Wayfinder-CppCore-v2
59d703b3a9fdf4a67f9b75fbbf4474933aeda7bf
f1d41905bf7523351bc0a1a6b08d04b06c533bd4
refs/heads/master
2020-05-19T15:54:41.035880
2010-06-29T11:56:03
2010-06-29T11:56:03
744,294
1
0
null
null
null
null
UTF-8
C++
false
false
7,249
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MemoryDBufRequester.h" #include "BitBuffer.h" #undef WRITE_TO_FILE #ifdef WRITE_TO_FILE # include <stdio.h> #endif using namespace std; MemoryDBufRequester::MemoryDBufRequester(DBufRequester* parent, uint32 maxMem) : DBufRequester(parent) { m_maxMem = maxMem; m_usedMem = 0; m_requesterType = OriginType::MEMORY; } MemoryDBufRequester::~MemoryDBufRequester() { #ifdef WRITE_TO_FILE FILE* file = fopen("MapFile.dump", "w"); // Write size of maps little endian. Oh. uint32 nbrMaps = m_buffers.size(); fwrite( &nbrMaps, 4, 1, file ); #endif // delete the saved buffers. for( storage_t::iterator it = m_buffers.begin(); it != m_buffers.end(); ++it ) { #ifdef WRITE_TO_FILE const MC2SimpleString& curDesc = it->first; const BitBuffer* curBuf = it->second; BitBuffer tempBuf( 4 + curDesc.length() + 4 + curBuf->getBufferSize() ); tempBuf.writeNextBALong( curDesc.length() ); tempBuf.writeNextByteArray( (const byte*)curDesc.c_str(), curDesc.length() ); tempBuf.writeNextBALong( curBuf->getBufferSize() ); tempBuf.writeNextByteArray( curBuf->getBufferAddress(), curBuf->getBufferSize() ); fwrite( tempBuf.getBufferAddress(), tempBuf.getBufferSize(), 1, file ); #endif DBufRequester::release(it->first, it->second); } #ifdef WRITE_TO_FILE fclose(file); #endif m_buffers.clear(); m_bufferLookup.clear(); } uint32 MemoryDBufRequester::getMemUse(const stringBufPair_t& entry) const { // A less optimistic size calculation than the old one. return 8 + 8 + 4 + entry.first.length() + entry.second->getBufferSize(); } void MemoryDBufRequester::setMaxSize( uint32 size ) { m_maxMem = size; } void MemoryDBufRequester::clearCache() { uint32 oldMem = m_maxMem; m_maxMem = 0; deleteOldMapsIfNecessary(); m_maxMem = oldMem; } void MemoryDBufRequester::internalRemove( const MC2SimpleString& descr ) { bufferMap_t::iterator findit = m_bufferLookup.find( &descr ); if ( findit != m_bufferLookup.end() ) { mc2log << "[MDBR]: Removing " << descr << " from storage" << endl; erase( findit ); } } bool MemoryDBufRequester::private_insert(const MC2SimpleString& descr, BitBuffer* buffer) { bufferMap_t::iterator findit = m_bufferLookup.find( &descr ); if ( findit == m_bufferLookup.end() ) { // Not there - insert right away // Add to the list storage_t::iterator listit = m_buffers.insert(m_buffers.end(), make_pair(descr, buffer)); // Add the pointer to the string and the iterator in the list // to the lookup map. m_bufferLookup.insert(make_pair(&(listit->first), listit) ); m_usedMem += getMemUse(*listit); return true; } else { // Delete the buffer since it is not deemed trustworthy BitBuffer* tmp = findit->second->second; erase(findit); delete tmp; // We don't do it this way anymore since we do not want // invalid buffers to propagate into any caches. We used // to release the buffer to the next requester in the past // Erase the buffer and insert it. // // storage_t::iterator listit = findit->second; // stringBufPair_t pair( *listit ); // DBufRequester::release( pair.first, pair.second ); return private_insert(descr, buffer); } // Cannot happen return false; } void MemoryDBufRequester::erase(bufferMap_t::iterator it) { storage_t::iterator lit = it->second; m_usedMem -= getMemUse(*lit); m_bufferLookup.erase(it); m_buffers.erase(lit); } void MemoryDBufRequester::erase(storage_t::iterator it) { // If not found in map, then it will be problems. erase(m_bufferLookup.find(&(it->first))); } BitBuffer* MemoryDBufRequester::requestCached(const MC2SimpleString& descr) { bufferMap_t::iterator it = m_bufferLookup.find( &descr ); if ( it != m_bufferLookup.end() ) { // Use the iterator in the map to find the buffer. BitBuffer* buf = it->second->second; buf->reset(); // Remove it from our storage. erase( it ); return buf; } else { return DBufRequester::requestCached(descr); } } void MemoryDBufRequester::deleteOldMapsIfNecessary() { while ( m_usedMem > m_maxMem && !m_buffers.empty() ) { // Delete first in list (oldest) storage_t::iterator lit = m_buffers.begin(); // Copy the pair since the flow of the program can lead us // back into insert. stringBufPair_t bufPair(*lit); erase( lit ); DBufRequester::release(bufPair.first, bufPair.second); } #ifdef MC2_SYSTEM // Check that the tracking of sizes work when running mc2. uint32 sum = 0; for( storage_t::iterator it = m_buffers.begin(); it != m_buffers.end(); ++it ) { sum += getMemUse(*it); } MC2_ASSERT( sum == m_usedMem ); #endif } MemoryDBufRequester::stringBufPair_t& MemoryDBufRequester::front() { return *(m_buffers.begin()); } void MemoryDBufRequester::pop_front() { // Delete first in list (oldest) storage_t::iterator lit = m_buffers.begin(); erase( lit ); } void MemoryDBufRequester::release(const MC2SimpleString& descr, BitBuffer* buffer) { // Insert the buffer into the storage if ( buffer != NULL ) { private_insert(descr, buffer); } // Keep track of mem use deleteOldMapsIfNecessary(); }
[ "hlars@sema-ovpn-morpheus.itinerary.com" ]
hlars@sema-ovpn-morpheus.itinerary.com
a5e53e2bc6a1275ee08b4528d92cfb95b4afaeb2
437a7f75d55785d1caf4da7324cceddfd79077c6
/Source/Clip2Tri/Public/Clip2TriFunctionLibrary.h
5c7594e2c5df118dd7cef9c32948a172d6fe2861
[]
no_license
GeorgeR/Clip2Tri
e29bfb09f16b3baffdc93632d8963568cc598143
1dcc966bcb6bfe45ce46c6559ccf210e33d4d248
refs/heads/master
2022-09-13T12:09:46.956877
2019-07-13T03:00:39
2019-07-13T03:00:39
193,871,924
1
0
null
null
null
null
UTF-8
C++
false
false
442
h
#pragma once #include "Kismet/BlueprintFunctionLibrary.h" #include "Clip2TriFunctionLibrary.generated.h" UCLASS() class CLIP2TRI_API UClip2TriFunctionLibrary : public UBlueprintFunctionLibrary { GENERATED_BODY() public: UFUNCTION(BlueprintCallable, Category = "Mesh") static void Triangulate(const TArray<FVector>& InPoints, TArray<FVector>& OutVertices, TArray<int32>& OutTriangles, TArray<int32>& OutBounds, bool bFlip = false); };
[ "dukecg@gmail.com" ]
dukecg@gmail.com
7a25d8a7b4b0bb753b78416c9e685b0ae420a2bf
bbac5636696840f1050afcc9a6d6e44e606b3687
/src/gcell.h
fe9bcc5b2640e5eb5feb88fdf5b71eb0bca8891c
[ "BSD-3-Clause" ]
permissive
tetra12/RePlAce
622ba8e94512f67dea896efbb4c04aec92d54c47
b38ef77a29346f03c1d64aaddb70cda8e0fd1e8d
refs/heads/master
2020-04-13T03:00:43.305411
2018-12-27T19:31:37
2018-12-27T19:31:37
162,919,039
0
0
BSD-3-Clause
2018-12-23T19:41:23
2018-12-23T19:41:23
null
UTF-8
C++
false
false
3,713
h
/////////////////////////////////////////////////////////////////////////////// // Authors: Ilgweon Kang and Lutong Wang // (respective Ph.D. advisors: Chung-Kuan Cheng, Andrew B. Kahng), // based on Dr. Jingwei Lu with ePlace and ePlace-MS // // Many subsequent improvements were made by Mingyu Woo // leading up to the initial release. // // BSD 3-Clause License // // Copyright (c) 2018, The Regents of the University of California // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #ifndef __GCELL__ #define __GCELL__ #include "global.h" class mypos { public: float x; float y; }; struct TILE { struct FPOS pmin; struct FPOS pmax; struct FPOS center; struct POS p; prec h_usage; prec v_usage; prec tmp_h_usage; prec tmp_v_usage; int pincnt; std::vector<int> cap; // new std::vector<int> blkg; // new //std::vector<std::vector<struct FPOS> > block_interval; // new std::vector<std::vector<mypos> > block_interval; // new std::vector<int> route; // new prec infl_ratio; // new std::vector<int> h_gr_usage_per_layer_l; std::vector<int> h_gr_usage_per_layer_r; std::vector<int> v_gr_usage_per_layer_l; std::vector<int> v_gr_usage_per_layer_r; int h_gr_usage_total; int v_gr_usage_total; // igkang // leftedge = 1 // rightedge = 2 prec h_supply2; prec v_supply2; prec h_supply; prec v_supply; prec area; prec h_inflation_ratio; prec v_inflation_ratio; prec inflation_area_thisTile; prec inflation_area_delta_thisTile; prec cell_area_befo_bloating_thisTile; prec inflatedRatio_thisTile; bool is_macro_included; }; void tile_init_cGP2D (); void get_blockage(); void get_interval_length(); void adjust_edge_cap(); void tile_clear (); void tile_reset_gr_usages (); void get_gr_usages_total (); #endif
[ "mgwoo@unist.ac.kr" ]
mgwoo@unist.ac.kr
246842e7983e9462751d96502d1f373cec2e5e97
2e18a47ce569a8f69b720e37f90a23792da0ad45
/Source Code/EECS441-1/eventKind.pb.h
e1ca8ee7f788716b8f39091c78de50b26809c51d
[]
no_license
jessupjn/WriteMe
fafd20dffac649a84adcbc58c271543515c5a0f1
5f07dcefad39c0354ac3393db32f5600f3b47d06
refs/heads/master
2016-09-06T02:45:23.115803
2014-02-04T16:38:27
2014-02-04T16:38:27
null
0
0
null
null
null
null
UTF-8
C++
false
true
7,358
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: eventKind.proto #ifndef PROTOBUF_eventKind_2eproto__INCLUDED #define PROTOBUF_eventKind_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 2005000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/generated_message_util.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) // Internal implementation detail -- do not call these. void protobuf_AddDesc_eventKind_2eproto(); void protobuf_AssignDesc_eventKind_2eproto(); void protobuf_ShutdownFile_eventKind_2eproto(); class chalkBoard; // =================================================================== class chalkBoard : public ::google::protobuf::Message { public: chalkBoard(); virtual ~chalkBoard(); chalkBoard(const chalkBoard& from); inline chalkBoard& operator=(const chalkBoard& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const chalkBoard& default_instance(); void Swap(chalkBoard* other); // implements Message ---------------------------------------------- chalkBoard* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const chalkBoard& from); void MergeFrom(const chalkBoard& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string changes = 1 [default = ""]; inline bool has_changes() const; inline void clear_changes(); static const int kChangesFieldNumber = 1; inline const ::std::string& changes() const; inline void set_changes(const ::std::string& value); inline void set_changes(const char* value); inline void set_changes(const char* value, size_t size); inline ::std::string* mutable_changes(); inline ::std::string* release_changes(); inline void set_allocated_changes(::std::string* changes); // optional int32 where = 2 [default = 0]; inline bool has_where() const; inline void clear_where(); static const int kWhereFieldNumber = 2; inline ::google::protobuf::int32 where() const; inline void set_where(::google::protobuf::int32 value); // @@protoc_insertion_point(class_scope:chalkBoard) private: inline void set_has_changes(); inline void clear_has_changes(); inline void set_has_where(); inline void clear_has_where(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::std::string* changes_; ::google::protobuf::int32 where_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(2 + 31) / 32]; friend void protobuf_AddDesc_eventKind_2eproto(); friend void protobuf_AssignDesc_eventKind_2eproto(); friend void protobuf_ShutdownFile_eventKind_2eproto(); void InitAsDefaultInstance(); static chalkBoard* default_instance_; }; // =================================================================== // =================================================================== // chalkBoard // optional string changes = 1 [default = ""]; inline bool chalkBoard::has_changes() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void chalkBoard::set_has_changes() { _has_bits_[0] |= 0x00000001u; } inline void chalkBoard::clear_has_changes() { _has_bits_[0] &= ~0x00000001u; } inline void chalkBoard::clear_changes() { if (changes_ != &::google::protobuf::internal::kEmptyString) { changes_->clear(); } clear_has_changes(); } inline const ::std::string& chalkBoard::changes() const { return *changes_; } inline void chalkBoard::set_changes(const ::std::string& value) { set_has_changes(); if (changes_ == &::google::protobuf::internal::kEmptyString) { changes_ = new ::std::string; } changes_->assign(value); } inline void chalkBoard::set_changes(const char* value) { set_has_changes(); if (changes_ == &::google::protobuf::internal::kEmptyString) { changes_ = new ::std::string; } changes_->assign(value); } inline void chalkBoard::set_changes(const char* value, size_t size) { set_has_changes(); if (changes_ == &::google::protobuf::internal::kEmptyString) { changes_ = new ::std::string; } changes_->assign(reinterpret_cast<const char*>(value), size); } inline ::std::string* chalkBoard::mutable_changes() { set_has_changes(); if (changes_ == &::google::protobuf::internal::kEmptyString) { changes_ = new ::std::string; } return changes_; } inline ::std::string* chalkBoard::release_changes() { clear_has_changes(); if (changes_ == &::google::protobuf::internal::kEmptyString) { return NULL; } else { ::std::string* temp = changes_; changes_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); return temp; } } inline void chalkBoard::set_allocated_changes(::std::string* changes) { if (changes_ != &::google::protobuf::internal::kEmptyString) { delete changes_; } if (changes) { set_has_changes(); changes_ = changes; } else { clear_has_changes(); changes_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); } } // optional int32 where = 2 [default = 0]; inline bool chalkBoard::has_where() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void chalkBoard::set_has_where() { _has_bits_[0] |= 0x00000002u; } inline void chalkBoard::clear_has_where() { _has_bits_[0] &= ~0x00000002u; } inline void chalkBoard::clear_where() { where_ = 0; clear_has_where(); } inline ::google::protobuf::int32 chalkBoard::where() const { return where_; } inline void chalkBoard::set_where(::google::protobuf::int32 value) { set_has_where(); where_ = value; } // @@protoc_insertion_point(namespace_scope) #ifndef SWIG namespace google { namespace protobuf { } // namespace google } // namespace protobuf #endif // SWIG // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_eventKind_2eproto__INCLUDED
[ "jessupjn@umich.edu" ]
jessupjn@umich.edu
6c8d04e5e52d55c190a0e70f02efa49d23acfbc9
11431fbde88431d2de5c465dd20becf14b95dce6
/Amber/src/Amber/Renderer/RenderCommand.cpp
25d26f183489d66eec59e986c3d2ca58ecaa5e84
[ "Apache-2.0" ]
permissive
muthubro/Amber
9f060fbe9cdce045b67ce2daa6809e5427741c6a
076db07de87d9231c59416114ac40ab9712aa697
refs/heads/master
2022-12-12T05:02:04.150445
2020-09-01T03:20:39
2020-09-01T03:20:39
260,773,227
0
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
#include "abpch.h" #include "RenderCommand.h" #include <glad/glad.h> #include "Amber/Platform/OpenGL/OpenGLRendererAPI.h" namespace Amber { Scope<RendererAPI> RenderCommand::s_RendererAPI = RendererAPI::Create(); }
[ "muth4muathasim@gmail.com" ]
muth4muathasim@gmail.com
6f858377ee18fbb66a37f3744cc431752902ff65
002a2717a38337186b0ce2455965d89a89e4ed0e
/duyetTru.cpp
d8920f8ed1206d01b31359cac236ea4a9e656662
[]
no_license
domiee13/TRR2
cc0cc3f7be665c75f3674344ccaeb128fde4b3a9
d8f9ee945b192c7eb64b7615c77e0ad097819df8
refs/heads/master
2022-07-06T09:17:37.450051
2020-05-16T23:40:00
2020-05-16T23:40:00
258,083,499
0
0
null
null
null
null
UTF-8
C++
false
false
2,935
cpp
#include <iostream> #include <fstream> #include <string> #include <stack> #define MAX 100 using namespace std; class doThi{ int n; int A[MAX][MAX]; public: int s; bool chuaxet[MAX]; void khoiTao(); void Reset(); void nhap1Dinh(); bool docDuLieu(string filename); void DFS(int u); //DFS stack bool isDuyetHet(); //Check xem DFS/BFS co duyet het cac phan tu khong bool stronglyConnective(); void duyetTru(); }; void doThi::khoiTao(){ for(int i = 1;i<=n;i++){ chuaxet[i] = true; } } void doThi::Reset(){ for(int i = 1;i<=n;i++){ chuaxet[i] = true; } } void doThi::nhap1Dinh(){ cout<<"s = "; cin>>s; } bool doThi::docDuLieu(string filename){ ifstream inp(filename.c_str(),ios::in); if(inp.is_open()){ inp>>n; cout<<"So dinh cua do thi la: "<<n<<endl; cout<<"Ma tran ke: "<<endl; for(int i = 1;i<=n;i++){ for(int j = 1;j<=n;j++){ inp>>A[i][j]; cout<<A[i][j]<<" "; } cout<<endl; } return true; } return false; } void doThi::DFS(int u){ stack<int> nganxep; nganxep.push(u); cout<<u<<" "; chuaxet[u] = false; while(!nganxep.empty()){ int u = nganxep.top(); nganxep.pop(); for(int t = 1;t<=n;t++){ if(chuaxet[t] && A[u][t]){ nganxep.push(u); nganxep.push(t); cout<<t<<" "; chuaxet[t]=false; break; } } } cout<<endl; } //ham nay xac dinh xem DFS(u) hoac BFS(u) co duyet het duoc cac dinh ko? // tra lai gia tri true neu DFS(u)=V hoac BFS(u)=V <=> chuaxet[1..n]=false bool doThi::isDuyetHet(){ for(int i = 1;i<=n;i++){ if(chuaxet[i]) return false; } return true; } //Xet xem do thi co lien thong manh hay khong ( kiem tra DFS(BFS) //voi moi dinh u thuoc do thi) bool doThi::stronglyConnective(){ for(int u = 1;u<=n;u++){ cout<<"Duyet DFS tu dinh "<<u<<": "<<endl; DFS(u); if(!isDuyetHet()){ cout<<"Do thi khong lien thong manh"<<endl; return false; } Reset(); } cout<<"Do thi lien thong manh"<<endl; return true; } void doThi::duyetTru(){ Reset(); for(int u = 1;u<=n;u++){ chuaxet[u] = false; if(u==1){ cout<<"Duyet DFS tu dinh 2: "<<endl; DFS(2); } else{ cout<<"Duyet DFS tu dinh 1: "<<endl; DFS(1); } if(!isDuyetHet()){ cout<<"Dinh "<<u<<" la dinh tru."<<endl; } // else cout<<"Dinh "<<u<<" khong la dinh tru."<<endl; Reset(); } } int main(){ doThi G; if(G.docDuLieu("3_6_DinhTru.inp")){ G.khoiTao(); G.duyetTru(); } return 0; }
[ "dungngocmd@gmail.com" ]
dungngocmd@gmail.com
fa7ddb4c7f07b056613d1e82bbb7f6c11aec4e16
a462d375164907ab13e8af31603fef1b448ace09
/src/cli/utils.h
93e31b5b2257bf1e90ee12c07efb777de1931ae2
[]
no_license
jeanlauliac/upd
3a460c9c0ba4a8ac17431a9ef141779b7638ad09
2e76b7cf3ddb06fc727d7fb7bb1b2426234bcea5
refs/heads/master
2021-01-21T17:30:10.906601
2018-07-29T15:16:41
2018-07-29T15:16:41
91,959,612
1
0
null
null
null
null
UTF-8
C++
false
false
617
h
#pragma once #include <iostream> #include <sstream> #include <vector> namespace upd { namespace cli { std::string ansi_sgr(std::vector<size_t> sgr_codes, bool use_color); std::string ansi_sgr(size_t sgr_code, bool use_color); template <typename OStream> OStream &ansi_sgr(OStream &os, std::vector<size_t> sgr_codes, bool use_color) { return os << ansi_sgr(sgr_codes, use_color); } template <typename OStream> OStream &fatal_error(OStream &os, bool use_color) { os << "upd: "; ansi_sgr(os, {31}, use_color) << "fatal:"; return ansi_sgr(os, {0}, use_color) << ' '; } } // namespace cli } // namespace upd
[ "jean@lauliac.com" ]
jean@lauliac.com
0727896c570d671955a7ace5f67675e24506f4e1
ef60541c0ff67e7a356503cc04908ccdb35abc8f
/frameworks/runtime-src/Classes/tiledMap/TmxUtil.cpp
594d14105db7f2d7e267a551818839fbc82ccc8c
[]
no_license
soon14/sanguomobile2
c059561770e2782f21ab188a5a7c56a3e57bc475
3d95cd96acf9ae625b087db112571a6741d8fdd7
refs/heads/master
2022-02-19T18:24:45.010644
2017-11-21T09:27:45
2017-11-21T09:27:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,739
cpp
//----------------------------------------------------------------------------- // TmxUtil.cpp // // Copyright (c) 2010-2014, Tamir Atias // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL TAMIR ATIAS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: Tamir Atias //----------------------------------------------------------------------------- #include <stdlib.h> #include <algorithm> #include <cctype> #include <functional> #ifdef USE_MINIZ #define MINIZ_HEADER_FILE_ONLY #include "miniz.c" #else #include <zlib.h> #endif #include <stdio.h> #include "TmxUtil.h" #include "cocos2d.h" static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } static std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0; (i < 4); i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while ((i++ < 3)) ret += '='; } return ret; } static std::string 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::string 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 += 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 += char_array_3[j]; } return ret; } namespace Tmx { // trim from start static inline std::string &ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } // trim from end static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } // trim from both ends static inline std::string &trim(std::string &s) { return ltrim(rtrim(s)); } std::string &Util::Trim(std::string &str) { return trim( str ); } std::string Util::DecodeBase64(const std::string &str) { return base64_decode(str); } char *Util::DecompressGZIP(const char *data, int dataSize, int expectedSize) { int bufferSize = expectedSize; int ret; z_stream strm; char *out = (char*)malloc(bufferSize); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.next_in = (Bytef*)data; strm.avail_in = dataSize; strm.next_out = (Bytef*)out; strm.avail_out = bufferSize; ret = inflateInit2(&strm, 15 + 32); if (ret != Z_OK) { free(out); return NULL; } do { ret = inflate(&strm, Z_SYNC_FLUSH); switch (ret) { case Z_NEED_DICT: case Z_STREAM_ERROR: ret = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&strm); free(out); return NULL; } if (ret != Z_STREAM_END) { out = (char *) realloc(out, bufferSize * 2); if (!out) { inflateEnd(&strm); free(out); return NULL; } strm.next_out = (Bytef *)(out + bufferSize); strm.avail_out = bufferSize; bufferSize *= 2; } } while (ret != Z_STREAM_END); if (strm.avail_in != 0) { free(out); return NULL; } inflateEnd(&strm); return out; } }
[ "chenhlb8055@gmail.com" ]
chenhlb8055@gmail.com
79435350f305456f53e38b9dc68918d99aef5d0f
66ed96884f5852c37bcc24b6ed37e7f6b5838317
/2754 - Saída 8 - URI Online Judge.cpp
cfaaf7b5f317e120537539698353772ac21e700b
[ "MIT" ]
permissive
Vinicius-Reis-da-Silva/problemas-resolvidos-de-maratonas
18328ba44c423626c7b2c4a51ec5c77ca484c100
6d4ff4bc8b9fd103c79c4d4b54b8e0805240ee99
refs/heads/master
2023-03-27T00:18:15.522088
2021-03-29T16:48:10
2021-03-29T16:48:10
253,654,271
1
0
null
null
null
null
ISO-8859-1
C++
false
false
806
cpp
#include<iostream> using namespace std; void imprimir(double x , double y); int main() { setlocale(LC_ALL,"Portuguese"); double x=234.345 , y=45.698; imprimir(x ,y); cout << scientific << x << " - " << y << endl; /* COLACA NA NOTAÇÃO CIENTIFICA COM BASE "e" */ cout << uppercase << x << " - " << y << endl; /* COLACA NA NOTAÇÃO CIENTIFICA COM BASE "E" */ cout.unsetf(ios::scientific); /* RETIRA DA NOTAÇÃO CIENTIFICA */ cout.precision(3); cout.setf(ios::fixed); cout << x << " - " << y << endl; cout << x << " - " << y << endl; return 0; } void imprimir(double x , double y){ cout.precision(6); cout.setf(ios::fixed); cout << x << " - " << y << endl; for(int i=0 ; i<4 ; i++){ cout.precision(i); cout << x << " - " << y << endl; } }
[ "viniciusreissilva808@gmail.com" ]
viniciusreissilva808@gmail.com
e0ff6a57a210425e4ff61faf14a9c830a3b92210
5ae2c8dbf694df0ff3bd0bbd24c6851eab0c2ea0
/src/node1_radarinterface/src/mmWaveDataHdl.cpp
9c3f789e0bc5fdfa93932c0f919fb9a94c3e4ec4
[]
no_license
YiShan8787/mm-clustering
1fe2a435e0b9eb075beeda94750192abe4deed65
63e25b9060dba63cbd1d079968624b76ffa40609
refs/heads/master
2023-01-31T05:46:10.233992
2020-12-09T07:23:41
2020-12-09T07:23:41
294,165,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,957
cpp
#include "mmWaveDataHdl.hpp" #include "DataHandlerClass.h" namespace node1_radarinterface { PLUGINLIB_EXPORT_CLASS(node1_radarinterface::mmWaveDataHdl, nodelet::Nodelet); mmWaveDataHdl::mmWaveDataHdl() {} void mmWaveDataHdl::onInit() { //ros::NodeHandle private_nh = getPrivateNodeHandle(); ros::NodeHandle private_nh("~"); std::string mySerialPort; std::string myFrameID; int myBaudRate; int myMaxAllowedElevationAngleDeg; int myMaxAllowedAzimuthAngleDeg; if (!private_nh.hasParam("data_port")) { ROS_INFO("No param named 'data_port'"); } private_nh.getParam("data_port", mySerialPort); private_nh.getParam("data_rate", myBaudRate); private_nh.getParam("frame_id", myFrameID); if (!(private_nh.getParam("max_allowed_elevation_angle_deg", myMaxAllowedElevationAngleDeg))) { myMaxAllowedElevationAngleDeg = 90; // Use max angle if none specified } if (!(private_nh.getParam("max_allowed_azimuth_angle_deg", myMaxAllowedAzimuthAngleDeg))) { myMaxAllowedAzimuthAngleDeg = 90; // Use max angle if none specified } ROS_INFO("mmWaveDataHdl: data_port = %s", mySerialPort.c_str()); ROS_INFO("mmWaveDataHdl: data_rate = %d", myBaudRate); ROS_INFO("mmWaveDataHdl: max_allowed_elevation_angle_deg = %d", myMaxAllowedElevationAngleDeg); ROS_INFO("mmWaveDataHdl: max_allowed_azimuth_angle_deg = %d", myMaxAllowedAzimuthAngleDeg); DataUARTHandler DataHandler(&private_nh); DataHandler.setFrameID( (char*) myFrameID.c_str() ); DataHandler.setUARTPort( (char*) mySerialPort.c_str() ); DataHandler.setBaudRate( myBaudRate ); DataHandler.setMaxAllowedElevationAngleDeg( myMaxAllowedElevationAngleDeg ); DataHandler.setMaxAllowedAzimuthAngleDeg( myMaxAllowedAzimuthAngleDeg ); DataHandler.start(); NODELET_DEBUG("mmWaveDataHdl: Finished onInit function"); } }
[ "59713684gx@gmail.com" ]
59713684gx@gmail.com
c7ff9f8914a53d1c615d1bf1ff9228e805991b02
1e30370ece8c98169154c3104a873626e7fed0dc
/VirtualCluster/VirtualCluster/opSplit.cpp
46cfee74eae65625b50b43b8ca7c494b4c2d6c45
[]
no_license
amelieczhou/myvirutalcluster
abefb29f3a8123a0ddd07e87c1743ab6ce1bb61d
b2ceed6a28c8962aaff38afc331a5da063e46e24
refs/heads/master
2016-09-06T01:48:30.275674
2013-09-09T03:02:51
2013-09-09T03:02:51
32,119,966
0
0
null
null
null
null
UTF-8
C++
false
false
19,365
cpp
#include "stdafx.h" #include "ConsolidateOperators.h" double opSplit(vector<VM*>* VM_queue, vector<Job*> jobs,bool checkcost, bool estimate, bool timeorcost) { if(timeorcost) return 0; bool dosplit = false; double costsplit = 0; vector<vector<VM*> > VM_queue_backup; for(int i=0; i<types; i++){ vector<VM*> vms; for(int j=0; j<VM_queue[i].size(); j++){ VM* vm = new VM(); *vm = *VM_queue[i][j]; vm->assigned_tasks.clear(); for(int out=0; out<VM_queue[i][j]->assigned_tasks.size(); out++){ vector<taskVertex*> tasks; for(int in=0; in<VM_queue[i][j]->assigned_tasks[out].size(); in++){ taskVertex* task = new taskVertex(); *task = *VM_queue[i][j]->assigned_tasks[out][in]; tasks.push_back(task); if(task->end_time < task->start_time) printf(""); } vm->assigned_tasks.push_back(tasks); } vms.push_back(vm); } VM_queue_backup.push_back(vms); } vector<Job*> jobs_backup; for(int i=0; i<jobs.size(); i++) { Job* job=new Job(jobs[i]->g); jobs_backup.push_back(job); } double initialcost = 0; for(int i=0; i<types; i++) for(int j=0; j<VM_queue[i].size(); j++) initialcost += priceOnDemand[i]*VM_queue[i][j]->life_time/60.0; pair<vertex_iter, vertex_iter> vp; updateVMqueue(VM_queue); //first consider split the tasks on the same VM but with very large gap //case2: split a task to different VMs to use their residual time for(int i=0; i<types; i++){ for(int j=0; j<VM_queue[i].size(); j++){ if(VM_queue[i][j]->assigned_tasks.size() == 1){ //find vms in vm queue i that the sum of their residual time is enough for task j execution for(int k1=0; k1<VM_queue[i].size(); k1++){ if(k1 != j && VM_queue[i][k1]->start_time + VM_queue[i][k1]->life_time > VM_queue[i][j]->start_time){ //put j to the end of k1 double moveafter1 = VM_queue[i][k1]->end_time - VM_queue[i][j]->start_time; if(moveafter1 <= 0) moveafter1 =0; bool deadlineok1 = true; for(int in=0; in<VM_queue[i][j]->assigned_tasks[0].size(); in++){ double exetime = VM_queue[i][j]->assigned_tasks[0][in]->end_time - VM_queue[i][j]->assigned_tasks[0][in]->start_time; double oldestTime = VM_queue[i][j]->assigned_tasks[0][in]->estTime[VM_queue[i][j]->assigned_tasks[0][in]->assigned_type]; VM_queue[i][j]->assigned_tasks[0][in]->start_time += moveafter1; VM_queue[i][j]->assigned_tasks[0][in]->estTime[VM_queue[i][j]->assigned_tasks[0][in]->assigned_type] = exetime; deadlineok1 = time_flood(jobs[VM_queue[i][j]->assigned_tasks[0][in]->job_id],VM_queue[i][j]->assigned_tasks[0][in]->name); VM_queue[i][j]->assigned_tasks[0][in]->estTime[VM_queue[i][j]->assigned_tasks[0][in]->assigned_type] = oldestTime; if(!deadlineok1) break; } if(!deadlineok1){ //site recovery for(int t=0; t<types; t++) for(int s=0; s<VM_queue_backup[t].size(); s++){ deepcopy(VM_queue[t][s], VM_queue_backup[t][s]); } continue;//try next vm k1 in queue i } updateVMqueue(VM_queue); vector<vector<VM*> > VM_queue_state; for(int iiter=0; iiter<types; iiter++){ vector<VM*> vms; for(int jiter=0; jiter<VM_queue[iiter].size(); jiter++){ VM* vm = new VM(); *vm = *VM_queue[iiter][jiter]; vm->assigned_tasks.clear(); for(int out=0; out<VM_queue[iiter][jiter]->assigned_tasks.size(); out++){ vector<taskVertex*> tasks; for(int in=0; in<VM_queue[iiter][jiter]->assigned_tasks[out].size(); in++){ taskVertex* task = new taskVertex(); *task = *VM_queue[iiter][jiter]->assigned_tasks[out][in]; tasks.push_back(task); if(task->end_time < task->start_time) printf(""); if(task->name != VM_queue_backup[iiter][jiter]->assigned_tasks[out][in]->name) printf(""); } vm->assigned_tasks.push_back(tasks); } vms.push_back(vm); } VM_queue_state.push_back(vms); } int splittask = -1, splitindex = -1; //sort(VM_queue[i][j]->assigned_tasks[0].begin(),VM_queue[i][j]->assigned_tasks[0].end(),taskfunction); vector<int> first_names, second_names; for(int in=0; in<VM_queue[i][j]->assigned_tasks[0].size(); in++){ if(VM_queue[i][k1]->start_time+VM_queue[i][k1]->life_time >= VM_queue[i][j]->assigned_tasks[0][in]->end_time) first_names.push_back(in); else second_names.push_back(in); if(VM_queue[i][k1]->start_time + VM_queue[i][k1]->life_time > VM_queue[i][j]->assigned_tasks[0][in]->start_time && VM_queue[i][k1]->start_time + VM_queue[i][k1]->life_time < VM_queue[i][j]->assigned_tasks[0][in]->end_time) {splittask = in;} if(in<VM_queue[i][j]->assigned_tasks[0].size()-1){ if(VM_queue[i][k1]->start_time + VM_queue[i][k1]->life_time >= VM_queue[i][j]->assigned_tasks[0][in]->end_time && VM_queue[i][k1]->start_time + VM_queue[i][k1]->life_time <= VM_queue[i][j]->assigned_tasks[0][in+1]->start_time) {splitindex = in; } } //else{//in==VM_queue[i][j]->assigned_tasks[0].size()-1 // if(VM_queue[i][k1]->start_time + VM_queue[i][k1]->life_time >= VM_queue[i][j]->assigned_tasks[0][in]->end_time) // splitindex = in; //} } if(splittask == -1 && splitindex == -1){ //do not need to split a task, can put vm j entirely on vm k1 //double cost1=0; int numoftasks = VM_queue[i][j]->assigned_tasks[0].size(); //for(int ttype=0; ttype<types; ttype++) // for(int tsize=0; tsize<VM_queue[ttype].size(); tsize++) // cost1 += priceOnDemand[VM_queue[ttype][tsize]->type]*VM_queue[ttype][tsize]->life_time /60.0; double t1 = VM_queue[i][j]->end_time - VM_queue[i][j]->start_time; double t2 = VM_queue[i][k1]->end_time - VM_queue[i][k1]->start_time; double t3 = VM_queue[i][j]->end_time + moveafter1 - VM_queue[i][k1]->start_time; costsplit = move(i,t1,t2,t3); if(checkcost && estimate && costsplit>1e-12){ for(int t=0; t<types; t++){ for(int s=0; s<VM_queue_backup[t].size(); s++){ deepcopy(VM_queue[t][s], VM_queue_backup[t][s]); } } deepdelete(VM_queue_backup); deepdelete(VM_queue_state); return costsplit; }else if(checkcost && estimate){ //do nothing deepdelete(VM_queue_state); continue;//to the next k1 }else if(!(checkcost && estimate)){ //}else if(!estimate){ //if(costsplit>1e-12) { if(moveafter1 == 0) move_operation2(jobs, VM_queue[i][j], VM_queue[i][k1],0); else move_operation1(jobs, VM_queue[i][j], VM_queue[i][k1],0,moveafter1); bool update = updateVMqueue(VM_queue); double cost2=0; for(int ttype=0; ttype<types; ttype++) for(int tsize=0; tsize<VM_queue[ttype].size(); tsize++) cost2 += priceOnDemand[VM_queue[ttype][tsize]->type]*VM_queue[ttype][tsize]->life_time /60.0; if(cost2 >= initialcost){ vector<taskVertex*> tasks; for(int t=0; t<numoftasks; t++) { taskVertex* task = VM_queue[i][k1]->assigned_tasks[0].back(); VM_queue[i][k1]->assigned_tasks[0].pop_back(); tasks.push_back(task); } VM_queue[i][j]->assigned_tasks.push_back(tasks); //site recovery for(int t=0; t<types; t++){ //VM_queue[t].resize(VM_queue_backup[t].size()); for(int s=0; s<VM_queue_backup[t].size(); s++){ deepcopy(VM_queue[t][s], VM_queue_backup[t][s]); } } deepdelete(VM_queue_state); continue;//to the next k1 } else{ if(checkcost){ vector<taskVertex*> tasks; for(int t=0; t<numoftasks; t++) { taskVertex* task = VM_queue[i][k1]->assigned_tasks[0].back(); VM_queue[i][k1]->assigned_tasks[0].pop_back(); tasks.push_back(task); } VM_queue[i][j]->assigned_tasks.push_back(tasks); //site recovery for(int t=0; t<types; t++){ //VM_queue[t].resize(VM_queue_backup[t].size()); for(int s=0; s<VM_queue_backup[t].size(); s++){ deepcopy(VM_queue[t][s], VM_queue_backup[t][s]); } } deepdelete(VM_queue_backup); deepdelete(VM_queue_state); return initialcost-cost2; } VM_queue[i].erase(VM_queue[i].begin()+j); deepdelete(VM_queue_backup); deepdelete(VM_queue_state); if(moveafter1 == 0) printf("split move operation 2\n"); else printf("split move operation 1\n"); return initialcost-cost2; } //} } deepdelete(VM_queue_state); }else if(splittask == -1){ //do not need to split task, can put some of the tasks in vm j to vm k1 //find another vm to hold the rest part of vm j double starttime = VM_queue[i][j]->assigned_tasks[0][second_names[0]]->start_time; for(int sn=1; sn<second_names.size(); sn++) if(starttime>VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->start_time) starttime = VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->start_time; double endtime = 0; for(int fn=0; fn<first_names.size(); fn++) if(endtime<VM_queue[i][j]->assigned_tasks[0][first_names[fn]]->end_time) endtime=VM_queue[i][j]->assigned_tasks[0][first_names[fn]]->end_time; for(int k2=0; k2<VM_queue[i].size(); k2++){ if(k1!=k2 && k2!=j && VM_queue[i][k2]->start_time + VM_queue[i][k2]->life_time > starttime){ double moveafter2 = VM_queue[i][k2]->end_time - starttime; if(moveafter2 <0) moveafter2 = 0; bool deadlineok2 = true; //for(int in=splitindex+1; in<VM_queue[i][j]->assigned_tasks[0].size(); in++){ for(int sn=0; sn<second_names.size(); sn++){ double exetime = VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->end_time - VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->start_time; double oldestTime = VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->estTime[VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->assigned_type]; VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->start_time += moveafter2; VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->estTime[VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->assigned_type] = exetime; deadlineok2 = time_flood(jobs[VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->job_id],VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->name); VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->estTime[VM_queue[i][j]->assigned_tasks[0][second_names[sn]]->assigned_type] = oldestTime; if(!deadlineok2) break; } if(!deadlineok2){ //site recovery for(int t=0; t<types; t++) for(int s=0; s<VM_queue_backup[t].size(); s++){ deepcopy(VM_queue[t][s], VM_queue_state[t][s]); } continue;//try next vm k2 in queue i } double t1= VM_queue[i][j]->end_time - VM_queue[i][j]->start_time; double t2= VM_queue[i][k1]->end_time - VM_queue[i][k1]->start_time; double t3 = VM_queue[i][k2]->end_time - VM_queue[i][k2]->start_time; double t4 = VM_queue[i][j]->end_time + moveafter2 - VM_queue[i][k2]->start_time + endtime + moveafter1 - VM_queue[i][k1]->start_time; costsplit = (ceil(t1/60)+ceil(t2/60)+ceil(t3/60)-ceil(t4/60))*priceOnDemand[i]; if(checkcost && estimate && costsplit>1e-12){ for(int t=0; t<types; t++) for(int s=0; s<VM_queue_backup[t].size(); s++) deepcopy(VM_queue[t][s],VM_queue_state[t][s]); deepdelete(VM_queue_backup); deepdelete(VM_queue_state); return costsplit; }else if(checkcost && estimate){ for(int t=0; t<types; t++) for(int s=0; s<VM_queue_backup[t].size(); s++){ deepcopy(VM_queue[t][s], VM_queue_state[t][s]); } continue;//to the next k2 }else if(!(checkcost && estimate)){ //}else if(!estimate){ updateVMqueue(VM_queue); /*double cost1=0; for(int ttype=0; ttype<types; ttype++) for(int tsize=0; tsize<VM_queue[ttype].size(); tsize++) cost1 += priceOnDemand[VM_queue[ttype][tsize]->type]*VM_queue[ttype][tsize]->life_time /60.0;*/ int numoftasks = VM_queue[i][j]->assigned_tasks[0].size(); for(int sn=0; sn<first_names.size(); sn++){ taskVertex* task = VM_queue[i][j]->assigned_tasks[0][first_names[sn]]; VM_queue[i][k1]->assigned_tasks[0].push_back(task); } for(int sn=0; sn<second_names.size(); sn++){ taskVertex* task = VM_queue[i][j]->assigned_tasks[0][second_names[sn]]; VM_queue[i][k2]->assigned_tasks[0].push_back(task); } VM_queue[i][j]->assigned_tasks.clear(); VM_queue[i][j]->end_time=VM_queue[i][j]->start_time=VM_queue[i][j]->life_time=VM_queue[i][j]->resi_time=0; bool update = updateVMqueue(VM_queue); double cost2=0; for(int ttype=0; ttype<types; ttype++) for(int tsize=0; tsize<VM_queue[ttype].size(); tsize++) cost2 += priceOnDemand[VM_queue[ttype][tsize]->type]*VM_queue[ttype][tsize]->life_time /60.0; if(cost2>=initialcost){ vector<taskVertex*> tasks,tasks1; vector<taskVertex*> firsttasks, secondtasks; for(int sn=0; sn<first_names.size(); sn++){ taskVertex* task = VM_queue[i][k1]->assigned_tasks[0].back(); VM_queue[i][k1]->assigned_tasks[0].pop_back(); firsttasks.push_back(task); } reverse(firsttasks.begin(),firsttasks.end()); //for(int t=0; t<numoftasks-splitindex-1; t++){ for(int sn=0; sn<second_names.size(); sn++){ taskVertex* task = VM_queue[i][k2]->assigned_tasks[0].back(); VM_queue[i][k2]->assigned_tasks[0].pop_back(); secondtasks.push_back(task); } reverse(secondtasks.begin(),secondtasks.end()); for(int t=0; t<numoftasks; t++){ int tt=0; for(; tt<first_names.size(); tt++){ if(first_names[tt]==t){ taskVertex* task = firsttasks[tt]; tasks.push_back(task); break; } } if(tt==first_names.size()){ for(int ttt=0; ttt<second_names.size(); ttt++){ if(second_names[ttt]==t){ taskVertex* task = secondtasks[ttt]; tasks.push_back(task); } } } } /*for(int t=0; t<numoftasks; t++) { taskVertex* task=tasks.back(); tasks1.push_back(task); }*/ //tasks.clear(); VM_queue[i][j]->assigned_tasks.push_back(tasks); for(int t=0; t<types; t++) for(int s=0; s<VM_queue_backup[t].size(); s++) deepcopy(VM_queue[t][s],VM_queue_state[t][s]); continue; }else{ if(checkcost){ vector<taskVertex*> tasks,tasks1; //for(int t=0; t<splitindex+1; t++){ //for(int sn=0; sn<first_names.size(); sn++){ // taskVertex* task = VM_queue[i][k1]->assigned_tasks[0].back(); // VM_queue[i][k1]->assigned_tasks[0].pop_back(); // tasks.push_back(task); //} ////for(int t=0; t<numoftasks-splitindex-1; t++){ //for(int sn=0; sn<second_names.size(); sn++){ // taskVertex* task = VM_queue[i][k2]->assigned_tasks[0].back(); // VM_queue[i][k2]->assigned_tasks[0].pop_back(); // tasks.push_back(task); //} vector<taskVertex*> firsttasks, secondtasks; for(int sn=0; sn<first_names.size(); sn++){ taskVertex* task = VM_queue[i][k1]->assigned_tasks[0].back(); VM_queue[i][k1]->assigned_tasks[0].pop_back(); firsttasks.push_back(task); } reverse(firsttasks.begin(),firsttasks.end()); //for(int t=0; t<numoftasks-splitindex-1; t++){ for(int sn=0; sn<second_names.size(); sn++){ taskVertex* task = VM_queue[i][k2]->assigned_tasks[0].back(); VM_queue[i][k2]->assigned_tasks[0].pop_back(); secondtasks.push_back(task); } reverse(secondtasks.begin(),secondtasks.end()); for(int t=0; t<numoftasks; t++){ int tt=0; for(; tt<first_names.size(); tt++){ if(first_names[tt]==t){ taskVertex* task = firsttasks[tt]; tasks.push_back(task); break; } } if(tt==first_names.size()){ for(int ttt=0; ttt<second_names.size(); ttt++){ if(second_names[ttt]==t){ taskVertex* task = secondtasks[ttt]; tasks.push_back(task); } } } } //for(int t=numoftasks-1; t>=0; t--) //{ // taskVertex* task=tasks[t];//tasks.back(); // //tasks.pop_back(); // tasks1.push_back(task); //} // tasks.clear(); VM_queue[i][j]->assigned_tasks.push_back(tasks); for(int t=0; t<types; t++) for(int s=0; s<VM_queue_backup[t].size(); s++) deepcopy(VM_queue[t][s],VM_queue_state[t][s]); deepdelete(VM_queue_backup); deepdelete(VM_queue_state); return initialcost-cost2; } VM_queue[i].erase(VM_queue[i].begin()+j); deepdelete(VM_queue_backup); deepdelete(VM_queue_state); printf("split without split a task\n"); return initialcost-cost2; } } } }//for next k2 deepdelete(VM_queue_state); }//if splittask == -1 else if(splitindex == -1){ //need to split a task, what to do with the data structure??? deepdelete(VM_queue_state); } } }//k1 for breaktime1 } }//task j in VM type i }//type i for(int t=0; t<types; t++) for(int s=0; s<VM_queue_backup[t].size(); s++){ deepcopy(VM_queue[t][s], VM_queue_backup[t][s]); } deepdelete(VM_queue_backup); return 0; }
[ "andyzhang870914@gmail.com@d3054936-c4ef-e995-d082-c26fb22fccf5" ]
andyzhang870914@gmail.com@d3054936-c4ef-e995-d082-c26fb22fccf5
30ea1940675ad1793aec188396ccb522293a1930
8b9f3bfaf993e5c74eb14b8091b0ead3f7845747
/IO/vtk/include/checkPoint.h
4802c3969c523b7782f4f2d897638a2e29cbf1c6
[]
no_license
paralab/Dendro-KT
ccabf0cd165b3863fdb45006dc817690d288cefd
0d5d0d7ec454d2b14e0afd8563fd4f65426887c2
refs/heads/master
2023-07-27T12:59:11.730087
2019-05-21T17:04:56
2019-05-21T17:04:56
151,742,127
2
1
null
2022-09-26T21:57:06
2018-10-05T15:33:46
C++
UTF-8
C++
false
false
7,690
h
// // Created by milinda on 7/12/17. /** *@author Milinda Fernando *School of Computing, University of Utah *@brief Contans utility functions to save/load mesh (octree) and variable list defined on the otree. */ // #ifndef SFCSORTBENCH_CHECKPOINT_H #define SFCSORTBENCH_CHECKPOINT_H #include "TreeNode.h" #include "mesh.h" #include "json.hpp" #include <iostream> #include <fstream> using json = nlohmann::json; namespace io { namespace checkpoint { /** *@brief Write an given octree to a file using binary file format. *@param[in] fName: file name *@param[in] pNodes: pointer to the begin location of the octree *@param[in] num: size of pNodes array or number of elements to write. * @note than this will write the elements in the order that they have in pNodes array. * binary file format: * <number of elements><list of elements ...> **/ int writeOctToFile(const char * fName,const ot::TreeNode* pNodes,const unsigned int num); /** *@brief Reads an octree speficied by the file name. *param[in] fName: input file name *param[out] pNodes: TreeNodes read from the specified file. **/ int readOctFromFile(const char * fName,std::vector<ot::TreeNode> & pNodes); /** * @breif: writes the variable vector to a file in binary format. * @param[in] fName: input file name. * @param[in] pMesh: pointer to the mesh which the variable defined on * @param [in] vec: pointer to the begin location of the variable vector. * binary file format: * <vecsize><localBegin><localEnd><values..> * * */ template <typename T> int writeVecToFile(const char * fName, const ot::Mesh* pMesh,const T* vec); /** * @breif: writes the variable vectors to a file in binary format. * @param[in] fName: input file name. * @param[in] pMesh: pointer to the mesh which the variable defined on * @param [in] vec: pointer to variable vector * @param [in] numVars: number of variables * binary file format: * <vecsize><localBegin><localEnd><values..> * * */ template <typename T> int writeVecToFile(const char * fName, const ot::Mesh* pMesh,const T** vec,const unsigned int numVars); /** * @breif: reads variable vector from the binary file. * @param[in] fName: input file name. * @param[in] pMesh: pointer to the mesh which the variable defined on * @param [out] vec: pointer to the begin location of the variable vector.(assumes memory allocated) * */ template <typename T> int readVecFromFile(const char * fName, const ot::Mesh* pMesh, T* vec); /** * @breif: reads variable vectors from the binary file. * @param[in] fName: input file name. * @param[in] pMesh: pointer to the mesh which the variable defined on * @param [in] numVars: number of variables * @param [out] vec: pointer to the begin location of the variable vector.(assumes memory allocated) * */ template <typename T> int readVecFromFile(const char * fName, const ot::Mesh* pMesh, T** vec, const unsigned int numVars); } // end of namespace checkpoint. }// end of namespace io // templated implementations namespace io { namespace checkpoint { template <typename T> int writeVecToFile(const char * fName, const ot::Mesh* pMesh,const T* vec) { unsigned int numNodes=pMesh->getNumLocalMeshNodes()+pMesh->getNumPreMeshNodes()+pMesh->getNumPostMeshNodes(); unsigned int nLocalBegin=pMesh->getNodeLocalBegin(); unsigned int nLocalEnd=pMesh->getNodeLocalEnd(); FILE * outfile=fopen(fName,"w"); if(outfile==NULL){std::cout<<fName<<" file open failed "<<std::endl; return 1;} fwrite(&numNodes,sizeof(unsigned int ),1,outfile); fwrite(&nLocalBegin,sizeof(unsigned int ),1,outfile); fwrite(&nLocalEnd,sizeof(unsigned int ),1,outfile); if(numNodes>0) fwrite((vec+nLocalBegin),sizeof(T),pMesh->getNumLocalMeshNodes(),outfile); fclose(outfile); return 0; } template <typename T> int writeVecToFile(const char * fName, const ot::Mesh* pMesh,const T** vec,const unsigned int numVars) { unsigned int numNodes=pMesh->getNumLocalMeshNodes()+pMesh->getNumPreMeshNodes()+pMesh->getNumPostMeshNodes(); unsigned int nLocalBegin=pMesh->getNodeLocalBegin(); unsigned int nLocalEnd=pMesh->getNodeLocalEnd(); FILE * outfile=fopen(fName,"w"); if(outfile==NULL){std::cout<<fName<<" file open failed "<<std::endl; return 1;} fwrite(&numNodes,sizeof(unsigned int ),1,outfile); fwrite(&nLocalBegin,sizeof(unsigned int ),1,outfile); fwrite(&nLocalEnd,sizeof(unsigned int ),1,outfile); if(numNodes>0) for(unsigned int i=0;i<numVars;i++) fwrite((vec[i]+nLocalBegin),sizeof(T),pMesh->getNumLocalMeshNodes(),outfile); fclose(outfile); return 0; } template <typename T> int readVecFromFile(const char * fName, const ot::Mesh* pMesh,T* vec) { unsigned int numNodes,nLocalBegin,nLocalEnd; FILE * infile = fopen(fName,"r"); if(infile==NULL){std::cout<<fName<<" file open failed "<<std::endl; return 1;} fread(&numNodes,sizeof(unsigned int ),1,infile); fread(&nLocalBegin,sizeof(unsigned int ),1,infile); fread(&nLocalEnd,sizeof(unsigned int ),1,infile); if(numNodes!=(pMesh->getNumPreMeshNodes()+pMesh->getNumLocalMeshNodes()+pMesh->getNumPostMeshNodes())) {std::cout<<fName<<" file number of total node mismatched with the mesh. "<<std::endl; return 1;} if(nLocalBegin!=pMesh->getNodeLocalBegin()) {std::cout<<fName<<" file local node begin location mismatched with the mesh. "<<std::endl; return 1;} if(nLocalEnd!=pMesh->getNodeLocalEnd()) {std::cout<<fName<<" file local node end location mismatched with the mesh. "<<std::endl; return 1;} if(numNodes>0) fread((vec+nLocalBegin),sizeof(T),pMesh->getNumLocalMeshNodes(),infile); fclose(infile); return 0; } template <typename T> int readVecFromFile(const char * fName, const ot::Mesh* pMesh, T** vec, const unsigned int numVars) { unsigned int numNodes,nLocalBegin,nLocalEnd; FILE * infile = fopen(fName,"r"); if(infile==NULL){std::cout<<fName<<" file open failed "<<std::endl; return 1;} fread(&numNodes,sizeof(unsigned int ),1,infile); fread(&nLocalBegin,sizeof(unsigned int ),1,infile); fread(&nLocalEnd,sizeof(unsigned int ),1,infile); if(numNodes!=(pMesh->getNumPreMeshNodes()+pMesh->getNumLocalMeshNodes()+pMesh->getNumPostMeshNodes())) {std::cout<<fName<<" file number of total node mismatched with the mesh. "<<std::endl; return 1;} if(nLocalBegin!=pMesh->getNodeLocalBegin()) {std::cout<<fName<<" file local node begin location mismatched with the mesh. "<<std::endl; return 1;} if(nLocalEnd!=pMesh->getNodeLocalEnd()) {std::cout<<fName<<" file local node end location mismatched with the mesh. "<<std::endl; return 1;} if(numNodes>0) for(unsigned int i=0;i<numVars;i++) fread((vec[i]+nLocalBegin),sizeof(T),pMesh->getNumLocalMeshNodes(),infile); fclose(infile); return 0; } } // end of namespace checkpoint } // end of namespace io #endif //SFCSORTBENCH_CHECKPOINT_H
[ "milinda@cs.utah.edu" ]
milinda@cs.utah.edu
e5106d834157f5ac738a462c015cd737b5084d42
24bc4990e9d0bef6a42a6f86dc783785b10dbd42
/ui/base/clipboard/url_file_parser_unittest.cc
3ecd743199c13299d7f9ea2eafb9296c7e304089
[ "BSD-3-Clause" ]
permissive
nwjs/chromium.src
7736ce86a9a0b810449a3b80a4af15de9ef9115d
454f26d09b2f6204c096b47f778705eab1e3ba46
refs/heads/nw75
2023-08-31T08:01:39.796085
2023-04-19T17:25:53
2023-04-19T17:25:53
50,512,158
161
201
BSD-3-Clause
2023-05-08T03:19:09
2016-01-27T14:17:03
null
UTF-8
C++
false
false
2,931
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/base/clipboard/url_file_parser.h" #include <tuple> #include "base/strings/string_piece.h" #include "testing/gtest/include/gtest/gtest.h" namespace ui::ClipboardUtil::internal { namespace { using UrlFileParserTest = testing::Test; TEST_F(UrlFileParserTest, Empty) { std::string file_contents = ""; std::string result = ExtractURLFromURLFileContents(file_contents); EXPECT_EQ("", result); } TEST_F(UrlFileParserTest, Basic) { std::string file_contents = R"( [InternetShortcut] URL=http://www.google.com/ )"; std::string result = ExtractURLFromURLFileContents(file_contents); EXPECT_EQ("http://www.google.com/", result); } TEST_F(UrlFileParserTest, MissingInternetShortcutSection) { std::string file_contents = R"( [SomethingElse] URL=http://www.google.com/ )"; std::string result = ExtractURLFromURLFileContents(file_contents); EXPECT_EQ("", result); } TEST_F(UrlFileParserTest, MissingURLKey) { std::string file_contents = R"( [InternetShortcut] Prop3=19,2 )"; std::string result = ExtractURLFromURLFileContents(file_contents); EXPECT_EQ("", result); } // This is the contents from // chrome/test/data/edge_profile/Favorites/Google.url TEST_F(UrlFileParserTest, Real) { std::string file_contents = R"( [DEFAULT] BASEURL=http://www.google.com/ [{000214A0-0000-0000-C000-000000000046}] Prop3=19,2 [InternetShortcut] IDList= URL=http://www.google.com/ IconFile=http://www.google.com/favicon.ico IconIndex=1 HotKey=0 )"; std::string result = ExtractURLFromURLFileContents(file_contents); EXPECT_EQ("http://www.google.com/", result); } TEST_F(UrlFileParserTest, URLHasEquals) { std::string file_contents = R"( [InternetShortcut] URL=https://www.google.com/search?q=search )"; std::string result = ExtractURLFromURLFileContents(file_contents); EXPECT_EQ("https://www.google.com/search?q=search", result); } // The following tests are parsing malformed contents. They test that the code // behaves reasonably and does not crash. TEST_F(UrlFileParserTest, MalformedTwoInternetShortcutSectionsFirstHasURL) { std::string file_contents = R"( [InternetShortcut] URL=http://www.google.com/ [InternetShortcut] )"; std::ignore = ExtractURLFromURLFileContents(file_contents); } TEST_F(UrlFileParserTest, MalformedTwoInternetShortcutSectionsSecondHasURL) { std::string file_contents = R"( [InternetShortcut] [InternetShortcut] URL=http://www.google.com/ )"; std::ignore = ExtractURLFromURLFileContents(file_contents); } TEST_F(UrlFileParserTest, MalformedTwoURLs) { std::string file_contents = R"( [InternetShortcut] URL=http://www.google.com/ URL=http://www.youtube.com/ )"; std::ignore = ExtractURLFromURLFileContents(file_contents); } } // namespace } // namespace ui::ClipboardUtil::internal
[ "roger@nwjs.io" ]
roger@nwjs.io
5a83c7a630f26b31cd9f470ef922ebf9cd90b927
e6063f71497be719a76f0ae9f1f7dbcfda1988c6
/tree/297_serialize_and_deserialize_binary_tree/work.cc
8ed854d09748bb87e753d94700ea1a21d643b903
[]
no_license
uangyy/leetcode
f308672a662fa1e881230b31b7674160d45c2494
912b683db040a9efbe5b58c329e2978097207ab0
refs/heads/master
2021-01-09T21:57:21.758043
2017-08-04T08:21:09
2017-08-04T08:21:09
36,731,293
1
0
null
null
null
null
UTF-8
C++
false
false
5,211
cc
<<<<<<< HEAD ======= #include <iostream> #include <vector> #include <queue> #include <sstream> using namespace std; >>>>>>> c58362629479780069d3a1e8c9d4b7599a327876 struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Codec { public: <<<<<<< HEAD // Encodes a tree to a single string. string serialize(TreeNode* root) { ======= int get_heigh(TreeNode *root) { if (!root) return 0; return 1 + max(get_heigh(root->left), get_heigh(root->right)); } void fix_res(string &res) { while (res[res.size() - 1] == 'n' || res[res.size() - 1] == ',') res.resize(res.size() - 1); res += "]"; } // Encodes a tree to a single string. string serialize(TreeNode* root) { queue<TreeNode *> level_nodes; string res = "["; int heigh = get_heigh(root), level = 0; if (!root) { res += "]"; return res; } level_nodes.push(root); ostringstream os; os << root->val; res += os.str() + ","; while (!level_nodes.empty()) { level++; int level_size = level_nodes.size(); TreeNode *node; if (level < heigh) while (level_size--) { node = level_nodes.front(); level_nodes.pop(); if (node->left) { level_nodes.push(node->left); os.str(""); os << node->left->val; res += os.str() + ","; } else { res += "n,"; } if (node->right) { level_nodes.push(node->right); os.str(""); os << node->right->val; res += os.str() + ","; } else { res += "n,"; } } else break; } fix_res(res); return res; } string get_token(string &str) { string res; int start = 0; for (int i = 0; i < str.size(); ++i) { if (str[i] == '[') ++start; else if (str[i] == ',' || str[i] == ']') { ++start; break; } else { res += str[i]; ++start; } } str = str.substr(start, str.size() - start); return res; } int str_to_int(const string str) { istringstream is(str); int val; is >> val; return val; >>>>>>> c58362629479780069d3a1e8c9d4b7599a327876 } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { <<<<<<< HEAD ======= if (data == "[]") return NULL; queue<TreeNode *> last_level_nodes; string token = get_token(data); int val, size_count; val = str_to_int(token); TreeNode *root = new TreeNode(val); last_level_nodes.push(root); while (data.size()) { size_count = last_level_nodes.size(); int del = 0; while (size_count) { token = get_token(data); if (token == "n") { if (del % 2) { size_count--; last_level_nodes.pop(); } ++del; } else if (token == "") { break; } else { val = str_to_int(token); TreeNode *tmp = last_level_nodes.front(); TreeNode *new_node = new TreeNode(val); last_level_nodes.push(new_node); if (del % 2) { tmp->right = new_node; size_count--; last_level_nodes.pop(); } else { tmp->left = new_node; } ++del; } } } return root; >>>>>>> c58362629479780069d3a1e8c9d4b7599a327876 } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root)); int main(int argc, char **argv) { <<<<<<< HEAD ======= TreeNode n1(11), n2(2), n3(3), n4(4), n5(5); n1.left = &n2; n1.right = &n3; n2.right = &n4; n3.left = &n5; Codec codec; string res = codec.serialize(&n1); cout << res << endl; TreeNode *tree = codec.deserialize(res); >>>>>>> c58362629479780069d3a1e8c9d4b7599a327876 return 0; }
[ "uangyy@gmail.com" ]
uangyy@gmail.com